diff --git a/Assembly-CSharp/-PrivateImplementationDetails-.cs b/Assembly-CSharp/-PrivateImplementationDetails-.cs new file mode 100644 index 000000000..b2bc96008 --- /dev/null +++ b/Assembly-CSharp/-PrivateImplementationDetails-.cs @@ -0,0 +1,73 @@ +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; + +[CompilerGenerated] +internal class _003CPrivateImplementationDetails_003E +{ + [StructLayout(LayoutKind.Explicit, Pack = 1, Size = 20)] + private struct _0024ArrayType_002420 + { + } + + [StructLayout(LayoutKind.Explicit, Pack = 1, Size = 32)] + private struct _0024ArrayType_002432 + { + } + + [StructLayout(LayoutKind.Explicit, Pack = 1, Size = 36)] + private struct _0024ArrayType_002436 + { + } + + [StructLayout(LayoutKind.Explicit, Pack = 1, Size = 16)] + private struct _0024ArrayType_002416 + { + } + + [StructLayout(LayoutKind.Explicit, Pack = 1, Size = 64)] + private struct _0024ArrayType_002464 + { + } + + [StructLayout(LayoutKind.Explicit, Pack = 1, Size = 24)] + private struct _0024ArrayType_002424 + { + } + + [StructLayout(LayoutKind.Explicit, Pack = 1, Size = 12)] + private struct _0024ArrayType_002412 + { + } + + [StructLayout(LayoutKind.Explicit, Pack = 1, Size = 40)] + private struct _0024ArrayType_002440 + { + } + + [StructLayout(LayoutKind.Explicit, Pack = 1, Size = 8192)] + private struct _0024ArrayType_00248192 + { + } + + internal static _0024ArrayType_002420 _0024_0024field_002D0; + + internal static _0024ArrayType_002432 _0024_0024field_002D1; + + internal static _0024ArrayType_002436 _0024_0024field_002D2; + + internal static _0024ArrayType_002416 _0024_0024field_002D3; + + internal static _0024ArrayType_002464 _0024_0024field_002D4; + + internal static _0024ArrayType_002416 _0024_0024field_002D5; + + internal static _0024ArrayType_002424 _0024_0024field_002D6; + + internal static _0024ArrayType_002412 _0024_0024field_002D7; + + internal static _0024ArrayType_002412 _0024_0024field_002D8; + + internal static _0024ArrayType_002440 _0024_0024field_002D9; + + internal static _0024ArrayType_00248192 _0024_0024field_002D10; +} diff --git a/Assembly-CSharp/Assembly-CSharp.csproj b/Assembly-CSharp/Assembly-CSharp.csproj index 7711680e9..4ad8c958d 100644 --- a/Assembly-CSharp/Assembly-CSharp.csproj +++ b/Assembly-CSharp/Assembly-CSharp.csproj @@ -1,13 +1,14 @@ - + - {8EF1BBB4-A18A-4B64-B581-3E19C4D7B030} + {7E232168-7164-4790-9EA5-47D5BE405A8F} Debug AnyCPU Library Assembly-CSharp v2.0 4 + True AnyCPU @@ -25,8 +26,35 @@ true + + D:\Games\SteamLibrary\steamapps\common\RimWorld\RimWorldWin_Data\Managed\UnityEngine.dll + + + C:\Windows\assembly\GAC_MSIL\System.Core\3.5.0.0__b77a5c561934e089\System.Core.dll + + + C:\Windows\assembly\GAC_MSIL\System.Xml\2.0.0.0__b77a5c561934e089\System.Xml.dll + + + C:\Windows\assembly\GAC_MSIL\System\2.0.0.0__b77a5c561934e089\System.dll + + + D:\Games\SteamLibrary\steamapps\common\RimWorld\RimWorldWin_Data\Managed\Assembly-CSharp-firstpass.dll + + + C:\Windows\assembly\GAC_MSIL\System.Xml.Linq\3.5.0.0__b77a5c561934e089\System.Xml.Linq.dll + + + D:\Games\SteamLibrary\steamapps\common\RimWorld\RimWorldWin_Data\Managed\NAudio.dll + + + D:\Games\SteamLibrary\steamapps\common\RimWorld\RimWorldWin_Data\Managed\NVorbis.dll + + + + + - @@ -3427,42 +3455,5 @@ - - - D:\Game\Steam\steamapps\common\RimWorld\RimWorldWin_Data\Managed\Assembly-CSharp-firstpass.dll - - - False - D:\Game\Steam\steamapps\common\RimWorld\RimWorldWin_Data\Managed\Mono.Posix.dll - - - D:\Game\Steam\steamapps\common\RimWorld\RimWorldWin_Data\Managed\Mono.Security.dll - - - D:\Game\Steam\steamapps\common\RimWorld\RimWorldWin_Data\Managed\NAudio.dll - - - D:\Game\Steam\steamapps\common\RimWorld\RimWorldWin_Data\Managed\NVorbis.dll - - - - - D:\Game\Steam\steamapps\common\RimWorld\RimWorldWin_Data\Managed\System.Core.dll - - - - - D:\Game\Steam\steamapps\common\RimWorld\RimWorldWin_Data\Managed\System.Xml.Linq.dll - - - D:\Game\Steam\steamapps\common\RimWorld\RimWorldWin_Data\Managed\UnityEngine.dll - - - D:\Game\Steam\steamapps\common\RimWorld\RimWorldWin_Data\Managed\UnityEngine.Networking.dll - - - D:\Game\Steam\steamapps\common\RimWorld\RimWorldWin_Data\Managed\UnityEngine.UI.dll - - \ No newline at end of file diff --git a/Assembly-CSharp/NVorbis.NAudioSupport/VorbisWaveReader.cs b/Assembly-CSharp/NVorbis.NAudioSupport/VorbisWaveReader.cs index 0de7adbd5..a05f36633 100644 --- a/Assembly-CSharp/NVorbis.NAudioSupport/VorbisWaveReader.cs +++ b/Assembly-CSharp/NVorbis.NAudioSupport/VorbisWaveReader.cs @@ -37,11 +37,12 @@ public override long Position } set { - if (value < 0L || value > this.Length) + if (value >= 0 && value <= this.Length) { - throw new ArgumentOutOfRangeException("value"); + this._reader.DecodedTime = TimeSpan.FromSeconds((double)value / (double)this._reader.SampleRate / (double)this._reader.Channels / 4.0); + return; } - this._reader.DecodedTime = TimeSpan.FromSeconds((double)value / (double)this._reader.SampleRate / (double)this._reader.Channels / 4.0); + throw new ArgumentOutOfRangeException("value"); } } @@ -77,11 +78,11 @@ public int CurrentStream { if (!this._reader.SwitchStreams(value)) { - throw new NVorbis.InvalidDataException("The selected stream is not a valid Vorbis stream!"); + throw new InvalidDataException("The selected stream is not a valid Vorbis stream!"); } if (this.NextStreamIndex.HasValue && value == this.NextStreamIndex.Value) { - this.NextStreamIndex = null; + this.NextStreamIndex = default(int?); } } } @@ -168,12 +169,7 @@ public override int Read(byte[] buffer, int offset, int count) { count /= 4; count -= count % this._reader.Channels; - float[] arg_2E_0; - if ((arg_2E_0 = VorbisWaveReader._conversionBuffer) == null) - { - arg_2E_0 = (VorbisWaveReader._conversionBuffer = new float[count]); - } - float[] array = arg_2E_0; + float[] array = VorbisWaveReader._conversionBuffer ?? (VorbisWaveReader._conversionBuffer = new float[count]); if (array.Length < count) { array = (VorbisWaveReader._conversionBuffer = new float[count]); diff --git a/Assembly-CSharp/Properties/AssemblyInfo.cs b/Assembly-CSharp/Properties/AssemblyInfo.cs index 43327acab..23bdafda9 100644 --- a/Assembly-CSharp/Properties/AssemblyInfo.cs +++ b/Assembly-CSharp/Properties/AssemblyInfo.cs @@ -1,9 +1,8 @@ -using System; using System.Reflection; using System.Runtime.CompilerServices; -[assembly: AssemblyVersion("0.17.6362.34601")] -[assembly: AssemblyCompany("Ludeon Studios")] [assembly: AssemblyCopyright("Copyright Ludeon Studios.")] [assembly: AssemblyTrademark("RimWorld is a registered trademark of Ludeon Studios.")] [assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)] +[assembly: AssemblyCompany("Ludeon Studios")] +[assembly: AssemblyVersion("0.17.6362.34601")] diff --git a/Assembly-CSharp/RimWorld.BaseGen/BaseGen.cs b/Assembly-CSharp/RimWorld.BaseGen/BaseGen.cs index e2f4cae89..e24764476 100644 --- a/Assembly-CSharp/RimWorld.BaseGen/BaseGen.cs +++ b/Assembly-CSharp/RimWorld.BaseGen/BaseGen.cs @@ -24,7 +24,7 @@ public static void Reset() List allDefsListForReading = DefDatabase.AllDefsListForReading; for (int i = 0; i < allDefsListForReading.Count; i++) { - List list; + List list = default(List); if (!BaseGen.rulesBySymbol.TryGetValue(allDefsListForReading[i].symbol, out list)) { list = new List(); @@ -39,65 +39,66 @@ public static void Generate() if (BaseGen.working) { Log.Error("Cannot call Generate() while already generating. Nested calls are not allowed."); - return; } - BaseGen.working = true; - try + else { - if (BaseGen.symbolStack.Empty) + BaseGen.working = true; + try { - Log.Warning("Symbol stack is empty."); - } - else if (BaseGen.globalSettings.map == null) - { - Log.Error("Called BaseGen.Resolve() with null map."); - } - else - { - int num = BaseGen.symbolStack.Count - 1; - int num2 = 0; - while (!BaseGen.symbolStack.Empty) + if (BaseGen.symbolStack.Empty) { - num2++; - if (num2 > 100000) - { - Log.Error("Error in BaseGen: Too many iterations. Infinite loop?"); - break; - } - Pair toResolve = BaseGen.symbolStack.Pop(); - if (BaseGen.symbolStack.Count == num) - { - BaseGen.globalSettings.mainRect = toResolve.Second.rect; - num--; - } - try - { - BaseGen.Resolve(toResolve); - } - catch (Exception ex) + Log.Warning("Symbol stack is empty."); + } + else if (BaseGen.globalSettings.map == null) + { + Log.Error("Called BaseGen.Resolve() with null map."); + } + else + { + int num = BaseGen.symbolStack.Count - 1; + int num2 = 0; + while (true) { - Log.Error(string.Concat(new object[] + if (!BaseGen.symbolStack.Empty) { - "Error while resolving symbol \"", - toResolve.First, - "\" with params=", - toResolve.Second, - "\n\nException: ", - ex - })); + num2++; + if (num2 <= 100000) + { + Pair toResolve = BaseGen.symbolStack.Pop(); + if (BaseGen.symbolStack.Count == num) + { + GlobalSettings obj = BaseGen.globalSettings; + ResolveParams second = toResolve.Second; + obj.mainRect = second.rect; + num--; + } + try + { + BaseGen.Resolve(toResolve); + } + catch (Exception ex) + { + Log.Error("Error while resolving symbol \"" + toResolve.First + "\" with params=" + toResolve.Second + "\n\nException: " + ex); + } + continue; + } + break; + } + return; } + Log.Error("Error in BaseGen: Too many iterations. Infinite loop?"); } } - } - catch (Exception arg) - { - Log.Error("Error in BaseGen: " + arg); - } - finally - { - BaseGen.working = false; - BaseGen.symbolStack.Clear(); - BaseGen.globalSettings.Clear(); + catch (Exception arg) + { + Log.Error("Error in BaseGen: " + arg); + } + finally + { + BaseGen.working = false; + BaseGen.symbolStack.Clear(); + BaseGen.globalSettings.Clear(); + } } } @@ -106,7 +107,7 @@ private static void Resolve(Pair toResolve) string first = toResolve.First; ResolveParams second = toResolve.Second; BaseGen.tmpResolvers.Clear(); - List list; + List list = default(List); if (BaseGen.rulesBySymbol.TryGetValue(first, out list)) { for (int i = 0; i < list.Count; i++) @@ -122,19 +123,15 @@ private static void Resolve(Pair toResolve) } } } - if (!BaseGen.tmpResolvers.Any()) + if (!BaseGen.tmpResolvers.Any()) { - Log.Warning(string.Concat(new object[] - { - "Could not find any RuleDef for symbol \"", - first, - "\" with any resolver that could resolve ", - second - })); - return; + Log.Warning("Could not find any RuleDef for symbol \"" + first + "\" with any resolver that could resolve " + second); + } + else + { + SymbolResolver symbolResolver2 = BaseGen.tmpResolvers.RandomElementByWeight((Func)((SymbolResolver x) => x.selectionWeight)); + symbolResolver2.Resolve(second); } - SymbolResolver symbolResolver2 = BaseGen.tmpResolvers.RandomElementByWeight((SymbolResolver x) => x.selectionWeight); - symbolResolver2.Resolve(second); } } } diff --git a/Assembly-CSharp/RimWorld.BaseGen/BaseGenUtility.cs b/Assembly-CSharp/RimWorld.BaseGen/BaseGenUtility.cs index a00fdfaa7..ef2cf3dba 100644 --- a/Assembly-CSharp/RimWorld.BaseGen/BaseGenUtility.cs +++ b/Assembly-CSharp/RimWorld.BaseGen/BaseGenUtility.cs @@ -20,13 +20,13 @@ public static ThingDef RandomCheapWallStuff(TechLevel techLevel, bool notVeryFla return ThingDefOf.WoodLog; } return (from d in DefDatabase.AllDefsListForReading - where BaseGenUtility.IsCheapWallStuff(d) && (!notVeryFlammable || d.BaseFlammability < 0.5f) - select d).RandomElement(); + where BaseGenUtility.IsCheapWallStuff(d) && (!notVeryFlammable || d.BaseFlammability < 0.5) + select d).RandomElement(); } public static bool IsCheapWallStuff(ThingDef d) { - return d.IsStuff && d.stuffProps.CanMake(ThingDefOf.Wall) && d.BaseMarketValue / d.VolumePerUnit < 5f; + return d.IsStuff && d.stuffProps.CanMake(ThingDefOf.Wall) && d.BaseMarketValue / d.VolumePerUnit < 5.0; } public static TerrainDef RandomBasicFloorDef(Faction faction, bool allowCarpet = false) @@ -35,9 +35,9 @@ public static TerrainDef RandomBasicFloorDef(Faction faction, bool allowCarpet = { return (from x in DefDatabase.AllDefsListForReading where x.IsCarpet - select x).RandomElement(); + select x).RandomElement(); } - return Rand.Element(TerrainDefOf.MetalTile, TerrainDefOf.PavedTile, TerrainDefOf.WoodPlankFloor, TerrainDefOf.TileSandstone); + return Rand.Element(TerrainDefOf.MetalTile, TerrainDefOf.PavedTile, TerrainDefOf.WoodPlankFloor, TerrainDefOf.TileSandstone); } public static TerrainDef CorrespondingTerrainDef(ThingDef stuffDef, bool beautiful) @@ -87,14 +87,11 @@ public static bool AnyDoorCardinalAdjacentTo(IntVec3 cell, Map map) public static bool AnyDoorCardinalAdjacentTo(CellRect rect, Map map) { - foreach (IntVec3 current in rect.ExpandedBy(1).EdgeCells) + foreach (IntVec3 edgeCell in rect.ExpandedBy(1).EdgeCells) { - if (!rect.IsCorner(current) && current.InBounds(map)) + if (!rect.IsCorner(edgeCell) && edgeCell.InBounds(map) && edgeCell.GetDoor(map) != null) { - if (current.GetDoor(map) != null) - { - return true; - } + return true; } } return false; diff --git a/Assembly-CSharp/RimWorld.BaseGen/GlobalSettings.cs b/Assembly-CSharp/RimWorld.BaseGen/GlobalSettings.cs index 557cf0ade..89171c6e5 100644 --- a/Assembly-CSharp/RimWorld.BaseGen/GlobalSettings.cs +++ b/Assembly-CSharp/RimWorld.BaseGen/GlobalSettings.cs @@ -1,4 +1,3 @@ -using System; using Verse; namespace RimWorld.BaseGen diff --git a/Assembly-CSharp/RimWorld.BaseGen/ResolveParams.cs b/Assembly-CSharp/RimWorld.BaseGen/ResolveParams.cs index 8f2d201ea..df3649a18 100644 --- a/Assembly-CSharp/RimWorld.BaseGen/ResolveParams.cs +++ b/Assembly-CSharp/RimWorld.BaseGen/ResolveParams.cs @@ -103,11 +103,11 @@ public void SetCustom(string name, T obj, bool inherit = false) } else { - this.custom = new Dictionary(this.custom); + this.custom = new Dictionary((IDictionary)this.custom); } if (!this.custom.ContainsKey(name)) { - this.custom.Add(name, obj); + this.custom.Add(name, (object)obj); } else if (!inherit) { @@ -117,176 +117,234 @@ public void SetCustom(string name, T obj, bool inherit = false) public void RemoveCustom(string name) { - if (this.custom == null) + if (this.custom != null) { - return; + this.custom = new Dictionary(this.custom); + this.custom.Remove(name); } - this.custom = new Dictionary(this.custom); - this.custom.Remove(name); } public bool TryGetCustom(string name, out T obj) { - object obj2; - if (this.custom == null || !this.custom.TryGetValue(name, out obj2)) + object obj2 = default(object); + if (this.custom != null && this.custom.TryGetValue(name, out obj2)) { - obj = default(T); - return false; + obj = (T)obj2; + return true; } - obj = (T)((object)obj2); - return true; + obj = default(T); + return false; } public T GetCustom(string name) { - object obj; - if (this.custom == null || !this.custom.TryGetValue(name, out obj)) + object obj = default(object); + if (this.custom != null && this.custom.TryGetValue(name, out obj)) { - return default(T); + return (T)obj; } - return (T)((object)obj); + return default(T); } public override string ToString() { - object[] expr_07 = new object[88]; - expr_07[0] = "rect="; - expr_07[1] = this.rect; - expr_07[2] = ", faction="; - expr_07[3] = ((this.faction == null) ? "null" : this.faction.ToString()); - expr_07[4] = ", custom="; - expr_07[5] = ((this.custom == null) ? "null" : this.custom.Count.ToString()); - expr_07[6] = ", ancientTempleEntranceHeight="; - int arg_AD_1 = 7; - int? num = this.ancientTempleEntranceHeight; - expr_07[arg_AD_1] = ((!num.HasValue) ? "null" : this.ancientTempleEntranceHeight.ToString()); - expr_07[8] = ", pawnGroupMakerParams="; - expr_07[9] = ((this.pawnGroupMakerParams == null) ? "null" : this.pawnGroupMakerParams.ToString()); - expr_07[10] = ", pawnGroupKindDef="; - expr_07[11] = ((this.pawnGroupKindDef == null) ? "null" : this.pawnGroupKindDef.ToString()); - expr_07[12] = ", roofDef="; - expr_07[13] = ((this.roofDef == null) ? "null" : this.roofDef.ToString()); - expr_07[14] = ", noRoof="; - int arg_168_1 = 15; - bool? flag = this.noRoof; - expr_07[arg_168_1] = ((!flag.HasValue) ? "null" : this.noRoof.ToString()); - expr_07[16] = ", addRoomCenterToRootsToUnfog="; - int arg_19D_1 = 17; - bool? flag2 = this.addRoomCenterToRootsToUnfog; - expr_07[arg_19D_1] = ((!flag2.HasValue) ? "null" : this.addRoomCenterToRootsToUnfog.ToString()); - expr_07[18] = ", singleThingToSpawn="; - expr_07[19] = ((this.singleThingToSpawn == null) ? "null" : this.singleThingToSpawn.ToString()); - expr_07[20] = ", singleThingDef="; - expr_07[21] = ((this.singleThingDef == null) ? "null" : this.singleThingDef.ToString()); - expr_07[22] = ", singleThingStuff="; - expr_07[23] = ((this.singleThingStuff == null) ? "null" : this.singleThingStuff.ToString()); - expr_07[24] = ", singleThingStackCount="; - int arg_25A_1 = 25; - int? num2 = this.singleThingStackCount; - expr_07[arg_25A_1] = ((!num2.HasValue) ? "null" : this.singleThingStackCount.ToString()); - expr_07[26] = ", singlePawnToSpawn="; - expr_07[27] = ((this.singlePawnToSpawn == null) ? "null" : this.singlePawnToSpawn.ToString()); - expr_07[28] = ", singlePawnKindDef="; - expr_07[29] = ((this.singlePawnKindDef == null) ? "null" : this.singlePawnKindDef.ToString()); - expr_07[30] = ", disableSinglePawn="; - int arg_2EA_1 = 31; - bool? flag3 = this.disableSinglePawn; - expr_07[arg_2EA_1] = ((!flag3.HasValue) ? "null" : this.disableSinglePawn.ToString()); - expr_07[32] = ", singlePawnLord="; - expr_07[33] = ((this.singlePawnLord == null) ? "null" : this.singlePawnLord.ToString()); - expr_07[34] = ", singlePawnSpawnCellExtraPredicate="; - expr_07[35] = ((this.singlePawnSpawnCellExtraPredicate == null) ? "null" : this.singlePawnSpawnCellExtraPredicate.ToString()); - expr_07[36] = ", singlePawnGenerationRequest="; - int arg_37A_1 = 37; - PawnGenerationRequest? pawnGenerationRequest = this.singlePawnGenerationRequest; - expr_07[arg_37A_1] = ((!pawnGenerationRequest.HasValue) ? "null" : this.singlePawnGenerationRequest.ToString()); - expr_07[38] = ", mechanoidsCount="; - int arg_3B0_1 = 39; - int? num3 = this.mechanoidsCount; - expr_07[arg_3B0_1] = ((!num3.HasValue) ? "null" : this.mechanoidsCount.ToString()); - expr_07[40] = ", hivesCount="; - int arg_3E6_1 = 41; - int? num4 = this.hivesCount; - expr_07[arg_3E6_1] = ((!num4.HasValue) ? "null" : this.hivesCount.ToString()); - expr_07[42] = ", disableHives="; - int arg_41C_1 = 43; - bool? flag4 = this.disableHives; - expr_07[arg_41C_1] = ((!flag4.HasValue) ? "null" : this.disableHives.ToString()); - expr_07[44] = ", thingRot="; - int arg_452_1 = 45; - Rot4? rot = this.thingRot; - expr_07[arg_452_1] = ((!rot.HasValue) ? "null" : this.thingRot.ToString()); - expr_07[46] = ", wallStuff="; - expr_07[47] = ((this.wallStuff == null) ? "null" : this.wallStuff.ToString()); - expr_07[48] = ", chanceToSkipWallBlock="; - int arg_4B5_1 = 49; - float? num5 = this.chanceToSkipWallBlock; - expr_07[arg_4B5_1] = ((!num5.HasValue) ? "null" : this.chanceToSkipWallBlock.ToString()); - expr_07[50] = ", floorDef="; - expr_07[51] = ((this.floorDef == null) ? "null" : this.floorDef.ToString()); - expr_07[52] = ", clearEdificeOnly="; - int arg_518_1 = 53; - bool? flag5 = this.clearEdificeOnly; - expr_07[arg_518_1] = ((!flag5.HasValue) ? "null" : this.clearEdificeOnly.ToString()); - expr_07[54] = ", ancientCryptosleepCasketGroupID="; - int arg_54E_1 = 55; - int? num6 = this.ancientCryptosleepCasketGroupID; - expr_07[arg_54E_1] = ((!num6.HasValue) ? "null" : this.ancientCryptosleepCasketGroupID.ToString()); - expr_07[56] = ", podContentsType="; - int arg_584_1 = 57; - PodContentsType? podContentsType = this.podContentsType; - expr_07[arg_584_1] = ((!podContentsType.HasValue) ? "null" : this.podContentsType.ToString()); - expr_07[58] = ", itemCollectionGeneratorDef="; - expr_07[59] = ((this.itemCollectionGeneratorDef == null) ? "null" : this.itemCollectionGeneratorDef.ToString()); - expr_07[60] = ", itemCollectionGeneratorParams="; - int arg_5E7_1 = 61; - ItemCollectionGeneratorParams? itemCollectionGeneratorParams = this.itemCollectionGeneratorParams; - expr_07[arg_5E7_1] = ((!itemCollectionGeneratorParams.HasValue) ? "null" : this.itemCollectionGeneratorParams.ToString()); - expr_07[62] = ", stockpileConcreteContents="; - expr_07[63] = ((this.stockpileConcreteContents == null) ? "null" : this.stockpileConcreteContents.Count.ToString()); - expr_07[64] = ", stockpileMarketValue="; - int arg_653_1 = 65; - float? num7 = this.stockpileMarketValue; - expr_07[arg_653_1] = ((!num7.HasValue) ? "null" : this.stockpileMarketValue.ToString()); - expr_07[66] = ", edgeDefenseWidth="; - int arg_689_1 = 67; - int? num8 = this.edgeDefenseWidth; - expr_07[arg_689_1] = ((!num8.HasValue) ? "null" : this.edgeDefenseWidth.ToString()); - expr_07[68] = ", edgeDefenseTurretsCount="; - int arg_6BF_1 = 69; - int? num9 = this.edgeDefenseTurretsCount; - expr_07[arg_6BF_1] = ((!num9.HasValue) ? "null" : this.edgeDefenseTurretsCount.ToString()); - expr_07[70] = ", edgeDefenseMortarsCount="; - int arg_6F5_1 = 71; - int? num10 = this.edgeDefenseMortarsCount; - expr_07[arg_6F5_1] = ((!num10.HasValue) ? "null" : this.edgeDefenseMortarsCount.ToString()); - expr_07[72] = ", edgeDefenseGuardsCount="; - int arg_72B_1 = 73; - int? num11 = this.edgeDefenseGuardsCount; - expr_07[arg_72B_1] = ((!num11.HasValue) ? "null" : this.edgeDefenseGuardsCount.ToString()); - expr_07[74] = ", mortarDef="; - expr_07[75] = ((this.mortarDef == null) ? "null" : this.mortarDef.ToString()); - expr_07[76] = ", pathwayFloorDef="; - expr_07[77] = ((this.pathwayFloorDef == null) ? "null" : this.pathwayFloorDef.ToString()); - expr_07[78] = ", cultivatedPlantDef="; - expr_07[79] = ((this.cultivatedPlantDef == null) ? "null" : this.cultivatedPlantDef.ToString()); - expr_07[80] = ", fillWithThingsPadding="; - int arg_7E8_1 = 81; - int? num12 = this.fillWithThingsPadding; - expr_07[arg_7E8_1] = ((!num12.HasValue) ? "null" : this.fillWithThingsPadding.ToString()); - expr_07[82] = ", factionBasePawnGroupPointsFactor="; - int arg_81E_1 = 83; - float? num13 = this.factionBasePawnGroupPointsFactor; - expr_07[arg_81E_1] = ((!num13.HasValue) ? "null" : this.factionBasePawnGroupPointsFactor.ToString()); - expr_07[84] = ", streetHorizontal="; - int arg_854_1 = 85; - bool? flag6 = this.streetHorizontal; - expr_07[arg_854_1] = ((!flag6.HasValue) ? "null" : this.streetHorizontal.ToString()); - expr_07[86] = ", edgeThingAvoidOtherEdgeThings="; - int arg_88A_1 = 87; - bool? flag7 = this.edgeThingAvoidOtherEdgeThings; - expr_07[arg_88A_1] = ((!flag7.HasValue) ? "null" : this.edgeThingAvoidOtherEdgeThings.ToString()); - return string.Concat(expr_07); + object[] obj = new object[88] + { + "rect=", + this.rect, + ", faction=", + (this.faction == null) ? "null" : this.faction.ToString(), + ", custom=", + (this.custom == null) ? "null" : this.custom.Count.ToString(), + ", ancientTempleEntranceHeight=", + null, + null, + null, + null, + null, + null, + null, + null, + null, + null, + null, + null, + null, + null, + null, + null, + null, + null, + null, + null, + null, + null, + null, + null, + null, + null, + null, + null, + null, + null, + null, + null, + null, + null, + null, + null, + null, + null, + null, + null, + null, + null, + null, + null, + null, + null, + null, + null, + null, + null, + null, + null, + null, + null, + null, + null, + null, + null, + null, + null, + null, + null, + null, + null, + null, + null, + null, + null, + null, + null, + null, + null, + null, + null, + null, + null, + null, + null, + null, + null, + null + }; + int? nullable = this.ancientTempleEntranceHeight; + obj[7] = ((!nullable.HasValue) ? "null" : this.ancientTempleEntranceHeight.ToString()); + obj[8] = ", pawnGroupMakerParams="; + obj[9] = ((this.pawnGroupMakerParams == null) ? "null" : this.pawnGroupMakerParams.ToString()); + obj[10] = ", pawnGroupKindDef="; + obj[11] = ((this.pawnGroupKindDef == null) ? "null" : this.pawnGroupKindDef.ToString()); + obj[12] = ", roofDef="; + obj[13] = ((this.roofDef == null) ? "null" : this.roofDef.ToString()); + obj[14] = ", noRoof="; + bool? nullable2 = this.noRoof; + obj[15] = ((!nullable2.HasValue) ? "null" : this.noRoof.ToString()); + obj[16] = ", addRoomCenterToRootsToUnfog="; + bool? nullable3 = this.addRoomCenterToRootsToUnfog; + obj[17] = ((!nullable3.HasValue) ? "null" : this.addRoomCenterToRootsToUnfog.ToString()); + obj[18] = ", singleThingToSpawn="; + obj[19] = ((this.singleThingToSpawn == null) ? "null" : this.singleThingToSpawn.ToString()); + obj[20] = ", singleThingDef="; + obj[21] = ((this.singleThingDef == null) ? "null" : this.singleThingDef.ToString()); + obj[22] = ", singleThingStuff="; + obj[23] = ((this.singleThingStuff == null) ? "null" : this.singleThingStuff.ToString()); + obj[24] = ", singleThingStackCount="; + int? nullable4 = this.singleThingStackCount; + obj[25] = ((!nullable4.HasValue) ? "null" : this.singleThingStackCount.ToString()); + obj[26] = ", singlePawnToSpawn="; + obj[27] = ((this.singlePawnToSpawn == null) ? "null" : this.singlePawnToSpawn.ToString()); + obj[28] = ", singlePawnKindDef="; + obj[29] = ((this.singlePawnKindDef == null) ? "null" : this.singlePawnKindDef.ToString()); + obj[30] = ", disableSinglePawn="; + bool? nullable5 = this.disableSinglePawn; + obj[31] = ((!nullable5.HasValue) ? "null" : this.disableSinglePawn.ToString()); + obj[32] = ", singlePawnLord="; + obj[33] = ((this.singlePawnLord == null) ? "null" : this.singlePawnLord.ToString()); + obj[34] = ", singlePawnSpawnCellExtraPredicate="; + obj[35] = (((object)this.singlePawnSpawnCellExtraPredicate == null) ? "null" : this.singlePawnSpawnCellExtraPredicate.ToString()); + obj[36] = ", singlePawnGenerationRequest="; + PawnGenerationRequest? nullable6 = this.singlePawnGenerationRequest; + obj[37] = ((!nullable6.HasValue) ? "null" : this.singlePawnGenerationRequest.ToString()); + obj[38] = ", mechanoidsCount="; + int? nullable7 = this.mechanoidsCount; + obj[39] = ((!nullable7.HasValue) ? "null" : this.mechanoidsCount.ToString()); + obj[40] = ", hivesCount="; + int? nullable8 = this.hivesCount; + obj[41] = ((!nullable8.HasValue) ? "null" : this.hivesCount.ToString()); + obj[42] = ", disableHives="; + bool? nullable9 = this.disableHives; + obj[43] = ((!nullable9.HasValue) ? "null" : this.disableHives.ToString()); + obj[44] = ", thingRot="; + Rot4? nullable10 = this.thingRot; + obj[45] = ((!nullable10.HasValue) ? "null" : this.thingRot.ToString()); + obj[46] = ", wallStuff="; + obj[47] = ((this.wallStuff == null) ? "null" : this.wallStuff.ToString()); + obj[48] = ", chanceToSkipWallBlock="; + float? nullable11 = this.chanceToSkipWallBlock; + obj[49] = ((!nullable11.HasValue) ? "null" : this.chanceToSkipWallBlock.ToString()); + obj[50] = ", floorDef="; + obj[51] = ((this.floorDef == null) ? "null" : this.floorDef.ToString()); + obj[52] = ", clearEdificeOnly="; + bool? nullable12 = this.clearEdificeOnly; + obj[53] = ((!nullable12.HasValue) ? "null" : this.clearEdificeOnly.ToString()); + obj[54] = ", ancientCryptosleepCasketGroupID="; + int? nullable13 = this.ancientCryptosleepCasketGroupID; + obj[55] = ((!nullable13.HasValue) ? "null" : this.ancientCryptosleepCasketGroupID.ToString()); + obj[56] = ", podContentsType="; + PodContentsType? nullable14 = this.podContentsType; + obj[57] = ((!nullable14.HasValue) ? "null" : this.podContentsType.ToString()); + obj[58] = ", itemCollectionGeneratorDef="; + obj[59] = ((this.itemCollectionGeneratorDef == null) ? "null" : this.itemCollectionGeneratorDef.ToString()); + obj[60] = ", itemCollectionGeneratorParams="; + ItemCollectionGeneratorParams? nullable15 = this.itemCollectionGeneratorParams; + obj[61] = ((!nullable15.HasValue) ? "null" : this.itemCollectionGeneratorParams.ToString()); + obj[62] = ", stockpileConcreteContents="; + obj[63] = ((this.stockpileConcreteContents == null) ? "null" : this.stockpileConcreteContents.Count.ToString()); + obj[64] = ", stockpileMarketValue="; + float? nullable16 = this.stockpileMarketValue; + obj[65] = ((!nullable16.HasValue) ? "null" : this.stockpileMarketValue.ToString()); + obj[66] = ", edgeDefenseWidth="; + int? nullable17 = this.edgeDefenseWidth; + obj[67] = ((!nullable17.HasValue) ? "null" : this.edgeDefenseWidth.ToString()); + obj[68] = ", edgeDefenseTurretsCount="; + int? nullable18 = this.edgeDefenseTurretsCount; + obj[69] = ((!nullable18.HasValue) ? "null" : this.edgeDefenseTurretsCount.ToString()); + obj[70] = ", edgeDefenseMortarsCount="; + int? nullable19 = this.edgeDefenseMortarsCount; + obj[71] = ((!nullable19.HasValue) ? "null" : this.edgeDefenseMortarsCount.ToString()); + obj[72] = ", edgeDefenseGuardsCount="; + int? nullable20 = this.edgeDefenseGuardsCount; + obj[73] = ((!nullable20.HasValue) ? "null" : this.edgeDefenseGuardsCount.ToString()); + obj[74] = ", mortarDef="; + obj[75] = ((this.mortarDef == null) ? "null" : this.mortarDef.ToString()); + obj[76] = ", pathwayFloorDef="; + obj[77] = ((this.pathwayFloorDef == null) ? "null" : this.pathwayFloorDef.ToString()); + obj[78] = ", cultivatedPlantDef="; + obj[79] = ((this.cultivatedPlantDef == null) ? "null" : this.cultivatedPlantDef.ToString()); + obj[80] = ", fillWithThingsPadding="; + int? nullable21 = this.fillWithThingsPadding; + obj[81] = ((!nullable21.HasValue) ? "null" : this.fillWithThingsPadding.ToString()); + obj[82] = ", factionBasePawnGroupPointsFactor="; + float? nullable22 = this.factionBasePawnGroupPointsFactor; + obj[83] = ((!nullable22.HasValue) ? "null" : this.factionBasePawnGroupPointsFactor.ToString()); + obj[84] = ", streetHorizontal="; + bool? nullable23 = this.streetHorizontal; + obj[85] = ((!nullable23.HasValue) ? "null" : this.streetHorizontal.ToString()); + obj[86] = ", edgeThingAvoidOtherEdgeThings="; + bool? nullable24 = this.edgeThingAvoidOtherEdgeThings; + obj[87] = ((!nullable24.HasValue) ? "null" : this.edgeThingAvoidOtherEdgeThings.ToString()); + return string.Concat(obj); } } } diff --git a/Assembly-CSharp/RimWorld.BaseGen/SymbolResolver.cs b/Assembly-CSharp/RimWorld.BaseGen/SymbolResolver.cs index 4a2551085..23bd59258 100644 --- a/Assembly-CSharp/RimWorld.BaseGen/SymbolResolver.cs +++ b/Assembly-CSharp/RimWorld.BaseGen/SymbolResolver.cs @@ -1,4 +1,3 @@ -using System; using Verse; namespace RimWorld.BaseGen diff --git a/Assembly-CSharp/RimWorld.BaseGen/SymbolResolver_AddWortToFermentingBarrels.cs b/Assembly-CSharp/RimWorld.BaseGen/SymbolResolver_AddWortToFermentingBarrels.cs index 1aa0c83e2..d9c11905f 100644 --- a/Assembly-CSharp/RimWorld.BaseGen/SymbolResolver_AddWortToFermentingBarrels.cs +++ b/Assembly-CSharp/RimWorld.BaseGen/SymbolResolver_AddWortToFermentingBarrels.cs @@ -1,4 +1,3 @@ -using System; using System.Collections.Generic; using UnityEngine; using Verse; @@ -32,11 +31,11 @@ public override void Resolve(ResolveParams rp) { if (!SymbolResolver_AddWortToFermentingBarrels.barrels[j].Fermented) { - int num = Rand.RangeInclusive(1, 25); - num = Mathf.Min(num, SymbolResolver_AddWortToFermentingBarrels.barrels[j].SpaceLeftForWort); - if (num > 0) + int a = Rand.RangeInclusive(1, 25); + a = Mathf.Min(a, SymbolResolver_AddWortToFermentingBarrels.barrels[j].SpaceLeftForWort); + if (a > 0) { - SymbolResolver_AddWortToFermentingBarrels.barrels[j].AddWort(num); + SymbolResolver_AddWortToFermentingBarrels.barrels[j].AddWort(a); SymbolResolver_AddWortToFermentingBarrels.barrels[j].Progress = progress; } } diff --git a/Assembly-CSharp/RimWorld.BaseGen/SymbolResolver_AncientCryptosleepCasket.cs b/Assembly-CSharp/RimWorld.BaseGen/SymbolResolver_AncientCryptosleepCasket.cs index 018f1e5ab..907542eb5 100644 --- a/Assembly-CSharp/RimWorld.BaseGen/SymbolResolver_AncientCryptosleepCasket.cs +++ b/Assembly-CSharp/RimWorld.BaseGen/SymbolResolver_AncientCryptosleepCasket.cs @@ -1,5 +1,4 @@ using RimWorld.Planet; -using System; using System.Collections.Generic; using Verse; @@ -17,8 +16,10 @@ public override void Resolve(ResolveParams rp) Rot4 rot = (!thingRot.HasValue) ? Rot4.North : thingRot.Value; Building_AncientCryptosleepCasket building_AncientCryptosleepCasket = (Building_AncientCryptosleepCasket)ThingMaker.MakeThing(ThingDefOf.AncientCryptosleepCasket, null); building_AncientCryptosleepCasket.groupID = groupID; - ItemCollectionGeneratorParams parms = default(ItemCollectionGeneratorParams); - parms.podContentsType = podContentsType2; + ItemCollectionGeneratorParams parms = new ItemCollectionGeneratorParams + { + podContentsType = podContentsType2 + }; List list = ItemCollectionGeneratorDefOf.AncientPodContents.Worker.Generate(parms); for (int i = 0; i < list.Count; i++) { diff --git a/Assembly-CSharp/RimWorld.BaseGen/SymbolResolver_AncientRuins.cs b/Assembly-CSharp/RimWorld.BaseGen/SymbolResolver_AncientRuins.cs index c698dd642..9ed188044 100644 --- a/Assembly-CSharp/RimWorld.BaseGen/SymbolResolver_AncientRuins.cs +++ b/Assembly-CSharp/RimWorld.BaseGen/SymbolResolver_AncientRuins.cs @@ -1,5 +1,3 @@ -using System; - namespace RimWorld.BaseGen { public class SymbolResolver_AncientRuins : SymbolResolver @@ -9,7 +7,7 @@ public override void Resolve(ResolveParams rp) ResolveParams resolveParams = rp; resolveParams.wallStuff = (rp.wallStuff ?? BaseGenUtility.RandomCheapWallStuff(rp.faction, true)); float? chanceToSkipWallBlock = rp.chanceToSkipWallBlock; - resolveParams.chanceToSkipWallBlock = new float?((!chanceToSkipWallBlock.HasValue) ? 0.1f : chanceToSkipWallBlock.Value); + resolveParams.chanceToSkipWallBlock = new float?((float)((!chanceToSkipWallBlock.HasValue) ? 0.10000000149011612 : chanceToSkipWallBlock.Value)); bool? clearEdificeOnly = rp.clearEdificeOnly; resolveParams.clearEdificeOnly = new bool?(!clearEdificeOnly.HasValue || clearEdificeOnly.Value); bool? noRoof = rp.noRoof; diff --git a/Assembly-CSharp/RimWorld.BaseGen/SymbolResolver_AncientShrine.cs b/Assembly-CSharp/RimWorld.BaseGen/SymbolResolver_AncientShrine.cs index c5a2b4823..e5a2cd0b9 100644 --- a/Assembly-CSharp/RimWorld.BaseGen/SymbolResolver_AncientShrine.cs +++ b/Assembly-CSharp/RimWorld.BaseGen/SymbolResolver_AncientShrine.cs @@ -1,4 +1,3 @@ -using System; using System.Collections.Generic; using Verse; @@ -11,15 +10,18 @@ public override void Resolve(ResolveParams rp) IntVec3 bottomLeft = rp.rect.BottomLeft; Map map = BaseGen.globalSettings.map; CellRect rect = new CellRect(bottomLeft.x + rp.rect.Width / 2 - 1, bottomLeft.z + rp.rect.Height / 2, 2, 1); - foreach (IntVec3 current in rect) + foreach (IntVec3 item in rect) { - List thingList = current.GetThingList(map); - for (int i = 0; i < thingList.Count; i++) + List thingList = item.GetThingList(map); + int num = 0; + while (num < thingList.Count) { - if (!thingList[i].def.destroyable) + if (thingList[num].def.destroyable) { - return; + num++; + continue; } + return; } } ResolveParams resolveParams = rp; diff --git a/Assembly-CSharp/RimWorld.BaseGen/SymbolResolver_AncientShrinesGroup.cs b/Assembly-CSharp/RimWorld.BaseGen/SymbolResolver_AncientShrinesGroup.cs index ab01282d9..93616cd20 100644 --- a/Assembly-CSharp/RimWorld.BaseGen/SymbolResolver_AncientShrinesGroup.cs +++ b/Assembly-CSharp/RimWorld.BaseGen/SymbolResolver_AncientShrinesGroup.cs @@ -1,4 +1,3 @@ -using System; using Verse; namespace RimWorld.BaseGen @@ -15,40 +14,44 @@ public class SymbolResolver_AncientShrinesGroup : SymbolResolver public override void Resolve(ResolveParams rp) { - int num = (rp.rect.Width + 1) / (SymbolResolver_AncientShrinesGroup.StandardAncientShrineSize.x + 1); - int num2 = (rp.rect.Height + 1) / (SymbolResolver_AncientShrinesGroup.StandardAncientShrineSize.z + 1); + int num = rp.rect.Width + 1; + IntVec2 standardAncientShrineSize = SymbolResolver_AncientShrinesGroup.StandardAncientShrineSize; + int num2 = num / (standardAncientShrineSize.x + 1); + int num3 = rp.rect.Height + 1; + IntVec2 standardAncientShrineSize2 = SymbolResolver_AncientShrinesGroup.StandardAncientShrineSize; + int num4 = num3 / (standardAncientShrineSize2.z + 1); IntVec3 bottomLeft = rp.rect.BottomLeft; PodContentsType? podContentsType = rp.podContentsType; if (!podContentsType.HasValue) { float value = Rand.Value; - if (value < 0.5f) - { - podContentsType = null; - } - else if (value < 0.7f) - { - podContentsType = new PodContentsType?(PodContentsType.Slave); - } - else - { - podContentsType = new PodContentsType?(PodContentsType.SpacerHostile); - } + podContentsType = ((!(value < 0.5)) ? ((!(value < 0.699999988079071)) ? new PodContentsType?(PodContentsType.SpacerHostile) : new PodContentsType?(PodContentsType.Slave)) : default(PodContentsType?)); } int? ancientCryptosleepCasketGroupID = rp.ancientCryptosleepCasketGroupID; int value2 = (!ancientCryptosleepCasketGroupID.HasValue) ? Find.UniqueIDsManager.GetNextAncientCryptosleepCasketGroupID() : ancientCryptosleepCasketGroupID.Value; - int num3 = 0; - for (int i = 0; i < num2; i++) + int num5 = 0; + for (int num6 = 0; num6 < num4; num6++) { - for (int j = 0; j < num; j++) + for (int num7 = 0; num7 < num2; num7++) { if (!Rand.Chance(0.25f)) { - if (num3 >= 6) + if (num5 >= 6) { break; } - CellRect rect = new CellRect(bottomLeft.x + j * (SymbolResolver_AncientShrinesGroup.StandardAncientShrineSize.x + 1), bottomLeft.z + i * (SymbolResolver_AncientShrinesGroup.StandardAncientShrineSize.z + 1), SymbolResolver_AncientShrinesGroup.StandardAncientShrineSize.x, SymbolResolver_AncientShrinesGroup.StandardAncientShrineSize.z); + int x = bottomLeft.x; + int num8 = num7; + IntVec2 standardAncientShrineSize3 = SymbolResolver_AncientShrinesGroup.StandardAncientShrineSize; + int minX = x + num8 * (standardAncientShrineSize3.x + 1); + int z = bottomLeft.z; + int num9 = num6; + IntVec2 standardAncientShrineSize4 = SymbolResolver_AncientShrinesGroup.StandardAncientShrineSize; + int minZ = z + num9 * (standardAncientShrineSize4.z + 1); + IntVec2 standardAncientShrineSize5 = SymbolResolver_AncientShrinesGroup.StandardAncientShrineSize; + int x2 = standardAncientShrineSize5.x; + IntVec2 standardAncientShrineSize6 = SymbolResolver_AncientShrinesGroup.StandardAncientShrineSize; + CellRect rect = new CellRect(minX, minZ, x2, standardAncientShrineSize6.z); if (rect.FullyContainedWithin(rp.rect)) { ResolveParams resolveParams = rp; @@ -56,7 +59,7 @@ public override void Resolve(ResolveParams rp) resolveParams.ancientCryptosleepCasketGroupID = new int?(value2); resolveParams.podContentsType = podContentsType; BaseGen.symbolStack.Push("ancientShrine", resolveParams); - num3++; + num5++; } } } diff --git a/Assembly-CSharp/RimWorld.BaseGen/SymbolResolver_AncientTemple.cs b/Assembly-CSharp/RimWorld.BaseGen/SymbolResolver_AncientTemple.cs index 1d0df32f4..252e3e16a 100644 --- a/Assembly-CSharp/RimWorld.BaseGen/SymbolResolver_AncientTemple.cs +++ b/Assembly-CSharp/RimWorld.BaseGen/SymbolResolver_AncientTemple.cs @@ -1,5 +1,3 @@ -using System; - namespace RimWorld.BaseGen { public class SymbolResolver_AncientTemple : SymbolResolver diff --git a/Assembly-CSharp/RimWorld.BaseGen/SymbolResolver_Barracks.cs b/Assembly-CSharp/RimWorld.BaseGen/SymbolResolver_Barracks.cs index 16414dea4..60561309c 100644 --- a/Assembly-CSharp/RimWorld.BaseGen/SymbolResolver_Barracks.cs +++ b/Assembly-CSharp/RimWorld.BaseGen/SymbolResolver_Barracks.cs @@ -1,5 +1,3 @@ -using System; - namespace RimWorld.BaseGen { public class SymbolResolver_Barracks : SymbolResolver diff --git a/Assembly-CSharp/RimWorld.BaseGen/SymbolResolver_BasePart_Indoors.cs b/Assembly-CSharp/RimWorld.BaseGen/SymbolResolver_BasePart_Indoors.cs index 69019010e..7a54bb030 100644 --- a/Assembly-CSharp/RimWorld.BaseGen/SymbolResolver_BasePart_Indoors.cs +++ b/Assembly-CSharp/RimWorld.BaseGen/SymbolResolver_BasePart_Indoors.cs @@ -1,4 +1,3 @@ -using System; using Verse; namespace RimWorld.BaseGen @@ -7,8 +6,7 @@ public class SymbolResolver_BasePart_Indoors : SymbolResolver { public override void Resolve(ResolveParams rp) { - bool flag = rp.rect.Width > 13 || rp.rect.Height > 13 || ((rp.rect.Width >= 9 || rp.rect.Height >= 9) && Rand.Chance(0.3f)); - if (flag) + if (rp.rect.Width > 13 || rp.rect.Height > 13 || ((rp.rect.Width >= 9 || rp.rect.Height >= 9) && Rand.Chance(0.3f))) { BaseGen.symbolStack.Push("basePart_indoors_division", rp); } diff --git a/Assembly-CSharp/RimWorld.BaseGen/SymbolResolver_BasePart_Indoors_Division_Split.cs b/Assembly-CSharp/RimWorld.BaseGen/SymbolResolver_BasePart_Indoors_Division_Split.cs index ea421f311..5b5cd81a2 100644 --- a/Assembly-CSharp/RimWorld.BaseGen/SymbolResolver_BasePart_Indoors_Division_Split.cs +++ b/Assembly-CSharp/RimWorld.BaseGen/SymbolResolver_BasePart_Indoors_Division_Split.cs @@ -1,4 +1,3 @@ -using System; using Verse; namespace RimWorld.BaseGen @@ -19,10 +18,8 @@ public override void Resolve(ResolveParams rp) if (rp.rect.Width < 9 && rp.rect.Height < 9) { Log.Warning("Too small rect. params=" + rp); - return; } - bool flag = (Rand.Bool && rp.rect.Height >= 9) || rp.rect.Width < 9; - if (flag) + else if ((Rand.Bool && rp.rect.Height >= 9) || rp.rect.Width < 9) { int num = Rand.RangeInclusive(4, rp.rect.Height - 5); ResolveParams resolveParams = rp; diff --git a/Assembly-CSharp/RimWorld.BaseGen/SymbolResolver_BasePart_Indoors_Leaf_Barracks.cs b/Assembly-CSharp/RimWorld.BaseGen/SymbolResolver_BasePart_Indoors_Leaf_Barracks.cs index 84bd48083..ee6fe2cf8 100644 --- a/Assembly-CSharp/RimWorld.BaseGen/SymbolResolver_BasePart_Indoors_Leaf_Barracks.cs +++ b/Assembly-CSharp/RimWorld.BaseGen/SymbolResolver_BasePart_Indoors_Leaf_Barracks.cs @@ -1,5 +1,3 @@ -using System; - namespace RimWorld.BaseGen { public class SymbolResolver_BasePart_Indoors_Leaf_Barracks : SymbolResolver diff --git a/Assembly-CSharp/RimWorld.BaseGen/SymbolResolver_BasePart_Indoors_Leaf_BatteryRoom.cs b/Assembly-CSharp/RimWorld.BaseGen/SymbolResolver_BasePart_Indoors_Leaf_BatteryRoom.cs index cd3b411e9..859eb7cfd 100644 --- a/Assembly-CSharp/RimWorld.BaseGen/SymbolResolver_BasePart_Indoors_Leaf_BatteryRoom.cs +++ b/Assembly-CSharp/RimWorld.BaseGen/SymbolResolver_BasePart_Indoors_Leaf_BatteryRoom.cs @@ -1,5 +1,3 @@ -using System; - namespace RimWorld.BaseGen { public class SymbolResolver_BasePart_Indoors_Leaf_BatteryRoom : SymbolResolver @@ -8,7 +6,19 @@ public class SymbolResolver_BasePart_Indoors_Leaf_BatteryRoom : SymbolResolver public override bool CanResolve(ResolveParams rp) { - return base.CanResolve(rp) && BaseGen.globalSettings.basePart_barracksResolved >= BaseGen.globalSettings.minBarracks && BaseGen.globalSettings.basePart_batteriesCoverage + (float)rp.rect.Area / (float)BaseGen.globalSettings.mainRect.Area < 0.06f && (rp.faction == null || rp.faction.def.techLevel >= TechLevel.Industrial); + if (!base.CanResolve(rp)) + { + return false; + } + if (BaseGen.globalSettings.basePart_barracksResolved < BaseGen.globalSettings.minBarracks) + { + return false; + } + if (BaseGen.globalSettings.basePart_batteriesCoverage + (float)rp.rect.Area / (float)BaseGen.globalSettings.mainRect.Area >= 0.059999998658895493) + { + return false; + } + return rp.faction == null || (int)rp.faction.def.techLevel >= 4; } public override void Resolve(ResolveParams rp) diff --git a/Assembly-CSharp/RimWorld.BaseGen/SymbolResolver_BasePart_Indoors_Leaf_Brewery.cs b/Assembly-CSharp/RimWorld.BaseGen/SymbolResolver_BasePart_Indoors_Leaf_Brewery.cs index 9e8df4078..700192be2 100644 --- a/Assembly-CSharp/RimWorld.BaseGen/SymbolResolver_BasePart_Indoors_Leaf_Brewery.cs +++ b/Assembly-CSharp/RimWorld.BaseGen/SymbolResolver_BasePart_Indoors_Leaf_Brewery.cs @@ -1,5 +1,3 @@ -using System; - namespace RimWorld.BaseGen { public class SymbolResolver_BasePart_Indoors_Leaf_Brewery : SymbolResolver @@ -8,7 +6,19 @@ public class SymbolResolver_BasePart_Indoors_Leaf_Brewery : SymbolResolver public override bool CanResolve(ResolveParams rp) { - return base.CanResolve(rp) && BaseGen.globalSettings.basePart_barracksResolved >= BaseGen.globalSettings.minBarracks && BaseGen.globalSettings.basePart_breweriesCoverage + (float)rp.rect.Area / (float)BaseGen.globalSettings.mainRect.Area < 0.08f && (rp.faction == null || rp.faction.def.techLevel >= TechLevel.Medieval); + if (!base.CanResolve(rp)) + { + return false; + } + if (BaseGen.globalSettings.basePart_barracksResolved < BaseGen.globalSettings.minBarracks) + { + return false; + } + if (BaseGen.globalSettings.basePart_breweriesCoverage + (float)rp.rect.Area / (float)BaseGen.globalSettings.mainRect.Area >= 0.079999998211860657) + { + return false; + } + return rp.faction == null || (int)rp.faction.def.techLevel >= 3; } public override void Resolve(ResolveParams rp) diff --git a/Assembly-CSharp/RimWorld.BaseGen/SymbolResolver_BasePart_Indoors_Leaf_DiningRoom.cs b/Assembly-CSharp/RimWorld.BaseGen/SymbolResolver_BasePart_Indoors_Leaf_DiningRoom.cs index 1efb88d3e..523ed6704 100644 --- a/Assembly-CSharp/RimWorld.BaseGen/SymbolResolver_BasePart_Indoors_Leaf_DiningRoom.cs +++ b/Assembly-CSharp/RimWorld.BaseGen/SymbolResolver_BasePart_Indoors_Leaf_DiningRoom.cs @@ -1,12 +1,18 @@ -using System; - namespace RimWorld.BaseGen { public class SymbolResolver_BasePart_Indoors_Leaf_DiningRoom : SymbolResolver { public override bool CanResolve(ResolveParams rp) { - return base.CanResolve(rp) && BaseGen.globalSettings.basePart_barracksResolved >= BaseGen.globalSettings.minBarracks; + if (!base.CanResolve(rp)) + { + return false; + } + if (BaseGen.globalSettings.basePart_barracksResolved < BaseGen.globalSettings.minBarracks) + { + return false; + } + return true; } public override void Resolve(ResolveParams rp) diff --git a/Assembly-CSharp/RimWorld.BaseGen/SymbolResolver_BasePart_Indoors_Leaf_Storage.cs b/Assembly-CSharp/RimWorld.BaseGen/SymbolResolver_BasePart_Indoors_Leaf_Storage.cs index b4f2bcdc2..06e5d6309 100644 --- a/Assembly-CSharp/RimWorld.BaseGen/SymbolResolver_BasePart_Indoors_Leaf_Storage.cs +++ b/Assembly-CSharp/RimWorld.BaseGen/SymbolResolver_BasePart_Indoors_Leaf_Storage.cs @@ -1,12 +1,18 @@ -using System; - namespace RimWorld.BaseGen { public class SymbolResolver_BasePart_Indoors_Leaf_Storage : SymbolResolver { public override bool CanResolve(ResolveParams rp) { - return base.CanResolve(rp) && BaseGen.globalSettings.basePart_barracksResolved >= BaseGen.globalSettings.minBarracks; + if (!base.CanResolve(rp)) + { + return false; + } + if (BaseGen.globalSettings.basePart_barracksResolved < BaseGen.globalSettings.minBarracks) + { + return false; + } + return true; } public override void Resolve(ResolveParams rp) diff --git a/Assembly-CSharp/RimWorld.BaseGen/SymbolResolver_BasePart_Outdoors.cs b/Assembly-CSharp/RimWorld.BaseGen/SymbolResolver_BasePart_Outdoors.cs index 8922bedce..9e02a4bef 100644 --- a/Assembly-CSharp/RimWorld.BaseGen/SymbolResolver_BasePart_Outdoors.cs +++ b/Assembly-CSharp/RimWorld.BaseGen/SymbolResolver_BasePart_Outdoors.cs @@ -1,4 +1,3 @@ -using System; using Verse; namespace RimWorld.BaseGen diff --git a/Assembly-CSharp/RimWorld.BaseGen/SymbolResolver_BasePart_Outdoors_Division_Grid.cs b/Assembly-CSharp/RimWorld.BaseGen/SymbolResolver_BasePart_Outdoors_Division_Grid.cs index 6ecb85def..5f8af6116 100644 --- a/Assembly-CSharp/RimWorld.BaseGen/SymbolResolver_BasePart_Outdoors_Division_Grid.cs +++ b/Assembly-CSharp/RimWorld.BaseGen/SymbolResolver_BasePart_Outdoors_Division_Grid.cs @@ -36,7 +36,7 @@ private class Child private List> optionsZ = new List>(); - private List children = new List(); + private List children = new List(); private static List, Pair>> options = new List, Pair>>(); @@ -51,53 +51,29 @@ public override bool CanResolve(ResolveParams rp) return false; } this.FillOptions(rp.rect); - return this.optionsX.Any>() && this.optionsZ.Any>(); + return this.optionsX.Any() && this.optionsZ.Any(); } public override void Resolve(ResolveParams rp) { this.FillOptions(rp.rect); - if (!Rand.Chance(0.2f)) + if ((Rand.Chance(0.2f) || (!this.TryResolveRandomOption(0, 0, rp) && !this.TryResolveRandomOption(0, 1, rp))) && !this.TryResolveRandomOption(1, 0, rp) && !this.TryResolveRandomOption(2, 0, rp) && !this.TryResolveRandomOption(2, 1, rp) && !this.TryResolveRandomOption(999999, 999999, rp)) { - if (this.TryResolveRandomOption(0, 0, rp)) - { - return; - } - if (this.TryResolveRandomOption(0, 1, rp)) - { - return; - } - } - if (this.TryResolveRandomOption(1, 0, rp)) - { - return; - } - if (this.TryResolveRandomOption(2, 0, rp)) - { - return; - } - if (this.TryResolveRandomOption(2, 1, rp)) - { - return; - } - if (this.TryResolveRandomOption(999999, 999999, rp)) - { - return; + Log.Warning("Grid resolver could not resolve any grid size. params=" + rp); } - Log.Warning("Grid resolver could not resolve any grid size. params=" + rp); } private void FillOptions(CellRect rect) { this.FillOptions(this.optionsX, rect.Width); this.FillOptions(this.optionsZ, rect.Height); - if (this.optionsZ.Any((Pair x) => x.First > 1)) + if (this.optionsZ.Any((Predicate>)((Pair x) => x.First > 1))) { - this.optionsX.RemoveAll((Pair x) => x.First >= 3 && this.GetRoomSize(x.First, x.Second, rect.Width) <= 7); + this.optionsX.RemoveAll((Predicate>)((Pair x) => x.First >= 3 && this.GetRoomSize(x.First, x.Second, rect.Width) <= 7)); } - if (this.optionsX.Any((Pair x) => x.First > 1)) + if (this.optionsX.Any((Predicate>)((Pair x) => x.First > 1))) { - this.optionsZ.RemoveAll((Pair x) => x.First >= 3 && this.GetRoomSize(x.First, x.Second, rect.Height) <= 7); + this.optionsZ.RemoveAll((Predicate>)((Pair x) => x.First >= 3 && this.GetRoomSize(x.First, x.Second, rect.Height) <= 7)); } } @@ -146,9 +122,9 @@ private bool TryResolveRandomOption(int maxWidthHeightDiff, int maxPathwayWidthD } } } - if (SymbolResolver_BasePart_Outdoors_Division_Grid.options.Any, Pair>>()) + if (SymbolResolver_BasePart_Outdoors_Division_Grid.options.Any()) { - Pair, Pair> pair = SymbolResolver_BasePart_Outdoors_Division_Grid.options.RandomElement, Pair>>(); + Pair, Pair> pair = SymbolResolver_BasePart_Outdoors_Division_Grid.options.RandomElement(); this.ResolveOption(pair.First.First, pair.First.Second, pair.Second.First, pair.Second.Second, rp); return true; } @@ -163,14 +139,7 @@ private void ResolveOption(int roomsPerRowX, int pathwayWidthX, int roomsPerRowZ ThingDef thingDef = null; if (pathwayWidthX >= 3) { - if (rp.faction == null || rp.faction.def.techLevel >= TechLevel.Industrial) - { - thingDef = ThingDefOf.StandingLamp; - } - else - { - thingDef = ThingDefOf.TorchLamp; - } + thingDef = ((rp.faction != null && (int)rp.faction.def.techLevel < 4) ? ThingDefOf.TorchLamp : ThingDefOf.StandingLamp); } TerrainDef floorDef = rp.pathwayFloorDef ?? BaseGenUtility.RandomBasicFloorDef(rp.faction, false); int num = roomSize; @@ -198,14 +167,14 @@ private void ResolveOption(int roomsPerRowX, int pathwayWidthX, int roomsPerRowZ num = 0; num2 = 0; this.children.Clear(); - for (int k = 0; k < roomsPerRowX; k++) + for (int num3 = 0; num3 < roomsPerRowX; num3++) { - for (int l = 0; l < roomsPerRowZ; l++) + for (int num4 = 0; num4 < roomsPerRowZ; num4++) { - SymbolResolver_BasePart_Outdoors_Division_Grid.Child child = new SymbolResolver_BasePart_Outdoors_Division_Grid.Child(); + Child child = new Child(); child.rect = new CellRect(rp.rect.minX + num, rp.rect.minZ + num2, roomSize, roomSize2); - child.gridX = k; - child.gridY = l; + child.gridX = num3; + child.gridY = num4; this.children.Add(child); num2 += roomSize2 + pathwayWidthZ; } @@ -213,12 +182,12 @@ private void ResolveOption(int roomsPerRowX, int pathwayWidthX, int roomsPerRowZ num2 = 0; } this.MergeRandomChildren(); - this.children.Shuffle(); - for (int m = 0; m < this.children.Count; m++) + this.children.Shuffle(); + for (int k = 0; k < this.children.Count; k++) { if (thingDef != null) { - IntVec3 c = new IntVec3(this.children[m].rect.maxX + 1, 0, this.children[m].rect.maxZ); + IntVec3 c = new IntVec3(this.children[k].rect.maxX + 1, 0, this.children[k].rect.maxZ); if (rp.rect.Contains(c) && c.Standable(map)) { ResolveParams resolveParams3 = rp; @@ -228,37 +197,39 @@ private void ResolveOption(int roomsPerRowX, int pathwayWidthX, int roomsPerRowZ } } ResolveParams resolveParams4 = rp; - resolveParams4.rect = this.children[m].rect; + resolveParams4.rect = this.children[k].rect; BaseGen.symbolStack.Push("basePart_outdoors", resolveParams4); } } private void MergeRandomChildren() { - if (this.children.Count < 4) + if (this.children.Count >= 4) { - return; - } - int num = GenMath.RoundRandom((float)this.children.Count / 6f); - for (int i = 0; i < num; i++) - { - SymbolResolver_BasePart_Outdoors_Division_Grid.Child child = this.children.Find((SymbolResolver_BasePart_Outdoors_Division_Grid.Child x) => !x.merged); - if (child == null) + int num = GenMath.RoundRandom((float)((float)this.children.Count / 6.0)); + int num2 = 0; + while (num2 < num) { + Child child = this.children.Find((Predicate)((Child x) => !x.merged)); + if (child != null) + { + Child child2 = this.children.Find((Predicate)((Child x) => x != child && ((Mathf.Abs(x.gridX - child.gridX) == 1 && x.gridY == child.gridY) || (Mathf.Abs(x.gridY - child.gridY) == 1 && x.gridX == child.gridX)))); + if (child2 != null) + { + this.children.Remove(child); + this.children.Remove(child2); + Child child3 = new Child(); + child3.gridX = Mathf.Min(child.gridX, child2.gridX); + child3.gridY = Mathf.Min(child.gridY, child2.gridY); + child3.merged = true; + child3.rect = CellRect.FromLimits(Mathf.Min(child.rect.minX, child2.rect.minX), Mathf.Min(child.rect.minZ, child2.rect.minZ), Mathf.Max(child.rect.maxX, child2.rect.maxX), Mathf.Max(child.rect.maxZ, child2.rect.maxZ)); + this.children.Add(child3); + } + num2++; + continue; + } break; } - SymbolResolver_BasePart_Outdoors_Division_Grid.Child child3 = this.children.Find((SymbolResolver_BasePart_Outdoors_Division_Grid.Child x) => x != child && ((Mathf.Abs(x.gridX - child.gridX) == 1 && x.gridY == child.gridY) || (Mathf.Abs(x.gridY - child.gridY) == 1 && x.gridX == child.gridX))); - if (child3 != null) - { - this.children.Remove(child); - this.children.Remove(child3); - SymbolResolver_BasePart_Outdoors_Division_Grid.Child child2 = new SymbolResolver_BasePart_Outdoors_Division_Grid.Child(); - child2.gridX = Mathf.Min(child.gridX, child3.gridX); - child2.gridY = Mathf.Min(child.gridY, child3.gridY); - child2.merged = true; - child2.rect = CellRect.FromLimits(Mathf.Min(child.rect.minX, child3.rect.minX), Mathf.Min(child.rect.minZ, child3.rect.minZ), Mathf.Max(child.rect.maxX, child3.rect.maxX), Mathf.Max(child.rect.maxZ, child3.rect.maxZ)); - this.children.Add(child2); - } } } } diff --git a/Assembly-CSharp/RimWorld.BaseGen/SymbolResolver_BasePart_Outdoors_Division_Split.cs b/Assembly-CSharp/RimWorld.BaseGen/SymbolResolver_BasePart_Outdoors_Division_Split.cs index 6bd9d030c..59623b133 100644 --- a/Assembly-CSharp/RimWorld.BaseGen/SymbolResolver_BasePart_Outdoors_Division_Split.cs +++ b/Assembly-CSharp/RimWorld.BaseGen/SymbolResolver_BasePart_Outdoors_Division_Split.cs @@ -1,4 +1,3 @@ -using System; using UnityEngine; using Verse; @@ -12,30 +11,38 @@ public class SymbolResolver_BasePart_Outdoors_Division_Split : SymbolResolver public override bool CanResolve(ResolveParams rp) { - int num; - int num2; - return base.CanResolve(rp) && (this.TryFindSplitPoint(false, rp.rect, out num, out num2) || this.TryFindSplitPoint(true, rp.rect, out num, out num2)); + if (!base.CanResolve(rp)) + { + return false; + } + int num = default(int); + int num2 = default(int); + if (!this.TryFindSplitPoint(false, rp.rect, out num, out num2) && !this.TryFindSplitPoint(true, rp.rect, out num, out num2)) + { + return false; + } + return true; } public override void Resolve(ResolveParams rp) { bool @bool = Rand.Bool; - int num; - int num2; + int num = default(int); + int num2 = default(int); bool flag; if (this.TryFindSplitPoint(@bool, rp.rect, out num, out num2)) { flag = @bool; + goto IL_0053; } - else + if (this.TryFindSplitPoint(!@bool, rp.rect, out num, out num2)) { - if (!this.TryFindSplitPoint(!@bool, rp.rect, out num, out num2)) - { - Log.Warning("Could not find split point."); - return; - } flag = !@bool; + goto IL_0053; } + Log.Warning("Could not find split point."); + return; + IL_0053: TerrainDef floorDef = rp.pathwayFloorDef ?? BaseGenUtility.RandomBasicFloorDef(rp.faction, false); ResolveParams resolveParams3; ResolveParams resolveParams5; @@ -84,7 +91,9 @@ private bool TryFindSplitPoint(bool horizontal, CellRect rect, out int splitPoin int num = (!horizontal) ? rect.Width : rect.Height; spaceBetween = SymbolResolver_BasePart_Outdoors_Division_Split.SpaceBetweenRange.RandomInRange; spaceBetween = Mathf.Min(spaceBetween, num - 10); - if (spaceBetween < SymbolResolver_BasePart_Outdoors_Division_Split.SpaceBetweenRange.min) + int num2 = spaceBetween; + IntRange spaceBetweenRange = SymbolResolver_BasePart_Outdoors_Division_Split.SpaceBetweenRange; + if (num2 < spaceBetweenRange.min) { splitPoint = -1; return false; diff --git a/Assembly-CSharp/RimWorld.BaseGen/SymbolResolver_BasePart_Outdoors_LeafDecorated_EdgeStreet.cs b/Assembly-CSharp/RimWorld.BaseGen/SymbolResolver_BasePart_Outdoors_LeafDecorated_EdgeStreet.cs index 349e9cc6f..09f6dc420 100644 --- a/Assembly-CSharp/RimWorld.BaseGen/SymbolResolver_BasePart_Outdoors_LeafDecorated_EdgeStreet.cs +++ b/Assembly-CSharp/RimWorld.BaseGen/SymbolResolver_BasePart_Outdoors_LeafDecorated_EdgeStreet.cs @@ -1,5 +1,3 @@ -using System; - namespace RimWorld.BaseGen { public class SymbolResolver_BasePart_Outdoors_LeafDecorated_EdgeStreet : SymbolResolver diff --git a/Assembly-CSharp/RimWorld.BaseGen/SymbolResolver_BasePart_Outdoors_LeafDecorated_RandomInnerRect.cs b/Assembly-CSharp/RimWorld.BaseGen/SymbolResolver_BasePart_Outdoors_LeafDecorated_RandomInnerRect.cs index ba7e48f1e..2515fb428 100644 --- a/Assembly-CSharp/RimWorld.BaseGen/SymbolResolver_BasePart_Outdoors_LeafDecorated_RandomInnerRect.cs +++ b/Assembly-CSharp/RimWorld.BaseGen/SymbolResolver_BasePart_Outdoors_LeafDecorated_RandomInnerRect.cs @@ -1,4 +1,3 @@ -using System; using Verse; namespace RimWorld.BaseGen diff --git a/Assembly-CSharp/RimWorld.BaseGen/SymbolResolver_BasePart_Outdoors_LeafPossiblyDecorated.cs b/Assembly-CSharp/RimWorld.BaseGen/SymbolResolver_BasePart_Outdoors_LeafPossiblyDecorated.cs index ddbaede58..872451822 100644 --- a/Assembly-CSharp/RimWorld.BaseGen/SymbolResolver_BasePart_Outdoors_LeafPossiblyDecorated.cs +++ b/Assembly-CSharp/RimWorld.BaseGen/SymbolResolver_BasePart_Outdoors_LeafPossiblyDecorated.cs @@ -1,4 +1,3 @@ -using System; using Verse; namespace RimWorld.BaseGen diff --git a/Assembly-CSharp/RimWorld.BaseGen/SymbolResolver_BasePart_Outdoors_Leaf_Building.cs b/Assembly-CSharp/RimWorld.BaseGen/SymbolResolver_BasePart_Outdoors_Leaf_Building.cs index 165a9258a..dc0263470 100644 --- a/Assembly-CSharp/RimWorld.BaseGen/SymbolResolver_BasePart_Outdoors_Leaf_Building.cs +++ b/Assembly-CSharp/RimWorld.BaseGen/SymbolResolver_BasePart_Outdoors_Leaf_Building.cs @@ -1,12 +1,18 @@ -using System; - namespace RimWorld.BaseGen { public class SymbolResolver_BasePart_Outdoors_Leaf_Building : SymbolResolver { public override bool CanResolve(ResolveParams rp) { - return base.CanResolve(rp) && (BaseGen.globalSettings.basePart_emptyNodesResolved >= BaseGen.globalSettings.minEmptyNodes || BaseGen.globalSettings.basePart_buildingsResolved < BaseGen.globalSettings.minBuildings); + if (!base.CanResolve(rp)) + { + return false; + } + if (BaseGen.globalSettings.basePart_emptyNodesResolved < BaseGen.globalSettings.minEmptyNodes && BaseGen.globalSettings.basePart_buildingsResolved >= BaseGen.globalSettings.minBuildings) + { + return false; + } + return true; } public override void Resolve(ResolveParams rp) diff --git a/Assembly-CSharp/RimWorld.BaseGen/SymbolResolver_BasePart_Outdoors_Leaf_Empty.cs b/Assembly-CSharp/RimWorld.BaseGen/SymbolResolver_BasePart_Outdoors_Leaf_Empty.cs index 64adf18aa..fd6adde19 100644 --- a/Assembly-CSharp/RimWorld.BaseGen/SymbolResolver_BasePart_Outdoors_Leaf_Empty.cs +++ b/Assembly-CSharp/RimWorld.BaseGen/SymbolResolver_BasePart_Outdoors_Leaf_Empty.cs @@ -1,12 +1,18 @@ -using System; - namespace RimWorld.BaseGen { public class SymbolResolver_BasePart_Outdoors_Leaf_Empty : SymbolResolver { public override bool CanResolve(ResolveParams rp) { - return base.CanResolve(rp) && BaseGen.globalSettings.basePart_buildingsResolved >= BaseGen.globalSettings.minBuildings; + if (!base.CanResolve(rp)) + { + return false; + } + if (BaseGen.globalSettings.basePart_buildingsResolved < BaseGen.globalSettings.minBuildings) + { + return false; + } + return true; } public override void Resolve(ResolveParams rp) diff --git a/Assembly-CSharp/RimWorld.BaseGen/SymbolResolver_BasePart_Outdoors_Leaf_Farm.cs b/Assembly-CSharp/RimWorld.BaseGen/SymbolResolver_BasePart_Outdoors_Leaf_Farm.cs index 2144f3739..b743d8e1a 100644 --- a/Assembly-CSharp/RimWorld.BaseGen/SymbolResolver_BasePart_Outdoors_Leaf_Farm.cs +++ b/Assembly-CSharp/RimWorld.BaseGen/SymbolResolver_BasePart_Outdoors_Leaf_Farm.cs @@ -1,5 +1,3 @@ -using System; - namespace RimWorld.BaseGen { public class SymbolResolver_BasePart_Outdoors_Leaf_Farm : SymbolResolver @@ -8,7 +6,23 @@ public class SymbolResolver_BasePart_Outdoors_Leaf_Farm : SymbolResolver public override bool CanResolve(ResolveParams rp) { - return base.CanResolve(rp) && BaseGen.globalSettings.basePart_buildingsResolved >= BaseGen.globalSettings.minBuildings && BaseGen.globalSettings.basePart_emptyNodesResolved >= BaseGen.globalSettings.minEmptyNodes && BaseGen.globalSettings.basePart_farmsCoverage + (float)rp.rect.Area / (float)BaseGen.globalSettings.mainRect.Area < 0.55f && (rp.rect.Width <= 15 && rp.rect.Height <= 15) && (rp.cultivatedPlantDef != null || SymbolResolver_CultivatedPlants.DeterminePlantDef(rp.rect) != null); + if (!base.CanResolve(rp)) + { + return false; + } + if (BaseGen.globalSettings.basePart_buildingsResolved < BaseGen.globalSettings.minBuildings) + { + return false; + } + if (BaseGen.globalSettings.basePart_emptyNodesResolved < BaseGen.globalSettings.minEmptyNodes) + { + return false; + } + if (BaseGen.globalSettings.basePart_farmsCoverage + (float)rp.rect.Area / (float)BaseGen.globalSettings.mainRect.Area >= 0.550000011920929) + { + return false; + } + return rp.rect.Width <= 15 && rp.rect.Height <= 15 && (rp.cultivatedPlantDef != null || SymbolResolver_CultivatedPlants.DeterminePlantDef(rp.rect) != null); } public override void Resolve(ResolveParams rp) diff --git a/Assembly-CSharp/RimWorld.BaseGen/SymbolResolver_BasePart_Outdoors_Leaf_PowerPlant.cs b/Assembly-CSharp/RimWorld.BaseGen/SymbolResolver_BasePart_Outdoors_Leaf_PowerPlant.cs index 0cbfd1db7..96f17e16d 100644 --- a/Assembly-CSharp/RimWorld.BaseGen/SymbolResolver_BasePart_Outdoors_Leaf_PowerPlant.cs +++ b/Assembly-CSharp/RimWorld.BaseGen/SymbolResolver_BasePart_Outdoors_Leaf_PowerPlant.cs @@ -1,4 +1,3 @@ -using System; using System.Collections.Generic; using UnityEngine; using Verse; @@ -25,37 +24,36 @@ public override bool CanResolve(ResolveParams rp) { return false; } - if (BaseGen.globalSettings.basePart_powerPlantsCoverage + (float)rp.rect.Area / (float)BaseGen.globalSettings.mainRect.Area >= 0.09f) + if (BaseGen.globalSettings.basePart_powerPlantsCoverage + (float)rp.rect.Area / (float)BaseGen.globalSettings.mainRect.Area >= 0.090000003576278687) { return false; } - if (rp.faction != null && rp.faction.def.techLevel < TechLevel.Industrial) + if (rp.faction != null && (int)rp.faction.def.techLevel < 4) { return false; } - if (rp.rect.Width > 13 || rp.rect.Height > 13) + if (rp.rect.Width <= 13 && rp.rect.Height <= 13) { - return false; + this.CalculateAvailablePowerPlants(rp.rect); + return SymbolResolver_BasePart_Outdoors_Leaf_PowerPlant.availablePowerPlants.Any(); } - this.CalculateAvailablePowerPlants(rp.rect); - return SymbolResolver_BasePart_Outdoors_Leaf_PowerPlant.availablePowerPlants.Any(); + return false; } public override void Resolve(ResolveParams rp) { this.CalculateAvailablePowerPlants(rp.rect); - if (!SymbolResolver_BasePart_Outdoors_Leaf_PowerPlant.availablePowerPlants.Any()) + if (SymbolResolver_BasePart_Outdoors_Leaf_PowerPlant.availablePowerPlants.Any()) { - return; + BaseGen.symbolStack.Push("refuel", rp); + ThingDef thingDef = SymbolResolver_BasePart_Outdoors_Leaf_PowerPlant.availablePowerPlants.RandomElement(); + ResolveParams resolveParams = rp; + resolveParams.singleThingDef = thingDef; + int? fillWithThingsPadding = rp.fillWithThingsPadding; + resolveParams.fillWithThingsPadding = new int?((!fillWithThingsPadding.HasValue) ? Mathf.Max(5 - thingDef.size.x, 1) : fillWithThingsPadding.Value); + BaseGen.symbolStack.Push("fillWithThings", resolveParams); + BaseGen.globalSettings.basePart_powerPlantsCoverage += (float)rp.rect.Area / (float)BaseGen.globalSettings.mainRect.Area; } - BaseGen.symbolStack.Push("refuel", rp); - ThingDef thingDef = SymbolResolver_BasePart_Outdoors_Leaf_PowerPlant.availablePowerPlants.RandomElement(); - ResolveParams resolveParams = rp; - resolveParams.singleThingDef = thingDef; - int? fillWithThingsPadding = rp.fillWithThingsPadding; - resolveParams.fillWithThingsPadding = new int?((!fillWithThingsPadding.HasValue) ? Mathf.Max(5 - thingDef.size.x, 1) : fillWithThingsPadding.Value); - BaseGen.symbolStack.Push("fillWithThings", resolveParams); - BaseGen.globalSettings.basePart_powerPlantsCoverage += (float)rp.rect.Area / (float)BaseGen.globalSettings.mainRect.Area; } private void CalculateAvailablePowerPlants(CellRect rect) @@ -74,7 +72,7 @@ private void CalculateAvailablePowerPlants(CellRect rect) } iterator.MoveNext(); } - if ((float)num / (float)rect.Area >= 0.5f) + if ((float)num / (float)rect.Area >= 0.5) { SymbolResolver_BasePart_Outdoors_Leaf_PowerPlant.availablePowerPlants.Add(ThingDefOf.SolarGenerator); } diff --git a/Assembly-CSharp/RimWorld.BaseGen/SymbolResolver_BatteryRoom.cs b/Assembly-CSharp/RimWorld.BaseGen/SymbolResolver_BatteryRoom.cs index e7c48cae2..2991660e0 100644 --- a/Assembly-CSharp/RimWorld.BaseGen/SymbolResolver_BatteryRoom.cs +++ b/Assembly-CSharp/RimWorld.BaseGen/SymbolResolver_BatteryRoom.cs @@ -1,5 +1,3 @@ -using System; - namespace RimWorld.BaseGen { public class SymbolResolver_BatteryRoom : SymbolResolver diff --git a/Assembly-CSharp/RimWorld.BaseGen/SymbolResolver_Brewery.cs b/Assembly-CSharp/RimWorld.BaseGen/SymbolResolver_Brewery.cs index 3b09ee249..070c72a4d 100644 --- a/Assembly-CSharp/RimWorld.BaseGen/SymbolResolver_Brewery.cs +++ b/Assembly-CSharp/RimWorld.BaseGen/SymbolResolver_Brewery.cs @@ -1,5 +1,3 @@ -using System; - namespace RimWorld.BaseGen { public class SymbolResolver_Brewery : SymbolResolver diff --git a/Assembly-CSharp/RimWorld.BaseGen/SymbolResolver_ChargeBatteries.cs b/Assembly-CSharp/RimWorld.BaseGen/SymbolResolver_ChargeBatteries.cs index 4fd6ac14b..7a4b91fc6 100644 --- a/Assembly-CSharp/RimWorld.BaseGen/SymbolResolver_ChargeBatteries.cs +++ b/Assembly-CSharp/RimWorld.BaseGen/SymbolResolver_ChargeBatteries.cs @@ -1,4 +1,3 @@ -using System; using System.Collections.Generic; using UnityEngine; using Verse; diff --git a/Assembly-CSharp/RimWorld.BaseGen/SymbolResolver_Clear.cs b/Assembly-CSharp/RimWorld.BaseGen/SymbolResolver_Clear.cs index 368766ed4..d3baac06f 100644 --- a/Assembly-CSharp/RimWorld.BaseGen/SymbolResolver_Clear.cs +++ b/Assembly-CSharp/RimWorld.BaseGen/SymbolResolver_Clear.cs @@ -1,4 +1,3 @@ -using System; using System.Collections.Generic; using Verse; diff --git a/Assembly-CSharp/RimWorld.BaseGen/SymbolResolver_CultivatedPlants.cs b/Assembly-CSharp/RimWorld.BaseGen/SymbolResolver_CultivatedPlants.cs index 2f2917660..20f26eb55 100644 --- a/Assembly-CSharp/RimWorld.BaseGen/SymbolResolver_CultivatedPlants.cs +++ b/Assembly-CSharp/RimWorld.BaseGen/SymbolResolver_CultivatedPlants.cs @@ -21,19 +21,15 @@ public override void Resolve(ResolveParams rp) { Map map = BaseGen.globalSettings.map; ThingDef thingDef = rp.cultivatedPlantDef ?? SymbolResolver_CultivatedPlants.DeterminePlantDef(rp.rect); - if (thingDef == null) + if (thingDef != null) { - return; - } - float growth = Rand.Range(0.2f, 1f); - int age = (!thingDef.plant.LimitedLifespan) ? 0 : Rand.Range(0, Mathf.Max(thingDef.plant.LifespanTicks - 2500, 0)); - CellRect.CellRectIterator iterator = rp.rect.GetIterator(); - while (!iterator.Done()) - { - float num = map.fertilityGrid.FertilityAt(iterator.Current); - if (num >= thingDef.plant.fertilityMin) + float growth = Rand.Range(0.2f, 1f); + int age = thingDef.plant.LimitedLifespan ? Rand.Range(0, Mathf.Max(thingDef.plant.LifespanTicks - 2500, 0)) : 0; + CellRect.CellRectIterator iterator = rp.rect.GetIterator(); + while (!iterator.Done()) { - if (this.TryDestroyBlockingThingsAt(iterator.Current)) + float num = map.fertilityGrid.FertilityAt(iterator.Current); + if (!(num < thingDef.plant.fertilityMin) && this.TryDestroyBlockingThingsAt(iterator.Current)) { Plant plant = (Plant)GenSpawn.Spawn(thingDef, iterator.Current, map); plant.Growth = growth; @@ -42,42 +38,42 @@ public override void Resolve(ResolveParams rp) plant.Age = age; } } + iterator.MoveNext(); } - iterator.MoveNext(); } } public static ThingDef DeterminePlantDef(CellRect rect) { Map map = BaseGen.globalSettings.map; - if (map.mapTemperature.OutdoorTemp < 0f || map.mapTemperature.OutdoorTemp > 58f) - { - return null; - } - float minFertility = 3.40282347E+38f; - bool flag = false; - CellRect.CellRectIterator iterator = rect.GetIterator(); - while (!iterator.Done()) + if (!(map.mapTemperature.OutdoorTemp < 0.0) && !(map.mapTemperature.OutdoorTemp > 58.0)) { - float num = map.fertilityGrid.FertilityAt(iterator.Current); - if (num > 0f) + float minFertility = 3.40282347E+38f; + bool flag = false; + CellRect.CellRectIterator iterator = rect.GetIterator(); + while (!iterator.Done()) { - flag = true; - minFertility = Mathf.Min(minFertility, num); + float num = map.fertilityGrid.FertilityAt(iterator.Current); + if (!(num <= 0.0)) + { + flag = true; + minFertility = Mathf.Min(minFertility, num); + } + iterator.MoveNext(); + } + if (!flag) + { + return null; + } + ThingDef result = default(ThingDef); + if ((from x in DefDatabase.AllDefsListForReading + where x.category == ThingCategory.Plant && x.plant.Sowable && !x.plant.IsTree && x.plant.fertilityMin <= minFertility && x.plant.Harvestable + select x).TryRandomElement(out result)) + { + return result; } - iterator.MoveNext(); - } - if (!flag) - { return null; } - ThingDef result; - if ((from x in DefDatabase.AllDefsListForReading - where x.category == ThingCategory.Plant && x.plant.Sowable && !x.plant.IsTree && x.plant.fertilityMin <= minFertility && x.plant.Harvestable - select x).TryRandomElement(out result)) - { - return result; - } return null; } @@ -88,13 +84,10 @@ private bool TryDestroyBlockingThingsAt(IntVec3 c) SymbolResolver_CultivatedPlants.tmpThings.AddRange(c.GetThingList(map)); for (int i = 0; i < SymbolResolver_CultivatedPlants.tmpThings.Count; i++) { - if (!(SymbolResolver_CultivatedPlants.tmpThings[i] is Pawn)) + if (!(SymbolResolver_CultivatedPlants.tmpThings[i] is Pawn) && !SymbolResolver_CultivatedPlants.tmpThings[i].def.destroyable) { - if (!SymbolResolver_CultivatedPlants.tmpThings[i].def.destroyable) - { - SymbolResolver_CultivatedPlants.tmpThings.Clear(); - return false; - } + SymbolResolver_CultivatedPlants.tmpThings.Clear(); + return false; } } for (int j = 0; j < SymbolResolver_CultivatedPlants.tmpThings.Count; j++) diff --git a/Assembly-CSharp/RimWorld.BaseGen/SymbolResolver_DiningRoom.cs b/Assembly-CSharp/RimWorld.BaseGen/SymbolResolver_DiningRoom.cs index a0410828e..957cb6e31 100644 --- a/Assembly-CSharp/RimWorld.BaseGen/SymbolResolver_DiningRoom.cs +++ b/Assembly-CSharp/RimWorld.BaseGen/SymbolResolver_DiningRoom.cs @@ -1,5 +1,3 @@ -using System; - namespace RimWorld.BaseGen { public class SymbolResolver_DiningRoom : SymbolResolver diff --git a/Assembly-CSharp/RimWorld.BaseGen/SymbolResolver_Doors.cs b/Assembly-CSharp/RimWorld.BaseGen/SymbolResolver_Doors.cs index ac2de5d0d..0edfe614a 100644 --- a/Assembly-CSharp/RimWorld.BaseGen/SymbolResolver_Doors.cs +++ b/Assembly-CSharp/RimWorld.BaseGen/SymbolResolver_Doors.cs @@ -1,4 +1,3 @@ -using System; using Verse; namespace RimWorld.BaseGen diff --git a/Assembly-CSharp/RimWorld.BaseGen/SymbolResolver_EdgeDefense.cs b/Assembly-CSharp/RimWorld.BaseGen/SymbolResolver_EdgeDefense.cs index fd066a0c7..e6450880a 100644 --- a/Assembly-CSharp/RimWorld.BaseGen/SymbolResolver_EdgeDefense.cs +++ b/Assembly-CSharp/RimWorld.BaseGen/SymbolResolver_EdgeDefense.cs @@ -16,7 +16,7 @@ public override void Resolve(ResolveParams rp) Map map = BaseGen.globalSettings.map; Faction faction = rp.faction ?? Find.FactionManager.RandomEnemyFaction(false, false, true); int? edgeDefenseGuardsCount = rp.edgeDefenseGuardsCount; - int num = (!edgeDefenseGuardsCount.HasValue) ? 0 : edgeDefenseGuardsCount.Value; + int num = edgeDefenseGuardsCount.HasValue ? edgeDefenseGuardsCount.Value : 0; int width; if (rp.edgeDefenseWidth.HasValue) { @@ -40,8 +40,8 @@ public override void Resolve(ResolveParams rp) { case 1: { - int? edgeDefenseTurretsCount = rp.edgeDefenseTurretsCount; - num2 = ((!edgeDefenseTurretsCount.HasValue) ? 0 : edgeDefenseTurretsCount.Value); + int? edgeDefenseTurretsCount2 = rp.edgeDefenseTurretsCount; + num2 = (edgeDefenseTurretsCount2.HasValue ? edgeDefenseTurretsCount2.Value : 0); num3 = 0; flag = false; flag2 = true; @@ -50,8 +50,8 @@ public override void Resolve(ResolveParams rp) } case 2: { - int? edgeDefenseTurretsCount2 = rp.edgeDefenseTurretsCount; - num2 = ((!edgeDefenseTurretsCount2.HasValue) ? (rp.rect.EdgeCellsCount / 30) : edgeDefenseTurretsCount2.Value); + int? edgeDefenseTurretsCount3 = rp.edgeDefenseTurretsCount; + num2 = ((!edgeDefenseTurretsCount3.HasValue) ? (rp.rect.EdgeCellsCount / 30) : edgeDefenseTurretsCount3.Value); num3 = 0; flag = false; flag2 = false; @@ -60,10 +60,10 @@ public override void Resolve(ResolveParams rp) } case 3: { - int? edgeDefenseTurretsCount3 = rp.edgeDefenseTurretsCount; - num2 = ((!edgeDefenseTurretsCount3.HasValue) ? (rp.rect.EdgeCellsCount / 30) : edgeDefenseTurretsCount3.Value); - int? edgeDefenseMortarsCount = rp.edgeDefenseMortarsCount; - num3 = ((!edgeDefenseMortarsCount.HasValue) ? (rp.rect.EdgeCellsCount / 75) : edgeDefenseMortarsCount.Value); + int? edgeDefenseTurretsCount4 = rp.edgeDefenseTurretsCount; + num2 = ((!edgeDefenseTurretsCount4.HasValue) ? (rp.rect.EdgeCellsCount / 30) : edgeDefenseTurretsCount4.Value); + int? edgeDefenseMortarsCount2 = rp.edgeDefenseMortarsCount; + num3 = ((!edgeDefenseMortarsCount2.HasValue) ? (rp.rect.EdgeCellsCount / 75) : edgeDefenseMortarsCount2.Value); flag = (num3 == 0); flag2 = false; flag3 = true; @@ -71,17 +71,17 @@ public override void Resolve(ResolveParams rp) } default: { - int? edgeDefenseTurretsCount4 = rp.edgeDefenseTurretsCount; - num2 = ((!edgeDefenseTurretsCount4.HasValue) ? (rp.rect.EdgeCellsCount / 30) : edgeDefenseTurretsCount4.Value); - int? edgeDefenseMortarsCount2 = rp.edgeDefenseMortarsCount; - num3 = ((!edgeDefenseMortarsCount2.HasValue) ? (rp.rect.EdgeCellsCount / 75) : edgeDefenseMortarsCount2.Value); + int? edgeDefenseTurretsCount = rp.edgeDefenseTurretsCount; + num2 = ((!edgeDefenseTurretsCount.HasValue) ? (rp.rect.EdgeCellsCount / 30) : edgeDefenseTurretsCount.Value); + int? edgeDefenseMortarsCount = rp.edgeDefenseMortarsCount; + num3 = ((!edgeDefenseMortarsCount.HasValue) ? (rp.rect.EdgeCellsCount / 75) : edgeDefenseMortarsCount.Value); flag = true; flag2 = false; flag3 = false; break; } } - if (faction != null && faction.def.techLevel < TechLevel.Industrial) + if (faction != null && (int)faction.def.techLevel < 4) { num2 = 0; num3 = 0; @@ -89,17 +89,18 @@ public override void Resolve(ResolveParams rp) if (num > 0) { Lord singlePawnLord = rp.singlePawnLord ?? LordMaker.MakeNewLord(faction, new LordJob_DefendBase(faction, rp.rect.CenterCell), map, null); - for (int i = 0; i < num; i++) + for (int num4 = 0; num4 < num; num4++) { - PawnGenerationRequest value = new PawnGenerationRequest(faction.RandomPawnKind(), faction, PawnGenerationContext.NonPlayer, -1, false, false, false, false, true, true, 1f, false, true, true, false, false, null, null, null, null, null, null); - ResolveParams rp2 = rp; - rp2.faction = faction; - rp2.singlePawnLord = singlePawnLord; - rp2.singlePawnGenerationRequest = new PawnGenerationRequest?(value); - rp2.singlePawnSpawnCellExtraPredicate = (rp2.singlePawnSpawnCellExtraPredicate ?? delegate(IntVec3 x) + PawnGenerationRequest value = new PawnGenerationRequest(faction.RandomPawnKind(), faction, PawnGenerationContext.NonPlayer, -1, false, false, false, false, true, true, 1f, false, true, true, false, false, null, default(float?), default(float?), default(Gender?), default(float?), (string)null); + ResolveParams resolveParams = rp; + resolveParams.faction = faction; + resolveParams.singlePawnLord = singlePawnLord; + resolveParams.singlePawnGenerationRequest = new PawnGenerationRequest?(value); + object obj = resolveParams.singlePawnSpawnCellExtraPredicate; + obj = (resolveParams.singlePawnSpawnCellExtraPredicate = (Predicate)delegate(IntVec3 x) { CellRect cellRect = rp.rect; - for (int m = 0; m < width; m++) + for (int num8 = 0; num8 < width; num8++) { if (cellRect.IsOnEdge(x)) { @@ -109,43 +110,41 @@ public override void Resolve(ResolveParams rp) } return true; }); - BaseGen.symbolStack.Push("pawn", rp2); + BaseGen.symbolStack.Push("pawn", resolveParams); } } CellRect rect = rp.rect; - for (int j = 0; j < width; j++) + for (int num5 = 0; num5 < width; num5++) { - if (j % 2 == 0) + if (num5 % 2 == 0) { - ResolveParams rp3 = rp; - rp3.faction = faction; - rp3.rect = rect; - BaseGen.symbolStack.Push("edgeSandbags", rp3); + ResolveParams resolveParams2 = rp; + resolveParams2.faction = faction; + resolveParams2.rect = rect; + BaseGen.symbolStack.Push("edgeSandbags", resolveParams2); if (!flag) - { break; - } } rect = rect.ContractedBy(1); } CellRect rect2 = (!flag3) ? rp.rect.ContractedBy(1) : rp.rect; - for (int k = 0; k < num3; k++) + for (int num6 = 0; num6 < num3; num6++) { - ResolveParams rp4 = rp; - rp4.faction = faction; - rp4.rect = rect2; - BaseGen.symbolStack.Push("edgeMannedMortar", rp4); + ResolveParams resolveParams3 = rp; + resolveParams3.faction = faction; + resolveParams3.rect = rect2; + BaseGen.symbolStack.Push("edgeMannedMortar", resolveParams3); } CellRect rect3 = (!flag2) ? rp.rect.ContractedBy(1) : rp.rect; - for (int l = 0; l < num2; l++) + for (int num7 = 0; num7 < num2; num7++) { - ResolveParams rp5 = rp; - rp5.faction = faction; - rp5.singleThingDef = ThingDefOf.TurretGun; - rp5.rect = rect3; + ResolveParams resolveParams4 = rp; + resolveParams4.faction = faction; + resolveParams4.singleThingDef = ThingDefOf.TurretGun; + resolveParams4.rect = rect3; bool? edgeThingAvoidOtherEdgeThings = rp.edgeThingAvoidOtherEdgeThings; - rp5.edgeThingAvoidOtherEdgeThings = new bool?(!edgeThingAvoidOtherEdgeThings.HasValue || edgeThingAvoidOtherEdgeThings.Value); - BaseGen.symbolStack.Push("edgeThing", rp5); + resolveParams4.edgeThingAvoidOtherEdgeThings = new bool?(!edgeThingAvoidOtherEdgeThings.HasValue || edgeThingAvoidOtherEdgeThings.Value); + BaseGen.symbolStack.Push("edgeThing", resolveParams4); } } } diff --git a/Assembly-CSharp/RimWorld.BaseGen/SymbolResolver_EdgeFloor.cs b/Assembly-CSharp/RimWorld.BaseGen/SymbolResolver_EdgeFloor.cs index d7c59905e..2cabd9c0d 100644 --- a/Assembly-CSharp/RimWorld.BaseGen/SymbolResolver_EdgeFloor.cs +++ b/Assembly-CSharp/RimWorld.BaseGen/SymbolResolver_EdgeFloor.cs @@ -1,4 +1,3 @@ -using System; using Verse; namespace RimWorld.BaseGen diff --git a/Assembly-CSharp/RimWorld.BaseGen/SymbolResolver_EdgeMannedMortar.cs b/Assembly-CSharp/RimWorld.BaseGen/SymbolResolver_EdgeMannedMortar.cs index b61ffb2fc..176a03bab 100644 --- a/Assembly-CSharp/RimWorld.BaseGen/SymbolResolver_EdgeMannedMortar.cs +++ b/Assembly-CSharp/RimWorld.BaseGen/SymbolResolver_EdgeMannedMortar.cs @@ -8,45 +8,36 @@ public class SymbolResolver_EdgeMannedMortar : SymbolResolver { public override bool CanResolve(ResolveParams rp) { - CellRect cellRect; + CellRect cellRect = default(CellRect); return base.CanResolve(rp) && this.TryFindRandomInnerRectTouchingEdge(rp.rect, out cellRect); } public override void Resolve(ResolveParams rp) { - CellRect rect; - if (!this.TryFindRandomInnerRectTouchingEdge(rp.rect, out rect)) + CellRect rect = default(CellRect); + if (this.TryFindRandomInnerRectTouchingEdge(rp.rect, out rect)) { - return; + Rot4 value = (!rect.Cells.Any((Func)((IntVec3 x) => x.x == rp.rect.minX))) ? ((!rect.Cells.Any((Func)((IntVec3 x) => x.x == rp.rect.maxX))) ? ((!rect.Cells.Any((Func)((IntVec3 x) => x.z == rp.rect.minZ))) ? Rot4.North : Rot4.South) : Rot4.East) : Rot4.West; + ResolveParams resolveParams = rp; + resolveParams.rect = rect; + resolveParams.thingRot = new Rot4?(value); + BaseGen.symbolStack.Push("mannedMortar", resolveParams); } - Rot4 value; - if (rect.Cells.Any((IntVec3 x) => x.x == rp.rect.minX)) - { - value = Rot4.West; - } - else if (rect.Cells.Any((IntVec3 x) => x.x == rp.rect.maxX)) - { - value = Rot4.East; - } - else if (rect.Cells.Any((IntVec3 x) => x.z == rp.rect.minZ)) - { - value = Rot4.South; - } - else - { - value = Rot4.North; - } - ResolveParams rp2 = rp; - rp2.rect = rect; - rp2.thingRot = new Rot4?(value); - BaseGen.symbolStack.Push("mannedMortar", rp2); } private bool TryFindRandomInnerRectTouchingEdge(CellRect rect, out CellRect mortarRect) { Map map = BaseGen.globalSettings.map; IntVec2 size = new IntVec2(3, 3); - return rect.TryFindRandomInnerRectTouchingEdge(size, out mortarRect, (CellRect x) => x.Cells.All((IntVec3 y) => y.Standable(map) && y.GetEdifice(map) == null) && GenConstruct.TerrainCanSupport(x, map, ThingDefOf.Turret_MortarBomb)) || rect.TryFindRandomInnerRectTouchingEdge(size, out mortarRect, (CellRect x) => x.Cells.All((IntVec3 y) => y.Standable(map) && y.GetEdifice(map) == null)); + if (rect.TryFindRandomInnerRectTouchingEdge(size, out mortarRect, (Predicate)((CellRect x) => x.Cells.All((Func)((IntVec3 y) => y.Standable(map) && y.GetEdifice(map) == null)) && GenConstruct.TerrainCanSupport(x, map, ThingDefOf.Turret_MortarBomb)))) + { + return true; + } + if (rect.TryFindRandomInnerRectTouchingEdge(size, out mortarRect, (Predicate)((CellRect x) => x.Cells.All((Func)((IntVec3 y) => y.Standable(map) && y.GetEdifice(map) == null))))) + { + return true; + } + return false; } } } diff --git a/Assembly-CSharp/RimWorld.BaseGen/SymbolResolver_EdgeSandbags.cs b/Assembly-CSharp/RimWorld.BaseGen/SymbolResolver_EdgeSandbags.cs index b3845d339..0c31dc0f6 100644 --- a/Assembly-CSharp/RimWorld.BaseGen/SymbolResolver_EdgeSandbags.cs +++ b/Assembly-CSharp/RimWorld.BaseGen/SymbolResolver_EdgeSandbags.cs @@ -15,7 +15,11 @@ public override void Resolve(ResolveParams rp) int num = 0; int num2 = 0; int num3 = -1; - if (rp.rect.EdgeCellsCount < (SymbolResolver_EdgeSandbags.LineLengthRange.max + SymbolResolver_EdgeSandbags.GapLengthRange.max) * 2) + int edgeCellsCount = rp.rect.EdgeCellsCount; + IntRange lineLengthRange = SymbolResolver_EdgeSandbags.LineLengthRange; + int max = lineLengthRange.max; + IntRange gapLengthRange = SymbolResolver_EdgeSandbags.GapLengthRange; + if (edgeCellsCount < (max + gapLengthRange.max) * 2) { num = rp.rect.EdgeCellsCount; } @@ -27,7 +31,7 @@ public override void Resolve(ResolveParams rp) { num2 = SymbolResolver_EdgeSandbags.GapLengthRange.RandomInRange; } - foreach (IntVec3 current in rp.rect.EdgeCells) + foreach (IntVec3 edgeCell in rp.rect.EdgeCells) { num3++; if (num2 > 0) @@ -45,22 +49,19 @@ public override void Resolve(ResolveParams rp) } } } - else if (current.Standable(map) && !current.Roofed(map)) + else if (edgeCell.Standable(map) && !edgeCell.Roofed(map) && !GenSpawn.WouldWipeAnythingWith(edgeCell, Rot4.North, ThingDefOf.Sandbags, map, (Predicate)((Thing x) => x.def.category == ThingCategory.Building || x.def.category == ThingCategory.Item))) { - if (!GenSpawn.WouldWipeAnythingWith(current, Rot4.North, ThingDefOf.Sandbags, map, (Thing x) => x.def.category == ThingCategory.Building || x.def.category == ThingCategory.Item)) + if (num > 0) { - if (num > 0) + num--; + if (num == 0) { - num--; - if (num == 0) - { - num2 = SymbolResolver_EdgeSandbags.GapLengthRange.RandomInRange; - } + num2 = SymbolResolver_EdgeSandbags.GapLengthRange.RandomInRange; } - Thing thing = ThingMaker.MakeThing(ThingDefOf.Sandbags, null); - thing.SetFaction(rp.faction, null); - GenSpawn.Spawn(thing, current, map); } + Thing thing = ThingMaker.MakeThing(ThingDefOf.Sandbags, null); + thing.SetFaction(rp.faction, null); + GenSpawn.Spawn(thing, edgeCell, map); } } } diff --git a/Assembly-CSharp/RimWorld.BaseGen/SymbolResolver_EdgeStreet.cs b/Assembly-CSharp/RimWorld.BaseGen/SymbolResolver_EdgeStreet.cs index dc61158b7..2400da2a9 100644 --- a/Assembly-CSharp/RimWorld.BaseGen/SymbolResolver_EdgeStreet.cs +++ b/Assembly-CSharp/RimWorld.BaseGen/SymbolResolver_EdgeStreet.cs @@ -1,4 +1,3 @@ -using System; using Verse; namespace RimWorld.BaseGen diff --git a/Assembly-CSharp/RimWorld.BaseGen/SymbolResolver_EdgeThing.cs b/Assembly-CSharp/RimWorld.BaseGen/SymbolResolver_EdgeThing.cs index 2e6c9a407..1a21f14d4 100644 --- a/Assembly-CSharp/RimWorld.BaseGen/SymbolResolver_EdgeThing.cs +++ b/Assembly-CSharp/RimWorld.BaseGen/SymbolResolver_EdgeThing.cs @@ -28,9 +28,9 @@ public override bool CanResolve(ResolveParams rp) { bool? edgeThingAvoidOtherEdgeThings = rp.edgeThingAvoidOtherEdgeThings; bool avoidOtherEdgeThings = edgeThingAvoidOtherEdgeThings.HasValue && edgeThingAvoidOtherEdgeThings.Value; + IntVec3 intVec = default(IntVec3); if (rp.thingRot.HasValue) { - IntVec3 intVec; if (!this.TryFindSpawnCell(rp.rect, rp.singleThingDef, rp.thingRot.Value, avoidOtherEdgeThings, out intVec)) { return false; @@ -38,7 +38,6 @@ public override bool CanResolve(ResolveParams rp) } else if (!rp.singleThingDef.rotatable) { - IntVec3 intVec; if (!this.TryFindSpawnCell(rp.rect, rp.singleThingDef, Rot4.North, avoidOtherEdgeThings, out intVec)) { return false; @@ -47,14 +46,16 @@ public override bool CanResolve(ResolveParams rp) else { bool flag = false; - for (int i = 0; i < 4; i++) + int num = 0; + while (num < 4) { - IntVec3 intVec; - if (this.TryFindSpawnCell(rp.rect, rp.singleThingDef, new Rot4(i), avoidOtherEdgeThings, out intVec)) + if (!this.TryFindSpawnCell(rp.rect, rp.singleThingDef, new Rot4(num), avoidOtherEdgeThings, out intVec)) { - flag = true; - break; + num++; + continue; } + flag = true; + break; } if (!flag) { @@ -67,52 +68,64 @@ public override bool CanResolve(ResolveParams rp) public override void Resolve(ResolveParams rp) { - ThingDef thingDef = rp.singleThingDef ?? (from x in DefDatabase.AllDefsListForReading - where (x.IsWeapon || x.IsMedicine || x.IsDrug) && x.graphicData != null && !x.destroyOnDrop && x.size.x <= rp.rect.Width && x.size.z <= rp.rect.Width && x.size.x <= rp.rect.Height && x.size.z <= rp.rect.Height - select x).RandomElement(); + ThingDef thingDef = rp.singleThingDef ?? DefDatabase.AllDefsListForReading.Where((Func)delegate(ThingDef x) + { + int result; + if ((x.IsWeapon || x.IsMedicine || x.IsDrug) && x.graphicData != null && !x.destroyOnDrop && x.size.x <= rp.rect.Width && x.size.z <= rp.rect.Width && x.size.x <= rp.rect.Height) + { + result = ((x.size.z <= rp.rect.Height) ? 1 : 0); + goto IL_00ba; + } + result = 0; + goto IL_00ba; + IL_00ba: + return (byte)result != 0; + }).RandomElement(); IntVec3 invalid = IntVec3.Invalid; Rot4 value = Rot4.North; bool? edgeThingAvoidOtherEdgeThings = rp.edgeThingAvoidOtherEdgeThings; bool avoidOtherEdgeThings = edgeThingAvoidOtherEdgeThings.HasValue && edgeThingAvoidOtherEdgeThings.Value; if (rp.thingRot.HasValue) { - if (!this.TryFindSpawnCell(rp.rect, thingDef, rp.thingRot.Value, avoidOtherEdgeThings, out invalid)) + if (this.TryFindSpawnCell(rp.rect, thingDef, rp.thingRot.Value, avoidOtherEdgeThings, out invalid)) { - return; + value = rp.thingRot.Value; + goto IL_0183; } - value = rp.thingRot.Value; + return; } - else if (!thingDef.rotatable) + if (!thingDef.rotatable) { - if (!this.TryFindSpawnCell(rp.rect, thingDef, Rot4.North, avoidOtherEdgeThings, out invalid)) + if (this.TryFindSpawnCell(rp.rect, thingDef, Rot4.North, avoidOtherEdgeThings, out invalid)) { - return; + value = Rot4.North; + goto IL_0183; } - value = Rot4.North; + return; } - else + this.randomRotations.Shuffle(); + bool flag = false; + int num = 0; + while (num < this.randomRotations.Count) { - this.randomRotations.Shuffle(); - bool flag = false; - for (int i = 0; i < this.randomRotations.Count; i++) + if (!this.TryFindSpawnCell(rp.rect, thingDef, new Rot4(this.randomRotations[num]), avoidOtherEdgeThings, out invalid)) { - if (this.TryFindSpawnCell(rp.rect, thingDef, new Rot4(this.randomRotations[i]), avoidOtherEdgeThings, out invalid)) - { - value = new Rot4(this.randomRotations[i]); - flag = true; - break; - } - } - if (!flag) - { - return; + num++; + continue; } + value = new Rot4(this.randomRotations[num]); + flag = true; + break; } - ResolveParams rp2 = rp; - rp2.rect = CellRect.SingleCell(invalid); - rp2.thingRot = new Rot4?(value); - rp2.singleThingDef = thingDef; - BaseGen.symbolStack.Push("thing", rp2); + if (!flag) + return; + goto IL_0183; + IL_0183: + ResolveParams resolveParams = rp; + resolveParams.rect = CellRect.SingleCell(invalid); + resolveParams.thingRot = new Rot4?(value); + resolveParams.singleThingDef = thingDef; + BaseGen.symbolStack.Push("thing", resolveParams); } private bool TryFindSpawnCell(CellRect rect, ThingDef thingDef, Rot4 rot, bool avoidOtherEdgeThings, out IntVec3 spawnCell) @@ -123,7 +136,7 @@ private bool TryFindSpawnCell(CellRect rect, ThingDef thingDef, Rot4 rot, bool a int num = -1; for (int i = 0; i < this.MaxTriesToAvoidOtherEdgeThings; i++) { - IntVec3 intVec; + IntVec3 intVec = default(IntVec3); if (this.TryFindSpawnCell(rect, thingDef, rot, out intVec)) { int distanceSquaredToExistingEdgeThing = this.GetDistanceSquaredToExistingEdgeThing(intVec, rect, thingDef); @@ -132,9 +145,7 @@ private bool TryFindSpawnCell(CellRect rect, ThingDef thingDef, Rot4 rot, bool a spawnCell = intVec; num = distanceSquaredToExistingEdgeThing; if (num == 2147483647) - { break; - } } } } @@ -150,27 +161,14 @@ private bool TryFindSpawnCell(CellRect rect, ThingDef thingDef, Rot4 rot, out In IntVec2 size = thingDef.size; GenAdj.AdjustForRotation(ref zero, ref size, rot); CellRect empty = CellRect.Empty; - Predicate basePredicate = delegate(CellRect x) - { - int arg_83_0; - if (x.Cells.All((IntVec3 y) => y.Standable(map))) - { - if (!GenSpawn.WouldWipeAnythingWith(x, thingDef, map, (Thing z) => z.def.category == ThingCategory.Building)) - { - arg_83_0 = ((thingDef.category != ThingCategory.Item || x.CenterCell.GetFirstItem(map) == null) ? 1 : 0); - return arg_83_0 != 0; - } - } - arg_83_0 = 0; - return arg_83_0 != 0; - }; + Predicate basePredicate = (Predicate)((CellRect x) => x.Cells.All((Func)((IntVec3 y) => y.Standable(map))) && !GenSpawn.WouldWipeAnythingWith(x, thingDef, map, (Predicate)((Thing z) => z.def.category == ThingCategory.Building)) && (thingDef.category != ThingCategory.Item || x.CenterCell.GetFirstItem(map) == null)); bool flag = false; if (thingDef.category == ThingCategory.Building) { - flag = rect.TryFindRandomInnerRectTouchingEdge(size, out empty, (CellRect x) => basePredicate(x) && !BaseGenUtility.AnyDoorCardinalAdjacentTo(x, map) && GenConstruct.TerrainCanSupport(x, map, thingDef)); + flag = rect.TryFindRandomInnerRectTouchingEdge(size, out empty, (Predicate)((CellRect x) => basePredicate(x) && !BaseGenUtility.AnyDoorCardinalAdjacentTo(x, map) && GenConstruct.TerrainCanSupport(x, map, thingDef))); if (!flag) { - flag = rect.TryFindRandomInnerRectTouchingEdge(size, out empty, (CellRect x) => basePredicate(x) && !BaseGenUtility.AnyDoorCardinalAdjacentTo(x, map)); + flag = rect.TryFindRandomInnerRectTouchingEdge(size, out empty, (Predicate)((CellRect x) => basePredicate(x) && !BaseGenUtility.AnyDoorCardinalAdjacentTo(x, map))); } } if (!flag && !rect.TryFindRandomInnerRectTouchingEdge(size, out empty, basePredicate)) @@ -197,21 +195,24 @@ private int GetDistanceSquaredToExistingEdgeThing(IntVec3 cell, CellRect rect, T { Map map = BaseGen.globalSettings.map; int num = 2147483647; - foreach (IntVec3 current in rect.EdgeCells) + foreach (IntVec3 edgeCell in rect.EdgeCells) { - List thingList = current.GetThingList(map); + List thingList = edgeCell.GetThingList(map); bool flag = false; - for (int i = 0; i < thingList.Count; i++) + int num2 = 0; + while (num2 < thingList.Count) { - if (thingList[i].def == thingDef) + if (thingList[num2].def != thingDef) { - flag = true; - break; + num2++; + continue; } + flag = true; + break; } if (flag) { - num = Mathf.Min(num, cell.DistanceToSquared(current)); + num = Mathf.Min(num, cell.DistanceToSquared(edgeCell)); } } return num; diff --git a/Assembly-CSharp/RimWorld.BaseGen/SymbolResolver_EdgeWalls.cs b/Assembly-CSharp/RimWorld.BaseGen/SymbolResolver_EdgeWalls.cs index b29514255..c164ac27e 100644 --- a/Assembly-CSharp/RimWorld.BaseGen/SymbolResolver_EdgeWalls.cs +++ b/Assembly-CSharp/RimWorld.BaseGen/SymbolResolver_EdgeWalls.cs @@ -1,4 +1,3 @@ -using System; using System.Collections.Generic; using Verse; @@ -9,9 +8,9 @@ public class SymbolResolver_EdgeWalls : SymbolResolver public override void Resolve(ResolveParams rp) { ThingDef wallStuff = rp.wallStuff ?? BaseGenUtility.RandomCheapWallStuff(rp.faction, false); - foreach (IntVec3 current in rp.rect.EdgeCells) + foreach (IntVec3 edgeCell in rp.rect.EdgeCells) { - this.TrySpawnWall(current, rp, wallStuff); + this.TrySpawnWall(edgeCell, rp, wallStuff); } } @@ -30,9 +29,9 @@ private Thing TrySpawnWall(IntVec3 c, ResolveParams rp, ThingDef wallStuff) return null; } } - for (int j = thingList.Count - 1; j >= 0; j--) + for (int num = thingList.Count - 1; num >= 0; num--) { - thingList[j].Destroy(DestroyMode.Vanish); + thingList[num].Destroy(DestroyMode.Vanish); } if (rp.chanceToSkipWallBlock.HasValue && Rand.Chance(rp.chanceToSkipWallBlock.Value)) { diff --git a/Assembly-CSharp/RimWorld.BaseGen/SymbolResolver_EmptyRoom.cs b/Assembly-CSharp/RimWorld.BaseGen/SymbolResolver_EmptyRoom.cs index fd661ad7d..146597ca9 100644 --- a/Assembly-CSharp/RimWorld.BaseGen/SymbolResolver_EmptyRoom.cs +++ b/Assembly-CSharp/RimWorld.BaseGen/SymbolResolver_EmptyRoom.cs @@ -1,4 +1,3 @@ -using System; using Verse; namespace RimWorld.BaseGen diff --git a/Assembly-CSharp/RimWorld.BaseGen/SymbolResolver_EnsureCanReachMapEdge.cs b/Assembly-CSharp/RimWorld.BaseGen/SymbolResolver_EnsureCanReachMapEdge.cs index ad2269468..cdf572e2c 100644 --- a/Assembly-CSharp/RimWorld.BaseGen/SymbolResolver_EnsureCanReachMapEdge.cs +++ b/Assembly-CSharp/RimWorld.BaseGen/SymbolResolver_EnsureCanReachMapEdge.cs @@ -21,7 +21,7 @@ public override void Resolve(ResolveParams rp) SymbolResolver_EnsureCanReachMapEdge.cellsInRandomOrder.Add(iterator.Current); iterator.MoveNext(); } - SymbolResolver_EnsureCanReachMapEdge.cellsInRandomOrder.Shuffle(); + SymbolResolver_EnsureCanReachMapEdge.cellsInRandomOrder.Shuffle(); this.TryMakeAllCellsReachable(false, rp); this.TryMakeAllCellsReachable(true, rp); } @@ -44,13 +44,9 @@ private void TryMakeAllCellsReachable(bool canPathThroughNonStandable, ResolvePa { bool found = false; IntVec3 foundDest = IntVec3.Invalid; - map.floodFiller.FloodFill(intVec, (IntVec3 x) => !found && this.CanTraverse(x, canPathThroughNonStandable), delegate(IntVec3 x) + map.floodFiller.FloodFill(intVec, (Predicate)((IntVec3 x) => !found && this.CanTraverse(x, canPathThroughNonStandable)), (Action)delegate(IntVec3 x) { - if (found) - { - return; - } - if (map.reachability.CanReachMapEdge(x, traverseParms)) + if (!found && map.reachability.CanReachMapEdge(x, traverseParms)) { found = true; foundDest = x; @@ -96,24 +92,14 @@ private void ReconstructPathAndDestroyWalls(IntVec3 foundDest, Room room, Resolv } if (intVec.IsValid) { - ThingDef arg_12F_0; - if ((arg_12F_0 = thingDef) == null) - { - arg_12F_0 = (rp.wallStuff ?? BaseGenUtility.RandomCheapWallStuff(rp.faction, false)); - } - ThingDef stuff = arg_12F_0; + ThingDef stuff = thingDef ?? rp.wallStuff ?? BaseGenUtility.RandomCheapWallStuff(rp.faction, false); Thing thing = ThingMaker.MakeThing(ThingDefOf.Door, stuff); thing.SetFaction(rp.faction, null); GenSpawn.Spawn(thing, intVec, map); } if (intVec2.IsValid && intVec2 != intVec && !intVec2.AdjacentToCardinal(intVec)) { - ThingDef arg_1A1_0; - if ((arg_1A1_0 = thingDef2) == null) - { - arg_1A1_0 = (rp.wallStuff ?? BaseGenUtility.RandomCheapWallStuff(rp.faction, false)); - } - ThingDef stuff2 = arg_1A1_0; + ThingDef stuff2 = thingDef2 ?? rp.wallStuff ?? BaseGenUtility.RandomCheapWallStuff(rp.faction, false); Thing thing2 = ThingMaker.MakeThing(ThingDefOf.Door, stuff2); thing2.SetFaction(rp.faction, null); GenSpawn.Spawn(thing2, intVec2, map); @@ -124,7 +110,19 @@ private bool CanTraverse(IntVec3 c, bool canPathThroughNonStandable) { Map map = BaseGen.globalSettings.map; Building edifice = c.GetEdifice(map); - return this.IsWallOrRock(edifice) || ((canPathThroughNonStandable || c.Standable(map)) && !c.Impassable(map)); + if (this.IsWallOrRock(edifice)) + { + return true; + } + if (!canPathThroughNonStandable && !c.Standable(map)) + { + return false; + } + if (!c.Impassable(map)) + { + return true; + } + return false; } private bool IsWallOrRock(Building b) diff --git a/Assembly-CSharp/RimWorld.BaseGen/SymbolResolver_ExtraDoor.cs b/Assembly-CSharp/RimWorld.BaseGen/SymbolResolver_ExtraDoor.cs index e5d239209..257eb8c1a 100644 --- a/Assembly-CSharp/RimWorld.BaseGen/SymbolResolver_ExtraDoor.cs +++ b/Assembly-CSharp/RimWorld.BaseGen/SymbolResolver_ExtraDoor.cs @@ -17,7 +17,7 @@ public override void Resolve(ResolveParams rp) { for (int j = 0; j < 2; j++) { - IntVec3 intVec; + IntVec3 intVec = default(IntVec3); if (this.TryFindRandomDoorSpawnCell(rp.rect, new Rot4(i), out intVec)) { int distanceToExistingDoors = this.GetDistanceToExistingDoors(intVec, rp.rect); @@ -26,9 +26,7 @@ public override void Resolve(ResolveParams rp) loc = intVec; num = distanceToExistingDoors; if (num == 2147483647) - { break; - } } } } @@ -45,9 +43,9 @@ public override void Resolve(ResolveParams rp) private bool WallHasDoor(CellRect rect, Rot4 dir) { Map map = BaseGen.globalSettings.map; - foreach (IntVec3 current in rect.GetEdgeCells(dir)) + foreach (IntVec3 edgeCell in rect.GetEdgeCells(dir)) { - if (current.GetDoor(map) != null) + if (edgeCell.GetDoor(map) != null) { return true; } @@ -65,12 +63,12 @@ private bool TryFindRandomDoorSpawnCell(CellRect rect, Rot4 dir, out IntVec3 fou found = IntVec3.Invalid; return false; } - int newX; - if (!Rand.TryRangeInclusiveWhere(rect.minX + 1, rect.maxX - 1, delegate(int x) + int newX = default(int); + if (!Rand.TryRangeInclusiveWhere(rect.minX + 1, rect.maxX - 1, (Predicate)delegate(int x) { - IntVec3 c = new IntVec3(x, 0, rect.maxZ + 1); - IntVec3 c2 = new IntVec3(x, 0, rect.maxZ - 1); - return c.InBounds(map) && c.Standable(map) && c2.InBounds(map) && c2.Standable(map); + IntVec3 c7 = new IntVec3(x, 0, rect.maxZ + 1); + IntVec3 c8 = new IntVec3(x, 0, rect.maxZ - 1); + return c7.InBounds(map) && c7.Standable(map) && c8.InBounds(map) && c8.Standable(map); }, out newX)) { found = IntVec3.Invalid; @@ -79,19 +77,19 @@ private bool TryFindRandomDoorSpawnCell(CellRect rect, Rot4 dir, out IntVec3 fou found = new IntVec3(newX, 0, rect.maxZ); return true; } - else if (dir == Rot4.South) + if (dir == Rot4.South) { if (rect.Width <= 2) { found = IntVec3.Invalid; return false; } - int newX2; - if (!Rand.TryRangeInclusiveWhere(rect.minX + 1, rect.maxX - 1, delegate(int x) + int newX2 = default(int); + if (!Rand.TryRangeInclusiveWhere(rect.minX + 1, rect.maxX - 1, (Predicate)delegate(int x) { - IntVec3 c = new IntVec3(x, 0, rect.minZ - 1); - IntVec3 c2 = new IntVec3(x, 0, rect.minZ + 1); - return c.InBounds(map) && c.Standable(map) && c2.InBounds(map) && c2.Standable(map); + IntVec3 c5 = new IntVec3(x, 0, rect.minZ - 1); + IntVec3 c6 = new IntVec3(x, 0, rect.minZ + 1); + return c5.InBounds(map) && c5.Standable(map) && c6.InBounds(map) && c6.Standable(map); }, out newX2)) { found = IntVec3.Invalid; @@ -100,19 +98,19 @@ private bool TryFindRandomDoorSpawnCell(CellRect rect, Rot4 dir, out IntVec3 fou found = new IntVec3(newX2, 0, rect.minZ); return true; } - else if (dir == Rot4.West) + if (dir == Rot4.West) { if (rect.Height <= 2) { found = IntVec3.Invalid; return false; } - int newZ; - if (!Rand.TryRangeInclusiveWhere(rect.minZ + 1, rect.maxZ - 1, delegate(int z) + int newZ = default(int); + if (!Rand.TryRangeInclusiveWhere(rect.minZ + 1, rect.maxZ - 1, (Predicate)delegate(int z) { - IntVec3 c = new IntVec3(rect.minX - 1, 0, z); - IntVec3 c2 = new IntVec3(rect.minX + 1, 0, z); - return c.InBounds(map) && c.Standable(map) && c2.InBounds(map) && c2.Standable(map); + IntVec3 c3 = new IntVec3(rect.minX - 1, 0, z); + IntVec3 c4 = new IntVec3(rect.minX + 1, 0, z); + return c3.InBounds(map) && c3.Standable(map) && c4.InBounds(map) && c4.Standable(map); }, out newZ)) { found = IntVec3.Invalid; @@ -121,35 +119,33 @@ private bool TryFindRandomDoorSpawnCell(CellRect rect, Rot4 dir, out IntVec3 fou found = new IntVec3(rect.minX, 0, newZ); return true; } - else + if (rect.Height <= 2) { - if (rect.Height <= 2) - { - found = IntVec3.Invalid; - return false; - } - int newZ2; - if (!Rand.TryRangeInclusiveWhere(rect.minZ + 1, rect.maxZ - 1, delegate(int z) - { - IntVec3 c = new IntVec3(rect.maxX + 1, 0, z); - IntVec3 c2 = new IntVec3(rect.maxX - 1, 0, z); - return c.InBounds(map) && c.Standable(map) && c2.InBounds(map) && c2.Standable(map); - }, out newZ2)) - { - found = IntVec3.Invalid; - return false; - } - found = new IntVec3(rect.maxX, 0, newZ2); - return true; + found = IntVec3.Invalid; + return false; + } + int newZ2 = default(int); + if (!Rand.TryRangeInclusiveWhere(rect.minZ + 1, rect.maxZ - 1, (Predicate)delegate(int z) + { + IntVec3 c = new IntVec3(rect.maxX + 1, 0, z); + IntVec3 c2 = new IntVec3(rect.maxX - 1, 0, z); + return c.InBounds(map) && c.Standable(map) && c2.InBounds(map) && c2.Standable(map); + }, out newZ2)) + { + found = IntVec3.Invalid; + return false; } + found = new IntVec3(rect.maxX, 0, newZ2); + return true; } private int GetDistanceToExistingDoors(IntVec3 cell, CellRect rect) { Map map = BaseGen.globalSettings.map; int num = 2147483647; - foreach (IntVec3 current in rect.EdgeCells) + foreach (IntVec3 edgeCell in rect.EdgeCells) { + IntVec3 current = edgeCell; if (current.GetDoor(map) != null) { num = Mathf.Min(num, Mathf.Abs(cell.x - current.x) + Mathf.Abs(cell.z - current.z)); diff --git a/Assembly-CSharp/RimWorld.BaseGen/SymbolResolver_FactionBase.cs b/Assembly-CSharp/RimWorld.BaseGen/SymbolResolver_FactionBase.cs index 5d3d07205..47d1af4cd 100644 --- a/Assembly-CSharp/RimWorld.BaseGen/SymbolResolver_FactionBase.cs +++ b/Assembly-CSharp/RimWorld.BaseGen/SymbolResolver_FactionBase.cs @@ -12,8 +12,7 @@ public class SymbolResolver_FactionBase : SymbolResolver public override void Resolve(ResolveParams rp) { - SymbolResolver_FactionBase.c__AnonStorey300 c__AnonStorey = new SymbolResolver_FactionBase.c__AnonStorey300(); - c__AnonStorey.map = BaseGen.globalSettings.map; + Map map = BaseGen.globalSettings.map; Faction faction = rp.faction ?? Find.FactionManager.RandomEnemyFaction(false, false, true); int num = 0; int? edgeDefenseWidth = rp.edgeDefenseWidth; @@ -21,20 +20,21 @@ public override void Resolve(ResolveParams rp) { num = rp.edgeDefenseWidth.Value; } - else if (rp.rect.Width >= 20 && rp.rect.Height >= 20 && (faction.def.techLevel >= TechLevel.Industrial || Rand.Bool)) + else if (rp.rect.Width >= 20 && rp.rect.Height >= 20 && ((int)faction.def.techLevel >= 4 || Rand.Bool)) { num = ((!Rand.Bool) ? 4 : 2); } - float num2 = (float)rp.rect.Area / 144f * 0.17f; - BaseGen.globalSettings.minEmptyNodes = ((num2 >= 1f) ? GenMath.RoundRandom(num2) : 0); - Lord singlePawnLord = rp.singlePawnLord ?? LordMaker.MakeNewLord(faction, new LordJob_DefendBase(faction, rp.rect.CenterCell), c__AnonStorey.map, null); + float num2 = (float)((float)rp.rect.Area / 144.0 * 0.17000000178813934); + BaseGen.globalSettings.minEmptyNodes = ((!(num2 < 1.0)) ? GenMath.RoundRandom(num2) : 0); + Lord singlePawnLord = rp.singlePawnLord ?? LordMaker.MakeNewLord(faction, new LordJob_DefendBase(faction, rp.rect.CenterCell), map, null); TraverseParms traverseParms = TraverseParms.For(TraverseMode.PassDoors, Danger.Deadly, false); ResolveParams resolveParams = rp; resolveParams.rect = rp.rect; resolveParams.faction = faction; resolveParams.singlePawnLord = singlePawnLord; resolveParams.pawnGroupKindDef = (rp.pawnGroupKindDef ?? PawnGroupKindDefOf.FactionBase); - resolveParams.singlePawnSpawnCellExtraPredicate = (rp.singlePawnSpawnCellExtraPredicate ?? ((IntVec3 x) => c__AnonStorey.map.reachability.CanReachMapEdge(x, traverseParms))); + object obj = rp.singlePawnSpawnCellExtraPredicate; + obj = (resolveParams.singlePawnSpawnCellExtraPredicate = (Predicate)((IntVec3 x) => map.reachability.CanReachMapEdge(x, traverseParms))); if (resolveParams.pawnGroupMakerParams == null) { float num3 = (!faction.def.techLevel.IsNeolithicOrWorse()) ? SymbolResolver_FactionBase.NonNeolithicPawnsPoints.RandomInRange : SymbolResolver_FactionBase.NeolithicPawnsPoints.RandomInRange; @@ -44,16 +44,16 @@ public override void Resolve(ResolveParams rp) num3 *= rp.factionBasePawnGroupPointsFactor.Value; } resolveParams.pawnGroupMakerParams = new PawnGroupMakerParms(); - resolveParams.pawnGroupMakerParams.tile = c__AnonStorey.map.Tile; + resolveParams.pawnGroupMakerParams.tile = map.Tile; resolveParams.pawnGroupMakerParams.faction = faction; resolveParams.pawnGroupMakerParams.points = num3; resolveParams.pawnGroupMakerParams.inhabitants = true; } BaseGen.symbolStack.Push("pawnGroup", resolveParams); - if (faction.def.techLevel >= TechLevel.Industrial) + if ((int)faction.def.techLevel >= 4) { - int num4 = (!Rand.Chance(0.75f)) ? 0 : GenMath.RoundRandom((float)rp.rect.Area / 400f); - for (int i = 0; i < num4; i++) + int num4 = Rand.Chance(0.75f) ? GenMath.RoundRandom((float)((float)rp.rect.Area / 400.0)) : 0; + for (int num5 = 0; num5 < num4; num5++) { ResolveParams resolveParams2 = rp; resolveParams2.faction = faction; diff --git a/Assembly-CSharp/RimWorld.BaseGen/SymbolResolver_Farm.cs b/Assembly-CSharp/RimWorld.BaseGen/SymbolResolver_Farm.cs index ab92dc14b..a7ee3d4c7 100644 --- a/Assembly-CSharp/RimWorld.BaseGen/SymbolResolver_Farm.cs +++ b/Assembly-CSharp/RimWorld.BaseGen/SymbolResolver_Farm.cs @@ -1,4 +1,3 @@ -using System; using UnityEngine; using Verse; @@ -14,13 +13,12 @@ public override bool CanResolve(ResolveParams rp) public override void Resolve(ResolveParams rp) { ThingDef thingDef = rp.cultivatedPlantDef ?? SymbolResolver_CultivatedPlants.DeterminePlantDef(rp.rect); - bool flag = rp.rect.Width >= 7 && rp.rect.Height >= 7 && (rp.rect.Width > 12 || rp.rect.Height > 12 || Rand.Bool) && thingDef.plant.Harvestable; - if (flag) + if (rp.rect.Width >= 7 && rp.rect.Height >= 7 && (rp.rect.Width > 12 || rp.rect.Height > 12 || Rand.Bool) && thingDef.plant.Harvestable) { CellRect rect = new CellRect(rp.rect.maxX - 3, rp.rect.maxZ - 3, 4, 4); ThingDef harvestedThingDef = thingDef.plant.harvestedThingDef; int num = Rand.RangeInclusive(2, 3); - for (int i = 0; i < num; i++) + for (int num2 = 0; num2 < num; num2++) { ResolveParams resolveParams = rp; resolveParams.rect = rect.ContractedBy(1); diff --git a/Assembly-CSharp/RimWorld.BaseGen/SymbolResolver_FillWithBeds.cs b/Assembly-CSharp/RimWorld.BaseGen/SymbolResolver_FillWithBeds.cs index 3d2c784ee..1371ff18c 100644 --- a/Assembly-CSharp/RimWorld.BaseGen/SymbolResolver_FillWithBeds.cs +++ b/Assembly-CSharp/RimWorld.BaseGen/SymbolResolver_FillWithBeds.cs @@ -10,33 +10,29 @@ public override void Resolve(ResolveParams rp) Map map = BaseGen.globalSettings.map; bool @bool = Rand.Bool; ThingDef thingDef = rp.singleThingDef ?? ((!Rand.Bool) ? ThingDefOf.SleepingSpot : ThingDefOf.Bed); - foreach (IntVec3 current in rp.rect) + foreach (IntVec3 item in rp.rect) { + IntVec3 current = item; if (@bool) { - if (current.x % 3 != 0 || current.z % 2 != 0) - { - continue; - } - } - else if (current.x % 2 != 0 || current.z % 3 != 0) - { - continue; + if (current.x % 3 == 0 && current.z % 2 == 0) + goto IL_00a1; } + else if (current.x % 2 == 0 && current.z % 3 == 0) + goto IL_00a1; + continue; + IL_00a1: Rot4 rot = (!@bool) ? Rot4.North : Rot4.West; - if (!GenSpawn.WouldWipeAnythingWith(current, rot, thingDef, map, (Thing x) => x.def.category == ThingCategory.Building)) + if (!GenSpawn.WouldWipeAnythingWith(current, rot, thingDef, map, (Predicate)((Thing x) => x.def.category == ThingCategory.Building)) && !BaseGenUtility.AnyDoorCardinalAdjacentTo(GenAdj.OccupiedRect(current, rot, thingDef.Size), map)) { - if (!BaseGenUtility.AnyDoorCardinalAdjacentTo(GenAdj.OccupiedRect(current, rot, thingDef.Size), map)) + ThingDef stuff = null; + if (thingDef.MadeFromStuff) { - ThingDef stuff = null; - if (thingDef.MadeFromStuff) - { - stuff = ThingDefOf.WoodLog; - } - Thing thing = ThingMaker.MakeThing(thingDef, stuff); - thing.SetFaction(rp.faction, null); - GenSpawn.Spawn(thing, current, map, rot, false); + stuff = ThingDefOf.WoodLog; } + Thing thing = ThingMaker.MakeThing(thingDef, stuff); + thing.SetFaction(rp.faction, null); + GenSpawn.Spawn(thing, current, map, rot, false); } } } diff --git a/Assembly-CSharp/RimWorld.BaseGen/SymbolResolver_FillWithThings.cs b/Assembly-CSharp/RimWorld.BaseGen/SymbolResolver_FillWithThings.cs index 117bc574a..0ebf15dbb 100644 --- a/Assembly-CSharp/RimWorld.BaseGen/SymbolResolver_FillWithThings.cs +++ b/Assembly-CSharp/RimWorld.BaseGen/SymbolResolver_FillWithThings.cs @@ -23,30 +23,28 @@ public override bool CanResolve(ResolveParams rp) IntVec3 zero = IntVec3.Zero; IntVec2 size = rp.singleThingDef.size; GenAdj.AdjustForRotation(ref zero, ref size, rot); - if (rp.rect.Width < size.x || rp.rect.Height < size.z) + if (rp.rect.Width >= size.x && rp.rect.Height >= size.z) { - return false; + goto IL_009d; } + return false; } + goto IL_009d; + IL_009d: return true; } public override void Resolve(ResolveParams rp) { - ThingDef arg_3A_0; - if ((arg_3A_0 = rp.singleThingDef) == null) - { - arg_3A_0 = (from x in ItemCollectionGeneratorUtility.allGeneratableItems - where x.IsWeapon || x.IsMedicine || x.IsDrug - select x).RandomElement(); - } - ThingDef thingDef = arg_3A_0; + ThingDef thingDef = rp.singleThingDef ?? (from x in ItemCollectionGeneratorUtility.allGeneratableItems + where x.IsWeapon || x.IsMedicine || x.IsDrug + select x).RandomElement(); Rot4? thingRot = rp.thingRot; Rot4 rot = (!thingRot.HasValue) ? Rot4.North : thingRot.Value; IntVec3 zero = IntVec3.Zero; IntVec2 size = thingDef.size; int? fillWithThingsPadding = rp.fillWithThingsPadding; - int num = (!fillWithThingsPadding.HasValue) ? 0 : fillWithThingsPadding.Value; + int num = fillWithThingsPadding.HasValue ? fillWithThingsPadding.Value : 0; if (num < 0) { num = 0; @@ -55,20 +53,22 @@ where x.IsWeapon || x.IsMedicine || x.IsDrug if (size.x <= 0 || size.z <= 0) { Log.Error("Thing has 0 size."); - return; } - for (int i = rp.rect.minX; i <= rp.rect.maxX - size.x + 1; i += size.x + num) + else { - for (int j = rp.rect.minZ; j <= rp.rect.maxZ - size.z + 1; j += size.z + num) + for (int num2 = rp.rect.minX; num2 <= rp.rect.maxX - size.x + 1; num2 += size.x + num) { - ResolveParams resolveParams = rp; - resolveParams.rect = new CellRect(i, j, size.x, size.z); - resolveParams.singleThingDef = thingDef; - resolveParams.thingRot = new Rot4?(rot); - BaseGen.symbolStack.Push("thing", resolveParams); + for (int num3 = rp.rect.minZ; num3 <= rp.rect.maxZ - size.z + 1; num3 += size.z + num) + { + ResolveParams resolveParams = rp; + resolveParams.rect = new CellRect(num2, num3, size.x, size.z); + resolveParams.singleThingDef = thingDef; + resolveParams.thingRot = new Rot4?(rot); + BaseGen.symbolStack.Push("thing", resolveParams); + } } + BaseGen.symbolStack.Push("clear", rp); } - BaseGen.symbolStack.Push("clear", rp); } } } diff --git a/Assembly-CSharp/RimWorld.BaseGen/SymbolResolver_FirefoamPopper.cs b/Assembly-CSharp/RimWorld.BaseGen/SymbolResolver_FirefoamPopper.cs index af65000b6..f86be4a98 100644 --- a/Assembly-CSharp/RimWorld.BaseGen/SymbolResolver_FirefoamPopper.cs +++ b/Assembly-CSharp/RimWorld.BaseGen/SymbolResolver_FirefoamPopper.cs @@ -7,38 +7,33 @@ public class SymbolResolver_FirefoamPopper : SymbolResolver { public override bool CanResolve(ResolveParams rp) { - IntVec3 intVec; - return base.CanResolve(rp) && this.TryFindSpawnCell(rp.rect, out intVec); + if (!base.CanResolve(rp)) + { + return false; + } + IntVec3 intVec = default(IntVec3); + if (!this.TryFindSpawnCell(rp.rect, out intVec)) + { + return false; + } + return true; } public override void Resolve(ResolveParams rp) { - IntVec3 loc; - if (!this.TryFindSpawnCell(rp.rect, out loc)) + IntVec3 loc = default(IntVec3); + if (this.TryFindSpawnCell(rp.rect, out loc)) { - return; + Thing thing = ThingMaker.MakeThing(ThingDefOf.FirefoamPopper, null); + thing.SetFaction(rp.faction, null); + GenSpawn.Spawn(thing, loc, BaseGen.globalSettings.map); } - Thing thing = ThingMaker.MakeThing(ThingDefOf.FirefoamPopper, null); - thing.SetFaction(rp.faction, null); - GenSpawn.Spawn(thing, loc, BaseGen.globalSettings.map); } private bool TryFindSpawnCell(CellRect rect, out IntVec3 result) { Map map = BaseGen.globalSettings.map; - return CellFinder.TryFindRandomCellInsideWith(rect, delegate(IntVec3 c) - { - bool arg_6C_0; - if (c.Standable(map) && !BaseGenUtility.AnyDoorCardinalAdjacentTo(c, map) && c.GetFirstItem(map) == null) - { - arg_6C_0 = !GenSpawn.WouldWipeAnythingWith(c, Rot4.North, ThingDefOf.FirefoamPopper, map, (Thing x) => x.def.category == ThingCategory.Building); - } - else - { - arg_6C_0 = false; - } - return arg_6C_0; - }, out result); + return CellFinder.TryFindRandomCellInsideWith(rect, (Predicate)((IntVec3 c) => c.Standable(map) && !BaseGenUtility.AnyDoorCardinalAdjacentTo(c, map) && c.GetFirstItem(map) == null && !GenSpawn.WouldWipeAnythingWith(c, Rot4.North, ThingDefOf.FirefoamPopper, map, (Predicate)((Thing x) => x.def.category == ThingCategory.Building))), out result); } } } diff --git a/Assembly-CSharp/RimWorld.BaseGen/SymbolResolver_FloorFill.cs b/Assembly-CSharp/RimWorld.BaseGen/SymbolResolver_FloorFill.cs index 5c2c24fdd..94f334c9c 100644 --- a/Assembly-CSharp/RimWorld.BaseGen/SymbolResolver_FloorFill.cs +++ b/Assembly-CSharp/RimWorld.BaseGen/SymbolResolver_FloorFill.cs @@ -1,4 +1,3 @@ -using System; using Verse; namespace RimWorld.BaseGen diff --git a/Assembly-CSharp/RimWorld.BaseGen/SymbolResolver_Hives.cs b/Assembly-CSharp/RimWorld.BaseGen/SymbolResolver_Hives.cs index e274489e8..d1714075f 100644 --- a/Assembly-CSharp/RimWorld.BaseGen/SymbolResolver_Hives.cs +++ b/Assembly-CSharp/RimWorld.BaseGen/SymbolResolver_Hives.cs @@ -10,32 +10,39 @@ public class SymbolResolver_Hives : SymbolResolver public override bool CanResolve(ResolveParams rp) { - IntVec3 intVec; - return base.CanResolve(rp) && this.TryFindFirstHivePos(rp.rect, out intVec); - } - - public override void Resolve(ResolveParams rp) - { - IntVec3 loc; - if (!this.TryFindFirstHivePos(rp.rect, out loc)) + if (!base.CanResolve(rp)) { - return; + return false; } - int? hivesCount = rp.hivesCount; - int num = (!hivesCount.HasValue) ? SymbolResolver_Hives.DefaultHivesCountRange.RandomInRange : hivesCount.Value; - Hive hive = (Hive)ThingMaker.MakeThing(ThingDefOf.Hive, null); - hive.SetFaction(Faction.OfInsects, null); - if (rp.disableHives.HasValue && rp.disableHives.Value) + IntVec3 intVec = default(IntVec3); + if (!this.TryFindFirstHivePos(rp.rect, out intVec)) { - hive.active = false; + return false; } - hive = (Hive)GenSpawn.Spawn(hive, loc, BaseGen.globalSettings.map); - for (int i = 0; i < num - 1; i++) + return true; + } + + public override void Resolve(ResolveParams rp) + { + IntVec3 loc = default(IntVec3); + if (this.TryFindFirstHivePos(rp.rect, out loc)) { - Hive hive2; - if (hive.GetComp().TrySpawnChildHive(true, out hive2)) + int? hivesCount = rp.hivesCount; + int num = (!hivesCount.HasValue) ? SymbolResolver_Hives.DefaultHivesCountRange.RandomInRange : hivesCount.Value; + Hive hive = (Hive)ThingMaker.MakeThing(ThingDefOf.Hive, null); + hive.SetFaction(Faction.OfInsects, null); + if (rp.disableHives.HasValue && rp.disableHives.Value) + { + hive.active = false; + } + hive = (Hive)GenSpawn.Spawn(hive, loc, BaseGen.globalSettings.map); + for (int i = 0; i < num - 1; i++) { - hive = hive2; + Hive hive2 = default(Hive); + if (hive.GetComp().TrySpawnChildHive(true, out hive2)) + { + hive = hive2; + } } } } @@ -45,7 +52,7 @@ private bool TryFindFirstHivePos(CellRect rect, out IntVec3 pos) Map map = BaseGen.globalSettings.map; return (from mc in rect.Cells where mc.Standable(map) - select mc).TryRandomElement(out pos); + select mc).TryRandomElement(out pos); } } } diff --git a/Assembly-CSharp/RimWorld.BaseGen/SymbolResolver_IndoorLighting.cs b/Assembly-CSharp/RimWorld.BaseGen/SymbolResolver_IndoorLighting.cs index dc61c7926..623e22afc 100644 --- a/Assembly-CSharp/RimWorld.BaseGen/SymbolResolver_IndoorLighting.cs +++ b/Assembly-CSharp/RimWorld.BaseGen/SymbolResolver_IndoorLighting.cs @@ -1,4 +1,3 @@ -using System; using Verse; namespace RimWorld.BaseGen @@ -10,19 +9,7 @@ public class SymbolResolver_IndoorLighting : SymbolResolver public override void Resolve(ResolveParams rp) { Map map = BaseGen.globalSettings.map; - ThingDef thingDef; - if (rp.faction == null || rp.faction.def.techLevel >= TechLevel.Industrial) - { - thingDef = ThingDefOf.StandingLamp; - } - else if (map.mapTemperature.OutdoorTemp > 18f) - { - thingDef = null; - } - else - { - thingDef = ThingDefOf.TorchLamp; - } + ThingDef thingDef = (rp.faction == null || (int)rp.faction.def.techLevel >= 4) ? ThingDefOf.StandingLamp : ((!(map.mapTemperature.OutdoorTemp > 18.0)) ? ThingDefOf.TorchLamp : null); if (thingDef != null) { ResolveParams resolveParams = rp; diff --git a/Assembly-CSharp/RimWorld.BaseGen/SymbolResolver_Interior_AncientTemple.cs b/Assembly-CSharp/RimWorld.BaseGen/SymbolResolver_Interior_AncientTemple.cs index ed51620e4..e64e18bd6 100644 --- a/Assembly-CSharp/RimWorld.BaseGen/SymbolResolver_Interior_AncientTemple.cs +++ b/Assembly-CSharp/RimWorld.BaseGen/SymbolResolver_Interior_AncientTemple.cs @@ -1,4 +1,3 @@ -using System; using System.Collections.Generic; using Verse; @@ -41,9 +40,9 @@ public override void Resolve(ResolveParams rp) } } int? ancientTempleEntranceHeight = rp.ancientTempleEntranceHeight; - int num = (!ancientTempleEntranceHeight.HasValue) ? 0 : ancientTempleEntranceHeight.Value; + int num = ancientTempleEntranceHeight.HasValue ? ancientTempleEntranceHeight.Value : 0; ResolveParams resolveParams4 = rp; - resolveParams4.rect.minZ = resolveParams4.rect.minZ + num; + resolveParams4.rect.minZ += num; BaseGen.symbolStack.Push("ancientShrinesGroup", resolveParams4); } } diff --git a/Assembly-CSharp/RimWorld.BaseGen/SymbolResolver_Interior_Barracks.cs b/Assembly-CSharp/RimWorld.BaseGen/SymbolResolver_Interior_Barracks.cs index 2ed753ffa..efd02bc8a 100644 --- a/Assembly-CSharp/RimWorld.BaseGen/SymbolResolver_Interior_Barracks.cs +++ b/Assembly-CSharp/RimWorld.BaseGen/SymbolResolver_Interior_Barracks.cs @@ -1,4 +1,3 @@ -using System; using Verse; namespace RimWorld.BaseGen @@ -16,27 +15,27 @@ public class SymbolResolver_Interior_Barracks : SymbolResolver public override void Resolve(ResolveParams rp) { Map map = BaseGen.globalSettings.map; - if (map.mapTemperature.OutdoorTemp > 22f) + if (map.mapTemperature.OutdoorTemp > 22.0) { ResolveParams resolveParams = rp; resolveParams.singleThingDef = ThingDefOf.PassiveCooler; BaseGen.symbolStack.Push("edgeThing", resolveParams); } bool flag = false; - if (map.mapTemperature.OutdoorTemp < 3f) + if (map.mapTemperature.OutdoorTemp < 3.0) { ThingDef singleThingDef; - if (rp.faction == null || rp.faction.def.techLevel >= TechLevel.Industrial) + if (rp.faction == null || (int)rp.faction.def.techLevel >= 4) { singleThingDef = ThingDefOf.Heater; } else { - singleThingDef = ((map.mapTemperature.OutdoorTemp >= -20f) ? ThingDefOf.TorchLamp : ThingDefOf.Campfire); + singleThingDef = ((!(map.mapTemperature.OutdoorTemp < -20.0)) ? ThingDefOf.TorchLamp : ThingDefOf.Campfire); flag = true; } - int num = (map.mapTemperature.OutdoorTemp >= -45f) ? 1 : 2; - for (int i = 0; i < num; i++) + int num = (!(map.mapTemperature.OutdoorTemp < -45.0)) ? 1 : 2; + for (int num2 = 0; num2 < num; num2++) { ResolveParams resolveParams2 = rp; resolveParams2.singleThingDef = singleThingDef; diff --git a/Assembly-CSharp/RimWorld.BaseGen/SymbolResolver_Interior_BatteryRoom.cs b/Assembly-CSharp/RimWorld.BaseGen/SymbolResolver_Interior_BatteryRoom.cs index 0de9042a1..ca8db4b45 100644 --- a/Assembly-CSharp/RimWorld.BaseGen/SymbolResolver_Interior_BatteryRoom.cs +++ b/Assembly-CSharp/RimWorld.BaseGen/SymbolResolver_Interior_BatteryRoom.cs @@ -1,4 +1,3 @@ -using System; using Verse; namespace RimWorld.BaseGen diff --git a/Assembly-CSharp/RimWorld.BaseGen/SymbolResolver_Interior_Brewery.cs b/Assembly-CSharp/RimWorld.BaseGen/SymbolResolver_Interior_Brewery.cs index b9ff52eba..e0b48d7e9 100644 --- a/Assembly-CSharp/RimWorld.BaseGen/SymbolResolver_Interior_Brewery.cs +++ b/Assembly-CSharp/RimWorld.BaseGen/SymbolResolver_Interior_Brewery.cs @@ -1,4 +1,3 @@ -using System; using Verse; namespace RimWorld.BaseGen @@ -24,17 +23,9 @@ public override void Resolve(ResolveParams rp) resolveParams.singleThingDef = ThingDefOf.PassiveCooler; BaseGen.symbolStack.Push("edgeThing", resolveParams); } - if (map.mapTemperature.OutdoorTemp < 7f) + if (map.mapTemperature.OutdoorTemp < 7.0) { - ThingDef singleThingDef; - if (rp.faction == null || rp.faction.def.techLevel >= TechLevel.Industrial) - { - singleThingDef = ThingDefOf.Heater; - } - else - { - singleThingDef = ThingDefOf.Campfire; - } + ThingDef singleThingDef = (rp.faction != null && (int)rp.faction.def.techLevel < 4) ? ThingDefOf.Campfire : ThingDefOf.Heater; ResolveParams resolveParams2 = rp; resolveParams2.singleThingDef = singleThingDef; BaseGen.symbolStack.Push("edgeThing", resolveParams2); diff --git a/Assembly-CSharp/RimWorld.BaseGen/SymbolResolver_Interior_DiningRoom.cs b/Assembly-CSharp/RimWorld.BaseGen/SymbolResolver_Interior_DiningRoom.cs index 648411ec4..409637d0d 100644 --- a/Assembly-CSharp/RimWorld.BaseGen/SymbolResolver_Interior_DiningRoom.cs +++ b/Assembly-CSharp/RimWorld.BaseGen/SymbolResolver_Interior_DiningRoom.cs @@ -1,4 +1,3 @@ -using System; using UnityEngine; using Verse; @@ -11,8 +10,8 @@ public override void Resolve(ResolveParams rp) BaseGen.symbolStack.Push("indoorLighting", rp); BaseGen.symbolStack.Push("randomlyPlaceMealsOnTables", rp); BaseGen.symbolStack.Push("placeChairsNearTables", rp); - int num = Mathf.Max(GenMath.RoundRandom((float)rp.rect.Area / 20f), 1); - for (int i = 0; i < num; i++) + int num = Mathf.Max(GenMath.RoundRandom((float)((float)rp.rect.Area / 20.0)), 1); + for (int num2 = 0; num2 < num; num2++) { ResolveParams resolveParams = rp; resolveParams.singleThingDef = ThingDefOf.TableShort; diff --git a/Assembly-CSharp/RimWorld.BaseGen/SymbolResolver_Interior_Storage.cs b/Assembly-CSharp/RimWorld.BaseGen/SymbolResolver_Interior_Storage.cs index 6d9e8e571..f64a088b1 100644 --- a/Assembly-CSharp/RimWorld.BaseGen/SymbolResolver_Interior_Storage.cs +++ b/Assembly-CSharp/RimWorld.BaseGen/SymbolResolver_Interior_Storage.cs @@ -1,4 +1,3 @@ -using System; using Verse; namespace RimWorld.BaseGen @@ -11,7 +10,7 @@ public override void Resolve(ResolveParams rp) { Map map = BaseGen.globalSettings.map; BaseGen.symbolStack.Push("stockpile", rp); - if (map.mapTemperature.OutdoorTemp > 15f) + if (map.mapTemperature.OutdoorTemp > 15.0) { ResolveParams resolveParams = rp; resolveParams.singleThingDef = ThingDefOf.PassiveCooler; diff --git a/Assembly-CSharp/RimWorld.BaseGen/SymbolResolver_ItemCollection.cs b/Assembly-CSharp/RimWorld.BaseGen/SymbolResolver_ItemCollection.cs index fd707dfe9..c6e03989d 100644 --- a/Assembly-CSharp/RimWorld.BaseGen/SymbolResolver_ItemCollection.cs +++ b/Assembly-CSharp/RimWorld.BaseGen/SymbolResolver_ItemCollection.cs @@ -12,17 +12,11 @@ public override void Resolve(ResolveParams rp) Map map = BaseGen.globalSettings.map; ItemCollectionGeneratorDef itemCollectionGeneratorDef = rp.itemCollectionGeneratorDef ?? ItemCollectionGeneratorDefOf.RandomGeneralGoods; ItemCollectionGeneratorParams? itemCollectionGeneratorParams = rp.itemCollectionGeneratorParams; - ItemCollectionGeneratorParams parms; - if (itemCollectionGeneratorParams.HasValue) + ItemCollectionGeneratorParams parms = (!itemCollectionGeneratorParams.HasValue) ? new ItemCollectionGeneratorParams { - parms = rp.itemCollectionGeneratorParams.Value; - } - else - { - parms = default(ItemCollectionGeneratorParams); - parms.count = rp.rect.Cells.Count((IntVec3 x) => x.Standable(map) && x.GetFirstItem(map) == null); - parms.techLevel = TechLevel.Spacer; - } + count = rp.rect.Cells.Count((Func)((IntVec3 x) => x.Standable(map) && x.GetFirstItem(map) == null)), + techLevel = TechLevel.Spacer + } : rp.itemCollectionGeneratorParams.Value; List list = itemCollectionGeneratorDef.Worker.Generate(parms); for (int i = 0; i < list.Count; i++) { diff --git a/Assembly-CSharp/RimWorld.BaseGen/SymbolResolver_MannedMortar.cs b/Assembly-CSharp/RimWorld.BaseGen/SymbolResolver_MannedMortar.cs index e1cedb39d..075e09c04 100644 --- a/Assembly-CSharp/RimWorld.BaseGen/SymbolResolver_MannedMortar.cs +++ b/Assembly-CSharp/RimWorld.BaseGen/SymbolResolver_MannedMortar.cs @@ -25,7 +25,11 @@ public override bool CanResolve(ResolveParams rp) } iterator.MoveNext(); } - return num >= 2; + if (num < 2) + { + return false; + } + return true; } public override void Resolve(ResolveParams rp) @@ -34,46 +38,40 @@ public override void Resolve(ResolveParams rp) Faction faction = rp.faction ?? Find.FactionManager.RandomEnemyFaction(false, false, true); Rot4? thingRot = rp.thingRot; Rot4 rot = (!thingRot.HasValue) ? Rot4.Random : thingRot.Value; - ThingDef arg_88_0; - if ((arg_88_0 = rp.mortarDef) == null) - { - arg_88_0 = (from x in DefDatabase.AllDefsListForReading - where x.category == ThingCategory.Building && x.building.IsMortar && x != ThingDefOf.Turret_MortarEMP - select x).RandomElement(); - } - ThingDef thingDef = arg_88_0; - IntVec3 intVec; - if (!this.TryFindMortarSpawnCell(rp.rect, rot, thingDef, out intVec)) - { - return; - } - if (thingDef.HasComp(typeof(CompMannable))) + ThingDef thingDef = rp.mortarDef ?? (from x in DefDatabase.AllDefsListForReading + where x.category == ThingCategory.Building && x.building.IsMortar && x != ThingDefOf.Turret_MortarEMP + select x).RandomElement(); + IntVec3 intVec = default(IntVec3); + if (this.TryFindMortarSpawnCell(rp.rect, rot, thingDef, out intVec)) { - IntVec3 c = Thing.InteractionCellWhenAt(thingDef, intVec, rot, map); - Lord singlePawnLord = LordMaker.MakeNewLord(faction, new LordJob_ManTurrets(), map, null); - int tile = map.Tile; - PawnGenerationRequest value = new PawnGenerationRequest(faction.RandomPawnKind(), faction, PawnGenerationContext.NonPlayer, tile, false, false, false, false, true, true, 1f, false, true, true, true, false, null, null, null, null, null, null); - ResolveParams resolveParams = rp; - resolveParams.faction = faction; - resolveParams.singlePawnGenerationRequest = new PawnGenerationRequest?(value); - resolveParams.rect = CellRect.SingleCell(c); - resolveParams.singlePawnLord = singlePawnLord; - BaseGen.symbolStack.Push("pawn", resolveParams); - } - if (thingDef.building.turretShellDef != null) - { - ResolveParams resolveParams2 = rp; - resolveParams2.faction = faction; - resolveParams2.singleThingDef = thingDef.building.turretShellDef; - resolveParams2.singleThingStackCount = new int?(Rand.RangeInclusive(5, Mathf.Min(8, thingDef.building.turretShellDef.stackLimit))); - BaseGen.symbolStack.Push("thing", resolveParams2); + if (thingDef.HasComp(typeof(CompMannable))) + { + IntVec3 c = Thing.InteractionCellWhenAt(thingDef, intVec, rot, map); + Lord singlePawnLord = LordMaker.MakeNewLord(faction, new LordJob_ManTurrets(), map, null); + int tile = map.Tile; + PawnGenerationRequest value = new PawnGenerationRequest(faction.RandomPawnKind(), faction, PawnGenerationContext.NonPlayer, tile, false, false, false, false, true, true, 1f, false, true, true, true, false, null, default(float?), default(float?), default(Gender?), default(float?), (string)null); + ResolveParams resolveParams = rp; + resolveParams.faction = faction; + resolveParams.singlePawnGenerationRequest = new PawnGenerationRequest?(value); + resolveParams.rect = CellRect.SingleCell(c); + resolveParams.singlePawnLord = singlePawnLord; + BaseGen.symbolStack.Push("pawn", resolveParams); + } + if (thingDef.building.turretShellDef != null) + { + ResolveParams resolveParams2 = rp; + resolveParams2.faction = faction; + resolveParams2.singleThingDef = thingDef.building.turretShellDef; + resolveParams2.singleThingStackCount = new int?(Rand.RangeInclusive(5, Mathf.Min(8, thingDef.building.turretShellDef.stackLimit))); + BaseGen.symbolStack.Push("thing", resolveParams2); + } + ResolveParams resolveParams3 = rp; + resolveParams3.faction = faction; + resolveParams3.singleThingDef = thingDef; + resolveParams3.rect = CellRect.SingleCell(intVec); + resolveParams3.thingRot = new Rot4?(rot); + BaseGen.symbolStack.Push("thing", resolveParams3); } - ResolveParams resolveParams3 = rp; - resolveParams3.faction = faction; - resolveParams3.singleThingDef = thingDef; - resolveParams3.rect = CellRect.SingleCell(intVec); - resolveParams3.thingRot = new Rot4?(rot); - BaseGen.symbolStack.Push("thing", resolveParams3); } private bool TryFindMortarSpawnCell(CellRect rect, Rot4 rot, ThingDef mortarDef, out IntVec3 cell) @@ -82,24 +80,32 @@ private bool TryFindMortarSpawnCell(CellRect rect, Rot4 rot, ThingDef mortarDef, Predicate edgeTouchCheck; if (rot == Rot4.North) { - edgeTouchCheck = ((CellRect x) => x.Cells.Any((IntVec3 y) => y.z == rect.maxZ)); + CellRect rect5; + edgeTouchCheck = (Predicate)((CellRect x) => x.Cells.Any((Func)((IntVec3 y) => y.z == rect5.maxZ))); } else if (rot == Rot4.South) { - edgeTouchCheck = ((CellRect x) => x.Cells.Any((IntVec3 y) => y.z == rect.minZ)); + CellRect rect4; + edgeTouchCheck = (Predicate)((CellRect x) => x.Cells.Any((Func)((IntVec3 y) => y.z == rect4.minZ))); } else if (rot == Rot4.West) { - edgeTouchCheck = ((CellRect x) => x.Cells.Any((IntVec3 y) => y.x == rect.minX)); + CellRect rect3; + edgeTouchCheck = (Predicate)((CellRect x) => x.Cells.Any((Func)((IntVec3 y) => y.x == rect3.minX))); } else { - edgeTouchCheck = ((CellRect x) => x.Cells.Any((IntVec3 y) => y.x == rect.maxX)); + CellRect rect2; + edgeTouchCheck = (Predicate)((CellRect x) => x.Cells.Any((Func)((IntVec3 y) => y.x == rect2.maxX))); } - return CellFinder.TryFindRandomCellInsideWith(rect, delegate(IntVec3 x) + return CellFinder.TryFindRandomCellInsideWith(rect, (Predicate)delegate(IntVec3 x) { CellRect obj = GenAdj.OccupiedRect(x, rot, mortarDef.size); - return Thing.InteractionCellWhenAt(mortarDef, x, rot, map).Standable(map) && obj.FullyContainedWithin(rect) && edgeTouchCheck(obj); + if (!Thing.InteractionCellWhenAt(mortarDef, x, rot, map).Standable(map)) + { + return false; + } + return obj.FullyContainedWithin(rect) && edgeTouchCheck(obj); }, out cell); } } diff --git a/Assembly-CSharp/RimWorld.BaseGen/SymbolResolver_OutdoorsCampfire.cs b/Assembly-CSharp/RimWorld.BaseGen/SymbolResolver_OutdoorsCampfire.cs index d2f97fb91..5b0d959d5 100644 --- a/Assembly-CSharp/RimWorld.BaseGen/SymbolResolver_OutdoorsCampfire.cs +++ b/Assembly-CSharp/RimWorld.BaseGen/SymbolResolver_OutdoorsCampfire.cs @@ -7,38 +7,33 @@ public class SymbolResolver_OutdoorsCampfire : SymbolResolver { public override bool CanResolve(ResolveParams rp) { - IntVec3 intVec; - return base.CanResolve(rp) && this.TryFindSpawnCell(rp.rect, out intVec); + if (!base.CanResolve(rp)) + { + return false; + } + IntVec3 intVec = default(IntVec3); + if (!this.TryFindSpawnCell(rp.rect, out intVec)) + { + return false; + } + return true; } public override void Resolve(ResolveParams rp) { - IntVec3 loc; - if (!this.TryFindSpawnCell(rp.rect, out loc)) + IntVec3 loc = default(IntVec3); + if (this.TryFindSpawnCell(rp.rect, out loc)) { - return; + Thing thing = ThingMaker.MakeThing(ThingDefOf.Campfire, null); + thing.SetFaction(rp.faction, null); + GenSpawn.Spawn(thing, loc, BaseGen.globalSettings.map); } - Thing thing = ThingMaker.MakeThing(ThingDefOf.Campfire, null); - thing.SetFaction(rp.faction, null); - GenSpawn.Spawn(thing, loc, BaseGen.globalSettings.map); } private bool TryFindSpawnCell(CellRect rect, out IntVec3 result) { Map map = BaseGen.globalSettings.map; - return CellFinder.TryFindRandomCellInsideWith(rect, delegate(IntVec3 c) - { - bool arg_7D_0; - if (c.Standable(map) && !c.Roofed(map) && !BaseGenUtility.AnyDoorCardinalAdjacentTo(c, map) && c.GetFirstItem(map) == null) - { - arg_7D_0 = !GenSpawn.WouldWipeAnythingWith(c, Rot4.North, ThingDefOf.Campfire, map, (Thing x) => x.def.category == ThingCategory.Building); - } - else - { - arg_7D_0 = false; - } - return arg_7D_0; - }, out result); + return CellFinder.TryFindRandomCellInsideWith(rect, (Predicate)((IntVec3 c) => c.Standable(map) && !c.Roofed(map) && !BaseGenUtility.AnyDoorCardinalAdjacentTo(c, map) && c.GetFirstItem(map) == null && !GenSpawn.WouldWipeAnythingWith(c, Rot4.North, ThingDefOf.Campfire, map, (Predicate)((Thing x) => x.def.category == ThingCategory.Building))), out result); } } } diff --git a/Assembly-CSharp/RimWorld.BaseGen/SymbolResolver_PawnGroup.cs b/Assembly-CSharp/RimWorld.BaseGen/SymbolResolver_PawnGroup.cs index 4af5d30cd..76d56d0b7 100644 --- a/Assembly-CSharp/RimWorld.BaseGen/SymbolResolver_PawnGroup.cs +++ b/Assembly-CSharp/RimWorld.BaseGen/SymbolResolver_PawnGroup.cs @@ -14,9 +14,13 @@ public override bool CanResolve(ResolveParams rp) { return false; } - return (from x in rp.rect.Cells + if (!(from x in rp.rect.Cells where x.Standable(BaseGen.globalSettings.map) - select x).Any(); + select x).Any()) + { + return false; + } + return true; } public override void Resolve(ResolveParams rp) @@ -31,10 +35,10 @@ public override void Resolve(ResolveParams rp) pawnGroupMakerParms.points = 250f; } PawnGroupKindDef groupKind = rp.pawnGroupKindDef ?? PawnGroupKindDefOf.Normal; - foreach (Pawn current in PawnGroupMakerUtility.GeneratePawns(groupKind, pawnGroupMakerParms, true)) + foreach (Pawn item in PawnGroupMakerUtility.GeneratePawns(groupKind, pawnGroupMakerParms, true)) { ResolveParams resolveParams = rp; - resolveParams.singlePawnToSpawn = current; + resolveParams.singlePawnToSpawn = item; BaseGen.symbolStack.Push("pawn", resolveParams); } } diff --git a/Assembly-CSharp/RimWorld.BaseGen/SymbolResolver_PlaceChairsNearTables.cs b/Assembly-CSharp/RimWorld.BaseGen/SymbolResolver_PlaceChairsNearTables.cs index 61a8a553f..64004fd60 100644 --- a/Assembly-CSharp/RimWorld.BaseGen/SymbolResolver_PlaceChairsNearTables.cs +++ b/Assembly-CSharp/RimWorld.BaseGen/SymbolResolver_PlaceChairsNearTables.cs @@ -1,4 +1,3 @@ -using System; using System.Collections.Generic; using Verse; @@ -29,40 +28,19 @@ public override void Resolve(ResolveParams rp) { CellRect cellRect = SymbolResolver_PlaceChairsNearTables.tables[j].OccupiedRect().ExpandedBy(1); bool flag = false; - foreach (IntVec3 current in cellRect.EdgeCells.InRandomOrder(null)) + foreach (IntVec3 item in cellRect.EdgeCells.InRandomOrder(null)) { - if (!cellRect.IsCorner(current) && rp.rect.Contains(current)) + IntVec3 current = item; + if (!cellRect.IsCorner(current) && rp.rect.Contains(current) && current.Standable(map) && current.GetEdifice(map) == null && (!flag || !Rand.Bool)) { - if (current.Standable(map) && current.GetEdifice(map) == null) - { - if (!flag || !Rand.Bool) - { - Rot4 value; - if (current.x == cellRect.minX) - { - value = Rot4.East; - } - else if (current.x == cellRect.maxX) - { - value = Rot4.West; - } - else if (current.z == cellRect.minZ) - { - value = Rot4.North; - } - else - { - value = Rot4.South; - } - ResolveParams resolveParams = rp; - resolveParams.rect = CellRect.SingleCell(current); - resolveParams.singleThingDef = ThingDefOf.DiningChair; - resolveParams.singleThingStuff = (rp.singleThingStuff ?? ThingDefOf.WoodLog); - resolveParams.thingRot = new Rot4?(value); - BaseGen.symbolStack.Push("thing", resolveParams); - flag = true; - } - } + Rot4 value = (current.x != cellRect.minX) ? ((current.x != cellRect.maxX) ? ((current.z != cellRect.minZ) ? Rot4.South : Rot4.North) : Rot4.West) : Rot4.East; + ResolveParams resolveParams = rp; + resolveParams.rect = CellRect.SingleCell(current); + resolveParams.singleThingDef = ThingDefOf.DiningChair; + resolveParams.singleThingStuff = (rp.singleThingStuff ?? ThingDefOf.WoodLog); + resolveParams.thingRot = new Rot4?(value); + BaseGen.symbolStack.Push("thing", resolveParams); + flag = true; } } } diff --git a/Assembly-CSharp/RimWorld.BaseGen/SymbolResolver_RandomMechanoidGroup.cs b/Assembly-CSharp/RimWorld.BaseGen/SymbolResolver_RandomMechanoidGroup.cs index f7fa3bfbf..6c18bb73b 100644 --- a/Assembly-CSharp/RimWorld.BaseGen/SymbolResolver_RandomMechanoidGroup.cs +++ b/Assembly-CSharp/RimWorld.BaseGen/SymbolResolver_RandomMechanoidGroup.cs @@ -17,28 +17,20 @@ public override void Resolve(ResolveParams rp) if (lord == null && num > 0) { Map map = BaseGen.globalSettings.map; - IntVec3 point; - LordJob lordJob; - if (Rand.Bool && (from x in rp.rect.Cells + IntVec3 point = default(IntVec3); + LordJob lordJob = (LordJob)((!Rand.Bool || !(from x in rp.rect.Cells where !x.Impassable(map) - select x).TryRandomElement(out point)) - { - lordJob = new LordJob_DefendPoint(point); - } - else - { - lordJob = new LordJob_AssaultColony(Faction.OfMechanoids, false, false, false, false, false); - } + select x).TryRandomElement(out point)) ? ((object)new LordJob_AssaultColony(Faction.OfMechanoids, false, false, false, false, false)) : ((object)new LordJob_DefendPoint(point))); lord = LordMaker.MakeNewLord(Faction.OfMechanoids, lordJob, map, null); } - for (int i = 0; i < num; i++) + for (int num2 = 0; num2 < num; num2++) { PawnKindDef pawnKindDef = rp.singlePawnKindDef; if (pawnKindDef == null) { pawnKindDef = (from kind in DefDatabase.AllDefsListForReading where kind.RaceProps.IsMechanoid - select kind).RandomElementByWeight((PawnKindDef kind) => 1f / kind.combatPower); + select kind).RandomElementByWeight((Func)((PawnKindDef kind) => (float)(1.0 / kind.combatPower))); } ResolveParams resolveParams = rp; resolveParams.singlePawnKindDef = pawnKindDef; diff --git a/Assembly-CSharp/RimWorld.BaseGen/SymbolResolver_RandomlyPlaceMealsOnTables.cs b/Assembly-CSharp/RimWorld.BaseGen/SymbolResolver_RandomlyPlaceMealsOnTables.cs index f33b33fc2..e266dc361 100644 --- a/Assembly-CSharp/RimWorld.BaseGen/SymbolResolver_RandomlyPlaceMealsOnTables.cs +++ b/Assembly-CSharp/RimWorld.BaseGen/SymbolResolver_RandomlyPlaceMealsOnTables.cs @@ -1,4 +1,3 @@ -using System; using System.Collections.Generic; using Verse; diff --git a/Assembly-CSharp/RimWorld.BaseGen/SymbolResolver_Refuel.cs b/Assembly-CSharp/RimWorld.BaseGen/SymbolResolver_Refuel.cs index 19ca50e46..e91583aeb 100644 --- a/Assembly-CSharp/RimWorld.BaseGen/SymbolResolver_Refuel.cs +++ b/Assembly-CSharp/RimWorld.BaseGen/SymbolResolver_Refuel.cs @@ -1,4 +1,3 @@ -using System; using System.Collections.Generic; using Verse; @@ -29,7 +28,7 @@ public override void Resolve(ResolveParams rp) for (int j = 0; j < SymbolResolver_Refuel.refuelables.Count; j++) { float fuelCapacity = SymbolResolver_Refuel.refuelables[j].Props.fuelCapacity; - float amount = Rand.Range(fuelCapacity / 2f, fuelCapacity); + float amount = Rand.Range((float)(fuelCapacity / 2.0), fuelCapacity); SymbolResolver_Refuel.refuelables[j].Refuel(amount); } SymbolResolver_Refuel.refuelables.Clear(); diff --git a/Assembly-CSharp/RimWorld.BaseGen/SymbolResolver_Roof.cs b/Assembly-CSharp/RimWorld.BaseGen/SymbolResolver_Roof.cs index e13380ede..dda8a85c2 100644 --- a/Assembly-CSharp/RimWorld.BaseGen/SymbolResolver_Roof.cs +++ b/Assembly-CSharp/RimWorld.BaseGen/SymbolResolver_Roof.cs @@ -1,4 +1,3 @@ -using System; using Verse; namespace RimWorld.BaseGen @@ -8,9 +7,7 @@ public class SymbolResolver_Roof : SymbolResolver public override void Resolve(ResolveParams rp) { if (rp.noRoof.HasValue && rp.noRoof.Value) - { return; - } RoofGrid roofGrid = BaseGen.globalSettings.map.roofGrid; RoofDef def = rp.roofDef ?? RoofDefOf.RoofConstructed; CellRect.CellRectIterator iterator = rp.rect.GetIterator(); diff --git a/Assembly-CSharp/RimWorld.BaseGen/SymbolResolver_SinglePawn.cs b/Assembly-CSharp/RimWorld.BaseGen/SymbolResolver_SinglePawn.cs index a37fc8c5c..b4f4cce51 100644 --- a/Assembly-CSharp/RimWorld.BaseGen/SymbolResolver_SinglePawn.cs +++ b/Assembly-CSharp/RimWorld.BaseGen/SymbolResolver_SinglePawn.cs @@ -9,86 +9,89 @@ public class SymbolResolver_SinglePawn : SymbolResolver { public override bool CanResolve(ResolveParams rp) { - IntVec3 intVec; - return base.CanResolve(rp) && ((rp.singlePawnToSpawn != null && rp.singlePawnToSpawn.Spawned) || SymbolResolver_SinglePawn.TryFindSpawnCell(rp, out intVec)); + if (!base.CanResolve(rp)) + { + return false; + } + if (rp.singlePawnToSpawn != null && rp.singlePawnToSpawn.Spawned) + { + return true; + } + IntVec3 intVec = default(IntVec3); + if (!SymbolResolver_SinglePawn.TryFindSpawnCell(rp, out intVec)) + { + return false; + } + return true; } public override void Resolve(ResolveParams rp) { if (rp.singlePawnToSpawn != null && rp.singlePawnToSpawn.Spawned) - { return; - } Map map = BaseGen.globalSettings.map; - IntVec3 loc; + IntVec3 loc = default(IntVec3); if (!SymbolResolver_SinglePawn.TryFindSpawnCell(rp, out loc)) { if (rp.singlePawnToSpawn != null) { Find.WorldPawns.PassToWorld(rp.singlePawnToSpawn, PawnDiscardDecideMode.Discard); } - return; } - Pawn pawn; - if (rp.singlePawnToSpawn == null) + else { - PawnGenerationRequest value; - if (rp.singlePawnGenerationRequest.HasValue) - { - value = rp.singlePawnGenerationRequest.Value; - } - else + Pawn pawn; + if (rp.singlePawnToSpawn == null) { - PawnKindDef arg_BE_0; - if ((arg_BE_0 = rp.singlePawnKindDef) == null) + PawnGenerationRequest request = default(PawnGenerationRequest); + if (rp.singlePawnGenerationRequest.HasValue) { - arg_BE_0 = (from x in DefDatabase.AllDefsListForReading - where x.defaultFactionType == null || !x.defaultFactionType.isPlayer - select x).RandomElement(); + request = rp.singlePawnGenerationRequest.Value; } - PawnKindDef pawnKindDef = arg_BE_0; - Faction faction = rp.faction; - if (faction == null && pawnKindDef.RaceProps.Humanlike) + else { - if (pawnKindDef.defaultFactionType != null) + PawnKindDef pawnKindDef = rp.singlePawnKindDef ?? (from x in DefDatabase.AllDefsListForReading + where x.defaultFactionType == null || !x.defaultFactionType.isPlayer + select x).RandomElement(); + Faction faction = rp.faction; + if (faction == null && pawnKindDef.RaceProps.Humanlike) { - faction = FactionUtility.DefaultFactionFrom(pawnKindDef.defaultFactionType); - if (faction == null) + if (pawnKindDef.defaultFactionType != null) { - return; + faction = FactionUtility.DefaultFactionFrom(pawnKindDef.defaultFactionType); + if (faction == null) + return; } + else if (!(from x in Find.FactionManager.AllFactions + where !x.IsPlayer + select x).TryRandomElement(out faction)) + return; } - else if (!(from x in Find.FactionManager.AllFactions - where !x.IsPlayer - select x).TryRandomElement(out faction)) - { - return; - } + int tile = map.Tile; + request = new PawnGenerationRequest(pawnKindDef, faction, PawnGenerationContext.NonPlayer, tile, false, false, false, false, true, false, 1f, false, true, true, false, false, null, default(float?), default(float?), default(Gender?), default(float?), (string)null); } - int tile = map.Tile; - value = new PawnGenerationRequest(pawnKindDef, faction, PawnGenerationContext.NonPlayer, tile, false, false, false, false, true, false, 1f, false, true, true, false, false, null, null, null, null, null, null); + pawn = PawnGenerator.GeneratePawn(request); + } + else + { + pawn = rp.singlePawnToSpawn; + } + if (!pawn.Dead && rp.disableSinglePawn.HasValue && rp.disableSinglePawn.Value) + { + pawn.mindState.Active = false; + } + GenSpawn.Spawn(pawn, loc, map); + if (rp.singlePawnLord != null) + { + rp.singlePawnLord.AddPawn(pawn); } - pawn = PawnGenerator.GeneratePawn(value); - } - else - { - pawn = rp.singlePawnToSpawn; - } - if (!pawn.Dead && rp.disableSinglePawn.HasValue && rp.disableSinglePawn.Value) - { - pawn.mindState.Active = false; - } - GenSpawn.Spawn(pawn, loc, map); - if (rp.singlePawnLord != null) - { - rp.singlePawnLord.AddPawn(pawn); } } public static bool TryFindSpawnCell(ResolveParams rp, out IntVec3 cell) { Map map = BaseGen.globalSettings.map; - return CellFinder.TryFindRandomCellInsideWith(rp.rect, (IntVec3 x) => x.Standable(map) && (rp.singlePawnSpawnCellExtraPredicate == null || rp.singlePawnSpawnCellExtraPredicate(x)), out cell); + return CellFinder.TryFindRandomCellInsideWith(rp.rect, (Predicate)((IntVec3 x) => x.Standable(map) && ((object)rp.singlePawnSpawnCellExtraPredicate == null || rp.singlePawnSpawnCellExtraPredicate(x))), out cell); } } } diff --git a/Assembly-CSharp/RimWorld.BaseGen/SymbolResolver_SingleThing.cs b/Assembly-CSharp/RimWorld.BaseGen/SymbolResolver_SingleThing.cs index 7c0cbf958..e9574f5aa 100644 --- a/Assembly-CSharp/RimWorld.BaseGen/SymbolResolver_SingleThing.cs +++ b/Assembly-CSharp/RimWorld.BaseGen/SymbolResolver_SingleThing.cs @@ -16,7 +16,7 @@ public override bool CanResolve(ResolveParams rp) { return true; } - IntVec3 intVec; + IntVec3 intVec = default(IntVec3); if (rp.singleThingToSpawn is Pawn) { ResolveParams rp2 = rp; @@ -26,7 +26,21 @@ public override bool CanResolve(ResolveParams rp) return false; } } - return ((rp.singleThingDef == null || rp.singleThingDef.category != ThingCategory.Item) && (rp.singleThingToSpawn == null || rp.singleThingToSpawn.def.category != ThingCategory.Item)) || this.TryFindSpawnCellForItem(rp.rect, out intVec); + if (rp.singleThingDef != null && rp.singleThingDef.category == ThingCategory.Item) + { + goto IL_00a3; + } + if (rp.singleThingToSpawn != null && rp.singleThingToSpawn.def.category == ThingCategory.Item) + goto IL_00a3; + goto IL_00b9; + IL_00b9: + return true; + IL_00a3: + if (!this.TryFindSpawnCellForItem(rp.rect, out intVec)) + { + return false; + } + goto IL_00b9; } public override void Resolve(ResolveParams rp) @@ -36,87 +50,74 @@ public override void Resolve(ResolveParams rp) ResolveParams resolveParams = rp; resolveParams.singlePawnToSpawn = (Pawn)rp.singleThingToSpawn; BaseGen.symbolStack.Push("pawn", resolveParams); - return; } - if (rp.singleThingToSpawn != null && rp.singleThingToSpawn.Spawned) - { - return; - } - ThingDef thingDef; - if (rp.singleThingToSpawn == null) + else { - ThingDef arg_9B_0; - if ((arg_9B_0 = rp.singleThingDef) == null) + if (rp.singleThingToSpawn != null && rp.singleThingToSpawn.Spawned) + return; + ThingDef thingDef = (rp.singleThingToSpawn != null) ? rp.singleThingToSpawn.def : (rp.singleThingDef ?? (from x in ItemCollectionGeneratorUtility.allGeneratableItems + where x.IsWeapon || x.IsMedicine || x.IsDrug + select x).RandomElement()); + Rot4? thingRot = rp.thingRot; + Rot4 rot = (!thingRot.HasValue) ? Rot4.North : thingRot.Value; + if (!thingDef.rotatable) { - arg_9B_0 = (from x in ItemCollectionGeneratorUtility.allGeneratableItems - where x.IsWeapon || x.IsMedicine || x.IsDrug - select x).RandomElement(); + rot = Rot4.North; } - thingDef = arg_9B_0; - } - else - { - thingDef = rp.singleThingToSpawn.def; - } - Rot4? thingRot = rp.thingRot; - Rot4 rot = (!thingRot.HasValue) ? Rot4.North : thingRot.Value; - if (!thingDef.rotatable) - { - rot = Rot4.North; - } - IntVec3 loc; - if (thingDef.category == ThingCategory.Item) - { - if (!this.TryFindSpawnCellForItem(rp.rect, out loc)) + IntVec3 loc = default(IntVec3); + if (thingDef.category == ThingCategory.Item) { - if (rp.singleThingToSpawn != null) + if (!this.TryFindSpawnCellForItem(rp.rect, out loc)) { - rp.singleThingToSpawn.Destroy(DestroyMode.Vanish); + if (rp.singleThingToSpawn != null) + { + rp.singleThingToSpawn.Destroy(DestroyMode.Vanish); + } + return; } - return; } - } - else - { - loc = this.FindBestSpawnCellForNonItem(rp.rect, thingDef, rot); - } - Thing thing; - if (rp.singleThingToSpawn == null) - { - ThingDef stuff = rp.singleThingStuff ?? GenStuff.DefaultStuffFor(thingDef); - thing = ThingMaker.MakeThing(thingDef, stuff); - Thing arg_185_0 = thing; - int? singleThingStackCount = rp.singleThingStackCount; - arg_185_0.stackCount = ((!singleThingStackCount.HasValue) ? 1 : singleThingStackCount.Value); - if (thing.stackCount <= 0) + else { - thing.stackCount = 1; + loc = this.FindBestSpawnCellForNonItem(rp.rect, thingDef, rot); } - if (thing.def.CanHaveFaction && thing.Faction != rp.faction) + Thing thing; + if (rp.singleThingToSpawn == null) { - thing.SetFaction(rp.faction, null); + ThingDef stuff = rp.singleThingStuff ?? GenStuff.DefaultStuffFor(thingDef); + thing = ThingMaker.MakeThing(thingDef, stuff); + Thing obj = thing; + int? singleThingStackCount = rp.singleThingStackCount; + obj.stackCount = ((!singleThingStackCount.HasValue) ? 1 : singleThingStackCount.Value); + if (thing.stackCount <= 0) + { + thing.stackCount = 1; + } + if (thing.def.CanHaveFaction && thing.Faction != rp.faction) + { + thing.SetFaction(rp.faction, null); + } + CompQuality compQuality = thing.TryGetComp(); + if (compQuality != null) + { + compQuality.SetQuality(QualityUtility.RandomBaseGenItemQuality(), ArtGenerationContext.Outsider); + } } - CompQuality compQuality = thing.TryGetComp(); - if (compQuality != null) + else { - compQuality.SetQuality(QualityUtility.RandomBaseGenItemQuality(), ArtGenerationContext.Outsider); + thing = rp.singleThingToSpawn; + } + thing = GenSpawn.Spawn(thing, loc, BaseGen.globalSettings.map, rot, false); + if (thing != null && thing.def.category == ThingCategory.Item) + { + thing.SetForbidden(true, false); } - } - else - { - thing = rp.singleThingToSpawn; - } - thing = GenSpawn.Spawn(thing, loc, BaseGen.globalSettings.map, rot, false); - if (thing != null && thing.def.category == ThingCategory.Item) - { - thing.SetForbidden(true, false); } } private bool TryFindSpawnCellForItem(CellRect rect, out IntVec3 result) { Map map = BaseGen.globalSettings.map; - return CellFinder.TryFindRandomCellInsideWith(rect, delegate(IntVec3 c) + return CellFinder.TryFindRandomCellInsideWith(rect, (Predicate)delegate(IntVec3 c) { if (c.GetFirstItem(map) != null) { @@ -139,40 +140,36 @@ private IntVec3 FindBestSpawnCellForNonItem(CellRect rect, ThingDef thingDef, Ro Map map = BaseGen.globalSettings.map; if (thingDef.category == ThingCategory.Building) { - foreach (IntVec3 current in rect.Cells.InRandomOrder(null)) + foreach (IntVec3 item in rect.Cells.InRandomOrder(null)) { - CellRect rect2 = GenAdj.OccupiedRect(current, rot, thingDef.size); + CellRect rect2 = GenAdj.OccupiedRect(item, rot, thingDef.size); if (rect2.FullyContainedWithin(rect) && !BaseGenUtility.AnyDoorCardinalAdjacentTo(rect2, map) && !this.AnyNonStandableCellOrAnyBuildingInside(rect2) && GenConstruct.TerrainCanSupport(rect2, map, thingDef)) { - IntVec3 result = current; - return result; + return item; } } - foreach (IntVec3 current2 in rect.Cells.InRandomOrder(null)) + foreach (IntVec3 item2 in rect.Cells.InRandomOrder(null)) { - CellRect rect3 = GenAdj.OccupiedRect(current2, rot, thingDef.size); + CellRect rect3 = GenAdj.OccupiedRect(item2, rot, thingDef.size); if (rect3.FullyContainedWithin(rect) && !BaseGenUtility.AnyDoorCardinalAdjacentTo(rect3, map) && !this.AnyNonStandableCellOrAnyBuildingInside(rect3)) { - IntVec3 result = current2; - return result; + return item2; } } } - foreach (IntVec3 current3 in rect.Cells.InRandomOrder(null)) + foreach (IntVec3 item3 in rect.Cells.InRandomOrder(null)) { - CellRect rect4 = GenAdj.OccupiedRect(current3, rot, thingDef.size); + CellRect rect4 = GenAdj.OccupiedRect(item3, rot, thingDef.size); if (rect4.FullyContainedWithin(rect) && !this.AnyNonStandableCellOrAnyBuildingInside(rect4)) { - IntVec3 result = current3; - return result; + return item3; } } - foreach (IntVec3 current4 in rect.Cells.InRandomOrder(null)) + foreach (IntVec3 item4 in rect.Cells.InRandomOrder(null)) { - if (GenAdj.OccupiedRect(current4, rot, thingDef.size).FullyContainedWithin(rect)) + if (GenAdj.OccupiedRect(item4, rot, thingDef.size).FullyContainedWithin(rect)) { - IntVec3 result = current4; - return result; + return item4; } } IntVec3 centerCell = rect.CenterCell; @@ -185,13 +182,23 @@ private IntVec3 FindBestSpawnCellForNonItem(CellRect rect, ThingDef thingDef, Ro { centerCell.z += -cellRect.minZ; } - if (cellRect.maxX >= map.Size.x) + int maxX = cellRect.maxX; + IntVec3 size = map.Size; + if (maxX >= size.x) { - centerCell.x -= cellRect.maxX - map.Size.x + 1; + int x = centerCell.x; + int maxX2 = cellRect.maxX; + IntVec3 size2 = map.Size; + centerCell.x = x - (maxX2 - size2.x + 1); } - if (cellRect.maxZ >= map.Size.z) + int maxZ = cellRect.maxZ; + IntVec3 size3 = map.Size; + if (maxZ >= size3.z) { - centerCell.z -= cellRect.maxZ - map.Size.z + 1; + int z = centerCell.z; + int maxZ2 = cellRect.maxZ; + IntVec3 size4 = map.Size; + centerCell.z = z - (maxZ2 - size4.z + 1); } return centerCell; } diff --git a/Assembly-CSharp/RimWorld.BaseGen/SymbolResolver_Stockpile.cs b/Assembly-CSharp/RimWorld.BaseGen/SymbolResolver_Stockpile.cs index 0e8e05a17..8ae50a4f9 100644 --- a/Assembly-CSharp/RimWorld.BaseGen/SymbolResolver_Stockpile.cs +++ b/Assembly-CSharp/RimWorld.BaseGen/SymbolResolver_Stockpile.cs @@ -1,4 +1,3 @@ -using System; using System.Collections.Generic; using System.Linq; using UnityEngine; @@ -15,31 +14,29 @@ public class SymbolResolver_Stockpile : SymbolResolver public override void Resolve(ResolveParams rp) { Map map = BaseGen.globalSettings.map; - if (rp.stockpileConcreteContents != null && rp.stockpileConcreteContents.Any()) + if (rp.stockpileConcreteContents != null && rp.stockpileConcreteContents.Any()) { this.CalculateFreeCells(rp.rect, 0f); int num = 0; - for (int i = rp.stockpileConcreteContents.Count - 1; i >= 0; i--) + int num2 = rp.stockpileConcreteContents.Count - 1; + while (num2 >= 0 && num < this.cells.Count) { - if (num >= this.cells.Count) - { - break; - } - GenSpawn.Spawn(rp.stockpileConcreteContents[i], this.cells[num], map); + GenSpawn.Spawn(rp.stockpileConcreteContents[num2], this.cells[num], map); num++; + num2--; } - for (int j = rp.stockpileConcreteContents.Count - 1; j >= 0; j--) + for (int num3 = rp.stockpileConcreteContents.Count - 1; num3 >= 0; num3--) { - if (!rp.stockpileConcreteContents[j].Spawned) + if (!rp.stockpileConcreteContents[num3].Spawned) { - rp.stockpileConcreteContents[j].Destroy(DestroyMode.Vanish); + rp.stockpileConcreteContents[num3].Destroy(DestroyMode.Vanish); } } rp.stockpileConcreteContents.Clear(); } else { - ItemCollectionGeneratorDef itemCollectionGeneratorDef = rp.itemCollectionGeneratorDef ?? Rand.Element(ItemCollectionGeneratorDefOf.RandomGeneralGoods, ItemCollectionGeneratorDefOf.Weapons, ItemCollectionGeneratorDefOf.Apparel, ItemCollectionGeneratorDefOf.RawResources); + ItemCollectionGeneratorDef itemCollectionGeneratorDef = rp.itemCollectionGeneratorDef ?? Rand.Element(ItemCollectionGeneratorDefOf.RandomGeneralGoods, ItemCollectionGeneratorDefOf.Weapons, ItemCollectionGeneratorDefOf.Apparel, ItemCollectionGeneratorDefOf.RawResources); ItemCollectionGeneratorParams? itemCollectionGeneratorParams = rp.itemCollectionGeneratorParams; ItemCollectionGeneratorParams value; if (itemCollectionGeneratorParams.HasValue) @@ -49,14 +46,15 @@ public override void Resolve(ResolveParams rp) else { this.CalculateFreeCells(rp.rect, 0.41f); - value = default(ItemCollectionGeneratorParams); - value.count = this.cells.Count; - value.techLevel = ((rp.faction == null) ? TechLevel.Spacer : rp.faction.def.techLevel); + value = new ItemCollectionGeneratorParams + { + count = this.cells.Count, + techLevel = ((rp.faction == null) ? TechLevel.Spacer : rp.faction.def.techLevel) + }; if (itemCollectionGeneratorDef.Worker is ItemCollectionGenerator_Standard) { float? stockpileMarketValue = rp.stockpileMarketValue; - float totalMarketValue = (!stockpileMarketValue.HasValue) ? Mathf.Min((float)this.cells.Count * 120f, 1800f) : stockpileMarketValue.Value; - value.totalMarketValue = totalMarketValue; + float num4 = value.totalMarketValue = ((!stockpileMarketValue.HasValue) ? Mathf.Min((float)((float)this.cells.Count * 120.0), 1800f) : stockpileMarketValue.Value); } } ResolveParams resolveParams = rp; @@ -70,19 +68,19 @@ private void CalculateFreeCells(CellRect rect, float freeCellsFraction) { Map map = BaseGen.globalSettings.map; this.cells.Clear(); - foreach (IntVec3 current in rect) + foreach (IntVec3 item in rect) { - if (current.Standable(map) && current.GetFirstItem(map) == null) + if (item.Standable(map) && item.GetFirstItem(map) == null) { - this.cells.Add(current); + this.cells.Add(item); } } int num = (int)(freeCellsFraction * (float)this.cells.Count); - for (int i = 0; i < num; i++) + for (int num2 = 0; num2 < num; num2++) { this.cells.RemoveAt(Rand.Range(0, this.cells.Count)); } - this.cells.Shuffle(); + this.cells.Shuffle(); } } } diff --git a/Assembly-CSharp/RimWorld.BaseGen/SymbolResolver_Storage.cs b/Assembly-CSharp/RimWorld.BaseGen/SymbolResolver_Storage.cs index 74ff0d7cd..64e074721 100644 --- a/Assembly-CSharp/RimWorld.BaseGen/SymbolResolver_Storage.cs +++ b/Assembly-CSharp/RimWorld.BaseGen/SymbolResolver_Storage.cs @@ -1,5 +1,3 @@ -using System; - namespace RimWorld.BaseGen { public class SymbolResolver_Storage : SymbolResolver diff --git a/Assembly-CSharp/RimWorld.BaseGen/SymbolResolver_Street.cs b/Assembly-CSharp/RimWorld.BaseGen/SymbolResolver_Street.cs index d04daf7ba..6c3cce7d3 100644 --- a/Assembly-CSharp/RimWorld.BaseGen/SymbolResolver_Street.cs +++ b/Assembly-CSharp/RimWorld.BaseGen/SymbolResolver_Street.cs @@ -1,4 +1,3 @@ -using System; using System.Collections.Generic; using Verse; @@ -24,15 +23,15 @@ private void CalculateStreet(CellRect rect, bool horizontal, TerrainDef floorDef { SymbolResolver_Street.street.Clear(); int num = (!horizontal) ? rect.Height : rect.Width; - for (int i = 0; i < num; i++) + for (int num2 = 0; num2 < num; num2++) { if (horizontal) { - SymbolResolver_Street.street.Add(this.CausesStreet(new IntVec3(rect.minX + i, 0, rect.minZ - 1), floorDef) && this.CausesStreet(new IntVec3(rect.minX + i, 0, rect.maxZ + 1), floorDef)); + SymbolResolver_Street.street.Add(this.CausesStreet(new IntVec3(rect.minX + num2, 0, rect.minZ - 1), floorDef) && this.CausesStreet(new IntVec3(rect.minX + num2, 0, rect.maxZ + 1), floorDef)); } else { - SymbolResolver_Street.street.Add(this.CausesStreet(new IntVec3(rect.minX - 1, 0, rect.minZ + i), floorDef) && this.CausesStreet(new IntVec3(rect.maxX + 1, 0, rect.minZ + i), floorDef)); + SymbolResolver_Street.street.Add(this.CausesStreet(new IntVec3(rect.minX - 1, 0, rect.minZ + num2), floorDef) && this.CausesStreet(new IntVec3(rect.maxX + 1, 0, rect.minZ + num2), floorDef)); } } } @@ -48,17 +47,16 @@ private void FillStreetGaps(bool horizontal, int width) } else if (num != -1 && i - num <= width) { - for (int j = i + 1; j < i + width + 1; j++) + int num2 = i + 1; + while (num2 < i + width + 1 && num2 < SymbolResolver_Street.street.Count) { - if (j >= SymbolResolver_Street.street.Count) + if (!SymbolResolver_Street.street[num2]) { - break; - } - if (SymbolResolver_Street.street[j]) - { - SymbolResolver_Street.street[i] = true; - break; + num2++; + continue; } + SymbolResolver_Street.street[i] = true; + break; } } } @@ -71,25 +69,21 @@ private void RemoveShortStreetParts(bool horizontal, int width) if (SymbolResolver_Street.street[i]) { int num = 0; - for (int j = i; j < SymbolResolver_Street.street.Count; j++) + int num2 = i; + while (num2 < SymbolResolver_Street.street.Count && SymbolResolver_Street.street[num2]) { - if (!SymbolResolver_Street.street[j]) - { - break; - } num++; + num2++; } - int num2 = 0; - for (int k = i; k >= 0; k--) + int num3 = 0; + int num4 = i; + while (num4 >= 0 && SymbolResolver_Street.street[num4]) { - if (!SymbolResolver_Street.street[k]) - { - break; - } - num2++; + num3++; + num4--; } - int num3 = num2 + num - 1; - if (num3 < width) + int num5 = num3 + num - 1; + if (num5 < width) { SymbolResolver_Street.street[i] = false; } @@ -102,14 +96,18 @@ private void SpawnFloor(CellRect rect, bool horizontal, TerrainDef floorDef) Map map = BaseGen.globalSettings.map; TerrainGrid terrainGrid = map.terrainGrid; CellRect.CellRectIterator iterator = rect.GetIterator(); - while (!iterator.Done()) + for (; !iterator.Done(); iterator.MoveNext()) { IntVec3 current = iterator.Current; - if ((horizontal && SymbolResolver_Street.street[current.x - rect.minX]) || (!horizontal && SymbolResolver_Street.street[current.z - rect.minZ])) + if (horizontal && SymbolResolver_Street.street[current.x - rect.minX]) { - terrainGrid.SetTerrain(current, floorDef); + goto IL_006f; } - iterator.MoveNext(); + if (!horizontal && SymbolResolver_Street.street[current.z - rect.minZ]) + goto IL_006f; + continue; + IL_006f: + terrainGrid.SetTerrain(current, floorDef); } } @@ -121,7 +119,19 @@ private bool CausesStreet(IntVec3 c, TerrainDef floorDef) return false; } Building edifice = c.GetEdifice(map); - return (edifice != null && edifice.def == ThingDefOf.Wall) || c.GetDoor(map) != null || c.GetTerrain(map) == floorDef; + if (edifice != null && edifice.def == ThingDefOf.Wall) + { + return true; + } + if (c.GetDoor(map) != null) + { + return true; + } + if (c.GetTerrain(map) == floorDef) + { + return true; + } + return false; } } } diff --git a/Assembly-CSharp/RimWorld.BaseGen/SymbolResolver_Symbol.cs b/Assembly-CSharp/RimWorld.BaseGen/SymbolResolver_Symbol.cs index f8034ff84..29c0b2afb 100644 --- a/Assembly-CSharp/RimWorld.BaseGen/SymbolResolver_Symbol.cs +++ b/Assembly-CSharp/RimWorld.BaseGen/SymbolResolver_Symbol.cs @@ -1,4 +1,3 @@ -using System; using System.Collections.Generic; using Verse; diff --git a/Assembly-CSharp/RimWorld.BaseGen/SymbolStack.cs b/Assembly-CSharp/RimWorld.BaseGen/SymbolStack.cs index c6e21ec42..2b7fd794c 100644 --- a/Assembly-CSharp/RimWorld.BaseGen/SymbolStack.cs +++ b/Assembly-CSharp/RimWorld.BaseGen/SymbolStack.cs @@ -1,4 +1,3 @@ -using System; using System.Collections.Generic; using Verse; diff --git a/Assembly-CSharp/RimWorld.Planet/Caravan.cs b/Assembly-CSharp/RimWorld.Planet/Caravan.cs index bf993bb82..25ba203f4 100644 --- a/Assembly-CSharp/RimWorld.Planet/Caravan.cs +++ b/Assembly-CSharp/RimWorld.Planet/Caravan.cs @@ -1,6 +1,6 @@ using System; using System.Collections.Generic; -using System.Diagnostics; +using System.Linq; using System.Text; using UnityEngine; using Verse; @@ -62,22 +62,10 @@ public override Material Material { get { - if (this.cachedMat == null) + if ((UnityEngine.Object)this.cachedMat == (UnityEngine.Object)null) { - Color color; - if (base.Faction == null) - { - color = Color.white; - } - else if (base.Faction.IsPlayer) - { - color = Caravan.PlayerCaravanColor; - } - else - { - color = base.Faction.Color; - } - this.cachedMat = MaterialPool.MatFrom(this.def.texture, ShaderDatabase.WorldOverlayTransparentLit, color, WorldMaterials.DynamicObjectRenderQueue); + Color color = (base.Faction != null) ? ((!base.Faction.IsPlayer) ? base.Faction.Color : Caravan.PlayerCaravanColor) : Color.white; + this.cachedMat = MaterialPool.MatFrom(base.def.texture, ShaderDatabase.WorldOverlayTransparentLit, color, WorldMaterials.DynamicObjectRenderQueue); } return this.cachedMat; } @@ -151,7 +139,7 @@ public float MassCapacity { get { - return CollectionsMassCalculator.Capacity(this.PawnsListForReading); + return CollectionsMassCalculator.Capacity(this.PawnsListForReading); } } @@ -159,7 +147,7 @@ public float MassUsage { get { - return CollectionsMassCalculator.MassUsage(this.PawnsListForReading, IgnorePawnsInventoryMode.DontIgnore, false, false); + return CollectionsMassCalculator.MassUsage(this.PawnsListForReading, IgnorePawnsInventoryMode.DontIgnore, false, false); } } @@ -371,23 +359,23 @@ public override void ExposeData() base.ExposeData(); if (Scribe.mode == LoadSaveMode.Saving) { - this.pawns.RemoveAll((Pawn x) => x.Destroyed); + this.pawns.RemoveAll((Predicate)((Pawn x) => x.Destroyed)); } - Scribe_Values.Look(ref this.nameInt, "name", null, false); - Scribe_Deep.Look>(ref this.pawns, "pawns", new object[] + Scribe_Values.Look(ref this.nameInt, "name", (string)null, false); + Scribe_Deep.Look>(ref this.pawns, "pawns", new object[1] { this }); Scribe_Values.Look(ref this.autoJoinable, "autoJoinable", false, false); - Scribe_Deep.Look(ref this.pather, "pather", new object[] + Scribe_Deep.Look(ref this.pather, "pather", new object[1] { this }); - Scribe_Deep.Look(ref this.trader, "trader", new object[] + Scribe_Deep.Look(ref this.trader, "trader", new object[1] { this }); - Scribe_Deep.Look(ref this.storyState, "storyState", new object[] + Scribe_Deep.Look(ref this.storyState, "storyState", new object[1] { this }); @@ -448,21 +436,12 @@ public void AddPawn(Pawn p, bool addCarriedPawnToWorldPawnsIfAny) if (p == null) { Log.Warning("Tried to add a null pawn to " + this); - return; } - if (p.Dead) + else if (p.Dead) { - Log.Warning(string.Concat(new object[] - { - "Tried to add ", - p, - " to ", - this, - ", but this pawn is dead." - })); - return; + Log.Warning("Tried to add " + p + " to " + this + ", but this pawn is dead."); } - if (this.pawns.TryAdd(p, true)) + else if (this.pawns.TryAdd(p, true)) { Pawn pawn = p.carryTracker.CarriedThing as Pawn; if (pawn != null) @@ -526,10 +505,7 @@ public override string GetInspectString() } else if (this.AnyPawnHasExtremeMentalBreak) { - stringBuilder.Append("CaravanMemberMentalBreak".Translate(new object[] - { - this.FirstPawnWithExtremeMentalBreak.LabelShort - })); + stringBuilder.Append("CaravanMemberMentalBreak".Translate(this.FirstPawnWithExtremeMentalBreak.LabelShort)); } else if (this.AllOwnersDowned) { @@ -555,10 +531,7 @@ public override string GetInspectString() Settlement settlement = CaravanVisitUtility.SettlementVisitedNow(this); if (settlement != null) { - stringBuilder.Append("CaravanVisiting".Translate(new object[] - { - settlement.Label - })); + stringBuilder.Append("CaravanVisiting".Translate(settlement.Label)); } else { @@ -567,19 +540,16 @@ public override string GetInspectString() } if (this.pather.Moving) { - float num = (float)CaravanArrivalTimeEstimator.EstimatedTicksToArrive(this, true) / 60000f; + float num = (float)((float)CaravanArrivalTimeEstimator.EstimatedTicksToArrive(this, true) / 60000.0); stringBuilder.AppendLine(); - stringBuilder.Append("CaravanEstimatedTimeToDestination".Translate(new object[] - { - num.ToString("0.#") - })); + stringBuilder.Append("CaravanEstimatedTimeToDestination".Translate(num.ToString("0.#"))); } if (this.ImmobilizedByMass) { stringBuilder.AppendLine(); stringBuilder.Append("CaravanImmobilizedByMass".Translate()); } - string text; + string text = default(string); if (CaravanPawnsNeedsUtility.AnyPawnOutOfFood(this, out text)) { stringBuilder.AppendLine(); @@ -591,47 +561,154 @@ public override string GetInspectString() stringBuilder.Append("."); } } - else if (this.DaysWorthOfFood.First < 1000f) + else if (this.DaysWorthOfFood.First < 1000.0) { Pair daysWorthOfFood = this.DaysWorthOfFood; stringBuilder.AppendLine(); - if (daysWorthOfFood.Second < 1000f) + if (daysWorthOfFood.Second < 1000.0) { - stringBuilder.Append("CaravanDaysOfFoodRot".Translate(new object[] - { - daysWorthOfFood.First.ToString("0.#"), - daysWorthOfFood.Second.ToString("0.#") - })); + stringBuilder.Append("CaravanDaysOfFoodRot".Translate(daysWorthOfFood.First.ToString("0.#"), daysWorthOfFood.Second.ToString("0.#"))); } else { - stringBuilder.Append("CaravanDaysOfFood".Translate(new object[] - { - daysWorthOfFood.First.ToString("0.#") - })); + stringBuilder.Append("CaravanDaysOfFood".Translate(daysWorthOfFood.First.ToString("0.#"))); } } stringBuilder.AppendLine(); - stringBuilder.AppendLine(string.Concat(new string[] - { - "CaravanBaseMovementTime".Translate(), - ": ", - ((float)this.TicksPerMove / 2500f).ToString("0.##"), - " ", - "CaravanHoursPerTile".Translate() - })); + stringBuilder.AppendLine("CaravanBaseMovementTime".Translate() + ": " + ((float)((float)this.TicksPerMove / 2500.0)).ToString("0.##") + " " + "CaravanHoursPerTile".Translate()); stringBuilder.Append("CurrentTileMovementTime".Translate() + ": " + Caravan_PathFollower.CostToDisplay(this, base.Tile, this.pather.nextTile, -1f).ToStringTicksToPeriod(true, false, true)); return stringBuilder.ToString(); } - [DebuggerHidden] public override IEnumerable GetGizmos() { - Caravan.c__IteratorFF c__IteratorFF = new Caravan.c__IteratorFF(); - c__IteratorFF.<>f__this = this; - Caravan.c__IteratorFF expr_0E = c__IteratorFF; - expr_0E.$PC = -2; - return expr_0E; + foreach (Gizmo gizmo in base.GetGizmos()) + { + yield return gizmo; + } + if (this.IsPlayerControlled) + { + if (CaravanMergeUtility.CanMergeAnySelectedCaravans) + { + yield return (Gizmo)CaravanMergeUtility.MergeCommand(this); + } + if (Find.WorldSelector.SingleSelectedObject == this && this.PawnsListForReading.Count((Func)((Pawn x) => x.IsColonist)) >= 2) + { + yield return (Gizmo)new Command_Action + { + defaultLabel = "CommandSplitCaravan".Translate(), + defaultDesc = "CommandSplitCaravanDesc".Translate(), + icon = Caravan.SplitCommand, + action = (Action)delegate + { + Find.WindowStack.Add(new Dialog_SplitCaravan(((_003CGetGizmos_003Ec__IteratorFF)/*Error near IL_01a0: stateMachine*/)._003C_003Ef__this)); + } + }; + } + if (Find.WorldSelector.SingleSelectedObject == this) + { + yield return (Gizmo)SettleInEmptyTileUtility.SettleCommand(this); + } + Settlement settlementVisitedNow = CaravanVisitUtility.SettlementVisitedNow(this); + if (settlementVisitedNow != null && settlementVisitedNow.CanTradeNow) + { + yield return (Gizmo)CaravanVisitUtility.TradeCommand(this); + } + if (settlementVisitedNow != null && ((WorldObject)settlementVisitedNow).GetComponent() != null && ((WorldObject)settlementVisitedNow).GetComponent().ActiveRequest) + { + yield return (Gizmo)CaravanVisitUtility.FulfillRequestCommand(this); + } + if (CaravanJourneyDestinationUtility.AnyJurneyDestinationAt(base.Tile)) + { + yield return (Gizmo)CaravanJourneyDestinationUtility.TakeOffCommand(base.Tile); + } + } + if (Prefs.DevMode) + { + yield return (Gizmo)new Command_Action + { + defaultLabel = "Dev: Mental break", + action = (Action)delegate() + { + Pawn pawn6 = default(Pawn); + if ((from x in ((_003CGetGizmos_003Ec__IteratorFF)/*Error near IL_02f3: stateMachine*/)._003C_003Ef__this.PawnsListForReading + where x.RaceProps.Humanlike && !x.InMentalState + select x).TryRandomElement(out pawn6)) + { + pawn6.mindState.mentalStateHandler.TryStartMentalState(MentalStateDefOf.WanderSad, (string)null, false, false, null); + } + } + }; + yield return (Gizmo)new Command_Action + { + defaultLabel = "Dev: Extreme mental break", + action = (Action)delegate() + { + Pawn pawn5 = default(Pawn); + if ((from x in ((_003CGetGizmos_003Ec__IteratorFF)/*Error near IL_033d: stateMachine*/)._003C_003Ef__this.PawnsListForReading + where x.RaceProps.Humanlike && !x.InMentalState + select x).TryRandomElement(out pawn5)) + { + pawn5.mindState.mentalStateHandler.TryStartMentalState(MentalStateDefOf.Berserk, (string)null, false, false, null); + } + } + }; + yield return (Gizmo)new Command_Action + { + defaultLabel = "Dev: Make random pawn hungry", + action = (Action)delegate() + { + Pawn pawn4 = default(Pawn); + if ((from x in ((_003CGetGizmos_003Ec__IteratorFF)/*Error near IL_0388: stateMachine*/)._003C_003Ef__this.PawnsListForReading + where x.needs.food != null + select x).TryRandomElement(out pawn4)) + { + pawn4.needs.food.CurLevelPercentage = 0f; + } + } + }; + yield return (Gizmo)new Command_Action + { + defaultLabel = "Dev: Kill random pawn", + action = (Action)delegate + { + Pawn pawn3 = default(Pawn); + if (((IEnumerable)((_003CGetGizmos_003Ec__IteratorFF)/*Error near IL_03d3: stateMachine*/)._003C_003Ef__this.PawnsListForReading).TryRandomElement(out pawn3)) + { + pawn3.Kill(default(DamageInfo?)); + Messages.Message("Dev: Killed " + pawn3.LabelShort, (WorldObject)((_003CGetGizmos_003Ec__IteratorFF)/*Error near IL_03d3: stateMachine*/)._003C_003Ef__this, MessageSound.Benefit); + } + } + }; + yield return (Gizmo)new Command_Action + { + defaultLabel = "Dev: Harm random pawn", + action = (Action)delegate + { + Pawn pawn2 = default(Pawn); + if (((IEnumerable)((_003CGetGizmos_003Ec__IteratorFF)/*Error near IL_041e: stateMachine*/)._003C_003Ef__this.PawnsListForReading).TryRandomElement(out pawn2)) + { + DamageInfo dinfo = new DamageInfo(DamageDefOf.Scratch, 10, -1f, null, null, null, DamageInfo.SourceCategory.ThingOrUnknown); + pawn2.TakeDamage(dinfo); + } + } + }; + yield return (Gizmo)new Command_Action + { + defaultLabel = "Dev: Down random pawn", + action = (Action)delegate() + { + Pawn pawn = default(Pawn); + if ((from x in ((_003CGetGizmos_003Ec__IteratorFF)/*Error near IL_0469: stateMachine*/)._003C_003Ef__this.PawnsListForReading + where !x.Downed + select x).TryRandomElement(out pawn)) + { + HealthUtility.DamageUntilDowned(pawn); + Messages.Message("Dev: Downed " + pawn.LabelShort, (WorldObject)((_003CGetGizmos_003Ec__IteratorFF)/*Error near IL_0469: stateMachine*/)._003C_003Ef__this, MessageSound.Benefit); + } + } + }; + } } public void RecacheImmobilizedNow() @@ -646,12 +723,12 @@ public void RecacheDaysWorthOfFood() public virtual void Notify_MemberDied(Pawn member) { - if (!this.PawnsListForReading.Any((Pawn x) => x != member && this.IsOwner(x))) + if (!this.PawnsListForReading.Any((Predicate)((Pawn x) => x != member && this.IsOwner(x)))) { this.RemovePawn(member); if (base.Faction == Faction.OfPlayer) { - Find.LetterStack.ReceiveLetter("LetterLabelAllCaravanColonistsDied".Translate(), "LetterAllCaravanColonistsDied".Translate(), LetterDefOf.BadNonUrgent, new GlobalTargetInfo(base.Tile), null); + Find.LetterStack.ReceiveLetter("LetterLabelAllCaravanColonistsDied".Translate(), "LetterAllCaravanColonistsDied".Translate(), LetterDefOf.BadNonUrgent, new GlobalTargetInfo(base.Tile), (string)null); } this.RemoveAllPawnsAndDiscardIfUnimportant(); Find.WorldObjects.Remove(this); @@ -665,12 +742,12 @@ public virtual void Notify_MemberDied(Pawn member) private void CheckAnyNonWorldPawns() { - for (int i = this.pawns.Count - 1; i >= 0; i--) + for (int num = this.pawns.Count - 1; num >= 0; num--) { - if (!this.pawns[i].IsWorldPawn()) + if (!this.pawns[num].IsWorldPawn()) { - Log.Error("Caravan member " + this.pawns[i] + " is not a world pawn. Removing..."); - this.pawns.Remove(this.pawns[i]); + Log.Error("Caravan member " + this.pawns[num] + " is not a world pawn. Removing..."); + this.pawns.Remove(this.pawns[num]); } } } @@ -704,14 +781,32 @@ virtual IThingHolder get_ParentHolder() return base.ParentHolder; } + IThingHolder IThingHolder.get_ParentHolder() + { + //ILSpy generated this explicit interface implementation from .override directive in get_ParentHolder + return this.get_ParentHolder(); + } + virtual int get_Tile() { return base.Tile; } + int IIncidentTarget.get_Tile() + { + //ILSpy generated this explicit interface implementation from .override directive in get_Tile + return this.get_Tile(); + } + virtual Faction get_Faction() { return base.Faction; } + + Faction ITrader.get_Faction() + { + //ILSpy generated this explicit interface implementation from .override directive in get_Faction + return this.get_Faction(); + } } } diff --git a/Assembly-CSharp/RimWorld.Planet/CaravanArrivalAction.cs b/Assembly-CSharp/RimWorld.Planet/CaravanArrivalAction.cs index c5fdff623..ebbc36d34 100644 --- a/Assembly-CSharp/RimWorld.Planet/CaravanArrivalAction.cs +++ b/Assembly-CSharp/RimWorld.Planet/CaravanArrivalAction.cs @@ -1,4 +1,3 @@ -using System; using Verse; namespace RimWorld.Planet diff --git a/Assembly-CSharp/RimWorld.Planet/CaravanArrivalAction_AttackSettlement.cs b/Assembly-CSharp/RimWorld.Planet/CaravanArrivalAction_AttackSettlement.cs index d9d4ea0aa..5bdb4ff43 100644 --- a/Assembly-CSharp/RimWorld.Planet/CaravanArrivalAction_AttackSettlement.cs +++ b/Assembly-CSharp/RimWorld.Planet/CaravanArrivalAction_AttackSettlement.cs @@ -11,10 +11,7 @@ public override string ReportString { get { - return "CaravanAttacking".Translate(new object[] - { - this.settlement.Label - }); + return "CaravanAttacking".Translate(this.settlement.Label); } } @@ -39,7 +36,7 @@ public override void Arrived(Caravan caravan) { if (!this.settlement.HasMap) { - LongEventHandler.QueueLongEvent(delegate + LongEventHandler.QueueLongEvent((Action)delegate() { this.DoArrivalAction(caravan); }, "GeneratingMapForNewEncounter", false, null); @@ -65,20 +62,11 @@ private void DoArrivalAction(Caravan caravan) if (!this.settlement.Faction.HostileTo(Faction.OfPlayer)) { this.settlement.Faction.SetHostileTo(Faction.OfPlayer, true); - Find.LetterStack.ReceiveLetter("LetterLabelCaravanEnteredEnemyBase".Translate(), "LetterCaravanEnteredEnemyBaseBecameHostile".Translate(new object[] - { - caravan.Label, - this.settlement.Label, - this.settlement.Faction.Name - }).CapitalizeFirst(), LetterDefOf.Good, t, null); + Find.LetterStack.ReceiveLetter("LetterLabelCaravanEnteredEnemyBase".Translate(), "LetterCaravanEnteredEnemyBaseBecameHostile".Translate(caravan.Label, this.settlement.Label, this.settlement.Faction.Name).CapitalizeFirst(), LetterDefOf.Good, (Thing)t, (string)null); } else { - Find.LetterStack.ReceiveLetter("LetterLabelCaravanEnteredEnemyBase".Translate(), "LetterCaravanEnteredEnemyBase".Translate(new object[] - { - caravan.Label, - this.settlement.Label - }).CapitalizeFirst(), LetterDefOf.Good, t, null); + Find.LetterStack.ReceiveLetter("LetterLabelCaravanEnteredEnemyBase".Translate(), "LetterCaravanEnteredEnemyBase".Translate(caravan.Label, this.settlement.Label).CapitalizeFirst(), LetterDefOf.Good, (Thing)t, (string)null); } } } diff --git a/Assembly-CSharp/RimWorld.Planet/CaravanArrivalAction_Enter.cs b/Assembly-CSharp/RimWorld.Planet/CaravanArrivalAction_Enter.cs index ed1b5c4b1..2d3ca3e91 100644 --- a/Assembly-CSharp/RimWorld.Planet/CaravanArrivalAction_Enter.cs +++ b/Assembly-CSharp/RimWorld.Planet/CaravanArrivalAction_Enter.cs @@ -1,4 +1,3 @@ -using System; using Verse; namespace RimWorld.Planet @@ -11,10 +10,7 @@ public override string ReportString { get { - return "CaravanEntering".Translate(new object[] - { - this.mapParent.Label - }); + return "CaravanEntering".Translate(this.mapParent.Label); } } @@ -38,29 +34,23 @@ public CaravanArrivalAction_Enter(MapParent mapParent) public override void Arrived(Caravan caravan) { Map map = this.mapParent.Map; - if (map == null) - { - return; - } - Pawn t = caravan.PawnsListForReading[0]; - CaravanDropInventoryMode dropInventoryMode = (!map.IsPlayerHome) ? CaravanDropInventoryMode.DoNotDrop : CaravanDropInventoryMode.UnloadIndividually; - bool draftColonists = this.mapParent.Faction != null && this.mapParent.Faction.HostileTo(Faction.OfPlayer); - CaravanEnterMapUtility.Enter(caravan, map, CaravanEnterMode.Edge, dropInventoryMode, draftColonists, null); - if (this.mapParent.def == WorldObjectDefOf.Ambush) + if (map != null) { - Find.TickManager.CurTimeSpeed = TimeSpeed.Paused; - Find.LetterStack.ReceiveLetter("LetterLabelCaravanEnteredAmbushMap".Translate(), "LetterCaravanEnteredAmbushMap".Translate(new object[] + Pawn t = caravan.PawnsListForReading[0]; + CaravanDropInventoryMode dropInventoryMode = (CaravanDropInventoryMode)(map.IsPlayerHome ? 2 : 0); + bool draftColonists = this.mapParent.Faction != null && this.mapParent.Faction.HostileTo(Faction.OfPlayer); + CaravanEnterMapUtility.Enter(caravan, map, CaravanEnterMode.Edge, dropInventoryMode, draftColonists, null); + if (this.mapParent.def == WorldObjectDefOf.Ambush) { - caravan.Label - }).CapitalizeFirst(), LetterDefOf.Good, t, null); - } - else if (caravan.IsPlayerControlled || this.mapParent.Faction == Faction.OfPlayer) - { - Messages.Message("MessageCaravanEnteredWorldObject".Translate(new object[] + Find.TickManager.CurTimeSpeed = TimeSpeed.Paused; + Find.LetterStack.ReceiveLetter("LetterLabelCaravanEnteredAmbushMap".Translate(), "LetterCaravanEnteredAmbushMap".Translate(caravan.Label).CapitalizeFirst(), LetterDefOf.Good, (Thing)t, (string)null); + } + else { - caravan.Label, - this.mapParent.Label - }).CapitalizeFirst(), t, MessageSound.Benefit); + if (!caravan.IsPlayerControlled && this.mapParent.Faction != Faction.OfPlayer) + return; + Messages.Message("MessageCaravanEnteredWorldObject".Translate(caravan.Label, this.mapParent.Label).CapitalizeFirst(), (Thing)t, MessageSound.Benefit); + } } } diff --git a/Assembly-CSharp/RimWorld.Planet/CaravanArrivalAction_VisitSettlement.cs b/Assembly-CSharp/RimWorld.Planet/CaravanArrivalAction_VisitSettlement.cs index f0b0a55d0..240aa8f5c 100644 --- a/Assembly-CSharp/RimWorld.Planet/CaravanArrivalAction_VisitSettlement.cs +++ b/Assembly-CSharp/RimWorld.Planet/CaravanArrivalAction_VisitSettlement.cs @@ -1,4 +1,3 @@ -using System; using Verse; namespace RimWorld.Planet @@ -11,10 +10,7 @@ public override string ReportString { get { - return "CaravanVisiting".Translate(new object[] - { - this.settlement.Label - }); + return "CaravanVisiting".Translate(this.settlement.Label); } } @@ -39,11 +35,7 @@ public override void Arrived(Caravan caravan) { if (caravan.IsPlayerControlled) { - Messages.Message("MessageCaravanIsVisitingSettlement".Translate(new object[] - { - caravan.Label, - this.settlement.Label - }).CapitalizeFirst(), caravan, MessageSound.Benefit); + Messages.Message("MessageCaravanIsVisitingSettlement".Translate(caravan.Label, this.settlement.Label).CapitalizeFirst(), (WorldObject)caravan, MessageSound.Benefit); } } diff --git a/Assembly-CSharp/RimWorld.Planet/CaravanArrivalAction_VisitSite.cs b/Assembly-CSharp/RimWorld.Planet/CaravanArrivalAction_VisitSite.cs index bbf3159e0..b9908c2f0 100644 --- a/Assembly-CSharp/RimWorld.Planet/CaravanArrivalAction_VisitSite.cs +++ b/Assembly-CSharp/RimWorld.Planet/CaravanArrivalAction_VisitSite.cs @@ -1,4 +1,3 @@ -using System; using Verse; namespace RimWorld.Planet @@ -11,13 +10,7 @@ public override string ReportString { get { - return (!this.site.KnownDanger) ? "CaravanVisiting".Translate(new object[] - { - this.site.Label - }) : "CaravanAttacking".Translate(new object[] - { - this.site.Label - }); + return (!this.site.KnownDanger) ? "CaravanVisiting".Translate(this.site.Label) : "CaravanAttacking".Translate(this.site.Label); } } diff --git a/Assembly-CSharp/RimWorld.Planet/CaravanArrivalTimeEstimator.cs b/Assembly-CSharp/RimWorld.Planet/CaravanArrivalTimeEstimator.cs index 42c347f9e..b986d7f79 100644 --- a/Assembly-CSharp/RimWorld.Planet/CaravanArrivalTimeEstimator.cs +++ b/Assembly-CSharp/RimWorld.Planet/CaravanArrivalTimeEstimator.cs @@ -1,4 +1,3 @@ -using System; using UnityEngine; using Verse; @@ -48,19 +47,17 @@ public static int EstimatedTicksToArrive(Caravan caravan, bool allowCaching) public static int EstimatedTicksToArrive(int from, int to, Caravan caravan) { - int result; using (WorldPath worldPath = Find.WorldPathFinder.FindPath(from, to, caravan, null)) { if (worldPath == WorldPath.NotFound) { - result = 0; - } - else - { - result = CaravanArrivalTimeEstimator.EstimatedTicksToArrive(from, to, worldPath, 0f, CaravanTicksPerMoveUtility.GetTicksPerMove(caravan), Find.TickManager.TicksAbs); + return 0; } + return CaravanArrivalTimeEstimator.EstimatedTicksToArrive(from, to, worldPath, 0f, CaravanTicksPerMoveUtility.GetTicksPerMove(caravan), Find.TickManager.TicksAbs); + IL_0044: + int result; + return result; } - return result; } public static int EstimatedTicksToArrive(int from, int to, WorldPath path, float nextTileCostLeft, int caravanTicksPerMove, int curTicksAbs) @@ -73,27 +70,28 @@ public static int EstimatedTicksToArrive(int from, int to, WorldPath path, float int num6 = 0; int num7 = 0; int num8; - if (CaravanRestUtility.WouldBeRestingAt(from, (long)curTicksAbs)) + if (CaravanRestUtility.WouldBeRestingAt(from, curTicksAbs)) { - num += CaravanRestUtility.LeftRestTicksAt(from, (long)curTicksAbs); + num += CaravanRestUtility.LeftRestTicksAt(from, curTicksAbs); num8 = num5; } else { - num8 = CaravanRestUtility.LeftNonRestTicksAt(from, (long)curTicksAbs); + num8 = CaravanRestUtility.LeftNonRestTicksAt(from, curTicksAbs); } while (true) { num7++; if (num7 >= 10000) { - break; + Log.ErrorOnce("Could not calculate estimated ticks to arrive. Too many iterations.", 1837451324); + return num; } if (num6 <= 0) { if (num2 == to) { - return num; + break; } bool flag = num3 == 0; int start = num2; @@ -107,10 +105,10 @@ public static int EstimatedTicksToArrive(int from, int to, WorldPath path, float else { int num10 = curTicksAbs + num; - float yearPercent = (float)GenDate.DayOfYear((long)num10, 0f) / 60f; + float yearPercent = (float)((float)GenDate.DayOfYear(num10, 0f) / 60.0); num9 = (float)Caravan_PathFollower.CostToMove(caravanTicksPerMove, start, num2, yearPercent); } - num6 = Mathf.CeilToInt(num9 / 1f); + num6 = Mathf.CeilToInt((float)(num9 / 1.0)); } if (num8 < num6) { @@ -126,7 +124,6 @@ public static int EstimatedTicksToArrive(int from, int to, WorldPath path, float num6 = 0; } } - Log.ErrorOnce("Could not calculate estimated ticks to arrive. Too many iterations.", 1837451324); return num; } } diff --git a/Assembly-CSharp/RimWorld.Planet/CaravanDropInventoryMode.cs b/Assembly-CSharp/RimWorld.Planet/CaravanDropInventoryMode.cs index 269a39792..cc94d53a8 100644 --- a/Assembly-CSharp/RimWorld.Planet/CaravanDropInventoryMode.cs +++ b/Assembly-CSharp/RimWorld.Planet/CaravanDropInventoryMode.cs @@ -1,11 +1,9 @@ -using System; - namespace RimWorld.Planet { public enum CaravanDropInventoryMode { - DoNotDrop, - DropInstantly, - UnloadIndividually + DoNotDrop = 0, + DropInstantly = 1, + UnloadIndividually = 2 } } diff --git a/Assembly-CSharp/RimWorld.Planet/CaravanDrugPolicyUtility.cs b/Assembly-CSharp/RimWorld.Planet/CaravanDrugPolicyUtility.cs index 623d28a93..97123fd75 100644 --- a/Assembly-CSharp/RimWorld.Planet/CaravanDrugPolicyUtility.cs +++ b/Assembly-CSharp/RimWorld.Planet/CaravanDrugPolicyUtility.cs @@ -1,4 +1,3 @@ -using System; using System.Collections.Generic; using Verse; @@ -17,18 +16,14 @@ public static void TryTakeScheduledDrugs(Caravan caravan) private static void TryTakeScheduledDrugs(Pawn pawn, Caravan caravan) { - if (pawn.drugs == null) + if (pawn.drugs != null) { - return; - } - DrugPolicy currentPolicy = pawn.drugs.CurrentPolicy; - for (int i = 0; i < currentPolicy.Count; i++) - { - if (pawn.drugs.ShouldTryToTakeScheduledNow(currentPolicy[i].drug)) + DrugPolicy currentPolicy = pawn.drugs.CurrentPolicy; + for (int i = 0; i < currentPolicy.Count; i++) { - Thing drug; - Pawn drugOwner; - if (CaravanInventoryUtility.TryGetThingOfDef(caravan, currentPolicy[i].drug, out drug, out drugOwner)) + Thing drug = default(Thing); + Pawn drugOwner = default(Pawn); + if (pawn.drugs.ShouldTryToTakeScheduledNow(currentPolicy[i].drug) && CaravanInventoryUtility.TryGetThingOfDef(caravan, currentPolicy[i].drug, out drug, out drugOwner)) { CaravanPawnsNeedsUtility.IngestDrug(pawn, drug, drugOwner, caravan); } diff --git a/Assembly-CSharp/RimWorld.Planet/CaravanEnterMapUtility.cs b/Assembly-CSharp/RimWorld.Planet/CaravanEnterMapUtility.cs index 622046fde..022225703 100644 --- a/Assembly-CSharp/RimWorld.Planet/CaravanEnterMapUtility.cs +++ b/Assembly-CSharp/RimWorld.Planet/CaravanEnterMapUtility.cs @@ -12,19 +12,11 @@ public static void Enter(Caravan caravan, Map map, CaravanEnterMode enterMode, C { if (enterMode == CaravanEnterMode.None) { - Log.Error(string.Concat(new object[] - { - "Caravan ", - caravan, - " tried to enter map ", - map, - " with enter mode ", - enterMode - })); + Log.Error("Caravan " + caravan + " tried to enter map " + map + " with enter mode " + enterMode); enterMode = CaravanEnterMode.Edge; } IntVec3 enterCell = CaravanEnterMapUtility.GetEnterCell(caravan, map, enterMode, extraCellValidator); - Func spawnCellGetter = (Pawn p) => CellFinder.RandomSpawnCellForPawnNear(enterCell, map, 4); + Func spawnCellGetter = (Func)((Pawn p) => CellFinder.RandomSpawnCellForPawnNear(enterCell, map, 4)); CaravanEnterMapUtility.Enter(caravan, map, spawnCellGetter, dropInventoryMode, draftColonists); } @@ -37,16 +29,21 @@ public static void Enter(Caravan caravan, Map map, Func spawnCell IntVec3 loc = spawnCellGetter(CaravanEnterMapUtility.tmpPawns[i]); GenSpawn.Spawn(CaravanEnterMapUtility.tmpPawns[i], loc, map, Rot4.Random, false); } - if (dropInventoryMode == CaravanDropInventoryMode.DropInstantly) + switch (dropInventoryMode) + { + case CaravanDropInventoryMode.DropInstantly: { CaravanEnterMapUtility.DropAllInventory(CaravanEnterMapUtility.tmpPawns); + break; } - else if (dropInventoryMode == CaravanDropInventoryMode.UnloadIndividually) + case CaravanDropInventoryMode.UnloadIndividually: { for (int j = 0; j < CaravanEnterMapUtility.tmpPawns.Count; j++) { CaravanEnterMapUtility.tmpPawns[j].inventory.UnloadEverything = true; } + break; + } } if (draftColonists) { @@ -72,22 +69,28 @@ public static void Enter(Caravan caravan, Map map, Func spawnCell private static IntVec3 GetEnterCell(Caravan caravan, Map map, CaravanEnterMode enterMode, Predicate extraCellValidator) { - if (enterMode == CaravanEnterMode.Edge) + switch (enterMode) + { + case CaravanEnterMode.Edge: { return CaravanEnterMapUtility.FindNearEdgeCell(map, extraCellValidator); } - if (enterMode != CaravanEnterMode.Center) + case CaravanEnterMode.Center: + { + return CaravanEnterMapUtility.FindCenterCell(map, extraCellValidator); + } + default: { throw new NotImplementedException("CaravanEnterMode"); } - return CaravanEnterMapUtility.FindCenterCell(map, extraCellValidator); + } } private static IntVec3 FindNearEdgeCell(Map map, Predicate extraCellValidator) { - Predicate baseValidator = (IntVec3 x) => x.Standable(map) && !x.Fogged(map); - IntVec3 root; - if (extraCellValidator != null && CellFinder.TryFindRandomEdgeCellWith((IntVec3 x) => baseValidator(x) && extraCellValidator(x), map, CellFinder.EdgeRoadChance_Neutral, out root)) + Predicate baseValidator = (Predicate)((IntVec3 x) => x.Standable(map) && !x.Fogged(map)); + IntVec3 root = default(IntVec3); + if ((object)extraCellValidator != null && CellFinder.TryFindRandomEdgeCellWith((Predicate)((IntVec3 x) => baseValidator(x) && extraCellValidator(x)), map, CellFinder.EdgeRoadChance_Neutral, out root)) { return CellFinder.RandomClosewalkCellNear(root, map, 5, null); } @@ -102,9 +105,9 @@ private static IntVec3 FindNearEdgeCell(Map map, Predicate extraCellVal private static IntVec3 FindCenterCell(Map map, Predicate extraCellValidator) { TraverseParms traverseParms = TraverseParms.For(TraverseMode.NoPassClosedDoors, Danger.Deadly, false); - Predicate baseValidator = (IntVec3 x) => x.Standable(map) && !x.Fogged(map) && map.reachability.CanReachMapEdge(x, traverseParms); - IntVec3 result; - if (extraCellValidator != null && RCellFinder.TryFindRandomCellNearTheCenterOfTheMapWith((IntVec3 x) => baseValidator(x) && extraCellValidator(x), map, out result)) + Predicate baseValidator = (Predicate)((IntVec3 x) => x.Standable(map) && !x.Fogged(map) && map.reachability.CanReachMapEdge(x, traverseParms)); + IntVec3 result = default(IntVec3); + if ((object)extraCellValidator != null && RCellFinder.TryFindRandomCellNearTheCenterOfTheMapWith((Predicate)((IntVec3 x) => baseValidator(x) && extraCellValidator(x)), map, out result)) { return result; } @@ -137,7 +140,7 @@ private static void DraftColonists(List pawns) private static bool TryRandomNonOccupiedClosewalkCellNear(IntVec3 root, Map map, int radius, out IntVec3 result) { - return CellFinder.TryFindRandomReachableCellNear(root, map, (float)radius, TraverseParms.For(TraverseMode.NoPassClosedDoors, Danger.Deadly, false), (IntVec3 c) => c.Standable(map) && c.GetFirstPawn(map) == null, null, out result, 999999); + return CellFinder.TryFindRandomReachableCellNear(root, map, (float)radius, TraverseParms.For(TraverseMode.NoPassClosedDoors, Danger.Deadly, false), (Predicate)((IntVec3 c) => c.Standable(map) && c.GetFirstPawn(map) == null), (Predicate)null, out result, 999999); } } } diff --git a/Assembly-CSharp/RimWorld.Planet/CaravanEnterMode.cs b/Assembly-CSharp/RimWorld.Planet/CaravanEnterMode.cs index bee2f6a6e..858a85f15 100644 --- a/Assembly-CSharp/RimWorld.Planet/CaravanEnterMode.cs +++ b/Assembly-CSharp/RimWorld.Planet/CaravanEnterMode.cs @@ -1,11 +1,9 @@ -using System; - namespace RimWorld.Planet { public enum CaravanEnterMode { - None, - Edge, - Center + None = 0, + Edge = 1, + Center = 2 } } diff --git a/Assembly-CSharp/RimWorld.Planet/CaravanExitMapUtility.cs b/Assembly-CSharp/RimWorld.Planet/CaravanExitMapUtility.cs index 78ecb0986..18f0c9b55 100644 --- a/Assembly-CSharp/RimWorld.Planet/CaravanExitMapUtility.cs +++ b/Assembly-CSharp/RimWorld.Planet/CaravanExitMapUtility.cs @@ -51,25 +51,28 @@ public static Caravan ExitMapAndCreateCaravan(IEnumerable pawns, Faction f CaravanExitMapUtility.tmpPawns.Clear(); CaravanExitMapUtility.tmpPawns.AddRange(pawns); Map map = null; - for (int i = 0; i < CaravanExitMapUtility.tmpPawns.Count; i++) + int num = 0; + while (num < CaravanExitMapUtility.tmpPawns.Count) { - map = CaravanExitMapUtility.tmpPawns[i].MapHeld; - if (map != null) + map = CaravanExitMapUtility.tmpPawns[num].MapHeld; + if (map == null) { - break; + num++; + continue; } + break; } Caravan caravan = CaravanMaker.MakeCaravan(CaravanExitMapUtility.tmpPawns, faction, startingTile, false); - for (int j = 0; j < CaravanExitMapUtility.tmpPawns.Count; j++) + for (int i = 0; i < CaravanExitMapUtility.tmpPawns.Count; i++) { - CaravanExitMapUtility.tmpPawns[j].ExitMap(false); + CaravanExitMapUtility.tmpPawns[i].ExitMap(false); } List pawnsListForReading = caravan.PawnsListForReading; - for (int k = 0; k < pawnsListForReading.Count; k++) + for (int j = 0; j < pawnsListForReading.Count; j++) { - if (!pawnsListForReading[k].IsWorldPawn()) + if (!pawnsListForReading[j].IsWorldPawn()) { - Find.WorldPawns.PassToWorld(pawnsListForReading[k], PawnDiscardDecideMode.Decide); + Find.WorldPawns.PassToWorld(pawnsListForReading[j], PawnDiscardDecideMode.Decide); } } if (map != null) @@ -91,14 +94,11 @@ public static void ExitMapAndJoinOrCreateCaravan(Pawn pawn) else if (pawn.IsColonist) { List list = CaravanExitMapUtility.AvailableExitTilesAt(pawn.Map); - Caravan caravan2 = CaravanExitMapUtility.ExitMapAndCreateCaravan(Gen.YieldSingle(pawn), pawn.Faction, pawn.Map.Tile, (!list.Any()) ? pawn.Map.Tile : list.RandomElement()); + Caravan caravan2 = CaravanExitMapUtility.ExitMapAndCreateCaravan(Gen.YieldSingle(pawn), pawn.Faction, pawn.Map.Tile, (!list.Any()) ? pawn.Map.Tile : list.RandomElement()); caravan2.autoJoinable = true; if (pawn.Faction == Faction.OfPlayer) { - Messages.Message("MessagePawnLeftMapAndCreatedCaravan".Translate(new object[] - { - pawn.LabelShort - }).CapitalizeFirst(), caravan2, MessageSound.Benefit); + Messages.Message("MessagePawnLeftMapAndCreatedCaravan".Translate(pawn.LabelShort).CapitalizeFirst(), (WorldObject)caravan2, MessageSound.Benefit); } } else @@ -109,7 +109,15 @@ public static void ExitMapAndJoinOrCreateCaravan(Pawn pawn) public static bool CanExitMapAndJoinOrCreateCaravanNow(Pawn pawn) { - return pawn.Spawned && pawn.Map.exitMapGrid.MapUsesExitGrid && (pawn.IsColonist || CaravanExitMapUtility.FindCaravanToJoinFor(pawn) != null); + if (!pawn.Spawned) + { + return false; + } + if (!pawn.Map.exitMapGrid.MapUsesExitGrid) + { + return false; + } + return pawn.IsColonist || CaravanExitMapUtility.FindCaravanToJoinFor(pawn) != null; } public static List AvailableExitTilesAt(Map map) @@ -125,48 +133,70 @@ public static List AvailableExitTilesAt(Map map) if (CaravanExitMapUtility.IsGoodCaravanStartingTile(num)) { Rot4 rotFromTo = grid.GetRotFromTo(currentTileID, num); - IntVec3 intVec; - if (CellFinder.TryFindRandomEdgeCellWith((IntVec3 x) => x.Walkable(map) && !x.Fogged(map), map, rotFromTo, CellFinder.EdgeRoadChance_Ignore, out intVec)) + IntVec3 intVec = default(IntVec3); + if (CellFinder.TryFindRandomEdgeCellWith((Predicate)((IntVec3 x) => x.Walkable(map) && !x.Fogged(map)), map, rotFromTo, CellFinder.EdgeRoadChance_Ignore, out intVec)) { CaravanExitMapUtility.retTiles.Add(num); } } } - CaravanExitMapUtility.retTiles.SortBy((int x) => grid.GetHeadingFromTo(currentTileID, x)); + CaravanExitMapUtility.retTiles.SortBy((Func)((int x) => grid.GetHeadingFromTo(currentTileID, x))); return CaravanExitMapUtility.retTiles; } public static int RandomBestExitTileFrom(Map map) { - CaravanExitMapUtility.c__AnonStorey388 c__AnonStorey = new CaravanExitMapUtility.c__AnonStorey388(); - c__AnonStorey.tile = map.TileInfo; - c__AnonStorey.options = CaravanExitMapUtility.AvailableExitTilesAt(map); - if (!c__AnonStorey.options.Any()) + Tile tile = map.TileInfo; + List options = CaravanExitMapUtility.AvailableExitTilesAt(map); + if (!options.Any()) { return -1; } - if (c__AnonStorey.tile.roads == null) + if (tile.roads == null) { - return c__AnonStorey.options.RandomElement(); + return options.RandomElement(); } int bestRoadIndex = -1; - for (int i = 0; i < c__AnonStorey.tile.roads.Count; i++) + for (int i = 0; i < tile.roads.Count; i++) { - if (c__AnonStorey.options.Contains(c__AnonStorey.tile.roads[i].neighbor)) + List obj = options; + Tile.RoadLink roadLink = tile.roads[i]; + if (obj.Contains(roadLink.neighbor)) { - if (bestRoadIndex == -1 || c__AnonStorey.tile.roads[i].road.priority > c__AnonStorey.tile.roads[bestRoadIndex].road.priority) + if (bestRoadIndex == -1) { - bestRoadIndex = i; + goto IL_00e9; } + Tile.RoadLink roadLink2 = tile.roads[i]; + int priority = roadLink2.road.priority; + Tile.RoadLink roadLink3 = tile.roads[bestRoadIndex]; + if (priority > roadLink3.road.priority) + goto IL_00e9; } + continue; + IL_00e9: + bestRoadIndex = i; } if (bestRoadIndex == -1) { - return c__AnonStorey.options.RandomElement(); + return options.RandomElement(); } - return (from rl in c__AnonStorey.tile.roads - where c__AnonStorey.options.Contains(rl.neighbor) && rl.road == c__AnonStorey.tile.roads[bestRoadIndex].road - select rl).RandomElement().neighbor; + Tile.RoadLink roadLink4 = tile.roads.Where((Func)delegate(Tile.RoadLink rl) + { + int result; + if (options.Contains(rl.neighbor)) + { + RoadDef road = rl.road; + Tile.RoadLink roadLink5 = tile.roads[bestRoadIndex]; + result = ((road == roadLink5.road) ? 1 : 0); + } + else + { + result = 0; + } + return (byte)result != 0; + }).RandomElement(); + return roadLink4.neighbor; } private static int FindRandomStartingTileBasedOnExitDir(int tileID, Direction8Way exitDir) @@ -187,14 +217,14 @@ private static int FindRandomStartingTileBasedOnExitDir(int tileID, Direction8Wa { return tileID; } - int result; + int result = default(int); if ((from x in CaravanExitMapUtility.tileCandidates where CaravanExitMapUtility.IsGoodCaravanStartingTile(x) - select x).TryRandomElement(out result)) + select x).TryRandomElement(out result)) { return result; } - return CaravanExitMapUtility.tileCandidates.RandomElement(); + return CaravanExitMapUtility.tileCandidates.RandomElement(); } private static bool IsGoodCaravanStartingTile(int tile) @@ -215,22 +245,19 @@ public static Caravan FindCaravanToJoinFor(Pawn pawn) for (int i = 0; i < caravans.Count; i++) { Caravan caravan = caravans[i]; - if (CaravanExitMapUtility.tmpNeighbors.Contains(caravan.Tile)) + if (CaravanExitMapUtility.tmpNeighbors.Contains(caravan.Tile) && caravan.autoJoinable) { - if (caravan.autoJoinable) + if (pawn.HostFaction == null) { - if (pawn.HostFaction == null) - { - if (caravan.Faction == pawn.Faction) - { - return caravan; - } - } - else if (caravan.Faction == pawn.HostFaction) + if (caravan.Faction == pawn.Faction) { return caravan; } } + else if (caravan.Faction == pawn.HostFaction) + { + return caravan; + } } } return null; @@ -250,41 +277,33 @@ public static bool IsTheOnlyJoinableCaravanForAnyPrisonerOrAnimal(Caravan c) } List maps = Find.Maps; List caravans = Find.WorldObjects.Caravans; - int i = 0; - while (i < maps.Count) + for (int i = 0; i < maps.Count; i++) { Map map = maps[i]; - if (!map.IsPlayerHome && Find.WorldGrid.IsNeighborOrSame(c.Tile, map.Tile) && map.mapPawns.FreeColonistsCount == 0) + if (!map.IsPlayerHome && Find.WorldGrid.IsNeighborOrSame(c.Tile, map.Tile) && map.mapPawns.FreeColonistsCount == 0 && map.mapPawns.AllPawns.Any((Func)((Pawn x) => x.Faction == Faction.OfPlayer || x.HostFaction == Faction.OfPlayer))) { - if (map.mapPawns.AllPawns.Any((Pawn x) => x.Faction == Faction.OfPlayer || x.HostFaction == Faction.OfPlayer)) + bool flag = false; + for (int j = 0; j < caravans.Count; j++) { - bool flag = false; - for (int j = 0; j < caravans.Count; j++) - { - Caravan caravan = caravans[j]; - if (c != caravan && caravan.autoJoinable && caravan.Faction == c.Faction && Find.WorldGrid.IsNeighborOrSame(caravan.Tile, map.Tile)) - { - flag = true; - break; - } - } - if (!flag) + Caravan caravan = caravans[j]; + if (c != caravan && caravan.autoJoinable && caravan.Faction == c.Faction && Find.WorldGrid.IsNeighborOrSame(caravan.Tile, map.Tile)) { - return true; + flag = true; + break; } } + if (!flag) + { + return true; + } } - IL_145: - i++; - continue; - goto IL_145; } return false; } public static void OpenTheOnlyJoinableCaravanForPrisonerOrAnimalDialog(Caravan c, Action confirmAction) { - Find.WindowStack.Add(Dialog_MessageBox.CreateConfirmation("ConfirmLeavePrisonersOrAnimalsBehind".Translate(), confirmAction, false, null)); + Find.WindowStack.Add(Dialog_MessageBox.CreateConfirmation("ConfirmLeavePrisonersOrAnimalsBehind".Translate(), confirmAction, false, (string)null)); } } } diff --git a/Assembly-CSharp/RimWorld.Planet/CaravanFormingUtility.cs b/Assembly-CSharp/RimWorld.Planet/CaravanFormingUtility.cs index ef9bd5c27..73f0055b5 100644 --- a/Assembly-CSharp/RimWorld.Planet/CaravanFormingUtility.cs +++ b/Assembly-CSharp/RimWorld.Planet/CaravanFormingUtility.cs @@ -16,7 +16,7 @@ public static class CaravanFormingUtility public static void FormAndCreateCaravan(IEnumerable pawns, Faction faction, int exitFromTile, int directionTile) { Caravan o = CaravanExitMapUtility.ExitMapAndCreateCaravan(pawns, faction, exitFromTile, directionTile); - Find.LetterStack.ReceiveLetter("LetterLabelFormedCaravan".Translate(), "LetterFormedCaravan".Translate(), LetterDefOf.Good, o, null); + Find.LetterStack.ReceiveLetter("LetterLabelFormedCaravan".Translate(), "LetterFormedCaravan".Translate(), LetterDefOf.Good, (WorldObject)o, (string)null); } public static void StartFormingCaravan(List pawns, Faction faction, List transferables, IntVec3 meetingPoint, IntVec3 exitSpot, int startingTile) @@ -24,35 +24,36 @@ public static void StartFormingCaravan(List pawns, Faction faction, List()) + else if (!pawns.Any()) { Log.Error("Can't start forming caravan with 0 pawns."); - return; } - if (pawns.Any((Pawn x) => x.Downed)) + else { - Log.Warning("Forming a caravan with a downed pawn. This shouldn't happen because we have to create a Lord."); - } - List list = transferables.ToList(); - list.RemoveAll((TransferableOneWay x) => x.CountToTransfer <= 0 || !x.HasAnyThing || x.AnyThing is Pawn); - for (int i = 0; i < pawns.Count; i++) - { - Lord lord = pawns[i].GetLord(); - if (lord != null) + if (pawns.Any((Predicate)((Pawn x) => x.Downed))) { - lord.Notify_PawnLost(pawns[i], PawnLostCondition.ForcedToJoinOtherLord); + Log.Warning("Forming a caravan with a downed pawn. This shouldn't happen because we have to create a Lord."); } - } - LordJob_FormAndSendCaravan lordJob = new LordJob_FormAndSendCaravan(list, meetingPoint, exitSpot, startingTile); - LordMaker.MakeNewLord(Faction.OfPlayer, lordJob, pawns[0].MapHeld, pawns); - for (int j = 0; j < pawns.Count; j++) - { - Pawn pawn = pawns[j]; - if (pawn.Spawned) + List list = transferables.ToList(); + list.RemoveAll((Predicate)((TransferableOneWay x) => x.CountToTransfer <= 0 || !x.HasAnyThing || x.AnyThing is Pawn)); + for (int i = 0; i < pawns.Count; i++) + { + Lord lord = pawns[i].GetLord(); + if (lord != null) + { + lord.Notify_PawnLost(pawns[i], PawnLostCondition.ForcedToJoinOtherLord); + } + } + LordJob_FormAndSendCaravan lordJob = new LordJob_FormAndSendCaravan(list, meetingPoint, exitSpot, startingTile); + LordMaker.MakeNewLord(Faction.OfPlayer, lordJob, pawns[0].MapHeld, pawns); + for (int j = 0; j < pawns.Count; j++) { - pawn.jobs.EndCurrentJob(JobCondition.InterruptForced, true); + Pawn pawn = pawns[j]; + if (pawn.Spawned) + { + pawn.jobs.EndCurrentJob(JobCondition.InterruptForced, true); + } } } } @@ -83,7 +84,7 @@ public static List AllReachableColonyItems(Map map, bool allowEvenIfOutsi for (int i = 0; i < allThings.Count; i++) { Thing thing = allThings[i]; - if (thing.def.category == ThingCategory.Item && (allowEvenIfOutsideHomeArea || map.areaManager.Home[thing.Position] || thing.IsInAnyStorage()) && (!thing.Position.Fogged(thing.Map) && (allowEvenIfReserved || !map.reservationManager.IsReserved(thing, Faction.OfPlayer))) && thing.def.EverHaulable) + if (thing.def.category == ThingCategory.Item && (allowEvenIfOutsideHomeArea || ((Area)map.areaManager.Home)[thing.Position] || thing.IsInAnyStorage()) && !thing.Position.Fogged(thing.Map) && (allowEvenIfReserved || !map.reservationManager.IsReserved(thing, Faction.OfPlayer)) && thing.def.EverHaulable) { CaravanFormingUtility.tmpReachableItems.Add(thing); } @@ -98,7 +99,7 @@ public static List AllSendablePawns(Map map, bool allowEvenIfDownedOrInMen for (int i = 0; i < allPawnsSpawned.Count; i++) { Pawn pawn = allPawnsSpawned[i]; - if ((allowEvenIfDownedOrInMentalState || !pawn.Downed) && (allowEvenIfDownedOrInMentalState || !pawn.InMentalState) && (!pawn.HostileTo(Faction.OfPlayer) && (pawn.Faction == Faction.OfPlayer || pawn.IsPrisonerOfColony)) && (allowEvenIfPrisonerNotSecure || !pawn.IsPrisoner || pawn.guest.PrisonerIsSecure) && (pawn.GetLord() == null || pawn.GetLord().LordJob is LordJob_VoluntarilyJoinable)) + if ((allowEvenIfDownedOrInMentalState || !pawn.Downed) && (allowEvenIfDownedOrInMentalState || !pawn.InMentalState) && !pawn.HostileTo(Faction.OfPlayer) && (pawn.Faction == Faction.OfPlayer || pawn.IsPrisonerOfColony) && (allowEvenIfPrisonerNotSecure || !pawn.IsPrisoner || pawn.guest.PrisonerIsSecure) && (pawn.GetLord() == null || pawn.GetLord().LordJob is LordJob_VoluntarilyJoinable)) { CaravanFormingUtility.tmpSendablePawns.Add(pawn); } diff --git a/Assembly-CSharp/RimWorld.Planet/CaravanIncidentUtility.cs b/Assembly-CSharp/RimWorld.Planet/CaravanIncidentUtility.cs index 3ab7b4c59..44936068d 100644 --- a/Assembly-CSharp/RimWorld.Planet/CaravanIncidentUtility.cs +++ b/Assembly-CSharp/RimWorld.Planet/CaravanIncidentUtility.cs @@ -34,7 +34,7 @@ public static float CalculateIncidentPoints(IEnumerable playerPawns) public static int CalculateIncidentMapSize(Caravan caravan) { float num = CaravanIncidentUtility.CalculateCaravanPawnsScore(caravan.PawnsListForReading); - int num2 = Mathf.RoundToInt(num * 900f); + int num2 = Mathf.RoundToInt((float)(num * 900.0)); return Mathf.Clamp(Mathf.RoundToInt(Mathf.Sqrt((float)num2)), 75, 110); } @@ -64,9 +64,9 @@ public static Map SetupCaravanAttackMap(Caravan caravan, List enemies) int num = CaravanIncidentUtility.CalculateIncidentMapSize(caravan); Map map = CaravanIncidentUtility.GetOrGenerateMapForIncident(caravan, new IntVec3(num, 1, num), WorldObjectDefOf.Ambush); IntVec3 playerStartingSpot; - IntVec3 root; + IntVec3 root = default(IntVec3); MultipleCaravansCellFinder.FindStartingCellsFor2Groups(map, out playerStartingSpot, out root); - CaravanEnterMapUtility.Enter(caravan, map, (Pawn x) => CellFinder.RandomSpawnCellForPawnNear(playerStartingSpot, map, 4), CaravanDropInventoryMode.DoNotDrop, true); + CaravanEnterMapUtility.Enter(caravan, map, (Func)((Pawn x) => CellFinder.RandomSpawnCellForPawnNear(playerStartingSpot, map, 4)), CaravanDropInventoryMode.DoNotDrop, true); for (int i = 0; i < enemies.Count; i++) { IntVec3 loc = CellFinder.RandomSpawnCellForPawnNear(root, map, 4); @@ -90,20 +90,9 @@ public static Map GetOrGenerateMapForIncident(Caravan caravan, IntVec3 size, Wor private static float CalculateCaravanPawnsScore(IEnumerable caravanPawns) { float num = 0f; - foreach (Pawn current in caravanPawns) + foreach (Pawn item in caravanPawns) { - if (current.IsColonist) - { - num += (current.Downed ? 0.35f : 1f); - } - else if (current.RaceProps.Humanlike) - { - num += 0.35f; - } - else - { - num += 0.2f * current.BodySize; - } + num = (float)((!item.IsColonist) ? ((!item.RaceProps.Humanlike) ? (num + 0.20000000298023224 * item.BodySize) : (num + 0.34999999403953552)) : (num + (item.Downed ? 0.34999999403953552 : 1.0))); } return num; } diff --git a/Assembly-CSharp/RimWorld.Planet/CaravanInventoryUtility.cs b/Assembly-CSharp/RimWorld.Planet/CaravanInventoryUtility.cs index 5776e79c3..05a19ed22 100644 --- a/Assembly-CSharp/RimWorld.Planet/CaravanInventoryUtility.cs +++ b/Assembly-CSharp/RimWorld.Planet/CaravanInventoryUtility.cs @@ -91,16 +91,10 @@ public static bool TryGetBestDrug(Caravan caravan, Pawn forPawn, Need_Chemical c if (thing2.IngestibleNow && thing2.def.IsDrug) { CompDrug compDrug = thing2.TryGetComp(); - if (compDrug != null && compDrug.Props.chemical != null) + if (compDrug != null && compDrug.Props.chemical != null && compDrug.Props.chemical.addictionHediff == addictionHediff.def && (forPawn.drugs == null || forPawn.drugs.CurrentPolicy[thing2.def].allowedForAddiction || forPawn.story == null || forPawn.story.traits.DegreeOfTrait(TraitDefOf.DrugDesire) > 0)) { - if (compDrug.Props.chemical.addictionHediff == addictionHediff.def) - { - if (forPawn.drugs == null || forPawn.drugs.CurrentPolicy[thing2.def].allowedForAddiction || forPawn.story == null || forPawn.story.traits.DegreeOfTrait(TraitDefOf.DrugDesire) > 0) - { - thing = thing2; - break; - } - } + thing = thing2; + break; } } } @@ -117,21 +111,15 @@ public static bool TryGetBestDrug(Caravan caravan, Pawn forPawn, Need_Chemical c public static bool TryGetBestMedicine(Caravan caravan, Pawn patient, out Medicine medicine, out Pawn owner) { - if (patient.playerSettings == null || patient.playerSettings.medCare <= MedicalCareCategory.NoMeds) - { - medicine = null; - owner = null; - return false; - } - List list = CaravanInventoryUtility.AllInventoryItems(caravan); - Medicine medicine2 = null; - float num = 0f; - for (int i = 0; i < list.Count; i++) + if (patient.playerSettings != null && (int)patient.playerSettings.medCare > 1) { - Thing thing = list[i]; - if (thing.def.IsMedicine) + List list = CaravanInventoryUtility.AllInventoryItems(caravan); + Medicine medicine2 = null; + float num = 0f; + for (int i = 0; i < list.Count; i++) { - if (patient.playerSettings.medCare.AllowsMedicine(thing.def)) + Thing thing = list[i]; + if (thing.def.IsMedicine && patient.playerSettings.medCare.AllowsMedicine(thing.def)) { float statValue = thing.GetStatValue(StatDefOf.MedicalPotency, true); if (statValue > num || medicine2 == null) @@ -141,12 +129,15 @@ public static bool TryGetBestMedicine(Caravan caravan, Pawn patient, out Medicin } } } - } - if (medicine2 != null) - { - medicine = medicine2; - owner = CaravanInventoryUtility.GetOwnerOf(caravan, medicine2); - return true; + if (medicine2 != null) + { + medicine = medicine2; + owner = CaravanInventoryUtility.GetOwnerOf(caravan, medicine2); + return true; + } + medicine = null; + owner = null; + return false; } medicine = null; owner = null; @@ -186,24 +177,16 @@ public static void MoveInventoryToSomeoneElse(Pawn itemOwner, Thing item, List

item.stackCount) { - Log.Warning(string.Concat(new object[] - { - "Tried to move item ", - item, - " with numToMove=", - numToMove, - " (item stack count = ", - item.stackCount, - ")" - })); - return; + Log.Warning("Tried to move item " + item + " with numToMove=" + numToMove + " (item stack count = " + item.stackCount + ")"); } - Pawn pawn = CaravanInventoryUtility.FindPawnToMoveInventoryTo(item, candidates, ignoreCandidates, itemOwner); - if (pawn == null) + else { - return; + Pawn pawn = CaravanInventoryUtility.FindPawnToMoveInventoryTo(item, candidates, ignoreCandidates, itemOwner); + if (pawn != null) + { + itemOwner.inventory.innerContainer.TryTransferToContainer(item, pawn.inventory.innerContainer, numToMove, true); + } } - itemOwner.inventory.innerContainer.TryTransferToContainer(item, pawn.inventory.innerContainer, numToMove, true); } public static Pawn FindPawnToMoveInventoryTo(Thing item, List candidates, List ignoreCandidates, Pawn currentItemOwner = null) @@ -213,22 +196,22 @@ public static Pawn FindPawnToMoveInventoryTo(Thing item, List candidates, Log.Error("Called FindPawnToMoveInventoryTo but the item is a pawn."); return null; } - Pawn result; + Pawn result = default(Pawn); if ((from x in candidates where CaravanInventoryUtility.CanMoveInventoryTo(x) && (ignoreCandidates == null || !ignoreCandidates.Contains(x)) && x != currentItemOwner && !MassUtility.IsOverEncumbered(x) - select x).TryRandomElement(out result)) + select x).TryRandomElement(out result)) { return result; } if ((from x in candidates where CaravanInventoryUtility.CanMoveInventoryTo(x) && (ignoreCandidates == null || !ignoreCandidates.Contains(x)) && x != currentItemOwner - select x).TryRandomElement(out result)) + select x).TryRandomElement(out result)) { return result; } if ((from x in candidates where (ignoreCandidates == null || !ignoreCandidates.Contains(x)) && x != currentItemOwner - select x).TryRandomElement(out result)) + select x).TryRandomElement(out result)) { return result; } @@ -237,42 +220,40 @@ where CaravanInventoryUtility.CanMoveInventoryTo(x) && (ignoreCandidates == null public static void MoveAllApparelToSomeonesInventory(Pawn moveFrom, List candidates) { - if (moveFrom.apparel == null) + if (moveFrom.apparel != null) { - return; - } - CaravanInventoryUtility.tmpApparel.Clear(); - CaravanInventoryUtility.tmpApparel.AddRange(moveFrom.apparel.WornApparel); - for (int i = 0; i < CaravanInventoryUtility.tmpApparel.Count; i++) - { - moveFrom.apparel.Remove(CaravanInventoryUtility.tmpApparel[i]); - Pawn pawn = CaravanInventoryUtility.FindPawnToMoveInventoryTo(CaravanInventoryUtility.tmpApparel[i], candidates, null, moveFrom); - if (pawn != null) + CaravanInventoryUtility.tmpApparel.Clear(); + CaravanInventoryUtility.tmpApparel.AddRange(moveFrom.apparel.WornApparel); + for (int i = 0; i < CaravanInventoryUtility.tmpApparel.Count; i++) { - pawn.inventory.innerContainer.TryAdd(CaravanInventoryUtility.tmpApparel[i], true); + moveFrom.apparel.Remove(CaravanInventoryUtility.tmpApparel[i]); + Pawn pawn = CaravanInventoryUtility.FindPawnToMoveInventoryTo(CaravanInventoryUtility.tmpApparel[i], candidates, null, moveFrom); + if (pawn != null) + { + pawn.inventory.innerContainer.TryAdd(CaravanInventoryUtility.tmpApparel[i], true); + } } + CaravanInventoryUtility.tmpApparel.Clear(); } - CaravanInventoryUtility.tmpApparel.Clear(); } public static void MoveAllEquipmentToSomeonesInventory(Pawn moveFrom, List candidates) { - if (moveFrom.equipment == null) + if (moveFrom.equipment != null) { - return; - } - CaravanInventoryUtility.tmpEquipment.Clear(); - CaravanInventoryUtility.tmpEquipment.AddRange(moveFrom.equipment.AllEquipmentListForReading); - for (int i = 0; i < CaravanInventoryUtility.tmpEquipment.Count; i++) - { - moveFrom.equipment.Remove(CaravanInventoryUtility.tmpEquipment[i]); - Pawn pawn = CaravanInventoryUtility.FindPawnToMoveInventoryTo(CaravanInventoryUtility.tmpEquipment[i], candidates, null, moveFrom); - if (pawn != null) + CaravanInventoryUtility.tmpEquipment.Clear(); + CaravanInventoryUtility.tmpEquipment.AddRange(moveFrom.equipment.AllEquipmentListForReading); + for (int i = 0; i < CaravanInventoryUtility.tmpEquipment.Count; i++) { - pawn.inventory.innerContainer.TryAdd(CaravanInventoryUtility.tmpEquipment[i], true); + moveFrom.equipment.Remove(CaravanInventoryUtility.tmpEquipment[i]); + Pawn pawn = CaravanInventoryUtility.FindPawnToMoveInventoryTo(CaravanInventoryUtility.tmpEquipment[i], candidates, null, moveFrom); + if (pawn != null) + { + pawn.inventory.innerContainer.TryAdd(CaravanInventoryUtility.tmpEquipment[i], true); + } } + CaravanInventoryUtility.tmpEquipment.Clear(); } - CaravanInventoryUtility.tmpEquipment.Clear(); } private static bool CanMoveInventoryTo(Pawn pawn) @@ -283,15 +264,24 @@ private static bool CanMoveInventoryTo(Pawn pawn) public static List TakeThings(Caravan caravan, Func takeQuantity) { List list = new List(); - foreach (Thing current in CaravanInventoryUtility.AllInventoryItems(caravan)) + List.Enumerator enumerator = CaravanInventoryUtility.AllInventoryItems(caravan).GetEnumerator(); + try { - int num = takeQuantity(current); - if (num > 0) + while (enumerator.MoveNext()) { - list.Add(current.holdingOwner.Take(current, num)); + Thing current = enumerator.Current; + int num = takeQuantity(current); + if (num > 0) + { + list.Add(current.holdingOwner.Take(current, num)); + } } + return list; + } + finally + { + ((IDisposable)(object)enumerator).Dispose(); } - return list; } public static void GiveThing(Caravan caravan, Thing thing) @@ -300,20 +290,18 @@ public static void GiveThing(Caravan caravan, Thing thing) if (pawn == null) { Log.Error(string.Format("Failed to give item {0} to caravan {1}; item was lost", thing, caravan)); - return; } - if (!pawn.inventory.innerContainer.TryAdd(thing, true)) + else if (!pawn.inventory.innerContainer.TryAdd(thing, true)) { Log.Error(string.Format("Failed to give item {0} to caravan {1}; item was lost", thing, caravan)); - return; } } public static bool HasThings(Caravan caravan, ThingDef thingDef, int count, Func validator = null) { return (from thing in CaravanInventoryUtility.AllInventoryItems(caravan) - where thing.def == thingDef && (validator == null || validator(thing)) - select thing).Sum((Thing thing) => thing.stackCount) >= count; + where thing.def == thingDef && ((object)validator == null || validator(thing)) + select thing).Sum((Func)((Thing thing) => thing.stackCount)) >= count; } } } diff --git a/Assembly-CSharp/RimWorld.Planet/CaravanJourneyDestinationUtility.cs b/Assembly-CSharp/RimWorld.Planet/CaravanJourneyDestinationUtility.cs index 95d90e980..736ff9101 100644 --- a/Assembly-CSharp/RimWorld.Planet/CaravanJourneyDestinationUtility.cs +++ b/Assembly-CSharp/RimWorld.Planet/CaravanJourneyDestinationUtility.cs @@ -17,19 +17,18 @@ public static bool AnyJurneyDestinationAt(int tile) public static Command TakeOffCommand(int tile) { - return new Command_Action + Command_Action command_Action = new Command_Action(); + command_Action.defaultLabel = "CommandTakeOff".Translate(); + command_Action.defaultDesc = "CommandTakeOffDesc".Translate(); + command_Action.icon = CaravanJourneyDestinationUtility.TakeOffCommandTex; + command_Action.action = (Action)delegate() { - defaultLabel = "CommandTakeOff".Translate(), - defaultDesc = "CommandTakeOffDesc".Translate(), - icon = CaravanJourneyDestinationUtility.TakeOffCommandTex, - action = delegate + Find.WindowStack.Add(Dialog_MessageBox.CreateConfirmation("CommandTakeOffConfirmation".Translate(), (Action)delegate() { - Find.WindowStack.Add(Dialog_MessageBox.CreateConfirmation("CommandTakeOffConfirmation".Translate(), delegate - { - CaravanJourneyDestinationUtility.TakeOff(tile); - }, false, null)); - } + CaravanJourneyDestinationUtility.TakeOff(tile); + }, false, (string)null)); }; + return command_Action; } public static WorldObject JurneyDestinationAt(int tile) diff --git a/Assembly-CSharp/RimWorld.Planet/CaravanMaker.cs b/Assembly-CSharp/RimWorld.Planet/CaravanMaker.cs index 7bf11714d..8ad2af5ec 100644 --- a/Assembly-CSharp/RimWorld.Planet/CaravanMaker.cs +++ b/Assembly-CSharp/RimWorld.Planet/CaravanMaker.cs @@ -1,4 +1,3 @@ -using System; using System.Collections.Generic; using Verse; diff --git a/Assembly-CSharp/RimWorld.Planet/CaravanMergeUtility.cs b/Assembly-CSharp/RimWorld.Planet/CaravanMergeUtility.cs index 9bdd3fb0f..4c5dfcd3a 100644 --- a/Assembly-CSharp/RimWorld.Planet/CaravanMergeUtility.cs +++ b/Assembly-CSharp/RimWorld.Planet/CaravanMergeUtility.cs @@ -45,7 +45,7 @@ public static Command MergeCommand(Caravan caravan) command_Action.defaultLabel = "CommandMergeCaravans".Translate(); command_Action.defaultDesc = "CommandMergeCaravansDesc".Translate(); command_Action.icon = CaravanMergeUtility.MergeCommandTex; - command_Action.action = delegate + command_Action.action = (Action)delegate { CaravanMergeUtility.TryMergeSelectedCaravans(); SoundDefOf.TickHigh.PlayOneShotOnCamera(null); @@ -65,18 +65,18 @@ public static void TryMergeSelectedCaravans() CaravanMergeUtility.tmpSelectedPlayerCaravans.Add(caravan); } } - while (CaravanMergeUtility.tmpSelectedPlayerCaravans.Any()) + while (CaravanMergeUtility.tmpSelectedPlayerCaravans.Any()) { Caravan caravan2 = CaravanMergeUtility.tmpSelectedPlayerCaravans[0]; CaravanMergeUtility.tmpSelectedPlayerCaravans.RemoveAt(0); CaravanMergeUtility.tmpCaravansOnSameTile.Clear(); CaravanMergeUtility.tmpCaravansOnSameTile.Add(caravan2); - for (int j = CaravanMergeUtility.tmpSelectedPlayerCaravans.Count - 1; j >= 0; j--) + for (int num = CaravanMergeUtility.tmpSelectedPlayerCaravans.Count - 1; num >= 0; num--) { - if (CaravanMergeUtility.CloseToEachOther(CaravanMergeUtility.tmpSelectedPlayerCaravans[j], caravan2)) + if (CaravanMergeUtility.CloseToEachOther(CaravanMergeUtility.tmpSelectedPlayerCaravans[num], caravan2)) { - CaravanMergeUtility.tmpCaravansOnSameTile.Add(CaravanMergeUtility.tmpSelectedPlayerCaravans[j]); - CaravanMergeUtility.tmpSelectedPlayerCaravans.RemoveAt(j); + CaravanMergeUtility.tmpCaravansOnSameTile.Add(CaravanMergeUtility.tmpSelectedPlayerCaravans[num]); + CaravanMergeUtility.tmpSelectedPlayerCaravans.RemoveAt(num); } } if (CaravanMergeUtility.tmpCaravansOnSameTile.Count >= 2) @@ -94,13 +94,17 @@ private static bool CloseToEachOther(Caravan c1, Caravan c2) } Vector3 drawPos = c1.DrawPos; Vector3 drawPos2 = c2.DrawPos; - float num = Find.WorldGrid.averageTileSize * 0.5f; - return (drawPos - drawPos2).sqrMagnitude < num * num; + float num = (float)(Find.WorldGrid.averageTileSize * 0.5); + if ((drawPos - drawPos2).sqrMagnitude < num * num) + { + return true; + } + return false; } private static void MergeCaravans(List caravans) { - Caravan caravan = caravans.MaxBy((Caravan x) => x.PawnsListForReading.Count); + Caravan caravan = caravans.MaxBy((Func)((Caravan x) => x.PawnsListForReading.Count)); for (int i = 0; i < caravans.Count; i++) { Caravan caravan2 = caravans[i]; diff --git a/Assembly-CSharp/RimWorld.Planet/CaravanNameGenerator.cs b/Assembly-CSharp/RimWorld.Planet/CaravanNameGenerator.cs index 27642263e..bca33dd15 100644 --- a/Assembly-CSharp/RimWorld.Planet/CaravanNameGenerator.cs +++ b/Assembly-CSharp/RimWorld.Planet/CaravanNameGenerator.cs @@ -1,4 +1,3 @@ -using System; using System.Collections.Generic; using Verse; diff --git a/Assembly-CSharp/RimWorld.Planet/CaravanPawnsAndItemsAbandonUtility.cs b/Assembly-CSharp/RimWorld.Planet/CaravanPawnsAndItemsAbandonUtility.cs index a28a3f714..5701058d0 100644 --- a/Assembly-CSharp/RimWorld.Planet/CaravanPawnsAndItemsAbandonUtility.cs +++ b/Assembly-CSharp/RimWorld.Planet/CaravanPawnsAndItemsAbandonUtility.cs @@ -16,78 +16,78 @@ public static void TryAbandonViaInterface(Thing t, Caravan caravan) Pawn p = t as Pawn; if (p != null) { - if (!caravan.PawnsListForReading.Any((Pawn x) => x != p && caravan.IsOwner(x))) + if (!caravan.PawnsListForReading.Any((Predicate)((Pawn x) => x != p && caravan.IsOwner(x)))) { - Messages.Message("MessageCantAbandonLastColonist".Translate(), caravan, MessageSound.RejectInput); - return; + Messages.Message("MessageCantAbandonLastColonist".Translate(), (WorldObject)caravan, MessageSound.RejectInput); } - Dialog_MessageBox window = Dialog_MessageBox.CreateConfirmation(CaravanPawnsAndItemsAbandonUtility.GetAbandonPawnDialogText(p, caravan), delegate + else { - bool flag = CaravanPawnsAndItemsAbandonUtility.WouldBeLeftToDie(p, caravan); - PawnDiedOrDownedThoughtsUtility.TryGiveThoughts(p, null, (!flag) ? PawnDiedOrDownedThoughtsKind.Abandoned : PawnDiedOrDownedThoughtsKind.AbandonedToDie); - CaravanInventoryUtility.MoveAllInventoryToSomeoneElse(p, caravan.PawnsListForReading, null); - caravan.RemovePawn(p); - if (flag) + Dialog_MessageBox window = Dialog_MessageBox.CreateConfirmation(CaravanPawnsAndItemsAbandonUtility.GetAbandonPawnDialogText(p, caravan), (Action)delegate() { - if (Rand.Value < 0.8f) - { - p.Destroy(DestroyMode.Vanish); - } - else + bool flag = CaravanPawnsAndItemsAbandonUtility.WouldBeLeftToDie(p, caravan); + PawnDiedOrDownedThoughtsUtility.TryGiveThoughts(p, default(DamageInfo?), (PawnDiedOrDownedThoughtsKind)((!flag) ? 1 : 2)); + CaravanInventoryUtility.MoveAllInventoryToSomeoneElse(p, caravan.PawnsListForReading, null); + caravan.RemovePawn(p); + if (flag) { - CaravanPawnsAndItemsAbandonUtility.HealIfPossible(p); + if (Rand.Value < 0.800000011920929) + { + p.Destroy(DestroyMode.Vanish); + } + else + { + CaravanPawnsAndItemsAbandonUtility.HealIfPossible(p); + } } - } - Find.WorldPawns.DiscardIfUnimportant(p); - }, true, null); - Find.WindowStack.Add(window); + Find.WorldPawns.DiscardIfUnimportant(p); + }, true, (string)null); + Find.WindowStack.Add(window); + } } else { - Dialog_MessageBox window2 = Dialog_MessageBox.CreateConfirmation("ConfirmAbandonItemDialog".Translate(new object[] - { - t.Label - }), delegate + Dialog_MessageBox window2 = Dialog_MessageBox.CreateConfirmation("ConfirmAbandonItemDialog".Translate(t.Label), (Action)delegate() { Pawn ownerOf = CaravanInventoryUtility.GetOwnerOf(caravan, t); if (ownerOf == null) { Log.Error("Could not find owner of " + t); - return; } - ownerOf.inventory.innerContainer.Remove(t); - t.Destroy(DestroyMode.Vanish); - caravan.RecacheImmobilizedNow(); - caravan.RecacheDaysWorthOfFood(); - }, true, null); + else + { + ownerOf.inventory.innerContainer.Remove(t); + t.Destroy(DestroyMode.Vanish); + caravan.RecacheImmobilizedNow(); + caravan.RecacheDaysWorthOfFood(); + } + }, true, (string)null); Find.WindowStack.Add(window2); } } public static void TryAbandonSpecificCountViaInterface(Thing t, Caravan caravan) { - Find.WindowStack.Add(new Dialog_Slider("AbandonSliderText".Translate(new object[] - { - t.LabelNoCount - }), 1, t.stackCount, delegate(int x) + Find.WindowStack.Add(new Dialog_Slider("AbandonSliderText".Translate(t.LabelNoCount), 1, t.stackCount, (Action)delegate(int x) { Pawn ownerOf = CaravanInventoryUtility.GetOwnerOf(caravan, t); if (ownerOf == null) { Log.Error("Could not find owner of " + t); - return; - } - if (x == t.stackCount) - { - ownerOf.inventory.innerContainer.Remove(t); - t.Destroy(DestroyMode.Vanish); } else { - t.SplitOff(x).Destroy(DestroyMode.Vanish); + if (x == t.stackCount) + { + ownerOf.inventory.innerContainer.Remove(t); + t.Destroy(DestroyMode.Vanish); + } + else + { + t.SplitOff(x).Destroy(DestroyMode.Vanish); + } + caravan.RecacheImmobilizedNow(); + caravan.RecacheDaysWorthOfFood(); } - caravan.RecacheImmobilizedNow(); - caravan.RecacheDaysWorthOfFood(); }, -2147483648)); } @@ -102,10 +102,7 @@ public static string GetAbandonButtonTooltip(Thing t, Caravan caravan, bool aban { stringBuilder.AppendLine(); stringBuilder.AppendLine(); - stringBuilder.Append("AbandonTipWillDie".Translate(new object[] - { - pawn.LabelShort - }).CapitalizeFirst()); + stringBuilder.Append("AbandonTipWillDie".Translate(pawn.LabelShort).CapitalizeFirst()); } } else @@ -154,29 +151,20 @@ private static string GetAbandonPawnDialogText(Pawn abandonedPawn, Caravan carav { StringBuilder stringBuilder = new StringBuilder(); bool flag = CaravanPawnsAndItemsAbandonUtility.WouldBeLeftToDie(abandonedPawn, caravan); - stringBuilder.Append("ConfirmAbandonPawnDialog".Translate(new object[] - { - abandonedPawn.Label - })); + stringBuilder.Append("ConfirmAbandonPawnDialog".Translate(abandonedPawn.Label)); if (flag) { stringBuilder.AppendLine(); stringBuilder.AppendLine(); - stringBuilder.Append("ConfirmAbandonPawnDialog_LeftToDie".Translate(new object[] - { - abandonedPawn.LabelShort - }).CapitalizeFirst()); + stringBuilder.Append("ConfirmAbandonPawnDialog_LeftToDie".Translate(abandonedPawn.LabelShort).CapitalizeFirst()); } List list = (abandonedPawn.equipment == null) ? null : abandonedPawn.equipment.AllEquipmentListForReading; List list2 = (abandonedPawn.apparel == null) ? null : abandonedPawn.apparel.WornApparel; - if (!list.NullOrEmpty() || !list2.NullOrEmpty()) + if (!list.NullOrEmpty() || !list2.NullOrEmpty()) { stringBuilder.AppendLine(); stringBuilder.AppendLine(); - stringBuilder.Append("ConfirmAbandonPawnDialog_EquipmentAndApparel".Translate(new object[] - { - abandonedPawn.LabelShort - }).CapitalizeFirst().AdjustedFor(abandonedPawn)); + stringBuilder.Append("ConfirmAbandonPawnDialog_EquipmentAndApparel".Translate(abandonedPawn.LabelShort).CapitalizeFirst().AdjustedFor(abandonedPawn)); stringBuilder.AppendLine(); if (list != null) { @@ -195,10 +183,7 @@ private static string GetAbandonPawnDialogText(Pawn abandonedPawn, Caravan carav } } } - PawnDiedOrDownedThoughtsUtility.BuildMoodThoughtsListString(abandonedPawn, null, (!flag) ? PawnDiedOrDownedThoughtsKind.Abandoned : PawnDiedOrDownedThoughtsKind.AbandonedToDie, stringBuilder, "\n\n" + "ConfirmAbandonPawnDialog_IndividualThoughts".Translate(new object[] - { - abandonedPawn.LabelShort - }), "\n\n" + "ConfirmAbandonPawnDialog_AllColonistsThoughts".Translate()); + PawnDiedOrDownedThoughtsUtility.BuildMoodThoughtsListString(abandonedPawn, default(DamageInfo?), (PawnDiedOrDownedThoughtsKind)((!flag) ? 1 : 2), stringBuilder, "\n\n" + "ConfirmAbandonPawnDialog_IndividualThoughts".Translate(abandonedPawn.LabelShort), "\n\n" + "ConfirmAbandonPawnDialog_AllColonistsThoughts".Translate()); return stringBuilder.ToString(); } @@ -208,7 +193,7 @@ private static bool WouldBeLeftToDie(Pawn p, Caravan caravan) { return true; } - if (p.health.hediffSet.BleedRateTotal > 0.4f) + if (p.health.hediffSet.BleedRateTotal > 0.40000000596046448) { return true; } diff --git a/Assembly-CSharp/RimWorld.Planet/CaravanPawnsNeedsUtility.cs b/Assembly-CSharp/RimWorld.Planet/CaravanPawnsNeedsUtility.cs index 06dfaa17c..cff249be6 100644 --- a/Assembly-CSharp/RimWorld.Planet/CaravanPawnsNeedsUtility.cs +++ b/Assembly-CSharp/RimWorld.Planet/CaravanPawnsNeedsUtility.cs @@ -1,4 +1,3 @@ -using System; using System.Collections.Generic; using UnityEngine; using Verse; @@ -14,9 +13,9 @@ public static class CaravanPawnsNeedsUtility public static void TrySatisfyPawnsNeeds(Caravan caravan) { List pawnsListForReading = caravan.PawnsListForReading; - for (int i = pawnsListForReading.Count - 1; i >= 0; i--) + for (int num = pawnsListForReading.Count - 1; num >= 0; num--) { - CaravanPawnsNeedsUtility.TrySatisfyPawnNeeds(pawnsListForReading[i], caravan); + CaravanPawnsNeedsUtility.TrySatisfyPawnNeeds(pawnsListForReading[num], caravan); } } @@ -38,24 +37,27 @@ public static bool AnyPawnOutOfFood(Caravan c, out string malnutritionHediff) if (pawn.RaceProps.EatsFood && !VirtualPlantsUtility.CanEatVirtualPlantsNow(pawn)) { bool flag = false; - for (int k = 0; k < CaravanPawnsNeedsUtility.tmpInvFood.Count; k++) + int num = 0; + while (num < CaravanPawnsNeedsUtility.tmpInvFood.Count) { - if (CaravanPawnsNeedsUtility.CanEverEatForNutrition(CaravanPawnsNeedsUtility.tmpInvFood[k].def, pawn)) + if (!CaravanPawnsNeedsUtility.CanEverEatForNutrition(CaravanPawnsNeedsUtility.tmpInvFood[num].def, pawn)) { - flag = true; - break; + num++; + continue; } + flag = true; + break; } if (!flag) { - int num = -1; - string text = null; - for (int l = 0; l < pawnsListForReading.Count; l++) + int num2 = -1; + string text = (string)null; + for (int k = 0; k < pawnsListForReading.Count; k++) { - Hediff firstHediffOfDef = pawnsListForReading[l].health.hediffSet.GetFirstHediffOfDef(HediffDefOf.Malnutrition, false); - if (firstHediffOfDef != null && (text == null || firstHediffOfDef.CurStageIndex > num)) + Hediff firstHediffOfDef = pawnsListForReading[k].health.hediffSet.GetFirstHediffOfDef(HediffDefOf.Malnutrition, false); + if (firstHediffOfDef != null && (text == null || firstHediffOfDef.CurStageIndex > num2)) { - num = firstHediffOfDef.CurStageIndex; + num2 = firstHediffOfDef.CurStageIndex; text = firstHediffOfDef.LabelCap; } } @@ -64,34 +66,33 @@ public static bool AnyPawnOutOfFood(Caravan c, out string malnutritionHediff) } } } - malnutritionHediff = null; + malnutritionHediff = (string)null; return false; } private static void TrySatisfyPawnNeeds(Pawn pawn, Caravan caravan) { - if (pawn.Dead) + if (!pawn.Dead) { - return; - } - List allNeeds = pawn.needs.AllNeeds; - for (int i = 0; i < allNeeds.Count; i++) - { - Need need = allNeeds[i]; - Need_Rest need_Rest = need as Need_Rest; - Need_Food need_Food = need as Need_Food; - Need_Chemical need_Chemical = need as Need_Chemical; - if (need_Rest != null) + List allNeeds = pawn.needs.AllNeeds; + for (int i = 0; i < allNeeds.Count; i++) { - CaravanPawnsNeedsUtility.TrySatisfyRestNeed(pawn, need_Rest, caravan); - } - else if (need_Food != null) - { - CaravanPawnsNeedsUtility.TrySatisfyFoodNeed(pawn, need_Food, caravan); - } - else if (need_Chemical != null) - { - CaravanPawnsNeedsUtility.TrySatisfyChemicalNeed(pawn, need_Chemical, caravan); + Need need = allNeeds[i]; + Need_Rest need_Rest = need as Need_Rest; + Need_Food need_Food = need as Need_Food; + Need_Chemical need_Chemical = need as Need_Chemical; + if (need_Rest != null) + { + CaravanPawnsNeedsUtility.TrySatisfyRestNeed(pawn, need_Rest, caravan); + } + else if (need_Food != null) + { + CaravanPawnsNeedsUtility.TrySatisfyFoodNeed(pawn, need_Food, caravan); + } + else if (need_Chemical != null) + { + CaravanPawnsNeedsUtility.TrySatisfyChemicalNeed(pawn, need_Chemical, caravan); + } } } } @@ -107,34 +108,29 @@ private static void TrySatisfyRestNeed(Pawn pawn, Need_Rest rest, Caravan carava private static void TrySatisfyFoodNeed(Pawn pawn, Need_Food food, Caravan caravan) { - if (food.CurCategory < HungerCategory.Hungry) - { - return; - } - Thing thing; - Pawn pawn2; - if (VirtualPlantsUtility.CanEatVirtualPlantsNow(pawn)) - { - VirtualPlantsUtility.EatVirtualPlants(pawn); - } - else if (CaravanInventoryUtility.TryGetBestFood(caravan, pawn, out thing, out pawn2)) + if ((int)food.CurCategory >= 1) { - food.CurLevel += thing.Ingested(pawn, food.NutritionWanted); - if (thing.Destroyed) + Thing thing = default(Thing); + Pawn pawn2 = default(Pawn); + if (VirtualPlantsUtility.CanEatVirtualPlantsNow(pawn)) { - if (pawn2 != null) - { - pawn2.inventory.innerContainer.Remove(thing); - caravan.RecacheImmobilizedNow(); - caravan.RecacheDaysWorthOfFood(); - } - if (!CaravanInventoryUtility.TryGetBestFood(caravan, pawn, out thing, out pawn2)) + VirtualPlantsUtility.EatVirtualPlants(pawn); + } + else if (CaravanInventoryUtility.TryGetBestFood(caravan, pawn, out thing, out pawn2)) + { + food.CurLevel += thing.Ingested(pawn, food.NutritionWanted); + if (thing.Destroyed) { - Messages.Message("MessageCaravanRunOutOfFood".Translate(new object[] + if (pawn2 != null) + { + pawn2.inventory.innerContainer.Remove(thing); + caravan.RecacheImmobilizedNow(); + caravan.RecacheDaysWorthOfFood(); + } + if (!CaravanInventoryUtility.TryGetBestFood(caravan, pawn, out thing, out pawn2)) { - caravan.LabelCap, - pawn.Label - }), caravan, MessageSound.SeriousAlert); + Messages.Message("MessageCaravanRunOutOfFood".Translate(caravan.LabelCap, pawn.Label), (WorldObject)caravan, MessageSound.SeriousAlert); + } } } } @@ -142,13 +138,9 @@ private static void TrySatisfyFoodNeed(Pawn pawn, Need_Food food, Caravan carava private static void TrySatisfyChemicalNeed(Pawn pawn, Need_Chemical chemical, Caravan caravan) { - if (chemical.CurCategory >= DrugDesireCategory.Satisfied) - { - return; - } - Thing drug; - Pawn drugOwner; - if (CaravanInventoryUtility.TryGetBestDrug(caravan, pawn, chemical, out drug, out drugOwner)) + Thing drug = default(Thing); + Pawn drugOwner = default(Pawn); + if ((int)chemical.CurCategory < 2 && CaravanInventoryUtility.TryGetBestDrug(caravan, pawn, chemical, out drug, out drugOwner)) { CaravanPawnsNeedsUtility.IngestDrug(pawn, drug, drugOwner, caravan); } @@ -172,17 +164,33 @@ public static void IngestDrug(Pawn pawn, Thing drug, Pawn drugOwner, Caravan car public static bool CanEverEatForNutrition(ThingDef food, Pawn pawn) { - return food.IsNutritionGivingIngestible && pawn.RaceProps.CanEverEat(food) && food.ingestible.preferability > FoodPreferability.NeverForNutrition && (!pawn.IsTeetotaler() || !food.IsDrug); + return food.IsNutritionGivingIngestible && pawn.RaceProps.CanEverEat(food) && (int)food.ingestible.preferability > 1 && (!pawn.IsTeetotaler() || !food.IsDrug); } public static bool CanNowEatForNutrition(ThingDef food, Pawn pawn) { - return CaravanPawnsNeedsUtility.CanEverEatForNutrition(food, pawn) && (pawn.needs.food.CurCategory >= HungerCategory.Starving || food.ingestible.preferability > FoodPreferability.DesperateOnly); + if (!CaravanPawnsNeedsUtility.CanEverEatForNutrition(food, pawn)) + { + return false; + } + if ((int)pawn.needs.food.CurCategory < 3 && (int)food.ingestible.preferability <= 2) + { + return false; + } + return true; } public static bool CanNowEatForNutrition(Thing food, Pawn pawn) { - return food.IngestibleNow && CaravanPawnsNeedsUtility.CanNowEatForNutrition(food.def, pawn); + if (!food.IngestibleNow) + { + return false; + } + if (!CaravanPawnsNeedsUtility.CanNowEatForNutrition(food.def, pawn)) + { + return false; + } + return true; } public static float GetFoodScore(Thing food, Pawn pawn) @@ -192,7 +200,7 @@ public static float GetFoodScore(Thing food, Pawn pawn) { CompRottable compRottable = food.TryGetComp(); int a = (compRottable == null) ? 2147483647 : compRottable.TicksUntilRotAtCurrentTemp; - float a2 = 1f - (float)Mathf.Min(a, 3600000) / 3600000f; + float a2 = (float)(1.0 - (float)Mathf.Min(a, 3600000) / 3600000.0); num += Mathf.Min(a2, 0.999f); } return num; @@ -202,7 +210,7 @@ public static float GetFoodScore(ThingDef food, Pawn pawn) { if (pawn.RaceProps.Humanlike) { - return (float)food.ingestible.preferability; + return (float)(int)food.ingestible.preferability; } float num = 0f; if (food == ThingDefOf.Kibble || food == ThingDefOf.Hay) @@ -217,11 +225,11 @@ public static float GetFoodScore(ThingDef food, Pawn pawn) { num = 2f; } - else if (food.ingestible.preferability < FoodPreferability.MealAwful) + else if ((int)food.ingestible.preferability < 5) { num = 1f; } - return num + Mathf.Min(food.ingestible.nutrition / 100f, 0.999f); + return num + Mathf.Min((float)(food.ingestible.nutrition / 100.0), 0.999f); } } } diff --git a/Assembly-CSharp/RimWorld.Planet/CaravanPeopleAndItemsTabUtility.cs b/Assembly-CSharp/RimWorld.Planet/CaravanPeopleAndItemsTabUtility.cs index 6cd0f8813..519b70729 100644 --- a/Assembly-CSharp/RimWorld.Planet/CaravanPeopleAndItemsTabUtility.cs +++ b/Assembly-CSharp/RimWorld.Planet/CaravanPeopleAndItemsTabUtility.cs @@ -58,7 +58,7 @@ public static void DoRows(Vector2 size, List things, Caravan caravan, ref } Text.Font = GameFont.Small; Rect rect = new Rect(0f, 0f, size.x, size.y).ContractedBy(10f); - Rect viewRect = new Rect(0f, 0f, rect.width - 16f, scrollViewHeight); + Rect viewRect = new Rect(0f, 0f, (float)(rect.width - 16.0), scrollViewHeight); bool listingUsesAbandonSpecificCountButtons = CaravanPeopleAndItemsTabUtility.AnyItemOrEmpty(things); Widgets.BeginScrollView(rect, ref scrollPosition, viewRect, true); float num = 0f; @@ -73,7 +73,7 @@ public static void DoRows(Vector2 size, List things, Caravan caravan, ref Widgets.ListSeparator(ref num, viewRect.width, "CaravanColonists".Translate()); flag = true; } - CaravanPeopleAndItemsTabUtility.DoRow(ref num, viewRect, rect, scrollPosition, pawn, caravan, ref specificNeedsTabForPawn, doNeeds, listingUsesAbandonSpecificCountButtons); + CaravanPeopleAndItemsTabUtility.DoRow(ref num, viewRect, rect, scrollPosition, (Thing)pawn, caravan, ref specificNeedsTabForPawn, doNeeds, listingUsesAbandonSpecificCountButtons); } } bool flag2 = false; @@ -87,7 +87,7 @@ public static void DoRows(Vector2 size, List things, Caravan caravan, ref Widgets.ListSeparator(ref num, viewRect.width, "CaravanPrisonersAndAnimals".Translate()); flag2 = true; } - CaravanPeopleAndItemsTabUtility.DoRow(ref num, viewRect, rect, scrollPosition, pawn2, caravan, ref specificNeedsTabForPawn, doNeeds, listingUsesAbandonSpecificCountButtons); + CaravanPeopleAndItemsTabUtility.DoRow(ref num, viewRect, rect, scrollPosition, (Thing)pawn2, caravan, ref specificNeedsTabForPawn, doNeeds, listingUsesAbandonSpecificCountButtons); } } bool flag3 = false; @@ -116,71 +116,71 @@ public static void DoRows(Vector2 size, List things, Caravan caravan, ref Text.Anchor = TextAnchor.UpperCenter; Widgets.Label(new Rect(0f, num, viewRect.width, 25f), "NoneBrackets".Translate()); Text.Anchor = TextAnchor.UpperLeft; - num += 25f; + num = (float)(num + 25.0); GUI.color = Color.white; } if (Event.current.type == EventType.Layout) { - scrollViewHeight = num + 30f; + scrollViewHeight = (float)(num + 30.0); } Widgets.EndScrollView(); } public static Vector2 GetSize(List things, float paneTopY, bool doNeeds = true) { - float num = 0f; - if (things.Any((Thing x) => x is Pawn)) + float a = 0f; + if (things.Any((Predicate)((Thing x) => x is Pawn))) { - num = 100f; + a = 100f; if (doNeeds) { - num += (float)CaravanPeopleAndItemsTabUtility.MaxNeedsCount(things) * 100f; + a = (float)(a + (float)CaravanPeopleAndItemsTabUtility.MaxNeedsCount(things) * 100.0); } - num += 24f; + a = (float)(a + 24.0); } - float num2 = 0f; + float b = 0f; if (CaravanPeopleAndItemsTabUtility.AnyItemOrEmpty(things)) { - num2 = 300f; - num2 += 24f; - num2 += 60f; + b = 300f; + b = (float)(b + 24.0); + b = (float)(b + 60.0); } - Vector2 result; - result.x = 103f + Mathf.Max(num, num2) + 16f; - result.y = Mathf.Min(550f, paneTopY - 30f); + Vector2 result = default(Vector2); + result.x = (float)(103.0 + Mathf.Max(a, b) + 16.0); + result.y = Mathf.Min(550f, (float)(paneTopY - 30.0)); return result; } private static bool AnyItemOrEmpty(List things) { - return things.Any((Thing x) => !(x is Pawn)) || !things.Any(); + return things.Any((Predicate)((Thing x) => !(x is Pawn))) || !things.Any(); } public static void DoAbandonButton(Rect rowRect, Thing t, Caravan caravan) { - Rect rect = new Rect(rowRect.width - 24f, (rowRect.height - 24f) / 2f, 24f, 24f); + Rect rect = new Rect((float)(rowRect.width - 24.0), (float)((rowRect.height - 24.0) / 2.0), 24f, 24f); if (Widgets.ButtonImage(rect, CaravanPeopleAndItemsTabUtility.AbandonButtonTex)) { CaravanPawnsAndItemsAbandonUtility.TryAbandonViaInterface(t, caravan); } - TooltipHandler.TipRegion(rect, () => CaravanPawnsAndItemsAbandonUtility.GetAbandonButtonTooltip(t, caravan, false), Gen.HashCombineInt(t.GetHashCode(), 1383004931)); + TooltipHandler.TipRegion(rect, (Func)(() => CaravanPawnsAndItemsAbandonUtility.GetAbandonButtonTooltip(t, caravan, false)), Gen.HashCombineInt(t.GetHashCode(), 1383004931)); } private static void DoAbandonSpecificCountButton(Rect rowRect, Thing t, Caravan caravan) { - Rect rect = new Rect(rowRect.width - 24f, (rowRect.height - 24f) / 2f, 24f, 24f); + Rect rect = new Rect((float)(rowRect.width - 24.0), (float)((rowRect.height - 24.0) / 2.0), 24f, 24f); if (Widgets.ButtonImage(rect, CaravanPeopleAndItemsTabUtility.AbandonSpecificCountButtonTex)) { CaravanPawnsAndItemsAbandonUtility.TryAbandonSpecificCountViaInterface(t, caravan); } - TooltipHandler.TipRegion(rect, () => CaravanPawnsAndItemsAbandonUtility.GetAbandonButtonTooltip(t, caravan, true), Gen.HashCombineInt(t.GetHashCode(), 1163428609)); + TooltipHandler.TipRegion(rect, (Func)(() => CaravanPawnsAndItemsAbandonUtility.GetAbandonButtonTooltip(t, caravan, true)), Gen.HashCombineInt(t.GetHashCode(), 1163428609)); } public static void DoOpenSpecificTabButton(Rect rowRect, Pawn p, ref Pawn specificTabForPawn) { Color baseColor = (p != specificTabForPawn) ? Color.white : CaravanPeopleAndItemsTabUtility.OpenedSpecificTabButtonColor; Color mouseoverColor = (p != specificTabForPawn) ? GenUI.MouseoverColor : CaravanPeopleAndItemsTabUtility.OpenedSpecificTabButtonMouseoverColor; - Rect rect = new Rect(rowRect.width - 24f, (rowRect.height - 24f) / 2f, 24f, 24f); + Rect rect = new Rect((float)(rowRect.width - 24.0), (float)((rowRect.height - 24.0) / 2.0), 24f, 24f); if (Widgets.ButtonImage(rect, CaravanPeopleAndItemsTabUtility.SpecificTabButtonTex, baseColor, mouseoverColor)) { if (p == specificTabForPawn) @@ -215,7 +215,7 @@ private static int MaxNeedsCount(List things) private static void DoRow(ref float curY, Rect viewRect, Rect scrollOutRect, Vector2 scrollPosition, Thing thing, Caravan caravan, ref Pawn specificNeedsTabForPawn, bool doNeeds, bool listingUsesAbandonSpecificCountButtons) { - float num = (!(thing is Pawn)) ? 30f : 50f; + float num = (float)((!(thing is Pawn)) ? 30.0 : 50.0); float num2 = scrollPosition.y - num; float num3 = scrollPosition.y + scrollOutRect.height; if (curY > num2 && curY < num3) @@ -240,7 +240,7 @@ private static void DoRow(Rect rect, Thing thing, Caravan caravan, ref Pawn spec } CaravanPeopleAndItemsTabUtility.DoAbandonButton(rect2, thing, caravan); rect2.width -= 24f; - Widgets.InfoCardButton(rect2.width - 24f, (rect.height - 24f) / 2f, thing); + Widgets.InfoCardButton((float)(rect2.width - 24.0), (float)((rect.height - 24.0) / 2.0), thing); rect2.width -= 24f; if (pawn != null && !pawn.Dead) { @@ -250,7 +250,7 @@ private static void DoRow(Rect rect, Thing thing, Caravan caravan, ref Pawn spec if (pawn == null) { Rect rect3 = rect2; - rect3.xMin = rect3.xMax - 60f; + rect3.xMin = (float)(rect3.xMax - 60.0); CaravanPeopleAndItemsTabUtility.TryDrawMass(thing, rect3); rect2.width -= 60f; } @@ -258,11 +258,11 @@ private static void DoRow(Rect rect, Thing thing, Caravan caravan, ref Pawn spec { Widgets.DrawHighlight(rect2); } - Rect rect4 = new Rect(4f, (rect.height - 27f) / 2f, 27f, 27f); + Rect rect4 = new Rect(4f, (float)((rect.height - 27.0) / 2.0), 27f, 27f); Widgets.ThingIcon(rect4, thing, 1f); if (pawn != null) { - Rect bgRect = new Rect(rect4.xMax + 4f, 16f, 100f, 18f); + Rect bgRect = new Rect((float)(rect4.xMax + 4.0), 16f, 100f, 18f); GenMapUI.DrawPawnLabel(pawn, bgRect, 1f, 100f, null, GameFont.Small, false, false); if (doNeeds) { @@ -279,7 +279,7 @@ private static void DoRow(Rect rect, Thing thing, Caravan caravan, ref Pawn spec { maxThresholdMarkers = 1; doTooltip = false; - TooltipHandler.TipRegion(rect5, new TipSignal(() => CaravanPeopleAndItemsTabUtility.CustomMoodNeedTooltip(mood), rect5.GetHashCode())); + TooltipHandler.TipRegion(rect5, new TipSignal((Func)(() => CaravanPeopleAndItemsTabUtility.CustomMoodNeedTooltip(mood)), rect5.GetHashCode())); } need.DrawOnGUI(rect5, maxThresholdMarkers, 10f, false, doTooltip); xMax = rect5.xMax; @@ -288,13 +288,13 @@ private static void DoRow(Rect rect, Thing thing, Caravan caravan, ref Pawn spec if (pawn.Downed) { GUI.color = new Color(1f, 0f, 0f, 0.5f); - Widgets.DrawLineHorizontal(0f, rect.height / 2f, rect.width); + Widgets.DrawLineHorizontal(0f, (float)(rect.height / 2.0), rect.width); GUI.color = Color.white; } } else { - Rect rect6 = new Rect(rect4.xMax + 4f, 0f, 300f, 30f); + Rect rect6 = new Rect((float)(rect4.xMax + 4.0), 0f, 300f, 30f); Text.Anchor = TextAnchor.MiddleLeft; Text.WordWrap = false; Widgets.Label(rect6, thing.LabelCap); diff --git a/Assembly-CSharp/RimWorld.Planet/CaravanRequestComp.cs b/Assembly-CSharp/RimWorld.Planet/CaravanRequestComp.cs index b070b69ed..751a714e7 100644 --- a/Assembly-CSharp/RimWorld.Planet/CaravanRequestComp.cs +++ b/Assembly-CSharp/RimWorld.Planet/CaravanRequestComp.cs @@ -1,4 +1,3 @@ -using System; using System.Collections.Generic; using Verse; @@ -31,14 +30,9 @@ public override string CompInspectStringExtra() { if (this.ActiveRequest) { - return "CaravanRequestInfo".Translate(new object[] - { - GenLabel.ThingLabel(this.requestThingDef, null, this.requestCount).CapitalizeFirst(), - this.rewards[0].LabelCap, - (this.expiration - Find.TickManager.TicksGame).ToStringTicksToDays("F1") - }); + return "CaravanRequestInfo".Translate(GenLabel.ThingLabel(this.requestThingDef, null, this.requestCount).CapitalizeFirst(), this.rewards[0].LabelCap, (this.expiration - Find.TickManager.TicksGame).ToStringTicksToDays("F1")); } - return null; + return (string)null; } public void GetChildHolders(List outChildren) @@ -61,7 +55,7 @@ public override void PostExposeData() base.PostExposeData(); Scribe_Defs.Look(ref this.requestThingDef, "requestThingDef"); Scribe_Values.Look(ref this.requestCount, "requestCount", 0, false); - Scribe_Deep.Look(ref this.rewards, "rewards", new object[] + Scribe_Deep.Look(ref this.rewards, "rewards", new object[1] { this }); @@ -78,5 +72,11 @@ virtual IThingHolder get_ParentHolder() { return base.ParentHolder; } + + IThingHolder IThingHolder.get_ParentHolder() + { + //ILSpy generated this explicit interface implementation from .override directive in get_ParentHolder + return this.get_ParentHolder(); + } } } diff --git a/Assembly-CSharp/RimWorld.Planet/CaravanRestUtility.cs b/Assembly-CSharp/RimWorld.Planet/CaravanRestUtility.cs index 72cf74af6..a95de44e4 100644 --- a/Assembly-CSharp/RimWorld.Planet/CaravanRestUtility.cs +++ b/Assembly-CSharp/RimWorld.Planet/CaravanRestUtility.cs @@ -1,4 +1,3 @@ -using System; using UnityEngine; using Verse; @@ -12,18 +11,19 @@ public static class CaravanRestUtility public static bool RestingNowAt(int tile) { - return CaravanRestUtility.WouldBeRestingAt(tile, (long)GenTicks.TicksAbs); + return CaravanRestUtility.WouldBeRestingAt(tile, GenTicks.TicksAbs); } public static bool WouldBeRestingAt(int tile, long ticksAbs) { - float num = GenDate.HourFloat(ticksAbs, Find.WorldGrid.LongLatOf(tile).x); - return num < 6f || num > 22f; + Vector2 vector = Find.WorldGrid.LongLatOf(tile); + float num = GenDate.HourFloat(ticksAbs, vector.x); + return num < 6.0 || num > 22.0; } public static int LeftRestTicksAt(int tile) { - return CaravanRestUtility.LeftRestTicksAt(tile, (long)GenTicks.TicksAbs); + return CaravanRestUtility.LeftRestTicksAt(tile, GenTicks.TicksAbs); } public static int LeftRestTicksAt(int tile, long ticksAbs) @@ -32,17 +32,18 @@ public static int LeftRestTicksAt(int tile, long ticksAbs) { return 0; } - float num = GenDate.HourFloat(ticksAbs, Find.WorldGrid.LongLatOf(tile).x); - if (num < 6f) + Vector2 vector = Find.WorldGrid.LongLatOf(tile); + float num = GenDate.HourFloat(ticksAbs, vector.x); + if (num < 6.0) { - return Mathf.CeilToInt((6f - num) * 2500f); + return Mathf.CeilToInt((float)((6.0 - num) * 2500.0)); } - return Mathf.CeilToInt((24f - num + 6f) * 2500f); + return Mathf.CeilToInt((float)((24.0 - num + 6.0) * 2500.0)); } public static int LeftNonRestTicksAt(int tile) { - return CaravanRestUtility.LeftNonRestTicksAt(tile, (long)GenTicks.TicksAbs); + return CaravanRestUtility.LeftNonRestTicksAt(tile, GenTicks.TicksAbs); } public static int LeftNonRestTicksAt(int tile, long ticksAbs) @@ -51,8 +52,9 @@ public static int LeftNonRestTicksAt(int tile, long ticksAbs) { return 0; } - float num = GenDate.HourFloat(ticksAbs, Find.WorldGrid.LongLatOf(tile).x); - return Mathf.CeilToInt((22f - num) * 2500f); + Vector2 vector = Find.WorldGrid.LongLatOf(tile); + float num = GenDate.HourFloat(ticksAbs, vector.x); + return Mathf.CeilToInt((float)((22.0 - num) * 2500.0)); } public static float DayPercentNotRestingAt(int tile) diff --git a/Assembly-CSharp/RimWorld.Planet/CaravanTendUtility.cs b/Assembly-CSharp/RimWorld.Planet/CaravanTendUtility.cs index 1283a5750..f0f82ff6b 100644 --- a/Assembly-CSharp/RimWorld.Planet/CaravanTendUtility.cs +++ b/Assembly-CSharp/RimWorld.Planet/CaravanTendUtility.cs @@ -1,4 +1,3 @@ -using System; using System.Collections.Generic; using Verse; @@ -11,25 +10,23 @@ public static class CaravanTendUtility public static void TryTendToRandomPawn(Caravan caravan) { CaravanTendUtility.FindPawnsNeedingTend(caravan, CaravanTendUtility.tmpPawnsNeedingTreatment); - if (!CaravanTendUtility.tmpPawnsNeedingTreatment.Any()) + if (CaravanTendUtility.tmpPawnsNeedingTreatment.Any()) { - return; - } - Pawn patient = CaravanTendUtility.tmpPawnsNeedingTreatment.RandomElement(); - Pawn pawn = CaravanTendUtility.FindBestDoctor(caravan, patient); - if (pawn == null) - { - return; - } - Medicine medicine = null; - Pawn pawn2 = null; - CaravanInventoryUtility.TryGetBestMedicine(caravan, patient, out medicine, out pawn2); - TendUtility.DoTend(pawn, patient, medicine); - if (medicine != null && medicine.Destroyed && pawn2 != null) - { - pawn2.inventory.innerContainer.Remove(medicine); + Pawn patient = CaravanTendUtility.tmpPawnsNeedingTreatment.RandomElement(); + Pawn pawn = CaravanTendUtility.FindBestDoctor(caravan, patient); + if (pawn != null) + { + Medicine medicine = null; + Pawn pawn2 = null; + CaravanInventoryUtility.TryGetBestMedicine(caravan, patient, out medicine, out pawn2); + TendUtility.DoTend(pawn, patient, medicine); + if (medicine != null && medicine.Destroyed && pawn2 != null) + { + pawn2.inventory.innerContainer.Remove(medicine); + } + CaravanTendUtility.tmpPawnsNeedingTreatment.Clear(); + } } - CaravanTendUtility.tmpPawnsNeedingTreatment.Clear(); } private static void FindPawnsNeedingTend(Caravan caravan, List outPawnsNeedingTend) @@ -39,12 +36,9 @@ private static void FindPawnsNeedingTend(Caravan caravan, List outPawnsNee for (int i = 0; i < pawnsListForReading.Count; i++) { Pawn pawn = pawnsListForReading[i]; - if (pawn.playerSettings == null || pawn.playerSettings.medCare > MedicalCareCategory.NoCare) + if ((pawn.playerSettings == null || (int)pawn.playerSettings.medCare > 0) && pawn.health.HasHediffsNeedingTend(false)) { - if (pawn.health.HasHediffsNeedingTend(false)) - { - outPawnsNeedingTend.Add(pawn); - } + outPawnsNeedingTend.Add(pawn); } } } @@ -57,19 +51,13 @@ private static Pawn FindBestDoctor(Caravan caravan, Pawn patient) for (int i = 0; i < pawnsListForReading.Count; i++) { Pawn pawn2 = pawnsListForReading[i]; - if (pawn2 != patient && CaravanUtility.IsOwner(pawn2, caravan.Faction)) + if (pawn2 != patient && CaravanUtility.IsOwner(pawn2, caravan.Faction) && !pawn2.Downed && !pawn2.InMentalState && (pawn2.story == null || !pawn2.story.WorkTypeIsDisabled(WorkTypeDefOf.Doctor))) { - if (!pawn2.Downed && !pawn2.InMentalState) + float statValue = pawn2.GetStatValue(StatDefOf.MedicalTendQuality, true); + if (statValue > num || pawn == null) { - if (pawn2.story == null || !pawn2.story.WorkTypeIsDisabled(WorkTypeDefOf.Doctor)) - { - float statValue = pawn2.GetStatValue(StatDefOf.MedicalTendQuality, true); - if (statValue > num || pawn == null) - { - num = statValue; - pawn = pawn2; - } - } + num = statValue; + pawn = pawn2; } } } diff --git a/Assembly-CSharp/RimWorld.Planet/CaravanTicksPerMoveUtility.cs b/Assembly-CSharp/RimWorld.Planet/CaravanTicksPerMoveUtility.cs index 19bacb318..26364ec66 100644 --- a/Assembly-CSharp/RimWorld.Planet/CaravanTicksPerMoveUtility.cs +++ b/Assembly-CSharp/RimWorld.Planet/CaravanTicksPerMoveUtility.cs @@ -1,4 +1,3 @@ -using System; using System.Collections.Generic; using UnityEngine; using Verse; @@ -24,7 +23,7 @@ public static int GetTicksPerMove(Caravan caravan) public static int GetTicksPerMove(List pawns) { - if (pawns.Any()) + if (pawns.Any()) { float num = 0f; for (int i = 0; i < pawns.Count; i++) @@ -32,7 +31,7 @@ public static int GetTicksPerMove(List pawns) int num2 = (!pawns[i].Downed) ? pawns[i].TicksPerMoveCardinal : 450; num += (float)num2 / (float)pawns.Count; } - num *= 190f; + num = (float)(num * 190.0); return Mathf.Max(Mathf.RoundToInt(num), 1); } return 2500; diff --git a/Assembly-CSharp/RimWorld.Planet/CaravanTweenerUtility.cs b/Assembly-CSharp/RimWorld.Planet/CaravanTweenerUtility.cs index 37b13259f..72028c84f 100644 --- a/Assembly-CSharp/RimWorld.Planet/CaravanTweenerUtility.cs +++ b/Assembly-CSharp/RimWorld.Planet/CaravanTweenerUtility.cs @@ -1,4 +1,3 @@ -using System; using System.Collections.Generic; using UnityEngine; using Verse; @@ -20,16 +19,8 @@ public static Vector3 PatherTweenedPosRoot(Caravan caravan) } if (caravan.pather.Moving) { - float num; - if (!caravan.pather.IsNextTilePassable()) - { - num = 0f; - } - else - { - num = 1f - caravan.pather.nextTileCostLeft / caravan.pather.nextTileCostTotal; - } - return worldGrid.GetTileCenter(caravan.pather.nextTile) * num + worldGrid.GetTileCenter(caravan.Tile) * (1f - num); + float num = (float)(caravan.pather.IsNextTilePassable() ? (1.0 - caravan.pather.nextTileCostLeft / caravan.pather.nextTileCostTotal) : 0.0); + return worldGrid.GetTileCenter(caravan.pather.nextTile) * num + worldGrid.GetTileCenter(caravan.Tile) * (float)(1.0 - num); } return worldGrid.GetTileCenter(caravan.Tile); } @@ -41,28 +32,8 @@ public static Vector3 CaravanCollisionPosOffsetFor(Caravan caravan) return Vector3.zero; } bool flag = caravan.Spawned && caravan.pather.Moving; - float d = 0.15f * Find.WorldGrid.averageTileSize; - if (!flag || caravan.pather.nextTile == caravan.pather.Destination) - { - int num; - if (flag) - { - num = caravan.pather.nextTile; - } - else - { - num = caravan.Tile; - } - int num2 = 0; - int vertexIndex = 0; - CaravanTweenerUtility.GetCaravansStandingAtOrAboutToStandAt(num, out num2, out vertexIndex, caravan); - if (num2 == 0) - { - return Vector3.zero; - } - return WorldRendererUtility.ProjectOnQuadTangentialToPlanet(Find.WorldGrid.GetTileCenter(num), GenGeo.RegularPolygonVertexPosition(num2, vertexIndex) * d); - } - else + float d = (float)(0.15000000596046448 * Find.WorldGrid.averageTileSize); + if (flag && caravan.pather.nextTile != caravan.pather.Destination) { if (CaravanTweenerUtility.DrawPosCollides(caravan)) { @@ -75,6 +46,15 @@ public static Vector3 CaravanCollisionPosOffsetFor(Caravan caravan) } return Vector3.zero; } + int num = (!flag) ? caravan.Tile : caravan.pather.nextTile; + int num2 = 0; + int vertexIndex = 0; + CaravanTweenerUtility.GetCaravansStandingAtOrAboutToStandAt(num, out num2, out vertexIndex, caravan); + if (num2 == 0) + { + return Vector3.zero; + } + return WorldRendererUtility.ProjectOnQuadTangentialToPlanet(Find.WorldGrid.GetTileCenter(num), GenGeo.RegularPolygonVertexPosition(num2, vertexIndex) * d); } private static void GetCaravansStandingAtOrAboutToStandAt(int tile, out int caravansCount, out int caravansWithLowerIdCount, Caravan forCaravan) @@ -82,49 +62,37 @@ private static void GetCaravansStandingAtOrAboutToStandAt(int tile, out int cara caravansCount = 0; caravansWithLowerIdCount = 0; List caravans = Find.WorldObjects.Caravans; - int i = 0; - while (i < caravans.Count) + for (int i = 0; i < caravans.Count; i++) { Caravan caravan = caravans[i]; if (caravan.Tile != tile) { if (caravan.pather.Moving && caravan.pather.nextTile == caravan.pather.Destination && caravan.pather.Destination == tile) - { - goto IL_87; - } + goto IL_0087; } else if (!caravan.pather.Moving) - { - goto IL_87; - } - IL_A4: - i++; + goto IL_0087; continue; - IL_87: + IL_0087: caravansCount++; if (caravan.ID < forCaravan.ID) { caravansWithLowerIdCount++; - goto IL_A4; } - goto IL_A4; } } private static bool DrawPosCollides(Caravan caravan) { Vector3 a = CaravanTweenerUtility.PatherTweenedPosRoot(caravan); - float num = Find.WorldGrid.averageTileSize * 0.2f; + float num = (float)(Find.WorldGrid.averageTileSize * 0.20000000298023224); List caravans = Find.WorldObjects.Caravans; for (int i = 0; i < caravans.Count; i++) { Caravan caravan2 = caravans[i]; - if (caravan2 != caravan) + if (caravan2 != caravan && Vector3.Distance(a, CaravanTweenerUtility.PatherTweenedPosRoot(caravan2)) < num) { - if (Vector3.Distance(a, CaravanTweenerUtility.PatherTweenedPosRoot(caravan2)) < num) - { - return true; - } + return true; } } return false; diff --git a/Assembly-CSharp/RimWorld.Planet/CaravanUtility.cs b/Assembly-CSharp/RimWorld.Planet/CaravanUtility.cs index 85901b84e..dc2f0d8b1 100644 --- a/Assembly-CSharp/RimWorld.Planet/CaravanUtility.cs +++ b/Assembly-CSharp/RimWorld.Planet/CaravanUtility.cs @@ -34,12 +34,23 @@ public static bool IsPlayerControlledCaravanMember(this Pawn pawn) public static int BestGotoDestNear(int tile, Caravan c) { - Predicate predicate = (int t) => !Find.World.Impassable(t) && c.CanReach(t); + Predicate predicate = (Predicate)delegate(int t) + { + if (Find.World.Impassable(t)) + { + return false; + } + if (!c.CanReach(t)) + { + return false; + } + return true; + }; if (predicate(tile)) { return tile; } - int result; + int result = default(int); GenWorldClosest.TryFindClosestTile(tile, predicate, out result, 50, true); return result; } diff --git a/Assembly-CSharp/RimWorld.Planet/CaravanVisitUtility.cs b/Assembly-CSharp/RimWorld.Planet/CaravanVisitUtility.cs index 07e880308..a0a074d20 100644 --- a/Assembly-CSharp/RimWorld.Planet/CaravanVisitUtility.cs +++ b/Assembly-CSharp/RimWorld.Planet/CaravanVisitUtility.cs @@ -34,18 +34,18 @@ public static Pawn BestNegotiator(Caravan caravan) public static Settlement SettlementVisitedNow(Caravan caravan) { - if (!caravan.Spawned || caravan.pather.Moving) + if (caravan.Spawned && !caravan.pather.Moving) { - return null; - } - List settlements = Find.WorldObjects.Settlements; - for (int i = 0; i < settlements.Count; i++) - { - Settlement settlement = settlements[i]; - if (settlement.Tile == caravan.Tile && settlement.Faction != caravan.Faction && settlement.Visitable) + List settlements = Find.WorldObjects.Settlements; + for (int i = 0; i < settlements.Count; i++) { - return settlement; + Settlement settlement = settlements[i]; + if (settlement.Tile == caravan.Tile && settlement.Faction != caravan.Faction && settlement.Visitable) + { + return settlement; + } } + return null; } return null; } @@ -57,7 +57,7 @@ public static Command TradeCommand(Caravan caravan) command_Action.defaultLabel = "CommandTrade".Translate(); command_Action.defaultDesc = "CommandTradeDesc".Translate(); command_Action.icon = CaravanVisitUtility.TradeCommandTex; - command_Action.action = delegate + command_Action.action = (Action)delegate() { Settlement settlement = CaravanVisitUtility.SettlementVisitedNow(caravan); if (settlement != null && settlement.CanTradeNow) @@ -68,7 +68,7 @@ public static Command TradeCommand(Caravan caravan) PawnRelationUtility.Notify_PawnsSeenByPlayer(settlement.Goods.OfType(), ref empty, ref empty2, "LetterRelatedPawnsTradingWithSettlement".Translate(), false); if (!empty2.NullOrEmpty()) { - Find.LetterStack.ReceiveLetter(empty, empty2, LetterDefOf.Good, settlement, null); + Find.LetterStack.ReceiveLetter(empty, empty2, LetterDefOf.Good, (WorldObject)settlement, (string)null); } } }; @@ -81,69 +81,67 @@ public static Command TradeCommand(Caravan caravan) public static Command FulfillRequestCommand(Caravan caravan) { - Func validator = (Thing thing) => thing.GetRotStage() == RotStage.Fresh; + Func validator = (Func)delegate(Thing thing) + { + if (thing.GetRotStage() != 0) + { + return false; + } + return true; + }; Command_Action command_Action = new Command_Action(); command_Action.defaultLabel = "CommandFulfillTradeOffer".Translate(); command_Action.defaultDesc = "CommandFulfillTradeOfferDesc".Translate(); command_Action.icon = CaravanVisitUtility.TradeCommandTex; - command_Action.action = delegate + command_Action.action = (Action)delegate() { Settlement settlement2 = CaravanVisitUtility.SettlementVisitedNow(caravan); - CaravanRequestComp caravanRequest = (settlement2 == null) ? null : settlement2.GetComponent(); + CaravanRequestComp caravanRequest = (settlement2 == null) ? null : ((WorldObject)settlement2).GetComponent(); if (caravanRequest != null) { if (!caravanRequest.ActiveRequest) { Log.Error("Attempted to fulfill an unavailable request"); - return; } - if (!CaravanInventoryUtility.HasThings(caravan, caravanRequest.requestThingDef, caravanRequest.requestCount, validator)) + else if (!CaravanInventoryUtility.HasThings(caravan, caravanRequest.requestThingDef, caravanRequest.requestCount, validator)) { - Messages.Message("CommandFulfillTradeOfferFailInsufficient".Translate(new object[] - { - GenLabel.ThingLabel(caravanRequest.requestThingDef, null, caravanRequest.requestCount) - }), MessageSound.Negative); - return; + Messages.Message("CommandFulfillTradeOfferFailInsufficient".Translate(GenLabel.ThingLabel(caravanRequest.requestThingDef, null, caravanRequest.requestCount)), MessageSound.Negative); } - Find.WindowStack.Add(Dialog_MessageBox.CreateConfirmation("CommandFulfillTradeOfferConfirm".Translate(new object[] - { - GenLabel.ThingLabel(caravanRequest.requestThingDef, null, caravanRequest.requestCount), - caravanRequest.rewards[0].Label - }), delegate + else { - int remaining = caravanRequest.requestCount; - List list = CaravanInventoryUtility.TakeThings(caravan, delegate(Thing thing) + Find.WindowStack.Add(Dialog_MessageBox.CreateConfirmation("CommandFulfillTradeOfferConfirm".Translate(GenLabel.ThingLabel(caravanRequest.requestThingDef, null, caravanRequest.requestCount), caravanRequest.rewards[0].Label), (Action)delegate() { - if (caravanRequest.requestThingDef != thing.def) + int remaining = caravanRequest.requestCount; + List list = CaravanInventoryUtility.TakeThings(caravan, (Func)delegate(Thing thing) + { + if (caravanRequest.requestThingDef != thing.def) + { + return 0; + } + int num = Mathf.Min(remaining, thing.stackCount); + remaining -= num; + return num; + }); + for (int i = 0; i < list.Count; i++) { - return 0; + list[i].Destroy(DestroyMode.Vanish); } - int num = Mathf.Min(remaining, thing.stackCount); - remaining -= num; - return num; - }); - for (int i = 0; i < list.Count; i++) - { - list[i].Destroy(DestroyMode.Vanish); - } - while (caravanRequest.rewards.Count > 0) - { - Thing thing2 = caravanRequest.rewards[caravanRequest.rewards.Count - 1]; - caravanRequest.rewards.Remove(thing2); - CaravanInventoryUtility.GiveThing(caravan, thing2); - } - caravanRequest.Disable(); - }, false, null)); + while (caravanRequest.rewards.Count > 0) + { + Thing thing2 = caravanRequest.rewards[caravanRequest.rewards.Count - 1]; + caravanRequest.rewards.Remove(thing2); + CaravanInventoryUtility.GiveThing(caravan, thing2); + } + caravanRequest.Disable(); + }, false, (string)null)); + } } }; Settlement settlement = CaravanVisitUtility.SettlementVisitedNow(caravan); - CaravanRequestComp caravanRequestComp = (settlement == null) ? null : settlement.GetComponent(); + CaravanRequestComp caravanRequestComp = (settlement == null) ? null : ((WorldObject)settlement).GetComponent(); if (!CaravanInventoryUtility.HasThings(caravan, caravanRequestComp.requestThingDef, caravanRequestComp.requestCount, validator)) { - command_Action.Disable("CommandFulfillTradeOfferFailInsufficient".Translate(new object[] - { - GenLabel.ThingLabel(caravanRequestComp.requestThingDef, null, caravanRequestComp.requestCount) - })); + command_Action.Disable("CommandFulfillTradeOfferFailInsufficient".Translate(GenLabel.ThingLabel(caravanRequestComp.requestThingDef, null, caravanRequestComp.requestCount))); } return command_Action; } diff --git a/Assembly-CSharp/RimWorld.Planet/Caravan_GotoMoteRenderer.cs b/Assembly-CSharp/RimWorld.Planet/Caravan_GotoMoteRenderer.cs index ba133c406..c2b95bbc0 100644 --- a/Assembly-CSharp/RimWorld.Planet/Caravan_GotoMoteRenderer.cs +++ b/Assembly-CSharp/RimWorld.Planet/Caravan_GotoMoteRenderer.cs @@ -1,4 +1,3 @@ -using System; using UnityEngine; using Verse; @@ -23,21 +22,20 @@ public class Caravan_GotoMoteRenderer public void RenderMote() { - float num = (Time.time - this.lastOrderedToTileTime) / 0.5f; - if (num > 1f) + float num = (float)((Time.time - this.lastOrderedToTileTime) / 0.5); + if (!(num > 1.0)) { - return; + if ((Object)Caravan_GotoMoteRenderer.cachedMaterial == (Object)null) + { + Caravan_GotoMoteRenderer.cachedMaterial = MaterialPool.MatFrom((Texture2D)Caravan_GotoMoteRenderer.FeedbackGoto.mainTexture, Caravan_GotoMoteRenderer.FeedbackGoto.shader, Color.white, WorldMaterials.DynamicObjectRenderQueue); + } + WorldGrid worldGrid = Find.WorldGrid; + Vector3 tileCenter = worldGrid.GetTileCenter(this.tile); + Color value = new Color(1f, 1f, 1f, (float)(1.0 - num)); + Caravan_GotoMoteRenderer.propertyBlock.SetColor(ShaderPropertyIDs.Color, value); + MaterialPropertyBlock materialPropertyBlock = Caravan_GotoMoteRenderer.propertyBlock; + WorldRendererUtility.DrawQuadTangentialToPlanet(tileCenter, (float)(0.800000011920929 * worldGrid.averageTileSize), 0.018f, Caravan_GotoMoteRenderer.cachedMaterial, false, false, materialPropertyBlock); } - if (Caravan_GotoMoteRenderer.cachedMaterial == null) - { - Caravan_GotoMoteRenderer.cachedMaterial = MaterialPool.MatFrom((Texture2D)Caravan_GotoMoteRenderer.FeedbackGoto.mainTexture, Caravan_GotoMoteRenderer.FeedbackGoto.shader, Color.white, WorldMaterials.DynamicObjectRenderQueue); - } - WorldGrid worldGrid = Find.WorldGrid; - Vector3 tileCenter = worldGrid.GetTileCenter(this.tile); - Color value = new Color(1f, 1f, 1f, 1f - num); - Caravan_GotoMoteRenderer.propertyBlock.SetColor(ShaderPropertyIDs.Color, value); - MaterialPropertyBlock materialPropertyBlock = Caravan_GotoMoteRenderer.propertyBlock; - WorldRendererUtility.DrawQuadTangentialToPlanet(tileCenter, 0.8f * worldGrid.averageTileSize, 0.018f, Caravan_GotoMoteRenderer.cachedMaterial, false, false, materialPropertyBlock); } public void OrderedToTile(int tile) diff --git a/Assembly-CSharp/RimWorld.Planet/Caravan_PathFollower.cs b/Assembly-CSharp/RimWorld.Planet/Caravan_PathFollower.cs index 98f6daa54..2e8645ce5 100644 --- a/Assembly-CSharp/RimWorld.Planet/Caravan_PathFollower.cs +++ b/Assembly-CSharp/RimWorld.Planet/Caravan_PathFollower.cs @@ -63,7 +63,7 @@ public void ExposeData() Scribe_Values.Look(ref this.nextTileCostTotal, "nextTileCostTotal", 0f, false); Scribe_Values.Look(ref this.destTile, "destTile", 0, false); Scribe_Deep.Look(ref this.arrivalAction, "arrivalAction", new object[0]); - if (Scribe.mode == LoadSaveMode.PostLoadInit && Current.ProgramState != ProgramState.Entry && this.moving) + if (Scribe.mode == LoadSaveMode.PostLoadInit && Current.ProgramState != 0 && this.moving) { this.StartPath(this.destTile, this.arrivalAction, true); } @@ -73,41 +73,37 @@ public void StartPath(int destTile, CaravanArrivalAction arrivalAction, bool rep { this.caravan.autoJoinable = false; if (!this.IsPassable(this.caravan.Tile) && !this.TryRecoverFromUnwalkablePosition(destTile, arrivalAction)) - { return; - } if (this.moving && this.curPath != null && this.destTile == destTile) - { return; - } if (!this.caravan.CanReach(destTile)) { this.PatherFailed(); - return; - } - this.destTile = destTile; - this.arrivalAction = arrivalAction; - if (this.nextTile < 0 || !this.IsNextTilePassable()) - { - this.nextTile = this.caravan.Tile; - } - if (this.AtDestinationPosition()) - { - this.PatherArrived(); - return; - } - if (this.curPath != null) - { - this.curPath.ReleaseToPool(); } - this.curPath = null; - this.moving = true; - if (repathImmediately) + else { - bool flag = this.TrySetNewPath(); - if (flag && this.nextTileCostLeft <= 0f && this.moving) + this.destTile = destTile; + this.arrivalAction = arrivalAction; + if (this.nextTile < 0 || !this.IsNextTilePassable()) { - this.TryEnterNextPathTile(); + this.nextTile = this.caravan.Tile; + } + if (this.AtDestinationPosition()) + { + this.PatherArrived(); + } + else + { + if (this.curPath != null) + { + this.curPath.ReleaseToPool(); + } + this.curPath = null; + this.moving = true; + if (repathImmediately && this.TrySetNewPath() && this.nextTileCostLeft <= 0.0 && this.moving) + { + this.TryEnterNextPathTile(); + } } } } @@ -131,17 +127,16 @@ public void PatherTick() { this.StopDead(); } - if (this.caravan.CantMove) + if (!this.caravan.CantMove) { - return; - } - if (this.nextTileCostLeft > 0f) - { - this.nextTileCostLeft -= this.CostToPayThisTick(); - } - else if (this.moving) - { - this.TryEnterNextPathTile(); + if (this.nextTileCostLeft > 0.0) + { + this.nextTileCostLeft -= this.CostToPayThisTick(); + } + else if (this.moving) + { + this.TryEnterNextPathTile(); + } } } @@ -168,17 +163,10 @@ public bool IsNextTilePassable() private bool TryRecoverFromUnwalkablePosition(int originalDest, CaravanArrivalAction originalArrivalAction) { - int num; - if (GenWorldClosest.TryFindClosestTile(this.caravan.Tile, (int t) => this.IsPassable(t), out num, 2147483647, true)) + int num = default(int); + if (GenWorldClosest.TryFindClosestTile(this.caravan.Tile, (Predicate)((int t) => this.IsPassable(t)), out num, 2147483647, true)) { - Log.Warning(string.Concat(new object[] - { - this.caravan, - " on unwalkable tile ", - this.caravan.Tile, - ". Teleporting to ", - num - })); + Log.Warning(this.caravan + " on unwalkable tile " + this.caravan.Tile + ". Teleporting to " + num); this.caravan.Tile = num; this.moving = false; this.nextTile = this.caravan.Tile; @@ -186,13 +174,7 @@ private bool TryRecoverFromUnwalkablePosition(int originalDest, CaravanArrivalAc return true; } Find.WorldObjects.Remove(this.caravan); - Log.Error(string.Concat(new object[] - { - this.caravan, - " on unwalkable tile ", - this.caravan.Tile, - ". Could not find walkable position nearby. Removed." - })); + Log.Error(this.caravan + " on unwalkable tile " + this.caravan.Tile + ". Could not find walkable position nearby. Removed."); return false; } @@ -206,10 +188,7 @@ private void PatherArrived() } else if (this.caravan.IsPlayerControlled && !this.caravan.VisibleToCameraNow()) { - Messages.Message("MessageCaravanArrivedAtDestination".Translate(new object[] - { - this.caravan.Label - }).CapitalizeFirst(), this.caravan, MessageSound.Benefit); + Messages.Message("MessageCaravanArrivedAtDestination".Translate(this.caravan.Label).CapitalizeFirst(), (WorldObject)this.caravan, MessageSound.Benefit); } } @@ -223,26 +202,25 @@ private void TryEnterNextPathTile() if (!this.IsNextTilePassable()) { this.PatherFailed(); - return; - } - this.caravan.Tile = this.nextTile; - if (this.NeedNewPath() && !this.TrySetNewPath()) - { - return; - } - if (this.AtDestinationPosition()) - { - this.PatherArrived(); } else { - if (this.curPath.NodesLeftCount == 0) + this.caravan.Tile = this.nextTile; + if (this.NeedNewPath() && !this.TrySetNewPath()) + return; + if (this.AtDestinationPosition()) + { + this.PatherArrived(); + } + else if (this.curPath.NodesLeftCount == 0) { Log.Error(this.caravan + " ran out of path nodes. Force-arriving."); this.PatherArrived(); - return; } - this.SetupMoveIntoNextTile(); + else + { + this.SetupMoveIntoNextTile(); + } } } @@ -250,32 +228,20 @@ private void SetupMoveIntoNextTile() { if (this.curPath.NodesLeftCount < 2) { - Log.Error(string.Concat(new object[] - { - this.caravan, - " at ", - this.caravan.Tile, - " ran out of path nodes while pathing to ", - this.destTile, - "." - })); + Log.Error(this.caravan + " at " + this.caravan.Tile + " ran out of path nodes while pathing to " + this.destTile + "."); this.PatherFailed(); - return; } - this.nextTile = this.curPath.ConsumeNextNode(); - if (Find.World.Impassable(this.nextTile)) + else { - Log.Error(string.Concat(new object[] + this.nextTile = this.curPath.ConsumeNextNode(); + if (Find.World.Impassable(this.nextTile)) { - this.caravan, - " entering ", - this.nextTile, - " which is unwalkable." - })); + Log.Error(this.caravan + " entering " + this.nextTile + " which is unwalkable."); + } + int num = this.CostToMove(this.caravan.Tile, this.nextTile); + this.nextTileCostTotal = (float)num; + this.nextTileCostLeft = (float)num; } - int num = this.CostToMove(this.caravan.Tile, this.nextTile); - this.nextTileCostTotal = (float)num; - this.nextTileCostLeft = (float)num; } private int CostToMove(int start, int end) @@ -301,18 +267,20 @@ public static int CostToDisplay(Caravan caravan, int start, int end, float yearP { return Caravan_PathFollower.CostToMove(caravan.TicksPerMove, start, end, yearPercent); } - int num = caravan.TicksPerMove; - num += WorldPathGrid.CalculatedCostAt(start, false, yearPercent); + int ticksPerMove = caravan.TicksPerMove; + ticksPerMove += WorldPathGrid.CalculatedCostAt(start, false, yearPercent); Tile tile = Find.WorldGrid[start]; - float num2 = 1f; + float num = 1f; if (tile.roads != null) { for (int i = 0; i < tile.roads.Count; i++) { - num2 = Mathf.Min(num2, tile.roads[i].road.movementCostMultiplier); + float a = num; + Tile.RoadLink roadLink = tile.roads[i]; + num = Mathf.Min(a, roadLink.road.movementCostMultiplier); } } - return Mathf.RoundToInt((float)num * num2); + return Mathf.RoundToInt((float)ticksPerMove * num); } private float CostToPayThisTick() @@ -322,9 +290,9 @@ private float CostToPayThisTick() { num = 100f; } - if (num < this.nextTileCostTotal / 120000f) + if (num < this.nextTileCostTotal / 120000.0) { - num = this.nextTileCostTotal / 120000f; + num = (float)(this.nextTileCostTotal / 120000.0); } return num; } @@ -368,21 +336,21 @@ private bool NeedNewPath() { return false; } - if (this.curPath == null || !this.curPath.Found || this.curPath.NodesLeftCount == 0) - { - return true; - } - int num = 0; - while (num < 20 && num < this.curPath.NodesLeftCount) + if (((this.curPath != null) ? (this.curPath.Found ? this.curPath.NodesLeftCount : 0) : 0) != 0) { - int tileID = this.curPath.Peek(num); - if (Find.World.Impassable(tileID)) + int num = 0; + while (num < 20 && num < this.curPath.NodesLeftCount) { - return true; + int tileID = this.curPath.Peek(num); + if (Find.World.Impassable(tileID)) + { + return true; + } + num++; } - num++; + return false; } - return false; + return true; } } } diff --git a/Assembly-CSharp/RimWorld.Planet/Caravan_TraderTracker.cs b/Assembly-CSharp/RimWorld.Planet/Caravan_TraderTracker.cs index 27b0330a0..12ab29d9b 100644 --- a/Assembly-CSharp/RimWorld.Planet/Caravan_TraderTracker.cs +++ b/Assembly-CSharp/RimWorld.Planet/Caravan_TraderTracker.cs @@ -1,6 +1,5 @@ using System; using System.Collections.Generic; -using System.Diagnostics; using System.Linq; using Verse; @@ -33,11 +32,20 @@ public IEnumerable Goods { get { - Caravan_TraderTracker.<>c__Iterator100 <>c__Iterator = new Caravan_TraderTracker.<>c__Iterator100(); - <>c__Iterator.<>f__this = this; - Caravan_TraderTracker.<>c__Iterator100 expr_0E = <>c__Iterator; - expr_0E.$PC = -2; - return expr_0E; + List inv = CaravanInventoryUtility.AllInventoryItems(this.caravan); + for (int j = 0; j < inv.Count; j++) + { + yield return inv[j]; + } + List pawns = this.caravan.PawnsListForReading; + for (int i = 0; i < pawns.Count; i++) + { + Pawn p = pawns[i]; + if (!this.caravan.IsOwner(p) && (!p.RaceProps.packAnimal || p.inventory == null || p.inventory.innerContainer.Count <= 0) && !this.soldPrisoners.Contains(p)) + { + yield return (Thing)p; + } + } } } @@ -61,7 +69,7 @@ public bool CanTradeNow { get { - return this.TraderKind != null && !this.caravan.AllOwnersDowned && this.caravan.Faction != Faction.OfPlayer && this.Goods.Any((Thing x) => this.TraderKind.WillTrade(x.def)); + return this.TraderKind != null && !this.caravan.AllOwnersDowned && this.caravan.Faction != Faction.OfPlayer && this.Goods.Any((Func)((Thing x) => this.TraderKind.WillTrade(x.def))); } } @@ -75,19 +83,34 @@ public void ExposeData() Scribe_Collections.Look(ref this.soldPrisoners, "soldPrisoners", LookMode.Reference, new object[0]); if (Scribe.mode == LoadSaveMode.PostLoadInit) { - this.soldPrisoners.RemoveAll((Pawn x) => x == null); + this.soldPrisoners.RemoveAll((Predicate)((Pawn x) => x == null)); } } - [DebuggerHidden] public IEnumerable ColonyThingsWillingToBuy(Pawn playerNegotiator) { - Caravan_TraderTracker.c__Iterator101 c__Iterator = new Caravan_TraderTracker.c__Iterator101(); - c__Iterator.playerNegotiator = playerNegotiator; - c__Iterator.<$>playerNegotiator = playerNegotiator; - Caravan_TraderTracker.c__Iterator101 expr_15 = c__Iterator; - expr_15.$PC = -2; - return expr_15; + Caravan playerCaravan = playerNegotiator.GetCaravan(); + List.Enumerator enumerator = CaravanInventoryUtility.AllInventoryItems(playerCaravan).GetEnumerator(); + try + { + while (enumerator.MoveNext()) + { + Thing item = enumerator.Current; + yield return item; + } + } + finally + { + ((IDisposable)(object)enumerator).Dispose(); + } + List pawns = playerCaravan.PawnsListForReading; + for (int i = 0; i < pawns.Count; i++) + { + if (!playerCaravan.IsOwner(pawns[i])) + { + yield return (Thing)pawns[i]; + } + } } public void GiveSoldThingToTrader(Thing toGive, int countToGive, Pawn playerNegotiator) @@ -95,37 +118,39 @@ public void GiveSoldThingToTrader(Thing toGive, int countToGive, Pawn playerNego if (this.Goods.Contains(toGive)) { Log.Error("Tried to add " + toGive + " to stock (pawn's trader tracker), but it's already here."); - return; - } - Caravan caravan = playerNegotiator.GetCaravan(); - Thing thing = toGive.SplitOff(countToGive); - thing.PreTraded(TradeAction.PlayerSells, playerNegotiator, this.caravan); - Pawn pawn = thing as Pawn; - if (pawn != null) - { - CaravanInventoryUtility.MoveAllInventoryToSomeoneElse(pawn, caravan.PawnsListForReading, null); - this.caravan.AddPawn(pawn, false); - if (pawn.IsWorldPawn() && !this.caravan.Spawned) - { - Find.WorldPawns.RemovePawn(pawn); - } - if (pawn.RaceProps.Humanlike) - { - this.soldPrisoners.Add(pawn); - } } else { - Pawn pawn2 = CaravanInventoryUtility.FindPawnToMoveInventoryTo(thing, this.caravan.PawnsListForReading, null, null); - if (pawn2 == null) + Caravan caravan = playerNegotiator.GetCaravan(); + Thing thing = toGive.SplitOff(countToGive); + thing.PreTraded(TradeAction.PlayerSells, playerNegotiator, this.caravan); + Pawn pawn = thing as Pawn; + if (pawn != null) { - Log.Error("Could not find pawn to move sold thing to (sold by player). thing=" + thing); - thing.Destroy(DestroyMode.Vanish); + CaravanInventoryUtility.MoveAllInventoryToSomeoneElse(pawn, caravan.PawnsListForReading, null); + this.caravan.AddPawn(pawn, false); + if (pawn.IsWorldPawn() && !this.caravan.Spawned) + { + Find.WorldPawns.RemovePawn(pawn); + } + if (pawn.RaceProps.Humanlike) + { + this.soldPrisoners.Add(pawn); + } } - else if (!pawn2.inventory.innerContainer.TryAdd(thing, true)) + else { - Log.Error("Could not add item to inventory."); - thing.Destroy(DestroyMode.Vanish); + Pawn pawn2 = CaravanInventoryUtility.FindPawnToMoveInventoryTo(thing, this.caravan.PawnsListForReading, null, null); + if (pawn2 == null) + { + Log.Error("Could not find pawn to move sold thing to (sold by player). thing=" + thing); + thing.Destroy(DestroyMode.Vanish); + } + else if (!pawn2.inventory.innerContainer.TryAdd(thing, true)) + { + Log.Error("Could not add item to inventory."); + thing.Destroy(DestroyMode.Vanish); + } } } } diff --git a/Assembly-CSharp/RimWorld.Planet/Caravan_Tweener.cs b/Assembly-CSharp/RimWorld.Planet/Caravan_Tweener.cs index b3eb8f8d3..7ccc7e491 100644 --- a/Assembly-CSharp/RimWorld.Planet/Caravan_Tweener.cs +++ b/Assembly-CSharp/RimWorld.Planet/Caravan_Tweener.cs @@ -1,4 +1,3 @@ -using System; using UnityEngine; namespace RimWorld.Planet diff --git a/Assembly-CSharp/RimWorld.Planet/CaravansBattlefield.cs b/Assembly-CSharp/RimWorld.Planet/CaravansBattlefield.cs index 68b1ec65e..a6b777bae 100644 --- a/Assembly-CSharp/RimWorld.Planet/CaravansBattlefield.cs +++ b/Assembly-CSharp/RimWorld.Planet/CaravansBattlefield.cs @@ -1,4 +1,3 @@ -using System; using Verse; namespace RimWorld.Planet @@ -43,20 +42,12 @@ public override void Tick() private void CheckWonBattle() { - if (this.wonBattle) + if (!this.wonBattle && !GenHostility.AnyHostileActiveThreat(base.Map)) { - return; + Messages.Message("MessageAmbushVictory".Translate(MapParent.GetForceExitAndRemoveMapCountdownTimeLeftString(60000)), (WorldObject)this, MessageSound.Benefit); + this.wonBattle = true; + base.StartForceExitAndRemoveMapCountdown(); } - if (GenHostility.AnyHostileActiveThreat(base.Map)) - { - return; - } - Messages.Message("MessageAmbushVictory".Translate(new object[] - { - MapParent.GetForceExitAndRemoveMapCountdownTimeLeftString(60000) - }), this, MessageSound.Benefit); - this.wonBattle = true; - base.StartForceExitAndRemoveMapCountdown(); } } } diff --git a/Assembly-CSharp/RimWorld.Planet/CompassWidget.cs b/Assembly-CSharp/RimWorld.Planet/CompassWidget.cs index 823d750b1..5399eff54 100644 --- a/Assembly-CSharp/RimWorld.Planet/CompassWidget.cs +++ b/Assembly-CSharp/RimWorld.Planet/CompassWidget.cs @@ -1,4 +1,3 @@ -using System; using UnityEngine; using Verse; @@ -18,14 +17,14 @@ private static float Angle get { Vector2 vector = GenWorldUI.WorldToUIPosition(Find.WorldGrid.NorthPolePos); - Vector2 vector2 = new Vector2((float)UI.screenWidth / 2f, (float)UI.screenHeight / 2f); - return Mathf.Atan2(vector.y - vector2.y, vector.x - vector2.x) * 57.29578f; + Vector2 vector2 = new Vector2((float)((float)UI.screenWidth / 2.0), (float)((float)UI.screenHeight / 2.0)); + return (float)(Mathf.Atan2(vector.y - vector2.y, vector.x - vector2.x) * 57.295780181884766); } } public static void CompassOnGUI(ref float curBaseY) { - Vector2 center = new Vector2((float)UI.screenWidth - 10f - 32f, curBaseY - 10f - 32f); + Vector2 center = new Vector2((float)((float)UI.screenWidth - 10.0 - 32.0), (float)(curBaseY - 10.0 - 32.0)); CompassWidget.CompassOnGUI(center); curBaseY -= 84f; } @@ -33,7 +32,7 @@ public static void CompassOnGUI(ref float curBaseY) private static void CompassOnGUI(Vector2 center) { Widgets.DrawTextureRotated(center, CompassWidget.CompassTex, CompassWidget.Angle, 1f); - Rect rect = new Rect(center.x - 32f, center.y - 32f, 64f, 64f); + Rect rect = new Rect((float)(center.x - 32.0), (float)(center.y - 32.0), 64f, 64f); TooltipHandler.TipRegion(rect, "CompassTip".Translate()); if (Widgets.ButtonInvisible(rect, false)) { diff --git a/Assembly-CSharp/RimWorld.Planet/DaysUntilRotCalculator.cs b/Assembly-CSharp/RimWorld.Planet/DaysUntilRotCalculator.cs index 0919062eb..75fa25f0d 100644 --- a/Assembly-CSharp/RimWorld.Planet/DaysUntilRotCalculator.cs +++ b/Assembly-CSharp/RimWorld.Planet/DaysUntilRotCalculator.cs @@ -1,4 +1,3 @@ -using System; using System.Collections.Generic; using UnityEngine; using Verse; @@ -24,7 +23,7 @@ public static float ApproxDaysUntilRot(List potentiallyFood, int assuming CompRottable compRottable = thing.TryGetComp(); if (compRottable != null) { - num = Mathf.Min(num, (float)compRottable.ApproxTicksUntilRotWhenAtTempOfTile(assumingTile) / 60000f); + num = Mathf.Min(num, (float)((float)compRottable.ApproxTicksUntilRotWhenAtTempOfTile(assumingTile) / 60000.0)); } } } @@ -80,15 +79,15 @@ public static float ApproxDaysUntilRotLeftAfterTransfer(List { if (transferableOneWay.AnyThing is Pawn) { - for (int j = transferableOneWay.things.Count - 1; j >= transferableOneWay.CountToTransfer; j--) + for (int num = transferableOneWay.things.Count - 1; num >= transferableOneWay.CountToTransfer; num--) { - Pawn pawn = (Pawn)transferableOneWay.things[j]; + Pawn pawn = (Pawn)transferableOneWay.things[num]; if (!InventoryCalculatorsUtility.ShouldIgnoreInventoryOf(pawn, ignoreInventory)) { ThingOwner innerContainer = pawn.inventory.innerContainer; - for (int k = 0; k < innerContainer.Count; k++) + for (int j = 0; j < innerContainer.Count; j++) { - DaysUntilRotCalculator.tmpThings.Add(innerContainer[k]); + DaysUntilRotCalculator.tmpThings.Add(innerContainer[j]); } } } @@ -108,25 +107,25 @@ public static float ApproxDaysUntilRotLeftAfterTradeableTransfer(List all { TransferableUtility.SimulateTradeableTransfer(allCurrentThings, tradeables, DaysUntilRotCalculator.tmpThingStackParts); DaysUntilRotCalculator.tmpThings.Clear(); - for (int i = DaysUntilRotCalculator.tmpThingStackParts.Count - 1; i >= 0; i--) + for (int num = DaysUntilRotCalculator.tmpThingStackParts.Count - 1; num >= 0; num--) { - if (DaysUntilRotCalculator.tmpThingStackParts[i].Count > 0) + if (DaysUntilRotCalculator.tmpThingStackParts[num].Count > 0) { - Pawn pawn = DaysUntilRotCalculator.tmpThingStackParts[i].Thing as Pawn; + Pawn pawn = DaysUntilRotCalculator.tmpThingStackParts[num].Thing as Pawn; if (pawn != null) { if (!InventoryCalculatorsUtility.ShouldIgnoreInventoryOf(pawn, ignoreInventory)) { ThingOwner innerContainer = pawn.inventory.innerContainer; - for (int j = 0; j < innerContainer.Count; j++) + for (int i = 0; i < innerContainer.Count; i++) { - DaysUntilRotCalculator.tmpThings.Add(innerContainer[j]); + DaysUntilRotCalculator.tmpThings.Add(innerContainer[i]); } } } else { - DaysUntilRotCalculator.tmpThings.Add(DaysUntilRotCalculator.tmpThingStackParts[i].Thing); + DaysUntilRotCalculator.tmpThings.Add(DaysUntilRotCalculator.tmpThingStackParts[num].Thing); } } } diff --git a/Assembly-CSharp/RimWorld.Planet/DaysWorthOfFoodCalculator.cs b/Assembly-CSharp/RimWorld.Planet/DaysWorthOfFoodCalculator.cs index 789560438..edbbf5262 100644 --- a/Assembly-CSharp/RimWorld.Planet/DaysWorthOfFoodCalculator.cs +++ b/Assembly-CSharp/RimWorld.Planet/DaysWorthOfFoodCalculator.cs @@ -1,4 +1,3 @@ -using System; using System.Collections.Generic; using UnityEngine; using Verse; @@ -52,7 +51,7 @@ private static float ApproxDaysWorthOfFood(List pawns, List ex } } } - if (!DaysWorthOfFoodCalculator.tmpFood.Any()) + if (!DaysWorthOfFoodCalculator.tmpFood.Any()) { return 0f; } @@ -64,48 +63,41 @@ private static float ApproxDaysWorthOfFood(List pawns, List ex DaysWorthOfFoodCalculator.tmpAnyFoodLeftIngestibleByPawn.Add(true); } float num = 0f; - bool flag; - do + while (true) { - flag = false; + bool flag = false; for (int m = 0; m < pawns.Count; m++) { Pawn pawn = pawns[m]; - if (DaysWorthOfFoodCalculator.tmpAnyFoodLeftIngestibleByPawn[m]) + if (DaysWorthOfFoodCalculator.tmpAnyFoodLeftIngestibleByPawn[m] && pawn.RaceProps.EatsFood && (!assumeCanEatLocalPlants || !VirtualPlantsUtility.CanEverEatVirtualPlants(pawn))) { - if (pawn.RaceProps.EatsFood && (!assumeCanEatLocalPlants || !VirtualPlantsUtility.CanEverEatVirtualPlants(pawn))) + while (true) { - do + int num2 = DaysWorthOfFoodCalculator.BestEverEdibleFoodIndexFor(pawns[m], DaysWorthOfFoodCalculator.tmpFood); + if (num2 < 0) { - int num2 = DaysWorthOfFoodCalculator.BestEverEdibleFoodIndexFor(pawns[m], DaysWorthOfFoodCalculator.tmpFood); - if (num2 < 0) - { - goto Block_13; - } - float num3 = Mathf.Min(DaysWorthOfFoodCalculator.tmpFood[num2].ThingDef.ingestible.nutrition, pawn.needs.food.NutritionBetweenHungryAndFed); - float num4 = num3 / pawn.needs.food.NutritionBetweenHungryAndFed * (float)pawn.needs.food.TicksUntilHungryWhenFed / 60000f; - List list; - List expr_25A = list = DaysWorthOfFoodCalculator.tmpDaysWorthOfFoodPerPawn; - int index; - int expr_25F = index = m; - float num5 = list[index]; - expr_25A[expr_25F] = num5 + num4; - DaysWorthOfFoodCalculator.tmpFood[num2] = DaysWorthOfFoodCalculator.tmpFood[num2].WithCount(DaysWorthOfFoodCalculator.tmpFood[num2].Count - 1); - flag = true; + DaysWorthOfFoodCalculator.tmpAnyFoodLeftIngestibleByPawn[m] = false; + break; } - while (DaysWorthOfFoodCalculator.tmpDaysWorthOfFoodPerPawn[m] < num); - IL_2C5: - num = Mathf.Max(num, DaysWorthOfFoodCalculator.tmpDaysWorthOfFoodPerPawn[m]); - goto IL_2DA; - Block_13: - DaysWorthOfFoodCalculator.tmpAnyFoodLeftIngestibleByPawn[m] = false; - goto IL_2C5; + float num3 = Mathf.Min(DaysWorthOfFoodCalculator.tmpFood[num2].ThingDef.ingestible.nutrition, pawn.needs.food.NutritionBetweenHungryAndFed); + float num4 = (float)(num3 / pawn.needs.food.NutritionBetweenHungryAndFed * (float)pawn.needs.food.TicksUntilHungryWhenFed / 60000.0); + List list; + List obj = list = DaysWorthOfFoodCalculator.tmpDaysWorthOfFoodPerPawn; + int index; + int index2 = index = m; + float num5 = list[index]; + obj[index2] = num5 + num4; + DaysWorthOfFoodCalculator.tmpFood[num2] = DaysWorthOfFoodCalculator.tmpFood[num2].WithCount(DaysWorthOfFoodCalculator.tmpFood[num2].Count - 1); + flag = true; + if (!(DaysWorthOfFoodCalculator.tmpDaysWorthOfFoodPerPawn[m] < num)) + break; } + num = Mathf.Max(num, DaysWorthOfFoodCalculator.tmpDaysWorthOfFoodPerPawn[m]); } - IL_2DA:; } + if (!flag) + break; } - while (flag); float num6 = 1000f; for (int n = 0; n < pawns.Count; n++) { @@ -119,7 +111,7 @@ private static float ApproxDaysWorthOfFood(List pawns, List ex public static float ApproxDaysWorthOfFood(Caravan caravan) { - return DaysWorthOfFoodCalculator.ApproxDaysWorthOfFood(caravan.PawnsListForReading, null, VirtualPlantsUtility.EnvironmentAllowsEatingVirtualPlantsNowAt(caravan.Tile), IgnorePawnsInventoryMode.DontIgnore); + return DaysWorthOfFoodCalculator.ApproxDaysWorthOfFood(caravan.PawnsListForReading, (List)null, VirtualPlantsUtility.EnvironmentAllowsEatingVirtualPlantsNowAt(caravan.Tile), IgnorePawnsInventoryMode.DontIgnore); } public static float ApproxDaysWorthOfFood(List transferables, bool assumeCanEatLocalPlants, IgnorePawnsInventoryMode ignoreInventory) @@ -165,9 +157,9 @@ public static float ApproxDaysWorthOfFoodLeftAfterTransfer(List= transferableOneWay.CountToTransfer; j--) + for (int num = transferableOneWay.things.Count - 1; num >= transferableOneWay.CountToTransfer; num--) { - Pawn pawn = (Pawn)transferableOneWay.things[j]; + Pawn pawn = (Pawn)transferableOneWay.things[num]; if (pawn.RaceProps.EatsFood && (!assumeCanEatLocalPlants || !VirtualPlantsUtility.CanEverEatVirtualPlants(pawn))) { DaysWorthOfFoodCalculator.tmpPawns.Add(pawn); @@ -225,9 +217,9 @@ public static float ApproxDaysWorthOfFoodLeftAfterTradeableTransfer(List TransferableUtility.SimulateTradeableTransfer(allCurrentThings, tradeables, DaysWorthOfFoodCalculator.tmpThingStackParts); DaysWorthOfFoodCalculator.tmpPawns.Clear(); DaysWorthOfFoodCalculator.tmpThingCounts.Clear(); - for (int i = DaysWorthOfFoodCalculator.tmpThingStackParts.Count - 1; i >= 0; i--) + for (int num = DaysWorthOfFoodCalculator.tmpThingStackParts.Count - 1; num >= 0; num--) { - Pawn pawn = DaysWorthOfFoodCalculator.tmpThingStackParts[i].Thing as Pawn; + Pawn pawn = DaysWorthOfFoodCalculator.tmpThingStackParts[num].Thing as Pawn; if (pawn != null) { if (pawn.RaceProps.EatsFood && (!assumeCanEatLocalPlants || !VirtualPlantsUtility.CanEverEatVirtualPlants(pawn))) @@ -237,7 +229,7 @@ public static float ApproxDaysWorthOfFoodLeftAfterTradeableTransfer(List } else { - DaysWorthOfFoodCalculator.tmpThingCounts.Add(new ThingCount(DaysWorthOfFoodCalculator.tmpThingStackParts[i].Thing.def, DaysWorthOfFoodCalculator.tmpThingStackParts[i].Count)); + DaysWorthOfFoodCalculator.tmpThingCounts.Add(new ThingCount(DaysWorthOfFoodCalculator.tmpThingStackParts[num].Thing.def, DaysWorthOfFoodCalculator.tmpThingStackParts[num].Count)); } } DaysWorthOfFoodCalculator.tmpThingStackParts.Clear(); diff --git a/Assembly-CSharp/RimWorld.Planet/DebugTile.cs b/Assembly-CSharp/RimWorld.Planet/DebugTile.cs index 8fa88e93d..67d5f20a7 100644 --- a/Assembly-CSharp/RimWorld.Planet/DebugTile.cs +++ b/Assembly-CSharp/RimWorld.Planet/DebugTile.cs @@ -1,4 +1,3 @@ -using System; using System.Collections.Generic; using UnityEngine; using Verse; @@ -36,8 +35,7 @@ private bool VisibleForCamera { get { - Rect rect = new Rect(0f, 0f, (float)UI.screenWidth, (float)UI.screenHeight); - return rect.Contains(this.ScreenPos); + return new Rect(0f, 0f, (float)UI.screenWidth, (float)UI.screenHeight).Contains(this.ScreenPos); } } @@ -52,55 +50,53 @@ public float DistanceToCamera public void Draw() { - if (!this.VisibleForCamera) + if (this.VisibleForCamera) { - return; - } - if (this.mesh == null) - { - Find.WorldGrid.GetTileVertices(this.tile, DebugTile.tmpVerts); - for (int i = 0; i < DebugTile.tmpVerts.Count; i++) + if ((Object)this.mesh == (Object)null) { - Vector3 a = DebugTile.tmpVerts[i]; - DebugTile.tmpVerts[i] = a + a.normalized * 0.012f; + Find.WorldGrid.GetTileVertices(this.tile, DebugTile.tmpVerts); + for (int i = 0; i < DebugTile.tmpVerts.Count; i++) + { + Vector3 a = DebugTile.tmpVerts[i]; + DebugTile.tmpVerts[i] = a + a.normalized * 0.012f; + } + this.mesh = new Mesh(); + this.mesh.name = "DebugTile"; + this.mesh.SetVertices(DebugTile.tmpVerts); + DebugTile.tmpIndices.Clear(); + for (int j = 0; j < DebugTile.tmpVerts.Count - 2; j++) + { + DebugTile.tmpIndices.Add(j + 2); + DebugTile.tmpIndices.Add(j + 1); + DebugTile.tmpIndices.Add(0); + } + this.mesh.SetTriangles(DebugTile.tmpIndices, 0); } - this.mesh = new Mesh(); - this.mesh.name = "DebugTile"; - this.mesh.SetVertices(DebugTile.tmpVerts); - DebugTile.tmpIndices.Clear(); - for (int j = 0; j < DebugTile.tmpVerts.Count - 2; j++) + Material material; + if ((Object)this.customMat != (Object)null) { - DebugTile.tmpIndices.Add(j + 2); - DebugTile.tmpIndices.Add(j + 1); - DebugTile.tmpIndices.Add(0); + material = this.customMat; } - this.mesh.SetTriangles(DebugTile.tmpIndices, 0); - } - Material material; - if (this.customMat != null) - { - material = this.customMat; - } - else - { - int num = Mathf.RoundToInt(this.colorPct * 100f); - num %= 100; - material = WorldDebugMatsSpectrum.Mat(num); + else + { + int num = Mathf.RoundToInt((float)(this.colorPct * 100.0)); + num %= 100; + material = WorldDebugMatsSpectrum.Mat(num); + } + Graphics.DrawMesh(this.mesh, Vector3.zero, Quaternion.identity, material, WorldCameraManager.WorldLayer); } - Graphics.DrawMesh(this.mesh, Vector3.zero, Quaternion.identity, material, WorldCameraManager.WorldLayer); } public void OnGUI() { - if (!this.VisibleForCamera) - { - return; - } - Vector2 screenPos = this.ScreenPos; - Rect rect = new Rect(screenPos.x - 20f, screenPos.y - 20f, 40f, 40f); - if (this.displayString != null) + if (this.VisibleForCamera) { - Widgets.Label(rect, this.displayString); + Vector2 screenPos = this.ScreenPos; + Rect rect = new Rect((float)(screenPos.x - 20.0), (float)(screenPos.y - 20.0), 40f, 40f); + if (this.displayString != null) + { + Widgets.Label(rect, this.displayString); + } } } } diff --git a/Assembly-CSharp/RimWorld.Planet/DebugWorldLine.cs b/Assembly-CSharp/RimWorld.Planet/DebugWorldLine.cs index 4f54d5ab6..cde7bb832 100644 --- a/Assembly-CSharp/RimWorld.Planet/DebugWorldLine.cs +++ b/Assembly-CSharp/RimWorld.Planet/DebugWorldLine.cs @@ -1,4 +1,3 @@ -using System; using UnityEngine; using Verse; @@ -45,27 +44,26 @@ public DebugWorldLine(Vector3 a, Vector3 b, bool onPlanetSurface, int ticksLeft) public void Draw() { float num = Vector3.Distance(this.a, this.b); - if (num < 0.001f) + if (!(num < 0.0010000000474974513)) { - return; - } - if (this.onPlanetSurface) - { - float averageTileSize = Find.WorldGrid.averageTileSize; - int num2 = Mathf.Max(Mathf.RoundToInt(num / averageTileSize), 0); - float num3 = 0.05f; - for (int i = 0; i < num2; i++) + if (this.onPlanetSurface) { - Vector3 vector = Vector3.Lerp(this.a, this.b, (float)i / (float)num2); - Vector3 vector2 = Vector3.Lerp(this.a, this.b, (float)(i + 1) / (float)num2); - vector = vector.normalized * (100f + num3); - vector2 = vector2.normalized * (100f + num3); - GenDraw.DrawWorldLineBetween(vector, vector2); + float averageTileSize = Find.WorldGrid.averageTileSize; + int num2 = Mathf.Max(Mathf.RoundToInt(num / averageTileSize), 0); + float num3 = 0.05f; + for (int num4 = 0; num4 < num2; num4++) + { + Vector3 vector = Vector3.Lerp(this.a, this.b, (float)num4 / (float)num2); + Vector3 vector2 = Vector3.Lerp(this.a, this.b, (float)(num4 + 1) / (float)num2); + vector = vector.normalized * (float)(100.0 + num3); + vector2 = vector2.normalized * (float)(100.0 + num3); + GenDraw.DrawWorldLineBetween(vector, vector2); + } + } + else + { + GenDraw.DrawWorldLineBetween(this.a, this.b); } - } - else - { - GenDraw.DrawWorldLineBetween(this.a, this.b); } } } diff --git a/Assembly-CSharp/RimWorld.Planet/DefeatAllEnemiesQuestComp.cs b/Assembly-CSharp/RimWorld.Planet/DefeatAllEnemiesQuestComp.cs index 808d601b5..9bc610231 100644 --- a/Assembly-CSharp/RimWorld.Planet/DefeatAllEnemiesQuestComp.cs +++ b/Assembly-CSharp/RimWorld.Planet/DefeatAllEnemiesQuestComp.cs @@ -1,4 +1,3 @@ -using System; using System.Collections.Generic; using Verse; @@ -51,7 +50,7 @@ public override void CompTick() base.CompTick(); if (this.active) { - MapParent mapParent = this.parent as MapParent; + MapParent mapParent = base.parent as MapParent; if (mapParent != null) { this.CheckAllEnemiesDefeated(mapParent); @@ -61,16 +60,11 @@ public override void CompTick() private void CheckAllEnemiesDefeated(MapParent mapParent) { - if (!mapParent.HasMap) + if (mapParent.HasMap && !GenHostility.AnyHostileActiveThreat(mapParent.Map)) { - return; + this.GiveRewardsAndSendLetter(); + this.StopQuest(); } - if (GenHostility.AnyHostileActiveThreat(mapParent.Map)) - { - return; - } - this.GiveRewardsAndSendLetter(); - this.StopQuest(); } public override void PostExposeData() @@ -79,7 +73,7 @@ public override void PostExposeData() Scribe_Values.Look(ref this.active, "active", false, false); Scribe_Values.Look(ref this.relationsImprovement, "relationsImprovement", 0f, false); Scribe_References.Look(ref this.requestingFaction, "requestingFaction", false); - Scribe_Deep.Look(ref this.rewards, "rewards", new object[] + Scribe_Deep.Look(ref this.rewards, "rewards", new object[1] { this }); @@ -87,17 +81,13 @@ public override void PostExposeData() private void GiveRewardsAndSendLetter() { - Map map = Find.AnyPlayerHomeMap ?? ((MapParent)this.parent).Map; + Map map = Find.AnyPlayerHomeMap ?? ((MapParent)base.parent).Map; DefeatAllEnemiesQuestComp.tmpRewards.AddRange(this.rewards); this.rewards.Clear(); IntVec3 intVec = DropCellFinder.TradeDropSpot(map); DropPodUtility.DropThingsNear(intVec, map, DefeatAllEnemiesQuestComp.tmpRewards, 110, false, false, true); DefeatAllEnemiesQuestComp.tmpRewards.Clear(); - Find.LetterStack.ReceiveLetter("LetterLabelDefeatAllEnemiesQuestCompleted".Translate(), "LetterDefeatAllEnemiesQuestCompleted".Translate(new object[] - { - this.requestingFaction.Name, - this.relationsImprovement.ToString("F0") - }), LetterDefOf.Good, new GlobalTargetInfo(intVec, map, false), null); + Find.LetterStack.ReceiveLetter("LetterLabelDefeatAllEnemiesQuestCompleted".Translate(), "LetterDefeatAllEnemiesQuestCompleted".Translate(this.requestingFaction.Name, this.relationsImprovement.ToString("F0")), LetterDefOf.Good, new GlobalTargetInfo(intVec, map, false), (string)null); } public void GetChildHolders(List outChildren) @@ -120,18 +110,20 @@ public override string CompInspectStringExtra() { if (this.active) { - return "QuestTargetDestroyInspectString".Translate(new object[] - { - this.requestingFaction.Name, - this.rewards[0].LabelCap - }).CapitalizeFirst(); + return "QuestTargetDestroyInspectString".Translate(this.requestingFaction.Name, this.rewards[0].LabelCap).CapitalizeFirst(); } - return null; + return (string)null; } virtual IThingHolder get_ParentHolder() { return base.ParentHolder; } + + IThingHolder IThingHolder.get_ParentHolder() + { + //ILSpy generated this explicit interface implementation from .override directive in get_ParentHolder + return this.get_ParentHolder(); + } } } diff --git a/Assembly-CSharp/RimWorld.Planet/DestroyedFactionBase.cs b/Assembly-CSharp/RimWorld.Planet/DestroyedFactionBase.cs index 3b0af0a76..9e2315e3e 100644 --- a/Assembly-CSharp/RimWorld.Planet/DestroyedFactionBase.cs +++ b/Assembly-CSharp/RimWorld.Planet/DestroyedFactionBase.cs @@ -1,6 +1,4 @@ -using System; using System.Collections.Generic; -using System.Diagnostics; using Verse; namespace RimWorld.Planet @@ -18,14 +16,16 @@ public override bool ShouldRemoveMapNow(out bool alsoRemoveWorldObject) return false; } - [DebuggerHidden] public override IEnumerable GetGizmos() { - DestroyedFactionBase.c__Iterator105 c__Iterator = new DestroyedFactionBase.c__Iterator105(); - c__Iterator.<>f__this = this; - DestroyedFactionBase.c__Iterator105 expr_0E = c__Iterator; - expr_0E.$PC = -2; - return expr_0E; + foreach (Gizmo gizmo in base.GetGizmos()) + { + yield return gizmo; + } + if (base.HasMap && Find.WorldSelector.SingleSelectedObject == this) + { + yield return (Gizmo)SettleInExistingMapUtility.SettleCommand(base.Map, false); + } } } } diff --git a/Assembly-CSharp/RimWorld.Planet/Dialog_SplitCaravan.cs b/Assembly-CSharp/RimWorld.Planet/Dialog_SplitCaravan.cs index f8fa7f046..760101ea9 100644 --- a/Assembly-CSharp/RimWorld.Planet/Dialog_SplitCaravan.cs +++ b/Assembly-CSharp/RimWorld.Planet/Dialog_SplitCaravan.cs @@ -10,8 +10,8 @@ public class Dialog_SplitCaravan : Window { private enum Tab { - Pawns, - Items + Pawns = 0, + Items = 1 } private const float TitleRectHeight = 40f; @@ -26,7 +26,7 @@ private enum Tab private TransferableOneWayWidget itemsTransfer; - private Dialog_SplitCaravan.Tab tab; + private Tab tab; private float lastSourceMassFlashTime = -9999f; @@ -167,9 +167,9 @@ private Pair DestDaysWorthOfFood public Dialog_SplitCaravan(Caravan caravan) { this.caravan = caravan; - this.closeOnEscapeKey = true; - this.forcePause = true; - this.absorbInputAroundWindow = true; + base.closeOnEscapeKey = true; + base.forcePause = true; + base.absorbInputAroundWindow = true; } public override void PostOpen() @@ -187,39 +187,40 @@ public override void DoWindowContents(Rect inRect) Text.Font = GameFont.Small; Text.Anchor = TextAnchor.UpperLeft; Dialog_SplitCaravan.tabsList.Clear(); - Dialog_SplitCaravan.tabsList.Add(new TabRecord("PawnsTab".Translate(), delegate + Dialog_SplitCaravan.tabsList.Add(new TabRecord("PawnsTab".Translate(), (Action)delegate { - this.tab = Dialog_SplitCaravan.Tab.Pawns; - }, this.tab == Dialog_SplitCaravan.Tab.Pawns)); - Dialog_SplitCaravan.tabsList.Add(new TabRecord("ItemsTab".Translate(), delegate + this.tab = Tab.Pawns; + }, this.tab == Tab.Pawns)); + Dialog_SplitCaravan.tabsList.Add(new TabRecord("ItemsTab".Translate(), (Action)delegate { - this.tab = Dialog_SplitCaravan.Tab.Items; - }, this.tab == Dialog_SplitCaravan.Tab.Items)); + this.tab = Tab.Items; + }, this.tab == Tab.Items)); inRect.yMin += 72f; Widgets.DrawMenuSection(inRect, true); TabDrawer.DrawTabs(inRect, Dialog_SplitCaravan.tabsList); inRect = inRect.ContractedBy(17f); GUI.BeginGroup(inRect); - Rect rect2 = inRect.AtZero(); - Rect rect3 = rect2; - rect3.y += 32f; - rect3.xMin += rect2.width - 515f; - this.DrawMassAndFoodInfo(rect3); - this.DoBottomButtons(rect2); - Rect inRect2 = rect2; + Rect rect2; + Rect rect3 = rect2 = inRect.AtZero(); + rect2.y += 32f; + rect2.xMin += (float)(rect3.width - 515.0); + this.DrawMassAndFoodInfo(rect2); + this.DoBottomButtons(rect3); + Rect inRect2 = rect3; inRect2.yMax -= 59f; bool flag = false; - Dialog_SplitCaravan.Tab tab = this.tab; - if (tab != Dialog_SplitCaravan.Tab.Pawns) + switch (this.tab) { - if (tab == Dialog_SplitCaravan.Tab.Items) - { - this.itemsTransfer.OnGUI(inRect2, out flag); - } - } - else + case Tab.Pawns: { this.pawnsTransfer.OnGUI(inRect2, out flag); + break; + } + case Tab.Items: + { + this.itemsTransfer.OnGUI(inRect2, out flag); + break; + } } if (flag) { @@ -235,7 +236,7 @@ public override bool CausesMessageBackground() private void AddToTransferables(Thing t) { - TransferableOneWay transferableOneWay = TransferableUtility.TransferableMatching(t, this.transferables); + TransferableOneWay transferableOneWay = TransferableUtility.TransferableMatching(t, this.transferables); if (transferableOneWay == null) { transferableOneWay = new TransferableOneWay(); @@ -247,26 +248,45 @@ private void AddToTransferables(Thing t) private void DrawMassAndFoodInfo(Rect rect) { TransferableUIUtility.DrawMassInfo(rect, this.SourceMassUsage, this.SourceMassCapacity, "SplitCaravanMassUsageTooltip".Translate(), this.lastSourceMassFlashTime, false); - CaravanUIUtility.DrawDaysWorthOfFoodInfo(new Rect(rect.x, rect.y + 19f, rect.width, rect.height), this.SourceDaysWorthOfFood.First, this.SourceDaysWorthOfFood.Second, this.EnvironmentAllowsEatingVirtualPlantsNow, false, 3.40282347E+38f); + CaravanUIUtility.DrawDaysWorthOfFoodInfo(new Rect(rect.x, (float)(rect.y + 19.0), rect.width, rect.height), this.SourceDaysWorthOfFood.First, this.SourceDaysWorthOfFood.Second, this.EnvironmentAllowsEatingVirtualPlantsNow, false, 3.40282347E+38f); TransferableUIUtility.DrawMassInfo(rect, this.DestMassUsage, this.DestMassCapacity, "SplitCaravanMassUsageTooltip".Translate(), this.lastDestMassFlashTime, true); - CaravanUIUtility.DrawDaysWorthOfFoodInfo(new Rect(rect.x, rect.y + 19f, rect.width, rect.height), this.DestDaysWorthOfFood.First, this.DestDaysWorthOfFood.Second, this.EnvironmentAllowsEatingVirtualPlantsNow, true, 3.40282347E+38f); + CaravanUIUtility.DrawDaysWorthOfFoodInfo(new Rect(rect.x, (float)(rect.y + 19.0), rect.width, rect.height), this.DestDaysWorthOfFood.First, this.DestDaysWorthOfFood.Second, this.EnvironmentAllowsEatingVirtualPlantsNow, true, 3.40282347E+38f); } private void DoBottomButtons(Rect rect) { - Rect rect2 = new Rect(rect.width / 2f - this.BottomButtonSize.x / 2f, rect.height - 55f, this.BottomButtonSize.x, this.BottomButtonSize.y); + double num = rect.width / 2.0; + Vector2 bottomButtonSize = this.BottomButtonSize; + double x = num - bottomButtonSize.x / 2.0; + double y = rect.height - 55.0; + Vector2 bottomButtonSize2 = this.BottomButtonSize; + float x2 = bottomButtonSize2.x; + Vector2 bottomButtonSize3 = this.BottomButtonSize; + Rect rect2 = new Rect((float)x, (float)y, x2, bottomButtonSize3.y); if (Widgets.ButtonText(rect2, "AcceptButton".Translate(), true, false, true) && this.TrySplitCaravan()) { SoundDefOf.TickHigh.PlayOneShotOnCamera(null); this.Close(false); } - Rect rect3 = new Rect(rect2.x - 10f - this.BottomButtonSize.x, rect2.y, this.BottomButtonSize.x, this.BottomButtonSize.y); + double num2 = rect2.x - 10.0; + Vector2 bottomButtonSize4 = this.BottomButtonSize; + double x3 = num2 - bottomButtonSize4.x; + float y2 = rect2.y; + Vector2 bottomButtonSize5 = this.BottomButtonSize; + float x4 = bottomButtonSize5.x; + Vector2 bottomButtonSize6 = this.BottomButtonSize; + Rect rect3 = new Rect((float)x3, y2, x4, bottomButtonSize6.y); if (Widgets.ButtonText(rect3, "ResetButton".Translate(), true, false, true)) { SoundDefOf.TickLow.PlayOneShotOnCamera(null); this.CalculateAndRecacheTransferables(); } - Rect rect4 = new Rect(rect2.xMax + 10f, rect2.y, this.BottomButtonSize.x, this.BottomButtonSize.y); + double x5 = rect2.xMax + 10.0; + float y3 = rect2.y; + Vector2 bottomButtonSize7 = this.BottomButtonSize; + float x6 = bottomButtonSize7.x; + Vector2 bottomButtonSize8 = this.BottomButtonSize; + Rect rect4 = new Rect((float)x5, y3, x6, bottomButtonSize8.y); if (Widgets.ButtonText(rect4, "CancelButton".Translate(), true, false, true)) { this.Close(true); @@ -278,7 +298,7 @@ private void CalculateAndRecacheTransferables() this.transferables = new List(); this.AddPawnsToTransferables(); this.AddItemsToTransferables(); - CaravanUIUtility.CreateCaravanTransferableWidgets(this.transferables, out this.pawnsTransfer, out this.itemsTransfer, "CaravanSplitSourceLabel".Translate(), "CaravanSplitDestLabel".Translate(), "SplitCaravanThingCountTip".Translate(), IgnorePawnsInventoryMode.Ignore, () => this.DestMassCapacity - this.DestMassUsage, false, this.caravan.Tile); + CaravanUIUtility.CreateCaravanTransferableWidgets(this.transferables, out this.pawnsTransfer, out this.itemsTransfer, "CaravanSplitSourceLabel".Translate(), "CaravanSplitDestLabel".Translate(), "SplitCaravanThingCountTip".Translate(), IgnorePawnsInventoryMode.Ignore, (Func)(() => this.DestMassCapacity - this.DestMassUsage), false, this.caravan.Tile); this.CountToTransferChanged(); } @@ -303,18 +323,20 @@ private bool TrySplitCaravan() this.caravan.RemovePawn(pawns[j]); caravan.AddPawn(pawns[j], true); } - this.transferables.RemoveAll((TransferableOneWay x) => x.AnyThing is Pawn); + this.transferables.RemoveAll((Predicate)((TransferableOneWay x) => x.AnyThing is Pawn)); for (int k = 0; k < this.transferables.Count; k++) { - TransferableUtility.TransferNoSplit(this.transferables[k].things, this.transferables[k].CountToTransfer, delegate(Thing thing, int numToTake) + TransferableUtility.TransferNoSplit(this.transferables[k].things, this.transferables[k].CountToTransfer, (Action)delegate(Thing thing, int numToTake) { Pawn ownerOf = CaravanInventoryUtility.GetOwnerOf(this.caravan, thing); if (ownerOf == null) { Log.Error("Error while splitting a caravan: Thing " + thing + " has no owner. Where did it come from then?"); - return; } - CaravanInventoryUtility.MoveInventoryToSomeoneElse(ownerOf, thing, pawns, null, numToTake); + else + { + CaravanInventoryUtility.MoveInventoryToSomeoneElse(ownerOf, thing, pawns, null, numToTake); + } }, true, true); } return true; @@ -322,14 +344,14 @@ private bool TrySplitCaravan() private bool CheckForErrors(List pawns) { - if (!pawns.Any((Pawn x) => CaravanUtility.IsOwner(x, Faction.OfPlayer) && !x.Downed)) + if (!pawns.Any((Predicate)((Pawn x) => CaravanUtility.IsOwner(x, Faction.OfPlayer) && !x.Downed))) { - Messages.Message("CaravanMustHaveAtLeastOneColonist".Translate(), this.caravan, MessageSound.RejectInput); + Messages.Message("CaravanMustHaveAtLeastOneColonist".Translate(), (WorldObject)this.caravan, MessageSound.RejectInput); return false; } if (!this.AnyNonDownedColonistLeftInSourceCaravan(pawns)) { - Messages.Message("SourceCaravanMustHaveAtLeastOneColonist".Translate(), this.caravan, MessageSound.RejectInput); + Messages.Message("SourceCaravanMustHaveAtLeastOneColonist".Translate(), (WorldObject)this.caravan, MessageSound.RejectInput); return false; } return true; @@ -365,11 +387,11 @@ private void FlashDestMass() private bool AnyNonDownedColonistLeftInSourceCaravan(List pawnsToTransfer) { - return this.transferables.Any((TransferableOneWay x) => x.things.Any(delegate(Thing y) + return this.transferables.Any((Predicate)((TransferableOneWay x) => x.things.Any((Predicate)delegate(Thing y) { Pawn pawn = y as Pawn; return pawn != null && CaravanUtility.IsOwner(pawn, Faction.OfPlayer) && !pawn.Downed && !pawnsToTransfer.Contains(pawn); - })); + }))); } private void CountToTransferChanged() diff --git a/Assembly-CSharp/RimWorld.Planet/ExpandableWorldObjectsUtility.cs b/Assembly-CSharp/RimWorld.Planet/ExpandableWorldObjectsUtility.cs index e83c5a5fc..9c00ac8ff 100644 --- a/Assembly-CSharp/RimWorld.Planet/ExpandableWorldObjectsUtility.cs +++ b/Assembly-CSharp/RimWorld.Planet/ExpandableWorldObjectsUtility.cs @@ -27,7 +27,7 @@ public static float TransitionPct public static void ExpandableWorldObjectsUpdate() { - float num = Time.deltaTime * 3f; + float num = (float)(Time.deltaTime * 3.0); if (Find.WorldCameraDriver.CurrentZoom == WorldCameraZoomRange.Close) { ExpandableWorldObjectsUtility.transitionPct -= num; @@ -41,31 +41,27 @@ public static void ExpandableWorldObjectsUpdate() public static void ExpandableWorldObjectsOnGUI() { - if (ExpandableWorldObjectsUtility.TransitionPct == 0f) + if (ExpandableWorldObjectsUtility.TransitionPct != 0.0) { - return; - } - ExpandableWorldObjectsUtility.tmpWorldObjects.Clear(); - ExpandableWorldObjectsUtility.tmpWorldObjects.AddRange(Find.WorldObjects.AllWorldObjects); - ExpandableWorldObjectsUtility.SortByExpandingIconPriority(ExpandableWorldObjectsUtility.tmpWorldObjects); - WorldTargeter worldTargeter = Find.WorldTargeter; - List worldObjectsUnderMouse = null; - if (worldTargeter.IsTargeting) - { - worldObjectsUnderMouse = GenWorldUI.WorldObjectsUnderMouse(UI.MousePositionOnUI); - } - for (int i = 0; i < ExpandableWorldObjectsUtility.tmpWorldObjects.Count; i++) - { - WorldObject worldObject = ExpandableWorldObjectsUtility.tmpWorldObjects[i]; - if (worldObject.def.expandingIcon) + ExpandableWorldObjectsUtility.tmpWorldObjects.Clear(); + ExpandableWorldObjectsUtility.tmpWorldObjects.AddRange(Find.WorldObjects.AllWorldObjects); + ExpandableWorldObjectsUtility.SortByExpandingIconPriority(ExpandableWorldObjectsUtility.tmpWorldObjects); + WorldTargeter worldTargeter = Find.WorldTargeter; + List worldObjectsUnderMouse = null; + if (worldTargeter.IsTargeting) + { + worldObjectsUnderMouse = GenWorldUI.WorldObjectsUnderMouse(UI.MousePositionOnUI); + } + for (int i = 0; i < ExpandableWorldObjectsUtility.tmpWorldObjects.Count; i++) { - if (!worldObject.HiddenBehindTerrainNow()) + WorldObject worldObject = ExpandableWorldObjectsUtility.tmpWorldObjects[i]; + if (worldObject.def.expandingIcon && !worldObject.HiddenBehindTerrainNow()) { Color expandingIconColor = worldObject.ExpandingIconColor; expandingIconColor.a = ExpandableWorldObjectsUtility.TransitionPct; if (worldTargeter.IsTargetedNow(worldObject, worldObjectsUnderMouse)) { - float num = GenMath.LerpDouble(-1f, 1f, 0.7f, 1f, Mathf.Sin(Time.time * 8f)); + float num = GenMath.LerpDouble(-1f, 1f, 0.7f, 1f, Mathf.Sin((float)(Time.time * 8.0))); expandingIconColor.r *= num; expandingIconColor.g *= num; expandingIconColor.b *= num; @@ -74,20 +70,20 @@ public static void ExpandableWorldObjectsOnGUI() GUI.DrawTexture(ExpandableWorldObjectsUtility.ExpandedIconScreenRect(worldObject), worldObject.ExpandingIcon); } } + ExpandableWorldObjectsUtility.tmpWorldObjects.Clear(); + GUI.color = Color.white; } - ExpandableWorldObjectsUtility.tmpWorldObjects.Clear(); - GUI.color = Color.white; } public static Rect ExpandedIconScreenRect(WorldObject o) { Vector2 vector = o.ScreenPos(); - return new Rect(vector.x - 15f, vector.y - 15f, 30f, 30f); + return new Rect((float)(vector.x - 15.0), (float)(vector.y - 15.0), 30f, 30f); } public static bool IsExpanded(WorldObject o) { - return ExpandableWorldObjectsUtility.TransitionPct > 0.5f && o.def.expandingIcon; + return ExpandableWorldObjectsUtility.TransitionPct > 0.5 && o.def.expandingIcon; } public static void GetExpandedWorldObjectUnderMouse(Vector2 mousePos, List outList) @@ -99,15 +95,9 @@ public static void GetExpandedWorldObjectUnderMouse(Vector2 mousePos, List worldObjects) { - worldObjects.SortBy(delegate(WorldObject x) + worldObjects.SortBy((Func)delegate(WorldObject x) { float num = x.ExpandingIconPriority; if (x.Faction != null && x.Faction.IsPlayer) { - num += 0.001f; + num = (float)(num + 0.0010000000474974513); } return num; - }, (WorldObject x) => x.ID); + }, (Func)((WorldObject x) => x.ID)); } } } diff --git a/Assembly-CSharp/RimWorld.Planet/FactionBase.cs b/Assembly-CSharp/RimWorld.Planet/FactionBase.cs index c93a94f6c..41c04e159 100644 --- a/Assembly-CSharp/RimWorld.Planet/FactionBase.cs +++ b/Assembly-CSharp/RimWorld.Planet/FactionBase.cs @@ -1,4 +1,3 @@ -using System; using UnityEngine; using Verse; @@ -44,7 +43,7 @@ public override Material Material { get { - if (this.cachedMat == null) + if ((Object)this.cachedMat == (Object)null) { this.cachedMat = MaterialPool.MatFrom(base.Faction.def.homeIconPath, ShaderDatabase.WorldOverlayTransparentLit, base.Faction.Color, WorldMaterials.WorldObjectRenderQueue); } @@ -66,13 +65,13 @@ public override MapGeneratorDef MapGeneratorDef public FactionBase() { - this.trader = new FactionBase_TraderTracker(this); + base.trader = new FactionBase_TraderTracker(this); } public override void ExposeData() { base.ExposeData(); - Scribe_Values.Look(ref this.nameInt, "nameInt", null, false); + Scribe_Values.Look(ref this.nameInt, "nameInt", (string)null, false); Scribe_Values.Look(ref this.namedByPlayer, "namedByPlayer", false, false); if (Scribe.mode == LoadSaveMode.PostLoadInit) { diff --git a/Assembly-CSharp/RimWorld.Planet/FactionBaseDefeatUtility.cs b/Assembly-CSharp/RimWorld.Planet/FactionBaseDefeatUtility.cs index 1b69f51d6..8dbb18be1 100644 --- a/Assembly-CSharp/RimWorld.Planet/FactionBaseDefeatUtility.cs +++ b/Assembly-CSharp/RimWorld.Planet/FactionBaseDefeatUtility.cs @@ -1,4 +1,3 @@ -using System; using System.Collections.Generic; using System.Text; using Verse; @@ -9,38 +8,29 @@ public static class FactionBaseDefeatUtility { public static void CheckDefeated(FactionBase factionBase) { - if (factionBase.Faction == Faction.OfPlayer) + if (factionBase.Faction != Faction.OfPlayer) { - return; - } - Map map = factionBase.Map; - if (map == null || !FactionBaseDefeatUtility.IsDefeated(map, factionBase.Faction)) - { - return; - } - StringBuilder stringBuilder = new StringBuilder(); - stringBuilder.Append("LetterFactionBaseDefeated".Translate(new object[] - { - factionBase.Label, - MapParent.GetForceExitAndRemoveMapCountdownTimeLeftString(60000) - })); - if (!FactionBaseDefeatUtility.HasAnyOtherBase(factionBase)) - { - factionBase.Faction.defeated = true; - stringBuilder.AppendLine(); - stringBuilder.AppendLine(); - stringBuilder.Append("LetterFactionBaseDefeated_FactionDestroyed".Translate(new object[] + Map map = factionBase.Map; + if (map != null && FactionBaseDefeatUtility.IsDefeated(map, factionBase.Faction)) { - factionBase.Faction.Name - })); + StringBuilder stringBuilder = new StringBuilder(); + stringBuilder.Append("LetterFactionBaseDefeated".Translate(factionBase.Label, MapParent.GetForceExitAndRemoveMapCountdownTimeLeftString(60000))); + if (!FactionBaseDefeatUtility.HasAnyOtherBase(factionBase)) + { + factionBase.Faction.defeated = true; + stringBuilder.AppendLine(); + stringBuilder.AppendLine(); + stringBuilder.Append("LetterFactionBaseDefeated_FactionDestroyed".Translate(factionBase.Faction.Name)); + } + Find.LetterStack.ReceiveLetter("LetterLabelFactionBaseDefeated".Translate(), stringBuilder.ToString(), LetterDefOf.Good, new GlobalTargetInfo(factionBase.Tile), (string)null); + DestroyedFactionBase destroyedFactionBase = (DestroyedFactionBase)WorldObjectMaker.MakeWorldObject(WorldObjectDefOf.DestroyedFactionBase); + destroyedFactionBase.Tile = factionBase.Tile; + Find.WorldObjects.Add(destroyedFactionBase); + map.info.parent = destroyedFactionBase; + Find.WorldObjects.Remove(factionBase); + destroyedFactionBase.StartForceExitAndRemoveMapCountdown(); + } } - Find.LetterStack.ReceiveLetter("LetterLabelFactionBaseDefeated".Translate(), stringBuilder.ToString(), LetterDefOf.Good, new GlobalTargetInfo(factionBase.Tile), null); - DestroyedFactionBase destroyedFactionBase = (DestroyedFactionBase)WorldObjectMaker.MakeWorldObject(WorldObjectDefOf.DestroyedFactionBase); - destroyedFactionBase.Tile = factionBase.Tile; - Find.WorldObjects.Add(destroyedFactionBase); - map.info.parent = destroyedFactionBase; - Find.WorldObjects.Remove(factionBase); - destroyedFactionBase.StartForceExitAndRemoveMapCountdown(); } private static bool IsDefeated(Map map, Faction faction) diff --git a/Assembly-CSharp/RimWorld.Planet/FactionBaseNameGenerator.cs b/Assembly-CSharp/RimWorld.Planet/FactionBaseNameGenerator.cs index 4ee11874f..f5566d6a3 100644 --- a/Assembly-CSharp/RimWorld.Planet/FactionBaseNameGenerator.cs +++ b/Assembly-CSharp/RimWorld.Planet/FactionBaseNameGenerator.cs @@ -1,4 +1,3 @@ -using System; using System.Collections.Generic; using Verse; @@ -10,21 +9,21 @@ public static class FactionBaseNameGenerator public static string GenerateFactionBaseName(FactionBase factionBase) { - if (factionBase.Faction == null || factionBase.Faction.def.baseNameMaker == null) + if (factionBase.Faction != null && factionBase.Faction.def.baseNameMaker != null) { - return factionBase.def.label; - } - FactionBaseNameGenerator.usedNames.Clear(); - List factionBases = Find.WorldObjects.FactionBases; - for (int i = 0; i < factionBases.Count; i++) - { - FactionBase factionBase2 = factionBases[i]; - if (factionBase2.Name != null) + FactionBaseNameGenerator.usedNames.Clear(); + List factionBases = Find.WorldObjects.FactionBases; + for (int i = 0; i < factionBases.Count; i++) { - FactionBaseNameGenerator.usedNames.Add(factionBase2.Name); + FactionBase factionBase2 = factionBases[i]; + if (factionBase2.Name != null) + { + FactionBaseNameGenerator.usedNames.Add(factionBase2.Name); + } } + return NameGenerator.GenerateName(factionBase.Faction.def.baseNameMaker, FactionBaseNameGenerator.usedNames, true); } - return NameGenerator.GenerateName(factionBase.Faction.def.baseNameMaker, FactionBaseNameGenerator.usedNames, true); + return factionBase.def.label; } } } diff --git a/Assembly-CSharp/RimWorld.Planet/FactionBase_TraderTracker.cs b/Assembly-CSharp/RimWorld.Planet/FactionBase_TraderTracker.cs index 5857ba8b0..c17d9976c 100644 --- a/Assembly-CSharp/RimWorld.Planet/FactionBase_TraderTracker.cs +++ b/Assembly-CSharp/RimWorld.Planet/FactionBase_TraderTracker.cs @@ -1,4 +1,3 @@ -using System; using System.Collections.Generic; using UnityEngine; using Verse; @@ -11,7 +10,7 @@ public FactionBase FactionBase { get { - return (FactionBase)this.settlement; + return (FactionBase)base.settlement; } } @@ -21,7 +20,7 @@ public override TraderKindDef TraderKind { FactionBase factionBase = this.FactionBase; List baseTraderKinds = factionBase.Faction.def.baseTraderKinds; - if (baseTraderKinds.NullOrEmpty()) + if (baseTraderKinds.NullOrEmpty()) { return null; } diff --git a/Assembly-CSharp/RimWorld.Planet/FloatMenuMakerWorld.cs b/Assembly-CSharp/RimWorld.Planet/FloatMenuMakerWorld.cs index 8b78d9f18..9600115af 100644 --- a/Assembly-CSharp/RimWorld.Planet/FloatMenuMakerWorld.cs +++ b/Assembly-CSharp/RimWorld.Planet/FloatMenuMakerWorld.cs @@ -1,4 +1,3 @@ -using System; using System.Collections.Generic; using UnityEngine; using Verse; diff --git a/Assembly-CSharp/RimWorld.Planet/GenWorldClosest.cs b/Assembly-CSharp/RimWorld.Planet/GenWorldClosest.cs index e9c0dbe43..d47a53aa0 100644 --- a/Assembly-CSharp/RimWorld.Planet/GenWorldClosest.cs +++ b/Assembly-CSharp/RimWorld.Planet/GenWorldClosest.cs @@ -8,7 +8,7 @@ public static class GenWorldClosest public static bool TryFindClosestTile(int rootTile, Predicate predicate, out int foundTile, int maxTilesToScan = 2147483647, bool canSearchThroughImpassable = true) { int foundTileLocal = -1; - Find.WorldFloodFiller.FloodFill(rootTile, (int x) => canSearchThroughImpassable || !Find.World.Impassable(x), delegate(int t) + Find.WorldFloodFiller.FloodFill(rootTile, (Predicate)((int x) => canSearchThroughImpassable || !Find.World.Impassable(x)), (Predicate)delegate(int t) { bool flag = predicate(t); if (flag) @@ -23,7 +23,7 @@ public static bool TryFindClosestTile(int rootTile, Predicate predicate, ou public static bool TryFindClosestPassableTile(int rootTile, out int foundTile) { - return GenWorldClosest.TryFindClosestTile(rootTile, (int x) => !Find.World.Impassable(x), out foundTile, 2147483647, true); + return GenWorldClosest.TryFindClosestTile(rootTile, (Predicate)((int x) => !Find.World.Impassable(x)), out foundTile, 2147483647, true); } } } diff --git a/Assembly-CSharp/RimWorld.Planet/GenWorldUI.cs b/Assembly-CSharp/RimWorld.Planet/GenWorldUI.cs index eb1f721b2..af4e0e33b 100644 --- a/Assembly-CSharp/RimWorld.Planet/GenWorldUI.cs +++ b/Assembly-CSharp/RimWorld.Planet/GenWorldUI.cs @@ -15,7 +15,7 @@ public static float CaravanDirectClickRadius { get { - return 0.35f * Find.WorldGrid.averageTileSize; + return (float)(0.34999999403953552 * Find.WorldGrid.averageTileSize); } } @@ -23,7 +23,7 @@ private static float CaravanWideClickRadius { get { - return 0.75f * Find.WorldGrid.averageTileSize; + return (float)(0.75 * Find.WorldGrid.averageTileSize); } } @@ -31,7 +31,7 @@ private static float DynamicallyDrawnObjectDirectClickRadius { get { - return 0.35f * Find.WorldGrid.averageTileSize; + return (float)(0.34999999403953552 * Find.WorldGrid.averageTileSize); } } @@ -50,7 +50,7 @@ public static List WorldObjectsUnderMouse(Vector2 mousePos) GenWorldUI.clickedCaravans.Add(caravan); } } - GenWorldUI.clickedCaravans.SortBy((Caravan x) => x.DistanceToMouse(mousePos)); + GenWorldUI.clickedCaravans.SortBy((Func)((Caravan x) => x.DistanceToMouse(mousePos))); for (int j = 0; j < GenWorldUI.clickedCaravans.Count; j++) { if (!list.Contains(GenWorldUI.clickedCaravans[j])) @@ -69,7 +69,7 @@ public static List WorldObjectsUnderMouse(Vector2 mousePos) GenWorldUI.clickedDynamicallyDrawnObjects.Add(worldObject); } } - GenWorldUI.clickedDynamicallyDrawnObjects.SortBy((WorldObject x) => x.DistanceToMouse(mousePos)); + GenWorldUI.clickedDynamicallyDrawnObjects.SortBy((Func)((WorldObject x) => x.DistanceToMouse(mousePos))); for (int l = 0; l < GenWorldUI.clickedDynamicallyDrawnObjects.Count; l++) { if (!list.Contains(GenWorldUI.clickedDynamicallyDrawnObjects[l])) @@ -97,7 +97,7 @@ public static List WorldObjectsUnderMouse(Vector2 mousePos) GenWorldUI.clickedCaravans.Add(caravan2); } } - GenWorldUI.clickedCaravans.SortBy((Caravan x) => x.DistanceToMouse(mousePos)); + GenWorldUI.clickedCaravans.SortBy((Func)((Caravan x) => x.DistanceToMouse(mousePos))); for (int num2 = 0; num2 < GenWorldUI.clickedCaravans.Count; num2++) { if (!list.Contains(GenWorldUI.clickedCaravans[num2])) diff --git a/Assembly-CSharp/RimWorld.Planet/GlobalTargetInfo.cs b/Assembly-CSharp/RimWorld.Planet/GlobalTargetInfo.cs index 5e37b8880..70ed2bd35 100644 --- a/Assembly-CSharp/RimWorld.Planet/GlobalTargetInfo.cs +++ b/Assembly-CSharp/RimWorld.Planet/GlobalTargetInfo.cs @@ -179,7 +179,11 @@ public GlobalTargetInfo(int tile) public override bool Equals(object obj) { - return obj is GlobalTargetInfo && this.Equals((GlobalTargetInfo)obj); + if (!(obj is GlobalTargetInfo)) + { + return false; + } + return this.Equals((GlobalTargetInfo)obj); } public bool Equals(GlobalTargetInfo other) @@ -195,7 +199,7 @@ public override int GetHashCode() } if (this.cellInt.IsValid) { - return Gen.HashCombine(this.cellInt.GetHashCode(), this.mapInt); + return Gen.HashCombine(this.cellInt.GetHashCode(), this.mapInt); } if (this.worldObjectInt != null) { @@ -347,19 +351,23 @@ public static explicit operator WorldObject(GlobalTargetInfo targ) public static bool operator ==(GlobalTargetInfo a, GlobalTargetInfo b) { - if (a.Thing != null || b.Thing != null) - { - return a.Thing == b.Thing; - } - if (a.cellInt.IsValid || b.cellInt.IsValid) + if (a.Thing == null && b.Thing == null) { + if (!a.cellInt.IsValid && !b.cellInt.IsValid) + { + if (a.WorldObject == null && b.WorldObject == null) + { + if (a.tileInt < 0 && b.tileInt < 0) + { + return true; + } + return a.tileInt == b.tileInt; + } + return a.WorldObject == b.WorldObject; + } return a.cellInt == b.cellInt && a.mapInt == b.mapInt; } - if (a.WorldObject != null || b.WorldObject != null) - { - return a.WorldObject == b.WorldObject; - } - return (a.tileInt < 0 && b.tileInt < 0) || a.tileInt == b.tileInt; + return a.Thing == b.Thing; } public static bool operator !=(GlobalTargetInfo a, GlobalTargetInfo b) diff --git a/Assembly-CSharp/RimWorld.Planet/Hilliness.cs b/Assembly-CSharp/RimWorld.Planet/Hilliness.cs index 530484810..255a3d479 100644 --- a/Assembly-CSharp/RimWorld.Planet/Hilliness.cs +++ b/Assembly-CSharp/RimWorld.Planet/Hilliness.cs @@ -1,14 +1,12 @@ -using System; - namespace RimWorld.Planet { public enum Hilliness : byte { - Undefined, - Flat, - SmallHills, - LargeHills, - Mountainous, - Impassable + Undefined = 0, + Flat = 1, + SmallHills = 2, + LargeHills = 3, + Mountainous = 4, + Impassable = 5 } } diff --git a/Assembly-CSharp/RimWorld.Planet/HillinessUtility.cs b/Assembly-CSharp/RimWorld.Planet/HillinessUtility.cs index 127c2c010..e1dd2b7e9 100644 --- a/Assembly-CSharp/RimWorld.Planet/HillinessUtility.cs +++ b/Assembly-CSharp/RimWorld.Planet/HillinessUtility.cs @@ -10,18 +10,30 @@ public static string GetLabel(this Hilliness h) switch (h) { case Hilliness.Flat: + { return "Hilliness_Flat".Translate(); + } case Hilliness.SmallHills: + { return "Hilliness_SmallHills".Translate(); + } case Hilliness.LargeHills: + { return "Hilliness_LargeHills".Translate(); + } case Hilliness.Mountainous: + { return "Hilliness_Mountainous".Translate(); + } case Hilliness.Impassable: + { return "Hilliness_Impassable".Translate(); + } default: - Log.ErrorOnce("Hilliness label unknown: " + h.ToString(), 694362); - return h.ToString(); + { + Log.ErrorOnce("Hilliness label unknown: " + ((Enum)(object)h).ToString(), 694362); + return ((Enum)(object)h).ToString(); + } } } diff --git a/Assembly-CSharp/RimWorld.Planet/IcosahedronGenerator.cs b/Assembly-CSharp/RimWorld.Planet/IcosahedronGenerator.cs index ace9615ff..9e80c4596 100644 --- a/Assembly-CSharp/RimWorld.Planet/IcosahedronGenerator.cs +++ b/Assembly-CSharp/RimWorld.Planet/IcosahedronGenerator.cs @@ -1,4 +1,3 @@ -using System; using System.Collections.Generic; using UnityEngine; @@ -6,7 +5,7 @@ namespace RimWorld.Planet { public static class IcosahedronGenerator { - private static readonly TriangleIndices[] IcosahedronTris = new TriangleIndices[] + private static readonly TriangleIndices[] IcosahedronTris = new TriangleIndices[20] { new TriangleIndices(0, 11, 5), new TriangleIndices(0, 5, 1), @@ -32,50 +31,38 @@ public static class IcosahedronGenerator public static void GenerateIcosahedron(List outVerts, List outTris, float radius, Vector3 viewCenter, float viewAngle) { - float num = (1f + Mathf.Sqrt(5f)) / 2f; + float num = (float)((1.0 + Mathf.Sqrt(5f)) / 2.0); outVerts.Clear(); - Vector3 vector = new Vector3(-1f, num, 0f); - outVerts.Add(vector.normalized * radius); - Vector3 vector2 = new Vector3(1f, num, 0f); - outVerts.Add(vector2.normalized * radius); - Vector3 vector3 = new Vector3(-1f, -num, 0f); - outVerts.Add(vector3.normalized * radius); - Vector3 vector4 = new Vector3(1f, -num, 0f); - outVerts.Add(vector4.normalized * radius); - Vector3 vector5 = new Vector3(0f, -1f, num); - outVerts.Add(vector5.normalized * radius); - Vector3 vector6 = new Vector3(0f, 1f, num); - outVerts.Add(vector6.normalized * radius); - Vector3 vector7 = new Vector3(0f, -1f, -num); - outVerts.Add(vector7.normalized * radius); - Vector3 vector8 = new Vector3(0f, 1f, -num); - outVerts.Add(vector8.normalized * radius); - Vector3 vector9 = new Vector3(num, 0f, -1f); - outVerts.Add(vector9.normalized * radius); - Vector3 vector10 = new Vector3(num, 0f, 1f); - outVerts.Add(vector10.normalized * radius); - Vector3 vector11 = new Vector3(-num, 0f, -1f); - outVerts.Add(vector11.normalized * radius); - Vector3 vector12 = new Vector3(-num, 0f, 1f); - outVerts.Add(vector12.normalized * radius); + outVerts.Add(new Vector3(-1f, num, 0f).normalized * radius); + outVerts.Add(new Vector3(1f, num, 0f).normalized * radius); + outVerts.Add(new Vector3(-1f, (float)(0.0 - num), 0f).normalized * radius); + outVerts.Add(new Vector3(1f, (float)(0.0 - num), 0f).normalized * radius); + outVerts.Add(new Vector3(0f, -1f, num).normalized * radius); + outVerts.Add(new Vector3(0f, 1f, num).normalized * radius); + outVerts.Add(new Vector3(0f, -1f, (float)(0.0 - num)).normalized * radius); + outVerts.Add(new Vector3(0f, 1f, (float)(0.0 - num)).normalized * radius); + outVerts.Add(new Vector3(num, 0f, -1f).normalized * radius); + outVerts.Add(new Vector3(num, 0f, 1f).normalized * radius); + outVerts.Add(new Vector3((float)(0.0 - num), 0f, -1f).normalized * radius); + outVerts.Add(new Vector3((float)(0.0 - num), 0f, 1f).normalized * radius); outTris.Clear(); - int i = 0; - int num2 = IcosahedronGenerator.IcosahedronTris.Length; - while (i < num2) + int num2 = 0; + int num3 = IcosahedronGenerator.IcosahedronTris.Length; + while (num2 < num3) { - TriangleIndices item = IcosahedronGenerator.IcosahedronTris[i]; + TriangleIndices item = IcosahedronGenerator.IcosahedronTris[num2]; if (IcosahedronGenerator.IcosahedronFaceNeeded(item.v1, item.v2, item.v3, outVerts, radius, viewCenter, viewAngle)) { outTris.Add(item); } - i++; + num2++; } MeshUtility.RemoveUnusedVertices(outVerts, outTris); } private static bool IcosahedronFaceNeeded(int v1, int v2, int v3, List verts, float radius, Vector3 viewCenter, float viewAngle) { - viewAngle += 18f; + viewAngle = (float)(viewAngle + 18.0); return MeshUtility.Visible(verts[v1], radius, viewCenter, viewAngle) || MeshUtility.Visible(verts[v2], radius, viewCenter, viewAngle) || MeshUtility.Visible(verts[v3], radius, viewCenter, viewAngle); } } diff --git a/Assembly-CSharp/RimWorld.Planet/ItemStashContentsComp.cs b/Assembly-CSharp/RimWorld.Planet/ItemStashContentsComp.cs index 8d12320fa..a9c261f4b 100644 --- a/Assembly-CSharp/RimWorld.Planet/ItemStashContentsComp.cs +++ b/Assembly-CSharp/RimWorld.Planet/ItemStashContentsComp.cs @@ -21,7 +21,7 @@ public ItemStashContentsComp() public override void PostExposeData() { base.PostExposeData(); - Scribe_Deep.Look(ref this.contents, "contents", new object[] + Scribe_Deep.Look(ref this.contents, "contents", new object[1] { this }); @@ -45,38 +45,38 @@ public override void PostPostRemove() public override string CompInspectStringExtra() { - if (!this.contents.Any) + if (this.contents.Any) { - return null; - } - ItemStashContentsComp.tmpContents.Clear(); - ItemStashContentsComp.tmpContents.AddRange(this.contents); - ItemStashContentsComp.tmpContents.SortByDescending((Thing x) => x.GetInnerIfMinified().MarketValue * (float)x.stackCount); - ItemStashContentsComp.tmpContentsStr.Clear(); - for (int i = 0; i < Mathf.Min(5, ItemStashContentsComp.tmpContents.Count); i++) - { - ItemStashContentsComp.tmpContentsStr.Add(ItemStashContentsComp.tmpContents[i].LabelShort); - } - string text = GenText.ToCommaList(ItemStashContentsComp.tmpContentsStr, true); - int count = ItemStashContentsComp.tmpContents.Count; - ItemStashContentsComp.tmpContents.Clear(); - ItemStashContentsComp.tmpContentsStr.Clear(); - if (count > 5) - { - return "SomeItemStashContents".Translate(new object[] + ItemStashContentsComp.tmpContents.Clear(); + ItemStashContentsComp.tmpContents.AddRange(this.contents); + ItemStashContentsComp.tmpContents.SortByDescending((Func)((Thing x) => x.GetInnerIfMinified().MarketValue * (float)x.stackCount)); + ItemStashContentsComp.tmpContentsStr.Clear(); + for (int i = 0; i < Mathf.Min(5, ItemStashContentsComp.tmpContents.Count); i++) + { + ItemStashContentsComp.tmpContentsStr.Add(ItemStashContentsComp.tmpContents[i].LabelShort); + } + string text = GenText.ToCommaList(ItemStashContentsComp.tmpContentsStr, true); + int count = ItemStashContentsComp.tmpContents.Count; + ItemStashContentsComp.tmpContents.Clear(); + ItemStashContentsComp.tmpContentsStr.Clear(); + if (count > 5) { - text - }); + return "SomeItemStashContents".Translate(text); + } + return "ItemStashContents".Translate(text); } - return "ItemStashContents".Translate(new object[] - { - text - }); + return (string)null; } virtual IThingHolder get_ParentHolder() { return base.ParentHolder; } + + IThingHolder IThingHolder.get_ParentHolder() + { + //ILSpy generated this explicit interface implementation from .override directive in get_ParentHolder + return this.get_ParentHolder(); + } } } diff --git a/Assembly-CSharp/RimWorld.Planet/MapParent.cs b/Assembly-CSharp/RimWorld.Planet/MapParent.cs index 5ad74bdf0..9f8bb9940 100644 --- a/Assembly-CSharp/RimWorld.Planet/MapParent.cs +++ b/Assembly-CSharp/RimWorld.Planet/MapParent.cs @@ -1,10 +1,10 @@ using System; using System.Collections.Generic; -using System.Diagnostics; using System.Linq; using System.Text; using UnityEngine; using Verse; +using Verse.Sound; namespace RimWorld.Planet { @@ -59,10 +59,7 @@ public virtual IEnumerable ExtraGenStepDefs { get { - MapParent.<>c__Iterator102 <>c__Iterator = new MapParent.<>c__Iterator102(); - MapParent.<>c__Iterator102 expr_07 = <>c__Iterator; - expr_07.$PC = -2; - return expr_07; + yield break; } } @@ -114,7 +111,7 @@ public virtual void Notify_CaravanFormed(Caravan caravan) if (!this.anyCaravanEverFormed) { this.anyCaravanEverFormed = true; - if (this.def.isTempIncidentMapOwner && this.HasMap) + if (base.def.isTempIncidentMapOwner && this.HasMap) { this.Map.StoryState.CopyTo(caravan.StoryState); } @@ -153,26 +150,88 @@ public override void Tick() this.CheckRemoveMapNow(); } - [DebuggerHidden] public override IEnumerable GetGizmos() { - MapParent.c__Iterator103 c__Iterator = new MapParent.c__Iterator103(); - c__Iterator.<>f__this = this; - MapParent.c__Iterator103 expr_0E = c__Iterator; - expr_0E.$PC = -2; - return expr_0E; + foreach (Gizmo gizmo in base.GetGizmos()) + { + yield return gizmo; + } + if (this.HasMap) + { + yield return (Gizmo)new Command_Action + { + defaultLabel = "CommandShowMap".Translate(), + defaultDesc = "CommandShowMapDesc".Translate(), + icon = MapParent.ShowMapCommand, + hotKey = KeyBindingDefOf.Misc1, + action = (Action)delegate + { + Current.Game.VisibleMap = ((_003CGetGizmos_003Ec__Iterator103)/*Error near IL_011d: stateMachine*/)._003C_003Ef__this.Map; + if (!CameraJumper.TryHideWorld()) + { + SoundDefOf.TabClose.PlayOneShotOnCamera(null); + } + } + }; + if (this is FactionBase && base.Faction == Faction.OfPlayer) + { + yield return (Gizmo)new Command_Action + { + defaultLabel = "CommandFormCaravan".Translate(), + defaultDesc = "CommandFormCaravanDesc".Translate(), + icon = MapParent.FormCaravanCommand, + hotKey = KeyBindingDefOf.Misc2, + tutorTag = "FormCaravan", + action = (Action)delegate + { + Find.WindowStack.Add(new Dialog_FormCaravan(((_003CGetGizmos_003Ec__Iterator103)/*Error near IL_01d6: stateMachine*/)._003C_003Ef__this.Map, false, null, true)); + } + }; + } + else if (this.Map.mapPawns.FreeColonistsSpawnedCount != 0) + { + Command_Action reformCaravan = new Command_Action + { + defaultLabel = "CommandReformCaravan".Translate(), + defaultDesc = "CommandReformCaravanDesc".Translate(), + icon = MapParent.FormCaravanCommand, + hotKey = KeyBindingDefOf.Misc2, + tutorTag = "ReformCaravan", + action = (Action)delegate + { + Find.WindowStack.Add(new Dialog_FormCaravan(((_003CGetGizmos_003Ec__Iterator103)/*Error near IL_0289: stateMachine*/)._003C_003Ef__this.Map, true, null, true)); + } + }; + if (GenHostility.AnyHostileActiveThreat(this.Map)) + { + reformCaravan.Disable("CommandReformCaravanFailHostilePawns".Translate()); + } + yield return (Gizmo)reformCaravan; + } + } } - [DebuggerHidden] public override IEnumerable GetFloatMenuOptions(Caravan caravan) { - MapParent.c__Iterator104 c__Iterator = new MapParent.c__Iterator104(); - c__Iterator.caravan = caravan; - c__Iterator.<$>caravan = caravan; - c__Iterator.<>f__this = this; - MapParent.c__Iterator104 expr_1C = c__Iterator; - expr_1C.$PC = -2; - return expr_1C; + foreach (FloatMenuOption floatMenuOption in base.GetFloatMenuOptions(caravan)) + { + yield return floatMenuOption; + } + if (this.HasMap && this.UseGenericEnterMapFloatMenuOption) + { + yield return new FloatMenuOption("EnterMap".Translate(this.Label), (Action)delegate + { + ((_003CGetFloatMenuOptions_003Ec__Iterator104)/*Error near IL_00fa: stateMachine*/).caravan.pather.StartPath(((_003CGetFloatMenuOptions_003Ec__Iterator104)/*Error near IL_00fa: stateMachine*/)._003C_003Ef__this.Tile, new CaravanArrivalAction_Enter(((_003CGetFloatMenuOptions_003Ec__Iterator104)/*Error near IL_00fa: stateMachine*/)._003C_003Ef__this), true); + }, MenuOptionPriority.Default, null, null, 0f, null, this); + if (Prefs.DevMode) + { + yield return new FloatMenuOption("EnterMap".Translate(this.Label) + " (Dev: instantly)", (Action)delegate + { + ((_003CGetFloatMenuOptions_003Ec__Iterator104)/*Error near IL_0160: stateMachine*/).caravan.Tile = ((_003CGetFloatMenuOptions_003Ec__Iterator104)/*Error near IL_0160: stateMachine*/)._003C_003Ef__this.Tile; + new CaravanArrivalAction_Enter(((_003CGetFloatMenuOptions_003Ec__Iterator104)/*Error near IL_0160: stateMachine*/)._003C_003Ef__this).Arrived(((_003CGetFloatMenuOptions_003Ec__Iterator104)/*Error near IL_0160: stateMachine*/).caravan); + }, MenuOptionPriority.Default, null, null, 0f, null, this); + } + } } public override string GetInspectString() @@ -184,10 +243,7 @@ public override string GetInspectString() { text += "\n"; } - text = text + "ForceExitAndRemoveMapCountdown".Translate(new object[] - { - this.ForceExitAndRemoveMapCountdownTimeLeftString - }) + "."; + text = text + "ForceExitAndRemoveMapCountdown".Translate(this.ForceExitAndRemoveMapCountdownTimeLeftString) + "."; } return text; } @@ -210,11 +266,11 @@ private void TickForceExitAndRemoveMapCountdown() this.ticksLeftToForceExitAndRemoveMap--; if (this.ticksLeftToForceExitAndRemoveMap == 0) { - if (Dialog_FormCaravan.AllSendablePawns(this.Map, true).Any((Pawn x) => x.IsColonist)) + if (Dialog_FormCaravan.AllSendablePawns(this.Map, true).Any((Predicate)((Pawn x) => x.IsColonist))) { Messages.Message("MessageYouHaveToReformCaravanNow".Translate(), new GlobalTargetInfo(base.Tile), MessageSound.Standard); Current.Game.VisibleMap = this.Map; - Dialog_FormCaravan window = new Dialog_FormCaravan(this.Map, true, delegate + Dialog_FormCaravan window = new Dialog_FormCaravan(this.Map, true, (Action)delegate { if (this.HasMap) { @@ -230,12 +286,12 @@ private void TickForceExitAndRemoveMapCountdown() MapParent.tmpPawns.AddRange(from x in this.Map.mapPawns.AllPawns where x.Faction == Faction.OfPlayer || x.HostFaction == Faction.OfPlayer select x); - if (MapParent.tmpPawns.Any()) + if (MapParent.tmpPawns.Any()) { - if (MapParent.tmpPawns.Any((Pawn x) => CaravanUtility.IsOwner(x, Faction.OfPlayer))) + if (MapParent.tmpPawns.Any((Predicate)((Pawn x) => CaravanUtility.IsOwner(x, Faction.OfPlayer)))) { Caravan o = CaravanExitMapUtility.ExitMapAndCreateCaravan(MapParent.tmpPawns, Faction.OfPlayer, base.Tile); - Messages.Message("MessageAutomaticallyReformedCaravan".Translate(), o, MessageSound.Benefit); + Messages.Message("MessageAutomaticallyReformedCaravan".Translate(), (WorldObject)o, MessageSound.Benefit); } else { @@ -244,10 +300,7 @@ private void TickForceExitAndRemoveMapCountdown() { stringBuilder.AppendLine(" " + MapParent.tmpPawns[i].LabelCap); } - Find.LetterStack.ReceiveLetter("LetterLabelPawnsLostDueToMapCountdown".Translate(), "LetterPawnsLostDueToMapCountdown".Translate(new object[] - { - stringBuilder.ToString().TrimEndNewlines() - }), LetterDefOf.BadNonUrgent, new GlobalTargetInfo(base.Tile), null); + Find.LetterStack.ReceiveLetter("LetterLabelPawnsLostDueToMapCountdown".Translate(), "LetterPawnsLostDueToMapCountdown".Translate(stringBuilder.ToString().TrimEndNewlines()), LetterDefOf.BadNonUrgent, new GlobalTargetInfo(base.Tile), (string)null); } MapParent.tmpPawns.Clear(); } @@ -265,7 +318,7 @@ private void TickForceExitAndRemoveMapCountdown() public void CheckRemoveMapNow() { - bool flag; + bool flag = default(bool); if (this.HasMap && this.ShouldRemoveMapNow(out flag)) { Map map = this.Map; @@ -304,5 +357,11 @@ virtual IThingHolder get_ParentHolder() { return base.ParentHolder; } + + IThingHolder IThingHolder.get_ParentHolder() + { + //ILSpy generated this explicit interface implementation from .override directive in get_ParentHolder + return this.get_ParentHolder(); + } } } diff --git a/Assembly-CSharp/RimWorld.Planet/MultipleCaravansCellFinder.cs b/Assembly-CSharp/RimWorld.Planet/MultipleCaravansCellFinder.cs index 4ac93d720..ffadfd30a 100644 --- a/Assembly-CSharp/RimWorld.Planet/MultipleCaravansCellFinder.cs +++ b/Assembly-CSharp/RimWorld.Planet/MultipleCaravansCellFinder.cs @@ -23,44 +23,60 @@ public static class MultipleCaravansCellFinder public static void FindStartingCellsFor2Groups(Map map, out IntVec3 first, out IntVec3 second) { - for (int i = 0; i < 10; i++) + int num = 0; + while (num < 10) { - if (MultipleCaravansCellFinder.TryFindOppositeSpots(map, 0.05f, out first, out second)) + if (!MultipleCaravansCellFinder.TryFindOppositeSpots(map, 0.05f, out first, out second)) { - return; + num++; + continue; } + return; } - for (int j = 0; j < 10; j++) + int num2 = 0; + while (num2 < 10) { - if (MultipleCaravansCellFinder.TryFindOppositeSpots(map, 0.15f, out first, out second)) + if (!MultipleCaravansCellFinder.TryFindOppositeSpots(map, 0.15f, out first, out second)) { - return; + num2++; + continue; } + return; } - if (!CellFinder.TryFindRandomEdgeCellWith((IntVec3 x) => x.Standable(map) && !x.Fogged(map), map, CellFinder.EdgeRoadChance_Neutral, out first)) + if (!CellFinder.TryFindRandomEdgeCellWith((Predicate)((IntVec3 x) => x.Standable(map) && !x.Fogged(map)), map, CellFinder.EdgeRoadChance_Neutral, out first)) { Log.Error("Could not find any valid starting cell for a caravan."); first = CellFinder.RandomCell(map); second = CellFinder.RandomCell(map); - return; } - IntVec3 localFirst = first; - float tryMinDistBetweenSpots = (float)Mathf.Max(map.Size.x, map.Size.z) * 0.6f; - if (!CellFinder.TryFindRandomEdgeCellWith((IntVec3 x) => x.Standable(map) && !x.Fogged(map) && !x.InHorDistOf(localFirst, tryMinDistBetweenSpots), map, CellFinder.EdgeRoadChance_Neutral, out second) && !CellFinder.TryFindRandomEdgeCellWith((IntVec3 x) => x.Standable(map) && !x.Fogged(map), map, 0.5f, out second)) + else { - Log.Error("Could not find any valid starting cell for a caravan."); - second = CellFinder.RandomCell(map); - return; + IntVec3 localFirst = first; + IntVec3 size = map.Size; + int x2 = size.x; + IntVec3 size2 = map.Size; + float tryMinDistBetweenSpots = (float)((float)Mathf.Max(x2, size2.z) * 0.60000002384185791); + if (!CellFinder.TryFindRandomEdgeCellWith((Predicate)((IntVec3 x) => x.Standable(map) && !x.Fogged(map) && !x.InHorDistOf(localFirst, tryMinDistBetweenSpots)), map, CellFinder.EdgeRoadChance_Neutral, out second) && !CellFinder.TryFindRandomEdgeCellWith((Predicate)((IntVec3 x) => x.Standable(map) && !x.Fogged(map)), map, 0.5f, out second)) + { + Log.Error("Could not find any valid starting cell for a caravan."); + second = CellFinder.RandomCell(map); + } + else + { + first = CellFinder.RandomClosewalkCellNear(first, map, 7, null); + second = CellFinder.RandomClosewalkCellNear(second, map, 7, null); + } } - first = CellFinder.RandomClosewalkCellNear(first, map, 7, null); - second = CellFinder.RandomClosewalkCellNear(second, map, 7, null); } private static bool TryFindOppositeSpots(Map map, float maxDistPctToOppositeSpots, out IntVec3 first, out IntVec3 second) { IntVec3 intVec = MultipleCaravansCellFinder.RandomSpotNearEdge(map); IntVec3 intVec2 = MultipleCaravansCellFinder.OppositeSpot(intVec, map); - int num = Mathf.Min(map.Size.x, map.Size.z); + IntVec3 size = map.Size; + int x = size.x; + IntVec3 size2 = map.Size; + int num = Mathf.Min(x, size2.z); CellRect cellRect = CellRect.CenteredOn(intVec, Mathf.Max(Mathf.RoundToInt((float)num * maxDistPctToOppositeSpots), 1)).ClipInsideMap(map); CellRect cellRect2 = CellRect.CenteredOn(intVec2, Mathf.Max(Mathf.RoundToInt((float)num * maxDistPctToOppositeSpots), 1)).ClipInsideMap(map); for (int i = 0; i < 20; i++) @@ -82,16 +98,28 @@ private static bool TryFindOppositeSpots(Map map, float maxDistPctToOppositeSpot private static IntVec3 RandomSpotNearEdge(Map map) { CellRect cellRect = CellRect.WholeMap(map); - cellRect.minX += Mathf.RoundToInt((float)map.Size.x * 0.2f); - cellRect.minZ += Mathf.RoundToInt((float)map.Size.z * 0.2f); - cellRect.maxX -= Mathf.RoundToInt((float)map.Size.x * 0.2f); - cellRect.maxZ -= Mathf.RoundToInt((float)map.Size.z * 0.2f); - return cellRect.EdgeCells.RandomElement(); + int minX = cellRect.minX; + IntVec3 size = map.Size; + cellRect.minX = minX + Mathf.RoundToInt((float)((float)size.x * 0.20000000298023224)); + int minZ = cellRect.minZ; + IntVec3 size2 = map.Size; + cellRect.minZ = minZ + Mathf.RoundToInt((float)((float)size2.z * 0.20000000298023224)); + int maxX = cellRect.maxX; + IntVec3 size3 = map.Size; + cellRect.maxX = maxX - Mathf.RoundToInt((float)((float)size3.x * 0.20000000298023224)); + int maxZ = cellRect.maxZ; + IntVec3 size4 = map.Size; + cellRect.maxZ = maxZ - Mathf.RoundToInt((float)((float)size4.z * 0.20000000298023224)); + return cellRect.EdgeCells.RandomElement(); } private static IntVec3 OppositeSpot(IntVec3 spot, Map map) { - return new IntVec3(map.Size.x - spot.x, spot.y, map.Size.z - spot.z); + IntVec3 size = map.Size; + int newX = size.x - spot.x; + int y = spot.y; + IntVec3 size2 = map.Size; + return new IntVec3(newX, y, size2.z - spot.z); } } } diff --git a/Assembly-CSharp/RimWorld.Planet/OverallRainfall.cs b/Assembly-CSharp/RimWorld.Planet/OverallRainfall.cs index 5b6843654..3eac4e9b4 100644 --- a/Assembly-CSharp/RimWorld.Planet/OverallRainfall.cs +++ b/Assembly-CSharp/RimWorld.Planet/OverallRainfall.cs @@ -1,15 +1,13 @@ -using System; - namespace RimWorld.Planet { public enum OverallRainfall { - AlmostNone, - Little, - LittleBitLess, - Normal, - LittleBitMore, - High, - VeryHigh + AlmostNone = 0, + Little = 1, + LittleBitLess = 2, + Normal = 3, + LittleBitMore = 4, + High = 5, + VeryHigh = 6 } } diff --git a/Assembly-CSharp/RimWorld.Planet/OverallRainfallUtility.cs b/Assembly-CSharp/RimWorld.Planet/OverallRainfallUtility.cs index 45cae3682..03e288d99 100644 --- a/Assembly-CSharp/RimWorld.Planet/OverallRainfallUtility.cs +++ b/Assembly-CSharp/RimWorld.Planet/OverallRainfallUtility.cs @@ -176,19 +176,34 @@ public static SimpleCurve GetRainfallCurve(this OverallRainfall overallRainfall) switch (overallRainfall) { case OverallRainfall.AlmostNone: + { return OverallRainfallUtility.Curve_AlmostNone; + } case OverallRainfall.Little: + { return OverallRainfallUtility.Curve_Little; + } case OverallRainfall.LittleBitLess: + { return OverallRainfallUtility.Curve_LittleBitLess; + } case OverallRainfall.LittleBitMore: + { return OverallRainfallUtility.Curve_LittleBitMore; + } case OverallRainfall.High: + { return OverallRainfallUtility.Curve_High; + } case OverallRainfall.VeryHigh: + { return OverallRainfallUtility.Curve_VeryHigh; } - return null; + default: + { + return null; + } + } } } } diff --git a/Assembly-CSharp/RimWorld.Planet/OverallTemperature.cs b/Assembly-CSharp/RimWorld.Planet/OverallTemperature.cs index ff34d605c..4135510ec 100644 --- a/Assembly-CSharp/RimWorld.Planet/OverallTemperature.cs +++ b/Assembly-CSharp/RimWorld.Planet/OverallTemperature.cs @@ -1,15 +1,13 @@ -using System; - namespace RimWorld.Planet { public enum OverallTemperature { - VeryCold, - Cold, - LittleBitColder, - Normal, - LittleBitWarmer, - Hot, - VeryHot + VeryCold = 0, + Cold = 1, + LittleBitColder = 2, + Normal = 3, + LittleBitWarmer = 4, + Hot = 5, + VeryHot = 6 } } diff --git a/Assembly-CSharp/RimWorld.Planet/OverallTemperatureUtility.cs b/Assembly-CSharp/RimWorld.Planet/OverallTemperatureUtility.cs index dfbd20504..7055255cc 100644 --- a/Assembly-CSharp/RimWorld.Planet/OverallTemperatureUtility.cs +++ b/Assembly-CSharp/RimWorld.Planet/OverallTemperatureUtility.cs @@ -208,19 +208,34 @@ public static SimpleCurve GetTemperatureCurve(this OverallTemperature overallTem switch (overallTemperature) { case OverallTemperature.VeryCold: + { return OverallTemperatureUtility.Curve_VeryCold; + } case OverallTemperature.Cold: + { return OverallTemperatureUtility.Curve_Cold; + } case OverallTemperature.LittleBitColder: + { return OverallTemperatureUtility.Curve_LittleBitColder; + } case OverallTemperature.LittleBitWarmer: + { return OverallTemperatureUtility.Curve_LittleBitWarmer; + } case OverallTemperature.Hot: + { return OverallTemperatureUtility.Curve_Hot; + } case OverallTemperature.VeryHot: + { return OverallTemperatureUtility.Curve_VeryHot; } - return null; + default: + { + return null; + } + } } } } diff --git a/Assembly-CSharp/RimWorld.Planet/PackedListOfLists.cs b/Assembly-CSharp/RimWorld.Planet/PackedListOfLists.cs index d5b14d342..41b4522e3 100644 --- a/Assembly-CSharp/RimWorld.Planet/PackedListOfLists.cs +++ b/Assembly-CSharp/RimWorld.Planet/PackedListOfLists.cs @@ -1,4 +1,3 @@ -using System; using System.Collections.Generic; using UnityEngine; @@ -11,7 +10,7 @@ public static class PackedListOfLists public static void AddList(List offsets, List values, List listToAdd) { offsets.Add(values.Count); - values.AddRange(listToAdd); + values.AddRange((IEnumerable)listToAdd); } public static void GetList(List offsets, List values, int listIndex, List outList) @@ -33,76 +32,76 @@ public static void GenerateVertToTrisPackedList(List verts, List list; - List expr_56 = list = PackedListOfLists.vertAdjacentTrisCount; - int num; - int expr_60 = num = triangleIndices.v1; - num = list[num]; - expr_56[expr_60] = num + 1; + List obj = list = PackedListOfLists.vertAdjacentTrisCount; + int v; + int index = v = triangleIndices.v1; + v = list[v]; + obj[index] = v + 1; List list2; - List expr_7C = list2 = PackedListOfLists.vertAdjacentTrisCount; - int expr_86 = num = triangleIndices.v2; - num = list2[num]; - expr_7C[expr_86] = num + 1; + List obj2 = list2 = PackedListOfLists.vertAdjacentTrisCount; + int index2 = v = triangleIndices.v2; + v = list2[v]; + obj2[index2] = v + 1; List list3; - List expr_A2 = list3 = PackedListOfLists.vertAdjacentTrisCount; - int expr_AC = num = triangleIndices.v3; - num = list3[num]; - expr_A2[expr_AC] = num + 1; - j++; + List obj3 = list3 = PackedListOfLists.vertAdjacentTrisCount; + int index3 = v = triangleIndices.v3; + v = list3[v]; + obj3[index3] = v + 1; + num2++; } - int num2 = 0; - int k = 0; + int num3 = 0; + int num4 = 0; int count3 = verts.Count; - while (k < count3) + while (num4 < count3) { - outOffsets.Add(num2); - int num3 = PackedListOfLists.vertAdjacentTrisCount[k]; - PackedListOfLists.vertAdjacentTrisCount[k] = 0; - for (int l = 0; l < num3; l++) + outOffsets.Add(num3); + int num5 = PackedListOfLists.vertAdjacentTrisCount[num4]; + PackedListOfLists.vertAdjacentTrisCount[num4] = 0; + for (int num6 = 0; num6 < num5; num6++) { outValues.Add(-1); } - num2 += num3; - k++; + num3 += num5; + num4++; } - int m = 0; + int num7 = 0; int count4 = tris.Count; - while (m < count4) + while (num7 < count4) { - TriangleIndices triangleIndices2 = tris[m]; - outValues[outOffsets[triangleIndices2.v1] + PackedListOfLists.vertAdjacentTrisCount[triangleIndices2.v1]] = m; - outValues[outOffsets[triangleIndices2.v2] + PackedListOfLists.vertAdjacentTrisCount[triangleIndices2.v2]] = m; - outValues[outOffsets[triangleIndices2.v3] + PackedListOfLists.vertAdjacentTrisCount[triangleIndices2.v3]] = m; + TriangleIndices triangleIndices2 = tris[num7]; + outValues[outOffsets[triangleIndices2.v1] + PackedListOfLists.vertAdjacentTrisCount[triangleIndices2.v1]] = num7; + outValues[outOffsets[triangleIndices2.v2] + PackedListOfLists.vertAdjacentTrisCount[triangleIndices2.v2]] = num7; + outValues[outOffsets[triangleIndices2.v3] + PackedListOfLists.vertAdjacentTrisCount[triangleIndices2.v3]] = num7; List list4; - List expr_1CC = list4 = PackedListOfLists.vertAdjacentTrisCount; - int num; - int expr_1D6 = num = triangleIndices2.v1; - num = list4[num]; - expr_1CC[expr_1D6] = num + 1; + List obj4 = list4 = PackedListOfLists.vertAdjacentTrisCount; + int v; + int index4 = v = triangleIndices2.v1; + v = list4[v]; + obj4[index4] = v + 1; List list5; - List expr_1F2 = list5 = PackedListOfLists.vertAdjacentTrisCount; - int expr_1FC = num = triangleIndices2.v2; - num = list5[num]; - expr_1F2[expr_1FC] = num + 1; + List obj5 = list5 = PackedListOfLists.vertAdjacentTrisCount; + int index5 = v = triangleIndices2.v2; + v = list5[v]; + obj5[index5] = v + 1; List list6; - List expr_218 = list6 = PackedListOfLists.vertAdjacentTrisCount; - int expr_222 = num = triangleIndices2.v3; - num = list6[num]; - expr_218[expr_222] = num + 1; - m++; + List obj6 = list6 = PackedListOfLists.vertAdjacentTrisCount; + int index6 = v = triangleIndices2.v3; + v = list6[v]; + obj6[index6] = v + 1; + num7++; } } } diff --git a/Assembly-CSharp/RimWorld.Planet/PawnDiscardDecideMode.cs b/Assembly-CSharp/RimWorld.Planet/PawnDiscardDecideMode.cs index 8042a173b..5529219f8 100644 --- a/Assembly-CSharp/RimWorld.Planet/PawnDiscardDecideMode.cs +++ b/Assembly-CSharp/RimWorld.Planet/PawnDiscardDecideMode.cs @@ -1,11 +1,9 @@ -using System; - namespace RimWorld.Planet { public enum PawnDiscardDecideMode { - Decide, - KeepForever, - Discard + Decide = 0, + KeepForever = 1, + Discard = 2 } } diff --git a/Assembly-CSharp/RimWorld.Planet/PlanetShapeGenerator.cs b/Assembly-CSharp/RimWorld.Planet/PlanetShapeGenerator.cs index 947f3092e..83ae7fbd9 100644 --- a/Assembly-CSharp/RimWorld.Planet/PlanetShapeGenerator.cs +++ b/Assembly-CSharp/RimWorld.Planet/PlanetShapeGenerator.cs @@ -1,4 +1,3 @@ -using System; using System.Collections.Generic; using UnityEngine; using Verse; @@ -123,14 +122,14 @@ private static void Subdivide(bool lastPass) { PackedListOfLists.GenerateVertToTrisPackedList(PlanetShapeGenerator.verts, PlanetShapeGenerator.tris, PlanetShapeGenerator.vertToTris_offsets, PlanetShapeGenerator.vertToTris_values); int count = PlanetShapeGenerator.verts.Count; - int i = 0; + int num = 0; int count2 = PlanetShapeGenerator.tris.Count; - while (i < count2) + while (num < count2) { - TriangleIndices triangleIndices = PlanetShapeGenerator.tris[i]; + TriangleIndices triangleIndices = PlanetShapeGenerator.tris[num]; Vector3 vector = (PlanetShapeGenerator.verts[triangleIndices.v1] + PlanetShapeGenerator.verts[triangleIndices.v2] + PlanetShapeGenerator.verts[triangleIndices.v3]) / 3f; PlanetShapeGenerator.verts.Add(vector.normalized * PlanetShapeGenerator.radius); - i++; + num++; } PlanetShapeGenerator.newTris.Clear(); if (lastPass) @@ -139,66 +138,68 @@ private static void Subdivide(bool lastPass) PlanetShapeGenerator.vertToTileIDs_values.Clear(); PlanetShapeGenerator.tileIDToVerts_offsets.Clear(); PlanetShapeGenerator.tileIDToVerts_values.Clear(); - int j = 0; + int num2 = 0; int count3 = PlanetShapeGenerator.verts.Count; - while (j < count3) + while (num2 < count3) { PlanetShapeGenerator.vertToTileIDs_offsets.Add(PlanetShapeGenerator.vertToTileIDs_values.Count); - if (j >= count) + if (num2 >= count) { - for (int k = 0; k < 6; k++) + for (int i = 0; i < 6; i++) { PlanetShapeGenerator.vertToTileIDs_values.Add(-1); } } - j++; + num2++; } } - for (int l = 0; l < count; l++) + for (int num3 = 0; num3 < count; num3++) { - PackedListOfLists.GetList(PlanetShapeGenerator.vertToTris_offsets, PlanetShapeGenerator.vertToTris_values, l, PlanetShapeGenerator.adjacentTris); + PackedListOfLists.GetList(PlanetShapeGenerator.vertToTris_offsets, PlanetShapeGenerator.vertToTris_values, num3, PlanetShapeGenerator.adjacentTris); int count4 = PlanetShapeGenerator.adjacentTris.Count; if (!lastPass) { - for (int m = 0; m < count4; m++) + for (int num4 = 0; num4 < count4; num4++) { - int num = PlanetShapeGenerator.adjacentTris[m]; - int v = count + num; - int nextOrderedVertex = PlanetShapeGenerator.tris[num].GetNextOrderedVertex(l); - int num2 = -1; - for (int n = 0; n < count4; n++) + int num5 = PlanetShapeGenerator.adjacentTris[num4]; + int v = count + num5; + int nextOrderedVertex = PlanetShapeGenerator.tris[num5].GetNextOrderedVertex(num3); + int num6 = -1; + for (int j = 0; j < count4; j++) { - if (m != n) + if (num4 == j) + { + continue; + } + TriangleIndices triangleIndices2 = PlanetShapeGenerator.tris[PlanetShapeGenerator.adjacentTris[j]]; + if (triangleIndices2.v1 != nextOrderedVertex && triangleIndices2.v2 != nextOrderedVertex && triangleIndices2.v3 != nextOrderedVertex) { - TriangleIndices triangleIndices2 = PlanetShapeGenerator.tris[PlanetShapeGenerator.adjacentTris[n]]; - if (triangleIndices2.v1 == nextOrderedVertex || triangleIndices2.v2 == nextOrderedVertex || triangleIndices2.v3 == nextOrderedVertex) - { - num2 = PlanetShapeGenerator.adjacentTris[n]; - break; - } + continue; } + num6 = PlanetShapeGenerator.adjacentTris[j]; + break; } - if (num2 >= 0) + if (num6 >= 0) { - int v2 = count + num2; - PlanetShapeGenerator.newTris.Add(new TriangleIndices(l, v2, v)); + int v2 = count + num6; + PlanetShapeGenerator.newTris.Add(new TriangleIndices(num3, v2, v)); } } } else if (count4 == 5 || count4 == 6) { - int num3 = 0; - int nextOrderedVertex2 = PlanetShapeGenerator.tris[PlanetShapeGenerator.adjacentTris[num3]].GetNextOrderedVertex(l); - int num4 = num3; + int num7 = 0; + int nextOrderedVertex2 = PlanetShapeGenerator.tris[PlanetShapeGenerator.adjacentTris[num7]].GetNextOrderedVertex(num3); + int num8 = num7; int currentTriangleVertex = nextOrderedVertex2; PlanetShapeGenerator.generatedTileVerts.Clear(); - for (int num5 = 0; num5 < count4; num5++) + for (int num9 = 0; num9 < count4; num9++) { - int item = count + PlanetShapeGenerator.adjacentTris[num4]; + int item = count + PlanetShapeGenerator.adjacentTris[num8]; PlanetShapeGenerator.generatedTileVerts.Add(item); - int nextAdjancetTriangle = PlanetShapeGenerator.GetNextAdjancetTriangle(num4, currentTriangleVertex, PlanetShapeGenerator.adjacentTris); - int nextOrderedVertex3 = PlanetShapeGenerator.tris[PlanetShapeGenerator.adjacentTris[nextAdjancetTriangle]].GetNextOrderedVertex(l); - num4 = nextAdjancetTriangle; + int nextAdjancetTriangle = PlanetShapeGenerator.GetNextAdjancetTriangle(num8, currentTriangleVertex, PlanetShapeGenerator.adjacentTris); + int nextOrderedVertex3 = PlanetShapeGenerator.tris[PlanetShapeGenerator.adjacentTris[nextAdjancetTriangle]].GetNextOrderedVertex(num3); + num8 = nextAdjancetTriangle; currentTriangleVertex = nextOrderedVertex3; } PlanetShapeGenerator.FinalizeGeneratedTile(PlanetShapeGenerator.generatedTileVerts); @@ -210,38 +211,41 @@ private static void Subdivide(bool lastPass) private static void FinalizeGeneratedTile(List generatedTileVerts) { - if ((generatedTileVerts.Count != 5 && generatedTileVerts.Count != 6) || generatedTileVerts.Count > 6) + if (generatedTileVerts.Count != 5 && generatedTileVerts.Count != 6) { - Log.Error("Planet shape generation internal error: generated a tile with " + generatedTileVerts.Count + " vertices. Only 5 and 6 are allowed."); - return; + goto IL_0024; } - if (PlanetShapeGenerator.ShouldDiscardGeneratedTile(generatedTileVerts)) - { - return; - } - int count = PlanetShapeGenerator.tileIDToFinalVerts_offsets.Count; - PlanetShapeGenerator.tileIDToFinalVerts_offsets.Add(PlanetShapeGenerator.finalVerts.Count); - int i = 0; - int count2 = generatedTileVerts.Count; - while (i < count2) + if (generatedTileVerts.Count > 6) + goto IL_0024; + if (!PlanetShapeGenerator.ShouldDiscardGeneratedTile(generatedTileVerts)) { - int index = generatedTileVerts[i]; - PlanetShapeGenerator.finalVerts.Add(PlanetShapeGenerator.verts[index]); - PlanetShapeGenerator.vertToTileIDs_values[PlanetShapeGenerator.vertToTileIDs_values.IndexOf(-1, PlanetShapeGenerator.vertToTileIDs_offsets[index])] = count; - i++; + int count = PlanetShapeGenerator.tileIDToFinalVerts_offsets.Count; + PlanetShapeGenerator.tileIDToFinalVerts_offsets.Add(PlanetShapeGenerator.finalVerts.Count); + int num = 0; + int count2 = generatedTileVerts.Count; + while (num < count2) + { + int index = generatedTileVerts[num]; + PlanetShapeGenerator.finalVerts.Add(PlanetShapeGenerator.verts[index]); + PlanetShapeGenerator.vertToTileIDs_values[PlanetShapeGenerator.vertToTileIDs_values.IndexOf(-1, PlanetShapeGenerator.vertToTileIDs_offsets[index])] = count; + num++; + } + PackedListOfLists.AddList(PlanetShapeGenerator.tileIDToVerts_offsets, PlanetShapeGenerator.tileIDToVerts_values, generatedTileVerts); } - PackedListOfLists.AddList(PlanetShapeGenerator.tileIDToVerts_offsets, PlanetShapeGenerator.tileIDToVerts_values, generatedTileVerts); + return; + IL_0024: + Log.Error("Planet shape generation internal error: generated a tile with " + generatedTileVerts.Count + " vertices. Only 5 and 6 are allowed."); } private static bool ShouldDiscardGeneratedTile(List generatedTileVerts) { Vector3 a = Vector3.zero; - int i = 0; + int num = 0; int count = generatedTileVerts.Count; - while (i < count) + while (num < count) { - a += PlanetShapeGenerator.verts[generatedTileVerts[i]]; - i++; + a += PlanetShapeGenerator.verts[generatedTileVerts[num]]; + num++; } return !MeshUtility.Visible(a / (float)generatedTileVerts.Count, PlanetShapeGenerator.radius, PlanetShapeGenerator.viewCenter, PlanetShapeGenerator.viewAngle); } @@ -249,39 +253,33 @@ private static bool ShouldDiscardGeneratedTile(List generatedTileVerts) private static void CalculateTileNeighbors() { List list = new List(); - int i = 0; + int num = 0; int count = PlanetShapeGenerator.tileIDToVerts_offsets.Count; - while (i < count) + while (num < count) { PlanetShapeGenerator.tmpNeighborsToAdd.Clear(); - PackedListOfLists.GetList(PlanetShapeGenerator.tileIDToVerts_offsets, PlanetShapeGenerator.tileIDToVerts_values, i, PlanetShapeGenerator.tmpVerts); - int j = 0; + PackedListOfLists.GetList(PlanetShapeGenerator.tileIDToVerts_offsets, PlanetShapeGenerator.tileIDToVerts_values, num, PlanetShapeGenerator.tmpVerts); + int num2 = 0; int count2 = PlanetShapeGenerator.tmpVerts.Count; - while (j < count2) + while (num2 < count2) { - PackedListOfLists.GetList(PlanetShapeGenerator.vertToTileIDs_offsets, PlanetShapeGenerator.vertToTileIDs_values, PlanetShapeGenerator.tmpVerts[j], PlanetShapeGenerator.tmpTileIDs); - PackedListOfLists.GetList(PlanetShapeGenerator.vertToTileIDs_offsets, PlanetShapeGenerator.vertToTileIDs_values, PlanetShapeGenerator.tmpVerts[(j + 1) % PlanetShapeGenerator.tmpVerts.Count], list); - int k = 0; + PackedListOfLists.GetList(PlanetShapeGenerator.vertToTileIDs_offsets, PlanetShapeGenerator.vertToTileIDs_values, PlanetShapeGenerator.tmpVerts[num2], PlanetShapeGenerator.tmpTileIDs); + PackedListOfLists.GetList(PlanetShapeGenerator.vertToTileIDs_offsets, PlanetShapeGenerator.vertToTileIDs_values, PlanetShapeGenerator.tmpVerts[(num2 + 1) % PlanetShapeGenerator.tmpVerts.Count], list); + int num3 = 0; int count3 = PlanetShapeGenerator.tmpTileIDs.Count; - while (k < count3) + while (num3 < count3) { - int num = PlanetShapeGenerator.tmpTileIDs[k]; - if (num != i) + int num4 = PlanetShapeGenerator.tmpTileIDs[num3]; + if (num4 != num && num4 != -1 && list.Contains(num4)) { - if (num != -1) - { - if (list.Contains(num)) - { - PlanetShapeGenerator.tmpNeighborsToAdd.Add(num); - } - } + PlanetShapeGenerator.tmpNeighborsToAdd.Add(num4); } - k++; + num3++; } - j++; + num2++; } - PackedListOfLists.AddList(PlanetShapeGenerator.tileIDToNeighbors_offsets, PlanetShapeGenerator.tileIDToNeighbors_values, PlanetShapeGenerator.tmpNeighborsToAdd); - i++; + PackedListOfLists.AddList(PlanetShapeGenerator.tileIDToNeighbors_offsets, PlanetShapeGenerator.tileIDToNeighbors_values, PlanetShapeGenerator.tmpNeighborsToAdd); + num++; } } @@ -289,17 +287,17 @@ private static int GetNextAdjancetTriangle(int currentAdjTriangleIndex, int curr { int i = 0; int count = adjacentTris.Count; - while (i < count) + for (; i < count; i++) { if (currentAdjTriangleIndex != i) { TriangleIndices triangleIndices = PlanetShapeGenerator.tris[adjacentTris[i]]; - if (triangleIndices.v1 == currentTriangleVertex || triangleIndices.v2 == currentTriangleVertex || triangleIndices.v3 == currentTriangleVertex) + if (triangleIndices.v1 != currentTriangleVertex && triangleIndices.v2 != currentTriangleVertex && triangleIndices.v3 != currentTriangleVertex) { - return i; + continue; } + return i; } - i++; } Log.Error("Planet shape generation internal error: could not find next adjacent triangle."); return -1; diff --git a/Assembly-CSharp/RimWorld.Planet/RoutePlannerWaypoint.cs b/Assembly-CSharp/RimWorld.Planet/RoutePlannerWaypoint.cs index 2e025bf22..867051388 100644 --- a/Assembly-CSharp/RimWorld.Planet/RoutePlannerWaypoint.cs +++ b/Assembly-CSharp/RimWorld.Planet/RoutePlannerWaypoint.cs @@ -1,6 +1,5 @@ using System; using System.Collections.Generic; -using System.Diagnostics; using System.Text; using Verse; @@ -40,32 +39,34 @@ public override string GetInspectString() { stringBuilder.AppendLine(); } - stringBuilder.Append("EstimatedTimeToThisWaypoint".Translate(new object[] - { - ticksToWaypoint.ToStringTicksToDays("0.#") - })); + stringBuilder.Append("EstimatedTimeToThisWaypoint".Translate(ticksToWaypoint.ToStringTicksToDays("0.#"))); if (num >= 2) { int ticksToWaypoint2 = worldRoutePlanner.GetTicksToWaypoint(num - 1); stringBuilder.AppendLine(); - stringBuilder.Append("EstimatedTimeToThisWaypointFromPrevious".Translate(new object[] - { - (ticksToWaypoint - ticksToWaypoint2).ToStringTicksToDays("0.#") - })); + stringBuilder.Append("EstimatedTimeToThisWaypointFromPrevious".Translate((ticksToWaypoint - ticksToWaypoint2).ToStringTicksToDays("0.#"))); } } } return stringBuilder.ToString(); } - [DebuggerHidden] public override IEnumerable GetGizmos() { - RoutePlannerWaypoint.c__Iterator109 c__Iterator = new RoutePlannerWaypoint.c__Iterator109(); - c__Iterator.<>f__this = this; - RoutePlannerWaypoint.c__Iterator109 expr_0E = c__Iterator; - expr_0E.$PC = -2; - return expr_0E; + foreach (Gizmo gizmo in base.GetGizmos()) + { + yield return gizmo; + } + yield return (Gizmo)new Command_Action + { + defaultLabel = "CommandRemoveWaypointLabel".Translate(), + defaultDesc = "CommandRemoveWaypointDesc".Translate(), + icon = TexCommand.RemoveRoutePlannerWaypoint, + action = (Action)delegate + { + Find.WorldRoutePlanner.TryRemoveWaypoint(((_003CGetGizmos_003Ec__Iterator109)/*Error near IL_00f5: stateMachine*/)._003C_003Ef__this, true); + } + }; } } } diff --git a/Assembly-CSharp/RimWorld.Planet/SettleInEmptyTileUtility.cs b/Assembly-CSharp/RimWorld.Planet/SettleInEmptyTileUtility.cs index 71f0889e3..cfe70c7be 100644 --- a/Assembly-CSharp/RimWorld.Planet/SettleInEmptyTileUtility.cs +++ b/Assembly-CSharp/RimWorld.Planet/SettleInEmptyTileUtility.cs @@ -17,21 +17,23 @@ public static void Settle(Caravan caravan) if (faction != Faction.OfPlayer) { Log.Error("Cannot settle with non-player faction."); - return; } - FactionBase newHome = SettleUtility.AddNewHome(caravan.Tile, faction); - LongEventHandler.QueueLongEvent(delegate + else { - GetOrGenerateMapUtility.GetOrGenerateMap(caravan.Tile, Find.World.info.initialMapSize, null); - }, "GeneratingMap", true, new Action(GameAndMapInitExceptionHandlers.ErrorWhileGeneratingMap)); - LongEventHandler.QueueLongEvent(delegate - { - Map map = newHome.Map; - Pawn t = caravan.PawnsListForReading[0]; - Predicate extraCellValidator = (IntVec3 x) => x.GetRoom(map, RegionType.Set_Passable).CellCount >= 600; - CaravanEnterMapUtility.Enter(caravan, map, CaravanEnterMode.Center, CaravanDropInventoryMode.DropInstantly, false, extraCellValidator); - CameraJumper.TryJump(t); - }, "SpawningColonists", true, new Action(GameAndMapInitExceptionHandlers.ErrorWhileGeneratingMap)); + FactionBase newHome = SettleUtility.AddNewHome(caravan.Tile, faction); + LongEventHandler.QueueLongEvent((Action)delegate() + { + GetOrGenerateMapUtility.GetOrGenerateMap(caravan.Tile, Find.World.info.initialMapSize, null); + }, "GeneratingMap", true, new Action(GameAndMapInitExceptionHandlers.ErrorWhileGeneratingMap)); + LongEventHandler.QueueLongEvent((Action)delegate() + { + Map map = newHome.Map; + Pawn t = caravan.PawnsListForReading[0]; + Predicate extraCellValidator = (Predicate)((IntVec3 x) => x.GetRoom(map, RegionType.Set_Passable).CellCount >= 600); + CaravanEnterMapUtility.Enter(caravan, map, CaravanEnterMode.Center, CaravanDropInventoryMode.DropInstantly, false, extraCellValidator); + CameraJumper.TryJump((Thing)t); + }, "SpawningColonists", true, new Action(GameAndMapInitExceptionHandlers.ErrorWhileGeneratingMap)); + } } public static Command SettleCommand(Caravan caravan) @@ -40,7 +42,7 @@ public static Command SettleCommand(Caravan caravan) command_Settle.defaultLabel = "CommandSettle".Translate(); command_Settle.defaultDesc = "CommandSettleDesc".Translate(); command_Settle.icon = SettleUtility.SettleCommandTex; - command_Settle.action = delegate + command_Settle.action = (Action)delegate() { SoundDefOf.TickHigh.PlayOneShotOnCamera(null); SettleInEmptyTileUtility.Settle(caravan); diff --git a/Assembly-CSharp/RimWorld.Planet/SettleInExistingMapUtility.cs b/Assembly-CSharp/RimWorld.Planet/SettleInExistingMapUtility.cs index 94949b665..b4effbd93 100644 --- a/Assembly-CSharp/RimWorld.Planet/SettleInExistingMapUtility.cs +++ b/Assembly-CSharp/RimWorld.Planet/SettleInExistingMapUtility.cs @@ -17,7 +17,7 @@ public static Command SettleCommand(Map map, bool requiresNoEnemies) command_Settle.defaultLabel = "CommandSettle".Translate(); command_Settle.defaultDesc = "CommandSettleDesc".Translate(); command_Settle.icon = SettleUtility.SettleCommandTex; - command_Settle.action = delegate + command_Settle.action = (Action)delegate() { SoundDefOf.TickHigh.PlayOneShotOnCamera(null); SettleInExistingMapUtility.Settle(map); @@ -41,13 +41,23 @@ public static Command SettleCommand(Map map, bool requiresNoEnemies) } else if (requiresNoEnemies) { - foreach (IAttackTarget current in map.attackTargetsCache.TargetsHostileToColony) + HashSet.Enumerator enumerator = map.attackTargetsCache.TargetsHostileToColony.GetEnumerator(); + try { - if (!current.ThreatDisabled()) + while (enumerator.MoveNext()) { - command_Settle.Disable("CommandSettleFailEnemies".Translate()); - break; + IAttackTarget current = enumerator.Current; + if (!current.ThreatDisabled()) + { + command_Settle.Disable("CommandSettleFailEnemies".Translate()); + return command_Settle; + } } + return command_Settle; + } + finally + { + ((IDisposable)(object)enumerator).Dispose(); } } } @@ -57,13 +67,12 @@ public static Command SettleCommand(Map map, bool requiresNoEnemies) public static void Settle(Map map) { MapParent parent = map.info.parent; - FactionBase factionBase = SettleUtility.AddNewHome(map.Tile, Faction.OfPlayer); - map.info.parent = factionBase; + FactionBase o = (FactionBase)(map.info.parent = SettleUtility.AddNewHome(map.Tile, Faction.OfPlayer)); if (parent != null) { Find.WorldObjects.Remove(parent); } - Messages.Message("MessageSettledInExistingMap".Translate(), factionBase, MessageSound.Benefit); + Messages.Message("MessageSettledInExistingMap".Translate(), (WorldObject)o, MessageSound.Benefit); SettleInExistingMapUtility.tmpPlayerPawns.Clear(); SettleInExistingMapUtility.tmpPlayerPawns.AddRange(from x in map.mapPawns.AllPawnsSpawned where x.Faction == Faction.OfPlayer || x.HostFaction == Faction.OfPlayer diff --git a/Assembly-CSharp/RimWorld.Planet/SettleUtility.cs b/Assembly-CSharp/RimWorld.Planet/SettleUtility.cs index b5c819791..ec4f773f1 100644 --- a/Assembly-CSharp/RimWorld.Planet/SettleUtility.cs +++ b/Assembly-CSharp/RimWorld.Planet/SettleUtility.cs @@ -1,4 +1,3 @@ -using System; using System.Collections.Generic; using UnityEngine; using Verse; diff --git a/Assembly-CSharp/RimWorld.Planet/Settlement.cs b/Assembly-CSharp/RimWorld.Planet/Settlement.cs index d5c7f0270..14260ca9d 100644 --- a/Assembly-CSharp/RimWorld.Planet/Settlement.cs +++ b/Assembly-CSharp/RimWorld.Planet/Settlement.cs @@ -1,6 +1,5 @@ using System; using System.Collections.Generic; -using System.Diagnostics; using Verse; namespace RimWorld.Planet @@ -93,7 +92,7 @@ public string TraderName { if (this.trader == null) { - return null; + return (string)null; } return this.trader.TraderName; } @@ -103,7 +102,11 @@ public bool CanTradeNow { get { - return this.trader != null && this.trader.CanTradeNow; + if (this.trader == null) + { + return false; + } + return this.trader.CanTradeNow; } } @@ -142,14 +145,14 @@ public override void ExposeData() { base.ExposeData(); Scribe_Collections.Look(ref this.previouslyGeneratedInhabitants, "previouslyGeneratedInhabitants", LookMode.Reference, new object[0]); - Scribe_Deep.Look(ref this.trader, "trader", new object[] + Scribe_Deep.Look(ref this.trader, "trader", new object[1] { this }); if (Scribe.mode == LoadSaveMode.PostLoadInit) { BackCompatibility.SettlementPostLoadInit(this); - this.previouslyGeneratedInhabitants.RemoveAll((Pawn x) => x == null); + this.previouslyGeneratedInhabitants.RemoveAll((Predicate)((Pawn x) => x == null)); } } @@ -165,12 +168,12 @@ public override void Tick() public override void Notify_MyMapRemoved(Map map) { base.Notify_MyMapRemoved(map); - for (int i = this.previouslyGeneratedInhabitants.Count - 1; i >= 0; i--) + for (int num = this.previouslyGeneratedInhabitants.Count - 1; num >= 0; num--) { - Pawn pawn = this.previouslyGeneratedInhabitants[i]; + Pawn pawn = this.previouslyGeneratedInhabitants[num]; if (pawn.DestroyedOrNull() || !pawn.IsWorldPawn()) { - this.previouslyGeneratedInhabitants.RemoveAt(i); + this.previouslyGeneratedInhabitants.RemoveAt(num); } } } @@ -190,26 +193,69 @@ public override void PostRemove() } } - [DebuggerHidden] public override IEnumerable GetGizmos() { - Settlement.c__Iterator106 c__Iterator = new Settlement.c__Iterator106(); - c__Iterator.<>f__this = this; - Settlement.c__Iterator106 expr_0E = c__Iterator; - expr_0E.$PC = -2; - return expr_0E; + foreach (Gizmo gizmo in base.GetGizmos()) + { + yield return gizmo; + } + if (this.Abandonable) + { + yield return (Gizmo)SettlementAbandonUtility.AbandonCommand(this); + } + if (base.Faction != Faction.OfPlayer && !PlayerKnowledgeDatabase.IsComplete(ConceptDefOf.FormCaravan)) + { + yield return (Gizmo)new Command_Action + { + defaultLabel = "CommandFormCaravan".Translate(), + defaultDesc = "CommandFormCaravanDesc".Translate(), + icon = MapParent.FormCaravanCommand, + action = (Action)delegate + { + Find.Tutor.learningReadout.TryActivateConcept(ConceptDefOf.FormCaravan); + Messages.Message("MessageSelectOwnBaseToFormCaravan".Translate(), MessageSound.RejectInput); + } + }; + } } - [DebuggerHidden] public override IEnumerable GetFloatMenuOptions(Caravan caravan) { - Settlement.c__Iterator107 c__Iterator = new Settlement.c__Iterator107(); - c__Iterator.caravan = caravan; - c__Iterator.<$>caravan = caravan; - c__Iterator.<>f__this = this; - Settlement.c__Iterator107 expr_1C = c__Iterator; - expr_1C.$PC = -2; - return expr_1C; + foreach (FloatMenuOption floatMenuOption in base.GetFloatMenuOptions(caravan)) + { + yield return floatMenuOption; + } + if (this.Visitable && CaravanVisitUtility.SettlementVisitedNow(caravan) != this) + { + yield return new FloatMenuOption("VisitSettlement".Translate(this.Label), (Action)delegate + { + ((_003CGetFloatMenuOptions_003Ec__Iterator107)/*Error near IL_0108: stateMachine*/).caravan.pather.StartPath(((_003CGetFloatMenuOptions_003Ec__Iterator107)/*Error near IL_0108: stateMachine*/)._003C_003Ef__this.Tile, new CaravanArrivalAction_VisitSettlement(((_003CGetFloatMenuOptions_003Ec__Iterator107)/*Error near IL_0108: stateMachine*/)._003C_003Ef__this), true); + }, MenuOptionPriority.Default, null, null, 0f, null, this); + if (Prefs.DevMode) + { + yield return new FloatMenuOption("VisitSettlement".Translate(this.Label) + " (Dev: instantly)", (Action)delegate + { + ((_003CGetFloatMenuOptions_003Ec__Iterator107)/*Error near IL_016e: stateMachine*/).caravan.Tile = ((_003CGetFloatMenuOptions_003Ec__Iterator107)/*Error near IL_016e: stateMachine*/)._003C_003Ef__this.Tile; + ((_003CGetFloatMenuOptions_003Ec__Iterator107)/*Error near IL_016e: stateMachine*/).caravan.pather.StopDead(); + new CaravanArrivalAction_VisitSettlement(((_003CGetFloatMenuOptions_003Ec__Iterator107)/*Error near IL_016e: stateMachine*/)._003C_003Ef__this).Arrived(((_003CGetFloatMenuOptions_003Ec__Iterator107)/*Error near IL_016e: stateMachine*/).caravan); + }, MenuOptionPriority.Default, null, null, 0f, null, this); + } + } + if (this.Attackable) + { + yield return new FloatMenuOption("AttackSettlement".Translate(this.Label), (Action)delegate + { + ((_003CGetFloatMenuOptions_003Ec__Iterator107)/*Error near IL_01d0: stateMachine*/).caravan.pather.StartPath(((_003CGetFloatMenuOptions_003Ec__Iterator107)/*Error near IL_01d0: stateMachine*/)._003C_003Ef__this.Tile, new CaravanArrivalAction_AttackSettlement(((_003CGetFloatMenuOptions_003Ec__Iterator107)/*Error near IL_01d0: stateMachine*/)._003C_003Ef__this), true); + }, MenuOptionPriority.Default, null, null, 0f, null, this); + if (Prefs.DevMode) + { + yield return new FloatMenuOption("AttackSettlement".Translate(this.Label) + " (Dev: instantly)", (Action)delegate + { + ((_003CGetFloatMenuOptions_003Ec__Iterator107)/*Error near IL_0236: stateMachine*/).caravan.Tile = ((_003CGetFloatMenuOptions_003Ec__Iterator107)/*Error near IL_0236: stateMachine*/)._003C_003Ef__this.Tile; + new CaravanArrivalAction_AttackSettlement(((_003CGetFloatMenuOptions_003Ec__Iterator107)/*Error near IL_0236: stateMachine*/)._003C_003Ef__this).Arrived(((_003CGetFloatMenuOptions_003Ec__Iterator107)/*Error near IL_0236: stateMachine*/).caravan); + }, MenuOptionPriority.Default, null, null, 0f, null, this); + } + } } public override void GetChildHolders(List outChildren) @@ -225,5 +271,11 @@ virtual Faction get_Faction() { return base.Faction; } + + Faction ITrader.get_Faction() + { + //ILSpy generated this explicit interface implementation from .override directive in get_Faction + return this.get_Faction(); + } } } diff --git a/Assembly-CSharp/RimWorld.Planet/SettlementAbandonUtility.cs b/Assembly-CSharp/RimWorld.Planet/SettlementAbandonUtility.cs index 2a60656af..75fb47fd0 100644 --- a/Assembly-CSharp/RimWorld.Planet/SettlementAbandonUtility.cs +++ b/Assembly-CSharp/RimWorld.Planet/SettlementAbandonUtility.cs @@ -19,7 +19,7 @@ public static Command AbandonCommand(Settlement settlement) command_Action.defaultLabel = "CommandAbandonHome".Translate(); command_Action.defaultDesc = "CommandAbandonHomeDesc".Translate(); command_Action.icon = SettlementAbandonUtility.AbandonCommandTex; - command_Action.action = delegate + command_Action.action = (Action)delegate() { SettlementAbandonUtility.TryAbandonViaInterface(settlement); }; @@ -32,7 +32,7 @@ public static Command AbandonCommand(Settlement settlement) public static bool AllColonistsThere(Settlement settlement) { - return !CaravanUtility.PlayerHasAnyCaravan() && !Find.Maps.Any((Map x) => x.info.parent != settlement && x.mapPawns.FreeColonistsSpawned.Any()); + return !CaravanUtility.PlayerHasAnyCaravan() && !Find.Maps.Any((Predicate)((Map x) => x.info.parent != settlement && x.mapPawns.FreeColonistsSpawned.Any())); } public static void TryAbandonViaInterface(Settlement settlement) @@ -47,10 +47,10 @@ public static void TryAbandonViaInterface(Settlement settlement) { StringBuilder stringBuilder = new StringBuilder(); IEnumerable source = map.mapPawns.PawnsInFaction(Faction.OfPlayer); - if (source.Count() != 0) + if (source.Count() != 0) { StringBuilder stringBuilder2 = new StringBuilder(); - foreach (Pawn current in from x in source + foreach (Pawn item in from x in source orderby x.IsColonist descending select x) { @@ -58,14 +58,11 @@ orderby x.IsColonist descending { stringBuilder2.AppendLine(); } - stringBuilder2.Append(" " + current.LabelCap); + stringBuilder2.Append(" " + item.LabelCap); } - stringBuilder.Append("ConfirmAbandonHomeWithColonyPawns".Translate(new object[] - { - stringBuilder2 - })); + stringBuilder.Append("ConfirmAbandonHomeWithColonyPawns".Translate(stringBuilder2)); } - PawnDiedOrDownedThoughtsUtility.BuildMoodThoughtsListString(map.mapPawns.AllPawns, PawnDiedOrDownedThoughtsKind.Abandoned, stringBuilder, null, "\n\n" + "ConfirmAbandonHomeNegativeThoughts_Everyone".Translate(), "ConfirmAbandonHomeNegativeThoughts"); + PawnDiedOrDownedThoughtsUtility.BuildMoodThoughtsListString(map.mapPawns.AllPawns, PawnDiedOrDownedThoughtsKind.Abandoned, stringBuilder, (string)null, "\n\n" + "ConfirmAbandonHomeNegativeThoughts_Everyone".Translate(), "ConfirmAbandonHomeNegativeThoughts"); if (stringBuilder.Length == 0) { SettlementAbandonUtility.Abandon(settlement); @@ -73,10 +70,10 @@ orderby x.IsColonist descending } else { - Find.WindowStack.Add(Dialog_MessageBox.CreateConfirmation(stringBuilder.ToString(), delegate + Find.WindowStack.Add(Dialog_MessageBox.CreateConfirmation(stringBuilder.ToString(), (Action)delegate() { SettlementAbandonUtility.Abandon(settlement); - }, false, null)); + }, false, (string)null)); } } } diff --git a/Assembly-CSharp/RimWorld.Planet/SettlementUtility.cs b/Assembly-CSharp/RimWorld.Planet/SettlementUtility.cs index 69bba4060..180de58fd 100644 --- a/Assembly-CSharp/RimWorld.Planet/SettlementUtility.cs +++ b/Assembly-CSharp/RimWorld.Planet/SettlementUtility.cs @@ -1,4 +1,3 @@ -using System; using System.Collections.Generic; using Verse; diff --git a/Assembly-CSharp/RimWorld.Planet/Settlement_TraderTracker.cs b/Assembly-CSharp/RimWorld.Planet/Settlement_TraderTracker.cs index 4e7265447..ea6560cda 100644 --- a/Assembly-CSharp/RimWorld.Planet/Settlement_TraderTracker.cs +++ b/Assembly-CSharp/RimWorld.Planet/Settlement_TraderTracker.cs @@ -1,6 +1,5 @@ using System; using System.Collections.Generic; -using System.Diagnostics; using Verse; namespace RimWorld.Planet @@ -66,11 +65,7 @@ public virtual string TraderName { return this.settlement.LabelCap; } - return "SettlementTrader".Translate(new object[] - { - this.settlement.LabelCap, - this.settlement.Faction.Name - }); + return "SettlementTrader".Translate(this.settlement.LabelCap, this.settlement.Faction.Name); } } @@ -78,7 +73,7 @@ public virtual bool CanTradeNow { get { - return this.TraderKind != null && (this.stock == null || this.stock.InnerListForReading.Any((Thing x) => this.TraderKind.WillTrade(x.def))); + return this.TraderKind != null && (this.stock == null || this.stock.InnerListForReading.Any((Predicate)((Thing x) => this.TraderKind.WillTrade(x.def)))); } } @@ -102,9 +97,9 @@ public virtual void ExposeData() this.tmpSavedPawns.Clear(); if (this.stock != null) { - for (int i = this.stock.Count - 1; i >= 0; i--) + for (int num = this.stock.Count - 1; num >= 0; num--) { - Pawn pawn = this.stock[i] as Pawn; + Pawn pawn = this.stock[num] as Pawn; if (pawn != null) { this.stock.Remove(pawn); @@ -116,25 +111,39 @@ public virtual void ExposeData() Scribe_Collections.Look(ref this.tmpSavedPawns, "tmpSavedPawns", LookMode.Reference, new object[0]); Scribe_Deep.Look>(ref this.stock, "stock", new object[0]); Scribe_Values.Look(ref this.lastStockGenerationTicks, "lastStockGenerationTicks", 0, false); - if (Scribe.mode == LoadSaveMode.PostLoadInit || Scribe.mode == LoadSaveMode.Saving) + if (Scribe.mode != LoadSaveMode.PostLoadInit && Scribe.mode != LoadSaveMode.Saving) + return; + for (int i = 0; i < this.tmpSavedPawns.Count; i++) { - for (int j = 0; j < this.tmpSavedPawns.Count; j++) - { - this.stock.TryAdd(this.tmpSavedPawns[j], false); - } - this.tmpSavedPawns.Clear(); + this.stock.TryAdd(this.tmpSavedPawns[i], false); } + this.tmpSavedPawns.Clear(); } - [DebuggerHidden] public virtual IEnumerable ColonyThingsWillingToBuy(Pawn playerNegotiator) { - Settlement_TraderTracker.c__Iterator108 c__Iterator = new Settlement_TraderTracker.c__Iterator108(); - c__Iterator.playerNegotiator = playerNegotiator; - c__Iterator.<$>playerNegotiator = playerNegotiator; - Settlement_TraderTracker.c__Iterator108 expr_15 = c__Iterator; - expr_15.$PC = -2; - return expr_15; + Caravan caravan = playerNegotiator.GetCaravan(); + List.Enumerator enumerator = CaravanInventoryUtility.AllInventoryItems(caravan).GetEnumerator(); + try + { + while (enumerator.MoveNext()) + { + Thing item = enumerator.Current; + yield return item; + } + } + finally + { + ((IDisposable)(object)enumerator).Dispose(); + } + List pawns = caravan.PawnsListForReading; + for (int i = 0; i < pawns.Count; i++) + { + if (!caravan.IsOwner(pawns[i])) + { + yield return (Thing)pawns[i]; + } + } } public virtual void GiveSoldThingToTrader(Thing toGive, int countToGive, Pawn playerNegotiator) @@ -149,9 +158,8 @@ public virtual void GiveSoldThingToTrader(Thing toGive, int countToGive, Pawn pl if (pawn.RaceProps.Humanlike) { Find.WorldPawns.DiscardIfUnimportant(pawn); - return; } - if (!this.stock.TryAdd(pawn, false)) + else if (!this.stock.TryAdd(pawn, false)) { pawn.Destroy(DestroyMode.Vanish); } @@ -198,18 +206,18 @@ public virtual void TraderTrackerTick() } else { - for (int i = this.stock.Count - 1; i >= 0; i--) + for (int num = this.stock.Count - 1; num >= 0; num--) { - Pawn pawn = this.stock[i] as Pawn; + Pawn pawn = this.stock[num] as Pawn; if (pawn != null && pawn.Destroyed) { this.stock.Remove(pawn); Find.WorldPawns.DiscardIfUnimportant(pawn); } } - for (int j = this.stock.Count - 1; j >= 0; j--) + for (int num2 = this.stock.Count - 1; num2 >= 0; num2--) { - Pawn pawn2 = this.stock[j] as Pawn; + Pawn pawn2 = this.stock[num2] as Pawn; if (pawn2 != null && !pawn2.IsWorldPawn()) { Log.Error("Faction base has non-world-pawns in its stock. Removing..."); @@ -224,9 +232,9 @@ public void TryDestroyStock() { if (this.stock != null) { - for (int i = this.stock.Count - 1; i >= 0; i--) + for (int num = this.stock.Count - 1; num >= 0; num--) { - Thing thing = this.stock[i]; + Thing thing = this.stock[num]; this.stock.Remove(thing); Pawn pawn = thing as Pawn; if (pawn != null) @@ -244,7 +252,11 @@ public void TryDestroyStock() public bool ContainsPawn(Pawn p) { - return this.stock != null && this.stock.Contains(p); + if (this.stock != null) + { + return this.stock.Contains(p); + } + return false; } protected virtual void RegenerateStock() @@ -253,10 +265,12 @@ protected virtual void RegenerateStock() this.stock = new ThingOwner(this); if (this.settlement.Faction == null || !this.settlement.Faction.IsPlayer) { - ItemCollectionGeneratorParams parms = default(ItemCollectionGeneratorParams); - parms.traderDef = this.TraderKind; - parms.forTile = this.settlement.Tile; - parms.forFaction = this.settlement.Faction; + ItemCollectionGeneratorParams parms = new ItemCollectionGeneratorParams + { + traderDef = this.TraderKind, + forTile = this.settlement.Tile, + forFaction = this.settlement.Faction + }; this.stock.TryAddRange(ItemCollectionGeneratorDefOf.TraderStock.Worker.Generate(parms), true); } for (int i = 0; i < this.stock.Count; i++) diff --git a/Assembly-CSharp/RimWorld.Planet/Site.cs b/Assembly-CSharp/RimWorld.Planet/Site.cs index 5f979c59c..449948569 100644 --- a/Assembly-CSharp/RimWorld.Planet/Site.cs +++ b/Assembly-CSharp/RimWorld.Planet/Site.cs @@ -1,6 +1,5 @@ using System; using System.Collections.Generic; -using System.Diagnostics; using System.Linq; using System.Text; using UnityEngine; @@ -32,7 +31,7 @@ public override string Label { return this.customLabel; } - if (this.core == SiteCoreDefOf.Nothing && this.parts.Any()) + if (this.core == SiteCoreDefOf.Nothing && this.parts.Any()) { return this.parts[0].label; } @@ -82,17 +81,9 @@ public override Material Material { get { - if (this.cachedMat == null) + if ((UnityEngine.Object)this.cachedMat == (UnityEngine.Object)null) { - Color color; - if (this.LeadingSiteDef.applyFactionColorToSiteTexture && base.Faction != null) - { - color = base.Faction.Color; - } - else - { - color = Color.white; - } + Color color = (!this.LeadingSiteDef.applyFactionColorToSiteTexture || base.Faction == null) ? Color.white : base.Faction.Color; this.cachedMat = MaterialPool.MatFrom(this.LeadingSiteDef.siteTexture, ShaderDatabase.WorldOverlayTransparentLit, color, WorldMaterials.WorldObjectRenderQueue); } return this.cachedMat; @@ -111,7 +102,7 @@ private SiteDefBase LeadingSiteDef { get { - if (this.core == SiteCoreDefOf.Nothing && this.parts.Any()) + if (this.core == SiteCoreDefOf.Nothing && this.parts.Any()) { return this.parts[0]; } @@ -123,18 +114,30 @@ public override IEnumerable ExtraGenStepDefs { get { - Site.<>c__Iterator10A <>c__Iterator10A = new Site.<>c__Iterator10A(); - <>c__Iterator10A.<>f__this = this; - Site.<>c__Iterator10A expr_0E = <>c__Iterator10A; - expr_0E.$PC = -2; - return expr_0E; + foreach (GenStepDef extraGenStepDef in base.ExtraGenStepDefs) + { + yield return extraGenStepDef; + } + List coreGenStepDefs = this.core.ExtraGenSteps; + for (int k = 0; k < coreGenStepDefs.Count; k++) + { + yield return coreGenStepDefs[k]; + } + for (int j = 0; j < this.parts.Count; j++) + { + List partGenStepDefs = this.parts[j].ExtraGenSteps; + for (int i = 0; i < partGenStepDefs.Count; i++) + { + yield return partGenStepDefs[i]; + } + } } } public override void ExposeData() { base.ExposeData(); - Scribe_Values.Look(ref this.customLabel, "customLabel", null, false); + Scribe_Values.Look(ref this.customLabel, "customLabel", (string)null, false); Scribe_Defs.Look(ref this.core, "core"); Scribe_Collections.Look(ref this.parts, "parts", LookMode.Def, new object[0]); Scribe_Values.Look(ref this.startedCountdown, "startedCountdown", false, false); @@ -174,49 +177,40 @@ public override bool ShouldRemoveMapNow(out bool alsoRemoveWorldObject) return !base.Map.mapPawns.AnyPawnBlockingMapRemoval; } - [DebuggerHidden] public override IEnumerable GetFloatMenuOptions(Caravan caravan) { - Site.c__Iterator10B c__Iterator10B = new Site.c__Iterator10B(); - c__Iterator10B.caravan = caravan; - c__Iterator10B.<$>caravan = caravan; - c__Iterator10B.<>f__this = this; - Site.c__Iterator10B expr_1C = c__Iterator10B; - expr_1C.$PC = -2; - return expr_1C; + foreach (FloatMenuOption floatMenuOption in base.GetFloatMenuOptions(caravan)) + { + yield return floatMenuOption; + } + foreach (FloatMenuOption floatMenuOption2 in this.core.Worker.GetFloatMenuOptions(caravan, this)) + { + yield return floatMenuOption2; + } } - [DebuggerHidden] public override IEnumerable GetGizmos() { - Site.c__Iterator10C c__Iterator10C = new Site.c__Iterator10C(); - c__Iterator10C.<>f__this = this; - Site.c__Iterator10C expr_0E = c__Iterator10C; - expr_0E.$PC = -2; - return expr_0E; + foreach (Gizmo gizmo in base.GetGizmos()) + { + yield return gizmo; + } + if (base.HasMap && Find.WorldSelector.SingleSelectedObject == this) + { + yield return (Gizmo)SettleInExistingMapUtility.SettleCommand(base.Map, true); + } } private void CheckStartForceExitAndRemoveMapCountdown() { - if (this.startedCountdown) - { - return; - } - if (GenHostility.AnyHostileActiveThreat(base.Map)) + if (!this.startedCountdown && !GenHostility.AnyHostileActiveThreat(base.Map)) { - return; + this.startedCountdown = true; + int num = Mathf.RoundToInt((float)(this.core.forceExitAndRemoveMapCountdownDurationDays * 60000.0)); + string text = (!this.anyEnemiesInitially) ? "MessageSiteCountdownBecauseNoEnemiesInitially".Translate(MapParent.GetForceExitAndRemoveMapCountdownTimeLeftString(num)) : "MessageSiteCountdownBecauseNoMoreEnemies".Translate(MapParent.GetForceExitAndRemoveMapCountdownTimeLeftString(num)); + Messages.Message(text, (WorldObject)this, MessageSound.Benefit); + base.StartForceExitAndRemoveMapCountdown(num); } - this.startedCountdown = true; - int num = Mathf.RoundToInt(this.core.forceExitAndRemoveMapCountdownDurationDays * 60000f); - string text = (!this.anyEnemiesInitially) ? "MessageSiteCountdownBecauseNoEnemiesInitially".Translate(new object[] - { - MapParent.GetForceExitAndRemoveMapCountdownTimeLeftString(num) - }) : "MessageSiteCountdownBecauseNoMoreEnemies".Translate(new object[] - { - MapParent.GetForceExitAndRemoveMapCountdownTimeLeftString(num) - }); - Messages.Message(text, this, MessageSound.Benefit); - base.StartForceExitAndRemoveMapCountdown(num); } public override string GetInspectString() @@ -235,19 +229,12 @@ public override string GetInspectString() } else if (this.parts.Count == 1) { - stringBuilder.Append("KnownSiteThreat".Translate(new object[] - { - this.parts[0].LabelCap - })); + stringBuilder.Append("KnownSiteThreat".Translate(this.parts[0].LabelCap)); } else { - StringBuilder arg_D9_0 = stringBuilder; - string arg_D4_0 = "KnownSiteThreats"; - object[] expr_A3 = new object[1]; - expr_A3[0] = GenText.ToCommaList(from x in this.parts - select x.LabelCap, true); - arg_D9_0.Append(arg_D4_0.Translate(expr_A3)); + stringBuilder.Append("KnownSiteThreats".Translate(GenText.ToCommaList(from x in this.parts + select x.LabelCap, true))); } } return stringBuilder.ToString(); diff --git a/Assembly-CSharp/RimWorld.Planet/SiteMaker.cs b/Assembly-CSharp/RimWorld.Planet/SiteMaker.cs index 87adc56b3..1331c6f64 100644 --- a/Assembly-CSharp/RimWorld.Planet/SiteMaker.cs +++ b/Assembly-CSharp/RimWorld.Planet/SiteMaker.cs @@ -14,21 +14,21 @@ public static Site TryMakeRandomSite(SiteCoreDef core, IEnumerable SitePartDef sitePartDef = null; if (possibleSiteParts != null) { - SiteMaker.TryFindNewRandomSitePartFor(core, null, possibleSiteParts, faction, out sitePartDef, disallowAlliedFactions, extraFactionValidator); + SiteMaker.TryFindNewRandomSitePartFor(core, (IEnumerable)null, possibleSiteParts, faction, out sitePartDef, disallowAlliedFactions, extraFactionValidator); } if (faction == null) { - IEnumerable arg_31_0; + object obj; if (sitePartDef != null) { - IEnumerable enumerable = Gen.YieldSingle(sitePartDef); - arg_31_0 = enumerable; + IEnumerable enumerable = Gen.YieldSingle(sitePartDef); + obj = enumerable; } else { - arg_31_0 = null; + obj = null; } - IEnumerable parts = arg_31_0; + IEnumerable parts = (IEnumerable)obj; if (!SiteMaker.TryFindRandomFactionFor(core, parts, out faction, disallowAlliedFactions, extraFactionValidator)) { return null; @@ -46,7 +46,7 @@ public static Site TryMakeRandomSite(SiteCoreDef core, IEnumerable public static Site TryMakeSite(SiteCoreDef core, IEnumerable parts, bool disallowAlliedFactions = true, Predicate extraFactionValidator = null) { - Faction faction; + Faction faction = default(Faction); if (!SiteMaker.TryFindRandomFactionFor(core, parts, out faction, disallowAlliedFactions, extraFactionValidator)) { return null; @@ -67,7 +67,7 @@ public static bool TryFindNewRandomSitePartFor(SiteCoreDef core, IEnumerable(out sitePart)) { return true; } @@ -78,8 +78,8 @@ public static bool TryFindNewRandomSitePartFor(SiteCoreDef core, IEnumerable SiteMaker.FactionCanOwn(core, existingSiteParts, fac, disallowAlliedFactions, extraFactionValidator) && SiteMaker.FactionCanOwn(x, fac, disallowAlliedFactions, extraFactionValidator)) - select x).TryRandomElement(out sitePart)) + where x == null || SiteMaker.possibleFactions.Any((Predicate)((Faction fac) => SiteMaker.FactionCanOwn(core, existingSiteParts, fac, disallowAlliedFactions, extraFactionValidator) && SiteMaker.FactionCanOwn(x, fac, disallowAlliedFactions, extraFactionValidator))) + select x).TryRandomElement(out sitePart)) { SiteMaker.possibleFactions.Clear(); return true; @@ -99,7 +99,7 @@ public static bool TryFindRandomFactionFor(SiteCoreDef core, IEnumerable(out faction)) { return true; } @@ -115,14 +115,13 @@ public static bool FactionCanOwn(SiteCoreDef core, IEnumerable part } if (parts != null) { - foreach (SitePartDef current in parts) + foreach (SitePartDef item in parts) { - if (!SiteMaker.FactionCanOwn(current, faction, disallowAlliedFactions, extraFactionValidator)) + if (!SiteMaker.FactionCanOwn(item, faction, disallowAlliedFactions, extraFactionValidator)) { return false; } } - return true; } return true; } @@ -134,7 +133,19 @@ private static bool FactionCanOwn(SiteDefBase siteDefBase, Faction faction, bool Log.Error("Called FactionCanOwn() with null SiteDefBase."); return false; } - return siteDefBase.FactionCanOwn(faction) && (!disallowAlliedFactions || faction == null || faction.HostileTo(Faction.OfPlayer)) && (extraFactionValidator == null || extraFactionValidator(faction)); + if (!siteDefBase.FactionCanOwn(faction)) + { + return false; + } + if (disallowAlliedFactions && faction != null && !faction.HostileTo(Faction.OfPlayer)) + { + return false; + } + if ((object)extraFactionValidator != null && !extraFactionValidator(faction)) + { + return false; + } + return true; } } } diff --git a/Assembly-CSharp/RimWorld.Planet/SphereGenerator.cs b/Assembly-CSharp/RimWorld.Planet/SphereGenerator.cs index b3c1156a9..afb728d9d 100644 --- a/Assembly-CSharp/RimWorld.Planet/SphereGenerator.cs +++ b/Assembly-CSharp/RimWorld.Planet/SphereGenerator.cs @@ -17,14 +17,14 @@ public static void Generate(int subdivisionsCount, float radius, Vector3 viewCen SphereGenerator.middlePointsCache.Clear(); outVerts = new List(); IcosahedronGenerator.GenerateIcosahedron(outVerts, SphereGenerator.tris, radius, viewCenter, viewAngle); - for (int i = 0; i < subdivisionsCount; i++) + for (int num = 0; num < subdivisionsCount; num++) { SphereGenerator.newTris.Clear(); - int j = 0; + int num2 = 0; int count = SphereGenerator.tris.Count; - while (j < count) + while (num2 < count) { - TriangleIndices triangleIndices = SphereGenerator.tris[j]; + TriangleIndices triangleIndices = SphereGenerator.tris[num2]; int middlePoint = SphereGenerator.GetMiddlePoint(triangleIndices.v1, triangleIndices.v2, outVerts, radius); int middlePoint2 = SphereGenerator.GetMiddlePoint(triangleIndices.v2, triangleIndices.v3, outVerts, radius); int middlePoint3 = SphereGenerator.GetMiddlePoint(triangleIndices.v3, triangleIndices.v1, outVerts, radius); @@ -32,29 +32,29 @@ public static void Generate(int subdivisionsCount, float radius, Vector3 viewCen SphereGenerator.newTris.Add(new TriangleIndices(triangleIndices.v2, middlePoint2, middlePoint)); SphereGenerator.newTris.Add(new TriangleIndices(triangleIndices.v3, middlePoint3, middlePoint2)); SphereGenerator.newTris.Add(new TriangleIndices(middlePoint, middlePoint2, middlePoint3)); - j++; + num2++; } SphereGenerator.tris.Clear(); SphereGenerator.tris.AddRange(SphereGenerator.newTris); } - MeshUtility.RemoveVertices(outVerts, SphereGenerator.tris, (Vector3 x) => !MeshUtility.Visible(x, radius, viewCenter, viewAngle)); + MeshUtility.RemoveVertices(outVerts, SphereGenerator.tris, (Predicate)((Vector3 x) => !MeshUtility.Visible(x, radius, viewCenter, viewAngle))); outIndices = new List(); - int k = 0; + int num3 = 0; int count2 = SphereGenerator.tris.Count; - while (k < count2) + while (num3 < count2) { - TriangleIndices triangleIndices2 = SphereGenerator.tris[k]; + TriangleIndices triangleIndices2 = SphereGenerator.tris[num3]; outIndices.Add(triangleIndices2.v1); outIndices.Add(triangleIndices2.v2); outIndices.Add(triangleIndices2.v3); - k++; + num3++; } } private static int GetMiddlePoint(int p1, int p2, List verts, float radius) { - long key = ((long)Mathf.Min(p1, p2) << 32) + (long)Mathf.Max(p1, p2); - int result; + long key = ((long)Mathf.Min(p1, p2) << 32) + Mathf.Max(p1, p2); + int result = default(int); if (SphereGenerator.middlePointsCache.TryGetValue(key, out result)) { return result; diff --git a/Assembly-CSharp/RimWorld.Planet/Tile.cs b/Assembly-CSharp/RimWorld.Planet/Tile.cs index 0b392fb73..1a735ae0b 100644 --- a/Assembly-CSharp/RimWorld.Planet/Tile.cs +++ b/Assembly-CSharp/RimWorld.Planet/Tile.cs @@ -1,4 +1,3 @@ -using System; using System.Collections.Generic; namespace RimWorld.Planet @@ -31,19 +30,19 @@ public struct RiverLink public float rainfall; - public List roads; + public List roads; - public List rivers; + public List rivers; public bool WaterCovered { get { - return this.elevation <= 0f; + return this.elevation <= 0.0; } } - public List VisibleRoads + public List VisibleRoads { get { @@ -51,7 +50,7 @@ public List VisibleRoads } } - public List VisibleRivers + public List VisibleRivers { get { @@ -61,24 +60,7 @@ public List VisibleRivers public override string ToString() { - return string.Concat(new object[] - { - "(", - this.biome, - " elev=", - this.elevation, - "m hill=", - this.hilliness, - " temp=", - this.temperature, - "°C rain=", - this.rainfall, - "mm roads=", - (this.roads != null) ? this.roads.Count : 0, - " rivers=", - (this.rivers != null) ? this.rivers.Count : 0, - ")" - }); + return "(" + this.biome + " elev=" + this.elevation + "m hill=" + this.hilliness + " temp=" + this.temperature + "°C rain=" + this.rainfall + "mm roads=" + ((this.roads != null) ? this.roads.Count : 0) + " rivers=" + ((this.rivers != null) ? this.rivers.Count : 0) + ")"; } } } diff --git a/Assembly-CSharp/RimWorld.Planet/TileFinder.cs b/Assembly-CSharp/RimWorld.Planet/TileFinder.cs index 258fd7d8d..efeff0a4f 100644 --- a/Assembly-CSharp/RimWorld.Planet/TileFinder.cs +++ b/Assembly-CSharp/RimWorld.Planet/TileFinder.cs @@ -19,26 +19,23 @@ public static int RandomFactionBaseTileFor(Faction faction, bool mustBeAutoChoos { for (int i = 0; i < 500; i++) { - int num; + int num = default(int); if ((from _ in Enumerable.Range(0, 100) - select Rand.Range(0, Find.WorldGrid.TilesCount)).TryRandomElementByWeight(delegate(int x) + select Rand.Range(0, Find.WorldGrid.TilesCount)).TryRandomElementByWeight((Func)delegate(int x) { Tile tile = Find.WorldGrid[x]; - if (!tile.biome.canBuildBase || !tile.biome.implemented || tile.hilliness == Hilliness.Impassable) + if (tile.biome.canBuildBase && tile.biome.implemented && tile.hilliness != Hilliness.Impassable) { - return 0f; - } - if (mustBeAutoChoosable && !tile.biome.canAutoChoose) - { - return 0f; + if (mustBeAutoChoosable && !tile.biome.canAutoChoose) + { + return 0f; + } + return tile.biome.factionBaseSelectionWeight; } - return tile.biome.factionBaseSelectionWeight; - }, out num)) + return 0f; + }, out num) && TileFinder.IsValidTileForNewSettlement(num, null)) { - if (TileFinder.IsValidTileForNewSettlement(num, null)) - { - return num; - } + return num; } } Log.Error("Failed to find faction base tile for " + faction); @@ -52,10 +49,7 @@ public static bool IsValidTileForNewSettlement(int tile, StringBuilder reason = { if (reason != null) { - reason.Append("CannotLandBiome".Translate(new object[] - { - tile2.biome.label - })); + reason.Append("CannotLandBiome".Translate(tile2.biome.label)); } return false; } @@ -90,10 +84,7 @@ public static bool IsValidTileForNewSettlement(int tile, StringBuilder reason = } else { - reason.Append("BaseAlreadyThere".Translate(new object[] - { - settlement.Faction.Name - })); + reason.Append("BaseAlreadyThere".Translate(settlement.Faction.Name)); } } return false; @@ -106,34 +97,34 @@ public static bool IsValidTileForNewSettlement(int tile, StringBuilder reason = } return false; } - if (Find.WorldObjects.AnyMapParentAt(tile) || Current.Game.FindMap(tile) != null) + if (!Find.WorldObjects.AnyMapParentAt(tile) && Current.Game.FindMap(tile) == null) { - if (reason != null) - { - reason.Append("TileOccupied".Translate()); - } - return false; + return true; } - return true; + if (reason != null) + { + reason.Append("TileOccupied".Translate()); + } + return false; } public static bool TryFindPassableTileWithTraversalDistance(int rootTile, int minDist, int maxDist, out int result, Predicate validator = null, bool ignoreFirstTilePassability = false) { TileFinder.tmpTiles.Clear(); - Find.WorldFloodFiller.FloodFill(rootTile, (int x) => !Find.World.Impassable(x) || (x == rootTile && ignoreFirstTilePassability), delegate(int tile, int traversalDistance) + Find.WorldFloodFiller.FloodFill(rootTile, (Predicate)((int x) => !Find.World.Impassable(x) || (x == rootTile && ignoreFirstTilePassability)), (Func)delegate(int tile, int traversalDistance) { if (traversalDistance > maxDist) { return true; } - if (traversalDistance >= minDist && (validator == null || validator(tile))) + if (traversalDistance >= minDist && ((object)validator == null || validator(tile))) { TileFinder.tmpTiles.Add(new Pair(tile, traversalDistance)); } return false; }, 2147483647); - Pair pair; - if (TileFinder.tmpTiles.TryRandomElementByWeight((Pair x) => 1f - (float)(x.Second - minDist) / ((float)(maxDist - minDist) + 0.01f), out pair)) + Pair pair = default(Pair); + if (((IEnumerable>)TileFinder.tmpTiles).TryRandomElementByWeight>((Func, float>)((Pair x) => (float)(1.0 - (float)(x.Second - minDist) / (float)((float)(maxDist - minDist) + 0.0099999997764825821))), out pair)) { result = pair.First; return true; @@ -144,25 +135,25 @@ public static bool TryFindPassableTileWithTraversalDistance(int rootTile, int mi public static bool TryFindRandomPlayerTile(out int tile) { - Map map; + Map map = default(Map); if ((from x in Find.Maps where x.IsPlayerHome && x.mapPawns.FreeColonistsSpawnedCount != 0 - select x).TryRandomElement(out map)) + select x).TryRandomElement(out map)) { tile = map.Tile; return true; } if ((from x in Find.Maps where x.IsPlayerHome - select x).TryRandomElement(out map)) + select x).TryRandomElement(out map)) { tile = map.Tile; return true; } - Caravan caravan; + Caravan caravan = default(Caravan); if ((from x in Find.WorldObjects.Caravans where x.IsPlayerControlled - select x).TryRandomElement(out caravan)) + select x).TryRandomElement(out caravan)) { tile = caravan.Tile; return true; @@ -173,13 +164,13 @@ where x.IsPlayerControlled public static bool TryFindNewSiteTile(out int tile) { - int rootTile; + int rootTile = default(int); if (!TileFinder.TryFindRandomPlayerTile(out rootTile)) { tile = -1; return false; } - return TileFinder.TryFindPassableTileWithTraversalDistance(rootTile, 8, 30, out tile, (int x) => !Find.WorldObjects.AnyWorldObjectAt(x) && TileFinder.IsValidTileForNewSettlement(x, null), false); + return TileFinder.TryFindPassableTileWithTraversalDistance(rootTile, 8, 30, out tile, (Predicate)((int x) => !Find.WorldObjects.AnyWorldObjectAt(x) && TileFinder.IsValidTileForNewSettlement(x, null)), false); } } } diff --git a/Assembly-CSharp/RimWorld.Planet/TileTemperaturesComp.cs b/Assembly-CSharp/RimWorld.Planet/TileTemperaturesComp.cs index b66a9693f..b28801ac4 100644 --- a/Assembly-CSharp/RimWorld.Planet/TileTemperaturesComp.cs +++ b/Assembly-CSharp/RimWorld.Planet/TileTemperaturesComp.cs @@ -1,4 +1,3 @@ -using System; using System.Collections.Generic; using Verse; using Verse.Noise; @@ -31,7 +30,7 @@ public CachedTileTemperatureData(int tile) this.twelfthlyTempAverages = new float[12]; for (int i = 0; i < 12; i++) { - this.twelfthlyTempAverages[i] = GenTemperature.AverageTemperatureAtTileForTwelfth(tile, (Twelfth)i); + this.twelfthlyTempAverages[i] = GenTemperature.AverageTemperatureAtTileForTwelfth(tile, (Twelfth)(byte)i); } this.CheckCache(); } @@ -53,12 +52,12 @@ public float OutdoorTemperatureAt(int absTick) public float OffsetFromDailyRandomVariation(int absTick) { - return (float)this.dailyVariationPerlinCached.GetValue((double)absTick, 0.0, 0.0) * 7f; + return (float)((float)this.dailyVariationPerlinCached.GetValue((double)absTick, 0.0, 0.0) * 7.0); } public float AverageTemperatureForTwelfth(Twelfth twelfth) { - return this.twelfthlyTempAverages[(int)twelfth]; + return this.twelfthlyTempAverages[(uint)twelfth]; } public void CheckCache() @@ -92,7 +91,7 @@ private float CalculateOutdoorTemperatureAtTile(int absTick, bool includeDailyVa } } - private TileTemperaturesComp.CachedTileTemperatureData[] cache; + private CachedTileTemperatureData[] cache; private List usedSlots; @@ -107,7 +106,7 @@ public override void WorldComponentTick() { this.cache[this.usedSlots[i]].CheckCache(); } - if (Find.TickManager.TicksGame % 300 == 84 && this.usedSlots.Any()) + if (Find.TickManager.TicksGame % 300 == 84 && this.usedSlots.Any()) { this.cache[this.usedSlots[0]] = null; this.usedSlots.RemoveAt(0); @@ -158,17 +157,17 @@ public bool SeasonAndOutdoorTemperatureAcceptableFor(int tile, ThingDef animalRa public void ClearCaches() { - this.cache = new TileTemperaturesComp.CachedTileTemperatureData[Find.WorldGrid.TilesCount]; + this.cache = new CachedTileTemperatureData[Find.WorldGrid.TilesCount]; this.usedSlots = new List(); } - private TileTemperaturesComp.CachedTileTemperatureData RetrieveCachedData(int tile) + private CachedTileTemperatureData RetrieveCachedData(int tile) { if (this.cache[tile] != null) { return this.cache[tile]; } - this.cache[tile] = new TileTemperaturesComp.CachedTileTemperatureData(tile); + this.cache[tile] = new CachedTileTemperatureData(tile); this.usedSlots.Add(tile); return this.cache[tile]; } diff --git a/Assembly-CSharp/RimWorld.Planet/TimeoutComp.cs b/Assembly-CSharp/RimWorld.Planet/TimeoutComp.cs index a6c1af7a6..3fc541d7c 100644 --- a/Assembly-CSharp/RimWorld.Planet/TimeoutComp.cs +++ b/Assembly-CSharp/RimWorld.Planet/TimeoutComp.cs @@ -1,4 +1,3 @@ -using System; using Verse; namespace RimWorld.Planet @@ -35,7 +34,7 @@ public int TicksLeft { get { - return (!this.Active) ? 0 : (this.timeoutEndTick - Find.TickManager.TicksGame); + return this.Active ? (this.timeoutEndTick - Find.TickManager.TicksGame) : 0; } } @@ -43,7 +42,7 @@ private bool ParentHasMap { get { - MapParent mapParent = this.parent as MapParent; + MapParent mapParent = base.parent as MapParent; return mapParent != null && mapParent.HasMap; } } @@ -58,7 +57,7 @@ public override void CompTick() base.CompTick(); if (this.ShouldRemoveWorldObjectNow) { - Find.WorldObjects.Remove(this.parent); + Find.WorldObjects.Remove(base.parent); } } @@ -72,12 +71,9 @@ public override string CompInspectStringExtra() { if (this.Active && !this.ParentHasMap) { - return "WorldObjectTimeout".Translate(new object[] - { - this.TicksLeft.ToStringTicksToPeriod(false, false, false) - }); + return "WorldObjectTimeout".Translate(this.TicksLeft.ToStringTicksToPeriod(false, false, false)); } - return null; + return (string)null; } } } diff --git a/Assembly-CSharp/RimWorld.Planet/TravelingTransportPods.cs b/Assembly-CSharp/RimWorld.Planet/TravelingTransportPods.cs index a6a172cef..12684afaf 100644 --- a/Assembly-CSharp/RimWorld.Planet/TravelingTransportPods.cs +++ b/Assembly-CSharp/RimWorld.Planet/TravelingTransportPods.cs @@ -64,11 +64,11 @@ private float TraveledPctStepPerTick return 1f; } float num = GenMath.SphericalDistance(start.normalized, end.normalized); - if (num == 0f) + if (num == 0.0) { return 1f; } - return 0.00025f / num; + return (float)(0.00025000001187436283 / num); } } @@ -116,11 +116,18 @@ public IEnumerable Pawns { get { - TravelingTransportPods.<>c__Iterator10D <>c__Iterator10D = new TravelingTransportPods.<>c__Iterator10D(); - <>c__Iterator10D.<>f__this = this; - TravelingTransportPods.<>c__Iterator10D expr_0E = <>c__Iterator10D; - expr_0E.$PC = -2; - return expr_0E; + for (int j = 0; j < this.pods.Count; j++) + { + ThingOwner things = this.pods[j].innerContainer; + for (int i = 0; i < things.Count; i++) + { + Pawn p = things[i] as Pawn; + if (p != null) + { + yield return p; + } + } + } } } @@ -154,7 +161,7 @@ public override void Tick() { base.Tick(); this.traveledPct += this.TraveledPctStepPerTick; - if (this.traveledPct >= 1f) + if (this.traveledPct >= 1.0) { this.traveledPct = 1f; this.Arrived(); @@ -202,58 +209,54 @@ public bool ContainsPawn(Pawn p) private void Arrived() { - if (this.arrived) - { - return; - } - this.arrived = true; - Map map = Current.Game.FindMap(this.destinationTile); - if (map != null) + if (!this.arrived) { - this.SpawnDropPodsInMap(map, null); - } - else if (!this.PodsHaveAnyPotentialCaravanOwner) - { - Caravan caravan = Find.WorldObjects.PlayerControlledCaravanAt(this.destinationTile); - if (caravan != null) + this.arrived = true; + Map map = Current.Game.FindMap(this.destinationTile); + if (map != null) { - this.GivePodContentsToCaravan(caravan); + this.SpawnDropPodsInMap(map, (string)null); } - else + else if (!this.PodsHaveAnyPotentialCaravanOwner) { - for (int i = 0; i < this.pods.Count; i++) + Caravan caravan = Find.WorldObjects.PlayerControlledCaravanAt(this.destinationTile); + if (caravan != null) { - this.pods[i].innerContainer.ClearAndDestroyContentsOrPassToWorld(DestroyMode.Vanish); + this.GivePodContentsToCaravan(caravan); } - this.RemoveAllPods(); - Find.WorldObjects.Remove(this); - Messages.Message("MessageTransportPodsArrivedAndLost".Translate(), new GlobalTargetInfo(this.destinationTile), MessageSound.Negative); - } - } - else - { - MapParent mapParent = Find.WorldObjects.MapParentAt(this.destinationTile); - if (mapParent != null && mapParent.TransportPodsCanLandAndGenerateMap && this.attackOnArrival) - { - LongEventHandler.QueueLongEvent(delegate + else { - Map orGenerateMap = GetOrGenerateMapUtility.GetOrGenerateMap(mapParent.Tile, null); - string extraMessagePart = null; - if (mapParent.Faction != null && !mapParent.Faction.HostileTo(Faction.OfPlayer)) + for (int i = 0; i < this.pods.Count; i++) { - mapParent.Faction.SetHostileTo(Faction.OfPlayer, true); - extraMessagePart = "MessageTransportPodsArrived_BecameHostile".Translate(new object[] - { - mapParent.Faction.Name - }).CapitalizeFirst(); + this.pods[i].innerContainer.ClearAndDestroyContentsOrPassToWorld(DestroyMode.Vanish); } - Find.TickManager.CurTimeSpeed = TimeSpeed.Paused; - this.SpawnDropPodsInMap(orGenerateMap, extraMessagePart); - }, "GeneratingMapForNewEncounter", false, null); + this.RemoveAllPods(); + Find.WorldObjects.Remove(this); + Messages.Message("MessageTransportPodsArrivedAndLost".Translate(), new GlobalTargetInfo(this.destinationTile), MessageSound.Negative); + } } else { - this.SpawnCaravanAtDestinationTile(); + MapParent mapParent = Find.WorldObjects.MapParentAt(this.destinationTile); + if (mapParent != null && mapParent.TransportPodsCanLandAndGenerateMap && this.attackOnArrival) + { + LongEventHandler.QueueLongEvent((Action)delegate + { + Map orGenerateMap = GetOrGenerateMapUtility.GetOrGenerateMap(mapParent.Tile, null); + string extraMessagePart = (string)null; + if (mapParent.Faction != null && !mapParent.Faction.HostileTo(Faction.OfPlayer)) + { + mapParent.Faction.SetHostileTo(Faction.OfPlayer, true); + extraMessagePart = "MessageTransportPodsArrived_BecameHostile".Translate(mapParent.Faction.Name).CapitalizeFirst(); + } + Find.TickManager.CurTimeSpeed = TimeSpeed.Paused; + this.SpawnDropPodsInMap(orGenerateMap, extraMessagePart); + }, "GeneratingMapForNewEncounter", false, null); + } + else + { + this.SpawnCaravanAtDestinationTile(); + } } } } @@ -261,7 +264,7 @@ private void Arrived() private void SpawnDropPodsInMap(Map map, string extraMessagePart = null) { this.RemoveAllPawnsFromWorldPawns(); - IntVec3 intVec; + IntVec3 intVec = default(IntVec3); if (this.destinationCell.IsValid && this.destinationCell.InBounds(map)) { intVec = this.destinationCell; @@ -275,7 +278,7 @@ private void SpawnDropPodsInMap(Map map, string extraMessagePart = null) } else { - if (this.arriveMode != PawnsArriveMode.EdgeDrop && this.arriveMode != PawnsArriveMode.Undecided) + if (((this.arriveMode != PawnsArriveMode.EdgeDrop) ? this.arriveMode : PawnsArriveMode.Undecided) != 0) { Log.Warning("Unsupported arrive mode " + this.arriveMode); } @@ -283,7 +286,7 @@ private void SpawnDropPodsInMap(Map map, string extraMessagePart = null) } for (int i = 0; i < this.pods.Count; i++) { - IntVec3 c; + IntVec3 c = default(IntVec3); DropCellFinder.TryFindDropSpotNear(intVec, map, out c, false, true); this.pods[i].parent = null; DropPodUtility.MakeDropPodAt(c, map, this.pods[i]); @@ -304,9 +307,9 @@ private void SpawnCaravanAtDestinationTile() for (int i = 0; i < this.pods.Count; i++) { ThingOwner innerContainer = this.pods[i].innerContainer; - for (int j = innerContainer.Count - 1; j >= 0; j--) + for (int num = innerContainer.Count - 1; num >= 0; num--) { - Pawn pawn = innerContainer[j] as Pawn; + Pawn pawn = innerContainer[num] as Pawn; if (pawn != null) { TravelingTransportPods.tmpPawns.Add(pawn); @@ -314,28 +317,28 @@ private void SpawnCaravanAtDestinationTile() } } } - int startingTile; + int startingTile = default(int); if (!GenWorldClosest.TryFindClosestPassableTile(this.destinationTile, out startingTile)) { startingTile = this.destinationTile; } Caravan o = CaravanMaker.MakeCaravan(TravelingTransportPods.tmpPawns, base.Faction, startingTile, true); - for (int k = 0; k < this.pods.Count; k++) + for (int j = 0; j < this.pods.Count; j++) { TravelingTransportPods.tmpContainedThings.Clear(); - TravelingTransportPods.tmpContainedThings.AddRange(this.pods[k].innerContainer); - for (int l = 0; l < TravelingTransportPods.tmpContainedThings.Count; l++) + TravelingTransportPods.tmpContainedThings.AddRange(this.pods[j].innerContainer); + for (int k = 0; k < TravelingTransportPods.tmpContainedThings.Count; k++) { - this.pods[k].innerContainer.Remove(TravelingTransportPods.tmpContainedThings[l]); - Pawn pawn2 = CaravanInventoryUtility.FindPawnToMoveInventoryTo(TravelingTransportPods.tmpContainedThings[l], TravelingTransportPods.tmpPawns, null, null); + this.pods[j].innerContainer.Remove(TravelingTransportPods.tmpContainedThings[k]); + Pawn pawn2 = CaravanInventoryUtility.FindPawnToMoveInventoryTo(TravelingTransportPods.tmpContainedThings[k], TravelingTransportPods.tmpPawns, null, null); bool flag = false; if (pawn2 != null) { - flag = pawn2.inventory.innerContainer.TryAdd(TravelingTransportPods.tmpContainedThings[l], true); + flag = pawn2.inventory.innerContainer.TryAdd(TravelingTransportPods.tmpContainedThings[k], true); } if (!flag) { - TravelingTransportPods.tmpContainedThings[l].Destroy(DestroyMode.Vanish); + TravelingTransportPods.tmpContainedThings[k].Destroy(DestroyMode.Vanish); } } } @@ -343,7 +346,7 @@ private void SpawnCaravanAtDestinationTile() Find.WorldObjects.Remove(this); TravelingTransportPods.tmpPawns.Clear(); TravelingTransportPods.tmpContainedThings.Clear(); - Messages.Message("MessageTransportPodsArrived".Translate(), o, MessageSound.Benefit); + Messages.Message("MessageTransportPodsArrived".Translate(), (WorldObject)o, MessageSound.Benefit); } private void GivePodContentsToCaravan(Caravan caravan) @@ -378,7 +381,7 @@ private void GivePodContentsToCaravan(Caravan caravan) this.RemoveAllPods(); Find.WorldObjects.Remove(this); TravelingTransportPods.tmpContainedThings.Clear(); - Messages.Message("MessageTransportPodsArrivedAndAddedToCaravan".Translate(), caravan, MessageSound.Benefit); + Messages.Message("MessageTransportPodsArrivedAndAddedToCaravan".Translate(), (WorldObject)caravan, MessageSound.Benefit); } private void RemoveAllPawnsFromWorldPawns() @@ -425,5 +428,11 @@ virtual IThingHolder get_ParentHolder() { return base.ParentHolder; } + + IThingHolder IThingHolder.get_ParentHolder() + { + //ILSpy generated this explicit interface implementation from .override directive in get_ParentHolder + return this.get_ParentHolder(); + } } } diff --git a/Assembly-CSharp/RimWorld.Planet/TriangleIndices.cs b/Assembly-CSharp/RimWorld.Planet/TriangleIndices.cs index 0be9cc9f2..94c683bd9 100644 --- a/Assembly-CSharp/RimWorld.Planet/TriangleIndices.cs +++ b/Assembly-CSharp/RimWorld.Planet/TriangleIndices.cs @@ -1,5 +1,3 @@ -using System; - namespace RimWorld.Planet { public struct TriangleIndices @@ -19,7 +17,21 @@ public TriangleIndices(int v1, int v2, int v3) public bool SharesAnyVertexWith(TriangleIndices t, int otherThan) { - return (this.v1 != otherThan && (this.v1 == t.v1 || this.v1 == t.v2 || this.v1 == t.v3)) || (this.v2 != otherThan && (this.v2 == t.v1 || this.v2 == t.v2 || this.v2 == t.v3)) || (this.v3 != otherThan && (this.v3 == t.v1 || this.v3 == t.v2 || this.v3 == t.v3)); + if (this.v1 != otherThan && (this.v1 == t.v1 || this.v1 == t.v2 || this.v1 == t.v3)) + { + goto IL_00cb; + } + if (this.v2 != otherThan && (this.v2 == t.v1 || this.v2 == t.v2 || this.v2 == t.v3)) + { + goto IL_00cb; + } + int result = (this.v3 != otherThan && (this.v3 == t.v1 || this.v3 == t.v2 || this.v3 == t.v3)) ? 1 : 0; + goto IL_00cc; + IL_00cc: + return (byte)result != 0; + IL_00cb: + result = 1; + goto IL_00cc; } public int GetNextOrderedVertex(int root) diff --git a/Assembly-CSharp/RimWorld.Planet/VirtualPlantsUtility.cs b/Assembly-CSharp/RimWorld.Planet/VirtualPlantsUtility.cs index 8027089c0..c9392b57d 100644 --- a/Assembly-CSharp/RimWorld.Planet/VirtualPlantsUtility.cs +++ b/Assembly-CSharp/RimWorld.Planet/VirtualPlantsUtility.cs @@ -1,4 +1,3 @@ -using System; using Verse; namespace RimWorld.Planet @@ -25,7 +24,11 @@ public static bool EnvironmentAllowsEatingVirtualPlantsNowAt(int tile) return false; } float temperatureAtTile = GenTemperature.GetTemperatureAtTile(tile); - return temperatureAtTile >= 0f; + if (temperatureAtTile < 0.0) + { + return false; + } + return true; } public static void EatVirtualPlants(Pawn p) diff --git a/Assembly-CSharp/RimWorld.Planet/WITab.cs b/Assembly-CSharp/RimWorld.Planet/WITab.cs index 1a4d68e96..fdf2c3741 100644 --- a/Assembly-CSharp/RimWorld.Planet/WITab.cs +++ b/Assembly-CSharp/RimWorld.Planet/WITab.cs @@ -1,4 +1,3 @@ -using System; using System.Linq; using Verse; @@ -50,7 +49,15 @@ protected override bool StillValid { get { - return WorldRendererUtility.WorldRenderedNow && Find.WindowStack.IsOpen() && this.InspectPane.CurTabs.Contains(this); + if (!WorldRendererUtility.WorldRenderedNow) + { + return false; + } + if (!Find.WindowStack.IsOpen()) + { + return false; + } + return this.InspectPane.CurTabs.Contains(this); } } diff --git a/Assembly-CSharp/RimWorld.Planet/WITab_Caravan_Gear.cs b/Assembly-CSharp/RimWorld.Planet/WITab_Caravan_Gear.cs index cf7cea579..84098f7a2 100644 --- a/Assembly-CSharp/RimWorld.Planet/WITab_Caravan_Gear.cs +++ b/Assembly-CSharp/RimWorld.Planet/WITab_Caravan_Gear.cs @@ -58,7 +58,7 @@ private List Pawns public WITab_Caravan_Gear() { - this.labelKey = "TabCaravanGear"; + base.labelKey = "TabCaravanGear"; } protected override void UpdateSize() @@ -66,8 +66,8 @@ protected override void UpdateSize() base.UpdateSize(); this.leftPaneWidth = 469f; this.rightPaneWidth = 345f; - this.size.x = this.leftPaneWidth + this.rightPaneWidth; - this.size.y = Mathf.Min(550f, this.PaneTopY - 30f); + base.size.x = this.leftPaneWidth + this.rightPaneWidth; + base.size.y = Mathf.Min(550f, (float)(this.PaneTopY - 30.0)); } public override void OnOpen() @@ -81,11 +81,11 @@ protected override void FillTab() Text.Font = GameFont.Small; this.CheckDraggedItemStillValid(); this.CheckDropDraggedItem(); - Rect position = new Rect(0f, 0f, this.leftPaneWidth, this.size.y); + Rect position = new Rect(0f, 0f, this.leftPaneWidth, base.size.y); GUI.BeginGroup(position); this.DoLeftPane(); GUI.EndGroup(); - Rect position2 = new Rect(position.xMax, 0f, this.rightPaneWidth, this.size.y); + Rect position2 = new Rect(position.xMax, 0f, this.rightPaneWidth, base.size.y); GUI.BeginGroup(position2); this.DoRightPane(); GUI.EndGroup(); @@ -98,24 +98,23 @@ protected override void FillTab() private void DoLeftPane() { - Rect rect = new Rect(0f, 0f, this.leftPaneWidth, this.size.y).ContractedBy(10f); - Rect rect2 = new Rect(0f, 0f, rect.width - 16f, this.leftPaneScrollViewHeight); + Rect rect = new Rect(0f, 0f, this.leftPaneWidth, base.size.y).ContractedBy(10f); + Rect rect2 = new Rect(0f, 0f, (float)(rect.width - 16.0), this.leftPaneScrollViewHeight); float num = 0f; Widgets.BeginScrollView(rect, ref this.leftPaneScrollPosition, rect2, true); this.DoPawnRows(ref num, rect2, rect); if (Event.current.type == EventType.Layout) { - this.leftPaneScrollViewHeight = num + 30f; + this.leftPaneScrollViewHeight = (float)(num + 30.0); } Widgets.EndScrollView(); } private void DoRightPane() { - Rect rect = new Rect(0f, 0f, this.rightPaneWidth, this.size.y).ContractedBy(10f); - Rect rect2 = new Rect(0f, 0f, rect.width - 16f, this.rightPaneScrollViewHeight); - bool flag = this.draggedItem != null && rect.Contains(Event.current.mousePosition) && this.CurrentWearerOf(this.draggedItem) != null; - if (flag) + Rect rect = new Rect(0f, 0f, this.rightPaneWidth, base.size.y).ContractedBy(10f); + Rect rect2 = new Rect(0f, 0f, (float)(rect.width - 16.0), this.rightPaneScrollViewHeight); + if (this.draggedItem != null && rect.Contains(Event.current.mousePosition) && this.CurrentWearerOf(this.draggedItem) != null) { Widgets.DrawHighlight(rect); if (this.droppedDraggedItem) @@ -129,7 +128,7 @@ private void DoRightPane() this.DoInventoryRows(ref num, rect2, rect); if (Event.current.type == EventType.Layout) { - this.rightPaneScrollViewHeight = num + 30f; + this.rightPaneScrollViewHeight = (float)(num + 30.0); } Widgets.EndScrollView(); } @@ -141,13 +140,12 @@ protected override void ExtraOnGUI() { Vector2 mousePosition = Event.current.mousePosition; Rect rect = new Rect(mousePosition.x - this.draggedItemPosOffset.x, mousePosition.y - this.draggedItemPosOffset.y, 32f, 32f); - Find.WindowStack.ImmediateWindow(1283641090, rect, WindowLayer.Super, delegate + Find.WindowStack.ImmediateWindow(1283641090, rect, WindowLayer.Super, (Action)delegate { - if (this.draggedItem == null) + if (this.draggedItem != null) { - return; + Widgets.ThingIcon(rect.AtZero(), this.draggedItem, 1f); } - Widgets.ThingIcon(rect.AtZero(), this.draggedItem, 1f); }, false, false, 0f); } this.CheckDropDraggedItem(); @@ -158,7 +156,7 @@ private void DoPawnRows(ref float curY, Rect scrollViewRect, Rect scrollOutRect) List pawns = this.Pawns; Text.Font = GameFont.Tiny; GUI.color = Color.gray; - Widgets.Label(new Rect(135f, curY + 6f, 200f, 100f), "DragToRearrange".Translate()); + Widgets.Label(new Rect(135f, (float)(curY + 6.0), 200f, 100f), "DragToRearrange".Translate()); GUI.color = Color.white; Text.Font = GameFont.Small; Widgets.ListSeparator(ref curY, scrollViewRect.width, "CaravanColonists".Translate()); @@ -188,7 +186,7 @@ private void DoPawnRows(ref float curY, Rect scrollViewRect, Rect scrollOutRect) private void DoPawnRow(ref float curY, Rect viewRect, Rect scrollOutRect, Pawn p) { - float num = this.leftPaneScrollPosition.y - 50f; + float num = (float)(this.leftPaneScrollPosition.y - 50.0); float num2 = this.leftPaneScrollPosition.y + scrollOutRect.height; if (curY > num && curY < num2) { @@ -203,21 +201,25 @@ private void DoPawnRow(Rect rect, Pawn p) Rect rect2 = rect.AtZero(); CaravanPeopleAndItemsTabUtility.DoAbandonButton(rect2, p, base.SelCaravan); rect2.width -= 24f; - Widgets.InfoCardButton(rect2.width - 24f, (rect.height - 24f) / 2f, p); + Widgets.InfoCardButton((float)(rect2.width - 24.0), (float)((rect.height - 24.0) / 2.0), p); rect2.width -= 24f; bool flag = this.draggedItem != null && rect2.Contains(Event.current.mousePosition) && this.CurrentWearerOf(this.draggedItem) != p; - if ((Mouse.IsOver(rect2) && this.draggedItem == null) || flag) + if (Mouse.IsOver(rect2) && this.draggedItem == null) { - Widgets.DrawHighlight(rect2); + goto IL_00ba; } + if (flag) + goto IL_00ba; + goto IL_00c0; + IL_00c0: if (flag && this.droppedDraggedItem) { this.TryEquipDraggedItem(p); SoundDefOf.TickTiny.PlayOneShotOnCamera(null); } - Rect rect3 = new Rect(4f, (rect.height - 27f) / 2f, 27f, 27f); + Rect rect3 = new Rect(4f, (float)((rect.height - 27.0) / 2.0), 27f, 27f); Widgets.ThingIcon(rect3, p, 1f); - Rect bgRect = new Rect(rect3.xMax + 4f, 16f, 100f, 18f); + Rect bgRect = new Rect((float)(rect3.xMax + 4.0), 16f, 100f, 18f); GenMapUI.DrawPawnLabel(p, bgRect, 1f, 100f, null, GameFont.Small, false, false); float xMax = bgRect.xMax; if (p.equipment != null) @@ -232,7 +234,7 @@ private void DoPawnRow(Rect rect, Pawn p) { WITab_Caravan_Gear.tmpApparel.Clear(); WITab_Caravan_Gear.tmpApparel.AddRange(p.apparel.WornApparel); - WITab_Caravan_Gear.tmpApparel.SortBy((Apparel x) => (int)x.def.apparel.LastLayer, (Apparel x) => -x.def.apparel.HumanBodyCoverage); + WITab_Caravan_Gear.tmpApparel.SortBy((Func)((Apparel x) => (int)x.def.apparel.LastLayer), (Func)((Apparel x) => (float)(0.0 - x.def.apparel.HumanBodyCoverage))); for (int j = 0; j < WITab_Caravan_Gear.tmpApparel.Count; j++) { this.DoEquippedGear(WITab_Caravan_Gear.tmpApparel[j], p, ref xMax); @@ -241,10 +243,14 @@ private void DoPawnRow(Rect rect, Pawn p) if (p.Downed) { GUI.color = new Color(1f, 0f, 0f, 0.5f); - Widgets.DrawLineHorizontal(0f, rect.height / 2f, rect.width); + Widgets.DrawLineHorizontal(0f, (float)(rect.height / 2.0), rect.width); GUI.color = Color.white; } GUI.EndGroup(); + return; + IL_00ba: + Widgets.DrawHighlight(rect2); + goto IL_00c0; } private void DoInventoryRows(ref float curY, Rect scrollViewRect, Rect scrollOutRect) @@ -290,7 +296,7 @@ private void DoInventoryRows(ref float curY, Rect scrollViewRect, Rect scrollOut private void DoInventoryRow(ref float curY, Rect viewRect, Rect scrollOutRect, Thing t) { - float num = this.rightPaneScrollPosition.y - 30f; + float num = (float)(this.rightPaneScrollPosition.y - 30.0); float num2 = this.rightPaneScrollPosition.y + scrollOutRect.height; if (curY > num && curY < num2) { @@ -303,17 +309,17 @@ private void DoInventoryRow(Rect rect, Thing t) { GUI.BeginGroup(rect); Rect rect2 = rect.AtZero(); - Widgets.InfoCardButton(rect2.width - 24f, (rect.height - 24f) / 2f, t); + Widgets.InfoCardButton((float)(rect2.width - 24.0), (float)((rect.height - 24.0) / 2.0), t); rect2.width -= 24f; if (this.draggedItem == null && Mouse.IsOver(rect2)) { Widgets.DrawHighlight(rect2); } - float num = (t != this.draggedItem) ? 1f : 0.5f; - Rect rect3 = new Rect(4f, (rect.height - 27f) / 2f, 27f, 27f); + float num = (float)((t != this.draggedItem) ? 1.0 : 0.5); + Rect rect3 = new Rect(4f, (float)((rect.height - 27.0) / 2.0), 27f, 27f); Widgets.ThingIcon(rect3, t, num); GUI.color = new Color(1f, 1f, 1f, num); - Rect rect4 = new Rect(rect3.xMax + 4f, 0f, 250f, 30f); + Rect rect4 = new Rect((float)(rect3.xMax + 4.0), 0f, 250f, 30f); Text.Anchor = TextAnchor.MiddleLeft; Text.WordWrap = false; Widgets.Label(rect4, t.LabelCap); @@ -335,19 +341,7 @@ private void DoEquippedGear(Thing t, Pawn p, ref float curX) { Rect rect = new Rect(curX, 9f, 32f, 32f); bool flag = Mouse.IsOver(rect); - float alpha; - if (t == this.draggedItem) - { - alpha = 0.2f; - } - else if (flag && this.draggedItem == null) - { - alpha = 0.75f; - } - else - { - alpha = 1f; - } + float alpha = (float)((t != this.draggedItem) ? ((!flag || this.draggedItem != null) ? 1.0 : 0.75) : 0.20000000298023224); Widgets.ThingIcon(rect, t, alpha); curX += 32f; TooltipHandler.TipRegion(rect, t.LabelCap); @@ -363,34 +357,26 @@ private void DoEquippedGear(Thing t, Pawn p, ref float curX) private void CheckDraggedItemStillValid() { - if (this.draggedItem == null) - { - return; - } - if (this.draggedItem.Destroyed) - { - this.draggedItem = null; - return; - } - if (this.CurrentWearerOf(this.draggedItem) != null) - { - return; - } - List list = CaravanInventoryUtility.AllInventoryItems(base.SelCaravan); - if (list.Contains(this.draggedItem)) + if (this.draggedItem != null) { - return; + if (this.draggedItem.Destroyed) + { + this.draggedItem = null; + } + else if (this.CurrentWearerOf(this.draggedItem) == null) + { + List list = CaravanInventoryUtility.AllInventoryItems(base.SelCaravan); + if (!list.Contains(this.draggedItem)) + { + this.draggedItem = null; + } + } } - this.draggedItem = null; } private void CheckDropDraggedItem() { - if (this.draggedItem == null) - { - return; - } - if (Event.current.type == EventType.MouseUp || Event.current.rawType == EventType.MouseUp) + if (this.draggedItem != null && (Event.current.type == EventType.MouseUp || Event.current.rawType == EventType.MouseUp)) { this.droppedDraggedItem = true; } @@ -404,11 +390,11 @@ private bool IsVisibleWeapon(ThingDef t) private Pawn CurrentWearerOf(Thing t) { IThingHolder parentHolder = t.ParentHolder; - if (parentHolder is Pawn_EquipmentTracker || parentHolder is Pawn_ApparelTracker) + if (!(parentHolder is Pawn_EquipmentTracker) && !(parentHolder is Pawn_ApparelTracker)) { - return (Pawn)parentHolder.ParentHolder; + return null; } - return null; + return (Pawn)parentHolder.ParentHolder; } private void MoveDraggedItemToInventory() @@ -433,16 +419,13 @@ private void TryEquipDraggedItem(Pawn p) { if (p.story != null && p.story.WorkTagIsDisabled(WorkTags.Violent)) { - Messages.Message("MessageCantEquipIncapableOfViolence".Translate(new object[] - { - p.LabelShort - }), p, MessageSound.RejectInput); + Messages.Message("MessageCantEquipIncapableOfViolence".Translate(p.LabelShort), (Thing)p, MessageSound.RejectInput); this.draggedItem = null; return; } if (!p.health.capacities.CapableOf(PawnCapacityDefOf.Manipulation)) { - Messages.Message("MessageCantEquipIncapableOfManipulation".Translate(), p, MessageSound.RejectInput); + Messages.Message("MessageCantEquipIncapableOfManipulation".Translate(), (Thing)p, MessageSound.RejectInput); this.draggedItem = null; return; } @@ -498,13 +481,7 @@ private void TryEquipDraggedItem(Pawn p) } else { - Log.Warning(string.Concat(new object[] - { - "Could not make ", - p, - " equip or wear ", - this.draggedItem - })); + Log.Warning("Could not make " + p + " equip or wear " + this.draggedItem); } this.draggedItem = null; } diff --git a/Assembly-CSharp/RimWorld.Planet/WITab_Caravan_Health.cs b/Assembly-CSharp/RimWorld.Planet/WITab_Caravan_Health.cs index c99dcd802..7b1cfdd67 100644 --- a/Assembly-CSharp/RimWorld.Planet/WITab_Caravan_Health.cs +++ b/Assembly-CSharp/RimWorld.Planet/WITab_Caravan_Health.cs @@ -49,7 +49,7 @@ private List CapacitiesToDisplay WITab_Caravan_Health.capacitiesToDisplay.Add(allDefsListForReading[i]); } } - WITab_Caravan_Health.capacitiesToDisplay.SortBy((PawnCapacityDef x) => x.listOrder); + WITab_Caravan_Health.capacitiesToDisplay.SortBy((Func)((PawnCapacityDef x) => x.listOrder)); return WITab_Caravan_Health.capacitiesToDisplay; } } @@ -68,21 +68,21 @@ private float SpecificHealthTabWidth public WITab_Caravan_Health() { - this.labelKey = "TabCaravanHealth"; + base.labelKey = "TabCaravanHealth"; } protected override void FillTab() { Text.Font = GameFont.Small; - Rect rect = new Rect(0f, 0f, this.size.x, this.size.y).ContractedBy(10f); - Rect rect2 = new Rect(0f, 0f, rect.width - 16f, this.scrollViewHeight); + Rect rect = new Rect(0f, 0f, base.size.x, base.size.y).ContractedBy(10f); + Rect rect2 = new Rect(0f, 0f, (float)(rect.width - 16.0), this.scrollViewHeight); float num = 0f; Widgets.BeginScrollView(rect, ref this.scrollPosition, rect2, true); this.DoColumnHeaders(ref num); this.DoRows(ref num, rect2, rect); if (Event.current.type == EventType.Layout) { - this.scrollViewHeight = num + 30f; + this.scrollViewHeight = (float)(num + 30.0); } Widgets.EndScrollView(); } @@ -90,11 +90,11 @@ protected override void FillTab() protected override void UpdateSize() { base.UpdateSize(); - this.size = this.GetRawSize(false); - if (this.size.x + this.SpecificHealthTabWidth > (float)UI.screenWidth) + base.size = this.GetRawSize(false); + if (base.size.x + this.SpecificHealthTabWidth > (float)UI.screenWidth) { this.compactMode = true; - this.size = this.GetRawSize(true); + base.size = this.GetRawSize(true); } else { @@ -110,19 +110,18 @@ protected override void ExtraOnGUI() { Rect tabRect = base.TabRect; float specificHealthTabWidth = this.SpecificHealthTabWidth; - Rect rect = new Rect(tabRect.xMax - 1f, tabRect.yMin, specificHealthTabWidth, tabRect.height); - Find.WindowStack.ImmediateWindow(1439870015, rect, WindowLayer.GameUI, delegate + Rect rect = new Rect((float)(tabRect.xMax - 1.0), tabRect.yMin, specificHealthTabWidth, tabRect.height); + Find.WindowStack.ImmediateWindow(1439870015, rect, WindowLayer.GameUI, (Action)delegate { - if (localSpecificHealthTabForPawn.DestroyedOrNull()) + if (!localSpecificHealthTabForPawn.DestroyedOrNull()) { - return; - } - Rect outRect = new Rect(0f, 20f, rect.width, rect.height - 20f); - HealthCardUtility.DrawPawnHealthCard(outRect, localSpecificHealthTabForPawn, false, true, localSpecificHealthTabForPawn); - if (Widgets.CloseButtonFor(rect.AtZero())) - { - this.specificHealthTabForPawn = null; - SoundDefOf.TabClose.PlayOneShotOnCamera(null); + Rect outRect = new Rect(0f, 20f, rect.width, (float)(rect.height - 20.0)); + HealthCardUtility.DrawPawnHealthCard(outRect, localSpecificHealthTabForPawn, false, true, localSpecificHealthTabForPawn); + if (Widgets.CloseButtonFor(rect.AtZero())) + { + this.specificHealthTabForPawn = null; + SoundDefOf.TabClose.PlayOneShotOnCamera(null); + } } }, true, false, 1f); } @@ -139,7 +138,7 @@ private void DoColumnHeaders(ref float curY) List list = this.CapacitiesToDisplay; for (int i = 0; i < list.Count; i++) { - num += 100f; + num = (float)(num + 100.0); Widgets.Label(new Rect(num, 3f, 100f, 100f), list[i].LabelCap); } Text.Anchor = TextAnchor.UpperLeft; @@ -189,18 +188,18 @@ private Vector2 GetRawSize(bool compactMode) float num = 100f; if (!compactMode) { - num += 100f; - num += (float)this.CapacitiesToDisplay.Count * 100f; + num = (float)(num + 100.0); + num = (float)(num + (float)this.CapacitiesToDisplay.Count * 100.0); } - Vector2 result; - result.x = 127f + num + 16f; - result.y = Mathf.Min(550f, this.PaneTopY - 30f); + Vector2 result = default(Vector2); + result.x = (float)(127.0 + num + 16.0); + result.y = Mathf.Min(550f, (float)(this.PaneTopY - 30.0)); return result; } private void DoRow(ref float curY, Rect viewRect, Rect scrollOutRect, Pawn p) { - float num = this.scrollPosition.y - 50f; + float num = (float)(this.scrollPosition.y - 50.0); float num2 = this.scrollPosition.y + scrollOutRect.height; if (curY > num && curY < num2) { @@ -215,7 +214,7 @@ private void DoRow(Rect rect, Pawn p) Rect rect2 = rect.AtZero(); CaravanPeopleAndItemsTabUtility.DoAbandonButton(rect2, p, base.SelCaravan); rect2.width -= 24f; - Widgets.InfoCardButton(rect2.width - 24f, (rect.height - 24f) / 2f, p); + Widgets.InfoCardButton((float)(rect2.width - 24.0), (float)((rect.height - 24.0) / 2.0), p); rect2.width -= 24f; CaravanPeopleAndItemsTabUtility.DoOpenSpecificTabButton(rect2, p, ref this.specificHealthTabForPawn); rect2.width -= 24f; @@ -223,9 +222,9 @@ private void DoRow(Rect rect, Pawn p) { Widgets.DrawHighlight(rect2); } - Rect rect3 = new Rect(4f, (rect.height - 27f) / 2f, 27f, 27f); + Rect rect3 = new Rect(4f, (float)((rect.height - 27.0) / 2.0), 27f, 27f); Widgets.ThingIcon(rect3, p, 1f); - Rect bgRect = new Rect(rect3.xMax + 4f, 16f, 100f, 18f); + Rect bgRect = new Rect((float)(rect3.xMax + 4.0), 16f, 100f, 18f); GenMapUI.DrawPawnLabel(p, bgRect, 1f, 100f, null, GameFont.Small, false, false); if (!this.compactMode) { @@ -238,27 +237,18 @@ private void DoRow(Rect rect, Pawn p) List list = this.CapacitiesToDisplay; for (int i = 0; i < list.Count; i++) { - num += 100f; + num = (float)(num + 100.0); Rect rect5 = new Rect(num, 0f, 100f, 50f); - if (!p.RaceProps.Humanlike || list[i].showOnHumanlikes) + if ((!p.RaceProps.Humanlike || list[i].showOnHumanlikes) && (!p.RaceProps.Animal || list[i].showOnAnimals) && (!p.RaceProps.IsMechanoid || list[i].showOnMechanoids) && PawnCapacityUtility.BodyCanEverDoCapacity(p.RaceProps.body, list[i])) { - if (!p.RaceProps.Animal || list[i].showOnAnimals) - { - if (!p.RaceProps.IsMechanoid || list[i].showOnMechanoids) - { - if (PawnCapacityUtility.BodyCanEverDoCapacity(p.RaceProps.body, list[i])) - { - this.DoCapacity(rect5, p, list[i]); - } - } - } + this.DoCapacity(rect5, p, list[i]); } } } if (p.Downed) { GUI.color = new Color(1f, 0f, 0f, 0.5f); - Widgets.DrawLineHorizontal(0f, rect.height / 2f, rect.width); + Widgets.DrawLineHorizontal(0f, (float)(rect.height / 2.0), rect.width); GUI.color = Color.white; } GUI.EndGroup(); diff --git a/Assembly-CSharp/RimWorld.Planet/WITab_Caravan_Items.cs b/Assembly-CSharp/RimWorld.Planet/WITab_Caravan_Items.cs index 6af805cdd..9222f56ce 100644 --- a/Assembly-CSharp/RimWorld.Planet/WITab_Caravan_Items.cs +++ b/Assembly-CSharp/RimWorld.Planet/WITab_Caravan_Items.cs @@ -1,4 +1,3 @@ -using System; using System.Collections.Generic; using UnityEngine; using Verse; @@ -17,14 +16,14 @@ public class WITab_Caravan_Items : WITab public WITab_Caravan_Items() { - this.labelKey = "TabCaravanItems"; + base.labelKey = "TabCaravanItems"; } protected override void FillTab() { float num = 0f; this.DrawMassUsage(ref num); - Rect position = new Rect(0f, num, this.size.x, this.size.y - num); + Rect position = new Rect(0f, num, base.size.x, base.size.y - num); GUI.BeginGroup(position); this.UpdateItemsList(); Pawn pawn = null; @@ -37,14 +36,14 @@ protected override void UpdateSize() { base.UpdateSize(); this.UpdateItemsList(); - this.size = CaravanPeopleAndItemsTabUtility.GetSize(this.items, this.PaneTopY, true); + base.size = CaravanPeopleAndItemsTabUtility.GetSize(this.items, this.PaneTopY, true); this.items.Clear(); } private void DrawMassUsage(ref float curY) { curY += 10f; - Rect rect = new Rect(10f, curY, this.size.x - 10f, 100f); + Rect rect = new Rect(10f, curY, (float)(base.size.x - 10.0), 100f); float massUsage = base.SelCaravan.MassUsage; float massCapacity = base.SelCaravan.MassCapacity; if (massUsage > massCapacity) @@ -52,11 +51,7 @@ private void DrawMassUsage(ref float curY) GUI.color = Color.red; } Text.Font = GameFont.Small; - Widgets.Label(rect, "MassCarried".Translate(new object[] - { - massUsage.ToString("0.##"), - massCapacity.ToString("0.##") - })); + Widgets.Label(rect, "MassCarried".Translate(massUsage.ToString("0.##"), massCapacity.ToString("0.##"))); GUI.color = Color.white; curY += 22f; } diff --git a/Assembly-CSharp/RimWorld.Planet/WITab_Caravan_Needs.cs b/Assembly-CSharp/RimWorld.Planet/WITab_Caravan_Needs.cs index 0384594be..822733d8c 100644 --- a/Assembly-CSharp/RimWorld.Planet/WITab_Caravan_Needs.cs +++ b/Assembly-CSharp/RimWorld.Planet/WITab_Caravan_Needs.cs @@ -24,23 +24,24 @@ private float SpecificNeedsTabWidth { get { - if (this.specificNeedsTabForPawn == null || this.specificNeedsTabForPawn.Destroyed) + if (this.specificNeedsTabForPawn != null && !this.specificNeedsTabForPawn.Destroyed) { - return 0f; + Vector2 size = NeedsCardUtility.GetSize(this.specificNeedsTabForPawn); + return size.x; } - return NeedsCardUtility.GetSize(this.specificNeedsTabForPawn).x; + return 0f; } } public WITab_Caravan_Needs() { - this.labelKey = "TabCaravanNeeds"; + base.labelKey = "TabCaravanNeeds"; } protected override void FillTab() { this.AddPawnsToTmpThings(); - CaravanPeopleAndItemsTabUtility.DoRows(this.size, WITab_Caravan_Needs.tmpThings, base.SelCaravan, ref this.scrollPosition, ref this.scrollViewHeight, false, ref this.specificNeedsTabForPawn, this.doNeeds); + CaravanPeopleAndItemsTabUtility.DoRows(base.size, WITab_Caravan_Needs.tmpThings, base.SelCaravan, ref this.scrollPosition, ref this.scrollViewHeight, false, ref this.specificNeedsTabForPawn, this.doNeeds); WITab_Caravan_Needs.tmpThings.Clear(); } @@ -48,17 +49,20 @@ protected override void UpdateSize() { base.UpdateSize(); this.AddPawnsToTmpThings(); - this.size = CaravanPeopleAndItemsTabUtility.GetSize(WITab_Caravan_Needs.tmpThings, this.PaneTopY, true); - if (this.size.x + this.SpecificNeedsTabWidth > (float)UI.screenWidth) + base.size = CaravanPeopleAndItemsTabUtility.GetSize(WITab_Caravan_Needs.tmpThings, this.PaneTopY, true); + if (base.size.x + this.SpecificNeedsTabWidth > (float)UI.screenWidth) { this.doNeeds = false; - this.size = CaravanPeopleAndItemsTabUtility.GetSize(WITab_Caravan_Needs.tmpThings, this.PaneTopY, false); + base.size = CaravanPeopleAndItemsTabUtility.GetSize(WITab_Caravan_Needs.tmpThings, this.PaneTopY, false); } else { this.doNeeds = true; } - this.size.y = Mathf.Max(this.size.y, NeedsCardUtility.FullSize.y); + ref Vector2 val = ref base.size; + float y = base.size.y; + Vector2 fullSize = NeedsCardUtility.FullSize; + val.y = Mathf.Max(y, fullSize.y); WITab_Caravan_Needs.tmpThings.Clear(); } @@ -70,18 +74,17 @@ protected override void ExtraOnGUI() { Rect tabRect = base.TabRect; float specificNeedsTabWidth = this.SpecificNeedsTabWidth; - Rect rect = new Rect(tabRect.xMax - 1f, tabRect.yMin, specificNeedsTabWidth, tabRect.height); - Find.WindowStack.ImmediateWindow(1439870015, rect, WindowLayer.GameUI, delegate + Rect rect = new Rect((float)(tabRect.xMax - 1.0), tabRect.yMin, specificNeedsTabWidth, tabRect.height); + Find.WindowStack.ImmediateWindow(1439870015, rect, WindowLayer.GameUI, (Action)delegate { - if (localSpecificNeedsTabForPawn.DestroyedOrNull()) + if (!localSpecificNeedsTabForPawn.DestroyedOrNull()) { - return; - } - NeedsCardUtility.DoNeedsMoodAndThoughts(rect.AtZero(), localSpecificNeedsTabForPawn, ref this.thoughtScrollPosition); - if (Widgets.CloseButtonFor(rect.AtZero())) - { - this.specificNeedsTabForPawn = null; - SoundDefOf.TabClose.PlayOneShotOnCamera(null); + NeedsCardUtility.DoNeedsMoodAndThoughts(rect.AtZero(), localSpecificNeedsTabForPawn, ref this.thoughtScrollPosition); + if (Widgets.CloseButtonFor(rect.AtZero())) + { + this.specificNeedsTabForPawn = null; + SoundDefOf.TabClose.PlayOneShotOnCamera(null); + } } }, true, false, 1f); } diff --git a/Assembly-CSharp/RimWorld.Planet/WITab_Caravan_Social.cs b/Assembly-CSharp/RimWorld.Planet/WITab_Caravan_Social.cs index 84b540bb3..200822bf2 100644 --- a/Assembly-CSharp/RimWorld.Planet/WITab_Caravan_Social.cs +++ b/Assembly-CSharp/RimWorld.Planet/WITab_Caravan_Social.cs @@ -44,20 +44,20 @@ private float SpecificSocialTabWidth public WITab_Caravan_Social() { - this.labelKey = "TabCaravanSocial"; + base.labelKey = "TabCaravanSocial"; } protected override void FillTab() { Text.Font = GameFont.Small; - Rect rect = new Rect(0f, 0f, this.size.x, this.size.y).ContractedBy(10f); - Rect rect2 = new Rect(0f, 0f, rect.width - 16f, this.scrollViewHeight); + Rect rect = new Rect(0f, 0f, base.size.x, base.size.y).ContractedBy(10f); + Rect rect2 = new Rect(0f, 0f, (float)(rect.width - 16.0), this.scrollViewHeight); float num = 0f; Widgets.BeginScrollView(rect, ref this.scrollPosition, rect2, true); this.DoRows(ref num, rect2, rect); if (Event.current.type == EventType.Layout) { - this.scrollViewHeight = num + 30f; + this.scrollViewHeight = (float)(num + 30.0); } Widgets.EndScrollView(); } @@ -65,8 +65,8 @@ protected override void FillTab() protected override void UpdateSize() { base.UpdateSize(); - this.size.x = 243f; - this.size.y = Mathf.Min(550f, this.PaneTopY - 30f); + base.size.x = 243f; + base.size.y = Mathf.Min(550f, (float)(this.PaneTopY - 30.0)); } protected override void ExtraOnGUI() @@ -77,18 +77,17 @@ protected override void ExtraOnGUI() { Rect tabRect = base.TabRect; float specificSocialTabWidth = this.SpecificSocialTabWidth; - Rect rect = new Rect(tabRect.xMax - 1f, tabRect.yMin, specificSocialTabWidth, tabRect.height); - Find.WindowStack.ImmediateWindow(1439870015, rect, WindowLayer.GameUI, delegate + Rect rect = new Rect((float)(tabRect.xMax - 1.0), tabRect.yMin, specificSocialTabWidth, tabRect.height); + Find.WindowStack.ImmediateWindow(1439870015, rect, WindowLayer.GameUI, (Action)delegate { - if (localSpecificSocialTabForPawn.DestroyedOrNull()) + if (!localSpecificSocialTabForPawn.DestroyedOrNull()) { - return; - } - SocialCardUtility.DrawSocialCard(rect.AtZero(), localSpecificSocialTabForPawn); - if (Widgets.CloseButtonFor(rect.AtZero())) - { - this.specificSocialTabForPawn = null; - SoundDefOf.TabClose.PlayOneShotOnCamera(null); + SocialCardUtility.DrawSocialCard(rect.AtZero(), localSpecificSocialTabForPawn); + if (Widgets.CloseButtonFor(rect.AtZero())) + { + this.specificSocialTabForPawn = null; + SoundDefOf.TabClose.PlayOneShotOnCamera(null); + } } }, true, false, 1f); } @@ -97,7 +96,9 @@ protected override void ExtraOnGUI() public override void OnOpen() { base.OnOpen(); - if ((this.specificSocialTabForPawn == null || !this.Pawns.Contains(this.specificSocialTabForPawn)) && this.Pawns.Any()) + if (this.specificSocialTabForPawn != null && this.Pawns.Contains(this.specificSocialTabForPawn)) + return; + if (this.Pawns.Any()) { this.specificSocialTabForPawn = this.Pawns[0]; } @@ -114,41 +115,35 @@ private void DoRows(ref float curY, Rect scrollViewRect, Rect scrollOutRect) for (int i = 0; i < pawns.Count; i++) { Pawn pawn = pawns[i]; - if (pawn.RaceProps.IsFlesh) + if (pawn.RaceProps.IsFlesh && pawn.IsColonist) { - if (pawn.IsColonist) + if (!flag) { - if (!flag) - { - Widgets.ListSeparator(ref curY, scrollViewRect.width, "CaravanColonists".Translate()); - flag = true; - } - this.DoRow(ref curY, scrollViewRect, scrollOutRect, pawn); + Widgets.ListSeparator(ref curY, scrollViewRect.width, "CaravanColonists".Translate()); + flag = true; } + this.DoRow(ref curY, scrollViewRect, scrollOutRect, pawn); } } bool flag2 = false; for (int j = 0; j < pawns.Count; j++) { Pawn pawn2 = pawns[j]; - if (pawn2.RaceProps.IsFlesh) + if (pawn2.RaceProps.IsFlesh && !pawn2.IsColonist) { - if (!pawn2.IsColonist) + if (!flag2) { - if (!flag2) - { - Widgets.ListSeparator(ref curY, scrollViewRect.width, "CaravanPrisonersAndAnimals".Translate()); - flag2 = true; - } - this.DoRow(ref curY, scrollViewRect, scrollOutRect, pawn2); + Widgets.ListSeparator(ref curY, scrollViewRect.width, "CaravanPrisonersAndAnimals".Translate()); + flag2 = true; } + this.DoRow(ref curY, scrollViewRect, scrollOutRect, pawn2); } } } private void DoRow(ref float curY, Rect viewRect, Rect scrollOutRect, Pawn p) { - float num = this.scrollPosition.y - 50f; + float num = (float)(this.scrollPosition.y - 50.0); float num2 = this.scrollPosition.y + scrollOutRect.height; if (curY > num && curY < num2) { @@ -163,7 +158,7 @@ private void DoRow(Rect rect, Pawn p) Rect rect2 = rect.AtZero(); CaravanPeopleAndItemsTabUtility.DoAbandonButton(rect2, p, base.SelCaravan); rect2.width -= 24f; - Widgets.InfoCardButton(rect2.width - 24f, (rect.height - 24f) / 2f, p); + Widgets.InfoCardButton((float)(rect2.width - 24.0), (float)((rect.height - 24.0) / 2.0), p); rect2.width -= 24f; CaravanPeopleAndItemsTabUtility.DoOpenSpecificTabButton(rect2, p, ref this.specificSocialTabForPawn); rect2.width -= 24f; @@ -171,14 +166,14 @@ private void DoRow(Rect rect, Pawn p) { Widgets.DrawHighlight(rect2); } - Rect rect3 = new Rect(4f, (rect.height - 27f) / 2f, 27f, 27f); + Rect rect3 = new Rect(4f, (float)((rect.height - 27.0) / 2.0), 27f, 27f); Widgets.ThingIcon(rect3, p, 1f); - Rect bgRect = new Rect(rect3.xMax + 4f, 16f, 100f, 18f); + Rect bgRect = new Rect((float)(rect3.xMax + 4.0), 16f, 100f, 18f); GenMapUI.DrawPawnLabel(p, bgRect, 1f, 100f, null, GameFont.Small, false, false); if (p.Downed) { GUI.color = new Color(1f, 0f, 0f, 0.5f); - Widgets.DrawLineHorizontal(0f, rect.height / 2f, rect.width); + Widgets.DrawLineHorizontal(0f, (float)(rect.height / 2.0), rect.width); GUI.color = Color.white; } GUI.EndGroup(); diff --git a/Assembly-CSharp/RimWorld.Planet/WITab_Planet.cs b/Assembly-CSharp/RimWorld.Planet/WITab_Planet.cs index 1fd91c937..865566358 100644 --- a/Assembly-CSharp/RimWorld.Planet/WITab_Planet.cs +++ b/Assembly-CSharp/RimWorld.Planet/WITab_Planet.cs @@ -1,4 +1,3 @@ -using System; using System.Text; using UnityEngine; using Verse; @@ -34,17 +33,20 @@ private string Desc public WITab_Planet() { - this.size = WITab_Planet.WinSize; - this.labelKey = "TabPlanet"; + base.size = WITab_Planet.WinSize; + base.labelKey = "TabPlanet"; } protected override void FillTab() { - Rect rect = new Rect(0f, 0f, WITab_Planet.WinSize.x, WITab_Planet.WinSize.y).ContractedBy(10f); - Rect rect2 = rect; + Vector2 winSize = WITab_Planet.WinSize; + float x = winSize.x; + Vector2 winSize2 = WITab_Planet.WinSize; + Rect rect; + Rect rect2 = rect = new Rect(0f, 0f, x, winSize2.y).ContractedBy(10f); Text.Font = GameFont.Medium; - Widgets.Label(rect2, Find.World.info.name); - Rect rect3 = rect; + Widgets.Label(rect, Find.World.info.name); + Rect rect3 = rect2; rect3.yMin += 35f; Text.Font = GameFont.Small; Widgets.Label(rect3, this.Desc); diff --git a/Assembly-CSharp/RimWorld.Planet/WITab_Terrain.cs b/Assembly-CSharp/RimWorld.Planet/WITab_Terrain.cs index a15397c3c..ccef4e79c 100644 --- a/Assembly-CSharp/RimWorld.Planet/WITab_Terrain.cs +++ b/Assembly-CSharp/RimWorld.Planet/WITab_Terrain.cs @@ -19,18 +19,21 @@ public override bool IsVisible public WITab_Terrain() { - this.size = WITab_Terrain.WinSize; - this.labelKey = "TabTerrain"; - this.tutorTag = "Terrain"; + base.size = WITab_Terrain.WinSize; + base.labelKey = "TabTerrain"; + base.tutorTag = "Terrain"; } protected override void FillTab() { - Rect rect = new Rect(0f, 0f, WITab_Terrain.WinSize.x, WITab_Terrain.WinSize.y).ContractedBy(10f); - Rect rect2 = rect; + Vector2 winSize = WITab_Terrain.WinSize; + float x = winSize.x; + Vector2 winSize2 = WITab_Terrain.WinSize; + Rect rect; + Rect rect2 = rect = new Rect(0f, 0f, x, winSize2.y).ContractedBy(10f); Text.Font = GameFont.Medium; - Widgets.Label(rect2, base.SelTile.biome.LabelCap); - Rect rect3 = rect; + Widgets.Label(rect, base.SelTile.biome.LabelCap); + Rect rect3 = rect2; rect3.yMin += 35f; Text.Font = GameFont.Small; Listing_Standard listing_Standard = new Listing_Standard(); @@ -38,7 +41,8 @@ protected override void FillTab() listing_Standard.Begin(rect3); Tile selTile = base.SelTile; int selTileID = base.SelTileID; - float y = Find.WorldGrid.LongLatOf(selTileID).y; + Vector2 vector = Find.WorldGrid.LongLatOf(selTileID); + float y = vector.y; listing_Standard.Label(selTile.biome.description, -1f); listing_Standard.Gap(8f); listing_Standard.GapLine(12f); @@ -50,11 +54,14 @@ protected override void FillTab() if (selTile.VisibleRoads != null) { listing_Standard.LabelDouble("Road".Translate(), GenText.ToCommaList((from roadlink in selTile.VisibleRoads - select roadlink.road.label).Distinct(), true).CapitalizeFirst()); + select roadlink.road.label).Distinct(), true).CapitalizeFirst()); } if (selTile.VisibleRivers != null) { - listing_Standard.LabelDouble("River".Translate(), selTile.VisibleRivers.MaxBy((Tile.RiverLink riverlink) => riverlink.river.degradeThreshold).river.LabelCap); + Listing_Standard obj = listing_Standard; + string leftLabel = "River".Translate(); + Tile.RiverLink riverLink = selTile.VisibleRivers.MaxBy((Func)((Tile.RiverLink riverlink) => riverlink.river.degradeThreshold)); + obj.LabelDouble(leftLabel, riverLink.river.LabelCap); } if (!Find.World.Impassable(selTileID)) { @@ -82,7 +89,10 @@ protected override void FillTab() listing_Standard.LabelDouble("Rainfall".Translate(), selTile.rainfall.ToString("F0") + "mm"); listing_Standard.LabelDouble("AnimalsCanGrazeNow".Translate(), (!VirtualPlantsUtility.EnvironmentAllowsEatingVirtualPlantsNowAt(selTileID)) ? "No".Translate() : "Yes".Translate()); listing_Standard.GapLine(12f); - listing_Standard.LabelDouble("TimeZone".Translate(), GenDate.TimeZoneAt(Find.WorldGrid.LongLatOf(selTileID).x).ToStringWithSign()); + Listing_Standard obj2 = listing_Standard; + string leftLabel2 = "TimeZone".Translate(); + Vector2 vector2 = Find.WorldGrid.LongLatOf(selTileID); + obj2.LabelDouble(leftLabel2, GenDate.TimeZoneAt(vector2.x).ToStringWithSign()); Rot4 rot = Find.World.CoastDirectionAt(selTileID); if (rot.IsValid) { diff --git a/Assembly-CSharp/RimWorld.Planet/World.cs b/Assembly-CSharp/RimWorld.Planet/World.cs index b6967781a..e1182ee63 100644 --- a/Assembly-CSharp/RimWorld.Planet/World.cs +++ b/Assembly-CSharp/RimWorld.Planet/World.cs @@ -107,11 +107,11 @@ public void ExposeData() Scribe_Deep.Look(ref this.info, "info", new object[0]); if (Scribe.mode == LoadSaveMode.LoadingVars) { - foreach (WorldGenStepDef current in from gs in DefDatabase.AllDefs + foreach (WorldGenStepDef item in from gs in DefDatabase.AllDefs orderby gs.order select gs) { - current.worldGenStep.GenerateFromScribe(this.info.seedString); + item.worldGenStep.GenerateFromScribe(this.info.seedString); } } else @@ -128,11 +128,11 @@ public void ExposeComponents() Scribe_Deep.Look(ref this.worldObjects, "worldObjects", new object[0]); Scribe_Deep.Look(ref this.settings, "settings", new object[0]); Scribe_Deep.Look(ref this.gameConditionManager, "gameConditionManager", new object[1]); - Scribe_Deep.Look(ref this.storyState, "storyState", new object[] + Scribe_Deep.Look(ref this.storyState, "storyState", new object[1] { this }); - Scribe_Collections.Look(ref this.components, "components", LookMode.Deep, new object[] + Scribe_Collections.Look(ref this.components, "components", LookMode.Deep, new object[1] { this }); @@ -166,15 +166,12 @@ public void ConstructComponents() private void FillComponents() { - this.components.RemoveAll((WorldComponent component) => component == null); - foreach (Type current in typeof(WorldComponent).AllSubclassesNonAbstract()) + this.components.RemoveAll((Predicate)((WorldComponent component) => component == null)); + foreach (Type item2 in typeof(WorldComponent).AllSubclassesNonAbstract()) { - if (this.GetComponent(current) == null) + if (this.GetComponent(item2) == null) { - WorldComponent item = (WorldComponent)Activator.CreateInstance(current, new object[] - { - this - }); + WorldComponent item = (WorldComponent)Activator.CreateInstance(item2, this); this.components.Add(item); } } @@ -229,13 +226,13 @@ public T GetComponent() where T : WorldComponent { for (int i = 0; i < this.components.Count; i++) { - T t = this.components[i] as T; - if (t != null) + T val = (T)(this.components[i] as T); + if (val != null) { - return t; + return val; } } - return (T)((object)null); + return (T)null; } public WorldComponent GetComponent(Type type) @@ -259,20 +256,20 @@ public Rot4 CoastDirectionAt(int tileID) } World.tmpOceanDirs.Clear(); this.grid.GetTileNeighbors(tileID, World.tmpNeighbors); - int i = 0; + int num = 0; int count = World.tmpNeighbors.Count; - while (i < count) + while (num < count) { - Tile tile2 = this.grid[World.tmpNeighbors[i]]; + Tile tile2 = this.grid[World.tmpNeighbors[num]]; if (tile2.biome == BiomeDefOf.Ocean) { - Rot4 rotFromTo = this.grid.GetRotFromTo(tileID, World.tmpNeighbors[i]); + Rot4 rotFromTo = this.grid.GetRotFromTo(tileID, World.tmpNeighbors[num]); if (!World.tmpOceanDirs.Contains(rotFromTo)) { World.tmpOceanDirs.Add(rotFromTo); } } - i++; + num++; } if (World.tmpOceanDirs.Count == 0) { @@ -291,16 +288,16 @@ public IEnumerable NaturalRockTypesIn(int tile) Rand.Seed = tile; List list = (from d in DefDatabase.AllDefs where d.category == ThingCategory.Building && d.building.isNaturalRock && !d.building.isResourceRock - select d).ToList(); + select d).ToList(); int num = Rand.RangeInclusive(2, 3); if (num > list.Count) { num = list.Count; } List list2 = new List(); - for (int i = 0; i < num; i++) + for (int num2 = 0; num2 < num; num2++) { - ThingDef item = list.RandomElement(); + ThingDef item = list.RandomElement(); list.Remove(item); list2.Add(item); } diff --git a/Assembly-CSharp/RimWorld.Planet/WorldAltitudeOffsets.cs b/Assembly-CSharp/RimWorld.Planet/WorldAltitudeOffsets.cs index 94637cd6c..aa7cf25f8 100644 --- a/Assembly-CSharp/RimWorld.Planet/WorldAltitudeOffsets.cs +++ b/Assembly-CSharp/RimWorld.Planet/WorldAltitudeOffsets.cs @@ -1,5 +1,3 @@ -using System; - namespace RimWorld.Planet { public static class WorldAltitudeOffsets diff --git a/Assembly-CSharp/RimWorld.Planet/WorldCameraDriver.cs b/Assembly-CSharp/RimWorld.Planet/WorldCameraDriver.cs index 94d1a8ce4..ceaf1de28 100644 --- a/Assembly-CSharp/RimWorld.Planet/WorldCameraDriver.cs +++ b/Assembly-CSharp/RimWorld.Planet/WorldCameraDriver.cs @@ -1,4 +1,3 @@ -using System; using UnityEngine; using Verse; @@ -72,7 +71,7 @@ private Camera MyCamera { get { - if (this.cachedCamera == null) + if ((Object)this.cachedCamera == (Object)null) { this.cachedCamera = base.GetComponent(); } @@ -84,7 +83,7 @@ public WorldCameraZoomRange CurrentZoom { get { - if (this.AltitudePercent < 0.025f) + if (this.AltitudePercent < 0.02500000037252903) { return WorldCameraZoomRange.Close; } @@ -145,129 +144,123 @@ public void Awake() public void OnGUI() { GUI.depth = 100; - if (LongEventHandler.ShouldWaitForEvent) + if (!LongEventHandler.ShouldWaitForEvent) { - return; - } - this.mouseCoveredByUI = false; - if (Find.WindowStack.GetWindowAt(UI.MousePositionOnUIInverted) != null) - { - this.mouseCoveredByUI = true; - } - if (!this.AnythingPreventsCameraMotion) - { - if (Event.current.type == EventType.MouseDrag && Event.current.button == 2) - { - this.mouseDragVect = Event.current.delta; - Event.current.Use(); - PlayerKnowledgeDatabase.KnowledgeDemonstrated(ConceptDefOf.WorldCameraMovement, KnowledgeAmount.FrameInteraction); - } - float num = 0f; - if (Event.current.type == EventType.ScrollWheel) - { - num -= Event.current.delta.y * 0.1f; - PlayerKnowledgeDatabase.KnowledgeDemonstrated(ConceptDefOf.WorldCameraMovement, KnowledgeAmount.SpecificInteraction); - } - if (KeyBindingDefOf.MapZoomIn.KeyDownEvent) - { - num += 2f; - PlayerKnowledgeDatabase.KnowledgeDemonstrated(ConceptDefOf.WorldCameraMovement, KnowledgeAmount.SpecificInteraction); - } - if (KeyBindingDefOf.MapZoomOut.KeyDownEvent) - { - num -= 2f; - PlayerKnowledgeDatabase.KnowledgeDemonstrated(ConceptDefOf.WorldCameraMovement, KnowledgeAmount.SpecificInteraction); - } - this.desiredAltitude -= num * 2.6f * this.altitude / 12f; - this.desiredAltitude = Mathf.Clamp(this.desiredAltitude, 125f, 1100f); - this.desiredRotation = Vector2.zero; - if (KeyBindingDefOf.MapDollyLeft.IsDown) - { - this.desiredRotation.x = -170f; - PlayerKnowledgeDatabase.KnowledgeDemonstrated(ConceptDefOf.WorldCameraMovement, KnowledgeAmount.SpecificInteraction); - } - if (KeyBindingDefOf.MapDollyRight.IsDown) - { - this.desiredRotation.x = 170f; - PlayerKnowledgeDatabase.KnowledgeDemonstrated(ConceptDefOf.WorldCameraMovement, KnowledgeAmount.SpecificInteraction); - } - if (KeyBindingDefOf.MapDollyUp.IsDown) - { - this.desiredRotation.y = 170f; - PlayerKnowledgeDatabase.KnowledgeDemonstrated(ConceptDefOf.WorldCameraMovement, KnowledgeAmount.SpecificInteraction); - } - if (KeyBindingDefOf.MapDollyDown.IsDown) + this.mouseCoveredByUI = false; + if (Find.WindowStack.GetWindowAt(UI.MousePositionOnUIInverted) != null) { - this.desiredRotation.y = -170f; - PlayerKnowledgeDatabase.KnowledgeDemonstrated(ConceptDefOf.WorldCameraMovement, KnowledgeAmount.SpecificInteraction); + this.mouseCoveredByUI = true; } - if (this.mouseDragVect != Vector2.zero) + if (!this.AnythingPreventsCameraMotion) { - this.mouseDragVect *= CameraDriver.HitchReduceFactor; - this.mouseDragVect.x = this.mouseDragVect.x * -1f; - this.desiredRotation += this.mouseDragVect * 25f; - this.mouseDragVect = Vector2.zero; + if (Event.current.type == EventType.MouseDrag && Event.current.button == 2) + { + this.mouseDragVect = Event.current.delta; + Event.current.Use(); + PlayerKnowledgeDatabase.KnowledgeDemonstrated(ConceptDefOf.WorldCameraMovement, KnowledgeAmount.FrameInteraction); + } + float num = 0f; + if (Event.current.type == EventType.ScrollWheel) + { + float num2 = num; + Vector2 delta = Event.current.delta; + num = (float)(num2 - delta.y * 0.10000000149011612); + PlayerKnowledgeDatabase.KnowledgeDemonstrated(ConceptDefOf.WorldCameraMovement, KnowledgeAmount.SpecificInteraction); + } + if (KeyBindingDefOf.MapZoomIn.KeyDownEvent) + { + num = (float)(num + 2.0); + PlayerKnowledgeDatabase.KnowledgeDemonstrated(ConceptDefOf.WorldCameraMovement, KnowledgeAmount.SpecificInteraction); + } + if (KeyBindingDefOf.MapZoomOut.KeyDownEvent) + { + num = (float)(num - 2.0); + PlayerKnowledgeDatabase.KnowledgeDemonstrated(ConceptDefOf.WorldCameraMovement, KnowledgeAmount.SpecificInteraction); + } + this.desiredAltitude -= (float)(num * 2.5999999046325684 * this.altitude / 12.0); + this.desiredAltitude = Mathf.Clamp(this.desiredAltitude, 125f, 1100f); + this.desiredRotation = Vector2.zero; + if (KeyBindingDefOf.MapDollyLeft.IsDown) + { + this.desiredRotation.x = -170f; + PlayerKnowledgeDatabase.KnowledgeDemonstrated(ConceptDefOf.WorldCameraMovement, KnowledgeAmount.SpecificInteraction); + } + if (KeyBindingDefOf.MapDollyRight.IsDown) + { + this.desiredRotation.x = 170f; + PlayerKnowledgeDatabase.KnowledgeDemonstrated(ConceptDefOf.WorldCameraMovement, KnowledgeAmount.SpecificInteraction); + } + if (KeyBindingDefOf.MapDollyUp.IsDown) + { + this.desiredRotation.y = 170f; + PlayerKnowledgeDatabase.KnowledgeDemonstrated(ConceptDefOf.WorldCameraMovement, KnowledgeAmount.SpecificInteraction); + } + if (KeyBindingDefOf.MapDollyDown.IsDown) + { + this.desiredRotation.y = -170f; + PlayerKnowledgeDatabase.KnowledgeDemonstrated(ConceptDefOf.WorldCameraMovement, KnowledgeAmount.SpecificInteraction); + } + if (this.mouseDragVect != Vector2.zero) + { + this.mouseDragVect *= CameraDriver.HitchReduceFactor; + this.mouseDragVect.x *= -1f; + this.desiredRotation += this.mouseDragVect * 25f; + this.mouseDragVect = Vector2.zero; + } } } } public void Update() { - if (LongEventHandler.ShouldWaitForEvent) + if (!LongEventHandler.ShouldWaitForEvent) { - return; - } - if (Find.World == null) - { - this.MyCamera.gameObject.SetActive(false); - return; - } - if (!Find.WorldInterface.everReset) - { - Find.WorldInterface.Reset(); - } - Vector2 lhs = this.CalculateCurInputDollyVect(); - if (lhs != Vector2.zero) - { - float d = (this.altitude - 125f) / 975f * 0.85f + 0.15f; - this.rotationVelocity = new Vector2(lhs.x, lhs.y) * d; - } - if (!this.AnythingPreventsCameraMotion) - { - float num = Time.deltaTime * CameraDriver.HitchReduceFactor; - this.sphereRotation *= Quaternion.AngleAxis(this.rotationVelocity.x * num * 0.3f, this.MyCamera.transform.up); - this.sphereRotation *= Quaternion.AngleAxis(-this.rotationVelocity.y * num * 0.3f, this.MyCamera.transform.right); - } - if (this.rotationVelocity != Vector2.zero) - { - this.rotationVelocity *= 0.9f; - if (this.rotationVelocity.magnitude < 0.05f) + if (Find.World == null) { - this.rotationVelocity = Vector2.zero; + this.MyCamera.gameObject.SetActive(false); + } + else + { + if (!Find.WorldInterface.everReset) + { + Find.WorldInterface.Reset(); + } + Vector2 lhs = this.CalculateCurInputDollyVect(); + if (lhs != Vector2.zero) + { + float d = (float)((this.altitude - 125.0) / 975.0 * 0.85000002384185791 + 0.15000000596046448); + this.rotationVelocity = new Vector2(lhs.x, lhs.y) * d; + } + if (!this.AnythingPreventsCameraMotion) + { + float num = Time.deltaTime * CameraDriver.HitchReduceFactor; + this.sphereRotation *= Quaternion.AngleAxis((float)(this.rotationVelocity.x * num * 0.30000001192092896), this.MyCamera.transform.up); + this.sphereRotation *= Quaternion.AngleAxis((float)((0.0 - this.rotationVelocity.y) * num * 0.30000001192092896), this.MyCamera.transform.right); + } + if (this.rotationVelocity != Vector2.zero) + { + this.rotationVelocity *= 0.9f; + if (this.rotationVelocity.magnitude < 0.05000000074505806) + { + this.rotationVelocity = Vector2.zero; + } + } + float num2 = this.desiredAltitude - this.altitude; + this.altitude += (float)(num2 * 0.40000000596046448); + this.rotationAnimation_lerpFactor += (float)(Time.deltaTime * 8.0); + if (Find.PlaySettings.lockNorthUp) + { + this.RotateSoNorthIsUp(false); + this.ClampXRotation(ref this.sphereRotation); + } + this.ApplyPositionToGameObject(); } } - float num2 = this.desiredAltitude - this.altitude; - this.altitude += num2 * 0.4f; - this.rotationAnimation_lerpFactor += Time.deltaTime * 8f; - if (Find.PlaySettings.lockNorthUp) - { - this.RotateSoNorthIsUp(false); - this.ClampXRotation(ref this.sphereRotation); - } - this.ApplyPositionToGameObject(); } private void ApplyPositionToGameObject() { - Quaternion rotation; - if (this.rotationAnimation_lerpFactor < 1f) - { - rotation = Quaternion.Lerp(this.rotationAnimation_prevSphereRotation, this.sphereRotation, this.rotationAnimation_lerpFactor); - } - else - { - rotation = this.sphereRotation; - } + Quaternion rotation = (!(this.rotationAnimation_lerpFactor < 1.0)) ? this.sphereRotation : Quaternion.Lerp(this.rotationAnimation_prevSphereRotation, this.sphereRotation, this.rotationAnimation_lerpFactor); if (Find.PlaySettings.lockNorthUp) { this.ClampXRotation(ref rotation); @@ -296,25 +289,25 @@ private Vector2 CalculateCurInputDollyVect() if (!rect2.Contains(mousePositionOnUIInverted) && !rect3.Contains(mousePositionOnUIInverted) && !rect.Contains(mousePositionOnUIInverted)) { Vector2 zero = Vector2.zero; - if (mousePositionOnUI.x >= 0f && mousePositionOnUI.x < 20f) + if (mousePositionOnUI.x >= 0.0 && mousePositionOnUI.x < 20.0) { zero.x -= 125f; } - if (mousePositionOnUI.x <= (float)UI.screenWidth && mousePositionOnUI.x > (float)UI.screenWidth - 20f) + if (mousePositionOnUI.x <= (float)UI.screenWidth && mousePositionOnUI.x > (float)UI.screenWidth - 20.0) { zero.x += 125f; } - if (mousePositionOnUI.y <= (float)UI.screenHeight && mousePositionOnUI.y > (float)UI.screenHeight - 20f) + if (mousePositionOnUI.y <= (float)UI.screenHeight && mousePositionOnUI.y > (float)UI.screenHeight - 20.0) { zero.y += 125f; } - if (mousePositionOnUI.y >= 0f && mousePositionOnUI.y < this.ScreenDollyEdgeWidthBottom) + if (mousePositionOnUI.y >= 0.0 && mousePositionOnUI.y < this.ScreenDollyEdgeWidthBottom) { - if (this.mouseTouchingScreenBottomEdgeStartTime < 0f) + if (this.mouseTouchingScreenBottomEdgeStartTime < 0.0) { this.mouseTouchingScreenBottomEdgeStartTime = Time.realtimeSinceStartup; } - if (Time.realtimeSinceStartup - this.mouseTouchingScreenBottomEdgeStartTime >= 0.28f) + if (Time.realtimeSinceStartup - this.mouseTouchingScreenBottomEdgeStartTime >= 0.2800000011920929) { zero.y -= 125f; } @@ -380,7 +373,7 @@ private void ClampXRotation(ref Quaternion invRot) float altitudePercent = this.AltitudePercent; float num = Mathf.Lerp(88.6f, 78f, altitudePercent); bool flag = false; - if (eulerAngles.x <= 90f) + if (eulerAngles.x <= 90.0) { if (eulerAngles.x > num) { @@ -388,9 +381,9 @@ private void ClampXRotation(ref Quaternion invRot) flag = true; } } - else if (eulerAngles.x < 360f - num) + else if (eulerAngles.x < 360.0 - num) { - eulerAngles.x = 360f - num; + eulerAngles.x = (float)(360.0 - num); flag = true; } if (flag) diff --git a/Assembly-CSharp/RimWorld.Planet/WorldCameraManager.cs b/Assembly-CSharp/RimWorld.Planet/WorldCameraManager.cs index fb4b91e7c..776010867 100644 --- a/Assembly-CSharp/RimWorld.Planet/WorldCameraManager.cs +++ b/Assembly-CSharp/RimWorld.Planet/WorldCameraManager.cs @@ -1,4 +1,3 @@ -using System; using UnityEngine; namespace RimWorld.Planet @@ -52,32 +51,23 @@ public static WorldCameraDriver WorldCameraDriver static WorldCameraManager() { WorldCameraManager.WorldLayerName = "World"; - WorldCameraManager.WorldLayerMask = LayerMask.GetMask(new string[] - { - WorldCameraManager.WorldLayerName - }); + WorldCameraManager.WorldLayerMask = LayerMask.GetMask(WorldCameraManager.WorldLayerName); WorldCameraManager.WorldLayer = LayerMask.NameToLayer(WorldCameraManager.WorldLayerName); WorldCameraManager.WorldSkyboxLayerName = "WorldSkybox"; - WorldCameraManager.WorldSkyboxLayerMask = LayerMask.GetMask(new string[] - { - WorldCameraManager.WorldSkyboxLayerName - }); + WorldCameraManager.WorldSkyboxLayerMask = LayerMask.GetMask(WorldCameraManager.WorldSkyboxLayerName); WorldCameraManager.WorldSkyboxLayer = LayerMask.NameToLayer(WorldCameraManager.WorldSkyboxLayerName); WorldCameraManager.SkyColor = new Color(0.0627451f, 0.09019608f, 0.117647059f); WorldCameraManager.worldCameraInt = WorldCameraManager.CreateWorldCamera(); WorldCameraManager.worldSkyboxCameraInt = WorldCameraManager.CreateWorldSkyboxCamera(WorldCameraManager.worldCameraInt); - WorldCameraManager.worldCameraDriverInt = WorldCameraManager.worldCameraInt.GetComponent(); + WorldCameraManager.worldCameraDriverInt = ((Component)WorldCameraManager.worldCameraInt).GetComponent(); } private static Camera CreateWorldCamera() { - GameObject gameObject = new GameObject("WorldCamera", new Type[] - { - typeof(Camera) - }); + GameObject gameObject = new GameObject("WorldCamera", typeof(Camera)); gameObject.SetActive(false); gameObject.AddComponent(); - UnityEngine.Object.DontDestroyOnLoad(gameObject); + Object.DontDestroyOnLoad(gameObject); Camera component = gameObject.GetComponent(); component.orthographic = false; component.cullingMask = WorldCameraManager.WorldLayerMask; @@ -93,12 +83,9 @@ private static Camera CreateWorldCamera() private static Camera CreateWorldSkyboxCamera(Camera parent) { - GameObject gameObject = new GameObject("WorldSkyboxCamera", new Type[] - { - typeof(Camera) - }); + GameObject gameObject = new GameObject("WorldSkyboxCamera", typeof(Camera)); gameObject.SetActive(true); - UnityEngine.Object.DontDestroyOnLoad(gameObject); + Object.DontDestroyOnLoad(gameObject); Camera component = gameObject.GetComponent(); component.transform.SetParent(parent.transform); component.orthographic = false; diff --git a/Assembly-CSharp/RimWorld.Planet/WorldCameraZoomRange.cs b/Assembly-CSharp/RimWorld.Planet/WorldCameraZoomRange.cs index 84d3b7f68..d7358c9b0 100644 --- a/Assembly-CSharp/RimWorld.Planet/WorldCameraZoomRange.cs +++ b/Assembly-CSharp/RimWorld.Planet/WorldCameraZoomRange.cs @@ -1,10 +1,8 @@ -using System; - namespace RimWorld.Planet { public enum WorldCameraZoomRange : byte { - Close, - Far + Close = 0, + Far = 1 } } diff --git a/Assembly-CSharp/RimWorld.Planet/WorldComponent.cs b/Assembly-CSharp/RimWorld.Planet/WorldComponent.cs index d422b27b8..f92ae8c87 100644 --- a/Assembly-CSharp/RimWorld.Planet/WorldComponent.cs +++ b/Assembly-CSharp/RimWorld.Planet/WorldComponent.cs @@ -1,4 +1,3 @@ -using System; using Verse; namespace RimWorld.Planet diff --git a/Assembly-CSharp/RimWorld.Planet/WorldDebugDrawer.cs b/Assembly-CSharp/RimWorld.Planet/WorldDebugDrawer.cs index 9fa56ea17..ea13f8684 100644 --- a/Assembly-CSharp/RimWorld.Planet/WorldDebugDrawer.cs +++ b/Assembly-CSharp/RimWorld.Planet/WorldDebugDrawer.cs @@ -1,4 +1,3 @@ -using System; using System.Collections.Generic; using UnityEngine; using Verse; @@ -15,7 +14,7 @@ public class WorldDebugDrawer private List debugLines = new List(); - public void FlashTile(int tile, float colorPct = 0f, string text = null) + public void FlashTile(int tile, float colorPct = 0, string text = null) { DebugTile debugTile = new DebugTile(); debugTile.tile = tile; @@ -66,22 +65,22 @@ public void WorldDebugDrawerUpdate() public void WorldDebugDrawerTick() { - for (int i = this.debugTiles.Count - 1; i >= 0; i--) + for (int num = this.debugTiles.Count - 1; num >= 0; num--) { - DebugTile debugTile = this.debugTiles[i]; + DebugTile debugTile = this.debugTiles[num]; debugTile.ticksLeft--; if (debugTile.ticksLeft <= 0) { - this.debugTiles.RemoveAt(i); + this.debugTiles.RemoveAt(num); } } - for (int j = this.debugLines.Count - 1; j >= 0; j--) + for (int num2 = this.debugLines.Count - 1; num2 >= 0; num2--) { - DebugWorldLine debugWorldLine = this.debugLines[j]; + DebugWorldLine debugWorldLine = this.debugLines[num2]; debugWorldLine.ticksLeft--; if (debugWorldLine.ticksLeft <= 0) { - this.debugLines.RemoveAt(j); + this.debugLines.RemoveAt(num2); } } } @@ -93,7 +92,7 @@ public void WorldDebugDrawerOnGUI() GUI.color = new Color(1f, 1f, 1f, 0.5f); for (int i = 0; i < this.debugTiles.Count; i++) { - if (this.debugTiles[i].DistanceToCamera <= 39f) + if (!(this.debugTiles[i].DistanceToCamera > 39.0)) { this.debugTiles[i].OnGUI(); } diff --git a/Assembly-CSharp/RimWorld.Planet/WorldDebugMatsSpectrum.cs b/Assembly-CSharp/RimWorld.Planet/WorldDebugMatsSpectrum.cs index 6205a1e0d..79be9f372 100644 --- a/Assembly-CSharp/RimWorld.Planet/WorldDebugMatsSpectrum.cs +++ b/Assembly-CSharp/RimWorld.Planet/WorldDebugMatsSpectrum.cs @@ -1,4 +1,3 @@ -using System; using UnityEngine; using Verse; @@ -21,7 +20,7 @@ static WorldDebugMatsSpectrum() WorldDebugMatsSpectrum.DebugSpectrum = DebugMatsSpectrum.DebugSpectrum; for (int i = 0; i < 100; i++) { - WorldDebugMatsSpectrum.spectrumMats[i] = MatsFromSpectrum.Get(WorldDebugMatsSpectrum.DebugSpectrum, (float)i / 100f, ShaderDatabase.WorldOverlayTransparent); + WorldDebugMatsSpectrum.spectrumMats[i] = MatsFromSpectrum.Get(WorldDebugMatsSpectrum.DebugSpectrum, (float)((float)i / 100.0), ShaderDatabase.WorldOverlayTransparent); } } diff --git a/Assembly-CSharp/RimWorld.Planet/WorldDragBox.cs b/Assembly-CSharp/RimWorld.Planet/WorldDragBox.cs index e2117f580..d78ddb8fa 100644 --- a/Assembly-CSharp/RimWorld.Planet/WorldDragBox.cs +++ b/Assembly-CSharp/RimWorld.Planet/WorldDragBox.cs @@ -16,7 +16,9 @@ public float LeftX { get { - return Math.Min(this.start.x, UI.MousePositionOnUIInverted.x); + float x = this.start.x; + Vector2 mousePositionOnUIInverted = UI.MousePositionOnUIInverted; + return Math.Min(x, mousePositionOnUIInverted.x); } } @@ -24,7 +26,9 @@ public float RightX { get { - return Math.Max(this.start.x, UI.MousePositionOnUIInverted.x); + float x = this.start.x; + Vector2 mousePositionOnUIInverted = UI.MousePositionOnUIInverted; + return Math.Max(x, mousePositionOnUIInverted.x); } } @@ -32,7 +36,9 @@ public float BotZ { get { - return Math.Min(this.start.y, UI.MousePositionOnUIInverted.y); + float y = this.start.y; + Vector2 mousePositionOnUIInverted = UI.MousePositionOnUIInverted; + return Math.Min(y, mousePositionOnUIInverted.y); } } @@ -40,7 +46,9 @@ public float TopZ { get { - return Math.Max(this.start.y, UI.MousePositionOnUIInverted.y); + float y = this.start.y; + Vector2 mousePositionOnUIInverted = UI.MousePositionOnUIInverted; + return Math.Max(y, mousePositionOnUIInverted.y); } } @@ -56,7 +64,11 @@ public float Diagonal { get { - return (this.start - new Vector2(UI.MousePositionOnUIInverted.x, UI.MousePositionOnUIInverted.y)).magnitude; + Vector2 a = this.start; + Vector2 mousePositionOnUIInverted = UI.MousePositionOnUIInverted; + float x = mousePositionOnUIInverted.x; + Vector2 mousePositionOnUIInverted2 = UI.MousePositionOnUIInverted; + return (a - new Vector2(x, mousePositionOnUIInverted2.y)).magnitude; } } @@ -64,7 +76,7 @@ public bool IsValid { get { - return this.Diagonal > 7f; + return this.Diagonal > 7.0; } } @@ -91,7 +103,11 @@ public bool Contains(WorldObject o) public bool Contains(Vector2 screenPoint) { - return screenPoint.x + 0.5f > this.LeftX && screenPoint.x - 0.5f < this.RightX && screenPoint.y + 0.5f > this.BotZ && screenPoint.y - 0.5f < this.TopZ; + if (screenPoint.x + 0.5 > this.LeftX && screenPoint.x - 0.5 < this.RightX && screenPoint.y + 0.5 > this.BotZ && screenPoint.y - 0.5 < this.TopZ) + { + return true; + } + return false; } } } diff --git a/Assembly-CSharp/RimWorld.Planet/WorldDynamicDrawManager.cs b/Assembly-CSharp/RimWorld.Planet/WorldDynamicDrawManager.cs index d760fe162..faa5d9fe2 100644 --- a/Assembly-CSharp/RimWorld.Planet/WorldDynamicDrawManager.cs +++ b/Assembly-CSharp/RimWorld.Planet/WorldDynamicDrawManager.cs @@ -39,26 +39,29 @@ public void DrawDynamicWorldObjects() this.drawingNow = true; try { - foreach (WorldObject current in this.drawObjects) + HashSet.Enumerator enumerator = this.drawObjects.GetEnumerator(); + try { - try + while (enumerator.MoveNext()) { - if (!current.def.expandingIcon || ExpandableWorldObjectsUtility.TransitionPct < 1f) + WorldObject current = enumerator.Current; + try { - current.Draw(); + if (!current.def.expandingIcon || !(ExpandableWorldObjectsUtility.TransitionPct >= 1.0)) + { + current.Draw(); + } } - } - catch (Exception ex) - { - Log.Error(string.Concat(new object[] + catch (Exception ex) { - "Exception drawing ", - current, - ": ", - ex - })); + Log.Error("Exception drawing " + current + ": " + ex); + } } } + finally + { + ((IDisposable)(object)enumerator).Dispose(); + } } catch (Exception arg) { diff --git a/Assembly-CSharp/RimWorld.Planet/WorldGenData.cs b/Assembly-CSharp/RimWorld.Planet/WorldGenData.cs index 3d8fa9409..a6ce77527 100644 --- a/Assembly-CSharp/RimWorld.Planet/WorldGenData.cs +++ b/Assembly-CSharp/RimWorld.Planet/WorldGenData.cs @@ -1,4 +1,3 @@ -using System; using System.Collections.Generic; using Verse; diff --git a/Assembly-CSharp/RimWorld.Planet/WorldGenStep_AncientRoads.cs b/Assembly-CSharp/RimWorld.Planet/WorldGenStep_AncientRoads.cs index 8228843b8..76af5f7e2 100644 --- a/Assembly-CSharp/RimWorld.Planet/WorldGenStep_AncientRoads.cs +++ b/Assembly-CSharp/RimWorld.Planet/WorldGenStep_AncientRoads.cs @@ -31,30 +31,39 @@ private void GenerateAncientRoads() { Find.WorldPathGrid.RecalculateAllPerceivedPathCosts(Season.Spring.GetMiddleYearPct(0f)); List> list = this.GenerateProspectiveRoads(); - list.Sort((List lhs, List rhs) => -lhs.Count.CompareTo(rhs.Count)); + list.Sort((Comparison>)((List lhs, List rhs) => -lhs.Count.CompareTo(rhs.Count))); HashSet used = new HashSet(); for (int i = 0; i < list.Count; i++) { - if (!list[i].Any((int elem) => used.Contains(elem))) + if (!list[i].Any((Predicate)((int elem) => used.Contains(elem)))) { if (list[i].Count < 4) { break; } - foreach (int current in list[i]) + List.Enumerator enumerator = list[i].GetEnumerator(); + try { - used.Add(current); + while (enumerator.MoveNext()) + { + int current = enumerator.Current; + used.Add(current); + } + } + finally + { + ((IDisposable)(object)enumerator).Dispose(); } for (int j = 0; j < list[i].Count - 1; j++) { float num = Find.WorldGrid.ApproxDistanceInTiles(list[i][j], list[i][j + 1]) * this.maximumSegmentCurviness; - float costCutoff = num * 12000f; - using (WorldPath worldPath = Find.WorldPathFinder.FindPath(list[i][j], list[i][j + 1], null, (float cost) => cost > costCutoff)) + float costCutoff = (float)(num * 12000.0); + using (WorldPath worldPath = Find.WorldPathFinder.FindPath(list[i][j], list[i][j + 1], null, (Func)((float cost) => cost > costCutoff))) { if (worldPath != null && worldPath != WorldPath.NotFound) { List nodesReversed = worldPath.NodesReversed; - if ((float)nodesReversed.Count <= Find.WorldGrid.ApproxDistanceInTiles(list[i][j], list[i][j + 1]) * this.maximumSegmentCurviness) + if (!((float)nodesReversed.Count > Find.WorldGrid.ApproxDistanceInTiles(list[i][j], list[i][j + 1]) * this.maximumSegmentCurviness)) { for (int k = 0; k < nodesReversed.Count - 1; k++) { @@ -92,15 +101,16 @@ private List> GenerateProspectiveRoads() { list3 = (from idx in list3 where idx != current && Math.Abs(Find.World.grid.GetHeadingFromTo(current, idx) - ang) < this.maximumSiteCurve - select idx).ToList(); - if (list3.Count == 0) + select idx).ToList(); + if (list3.Count != 0) { - break; + int num = list3.MinBy((Func)((int idx) => Find.World.grid.ApproxDistanceInTiles(current, idx))); + ang = Find.World.grid.GetHeadingFromTo(current, num); + current = num; + list2.Add(current); + continue; } - int num = list3.MinBy((int idx) => Find.World.grid.ApproxDistanceInTiles(current, idx)); - ang = Find.World.grid.GetHeadingFromTo(current, num); - current = num; - list2.Add(current); + break; } list.Add(list2); } diff --git a/Assembly-CSharp/RimWorld.Planet/WorldGenStep_AncientSites.cs b/Assembly-CSharp/RimWorld.Planet/WorldGenStep_AncientSites.cs index 8566a0dd0..6cc06d8e0 100644 --- a/Assembly-CSharp/RimWorld.Planet/WorldGenStep_AncientSites.cs +++ b/Assembly-CSharp/RimWorld.Planet/WorldGenStep_AncientSites.cs @@ -1,4 +1,3 @@ -using System; using Verse; namespace RimWorld.Planet @@ -23,8 +22,8 @@ public override void GenerateFromScribe(string seed) private void GenerateAncientSites() { - int num = GenMath.RoundRandom((float)Find.WorldGrid.TilesCount / 100000f * this.ancientSitesPer100kTiles.RandomInRange); - for (int i = 0; i < num; i++) + int num = GenMath.RoundRandom((float)((float)Find.WorldGrid.TilesCount / 100000.0 * this.ancientSitesPer100kTiles.RandomInRange)); + for (int num2 = 0; num2 < num; num2++) { Find.World.genData.ancientSites.Add(TileFinder.RandomFactionBaseTileFor(null, false)); } diff --git a/Assembly-CSharp/RimWorld.Planet/WorldGenStep_Components.cs b/Assembly-CSharp/RimWorld.Planet/WorldGenStep_Components.cs index 20004d4bd..01774afc0 100644 --- a/Assembly-CSharp/RimWorld.Planet/WorldGenStep_Components.cs +++ b/Assembly-CSharp/RimWorld.Planet/WorldGenStep_Components.cs @@ -1,4 +1,3 @@ -using System; using Verse; namespace RimWorld.Planet diff --git a/Assembly-CSharp/RimWorld.Planet/WorldGenStep_Factions.cs b/Assembly-CSharp/RimWorld.Planet/WorldGenStep_Factions.cs index 5225d9d71..86f093bd4 100644 --- a/Assembly-CSharp/RimWorld.Planet/WorldGenStep_Factions.cs +++ b/Assembly-CSharp/RimWorld.Planet/WorldGenStep_Factions.cs @@ -1,4 +1,3 @@ -using System; using Verse; namespace RimWorld.Planet diff --git a/Assembly-CSharp/RimWorld.Planet/WorldGenStep_Lakes.cs b/Assembly-CSharp/RimWorld.Planet/WorldGenStep_Lakes.cs index 4a2a779aa..909a22a52 100644 --- a/Assembly-CSharp/RimWorld.Planet/WorldGenStep_Lakes.cs +++ b/Assembly-CSharp/RimWorld.Planet/WorldGenStep_Lakes.cs @@ -25,24 +25,21 @@ private void GenerateLakes() List oceanChunk = new List(); for (int i = 0; i < grid.TilesCount; i++) { - if (!touched[i]) + if (!touched[i] && grid[i].biome == BiomeDefOf.Ocean) { - if (grid[i].biome == BiomeDefOf.Ocean) + Find.WorldFloodFiller.FloodFill(i, (Predicate)((int tid) => grid[tid].biome == BiomeDefOf.Ocean), (Action)delegate(int tid) { - Find.WorldFloodFiller.FloodFill(i, (int tid) => grid[tid].biome == BiomeDefOf.Ocean, delegate(int tid) - { - oceanChunk.Add(tid); - touched[tid] = true; - }, 2147483647); - if (oceanChunk.Count <= 15) + oceanChunk.Add(tid); + touched[tid] = true; + }, 2147483647); + if (oceanChunk.Count <= 15) + { + for (int j = 0; j < oceanChunk.Count; j++) { - for (int j = 0; j < oceanChunk.Count; j++) - { - grid[oceanChunk[j]].biome = BiomeDefOf.Lake; - } + grid[oceanChunk[j]].biome = BiomeDefOf.Lake; } - oceanChunk.Clear(); } + oceanChunk.Clear(); } } } diff --git a/Assembly-CSharp/RimWorld.Planet/WorldGenStep_Rivers.cs b/Assembly-CSharp/RimWorld.Planet/WorldGenStep_Rivers.cs index 3e59494cf..db2c97a19 100644 --- a/Assembly-CSharp/RimWorld.Planet/WorldGenStep_Rivers.cs +++ b/Assembly-CSharp/RimWorld.Planet/WorldGenStep_Rivers.cs @@ -67,7 +67,7 @@ private void GenerateRivers() Find.WorldPathGrid.RecalculateAllPerceivedPathCosts(-1f); List coastalWaterTiles = this.GetCoastalWaterTiles(); List neighbors = new List(); - List[] array = Find.WorldPathFinder.FloodPathsWithCostForTree(coastalWaterTiles, delegate(int st, int ed) + List[] array = Find.WorldPathFinder.FloodPathsWithCostForTree(coastalWaterTiles, (Func)delegate(int st, int ed) { Tile tile = Find.WorldGrid[ed]; Tile tile2 = Find.WorldGrid[st]; @@ -86,7 +86,7 @@ private void GenerateRivers() num2 = 2f; } return Mathf.RoundToInt(num2 * WorldGenStep_Rivers.ElevationChangeCost.Evaluate(WorldGenStep_Rivers.GetImpliedElevation(tile2) - WorldGenStep_Rivers.GetImpliedElevation(tile))); - }, (int tid) => Find.WorldGrid[tid].WaterCovered, null); + }, (Func)((int tid) => Find.WorldGrid[tid].WaterCovered), null); float[] flow = new float[array.Length]; for (int i = 0; i < coastalWaterTiles.Count; i++) { @@ -165,7 +165,7 @@ private void CreateRivers(float[] flow, List[] riverPaths, int index) float targetFlow = flow[list[i]]; RiverDef riverDef = (from rd in DefDatabase.AllDefs where rd.spawnFlowThreshold > 0 && (float)rd.spawnFlowThreshold <= targetFlow - select rd).MaxByWithFallback((RiverDef rd) => rd.spawnFlowThreshold, null); + select rd).MaxByWithFallback((Func)((RiverDef rd) => rd.spawnFlowThreshold), (RiverDef)null); if (riverDef != null && Rand.Value < riverDef.spawnChance) { Find.WorldGrid.OverlayRiver(index, list[i], riverDef); @@ -176,32 +176,38 @@ private void CreateRivers(float[] flow, List[] riverPaths, int index) private void ExtendRiver(float[] flow, List[] riverPaths, int index, RiverDef incomingRiver) { - if (riverPaths[index] == null) - { - return; - } - int bestOutput = riverPaths[index].MaxBy((int ni) => flow[ni]); - RiverDef riverDef = incomingRiver; - while (riverDef != null && (float)riverDef.degradeThreshold > flow[bestOutput]) - { - riverDef = riverDef.degradeChild; - } - if (riverDef != null) - { - Find.WorldGrid.OverlayRiver(index, bestOutput, riverDef); - this.ExtendRiver(flow, riverPaths, bestOutput, riverDef); - } - if (incomingRiver.branches != null) + if (riverPaths[index] != null) { - foreach (int alternateRiver in from ni in riverPaths[index] - where ni != bestOutput - select ni) + int bestOutput = riverPaths[index].MaxBy((Func)((int ni) => flow[ni])); + RiverDef riverDef = incomingRiver; + while (riverDef != null && (float)riverDef.degradeThreshold > flow[bestOutput]) + { + riverDef = riverDef.degradeChild; + } + if (riverDef != null) + { + Find.WorldGrid.OverlayRiver(index, bestOutput, riverDef); + this.ExtendRiver(flow, riverPaths, bestOutput, riverDef); + } + if (incomingRiver.branches != null) { - RiverDef.Branch branch2 = incomingRiver.branches.Where((RiverDef.Branch branch) => (float)branch.minFlow <= flow[alternateRiver]).MaxByWithFallback((RiverDef.Branch branch) => branch.minFlow, null); - if (branch2 != null && Rand.Value < branch2.chance) + using (IEnumerator enumerator = (from ni in riverPaths[index] + where ni != bestOutput + select ni).GetEnumerator()) { - Find.WorldGrid.OverlayRiver(index, alternateRiver, branch2.child); - this.ExtendRiver(flow, riverPaths, alternateRiver, branch2.child); + int alternateRiver; + while (enumerator.MoveNext()) + { + alternateRiver = enumerator.Current; + RiverDef.Branch branch2 = (from branch in incomingRiver.branches + where (float)branch.minFlow <= flow[alternateRiver] + select branch).MaxByWithFallback((Func)((RiverDef.Branch branch) => branch.minFlow), (RiverDef.Branch)null); + if (branch2 != null && Rand.Value < branch2.chance) + { + Find.WorldGrid.OverlayRiver(index, alternateRiver, branch2.child); + this.ExtendRiver(flow, riverPaths, alternateRiver, branch2.child); + } + } } } } @@ -209,8 +215,8 @@ private void ExtendRiver(float[] flow, List[] riverPaths, int index, RiverD public static float CalculateEvaporationConstant(float temperature) { - float num = 0.61121f * Mathf.Exp((18.678f - temperature / 234.5f) * (temperature / (257.14f + temperature))); - return num / (temperature + 273f); + float num = (float)(0.61120998859405518 * Mathf.Exp((float)((18.677999496459961 - temperature / 234.5) * (temperature / (257.1400146484375 + temperature))))); + return (float)(num / (temperature + 273.0)); } public static float CalculateRiverSurfaceArea(float flow) @@ -225,7 +231,7 @@ public static float CalculateEvaporativeArea(float flow) public static float CalculateTotalEvaporation(float flow, float temperature) { - return WorldGenStep_Rivers.CalculateEvaporationConstant(temperature) * WorldGenStep_Rivers.CalculateEvaporativeArea(flow) * 250f; + return (float)(WorldGenStep_Rivers.CalculateEvaporationConstant(temperature) * WorldGenStep_Rivers.CalculateEvaporativeArea(flow) * 250.0); } } } diff --git a/Assembly-CSharp/RimWorld.Planet/WorldGenStep_Roads.cs b/Assembly-CSharp/RimWorld.Planet/WorldGenStep_Roads.cs index 86c6b7ffe..d62875c70 100644 --- a/Assembly-CSharp/RimWorld.Planet/WorldGenStep_Roads.cs +++ b/Assembly-CSharp/RimWorld.Planet/WorldGenStep_Roads.cs @@ -19,9 +19,9 @@ private struct Link private class Connectedness { - public WorldGenStep_Roads.Connectedness parent; + public Connectedness parent; - public WorldGenStep_Roads.Connectedness Group() + public Connectedness Group() { if (this.parent == null) { @@ -62,48 +62,47 @@ public override void GenerateFromScribe(string seed) private void GenerateRoadEndpoints() { List list = (from wo in Find.WorldObjects.AllWorldObjects - where Rand.Value > 0.05f - select wo.Tile).ToList(); - int num = GenMath.RoundRandom((float)Find.WorldGrid.TilesCount / 100000f * WorldGenStep_Roads.ExtraRoadNodesPer100kTiles.RandomInRange); - for (int i = 0; i < num; i++) + where Rand.Value > 0.05000000074505806 + select wo.Tile).ToList(); + int num = GenMath.RoundRandom((float)((float)Find.WorldGrid.TilesCount / 100000.0 * WorldGenStep_Roads.ExtraRoadNodesPer100kTiles.RandomInRange)); + for (int num2 = 0; num2 < num; num2++) { list.Add(TileFinder.RandomFactionBaseTileFor(null, false)); } List list2 = new List(); - for (int j = 0; j < list.Count; j++) + for (int i = 0; i < list.Count; i++) { - int num2 = Mathf.Max(0, WorldGenStep_Roads.RoadDistanceFromSettlement.RandomInRange); - int num3 = list[j]; - for (int k = 0; k < num2; k++) + int num3 = Mathf.Max(0, WorldGenStep_Roads.RoadDistanceFromSettlement.RandomInRange); + int num4 = list[i]; + for (int num5 = 0; num5 < num3; num5++) { - Find.WorldGrid.GetTileNeighbors(num3, list2); - num3 = list2.RandomElement(); + Find.WorldGrid.GetTileNeighbors(num4, list2); + num4 = list2.RandomElement(); } - if (Find.WorldReachability.CanReach(list[j], num3)) + if (Find.WorldReachability.CanReach(list[i], num4)) { - list[j] = num3; + list[i] = num4; } } - list = list.Distinct().ToList(); - Find.World.genData.roadNodes = list; + list = (Find.World.genData.roadNodes = list.Distinct().ToList()); } private void GenerateRoadNetwork() { Find.WorldPathGrid.RecalculateAllPerceivedPathCosts(Season.Spring.GetMiddleYearPct(0f)); - List linkProspective = this.GenerateProspectiveLinks(Find.World.genData.roadNodes); - List linkFinal = this.GenerateFinalLinks(linkProspective, Find.World.genData.roadNodes.Count); + List linkProspective = this.GenerateProspectiveLinks(Find.World.genData.roadNodes); + List linkFinal = this.GenerateFinalLinks(linkProspective, Find.World.genData.roadNodes.Count); this.DrawLinksOnWorld(linkFinal, Find.World.genData.roadNodes); } - private List GenerateProspectiveLinks(List indexToTile) + private List GenerateProspectiveLinks(List indexToTile) { Dictionary tileToIndexLookup = new Dictionary(); for (int i = 0; i < indexToTile.Count; i++) { tileToIndexLookup[indexToTile[i]] = i; } - List linkProspective = new List(); + List linkProspective = new List(); List list = new List(); int srcIndex; for (srcIndex = 0; srcIndex < indexToTile.Count; srcIndex++) @@ -112,13 +111,13 @@ private void GenerateRoadNetwork() list.Clear(); list.Add(srcTile); int found = 0; - WorldPathFinder arg_D8_0 = Find.WorldPathFinder; - Func terminator = delegate(int tile, float distance) + WorldPathFinder worldPathFinder = Find.WorldPathFinder; + Func terminator = (Func)delegate(int tile, float distance) { if (tile != srcTile && tileToIndexLookup.ContainsKey(tile)) { found++; - linkProspective.Add(new WorldGenStep_Roads.Link + linkProspective.Add(new Link { distance = distance, indexA = srcIndex, @@ -127,69 +126,62 @@ private void GenerateRoadNetwork() } return found >= 8; }; - arg_D8_0.FloodPathsWithCost(list, (int src, int dst) => WorldPathFinder.StandardPathCost(src, dst, null), null, terminator); + worldPathFinder.FloodPathsWithCost(list, (Func)((int src, int dst) => WorldPathFinder.StandardPathCost(src, dst, null)), null, terminator); } - linkProspective.Sort((WorldGenStep_Roads.Link lhs, WorldGenStep_Roads.Link rhs) => lhs.distance.CompareTo(rhs.distance)); + linkProspective.Sort((Comparison)((Link lhs, Link rhs) => lhs.distance.CompareTo(rhs.distance))); return linkProspective; } - private List GenerateFinalLinks(List linkProspective, int endpointCount) + private List GenerateFinalLinks(List linkProspective, int endpointCount) { - List list = new List(); - for (int i = 0; i < endpointCount; i++) + List list = new List(); + for (int num = 0; num < endpointCount; num++) { - list.Add(new WorldGenStep_Roads.Connectedness()); + list.Add(new Connectedness()); } - List list2 = new List(); - int j = 0; - while (j < linkProspective.Count) + List list2 = new List(); + for (int i = 0; i < linkProspective.Count; i++) { - WorldGenStep_Roads.Link prospective = linkProspective[j]; - if (list[prospective.indexA].Group() != list[prospective.indexB].Group()) + Link prospective = linkProspective[i]; + if (list[prospective.indexA].Group() != list[prospective.indexB].Group() || (!(Rand.Value > 0.014999999664723873) && !list2.Any((Predicate)((Link link) => link.indexB == prospective.indexA && link.indexA == prospective.indexB)))) { - goto IL_A9; - } - if (Rand.Value <= 0.015f) - { - if (!list2.Any((WorldGenStep_Roads.Link link) => link.indexB == prospective.indexA && link.indexA == prospective.indexB)) + if (Rand.Value > 0.10000000149011612) { - goto IL_A9; + list2.Add(prospective); + } + if (list[prospective.indexA].Group() != list[prospective.indexB].Group()) + { + Connectedness parent = list[prospective.indexA].Group().parent = new Connectedness(); + list[prospective.indexB].Group().parent = parent; } } - IL_13B: - j++; - continue; - IL_A9: - if (Rand.Value > 0.1f) - { - list2.Add(prospective); - } - if (list[prospective.indexA].Group() != list[prospective.indexB].Group()) - { - WorldGenStep_Roads.Connectedness parent = new WorldGenStep_Roads.Connectedness(); - list[prospective.indexA].Group().parent = parent; - list[prospective.indexB].Group().parent = parent; - goto IL_13B; - } - goto IL_13B; } return list2; } - private void DrawLinksOnWorld(List linkFinal, List indexToTile) + private void DrawLinksOnWorld(List linkFinal, List indexToTile) { - foreach (WorldGenStep_Roads.Link current in linkFinal) + List.Enumerator enumerator = linkFinal.GetEnumerator(); + try { - WorldPath worldPath = Find.WorldPathFinder.FindPath(indexToTile[current.indexA], indexToTile[current.indexB], null, null); - List nodesReversed = worldPath.NodesReversed; - RoadDef roadDef = (from rd in DefDatabase.AllDefsListForReading - where !rd.ancientOnly - select rd).RandomElementWithFallback(null); - for (int i = 0; i < nodesReversed.Count - 1; i++) + while (enumerator.MoveNext()) { - Find.WorldGrid.OverlayRoad(nodesReversed[i], nodesReversed[i + 1], roadDef); + Link current = enumerator.Current; + WorldPath worldPath = Find.WorldPathFinder.FindPath(indexToTile[current.indexA], indexToTile[current.indexB], null, null); + List nodesReversed = worldPath.NodesReversed; + RoadDef roadDef = (from rd in DefDatabase.AllDefsListForReading + where !rd.ancientOnly + select rd).RandomElementWithFallback(null); + for (int i = 0; i < nodesReversed.Count - 1; i++) + { + Find.WorldGrid.OverlayRoad(nodesReversed[i], nodesReversed[i + 1], roadDef); + } + worldPath.ReleaseToPool(); } - worldPath.ReleaseToPool(); + } + finally + { + ((IDisposable)(object)enumerator).Dispose(); } } } diff --git a/Assembly-CSharp/RimWorld.Planet/WorldGenStep_Terrain.cs b/Assembly-CSharp/RimWorld.Planet/WorldGenStep_Terrain.cs index 46feff504..79c4243a9 100644 --- a/Assembly-CSharp/RimWorld.Planet/WorldGenStep_Terrain.cs +++ b/Assembly-CSharp/RimWorld.Planet/WorldGenStep_Terrain.cs @@ -118,9 +118,9 @@ private void GenerateGridIntoWorld() List tiles = Find.WorldGrid.tiles; tiles.Clear(); int tilesCount = Find.WorldGrid.TilesCount; - for (int i = 0; i < tilesCount; i++) + for (int num = 0; num < tilesCount; num++) { - Tile item = this.GenerateTileFor(i); + Tile item = this.GenerateTileFor(num); tiles.Add(item); } } @@ -128,94 +128,71 @@ private void GenerateGridIntoWorld() private void SetupElevationNoise() { float freqMultiplier = WorldGenStep_Terrain.FreqMultiplier; - ModuleBase lhs = new Perlin((double)(0.035f * freqMultiplier), 2.0, 0.40000000596046448, 6, Rand.Range(0, 2147483647), QualityMode.High); - ModuleBase moduleBase = new RidgedMultifractal((double)(0.012f * freqMultiplier), 2.0, 6, Rand.Range(0, 2147483647), QualityMode.High); - ModuleBase moduleBase2 = new Perlin((double)(0.12f * freqMultiplier), 2.0, 0.5, 5, Rand.Range(0, 2147483647), QualityMode.High); - ModuleBase moduleBase3 = new Perlin((double)(0.01f * freqMultiplier), 2.0, 0.5, 5, Rand.Range(0, 2147483647), QualityMode.High); + ModuleBase lhs = new Perlin(0.035000000149011612 * freqMultiplier, 2.0, 0.40000000596046448, 6, Rand.Range(0, 2147483647), QualityMode.High); + ModuleBase lhs2 = new RidgedMultifractal(0.012000000104308128 * freqMultiplier, 2.0, 6, Rand.Range(0, 2147483647), QualityMode.High); + ModuleBase input = new Perlin(0.11999999731779099 * freqMultiplier, 2.0, 0.5, 5, Rand.Range(0, 2147483647), QualityMode.High); + ModuleBase moduleBase = new Perlin(0.0099999997764825821 * freqMultiplier, 2.0, 0.5, 5, Rand.Range(0, 2147483647), QualityMode.High); float num; - if (Find.World.PlanetCoverage < 0.55f) + if (Find.World.PlanetCoverage < 0.550000011920929) { - ModuleBase moduleBase4 = new DistanceFromPlanetViewCenter(Find.WorldGrid.viewCenter, Find.WorldGrid.viewAngle, true); - moduleBase4 = new ScaleBias(2.0, -1.0, moduleBase4); - moduleBase3 = new Blend(moduleBase3, moduleBase4, new Const(0.40000000596046448)); + ModuleBase input2 = new DistanceFromPlanetViewCenter(Find.WorldGrid.viewCenter, Find.WorldGrid.viewAngle, true); + input2 = new ScaleBias(2.0, -1.0, input2); + moduleBase = new Blend(moduleBase, input2, new Const(0.40000000596046448)); num = Rand.Range(-0.4f, -0.35f); } else { num = Rand.Range(0.15f, 0.25f); } - NoiseDebugUI.StorePlanetNoise(moduleBase3, "elevContinents"); - moduleBase2 = new ScaleBias(0.5, 0.5, moduleBase2); - moduleBase = new Multiply(moduleBase, moduleBase2); + NoiseDebugUI.StorePlanetNoise(moduleBase, "elevContinents"); + input = new ScaleBias(0.5, 0.5, input); + lhs2 = new Multiply(lhs2, input); float num2 = Rand.Range(0.4f, 0.6f); - this.noiseElevation = new Blend(lhs, moduleBase, new Const((double)num2)); - this.noiseElevation = new Blend(this.noiseElevation, moduleBase3, new Const((double)num)); - if (Find.World.PlanetCoverage < 0.9999f) + this.noiseElevation = new Blend(lhs, lhs2, new Const((double)num2)); + this.noiseElevation = new Blend(this.noiseElevation, moduleBase, new Const((double)num)); + if (Find.World.PlanetCoverage < 0.99989998340606689) { this.noiseElevation = new ConvertToIsland(Find.WorldGrid.viewCenter, Find.WorldGrid.viewAngle, this.noiseElevation); } this.noiseElevation = new ScaleBias(0.5, 0.5, this.noiseElevation); this.noiseElevation = new Power(this.noiseElevation, new Const(3.0)); NoiseDebugUI.StorePlanetNoise(this.noiseElevation, "noiseElevation"); - this.noiseElevation = new ScaleBias((double)WorldGenStep_Terrain.ElevationRange.Span, (double)WorldGenStep_Terrain.ElevationRange.min, this.noiseElevation); + double scale = (double)WorldGenStep_Terrain.ElevationRange.Span; + FloatRange elevationRange = WorldGenStep_Terrain.ElevationRange; + this.noiseElevation = new ScaleBias(scale, (double)elevationRange.min, this.noiseElevation); } private void SetupTemperatureOffsetNoise() { float freqMultiplier = WorldGenStep_Terrain.FreqMultiplier; - this.noiseTemperatureOffset = new Perlin((double)(0.018f * freqMultiplier), 2.0, 0.5, 6, Rand.Range(0, 2147483647), QualityMode.High); + this.noiseTemperatureOffset = new Perlin(0.017999999225139618 * freqMultiplier, 2.0, 0.5, 6, Rand.Range(0, 2147483647), QualityMode.High); this.noiseTemperatureOffset = new Multiply(this.noiseTemperatureOffset, new Const(4.0)); } private void SetupRainfallNoise() { float freqMultiplier = WorldGenStep_Terrain.FreqMultiplier; - ModuleBase moduleBase = new Perlin((double)(0.015f * freqMultiplier), 2.0, 0.5, 6, Rand.Range(0, 2147483647), QualityMode.High); - moduleBase = new ScaleBias(0.5, 0.5, moduleBase); - NoiseDebugUI.StorePlanetNoise(moduleBase, "basePerlin"); - ModuleBase moduleBase2 = new AbsLatitudeCurve(new SimpleCurve - { - { - 0f, - 1.12f, - true - }, - { - 25f, - 0.94f, - true - }, - { - 45f, - 0.7f, - true - }, - { - 70f, - 0.3f, - true - }, - { - 80f, - 0.05f, - true - }, - { - 90f, - 0.05f, - true - } - }, 100f); - NoiseDebugUI.StorePlanetNoise(moduleBase2, "latCurve"); - this.noiseRainfall = new Multiply(moduleBase, moduleBase2); + ModuleBase input = new Perlin(0.014999999664723873 * freqMultiplier, 2.0, 0.5, 6, Rand.Range(0, 2147483647), QualityMode.High); + input = new ScaleBias(0.5, 0.5, input); + NoiseDebugUI.StorePlanetNoise(input, "basePerlin"); + SimpleCurve simpleCurve = new SimpleCurve(); + simpleCurve.Add(0f, 1.12f, true); + simpleCurve.Add(25f, 0.94f, true); + simpleCurve.Add(45f, 0.7f, true); + simpleCurve.Add(70f, 0.3f, true); + simpleCurve.Add(80f, 0.05f, true); + simpleCurve.Add(90f, 0.05f, true); + ModuleBase moduleBase = new AbsLatitudeCurve(simpleCurve, 100f); + NoiseDebugUI.StorePlanetNoise(moduleBase, "latCurve"); + this.noiseRainfall = new Multiply(input, moduleBase); float num = 0.000222222225f; - float num2 = -500f * num; - ModuleBase moduleBase3 = new ScaleBias((double)num, (double)num2, this.noiseElevation); - moduleBase3 = new ScaleBias(-1.0, 1.0, moduleBase3); - moduleBase3 = new Clamp(0.0, 1.0, moduleBase3); - NoiseDebugUI.StorePlanetNoise(moduleBase3, "elevationRainfallEffect"); - this.noiseRainfall = new Multiply(this.noiseRainfall, moduleBase3); - Func processor = delegate(double val) + float num2 = (float)(-500.0 * num); + ModuleBase input2 = new ScaleBias((double)num, (double)num2, this.noiseElevation); + input2 = new ScaleBias(-1.0, 1.0, input2); + input2 = new Clamp(0.0, 1.0, input2); + NoiseDebugUI.StorePlanetNoise(input2, "elevationRainfallEffect"); + this.noiseRainfall = new Multiply(this.noiseRainfall, input2); + Func processor = (Func)delegate(double val) { if (val < 0.0) { @@ -246,16 +223,16 @@ private void SetupRainfallNoise() private void SetupHillinessNoise() { float freqMultiplier = WorldGenStep_Terrain.FreqMultiplier; - this.noiseMountainLines = new Perlin((double)(0.025f * freqMultiplier), 2.0, 0.5, 6, Rand.Range(0, 2147483647), QualityMode.High); - ModuleBase moduleBase = new Perlin((double)(0.06f * freqMultiplier), 2.0, 0.5, 6, Rand.Range(0, 2147483647), QualityMode.High); + this.noiseMountainLines = new Perlin(0.02500000037252903 * freqMultiplier, 2.0, 0.5, 6, Rand.Range(0, 2147483647), QualityMode.High); + ModuleBase module = new Perlin(0.059999998658895493 * freqMultiplier, 2.0, 0.5, 6, Rand.Range(0, 2147483647), QualityMode.High); this.noiseMountainLines = new Abs(this.noiseMountainLines); this.noiseMountainLines = new OneMinus(this.noiseMountainLines); - moduleBase = new Filter(moduleBase, -0.3f, 1f); - this.noiseMountainLines = new Multiply(this.noiseMountainLines, moduleBase); + module = new Filter(module, -0.3f, 1f); + this.noiseMountainLines = new Multiply(this.noiseMountainLines, module); this.noiseMountainLines = new OneMinus(this.noiseMountainLines); NoiseDebugUI.StorePlanetNoise(this.noiseMountainLines, "noiseMountainLines"); - this.noiseHillsPatchesMacro = new Perlin((double)(0.032f * freqMultiplier), 2.0, 0.5, 5, Rand.Range(0, 2147483647), QualityMode.Medium); - this.noiseHillsPatchesMicro = new Perlin((double)(0.19f * freqMultiplier), 2.0, 0.5, 6, Rand.Range(0, 2147483647), QualityMode.High); + this.noiseHillsPatchesMacro = new Perlin(0.032000001519918442 * freqMultiplier, 2.0, 0.5, 5, Rand.Range(0, 2147483647), QualityMode.Medium); + this.noiseHillsPatchesMicro = new Perlin(0.18999999761581421 * freqMultiplier, 2.0, 0.5, 6, Rand.Range(0, 2147483647), QualityMode.High); } private Tile GenerateTileFor(int tileID) @@ -264,9 +241,9 @@ private Tile GenerateTileFor(int tileID) Vector3 tileCenter = Find.WorldGrid.GetTileCenter(tileID); tile.elevation = this.noiseElevation.GetValue(tileCenter); float value = this.noiseMountainLines.GetValue(tileCenter); - if (value > 0.235f || tile.elevation <= 0f) + if (value > 0.23499999940395355 || tile.elevation <= 0.0) { - if (tile.elevation > 0f && this.noiseHillsPatchesMicro.GetValue(tileCenter) > 0.46f && this.noiseHillsPatchesMacro.GetValue(tileCenter) > -0.3f) + if (tile.elevation > 0.0 && this.noiseHillsPatchesMicro.GetValue(tileCenter) > 0.46000000834465027 && this.noiseHillsPatchesMacro.GetValue(tileCenter) > -0.30000001192092896) { if (Rand.Bool) { @@ -282,25 +259,33 @@ private Tile GenerateTileFor(int tileID) tile.hilliness = Hilliness.Flat; } } - else if (value > 0.12f) + else if (value > 0.11999999731779099) { switch (Rand.Range(0, 4)) { case 0: + { tile.hilliness = Hilliness.Flat; break; + } case 1: + { tile.hilliness = Hilliness.SmallHills; break; + } case 2: + { tile.hilliness = Hilliness.LargeHills; break; + } case 3: + { tile.hilliness = Hilliness.Mountainous; break; } + } } - else if (value > 0.0363f) + else if (value > 0.036299999803304672) { tile.hilliness = Hilliness.Mountainous; } @@ -308,7 +293,8 @@ private Tile GenerateTileFor(int tileID) { tile.hilliness = Hilliness.Impassable; } - float num = WorldGenStep_Terrain.BaseTemperatureAtLatitude(Find.WorldGrid.LongLatOf(tileID).y); + Vector2 vector = Find.WorldGrid.LongLatOf(tileID); + float num = WorldGenStep_Terrain.BaseTemperatureAtLatitude(vector.y); num -= WorldGenStep_Terrain.TemperatureReductionAtElevation(tile.elevation); num += this.noiseTemperatureOffset.GetValue(tileCenter); SimpleCurve temperatureCurve = Find.World.info.overallTemperature.GetTemperatureCurve(); @@ -350,15 +336,15 @@ private BiomeDef BiomeFrom(Tile ws) private static float FertilityFactorFromTemperature(float temp) { - if (temp < -15f) + if (temp < -15.0) { return 0f; } - if (temp < 30f) + if (temp < 30.0) { return Mathf.InverseLerp(-15f, 30f, temp); } - if (temp < 50f) + if (temp < 50.0) { return Mathf.InverseLerp(50f, 30f, temp); } @@ -367,17 +353,17 @@ private static float FertilityFactorFromTemperature(float temp) private static float BaseTemperatureAtLatitude(float lat) { - float x = Mathf.Abs(lat) / 90f; + float x = (float)(Mathf.Abs(lat) / 90.0); return WorldGenStep_Terrain.AvgTempByLatitudeCurve.Evaluate(x); } private static float TemperatureReductionAtElevation(float elev) { - if (elev < 250f) + if (elev < 250.0) { return 0f; } - float t = (elev - 250f) / 4750f; + float t = (float)((elev - 250.0) / 4750.0); return Mathf.Lerp(0f, 40f, t); } } diff --git a/Assembly-CSharp/RimWorld.Planet/WorldGenerator.cs b/Assembly-CSharp/RimWorld.Planet/WorldGenerator.cs index f97536ad1..d8a1b0d7c 100644 --- a/Assembly-CSharp/RimWorld.Planet/WorldGenerator.cs +++ b/Assembly-CSharp/RimWorld.Planet/WorldGenerator.cs @@ -20,12 +20,12 @@ public static World GenerateWorld(float planetCoverage, string seedString, Overa Current.CreatingWorld.info.seedString = seedString; Current.CreatingWorld.info.overallRainfall = overallRainfall; Current.CreatingWorld.info.overallTemperature = overallTemperature; - Current.CreatingWorld.info.name = NameGenerator.GenerateName(RulePackDefOf.NamerWorld, null, false); - foreach (WorldGenStepDef current in from gs in DefDatabase.AllDefs + Current.CreatingWorld.info.name = NameGenerator.GenerateName(RulePackDefOf.NamerWorld, (Predicate)null, false); + foreach (WorldGenStepDef item in from gs in DefDatabase.AllDefs orderby gs.order select gs) { - current.worldGenStep.GenerateFresh(seedString); + item.worldGenStep.GenerateFresh(seedString); } Current.CreatingWorld.FinalizeInit(); Find.Scenario.PostWorldGenerate(); diff --git a/Assembly-CSharp/RimWorld.Planet/WorldGlobalControls.cs b/Assembly-CSharp/RimWorld.Planet/WorldGlobalControls.cs index 9bdb83171..95ee854d6 100644 --- a/Assembly-CSharp/RimWorld.Planet/WorldGlobalControls.cs +++ b/Assembly-CSharp/RimWorld.Planet/WorldGlobalControls.cs @@ -1,4 +1,3 @@ -using System; using UnityEngine; using Verse; @@ -14,45 +13,44 @@ public class WorldGlobalControls public void WorldGlobalControlsOnGUI() { - if (Event.current.type == EventType.Layout) + if (Event.current.type != EventType.Layout) { - return; - } - float num = (float)UI.screenWidth - 200f; - float num2 = (float)UI.screenHeight - 4f; - if (Current.ProgramState == ProgramState.Playing) - { - num2 -= 35f; - } - GlobalControlsUtility.DoPlaySettings(this.rowVisibility, true, ref num2); - if (Current.ProgramState == ProgramState.Playing) - { - num2 -= 4f; - GlobalControlsUtility.DoTimespeedControls(num, 200f, ref num2); - if (Find.VisibleMap != null || Find.WorldSelector.AnyObjectOrTileSelected) + float num = (float)((float)UI.screenWidth - 200.0); + float num2 = (float)((float)UI.screenHeight - 4.0); + if (Current.ProgramState == ProgramState.Playing) { - num2 -= 4f; - GlobalControlsUtility.DoDate(num, 200f, ref num2); + num2 = (float)(num2 - 35.0); + } + GlobalControlsUtility.DoPlaySettings(this.rowVisibility, true, ref num2); + if (Current.ProgramState == ProgramState.Playing) + { + num2 = (float)(num2 - 4.0); + GlobalControlsUtility.DoTimespeedControls(num, 200f, ref num2); + if (Find.VisibleMap != null || Find.WorldSelector.AnyObjectOrTileSelected) + { + num2 = (float)(num2 - 4.0); + GlobalControlsUtility.DoDate(num, 200f, ref num2); + } + float num3 = 230f; + float num4 = Find.World.gameConditionManager.TotalHeightAt((float)(num3 - 15.0)); + Rect rect = new Rect((float)(num - 30.0), num2 - num4, num3, num4); + Find.World.gameConditionManager.DoConditionsUI(rect); + num2 -= rect.height; + } + if (Prefs.ShowRealtimeClock) + { + GlobalControlsUtility.DoRealtimeClock(num, 200f, ref num2); + } + Find.WorldRoutePlanner.DoRoutePlannerButton(ref num2); + if (!Find.PlaySettings.lockNorthUp) + { + CompassWidget.CompassOnGUI(ref num2); + } + if (Current.ProgramState == ProgramState.Playing) + { + num2 = (float)(num2 - 10.0); + Find.LetterStack.LettersOnGUI(num2); } - float num3 = 230f; - float num4 = Find.World.gameConditionManager.TotalHeightAt(num3 - 15f); - Rect rect = new Rect(num - 30f, num2 - num4, num3, num4); - Find.World.gameConditionManager.DoConditionsUI(rect); - num2 -= rect.height; - } - if (Prefs.ShowRealtimeClock) - { - GlobalControlsUtility.DoRealtimeClock(num, 200f, ref num2); - } - Find.WorldRoutePlanner.DoRoutePlannerButton(ref num2); - if (!Find.PlaySettings.lockNorthUp) - { - CompassWidget.CompassOnGUI(ref num2); - } - if (Current.ProgramState == ProgramState.Playing) - { - num2 -= 10f; - Find.LetterStack.LettersOnGUI(num2); } } } diff --git a/Assembly-CSharp/RimWorld.Planet/WorldGrid.cs b/Assembly-CSharp/RimWorld.Planet/WorldGrid.cs index 75e576dcd..bc488fb1f 100644 --- a/Assembly-CSharp/RimWorld.Planet/WorldGrid.cs +++ b/Assembly-CSharp/RimWorld.Planet/WorldGrid.cs @@ -61,9 +61,9 @@ public List TileIndices { int tilesCount = this.TilesCount; this.tileIndices = new List(); - for (int i = 0; i < tilesCount; i++) + for (int num = 0; num < tilesCount; num++) { - this.tileIndices.Add(i); + this.tileIndices.Add(num); } } return this.tileIndices; @@ -87,14 +87,14 @@ public WorldGrid() public bool InBounds(int tileID) { - return (ulong)tileID < (ulong)((long)this.TilesCount); + return (uint)tileID < this.TilesCount; } public Vector2 LongLatOf(int tileID) { Vector3 tileCenter = this.GetTileCenter(tileID); - float x = Mathf.Atan2(tileCenter.x, -tileCenter.z) * 57.29578f; - float y = Mathf.Asin(tileCenter.y / 100f) * 57.29578f; + float x = (float)(Mathf.Atan2(tileCenter.x, (float)(0.0 - tileCenter.z)) * 57.295780181884766); + float y = (float)(Mathf.Asin((float)(tileCenter.y / 100.0)) * 57.295780181884766); return new Vector2(x, y); } @@ -105,17 +105,17 @@ public float GetHeadingFromTo(Vector3 from, Vector3 to) return 0f; } Vector3 northPolePos = this.NorthPolePos; - Vector3 from2; - Vector3 rhs; + Vector3 from2 = default(Vector3); + Vector3 rhs = default(Vector3); WorldRendererUtility.GetTangentialVectorFacing(from, northPolePos, out from2, out rhs); - Vector3 vector; - Vector3 vector2; + Vector3 vector = default(Vector3); + Vector3 vector2 = default(Vector3); WorldRendererUtility.GetTangentialVectorFacing(from, to, out vector, out vector2); float num = Vector3.Angle(from2, vector); float num2 = Vector3.Dot(vector, rhs); - if (num2 < 0f) + if (num2 < 0.0) { - num = 360f - num; + num = (float)(360.0 - num); } return num; } @@ -134,58 +134,58 @@ public float GetHeadingFromTo(int fromTileID, int toTileID) public Direction8Way GetDirection8WayFromTo(int fromTileID, int toTileID) { float headingFromTo = this.GetHeadingFromTo(fromTileID, toTileID); - if (headingFromTo >= 337.5f || headingFromTo < 22.5f) + if (!(headingFromTo >= 337.5) && !(headingFromTo < 22.5)) { - return Direction8Way.North; - } - if (headingFromTo < 67.5f) - { - return Direction8Way.NorthEast; - } - if (headingFromTo < 112.5f) - { - return Direction8Way.East; - } - if (headingFromTo < 157.5f) - { - return Direction8Way.SouthEast; - } - if (headingFromTo < 202.5f) - { - return Direction8Way.South; - } - if (headingFromTo < 247.5f) - { - return Direction8Way.SouthWest; - } - if (headingFromTo < 292.5f) - { - return Direction8Way.West; + if (headingFromTo < 67.5) + { + return Direction8Way.NorthEast; + } + if (headingFromTo < 112.5) + { + return Direction8Way.East; + } + if (headingFromTo < 157.5) + { + return Direction8Way.SouthEast; + } + if (headingFromTo < 202.5) + { + return Direction8Way.South; + } + if (headingFromTo < 247.5) + { + return Direction8Way.SouthWest; + } + if (headingFromTo < 292.5) + { + return Direction8Way.West; + } + return Direction8Way.NorthWest; } - return Direction8Way.NorthWest; + return Direction8Way.North; } public Rot4 GetRotFromTo(int fromTileID, int toTileID) { float headingFromTo = this.GetHeadingFromTo(fromTileID, toTileID); - if (headingFromTo >= 315f || headingFromTo < 45f) - { - return Rot4.North; - } - if (headingFromTo < 135f) - { - return Rot4.East; - } - if (headingFromTo < 225f) + if (!(headingFromTo >= 315.0) && !(headingFromTo < 45.0)) { - return Rot4.South; + if (headingFromTo < 135.0) + { + return Rot4.East; + } + if (headingFromTo < 225.0) + { + return Rot4.South; + } + return Rot4.West; } - return Rot4.West; + return Rot4.North; } public void GetTileVertices(int tileID, List outVerts) { - PackedListOfLists.GetList(this.tileIDToVerts_offsets, this.verts, tileID, outVerts); + PackedListOfLists.GetList(this.tileIDToVerts_offsets, this.verts, tileID, outVerts); } public void GetTileVerticesIndices(int tileID, List outVertsIndices) @@ -197,15 +197,15 @@ public void GetTileVerticesIndices(int tileID, List outVertsIndices) { num2 = this.tileIDToVerts_offsets[tileID + 1]; } - for (int i = num; i < num2; i++) + for (int num3 = num; num3 < num2; num3++) { - outVertsIndices.Add(i); + outVertsIndices.Add(num3); } } public void GetTileNeighbors(int tileID, List outNeighbors) { - PackedListOfLists.GetList(this.tileIDToNeighbors_offsets, this.tileIDToNeighbors_values, tileID, outNeighbors); + PackedListOfLists.GetList(this.tileIDToNeighbors_offsets, this.tileIDToNeighbors_values, tileID, outNeighbors); } public bool IsNeighbor(int tile1, int tile2) @@ -224,9 +224,9 @@ public Vector3 GetTileCenter(int tileID) int num = (tileID + 1 >= this.tileIDToVerts_offsets.Count) ? this.verts.Count : this.tileIDToVerts_offsets[tileID + 1]; Vector3 a = Vector3.zero; int num2 = 0; - for (int i = this.tileIDToVerts_offsets[tileID]; i < num; i++) + for (int num3 = this.tileIDToVerts_offsets[tileID]; num3 < num; num3++) { - a += this.verts[i]; + a += this.verts[num3]; num2++; } return a / (float)num2; @@ -234,17 +234,18 @@ public Vector3 GetTileCenter(int tileID) public float TileRadiusToAngle(float radius) { - return radius / (628.318542f / this.averageTileSize) * 360f; + return (float)(radius / (628.31854248046875 / this.averageTileSize) * 360.0); } public float DistanceFromEquatorNormalized(int tile) { - return Mathf.Abs(Find.WorldGrid.GetTileCenter(tile).y / 100f); + Vector3 tileCenter = Find.WorldGrid.GetTileCenter(tile); + return Mathf.Abs((float)(tileCenter.y / 100.0)); } public float ApproxDistanceInTiles(float sphericalDistance) { - return sphericalDistance * 100f / this.averageTileSize; + return (float)(sphericalDistance * 100.0 / this.averageTileSize); } public float ApproxDistanceInTiles(int firstTile, int secondTile) @@ -259,42 +260,43 @@ public void OverlayRoad(int fromTile, int toTile, RoadDef roadDef) if (roadDef == null) { Log.ErrorOnce("Attempted to remove road with overlayRoad; not supported", 90292249); - return; } - RoadDef roadDef2 = this.GetRoadDef(fromTile, toTile, false); - if (roadDef2 == roadDef) + else { - return; - } - Tile tile = this[fromTile]; - Tile tile2 = this[toTile]; - if (roadDef2 != null) - { - if (roadDef2.priority >= roadDef.priority) + RoadDef roadDef2 = this.GetRoadDef(fromTile, toTile, false); + if (roadDef2 != roadDef) { - return; + Tile tile = this[fromTile]; + Tile tile2 = this[toTile]; + if (roadDef2 != null) + { + if (roadDef2.priority >= roadDef.priority) + { + return; + } + tile.roads.RemoveAll((Predicate)((Tile.RoadLink rl) => rl.neighbor == toTile)); + tile2.roads.RemoveAll((Predicate)((Tile.RoadLink rl) => rl.neighbor == fromTile)); + } + if (tile.roads == null) + { + tile.roads = new List(); + } + if (tile2.roads == null) + { + tile2.roads = new List(); + } + tile.roads.Add(new Tile.RoadLink + { + neighbor = toTile, + road = roadDef + }); + tile2.roads.Add(new Tile.RoadLink + { + neighbor = fromTile, + road = roadDef + }); } - tile.roads.RemoveAll((Tile.RoadLink rl) => rl.neighbor == toTile); - tile2.roads.RemoveAll((Tile.RoadLink rl) => rl.neighbor == fromTile); - } - if (tile.roads == null) - { - tile.roads = new List(); - } - if (tile2.roads == null) - { - tile2.roads = new List(); } - tile.roads.Add(new Tile.RoadLink - { - neighbor = toTile, - road = roadDef - }); - tile2.roads.Add(new Tile.RoadLink - { - neighbor = fromTile, - road = roadDef - }); } public RoadDef GetRoadDef(int fromTile, int toTile, bool visibleOnly = true) @@ -312,9 +314,11 @@ public RoadDef GetRoadDef(int fromTile, int toTile, bool visibleOnly = true) } for (int i = 0; i < list.Count; i++) { - if (list[i].neighbor == toTile) + Tile.RoadLink roadLink = list[i]; + if (roadLink.neighbor == toTile) { - return list[i].road; + Tile.RoadLink roadLink2 = list[i]; + return roadLink2.road; } } return null; @@ -325,42 +329,43 @@ public void OverlayRiver(int fromTile, int toTile, RiverDef riverDef) if (riverDef == null) { Log.ErrorOnce("Attempted to remove river with overlayRiver; not supported", 90292250); - return; } - RiverDef riverDef2 = this.GetRiverDef(fromTile, toTile, false); - if (riverDef2 == riverDef) + else { - return; - } - Tile tile = this[fromTile]; - Tile tile2 = this[toTile]; - if (riverDef2 != null) - { - if (riverDef2.degradeThreshold >= riverDef.degradeThreshold) + RiverDef riverDef2 = this.GetRiverDef(fromTile, toTile, false); + if (riverDef2 != riverDef) { - return; + Tile tile = this[fromTile]; + Tile tile2 = this[toTile]; + if (riverDef2 != null) + { + if (riverDef2.degradeThreshold >= riverDef.degradeThreshold) + { + return; + } + tile.rivers.RemoveAll((Predicate)((Tile.RiverLink rl) => rl.neighbor == toTile)); + tile2.rivers.RemoveAll((Predicate)((Tile.RiverLink rl) => rl.neighbor == fromTile)); + } + if (tile.rivers == null) + { + tile.rivers = new List(); + } + if (tile2.rivers == null) + { + tile2.rivers = new List(); + } + tile.rivers.Add(new Tile.RiverLink + { + neighbor = toTile, + river = riverDef + }); + tile2.rivers.Add(new Tile.RiverLink + { + neighbor = fromTile, + river = riverDef + }); } - tile.rivers.RemoveAll((Tile.RiverLink rl) => rl.neighbor == toTile); - tile2.rivers.RemoveAll((Tile.RiverLink rl) => rl.neighbor == fromTile); - } - if (tile.rivers == null) - { - tile.rivers = new List(); } - if (tile2.rivers == null) - { - tile2.rivers = new List(); - } - tile.rivers.Add(new Tile.RiverLink - { - neighbor = toTile, - river = riverDef - }); - tile2.rivers.Add(new Tile.RiverLink - { - neighbor = fromTile, - river = riverDef - }); } public RiverDef GetRiverDef(int fromTile, int toTile, bool visibleOnly = true) @@ -378,9 +383,11 @@ public RiverDef GetRiverDef(int fromTile, int toTile, bool visibleOnly = true) } for (int i = 0; i < list.Count; i++) { - if (list[i].neighbor == toTile) + Tile.RiverLink riverLink = list[i]; + if (riverLink.neighbor == toTile) { - return list[i].river; + Tile.RiverLink riverLink2 = list[i]; + return riverLink2.river; } } return null; @@ -395,9 +402,11 @@ public float GetRoadMovementMultiplierFast(int fromTile, int toTile) } for (int i = 0; i < roads.Count; i++) { - if (roads[i].neighbor == toTile) + Tile.RoadLink roadLink = roads[i]; + if (roadLink.neighbor == toTile) { - return roads[i].road.movementCostMultiplier; + Tile.RoadLink roadLink2 = roads[i]; + return roadLink2.road.movementCostMultiplier; } } return 1f; @@ -405,39 +414,33 @@ public float GetRoadMovementMultiplierFast(int fromTile, int toTile) public int TraversalDistanceBetween(int start, int end) { - if (start < 0 || end < 0) + if (start >= 0 && end >= 0) { - return 0; - } - if (this.cachedTraversalDistanceForStart == start && this.cachedTraversalDistanceForEnd == end) - { - return this.cachedTraversalDistance; - } - int finalDist = -1; - Find.WorldFloodFiller.FloodFill(start, (int x) => true, delegate(int tile, int dist) - { - if (tile == end) + if (this.cachedTraversalDistanceForStart == start && this.cachedTraversalDistanceForEnd == end) { - finalDist = dist; - return true; + return this.cachedTraversalDistance; } - return false; - }, 2147483647); - if (finalDist < 0) - { - Log.Error(string.Concat(new object[] + int finalDist = -1; + Find.WorldFloodFiller.FloodFill(start, (Predicate)((int x) => true), (Func)delegate(int tile, int dist) { - "Could not reach tile ", - end, - " from ", - start - })); - return 0; + if (tile == end) + { + finalDist = dist; + return true; + } + return false; + }, 2147483647); + if (finalDist < 0) + { + Log.Error("Could not reach tile " + end + " from " + start); + return 0; + } + this.cachedTraversalDistance = finalDist; + this.cachedTraversalDistanceForStart = start; + this.cachedTraversalDistanceForEnd = end; + return finalDist; } - this.cachedTraversalDistance = finalDist; - this.cachedTraversalDistanceForStart = start; - this.cachedTraversalDistanceForEnd = end; - return finalDist; + return 0; } private void CalculateAverageTileSize() @@ -445,13 +448,13 @@ private void CalculateAverageTileSize() int tilesCount = this.TilesCount; double num = 0.0; int num2 = 0; - for (int i = 0; i < tilesCount; i++) + for (int num3 = 0; num3 < tilesCount; num3++) { - Vector3 tileCenter = this.GetTileCenter(i); - int num3 = (i + 1 >= this.tileIDToNeighbors_offsets.Count) ? this.tileIDToNeighbors_values.Count : this.tileIDToNeighbors_offsets[i + 1]; - for (int j = this.tileIDToNeighbors_offsets[i]; j < num3; j++) + Vector3 tileCenter = this.GetTileCenter(num3); + int num4 = (num3 + 1 >= this.tileIDToNeighbors_offsets.Count) ? this.tileIDToNeighbors_values.Count : this.tileIDToNeighbors_offsets[num3 + 1]; + for (int num5 = this.tileIDToNeighbors_offsets[num3]; num5 < num4; num5++) { - int tileID = this.tileIDToNeighbors_values[j]; + int tileID = this.tileIDToNeighbors_values[num5]; Vector3 tileCenter2 = this.GetTileCenter(tileID); num += (double)Vector3.Distance(tileCenter, tileCenter2); num2++; @@ -462,12 +465,12 @@ private void CalculateAverageTileSize() private void CalculateViewCenterAndAngle() { - this.viewAngle = Find.World.PlanetCoverage * 180f; + this.viewAngle = (float)(Find.World.PlanetCoverage * 180.0); this.viewCenter = Vector3.back; float angle = 45f; - if (this.viewAngle > 45f) + if (this.viewAngle > 45.0) { - angle = Mathf.Max(90f - this.viewAngle, 0f); + angle = Mathf.Max((float)(90.0 - this.viewAngle), 0f); } this.viewCenter = Quaternion.AngleAxis(angle, Vector3.right) * this.viewCenter; } diff --git a/Assembly-CSharp/RimWorld.Planet/WorldInfo.cs b/Assembly-CSharp/RimWorld.Planet/WorldInfo.cs index 5dd42d839..e58f58bc1 100644 --- a/Assembly-CSharp/RimWorld.Planet/WorldInfo.cs +++ b/Assembly-CSharp/RimWorld.Planet/WorldInfo.cs @@ -1,4 +1,3 @@ -using System; using Verse; namespace RimWorld.Planet @@ -35,9 +34,9 @@ public int Seed public void ExposeData() { - Scribe_Values.Look(ref this.name, "name", null, false); + Scribe_Values.Look(ref this.name, "name", (string)null, false); Scribe_Values.Look(ref this.planetCoverage, "planetCoverage", 0f, false); - Scribe_Values.Look(ref this.seedString, "seedString", null, false); + Scribe_Values.Look(ref this.seedString, "seedString", (string)null, false); Scribe_Values.Look(ref this.overallRainfall, "overallRainfall", OverallRainfall.AlmostNone, false); Scribe_Values.Look(ref this.overallTemperature, "overallTemperature", OverallTemperature.VeryCold, false); Scribe_Values.Look(ref this.initialMapSize, "initialMapSize", default(IntVec3), false); diff --git a/Assembly-CSharp/RimWorld.Planet/WorldInspectPane.cs b/Assembly-CSharp/RimWorld.Planet/WorldInspectPane.cs index 879d2ff00..745f74638 100644 --- a/Assembly-CSharp/RimWorld.Planet/WorldInspectPane.cs +++ b/Assembly-CSharp/RimWorld.Planet/WorldInspectPane.cs @@ -9,7 +9,7 @@ namespace RimWorld.Planet { public class WorldInspectPane : Window, IInspectPane { - private static readonly WITab[] TileTabs = new WITab[] + private static readonly WITab[] TileTabs = new WITab[2] { new WITab_Terrain(), new WITab_Planet() @@ -81,12 +81,14 @@ public float PaneTopY { get { - float num = (float)UI.screenHeight - InspectPaneUtility.PaneSize.y; + float num = (float)UI.screenHeight; + Vector2 paneSize = InspectPaneUtility.PaneSize; + float num2 = num - paneSize.y; if (Current.ProgramState == ProgramState.Playing) { - num -= 35f; + num2 = (float)(num2 - 35.0); } - return num; + return num2; } } @@ -159,7 +161,7 @@ private string TileInspectString if (tile.VisibleRoads != null) { stringBuilder.Append("\n" + (from rl in tile.VisibleRoads - select rl.road).MaxBy((RoadDef road) => road.priority).LabelCap); + select rl.road).MaxBy((Func)((RoadDef road) => road.priority)).LabelCap); } return stringBuilder.ToString(); } @@ -167,19 +169,19 @@ private string TileInspectString public WorldInspectPane() { - this.layer = WindowLayer.GameUI; - this.soundAppear = null; - this.soundClose = null; - this.closeOnClickedOutside = false; - this.closeOnEscapeKey = false; - this.preventCameraMotion = false; + base.layer = WindowLayer.GameUI; + base.soundAppear = null; + base.soundClose = null; + base.closeOnClickedOutside = false; + base.closeOnEscapeKey = false; + base.preventCameraMotion = false; } protected override void SetInitialSizeAndPosition() { base.SetInitialSizeAndPosition(); - this.windowRect.x = 0f; - this.windowRect.y = this.PaneTopY; + base.windowRect.x = 0f; + base.windowRect.y = this.PaneTopY; } public void DrawInspectGizmos() @@ -213,17 +215,16 @@ public string GetLabel(Rect rect) public void SelectNextInCell() { - if (!this.AnythingSelected) + if (this.AnythingSelected) { - return; - } - if (this.NumSelectedObjects > 0) - { - Find.WorldSelector.SelectFirstOrNextAt(this.Selected[0].Tile); - } - else - { - Find.WorldSelector.SelectFirstOrNextAt(this.SelectedTile); + if (this.NumSelectedObjects > 0) + { + Find.WorldSelector.SelectFirstOrNextAt(this.Selected[0].Tile); + } + else + { + Find.WorldSelector.SelectFirstOrNextAt(this.SelectedTile); + } } } @@ -245,19 +246,18 @@ public void DoPaneContents(Rect rect) public void DoInspectPaneButtons(Rect rect, ref float lineEndWidth) { WorldObject singleSelectedObject = Find.WorldSelector.SingleSelectedObject; - if (singleSelectedObject != null || this.SelectedTile >= 0) + if (singleSelectedObject == null && this.SelectedTile < 0) + return; + float x = (float)(rect.width - 48.0); + if (singleSelectedObject != null) { - float x = rect.width - 48f; - if (singleSelectedObject != null) - { - Widgets.InfoCardButton(x, 0f, singleSelectedObject); - } - else - { - Widgets.InfoCardButton(x, 0f, Find.WorldGrid[this.SelectedTile].biome); - } - lineEndWidth += 24f; + Widgets.InfoCardButton(x, 0f, singleSelectedObject); + } + else + { + Widgets.InfoCardButton(x, 0f, Find.WorldGrid[this.SelectedTile].biome); } + lineEndWidth += 24f; } public override void DoWindowContents(Rect rect) diff --git a/Assembly-CSharp/RimWorld.Planet/WorldInspectPaneUtility.cs b/Assembly-CSharp/RimWorld.Planet/WorldInspectPaneUtility.cs index 8ea289ac1..68e8a0197 100644 --- a/Assembly-CSharp/RimWorld.Planet/WorldInspectPaneUtility.cs +++ b/Assembly-CSharp/RimWorld.Planet/WorldInspectPaneUtility.cs @@ -1,4 +1,3 @@ -using System; using System.Collections.Generic; using UnityEngine; using Verse; diff --git a/Assembly-CSharp/RimWorld.Planet/WorldLayer.cs b/Assembly-CSharp/RimWorld.Planet/WorldLayer.cs index 014e1f0bb..582ffc0b4 100644 --- a/Assembly-CSharp/RimWorld.Planet/WorldLayer.cs +++ b/Assembly-CSharp/RimWorld.Planet/WorldLayer.cs @@ -1,7 +1,5 @@ -using System; using System.Collections; using System.Collections.Generic; -using System.Diagnostics; using UnityEngine; using Verse; @@ -60,7 +58,7 @@ public bool Dirty protected LayerSubMesh GetSubMesh(Material material) { - int num; + int num = default(int); return this.GetSubMesh(material, out num); } @@ -69,7 +67,7 @@ protected LayerSubMesh GetSubMesh(Material material, out int subMeshIndex) for (int i = 0; i < this.subMeshes.Count; i++) { LayerSubMesh layerSubMesh = this.subMeshes[i]; - if (layerSubMesh.material == material && layerSubMesh.verts.Count < 40000) + if ((Object)layerSubMesh.material == (Object)material && layerSubMesh.verts.Count < 40000) { subMeshIndex = i; return layerSubMesh; @@ -116,7 +114,7 @@ public void Render() { if (this.subMeshes[i].finalized) { - if (alpha != 1f) + if (alpha != 1.0) { Color color = this.subMeshes[i].material.color; WorldLayer.propertyBlock.SetColor(ShaderPropertyIDs.Color, new Color(color.r, color.g, color.b, color.a * alpha)); @@ -130,14 +128,11 @@ public void Render() } } - [DebuggerHidden] public virtual IEnumerable Regenerate() { - WorldLayer.c__IteratorEE c__IteratorEE = new WorldLayer.c__IteratorEE(); - c__IteratorEE.<>f__this = this; - WorldLayer.c__IteratorEE expr_0E = c__IteratorEE; - expr_0E.$PC = -2; - return expr_0E; + this.dirty = false; + this.ClearSubMeshes(MeshParts.All); + yield break; } public void SetDirty() diff --git a/Assembly-CSharp/RimWorld.Planet/WorldLayer_CurrentMapTile.cs b/Assembly-CSharp/RimWorld.Planet/WorldLayer_CurrentMapTile.cs index a817a40b1..2efdb4a12 100644 --- a/Assembly-CSharp/RimWorld.Planet/WorldLayer_CurrentMapTile.cs +++ b/Assembly-CSharp/RimWorld.Planet/WorldLayer_CurrentMapTile.cs @@ -1,4 +1,3 @@ -using System; using UnityEngine; using Verse; diff --git a/Assembly-CSharp/RimWorld.Planet/WorldLayer_Glow.cs b/Assembly-CSharp/RimWorld.Planet/WorldLayer_Glow.cs index 1c2fa4ff2..106f2c67c 100644 --- a/Assembly-CSharp/RimWorld.Planet/WorldLayer_Glow.cs +++ b/Assembly-CSharp/RimWorld.Planet/WorldLayer_Glow.cs @@ -1,6 +1,7 @@ -using System; using System.Collections; -using System.Diagnostics; +using System.Collections.Generic; +using UnityEngine; +using Verse; namespace RimWorld.Planet { @@ -10,14 +11,19 @@ public class WorldLayer_Glow : WorldLayer public const float GlowRadius = 8f; - [DebuggerHidden] public override IEnumerable Regenerate() { - WorldLayer_Glow.c__IteratorF0 c__IteratorF = new WorldLayer_Glow.c__IteratorF0(); - c__IteratorF.<>f__this = this; - WorldLayer_Glow.c__IteratorF0 expr_0E = c__IteratorF; - expr_0E.$PC = -2; - return expr_0E; + foreach (object item in base.Regenerate()) + { + yield return item; + } + List tmpVerts; + List tmpIndices; + SphereGenerator.Generate(4, 108.1f, Vector3.forward, 360f, out tmpVerts, out tmpIndices); + LayerSubMesh subMesh = base.GetSubMesh(WorldMaterials.PlanetGlow); + subMesh.verts.AddRange(tmpVerts); + subMesh.tris.AddRange(tmpIndices); + base.FinalizeMesh(MeshParts.All, true); } } } diff --git a/Assembly-CSharp/RimWorld.Planet/WorldLayer_Hills.cs b/Assembly-CSharp/RimWorld.Planet/WorldLayer_Hills.cs index 62d15b937..12cb83ba1 100644 --- a/Assembly-CSharp/RimWorld.Planet/WorldLayer_Hills.cs +++ b/Assembly-CSharp/RimWorld.Planet/WorldLayer_Hills.cs @@ -1,6 +1,5 @@ -using System; using System.Collections; -using System.Diagnostics; +using UnityEngine; using Verse; namespace RimWorld.Planet @@ -19,14 +18,68 @@ public class WorldLayer_Hills : WorldLayer private static readonly FloatRange BasePosOffsetRange_ImpassableMountains = new FloatRange(0f, 0.08f); - [DebuggerHidden] public override IEnumerable Regenerate() { - WorldLayer_Hills.c__IteratorF1 c__IteratorF = new WorldLayer_Hills.c__IteratorF1(); - c__IteratorF.<>f__this = this; - WorldLayer_Hills.c__IteratorF1 expr_0E = c__IteratorF; - expr_0E.$PC = -2; - return expr_0E; + foreach (object item in base.Regenerate()) + { + yield return item; + } + Rand.PushState(); + Rand.Seed = Find.World.info.Seed; + WorldGrid grid = Find.WorldGrid; + int tilesCount = grid.TilesCount; + for (int i = 0; i < tilesCount; i++) + { + Tile tile = grid[i]; + Material mat; + FloatRange basePosOffsetRange; + switch (tile.hilliness) + { + case Hilliness.SmallHills: + { + mat = WorldMaterials.SmallHills; + basePosOffsetRange = WorldLayer_Hills.BasePosOffsetRange_SmallHills; + goto IL_019a; + } + case Hilliness.LargeHills: + { + mat = WorldMaterials.LargeHills; + basePosOffsetRange = WorldLayer_Hills.BasePosOffsetRange_LargeHills; + goto IL_019a; + } + case Hilliness.Mountainous: + { + mat = WorldMaterials.Mountains; + basePosOffsetRange = WorldLayer_Hills.BasePosOffsetRange_Mountains; + goto IL_019a; + } + case Hilliness.Impassable: + { + mat = WorldMaterials.ImpassableMountains; + basePosOffsetRange = WorldLayer_Hills.BasePosOffsetRange_ImpassableMountains; + goto IL_019a; + } + } + continue; + IL_019a: + LayerSubMesh subMesh = base.GetSubMesh(mat); + Vector3 origPos; + Vector3 pos = origPos = grid.GetTileCenter(i); + float length = pos.magnitude; + pos += Rand.PointOnSphere * basePosOffsetRange.RandomInRange * grid.averageTileSize; + pos = pos.normalized * length; + WorldRendererUtility.PrintQuadTangentialToPlanet(pos, origPos, WorldLayer_Hills.BaseSizeRange.RandomInRange * grid.averageTileSize, 0.005f, subMesh, false, true, false); + IntVec2 texturesInAtlas = WorldLayer_Hills.TexturesInAtlas; + int indexX = Rand.Range(0, texturesInAtlas.x); + IntVec2 texturesInAtlas2 = WorldLayer_Hills.TexturesInAtlas; + int indexY = Rand.Range(0, texturesInAtlas2.z); + IntVec2 texturesInAtlas3 = WorldLayer_Hills.TexturesInAtlas; + int x = texturesInAtlas3.x; + IntVec2 texturesInAtlas4 = WorldLayer_Hills.TexturesInAtlas; + WorldRendererUtility.PrintTextureAtlasUVs(indexX, indexY, x, texturesInAtlas4.z, subMesh); + } + Rand.PopState(); + base.FinalizeMesh(MeshParts.All, true); } } } diff --git a/Assembly-CSharp/RimWorld.Planet/WorldLayer_MouseTile.cs b/Assembly-CSharp/RimWorld.Planet/WorldLayer_MouseTile.cs index eaaeb05ca..c6ec80818 100644 --- a/Assembly-CSharp/RimWorld.Planet/WorldLayer_MouseTile.cs +++ b/Assembly-CSharp/RimWorld.Planet/WorldLayer_MouseTile.cs @@ -1,4 +1,3 @@ -using System; using UnityEngine; using Verse; diff --git a/Assembly-CSharp/RimWorld.Planet/WorldLayer_Paths.cs b/Assembly-CSharp/RimWorld.Planet/WorldLayer_Paths.cs index 1c5dce64e..5c025bb41 100644 --- a/Assembly-CSharp/RimWorld.Planet/WorldLayer_Paths.cs +++ b/Assembly-CSharp/RimWorld.Planet/WorldLayer_Paths.cs @@ -1,4 +1,3 @@ -using System; using System.Collections.Generic; using UnityEngine; using Verse; @@ -26,7 +25,7 @@ public struct OutputDirection private List tmpNeighbors = new List(); - public void GeneratePaths(LayerSubMesh subMesh, int tileID, List nodes, Color32 color, bool allowSmoothTransition) + public void GeneratePaths(LayerSubMesh subMesh, int tileID, List nodes, Color32 color, bool allowSmoothTransition) { WorldGrid worldGrid = Find.WorldGrid; worldGrid.GetTileVertices(tileID, this.tmpVerts); @@ -34,99 +33,118 @@ public void GeneratePaths(LayerSubMesh subMesh, int tileID, List verts = this.tmpVerts; + List obj = this.tmpNeighbors; + OutputDirection outputDirection = nodes[0]; + this.AddPathEndpoint(subMesh, verts, obj.IndexOf(outputDirection.neighbor), color, nodes[0]); + List verts2 = subMesh.verts; + Vector3 tileCenter = worldGrid.GetTileCenter(tileID); + OutputDirection outputDirection2 = nodes[0]; + float distortionFrequency = outputDirection2.distortionFrequency; + OutputDirection outputDirection3 = nodes[0]; + verts2.Add(this.FinalizePoint(tileCenter, distortionFrequency, outputDirection3.distortionIntensity)); + subMesh.colors.Add(color.MutateAlpha((byte)0)); subMesh.tris.Add(count); subMesh.tris.Add(count + 3); subMesh.tris.Add(count + 1); subMesh.tris.Add(count + 1); subMesh.tris.Add(count + 3); subMesh.tris.Add(count + 2); - return; } - if (nodes.Count == 2) + else { - int count2 = subMesh.verts.Count; - int num = this.tmpNeighbors.IndexOf(nodes[0].neighbor); - int num2 = this.tmpNeighbors.IndexOf(nodes[1].neighbor); - if (allowSmoothTransition && Mathf.Abs(num - num2) > 1 && Mathf.Abs((num - num2 + this.tmpVerts.Count) % this.tmpVerts.Count) > 1) + if (nodes.Count == 2) { - this.AddPathEndpoint(subMesh, this.tmpVerts, num, color, nodes[0]); - this.AddPathEndpoint(subMesh, this.tmpVerts, num2, color, nodes[1]); - subMesh.tris.Add(count2); - subMesh.tris.Add(count2 + 5); - subMesh.tris.Add(count2 + 1); - subMesh.tris.Add(count2 + 5); - subMesh.tris.Add(count2 + 4); - subMesh.tris.Add(count2 + 1); - subMesh.tris.Add(count2 + 1); - subMesh.tris.Add(count2 + 4); - subMesh.tris.Add(count2 + 2); - subMesh.tris.Add(count2 + 4); - subMesh.tris.Add(count2 + 3); - subMesh.tris.Add(count2 + 2); - return; + int count2 = subMesh.verts.Count; + List obj2 = this.tmpNeighbors; + OutputDirection outputDirection4 = nodes[0]; + int num = obj2.IndexOf(outputDirection4.neighbor); + List obj3 = this.tmpNeighbors; + OutputDirection outputDirection5 = nodes[1]; + int num2 = obj3.IndexOf(outputDirection5.neighbor); + if (allowSmoothTransition && Mathf.Abs(num - num2) > 1 && Mathf.Abs((num - num2 + this.tmpVerts.Count) % this.tmpVerts.Count) > 1) + { + this.AddPathEndpoint(subMesh, this.tmpVerts, num, color, nodes[0]); + this.AddPathEndpoint(subMesh, this.tmpVerts, num2, color, nodes[1]); + subMesh.tris.Add(count2); + subMesh.tris.Add(count2 + 5); + subMesh.tris.Add(count2 + 1); + subMesh.tris.Add(count2 + 5); + subMesh.tris.Add(count2 + 4); + subMesh.tris.Add(count2 + 1); + subMesh.tris.Add(count2 + 1); + subMesh.tris.Add(count2 + 4); + subMesh.tris.Add(count2 + 2); + subMesh.tris.Add(count2 + 4); + subMesh.tris.Add(count2 + 3); + subMesh.tris.Add(count2 + 2); + return; + } } - } - float num3 = 0f; - for (int i = 0; i < nodes.Count; i++) - { - num3 = Mathf.Max(num3, nodes[i].width); - } - Vector3 vector = worldGrid.GetTileCenter(tileID); - this.tmpHexVerts.Clear(); - for (int j = 0; j < this.tmpVerts.Count; j++) - { - this.tmpHexVerts.Add(this.FinalizePoint(Vector3.LerpUnclamped(vector, this.tmpVerts[j], num3 * 0.5f * 2f), 0f, 0f)); - } - vector = this.FinalizePoint(vector, 0f, 0f); - int count3 = subMesh.verts.Count; - subMesh.verts.Add(vector); - subMesh.colors.Add(color); - int count4 = subMesh.verts.Count; - for (int k = 0; k < this.tmpHexVerts.Count; k++) - { - subMesh.verts.Add(this.tmpHexVerts[k]); - subMesh.colors.Add(color.MutateAlpha(0)); - subMesh.tris.Add(count3); - subMesh.tris.Add(count4 + (k + 1) % this.tmpHexVerts.Count); - subMesh.tris.Add(count4 + k); - } - for (int l = 0; l < nodes.Count; l++) - { - if (nodes[l].width != 0f) + float num3 = 0f; + for (int i = 0; i < nodes.Count; i++) { - int count5 = subMesh.verts.Count; - int num4 = this.tmpNeighbors.IndexOf(nodes[l].neighbor); - this.AddPathEndpoint(subMesh, this.tmpVerts, num4, color, nodes[l]); - subMesh.tris.Add(count5); - subMesh.tris.Add(count4 + (num4 + this.tmpHexVerts.Count - 1) % this.tmpHexVerts.Count); - subMesh.tris.Add(count3); - subMesh.tris.Add(count5); - subMesh.tris.Add(count3); - subMesh.tris.Add(count5 + 1); - subMesh.tris.Add(count5 + 1); - subMesh.tris.Add(count3); - subMesh.tris.Add(count5 + 2); + float a = num3; + OutputDirection outputDirection6 = nodes[i]; + num3 = Mathf.Max(a, outputDirection6.width); + } + Vector3 tileCenter2 = worldGrid.GetTileCenter(tileID); + this.tmpHexVerts.Clear(); + for (int j = 0; j < this.tmpVerts.Count; j++) + { + this.tmpHexVerts.Add(this.FinalizePoint(Vector3.LerpUnclamped(tileCenter2, this.tmpVerts[j], (float)(num3 * 0.5 * 2.0)), 0f, 0f)); + } + tileCenter2 = this.FinalizePoint(tileCenter2, 0f, 0f); + int count3 = subMesh.verts.Count; + subMesh.verts.Add(tileCenter2); + subMesh.colors.Add(color); + int count4 = subMesh.verts.Count; + for (int k = 0; k < this.tmpHexVerts.Count; k++) + { + subMesh.verts.Add(this.tmpHexVerts[k]); + subMesh.colors.Add(color.MutateAlpha((byte)0)); subMesh.tris.Add(count3); - subMesh.tris.Add(count4 + (num4 + 2) % this.tmpHexVerts.Count); - subMesh.tris.Add(count5 + 2); + subMesh.tris.Add(count4 + (k + 1) % this.tmpHexVerts.Count); + subMesh.tris.Add(count4 + k); + } + for (int l = 0; l < nodes.Count; l++) + { + OutputDirection outputDirection7 = nodes[l]; + if (outputDirection7.width != 0.0) + { + int count5 = subMesh.verts.Count; + List obj4 = this.tmpNeighbors; + OutputDirection outputDirection8 = nodes[l]; + int num4 = obj4.IndexOf(outputDirection8.neighbor); + this.AddPathEndpoint(subMesh, this.tmpVerts, num4, color, nodes[l]); + subMesh.tris.Add(count5); + subMesh.tris.Add(count4 + (num4 + this.tmpHexVerts.Count - 1) % this.tmpHexVerts.Count); + subMesh.tris.Add(count3); + subMesh.tris.Add(count5); + subMesh.tris.Add(count3); + subMesh.tris.Add(count5 + 1); + subMesh.tris.Add(count5 + 1); + subMesh.tris.Add(count3); + subMesh.tris.Add(count5 + 2); + subMesh.tris.Add(count3); + subMesh.tris.Add(count4 + (num4 + 2) % this.tmpHexVerts.Count); + subMesh.tris.Add(count5 + 2); + } } } } - private void AddPathEndpoint(LayerSubMesh subMesh, List verts, int index, Color32 color, WorldLayer_Paths.OutputDirection data) + private void AddPathEndpoint(LayerSubMesh subMesh, List verts, int index, Color32 color, OutputDirection data) { int index2 = (index + 1) % verts.Count; Vector3 a = this.FinalizePoint(verts[index], data.distortionFrequency, data.distortionIntensity); Vector3 b = this.FinalizePoint(verts[index2], data.distortionFrequency, data.distortionIntensity); - subMesh.verts.Add(Vector3.LerpUnclamped(a, b, 0.5f - data.width)); - subMesh.colors.Add(color.MutateAlpha(0)); + subMesh.verts.Add(Vector3.LerpUnclamped(a, b, (float)(0.5 - data.width))); + subMesh.colors.Add(color.MutateAlpha((byte)0)); subMesh.verts.Add(Vector3.LerpUnclamped(a, b, 0.5f)); subMesh.colors.Add(color); - subMesh.verts.Add(Vector3.LerpUnclamped(a, b, 0.5f + data.width)); - subMesh.colors.Add(color.MutateAlpha(0)); + subMesh.verts.Add(Vector3.LerpUnclamped(a, b, (float)(0.5 + data.width))); + subMesh.colors.Add(color.MutateAlpha((byte)0)); } public abstract Vector3 FinalizePoint(Vector3 inp, float distortionFrequency, float distortionIntensity); diff --git a/Assembly-CSharp/RimWorld.Planet/WorldLayer_Rivers.cs b/Assembly-CSharp/RimWorld.Planet/WorldLayer_Rivers.cs index bb9d3b135..c7e2541a0 100644 --- a/Assembly-CSharp/RimWorld.Planet/WorldLayer_Rivers.cs +++ b/Assembly-CSharp/RimWorld.Planet/WorldLayer_Rivers.cs @@ -1,7 +1,7 @@ -using System; using System.Collections; -using System.Diagnostics; +using System.Collections.Generic; using UnityEngine; +using Verse; using Verse.Noise; namespace RimWorld.Planet @@ -12,7 +12,7 @@ public class WorldLayer_Rivers : WorldLayer_Paths private const float PerlinMagnitude = 0.1f; - private Color32 riverColor = new Color32(73, 82, 100, 255); + private Color32 riverColor = new Color32((byte)73, (byte)82, (byte)100, (byte)255); private ModuleBase riverDisplacementX = new Perlin(0.60000002384185791, 2.0, 0.5, 3, 84905524, QualityMode.Medium); @@ -22,17 +22,58 @@ public class WorldLayer_Rivers : WorldLayer_Paths public WorldLayer_Rivers() { - this.pointyEnds = true; + base.pointyEnds = true; } - [DebuggerHidden] public override IEnumerable Regenerate() { - WorldLayer_Rivers.c__IteratorF2 c__IteratorF = new WorldLayer_Rivers.c__IteratorF2(); - c__IteratorF.<>f__this = this; - WorldLayer_Rivers.c__IteratorF2 expr_0E = c__IteratorF; - expr_0E.$PC = -2; - return expr_0E; + foreach (object item3 in base.Regenerate()) + { + yield return item3; + } + LayerSubMesh subMesh = base.GetSubMesh(WorldMaterials.Rivers); + LayerSubMesh subMeshBorder = base.GetSubMesh(WorldMaterials.RiversBorder); + WorldGrid grid = Find.WorldGrid; + List outputs = new List(); + List outputsBorder = new List(); + for (int i = 0; i < grid.TilesCount; i++) + { + if (i % 1000 == 0) + { + yield return (object)null; + } + if (subMesh.verts.Count > 60000) + { + subMesh = base.GetSubMesh(WorldMaterials.Rivers); + subMeshBorder = base.GetSubMesh(WorldMaterials.RiversBorder); + } + Tile tile = grid[i]; + if (tile.rivers != null) + { + outputs.Clear(); + outputsBorder.Clear(); + for (int rc = 0; rc < tile.rivers.Count; rc++) + { + List obj = outputs; + OutputDirection item = default(OutputDirection); + Tile.RiverLink riverLink = tile.rivers[rc]; + item.neighbor = riverLink.neighbor; + Tile.RiverLink riverLink2 = tile.rivers[rc]; + item.width = (float)(riverLink2.river.widthOnWorld - 0.20000000298023224); + obj.Add(item); + List obj2 = outputsBorder; + OutputDirection item2 = default(OutputDirection); + Tile.RiverLink riverLink3 = tile.rivers[rc]; + item2.neighbor = riverLink3.neighbor; + Tile.RiverLink riverLink4 = tile.rivers[rc]; + item2.width = riverLink4.river.widthOnWorld; + obj2.Add(item2); + } + base.GeneratePaths(subMesh, i, outputs, this.riverColor, true); + base.GeneratePaths(subMeshBorder, i, outputsBorder, this.riverColor, true); + } + } + base.FinalizeMesh(MeshParts.All, false); } public override Vector3 FinalizePoint(Vector3 inp, float distortionFrequency, float distortionIntensity) diff --git a/Assembly-CSharp/RimWorld.Planet/WorldLayer_Roads.cs b/Assembly-CSharp/RimWorld.Planet/WorldLayer_Roads.cs index d91f77023..4564081bc 100644 --- a/Assembly-CSharp/RimWorld.Planet/WorldLayer_Roads.cs +++ b/Assembly-CSharp/RimWorld.Planet/WorldLayer_Roads.cs @@ -1,7 +1,9 @@ using System; using System.Collections; -using System.Diagnostics; +using System.Collections.Generic; +using System.Linq; using UnityEngine; +using Verse; using Verse.Noise; namespace RimWorld.Planet @@ -14,14 +16,75 @@ public class WorldLayer_Roads : WorldLayer_Paths private ModuleBase roadDisplacementZ = new Perlin(1.0, 2.0, 0.5, 3, 87116801, QualityMode.Medium); - [DebuggerHidden] public override IEnumerable Regenerate() { - WorldLayer_Roads.c__IteratorF3 c__IteratorF = new WorldLayer_Roads.c__IteratorF3(); - c__IteratorF.<>f__this = this; - WorldLayer_Roads.c__IteratorF3 expr_0E = c__IteratorF; - expr_0E.$PC = -2; - return expr_0E; + foreach (object item2 in base.Regenerate()) + { + yield return item2; + } + LayerSubMesh subMesh = base.GetSubMesh(WorldMaterials.Roads); + WorldGrid grid = Find.WorldGrid; + List roadLayerDefs = (from rwld in DefDatabase.AllDefs + orderby rwld.order + select rwld).ToList(); + for (int i = 0; i < grid.TilesCount; i++) + { + if (i % 1000 == 0) + { + yield return (object)null; + } + if (subMesh.verts.Count > 60000) + { + subMesh = base.GetSubMesh(WorldMaterials.Roads); + } + Tile tile = grid[i]; + if (!tile.WaterCovered) + { + List outputs = new List(); + if (tile.roads != null) + { + bool allowSmoothTransitions = true; + for (int rc2 = 0; rc2 < tile.roads.Count - 1; rc2++) + { + Tile.RoadLink roadLink = tile.roads[rc2]; + string worldTransitionGroup = roadLink.road.worldTransitionGroup; + Tile.RoadLink roadLink2 = tile.roads[rc2 + 1]; + if (worldTransitionGroup != roadLink2.road.worldTransitionGroup) + { + allowSmoothTransitions = false; + } + } + for (int roadLayer = 0; roadLayer < roadLayerDefs.Count; roadLayer++) + { + bool hasWidth = false; + outputs.Clear(); + for (int rc = 0; rc < tile.roads.Count; rc++) + { + Tile.RoadLink roadLink3 = tile.roads[rc]; + RoadDef roadDef = roadLink3.road; + float layerWidth = roadDef.GetLayerWidth(roadLayerDefs[roadLayer]); + if (layerWidth > 0.0) + { + hasWidth = true; + } + List obj = outputs; + OutputDirection item = default(OutputDirection); + Tile.RoadLink roadLink4 = tile.roads[rc]; + item.neighbor = roadLink4.neighbor; + item.width = layerWidth; + item.distortionFrequency = roadDef.distortionFrequency; + item.distortionIntensity = roadDef.distortionIntensity; + obj.Add(item); + } + if (hasWidth) + { + base.GeneratePaths(subMesh, i, outputs, roadLayerDefs[roadLayer].color, allowSmoothTransitions); + } + } + } + } + } + base.FinalizeMesh(MeshParts.All, false); } public override Vector3 FinalizePoint(Vector3 inp, float distortionFrequency, float distortionIntensity) diff --git a/Assembly-CSharp/RimWorld.Planet/WorldLayer_SelectedTile.cs b/Assembly-CSharp/RimWorld.Planet/WorldLayer_SelectedTile.cs index c64546ba6..ce06b819e 100644 --- a/Assembly-CSharp/RimWorld.Planet/WorldLayer_SelectedTile.cs +++ b/Assembly-CSharp/RimWorld.Planet/WorldLayer_SelectedTile.cs @@ -1,4 +1,3 @@ -using System; using UnityEngine; using Verse; diff --git a/Assembly-CSharp/RimWorld.Planet/WorldLayer_SettleTile.cs b/Assembly-CSharp/RimWorld.Planet/WorldLayer_SettleTile.cs index e68f0d3f0..ffd7474c6 100644 --- a/Assembly-CSharp/RimWorld.Planet/WorldLayer_SettleTile.cs +++ b/Assembly-CSharp/RimWorld.Planet/WorldLayer_SettleTile.cs @@ -1,4 +1,3 @@ -using System; using UnityEngine; using Verse; @@ -35,7 +34,7 @@ protected override float Alpha { get { - return Mathf.Abs(Time.time % 2f - 1f); + return Mathf.Abs((float)(Time.time % 2.0 - 1.0)); } } } diff --git a/Assembly-CSharp/RimWorld.Planet/WorldLayer_SingleTile.cs b/Assembly-CSharp/RimWorld.Planet/WorldLayer_SingleTile.cs index 11cef5ad9..591f9b4f9 100644 --- a/Assembly-CSharp/RimWorld.Planet/WorldLayer_SingleTile.cs +++ b/Assembly-CSharp/RimWorld.Planet/WorldLayer_SingleTile.cs @@ -1,8 +1,7 @@ -using System; using System.Collections; using System.Collections.Generic; -using System.Diagnostics; using UnityEngine; +using Verse; namespace RimWorld.Planet { @@ -30,14 +29,35 @@ public override bool ShouldRegenerate } } - [DebuggerHidden] public override IEnumerable Regenerate() { - WorldLayer_SingleTile.c__IteratorEF c__IteratorEF = new WorldLayer_SingleTile.c__IteratorEF(); - c__IteratorEF.<>f__this = this; - WorldLayer_SingleTile.c__IteratorEF expr_0E = c__IteratorEF; - expr_0E.$PC = -2; - return expr_0E; + foreach (object item in base.Regenerate()) + { + yield return item; + } + int tile = this.Tile; + if (tile >= 0) + { + LayerSubMesh subMesh = base.GetSubMesh(this.Material); + Find.WorldGrid.GetTileVertices(tile, this.verts); + int startVertIndex = subMesh.verts.Count; + int i = 0; + int count = this.verts.Count; + while (i < count) + { + subMesh.verts.Add(this.verts[i] + this.verts[i].normalized * 0.012f); + subMesh.uvs.Add((GenGeo.RegularPolygonVertexPosition(count, i) + Vector2.one) / 2f); + if (i < count - 2) + { + subMesh.tris.Add(startVertIndex + i + 2); + subMesh.tris.Add(startVertIndex + i + 1); + subMesh.tris.Add(startVertIndex); + } + i++; + } + base.FinalizeMesh(MeshParts.All, false); + } + this.lastDrawnTile = tile; } } } diff --git a/Assembly-CSharp/RimWorld.Planet/WorldLayer_Stars.cs b/Assembly-CSharp/RimWorld.Planet/WorldLayer_Stars.cs index 25fd7fc48..f14b63b0c 100644 --- a/Assembly-CSharp/RimWorld.Planet/WorldLayer_Stars.cs +++ b/Assembly-CSharp/RimWorld.Planet/WorldLayer_Stars.cs @@ -1,6 +1,4 @@ -using System; using System.Collections; -using System.Diagnostics; using UnityEngine; using Verse; @@ -56,14 +54,32 @@ protected override Quaternion Rotation } } - [DebuggerHidden] public override IEnumerable Regenerate() { - WorldLayer_Stars.c__IteratorF4 c__IteratorF = new WorldLayer_Stars.c__IteratorF4(); - c__IteratorF.<>f__this = this; - WorldLayer_Stars.c__IteratorF4 expr_0E = c__IteratorF; - expr_0E.$PC = -2; - return expr_0E; + foreach (object item in base.Regenerate()) + { + yield return item; + } + Rand.PushState(); + Rand.Seed = Find.World.info.Seed; + for (int i = 0; i < 1500; i++) + { + Vector3 pointNormal = Rand.PointOnSphere; + Vector3 point = pointNormal * 10f; + LayerSubMesh subMesh = base.GetSubMesh(WorldMaterials.Stars); + float size = WorldLayer_Stars.StarsDrawSize.RandomInRange; + Vector3 sunVector = (!this.UseStaticRotation) ? Vector3.forward : GenCelestial.CurSunPositionInWorldSpace().normalized; + float dot = Vector3.Dot(pointNormal, sunVector); + if (dot > 0.800000011920929) + { + size *= GenMath.LerpDouble(0.8f, 1f, 1f, 0.35f, dot); + } + WorldRendererUtility.PrintQuadTangentialToPlanet(point, size, 0f, subMesh, true, true, true); + } + this.calculatedForStartingTile = ((Find.GameInitData == null) ? (-1) : Find.GameInitData.startingTile); + this.calculatedForStaticRotation = this.UseStaticRotation; + Rand.PopState(); + base.FinalizeMesh(MeshParts.All, true); } } } diff --git a/Assembly-CSharp/RimWorld.Planet/WorldLayer_Sun.cs b/Assembly-CSharp/RimWorld.Planet/WorldLayer_Sun.cs index 62bc0729b..c59f9a355 100644 --- a/Assembly-CSharp/RimWorld.Planet/WorldLayer_Sun.cs +++ b/Assembly-CSharp/RimWorld.Planet/WorldLayer_Sun.cs @@ -1,7 +1,6 @@ -using System; using System.Collections; -using System.Diagnostics; using UnityEngine; +using Verse; namespace RimWorld.Planet { @@ -25,14 +24,18 @@ protected override Quaternion Rotation } } - [DebuggerHidden] public override IEnumerable Regenerate() { - WorldLayer_Sun.c__IteratorF5 c__IteratorF = new WorldLayer_Sun.c__IteratorF5(); - c__IteratorF.<>f__this = this; - WorldLayer_Sun.c__IteratorF5 expr_0E = c__IteratorF; - expr_0E.$PC = -2; - return expr_0E; + foreach (object item in base.Regenerate()) + { + yield return item; + } + Rand.PushState(); + Rand.Seed = Find.World.info.Seed; + LayerSubMesh sunSubMesh = base.GetSubMesh(WorldMaterials.Sun); + WorldRendererUtility.PrintQuadTangentialToPlanet(Vector3.forward * 10f, 15f, 0f, sunSubMesh, true, false, true); + Rand.PopState(); + base.FinalizeMesh(MeshParts.All, true); } } } diff --git a/Assembly-CSharp/RimWorld.Planet/WorldLayer_Terrain.cs b/Assembly-CSharp/RimWorld.Planet/WorldLayer_Terrain.cs index b2fae08e3..0bf9dc2f2 100644 --- a/Assembly-CSharp/RimWorld.Planet/WorldLayer_Terrain.cs +++ b/Assembly-CSharp/RimWorld.Planet/WorldLayer_Terrain.cs @@ -1,8 +1,7 @@ -using System; using System.Collections; using System.Collections.Generic; -using System.Diagnostics; using UnityEngine; +using Verse; namespace RimWorld.Planet { @@ -14,49 +13,165 @@ public class WorldLayer_Terrain : WorldLayer private List elevationValues = new List(); - [DebuggerHidden] public override IEnumerable Regenerate() { - WorldLayer_Terrain.c__IteratorF6 c__IteratorF = new WorldLayer_Terrain.c__IteratorF6(); - c__IteratorF.<>f__this = this; - WorldLayer_Terrain.c__IteratorF6 expr_0E = c__IteratorF; - expr_0E.$PC = -2; - return expr_0E; + foreach (object item in base.Regenerate()) + { + yield return item; + } + World world = Find.World; + WorldGrid grid = world.grid; + int tilesCount = grid.TilesCount; + List tiles = grid.tiles; + List tileIDToVerts_offsets = grid.tileIDToVerts_offsets; + List verts = grid.verts; + this.triangleIndexToTileID.Clear(); + foreach (object item2 in this.CalculateInterpolatedVerticesParams()) + { + yield return item2; + } + int colorsAndUVsIndex = 0; + for (int j = 0; j < tilesCount; j++) + { + Tile tile = tiles[j]; + BiomeDef biome = tile.biome; + int subMeshIndex; + LayerSubMesh subMesh = base.GetSubMesh(biome.DrawMaterial, out subMeshIndex); + while (subMeshIndex >= this.triangleIndexToTileID.Count) + { + this.triangleIndexToTileID.Add(new List()); + } + int startVertIndex = subMesh.verts.Count; + int vertIndex = 0; + int oneAfterLastVert = (j + 1 >= tileIDToVerts_offsets.Count) ? verts.Count : tileIDToVerts_offsets[j + 1]; + for (int i = tileIDToVerts_offsets[j]; i < oneAfterLastVert; i++) + { + subMesh.verts.Add(verts[i]); + subMesh.uvs.Add(this.elevationValues[colorsAndUVsIndex]); + colorsAndUVsIndex++; + if (i < oneAfterLastVert - 2) + { + subMesh.tris.Add(startVertIndex + vertIndex + 2); + subMesh.tris.Add(startVertIndex + vertIndex + 1); + subMesh.tris.Add(startVertIndex); + this.triangleIndexToTileID[subMeshIndex].Add(j); + } + vertIndex++; + } + } + base.FinalizeMesh(MeshParts.All, true); + foreach (object item3 in this.RegenerateMeshColliders()) + { + yield return item3; + } + this.elevationValues.Clear(); + this.elevationValues.TrimExcess(); } public int GetTileIDFromRayHit(RaycastHit hit) { - int i = 0; + int num = 0; int count = this.meshCollidersInOrder.Count; - while (i < count) + while (num < count) { - if (this.meshCollidersInOrder[i] == hit.collider) + if ((Object)this.meshCollidersInOrder[num] == (Object)hit.collider) { - return this.triangleIndexToTileID[i][hit.triangleIndex]; + return this.triangleIndexToTileID[num][hit.triangleIndex]; } - i++; + num++; } return -1; } - [DebuggerHidden] private IEnumerable RegenerateMeshColliders() { - WorldLayer_Terrain.c__IteratorF7 c__IteratorF = new WorldLayer_Terrain.c__IteratorF7(); - c__IteratorF.<>f__this = this; - WorldLayer_Terrain.c__IteratorF7 expr_0E = c__IteratorF; - expr_0E.$PC = -2; - return expr_0E; + this.meshCollidersInOrder.Clear(); + GameObject gameObject = WorldTerrainColliderManager.GameObject; + MeshCollider[] components = gameObject.GetComponents(); + for (int j = 0; j < components.Length; j++) + { + MeshCollider component = components[j]; + Object.Destroy(component); + } + for (int i = 0; i < base.subMeshes.Count; i++) + { + MeshCollider comp = gameObject.AddComponent(); + comp.sharedMesh = base.subMeshes[i].mesh; + this.meshCollidersInOrder.Add(comp); + yield return (object)null; + } } - [DebuggerHidden] private IEnumerable CalculateInterpolatedVerticesParams() { - WorldLayer_Terrain.c__IteratorF8 c__IteratorF = new WorldLayer_Terrain.c__IteratorF8(); - c__IteratorF.<>f__this = this; - WorldLayer_Terrain.c__IteratorF8 expr_0E = c__IteratorF; - expr_0E.$PC = -2; - return expr_0E; + this.elevationValues.Clear(); + World world = Find.World; + WorldGrid grid = world.grid; + int tilesCount = grid.TilesCount; + List verts = grid.verts; + List tileIDToVerts_offsets = grid.tileIDToVerts_offsets; + List tileIDToNeighbors_offsets = grid.tileIDToNeighbors_offsets; + List tileIDToNeighbors_values = grid.tileIDToNeighbors_values; + List tiles = grid.tiles; + for (int l = 0; l < tilesCount; l++) + { + Tile tile = tiles[l]; + float elevation = tile.elevation; + int oneAfterLastNeighbor = (l + 1 >= tileIDToNeighbors_offsets.Count) ? tileIDToNeighbors_values.Count : tileIDToNeighbors_offsets[l + 1]; + int oneAfterLastVert = (l + 1 >= tilesCount) ? verts.Count : tileIDToVerts_offsets[l + 1]; + for (int k = tileIDToVerts_offsets[l]; k < oneAfterLastVert; k++) + { + Vector3 elevationVal = new Vector3 + { + x = elevation + }; + bool isCoast = false; + for (int j = tileIDToNeighbors_offsets[l]; j < oneAfterLastNeighbor; j++) + { + int oneAfterLastNeighVert = (tileIDToNeighbors_values[j] + 1 >= tileIDToVerts_offsets.Count) ? verts.Count : tileIDToVerts_offsets[tileIDToNeighbors_values[j] + 1]; + int i = tileIDToVerts_offsets[tileIDToNeighbors_values[j]]; + while (i < oneAfterLastNeighVert) + { + if (!(verts[i] == verts[k])) + { + i++; + continue; + } + Tile neigh = tiles[tileIDToNeighbors_values[j]]; + if (!isCoast) + { + if (neigh.elevation >= 0.0 && elevation <= 0.0) + { + goto IL_02e4; + } + if (neigh.elevation <= 0.0 && elevation >= 0.0) + goto IL_02e4; + if (neigh.elevation > elevationVal.x) + { + elevationVal.x = neigh.elevation; + } + } + break; + IL_02e4: + isCoast = true; + break; + } + } + if (isCoast) + { + elevationVal.x = 0f; + } + if ((Object)tile.biome.DrawMaterial.shader != (Object)ShaderDatabase.WorldOcean && elevationVal.x < 0.0) + { + elevationVal.x = 0f; + } + this.elevationValues.Add(elevationVal); + } + if (l % 1000 == 0) + { + yield return (object)null; + } + } } } } diff --git a/Assembly-CSharp/RimWorld.Planet/WorldLayer_UngeneratedPlanetParts.cs b/Assembly-CSharp/RimWorld.Planet/WorldLayer_UngeneratedPlanetParts.cs index fb9020d47..5c462caa9 100644 --- a/Assembly-CSharp/RimWorld.Planet/WorldLayer_UngeneratedPlanetParts.cs +++ b/Assembly-CSharp/RimWorld.Planet/WorldLayer_UngeneratedPlanetParts.cs @@ -1,6 +1,7 @@ -using System; using System.Collections; -using System.Diagnostics; +using System.Collections.Generic; +using UnityEngine; +using Verse; namespace RimWorld.Planet { @@ -10,14 +11,24 @@ public class WorldLayer_UngeneratedPlanetParts : WorldLayer private const float ViewAngleOffset = 10f; - [DebuggerHidden] public override IEnumerable Regenerate() { - WorldLayer_UngeneratedPlanetParts.c__IteratorF9 c__IteratorF = new WorldLayer_UngeneratedPlanetParts.c__IteratorF9(); - c__IteratorF.<>f__this = this; - WorldLayer_UngeneratedPlanetParts.c__IteratorF9 expr_0E = c__IteratorF; - expr_0E.$PC = -2; - return expr_0E; + foreach (object item in base.Regenerate()) + { + yield return item; + } + Vector3 planetViewCenter = Find.WorldGrid.viewCenter; + float planetViewAngle = Find.WorldGrid.viewAngle; + if (planetViewAngle < 180.0) + { + List tmpVerts; + List tmpIndices; + SphereGenerator.Generate(4, 99.85f, -planetViewCenter, (float)(180.0 - Mathf.Min(planetViewAngle, 180f) + 10.0), out tmpVerts, out tmpIndices); + LayerSubMesh subMesh = base.GetSubMesh(WorldMaterials.UngeneratedPlanetParts); + subMesh.verts.AddRange(tmpVerts); + subMesh.tris.AddRange(tmpIndices); + } + base.FinalizeMesh(MeshParts.All, true); } } } diff --git a/Assembly-CSharp/RimWorld.Planet/WorldLayer_WorldObjects.cs b/Assembly-CSharp/RimWorld.Planet/WorldLayer_WorldObjects.cs index bd12779c1..ac7acd839 100644 --- a/Assembly-CSharp/RimWorld.Planet/WorldLayer_WorldObjects.cs +++ b/Assembly-CSharp/RimWorld.Planet/WorldLayer_WorldObjects.cs @@ -1,6 +1,7 @@ -using System; using System.Collections; -using System.Diagnostics; +using System.Collections.Generic; +using UnityEngine; +using Verse; namespace RimWorld.Planet { @@ -8,14 +9,34 @@ public abstract class WorldLayer_WorldObjects : WorldLayer { protected abstract bool ShouldSkip(WorldObject worldObject); - [DebuggerHidden] public override IEnumerable Regenerate() { - WorldLayer_WorldObjects.c__IteratorFA c__IteratorFA = new WorldLayer_WorldObjects.c__IteratorFA(); - c__IteratorFA.<>f__this = this; - WorldLayer_WorldObjects.c__IteratorFA expr_0E = c__IteratorFA; - expr_0E.$PC = -2; - return expr_0E; + foreach (object item in base.Regenerate()) + { + yield return item; + } + List allObjects = Find.WorldObjects.AllWorldObjects; + for (int i = 0; i < allObjects.Count; i++) + { + WorldObject o = allObjects[i]; + if (!o.def.useDynamicDrawer && !this.ShouldSkip(o)) + { + Material mat = o.Material; + if ((Object)mat == (Object)null) + { + Log.ErrorOnce("World object " + o + " returned null material.", Gen.HashCombineInt(1948576891, o.ID)); + } + else + { + LayerSubMesh subMesh = base.GetSubMesh(mat); + Rand.PushState(); + Rand.Seed = o.ID; + o.Print(subMesh); + Rand.PopState(); + } + } + } + base.FinalizeMesh(MeshParts.All, false); } } } diff --git a/Assembly-CSharp/RimWorld.Planet/WorldLayer_WorldObjects_Expandable.cs b/Assembly-CSharp/RimWorld.Planet/WorldLayer_WorldObjects_Expandable.cs index 6ed24cafe..3e4315586 100644 --- a/Assembly-CSharp/RimWorld.Planet/WorldLayer_WorldObjects_Expandable.cs +++ b/Assembly-CSharp/RimWorld.Planet/WorldLayer_WorldObjects_Expandable.cs @@ -1,5 +1,3 @@ -using System; - namespace RimWorld.Planet { public class WorldLayer_WorldObjects_Expandable : WorldLayer_WorldObjects @@ -8,7 +6,7 @@ protected override float Alpha { get { - return 1f - ExpandableWorldObjectsUtility.TransitionPct; + return (float)(1.0 - ExpandableWorldObjectsUtility.TransitionPct); } } diff --git a/Assembly-CSharp/RimWorld.Planet/WorldLayer_WorldObjects_NonExpandable.cs b/Assembly-CSharp/RimWorld.Planet/WorldLayer_WorldObjects_NonExpandable.cs index 72edb85a8..a27971f8e 100644 --- a/Assembly-CSharp/RimWorld.Planet/WorldLayer_WorldObjects_NonExpandable.cs +++ b/Assembly-CSharp/RimWorld.Planet/WorldLayer_WorldObjects_NonExpandable.cs @@ -1,5 +1,3 @@ -using System; - namespace RimWorld.Planet { public class WorldLayer_WorldObjects_NonExpandable : WorldLayer_WorldObjects diff --git a/Assembly-CSharp/RimWorld.Planet/WorldMaterials.cs b/Assembly-CSharp/RimWorld.Planet/WorldMaterials.cs index 3252d2594..f337a487f 100644 --- a/Assembly-CSharp/RimWorld.Planet/WorldMaterials.cs +++ b/Assembly-CSharp/RimWorld.Planet/WorldMaterials.cs @@ -1,4 +1,3 @@ -using System; using UnityEngine; using Verse; @@ -112,12 +111,12 @@ static WorldMaterials() WorldMaterials.TargetSquareMatSingle = MaterialPool.MatFrom("UI/Overlays/TargetHighlight_Square", ShaderDatabase.Transparent, 3560); WorldMaterials.NumMatsPerMode = 50; WorldMaterials.OverlayModeMatOcean = SolidColorMaterials.NewSolidColorMaterial(new Color(0.09f, 0.18f, 0.2f), ShaderDatabase.Transparent); - WorldMaterials.FertilitySpectrum = new Color[] + WorldMaterials.FertilitySpectrum = new Color[2] { new Color(0f, 1f, 0f, 0f), new Color(0f, 1f, 0f, 0.5f) }; - WorldMaterials.TemperatureSpectrum = new Color[] + WorldMaterials.TemperatureSpectrum = new Color[8] { new Color(1f, 1f, 1f), new Color(0f, 0f, 1f), @@ -128,14 +127,14 @@ static WorldMaterials() new Color(1f, 0.6f, 0.18f), new Color(1f, 0f, 0f) }; - WorldMaterials.ElevationSpectrum = new Color[] + WorldMaterials.ElevationSpectrum = new Color[4] { new Color(0.224f, 0.18f, 0.15f), new Color(0.447f, 0.369f, 0.298f), new Color(0.6f, 0.6f, 0.6f), new Color(1f, 1f, 1f) }; - WorldMaterials.RainfallSpectrum = new Color[] + WorldMaterials.RainfallSpectrum = new Color[12] { new Color(0.9f, 0.9f, 0.9f), GenColor.FromBytes(190, 190, 190, 255), @@ -159,9 +158,9 @@ static WorldMaterials() private static void GenerateMats(ref Material[] mats, Color[] colorSpectrum, int numMats) { mats = new Material[numMats]; - for (int i = 0; i < numMats; i++) + for (int num = 0; num < numMats; num++) { - mats[i] = MatsFromSpectrum.Get(colorSpectrum, (float)i / (float)numMats); + mats[num] = MatsFromSpectrum.Get(colorSpectrum, (float)num / (float)numMats); } } diff --git a/Assembly-CSharp/RimWorld.Planet/WorldObject.cs b/Assembly-CSharp/RimWorld.Planet/WorldObject.cs index fe510d5b7..44e35a1bb 100644 --- a/Assembly-CSharp/RimWorld.Planet/WorldObject.cs +++ b/Assembly-CSharp/RimWorld.Planet/WorldObject.cs @@ -1,6 +1,5 @@ using System; using System.Collections.Generic; -using System.Diagnostics; using System.Linq; using System.Text; using UnityEngine; @@ -179,10 +178,7 @@ public virtual IEnumerable SpecialDisplayStats { get { - WorldObject.<>c__IteratorFC <>c__IteratorFC = new WorldObject.<>c__IteratorFC(); - WorldObject.<>c__IteratorFC expr_07 = <>c__IteratorFC; - expr_07.$PC = -2; - return expr_07; + yield break; } } @@ -218,17 +214,12 @@ public virtual void SetFaction(Faction newFaction) { if (!this.def.canHaveFaction && newFaction != null) { - Log.Warning(string.Concat(new object[] - { - "Tried to set faction to ", - newFaction, - " but this world object (", - this, - ") cannot have faction." - })); - return; + Log.Warning("Tried to set faction to " + newFaction + " but this world object (" + this + ") cannot have faction."); + } + else + { + this.factionInt = newFaction; } - this.factionInt = newFaction; } public virtual string GetInspectString() @@ -319,24 +310,24 @@ public virtual void PostRemove() public virtual void Print(LayerSubMesh subMesh) { float averageTileSize = Find.WorldGrid.averageTileSize; - WorldRendererUtility.PrintQuadTangentialToPlanet(this.DrawPos, 0.7f * averageTileSize, 0.015f, subMesh, false, true, true); + WorldRendererUtility.PrintQuadTangentialToPlanet(this.DrawPos, (float)(0.699999988079071 * averageTileSize), 0.015f, subMesh, false, true, true); } public virtual void Draw() { float averageTileSize = Find.WorldGrid.averageTileSize; float transitionPct = ExpandableWorldObjectsUtility.TransitionPct; - if (this.def.expandingIcon && transitionPct > 0f) + if (this.def.expandingIcon && transitionPct > 0.0) { Color color = this.Material.color; - float num = 1f - transitionPct; + float num = (float)(1.0 - transitionPct); WorldObject.propertyBlock.SetColor(ShaderPropertyIDs.Color, new Color(color.r, color.g, color.b, color.a * num)); MaterialPropertyBlock materialPropertyBlock = WorldObject.propertyBlock; - WorldRendererUtility.DrawQuadTangentialToPlanet(this.DrawPos, 0.7f * averageTileSize, 0.015f, this.Material, false, false, materialPropertyBlock); + WorldRendererUtility.DrawQuadTangentialToPlanet(this.DrawPos, (float)(0.699999988079071 * averageTileSize), 0.015f, this.Material, false, false, materialPropertyBlock); } else { - WorldRendererUtility.DrawQuadTangentialToPlanet(this.DrawPos, 0.7f * averageTileSize, 0.015f, this.Material, false, false, null); + WorldRendererUtility.DrawQuadTangentialToPlanet(this.DrawPos, (float)(0.699999988079071 * averageTileSize), 0.015f, this.Material, false, false, null); } } @@ -344,13 +335,13 @@ public T GetComponent() where T : WorldObjectComp { for (int i = 0; i < this.comps.Count; i++) { - T t = this.comps[i] as T; - if (t != null) + T val = (T)(this.comps[i] as T); + if (val != null) { - return t; + return val; } } - return (T)((object)null); + return (T)null; } public WorldObjectComp GetComponent(Type type) @@ -365,26 +356,26 @@ public WorldObjectComp GetComponent(Type type) return null; } - [DebuggerHidden] public virtual IEnumerable GetGizmos() { - WorldObject.c__IteratorFD c__IteratorFD = new WorldObject.c__IteratorFD(); - c__IteratorFD.<>f__this = this; - WorldObject.c__IteratorFD expr_0E = c__IteratorFD; - expr_0E.$PC = -2; - return expr_0E; + for (int i = 0; i < this.comps.Count; i++) + { + foreach (Gizmo gizmo in this.comps[i].GetGizmos()) + { + yield return gizmo; + } + } } - [DebuggerHidden] public virtual IEnumerable GetFloatMenuOptions(Caravan caravan) { - WorldObject.c__IteratorFE c__IteratorFE = new WorldObject.c__IteratorFE(); - c__IteratorFE.caravan = caravan; - c__IteratorFE.<$>caravan = caravan; - c__IteratorFE.<>f__this = this; - WorldObject.c__IteratorFE expr_1C = c__IteratorFE; - expr_1C.$PC = -2; - return expr_1C; + for (int i = 0; i < this.comps.Count; i++) + { + foreach (FloatMenuOption floatMenuOption in this.comps[i].GetFloatMenuOptions(caravan)) + { + yield return floatMenuOption; + } + } } public virtual IEnumerable GetInspectTabs() @@ -398,15 +389,7 @@ public virtual IEnumerable GetInspectTabs() public override string ToString() { - return string.Concat(new object[] - { - base.GetType().Name, - " ", - this.LabelCap, - " (tile=", - this.Tile, - ")" - }); + return base.GetType().Name + " " + this.LabelCap + " (tile=" + this.Tile + ")"; } public override int GetHashCode() diff --git a/Assembly-CSharp/RimWorld.Planet/WorldObjectComp.cs b/Assembly-CSharp/RimWorld.Planet/WorldObjectComp.cs index c00b97252..49df27953 100644 --- a/Assembly-CSharp/RimWorld.Planet/WorldObjectComp.cs +++ b/Assembly-CSharp/RimWorld.Planet/WorldObjectComp.cs @@ -1,6 +1,4 @@ -using System; using System.Collections.Generic; -using System.Diagnostics; using Verse; namespace RimWorld.Planet @@ -28,32 +26,24 @@ public virtual void CompTick() { } - [DebuggerHidden] public virtual IEnumerable GetGizmos() { - WorldObjectComp.c__Iterator10E c__Iterator10E = new WorldObjectComp.c__Iterator10E(); - WorldObjectComp.c__Iterator10E expr_07 = c__Iterator10E; - expr_07.$PC = -2; - return expr_07; + yield break; } - [DebuggerHidden] public virtual IEnumerable GetFloatMenuOptions(Caravan caravan) { - WorldObjectComp.c__Iterator10F c__Iterator10F = new WorldObjectComp.c__Iterator10F(); - WorldObjectComp.c__Iterator10F expr_07 = c__Iterator10F; - expr_07.$PC = -2; - return expr_07; + yield break; } public virtual string CompInspectStringExtra() { - return null; + return (string)null; } public virtual string GetDescriptionPart() { - return null; + return (string)null; } public virtual void PostPostRemove() @@ -66,15 +56,7 @@ public virtual void PostExposeData() public override string ToString() { - return string.Concat(new object[] - { - base.GetType().Name, - "(parent=", - this.parent, - " at=", - (this.parent == null) ? -1 : this.parent.Tile, - ")" - }); + return base.GetType().Name + "(parent=" + this.parent + " at=" + ((this.parent == null) ? (-1) : this.parent.Tile) + ")"; } } } diff --git a/Assembly-CSharp/RimWorld.Planet/WorldObjectSelectionUtility.cs b/Assembly-CSharp/RimWorld.Planet/WorldObjectSelectionUtility.cs index a9e0be271..ddc5f594a 100644 --- a/Assembly-CSharp/RimWorld.Planet/WorldObjectSelectionUtility.cs +++ b/Assembly-CSharp/RimWorld.Planet/WorldObjectSelectionUtility.cs @@ -1,6 +1,4 @@ -using System; using System.Collections.Generic; -using System.Diagnostics; using UnityEngine; using Verse; @@ -8,22 +6,33 @@ namespace RimWorld.Planet { public static class WorldObjectSelectionUtility { - [DebuggerHidden] public static IEnumerable MultiSelectableWorldObjectsInScreenRectDistinct(Rect rect) { - WorldObjectSelectionUtility.c__Iterator1A5 c__Iterator1A = new WorldObjectSelectionUtility.c__Iterator1A5(); - c__Iterator1A.rect = rect; - c__Iterator1A.<$>rect = rect; - WorldObjectSelectionUtility.c__Iterator1A5 expr_15 = c__Iterator1A; - expr_15.$PC = -2; - return expr_15; + List allObjects = Find.WorldObjects.AllWorldObjects; + for (int i = 0; i < allObjects.Count; i++) + { + if (!allObjects[i].NeverMultiSelect && !allObjects[i].HiddenBehindTerrainNow()) + { + if (ExpandableWorldObjectsUtility.IsExpanded(allObjects[i])) + { + if (rect.Overlaps(ExpandableWorldObjectsUtility.ExpandedIconScreenRect(allObjects[i]))) + { + yield return allObjects[i]; + } + } + else if (rect.Contains(allObjects[i].ScreenPos())) + { + yield return allObjects[i]; + } + } + } } public static bool HiddenBehindTerrainNow(this WorldObject o) { Vector3 normalized = o.DrawPos.normalized; Vector3 currentlyLookingAtPointOnSphere = Find.WorldCameraDriver.CurrentlyLookingAtPointOnSphere; - return Vector3.Angle(normalized, currentlyLookingAtPointOnSphere) > 73f; + return Vector3.Angle(normalized, currentlyLookingAtPointOnSphere) > 73.0; } public static Vector2 ScreenPos(this WorldObject o) @@ -43,15 +52,14 @@ public static bool VisibleToCameraNow(this WorldObject o) return false; } Vector2 point = o.ScreenPos(); - Rect rect = new Rect(0f, 0f, (float)UI.screenWidth, (float)UI.screenHeight); - return rect.Contains(point); + return new Rect(0f, 0f, (float)UI.screenWidth, (float)UI.screenHeight).Contains(point); } public static float DistanceToMouse(this WorldObject o, Vector2 mousePos) { Ray ray = Find.WorldCamera.ScreenPointToRay(mousePos * Prefs.UIScale); int worldLayerMask = WorldCameraManager.WorldLayerMask; - RaycastHit raycastHit; + RaycastHit raycastHit = default(RaycastHit); if (Physics.Raycast(ray, out raycastHit, 1500f, worldLayerMask)) { return Vector3.Distance(raycastHit.point, o.DrawPos); diff --git a/Assembly-CSharp/RimWorld.Planet/WorldObjectsHolder.cs b/Assembly-CSharp/RimWorld.Planet/WorldObjectsHolder.cs index d1c6969ec..0676f9b0e 100644 --- a/Assembly-CSharp/RimWorld.Planet/WorldObjectsHolder.cs +++ b/Assembly-CSharp/RimWorld.Planet/WorldObjectsHolder.cs @@ -1,6 +1,4 @@ -using System; using System.Collections.Generic; -using System.Diagnostics; using Verse; namespace RimWorld.Planet @@ -146,12 +144,12 @@ public void ExposeData() if (Scribe.mode == LoadSaveMode.Saving) { WorldObjectsHolder.tmpUnsavedWorldObjects.Clear(); - for (int i = this.worldObjects.Count - 1; i >= 0; i--) + for (int num = this.worldObjects.Count - 1; num >= 0; num--) { - if (!this.worldObjects[i].def.saved) + if (!this.worldObjects[num].def.saved) { - WorldObjectsHolder.tmpUnsavedWorldObjects.Add(this.worldObjects[i]); - this.worldObjects.RemoveAt(i); + WorldObjectsHolder.tmpUnsavedWorldObjects.Add(this.worldObjects[num]); + this.worldObjects.RemoveAt(num); } } } @@ -163,9 +161,9 @@ public void ExposeData() } if (Scribe.mode == LoadSaveMode.PostLoadInit) { - for (int j = 0; j < this.worldObjects.Count; j++) + for (int i = 0; i < this.worldObjects.Count; i++) { - this.worldObjects[j].SpawnSetup(); + this.worldObjects[i].SpawnSetup(); } this.Recache(); } @@ -176,17 +174,19 @@ public void Add(WorldObject o) if (this.worldObjects.Contains(o)) { Log.Error("Tried to add world object " + o + " to world, but it's already here."); - return; } - if (o.Tile < 0) + else { - Log.Error("Tried to add world object " + o + " but its tile is not set. Setting to 0."); - o.Tile = 0; + if (o.Tile < 0) + { + Log.Error("Tried to add world object " + o + " but its tile is not set. Setting to 0."); + o.Tile = 0; + } + this.worldObjects.Add(o); + this.AddToCache(o); + o.SpawnSetup(); + o.PostAdd(); } - this.worldObjects.Add(o); - this.AddToCache(o); - o.SpawnSetup(); - o.PostAdd(); } public void Remove(WorldObject o) @@ -194,11 +194,13 @@ public void Remove(WorldObject o) if (!this.worldObjects.Contains(o)) { Log.Error("Tried to remove world object " + o + " from world, but it's not here."); - return; } - this.worldObjects.Remove(o); - this.RemoveFromCache(o); - o.PostRemove(); + else + { + this.worldObjects.Remove(o); + this.RemoveFromCache(o); + o.PostRemove(); + } } public void WorldObjectsHolderTick() @@ -316,16 +318,18 @@ public bool Contains(WorldObject o) return this.worldObjects.Contains(o); } - [DebuggerHidden] public IEnumerable ObjectsAt(int tileID) { - WorldObjectsHolder.c__Iterator110 c__Iterator = new WorldObjectsHolder.c__Iterator110(); - c__Iterator.tileID = tileID; - c__Iterator.<$>tileID = tileID; - c__Iterator.<>f__this = this; - WorldObjectsHolder.c__Iterator110 expr_1C = c__Iterator; - expr_1C.$PC = -2; - return expr_1C; + if (tileID >= 0) + { + for (int i = 0; i < this.worldObjects.Count; i++) + { + if (this.worldObjects[i].Tile == tileID) + { + yield return this.worldObjects[i]; + } + } + } } public bool AnyWorldObjectAt(int tile) @@ -346,10 +350,10 @@ public T WorldObjectAt(int tile) where T : class { if (this.worldObjects[i].Tile == tile && this.worldObjects[i] is T) { - return this.worldObjects[i] as T; + return (T)(((object)this.worldObjects[i]) as T); } } - return (T)((object)null); + return (T)null; } public bool AnyFactionBaseAt(int tile) diff --git a/Assembly-CSharp/RimWorld.Planet/WorldPath.cs b/Assembly-CSharp/RimWorld.Planet/WorldPath.cs index 337f2eeff..5d6464c91 100644 --- a/Assembly-CSharp/RimWorld.Planet/WorldPath.cs +++ b/Assembly-CSharp/RimWorld.Planet/WorldPath.cs @@ -19,7 +19,7 @@ public bool Found { get { - return this.totalCostInt >= 0f; + return this.totalCostInt >= 0.0; } } @@ -81,10 +81,12 @@ public void SetupFound(float totalCost) if (this == WorldPath.NotFound) { Log.Warning("Calling SetupFound with totalCost=" + totalCost + " on WorldPath.NotFound"); - return; } - this.totalCostInt = totalCost; - this.curNodeIndex = this.nodes.Count - 1; + else + { + this.totalCostInt = totalCost; + this.curNodeIndex = this.nodes.Count - 1; + } } public void Dispose() @@ -104,10 +106,9 @@ public void ReleaseToPool() public static WorldPath NewNotFound() { - return new WorldPath - { - totalCostInt = -1f - }; + WorldPath worldPath = new WorldPath(); + worldPath.totalCostInt = -1f; + return worldPath; } public int ConsumeNextNode() @@ -132,30 +133,12 @@ public override string ToString() { return "WorldPath(not in use)"; } - return string.Concat(new object[] - { - "WorldPath(nodeCount= ", - this.nodes.Count, - (this.nodes.Count <= 0) ? string.Empty : string.Concat(new object[] - { - " first=", - this.FirstNode, - " last=", - this.LastNode - }), - " cost=", - this.totalCostInt, - " )" - }); + return "WorldPath(nodeCount= " + this.nodes.Count + ((this.nodes.Count <= 0) ? string.Empty : (" first=" + this.FirstNode + " last=" + this.LastNode)) + " cost=" + this.totalCostInt + " )"; } public void DrawPath(Caravan pathingCaravan) { - if (!this.Found) - { - return; - } - if (this.NodesLeftCount > 0) + if (this.Found && this.NodesLeftCount > 0) { WorldGrid worldGrid = Find.WorldGrid; float d = 0.05f; @@ -173,7 +156,7 @@ public void DrawPath(Caravan pathingCaravan) Vector3 vector2 = worldGrid.GetTileCenter(this.Peek(0)); a2 += a2.normalized * d; vector2 += vector2.normalized * d; - if ((a2 - vector2).sqrMagnitude > 0.005f) + if ((a2 - vector2).sqrMagnitude > 0.004999999888241291) { GenDraw.DrawWorldLineBetween(a2, vector2); } diff --git a/Assembly-CSharp/RimWorld.Planet/WorldPathFinder.cs b/Assembly-CSharp/RimWorld.Planet/WorldPathFinder.cs index 4dbd7b3a6..2b151b4ff 100644 --- a/Assembly-CSharp/RimWorld.Planet/WorldPathFinder.cs +++ b/Assembly-CSharp/RimWorld.Planet/WorldPathFinder.cs @@ -33,9 +33,9 @@ private struct PathFinderNodeFast public ushort status; } - private class CostNodeComparer : IComparer + private class CostNodeComparer : IComparer { - public int Compare(WorldPathFinder.CostNode a, WorldPathFinder.CostNode b) + public int Compare(CostNode a, CostNode b) { int cost = a.cost; int cost2 = b.cost; @@ -55,13 +55,13 @@ public int Compare(WorldPathFinder.CostNode a, WorldPathFinder.CostNode b) private const float BestRoadDiscount = 0.5f; - private FastPriorityQueue openList; + private FastPriorityQueue openList; - private WorldPathFinder.PathFinderNodeFast[] calcGrid; + private PathFinderNodeFast[] calcGrid; - private ushort statusOpenValue = 1; + private ushort statusOpenValue = (ushort)1; - private ushort statusClosedValue = 2; + private ushort statusClosedValue = (ushort)2; private static readonly SimpleCurve HeuristicStrength_DistanceCurve = new SimpleCurve { @@ -81,32 +81,20 @@ public int Compare(WorldPathFinder.CostNode a, WorldPathFinder.CostNode b) public WorldPathFinder() { - this.calcGrid = new WorldPathFinder.PathFinderNodeFast[Find.WorldGrid.TilesCount]; - this.openList = new FastPriorityQueue(new WorldPathFinder.CostNodeComparer()); + this.calcGrid = new PathFinderNodeFast[Find.WorldGrid.TilesCount]; + this.openList = new FastPriorityQueue(new CostNodeComparer()); } public WorldPath FindPath(int startTile, int destTile, Caravan caravan, Func terminator = null) { if (startTile < 0) { - Log.Error(string.Concat(new object[] - { - "Tried to FindPath with invalid start tile ", - startTile, - ", caravan= ", - caravan - })); + Log.Error("Tried to FindPath with invalid start tile " + startTile + ", caravan= " + caravan); return WorldPath.NotFound; } if (destTile < 0) { - Log.Error(string.Concat(new object[] - { - "Tried to FindPath with invalid dest tile ", - destTile, - ", caravan= ", - caravan - })); + Log.Error("Tried to FindPath with invalid dest tile " + destTile + ", caravan= " + caravan); return WorldPath.NotFound; } if (caravan != null) @@ -129,8 +117,8 @@ public WorldPath FindPath(int startTile, int destTile, Caravan caravan, Func= 65435) { this.ResetStatuses(); @@ -141,10 +129,15 @@ public WorldPath FindPath(int startTile, int destTile, Caravan caravan, Func 0) + this.openList.Push(new CostNode(startTile, 0)); + while (true) { - WorldPathFinder.CostNode costNode = this.openList.Pop(); + if (this.openList.Count <= 0) + { + Log.Warning(caravan + " pathing from " + startTile + " to " + destTile + " ran out of tiles to process."); + return WorldPath.NotFound; + } + CostNode costNode = this.openList.Pop(); if (costNode.cost == this.calcGrid[costNode.tile].costNodeCost) { int tile = costNode.tile; @@ -152,7 +145,7 @@ public WorldPath FindPath(int startTile, int destTile, Caravan caravan, Func 500000) { - Log.Warning(string.Concat(new object[] - { - caravan, - " pathing from ", - startTile, - " to ", - destTile, - " hit search limit of ", - 500000, - " tiles." - })); + Log.Warning(caravan + " pathing from " + startTile + " to " + destTile + " hit search limit of " + 500000 + " tiles."); return WorldPath.NotFound; } int num4 = (tile + 1 >= tileIDToNeighbors_offsets.Count) ? tileIDToNeighbors_values.Count : tileIDToNeighbors_offsets[tile + 1]; for (int i = tileIDToNeighbors_offsets[tile]; i < num4; i++) { int num5 = tileIDToNeighbors_values[i]; - if (this.calcGrid[num5].status != this.statusClosedValue) + int num7; + ushort status; + if (this.calcGrid[num5].status != this.statusClosedValue && !world.Impassable(num5)) { - if (!world.Impassable(num5)) + int num6 = num2; + num6 += pathGrid[num5]; + num6 = (int)((float)num6 * grid.GetRoadMovementMultiplierFast(tile, num5)); + num7 = num6 + this.calcGrid[tile].knownCost; + status = this.calcGrid[num5].status; + if (status != this.statusClosedValue && status != this.statusOpenValue) { - int num6 = num2; - num6 += pathGrid[num5]; - num6 = (int)((float)num6 * grid.GetRoadMovementMultiplierFast(tile, num5)); - int num7 = num6 + this.calcGrid[tile].knownCost; - ushort status = this.calcGrid[num5].status; - if ((status != this.statusClosedValue && status != this.statusOpenValue) || this.calcGrid[num5].knownCost > num7) - { - Vector3 tileCenter = grid.GetTileCenter(num5); - if (status != this.statusClosedValue && status != this.statusOpenValue) - { - float num8 = grid.ApproxDistanceInTiles(GenMath.SphericalDistance(tileCenter.normalized, normalized)); - this.calcGrid[num5].heuristicCost = Mathf.RoundToInt((float)num2 * num8 * (float)num3 * 0.5f); - } - int num9 = num7 + this.calcGrid[num5].heuristicCost; - this.calcGrid[num5].parentTile = tile; - this.calcGrid[num5].knownCost = num7; - this.calcGrid[num5].status = this.statusOpenValue; - this.calcGrid[num5].costNodeCost = num9; - this.openList.Push(new WorldPathFinder.CostNode(num5, num9)); - } + goto IL_0416; } + if (this.calcGrid[num5].knownCost > num7) + goto IL_0416; + } + continue; + IL_0416: + Vector3 tileCenter = grid.GetTileCenter(num5); + if (status != this.statusClosedValue && status != this.statusOpenValue) + { + float num8 = grid.ApproxDistanceInTiles(GenMath.SphericalDistance(tileCenter.normalized, normalized)); + this.calcGrid[num5].heuristicCost = Mathf.RoundToInt((float)((float)num2 * num8 * (float)num3 * 0.5)); } + int num9 = num7 + this.calcGrid[num5].heuristicCost; + this.calcGrid[num5].parentTile = tile; + this.calcGrid[num5].knownCost = num7; + this.calcGrid[num5].status = this.statusOpenValue; + this.calcGrid[num5].costNodeCost = num9; + this.openList.Push(new CostNode(num5, num9)); } num++; this.calcGrid[tile].status = this.statusClosedValue; - if (terminator != null && terminator((float)this.calcGrid[tile].costNodeCost)) - { - return WorldPath.NotFound; - } + if ((object)terminator != null && terminator((float)this.calcGrid[tile].costNodeCost)) + break; } } } - Log.Warning(string.Concat(new object[] - { - caravan, - " pathing from ", - startTile, - " to ", - destTile, - " ran out of tiles to process." - })); return WorldPath.NotFound; } public void FloodPathsWithCost(List startTiles, Func costFunc, Func impassable = null, Func terminator = null) { - if (startTiles.Count >= 1) + if (startTiles.Count < 1 || startTiles.Any((Predicate)((int st) => st == -1))) { - if (!startTiles.Any((int st) => st == -1)) + Log.Error("Tried to FindPath with invalid start tiles"); + } + else + { + World world = Find.World; + WorldGrid grid = world.grid; + List tileIDToNeighbors_offsets = grid.tileIDToNeighbors_offsets; + List tileIDToNeighbors_values = grid.tileIDToNeighbors_values; + if ((object)impassable == null) { - World world = Find.World; - WorldGrid grid = world.grid; - List tileIDToNeighbors_offsets = grid.tileIDToNeighbors_offsets; - List tileIDToNeighbors_values = grid.tileIDToNeighbors_values; - if (impassable == null) - { - impassable = ((int tid) => world.Impassable(tid)); - } - this.statusOpenValue += 2; - this.statusClosedValue += 2; - if (this.statusClosedValue >= 65435) - { - this.ResetStatuses(); - } - this.openList.Clear(); - foreach (int current in startTiles) + impassable = (Func)((int tid) => world.Impassable(tid)); + } + this.statusOpenValue = (ushort)(this.statusOpenValue + 2); + this.statusClosedValue = (ushort)(this.statusClosedValue + 2); + if (this.statusClosedValue >= 65435) + { + this.ResetStatuses(); + } + this.openList.Clear(); + List.Enumerator enumerator = startTiles.GetEnumerator(); + try + { + while (enumerator.MoveNext()) { + int current = enumerator.Current; this.calcGrid[current].knownCost = 0; this.calcGrid[current].costNodeCost = 0; this.calcGrid[current].parentTile = current; this.calcGrid[current].status = this.statusOpenValue; - this.openList.Push(new WorldPathFinder.CostNode(current, 0)); + this.openList.Push(new CostNode(current, 0)); } - while (this.openList.Count > 0) + } + finally + { + ((IDisposable)(object)enumerator).Dispose(); + } + while (this.openList.Count > 0) + { + CostNode costNode = this.openList.Pop(); + if (costNode.cost == this.calcGrid[costNode.tile].costNodeCost) { - WorldPathFinder.CostNode costNode = this.openList.Pop(); - if (costNode.cost == this.calcGrid[costNode.tile].costNodeCost) + int tile = costNode.tile; + if (this.calcGrid[tile].status != this.statusClosedValue) { - int tile = costNode.tile; - if (this.calcGrid[tile].status != this.statusClosedValue) + int num = (tile + 1 >= tileIDToNeighbors_offsets.Count) ? tileIDToNeighbors_values.Count : tileIDToNeighbors_offsets[tile + 1]; + for (int i = tileIDToNeighbors_offsets[tile]; i < num; i++) { - int num = (tile + 1 >= tileIDToNeighbors_offsets.Count) ? tileIDToNeighbors_values.Count : tileIDToNeighbors_offsets[tile + 1]; - for (int i = tileIDToNeighbors_offsets[tile]; i < num; i++) + int num2 = tileIDToNeighbors_values[i]; + int num4; + if (this.calcGrid[num2].status != this.statusClosedValue && !impassable(num2)) { - int num2 = tileIDToNeighbors_values[i]; - if (this.calcGrid[num2].status != this.statusClosedValue) + int num3 = costFunc(tile, num2); + num4 = num3 + this.calcGrid[tile].knownCost; + ushort status = this.calcGrid[num2].status; + if (status != this.statusClosedValue && status != this.statusOpenValue) { - if (!impassable(num2)) - { - int num3 = costFunc(tile, num2); - int num4 = num3 + this.calcGrid[tile].knownCost; - ushort status = this.calcGrid[num2].status; - if ((status != this.statusClosedValue && status != this.statusOpenValue) || this.calcGrid[num2].knownCost > num4) - { - int num5 = num4; - this.calcGrid[num2].parentTile = tile; - this.calcGrid[num2].knownCost = num4; - this.calcGrid[num2].status = this.statusOpenValue; - this.calcGrid[num2].costNodeCost = num5; - this.openList.Push(new WorldPathFinder.CostNode(num2, num5)); - } - } + goto IL_029a; } + if (this.calcGrid[num2].knownCost > num4) + goto IL_029a; } - this.calcGrid[tile].status = this.statusClosedValue; - if (terminator != null && terminator(tile, (float)this.calcGrid[tile].costNodeCost)) - { - break; - } + continue; + IL_029a: + int num5 = num4; + this.calcGrid[num2].parentTile = tile; + this.calcGrid[num2].knownCost = num4; + this.calcGrid[num2].status = this.statusOpenValue; + this.calcGrid[num2].costNodeCost = num5; + this.openList.Push(new CostNode(num2, num5)); } + this.calcGrid[tile].status = this.statusClosedValue; + if ((object)terminator != null && terminator(tile, (float)this.calcGrid[tile].costNodeCost)) + break; } } - return; } } - Log.Error("Tried to FindPath with invalid start tiles"); } public List[] FloodPathsWithCostForTree(List startTiles, Func costFunc, Func impassable = null, Func terminator = null) @@ -329,15 +314,16 @@ private WorldPath FinalizedPath(int lastTile) int num = lastTile; while (true) { - WorldPathFinder.PathFinderNodeFast pathFinderNodeFast = this.calcGrid[num]; + PathFinderNodeFast pathFinderNodeFast = this.calcGrid[num]; int parentTile = pathFinderNodeFast.parentTile; int num2 = num; emptyWorldPath.AddNode(num2); - if (num2 == parentTile) + if (num2 != parentTile) { - break; + num = parentTile; + continue; } - num = parentTile; + break; } emptyWorldPath.SetupFound((float)this.calcGrid[lastTile].knownCost); return emptyWorldPath; @@ -346,12 +332,12 @@ private WorldPath FinalizedPath(int lastTile) private void ResetStatuses() { int num = this.calcGrid.Length; - for (int i = 0; i < num; i++) + for (int num2 = 0; num2 < num; num2++) { - this.calcGrid[i].status = 0; + this.calcGrid[num2].status = (ushort)0; } - this.statusOpenValue = 1; - this.statusClosedValue = 2; + this.statusOpenValue = (ushort)1; + this.statusClosedValue = (ushort)2; } private int CalculateHeuristicStrength(int startTile, int destTile) diff --git a/Assembly-CSharp/RimWorld.Planet/WorldPathGrid.cs b/Assembly-CSharp/RimWorld.Planet/WorldPathGrid.cs index 70a7859c2..1f6d98ed8 100644 --- a/Assembly-CSharp/RimWorld.Planet/WorldPathGrid.cs +++ b/Assembly-CSharp/RimWorld.Planet/WorldPathGrid.cs @@ -1,4 +1,3 @@ -using System; using UnityEngine; using Verse; @@ -16,7 +15,7 @@ private static int DayOfYearAt0Long { get { - return GenDate.DayOfYear((long)GenTicks.TicksAbs, 0f); + return GenDate.DayOfYear(GenTicks.TicksAbs, 0f); } } @@ -40,7 +39,11 @@ public void WorldPathGridTick() public bool Passable(int tile) { - return Find.WorldGrid.InBounds(tile) && this.pathGrid[tile] < 1000000; + if (!Find.WorldGrid.InBounds(tile)) + { + return false; + } + return this.pathGrid[tile] < 1000000; } public bool PassableFast(int tile) @@ -55,15 +58,14 @@ public int PerceivedPathCostAt(int tile) public void RecalculatePerceivedPathCostAt(int tile, float yearPercent = -1f) { - if (!Find.WorldGrid.InBounds(tile)) + if (Find.WorldGrid.InBounds(tile)) { - return; - } - bool flag = this.PassableFast(tile); - this.pathGrid[tile] = WorldPathGrid.CalculatedCostAt(tile, true, yearPercent); - if (flag != this.PassableFast(tile)) - { - Find.WorldReachability.ClearCache(); + bool flag = this.PassableFast(tile); + this.pathGrid[tile] = WorldPathGrid.CalculatedCostAt(tile, true, yearPercent); + if (flag != this.PassableFast(tile)) + { + Find.WorldReachability.ClearCache(); + } } } @@ -84,14 +86,15 @@ public static int CalculatedCostAt(int tile, bool perceivedStatic, float yearPer { return 1000000; } - if (yearPercent < 0f) + if (yearPercent < 0.0) { - yearPercent = (float)WorldPathGrid.DayOfYearAt0Long / 60f; + yearPercent = (float)((float)WorldPathGrid.DayOfYearAt0Long / 60.0); } float num2 = yearPercent; - if (Find.WorldGrid.LongLatOf(tile).y < 0f) + Vector2 vector = Find.WorldGrid.LongLatOf(tile); + if (vector.y < 0.0) { - num2 = (num2 + 0.5f) % 1f; + num2 = (float)((num2 + 0.5) % 1.0); } num += Mathf.RoundToInt(tile2.biome.pathCost.Evaluate(num2)); if (tile2.hilliness == Hilliness.Impassable) @@ -106,18 +109,30 @@ private static int CostFromTileHilliness(Hilliness hilliness) switch (hilliness) { case Hilliness.Flat: + { return 0; + } case Hilliness.SmallHills: + { return 2000; + } case Hilliness.LargeHills: + { return 6000; + } case Hilliness.Mountainous: + { return 30000; + } case Hilliness.Impassable: + { return 30000; + } default: + { return 0; } + } } } } diff --git a/Assembly-CSharp/RimWorld.Planet/WorldPathPool.cs b/Assembly-CSharp/RimWorld.Planet/WorldPathPool.cs index 4f552655d..898989133 100644 --- a/Assembly-CSharp/RimWorld.Planet/WorldPathPool.cs +++ b/Assembly-CSharp/RimWorld.Planet/WorldPathPool.cs @@ -1,4 +1,3 @@ -using System; using System.Collections.Generic; using Verse; diff --git a/Assembly-CSharp/RimWorld.Planet/WorldPawnSituation.cs b/Assembly-CSharp/RimWorld.Planet/WorldPawnSituation.cs index c79e6ab94..367dc11f4 100644 --- a/Assembly-CSharp/RimWorld.Planet/WorldPawnSituation.cs +++ b/Assembly-CSharp/RimWorld.Planet/WorldPawnSituation.cs @@ -1,16 +1,14 @@ -using System; - namespace RimWorld.Planet { public enum WorldPawnSituation { - None, - Free, - Dead, - FactionLeader, - Kidnapped, - CaravanMember, - InTravelingTransportPod, - ForSaleBySettlement + None = 0, + Free = 1, + Dead = 2, + FactionLeader = 3, + Kidnapped = 4, + CaravanMember = 5, + InTravelingTransportPod = 6, + ForSaleBySettlement = 7 } } diff --git a/Assembly-CSharp/RimWorld.Planet/WorldPawns.cs b/Assembly-CSharp/RimWorld.Planet/WorldPawns.cs index fd4607557..ff7f82f1f 100644 --- a/Assembly-CSharp/RimWorld.Planet/WorldPawns.cs +++ b/Assembly-CSharp/RimWorld.Planet/WorldPawns.cs @@ -64,14 +64,23 @@ public void WorldPawnsTick() } WorldPawns.tmpPawnsToTick.Clear(); WorldPawns.tmpPawnsToRemove.Clear(); - foreach (Pawn current in this.pawnsDead) + HashSet.Enumerator enumerator = this.pawnsDead.GetEnumerator(); + try { - if (current.Discarded) + while (enumerator.MoveNext()) { - Log.Error("World pawn " + current + " has been discarded while still being a world pawn. This should never happen, because discard destroy mode means that the pawn is no longer managed by anything. Pawn should have been removed from the world first."); - WorldPawns.tmpPawnsToRemove.Add(current); + Pawn current = enumerator.Current; + if (current.Discarded) + { + Log.Error("World pawn " + current + " has been discarded while still being a world pawn. This should never happen, because discard destroy mode means that the pawn is no longer managed by anything. Pawn should have been removed from the world first."); + WorldPawns.tmpPawnsToRemove.Add(current); + } } } + finally + { + ((IDisposable)(object)enumerator).Dispose(); + } for (int j = 0; j < WorldPawns.tmpPawnsToRemove.Count; j++) { this.pawnsDead.Remove(WorldPawns.tmpPawnsToRemove[j]); @@ -96,37 +105,44 @@ public void PassToWorld(Pawn pawn, PawnDiscardDecideMode discardMode = PawnDisca if (pawn.Spawned) { Log.Error("Tried to call PassToWorld with spawned pawn: " + pawn + ". Despawn him first."); - return; } - if (this.Contains(pawn)) + else if (this.Contains(pawn)) { Log.Error("Tried to pass pawn " + pawn + " to world, but it's already here."); - return; - } - if (discardMode == PawnDiscardDecideMode.KeepForever && pawn.Discarded) - { - Log.Error("Tried to pass a discarded pawn " + pawn + " to world with discardMode=Keep. Discarded pawns should never be stored in WorldPawns."); - discardMode = PawnDiscardDecideMode.Decide; } - switch (discardMode) + else { - case PawnDiscardDecideMode.Decide: - if (this.ShouldKeep(pawn)) + if (discardMode == PawnDiscardDecideMode.KeepForever && pawn.Discarded) + { + Log.Error("Tried to pass a discarded pawn " + pawn + " to world with discardMode=Keep. Discarded pawns should never be stored in WorldPawns."); + discardMode = PawnDiscardDecideMode.Decide; + } + switch (discardMode) + { + case PawnDiscardDecideMode.Decide: + { + if (this.ShouldKeep(pawn)) + { + this.AddPawn(pawn); + } + else + { + this.DiscardPawn(pawn); + } + break; + } + case PawnDiscardDecideMode.KeepForever: { + this.pawnsForcefullyKeptAsWorldPawns.Add(pawn); this.AddPawn(pawn); + break; } - else + case PawnDiscardDecideMode.Discard: { this.DiscardPawn(pawn); + break; + } } - break; - case PawnDiscardDecideMode.KeepForever: - this.pawnsForcefullyKeptAsWorldPawns.Add(pawn); - this.AddPawn(pawn); - break; - case PawnDiscardDecideMode.Discard: - this.DiscardPawn(pawn); - break; } } @@ -134,14 +150,7 @@ public void RemovePawn(Pawn p) { if (!this.Contains(p)) { - Log.Error(string.Concat(new object[] - { - "Tried to remove pawn ", - p, - " from ", - base.GetType(), - ", but it's not here." - })); + Log.Error("Tried to remove pawn " + p + " from " + base.GetType() + ", but it's not here."); } this.pawnsAlive.Remove(p); this.pawnsDead.Remove(p); @@ -154,31 +163,31 @@ public WorldPawnSituation GetSituation(Pawn p) { return WorldPawnSituation.None; } - if (p.Dead || p.Destroyed) + if (!p.Dead && !p.Destroyed) { - return WorldPawnSituation.Dead; - } - if (PawnUtility.IsFactionLeader(p)) - { - return WorldPawnSituation.FactionLeader; - } - if (PawnUtility.IsKidnappedPawn(p)) - { - return WorldPawnSituation.Kidnapped; - } - if (p.IsCaravanMember()) - { - return WorldPawnSituation.CaravanMember; - } - if (PawnUtility.IsTravelingInTransportPodWorldObject(p)) - { - return WorldPawnSituation.InTravelingTransportPod; - } - if (PawnUtility.ForSaleBySettlement(p)) - { - return WorldPawnSituation.ForSaleBySettlement; + if (PawnUtility.IsFactionLeader(p)) + { + return WorldPawnSituation.FactionLeader; + } + if (PawnUtility.IsKidnappedPawn(p)) + { + return WorldPawnSituation.Kidnapped; + } + if (p.IsCaravanMember()) + { + return WorldPawnSituation.CaravanMember; + } + if (PawnUtility.IsTravelingInTransportPodWorldObject(p)) + { + return WorldPawnSituation.InTravelingTransportPod; + } + if (PawnUtility.ForSaleBySettlement(p)) + { + return WorldPawnSituation.ForSaleBySettlement; + } + return WorldPawnSituation.Free; } - return WorldPawnSituation.Free; + return WorldPawnSituation.Dead; } public IEnumerable GetPawnsBySituation(WorldPawnSituation situation) @@ -191,21 +200,39 @@ where this.GetSituation(x) == situation public int GetPawnsBySituationCount(WorldPawnSituation situation) { int num = 0; - foreach (Pawn current in this.pawnsAlive) + HashSet.Enumerator enumerator = this.pawnsAlive.GetEnumerator(); + try { - if (this.GetSituation(current) == situation) + while (enumerator.MoveNext()) { - num++; + Pawn current = enumerator.Current; + if (this.GetSituation(current) == situation) + { + num++; + } } } - foreach (Pawn current2 in this.pawnsDead) + finally + { + ((IDisposable)(object)enumerator).Dispose(); + } + HashSet.Enumerator enumerator2 = this.pawnsDead.GetEnumerator(); + try { - if (this.GetSituation(current2) == situation) + while (enumerator2.MoveNext()) { - num++; + Pawn current2 = enumerator2.Current; + if (this.GetSituation(current2) == situation) + { + num++; + } } + return num; + } + finally + { + ((IDisposable)(object)enumerator2).Dispose(); } - return num; } private bool ShouldAutoTendTo(Pawn pawn) @@ -215,19 +242,17 @@ private bool ShouldAutoTendTo(Pawn pawn) public void DiscardIfUnimportant(Pawn pawn) { - if (pawn.Discarded) - { - return; - } - if (!this.Contains(pawn)) - { - Log.Warning(pawn + " is not a world pawn."); - return; - } - if (!this.ShouldKeep(pawn)) + if (!pawn.Discarded) { - this.RemovePawn(pawn); - this.DiscardPawn(pawn); + if (!this.Contains(pawn)) + { + Log.Warning(pawn + " is not a world pawn."); + } + else if (!this.ShouldKeep(pawn)) + { + this.RemovePawn(pawn); + this.DiscardPawn(pawn); + } } } @@ -249,28 +274,21 @@ public void LogWorldPawns() { StringBuilder stringBuilder = new StringBuilder(); stringBuilder.AppendLine("======= World Pawns ======="); - stringBuilder.AppendLine("Count: " + this.AllPawnsAliveOrDead.Count()); + stringBuilder.AppendLine("Count: " + this.AllPawnsAliveOrDead.Count()); WorldPawnSituation[] array = (WorldPawnSituation[])Enum.GetValues(typeof(WorldPawnSituation)); for (int i = 0; i < array.Length; i++) { WorldPawnSituation worldPawnSituation = array[i]; - if (worldPawnSituation != WorldPawnSituation.None) + if (worldPawnSituation != 0) { stringBuilder.AppendLine(); stringBuilder.AppendLine("== " + worldPawnSituation + " =="); - foreach (Pawn current in from x in this.GetPawnsBySituation(worldPawnSituation) - orderby (x.Faction != null) ? x.Faction.loadID : -1 + foreach (Pawn item in from x in this.GetPawnsBySituation(worldPawnSituation) + orderby (x.Faction != null) ? x.Faction.loadID : (-1) select x) { - string text = (current.Name == null) ? current.LabelCap : current.Name.ToStringFull; - stringBuilder.AppendLine(string.Concat(new object[] - { - text, - ", ", - current.KindLabel, - ", ", - current.Faction - })); + string text = (item.Name == null) ? item.LabelCap : item.Name.ToStringFull; + stringBuilder.AppendLine(text + ", " + item.KindLabel + ", " + item.Faction); } } } @@ -353,19 +371,16 @@ private bool ShouldKeep(Pawn pawn) return true; } } - foreach (Pawn current in PawnsFinder.AllMapsAndWorld_Alive) + foreach (Pawn item in PawnsFinder.AllMapsAndWorld_Alive) { - if (current.needs.mood != null && current.needs.mood.thoughts.memories.AnyMemoryConcerns(pawn)) + if (item.needs.mood != null && item.needs.mood.thoughts.memories.AnyMemoryConcerns(pawn)) { return true; } } - if (!pawn.RaceProps.Animal && pawn.RaceProps.IsFlesh) + if (!pawn.RaceProps.Animal && pawn.RaceProps.IsFlesh && pawn.relations.RelatedPawns.Any((Func)((Pawn x) => x.relations.everSeenByPlayer))) { - if (pawn.relations.RelatedPawns.Any((Pawn x) => x.relations.everSeenByPlayer)) - { - return true; - } + return true; } return false; } @@ -382,8 +397,8 @@ private void AddPawn(Pawn p) } if ((p.Faction == null || p.Faction.IsPlayer) && p.RaceProps.Humanlike && !p.Dead && this.GetSituation(p) == WorldPawnSituation.Free) { - bool tryMedievalOrBetter = p.Faction != null && p.Faction.def.techLevel >= TechLevel.Medieval; - Faction newFaction; + bool tryMedievalOrBetter = p.Faction != null && (int)p.Faction.def.techLevel >= 3; + Faction newFaction = default(Faction); if (Find.FactionManager.TryGetRandomNonColonyHumanlikeFaction(out newFaction, tryMedievalOrBetter, false)) { p.SetFaction(newFaction, null); diff --git a/Assembly-CSharp/RimWorld.Planet/WorldPawnsUtility.cs b/Assembly-CSharp/RimWorld.Planet/WorldPawnsUtility.cs index b63564034..e100feee8 100644 --- a/Assembly-CSharp/RimWorld.Planet/WorldPawnsUtility.cs +++ b/Assembly-CSharp/RimWorld.Planet/WorldPawnsUtility.cs @@ -1,4 +1,3 @@ -using System; using Verse; namespace RimWorld.Planet diff --git a/Assembly-CSharp/RimWorld.Planet/WorldReachability.cs b/Assembly-CSharp/RimWorld.Planet/WorldReachability.cs index ef8193d3c..67b2989da 100644 --- a/Assembly-CSharp/RimWorld.Planet/WorldReachability.cs +++ b/Assembly-CSharp/RimWorld.Planet/WorldReachability.cs @@ -32,20 +32,24 @@ public bool CanReach(Caravan c, int tile) public bool CanReach(int startTile, int destTile) { - if (startTile < 0 || startTile >= this.fields.Length || destTile < 0 || destTile >= this.fields.Length) + if (startTile >= 0 && startTile < this.fields.Length && destTile >= 0 && destTile < this.fields.Length) { + if (this.fields[startTile] != this.impassableFieldID && this.fields[destTile] != this.impassableFieldID) + { + if (!this.IsValidField(this.fields[startTile]) && !this.IsValidField(this.fields[destTile])) + { + this.FloodFillAt(startTile); + if (this.fields[startTile] == this.impassableFieldID) + { + return false; + } + return this.fields[startTile] == this.fields[destTile]; + } + return this.fields[startTile] == this.fields[destTile]; + } return false; } - if (this.fields[startTile] == this.impassableFieldID || this.fields[destTile] == this.impassableFieldID) - { - return false; - } - if (this.IsValidField(this.fields[startTile]) || this.IsValidField(this.fields[destTile])) - { - return this.fields[startTile] == this.fields[destTile]; - } - this.FloodFillAt(startTile); - return this.fields[startTile] != this.impassableFieldID && this.fields[startTile] == this.fields[destTile]; + return false; } private void InvalidateAllFields() @@ -70,13 +74,15 @@ private void FloodFillAt(int tile) if (world.Impassable(tile)) { this.fields[tile] = this.impassableFieldID; - return; } - Find.WorldFloodFiller.FloodFill(tile, (int x) => !world.Impassable(x), delegate(int x) + else { - this.fields[x] = this.nextFieldID; - }, 2147483647); - this.nextFieldID++; + Find.WorldFloodFiller.FloodFill(tile, (Predicate)((int x) => !world.Impassable(x)), (Action)delegate(int x) + { + this.fields[x] = this.nextFieldID; + }, 2147483647); + this.nextFieldID++; + } } } } diff --git a/Assembly-CSharp/RimWorld.Planet/WorldReachabilityUtility.cs b/Assembly-CSharp/RimWorld.Planet/WorldReachabilityUtility.cs index d8bfc5630..810145790 100644 --- a/Assembly-CSharp/RimWorld.Planet/WorldReachabilityUtility.cs +++ b/Assembly-CSharp/RimWorld.Planet/WorldReachabilityUtility.cs @@ -1,4 +1,3 @@ -using System; using Verse; namespace RimWorld.Planet diff --git a/Assembly-CSharp/RimWorld.Planet/WorldRenderMode.cs b/Assembly-CSharp/RimWorld.Planet/WorldRenderMode.cs index b4e80cc72..bb1f11458 100644 --- a/Assembly-CSharp/RimWorld.Planet/WorldRenderMode.cs +++ b/Assembly-CSharp/RimWorld.Planet/WorldRenderMode.cs @@ -1,10 +1,8 @@ -using System; - namespace RimWorld.Planet { public enum WorldRenderMode { - None, - Planet + None = 0, + Planet = 1 } } diff --git a/Assembly-CSharp/RimWorld.Planet/WorldRenderer.cs b/Assembly-CSharp/RimWorld.Planet/WorldRenderer.cs index 22d654f83..781dc8b54 100644 --- a/Assembly-CSharp/RimWorld.Planet/WorldRenderer.cs +++ b/Assembly-CSharp/RimWorld.Planet/WorldRenderer.cs @@ -1,7 +1,6 @@ using System; using System.Collections; using System.Collections.Generic; -using System.Diagnostics; using UnityEngine; using Verse; @@ -22,12 +21,9 @@ private bool ShouldRegenerateDirtyLayersInLongEvent { for (int i = 0; i < this.layers.Count; i++) { - if (this.layers[i].Dirty) + if (this.layers[i].Dirty && this.layers[i] is WorldLayer_Terrain) { - if (this.layers[i] is WorldLayer_Terrain) - { - return true; - } + return true; } } return false; @@ -36,9 +32,9 @@ private bool ShouldRegenerateDirtyLayersInLongEvent public WorldRenderer() { - foreach (Type current in typeof(WorldLayer).AllLeafSubclasses()) + foreach (Type item in typeof(WorldLayer).AllLeafSubclasses()) { - this.layers.Add((WorldLayer)Activator.CreateInstance(current)); + this.layers.Add((WorldLayer)Activator.CreateInstance(item)); } } @@ -69,14 +65,20 @@ public void RegenerateAllLayersNow() } } - [DebuggerHidden] private IEnumerable RegenerateDirtyLayersNow_Async() { - WorldRenderer.c__IteratorFB c__IteratorFB = new WorldRenderer.c__IteratorFB(); - c__IteratorFB.<>f__this = this; - WorldRenderer.c__IteratorFB expr_0E = c__IteratorFB; - expr_0E.$PC = -2; - return expr_0E; + for (int i = 0; i < this.layers.Count; i++) + { + if (this.layers[i].Dirty) + { + foreach (object item in this.layers[i].Regenerate()) + { + yield return item; + } + yield return (object)null; + } + } + this.asynchronousRegenerationActive = false; } public void Notify_StaticWorldObjectPosChanged() @@ -101,33 +103,34 @@ public void DrawWorldLayers() if (this.asynchronousRegenerationActive) { Log.Error("Called DrawWorldLayers() but already regenerating. This shouldn't ever happen because LongEventHandler should have stopped us."); - return; } - if (this.ShouldRegenerateDirtyLayersInLongEvent) + else if (this.ShouldRegenerateDirtyLayersInLongEvent) { this.asynchronousRegenerationActive = true; LongEventHandler.QueueLongEvent(this.RegenerateDirtyLayersNow_Async(), "GeneratingPlanet", null); - return; } - WorldRendererUtility.UpdateWorldShadersParams(); - for (int i = 0; i < this.layers.Count; i++) + else { - this.layers[i].Render(); + WorldRendererUtility.UpdateWorldShadersParams(); + for (int i = 0; i < this.layers.Count; i++) + { + this.layers[i].Render(); + } } } public int GetTileIDFromRayHit(RaycastHit hit) { - int i = 0; + int num = 0; int count = this.layers.Count; - while (i < count) + while (num < count) { - WorldLayer_Terrain worldLayer_Terrain = this.layers[i] as WorldLayer_Terrain; + WorldLayer_Terrain worldLayer_Terrain = this.layers[num] as WorldLayer_Terrain; if (worldLayer_Terrain != null) { return worldLayer_Terrain.GetTileIDFromRayHit(hit); } - i++; + num++; } return -1; } diff --git a/Assembly-CSharp/RimWorld.Planet/WorldRendererUtility.cs b/Assembly-CSharp/RimWorld.Planet/WorldRendererUtility.cs index cc102b7a9..b7330c0c7 100644 --- a/Assembly-CSharp/RimWorld.Planet/WorldRendererUtility.cs +++ b/Assembly-CSharp/RimWorld.Planet/WorldRendererUtility.cs @@ -1,4 +1,3 @@ -using System; using UnityEngine; using Verse; @@ -33,8 +32,7 @@ public static bool WorldRenderedNow public static void UpdateWorldShadersParams() { Vector3 v = -GenCelestial.CurSunPositionInWorldSpace(); - bool usePlanetDayNightSystem = Find.PlaySettings.usePlanetDayNightSystem; - float value = (!usePlanetDayNightSystem) ? 0f : 1f; + float value = (float)((!Find.PlaySettings.usePlanetDayNightSystem) ? 0.0 : 1.0); Shader.SetGlobalVector(ShaderPropertyIDs.PlanetSunLightDirection, v); Shader.SetGlobalFloat(ShaderPropertyIDs.PlanetSunLightEnabled, value); WorldMaterials.PlanetGlow.SetFloat(ShaderPropertyIDs.PlanetRadius, 100f); @@ -48,11 +46,11 @@ public static void PrintQuadTangentialToPlanet(Vector3 pos, float size, float al public static void PrintQuadTangentialToPlanet(Vector3 pos, Vector3 posForTangents, float size, float altOffset, LayerSubMesh subMesh, bool counterClockwise = false, bool randomizeRotation = false, bool printUVs = true) { - Vector3 a; - Vector3 a2; + Vector3 a = default(Vector3); + Vector3 a2 = default(Vector3); WorldRendererUtility.GetTangentsToPlanet(posForTangents, out a, out a2, randomizeRotation); Vector3 normalized = posForTangents.normalized; - float d = size * 0.5f; + float d = (float)(size * 0.5); Vector3 item = pos - a * d - a2 * d + normalized * altOffset; Vector3 item2 = pos - a * d + a2 * d + normalized * altOffset; Vector3 item3 = pos + a * d + a2 * d + normalized * altOffset; @@ -91,47 +89,33 @@ public static void PrintQuadTangentialToPlanet(Vector3 pos, Vector3 posForTangen public static void DrawQuadTangentialToPlanet(Vector3 pos, float size, float altOffset, Material material, bool counterClockwise = false, bool useSkyboxLayer = false, MaterialPropertyBlock propertyBlock = null) { - if (material == null) + if ((Object)material == (Object)null) { Log.Warning("Tried to draw quad with null material."); - return; - } - Vector3 normalized = pos.normalized; - Vector3 vector; - if (counterClockwise) - { - vector = -normalized; } else { - vector = normalized; - } - Quaternion q = Quaternion.LookRotation(Vector3.Cross(vector, Vector3.up), vector); - Vector3 s = new Vector3(size, 1f, size); - Matrix4x4 matrix = default(Matrix4x4); - matrix.SetTRS(pos + normalized * altOffset, q, s); - int layer = (!useSkyboxLayer) ? WorldCameraManager.WorldLayer : WorldCameraManager.WorldSkyboxLayer; - if (propertyBlock != null) - { - Graphics.DrawMesh(MeshPool.plane10, matrix, material, layer, null, 0, propertyBlock); - } - else - { - Graphics.DrawMesh(MeshPool.plane10, matrix, material, layer); + Vector3 normalized = pos.normalized; + Vector3 vector = (!counterClockwise) ? normalized : (-normalized); + Quaternion q = Quaternion.LookRotation(Vector3.Cross(vector, Vector3.up), vector); + Vector3 s = new Vector3(size, 1f, size); + Matrix4x4 matrix = default(Matrix4x4); + matrix.SetTRS(pos + normalized * altOffset, q, s); + int layer = (!useSkyboxLayer) ? WorldCameraManager.WorldLayer : WorldCameraManager.WorldSkyboxLayer; + if (propertyBlock != null) + { + Graphics.DrawMesh(MeshPool.plane10, matrix, material, layer, null, 0, propertyBlock); + } + else + { + Graphics.DrawMesh(MeshPool.plane10, matrix, material, layer); + } } } public static void GetTangentsToPlanet(Vector3 pos, out Vector3 first, out Vector3 second, bool randomizeRotation = false) { - Vector3 upwards; - if (randomizeRotation) - { - upwards = Rand.PointOnSphere; - } - else - { - upwards = Vector3.up; - } + Vector3 upwards = (!randomizeRotation) ? Vector3.up : Rand.PointOnSphere; Quaternion rotation = Quaternion.LookRotation(pos.normalized, upwards); first = rotation * Vector3.up; second = rotation * Vector3.right; @@ -139,8 +123,8 @@ public static void GetTangentsToPlanet(Vector3 pos, out Vector3 first, out Vecto public static Vector3 ProjectOnQuadTangentialToPlanet(Vector3 center, Vector2 point) { - Vector3 a; - Vector3 a2; + Vector3 a = default(Vector3); + Vector3 a2 = default(Vector3); WorldRendererUtility.GetTangentsToPlanet(center, out a, out a2, false); return point.x * a + point.y * a2; } @@ -154,8 +138,8 @@ public static void GetTangentialVectorFacing(Vector3 root, Vector3 pointToFace, public static void PrintTextureAtlasUVs(int indexX, int indexY, int numX, int numY, LayerSubMesh subMesh) { - float num = 1f / (float)numX; - float num2 = 1f / (float)numY; + float num = (float)(1.0 / (float)numX); + float num2 = (float)(1.0 / (float)numY); float num3 = (float)indexX * num; float num4 = (float)indexY * num2; subMesh.uvs.Add(new Vector2(num3, num4)); diff --git a/Assembly-CSharp/RimWorld.Planet/WorldRoutePlanner.cs b/Assembly-CSharp/RimWorld.Planet/WorldRoutePlanner.cs index 00b367afc..170f6d70a 100644 --- a/Assembly-CSharp/RimWorld.Planet/WorldRoutePlanner.cs +++ b/Assembly-CSharp/RimWorld.Planet/WorldRoutePlanner.cs @@ -50,7 +50,19 @@ private bool ShouldStop { get { - return !this.active || !WorldRendererUtility.WorldRenderedNow || (Current.ProgramState == ProgramState.Playing && Find.TickManager.CurTimeSpeed != TimeSpeed.Paused); + if (!this.active) + { + return true; + } + if (!WorldRendererUtility.WorldRenderedNow) + { + return true; + } + if (((Current.ProgramState == ProgramState.Playing) ? Find.TickManager.CurTimeSpeed : TimeSpeed.Paused) != 0) + { + return true; + } + return false; } } @@ -59,7 +71,7 @@ private int CaravanTicksPerMove get { List caravanPawns = this.CaravanPawns; - if (!caravanPawns.NullOrEmpty()) + if (!caravanPawns.NullOrEmpty()) { return CaravanTicksPerMoveUtility.GetTicksPerMove(caravanPawns); } @@ -88,7 +100,7 @@ private Caravan CaravanAtTheFirstWaypoint { get { - if (!this.waypoints.Any()) + if (!this.waypoints.Any()) { return null; } @@ -146,141 +158,140 @@ public void WorldRoutePlannerUpdate() { this.Stop(); } - if (!this.active) - { - return; - } - for (int i = 0; i < this.paths.Count; i++) + if (this.active) { - this.paths[i].DrawPath(null); + for (int i = 0; i < this.paths.Count; i++) + { + this.paths[i].DrawPath(null); + } } } public void WorldRoutePlannerOnGUI() { - WorldRoutePlanner.c__AnonStorey47D c__AnonStorey47D = new WorldRoutePlanner.c__AnonStorey47D(); - c__AnonStorey47D.<>f__this = this; - if (!this.active) - { - return; - } - if (Event.current.type == EventType.KeyDown && Event.current.keyCode == KeyCode.Escape) + if (this.active) { - if (this.currentFormCaravanDialog != null) + if (Event.current.type == EventType.KeyDown && Event.current.keyCode == KeyCode.Escape) { - Find.WindowStack.Add(this.currentFormCaravanDialog); + if (this.currentFormCaravanDialog != null) + { + Find.WindowStack.Add(this.currentFormCaravanDialog); + } + else + { + SoundDefOf.TickLow.PlayOneShotOnCamera(null); + } + this.Stop(); + Event.current.Use(); } else { - SoundDefOf.TickLow.PlayOneShotOnCamera(null); - } - this.Stop(); - Event.current.Use(); - return; - } - GenUI.DrawMouseAttachment(WorldRoutePlanner.MouseAttachment); - if (Event.current.type == EventType.MouseDown && Event.current.button == 1) - { - Caravan caravan = Find.WorldSelector.SelectableObjectsUnderMouse().FirstOrDefault() as Caravan; - int tile = (caravan == null) ? GenWorld.MouseTile(true) : caravan.Tile; - if (tile >= 0) - { - RoutePlannerWaypoint waypoint = this.MostRecentWaypointAt(tile); - if (waypoint != null) + GenUI.DrawMouseAttachment(WorldRoutePlanner.MouseAttachment); + if (Event.current.type == EventType.MouseDown && Event.current.button == 1) { - if (waypoint == this.waypoints[this.waypoints.Count - 1]) - { - this.TryRemoveWaypoint(waypoint, true); - } - else + Caravan caravan = Find.WorldSelector.SelectableObjectsUnderMouse().FirstOrDefault() as Caravan; + int tile = (caravan == null) ? GenWorld.MouseTile(true) : caravan.Tile; + if (tile >= 0) { - List list = new List(); - list.Add(new FloatMenuOption("AddWaypoint".Translate(), delegate + RoutePlannerWaypoint waypoint = this.MostRecentWaypointAt(tile); + if (waypoint != null) { - this.TryAddWaypoint(tile, true); - }, MenuOptionPriority.Default, null, null, 0f, null, null)); - list.Add(new FloatMenuOption("RemoveWaypoint".Translate(), delegate + if (waypoint == this.waypoints[this.waypoints.Count - 1]) + { + this.TryRemoveWaypoint(waypoint, true); + } + else + { + List list = new List(); + list.Add(new FloatMenuOption("AddWaypoint".Translate(), (Action)delegate + { + this.TryAddWaypoint(tile, true); + }, MenuOptionPriority.Default, null, null, 0f, null, null)); + list.Add(new FloatMenuOption("RemoveWaypoint".Translate(), (Action)delegate + { + this.TryRemoveWaypoint(waypoint, true); + }, MenuOptionPriority.Default, null, null, 0f, null, null)); + Find.WindowStack.Add(new FloatMenu(list)); + } + } + else { - this.TryRemoveWaypoint(waypoint, true); - }, MenuOptionPriority.Default, null, null, 0f, null, null)); - Find.WindowStack.Add(new FloatMenu(list)); + this.TryAddWaypoint(tile, true); + } + Event.current.Use(); } } - else + float num = (float)UI.screenWidth; + Vector2 bottomWindowSize = WorldRoutePlanner.BottomWindowSize; + double x = (num - bottomWindowSize.x) / 2.0; + float num2 = (float)UI.screenHeight; + Vector2 bottomWindowSize2 = WorldRoutePlanner.BottomWindowSize; + double y = num2 - bottomWindowSize2.y - 45.0; + Vector2 bottomWindowSize3 = WorldRoutePlanner.BottomWindowSize; + float x2 = bottomWindowSize3.x; + Vector2 bottomWindowSize4 = WorldRoutePlanner.BottomWindowSize; + Rect rect = new Rect((float)x, (float)y, x2, bottomWindowSize4.y); + if (Current.ProgramState == ProgramState.Entry) { - this.TryAddWaypoint(tile, true); + rect.y -= 22f; } - Event.current.Use(); - } - } - c__AnonStorey47D.rect = new Rect(((float)UI.screenWidth - WorldRoutePlanner.BottomWindowSize.x) / 2f, (float)UI.screenHeight - WorldRoutePlanner.BottomWindowSize.y - 45f, WorldRoutePlanner.BottomWindowSize.x, WorldRoutePlanner.BottomWindowSize.y); - if (Current.ProgramState == ProgramState.Entry) - { - WorldRoutePlanner.c__AnonStorey47D expr_24E_cp_0 = c__AnonStorey47D; - expr_24E_cp_0.rect.y = expr_24E_cp_0.rect.y - 22f; - } - Find.WindowStack.ImmediateWindow(1373514241, c__AnonStorey47D.rect, WindowLayer.Dialog, delegate - { - if (!c__AnonStorey47D.<>f__this.active) - { - return; - } - GUI.color = Color.white; - Text.Anchor = TextAnchor.UpperCenter; - Text.Font = GameFont.Small; - float num = 6f; - if (c__AnonStorey47D.<>f__this.waypoints.Count >= 2) - { - Widgets.Label(new Rect(0f, num, c__AnonStorey47D.rect.width, 25f), "RoutePlannerEstTimeToFinalDest".Translate(new object[] - { - c__AnonStorey47D.<>f__this.GetTicksToWaypoint(c__AnonStorey47D.<>f__this.waypoints.Count - 1).ToStringTicksToDays("0.#") - })); - } - else if (c__AnonStorey47D.<>f__this.cantRemoveFirstWaypoint) - { - Widgets.Label(new Rect(0f, num, c__AnonStorey47D.rect.width, 25f), "RoutePlannerAddOneOrMoreWaypoints".Translate()); - } - else - { - Widgets.Label(new Rect(0f, num, c__AnonStorey47D.rect.width, 25f), "RoutePlannerAddTwoOrMoreWaypoints".Translate()); - } - num += 20f; - if (c__AnonStorey47D.<>f__this.CaravanPawns.NullOrEmpty()) - { - GUI.color = new Color(0.8f, 0.6f, 0.6f); - Widgets.Label(new Rect(0f, num, c__AnonStorey47D.rect.width, 25f), "RoutePlannerUsingAverageTicksPerMoveWarning".Translate()); - } - else if (c__AnonStorey47D.<>f__this.currentFormCaravanDialog == null && c__AnonStorey47D.<>f__this.CaravanAtTheFirstWaypoint != null) - { - GUI.color = Color.gray; - Widgets.Label(new Rect(0f, num, c__AnonStorey47D.rect.width, 25f), "RoutePlannerUsingTicksPerMoveOfCaravan".Translate(new object[] + Find.WindowStack.ImmediateWindow(1373514241, rect, WindowLayer.Dialog, (Action)delegate { - c__AnonStorey47D.<>f__this.CaravanAtTheFirstWaypoint.LabelCap - })); - } - num += 20f; - GUI.color = Color.gray; - Widgets.Label(new Rect(0f, num, c__AnonStorey47D.rect.width, 25f), "RoutePlannerPressRMBToAddAndRemoveWaypoints".Translate()); - num += 20f; - if (c__AnonStorey47D.<>f__this.currentFormCaravanDialog != null) - { - Widgets.Label(new Rect(0f, num, c__AnonStorey47D.rect.width, 25f), "RoutePlannerPressEscapeToReturnToCaravanFormationDialog".Translate()); - } - else - { - Widgets.Label(new Rect(0f, num, c__AnonStorey47D.rect.width, 25f), "RoutePlannerPressEscapeToExit".Translate()); + if (this.active) + { + GUI.color = Color.white; + Text.Anchor = TextAnchor.UpperCenter; + Text.Font = GameFont.Small; + float num3 = 6f; + if (this.waypoints.Count >= 2) + { + Widgets.Label(new Rect(0f, num3, rect.width, 25f), "RoutePlannerEstTimeToFinalDest".Translate(this.GetTicksToWaypoint(this.waypoints.Count - 1).ToStringTicksToDays("0.#"))); + } + else if (this.cantRemoveFirstWaypoint) + { + Widgets.Label(new Rect(0f, num3, rect.width, 25f), "RoutePlannerAddOneOrMoreWaypoints".Translate()); + } + else + { + Widgets.Label(new Rect(0f, num3, rect.width, 25f), "RoutePlannerAddTwoOrMoreWaypoints".Translate()); + } + num3 = (float)(num3 + 20.0); + if (this.CaravanPawns.NullOrEmpty()) + { + GUI.color = new Color(0.8f, 0.6f, 0.6f); + Widgets.Label(new Rect(0f, num3, rect.width, 25f), "RoutePlannerUsingAverageTicksPerMoveWarning".Translate()); + } + else if (this.currentFormCaravanDialog == null && this.CaravanAtTheFirstWaypoint != null) + { + GUI.color = Color.gray; + Widgets.Label(new Rect(0f, num3, rect.width, 25f), "RoutePlannerUsingTicksPerMoveOfCaravan".Translate(this.CaravanAtTheFirstWaypoint.LabelCap)); + } + num3 = (float)(num3 + 20.0); + GUI.color = Color.gray; + Widgets.Label(new Rect(0f, num3, rect.width, 25f), "RoutePlannerPressRMBToAddAndRemoveWaypoints".Translate()); + num3 = (float)(num3 + 20.0); + if (this.currentFormCaravanDialog != null) + { + Widgets.Label(new Rect(0f, num3, rect.width, 25f), "RoutePlannerPressEscapeToReturnToCaravanFormationDialog".Translate()); + } + else + { + Widgets.Label(new Rect(0f, num3, rect.width, 25f), "RoutePlannerPressEscapeToExit".Translate()); + } + num3 = (float)(num3 + 20.0); + GUI.color = Color.white; + Text.Anchor = TextAnchor.UpperLeft; + } + }, true, false, 1f); } - num += 20f; - GUI.color = Color.white; - Text.Anchor = TextAnchor.UpperLeft; - }, true, false, 1f); + } } public void DoRoutePlannerButton(ref float curBaseY) { float num = (float)WorldRoutePlanner.ButtonTex.width; float num2 = (float)WorldRoutePlanner.ButtonTex.height; - Rect rect = new Rect((float)UI.screenWidth - 10f - num, curBaseY - 10f - num2, num, num2); + Rect rect = new Rect((float)((float)UI.screenWidth - 10.0 - num), (float)(curBaseY - 10.0 - num2), num, num2); if (Widgets.ButtonImage(rect, WorldRoutePlanner.ButtonTex, Color.white, new Color(0.8f, 0.8f, 0.8f))) { if (this.active) @@ -295,7 +306,7 @@ public void DoRoutePlannerButton(ref float curBaseY) } } TooltipHandler.TipRegion(rect, "RoutePlannerButtonTip".Translate()); - curBaseY -= num2 + 20f; + curBaseY -= (float)(num2 + 20.0); } public int GetTicksToWaypoint(int index) @@ -308,53 +319,52 @@ private void TryAddWaypoint(int tile, bool playSound = true) if (Find.World.Impassable(tile)) { Messages.Message("MessageCantAddWaypointBecauseImpassable".Translate(), MessageSound.RejectInput); - return; } - if (this.waypoints.Any() && !Find.WorldReachability.CanReach(this.waypoints[this.waypoints.Count - 1].Tile, tile)) + else if (this.waypoints.Any() && !Find.WorldReachability.CanReach(this.waypoints[this.waypoints.Count - 1].Tile, tile)) { Messages.Message("MessageCantAddWaypointBecauseUnreachable".Translate(), MessageSound.RejectInput); - return; } - if (this.waypoints.Count >= 25) + else if (this.waypoints.Count >= 25) { - Messages.Message("MessageCantAddWaypointBecauseLimit".Translate(new object[] - { - 25 - }), MessageSound.RejectInput); - return; + Messages.Message("MessageCantAddWaypointBecauseLimit".Translate(25), MessageSound.RejectInput); } - RoutePlannerWaypoint routePlannerWaypoint = (RoutePlannerWaypoint)WorldObjectMaker.MakeWorldObject(WorldObjectDefOf.RoutePlannerWaypoint); - routePlannerWaypoint.Tile = tile; - Find.WorldObjects.Add(routePlannerWaypoint); - this.waypoints.Add(routePlannerWaypoint); - this.RecreatePaths(); - if (playSound) + else { - SoundDefOf.TickHigh.PlayOneShotOnCamera(null); + RoutePlannerWaypoint routePlannerWaypoint = (RoutePlannerWaypoint)WorldObjectMaker.MakeWorldObject(WorldObjectDefOf.RoutePlannerWaypoint); + routePlannerWaypoint.Tile = tile; + Find.WorldObjects.Add(routePlannerWaypoint); + this.waypoints.Add(routePlannerWaypoint); + this.RecreatePaths(); + if (playSound) + { + SoundDefOf.TickHigh.PlayOneShotOnCamera(null); + } } } public void TryRemoveWaypoint(RoutePlannerWaypoint point, bool playSound = true) { - if (this.cantRemoveFirstWaypoint && this.waypoints.Any() && point == this.waypoints[0]) + if (this.cantRemoveFirstWaypoint && this.waypoints.Any() && point == this.waypoints[0]) { Messages.Message("MessageCantRemoveWaypointBecauseFirst".Translate(), MessageSound.RejectInput); - return; } - Find.WorldObjects.Remove(point); - this.waypoints.Remove(point); - for (int i = this.waypoints.Count - 1; i >= 1; i--) + else { - if (this.waypoints[i].Tile == this.waypoints[i - 1].Tile) + Find.WorldObjects.Remove(point); + this.waypoints.Remove(point); + for (int num = this.waypoints.Count - 1; num >= 1; num--) { - Find.WorldObjects.Remove(this.waypoints[i]); - this.waypoints.RemoveAt(i); + if (this.waypoints[num].Tile == this.waypoints[num - 1].Tile) + { + Find.WorldObjects.Remove(this.waypoints[num]); + this.waypoints.RemoveAt(num); + } + } + this.RecreatePaths(); + if (playSound) + { + SoundDefOf.TickLow.PlayOneShotOnCamera(null); } - } - this.RecreatePaths(); - if (playSound) - { - SoundDefOf.TickLow.PlayOneShotOnCamera(null); } } @@ -394,11 +404,11 @@ private void RecreatePaths() private RoutePlannerWaypoint MostRecentWaypointAt(int tile) { - for (int i = this.waypoints.Count - 1; i >= 0; i--) + for (int num = this.waypoints.Count - 1; num >= 0; num--) { - if (this.waypoints[i].Tile == tile) + if (this.waypoints[num].Tile == tile) { - return this.waypoints[i]; + return this.waypoints[num]; } } return null; diff --git a/Assembly-CSharp/RimWorld.Planet/WorldSelectionDrawer.cs b/Assembly-CSharp/RimWorld.Planet/WorldSelectionDrawer.cs index d98a2a682..3767bbacf 100644 --- a/Assembly-CSharp/RimWorld.Planet/WorldSelectionDrawer.cs +++ b/Assembly-CSharp/RimWorld.Planet/WorldSelectionDrawer.cs @@ -1,4 +1,3 @@ -using System; using System.Collections.Generic; using UnityEngine; using Verse; @@ -61,9 +60,9 @@ public static void DrawSelectionOverlays() private static void DrawSelectionBracketOnGUIFor(WorldObject obj) { Vector2 vector = obj.ScreenPos(); - Rect rect = new Rect(vector.x - 17.5f, vector.y - 17.5f, 35f, 35f); - Vector2 textureSize = new Vector2((float)SelectionDrawerUtility.SelectedTexGUI.width * 0.4f, (float)SelectionDrawerUtility.SelectedTexGUI.height * 0.4f); - SelectionDrawerUtility.CalculateSelectionBracketPositionsUI(WorldSelectionDrawer.bracketLocs, obj, rect, WorldSelectionDrawer.selectTimes, textureSize, 25f); + Rect rect = new Rect((float)(vector.x - 17.5), (float)(vector.y - 17.5), 35f, 35f); + Vector2 textureSize = new Vector2((float)((float)SelectionDrawerUtility.SelectedTexGUI.width * 0.40000000596046448), (float)((float)SelectionDrawerUtility.SelectedTexGUI.height * 0.40000000596046448)); + SelectionDrawerUtility.CalculateSelectionBracketPositionsUI(WorldSelectionDrawer.bracketLocs, obj, rect, WorldSelectionDrawer.selectTimes, textureSize, 25f); if (obj.HiddenBehindTerrainNow()) { GUI.color = WorldSelectionDrawer.HiddenSelectionBracketColor; diff --git a/Assembly-CSharp/RimWorld.Planet/WorldSelector.cs b/Assembly-CSharp/RimWorld.Planet/WorldSelector.cs index e59d75c41..fdeb9aa29 100644 --- a/Assembly-CSharp/RimWorld.Planet/WorldSelector.cs +++ b/Assembly-CSharp/RimWorld.Planet/WorldSelector.cs @@ -1,6 +1,5 @@ using System; using System.Collections.Generic; -using System.Diagnostics; using System.Linq; using UnityEngine; using Verse; @@ -170,21 +169,19 @@ public void Select(WorldObject obj, bool playSound = true) if (obj == null) { Log.Error("Cannot select null."); - return; } - this.selectedTile = -1; - if (this.selected.Count >= 80) - { - return; - } - if (!this.IsSelected(obj)) + else { - if (playSound) + this.selectedTile = -1; + if (this.selected.Count < 80 && !this.IsSelected(obj)) { - this.PlaySelectionSoundFor(obj); + if (playSound) + { + this.PlaySelectionSoundFor(obj); + } + this.selected.Add(obj); + WorldSelectionDrawer.Notify_Selected(obj); } - this.selected.Add(obj); - WorldSelectionDrawer.Notify_Selected(obj); } } @@ -232,13 +229,13 @@ private void SelectInsideDragBox() } if (!flag) { - List list3 = WorldObjectSelectionUtility.MultiSelectableWorldObjectsInScreenRectDistinct(this.dragBox.ScreenRect).ToList(); - if (list3.Any((WorldObject x) => x is Caravan)) + List list3 = WorldObjectSelectionUtility.MultiSelectableWorldObjectsInScreenRectDistinct(this.dragBox.ScreenRect).ToList(); + if (list3.Any((Predicate)((WorldObject x) => x is Caravan))) { - list3.RemoveAll((WorldObject x) => !(x is Caravan)); - if (list3.Any((WorldObject x) => x.Faction == Faction.OfPlayer)) + list3.RemoveAll((Predicate)((WorldObject x) => !(x is Caravan))); + if (list3.Any((Predicate)((WorldObject x) => x.Faction == Faction.OfPlayer))) { - list3.RemoveAll((WorldObject x) => x.Faction != Faction.OfPlayer); + list3.RemoveAll((Predicate)((WorldObject x) => x.Faction != Faction.OfPlayer)); } } for (int k = 0; k < list3.Count; k++) @@ -249,14 +246,14 @@ private void SelectInsideDragBox() } if (!flag) { - bool canSelectTile = this.dragBox.Diagonal < 30f; + bool canSelectTile = this.dragBox.Diagonal < 30.0; this.SelectUnderMouse(canSelectTile); } } public IEnumerable SelectableObjectsUnderMouse() { - bool flag; + bool flag = default(bool); return this.SelectableObjectsUnderMouse(out flag, out flag); } @@ -270,7 +267,7 @@ public IEnumerable SelectableObjectsUnderMouse(out bool clickedDire { clickedDirectlyOnCaravan = true; usedColonistBar = true; - return Gen.YieldSingle(caravan); + return Gen.YieldSingle((WorldObject)caravan); } } List list = GenWorldUI.WorldObjectsUnderMouse(UI.MousePositionOnUI); @@ -278,9 +275,9 @@ public IEnumerable SelectableObjectsUnderMouse(out bool clickedDire if (list.Count > 0 && list[0] is Caravan && list[0].DistanceToMouse(UI.MousePositionOnUI) < GenWorldUI.CaravanDirectClickRadius) { clickedDirectlyOnCaravan = true; - for (int i = list.Count - 1; i >= 0; i--) + for (int num = list.Count - 1; num >= 0; num--) { - WorldObject worldObject = list[i]; + WorldObject worldObject = list[num]; if (worldObject is Caravan && worldObject.DistanceToMouse(UI.MousePositionOnUI) > GenWorldUI.CaravanDirectClickRadius) { list.Remove(worldObject); @@ -291,15 +288,15 @@ public IEnumerable SelectableObjectsUnderMouse(out bool clickedDire return list; } - [DebuggerHidden] public static IEnumerable SelectableObjectsAt(int tileID) { - WorldSelector.c__Iterator1A6 c__Iterator1A = new WorldSelector.c__Iterator1A6(); - c__Iterator1A.tileID = tileID; - c__Iterator1A.<$>tileID = tileID; - WorldSelector.c__Iterator1A6 expr_15 = c__Iterator1A; - expr_15.$PC = -2; - return expr_15; + foreach (WorldObject item in Find.WorldObjects.ObjectsAt(tileID)) + { + if (item.SelectableNow) + { + yield return item; + } + } } private void SelectUnderMouse(bool canSelectTile = true) @@ -321,9 +318,9 @@ private void SelectUnderMouse(bool canSelectTile = true) return; } } - bool flag; - bool flag2; - List list = this.SelectableObjectsUnderMouse(out flag, out flag2).ToList(); + bool flag = default(bool); + bool flag2 = default(bool); + List list = this.SelectableObjectsUnderMouse(out flag, out flag2).ToList(); if (flag2 || (flag && list.Count >= 2)) { canSelectTile = false; @@ -343,23 +340,32 @@ private void SelectUnderMouse(bool canSelectTile = true) { WorldObject worldObject = (from obj in list where this.selected.Contains(obj) - select obj).FirstOrDefault(); + select obj).FirstOrDefault(); if (worldObject != null) { if (!this.ShiftIsHeld) { - int tile = (!canSelectTile) ? -1 : GenWorld.MouseTile(false); + int tile = (!canSelectTile) ? (-1) : GenWorld.MouseTile(false); this.SelectFirstOrNextFrom(list, tile); } else { - foreach (WorldObject current in list) + List.Enumerator enumerator = list.GetEnumerator(); + try { - if (this.selected.Contains(current)) + while (enumerator.MoveNext()) { - this.Deselect(current); + WorldObject current = enumerator.Current; + if (this.selected.Contains(current)) + { + this.Deselect(current); + } } } + finally + { + ((IDisposable)(object)enumerator).Dispose(); + } } } else @@ -375,28 +381,21 @@ where this.selected.Contains(obj) public void SelectFirstOrNextAt(int tileID) { - this.SelectFirstOrNextFrom(WorldSelector.SelectableObjectsAt(tileID).ToList(), tileID); + this.SelectFirstOrNextFrom(WorldSelector.SelectableObjectsAt(tileID).ToList(), tileID); } private void SelectAllMatchingObjectUnderMouseOnScreen() { - List list = this.SelectableObjectsUnderMouse().ToList(); - if (list.Count == 0) - { - return; - } - Type type = list[0].GetType(); - List allWorldObjects = Find.WorldObjects.AllWorldObjects; - for (int i = 0; i < allWorldObjects.Count; i++) + List list = this.SelectableObjectsUnderMouse().ToList(); + if (list.Count != 0) { - if (list[0].Faction == allWorldObjects[i].Faction) + Type type = list[0].GetType(); + List allWorldObjects = Find.WorldObjects.AllWorldObjects; + for (int i = 0; i < allWorldObjects.Count; i++) { - if (type == allWorldObjects[i].GetType()) + if (list[0].Faction == allWorldObjects[i].Faction && type == allWorldObjects[i].GetType() && allWorldObjects[i].VisibleToCameraNow()) { - if (allWorldObjects[i].VisibleToCameraNow()) - { - this.Select(allWorldObjects[i], true); - } + this.Select(allWorldObjects[i], true); } } } @@ -404,41 +403,41 @@ private void SelectAllMatchingObjectUnderMouseOnScreen() private void AutoOrderToTile(Caravan c, int tile) { - if (tile < 0) - { - return; - } - if (c.autoJoinable && CaravanExitMapUtility.IsTheOnlyJoinableCaravanForAnyPrisonerOrAnimal(c)) + if (tile >= 0) { - CaravanExitMapUtility.OpenTheOnlyJoinableCaravanForPrisonerOrAnimalDialog(c, delegate + if (c.autoJoinable && CaravanExitMapUtility.IsTheOnlyJoinableCaravanForAnyPrisonerOrAnimal(c)) + { + CaravanExitMapUtility.OpenTheOnlyJoinableCaravanForPrisonerOrAnimalDialog(c, (Action)delegate() + { + this.AutoOrderToTileNow(c, tile); + }); + } + else { this.AutoOrderToTileNow(c, tile); - }); - } - else - { - this.AutoOrderToTileNow(c, tile); + } } } private void AutoOrderToTileNow(Caravan c, int tile) { - if (tile < 0 || (tile == c.Tile && !c.pather.Moving)) - { - return; - } - int num = CaravanUtility.BestGotoDestNear(tile, c); - if (num >= 0) + if (tile >= 0) { - c.pather.StartPath(num, null, true); - c.gotoMote.OrderedToTile(num); - SoundDefOf.ColonistOrdered.PlayOneShotOnCamera(null); + if (tile == c.Tile && !c.pather.Moving) + return; + int num = CaravanUtility.BestGotoDestNear(tile, c); + if (num >= 0) + { + c.pather.StartPath(num, null, true); + c.gotoMote.OrderedToTile(num); + SoundDefOf.ColonistOrdered.PlayOneShotOnCamera(null); + } } } private void SelectFirstOrNextFrom(List objects, int tile) { - int num = objects.FindIndex((WorldObject x) => this.selected.Contains(x)); + int num = objects.FindIndex((Predicate)((WorldObject x) => this.selected.Contains(x))); int num2 = -1; int num3 = -1; if (num != -1) diff --git a/Assembly-CSharp/RimWorld.Planet/WorldSettings.cs b/Assembly-CSharp/RimWorld.Planet/WorldSettings.cs index 7ed33ca15..bf5e31ae7 100644 --- a/Assembly-CSharp/RimWorld.Planet/WorldSettings.cs +++ b/Assembly-CSharp/RimWorld.Planet/WorldSettings.cs @@ -1,4 +1,3 @@ -using System; using Verse; namespace RimWorld.Planet diff --git a/Assembly-CSharp/RimWorld.Planet/WorldTerrainColliderManager.cs b/Assembly-CSharp/RimWorld.Planet/WorldTerrainColliderManager.cs index d7312abde..b30bef927 100644 --- a/Assembly-CSharp/RimWorld.Planet/WorldTerrainColliderManager.cs +++ b/Assembly-CSharp/RimWorld.Planet/WorldTerrainColliderManager.cs @@ -1,4 +1,3 @@ -using System; using UnityEngine; using Verse; @@ -25,7 +24,7 @@ static WorldTerrainColliderManager() private static GameObject CreateGameObject() { GameObject gameObject = new GameObject("WorldTerrainCollider"); - UnityEngine.Object.DontDestroyOnLoad(gameObject); + Object.DontDestroyOnLoad(gameObject); gameObject.layer = WorldCameraManager.WorldLayer; return gameObject; } diff --git a/Assembly-CSharp/RimWorld/ActiveDropPod.cs b/Assembly-CSharp/RimWorld/ActiveDropPod.cs index c11fb8128..5ed4eed1c 100644 --- a/Assembly-CSharp/RimWorld/ActiveDropPod.cs +++ b/Assembly-CSharp/RimWorld/ActiveDropPod.cs @@ -35,7 +35,7 @@ public override void ExposeData() { base.ExposeData(); Scribe_Values.Look(ref this.age, "age", 0, false); - Scribe_Deep.Look(ref this.contents, "contents", new object[] + Scribe_Deep.Look(ref this.contents, "contents", new object[1] { this }); @@ -81,11 +81,11 @@ public override void Destroy(DestroyMode mode = DestroyMode.Vanish) private void PodOpen() { - for (int i = this.contents.innerContainer.Count - 1; i >= 0; i--) + for (int num = this.contents.innerContainer.Count - 1; num >= 0; num--) { - Thing thing = this.contents.innerContainer[i]; - Thing thing2; - GenPlace.TryPlaceThing(thing, base.Position, base.Map, ThingPlaceMode.Near, out thing2, delegate(Thing placedThing, int count) + Thing thing = this.contents.innerContainer[num]; + Thing thing2 = default(Thing); + GenPlace.TryPlaceThing(thing, base.Position, base.Map, ThingPlaceMode.Near, out thing2, (Action)delegate(Thing placedThing, int count) { if (Find.TickManager.TicksGame < 1200 && TutorSystem.TutorialMode && placedThing.def.category == ThingCategory.Item) { @@ -97,10 +97,7 @@ private void PodOpen() { if (pawn.RaceProps.Humanlike) { - TaleRecorder.RecordTale(TaleDefOf.LandedInPod, new object[] - { - pawn - }); + TaleRecorder.RecordTale(TaleDefOf.LandedInPod, pawn); } if (pawn.IsColonist && pawn.Spawned && !base.Map.IsPlayerHome) { @@ -111,7 +108,7 @@ private void PodOpen() this.contents.innerContainer.ClearAndDestroyContents(DestroyMode.Vanish); if (this.contents.leaveSlag) { - for (int j = 0; j < 1; j++) + for (int i = 0; i < 1; i++) { Thing thing3 = ThingMaker.MakeThing(ThingDefOf.ChunkSlagSteel, null); GenPlace.TryPlaceThing(thing3, base.Position, base.Map, ThingPlaceMode.Near, null); @@ -125,5 +122,11 @@ virtual IThingHolder get_ParentHolder() { return base.ParentHolder; } + + IThingHolder IThingHolder.get_ParentHolder() + { + //ILSpy generated this explicit interface implementation from .override directive in get_ParentHolder + return this.get_ParentHolder(); + } } } diff --git a/Assembly-CSharp/RimWorld/ActiveDropPodInfo.cs b/Assembly-CSharp/RimWorld/ActiveDropPodInfo.cs index cb25c4e96..a4b2b91f0 100644 --- a/Assembly-CSharp/RimWorld/ActiveDropPodInfo.cs +++ b/Assembly-CSharp/RimWorld/ActiveDropPodInfo.cs @@ -1,4 +1,3 @@ -using System; using System.Collections.Generic; using Verse; @@ -85,14 +84,16 @@ public void ExposeData() { Scribe_Collections.Look(ref this.tmpSavedPawns, "tmpSavedPawns", LookMode.Reference, new object[0]); } - Scribe_Deep.Look(ref this.innerContainer, "innerContainer", new object[] + Scribe_Deep.Look(ref this.innerContainer, "innerContainer", new object[1] { this }); Scribe_Values.Look(ref this.openDelay, "openDelay", 110, false); Scribe_Values.Look(ref this.leaveSlag, "leaveSlag", false, false); - if (this.savePawnsWithReferenceMode && (Scribe.mode == LoadSaveMode.PostLoadInit || Scribe.mode == LoadSaveMode.Saving)) + if (this.savePawnsWithReferenceMode) { + if (Scribe.mode != LoadSaveMode.PostLoadInit && Scribe.mode != LoadSaveMode.Saving) + return; for (int j = 0; j < this.tmpSavedPawns.Count; j++) { this.innerContainer.TryAdd(this.tmpSavedPawns[j], true); diff --git a/Assembly-CSharp/RimWorld/ActiveLessonHandler.cs b/Assembly-CSharp/RimWorld/ActiveLessonHandler.cs index 135103f2f..123768b6e 100644 --- a/Assembly-CSharp/RimWorld/ActiveLessonHandler.cs +++ b/Assembly-CSharp/RimWorld/ActiveLessonHandler.cs @@ -33,9 +33,7 @@ public void Activate(InstructionDef id) { Lesson_Instruction lesson_Instruction = this.activeLesson as Lesson_Instruction; if (lesson_Instruction != null && id == lesson_Instruction.def) - { return; - } Lesson_Instruction lesson_Instruction2 = (Lesson_Instruction)Activator.CreateInstance(id.instructionClass); lesson_Instruction2.def = id; this.activeLesson = lesson_Instruction2; @@ -65,20 +63,18 @@ public void Deactivate() public void ActiveLessonOnGUI() { - if (Time.timeSinceLevelLoad < 0.01f || !this.ActiveLessonVisible) + if (!(Time.timeSinceLevelLoad < 0.0099999997764825821) && this.ActiveLessonVisible) { - return; + this.activeLesson.LessonOnGUI(); } - this.activeLesson.LessonOnGUI(); } public void ActiveLessonUpdate() { - if (Time.timeSinceLevelLoad < 0.01f || !this.ActiveLessonVisible) + if (!(Time.timeSinceLevelLoad < 0.0099999997764825821) && this.ActiveLessonVisible) { - return; + this.activeLesson.LessonUpdate(); } - this.activeLesson.LessonUpdate(); } public void Notify_KnowledgeDemonstrated(ConceptDef conc) diff --git a/Assembly-CSharp/RimWorld/AddictionUtility.cs b/Assembly-CSharp/RimWorld/AddictionUtility.cs index 1bcf83217..e36601fda 100644 --- a/Assembly-CSharp/RimWorld/AddictionUtility.cs +++ b/Assembly-CSharp/RimWorld/AddictionUtility.cs @@ -33,7 +33,7 @@ public static Hediff_Addiction FindAddictionHediff(Pawn pawn, Thing drug) public static Hediff_Addiction FindAddictionHediff(Pawn pawn, ChemicalDef chemical) { - return (Hediff_Addiction)pawn.health.hediffSet.hediffs.Find((Hediff x) => x.def == chemical.addictionHediff); + return (Hediff_Addiction)pawn.health.hediffSet.hediffs.Find((Predicate)((Hediff x) => x.def == chemical.addictionHediff)); } public static Hediff FindToleranceHediff(Pawn pawn, ChemicalDef chemical) @@ -42,7 +42,7 @@ public static Hediff FindToleranceHediff(Pawn pawn, ChemicalDef chemical) { return null; } - return pawn.health.hediffSet.hediffs.Find((Hediff x) => x.def == chemical.toleranceHediff); + return pawn.health.hediffSet.hediffs.Find((Predicate)((Hediff x) => x.def == chemical.toleranceHediff)); } public static void ModifyChemicalEffectForToleranceAndBodySize(Pawn pawn, ChemicalDef chemicalDef, ref float effect) @@ -60,19 +60,10 @@ public static void ModifyChemicalEffectForToleranceAndBodySize(Pawn pawn, Chemic public static void CheckDrugAddictionTeachOpportunity(Pawn pawn) { - if (!pawn.RaceProps.IsFlesh || !pawn.Spawned) + if (pawn.RaceProps.IsFlesh && pawn.Spawned && (pawn.Faction == Faction.OfPlayer || pawn.HostFaction == Faction.OfPlayer) && AddictionUtility.AddictedToAnything(pawn)) { - return; + LessonAutoActivator.TeachOpportunity(ConceptDefOf.DrugAddiction, pawn, OpportunityType.Important); } - if (pawn.Faction != Faction.OfPlayer && pawn.HostFaction != Faction.OfPlayer) - { - return; - } - if (!AddictionUtility.AddictedToAnything(pawn)) - { - return; - } - LessonAutoActivator.TeachOpportunity(ConceptDefOf.DrugAddiction, pawn, OpportunityType.Important); } public static bool AddictedToAnything(Pawn pawn) @@ -101,21 +92,12 @@ public static bool CanBingeOnNow(Pawn pawn, ChemicalDef chemical, DrugCategory d List list = pawn.Map.listerThings.ThingsInGroup(ThingRequestGroup.Drug); for (int i = 0; i < list.Count; i++) { - if (!list[i].Position.Fogged(list[i].Map)) + if (!list[i].Position.Fogged(list[i].Map) && (drugCategory == DrugCategory.Any || list[i].def.ingestible.drugCategory == drugCategory)) { - if (drugCategory == DrugCategory.Any || list[i].def.ingestible.drugCategory == drugCategory) + CompDrug compDrug = list[i].TryGetComp(); + if (compDrug.Props.chemical == chemical && (list[i].Position.Roofed(list[i].Map) || list[i].Position.InHorDistOf(pawn.Position, 45f)) && pawn.CanReach(list[i], PathEndMode.ClosestTouch, Danger.Deadly, false, TraverseMode.ByPawn)) { - CompDrug compDrug = list[i].TryGetComp(); - if (compDrug.Props.chemical == chemical) - { - if (list[i].Position.Roofed(list[i].Map) || list[i].Position.InHorDistOf(pawn.Position, 45f)) - { - if (pawn.CanReach(list[i], PathEndMode.ClosestTouch, Danger.Deadly, false, TraverseMode.ByPawn)) - { - return true; - } - } - } + return true; } } } diff --git a/Assembly-CSharp/RimWorld/AgeInjuryUtility.cs b/Assembly-CSharp/RimWorld/AgeInjuryUtility.cs index c3ade6080..bac45c93a 100644 --- a/Assembly-CSharp/RimWorld/AgeInjuryUtility.cs +++ b/Assembly-CSharp/RimWorld/AgeInjuryUtility.cs @@ -1,7 +1,6 @@ using RimWorld.Planet; using System; using System.Collections.Generic; -using System.Diagnostics; using System.Linq; using System.Text; using UnityEngine; @@ -20,47 +19,58 @@ public static IEnumerable RandomHediffsToGainOnBirthday(Pa return AgeInjuryUtility.RandomHediffsToGainOnBirthday(pawn.def, age); } - [DebuggerHidden] private static IEnumerable RandomHediffsToGainOnBirthday(ThingDef raceDef, int age) { - AgeInjuryUtility.c__IteratorC6 c__IteratorC = new AgeInjuryUtility.c__IteratorC6(); - c__IteratorC.raceDef = raceDef; - c__IteratorC.age = age; - c__IteratorC.<$>raceDef = raceDef; - c__IteratorC.<$>age = age; - AgeInjuryUtility.c__IteratorC6 expr_23 = c__IteratorC; - expr_23.$PC = -2; - return expr_23; + List sets = raceDef.race.hediffGiverSets; + if (sets != null) + { + for (int j = 0; j < sets.Count; j++) + { + List givers = sets[j].hediffGivers; + for (int i = 0; i < givers.Count; i++) + { + HediffGiver_Birthday agb = givers[i] as HediffGiver_Birthday; + if (agb != null) + { + float ageFractionOfLifeExpectancy = (float)age / raceDef.race.lifeExpectancy; + if (Rand.Value < agb.ageFractionChanceCurve.Evaluate(ageFractionOfLifeExpectancy)) + { + yield return agb; + } + } + } + } + } } public static void GenerateRandomOldAgeInjuries(Pawn pawn, bool tryNotToKillPawn) { int num = 0; - for (int i = 10; i < Mathf.Min(pawn.ageTracker.AgeBiologicalYears, 120); i += 10) + for (int num2 = 10; num2 < Mathf.Min(pawn.ageTracker.AgeBiologicalYears, 120); num2 += 10) { - if (Rand.Value < 0.15f) + if (Rand.Value < 0.15000000596046448) { num++; } } - for (int j = 0; j < num; j++) + for (int num3 = 0; num3 < num; num3++) { IEnumerable source = from x in pawn.health.hediffSet.GetNotMissingParts(BodyPartHeight.Undefined, BodyPartDepth.Undefined) where x.depth == BodyPartDepth.Outside && !Mathf.Approximately(x.def.oldInjuryBaseChance, 0f) && !pawn.health.hediffSet.PartOrAnyAncestorHasDirectlyAddedParts(x) select x; - if (source.Any()) + if (source.Any()) { - BodyPartRecord bodyPartRecord = source.RandomElementByWeight((BodyPartRecord x) => x.coverageAbs); - DamageDef dam = AgeInjuryUtility.RandomOldInjuryDamageType(bodyPartRecord.def.frostbiteVulnerability > 0f && pawn.RaceProps.ToolUser); + BodyPartRecord bodyPartRecord = source.RandomElementByWeight((Func)((BodyPartRecord x) => x.coverageAbs)); + DamageDef dam = AgeInjuryUtility.RandomOldInjuryDamageType(bodyPartRecord.def.frostbiteVulnerability > 0.0 && pawn.RaceProps.ToolUser); HediffDef hediffDefFromDamage = HealthUtility.GetHediffDefFromDamage(dam, pawn, bodyPartRecord); - if (bodyPartRecord.def.oldInjuryBaseChance > 0f && hediffDefFromDamage.CompPropsFor(typeof(HediffComp_GetsOld)) != null) + if (bodyPartRecord.def.oldInjuryBaseChance > 0.0 && hediffDefFromDamage.CompPropsFor(typeof(HediffComp_GetsOld)) != null) { if (Rand.Chance(bodyPartRecord.def.amputateIfGeneratedInjuredChance)) { Hediff_MissingPart hediff_MissingPart = (Hediff_MissingPart)HediffMaker.MakeHediff(HediffDefOf.MissingBodyPart, pawn, null); hediff_MissingPart.lastInjury = hediffDefFromDamage; hediff_MissingPart.TryGetComp().IsOld = true; - pawn.health.AddHediff(hediff_MissingPart, bodyPartRecord, null); + pawn.health.AddHediff(hediff_MissingPart, bodyPartRecord, default(DamageInfo?)); if (pawn.RaceProps.Humanlike && (bodyPartRecord.def == BodyPartDefOf.LeftLeg || bodyPartRecord.def == BodyPartDefOf.RightLeg) && Rand.Chance(0.5f)) { RecipeDefOf.InstallPegLeg.Worker.ApplyOnPawn(pawn, bodyPartRecord, null, AgeInjuryUtility.emptyIngredientsList); @@ -71,45 +81,58 @@ public static void GenerateRandomOldAgeInjuries(Pawn pawn, bool tryNotToKillPawn Hediff_Injury hediff_Injury = (Hediff_Injury)HediffMaker.MakeHediff(hediffDefFromDamage, pawn, null); hediff_Injury.Severity = (float)Rand.RangeInclusive(2, 6); hediff_Injury.TryGetComp().IsOld = true; - pawn.health.AddHediff(hediff_Injury, bodyPartRecord, null); + pawn.health.AddHediff(hediff_Injury, bodyPartRecord, default(DamageInfo?)); } } } } - for (int k = 1; k < pawn.ageTracker.AgeBiologicalYears; k++) + int num4 = 1; + while (num4 < pawn.ageTracker.AgeBiologicalYears) { - foreach (HediffGiver_Birthday current in AgeInjuryUtility.RandomHediffsToGainOnBirthday(pawn, k)) + foreach (HediffGiver_Birthday item in AgeInjuryUtility.RandomHediffsToGainOnBirthday(pawn, num4)) { - current.TryApplyAndSimulateSeverityChange(pawn, (float)k, tryNotToKillPawn); + item.TryApplyAndSimulateSeverityChange(pawn, (float)num4, tryNotToKillPawn); if (pawn.Dead) - { break; - } } - if (pawn.Dead) + if (!pawn.Dead) { - break; + num4++; + continue; } + break; } } private static DamageDef RandomOldInjuryDamageType(bool allowFrostbite) { - switch (Rand.RangeInclusive(0, 3 + ((!allowFrostbite) ? 0 : 1))) + switch (Rand.RangeInclusive(0, 3 + (allowFrostbite ? 1 : 0))) { case 0: + { return DamageDefOf.Bullet; + } case 1: + { return DamageDefOf.Scratch; + } case 2: + { return DamageDefOf.Bite; + } case 3: + { return DamageDefOf.Stab; + } case 4: + { return DamageDefOf.Frostbite; + } default: + { throw new Exception(); } + } } public static void LogOldInjuryCalculations() @@ -122,18 +145,12 @@ public static void LogOldInjuryCalculations() List list = new List(); for (int j = 0; j < 100; j++) { - foreach (HediffGiver_Birthday current in AgeInjuryUtility.RandomHediffsToGainOnBirthday(ThingDefOf.Human, j)) + foreach (HediffGiver_Birthday item in AgeInjuryUtility.RandomHediffsToGainOnBirthday(ThingDefOf.Human, j)) { - if (!list.Contains(current.hediff)) + if (!list.Contains(item.hediff)) { - list.Add(current.hediff); - stringBuilder.AppendLine(string.Concat(new object[] - { - " age ", - j, - " - ", - current.hediff - })); + list.Add(item.hediff); + stringBuilder.AppendLine(" age " + j + " - " + item.hediff); } } } @@ -147,9 +164,18 @@ public static void LogOldInjuryCalculations() if (pawn.ageTracker.AgeBiologicalYears >= 40) { stringBuilder.AppendLine(pawn.Name + " age " + pawn.ageTracker.AgeBiologicalYears); - foreach (Hediff current2 in pawn.health.hediffSet.hediffs) + List.Enumerator enumerator2 = pawn.health.hediffSet.hediffs.GetEnumerator(); + try + { + while (enumerator2.MoveNext()) + { + Hediff current2 = enumerator2.Current; + stringBuilder.AppendLine(" - " + current2); + } + } + finally { - stringBuilder.AppendLine(" - " + current2); + ((IDisposable)(object)enumerator2).Dispose(); } } Find.WorldPawns.PassToWorld(pawn, PawnDiscardDecideMode.Discard); diff --git a/Assembly-CSharp/RimWorld/Alert.cs b/Assembly-CSharp/RimWorld/Alert.cs index 0920af8f9..620a4adfa 100644 --- a/Assembly-CSharp/RimWorld/Alert.cs +++ b/Assembly-CSharp/RimWorld/Alert.cs @@ -52,7 +52,8 @@ public virtual bool Active { get { - return this.GetReport().active; + AlertReport report = this.GetReport(); + return report.active; } } @@ -70,14 +71,14 @@ public virtual string GetLabel() public void Notify_Started() { - if (this.Priority >= AlertPriority.High) + if ((int)this.Priority >= 1) { if (this.alertBounce == null) { this.alertBounce = new AlertBounce(); } this.alertBounce.DoAlertStartEffect(); - if (Time.timeSinceLevelLoad > 1f && Time.realtimeSinceStartup > this.lastBellTime + 0.5f) + if (Time.timeSinceLevelLoad > 1.0 && Time.realtimeSinceStartup > this.lastBellTime + 0.5) { SoundDefOf.TinyBell.PlayOneShotOnCamera(null); this.lastBellTime = Time.realtimeSinceStartup; @@ -94,7 +95,7 @@ public virtual Rect DrawAt(float topY, bool minimized) Text.Font = GameFont.Small; string label = this.GetLabel(); float height = Text.CalcHeight(label, 148f); - Rect rect = new Rect((float)UI.screenWidth - 154f, topY, 154f, height); + Rect rect = new Rect((float)((float)UI.screenWidth - 154.0), topY, 154f, height); if (this.alertBounce != null) { rect.x -= this.alertBounce.CalculateHorizontalOffset(); @@ -110,9 +111,14 @@ public virtual Rect DrawAt(float topY, bool minimized) { GUI.DrawTexture(rect, Alert.AlertBGTexHighlight); } - if (Widgets.ButtonInvisible(rect, false) && this.GetReport().culprit.IsValid) + if (Widgets.ButtonInvisible(rect, false)) { - CameraJumper.TryJumpAndSelect(this.GetReport().culprit); + AlertReport report = this.GetReport(); + if (report.culprit.IsValid) + { + AlertReport report2 = this.GetReport(); + CameraJumper.TryJumpAndSelect(report2.culprit); + } } Text.Anchor = TextAnchor.UpperLeft; return rect; @@ -120,34 +126,35 @@ public virtual Rect DrawAt(float topY, bool minimized) public void DrawInfoPane() { - Alert.c__AnonStorey3E9 c__AnonStorey3E = new Alert.c__AnonStorey3E9(); Text.Font = GameFont.Small; Text.Anchor = TextAnchor.UpperLeft; - c__AnonStorey3E.expString = this.GetExplanation(); - if (this.GetReport().culprit.IsValid) + string expString = this.GetExplanation(); + AlertReport report = this.GetReport(); + if (report.culprit.IsValid) { - c__AnonStorey3E.expString = c__AnonStorey3E.expString + "\n\n(" + "ClickToJumpToProblem".Translate() + ")"; + expString = expString + "\n\n(" + "ClickToJumpToProblem".Translate() + ")"; } - float num = Text.CalcHeight(c__AnonStorey3E.expString, 310f); - num += 20f; - c__AnonStorey3E.infoRect = new Rect((float)UI.screenWidth - 154f - 330f - 8f, Mathf.Max(Mathf.Min(Event.current.mousePosition.y, (float)UI.screenHeight - num), 0f), 330f, num); - if (c__AnonStorey3E.infoRect.yMax > (float)UI.screenHeight) + float num = Text.CalcHeight(expString, 310f); + num = (float)(num + 20.0); + double x = (float)UI.screenWidth - 154.0 - 330.0 - 8.0; + Vector2 mousePosition = Event.current.mousePosition; + Rect infoRect = new Rect((float)x, Mathf.Max(Mathf.Min(mousePosition.y, (float)UI.screenHeight - num), 0f), 330f, num); + if (infoRect.yMax > (float)UI.screenHeight) { - Alert.c__AnonStorey3E9 expr_E2_cp_0 = c__AnonStorey3E; - expr_E2_cp_0.infoRect.y = expr_E2_cp_0.infoRect.y - ((float)UI.screenHeight - c__AnonStorey3E.infoRect.yMax); + infoRect.y -= (float)UI.screenHeight - infoRect.yMax; } - if (c__AnonStorey3E.infoRect.y < 0f) + if (infoRect.y < 0.0) { - c__AnonStorey3E.infoRect.y = 0f; + infoRect.y = 0f; } - Find.WindowStack.ImmediateWindow(138956, c__AnonStorey3E.infoRect, WindowLayer.GameUI, delegate + Find.WindowStack.ImmediateWindow(138956, infoRect, WindowLayer.GameUI, (Action)delegate { Text.Font = GameFont.Small; - Rect rect = c__AnonStorey3E.infoRect.AtZero(); + Rect rect = infoRect.AtZero(); Widgets.DrawWindowBackground(rect); Rect position = rect.ContractedBy(10f); GUI.BeginGroup(position); - Widgets.Label(new Rect(0f, 0f, position.width, position.height), c__AnonStorey3E.expString); + Widgets.Label(new Rect(0f, 0f, position.width, position.height), expString); GUI.EndGroup(); }, false, false, 1f); } diff --git a/Assembly-CSharp/RimWorld/AlertBounce.cs b/Assembly-CSharp/RimWorld/AlertBounce.cs index b57cce6de..61d70788d 100644 --- a/Assembly-CSharp/RimWorld/AlertBounce.cs +++ b/Assembly-CSharp/RimWorld/AlertBounce.cs @@ -1,4 +1,3 @@ -using System; using UnityEngine; namespace RimWorld @@ -41,14 +40,14 @@ public float CalculateHorizontalOffset() } float num = Mathf.Min(Time.time - this.lastTime, 0.05f); this.lastTime = Time.time; - this.velocity -= 1200f * num; + this.velocity -= (float)(1200.0 * num); this.position += this.velocity * num; - if (this.position < 0f) + if (this.position < 0.0) { this.position = 0f; - this.velocity = Mathf.Max(-this.velocity / 3f - 1f, 0f); + this.velocity = Mathf.Max((float)((0.0 - this.velocity) / 3.0 - 1.0), 0f); } - if (Mathf.Abs(this.velocity) < 0.0001f && this.position < 1f) + if (Mathf.Abs(this.velocity) < 9.9999997473787516E-05 && this.position < 1.0) { this.velocity = 0f; this.position = 0f; diff --git a/Assembly-CSharp/RimWorld/AlertPriority.cs b/Assembly-CSharp/RimWorld/AlertPriority.cs index 6d6dfe0b0..d5ff5b864 100644 --- a/Assembly-CSharp/RimWorld/AlertPriority.cs +++ b/Assembly-CSharp/RimWorld/AlertPriority.cs @@ -1,11 +1,9 @@ -using System; - namespace RimWorld { public enum AlertPriority : byte { - Medium, - High, - Critical + Medium = 0, + High = 1, + Critical = 2 } } diff --git a/Assembly-CSharp/RimWorld/AlertReport.cs b/Assembly-CSharp/RimWorld/AlertReport.cs index 25190a4ec..586eb7d7e 100644 --- a/Assembly-CSharp/RimWorld/AlertReport.cs +++ b/Assembly-CSharp/RimWorld/AlertReport.cs @@ -1,5 +1,4 @@ using RimWorld.Planet; -using System; using Verse; namespace RimWorld diff --git a/Assembly-CSharp/RimWorld/Alert_AwaitingMedicalOperation.cs b/Assembly-CSharp/RimWorld/Alert_AwaitingMedicalOperation.cs index 9955ed90d..305993f46 100644 --- a/Assembly-CSharp/RimWorld/Alert_AwaitingMedicalOperation.cs +++ b/Assembly-CSharp/RimWorld/Alert_AwaitingMedicalOperation.cs @@ -20,22 +20,22 @@ where HealthAIUtility.ShouldHaveSurgeryDoneNow(p) && p.InBed() public override string GetLabel() { - return string.Format("PatientsAwaitingMedicalOperation".Translate(), this.AwaitingMedicalOperation.Count().ToStringCached()); + return string.Format("PatientsAwaitingMedicalOperation".Translate(), this.AwaitingMedicalOperation.Count().ToStringCached()); } public override string GetExplanation() { StringBuilder stringBuilder = new StringBuilder(); - foreach (Pawn current in this.AwaitingMedicalOperation) + foreach (Pawn item in this.AwaitingMedicalOperation) { - stringBuilder.AppendLine(" " + current.NameStringShort); + stringBuilder.AppendLine(" " + item.NameStringShort); } return string.Format("PatientsAwaitingMedicalOperationDesc".Translate(), stringBuilder.ToString()); } public override AlertReport GetReport() { - return this.AwaitingMedicalOperation.FirstOrDefault(); + return (Thing)this.AwaitingMedicalOperation.FirstOrDefault(); } } } diff --git a/Assembly-CSharp/RimWorld/Alert_BilliardsTableOnWall.cs b/Assembly-CSharp/RimWorld/Alert_BilliardsTableOnWall.cs index bd92f40e9..ce6019f94 100644 --- a/Assembly-CSharp/RimWorld/Alert_BilliardsTableOnWall.cs +++ b/Assembly-CSharp/RimWorld/Alert_BilliardsTableOnWall.cs @@ -1,4 +1,3 @@ -using System; using System.Collections.Generic; using Verse; @@ -8,8 +7,8 @@ public class Alert_BilliardsTableOnWall : Alert { public Alert_BilliardsTableOnWall() { - this.defaultLabel = "BilliardsNeedsSpace".Translate(); - this.defaultExplanation = "BilliardsNeedsSpaceDesc".Translate(); + base.defaultLabel = "BilliardsNeedsSpace".Translate(); + base.defaultExplanation = "BilliardsNeedsSpaceDesc".Translate(); } private Thing BadTable() diff --git a/Assembly-CSharp/RimWorld/Alert_BrawlerHasRangedWeapon.cs b/Assembly-CSharp/RimWorld/Alert_BrawlerHasRangedWeapon.cs index 9e065659c..a6e3c3661 100644 --- a/Assembly-CSharp/RimWorld/Alert_BrawlerHasRangedWeapon.cs +++ b/Assembly-CSharp/RimWorld/Alert_BrawlerHasRangedWeapon.cs @@ -1,4 +1,3 @@ -using System; using Verse; namespace RimWorld @@ -7,17 +6,17 @@ public class Alert_BrawlerHasRangedWeapon : Alert { public Alert_BrawlerHasRangedWeapon() { - this.defaultLabel = "BrawlerHasRangedWeapon".Translate(); - this.defaultExplanation = "BrawlerHasRangedWeaponDesc".Translate(); + base.defaultLabel = "BrawlerHasRangedWeapon".Translate(); + base.defaultExplanation = "BrawlerHasRangedWeaponDesc".Translate(); } public override AlertReport GetReport() { - foreach (Pawn current in PawnsFinder.AllMaps_FreeColonistsSpawned) + foreach (Pawn item in PawnsFinder.AllMaps_FreeColonistsSpawned) { - if (current.story.traits.HasTrait(TraitDefOf.Brawler) && current.equipment.Primary != null && current.equipment.Primary.def.IsRangedWeapon) + if (item.story.traits.HasTrait(TraitDefOf.Brawler) && item.equipment.Primary != null && item.equipment.Primary.def.IsRangedWeapon) { - return current; + return (Thing)item; } } return false; diff --git a/Assembly-CSharp/RimWorld/Alert_ColonistNeedsRescuing.cs b/Assembly-CSharp/RimWorld/Alert_ColonistNeedsRescuing.cs index 18c7d0184..b97adddaf 100644 --- a/Assembly-CSharp/RimWorld/Alert_ColonistNeedsRescuing.cs +++ b/Assembly-CSharp/RimWorld/Alert_ColonistNeedsRescuing.cs @@ -1,4 +1,3 @@ -using System; using System.Collections.Generic; using System.Linq; using System.Text; @@ -12,21 +11,32 @@ private IEnumerable ColonistsNeedingRescue { get { - Alert_ColonistNeedsRescuing.<>c__Iterator186 <>c__Iterator = new Alert_ColonistNeedsRescuing.<>c__Iterator186(); - Alert_ColonistNeedsRescuing.<>c__Iterator186 expr_07 = <>c__Iterator; - expr_07.$PC = -2; - return expr_07; + foreach (Pawn item in PawnsFinder.AllMaps_FreeColonistsSpawned) + { + if (Alert_ColonistNeedsRescuing.NeedsRescue(item)) + { + yield return item; + } + } } } public static bool NeedsRescue(Pawn p) { - return p.Downed && !p.InBed() && !(p.ParentHolder is Pawn_CarryTracker) && (p.jobs.jobQueue == null || p.jobs.jobQueue.Count <= 0 || !p.jobs.jobQueue.Peek().job.CanBeginNow(p)); + if (p.Downed && !p.InBed() && !(p.ParentHolder is Pawn_CarryTracker)) + { + if (p.jobs.jobQueue != null && p.jobs.jobQueue.Count > 0 && p.jobs.jobQueue.Peek().job.CanBeginNow(p)) + { + return false; + } + return true; + } + return false; } public override string GetLabel() { - if (this.ColonistsNeedingRescue.Count() == 1) + if (this.ColonistsNeedingRescue.Count() == 1) { return "ColonistNeedsRescue".Translate(); } @@ -36,16 +46,16 @@ public override string GetLabel() public override string GetExplanation() { StringBuilder stringBuilder = new StringBuilder(); - foreach (Pawn current in this.ColonistsNeedingRescue) + foreach (Pawn item in this.ColonistsNeedingRescue) { - stringBuilder.AppendLine(" " + current.NameStringShort); + stringBuilder.AppendLine(" " + item.NameStringShort); } return string.Format("ColonistsNeedRescueDesc".Translate(), stringBuilder.ToString()); } public override AlertReport GetReport() { - return AlertReport.CulpritIs(this.ColonistsNeedingRescue.FirstOrDefault()); + return AlertReport.CulpritIs((Thing)this.ColonistsNeedingRescue.FirstOrDefault()); } } } diff --git a/Assembly-CSharp/RimWorld/Alert_ColonistNeedsTend.cs b/Assembly-CSharp/RimWorld/Alert_ColonistNeedsTend.cs index 4a17f4b25..02763b629 100644 --- a/Assembly-CSharp/RimWorld/Alert_ColonistNeedsTend.cs +++ b/Assembly-CSharp/RimWorld/Alert_ColonistNeedsTend.cs @@ -1,4 +1,3 @@ -using System; using System.Collections.Generic; using System.Linq; using System.Text; @@ -12,37 +11,44 @@ private IEnumerable NeedingColonists { get { - Alert_ColonistNeedsTend.<>c__Iterator189 <>c__Iterator = new Alert_ColonistNeedsTend.<>c__Iterator189(); - Alert_ColonistNeedsTend.<>c__Iterator189 expr_07 = <>c__Iterator; - expr_07.$PC = -2; - return expr_07; + foreach (Pawn item in PawnsFinder.AllMaps_FreeColonistsSpawned) + { + if (item.health.HasHediffsNeedingTendByColony(true)) + { + Building_Bed curBed = item.CurrentBed(); + if ((curBed == null || !curBed.Medical) && !Alert_ColonistNeedsRescuing.NeedsRescue(item)) + { + yield return item; + } + } + } } } public Alert_ColonistNeedsTend() { - this.defaultLabel = "ColonistNeedsTreatment".Translate(); - this.defaultPriority = AlertPriority.High; + base.defaultLabel = "ColonistNeedsTreatment".Translate(); + base.defaultPriority = AlertPriority.High; } public override string GetExplanation() { StringBuilder stringBuilder = new StringBuilder(); - foreach (Pawn current in this.NeedingColonists) + foreach (Pawn needingColonist in this.NeedingColonists) { - stringBuilder.AppendLine(" " + current.NameStringShort); + stringBuilder.AppendLine(" " + needingColonist.NameStringShort); } return string.Format("ColonistNeedsTreatmentDesc".Translate(), stringBuilder.ToString()); } public override AlertReport GetReport() { - Pawn pawn = this.NeedingColonists.FirstOrDefault(); + Pawn pawn = this.NeedingColonists.FirstOrDefault(); if (pawn == null) { return false; } - return AlertReport.CulpritIs(pawn); + return AlertReport.CulpritIs((Thing)pawn); } } } diff --git a/Assembly-CSharp/RimWorld/Alert_ColonistsIdle.cs b/Assembly-CSharp/RimWorld/Alert_ColonistsIdle.cs index 47cc5d1d0..f48fe9742 100644 --- a/Assembly-CSharp/RimWorld/Alert_ColonistsIdle.cs +++ b/Assembly-CSharp/RimWorld/Alert_ColonistsIdle.cs @@ -1,4 +1,3 @@ -using System; using System.Collections.Generic; using System.Linq; using System.Text; @@ -14,24 +13,34 @@ private IEnumerable IdleColonists { get { - Alert_ColonistsIdle.<>c__Iterator18A <>c__Iterator18A = new Alert_ColonistsIdle.<>c__Iterator18A(); - Alert_ColonistsIdle.<>c__Iterator18A expr_07 = <>c__Iterator18A; - expr_07.$PC = -2; - return expr_07; + List maps = Find.Maps; + for (int i = 0; i < maps.Count; i++) + { + if (maps[i].IsPlayerHome) + { + foreach (Pawn item in maps[i].mapPawns.FreeColonistsSpawned) + { + if (item.mindState.IsIdle) + { + yield return item; + } + } + } + } } } public override string GetLabel() { - return string.Format("ColonistsIdle".Translate(), this.IdleColonists.Count().ToStringCached()); + return string.Format("ColonistsIdle".Translate(), this.IdleColonists.Count().ToStringCached()); } public override string GetExplanation() { StringBuilder stringBuilder = new StringBuilder(); - foreach (Pawn current in this.IdleColonists) + foreach (Pawn idleColonist in this.IdleColonists) { - stringBuilder.AppendLine(" " + current.NameStringShort); + stringBuilder.AppendLine(" " + idleColonist.NameStringShort); } return string.Format("ColonistsIdleDesc".Translate(), stringBuilder.ToString()); } @@ -42,7 +51,7 @@ public override AlertReport GetReport() { return AlertReport.Inactive; } - return this.IdleColonists.FirstOrDefault(); + return (Thing)this.IdleColonists.FirstOrDefault(); } } } diff --git a/Assembly-CSharp/RimWorld/Alert_Critical.cs b/Assembly-CSharp/RimWorld/Alert_Critical.cs index e460d22e6..52962b440 100644 --- a/Assembly-CSharp/RimWorld/Alert_Critical.cs +++ b/Assembly-CSharp/RimWorld/Alert_Critical.cs @@ -1,4 +1,3 @@ -using System; using UnityEngine; using Verse; @@ -25,17 +24,16 @@ protected override Color BGColor public Alert_Critical() { - this.defaultPriority = AlertPriority.Critical; + base.defaultPriority = AlertPriority.Critical; } public override void AlertActiveUpdate() { if (this.lastActiveFrame < Time.frameCount - 1) { - Messages.Message("MessageCriticalAlert".Translate(new object[] - { - this.GetLabel() - }), this.GetReport().culprit, MessageSound.SeriousAlert); + string text = "MessageCriticalAlert".Translate(this.GetLabel()); + AlertReport report = this.GetReport(); + Messages.Message(text, report.culprit, MessageSound.SeriousAlert); } this.lastActiveFrame = Time.frameCount; } diff --git a/Assembly-CSharp/RimWorld/Alert_Exhaustion.cs b/Assembly-CSharp/RimWorld/Alert_Exhaustion.cs index c485a548e..7ce55e49e 100644 --- a/Assembly-CSharp/RimWorld/Alert_Exhaustion.cs +++ b/Assembly-CSharp/RimWorld/Alert_Exhaustion.cs @@ -20,23 +20,23 @@ private IEnumerable ExhaustedColonists public Alert_Exhaustion() { - this.defaultLabel = "Exhaustion".Translate(); - this.defaultPriority = AlertPriority.High; + base.defaultLabel = "Exhaustion".Translate(); + base.defaultPriority = AlertPriority.High; } public override string GetExplanation() { StringBuilder stringBuilder = new StringBuilder(); - foreach (Pawn current in this.ExhaustedColonists) + foreach (Pawn exhaustedColonist in this.ExhaustedColonists) { - stringBuilder.AppendLine(" " + current.NameStringShort); + stringBuilder.AppendLine(" " + exhaustedColonist.NameStringShort); } return string.Format("ExhaustionDesc".Translate(), stringBuilder.ToString()); } public override AlertReport GetReport() { - return AlertReport.CulpritIs(this.ExhaustedColonists.FirstOrDefault()); + return AlertReport.CulpritIs((Thing)this.ExhaustedColonists.FirstOrDefault()); } } } diff --git a/Assembly-CSharp/RimWorld/Alert_FireInHomeArea.cs b/Assembly-CSharp/RimWorld/Alert_FireInHomeArea.cs index 07fcd4f0a..128738fda 100644 --- a/Assembly-CSharp/RimWorld/Alert_FireInHomeArea.cs +++ b/Assembly-CSharp/RimWorld/Alert_FireInHomeArea.cs @@ -1,4 +1,3 @@ -using System; using System.Collections.Generic; using Verse; @@ -17,7 +16,7 @@ private Fire FireInHomeArea for (int j = 0; j < list.Count; j++) { Thing thing = list[j]; - if (maps[i].areaManager.Home[thing.Position] && !thing.Position.Fogged(thing.Map)) + if (((Area)maps[i].areaManager.Home)[thing.Position] && !thing.Position.Fogged(thing.Map)) { return (Fire)thing; } @@ -29,8 +28,8 @@ private Fire FireInHomeArea public Alert_FireInHomeArea() { - this.defaultLabel = "FireInHomeArea".Translate(); - this.defaultExplanation = "FireInHomeAreaDesc".Translate(); + base.defaultLabel = "FireInHomeArea".Translate(); + base.defaultExplanation = "FireInHomeAreaDesc".Translate(); } public override AlertReport GetReport() @@ -38,7 +37,7 @@ public override AlertReport GetReport() Fire fireInHomeArea = this.FireInHomeArea; if (fireInHomeArea != null) { - return AlertReport.CulpritIs(fireInHomeArea); + return AlertReport.CulpritIs((Thing)fireInHomeArea); } return false; } diff --git a/Assembly-CSharp/RimWorld/Alert_HunterHasShieldAndRangedWeapon.cs b/Assembly-CSharp/RimWorld/Alert_HunterHasShieldAndRangedWeapon.cs index da48d324b..96cee80ea 100644 --- a/Assembly-CSharp/RimWorld/Alert_HunterHasShieldAndRangedWeapon.cs +++ b/Assembly-CSharp/RimWorld/Alert_HunterHasShieldAndRangedWeapon.cs @@ -1,4 +1,3 @@ -using System; using Verse; namespace RimWorld @@ -7,17 +6,17 @@ public class Alert_HunterHasShieldAndRangedWeapon : Alert { public Alert_HunterHasShieldAndRangedWeapon() { - this.defaultLabel = "HunterHasShieldAndRangedWeapon".Translate(); - this.defaultExplanation = "HunterHasShieldAndRangedWeaponDesc".Translate(); + base.defaultLabel = "HunterHasShieldAndRangedWeapon".Translate(); + base.defaultExplanation = "HunterHasShieldAndRangedWeaponDesc".Translate(); } private Pawn BadHunter() { - foreach (Pawn current in PawnsFinder.AllMaps_FreeColonistsSpawned) + foreach (Pawn item in PawnsFinder.AllMaps_FreeColonistsSpawned) { - if (current.workSettings.WorkIsActive(WorkTypeDefOf.Hunting) && WorkGiver_HunterHunt.HasShieldAndRangedWeapon(current)) + if (item.workSettings.WorkIsActive(WorkTypeDefOf.Hunting) && WorkGiver_HunterHunt.HasShieldAndRangedWeapon(item)) { - return current; + return item; } } return null; @@ -30,7 +29,7 @@ public override AlertReport GetReport() { return false; } - return AlertReport.CulpritIs(pawn); + return AlertReport.CulpritIs((Thing)pawn); } } } diff --git a/Assembly-CSharp/RimWorld/Alert_HunterLacksRangedWeapon.cs b/Assembly-CSharp/RimWorld/Alert_HunterLacksRangedWeapon.cs index 3ad2046d5..1dc582a94 100644 --- a/Assembly-CSharp/RimWorld/Alert_HunterLacksRangedWeapon.cs +++ b/Assembly-CSharp/RimWorld/Alert_HunterLacksRangedWeapon.cs @@ -1,4 +1,3 @@ -using System; using Verse; namespace RimWorld @@ -7,18 +6,18 @@ public class Alert_HunterLacksRangedWeapon : Alert { public Alert_HunterLacksRangedWeapon() { - this.defaultLabel = "HunterLacksWeapon".Translate(); - this.defaultExplanation = "HunterLacksWeaponDesc".Translate(); - this.defaultPriority = AlertPriority.High; + base.defaultLabel = "HunterLacksWeapon".Translate(); + base.defaultExplanation = "HunterLacksWeaponDesc".Translate(); + base.defaultPriority = AlertPriority.High; } public override AlertReport GetReport() { - foreach (Pawn current in PawnsFinder.AllMaps_FreeColonistsSpawned) + foreach (Pawn item in PawnsFinder.AllMaps_FreeColonistsSpawned) { - if (current.workSettings.WorkIsActive(WorkTypeDefOf.Hunting) && !WorkGiver_HunterHunt.HasHuntingWeapon(current) && !current.Downed) + if (item.workSettings.WorkIsActive(WorkTypeDefOf.Hunting) && !WorkGiver_HunterHunt.HasHuntingWeapon(item) && !item.Downed) { - return current; + return (Thing)item; } } return false; diff --git a/Assembly-CSharp/RimWorld/Alert_Hypothermia.cs b/Assembly-CSharp/RimWorld/Alert_Hypothermia.cs index 627c91ccd..8e2dde9b1 100644 --- a/Assembly-CSharp/RimWorld/Alert_Hypothermia.cs +++ b/Assembly-CSharp/RimWorld/Alert_Hypothermia.cs @@ -1,4 +1,3 @@ -using System; using System.Collections.Generic; using System.Linq; using System.Text; @@ -12,39 +11,43 @@ private IEnumerable HypothermiaDangerColonists { get { - Alert_Hypothermia.<>c__Iterator185 <>c__Iterator = new Alert_Hypothermia.<>c__Iterator185(); - Alert_Hypothermia.<>c__Iterator185 expr_07 = <>c__Iterator; - expr_07.$PC = -2; - return expr_07; + foreach (Pawn item in PawnsFinder.AllMaps_FreeColonistsSpawned) + { + if (!item.SafeTemperatureRange().Includes(item.AmbientTemperature)) + { + Hediff hypo = item.health.hediffSet.GetFirstHediffOfDef(HediffDefOf.Hypothermia, false); + if (hypo != null && hypo.CurStageIndex >= 3) + { + yield return item; + } + } + } } } public Alert_Hypothermia() { - this.defaultLabel = "AlertHypothermia".Translate(); + base.defaultLabel = "AlertHypothermia".Translate(); } public override string GetExplanation() { StringBuilder stringBuilder = new StringBuilder(); - foreach (Pawn current in this.HypothermiaDangerColonists) + foreach (Pawn hypothermiaDangerColonist in this.HypothermiaDangerColonists) { - stringBuilder.AppendLine(" " + current.NameStringShort); + stringBuilder.AppendLine(" " + hypothermiaDangerColonist.NameStringShort); } - return "AlertHypothermiaDesc".Translate(new object[] - { - stringBuilder.ToString() - }); + return "AlertHypothermiaDesc".Translate(stringBuilder.ToString()); } public override AlertReport GetReport() { - Pawn pawn = this.HypothermiaDangerColonists.FirstOrDefault(); + Pawn pawn = this.HypothermiaDangerColonists.FirstOrDefault(); if (pawn == null) { return false; } - return AlertReport.CulpritIs(pawn); + return AlertReport.CulpritIs((Thing)pawn); } } } diff --git a/Assembly-CSharp/RimWorld/Alert_HypothermicAnimals.cs b/Assembly-CSharp/RimWorld/Alert_HypothermicAnimals.cs index a67718e4c..3ca30b4f2 100644 --- a/Assembly-CSharp/RimWorld/Alert_HypothermicAnimals.cs +++ b/Assembly-CSharp/RimWorld/Alert_HypothermicAnimals.cs @@ -27,15 +27,9 @@ public override string GetExplanation() { StringBuilder stringBuilder = new StringBuilder(); stringBuilder.AppendLine("Debug alert:\n\nThese wild animals are hypothermic. This may indicate a bug (but it may not, if the animals are trapped or in some other wierd but legitimate situation):"); - foreach (Pawn current in this.HypothermicAnimals) + foreach (Pawn hypothermicAnimal in this.HypothermicAnimals) { - stringBuilder.AppendLine(string.Concat(new object[] - { - " ", - current, - " at ", - current.Position - })); + stringBuilder.AppendLine(" " + hypothermicAnimal + " at " + hypothermicAnimal.Position); } return stringBuilder.ToString(); } @@ -46,7 +40,7 @@ public override AlertReport GetReport() { return false; } - return this.HypothermicAnimals.FirstOrDefault(); + return (Thing)this.HypothermicAnimals.FirstOrDefault(); } } } diff --git a/Assembly-CSharp/RimWorld/Alert_ImmobileCaravan.cs b/Assembly-CSharp/RimWorld/Alert_ImmobileCaravan.cs index c865bd779..432b2012c 100644 --- a/Assembly-CSharp/RimWorld/Alert_ImmobileCaravan.cs +++ b/Assembly-CSharp/RimWorld/Alert_ImmobileCaravan.cs @@ -1,5 +1,4 @@ using RimWorld.Planet; -using System; using System.Collections.Generic; using Verse; @@ -25,14 +24,14 @@ private Caravan FirstImmobileCaravan public Alert_ImmobileCaravan() { - this.defaultLabel = "ImmobileCaravan".Translate(); - this.defaultExplanation = "ImmobileCaravanDesc".Translate(); - this.defaultPriority = AlertPriority.High; + base.defaultLabel = "ImmobileCaravan".Translate(); + base.defaultExplanation = "ImmobileCaravanDesc".Translate(); + base.defaultPriority = AlertPriority.High; } public override AlertReport GetReport() { - return this.FirstImmobileCaravan; + return (WorldObject)this.FirstImmobileCaravan; } } } diff --git a/Assembly-CSharp/RimWorld/Alert_LifeThreateningHediff.cs b/Assembly-CSharp/RimWorld/Alert_LifeThreateningHediff.cs index 01a59520c..b22efc6a0 100644 --- a/Assembly-CSharp/RimWorld/Alert_LifeThreateningHediff.cs +++ b/Assembly-CSharp/RimWorld/Alert_LifeThreateningHediff.cs @@ -12,10 +12,26 @@ private IEnumerable SickPawns { get { - Alert_LifeThreateningHediff.<>c__Iterator187 <>c__Iterator = new Alert_LifeThreateningHediff.<>c__Iterator187(); - Alert_LifeThreateningHediff.<>c__Iterator187 expr_07 = <>c__Iterator; - expr_07.$PC = -2; - return expr_07; + foreach (Pawn item in PawnsFinder.AllMaps_FreeColonistsAndPrisonersSpawned) + { + List.Enumerator enumerator2 = item.health.hediffSet.hediffs.GetEnumerator(); + try + { + while (enumerator2.MoveNext()) + { + Hediff diff = enumerator2.Current; + if (diff.CurStage != null && diff.CurStage.lifeThreatening && !diff.FullyImmune()) + { + yield return item; + break; + } + } + } + finally + { + ((IDisposable)(object)enumerator2).Dispose(); + } + } } } @@ -28,17 +44,26 @@ public override string GetExplanation() { StringBuilder stringBuilder = new StringBuilder(); bool flag = false; - foreach (Pawn current in this.SickPawns) + foreach (Pawn sickPawn in this.SickPawns) { - stringBuilder.AppendLine(" " + current.NameStringShort); - foreach (Hediff current2 in current.health.hediffSet.hediffs) + stringBuilder.AppendLine(" " + sickPawn.NameStringShort); + List.Enumerator enumerator2 = sickPawn.health.hediffSet.hediffs.GetEnumerator(); + try { - if (current2.CurStage != null && current2.CurStage.lifeThreatening && current2.Part != null && current2.Part != current.RaceProps.body.corePart) + while (enumerator2.MoveNext()) { - flag = true; - break; + Hediff current2 = enumerator2.Current; + if (current2.CurStage != null && current2.CurStage.lifeThreatening && current2.Part != null && current2.Part != sickPawn.RaceProps.body.corePart) + { + flag = true; + break; + } } } + finally + { + ((IDisposable)(object)enumerator2).Dispose(); + } } if (flag) { @@ -49,7 +74,7 @@ public override string GetExplanation() public override AlertReport GetReport() { - return AlertReport.CulpritIs(this.SickPawns.FirstOrDefault()); + return AlertReport.CulpritIs((Thing)this.SickPawns.FirstOrDefault()); } } } diff --git a/Assembly-CSharp/RimWorld/Alert_LowFood.cs b/Assembly-CSharp/RimWorld/Alert_LowFood.cs index a9a05e720..808b46e58 100644 --- a/Assembly-CSharp/RimWorld/Alert_LowFood.cs +++ b/Assembly-CSharp/RimWorld/Alert_LowFood.cs @@ -12,8 +12,8 @@ public class Alert_LowFood : Alert public Alert_LowFood() { - this.defaultLabel = "LowFood".Translate(); - this.defaultPriority = AlertPriority.High; + base.defaultLabel = "LowFood".Translate(); + base.defaultPriority = AlertPriority.High; } public override string GetExplanation() @@ -26,7 +26,7 @@ public override string GetExplanation() float totalHumanEdibleNutrition = map.resourceCounter.TotalHumanEdibleNutrition; int num = map.mapPawns.FreeColonistsSpawnedCount + (from pr in map.mapPawns.PrisonersOfColony where pr.guest.GetsFood - select pr).Count(); + select pr).Count(); int num2 = Mathf.FloorToInt(totalHumanEdibleNutrition / (float)num); return string.Format("LowFoodDesc".Translate(), totalHumanEdibleNutrition.ToString("F0"), num.ToStringCached(), num2.ToStringCached()); } @@ -49,7 +49,7 @@ private Map MapWithLowFood() if (map.IsPlayerHome) { int freeColonistsSpawnedCount = map.mapPawns.FreeColonistsSpawnedCount; - if (map.resourceCounter.TotalHumanEdibleNutrition < 4f * (float)freeColonistsSpawnedCount) + if (map.resourceCounter.TotalHumanEdibleNutrition < 4.0 * (float)freeColonistsSpawnedCount) { return map; } diff --git a/Assembly-CSharp/RimWorld/Alert_LowMedicine.cs b/Assembly-CSharp/RimWorld/Alert_LowMedicine.cs index 9add0a93e..86ecc1396 100644 --- a/Assembly-CSharp/RimWorld/Alert_LowMedicine.cs +++ b/Assembly-CSharp/RimWorld/Alert_LowMedicine.cs @@ -1,4 +1,3 @@ -using System; using System.Collections.Generic; using Verse; @@ -10,8 +9,8 @@ public class Alert_LowMedicine : Alert public Alert_LowMedicine() { - this.defaultLabel = "LowMedicine".Translate(); - this.defaultPriority = AlertPriority.High; + base.defaultLabel = "LowMedicine".Translate(); + base.defaultPriority = AlertPriority.High; } public override string GetExplanation() @@ -24,7 +23,7 @@ public override string GetExplanation() int num = this.MedicineCount(map); if (num == 0) { - return string.Format("NoMedicineDesc".Translate(), new object[0]); + return string.Format("NoMedicineDesc".Translate()); } return string.Format("LowMedicineDesc".Translate(), num); } @@ -44,12 +43,9 @@ private Map MapWithLowMedicine() for (int i = 0; i < maps.Count; i++) { Map map = maps[i]; - if (map.IsPlayerHome) + if (map.IsPlayerHome && (float)this.MedicineCount(map) < 2.0 * (float)map.mapPawns.FreeColonistsSpawnedCount) { - if ((float)this.MedicineCount(map) < 2f * (float)map.mapPawns.FreeColonistsSpawnedCount) - { - return map; - } + return map; } } return null; diff --git a/Assembly-CSharp/RimWorld/Alert_MajorOrExtremeBreakRisk.cs b/Assembly-CSharp/RimWorld/Alert_MajorOrExtremeBreakRisk.cs index 901955720..a89bcce5b 100644 --- a/Assembly-CSharp/RimWorld/Alert_MajorOrExtremeBreakRisk.cs +++ b/Assembly-CSharp/RimWorld/Alert_MajorOrExtremeBreakRisk.cs @@ -1,4 +1,3 @@ -using System; using System.Linq; using Verse; @@ -18,15 +17,15 @@ public override string GetExplanation() public override AlertReport GetReport() { - Pawn pawn = BreakRiskAlertUtility.PawnsAtRiskExtreme.FirstOrDefault(); + Pawn pawn = BreakRiskAlertUtility.PawnsAtRiskExtreme.FirstOrDefault(); if (pawn != null) { - return pawn; + return (Thing)pawn; } - pawn = BreakRiskAlertUtility.PawnsAtRiskMajor.FirstOrDefault(); + pawn = BreakRiskAlertUtility.PawnsAtRiskMajor.FirstOrDefault(); if (pawn != null) { - return pawn; + return (Thing)pawn; } return false; } diff --git a/Assembly-CSharp/RimWorld/Alert_MinorBreakRisk.cs b/Assembly-CSharp/RimWorld/Alert_MinorBreakRisk.cs index f0e524bd3..08cc2e4c0 100644 --- a/Assembly-CSharp/RimWorld/Alert_MinorBreakRisk.cs +++ b/Assembly-CSharp/RimWorld/Alert_MinorBreakRisk.cs @@ -1,4 +1,3 @@ -using System; using System.Linq; using Verse; @@ -8,7 +7,7 @@ public class Alert_MinorBreakRisk : Alert { public Alert_MinorBreakRisk() { - this.defaultPriority = AlertPriority.High; + base.defaultPriority = AlertPriority.High; } public override string GetLabel() @@ -23,15 +22,15 @@ public override string GetExplanation() public override AlertReport GetReport() { - if (BreakRiskAlertUtility.PawnsAtRiskExtreme.Any() || BreakRiskAlertUtility.PawnsAtRiskMajor.Any()) + if (!BreakRiskAlertUtility.PawnsAtRiskExtreme.Any() && !BreakRiskAlertUtility.PawnsAtRiskMajor.Any()) { + Pawn pawn = BreakRiskAlertUtility.PawnsAtRiskMinor.FirstOrDefault(); + if (pawn != null) + { + return (Thing)pawn; + } return false; } - Pawn pawn = BreakRiskAlertUtility.PawnsAtRiskMinor.FirstOrDefault(); - if (pawn != null) - { - return pawn; - } return false; } } diff --git a/Assembly-CSharp/RimWorld/Alert_NeedBatteries.cs b/Assembly-CSharp/RimWorld/Alert_NeedBatteries.cs index 712a73a62..86ecd685e 100644 --- a/Assembly-CSharp/RimWorld/Alert_NeedBatteries.cs +++ b/Assembly-CSharp/RimWorld/Alert_NeedBatteries.cs @@ -1,4 +1,3 @@ -using System; using System.Collections.Generic; using Verse; @@ -8,8 +7,8 @@ public class Alert_NeedBatteries : Alert { public Alert_NeedBatteries() { - this.defaultLabel = "NeedBatteries".Translate(); - this.defaultExplanation = "NeedBatteriesDesc".Translate(); + base.defaultLabel = "NeedBatteries".Translate(); + base.defaultExplanation = "NeedBatteriesDesc".Translate(); } public override AlertReport GetReport() @@ -27,7 +26,23 @@ public override AlertReport GetReport() private bool NeedBatteries(Map map) { - return map.IsPlayerHome && !map.listerBuildings.ColonistsHaveBuilding(ThingDefOf.Battery) && (map.listerBuildings.ColonistsHaveBuilding(ThingDefOf.SolarGenerator) || map.listerBuildings.ColonistsHaveBuilding(ThingDefOf.WindTurbine)) && !map.listerBuildings.ColonistsHaveBuilding(ThingDefOf.GeothermalGenerator); + if (!map.IsPlayerHome) + { + return false; + } + if (map.listerBuildings.ColonistsHaveBuilding(ThingDefOf.Battery)) + { + return false; + } + if (!map.listerBuildings.ColonistsHaveBuilding(ThingDefOf.SolarGenerator) && !map.listerBuildings.ColonistsHaveBuilding(ThingDefOf.WindTurbine)) + { + return false; + } + if (map.listerBuildings.ColonistsHaveBuilding(ThingDefOf.GeothermalGenerator)) + { + return false; + } + return true; } } } diff --git a/Assembly-CSharp/RimWorld/Alert_NeedColonistBeds.cs b/Assembly-CSharp/RimWorld/Alert_NeedColonistBeds.cs index cb37dc383..d2f21ab2e 100644 --- a/Assembly-CSharp/RimWorld/Alert_NeedColonistBeds.cs +++ b/Assembly-CSharp/RimWorld/Alert_NeedColonistBeds.cs @@ -1,4 +1,3 @@ -using System; using System.Collections.Generic; using Verse; @@ -8,9 +7,9 @@ public class Alert_NeedColonistBeds : Alert { public Alert_NeedColonistBeds() { - this.defaultLabel = "NeedColonistBeds".Translate(); - this.defaultExplanation = "NeedColonistBedsDesc".Translate(); - this.defaultPriority = AlertPriority.High; + base.defaultLabel = "NeedColonistBeds".Translate(); + base.defaultExplanation = "NeedColonistBedsDesc".Translate(); + base.defaultPriority = AlertPriority.High; } public override AlertReport GetReport() @@ -56,10 +55,10 @@ private bool NeedColonistBeds(Map map) } int num3 = 0; int num4 = 0; - foreach (Pawn current in map.mapPawns.FreeColonistsSpawned) + foreach (Pawn item in map.mapPawns.FreeColonistsSpawned) { - Pawn pawn = LovePartnerRelationUtility.ExistingMostLikedLovePartner(current, false); - if (pawn == null || !pawn.Spawned || pawn.Map != current.Map || pawn.Faction != Faction.OfPlayer || pawn.HostFaction != null) + Pawn pawn = LovePartnerRelationUtility.ExistingMostLikedLovePartner(item, false); + if (pawn == null || !pawn.Spawned || pawn.Map != item.Map || pawn.Faction != Faction.OfPlayer || pawn.HostFaction != null) { num3++; } @@ -83,7 +82,7 @@ private bool NeedColonistBeds(Map map) num -= 2; } } - for (int k = 0; k < num3; k++) + for (int num5 = 0; num5 < num3; num5++) { if (num2 > 0) { diff --git a/Assembly-CSharp/RimWorld/Alert_NeedDefenses.cs b/Assembly-CSharp/RimWorld/Alert_NeedDefenses.cs index 1f8fff8fa..179ab6945 100644 --- a/Assembly-CSharp/RimWorld/Alert_NeedDefenses.cs +++ b/Assembly-CSharp/RimWorld/Alert_NeedDefenses.cs @@ -8,24 +8,24 @@ public class Alert_NeedDefenses : Alert { public Alert_NeedDefenses() { - this.defaultLabel = "NeedDefenses".Translate(); - this.defaultExplanation = "NeedDefensesDesc".Translate(); - this.defaultPriority = AlertPriority.High; + base.defaultLabel = "NeedDefenses".Translate(); + base.defaultExplanation = "NeedDefensesDesc".Translate(); + base.defaultPriority = AlertPriority.High; } public override AlertReport GetReport() { - if (GenDate.DaysPassed < 2 || GenDate.DaysPassed > 5) + if (GenDate.DaysPassed >= 2 && GenDate.DaysPassed <= 5) { - return false; - } - List maps = Find.Maps; - for (int i = 0; i < maps.Count; i++) - { - if (this.NeedDefenses(maps[i])) + List maps = Find.Maps; + for (int i = 0; i < maps.Count; i++) { - return true; + if (this.NeedDefenses(maps[i])) + { + return true; + } } + return false; } return false; } @@ -36,7 +36,11 @@ private bool NeedDefenses(Map map) { return false; } - return !map.listerBuildings.allBuildingsColonist.Any((Building b) => (b.def.building != null && (b.def.building.IsTurret || b.def.building.isTrap)) || b.def == ThingDefOf.Sandbags); + if (map.listerBuildings.allBuildingsColonist.Any((Predicate)((Building b) => (b.def.building != null && (b.def.building.IsTurret || b.def.building.isTrap)) || b.def == ThingDefOf.Sandbags))) + { + return false; + } + return true; } } } diff --git a/Assembly-CSharp/RimWorld/Alert_NeedDoctor.cs b/Assembly-CSharp/RimWorld/Alert_NeedDoctor.cs index 91f57d200..e57bc341e 100644 --- a/Assembly-CSharp/RimWorld/Alert_NeedDoctor.cs +++ b/Assembly-CSharp/RimWorld/Alert_NeedDoctor.cs @@ -1,4 +1,3 @@ -using System; using System.Collections.Generic; using System.Linq; using System.Text; @@ -12,25 +11,52 @@ private IEnumerable Patients { get { - Alert_NeedDoctor.<>c__Iterator188 <>c__Iterator = new Alert_NeedDoctor.<>c__Iterator188(); - Alert_NeedDoctor.<>c__Iterator188 expr_07 = <>c__Iterator; - expr_07.$PC = -2; - return expr_07; + List maps = Find.Maps; + for (int i = 0; i < maps.Count; i++) + { + if (maps[i].IsPlayerHome) + { + bool healthyDoc = false; + foreach (Pawn item in maps[i].mapPawns.FreeColonistsSpawned) + { + if (!item.Downed && item.workSettings != null && item.workSettings.WorkIsActive(WorkTypeDefOf.Doctor)) + { + healthyDoc = true; + break; + } + } + if (!healthyDoc) + { + foreach (Pawn item2 in maps[i].mapPawns.FreeColonistsSpawned) + { + if (item2.Downed && (int)item2.needs.food.CurCategory < 0 && item2.InBed()) + { + goto IL_01b3; + } + if (HealthAIUtility.ShouldBeTendedNow(item2)) + goto IL_01b3; + continue; + IL_01b3: + yield return item2; + } + } + } + } } } public Alert_NeedDoctor() { - this.defaultLabel = "NeedDoctor".Translate(); - this.defaultPriority = AlertPriority.High; + base.defaultLabel = "NeedDoctor".Translate(); + base.defaultPriority = AlertPriority.High; } public override string GetExplanation() { StringBuilder stringBuilder = new StringBuilder(); - foreach (Pawn current in this.Patients) + foreach (Pawn patient in this.Patients) { - stringBuilder.AppendLine(" " + current.NameStringShort); + stringBuilder.AppendLine(" " + patient.NameStringShort); } return string.Format("NeedDoctorDesc".Translate(), stringBuilder.ToString()); } @@ -41,12 +67,12 @@ public override AlertReport GetReport() { return false; } - Pawn pawn = this.Patients.FirstOrDefault(); + Pawn pawn = this.Patients.FirstOrDefault(); if (pawn == null) { return false; } - return AlertReport.CulpritIs(pawn); + return AlertReport.CulpritIs((Thing)pawn); } } } diff --git a/Assembly-CSharp/RimWorld/Alert_NeedJoySource.cs b/Assembly-CSharp/RimWorld/Alert_NeedJoySource.cs index 12e55a1a6..dd63ffa93 100644 --- a/Assembly-CSharp/RimWorld/Alert_NeedJoySource.cs +++ b/Assembly-CSharp/RimWorld/Alert_NeedJoySource.cs @@ -8,13 +8,13 @@ public class Alert_NeedJoySource : Alert { public Alert_NeedJoySource() { - this.defaultLabel = "NeedJoySource".Translate(); - this.defaultExplanation = "NeedJoySourceDesc".Translate(); + base.defaultLabel = "NeedJoySource".Translate(); + base.defaultExplanation = "NeedJoySourceDesc".Translate(); } public override AlertReport GetReport() { - if (GenDate.DaysPassedFloat < 6.5f) + if (GenDate.DaysPassedFloat < 6.5) { return false; } @@ -35,7 +35,11 @@ private bool NeedJoySource(Map map) { return false; } - return !map.listerBuildings.allBuildingsColonist.Any((Building b) => b.def.building.isJoySource); + if (map.listerBuildings.allBuildingsColonist.Any((Predicate)((Building b) => b.def.building.isJoySource))) + { + return false; + } + return true; } } } diff --git a/Assembly-CSharp/RimWorld/Alert_NeedMealSource.cs b/Assembly-CSharp/RimWorld/Alert_NeedMealSource.cs index b68260a46..9db432919 100644 --- a/Assembly-CSharp/RimWorld/Alert_NeedMealSource.cs +++ b/Assembly-CSharp/RimWorld/Alert_NeedMealSource.cs @@ -8,8 +8,8 @@ public class Alert_NeedMealSource : Alert { public Alert_NeedMealSource() { - this.defaultLabel = "NeedMealSource".Translate(); - this.defaultExplanation = "NeedMealSourceDesc".Translate(); + base.defaultLabel = "NeedMealSource".Translate(); + base.defaultExplanation = "NeedMealSourceDesc".Translate(); } public override AlertReport GetReport() @@ -35,7 +35,11 @@ private bool NeedMealSource(Map map) { return false; } - return !map.listerBuildings.allBuildingsColonist.Any((Building b) => b.def.building.isMealSource); + if (map.listerBuildings.allBuildingsColonist.Any((Predicate)((Building b) => b.def.building.isMealSource))) + { + return false; + } + return true; } } } diff --git a/Assembly-CSharp/RimWorld/Alert_NeedMiner.cs b/Assembly-CSharp/RimWorld/Alert_NeedMiner.cs index 11cdcdf21..9a00148f3 100644 --- a/Assembly-CSharp/RimWorld/Alert_NeedMiner.cs +++ b/Assembly-CSharp/RimWorld/Alert_NeedMiner.cs @@ -9,9 +9,9 @@ public class Alert_NeedMiner : Alert { public Alert_NeedMiner() { - this.defaultLabel = "NeedMiner".Translate(); - this.defaultExplanation = "NeedMinerDesc".Translate(); - this.defaultPriority = AlertPriority.High; + base.defaultLabel = "NeedMiner".Translate(); + base.defaultExplanation = "NeedMinerDesc".Translate(); + base.defaultPriority = AlertPriority.High; } public override AlertReport GetReport() @@ -24,13 +24,13 @@ public override AlertReport GetReport() { Designation designation = (from d in map.designationManager.allDesignations where d.def == DesignationDefOf.Mine - select d).FirstOrDefault(); + select d).FirstOrDefault(); if (designation != null) { bool flag = false; - foreach (Pawn current in map.mapPawns.FreeColonistsSpawned) + foreach (Pawn item in map.mapPawns.FreeColonistsSpawned) { - if (!current.Downed && current.workSettings != null && current.workSettings.GetPriority(WorkTypeDefOf.Mining) > 0) + if (!item.Downed && item.workSettings != null && item.workSettings.GetPriority(WorkTypeDefOf.Mining) > 0) { flag = true; break; diff --git a/Assembly-CSharp/RimWorld/Alert_NeedResearchProject.cs b/Assembly-CSharp/RimWorld/Alert_NeedResearchProject.cs index 6baee9b79..f77413aa2 100644 --- a/Assembly-CSharp/RimWorld/Alert_NeedResearchProject.cs +++ b/Assembly-CSharp/RimWorld/Alert_NeedResearchProject.cs @@ -1,4 +1,3 @@ -using System; using System.Collections.Generic; using Verse; @@ -8,8 +7,8 @@ public class Alert_NeedResearchProject : Alert { public Alert_NeedResearchProject() { - this.defaultLabel = "NeedResearchProject".Translate(); - this.defaultExplanation = "NeedResearchProjectDesc".Translate(); + base.defaultLabel = "NeedResearchProject".Translate(); + base.defaultExplanation = "NeedResearchProjectDesc".Translate(); } public override AlertReport GetReport() @@ -24,16 +23,16 @@ public override AlertReport GetReport() } bool flag = false; List maps = Find.Maps; - for (int i = 0; i < maps.Count; i++) + int num = 0; + while (num < maps.Count) { - if (maps[i].IsPlayerHome) + if (!maps[num].IsPlayerHome || !maps[num].listerBuildings.ColonistsHaveResearchBench()) { - if (maps[i].listerBuildings.ColonistsHaveResearchBench()) - { - flag = true; - break; - } + num++; + continue; } + flag = true; + break; } if (!flag) { diff --git a/Assembly-CSharp/RimWorld/Alert_NeedWarden.cs b/Assembly-CSharp/RimWorld/Alert_NeedWarden.cs index 1f6bd88f2..8d6aaacd3 100644 --- a/Assembly-CSharp/RimWorld/Alert_NeedWarden.cs +++ b/Assembly-CSharp/RimWorld/Alert_NeedWarden.cs @@ -1,4 +1,3 @@ -using System; using System.Collections.Generic; using System.Linq; using Verse; @@ -9,9 +8,9 @@ public class Alert_NeedWarden : Alert { public Alert_NeedWarden() { - this.defaultLabel = "NeedWarden".Translate(); - this.defaultExplanation = "NeedWardenDesc".Translate(); - this.defaultPriority = AlertPriority.High; + base.defaultLabel = "NeedWarden".Translate(); + base.defaultExplanation = "NeedWardenDesc".Translate(); + base.defaultPriority = AlertPriority.High; } public override AlertReport GetReport() @@ -20,24 +19,21 @@ public override AlertReport GetReport() for (int i = 0; i < maps.Count; i++) { Map map = maps[i]; - if (map.IsPlayerHome) + if (map.IsPlayerHome && map.mapPawns.PrisonersOfColonySpawned.Any()) { - if (map.mapPawns.PrisonersOfColonySpawned.Any()) + bool flag = false; + foreach (Pawn item in map.mapPawns.FreeColonistsSpawned) { - bool flag = false; - foreach (Pawn current in map.mapPawns.FreeColonistsSpawned) + if (!item.Downed && item.workSettings != null && item.workSettings.GetPriority(WorkTypeDefOf.Warden) > 0) { - if (!current.Downed && current.workSettings != null && current.workSettings.GetPriority(WorkTypeDefOf.Warden) > 0) - { - flag = true; - break; - } - } - if (!flag) - { - return AlertReport.CulpritIs(map.mapPawns.PrisonersOfColonySpawned.First()); + flag = true; + break; } } + if (!flag) + { + return AlertReport.CulpritIs((Thing)map.mapPawns.PrisonersOfColonySpawned.First()); + } } } return AlertReport.Inactive; diff --git a/Assembly-CSharp/RimWorld/Alert_NeedWarmClothes.cs b/Assembly-CSharp/RimWorld/Alert_NeedWarmClothes.cs index 8bef61f06..122d2aab3 100644 --- a/Assembly-CSharp/RimWorld/Alert_NeedWarmClothes.cs +++ b/Assembly-CSharp/RimWorld/Alert_NeedWarmClothes.cs @@ -21,8 +21,8 @@ public class Alert_NeedWarmClothes : Alert public Alert_NeedWarmClothes() { - this.defaultLabel = "NeedWarmClothes".Translate(); - this.defaultPriority = AlertPriority.High; + base.defaultLabel = "NeedWarmClothes".Translate(); + base.defaultPriority = AlertPriority.High; } private int NeededWarmClothesCount(Map map) @@ -34,9 +34,9 @@ private int ColonistsWithWarmClothesCount(Map map) { float num = this.LowestTemperatureComing(map); int num2 = 0; - foreach (Pawn current in map.mapPawns.FreeColonistsSpawned) + foreach (Pawn item in map.mapPawns.FreeColonistsSpawned) { - if (current.GetStatValue(StatDefOf.ComfyTemperatureMin, true) <= num) + if (item.GetStatValue(StatDefOf.ComfyTemperatureMin, true) <= num) { num2++; } @@ -52,59 +52,58 @@ private int FreeWarmClothesSetsCount(Map map) List list = map.listerThings.ThingsInGroup(ThingRequestGroup.Apparel); for (int i = 0; i < list.Count; i++) { - if (list[i].IsInAnyStorage()) + if (list[i].IsInAnyStorage() && !(list[i].GetStatValue(StatDefOf.Insulation_Cold, true) >= 0.0)) { - if (list[i].GetStatValue(StatDefOf.Insulation_Cold, true) < 0f) + if (list[i].def.apparel.bodyPartGroups.Contains(BodyPartGroupDefOf.Torso)) { - if (list[i].def.apparel.bodyPartGroups.Contains(BodyPartGroupDefOf.Torso)) + if (list[i].def.apparel.layers.Contains(ApparelLayer.OnSkin)) { - if (list[i].def.apparel.layers.Contains(ApparelLayer.OnSkin)) - { - Alert_NeedWarmClothes.shirts.Add(list[i]); - } - else - { - Alert_NeedWarmClothes.jackets.Add(list[i]); - } + Alert_NeedWarmClothes.shirts.Add(list[i]); } - if (list[i].def.apparel.bodyPartGroups.Contains(BodyPartGroupDefOf.Legs)) + else { - Alert_NeedWarmClothes.pants.Add(list[i]); + Alert_NeedWarmClothes.jackets.Add(list[i]); } } + if (list[i].def.apparel.bodyPartGroups.Contains(BodyPartGroupDefOf.Legs)) + { + Alert_NeedWarmClothes.pants.Add(list[i]); + } } } - Alert_NeedWarmClothes.jackets.SortByDescending((Thing x) => x.GetStatValue(StatDefOf.Insulation_Cold, true)); - Alert_NeedWarmClothes.shirts.SortByDescending((Thing x) => x.GetStatValue(StatDefOf.Insulation_Cold, true)); - Alert_NeedWarmClothes.pants.SortByDescending((Thing x) => x.GetStatValue(StatDefOf.Insulation_Cold, true)); + Alert_NeedWarmClothes.jackets.SortByDescending((Func)((Thing x) => x.GetStatValue(StatDefOf.Insulation_Cold, true))); + Alert_NeedWarmClothes.shirts.SortByDescending((Func)((Thing x) => x.GetStatValue(StatDefOf.Insulation_Cold, true))); + Alert_NeedWarmClothes.pants.SortByDescending((Func)((Thing x) => x.GetStatValue(StatDefOf.Insulation_Cold, true))); float num = ThingDefOf.Human.GetStatValueAbstract(StatDefOf.ComfyTemperatureMin, null) - this.LowestTemperatureComing(map); - if (num <= 0f) + if (num <= 0.0) { return GenMath.Max(Alert_NeedWarmClothes.jackets.Count, Alert_NeedWarmClothes.shirts.Count, Alert_NeedWarmClothes.pants.Count); } int num2 = 0; - while (Alert_NeedWarmClothes.jackets.Any() || Alert_NeedWarmClothes.shirts.Any() || Alert_NeedWarmClothes.pants.Any()) + while (true) { + if (!Alert_NeedWarmClothes.jackets.Any() && !Alert_NeedWarmClothes.shirts.Any() && !Alert_NeedWarmClothes.pants.Any()) + break; float num3 = 0f; - if (Alert_NeedWarmClothes.jackets.Any()) + if (Alert_NeedWarmClothes.jackets.Any()) { Thing thing = Alert_NeedWarmClothes.jackets[Alert_NeedWarmClothes.jackets.Count - 1]; - Alert_NeedWarmClothes.jackets.RemoveLast(); - float num4 = -thing.GetStatValue(StatDefOf.Insulation_Cold, true); + Alert_NeedWarmClothes.jackets.RemoveLast(); + float num4 = (float)(0.0 - thing.GetStatValue(StatDefOf.Insulation_Cold, true)); num3 += num4; } - if (num3 < num && Alert_NeedWarmClothes.shirts.Any()) + if (num3 < num && Alert_NeedWarmClothes.shirts.Any()) { Thing thing2 = Alert_NeedWarmClothes.shirts[Alert_NeedWarmClothes.shirts.Count - 1]; - Alert_NeedWarmClothes.shirts.RemoveLast(); - float num5 = -thing2.GetStatValue(StatDefOf.Insulation_Cold, true); + Alert_NeedWarmClothes.shirts.RemoveLast(); + float num5 = (float)(0.0 - thing2.GetStatValue(StatDefOf.Insulation_Cold, true)); num3 += num5; } - if (num3 < num && Alert_NeedWarmClothes.pants.Any()) + if (num3 < num && Alert_NeedWarmClothes.pants.Any()) { for (int j = 0; j < Alert_NeedWarmClothes.pants.Count; j++) { - float num6 = -Alert_NeedWarmClothes.pants[j].GetStatValue(StatDefOf.Insulation_Cold, true); + float num6 = (float)(0.0 - Alert_NeedWarmClothes.pants[j].GetStatValue(StatDefOf.Insulation_Cold, true)); if (num6 + num3 >= num) { num3 += num6; @@ -113,10 +112,8 @@ private int FreeWarmClothesSetsCount(Map map) } } } - if (num3 < num) - { + if (!(num3 >= num)) break; - } num2++; } return num2; @@ -153,18 +150,9 @@ public override string GetExplanation() int num = this.MissingWarmClothesCount(map); if (num == this.NeededWarmClothesCount(map)) { - return "NeedWarmClothesDesc1All".Translate() + "\n\n" + "NeedWarmClothesDesc2".Translate(new object[] - { - this.LowestTemperatureComing(map).ToStringTemperature("F0") - }); + return "NeedWarmClothesDesc1All".Translate() + "\n\n" + "NeedWarmClothesDesc2".Translate(this.LowestTemperatureComing(map).ToStringTemperature("F0")); } - return "NeedWarmClothesDesc1".Translate(new object[] - { - num - }) + "\n\n" + "NeedWarmClothesDesc2".Translate(new object[] - { - this.LowestTemperatureComing(map).ToStringTemperature("F0") - }); + return "NeedWarmClothesDesc1".Translate(num) + "\n\n" + "NeedWarmClothesDesc2".Translate(this.LowestTemperatureComing(map).ToStringTemperature("F0")); } public override AlertReport GetReport() @@ -175,11 +163,11 @@ public override AlertReport GetReport() return false; } float num = this.LowestTemperatureComing(map); - foreach (Pawn current in map.mapPawns.FreeColonistsSpawned) + foreach (Pawn item in map.mapPawns.FreeColonistsSpawned) { - if (current.GetStatValue(StatDefOf.ComfyTemperatureMin, true) > num) + if (item.GetStatValue(StatDefOf.ComfyTemperatureMin, true) > num) { - return current; + return (Thing)item; } } return true; @@ -191,15 +179,9 @@ private Map MapWithMissingWarmClothes() for (int i = 0; i < maps.Count; i++) { Map map = maps[i]; - if (map.IsPlayerHome) + if (map.IsPlayerHome && !(this.LowestTemperatureComing(map) >= 5.0) && this.MissingWarmClothesCount(map) > 0) { - if (this.LowestTemperatureComing(map) < 5f) - { - if (this.MissingWarmClothesCount(map) > 0) - { - return map; - } - } + return map; } } return null; diff --git a/Assembly-CSharp/RimWorld/Alert_PasteDispenserNeedsHopper.cs b/Assembly-CSharp/RimWorld/Alert_PasteDispenserNeedsHopper.cs index 6027c193c..8b6252b28 100644 --- a/Assembly-CSharp/RimWorld/Alert_PasteDispenserNeedsHopper.cs +++ b/Assembly-CSharp/RimWorld/Alert_PasteDispenserNeedsHopper.cs @@ -9,9 +9,9 @@ public class Alert_PasteDispenserNeedsHopper : Alert { public Alert_PasteDispenserNeedsHopper() { - this.defaultLabel = "NeedFoodHopper".Translate(); - this.defaultExplanation = "NeedFoodHopperDesc".Translate(); - this.defaultPriority = AlertPriority.High; + base.defaultLabel = "NeedFoodHopper".Translate(); + base.defaultExplanation = "NeedFoodHopperDesc".Translate(); + base.defaultPriority = AlertPriority.High; } public override AlertReport GetReport() @@ -19,17 +19,17 @@ public override AlertReport GetReport() List maps = Find.Maps; for (int i = 0; i < maps.Count; i++) { - foreach (Building current in from b in maps[i].listerBuildings.allBuildingsColonist + foreach (Building item in from b in maps[i].listerBuildings.allBuildingsColonist where b.def.IsFoodDispenser select b) { bool flag = false; ThingDef hopper = ThingDefOf.Hopper; - foreach (IntVec3 current2 in GenAdj.CellsAdjacentCardinal(current)) + foreach (IntVec3 item2 in GenAdj.CellsAdjacentCardinal(item)) { - if (current2.InBounds(maps[i])) + if (item2.InBounds(maps[i])) { - Thing edifice = current2.GetEdifice(current.Map); + Thing edifice = item2.GetEdifice(item.Map); if (edifice != null && edifice.def == hopper) { flag = true; @@ -39,7 +39,7 @@ where b.def.IsFoodDispenser } if (!flag) { - return AlertReport.CulpritIs(current); + return AlertReport.CulpritIs((Thing)item); } } } diff --git a/Assembly-CSharp/RimWorld/Alert_ShieldUserHasRangedWeapon.cs b/Assembly-CSharp/RimWorld/Alert_ShieldUserHasRangedWeapon.cs index 91381c319..2aae2013e 100644 --- a/Assembly-CSharp/RimWorld/Alert_ShieldUserHasRangedWeapon.cs +++ b/Assembly-CSharp/RimWorld/Alert_ShieldUserHasRangedWeapon.cs @@ -7,20 +7,17 @@ public class Alert_ShieldUserHasRangedWeapon : Alert { public Alert_ShieldUserHasRangedWeapon() { - this.defaultLabel = "ShieldUserHasRangedWeapon".Translate(); - this.defaultExplanation = "ShieldUserHasRangedWeaponDesc".Translate(); + base.defaultLabel = "ShieldUserHasRangedWeapon".Translate(); + base.defaultExplanation = "ShieldUserHasRangedWeaponDesc".Translate(); } public override AlertReport GetReport() { - foreach (Pawn current in PawnsFinder.AllMaps_FreeColonistsSpawned) + foreach (Pawn item in PawnsFinder.AllMaps_FreeColonistsSpawned) { - if (current.equipment.Primary != null && current.equipment.Primary.def.IsRangedWeapon) + if (item.equipment.Primary != null && item.equipment.Primary.def.IsRangedWeapon && item.apparel.WornApparel.Any((Predicate)((Apparel ap) => ap.def == ThingDefOf.Apparel_ShieldBelt))) { - if (current.apparel.WornApparel.Any((Apparel ap) => ap.def == ThingDefOf.Apparel_ShieldBelt)) - { - return current; - } + return (Thing)item; } } return false; diff --git a/Assembly-CSharp/RimWorld/Alert_StarvationAnimals.cs b/Assembly-CSharp/RimWorld/Alert_StarvationAnimals.cs index 5ee3675ff..c1756106b 100644 --- a/Assembly-CSharp/RimWorld/Alert_StarvationAnimals.cs +++ b/Assembly-CSharp/RimWorld/Alert_StarvationAnimals.cs @@ -21,20 +21,20 @@ private IEnumerable StarvingAnimals public Alert_StarvationAnimals() { - this.defaultLabel = "StarvationAnimals".Translate(); + base.defaultLabel = "StarvationAnimals".Translate(); } public override string GetExplanation() { StringBuilder stringBuilder = new StringBuilder(); - foreach (Pawn current in from a in this.StarvingAnimals + foreach (Pawn item in from a in this.StarvingAnimals orderby a.def.label select a) { - stringBuilder.Append(" " + current.NameStringShort); - if (current.Name.IsValid && !current.Name.Numerical) + stringBuilder.Append(" " + item.NameStringShort); + if (item.Name.IsValid && !item.Name.Numerical) { - stringBuilder.Append(" (" + current.def.label + ")"); + stringBuilder.Append(" (" + item.def.label + ")"); } stringBuilder.AppendLine(); } @@ -43,7 +43,7 @@ orderby a.def.label public override AlertReport GetReport() { - return AlertReport.CulpritIs(this.StarvingAnimals.FirstOrDefault()); + return AlertReport.CulpritIs((Thing)this.StarvingAnimals.FirstOrDefault()); } } } diff --git a/Assembly-CSharp/RimWorld/Alert_StarvationColonists.cs b/Assembly-CSharp/RimWorld/Alert_StarvationColonists.cs index 51d364d17..6717047b6 100644 --- a/Assembly-CSharp/RimWorld/Alert_StarvationColonists.cs +++ b/Assembly-CSharp/RimWorld/Alert_StarvationColonists.cs @@ -20,23 +20,23 @@ private IEnumerable StarvingColonists public Alert_StarvationColonists() { - this.defaultLabel = "Starvation".Translate(); - this.defaultPriority = AlertPriority.High; + base.defaultLabel = "Starvation".Translate(); + base.defaultPriority = AlertPriority.High; } public override string GetExplanation() { StringBuilder stringBuilder = new StringBuilder(); - foreach (Pawn current in this.StarvingColonists) + foreach (Pawn starvingColonist in this.StarvingColonists) { - stringBuilder.AppendLine(" " + current.NameStringShort); + stringBuilder.AppendLine(" " + starvingColonist.NameStringShort); } return string.Format("StarvationDesc".Translate(), stringBuilder.ToString()); } public override AlertReport GetReport() { - return AlertReport.CulpritIs(this.StarvingColonists.FirstOrDefault()); + return AlertReport.CulpritIs((Thing)this.StarvingColonists.FirstOrDefault()); } } } diff --git a/Assembly-CSharp/RimWorld/Alert_TatteredApparel.cs b/Assembly-CSharp/RimWorld/Alert_TatteredApparel.cs index 53ec48e48..c284a7f35 100644 --- a/Assembly-CSharp/RimWorld/Alert_TatteredApparel.cs +++ b/Assembly-CSharp/RimWorld/Alert_TatteredApparel.cs @@ -1,4 +1,3 @@ -using System; using Verse; namespace RimWorld @@ -15,8 +14,8 @@ protected override ThoughtDef Thought public Alert_TatteredApparel() { - this.defaultLabel = "AlertTatteredApparel".Translate(); - this.explanationKey = "AlertTatteredApparelDesc"; + base.defaultLabel = "AlertTatteredApparel".Translate(); + base.explanationKey = "AlertTatteredApparelDesc"; } } } diff --git a/Assembly-CSharp/RimWorld/Alert_Thought.cs b/Assembly-CSharp/RimWorld/Alert_Thought.cs index b8bdbeadd..24424a3cd 100644 --- a/Assembly-CSharp/RimWorld/Alert_Thought.cs +++ b/Assembly-CSharp/RimWorld/Alert_Thought.cs @@ -1,6 +1,4 @@ -using System; using System.Collections.Generic; -using System.Diagnostics; using System.Linq; using System.Text; using Verse; @@ -18,22 +16,46 @@ protected abstract ThoughtDef Thought get; } - [DebuggerHidden] private IEnumerable AffectedPawns() { - Alert_Thought.c__Iterator18B c__Iterator18B = new Alert_Thought.c__Iterator18B(); - c__Iterator18B.<>f__this = this; - Alert_Thought.c__Iterator18B expr_0E = c__Iterator18B; - expr_0E.$PC = -2; - return expr_0E; + foreach (Pawn allMaps_FreeColonist in PawnsFinder.AllMaps_FreeColonists) + { + if (allMaps_FreeColonist.Dead) + { + Log.Error("Dead pawn in PawnsFinder.AllMaps_FreeColonists:" + allMaps_FreeColonist); + } + else + { + allMaps_FreeColonist.needs.mood.thoughts.GetAllMoodThoughts(Alert_Thought.tmpThoughts); + try + { + ThoughtDef requiredDef = this.Thought; + int i = 0; + while (i < Alert_Thought.tmpThoughts.Count) + { + if (Alert_Thought.tmpThoughts[i].def != requiredDef) + { + i++; + continue; + } + yield return allMaps_FreeColonist; + break; + } + } + finally + { + ((_003CAffectedPawns_003Ec__Iterator18B)/*Error near IL_0138: stateMachine*/)._003C_003E__Finally0(); + } + } + } } public override AlertReport GetReport() { - Pawn pawn = this.AffectedPawns().FirstOrDefault(); + Pawn pawn = this.AffectedPawns().FirstOrDefault(); if (pawn != null) { - return AlertReport.CulpritIs(pawn); + return AlertReport.CulpritIs((Thing)pawn); } return AlertReport.Inactive; } @@ -41,14 +63,11 @@ public override AlertReport GetReport() public override string GetExplanation() { StringBuilder stringBuilder = new StringBuilder(); - foreach (Pawn current in this.AffectedPawns()) + foreach (Pawn item in this.AffectedPawns()) { - stringBuilder.AppendLine(" " + current.NameStringShort); + stringBuilder.AppendLine(" " + item.NameStringShort); } - return this.explanationKey.Translate(new object[] - { - stringBuilder.ToString() - }); + return this.explanationKey.Translate(stringBuilder.ToString()); } } } diff --git a/Assembly-CSharp/RimWorld/Alert_UnhappyNudity.cs b/Assembly-CSharp/RimWorld/Alert_UnhappyNudity.cs index 0ebcd6158..3180f07b9 100644 --- a/Assembly-CSharp/RimWorld/Alert_UnhappyNudity.cs +++ b/Assembly-CSharp/RimWorld/Alert_UnhappyNudity.cs @@ -1,4 +1,3 @@ -using System; using Verse; namespace RimWorld @@ -15,8 +14,8 @@ protected override ThoughtDef Thought public Alert_UnhappyNudity() { - this.defaultLabel = "AlertUnhappyNudity".Translate(); - this.explanationKey = "AlertUnhappyNudityDesc"; + base.defaultLabel = "AlertUnhappyNudity".Translate(); + base.explanationKey = "AlertUnhappyNudityDesc"; } } } diff --git a/Assembly-CSharp/RimWorld/AlertsReadout.cs b/Assembly-CSharp/RimWorld/AlertsReadout.cs index 445b3ac91..dd655dd3a 100644 --- a/Assembly-CSharp/RimWorld/AlertsReadout.cs +++ b/Assembly-CSharp/RimWorld/AlertsReadout.cs @@ -1,6 +1,5 @@ using RimWorld.Planet; using System; -using System.Collections; using System.Collections.Generic; using UnityEngine; using Verse; @@ -30,20 +29,16 @@ public class AlertsReadout public AlertsReadout() { this.AllAlerts.Clear(); - foreach (Type current in typeof(Alert).AllLeafSubclasses()) + foreach (Type item2 in typeof(Alert).AllLeafSubclasses()) { - this.AllAlerts.Add((Alert)Activator.CreateInstance(current)); + this.AllAlerts.Add((Alert)Activator.CreateInstance(item2)); } if (this.PriosInDrawOrder == null) { this.PriosInDrawOrder = new List(); - using (IEnumerator enumerator2 = Enum.GetValues(typeof(AlertPriority)).GetEnumerator()) + foreach (byte value in Enum.GetValues(typeof(AlertPriority))) { - while (enumerator2.MoveNext()) - { - AlertPriority item = (AlertPriority)((byte)enumerator2.Current); - this.PriosInDrawOrder.Add(item); - } + this.PriosInDrawOrder.Add((AlertPriority)value); } this.PriosInDrawOrder.Reverse(); } @@ -51,134 +46,134 @@ public AlertsReadout() public void AlertsReadoutUpdate() { - if (Mathf.Max(Find.TickManager.TicksGame, Find.TutorialState.endTick) < 600) - { - return; - } - if (Find.Storyteller.def.disableAlerts) - { - this.activeAlerts.Clear(); - return; - } - this.curAlertIndex++; - if (this.curAlertIndex >= AlertsReadout.AlertCycleLength) - { - this.curAlertIndex = 0; - } - for (int i = this.curAlertIndex; i < this.AllAlerts.Count; i += AlertsReadout.AlertCycleLength) + if (Mathf.Max(Find.TickManager.TicksGame, Find.TutorialState.endTick) >= 600) { - Alert alert = this.AllAlerts[i]; - try + if (Find.Storyteller.def.disableAlerts) { - if (alert.Active) + this.activeAlerts.Clear(); + } + else + { + this.curAlertIndex++; + if (this.curAlertIndex >= AlertsReadout.AlertCycleLength) { - if (!this.activeAlerts.Contains(alert)) - { - this.activeAlerts.Add(alert); - alert.Notify_Started(); - } + this.curAlertIndex = 0; } - else + for (int num = this.curAlertIndex; num < this.AllAlerts.Count; num += AlertsReadout.AlertCycleLength) { - for (int j = 0; j < this.activeAlerts.Count; j++) + Alert alert = this.AllAlerts[num]; + try + { + if (alert.Active) + { + if (!this.activeAlerts.Contains(alert)) + { + this.activeAlerts.Add(alert); + alert.Notify_Started(); + } + } + else + { + int num2 = 0; + while (num2 < this.activeAlerts.Count) + { + if (this.activeAlerts[num2] != alert) + { + num2++; + continue; + } + this.activeAlerts.RemoveAt(num2); + break; + } + } + } + catch (Exception ex) { - if (this.activeAlerts[j] == alert) + Log.ErrorOnce("Exception processing alert " + alert.ToString() + ": " + ex.ToString(), 743575); + if (this.activeAlerts.Contains(alert)) { - this.activeAlerts.RemoveAt(j); - break; + this.activeAlerts.Remove(alert); } } } - } - catch (Exception ex) - { - Log.ErrorOnce("Exception processing alert " + alert.ToString() + ": " + ex.ToString(), 743575); - if (this.activeAlerts.Contains(alert)) + for (int num3 = this.activeAlerts.Count - 1; num3 >= 0; num3--) { - this.activeAlerts.Remove(alert); + Alert alert2 = this.activeAlerts[num3]; + try + { + this.activeAlerts[num3].AlertActiveUpdate(); + } + catch (Exception ex2) + { + Log.ErrorOnce("Exception updating alert " + alert2.ToString() + ": " + ex2.ToString(), 743575); + this.activeAlerts.RemoveAt(num3); + } } + if (this.mouseoverAlertIndex >= 0 && this.mouseoverAlertIndex < this.activeAlerts.Count) + { + AlertReport report = this.activeAlerts[this.mouseoverAlertIndex].GetReport(); + GlobalTargetInfo culprit = report.culprit; + if (culprit.IsValid && culprit.IsMapTarget && Find.VisibleMap != null && culprit.Map == Find.VisibleMap) + { + GenDraw.DrawArrowPointingAt(((TargetInfo)culprit).CenterVector3, false); + } + } + this.mouseoverAlertIndex = -1; } } - for (int k = this.activeAlerts.Count - 1; k >= 0; k--) - { - Alert alert2 = this.activeAlerts[k]; - try - { - this.activeAlerts[k].AlertActiveUpdate(); - } - catch (Exception ex2) - { - Log.ErrorOnce("Exception updating alert " + alert2.ToString() + ": " + ex2.ToString(), 743575); - this.activeAlerts.RemoveAt(k); - } - } - if (this.mouseoverAlertIndex >= 0 && this.mouseoverAlertIndex < this.activeAlerts.Count) - { - GlobalTargetInfo culprit = this.activeAlerts[this.mouseoverAlertIndex].GetReport().culprit; - if (culprit.IsValid && culprit.IsMapTarget && Find.VisibleMap != null && culprit.Map == Find.VisibleMap) - { - GenDraw.DrawArrowPointingAt(((TargetInfo)culprit).CenterVector3, false); - } - } - this.mouseoverAlertIndex = -1; } public void AlertsReadoutOnGUI() { - if (Event.current.type == EventType.Layout) - { - return; - } - if (this.activeAlerts.Count == 0) - { - return; - } - Alert alert = null; - AlertPriority alertPriority = AlertPriority.Critical; - bool flag = false; - float num = Find.LetterStack.LastTopY - (float)this.activeAlerts.Count * 28f; - Rect rect = new Rect((float)UI.screenWidth - 154f, num, 154f, this.lastFinalY - num); - float num2 = GenUI.BackgroundDarkAlphaForText(); - if (num2 > 0.001f) - { - GUI.color = new Color(1f, 1f, 1f, num2); - Widgets.DrawShadowAround(rect); - GUI.color = Color.white; - } - float num3 = num; - if (num3 < 0f) - { - num3 = 0f; - } - for (int i = 0; i < this.PriosInDrawOrder.Count; i++) + if (((Event.current.type != EventType.Layout) ? this.activeAlerts.Count : 0) != 0) { - AlertPriority alertPriority2 = this.PriosInDrawOrder[i]; - for (int j = 0; j < this.activeAlerts.Count; j++) + Alert alert = null; + AlertPriority alertPriority = AlertPriority.Critical; + bool flag = false; + float num = (float)(Find.LetterStack.LastTopY - (float)this.activeAlerts.Count * 28.0); + Rect rect = new Rect((float)((float)UI.screenWidth - 154.0), num, 154f, this.lastFinalY - num); + float num2 = GenUI.BackgroundDarkAlphaForText(); + if (num2 > 0.0010000000474974513) + { + GUI.color = new Color(1f, 1f, 1f, num2); + Widgets.DrawShadowAround(rect); + GUI.color = Color.white; + } + float num3 = num; + if (num3 < 0.0) + { + num3 = 0f; + } + for (int i = 0; i < this.PriosInDrawOrder.Count; i++) { - Alert alert2 = this.activeAlerts[j]; - if (alert2.Priority == alertPriority2) + AlertPriority alertPriority2 = this.PriosInDrawOrder[i]; + for (int j = 0; j < this.activeAlerts.Count; j++) { - if (!flag) - { - alertPriority = alertPriority2; - flag = true; - } - Rect rect2 = alert2.DrawAt(num3, alertPriority2 != alertPriority); - if (Mouse.IsOver(rect2)) + Alert alert2 = this.activeAlerts[j]; + if (alert2.Priority == alertPriority2) { - alert = alert2; - this.mouseoverAlertIndex = j; + if (!flag) + { + alertPriority = alertPriority2; + flag = true; + } + Rect rect2 = alert2.DrawAt(num3, alertPriority2 != alertPriority); + if (Mouse.IsOver(rect2)) + { + alert = alert2; + this.mouseoverAlertIndex = j; + } + num3 += rect2.height; } - num3 += rect2.height; } } - } - this.lastFinalY = num3; - UIHighlighter.HighlightOpportunity(rect, "Alerts"); - if (alert != null) - { - alert.DrawInfoPane(); - PlayerKnowledgeDatabase.KnowledgeDemonstrated(ConceptDefOf.Alerts, KnowledgeAmount.FrameDisplayed); + this.lastFinalY = num3; + UIHighlighter.HighlightOpportunity(rect, "Alerts"); + if (alert != null) + { + alert.DrawInfoPane(); + PlayerKnowledgeDatabase.KnowledgeDemonstrated(ConceptDefOf.Alerts, KnowledgeAmount.FrameDisplayed); + } } } } diff --git a/Assembly-CSharp/RimWorld/AllowedAreaMode.cs b/Assembly-CSharp/RimWorld/AllowedAreaMode.cs index 09a7b4ad7..b7fd425d3 100644 --- a/Assembly-CSharp/RimWorld/AllowedAreaMode.cs +++ b/Assembly-CSharp/RimWorld/AllowedAreaMode.cs @@ -1,11 +1,9 @@ -using System; - namespace RimWorld { public enum AllowedAreaMode : byte { Humanlike = 1, - Animal, - Any + Animal = 2, + Any = 3 } } diff --git a/Assembly-CSharp/RimWorld/AmmoContainer.cs b/Assembly-CSharp/RimWorld/AmmoContainer.cs index 813c81ee8..b65215d96 100644 --- a/Assembly-CSharp/RimWorld/AmmoContainer.cs +++ b/Assembly-CSharp/RimWorld/AmmoContainer.cs @@ -1,4 +1,3 @@ -using System; using Verse; namespace RimWorld @@ -20,7 +19,11 @@ public AmmoContainer(Verb verb) public bool HasAmmo() { - return !this.limitedAmmo || this.ammo > 0; + if (!this.limitedAmmo) + { + return true; + } + return this.ammo > 0; } public void ConsumeAmmo() diff --git a/Assembly-CSharp/RimWorld/AnimalBiomeRecord.cs b/Assembly-CSharp/RimWorld/AnimalBiomeRecord.cs index ea39c8413..52e823414 100644 --- a/Assembly-CSharp/RimWorld/AnimalBiomeRecord.cs +++ b/Assembly-CSharp/RimWorld/AnimalBiomeRecord.cs @@ -1,4 +1,3 @@ -using System; using System.Xml; using Verse; diff --git a/Assembly-CSharp/RimWorld/Antimissile.cs b/Assembly-CSharp/RimWorld/Antimissile.cs index 0c532edb5..cc2854caf 100644 --- a/Assembly-CSharp/RimWorld/Antimissile.cs +++ b/Assembly-CSharp/RimWorld/Antimissile.cs @@ -1,4 +1,3 @@ -using System; using UnityEngine; using Verse; @@ -10,8 +9,8 @@ public override Vector3 ExactPosition { get { - Vector3 b = (((Projectile)this.assignedTarget).ExactPosition - this.origin) * (1f - (float)this.ticksToImpact / (float)base.StartingTicksToImpact); - return this.origin + b + Vector3.up * this.def.Altitude; + Vector3 b = (((Projectile)base.assignedTarget).ExactPosition - base.origin) * (float)(1.0 - (float)base.ticksToImpact / (float)base.StartingTicksToImpact); + return base.origin + b + Vector3.up * base.def.Altitude; } } @@ -19,7 +18,7 @@ public override Quaternion ExactRotation { get { - return Quaternion.LookRotation(((Projectile)this.assignedTarget).ExactPosition - this.ExactPosition); + return Quaternion.LookRotation(((Projectile)base.assignedTarget).ExactPosition - this.ExactPosition); } } diff --git a/Assembly-CSharp/RimWorld/Apparel.cs b/Assembly-CSharp/RimWorld/Apparel.cs index 1011fc6ae..096134563 100644 --- a/Assembly-CSharp/RimWorld/Apparel.cs +++ b/Assembly-CSharp/RimWorld/Apparel.cs @@ -1,6 +1,4 @@ -using System; using System.Collections.Generic; -using System.Diagnostics; using Verse; namespace RimWorld @@ -28,7 +26,7 @@ public bool WornByCorpse public void Notify_PawnKilled() { - if (this.def.apparel.careIfWornByCorpse) + if (base.def.apparel.careIfWornByCorpse) { this.wornByCorpseInt = true; } @@ -54,13 +52,9 @@ public virtual bool AllowVerbCast(IntVec3 root, Map map, LocalTargetInfo targ) return true; } - [DebuggerHidden] public virtual IEnumerable GetWornGizmos() { - Apparel.c__Iterator15F c__Iterator15F = new Apparel.c__Iterator15F(); - Apparel.c__Iterator15F expr_07 = c__Iterator15F; - expr_07.$PC = -2; - return expr_07; + yield break; } public override string GetInspectString() diff --git a/Assembly-CSharp/RimWorld/ApparelGraphicRecord.cs b/Assembly-CSharp/RimWorld/ApparelGraphicRecord.cs index d3a77c52c..3cf6a2f38 100644 --- a/Assembly-CSharp/RimWorld/ApparelGraphicRecord.cs +++ b/Assembly-CSharp/RimWorld/ApparelGraphicRecord.cs @@ -1,4 +1,3 @@ -using System; using Verse; namespace RimWorld diff --git a/Assembly-CSharp/RimWorld/ApparelGraphicRecordGetter.cs b/Assembly-CSharp/RimWorld/ApparelGraphicRecordGetter.cs index 01aa7d82c..271d8d987 100644 --- a/Assembly-CSharp/RimWorld/ApparelGraphicRecordGetter.cs +++ b/Assembly-CSharp/RimWorld/ApparelGraphicRecordGetter.cs @@ -17,15 +17,7 @@ public static bool TryGetGraphicApparel(Apparel apparel, BodyType bodyType, out rec = new ApparelGraphicRecord(null, null); return false; } - string path; - if (apparel.def.apparel.LastLayer == ApparelLayer.Overhead) - { - path = apparel.def.apparel.wornGraphicPath; - } - else - { - path = apparel.def.apparel.wornGraphicPath + "_" + bodyType.ToString(); - } + string path = (apparel.def.apparel.LastLayer != ApparelLayer.Overhead) ? (apparel.def.apparel.wornGraphicPath + "_" + ((Enum)(object)bodyType).ToString()) : apparel.def.apparel.wornGraphicPath; Graphic graphic = GraphicDatabase.Get(path, ShaderDatabase.Cutout, apparel.def.graphicData.drawSize, apparel.DrawColor); rec = new ApparelGraphicRecord(graphic, apparel); return true; diff --git a/Assembly-CSharp/RimWorld/ApparelLayer.cs b/Assembly-CSharp/RimWorld/ApparelLayer.cs index 6737dd4ca..84cdf473f 100644 --- a/Assembly-CSharp/RimWorld/ApparelLayer.cs +++ b/Assembly-CSharp/RimWorld/ApparelLayer.cs @@ -1,13 +1,11 @@ -using System; - namespace RimWorld { public enum ApparelLayer : byte { - OnSkin, - Middle, - Shell, - Belt, - Overhead + OnSkin = 0, + Middle = 1, + Shell = 2, + Belt = 3, + Overhead = 4 } } diff --git a/Assembly-CSharp/RimWorld/ApparelProperties.cs b/Assembly-CSharp/RimWorld/ApparelProperties.cs index 8b0efc3e3..bbee42edd 100644 --- a/Assembly-CSharp/RimWorld/ApparelProperties.cs +++ b/Assembly-CSharp/RimWorld/ApparelProperties.cs @@ -1,6 +1,5 @@ using System; using System.Collections.Generic; -using System.Diagnostics; using System.Linq; using System.Text; using Verse; @@ -38,7 +37,7 @@ public float HumanBodyCoverage { get { - if (this.cachedHumanBodyCoverage < 0f) + if (this.cachedHumanBodyCoverage < 0.0) { this.cachedHumanBodyCoverage = 0f; List allParts = BodyDefOf.Human.AllParts; @@ -54,16 +53,12 @@ public float HumanBodyCoverage } } - [DebuggerHidden] public IEnumerable ConfigErrors(ThingDef parentDef) { - ApparelProperties.c__Iterator76 c__Iterator = new ApparelProperties.c__Iterator76(); - c__Iterator.parentDef = parentDef; - c__Iterator.<$>parentDef = parentDef; - c__Iterator.<>f__this = this; - ApparelProperties.c__Iterator76 expr_1C = c__Iterator; - expr_1C.$PC = -2; - return expr_1C; + if (this.layers.NullOrEmpty()) + { + yield return parentDef.defName + " apparel has no layers."; + } } public bool CoversBodyPart(BodyPartRecord partRec) @@ -81,18 +76,18 @@ public bool CoversBodyPart(BodyPartRecord partRec) public string GetCoveredOuterPartsString(BodyDef body) { IEnumerable source = from x in body.AllParts - where x.depth == BodyPartDepth.Outside && x.groups.Any((BodyPartGroupDef y) => this.bodyPartGroups.Contains(y)) + where x.depth == BodyPartDepth.Outside && x.groups.Any((Predicate)((BodyPartGroupDef y) => this.bodyPartGroups.Contains(y))) select x; StringBuilder stringBuilder = new StringBuilder(); bool flag = true; - foreach (BodyPartRecord current in source.Distinct()) + foreach (BodyPartRecord item in source.Distinct()) { if (!flag) { stringBuilder.Append(", "); } flag = false; - stringBuilder.Append(current.def.label); + stringBuilder.Append(item.def.label); } return stringBuilder.ToString().CapitalizeFirst(); } diff --git a/Assembly-CSharp/RimWorld/ApparelUtility.cs b/Assembly-CSharp/RimWorld/ApparelUtility.cs index e783878b2..21b4a248e 100644 --- a/Assembly-CSharp/RimWorld/ApparelUtility.cs +++ b/Assembly-CSharp/RimWorld/ApparelUtility.cs @@ -21,18 +21,18 @@ public LayerGroupPair(ApparelLayer layer, BodyPartGroupDef group) public override bool Equals(object rhs) { - if (!(rhs is ApparelUtility.LayerGroupPair)) + if (!(rhs is LayerGroupPair)) { return false; } - ApparelUtility.LayerGroupPair layerGroupPair = (ApparelUtility.LayerGroupPair)rhs; + LayerGroupPair layerGroupPair = (LayerGroupPair)rhs; return layerGroupPair.layer == this.layer && layerGroupPair.group == this.group; } public override int GetHashCode() { int num = 17; - num = num * 23 + this.layer.GetHashCode(); + num = num * 23 + ((Enum)(object)this.layer).GetHashCode(); return num * 23 + this.group.GetHashCode(); } } @@ -40,37 +40,43 @@ public override int GetHashCode() public static bool CanWearTogether(ThingDef A, ThingDef B) { bool flag = false; - for (int i = 0; i < A.apparel.layers.Count; i++) + int num = 0; + while (num < A.apparel.layers.Count) { - for (int j = 0; j < B.apparel.layers.Count; j++) + int num2 = 0; + while (num2 < B.apparel.layers.Count) { - if (A.apparel.layers[i] == B.apparel.layers[j]) + if (A.apparel.layers[num] == B.apparel.layers[num2]) { flag = true; } - if (flag) + if (!flag) { - break; + num2++; + continue; } + break; } - if (flag) + if (!flag) { - break; + num++; + continue; } + break; } if (!flag) { return true; } - for (int k = 0; k < A.apparel.bodyPartGroups.Count; k++) + for (int i = 0; i < A.apparel.bodyPartGroups.Count; i++) { - for (int l = 0; l < B.apparel.bodyPartGroups.Count; l++) + for (int j = 0; j < B.apparel.bodyPartGroups.Count; j++) { - BodyPartGroupDef item = A.apparel.bodyPartGroups[k]; - BodyPartGroupDef item2 = B.apparel.bodyPartGroups[l]; - for (int m = 0; m < BodyDefOf.Human.AllParts.Count; m++) + BodyPartGroupDef item = A.apparel.bodyPartGroups[i]; + BodyPartGroupDef item2 = B.apparel.bodyPartGroups[j]; + for (int k = 0; k < BodyDefOf.Human.AllParts.Count; k++) { - BodyPartRecord bodyPartRecord = BodyDefOf.Human.AllParts[m]; + BodyPartRecord bodyPartRecord = BodyDefOf.Human.AllParts[k]; if (bodyPartRecord.groups.Contains(item) && bodyPartRecord.groups.Contains(item2)) { return false; @@ -81,40 +87,42 @@ public static bool CanWearTogether(ThingDef A, ThingDef B) return true; } - public static void GenerateLayerGroupPairs(ThingDef td, Action callback) + public static void GenerateLayerGroupPairs(ThingDef td, Action callback) { for (int i = 0; i < td.apparel.layers.Count; i++) { for (int j = 0; j < td.apparel.bodyPartGroups.Count; j++) { - callback(new ApparelUtility.LayerGroupPair(td.apparel.layers[i], td.apparel.bodyPartGroups[j])); + callback(new LayerGroupPair(td.apparel.layers[i], td.apparel.bodyPartGroups[j])); } } } public static bool HasPartsToWear(Pawn p, ThingDef apparel) { - ApparelUtility.c__AnonStorey34F c__AnonStorey34F = new ApparelUtility.c__AnonStorey34F(); List hediffs = p.health.hediffSet.hediffs; bool flag = false; - for (int j = 0; j < hediffs.Count; j++) + int num = 0; + while (num < hediffs.Count) { - if (hediffs[j] is Hediff_MissingPart) + if (!(hediffs[num] is Hediff_MissingPart)) { - flag = true; - break; + num++; + continue; } + flag = true; + break; } if (!flag) { return true; } IEnumerable notMissingParts = p.health.hediffSet.GetNotMissingParts(BodyPartHeight.Undefined, BodyPartDepth.Undefined); - c__AnonStorey34F.groups = apparel.apparel.bodyPartGroups; + List groups = apparel.apparel.bodyPartGroups; int i; - for (i = 0; i < c__AnonStorey34F.groups.Count; i++) + for (i = 0; i < groups.Count; i++) { - if (notMissingParts.Any((BodyPartRecord x) => x.IsInGroup(c__AnonStorey34F.groups[i]))) + if (notMissingParts.Any((Func)((BodyPartRecord x) => x.IsInGroup(groups[i])))) { return true; } diff --git a/Assembly-CSharp/RimWorld/ArchitectCategoryTab.cs b/Assembly-CSharp/RimWorld/ArchitectCategoryTab.cs index 477a4b9f3..057140efe 100644 --- a/Assembly-CSharp/RimWorld/ArchitectCategoryTab.cs +++ b/Assembly-CSharp/RimWorld/ArchitectCategoryTab.cs @@ -15,7 +15,7 @@ public static Rect InfoRect { get { - return new Rect(0f, (float)(UI.screenHeight - 35) - ((MainTabWindow_Architect)MainButtonDefOf.Architect.TabWindow).WinHeight - 230f, 200f, 230f); + return new Rect(0f, (float)((float)(UI.screenHeight - 35) - ((MainTabWindow_Architect)MainButtonDefOf.Architect.TabWindow).WinHeight - 230.0), 200f, 230f); } } @@ -33,10 +33,10 @@ public void DesignationTabOnGUI() { if (Find.DesignatorManager.SelectedDesignator != null) { - Find.DesignatorManager.SelectedDesignator.DoExtraGuiControls(0f, (float)(UI.screenHeight - 35) - ((MainTabWindow_Architect)MainButtonDefOf.Architect.TabWindow).WinHeight - 230f); + Find.DesignatorManager.SelectedDesignator.DoExtraGuiControls(0f, (float)((float)(UI.screenHeight - 35) - ((MainTabWindow_Architect)MainButtonDefOf.Architect.TabWindow).WinHeight - 230.0)); } float startX = 210f; - Gizmo selectedDesignator; + Gizmo selectedDesignator = default(Gizmo); GizmoGridDrawer.DrawGizmoGrid(this.def.ResolvedAllowedDesignators.Cast(), startX, out selectedDesignator); if (selectedDesignator == null && Find.DesignatorManager.SelectedDesignator != null) { @@ -47,7 +47,7 @@ public void DesignationTabOnGUI() protected void DoInfoBox(Rect infoRect, Designator designator) { - Find.WindowStack.ImmediateWindow(32520, infoRect, WindowLayer.GameUI, delegate + Find.WindowStack.ImmediateWindow(32520, infoRect, WindowLayer.GameUI, (Action)delegate() { if (designator != null) { diff --git a/Assembly-CSharp/RimWorld/AreaAllowedGUI.cs b/Assembly-CSharp/RimWorld/AreaAllowedGUI.cs index 4ce3ac9d4..404717ef3 100644 --- a/Assembly-CSharp/RimWorld/AreaAllowedGUI.cs +++ b/Assembly-CSharp/RimWorld/AreaAllowedGUI.cs @@ -1,4 +1,3 @@ -using System; using System.Collections.Generic; using UnityEngine; using Verse; @@ -10,37 +9,36 @@ public static class AreaAllowedGUI { public static void DoAllowedAreaSelectors(Rect rect, Pawn p, AllowedAreaMode mode) { - if (Find.VisibleMap == null) + if (Find.VisibleMap != null) { - return; - } - List allAreas = Find.VisibleMap.areaManager.AllAreas; - int num = 1; - for (int i = 0; i < allAreas.Count; i++) - { - if (allAreas[i].AssignableAsAllowed(mode)) + List allAreas = Find.VisibleMap.areaManager.AllAreas; + int num = 1; + for (int i = 0; i < allAreas.Count; i++) { - num++; + if (allAreas[i].AssignableAsAllowed(mode)) + { + num++; + } } - } - float num2 = rect.width / (float)num; - Text.WordWrap = false; - Text.Font = GameFont.Tiny; - Rect rect2 = new Rect(rect.x, rect.y, num2, rect.height); - AreaAllowedGUI.DoAreaSelector(rect2, p, null); - int num3 = 1; - for (int j = 0; j < allAreas.Count; j++) - { - if (allAreas[j].AssignableAsAllowed(mode)) + float num2 = rect.width / (float)num; + Text.WordWrap = false; + Text.Font = GameFont.Tiny; + Rect rect2 = new Rect(rect.x, rect.y, num2, rect.height); + AreaAllowedGUI.DoAreaSelector(rect2, p, null); + int num3 = 1; + for (int j = 0; j < allAreas.Count; j++) { - float num4 = (float)num3 * num2; - Rect rect3 = new Rect(rect.x + num4, rect.y, num2, rect.height); - AreaAllowedGUI.DoAreaSelector(rect3, p, allAreas[j]); - num3++; + if (allAreas[j].AssignableAsAllowed(mode)) + { + float num4 = (float)num3 * num2; + Rect rect3 = new Rect(rect.x + num4, rect.y, num2, rect.height); + AreaAllowedGUI.DoAreaSelector(rect3, p, allAreas[j]); + num3++; + } } + Text.WordWrap = true; + Text.Font = GameFont.Small; } - Text.WordWrap = true; - Text.Font = GameFont.Small; } private static void DoAreaSelector(Rect rect, Pawn p, Area area) diff --git a/Assembly-CSharp/RimWorld/Area_Allowed.cs b/Assembly-CSharp/RimWorld/Area_Allowed.cs index fa8911c5a..acb477858 100644 --- a/Assembly-CSharp/RimWorld/Area_Allowed.cs +++ b/Assembly-CSharp/RimWorld/Area_Allowed.cs @@ -1,4 +1,3 @@ -using System; using UnityEngine; using Verse; @@ -62,7 +61,7 @@ public Area_Allowed() public Area_Allowed(AreaManager areaManager, AllowedAreaMode mode, string label = null) : base(areaManager) { - this.areaManager = areaManager; + base.areaManager = areaManager; this.mode = mode; if (!label.NullOrEmpty()) { @@ -75,23 +74,18 @@ public Area_Allowed(AreaManager areaManager, AllowedAreaMode mode, string label { if (mode == AllowedAreaMode.Animal) { - this.labelInt = "AreaAnimalDefaultLabel".Translate(new object[] - { - num - }); + this.labelInt = "AreaAnimalDefaultLabel".Translate(num); } else { - this.labelInt = "AreaDefaultLabel".Translate(new object[] - { - num - }); + this.labelInt = "AreaDefaultLabel".Translate(num); } - if (areaManager.GetLabeled(this.labelInt) == null) + if (areaManager.GetLabeled(this.labelInt) != null) { - break; + num++; + continue; } - num++; + break; } } this.colorInt = new Color(Rand.Value, Rand.Value, Rand.Value); @@ -101,14 +95,14 @@ public Area_Allowed(AreaManager areaManager, AllowedAreaMode mode, string label public override void ExposeData() { base.ExposeData(); - Scribe_Values.Look(ref this.labelInt, "label", null, false); + Scribe_Values.Look(ref this.labelInt, "label", (string)null, false); Scribe_Values.Look(ref this.colorInt, "color", default(Color), false); Scribe_Values.Look(ref this.mode, "mode", (AllowedAreaMode)0, false); } public override bool AssignableAsAllowed(AllowedAreaMode mode) { - return (byte)(mode & this.mode) != 0; + return (mode & this.mode) != (AllowedAreaMode)0; } public override void SetLabel(string label) @@ -118,13 +112,7 @@ public override void SetLabel(string label) public override string GetUniqueLoadID() { - return string.Concat(new object[] - { - "Area_", - this.ID, - "_Named_", - this.labelInt - }); + return "Area_" + base.ID + "_Named_" + this.labelInt; } public override string ToString() diff --git a/Assembly-CSharp/RimWorld/Area_BuildRoof.cs b/Assembly-CSharp/RimWorld/Area_BuildRoof.cs index c154104b4..fe609ba63 100644 --- a/Assembly-CSharp/RimWorld/Area_BuildRoof.cs +++ b/Assembly-CSharp/RimWorld/Area_BuildRoof.cs @@ -1,4 +1,3 @@ -using System; using UnityEngine; using Verse; @@ -40,7 +39,7 @@ public Area_BuildRoof(AreaManager areaManager) : base(areaManager) public override string GetUniqueLoadID() { - return "Area_" + this.ID + "_BuildRoof"; + return "Area_" + base.ID + "_BuildRoof"; } } } diff --git a/Assembly-CSharp/RimWorld/Area_Home.cs b/Assembly-CSharp/RimWorld/Area_Home.cs index 7d11b4a19..44d6b7f24 100644 --- a/Assembly-CSharp/RimWorld/Area_Home.cs +++ b/Assembly-CSharp/RimWorld/Area_Home.cs @@ -1,4 +1,3 @@ -using System; using UnityEngine; using Verse; @@ -40,22 +39,21 @@ public Area_Home(AreaManager areaManager) : base(areaManager) public override bool AssignableAsAllowed(AllowedAreaMode mode) { - return (byte)(mode & AllowedAreaMode.Any) != 0; + return (byte)((int)mode & 3) != 0; } public override string GetUniqueLoadID() { - return "Area_" + this.ID + "_Home"; + return "Area_" + base.ID + "_Home"; } protected override void Set(IntVec3 c, bool val) { - if (base[c] == val) + if (base[c] != val) { - return; + base.Set(c, val); + base.Map.listerFilthInHomeArea.Notify_HomeAreaChanged(c); } - base.Set(c, val); - base.Map.listerFilthInHomeArea.Notify_HomeAreaChanged(c); } } } diff --git a/Assembly-CSharp/RimWorld/Area_NoRoof.cs b/Assembly-CSharp/RimWorld/Area_NoRoof.cs index a1f67923a..a2a311d66 100644 --- a/Assembly-CSharp/RimWorld/Area_NoRoof.cs +++ b/Assembly-CSharp/RimWorld/Area_NoRoof.cs @@ -1,4 +1,3 @@ -using System; using UnityEngine; using Verse; @@ -40,7 +39,7 @@ public Area_NoRoof(AreaManager areaManager) : base(areaManager) public override string GetUniqueLoadID() { - return "Area_" + this.ID + "_NoRoof"; + return "Area_" + base.ID + "_NoRoof"; } } } diff --git a/Assembly-CSharp/RimWorld/Area_SnowClear.cs b/Assembly-CSharp/RimWorld/Area_SnowClear.cs index af2079b7c..335e1e37e 100644 --- a/Assembly-CSharp/RimWorld/Area_SnowClear.cs +++ b/Assembly-CSharp/RimWorld/Area_SnowClear.cs @@ -1,4 +1,3 @@ -using System; using UnityEngine; using Verse; @@ -40,7 +39,7 @@ public Area_SnowClear(AreaManager areaManager) : base(areaManager) public override string GetUniqueLoadID() { - return "Area_" + this.ID + "_SnowClear"; + return "Area_" + base.ID + "_SnowClear"; } } } diff --git a/Assembly-CSharp/RimWorld/ArtGenerationContext.cs b/Assembly-CSharp/RimWorld/ArtGenerationContext.cs index 1e126c7e0..eb467ad3c 100644 --- a/Assembly-CSharp/RimWorld/ArtGenerationContext.cs +++ b/Assembly-CSharp/RimWorld/ArtGenerationContext.cs @@ -1,10 +1,8 @@ -using System; - namespace RimWorld { public enum ArtGenerationContext : byte { - Outsider, - Colony + Outsider = 0, + Colony = 1 } } diff --git a/Assembly-CSharp/RimWorld/AutoHomeAreaMaker.cs b/Assembly-CSharp/RimWorld/AutoHomeAreaMaker.cs index 759dcffcc..f5ff4094e 100644 --- a/Assembly-CSharp/RimWorld/AutoHomeAreaMaker.cs +++ b/Assembly-CSharp/RimWorld/AutoHomeAreaMaker.cs @@ -1,4 +1,3 @@ -using System; using Verse; namespace RimWorld @@ -14,29 +13,38 @@ private static bool ShouldAdd() public static void Notify_BuildingSpawned(Thing b) { - if (!AutoHomeAreaMaker.ShouldAdd() || !b.def.building.expandHomeArea || b.Faction != Faction.OfPlayer) + if (AutoHomeAreaMaker.ShouldAdd() && b.def.building.expandHomeArea && b.Faction == Faction.OfPlayer) { - return; - } - CellRect cellRect = new CellRect(b.Position.x - b.RotatedSize.x / 2 - 4, b.Position.z - b.RotatedSize.z / 2 - 4, b.RotatedSize.x + 8, b.RotatedSize.z + 8); - cellRect.ClipInsideMap(b.Map); - foreach (IntVec3 current in cellRect) - { - b.Map.areaManager.Home[current] = true; + IntVec3 position = b.Position; + int x = position.x; + IntVec2 rotatedSize = b.RotatedSize; + int minX = x - rotatedSize.x / 2 - 4; + IntVec3 position2 = b.Position; + int z = position2.z; + IntVec2 rotatedSize2 = b.RotatedSize; + int minZ = z - rotatedSize2.z / 2 - 4; + IntVec2 rotatedSize3 = b.RotatedSize; + int width = rotatedSize3.x + 8; + IntVec2 rotatedSize4 = b.RotatedSize; + CellRect cellRect = new CellRect(minX, minZ, width, rotatedSize4.z + 8); + cellRect.ClipInsideMap(b.Map); + foreach (IntVec3 item in cellRect) + { + ((Area)b.Map.areaManager.Home)[item] = true; + } } } public static void Notify_ZoneCellAdded(IntVec3 c, Zone zone) { - if (!AutoHomeAreaMaker.ShouldAdd()) - { - return; - } - CellRect.CellRectIterator iterator = CellRect.CenteredOn(c, 4).ClipInsideMap(zone.Map).GetIterator(); - while (!iterator.Done()) + if (AutoHomeAreaMaker.ShouldAdd()) { - zone.Map.areaManager.Home[iterator.Current] = true; - iterator.MoveNext(); + CellRect.CellRectIterator iterator = CellRect.CenteredOn(c, 4).ClipInsideMap(zone.Map).GetIterator(); + while (!iterator.Done()) + { + ((Area)zone.Map.areaManager.Home)[iterator.Current] = true; + iterator.MoveNext(); + } } } } diff --git a/Assembly-CSharp/RimWorld/AutoUndrafter.cs b/Assembly-CSharp/RimWorld/AutoUndrafter.cs index d9391acad..1621c26e1 100644 --- a/Assembly-CSharp/RimWorld/AutoUndrafter.cs +++ b/Assembly-CSharp/RimWorld/AutoUndrafter.cs @@ -51,7 +51,11 @@ private bool ShouldAutoUndraft() { return false; } - return !this.pawn.Map.attackTargetsCache.GetPotentialTargetsFor(this.pawn).Any((IAttackTarget x) => !x.ThreatDisabled()); + if (this.pawn.Map.attackTargetsCache.GetPotentialTargetsFor(this.pawn).Any((Predicate)((IAttackTarget x) => !x.ThreatDisabled()))) + { + return false; + } + return true; } } } diff --git a/Assembly-CSharp/RimWorld/Autosaver.cs b/Assembly-CSharp/RimWorld/Autosaver.cs index b12843c04..7747e0d78 100644 --- a/Assembly-CSharp/RimWorld/Autosaver.cs +++ b/Assembly-CSharp/RimWorld/Autosaver.cs @@ -1,6 +1,5 @@ using System; using System.Collections.Generic; -using System.Diagnostics; using System.IO; using System.Linq; using UnityEngine; @@ -22,7 +21,7 @@ private float AutosaveIntervalDays get { float num = Prefs.AutosaveIntervalDays; - if (Current.Game.Info.permadeathMode && num > 1f) + if (Current.Game.Info.permadeathMode && num > 1.0) { num = 1f; } @@ -34,7 +33,7 @@ private int AutosaveIntervalTicks { get { - return Mathf.RoundToInt(this.AutosaveIntervalDays * 60000f); + return Mathf.RoundToInt((float)(this.AutosaveIntervalDays * 60000.0)); } } @@ -51,15 +50,7 @@ public void AutosaverTick() private void DoAutosave() { ProfilerThreadCheck.BeginSample("DoAutosave"); - string fileName; - if (Current.Game.Info.permadeathMode) - { - fileName = Current.Game.Info.permadeathModeUniqueName; - } - else - { - fileName = this.NewAutosaveFileName(); - } + string fileName = (!Current.Game.Info.permadeathMode) ? this.NewAutosaveFileName() : Current.Game.Info.permadeathModeUniqueName; GameDataSaveLoader.SaveGame(fileName); ProfilerThreadCheck.EndSample(); } @@ -73,21 +64,20 @@ private string NewAutosaveFileName() { string text = (from name in this.AutoSaveNames() where !SaveGameFilesUtility.SavedGameNamedExists(name) - select name).FirstOrDefault(); + select name).FirstOrDefault(); if (text != null) { return text; } - return this.AutoSaveNames().MinBy((string name) => new FileInfo(GenFilePaths.FilePathForSavedGame(name)).LastWriteTime); + return this.AutoSaveNames().MinBy((Func)((string name) => new FileInfo(GenFilePaths.FilePathForSavedGame(name)).LastWriteTime)); } - [DebuggerHidden] private IEnumerable AutoSaveNames() { - Autosaver.c__Iterator1A7 c__Iterator1A = new Autosaver.c__Iterator1A7(); - Autosaver.c__Iterator1A7 expr_07 = c__Iterator1A; - expr_07.$PC = -2; - return expr_07; + for (int i = 1; i <= 5; i++) + { + yield return "Autosave-" + i; + } } } } diff --git a/Assembly-CSharp/RimWorld/Autotests_ColonyMaker.cs b/Assembly-CSharp/RimWorld/Autotests_ColonyMaker.cs index ecc5bd42f..da76466e7 100644 --- a/Assembly-CSharp/RimWorld/Autotests_ColonyMaker.cs +++ b/Assembly-CSharp/RimWorld/Autotests_ColonyMaker.cs @@ -1,5 +1,4 @@ using System; -using System.Collections; using System.Collections.Generic; using System.Linq; using UnityEngine; @@ -25,29 +24,12 @@ private static Map Map public static void MakeColony_Full() { - Autotests_ColonyMaker.MakeColony(new ColonyMakerFlag[] - { - ColonyMakerFlag.ConduitGrid, - ColonyMakerFlag.PowerPlants, - ColonyMakerFlag.Batteries, - ColonyMakerFlag.WorkTables, - ColonyMakerFlag.AllBuildings, - ColonyMakerFlag.AllItems, - ColonyMakerFlag.Filth, - ColonyMakerFlag.ColonistsMany, - ColonyMakerFlag.ColonistsHungry, - ColonyMakerFlag.ColonistsTired, - ColonyMakerFlag.ColonistsInjured, - ColonyMakerFlag.ColonistsDiseased, - ColonyMakerFlag.Beds, - ColonyMakerFlag.Stockpiles, - ColonyMakerFlag.GrowingZones - }); + Autotests_ColonyMaker.MakeColony(ColonyMakerFlag.ConduitGrid, ColonyMakerFlag.PowerPlants, ColonyMakerFlag.Batteries, ColonyMakerFlag.WorkTables, ColonyMakerFlag.AllBuildings, ColonyMakerFlag.AllItems, ColonyMakerFlag.Filth, ColonyMakerFlag.ColonistsMany, ColonyMakerFlag.ColonistsHungry, ColonyMakerFlag.ColonistsTired, ColonyMakerFlag.ColonistsInjured, ColonyMakerFlag.ColonistsDiseased, ColonyMakerFlag.Beds, ColonyMakerFlag.Stockpiles, ColonyMakerFlag.GrowingZones); } public static void MakeColony_Animals() { - Autotests_ColonyMaker.MakeColony(new ColonyMakerFlag[1]); + Autotests_ColonyMaker.MakeColony(default(ColonyMakerFlag)); } public static void MakeColony(params ColonyMakerFlag[] flags) @@ -63,43 +45,47 @@ public static void MakeColony(params ColonyMakerFlag[] flags) { Autotests_ColonyMaker.usedCells.ClearAndResizeTo(Autotests_ColonyMaker.Map); } - Autotests_ColonyMaker.overRect = new CellRect(Autotests_ColonyMaker.Map.Center.x - 50, Autotests_ColonyMaker.Map.Center.z - 50, 100, 100); + IntVec3 center = Autotests_ColonyMaker.Map.Center; + int minX = center.x - 50; + IntVec3 center2 = Autotests_ColonyMaker.Map.Center; + Autotests_ColonyMaker.overRect = new CellRect(minX, center2.z - 50, 100, 100); Autotests_ColonyMaker.DeleteAllSpawnedPawns(); GenDebug.ClearArea(Autotests_ColonyMaker.overRect, Find.VisibleMap); if (flags.Contains(ColonyMakerFlag.Animals)) { - foreach (PawnKindDef current in from k in DefDatabase.AllDefs + foreach (PawnKindDef item in from k in DefDatabase.AllDefs where k.RaceProps.Animal select k) { - CellRect cellRect; - if (!Autotests_ColonyMaker.TryGetFreeRect(6, 3, out cellRect)) + CellRect cellRect = default(CellRect); + if (Autotests_ColonyMaker.TryGetFreeRect(6, 3, out cellRect)) { - return; - } - cellRect = cellRect.ContractedBy(1); - foreach (IntVec3 current2 in cellRect) - { - Autotests_ColonyMaker.Map.terrainGrid.SetTerrain(current2, TerrainDefOf.Concrete); - } - GenSpawn.Spawn(PawnGenerator.GeneratePawn(current, null), cellRect.Cells.ElementAt(0), Autotests_ColonyMaker.Map); - IntVec3 intVec = cellRect.Cells.ElementAt(1); - Pawn p = (Pawn)GenSpawn.Spawn(PawnGenerator.GeneratePawn(current, null), intVec, Autotests_ColonyMaker.Map); - HealthUtility.DamageUntilDead(p); - Corpse thing = (Corpse)intVec.GetThingList(Find.VisibleMap).First((Thing t) => t is Corpse); - CompRottable compRottable = thing.TryGetComp(); - if (compRottable != null) - { - compRottable.RotProgress += 1200000f; - } - if (current.RaceProps.leatherDef != null) - { - GenSpawn.Spawn(current.RaceProps.leatherDef, cellRect.Cells.ElementAt(2), Autotests_ColonyMaker.Map); - } - if (current.RaceProps.meatDef != null) - { - GenSpawn.Spawn(current.RaceProps.meatDef, cellRect.Cells.ElementAt(3), Autotests_ColonyMaker.Map); + cellRect = cellRect.ContractedBy(1); + foreach (IntVec3 item2 in cellRect) + { + Autotests_ColonyMaker.Map.terrainGrid.SetTerrain(item2, TerrainDefOf.Concrete); + } + GenSpawn.Spawn(PawnGenerator.GeneratePawn(item, null), cellRect.Cells.ElementAt(0), Autotests_ColonyMaker.Map); + IntVec3 intVec = cellRect.Cells.ElementAt(1); + Pawn p = (Pawn)GenSpawn.Spawn(PawnGenerator.GeneratePawn(item, null), intVec, Autotests_ColonyMaker.Map); + HealthUtility.DamageUntilDead(p); + Corpse thing = (Corpse)intVec.GetThingList(Find.VisibleMap).First((Func)((Thing t) => t is Corpse)); + CompRottable compRottable = thing.TryGetComp(); + if (compRottable != null) + { + compRottable.RotProgress += 1200000f; + } + if (item.RaceProps.leatherDef != null) + { + GenSpawn.Spawn(item.RaceProps.leatherDef, cellRect.Cells.ElementAt(2), Autotests_ColonyMaker.Map); + } + if (item.RaceProps.meatDef != null) + { + GenSpawn.Spawn(item.RaceProps.meatDef, cellRect.Cells.ElementAt(3), Autotests_ColonyMaker.Map); + } + continue; } + return; } } if (flags.Contains(ColonyMakerFlag.ConduitGrid)) @@ -107,38 +93,40 @@ where k.RaceProps.Animal Designator_Build designator_Build = new Designator_Build(ThingDefOf.PowerConduit); for (int i = Autotests_ColonyMaker.overRect.minX; i < Autotests_ColonyMaker.overRect.maxX; i++) { - for (int j = Autotests_ColonyMaker.overRect.minZ; j < Autotests_ColonyMaker.overRect.maxZ; j += 7) + for (int num = Autotests_ColonyMaker.overRect.minZ; num < Autotests_ColonyMaker.overRect.maxZ; num += 7) { - designator_Build.DesignateSingleCell(new IntVec3(i, 0, j)); + designator_Build.DesignateSingleCell(new IntVec3(i, 0, num)); } } - for (int k2 = Autotests_ColonyMaker.overRect.minZ; k2 < Autotests_ColonyMaker.overRect.maxZ; k2++) + for (int j = Autotests_ColonyMaker.overRect.minZ; j < Autotests_ColonyMaker.overRect.maxZ; j++) { - for (int l = Autotests_ColonyMaker.overRect.minX; l < Autotests_ColonyMaker.overRect.maxX; l += 7) + for (int num2 = Autotests_ColonyMaker.overRect.minX; num2 < Autotests_ColonyMaker.overRect.maxX; num2 += 7) { - designator_Build.DesignateSingleCell(new IntVec3(l, 0, k2)); + designator_Build.DesignateSingleCell(new IntVec3(num2, 0, j)); } } } if (flags.Contains(ColonyMakerFlag.PowerPlants)) { - List list = new List + List list = new List(); + list.Add(ThingDefOf.SolarGenerator); + list.Add(ThingDefOf.WindTurbine); + List list2 = list; + int num3 = 0; + while (num3 < 8) { - ThingDefOf.SolarGenerator, - ThingDefOf.WindTurbine - }; - for (int m = 0; m < 8; m++) - { - if (Autotests_ColonyMaker.TryMakeBuilding(list[m % list.Count]) == null) + if (Autotests_ColonyMaker.TryMakeBuilding(list2[num3 % list2.Count]) != null) { - Log.Message("Could not make solar generator."); - break; + num3++; + continue; } + Log.Message("Could not make solar generator."); + break; } } if (flags.Contains(ColonyMakerFlag.Batteries)) { - for (int n = 0; n < 6; n++) + for (int l = 0; l < 6; l++) { Thing thing2 = Autotests_ColonyMaker.TryMakeBuilding(ThingDefOf.Battery); if (thing2 == null) @@ -154,20 +142,29 @@ where k.RaceProps.Animal IEnumerable enumerable = from def in DefDatabase.AllDefs where typeof(Building_WorkTable).IsAssignableFrom(def.thingClass) select def; - foreach (ThingDef current3 in enumerable) + foreach (ThingDef item3 in enumerable) { - Thing thing3 = Autotests_ColonyMaker.TryMakeBuilding(current3); + Thing thing3 = Autotests_ColonyMaker.TryMakeBuilding(item3); if (thing3 == null) { - Log.Message("Could not make worktable: " + current3.defName); + Log.Message("Could not make worktable: " + item3.defName); break; } Building_WorkTable building_WorkTable = thing3 as Building_WorkTable; if (building_WorkTable != null) { - foreach (RecipeDef current4 in building_WorkTable.def.AllRecipes) + List.Enumerator enumerator4 = building_WorkTable.def.AllRecipes.GetEnumerator(); + try + { + while (enumerator4.MoveNext()) + { + RecipeDef current4 = enumerator4.Current; + building_WorkTable.billStack.AddBill(current4.MakeNewBill()); + } + } + finally { - building_WorkTable.billStack.AddBill(current4.MakeNewBill()); + ((IDisposable)(object)enumerator4).Dispose(); } } } @@ -177,19 +174,20 @@ where typeof(Building_WorkTable).IsAssignableFrom(def.thingClass) IEnumerable enumerable2 = from def in DefDatabase.AllDefs where def.category == ThingCategory.Building && def.designationCategory != null select def; - foreach (ThingDef current5 in enumerable2) + foreach (ThingDef item4 in enumerable2) { - if (current5 != ThingDefOf.PowerConduit) + if (item4 != ThingDefOf.PowerConduit) { - if (Autotests_ColonyMaker.TryMakeBuilding(current5) == null) + Thing thing4 = Autotests_ColonyMaker.TryMakeBuilding(item4); + if (thing4 == null) { - Log.Message("Could not make building: " + current5.defName); + Log.Message("Could not make building: " + item4.defName); break; } } } } - CellRect rect; + CellRect rect = default(CellRect); if (!Autotests_ColonyMaker.TryGetFreeRect(33, 33, out rect)) { Log.Error("Could not get wallable rect"); @@ -199,20 +197,20 @@ where typeof(Building_WorkTable).IsAssignableFrom(def.thingClass) { List itemDefs = (from def in DefDatabase.AllDefs where DebugThingPlaceHelper.IsDebugSpawnable(def) && def.category == ThingCategory.Item - select def).ToList(); + select def).ToList(); Autotests_ColonyMaker.FillWithItems(rect, itemDefs); } else if (flags.Contains(ColonyMakerFlag.ItemsRawFood)) { - List list2 = new List(); - list2.Add(ThingDefOf.RawPotatoes); - Autotests_ColonyMaker.FillWithItems(rect, list2); + List list3 = new List(); + list3.Add(ThingDefOf.RawPotatoes); + Autotests_ColonyMaker.FillWithItems(rect, list3); } if (flags.Contains(ColonyMakerFlag.Filth)) { - foreach (IntVec3 current6 in rect) + foreach (IntVec3 item5 in rect) { - GenSpawn.Spawn(ThingDefOf.FilthDirt, current6, Autotests_ColonyMaker.Map); + GenSpawn.Spawn(ThingDefOf.FilthDirt, item5, Autotests_ColonyMaker.Map); } } if (flags.Contains(ColonyMakerFlag.ItemsWall)) @@ -220,9 +218,9 @@ where DebugThingPlaceHelper.IsDebugSpawnable(def) && def.category == ThingCatego CellRect cellRect2 = rect.ExpandedBy(1); Designator_Build designator_Build2 = new Designator_Build(ThingDefOf.Wall); designator_Build2.SetStuffDef(ThingDefOf.WoodLog); - foreach (IntVec3 current7 in cellRect2.EdgeCells) + foreach (IntVec3 edgeCell in cellRect2.EdgeCells) { - designator_Build2.DesignateSingleCell(current7); + designator_Build2.DesignateSingleCell(edgeCell); } } if (flags.Contains(ColonyMakerFlag.ColonistsMany)) @@ -235,18 +233,19 @@ where DebugThingPlaceHelper.IsDebugSpawnable(def) && def.category == ThingCatego } if (flags.Contains(ColonyMakerFlag.Fire)) { - CellRect cellRect3; + CellRect cellRect3 = default(CellRect); if (!Autotests_ColonyMaker.TryGetFreeRect(30, 30, out cellRect3)) { Log.Error("Could not get free rect for fire."); } ThingDef plantTreeOak = ThingDefOf.PlantTreeOak; - foreach (IntVec3 current8 in cellRect3) + foreach (IntVec3 item6 in cellRect3) { - GenSpawn.Spawn(plantTreeOak, current8, Autotests_ColonyMaker.Map); + GenSpawn.Spawn(plantTreeOak, item6, Autotests_ColonyMaker.Map); } - foreach (IntVec3 current9 in cellRect3) + foreach (IntVec3 item7 in cellRect3) { + IntVec3 current9 = item7; if (current9.x % 7 == 0 && current9.z % 7 == 0) { GenExplosion.DoExplosion(current9, Find.VisibleMap, 3.9f, DamageDefOf.Flame, null, null, null, null, null, 0f, 1, false, null, 0f, 1); @@ -255,39 +254,39 @@ where DebugThingPlaceHelper.IsDebugSpawnable(def) && def.category == ThingCatego } if (flags.Contains(ColonyMakerFlag.ColonistsHungry)) { - Autotests_ColonyMaker.DoToColonists(0.4f, delegate(Pawn col) + Autotests_ColonyMaker.DoToColonists(0.4f, (Action)delegate(Pawn col) { col.needs.food.CurLevel = Mathf.Max(0f, Rand.Range(-0.05f, 0.05f)); }); } if (flags.Contains(ColonyMakerFlag.ColonistsTired)) { - Autotests_ColonyMaker.DoToColonists(0.4f, delegate(Pawn col) + Autotests_ColonyMaker.DoToColonists(0.4f, (Action)delegate(Pawn col) { col.needs.rest.CurLevel = Mathf.Max(0f, Rand.Range(-0.05f, 0.05f)); }); } if (flags.Contains(ColonyMakerFlag.ColonistsInjured)) { - Autotests_ColonyMaker.DoToColonists(0.4f, delegate(Pawn col) + Autotests_ColonyMaker.DoToColonists(0.4f, (Action)delegate(Pawn col) { - DamageDef def = (from d in DefDatabase.AllDefs + DamageDef def2 = (from d in DefDatabase.AllDefs where d.externalViolence - select d).RandomElement(); - col.TakeDamage(new DamageInfo(def, 10, -1f, null, null, null, DamageInfo.SourceCategory.ThingOrUnknown)); + select d).RandomElement(); + col.TakeDamage(new DamageInfo(def2, 10, -1f, null, null, null, DamageInfo.SourceCategory.ThingOrUnknown)); }); } if (flags.Contains(ColonyMakerFlag.ColonistsDiseased)) { - foreach (HediffDef current10 in from d in DefDatabase.AllDefs + foreach (HediffDef item8 in from d in DefDatabase.AllDefs where d.hediffClass != typeof(Hediff_AddedPart) && (d.HasComp(typeof(HediffComp_Immunizable)) || d.HasComp(typeof(HediffComp_GrowthMode))) select d) { Pawn pawn = PawnGenerator.GeneratePawn(Faction.OfPlayer.def.basicMemberKind, Faction.OfPlayer); - CellRect cellRect4; + CellRect cellRect4 = default(CellRect); Autotests_ColonyMaker.TryGetFreeRect(1, 1, out cellRect4); GenSpawn.Spawn(pawn, cellRect4.CenterCell, Autotests_ColonyMaker.Map); - pawn.health.AddHediff(current10, null, null); + pawn.health.AddHediff(item8, null, default(DamageInfo?)); } } if (flags.Contains(ColonyMakerFlag.Beds)) @@ -296,53 +295,52 @@ where d.externalViolence where def.thingClass == typeof(Building_Bed) select def; int freeColonistsCount = Autotests_ColonyMaker.Map.mapPawns.FreeColonistsCount; - for (int num = 0; num < freeColonistsCount; num++) + int num4 = 0; + while (num4 < freeColonistsCount) { - if (Autotests_ColonyMaker.TryMakeBuilding(source.RandomElement()) == null) + if (Autotests_ColonyMaker.TryMakeBuilding(source.RandomElement()) != null) { - Log.Message("Could not make beds."); - break; + num4++; + continue; } + Log.Message("Could not make beds."); + break; } } if (flags.Contains(ColonyMakerFlag.Stockpiles)) { Designator_ZoneAddStockpile_Resources designator_ZoneAddStockpile_Resources = new Designator_ZoneAddStockpile_Resources(); - using (IEnumerator enumerator11 = Enum.GetValues(typeof(StoragePriority)).GetEnumerator()) + foreach (byte value in Enum.GetValues(typeof(StoragePriority))) { - while (enumerator11.MoveNext()) - { - StoragePriority priority = (StoragePriority)((byte)enumerator11.Current); - CellRect cellRect5; - Autotests_ColonyMaker.TryGetFreeRect(7, 7, out cellRect5); - cellRect5 = cellRect5.ContractedBy(1); - designator_ZoneAddStockpile_Resources.DesignateMultiCell(cellRect5.Cells); - Zone_Stockpile zone_Stockpile = (Zone_Stockpile)Autotests_ColonyMaker.Map.zoneManager.ZoneAt(cellRect5.CenterCell); - zone_Stockpile.settings.Priority = priority; - } + CellRect cellRect5 = default(CellRect); + Autotests_ColonyMaker.TryGetFreeRect(7, 7, out cellRect5); + cellRect5 = cellRect5.ContractedBy(1); + designator_ZoneAddStockpile_Resources.DesignateMultiCell(cellRect5.Cells); + Zone_Stockpile zone_Stockpile = (Zone_Stockpile)Autotests_ColonyMaker.Map.zoneManager.ZoneAt(cellRect5.CenterCell); + zone_Stockpile.settings.Priority = (StoragePriority)value; } } if (flags.Contains(ColonyMakerFlag.GrowingZones)) { Zone_Growing dummyZone = new Zone_Growing(Autotests_ColonyMaker.Map.zoneManager); - foreach (ThingDef current11 in from d in DefDatabase.AllDefs + foreach (ThingDef item9 in from d in DefDatabase.AllDefs where d.plant != null && GenPlant.CanSowOnGrower(d, dummyZone) select d) { - CellRect cellRect6; + CellRect cellRect6 = default(CellRect); if (!Autotests_ColonyMaker.TryGetFreeRect(6, 6, out cellRect6)) { Log.Error("Could not get growing zone rect."); } cellRect6 = cellRect6.ContractedBy(1); - foreach (IntVec3 current12 in cellRect6) + foreach (IntVec3 item10 in cellRect6) { - Autotests_ColonyMaker.Map.terrainGrid.SetTerrain(current12, TerrainDefOf.Soil); + Autotests_ColonyMaker.Map.terrainGrid.SetTerrain(item10, TerrainDefOf.Soil); } Designator_ZoneAdd_Growing designator_ZoneAdd_Growing = new Designator_ZoneAdd_Growing(); designator_ZoneAdd_Growing.DesignateMultiCell(cellRect6.Cells); Zone_Growing zone_Growing = (Zone_Growing)Autotests_ColonyMaker.Map.zoneManager.ZoneAt(cellRect6.CenterCell); - zone_Growing.SetPlantDefToGrow(current11); + zone_Growing.SetPlantDefToGrow(item9); } dummyZone.Delete(); } @@ -355,9 +353,10 @@ where d.externalViolence private static void FillWithItems(CellRect rect, List itemDefs) { int num = 0; - foreach (IntVec3 current in rect) + foreach (IntVec3 item in rect) { - if (current.x % 6 != 0 && current.z % 6 != 0) + IntVec3 current = item; + if (((current.x % 6 != 0) ? (current.z % 6) : 0) != 0) { ThingDef def = itemDefs[num]; DebugThingPlaceHelper.DebugSpawn(def, current, -1, true); @@ -372,14 +371,14 @@ private static void FillWithItems(CellRect rect, List itemDefs) private static Thing TryMakeBuilding(ThingDef def) { - CellRect cellRect; + CellRect cellRect = default(CellRect); if (!Autotests_ColonyMaker.TryGetFreeRect(def.size.x + 2, def.size.z + 2, out cellRect)) { return null; } - foreach (IntVec3 current in cellRect) + foreach (IntVec3 item in cellRect) { - Autotests_ColonyMaker.Map.terrainGrid.SetTerrain(current, TerrainDefOf.Concrete); + Autotests_ColonyMaker.Map.terrainGrid.SetTerrain(item, TerrainDefOf.Concrete); } Designator_Build designator_Build = new Designator_Build(def); designator_Build.DesignateSingleCell(cellRect.CenterCell); @@ -394,29 +393,35 @@ private static bool TryGetFreeRect(int width, int height, out CellRect result) { CellRect cellRect = new CellRect(j, i, width, height); bool flag = true; - for (int k = cellRect.minZ; k <= cellRect.maxZ; k++) + int num = cellRect.minZ; + while (num <= cellRect.maxZ) { - for (int l = cellRect.minX; l <= cellRect.maxX; l++) + int num2 = cellRect.minX; + while (num2 <= cellRect.maxX) { - if (Autotests_ColonyMaker.usedCells[l, k]) + if (!Autotests_ColonyMaker.usedCells[num2, num]) { - flag = false; - break; + num2++; + continue; } + flag = false; + break; } - if (!flag) + if (flag) { - break; + num++; + continue; } + break; } if (flag) { result = cellRect; - for (int m = cellRect.minZ; m <= cellRect.maxZ; m++) + for (int k = cellRect.minZ; k <= cellRect.maxZ; k++) { - for (int n = cellRect.minX; n <= cellRect.maxX; n++) + for (int l = cellRect.minX; l <= cellRect.maxX; l++) { - IntVec3 c = new IntVec3(n, 0, m); + IntVec3 c = new IntVec3(l, 0, k); Autotests_ColonyMaker.usedCells.Set(c, true); if (c.GetTerrain(Find.VisibleMap).passability == Traversability.Impassable) { @@ -436,29 +441,27 @@ private static void DoToColonists(float fraction, Action funcToDo) { int num = Rand.RangeInclusive(1, Mathf.RoundToInt((float)Autotests_ColonyMaker.Map.mapPawns.FreeColonistsCount * fraction)); int num2 = 0; - foreach (Pawn current in Autotests_ColonyMaker.Map.mapPawns.FreeColonists.InRandomOrder(null)) + foreach (Pawn item in Autotests_ColonyMaker.Map.mapPawns.FreeColonists.InRandomOrder(null)) { - funcToDo(current); + funcToDo(item); num2++; if (num2 >= num) - { break; - } } } private static void MakeColonists(int count, IntVec3 center) { - for (int i = 0; i < count; i++) + for (int num = 0; num < count; num++) { - CellRect cellRect; + CellRect cellRect = default(CellRect); Autotests_ColonyMaker.TryGetFreeRect(1, 1, out cellRect); Pawn pawn = PawnGenerator.GeneratePawn(Faction.OfPlayer.def.basicMemberKind, Faction.OfPlayer); - foreach (WorkTypeDef current in DefDatabase.AllDefs) + foreach (WorkTypeDef allDef in DefDatabase.AllDefs) { - if (!pawn.story.WorkTypeIsDisabled(current)) + if (!pawn.story.WorkTypeIsDisabled(allDef)) { - pawn.workSettings.SetPriority(current, 3); + pawn.workSettings.SetPriority(allDef, 3); } } GenSpawn.Spawn(pawn, cellRect.CenterCell, Autotests_ColonyMaker.Map); @@ -467,19 +470,28 @@ private static void MakeColonists(int count, IntVec3 center) private static void DeleteAllSpawnedPawns() { - foreach (Pawn current in Autotests_ColonyMaker.Map.mapPawns.AllPawnsSpawned.ToList()) + List.Enumerator enumerator = Autotests_ColonyMaker.Map.mapPawns.AllPawnsSpawned.ToList().GetEnumerator(); + try + { + while (enumerator.MoveNext()) + { + Pawn current = enumerator.Current; + current.Destroy(DestroyMode.Vanish); + current.relations.ClearAllRelations(); + } + } + finally { - current.Destroy(DestroyMode.Vanish); - current.relations.ClearAllRelations(); + ((IDisposable)(object)enumerator).Dispose(); } Find.GameEnder.gameEnding = false; } private static void ClearAllHomeArea() { - foreach (IntVec3 current in Autotests_ColonyMaker.Map.AllCells) + foreach (IntVec3 allCell in Autotests_ColonyMaker.Map.AllCells) { - Autotests_ColonyMaker.Map.areaManager.Home[current] = false; + ((Area)Autotests_ColonyMaker.Map.areaManager.Home)[allCell] = false; } } diff --git a/Assembly-CSharp/RimWorld/Autotests_RandomNumbers.cs b/Assembly-CSharp/RimWorld/Autotests_RandomNumbers.cs index e93e36878..7d560c9f3 100644 --- a/Assembly-CSharp/RimWorld/Autotests_RandomNumbers.cs +++ b/Assembly-CSharp/RimWorld/Autotests_RandomNumbers.cs @@ -1,6 +1,5 @@ using System; using System.Collections.Generic; -using System.Diagnostics; using System.Linq; using Verse; @@ -20,39 +19,28 @@ public static void Run() private static void CheckSimpleFloats() { - List list = Autotests_RandomNumbers.RandomFloats(500).ToList(); - if (list.Any((float x) => x < 0f || x > 1f)) + List list = Autotests_RandomNumbers.RandomFloats(500).ToList(); + if (list.Any((Predicate)((float x) => x < 0.0 || x > 1.0))) { Log.Error("Float out of range."); } - if (list.Any((float x) => x < 0.1f)) + if (!list.Any((Predicate)((float x) => x < 0.10000000149011612)) || !list.Any((Predicate)((float x) => (double)x > 0.5 && (double)x < 0.6)) || !list.Any((Predicate)((float x) => (double)x > 0.9))) { - if (list.Any((float x) => (double)x > 0.5 && (double)x < 0.6)) - { - if (list.Any((float x) => (double)x > 0.9)) - { - goto IL_C4; - } - } + Log.Warning("Possibly uneven distribution."); } - Log.Warning("Possibly uneven distribution."); - IL_C4: - list = Autotests_RandomNumbers.RandomFloats(1300000).ToList(); - int num = list.Count((float x) => (double)x < 0.1); - Log.Message("< 0.1 count (should be ~10%): " + (float)num / (float)list.Count() * 100f + "%"); - num = list.Count((float x) => (double)x < 0.0001); - Log.Message("< 0.0001 count (should be ~0.01%): " + (float)num / (float)list.Count() * 100f + "%"); + list = Autotests_RandomNumbers.RandomFloats(1300000).ToList(); + int num = list.Count((Func)((float x) => (double)x < 0.1)); + Log.Message("< 0.1 count (should be ~10%): " + (float)((float)num / (float)list.Count() * 100.0) + "%"); + num = list.Count((Func)((float x) => (double)x < 0.0001)); + Log.Message("< 0.0001 count (should be ~0.01%): " + (float)((float)num / (float)list.Count() * 100.0) + "%"); } - [DebuggerHidden] private static IEnumerable RandomFloats(int count) { - Autotests_RandomNumbers.c__Iterator1A8 c__Iterator1A = new Autotests_RandomNumbers.c__Iterator1A8(); - c__Iterator1A.count = count; - c__Iterator1A.<$>count = count; - Autotests_RandomNumbers.c__Iterator1A8 expr_15 = c__Iterator1A; - expr_15.$PC = -2; - return expr_15; + for (int i = 0; i < count; i++) + { + yield return Rand.Value; + } } private static void CheckIntsRange() @@ -64,57 +52,52 @@ private static void CheckIntsRange() while (true) { bool flag = true; - for (int i = num; i <= num2; i++) + int num4 = num; + while (num4 <= num2) { - if (!dictionary.ContainsKey(i)) + if (dictionary.ContainsKey(num4)) { - flag = false; - break; + num4++; + continue; } - } - if (flag) - { + flag = false; break; } - num3++; - if (num3 == 200000) - { - goto Block_3; - } - int num4 = Rand.RangeInclusive(num, num2); - if (num4 < num || num4 > num2) - { - Log.Error("Value out of range."); - } - if (dictionary.ContainsKey(num4)) - { - Dictionary dictionary2; - Dictionary expr_92 = dictionary2 = dictionary; - int num5; - int expr_97 = num5 = num4; - num5 = dictionary2[num5]; - expr_92[expr_97] = num5 + 1; - } - else + if (!flag) { - dictionary.Add(num4, 1); + num3++; + if (num3 == 200000) + { + Log.Error("Failed to find all numbers in a range."); + return; + } + int num5 = Rand.RangeInclusive(num, num2); + if (num5 < num || num5 > num2) + { + Log.Error("Value out of range."); + } + if (dictionary.ContainsKey(num5)) + { + Dictionary dictionary2; + Dictionary obj = dictionary2 = dictionary; + int key; + int key2 = key = num5; + key = dictionary2[key]; + obj[key2] = key + 1; + } + else + { + dictionary.Add(num5, 1); + } + continue; } + break; } - Log.Message(string.Concat(new object[] - { - "Values between ", - num, - " and ", - num2, - " (value: number of occurrences):" - })); - for (int j = num; j <= num2; j++) + Log.Message("Values between " + num + " and " + num2 + " (value: number of occurrences):"); + for (int num6 = num; num6 <= num2; num6++) { - Log.Message(j + ": " + dictionary[j]); + Log.Message(num6 + ": " + dictionary[num6]); } - return; - Block_3: - Log.Error("Failed to find all numbers in a range."); } private static void CheckIntsDistribution() @@ -129,13 +112,7 @@ private static void CheckIntsDistribution() int i; for (i = 0; i < 4; i++) { - Log.Message(string.Concat(new object[] - { - i, - ": ", - (float)list.Count((int x) => x == i) / (float)list.Count() * 100f, - "%" - })); + Log.Message(i + ": " + (float)((float)list.Count((Func)((int x) => x == i)) / (float)list.Count() * 100.0) + "%"); } } @@ -176,10 +153,9 @@ private static void TestPushSeed(int seed1, int seed2) int int5 = Rand.Int; Rand.PopState(); int int6 = Rand.Int; - if (@int != int4 || int2 != int6 || int3 != int5) - { - Log.Error("PushSeed broken."); - } + if (@int == int4 && int2 == int6 && int3 == int5) + return; + Log.Error("PushSeed broken."); } } } diff --git a/Assembly-CSharp/RimWorld/Backstory.cs b/Assembly-CSharp/RimWorld/Backstory.cs index 1dd5ef3d2..a8fb48d2e 100644 --- a/Assembly-CSharp/RimWorld/Backstory.cs +++ b/Assembly-CSharp/RimWorld/Backstory.cs @@ -1,6 +1,5 @@ using System; using System.Collections.Generic; -using System.Diagnostics; using System.Text; using UnityEngine; using Verse; @@ -48,11 +47,14 @@ public IEnumerable DisabledWorkTypes { get { - Backstory.<>c__IteratorDB <>c__IteratorDB = new Backstory.<>c__IteratorDB(); - <>c__IteratorDB.<>f__this = this; - Backstory.<>c__IteratorDB expr_0E = <>c__IteratorDB; - expr_0E.$PC = -2; - return expr_0E; + List list = DefDatabase.AllDefsListForReading; + for (int i = 0; i < list.Count; i++) + { + if (!this.AllowsWorkType(list[i])) + { + yield return list[i]; + } + } } } @@ -60,11 +62,14 @@ public IEnumerable DisabledWorkGivers { get { - Backstory.<>c__IteratorDC <>c__IteratorDC = new Backstory.<>c__IteratorDC(); - <>c__IteratorDC.<>f__this = this; - Backstory.<>c__IteratorDC expr_0E = <>c__IteratorDC; - expr_0E.$PC = -2; - return expr_0E; + List list = DefDatabase.AllDefsListForReading; + for (int i = 0; i < list.Count; i++) + { + if (!this.AllowsWorkGiver(list[i])) + { + yield return list[i]; + } + } } } @@ -106,15 +111,25 @@ public bool DisallowsTrait(TraitDef def, int degree) public BodyType BodyTypeFor(Gender g) { - if (this.bodyTypeGlobal != BodyType.Undefined || g == Gender.None) - { - return this.bodyTypeGlobal; - } - if (g == Gender.Female) + if (this.bodyTypeGlobal == BodyType.Undefined) { - return this.bodyTypeFemale; + switch (g) + { + case Gender.None: + goto IL_0011; + case Gender.Female: + { + return this.bodyTypeFemale; + } + default: + { + return this.bodyTypeMale; + } + } } - return this.bodyTypeMale; + goto IL_0011; + IL_0011: + return this.bodyTypeGlobal; } public string FullDescriptionFor(Pawn p) @@ -133,20 +148,13 @@ public string FullDescriptionFor(Pawn p) } } stringBuilder.AppendLine(); - foreach (WorkTypeDef current in this.DisabledWorkTypes) + foreach (WorkTypeDef disabledWorkType in this.DisabledWorkTypes) { - stringBuilder.AppendLine(current.gerundLabel + " " + "DisabledLower".Translate()); + stringBuilder.AppendLine(disabledWorkType.gerundLabel + " " + "DisabledLower".Translate()); } - foreach (WorkGiverDef current2 in this.DisabledWorkGivers) + foreach (WorkGiverDef disabledWorkGiver in this.DisabledWorkGivers) { - stringBuilder.AppendLine(string.Concat(new string[] - { - current2.workType.gerundLabel, - " -> ", - current2.label, - " ", - "DisabledLower".Translate() - })); + stringBuilder.AppendLine(disabledWorkGiver.workType.gerundLabel + " -> " + disabledWorkGiver.label + " " + "DisabledLower".Translate()); } return stringBuilder.ToString().TrimEndNewlines(); } @@ -199,7 +207,7 @@ public void PostLoad() this.bodyTypeFemale = BodyType.Female; } } - this.baseDesc = this.baseDesc.TrimEnd(new char[0]); + this.baseDesc = this.baseDesc.TrimEnd(); } public void ResolveReferences() @@ -208,23 +216,90 @@ public void ResolveReferences() string s = this.title.Replace('-', ' '); s = GenText.CapitalizedNoSpaces(s); this.identifier = GenText.RemoveNonAlphanumeric(s) + num.ToString(); - foreach (KeyValuePair current in this.skillGains) + Dictionary.Enumerator enumerator = this.skillGains.GetEnumerator(); + try + { + while (enumerator.MoveNext()) + { + KeyValuePair current = enumerator.Current; + this.skillGainsResolved.Add(DefDatabase.GetNamed(current.Key, true), current.Value); + } + } + finally { - this.skillGainsResolved.Add(DefDatabase.GetNamed(current.Key, true), current.Value); + ((IDisposable)(object)enumerator).Dispose(); } this.skillGains = null; } - [DebuggerHidden] public IEnumerable ConfigErrors(bool ignoreNoSpawnCategories) { - Backstory.c__IteratorDD c__IteratorDD = new Backstory.c__IteratorDD(); - c__IteratorDD.ignoreNoSpawnCategories = ignoreNoSpawnCategories; - c__IteratorDD.<$>ignoreNoSpawnCategories = ignoreNoSpawnCategories; - c__IteratorDD.<>f__this = this; - Backstory.c__IteratorDD expr_1C = c__IteratorDD; - expr_1C.$PC = -2; - return expr_1C; + if (this.title.NullOrEmpty()) + { + yield return "null title, baseDesc is " + this.baseDesc; + } + if (this.titleShort.NullOrEmpty()) + { + yield return "null titleShort, baseDesc is " + this.baseDesc; + } + if (((int)this.workDisables & 8) != 0 && this.spawnCategories.Contains("Raider")) + { + yield return "cannot do Violent work but can spawn as a raider"; + } + if (this.spawnCategories.Count == 0 && !ignoreNoSpawnCategories) + { + yield return "no spawn categories"; + } + if (this.spawnCategories.Count == 1 && this.spawnCategories[0] == "Trader") + { + yield return "only Trader spawn category"; + } + if (!this.baseDesc.NullOrEmpty()) + { + if (char.IsWhiteSpace(this.baseDesc[0])) + { + yield return "baseDesc starts with whitepspace"; + } + if (char.IsWhiteSpace(this.baseDesc[this.baseDesc.Length - 1])) + { + yield return "baseDesc ends with whitespace"; + } + } + if (Prefs.DevMode) + { + Dictionary.Enumerator enumerator = this.skillGainsResolved.GetEnumerator(); + try + { + while (enumerator.MoveNext()) + { + KeyValuePair kvp2 = enumerator.Current; + if (kvp2.Key.IsDisabled(this.workDisables, this.DisabledWorkTypes)) + { + yield return "modifies skill " + kvp2.Key + " but also disables this skill"; + } + } + } + finally + { + ((IDisposable)(object)enumerator).Dispose(); + } + Dictionary.Enumerator enumerator2 = BackstoryDatabase.allBackstories.GetEnumerator(); + try + { + while (enumerator2.MoveNext()) + { + KeyValuePair kvp = enumerator2.Current; + if (kvp.Value != this && kvp.Value.identifier == this.identifier) + { + yield return "backstory identifier used more than once: " + this.identifier; + } + } + } + finally + { + ((IDisposable)(object)enumerator2).Dispose(); + } + } } public void SetTitle(string newTitle) diff --git a/Assembly-CSharp/RimWorld/BackstoryDatabase.cs b/Assembly-CSharp/RimWorld/BackstoryDatabase.cs index 52b27d9fe..6a10618f6 100644 --- a/Assembly-CSharp/RimWorld/BackstoryDatabase.cs +++ b/Assembly-CSharp/RimWorld/BackstoryDatabase.cs @@ -16,15 +16,15 @@ public static void Clear() public static void ReloadAllBackstories() { - foreach (Backstory current in DirectXmlLoader.LoadXmlDataInResourcesFolder("Backstories/Shuffled")) + foreach (Backstory item in DirectXmlLoader.LoadXmlDataInResourcesFolder("Backstories/Shuffled")) { - current.PostLoad(); - current.ResolveReferences(); - foreach (string current2 in current.ConfigErrors(false)) + item.PostLoad(); + item.ResolveReferences(); + foreach (string item2 in item.ConfigErrors(false)) { - Log.Error(current.Title + ": " + current2); + Log.Error(item.Title + ": " + item2); } - BackstoryDatabase.AddBackstory(current); + BackstoryDatabase.AddBackstory(item); } SolidBioDatabase.LoadAllBios(); } @@ -34,18 +34,12 @@ public static void AddBackstory(Backstory bs) BackstoryHardcodedData.InjectHardcodedData(bs); if (BackstoryDatabase.allBackstories.ContainsKey(bs.identifier)) { - Log.Error(string.Concat(new string[] - { - "Backstory ", - bs.Title, - " has same unique save key ", - bs.identifier, - " as old backstory ", - BackstoryDatabase.allBackstories[bs.identifier].Title - })); - return; + Log.Error("Backstory " + bs.Title + " has same unique save key " + bs.identifier + " as old backstory " + BackstoryDatabase.allBackstories[bs.identifier].Title); + } + else + { + BackstoryDatabase.allBackstories.Add(bs.identifier, bs); } - BackstoryDatabase.allBackstories.Add(bs.identifier, bs); } public static bool TryGetWithIdentifier(string identifier, out Backstory bs) @@ -57,7 +51,7 @@ public static Backstory RandomBackstory(BackstorySlot slot) { return (from bs in BackstoryDatabase.allBackstories where bs.Value.slot == slot - select bs).RandomElement>().Value; + select bs).RandomElement().Value; } } } diff --git a/Assembly-CSharp/RimWorld/BackstoryHardcodedData.cs b/Assembly-CSharp/RimWorld/BackstoryHardcodedData.cs index f45c65f93..c3a621e3f 100644 --- a/Assembly-CSharp/RimWorld/BackstoryHardcodedData.cs +++ b/Assembly-CSharp/RimWorld/BackstoryHardcodedData.cs @@ -1,5 +1,3 @@ -using System; - namespace RimWorld { internal static class BackstoryHardcodedData diff --git a/Assembly-CSharp/RimWorld/BackstorySlot.cs b/Assembly-CSharp/RimWorld/BackstorySlot.cs index c27579fc8..fa39fa204 100644 --- a/Assembly-CSharp/RimWorld/BackstorySlot.cs +++ b/Assembly-CSharp/RimWorld/BackstorySlot.cs @@ -1,10 +1,8 @@ -using System; - namespace RimWorld { public enum BackstorySlot : byte { - Childhood, - Adulthood + Childhood = 0, + Adulthood = 1 } } diff --git a/Assembly-CSharp/RimWorld/BeachMaker.cs b/Assembly-CSharp/RimWorld/BeachMaker.cs index eba40a904..b961bd346 100644 --- a/Assembly-CSharp/RimWorld/BeachMaker.cs +++ b/Assembly-CSharp/RimWorld/BeachMaker.cs @@ -1,4 +1,3 @@ -using System; using Verse; using Verse.Noise; @@ -24,30 +23,38 @@ public static void Init(Map map) if (!a.IsValid) { BeachMaker.beachNoise = null; - return; } - ModuleBase moduleBase = new Perlin(0.029999999329447746, 2.0, 0.5, 3, Rand.Range(0, 2147483647), QualityMode.Medium); - moduleBase = new ScaleBias(0.5, 0.5, moduleBase); - NoiseDebugUI.StoreNoiseRender(moduleBase, "BeachMaker base", new IntVec2(map.Size.x, map.Size.z)); - ModuleBase moduleBase2 = new DistFromAxis(BeachMaker.CoastWidthRange.RandomInRange); - if (a == Rot4.North) + else { - moduleBase2 = new Rotate(0.0, 90.0, 0.0, moduleBase2); - moduleBase2 = new Translate(0.0, 0.0, (double)(-(double)map.Size.z), moduleBase2); + ModuleBase input = new Perlin(0.029999999329447746, 2.0, 0.5, 3, Rand.Range(0, 2147483647), QualityMode.Medium); + input = new ScaleBias(0.5, 0.5, input); + ModuleBase noise = input; + IntVec3 size = map.Size; + int x = size.x; + IntVec3 size2 = map.Size; + NoiseDebugUI.StoreNoiseRender(noise, "BeachMaker base", new IntVec2(x, size2.z)); + ModuleBase input2 = new DistFromAxis(BeachMaker.CoastWidthRange.RandomInRange); + if (a == Rot4.North) + { + input2 = new Rotate(0.0, 90.0, 0.0, input2); + IntVec3 size3 = map.Size; + input2 = new Translate(0.0, 0.0, (double)(-size3.z), input2); + } + else if (a == Rot4.East) + { + IntVec3 size4 = map.Size; + input2 = new Translate((double)(-size4.x), 0.0, 0.0, input2); + } + else if (a == Rot4.South) + { + input2 = new Rotate(0.0, 90.0, 0.0, input2); + } + input2 = new ScaleBias(1.0, -1.0, input2); + input2 = new Clamp(-1.0, 2.5, input2); + NoiseDebugUI.StoreNoiseRender(input2, "BeachMaker axis bias"); + BeachMaker.beachNoise = new Add(input, input2); + NoiseDebugUI.StoreNoiseRender(BeachMaker.beachNoise, "beachNoise"); } - else if (a == Rot4.East) - { - moduleBase2 = new Translate((double)(-(double)map.Size.x), 0.0, 0.0, moduleBase2); - } - else if (a == Rot4.South) - { - moduleBase2 = new Rotate(0.0, 90.0, 0.0, moduleBase2); - } - moduleBase2 = new ScaleBias(1.0, -1.0, moduleBase2); - moduleBase2 = new Clamp(-1.0, 2.5, moduleBase2); - NoiseDebugUI.StoreNoiseRender(moduleBase2, "BeachMaker axis bias"); - BeachMaker.beachNoise = new Add(moduleBase, moduleBase2); - NoiseDebugUI.StoreNoiseRender(BeachMaker.beachNoise, "beachNoise"); } public static void Cleanup() @@ -62,15 +69,15 @@ public static TerrainDef BeachTerrainAt(IntVec3 loc, BiomeDef biome) return null; } float value = BeachMaker.beachNoise.GetValue(loc); - if (value < 0.1f) + if (value < 0.10000000149011612) { return TerrainDefOf.WaterOceanDeep; } - if (value < 0.45f) + if (value < 0.44999998807907104) { return TerrainDefOf.WaterOceanShallow; } - if (value < 1f) + if (value < 1.0) { return (biome != BiomeDefOf.SeaIce) ? TerrainDefOf.Sand : TerrainDefOf.Ice; } diff --git a/Assembly-CSharp/RimWorld/BeautyCategory.cs b/Assembly-CSharp/RimWorld/BeautyCategory.cs index bde9e4d3b..7f3ca288f 100644 --- a/Assembly-CSharp/RimWorld/BeautyCategory.cs +++ b/Assembly-CSharp/RimWorld/BeautyCategory.cs @@ -1,15 +1,13 @@ -using System; - namespace RimWorld { public enum BeautyCategory : byte { - Hideous, - VeryUgly, - Ugly, - Neutral, - Pretty, - VeryPretty, - Beautiful + Hideous = 0, + VeryUgly = 1, + Ugly = 2, + Neutral = 3, + Pretty = 4, + VeryPretty = 5, + Beautiful = 6 } } diff --git a/Assembly-CSharp/RimWorld/BeautyUtility.cs b/Assembly-CSharp/RimWorld/BeautyUtility.cs index 119904529..85fc71b08 100644 --- a/Assembly-CSharp/RimWorld/BeautyUtility.cs +++ b/Assembly-CSharp/RimWorld/BeautyUtility.cs @@ -1,4 +1,3 @@ -using System; using System.Collections.Generic; using Verse; @@ -34,50 +33,50 @@ public static void FillBeautyRelevantCells(IntVec3 root, Map map) { BeautyUtility.beautyRelevantCells.Clear(); Room room = root.GetRoom(map, RegionType.Set_Passable); - if (room == null) + if (room != null) { - return; - } - BeautyUtility.visibleRooms.Clear(); - BeautyUtility.visibleRooms.Add(room); - if (room.Regions.Count == 1 && room.Regions[0].type == RegionType.Portal) - { - foreach (Region current in room.Regions[0].Neighbors) + BeautyUtility.visibleRooms.Clear(); + BeautyUtility.visibleRooms.Add(room); + if (room.Regions.Count == 1 && room.Regions[0].type == RegionType.Portal) { - if (!BeautyUtility.visibleRooms.Contains(current.Room)) + foreach (Region neighbor in room.Regions[0].Neighbors) { - BeautyUtility.visibleRooms.Add(current.Room); + if (!BeautyUtility.visibleRooms.Contains(neighbor.Room)) + { + BeautyUtility.visibleRooms.Add(neighbor.Room); + } } } - } - for (int i = 0; i < BeautyUtility.SampleNumCells_Beauty; i++) - { - IntVec3 intVec = root + GenRadial.RadialPattern[i]; - if (intVec.InBounds(map) && !intVec.Fogged(map)) + for (int i = 0; i < BeautyUtility.SampleNumCells_Beauty; i++) { - Room room2 = intVec.GetRoom(map, RegionType.Set_Passable); - if (!BeautyUtility.visibleRooms.Contains(room2)) + IntVec3 intVec = root + GenRadial.RadialPattern[i]; + if (intVec.InBounds(map) && !intVec.Fogged(map)) { - bool flag = false; - for (int j = 0; j < 8; j++) + Room room2 = intVec.GetRoom(map, RegionType.Set_Passable); + if (!BeautyUtility.visibleRooms.Contains(room2)) { - IntVec3 loc = intVec + GenAdj.AdjacentCells[j]; - if (BeautyUtility.visibleRooms.Contains(loc.GetRoom(map, RegionType.Set_Passable))) + bool flag = false; + for (int j = 0; j < 8; j++) { - flag = true; - break; + IntVec3 loc = intVec + GenAdj.AdjacentCells[j]; + if (BeautyUtility.visibleRooms.Contains(loc.GetRoom(map, RegionType.Set_Passable))) + { + flag = true; + break; + } } + if (flag) + goto IL_0173; + continue; } - if (!flag) - { - goto IL_17F; - } + goto IL_0173; } + continue; + IL_0173: BeautyUtility.beautyRelevantCells.Add(intVec); } - IL_17F:; + BeautyUtility.visibleRooms.Clear(); } - BeautyUtility.visibleRooms.Clear(); } public static float CellBeauty(IntVec3 c, Map map, List countedThings = null) @@ -86,41 +85,35 @@ public static float CellBeauty(IntVec3 c, Map map, List countedThings = n float num2 = 0f; bool flag = false; List list = map.thingGrid.ThingsListAt(c); - int i = 0; - while (i < list.Count) + for (int i = 0; i < list.Count; i++) { Thing thing = list[i]; - if (countedThings == null) - { - goto IL_4D; - } - if (!countedThings.Contains(thing)) + if (countedThings != null) { + if (countedThings.Contains(thing)) + { + continue; + } countedThings.Add(thing); - goto IL_4D; } - IL_CC: - i++; - continue; - IL_4D: SlotGroup slotGroup = thing.GetSlotGroup(); - if (slotGroup != null && slotGroup.parent.IgnoreStoredThingsBeauty) - { - goto IL_CC; - } - float num3 = thing.GetStatValue(StatDefOf.Beauty, true); - if (thing is Filth && !map.roofGrid.Roofed(c)) + if (slotGroup == null || !slotGroup.parent.IgnoreStoredThingsBeauty) { - num3 *= 0.3f; - } - if (thing.def.Fillage == FillCategory.Full) - { - flag = true; - num2 += num3; - goto IL_CC; + float num3 = thing.GetStatValue(StatDefOf.Beauty, true); + if (thing is Filth && !map.roofGrid.Roofed(c)) + { + num3 = (float)(num3 * 0.30000001192092896); + } + if (thing.def.Fillage == FillCategory.Full) + { + flag = true; + num2 += num3; + } + else + { + num += num3; + } } - num += num3; - goto IL_CC; } if (flag) { diff --git a/Assembly-CSharp/RimWorld/Bill.cs b/Assembly-CSharp/RimWorld/Bill.cs index a2d533192..3ff9dcce0 100644 --- a/Assembly-CSharp/RimWorld/Bill.cs +++ b/Assembly-CSharp/RimWorld/Bill.cs @@ -1,4 +1,3 @@ -using System; using System.Collections.Generic; using UnityEngine; using Verse; @@ -79,7 +78,7 @@ protected virtual string StatusString { get { - return null; + return (string)null; } } @@ -100,7 +99,11 @@ public bool DeletedOrDereferenced return true; } Thing thing = this.billStack.billGiver as Thing; - return thing != null && thing.Destroyed; + if (thing != null && thing.Destroyed) + { + return true; + } + return false; } } @@ -125,11 +128,11 @@ public virtual void ExposeData() Scribe_Values.Look(ref this.allowedSkillRange, "allowedSkillRange", default(IntRange), false); if (Scribe.mode == LoadSaveMode.Saving && this.recipe.fixedIngredientFilter != null) { - foreach (ThingDef current in DefDatabase.AllDefs) + foreach (ThingDef allDef in DefDatabase.AllDefs) { - if (!this.recipe.fixedIngredientFilter.Allows(current)) + if (!this.recipe.fixedIngredientFilter.Allows(allDef)) { - this.ingredientFilter.SetAllow(current, false); + this.ingredientFilter.SetAllow(allDef, false); } } } @@ -141,11 +144,14 @@ public virtual bool PawnAllowedToStartAnew(Pawn p) if (this.recipe.workSkill != null) { int level = p.skills.GetSkill(this.recipe.workSkill).Level; - if (level < this.allowedSkillRange.min || level > this.allowedSkillRange.max) + if (level >= this.allowedSkillRange.min && level <= this.allowedSkillRange.max) { - return false; + goto IL_0050; } + return false; } + goto IL_0050; + IL_0050: return true; } @@ -180,12 +186,12 @@ public Rect DoInterface(float x, float y, float width, int index) num = Mathf.Max(17f, this.StatusLineMinHeight); } rect.height += num; - Color white = Color.white; + Color color = Color.white; if (!this.ShouldDoNow()) { - white = new Color(1f, 0.7f, 0.7f, 0.7f); + color = new Color(1f, 0.7f, 0.7f, 0.7f); } - GUI.color = white; + GUI.color = color; Text.Font = GameFont.Small; if (index % 2 == 0) { @@ -193,7 +199,7 @@ public Rect DoInterface(float x, float y, float width, int index) } GUI.BeginGroup(rect); Rect butRect = new Rect(0f, 0f, 24f, 24f); - if (this.billStack.IndexOf(this) > 0 && Widgets.ButtonImage(butRect, TexButton.ReorderUp, white)) + if (this.billStack.IndexOf(this) > 0 && Widgets.ButtonImage(butRect, TexButton.ReorderUp, color)) { this.billStack.Reorder(this, -1); SoundDefOf.TickHigh.PlayOneShotOnCamera(null); @@ -201,30 +207,30 @@ public Rect DoInterface(float x, float y, float width, int index) if (this.billStack.IndexOf(this) < this.billStack.Count - 1) { Rect butRect2 = new Rect(0f, 24f, 24f, 24f); - if (Widgets.ButtonImage(butRect2, TexButton.ReorderDown, white)) + if (Widgets.ButtonImage(butRect2, TexButton.ReorderDown, color)) { this.billStack.Reorder(this, 1); SoundDefOf.TickLow.PlayOneShotOnCamera(null); } } - Rect rect2 = new Rect(28f, 0f, rect.width - 48f - 20f, 48f); + Rect rect2 = new Rect(28f, 0f, (float)(rect.width - 48.0 - 20.0), 48f); Widgets.Label(rect2, this.LabelCap); - this.DoConfigInterface(rect.AtZero(), white); - Rect rect3 = new Rect(rect.width - 24f, 0f, 24f, 24f); - if (Widgets.ButtonImage(rect3, TexButton.DeleteX, white)) + this.DoConfigInterface(rect.AtZero(), color); + Rect rect3 = new Rect((float)(rect.width - 24.0), 0f, 24f, 24f); + if (Widgets.ButtonImage(rect3, TexButton.DeleteX, color)) { this.billStack.Delete(this); } Rect butRect3 = new Rect(rect3); - butRect3.x -= butRect3.width + 4f; - if (Widgets.ButtonImage(butRect3, TexButton.Suspend, white)) + butRect3.x -= (float)(butRect3.width + 4.0); + if (Widgets.ButtonImage(butRect3, TexButton.Suspend, color)) { this.suspended = !this.suspended; } if (!this.StatusString.NullOrEmpty()) { Text.Font = GameFont.Tiny; - Rect rect4 = new Rect(24f, rect.height - num, rect.width - 24f, num); + Rect rect4 = new Rect(24f, rect.height - num, (float)(rect.width - 24.0), num); Widgets.Label(rect4, this.StatusString); this.DoStatusLineInterface(rect4); } @@ -233,7 +239,7 @@ public Rect DoInterface(float x, float y, float width, int index) { Text.Font = GameFont.Medium; Text.Anchor = TextAnchor.MiddleCenter; - Rect rect5 = new Rect(rect.x + rect.width / 2f - 70f, rect.y + rect.height / 2f - 20f, 140f, 40f); + Rect rect5 = new Rect((float)(rect.x + rect.width / 2.0 - 70.0), (float)(rect.y + rect.height / 2.0 - 20.0), 140f, 40f); GUI.DrawTexture(rect5, TexUI.GrayTextBG); Widgets.Label(rect5, "SuspendedCaps".Translate()); Text.Anchor = TextAnchor.UpperLeft; @@ -272,13 +278,10 @@ public bool IsFixedOrAllowedIngredient(ThingDef def) public static void CreateNoPawnsWithSkillDialog(RecipeDef recipe) { - string text = "RecipeRequiresSkills".Translate(new object[] - { - recipe.LabelCap - }); - text += "\n\n"; - text += recipe.MinSkillString; - Find.WindowStack.Add(new Dialog_MessageBox(text, null, null, null, null, null, false)); + string str = "RecipeRequiresSkills".Translate(recipe.LabelCap); + str += "\n\n"; + str += recipe.MinSkillString; + Find.WindowStack.Add(new Dialog_MessageBox(str, (string)null, null, (string)null, null, (string)null, false)); } public virtual BillStoreModeDef GetStoreMode() @@ -288,13 +291,7 @@ public virtual BillStoreModeDef GetStoreMode() public string GetUniqueLoadID() { - return string.Concat(new object[] - { - "Bill_", - this.recipe.defName, - "_", - this.loadID - }); + return "Bill_" + this.recipe.defName + "_" + this.loadID; } public override string ToString() diff --git a/Assembly-CSharp/RimWorld/BillRepeatModeDef.cs b/Assembly-CSharp/RimWorld/BillRepeatModeDef.cs index 23804361d..1a955be14 100644 --- a/Assembly-CSharp/RimWorld/BillRepeatModeDef.cs +++ b/Assembly-CSharp/RimWorld/BillRepeatModeDef.cs @@ -1,4 +1,3 @@ -using System; using Verse; namespace RimWorld diff --git a/Assembly-CSharp/RimWorld/BillRepeatModeDefOf.cs b/Assembly-CSharp/RimWorld/BillRepeatModeDefOf.cs index e7794b9ea..30603230d 100644 --- a/Assembly-CSharp/RimWorld/BillRepeatModeDefOf.cs +++ b/Assembly-CSharp/RimWorld/BillRepeatModeDefOf.cs @@ -1,5 +1,3 @@ -using System; - namespace RimWorld { [DefOf] diff --git a/Assembly-CSharp/RimWorld/BillRepeatModeUtility.cs b/Assembly-CSharp/RimWorld/BillRepeatModeUtility.cs index da1b47575..b401312fd 100644 --- a/Assembly-CSharp/RimWorld/BillRepeatModeUtility.cs +++ b/Assembly-CSharp/RimWorld/BillRepeatModeUtility.cs @@ -26,11 +26,11 @@ public static string GetLabel(this BillRepeatModeDef brm) public static void MakeConfigFloatMenu(Bill_Production bill) { List list = new List(); - list.Add(new FloatMenuOption("DoXTimes".Translate(), delegate + list.Add(new FloatMenuOption("DoXTimes".Translate(), (Action)delegate() { bill.repeatMode = BillRepeatModeDefOf.RepeatCount; }, MenuOptionPriority.Default, null, null, 0f, null, null)); - FloatMenuOption item = new FloatMenuOption("DoUntilYouHaveX".Translate(), delegate + FloatMenuOption item = new FloatMenuOption("DoUntilYouHaveX".Translate(), (Action)delegate() { if (!bill.recipe.WorkerCounter.CanCountProducts(bill)) { @@ -42,7 +42,7 @@ public static void MakeConfigFloatMenu(Bill_Production bill) } }, MenuOptionPriority.Default, null, null, 0f, null, null); list.Add(item); - list.Add(new FloatMenuOption("DoForever".Translate(), delegate + list.Add(new FloatMenuOption("DoForever".Translate(), (Action)delegate() { bill.repeatMode = BillRepeatModeDefOf.Forever; }, MenuOptionPriority.Default, null, null, 0f, null, null)); diff --git a/Assembly-CSharp/RimWorld/BillStack.cs b/Assembly-CSharp/RimWorld/BillStack.cs index 665a62185..663521fa6 100644 --- a/Assembly-CSharp/RimWorld/BillStack.cs +++ b/Assembly-CSharp/RimWorld/BillStack.cs @@ -81,7 +81,7 @@ public BillStack(IBillGiver giver) public IEnumerator GetEnumerator() { - return this.bills.GetEnumerator(); + return (IEnumerator)(object)this.bills.GetEnumerator(); } public void AddBill(Bill bill) @@ -114,11 +114,11 @@ public void Reorder(Bill bill, int offset) public void RemoveIncompletableBills() { - for (int i = this.bills.Count - 1; i >= 0; i--) + for (int num = this.bills.Count - 1; num >= 0; num--) { - if (!this.bills[i].CompletableEver) + if (!this.bills[num].CompletableEver) { - this.bills.Remove(this.bills[i]); + this.bills.Remove(this.bills[num]); } } } @@ -156,8 +156,8 @@ public Bill DoListing(Rect rect, Func> recipeOptionsMaker, } Text.Anchor = TextAnchor.UpperLeft; GUI.color = Color.white; - Rect outRect = new Rect(0f, 35f, rect.width, rect.height - 35f); - Rect viewRect = new Rect(0f, 0f, outRect.width - 16f, viewHeight); + Rect outRect = new Rect(0f, 35f, rect.width, (float)(rect.height - 35.0)); + Rect viewRect = new Rect(0f, 0f, (float)(outRect.width - 16.0), viewHeight); Widgets.BeginScrollView(outRect, ref scrollPosition, viewRect, true); float num = 0f; for (int i = 0; i < this.Count; i++) @@ -168,11 +168,11 @@ public Bill DoListing(Rect rect, Func> recipeOptionsMaker, { result = bill; } - num += rect3.height + 6f; + num = (float)(num + (rect3.height + 6.0)); } if (Event.current.type == EventType.Layout) { - viewHeight = num + 60f; + viewHeight = (float)(num + 60.0); } Widgets.EndScrollView(); GUI.EndGroup(); diff --git a/Assembly-CSharp/RimWorld/BillStoreModeDef.cs b/Assembly-CSharp/RimWorld/BillStoreModeDef.cs index d91ab26e3..780fb33c2 100644 --- a/Assembly-CSharp/RimWorld/BillStoreModeDef.cs +++ b/Assembly-CSharp/RimWorld/BillStoreModeDef.cs @@ -1,4 +1,3 @@ -using System; using Verse; namespace RimWorld diff --git a/Assembly-CSharp/RimWorld/BillStoreModeDefOf.cs b/Assembly-CSharp/RimWorld/BillStoreModeDefOf.cs index c97b43514..6b88bd9df 100644 --- a/Assembly-CSharp/RimWorld/BillStoreModeDefOf.cs +++ b/Assembly-CSharp/RimWorld/BillStoreModeDefOf.cs @@ -1,5 +1,3 @@ -using System; - namespace RimWorld { [DefOf] diff --git a/Assembly-CSharp/RimWorld/BillUtility.cs b/Assembly-CSharp/RimWorld/BillUtility.cs index 46d9de884..576762403 100644 --- a/Assembly-CSharp/RimWorld/BillUtility.cs +++ b/Assembly-CSharp/RimWorld/BillUtility.cs @@ -1,4 +1,3 @@ -using System; using Verse; namespace RimWorld diff --git a/Assembly-CSharp/RimWorld/Bill_Medical.cs b/Assembly-CSharp/RimWorld/Bill_Medical.cs index 3a6c52adf..c7ad2dc75 100644 --- a/Assembly-CSharp/RimWorld/Bill_Medical.cs +++ b/Assembly-CSharp/RimWorld/Bill_Medical.cs @@ -24,7 +24,11 @@ public override bool CompletableEver { get { - return !this.recipe.targetsBodyPart || this.recipe.Worker.GetPartsToApplyOn(this.GiverPawn, this.recipe).Contains(this.part); + if (base.recipe.targetsBodyPart && !base.recipe.Worker.GetPartsToApplyOn(this.GiverPawn, base.recipe).Contains(this.part)) + { + return false; + } + return true; } } @@ -40,20 +44,22 @@ public BodyPartRecord Part } set { - if (this.billStack == null) + if (base.billStack == null) { Log.Error("Can only set Bill_Medical.Part after the bill has been added to a pawn's bill stack."); - return; - } - if (value != null) - { - this.partIndex = this.GiverPawn.RaceProps.body.GetIndexOfPart(value); } else { - this.partIndex = -1; + if (value != null) + { + this.partIndex = this.GiverPawn.RaceProps.body.GetIndexOfPart(value); + } + else + { + this.partIndex = -1; + } + this.part = value; } - this.part = value; } } @@ -61,8 +67,8 @@ private Pawn GiverPawn { get { - Pawn pawn = this.billStack.billGiver as Pawn; - Corpse corpse = this.billStack.billGiver as Corpse; + Pawn pawn = base.billStack.billGiver as Pawn; + Corpse corpse = base.billStack.billGiver as Corpse; if (corpse != null) { pawn = corpse.InnerPawn; @@ -80,8 +86,8 @@ public override string Label get { StringBuilder stringBuilder = new StringBuilder(); - stringBuilder.Append(this.recipe.Worker.GetLabelWhenUsedOn(this.GiverPawn, this.part)); - if (this.Part != null && !this.recipe.hideBodyPartNames) + stringBuilder.Append(base.recipe.Worker.GetLabelWhenUsedOn(this.GiverPawn, this.part)); + if (this.Part != null && !base.recipe.hideBodyPartNames) { stringBuilder.Append(" (" + this.Part.def.label + ")"); } @@ -99,7 +105,11 @@ public Bill_Medical(RecipeDef recipe) : base(recipe) public override bool ShouldDoNow() { - return !this.suspended; + if (base.suspended) + { + return false; + } + return true; } public override void Notify_IterationCompleted(Pawn billDoer, List ingredients) @@ -108,35 +118,41 @@ public override void Notify_IterationCompleted(Pawn billDoer, List ingred if (this.CompletableEver) { Pawn giverPawn = this.GiverPawn; - this.recipe.Worker.ApplyOnPawn(giverPawn, this.Part, billDoer, ingredients); + base.recipe.Worker.ApplyOnPawn(giverPawn, this.Part, billDoer, ingredients); if (giverPawn.RaceProps.IsFlesh) { giverPawn.records.Increment(RecordDefOf.OperationsReceived); billDoer.records.Increment(RecordDefOf.OperationsPerformed); } } - this.billStack.Delete(this); + base.billStack.Delete(this); } public override void Notify_DoBillStarted(Pawn billDoer) { base.Notify_DoBillStarted(billDoer); - if (!this.GiverPawn.Dead && this.recipe.anesthetize && HealthUtility.TryAnesthetize(this.GiverPawn)) + if (!this.GiverPawn.Dead && base.recipe.anesthetize && HealthUtility.TryAnesthetize(this.GiverPawn)) { List placedThings = billDoer.CurJob.placedThings; - for (int i = 0; i < placedThings.Count; i++) + int num = 0; + while (true) { - if (placedThings[i].thing is Medicine) + if (num < placedThings.Count) { - this.recipe.Worker.ConsumeIngredient(placedThings[i].thing.SplitOff(1), this.recipe, billDoer.MapHeld); - placedThings[i].Count--; - if (placedThings[i].thing.Destroyed || placedThings[i].Count <= 0) + if (!(placedThings[num].thing is Medicine)) { - placedThings.RemoveAt(i); + num++; + continue; } break; } + return; } + base.recipe.Worker.ConsumeIngredient(placedThings[num].thing.SplitOff(1), base.recipe, billDoer.MapHeld); + placedThings[num].Count--; + if (!placedThings[num].thing.Destroyed && placedThings[num].Count > 0) + return; + placedThings.RemoveAt(num); } } diff --git a/Assembly-CSharp/RimWorld/Bill_Production.cs b/Assembly-CSharp/RimWorld/Bill_Production.cs index 044e99ae6..a94660ba2 100644 --- a/Assembly-CSharp/RimWorld/Bill_Production.cs +++ b/Assembly-CSharp/RimWorld/Bill_Production.cs @@ -38,7 +38,7 @@ protected override float StatusLineMinHeight { get { - return (!this.CanUnpause()) ? 0f : 24f; + return (float)((!this.CanUnpause()) ? 0.0 : 24.0); } } @@ -56,7 +56,7 @@ public string RepeatInfoText } if (this.repeatMode == BillRepeatModeDefOf.TargetCount) { - return this.recipe.WorkerCounter.CountProducts(this).ToString() + "/" + this.targetCount.ToString(); + return base.recipe.WorkerCounter.CountProducts(this).ToString() + "/" + this.targetCount.ToString(); } throw new InvalidOperationException(); } @@ -101,7 +101,7 @@ public override bool ShouldDoNow() { this.paused = false; } - if (this.suspended) + if (base.suspended) { return false; } @@ -115,7 +115,7 @@ public override bool ShouldDoNow() } if (this.repeatMode == BillRepeatModeDefOf.TargetCount) { - int num = this.recipe.WorkerCounter.CountProducts(this); + int num = base.recipe.WorkerCounter.CountProducts(this); if (this.pauseWhenSatisfied && num >= this.targetCount) { this.paused = true; @@ -124,7 +124,11 @@ public override bool ShouldDoNow() { this.paused = false; } - return !this.paused && num < this.targetCount; + if (this.paused) + { + return false; + } + return num < this.targetCount; } throw new InvalidOperationException(); } @@ -139,10 +143,7 @@ public override void Notify_IterationCompleted(Pawn billDoer, List ingred } if (this.repeatCount == 0) { - Messages.Message("MessageBillComplete".Translate(new object[] - { - this.LabelCap - }), (Thing)this.billStack.billGiver, MessageSound.Benefit); + Messages.Message("MessageBillComplete".Translate(this.LabelCap), (Thing)base.billStack.billGiver, MessageSound.Benefit); } } } @@ -153,16 +154,16 @@ protected override void DoConfigInterface(Rect baseRect, Color baseColor) GUI.color = new Color(1f, 1f, 1f, 0.65f); Widgets.Label(rect, this.RepeatInfoText); GUI.color = baseColor; - WidgetRow widgetRow = new WidgetRow(baseRect.xMax, baseRect.y + 29f, UIDirection.LeftThenUp, 99999f, 4f); - if (widgetRow.ButtonText("Details".Translate() + "...", null, true, false)) + WidgetRow widgetRow = new WidgetRow(baseRect.xMax, (float)(baseRect.y + 29.0), UIDirection.LeftThenUp, 99999f, 4f); + if (widgetRow.ButtonText("Details".Translate() + "...", (string)null, true, false)) { - Find.WindowStack.Add(new Dialog_BillConfig(this, ((Thing)this.billStack.billGiver).Position)); + Find.WindowStack.Add(new Dialog_BillConfig(this, ((Thing)base.billStack.billGiver).Position)); } - if (widgetRow.ButtonText(this.repeatMode.GetLabel().PadRight(20), null, true, false)) + if (widgetRow.ButtonText(this.repeatMode.GetLabel().PadRight(20), (string)null, true, false)) { BillRepeatModeUtility.MakeConfigFloatMenu(this); } - if (widgetRow.ButtonIcon(TexButton.Plus, null)) + if (widgetRow.ButtonIcon(TexButton.Plus, (string)null)) { if (this.repeatMode == BillRepeatModeDefOf.Forever) { @@ -171,7 +172,7 @@ protected override void DoConfigInterface(Rect baseRect, Color baseColor) } else if (this.repeatMode == BillRepeatModeDefOf.TargetCount) { - int num = this.recipe.targetCountAdjustment * GenUI.CurrentAdjustmentMultiplier(); + int num = base.recipe.targetCountAdjustment * GenUI.CurrentAdjustmentMultiplier(); this.targetCount += num; this.unpauseWhenYouHave += num; } @@ -182,10 +183,10 @@ protected override void DoConfigInterface(Rect baseRect, Color baseColor) SoundDefOf.AmountIncrement.PlayOneShotOnCamera(null); if (TutorSystem.TutorialMode && this.repeatMode == BillRepeatModeDefOf.RepeatCount) { - TutorSystem.Notify_Event(this.recipe.defName + "-RepeatCountSetTo-" + this.repeatCount); + TutorSystem.Notify_Event(base.recipe.defName + "-RepeatCountSetTo-" + this.repeatCount); } } - if (widgetRow.ButtonIcon(TexButton.Minus, null)) + if (widgetRow.ButtonIcon(TexButton.Minus, (string)null)) { if (this.repeatMode == BillRepeatModeDefOf.Forever) { @@ -194,7 +195,7 @@ protected override void DoConfigInterface(Rect baseRect, Color baseColor) } else if (this.repeatMode == BillRepeatModeDefOf.TargetCount) { - int num2 = this.recipe.targetCountAdjustment * GenUI.CurrentAdjustmentMultiplier(); + int num2 = base.recipe.targetCountAdjustment * GenUI.CurrentAdjustmentMultiplier(); this.targetCount = Mathf.Max(0, this.targetCount - num2); this.unpauseWhenYouHave = Mathf.Max(0, this.unpauseWhenYouHave - num2); } @@ -205,14 +206,14 @@ protected override void DoConfigInterface(Rect baseRect, Color baseColor) SoundDefOf.AmountDecrement.PlayOneShotOnCamera(null); if (TutorSystem.TutorialMode && this.repeatMode == BillRepeatModeDefOf.RepeatCount) { - TutorSystem.Notify_Event(this.recipe.defName + "-RepeatCountSetTo-" + this.repeatCount); + TutorSystem.Notify_Event(base.recipe.defName + "-RepeatCountSetTo-" + this.repeatCount); } } } private bool CanUnpause() { - return this.repeatMode == BillRepeatModeDefOf.TargetCount && this.paused && this.pauseWhenSatisfied && this.recipe.WorkerCounter.CountProducts(this) < this.targetCount; + return this.repeatMode == BillRepeatModeDefOf.TargetCount && this.paused && this.pauseWhenSatisfied && base.recipe.WorkerCounter.CountProducts(this) < this.targetCount; } public override void DoStatusLineInterface(Rect rect) @@ -220,7 +221,7 @@ public override void DoStatusLineInterface(Rect rect) if (this.paused) { WidgetRow widgetRow = new WidgetRow(rect.xMax, rect.y, UIDirection.LeftThenUp, 99999f, 4f); - if (widgetRow.ButtonText("Unpause".Translate(), null, true, false)) + if (widgetRow.ButtonText("Unpause".Translate(), (string)null, true, false)) { this.paused = false; } diff --git a/Assembly-CSharp/RimWorld/Bill_ProductionWithUft.cs b/Assembly-CSharp/RimWorld/Bill_ProductionWithUft.cs index a2232c77b..fe9ff8b87 100644 --- a/Assembly-CSharp/RimWorld/Bill_ProductionWithUft.cs +++ b/Assembly-CSharp/RimWorld/Bill_ProductionWithUft.cs @@ -1,4 +1,3 @@ -using System; using System.Collections.Generic; using Verse; @@ -16,10 +15,7 @@ protected override string StatusString { return (string.Empty + base.StatusString).Trim(); } - return ("BoundWorkerIs".Translate(new object[] - { - this.BoundWorker.NameStringShort - }) + base.StatusString).Trim(); + return ("BoundWorkerIs".Translate(this.BoundWorker.NameStringShort) + base.StatusString).Trim(); } } @@ -32,31 +28,34 @@ public Pawn BoundWorker return null; } Pawn creator = this.boundUftInt.Creator; - if (creator == null || creator.Downed || creator.HostFaction != null || creator.Destroyed || !creator.Spawned) - { - this.boundUftInt = null; - return null; - } - Thing thing = this.billStack.billGiver as Thing; - if (thing != null) + if (creator != null && !creator.Downed && creator.HostFaction == null && !creator.Destroyed && creator.Spawned) { - WorkTypeDef workTypeDef = null; - List allDefsListForReading = DefDatabase.AllDefsListForReading; - for (int i = 0; i < allDefsListForReading.Count; i++) + Thing thing = base.billStack.billGiver as Thing; + if (thing != null) { - if (allDefsListForReading[i].fixedBillGiverDefs != null && allDefsListForReading[i].fixedBillGiverDefs.Contains(thing.def)) + WorkTypeDef workTypeDef = null; + List allDefsListForReading = DefDatabase.AllDefsListForReading; + int num = 0; + while (num < allDefsListForReading.Count) { - workTypeDef = allDefsListForReading[i].workType; + if (allDefsListForReading[num].fixedBillGiverDefs == null || !allDefsListForReading[num].fixedBillGiverDefs.Contains(thing.def)) + { + num++; + continue; + } + workTypeDef = allDefsListForReading[num].workType; break; } + if (workTypeDef != null && !creator.workSettings.WorkIsActive(workTypeDef)) + { + this.boundUftInt = null; + return null; + } } - if (workTypeDef != null && !creator.workSettings.WorkIsActive(workTypeDef)) - { - this.boundUftInt = null; - return null; - } + return creator; } - return creator; + this.boundUftInt = null; + return null; } } @@ -78,21 +77,20 @@ public Bill_ProductionWithUft(RecipeDef recipe) : base(recipe) public void SetBoundUft(UnfinishedThing value, bool setOtherLink = true) { - if (value == this.boundUftInt) + if (value != this.boundUftInt) { - return; - } - UnfinishedThing unfinishedThing = this.boundUftInt; - this.boundUftInt = value; - if (setOtherLink) - { - if (unfinishedThing != null && unfinishedThing.BoundBill == this) - { - unfinishedThing.BoundBill = null; - } - if (value != null && value.BoundBill != this) + UnfinishedThing unfinishedThing = this.boundUftInt; + this.boundUftInt = value; + if (setOtherLink) { - this.boundUftInt.BoundBill = this; + if (unfinishedThing != null && unfinishedThing.BoundBill == this) + { + unfinishedThing.BoundBill = null; + } + if (value != null && value.BoundBill != this) + { + this.boundUftInt.BoundBill = this; + } } } } diff --git a/Assembly-CSharp/RimWorld/BiomeAnimalRecord.cs b/Assembly-CSharp/RimWorld/BiomeAnimalRecord.cs index a6a9308e3..a6a801e55 100644 --- a/Assembly-CSharp/RimWorld/BiomeAnimalRecord.cs +++ b/Assembly-CSharp/RimWorld/BiomeAnimalRecord.cs @@ -1,4 +1,3 @@ -using System; using System.Xml; using Verse; diff --git a/Assembly-CSharp/RimWorld/BiomeDef.cs b/Assembly-CSharp/RimWorld/BiomeDef.cs index 4e4c72aae..67b161105 100644 --- a/Assembly-CSharp/RimWorld/BiomeDef.cs +++ b/Assembly-CSharp/RimWorld/BiomeDef.cs @@ -83,7 +83,7 @@ public Material DrawMaterial { get { - if (this.cachedMat == null) + if ((UnityEngine.Object)this.cachedMat == (UnityEngine.Object)null) { if (this.texture.NullOrEmpty()) { @@ -111,11 +111,13 @@ public IEnumerable AllWildPlants { get { - BiomeDef.<>c__Iterator8C <>c__Iterator8C = new BiomeDef.<>c__Iterator8C(); - <>c__Iterator8C.<>f__this = this; - BiomeDef.<>c__Iterator8C expr_0E = <>c__Iterator8C; - expr_0E.$PC = -2; - return expr_0E; + foreach (ThingDef allDef in DefDatabase.AllDefs) + { + if (allDef.category == ThingCategory.Plant && this.CommonalityOfPlant(allDef) > 0.0) + { + yield return allDef; + } + } } } @@ -123,11 +125,13 @@ public IEnumerable AllWildAnimals { get { - BiomeDef.<>c__Iterator8D <>c__Iterator8D = new BiomeDef.<>c__Iterator8D(); - <>c__Iterator8D.<>f__this = this; - BiomeDef.<>c__Iterator8D expr_0E = <>c__Iterator8D; - expr_0E.$PC = -2; - return expr_0E; + foreach (PawnKindDef allDef in DefDatabase.AllDefs) + { + if (this.CommonalityOfAnimal(allDef) > 0.0) + { + yield return allDef; + } + } } } @@ -140,21 +144,21 @@ public float CommonalityOfAnimal(PawnKindDef animalDef) { this.cachedAnimalCommonalities.Add(this.wildAnimals[i].animal, this.wildAnimals[i].commonality); } - foreach (PawnKindDef current in DefDatabase.AllDefs) + foreach (PawnKindDef allDef in DefDatabase.AllDefs) { - if (current.RaceProps.wildBiomes != null) + if (allDef.RaceProps.wildBiomes != null) { - for (int j = 0; j < current.RaceProps.wildBiomes.Count; j++) + for (int j = 0; j < allDef.RaceProps.wildBiomes.Count; j++) { - if (current.RaceProps.wildBiomes[j].biome == this) + if (allDef.RaceProps.wildBiomes[j].biome == this) { - this.cachedAnimalCommonalities.Add(current, current.RaceProps.wildBiomes[j].commonality); + this.cachedAnimalCommonalities.Add(allDef, allDef.RaceProps.wildBiomes[j].commonality); } } } } } - float result; + float result = default(float); if (this.cachedAnimalCommonalities.TryGetValue(animalDef, out result)) { return result; @@ -171,21 +175,21 @@ public float CommonalityOfPlant(ThingDef plantDef) { this.cachedPlantCommonalities.Add(this.wildPlants[i].plant, this.wildPlants[i].commonality); } - foreach (ThingDef current in DefDatabase.AllDefs) + foreach (ThingDef allDef in DefDatabase.AllDefs) { - if (current.plant != null && current.plant.wildBiomes != null) + if (allDef.plant != null && allDef.plant.wildBiomes != null) { - for (int j = 0; j < current.plant.wildBiomes.Count; j++) + for (int j = 0; j < allDef.plant.wildBiomes.Count; j++) { - if (current.plant.wildBiomes[j].biome == this) + if (allDef.plant.wildBiomes[j].biome == this) { - this.cachedPlantCommonalities.Add(current, current.plant.wildBiomes[j].commonality); + this.cachedPlantCommonalities.Add(allDef, allDef.plant.wildBiomes[j].commonality); } } } } } - float result; + float result = default(float); if (this.cachedPlantCommonalities.TryGetValue(plantDef, out result)) { return result; @@ -202,21 +206,21 @@ public float CommonalityOfDisease(IncidentDef diseaseInc) { this.cachedDiseaseCommonalities.Add(this.diseases[i].diseaseInc, this.diseases[i].commonality); } - foreach (IncidentDef current in DefDatabase.AllDefs) + foreach (IncidentDef allDef in DefDatabase.AllDefs) { - if (current.diseaseBiomeRecords != null) + if (allDef.diseaseBiomeRecords != null) { - for (int j = 0; j < current.diseaseBiomeRecords.Count; j++) + for (int j = 0; j < allDef.diseaseBiomeRecords.Count; j++) { - if (current.diseaseBiomeRecords[j].biome == this) + if (allDef.diseaseBiomeRecords[j].biome == this) { - this.cachedDiseaseCommonalities.Add(current.diseaseBiomeRecords[j].diseaseInc, current.diseaseBiomeRecords[j].commonality); + this.cachedDiseaseCommonalities.Add(allDef.diseaseBiomeRecords[j].diseaseInc, allDef.diseaseBiomeRecords[j].commonality); } } } } } - float result; + float result = default(float); if (this.cachedDiseaseCommonalities.TryGetValue(diseaseInc, out result)) { return result; diff --git a/Assembly-CSharp/RimWorld/BiomeDefOf.cs b/Assembly-CSharp/RimWorld/BiomeDefOf.cs index 3437d1830..c14b65936 100644 --- a/Assembly-CSharp/RimWorld/BiomeDefOf.cs +++ b/Assembly-CSharp/RimWorld/BiomeDefOf.cs @@ -1,5 +1,3 @@ -using System; - namespace RimWorld { [DefOf] diff --git a/Assembly-CSharp/RimWorld/BiomeDiseaseRecord.cs b/Assembly-CSharp/RimWorld/BiomeDiseaseRecord.cs index a5ee851e8..63af254ad 100644 --- a/Assembly-CSharp/RimWorld/BiomeDiseaseRecord.cs +++ b/Assembly-CSharp/RimWorld/BiomeDiseaseRecord.cs @@ -1,5 +1,3 @@ -using System; - namespace RimWorld { public class BiomeDiseaseRecord diff --git a/Assembly-CSharp/RimWorld/BiomePlantRecord.cs b/Assembly-CSharp/RimWorld/BiomePlantRecord.cs index fb4bd5c7a..db1b114b7 100644 --- a/Assembly-CSharp/RimWorld/BiomePlantRecord.cs +++ b/Assembly-CSharp/RimWorld/BiomePlantRecord.cs @@ -1,4 +1,3 @@ -using System; using System.Xml; using Verse; diff --git a/Assembly-CSharp/RimWorld/BiomeWorker.cs b/Assembly-CSharp/RimWorld/BiomeWorker.cs index a1429c391..3ae09965d 100644 --- a/Assembly-CSharp/RimWorld/BiomeWorker.cs +++ b/Assembly-CSharp/RimWorld/BiomeWorker.cs @@ -1,5 +1,4 @@ using RimWorld.Planet; -using System; namespace RimWorld { diff --git a/Assembly-CSharp/RimWorld/BiomeWorker_AridShrubland.cs b/Assembly-CSharp/RimWorld/BiomeWorker_AridShrubland.cs index a5afb21a7..cd1ab83ba 100644 --- a/Assembly-CSharp/RimWorld/BiomeWorker_AridShrubland.cs +++ b/Assembly-CSharp/RimWorld/BiomeWorker_AridShrubland.cs @@ -1,5 +1,4 @@ using RimWorld.Planet; -using System; namespace RimWorld { @@ -11,15 +10,15 @@ public override float GetScore(Tile tile) { return -100f; } - if (tile.temperature < -10f) + if (tile.temperature < -10.0) { return 0f; } - if (tile.rainfall < 600f || tile.rainfall >= 2000f) + if (!(tile.rainfall < 600.0) && !(tile.rainfall >= 2000.0)) { - return 0f; + return (float)(22.5 + (tile.temperature - 20.0) * 2.2000000476837158 + (tile.rainfall - 600.0) / 100.0); } - return 22.5f + (tile.temperature - 20f) * 2.2f + (tile.rainfall - 600f) / 100f; + return 0f; } } } diff --git a/Assembly-CSharp/RimWorld/BiomeWorker_BorealForest.cs b/Assembly-CSharp/RimWorld/BiomeWorker_BorealForest.cs index ba96dce0e..8519f6283 100644 --- a/Assembly-CSharp/RimWorld/BiomeWorker_BorealForest.cs +++ b/Assembly-CSharp/RimWorld/BiomeWorker_BorealForest.cs @@ -1,5 +1,4 @@ using RimWorld.Planet; -using System; namespace RimWorld { @@ -11,11 +10,11 @@ public override float GetScore(Tile tile) { return -100f; } - if (tile.temperature < -10f) + if (tile.temperature < -10.0) { return 0f; } - if (tile.rainfall < 600f) + if (tile.rainfall < 600.0) { return 0f; } diff --git a/Assembly-CSharp/RimWorld/BiomeWorker_Desert.cs b/Assembly-CSharp/RimWorld/BiomeWorker_Desert.cs index c8f88f438..e069c92b7 100644 --- a/Assembly-CSharp/RimWorld/BiomeWorker_Desert.cs +++ b/Assembly-CSharp/RimWorld/BiomeWorker_Desert.cs @@ -1,5 +1,4 @@ using RimWorld.Planet; -using System; namespace RimWorld { @@ -11,11 +10,11 @@ public override float GetScore(Tile tile) { return -100f; } - if (tile.rainfall >= 600f) + if (tile.rainfall >= 600.0) { return 0f; } - return tile.temperature + 0.0001f; + return (float)(tile.temperature + 9.9999997473787516E-05); } } } diff --git a/Assembly-CSharp/RimWorld/BiomeWorker_ExtremeDesert.cs b/Assembly-CSharp/RimWorld/BiomeWorker_ExtremeDesert.cs index 9594dbc63..22b5be793 100644 --- a/Assembly-CSharp/RimWorld/BiomeWorker_ExtremeDesert.cs +++ b/Assembly-CSharp/RimWorld/BiomeWorker_ExtremeDesert.cs @@ -1,5 +1,4 @@ using RimWorld.Planet; -using System; namespace RimWorld { @@ -11,11 +10,11 @@ public override float GetScore(Tile tile) { return -100f; } - if (tile.rainfall >= 340f) + if (tile.rainfall >= 340.0) { return 0f; } - return tile.temperature * 2.7f - 13f - tile.rainfall * 0.14f; + return (float)(tile.temperature * 2.7000000476837158 - 13.0 - tile.rainfall * 0.14000000059604645); } } } diff --git a/Assembly-CSharp/RimWorld/BiomeWorker_IceSheet.cs b/Assembly-CSharp/RimWorld/BiomeWorker_IceSheet.cs index 1c57fcad0..cc348bebc 100644 --- a/Assembly-CSharp/RimWorld/BiomeWorker_IceSheet.cs +++ b/Assembly-CSharp/RimWorld/BiomeWorker_IceSheet.cs @@ -1,5 +1,4 @@ using RimWorld.Planet; -using System; namespace RimWorld { @@ -16,7 +15,7 @@ public override float GetScore(Tile tile) public static float PermaIceScore(Tile tile) { - return -20f + -tile.temperature * 2f; + return (float)(-20.0 + (0.0 - tile.temperature) * 2.0); } } } diff --git a/Assembly-CSharp/RimWorld/BiomeWorker_Ocean.cs b/Assembly-CSharp/RimWorld/BiomeWorker_Ocean.cs index 9fdc25045..858c1df57 100644 --- a/Assembly-CSharp/RimWorld/BiomeWorker_Ocean.cs +++ b/Assembly-CSharp/RimWorld/BiomeWorker_Ocean.cs @@ -1,5 +1,4 @@ using RimWorld.Planet; -using System; namespace RimWorld { diff --git a/Assembly-CSharp/RimWorld/BiomeWorker_SeaIce.cs b/Assembly-CSharp/RimWorld/BiomeWorker_SeaIce.cs index 7efe861d5..e9ae3e09f 100644 --- a/Assembly-CSharp/RimWorld/BiomeWorker_SeaIce.cs +++ b/Assembly-CSharp/RimWorld/BiomeWorker_SeaIce.cs @@ -1,5 +1,4 @@ using RimWorld.Planet; -using System; namespace RimWorld { @@ -11,7 +10,7 @@ public override float GetScore(Tile tile) { return -100f; } - return BiomeWorker_IceSheet.PermaIceScore(tile) - 23f; + return (float)(BiomeWorker_IceSheet.PermaIceScore(tile) - 23.0); } } } diff --git a/Assembly-CSharp/RimWorld/BiomeWorker_TemperateForest.cs b/Assembly-CSharp/RimWorld/BiomeWorker_TemperateForest.cs index c23717507..79ba640c1 100644 --- a/Assembly-CSharp/RimWorld/BiomeWorker_TemperateForest.cs +++ b/Assembly-CSharp/RimWorld/BiomeWorker_TemperateForest.cs @@ -1,5 +1,4 @@ using RimWorld.Planet; -using System; namespace RimWorld { @@ -11,15 +10,15 @@ public override float GetScore(Tile tile) { return -100f; } - if (tile.temperature < -10f) + if (tile.temperature < -10.0) { return 0f; } - if (tile.rainfall < 600f) + if (tile.rainfall < 600.0) { return 0f; } - return 15f + (tile.temperature - 7f) + (tile.rainfall - 600f) / 180f; + return (float)(15.0 + (tile.temperature - 7.0) + (tile.rainfall - 600.0) / 180.0); } } } diff --git a/Assembly-CSharp/RimWorld/BiomeWorker_TropicalRainforest.cs b/Assembly-CSharp/RimWorld/BiomeWorker_TropicalRainforest.cs index 4ce5d7d1d..5b6fc278f 100644 --- a/Assembly-CSharp/RimWorld/BiomeWorker_TropicalRainforest.cs +++ b/Assembly-CSharp/RimWorld/BiomeWorker_TropicalRainforest.cs @@ -1,5 +1,4 @@ using RimWorld.Planet; -using System; namespace RimWorld { @@ -11,15 +10,15 @@ public override float GetScore(Tile tile) { return -100f; } - if (tile.temperature < 15f) + if (tile.temperature < 15.0) { return 0f; } - if (tile.rainfall < 2000f) + if (tile.rainfall < 2000.0) { return 0f; } - return 28f + (tile.temperature - 20f) * 1.5f + (tile.rainfall - 600f) / 165f; + return (float)(28.0 + (tile.temperature - 20.0) * 1.5 + (tile.rainfall - 600.0) / 165.0); } } } diff --git a/Assembly-CSharp/RimWorld/BiomeWorker_Tundra.cs b/Assembly-CSharp/RimWorld/BiomeWorker_Tundra.cs index 4f79c5d8f..99d1fea14 100644 --- a/Assembly-CSharp/RimWorld/BiomeWorker_Tundra.cs +++ b/Assembly-CSharp/RimWorld/BiomeWorker_Tundra.cs @@ -1,5 +1,4 @@ using RimWorld.Planet; -using System; namespace RimWorld { @@ -11,7 +10,7 @@ public override float GetScore(Tile tile) { return -100f; } - return -tile.temperature; + return (float)(0.0 - tile.temperature); } } } diff --git a/Assembly-CSharp/RimWorld/Blueprint.cs b/Assembly-CSharp/RimWorld/Blueprint.cs index 35fd83d71..008707542 100644 --- a/Assembly-CSharp/RimWorld/Blueprint.cs +++ b/Assembly-CSharp/RimWorld/Blueprint.cs @@ -1,4 +1,3 @@ -using System; using System.Collections.Generic; using System.Text; using Verse; @@ -14,7 +13,7 @@ public override string Label { get { - return this.def.entityDefToBuild.label + "BlueprintLabelExtra".Translate(); + return base.def.entityDefToBuild.label + "BlueprintLabelExtra".Translate(); } } @@ -26,7 +25,7 @@ protected abstract float WorkTotal public override void Tick() { base.Tick(); - if (!GenConstruct.CanBuildOnTerrain(this.def.entityDefToBuild, base.Position, base.Map, base.Rotation, null)) + if (!GenConstruct.CanBuildOnTerrain(base.def.entityDefToBuild, base.Position, base.Map, base.Rotation, null)) { this.Destroy(DestroyMode.Cancel); } @@ -34,7 +33,7 @@ public override void Tick() public override void Draw() { - if (this.def.drawerType == DrawerType.RealtimeOnly) + if (base.def.drawerType == DrawerType.RealtimeOnly) { base.Draw(); } @@ -57,18 +56,7 @@ public virtual bool TryReplaceWithSolidThing(Pawn workerPawn, out Thing createdT Thing thing = this.FirstBlockingThing(null, null, false); if (thing != null) { - Log.Error(string.Concat(new object[] - { - workerPawn, - " tried to replace blueprint ", - this.ToString(), - " at ", - base.Position, - " with solid thing, but it is blocked by ", - thing, - " at ", - thing.Position - })); + Log.Error(workerPawn + " tried to replace blueprint " + this.ToString() + " at " + base.Position + " with solid thing, but it is blocked by " + thing + " at " + thing.Position); if (thing != workerPawn) { createdThing = null; @@ -105,7 +93,7 @@ public virtual bool TryReplaceWithSolidThing(Pawn workerPawn, out Thing createdT public Thing BlockingHaulableOnTop() { - if (this.def.entityDefToBuild.passability == Traversability.Standable) + if (base.def.entityDefToBuild.passability == Traversability.Standable) { return null; } @@ -135,12 +123,9 @@ public Thing FirstBlockingThing(Pawn pawnToIgnore = null, Thing thingToIgnore = for (int i = 0; i < thingList.Count; i++) { Thing thing = thingList[i]; - if (!haulableOnly || thing.def.EverHaulable) + if ((!haulableOnly || thing.def.EverHaulable) && GenConstruct.BlocksFramePlacement(this, thing) && thing != pawnToIgnore && thing != thingToIgnore) { - if (GenConstruct.BlocksFramePlacement(this, thing) && thing != pawnToIgnore && thing != thingToIgnore) - { - return thing; - } + return thing; } } iterator.MoveNext(); diff --git a/Assembly-CSharp/RimWorld/Blueprint_Build.cs b/Assembly-CSharp/RimWorld/Blueprint_Build.cs index 4683b2825..2bb41e164 100644 --- a/Assembly-CSharp/RimWorld/Blueprint_Build.cs +++ b/Assembly-CSharp/RimWorld/Blueprint_Build.cs @@ -1,6 +1,5 @@ using System; using System.Collections.Generic; -using System.Diagnostics; using System.Text; using Verse; @@ -17,11 +16,7 @@ public override string Label string label = base.Label; if (this.stuffToUse != null) { - return "ThingMadeOfStuffLabel".Translate(new object[] - { - this.stuffToUse.LabelAsStuff, - label - }); + return "ThingMadeOfStuffLabel".Translate(this.stuffToUse.LabelAsStuff, label); } return label; } @@ -31,7 +26,7 @@ protected override float WorkTotal { get { - return this.def.entityDefToBuild.GetStatValueAbstract(StatDefOf.WorkToBuild, this.stuffToUse); + return base.def.entityDefToBuild.GetStatValueAbstract(StatDefOf.WorkToBuild, this.stuffToUse); } } @@ -48,22 +43,25 @@ public override ThingDef UIStuff() public override List MaterialsNeeded() { - return this.def.entityDefToBuild.CostListAdjusted(this.stuffToUse, true); + return base.def.entityDefToBuild.CostListAdjusted(this.stuffToUse, true); } protected override Thing MakeSolidThing() { - return ThingMaker.MakeThing(this.def.entityDefToBuild.frameDef, this.stuffToUse); + return ThingMaker.MakeThing(base.def.entityDefToBuild.frameDef, this.stuffToUse); } - [DebuggerHidden] public override IEnumerable GetGizmos() { - Blueprint_Build.c__Iterator143 c__Iterator = new Blueprint_Build.c__Iterator143(); - c__Iterator.<>f__this = this; - Blueprint_Build.c__Iterator143 expr_0E = c__Iterator; - expr_0E.$PC = -2; - return expr_0E; + foreach (Gizmo gizmo in base.GetGizmos()) + { + yield return gizmo; + } + Command buildCopy = BuildCopyCommandUtility.BuildCopyCommand(base.def.entityDefToBuild, this.stuffToUse); + if (buildCopy != null) + { + yield return (Gizmo)buildCopy; + } } public override string GetInspectString() @@ -76,14 +74,23 @@ public override string GetInspectString() } stringBuilder.AppendLine("ContainedResources".Translate() + ":"); bool flag = true; - foreach (ThingCountClass current in this.MaterialsNeeded()) + List.Enumerator enumerator = this.MaterialsNeeded().GetEnumerator(); + try { - if (!flag) + while (enumerator.MoveNext()) { - stringBuilder.AppendLine(); + ThingCountClass current = enumerator.Current; + if (!flag) + { + stringBuilder.AppendLine(); + } + stringBuilder.Append(current.thingDef.LabelCap + ": 0 / " + current.count); + flag = false; } - stringBuilder.Append(current.thingDef.LabelCap + ": 0 / " + current.count); - flag = false; + } + finally + { + ((IDisposable)(object)enumerator).Dispose(); } return stringBuilder.ToString().Trim(); } diff --git a/Assembly-CSharp/RimWorld/Blueprint_Door.cs b/Assembly-CSharp/RimWorld/Blueprint_Door.cs index c1f941bb2..2cf8e222c 100644 --- a/Assembly-CSharp/RimWorld/Blueprint_Door.cs +++ b/Assembly-CSharp/RimWorld/Blueprint_Door.cs @@ -1,5 +1,3 @@ -using System; - namespace RimWorld { public class Blueprint_Door : Blueprint_Build diff --git a/Assembly-CSharp/RimWorld/Blueprint_Install.cs b/Assembly-CSharp/RimWorld/Blueprint_Install.cs index d60464a0c..f4700c154 100644 --- a/Assembly-CSharp/RimWorld/Blueprint_Install.cs +++ b/Assembly-CSharp/RimWorld/Blueprint_Install.cs @@ -1,6 +1,5 @@ using System; using System.Collections.Generic; -using System.Diagnostics; using Verse; using Verse.Sound; @@ -88,14 +87,17 @@ public override bool TryReplaceWithSolidThing(Pawn workerPawn, out Thing created return flag; } - [DebuggerHidden] public override IEnumerable GetGizmos() { - Blueprint_Install.c__Iterator144 c__Iterator = new Blueprint_Install.c__Iterator144(); - c__Iterator.<>f__this = this; - Blueprint_Install.c__Iterator144 expr_0E = c__Iterator; - expr_0E.$PC = -2; - return expr_0E; + foreach (Gizmo gizmo in base.GetGizmos()) + { + yield return gizmo; + } + Command buildCopy = BuildCopyCommandUtility.BuildCopyCommand(this.ThingToInstall.def, this.ThingToInstall.Stuff); + if (buildCopy != null) + { + yield return (Gizmo)buildCopy; + } } internal void SetThingToInstallFromMinified(MinifiedThing itemToInstall) @@ -109,10 +111,12 @@ internal void SetBuildingToReinstall(Building buildingToReinstall) if (!buildingToReinstall.def.Minifiable) { Log.Error("Tried to reinstall non-minifiable building."); - return; } - this.miniToInstall = null; - this.buildingToReinstall = buildingToReinstall; + else + { + this.miniToInstall = null; + this.buildingToReinstall = buildingToReinstall; + } } } } diff --git a/Assembly-CSharp/RimWorld/BodyDefOf.cs b/Assembly-CSharp/RimWorld/BodyDefOf.cs index 675fbcb3b..e2402838b 100644 --- a/Assembly-CSharp/RimWorld/BodyDefOf.cs +++ b/Assembly-CSharp/RimWorld/BodyDefOf.cs @@ -1,4 +1,3 @@ -using System; using Verse; namespace RimWorld diff --git a/Assembly-CSharp/RimWorld/BodyPartDefOf.cs b/Assembly-CSharp/RimWorld/BodyPartDefOf.cs index f8877c6d1..4ae931749 100644 --- a/Assembly-CSharp/RimWorld/BodyPartDefOf.cs +++ b/Assembly-CSharp/RimWorld/BodyPartDefOf.cs @@ -1,4 +1,3 @@ -using System; using Verse; namespace RimWorld diff --git a/Assembly-CSharp/RimWorld/BodyPartGroupDefOf.cs b/Assembly-CSharp/RimWorld/BodyPartGroupDefOf.cs index bdd17ef06..4c6b8e483 100644 --- a/Assembly-CSharp/RimWorld/BodyPartGroupDefOf.cs +++ b/Assembly-CSharp/RimWorld/BodyPartGroupDefOf.cs @@ -1,4 +1,3 @@ -using System; using Verse; namespace RimWorld diff --git a/Assembly-CSharp/RimWorld/BodyType.cs b/Assembly-CSharp/RimWorld/BodyType.cs index 6bde2aabb..5060c1b17 100644 --- a/Assembly-CSharp/RimWorld/BodyType.cs +++ b/Assembly-CSharp/RimWorld/BodyType.cs @@ -1,14 +1,12 @@ -using System; - namespace RimWorld { public enum BodyType : byte { - Undefined, - Male, - Female, - Thin, - Hulk, - Fat + Undefined = 0, + Male = 1, + Female = 2, + Thin = 3, + Hulk = 4, + Fat = 5 } } diff --git a/Assembly-CSharp/RimWorld/BreakRiskAlertUtility.cs b/Assembly-CSharp/RimWorld/BreakRiskAlertUtility.cs index 91f17560a..b50b47519 100644 --- a/Assembly-CSharp/RimWorld/BreakRiskAlertUtility.cs +++ b/Assembly-CSharp/RimWorld/BreakRiskAlertUtility.cs @@ -1,4 +1,3 @@ -using System; using System.Collections.Generic; using System.Linq; using System.Text; @@ -12,10 +11,13 @@ public static IEnumerable PawnsAtRiskExtreme { get { - BreakRiskAlertUtility.<>c__Iterator18C <>c__Iterator18C = new BreakRiskAlertUtility.<>c__Iterator18C(); - BreakRiskAlertUtility.<>c__Iterator18C expr_07 = <>c__Iterator18C; - expr_07.$PC = -2; - return expr_07; + foreach (Pawn item in PawnsFinder.AllMaps_FreeColonistsSpawned) + { + if (!item.Downed && item.mindState.mentalBreaker.BreakExtremeIsImminent) + { + yield return item; + } + } } } @@ -23,10 +25,13 @@ public static IEnumerable PawnsAtRiskMajor { get { - BreakRiskAlertUtility.<>c__Iterator18D <>c__Iterator18D = new BreakRiskAlertUtility.<>c__Iterator18D(); - BreakRiskAlertUtility.<>c__Iterator18D expr_07 = <>c__Iterator18D; - expr_07.$PC = -2; - return expr_07; + foreach (Pawn item in PawnsFinder.AllMaps_FreeColonistsSpawned) + { + if (!item.Downed && item.mindState.mentalBreaker.BreakMajorIsImminent) + { + yield return item; + } + } } } @@ -34,10 +39,13 @@ public static IEnumerable PawnsAtRiskMinor { get { - BreakRiskAlertUtility.<>c__Iterator18E <>c__Iterator18E = new BreakRiskAlertUtility.<>c__Iterator18E(); - BreakRiskAlertUtility.<>c__Iterator18E expr_07 = <>c__Iterator18E; - expr_07.$PC = -2; - return expr_07; + foreach (Pawn item in PawnsFinder.AllMaps_FreeColonistsSpawned) + { + if (!item.Downed && item.mindState.mentalBreaker.BreakMinorIsImminent) + { + yield return item; + } + } } } @@ -45,7 +53,7 @@ public static string AlertLabel { get { - int num = BreakRiskAlertUtility.PawnsAtRiskExtreme.Count(); + int num = BreakRiskAlertUtility.PawnsAtRiskExtreme.Count(); string text; if (num > 0) { @@ -53,14 +61,14 @@ public static string AlertLabel } else { - num = BreakRiskAlertUtility.PawnsAtRiskMajor.Count(); + num = BreakRiskAlertUtility.PawnsAtRiskMajor.Count(); if (num > 0) { text = "BreakRiskMajor".Translate(); } else { - num = BreakRiskAlertUtility.PawnsAtRiskMinor.Count(); + num = BreakRiskAlertUtility.PawnsAtRiskMinor.Count(); text = "BreakRiskMinor".Translate(); } } @@ -77,49 +85,40 @@ public static string AlertExplanation get { StringBuilder stringBuilder = new StringBuilder(); - if (BreakRiskAlertUtility.PawnsAtRiskExtreme.Any()) + if (BreakRiskAlertUtility.PawnsAtRiskExtreme.Any()) { StringBuilder stringBuilder2 = new StringBuilder(); - foreach (Pawn current in BreakRiskAlertUtility.PawnsAtRiskExtreme) + foreach (Pawn item in BreakRiskAlertUtility.PawnsAtRiskExtreme) { - stringBuilder2.AppendLine(" " + current.NameStringShort); + stringBuilder2.AppendLine(" " + item.NameStringShort); } - stringBuilder.Append("BreakRiskExtremeDesc".Translate(new object[] - { - stringBuilder2 - })); + stringBuilder.Append("BreakRiskExtremeDesc".Translate(stringBuilder2)); } - if (BreakRiskAlertUtility.PawnsAtRiskMajor.Any()) + if (BreakRiskAlertUtility.PawnsAtRiskMajor.Any()) { if (stringBuilder.Length != 0) { stringBuilder.AppendLine(); } StringBuilder stringBuilder3 = new StringBuilder(); - foreach (Pawn current2 in BreakRiskAlertUtility.PawnsAtRiskMajor) + foreach (Pawn item2 in BreakRiskAlertUtility.PawnsAtRiskMajor) { - stringBuilder3.AppendLine(" " + current2.NameStringShort); + stringBuilder3.AppendLine(" " + item2.NameStringShort); } - stringBuilder.Append("BreakRiskMajorDesc".Translate(new object[] - { - stringBuilder3 - })); + stringBuilder.Append("BreakRiskMajorDesc".Translate(stringBuilder3)); } - if (BreakRiskAlertUtility.PawnsAtRiskMinor.Any()) + if (BreakRiskAlertUtility.PawnsAtRiskMinor.Any()) { if (stringBuilder.Length != 0) { stringBuilder.AppendLine(); } StringBuilder stringBuilder4 = new StringBuilder(); - foreach (Pawn current3 in BreakRiskAlertUtility.PawnsAtRiskMinor) + foreach (Pawn item3 in BreakRiskAlertUtility.PawnsAtRiskMinor) { - stringBuilder4.AppendLine(" " + current3.NameStringShort); + stringBuilder4.AppendLine(" " + item3.NameStringShort); } - stringBuilder.Append("BreakRiskMinorDesc".Translate(new object[] - { - stringBuilder4 - })); + stringBuilder.Append("BreakRiskMinorDesc".Translate(stringBuilder4)); } stringBuilder.AppendLine(); stringBuilder.Append("BreakRiskDescEnding".Translate()); diff --git a/Assembly-CSharp/RimWorld/BreakdownManager.cs b/Assembly-CSharp/RimWorld/BreakdownManager.cs index 303a9e9fc..03631233d 100644 --- a/Assembly-CSharp/RimWorld/BreakdownManager.cs +++ b/Assembly-CSharp/RimWorld/BreakdownManager.cs @@ -1,4 +1,3 @@ -using System; using System.Collections.Generic; using Verse; diff --git a/Assembly-CSharp/RimWorld/BreakdownableUtility.cs b/Assembly-CSharp/RimWorld/BreakdownableUtility.cs index 25b90cb88..3cbb45d9a 100644 --- a/Assembly-CSharp/RimWorld/BreakdownableUtility.cs +++ b/Assembly-CSharp/RimWorld/BreakdownableUtility.cs @@ -1,4 +1,3 @@ -using System; using Verse; namespace RimWorld @@ -8,7 +7,11 @@ public static class BreakdownableUtility public static bool IsBrokenDown(this Thing t) { CompBreakdownable compBreakdownable = t.TryGetComp(); - return compBreakdownable != null && compBreakdownable.BrokenDown; + if (compBreakdownable != null) + { + return compBreakdownable.BrokenDown; + } + return false; } } } diff --git a/Assembly-CSharp/RimWorld/BuildCopyCommandUtility.cs b/Assembly-CSharp/RimWorld/BuildCopyCommandUtility.cs index 0b628b5c8..2c1b964cb 100644 --- a/Assembly-CSharp/RimWorld/BuildCopyCommandUtility.cs +++ b/Assembly-CSharp/RimWorld/BuildCopyCommandUtility.cs @@ -19,7 +19,7 @@ public static Command BuildCopyCommand(BuildableDef buildable, ThingDef stuff) return null; } Command_Action command_Action = new Command_Action(); - command_Action.action = delegate + command_Action.action = (Action)delegate() { SoundDefOf.SelectDesignator.PlayOneShotOnCamera(null); des.SetStuffDef(stuff); diff --git a/Assembly-CSharp/RimWorld/BuildDesignatorUtility.cs b/Assembly-CSharp/RimWorld/BuildDesignatorUtility.cs index d44925f6a..1500cc14f 100644 --- a/Assembly-CSharp/RimWorld/BuildDesignatorUtility.cs +++ b/Assembly-CSharp/RimWorld/BuildDesignatorUtility.cs @@ -1,4 +1,3 @@ -using System; using Verse; namespace RimWorld @@ -8,8 +7,10 @@ public static class BuildDesignatorUtility public static void TryDrawPowerGridAndAnticipatedConnection(BuildableDef def) { ThingDef thingDef = def as ThingDef; - if (thingDef != null && (thingDef.EverTransmitsPower || thingDef.ConnectToPower)) + if (thingDef != null) { + if (!thingDef.EverTransmitsPower && !thingDef.ConnectToPower) + return; OverlayDrawHandler.DrawPowerGridOverlayThisFrame(); if (thingDef.ConnectToPower) { diff --git a/Assembly-CSharp/RimWorld/BuildingProperties.cs b/Assembly-CSharp/RimWorld/BuildingProperties.cs index 61b76ccd4..faf7aa82e 100644 --- a/Assembly-CSharp/RimWorld/BuildingProperties.cs +++ b/Assembly-CSharp/RimWorld/BuildingProperties.cs @@ -1,6 +1,5 @@ using System; using System.Collections.Generic; -using System.Diagnostics; using UnityEngine; using Verse; @@ -194,16 +193,20 @@ public bool IsMortar } } - [DebuggerHidden] public IEnumerable ConfigErrors(ThingDef parent) { - BuildingProperties.c__Iterator77 c__Iterator = new BuildingProperties.c__Iterator77(); - c__Iterator.parent = parent; - c__Iterator.<$>parent = parent; - c__Iterator.<>f__this = this; - BuildingProperties.c__Iterator77 expr_1C = c__Iterator; - expr_1C.$PC = -2; - return expr_1C; + if (this.isTrap && !this.isEdifice) + { + yield return "isTrap but is not edifice. Code will break."; + } + if (this.alwaysDeconstructible && !this.deconstructible) + { + yield return "alwaysDeconstructible=true but deconstructible=false"; + } + if (parent.holdsRoof && !this.isEdifice) + { + yield return "holds roof but is not an edifice."; + } } public void PostLoadSpecial(ThingDef parent) @@ -214,7 +217,7 @@ public void ResolveReferencesSpecial() { if (!this.turretTopGraphicPath.NullOrEmpty()) { - LongEventHandler.ExecuteWhenFinished(delegate + LongEventHandler.ExecuteWhenFinished((Action)delegate { this.turretTopMat = MaterialPool.MatFrom(this.turretTopGraphicPath); }); diff --git a/Assembly-CSharp/RimWorld/Building_AncientCryptosleepCasket.cs b/Assembly-CSharp/RimWorld/Building_AncientCryptosleepCasket.cs index d5e2629d0..3e69dcf08 100644 --- a/Assembly-CSharp/RimWorld/Building_AncientCryptosleepCasket.cs +++ b/Assembly-CSharp/RimWorld/Building_AncientCryptosleepCasket.cs @@ -1,6 +1,5 @@ using System; using System.Collections.Generic; -using System.Diagnostics; using System.Linq; using Verse; using Verse.AI.Group; @@ -20,56 +19,55 @@ public override void ExposeData() public override void PreApplyDamage(DamageInfo dinfo, out bool absorbed) { base.PreApplyDamage(dinfo, out absorbed); - if (absorbed) + if (!absorbed) { - return; - } - if (!this.contentsKnown && this.innerContainer.Count > 0 && dinfo.Def.harmsHealth && dinfo.Instigator != null && dinfo.Instigator.Faction != null) - { - bool flag = false; - foreach (Thing current in ((IEnumerable)this.innerContainer)) + if (!base.contentsKnown && base.innerContainer.Count > 0 && dinfo.Def.harmsHealth && dinfo.Instigator != null && dinfo.Instigator.Faction != null) { - Pawn pawn = current as Pawn; - if (pawn != null) + bool flag = false; + foreach (Thing item in (IEnumerable)base.innerContainer) { - flag = true; - break; + Pawn pawn = item as Pawn; + if (pawn != null) + { + flag = true; + break; + } + } + if (flag) + { + this.EjectContents(); } } - if (flag) - { - this.EjectContents(); - } + absorbed = false; } - absorbed = false; } public override void EjectContents() { List list = new List(); - if (!this.contentsKnown) + if (!base.contentsKnown) { - list.AddRange(this.innerContainer); - list.AddRange(this.UnopenedCasketsInGroup().SelectMany((Building_AncientCryptosleepCasket c) => c.innerContainer)); + list.AddRange(base.innerContainer); + list.AddRange(this.UnopenedCasketsInGroup().SelectMany((Func>)((Building_AncientCryptosleepCasket c) => c.innerContainer))); } - bool contentsKnown = this.contentsKnown; + bool contentsKnown = base.contentsKnown; base.EjectContents(); if (!contentsKnown) { ThingDef filthSlime = ThingDefOf.FilthSlime; FilthMaker.MakeFilth(base.Position, base.Map, filthSlime, Rand.Range(8, 12)); this.SetFaction(null, null); - foreach (Building_AncientCryptosleepCasket current in this.UnopenedCasketsInGroup()) + foreach (Building_AncientCryptosleepCasket item in this.UnopenedCasketsInGroup()) { - current.EjectContents(); + item.EjectContents(); } List source = (from t in list where t is Pawn - select t).Cast().ToList(); + select t).Cast().ToList(); IEnumerable enumerable = from p in source where p.RaceProps.Humanlike && p.GetLord() == null && p.Faction.def == FactionDefOf.SpacerHostile select p; - if (enumerable.Any()) + if (enumerable.Any()) { Faction faction = Find.FactionManager.FirstFactionOfDef(FactionDefOf.SpacerHostile); LordMaker.MakeNewLord(faction, new LordJob_AssaultColony(faction, false, false, false, false, false), base.Map, enumerable); @@ -77,14 +75,29 @@ where t is Pawn } } - [DebuggerHidden] private IEnumerable UnopenedCasketsInGroup() { - Building_AncientCryptosleepCasket.c__Iterator152 c__Iterator = new Building_AncientCryptosleepCasket.c__Iterator152(); - c__Iterator.<>f__this = this; - Building_AncientCryptosleepCasket.c__Iterator152 expr_0E = c__Iterator; - expr_0E.$PC = -2; - return expr_0E; + yield return this; + if (this.groupID != -1) + { + List.Enumerator enumerator = base.Map.listerThings.ThingsOfDef(ThingDefOf.AncientCryptosleepCasket).GetEnumerator(); + try + { + while (enumerator.MoveNext()) + { + Thing t = enumerator.Current; + Building_AncientCryptosleepCasket casket = t as Building_AncientCryptosleepCasket; + if (casket.groupID == this.groupID && !casket.contentsKnown) + { + yield return casket; + } + } + } + finally + { + ((IDisposable)(object)enumerator).Dispose(); + } + } } } } diff --git a/Assembly-CSharp/RimWorld/Building_Art.cs b/Assembly-CSharp/RimWorld/Building_Art.cs index 41317ee16..999ebbe83 100644 --- a/Assembly-CSharp/RimWorld/Building_Art.cs +++ b/Assembly-CSharp/RimWorld/Building_Art.cs @@ -1,4 +1,3 @@ -using System; using Verse; namespace RimWorld @@ -7,16 +6,9 @@ public class Building_Art : Building { public override string GetInspectString() { - string inspectString = base.GetInspectString(); - string text = inspectString; - return string.Concat(new string[] - { - text, - "\n", - StatDefOf.Beauty.LabelCap, - ": ", - StatDefOf.Beauty.ValueToString(this.GetStatValue(StatDefOf.Beauty, true), ToStringNumberSense.Absolute) - }); + string inspectString; + string text = inspectString = base.GetInspectString(); + return inspectString + "\n" + StatDefOf.Beauty.LabelCap + ": " + StatDefOf.Beauty.ValueToString(this.GetStatValue(StatDefOf.Beauty, true), ToStringNumberSense.Absolute); } } } diff --git a/Assembly-CSharp/RimWorld/Building_Battery.cs b/Assembly-CSharp/RimWorld/Building_Battery.cs index c9b63fef8..8a3423d6b 100644 --- a/Assembly-CSharp/RimWorld/Building_Battery.cs +++ b/Assembly-CSharp/RimWorld/Building_Battery.cs @@ -1,4 +1,3 @@ -using System; using UnityEngine; using Verse; using Verse.Sound; @@ -34,13 +33,15 @@ public override void Draw() { base.Draw(); CompPowerBattery comp = base.GetComp(); - GenDraw.FillableBarRequest r = default(GenDraw.FillableBarRequest); - r.center = this.DrawPos + Vector3.up * 0.1f; - r.size = Building_Battery.BarSize; - r.fillPercent = comp.StoredEnergy / comp.Props.storedEnergyMax; - r.filledMat = Building_Battery.BatteryBarFilledMat; - r.unfilledMat = Building_Battery.BatteryBarUnfilledMat; - r.margin = 0.15f; + GenDraw.FillableBarRequest r = new GenDraw.FillableBarRequest + { + center = this.DrawPos + Vector3.up * 0.1f, + size = Building_Battery.BarSize, + fillPercent = comp.StoredEnergy / comp.Props.storedEnergyMax, + filledMat = Building_Battery.BatteryBarFilledMat, + unfilledMat = Building_Battery.BatteryBarUnfilledMat, + margin = 0.15f + }; Rot4 rotation = base.Rotation; rotation.Rotate(RotationDirection.Clockwise); r.rotation = rotation; @@ -68,7 +69,7 @@ public override void Tick() if (this.ticksToExplode == 0) { IntVec3 randomCell = this.OccupiedRect().RandomCell; - float radius = Rand.Range(0.5f, 1f) * 3f; + float radius = (float)(Rand.Range(0.5f, 1f) * 3.0); GenExplosion.DoExplosion(randomCell, base.Map, radius, DamageDefOf.Flame, null, null, null, null, null, 0f, 1, false, null, 0f, 1); base.GetComp().DrawPower(400f); } @@ -77,7 +78,7 @@ public override void Tick() public override void PostApplyDamage(DamageInfo dinfo, float totalDamageDealt) { - if (!base.Destroyed && this.ticksToExplode == 0 && dinfo.Def == DamageDefOf.Flame && Rand.Value < 0.05f && base.GetComp().StoredEnergy > 500f) + if (!base.Destroyed && this.ticksToExplode == 0 && dinfo.Def == DamageDefOf.Flame && Rand.Value < 0.05000000074505806 && base.GetComp().StoredEnergy > 500.0) { this.ticksToExplode = Rand.Range(70, 150); this.StartWickSustainer(); @@ -86,7 +87,7 @@ public override void PostApplyDamage(DamageInfo dinfo, float totalDamageDealt) private void StartWickSustainer() { - SoundInfo info = SoundInfo.InMap(this, MaintenanceType.PerTick); + SoundInfo info = SoundInfo.InMap((Thing)this, MaintenanceType.PerTick); this.wickSustainer = SoundDefOf.HissSmall.TrySpawnSustainer(info); } } diff --git a/Assembly-CSharp/RimWorld/Building_Bed.cs b/Assembly-CSharp/RimWorld/Building_Bed.cs index 344afe093..67b7ba76e 100644 --- a/Assembly-CSharp/RimWorld/Building_Bed.cs +++ b/Assembly-CSharp/RimWorld/Building_Bed.cs @@ -1,6 +1,5 @@ using System; using System.Collections.Generic; -using System.Diagnostics; using System.Linq; using System.Text; using UnityEngine; @@ -40,22 +39,23 @@ public bool ForPrisoners } set { - if (value == this.forPrisonersInt || !this.def.building.bed_humanlike) + if (value != this.forPrisonersInt && base.def.building.bed_humanlike) { - return; - } - if (Current.ProgramState != ProgramState.Playing) - { - Log.Error("Tried to set ForPrisoners while game mode was " + Current.ProgramState); - return; - } - this.RemoveAllOwners(); - this.forPrisonersInt = value; - this.Notify_ColorChanged(); - if (base.Spawned) - { - base.Map.mapDrawer.MapMeshDirty(base.Position, MapMeshFlag.Things); - this.NotifyRoomBedTypeChanged(); + if (Current.ProgramState != ProgramState.Playing) + { + Log.Error("Tried to set ForPrisoners while game mode was " + Current.ProgramState); + } + else + { + this.RemoveAllOwners(); + this.forPrisonersInt = value; + this.Notify_ColorChanged(); + if (base.Spawned) + { + base.Map.mapDrawer.MapMeshDirty(base.Position, MapMeshFlag.Things); + this.NotifyRoomBedTypeChanged(); + } + } } } } @@ -68,19 +68,18 @@ public bool Medical } set { - if (value == this.medicalInt || !this.def.building.bed_humanlike) + if (value != this.medicalInt && base.def.building.bed_humanlike) { - return; - } - this.RemoveAllOwners(); - this.medicalInt = value; - this.Notify_ColorChanged(); - if (base.Spawned) - { - base.Map.mapDrawer.MapMeshDirty(base.Position, MapMeshFlag.Things); - this.NotifyRoomBedTypeChanged(); + this.RemoveAllOwners(); + this.medicalInt = value; + this.Notify_ColorChanged(); + if (base.Spawned) + { + base.Map.mapDrawer.MapMeshDirty(base.Position, MapMeshFlag.Things); + this.NotifyRoomBedTypeChanged(); + } + this.FacilityChanged(); } - this.FacilityChanged(); } } @@ -116,11 +115,14 @@ public IEnumerable CurOccupants { get { - Building_Bed.<>c__Iterator153 <>c__Iterator = new Building_Bed.<>c__Iterator153(); - <>c__Iterator.<>f__this = this; - Building_Bed.<>c__Iterator153 expr_0E = <>c__Iterator; - expr_0E.$PC = -2; - return expr_0E; + for (int i = 0; i < this.SleepingSlotsCount; i++) + { + Pawn occupant = this.GetCurOccupant(i); + if (occupant != null) + { + yield return occupant; + } + } } } @@ -128,7 +130,7 @@ public override Color DrawColor { get { - if (this.def.MadeFromStuff) + if (base.def.MadeFromStuff) { return base.DrawColor; } @@ -140,7 +142,7 @@ public override Color DrawColorTwo { get { - if (!this.def.building.bed_humanlike) + if (!base.def.building.bed_humanlike) { return base.DrawColorTwo; } @@ -158,7 +160,7 @@ public override Color DrawColorTwo { return Building_Bed.SheetColorMedical; } - if (this.def == ThingDefOf.RoyalBed) + if (base.def == ThingDefOf.RoyalBed) { return Building_Bed.SheetColorRoyal; } @@ -170,7 +172,7 @@ public int SleepingSlotsCount { get { - return this.def.size.x; + return base.def.size.x; } } @@ -210,12 +212,15 @@ private bool PlayerCanSeeOwners { return true; } - for (int i = 0; i < this.owners.Count; i++) + int num = 0; + while (num < this.owners.Count) { - if (this.owners[i].Faction == Faction.OfPlayer || this.owners[i].HostFaction == Faction.OfPlayer) + if (this.owners[num].Faction != Faction.OfPlayer && this.owners[num].HostFaction != Faction.OfPlayer) { - return true; + num++; + continue; } + return true; } return false; } @@ -245,7 +250,7 @@ public override void SpawnSetup(Map map, bool respawningAfterLoad) if (!this.alreadySetDefaultMed) { this.alreadySetDefaultMed = true; - if (this.def.building.bed_defaultMedical) + if (base.def.building.bed_defaultMedical) { this.Medical = true; } @@ -289,111 +294,185 @@ public static bool RoomCanBePrisonCell(Room r) return !r.TouchesMapEdge && !r.IsHuge && r.RegionType == RegionType.Normal; } - [DebuggerHidden] public override IEnumerable GetGizmos() { - Building_Bed.c__Iterator154 c__Iterator = new Building_Bed.c__Iterator154(); - c__Iterator.<>f__this = this; - Building_Bed.c__Iterator154 expr_0E = c__Iterator; - expr_0E.$PC = -2; - return expr_0E; + foreach (Gizmo gizmo in base.GetGizmos()) + { + yield return gizmo; + } + if (base.def.building.bed_humanlike && base.Faction == Faction.OfPlayer) + { + Command_Toggle pris = new Command_Toggle + { + defaultLabel = "CommandBedSetForPrisonersLabel".Translate(), + defaultDesc = "CommandBedSetForPrisonersDesc".Translate(), + icon = ContentFinder.Get("UI/Commands/ForPrisoners", true), + isActive = (Func)(() => ((_003CGetGizmos_003Ec__Iterator154)/*Error near IL_0132: stateMachine*/)._003C_003Ef__this.ForPrisoners), + toggleAction = (Action)delegate + { + ((_003CGetGizmos_003Ec__Iterator154)/*Error near IL_0149: stateMachine*/)._003C_003Ef__this.ToggleForPrisonersByInterface(); + } + }; + if (!Building_Bed.RoomCanBePrisonCell(this.GetRoom(RegionType.Set_Passable)) && !this.ForPrisoners) + { + pris.Disable("CommandBedSetForPrisonersFailOutdoors".Translate()); + } + pris.hotKey = KeyBindingDefOf.Misc3; + pris.turnOffSound = null; + pris.turnOnSound = null; + yield return (Gizmo)pris; + yield return (Gizmo)new Command_Toggle + { + defaultLabel = "CommandBedSetAsMedicalLabel".Translate(), + defaultDesc = "CommandBedSetAsMedicalDesc".Translate(), + icon = ContentFinder.Get("UI/Commands/AsMedical", true), + isActive = (Func)(() => ((_003CGetGizmos_003Ec__Iterator154)/*Error near IL_0226: stateMachine*/)._003C_003Ef__this.Medical), + toggleAction = (Action)delegate + { + ((_003CGetGizmos_003Ec__Iterator154)/*Error near IL_023d: stateMachine*/)._003C_003Ef__this.Medical = !((_003CGetGizmos_003Ec__Iterator154)/*Error near IL_023d: stateMachine*/)._003C_003Ef__this.Medical; + }, + hotKey = KeyBindingDefOf.Misc2 + }; + if (!this.ForPrisoners && !this.Medical) + { + yield return (Gizmo)new Command_Action + { + defaultLabel = "CommandBedSetOwnerLabel".Translate(), + icon = ContentFinder.Get("UI/Commands/AssignOwner", true), + defaultDesc = "CommandBedSetOwnerDesc".Translate(), + action = (Action)delegate + { + Find.WindowStack.Add(new Dialog_AssignBuildingOwner(((_003CGetGizmos_003Ec__Iterator154)/*Error near IL_02e7: stateMachine*/)._003C_003Ef__this)); + }, + hotKey = KeyBindingDefOf.Misc3 + }; + } + } } private void ToggleForPrisonersByInterface() { - if (Building_Bed.lastPrisonerSetChangeFrame == Time.frameCount) + if (Building_Bed.lastPrisonerSetChangeFrame != Time.frameCount) { - return; - } - Building_Bed.lastPrisonerSetChangeFrame = Time.frameCount; - bool newForPrisoners = !this.ForPrisoners; - SoundDef soundDef = (!newForPrisoners) ? SoundDefOf.CheckboxTurnedOff : SoundDefOf.CheckboxTurnedOn; - soundDef.PlayOneShotOnCamera(null); - List bedsToAffect = new List(); - foreach (Building_Bed current in (from so in Find.Selector.SelectedObjects - where so is Building_Bed - select so).Cast()) - { - if (current.ForPrisoners != newForPrisoners) + Building_Bed.lastPrisonerSetChangeFrame = Time.frameCount; + bool newForPrisoners = !this.ForPrisoners; + SoundDef soundDef = (!newForPrisoners) ? SoundDefOf.CheckboxTurnedOff : SoundDefOf.CheckboxTurnedOn; + soundDef.PlayOneShotOnCamera(null); + List bedsToAffect = new List(); + foreach (Building_Bed item in (from so in Find.Selector.SelectedObjects + where so is Building_Bed + select so).Cast()) { - Room room = current.GetRoom(RegionType.Set_Passable); - if (room == null || !Building_Bed.RoomCanBePrisonCell(room)) + if (item.ForPrisoners != newForPrisoners) { - if (!bedsToAffect.Contains(current)) + Room room = item.GetRoom(RegionType.Set_Passable); + if (room != null && Building_Bed.RoomCanBePrisonCell(room)) { - bedsToAffect.Add(current); + foreach (Building_Bed containedBed in room.ContainedBeds) + { + if (!bedsToAffect.Contains(containedBed)) + { + bedsToAffect.Add(containedBed); + } + } + } + else if (!bedsToAffect.Contains(item)) + { + bedsToAffect.Add(item); } } - else + } + Action action = (Action)delegate + { + List list = new List(); + List.Enumerator enumerator4 = bedsToAffect.GetEnumerator(); + try { - foreach (Building_Bed current2 in room.ContainedBeds) + while (enumerator4.MoveNext()) { - if (!bedsToAffect.Contains(current2)) + Building_Bed current4 = enumerator4.Current; + Room room2 = current4.GetRoom(RegionType.Set_Passable); + current4.ForPrisoners = (newForPrisoners && !room2.TouchesMapEdge); + for (int j = 0; j < this.SleepingSlotsCount; j++) + { + Pawn curOccupant = this.GetCurOccupant(j); + if (curOccupant != null) + { + curOccupant.jobs.EndCurrentJob(JobCondition.InterruptForced, true); + } + } + if (!list.Contains(room2) && !room2.TouchesMapEdge) { - bedsToAffect.Add(current2); + list.Add(room2); } } } - } - } - Action action = delegate - { - List list = new List(); - foreach (Building_Bed current4 in bedsToAffect) - { - Room room2 = current4.GetRoom(RegionType.Set_Passable); - current4.ForPrisoners = (newForPrisoners && !room2.TouchesMapEdge); - for (int j = 0; j < this.SleepingSlotsCount; j++) + finally + { + ((IDisposable)(object)enumerator4).Dispose(); + } + List.Enumerator enumerator5 = list.GetEnumerator(); + try { - Pawn curOccupant = this.GetCurOccupant(j); - if (curOccupant != null) + while (enumerator5.MoveNext()) { - curOccupant.jobs.EndCurrentJob(JobCondition.InterruptForced, true); + Room current5 = enumerator5.Current; + current5.Notify_RoomShapeOrContainedBedsChanged(); } } - if (!list.Contains(room2) && !room2.TouchesMapEdge) + finally { - list.Add(room2); + ((IDisposable)(object)enumerator5).Dispose(); } - } - foreach (Room current5 in list) - { - current5.Notify_RoomShapeOrContainedBedsChanged(); - } - }; - if ((from b in bedsToAffect - where b.owners.Any() && b != this - select b).Count() == 0) - { - action(); - } - else - { - StringBuilder stringBuilder = new StringBuilder(); - if (newForPrisoners) + }; + if ((from b in bedsToAffect + where b.owners.Any() && b != this + select b).Count() == 0) { - stringBuilder.Append("TurningOnPrisonerBedWarning".Translate()); + action(); } else { - stringBuilder.Append("TurningOffPrisonerBedWarning".Translate()); - } - stringBuilder.AppendLine(); - foreach (Building_Bed current3 in bedsToAffect) - { - if ((newForPrisoners && !current3.ForPrisoners) || (!newForPrisoners && current3.ForPrisoners)) + StringBuilder stringBuilder = new StringBuilder(); + if (newForPrisoners) { - for (int i = 0; i < current3.owners.Count; i++) + stringBuilder.Append("TurningOnPrisonerBedWarning".Translate()); + } + else + { + stringBuilder.Append("TurningOffPrisonerBedWarning".Translate()); + } + stringBuilder.AppendLine(); + List.Enumerator enumerator3 = bedsToAffect.GetEnumerator(); + try + { + while (enumerator3.MoveNext()) { - stringBuilder.AppendLine(); - stringBuilder.Append(current3.owners[i].NameStringShort); + Building_Bed current3 = enumerator3.Current; + if (newForPrisoners && !current3.ForPrisoners) + { + goto IL_0242; + } + if (!newForPrisoners && current3.ForPrisoners) + goto IL_0242; + continue; + IL_0242: + for (int i = 0; i < current3.owners.Count; i++) + { + stringBuilder.AppendLine(); + stringBuilder.Append(current3.owners[i].NameStringShort); + } } } + finally + { + ((IDisposable)(object)enumerator3).Dispose(); + } + stringBuilder.AppendLine(); + stringBuilder.AppendLine(); + stringBuilder.Append("AreYouSure".Translate()); + Find.WindowStack.Add(Dialog_MessageBox.CreateConfirmation(stringBuilder.ToString(), action, false, (string)null)); } - stringBuilder.AppendLine(); - stringBuilder.AppendLine(); - stringBuilder.Append("AreYouSure".Translate()); - Find.WindowStack.Add(Dialog_MessageBox.CreateConfirmation(stringBuilder.ToString(), action, false, null)); } } @@ -401,7 +480,7 @@ public override string GetInspectString() { StringBuilder stringBuilder = new StringBuilder(); stringBuilder.Append(base.GetInspectString()); - if (this.def.building.bed_humanlike) + if (base.def.building.bed_humanlike) { stringBuilder.AppendLine(); if (this.ForPrisoners) @@ -448,37 +527,51 @@ public override string GetInspectString() return stringBuilder.ToString().TrimEndNewlines(); } - [DebuggerHidden] public override IEnumerable GetFloatMenuOptions(Pawn myPawn) { - Building_Bed.c__Iterator155 c__Iterator = new Building_Bed.c__Iterator155(); - c__Iterator.myPawn = myPawn; - c__Iterator.<$>myPawn = myPawn; - c__Iterator.<>f__this = this; - Building_Bed.c__Iterator155 expr_1C = c__Iterator; - expr_1C.$PC = -2; - return expr_1C; + if (myPawn.RaceProps.Humanlike && !this.ForPrisoners && this.Medical && !myPawn.Drafted && base.Faction == Faction.OfPlayer) + { + if (!HealthAIUtility.ShouldSeekMedicalRest(myPawn) && !HealthAIUtility.ShouldSeekMedicalRestUrgent(myPawn)) + { + yield return new FloatMenuOption("UseMedicalBed".Translate() + " (" + "NotInjured".Translate() + ")", null, MenuOptionPriority.Default, null, null, 0f, null, null); + } + else + { + Action sleep = (Action)delegate + { + if (!((_003CGetFloatMenuOptions_003Ec__Iterator155)/*Error near IL_00ee: stateMachine*/)._003C_003Ef__this.ForPrisoners && ((_003CGetFloatMenuOptions_003Ec__Iterator155)/*Error near IL_00ee: stateMachine*/)._003C_003Ef__this.Medical && ((_003CGetFloatMenuOptions_003Ec__Iterator155)/*Error near IL_00ee: stateMachine*/).myPawn.CanReserveAndReach((Thing)((_003CGetFloatMenuOptions_003Ec__Iterator155)/*Error near IL_00ee: stateMachine*/)._003C_003Ef__this, PathEndMode.ClosestTouch, Danger.Deadly, ((_003CGetFloatMenuOptions_003Ec__Iterator155)/*Error near IL_00ee: stateMachine*/)._003C_003Ef__this.SleepingSlotsCount, -1, null, true)) + { + Job job = new Job(JobDefOf.LayDown, (Thing)((_003CGetFloatMenuOptions_003Ec__Iterator155)/*Error near IL_00ee: stateMachine*/)._003C_003Ef__this); + job.restUntilHealed = true; + ((_003CGetFloatMenuOptions_003Ec__Iterator155)/*Error near IL_00ee: stateMachine*/).myPawn.jobs.TryTakeOrderedJob(job, JobTag.Misc); + ((_003CGetFloatMenuOptions_003Ec__Iterator155)/*Error near IL_00ee: stateMachine*/).myPawn.mindState.ResetLastDisturbanceTick(); + } + }; + if (this.AnyUnoccupiedSleepingSlot) + { + yield return FloatMenuUtility.DecoratePrioritizedTask(new FloatMenuOption("UseMedicalBed".Translate(), sleep, MenuOptionPriority.Default, null, null, 0f, null, null), myPawn, (Thing)this, "ReservedBy"); + } + else + { + yield return FloatMenuUtility.DecoratePrioritizedTask(new FloatMenuOption("UseMedicalBed".Translate(), sleep, MenuOptionPriority.Default, null, null, 0f, null, null), myPawn, (Thing)this, "SomeoneElseSleeping"); + } + } + } } public override void DrawGUIOverlay() { - if (this.Medical) - { - return; - } - if (Find.CameraDriver.CurrentZoom == CameraZoomRange.Closest && this.PlayerCanSeeOwners) + if (!this.Medical && Find.CameraDriver.CurrentZoom == CameraZoomRange.Closest && this.PlayerCanSeeOwners) { Color defaultThingLabelColor = GenMapUI.DefaultThingLabelColor; - if (!this.owners.Any()) + if (!this.owners.Any()) { GenMapUI.DrawThingLabel(this, "Unowned".Translate(), defaultThingLabelColor); } else if (this.owners.Count == 1) { if (this.owners[0].InBed() && this.owners[0].CurrentBed() == this) - { return; - } GenMapUI.DrawThingLabel(this, this.owners[0].NameStringShort, defaultThingLabelColor); } else @@ -506,15 +599,9 @@ public Pawn GetCurOccupant(int slotIndex) for (int i = 0; i < list.Count; i++) { Pawn pawn = list[i] as Pawn; - if (pawn != null) + if (pawn != null && pawn.CurJob != null && pawn.jobs.curDriver.layingDown == LayingDownState.LayingInBed) { - if (pawn.CurJob != null) - { - if (pawn.jobs.curDriver.layingDown == LayingDownState.LayingInBed) - { - return pawn; - } - } + return pawn; } } return null; @@ -547,44 +634,45 @@ public Pawn GetCurOccupantAt(IntVec3 pos) public IntVec3 GetSleepingSlotPos(int index) { - if (index < 0 || index >= this.SleepingSlotsCount) + if (index >= 0 && index < this.SleepingSlotsCount) { - Log.Error(string.Concat(new object[] + CellRect cellRect = this.OccupiedRect(); + if (base.Rotation == Rot4.North) { - "Tried to get sleeping slot pos with index ", - index, - ", but there are only ", - this.SleepingSlotsCount, - " sleeping slots available." - })); - return base.Position; - } - CellRect cellRect = this.OccupiedRect(); - if (base.Rotation == Rot4.North) - { - return new IntVec3(cellRect.minX + index, base.Position.y, cellRect.minZ); - } - if (base.Rotation == Rot4.East) - { - return new IntVec3(cellRect.minX, base.Position.y, cellRect.maxZ - index); - } - if (base.Rotation == Rot4.South) - { - return new IntVec3(cellRect.minX + index, base.Position.y, cellRect.maxZ); + int newX = cellRect.minX + index; + IntVec3 position = base.Position; + return new IntVec3(newX, position.y, cellRect.minZ); + } + if (base.Rotation == Rot4.East) + { + int minX = cellRect.minX; + IntVec3 position2 = base.Position; + return new IntVec3(minX, position2.y, cellRect.maxZ - index); + } + if (base.Rotation == Rot4.South) + { + int newX2 = cellRect.minX + index; + IntVec3 position3 = base.Position; + return new IntVec3(newX2, position3.y, cellRect.maxZ); + } + int maxX = cellRect.maxX; + IntVec3 position4 = base.Position; + return new IntVec3(maxX, position4.y, cellRect.maxZ - index); } - return new IntVec3(cellRect.maxX, base.Position.y, cellRect.maxZ - index); + Log.Error("Tried to get sleeping slot pos with index " + index + ", but there are only " + this.SleepingSlotsCount + " sleeping slots available."); + return base.Position; } public void SortOwners() { - this.owners.SortBy((Pawn x) => x.thingIDNumber); + this.owners.SortBy((Func)((Pawn x) => x.thingIDNumber)); } private void RemoveAllOwners() { - for (int i = this.owners.Count - 1; i >= 0; i--) + for (int num = this.owners.Count - 1; num >= 0; num--) { - this.owners[i].ownership.UnclaimBed(); + this.owners[num].ownership.UnclaimBed(); } } @@ -617,11 +705,11 @@ private Vector3 GetMultiOwnersLabelScreenPosFor(int slotIndex) Vector3 drawPos = this.DrawPos; if (base.Rotation.IsHorizontal) { - drawPos.z = (float)sleepingSlotPos.z + 0.6f; + drawPos.z = (float)((float)sleepingSlotPos.z + 0.60000002384185791); } else { - drawPos.x = (float)sleepingSlotPos.x + 0.5f; + drawPos.x = (float)((float)sleepingSlotPos.x + 0.5); drawPos.z += -0.4f; } Vector2 v = drawPos.MapToUIPosition(); @@ -635,28 +723,31 @@ private Vector3 GetMultiOwnersLabelScreenPosFor(int slotIndex) private Vector3 AdjustOwnerLabelPosToAvoidOverlapping(Vector3 screenPos, int slotIndex) { Text.Font = GameFont.Tiny; - float num = Text.CalcSize(this.owners[slotIndex].NameStringShort).x + 1f; - Vector2 vector = this.DrawPos.MapToUIPosition(); - float num2 = Mathf.Abs(screenPos.x - vector.x); + Vector2 vector = Text.CalcSize(this.owners[slotIndex].NameStringShort); + float num = (float)(vector.x + 1.0); + Vector2 vector2 = this.DrawPos.MapToUIPosition(); + float num2 = Mathf.Abs(screenPos.x - vector2.x); IntVec3 sleepingSlotPos = this.GetSleepingSlotPos(slotIndex); - if (num > num2 * 2f) + if (num > num2 * 2.0) { - float num3; + float num3 = 0f; if (slotIndex == 0) { - num3 = (float)this.GetSleepingSlotPos(1).x; + IntVec3 sleepingSlotPos2 = this.GetSleepingSlotPos(1); + num3 = (float)sleepingSlotPos2.x; } else { - num3 = (float)this.GetSleepingSlotPos(0).x; + IntVec3 sleepingSlotPos3 = this.GetSleepingSlotPos(0); + num3 = (float)sleepingSlotPos3.x; } if ((float)sleepingSlotPos.x < num3) { - screenPos.x -= (num - num2 * 2f) / 2f; + screenPos.x -= (float)((num - num2 * 2.0) / 2.0); } else { - screenPos.x += (num - num2 * 2f) / 2f; + screenPos.x += (float)((num - num2 * 2.0) / 2.0); } } return screenPos; diff --git a/Assembly-CSharp/RimWorld/Building_BlastingCharge.cs b/Assembly-CSharp/RimWorld/Building_BlastingCharge.cs index 4e7c3248c..a203da6c2 100644 --- a/Assembly-CSharp/RimWorld/Building_BlastingCharge.cs +++ b/Assembly-CSharp/RimWorld/Building_BlastingCharge.cs @@ -1,20 +1,26 @@ using System; using System.Collections.Generic; -using System.Diagnostics; +using UnityEngine; using Verse; namespace RimWorld { public class Building_BlastingCharge : Building { - [DebuggerHidden] public override IEnumerable GetGizmos() { - Building_BlastingCharge.c__Iterator146 c__Iterator = new Building_BlastingCharge.c__Iterator146(); - c__Iterator.<>f__this = this; - Building_BlastingCharge.c__Iterator146 expr_0E = c__Iterator; - expr_0E.$PC = -2; - return expr_0E; + Command_Action com = new Command_Action + { + icon = ContentFinder.Get("UI/Commands/Detonate", true), + defaultDesc = "CommandDetonateDesc".Translate(), + action = new Action(this.Command_Detonate) + }; + if (base.GetComp().wickStarted) + { + com.Disable((string)null); + } + com.defaultLabel = "CommandDetonateLabel".Translate(); + yield return (Gizmo)com; } private void Command_Detonate() diff --git a/Assembly-CSharp/RimWorld/Building_Casket.cs b/Assembly-CSharp/RimWorld/Building_Casket.cs index caa4b8be3..e9a7bde86 100644 --- a/Assembly-CSharp/RimWorld/Building_Casket.cs +++ b/Assembly-CSharp/RimWorld/Building_Casket.cs @@ -63,17 +63,16 @@ public override void Tick() public virtual void Open() { - if (!this.HasAnyContents) + if (this.HasAnyContents) { - return; + this.EjectContents(); } - this.EjectContents(); } public override void ExposeData() { base.ExposeData(); - Scribe_Deep.Look(ref this.innerContainer, "innerContainer", new object[] + Scribe_Deep.Look(ref this.innerContainer, "innerContainer", new object[1] { this }); @@ -116,7 +115,7 @@ public virtual bool TryAcceptThing(Thing thing, bool allowSpecialEffects = true) { return false; } - bool flag; + bool flag = false; if (thing.holdingOwner != null) { thing.holdingOwner.TryTransferToContainer(thing, this.innerContainer, thing.stackCount, true); @@ -144,17 +143,26 @@ public override void Destroy(DestroyMode mode = DestroyMode.Vanish) if (mode != DestroyMode.Deconstruct) { List list = new List(); - foreach (Thing current in ((IEnumerable)this.innerContainer)) + foreach (Thing item in (IEnumerable)this.innerContainer) { - Pawn pawn = current as Pawn; + Pawn pawn = item as Pawn; if (pawn != null) { list.Add(pawn); } } - foreach (Pawn current2 in list) + List.Enumerator enumerator2 = list.GetEnumerator(); + try { - HealthUtility.DamageUntilDowned(current2); + while (enumerator2.MoveNext()) + { + Pawn current2 = enumerator2.Current; + HealthUtility.DamageUntilDowned(current2); + } + } + finally + { + ((IDisposable)(object)enumerator2).Dispose(); } } this.EjectContents(); @@ -172,15 +180,7 @@ public virtual void EjectContents() public override string GetInspectString() { string text = base.GetInspectString(); - string str; - if (!this.contentsKnown) - { - str = "UnknownLower".Translate(); - } - else - { - str = this.innerContainer.ContentsString; - } + string str = this.contentsKnown ? this.innerContainer.ContentsString : "UnknownLower".Translate(); if (!text.NullOrEmpty()) { text += "\n"; @@ -192,5 +192,11 @@ virtual IThingHolder get_ParentHolder() { return base.ParentHolder; } + + IThingHolder IThingHolder.get_ParentHolder() + { + //ILSpy generated this explicit interface implementation from .override directive in get_ParentHolder + return this.get_ParentHolder(); + } } } diff --git a/Assembly-CSharp/RimWorld/Building_CommsConsole.cs b/Assembly-CSharp/RimWorld/Building_CommsConsole.cs index de2f9ee3e..538c84445 100644 --- a/Assembly-CSharp/RimWorld/Building_CommsConsole.cs +++ b/Assembly-CSharp/RimWorld/Building_CommsConsole.cs @@ -14,7 +14,11 @@ public bool CanUseCommsNow { get { - return (!base.Spawned || !base.Map.gameConditionManager.ConditionIsActive(GameConditionDefOf.SolarFlare)) && this.powerComp.PowerOn; + if (base.Spawned && base.Map.gameConditionManager.ConditionIsActive(GameConditionDefOf.SolarFlare)) + { + return false; + } + return this.powerComp.PowerOn; } } @@ -28,7 +32,7 @@ public override void SpawnSetup(Map map, bool respawningAfterLoad) private void UseAct(Pawn myPawn, ICommunicable commTarget) { - Job job = new Job(JobDefOf.UseCommsConsole, this); + Job job = new Job(JobDefOf.UseCommsConsole, (Thing)this); job.commTarget = commTarget; myPawn.jobs.TryTakeOrderedJob(job, JobTag.Misc); PlayerKnowledgeDatabase.KnowledgeDemonstrated(ConceptDefOf.OpeningComms, KnowledgeAmount.Total); @@ -36,108 +40,100 @@ private void UseAct(Pawn myPawn, ICommunicable commTarget) public override IEnumerable GetFloatMenuOptions(Pawn myPawn) { - if (!myPawn.CanReach(this, PathEndMode.InteractionCell, Danger.Some, false, TraverseMode.ByPawn)) + if (!myPawn.CanReach((Thing)this, PathEndMode.InteractionCell, Danger.Some, false, TraverseMode.ByPawn)) { FloatMenuOption item = new FloatMenuOption("CannotUseNoPath".Translate(), null, MenuOptionPriority.Default, null, null, 0f, null, null); - return new List - { - item - }; + List list = new List(); + list.Add(item); + return list; } if (base.Spawned && base.Map.gameConditionManager.ConditionIsActive(GameConditionDefOf.SolarFlare)) { FloatMenuOption item2 = new FloatMenuOption("CannotUseSolarFlare".Translate(), null, MenuOptionPriority.Default, null, null, 0f, null, null); - return new List - { - item2 - }; + List list = new List(); + list.Add(item2); + return list; } if (!this.powerComp.PowerOn) { FloatMenuOption item3 = new FloatMenuOption("CannotUseNoPower".Translate(), null, MenuOptionPriority.Default, null, null, 0f, null, null); - return new List - { - item3 - }; + List list = new List(); + list.Add(item3); + return list; } if (!myPawn.health.capacities.CapableOf(PawnCapacityDefOf.Talking)) { - FloatMenuOption item4 = new FloatMenuOption("CannotUseReason".Translate(new object[] - { - "IncapableOfCapacity".Translate(new object[] - { - PawnCapacityDefOf.Talking.label - }) - }), null, MenuOptionPriority.Default, null, null, 0f, null, null); - return new List - { - item4 - }; + FloatMenuOption item4 = new FloatMenuOption("CannotUseReason".Translate("IncapableOfCapacity".Translate(PawnCapacityDefOf.Talking.label)), null, MenuOptionPriority.Default, null, null, 0f, null, null); + List list = new List(); + list.Add(item4); + return list; } if (!this.CanUseCommsNow) { Log.Error(myPawn + " could not use comm console for unknown reason."); FloatMenuOption item5 = new FloatMenuOption("Cannot use now", null, MenuOptionPriority.Default, null, null, 0f, null, null); - return new List - { - item5 - }; + List list = new List(); + list.Add(item5); + return list; } - List list = new List(); + List list2 = new List(); IEnumerable enumerable = myPawn.Map.passingShipManager.passingShips.Cast().Concat(Find.FactionManager.AllFactionsInViewOrder.Cast()); - foreach (ICommunicable commTarget in enumerable) + using (IEnumerator enumerator = enumerable.GetEnumerator()) { - ICommunicable localCommTarget = commTarget; - string text = "CallOnRadio".Translate(new object[] + ICommunicable commTarget; + while (enumerator.MoveNext()) { - localCommTarget.GetCallLabel() - }); - Faction faction = localCommTarget as Faction; - if (faction != null) - { - if (faction.IsPlayer) + commTarget = enumerator.Current; + ICommunicable localCommTarget = commTarget; + string text = "CallOnRadio".Translate(localCommTarget.GetCallLabel()); + Faction faction = localCommTarget as Faction; + if (faction != null) { + if (!faction.IsPlayer) + { + if (Building_CommsConsole.LeaderIsAvailableToTalk(faction)) + { + goto IL_02fe; + } + string str = (faction.leader == null) ? "LeaderUnavailableNoLeader".Translate() : "LeaderUnavailable".Translate(faction.leader.LabelShort); + list2.Add(new FloatMenuOption(text + " (" + str + ")", null, MenuOptionPriority.Default, null, null, 0f, null, null)); + } continue; } - if (!Building_CommsConsole.LeaderIsAvailableToTalk(faction)) + goto IL_02fe; + IL_02fe: + Action action = (Action)delegate() { - string str; - if (faction.leader != null) + ICommunicable commTarget2 = localCommTarget; + if (commTarget is TradeShip && !Building_OrbitalTradeBeacon.AllPowered(base.Map).Any()) { - str = "LeaderUnavailable".Translate(new object[] - { - faction.leader.LabelShort - }); + Messages.Message("MessageNeedBeaconToTradeWithShip".Translate(), (Thing)this, MessageSound.RejectInput); } else { - str = "LeaderUnavailableNoLeader".Translate(); + Job job = new Job(JobDefOf.UseCommsConsole, (Thing)this); + job.commTarget = commTarget2; + myPawn.jobs.TryTakeOrderedJob(job, JobTag.Misc); + PlayerKnowledgeDatabase.KnowledgeDemonstrated(ConceptDefOf.OpeningComms, KnowledgeAmount.Total); } - list.Add(new FloatMenuOption(text + " (" + str + ")", null, MenuOptionPriority.Default, null, null, 0f, null, null)); - continue; - } + }; + list2.Add(FloatMenuUtility.DecoratePrioritizedTask(new FloatMenuOption(text, action, MenuOptionPriority.InitiateSocial, null, null, 0f, null, null), myPawn, (Thing)this, "ReservedBy")); } - Action action = delegate - { - ICommunicable localCommTarget = localCommTarget; - if (commTarget is TradeShip && !Building_OrbitalTradeBeacon.AllPowered(this.Map).Any()) - { - Messages.Message("MessageNeedBeaconToTradeWithShip".Translate(), this, MessageSound.RejectInput); - return; - } - Job job = new Job(JobDefOf.UseCommsConsole, this); - job.commTarget = localCommTarget; - myPawn.jobs.TryTakeOrderedJob(job, JobTag.Misc); - PlayerKnowledgeDatabase.KnowledgeDemonstrated(ConceptDefOf.OpeningComms, KnowledgeAmount.Total); - }; - list.Add(FloatMenuUtility.DecoratePrioritizedTask(new FloatMenuOption(text, action, MenuOptionPriority.InitiateSocial, null, null, 0f, null, null), myPawn, this, "ReservedBy")); + return list2; } - return list; } public static bool LeaderIsAvailableToTalk(Faction fac) { - return fac.leader != null && (!fac.leader.Spawned || (!fac.leader.Downed && !fac.leader.IsPrisoner && fac.leader.Awake() && !fac.leader.InMentalState)); + if (fac.leader == null) + { + return false; + } + if (fac.leader.Spawned && (fac.leader.Downed || fac.leader.IsPrisoner || !fac.leader.Awake() || fac.leader.InMentalState)) + { + return false; + } + return true; } } } diff --git a/Assembly-CSharp/RimWorld/Building_Cooler.cs b/Assembly-CSharp/RimWorld/Building_Cooler.cs index 71969e5b3..b262009e7 100644 --- a/Assembly-CSharp/RimWorld/Building_Cooler.cs +++ b/Assembly-CSharp/RimWorld/Building_Cooler.cs @@ -1,4 +1,3 @@ -using System; using UnityEngine; using Verse; @@ -12,7 +11,7 @@ public class Building_Cooler : Building_TempControl public override void TickRare() { - if (this.compPowerTrader.PowerOn) + if (base.compPowerTrader.PowerOn) { IntVec3 intVec = base.Position + IntVec3.South.RotatedBy(base.Rotation); IntVec3 intVec2 = base.Position + IntVec3.North.RotatedBy(base.Rotation); @@ -22,34 +21,34 @@ public override void TickRare() float temperature = intVec2.GetTemperature(base.Map); float temperature2 = intVec.GetTemperature(base.Map); float num = temperature - temperature2; - if (temperature - 40f > num) + if (temperature - 40.0 > num) { - num = temperature - 40f; + num = (float)(temperature - 40.0); } - float num2 = 1f - num * 0.0076923077f; - if (num2 < 0f) + float num2 = (float)(1.0 - num * 0.0076923076994717121); + if (num2 < 0.0) { num2 = 0f; } - float num3 = this.compTempControl.Props.energyPerSecond * num2 * 4.16666651f; - float num4 = GenTemperature.ControlTemperatureTempChange(intVec, base.Map, num3, this.compTempControl.targetTemperature); + float num3 = (float)(base.compTempControl.Props.energyPerSecond * num2 * 4.1666665077209473); + float num4 = GenTemperature.ControlTemperatureTempChange(intVec, base.Map, num3, base.compTempControl.targetTemperature); flag = !Mathf.Approximately(num4, 0f); if (flag) { intVec.GetRoomGroup(base.Map).Temperature += num4; - GenTemperature.PushHeat(intVec2, base.Map, -num3 * 1.25f); + GenTemperature.PushHeat(intVec2, base.Map, (float)((0.0 - num3) * 1.25)); } } - CompProperties_Power props = this.compPowerTrader.Props; + CompProperties_Power props = base.compPowerTrader.Props; if (flag) { - this.compPowerTrader.PowerOutput = -props.basePowerConsumption; + base.compPowerTrader.PowerOutput = (float)(0.0 - props.basePowerConsumption); } else { - this.compPowerTrader.PowerOutput = -props.basePowerConsumption * this.compTempControl.Props.lowPowerConsumptionFactor; + base.compPowerTrader.PowerOutput = (float)((0.0 - props.basePowerConsumption) * base.compTempControl.Props.lowPowerConsumptionFactor); } - this.compTempControl.operatingAtHighPower = flag; + base.compTempControl.operatingAtHighPower = flag; } } } diff --git a/Assembly-CSharp/RimWorld/Building_CrashedShipPart.cs b/Assembly-CSharp/RimWorld/Building_CrashedShipPart.cs index fbba076d6..91395654d 100644 --- a/Assembly-CSharp/RimWorld/Building_CrashedShipPart.cs +++ b/Assembly-CSharp/RimWorld/Building_CrashedShipPart.cs @@ -72,10 +72,7 @@ public override string GetInspectString() { stringBuilder.AppendLine(); } - stringBuilder.Append("AwokeDaysAgo".Translate(new object[] - { - this.age.TicksToDays().ToString("F1") - })); + stringBuilder.Append("AwokeDaysAgo".Translate(this.age.TicksToDays().ToString("F1"))); return stringBuilder.ToString(); } @@ -97,23 +94,31 @@ public override void Tick() public override void PreApplyDamage(DamageInfo dinfo, out bool absorbed) { base.PreApplyDamage(dinfo, out absorbed); - if (absorbed) - { - return; - } - if (dinfo.Def.harmsHealth) + if (!absorbed) { - if (this.lord != null) - { - this.lord.ReceiveMemo(Building_CrashedShipPart.MemoDamaged); - } - float num = (float)(this.HitPoints - dinfo.Amount); - if ((num < (float)base.MaxHitPoints * 0.98f && dinfo.Instigator != null && dinfo.Instigator.Faction != null) || num < (float)base.MaxHitPoints * 0.9f) + if (dinfo.Def.harmsHealth) { - this.TrySpawnMechanoids(); + if (this.lord != null) + { + this.lord.ReceiveMemo(Building_CrashedShipPart.MemoDamaged); + } + float num = (float)(this.HitPoints - dinfo.Amount); + if (num < (float)base.MaxHitPoints * 0.98000001907348633 && dinfo.Instigator != null && dinfo.Instigator.Faction != null) + { + goto IL_008f; + } + if (num < (float)base.MaxHitPoints * 0.89999997615814209) + goto IL_008f; } + goto IL_0095; } + return; + IL_0095: absorbed = false; + return; + IL_008f: + this.TrySpawnMechanoids(); + goto IL_0095; } public void Notify_AdjacentBlueprintReplacedWithSolidThing(Pawn by) @@ -126,51 +131,48 @@ public void Notify_AdjacentBlueprintReplacedWithSolidThing(Pawn by) private void TrySpawnMechanoids() { - if (this.pointsLeft <= 0f) + if (!(this.pointsLeft <= 0.0)) { - return; - } - if (this.lord == null) - { - IntVec3 invalid; - if (!CellFinder.TryFindRandomCellNear(base.Position, base.Map, 5, (IntVec3 c) => c.Standable(base.Map) && base.Map.reachability.CanReach(c, this, PathEndMode.Touch, TraverseParms.For(TraverseMode.PassDoors, Danger.Deadly, false)), out invalid)) + if (this.lord == null) { - Log.Error("Found no place for mechanoids to defend " + this); - invalid = IntVec3.Invalid; + IntVec3 invalid = default(IntVec3); + if (!CellFinder.TryFindRandomCellNear(base.Position, base.Map, 5, (Predicate)((IntVec3 c) => c.Standable(base.Map) && base.Map.reachability.CanReach(c, (Thing)this, PathEndMode.Touch, TraverseParms.For(TraverseMode.PassDoors, Danger.Deadly, false))), out invalid)) + { + Log.Error("Found no place for mechanoids to defend " + this); + invalid = IntVec3.Invalid; + } + LordJob_MechanoidsDefendShip lordJob = new LordJob_MechanoidsDefendShip(this, base.Faction, 21f, invalid); + this.lord = LordMaker.MakeNewLord(Faction.OfMechanoids, lordJob, base.Map, null); } - LordJob_MechanoidsDefendShip lordJob = new LordJob_MechanoidsDefendShip(this, base.Faction, 21f, invalid); - this.lord = LordMaker.MakeNewLord(Faction.OfMechanoids, lordJob, base.Map, null); - } - PawnKindDef kindDef; - while ((from def in DefDatabase.AllDefs - where def.RaceProps.IsMechanoid && def.isFighter && def.combatPower <= this.pointsLeft - select def).TryRandomElement(out kindDef)) - { - IntVec3 center; - if ((from cell in GenAdj.CellsAdjacent8Way(this) + PawnKindDef kindDef = default(PawnKindDef); + IntVec3 center = default(IntVec3); + while ((from def in DefDatabase.AllDefs + where def.RaceProps.IsMechanoid && def.isFighter && def.combatPower <= this.pointsLeft + select def).TryRandomElement(out kindDef) && (from cell in GenAdj.CellsAdjacent8Way(this) where this.CanSpawnMechanoidAt(cell) - select cell).TryRandomElement(out center)) + select cell).TryRandomElement(out center)) { Pawn pawn = PawnGenerator.GeneratePawn(kindDef, Faction.OfMechanoids); - if (GenPlace.TryPlaceThing(pawn, center, base.Map, ThingPlaceMode.Near, null)) + if (!GenPlace.TryPlaceThing(pawn, center, base.Map, ThingPlaceMode.Near, null)) { - this.lord.AddPawn(pawn); - this.pointsLeft -= pawn.kindDef.combatPower; - continue; + Find.WorldPawns.PassToWorld(pawn, PawnDiscardDecideMode.Discard); + break; } - Find.WorldPawns.PassToWorld(pawn, PawnDiscardDecideMode.Discard); + this.lord.AddPawn(pawn); + this.pointsLeft -= pawn.kindDef.combatPower; } - IL_130: this.pointsLeft = 0f; SoundDefOf.PsychicPulseGlobal.PlayOneShotOnCamera(base.Map); - return; } - goto IL_130; } private bool CanSpawnMechanoidAt(IntVec3 c) { - return c.Walkable(base.Map); + if (!c.Walkable(base.Map)) + { + return false; + } + return true; } private void ExpandSnow() @@ -179,15 +181,15 @@ private void ExpandSnow() { this.snowNoise = new Perlin(0.054999999701976776, 2.0, 0.5, 5, Rand.Range(0, 651431), QualityMode.Medium); } - if (this.snowRadius < 8f) + if (this.snowRadius < 8.0) { this.snowRadius += 1.3f; } - else if (this.snowRadius < 17f) + else if (this.snowRadius < 17.0) { this.snowRadius += 0.7f; } - else if (this.snowRadius < 30f) + else if (this.snowRadius < 30.0) { this.snowRadius += 0.4f; } @@ -195,37 +197,41 @@ private void ExpandSnow() { this.snowRadius += 0.1f; } - if (this.snowRadius > 55f) + if (this.snowRadius > 55.0) { this.snowRadius = 55f; } CellRect occupiedRect = this.OccupiedRect(); Building_CrashedShipPart.reachableCells.Clear(); - base.Map.floodFiller.FloodFill(base.Position, (IntVec3 x) => (float)x.DistanceToSquared(this.Position) <= this.snowRadius * this.snowRadius && (occupiedRect.Contains(x) || !x.Filled(this.Map)), delegate(IntVec3 x) + base.Map.floodFiller.FloodFill(base.Position, (Predicate)delegate(IntVec3 x) + { + if ((float)x.DistanceToSquared(base.Position) > this.snowRadius * this.snowRadius) + { + return false; + } + return occupiedRect.Contains(x) || !x.Filled(base.Map); + }, (Action)delegate(IntVec3 x) { Building_CrashedShipPart.reachableCells.Add(x); }, false); int num = GenRadial.NumCellsInRadius(this.snowRadius); - for (int i = 0; i < num; i++) + for (int num2 = 0; num2 < num; num2++) { - IntVec3 intVec = base.Position + GenRadial.RadialPattern[i]; - if (intVec.InBounds(base.Map)) + IntVec3 intVec = base.Position + GenRadial.RadialPattern[num2]; + if (intVec.InBounds(base.Map) && Building_CrashedShipPart.reachableCells.Contains(intVec)) { - if (Building_CrashedShipPart.reachableCells.Contains(intVec)) + float value = this.snowNoise.GetValue(intVec); + value = (float)(value + 1.0); + value = (float)(value * 0.5); + if (value < 0.10000000149011612) { - float num2 = this.snowNoise.GetValue(intVec); - num2 += 1f; - num2 *= 0.5f; - if (num2 < 0.1f) - { - num2 = 0.1f; - } - if (base.Map.snowGrid.GetDepth(intVec) <= num2) - { - float lengthHorizontal = (intVec - base.Position).LengthHorizontal; - float num3 = 1f - lengthHorizontal / this.snowRadius; - base.Map.snowGrid.AddDepth(intVec, num3 * 0.12f * num2); - } + value = 0.1f; + } + if (!(base.Map.snowGrid.GetDepth(intVec) > value)) + { + float lengthHorizontal = (intVec - base.Position).LengthHorizontal; + float num3 = (float)(1.0 - lengthHorizontal / this.snowRadius); + base.Map.snowGrid.AddDepth(intVec, (float)(num3 * 0.11999999731779099 * value)); } } } @@ -233,34 +239,33 @@ private void ExpandSnow() private void HarmPlant() { - if (this.PlantHarmRange < 0.0001f) + if (!(this.PlantHarmRange < 9.9999997473787516E-05)) { - return; - } - float angle = Rand.Range(0f, 360f); - float num = Rand.Range(0f, this.PlantHarmRange); - num = Mathf.Sqrt(num / this.PlantHarmRange) * this.PlantHarmRange; - Quaternion rotation = Quaternion.AngleAxis(angle, Vector3.up); - Vector3 point = Vector3.forward * num; - Vector3 v = rotation * point; - IntVec3 b = IntVec3.FromVector3(v); - IntVec3 c = base.Position + b; - if (c.InBounds(base.Map)) - { - Plant plant = c.GetPlant(base.Map); - if (plant != null) + float angle = Rand.Range(0f, 360f); + float num = Rand.Range(0f, this.PlantHarmRange); + num = Mathf.Sqrt(num / this.PlantHarmRange) * this.PlantHarmRange; + Quaternion rotation = Quaternion.AngleAxis(angle, Vector3.up); + Vector3 point = Vector3.forward * num; + Vector3 v = rotation * point; + IntVec3 b = IntVec3.FromVector3(v); + IntVec3 c = base.Position + b; + if (c.InBounds(base.Map)) { - if (Rand.Value < 0.2f) - { - plant.Kill(null); - } - else + Plant plant = c.GetPlant(base.Map); + if (plant != null) { - plant.MakeLeafless(false); + if (Rand.Value < 0.20000000298023224) + { + plant.Kill(default(DamageInfo?)); + } + else + { + plant.MakeLeafless(false); + } } } + this.ticksToPlantHarm = this.PlantHarmInterval; } - this.ticksToPlantHarm = this.PlantHarmInterval; } } } diff --git a/Assembly-CSharp/RimWorld/Building_CryptosleepCasket.cs b/Assembly-CSharp/RimWorld/Building_CryptosleepCasket.cs index b8e78bf63..171cffcbe 100644 --- a/Assembly-CSharp/RimWorld/Building_CryptosleepCasket.cs +++ b/Assembly-CSharp/RimWorld/Building_CryptosleepCasket.cs @@ -1,7 +1,7 @@ using System; using System.Collections.Generic; -using System.Diagnostics; using System.Linq; +using UnityEngine; using Verse; using Verse.AI; using Verse.Sound; @@ -23,39 +23,68 @@ public override bool TryAcceptThing(Thing thing, bool allowSpecialEffects = true return false; } - [DebuggerHidden] public override IEnumerable GetFloatMenuOptions(Pawn myPawn) { - Building_CryptosleepCasket.c__Iterator150 c__Iterator = new Building_CryptosleepCasket.c__Iterator150(); - c__Iterator.myPawn = myPawn; - c__Iterator.<$>myPawn = myPawn; - c__Iterator.<>f__this = this; - Building_CryptosleepCasket.c__Iterator150 expr_1C = c__Iterator; - expr_1C.$PC = -2; - return expr_1C; + foreach (FloatMenuOption floatMenuOption in base.GetFloatMenuOptions(myPawn)) + { + yield return floatMenuOption; + } + if (base.innerContainer.Count == 0) + { + if (!myPawn.CanReach((Thing)this, PathEndMode.InteractionCell, Danger.Deadly, false, TraverseMode.ByPawn)) + { + FloatMenuOption failer = new FloatMenuOption("CannotUseNoPath".Translate(), null, MenuOptionPriority.Default, null, null, 0f, null, null); + yield return failer; + } + else + { + JobDef jobDef = JobDefOf.EnterCryptosleepCasket; + string jobStr = "EnterCryptosleepCasket".Translate(); + Action jobAction = (Action)delegate + { + Job job = new Job(((_003CGetFloatMenuOptions_003Ec__Iterator150)/*Error near IL_0141: stateMachine*/)._003CjobDef_003E__3, (Thing)((_003CGetFloatMenuOptions_003Ec__Iterator150)/*Error near IL_0141: stateMachine*/)._003C_003Ef__this); + ((_003CGetFloatMenuOptions_003Ec__Iterator150)/*Error near IL_0141: stateMachine*/).myPawn.jobs.TryTakeOrderedJob(job, JobTag.Misc); + }; + yield return FloatMenuUtility.DecoratePrioritizedTask(new FloatMenuOption(jobStr, jobAction, MenuOptionPriority.Default, null, null, 0f, null, null), myPawn, (Thing)this, "ReservedBy"); + } + } } - [DebuggerHidden] public override IEnumerable GetGizmos() { - Building_CryptosleepCasket.c__Iterator151 c__Iterator = new Building_CryptosleepCasket.c__Iterator151(); - c__Iterator.<>f__this = this; - Building_CryptosleepCasket.c__Iterator151 expr_0E = c__Iterator; - expr_0E.$PC = -2; - return expr_0E; + foreach (Gizmo gizmo in base.GetGizmos()) + { + yield return gizmo; + } + if (base.Faction == Faction.OfPlayer && base.innerContainer.Count > 0 && base.def.building.isPlayerEjectable) + { + Command_Action eject = new Command_Action + { + action = new Action(this.EjectContents), + defaultLabel = "CommandPodEject".Translate(), + defaultDesc = "CommandPodEjectDesc".Translate() + }; + if (base.innerContainer.Count == 0) + { + eject.Disable("CommandPodEjectFailEmpty".Translate()); + } + eject.hotKey = KeyBindingDefOf.Misc1; + eject.icon = ContentFinder.Get("UI/Commands/PodEject", true); + yield return (Gizmo)eject; + } } public override void EjectContents() { ThingDef filthSlime = ThingDefOf.FilthSlime; - foreach (Thing current in ((IEnumerable)this.innerContainer)) + foreach (Thing item in (IEnumerable)base.innerContainer) { - Pawn pawn = current as Pawn; + Pawn pawn = item as Pawn; if (pawn != null) { PawnComponentsUtility.AddComponentsForSpawn(pawn); pawn.filth.GainFilth(filthSlime); - pawn.health.AddHediff(HediffDefOf.CryptosleepSickness, null, null); + pawn.health.AddHediff(HediffDefOf.CryptosleepSickness, null, default(DamageInfo?)); } } if (!base.Destroyed) @@ -70,23 +99,23 @@ public static Building_CryptosleepCasket FindCryptosleepCasketFor(Pawn p, Pawn t IEnumerable enumerable = from def in DefDatabase.AllDefs where typeof(Building_CryptosleepCasket).IsAssignableFrom(def.thingClass) select def; - foreach (ThingDef current in enumerable) + foreach (ThingDef item in enumerable) { - Predicate validator = delegate(Thing x) + Predicate validator = (Predicate)delegate(Thing x) { - bool arg_2F_0; + int result; if (!((Building_CryptosleepCasket)x).HasAnyContents) { bool ignoreOtherReservations2 = ignoreOtherReservations; - arg_2F_0 = traveler.CanReserve(x, 1, -1, null, ignoreOtherReservations2); + result = (traveler.CanReserve(x, 1, -1, null, ignoreOtherReservations2) ? 1 : 0); } else { - arg_2F_0 = false; + result = 0; } - return arg_2F_0; + return (byte)result != 0; }; - Building_CryptosleepCasket building_CryptosleepCasket = (Building_CryptosleepCasket)GenClosest.ClosestThingReachable(p.Position, p.Map, ThingRequest.ForDef(current), PathEndMode.InteractionCell, TraverseParms.For(traveler, Danger.Deadly, TraverseMode.ByPawn, false), 9999f, validator, null, 0, -1, false, RegionType.Set_Passable, false); + Building_CryptosleepCasket building_CryptosleepCasket = (Building_CryptosleepCasket)GenClosest.ClosestThingReachable(p.Position, p.Map, ThingRequest.ForDef(item), PathEndMode.InteractionCell, TraverseParms.For(traveler, Danger.Deadly, TraverseMode.ByPawn, false), 9999f, validator, null, 0, -1, false, RegionType.Set_Passable, false); if (building_CryptosleepCasket != null) { return building_CryptosleepCasket; diff --git a/Assembly-CSharp/RimWorld/Building_Door.cs b/Assembly-CSharp/RimWorld/Building_Door.cs index 771390214..b763a7fe2 100644 --- a/Assembly-CSharp/RimWorld/Building_Door.cs +++ b/Assembly-CSharp/RimWorld/Building_Door.cs @@ -1,6 +1,5 @@ using System; using System.Collections.Generic; -using System.Diagnostics; using UnityEngine; using Verse; using Verse.AI; @@ -55,7 +54,11 @@ public bool FreePassage { get { - return this.openInt && (this.holdOpenInt || !this.WillCloseSoon); + if (!this.openInt) + { + return false; + } + return this.holdOpenInt || !this.WillCloseSoon; } } @@ -88,12 +91,9 @@ public bool WillCloseSoon for (int j = 0; j < thingList.Count; j++) { Pawn pawn = thingList[j] as Pawn; - if (pawn != null && !pawn.HostileTo(this)) + if (pawn != null && !pawn.HostileTo(this) && (pawn.Position == base.Position || (pawn.pather.MovingNow && pawn.pather.nextCell == base.Position))) { - if (pawn.Position == base.Position || (pawn.pather.MovingNow && pawn.pather.nextCell == base.Position)) - { - return true; - } + return true; } } } @@ -107,13 +107,16 @@ public bool BlockedOpenMomentary get { List thingList = base.Position.GetThingList(base.Map); - for (int i = 0; i < thingList.Count; i++) + int num = 0; + while (num < thingList.Count) { - Thing thing = thingList[i]; - if (thing.def.category == ThingCategory.Item || thing.def.category == ThingCategory.Pawn) + Thing thing = thingList[num]; + if (thing.def.category != ThingCategory.Item && thing.def.category != ThingCategory.Pawn) { - return true; + num++; + continue; } + return true; } return false; } @@ -139,10 +142,10 @@ public int TicksToOpenNow { get { - float num = 45f / this.GetStatValue(StatDefOf.DoorOpenSpeed, true); + float num = (float)(45.0 / this.GetStatValue(StatDefOf.DoorOpenSpeed, true)); if (this.DoorPowerOn) { - num *= 0.25f; + num = (float)(num * 0.25); } return Mathf.RoundToInt(num); } @@ -238,7 +241,7 @@ public override void Tick() { this.visualTicksOpen--; } - if ((Find.TickManager.TicksGame + this.thingIDNumber.HashOffset()) % 375 == 0) + if ((Find.TickManager.TicksGame + base.thingIDNumber.HashOffset()) % 375 == 0) { GenTemperature.EqualizeTemperaturesThroughBuilding(this, 1f, false); } @@ -264,7 +267,7 @@ public override void Tick() } } } - if ((Find.TickManager.TicksGame + this.thingIDNumber.HashOffset()) % 22 == 0) + if ((Find.TickManager.TicksGame + base.thingIDNumber.HashOffset()) % 22 == 0) { GenTemperature.EqualizeTemperaturesThroughBuilding(this, 1f, false); } @@ -296,12 +299,24 @@ public bool CanPhysicallyPass(Pawn p) public virtual bool PawnCanOpen(Pawn p) { Lord lord = p.GetLord(); - return (lord != null && lord.LordJob != null && lord.LordJob.CanOpenAnyDoor(p)) || base.Faction == null || GenAI.MachinesLike(base.Faction, p); + if (lord != null && lord.LordJob != null && lord.LordJob.CanOpenAnyDoor(p)) + { + return true; + } + if (base.Faction == null) + { + return true; + } + return GenAI.MachinesLike(base.Faction, p); } public override bool BlocksPawn(Pawn p) { - return !this.openInt && !this.PawnCanOpen(p); + if (this.openInt) + { + return false; + } + return !this.PawnCanOpen(p); } protected void DoorOpen(int ticksToClose = 60) @@ -312,29 +327,28 @@ protected void DoorOpen(int ticksToClose = 60) this.openInt = true; if (this.DoorPowerOn) { - this.def.building.soundDoorOpenPowered.PlayOneShot(new TargetInfo(base.Position, base.Map, false)); + base.def.building.soundDoorOpenPowered.PlayOneShot(new TargetInfo(base.Position, base.Map, false)); } else { - this.def.building.soundDoorOpenManual.PlayOneShot(new TargetInfo(base.Position, base.Map, false)); + base.def.building.soundDoorOpenManual.PlayOneShot(new TargetInfo(base.Position, base.Map, false)); } } } protected void DoorTryClose() { - if (this.holdOpenInt || this.BlockedOpenMomentary) + if (!this.holdOpenInt && !this.BlockedOpenMomentary) { - return; - } - this.openInt = false; - if (this.DoorPowerOn) - { - this.def.building.soundDoorClosePowered.PlayOneShot(new TargetInfo(base.Position, base.Map, false)); - } - else - { - this.def.building.soundDoorCloseManual.PlayOneShot(new TargetInfo(base.Position, base.Map, false)); + this.openInt = false; + if (this.DoorPowerOn) + { + base.def.building.soundDoorClosePowered.PlayOneShot(new TargetInfo(base.Position, base.Map, false)); + } + else + { + base.def.building.soundDoorCloseManual.PlayOneShot(new TargetInfo(base.Position, base.Map, false)); + } } } @@ -352,7 +366,7 @@ public override void Draw() { base.Rotation = Building_Door.DoorRotationAt(base.Position, base.Map); float num = Mathf.Clamp01((float)this.visualTicksOpen / (float)this.VisualTicksToOpen); - float d = 0f + 0.45f * num; + float d = (float)(0.0 + 0.44999998807907104 * num); for (int i = 0; i < 2; i++) { Vector3 vector = default(Vector3); @@ -427,14 +441,27 @@ public static Rot4 DoorRotationAt(IntVec3 loc, Map map) return Rot4.East; } - [DebuggerHidden] public override IEnumerable GetGizmos() { - Building_Door.c__Iterator156 c__Iterator = new Building_Door.c__Iterator156(); - c__Iterator.<>f__this = this; - Building_Door.c__Iterator156 expr_0E = c__Iterator; - expr_0E.$PC = -2; - return expr_0E; + foreach (Gizmo gizmo in base.GetGizmos()) + { + yield return gizmo; + } + if (base.Faction == Faction.OfPlayer) + { + yield return (Gizmo)new Command_Toggle + { + defaultLabel = "CommandToggleDoorHoldOpen".Translate(), + defaultDesc = "CommandToggleDoorHoldOpenDesc".Translate(), + hotKey = KeyBindingDefOf.Misc3, + icon = TexCommand.HoldOpen, + isActive = (Func)(() => ((_003CGetGizmos_003Ec__Iterator156)/*Error near IL_011a: stateMachine*/)._003C_003Ef__this.holdOpenInt), + toggleAction = (Action)delegate + { + ((_003CGetGizmos_003Ec__Iterator156)/*Error near IL_0131: stateMachine*/)._003C_003Ef__this.holdOpenInt = !((_003CGetGizmos_003Ec__Iterator156)/*Error near IL_0131: stateMachine*/)._003C_003Ef__this.holdOpenInt; + } + }; + } } private void ClearReachabilityCache(Map map) diff --git a/Assembly-CSharp/RimWorld/Building_FermentingBarrel.cs b/Assembly-CSharp/RimWorld/Building_FermentingBarrel.cs index 17b173f3c..506e7c84c 100644 --- a/Assembly-CSharp/RimWorld/Building_FermentingBarrel.cs +++ b/Assembly-CSharp/RimWorld/Building_FermentingBarrel.cs @@ -1,6 +1,5 @@ using System; using System.Collections.Generic; -using System.Diagnostics; using System.Text; using UnityEngine; using Verse; @@ -38,12 +37,11 @@ public float Progress } set { - if (value == this.progressInt) + if (value != this.progressInt) { - return; + this.progressInt = value; + this.barFilledCachedMat = null; } - this.progressInt = value; - this.barFilledCachedMat = null; } } @@ -51,7 +49,7 @@ private Material BarFilledMat { get { - if (this.barFilledCachedMat == null) + if ((UnityEngine.Object)this.barFilledCachedMat == (UnityEngine.Object)null) { this.barFilledCachedMat = SolidColorMaterials.SimpleSolidColorMaterial(Color.Lerp(Building_FermentingBarrel.BarZeroProgressColor, Building_FermentingBarrel.BarFermentedColor, this.Progress), false); } @@ -83,7 +81,7 @@ public bool Fermented { get { - return !this.Empty && this.Progress >= 1f; + return !this.Empty && this.Progress >= 1.0; } } @@ -91,13 +89,13 @@ private float CurrentTempProgressSpeedFactor { get { - CompProperties_TemperatureRuinable compProperties = this.def.GetCompProperties(); + CompProperties_TemperatureRuinable compProperties = base.def.GetCompProperties(); float ambientTemperature = base.AmbientTemperature; if (ambientTemperature < compProperties.minSafeTemperature) { return 0.1f; } - if (ambientTemperature < 7f) + if (ambientTemperature < 7.0) { return GenMath.LerpDouble(compProperties.minSafeTemperature, 7f, 0.1f, 1f, ambientTemperature); } @@ -109,7 +107,7 @@ private float ProgressPerTickAtCurrentTemp { get { - return 1.66666666E-06f * this.CurrentTempProgressSpeedFactor; + return (float)(1.6666666624587378E-06 * this.CurrentTempProgressSpeedFactor); } } @@ -117,7 +115,7 @@ private int EstimatedTicksLeft { get { - return Mathf.Max(Mathf.RoundToInt((1f - this.Progress) / this.ProgressPerTickAtCurrentTemp), 0); + return Mathf.Max(Mathf.RoundToInt((float)((1.0 - this.Progress) / this.ProgressPerTickAtCurrentTemp)), 0); } } @@ -133,7 +131,7 @@ public override void TickRare() base.TickRare(); if (!this.Empty) { - this.Progress = Mathf.Min(this.Progress + 250f * this.ProgressPerTickAtCurrentTemp, 1f); + this.Progress = Mathf.Min((float)(this.Progress + 250.0 * this.ProgressPerTickAtCurrentTemp), 1f); } } @@ -143,15 +141,16 @@ public void AddWort(int count) if (this.Fermented) { Log.Warning("Tried to add wort to a barrel full of beer. Colonists should take the beer first."); - return; } - int num = Mathf.Min(count, 25 - this.wortCount); - if (num <= 0) + else { - return; + int num = Mathf.Min(count, 25 - this.wortCount); + if (num > 0) + { + this.Progress = GenMath.WeightedAverage(0f, (float)num, this.Progress, (float)this.wortCount); + this.wortCount += num; + } } - this.Progress = GenMath.WeightedAverage(0f, (float)num, this.Progress, (float)this.wortCount); - this.wortCount += num; } protected override void ReceiveCompSignal(string signal) @@ -187,19 +186,11 @@ public override string GetInspectString() { if (this.Fermented) { - stringBuilder.AppendLine("ContainsBeer".Translate(new object[] - { - this.wortCount, - 25 - })); + stringBuilder.AppendLine("ContainsBeer".Translate(this.wortCount, 25)); } else { - stringBuilder.AppendLine("ContainsWort".Translate(new object[] - { - this.wortCount, - 25 - })); + stringBuilder.AppendLine("ContainsWort".Translate(this.wortCount, 25)); } } if (!this.Empty) @@ -210,29 +201,15 @@ public override string GetInspectString() } else { - stringBuilder.AppendLine("FermentationProgress".Translate(new object[] + stringBuilder.AppendLine("FermentationProgress".Translate(this.Progress.ToStringPercent(), this.EstimatedTicksLeft.ToStringTicksToPeriod(true, false, true))); + if (this.CurrentTempProgressSpeedFactor != 1.0) { - this.Progress.ToStringPercent(), - this.EstimatedTicksLeft.ToStringTicksToPeriod(true, false, true) - })); - if (this.CurrentTempProgressSpeedFactor != 1f) - { - stringBuilder.AppendLine("FermentationBarrelOutOfIdealTemperature".Translate(new object[] - { - this.CurrentTempProgressSpeedFactor.ToStringPercent() - })); + stringBuilder.AppendLine("FermentationBarrelOutOfIdealTemperature".Translate(this.CurrentTempProgressSpeedFactor.ToStringPercent())); } } } stringBuilder.AppendLine("Temperature".Translate() + ": " + base.AmbientTemperature.ToStringTemperature("F0")); - stringBuilder.AppendLine(string.Concat(new string[] - { - "IdealFermentingTemperature".Translate(), - ": ", - 7f.ToStringTemperature("F0"), - " ~ ", - comp.Props.maxSafeTemperature.ToStringTemperature("F0") - })); + stringBuilder.AppendLine("IdealFermentingTemperature".Translate() + ": " + 7f.ToStringTemperature("F0") + " ~ " + comp.Props.maxSafeTemperature.ToStringTemperature("F0")); return stringBuilder.ToString().TrimEndNewlines(); } @@ -261,7 +238,7 @@ public override void Draw() { center = drawPos, size = Building_FermentingBarrel.BarSize, - fillPercent = (float)this.wortCount / 25f, + fillPercent = (float)((float)this.wortCount / 25.0), filledMat = this.BarFilledMat, unfilledMat = Building_FermentingBarrel.BarUnfilledMat, margin = 0.1f, @@ -270,14 +247,23 @@ public override void Draw() } } - [DebuggerHidden] public override IEnumerable GetGizmos() { - Building_FermentingBarrel.c__Iterator157 c__Iterator = new Building_FermentingBarrel.c__Iterator157(); - c__Iterator.<>f__this = this; - Building_FermentingBarrel.c__Iterator157 expr_0E = c__Iterator; - expr_0E.$PC = -2; - return expr_0E; + foreach (Gizmo gizmo in base.GetGizmos()) + { + yield return gizmo; + } + if (Prefs.DevMode && !this.Empty) + { + yield return (Gizmo)new Command_Action + { + defaultLabel = "Debug: Set progress to 1", + action = (Action)delegate + { + ((_003CGetGizmos_003Ec__Iterator157)/*Error near IL_00e5: stateMachine*/)._003C_003Ef__this.Progress = 1f; + } + }; + } } } } diff --git a/Assembly-CSharp/RimWorld/Building_Grave.cs b/Assembly-CSharp/RimWorld/Building_Grave.cs index 4d531305a..5609f29dc 100644 --- a/Assembly-CSharp/RimWorld/Building_Grave.cs +++ b/Assembly-CSharp/RimWorld/Building_Grave.cs @@ -1,8 +1,8 @@ using System; using System.Collections.Generic; -using System.Diagnostics; using System.Linq; using System.Text; +using UnityEngine; using Verse; namespace RimWorld @@ -19,19 +19,19 @@ public override Graphic Graphic { get { - if (!this.HasCorpse) + if (this.HasCorpse) { - return base.Graphic; - } - if (this.def.building.fullGraveGraphicData == null) - { - return base.Graphic; - } - if (this.cachedGraphicFull == null) - { - this.cachedGraphicFull = this.def.building.fullGraveGraphicData.GraphicColoredFor(this); + if (base.def.building.fullGraveGraphicData == null) + { + return base.Graphic; + } + if (this.cachedGraphicFull == null) + { + this.cachedGraphicFull = base.def.building.fullGraveGraphicData.GraphicColoredFor(this); + } + return this.cachedGraphicFull; } - return this.cachedGraphicFull; + return base.Graphic; } } @@ -47,9 +47,9 @@ public Corpse Corpse { get { - for (int i = 0; i < this.innerContainer.Count; i++) + for (int i = 0; i < base.innerContainer.Count; i++) { - Corpse corpse = this.innerContainer[i] as Corpse; + Corpse corpse = base.innerContainer[i] as Corpse; if (corpse != null) { return corpse; @@ -78,11 +78,10 @@ public IEnumerable AssignedPawns { get { - Building_Grave.<>c__Iterator158 <>c__Iterator = new Building_Grave.<>c__Iterator158(); - <>c__Iterator.<>f__this = this; - Building_Grave.<>c__Iterator158 expr_0E = <>c__Iterator; - expr_0E.$PC = -2; - return expr_0E; + if (this.assignedPawn != null) + { + yield return this.assignedPawn; + } } } @@ -122,23 +121,23 @@ public StorageSettings GetStoreSettings() public StorageSettings GetParentStoreSettings() { - return this.def.building.fixedStorageSettings; + return base.def.building.fixedStorageSettings; } public override void PostMake() { base.PostMake(); this.storageSettings = new StorageSettings(this); - if (this.def.building.defaultStorageSettings != null) + if (base.def.building.defaultStorageSettings != null) { - this.storageSettings.CopyFrom(this.def.building.defaultStorageSettings); + this.storageSettings.CopyFrom(base.def.building.defaultStorageSettings); } } public override void ExposeData() { base.ExposeData(); - Scribe_Deep.Look(ref this.storageSettings, "storageSettings", new object[] + Scribe_Deep.Look(ref this.storageSettings, "storageSettings", new object[1] { this }); @@ -211,14 +210,33 @@ public override bool TryAcceptThing(Thing thing, bool allowSpecialEffects = true return false; } - [DebuggerHidden] public override IEnumerable GetGizmos() { - Building_Grave.c__Iterator159 c__Iterator = new Building_Grave.c__Iterator159(); - c__Iterator.<>f__this = this; - Building_Grave.c__Iterator159 expr_0E = c__Iterator; - expr_0E.$PC = -2; - return expr_0E; + foreach (Gizmo gizmo in base.GetGizmos()) + { + yield return gizmo; + } + if (this.StorageTabVisible) + { + foreach (Gizmo item in StorageSettingsClipboard.CopyPasteGizmosFor(this.storageSettings)) + { + yield return item; + } + } + if (!this.HasCorpse) + { + yield return (Gizmo)new Command_Action + { + defaultLabel = "CommandGraveAssignColonistLabel".Translate(), + icon = ContentFinder.Get("UI/Commands/AssignOwner", true), + defaultDesc = "CommandGraveAssignColonistDesc".Translate(), + action = (Action)delegate + { + Find.WindowStack.Add(new Dialog_AssignBuildingOwner(((_003CGetGizmos_003Ec__Iterator159)/*Error near IL_01a7: stateMachine*/)._003C_003Ef__this)); + }, + hotKey = KeyBindingDefOf.Misc3 + }; + } } public override string GetInspectString() diff --git a/Assembly-CSharp/RimWorld/Building_Heater.cs b/Assembly-CSharp/RimWorld/Building_Heater.cs index 9a8a5d099..eb7ddb453 100644 --- a/Assembly-CSharp/RimWorld/Building_Heater.cs +++ b/Assembly-CSharp/RimWorld/Building_Heater.cs @@ -1,4 +1,3 @@ -using System; using UnityEngine; using Verse; @@ -10,36 +9,24 @@ public class Building_Heater : Building_TempControl public override void TickRare() { - if (this.compPowerTrader.PowerOn) + if (base.compPowerTrader.PowerOn) { float ambientTemperature = base.AmbientTemperature; - float num; - if (ambientTemperature < 20f) - { - num = 1f; - } - else if (ambientTemperature > 120f) - { - num = 0f; - } - else - { - num = Mathf.InverseLerp(120f, 20f, ambientTemperature); - } - float energyLimit = this.compTempControl.Props.energyPerSecond * num * 4.16666651f; - float num2 = GenTemperature.ControlTemperatureTempChange(base.Position, base.Map, energyLimit, this.compTempControl.targetTemperature); + float num = (float)((!(ambientTemperature < 20.0)) ? ((!(ambientTemperature > 120.0)) ? Mathf.InverseLerp(120f, 20f, ambientTemperature) : 0.0) : 1.0); + float energyLimit = (float)(base.compTempControl.Props.energyPerSecond * num * 4.1666665077209473); + float num2 = GenTemperature.ControlTemperatureTempChange(base.Position, base.Map, energyLimit, base.compTempControl.targetTemperature); bool flag = !Mathf.Approximately(num2, 0f); - CompProperties_Power props = this.compPowerTrader.Props; + CompProperties_Power props = base.compPowerTrader.Props; if (flag) { this.GetRoomGroup().Temperature += num2; - this.compPowerTrader.PowerOutput = -props.basePowerConsumption; + base.compPowerTrader.PowerOutput = (float)(0.0 - props.basePowerConsumption); } else { - this.compPowerTrader.PowerOutput = -props.basePowerConsumption * this.compTempControl.Props.lowPowerConsumptionFactor; + base.compPowerTrader.PowerOutput = (float)((0.0 - props.basePowerConsumption) * base.compTempControl.Props.lowPowerConsumptionFactor); } - this.compTempControl.operatingAtHighPower = flag; + base.compTempControl.operatingAtHighPower = flag; } } } diff --git a/Assembly-CSharp/RimWorld/Building_MarriageSpot.cs b/Assembly-CSharp/RimWorld/Building_MarriageSpot.cs index bd5c0cfef..53f42e667 100644 --- a/Assembly-CSharp/RimWorld/Building_MarriageSpot.cs +++ b/Assembly-CSharp/RimWorld/Building_MarriageSpot.cs @@ -24,23 +24,17 @@ private string UsableNowStatus() if (!this.AnyCoupleForWhichIsValid()) { StringBuilder stringBuilder = new StringBuilder(); - Pair pair; + Pair pair = default(Pair); if (this.TryFindAnyFiancesCouple(out pair)) { if (!MarriageSpotUtility.IsValidMarriageSpotFor(base.Position, pair.First, pair.Second, stringBuilder)) { - return "MarriageSpotNotUsable".Translate(new object[] - { - stringBuilder - }); + return "MarriageSpotNotUsable".Translate(stringBuilder); } } else if (!MarriageSpotUtility.IsValidMarriageSpot(base.Position, base.Map, stringBuilder)) { - return "MarriageSpotNotUsable".Translate(new object[] - { - stringBuilder - }); + return "MarriageSpotNotUsable".Translate(stringBuilder); } } return "MarriageSpotUsable".Translate(); @@ -48,21 +42,21 @@ private string UsableNowStatus() private bool AnyCoupleForWhichIsValid() { - return base.Map.mapPawns.FreeColonistsSpawned.Any(delegate(Pawn p) + return base.Map.mapPawns.FreeColonistsSpawned.Any((Func)delegate(Pawn p) { - Pawn firstDirectRelationPawn = p.relations.GetFirstDirectRelationPawn(PawnRelationDefOf.Fiance, (Pawn x) => x.Spawned); + Pawn firstDirectRelationPawn = p.relations.GetFirstDirectRelationPawn(PawnRelationDefOf.Fiance, (Predicate)((Pawn x) => x.Spawned)); return firstDirectRelationPawn != null && MarriageSpotUtility.IsValidMarriageSpotFor(base.Position, p, firstDirectRelationPawn, null); }); } private bool TryFindAnyFiancesCouple(out Pair fiances) { - foreach (Pawn current in base.Map.mapPawns.FreeColonistsSpawned) + foreach (Pawn item in base.Map.mapPawns.FreeColonistsSpawned) { - Pawn firstDirectRelationPawn = current.relations.GetFirstDirectRelationPawn(PawnRelationDefOf.Fiance, (Pawn x) => x.Spawned); + Pawn firstDirectRelationPawn = item.relations.GetFirstDirectRelationPawn(PawnRelationDefOf.Fiance, (Predicate)((Pawn x) => x.Spawned)); if (firstDirectRelationPawn != null) { - fiances = new Pair(current, firstDirectRelationPawn); + fiances = new Pair(item, firstDirectRelationPawn); return true; } } diff --git a/Assembly-CSharp/RimWorld/Building_NutrientPasteDispenser.cs b/Assembly-CSharp/RimWorld/Building_NutrientPasteDispenser.cs index 255175c30..0b1ca853d 100644 --- a/Assembly-CSharp/RimWorld/Building_NutrientPasteDispenser.cs +++ b/Assembly-CSharp/RimWorld/Building_NutrientPasteDispenser.cs @@ -32,7 +32,7 @@ private List AdjCellsCardinalInBounds { this.cachedAdjCellsCardinal = (from c in GenAdj.CellsAdjacentCardinal(this) where c.InBounds(base.Map) - select c).ToList(); + select c).ToList(); } return this.cachedAdjCellsCardinal; } @@ -58,7 +58,7 @@ public virtual Building AdjacentReachableHopper(Pawn reacher) { IntVec3 c = this.AdjCellsCardinalInBounds[i]; Building edifice = c.GetEdifice(base.Map); - if (edifice != null && edifice.def == ThingDefOf.Hopper && reacher.CanReach(edifice, PathEndMode.Touch, Danger.Deadly, false, TraverseMode.ByPawn)) + if (edifice != null && edifice.def == ThingDefOf.Hopper && reacher.CanReach((Thing)edifice, PathEndMode.Touch, Danger.Deadly, false, TraverseMode.ByPawn)) { return (Building_Storage)edifice; } @@ -72,28 +72,24 @@ public virtual Thing TryDispenseFood() { return null; } - float num = this.def.building.nutritionCostPerDispense - 0.0001f; + float num = (float)(base.def.building.nutritionCostPerDispense - 9.9999997473787516E-05); List list = new List(); while (true) { Thing thing = this.FindFeedInAnyHopper(); if (thing == null) { - break; + Log.Error("Did not find enough food in hoppers while trying to dispense."); + return null; } int num2 = Mathf.Min(thing.stackCount, Mathf.CeilToInt(num / thing.def.ingestible.nutrition)); num -= (float)num2 * thing.def.ingestible.nutrition; list.Add(thing.def); thing.SplitOff(num2); - if (num <= 0f) - { - goto Block_3; - } + if (num <= 0.0) + break; } - Log.Error("Did not find enough food in hoppers while trying to dispense."); - return null; - Block_3: - this.def.building.soundDispense.PlayOneShot(new TargetInfo(base.Position, base.Map, false)); + base.def.building.soundDispense.PlayOneShot(new TargetInfo(base.Position, base.Map, false)); Thing thing2 = ThingMaker.MakeThing(ThingDefOf.MealNutrientPaste, null); CompIngredients compIngredients = thing2.TryGetComp(); for (int i = 0; i < list.Count; i++) @@ -155,7 +151,7 @@ public virtual bool HasEnoughFeedstockInHoppers() { num += (float)thing.stackCount * thing.def.ingestible.nutrition; } - if (num >= this.def.building.nutritionCostPerDispense) + if (num >= base.def.building.nutritionCostPerDispense) { return true; } @@ -165,7 +161,7 @@ public virtual bool HasEnoughFeedstockInHoppers() public static bool IsAcceptableFeedstock(ThingDef def) { - return def.IsNutritionGivingIngestible && def.ingestible.preferability != FoodPreferability.Undefined && (def.ingestible.foodType & FoodTypeFlags.Plant) != FoodTypeFlags.Plant && (def.ingestible.foodType & FoodTypeFlags.Tree) != FoodTypeFlags.Tree; + return def.IsNutritionGivingIngestible && def.ingestible.preferability != 0 && ((int)def.ingestible.foodType & 64) != 64 && ((int)def.ingestible.foodType & 128) != 128; } } } diff --git a/Assembly-CSharp/RimWorld/Building_OrbitalTradeBeacon.cs b/Assembly-CSharp/RimWorld/Building_OrbitalTradeBeacon.cs index 3f3c1c26b..3b5b28d8e 100644 --- a/Assembly-CSharp/RimWorld/Building_OrbitalTradeBeacon.cs +++ b/Assembly-CSharp/RimWorld/Building_OrbitalTradeBeacon.cs @@ -1,7 +1,7 @@ using System; using System.Collections.Generic; -using System.Diagnostics; using System.Linq; +using UnityEngine; using Verse; namespace RimWorld @@ -20,14 +20,23 @@ public IEnumerable TradeableCells } } - [DebuggerHidden] public override IEnumerable GetGizmos() { - Building_OrbitalTradeBeacon.c__Iterator15A c__Iterator15A = new Building_OrbitalTradeBeacon.c__Iterator15A(); - c__Iterator15A.<>f__this = this; - Building_OrbitalTradeBeacon.c__Iterator15A expr_0E = c__Iterator15A; - expr_0E.$PC = -2; - return expr_0E; + foreach (Gizmo gizmo in base.GetGizmos()) + { + yield return gizmo; + } + if (DesignatorUtility.FindAllowedDesignator() != null) + { + yield return (Gizmo)new Command_Action + { + action = new Action(this.MakeMatchingStockpile), + hotKey = KeyBindingDefOf.Misc1, + defaultDesc = "CommandMakeBeaconStockpileDesc".Translate(), + icon = ContentFinder.Get("UI/Designators/ZoneCreate_Stockpile", true), + defaultLabel = "CommandMakeBeaconStockpileLabel".Translate() + }; + } } private void MakeMatchingStockpile() @@ -50,13 +59,13 @@ public static List TradeableCellsAround(IntVec3 pos, Map map) { return Building_OrbitalTradeBeacon.tradeableCells; } - RegionTraverser.BreadthFirstTraverse(region, (Region from, Region r) => r.portal == null, delegate(Region r) + RegionTraverser.BreadthFirstTraverse(region, (RegionEntryPredicate)((Region from, Region r) => r.portal == null), (RegionProcessor)delegate(Region r) { - foreach (IntVec3 current in r.Cells) + foreach (IntVec3 cell in r.Cells) { - if (current.InHorDistOf(pos, 7.9f)) + if (cell.InHorDistOf(pos, 7.9f)) { - Building_OrbitalTradeBeacon.tradeableCells.Add(current); + Building_OrbitalTradeBeacon.tradeableCells.Add(cell); } } return false; @@ -64,15 +73,16 @@ public static List TradeableCellsAround(IntVec3 pos, Map map) return Building_OrbitalTradeBeacon.tradeableCells; } - [DebuggerHidden] public static IEnumerable AllPowered(Map map) { - Building_OrbitalTradeBeacon.c__Iterator15B c__Iterator15B = new Building_OrbitalTradeBeacon.c__Iterator15B(); - c__Iterator15B.map = map; - c__Iterator15B.<$>map = map; - Building_OrbitalTradeBeacon.c__Iterator15B expr_15 = c__Iterator15B; - expr_15.$PC = -2; - return expr_15; + foreach (Building_OrbitalTradeBeacon item in map.listerBuildings.AllBuildingsColonistOfClass()) + { + CompPowerTrader power = item.GetComp(); + if (power == null || power.PowerOn) + { + yield return item; + } + } } } } diff --git a/Assembly-CSharp/RimWorld/Building_PlantGrower.cs b/Assembly-CSharp/RimWorld/Building_PlantGrower.cs index 5ccc3b70c..119f1452e 100644 --- a/Assembly-CSharp/RimWorld/Building_PlantGrower.cs +++ b/Assembly-CSharp/RimWorld/Building_PlantGrower.cs @@ -1,6 +1,5 @@ using System; using System.Collections.Generic; -using System.Diagnostics; using System.Linq; using Verse; @@ -16,28 +15,39 @@ public IEnumerable PlantsOnMe { get { - Building_PlantGrower.<>c__Iterator15C <>c__Iterator15C = new Building_PlantGrower.<>c__Iterator15C(); - <>c__Iterator15C.<>f__this = this; - Building_PlantGrower.<>c__Iterator15C expr_0E = <>c__Iterator15C; - expr_0E.$PC = -2; - return expr_0E; + if (base.Spawned) + { + CellRect.CellRectIterator cri = this.OccupiedRect().GetIterator(); + while (!cri.Done()) + { + List thingList = base.Map.thingGrid.ThingsListAt(cri.Current); + for (int i = 0; i < thingList.Count; i++) + { + Plant p = thingList[i] as Plant; + if (p != null) + { + yield return p; + } + } + cri.MoveNext(); + } + } } } - [DebuggerHidden] public override IEnumerable GetGizmos() { - Building_PlantGrower.c__Iterator15D c__Iterator15D = new Building_PlantGrower.c__Iterator15D(); - c__Iterator15D.<>f__this = this; - Building_PlantGrower.c__Iterator15D expr_0E = c__Iterator15D; - expr_0E.$PC = -2; - return expr_0E; + foreach (Gizmo gizmo in base.GetGizmos()) + { + yield return gizmo; + } + yield return (Gizmo)PlantToGrowSettableUtility.SetPlantToGrowCommand(this); } public override void PostMake() { base.PostMake(); - this.plantDefToGrow = this.def.building.defaultPlantToGrow; + this.plantDefToGrow = base.def.building.defaultPlantToGrow; } public override void SpawnSetup(Map map, bool respawningAfterLoad) @@ -57,19 +67,28 @@ public override void TickRare() { if (this.compPower != null && !this.compPower.PowerOn) { - foreach (Plant current in this.PlantsOnMe) + foreach (Plant item in this.PlantsOnMe) { DamageInfo dinfo = new DamageInfo(DamageDefOf.Rotting, 4, -1f, null, null, null, DamageInfo.SourceCategory.ThingOrUnknown); - current.TakeDamage(dinfo); + item.TakeDamage(dinfo); } } } public override void DeSpawn() { - foreach (Plant current in this.PlantsOnMe.ToList()) + List.Enumerator enumerator = this.PlantsOnMe.ToList().GetEnumerator(); + try { - current.Destroy(DestroyMode.Vanish); + while (enumerator.MoveNext()) + { + Plant current = enumerator.Current; + current.Destroy(DestroyMode.Vanish); + } + } + finally + { + ((IDisposable)(object)enumerator).Dispose(); } base.DeSpawn(); } @@ -79,14 +98,7 @@ public override string GetInspectString() string text = base.GetInspectString(); if (base.Spawned) { - if (GenPlant.GrowthSeasonNow(base.Position, base.Map)) - { - text = text + "\n" + "GrowSeasonHereNow".Translate(); - } - else - { - text = text + "\n" + "CannotGrowBadSeasonTemperature".Translate(); - } + text = ((!GenPlant.GrowthSeasonNow(base.Position, base.Map)) ? (text + "\n" + "CannotGrowBadSeasonTemperature".Translate()) : (text + "\n" + "GrowSeasonHereNow".Translate())); } return text; } @@ -103,12 +115,22 @@ public void SetPlantDefToGrow(ThingDef plantDef) public bool CanAcceptSowNow() { - return this.compPower == null || this.compPower.PowerOn; + if (this.compPower != null && !this.compPower.PowerOn) + { + return false; + } + return true; } virtual Map get_Map() { return base.Map; } + + Map IPlantToGrowSettable.get_Map() + { + //ILSpy generated this explicit interface implementation from .override directive in get_Map + return this.get_Map(); + } } } diff --git a/Assembly-CSharp/RimWorld/Building_PoisonShipPart.cs b/Assembly-CSharp/RimWorld/Building_PoisonShipPart.cs index 38363657f..05599f4ec 100644 --- a/Assembly-CSharp/RimWorld/Building_PoisonShipPart.cs +++ b/Assembly-CSharp/RimWorld/Building_PoisonShipPart.cs @@ -1,4 +1,3 @@ -using System; using UnityEngine; namespace RimWorld @@ -9,7 +8,7 @@ protected override float PlantHarmRange { get { - return Mathf.Min(3f + 30f * ((float)this.age / 60000f), 140f); + return Mathf.Min((float)(3.0 + 30.0 * ((float)base.age / 60000.0)), 140f); } } @@ -17,7 +16,7 @@ protected override int PlantHarmInterval { get { - float f = 4f - 0.6f * (float)this.age / 60000f; + float f = (float)(4.0 - 0.60000002384185791 * (float)base.age / 60000.0); return Mathf.Clamp(Mathf.RoundToInt(f), 2, 4); } } diff --git a/Assembly-CSharp/RimWorld/Building_PowerSwitch.cs b/Assembly-CSharp/RimWorld/Building_PowerSwitch.cs index 25ca6b19b..336c361a5 100644 --- a/Assembly-CSharp/RimWorld/Building_PowerSwitch.cs +++ b/Assembly-CSharp/RimWorld/Building_PowerSwitch.cs @@ -1,4 +1,3 @@ -using System; using System.Text; using Verse; @@ -49,10 +48,9 @@ public override void ExposeData() protected override void ReceiveCompSignal(string signal) { - if (signal == "FlickedOff" || signal == "FlickedOn" || signal == "ScheduledOn" || signal == "ScheduledOff") - { - this.UpdatePowerGrid(); - } + if (!(signal == "FlickedOff") && !(signal == "FlickedOn") && !(signal == "ScheduledOn") && !(signal == "ScheduledOff")) + return; + this.UpdatePowerGrid(); } public override string GetInspectString() diff --git a/Assembly-CSharp/RimWorld/Building_PsychicEmanator.cs b/Assembly-CSharp/RimWorld/Building_PsychicEmanator.cs index 992c2e078..64c217825 100644 --- a/Assembly-CSharp/RimWorld/Building_PsychicEmanator.cs +++ b/Assembly-CSharp/RimWorld/Building_PsychicEmanator.cs @@ -26,7 +26,7 @@ protected override float PlantHarmRange { get { - return Mathf.Min(3f + 40f * ((float)this.age / 60000f), 20f); + return Mathf.Min((float)(3.0 + 40.0 * ((float)base.age / 60000.0)), 20f); } } @@ -54,26 +54,31 @@ public override string GetInspectString() switch (this.droneLevel) { case PsychicDroneLevel.BadLow: + { text = "PsychicDroneLevelLow".Translate(); break; + } case PsychicDroneLevel.BadMedium: + { text = "PsychicDroneLevelMedium".Translate(); break; + } case PsychicDroneLevel.BadHigh: + { text = "PsychicDroneLevelHigh".Translate(); break; + } case PsychicDroneLevel.BadExtreme: + { text = "PsychicDroneLevelExtreme".Translate(); break; } + } if (stringBuilder.Length != 0) { stringBuilder.AppendLine(); } - stringBuilder.Append("PsychicDroneLevel".Translate(new object[] - { - text - })); + stringBuilder.Append("PsychicDroneLevel".Translate(text)); return stringBuilder.ToString(); } @@ -96,14 +101,13 @@ public override void Tick() private void IncreaseDroneLevel() { - if (this.droneLevel == PsychicDroneLevel.BadExtreme) + if (this.droneLevel != PsychicDroneLevel.BadExtreme) { - return; + this.droneLevel += (byte)1; + string text = "LetterPsychicDroneLevelIncreased".Translate(); + Find.LetterStack.ReceiveLetter("LetterLabelPsychicDroneLevelIncreased".Translate(), text, LetterDefOf.BadNonUrgent, (string)null); + SoundDefOf.PsychicPulseGlobal.PlayOneShotOnCamera(base.Map); } - this.droneLevel += 1; - string text = "LetterPsychicDroneLevelIncreased".Translate(); - Find.LetterStack.ReceiveLetter("LetterLabelPsychicDroneLevelIncreased".Translate(), text, LetterDefOf.BadNonUrgent, null); - SoundDefOf.PsychicPulseGlobal.PlayOneShotOnCamera(base.Map); } private void DoAnimalInsanityPulse() @@ -111,11 +115,11 @@ private void DoAnimalInsanityPulse() IEnumerable enumerable = from p in base.Map.mapPawns.AllPawnsSpawned where p.RaceProps.Animal && p.Position.InHorDistOf(base.Position, 25f) select p; - foreach (Pawn current in enumerable) + foreach (Pawn item in enumerable) { - current.mindState.mentalStateHandler.TryStartMentalState(MentalStateDefOf.Manhunter, null, false, false, null); + item.mindState.mentalStateHandler.TryStartMentalState(MentalStateDefOf.Manhunter, (string)null, false, false, null); } - Messages.Message("MessageAnimalInsanityPulse".Translate(), this, MessageSound.Negative); + Messages.Message("MessageAnimalInsanityPulse".Translate(), (Thing)this, MessageSound.Negative); SoundDefOf.PsychicPulseGlobal.PlayOneShotOnCamera(base.Map); if (base.Map == Find.VisibleMap) { diff --git a/Assembly-CSharp/RimWorld/Building_ResearchBench.cs b/Assembly-CSharp/RimWorld/Building_ResearchBench.cs index fcba58d47..8bce16426 100644 --- a/Assembly-CSharp/RimWorld/Building_ResearchBench.cs +++ b/Assembly-CSharp/RimWorld/Building_ResearchBench.cs @@ -1,4 +1,3 @@ -using System; using Verse; namespace RimWorld diff --git a/Assembly-CSharp/RimWorld/Building_Sarcophagus.cs b/Assembly-CSharp/RimWorld/Building_Sarcophagus.cs index 98e2ae5db..c43c9bac3 100644 --- a/Assembly-CSharp/RimWorld/Building_Sarcophagus.cs +++ b/Assembly-CSharp/RimWorld/Building_Sarcophagus.cs @@ -1,4 +1,3 @@ -using System; using Verse; namespace RimWorld @@ -32,11 +31,11 @@ public override void Notify_CorpseBuried(Pawn worker) if (this.thisIsFirstBodyEver && worker.IsColonist && base.Corpse.InnerPawn.def.race.Humanlike && !base.Corpse.everBuriedInSarcophagus) { base.Corpse.everBuriedInSarcophagus = true; - foreach (Pawn current in base.Map.mapPawns.FreeColonists) + foreach (Pawn freeColonist in base.Map.mapPawns.FreeColonists) { - if (current.needs.mood != null) + if (freeColonist.needs.mood != null) { - current.needs.mood.thoughts.memories.TryGainMemory(ThoughtDefOf.KnowBuriedInSarcophagus, null); + freeColonist.needs.mood.thoughts.memories.TryGainMemory(ThoughtDefOf.KnowBuriedInSarcophagus, null); } } } diff --git a/Assembly-CSharp/RimWorld/Building_ShipComputerCore.cs b/Assembly-CSharp/RimWorld/Building_ShipComputerCore.cs index 5eaddc22b..c6ac066d2 100644 --- a/Assembly-CSharp/RimWorld/Building_ShipComputerCore.cs +++ b/Assembly-CSharp/RimWorld/Building_ShipComputerCore.cs @@ -1,7 +1,7 @@ using System; using System.Collections.Generic; -using System.Diagnostics; using System.Linq; +using UnityEngine; using Verse; namespace RimWorld @@ -12,18 +12,33 @@ private bool CanLaunchNow { get { - return !ShipUtility.LaunchFailReasons(this).Any(); + return !ShipUtility.LaunchFailReasons(this).Any(); } } - [DebuggerHidden] public override IEnumerable GetGizmos() { - Building_ShipComputerCore.c__Iterator149 c__Iterator = new Building_ShipComputerCore.c__Iterator149(); - c__Iterator.<>f__this = this; - Building_ShipComputerCore.c__Iterator149 expr_0E = c__Iterator; - expr_0E.$PC = -2; - return expr_0E; + foreach (Gizmo gizmo in base.GetGizmos()) + { + yield return gizmo; + } + Command_Action launch = new Command_Action + { + action = new Action(this.TryLaunch), + defaultLabel = "CommandShipLaunch".Translate(), + defaultDesc = "CommandShipLaunchDesc".Translate() + }; + if (!this.CanLaunchNow) + { + launch.Disable(ShipUtility.LaunchFailReasons(this).First()); + } + if (ShipCountdown.CountingDown) + { + launch.Disable((string)null); + } + launch.hotKey = KeyBindingDefOf.Misc1; + launch.icon = ContentFinder.Get("UI/Commands/LaunchShip", true); + yield return (Gizmo)launch; } private void TryLaunch() diff --git a/Assembly-CSharp/RimWorld/Building_Storage.cs b/Assembly-CSharp/RimWorld/Building_Storage.cs index 3acbf6fa6..8ca5546f2 100644 --- a/Assembly-CSharp/RimWorld/Building_Storage.cs +++ b/Assembly-CSharp/RimWorld/Building_Storage.cs @@ -1,6 +1,4 @@ -using System; using System.Collections.Generic; -using System.Diagnostics; using System.Linq; using Verse; @@ -26,7 +24,7 @@ public bool IgnoreStoredThingsBeauty { get { - return this.def.building.ignoreStoredThingsBeauty; + return base.def.building.ignoreStoredThingsBeauty; } } @@ -47,21 +45,19 @@ public virtual void Notify_LostThing(Thing newItem) { } - [DebuggerHidden] public virtual IEnumerable AllSlotCells() { - Building_Storage.c__Iterator14A c__Iterator14A = new Building_Storage.c__Iterator14A(); - c__Iterator14A.<>f__this = this; - Building_Storage.c__Iterator14A expr_0E = c__Iterator14A; - expr_0E.$PC = -2; - return expr_0E; + foreach (IntVec3 item in GenAdj.CellsOccupiedBy(this)) + { + yield return item; + } } public List AllSlotCellsList() { if (this.cachedOccupiedCells == null) { - this.cachedOccupiedCells = this.AllSlotCells().ToList(); + this.cachedOccupiedCells = this.AllSlotCells().ToList(); } return this.cachedOccupiedCells; } @@ -73,7 +69,7 @@ public StorageSettings GetStoreSettings() public StorageSettings GetParentStoreSettings() { - return this.def.building.fixedStorageSettings; + return base.def.building.fixedStorageSettings; } public string SlotYielderLabel() @@ -85,23 +81,23 @@ public override void PostMake() { base.PostMake(); this.settings = new StorageSettings(this); - if (this.def.building.defaultStorageSettings != null) + if (base.def.building.defaultStorageSettings != null) { - this.settings.CopyFrom(this.def.building.defaultStorageSettings); + this.settings.CopyFrom(base.def.building.defaultStorageSettings); } } public override void SpawnSetup(Map map, bool respawningAfterLoad) { base.SpawnSetup(map, respawningAfterLoad); - this.cachedOccupiedCells = this.AllSlotCells().ToList(); + this.cachedOccupiedCells = this.AllSlotCells().ToList(); this.slotGroup = new SlotGroup(this); } public override void ExposeData() { base.ExposeData(); - Scribe_Deep.Look(ref this.settings, "settings", new object[] + Scribe_Deep.Look(ref this.settings, "settings", new object[1] { this }); @@ -116,19 +112,27 @@ public override void DeSpawn() base.DeSpawn(); } - [DebuggerHidden] public override IEnumerable GetGizmos() { - Building_Storage.c__Iterator14B c__Iterator14B = new Building_Storage.c__Iterator14B(); - c__Iterator14B.<>f__this = this; - Building_Storage.c__Iterator14B expr_0E = c__Iterator14B; - expr_0E.$PC = -2; - return expr_0E; + foreach (Gizmo gizmo in base.GetGizmos()) + { + yield return gizmo; + } + foreach (Gizmo item in StorageSettingsClipboard.CopyPasteGizmosFor(this.settings)) + { + yield return item; + } } virtual Map get_Map() { return base.Map; } + + Map ISlotGroupParent.get_Map() + { + //ILSpy generated this explicit interface implementation from .override directive in get_Map + return this.get_Map(); + } } } diff --git a/Assembly-CSharp/RimWorld/Building_SunLamp.cs b/Assembly-CSharp/RimWorld/Building_SunLamp.cs index c15a6b189..7374fad85 100644 --- a/Assembly-CSharp/RimWorld/Building_SunLamp.cs +++ b/Assembly-CSharp/RimWorld/Building_SunLamp.cs @@ -1,7 +1,7 @@ using System; using System.Collections.Generic; -using System.Diagnostics; using System.Linq; +using UnityEngine; using Verse; namespace RimWorld @@ -12,18 +12,27 @@ public IEnumerable GrowableCells { get { - return GenRadial.RadialCellsAround(base.Position, this.def.specialDisplayRadius, true); + return GenRadial.RadialCellsAround(base.Position, base.def.specialDisplayRadius, true); } } - [DebuggerHidden] public override IEnumerable GetGizmos() { - Building_SunLamp.c__Iterator15E c__Iterator15E = new Building_SunLamp.c__Iterator15E(); - c__Iterator15E.<>f__this = this; - Building_SunLamp.c__Iterator15E expr_0E = c__Iterator15E; - expr_0E.$PC = -2; - return expr_0E; + foreach (Gizmo gizmo in base.GetGizmos()) + { + yield return gizmo; + } + if (DesignatorUtility.FindAllowedDesignator() != null) + { + yield return (Gizmo)new Command_Action + { + action = new Action(this.MakeMatchingGrowZone), + hotKey = KeyBindingDefOf.Misc2, + defaultDesc = "CommandSunLampMakeGrowingZoneDesc".Translate(), + icon = ContentFinder.Get("UI/Designators/ZoneCreate_Growing", true), + defaultLabel = "CommandSunLampMakeGrowingZoneLabel".Translate() + }; + } } private void MakeMatchingGrowZone() diff --git a/Assembly-CSharp/RimWorld/Building_TempControl.cs b/Assembly-CSharp/RimWorld/Building_TempControl.cs index 6beef2b92..1190d71c1 100644 --- a/Assembly-CSharp/RimWorld/Building_TempControl.cs +++ b/Assembly-CSharp/RimWorld/Building_TempControl.cs @@ -1,4 +1,3 @@ -using System; using Verse; namespace RimWorld diff --git a/Assembly-CSharp/RimWorld/Building_Trap.cs b/Assembly-CSharp/RimWorld/Building_Trap.cs index d21adcb49..c229262be 100644 --- a/Assembly-CSharp/RimWorld/Building_Trap.cs +++ b/Assembly-CSharp/RimWorld/Building_Trap.cs @@ -1,4 +1,3 @@ -using System; using System.Collections.Generic; using UnityEngine; using Verse; @@ -61,19 +60,11 @@ public override void Tick() protected virtual float SpringChance(Pawn p) { - float num; - if (this.KnowsOfTrap(p)) - { - num = 0.004f; - } - else - { - num = this.GetStatValue(StatDefOf.TrapSpringChance, true); - } + float num = (float)((!this.KnowsOfTrap(p)) ? this.GetStatValue(StatDefOf.TrapSpringChance, true) : 0.0040000001899898052); num *= GenMath.LerpDouble(0.4f, 0.8f, 0f, 1f, p.BodySize); if (p.RaceProps.Animal) { - num *= 0.1f; + num = (float)(num * 0.10000000149011612); } return Mathf.Clamp01(num); } @@ -83,16 +74,9 @@ private void CheckSpring(Pawn p) if (Rand.Value < this.SpringChance(p)) { this.Spring(p); - if (p.Faction == Faction.OfPlayer || p.HostFaction == Faction.OfPlayer) - { - Find.LetterStack.ReceiveLetter("LetterFriendlyTrapSprungLabel".Translate(new object[] - { - p.NameStringShort - }), "LetterFriendlyTrapSprung".Translate(new object[] - { - p.NameStringShort - }), LetterDefOf.BadNonUrgent, new TargetInfo(base.Position, base.Map, false), null); - } + if (p.Faction != Faction.OfPlayer && p.HostFaction != Faction.OfPlayer) + return; + Find.LetterStack.ReceiveLetter("LetterFriendlyTrapSprungLabel".Translate(p.NameStringShort), "LetterFriendlyTrapSprung".Translate(p.NameStringShort), LetterDefOf.BadNonUrgent, new TargetInfo(base.Position, base.Map, false), (string)null); } } @@ -111,33 +95,37 @@ public bool KnowsOfTrap(Pawn p) return true; } Lord lord = p.GetLord(); - return p.guest != null && lord != null && lord.LordJob is LordJob_FormAndSendCaravan; + if (p.guest != null && lord != null && lord.LordJob is LordJob_FormAndSendCaravan) + { + return true; + } + return false; } public override ushort PathFindCostFor(Pawn p) { if (!this.Armed) { - return 0; + return (ushort)0; } if (this.KnowsOfTrap(p)) { - return 800; + return (ushort)800; } - return 0; + return (ushort)0; } public override ushort PathWalkCostFor(Pawn p) { if (!this.Armed) { - return 0; + return (ushort)0; } if (this.KnowsOfTrap(p)) { - return 30; + return (ushort)30; } - return 0; + return (ushort)0; } public override bool IsDangerousFor(Pawn p) @@ -152,15 +140,7 @@ public override string GetInspectString() { text += "\n"; } - if (this.Armed) - { - text += "TrapArmed".Translate(); - } - else - { - text += "TrapNotArmed".Translate(); - } - return text; + return (!this.Armed) ? (text + "TrapNotArmed".Translate()) : (text + "TrapArmed".Translate()); } public void Spring(Pawn p) diff --git a/Assembly-CSharp/RimWorld/Building_TrapExplosive.cs b/Assembly-CSharp/RimWorld/Building_TrapExplosive.cs index 823ba68d8..041f37239 100644 --- a/Assembly-CSharp/RimWorld/Building_TrapExplosive.cs +++ b/Assembly-CSharp/RimWorld/Building_TrapExplosive.cs @@ -1,4 +1,3 @@ -using System; using Verse; namespace RimWorld diff --git a/Assembly-CSharp/RimWorld/Building_TrapRearmable.cs b/Assembly-CSharp/RimWorld/Building_TrapRearmable.cs index 409f5446d..e6b27c35f 100644 --- a/Assembly-CSharp/RimWorld/Building_TrapRearmable.cs +++ b/Assembly-CSharp/RimWorld/Building_TrapRearmable.cs @@ -1,6 +1,5 @@ using System; using System.Collections.Generic; -using System.Diagnostics; using UnityEngine; using Verse; using Verse.Sound; @@ -37,7 +36,7 @@ public override Graphic Graphic } if (this.graphicUnarmedInt == null) { - this.graphicUnarmedInt = this.def.building.trapUnarmedGraphicData.GraphicColoredFor(this); + this.graphicUnarmedInt = base.def.building.trapUnarmedGraphicData.GraphicColoredFor(this); } return this.graphicUnarmedInt; } @@ -59,7 +58,7 @@ protected override void SpringSub(Pawn p) } if (this.autoRearm) { - base.Map.designationManager.AddDesignation(new Designation(this, DesignationDefOf.RearmTrap)); + base.Map.designationManager.AddDesignation(new Designation((Thing)this, DesignationDefOf.RearmTrap)); } } @@ -71,31 +70,39 @@ public void Rearm() private void DamagePawn(Pawn p) { - BodyPartHeight height = (Rand.Value >= 0.666f) ? BodyPartHeight.Middle : BodyPartHeight.Top; + BodyPartHeight height = (BodyPartHeight)((!(Rand.Value < 0.66600000858306885)) ? 2 : 3); int num = Mathf.RoundToInt(this.GetStatValue(StatDefOf.TrapMeleeDamage, true) * Building_TrapRearmable.TrapDamageFactor.RandomInRange); int randomInRange = Building_TrapRearmable.DamageCount.RandomInRange; - for (int i = 0; i < randomInRange; i++) + int num2 = 0; + while (num2 < randomInRange && num > 0) { - if (num <= 0) - { - break; - } - int num2 = Mathf.Max(1, Mathf.RoundToInt(Rand.Value * (float)num)); - num -= num2; - DamageInfo dinfo = new DamageInfo(DamageDefOf.Stab, num2, -1f, this, null, null, DamageInfo.SourceCategory.ThingOrUnknown); + int num3 = Mathf.Max(1, Mathf.RoundToInt(Rand.Value * (float)num)); + num -= num3; + DamageInfo dinfo = new DamageInfo(DamageDefOf.Stab, num3, -1f, this, null, null, DamageInfo.SourceCategory.ThingOrUnknown); dinfo.SetBodyRegion(height, BodyPartDepth.Outside); p.TakeDamage(dinfo); + num2++; } } - [DebuggerHidden] public override IEnumerable GetGizmos() { - Building_TrapRearmable.c__Iterator147 c__Iterator = new Building_TrapRearmable.c__Iterator147(); - c__Iterator.<>f__this = this; - Building_TrapRearmable.c__Iterator147 expr_0E = c__Iterator; - expr_0E.$PC = -2; - return expr_0E; + foreach (Gizmo gizmo in base.GetGizmos()) + { + yield return gizmo; + } + yield return (Gizmo)new Command_Toggle + { + defaultLabel = "CommandAutoRearm".Translate(), + defaultDesc = "CommandAutoRearmDesc".Translate(), + hotKey = KeyBindingDefOf.Misc3, + icon = TexCommand.RearmTrap, + isActive = (Func)(() => ((_003CGetGizmos_003Ec__Iterator147)/*Error near IL_0105: stateMachine*/)._003C_003Ef__this.autoRearm), + toggleAction = (Action)delegate + { + ((_003CGetGizmos_003Ec__Iterator147)/*Error near IL_011c: stateMachine*/)._003C_003Ef__this.autoRearm = !((_003CGetGizmos_003Ec__Iterator147)/*Error near IL_011c: stateMachine*/)._003C_003Ef__this.autoRearm; + } + }; } } } diff --git a/Assembly-CSharp/RimWorld/Building_Turret.cs b/Assembly-CSharp/RimWorld/Building_Turret.cs index c721a712d..7ac1d76d4 100644 --- a/Assembly-CSharp/RimWorld/Building_Turret.cs +++ b/Assembly-CSharp/RimWorld/Building_Turret.cs @@ -1,4 +1,3 @@ -using System; using Verse; using Verse.AI; @@ -90,7 +89,7 @@ public override void ExposeData() base.ExposeData(); Scribe_TargetInfo.Look(ref this.forcedTarget, "forcedTarget"); Scribe_TargetInfo.Look(ref this.lastAttackedTarget, "lastAttackedTarget"); - Scribe_Deep.Look(ref this.stunner, "stunner", new object[] + Scribe_Deep.Look(ref this.stunner, "stunner", new object[1] { this }); @@ -100,12 +99,11 @@ public override void ExposeData() public override void PreApplyDamage(DamageInfo dinfo, out bool absorbed) { base.PreApplyDamage(dinfo, out absorbed); - if (absorbed) + if (!absorbed) { - return; + this.stunner.Notify_DamageApplied(dinfo, true); + absorbed = false; } - this.stunner.Notify_DamageApplied(dinfo, true); - absorbed = false; } public abstract void OrderAttack(LocalTargetInfo targ); @@ -118,7 +116,11 @@ public bool ThreatDisabled() return true; } CompMannable comp2 = base.GetComp(); - return comp2 != null && !comp2.MannedNow; + if (comp2 != null && !comp2.MannedNow) + { + return true; + } + return false; } protected void OnAttackedTarget(LocalTargetInfo target) diff --git a/Assembly-CSharp/RimWorld/Building_TurretGun.cs b/Assembly-CSharp/RimWorld/Building_TurretGun.cs index 74bb67f5b..77abb2c56 100644 --- a/Assembly-CSharp/RimWorld/Building_TurretGun.cs +++ b/Assembly-CSharp/RimWorld/Building_TurretGun.cs @@ -1,6 +1,5 @@ using System; using System.Collections.Generic; -using System.Diagnostics; using System.Linq; using System.Text; using UnityEngine; @@ -89,7 +88,7 @@ public Thing Gun { if (this.gunInt == null) { - this.gunInt = ThingMaker.MakeThing(this.def.building.turretGunDef, null); + this.gunInt = ThingMaker.MakeThing(base.def.building.turretGunDef, null); List allVerbs = this.gunInt.TryGetComp().AllVerbs; for (int i = 0; i < allVerbs.Count; i++) { @@ -150,25 +149,22 @@ public override void OrderAttack(LocalTargetInfo targ) { if (!targ.IsValid) { - if (this.forcedTarget.IsValid) + if (base.forcedTarget.IsValid) { this.ResetForcedTarget(); } - return; } - if ((targ.Cell - base.Position).LengthHorizontal < this.GunCompEq.PrimaryVerb.verbProps.minRange) + else if ((targ.Cell - base.Position).LengthHorizontal < this.GunCompEq.PrimaryVerb.verbProps.minRange) { - Messages.Message("MessageTargetBelowMinimumRange".Translate(), this, MessageSound.RejectInput); - return; + Messages.Message("MessageTargetBelowMinimumRange".Translate(), (Thing)this, MessageSound.RejectInput); } - if ((targ.Cell - base.Position).LengthHorizontal > this.GunCompEq.PrimaryVerb.verbProps.range) + else if ((targ.Cell - base.Position).LengthHorizontal > this.GunCompEq.PrimaryVerb.verbProps.range) { - Messages.Message("MessageTargetBeyondMaximumRange".Translate(), this, MessageSound.RejectInput); - return; + Messages.Message("MessageTargetBeyondMaximumRange".Translate(), (Thing)this, MessageSound.RejectInput); } - if (this.forcedTarget != targ) + else if (base.forcedTarget != targ) { - this.forcedTarget = targ; + base.forcedTarget = targ; if (this.burstCooldownTicksLeft <= 0) { this.TryStartShootSomething(false); @@ -179,7 +175,7 @@ public override void OrderAttack(LocalTargetInfo targ) public override void Tick() { base.Tick(); - if (this.forcedTarget.IsValid && !this.CanSetForcedTarget) + if (base.forcedTarget.IsValid && !this.CanSetForcedTarget) { this.ResetForcedTarget(); } @@ -187,15 +183,14 @@ public override void Tick() { this.holdFire = false; } - if (this.forcedTarget.ThingDestroyed) + if (base.forcedTarget.ThingDestroyed) { this.ResetForcedTarget(); } - bool flag = (this.powerComp == null || this.powerComp.PowerOn) && (this.mannableComp == null || this.mannableComp.MannedNow); - if (flag && base.Spawned) + if ((this.powerComp == null || this.powerComp.PowerOn) && (this.mannableComp == null || this.mannableComp.MannedNow) && base.Spawned) { this.GunCompEq.verbTracker.VerbsTick(); - if (!this.stunner.Stunned && this.GunCompEq.PrimaryVerb.state != VerbState.Bursting) + if (!base.stunner.Stunned && this.GunCompEq.PrimaryVerb.state != VerbState.Bursting) { if (this.WarmingUp) { @@ -230,40 +225,42 @@ protected void TryStartShootSomething(bool canBeginBurstImmediately) if (!base.Spawned || (this.holdFire && this.CanToggleHoldFire) || (this.GunCompEq.PrimaryVerb.verbProps.projectileDef.projectile.flyOverhead && base.Map.roofGrid.Roofed(base.Position))) { this.ResetCurrentTarget(); - return; - } - bool isValid = this.currentTargetInt.IsValid; - if (this.forcedTarget.IsValid) - { - this.currentTargetInt = this.forcedTarget; } else { - this.currentTargetInt = this.TryFindNewTarget(); - } - if (!isValid && this.currentTargetInt.IsValid) - { - SoundDefOf.TurretAcquireTarget.PlayOneShot(new TargetInfo(base.Position, base.Map, false)); - } - if (this.currentTargetInt.IsValid) - { - if (this.def.building.turretBurstWarmupTime > 0f) + bool isValid = this.currentTargetInt.IsValid; + if (base.forcedTarget.IsValid) { - this.burstWarmupTicksLeft = this.def.building.turretBurstWarmupTime.SecondsToTicks(); + this.currentTargetInt = base.forcedTarget; } - else if (canBeginBurstImmediately) + else + { + this.currentTargetInt = this.TryFindNewTarget(); + } + if (!isValid && this.currentTargetInt.IsValid) { - this.BeginBurst(); + SoundDefOf.TurretAcquireTarget.PlayOneShot(new TargetInfo(base.Position, base.Map, false)); + } + if (this.currentTargetInt.IsValid) + { + if (base.def.building.turretBurstWarmupTime > 0.0) + { + this.burstWarmupTicksLeft = base.def.building.turretBurstWarmupTime.SecondsToTicks(); + } + else if (canBeginBurstImmediately) + { + this.BeginBurst(); + } + else + { + this.burstWarmupTicksLeft = 1; + } } else { - this.burstWarmupTicksLeft = 1; + this.ResetCurrentTarget(); } } - else - { - this.ResetCurrentTarget(); - } } protected LocalTargetInfo TryFindNewTarget() @@ -272,24 +269,24 @@ protected LocalTargetInfo TryFindNewTarget() Faction faction = attackTargetSearcher.Thing.Faction; float range = this.GunCompEq.PrimaryVerb.verbProps.range; float minRange = this.GunCompEq.PrimaryVerb.verbProps.minRange; - Building t; - if (Rand.Value < 0.5f && this.GunCompEq.PrimaryVerb.verbProps.projectileDef.projectile.flyOverhead && faction.HostileTo(Faction.OfPlayer) && base.Map.listerBuildings.allBuildingsColonist.Where(delegate(Building x) + Building t = default(Building); + if (Rand.Value < 0.5 && this.GunCompEq.PrimaryVerb.verbProps.projectileDef.projectile.flyOverhead && faction.HostileTo(Faction.OfPlayer) && base.Map.listerBuildings.allBuildingsColonist.Where((Func)delegate(Building x) { - float num = (float)x.Position.DistanceToSquared(this.Position); + float num = (float)x.Position.DistanceToSquared(base.Position); return num > minRange * minRange && num < range * range; - }).TryRandomElement(out t)) + }).TryRandomElement(out t)) { - return t; + return (Thing)t; } TargetScanFlags targetScanFlags = TargetScanFlags.NeedThreat; if (!this.GunCompEq.PrimaryVerb.verbProps.projectileDef.projectile.flyOverhead) { - targetScanFlags |= TargetScanFlags.NeedLOSToAll; - targetScanFlags |= TargetScanFlags.LOSBlockableByGas; + targetScanFlags = (TargetScanFlags)(byte)((int)targetScanFlags | 3); + targetScanFlags = (TargetScanFlags)(byte)((int)targetScanFlags | 64); } if (this.GunCompEq.PrimaryVerb.verbProps.ai_IsIncendiary) { - targetScanFlags |= TargetScanFlags.NeedNonBurning; + targetScanFlags = (TargetScanFlags)(byte)((int)targetScanFlags | 16); } return (Thing)AttackTargetFinder.BestShootTargetFromCurrentPosition(attackTargetSearcher, new Predicate(this.IsValidTarget), range, minRange, targetScanFlags); } @@ -336,9 +333,9 @@ protected void BeginBurst() protected void BurstComplete() { - if (this.def.building.turretBurstCooldownTime >= 0f) + if (base.def.building.turretBurstCooldownTime >= 0.0) { - this.burstCooldownTicksLeft = this.def.building.turretBurstCooldownTime.SecondsToTicks(); + this.burstCooldownTicksLeft = base.def.building.turretBurstCooldownTime.SecondsToTicks(); } else { @@ -356,7 +353,7 @@ public override string GetInspectString() stringBuilder.AppendLine(inspectString); } stringBuilder.AppendLine("GunInstalled".Translate() + ": " + this.Gun.Label); - if (this.GunCompEq.PrimaryVerb.verbProps.minRange > 0f) + if (this.GunCompEq.PrimaryVerb.verbProps.minRange > 0.0) { stringBuilder.AppendLine("MinimumRange".Translate() + ": " + this.GunCompEq.PrimaryVerb.verbProps.minRange.ToString("F0")); } @@ -364,7 +361,7 @@ public override string GetInspectString() { stringBuilder.AppendLine("CanFireIn".Translate() + ": " + this.burstCooldownTicksLeft.TicksToSecondsString()); } - if (this.def.building.turretShellDef != null) + if (base.def.building.turretShellDef != null) { if (this.loaded) { @@ -387,31 +384,25 @@ public override void Draw() public override void DrawExtraSelectionOverlays() { float range = this.GunCompEq.PrimaryVerb.verbProps.range; - if (range < 90f) + if (range < 90.0) { GenDraw.DrawRadiusRing(base.Position, range); } float minRange = this.GunCompEq.PrimaryVerb.verbProps.minRange; - if (minRange < 90f && minRange > 0.1f) + if (minRange < 90.0 && minRange > 0.10000000149011612) { GenDraw.DrawRadiusRing(base.Position, minRange); } if (this.WarmingUp) { - int degreesWide = (int)((float)this.burstWarmupTicksLeft * 0.5f); - GenDraw.DrawAimPie(this, this.CurrentTarget, degreesWide, (float)this.def.size.x * 0.5f); + int degreesWide = (int)((float)this.burstWarmupTicksLeft * 0.5); + GenDraw.DrawAimPie(this, this.CurrentTarget, degreesWide, (float)((float)base.def.size.x * 0.5)); } - if (this.forcedTarget.IsValid && (!this.forcedTarget.HasThing || this.forcedTarget.Thing.Spawned)) + if (base.forcedTarget.IsValid) { - Vector3 b; - if (this.forcedTarget.HasThing) - { - b = this.forcedTarget.Thing.TrueCenter(); - } - else - { - b = this.forcedTarget.Cell.ToVector3Shifted(); - } + if (base.forcedTarget.HasThing && !base.forcedTarget.Thing.Spawned) + return; + Vector3 b = (!base.forcedTarget.HasThing) ? base.forcedTarget.Cell.ToVector3Shifted() : base.forcedTarget.Thing.TrueCenter(); Vector3 a = this.TrueCenter(); b.y = Altitudes.AltitudeFor(AltitudeLayer.MetaOverlays); a.y = b.y; @@ -419,19 +410,67 @@ public override void DrawExtraSelectionOverlays() } } - [DebuggerHidden] public override IEnumerable GetGizmos() { - Building_TurretGun.c__Iterator148 c__Iterator = new Building_TurretGun.c__Iterator148(); - c__Iterator.<>f__this = this; - Building_TurretGun.c__Iterator148 expr_0E = c__Iterator; - expr_0E.$PC = -2; - return expr_0E; + foreach (Gizmo gizmo in base.GetGizmos()) + { + yield return gizmo; + } + if (this.CanSetForcedTarget) + { + yield return (Gizmo)new Command_VerbTarget + { + defaultLabel = "CommandSetForceAttackTarget".Translate(), + defaultDesc = "CommandSetForceAttackTargetDesc".Translate(), + icon = ContentFinder.Get("UI/Commands/Attack", true), + verb = this.GunCompEq.PrimaryVerb, + hotKey = KeyBindingDefOf.Misc4 + }; + } + if (base.forcedTarget.IsValid) + { + Command_Action stop = new Command_Action + { + defaultLabel = "CommandStopForceAttack".Translate(), + defaultDesc = "CommandStopForceAttackDesc".Translate(), + icon = ContentFinder.Get("UI/Commands/Halt", true), + action = (Action)delegate + { + ((_003CGetGizmos_003Ec__Iterator148)/*Error near IL_01b6: stateMachine*/)._003C_003Ef__this.ResetForcedTarget(); + SoundDefOf.TickLow.PlayOneShotOnCamera(null); + } + }; + if (!base.forcedTarget.IsValid) + { + stop.Disable("CommandStopAttackFailNotForceAttacking".Translate()); + } + stop.hotKey = KeyBindingDefOf.Misc5; + yield return (Gizmo)stop; + } + if (this.CanToggleHoldFire) + { + yield return (Gizmo)new Command_Toggle + { + defaultLabel = "CommandHoldFire".Translate(), + defaultDesc = "CommandHoldFireDesc".Translate(), + icon = ContentFinder.Get("UI/Commands/HoldFire", true), + hotKey = KeyBindingDefOf.Misc6, + toggleAction = (Action)delegate + { + ((_003CGetGizmos_003Ec__Iterator148)/*Error near IL_028a: stateMachine*/)._003C_003Ef__this.holdFire = !((_003CGetGizmos_003Ec__Iterator148)/*Error near IL_028a: stateMachine*/)._003C_003Ef__this.holdFire; + if (((_003CGetGizmos_003Ec__Iterator148)/*Error near IL_028a: stateMachine*/)._003C_003Ef__this.holdFire) + { + ((_003CGetGizmos_003Ec__Iterator148)/*Error near IL_028a: stateMachine*/)._003C_003Ef__this.ResetForcedTarget(); + } + }, + isActive = (Func)(() => ((_003CGetGizmos_003Ec__Iterator148)/*Error near IL_02a1: stateMachine*/)._003C_003Ef__this.holdFire) + }; + } } private void ResetForcedTarget() { - this.forcedTarget = LocalTargetInfo.Invalid; + base.forcedTarget = LocalTargetInfo.Invalid; this.burstWarmupTicksLeft = 0; if (this.burstCooldownTicksLeft <= 0) { diff --git a/Assembly-CSharp/RimWorld/Building_Vent.cs b/Assembly-CSharp/RimWorld/Building_Vent.cs index 945c7b268..88abf7a28 100644 --- a/Assembly-CSharp/RimWorld/Building_Vent.cs +++ b/Assembly-CSharp/RimWorld/Building_Vent.cs @@ -1,4 +1,3 @@ -using System; using System.Text; using Verse; diff --git a/Assembly-CSharp/RimWorld/Building_WorkTable.cs b/Assembly-CSharp/RimWorld/Building_WorkTable.cs index 0ae54a26d..7d2ba3a5e 100644 --- a/Assembly-CSharp/RimWorld/Building_WorkTable.cs +++ b/Assembly-CSharp/RimWorld/Building_WorkTable.cs @@ -1,4 +1,3 @@ -using System; using System.Collections.Generic; using Verse; @@ -18,7 +17,15 @@ public bool CanWorkWithoutPower { get { - return this.powerComp == null || this.def.building.unpoweredWorkTableWorkSpeedFactor > 0f; + if (this.powerComp == null) + { + return true; + } + if (base.def.building.unpoweredWorkTableWorkSpeedFactor > 0.0) + { + return true; + } + return false; } } @@ -26,7 +33,19 @@ public virtual bool UsableNow { get { - return (this.CanWorkWithoutPower || (this.powerComp != null && this.powerComp.PowerOn)) && (this.refuelableComp == null || this.refuelableComp.HasFuel) && (this.breakdownableComp == null || !this.breakdownableComp.BrokenDown); + if (!this.CanWorkWithoutPower && (this.powerComp == null || !this.powerComp.PowerOn)) + { + return false; + } + if (this.refuelableComp != null && !this.refuelableComp.HasFuel) + { + return false; + } + if (this.breakdownableComp != null && this.breakdownableComp.BrokenDown) + { + return false; + } + return true; } } @@ -62,7 +81,7 @@ public Building_WorkTable() public override void ExposeData() { base.ExposeData(); - Scribe_Deep.Look(ref this.billStack, "billStack", new object[] + Scribe_Deep.Look(ref this.billStack, "billStack", new object[1] { this }); @@ -93,5 +112,11 @@ virtual Map get_Map() { return base.Map; } + + Map IBillGiver.get_Map() + { + //ILSpy generated this explicit interface implementation from .override directive in get_Map + return this.get_Map(); + } } } diff --git a/Assembly-CSharp/RimWorld/Building_WorkTable_HeatPush.cs b/Assembly-CSharp/RimWorld/Building_WorkTable_HeatPush.cs index e83f20cf4..e20615125 100644 --- a/Assembly-CSharp/RimWorld/Building_WorkTable_HeatPush.cs +++ b/Assembly-CSharp/RimWorld/Building_WorkTable_HeatPush.cs @@ -1,4 +1,3 @@ -using System; using Verse; namespace RimWorld @@ -12,7 +11,7 @@ public override void UsedThisTick() base.UsedThisTick(); if (Find.TickManager.TicksGame % 30 == 4) { - GenTemperature.PushHeat(this, this.def.building.heatPerTickWhileWorking * 30f); + GenTemperature.PushHeat(this, (float)(base.def.building.heatPerTickWhileWorking * 30.0)); } } } diff --git a/Assembly-CSharp/RimWorld/Bullet.cs b/Assembly-CSharp/RimWorld/Bullet.cs index fc02527d9..f689a8432 100644 --- a/Assembly-CSharp/RimWorld/Bullet.cs +++ b/Assembly-CSharp/RimWorld/Bullet.cs @@ -1,4 +1,3 @@ -using System; using UnityEngine; using Verse; using Verse.Sound; @@ -13,9 +12,12 @@ protected override void Impact(Thing hitThing) base.Impact(hitThing); if (hitThing != null) { - int damageAmountBase = this.def.projectile.damageAmountBase; - ThingDef equipmentDef = this.equipmentDef; - DamageInfo dinfo = new DamageInfo(this.def.projectile.damageDef, damageAmountBase, this.ExactRotation.eulerAngles.y, this.launcher, null, equipmentDef, DamageInfo.SourceCategory.ThingOrUnknown); + int damageAmountBase = base.def.projectile.damageAmountBase; + ThingDef equipmentDef = base.equipmentDef; + DamageDef damageDef = base.def.projectile.damageDef; + int amount = damageAmountBase; + Vector3 eulerAngles = this.ExactRotation.eulerAngles; + DamageInfo dinfo = new DamageInfo(damageDef, amount, eulerAngles.y, base.launcher, null, equipmentDef, DamageInfo.SourceCategory.ThingOrUnknown); hitThing.TakeDamage(dinfo); } else @@ -24,7 +26,7 @@ protected override void Impact(Thing hitThing) MoteMaker.MakeStaticMote(this.ExactPosition, map, ThingDefOf.Mote_ShotHit_Dirt, 1f); if (base.Position.GetTerrain(map).takeSplashes) { - MoteMaker.MakeWaterSplash(this.ExactPosition, map, Mathf.Sqrt((float)this.def.projectile.damageAmountBase) * 1f, 4f); + MoteMaker.MakeWaterSplash(this.ExactPosition, map, (float)(Mathf.Sqrt((float)base.def.projectile.damageAmountBase) * 1.0), 4f); } } } diff --git a/Assembly-CSharp/RimWorld/BuySellMode.cs b/Assembly-CSharp/RimWorld/BuySellMode.cs index 9158a18aa..9789f6199 100644 --- a/Assembly-CSharp/RimWorld/BuySellMode.cs +++ b/Assembly-CSharp/RimWorld/BuySellMode.cs @@ -1,10 +1,8 @@ -using System; - namespace RimWorld { public enum BuySellMode : byte { - Buying, - Selling + Buying = 0, + Selling = 1 } } diff --git a/Assembly-CSharp/RimWorld/CaravanUIUtility.cs b/Assembly-CSharp/RimWorld/CaravanUIUtility.cs index b7b9d9cc4..cdd8acbf1 100644 --- a/Assembly-CSharp/RimWorld/CaravanUIUtility.cs +++ b/Assembly-CSharp/RimWorld/CaravanUIUtility.cs @@ -15,57 +15,27 @@ public static class CaravanUIUtility public static void DrawDaysWorthOfFoodInfo(Rect rect, float daysWorthOfFood, float daysUntilRot, bool canEatLocalPlants, bool alignRight = false, float truncToWidth = 3.40282347E+38f) { GUI.color = Color.gray; - string text; - if (daysWorthOfFood >= 1000f) - { - text = "InfiniteDaysWorthOfFoodInfo".Translate(); - } - else if (daysUntilRot < 1000f) - { - text = "DaysWorthOfFoodInfoRot".Translate(new object[] - { - daysWorthOfFood.ToString("0.#"), - daysUntilRot.ToString("0.#") - }); - } - else - { - text = "DaysWorthOfFoodInfo".Translate(new object[] - { - daysWorthOfFood.ToString("0.#") - }); - } + string text = (!(daysWorthOfFood >= 1000.0)) ? ((!(daysUntilRot < 1000.0)) ? "DaysWorthOfFoodInfo".Translate(daysWorthOfFood.ToString("0.#")) : "DaysWorthOfFoodInfoRot".Translate(daysWorthOfFood.ToString("0.#"), daysUntilRot.ToString("0.#"))) : "InfiniteDaysWorthOfFoodInfo".Translate(); string text2 = text; - if (truncToWidth != 3.40282347E+38f) + if (truncToWidth != 3.4028234663852886E+38) { text2 = text.Truncate(truncToWidth, null); } Vector2 vector = Text.CalcSize(text2); - Rect rect2; - if (alignRight) - { - rect2 = new Rect(rect.xMax - vector.x, rect.y, vector.x, vector.y); - } - else - { - rect2 = new Rect(rect.x, rect.y, vector.x, vector.y); - } + Rect rect2 = (!alignRight) ? new Rect(rect.x, rect.y, vector.x, vector.y) : new Rect(rect.xMax - vector.x, rect.y, vector.x, vector.y); Widgets.Label(rect2, text2); - string text3 = string.Empty; - if (truncToWidth != 3.40282347E+38f && Text.CalcSize(text).x > truncToWidth) - { - text3 = text3 + text + "\n\n"; - } - text3 = text3 + "DaysWorthOfFoodTooltip".Translate() + "\n\n"; - if (canEatLocalPlants) - { - text3 += "DaysWorthOfFoodTooltip_CanEatLocalPlants".Translate(); - } - else + string str = string.Empty; + if (truncToWidth != 3.4028234663852886E+38) { - text3 += "DaysWorthOfFoodTooltip_CantEatLocalPlants".Translate(); + Vector2 vector2 = Text.CalcSize(text); + if (vector2.x > truncToWidth) + { + str = str + text + "\n\n"; + } } - TooltipHandler.TipRegion(rect2, text3); + str = str + "DaysWorthOfFoodTooltip".Translate() + "\n\n"; + str = ((!canEatLocalPlants) ? (str + "DaysWorthOfFoodTooltip_CantEatLocalPlants".Translate()) : (str + "DaysWorthOfFoodTooltip_CanEatLocalPlants".Translate())); + TooltipHandler.TipRegion(rect2, str); GUI.color = Color.white; } diff --git a/Assembly-CSharp/RimWorld/CharacterCardUtility.cs b/Assembly-CSharp/RimWorld/CharacterCardUtility.cs index 073a609a8..9a86a0dbb 100644 --- a/Assembly-CSharp/RimWorld/CharacterCardUtility.cs +++ b/Assembly-CSharp/RimWorld/CharacterCardUtility.cs @@ -1,7 +1,5 @@ using System; -using System.Collections; using System.Collections.Generic; -using System.Diagnostics; using System.Linq; using System.Text; using System.Text.RegularExpressions; @@ -35,7 +33,7 @@ public static void DrawCharacterCard(Rect rect, Pawn pawn) public static void DrawCharacterCard(Rect rect, Pawn pawn, Action randomizeCallback) { GUI.BeginGroup(rect); - bool flag = randomizeCallback != null; + bool flag = (object)randomizeCallback != null; Rect rect2 = new Rect(0f, 0f, 300f, 30f); NameTriple nameTriple = pawn.Name as NameTriple; if (flag && nameTriple != null) @@ -47,7 +45,7 @@ public static void DrawCharacterCard(Rect rect, Pawn pawn, Action randomizeCallb rect4.x += rect4.width; Rect rect5 = new Rect(rect2); rect5.width *= 0.333f; - rect5.x += rect4.width * 2f; + rect5.x += (float)(rect4.width * 2.0); string first = nameTriple.First; string nick = nameTriple.Nick; string last = nameTriple.Last; @@ -74,9 +72,9 @@ public static void DrawCharacterCard(Rect rect, Pawn pawn, Action randomizeCallb Widgets.Label(rect2, pawn.Name.ToStringFull); Text.Font = GameFont.Small; } - if (randomizeCallback != null) + if ((object)randomizeCallback != null) { - Rect rect6 = new Rect(rect2.xMax + 6f, 0f, 100f, rect2.height); + Rect rect6 = new Rect((float)(rect2.xMax + 6.0), 0f, 100f, rect2.height); if (Widgets.ButtonText(rect6, "Randomize".Translate(), true, false, true)) { SoundDefOf.TickTiny.PlayOneShotOnCamera(null); @@ -86,7 +84,7 @@ public static void DrawCharacterCard(Rect rect, Pawn pawn, Action randomizeCallb } if (!flag && pawn.IsColonist && !pawn.health.Dead) { - Rect rect7 = new Rect(CharacterCardUtility.PawnCardSize.x - 85f, 0f, 30f, 30f); + Rect rect7 = new Rect((float)(CharacterCardUtility.PawnCardSize.x - 85.0), 0f, 30f, 30f); TooltipHandler.TipRegion(rect7, new TipSignal("RenameColonist".Translate())); if (Widgets.ButtonImage(rect7, TexButton.Rename)) { @@ -95,51 +93,47 @@ public static void DrawCharacterCard(Rect rect, Pawn pawn, Action randomizeCallb } if (flag) { - Widgets.InfoCardButton(CharacterCardUtility.PawnCardSize.x - 115f, 0f, pawn); + Widgets.InfoCardButton((float)(CharacterCardUtility.PawnCardSize.x - 115.0), 0f, pawn); } string label = pawn.MainDesc(true); Rect rect8 = new Rect(0f, 45f, rect.width, 60f); Widgets.Label(rect8, label); - TooltipHandler.TipRegion(rect8, () => pawn.ageTracker.AgeTooltipString, 6873641); + TooltipHandler.TipRegion(rect8, (Func)(() => pawn.ageTracker.AgeTooltipString), 6873641); Rect position = new Rect(0f, 100f, 250f, 450f); Rect position2 = new Rect(position.xMax, 100f, 258f, 450f); GUI.BeginGroup(position); float num = 0f; Text.Font = GameFont.Medium; Widgets.Label(new Rect(0f, 0f, 200f, 30f), "Backstory".Translate()); - num += 30f; + num = (float)(num + 30.0); Text.Font = GameFont.Small; - using (IEnumerator enumerator = Enum.GetValues(typeof(BackstorySlot)).GetEnumerator()) + foreach (byte value in Enum.GetValues(typeof(BackstorySlot))) { - while (enumerator.MoveNext()) + Backstory backstory = pawn.story.GetBackstory((BackstorySlot)value); + if (backstory != null) { - BackstorySlot backstorySlot = (BackstorySlot)((byte)enumerator.Current); - Backstory backstory = pawn.story.GetBackstory(backstorySlot); - if (backstory != null) + Rect rect9 = new Rect(0f, num, position.width, 24f); + if (Mouse.IsOver(rect9)) { - Rect rect9 = new Rect(0f, num, position.width, 24f); - if (Mouse.IsOver(rect9)) - { - Widgets.DrawHighlight(rect9); - } - TooltipHandler.TipRegion(rect9, backstory.FullDescriptionFor(pawn)); - Text.Anchor = TextAnchor.MiddleLeft; - string str = (backstorySlot != BackstorySlot.Adulthood) ? "Childhood".Translate() : "Adulthood".Translate(); - Widgets.Label(rect9, str + ":"); - Text.Anchor = TextAnchor.UpperLeft; - Rect rect10 = new Rect(rect9); - rect10.x += 90f; - rect10.width -= 90f; - string title = backstory.Title; - Widgets.Label(rect10, title); - num += rect9.height + 2f; + Widgets.DrawHighlight(rect9); } + TooltipHandler.TipRegion(rect9, backstory.FullDescriptionFor(pawn)); + Text.Anchor = TextAnchor.MiddleLeft; + string str = (value != 1) ? "Childhood".Translate() : "Adulthood".Translate(); + Widgets.Label(rect9, str + ":"); + Text.Anchor = TextAnchor.UpperLeft; + Rect rect10 = new Rect(rect9); + rect10.x += 90f; + rect10.width -= 90f; + string title = backstory.Title; + Widgets.Label(rect10, title); + num = (float)(num + (rect9.height + 2.0)); } } - num += 25f; + num = (float)(num + 25.0); Text.Font = GameFont.Medium; Widgets.Label(new Rect(0f, num, 200f, 30f), "IncapableOf".Translate()); - num += 30f; + num = (float)(num + 30.0); Text.Font = GameFont.Small; StringBuilder stringBuilder = new StringBuilder(); WorkTags combinedDisabledWorkTags = pawn.story.CombinedDisabledWorkTags; @@ -149,30 +143,39 @@ public static void DrawCharacterCard(Rect rect, Pawn pawn, Action randomizeCallb } else { - List list = CharacterCardUtility.WorkTagsFrom(combinedDisabledWorkTags).ToList(); + List list = CharacterCardUtility.WorkTagsFrom(combinedDisabledWorkTags).ToList(); bool flag2 = true; - foreach (WorkTags current in list) + List.Enumerator enumerator2 = list.GetEnumerator(); + try { - if (!flag2) + while (enumerator2.MoveNext()) { - stringBuilder.Append(current.LabelTranslated().ToLower()); - } - else - { - stringBuilder.Append(current.LabelTranslated()); + WorkTags current = enumerator2.Current; + if (!flag2) + { + stringBuilder.Append(current.LabelTranslated().ToLower()); + } + else + { + stringBuilder.Append(current.LabelTranslated()); + } + stringBuilder.Append(", "); + flag2 = false; } - stringBuilder.Append(", "); - flag2 = false; + } + finally + { + ((IDisposable)(object)enumerator2).Dispose(); } } string text = stringBuilder.ToString(); text = text.Substring(0, text.Length - 2); Rect rect11 = new Rect(0f, num, position.width, 999f); Widgets.Label(rect11, text); - num += 100f; + num = (float)(num + 100.0); Text.Font = GameFont.Medium; Widgets.Label(new Rect(0f, num, 200f, 30f), "Traits".Translate()); - num += 30f; + num = (float)(num + 30.0); Text.Font = GameFont.Small; for (int i = 0; i < pawn.story.traits.allTraits.Count; i++) { @@ -183,24 +186,16 @@ public static void DrawCharacterCard(Rect rect, Pawn pawn, Action randomizeCallb Widgets.DrawHighlight(rect12); } Widgets.Label(rect12, trait.LabelCap); - num += rect12.height + 2f; + num = (float)(num + (rect12.height + 2.0)); Trait trLocal = trait; - TipSignal tip = new TipSignal(() => trLocal.TipString(pawn), (int)num * 37); + TipSignal tip = new TipSignal((Func)(() => trLocal.TipString(pawn)), (int)num * 37); TooltipHandler.TipRegion(rect12, tip); } GUI.EndGroup(); GUI.BeginGroup(position2); Text.Font = GameFont.Medium; Widgets.Label(new Rect(0f, 0f, 200f, 30f), "Skills".Translate()); - SkillUI.SkillDrawMode mode; - if (Current.ProgramState == ProgramState.Playing) - { - mode = SkillUI.SkillDrawMode.Gameplay; - } - else - { - mode = SkillUI.SkillDrawMode.Menu; - } + SkillUI.SkillDrawMode mode = (SkillUI.SkillDrawMode)((Current.ProgramState != ProgramState.Playing) ? 1 : 0); SkillUI.DrawSkillsOf(pawn, new Vector2(0f, 35f), mode); GUI.EndGroup(); GUI.EndGroup(); @@ -215,15 +210,15 @@ public static void DoNameInputRect(Rect rect, ref string name, int maxLength) } } - [DebuggerHidden] private static IEnumerable WorkTagsFrom(WorkTags tags) { - CharacterCardUtility.c__Iterator196 c__Iterator = new CharacterCardUtility.c__Iterator196(); - c__Iterator.tags = tags; - c__Iterator.<$>tags = tags; - CharacterCardUtility.c__Iterator196 expr_15 = c__Iterator; - expr_15.$PC = -2; - return expr_15; + foreach (WorkTags allSelectedItem in ((Enum)(object)tags).GetAllSelectedItems()) + { + if (allSelectedItem != 0) + { + yield return allSelectedItem; + } + } } } } diff --git a/Assembly-CSharp/RimWorld/ChemicalDef.cs b/Assembly-CSharp/RimWorld/ChemicalDef.cs index 09af63569..14a6c5318 100644 --- a/Assembly-CSharp/RimWorld/ChemicalDef.cs +++ b/Assembly-CSharp/RimWorld/ChemicalDef.cs @@ -1,4 +1,3 @@ -using System; using System.Collections.Generic; using Verse; diff --git a/Assembly-CSharp/RimWorld/ChemicalDefOf.cs b/Assembly-CSharp/RimWorld/ChemicalDefOf.cs index 1477bf2a5..67f2e82ef 100644 --- a/Assembly-CSharp/RimWorld/ChemicalDefOf.cs +++ b/Assembly-CSharp/RimWorld/ChemicalDefOf.cs @@ -1,5 +1,3 @@ -using System; - namespace RimWorld { [DefOf] diff --git a/Assembly-CSharp/RimWorld/ChildRelationUtility.cs b/Assembly-CSharp/RimWorld/ChildRelationUtility.cs index bfcac023f..dfc3194c2 100644 --- a/Assembly-CSharp/RimWorld/ChildRelationUtility.cs +++ b/Assembly-CSharp/RimWorld/ChildRelationUtility.cs @@ -1,4 +1,3 @@ -using System; using UnityEngine; using Verse; @@ -50,7 +49,7 @@ public static float ChanceOfBecomingChildOf(Pawn child, Pawn father, Pawn mother bool fatherIsNew = father != null && child.GetFather() != father; bool motherIsNew = mother != null && child.GetMother() != mother; float skinColorFactor = ChildRelationUtility.GetSkinColorFactor(melanin, melanin2, melanin3, fatherIsNew, motherIsNew); - if (skinColorFactor <= 0f) + if (skinColorFactor <= 0.0) { return 0f; } @@ -61,7 +60,7 @@ public static float ChanceOfBecomingChildOf(Pawn child, Pawn father, Pawn mother if (father != null && child.GetFather() == null) { num = ChildRelationUtility.GetParentAgeFactor(father, child, 14f, 30f, 50f); - if (num == 0f) + if (num == 0.0) { return 0f; } @@ -73,7 +72,7 @@ public static float ChanceOfBecomingChildOf(Pawn child, Pawn father, Pawn mother if (mother != null && child.GetMother() == null) { num2 = ChildRelationUtility.GetParentAgeFactor(mother, child, 16f, 27f, 45f); - if (num2 == 0f) + if (num2 == 0.0) { return 0f; } @@ -82,7 +81,7 @@ public static float ChanceOfBecomingChildOf(Pawn child, Pawn father, Pawn mother { return 0f; } - num3 = 1f - (float)mother.relations.ChildrenCount / (float)num5; + num3 = (float)(1.0 - (float)mother.relations.ChildrenCount / (float)num5); if (mother.story.traits.HasTrait(TraitDefOf.Gay)) { num4 = 0.1f; @@ -94,7 +93,7 @@ public static float ChanceOfBecomingChildOf(Pawn child, Pawn father, Pawn mother Pawn firstDirectRelationPawn = mother.relations.GetFirstDirectRelationPawn(PawnRelationDefOf.Spouse, null); if (firstDirectRelationPawn != null && firstDirectRelationPawn != father) { - num6 *= 0.15f; + num6 = (float)(num6 * 0.15000000596046448); } } if (father != null) @@ -102,7 +101,7 @@ public static float ChanceOfBecomingChildOf(Pawn child, Pawn father, Pawn mother Pawn firstDirectRelationPawn2 = father.relations.GetFirstDirectRelationPawn(PawnRelationDefOf.Spouse, null); if (firstDirectRelationPawn2 != null && firstDirectRelationPawn2 != mother) { - num6 *= 0.15f; + num6 = (float)(num6 * 0.15000000596046448); } } return skinColorFactor * num * num2 * num3 * num6 * num4; @@ -112,22 +111,15 @@ private static float GetParentAgeFactor(Pawn parent, Pawn child, float minAgeToH { float num = PawnRelationUtility.MaxPossibleBioAgeAt(parent.ageTracker.AgeBiologicalYearsFloat, parent.ageTracker.AgeChronologicalYearsFloat, child.ageTracker.AgeChronologicalYearsFloat); float num2 = PawnRelationUtility.MinPossibleBioAgeAt(parent.ageTracker.AgeBiologicalYearsFloat, child.ageTracker.AgeChronologicalYearsFloat); - if (num <= 0f) + if (num <= 0.0) { return 0f; } if (num2 > num) { - if (num2 > num + 0.1f) + if (num2 > num + 0.10000000149011612) { - Log.Warning(string.Concat(new object[] - { - "Min possible bio age (", - num2, - ") is greater than max possible bio age (", - num, - ")." - })); + Log.Warning("Min possible bio age (" + num2 + ") is greater than max possible bio age (" + num + ")."); } return 0f; } @@ -142,7 +134,7 @@ private static float GetParentAgeFactor(Pawn parent, Pawn child, float minAgeToH public static bool ChildWantsNameOfAnyParent(Pawn child) { - return Rand.ValueSeeded(child.thingIDNumber ^ 88271612) < 0.99f; + return Rand.ValueSeeded(child.thingIDNumber ^ 88271612) < 0.99000000953674316; } private static int NumberOfChildrenFemaleWantsEver(Pawn female) @@ -164,7 +156,7 @@ private static int NumberOfChildrenFemaleWantsEver(Pawn female) { return new float?(pawn.story.melanin); } - return null; + return default(float?); } private static float GetAgeFactor(float ageAtBirth, float min, float max, float mid) @@ -178,11 +170,11 @@ private static float GetSkinColorFactor(float? childMelanin, float? fatherMelani { float num = Mathf.Min(fatherMelanin.Value, motherMelanin.Value); float num2 = Mathf.Max(fatherMelanin.Value, motherMelanin.Value); - if (childMelanin.HasValue && childMelanin.Value < num - 0.05f) + if (childMelanin.HasValue && childMelanin.Value < num - 0.05000000074505806) { return 0f; } - if (childMelanin.HasValue && childMelanin.Value > num2 + 0.05f) + if (childMelanin.HasValue && childMelanin.Value > num2 + 0.05000000074505806) { return 0f; } @@ -211,18 +203,15 @@ private static float GetNewParentSkinColorFactor(float? newParentMelanin, float? } return PawnSkinColors.GetMelaninCommonalityFactor(newParentMelanin.Value); } - else + if (childMelanin.HasValue) { - if (childMelanin.HasValue) - { - float reflectedSkin = ChildRelationUtility.GetReflectedSkin(otherParentMelanin.Value, childMelanin.Value); - return ChildRelationUtility.GetMelaninSimilarityFactor(newParentMelanin.Value, reflectedSkin); - } - float melanin = (newParentMelanin.Value + otherParentMelanin.Value) / 2f; - return PawnSkinColors.GetMelaninCommonalityFactor(melanin); + float reflectedSkin = ChildRelationUtility.GetReflectedSkin(otherParentMelanin.Value, childMelanin.Value); + return ChildRelationUtility.GetMelaninSimilarityFactor(newParentMelanin.Value, reflectedSkin); } + float melanin = (float)((newParentMelanin.Value + otherParentMelanin.Value) / 2.0); + return PawnSkinColors.GetMelaninCommonalityFactor(melanin); } - else if (!otherParentMelanin.HasValue) + if (!otherParentMelanin.HasValue) { if (childMelanin.HasValue) { @@ -230,15 +219,12 @@ private static float GetNewParentSkinColorFactor(float? newParentMelanin, float? } return 1f; } - else + if (childMelanin.HasValue) { - if (childMelanin.HasValue) - { - float reflectedSkin2 = ChildRelationUtility.GetReflectedSkin(otherParentMelanin.Value, childMelanin.Value); - return PawnSkinColors.GetMelaninCommonalityFactor(reflectedSkin2); - } - return PawnSkinColors.GetMelaninCommonalityFactor(otherParentMelanin.Value); + float reflectedSkin2 = ChildRelationUtility.GetReflectedSkin(otherParentMelanin.Value, childMelanin.Value); + return PawnSkinColors.GetMelaninCommonalityFactor(reflectedSkin2); } + return PawnSkinColors.GetMelaninCommonalityFactor(otherParentMelanin.Value); } public static float GetReflectedSkin(float value, float mirror) @@ -248,8 +234,8 @@ public static float GetReflectedSkin(float value, float mirror) public static float GetMelaninSimilarityFactor(float melanin1, float melanin2) { - float min = Mathf.Clamp01(melanin1 - 0.15f); - float max = Mathf.Clamp01(melanin1 + 0.15f); + float min = Mathf.Clamp01((float)(melanin1 - 0.15000000596046448)); + float max = Mathf.Clamp01((float)(melanin1 + 0.15000000596046448)); return GenMath.GetFactorInInterval(min, melanin1, max, 2.5f, melanin2); } @@ -257,7 +243,7 @@ public static float GetRandomChildSkinColor(float fatherMelanin, float motherMel { float clampMin = Mathf.Min(fatherMelanin, motherMelanin); float clampMax = Mathf.Max(fatherMelanin, motherMelanin); - float value = (fatherMelanin + motherMelanin) / 2f; + float value = (float)((fatherMelanin + motherMelanin) / 2.0); return PawnSkinColors.GetRandomMelaninSimilarTo(value, clampMin, clampMax); } @@ -269,7 +255,19 @@ public static bool DefinitelyHasNotBirthName(Pawn pawn) return false; } string last = ((NameTriple)spouse.Name).Last; - return !(((NameTriple)pawn.Name).Last != last) && ((spouse.GetMother() != null && ((NameTriple)spouse.GetMother().Name).Last == last) || (spouse.GetFather() != null && ((NameTriple)spouse.GetFather().Name).Last == last)); + if (((NameTriple)pawn.Name).Last != last) + { + return false; + } + if (spouse.GetMother() != null && ((NameTriple)spouse.GetMother().Name).Last == last) + { + goto IL_0093; + } + if (spouse.GetFather() != null && ((NameTriple)spouse.GetFather().Name).Last == last) + goto IL_0093; + return false; + IL_0093: + return true; } } } diff --git a/Assembly-CSharp/RimWorld/ChoiceLetter_ItemStashFeeDemand.cs b/Assembly-CSharp/RimWorld/ChoiceLetter_ItemStashFeeDemand.cs index a7943a22a..b845a5332 100644 --- a/Assembly-CSharp/RimWorld/ChoiceLetter_ItemStashFeeDemand.cs +++ b/Assembly-CSharp/RimWorld/ChoiceLetter_ItemStashFeeDemand.cs @@ -1,3 +1,4 @@ +using RimWorld.Planet; using System; using System.Collections.Generic; using Verse; @@ -26,11 +27,32 @@ protected override IEnumerable Choices { get { - ChoiceLetter_ItemStashFeeDemand.<>c__Iterator19E <>c__Iterator19E = new ChoiceLetter_ItemStashFeeDemand.<>c__Iterator19E(); - <>c__Iterator19E.<>f__this = this; - ChoiceLetter_ItemStashFeeDemand.<>c__Iterator19E expr_0E = <>c__Iterator19E; - expr_0E.$PC = -2; - return expr_0E; + DiaOption accept = new DiaOption("ItemStashQuest_Accept".Translate()) + { + action = (Action)delegate + { + int tile = default(int); + if (!TileFinder.TryFindNewSiteTile(out tile)) + { + Find.LetterStack.RemoveLetter(((_003C_003Ec__Iterator19E)/*Error near IL_0044: stateMachine*/)._003C_003Ef__this); + } + else + { + Site o = IncidentWorker_QuestItemStash.CreateSite(tile, ((_003C_003Ec__Iterator19E)/*Error near IL_0044: stateMachine*/)._003C_003Ef__this.sitePart, ((_003C_003Ec__Iterator19E)/*Error near IL_0044: stateMachine*/)._003C_003Ef__this.siteDaysTimeout, ((_003C_003Ec__Iterator19E)/*Error near IL_0044: stateMachine*/)._003C_003Ef__this.siteFaction, ((_003C_003Ec__Iterator19E)/*Error near IL_0044: stateMachine*/)._003C_003Ef__this.items, ((_003C_003Ec__Iterator19E)/*Error near IL_0044: stateMachine*/)._003C_003Ef__this.sitePartsKnown); + CameraJumper.TryJumpAndSelect((WorldObject)o); + TradeUtility.LaunchSilver(((_003C_003Ec__Iterator19E)/*Error near IL_0044: stateMachine*/)._003C_003Ef__this.map, ((_003C_003Ec__Iterator19E)/*Error near IL_0044: stateMachine*/)._003C_003Ef__this.fee); + Find.LetterStack.RemoveLetter(((_003C_003Ec__Iterator19E)/*Error near IL_0044: stateMachine*/)._003C_003Ef__this); + } + }, + resolveTree = true + }; + if (this.map == null || !TradeUtility.ColonyHasEnoughSilver(this.map, this.fee)) + { + accept.Disable("NeedSilverLaunchable".Translate(this.fee)); + } + yield return accept; + yield return base.Reject; + yield return base.Postpone; } } @@ -38,7 +60,19 @@ public override bool StillValid { get { - return base.StillValid && !this.alliedFaction.HostileTo(Faction.OfPlayer) && (this.map == null || Find.Maps.Contains(this.map)); + if (!base.StillValid) + { + return false; + } + if (this.alliedFaction.HostileTo(Faction.OfPlayer)) + { + return false; + } + if (this.map != null && !Find.Maps.Contains(this.map)) + { + return false; + } + return true; } } @@ -53,7 +87,7 @@ public override void ExposeData() Scribe_References.Look(ref this.map, "map", false); Scribe_Values.Look(ref this.fee, "fee", 0, false); Scribe_Values.Look(ref this.siteDaysTimeout, "siteDaysTimeout", 0, false); - Scribe_Deep.Look(ref this.items, "items", new object[] + Scribe_Deep.Look(ref this.items, "items", new object[1] { this }); @@ -83,5 +117,11 @@ virtual IThingHolder get_ParentHolder() { return base.ParentHolder; } + + IThingHolder IThingHolder.get_ParentHolder() + { + //ILSpy generated this explicit interface implementation from .override directive in get_ParentHolder + return this.get_ParentHolder(); + } } } diff --git a/Assembly-CSharp/RimWorld/ChoiceLetter_RansomDemand.cs b/Assembly-CSharp/RimWorld/ChoiceLetter_RansomDemand.cs index 77ce43346..66ded1196 100644 --- a/Assembly-CSharp/RimWorld/ChoiceLetter_RansomDemand.cs +++ b/Assembly-CSharp/RimWorld/ChoiceLetter_RansomDemand.cs @@ -18,11 +18,40 @@ protected override IEnumerable Choices { get { - ChoiceLetter_RansomDemand.<>c__Iterator19F <>c__Iterator19F = new ChoiceLetter_RansomDemand.<>c__Iterator19F(); - <>c__Iterator19F.<>f__this = this; - ChoiceLetter_RansomDemand.<>c__Iterator19F expr_0E = <>c__Iterator19F; - expr_0E.$PC = -2; - return expr_0E; + DiaOption accept = new DiaOption("RansomDemand_Accept".Translate()) + { + action = (Action)delegate() + { + ((_003C_003Ec__Iterator19F)/*Error near IL_0044: stateMachine*/)._003C_003Ef__this.faction.kidnapped.RemoveKidnappedPawn(((_003C_003Ec__Iterator19F)/*Error near IL_0044: stateMachine*/)._003C_003Ef__this.kidnapped); + Find.WorldPawns.RemovePawn(((_003C_003Ec__Iterator19F)/*Error near IL_0044: stateMachine*/)._003C_003Ef__this.kidnapped); + IntVec3 intVec = default(IntVec3); + if ((int)((_003C_003Ec__Iterator19F)/*Error near IL_0044: stateMachine*/)._003C_003Ef__this.faction.def.techLevel < 5) + { + if (!CellFinder.TryFindRandomEdgeCellWith((Predicate)((IntVec3 c) => c.Standable(((_003C_003Ec__Iterator19F)/*Error near IL_0044: stateMachine*/)._003C_003Ef__this.map) && ((_003C_003Ec__Iterator19F)/*Error near IL_0044: stateMachine*/)._003C_003Ef__this.map.reachability.CanReachColony(c)), ((_003C_003Ec__Iterator19F)/*Error near IL_0044: stateMachine*/)._003C_003Ef__this.map, CellFinder.EdgeRoadChance_Friendly, out intVec) && !CellFinder.TryFindRandomEdgeCellWith((Predicate)((IntVec3 c) => c.Standable(((_003C_003Ec__Iterator19F)/*Error near IL_0044: stateMachine*/)._003C_003Ef__this.map)), ((_003C_003Ec__Iterator19F)/*Error near IL_0044: stateMachine*/)._003C_003Ef__this.map, CellFinder.EdgeRoadChance_Friendly, out intVec)) + { + Log.Warning("Could not find any edge cell."); + intVec = DropCellFinder.TradeDropSpot(((_003C_003Ec__Iterator19F)/*Error near IL_0044: stateMachine*/)._003C_003Ef__this.map); + } + GenSpawn.Spawn(((_003C_003Ec__Iterator19F)/*Error near IL_0044: stateMachine*/)._003C_003Ef__this.kidnapped, intVec, ((_003C_003Ec__Iterator19F)/*Error near IL_0044: stateMachine*/)._003C_003Ef__this.map); + } + else + { + intVec = DropCellFinder.TradeDropSpot(((_003C_003Ec__Iterator19F)/*Error near IL_0044: stateMachine*/)._003C_003Ef__this.map); + TradeUtility.SpawnDropPod(intVec, ((_003C_003Ec__Iterator19F)/*Error near IL_0044: stateMachine*/)._003C_003Ef__this.map, ((_003C_003Ec__Iterator19F)/*Error near IL_0044: stateMachine*/)._003C_003Ef__this.kidnapped); + } + CameraJumper.TryJump(intVec, ((_003C_003Ec__Iterator19F)/*Error near IL_0044: stateMachine*/)._003C_003Ef__this.map); + TradeUtility.LaunchSilver(((_003C_003Ec__Iterator19F)/*Error near IL_0044: stateMachine*/)._003C_003Ef__this.map, ((_003C_003Ec__Iterator19F)/*Error near IL_0044: stateMachine*/)._003C_003Ef__this.fee); + Find.LetterStack.RemoveLetter(((_003C_003Ec__Iterator19F)/*Error near IL_0044: stateMachine*/)._003C_003Ef__this); + }, + resolveTree = true + }; + if (!TradeUtility.ColonyHasEnoughSilver(this.map, this.fee)) + { + accept.Disable("NeedSilverLaunchable".Translate(this.fee.ToString())); + } + yield return accept; + yield return base.Reject; + yield return base.Postpone; } } @@ -30,7 +59,15 @@ public override bool StillValid { get { - return base.StillValid && Find.Maps.Contains(this.map) && this.faction.kidnapped.KidnappedPawnsListForReading.Contains(this.kidnapped); + if (!base.StillValid) + { + return false; + } + if (!Find.Maps.Contains(this.map)) + { + return false; + } + return this.faction.kidnapped.KidnappedPawnsListForReading.Contains(this.kidnapped); } } diff --git a/Assembly-CSharp/RimWorld/CollectionsMassCalculator.cs b/Assembly-CSharp/RimWorld/CollectionsMassCalculator.cs index e04deede3..63bb71a7a 100644 --- a/Assembly-CSharp/RimWorld/CollectionsMassCalculator.cs +++ b/Assembly-CSharp/RimWorld/CollectionsMassCalculator.cs @@ -40,14 +40,7 @@ public static float MassUsage(List stackParts, IgnorePawnsInvent Pawn pawn = thing as Pawn; if (pawn != null) { - if (includePawnsMass) - { - num += pawn.GetStatValue(StatDefOf.Mass, true) * (float)count; - } - else - { - num += MassUtility.GearAndInventoryMass(pawn) * (float)count; - } + num = ((!includePawnsMass) ? (num + MassUtility.GearAndInventoryMass(pawn) * (float)count) : (num + pawn.GetStatValue(StatDefOf.Mass, true) * (float)count)); if (InventoryCalculatorsUtility.ShouldIgnoreInventoryOf(pawn, ignoreInventory)) { num -= MassUtility.InventoryMass(pawn) * (float)count; @@ -76,15 +69,12 @@ public static float CapacityTransferables(List transferables CollectionsMassCalculator.tmpThingStackParts.Clear(); for (int i = 0; i < transferables.Count; i++) { - if (transferables[i].HasAnyThing) + if (transferables[i].HasAnyThing && transferables[i].AnyThing is Pawn) { - if (transferables[i].AnyThing is Pawn) + TransferableUtility.TransferNoSplit(transferables[i].things, transferables[i].CountToTransfer, (Action)delegate(Thing originalThing, int toTake) { - TransferableUtility.TransferNoSplit(transferables[i].things, transferables[i].CountToTransfer, delegate(Thing originalThing, int toTake) - { - CollectionsMassCalculator.tmpThingStackParts.Add(new ThingStackPart(originalThing, toTake)); - }, false, false); - } + CollectionsMassCalculator.tmpThingStackParts.Add(new ThingStackPart(originalThing, toTake)); + }, false, false); } } float result = CollectionsMassCalculator.Capacity(CollectionsMassCalculator.tmpThingStackParts); @@ -97,18 +87,15 @@ public static float CapacityLeftAfterTransfer(List transfera CollectionsMassCalculator.tmpThingStackParts.Clear(); for (int i = 0; i < transferables.Count; i++) { - if (transferables[i].HasAnyThing) + if (transferables[i].HasAnyThing && transferables[i].AnyThing is Pawn) { - if (transferables[i].AnyThing is Pawn) + CollectionsMassCalculator.thingsInReverse.Clear(); + CollectionsMassCalculator.thingsInReverse.AddRange(transferables[i].things); + CollectionsMassCalculator.thingsInReverse.Reverse(); + TransferableUtility.TransferNoSplit(CollectionsMassCalculator.thingsInReverse, transferables[i].MaxCount - transferables[i].CountToTransfer, (Action)delegate(Thing originalThing, int toTake) { - CollectionsMassCalculator.thingsInReverse.Clear(); - CollectionsMassCalculator.thingsInReverse.AddRange(transferables[i].things); - CollectionsMassCalculator.thingsInReverse.Reverse(); - TransferableUtility.TransferNoSplit(CollectionsMassCalculator.thingsInReverse, transferables[i].MaxCount - transferables[i].CountToTransfer, delegate(Thing originalThing, int toTake) - { - CollectionsMassCalculator.tmpThingStackParts.Add(new ThingStackPart(originalThing, toTake)); - }, false, false); - } + CollectionsMassCalculator.tmpThingStackParts.Add(new ThingStackPart(originalThing, toTake)); + }, false, false); } } CollectionsMassCalculator.thingsInReverse.Clear(); @@ -130,7 +117,7 @@ public static float Capacity(List things) where T : Thing CollectionsMassCalculator.tmpThingStackParts.Clear(); for (int i = 0; i < things.Count; i++) { - CollectionsMassCalculator.tmpThingStackParts.Add(new ThingStackPart(things[i], things[i].stackCount)); + CollectionsMassCalculator.tmpThingStackParts.Add(new ThingStackPart((Thing)(object)things[i], ((Thing)(object)things[i]).stackCount)); } float result = CollectionsMassCalculator.Capacity(CollectionsMassCalculator.tmpThingStackParts); CollectionsMassCalculator.tmpThingStackParts.Clear(); @@ -142,7 +129,7 @@ public static float MassUsageTransferables(List transferable CollectionsMassCalculator.tmpThingStackParts.Clear(); for (int i = 0; i < transferables.Count; i++) { - TransferableUtility.TransferNoSplit(transferables[i].things, transferables[i].CountToTransfer, delegate(Thing originalThing, int toTake) + TransferableUtility.TransferNoSplit(transferables[i].things, transferables[i].CountToTransfer, (Action)delegate(Thing originalThing, int toTake) { CollectionsMassCalculator.tmpThingStackParts.Add(new ThingStackPart(originalThing, toTake)); }, false, false); @@ -160,7 +147,7 @@ public static float MassUsageLeftAfterTransfer(List transfer CollectionsMassCalculator.thingsInReverse.Clear(); CollectionsMassCalculator.thingsInReverse.AddRange(transferables[i].things); CollectionsMassCalculator.thingsInReverse.Reverse(); - TransferableUtility.TransferNoSplit(CollectionsMassCalculator.thingsInReverse, transferables[i].MaxCount - transferables[i].CountToTransfer, delegate(Thing originalThing, int toTake) + TransferableUtility.TransferNoSplit(CollectionsMassCalculator.thingsInReverse, transferables[i].MaxCount - transferables[i].CountToTransfer, (Action)delegate(Thing originalThing, int toTake) { CollectionsMassCalculator.tmpThingStackParts.Add(new ThingStackPart(originalThing, toTake)); }, false, false); @@ -175,7 +162,7 @@ public static float MassUsage(List things, IgnorePawnsInventoryMode ignore CollectionsMassCalculator.tmpThingStackParts.Clear(); for (int i = 0; i < things.Count; i++) { - CollectionsMassCalculator.tmpThingStackParts.Add(new ThingStackPart(things[i], things[i].stackCount)); + CollectionsMassCalculator.tmpThingStackParts.Add(new ThingStackPart((Thing)(object)things[i], ((Thing)(object)things[i]).stackCount)); } float result = CollectionsMassCalculator.MassUsage(CollectionsMassCalculator.tmpThingStackParts, ignoreInventory, includePawnsMass, ignoreCorpsesGearAndInventory); CollectionsMassCalculator.tmpThingStackParts.Clear(); diff --git a/Assembly-CSharp/RimWorld/ColonistBar.cs b/Assembly-CSharp/RimWorld/ColonistBar.cs index 3850bb3f0..6ff3c6577 100644 --- a/Assembly-CSharp/RimWorld/ColonistBar.cs +++ b/Assembly-CSharp/RimWorld/ColonistBar.cs @@ -41,7 +41,7 @@ public Entry(Pawn pawn, Map map, int group) private ColonistBarDrawLocsFinder drawLocsFinder = new ColonistBarDrawLocsFinder(); - private List cachedEntries = new List(); + private List cachedEntries = new List(); private List cachedDrawLocs = new List(); @@ -69,7 +69,7 @@ public Entry(Pawn pawn, Map map, int group) private static List tmpCaravanPawns = new List(); - public List Entries + public List Entries { get { @@ -82,11 +82,13 @@ private bool ShowGroupFrames { get { - List entries = this.Entries; + List entries = this.Entries; int num = -1; for (int i = 0; i < entries.Count; i++) { - num = Mathf.Max(num, entries[i].group); + int a = num; + Entry entry = entries[i]; + num = Mathf.Max(a, entry.group); } return num >= 1; } @@ -120,7 +122,7 @@ public float SpaceBetweenColonistsHorizontal { get { - return 24f * this.Scale; + return (float)(24.0 * this.Scale); } } @@ -128,7 +130,11 @@ private bool Visible { get { - return UI.screenWidth >= 800 && UI.screenHeight >= 500; + if (UI.screenWidth >= 800 && UI.screenHeight >= 500) + { + return true; + } + return false; } } @@ -139,19 +145,22 @@ public void MarkColonistsDirty() public void ColonistBarOnGUI() { - if (!this.Visible) - { - return; - } - if (Event.current.type != EventType.Layout) + if (this.Visible && Event.current.type != EventType.Layout) { - List entries = this.Entries; + List entries = this.Entries; int num = -1; bool showGroupFrames = this.ShowGroupFrames; for (int i = 0; i < this.cachedDrawLocs.Count; i++) { - Rect rect = new Rect(this.cachedDrawLocs[i].x, this.cachedDrawLocs[i].y, this.Size.x, this.Size.y); - ColonistBar.Entry entry = entries[i]; + Vector2 vector = this.cachedDrawLocs[i]; + float x = vector.x; + Vector2 vector2 = this.cachedDrawLocs[i]; + float y = vector2.y; + Vector2 size = this.Size; + float x2 = size.x; + Vector2 size2 = this.Size; + Rect rect = new Rect(x, y, x2, size2.y); + Entry entry = entries[i]; bool flag = num != entry.group; num = entry.group; if (entry.pawn != null) @@ -175,7 +184,7 @@ public void ColonistBarOnGUI() { for (int j = 0; j < this.cachedDrawLocs.Count; j++) { - ColonistBar.Entry entry2 = entries[j]; + Entry entry2 = entries[j]; bool flag2 = num != entry2.group; num = entry2.group; if (flag2) @@ -189,88 +198,84 @@ public void ColonistBarOnGUI() private void CheckRecacheEntries() { - if (!this.entriesDirty) + if (this.entriesDirty) { - return; - } - this.entriesDirty = false; - this.cachedEntries.Clear(); - if (Find.PlaySettings.showColonistBar) - { - ColonistBar.tmpMaps.Clear(); - ColonistBar.tmpMaps.AddRange(Find.Maps); - ColonistBar.tmpMaps.SortBy((Map x) => !x.IsPlayerHome, (Map x) => x.uniqueID); - int num = 0; - for (int i = 0; i < ColonistBar.tmpMaps.Count; i++) + this.entriesDirty = false; + this.cachedEntries.Clear(); + if (Find.PlaySettings.showColonistBar) { - ColonistBar.tmpPawns.Clear(); - ColonistBar.tmpPawns.AddRange(ColonistBar.tmpMaps[i].mapPawns.FreeColonists); - List list = ColonistBar.tmpMaps[i].listerThings.ThingsInGroup(ThingRequestGroup.Corpse); - for (int j = 0; j < list.Count; j++) + ColonistBar.tmpMaps.Clear(); + ColonistBar.tmpMaps.AddRange(Find.Maps); + ColonistBar.tmpMaps.SortBy((Func)((Map x) => !x.IsPlayerHome), (Func)((Map x) => x.uniqueID)); + int num = 0; + for (int i = 0; i < ColonistBar.tmpMaps.Count; i++) { - if (!list[j].IsDessicated()) + ColonistBar.tmpPawns.Clear(); + ColonistBar.tmpPawns.AddRange(ColonistBar.tmpMaps[i].mapPawns.FreeColonists); + List list = ColonistBar.tmpMaps[i].listerThings.ThingsInGroup(ThingRequestGroup.Corpse); + for (int j = 0; j < list.Count; j++) { - Pawn innerPawn = ((Corpse)list[j]).InnerPawn; - if (innerPawn != null) + if (!list[j].IsDessicated()) { - if (innerPawn.IsColonist) + Pawn innerPawn = ((Corpse)list[j]).InnerPawn; + if (innerPawn != null && innerPawn.IsColonist) { ColonistBar.tmpPawns.Add(innerPawn); } } } - } - List allPawnsSpawned = ColonistBar.tmpMaps[i].mapPawns.AllPawnsSpawned; - for (int k = 0; k < allPawnsSpawned.Count; k++) - { - Corpse corpse = allPawnsSpawned[k].carryTracker.CarriedThing as Corpse; - if (corpse != null && !corpse.IsDessicated() && corpse.InnerPawn.IsColonist) + List allPawnsSpawned = ColonistBar.tmpMaps[i].mapPawns.AllPawnsSpawned; + for (int k = 0; k < allPawnsSpawned.Count; k++) { - ColonistBar.tmpPawns.Add(corpse.InnerPawn); + Corpse corpse = allPawnsSpawned[k].carryTracker.CarriedThing as Corpse; + if (corpse != null && !corpse.IsDessicated() && corpse.InnerPawn.IsColonist) + { + ColonistBar.tmpPawns.Add(corpse.InnerPawn); + } } + ColonistBar.tmpPawns.SortBy((Func)((Pawn x) => x.thingIDNumber)); + for (int l = 0; l < ColonistBar.tmpPawns.Count; l++) + { + this.cachedEntries.Add(new Entry(ColonistBar.tmpPawns[l], ColonistBar.tmpMaps[i], num)); + } + if (!ColonistBar.tmpPawns.Any()) + { + this.cachedEntries.Add(new Entry(null, ColonistBar.tmpMaps[i], num)); + } + num++; } - ColonistBar.tmpPawns.SortBy((Pawn x) => x.thingIDNumber); - for (int l = 0; l < ColonistBar.tmpPawns.Count; l++) - { - this.cachedEntries.Add(new ColonistBar.Entry(ColonistBar.tmpPawns[l], ColonistBar.tmpMaps[i], num)); - } - if (!ColonistBar.tmpPawns.Any()) - { - this.cachedEntries.Add(new ColonistBar.Entry(null, ColonistBar.tmpMaps[i], num)); - } - num++; - } - ColonistBar.tmpCaravans.Clear(); - ColonistBar.tmpCaravans.AddRange(Find.WorldObjects.Caravans); - ColonistBar.tmpCaravans.SortBy((Caravan x) => x.ID); - for (int m = 0; m < ColonistBar.tmpCaravans.Count; m++) - { - if (ColonistBar.tmpCaravans[m].IsPlayerControlled) + ColonistBar.tmpCaravans.Clear(); + ColonistBar.tmpCaravans.AddRange(Find.WorldObjects.Caravans); + ColonistBar.tmpCaravans.SortBy((Func)((Caravan x) => x.ID)); + for (int m = 0; m < ColonistBar.tmpCaravans.Count; m++) { - ColonistBar.tmpPawns.Clear(); - ColonistBar.tmpPawns.AddRange(ColonistBar.tmpCaravans[m].PawnsListForReading); - ColonistBar.tmpPawns.SortBy((Pawn x) => x.thingIDNumber); - for (int n = 0; n < ColonistBar.tmpPawns.Count; n++) + if (ColonistBar.tmpCaravans[m].IsPlayerControlled) { - if (ColonistBar.tmpPawns[n].IsColonist) + ColonistBar.tmpPawns.Clear(); + ColonistBar.tmpPawns.AddRange(ColonistBar.tmpCaravans[m].PawnsListForReading); + ColonistBar.tmpPawns.SortBy((Func)((Pawn x) => x.thingIDNumber)); + for (int n = 0; n < ColonistBar.tmpPawns.Count; n++) { - this.cachedEntries.Add(new ColonistBar.Entry(ColonistBar.tmpPawns[n], null, num)); + if (ColonistBar.tmpPawns[n].IsColonist) + { + this.cachedEntries.Add(new Entry(ColonistBar.tmpPawns[n], null, num)); + } } + num++; } - num++; } } + this.drawer.Notify_RecachedEntries(); + ColonistBar.tmpPawns.Clear(); + ColonistBar.tmpMaps.Clear(); + ColonistBar.tmpCaravans.Clear(); + this.drawLocsFinder.CalculateDrawLocs(this.cachedDrawLocs, out this.cachedScale); } - this.drawer.Notify_RecachedEntries(); - ColonistBar.tmpPawns.Clear(); - ColonistBar.tmpMaps.Clear(); - ColonistBar.tmpCaravans.Clear(); - this.drawLocsFinder.CalculateDrawLocs(this.cachedDrawLocs, out this.cachedScale); } public float GetEntryRectAlpha(Rect rect) { - float t; + float t = default(float); if (Messages.CollidesWithAnyMessage(rect, out t)) { return Mathf.Lerp(1f, 0.2f, t); @@ -280,37 +285,47 @@ public float GetEntryRectAlpha(Rect rect) public bool AnyColonistOrCorpseAt(Vector2 pos) { - ColonistBar.Entry entry; - return this.TryGetEntryAt(pos, out entry) && entry.pawn != null; + Entry entry = default(Entry); + if (!this.TryGetEntryAt(pos, out entry)) + { + return false; + } + return entry.pawn != null; } - public bool TryGetEntryAt(Vector2 pos, out ColonistBar.Entry entry) + public bool TryGetEntryAt(Vector2 pos, out Entry entry) { List drawLocs = this.DrawLocs; - List entries = this.Entries; + List entries = this.Entries; Vector2 size = this.Size; for (int i = 0; i < drawLocs.Count; i++) { - Rect rect = new Rect(drawLocs[i].x, drawLocs[i].y, size.x, size.y); + Vector2 vector = drawLocs[i]; + float x = vector.x; + Vector2 vector2 = drawLocs[i]; + Rect rect = new Rect(x, vector2.y, size.x, size.y); if (rect.Contains(pos)) { entry = entries[i]; return true; } } - entry = default(ColonistBar.Entry); + entry = default(Entry); return false; } public List GetColonistsInOrder() { - List entries = this.Entries; + List entries = this.Entries; ColonistBar.tmpColonistsInOrder.Clear(); for (int i = 0; i < entries.Count; i++) { - if (entries[i].pawn != null) + Entry entry = entries[i]; + if (entry.pawn != null) { - ColonistBar.tmpColonistsInOrder.Add(entries[i].pawn); + List obj = ColonistBar.tmpColonistsInOrder; + Entry entry2 = entries[i]; + obj.Add(entry2.pawn); } } return ColonistBar.tmpColonistsInOrder; @@ -319,42 +334,36 @@ public List GetColonistsInOrder() public List ColonistsOrCorpsesInScreenRect(Rect rect) { List drawLocs = this.DrawLocs; - List entries = this.Entries; + List entries = this.Entries; Vector2 size = this.Size; ColonistBar.tmpColonistsWithMap.Clear(); for (int i = 0; i < drawLocs.Count; i++) { - if (rect.Overlaps(new Rect(drawLocs[i].x, drawLocs[i].y, size.x, size.y))) + Vector2 vector = drawLocs[i]; + float x2 = vector.x; + Vector2 vector2 = drawLocs[i]; + if (rect.Overlaps(new Rect(x2, vector2.y, size.x, size.y))) { - Pawn pawn = entries[i].pawn; + Entry entry = entries[i]; + Pawn pawn = entry.pawn; if (pawn != null) { - Thing first; - if (pawn.Dead && pawn.Corpse != null && pawn.Corpse.SpawnedOrAnyParentSpawned) - { - first = pawn.Corpse; - } - else - { - first = pawn; - } - ColonistBar.tmpColonistsWithMap.Add(new Pair(first, entries[i].map)); + Thing thing = (Thing)((!pawn.Dead || pawn.Corpse == null || !pawn.Corpse.SpawnedOrAnyParentSpawned) ? ((object)pawn) : ((object)pawn.Corpse)); + List> obj = ColonistBar.tmpColonistsWithMap; + Thing first = thing; + Entry entry2 = entries[i]; + obj.Add(new Pair(first, entry2.map)); } } } - if (WorldRendererUtility.WorldRenderedNow) + if (WorldRendererUtility.WorldRenderedNow && ColonistBar.tmpColonistsWithMap.Any((Predicate>)((Pair x) => x.Second == null))) { - if (ColonistBar.tmpColonistsWithMap.Any((Pair x) => x.Second == null)) - { - ColonistBar.tmpColonistsWithMap.RemoveAll((Pair x) => x.Second != null); - goto IL_1A1; - } + ColonistBar.tmpColonistsWithMap.RemoveAll((Predicate>)((Pair x) => x.Second != null)); } - if (ColonistBar.tmpColonistsWithMap.Any((Pair x) => x.Second == Find.VisibleMap)) + else if (ColonistBar.tmpColonistsWithMap.Any((Predicate>)((Pair x) => x.Second == Find.VisibleMap))) { - ColonistBar.tmpColonistsWithMap.RemoveAll((Pair x) => x.Second != Find.VisibleMap); + ColonistBar.tmpColonistsWithMap.RemoveAll((Predicate>)((Pair x) => x.Second != Find.VisibleMap)); } - IL_1A1: ColonistBar.tmpColonists.Clear(); for (int j = 0; j < ColonistBar.tmpColonistsWithMap.Count; j++) { @@ -436,22 +445,13 @@ public Thing ColonistOrCorpseAt(Vector2 pos) { return null; } - ColonistBar.Entry entry; + Entry entry = default(Entry); if (!this.TryGetEntryAt(pos, out entry)) { return null; } Pawn pawn = entry.pawn; - Thing result; - if (pawn != null && pawn.Dead && pawn.Corpse != null && pawn.Corpse.SpawnedOrAnyParentSpawned) - { - result = pawn.Corpse; - } - else - { - result = pawn; - } - return result; + return (Thing)((pawn == null || !pawn.Dead || pawn.Corpse == null || !pawn.Corpse.SpawnedOrAnyParentSpawned) ? ((object)pawn) : ((object)pawn.Corpse)); } } } diff --git a/Assembly-CSharp/RimWorld/ColonistBarColonistDrawer.cs b/Assembly-CSharp/RimWorld/ColonistBarColonistDrawer.cs index 2e558d413..b597e94ba 100644 --- a/Assembly-CSharp/RimWorld/ColonistBarColonistDrawer.cs +++ b/Assembly-CSharp/RimWorld/ColonistBarColonistDrawer.cs @@ -42,7 +42,7 @@ public class ColonistBarColonistDrawer private static readonly Texture2D Icon_Burning = ContentFinder.Get("UI/Icons/ColonistBar/Burning", true); - public static readonly Vector2 PawnTextureSize = new Vector2(ColonistBar.BaseSize.x - 2f, 75f); + public static readonly Vector2 PawnTextureSize = new Vector2((float)(ColonistBar.BaseSize.x - 2.0), 75f); private static readonly Vector3 PawnTextureCameraOffset = new Vector3(0f, 0f, 0.3f); @@ -72,7 +72,7 @@ public void DrawColonist(Rect rect, Pawn colonist, Map pawnMap) position.height = num; GUI.DrawTexture(position, ColonistBarColonistDrawer.MoodBGTex); } - Rect rect2 = rect.ContractedBy(-2f * this.ColonistBar.Scale); + Rect rect2 = rect.ContractedBy((float)(-2.0 * this.ColonistBar.Scale)); if (flag && !WorldRendererUtility.WorldRenderedNow) { this.DrawSelectionOverlayOnGUI(colonist, rect2); @@ -82,16 +82,17 @@ public void DrawColonist(Rect rect, Pawn colonist, Map pawnMap) this.DrawCaravanSelectionOverlayOnGUI(colonist.GetCaravan(), rect2); } GUI.DrawTexture(this.GetPawnTextureRect(rect.x, rect.y), PortraitsCache.Get(colonist, ColonistBarColonistDrawer.PawnTextureSize, ColonistBarColonistDrawer.PawnTextureCameraOffset, 1.28205f)); - GUI.color = new Color(1f, 1f, 1f, entryRectAlpha * 0.8f); + GUI.color = new Color(1f, 1f, 1f, (float)(entryRectAlpha * 0.800000011920929)); this.DrawIcons(rect, colonist); GUI.color = color; if (colonist.Dead) { GUI.DrawTexture(rect, ColonistBarColonistDrawer.DeadColonistTex); } - float num2 = 4f * this.ColonistBar.Scale; - Vector2 pos = new Vector2(rect.center.x, rect.yMax - num2); - GenMapUI.DrawPawnLabel(colonist, pos, entryRectAlpha, rect.width + this.ColonistBar.SpaceBetweenColonistsHorizontal - 2f, this.pawnLabelsCache, GameFont.Tiny, true, true); + float num2 = (float)(4.0 * this.ColonistBar.Scale); + Vector2 center = rect.center; + Vector2 pos = new Vector2(center.x, rect.yMax - num2); + GenMapUI.DrawPawnLabel(colonist, pos, entryRectAlpha, (float)(rect.width + this.ColonistBar.SpaceBetweenColonistsHorizontal - 2.0), this.pawnLabelsCache, GameFont.Tiny, true, true); Text.Font = GameFont.Small; GUI.color = Color.white; } @@ -105,42 +106,35 @@ private Rect GroupFrameRect(int group) List drawLocs = this.ColonistBar.DrawLocs; for (int i = 0; i < entries.Count; i++) { - if (entries[i].group == group) + ColonistBar.Entry entry = entries[i]; + if (entry.group == group) { - num = Mathf.Min(num, drawLocs[i].x); - num2 = Mathf.Max(num2, drawLocs[i].x + this.ColonistBar.Size.x); - num3 = Mathf.Max(num3, drawLocs[i].y + this.ColonistBar.Size.y); + float a = num; + Vector2 vector = drawLocs[i]; + num = Mathf.Min(a, vector.x); + float a2 = num2; + Vector2 vector2 = drawLocs[i]; + float x = vector2.x; + Vector2 size = this.ColonistBar.Size; + num2 = Mathf.Max(a2, x + size.x); + float a3 = num3; + Vector2 vector3 = drawLocs[i]; + float y = vector3.y; + Vector2 size2 = this.ColonistBar.Size; + num3 = Mathf.Max(a3, y + size2.y); } } - return new Rect(num, 0f, num2 - num, num3).ContractedBy(-12f * this.ColonistBar.Scale); + return new Rect(num, 0f, num2 - num, num3).ContractedBy((float)(-12.0 * this.ColonistBar.Scale)); } public void DrawGroupFrame(int group) { Rect position = this.GroupFrameRect(group); List entries = this.ColonistBar.Entries; - Map map = entries.Find((ColonistBar.Entry x) => x.group == group).map; - float num; - if (map == null) - { - if (WorldRendererUtility.WorldRenderedNow) - { - num = 1f; - } - else - { - num = 0.75f; - } - } - else if (map != Find.VisibleMap || WorldRendererUtility.WorldRenderedNow) - { - num = 0.75f; - } - else - { - num = 1f; - } - Widgets.DrawRectFast(position, new Color(0.5f, 0.5f, 0.5f, 0.4f * num), null); + ColonistBar.Entry entry = entries.Find((Predicate)((ColonistBar.Entry x) => x.group == group)); + Map map = entry.map; + float num = (float)((map != null) ? ((map == Find.VisibleMap && !WorldRendererUtility.WorldRenderedNow) ? 1.0 : 0.75) : ((!WorldRendererUtility.WorldRenderedNow) ? 0.75 : 1.0)); + Widgets.DrawRectFast(position, new Color(0.5f, 0.5f, 0.5f, (float)(0.40000000596046448 * num)), null); } private void ApplyEntryInAnotherMapAlphaFactor(Map map, ref float alpha) @@ -152,8 +146,10 @@ private void ApplyEntryInAnotherMapAlphaFactor(Map map, ref float alpha) alpha = Mathf.Min(alpha, 0.4f); } } - else if (map != Find.VisibleMap || WorldRendererUtility.WorldRenderedNow) + else { + if (map == Find.VisibleMap && !WorldRendererUtility.WorldRenderedNow) + return; alpha = Mathf.Min(alpha, 0.4f); } } @@ -163,11 +159,11 @@ public void HandleClicks(Rect rect, Pawn colonist) if (Event.current.type == EventType.MouseDown && Event.current.button == 0 && Event.current.clickCount == 2 && Mouse.IsOver(rect)) { Event.current.Use(); - CameraJumper.TryJump(colonist); + CameraJumper.TryJump((Thing)colonist); } if (Event.current.button == 1 && Widgets.ButtonInvisible(rect, false)) { - CameraJumper.TryJumpAndSelect(CameraJumper.GetWorldTarget(colonist)); + CameraJumper.TryJumpAndSelect(CameraJumper.GetWorldTarget((Thing)colonist)); } } @@ -177,43 +173,50 @@ public void HandleGroupFrameClicks(int group) if (Event.current.type == EventType.MouseUp && Event.current.button == 0 && Mouse.IsOver(rect) && !this.ColonistBar.AnyColonistOrCorpseAt(UI.MousePositionOnUIInverted)) { bool worldRenderedNow = WorldRendererUtility.WorldRenderedNow; - if ((!worldRenderedNow && !Find.Selector.dragBox.IsValidAndActive) || (worldRenderedNow && !Find.WorldSelector.dragBox.IsValidAndActive)) + if (!worldRenderedNow && !Find.Selector.dragBox.IsValidAndActive) { - Find.Selector.dragBox.active = false; - Find.WorldSelector.dragBox.active = false; - ColonistBar.Entry entry = this.ColonistBar.Entries.Find((ColonistBar.Entry x) => x.group == group); - Map map = entry.map; - if (map == null) - { - if (WorldRendererUtility.WorldRenderedNow) - { - CameraJumper.TrySelect(entry.pawn); - } - else - { - CameraJumper.TryJumpAndSelect(entry.pawn); - } - } - else - { - if (!CameraJumper.TryHideWorld() && Current.Game.VisibleMap != map) - { - SoundDefOf.MapSelected.PlayOneShotOnCamera(null); - } - Current.Game.VisibleMap = map; - } + goto IL_0096; + } + if (worldRenderedNow && !Find.WorldSelector.dragBox.IsValidAndActive) + goto IL_0096; + } + goto IL_014c; + IL_0096: + Find.Selector.dragBox.active = false; + Find.WorldSelector.dragBox.active = false; + ColonistBar.Entry entry = this.ColonistBar.Entries.Find((Predicate)((ColonistBar.Entry x) => x.group == group)); + Map map = entry.map; + if (map == null) + { + if (WorldRendererUtility.WorldRenderedNow) + { + CameraJumper.TrySelect((Thing)entry.pawn); + } + else + { + CameraJumper.TryJumpAndSelect((Thing)entry.pawn); + } + } + else + { + if (!CameraJumper.TryHideWorld() && Current.Game.VisibleMap != map) + { + SoundDefOf.MapSelected.PlayOneShotOnCamera(null); } + Current.Game.VisibleMap = map; } + goto IL_014c; + IL_014c: if (Event.current.button == 1 && Widgets.ButtonInvisible(rect, false)) { - ColonistBar.Entry entry2 = this.ColonistBar.Entries.Find((ColonistBar.Entry x) => x.group == group); + ColonistBar.Entry entry2 = this.ColonistBar.Entries.Find((Predicate)((ColonistBar.Entry x) => x.group == group)); if (entry2.map != null) { CameraJumper.TryJumpAndSelect(CameraJumper.GetWorldTargetOfMap(entry2.map)); } else if (entry2.pawn != null) { - CameraJumper.TryJumpAndSelect(entry2.pawn); + CameraJumper.TryJumpAndSelect((Thing)entry2.pawn); } } } @@ -226,73 +229,75 @@ public void Notify_RecachedEntries() private Rect GetPawnTextureRect(float x, float y) { Vector2 vector = ColonistBarColonistDrawer.PawnTextureSize * this.ColonistBar.Scale; - Rect rect = new Rect(x + 1f, y - (vector.y - this.ColonistBar.Size.y) - 1f, vector.x, vector.y); + double x2 = x + 1.0; + float y2 = vector.y; + Vector2 size = this.ColonistBar.Size; + Rect rect = new Rect((float)x2, (float)(y - (y2 - size.y) - 1.0), vector.x, vector.y); rect = rect.ContractedBy(1f); return rect; } private void DrawIcons(Rect rect, Pawn colonist) { - if (colonist.Dead) + if (!colonist.Dead) { - return; - } - float num = 20f * this.ColonistBar.Scale; - Vector2 vector = new Vector2(rect.x + 1f, rect.yMax - num - 1f); - bool flag = false; - if (colonist.CurJob != null) - { - JobDef def = colonist.CurJob.def; - if (def == JobDefOf.AttackMelee || def == JobDefOf.AttackStatic) + float num = (float)(20.0 * this.ColonistBar.Scale); + Vector2 vector = new Vector2((float)(rect.x + 1.0), (float)(rect.yMax - num - 1.0)); + bool flag = false; + if (colonist.CurJob != null) { - flag = true; - } - else if (def == JobDefOf.WaitCombat) - { - Stance_Busy stance_Busy = colonist.stances.curStance as Stance_Busy; - if (stance_Busy != null && stance_Busy.focusTarg.IsValid) + JobDef def = colonist.CurJob.def; + if (def == JobDefOf.AttackMelee || def == JobDefOf.AttackStatic) { flag = true; } + else if (def == JobDefOf.WaitCombat) + { + Stance_Busy stance_Busy = colonist.stances.curStance as Stance_Busy; + if (stance_Busy != null && stance_Busy.focusTarg.IsValid) + { + flag = true; + } + } + } + if (colonist.InAggroMentalState) + { + this.DrawIcon(ColonistBarColonistDrawer.Icon_MentalStateAggro, ref vector, colonist.MentalStateDef.LabelCap); + } + else if (colonist.InMentalState) + { + this.DrawIcon(ColonistBarColonistDrawer.Icon_MentalStateNonAggro, ref vector, colonist.MentalStateDef.LabelCap); + } + else if (colonist.InBed() && colonist.CurrentBed().Medical) + { + this.DrawIcon(ColonistBarColonistDrawer.Icon_MedicalRest, ref vector, "ActivityIconMedicalRest".Translate()); + } + else if (colonist.CurJob != null && colonist.jobs.curDriver.asleep) + { + this.DrawIcon(ColonistBarColonistDrawer.Icon_Sleeping, ref vector, "ActivityIconSleeping".Translate()); + } + else if (colonist.CurJob != null && colonist.CurJob.def == JobDefOf.FleeAndCower) + { + this.DrawIcon(ColonistBarColonistDrawer.Icon_Fleeing, ref vector, "ActivityIconFleeing".Translate()); + } + else if (flag) + { + this.DrawIcon(ColonistBarColonistDrawer.Icon_Attacking, ref vector, "ActivityIconAttacking".Translate()); + } + else if (colonist.mindState.IsIdle && GenDate.DaysPassed >= 1) + { + this.DrawIcon(ColonistBarColonistDrawer.Icon_Idle, ref vector, "ActivityIconIdle".Translate()); + } + if (colonist.IsBurning()) + { + this.DrawIcon(ColonistBarColonistDrawer.Icon_Burning, ref vector, "ActivityIconBurning".Translate()); } - } - if (colonist.InAggroMentalState) - { - this.DrawIcon(ColonistBarColonistDrawer.Icon_MentalStateAggro, ref vector, colonist.MentalStateDef.LabelCap); - } - else if (colonist.InMentalState) - { - this.DrawIcon(ColonistBarColonistDrawer.Icon_MentalStateNonAggro, ref vector, colonist.MentalStateDef.LabelCap); - } - else if (colonist.InBed() && colonist.CurrentBed().Medical) - { - this.DrawIcon(ColonistBarColonistDrawer.Icon_MedicalRest, ref vector, "ActivityIconMedicalRest".Translate()); - } - else if (colonist.CurJob != null && colonist.jobs.curDriver.asleep) - { - this.DrawIcon(ColonistBarColonistDrawer.Icon_Sleeping, ref vector, "ActivityIconSleeping".Translate()); - } - else if (colonist.CurJob != null && colonist.CurJob.def == JobDefOf.FleeAndCower) - { - this.DrawIcon(ColonistBarColonistDrawer.Icon_Fleeing, ref vector, "ActivityIconFleeing".Translate()); - } - else if (flag) - { - this.DrawIcon(ColonistBarColonistDrawer.Icon_Attacking, ref vector, "ActivityIconAttacking".Translate()); - } - else if (colonist.mindState.IsIdle && GenDate.DaysPassed >= 1) - { - this.DrawIcon(ColonistBarColonistDrawer.Icon_Idle, ref vector, "ActivityIconIdle".Translate()); - } - if (colonist.IsBurning()) - { - this.DrawIcon(ColonistBarColonistDrawer.Icon_Burning, ref vector, "ActivityIconBurning".Translate()); } } private void DrawIcon(Texture2D icon, ref Vector2 pos, string tooltip) { - float num = 20f * this.ColonistBar.Scale; + float num = (float)(20.0 * this.ColonistBar.Scale); Rect rect = new Rect(pos.x, pos.y, num, num); GUI.DrawTexture(rect, icon); TooltipHandler.TipRegion(rect, tooltip); @@ -306,17 +311,17 @@ private void DrawSelectionOverlayOnGUI(Pawn colonist, Rect rect) { obj = colonist.Corpse; } - float num = 0.4f * this.ColonistBar.Scale; + float num = (float)(0.40000000596046448 * this.ColonistBar.Scale); Vector2 textureSize = new Vector2((float)SelectionDrawerUtility.SelectedTexGUI.width * num, (float)SelectionDrawerUtility.SelectedTexGUI.height * num); - SelectionDrawerUtility.CalculateSelectionBracketPositionsUI(ColonistBarColonistDrawer.bracketLocs, obj, rect, SelectionDrawer.SelectTimes, textureSize, 20f * this.ColonistBar.Scale); + SelectionDrawerUtility.CalculateSelectionBracketPositionsUI(ColonistBarColonistDrawer.bracketLocs, obj, rect, SelectionDrawer.SelectTimes, textureSize, (float)(20.0 * this.ColonistBar.Scale)); this.DrawSelectionOverlayOnGUI(ColonistBarColonistDrawer.bracketLocs, num); } private void DrawCaravanSelectionOverlayOnGUI(Caravan caravan, Rect rect) { - float num = 0.4f * this.ColonistBar.Scale; + float num = (float)(0.40000000596046448 * this.ColonistBar.Scale); Vector2 textureSize = new Vector2((float)SelectionDrawerUtility.SelectedTexGUI.width * num, (float)SelectionDrawerUtility.SelectedTexGUI.height * num); - SelectionDrawerUtility.CalculateSelectionBracketPositionsUI(ColonistBarColonistDrawer.bracketLocs, caravan, rect, WorldSelectionDrawer.SelectTimes, textureSize, 20f * this.ColonistBar.Scale); + SelectionDrawerUtility.CalculateSelectionBracketPositionsUI(ColonistBarColonistDrawer.bracketLocs, caravan, rect, WorldSelectionDrawer.SelectTimes, textureSize, (float)(20.0 * this.ColonistBar.Scale)); this.DrawSelectionOverlayOnGUI(ColonistBarColonistDrawer.bracketLocs, num); } diff --git a/Assembly-CSharp/RimWorld/ColonistBarDrawLocsFinder.cs b/Assembly-CSharp/RimWorld/ColonistBarDrawLocsFinder.cs index 4a4fffcdb..43be4fd8b 100644 --- a/Assembly-CSharp/RimWorld/ColonistBarDrawLocsFinder.cs +++ b/Assembly-CSharp/RimWorld/ColonistBarDrawLocsFinder.cs @@ -26,7 +26,7 @@ private static float MaxColonistBarWidth { get { - return (float)UI.screenWidth - 520f; + return (float)((float)UI.screenWidth - 520.0); } } @@ -36,13 +36,15 @@ public void CalculateDrawLocs(List outDrawLocs, out float scale) { outDrawLocs.Clear(); scale = 1f; - return; } - this.CalculateColonistsInGroup(); - bool onlyOneRow; - int maxPerGlobalRow; - scale = this.FindBestScale(out onlyOneRow, out maxPerGlobalRow); - this.CalculateDrawLocs(outDrawLocs, scale, onlyOneRow, maxPerGlobalRow); + else + { + this.CalculateColonistsInGroup(); + bool onlyOneRow = default(bool); + int maxPerGlobalRow = default(int); + scale = this.FindBestScale(out onlyOneRow, out maxPerGlobalRow); + this.CalculateDrawLocs(outDrawLocs, scale, onlyOneRow, maxPerGlobalRow); + } } private void CalculateColonistsInGroup() @@ -50,18 +52,19 @@ private void CalculateColonistsInGroup() this.entriesInGroup.Clear(); List entries = this.ColonistBar.Entries; int num = this.CalculateGroupsCount(); - for (int i = 0; i < num; i++) + for (int num2 = 0; num2 < num; num2++) { this.entriesInGroup.Add(0); } - for (int j = 0; j < entries.Count; j++) + for (int i = 0; i < entries.Count; i++) { List list; - List expr_49 = list = this.entriesInGroup; - int num2; - int expr_5C = num2 = entries[j].group; - num2 = list[num2]; - expr_49[expr_5C] = num2 + 1; + List obj = list = this.entriesInGroup; + ColonistBar.Entry entry = entries[i]; + int group; + int index = group = entry.group; + group = list[group]; + obj[index] = group + 1; } } @@ -72,10 +75,13 @@ private int CalculateGroupsCount() int num2 = 0; for (int i = 0; i < entries.Count; i++) { - if (num != entries[i].group) + int num3 = num; + ColonistBar.Entry entry = entries[i]; + if (num3 != entry.group) { num2++; - num = entries[i].group; + ColonistBar.Entry entry2 = entries[i]; + num = entry2.group; } } return num2; @@ -88,8 +94,9 @@ private float FindBestScale(out bool onlyOneRow, out int maxPerGlobalRow) int num2 = this.CalculateGroupsCount(); while (true) { - float num3 = (ColonistBar.BaseSize.x + 24f) * num; - float num4 = ColonistBarDrawLocsFinder.MaxColonistBarWidth - (float)(num2 - 1) * 25f * num; + Vector2 baseSize = ColonistBar.BaseSize; + float num3 = (float)((baseSize.x + 24.0) * num); + float num4 = (float)(ColonistBarDrawLocsFinder.MaxColonistBarWidth - (float)(num2 - 1) * 25.0 * num); maxPerGlobalRow = Mathf.FloorToInt(num4 / num3); onlyOneRow = true; if (this.TryDistributeHorizontalSlotsBetweenGroups(maxPerGlobalRow)) @@ -99,15 +106,23 @@ private float FindBestScale(out bool onlyOneRow, out int maxPerGlobalRow) int num5 = -1; for (int i = 0; i < entries.Count; i++) { - if (num5 != entries[i].group) + int num6 = num5; + ColonistBar.Entry entry = entries[i]; + if (num6 != entry.group) { - num5 = entries[i].group; - int num6 = Mathf.CeilToInt((float)this.entriesInGroup[entries[i].group] / (float)this.horizontalSlotsPerGroup[entries[i].group]); - if (num6 > 1) + ColonistBar.Entry entry2 = entries[i]; + num5 = entry2.group; + List obj = this.entriesInGroup; + ColonistBar.Entry entry3 = entries[i]; + float num7 = (float)obj[entry3.group]; + List obj2 = this.horizontalSlotsPerGroup; + ColonistBar.Entry entry4 = entries[i]; + int num8 = Mathf.CeilToInt(num7 / (float)obj2[entry4.group]); + if (num8 > 1) { onlyOneRow = false; } - if (num6 > allowedRowsCountForScale) + if (num8 > allowedRowsCountForScale) { flag = false; break; @@ -115,11 +130,9 @@ private float FindBestScale(out bool onlyOneRow, out int maxPerGlobalRow) } } if (flag) - { break; - } } - num *= 0.95f; + num = (float)(num * 0.949999988079071); } return num; } @@ -128,32 +141,32 @@ private bool TryDistributeHorizontalSlotsBetweenGroups(int maxPerGlobalRow) { int num = this.CalculateGroupsCount(); this.horizontalSlotsPerGroup.Clear(); - for (int k = 0; k < num; k++) + for (int num2 = 0; num2 < num; num2++) { this.horizontalSlotsPerGroup.Add(0); } - GenMath.DHondtDistribution(this.horizontalSlotsPerGroup, (int i) => (float)this.entriesInGroup[i], maxPerGlobalRow); + GenMath.DHondtDistribution(this.horizontalSlotsPerGroup, (Func)((int i) => (float)this.entriesInGroup[i]), maxPerGlobalRow); for (int j = 0; j < this.horizontalSlotsPerGroup.Count; j++) { if (this.horizontalSlotsPerGroup[j] == 0) { - int num2 = this.horizontalSlotsPerGroup.Max(); - if (num2 <= 1) + int num3 = this.horizontalSlotsPerGroup.Max(); + if (num3 <= 1) { return false; } - int num3 = this.horizontalSlotsPerGroup.IndexOf(num2); + int num4 = this.horizontalSlotsPerGroup.IndexOf(num3); List list; - List expr_89 = list = this.horizontalSlotsPerGroup; - int num4; - int expr_8E = num4 = num3; - num4 = list[num4]; - expr_89[expr_8E] = num4 - 1; + List obj = list = this.horizontalSlotsPerGroup; + int index; + int index2 = index = num4; + index = list[index]; + obj[index2] = index - 1; List list2; - List expr_AB = list2 = this.horizontalSlotsPerGroup; - int expr_AF = num4 = j; - num4 = list2[num4]; - expr_AB[expr_AF] = num4 + 1; + List obj2 = list2 = this.horizontalSlotsPerGroup; + int index3 = index = j; + index = list2[index]; + obj2[index3] = index + 1; } } return true; @@ -161,11 +174,11 @@ private bool TryDistributeHorizontalSlotsBetweenGroups(int maxPerGlobalRow) private static int GetAllowedRowsCountForScale(float scale) { - if (scale > 0.58f) + if (scale > 0.57999998331069946) { return 1; } - if (scale > 0.42f) + if (scale > 0.41999998688697815) { return 2; } @@ -185,44 +198,59 @@ private void CalculateDrawLocs(List outDrawLocs, float scale, bool only num = this.ColonistBar.Entries.Count; } int num2 = this.CalculateGroupsCount(); - float num3 = (ColonistBar.BaseSize.x + 24f) * scale; - float num4 = (float)num * num3 + (float)(num2 - 1) * 25f * scale; + Vector2 baseSize = ColonistBar.BaseSize; + float num3 = (float)((baseSize.x + 24.0) * scale); + float num4 = (float)((float)num * num3 + (float)(num2 - 1) * 25.0 * scale); List entries = this.ColonistBar.Entries; int num5 = -1; int num6 = -1; - float num7 = ((float)UI.screenWidth - num4) / 2f; + float num7 = (float)(((float)UI.screenWidth - num4) / 2.0); for (int j = 0; j < entries.Count; j++) { - if (num5 != entries[j].group) + int num8 = num5; + ColonistBar.Entry entry = entries[j]; + if (num8 != entry.group) { if (num5 >= 0) { - num7 += 25f * scale; - num7 += (float)this.horizontalSlotsPerGroup[num5] * scale * (ColonistBar.BaseSize.x + 24f); + num7 = (float)(num7 + 25.0 * scale); + float num9 = num7; + float num10 = (float)this.horizontalSlotsPerGroup[num5] * scale; + Vector2 baseSize2 = ColonistBar.BaseSize; + num7 = (float)(num9 + num10 * (baseSize2.x + 24.0)); } num6 = 0; - num5 = entries[j].group; + ColonistBar.Entry entry2 = entries[j]; + num5 = entry2.group; } else { num6++; } - Vector2 drawLoc = this.GetDrawLoc(num7, 21f, entries[j].group, num6, scale); + float groupStartX = num7; + ColonistBar.Entry entry3 = entries[j]; + Vector2 drawLoc = this.GetDrawLoc(groupStartX, 21f, entry3.group, num6, scale); outDrawLocs.Add(drawLoc); } } private Vector2 GetDrawLoc(float groupStartX, float groupStartY, int group, int numInGroup, float scale) { - float num = groupStartX + (float)(numInGroup % this.horizontalSlotsPerGroup[group]) * scale * (ColonistBar.BaseSize.x + 24f); - float y = groupStartY + (float)(numInGroup / this.horizontalSlotsPerGroup[group]) * scale * (ColonistBar.BaseSize.y + 32f); - bool flag = numInGroup >= this.entriesInGroup[group] - this.entriesInGroup[group] % this.horizontalSlotsPerGroup[group]; - if (flag) + float num = (float)(numInGroup % this.horizontalSlotsPerGroup[group]) * scale; + Vector2 baseSize = ColonistBar.BaseSize; + float num2 = (float)(groupStartX + num * (baseSize.x + 24.0)); + float num3 = (float)(numInGroup / this.horizontalSlotsPerGroup[group]) * scale; + Vector2 baseSize2 = ColonistBar.BaseSize; + float y = (float)(groupStartY + num3 * (baseSize2.y + 32.0)); + if (numInGroup >= this.entriesInGroup[group] - this.entriesInGroup[group] % this.horizontalSlotsPerGroup[group]) { - int num2 = this.horizontalSlotsPerGroup[group] - this.entriesInGroup[group] % this.horizontalSlotsPerGroup[group]; - num += (float)num2 * scale * (ColonistBar.BaseSize.x + 24f) * 0.5f; + int num4 = this.horizontalSlotsPerGroup[group] - this.entriesInGroup[group] % this.horizontalSlotsPerGroup[group]; + float num5 = num2; + float num6 = (float)num4 * scale; + Vector2 baseSize3 = ColonistBar.BaseSize; + num2 = (float)(num5 + num6 * (baseSize3.x + 24.0) * 0.5); } - return new Vector2(num, y); + return new Vector2(num2, y); } } } diff --git a/Assembly-CSharp/RimWorld/ColonyMakerFlag.cs b/Assembly-CSharp/RimWorld/ColonyMakerFlag.cs index 986bbabc5..7c9312638 100644 --- a/Assembly-CSharp/RimWorld/ColonyMakerFlag.cs +++ b/Assembly-CSharp/RimWorld/ColonyMakerFlag.cs @@ -1,28 +1,26 @@ -using System; - namespace RimWorld { public enum ColonyMakerFlag { - Animals, - ConduitGrid, - PowerPlants, - Batteries, - WorkTables, - AllBuildings, - ItemsWall, - AllItems, - ItemsRawFood, - Filth, - Fire, - ColonistOne, - ColonistsMany, - ColonistsHungry, - ColonistsTired, - ColonistsInjured, - ColonistsDiseased, - Stockpiles, - GrowingZones, - Beds + Animals = 0, + ConduitGrid = 1, + PowerPlants = 2, + Batteries = 3, + WorkTables = 4, + AllBuildings = 5, + ItemsWall = 6, + AllItems = 7, + ItemsRawFood = 8, + Filth = 9, + Fire = 10, + ColonistOne = 11, + ColonistsMany = 12, + ColonistsHungry = 13, + ColonistsTired = 14, + ColonistsInjured = 15, + ColonistsDiseased = 16, + Stockpiles = 17, + GrowingZones = 18, + Beds = 19 } } diff --git a/Assembly-CSharp/RimWorld/ComfortCategory.cs b/Assembly-CSharp/RimWorld/ComfortCategory.cs index 13c95164f..04a2b76ae 100644 --- a/Assembly-CSharp/RimWorld/ComfortCategory.cs +++ b/Assembly-CSharp/RimWorld/ComfortCategory.cs @@ -1,14 +1,12 @@ -using System; - namespace RimWorld { public enum ComfortCategory : byte { - Uncomfortable, - Normal, - Comfortable, - VeryComfortable, - ExtremelyComfortable, - LuxuriantlyComfortable + Uncomfortable = 0, + Normal = 1, + Comfortable = 2, + VeryComfortable = 3, + ExtremelyComfortable = 4, + LuxuriantlyComfortable = 5 } } diff --git a/Assembly-CSharp/RimWorld/Command_LoadToTransporter.cs b/Assembly-CSharp/RimWorld/Command_LoadToTransporter.cs index c44cd75cd..f4844f5c6 100644 --- a/Assembly-CSharp/RimWorld/Command_LoadToTransporter.cs +++ b/Assembly-CSharp/RimWorld/Command_LoadToTransporter.cs @@ -34,7 +34,7 @@ public override void ProcessInput(Event ev) { Map map = this.transComp.Map; Command_LoadToTransporter.tmpFuelingPortGivers.Clear(); - map.floodFiller.FloodFill(fuelingPortSource.Position, (IntVec3 x) => FuelingPortUtility.AnyFuelingPortGiverAt(x, map), delegate(IntVec3 x) + map.floodFiller.FloodFill(fuelingPortSource.Position, (Predicate)((IntVec3 x) => FuelingPortUtility.AnyFuelingPortGiverAt(x, map)), (Action)delegate(IntVec3 x) { Command_LoadToTransporter.tmpFuelingPortGivers.Add(FuelingPortUtility.FuelingPortGiverAt(x, map)); }, false); @@ -43,7 +43,7 @@ public override void ProcessInput(Event ev) Building fuelingPortSource2 = this.transporters[i].Launchable.FuelingPortSource; if (fuelingPortSource2 != null && !Command_LoadToTransporter.tmpFuelingPortGivers.Contains(fuelingPortSource2)) { - Messages.Message("MessageTransportersNotAdjacent".Translate(), fuelingPortSource2, MessageSound.RejectInput); + Messages.Message("MessageTransportersNotAdjacent".Translate(), (Thing)fuelingPortSource2, MessageSound.RejectInput); return; } } @@ -51,13 +51,10 @@ public override void ProcessInput(Event ev) } for (int j = 0; j < this.transporters.Count; j++) { - if (this.transporters[j] != this.transComp) + if (this.transporters[j] != this.transComp && !this.transComp.Map.reachability.CanReach(this.transComp.parent.Position, (Thing)this.transporters[j].parent, PathEndMode.Touch, TraverseParms.For(TraverseMode.PassDoors, Danger.Deadly, false))) { - if (!this.transComp.Map.reachability.CanReach(this.transComp.parent.Position, this.transporters[j].parent, PathEndMode.Touch, TraverseParms.For(TraverseMode.PassDoors, Danger.Deadly, false))) - { - Messages.Message("MessageTransporterUnreachable".Translate(), this.transporters[j].parent, MessageSound.RejectInput); - return; - } + Messages.Message("MessageTransporterUnreachable".Translate(), (Thing)this.transporters[j].parent, MessageSound.RejectInput); + return; } } Find.WindowStack.Add(new Dialog_LoadTransporters(this.transComp.Map, this.transporters)); diff --git a/Assembly-CSharp/RimWorld/Command_SetTargetFuelLevel.cs b/Assembly-CSharp/RimWorld/Command_SetTargetFuelLevel.cs index 9d6e8d78b..2bb009430 100644 --- a/Assembly-CSharp/RimWorld/Command_SetTargetFuelLevel.cs +++ b/Assembly-CSharp/RimWorld/Command_SetTargetFuelLevel.cs @@ -32,35 +32,23 @@ public override void ProcessInput(Event ev) } } int startingValue = num / 2; - for (int j = 0; j < this.refuelables.Count; j++) + int num2 = 0; + while (num2 < this.refuelables.Count) { - if ((int)this.refuelables[j].TargetFuelLevel <= num) + if ((int)this.refuelables[num2].TargetFuelLevel > num) { - startingValue = (int)this.refuelables[j].TargetFuelLevel; - break; + num2++; + continue; } + startingValue = (int)this.refuelables[num2].TargetFuelLevel; + break; } - Func textGetter; - if (this.refuelable.parent.def.building.hasFuelingPort) + Func textGetter = (!this.refuelable.parent.def.building.hasFuelingPort) ? ((Func)((int x) => "SetTargetFuelLevel".Translate(x))) : ((Func)((int x) => "SetPodLauncherTargetFuelLevel".Translate(x, CompLaunchable.MaxLaunchDistanceAtFuelLevel((float)x)))); + Dialog_Slider window = new Dialog_Slider(textGetter, 0, num, (Action)delegate(int value) { - textGetter = ((int x) => "SetPodLauncherTargetFuelLevel".Translate(new object[] + for (int j = 0; j < this.refuelables.Count; j++) { - x, - CompLaunchable.MaxLaunchDistanceAtFuelLevel((float)x) - })); - } - else - { - textGetter = ((int x) => "SetTargetFuelLevel".Translate(new object[] - { - x - })); - } - Dialog_Slider window = new Dialog_Slider(textGetter, 0, num, delegate(int value) - { - for (int k = 0; k < this.refuelables.Count; k++) - { - this.refuelables[k].TargetFuelLevel = (float)value; + this.refuelables[j].TargetFuelLevel = (float)value; } }, startingValue); Find.WindowStack.Add(window); diff --git a/Assembly-CSharp/RimWorld/CompAffectedByFacilities.cs b/Assembly-CSharp/RimWorld/CompAffectedByFacilities.cs index 35f583a3e..9fdaf15bf 100644 --- a/Assembly-CSharp/RimWorld/CompAffectedByFacilities.cs +++ b/Assembly-CSharp/RimWorld/CompAffectedByFacilities.cs @@ -1,6 +1,6 @@ using System; using System.Collections.Generic; -using System.Diagnostics; +using System.Linq; using System.Text; using UnityEngine; using Verse; @@ -32,11 +32,17 @@ private IEnumerable ThingsICanLinkTo { get { - CompAffectedByFacilities.<>c__Iterator162 <>c__Iterator = new CompAffectedByFacilities.<>c__Iterator162(); - <>c__Iterator.<>f__this = this; - CompAffectedByFacilities.<>c__Iterator162 expr_0E = <>c__Iterator; - expr_0E.$PC = -2; - return expr_0E; + if (base.parent.Spawned) + { + IEnumerable potentialThings = CompAffectedByFacilities.PotentialThingsToLinkTo(base.parent.def, base.parent.Position, base.parent.Rotation, base.parent.Map); + foreach (Thing item in potentialThings) + { + if (this.CanLinkTo(item)) + { + yield return item; + } + } + } } } @@ -62,12 +68,20 @@ public bool CanLinkTo(Thing facility) public static bool CanPotentiallyLinkTo_Static(Thing facility, ThingDef myDef, IntVec3 myPos, Rot4 myRot) { - return CompAffectedByFacilities.CanPotentiallyLinkTo_Static(facility.def, facility.Position, facility.Rotation, myDef, myPos, myRot) && CompAffectedByFacilities.IsPotentiallyValidFacilityForMe_Static(facility, myDef, myPos, myRot); + if (!CompAffectedByFacilities.CanPotentiallyLinkTo_Static(facility.def, facility.Position, facility.Rotation, myDef, myPos, myRot)) + { + return false; + } + if (!CompAffectedByFacilities.IsPotentiallyValidFacilityForMe_Static(facility, myDef, myPos, myRot)) + { + return false; + } + return true; } public bool CanPotentiallyLinkTo(ThingDef facilityDef, IntVec3 facilityPos, Rot4 facilityRot) { - if (!CompAffectedByFacilities.CanPotentiallyLinkTo_Static(facilityDef, facilityPos, facilityRot, this.parent.def, this.parent.Position, this.parent.Rotation)) + if (!CompAffectedByFacilities.CanPotentiallyLinkTo_Static(facilityDef, facilityPos, facilityRot, base.parent.def, base.parent.Position, base.parent.Rotation)) { return false; } @@ -94,64 +108,79 @@ public bool CanPotentiallyLinkTo(ThingDef facilityDef, IntVec3 facilityPos, Rot4 return true; } CompProperties_Facility compProperties = facilityDef.GetCompProperties(); - return num + 1 <= compProperties.maxSimultaneous; + if (num + 1 > compProperties.maxSimultaneous) + { + return false; + } + return true; } public static bool CanPotentiallyLinkTo_Static(ThingDef facilityDef, IntVec3 facilityPos, Rot4 facilityRot, ThingDef myDef, IntVec3 myPos, Rot4 myRot) { CompProperties_Facility compProperties = facilityDef.GetCompProperties(); + bool flag; if (compProperties.mustBePlacedAdjacent) { - bool flag = false; - foreach (IntVec3 current in GenAdj.CellsOccupiedBy(myPos, myRot, myDef.size)) + flag = false; + foreach (IntVec3 item in GenAdj.CellsOccupiedBy(myPos, myRot, myDef.size)) { - foreach (IntVec3 current2 in GenAdj.CellsOccupiedBy(facilityPos, facilityRot, facilityDef.size)) + IntVec3 current = item; + foreach (IntVec3 item2 in GenAdj.CellsOccupiedBy(facilityPos, facilityRot, facilityDef.size)) { + IntVec3 current2 = item2; if (Mathf.Abs(current.x - current2.x) <= 1 && Mathf.Abs(current.z - current2.z) <= 1) { flag = true; - goto IL_CB; + goto IL_00cb; } } } - IL_CB: - if (!flag) - { - return false; - } + goto IL_00cb; } - else + Vector3 a = Gen.TrueCenter(myPos, myRot, myDef.size, myDef.Altitude); + Vector3 b = Gen.TrueCenter(facilityPos, facilityRot, facilityDef.size, facilityDef.Altitude); + if (Vector3.Distance(a, b) > 8.0) { - Vector3 a = Gen.TrueCenter(myPos, myRot, myDef.size, myDef.Altitude); - Vector3 b = Gen.TrueCenter(facilityPos, facilityRot, facilityDef.size, facilityDef.Altitude); - if (Vector3.Distance(a, b) > 8f) - { - return false; - } + return false; } + goto IL_0119; + IL_0119: return true; + IL_00cb: + if (!flag) + { + return false; + } + goto IL_0119; } public bool IsValidFacilityForMe(Thing facility) { - return CompAffectedByFacilities.IsPotentiallyValidFacilityForMe_Static(facility, this.parent.def, this.parent.Position, this.parent.Rotation); + if (!CompAffectedByFacilities.IsPotentiallyValidFacilityForMe_Static(facility, base.parent.def, base.parent.Position, base.parent.Rotation)) + { + return false; + } + return true; } private bool IsPotentiallyValidFacilityForMe(ThingDef facilityDef, IntVec3 facilityPos, Rot4 facilityRot) { - if (!CompAffectedByFacilities.IsPotentiallyValidFacilityForMe_Static(facilityDef, facilityPos, facilityRot, this.parent.def, this.parent.Position, this.parent.Rotation, this.parent.Map)) + if (!CompAffectedByFacilities.IsPotentiallyValidFacilityForMe_Static(facilityDef, facilityPos, facilityRot, base.parent.def, base.parent.Position, base.parent.Rotation, base.parent.Map)) { return false; } CompProperties_Facility compProperties = facilityDef.GetCompProperties(); if (compProperties.canLinkToMedBedsOnly) { - Building_Bed building_Bed = this.parent as Building_Bed; - if (building_Bed == null || !building_Bed.Medical) + Building_Bed building_Bed = base.parent as Building_Bed; + if (building_Bed != null && building_Bed.Medical) { - return false; + goto IL_006c; } + return false; } + goto IL_006c; + IL_006c: return true; } @@ -164,7 +193,7 @@ private static bool IsPotentiallyValidFacilityForMe_Static(ThingDef facilityDef, { CellRect startRect = GenAdj.OccupiedRect(myPos, myRot, myDef.size); CellRect endRect = GenAdj.OccupiedRect(facilityPos, facilityRot, facilityDef.size); - bool result = false; + bool flag = false; for (int i = startRect.minZ; i <= startRect.maxZ; i++) { for (int j = startRect.minX; j <= startRect.maxX; j++) @@ -176,15 +205,20 @@ private static bool IsPotentiallyValidFacilityForMe_Static(ThingDef facilityDef, IntVec3 start = new IntVec3(j, 0, i); IntVec3 end = new IntVec3(l, 0, k); if (GenSight.LineOfSight(start, end, map, startRect, endRect)) - { - result = true; - return result; - } + goto IL_0080; } } } + continue; + IL_0080: + flag = true; + break; } - return result; + if (!flag) + { + return false; + } + return true; } public void Notify_NewLink(Thing facility) @@ -200,7 +234,7 @@ public void Notify_NewLink(Thing facility) Thing potentiallySupplantedFacility = this.GetPotentiallySupplantedFacility(facility.def, facility.Position, facility.Rotation); if (potentiallySupplantedFacility != null) { - potentiallySupplantedFacility.TryGetComp().Notify_LinkRemoved(this.parent); + potentiallySupplantedFacility.TryGetComp().Notify_LinkRemoved(base.parent); this.linkedFacilities.Remove(potentiallySupplantedFacility); } this.linkedFacilities.Add(facility); @@ -250,11 +284,11 @@ public override void PostDrawExtraSelectionOverlays() { if (this.IsFacilityActive(this.linkedFacilities[i])) { - GenDraw.DrawLineBetween(this.parent.TrueCenter(), this.linkedFacilities[i].TrueCenter()); + GenDraw.DrawLineBetween(base.parent.TrueCenter(), this.linkedFacilities[i].TrueCenter()); } else { - GenDraw.DrawLineBetween(this.parent.TrueCenter(), this.linkedFacilities[i].TrueCenter(), CompAffectedByFacilities.InactiveFacilityLineMat); + GenDraw.DrawLineBetween(base.parent.TrueCenter(), this.linkedFacilities[i].TrueCenter(), CompAffectedByFacilities.InactiveFacilityLineMat); } } } @@ -267,43 +301,82 @@ private bool IsBetter(ThingDef facilityDef, IntVec3 facilityPos, Rot4 facilityRo return false; } Vector3 b = Gen.TrueCenter(facilityPos, facilityRot, facilityDef.size, facilityDef.Altitude); - Vector3 a = this.parent.TrueCenter(); + Vector3 a = base.parent.TrueCenter(); float num = Vector3.Distance(a, b); float num2 = Vector3.Distance(a, thanThisFacility.TrueCenter()); if (num != num2) { return num < num2; } - if (facilityPos.x != thanThisFacility.Position.x) + int x = facilityPos.x; + IntVec3 position = thanThisFacility.Position; + if (x != position.x) { - return facilityPos.x < thanThisFacility.Position.x; + int x2 = facilityPos.x; + IntVec3 position2 = thanThisFacility.Position; + return x2 < position2.x; } - return facilityPos.z < thanThisFacility.Position.z; + int z = facilityPos.z; + IntVec3 position3 = thanThisFacility.Position; + return z < position3.z; } - [DebuggerHidden] public static IEnumerable PotentialThingsToLinkTo(ThingDef myDef, IntVec3 myPos, Rot4 myRot, Map map) { - CompAffectedByFacilities.c__Iterator163 c__Iterator = new CompAffectedByFacilities.c__Iterator163(); - c__Iterator.myDef = myDef; - c__Iterator.map = map; - c__Iterator.myPos = myPos; - c__Iterator.myRot = myRot; - c__Iterator.<$>myDef = myDef; - c__Iterator.<$>map = map; - c__Iterator.<$>myPos = myPos; - c__Iterator.<$>myRot = myRot; - CompAffectedByFacilities.c__Iterator163 expr_3F = c__Iterator; - expr_3F.$PC = -2; - return expr_3F; + CompAffectedByFacilities.alreadyReturnedCount.Clear(); + CompProperties_AffectedByFacilities myProps = myDef.GetCompProperties(); + if (myProps.linkableFacilities != null) + { + IEnumerable candidates = Enumerable.Empty(); + for (int i = 0; i < myProps.linkableFacilities.Count; i++) + { + candidates = candidates.Concat(map.listerThings.ThingsOfDef(myProps.linkableFacilities[i])); + } + Vector3 myTrueCenter = Gen.TrueCenter(myPos, myRot, myDef.size, myDef.Altitude); + IOrderedEnumerable sortedCandidates = (from x in candidates + orderby Vector3.Distance(((_003CPotentialThingsToLinkTo_003Ec__Iterator163)/*Error near IL_00fe: stateMachine*/)._003CmyTrueCenter_003E__3, x.TrueCenter()) + select x).ThenBy((Func)delegate(Thing x) + { + IntVec3 position2 = x.Position; + return position2.x; + }).ThenBy((Func)delegate(Thing x) + { + IntVec3 position = x.Position; + return position.z; + }); + foreach (Thing item in sortedCandidates) + { + if (CompAffectedByFacilities.CanPotentiallyLinkTo_Static(item, myDef, myPos, myRot)) + { + CompProperties_Facility facilityProps = item.def.GetCompProperties(); + if (CompAffectedByFacilities.alreadyReturnedCount.ContainsKey(item.def)) + { + if (CompAffectedByFacilities.alreadyReturnedCount[item.def] < facilityProps.maxSimultaneous) + goto IL_022a; + continue; + } + CompAffectedByFacilities.alreadyReturnedCount.Add(item.def, 0); + goto IL_022a; + } + continue; + IL_022a: + Dictionary dictionary; + Dictionary obj = dictionary = CompAffectedByFacilities.alreadyReturnedCount; + ThingDef def; + ThingDef key = def = item.def; + int num = dictionary[def]; + obj[key] = num + 1; + yield return item; + } + } } public static void DrawLinesToPotentialThingsToLinkTo(ThingDef myDef, IntVec3 myPos, Rot4 myRot, Map map) { Vector3 a = Gen.TrueCenter(myPos, myRot, myDef.size, myDef.Altitude); - foreach (Thing current in CompAffectedByFacilities.PotentialThingsToLinkTo(myDef, myPos, myRot, map)) + foreach (Thing item in CompAffectedByFacilities.PotentialThingsToLinkTo(myDef, myPos, myRot, map)) { - GenDraw.DrawLineBetween(a, current.TrueCenter()); + GenDraw.DrawLineBetween(a, item.TrueCenter()); } } @@ -312,7 +385,7 @@ public void DrawRedLineToPotentiallySupplantedFacility(ThingDef facilityDef, Int Thing potentiallySupplantedFacility = this.GetPotentiallySupplantedFacility(facilityDef, facilityPos, facilityRot); if (potentiallySupplantedFacility != null) { - GenDraw.DrawLineBetween(this.parent.TrueCenter(), potentiallySupplantedFacility.TrueCenter(), CompAffectedByFacilities.InactiveFacilityLineMat); + GenDraw.DrawLineBetween(base.parent.TrueCenter(), potentiallySupplantedFacility.TrueCenter(), CompAffectedByFacilities.InactiveFacilityLineMat); } } @@ -343,12 +416,9 @@ private Thing GetPotentiallySupplantedFacility(ThingDef facilityDef, IntVec3 fac Thing thing2 = thing; for (int j = 0; j < this.linkedFacilities.Count; j++) { - if (facilityDef == this.linkedFacilities[j].def) + if (facilityDef == this.linkedFacilities[j].def && this.IsBetter(thing2.def, thing2.Position, thing2.Rotation, this.linkedFacilities[j])) { - if (this.IsBetter(thing2.def, thing2.Position, thing2.Rotation, this.linkedFacilities[j])) - { - thing2 = this.linkedFacilities[j]; - } + thing2 = this.linkedFacilities[j]; } } return thing2; @@ -378,47 +448,47 @@ public void GetStatsExplanation(StatDef stat, StringBuilder sb) for (int i = 0; i < this.linkedFacilities.Count; i++) { bool flag2 = false; - for (int j = 0; j < this.alreadyUsed.Count; j++) + int num = 0; + while (num < this.alreadyUsed.Count) { - if (this.alreadyUsed[j] == this.linkedFacilities[i].def) + if (this.alreadyUsed[num] != this.linkedFacilities[i].def) { - flag2 = true; - break; + num++; + continue; } + flag2 = true; + break; } - if (!flag2) + if (!flag2 && this.IsFacilityActive(this.linkedFacilities[i])) { - if (this.IsFacilityActive(this.linkedFacilities[i])) + CompProperties_Facility compProperties = this.linkedFacilities[i].def.GetCompProperties(); + if (compProperties.statOffsets != null) { - CompProperties_Facility compProperties = this.linkedFacilities[i].def.GetCompProperties(); - if (compProperties.statOffsets != null) + float statOffsetFromList = compProperties.statOffsets.GetStatOffsetFromList(stat); + if (statOffsetFromList != 0.0) { - float num = compProperties.statOffsets.GetStatOffsetFromList(stat); - if (num != 0f) + if (!flag) { - if (!flag) - { - flag = true; - sb.AppendLine(); - sb.AppendLine("StatsReport_Facilities".Translate() + ":"); - } - int num2 = 0; - for (int k = 0; k < this.linkedFacilities.Count; k++) - { - if (this.IsFacilityActive(this.linkedFacilities[k]) && this.linkedFacilities[k].def == this.linkedFacilities[i].def) - { - num2++; - } - } - num *= (float)num2; - sb.Append(" "); - if (num2 != 1) + flag = true; + sb.AppendLine(); + sb.AppendLine("StatsReport_Facilities".Translate() + ":"); + } + int num2 = 0; + for (int j = 0; j < this.linkedFacilities.Count; j++) + { + if (this.IsFacilityActive(this.linkedFacilities[j]) && this.linkedFacilities[j].def == this.linkedFacilities[i].def) { - sb.Append(num2.ToString() + "x "); + num2++; } - sb.AppendLine(this.linkedFacilities[i].LabelCap + ": " + num.ToStringByStyle(stat.toStringStyle, ToStringNumberSense.Offset)); - this.alreadyUsed.Add(this.linkedFacilities[i].def); } + statOffsetFromList *= (float)num2; + sb.Append(" "); + if (num2 != 1) + { + sb.Append(num2.ToString() + "x "); + } + sb.AppendLine(this.linkedFacilities[i].LabelCap + ": " + statOffsetFromList.ToStringByStyle(stat.toStringStyle, ToStringNumberSense.Offset)); + this.alreadyUsed.Add(this.linkedFacilities[i].def); } } } @@ -438,12 +508,12 @@ public bool IsFacilityActive(Thing facility) private void LinkToNearbyFacilities() { this.UnlinkAll(); - if (this.parent.Spawned) + if (base.parent.Spawned) { - foreach (Thing current in this.ThingsICanLinkTo) + foreach (Thing item in this.ThingsICanLinkTo) { - this.linkedFacilities.Add(current); - current.TryGetComp().Notify_NewLink(this.parent); + this.linkedFacilities.Add(item); + item.TryGetComp().Notify_NewLink(base.parent); } } } @@ -452,7 +522,7 @@ private void UnlinkAll() { for (int i = 0; i < this.linkedFacilities.Count; i++) { - this.linkedFacilities[i].TryGetComp().Notify_LinkRemoved(this.parent); + this.linkedFacilities[i].TryGetComp().Notify_LinkRemoved(base.parent); } this.linkedFacilities.Clear(); } diff --git a/Assembly-CSharp/RimWorld/CompArt.cs b/Assembly-CSharp/RimWorld/CompArt.cs index 32680ce0c..70cc3a0e4 100644 --- a/Assembly-CSharp/RimWorld/CompArt.cs +++ b/Assembly-CSharp/RimWorld/CompArt.cs @@ -1,4 +1,3 @@ -using System; using Verse; namespace RimWorld @@ -50,14 +49,21 @@ public bool CanShowArt { if (this.Props.mustBeFullGrave) { - Building_Grave building_Grave = this.parent as Building_Grave; - if (building_Grave == null || !building_Grave.HasCorpse) + Building_Grave building_Grave = base.parent as Building_Grave; + if (building_Grave != null && building_Grave.HasCorpse) { - return false; + goto IL_002f; } + return false; } - QualityCategory qualityCategory; - return !this.parent.TryGetQuality(out qualityCategory) || qualityCategory >= this.Props.minQualityForArtistic; + goto IL_002f; + IL_002f: + QualityCategory qualityCategory = default(QualityCategory); + if (!((Thing)base.parent).TryGetQuality(out qualityCategory)) + { + return true; + } + return (int)qualityCategory >= (int)this.Props.minQualityForArtistic; } } @@ -73,7 +79,7 @@ public CompProperties_Art Props { get { - return (CompProperties_Art)this.props; + return (CompProperties_Art)base.props; } } @@ -115,7 +121,7 @@ private void InitializeArt(Thing relatedThing, ArtGenerationContext source) } else { - this.titleInt = null; + this.titleInt = (string)null; this.taleRef = null; } } @@ -130,8 +136,8 @@ public void JustCreatedBy(Pawn pawn) public void Clear() { - this.authorNameInt = null; - this.titleInt = null; + this.authorNameInt = (string)null; + this.titleInt = (string)null; if (this.taleRef != null) { this.taleRef.ReferenceDestroyed(); @@ -142,8 +148,8 @@ public void Clear() public override void PostExposeData() { base.PostExposeData(); - Scribe_Values.Look(ref this.authorNameInt, "authorName", null, false); - Scribe_Values.Look(ref this.titleInt, "title", null, false); + Scribe_Values.Look(ref this.authorNameInt, "authorName", (string)null, false); + Scribe_Values.Look(ref this.titleInt, "title", (string)null, false); Scribe_Deep.Look(ref this.taleRef, "taleRef", new object[0]); } @@ -151,18 +157,11 @@ public override string CompInspectStringExtra() { if (!this.Active) { - return null; + return (string)null; } - string text = "Author".Translate() + ": " + this.AuthorName; - string text2 = text; - return string.Concat(new string[] - { - text2, - "\n", - "Title".Translate(), - ": ", - this.Title - }); + string text; + string text2 = text = "Author".Translate() + ": " + this.AuthorName; + return text + "\n" + "Title".Translate() + ": " + this.Title; } public override void PostDestroy(DestroyMode mode, Map previousMap) @@ -179,26 +178,30 @@ public override string GetDescriptionPart() { if (!this.Active) { - return null; + return (string)null; } - string str = string.Empty; - str += this.Title; - str += "\n\n"; - str += this.GenerateImageDescription(); - str += "\n\n"; - return str + "Author".Translate() + ": " + this.AuthorName; + string empty = string.Empty; + empty += this.Title; + empty += "\n\n"; + empty += this.GenerateImageDescription(); + empty += "\n\n"; + return empty + "Author".Translate() + ": " + this.AuthorName; } public override bool AllowStackWith(Thing other) { - return !this.Active; + if (this.Active) + { + return false; + } + return true; } public string GenerateImageDescription() { if (this.taleRef == null) { - Log.Error("Did CompArt.GenerateImageDescription without initializing art: " + this.parent); + Log.Error("Did CompArt.GenerateImageDescription without initializing art: " + base.parent); this.InitializeArt(ArtGenerationContext.Outsider); } return this.taleRef.GenerateText(TextGenerationPurpose.ArtDescription, this.Props.descriptionMaker.Rules); @@ -208,7 +211,7 @@ private string GenerateTitle() { if (this.taleRef == null) { - Log.Error("Did CompArt.GenerateTitle without initializing art: " + this.parent); + Log.Error("Did CompArt.GenerateTitle without initializing art: " + base.parent); this.InitializeArt(ArtGenerationContext.Outsider); } return GenText.CapitalizeAsTitle(this.taleRef.GenerateText(TextGenerationPurpose.ArtName, this.Props.nameMaker.Rules)); diff --git a/Assembly-CSharp/RimWorld/CompBreakdownable.cs b/Assembly-CSharp/RimWorld/CompBreakdownable.cs index 5c4adfd8e..61f45ce6d 100644 --- a/Assembly-CSharp/RimWorld/CompBreakdownable.cs +++ b/Assembly-CSharp/RimWorld/CompBreakdownable.cs @@ -1,4 +1,3 @@ -using System; using Verse; namespace RimWorld @@ -31,15 +30,15 @@ public override void PostDraw() { if (this.brokenDownInt) { - this.parent.Map.overlayDrawer.DrawOverlay(this.parent, OverlayTypes.BrokenDown); + base.parent.Map.overlayDrawer.DrawOverlay(base.parent, OverlayTypes.BrokenDown); } } public override void PostSpawnSetup(bool respawningAfterLoad) { base.PostSpawnSetup(respawningAfterLoad); - this.powerComp = this.parent.GetComp(); - this.parent.Map.GetComponent().Register(this); + this.powerComp = base.parent.GetComp(); + base.parent.Map.GetComponent().Register(this); } public override void PostDeSpawn(Map map) @@ -64,27 +63,21 @@ protected bool CanBreakdownNow() public void Notify_Repaired() { this.brokenDownInt = false; - this.parent.Map.GetComponent().Notify_Repaired(this.parent); - if (this.parent is Building_PowerSwitch) + base.parent.Map.GetComponent().Notify_Repaired(base.parent); + if (base.parent is Building_PowerSwitch) { - this.parent.Map.powerNetManager.Notfiy_TransmitterTransmitsPowerNowChanged(this.parent.GetComp()); + base.parent.Map.powerNetManager.Notfiy_TransmitterTransmitsPowerNowChanged(base.parent.GetComp()); } } public void DoBreakdown() { this.brokenDownInt = true; - this.parent.BroadcastCompSignal("Breakdown"); - this.parent.Map.GetComponent().Notify_BrokenDown(this.parent); - if (this.parent.Faction == Faction.OfPlayer) + base.parent.BroadcastCompSignal("Breakdown"); + base.parent.Map.GetComponent().Notify_BrokenDown(base.parent); + if (base.parent.Faction == Faction.OfPlayer) { - Find.LetterStack.ReceiveLetter("LetterLabelBuildingBrokenDown".Translate(new object[] - { - this.parent.LabelShort - }), "LetterBuildingBrokenDown".Translate(new object[] - { - this.parent.LabelShort - }), LetterDefOf.BadNonUrgent, this.parent, null); + Find.LetterStack.ReceiveLetter("LetterLabelBuildingBrokenDown".Translate(base.parent.LabelShort), "LetterBuildingBrokenDown".Translate(base.parent.LabelShort), LetterDefOf.BadNonUrgent, (Thing)base.parent, (string)null); } } @@ -94,7 +87,7 @@ public override string CompInspectStringExtra() { return "BrokenDown".Translate(); } - return null; + return (string)null; } } } diff --git a/Assembly-CSharp/RimWorld/CompDeepDrill.cs b/Assembly-CSharp/RimWorld/CompDeepDrill.cs index 2fb4625e3..26a05ce30 100644 --- a/Assembly-CSharp/RimWorld/CompDeepDrill.cs +++ b/Assembly-CSharp/RimWorld/CompDeepDrill.cs @@ -1,4 +1,3 @@ -using System; using UnityEngine; using Verse; @@ -18,13 +17,13 @@ public float ProgressToNextLumpPercent { get { - return this.lumpProgress / 14000f; + return (float)(this.lumpProgress / 14000.0); } } public override void PostSpawnSetup(bool respawningAfterLoad) { - this.powerComp = this.parent.TryGetComp(); + this.powerComp = base.parent.TryGetComp(); } public override void PostExposeData() @@ -37,8 +36,8 @@ public void DrillWorkDone(Pawn driller) { float statValue = driller.GetStatValue(StatDefOf.MiningSpeed, true); this.lumpProgress += statValue; - this.lumpYieldPct += statValue * driller.GetStatValue(StatDefOf.MiningYield, true) / 14000f; - if (this.lumpProgress > 14000f) + this.lumpYieldPct += (float)(statValue * driller.GetStatValue(StatDefOf.MiningYield, true) / 14000.0); + if (this.lumpProgress > 14000.0) { this.TryProduceLump(this.lumpYieldPct); this.lumpProgress = 0f; @@ -48,22 +47,17 @@ public void DrillWorkDone(Pawn driller) private void TryProduceLump(float yieldPct) { - ThingDef thingDef; - int num; - IntVec3 c; + ThingDef thingDef = default(ThingDef); + int num = default(int); + IntVec3 c = default(IntVec3); if (this.TryGetNextResource(out thingDef, out num, out c)) { - int num2 = Mathf.Min(new int[] - { - num, - thingDef.deepCountPerCell / 2, - thingDef.stackLimit - }); - this.parent.Map.deepResourceGrid.SetAt(c, thingDef, num - num2); + int num2 = Mathf.Min(num, thingDef.deepCountPerCell / 2, thingDef.stackLimit); + base.parent.Map.deepResourceGrid.SetAt(c, thingDef, num - num2); int stackCount = Mathf.Max(1, GenMath.RoundRandom((float)num2 * yieldPct)); Thing thing = ThingMaker.MakeThing(thingDef, null); thing.stackCount = stackCount; - GenPlace.TryPlaceThing(thing, this.parent.InteractionCell, this.parent.Map, ThingPlaceMode.Near, null); + GenPlace.TryPlaceThing(thing, base.parent.InteractionCell, base.parent.Map, ThingPlaceMode.Near, null); } else { @@ -75,14 +69,14 @@ public bool TryGetNextResource(out ThingDef resDef, out int countPresent, out In { for (int i = 0; i < 9; i++) { - IntVec3 intVec = this.parent.Position + GenRadial.RadialPattern[i]; - if (intVec.InBounds(this.parent.Map)) + IntVec3 intVec = base.parent.Position + GenRadial.RadialPattern[i]; + if (intVec.InBounds(base.parent.Map)) { - ThingDef thingDef = this.parent.Map.deepResourceGrid.ThingDefAt(intVec); + ThingDef thingDef = base.parent.Map.deepResourceGrid.ThingDefAt(intVec); if (thingDef != null) { resDef = thingDef; - countPresent = this.parent.Map.deepResourceGrid.CountAt(intVec); + countPresent = base.parent.Map.deepResourceGrid.CountAt(intVec); cell = intVec; return true; } @@ -96,34 +90,33 @@ public bool TryGetNextResource(out ThingDef resDef, out int countPresent, out In public bool CanDrillNow() { - return (this.powerComp == null || this.powerComp.PowerOn) && this.ResourcesPresent(); + if (this.powerComp != null && !this.powerComp.PowerOn) + { + return false; + } + if (!this.ResourcesPresent()) + { + return false; + } + return true; } public bool ResourcesPresent() { - ThingDef thingDef; - int num; - IntVec3 intVec; + ThingDef thingDef = default(ThingDef); + int num = default(int); + IntVec3 intVec = default(IntVec3); return this.TryGetNextResource(out thingDef, out num, out intVec); } public override string CompInspectStringExtra() { - ThingDef thingDef; - int num; - IntVec3 intVec; + ThingDef thingDef = default(ThingDef); + int num = default(int); + IntVec3 intVec = default(IntVec3); if (this.TryGetNextResource(out thingDef, out num, out intVec)) { - return string.Concat(new string[] - { - "ResourceBelow".Translate(), - ": ", - thingDef.label, - "\n", - "ProgressToNextLump".Translate(), - ": ", - this.ProgressToNextLumpPercent.ToStringPercent("F0") - }); + return "ResourceBelow".Translate() + ": " + thingDef.label + "\n" + "ProgressToNextLump".Translate() + ": " + this.ProgressToNextLumpPercent.ToStringPercent("F0"); } return "ResourceBelow".Translate() + ": " + "NothingLower".Translate(); } diff --git a/Assembly-CSharp/RimWorld/CompDeepScanner.cs b/Assembly-CSharp/RimWorld/CompDeepScanner.cs index 11831c387..31b0ca083 100644 --- a/Assembly-CSharp/RimWorld/CompDeepScanner.cs +++ b/Assembly-CSharp/RimWorld/CompDeepScanner.cs @@ -1,4 +1,3 @@ -using System; using Verse; namespace RimWorld @@ -10,14 +9,14 @@ public class CompDeepScanner : ThingComp public override void PostSpawnSetup(bool respawningAfterLoad) { base.PostSpawnSetup(respawningAfterLoad); - this.powerComp = this.parent.GetComp(); + this.powerComp = base.parent.GetComp(); } public override void PostDrawExtraSelectionOverlays() { if (this.powerComp.PowerOn) { - this.parent.Map.deepResourceGrid.MarkForDraw(); + base.parent.Map.deepResourceGrid.MarkForDraw(); } } } diff --git a/Assembly-CSharp/RimWorld/CompDrug.cs b/Assembly-CSharp/RimWorld/CompDrug.cs index 5f1724187..a3a944aca 100644 --- a/Assembly-CSharp/RimWorld/CompDrug.cs +++ b/Assembly-CSharp/RimWorld/CompDrug.cs @@ -9,7 +9,7 @@ public CompProperties_Drug Props { get { - return (CompProperties_Drug)this.props; + return (CompProperties_Drug)base.props; } } @@ -20,30 +20,23 @@ public override void PostIngested(Pawn ingester) HediffDef addictionHediffDef = this.Props.chemical.addictionHediff; Hediff_Addiction hediff_Addiction = AddictionUtility.FindAddictionHediff(ingester, this.Props.chemical); Hediff hediff = AddictionUtility.FindToleranceHediff(ingester, this.Props.chemical); - float num = (hediff == null) ? 0f : hediff.Severity; + float num = (float)((hediff == null) ? 0.0 : hediff.Severity); if (hediff_Addiction != null) { hediff_Addiction.Severity += this.Props.existingAddictionSeverityOffset; } else if (Rand.Value < this.Props.addictiveness && num >= this.Props.minToleranceToAddict) { - ingester.health.AddHediff(addictionHediffDef, null, null); + ingester.health.AddHediff(addictionHediffDef, null, default(DamageInfo?)); if (PawnUtility.ShouldSendNotificationAbout(ingester)) { - Find.LetterStack.ReceiveLetter("LetterLabelNewlyAddicted".Translate(new object[] - { - this.Props.chemical.label - }).CapitalizeFirst(), "LetterNewlyAddicted".Translate(new object[] - { - ingester.LabelShort, - this.Props.chemical.label - }).AdjustedFor(ingester).CapitalizeFirst(), LetterDefOf.BadNonUrgent, ingester, null); + Find.LetterStack.ReceiveLetter("LetterLabelNewlyAddicted".Translate(this.Props.chemical.label).CapitalizeFirst(), "LetterNewlyAddicted".Translate(ingester.LabelShort, this.Props.chemical.label).AdjustedFor(ingester).CapitalizeFirst(), LetterDefOf.BadNonUrgent, (Thing)ingester, (string)null); } AddictionUtility.CheckDrugAddictionTeachOpportunity(ingester); } if (addictionHediffDef.causesNeed != null) { - Need need = ingester.needs.AllNeeds.Find((Need x) => x.def == addictionHediffDef.causesNeed); + Need need = ingester.needs.AllNeeds.Find((Predicate)((Need x) => x.def == addictionHediffDef.causesNeed)); if (need != null) { float needLevelOffset = this.Props.needLevelOffset; @@ -52,24 +45,20 @@ public override void PostIngested(Pawn ingester) } } Hediff firstHediffOfDef = ingester.health.hediffSet.GetFirstHediffOfDef(HediffDefOf.DrugOverdose, false); - float num2 = (firstHediffOfDef == null) ? 0f : firstHediffOfDef.Severity; - if (num2 < 0.9f && Rand.Value < this.Props.largeOverdoseChance) + float num2 = (float)((firstHediffOfDef == null) ? 0.0 : firstHediffOfDef.Severity); + if (num2 < 0.89999997615814209 && Rand.Value < this.Props.largeOverdoseChance) { float num3 = Rand.Range(0.85f, 0.99f); HealthUtility.AdjustSeverity(ingester, HediffDefOf.DrugOverdose, num3 - num2); if (ingester.Faction == Faction.OfPlayer) { - Messages.Message("MessageAccidentalOverdose".Translate(new object[] - { - ingester.LabelIndefinite(), - this.parent.LabelNoCount - }).CapitalizeFirst(), MessageSound.Negative); + Messages.Message("MessageAccidentalOverdose".Translate(ingester.LabelIndefinite(), base.parent.LabelNoCount).CapitalizeFirst(), MessageSound.Negative); } } else { float num4 = this.Props.overdoseSeverityOffset.RandomInRange / ingester.BodySize; - if (num4 > 0f) + if (num4 > 0.0) { HealthUtility.AdjustSeverity(ingester, HediffDefOf.DrugOverdose, num4); } @@ -81,7 +70,7 @@ public override void PostIngested(Pawn ingester) } if (ingester.drugs != null) { - ingester.drugs.Notify_DrugIngested(this.parent); + ingester.drugs.Notify_DrugIngested(base.parent); } } } diff --git a/Assembly-CSharp/RimWorld/CompEggLayer.cs b/Assembly-CSharp/RimWorld/CompEggLayer.cs index 733fa59eb..50ca9bfd8 100644 --- a/Assembly-CSharp/RimWorld/CompEggLayer.cs +++ b/Assembly-CSharp/RimWorld/CompEggLayer.cs @@ -1,4 +1,3 @@ -using System; using UnityEngine; using Verse; @@ -16,8 +15,16 @@ private bool Active { get { - Pawn pawn = this.parent as Pawn; - return (!this.Props.eggLayFemaleOnly || pawn == null || pawn.gender == Gender.Female) && (pawn == null || pawn.ageTracker.CurLifeStage.milkable); + Pawn pawn = base.parent as Pawn; + if (this.Props.eggLayFemaleOnly && pawn != null && pawn.gender != Gender.Female) + { + return false; + } + if (pawn != null && !pawn.ageTracker.CurLifeStage.milkable) + { + return false; + } + return true; } } @@ -25,7 +32,11 @@ public bool CanLayNow { get { - return this.Active && this.eggProgress >= 1f; + if (!this.Active) + { + return false; + } + return this.eggProgress >= 1.0; } } @@ -49,7 +60,7 @@ public CompProperties_EggLayer Props { get { - return (CompProperties_EggLayer)this.props; + return (CompProperties_EggLayer)base.props; } } @@ -65,14 +76,14 @@ public override void CompTick() { if (this.Active) { - float num = 1f / (this.Props.eggLayIntervalDays * 60000f); - Pawn pawn = this.parent as Pawn; + float num = (float)(1.0 / (this.Props.eggLayIntervalDays * 60000.0)); + Pawn pawn = base.parent as Pawn; if (pawn != null) { num *= PawnUtility.BodyResourceGrowthSpeed(pawn); } this.eggProgress += num; - if (this.eggProgress > 1f) + if (this.eggProgress > 1.0) { this.eggProgress = 1f; } @@ -93,7 +104,7 @@ public virtual Thing ProduceEgg() { if (!this.Active) { - Log.Error("LayEgg while not Active: " + this.parent); + Log.Error("LayEgg while not Active: " + base.parent); } this.eggProgress = 0f; int randomInRange = this.Props.eggCountRange.RandomInRange; @@ -115,8 +126,8 @@ public virtual Thing ProduceEgg() CompHatcher compHatcher = thing.TryGetComp(); if (compHatcher != null) { - compHatcher.hatcheeFaction = this.parent.Faction; - Pawn pawn = this.parent as Pawn; + compHatcher.hatcheeFaction = base.parent.Faction; + Pawn pawn = base.parent as Pawn; if (pawn != null) { compHatcher.hatcheeParent = pawn; @@ -133,7 +144,7 @@ public override string CompInspectStringExtra() { if (!this.Active) { - return null; + return (string)null; } string text = "EggProgress".Translate() + ": " + this.eggProgress.ToStringPercent(); if (this.fertilizationCount > 0) diff --git a/Assembly-CSharp/RimWorld/CompExplosive.cs b/Assembly-CSharp/RimWorld/CompExplosive.cs index f4a48082d..6de415000 100644 --- a/Assembly-CSharp/RimWorld/CompExplosive.cs +++ b/Assembly-CSharp/RimWorld/CompExplosive.cs @@ -1,4 +1,3 @@ -using System; using UnityEngine; using Verse; using Verse.Sound; @@ -21,7 +20,7 @@ public CompProperties_Explosive Props { get { - return (CompProperties_Explosive)this.props; + return (CompProperties_Explosive)base.props; } } @@ -29,7 +28,7 @@ protected int StartWickThreshold { get { - return Mathf.RoundToInt(this.Props.startWickHitPointsPercent * (float)this.parent.MaxHitPoints); + return Mathf.RoundToInt(this.Props.startWickHitPointsPercent * (float)base.parent.MaxHitPoints); } } @@ -37,12 +36,12 @@ private bool CanEverExplodeFromDamage { get { - if (this.Props.chanceNeverExplodeFromDamage < 1E-05f) + if (this.Props.chanceNeverExplodeFromDamage < 9.9999997473787516E-06) { return true; } Rand.PushState(); - Rand.Seed = this.parent.thingIDNumber.GetHashCode(); + Rand.Seed = base.parent.thingIDNumber.GetHashCode(); bool result = Rand.Value < this.Props.chanceNeverExplodeFromDamage; Rand.PopState(); return result; @@ -73,15 +72,15 @@ public override void CompTick() this.wickTicksLeft--; if (this.wickTicksLeft <= 0) { - this.Detonate(this.parent.MapHeld); + this.Detonate(base.parent.MapHeld); } } } private void StartWickSustainer() { - SoundDefOf.MetalHitImportant.PlayOneShot(new TargetInfo(this.parent.Position, this.parent.Map, false)); - SoundInfo info = SoundInfo.InMap(this.parent, MaintenanceType.PerTick); + SoundDefOf.MetalHitImportant.PlayOneShot(new TargetInfo(base.parent.Position, base.parent.Map, false)); + SoundInfo info = SoundInfo.InMap((Thing)base.parent, MaintenanceType.PerTick); this.wickSoundSustainer = SoundDefOf.HissSmall.TrySpawnSustainer(info); } @@ -89,7 +88,7 @@ public override void PostDraw() { if (this.wickStarted) { - this.parent.Map.overlayDrawer.DrawOverlay(this.parent, OverlayTypes.BurningWick); + base.parent.Map.overlayDrawer.DrawOverlay(base.parent, OverlayTypes.BurningWick); } } @@ -98,11 +97,11 @@ public override void PostPreApplyDamage(DamageInfo dinfo, out bool absorbed) absorbed = false; if (this.CanEverExplodeFromDamage) { - if (dinfo.Def.externalViolence && dinfo.Amount >= this.parent.HitPoints) + if (dinfo.Def.externalViolence && dinfo.Amount >= base.parent.HitPoints) { - if (this.parent.MapHeld != null) + if (base.parent.MapHeld != null) { - this.Detonate(this.parent.MapHeld); + this.Detonate(base.parent.MapHeld); absorbed = true; } } @@ -115,17 +114,13 @@ public override void PostPreApplyDamage(DamageInfo dinfo, out bool absorbed) public override void PostPostApplyDamage(DamageInfo dinfo, float totalDamageDealt) { - if (!this.CanEverExplodeFromDamage) - { - return; - } - if (!this.parent.Destroyed) + if (this.CanEverExplodeFromDamage && !base.parent.Destroyed) { if (this.wickStarted && dinfo.Def == DamageDefOf.Stun) { this.StopWick(); } - else if (!this.wickStarted && this.parent.HitPoints <= this.StartWickThreshold && dinfo.Def.externalViolence) + else if (!this.wickStarted && base.parent.HitPoints <= this.StartWickThreshold && dinfo.Def.externalViolence) { this.StartWick(dinfo.Instigator); } @@ -134,15 +129,14 @@ public override void PostPostApplyDamage(DamageInfo dinfo, float totalDamageDeal public void StartWick(Thing instigator = null) { - if (this.wickStarted) + if (!this.wickStarted) { - return; + this.instigator = instigator; + this.wickStarted = true; + this.wickTicksLeft = this.Props.wickTicks.RandomInRange; + this.StartWickSustainer(); + GenExplosion.NotifyNearbyPawnsOfDangerousExplosive(base.parent, this.Props.explosiveDamageType, null); } - this.instigator = instigator; - this.wickStarted = true; - this.wickTicksLeft = this.Props.wickTicks.RandomInRange; - this.StartWickSustainer(); - GenExplosion.NotifyNearbyPawnsOfDangerousExplosive(this.parent, this.Props.explosiveDamageType, null); } public void StopWick() @@ -153,40 +147,40 @@ public void StopWick() protected void Detonate(Map map) { - if (this.detonated) - { - return; - } - this.detonated = true; - if (!this.parent.SpawnedOrAnyParentSpawned) - { - return; - } - if (!this.parent.Destroyed) - { - this.parent.Kill(null); - } - if (map == null) - { - Log.Warning("Tried to detonate CompExplosive in a null map."); - return; - } - CompProperties_Explosive props = this.Props; - float num = props.explosiveRadius; - if (this.parent.stackCount > 1 && props.explosiveExpandPerStackcount > 0f) + if (!this.detonated) { - num += Mathf.Sqrt((float)(this.parent.stackCount - 1) * props.explosiveExpandPerStackcount); - } - if (props.explosionEffect != null) - { - Effecter effecter = props.explosionEffect.Spawn(); - effecter.Trigger(new TargetInfo(this.parent.PositionHeld, map, false), new TargetInfo(this.parent.PositionHeld, map, false)); - effecter.Cleanup(); + this.detonated = true; + if (base.parent.SpawnedOrAnyParentSpawned) + { + if (!base.parent.Destroyed) + { + base.parent.Kill(default(DamageInfo?)); + } + if (map == null) + { + Log.Warning("Tried to detonate CompExplosive in a null map."); + } + else + { + CompProperties_Explosive props = this.Props; + float num = props.explosiveRadius; + if (base.parent.stackCount > 1 && props.explosiveExpandPerStackcount > 0.0) + { + num += Mathf.Sqrt((float)(base.parent.stackCount - 1) * props.explosiveExpandPerStackcount); + } + if (props.explosionEffect != null) + { + Effecter effecter = props.explosionEffect.Spawn(); + effecter.Trigger(new TargetInfo(base.parent.PositionHeld, map, false), new TargetInfo(base.parent.PositionHeld, map, false)); + effecter.Cleanup(); + } + ThingDef postExplosionSpawnThingDef = props.postExplosionSpawnThingDef; + float postExplosionSpawnChance = props.postExplosionSpawnChance; + int postExplosionSpawnThingCount = props.postExplosionSpawnThingCount; + GenExplosion.DoExplosion(base.parent.PositionHeld, map, num, props.explosiveDamageType, this.instigator ?? base.parent, null, null, null, postExplosionSpawnThingDef, postExplosionSpawnChance, postExplosionSpawnThingCount, props.applyDamageToExplosionCellsNeighbors, props.preExplosionSpawnThingDef, props.preExplosionSpawnChance, props.preExplosionSpawnThingCount); + } + } } - ThingDef postExplosionSpawnThingDef = props.postExplosionSpawnThingDef; - float postExplosionSpawnChance = props.postExplosionSpawnChance; - int postExplosionSpawnThingCount = props.postExplosionSpawnThingCount; - GenExplosion.DoExplosion(this.parent.PositionHeld, map, num, props.explosiveDamageType, this.instigator ?? this.parent, null, null, null, postExplosionSpawnThingDef, postExplosionSpawnChance, postExplosionSpawnThingCount, props.applyDamageToExplosionCellsNeighbors, props.preExplosionSpawnThingDef, props.preExplosionSpawnChance, props.preExplosionSpawnThingCount); } } } diff --git a/Assembly-CSharp/RimWorld/CompFacility.cs b/Assembly-CSharp/RimWorld/CompFacility.cs index 7bbb69aa6..21f4d9402 100644 --- a/Assembly-CSharp/RimWorld/CompFacility.cs +++ b/Assembly-CSharp/RimWorld/CompFacility.cs @@ -16,8 +16,12 @@ public bool CanBeActive { get { - CompPowerTrader compPowerTrader = this.parent.TryGetComp(); - return compPowerTrader == null || compPowerTrader.PowerOn; + CompPowerTrader compPowerTrader = base.parent.TryGetComp(); + if (compPowerTrader != null && !compPowerTrader.PowerOn) + { + return false; + } + return true; } } @@ -25,7 +29,7 @@ public CompProperties_Facility Props { get { - return (CompProperties_Facility)this.props; + return (CompProperties_Facility)base.props; } } @@ -35,15 +39,24 @@ public static void DrawLinesToPotentialThingsToLinkTo(ThingDef myDef, IntVec3 my Vector3 a = Gen.TrueCenter(myPos, myRot, myDef.size, myDef.Altitude); for (int i = 0; i < compProperties.linkableBuildings.Count; i++) { - foreach (Thing current in map.listerThings.ThingsOfDef(compProperties.linkableBuildings[i])) + List.Enumerator enumerator = map.listerThings.ThingsOfDef(compProperties.linkableBuildings[i]).GetEnumerator(); + try { - CompAffectedByFacilities compAffectedByFacilities = current.TryGetComp(); - if (compAffectedByFacilities != null && compAffectedByFacilities.CanPotentiallyLinkTo(myDef, myPos, myRot)) + while (enumerator.MoveNext()) { - GenDraw.DrawLineBetween(a, current.TrueCenter()); - compAffectedByFacilities.DrawRedLineToPotentiallySupplantedFacility(myDef, myPos, myRot); + Thing current = enumerator.Current; + CompAffectedByFacilities compAffectedByFacilities = current.TryGetComp(); + if (compAffectedByFacilities != null && compAffectedByFacilities.CanPotentiallyLinkTo(myDef, myPos, myRot)) + { + GenDraw.DrawLineBetween(a, current.TrueCenter()); + compAffectedByFacilities.DrawRedLineToPotentiallySupplantedFacility(myDef, myPos, myRot); + } } } + finally + { + ((IDisposable)(object)enumerator).Dispose(); + } } } @@ -96,9 +109,18 @@ public override void PostDeSpawn(Map map) this.thingsToNotify.Add(this.linkedBuildings[i]); } this.UnlinkAll(); - foreach (Thing current in this.thingsToNotify) + HashSet.Enumerator enumerator = this.thingsToNotify.GetEnumerator(); + try + { + while (enumerator.MoveNext()) + { + Thing current = enumerator.Current; + current.TryGetComp().Notify_FacilityDespawned(); + } + } + finally { - current.TryGetComp().Notify_FacilityDespawned(); + ((IDisposable)(object)enumerator).Dispose(); } } @@ -107,13 +129,13 @@ public override void PostDrawExtraSelectionOverlays() for (int i = 0; i < this.linkedBuildings.Count; i++) { CompAffectedByFacilities compAffectedByFacilities = this.linkedBuildings[i].TryGetComp(); - if (compAffectedByFacilities.IsFacilityActive(this.parent)) + if (compAffectedByFacilities.IsFacilityActive(base.parent)) { - GenDraw.DrawLineBetween(this.parent.TrueCenter(), this.linkedBuildings[i].TrueCenter()); + GenDraw.DrawLineBetween(base.parent.TrueCenter(), this.linkedBuildings[i].TrueCenter()); } else { - GenDraw.DrawLineBetween(this.parent.TrueCenter(), this.linkedBuildings[i].TrueCenter(), CompAffectedByFacilities.InactiveFacilityLineMat); + GenDraw.DrawLineBetween(base.parent.TrueCenter(), this.linkedBuildings[i].TrueCenter(), CompAffectedByFacilities.InactiveFacilityLineMat); } } } @@ -123,7 +145,7 @@ public override string CompInspectStringExtra() CompProperties_Facility props = this.Props; if (props.statOffsets == null) { - return null; + return (string)null; } bool flag = this.AmIActiveForAnyone(); StringBuilder stringBuilder = new StringBuilder(); @@ -157,19 +179,27 @@ private void LinkToNearbyBuildings() { this.UnlinkAll(); CompProperties_Facility props = this.Props; - if (props.linkableBuildings == null) - { - return; - } - for (int i = 0; i < props.linkableBuildings.Count; i++) + if (props.linkableBuildings != null) { - foreach (Thing current in this.parent.Map.listerThings.ThingsOfDef(props.linkableBuildings[i])) + for (int i = 0; i < props.linkableBuildings.Count; i++) { - CompAffectedByFacilities compAffectedByFacilities = current.TryGetComp(); - if (compAffectedByFacilities != null && compAffectedByFacilities.CanLinkTo(this.parent)) + List.Enumerator enumerator = base.parent.Map.listerThings.ThingsOfDef(props.linkableBuildings[i]).GetEnumerator(); + try + { + while (enumerator.MoveNext()) + { + Thing current = enumerator.Current; + CompAffectedByFacilities compAffectedByFacilities = current.TryGetComp(); + if (compAffectedByFacilities != null && compAffectedByFacilities.CanLinkTo(base.parent)) + { + this.linkedBuildings.Add(current); + compAffectedByFacilities.Notify_NewLink(base.parent); + } + } + } + finally { - this.linkedBuildings.Add(current); - compAffectedByFacilities.Notify_NewLink(this.parent); + ((IDisposable)(object)enumerator).Dispose(); } } } @@ -180,7 +210,7 @@ private bool AmIActiveForAnyone() for (int i = 0; i < this.linkedBuildings.Count; i++) { CompAffectedByFacilities compAffectedByFacilities = this.linkedBuildings[i].TryGetComp(); - if (compAffectedByFacilities.IsFacilityActive(this.parent)) + if (compAffectedByFacilities.IsFacilityActive(base.parent)) { return true; } @@ -192,7 +222,7 @@ private void UnlinkAll() { for (int i = 0; i < this.linkedBuildings.Count; i++) { - this.linkedBuildings[i].TryGetComp().Notify_LinkRemoved(this.parent); + this.linkedBuildings[i].TryGetComp().Notify_LinkRemoved(base.parent); } this.linkedBuildings.Clear(); } diff --git a/Assembly-CSharp/RimWorld/CompFireOverlay.cs b/Assembly-CSharp/RimWorld/CompFireOverlay.cs index 58aa79a8f..9e3dffacc 100644 --- a/Assembly-CSharp/RimWorld/CompFireOverlay.cs +++ b/Assembly-CSharp/RimWorld/CompFireOverlay.cs @@ -1,4 +1,3 @@ -using System; using UnityEngine; using Verse; @@ -13,16 +12,16 @@ public CompProperties_FireOverlay Props { get { - return (CompProperties_FireOverlay)this.props; + return (CompProperties_FireOverlay)base.props; } } public override void PostDraw() { base.PostDraw(); - Vector3 drawPos = this.parent.DrawPos; + Vector3 drawPos = base.parent.DrawPos; drawPos.y += 0.046875f; - CompFireOverlay.FireGraphic.Draw(drawPos, Rot4.North, this.parent); + CompFireOverlay.FireGraphic.Draw(drawPos, Rot4.North, base.parent); } } } diff --git a/Assembly-CSharp/RimWorld/CompFlickable.cs b/Assembly-CSharp/RimWorld/CompFlickable.cs index f6625fad1..7aded3991 100644 --- a/Assembly-CSharp/RimWorld/CompFlickable.cs +++ b/Assembly-CSharp/RimWorld/CompFlickable.cs @@ -1,6 +1,5 @@ using System; using System.Collections.Generic; -using System.Diagnostics; using UnityEngine; using Verse; using Verse.Sound; @@ -27,7 +26,7 @@ private CompProperties_Flickable Props { get { - return (CompProperties_Flickable)this.props; + return (CompProperties_Flickable)base.props; } } @@ -35,7 +34,7 @@ private Texture2D CommandTex { get { - if (this.cachedCommandTex == null) + if ((UnityEngine.Object)this.cachedCommandTex == (UnityEngine.Object)null) { this.cachedCommandTex = ContentFinder.Get(this.Props.commandTexture, true); } @@ -51,22 +50,21 @@ public bool SwitchIsOn } set { - if (this.switchOnInt == value) + if (this.switchOnInt != value) { - return; - } - this.switchOnInt = value; - if (this.switchOnInt) - { - this.parent.BroadcastCompSignal("FlickedOn"); - } - else - { - this.parent.BroadcastCompSignal("FlickedOff"); - } - if (this.parent.Spawned) - { - this.parent.Map.mapDrawer.MapMeshDirty(this.parent.Position, MapMeshFlag.Things | MapMeshFlag.Buildings); + this.switchOnInt = value; + if (this.switchOnInt) + { + base.parent.BroadcastCompSignal("FlickedOn"); + } + else + { + base.parent.BroadcastCompSignal("FlickedOff"); + } + if (base.parent.Spawned) + { + base.parent.Map.mapDrawer.MapMeshDirty(base.parent.Position, MapMeshFlag.Things | MapMeshFlag.Buildings); + } } } } @@ -77,11 +75,11 @@ public Graphic CurrentGraphic { if (this.SwitchIsOn) { - return this.parent.DefaultGraphic; + return base.parent.DefaultGraphic; } if (this.offGraphic == null) { - this.offGraphic = GraphicDatabase.Get(this.parent.def.graphicData.graphicClass, this.parent.def.graphicData.texPath + "_Off", ShaderDatabase.ShaderFromType(this.parent.def.graphicData.shaderType), this.parent.def.graphicData.drawSize, this.parent.DrawColor, this.parent.DrawColorTwo); + this.offGraphic = GraphicDatabase.Get(base.parent.def.graphicData.graphicClass, base.parent.def.graphicData.texPath + "_Off", ShaderDatabase.ShaderFromType(base.parent.def.graphicData.shaderType), base.parent.def.graphicData.drawSize, base.parent.DrawColor, base.parent.DrawColorTwo); } return this.offGraphic; } @@ -102,7 +100,7 @@ public bool WantsFlick() public void DoFlick() { this.SwitchIsOn = !this.SwitchIsOn; - SoundDefOf.FlickSwitch.PlayOneShot(new TargetInfo(this.parent.Position, this.parent.Map, false)); + SoundDefOf.FlickSwitch.PlayOneShot(new TargetInfo(base.parent.Position, base.parent.Map, false)); } public void ResetToOn() @@ -111,14 +109,28 @@ public void ResetToOn() this.wantSwitchOn = true; } - [DebuggerHidden] public override IEnumerable CompGetGizmosExtra() { - CompFlickable.c__IteratorB4 c__IteratorB = new CompFlickable.c__IteratorB4(); - c__IteratorB.<>f__this = this; - CompFlickable.c__IteratorB4 expr_0E = c__IteratorB; - expr_0E.$PC = -2; - return expr_0E; + foreach (Gizmo item in base.CompGetGizmosExtra()) + { + yield return item; + } + if (base.parent.Faction == Faction.OfPlayer) + { + yield return (Gizmo)new Command_Toggle + { + hotKey = KeyBindingDefOf.CommandTogglePower, + icon = this.CommandTex, + defaultLabel = this.Props.commandLabelKey.Translate(), + defaultDesc = this.Props.commandDescKey.Translate(), + isActive = (Func)(() => ((_003CCompGetGizmosExtra_003Ec__IteratorB4)/*Error near IL_013b: stateMachine*/)._003C_003Ef__this.wantSwitchOn), + toggleAction = (Action)delegate + { + ((_003CCompGetGizmosExtra_003Ec__IteratorB4)/*Error near IL_0152: stateMachine*/)._003C_003Ef__this.wantSwitchOn = !((_003CCompGetGizmosExtra_003Ec__IteratorB4)/*Error near IL_0152: stateMachine*/)._003C_003Ef__this.wantSwitchOn; + FlickUtility.UpdateFlickDesignation(((_003CCompGetGizmosExtra_003Ec__IteratorB4)/*Error near IL_0152: stateMachine*/)._003C_003Ef__this.parent); + } + }; + } } } } diff --git a/Assembly-CSharp/RimWorld/CompFoodPoisonable.cs b/Assembly-CSharp/RimWorld/CompFoodPoisonable.cs index 4b9a5d58c..f26a99aa2 100644 --- a/Assembly-CSharp/RimWorld/CompFoodPoisonable.cs +++ b/Assembly-CSharp/RimWorld/CompFoodPoisonable.cs @@ -1,4 +1,3 @@ -using System; using UnityEngine; using Verse; @@ -37,14 +36,14 @@ public override void PreAbsorbStack(Thing otherStack, int count) { base.PreAbsorbStack(otherStack, count); CompFoodPoisonable compFoodPoisonable = otherStack.TryGetComp(); - this.poisonPct = GenMath.WeightedAverage(this.poisonPct, (float)this.parent.stackCount, compFoodPoisonable.poisonPct, (float)count); + this.poisonPct = GenMath.WeightedAverage(this.poisonPct, (float)base.parent.stackCount, compFoodPoisonable.poisonPct, (float)count); } public override void PostIngested(Pawn ingester) { if (Rand.Value < this.poisonPct) { - FoodUtility.AddFoodPoisoningHediff(ingester, this.parent); + FoodUtility.AddFoodPoisoningHediff(ingester, base.parent); } } } diff --git a/Assembly-CSharp/RimWorld/CompFoodPoisoningChance.cs b/Assembly-CSharp/RimWorld/CompFoodPoisoningChance.cs index 2998baf4c..9f2a383a0 100644 --- a/Assembly-CSharp/RimWorld/CompFoodPoisoningChance.cs +++ b/Assembly-CSharp/RimWorld/CompFoodPoisoningChance.cs @@ -1,4 +1,3 @@ -using System; using Verse; namespace RimWorld @@ -9,19 +8,17 @@ private CompProperties_FoodPoisoningChance Props { get { - return (CompProperties_FoodPoisoningChance)this.props; + return (CompProperties_FoodPoisoningChance)base.props; } } public override void PostIngested(Pawn ingester) { if (this.Props.humanlikeOnly && !ingester.RaceProps.Humanlike) - { return; - } if (Rand.Value < this.Props.chance) { - FoodUtility.AddFoodPoisoningHediff(ingester, this.parent); + FoodUtility.AddFoodPoisoningHediff(ingester, base.parent); } } } diff --git a/Assembly-CSharp/RimWorld/CompForbiddable.cs b/Assembly-CSharp/RimWorld/CompForbiddable.cs index f2492c8d1..fa350fc2c 100644 --- a/Assembly-CSharp/RimWorld/CompForbiddable.cs +++ b/Assembly-CSharp/RimWorld/CompForbiddable.cs @@ -1,6 +1,5 @@ using System; using System.Collections.Generic; -using System.Diagnostics; using Verse; namespace RimWorld @@ -17,24 +16,23 @@ public bool Forbidden } set { - if (value == this.forbiddenInt) + if (value != this.forbiddenInt) { - return; - } - this.forbiddenInt = value; - if (this.parent.Spawned) - { - if (this.forbiddenInt) - { - this.parent.Map.listerHaulables.Notify_Forbidden(this.parent); - } - else + this.forbiddenInt = value; + if (base.parent.Spawned) { - this.parent.Map.listerHaulables.Notify_Unforbidden(this.parent); - } - if (this.parent is Building_Door) - { - this.parent.Map.reachability.ClearCache(); + if (this.forbiddenInt) + { + base.parent.Map.listerHaulables.Notify_Forbidden(base.parent); + } + else + { + base.parent.Map.listerHaulables.Notify_Unforbidden(base.parent); + } + if (base.parent is Building_Door) + { + base.parent.Map.reachability.ClearCache(); + } } } } @@ -49,24 +47,24 @@ public override void PostDraw() { if (this.forbiddenInt) { - if (this.parent is Blueprint || this.parent is Frame) + if (base.parent is Blueprint || base.parent is Frame) { - if (this.parent.def.size.x > 1 || this.parent.def.size.z > 1) + if (base.parent.def.size.x > 1 || base.parent.def.size.z > 1) { - this.parent.Map.overlayDrawer.DrawOverlay(this.parent, OverlayTypes.ForbiddenBig); + base.parent.Map.overlayDrawer.DrawOverlay(base.parent, OverlayTypes.ForbiddenBig); } else { - this.parent.Map.overlayDrawer.DrawOverlay(this.parent, OverlayTypes.Forbidden); + base.parent.Map.overlayDrawer.DrawOverlay(base.parent, OverlayTypes.Forbidden); } } - else if (this.parent.def.category == ThingCategory.Building) + else if (base.parent.def.category == ThingCategory.Building) { - this.parent.Map.overlayDrawer.DrawOverlay(this.parent, OverlayTypes.ForbiddenBig); + base.parent.Map.overlayDrawer.DrawOverlay(base.parent, OverlayTypes.ForbiddenBig); } else { - this.parent.Map.overlayDrawer.DrawOverlay(this.parent, OverlayTypes.Forbidden); + base.parent.Map.overlayDrawer.DrawOverlay(base.parent, OverlayTypes.Forbidden); } } } @@ -76,14 +74,44 @@ public override void PostSplitOff(Thing piece) piece.SetForbidden(this.forbiddenInt, true); } - [DebuggerHidden] public override IEnumerable CompGetGizmosExtra() { - CompForbiddable.c__Iterator164 c__Iterator = new CompForbiddable.c__Iterator164(); - c__Iterator.<>f__this = this; - CompForbiddable.c__Iterator164 expr_0E = c__Iterator; - expr_0E.$PC = -2; - return expr_0E; + if (base.parent is Building && base.parent.Faction != Faction.OfPlayer) + yield break; + Command_Toggle com = new Command_Toggle + { + hotKey = KeyBindingDefOf.CommandItemForbid, + icon = TexCommand.Forbidden, + isActive = (Func)(() => !((_003CCompGetGizmosExtra_003Ec__Iterator164)/*Error near IL_0086: stateMachine*/)._003C_003Ef__this.forbiddenInt), + defaultLabel = "CommandForbid".Translate() + }; + if (this.forbiddenInt) + { + com.defaultDesc = "CommandForbiddenDesc".Translate(); + } + else + { + com.defaultDesc = "CommandNotForbiddenDesc".Translate(); + } + if (base.parent.def.IsDoor) + { + com.tutorTag = "ToggleForbidden-Door"; + com.toggleAction = (Action)delegate + { + ((_003CCompGetGizmosExtra_003Ec__Iterator164)/*Error near IL_011b: stateMachine*/)._003C_003Ef__this.Forbidden = !((_003CCompGetGizmosExtra_003Ec__Iterator164)/*Error near IL_011b: stateMachine*/)._003C_003Ef__this.Forbidden; + PlayerKnowledgeDatabase.KnowledgeDemonstrated(ConceptDefOf.ForbiddingDoors, KnowledgeAmount.SpecificInteraction); + }; + } + else + { + com.tutorTag = "ToggleForbidden"; + com.toggleAction = (Action)delegate + { + ((_003CCompGetGizmosExtra_003Ec__Iterator164)/*Error near IL_0147: stateMachine*/)._003C_003Ef__this.Forbidden = !((_003CCompGetGizmosExtra_003Ec__Iterator164)/*Error near IL_0147: stateMachine*/)._003C_003Ef__this.Forbidden; + PlayerKnowledgeDatabase.KnowledgeDemonstrated(ConceptDefOf.Forbidding, KnowledgeAmount.SpecificInteraction); + }; + } + yield return (Gizmo)com; } } } diff --git a/Assembly-CSharp/RimWorld/CompGatherSpot.cs b/Assembly-CSharp/RimWorld/CompGatherSpot.cs index 057d6a5fd..f90d81bec 100644 --- a/Assembly-CSharp/RimWorld/CompGatherSpot.cs +++ b/Assembly-CSharp/RimWorld/CompGatherSpot.cs @@ -1,6 +1,5 @@ using System; using System.Collections.Generic; -using System.Diagnostics; using Verse; namespace RimWorld @@ -17,20 +16,19 @@ public bool Active } set { - if (value == this.active) + if (value != this.active) { - return; - } - this.active = value; - if (this.parent.Spawned) - { - if (this.active) - { - this.parent.Map.gatherSpotLister.RegisterActivated(this); - } - else + this.active = value; + if (base.parent.Spawned) { - this.parent.Map.gatherSpotLister.RegisterDeactivated(this); + if (this.active) + { + base.parent.Map.gatherSpotLister.RegisterActivated(this); + } + else + { + base.parent.Map.gatherSpotLister.RegisterDeactivated(this); + } } } } @@ -46,7 +44,7 @@ public override void PostSpawnSetup(bool respawningAfterLoad) base.PostSpawnSetup(respawningAfterLoad); if (this.Active) { - this.parent.Map.gatherSpotLister.RegisterActivated(this); + base.parent.Map.gatherSpotLister.RegisterActivated(this); } } @@ -59,14 +57,28 @@ public override void PostDeSpawn(Map map) } } - [DebuggerHidden] public override IEnumerable CompGetGizmosExtra() { - CompGatherSpot.c__Iterator165 c__Iterator = new CompGatherSpot.c__Iterator165(); - c__Iterator.<>f__this = this; - CompGatherSpot.c__Iterator165 expr_0E = c__Iterator; - expr_0E.$PC = -2; - return expr_0E; + Command_Toggle com = new Command_Toggle + { + hotKey = KeyBindingDefOf.CommandTogglePower, + defaultLabel = "CommandGatherSpotToggleLabel".Translate(), + icon = TexCommand.GatherSpotActive, + isActive = (Func)(() => ((_003CCompGetGizmosExtra_003Ec__Iterator165)/*Error near IL_0067: stateMachine*/)._003C_003Ef__this.Active), + toggleAction = (Action)delegate + { + ((_003CCompGetGizmosExtra_003Ec__Iterator165)/*Error near IL_007e: stateMachine*/)._003C_003Ef__this.Active = !((_003CCompGetGizmosExtra_003Ec__Iterator165)/*Error near IL_007e: stateMachine*/)._003C_003Ef__this.Active; + } + }; + if (this.Active) + { + com.defaultDesc = "CommandGatherSpotToggleDescActive".Translate(); + } + else + { + com.defaultDesc = "CommandGatherSpotToggleDescInactive".Translate(); + } + yield return (Gizmo)com; } } } diff --git a/Assembly-CSharp/RimWorld/CompHasGatherableBodyResource.cs b/Assembly-CSharp/RimWorld/CompHasGatherableBodyResource.cs index 695ace28b..ffa986fd6 100644 --- a/Assembly-CSharp/RimWorld/CompHasGatherableBodyResource.cs +++ b/Assembly-CSharp/RimWorld/CompHasGatherableBodyResource.cs @@ -1,4 +1,3 @@ -using System; using UnityEngine; using Verse; @@ -40,7 +39,11 @@ protected virtual bool Active { get { - return this.parent.Faction != null; + if (base.parent.Faction == null) + { + return false; + } + return true; } } @@ -48,7 +51,11 @@ public bool ActiveAndFull { get { - return this.Active && this.fullness >= 1f; + if (!this.Active) + { + return false; + } + return this.fullness >= 1.0; } } @@ -62,14 +69,14 @@ public override void CompTick() { if (this.Active) { - float num = 1f / (float)(this.GatherResourcesIntervalDays * 60000); - Pawn pawn = this.parent as Pawn; + float num = (float)(1.0 / (float)(this.GatherResourcesIntervalDays * 60000)); + Pawn pawn = base.parent as Pawn; if (pawn != null) { num *= PawnUtility.BodyResourceGrowthSpeed(pawn); } this.fullness += num; - if (this.fullness > 1f) + if (this.fullness > 1.0) { this.fullness = 1f; } @@ -80,24 +87,26 @@ public void Gathered(Pawn doer) { if (!this.Active) { - Log.Error(doer + " gathered body resources while not Active: " + this.parent); + Log.Error(doer + " gathered body resources while not Active: " + base.parent); } if (Rand.Value > doer.GetStatValue(StatDefOf.AnimalGatherYield, true)) { - Vector3 loc = (doer.DrawPos + this.parent.DrawPos) / 2f; - MoteMaker.ThrowText(loc, this.parent.Map, "TextMote_ProductWasted".Translate(), 3.65f); - return; + Vector3 loc = (doer.DrawPos + base.parent.DrawPos) / 2f; + MoteMaker.ThrowText(loc, base.parent.Map, "TextMote_ProductWasted".Translate(), 3.65f); } - int i = GenMath.RoundRandom((float)this.ResourceAmount * this.fullness); - while (i > 0) + else { - int num = Mathf.Clamp(i, 1, this.ResourceDef.stackLimit); - i -= num; - Thing thing = ThingMaker.MakeThing(this.ResourceDef, null); - thing.stackCount = num; - GenPlace.TryPlaceThing(thing, doer.Position, doer.Map, ThingPlaceMode.Near, null); + int num = GenMath.RoundRandom((float)this.ResourceAmount * this.fullness); + while (num > 0) + { + int num2 = Mathf.Clamp(num, 1, this.ResourceDef.stackLimit); + num -= num2; + Thing thing = ThingMaker.MakeThing(this.ResourceDef, null); + thing.stackCount = num2; + GenPlace.TryPlaceThing(thing, doer.Position, doer.Map, ThingPlaceMode.Near, null); + } + this.fullness = 0f; } - this.fullness = 0f; } } } diff --git a/Assembly-CSharp/RimWorld/CompHatcher.cs b/Assembly-CSharp/RimWorld/CompHatcher.cs index 780ea7330..d46a6c2dc 100644 --- a/Assembly-CSharp/RimWorld/CompHatcher.cs +++ b/Assembly-CSharp/RimWorld/CompHatcher.cs @@ -1,5 +1,4 @@ using RimWorld.Planet; -using System; using UnityEngine; using Verse; @@ -19,7 +18,7 @@ public CompProperties_Hatcher Props { get { - return (CompProperties_Hatcher)this.props; + return (CompProperties_Hatcher)base.props; } } @@ -27,7 +26,7 @@ private CompTemperatureRuinable FreezerComp { get { - return this.parent.GetComp(); + return base.parent.GetComp(); } } @@ -53,9 +52,9 @@ public override void CompTick() { if (!this.TemperatureDamaged) { - float num = 1f / (this.Props.hatcherDaystoHatch * 60000f); + float num = (float)(1.0 / (this.Props.hatcherDaystoHatch * 60000.0)); this.gestateProgress += num; - if (this.gestateProgress > 1f) + if (this.gestateProgress > 1.0) { this.Hatch(); } @@ -64,11 +63,11 @@ public override void CompTick() public void Hatch() { - PawnGenerationRequest request = new PawnGenerationRequest(this.Props.hatcherPawn, this.hatcheeFaction, PawnGenerationContext.NonPlayer, -1, false, true, false, false, true, false, 1f, false, true, true, false, false, null, null, null, null, null, null); - for (int i = 0; i < this.parent.stackCount; i++) + PawnGenerationRequest request = new PawnGenerationRequest(this.Props.hatcherPawn, this.hatcheeFaction, PawnGenerationContext.NonPlayer, -1, false, true, false, false, true, false, 1f, false, true, true, false, false, null, default(float?), default(float?), default(Gender?), default(float?), (string)null); + for (int i = 0; i < base.parent.stackCount; i++) { Pawn pawn = PawnGenerator.GeneratePawn(request); - if (PawnUtility.TrySpawnHatchedOrBornPawn(pawn, this.parent)) + if (PawnUtility.TrySpawnHatchedOrBornPawn(pawn, base.parent)) { if (pawn != null) { @@ -88,9 +87,9 @@ public void Hatch() pawn.relations.AddDirectRelation(PawnRelationDefOf.Parent, this.otherParent); } } - if (this.parent.Spawned) + if (base.parent.Spawned) { - FilthMaker.MakeFilth(this.parent.Position, this.parent.Map, ThingDefOf.FilthAmnioticFluid, 1); + FilthMaker.MakeFilth(base.parent.Position, base.parent.Map, ThingDefOf.FilthAmnioticFluid, 1); } } else @@ -98,12 +97,12 @@ public void Hatch() Find.WorldPawns.PassToWorld(pawn, PawnDiscardDecideMode.Discard); } } - this.parent.Destroy(DestroyMode.Vanish); + base.parent.Destroy(DestroyMode.Vanish); } public override void PreAbsorbStack(Thing otherStack, int count) { - float t = (float)count / (float)(this.parent.stackCount + count); + float t = (float)count / (float)(base.parent.stackCount + count); CompHatcher comp = ((ThingWithComps)otherStack).GetComp(); float b = comp.gestateProgress; this.gestateProgress = Mathf.Lerp(this.gestateProgress, b, t); @@ -121,13 +120,18 @@ public override void PostSplitOff(Thing piece) public override void PrePreTraded(TradeAction action, Pawn playerNegotiator, ITrader trader) { base.PrePreTraded(action, playerNegotiator, trader); - if (action == TradeAction.PlayerBuys) + switch (action) + { + case TradeAction.PlayerBuys: { this.hatcheeFaction = Faction.OfPlayer; + break; } - else if (action == TradeAction.PlayerSells) + case TradeAction.PlayerSells: { this.hatcheeFaction = trader.Faction; + break; + } } } @@ -143,7 +147,7 @@ public override string CompInspectStringExtra() { return "EggProgress".Translate() + ": " + this.gestateProgress.ToStringPercent(); } - return null; + return (string)null; } } } diff --git a/Assembly-CSharp/RimWorld/CompIngredients.cs b/Assembly-CSharp/RimWorld/CompIngredients.cs index 0774a3455..4871369b2 100644 --- a/Assembly-CSharp/RimWorld/CompIngredients.cs +++ b/Assembly-CSharp/RimWorld/CompIngredients.cs @@ -1,4 +1,3 @@ -using System; using System.Collections.Generic; using System.Text; using Verse; @@ -28,7 +27,7 @@ public void RegisterIngredient(ThingDef def) public override void PostSplitOff(Thing piece) { base.PostSplitOff(piece); - if (piece != this.parent) + if (piece != base.parent) { CompIngredients compIngredients = piece.TryGetComp(); for (int i = 0; i < this.ingredients.Count; i++) @@ -52,7 +51,7 @@ public override void PreAbsorbStack(Thing otherStack, int count) } if (this.ingredients.Count > 3) { - this.ingredients.Shuffle(); + this.ingredients.Shuffle(); while (this.ingredients.Count > 3) { this.ingredients.Remove(this.ingredients[this.ingredients.Count - 1]); diff --git a/Assembly-CSharp/RimWorld/CompLaunchable.cs b/Assembly-CSharp/RimWorld/CompLaunchable.cs index 928a3db0a..d27e88c7d 100644 --- a/Assembly-CSharp/RimWorld/CompLaunchable.cs +++ b/Assembly-CSharp/RimWorld/CompLaunchable.cs @@ -1,7 +1,6 @@ using RimWorld.Planet; using System; using System.Collections.Generic; -using System.Diagnostics; using UnityEngine; using Verse; @@ -22,7 +21,7 @@ public Building FuelingPortSource { get { - return FuelingPortUtility.FuelingPortGiverAtFuelingPortCell(this.parent.Position, this.parent.Map); + return FuelingPortUtility.FuelingPortGiverAtFuelingPortCell(base.parent.Position, base.parent.Map); } } @@ -70,7 +69,7 @@ public List TransportersInGroup { get { - return this.Transporter.TransportersInGroup(this.parent.Map); + return this.Transporter.TransportersInGroup(base.parent.Map); } } @@ -97,7 +96,7 @@ public bool AnyInGroupIsUnderRoof List transportersInGroup = this.TransportersInGroup; for (int i = 0; i < transportersInGroup.Count; i++) { - if (transportersInGroup[i].parent.Position.Roofed(this.parent.Map)) + if (transportersInGroup[i].parent.Position.Roofed(base.parent.Map)) { return true; } @@ -112,7 +111,7 @@ public CompTransporter Transporter { if (this.cachedCompTransporter == null) { - this.cachedCompTransporter = this.parent.GetComp(); + this.cachedCompTransporter = base.parent.GetComp(); } return this.cachedCompTransporter; } @@ -220,61 +219,92 @@ private int MaxLaunchDistanceEverPossible } } - [DebuggerHidden] public override IEnumerable CompGetGizmosExtra() { - CompLaunchable.c__Iterator166 c__Iterator = new CompLaunchable.c__Iterator166(); - c__Iterator.<>f__this = this; - CompLaunchable.c__Iterator166 expr_0E = c__Iterator; - expr_0E.$PC = -2; - return expr_0E; - } - - public override string CompInspectStringExtra() - { - if (!this.LoadingInProgressOrReadyToLaunch) - { - return null; - } - if (!this.AllInGroupConnectedToFuelingPort) + foreach (Gizmo item in base.CompGetGizmosExtra()) { - return "NotReadyForLaunch".Translate() + ": " + "NotAllInGroupConnectedToFuelingPort".Translate() + "."; + yield return item; } - if (!this.AllFuelingPortSourcesInGroupHaveAnyFuel) + if (this.LoadingInProgressOrReadyToLaunch) { - return "NotReadyForLaunch".Translate() + ": " + "NotAllFuelingPortSourcesInGroupHaveAnyFuel".Translate() + "."; + Command_Action launch = new Command_Action + { + defaultLabel = "CommandLaunchGroup".Translate(), + defaultDesc = "CommandLaunchGroupDesc".Translate(), + icon = CompLaunchable.LaunchCommandTex, + action = (Action)delegate + { + if (((_003CCompGetGizmosExtra_003Ec__Iterator166)/*Error near IL_0105: stateMachine*/)._003C_003Ef__this.AnyInGroupHasAnythingLeftToLoad) + { + Find.WindowStack.Add(Dialog_MessageBox.CreateConfirmation("ConfirmSendNotCompletelyLoadedPods".Translate(((_003CCompGetGizmosExtra_003Ec__Iterator166)/*Error near IL_0105: stateMachine*/)._003C_003Ef__this.FirstThingLeftToLoadInGroup.LabelCapNoCount), new Action(((_003CCompGetGizmosExtra_003Ec__Iterator166)/*Error near IL_0105: stateMachine*/)._003C_003Ef__this.StartChoosingDestination), false, (string)null)); + } + else + { + ((_003CCompGetGizmosExtra_003Ec__Iterator166)/*Error near IL_0105: stateMachine*/)._003C_003Ef__this.StartChoosingDestination(); + } + } + }; + if (!this.AllInGroupConnectedToFuelingPort) + { + launch.Disable("CommandLaunchGroupFailNotConnectedToFuelingPort".Translate()); + } + else if (!this.AllFuelingPortSourcesInGroupHaveAnyFuel) + { + launch.Disable("CommandLaunchGroupFailNoFuel".Translate()); + } + else if (this.AnyInGroupIsUnderRoof) + { + launch.Disable("CommandLaunchGroupFailUnderRoof".Translate()); + } + yield return (Gizmo)launch; } - if (this.AnyInGroupHasAnythingLeftToLoad) + } + + public override string CompInspectStringExtra() + { + if (this.LoadingInProgressOrReadyToLaunch) { - return "NotReadyForLaunch".Translate() + ": " + "TransportPodInGroupHasSomethingLeftToLoad".Translate() + "."; + if (!this.AllInGroupConnectedToFuelingPort) + { + return "NotReadyForLaunch".Translate() + ": " + "NotAllInGroupConnectedToFuelingPort".Translate() + "."; + } + if (!this.AllFuelingPortSourcesInGroupHaveAnyFuel) + { + return "NotReadyForLaunch".Translate() + ": " + "NotAllFuelingPortSourcesInGroupHaveAnyFuel".Translate() + "."; + } + if (this.AnyInGroupHasAnythingLeftToLoad) + { + return "NotReadyForLaunch".Translate() + ": " + "TransportPodInGroupHasSomethingLeftToLoad".Translate() + "."; + } + return "ReadyForLaunch".Translate(); } - return "ReadyForLaunch".Translate(); + return (string)null; } private void StartChoosingDestination() { - CameraJumper.TryJump(CameraJumper.GetWorldTarget(this.parent)); + CameraJumper.TryJump(CameraJumper.GetWorldTarget((Thing)base.parent)); Find.WorldSelector.ClearSelection(); - int tile = this.parent.Map.Tile; - Find.WorldTargeter.BeginTargeting(new Func(this.ChoseWorldTarget), true, CompLaunchable.TargeterMouseAttachment, true, delegate + int tile = base.parent.Map.Tile; + Find.WorldTargeter.BeginTargeting(new Func(this.ChoseWorldTarget), true, CompLaunchable.TargeterMouseAttachment, true, (Action)delegate { GenDraw.DrawWorldRadiusRing(tile, this.MaxLaunchDistance); - }, delegate(GlobalTargetInfo target) + }, (Func)delegate(GlobalTargetInfo target) { if (!target.IsValid) { - return null; + return (string)null; } int num = Find.WorldGrid.TraversalDistanceBetween(tile, target.Tile); - if (num <= this.MaxLaunchDistance) - { - return null; - } - if (num > this.MaxLaunchDistanceEverPossible) + if (num > this.MaxLaunchDistance) { - return "TransportPodDestinationBeyondMaximumRange".Translate(); + if (num > this.MaxLaunchDistanceEverPossible) + { + return "TransportPodDestinationBeyondMaximumRange".Translate(); + } + return "TransportPodNotEnoughFuel".Translate(); } - return "TransportPodNotEnoughFuel".Translate(); + return (string)null; }); } @@ -289,81 +319,72 @@ private bool ChoseWorldTarget(GlobalTargetInfo target) Messages.Message("MessageTransportPodsDestinationIsInvalid".Translate(), MessageSound.RejectInput); return false; } - int num = Find.WorldGrid.TraversalDistanceBetween(this.parent.Map.Tile, target.Tile); + int num = Find.WorldGrid.TraversalDistanceBetween(base.parent.Map.Tile, target.Tile); if (num > this.MaxLaunchDistance) { - Messages.Message("MessageTransportPodsDestinationIsTooFar".Translate(new object[] - { - CompLaunchable.FuelNeededToLaunchAtDist((float)num).ToString("0.#") - }), MessageSound.RejectInput); + float num2 = CompLaunchable.FuelNeededToLaunchAtDist((float)num); + Messages.Message("MessageTransportPodsDestinationIsTooFar".Translate(num2.ToString("0.#")), MessageSound.RejectInput); return false; } MapParent mapParent = target.WorldObject as MapParent; + bool flag = false; if (mapParent != null && mapParent.HasMap) { - Map myMap = this.parent.Map; + Map myMap = base.parent.Map; Map map = mapParent.Map; Current.Game.VisibleMap = map; - Targeter arg_13B_0 = Find.Targeter; - Action actionWhenFinished = delegate + Targeter targeter = Find.Targeter; + Action actionWhenFinished = (Action)delegate { if (Find.Maps.Contains(myMap)) { Current.Game.VisibleMap = myMap; } }; - arg_13B_0.BeginTargeting(TargetingParameters.ForDropPodsDestination(), delegate(LocalTargetInfo x) + targeter.BeginTargeting(TargetingParameters.ForDropPodsDestination(), (Action)delegate(LocalTargetInfo x) { - if (!this.LoadingInProgressOrReadyToLaunch) + if (this.LoadingInProgressOrReadyToLaunch) { - return; + this.TryLaunch(x.ToGlobalTargetInfo(map), PawnsArriveMode.Undecided, false); } - this.TryLaunch(x.ToGlobalTargetInfo(map), PawnsArriveMode.Undecided, false); }, null, actionWhenFinished, CompLaunchable.TargeterMouseAttachment); return true; } - bool flag; if (mapParent != null) { Settlement settlement = mapParent as Settlement; List list = new List(); if (settlement != null && settlement.Visitable) { - list.Add(new FloatMenuOption("VisitSettlement".Translate(new object[] + list.Add(new FloatMenuOption("VisitSettlement".Translate(target.WorldObject.Label), (Action)delegate() { - target.WorldObject.Label - }), delegate - { - if (!this.LoadingInProgressOrReadyToLaunch) + if (this.LoadingInProgressOrReadyToLaunch) { - return; + this.TryLaunch(target, PawnsArriveMode.Undecided, false); + CameraJumper.TryHideWorld(); } - this.TryLaunch(target, PawnsArriveMode.Undecided, false); - CameraJumper.TryHideWorld(); }, MenuOptionPriority.Default, null, null, 0f, null, null)); } if (mapParent.TransportPodsCanLandAndGenerateMap) { - list.Add(new FloatMenuOption("DropAtEdge".Translate(), delegate + list.Add(new FloatMenuOption("DropAtEdge".Translate(), (Action)delegate() { - if (!this.LoadingInProgressOrReadyToLaunch) + if (this.LoadingInProgressOrReadyToLaunch) { - return; + this.TryLaunch(target, PawnsArriveMode.EdgeDrop, true); + CameraJumper.TryHideWorld(); } - this.TryLaunch(target, PawnsArriveMode.EdgeDrop, true); - CameraJumper.TryHideWorld(); }, MenuOptionPriority.Default, null, null, 0f, null, null)); - list.Add(new FloatMenuOption("DropInCenter".Translate(), delegate + list.Add(new FloatMenuOption("DropInCenter".Translate(), (Action)delegate() { - if (!this.LoadingInProgressOrReadyToLaunch) + if (this.LoadingInProgressOrReadyToLaunch) { - return; + this.TryLaunch(target, PawnsArriveMode.CenterDrop, true); + CameraJumper.TryHideWorld(); } - this.TryLaunch(target, PawnsArriveMode.CenterDrop, true); - CameraJumper.TryHideWorld(); }, MenuOptionPriority.Default, null, null, 0f, null, null)); } - if (list.Any()) + if (list.Any()) { Find.WorldTargeter.closeWorldTabWhenFinished = false; Find.WindowStack.Add(new FloatMenu(list)); @@ -375,66 +396,65 @@ private bool ChoseWorldTarget(GlobalTargetInfo target) { flag = true; } - if (!flag) + if (flag) { - return false; - } - if (Find.World.Impassable(target.Tile)) - { - Messages.Message("MessageTransportPodsDestinationIsInvalid".Translate(), MessageSound.RejectInput); - return false; + if (Find.World.Impassable(target.Tile)) + { + Messages.Message("MessageTransportPodsDestinationIsInvalid".Translate(), MessageSound.RejectInput); + return false; + } + this.TryLaunch(target, PawnsArriveMode.Undecided, false); + return true; } - this.TryLaunch(target, PawnsArriveMode.Undecided, false); - return true; + return false; } private void TryLaunch(GlobalTargetInfo target, PawnsArriveMode arriveMode, bool attackOnArrival) { - if (!this.parent.Spawned) + if (!base.parent.Spawned) { - Log.Error("Tried to launch " + this.parent + ", but it's unspawned."); - return; + Log.Error("Tried to launch " + base.parent + ", but it's unspawned."); } - List transportersInGroup = this.TransportersInGroup; - if (transportersInGroup == null) - { - Log.Error("Tried to launch " + this.parent + ", but it's not in any group."); - return; - } - if (!this.LoadingInProgressOrReadyToLaunch || !this.AllInGroupConnectedToFuelingPort || !this.AllFuelingPortSourcesInGroupHaveAnyFuel) - { - return; - } - Map map = this.parent.Map; - int num = Find.WorldGrid.TraversalDistanceBetween(map.Tile, target.Tile); - if (num > this.MaxLaunchDistance) + else { - return; - } - this.Transporter.TryRemoveLord(map); - int groupID = this.Transporter.groupID; - float amount = Mathf.Max(CompLaunchable.FuelNeededToLaunchAtDist((float)num), 1f); - for (int i = 0; i < transportersInGroup.Count; i++) - { - CompTransporter compTransporter = transportersInGroup[i]; - Building fuelingPortSource = compTransporter.Launchable.FuelingPortSource; - if (fuelingPortSource != null) + List transportersInGroup = this.TransportersInGroup; + if (transportersInGroup == null) + { + Log.Error("Tried to launch " + base.parent + ", but it's not in any group."); + } + else if (this.LoadingInProgressOrReadyToLaunch && this.AllInGroupConnectedToFuelingPort && this.AllFuelingPortSourcesInGroupHaveAnyFuel) { - fuelingPortSource.TryGetComp().ConsumeFuel(amount); + Map map = base.parent.Map; + int num = Find.WorldGrid.TraversalDistanceBetween(map.Tile, target.Tile); + if (num <= this.MaxLaunchDistance) + { + this.Transporter.TryRemoveLord(map); + int groupID = this.Transporter.groupID; + float amount = Mathf.Max(CompLaunchable.FuelNeededToLaunchAtDist((float)num), 1f); + for (int i = 0; i < transportersInGroup.Count; i++) + { + CompTransporter compTransporter = transportersInGroup[i]; + Building fuelingPortSource = compTransporter.Launchable.FuelingPortSource; + if (fuelingPortSource != null) + { + fuelingPortSource.TryGetComp().ConsumeFuel(amount); + } + DropPodLeaving dropPodLeaving = (DropPodLeaving)ThingMaker.MakeThing(ThingDefOf.DropPodLeaving, null); + dropPodLeaving.groupID = groupID; + dropPodLeaving.destinationTile = target.Tile; + dropPodLeaving.destinationCell = target.Cell; + dropPodLeaving.arriveMode = arriveMode; + dropPodLeaving.attackOnArrival = attackOnArrival; + ThingOwner directlyHeldThings = compTransporter.GetDirectlyHeldThings(); + dropPodLeaving.Contents = new ActiveDropPodInfo(); + dropPodLeaving.Contents.innerContainer.TryAddRange(directlyHeldThings, true); + directlyHeldThings.Clear(); + compTransporter.CleanUpLoadingVars(map); + compTransporter.parent.Destroy(DestroyMode.Vanish); + GenSpawn.Spawn(dropPodLeaving, compTransporter.parent.Position, map); + } + } } - DropPodLeaving dropPodLeaving = (DropPodLeaving)ThingMaker.MakeThing(ThingDefOf.DropPodLeaving, null); - dropPodLeaving.groupID = groupID; - dropPodLeaving.destinationTile = target.Tile; - dropPodLeaving.destinationCell = target.Cell; - dropPodLeaving.arriveMode = arriveMode; - dropPodLeaving.attackOnArrival = attackOnArrival; - ThingOwner directlyHeldThings = compTransporter.GetDirectlyHeldThings(); - dropPodLeaving.Contents = new ActiveDropPodInfo(); - dropPodLeaving.Contents.innerContainer.TryAddRange(directlyHeldThings, true); - directlyHeldThings.Clear(); - compTransporter.CleanUpLoadingVars(map); - compTransporter.parent.Destroy(DestroyMode.Vanish); - GenSpawn.Spawn(dropPodLeaving, compTransporter.parent.Position, map); } } @@ -442,18 +462,18 @@ public void Notify_FuelingPortSourceDeSpawned() { if (this.Transporter.CancelLoad()) { - Messages.Message("MessageTransportersLoadCanceled_FuelingPortGiverDeSpawned".Translate(), this.parent, MessageSound.Negative); + Messages.Message("MessageTransportersLoadCanceled_FuelingPortGiverDeSpawned".Translate(), (Thing)base.parent, MessageSound.Negative); } } public static int MaxLaunchDistanceAtFuelLevel(float fuelLevel) { - return Mathf.FloorToInt(fuelLevel / 2.25f); + return Mathf.FloorToInt((float)(fuelLevel / 2.25)); } public static float FuelNeededToLaunchAtDist(float dist) { - return 2.25f * dist; + return (float)(2.25 * dist); } } } diff --git a/Assembly-CSharp/RimWorld/CompLongRangeMineralScanner.cs b/Assembly-CSharp/RimWorld/CompLongRangeMineralScanner.cs index d1722eb1a..35411964f 100644 --- a/Assembly-CSharp/RimWorld/CompLongRangeMineralScanner.cs +++ b/Assembly-CSharp/RimWorld/CompLongRangeMineralScanner.cs @@ -1,7 +1,6 @@ using RimWorld.Planet; using System; using System.Collections.Generic; -using System.Diagnostics; using UnityEngine; using Verse; @@ -23,7 +22,7 @@ public CompProperties_LongRangeMineralScanner Props { get { - return (CompProperties_LongRangeMineralScanner)this.props; + return (CompProperties_LongRangeMineralScanner)base.props; } } @@ -43,7 +42,15 @@ public bool Active { get { - return this.parent.Spawned && (this.powerComp == null || this.powerComp.PowerOn) && this.parent.Faction == Faction.OfPlayer; + if (!base.parent.Spawned) + { + return false; + } + if (this.powerComp != null && !this.powerComp.PowerOn) + { + return false; + } + return base.parent.Faction == Faction.OfPlayer; } } @@ -53,7 +60,7 @@ private float EffectiveMtbDays { CompProperties_LongRangeMineralScanner props = this.Props; float effectiveAreaPct = this.EffectiveAreaPct; - if (effectiveAreaPct <= 0.001f) + if (effectiveAreaPct <= 0.0010000000474974513) { return -1f; } @@ -72,7 +79,7 @@ private float EffectiveAreaPct public override void PostSpawnSetup(bool respawningAfterLoad) { base.PostSpawnSetup(respawningAfterLoad); - this.powerComp = this.parent.GetComp(); + this.powerComp = base.parent.GetComp(); this.RecacheEffectiveAreaPct(); } @@ -97,81 +104,71 @@ private void RecacheEffectiveAreaPct() if (!this.Active) { this.cachedEffectiveAreaPct = 0f; - return; } - this.CalculateOtherActiveMineralScanners(); - if (!this.otherActiveMineralScanners.Any>()) + else { - this.cachedEffectiveAreaPct = 1f; - return; - } - CompProperties_LongRangeMineralScanner props = this.Props; - WorldGrid worldGrid = Find.WorldGrid; - Vector3 tileCenter = worldGrid.GetTileCenter(this.parent.Tile); - float angle = worldGrid.TileRadiusToAngle(props.radius); - int num = 0; - int count = this.otherActiveMineralScanners.Count; - Rand.PushState(this.parent.thingIDNumber); - for (int i = 0; i < 400; i++) - { - Vector3 point = Rand.PointOnSphereCap(tileCenter, angle); - bool flag = false; - for (int j = 0; j < count; j++) + this.CalculateOtherActiveMineralScanners(); + if (!this.otherActiveMineralScanners.Any()) { - Pair pair = this.otherActiveMineralScanners[j]; - if (MeshUtility.Visible(point, 1f, pair.First, pair.Second)) - { - flag = true; - break; - } + this.cachedEffectiveAreaPct = 1f; } - if (!flag) + else { - num++; + CompProperties_LongRangeMineralScanner props = this.Props; + WorldGrid worldGrid = Find.WorldGrid; + Vector3 tileCenter = worldGrid.GetTileCenter(base.parent.Tile); + float angle = worldGrid.TileRadiusToAngle(props.radius); + int num = 0; + int count = this.otherActiveMineralScanners.Count; + Rand.PushState(base.parent.thingIDNumber); + for (int i = 0; i < 400; i++) + { + Vector3 point = Rand.PointOnSphereCap(tileCenter, angle); + bool flag = false; + for (int num2 = 0; num2 < count; num2++) + { + Pair pair = this.otherActiveMineralScanners[num2]; + if (MeshUtility.Visible(point, 1f, pair.First, pair.Second)) + { + flag = true; + break; + } + } + if (!flag) + { + num++; + } + } + Rand.PopState(); + this.cachedEffectiveAreaPct = (float)((float)num / 400.0); } } - Rand.PopState(); - this.cachedEffectiveAreaPct = (float)num / 400f; } private void CheckTryFindMinerals(int interval) { - if (!this.Active) - { - return; - } - float effectiveMtbDays = this.EffectiveMtbDays; - if (effectiveMtbDays <= 0f) - { - return; - } - if (Rand.MTBEventOccurs(effectiveMtbDays, 60000f, (float)interval)) + if (this.Active) { - this.FoundMinerals(); + float effectiveMtbDays = this.EffectiveMtbDays; + if (!(effectiveMtbDays <= 0.0) && Rand.MTBEventOccurs(effectiveMtbDays, 60000f, (float)interval)) + { + this.FoundMinerals(); + } } } private void FoundMinerals() { - int tile; - if (!TileFinder.TryFindNewSiteTile(out tile)) - { - return; - } - Site site; - if (Rand.Chance(0.6f)) - { - site = SiteMaker.TryMakeSite(SiteCoreDefOf.PreciousLump, null, true, null); - } - else - { - site = SiteMaker.TryMakeRandomSite(SiteCoreDefOf.PreciousLump, this.PossibleSiteParts, null, true, null); - } - if (site != null) + int tile = default(int); + if (TileFinder.TryFindNewSiteTile(out tile)) { - site.Tile = tile; - Find.WorldObjects.Add(site); - Find.LetterStack.ReceiveLetter("LetterLabelFoundPreciousLump".Translate(), "LetterFoundPreciousLump".Translate(), LetterDefOf.Good, site, null); + Site site = (!Rand.Chance(0.6f)) ? SiteMaker.TryMakeRandomSite(SiteCoreDefOf.PreciousLump, this.PossibleSiteParts, null, true, null) : SiteMaker.TryMakeSite(SiteCoreDefOf.PreciousLump, null, true, null); + if (site != null) + { + site.Tile = tile; + Find.WorldObjects.Add(site); + Find.LetterStack.ReceiveLetter("LetterLabelFoundPreciousLump".Translate(), "LetterFoundPreciousLump".Translate(), LetterDefOf.Good, (WorldObject)site, (string)null); + } } } @@ -210,7 +207,7 @@ private bool InterruptsMe(CompLongRangeMineralScanner otherScanner) { return otherScanner.Props.mtbDays < this.Props.mtbDays; } - return otherScanner.parent.thingIDNumber < this.parent.thingIDNumber; + return otherScanner.parent.thingIDNumber < base.parent.thingIDNumber; } public override string CompInspectStringExtra() @@ -218,22 +215,24 @@ public override string CompInspectStringExtra() if (this.Active) { this.RecacheEffectiveAreaPct(); - return "LongRangeMineralScannerEfficiency".Translate(new object[] - { - this.EffectiveAreaPct.ToStringPercent() - }); + return "LongRangeMineralScannerEfficiency".Translate(this.EffectiveAreaPct.ToStringPercent()); } - return null; + return (string)null; } - [DebuggerHidden] public override IEnumerable CompGetGizmosExtra() { - CompLongRangeMineralScanner.c__Iterator167 c__Iterator = new CompLongRangeMineralScanner.c__Iterator167(); - c__Iterator.<>f__this = this; - CompLongRangeMineralScanner.c__Iterator167 expr_0E = c__Iterator; - expr_0E.$PC = -2; - return expr_0E; + if (Prefs.DevMode) + { + yield return (Gizmo)new Command_Action + { + defaultLabel = "Dev: Find resources now", + action = (Action)delegate + { + ((_003CCompGetGizmosExtra_003Ec__Iterator167)/*Error near IL_004c: stateMachine*/)._003C_003Ef__this.FoundMinerals(); + } + }; + } } } } diff --git a/Assembly-CSharp/RimWorld/CompMaintainable.cs b/Assembly-CSharp/RimWorld/CompMaintainable.cs index f1c29d976..b50639baf 100644 --- a/Assembly-CSharp/RimWorld/CompMaintainable.cs +++ b/Assembly-CSharp/RimWorld/CompMaintainable.cs @@ -1,4 +1,3 @@ -using System; using Verse; namespace RimWorld @@ -11,7 +10,7 @@ public CompProperties_Maintainable Props { get { - return (CompProperties_Maintainable)this.props; + return (CompProperties_Maintainable)base.props; } } @@ -38,15 +37,13 @@ public override void PostExposeData() public override void CompTickRare() { - Hive hive = this.parent as Hive; + Hive hive = base.parent as Hive; if (hive != null && !hive.active) - { return; - } this.ticksSinceMaintain += 250; if (this.CurStage == MaintainableStage.Damaging) { - this.parent.TakeDamage(new DamageInfo(DamageDefOf.Deterioration, this.Props.damagePerTickRare, -1f, null, null, null, DamageInfo.SourceCategory.ThingOrUnknown)); + base.parent.TakeDamage(new DamageInfo(DamageDefOf.Deterioration, this.Props.damagePerTickRare, -1f, null, null, null, DamageInfo.SourceCategory.ThingOrUnknown)); } } @@ -57,16 +54,21 @@ public void Maintained() public override string CompInspectStringExtra() { - MaintainableStage curStage = this.CurStage; - if (curStage == MaintainableStage.NeedsMaintenance) + switch (this.CurStage) + { + case MaintainableStage.NeedsMaintenance: { return "DueForMaintenance".Translate(); } - if (curStage != MaintainableStage.Damaging) + case MaintainableStage.Damaging: { - return null; + return "DeterioratingDueToLackOfMaintenance".Translate(); + } + default: + { + return (string)null; + } } - return "DeterioratingDueToLackOfMaintenance".Translate(); } } } diff --git a/Assembly-CSharp/RimWorld/CompMannable.cs b/Assembly-CSharp/RimWorld/CompMannable.cs index 2d78f14f3..624ac4810 100644 --- a/Assembly-CSharp/RimWorld/CompMannable.cs +++ b/Assembly-CSharp/RimWorld/CompMannable.cs @@ -1,7 +1,7 @@ using System; using System.Collections.Generic; -using System.Diagnostics; using Verse; +using Verse.AI; namespace RimWorld { @@ -35,7 +35,7 @@ public CompProperties_Mannable Props { get { - return (CompProperties_Mannable)this.props; + return (CompProperties_Mannable)base.props; } } @@ -43,19 +43,20 @@ public void ManForATick(Pawn pawn) { this.lastManTick = Find.TickManager.TicksGame; this.lastManPawn = pawn; - pawn.mindState.lastMannedThing = this.parent; + pawn.mindState.lastMannedThing = base.parent; } - [DebuggerHidden] public override IEnumerable CompFloatMenuOptions(Pawn pawn) { - CompMannable.c__Iterator168 c__Iterator = new CompMannable.c__Iterator168(); - c__Iterator.pawn = pawn; - c__Iterator.<$>pawn = pawn; - c__Iterator.<>f__this = this; - CompMannable.c__Iterator168 expr_1C = c__Iterator; - expr_1C.$PC = -2; - return expr_1C; + if (pawn.RaceProps.ToolUser && pawn.CanReserveAndReach((Thing)base.parent, PathEndMode.InteractionCell, Danger.Deadly, 1, -1, null, false) && (this.Props.manWorkType == WorkTags.None || pawn.story == null || !pawn.story.WorkTagIsDisabled(this.Props.manWorkType))) + { + FloatMenuOption opt = new FloatMenuOption("OrderManThing".Translate(base.parent.LabelShort), (Action)delegate + { + Job job = new Job(JobDefOf.ManTurret, (Thing)((_003CCompFloatMenuOptions_003Ec__Iterator168)/*Error near IL_00d9: stateMachine*/)._003C_003Ef__this.parent); + ((_003CCompFloatMenuOptions_003Ec__Iterator168)/*Error near IL_00d9: stateMachine*/).pawn.jobs.TryTakeOrderedJob(job, JobTag.Misc); + }, MenuOptionPriority.Default, null, null, 0f, null, null); + yield return opt; + } } } } diff --git a/Assembly-CSharp/RimWorld/CompMelter.cs b/Assembly-CSharp/RimWorld/CompMelter.cs index 2a6ec56a5..80b6ce356 100644 --- a/Assembly-CSharp/RimWorld/CompMelter.cs +++ b/Assembly-CSharp/RimWorld/CompMelter.cs @@ -1,4 +1,3 @@ -using System; using Verse; namespace RimWorld @@ -9,16 +8,15 @@ public class CompMelter : ThingComp public override void CompTickRare() { - float ambientTemperature = this.parent.AmbientTemperature; - if (ambientTemperature < 0f) + float ambientTemperature = base.parent.AmbientTemperature; + if (!(ambientTemperature < 0.0)) { - return; - } - float f = 0.15f * (ambientTemperature / 10f); - int num = GenMath.RoundRandom(f); - if (num > 0) - { - this.parent.TakeDamage(new DamageInfo(DamageDefOf.Rotting, num, -1f, null, null, null, DamageInfo.SourceCategory.ThingOrUnknown)); + float f = (float)(0.15000000596046448 * (ambientTemperature / 10.0)); + int num = GenMath.RoundRandom(f); + if (num > 0) + { + base.parent.TakeDamage(new DamageInfo(DamageDefOf.Rotting, num, -1f, null, null, null, DamageInfo.SourceCategory.ThingOrUnknown)); + } } } } diff --git a/Assembly-CSharp/RimWorld/CompMilkable.cs b/Assembly-CSharp/RimWorld/CompMilkable.cs index 3ada53cf8..f32079b06 100644 --- a/Assembly-CSharp/RimWorld/CompMilkable.cs +++ b/Assembly-CSharp/RimWorld/CompMilkable.cs @@ -1,4 +1,3 @@ -using System; using Verse; namespace RimWorld @@ -41,7 +40,7 @@ public CompProperties_Milkable Props { get { - return (CompProperties_Milkable)this.props; + return (CompProperties_Milkable)base.props; } } @@ -53,8 +52,16 @@ protected override bool Active { return false; } - Pawn pawn = this.parent as Pawn; - return (!this.Props.milkFemaleOnly || pawn == null || pawn.gender == Gender.Female) && (pawn == null || pawn.ageTracker.CurLifeStage.milkable); + Pawn pawn = base.parent as Pawn; + if (this.Props.milkFemaleOnly && pawn != null && pawn.gender != Gender.Female) + { + return false; + } + if (pawn != null && !pawn.ageTracker.CurLifeStage.milkable) + { + return false; + } + return true; } } @@ -62,7 +69,7 @@ public override string CompInspectStringExtra() { if (!this.Active) { - return null; + return (string)null; } return "MilkFullness".Translate() + ": " + base.Fullness.ToStringPercent(); } diff --git a/Assembly-CSharp/RimWorld/CompNeurotrainer.cs b/Assembly-CSharp/RimWorld/CompNeurotrainer.cs index 2c9cb5b86..f82e68972 100644 --- a/Assembly-CSharp/RimWorld/CompNeurotrainer.cs +++ b/Assembly-CSharp/RimWorld/CompNeurotrainer.cs @@ -1,4 +1,3 @@ -using System; using Verse; namespace RimWorld @@ -39,7 +38,11 @@ public override bool AllowStackWith(Thing other) return false; } CompNeurotrainer compNeurotrainer = other.TryGetComp(); - return compNeurotrainer != null && compNeurotrainer.skill == this.skill; + if (compNeurotrainer != null && compNeurotrainer.skill == this.skill) + { + return true; + } + return false; } public override void PostSplitOff(Thing piece) diff --git a/Assembly-CSharp/RimWorld/CompPower.cs b/Assembly-CSharp/RimWorld/CompPower.cs index 81213448c..8bd8096e6 100644 --- a/Assembly-CSharp/RimWorld/CompPower.cs +++ b/Assembly-CSharp/RimWorld/CompPower.cs @@ -1,7 +1,8 @@ using System; using System.Collections.Generic; -using System.Diagnostics; +using UnityEngine; using Verse; +using Verse.Sound; namespace RimWorld { @@ -23,7 +24,7 @@ public bool TransmitsPowerNow { get { - return ((Building)this.parent).TransmitsPowerNow; + return ((Building)base.parent).TransmitsPowerNow; } } @@ -47,7 +48,7 @@ public CompProperties_Power Props { get { - return (CompProperties_Power)this.props; + return (CompProperties_Power)base.props; } } @@ -71,7 +72,7 @@ public override void PostExposeData() { thing = this.connectParent.parent; } - Scribe_References.Look(ref thing, "parentThing", false); + Scribe_References.Look(ref thing, "parentThing", false); if (thing != null) { this.connectParent = ((ThingWithComps)thing).GetComp(); @@ -85,51 +86,49 @@ public override void PostExposeData() public override void PostSpawnSetup(bool respawningAfterLoad) { base.PostSpawnSetup(respawningAfterLoad); - if (this.Props.transmitsPower || this.parent.def.ConnectToPower) + if (!this.Props.transmitsPower && !base.parent.def.ConnectToPower) + return; + base.parent.Map.mapDrawer.MapMeshDirty(base.parent.Position, MapMeshFlag.PowerGrid, true, false); + if (this.Props.transmitsPower) { - this.parent.Map.mapDrawer.MapMeshDirty(this.parent.Position, MapMeshFlag.PowerGrid, true, false); - if (this.Props.transmitsPower) - { - this.parent.Map.powerNetManager.Notify_TransmitterSpawned(this); - } - if (this.parent.def.ConnectToPower) - { - this.parent.Map.powerNetManager.Notify_ConnectorWantsConnect(this); - } - this.SetUpPowerVars(); + base.parent.Map.powerNetManager.Notify_TransmitterSpawned(this); + } + if (base.parent.def.ConnectToPower) + { + base.parent.Map.powerNetManager.Notify_ConnectorWantsConnect(this); } + this.SetUpPowerVars(); } public override void PostDeSpawn(Map map) { base.PostDeSpawn(map); - if (this.Props.transmitsPower || this.parent.def.ConnectToPower) + if (!this.Props.transmitsPower && !base.parent.def.ConnectToPower) + return; + if (this.Props.transmitsPower) { - if (this.Props.transmitsPower) + if (this.connectChildren != null) { - if (this.connectChildren != null) + for (int i = 0; i < this.connectChildren.Count; i++) { - for (int i = 0; i < this.connectChildren.Count; i++) - { - this.connectChildren[i].LostConnectParent(); - } + this.connectChildren[i].LostConnectParent(); } - map.powerNetManager.Notify_TransmitterDespawned(this); - } - if (this.parent.def.ConnectToPower) - { - map.powerNetManager.Notify_ConnectorDespawned(this); } - map.mapDrawer.MapMeshDirty(this.parent.Position, MapMeshFlag.PowerGrid, true, false); + map.powerNetManager.Notify_TransmitterDespawned(this); } + if (base.parent.def.ConnectToPower) + { + map.powerNetManager.Notify_ConnectorDespawned(this); + } + map.mapDrawer.MapMeshDirty(base.parent.Position, MapMeshFlag.PowerGrid, true, false); } public virtual void LostConnectParent() { this.connectParent = null; - if (this.parent.Spawned) + if (base.parent.Spawned) { - this.parent.Map.powerNetManager.Notify_ConnectorWantsConnect(this); + base.parent.Map.powerNetManager.Notify_ConnectorWantsConnect(this); } } @@ -138,7 +137,7 @@ public override void PostPrintOnto(SectionLayer layer) base.PostPrintOnto(layer); if (this.connectParent != null) { - PowerNetGraphics.PrintWirePieceConnecting(layer, this.parent, this.connectParent.parent, false); + PowerNetGraphics.PrintWirePieceConnecting(layer, base.parent, this.connectParent.parent, false); } } @@ -146,26 +145,39 @@ public override void CompPrintForPowerGrid(SectionLayer layer) { if (this.TransmitsPowerNow) { - PowerOverlayMats.LinkedOverlayGraphic.Print(layer, this.parent); + PowerOverlayMats.LinkedOverlayGraphic.Print(layer, base.parent); } - if (this.parent.def.ConnectToPower) + if (base.parent.def.ConnectToPower) { - PowerNetGraphics.PrintOverlayConnectorBaseFor(layer, this.parent); + PowerNetGraphics.PrintOverlayConnectorBaseFor(layer, base.parent); } if (this.connectParent != null) { - PowerNetGraphics.PrintWirePieceConnecting(layer, this.parent, this.connectParent.parent, true); + PowerNetGraphics.PrintWirePieceConnecting(layer, base.parent, this.connectParent.parent, true); } } - [DebuggerHidden] public override IEnumerable CompGetGizmosExtra() { - CompPower.c__IteratorB2 c__IteratorB = new CompPower.c__IteratorB2(); - c__IteratorB.<>f__this = this; - CompPower.c__IteratorB2 expr_0E = c__IteratorB; - expr_0E.$PC = -2; - return expr_0E; + foreach (Gizmo item in base.CompGetGizmosExtra()) + { + yield return item; + } + if (this.connectParent != null && base.parent.Faction == Faction.OfPlayer) + { + yield return (Gizmo)new Command_Action + { + action = (Action)delegate + { + SoundDefOf.TickTiny.PlayOneShotOnCamera(null); + ((_003CCompGetGizmosExtra_003Ec__IteratorB2)/*Error near IL_00e5: stateMachine*/)._003C_003Ef__this.TryManualReconnect(); + }, + hotKey = KeyBindingDefOf.Misc1, + defaultDesc = "CommandTryReconnectDesc".Translate(), + icon = ContentFinder.Get("UI/Commands/TryReconnect", true), + defaultLabel = "CommandTryReconnectLabel".Translate() + }; + } } private void TryManualReconnect() @@ -179,11 +191,11 @@ private void TryManualReconnect() { CompPower.recentlyConnectedNets.Add(this.PowerNet); } - CompPower compPower = PowerConnectionMaker.BestTransmitterForConnector(this.parent.Position, this.parent.Map, CompPower.recentlyConnectedNets); + CompPower compPower = PowerConnectionMaker.BestTransmitterForConnector(base.parent.Position, base.parent.Map, CompPower.recentlyConnectedNets); if (compPower == null) { CompPower.recentlyConnectedNets.Clear(); - compPower = PowerConnectionMaker.BestTransmitterForConnector(this.parent.Position, this.parent.Map, null); + compPower = PowerConnectionMaker.BestTransmitterForConnector(base.parent.Position, base.parent.Map, null); } if (compPower != null) { @@ -193,8 +205,8 @@ private void TryManualReconnect() { MoteMaker.ThrowMetaPuff(compPower.parent.Position.ToVector3Shifted(), compPower.parent.Map); } - this.parent.Map.mapDrawer.MapMeshDirty(this.parent.Position, MapMeshFlag.PowerGrid); - this.parent.Map.mapDrawer.MapMeshDirty(this.parent.Position, MapMeshFlag.Things); + base.parent.Map.mapDrawer.MapMeshDirty(base.parent.Position, MapMeshFlag.PowerGrid); + base.parent.Map.mapDrawer.MapMeshDirty(base.parent.Position, MapMeshFlag.Things); } } @@ -202,28 +214,21 @@ public void ConnectToTransmitter(CompPower transmitter, bool reconnectingAfterLo { if (this.connectParent != null && (!reconnectingAfterLoading || this.connectParent != transmitter)) { - Log.Error(string.Concat(new object[] - { - "Tried to connect ", - this, - " to transmitter ", - transmitter, - " but it's already connected to ", - this.connectParent, - "." - })); - return; + Log.Error("Tried to connect " + this + " to transmitter " + transmitter + " but it's already connected to " + this.connectParent + "."); } - this.connectParent = transmitter; - if (this.connectParent.connectChildren == null) + else { - this.connectParent.connectChildren = new List(); - } - transmitter.connectChildren.Add(this); - PowerNet powerNet = this.PowerNet; - if (powerNet != null) - { - powerNet.RegisterConnector(this); + this.connectParent = transmitter; + if (this.connectParent.connectChildren == null) + { + this.connectParent.connectChildren = new List(); + } + transmitter.connectChildren.Add(this); + PowerNet powerNet = this.PowerNet; + if (powerNet != null) + { + powerNet.RegisterConnector(this); + } } } @@ -235,11 +240,7 @@ public override string CompInspectStringExtra() } string text = (this.PowerNet.CurrentEnergyGainRate() / CompPower.WattsToWattDaysPerTick).ToString("F0"); string text2 = this.PowerNet.CurrentStoredEnergy().ToString("F0"); - return "PowerConnectedRateStored".Translate(new object[] - { - text, - text2 - }); + return "PowerConnectedRateStored".Translate(text, text2); } } } diff --git a/Assembly-CSharp/RimWorld/CompPowerBattery.cs b/Assembly-CSharp/RimWorld/CompPowerBattery.cs index ca4aa96b6..62f9a124d 100644 --- a/Assembly-CSharp/RimWorld/CompPowerBattery.cs +++ b/Assembly-CSharp/RimWorld/CompPowerBattery.cs @@ -1,6 +1,5 @@ using System; using System.Collections.Generic; -using System.Diagnostics; using UnityEngine; using Verse; @@ -14,7 +13,7 @@ public float AmountCanAccept { get { - if (this.parent.IsBrokenDown()) + if (base.parent.IsBrokenDown()) { return 0f; } @@ -43,7 +42,7 @@ public float StoredEnergyPct { get { - return (CompProperties_Battery)this.props; + return (CompProperties_Battery)base.props; } } @@ -60,25 +59,27 @@ public override void PostExposeData() public void AddEnergy(float amount) { - if (amount < 0f) + if (amount < 0.0) { Log.Error("Cannot add negative energy " + amount); - return; } - if (amount > this.AmountCanAccept) + else { - amount = this.AmountCanAccept; + if (amount > this.AmountCanAccept) + { + amount = this.AmountCanAccept; + } + amount *= this.Props.efficiency; + this.storedEnergy += amount; } - amount *= this.Props.efficiency; - this.storedEnergy += amount; } public void DrawPower(float amount) { this.storedEnergy -= amount; - if (this.storedEnergy < 0f) + if (this.storedEnergy < 0.0) { - Log.Error("Drawing power we don't have from " + this.parent); + Log.Error("Drawing power we don't have from " + base.parent); this.storedEnergy = 0f; } } @@ -100,36 +101,37 @@ public override void ReceiveCompSignal(string signal) public override string CompInspectStringExtra() { CompProperties_Battery props = this.Props; - string text = string.Concat(new string[] - { - "PowerBatteryStored".Translate(), - ": ", - this.storedEnergy.ToString("F0"), - " / ", - props.storedEnergyMax.ToString("F0"), - " Wd" - }); - string text2 = text; - text = string.Concat(new string[] - { - text2, - "\n", - "PowerBatteryEfficiency".Translate(), - ": ", - (props.efficiency * 100f).ToString("F0"), - "%" - }); - return text + "\n" + base.CompInspectStringExtra(); + string text; + string text2 = text = "PowerBatteryStored".Translate() + ": " + this.storedEnergy.ToString("F0") + " / " + props.storedEnergyMax.ToString("F0") + " Wd"; + text2 = text + "\n" + "PowerBatteryEfficiency".Translate() + ": " + ((float)(props.efficiency * 100.0)).ToString("F0") + "%"; + return text2 + "\n" + base.CompInspectStringExtra(); } - [DebuggerHidden] public override IEnumerable CompGetGizmosExtra() { - CompPowerBattery.c__IteratorB3 c__IteratorB = new CompPowerBattery.c__IteratorB3(); - c__IteratorB.<>f__this = this; - CompPowerBattery.c__IteratorB3 expr_0E = c__IteratorB; - expr_0E.$PC = -2; - return expr_0E; + foreach (Gizmo item in base.CompGetGizmosExtra()) + { + yield return item; + } + if (Prefs.DevMode) + { + yield return (Gizmo)new Command_Action + { + defaultLabel = "DEBUG: Fill", + action = (Action)delegate + { + ((_003CCompGetGizmosExtra_003Ec__IteratorB3)/*Error near IL_00d9: stateMachine*/)._003C_003Ef__this.SetStoredEnergyPct(1f); + } + }; + yield return (Gizmo)new Command_Action + { + defaultLabel = "DEBUG: Empty", + action = (Action)delegate + { + ((_003CCompGetGizmosExtra_003Ec__IteratorB3)/*Error near IL_0123: stateMachine*/)._003C_003Ef__this.SetStoredEnergyPct(0f); + } + }; + } } } } diff --git a/Assembly-CSharp/RimWorld/CompPowerPlant.cs b/Assembly-CSharp/RimWorld/CompPowerPlant.cs index 8307e1ec7..cbd2f95ec 100644 --- a/Assembly-CSharp/RimWorld/CompPowerPlant.cs +++ b/Assembly-CSharp/RimWorld/CompPowerPlant.cs @@ -1,5 +1,3 @@ -using System; - namespace RimWorld { public class CompPowerPlant : CompPowerTrader @@ -12,16 +10,16 @@ protected virtual float DesiredPowerOutput { get { - return -base.Props.basePowerConsumption; + return (float)(0.0 - base.Props.basePowerConsumption); } } public override void PostSpawnSetup(bool respawningAfterLoad) { base.PostSpawnSetup(respawningAfterLoad); - this.refuelableComp = this.parent.GetComp(); - this.breakdownableComp = this.parent.GetComp(); - if (base.Props.basePowerConsumption < 0f && !this.parent.IsBrokenDown()) + this.refuelableComp = base.parent.GetComp(); + this.breakdownableComp = base.parent.GetComp(); + if (base.Props.basePowerConsumption < 0.0 && !base.parent.IsBrokenDown()) { base.PowerOn = true; } @@ -35,14 +33,24 @@ public override void CompTick() public void UpdateDesiredPowerOutput() { - if ((this.breakdownableComp != null && this.breakdownableComp.BrokenDown) || (this.refuelableComp != null && !this.refuelableComp.HasFuel) || (this.flickableComp != null && !this.flickableComp.SwitchIsOn) || !base.PowerOn) + if (this.breakdownableComp != null && this.breakdownableComp.BrokenDown) + { + goto IL_005c; + } + if (this.refuelableComp != null && !this.refuelableComp.HasFuel) { - base.PowerOutput = 0f; + goto IL_005c; } - else + if (base.flickableComp != null && !base.flickableComp.SwitchIsOn) { - base.PowerOutput = this.DesiredPowerOutput; + goto IL_005c; } + if (!base.PowerOn) + goto IL_005c; + base.PowerOutput = this.DesiredPowerOutput; + return; + IL_005c: + base.PowerOutput = 0f; } } } diff --git a/Assembly-CSharp/RimWorld/CompPowerPlantSolar.cs b/Assembly-CSharp/RimWorld/CompPowerPlantSolar.cs index d648fedf7..42247c0a3 100644 --- a/Assembly-CSharp/RimWorld/CompPowerPlantSolar.cs +++ b/Assembly-CSharp/RimWorld/CompPowerPlantSolar.cs @@ -1,4 +1,3 @@ -using System; using UnityEngine; using Verse; @@ -21,7 +20,7 @@ protected override float DesiredPowerOutput { get { - return Mathf.Lerp(0f, 1700f, this.parent.Map.skyManager.CurSkyGlow) * this.RoofedPowerOutputFactor; + return Mathf.Lerp(0f, 1700f, base.parent.Map.skyManager.CurSkyGlow) * this.RoofedPowerOutputFactor; } } @@ -31,10 +30,10 @@ private float RoofedPowerOutputFactor { int num = 0; int num2 = 0; - foreach (IntVec3 current in this.parent.OccupiedRect()) + foreach (IntVec3 item in base.parent.OccupiedRect()) { num++; - if (this.parent.Map.roofGrid.Roofed(current)) + if (base.parent.Map.roofGrid.Roofed(item)) { num2++; } @@ -46,14 +45,16 @@ private float RoofedPowerOutputFactor public override void PostDraw() { base.PostDraw(); - GenDraw.FillableBarRequest r = default(GenDraw.FillableBarRequest); - r.center = this.parent.DrawPos + Vector3.up * 0.1f; - r.size = CompPowerPlantSolar.BarSize; - r.fillPercent = base.PowerOutput / 1700f; - r.filledMat = CompPowerPlantSolar.PowerPlantSolarBarFilledMat; - r.unfilledMat = CompPowerPlantSolar.PowerPlantSolarBarUnfilledMat; - r.margin = 0.15f; - Rot4 rotation = this.parent.Rotation; + GenDraw.FillableBarRequest r = new GenDraw.FillableBarRequest + { + center = base.parent.DrawPos + Vector3.up * 0.1f, + size = CompPowerPlantSolar.BarSize, + fillPercent = (float)(base.PowerOutput / 1700.0), + filledMat = CompPowerPlantSolar.PowerPlantSolarBarFilledMat, + unfilledMat = CompPowerPlantSolar.PowerPlantSolarBarUnfilledMat, + margin = 0.15f + }; + Rot4 rotation = base.parent.Rotation; rotation.Rotate(RotationDirection.Clockwise); r.rotation = rotation; GenDraw.DrawFillableBar(r); diff --git a/Assembly-CSharp/RimWorld/CompPowerPlantSteam.cs b/Assembly-CSharp/RimWorld/CompPowerPlantSteam.cs index e8aee2f41..82bbe12a7 100644 --- a/Assembly-CSharp/RimWorld/CompPowerPlantSteam.cs +++ b/Assembly-CSharp/RimWorld/CompPowerPlantSteam.cs @@ -1,4 +1,3 @@ -using System; using Verse; namespace RimWorld @@ -12,7 +11,7 @@ public class CompPowerPlantSteam : CompPowerPlant public override void PostSpawnSetup(bool respawningAfterLoad) { base.PostSpawnSetup(respawningAfterLoad); - this.steamSprayer = new IntermittentSteamSprayer(this.parent); + this.steamSprayer = new IntermittentSteamSprayer(base.parent); } public override void CompTick() @@ -20,11 +19,11 @@ public override void CompTick() base.CompTick(); if (this.geyser == null) { - this.geyser = (Building_SteamGeyser)this.parent.Map.thingGrid.ThingAt(this.parent.Position, ThingDefOf.SteamGeyser); + this.geyser = (Building_SteamGeyser)base.parent.Map.thingGrid.ThingAt(base.parent.Position, ThingDefOf.SteamGeyser); } if (this.geyser != null) { - this.geyser.harvester = (Building)this.parent; + this.geyser.harvester = (Building)base.parent; this.steamSprayer.SteamSprayerTick(); } } diff --git a/Assembly-CSharp/RimWorld/CompPowerPlantWind.cs b/Assembly-CSharp/RimWorld/CompPowerPlantWind.cs index 14c322e58..255cb85f0 100644 --- a/Assembly-CSharp/RimWorld/CompPowerPlantWind.cs +++ b/Assembly-CSharp/RimWorld/CompPowerPlantWind.cs @@ -1,4 +1,3 @@ -using System; using System.Collections.Generic; using System.Text; using UnityEngine; @@ -53,14 +52,14 @@ private float PowerPercent { get { - return base.PowerOutput / (-base.Props.basePowerConsumption * 1.5f); + return (float)(base.PowerOutput / ((0.0 - base.Props.basePowerConsumption) * 1.5)); } } public override void PostSpawnSetup(bool respawningAfterLoad) { base.PostSpawnSetup(respawningAfterLoad); - CompPowerPlantWind.BarSize = new Vector2((float)this.parent.def.size.z - 0.95f, 0.14f); + CompPowerPlantWind.BarSize = new Vector2((float)((float)base.parent.def.size.z - 0.949999988079071), 0.14f); this.RecalculateBlockages(); this.spinPosition = Rand.Range(0f, 15f); } @@ -78,67 +77,69 @@ public override void CompTick() if (!base.PowerOn) { this.cachedPowerOutput = 0f; - return; } - this.ticksSinceWeatherUpdate++; - if (this.ticksSinceWeatherUpdate >= this.updateWeatherEveryXTicks) + else { - float num = Mathf.Min(this.parent.Map.windManager.WindSpeed, 1.5f); - this.ticksSinceWeatherUpdate = 0; - this.cachedPowerOutput = -(base.Props.basePowerConsumption * num); - this.RecalculateBlockages(); - if (this.windPathBlockedCells.Count > 0) + this.ticksSinceWeatherUpdate++; + if (this.ticksSinceWeatherUpdate >= this.updateWeatherEveryXTicks) { - float num2 = 0f; - for (int i = 0; i < this.windPathBlockedCells.Count; i++) + float num = Mathf.Min(base.parent.Map.windManager.WindSpeed, 1.5f); + this.ticksSinceWeatherUpdate = 0; + this.cachedPowerOutput = (float)(0.0 - base.Props.basePowerConsumption * num); + this.RecalculateBlockages(); + if (this.windPathBlockedCells.Count > 0) { - num2 += this.cachedPowerOutput * 0.2f; - } - this.cachedPowerOutput -= num2; - if (this.cachedPowerOutput < 0f) - { - this.cachedPowerOutput = 0f; + float num2 = 0f; + for (int i = 0; i < this.windPathBlockedCells.Count; i++) + { + num2 = (float)(num2 + this.cachedPowerOutput * 0.20000000298023224); + } + this.cachedPowerOutput -= num2; + if (this.cachedPowerOutput < 0.0) + { + this.cachedPowerOutput = 0f; + } } } - } - if (this.cachedPowerOutput > 0.01f) - { - this.spinPosition += this.PowerPercent * 0.05f; + if (this.cachedPowerOutput > 0.0099999997764825821) + { + this.spinPosition += (float)(this.PowerPercent * 0.05000000074505806); + } } } public override void PostDraw() { base.PostDraw(); - GenDraw.FillableBarRequest r = new GenDraw.FillableBarRequest - { - center = this.parent.DrawPos + Vector3.up * 0.1f, - size = CompPowerPlantWind.BarSize, - fillPercent = this.PowerPercent, - filledMat = CompPowerPlantWind.WindTurbineBarFilledMat, - unfilledMat = CompPowerPlantWind.WindTurbineBarUnfilledMat, - margin = 0.15f - }; - Rot4 rotation = this.parent.Rotation; + GenDraw.FillableBarRequest fillableBarRequest = default(GenDraw.FillableBarRequest); + GenDraw.FillableBarRequest fillableBarRequest2 = fillableBarRequest; + fillableBarRequest2.center = base.parent.DrawPos + Vector3.up * 0.1f; + fillableBarRequest2.size = CompPowerPlantWind.BarSize; + fillableBarRequest2.fillPercent = this.PowerPercent; + fillableBarRequest2.filledMat = CompPowerPlantWind.WindTurbineBarFilledMat; + fillableBarRequest2.unfilledMat = CompPowerPlantWind.WindTurbineBarUnfilledMat; + fillableBarRequest2.margin = 0.15f; + fillableBarRequest = fillableBarRequest2; + Rot4 rotation = base.parent.Rotation; rotation.Rotate(RotationDirection.Clockwise); - r.rotation = rotation; - GenDraw.DrawFillableBar(r); - Vector3 vector = this.parent.TrueCenter(); - vector += this.parent.Rotation.FacingCell.ToVector3() * 0.7f; + fillableBarRequest.rotation = rotation; + GenDraw.DrawFillableBar(fillableBarRequest); + Vector3 vector = base.parent.TrueCenter(); + vector += base.parent.Rotation.FacingCell.ToVector3() * 0.7f; vector.y += 0.046875f; - float num = 4f * Mathf.Sin(this.spinPosition); - if (num < 0f) + float num = (float)(4.0 * Mathf.Sin(this.spinPosition)); + if (num < 0.0) { - num *= -1f; + num = (float)(num * -1.0); } - bool flag = this.spinPosition % 3.14159274f * 2f < 3.14159274f; + bool flag = this.spinPosition % 3.1415927410125732 * 2.0 < 3.1415927410125732; Vector2 vector2 = new Vector2(num, 1f); Vector3 s = new Vector3(vector2.x, 1f, vector2.y); Matrix4x4 matrix = default(Matrix4x4); - matrix.SetTRS(vector, this.parent.Rotation.AsQuat, s); + matrix.SetTRS(vector, base.parent.Rotation.AsQuat, s); Graphics.DrawMesh((!flag) ? MeshPool.plane10Flip : MeshPool.plane10, matrix, CompPowerPlantWind.WindTurbineBladesMat, 0); vector.y -= 0.09375f; - matrix.SetTRS(vector, this.parent.Rotation.AsQuat, s); + matrix.SetTRS(vector, base.parent.Rotation.AsQuat, s); Graphics.DrawMesh((!flag) ? MeshPool.plane10 : MeshPool.plane10Flip, matrix, CompPowerPlantWind.WindTurbineBladesMat, 0); } @@ -170,7 +171,7 @@ private void RecalculateBlockages() { if (this.windPathCells.Count == 0) { - IEnumerable collection = WindTurbineUtility.CalculateWindCells(this.parent.Position, this.parent.Rotation, this.parent.def.size); + IEnumerable collection = WindTurbineUtility.CalculateWindCells(base.parent.Position, base.parent.Rotation, base.parent.def.size); this.windPathCells.AddRange(collection); } this.windPathBlockedCells.Clear(); @@ -178,14 +179,14 @@ private void RecalculateBlockages() for (int i = 0; i < this.windPathCells.Count; i++) { IntVec3 intVec = this.windPathCells[i]; - if (this.parent.Map.roofGrid.Roofed(intVec)) + if (base.parent.Map.roofGrid.Roofed(intVec)) { this.windPathBlockedByThings.Add(null); this.windPathBlockedCells.Add(intVec); } else { - List list = this.parent.Map.thingGrid.ThingsListAt(intVec); + List list = base.parent.Map.thingGrid.ThingsListAt(intVec); for (int j = 0; j < list.Count; j++) { Thing thing = list[j]; diff --git a/Assembly-CSharp/RimWorld/CompPowerTrader.cs b/Assembly-CSharp/RimWorld/CompPowerTrader.cs index 7f71055d4..35c8eea97 100644 --- a/Assembly-CSharp/RimWorld/CompPowerTrader.cs +++ b/Assembly-CSharp/RimWorld/CompPowerTrader.cs @@ -34,11 +34,11 @@ public float PowerOutput set { this.powerOutputInt = value; - if (this.powerOutputInt > 0f) + if (this.powerOutputInt > 0.0) { this.powerLastOutputted = true; } - if (this.powerOutputInt < 0f) + if (this.powerOutputInt < 0.0) { this.powerLastOutputted = false; } @@ -61,53 +61,53 @@ public bool PowerOn } set { - if (this.powerOnInt == value) + if (this.powerOnInt != value) { - return; - } - this.powerOnInt = value; - if (this.powerOnInt) - { - if (!FlickUtility.WantsToBeOn(this.parent)) - { - Log.Warning("Tried to power on " + this.parent + " which did not desire it."); - return; - } - if (this.parent.IsBrokenDown()) - { - Log.Warning("Tried to power on " + this.parent + " which is broken down."); - return; - } - if (this.powerStartedAction != null) - { - this.powerStartedAction(); - } - this.parent.BroadcastCompSignal("PowerTurnedOn"); - SoundDef soundDef = ((CompProperties_Power)this.parent.def.CompDefForAssignableFrom()).soundPowerOn; - if (soundDef.NullOrUndefined()) - { - soundDef = SoundDefOf.PowerOnSmall; - } - soundDef.PlayOneShot(new TargetInfo(this.parent.Position, this.parent.Map, false)); - this.StartSustainerPoweredIfInactive(); - } - else - { - if (this.powerStoppedAction != null) + this.powerOnInt = value; + if (this.powerOnInt) { - this.powerStoppedAction(); + if (!FlickUtility.WantsToBeOn(base.parent)) + { + Log.Warning("Tried to power on " + base.parent + " which did not desire it."); + } + else if (base.parent.IsBrokenDown()) + { + Log.Warning("Tried to power on " + base.parent + " which is broken down."); + } + else + { + if ((object)this.powerStartedAction != null) + { + this.powerStartedAction(); + } + base.parent.BroadcastCompSignal("PowerTurnedOn"); + SoundDef soundDef = ((CompProperties_Power)base.parent.def.CompDefForAssignableFrom()).soundPowerOn; + if (soundDef.NullOrUndefined()) + { + soundDef = SoundDefOf.PowerOnSmall; + } + soundDef.PlayOneShot(new TargetInfo(base.parent.Position, base.parent.Map, false)); + this.StartSustainerPoweredIfInactive(); + } } - this.parent.BroadcastCompSignal("PowerTurnedOff"); - SoundDef soundDef2 = ((CompProperties_Power)this.parent.def.CompDefForAssignableFrom()).soundPowerOff; - if (soundDef2.NullOrUndefined()) + else { - soundDef2 = SoundDefOf.PowerOffSmall; + if ((object)this.powerStoppedAction != null) + { + this.powerStoppedAction(); + } + base.parent.BroadcastCompSignal("PowerTurnedOff"); + SoundDef soundDef2 = ((CompProperties_Power)base.parent.def.CompDefForAssignableFrom()).soundPowerOff; + if (soundDef2.NullOrUndefined()) + { + soundDef2 = SoundDefOf.PowerOffSmall; + } + if (base.parent.Spawned) + { + soundDef2.PlayOneShot(new TargetInfo(base.parent.Position, base.parent.Map, false)); + } + this.EndSustainerPoweredIfActive(); } - if (this.parent.Spawned) - { - soundDef2.PlayOneShot(new TargetInfo(this.parent.Position, this.parent.Map, false)); - } - this.EndSustainerPoweredIfActive(); } } } @@ -117,7 +117,7 @@ public string DebugString get { StringBuilder stringBuilder = new StringBuilder(); - stringBuilder.AppendLine(this.parent.LabelCap + " CompPower:"); + stringBuilder.AppendLine(base.parent.LabelCap + " CompPower:"); stringBuilder.AppendLine(" PowerOn: " + this.PowerOn); stringBuilder.AppendLine(" energyProduction: " + this.PowerOutput); return stringBuilder.ToString(); @@ -139,7 +139,7 @@ public override void ReceiveCompSignal(string signal) public override void PostSpawnSetup(bool respawningAfterLoad) { base.PostSpawnSetup(respawningAfterLoad); - this.flickableComp = this.parent.GetComp(); + this.flickableComp = base.parent.GetComp(); } public override void PostDeSpawn(Map map) @@ -158,18 +158,15 @@ public override void PostExposeData() public override void PostDraw() { base.PostDraw(); - if (!this.parent.IsBrokenDown()) + if (!base.parent.IsBrokenDown()) { if (this.flickableComp != null && !this.flickableComp.SwitchIsOn) { - this.parent.Map.overlayDrawer.DrawOverlay(this.parent, OverlayTypes.PowerOff); + base.parent.Map.overlayDrawer.DrawOverlay(base.parent, OverlayTypes.PowerOff); } - else if (FlickUtility.WantsToBeOn(this.parent)) + else if (FlickUtility.WantsToBeOn(base.parent) && !this.PowerOn) { - if (!this.PowerOn) - { - this.parent.Map.overlayDrawer.DrawOverlay(this.parent, OverlayTypes.NeedsPower); - } + base.parent.Map.overlayDrawer.DrawOverlay(base.parent, OverlayTypes.NeedsPower); } } } @@ -178,8 +175,8 @@ public override void SetUpPowerVars() { base.SetUpPowerVars(); CompProperties_Power props = base.Props; - this.PowerOutput = -1f * props.basePowerConsumption; - this.powerLastOutputted = (props.basePowerConsumption <= 0f); + this.PowerOutput = (float)(-1.0 * props.basePowerConsumption); + this.powerLastOutputted = (props.basePowerConsumption <= 0.0); } public override void ResetPowerVars() @@ -203,15 +200,7 @@ public override void LostConnectParent() public override string CompInspectStringExtra() { - string str; - if (this.powerLastOutputted) - { - str = "PowerOutput".Translate() + ": " + this.PowerOutput.ToString("#####0") + " W"; - } - else - { - str = "PowerNeeded".Translate() + ": " + (-this.PowerOutput).ToString("#####0") + " W"; - } + string str = (!this.powerLastOutputted) ? ("PowerNeeded".Translate() + ": " + ((float)(0.0 - this.PowerOutput)).ToString("#####0") + " W") : ("PowerOutput".Translate() + ": " + this.PowerOutput.ToString("#####0") + " W"); return str + "\n" + base.CompInspectStringExtra(); } @@ -220,7 +209,7 @@ private void StartSustainerPoweredIfInactive() CompProperties_Power props = base.Props; if (!props.soundAmbientPowered.NullOrUndefined() && this.sustainerPowered == null) { - SoundInfo info = SoundInfo.InMap(this.parent, MaintenanceType.None); + SoundInfo info = SoundInfo.InMap((Thing)base.parent, MaintenanceType.None); this.sustainerPowered = props.soundAmbientPowered.TrySpawnSustainer(info); } } diff --git a/Assembly-CSharp/RimWorld/CompPowerTransmitter.cs b/Assembly-CSharp/RimWorld/CompPowerTransmitter.cs index 733f56fca..88cf03689 100644 --- a/Assembly-CSharp/RimWorld/CompPowerTransmitter.cs +++ b/Assembly-CSharp/RimWorld/CompPowerTransmitter.cs @@ -1,5 +1,3 @@ -using System; - namespace RimWorld { public class CompPowerTransmitter : CompPower diff --git a/Assembly-CSharp/RimWorld/CompProperties_AffectedByFacilities.cs b/Assembly-CSharp/RimWorld/CompProperties_AffectedByFacilities.cs index 4ab24e0db..cb5fc7394 100644 --- a/Assembly-CSharp/RimWorld/CompProperties_AffectedByFacilities.cs +++ b/Assembly-CSharp/RimWorld/CompProperties_AffectedByFacilities.cs @@ -1,4 +1,3 @@ -using System; using System.Collections.Generic; using Verse; @@ -10,7 +9,7 @@ public class CompProperties_AffectedByFacilities : CompProperties public CompProperties_AffectedByFacilities() { - this.compClass = typeof(CompAffectedByFacilities); + base.compClass = typeof(CompAffectedByFacilities); } } } diff --git a/Assembly-CSharp/RimWorld/CompProperties_Art.cs b/Assembly-CSharp/RimWorld/CompProperties_Art.cs index c000e0a63..6be276e43 100644 --- a/Assembly-CSharp/RimWorld/CompProperties_Art.cs +++ b/Assembly-CSharp/RimWorld/CompProperties_Art.cs @@ -1,4 +1,3 @@ -using System; using Verse; namespace RimWorld @@ -17,7 +16,7 @@ public class CompProperties_Art : CompProperties public CompProperties_Art() { - this.compClass = typeof(CompArt); + base.compClass = typeof(CompArt); } } } diff --git a/Assembly-CSharp/RimWorld/CompProperties_Battery.cs b/Assembly-CSharp/RimWorld/CompProperties_Battery.cs index 932882b98..b3f250655 100644 --- a/Assembly-CSharp/RimWorld/CompProperties_Battery.cs +++ b/Assembly-CSharp/RimWorld/CompProperties_Battery.cs @@ -1,5 +1,3 @@ -using System; - namespace RimWorld { public class CompProperties_Battery : CompProperties_Power @@ -10,7 +8,7 @@ public class CompProperties_Battery : CompProperties_Power public CompProperties_Battery() { - this.compClass = typeof(CompPowerBattery); + base.compClass = typeof(CompPowerBattery); } } } diff --git a/Assembly-CSharp/RimWorld/CompProperties_Breakdownable.cs b/Assembly-CSharp/RimWorld/CompProperties_Breakdownable.cs index d935d1c0c..6e054065d 100644 --- a/Assembly-CSharp/RimWorld/CompProperties_Breakdownable.cs +++ b/Assembly-CSharp/RimWorld/CompProperties_Breakdownable.cs @@ -1,4 +1,3 @@ -using System; using Verse; namespace RimWorld @@ -7,7 +6,7 @@ public class CompProperties_Breakdownable : CompProperties { public CompProperties_Breakdownable() { - this.compClass = typeof(CompBreakdownable); + base.compClass = typeof(CompBreakdownable); } } } diff --git a/Assembly-CSharp/RimWorld/CompProperties_Drug.cs b/Assembly-CSharp/RimWorld/CompProperties_Drug.cs index b72424cce..68650fdbc 100644 --- a/Assembly-CSharp/RimWorld/CompProperties_Drug.cs +++ b/Assembly-CSharp/RimWorld/CompProperties_Drug.cs @@ -1,6 +1,4 @@ -using System; using System.Collections.Generic; -using System.Diagnostics; using Verse; namespace RimWorld @@ -29,7 +27,7 @@ public bool Addictive { get { - return this.addictiveness > 0f; + return this.addictiveness > 0.0; } } @@ -37,35 +35,37 @@ public bool CanCauseOverdose { get { - return this.overdoseSeverityOffset.TrueMax > 0f; + return this.overdoseSeverityOffset.TrueMax > 0.0; } } public CompProperties_Drug() { - this.compClass = typeof(CompDrug); + base.compClass = typeof(CompDrug); } - [DebuggerHidden] public override IEnumerable ConfigErrors(ThingDef parentDef) { - CompProperties_Drug.c__Iterator7B c__Iterator7B = new CompProperties_Drug.c__Iterator7B(); - c__Iterator7B.parentDef = parentDef; - c__Iterator7B.<$>parentDef = parentDef; - c__Iterator7B.<>f__this = this; - CompProperties_Drug.c__Iterator7B expr_1C = c__Iterator7B; - expr_1C.$PC = -2; - return expr_1C; + foreach (string item in base.ConfigErrors(parentDef)) + { + yield return item; + } + if (this.Addictive && this.chemical == null) + { + yield return "addictive but chemical is null"; + } } - [DebuggerHidden] public override IEnumerable SpecialDisplayStats() { - CompProperties_Drug.c__Iterator7C c__Iterator7C = new CompProperties_Drug.c__Iterator7C(); - c__Iterator7C.<>f__this = this; - CompProperties_Drug.c__Iterator7C expr_0E = c__Iterator7C; - expr_0E.$PC = -2; - return expr_0E; + foreach (StatDrawEntry item in base.SpecialDisplayStats()) + { + yield return item; + } + if (this.Addictive) + { + yield return new StatDrawEntry(StatCategoryDefOf.Basics, "Addictiveness".Translate(), this.addictiveness.ToStringPercent(), 0); + } } } } diff --git a/Assembly-CSharp/RimWorld/CompProperties_EggLayer.cs b/Assembly-CSharp/RimWorld/CompProperties_EggLayer.cs index 216c7d9dd..edd2c9401 100644 --- a/Assembly-CSharp/RimWorld/CompProperties_EggLayer.cs +++ b/Assembly-CSharp/RimWorld/CompProperties_EggLayer.cs @@ -1,4 +1,3 @@ -using System; using Verse; namespace RimWorld @@ -21,7 +20,7 @@ public class CompProperties_EggLayer : CompProperties public CompProperties_EggLayer() { - this.compClass = typeof(CompEggLayer); + base.compClass = typeof(CompEggLayer); } } } diff --git a/Assembly-CSharp/RimWorld/CompProperties_Explosive.cs b/Assembly-CSharp/RimWorld/CompProperties_Explosive.cs index 07bf43192..3afb88a75 100644 --- a/Assembly-CSharp/RimWorld/CompProperties_Explosive.cs +++ b/Assembly-CSharp/RimWorld/CompProperties_Explosive.cs @@ -1,4 +1,3 @@ -using System; using Verse; namespace RimWorld @@ -39,7 +38,7 @@ public class CompProperties_Explosive : CompProperties public CompProperties_Explosive() { - this.compClass = typeof(CompExplosive); + base.compClass = typeof(CompExplosive); } } } diff --git a/Assembly-CSharp/RimWorld/CompProperties_Facility.cs b/Assembly-CSharp/RimWorld/CompProperties_Facility.cs index 40bc39435..0e1b36846 100644 --- a/Assembly-CSharp/RimWorld/CompProperties_Facility.cs +++ b/Assembly-CSharp/RimWorld/CompProperties_Facility.cs @@ -1,4 +1,3 @@ -using System; using System.Collections.Generic; using Verse; @@ -19,7 +18,7 @@ public class CompProperties_Facility : CompProperties public CompProperties_Facility() { - this.compClass = typeof(CompFacility); + base.compClass = typeof(CompFacility); } public override void ResolveReferences(ThingDef parentDef) @@ -31,13 +30,16 @@ public override void ResolveReferences(ThingDef parentDef) CompProperties_AffectedByFacilities compProperties = allDefsListForReading[i].GetCompProperties(); if (compProperties != null && compProperties.linkableFacilities != null) { - for (int j = 0; j < compProperties.linkableFacilities.Count; j++) + int num = 0; + while (num < compProperties.linkableFacilities.Count) { - if (compProperties.linkableFacilities[j] == parentDef) + if (compProperties.linkableFacilities[num] != parentDef) { - this.linkableBuildings.Add(allDefsListForReading[i]); - break; + num++; + continue; } + this.linkableBuildings.Add(allDefsListForReading[i]); + break; } } } diff --git a/Assembly-CSharp/RimWorld/CompProperties_FireOverlay.cs b/Assembly-CSharp/RimWorld/CompProperties_FireOverlay.cs index 1916671fe..1588bd46c 100644 --- a/Assembly-CSharp/RimWorld/CompProperties_FireOverlay.cs +++ b/Assembly-CSharp/RimWorld/CompProperties_FireOverlay.cs @@ -1,4 +1,3 @@ -using System; using UnityEngine; using Verse; @@ -12,7 +11,7 @@ public class CompProperties_FireOverlay : CompProperties public CompProperties_FireOverlay() { - this.compClass = typeof(CompFireOverlay); + base.compClass = typeof(CompFireOverlay); } } } diff --git a/Assembly-CSharp/RimWorld/CompProperties_Flickable.cs b/Assembly-CSharp/RimWorld/CompProperties_Flickable.cs index c5e70056e..24bd4c9b9 100644 --- a/Assembly-CSharp/RimWorld/CompProperties_Flickable.cs +++ b/Assembly-CSharp/RimWorld/CompProperties_Flickable.cs @@ -1,4 +1,3 @@ -using System; using Verse; namespace RimWorld @@ -13,7 +12,7 @@ public class CompProperties_Flickable : CompProperties public CompProperties_Flickable() { - this.compClass = typeof(CompFlickable); + base.compClass = typeof(CompFlickable); } } } diff --git a/Assembly-CSharp/RimWorld/CompProperties_FoodPoisonable.cs b/Assembly-CSharp/RimWorld/CompProperties_FoodPoisonable.cs index 3e5a979a7..13fddb204 100644 --- a/Assembly-CSharp/RimWorld/CompProperties_FoodPoisonable.cs +++ b/Assembly-CSharp/RimWorld/CompProperties_FoodPoisonable.cs @@ -1,4 +1,3 @@ -using System; using Verse; namespace RimWorld @@ -7,7 +6,7 @@ public class CompProperties_FoodPoisonable : CompProperties { public CompProperties_FoodPoisonable() { - this.compClass = typeof(CompFoodPoisonable); + base.compClass = typeof(CompFoodPoisonable); } } } diff --git a/Assembly-CSharp/RimWorld/CompProperties_FoodPoisoningChance.cs b/Assembly-CSharp/RimWorld/CompProperties_FoodPoisoningChance.cs index 95c94aa6e..2daf7784b 100644 --- a/Assembly-CSharp/RimWorld/CompProperties_FoodPoisoningChance.cs +++ b/Assembly-CSharp/RimWorld/CompProperties_FoodPoisoningChance.cs @@ -1,4 +1,3 @@ -using System; using Verse; namespace RimWorld @@ -11,7 +10,7 @@ public class CompProperties_FoodPoisoningChance : CompProperties public CompProperties_FoodPoisoningChance() { - this.compClass = typeof(CompFoodPoisoningChance); + base.compClass = typeof(CompFoodPoisoningChance); } } } diff --git a/Assembly-CSharp/RimWorld/CompProperties_Forbiddable.cs b/Assembly-CSharp/RimWorld/CompProperties_Forbiddable.cs index 89e33cc37..45883ce5b 100644 --- a/Assembly-CSharp/RimWorld/CompProperties_Forbiddable.cs +++ b/Assembly-CSharp/RimWorld/CompProperties_Forbiddable.cs @@ -1,4 +1,3 @@ -using System; using Verse; namespace RimWorld @@ -7,7 +6,7 @@ public class CompProperties_Forbiddable : CompProperties { public CompProperties_Forbiddable() { - this.compClass = typeof(CompForbiddable); + base.compClass = typeof(CompForbiddable); } } } diff --git a/Assembly-CSharp/RimWorld/CompProperties_Glower.cs b/Assembly-CSharp/RimWorld/CompProperties_Glower.cs index ec6ab442a..e426a08ff 100644 --- a/Assembly-CSharp/RimWorld/CompProperties_Glower.cs +++ b/Assembly-CSharp/RimWorld/CompProperties_Glower.cs @@ -1,4 +1,3 @@ -using System; using Verse; namespace RimWorld @@ -13,7 +12,7 @@ public class CompProperties_Glower : CompProperties public CompProperties_Glower() { - this.compClass = typeof(CompGlower); + base.compClass = typeof(CompGlower); } } } diff --git a/Assembly-CSharp/RimWorld/CompProperties_Hatcher.cs b/Assembly-CSharp/RimWorld/CompProperties_Hatcher.cs index 8469069c2..0608ae0b9 100644 --- a/Assembly-CSharp/RimWorld/CompProperties_Hatcher.cs +++ b/Assembly-CSharp/RimWorld/CompProperties_Hatcher.cs @@ -1,4 +1,3 @@ -using System; using Verse; namespace RimWorld @@ -11,7 +10,7 @@ public class CompProperties_Hatcher : CompProperties public CompProperties_Hatcher() { - this.compClass = typeof(CompHatcher); + base.compClass = typeof(CompHatcher); } } } diff --git a/Assembly-CSharp/RimWorld/CompProperties_Ingredients.cs b/Assembly-CSharp/RimWorld/CompProperties_Ingredients.cs index a4b21b783..b696d7603 100644 --- a/Assembly-CSharp/RimWorld/CompProperties_Ingredients.cs +++ b/Assembly-CSharp/RimWorld/CompProperties_Ingredients.cs @@ -1,4 +1,3 @@ -using System; using Verse; namespace RimWorld @@ -7,7 +6,7 @@ public class CompProperties_Ingredients : CompProperties { public CompProperties_Ingredients() { - this.compClass = typeof(CompIngredients); + base.compClass = typeof(CompIngredients); } } } diff --git a/Assembly-CSharp/RimWorld/CompProperties_Launchable.cs b/Assembly-CSharp/RimWorld/CompProperties_Launchable.cs index 8b8344267..845a4f6d1 100644 --- a/Assembly-CSharp/RimWorld/CompProperties_Launchable.cs +++ b/Assembly-CSharp/RimWorld/CompProperties_Launchable.cs @@ -1,4 +1,3 @@ -using System; using Verse; namespace RimWorld @@ -7,7 +6,7 @@ public class CompProperties_Launchable : CompProperties { public CompProperties_Launchable() { - this.compClass = typeof(CompLaunchable); + base.compClass = typeof(CompLaunchable); } } } diff --git a/Assembly-CSharp/RimWorld/CompProperties_LongRangeMineralScanner.cs b/Assembly-CSharp/RimWorld/CompProperties_LongRangeMineralScanner.cs index d2aff6fa9..89be5f93d 100644 --- a/Assembly-CSharp/RimWorld/CompProperties_LongRangeMineralScanner.cs +++ b/Assembly-CSharp/RimWorld/CompProperties_LongRangeMineralScanner.cs @@ -1,4 +1,3 @@ -using System; using Verse; namespace RimWorld @@ -11,7 +10,7 @@ public class CompProperties_LongRangeMineralScanner : CompProperties public CompProperties_LongRangeMineralScanner() { - this.compClass = typeof(CompLongRangeMineralScanner); + base.compClass = typeof(CompLongRangeMineralScanner); } } } diff --git a/Assembly-CSharp/RimWorld/CompProperties_Maintainable.cs b/Assembly-CSharp/RimWorld/CompProperties_Maintainable.cs index 94d0261df..1e885c8dc 100644 --- a/Assembly-CSharp/RimWorld/CompProperties_Maintainable.cs +++ b/Assembly-CSharp/RimWorld/CompProperties_Maintainable.cs @@ -1,4 +1,3 @@ -using System; using Verse; namespace RimWorld @@ -13,7 +12,7 @@ public class CompProperties_Maintainable : CompProperties public CompProperties_Maintainable() { - this.compClass = typeof(CompMaintainable); + base.compClass = typeof(CompMaintainable); } } } diff --git a/Assembly-CSharp/RimWorld/CompProperties_Mannable.cs b/Assembly-CSharp/RimWorld/CompProperties_Mannable.cs index b4e25bba1..21df3eaa8 100644 --- a/Assembly-CSharp/RimWorld/CompProperties_Mannable.cs +++ b/Assembly-CSharp/RimWorld/CompProperties_Mannable.cs @@ -1,4 +1,3 @@ -using System; using Verse; namespace RimWorld @@ -9,7 +8,7 @@ public class CompProperties_Mannable : CompProperties public CompProperties_Mannable() { - this.compClass = typeof(CompMannable); + base.compClass = typeof(CompMannable); } } } diff --git a/Assembly-CSharp/RimWorld/CompProperties_Milkable.cs b/Assembly-CSharp/RimWorld/CompProperties_Milkable.cs index 663350cf3..7b3c0b78a 100644 --- a/Assembly-CSharp/RimWorld/CompProperties_Milkable.cs +++ b/Assembly-CSharp/RimWorld/CompProperties_Milkable.cs @@ -1,4 +1,3 @@ -using System; using Verse; namespace RimWorld @@ -15,7 +14,7 @@ public class CompProperties_Milkable : CompProperties public CompProperties_Milkable() { - this.compClass = typeof(CompMilkable); + base.compClass = typeof(CompMilkable); } } } diff --git a/Assembly-CSharp/RimWorld/CompProperties_Power.cs b/Assembly-CSharp/RimWorld/CompProperties_Power.cs index 2098ca6bd..9d4fe1c82 100644 --- a/Assembly-CSharp/RimWorld/CompProperties_Power.cs +++ b/Assembly-CSharp/RimWorld/CompProperties_Power.cs @@ -1,6 +1,4 @@ -using System; using System.Collections.Generic; -using System.Diagnostics; using Verse; namespace RimWorld @@ -21,16 +19,12 @@ public class CompProperties_Power : CompProperties public SoundDef soundAmbientPowered; - [DebuggerHidden] public override IEnumerable ConfigErrors(ThingDef parentDef) { - CompProperties_Power.c__Iterator7A c__Iterator7A = new CompProperties_Power.c__Iterator7A(); - c__Iterator7A.parentDef = parentDef; - c__Iterator7A.<$>parentDef = parentDef; - c__Iterator7A.<>f__this = this; - CompProperties_Power.c__Iterator7A expr_1C = c__Iterator7A; - expr_1C.$PC = -2; - return expr_1C; + foreach (string item in base.ConfigErrors(parentDef)) + { + yield return item; + } } } } diff --git a/Assembly-CSharp/RimWorld/CompProperties_Refuelable.cs b/Assembly-CSharp/RimWorld/CompProperties_Refuelable.cs index 27b3ab556..294f9ab1e 100644 --- a/Assembly-CSharp/RimWorld/CompProperties_Refuelable.cs +++ b/Assembly-CSharp/RimWorld/CompProperties_Refuelable.cs @@ -1,4 +1,3 @@ -using System; using Verse; namespace RimWorld @@ -31,7 +30,7 @@ public class CompProperties_Refuelable : CompProperties public CompProperties_Refuelable() { - this.compClass = typeof(CompRefuelable); + base.compClass = typeof(CompRefuelable); } public override void ResolveReferences(ThingDef parentDef) diff --git a/Assembly-CSharp/RimWorld/CompProperties_RoomIdentifier.cs b/Assembly-CSharp/RimWorld/CompProperties_RoomIdentifier.cs index c072fc2bb..1c54206b5 100644 --- a/Assembly-CSharp/RimWorld/CompProperties_RoomIdentifier.cs +++ b/Assembly-CSharp/RimWorld/CompProperties_RoomIdentifier.cs @@ -1,4 +1,3 @@ -using System; using Verse; namespace RimWorld @@ -9,7 +8,7 @@ public class CompProperties_RoomIdentifier : CompProperties public CompProperties_RoomIdentifier() { - this.compClass = typeof(CompRoomIdentifier); + base.compClass = typeof(CompRoomIdentifier); } } } diff --git a/Assembly-CSharp/RimWorld/CompProperties_Rottable.cs b/Assembly-CSharp/RimWorld/CompProperties_Rottable.cs index d727c6490..25e7e2d18 100644 --- a/Assembly-CSharp/RimWorld/CompProperties_Rottable.cs +++ b/Assembly-CSharp/RimWorld/CompProperties_Rottable.cs @@ -1,6 +1,4 @@ -using System; using System.Collections.Generic; -using System.Diagnostics; using UnityEngine; using Verse; @@ -22,7 +20,7 @@ public int TicksToRotStart { get { - return Mathf.RoundToInt(this.daysToRotStart * 60000f); + return Mathf.RoundToInt((float)(this.daysToRotStart * 60000.0)); } } @@ -30,13 +28,13 @@ public int TicksToDessicated { get { - return Mathf.RoundToInt(this.daysToDessicated * 60000f); + return Mathf.RoundToInt((float)(this.daysToDessicated * 60000.0)); } } public CompProperties_Rottable() { - this.compClass = typeof(CompRottable); + base.compClass = typeof(CompRottable); } public CompProperties_Rottable(float daysToRotStart) @@ -44,16 +42,16 @@ public CompProperties_Rottable(float daysToRotStart) this.daysToRotStart = daysToRotStart; } - [DebuggerHidden] public override IEnumerable ConfigErrors(ThingDef parentDef) { - CompProperties_Rottable.c__Iterator7D c__Iterator7D = new CompProperties_Rottable.c__Iterator7D(); - c__Iterator7D.parentDef = parentDef; - c__Iterator7D.<$>parentDef = parentDef; - c__Iterator7D.<>f__this = this; - CompProperties_Rottable.c__Iterator7D expr_1C = c__Iterator7D; - expr_1C.$PC = -2; - return expr_1C; + foreach (string item in base.ConfigErrors(parentDef)) + { + yield return item; + } + if (parentDef.tickerType != TickerType.Rare) + { + yield return "CompRottable needs tickerType " + TickerType.Rare + ", has " + parentDef.tickerType; + } } } } diff --git a/Assembly-CSharp/RimWorld/CompProperties_Schedule.cs b/Assembly-CSharp/RimWorld/CompProperties_Schedule.cs index a89d3078a..736639551 100644 --- a/Assembly-CSharp/RimWorld/CompProperties_Schedule.cs +++ b/Assembly-CSharp/RimWorld/CompProperties_Schedule.cs @@ -1,4 +1,3 @@ -using System; using Verse; namespace RimWorld @@ -13,7 +12,7 @@ public class CompProperties_Schedule : CompProperties public CompProperties_Schedule() { - this.compClass = typeof(CompSchedule); + base.compClass = typeof(CompSchedule); } } } diff --git a/Assembly-CSharp/RimWorld/CompProperties_Shearable.cs b/Assembly-CSharp/RimWorld/CompProperties_Shearable.cs index 9113a46f2..2d192428f 100644 --- a/Assembly-CSharp/RimWorld/CompProperties_Shearable.cs +++ b/Assembly-CSharp/RimWorld/CompProperties_Shearable.cs @@ -1,4 +1,3 @@ -using System; using Verse; namespace RimWorld @@ -13,7 +12,7 @@ public class CompProperties_Shearable : CompProperties public CompProperties_Shearable() { - this.compClass = typeof(CompShearable); + base.compClass = typeof(CompShearable); } } } diff --git a/Assembly-CSharp/RimWorld/CompProperties_ShipPart.cs b/Assembly-CSharp/RimWorld/CompProperties_ShipPart.cs index e3292f0f4..e6480939a 100644 --- a/Assembly-CSharp/RimWorld/CompProperties_ShipPart.cs +++ b/Assembly-CSharp/RimWorld/CompProperties_ShipPart.cs @@ -1,4 +1,3 @@ -using System; using Verse; namespace RimWorld @@ -7,7 +6,7 @@ public class CompProperties_ShipPart : CompProperties { public CompProperties_ShipPart() { - this.compClass = typeof(CompShipPart); + base.compClass = typeof(CompShipPart); } } } diff --git a/Assembly-CSharp/RimWorld/CompProperties_Spawner.cs b/Assembly-CSharp/RimWorld/CompProperties_Spawner.cs index 8e46b42ef..c78f14c70 100644 --- a/Assembly-CSharp/RimWorld/CompProperties_Spawner.cs +++ b/Assembly-CSharp/RimWorld/CompProperties_Spawner.cs @@ -1,4 +1,3 @@ -using System; using Verse; namespace RimWorld @@ -17,7 +16,7 @@ public class CompProperties_Spawner : CompProperties public CompProperties_Spawner() { - this.compClass = typeof(CompSpawner); + base.compClass = typeof(CompSpawner); } } } diff --git a/Assembly-CSharp/RimWorld/CompProperties_SpawnerFilth.cs b/Assembly-CSharp/RimWorld/CompProperties_SpawnerFilth.cs index 49a514493..9db625d30 100644 --- a/Assembly-CSharp/RimWorld/CompProperties_SpawnerFilth.cs +++ b/Assembly-CSharp/RimWorld/CompProperties_SpawnerFilth.cs @@ -1,4 +1,3 @@ -using System; using Verse; namespace RimWorld @@ -19,7 +18,7 @@ public class CompProperties_SpawnerFilth : CompProperties public CompProperties_SpawnerFilth() { - this.compClass = typeof(CompSpawnerFilth); + base.compClass = typeof(CompSpawnerFilth); } } } diff --git a/Assembly-CSharp/RimWorld/CompProperties_SpawnerHives.cs b/Assembly-CSharp/RimWorld/CompProperties_SpawnerHives.cs index 78a2e7689..f7a97c40c 100644 --- a/Assembly-CSharp/RimWorld/CompProperties_SpawnerHives.cs +++ b/Assembly-CSharp/RimWorld/CompProperties_SpawnerHives.cs @@ -1,4 +1,3 @@ -using System; using Verse; namespace RimWorld @@ -13,7 +12,7 @@ public class CompProperties_SpawnerHives : CompProperties public CompProperties_SpawnerHives() { - this.compClass = typeof(CompSpawnerHives); + base.compClass = typeof(CompSpawnerHives); } } } diff --git a/Assembly-CSharp/RimWorld/CompProperties_Targetable.cs b/Assembly-CSharp/RimWorld/CompProperties_Targetable.cs index 957acf50f..2e239498b 100644 --- a/Assembly-CSharp/RimWorld/CompProperties_Targetable.cs +++ b/Assembly-CSharp/RimWorld/CompProperties_Targetable.cs @@ -1,5 +1,3 @@ -using System; - namespace RimWorld { public class CompProperties_Targetable : CompProperties_UseEffect @@ -8,7 +6,7 @@ public class CompProperties_Targetable : CompProperties_UseEffect public CompProperties_Targetable() { - this.compClass = typeof(CompTargetable); + base.compClass = typeof(CompTargetable); } } } diff --git a/Assembly-CSharp/RimWorld/CompProperties_TempControl.cs b/Assembly-CSharp/RimWorld/CompProperties_TempControl.cs index 4644540ba..1fa6774d9 100644 --- a/Assembly-CSharp/RimWorld/CompProperties_TempControl.cs +++ b/Assembly-CSharp/RimWorld/CompProperties_TempControl.cs @@ -1,4 +1,3 @@ -using System; using Verse; namespace RimWorld @@ -17,7 +16,7 @@ public class CompProperties_TempControl : CompProperties public CompProperties_TempControl() { - this.compClass = typeof(CompTempControl); + base.compClass = typeof(CompTempControl); } } } diff --git a/Assembly-CSharp/RimWorld/CompProperties_TemperatureRuinable.cs b/Assembly-CSharp/RimWorld/CompProperties_TemperatureRuinable.cs index 671821a94..da32b46c3 100644 --- a/Assembly-CSharp/RimWorld/CompProperties_TemperatureRuinable.cs +++ b/Assembly-CSharp/RimWorld/CompProperties_TemperatureRuinable.cs @@ -1,4 +1,3 @@ -using System; using Verse; namespace RimWorld @@ -13,7 +12,7 @@ public class CompProperties_TemperatureRuinable : CompProperties public CompProperties_TemperatureRuinable() { - this.compClass = typeof(CompTemperatureRuinable); + base.compClass = typeof(CompTemperatureRuinable); } } } diff --git a/Assembly-CSharp/RimWorld/CompProperties_TerrainPump.cs b/Assembly-CSharp/RimWorld/CompProperties_TerrainPump.cs index 3ff32b348..3a43c6b44 100644 --- a/Assembly-CSharp/RimWorld/CompProperties_TerrainPump.cs +++ b/Assembly-CSharp/RimWorld/CompProperties_TerrainPump.cs @@ -1,4 +1,3 @@ -using System; using Verse; namespace RimWorld diff --git a/Assembly-CSharp/RimWorld/CompProperties_TerrainPumpDry.cs b/Assembly-CSharp/RimWorld/CompProperties_TerrainPumpDry.cs index c10792e8e..a235cea45 100644 --- a/Assembly-CSharp/RimWorld/CompProperties_TerrainPumpDry.cs +++ b/Assembly-CSharp/RimWorld/CompProperties_TerrainPumpDry.cs @@ -1,12 +1,10 @@ -using System; - namespace RimWorld { public class CompProperties_TerrainPumpDry : CompProperties_TerrainPump { public CompProperties_TerrainPumpDry() { - this.compClass = typeof(CompTerrainPumpDry); + base.compClass = typeof(CompTerrainPumpDry); } } } diff --git a/Assembly-CSharp/RimWorld/CompProperties_Transporter.cs b/Assembly-CSharp/RimWorld/CompProperties_Transporter.cs index 39c501c7a..d30b01ed0 100644 --- a/Assembly-CSharp/RimWorld/CompProperties_Transporter.cs +++ b/Assembly-CSharp/RimWorld/CompProperties_Transporter.cs @@ -1,4 +1,3 @@ -using System; using Verse; namespace RimWorld @@ -9,7 +8,7 @@ public class CompProperties_Transporter : CompProperties public CompProperties_Transporter() { - this.compClass = typeof(CompTransporter); + base.compClass = typeof(CompTransporter); } } } diff --git a/Assembly-CSharp/RimWorld/CompProperties_Usable.cs b/Assembly-CSharp/RimWorld/CompProperties_Usable.cs index c7dd7e58d..56eb9595e 100644 --- a/Assembly-CSharp/RimWorld/CompProperties_Usable.cs +++ b/Assembly-CSharp/RimWorld/CompProperties_Usable.cs @@ -1,4 +1,3 @@ -using System; using Verse; namespace RimWorld @@ -11,7 +10,7 @@ public class CompProperties_Usable : CompProperties public CompProperties_Usable() { - this.compClass = typeof(CompUsable); + base.compClass = typeof(CompUsable); } } } diff --git a/Assembly-CSharp/RimWorld/CompProperties_UseEffect.cs b/Assembly-CSharp/RimWorld/CompProperties_UseEffect.cs index 95de8b46b..79cb49dee 100644 --- a/Assembly-CSharp/RimWorld/CompProperties_UseEffect.cs +++ b/Assembly-CSharp/RimWorld/CompProperties_UseEffect.cs @@ -1,4 +1,3 @@ -using System; using Verse; namespace RimWorld @@ -9,7 +8,7 @@ public class CompProperties_UseEffect : CompProperties public CompProperties_UseEffect() { - this.compClass = typeof(CompUseEffect); + base.compClass = typeof(CompUseEffect); } } } diff --git a/Assembly-CSharp/RimWorld/CompQuality.cs b/Assembly-CSharp/RimWorld/CompQuality.cs index 68e3b3e90..83fdffd74 100644 --- a/Assembly-CSharp/RimWorld/CompQuality.cs +++ b/Assembly-CSharp/RimWorld/CompQuality.cs @@ -1,4 +1,3 @@ -using System; using Verse; namespace RimWorld @@ -18,7 +17,7 @@ public QualityCategory Quality public void SetQuality(QualityCategory q, ArtGenerationContext source) { this.qualityInt = q; - CompArt compArt = this.parent.TryGetComp(); + CompArt compArt = base.parent.TryGetComp(); if (compArt != null) { compArt.InitializeArt(source); @@ -38,8 +37,12 @@ public override void PostPostGeneratedForTrader(TraderKindDef trader, int forTil public override bool AllowStackWith(Thing other) { - QualityCategory qualityCategory; - return other.TryGetQuality(out qualityCategory) && this.qualityInt == qualityCategory; + QualityCategory qualityCategory = default(QualityCategory); + if (other.TryGetQuality(out qualityCategory)) + { + return this.qualityInt == qualityCategory; + } + return false; } public override void PostSplitOff(Thing piece) @@ -50,10 +53,7 @@ public override void PostSplitOff(Thing piece) public override string CompInspectStringExtra() { - return "QualityIs".Translate(new object[] - { - this.Quality.GetLabel().CapitalizeFirst() - }); + return "QualityIs".Translate(this.Quality.GetLabel().CapitalizeFirst()); } } } diff --git a/Assembly-CSharp/RimWorld/CompRefuelable.cs b/Assembly-CSharp/RimWorld/CompRefuelable.cs index 673f8f6e9..76da95204 100644 --- a/Assembly-CSharp/RimWorld/CompRefuelable.cs +++ b/Assembly-CSharp/RimWorld/CompRefuelable.cs @@ -1,6 +1,5 @@ using System; using System.Collections.Generic; -using System.Diagnostics; using System.Linq; using UnityEngine; using Verse; @@ -32,7 +31,7 @@ public float TargetFuelLevel { get { - if (this.configuredTargetFuelLevel >= 0f) + if (this.configuredTargetFuelLevel >= 0.0) { return this.configuredTargetFuelLevel; } @@ -52,7 +51,7 @@ public CompProperties_Refuelable Props { get { - return (CompProperties_Refuelable)this.props; + return (CompProperties_Refuelable)base.props; } } @@ -84,7 +83,7 @@ public bool IsFull { get { - return this.TargetFuelLevel - this.fuel < 1f; + return this.TargetFuelLevel - this.fuel < 1.0; } } @@ -92,7 +91,7 @@ public bool HasFuel { get { - return this.fuel > 0f; + return this.fuel > 0.0; } } @@ -100,7 +99,7 @@ private float ConsumptionRatePerTick { get { - return this.Props.fuelConsumptionRate / 60000f; + return (float)(this.Props.fuelConsumptionRate / 60000.0); } } @@ -108,7 +107,7 @@ public bool ShouldAutoRefuelNow { get { - return this.FuelPercentOfTarget <= this.Props.autoRefuelPercent && !this.IsFull && this.TargetFuelLevel > 0f && !this.parent.IsBurning() && (this.flickComp == null || this.flickComp.SwitchIsOn) && this.parent.Map.designationManager.DesignationOn(this.parent, DesignationDefOf.Flick) == null && this.parent.Map.designationManager.DesignationOn(this.parent, DesignationDefOf.Deconstruct) == null; + return this.FuelPercentOfTarget <= this.Props.autoRefuelPercent && !this.IsFull && this.TargetFuelLevel > 0.0 && !base.parent.IsBurning() && (this.flickComp == null || this.flickComp.SwitchIsOn) && base.parent.Map.designationManager.DesignationOn(base.parent, DesignationDefOf.Flick) == null && base.parent.Map.designationManager.DesignationOn(base.parent, DesignationDefOf.Deconstruct) == null; } } @@ -119,7 +118,7 @@ public override void Initialize(CompProperties props) { this.fuel = this.Props.fuelCapacity; } - this.flickComp = this.parent.GetComp(); + this.flickComp = base.parent.GetComp(); } public override void PostExposeData() @@ -134,18 +133,20 @@ public override void PostDraw() base.PostDraw(); if (!this.HasFuel && this.Props.drawOutOfFuelOverlay) { - this.parent.Map.overlayDrawer.DrawOverlay(this.parent, OverlayTypes.OutOfFuel); + base.parent.Map.overlayDrawer.DrawOverlay(base.parent, OverlayTypes.OutOfFuel); } if (this.Props.drawFuelGaugeInMap) { - GenDraw.FillableBarRequest r = default(GenDraw.FillableBarRequest); - r.center = this.parent.DrawPos + Vector3.up * 0.1f; - r.size = CompRefuelable.FuelBarSize; - r.fillPercent = this.FuelPercentOfMax; - r.filledMat = CompRefuelable.FuelBarFilledMat; - r.unfilledMat = CompRefuelable.FuelBarUnfilledMat; - r.margin = 0.15f; - Rot4 rotation = this.parent.Rotation; + GenDraw.FillableBarRequest r = new GenDraw.FillableBarRequest + { + center = base.parent.DrawPos + Vector3.up * 0.1f, + size = CompRefuelable.FuelBarSize, + fillPercent = this.FuelPercentOfMax, + filledMat = CompRefuelable.FuelBarFilledMat, + unfilledMat = CompRefuelable.FuelBarUnfilledMat, + margin = 0.15f + }; + Rot4 rotation = base.parent.Rotation; rotation.Rotate(RotationDirection.Clockwise); r.rotation = rotation; GenDraw.DrawFillableBar(r); @@ -157,40 +158,30 @@ public override void PostDestroy(DestroyMode mode, Map previousMap) base.PostDestroy(mode, previousMap); if (previousMap != null && this.Props.fuelFilter.AllowedDefCount == 1) { - ThingDef thingDef = this.Props.fuelFilter.AllowedThingDefs.First(); + ThingDef thingDef = this.Props.fuelFilter.AllowedThingDefs.First(); float num = 1f; - int i = GenMath.RoundRandom(num * this.fuel); - while (i > 0) + int num2 = GenMath.RoundRandom(num * this.fuel); + while (num2 > 0) { Thing thing = ThingMaker.MakeThing(thingDef, null); - thing.stackCount = Mathf.Min(i, thingDef.stackLimit); - i -= thing.stackCount; - GenPlace.TryPlaceThing(thing, this.parent.Position, previousMap, ThingPlaceMode.Near, null); + thing.stackCount = Mathf.Min(num2, thingDef.stackLimit); + num2 -= thing.stackCount; + GenPlace.TryPlaceThing(thing, base.parent.Position, previousMap, ThingPlaceMode.Near, null); } } } public override string CompInspectStringExtra() { - string text = string.Concat(new string[] - { - "Fuel".Translate(), - ": ", - this.fuel.ToStringDecimalIfSmall(), - " / ", - this.Props.fuelCapacity.ToStringDecimalIfSmall() - }); + string text = "Fuel".Translate() + ": " + this.fuel.ToStringDecimalIfSmall() + " / " + this.Props.fuelCapacity.ToStringDecimalIfSmall(); if (!this.Props.consumeFuelOnlyWhenUsed && this.HasFuel) { - int numTicks = (int)(this.fuel / this.Props.fuelConsumptionRate * 60000f); + int numTicks = (int)(this.fuel / this.Props.fuelConsumptionRate * 60000.0); text = text + " (" + numTicks.ToStringTicksToPeriod(true, false, true) + ")"; } if (this.Props.targetFuelLevelConfigurable) { - text = text + "\n" + "ConfiguredTargetFuelLevel".Translate(new object[] - { - this.TargetFuelLevel.ToStringDecimalIfSmall() - }); + text = text + "\n" + "ConfiguredTargetFuelLevel".Translate(this.TargetFuelLevel.ToStringDecimalIfSmall()); } return text; } @@ -202,7 +193,7 @@ public override void CompTick() { this.ConsumeFuel(this.ConsumptionRatePerTick); } - if (this.Props.fuelConsumptionPerTickInRain > 0f && this.parent.Spawned && this.parent.Map.weatherManager.RainRate > 0.4f && !this.parent.Map.roofGrid.Roofed(this.parent.Position)) + if (this.Props.fuelConsumptionPerTickInRain > 0.0 && base.parent.Spawned && base.parent.Map.weatherManager.RainRate > 0.40000000596046448 && !base.parent.Map.roofGrid.Roofed(base.parent.Position)) { this.ConsumeFuel(this.Props.fuelConsumptionPerTickInRain); } @@ -210,19 +201,18 @@ public override void CompTick() public void ConsumeFuel(float amount) { - if (this.fuel <= 0f) - { - return; - } - this.fuel -= amount; - if (this.fuel <= 0f) + if (!(this.fuel <= 0.0)) { - this.fuel = 0f; - if (this.Props.destroyOnNoFuel) + this.fuel -= amount; + if (this.fuel <= 0.0) { - this.parent.Destroy(DestroyMode.Vanish); + this.fuel = 0f; + if (this.Props.destroyOnNoFuel) + { + base.parent.Destroy(DestroyMode.Vanish); + } + base.parent.BroadcastCompSignal("RanOutOfFuel"); } - this.parent.BroadcastCompSignal("RanOutOfFuel"); } } @@ -239,7 +229,7 @@ public void Refuel(float amount) { this.fuel = this.Props.fuelCapacity; } - this.parent.BroadcastCompSignal("Refueled"); + base.parent.BroadcastCompSignal("Refueled"); } public void Notify_UsedThisTick() @@ -253,14 +243,46 @@ public int GetFuelCountToFullyRefuel() return Mathf.Max(Mathf.CeilToInt(f), 1); } - [DebuggerHidden] public override IEnumerable CompGetGizmosExtra() { - CompRefuelable.c__Iterator16A c__Iterator16A = new CompRefuelable.c__Iterator16A(); - c__Iterator16A.<>f__this = this; - CompRefuelable.c__Iterator16A expr_0E = c__Iterator16A; - expr_0E.$PC = -2; - return expr_0E; + if (this.Props.targetFuelLevelConfigurable) + { + yield return (Gizmo)new Command_SetTargetFuelLevel + { + refuelable = this, + defaultLabel = "CommandSetTargetFuelLevel".Translate(), + defaultDesc = "CommandSetTargetFuelLevelDesc".Translate(), + icon = CompRefuelable.SetTargetFuelLevelCommand + }; + } + if (this.Props.showFuelGizmo && Find.Selector.SingleSelectedThing == base.parent) + { + yield return (Gizmo)new Gizmo_RefuelableFuelStatus + { + refuelable = this + }; + } + if (Prefs.DevMode) + { + yield return (Gizmo)new Command_Action + { + defaultLabel = "Debug: Set fuel to 0.1", + action = (Action)delegate + { + ((_003CCompGetGizmosExtra_003Ec__Iterator16A)/*Error near IL_013e: stateMachine*/)._003C_003Ef__this.fuel = 0.1f; + ((_003CCompGetGizmosExtra_003Ec__Iterator16A)/*Error near IL_013e: stateMachine*/)._003C_003Ef__this.parent.BroadcastCompSignal("Refueled"); + } + }; + yield return (Gizmo)new Command_Action + { + defaultLabel = "Debug: Set fuel to max", + action = (Action)delegate + { + ((_003CCompGetGizmosExtra_003Ec__Iterator16A)/*Error near IL_0188: stateMachine*/)._003C_003Ef__this.fuel = ((_003CCompGetGizmosExtra_003Ec__Iterator16A)/*Error near IL_0188: stateMachine*/)._003C_003Ef__this.Props.fuelCapacity; + ((_003CCompGetGizmosExtra_003Ec__Iterator16A)/*Error near IL_0188: stateMachine*/)._003C_003Ef__this.parent.BroadcastCompSignal("Refueled"); + } + }; + } } } } diff --git a/Assembly-CSharp/RimWorld/CompReportWorkSpeed.cs b/Assembly-CSharp/RimWorld/CompReportWorkSpeed.cs index e2da38407..e08a3df68 100644 --- a/Assembly-CSharp/RimWorld/CompReportWorkSpeed.cs +++ b/Assembly-CSharp/RimWorld/CompReportWorkSpeed.cs @@ -1,4 +1,3 @@ -using System; using Verse; namespace RimWorld @@ -7,38 +6,38 @@ public class CompReportWorkSpeed : ThingComp { public override string CompInspectStringExtra() { - bool flag = StatPart_WorkTableOutdoors.Applies(this.parent.def, this.parent.Map, this.parent.Position); - bool flag2 = StatPart_WorkTableTemperature.Applies(this.parent); - bool flag3 = StatPart_WorkTableUnpowered.Applies(this.parent); - if (flag || flag2 || flag3) + bool flag = StatPart_WorkTableOutdoors.Applies(base.parent.def, base.parent.Map, base.parent.Position); + bool flag2 = StatPart_WorkTableTemperature.Applies(base.parent); + bool flag3 = StatPart_WorkTableUnpowered.Applies(base.parent); + if (!flag && !flag2 && !flag3) { - string text = "WorkSpeedPenalty".Translate() + ": "; - bool flag4 = false; - if (flag) - { - text += "Outdoors".Translate().ToLower(); - flag4 = true; - } - if (flag2) + return (string)null; + } + string text = "WorkSpeedPenalty".Translate() + ": "; + bool flag4 = false; + if (flag) + { + text += "Outdoors".Translate().ToLower(); + flag4 = true; + } + if (flag2) + { + if (flag4) { - if (flag4) - { - text += ", "; - } - text += "BadTemperature".Translate().ToLower(); - flag4 = true; + text += ", "; } - if (flag3) + text += "BadTemperature".Translate().ToLower(); + flag4 = true; + } + if (flag3) + { + if (flag4) { - if (flag4) - { - text += ", "; - } - text += "NoPower".Translate().ToLower(); + text += ", "; } - return text; + text += "NoPower".Translate().ToLower(); } - return null; + return text; } } } diff --git a/Assembly-CSharp/RimWorld/CompRoomIdentifier.cs b/Assembly-CSharp/RimWorld/CompRoomIdentifier.cs index 225e6f38a..26c3a06a2 100644 --- a/Assembly-CSharp/RimWorld/CompRoomIdentifier.cs +++ b/Assembly-CSharp/RimWorld/CompRoomIdentifier.cs @@ -1,4 +1,3 @@ -using System; using Verse; namespace RimWorld @@ -9,30 +8,14 @@ private CompProperties_RoomIdentifier Props { get { - return (CompProperties_RoomIdentifier)this.props; + return (CompProperties_RoomIdentifier)base.props; } } public override string CompInspectStringExtra() { - Room room = this.parent.GetRoom(RegionType.Set_All); - string str; - if (room == null || room.Role == RoomRoleDefOf.None) - { - str = "Outdoors".Translate(); - } - else - { - str = string.Concat(new string[] - { - room.Role.LabelCap, - " (", - room.GetStatScoreStage(this.Props.roomStat).label, - ", ", - this.Props.roomStat.ScoreToString(room.GetStat(this.Props.roomStat)), - ")" - }); - } + Room room = base.parent.GetRoom(RegionType.Set_All); + string str = (room != null && room.Role != RoomRoleDefOf.None) ? (room.Role.LabelCap + " (" + room.GetStatScoreStage(this.Props.roomStat).label + ", " + this.Props.roomStat.ScoreToString(room.GetStat(this.Props.roomStat)) + ")") : "Outdoors".Translate(); return "Room".Translate() + ": " + str; } } diff --git a/Assembly-CSharp/RimWorld/CompRottable.cs b/Assembly-CSharp/RimWorld/CompRottable.cs index be1b08fc4..c730d8b61 100644 --- a/Assembly-CSharp/RimWorld/CompRottable.cs +++ b/Assembly-CSharp/RimWorld/CompRottable.cs @@ -1,4 +1,3 @@ -using System; using System.Text; using UnityEngine; using Verse; @@ -13,7 +12,7 @@ private CompProperties_Rottable PropsRot { get { - return (CompProperties_Rottable)this.props; + return (CompProperties_Rottable)base.props; } } @@ -62,9 +61,9 @@ public int TicksUntilRotAtCurrentTemp { get { - float num = this.parent.AmbientTemperature; - num = (float)Mathf.RoundToInt(num); - return this.TicksUntilRotAtTemp(num); + float ambientTemperature = base.parent.AmbientTemperature; + ambientTemperature = (float)Mathf.RoundToInt(ambientTemperature); + return this.TicksUntilRotAtTemp(ambientTemperature); } } @@ -78,41 +77,36 @@ public override void CompTickRare() { float rotProgress = this.RotProgress; float num = 1f; - float ambientTemperature = this.parent.AmbientTemperature; + float ambientTemperature = base.parent.AmbientTemperature; num *= GenTemperature.RotRateAtTemperature(ambientTemperature); - this.RotProgress += Mathf.Round(num * 250f); + this.RotProgress += Mathf.Round((float)(num * 250.0)); if (this.Stage == RotStage.Rotting && this.PropsRot.rotDestroys) { - if (this.parent.Spawned && this.parent.Map.slotGroupManager.SlotGroupAt(this.parent.Position) != null) + if (base.parent.Spawned && base.parent.Map.slotGroupManager.SlotGroupAt(base.parent.Position) != null) { - Messages.Message("MessageRottedAwayInStorage".Translate(new object[] - { - this.parent.Label - }).CapitalizeFirst(), MessageSound.Silent); + Messages.Message("MessageRottedAwayInStorage".Translate(base.parent.Label).CapitalizeFirst(), MessageSound.Silent); LessonAutoActivator.TeachOpportunity(ConceptDefOf.SpoilageAndFreezers, OpportunityType.GoodToKnow); } - this.parent.Destroy(DestroyMode.Vanish); - return; + base.parent.Destroy(DestroyMode.Vanish); } - bool flag = Mathf.FloorToInt(rotProgress / 60000f) != Mathf.FloorToInt(this.RotProgress / 60000f); - if (flag && this.ShouldTakeRotDamage()) + else if (Mathf.FloorToInt((float)(rotProgress / 60000.0)) != Mathf.FloorToInt((float)(this.RotProgress / 60000.0)) && this.ShouldTakeRotDamage()) { - if (this.Stage == RotStage.Rotting && this.PropsRot.rotDamagePerDay > 0f) + if (this.Stage == RotStage.Rotting && this.PropsRot.rotDamagePerDay > 0.0) { - this.parent.TakeDamage(new DamageInfo(DamageDefOf.Rotting, GenMath.RoundRandom(this.PropsRot.rotDamagePerDay), -1f, null, null, null, DamageInfo.SourceCategory.ThingOrUnknown)); + base.parent.TakeDamage(new DamageInfo(DamageDefOf.Rotting, GenMath.RoundRandom(this.PropsRot.rotDamagePerDay), -1f, null, null, null, DamageInfo.SourceCategory.ThingOrUnknown)); } - else if (this.Stage == RotStage.Dessicated && this.PropsRot.dessicatedDamagePerDay > 0f) + else if (this.Stage == RotStage.Dessicated && this.PropsRot.dessicatedDamagePerDay > 0.0) { - this.parent.TakeDamage(new DamageInfo(DamageDefOf.Rotting, GenMath.RoundRandom(this.PropsRot.dessicatedDamagePerDay), -1f, null, null, null, DamageInfo.SourceCategory.ThingOrUnknown)); + base.parent.TakeDamage(new DamageInfo(DamageDefOf.Rotting, GenMath.RoundRandom(this.PropsRot.dessicatedDamagePerDay), -1f, null, null, null, DamageInfo.SourceCategory.ThingOrUnknown)); } } } private bool ShouldTakeRotDamage() { - if (this.parent.ParentHolder != null) + if (base.parent.ParentHolder != null) { - Thing thing = this.parent.ParentHolder as Thing; + Thing thing = base.parent.ParentHolder as Thing; if (thing != null && thing.def.category == ThingCategory.Building && thing.def.building.preventDeterioration) { return false; @@ -123,7 +117,7 @@ private bool ShouldTakeRotDamage() public override void PreAbsorbStack(Thing otherStack, int count) { - float t = (float)count / (float)(this.parent.stackCount + count); + float t = (float)count / (float)(base.parent.stackCount + count); float rotProgress = ((ThingWithComps)otherStack).GetComp().RotProgress; this.RotProgress = Mathf.Lerp(this.RotProgress, rotProgress, t); } @@ -135,9 +129,9 @@ public override void PostSplitOff(Thing piece) public override void PostIngested(Pawn ingester) { - if (this.Stage != RotStage.Fresh) + if (this.Stage != 0) { - FoodUtility.AddFoodPoisoningHediff(ingester, this.parent); + FoodUtility.AddFoodPoisoningHediff(ingester, base.parent); } } @@ -147,40 +141,40 @@ public override string CompInspectStringExtra() switch (this.Stage) { case RotStage.Fresh: + { stringBuilder.Append("RotStateFresh".Translate() + "."); break; + } case RotStage.Rotting: + { stringBuilder.Append("RotStateRotting".Translate() + "."); break; + } case RotStage.Dessicated: + { stringBuilder.Append("RotStateDessicated".Translate() + "."); break; } + } float num = (float)this.PropsRot.TicksToRotStart - this.RotProgress; - if (num > 0f) + if (num > 0.0) { - float num2 = this.parent.AmbientTemperature; - num2 = (float)Mathf.RoundToInt(num2); - float num3 = GenTemperature.RotRateAtTemperature(num2); + float ambientTemperature = base.parent.AmbientTemperature; + ambientTemperature = (float)Mathf.RoundToInt(ambientTemperature); + float num2 = GenTemperature.RotRateAtTemperature(ambientTemperature); int ticksUntilRotAtCurrentTemp = this.TicksUntilRotAtCurrentTemp; stringBuilder.AppendLine(); - if (num3 < 0.001f) + if (num2 < 0.0010000000474974513) { stringBuilder.Append("CurrentlyFrozen".Translate() + "."); } - else if (num3 < 0.999f) + else if (num2 < 0.99900001287460327) { - stringBuilder.Append("CurrentlyRefrigerated".Translate(new object[] - { - ticksUntilRotAtCurrentTemp.ToStringTicksToPeriodVagueMax() - }) + "."); + stringBuilder.Append("CurrentlyRefrigerated".Translate(ticksUntilRotAtCurrentTemp.ToStringTicksToPeriodVagueMax()) + "."); } else { - stringBuilder.Append("NotRefrigerated".Translate(new object[] - { - ticksUntilRotAtCurrentTemp.ToStringTicksToPeriodVagueMax() - }) + "."); + stringBuilder.Append("NotRefrigerated".Translate(ticksUntilRotAtCurrentTemp.ToStringTicksToPeriodVagueMax()) + "."); } } return stringBuilder.ToString(); @@ -195,12 +189,12 @@ public int ApproxTicksUntilRotWhenAtTempOfTile(int tile) public int TicksUntilRotAtTemp(float temp) { float num = GenTemperature.RotRateAtTemperature(temp); - if (num <= 0f) + if (num <= 0.0) { return 2147483647; } float num2 = (float)this.PropsRot.TicksToRotStart - this.RotProgress; - if (num2 <= 0f) + if (num2 <= 0.0) { return 0; } @@ -209,7 +203,7 @@ public int TicksUntilRotAtTemp(float temp) private void StageChanged() { - Corpse corpse = this.parent as Corpse; + Corpse corpse = base.parent as Corpse; if (corpse != null) { corpse.RotStageChanged(); diff --git a/Assembly-CSharp/RimWorld/CompSchedule.cs b/Assembly-CSharp/RimWorld/CompSchedule.cs index d731a9d88..835db3af9 100644 --- a/Assembly-CSharp/RimWorld/CompSchedule.cs +++ b/Assembly-CSharp/RimWorld/CompSchedule.cs @@ -1,4 +1,3 @@ -using System; using Verse; namespace RimWorld @@ -15,7 +14,7 @@ public CompProperties_Schedule Props { get { - return (CompProperties_Schedule)this.props; + return (CompProperties_Schedule)base.props; } } @@ -27,12 +26,11 @@ public bool Allowed } set { - if (this.intAllowed == value) + if (this.intAllowed != value) { - return; + this.intAllowed = value; + base.parent.BroadcastCompSignal((!this.intAllowed) ? "ScheduledOff" : "ScheduledOn"); } - this.intAllowed = value; - this.parent.BroadcastCompSignal((!this.intAllowed) ? "ScheduledOff" : "ScheduledOn"); } } @@ -50,7 +48,7 @@ public override void CompTickRare() public void RecalculateAllowed() { - float num = GenLocalDate.DayPercent(this.parent); + float num = GenLocalDate.DayPercent(base.parent); if (this.Props.startTime <= this.Props.endTime) { this.Allowed = (num > this.Props.startTime && num < this.Props.endTime); @@ -67,7 +65,7 @@ public override string CompInspectStringExtra() { return this.Props.offMessage; } - return null; + return (string)null; } } } diff --git a/Assembly-CSharp/RimWorld/CompShearable.cs b/Assembly-CSharp/RimWorld/CompShearable.cs index 1d65e47bf..6c2116360 100644 --- a/Assembly-CSharp/RimWorld/CompShearable.cs +++ b/Assembly-CSharp/RimWorld/CompShearable.cs @@ -1,4 +1,3 @@ -using System; using Verse; namespace RimWorld @@ -41,7 +40,7 @@ public CompProperties_Shearable Props { get { - return (CompProperties_Shearable)this.props; + return (CompProperties_Shearable)base.props; } } @@ -53,8 +52,12 @@ protected override bool Active { return false; } - Pawn pawn = this.parent as Pawn; - return pawn == null || pawn.ageTracker.CurLifeStage.shearable; + Pawn pawn = base.parent as Pawn; + if (pawn != null && !pawn.ageTracker.CurLifeStage.shearable) + { + return false; + } + return true; } } @@ -62,7 +65,7 @@ public override string CompInspectStringExtra() { if (!this.Active) { - return null; + return (string)null; } return "WoolGrowth".Translate() + ": " + base.Fullness.ToStringPercent(); } diff --git a/Assembly-CSharp/RimWorld/CompShipPart.cs b/Assembly-CSharp/RimWorld/CompShipPart.cs index 9a5d33d47..8ff56f479 100644 --- a/Assembly-CSharp/RimWorld/CompShipPart.cs +++ b/Assembly-CSharp/RimWorld/CompShipPart.cs @@ -1,41 +1,43 @@ using System; using System.Collections.Generic; -using System.Diagnostics; using System.Linq; using System.Text; +using UnityEngine; using Verse; namespace RimWorld { public class CompShipPart : ThingComp { - [DebuggerHidden] public override IEnumerable CompGetGizmosExtra() { - CompShipPart.c__Iterator170 c__Iterator = new CompShipPart.c__Iterator170(); - c__Iterator.<>f__this = this; - CompShipPart.c__Iterator170 expr_0E = c__Iterator; - expr_0E.$PC = -2; - return expr_0E; + yield return (Gizmo)new Command_Action + { + action = new Action(this.ShowReport), + defaultLabel = "CommandShipLaunchReport".Translate(), + defaultDesc = "CommandShipLaunchReportDesc".Translate(), + hotKey = KeyBindingDefOf.Misc4, + icon = ContentFinder.Get("UI/Commands/LaunchReport", true) + }; } public void ShowReport() { StringBuilder stringBuilder = new StringBuilder(); - if (!ShipUtility.LaunchFailReasons((Building)this.parent).Any()) + if (!ShipUtility.LaunchFailReasons((Building)base.parent).Any()) { stringBuilder.AppendLine("ShipReportCanLaunch".Translate()); } else { stringBuilder.AppendLine("ShipReportCannotLaunch".Translate()); - foreach (string current in ShipUtility.LaunchFailReasons((Building)this.parent)) + foreach (string item in ShipUtility.LaunchFailReasons((Building)base.parent)) { stringBuilder.AppendLine(); - stringBuilder.AppendLine(current); + stringBuilder.AppendLine(item); } } - Dialog_MessageBox window = new Dialog_MessageBox(stringBuilder.ToString(), null, null, null, null, null, false); + Dialog_MessageBox window = new Dialog_MessageBox(stringBuilder.ToString(), (string)null, null, (string)null, null, (string)null, false); Find.WindowStack.Add(window); } } diff --git a/Assembly-CSharp/RimWorld/CompSpawner.cs b/Assembly-CSharp/RimWorld/CompSpawner.cs index 018aac805..b21a254ea 100644 --- a/Assembly-CSharp/RimWorld/CompSpawner.cs +++ b/Assembly-CSharp/RimWorld/CompSpawner.cs @@ -1,6 +1,5 @@ using System; using System.Collections.Generic; -using System.Diagnostics; using Verse; namespace RimWorld @@ -13,7 +12,7 @@ public CompProperties_Spawner PropsSpawner { get { - return (CompProperties_Spawner)this.props; + return (CompProperties_Spawner)base.props; } } @@ -27,22 +26,20 @@ public override void PostSpawnSetup(bool respawningAfterLoad) public override void CompTick() { - if (this.parent.Position.Fogged(this.parent.Map)) + if (!base.parent.Position.Fogged(base.parent.Map)) { - return; + this.ticksUntilSpawn--; + this.CheckShouldSpawn(); } - this.ticksUntilSpawn--; - this.CheckShouldSpawn(); } public override void CompTickRare() { - if (this.parent.Position.Fogged(this.parent.Map)) + if (!base.parent.Position.Fogged(base.parent.Map)) { - return; + this.ticksUntilSpawn -= 250; + this.CheckShouldSpawn(); } - this.ticksUntilSpawn -= 250; - this.CheckShouldSpawn(); } private void CheckShouldSpawn() @@ -61,7 +58,7 @@ public bool TryDoSpawn() int num = 0; for (int i = 0; i < 9; i++) { - List thingList = (this.parent.Position + GenAdj.AdjacentCellsAndInside[i]).GetThingList(this.parent.Map); + List thingList = (base.parent.Position + GenAdj.AdjacentCellsAndInside[i]).GetThingList(base.parent.Map); for (int j = 0; j < thingList.Count; j++) { if (thingList[j].def == this.PropsSpawner.thingToSpawn) @@ -75,13 +72,13 @@ public bool TryDoSpawn() } } } - IntVec3 center; + IntVec3 center = default(IntVec3); if (this.TryFindSpawnCell(out center)) { Thing thing = ThingMaker.MakeThing(this.PropsSpawner.thingToSpawn, null); thing.stackCount = this.PropsSpawner.spawnCount; - Thing t; - GenPlace.TryPlaceThing(thing, center, this.parent.Map, ThingPlaceMode.Direct, out t, null); + Thing t = default(Thing); + GenPlace.TryPlaceThing(thing, center, base.parent.Map, ThingPlaceMode.Direct, out t, (Action)null); if (this.PropsSpawner.spawnForbidden) { t.SetForbidden(true, true); @@ -93,35 +90,32 @@ public bool TryDoSpawn() private bool TryFindSpawnCell(out IntVec3 result) { - foreach (IntVec3 current in GenAdj.CellsAdjacent8Way(this.parent).InRandomOrder(null)) + foreach (IntVec3 item in GenAdj.CellsAdjacent8Way(base.parent).InRandomOrder(null)) { - if (current.Walkable(this.parent.Map)) + if (item.Walkable(base.parent.Map)) { - Building edifice = current.GetEdifice(this.parent.Map); + Building edifice = item.GetEdifice(base.parent.Map); if (edifice == null || !this.PropsSpawner.thingToSpawn.IsEdifice()) { Building_Door building_Door = edifice as Building_Door; - if (building_Door == null || building_Door.FreePassage) + if ((building_Door == null || building_Door.FreePassage) && GenSight.LineOfSight(base.parent.Position, item, base.parent.Map, false, null, 0, 0)) { - if (GenSight.LineOfSight(this.parent.Position, current, this.parent.Map, false, null, 0, 0)) + bool flag = false; + List thingList = item.GetThingList(base.parent.Map); + for (int i = 0; i < thingList.Count; i++) { - bool flag = false; - List thingList = current.GetThingList(this.parent.Map); - for (int i = 0; i < thingList.Count; i++) + Thing thing = thingList[i]; + if (thing.def.category == ThingCategory.Item && (thing.def != this.PropsSpawner.thingToSpawn || thing.stackCount > this.PropsSpawner.thingToSpawn.stackLimit - this.PropsSpawner.spawnCount)) { - Thing thing = thingList[i]; - if (thing.def.category == ThingCategory.Item && (thing.def != this.PropsSpawner.thingToSpawn || thing.stackCount > this.PropsSpawner.thingToSpawn.stackLimit - this.PropsSpawner.spawnCount)) - { - flag = true; - break; - } - } - if (!flag) - { - result = current; - return true; + flag = true; + break; } } + if (!flag) + { + result = item; + return true; + } } } } @@ -140,14 +134,21 @@ public override void PostExposeData() Scribe_Values.Look(ref this.ticksUntilSpawn, "ticksUntilSpawn", 0, false); } - [DebuggerHidden] public override IEnumerable CompGetGizmosExtra() { - CompSpawner.c__Iterator16B c__Iterator16B = new CompSpawner.c__Iterator16B(); - c__Iterator16B.<>f__this = this; - CompSpawner.c__Iterator16B expr_0E = c__Iterator16B; - expr_0E.$PC = -2; - return expr_0E; + if (Prefs.DevMode) + { + yield return (Gizmo)new Command_Action + { + defaultLabel = "DEBUG: Spawn " + this.PropsSpawner.thingToSpawn.label, + icon = TexCommand.DesirePower, + action = (Action)delegate + { + ((_003CCompGetGizmosExtra_003Ec__Iterator16B)/*Error near IL_0076: stateMachine*/)._003C_003Ef__this.TryDoSpawn(); + ((_003CCompGetGizmosExtra_003Ec__Iterator16B)/*Error near IL_0076: stateMachine*/)._003C_003Ef__this.ResetCountdown(); + } + }; + } } } } diff --git a/Assembly-CSharp/RimWorld/CompSpawnerFilth.cs b/Assembly-CSharp/RimWorld/CompSpawnerFilth.cs index 6a0f9ee02..f4ef7e81b 100644 --- a/Assembly-CSharp/RimWorld/CompSpawnerFilth.cs +++ b/Assembly-CSharp/RimWorld/CompSpawnerFilth.cs @@ -11,7 +11,7 @@ private CompProperties_SpawnerFilth Props { get { - return (CompProperties_SpawnerFilth)this.props; + return (CompProperties_SpawnerFilth)base.props; } } @@ -19,13 +19,17 @@ private bool CanSpawnFilth { get { - Hive hive = this.parent as Hive; + Hive hive = base.parent as Hive; if (hive != null && !hive.active) { return false; } RotStage? requiredRotStage = this.Props.requiredRotStage; - return !requiredRotStage.HasValue || !(this.parent.GetRotStage() != this.Props.requiredRotStage); + if (requiredRotStage.HasValue && base.parent.GetRotStage() != this.Props.requiredRotStage) + { + return false; + } + return true; } } @@ -50,33 +54,28 @@ public override void CompTickRare() { if (this.CanSpawnFilth) { - if (this.Props.spawnMtbHours > 0f && Rand.MTBEventOccurs(this.Props.spawnMtbHours, 2500f, 250f)) + if (this.Props.spawnMtbHours > 0.0 && Rand.MTBEventOccurs(this.Props.spawnMtbHours, 2500f, 250f)) { this.TrySpawnFilth(); } - if (this.Props.spawnEveryDays >= 0f && Find.TickManager.TicksGame >= this.nextSpawnTimestamp) + if (this.Props.spawnEveryDays >= 0.0 && Find.TickManager.TicksGame >= this.nextSpawnTimestamp) { if (this.nextSpawnTimestamp != -1) { this.TrySpawnFilth(); } - this.nextSpawnTimestamp = Find.TickManager.TicksGame + (int)(this.Props.spawnEveryDays * 60000f); + this.nextSpawnTimestamp = Find.TickManager.TicksGame + (int)(this.Props.spawnEveryDays * 60000.0); } } } public void TrySpawnFilth() { - if (this.parent.Map == null) - { - return; - } - IntVec3 c; - if (!CellFinder.TryFindRandomReachableCellNear(this.parent.Position, this.parent.Map, this.Props.spawnRadius, TraverseParms.For(TraverseMode.NoPassClosedDoors, Danger.Deadly, false), (IntVec3 x) => x.Standable(this.parent.Map), (Region x) => true, out c, 999999)) + IntVec3 c = default(IntVec3); + if (base.parent.Map != null && CellFinder.TryFindRandomReachableCellNear(base.parent.Position, base.parent.Map, this.Props.spawnRadius, TraverseParms.For(TraverseMode.NoPassClosedDoors, Danger.Deadly, false), (Predicate)((IntVec3 x) => x.Standable(base.parent.Map)), (Predicate)((Region x) => true), out c, 999999)) { - return; + FilthMaker.MakeFilth(c, base.parent.Map, this.Props.filthDef, 1); } - FilthMaker.MakeFilth(c, this.parent.Map, this.Props.filthDef, 1); } } } diff --git a/Assembly-CSharp/RimWorld/CompSpawnerHives.cs b/Assembly-CSharp/RimWorld/CompSpawnerHives.cs index cd95fbe25..0f9a0891b 100644 --- a/Assembly-CSharp/RimWorld/CompSpawnerHives.cs +++ b/Assembly-CSharp/RimWorld/CompSpawnerHives.cs @@ -1,6 +1,5 @@ using System; using System.Collections.Generic; -using System.Diagnostics; using UnityEngine; using Verse; @@ -16,7 +15,7 @@ private CompProperties_SpawnerHives Props { get { - return (CompProperties_SpawnerHives)this.props; + return (CompProperties_SpawnerHives)base.props; } } @@ -24,7 +23,7 @@ private bool CanSpawnChildHive { get { - return HivesUtility.TotalSpawnedHivesCount(this.parent.Map) < 30; + return HivesUtility.TotalSpawnedHivesCount(base.parent.Map) < 30; } } @@ -38,14 +37,16 @@ public override void PostSpawnSetup(bool respawningAfterLoad) public override void CompTickRare() { - Hive hive = this.parent as Hive; - if ((hive == null || hive.active) && Find.TickManager.TicksGame >= this.nextHiveSpawnTick) + Hive hive = base.parent as Hive; + if (hive != null && !hive.active) + return; + if (Find.TickManager.TicksGame >= this.nextHiveSpawnTick) { - Hive hive2; + Hive hive2 = default(Hive); if (this.TrySpawnChildHive(false, out hive2)) { hive2.nextPawnSpawnTick = Find.TickManager.TicksGame + Rand.Range(150, 350); - Messages.Message("MessageHiveReproduced".Translate(), hive2, MessageSound.Negative); + Messages.Message("MessageHiveReproduced".Translate(), (Thing)hive2, MessageSound.Negative); } else { @@ -56,7 +57,7 @@ public override void CompTickRare() public override string CompInspectStringExtra() { - string text = null; + string text = (string)null; if (this.CanSpawnChildHive) { text = text + "HiveReproducesIn".Translate() + ": " + (this.nextHiveSpawnTick - Find.TickManager.TicksGame).ToStringTicksToPeriod(true, false, true); @@ -66,25 +67,19 @@ public override string CompInspectStringExtra() public void CalculateNextHiveSpawnTick() { - Room room = this.parent.GetRoom(RegionType.Set_Passable); + Room room = base.parent.GetRoom(RegionType.Set_Passable); int num = 0; int num2 = GenRadial.NumCellsInRadius(9f); - for (int i = 0; i < num2; i++) + for (int num3 = 0; num3 < num2; num3++) { - IntVec3 intVec = this.parent.Position + GenRadial.RadialPattern[i]; - if (intVec.InBounds(this.parent.Map)) + IntVec3 intVec = base.parent.Position + GenRadial.RadialPattern[num3]; + if (intVec.InBounds(base.parent.Map) && intVec.GetRoom(base.parent.Map, RegionType.Set_Passable) == room && intVec.GetThingList(base.parent.Map).Any((Predicate)((Thing t) => t is Hive))) { - if (intVec.GetRoom(this.parent.Map, RegionType.Set_Passable) == room) - { - if (intVec.GetThingList(this.parent.Map).Any((Thing t) => t is Hive)) - { - num++; - } - } + num++; } } - float num3 = GenMath.LerpDouble(0f, 7f, 1f, 0.35f, (float)Mathf.Clamp(num, 0, 7)); - this.nextHiveSpawnTick = Find.TickManager.TicksGame + (int)(this.Props.HiveSpawnIntervalDays.RandomInRange * 60000f / (num3 * Find.Storyteller.difficulty.enemyReproductionRateFactor)); + float num4 = GenMath.LerpDouble(0f, 7f, 1f, 0.35f, (float)Mathf.Clamp(num, 0, 7)); + this.nextHiveSpawnTick = Find.TickManager.TicksGame + (int)(this.Props.HiveSpawnIntervalDays.RandomInRange * 60000.0 / (num4 * Find.Storyteller.difficulty.enemyReproductionRateFactor)); } public bool TrySpawnChildHive(bool ignoreRoofedRequirement, out Hive newHive) @@ -95,29 +90,36 @@ public bool TrySpawnChildHive(bool ignoreRoofedRequirement, out Hive newHive) return false; } IntVec3 invalid = IntVec3.Invalid; - for (int i = 0; i < 3; i++) + int num = 0; + while (num < 3) { float minDist = this.Props.HiveSpawnPreferredMinDist; - if (i == 1) + switch (num) + { + case 1: { minDist = 0f; + break; } - else if (i == 2) + case 2: { newHive = null; return false; } - if (CellFinder.TryFindRandomReachableCellNear(this.parent.Position, this.parent.Map, this.Props.HiveSpawnRadius, TraverseParms.For(TraverseMode.NoPassClosedDoors, Danger.Deadly, false), (IntVec3 c) => this.CanSpawnHiveAt(c, minDist, ignoreRoofedRequirement), null, out invalid, 999999)) + } + if (!CellFinder.TryFindRandomReachableCellNear(base.parent.Position, base.parent.Map, this.Props.HiveSpawnRadius, TraverseParms.For(TraverseMode.NoPassClosedDoors, Danger.Deadly, false), (Predicate)((IntVec3 c) => this.CanSpawnHiveAt(c, minDist, ignoreRoofedRequirement)), (Predicate)null, out invalid, 999999)) { - break; + num++; + continue; } + break; } - newHive = (Hive)GenSpawn.Spawn(this.parent.def, invalid, this.parent.Map); - if (newHive.Faction != this.parent.Faction) + newHive = (Hive)GenSpawn.Spawn(base.parent.def, invalid, base.parent.Map); + if (newHive.Faction != base.parent.Faction) { - newHive.SetFaction(this.parent.Faction, null); + newHive.SetFaction(base.parent.Faction, null); } - Hive hive = this.parent as Hive; + Hive hive = base.parent as Hive; if (hive != null) { newHive.active = hive.active; @@ -128,45 +130,52 @@ public bool TrySpawnChildHive(bool ignoreRoofedRequirement, out Hive newHive) private bool CanSpawnHiveAt(IntVec3 c, float minDist, bool ignoreRoofedRequirement) { - if ((!ignoreRoofedRequirement && !c.Roofed(this.parent.Map)) || !c.Standable(this.parent.Map) || (minDist != 0f && (float)c.DistanceToSquared(this.parent.Position) < minDist * minDist)) - { - return false; - } - for (int i = 0; i < 8; i++) + if ((ignoreRoofedRequirement || c.Roofed(base.parent.Map)) && c.Standable(base.parent.Map) && (minDist == 0.0 || (float)c.DistanceToSquared(base.parent.Position) >= minDist * minDist)) { - IntVec3 c2 = c + GenAdj.AdjacentCells[i]; - if (c2.InBounds(this.parent.Map)) + for (int i = 0; i < 8; i++) { - List thingList = c2.GetThingList(this.parent.Map); - for (int j = 0; j < thingList.Count; j++) + IntVec3 c2 = c + GenAdj.AdjacentCells[i]; + if (c2.InBounds(base.parent.Map)) { - if (thingList[j] is Hive) + List thingList = c2.GetThingList(base.parent.Map); + for (int j = 0; j < thingList.Count; j++) { - return false; + if (thingList[j] is Hive) + { + return false; + } } } } - } - List thingList2 = c.GetThingList(this.parent.Map); - for (int k = 0; k < thingList2.Count; k++) - { - Thing thing = thingList2[k]; - if ((thing.def.category == ThingCategory.Item || thing.def.category == ThingCategory.Building) && GenSpawn.SpawningWipes(this.parent.def, thing.def)) + List thingList2 = c.GetThingList(base.parent.Map); + for (int k = 0; k < thingList2.Count; k++) { - return false; + Thing thing = thingList2[k]; + if ((thing.def.category == ThingCategory.Item || thing.def.category == ThingCategory.Building) && GenSpawn.SpawningWipes(base.parent.def, thing.def)) + { + return false; + } } + return true; } - return true; + return false; } - [DebuggerHidden] public override IEnumerable CompGetGizmosExtra() { - CompSpawnerHives.c__Iterator16C c__Iterator16C = new CompSpawnerHives.c__Iterator16C(); - c__Iterator16C.<>f__this = this; - CompSpawnerHives.c__Iterator16C expr_0E = c__Iterator16C; - expr_0E.$PC = -2; - return expr_0E; + if (Prefs.DevMode) + { + yield return (Gizmo)new Command_Action + { + defaultLabel = "DEBUG: Reproduce", + icon = TexCommand.GatherSpotActive, + action = (Action)delegate + { + Hive hive = default(Hive); + ((_003CCompGetGizmosExtra_003Ec__Iterator16C)/*Error near IL_005c: stateMachine*/)._003C_003Ef__this.TrySpawnChildHive(false, out hive); + } + }; + } } public override void PostExposeData() diff --git a/Assembly-CSharp/RimWorld/CompTargetEffect.cs b/Assembly-CSharp/RimWorld/CompTargetEffect.cs index 9fda25498..c75d8b50d 100644 --- a/Assembly-CSharp/RimWorld/CompTargetEffect.cs +++ b/Assembly-CSharp/RimWorld/CompTargetEffect.cs @@ -1,4 +1,3 @@ -using System; using Verse; namespace RimWorld diff --git a/Assembly-CSharp/RimWorld/CompTargetEffect_Berserk.cs b/Assembly-CSharp/RimWorld/CompTargetEffect_Berserk.cs index b383eb47d..900bfea04 100644 --- a/Assembly-CSharp/RimWorld/CompTargetEffect_Berserk.cs +++ b/Assembly-CSharp/RimWorld/CompTargetEffect_Berserk.cs @@ -1,4 +1,3 @@ -using System; using Verse; namespace RimWorld @@ -8,11 +7,10 @@ public class CompTargetEffect_Berserk : CompTargetEffect public override void DoEffectOn(Pawn user, Thing target) { Pawn pawn = (Pawn)target; - if (pawn.Dead) + if (!pawn.Dead) { - return; + pawn.mindState.mentalStateHandler.TryStartMentalState(MentalStateDefOf.Berserk, (string)null, true, false, null); } - pawn.mindState.mentalStateHandler.TryStartMentalState(MentalStateDefOf.Berserk, null, true, false, null); } } } diff --git a/Assembly-CSharp/RimWorld/CompTargetEffect_BrainDamageChance.cs b/Assembly-CSharp/RimWorld/CompTargetEffect_BrainDamageChance.cs index 16e47fbb3..f89f4dcf6 100644 --- a/Assembly-CSharp/RimWorld/CompTargetEffect_BrainDamageChance.cs +++ b/Assembly-CSharp/RimWorld/CompTargetEffect_BrainDamageChance.cs @@ -1,4 +1,3 @@ -using System; using Verse; namespace RimWorld @@ -10,19 +9,14 @@ public class CompTargetEffect_BrainDamageChance : CompTargetEffect public override void DoEffectOn(Pawn user, Thing target) { Pawn pawn = (Pawn)target; - if (pawn.Dead) - { - return; - } - if (Rand.Value <= 0.3f) + if (!pawn.Dead && Rand.Value <= 0.30000001192092896) { BodyPartRecord brain = pawn.health.hediffSet.GetBrain(); - if (brain == null) + if (brain != null) { - return; + int amount = Rand.RangeInclusive(1, 5); + pawn.TakeDamage(new DamageInfo(DamageDefOf.Flame, amount, -1f, user, brain, base.parent.def, DamageInfo.SourceCategory.ThingOrUnknown)); } - int amount = Rand.RangeInclusive(1, 5); - pawn.TakeDamage(new DamageInfo(DamageDefOf.Flame, amount, -1f, user, brain, this.parent.def, DamageInfo.SourceCategory.ThingOrUnknown)); } } } diff --git a/Assembly-CSharp/RimWorld/CompTargetEffect_GoodwillImpact.cs b/Assembly-CSharp/RimWorld/CompTargetEffect_GoodwillImpact.cs index fc1ffb3e7..935d02d05 100644 --- a/Assembly-CSharp/RimWorld/CompTargetEffect_GoodwillImpact.cs +++ b/Assembly-CSharp/RimWorld/CompTargetEffect_GoodwillImpact.cs @@ -1,4 +1,3 @@ -using System; using Verse; namespace RimWorld diff --git a/Assembly-CSharp/RimWorld/CompTargetEffect_Manhunter.cs b/Assembly-CSharp/RimWorld/CompTargetEffect_Manhunter.cs index 6474e9319..c4f7e40db 100644 --- a/Assembly-CSharp/RimWorld/CompTargetEffect_Manhunter.cs +++ b/Assembly-CSharp/RimWorld/CompTargetEffect_Manhunter.cs @@ -1,4 +1,3 @@ -using System; using Verse; namespace RimWorld @@ -8,11 +7,10 @@ public class CompTargetEffect_Manhunter : CompTargetEffect public override void DoEffectOn(Pawn user, Thing target) { Pawn pawn = (Pawn)target; - if (pawn.Dead) + if (!pawn.Dead) { - return; + pawn.mindState.mentalStateHandler.TryStartMentalState(MentalStateDefOf.Manhunter, (string)null, false, false, null); } - pawn.mindState.mentalStateHandler.TryStartMentalState(MentalStateDefOf.Manhunter, null, false, false, null); } } } diff --git a/Assembly-CSharp/RimWorld/CompTargetEffect_MoodBoost.cs b/Assembly-CSharp/RimWorld/CompTargetEffect_MoodBoost.cs index 8a760bfbb..d1158f95f 100644 --- a/Assembly-CSharp/RimWorld/CompTargetEffect_MoodBoost.cs +++ b/Assembly-CSharp/RimWorld/CompTargetEffect_MoodBoost.cs @@ -1,4 +1,3 @@ -using System; using Verse; namespace RimWorld @@ -8,11 +7,10 @@ public class CompTargetEffect_MoodBoost : CompTargetEffect public override void DoEffectOn(Pawn user, Thing target) { Pawn pawn = (Pawn)target; - if (pawn.Dead || pawn.needs == null || pawn.needs.mood == null) + if (!pawn.Dead && pawn.needs != null && pawn.needs.mood != null) { - return; + pawn.needs.mood.thoughts.memories.TryGainMemory((Thought_Memory)ThoughtMaker.MakeThought(ThoughtDefOf.ArtifactMoodBoost), null); } - pawn.needs.mood.thoughts.memories.TryGainMemory((Thought_Memory)ThoughtMaker.MakeThought(ThoughtDefOf.ArtifactMoodBoost), null); } } } diff --git a/Assembly-CSharp/RimWorld/CompTargetEffect_PsychicShock.cs b/Assembly-CSharp/RimWorld/CompTargetEffect_PsychicShock.cs index 0d7ffc353..c577e4fa0 100644 --- a/Assembly-CSharp/RimWorld/CompTargetEffect_PsychicShock.cs +++ b/Assembly-CSharp/RimWorld/CompTargetEffect_PsychicShock.cs @@ -1,4 +1,3 @@ -using System; using Verse; namespace RimWorld @@ -8,14 +7,13 @@ public class CompTargetEffect_PsychicShock : CompTargetEffect public override void DoEffectOn(Pawn user, Thing target) { Pawn pawn = (Pawn)target; - if (pawn.Dead) + if (!pawn.Dead) { - return; + Hediff hediff = HediffMaker.MakeHediff(HediffDefOf.PsychicShock, pawn, null); + BodyPartRecord part = null; + pawn.RaceProps.body.GetPartsWithTag("ConsciousnessSource").TryRandomElement(out part); + pawn.health.AddHediff(hediff, part, default(DamageInfo?)); } - Hediff hediff = HediffMaker.MakeHediff(HediffDefOf.PsychicShock, pawn, null); - BodyPartRecord part = null; - pawn.RaceProps.body.GetPartsWithTag("ConsciousnessSource").TryRandomElement(out part); - pawn.health.AddHediff(hediff, part, null); } } } diff --git a/Assembly-CSharp/RimWorld/CompTargetable.cs b/Assembly-CSharp/RimWorld/CompTargetable.cs index b6a563e9e..4e4217257 100644 --- a/Assembly-CSharp/RimWorld/CompTargetable.cs +++ b/Assembly-CSharp/RimWorld/CompTargetable.cs @@ -12,7 +12,7 @@ private CompProperties_Targetable Props { get { - return (CompProperties_Targetable)this.props; + return (CompProperties_Targetable)base.props; } } @@ -31,10 +31,10 @@ public override bool SelectedUseOption(Pawn p) { if (this.PlayerChoosesTarget) { - Find.Targeter.BeginTargeting(this.GetTargetingParameters(), delegate(LocalTargetInfo t) + Find.Targeter.BeginTargeting(this.GetTargetingParameters(), (Action)delegate(LocalTargetInfo t) { this.target = t.Thing; - this.parent.GetComp().TryStartUseJob(p); + base.parent.GetComp().TryStartUseJob(p); }, p, null, null); return true; } @@ -45,19 +45,15 @@ public override bool SelectedUseOption(Pawn p) public override void DoEffect(Pawn usedBy) { if (this.PlayerChoosesTarget && this.target == null) - { return; - } if (this.target != null && !this.GetTargetingParameters().CanTarget(this.target)) - { return; - } base.DoEffect(usedBy); - foreach (Thing current in this.GetTargets(this.target)) + foreach (Thing target2 in this.GetTargets(this.target)) { - foreach (CompTargetEffect current2 in this.parent.GetComps()) + foreach (CompTargetEffect comp in base.parent.GetComps()) { - current2.DoEffectOn(usedBy, current); + comp.DoEffectOn(usedBy, target2); } } this.target = null; @@ -72,7 +68,7 @@ public bool BaseTargetValidator(Thing t) if (this.Props.psychicSensitiveTargetsOnly) { Pawn pawn = t as Pawn; - if (pawn != null && pawn.GetStatValue(StatDefOf.PsychicSensitivity, true) <= 0f) + if (pawn != null && pawn.GetStatValue(StatDefOf.PsychicSensitivity, true) <= 0.0) { return false; } diff --git a/Assembly-CSharp/RimWorld/CompTargetable_AllAnimalsOnTheMap.cs b/Assembly-CSharp/RimWorld/CompTargetable_AllAnimalsOnTheMap.cs index 6588b0b30..54c497929 100644 --- a/Assembly-CSharp/RimWorld/CompTargetable_AllAnimalsOnTheMap.cs +++ b/Assembly-CSharp/RimWorld/CompTargetable_AllAnimalsOnTheMap.cs @@ -8,7 +8,7 @@ public class CompTargetable_AllAnimalsOnTheMap : CompTargetable_AllPawnsOnTheMap protected override TargetingParameters GetTargetingParameters() { TargetingParameters targetingParameters = base.GetTargetingParameters(); - targetingParameters.validator = delegate(TargetInfo targ) + targetingParameters.validator = (Predicate)delegate(TargetInfo targ) { if (!base.BaseTargetValidator(targ.Thing)) { diff --git a/Assembly-CSharp/RimWorld/CompTargetable_AllPawnsOnTheMap.cs b/Assembly-CSharp/RimWorld/CompTargetable_AllPawnsOnTheMap.cs index d78996011..77c6a434f 100644 --- a/Assembly-CSharp/RimWorld/CompTargetable_AllPawnsOnTheMap.cs +++ b/Assembly-CSharp/RimWorld/CompTargetable_AllPawnsOnTheMap.cs @@ -1,6 +1,5 @@ using System; using System.Collections.Generic; -using System.Diagnostics; using Verse; namespace RimWorld @@ -17,22 +16,35 @@ protected override bool PlayerChoosesTarget protected override TargetingParameters GetTargetingParameters() { - return new TargetingParameters - { - canTargetPawns = true, - canTargetBuildings = false, - validator = ((TargetInfo x) => base.BaseTargetValidator(x.Thing)) - }; + TargetingParameters targetingParameters = new TargetingParameters(); + targetingParameters.canTargetPawns = true; + targetingParameters.canTargetBuildings = false; + targetingParameters.validator = (Predicate)((TargetInfo x) => base.BaseTargetValidator(x.Thing)); + return targetingParameters; } - [DebuggerHidden] public override IEnumerable GetTargets(Thing targetChosenByPlayer = null) { - CompTargetable_AllPawnsOnTheMap.c__Iterator172 c__Iterator = new CompTargetable_AllPawnsOnTheMap.c__Iterator172(); - c__Iterator.<>f__this = this; - CompTargetable_AllPawnsOnTheMap.c__Iterator172 expr_0E = c__Iterator; - expr_0E.$PC = -2; - return expr_0E; + if (base.parent.MapHeld != null) + { + TargetingParameters tp = this.GetTargetingParameters(); + List.Enumerator enumerator = base.parent.MapHeld.mapPawns.AllPawnsSpawned.GetEnumerator(); + try + { + while (enumerator.MoveNext()) + { + Pawn p = enumerator.Current; + if (tp.CanTarget((Thing)p)) + { + yield return (Thing)p; + } + } + } + finally + { + ((IDisposable)(object)enumerator).Dispose(); + } + } } } } diff --git a/Assembly-CSharp/RimWorld/CompTargetable_SinglePawn.cs b/Assembly-CSharp/RimWorld/CompTargetable_SinglePawn.cs index 3a6e198eb..b67b5f1e4 100644 --- a/Assembly-CSharp/RimWorld/CompTargetable_SinglePawn.cs +++ b/Assembly-CSharp/RimWorld/CompTargetable_SinglePawn.cs @@ -1,6 +1,5 @@ using System; using System.Collections.Generic; -using System.Diagnostics; using Verse; namespace RimWorld @@ -17,23 +16,16 @@ protected override bool PlayerChoosesTarget protected override TargetingParameters GetTargetingParameters() { - return new TargetingParameters - { - canTargetPawns = true, - canTargetBuildings = false, - validator = ((TargetInfo x) => base.BaseTargetValidator(x.Thing)) - }; + TargetingParameters targetingParameters = new TargetingParameters(); + targetingParameters.canTargetPawns = true; + targetingParameters.canTargetBuildings = false; + targetingParameters.validator = (Predicate)((TargetInfo x) => base.BaseTargetValidator(x.Thing)); + return targetingParameters; } - [DebuggerHidden] public override IEnumerable GetTargets(Thing targetChosenByPlayer = null) { - CompTargetable_SinglePawn.c__Iterator173 c__Iterator = new CompTargetable_SinglePawn.c__Iterator173(); - c__Iterator.targetChosenByPlayer = targetChosenByPlayer; - c__Iterator.<$>targetChosenByPlayer = targetChosenByPlayer; - CompTargetable_SinglePawn.c__Iterator173 expr_15 = c__Iterator; - expr_15.$PC = -2; - return expr_15; + yield return targetChosenByPlayer; } } } diff --git a/Assembly-CSharp/RimWorld/CompTempControl.cs b/Assembly-CSharp/RimWorld/CompTempControl.cs index 417a424a4..340218544 100644 --- a/Assembly-CSharp/RimWorld/CompTempControl.cs +++ b/Assembly-CSharp/RimWorld/CompTempControl.cs @@ -1,6 +1,5 @@ using System; using System.Collections.Generic; -using System.Diagnostics; using System.Text; using UnityEngine; using Verse; @@ -21,14 +20,14 @@ public CompProperties_TempControl Props { get { - return (CompProperties_TempControl)this.props; + return (CompProperties_TempControl)base.props; } } public override void PostSpawnSetup(bool respawningAfterLoad) { base.PostSpawnSetup(respawningAfterLoad); - if (this.targetTemperature < -2000f) + if (this.targetTemperature < -2000.0) { this.targetTemperature = this.Props.defaultTargetTemperature; } @@ -42,24 +41,83 @@ public override void PostExposeData() private float RoundedToCurrentTempModeOffset(float celsiusTemp) { - float num = GenTemperature.CelsiusToOffset(celsiusTemp, Prefs.TemperatureMode); - num = (float)Mathf.RoundToInt(num); - return GenTemperature.ConvertTemperatureOffset(num, Prefs.TemperatureMode, TemperatureDisplayMode.Celsius); + float f = GenTemperature.CelsiusToOffset(celsiusTemp, Prefs.TemperatureMode); + f = (float)Mathf.RoundToInt(f); + return GenTemperature.ConvertTemperatureOffset(f, Prefs.TemperatureMode, TemperatureDisplayMode.Celsius); } - [DebuggerHidden] public override IEnumerable CompGetGizmosExtra() { - CompTempControl.c__Iterator16D c__Iterator16D = new CompTempControl.c__Iterator16D(); - c__Iterator16D.<>f__this = this; - CompTempControl.c__Iterator16D expr_0E = c__Iterator16D; - expr_0E.$PC = -2; - return expr_0E; + foreach (Gizmo item in base.CompGetGizmosExtra()) + { + yield return item; + } + float offset4 = this.RoundedToCurrentTempModeOffset(-10f); + yield return (Gizmo)new Command_Action + { + action = (Action)delegate + { + ((_003CCompGetGizmosExtra_003Ec__Iterator16D)/*Error near IL_00e1: stateMachine*/)._003C_003Ef__this.InterfaceChangeTargetTemperature(((_003CCompGetGizmosExtra_003Ec__Iterator16D)/*Error near IL_00e1: stateMachine*/)._003Coffset_003E__2); + }, + defaultLabel = offset4.ToStringTemperatureOffset("F0"), + defaultDesc = "CommandLowerTempDesc".Translate(), + hotKey = KeyBindingDefOf.Misc5, + icon = ContentFinder.Get("UI/Commands/TempLower", true) + }; + float offset3 = this.RoundedToCurrentTempModeOffset(-1f); + yield return (Gizmo)new Command_Action + { + action = (Action)delegate + { + ((_003CCompGetGizmosExtra_003Ec__Iterator16D)/*Error near IL_0187: stateMachine*/)._003C_003Ef__this.InterfaceChangeTargetTemperature(((_003CCompGetGizmosExtra_003Ec__Iterator16D)/*Error near IL_0187: stateMachine*/)._003Coffset_003E__4); + }, + defaultLabel = offset3.ToStringTemperatureOffset("F0"), + defaultDesc = "CommandLowerTempDesc".Translate(), + hotKey = KeyBindingDefOf.Misc4, + icon = ContentFinder.Get("UI/Commands/TempLower", true) + }; + yield return (Gizmo)new Command_Action + { + action = (Action)delegate + { + ((_003CCompGetGizmosExtra_003Ec__Iterator16D)/*Error near IL_0217: stateMachine*/)._003C_003Ef__this.targetTemperature = 21f; + SoundDefOf.TickTiny.PlayOneShotOnCamera(null); + ((_003CCompGetGizmosExtra_003Ec__Iterator16D)/*Error near IL_0217: stateMachine*/)._003C_003Ef__this.ThrowCurrentTemperatureText(); + }, + defaultLabel = "CommandResetTemp".Translate(), + defaultDesc = "CommandResetTempDesc".Translate(), + hotKey = KeyBindingDefOf.Misc1, + icon = ContentFinder.Get("UI/Commands/TempReset", true) + }; + float offset2 = this.RoundedToCurrentTempModeOffset(1f); + yield return (Gizmo)new Command_Action + { + action = (Action)delegate + { + ((_003CCompGetGizmosExtra_003Ec__Iterator16D)/*Error near IL_02b7: stateMachine*/)._003C_003Ef__this.InterfaceChangeTargetTemperature(((_003CCompGetGizmosExtra_003Ec__Iterator16D)/*Error near IL_02b7: stateMachine*/)._003Coffset_003E__7); + }, + defaultLabel = "+" + offset2.ToStringTemperatureOffset("F0"), + defaultDesc = "CommandRaiseTempDesc".Translate(), + hotKey = KeyBindingDefOf.Misc2, + icon = ContentFinder.Get("UI/Commands/TempRaise", true) + }; + float offset = this.RoundedToCurrentTempModeOffset(10f); + yield return (Gizmo)new Command_Action + { + action = (Action)delegate + { + ((_003CCompGetGizmosExtra_003Ec__Iterator16D)/*Error near IL_0367: stateMachine*/)._003C_003Ef__this.InterfaceChangeTargetTemperature(((_003CCompGetGizmosExtra_003Ec__Iterator16D)/*Error near IL_0367: stateMachine*/)._003Coffset_003E__9); + }, + defaultLabel = "+" + offset.ToStringTemperatureOffset("F0"), + defaultDesc = "CommandRaiseTempDesc".Translate(), + hotKey = KeyBindingDefOf.Misc3, + icon = ContentFinder.Get("UI/Commands/TempRaise", true) + }; } private void InterfaceChangeTargetTemperature(float offset) { - if (offset > 0f) + if (offset > 0.0) { SoundDefOf.AmountIncrement.PlayOneShotOnCamera(null); } @@ -74,7 +132,7 @@ private void InterfaceChangeTargetTemperature(float offset) private void ThrowCurrentTemperatureText() { - MoteMaker.ThrowText(this.parent.TrueCenter() + new Vector3(0.5f, 0f, 0.5f), this.parent.Map, this.targetTemperature.ToStringTemperature("F0"), Color.white, -1f); + MoteMaker.ThrowText(base.parent.TrueCenter() + new Vector3(0.5f, 0f, 0.5f), base.parent.Map, this.targetTemperature.ToStringTemperature("F0"), Color.white, -1f); } public override string CompInspectStringExtra() diff --git a/Assembly-CSharp/RimWorld/CompTemperatureRuinable.cs b/Assembly-CSharp/RimWorld/CompTemperatureRuinable.cs index 92b18a472..47235e16f 100644 --- a/Assembly-CSharp/RimWorld/CompTemperatureRuinable.cs +++ b/Assembly-CSharp/RimWorld/CompTemperatureRuinable.cs @@ -1,4 +1,3 @@ -using System; using UnityEngine; using Verse; @@ -14,7 +13,7 @@ public CompProperties_TemperatureRuinable Props { get { - return (CompProperties_TemperatureRuinable)this.props; + return (CompProperties_TemperatureRuinable)base.props; } } @@ -22,7 +21,7 @@ public bool Ruined { get { - return this.ruinedPercent >= 1f; + return this.ruinedPercent >= 1.0; } } @@ -50,7 +49,7 @@ private void DoTicks(int ticks) { if (!this.Ruined) { - float ambientTemperature = this.parent.AmbientTemperature; + float ambientTemperature = base.parent.AmbientTemperature; if (ambientTemperature > this.Props.maxSafeTemperature) { this.ruinedPercent += (ambientTemperature - this.Props.maxSafeTemperature) * this.Props.progressPerDegreePerTick * (float)ticks; @@ -59,12 +58,12 @@ private void DoTicks(int ticks) { this.ruinedPercent -= (ambientTemperature - this.Props.minSafeTemperature) * this.Props.progressPerDegreePerTick * (float)ticks; } - if (this.ruinedPercent >= 1f) + if (this.ruinedPercent >= 1.0) { this.ruinedPercent = 1f; - this.parent.BroadcastCompSignal("RuinedByTemperature"); + base.parent.BroadcastCompSignal("RuinedByTemperature"); } - else if (this.ruinedPercent < 0f) + else if (this.ruinedPercent < 0.0) { this.ruinedPercent = 0f; } @@ -73,7 +72,7 @@ private void DoTicks(int ticks) public override void PreAbsorbStack(Thing otherStack, int count) { - float t = (float)count / (float)(this.parent.stackCount + count); + float t = (float)count / (float)(base.parent.stackCount + count); CompTemperatureRuinable comp = ((ThingWithComps)otherStack).GetComp(); this.ruinedPercent = Mathf.Lerp(this.ruinedPercent, comp.ruinedPercent, t); } @@ -96,25 +95,25 @@ public override string CompInspectStringExtra() { return "RuinedByTemperature".Translate(); } - if (this.ruinedPercent > 0f) + string str; + if (this.ruinedPercent > 0.0) { - float ambientTemperature = this.parent.AmbientTemperature; - string str; + float ambientTemperature = base.parent.AmbientTemperature; if (ambientTemperature > this.Props.maxSafeTemperature) { str = "Overheating".Translate(); + goto IL_0076; } - else + if (ambientTemperature < this.Props.minSafeTemperature) { - if (ambientTemperature >= this.Props.minSafeTemperature) - { - return null; - } str = "Freezing".Translate(); + goto IL_0076; } - return str + ": " + this.ruinedPercent.ToStringPercent(); + return (string)null; } - return null; + return (string)null; + IL_0076: + return str + ": " + this.ruinedPercent.ToStringPercent(); } } } diff --git a/Assembly-CSharp/RimWorld/CompTerrainPump.cs b/Assembly-CSharp/RimWorld/CompTerrainPump.cs index 3fe5556ae..187f67c20 100644 --- a/Assembly-CSharp/RimWorld/CompTerrainPump.cs +++ b/Assembly-CSharp/RimWorld/CompTerrainPump.cs @@ -1,6 +1,5 @@ using System; using System.Collections.Generic; -using System.Diagnostics; using UnityEngine; using Verse; @@ -16,7 +15,7 @@ private CompProperties_TerrainPump Props { get { - return (CompProperties_TerrainPump)this.props; + return (CompProperties_TerrainPump)base.props; } } @@ -24,7 +23,7 @@ private float ProgressDays { get { - return (float)this.progressTicks / 60000f; + return (float)((float)this.progressTicks / 60000.0); } } @@ -49,19 +48,19 @@ private int TicksUntilRadiusInteger get { float num = Mathf.Ceil(this.CurrentRadius) - this.CurrentRadius; - if (num < 1E-05f) + if (num < 9.9999997473787516E-06) { num = 1f; } float num2 = this.Props.radius / this.Props.daysToRadius; float num3 = num / num2; - return (int)(num3 * 60000f); + return (int)(num3 * 60000.0); } } public override void PostSpawnSetup(bool respawningAfterLoad) { - this.powerComp = this.parent.TryGetComp(); + this.powerComp = base.parent.TryGetComp(); } public override void PostDeSpawn(Map map) @@ -75,9 +74,9 @@ public override void CompTickRare() { this.progressTicks += 250; int num = GenRadial.NumCellsInRadius(this.CurrentRadius); - for (int i = 0; i < num; i++) + for (int num2 = 0; num2 < num; num2++) { - this.AffectCell(this.parent.Position + GenRadial.RadialPattern[i]); + this.AffectCell(base.parent.Position + GenRadial.RadialPattern[num2]); } } } @@ -91,47 +90,36 @@ public override void PostExposeData() public override void PostDrawExtraSelectionOverlays() { - if (this.CurrentRadius < this.Props.radius - 0.0001f) + if (this.CurrentRadius < this.Props.radius - 9.9999997473787516E-05) { - GenDraw.DrawRadiusRing(this.parent.Position, this.CurrentRadius); + GenDraw.DrawRadiusRing(base.parent.Position, this.CurrentRadius); } } public override string CompInspectStringExtra() { - string text = string.Concat(new string[] - { - "TimePassed".Translate().CapitalizeFirst(), - ": ", - this.progressTicks.ToStringTicksToPeriod(true, false, true), - "\n", - "CurrentRadius".Translate().CapitalizeFirst(), - ": ", - this.CurrentRadius.ToString("F1") - }); + string text = "TimePassed".Translate().CapitalizeFirst() + ": " + this.progressTicks.ToStringTicksToPeriod(true, false, true) + "\n" + "CurrentRadius".Translate().CapitalizeFirst() + ": " + this.CurrentRadius.ToString("F1"); if (this.ProgressDays < this.Props.daysToRadius && this.Working) { string text2 = text; - text = string.Concat(new string[] - { - text2, - "\n", - "RadiusExpandsIn".Translate().CapitalizeFirst(), - ": ", - this.TicksUntilRadiusInteger.ToStringTicksToPeriod(true, false, true) - }); + text = text2 + "\n" + "RadiusExpandsIn".Translate().CapitalizeFirst() + ": " + this.TicksUntilRadiusInteger.ToStringTicksToPeriod(true, false, true); } return text; } - [DebuggerHidden] public override IEnumerable CompGetGizmosExtra() { - CompTerrainPump.c__Iterator16E c__Iterator16E = new CompTerrainPump.c__Iterator16E(); - c__Iterator16E.<>f__this = this; - CompTerrainPump.c__Iterator16E expr_0E = c__Iterator16E; - expr_0E.$PC = -2; - return expr_0E; + if (Prefs.DevMode) + { + yield return (Gizmo)new Command_Action + { + defaultLabel = "DEBUG: Progress 1 day", + action = (Action)delegate + { + ((_003CCompGetGizmosExtra_003Ec__Iterator16E)/*Error near IL_004c: stateMachine*/)._003C_003Ef__this.progressTicks += 60000; + } + }; + } } } } diff --git a/Assembly-CSharp/RimWorld/CompTerrainPumpDry.cs b/Assembly-CSharp/RimWorld/CompTerrainPumpDry.cs index c73d684e9..868d17999 100644 --- a/Assembly-CSharp/RimWorld/CompTerrainPumpDry.cs +++ b/Assembly-CSharp/RimWorld/CompTerrainPumpDry.cs @@ -1,4 +1,3 @@ -using System; using Verse; namespace RimWorld @@ -7,18 +6,17 @@ public class CompTerrainPumpDry : CompTerrainPump { protected override void AffectCell(IntVec3 c) { - TerrainDef terrain = c.GetTerrain(this.parent.Map); - if (terrain.driesTo == null) + TerrainDef terrain = c.GetTerrain(base.parent.Map); + if (terrain.driesTo != null) { - return; - } - if (this.parent.Map.Biome == BiomeDefOf.SeaIce) - { - this.parent.Map.terrainGrid.SetTerrain(c, TerrainDefOf.Ice); - } - else - { - this.parent.Map.terrainGrid.SetTerrain(c, terrain.driesTo); + if (base.parent.Map.Biome == BiomeDefOf.SeaIce) + { + base.parent.Map.terrainGrid.SetTerrain(c, TerrainDefOf.Ice); + } + else + { + base.parent.Map.terrainGrid.SetTerrain(c, terrain.driesTo); + } } } } diff --git a/Assembly-CSharp/RimWorld/CompTransporter.cs b/Assembly-CSharp/RimWorld/CompTransporter.cs index 8992f8969..b6578aff3 100644 --- a/Assembly-CSharp/RimWorld/CompTransporter.cs +++ b/Assembly-CSharp/RimWorld/CompTransporter.cs @@ -1,9 +1,9 @@ using System; using System.Collections.Generic; -using System.Diagnostics; using UnityEngine; using Verse; using Verse.AI.Group; +using Verse.Sound; namespace RimWorld { @@ -34,7 +34,7 @@ public CompProperties_Transporter Props { get { - return (CompProperties_Transporter)this.props; + return (CompProperties_Transporter)base.props; } } @@ -42,7 +42,7 @@ public Map Map { get { - return this.parent.MapHeld; + return base.parent.MapHeld; } } @@ -76,7 +76,7 @@ public CompLaunchable Launchable { if (this.cachedCompLaunchable == null) { - this.cachedCompLaunchable = this.parent.GetComp(); + this.cachedCompLaunchable = base.parent.GetComp(); } return this.cachedCompLaunchable; } @@ -90,7 +90,7 @@ public Thing FirstThingLeftToLoad { return null; } - TransferableOneWay transferableOneWay = this.leftToLoad.Find((TransferableOneWay x) => x.CountToTransfer != 0 && x.HasAnyThing); + TransferableOneWay transferableOneWay = this.leftToLoad.Find((Predicate)((TransferableOneWay x) => x.CountToTransfer != 0 && x.HasAnyThing)); if (transferableOneWay != null) { return transferableOneWay.AnyThing; @@ -103,7 +103,7 @@ public Thing FirstThingLeftToLoadInGroup { get { - List list = this.TransportersInGroup(this.parent.Map); + List list = this.TransportersInGroup(base.parent.Map); for (int i = 0; i < list.Count; i++) { Thing firstThingLeftToLoad = list[i].FirstThingLeftToLoad; @@ -125,7 +125,7 @@ public override void PostExposeData() { base.PostExposeData(); Scribe_Values.Look(ref this.groupID, "groupID", 0, false); - Scribe_Deep.Look(ref this.innerContainer, "innerContainer", new object[] + Scribe_Deep.Look(ref this.innerContainer, "innerContainer", new object[1] { this }); @@ -152,14 +152,90 @@ public List TransportersInGroup(Map map) return CompTransporter.tmpTransportersInGroup; } - [DebuggerHidden] public override IEnumerable CompGetGizmosExtra() { - CompTransporter.c__Iterator16F c__Iterator16F = new CompTransporter.c__Iterator16F(); - c__Iterator16F.<>f__this = this; - CompTransporter.c__Iterator16F expr_0E = c__Iterator16F; - expr_0E.$PC = -2; - return expr_0E; + foreach (Gizmo item in base.CompGetGizmosExtra()) + { + yield return item; + } + if (this.LoadingInProgressOrReadyToLaunch) + { + yield return (Gizmo)new Command_Action + { + defaultLabel = "CommandCancelLoad".Translate(), + defaultDesc = "CommandCancelLoadDesc".Translate(), + icon = CompTransporter.CancelLoadCommandTex, + action = (Action)delegate + { + SoundDefOf.DesignateCancel.PlayOneShotOnCamera(null); + ((_003CCompGetGizmosExtra_003Ec__Iterator16F)/*Error near IL_0115: stateMachine*/)._003C_003Ef__this.CancelLoad(); + } + }; + yield return (Gizmo)new Command_Action + { + defaultLabel = "CommandSelectPreviousTransporter".Translate(), + defaultDesc = "CommandSelectPreviousTransporterDesc".Translate(), + icon = CompTransporter.SelectPreviousInGroupCommandTex, + action = (Action)delegate + { + ((_003CCompGetGizmosExtra_003Ec__Iterator16F)/*Error near IL_0189: stateMachine*/)._003C_003Ef__this.SelectPreviousInGroup(); + } + }; + yield return (Gizmo)new Command_Action + { + defaultLabel = "CommandSelectAllTransporters".Translate(), + defaultDesc = "CommandSelectAllTransportersDesc".Translate(), + icon = CompTransporter.SelectAllInGroupCommandTex, + action = (Action)delegate + { + ((_003CCompGetGizmosExtra_003Ec__Iterator16F)/*Error near IL_01fd: stateMachine*/)._003C_003Ef__this.SelectAllInGroup(); + } + }; + yield return (Gizmo)new Command_Action + { + defaultLabel = "CommandSelectNextTransporter".Translate(), + defaultDesc = "CommandSelectNextTransporterDesc".Translate(), + icon = CompTransporter.SelectNextInGroupCommandTex, + action = (Action)delegate + { + ((_003CCompGetGizmosExtra_003Ec__Iterator16F)/*Error near IL_0271: stateMachine*/)._003C_003Ef__this.SelectNextInGroup(); + } + }; + } + else + { + Command_LoadToTransporter loadGroup = new Command_LoadToTransporter(); + int selectedTransportersCount = 0; + for (int i = 0; i < Find.Selector.NumSelected; i++) + { + Thing t = Find.Selector.SelectedObjectsListForReading[i] as Thing; + if (t != null && t.def == base.parent.def) + { + CompLaunchable cl = t.TryGetComp(); + if (cl == null || (cl.FuelingPortSource != null && cl.FuelingPortSourceHasAnyFuel)) + { + selectedTransportersCount++; + } + } + } + loadGroup.defaultLabel = "CommandLoadTransporter".Translate(selectedTransportersCount.ToString()); + loadGroup.defaultDesc = "CommandLoadTransporterDesc".Translate(); + loadGroup.icon = CompTransporter.LoadCommandTex; + loadGroup.transComp = this; + CompLaunchable launchable = this.Launchable; + if (launchable != null) + { + if (!launchable.ConnectedToFuelingPort) + { + loadGroup.Disable("CommandLoadTransporterFailNotConnectedToFuelingPort".Translate()); + } + else if (!launchable.FuelingPortSourceHasAnyFuel) + { + loadGroup.Disable("CommandLoadTransporterFailNoFuel".Translate()); + } + } + yield return (Gizmo)loadGroup; + } } public override void PostDeSpawn(Map map) @@ -169,28 +245,29 @@ public override void PostDeSpawn(Map map) { Messages.Message("MessageTransportersLoadCanceled_TransporterDestroyed".Translate(), MessageSound.Negative); } - this.innerContainer.TryDropAll(this.parent.Position, map, ThingPlaceMode.Near); + this.innerContainer.TryDropAll(base.parent.Position, map, ThingPlaceMode.Near); } public void AddToTheToLoadList(TransferableOneWay t, int count) { - if (!t.HasAnyThing || t.CountToTransfer <= 0) + if (t.HasAnyThing && t.CountToTransfer > 0) { - return; - } - if (this.leftToLoad == null) - { - this.leftToLoad = new List(); - } - if (TransferableUtility.TransferableMatching(t.AnyThing, this.leftToLoad) != null) - { - Log.Error("Transferable already exists."); - return; + if (this.leftToLoad == null) + { + this.leftToLoad = new List(); + } + if (TransferableUtility.TransferableMatching(t.AnyThing, this.leftToLoad) != null) + { + Log.Error("Transferable already exists."); + } + else + { + TransferableOneWay transferableOneWay = new TransferableOneWay(); + this.leftToLoad.Add(transferableOneWay); + transferableOneWay.things.AddRange(t.things); + transferableOneWay.AdjustTo(count); + } } - TransferableOneWay transferableOneWay = new TransferableOneWay(); - this.leftToLoad.Add(transferableOneWay); - transferableOneWay.things.AddRange(t.things); - transferableOneWay.AdjustTo(count); } public void Notify_ThingAdded(Thing t) @@ -226,21 +303,20 @@ public bool CancelLoad(Map map) public void TryRemoveLord(Map map) { - if (!this.LoadingInProgressOrReadyToLaunch) - { - return; - } - Lord lord = TransporterUtility.FindLord(this.groupID, map); - if (lord != null) + if (this.LoadingInProgressOrReadyToLaunch) { - map.lordManager.RemoveLord(lord); + Lord lord = TransporterUtility.FindLord(this.groupID, map); + if (lord != null) + { + map.lordManager.RemoveLord(lord); + } } } public void CleanUpLoadingVars(Map map) { this.groupID = -1; - this.innerContainer.TryDropAll(this.parent.Position, map, ThingPlaceMode.Near); + this.innerContainer.TryDropAll(base.parent.Position, map, ThingPlaceMode.Near); if (this.leftToLoad != null) { this.leftToLoad.Clear(); @@ -249,23 +325,21 @@ public void CleanUpLoadingVars(Map map) private void SubtractFromToLoadList(Thing t, int count) { - if (this.leftToLoad == null) - { - return; - } - TransferableOneWay transferableOneWay = TransferableUtility.TransferableMatchingDesperate(t, this.leftToLoad); - if (transferableOneWay == null) - { - return; - } - transferableOneWay.AdjustBy(-count); - if (transferableOneWay.CountToTransfer <= 0) - { - this.leftToLoad.Remove(transferableOneWay); - } - if (!this.AnyInGroupHasAnythingLeftToLoad) + if (this.leftToLoad != null) { - Messages.Message("MessageFinishedLoadingTransporters".Translate(), this.parent, MessageSound.Benefit); + TransferableOneWay transferableOneWay = TransferableUtility.TransferableMatchingDesperate(t, this.leftToLoad); + if (transferableOneWay != null) + { + transferableOneWay.AdjustBy(-count); + if (transferableOneWay.CountToTransfer <= 0) + { + this.leftToLoad.Remove(transferableOneWay); + } + if (!this.AnyInGroupHasAnythingLeftToLoad) + { + Messages.Message("MessageFinishedLoadingTransporters".Translate(), (Thing)base.parent, MessageSound.Benefit); + } + } } } @@ -273,7 +347,7 @@ private void SelectPreviousInGroup() { List list = this.TransportersInGroup(this.Map); int num = list.IndexOf(this); - CameraJumper.TryJumpAndSelect(list[GenMath.PositiveMod(num - 1, list.Count)].parent); + CameraJumper.TryJumpAndSelect((Thing)list[GenMath.PositiveMod(num - 1, list.Count)].parent); } private void SelectAllInGroup() @@ -291,12 +365,18 @@ private void SelectNextInGroup() { List list = this.TransportersInGroup(this.Map); int num = list.IndexOf(this); - CameraJumper.TryJumpAndSelect(list[(num + 1) % list.Count].parent); + CameraJumper.TryJumpAndSelect((Thing)list[(num + 1) % list.Count].parent); } virtual IThingHolder get_ParentHolder() { return base.ParentHolder; } + + IThingHolder IThingHolder.get_ParentHolder() + { + //ILSpy generated this explicit interface implementation from .override directive in get_ParentHolder + return this.get_ParentHolder(); + } } } diff --git a/Assembly-CSharp/RimWorld/CompUsable.cs b/Assembly-CSharp/RimWorld/CompUsable.cs index 3981fef90..49c639850 100644 --- a/Assembly-CSharp/RimWorld/CompUsable.cs +++ b/Assembly-CSharp/RimWorld/CompUsable.cs @@ -1,6 +1,5 @@ using System; using System.Collections.Generic; -using System.Diagnostics; using System.Linq; using Verse; using Verse.AI; @@ -13,7 +12,7 @@ protected CompProperties_Usable Props { get { - return (CompProperties_Usable)this.props; + return (CompProperties_Usable)base.props; } } @@ -25,37 +24,48 @@ protected virtual string FloatMenuOptionLabel } } - [DebuggerHidden] public override IEnumerable CompFloatMenuOptions(Pawn myPawn) { - CompUsable.c__Iterator169 c__Iterator = new CompUsable.c__Iterator169(); - c__Iterator.myPawn = myPawn; - c__Iterator.<$>myPawn = myPawn; - c__Iterator.<>f__this = this; - CompUsable.c__Iterator169 expr_1C = c__Iterator; - expr_1C.$PC = -2; - return expr_1C; + if (!myPawn.CanReserve((Thing)base.parent, 1, -1, null, false)) + { + yield return new FloatMenuOption(this.FloatMenuOptionLabel + " (" + "Reserved".Translate() + ")", null, MenuOptionPriority.Default, null, null, 0f, null, null); + } + else + { + FloatMenuOption useopt = new FloatMenuOption(this.FloatMenuOptionLabel, (Action)delegate + { + if (((_003CCompFloatMenuOptions_003Ec__Iterator169)/*Error near IL_00a0: stateMachine*/).myPawn.CanReserveAndReach((Thing)((_003CCompFloatMenuOptions_003Ec__Iterator169)/*Error near IL_00a0: stateMachine*/)._003C_003Ef__this.parent, PathEndMode.Touch, Danger.Deadly, 1, -1, null, false)) + { + foreach (CompUseEffect comp in ((_003CCompFloatMenuOptions_003Ec__Iterator169)/*Error near IL_00a0: stateMachine*/)._003C_003Ef__this.parent.GetComps()) + { + if (comp.SelectedUseOption(((_003CCompFloatMenuOptions_003Ec__Iterator169)/*Error near IL_00a0: stateMachine*/).myPawn)) + return; + } + ((_003CCompFloatMenuOptions_003Ec__Iterator169)/*Error near IL_00a0: stateMachine*/)._003C_003Ef__this.TryStartUseJob(((_003CCompFloatMenuOptions_003Ec__Iterator169)/*Error near IL_00a0: stateMachine*/).myPawn); + } + }, MenuOptionPriority.Default, null, null, 0f, null, null); + yield return useopt; + } } public void TryStartUseJob(Pawn user) { - if (!user.CanReserveAndReach(this.parent, PathEndMode.Touch, Danger.Deadly, 1, -1, null, false)) + if (user.CanReserveAndReach((Thing)base.parent, PathEndMode.Touch, Danger.Deadly, 1, -1, null, false)) { - return; + Job job = new Job(this.Props.useJob, (Thing)base.parent); + user.jobs.TryTakeOrderedJob(job, JobTag.Misc); } - Job job = new Job(this.Props.useJob, this.parent); - user.jobs.TryTakeOrderedJob(job, JobTag.Misc); } public void UsedBy(Pawn p) { - foreach (CompUseEffect current in from x in this.parent.GetComps() + foreach (CompUseEffect item in from x in base.parent.GetComps() orderby x.OrderPriority descending select x) { try { - current.DoEffect(p); + item.DoEffect(p); } catch (Exception arg) { diff --git a/Assembly-CSharp/RimWorld/CompUseEffect.cs b/Assembly-CSharp/RimWorld/CompUseEffect.cs index f69cd1535..10f28cdec 100644 --- a/Assembly-CSharp/RimWorld/CompUseEffect.cs +++ b/Assembly-CSharp/RimWorld/CompUseEffect.cs @@ -1,4 +1,3 @@ -using System; using Verse; namespace RimWorld @@ -19,7 +18,7 @@ private CompProperties_UseEffect Props { get { - return (CompProperties_UseEffect)this.props; + return (CompProperties_UseEffect)base.props; } } diff --git a/Assembly-CSharp/RimWorld/CompUseEffect_Artifact.cs b/Assembly-CSharp/RimWorld/CompUseEffect_Artifact.cs index 7f9d30de4..9ff1a6020 100644 --- a/Assembly-CSharp/RimWorld/CompUseEffect_Artifact.cs +++ b/Assembly-CSharp/RimWorld/CompUseEffect_Artifact.cs @@ -1,4 +1,3 @@ -using System; using Verse; using Verse.Sound; @@ -19,7 +18,7 @@ public override void DoEffect(Pawn usedBy) base.DoEffect(usedBy); SoundDefOf.PsychicPulseGlobal.PlayOneShotOnCamera(usedBy.MapHeld); usedBy.records.Increment(RecordDefOf.ArtifactsActivated); - this.parent.Destroy(DestroyMode.Vanish); + base.parent.Destroy(DestroyMode.Vanish); } } } diff --git a/Assembly-CSharp/RimWorld/CompUseEffect_LearnSkill.cs b/Assembly-CSharp/RimWorld/CompUseEffect_LearnSkill.cs index 7229f44c7..cd5336375 100644 --- a/Assembly-CSharp/RimWorld/CompUseEffect_LearnSkill.cs +++ b/Assembly-CSharp/RimWorld/CompUseEffect_LearnSkill.cs @@ -1,4 +1,3 @@ -using System; using Verse; namespace RimWorld @@ -18,21 +17,15 @@ public override float OrderPriority public override void DoEffect(Pawn user) { base.DoEffect(user); - SkillDef skill = this.parent.GetComp().skill; + SkillDef skill = base.parent.GetComp().skill; int level = user.skills.GetSkill(skill).Level; user.skills.Learn(skill, 50000f, true); int level2 = user.skills.GetSkill(skill).Level; if (PawnUtility.ShouldSendNotificationAbout(user)) { - Messages.Message("NeurotrainerUsed".Translate(new object[] - { - user.LabelShort, - skill.label, - level, - level2 - }), user, MessageSound.Benefit); + Messages.Message("NeurotrainerUsed".Translate(user.LabelShort, skill.label, level, level2), (Thing)user, MessageSound.Benefit); } - this.parent.Destroy(DestroyMode.Vanish); + base.parent.Destroy(DestroyMode.Vanish); } } } diff --git a/Assembly-CSharp/RimWorld/CompUseEffect_StartWick.cs b/Assembly-CSharp/RimWorld/CompUseEffect_StartWick.cs index c643b8f62..658002a1c 100644 --- a/Assembly-CSharp/RimWorld/CompUseEffect_StartWick.cs +++ b/Assembly-CSharp/RimWorld/CompUseEffect_StartWick.cs @@ -1,4 +1,3 @@ -using System; using Verse; namespace RimWorld @@ -8,7 +7,7 @@ public class CompUseEffect_StartWick : CompUseEffect public override void DoEffect(Pawn usedBy) { base.DoEffect(usedBy); - this.parent.GetComp().StartWick(null); + base.parent.GetComp().StartWick(null); } } } diff --git a/Assembly-CSharp/RimWorld/ConceptDef.cs b/Assembly-CSharp/RimWorld/ConceptDef.cs index d0b263e5c..50aad6b9a 100644 --- a/Assembly-CSharp/RimWorld/ConceptDef.cs +++ b/Assembly-CSharp/RimWorld/ConceptDef.cs @@ -1,6 +1,4 @@ -using System; using System.Collections.Generic; -using System.Diagnostics; using Verse; namespace RimWorld @@ -25,7 +23,7 @@ public bool TriggeredDirect { get { - return this.priority <= 0f; + return this.priority <= 0.0; } } @@ -40,20 +38,30 @@ public string HelpTextAdjusted public override void PostLoad() { base.PostLoad(); - if (this.defName == "UnnamedDef") + if (base.defName == "UnnamedDef") { - this.defName = this.defName.ToString(); + base.defName = base.defName.ToString(); } } - [DebuggerHidden] public override IEnumerable ConfigErrors() { - ConceptDef.c__Iterator9E c__Iterator9E = new ConceptDef.c__Iterator9E(); - c__Iterator9E.<>f__this = this; - ConceptDef.c__Iterator9E expr_0E = c__Iterator9E; - expr_0E.$PC = -2; - return expr_0E; + foreach (string item in base.ConfigErrors()) + { + yield return item; + } + if (this.priority > 9999999.0) + { + yield return "priority isn't set"; + } + if (this.helpText.NullOrEmpty()) + { + yield return "no help text"; + } + if (this.TriggeredDirect && base.label.NullOrEmpty()) + { + yield return "no label"; + } } public static ConceptDef Named(string defName) diff --git a/Assembly-CSharp/RimWorld/ConceptDefOf.cs b/Assembly-CSharp/RimWorld/ConceptDefOf.cs index 64109190a..796e03873 100644 --- a/Assembly-CSharp/RimWorld/ConceptDefOf.cs +++ b/Assembly-CSharp/RimWorld/ConceptDefOf.cs @@ -1,5 +1,3 @@ -using System; - namespace RimWorld { [DefOf] diff --git a/Assembly-CSharp/RimWorld/CopyPasteUI.cs b/Assembly-CSharp/RimWorld/CopyPasteUI.cs index 077ef9b11..4ff7a7c67 100644 --- a/Assembly-CSharp/RimWorld/CopyPasteUI.cs +++ b/Assembly-CSharp/RimWorld/CopyPasteUI.cs @@ -15,14 +15,14 @@ public static class CopyPasteUI public static void DoCopyPasteButtons(Rect rect, Action copyAction, Action pasteAction) { - Rect rect2 = new Rect(rect.x, rect.y + (rect.height / 2f - 12f), 18f, 24f); + Rect rect2 = new Rect(rect.x, (float)(rect.y + (rect.height / 2.0 - 12.0)), 18f, 24f); if (Widgets.ButtonImage(rect2, TexButton.Copy)) { copyAction(); SoundDefOf.TickHigh.PlayOneShotOnCamera(null); } TooltipHandler.TipRegion(rect2, "Copy".Translate()); - if (pasteAction != null) + if ((object)pasteAction != null) { Rect rect3 = rect2; rect3.x = rect2.xMax; diff --git a/Assembly-CSharp/RimWorld/CostListCalculator.cs b/Assembly-CSharp/RimWorld/CostListCalculator.cs index f008d4b36..4644432e4 100644 --- a/Assembly-CSharp/RimWorld/CostListCalculator.cs +++ b/Assembly-CSharp/RimWorld/CostListCalculator.cs @@ -1,4 +1,3 @@ -using System; using System.Collections.Generic; using UnityEngine; using Verse; @@ -22,7 +21,7 @@ public static List CostListAdjusted(this Thing thing) public static List CostListAdjusted(this BuildableDef entDef, ThingDef stuff, bool errorOnNullStuff = true) { int key = CostListCalculator.RequestHash(entDef, stuff); - List list; + List list = default(List); if (!CostListCalculator.cachedCosts.TryGetValue(key, out list)) { list = new List(); @@ -49,14 +48,7 @@ public static List CostListAdjusted(this BuildableDef entDef, T } else if (stuff != null) { - Log.Error(string.Concat(new object[] - { - "Got AdjustedCostList for ", - entDef, - " with stuff ", - stuff, - " but is not MadeFromStuff." - })); + Log.Error("Got AdjustedCostList for " + entDef + " with stuff " + stuff + " but is not MadeFromStuff."); } bool flag = false; if (entDef.costList != null) @@ -86,10 +78,10 @@ public static List CostListAdjusted(this BuildableDef entDef, T private static int RequestHash(BuildableDef entDef, ThingDef stuff) { - int num = (int)entDef.shortHash; + int num = entDef.shortHash; if (stuff != null) { - num += (int)stuff.shortHash << 16; + num += stuff.shortHash << 16; } return num; } diff --git a/Assembly-CSharp/RimWorld/CreditsAssembler.cs b/Assembly-CSharp/RimWorld/CreditsAssembler.cs index ffb20d6a1..e67527059 100644 --- a/Assembly-CSharp/RimWorld/CreditsAssembler.cs +++ b/Assembly-CSharp/RimWorld/CreditsAssembler.cs @@ -1,19 +1,84 @@ using System; using System.Collections.Generic; -using System.Diagnostics; using Verse; namespace RimWorld { public class CreditsAssembler { - [DebuggerHidden] public static IEnumerable AllCredits() { - CreditsAssembler.c__Iterator19D c__Iterator19D = new CreditsAssembler.c__Iterator19D(); - CreditsAssembler.c__Iterator19D expr_07 = c__Iterator19D; - expr_07.$PC = -2; - return expr_07; + yield return (CreditsEntry)new CreditRecord_Space(200f); + yield return (CreditsEntry)new CreditRecord_Title("Credits_Developers".Translate()); + yield return (CreditsEntry)new CreditRecord_Space(50f); + yield return (CreditsEntry)new CreditRecord_Role("Credit_DirectionVarious", "Tynan Sylvester", "@TynanSylvester"); + yield return (CreditsEntry)new CreditRecord_Space(35f); + yield return (CreditsEntry)new CreditRecord_Role("Credit_Code", "Piotr Walczak", "@isonil11"); + yield return (CreditsEntry)new CreditRecord_Space(35f); + yield return (CreditsEntry)new CreditRecord_Role("Credit_MusicAndSound", "Alistair Lindsay", "@AlistairLindsay"); + yield return (CreditsEntry)new CreditRecord_Space(35f); + yield return (CreditsEntry)new CreditRecord_Role("Credit_GameArt", "Rhopunzel", "@Rhopunzel"); + yield return (CreditsEntry)new CreditRecord_Space(35f); + yield return (CreditsEntry)new CreditRecord_Role("Credit_GameArt", "Kay Fedewa", "@TheZebrafox"); + yield return (CreditsEntry)new CreditRecord_Space(35f); + yield return (CreditsEntry)new CreditRecord_Role("Credit_MenuArt", "Ricardo Tome", (string)null); + yield return (CreditsEntry)new CreditRecord_Space(200f); + yield return (CreditsEntry)new CreditRecord_Title("Credits_TitleCommunity".Translate()); + yield return (CreditsEntry)new CreditRecord_Space(50f); + yield return (CreditsEntry)new CreditRecord_Role("Credit_ModDonation", "Zhentar", (string)null); + yield return (CreditsEntry)new CreditRecord_Role("Credit_ModDonation", "Haplo", (string)null); + yield return (CreditsEntry)new CreditRecord_Role("Credit_ModDonation", "iame6162013", (string)null); + yield return (CreditsEntry)new CreditRecord_Role("Credit_ModDonation", "Shinzy", (string)null); + yield return (CreditsEntry)new CreditRecord_Role("Credit_WritingDonation", "John Woolley", (string)null); + yield return (CreditsEntry)new CreditRecord_Role("Credit_Moderator", "ItchyFlea", (string)null); + yield return (CreditsEntry)new CreditRecord_Role("Credit_Moderator", "Ramsis", (string)null); + yield return (CreditsEntry)new CreditRecord_Role("Credit_Moderator", "Calahan", (string)null); + yield return (CreditsEntry)new CreditRecord_Role("Credit_Moderator", "milon", (string)null); + yield return (CreditsEntry)new CreditRecord_Role("Credit_Moderator", "Evul", (string)null); + yield return (CreditsEntry)new CreditRecord_Role("Credit_Moderator", "Semmy", (string)null); + yield return (CreditsEntry)new CreditRecord_Role("Credit_WikiMaster", "ZestyLemons", (string)null); + yield return (CreditsEntry)new CreditRecord_Role("Credit_Tester", "ItchyFlea", (string)null); + yield return (CreditsEntry)new CreditRecord_Role("Credit_Tester", "Haplo", (string)null); + yield return (CreditsEntry)new CreditRecord_Role("Credit_Tester", "Semmy", (string)null); + yield return (CreditsEntry)new CreditRecord_Role("Credit_Tester", "drb89", (string)null); + yield return (CreditsEntry)new CreditRecord_Role("Credit_Tester", "Skissor", (string)null); + yield return (CreditsEntry)new CreditRecord_Role("Credit_Tester", "MarvinKosh", (string)null); + yield return (CreditsEntry)new CreditRecord_Role("Credit_Tester", "TLHeart", (string)null); + yield return (CreditsEntry)new CreditRecord_Role("Credit_Tester", "Sion", (string)null); + yield return (CreditsEntry)new CreditRecord_Role("Credit_Tester", "Evul", (string)null); + yield return (CreditsEntry)new CreditRecord_Role("Credit_Tester", "enystrom8734", (string)null); + yield return (CreditsEntry)new CreditRecord_Role("Credit_Tester", "pheanox", (string)null); + yield return (CreditsEntry)new CreditRecord_Role("Credit_Tester", "Nasikabatrachus", (string)null); + yield return (CreditsEntry)new CreditRecord_Role("Credit_Tester", "_alphaBeta_", (string)null); + yield return (CreditsEntry)new CreditRecord_Role("Credit_Tester", "letharion", (string)null); + yield return (CreditsEntry)new CreditRecord_Role("Credit_Tester", "Laos", (string)null); + yield return (CreditsEntry)new CreditRecord_Role("Credit_Tester", "Coenmjc", (string)null); + yield return (CreditsEntry)new CreditRecord_Role("Credit_Tester", "Gaesatae", (string)null); + yield return (CreditsEntry)new CreditRecord_Role("Credit_Tester", "skullywag", (string)null); + yield return (CreditsEntry)new CreditRecord_Role("Credit_Tester", "Vas", (string)null); + yield return (CreditsEntry)new CreditRecord_Role("Credit_Tester", "theDee05", (string)null); + yield return (CreditsEntry)new CreditRecord_Role(string.Empty, "Many other gracious volunteers!", (string)null); + yield return (CreditsEntry)new CreditRecord_Space(200f); + foreach (LoadedLanguage allLoadedLanguage in LanguageDatabase.AllLoadedLanguages) + { + if (allLoadedLanguage.info.credits.Count > 0) + { + yield return (CreditsEntry)new CreditRecord_Title("Credits_TitleLanguage".Translate(allLoadedLanguage.FriendlyNameEnglish)); + } + List.Enumerator enumerator2 = allLoadedLanguage.info.credits.GetEnumerator(); + try + { + while (enumerator2.MoveNext()) + { + CreditsEntry langCred = enumerator2.Current; + yield return langCred; + } + } + finally + { + ((IDisposable)(object)enumerator2).Dispose(); + } + } } } } diff --git a/Assembly-CSharp/RimWorld/DamageArmorCategoryDefOf.cs b/Assembly-CSharp/RimWorld/DamageArmorCategoryDefOf.cs index a5219747a..e7fc45b12 100644 --- a/Assembly-CSharp/RimWorld/DamageArmorCategoryDefOf.cs +++ b/Assembly-CSharp/RimWorld/DamageArmorCategoryDefOf.cs @@ -1,4 +1,3 @@ -using System; using Verse; namespace RimWorld diff --git a/Assembly-CSharp/RimWorld/DamageDefOf.cs b/Assembly-CSharp/RimWorld/DamageDefOf.cs index 500aeef55..b1bed58e6 100644 --- a/Assembly-CSharp/RimWorld/DamageDefOf.cs +++ b/Assembly-CSharp/RimWorld/DamageDefOf.cs @@ -1,4 +1,3 @@ -using System; using Verse; namespace RimWorld diff --git a/Assembly-CSharp/RimWorld/DamageWatcher.cs b/Assembly-CSharp/RimWorld/DamageWatcher.cs index 4781d4068..560f47bd7 100644 --- a/Assembly-CSharp/RimWorld/DamageWatcher.cs +++ b/Assembly-CSharp/RimWorld/DamageWatcher.cs @@ -1,4 +1,3 @@ -using System; using Verse; namespace RimWorld @@ -47,23 +46,22 @@ public float DaysSinceSeriousDamage public void Notify_DamageTaken(Thing damagee, float amount) { - if (damagee.Faction != Faction.OfPlayer) + if (damagee.Faction == Faction.OfPlayer) { - return; - } - if (damagee.def.category == ThingCategory.Pawn && damagee.def.race.Humanlike) - { - amount *= 5f; - } - this.recentDamage += amount; - this.everDamage += amount; - if (this.recentDamage > 8000f) - { - this.recentDamage = 8000f; - } - if (this.recentDamage >= 7500f) - { - this.lastSeriousDamageTick = Find.TickManager.TicksGame; + if (damagee.def.category == ThingCategory.Pawn && damagee.def.race.Humanlike) + { + amount = (float)(amount * 5.0); + } + this.recentDamage += amount; + this.everDamage += amount; + if (this.recentDamage > 8000.0) + { + this.recentDamage = 8000f; + } + if (this.recentDamage >= 7500.0) + { + this.lastSeriousDamageTick = Find.TickManager.TicksGame; + } } } @@ -72,7 +70,7 @@ public void DamageWatcherTick() if (Find.TickManager.TicksGame % 2000 == 0) { this.recentDamage -= 70f; - if (this.recentDamage < 0f) + if (this.recentDamage < 0.0) { this.recentDamage = 0f; } diff --git a/Assembly-CSharp/RimWorld/DangerWatcher.cs b/Assembly-CSharp/RimWorld/DangerWatcher.cs index d611d4a01..47a59540d 100644 --- a/Assembly-CSharp/RimWorld/DangerWatcher.cs +++ b/Assembly-CSharp/RimWorld/DangerWatcher.cs @@ -1,4 +1,5 @@ using System; +using System.Collections.Generic; using System.Linq; using UnityEngine; using Verse; @@ -27,12 +28,12 @@ public StoryDanger DangerRating { if (Find.TickManager.TicksGame > this.lastUpdateTick + 101) { - int num = this.map.attackTargetsCache.TargetsHostileToColony.Count((IAttackTarget x) => !x.ThreatDisabled()); + int num = this.map.attackTargetsCache.TargetsHostileToColony.Count((Func)((IAttackTarget x) => !x.ThreatDisabled())); if (num == 0) { this.dangerRatingInt = StoryDanger.None; } - else if (num <= Mathf.CeilToInt((float)this.map.mapPawns.FreeColonistsSpawnedCount * 0.5f)) + else if (num <= Mathf.CeilToInt((float)((float)this.map.mapPawns.FreeColonistsSpawnedCount * 0.5))) { this.dangerRatingInt = StoryDanger.Low; } @@ -45,14 +46,23 @@ public StoryDanger DangerRating } else { - foreach (Lord current in this.map.lordManager.lords) + List.Enumerator enumerator = this.map.lordManager.lords.GetEnumerator(); + try { - if (current.CurLordToil is LordToil_AssaultColony) + while (enumerator.MoveNext()) { - this.dangerRatingInt = StoryDanger.High; - break; + Lord current = enumerator.Current; + if (current.CurLordToil is LordToil_AssaultColony) + { + this.dangerRatingInt = StoryDanger.High; + break; + } } } + finally + { + ((IDisposable)(object)enumerator).Dispose(); + } } } this.lastUpdateTick = Find.TickManager.TicksGame; diff --git a/Assembly-CSharp/RimWorld/DateNotifier.cs b/Assembly-CSharp/RimWorld/DateNotifier.cs index 6db76e21e..fac5cd1e2 100644 --- a/Assembly-CSharp/RimWorld/DateNotifier.cs +++ b/Assembly-CSharp/RimWorld/DateNotifier.cs @@ -1,5 +1,5 @@ -using System; using System.Collections.Generic; +using UnityEngine; using Verse; namespace RimWorld @@ -16,23 +16,42 @@ public void ExposeData() public void DateNotifierTick() { Map map = this.FindPlayerHomeWithMinTimezone(); - float latitude = (map == null) ? 0f : Find.WorldGrid.LongLatOf(map.Tile).y; - float longitude = (map == null) ? 0f : Find.WorldGrid.LongLatOf(map.Tile).x; - Season season = GenDate.Season((long)Find.TickManager.TicksAbs, latitude, longitude); - if (season != this.lastSeason && (this.lastSeason == Season.Undefined || season != this.lastSeason.GetPreviousSeason())) + double num; + if (map != null) { - if (this.lastSeason != Season.Undefined && this.AnyPlayerHomeSeasonsAreMeaningful()) + Vector2 vector = Find.WorldGrid.LongLatOf(map.Tile); + num = vector.y; + } + else + { + num = 0.0; + } + float latitude = (float)num; + double num2; + if (map != null) + { + Vector2 vector2 = Find.WorldGrid.LongLatOf(map.Tile); + num2 = vector2.x; + } + else + { + num2 = 0.0; + } + float longitude = (float)num2; + Season season = GenDate.Season(Find.TickManager.TicksAbs, latitude, longitude); + if (season != this.lastSeason) + { + if (this.lastSeason != 0 && season == this.lastSeason.GetPreviousSeason()) + return; + if (this.lastSeason != 0 && this.AnyPlayerHomeSeasonsAreMeaningful()) { if (GenDate.YearsPassed == 0 && season == Season.Summer && this.AnyPlayerHomeAvgTempIsLowInWinter()) { - Find.LetterStack.ReceiveLetter("LetterLabelFirstSummerWarning".Translate(), "FirstSummerWarning".Translate(), LetterDefOf.Good, null); + Find.LetterStack.ReceiveLetter("LetterLabelFirstSummerWarning".Translate(), "FirstSummerWarning".Translate(), LetterDefOf.Good, (string)null); } else if (GenDate.DaysPassed > 5) { - Messages.Message("MessageSeasonBegun".Translate(new object[] - { - season.Label() - }).CapitalizeFirst(), MessageSound.Standard); + Messages.Message("MessageSeasonBegun".Translate(season.Label()).CapitalizeFirst(), MessageSound.Standard); } } this.lastSeason = season; @@ -48,7 +67,8 @@ private Map FindPlayerHomeWithMinTimezone() { if (maps[i].IsPlayerHome) { - int num2 = GenDate.TimeZoneAt(Find.WorldGrid.LongLatOf(maps[i].Tile).x); + Vector2 vector = Find.WorldGrid.LongLatOf(maps[i].Tile); + int num2 = GenDate.TimeZoneAt(vector.x); if (map == null || num2 < num) { map = maps[i]; @@ -77,9 +97,14 @@ private bool AnyPlayerHomeAvgTempIsLowInWinter() List maps = Find.Maps; for (int i = 0; i < maps.Count; i++) { - if (maps[i].IsPlayerHome && GenTemperature.AverageTemperatureAtTileForTwelfth(maps[i].Tile, Season.Winter.GetMiddleTwelfth(Find.WorldGrid.LongLatOf(maps[i].Tile).y)) < 8f) + if (maps[i].IsPlayerHome) { - return true; + int tile = maps[i].Tile; + Vector2 vector = Find.WorldGrid.LongLatOf(maps[i].Tile); + if (GenTemperature.AverageTemperatureAtTileForTwelfth(tile, Season.Winter.GetMiddleTwelfth(vector.y)) < 8.0) + { + return true; + } } } return false; diff --git a/Assembly-CSharp/RimWorld/DateReadout.cs b/Assembly-CSharp/RimWorld/DateReadout.cs index 17e5ad017..736fcd86e 100644 --- a/Assembly-CSharp/RimWorld/DateReadout.cs +++ b/Assembly-CSharp/RimWorld/DateReadout.cs @@ -37,7 +37,7 @@ static DateReadout() public static void Reset() { - DateReadout.dateString = null; + DateReadout.dateString = (string)null; DateReadout.dateStringDay = -1; DateReadout.dateStringSeason = Season.Undefined; DateReadout.dateStringQuadrum = Quadrum.Undefined; @@ -63,26 +63,27 @@ public static void DateOnGUI(Rect dateRect) else { if (Find.VisibleMap == null) - { return; - } location = Find.WorldGrid.LongLatOf(Find.VisibleMap.Tile); } - int index = GenDate.HourInteger((long)Find.TickManager.TicksAbs, location.x); - int num = GenDate.DayOfTwelfth((long)Find.TickManager.TicksAbs, location.x); - Season season = GenDate.Season((long)Find.TickManager.TicksAbs, location); - Quadrum quadrum = GenDate.Quadrum((long)Find.TickManager.TicksAbs, location.x); - int num2 = GenDate.Year((long)Find.TickManager.TicksAbs, location.x); + int index = GenDate.HourInteger(Find.TickManager.TicksAbs, location.x); + int num = GenDate.DayOfTwelfth(Find.TickManager.TicksAbs, location.x); + Season season = GenDate.Season(Find.TickManager.TicksAbs, location); + Quadrum quadrum = GenDate.Quadrum(Find.TickManager.TicksAbs, location.x); + int num2 = GenDate.Year(Find.TickManager.TicksAbs, location.x); if (num != DateReadout.dateStringDay || season != DateReadout.dateStringSeason || quadrum != DateReadout.dateStringQuadrum || num2 != DateReadout.dateStringYear) { - DateReadout.dateString = GenDate.DateReadoutStringAt((long)Find.TickManager.TicksAbs, location); + DateReadout.dateString = GenDate.DateReadoutStringAt(Find.TickManager.TicksAbs, location); DateReadout.dateStringDay = num; DateReadout.dateStringSeason = season; DateReadout.dateStringQuadrum = quadrum; DateReadout.dateStringYear = num2; } Text.Font = GameFont.Small; - float num3 = Mathf.Max(Text.CalcSize(DateReadout.fastHourStrings[index]).x, Text.CalcSize(DateReadout.dateString).x + 7f); + Vector2 vector = Text.CalcSize(DateReadout.fastHourStrings[index]); + float x = vector.x; + Vector2 vector2 = Text.CalcSize(DateReadout.dateString); + float num3 = Mathf.Max(x, (float)(vector2.x + 7.0)); dateRect.xMin = dateRect.xMax - num3; if (Mouse.IsOver(dateRect)) { @@ -98,23 +99,15 @@ public static void DateOnGUI(Rect dateRect) Widgets.Label(rect, DateReadout.dateString); Text.Anchor = TextAnchor.UpperLeft; GUI.EndGroup(); - TooltipHandler.TipRegion(dateRect, new TipSignal(delegate + TooltipHandler.TipRegion(dateRect, new TipSignal((Func)delegate { StringBuilder stringBuilder = new StringBuilder(); for (int i = 0; i < 4; i++) { - Quadrum quadrum2 = (Quadrum)i; + Quadrum quadrum2 = (Quadrum)(byte)i; stringBuilder.AppendLine(quadrum2.Label() + " - " + quadrum2.GetSeason(location.y).LabelCap()); } - return "DateReadoutTip".Translate(new object[] - { - GenDate.DaysPassed, - 15, - season.LabelCap(), - 15, - GenDate.Quadrum((long)GenTicks.TicksAbs, location.x).Label(), - stringBuilder.ToString() - }); + return "DateReadoutTip".Translate(GenDate.DaysPassed, 15, season.LabelCap(), 15, GenDate.Quadrum(GenTicks.TicksAbs, location.x).Label(), stringBuilder.ToString()); }, 86423)); } } diff --git a/Assembly-CSharp/RimWorld/DeadPlant.cs b/Assembly-CSharp/RimWorld/DeadPlant.cs index 615e2f0d8..29d7ad047 100644 --- a/Assembly-CSharp/RimWorld/DeadPlant.cs +++ b/Assembly-CSharp/RimWorld/DeadPlant.cs @@ -1,5 +1,3 @@ -using System; - namespace RimWorld { public class DeadPlant : Plant @@ -46,7 +44,7 @@ public override PlantLifeStage LifeStage public override string GetInspectStringLowPriority() { - return null; + return (string)null; } public override string GetInspectString() diff --git a/Assembly-CSharp/RimWorld/DeathActionWorker_BigExplosion.cs b/Assembly-CSharp/RimWorld/DeathActionWorker_BigExplosion.cs index 829753cdf..8f3d1f5cd 100644 --- a/Assembly-CSharp/RimWorld/DeathActionWorker_BigExplosion.cs +++ b/Assembly-CSharp/RimWorld/DeathActionWorker_BigExplosion.cs @@ -1,4 +1,3 @@ -using System; using Verse; namespace RimWorld @@ -7,19 +6,7 @@ public class DeathActionWorker_BigExplosion : DeathActionWorker { public override void PawnDied(Corpse corpse) { - float radius; - if (corpse.InnerPawn.ageTracker.CurLifeStageIndex == 0) - { - radius = 1.9f; - } - else if (corpse.InnerPawn.ageTracker.CurLifeStageIndex == 1) - { - radius = 2.9f; - } - else - { - radius = 4.9f; - } + float radius = (float)((corpse.InnerPawn.ageTracker.CurLifeStageIndex != 0) ? ((corpse.InnerPawn.ageTracker.CurLifeStageIndex != 1) ? 4.9000000953674316 : 2.9000000953674316) : 1.8999999761581421); GenExplosion.DoExplosion(corpse.Position, corpse.Map, radius, DamageDefOf.Flame, corpse.InnerPawn, null, null, null, null, 0f, 1, false, null, 0f, 1); } } diff --git a/Assembly-CSharp/RimWorld/DeathActionWorker_SmallExplosion.cs b/Assembly-CSharp/RimWorld/DeathActionWorker_SmallExplosion.cs index a5b23732e..8a60c22c0 100644 --- a/Assembly-CSharp/RimWorld/DeathActionWorker_SmallExplosion.cs +++ b/Assembly-CSharp/RimWorld/DeathActionWorker_SmallExplosion.cs @@ -1,4 +1,3 @@ -using System; using Verse; namespace RimWorld diff --git a/Assembly-CSharp/RimWorld/DefGenerator.cs b/Assembly-CSharp/RimWorld/DefGenerator.cs index 6406cc320..961f345ab 100644 --- a/Assembly-CSharp/RimWorld/DefGenerator.cs +++ b/Assembly-CSharp/RimWorld/DefGenerator.cs @@ -1,4 +1,3 @@ -using System; using System.Collections.Generic; using System.Linq; using Verse; @@ -10,40 +9,40 @@ public static class DefGenerator public static void GenerateImpliedDefs_PreResolve() { IEnumerable enumerable = ThingDefGenerator_Buildings.ImpliedBlueprintAndFrameDefs().Concat(ThingDefGenerator_Meat.ImpliedMeatDefs()).Concat(ThingDefGenerator_Corpses.ImpliedCorpseDefs()).Concat(ThingDefGenerator_Leather.ImpliedLeatherDefs()); - foreach (ThingDef current in enumerable) + foreach (ThingDef item in enumerable) { - current.PostLoad(); - DefDatabase.Add(current); + item.PostLoad(); + DefDatabase.Add(item); } DirectXmlCrossRefLoader.ResolveAllWantedCrossReferences(FailMode.Silent); - foreach (TerrainDef current2 in TerrainDefGenerator_Stone.ImpliedTerrainDefs()) + foreach (TerrainDef item2 in TerrainDefGenerator_Stone.ImpliedTerrainDefs()) { - current2.PostLoad(); - DefDatabase.Add(current2); + item2.PostLoad(); + DefDatabase.Add(item2); } - foreach (RecipeDef current3 in RecipeDefGenerator.ImpliedRecipeDefs()) + foreach (RecipeDef item3 in RecipeDefGenerator.ImpliedRecipeDefs()) { - current3.PostLoad(); - DefDatabase.Add(current3); + item3.PostLoad(); + DefDatabase.Add(item3); } - foreach (PawnColumnDef current4 in PawnColumnDefgenerator.ImpliedPawnColumnDefs()) + foreach (PawnColumnDef item4 in PawnColumnDefgenerator.ImpliedPawnColumnDefs()) { - current4.PostLoad(); - DefDatabase.Add(current4); + item4.PostLoad(); + DefDatabase.Add(item4); } } public static void GenerateImpliedDefs_PostResolve() { - foreach (KeyBindingCategoryDef current in KeyBindingDefGenerator.ImpliedKeyBindingCategoryDefs()) + foreach (KeyBindingCategoryDef item in KeyBindingDefGenerator.ImpliedKeyBindingCategoryDefs()) { - current.PostLoad(); - DefDatabase.Add(current); + item.PostLoad(); + DefDatabase.Add(item); } - foreach (KeyBindingDef current2 in KeyBindingDefGenerator.ImpliedKeyBindingDefs()) + foreach (KeyBindingDef item2 in KeyBindingDefGenerator.ImpliedKeyBindingDefs()) { - current2.PostLoad(); - DefDatabase.Add(current2); + item2.PostLoad(); + DefDatabase.Add(item2); } } } diff --git a/Assembly-CSharp/RimWorld/DefOfHelper.cs b/Assembly-CSharp/RimWorld/DefOfHelper.cs index 20e4c86db..d21cc1f1c 100644 --- a/Assembly-CSharp/RimWorld/DefOfHelper.cs +++ b/Assembly-CSharp/RimWorld/DefOfHelper.cs @@ -11,9 +11,9 @@ public static class DefOfHelper public static void RebindAllDefOfs(bool earlyTryMode) { DefOfHelper.earlyTry = earlyTryMode; - foreach (Type current in GenTypes.AllTypesWithAttribute()) + foreach (Type item in GenTypes.AllTypesWithAttribute()) { - DefOfHelper.BindDefsFor(current); + DefOfHelper.BindDefsFor(item); } } diff --git a/Assembly-CSharp/RimWorld/DesignateMode.cs b/Assembly-CSharp/RimWorld/DesignateMode.cs index aa2ae08e7..1bdbba327 100644 --- a/Assembly-CSharp/RimWorld/DesignateMode.cs +++ b/Assembly-CSharp/RimWorld/DesignateMode.cs @@ -1,10 +1,8 @@ -using System; - namespace RimWorld { public enum DesignateMode : byte { - Add, - Remove + Add = 0, + Remove = 1 } } diff --git a/Assembly-CSharp/RimWorld/DesignationCategoryDefOf.cs b/Assembly-CSharp/RimWorld/DesignationCategoryDefOf.cs index 1f2a19dc4..ee365098c 100644 --- a/Assembly-CSharp/RimWorld/DesignationCategoryDefOf.cs +++ b/Assembly-CSharp/RimWorld/DesignationCategoryDefOf.cs @@ -1,4 +1,3 @@ -using System; using Verse; namespace RimWorld diff --git a/Assembly-CSharp/RimWorld/DesignationDefOf.cs b/Assembly-CSharp/RimWorld/DesignationDefOf.cs index e9f53754d..b43167bb4 100644 --- a/Assembly-CSharp/RimWorld/DesignationDefOf.cs +++ b/Assembly-CSharp/RimWorld/DesignationDefOf.cs @@ -1,4 +1,3 @@ -using System; using Verse; namespace RimWorld diff --git a/Assembly-CSharp/RimWorld/Designator_AreaAllowed.cs b/Assembly-CSharp/RimWorld/Designator_AreaAllowed.cs index 7442bc814..cafe3e6c3 100644 --- a/Assembly-CSharp/RimWorld/Designator_AreaAllowed.cs +++ b/Assembly-CSharp/RimWorld/Designator_AreaAllowed.cs @@ -34,9 +34,9 @@ public static Area SelectedArea public Designator_AreaAllowed(DesignateMode mode) { - this.soundDragSustain = SoundDefOf.DesignateDragStandard; - this.soundDragChanged = SoundDefOf.DesignateDragStandardChanged; - this.useMouseIcon = true; + base.soundDragSustain = SoundDefOf.DesignateDragStandard; + base.soundDragChanged = SoundDefOf.DesignateDragStandardChanged; + base.useMouseIcon = true; } public static void ClearSelectedArea() @@ -55,19 +55,18 @@ public override void SelectedUpdate() public override void ProcessInput(Event ev) { - if (!base.CheckCanInteract()) + if (base.CheckCanInteract()) { - return; + if (Designator_AreaAllowed.selectedArea != null) + { + base.ProcessInput(ev); + } + AreaUtility.MakeAllowedAreaListFloatMenu((Action)delegate(Area a) + { + Designator_AreaAllowed.selectedArea = a; + base.ProcessInput(ev); + }, AllowedAreaMode.Any, false, true, base.Map); } - if (Designator_AreaAllowed.selectedArea != null) - { - base.ProcessInput(ev); - } - AreaUtility.MakeAllowedAreaListFloatMenu(delegate(Area a) - { - Designator_AreaAllowed.selectedArea = a; - this.ProcessInput(ev); - }, AllowedAreaMode.Any, false, true, base.Map); } protected override void FinalizeDesignationSucceeded() diff --git a/Assembly-CSharp/RimWorld/Designator_AreaAllowedClear.cs b/Assembly-CSharp/RimWorld/Designator_AreaAllowedClear.cs index c725e7e48..dcd0de666 100644 --- a/Assembly-CSharp/RimWorld/Designator_AreaAllowedClear.cs +++ b/Assembly-CSharp/RimWorld/Designator_AreaAllowedClear.cs @@ -1,4 +1,3 @@ -using System; using UnityEngine; using Verse; @@ -8,14 +7,14 @@ public class Designator_AreaAllowedClear : Designator_AreaAllowed { public Designator_AreaAllowedClear() : base(DesignateMode.Remove) { - this.defaultLabel = "DesignatorClearAreaAllowed".Translate(); - this.defaultDesc = "DesignatorClearAreaAllowedDesc".Translate(); - this.icon = ContentFinder.Get("UI/Designators/AreaAllowedClear", true); - this.soundDragSustain = SoundDefOf.DesignateDragAreaDelete; - this.soundDragChanged = SoundDefOf.DesignateDragAreaDeleteChanged; - this.soundSucceeded = SoundDefOf.DesignateAreaDelete; - this.hotKey = KeyBindingDefOf.Misc9; - this.tutorTag = "AreaAllowedClear"; + base.defaultLabel = "DesignatorClearAreaAllowed".Translate(); + base.defaultDesc = "DesignatorClearAreaAllowedDesc".Translate(); + base.icon = ContentFinder.Get("UI/Designators/AreaAllowedClear", true); + base.soundDragSustain = SoundDefOf.DesignateDragAreaDelete; + base.soundDragChanged = SoundDefOf.DesignateDragAreaDeleteChanged; + base.soundSucceeded = SoundDefOf.DesignateAreaDelete; + base.hotKey = KeyBindingDefOf.Misc9; + base.tutorTag = "AreaAllowedClear"; } public override AcceptanceReport CanDesignateCell(IntVec3 c) diff --git a/Assembly-CSharp/RimWorld/Designator_AreaAllowedExpand.cs b/Assembly-CSharp/RimWorld/Designator_AreaAllowedExpand.cs index 21dbb2e9d..b18fb11bc 100644 --- a/Assembly-CSharp/RimWorld/Designator_AreaAllowedExpand.cs +++ b/Assembly-CSharp/RimWorld/Designator_AreaAllowedExpand.cs @@ -1,4 +1,3 @@ -using System; using UnityEngine; using Verse; @@ -8,14 +7,14 @@ public class Designator_AreaAllowedExpand : Designator_AreaAllowed { public Designator_AreaAllowedExpand() : base(DesignateMode.Add) { - this.defaultLabel = "DesignatorExpandAreaAllowed".Translate(); - this.defaultDesc = "DesignatorExpandAreaAllowedDesc".Translate(); - this.icon = ContentFinder.Get("UI/Designators/AreaAllowedExpand", true); - this.soundDragSustain = SoundDefOf.DesignateDragAreaAdd; - this.soundDragChanged = SoundDefOf.DesignateDragAreaAddChanged; - this.soundSucceeded = SoundDefOf.DesignateAreaAdd; - this.hotKey = KeyBindingDefOf.Misc8; - this.tutorTag = "AreaAllowedExpand"; + base.defaultLabel = "DesignatorExpandAreaAllowed".Translate(); + base.defaultDesc = "DesignatorExpandAreaAllowedDesc".Translate(); + base.icon = ContentFinder.Get("UI/Designators/AreaAllowedExpand", true); + base.soundDragSustain = SoundDefOf.DesignateDragAreaAdd; + base.soundDragChanged = SoundDefOf.DesignateDragAreaAddChanged; + base.soundSucceeded = SoundDefOf.DesignateAreaAdd; + base.hotKey = KeyBindingDefOf.Misc8; + base.tutorTag = "AreaAllowedExpand"; } public override AcceptanceReport CanDesignateCell(IntVec3 c) diff --git a/Assembly-CSharp/RimWorld/Designator_AreaBuildRoof.cs b/Assembly-CSharp/RimWorld/Designator_AreaBuildRoof.cs index 3a8cf6d9f..bb266350d 100644 --- a/Assembly-CSharp/RimWorld/Designator_AreaBuildRoof.cs +++ b/Assembly-CSharp/RimWorld/Designator_AreaBuildRoof.cs @@ -1,4 +1,3 @@ -using System; using Verse; namespace RimWorld @@ -26,9 +25,9 @@ public override bool DragDrawMeasurements public Designator_AreaBuildRoof(DesignateMode mode) { this.mode = mode; - this.soundDragSustain = SoundDefOf.DesignateDragStandard; - this.soundDragChanged = SoundDefOf.DesignateDragStandardChanged; - this.useMouseIcon = true; + base.soundDragSustain = SoundDefOf.DesignateDragStandard; + base.soundDragChanged = SoundDefOf.DesignateDragStandardChanged; + base.useMouseIcon = true; } public override AcceptanceReport CanDesignateCell(IntVec3 c) @@ -41,7 +40,7 @@ public override AcceptanceReport CanDesignateCell(IntVec3 c) { return false; } - bool flag = base.Map.areaManager.BuildRoof[c]; + bool flag = ((Area)base.Map.areaManager.BuildRoof)[c]; if (this.mode == DesignateMode.Add) { return !flag; @@ -53,12 +52,12 @@ public override void DesignateSingleCell(IntVec3 c) { if (this.mode == DesignateMode.Add) { - base.Map.areaManager.BuildRoof[c] = true; - base.Map.areaManager.NoRoof[c] = false; + ((Area)base.Map.areaManager.BuildRoof)[c] = true; + ((Area)base.Map.areaManager.NoRoof)[c] = false; } else if (this.mode == DesignateMode.Remove) { - base.Map.areaManager.BuildRoof[c] = false; + ((Area)base.Map.areaManager.BuildRoof)[c] = false; } } diff --git a/Assembly-CSharp/RimWorld/Designator_AreaBuildRoofClear.cs b/Assembly-CSharp/RimWorld/Designator_AreaBuildRoofClear.cs index 2172dcaa0..bdec80fb3 100644 --- a/Assembly-CSharp/RimWorld/Designator_AreaBuildRoofClear.cs +++ b/Assembly-CSharp/RimWorld/Designator_AreaBuildRoofClear.cs @@ -1,4 +1,3 @@ -using System; using UnityEngine; using Verse; @@ -8,13 +7,13 @@ public class Designator_AreaBuildRoofClear : Designator_AreaBuildRoof { public Designator_AreaBuildRoofClear() : base(DesignateMode.Remove) { - this.defaultLabel = "DesignatorAreaBuildRoofClear".Translate(); - this.defaultDesc = "DesignatorAreaBuildRoofClearDesc".Translate(); - this.icon = ContentFinder.Get("UI/Designators/BuildRoofAreaClear", true); - this.hotKey = KeyBindingDefOf.Misc11; - this.soundDragSustain = SoundDefOf.DesignateDragAreaDelete; - this.soundDragChanged = SoundDefOf.DesignateDragAreaDeleteChanged; - this.soundSucceeded = SoundDefOf.DesignateAreaDelete; + base.defaultLabel = "DesignatorAreaBuildRoofClear".Translate(); + base.defaultDesc = "DesignatorAreaBuildRoofClearDesc".Translate(); + base.icon = ContentFinder.Get("UI/Designators/BuildRoofAreaClear", true); + base.hotKey = KeyBindingDefOf.Misc11; + base.soundDragSustain = SoundDefOf.DesignateDragAreaDelete; + base.soundDragChanged = SoundDefOf.DesignateDragAreaDeleteChanged; + base.soundSucceeded = SoundDefOf.DesignateAreaDelete; } } } diff --git a/Assembly-CSharp/RimWorld/Designator_AreaBuildRoofExpand.cs b/Assembly-CSharp/RimWorld/Designator_AreaBuildRoofExpand.cs index 6ca609836..b20505f12 100644 --- a/Assembly-CSharp/RimWorld/Designator_AreaBuildRoofExpand.cs +++ b/Assembly-CSharp/RimWorld/Designator_AreaBuildRoofExpand.cs @@ -1,4 +1,3 @@ -using System; using UnityEngine; using Verse; @@ -8,14 +7,14 @@ public class Designator_AreaBuildRoofExpand : Designator_AreaBuildRoof { public Designator_AreaBuildRoofExpand() : base(DesignateMode.Add) { - this.defaultLabel = "DesignatorAreaBuildRoofExpand".Translate(); - this.defaultDesc = "DesignatorAreaBuildRoofExpandDesc".Translate(); - this.icon = ContentFinder.Get("UI/Designators/BuildRoofAreaExpand", true); - this.hotKey = KeyBindingDefOf.Misc10; - this.soundDragSustain = SoundDefOf.DesignateDragAreaAdd; - this.soundDragChanged = SoundDefOf.DesignateDragAreaAddChanged; - this.soundSucceeded = SoundDefOf.DesignateAreaAdd; - this.tutorTag = "AreaBuildRoofExpand"; + base.defaultLabel = "DesignatorAreaBuildRoofExpand".Translate(); + base.defaultDesc = "DesignatorAreaBuildRoofExpandDesc".Translate(); + base.icon = ContentFinder.Get("UI/Designators/BuildRoofAreaExpand", true); + base.hotKey = KeyBindingDefOf.Misc10; + base.soundDragSustain = SoundDefOf.DesignateDragAreaAdd; + base.soundDragChanged = SoundDefOf.DesignateDragAreaAddChanged; + base.soundSucceeded = SoundDefOf.DesignateAreaAdd; + base.tutorTag = "AreaBuildRoofExpand"; } } } diff --git a/Assembly-CSharp/RimWorld/Designator_AreaHome.cs b/Assembly-CSharp/RimWorld/Designator_AreaHome.cs index 67aa4b74e..987e6934b 100644 --- a/Assembly-CSharp/RimWorld/Designator_AreaHome.cs +++ b/Assembly-CSharp/RimWorld/Designator_AreaHome.cs @@ -1,4 +1,3 @@ -using System; using Verse; namespace RimWorld @@ -26,10 +25,10 @@ public override bool DragDrawMeasurements public Designator_AreaHome(DesignateMode mode) { this.mode = mode; - this.soundDragSustain = SoundDefOf.DesignateDragStandard; - this.soundDragChanged = SoundDefOf.DesignateDragStandardChanged; - this.useMouseIcon = true; - this.hotKey = KeyBindingDefOf.Misc7; + base.soundDragSustain = SoundDefOf.DesignateDragStandard; + base.soundDragChanged = SoundDefOf.DesignateDragStandardChanged; + base.useMouseIcon = true; + base.hotKey = KeyBindingDefOf.Misc7; } public override AcceptanceReport CanDesignateCell(IntVec3 c) @@ -38,7 +37,7 @@ public override AcceptanceReport CanDesignateCell(IntVec3 c) { return false; } - bool flag = base.Map.areaManager.Home[c]; + bool flag = ((Area)base.Map.areaManager.Home)[c]; if (this.mode == DesignateMode.Add) { return !flag; @@ -50,11 +49,11 @@ public override void DesignateSingleCell(IntVec3 c) { if (this.mode == DesignateMode.Add) { - base.Map.areaManager.Home[c] = true; + ((Area)base.Map.areaManager.Home)[c] = true; } else { - base.Map.areaManager.Home[c] = false; + ((Area)base.Map.areaManager.Home)[c] = false; } } diff --git a/Assembly-CSharp/RimWorld/Designator_AreaHomeClear.cs b/Assembly-CSharp/RimWorld/Designator_AreaHomeClear.cs index 1deb874bd..c9c2b7cd0 100644 --- a/Assembly-CSharp/RimWorld/Designator_AreaHomeClear.cs +++ b/Assembly-CSharp/RimWorld/Designator_AreaHomeClear.cs @@ -1,4 +1,3 @@ -using System; using UnityEngine; using Verse; @@ -8,12 +7,12 @@ public class Designator_AreaHomeClear : Designator_AreaHome { public Designator_AreaHomeClear() : base(DesignateMode.Remove) { - this.defaultLabel = "DesignatorAreaHomeClear".Translate(); - this.defaultDesc = "DesignatorAreaHomeClearDesc".Translate(); - this.icon = ContentFinder.Get("UI/Designators/HomeAreaOff", true); - this.soundDragSustain = SoundDefOf.DesignateDragAreaDelete; - this.soundDragChanged = SoundDefOf.DesignateDragAreaDeleteChanged; - this.soundSucceeded = SoundDefOf.DesignateAreaDelete; + base.defaultLabel = "DesignatorAreaHomeClear".Translate(); + base.defaultDesc = "DesignatorAreaHomeClearDesc".Translate(); + base.icon = ContentFinder.Get("UI/Designators/HomeAreaOff", true); + base.soundDragSustain = SoundDefOf.DesignateDragAreaDelete; + base.soundDragChanged = SoundDefOf.DesignateDragAreaDeleteChanged; + base.soundSucceeded = SoundDefOf.DesignateAreaDelete; } } } diff --git a/Assembly-CSharp/RimWorld/Designator_AreaHomeExpand.cs b/Assembly-CSharp/RimWorld/Designator_AreaHomeExpand.cs index d7c13a6cd..3cc8947c3 100644 --- a/Assembly-CSharp/RimWorld/Designator_AreaHomeExpand.cs +++ b/Assembly-CSharp/RimWorld/Designator_AreaHomeExpand.cs @@ -1,4 +1,3 @@ -using System; using UnityEngine; using Verse; @@ -8,13 +7,13 @@ public class Designator_AreaHomeExpand : Designator_AreaHome { public Designator_AreaHomeExpand() : base(DesignateMode.Add) { - this.defaultLabel = "DesignatorAreaHomeExpand".Translate(); - this.defaultDesc = "DesignatorAreaHomeExpandDesc".Translate(); - this.icon = ContentFinder.Get("UI/Designators/HomeAreaOn", true); - this.soundDragSustain = SoundDefOf.DesignateDragAreaAdd; - this.soundDragChanged = SoundDefOf.DesignateDragAreaAddChanged; - this.soundSucceeded = SoundDefOf.DesignateAreaAdd; - this.tutorTag = "AreaHomeExpand"; + base.defaultLabel = "DesignatorAreaHomeExpand".Translate(); + base.defaultDesc = "DesignatorAreaHomeExpandDesc".Translate(); + base.icon = ContentFinder.Get("UI/Designators/HomeAreaOn", true); + base.soundDragSustain = SoundDefOf.DesignateDragAreaAdd; + base.soundDragChanged = SoundDefOf.DesignateDragAreaAddChanged; + base.soundSucceeded = SoundDefOf.DesignateAreaAdd; + base.tutorTag = "AreaHomeExpand"; } } } diff --git a/Assembly-CSharp/RimWorld/Designator_AreaNoRoof.cs b/Assembly-CSharp/RimWorld/Designator_AreaNoRoof.cs index 4badcce61..94449da71 100644 --- a/Assembly-CSharp/RimWorld/Designator_AreaNoRoof.cs +++ b/Assembly-CSharp/RimWorld/Designator_AreaNoRoof.cs @@ -1,4 +1,3 @@ -using System; using System.Collections.Generic; using Verse; @@ -33,9 +32,9 @@ public override bool DragDrawMeasurements public Designator_AreaNoRoof(DesignateMode mode) { this.mode = mode; - this.soundDragSustain = SoundDefOf.DesignateDragStandard; - this.soundDragChanged = SoundDefOf.DesignateDragStandardChanged; - this.useMouseIcon = true; + base.soundDragSustain = SoundDefOf.DesignateDragStandard; + base.soundDragChanged = SoundDefOf.DesignateDragStandardChanged; + base.useMouseIcon = true; } public override AcceptanceReport CanDesignateCell(IntVec3 c) @@ -53,7 +52,7 @@ public override AcceptanceReport CanDesignateCell(IntVec3 c) { return "MessageNothingCanRemoveThickRoofs".Translate(); } - bool flag = base.Map.areaManager.NoRoof[c]; + bool flag = ((Area)base.Map.areaManager.NoRoof)[c]; if (this.mode == DesignateMode.Add) { return !flag; @@ -65,12 +64,12 @@ public override void DesignateSingleCell(IntVec3 c) { if (this.mode == DesignateMode.Add) { - base.Map.areaManager.NoRoof[c] = true; + ((Area)base.Map.areaManager.NoRoof)[c] = true; Designator_AreaNoRoof.justAddedCells.Add(c); } else if (this.mode == DesignateMode.Remove) { - base.Map.areaManager.NoRoof[c] = false; + ((Area)base.Map.areaManager.NoRoof)[c] = false; Designator_AreaNoRoof.justRemovedCells.Add(c); } } @@ -82,7 +81,7 @@ protected override void FinalizeDesignationSucceeded() { for (int i = 0; i < Designator_AreaNoRoof.justAddedCells.Count; i++) { - base.Map.areaManager.BuildRoof[Designator_AreaNoRoof.justAddedCells[i]] = false; + ((Area)base.Map.areaManager.BuildRoof)[Designator_AreaNoRoof.justAddedCells[i]] = false; } Designator_AreaNoRoof.justAddedCells.Clear(); } diff --git a/Assembly-CSharp/RimWorld/Designator_AreaNoRoofClear.cs b/Assembly-CSharp/RimWorld/Designator_AreaNoRoofClear.cs index 6d2bd5b0f..e162be0ca 100644 --- a/Assembly-CSharp/RimWorld/Designator_AreaNoRoofClear.cs +++ b/Assembly-CSharp/RimWorld/Designator_AreaNoRoofClear.cs @@ -1,4 +1,3 @@ -using System; using UnityEngine; using Verse; @@ -8,13 +7,13 @@ public class Designator_AreaNoRoofClear : Designator_AreaNoRoof { public Designator_AreaNoRoofClear() : base(DesignateMode.Remove) { - this.defaultLabel = "DesignatorAreaNoRoofClear".Translate(); - this.defaultDesc = "DesignatorAreaNoRoofClearDesc".Translate(); - this.icon = ContentFinder.Get("UI/Designators/NoRoofAreaOff", true); - this.hotKey = KeyBindingDefOf.Misc6; - this.soundDragSustain = SoundDefOf.DesignateDragAreaDelete; - this.soundDragChanged = SoundDefOf.DesignateDragAreaDeleteChanged; - this.soundSucceeded = SoundDefOf.DesignateAreaDelete; + base.defaultLabel = "DesignatorAreaNoRoofClear".Translate(); + base.defaultDesc = "DesignatorAreaNoRoofClearDesc".Translate(); + base.icon = ContentFinder.Get("UI/Designators/NoRoofAreaOff", true); + base.hotKey = KeyBindingDefOf.Misc6; + base.soundDragSustain = SoundDefOf.DesignateDragAreaDelete; + base.soundDragChanged = SoundDefOf.DesignateDragAreaDeleteChanged; + base.soundSucceeded = SoundDefOf.DesignateAreaDelete; } } } diff --git a/Assembly-CSharp/RimWorld/Designator_AreaNoRoofExpand.cs b/Assembly-CSharp/RimWorld/Designator_AreaNoRoofExpand.cs index 26a03e718..1772ce5dd 100644 --- a/Assembly-CSharp/RimWorld/Designator_AreaNoRoofExpand.cs +++ b/Assembly-CSharp/RimWorld/Designator_AreaNoRoofExpand.cs @@ -1,4 +1,3 @@ -using System; using UnityEngine; using Verse; @@ -8,13 +7,13 @@ public class Designator_AreaNoRoofExpand : Designator_AreaNoRoof { public Designator_AreaNoRoofExpand() : base(DesignateMode.Add) { - this.defaultLabel = "DesignatorAreaNoRoofExpand".Translate(); - this.defaultDesc = "DesignatorAreaNoRoofExpandDesc".Translate(); - this.icon = ContentFinder.Get("UI/Designators/NoRoofAreaOn", true); - this.hotKey = KeyBindingDefOf.Misc5; - this.soundDragSustain = SoundDefOf.DesignateDragAreaAdd; - this.soundDragChanged = SoundDefOf.DesignateDragAreaAddChanged; - this.soundSucceeded = SoundDefOf.DesignateAreaAdd; + base.defaultLabel = "DesignatorAreaNoRoofExpand".Translate(); + base.defaultDesc = "DesignatorAreaNoRoofExpandDesc".Translate(); + base.icon = ContentFinder.Get("UI/Designators/NoRoofAreaOn", true); + base.hotKey = KeyBindingDefOf.Misc5; + base.soundDragSustain = SoundDefOf.DesignateDragAreaAdd; + base.soundDragChanged = SoundDefOf.DesignateDragAreaAddChanged; + base.soundSucceeded = SoundDefOf.DesignateAreaAdd; } } } diff --git a/Assembly-CSharp/RimWorld/Designator_AreaSnowClear.cs b/Assembly-CSharp/RimWorld/Designator_AreaSnowClear.cs index 9247a509d..f3399b9d7 100644 --- a/Assembly-CSharp/RimWorld/Designator_AreaSnowClear.cs +++ b/Assembly-CSharp/RimWorld/Designator_AreaSnowClear.cs @@ -1,4 +1,3 @@ -using System; using Verse; namespace RimWorld @@ -26,11 +25,11 @@ public override bool DragDrawMeasurements public Designator_AreaSnowClear(DesignateMode mode) { this.mode = mode; - this.soundDragSustain = SoundDefOf.DesignateDragStandard; - this.soundDragChanged = SoundDefOf.DesignateDragStandardChanged; - this.useMouseIcon = true; - this.hotKey = KeyBindingDefOf.Misc7; - this.tutorTag = "AreaSnowClear"; + base.soundDragSustain = SoundDefOf.DesignateDragStandard; + base.soundDragChanged = SoundDefOf.DesignateDragStandardChanged; + base.useMouseIcon = true; + base.hotKey = KeyBindingDefOf.Misc7; + base.tutorTag = "AreaSnowClear"; } public override AcceptanceReport CanDesignateCell(IntVec3 c) @@ -39,7 +38,7 @@ public override AcceptanceReport CanDesignateCell(IntVec3 c) { return false; } - bool flag = base.Map.areaManager.SnowClear[c]; + bool flag = ((Area)base.Map.areaManager.SnowClear)[c]; if (this.mode == DesignateMode.Add) { return !flag; @@ -51,11 +50,11 @@ public override void DesignateSingleCell(IntVec3 c) { if (this.mode == DesignateMode.Add) { - base.Map.areaManager.SnowClear[c] = true; + ((Area)base.Map.areaManager.SnowClear)[c] = true; } else { - base.Map.areaManager.SnowClear[c] = false; + ((Area)base.Map.areaManager.SnowClear)[c] = false; } } diff --git a/Assembly-CSharp/RimWorld/Designator_AreaSnowClearClear.cs b/Assembly-CSharp/RimWorld/Designator_AreaSnowClearClear.cs index f40b9dbcb..3dd7959f4 100644 --- a/Assembly-CSharp/RimWorld/Designator_AreaSnowClearClear.cs +++ b/Assembly-CSharp/RimWorld/Designator_AreaSnowClearClear.cs @@ -1,4 +1,3 @@ -using System; using UnityEngine; using Verse; @@ -8,12 +7,12 @@ public class Designator_AreaSnowClearClear : Designator_AreaSnowClear { public Designator_AreaSnowClearClear() : base(DesignateMode.Remove) { - this.defaultLabel = "DesignatorAreaSnowClearClear".Translate(); - this.defaultDesc = "DesignatorAreaSnowClearClearDesc".Translate(); - this.icon = ContentFinder.Get("UI/Designators/SnowClearAreaOff", true); - this.soundDragSustain = SoundDefOf.DesignateDragAreaDelete; - this.soundDragChanged = SoundDefOf.DesignateDragAreaDeleteChanged; - this.soundSucceeded = SoundDefOf.DesignateAreaDelete; + base.defaultLabel = "DesignatorAreaSnowClearClear".Translate(); + base.defaultDesc = "DesignatorAreaSnowClearClearDesc".Translate(); + base.icon = ContentFinder.Get("UI/Designators/SnowClearAreaOff", true); + base.soundDragSustain = SoundDefOf.DesignateDragAreaDelete; + base.soundDragChanged = SoundDefOf.DesignateDragAreaDeleteChanged; + base.soundSucceeded = SoundDefOf.DesignateAreaDelete; } } } diff --git a/Assembly-CSharp/RimWorld/Designator_AreaSnowClearExpand.cs b/Assembly-CSharp/RimWorld/Designator_AreaSnowClearExpand.cs index 99182f2b5..6052aa6ee 100644 --- a/Assembly-CSharp/RimWorld/Designator_AreaSnowClearExpand.cs +++ b/Assembly-CSharp/RimWorld/Designator_AreaSnowClearExpand.cs @@ -1,4 +1,3 @@ -using System; using UnityEngine; using Verse; @@ -8,12 +7,12 @@ public class Designator_AreaSnowClearExpand : Designator_AreaSnowClear { public Designator_AreaSnowClearExpand() : base(DesignateMode.Add) { - this.defaultLabel = "DesignatorAreaSnowClearExpand".Translate(); - this.defaultDesc = "DesignatorAreaSnowClearExpandDesc".Translate(); - this.icon = ContentFinder.Get("UI/Designators/SnowClearAreaOn", true); - this.soundDragSustain = SoundDefOf.DesignateDragAreaAdd; - this.soundDragChanged = SoundDefOf.DesignateDragAreaAddChanged; - this.soundSucceeded = SoundDefOf.DesignateAreaAdd; + base.defaultLabel = "DesignatorAreaSnowClearExpand".Translate(); + base.defaultDesc = "DesignatorAreaSnowClearExpandDesc".Translate(); + base.icon = ContentFinder.Get("UI/Designators/SnowClearAreaOn", true); + base.soundDragSustain = SoundDefOf.DesignateDragAreaAdd; + base.soundDragChanged = SoundDefOf.DesignateDragAreaAddChanged; + base.soundSucceeded = SoundDefOf.DesignateAreaAdd; } } } diff --git a/Assembly-CSharp/RimWorld/Designator_Build.cs b/Assembly-CSharp/RimWorld/Designator_Build.cs index b8905c0bd..80d8ca9d7 100644 --- a/Assembly-CSharp/RimWorld/Designator_Build.cs +++ b/Assembly-CSharp/RimWorld/Designator_Build.cs @@ -113,35 +113,38 @@ public override string HighlightTag { get { - if (this.cachedHighlightTag == null && this.tutorTag != null) + if (base.cachedHighlightTag == null && base.tutorTag != null) { - this.cachedHighlightTag = "Designator-Build-" + this.tutorTag; + base.cachedHighlightTag = "Designator-Build-" + base.tutorTag; } - return this.cachedHighlightTag; + return base.cachedHighlightTag; } } public Designator_Build(BuildableDef entDef) { this.entDef = entDef; - this.icon = entDef.uiIcon; - this.hotKey = entDef.designationHotKey; - this.tutorTag = entDef.defName; + base.icon = entDef.uiIcon; + base.hotKey = entDef.designationHotKey; + base.tutorTag = entDef.defName; ThingDef thingDef = entDef as ThingDef; if (thingDef != null && thingDef.uiIconPath.NullOrEmpty()) { - this.iconProportions = thingDef.graphicData.drawSize; - this.iconDrawScale = GenUI.IconDrawScale(thingDef); + base.iconProportions = thingDef.graphicData.drawSize; + base.iconDrawScale = GenUI.IconDrawScale(thingDef); } else { - this.iconProportions = new Vector2(1f, 1f); - this.iconDrawScale = 1f; + base.iconProportions = new Vector2(1f, 1f); + base.iconDrawScale = 1f; } TerrainDef terrainDef = entDef as TerrainDef; if (terrainDef != null) { - this.iconTexCoords = new Rect(0f, 0f, Designator_Build.TerrainTextureCroppedSize.x / (float)this.icon.width, Designator_Build.TerrainTextureCroppedSize.y / (float)this.icon.height); + Vector2 terrainTextureCroppedSize = Designator_Build.TerrainTextureCroppedSize; + float width = terrainTextureCroppedSize.x / (float)base.icon.width; + Vector2 terrainTextureCroppedSize2 = Designator_Build.TerrainTextureCroppedSize; + base.iconTexCoords = new Rect(0f, 0f, width, terrainTextureCroppedSize2.y / (float)base.icon.height); } this.ResetStuffToDefault(); } @@ -161,15 +164,7 @@ public override void DrawMouseAttachments() if (!ArchitectCategoryTab.InfoRect.Contains(UI.MousePositionOnUIInverted)) { DesignationDragger dragger = Find.DesignatorManager.Dragger; - int num; - if (dragger.Dragging) - { - num = dragger.DragCells.Count(); - } - else - { - num = 1; - } + int num = (!dragger.Dragging) ? 1 : dragger.DragCells.Count(); float num2 = 0f; Vector2 vector = Event.current.mousePosition + Designator_Build.DragPriceDrawOffset; List list = this.entDef.CostListAdjusted(this.stuffDef, true); @@ -179,7 +174,7 @@ public override void DrawMouseAttachments() float y = vector.y + num2; Rect position = new Rect(vector.x, y, 27f, 27f); GUI.DrawTexture(position, thingCountClass.thingDef.uiIcon); - Rect rect = new Rect(vector.x + 29f, y, 999f, 29f); + Rect rect = new Rect((float)(vector.x + 29.0), y, 999f, 29f); int num3 = num * thingCountClass.count; string text = num3.ToString(); if (base.Map.resourceCounter.GetCount(thingCountClass.thingDef) < num3) @@ -192,69 +187,74 @@ public override void DrawMouseAttachments() Widgets.Label(rect, text); Text.Anchor = TextAnchor.UpperLeft; GUI.color = Color.white; - num2 += 29f; + num2 = (float)(num2 + 29.0); } } } public override void ProcessInput(Event ev) { - if (!base.CheckCanInteract()) + if (base.CheckCanInteract()) { - return; - } - ThingDef thingDef = this.entDef as ThingDef; - if (thingDef == null || !thingDef.MadeFromStuff) - { - base.ProcessInput(ev); - } - else - { - List list = new List(); - foreach (ThingDef current in base.Map.resourceCounter.AllCountedAmounts.Keys) - { - if (current.IsStuff && current.stuffProps.CanMake(thingDef) && (DebugSettings.godMode || base.Map.listerThings.ThingsOfDef(current).Count > 0)) - { - ThingDef localStuffDef = current; - string labelCap = localStuffDef.LabelCap; - list.Add(new FloatMenuOption(labelCap, delegate - { - this.ProcessInput(ev); - Find.DesignatorManager.Select(this); - this.stuffDef = localStuffDef; - this.writeStuff = true; - }, MenuOptionPriority.Default, null, null, 0f, null, null) - { - tutorTag = "SelectStuff-" + thingDef.defName + "-" + localStuffDef.defName - }); - } - } - if (list.Count == 0) + ThingDef thingDef = this.entDef as ThingDef; + if (thingDef == null || !thingDef.MadeFromStuff) { - Messages.Message("NoStuffsToBuildWith".Translate(), MessageSound.RejectInput); + base.ProcessInput(ev); } else { - FloatMenu floatMenu = new FloatMenu(list); - floatMenu.vanishIfMouseDistant = true; - Find.WindowStack.Add(floatMenu); - Find.DesignatorManager.Select(this); + List list = new List(); + Dictionary.KeyCollection.Enumerator enumerator = base.Map.resourceCounter.AllCountedAmounts.Keys.GetEnumerator(); + try + { + while (enumerator.MoveNext()) + { + ThingDef current = enumerator.Current; + if (current.IsStuff && current.stuffProps.CanMake(thingDef) && (DebugSettings.godMode || base.Map.listerThings.ThingsOfDef(current).Count > 0)) + { + ThingDef localStuffDef = current; + string labelCap = localStuffDef.LabelCap; + FloatMenuOption floatMenuOption = new FloatMenuOption(labelCap, (Action)delegate() + { + base.ProcessInput(ev); + Find.DesignatorManager.Select(this); + this.stuffDef = localStuffDef; + this.writeStuff = true; + }, MenuOptionPriority.Default, null, null, 0f, null, null); + floatMenuOption.tutorTag = "SelectStuff-" + thingDef.defName + "-" + localStuffDef.defName; + list.Add(floatMenuOption); + } + } + } + finally + { + ((IDisposable)(object)enumerator).Dispose(); + } + if (list.Count == 0) + { + Messages.Message("NoStuffsToBuildWith".Translate(), MessageSound.RejectInput); + } + else + { + FloatMenu floatMenu = new FloatMenu(list); + floatMenu.vanishIfMouseDistant = true; + Find.WindowStack.Add(floatMenu); + Find.DesignatorManager.Select(this); + } } } } public override AcceptanceReport CanDesignateCell(IntVec3 c) { - return GenConstruct.CanPlaceBlueprintAt(this.entDef, c, this.placingRot, base.Map, DebugSettings.godMode, null); + return GenConstruct.CanPlaceBlueprintAt(this.entDef, c, base.placingRot, base.Map, DebugSettings.godMode, null); } public override void DesignateSingleCell(IntVec3 c) { if (TutorSystem.TutorialMode && !TutorSystem.AllowAction(new EventPack(base.TutorTagDesignate, c))) - { return; - } - if (DebugSettings.godMode || this.entDef.GetStatValueAbstract(StatDefOf.WorkToBuild, this.stuffDef) == 0f) + if (DebugSettings.godMode || this.entDef.GetStatValueAbstract(StatDefOf.WorkToBuild, this.stuffDef) == 0.0) { if (this.entDef is TerrainDef) { @@ -264,15 +264,15 @@ public override void DesignateSingleCell(IntVec3 c) { Thing thing = ThingMaker.MakeThing((ThingDef)this.entDef, this.stuffDef); thing.SetFactionDirect(Faction.OfPlayer); - GenSpawn.Spawn(thing, c, base.Map, this.placingRot, false); + GenSpawn.Spawn(thing, c, base.Map, base.placingRot, false); } } else { - GenSpawn.WipeExistingThings(c, this.placingRot, this.entDef.blueprintDef, base.Map, DestroyMode.Deconstruct); - GenConstruct.PlaceBlueprintForBuild(this.entDef, c, base.Map, this.placingRot, Faction.OfPlayer, this.stuffDef); + GenSpawn.WipeExistingThings(c, base.placingRot, this.entDef.blueprintDef, base.Map, DestroyMode.Deconstruct); + GenConstruct.PlaceBlueprintForBuild(this.entDef, c, base.Map, base.placingRot, Faction.OfPlayer, this.stuffDef); } - MoteMaker.ThrowMetaPuffs(GenAdj.OccupiedRect(c, this.placingRot, this.entDef.Size), base.Map); + MoteMaker.ThrowMetaPuffs(GenAdj.OccupiedRect(c, base.placingRot, this.entDef.Size), base.Map); ThingDef thingDef = this.entDef as ThingDef; if (thingDef != null && thingDef.IsOrbitalTradeBeacon) { @@ -286,7 +286,7 @@ public override void DesignateSingleCell(IntVec3 c) { for (int i = 0; i < this.entDef.PlaceWorkers.Count; i++) { - this.entDef.PlaceWorkers[i].PostPlace(base.Map, this.entDef, c, this.placingRot); + this.entDef.PlaceWorkers[i].PostPlace(base.Map, this.entDef, c, base.placingRot); } } } @@ -321,24 +321,16 @@ public override void DrawPanelReadout(ref float curY, float width) } GUI.DrawTexture(new Rect(0f, curY, 20f, 20f), image); GUI.color = color; - if (thingCountClass.thingDef != null && thingCountClass.thingDef.resourceReadoutPriority != ResourceCountPriority.Uncounted && base.Map.resourceCounter.GetCount(thingCountClass.thingDef) < thingCountClass.count) + if (thingCountClass.thingDef != null && thingCountClass.thingDef.resourceReadoutPriority != 0 && base.Map.resourceCounter.GetCount(thingCountClass.thingDef) < thingCountClass.count) { GUI.color = Color.red; } - Widgets.Label(new Rect(26f, curY + 2f, 50f, 100f), thingCountClass.count.ToString()); + Widgets.Label(new Rect(26f, (float)(curY + 2.0), 50f, 100f), thingCountClass.count.ToString()); GUI.color = Color.white; - string text; - if (thingCountClass.thingDef == null) - { - text = "(" + "UnchosenStuff".Translate() + ")"; - } - else - { - text = thingCountClass.thingDef.LabelCap; - } - float width2 = width - 60f; - float num = Text.CalcHeight(text, width2) - 2f; - Widgets.Label(new Rect(60f, curY + 2f, width2, num), text); + string text = (thingCountClass.thingDef != null) ? thingCountClass.thingDef.LabelCap : ("(" + "UnchosenStuff".Translate() + ")"); + float width2 = (float)(width - 60.0); + float num = (float)(Text.CalcHeight(text, width2) - 2.0); + Widgets.Label(new Rect(60f, (float)(curY + 2.0), width2, num), text); curY += num; } ThingDef thingDef = this.entDef as ThingDef; diff --git a/Assembly-CSharp/RimWorld/Designator_Cancel.cs b/Assembly-CSharp/RimWorld/Designator_Cancel.cs index 6a74ff33a..97f08df57 100644 --- a/Assembly-CSharp/RimWorld/Designator_Cancel.cs +++ b/Assembly-CSharp/RimWorld/Designator_Cancel.cs @@ -18,15 +18,15 @@ public override int DraggableDimensions public Designator_Cancel() { - this.defaultLabel = "DesignatorCancel".Translate(); - this.defaultDesc = "DesignatorCancelDesc".Translate(); - this.icon = ContentFinder.Get("UI/Designators/Cancel", true); - this.useMouseIcon = true; - this.soundDragSustain = SoundDefOf.DesignateDragStandard; - this.soundDragChanged = SoundDefOf.DesignateDragStandardChanged; - this.soundSucceeded = SoundDefOf.DesignateCancel; - this.hotKey = KeyBindingDefOf.DesignatorCancel; - this.tutorTag = "Cancel"; + base.defaultLabel = "DesignatorCancel".Translate(); + base.defaultDesc = "DesignatorCancelDesc".Translate(); + base.icon = ContentFinder.Get("UI/Designators/Cancel", true); + base.useMouseIcon = true; + base.soundDragSustain = SoundDefOf.DesignateDragStandard; + base.soundDragChanged = SoundDefOf.DesignateDragStandardChanged; + base.soundSucceeded = SoundDefOf.DesignateCancel; + base.hotKey = KeyBindingDefOf.DesignatorCancel; + base.tutorTag = "Cancel"; } public override AcceptanceReport CanDesignateCell(IntVec3 c) @@ -35,7 +35,7 @@ public override AcceptanceReport CanDesignateCell(IntVec3 c) { return false; } - if (this.CancelableDesignationsAt(c).Count() > 0) + if (this.CancelableDesignationsAt(c).Count() > 0) { return true; } @@ -52,19 +52,28 @@ public override AcceptanceReport CanDesignateCell(IntVec3 c) public override void DesignateSingleCell(IntVec3 c) { - foreach (Designation current in this.CancelableDesignationsAt(c).ToList()) + List.Enumerator enumerator = this.CancelableDesignationsAt(c).ToList().GetEnumerator(); + try { - if (current.def.designateCancelable) + while (enumerator.MoveNext()) { - base.Map.designationManager.RemoveDesignation(current); + Designation current = enumerator.Current; + if (current.def.designateCancelable) + { + base.Map.designationManager.RemoveDesignation(current); + } } } + finally + { + ((IDisposable)(object)enumerator).Dispose(); + } List thingList = c.GetThingList(base.Map); - for (int i = thingList.Count - 1; i >= 0; i--) + for (int num = thingList.Count - 1; num >= 0; num--) { - if (this.CanDesignateThing(thingList[i]).Accepted) + if (this.CanDesignateThing(thingList[num]).Accepted) { - this.DesignateThing(thingList[i]); + this.DesignateThing(thingList[num]); } } } @@ -73,9 +82,9 @@ public override AcceptanceReport CanDesignateThing(Thing t) { if (base.Map.designationManager.DesignationOn(t) != null) { - foreach (Designation current in base.Map.designationManager.AllDesignationsOn(t)) + foreach (Designation item in base.Map.designationManager.AllDesignationsOn(t)) { - if (current.def.designateCancelable) + if (item.def.designateCancelable) { return true; } diff --git a/Assembly-CSharp/RimWorld/Designator_Claim.cs b/Assembly-CSharp/RimWorld/Designator_Claim.cs index ff99dc289..b074c62d4 100644 --- a/Assembly-CSharp/RimWorld/Designator_Claim.cs +++ b/Assembly-CSharp/RimWorld/Designator_Claim.cs @@ -18,14 +18,14 @@ public override int DraggableDimensions public Designator_Claim() { - this.defaultLabel = "DesignatorClaim".Translate(); - this.defaultDesc = "DesignatorClaimDesc".Translate(); - this.icon = ContentFinder.Get("UI/Designators/Claim", true); - this.soundDragSustain = SoundDefOf.DesignateDragStandard; - this.soundDragChanged = SoundDefOf.DesignateDragStandardChanged; - this.useMouseIcon = true; - this.soundSucceeded = SoundDefOf.DesignateClaim; - this.hotKey = KeyBindingDefOf.Misc4; + base.defaultLabel = "DesignatorClaim".Translate(); + base.defaultDesc = "DesignatorClaimDesc".Translate(); + base.icon = ContentFinder.Get("UI/Designators/Claim", true); + base.soundDragSustain = SoundDefOf.DesignateDragStandard; + base.soundDragChanged = SoundDefOf.DesignateDragStandardChanged; + base.useMouseIcon = true; + base.soundSucceeded = SoundDefOf.DesignateClaim; + base.hotKey = KeyBindingDefOf.Misc4; } public override AcceptanceReport CanDesignateCell(IntVec3 c) @@ -40,7 +40,7 @@ public override AcceptanceReport CanDesignateCell(IntVec3 c) } if (!(from t in c.GetThingList(base.Map) where this.CanDesignateThing(t).Accepted - select t).Any()) + select t).Any()) { return "MessageMustDesignateClaimable".Translate(); } diff --git a/Assembly-CSharp/RimWorld/Designator_Deconstruct.cs b/Assembly-CSharp/RimWorld/Designator_Deconstruct.cs index 3640c9910..5f3111daf 100644 --- a/Assembly-CSharp/RimWorld/Designator_Deconstruct.cs +++ b/Assembly-CSharp/RimWorld/Designator_Deconstruct.cs @@ -17,14 +17,14 @@ public override int DraggableDimensions public Designator_Deconstruct() { - this.defaultLabel = "DesignatorDeconstruct".Translate(); - this.defaultDesc = "DesignatorDeconstructDesc".Translate(); - this.icon = ContentFinder.Get("UI/Designators/Deconstruct", true); - this.soundDragSustain = SoundDefOf.DesignateDragStandard; - this.soundDragChanged = SoundDefOf.DesignateDragStandardChanged; - this.useMouseIcon = true; - this.soundSucceeded = SoundDefOf.DesignateDeconstruct; - this.hotKey = KeyBindingDefOf.DesignatorDeconstruct; + base.defaultLabel = "DesignatorDeconstruct".Translate(); + base.defaultDesc = "DesignatorDeconstructDesc".Translate(); + base.icon = ContentFinder.Get("UI/Designators/Deconstruct", true); + base.soundDragSustain = SoundDefOf.DesignateDragStandard; + base.soundDragChanged = SoundDefOf.DesignateDragStandardChanged; + base.useMouseIcon = true; + base.soundSucceeded = SoundDefOf.DesignateDeconstruct; + base.hotKey = KeyBindingDefOf.DesignatorDeconstruct; } public override AcceptanceReport CanDesignateCell(IntVec3 c) @@ -37,7 +37,8 @@ public override AcceptanceReport CanDesignateCell(IntVec3 c) { return false; } - if (this.TopDeconstructibleInCell(c) == null) + Thing thing = this.TopDeconstructibleInCell(c); + if (thing == null) { return false; } @@ -51,13 +52,13 @@ public override void DesignateSingleCell(IntVec3 loc) private Thing TopDeconstructibleInCell(IntVec3 loc) { - foreach (Thing current in from t in base.Map.thingGrid.ThingsAt(loc) + foreach (Thing item in from t in base.Map.thingGrid.ThingsAt(loc) orderby t.def.altitudeLayer descending select t) { - if (this.CanDesignateThing(current).Accepted) + if (this.CanDesignateThing(item).Accepted) { - return current; + return item; } } return null; @@ -70,7 +71,7 @@ public override void DesignateThing(Thing t) t.SetFaction(Faction.OfPlayer, null); } Thing innerIfMinified = t.GetInnerIfMinified(); - if (DebugSettings.godMode || innerIfMinified.GetStatValue(StatDefOf.WorkToBuild, true) == 0f || t.def.IsFrame) + if (DebugSettings.godMode || innerIfMinified.GetStatValue(StatDefOf.WorkToBuild, true) == 0.0 || t.def.IsFrame) { t.Destroy(DestroyMode.Deconstruct); } diff --git a/Assembly-CSharp/RimWorld/Designator_Haul.cs b/Assembly-CSharp/RimWorld/Designator_Haul.cs index ddab17d98..7ee2915fe 100644 --- a/Assembly-CSharp/RimWorld/Designator_Haul.cs +++ b/Assembly-CSharp/RimWorld/Designator_Haul.cs @@ -1,4 +1,3 @@ -using System; using UnityEngine; using Verse; @@ -16,33 +15,33 @@ public override int DraggableDimensions public Designator_Haul() { - this.defaultLabel = "DesignatorHaulThings".Translate(); - this.icon = ContentFinder.Get("UI/Designators/Haul", true); - this.defaultDesc = "DesignatorHaulThingsDesc".Translate(); - this.soundDragSustain = SoundDefOf.DesignateDragStandard; - this.soundDragChanged = SoundDefOf.DesignateDragStandardChanged; - this.useMouseIcon = true; - this.soundSucceeded = SoundDefOf.DesignateHaul; - this.hotKey = KeyBindingDefOf.Misc12; + base.defaultLabel = "DesignatorHaulThings".Translate(); + base.icon = ContentFinder.Get("UI/Designators/Haul", true); + base.defaultDesc = "DesignatorHaulThingsDesc".Translate(); + base.soundDragSustain = SoundDefOf.DesignateDragStandard; + base.soundDragChanged = SoundDefOf.DesignateDragStandardChanged; + base.useMouseIcon = true; + base.soundSucceeded = SoundDefOf.DesignateHaul; + base.hotKey = KeyBindingDefOf.Misc12; } public override AcceptanceReport CanDesignateCell(IntVec3 c) { - if (!c.InBounds(base.Map) || c.Fogged(base.Map)) + if (c.InBounds(base.Map) && !c.Fogged(base.Map)) { - return false; - } - Thing firstHaulable = c.GetFirstHaulable(base.Map); - if (firstHaulable == null) - { - return "MessageMustDesignateHaulable".Translate(); + Thing firstHaulable = c.GetFirstHaulable(base.Map); + if (firstHaulable == null) + { + return "MessageMustDesignateHaulable".Translate(); + } + AcceptanceReport result = this.CanDesignateThing(firstHaulable); + if (!result.Accepted) + { + return result; + } + return true; } - AcceptanceReport result = this.CanDesignateThing(firstHaulable); - if (!result.Accepted) - { - return result; - } - return true; + return false; } public override void DesignateSingleCell(IntVec3 c) diff --git a/Assembly-CSharp/RimWorld/Designator_Hunt.cs b/Assembly-CSharp/RimWorld/Designator_Hunt.cs index e00481f13..0a1a5271a 100644 --- a/Assembly-CSharp/RimWorld/Designator_Hunt.cs +++ b/Assembly-CSharp/RimWorld/Designator_Hunt.cs @@ -1,6 +1,5 @@ using System; using System.Collections.Generic; -using System.Diagnostics; using System.Linq; using UnityEngine; using Verse; @@ -21,14 +20,14 @@ public override int DraggableDimensions public Designator_Hunt() { - this.defaultLabel = "DesignatorHunt".Translate(); - this.defaultDesc = "DesignatorHuntDesc".Translate(); - this.icon = ContentFinder.Get("UI/Designators/Hunt", true); - this.soundDragSustain = SoundDefOf.DesignateDragStandard; - this.soundDragChanged = SoundDefOf.DesignateDragStandardChanged; - this.useMouseIcon = true; - this.soundSucceeded = SoundDefOf.DesignateHunt; - this.hotKey = KeyBindingDefOf.Misc11; + base.defaultLabel = "DesignatorHunt".Translate(); + base.defaultDesc = "DesignatorHuntDesc".Translate(); + base.icon = ContentFinder.Get("UI/Designators/Hunt", true); + base.soundDragSustain = SoundDefOf.DesignateDragStandard; + base.soundDragChanged = SoundDefOf.DesignateDragStandardChanged; + base.useMouseIcon = true; + base.soundSucceeded = SoundDefOf.DesignateHunt; + base.hotKey = KeyBindingDefOf.Misc11; } public override AcceptanceReport CanDesignateCell(IntVec3 c) @@ -37,7 +36,7 @@ public override AcceptanceReport CanDesignateCell(IntVec3 c) { return false; } - if (!this.HuntablesInCell(c).Any()) + if (!this.HuntablesInCell(c).Any()) { return "MessageMustDesignateHuntable".Translate(); } @@ -46,9 +45,9 @@ public override AcceptanceReport CanDesignateCell(IntVec3 c) public override void DesignateSingleCell(IntVec3 loc) { - foreach (Pawn current in this.HuntablesInCell(loc)) + foreach (Pawn item in this.HuntablesInCell(loc)) { - this.DesignateThing(current); + this.DesignateThing(item); } } @@ -72,30 +71,35 @@ public override void DesignateThing(Thing t) protected override void FinalizeDesignationSucceeded() { base.FinalizeDesignationSucceeded(); - foreach (PawnKindDef kind in (from p in this.justDesignated - select p.kindDef).Distinct()) + using (IEnumerator enumerator = (from p in this.justDesignated + select p.kindDef).Distinct().GetEnumerator()) { - if (kind.RaceProps.manhunterOnDamageChance > 0.2f) + PawnKindDef kind; + while (enumerator.MoveNext()) { - Messages.Message("MessageAnimalsGoPsychoHunted".Translate(new object[] + kind = enumerator.Current; + if (kind.RaceProps.manhunterOnDamageChance > 0.20000000298023224) { - kind.label - }), this.justDesignated.First((Pawn x) => x.kindDef == kind), MessageSound.Standard); + Messages.Message("MessageAnimalsGoPsychoHunted".Translate(kind.label), (Thing)this.justDesignated.First((Func)((Pawn x) => x.kindDef == kind)), MessageSound.Standard); + } } } this.justDesignated.Clear(); } - [DebuggerHidden] private IEnumerable HuntablesInCell(IntVec3 c) { - Designator_Hunt.c__Iterator18F c__Iterator18F = new Designator_Hunt.c__Iterator18F(); - c__Iterator18F.c = c; - c__Iterator18F.<$>c = c; - c__Iterator18F.<>f__this = this; - Designator_Hunt.c__Iterator18F expr_1C = c__Iterator18F; - expr_1C.$PC = -2; - return expr_1C; + if (!c.Fogged(base.Map)) + { + List thingList = c.GetThingList(base.Map); + for (int i = 0; i < thingList.Count; i++) + { + if (this.CanDesignateThing(thingList[i]).Accepted) + { + yield return (Pawn)thingList[i]; + } + } + } } } } diff --git a/Assembly-CSharp/RimWorld/Designator_Install.cs b/Assembly-CSharp/RimWorld/Designator_Install.cs index bcd6afc7c..5ba76b303 100644 --- a/Assembly-CSharp/RimWorld/Designator_Install.cs +++ b/Assembly-CSharp/RimWorld/Designator_Install.cs @@ -84,14 +84,18 @@ public override bool Visible { get { - return Find.Selector.SingleSelectedThing != null && base.Visible; + if (Find.Selector.SingleSelectedThing == null) + { + return false; + } + return base.Visible; } } public Designator_Install() { - this.icon = TexCommand.Install; - this.iconProportions = new Vector2(1f, 1f); + base.icon = TexCommand.Install; + base.iconProportions = new Vector2(1f, 1f); } public override bool CanRemainSelected() @@ -107,7 +111,7 @@ public override void ProcessInput(Event ev) InstallBlueprintUtility.CancelBlueprintsFor(miniToInstallOrBuildingToReinstall); if (!((ThingDef)this.PlacingDef).rotatable) { - this.placingRot = Rot4.North; + base.placingRot = Rot4.North; } } base.ProcessInput(ev); @@ -115,34 +119,34 @@ public override void ProcessInput(Event ev) public override AcceptanceReport CanDesignateCell(IntVec3 c) { - if (!(this.MiniToInstallOrBuildingToReinstall is MinifiedThing) && c.GetThingList(base.Map).Find((Thing x) => x.Position == c && x.Rotation == this.placingRot && x.def == this.PlacingDef) != null) + if (!(this.MiniToInstallOrBuildingToReinstall is MinifiedThing) && c.GetThingList(base.Map).Find((Predicate)((Thing x) => x.Position == c && x.Rotation == base.placingRot && x.def == this.PlacingDef)) != null) { return new AcceptanceReport("IdenticalThingExists".Translate()); } Thing miniToInstallOrBuildingToReinstall = this.MiniToInstallOrBuildingToReinstall; - return GenConstruct.CanPlaceBlueprintAt(this.PlacingDef, c, this.placingRot, base.Map, false, miniToInstallOrBuildingToReinstall); + return GenConstruct.CanPlaceBlueprintAt(this.PlacingDef, c, base.placingRot, base.Map, false, miniToInstallOrBuildingToReinstall); } public override void DesignateSingleCell(IntVec3 c) { - GenSpawn.WipeExistingThings(c, this.placingRot, this.PlacingDef.installBlueprintDef, base.Map, DestroyMode.Deconstruct); + GenSpawn.WipeExistingThings(c, base.placingRot, this.PlacingDef.installBlueprintDef, base.Map, DestroyMode.Deconstruct); MinifiedThing minifiedThing = this.MiniToInstallOrBuildingToReinstall as MinifiedThing; if (minifiedThing != null) { - GenConstruct.PlaceBlueprintForInstall(minifiedThing, c, base.Map, this.placingRot, Faction.OfPlayer); + GenConstruct.PlaceBlueprintForInstall(minifiedThing, c, base.Map, base.placingRot, Faction.OfPlayer); } else { - GenConstruct.PlaceBlueprintForReinstall((Building)this.MiniToInstallOrBuildingToReinstall, c, base.Map, this.placingRot, Faction.OfPlayer); + GenConstruct.PlaceBlueprintForReinstall((Building)this.MiniToInstallOrBuildingToReinstall, c, base.Map, base.placingRot, Faction.OfPlayer); } - MoteMaker.ThrowMetaPuffs(GenAdj.OccupiedRect(c, this.placingRot, this.PlacingDef.Size), base.Map); + MoteMaker.ThrowMetaPuffs(GenAdj.OccupiedRect(c, base.placingRot, this.PlacingDef.Size), base.Map); Find.DesignatorManager.Deselect(); } protected override void DrawGhost(Color ghostCol) { Graphic baseGraphic = this.ThingToInstall.Graphic.ExtractInnerGraphicFor(this.ThingToInstall); - GhostDrawer.DrawGhostThing(UI.MouseCell(), this.placingRot, (ThingDef)this.PlacingDef, baseGraphic, ghostCol, AltitudeLayer.Blueprint); + GhostDrawer.DrawGhostThing(UI.MouseCell(), base.placingRot, (ThingDef)this.PlacingDef, baseGraphic, ghostCol, AltitudeLayer.Blueprint); } public override void SelectedUpdate() diff --git a/Assembly-CSharp/RimWorld/Designator_Mine.cs b/Assembly-CSharp/RimWorld/Designator_Mine.cs index 73921385e..3b0272ef0 100644 --- a/Assembly-CSharp/RimWorld/Designator_Mine.cs +++ b/Assembly-CSharp/RimWorld/Designator_Mine.cs @@ -1,4 +1,3 @@ -using System; using UnityEngine; using Verse; @@ -24,15 +23,15 @@ public override bool DragDrawMeasurements public Designator_Mine() { - this.defaultLabel = "DesignatorMine".Translate(); - this.icon = ContentFinder.Get("UI/Designators/Mine", true); - this.defaultDesc = "DesignatorMineDesc".Translate(); - this.useMouseIcon = true; - this.soundDragSustain = SoundDefOf.DesignateDragStandard; - this.soundDragChanged = SoundDefOf.DesignateDragStandardChanged; - this.soundSucceeded = SoundDefOf.DesignateMine; - this.hotKey = KeyBindingDefOf.Misc10; - this.tutorTag = "Mine"; + base.defaultLabel = "DesignatorMine".Translate(); + base.icon = ContentFinder.Get("UI/Designators/Mine", true); + base.defaultDesc = "DesignatorMineDesc".Translate(); + base.useMouseIcon = true; + base.soundDragSustain = SoundDefOf.DesignateDragStandard; + base.soundDragChanged = SoundDefOf.DesignateDragStandardChanged; + base.soundSucceeded = SoundDefOf.DesignateMine; + base.hotKey = KeyBindingDefOf.Misc10; + base.tutorTag = "Mine"; } public override AcceptanceReport CanDesignateCell(IntVec3 c) diff --git a/Assembly-CSharp/RimWorld/Designator_Open.cs b/Assembly-CSharp/RimWorld/Designator_Open.cs index 0c2d49057..d29e5a79f 100644 --- a/Assembly-CSharp/RimWorld/Designator_Open.cs +++ b/Assembly-CSharp/RimWorld/Designator_Open.cs @@ -1,6 +1,4 @@ -using System; using System.Collections.Generic; -using System.Diagnostics; using System.Linq; using UnityEngine; using Verse; @@ -19,13 +17,13 @@ public override int DraggableDimensions public Designator_Open() { - this.defaultLabel = "DesignatorOpen".Translate(); - this.defaultDesc = "DesignatorOpenDesc".Translate(); - this.icon = ContentFinder.Get("UI/Designators/Open", true); - this.soundDragSustain = SoundDefOf.DesignateDragStandard; - this.soundDragChanged = SoundDefOf.DesignateDragStandardChanged; - this.useMouseIcon = true; - this.soundSucceeded = SoundDefOf.DesignateClaim; + base.defaultLabel = "DesignatorOpen".Translate(); + base.defaultDesc = "DesignatorOpenDesc".Translate(); + base.icon = ContentFinder.Get("UI/Designators/Open", true); + base.soundDragSustain = SoundDefOf.DesignateDragStandard; + base.soundDragChanged = SoundDefOf.DesignateDragStandardChanged; + base.useMouseIcon = true; + base.soundSucceeded = SoundDefOf.DesignateClaim; } protected override void FinalizeDesignationFailed() @@ -40,7 +38,7 @@ public override AcceptanceReport CanDesignateCell(IntVec3 c) { return false; } - if (!this.OpenablesInCell(c).Any()) + if (!this.OpenablesInCell(c).Any()) { return false; } @@ -49,20 +47,20 @@ public override AcceptanceReport CanDesignateCell(IntVec3 c) public override void DesignateSingleCell(IntVec3 c) { - foreach (Thing current in this.OpenablesInCell(c)) + foreach (Thing item in this.OpenablesInCell(c)) { - this.DesignateThing(current); + this.DesignateThing(item); } } public override AcceptanceReport CanDesignateThing(Thing t) { IOpenable openable = t as IOpenable; - if (openable == null || !openable.CanOpen || base.Map.designationManager.DesignationOn(t, DesignationDefOf.Open) != null) + if (openable != null && openable.CanOpen && base.Map.designationManager.DesignationOn(t, DesignationDefOf.Open) == null) { - return false; + return true; } - return true; + return false; } public override void DesignateThing(Thing t) @@ -70,16 +68,19 @@ public override void DesignateThing(Thing t) base.Map.designationManager.AddDesignation(new Designation(t, DesignationDefOf.Open)); } - [DebuggerHidden] private IEnumerable OpenablesInCell(IntVec3 c) { - Designator_Open.c__Iterator190 c__Iterator = new Designator_Open.c__Iterator190(); - c__Iterator.c = c; - c__Iterator.<$>c = c; - c__Iterator.<>f__this = this; - Designator_Open.c__Iterator190 expr_1C = c__Iterator; - expr_1C.$PC = -2; - return expr_1C; + if (!c.Fogged(base.Map)) + { + List thingList = c.GetThingList(base.Map); + for (int i = 0; i < thingList.Count; i++) + { + if (this.CanDesignateThing(thingList[i]).Accepted) + { + yield return thingList[i]; + } + } + } } } } diff --git a/Assembly-CSharp/RimWorld/Designator_Place.cs b/Assembly-CSharp/RimWorld/Designator_Place.cs index e1e49b6ec..a2b42dc92 100644 --- a/Assembly-CSharp/RimWorld/Designator_Place.cs +++ b/Assembly-CSharp/RimWorld/Designator_Place.cs @@ -22,9 +22,9 @@ public abstract BuildableDef PlacingDef public Designator_Place() { - this.soundDragSustain = SoundDefOf.DesignateDragBuilding; - this.soundDragChanged = SoundDefOf.DesignateDragBuildingChanged; - this.soundSucceeded = SoundDefOf.DesignatePlaceBuilding; + base.soundDragSustain = SoundDefOf.DesignateDragBuilding; + base.soundDragChanged = SoundDefOf.DesignateDragBuildingChanged; + base.soundSucceeded = SoundDefOf.DesignatePlaceBuilding; } public override void DoExtraGuiControls(float leftX, float bottomY) @@ -32,13 +32,13 @@ public override void DoExtraGuiControls(float leftX, float bottomY) ThingDef thingDef = this.PlacingDef as ThingDef; if (thingDef != null && thingDef.rotatable) { - Rect winRect = new Rect(leftX, bottomY - 90f, 200f, 90f); - Find.WindowStack.ImmediateWindow(73095, winRect, WindowLayer.GameUI, delegate + Rect winRect = new Rect(leftX, (float)(bottomY - 90.0), 200f, 90f); + Find.WindowStack.ImmediateWindow(73095, winRect, WindowLayer.GameUI, (Action)delegate { RotationDirection rotationDirection = RotationDirection.None; Text.Anchor = TextAnchor.MiddleCenter; Text.Font = GameFont.Medium; - Rect rect = new Rect(winRect.width / 2f - 64f - 5f, 15f, 64f, 64f); + Rect rect = new Rect((float)(winRect.width / 2.0 - 64.0 - 5.0), 15f, 64f, 64f); if (Widgets.ButtonImage(rect, TexUI.RotLeftTex)) { SoundDefOf.AmountDecrement.PlayOneShotOnCamera(null); @@ -46,7 +46,7 @@ public override void DoExtraGuiControls(float leftX, float bottomY) Event.current.Use(); } Widgets.Label(rect, KeyBindingDefOf.DesignatorRotateLeft.MainKeyLabel); - Rect rect2 = new Rect(winRect.width / 2f + 5f, 15f, 64f, 64f); + Rect rect2 = new Rect((float)(winRect.width / 2.0 + 5.0), 15f, 64f, 64f); if (Widgets.ButtonImage(rect2, TexUI.RotRightTex)) { SoundDefOf.AmountIncrement.PlayOneShotOnCamera(null); @@ -54,7 +54,7 @@ public override void DoExtraGuiControls(float leftX, float bottomY) Event.current.Use(); } Widgets.Label(rect2, KeyBindingDefOf.DesignatorRotateRight.MainKeyLabel); - if (rotationDirection != RotationDirection.None) + if (rotationDirection != 0) { this.placingRot.Rotate(rotationDirection); } @@ -83,23 +83,17 @@ public override void SelectedUpdate() if (this.PlacingDef is TerrainDef) { GenUI.RenderMouseoverBracket(); - return; - } - Color ghostCol; - if (this.CanDesignateCell(intVec).Accepted) - { - ghostCol = new Color(0.5f, 1f, 0.6f, 0.4f); } else { - ghostCol = new Color(1f, 0f, 0f, 0.4f); - } - this.DrawGhost(ghostCol); - if (this.CanDesignateCell(intVec).Accepted && this.PlacingDef.specialDisplayRadius > 0.01f) - { - GenDraw.DrawRadiusRing(UI.MouseCell(), this.PlacingDef.specialDisplayRadius); + Color ghostCol = (!this.CanDesignateCell(intVec).Accepted) ? new Color(1f, 0f, 0f, 0.4f) : new Color(0.5f, 1f, 0.6f, 0.4f); + this.DrawGhost(ghostCol); + if (this.CanDesignateCell(intVec).Accepted && this.PlacingDef.specialDisplayRadius > 0.0099999997764825821) + { + GenDraw.DrawRadiusRing(UI.MouseCell(), this.PlacingDef.specialDisplayRadius); + } + GenDraw.DrawInteractionCell((ThingDef)this.PlacingDef, intVec, this.placingRot); } - GenDraw.DrawInteractionCell((ThingDef)this.PlacingDef, intVec, this.placingRot); } } @@ -118,7 +112,7 @@ private void HandleRotationShortcuts() Event.current.Use(); Designator_Place.middleMouseDownTime = Time.realtimeSinceStartup; } - if (Event.current.type == EventType.MouseUp && Time.realtimeSinceStartup - Designator_Place.middleMouseDownTime < 0.15f) + if (Event.current.type == EventType.MouseUp && Time.realtimeSinceStartup - Designator_Place.middleMouseDownTime < 0.15000000596046448) { rotationDirection = RotationDirection.Clockwise; } diff --git a/Assembly-CSharp/RimWorld/Designator_Plan.cs b/Assembly-CSharp/RimWorld/Designator_Plan.cs index 60e72e8fa..e0a4e0018 100644 --- a/Assembly-CSharp/RimWorld/Designator_Plan.cs +++ b/Assembly-CSharp/RimWorld/Designator_Plan.cs @@ -1,4 +1,3 @@ -using System; using Verse; namespace RimWorld @@ -28,10 +27,10 @@ public override bool DragDrawMeasurements public Designator_Plan(DesignateMode mode) { this.mode = mode; - this.soundDragSustain = SoundDefOf.DesignateDragStandard; - this.soundDragChanged = SoundDefOf.DesignateDragStandardChanged; - this.useMouseIcon = true; - this.hotKey = KeyBindingDefOf.Misc9; + base.soundDragSustain = SoundDefOf.DesignateDragStandard; + base.soundDragChanged = SoundDefOf.DesignateDragStandardChanged; + base.useMouseIcon = true; + base.hotKey = KeyBindingDefOf.Misc9; this.desDef = DesignationDefOf.Plan; } diff --git a/Assembly-CSharp/RimWorld/Designator_PlanAdd.cs b/Assembly-CSharp/RimWorld/Designator_PlanAdd.cs index 22af5ba57..34fe816db 100644 --- a/Assembly-CSharp/RimWorld/Designator_PlanAdd.cs +++ b/Assembly-CSharp/RimWorld/Designator_PlanAdd.cs @@ -1,4 +1,3 @@ -using System; using UnityEngine; using Verse; @@ -8,11 +7,11 @@ public class Designator_PlanAdd : Designator_Plan { public Designator_PlanAdd() : base(DesignateMode.Add) { - this.defaultLabel = "DesignatorPlan".Translate(); - this.defaultDesc = "DesignatorPlanDesc".Translate(); - this.icon = ContentFinder.Get("UI/Designators/PlanOn", true); - this.soundSucceeded = SoundDefOf.DesignatePlanAdd; - this.hotKey = KeyBindingDefOf.Misc9; + base.defaultLabel = "DesignatorPlan".Translate(); + base.defaultDesc = "DesignatorPlanDesc".Translate(); + base.icon = ContentFinder.Get("UI/Designators/PlanOn", true); + base.soundSucceeded = SoundDefOf.DesignatePlanAdd; + base.hotKey = KeyBindingDefOf.Misc9; } } } diff --git a/Assembly-CSharp/RimWorld/Designator_PlanRemove.cs b/Assembly-CSharp/RimWorld/Designator_PlanRemove.cs index c22d35443..8807635f7 100644 --- a/Assembly-CSharp/RimWorld/Designator_PlanRemove.cs +++ b/Assembly-CSharp/RimWorld/Designator_PlanRemove.cs @@ -1,4 +1,3 @@ -using System; using UnityEngine; using Verse; @@ -8,11 +7,11 @@ public class Designator_PlanRemove : Designator_Plan { public Designator_PlanRemove() : base(DesignateMode.Remove) { - this.defaultLabel = "DesignatorPlanRemove".Translate(); - this.defaultDesc = "DesignatorPlanRemoveDesc".Translate(); - this.icon = ContentFinder.Get("UI/Designators/PlanOff", true); - this.soundSucceeded = SoundDefOf.DesignatePlanRemove; - this.hotKey = KeyBindingDefOf.Misc8; + base.defaultLabel = "DesignatorPlanRemove".Translate(); + base.defaultDesc = "DesignatorPlanRemoveDesc".Translate(); + base.icon = ContentFinder.Get("UI/Designators/PlanOff", true); + base.soundSucceeded = SoundDefOf.DesignatePlanRemove; + base.hotKey = KeyBindingDefOf.Misc8; } } } diff --git a/Assembly-CSharp/RimWorld/Designator_Plants.cs b/Assembly-CSharp/RimWorld/Designator_Plants.cs index 893d17dad..1ba16e2ee 100644 --- a/Assembly-CSharp/RimWorld/Designator_Plants.cs +++ b/Assembly-CSharp/RimWorld/Designator_Plants.cs @@ -1,4 +1,3 @@ -using System; using Verse; namespace RimWorld @@ -34,21 +33,21 @@ public override AcceptanceReport CanDesignateThing(Thing t) public override AcceptanceReport CanDesignateCell(IntVec3 c) { - if (!c.InBounds(base.Map) || c.Fogged(base.Map)) + if (c.InBounds(base.Map) && !c.Fogged(base.Map)) { - return false; - } - Plant plant = c.GetPlant(base.Map); - if (plant == null) - { - return "MessageMustDesignatePlants".Translate(); + Plant plant = c.GetPlant(base.Map); + if (plant == null) + { + return "MessageMustDesignatePlants".Translate(); + } + AcceptanceReport result = this.CanDesignateThing(plant); + if (!result.Accepted) + { + return result; + } + return true; } - AcceptanceReport result = this.CanDesignateThing(plant); - if (!result.Accepted) - { - return result; - } - return true; + return false; } public override void DesignateSingleCell(IntVec3 c) diff --git a/Assembly-CSharp/RimWorld/Designator_PlantsCut.cs b/Assembly-CSharp/RimWorld/Designator_PlantsCut.cs index f98a931d2..f9cda709c 100644 --- a/Assembly-CSharp/RimWorld/Designator_PlantsCut.cs +++ b/Assembly-CSharp/RimWorld/Designator_PlantsCut.cs @@ -1,4 +1,3 @@ -using System; using UnityEngine; using Verse; @@ -8,15 +7,15 @@ public class Designator_PlantsCut : Designator_Plants { public Designator_PlantsCut() { - this.defaultLabel = "DesignatorCutPlants".Translate(); - this.defaultDesc = "DesignatorCutPlantsDesc".Translate(); - this.icon = ContentFinder.Get("UI/Designators/CutPlants", true); - this.soundDragSustain = SoundDefOf.DesignateDragStandard; - this.soundDragChanged = SoundDefOf.DesignateDragStandardChanged; - this.useMouseIcon = true; - this.soundSucceeded = SoundDefOf.DesignateCutPlants; - this.hotKey = KeyBindingDefOf.Misc3; - this.designationDef = DesignationDefOf.CutPlant; + base.defaultLabel = "DesignatorCutPlants".Translate(); + base.defaultDesc = "DesignatorCutPlantsDesc".Translate(); + base.icon = ContentFinder.Get("UI/Designators/CutPlants", true); + base.soundDragSustain = SoundDefOf.DesignateDragStandard; + base.soundDragChanged = SoundDefOf.DesignateDragStandardChanged; + base.useMouseIcon = true; + base.soundSucceeded = SoundDefOf.DesignateCutPlants; + base.hotKey = KeyBindingDefOf.Misc3; + base.designationDef = DesignationDefOf.CutPlant; } public override Texture2D IconReverseDesignating(Thing t) diff --git a/Assembly-CSharp/RimWorld/Designator_PlantsHarvest.cs b/Assembly-CSharp/RimWorld/Designator_PlantsHarvest.cs index d4da95943..02c822d52 100644 --- a/Assembly-CSharp/RimWorld/Designator_PlantsHarvest.cs +++ b/Assembly-CSharp/RimWorld/Designator_PlantsHarvest.cs @@ -1,4 +1,3 @@ -using System; using UnityEngine; using Verse; @@ -8,15 +7,15 @@ public class Designator_PlantsHarvest : Designator_Plants { public Designator_PlantsHarvest() { - this.defaultLabel = "DesignatorHarvest".Translate(); - this.defaultDesc = "DesignatorHarvestDesc".Translate(); - this.icon = ContentFinder.Get("UI/Designators/Harvest", true); - this.soundDragSustain = SoundDefOf.DesignateDragStandard; - this.soundDragChanged = SoundDefOf.DesignateDragStandardChanged; - this.useMouseIcon = true; - this.soundSucceeded = SoundDefOf.DesignateHarvest; - this.hotKey = KeyBindingDefOf.Misc2; - this.designationDef = DesignationDefOf.HarvestPlant; + base.defaultLabel = "DesignatorHarvest".Translate(); + base.defaultDesc = "DesignatorHarvestDesc".Translate(); + base.icon = ContentFinder.Get("UI/Designators/Harvest", true); + base.soundDragSustain = SoundDefOf.DesignateDragStandard; + base.soundDragChanged = SoundDefOf.DesignateDragStandardChanged; + base.useMouseIcon = true; + base.soundSucceeded = SoundDefOf.DesignateHarvest; + base.hotKey = KeyBindingDefOf.Misc2; + base.designationDef = DesignationDefOf.HarvestPlant; } public override AcceptanceReport CanDesignateThing(Thing t) @@ -27,11 +26,11 @@ public override AcceptanceReport CanDesignateThing(Thing t) return result; } Plant plant = (Plant)t; - if (!plant.HarvestableNow || plant.def.plant.harvestTag != "Standard") + if (plant.HarvestableNow && !(plant.def.plant.harvestTag != "Standard")) { - return "MessageMustDesignateHarvestable".Translate(); + return true; } - return true; + return "MessageMustDesignateHarvestable".Translate(); } } } diff --git a/Assembly-CSharp/RimWorld/Designator_PlantsHarvestWood.cs b/Assembly-CSharp/RimWorld/Designator_PlantsHarvestWood.cs index 36f7b2d8e..1c396660b 100644 --- a/Assembly-CSharp/RimWorld/Designator_PlantsHarvestWood.cs +++ b/Assembly-CSharp/RimWorld/Designator_PlantsHarvestWood.cs @@ -1,4 +1,3 @@ -using System; using UnityEngine; using Verse; @@ -8,16 +7,16 @@ public class Designator_PlantsHarvestWood : Designator_Plants { public Designator_PlantsHarvestWood() { - this.defaultLabel = "DesignatorHarvestWood".Translate(); - this.defaultDesc = "DesignatorHarvestWoodDesc".Translate(); - this.icon = ContentFinder.Get("UI/Designators/HarvestWood", true); - this.soundDragSustain = SoundDefOf.DesignateDragStandard; - this.soundDragChanged = SoundDefOf.DesignateDragStandardChanged; - this.useMouseIcon = true; - this.soundSucceeded = SoundDefOf.DesignateHarvest; - this.hotKey = KeyBindingDefOf.Misc1; - this.designationDef = DesignationDefOf.HarvestPlant; - this.tutorTag = "PlantsHarvestWood"; + base.defaultLabel = "DesignatorHarvestWood".Translate(); + base.defaultDesc = "DesignatorHarvestWoodDesc".Translate(); + base.icon = ContentFinder.Get("UI/Designators/HarvestWood", true); + base.soundDragSustain = SoundDefOf.DesignateDragStandard; + base.soundDragChanged = SoundDefOf.DesignateDragStandardChanged; + base.useMouseIcon = true; + base.soundSucceeded = SoundDefOf.DesignateHarvest; + base.hotKey = KeyBindingDefOf.Misc1; + base.designationDef = DesignationDefOf.HarvestPlant; + base.tutorTag = "PlantsHarvestWood"; } public override AcceptanceReport CanDesignateThing(Thing t) @@ -28,11 +27,11 @@ public override AcceptanceReport CanDesignateThing(Thing t) return result; } Plant plant = (Plant)t; - if (!plant.HarvestableNow || plant.def.plant.harvestTag != "Wood") + if (plant.HarvestableNow && !(plant.def.plant.harvestTag != "Wood")) { - return "MessageMustDesignateHarvestableWood".Translate(); + return true; } - return true; + return "MessageMustDesignateHarvestableWood".Translate(); } } } diff --git a/Assembly-CSharp/RimWorld/Designator_RearmTrap.cs b/Assembly-CSharp/RimWorld/Designator_RearmTrap.cs index cc603d53d..ceed8997d 100644 --- a/Assembly-CSharp/RimWorld/Designator_RearmTrap.cs +++ b/Assembly-CSharp/RimWorld/Designator_RearmTrap.cs @@ -1,6 +1,4 @@ -using System; using System.Collections.Generic; -using System.Diagnostics; using System.Linq; using UnityEngine; using Verse; @@ -19,14 +17,14 @@ public override int DraggableDimensions public Designator_RearmTrap() { - this.defaultLabel = "DesignatorRearmTrap".Translate(); - this.defaultDesc = "DesignatorRearmTrapDesc".Translate(); - this.icon = ContentFinder.Get("UI/Designators/RearmTrap", true); - this.soundDragSustain = SoundDefOf.DesignateDragStandard; - this.soundDragChanged = SoundDefOf.DesignateDragStandardChanged; - this.useMouseIcon = true; - this.soundSucceeded = SoundDefOf.DesignateClaim; - this.hotKey = KeyBindingDefOf.Misc7; + base.defaultLabel = "DesignatorRearmTrap".Translate(); + base.defaultDesc = "DesignatorRearmTrapDesc".Translate(); + base.icon = ContentFinder.Get("UI/Designators/RearmTrap", true); + base.soundDragSustain = SoundDefOf.DesignateDragStandard; + base.soundDragChanged = SoundDefOf.DesignateDragStandardChanged; + base.useMouseIcon = true; + base.soundSucceeded = SoundDefOf.DesignateClaim; + base.hotKey = KeyBindingDefOf.Misc7; } public override AcceptanceReport CanDesignateCell(IntVec3 c) @@ -35,7 +33,7 @@ public override AcceptanceReport CanDesignateCell(IntVec3 c) { return false; } - if (!this.RearmablesInCell(c).Any()) + if (!this.RearmablesInCell(c).Any()) { return false; } @@ -44,9 +42,9 @@ public override AcceptanceReport CanDesignateCell(IntVec3 c) public override void DesignateSingleCell(IntVec3 c) { - foreach (Thing current in this.RearmablesInCell(c)) + foreach (Thing item in this.RearmablesInCell(c)) { - this.DesignateThing(current); + this.DesignateThing(item); } } @@ -61,16 +59,19 @@ public override void DesignateThing(Thing t) base.Map.designationManager.AddDesignation(new Designation(t, DesignationDefOf.RearmTrap)); } - [DebuggerHidden] private IEnumerable RearmablesInCell(IntVec3 c) { - Designator_RearmTrap.c__Iterator191 c__Iterator = new Designator_RearmTrap.c__Iterator191(); - c__Iterator.c = c; - c__Iterator.<$>c = c; - c__Iterator.<>f__this = this; - Designator_RearmTrap.c__Iterator191 expr_1C = c__Iterator; - expr_1C.$PC = -2; - return expr_1C; + if (!c.Fogged(base.Map)) + { + List thingList = c.GetThingList(base.Map); + for (int i = 0; i < thingList.Count; i++) + { + if (this.CanDesignateThing(thingList[i]).Accepted) + { + yield return thingList[i]; + } + } + } } } } diff --git a/Assembly-CSharp/RimWorld/Designator_RemoveFloor.cs b/Assembly-CSharp/RimWorld/Designator_RemoveFloor.cs index 3ad3c4153..60e9c0ca0 100644 --- a/Assembly-CSharp/RimWorld/Designator_RemoveFloor.cs +++ b/Assembly-CSharp/RimWorld/Designator_RemoveFloor.cs @@ -1,4 +1,3 @@ -using System; using UnityEngine; using Verse; @@ -24,36 +23,36 @@ public override bool DragDrawMeasurements public Designator_RemoveFloor() { - this.defaultLabel = "DesignatorRemoveFloor".Translate(); - this.defaultDesc = "DesignatorRemoveFloorDesc".Translate(); - this.icon = ContentFinder.Get("UI/Designators/RemoveFloor", true); - this.useMouseIcon = true; - this.soundDragSustain = SoundDefOf.DesignateDragStandard; - this.soundDragChanged = SoundDefOf.DesignateDragStandardChanged; - this.soundSucceeded = SoundDefOf.DesignateSmoothFloor; - this.hotKey = KeyBindingDefOf.Misc1; + base.defaultLabel = "DesignatorRemoveFloor".Translate(); + base.defaultDesc = "DesignatorRemoveFloorDesc".Translate(); + base.icon = ContentFinder.Get("UI/Designators/RemoveFloor", true); + base.useMouseIcon = true; + base.soundDragSustain = SoundDefOf.DesignateDragStandard; + base.soundDragChanged = SoundDefOf.DesignateDragStandardChanged; + base.soundSucceeded = SoundDefOf.DesignateSmoothFloor; + base.hotKey = KeyBindingDefOf.Misc1; } public override AcceptanceReport CanDesignateCell(IntVec3 c) { - if (!c.InBounds(base.Map) || c.Fogged(base.Map)) + if (c.InBounds(base.Map) && !c.Fogged(base.Map)) { - return false; + if (base.Map.designationManager.DesignationAt(c, DesignationDefOf.RemoveFloor) != null) + { + return false; + } + Building edifice = c.GetEdifice(base.Map); + if (edifice != null && edifice.def.Fillage == FillCategory.Full && edifice.def.passability == Traversability.Impassable) + { + return false; + } + if (!base.Map.terrainGrid.CanRemoveTopLayerAt(c)) + { + return "TerrainMustBeRemovable".Translate(); + } + return AcceptanceReport.WasAccepted; } - if (base.Map.designationManager.DesignationAt(c, DesignationDefOf.RemoveFloor) != null) - { - return false; - } - Building edifice = c.GetEdifice(base.Map); - if (edifice != null && edifice.def.Fillage == FillCategory.Full && edifice.def.passability == Traversability.Impassable) - { - return false; - } - if (!base.Map.terrainGrid.CanRemoveTopLayerAt(c)) - { - return "TerrainMustBeRemovable".Translate(); - } - return AcceptanceReport.WasAccepted; + return false; } public override void DesignateSingleCell(IntVec3 c) @@ -61,9 +60,11 @@ public override void DesignateSingleCell(IntVec3 c) if (DebugSettings.godMode) { base.Map.terrainGrid.RemoveTopLayer(c, true); - return; } - base.Map.designationManager.AddDesignation(new Designation(c, DesignationDefOf.RemoveFloor)); + else + { + base.Map.designationManager.AddDesignation(new Designation(c, DesignationDefOf.RemoveFloor)); + } } public override void SelectedUpdate() diff --git a/Assembly-CSharp/RimWorld/Designator_Slaughter.cs b/Assembly-CSharp/RimWorld/Designator_Slaughter.cs index 64faa0e0b..9579c4412 100644 --- a/Assembly-CSharp/RimWorld/Designator_Slaughter.cs +++ b/Assembly-CSharp/RimWorld/Designator_Slaughter.cs @@ -1,6 +1,4 @@ -using System; using System.Collections.Generic; -using System.Diagnostics; using System.Linq; using UnityEngine; using Verse; @@ -21,14 +19,14 @@ public override int DraggableDimensions public Designator_Slaughter() { - this.defaultLabel = "DesignatorSlaughter".Translate(); - this.defaultDesc = "DesignatorSlaughterDesc".Translate(); - this.icon = ContentFinder.Get("UI/Designators/Slaughter", true); - this.soundDragSustain = SoundDefOf.DesignateDragStandard; - this.soundDragChanged = SoundDefOf.DesignateDragStandardChanged; - this.useMouseIcon = true; - this.soundSucceeded = SoundDefOf.DesignateHunt; - this.hotKey = KeyBindingDefOf.Misc11; + base.defaultLabel = "DesignatorSlaughter".Translate(); + base.defaultDesc = "DesignatorSlaughterDesc".Translate(); + base.icon = ContentFinder.Get("UI/Designators/Slaughter", true); + base.soundDragSustain = SoundDefOf.DesignateDragStandard; + base.soundDragChanged = SoundDefOf.DesignateDragStandardChanged; + base.useMouseIcon = true; + base.soundSucceeded = SoundDefOf.DesignateHunt; + base.hotKey = KeyBindingDefOf.Misc11; } public override AcceptanceReport CanDesignateCell(IntVec3 c) @@ -37,7 +35,7 @@ public override AcceptanceReport CanDesignateCell(IntVec3 c) { return false; } - if (!this.SlaughterablesInCell(c).Any()) + if (!this.SlaughterablesInCell(c).Any()) { return "MessageMustDesignateSlaughterable".Translate(); } @@ -46,9 +44,9 @@ public override AcceptanceReport CanDesignateCell(IntVec3 c) public override void DesignateSingleCell(IntVec3 loc) { - foreach (Pawn current in this.SlaughterablesInCell(loc)) + foreach (Pawn item in this.SlaughterablesInCell(loc)) { - this.DesignateThing(current); + this.DesignateThing(item); } } @@ -78,16 +76,19 @@ protected override void FinalizeDesignationSucceeded() this.justDesignated.Clear(); } - [DebuggerHidden] private IEnumerable SlaughterablesInCell(IntVec3 c) { - Designator_Slaughter.c__Iterator192 c__Iterator = new Designator_Slaughter.c__Iterator192(); - c__Iterator.c = c; - c__Iterator.<$>c = c; - c__Iterator.<>f__this = this; - Designator_Slaughter.c__Iterator192 expr_1C = c__Iterator; - expr_1C.$PC = -2; - return expr_1C; + if (!c.Fogged(base.Map)) + { + List thingList = c.GetThingList(base.Map); + for (int i = 0; i < thingList.Count; i++) + { + if (this.CanDesignateThing(thingList[i]).Accepted) + { + yield return (Pawn)thingList[i]; + } + } + } } } } diff --git a/Assembly-CSharp/RimWorld/Designator_SmoothFloor.cs b/Assembly-CSharp/RimWorld/Designator_SmoothFloor.cs index 9f87a6085..e86db7ffd 100644 --- a/Assembly-CSharp/RimWorld/Designator_SmoothFloor.cs +++ b/Assembly-CSharp/RimWorld/Designator_SmoothFloor.cs @@ -1,4 +1,3 @@ -using System; using UnityEngine; using Verse; @@ -24,14 +23,14 @@ public override bool DragDrawMeasurements public Designator_SmoothFloor() { - this.defaultLabel = "DesignatorSmoothFloor".Translate(); - this.defaultDesc = "DesignatorSmoothFloorDesc".Translate(); - this.icon = ContentFinder.Get("UI/Designators/SmoothFloor", true); - this.useMouseIcon = true; - this.soundDragSustain = SoundDefOf.DesignateDragStandard; - this.soundDragChanged = SoundDefOf.DesignateDragStandardChanged; - this.soundSucceeded = SoundDefOf.DesignateSmoothFloor; - this.hotKey = KeyBindingDefOf.Misc1; + base.defaultLabel = "DesignatorSmoothFloor".Translate(); + base.defaultDesc = "DesignatorSmoothFloorDesc".Translate(); + base.icon = ContentFinder.Get("UI/Designators/SmoothFloor", true); + base.useMouseIcon = true; + base.soundDragSustain = SoundDefOf.DesignateDragStandard; + base.soundDragChanged = SoundDefOf.DesignateDragStandardChanged; + base.soundSucceeded = SoundDefOf.DesignateSmoothFloor; + base.hotKey = KeyBindingDefOf.Misc1; } public override AcceptanceReport CanDesignateCell(IntVec3 c) diff --git a/Assembly-CSharp/RimWorld/Designator_Strip.cs b/Assembly-CSharp/RimWorld/Designator_Strip.cs index 014ebbc27..5ded5dbf2 100644 --- a/Assembly-CSharp/RimWorld/Designator_Strip.cs +++ b/Assembly-CSharp/RimWorld/Designator_Strip.cs @@ -1,6 +1,4 @@ -using System; using System.Collections.Generic; -using System.Diagnostics; using System.Linq; using UnityEngine; using Verse; @@ -19,14 +17,14 @@ public override int DraggableDimensions public Designator_Strip() { - this.defaultLabel = "DesignatorStrip".Translate(); - this.defaultDesc = "DesignatorStripDesc".Translate(); - this.icon = ContentFinder.Get("UI/Designators/Strip", true); - this.soundDragSustain = SoundDefOf.DesignateDragStandard; - this.soundDragChanged = SoundDefOf.DesignateDragStandardChanged; - this.useMouseIcon = true; - this.soundSucceeded = SoundDefOf.DesignateClaim; - this.hotKey = KeyBindingDefOf.Misc11; + base.defaultLabel = "DesignatorStrip".Translate(); + base.defaultDesc = "DesignatorStripDesc".Translate(); + base.icon = ContentFinder.Get("UI/Designators/Strip", true); + base.soundDragSustain = SoundDefOf.DesignateDragStandard; + base.soundDragChanged = SoundDefOf.DesignateDragStandardChanged; + base.useMouseIcon = true; + base.soundSucceeded = SoundDefOf.DesignateClaim; + base.hotKey = KeyBindingDefOf.Misc11; } public override AcceptanceReport CanDesignateCell(IntVec3 c) @@ -35,7 +33,7 @@ public override AcceptanceReport CanDesignateCell(IntVec3 c) { return false; } - if (!this.StrippablesInCell(c).Any()) + if (!this.StrippablesInCell(c).Any()) { return "MessageMustDesignateStrippable".Translate(); } @@ -44,9 +42,9 @@ public override AcceptanceReport CanDesignateCell(IntVec3 c) public override void DesignateSingleCell(IntVec3 c) { - foreach (Thing current in this.StrippablesInCell(c)) + foreach (Thing item in this.StrippablesInCell(c)) { - this.DesignateThing(current); + this.DesignateThing(item); } } @@ -64,16 +62,19 @@ public override void DesignateThing(Thing t) base.Map.designationManager.AddDesignation(new Designation(t, DesignationDefOf.Strip)); } - [DebuggerHidden] private IEnumerable StrippablesInCell(IntVec3 c) { - Designator_Strip.c__Iterator193 c__Iterator = new Designator_Strip.c__Iterator193(); - c__Iterator.c = c; - c__Iterator.<$>c = c; - c__Iterator.<>f__this = this; - Designator_Strip.c__Iterator193 expr_1C = c__Iterator; - expr_1C.$PC = -2; - return expr_1C; + if (!c.Fogged(base.Map)) + { + List thingList = c.GetThingList(base.Map); + for (int i = 0; i < thingList.Count; i++) + { + if (this.CanDesignateThing(thingList[i]).Accepted) + { + yield return thingList[i]; + } + } + } } } } diff --git a/Assembly-CSharp/RimWorld/Designator_Tame.cs b/Assembly-CSharp/RimWorld/Designator_Tame.cs index ffe6b417c..9b5b87ce3 100644 --- a/Assembly-CSharp/RimWorld/Designator_Tame.cs +++ b/Assembly-CSharp/RimWorld/Designator_Tame.cs @@ -1,6 +1,5 @@ using System; using System.Collections.Generic; -using System.Diagnostics; using System.Linq; using UnityEngine; using Verse; @@ -21,15 +20,15 @@ public override int DraggableDimensions public Designator_Tame() { - this.defaultLabel = "DesignatorTame".Translate(); - this.defaultDesc = "DesignatorTameDesc".Translate(); - this.icon = ContentFinder.Get("UI/Designators/Tame", true); - this.soundDragSustain = SoundDefOf.DesignateDragStandard; - this.soundDragChanged = SoundDefOf.DesignateDragStandardChanged; - this.useMouseIcon = true; - this.soundSucceeded = SoundDefOf.DesignateClaim; - this.hotKey = KeyBindingDefOf.Misc4; - this.tutorTag = "Tame"; + base.defaultLabel = "DesignatorTame".Translate(); + base.defaultDesc = "DesignatorTameDesc".Translate(); + base.icon = ContentFinder.Get("UI/Designators/Tame", true); + base.soundDragSustain = SoundDefOf.DesignateDragStandard; + base.soundDragChanged = SoundDefOf.DesignateDragStandardChanged; + base.useMouseIcon = true; + base.soundSucceeded = SoundDefOf.DesignateClaim; + base.hotKey = KeyBindingDefOf.Misc4; + base.tutorTag = "Tame"; } public override AcceptanceReport CanDesignateCell(IntVec3 c) @@ -38,7 +37,7 @@ public override AcceptanceReport CanDesignateCell(IntVec3 c) { return false; } - if (!this.TameablesInCell(c).Any()) + if (!this.TameablesInCell(c).Any()) { return "MessageMustDesignateTameable".Translate(); } @@ -47,16 +46,16 @@ public override AcceptanceReport CanDesignateCell(IntVec3 c) public override void DesignateSingleCell(IntVec3 loc) { - foreach (Pawn current in this.TameablesInCell(loc)) + foreach (Pawn item in this.TameablesInCell(loc)) { - this.DesignateThing(current); + this.DesignateThing(item); } } public override AcceptanceReport CanDesignateThing(Thing t) { Pawn pawn = t as Pawn; - if (pawn != null && pawn.def.race.Animal && pawn.Faction == null && pawn.RaceProps.wildness < 1f && !pawn.HostileTo(t) && base.Map.designationManager.DesignationOn(pawn, DesignationDefOf.Tame) == null) + if (pawn != null && pawn.def.race.Animal && pawn.Faction == null && pawn.RaceProps.wildness < 1.0 && !pawn.HostileTo(t) && base.Map.designationManager.DesignationOn(pawn, DesignationDefOf.Tame) == null) { return true; } @@ -66,43 +65,42 @@ public override AcceptanceReport CanDesignateThing(Thing t) protected override void FinalizeDesignationSucceeded() { base.FinalizeDesignationSucceeded(); - foreach (PawnKindDef kind in (from p in this.justDesignated - select p.kindDef).Distinct()) + using (IEnumerator enumerator = (from p in this.justDesignated + select p.kindDef).Distinct().GetEnumerator()) { - if (kind.RaceProps.manhunterOnTameFailChance > 0f) + PawnKindDef kind; + while (enumerator.MoveNext()) { - Messages.Message("MessageAnimalManhuntsOnTameFailed".Translate(new object[] + kind = enumerator.Current; + if (kind.RaceProps.manhunterOnTameFailChance > 0.0) { - kind.label, - kind.RaceProps.manhunterOnTameFailChance.ToStringPercent("F2") - }), this.justDesignated.First((Pawn x) => x.kindDef == kind), MessageSound.Standard); + Messages.Message("MessageAnimalManhuntsOnTameFailed".Translate(kind.label, kind.RaceProps.manhunterOnTameFailChance.ToStringPercent("F2")), (Thing)this.justDesignated.First((Func)((Pawn x) => x.kindDef == kind)), MessageSound.Standard); + } } } IEnumerable source = from c in base.Map.mapPawns.FreeColonistsSpawned where c.workSettings.WorkIsActive(WorkTypeDefOf.Handling) select c; - if (!source.Any()) + if (!source.Any()) { source = base.Map.mapPawns.FreeColonistsSpawned; } - if (source.Any()) + if (source.Any()) { - Pawn pawn = source.MaxBy((Pawn c) => c.skills.GetSkill(SkillDefOf.Animals).Level); + Pawn pawn = source.MaxBy((Func)((Pawn c) => c.skills.GetSkill(SkillDefOf.Animals).Level)); int level = pawn.skills.GetSkill(SkillDefOf.Animals).Level; - foreach (ThingDef ad in (from t in this.justDesignated - select t.def).Distinct()) + using (IEnumerator enumerator2 = (from t in this.justDesignated + select t.def).Distinct().GetEnumerator()) { - int num = Mathf.RoundToInt(ad.GetStatValueAbstract(StatDefOf.MinimumHandlingSkill, null)); - if (num > level) + ThingDef ad; + while (enumerator2.MoveNext()) { - Messages.Message("MessageNoHandlerSkilledEnough".Translate(new object[] + ad = enumerator2.Current; + int num = Mathf.RoundToInt(ad.GetStatValueAbstract(StatDefOf.MinimumHandlingSkill, null)); + if (num > level) { - ad.label, - num.ToStringCached(), - SkillDefOf.Animals.LabelCap, - pawn.LabelShort, - level - }), this.justDesignated.First((Pawn x) => x.def == ad), MessageSound.Negative); + Messages.Message("MessageNoHandlerSkilledEnough".Translate(ad.label, num.ToStringCached(), SkillDefOf.Animals.LabelCap, pawn.LabelShort, level), (Thing)this.justDesignated.First((Func)((Pawn x) => x.def == ad)), MessageSound.Negative); + } } } } @@ -117,16 +115,19 @@ public override void DesignateThing(Thing t) this.justDesignated.Add((Pawn)t); } - [DebuggerHidden] private IEnumerable TameablesInCell(IntVec3 c) { - Designator_Tame.c__Iterator194 c__Iterator = new Designator_Tame.c__Iterator194(); - c__Iterator.c = c; - c__Iterator.<$>c = c; - c__Iterator.<>f__this = this; - Designator_Tame.c__Iterator194 expr_1C = c__Iterator; - expr_1C.$PC = -2; - return expr_1C; + if (!c.Fogged(base.Map)) + { + List thingList = c.GetThingList(base.Map); + for (int i = 0; i < thingList.Count; i++) + { + if (this.CanDesignateThing(thingList[i]).Accepted) + { + yield return (Pawn)thingList[i]; + } + } + } } } } diff --git a/Assembly-CSharp/RimWorld/Designator_Uninstall.cs b/Assembly-CSharp/RimWorld/Designator_Uninstall.cs index bfae21d21..818d1a0a2 100644 --- a/Assembly-CSharp/RimWorld/Designator_Uninstall.cs +++ b/Assembly-CSharp/RimWorld/Designator_Uninstall.cs @@ -17,14 +17,14 @@ public override int DraggableDimensions public Designator_Uninstall() { - this.defaultLabel = "DesignatorUninstall".Translate(); - this.defaultDesc = "DesignatorUninstallDesc".Translate(); - this.icon = ContentFinder.Get("UI/Designators/Uninstall", true); - this.soundDragSustain = SoundDefOf.DesignateDragStandard; - this.soundDragChanged = SoundDefOf.DesignateDragStandardChanged; - this.useMouseIcon = true; - this.soundSucceeded = SoundDefOf.DesignateDeconstruct; - this.hotKey = KeyBindingDefOf.Misc12; + base.defaultLabel = "DesignatorUninstall".Translate(); + base.defaultDesc = "DesignatorUninstallDesc".Translate(); + base.icon = ContentFinder.Get("UI/Designators/Uninstall", true); + base.soundDragSustain = SoundDefOf.DesignateDragStandard; + base.soundDragChanged = SoundDefOf.DesignateDragStandardChanged; + base.useMouseIcon = true; + base.soundSucceeded = SoundDefOf.DesignateDeconstruct; + base.hotKey = KeyBindingDefOf.Misc12; } public override AcceptanceReport CanDesignateCell(IntVec3 c) @@ -37,7 +37,8 @@ public override AcceptanceReport CanDesignateCell(IntVec3 c) { return false; } - if (this.TopUninstallableInCell(c) == null) + Thing thing = this.TopUninstallableInCell(c); + if (thing == null) { return false; } @@ -51,13 +52,13 @@ public override void DesignateSingleCell(IntVec3 loc) private Thing TopUninstallableInCell(IntVec3 loc) { - foreach (Thing current in from t in base.Map.thingGrid.ThingsAt(loc) + foreach (Thing item in from t in base.Map.thingGrid.ThingsAt(loc) orderby t.def.altitudeLayer descending select t) { - if (this.CanDesignateThing(current).Accepted) + if (this.CanDesignateThing(item).Accepted) { - return current; + return item; } } return null; @@ -69,7 +70,7 @@ public override void DesignateThing(Thing t) { t.SetFaction(Faction.OfPlayer, null); } - if (DebugSettings.godMode || t.GetStatValue(StatDefOf.WorkToBuild, true) == 0f || t.def.IsFrame) + if (DebugSettings.godMode || t.GetStatValue(StatDefOf.WorkToBuild, true) == 0.0 || t.def.IsFrame) { t.Uninstall(); } diff --git a/Assembly-CSharp/RimWorld/Designator_Zone.cs b/Assembly-CSharp/RimWorld/Designator_Zone.cs index 68708e04b..d18360531 100644 --- a/Assembly-CSharp/RimWorld/Designator_Zone.cs +++ b/Assembly-CSharp/RimWorld/Designator_Zone.cs @@ -1,4 +1,3 @@ -using System; using Verse; namespace RimWorld diff --git a/Assembly-CSharp/RimWorld/Designator_ZoneAdd.cs b/Assembly-CSharp/RimWorld/Designator_ZoneAdd.cs index cf9d6faaa..97342baed 100644 --- a/Assembly-CSharp/RimWorld/Designator_ZoneAdd.cs +++ b/Assembly-CSharp/RimWorld/Designator_ZoneAdd.cs @@ -33,10 +33,10 @@ protected abstract string NewZoneLabel public Designator_ZoneAdd() { - this.soundDragSustain = SoundDefOf.DesignateDragAreaAdd; - this.soundDragChanged = SoundDefOf.DesignateDragAreaAddChanged; - this.soundSucceeded = SoundDefOf.DesignateZoneAdd; - this.useMouseIcon = true; + base.soundDragSustain = SoundDefOf.DesignateDragAreaAdd; + base.soundDragChanged = SoundDefOf.DesignateDragAreaAddChanged; + base.soundSucceeded = SoundDefOf.DesignateZoneAdd; + base.useMouseIcon = true; } protected abstract Zone MakeNewZone(); @@ -52,29 +52,15 @@ public override void SelectedUpdate() public override void DrawMouseAttachments() { - if (this.useMouseIcon) + if (base.useMouseIcon) { string text = string.Empty; if (!Input.GetKey(KeyCode.Mouse0)) { Zone selectedZone = Find.Selector.SelectedZone; - if (selectedZone != null) - { - text = "ExpandOrCreateZone".Translate(new object[] - { - selectedZone.label, - this.NewZoneLabel - }); - } - else - { - text = "CreateNewZone".Translate(new object[] - { - this.NewZoneLabel - }); - } + text = ((selectedZone == null) ? "CreateNewZone".Translate(this.NewZoneLabel) : "ExpandOrCreateZone".Translate(selectedZone.label, this.NewZoneLabel)); } - GenUI.DrawMouseAttachment(this.icon, text); + GenUI.DrawMouseAttachment(base.icon, text); } } @@ -97,9 +83,9 @@ public override AcceptanceReport CanDesignateCell(IntVec3 c) { return false; } - foreach (Thing current in base.Map.thingGrid.ThingsAt(c)) + foreach (Thing item in base.Map.thingGrid.ThingsAt(c)) { - if (!current.def.CanOverlapZones) + if (!item.def.CanOverlapZones) { return false; } @@ -109,7 +95,8 @@ public override AcceptanceReport CanDesignateCell(IntVec3 c) public override void DesignateMultiCell(IEnumerable cells) { - List list = cells.ToList(); + List list = cells.ToList(); + bool flag = false; if (list.Count == 1) { Zone zone = base.Map.zoneManager.ZoneAt(list[0]); @@ -125,9 +112,9 @@ public override void DesignateMultiCell(IEnumerable cells) if (this.SelectedZone == null) { Zone zone2 = null; - foreach (IntVec3 current in cells) + foreach (IntVec3 item in cells) { - Zone zone3 = base.Map.zoneManager.ZoneAt(current); + Zone zone3 = base.Map.zoneManager.ZoneAt(item); if (zone3 != null && zone3.GetType() == this.zoneTypeToPlace) { if (zone2 == null) @@ -143,61 +130,53 @@ public override void DesignateMultiCell(IEnumerable cells) } this.SelectedZone = zone2; } - list.RemoveAll((IntVec3 c) => base.Map.zoneManager.ZoneAt(c) != null); - if (list.Count == 0) - { - return; - } - if (TutorSystem.TutorialMode && !TutorSystem.AllowAction(new EventPack(base.TutorTagDesignate, list))) + list.RemoveAll((Predicate)((IntVec3 c) => base.Map.zoneManager.ZoneAt(c) != null)); + if (list.Count != 0 && (!TutorSystem.TutorialMode || TutorSystem.AllowAction(new EventPack(base.TutorTagDesignate, list)))) { - return; - } - if (this.SelectedZone == null) - { - this.SelectedZone = this.MakeNewZone(); - this.SelectedZone.AddCell(list[0]); - list.RemoveAt(0); - } - bool somethingSucceeded; - while (true) - { - somethingSucceeded = true; - int count = list.Count; - for (int i = list.Count - 1; i >= 0; i--) + if (this.SelectedZone == null) { - bool flag = false; - for (int j = 0; j < 4; j++) + this.SelectedZone = this.MakeNewZone(); + this.SelectedZone.AddCell(list[0]); + list.RemoveAt(0); + } + while (true) + { + flag = true; + int count = list.Count; + for (int num = list.Count - 1; num >= 0; num--) { - IntVec3 c2 = list[i] + GenAdj.CardinalDirections[j]; - if (c2.InBounds(base.Map)) + bool flag2 = false; + for (int i = 0; i < 4; i++) { - if (base.Map.zoneManager.ZoneAt(c2) == this.SelectedZone) + IntVec3 c2 = list[num] + GenAdj.CardinalDirections[i]; + if (c2.InBounds(base.Map) && base.Map.zoneManager.ZoneAt(c2) == this.SelectedZone) { - flag = true; + flag2 = true; break; } } + if (flag2) + { + this.SelectedZone.AddCell(list[num]); + list.RemoveAt(num); + } } - if (flag) + if (list.Count != 0) { - this.SelectedZone.AddCell(list[i]); - list.RemoveAt(i); + if (list.Count == count) + { + this.SelectedZone = this.MakeNewZone(); + this.SelectedZone.AddCell(list[0]); + list.RemoveAt(0); + } + continue; } - } - if (list.Count == 0) - { break; } - if (list.Count == count) - { - this.SelectedZone = this.MakeNewZone(); - this.SelectedZone.AddCell(list[0]); - list.RemoveAt(0); - } + this.SelectedZone.CheckContiguous(); + base.Finalize(flag); + TutorSystem.Notify_Event(new EventPack(base.TutorTagDesignate, list)); } - this.SelectedZone.CheckContiguous(); - base.Finalize(somethingSucceeded); - TutorSystem.Notify_Event(new EventPack(base.TutorTagDesignate, list)); } } } diff --git a/Assembly-CSharp/RimWorld/Designator_ZoneAddStockpile.cs b/Assembly-CSharp/RimWorld/Designator_ZoneAddStockpile.cs index 848a36e7e..81bc03805 100644 --- a/Assembly-CSharp/RimWorld/Designator_ZoneAddStockpile.cs +++ b/Assembly-CSharp/RimWorld/Designator_ZoneAddStockpile.cs @@ -1,4 +1,3 @@ -using System; using System.Collections.Generic; using Verse; @@ -18,7 +17,7 @@ protected override string NewZoneLabel public Designator_ZoneAddStockpile() { - this.zoneTypeToPlace = typeof(Zone_Stockpile); + base.zoneTypeToPlace = typeof(Zone_Stockpile); } protected override Zone MakeNewZone() diff --git a/Assembly-CSharp/RimWorld/Designator_ZoneAddStockpile_Dumping.cs b/Assembly-CSharp/RimWorld/Designator_ZoneAddStockpile_Dumping.cs index 51352a32a..7a976788c 100644 --- a/Assembly-CSharp/RimWorld/Designator_ZoneAddStockpile_Dumping.cs +++ b/Assembly-CSharp/RimWorld/Designator_ZoneAddStockpile_Dumping.cs @@ -1,4 +1,3 @@ -using System; using UnityEngine; using Verse; @@ -8,11 +7,11 @@ public class Designator_ZoneAddStockpile_Dumping : Designator_ZoneAddStockpile { public Designator_ZoneAddStockpile_Dumping() { - this.preset = StorageSettingsPreset.DumpingStockpile; - this.defaultLabel = this.preset.PresetName(); - this.defaultDesc = "DesignatorZoneCreateStorageDumpingDesc".Translate(); - this.icon = ContentFinder.Get("UI/Designators/ZoneCreate_Stockpile", true); - this.hotKey = KeyBindingDefOf.Misc3; + base.preset = StorageSettingsPreset.DumpingStockpile; + base.defaultLabel = base.preset.PresetName(); + base.defaultDesc = "DesignatorZoneCreateStorageDumpingDesc".Translate(); + base.icon = ContentFinder.Get("UI/Designators/ZoneCreate_Stockpile", true); + base.hotKey = KeyBindingDefOf.Misc3; } protected override void FinalizeDesignationSucceeded() diff --git a/Assembly-CSharp/RimWorld/Designator_ZoneAddStockpile_Resources.cs b/Assembly-CSharp/RimWorld/Designator_ZoneAddStockpile_Resources.cs index 01c28afee..d35065606 100644 --- a/Assembly-CSharp/RimWorld/Designator_ZoneAddStockpile_Resources.cs +++ b/Assembly-CSharp/RimWorld/Designator_ZoneAddStockpile_Resources.cs @@ -1,4 +1,3 @@ -using System; using UnityEngine; using Verse; @@ -8,12 +7,12 @@ public class Designator_ZoneAddStockpile_Resources : Designator_ZoneAddStockpile { public Designator_ZoneAddStockpile_Resources() { - this.preset = StorageSettingsPreset.DefaultStockpile; - this.defaultLabel = this.preset.PresetName(); - this.defaultDesc = "DesignatorZoneCreateStorageResourcesDesc".Translate(); - this.icon = ContentFinder.Get("UI/Designators/ZoneCreate_Stockpile", true); - this.hotKey = KeyBindingDefOf.Misc1; - this.tutorTag = "ZoneAddStockpile_Resources"; + base.preset = StorageSettingsPreset.DefaultStockpile; + base.defaultLabel = base.preset.PresetName(); + base.defaultDesc = "DesignatorZoneCreateStorageResourcesDesc".Translate(); + base.icon = ContentFinder.Get("UI/Designators/ZoneCreate_Stockpile", true); + base.hotKey = KeyBindingDefOf.Misc1; + base.tutorTag = "ZoneAddStockpile_Resources"; } protected override void FinalizeDesignationSucceeded() diff --git a/Assembly-CSharp/RimWorld/Designator_ZoneAdd_Growing.cs b/Assembly-CSharp/RimWorld/Designator_ZoneAdd_Growing.cs index 691894a73..9063d23ee 100644 --- a/Assembly-CSharp/RimWorld/Designator_ZoneAdd_Growing.cs +++ b/Assembly-CSharp/RimWorld/Designator_ZoneAdd_Growing.cs @@ -1,4 +1,3 @@ -using System; using UnityEngine; using Verse; @@ -16,12 +15,12 @@ protected override string NewZoneLabel public Designator_ZoneAdd_Growing() { - this.zoneTypeToPlace = typeof(Zone_Growing); - this.defaultLabel = "GrowingZone".Translate(); - this.defaultDesc = "DesignatorGrowingZoneDesc".Translate(); - this.icon = ContentFinder.Get("UI/Designators/ZoneCreate_Growing", true); - this.hotKey = KeyBindingDefOf.Misc2; - this.tutorTag = "ZoneAdd_Growing"; + base.zoneTypeToPlace = typeof(Zone_Growing); + base.defaultLabel = "GrowingZone".Translate(); + base.defaultDesc = "DesignatorGrowingZoneDesc".Translate(); + base.icon = ContentFinder.Get("UI/Designators/ZoneCreate_Growing", true); + base.hotKey = KeyBindingDefOf.Misc2; + base.tutorTag = "ZoneAdd_Growing"; } public override AcceptanceReport CanDesignateCell(IntVec3 c) diff --git a/Assembly-CSharp/RimWorld/Designator_ZoneDelete.cs b/Assembly-CSharp/RimWorld/Designator_ZoneDelete.cs index f87d2aa26..2d6f73463 100644 --- a/Assembly-CSharp/RimWorld/Designator_ZoneDelete.cs +++ b/Assembly-CSharp/RimWorld/Designator_ZoneDelete.cs @@ -1,4 +1,3 @@ -using System; using System.Collections.Generic; using UnityEngine; using Verse; @@ -11,14 +10,14 @@ public class Designator_ZoneDelete : Designator_Zone public Designator_ZoneDelete() { - this.defaultLabel = "DesignatorZoneDelete".Translate(); - this.defaultDesc = "DesignatorZoneDeleteDesc".Translate(); - this.soundDragSustain = SoundDefOf.DesignateDragAreaDelete; - this.soundDragChanged = SoundDefOf.DesignateDragAreaDeleteChanged; - this.soundSucceeded = SoundDefOf.DesignateZoneDelete; - this.useMouseIcon = true; - this.icon = ContentFinder.Get("UI/Designators/ZoneDelete", true); - this.hotKey = KeyBindingDefOf.Misc4; + base.defaultLabel = "DesignatorZoneDelete".Translate(); + base.defaultDesc = "DesignatorZoneDeleteDesc".Translate(); + base.soundDragSustain = SoundDefOf.DesignateDragAreaDelete; + base.soundDragChanged = SoundDefOf.DesignateDragAreaDeleteChanged; + base.soundSucceeded = SoundDefOf.DesignateZoneDelete; + base.useMouseIcon = true; + base.icon = ContentFinder.Get("UI/Designators/ZoneDelete", true); + base.hotKey = KeyBindingDefOf.Misc4; } public override AcceptanceReport CanDesignateCell(IntVec3 sq) diff --git a/Assembly-CSharp/RimWorld/Dialog_AddPreferredName.cs b/Assembly-CSharp/RimWorld/Dialog_AddPreferredName.cs index fe2205ce7..9a0b7cf85 100644 --- a/Assembly-CSharp/RimWorld/Dialog_AddPreferredName.cs +++ b/Assembly-CSharp/RimWorld/Dialog_AddPreferredName.cs @@ -24,12 +24,12 @@ public override Vector2 InitialSize public Dialog_AddPreferredName() { - this.doCloseButton = true; - this.absorbInputAroundWindow = true; + base.doCloseButton = true; + base.absorbInputAroundWindow = true; this.cachedNames = (from n in (from b in SolidBioDatabase.allBios select b.name).Concat(PawnNameDatabaseSolid.AllNames()) orderby n.Last descending - select n).ToList(); + select n).ToList(); } public override void DoWindowContents(Rect inRect) @@ -41,24 +41,22 @@ public override void DoWindowContents(Rect inRect) if (text.Length < 20) { this.searchName = text; - this.searchWords = this.searchName.Replace("'", string.Empty).Split(new char[] - { - ' ' - }); + this.searchWords = this.searchName.Replace("'", string.Empty).Split(' '); } listing_Standard.Gap(4f); if (this.searchName.Length > 1) { - foreach (NameTriple current in this.cachedNames.Where(new Func(this.FilterMatch))) + foreach (NameTriple item in this.cachedNames.Where(new Func(this.FilterMatch))) { - if (listing_Standard.ButtonText(current.ToString(), null)) + if (listing_Standard.ButtonText(item.ToString(), (string)null)) { - this.TryChooseName(current); + this.TryChooseName(item); } - if (listing_Standard.CurHeight + 30f > inRect.height - (this.CloseButSize.y + 8f)) - { + double num = listing_Standard.CurHeight + 30.0; + float height = inRect.height; + Vector2 closeButSize = base.CloseButSize; + if (num > height - (closeButSize.y + 8.0)) break; - } } } listing_Standard.End(); @@ -78,7 +76,11 @@ private bool FilterMatch(NameTriple n) { return n.Last.StartsWith(this.searchName, StringComparison.OrdinalIgnoreCase) || n.First.StartsWith(this.searchName, StringComparison.OrdinalIgnoreCase) || n.Nick.StartsWith(this.searchName, StringComparison.OrdinalIgnoreCase); } - return this.searchWords.Length == 2 && n.First.EqualsIgnoreCase(this.searchWords[0]) && (n.Last.StartsWith(this.searchWords[1], StringComparison.OrdinalIgnoreCase) || n.Nick.StartsWith(this.searchWords[1], StringComparison.OrdinalIgnoreCase)); + if (this.searchWords.Length == 2) + { + return n.First.EqualsIgnoreCase(this.searchWords[0]) && (n.Last.StartsWith(this.searchWords[1], StringComparison.OrdinalIgnoreCase) || n.Nick.StartsWith(this.searchWords[1], StringComparison.OrdinalIgnoreCase)); + } + return false; } private void TryChooseName(NameTriple name) diff --git a/Assembly-CSharp/RimWorld/Dialog_AdvancedGameConfig.cs b/Assembly-CSharp/RimWorld/Dialog_AdvancedGameConfig.cs index b713c1695..d3a9862fe 100644 --- a/Assembly-CSharp/RimWorld/Dialog_AdvancedGameConfig.cs +++ b/Assembly-CSharp/RimWorld/Dialog_AdvancedGameConfig.cs @@ -1,4 +1,3 @@ -using System; using UnityEngine; using Verse; @@ -10,7 +9,7 @@ public class Dialog_AdvancedGameConfig : Window private int selTile = -1; - private static readonly int[] MapSizes = new int[] + private static readonly int[] MapSizes = new int[8] { 200, 225, @@ -32,10 +31,10 @@ public override Vector2 InitialSize public Dialog_AdvancedGameConfig(int selTile) { - this.doCloseButton = true; - this.closeOnEscapeKey = true; - this.forcePause = true; - this.absorbInputAroundWindow = true; + base.doCloseButton = true; + base.closeOnEscapeKey = true; + base.forcePause = true; + base.absorbInputAroundWindow = true; this.selTile = selTile; } @@ -49,27 +48,30 @@ public override void DoWindowContents(Rect inRect) for (int i = 0; i < mapSizes.Length; i++) { int num = mapSizes[i]; - if (num == 200) + switch (num) + { + case 200: { listing_Standard.Label("MapSizeSmall".Translate(), -1f); + break; } - else if (num == 250) + case 250: { listing_Standard.Label("MapSizeMedium".Translate(), -1f); + break; } - else if (num == 300) + case 300: { listing_Standard.Label("MapSizeLarge".Translate(), -1f); + break; } - else if (num == 350) + case 350: { listing_Standard.Label("MapSizeExtreme".Translate(), -1f); + break; } - string label = "MapSizeDesc".Translate(new object[] - { - num, - num * num - }); + } + string label = "MapSizeDesc".Translate(num, num * num); if (listing_Standard.RadioButton(label, Find.GameInitData.mapSize == num, 0f)) { Find.GameInitData.mapSize = num; @@ -78,49 +80,28 @@ public override void DoWindowContents(Rect inRect) listing_Standard.NewColumn(); GenUI.SetLabelAlign(TextAnchor.MiddleCenter); listing_Standard.Label("MapStartSeason".Translate(), -1f); - string label2; - if (Find.GameInitData.startingSeason == Season.Undefined) - { - label2 = "MapStartSeasonDefault".Translate(); - } - else - { - label2 = Find.GameInitData.startingSeason.LabelCap(); - } + string label2 = (Find.GameInitData.startingSeason != 0) ? Find.GameInitData.startingSeason.LabelCap() : "MapStartSeasonDefault".Translate(); Rect rect = listing_Standard.GetRect(32f); GridLayout gridLayout = new GridLayout(rect, 5, 1, 0f, 4f); if (Widgets.ButtonText(gridLayout.GetCellRectByIndex(0, 1, 1), "-", true, false, true)) { - Season season = Find.GameInitData.startingSeason; - if (season == Season.Undefined) - { - season = Season.Winter; - } - else - { - season -= 1; - } - Find.GameInitData.startingSeason = season; + Season startingSeason = Find.GameInitData.startingSeason; + startingSeason = ((startingSeason != 0) ? (startingSeason - 1) : Season.Winter); + Find.GameInitData.startingSeason = startingSeason; } Widgets.Label(gridLayout.GetCellRectByIndex(1, 3, 1), label2); if (Widgets.ButtonText(gridLayout.GetCellRectByIndex(4, 1, 1), "+", true, false, true)) { - Season season2 = Find.GameInitData.startingSeason; - if (season2 == Season.Winter) - { - season2 = Season.Undefined; - } - else - { - season2 += 1; - } - Find.GameInitData.startingSeason = season2; + Season startingSeason2 = Find.GameInitData.startingSeason; + startingSeason2 = ((startingSeason2 != Season.Winter) ? (startingSeason2 + 1) : Season.Undefined); + Find.GameInitData.startingSeason = startingSeason2; } GenUI.ResetLabelAlign(); - if (this.selTile >= 0 && Find.GameInitData.startingSeason != Season.Undefined) + if (((this.selTile >= 0) ? Find.GameInitData.startingSeason : Season.Undefined) != 0) { - float y = Find.WorldGrid.LongLatOf(this.selTile).y; - if (GenTemperature.AverageTemperatureAtTileForTwelfth(this.selTile, Find.GameInitData.startingSeason.GetFirstTwelfth(y)) < 3f) + Vector2 vector = Find.WorldGrid.LongLatOf(this.selTile); + float y = vector.y; + if (GenTemperature.AverageTemperatureAtTileForTwelfth(this.selTile, Find.GameInitData.startingSeason.GetFirstTwelfth(y)) < 3.0) { listing_Standard.Label("MapTemperatureDangerWarning".Translate(), -1f); } diff --git a/Assembly-CSharp/RimWorld/Dialog_AssignBuildingOwner.cs b/Assembly-CSharp/RimWorld/Dialog_AssignBuildingOwner.cs index 96e82376d..d782d3c51 100644 --- a/Assembly-CSharp/RimWorld/Dialog_AssignBuildingOwner.cs +++ b/Assembly-CSharp/RimWorld/Dialog_AssignBuildingOwner.cs @@ -1,4 +1,4 @@ -using System; +using System.Collections.Generic; using System.Linq; using UnityEngine; using Verse; @@ -25,11 +25,11 @@ public override Vector2 InitialSize public Dialog_AssignBuildingOwner(IAssignableBuilding assignable) { this.assignable = assignable; - this.closeOnEscapeKey = true; - this.doCloseButton = true; - this.doCloseX = true; - this.closeOnClickedOutside = true; - this.absorbInputAroundWindow = true; + base.closeOnEscapeKey = true; + base.doCloseButton = true; + base.doCloseX = true; + base.closeOnClickedOutside = true; + base.absorbInputAroundWindow = true; } public override void DoWindowContents(Rect inRect) @@ -39,52 +39,59 @@ public override void DoWindowContents(Rect inRect) outRect.yMin += 20f; outRect.yMax -= 40f; outRect.width -= 16f; - Rect viewRect = new Rect(0f, 0f, outRect.width - 16f, (float)this.assignable.AssigningCandidates.Count() * 35f + 100f); + Rect viewRect = new Rect(0f, 0f, (float)(outRect.width - 16.0), (float)((float)this.assignable.AssigningCandidates.Count() * 35.0 + 100.0)); Widgets.BeginScrollView(outRect, ref this.scrollPosition, viewRect, true); float num = 0f; bool flag = false; - foreach (Pawn current in this.assignable.AssignedPawns) + foreach (Pawn assignedPawn in this.assignable.AssignedPawns) { flag = true; - Rect rect = new Rect(0f, num, viewRect.width * 0.6f, 32f); - Widgets.Label(rect, current.LabelCap); + Rect rect = new Rect(0f, num, (float)(viewRect.width * 0.60000002384185791), 32f); + Widgets.Label(rect, assignedPawn.LabelCap); rect.x = rect.xMax; - rect.width = viewRect.width * 0.4f; + rect.width = (float)(viewRect.width * 0.40000000596046448); if (Widgets.ButtonText(rect, "BuildingUnassign".Translate(), true, false, true)) { - this.assignable.TryUnassignPawn(current); + this.assignable.TryUnassignPawn(assignedPawn); SoundDefOf.Click.PlayOneShotOnCamera(null); return; } - num += 35f; + num = (float)(num + 35.0); } if (flag) { - num += 15f; + num = (float)(num + 15.0); } - foreach (Pawn current2 in this.assignable.AssigningCandidates) + using (IEnumerator enumerator2 = this.assignable.AssigningCandidates.GetEnumerator()) { - if (!this.assignable.AssignedPawns.Contains(current2)) + Pawn current2; + while (enumerator2.MoveNext()) { - Rect rect2 = new Rect(0f, num, viewRect.width * 0.6f, 32f); - Widgets.Label(rect2, current2.LabelCap); - rect2.x = rect2.xMax; - rect2.width = viewRect.width * 0.4f; - if (Widgets.ButtonText(rect2, "BuildingAssign".Translate(), true, false, true)) + current2 = enumerator2.Current; + if (!this.assignable.AssignedPawns.Contains(current2)) { - this.assignable.TryAssignPawn(current2); - if (this.assignable.MaxAssignedPawnsCount == 1) - { - this.Close(true); - } - else - { - SoundDefOf.Click.PlayOneShotOnCamera(null); - } - return; + Rect rect2 = new Rect(0f, num, (float)(viewRect.width * 0.60000002384185791), 32f); + Widgets.Label(rect2, current2.LabelCap); + rect2.x = rect2.xMax; + rect2.width = (float)(viewRect.width * 0.40000000596046448); + if (Widgets.ButtonText(rect2, "BuildingAssign".Translate(), true, false, true)) + goto IL_0217; + num = (float)(num + 35.0); } - num += 35f; } + goto end_IL_0185; + IL_0217: + this.assignable.TryAssignPawn(current2); + if (this.assignable.MaxAssignedPawnsCount == 1) + { + this.Close(true); + } + else + { + SoundDefOf.Click.PlayOneShotOnCamera(null); + } + return; + end_IL_0185:; } Widgets.EndScrollView(); } diff --git a/Assembly-CSharp/RimWorld/Dialog_BillConfig.cs b/Assembly-CSharp/RimWorld/Dialog_BillConfig.cs index 8087b6016..d46cc0be0 100644 --- a/Assembly-CSharp/RimWorld/Dialog_BillConfig.cs +++ b/Assembly-CSharp/RimWorld/Dialog_BillConfig.cs @@ -28,12 +28,12 @@ public Dialog_BillConfig(Bill_Production bill, IntVec3 billGiverPos) { this.billGiverPos = billGiverPos; this.bill = bill; - this.forcePause = true; - this.doCloseX = true; - this.closeOnEscapeKey = true; - this.doCloseButton = true; - this.absorbInputAroundWindow = true; - this.closeOnClickedOutside = true; + base.forcePause = true; + base.doCloseX = true; + base.closeOnEscapeKey = true; + base.doCloseButton = true; + base.absorbInputAroundWindow = true; + base.closeOnClickedOutside = true; } private void AdjustCount(int offset) @@ -63,37 +63,44 @@ public override void DoWindowContents(Rect inRect) Text.Font = GameFont.Medium; Rect rect = new Rect(0f, 0f, 400f, 50f); Widgets.Label(rect, this.bill.LabelCap); - Rect rect2 = new Rect(0f, 80f, 200f, inRect.height - 80f); - Rect rect3 = new Rect(rect2.xMax + 17f, 50f, 180f, inRect.height - 50f - this.CloseButSize.y); - Rect rect4 = new Rect(rect3.xMax + 17f, 50f, inRect.width - (rect3.xMax + 17f), inRect.height - 50f - this.CloseButSize.y); + Rect rect2 = new Rect(0f, 80f, 200f, (float)(inRect.height - 80.0)); + double x = rect2.xMax + 17.0; + double num = inRect.height - 50.0; + Vector2 closeButSize = base.CloseButSize; + Rect rect3 = new Rect((float)x, 50f, 180f, (float)(num - closeButSize.y)); + double x2 = rect3.xMax + 17.0; + double width = inRect.width - (rect3.xMax + 17.0); + double num2 = inRect.height - 50.0; + Vector2 closeButSize2 = base.CloseButSize; + Rect rect4 = new Rect((float)x2, 50f, (float)width, (float)(num2 - closeButSize2.y)); Text.Font = GameFont.Small; Listing_Standard listing_Standard = new Listing_Standard(); listing_Standard.Begin(rect3); if (this.bill.suspended) { - if (listing_Standard.ButtonText("Suspended".Translate(), null)) + if (listing_Standard.ButtonText("Suspended".Translate(), (string)null)) { this.bill.suspended = false; } } - else if (listing_Standard.ButtonText("NotSuspended".Translate(), null)) + else if (listing_Standard.ButtonText("NotSuspended".Translate(), (string)null)) { this.bill.suspended = true; } - if (listing_Standard.ButtonText(this.bill.repeatMode.GetLabel(), null)) + if (listing_Standard.ButtonText(this.bill.repeatMode.GetLabel(), (string)null)) { BillRepeatModeUtility.MakeConfigFloatMenu(this.bill); } string label = ("BillStoreMode_" + this.bill.storeMode).Translate(); - if (listing_Standard.ButtonText(label, null)) + if (listing_Standard.ButtonText(label, (string)null)) { List list = new List(); - foreach (BillStoreModeDef current in from bsm in DefDatabase.AllDefs + foreach (BillStoreModeDef item in from bsm in DefDatabase.AllDefs orderby bsm.listOrder select bsm) { - BillStoreModeDef smLocal = current; - list.Add(new FloatMenuOption(("BillStoreMode_" + current).Translate(), delegate + BillStoreModeDef smLocal = item; + list.Add(new FloatMenuOption(("BillStoreMode_" + item).Translate(), (Action)delegate { this.bill.storeMode = smLocal; }, MenuOptionPriority.Default, null, null, 0f, null, null)); @@ -103,34 +110,24 @@ orderby bsm.listOrder listing_Standard.Gap(12f); if (this.bill.repeatMode == BillRepeatModeDefOf.RepeatCount) { - listing_Standard.Label("RepeatCount".Translate(new object[] - { - this.bill.RepeatInfoText - }), -1f); + listing_Standard.Label("RepeatCount".Translate(this.bill.RepeatInfoText), -1f); listing_Standard.IntSetter(ref this.bill.repeatCount, 1, "1", 42f); listing_Standard.IntAdjuster(ref this.bill.repeatCount, 1, 0); listing_Standard.IntAdjuster(ref this.bill.repeatCount, 25, 0); } else if (this.bill.repeatMode == BillRepeatModeDefOf.TargetCount) { - string text = "CurrentlyHave".Translate() + ": "; - text += this.bill.recipe.WorkerCounter.CountProducts(this.bill); - text += " / "; - text += ((this.bill.targetCount >= 999999) ? "Infinite".Translate().ToLower() : this.bill.targetCount.ToString()); - string text2 = this.bill.recipe.WorkerCounter.ProductsDescription(this.bill); - if (!text2.NullOrEmpty()) + string arg = "CurrentlyHave".Translate() + ": "; + arg += this.bill.recipe.WorkerCounter.CountProducts(this.bill); + arg += " / "; + arg += ((this.bill.targetCount >= 999999) ? "Infinite".Translate().ToLower() : this.bill.targetCount.ToString()); + string text = this.bill.recipe.WorkerCounter.ProductsDescription(this.bill); + if (!text.NullOrEmpty()) { - string text3 = text; - text = string.Concat(new string[] - { - text3, - "\n", - "CountingProducts".Translate(), - ": ", - text2 - }); + string text2 = arg; + arg = text2 + "\n" + "CountingProducts".Translate() + ": " + text; } - listing_Standard.Label(text, -1f); + listing_Standard.Label(arg, -1f); int targetCount = this.bill.targetCount; listing_Standard.IntSetter(ref this.bill.targetCount, 1, "1", 42f); listing_Standard.IntAdjuster(ref this.bill.targetCount, 1, 1); @@ -141,22 +138,19 @@ orderby bsm.listOrder listing_Standard.Gap(12f); listing_Standard.Label("IngredientSearchRadius".Translate() + ": " + this.bill.ingredientSearchRadius.ToString("F0"), -1f); this.bill.ingredientSearchRadius = listing_Standard.Slider(this.bill.ingredientSearchRadius, 3f, 100f); - if (this.bill.ingredientSearchRadius >= 100f) + if (this.bill.ingredientSearchRadius >= 100.0) { this.bill.ingredientSearchRadius = 999f; } if (this.bill.recipe.workSkill != null) { - listing_Standard.Label("AllowedSkillRange".Translate(new object[] - { - this.bill.recipe.workSkill.label.ToLower() - }), -1f); + listing_Standard.Label("AllowedSkillRange".Translate(this.bill.recipe.workSkill.label.ToLower()), -1f); listing_Standard.IntRange(ref this.bill.allowedSkillRange, 0, 20); } if (this.bill.repeatMode == BillRepeatModeDefOf.TargetCount) { listing_Standard.Gap(12f); - listing_Standard.CheckboxLabeled("PauseWhenSatisfied".Translate(), ref this.bill.pauseWhenSatisfied, null); + listing_Standard.CheckboxLabeled("PauseWhenSatisfied".Translate(), ref this.bill.pauseWhenSatisfied, (string)null); if (this.bill.pauseWhenSatisfied) { listing_Standard.Label("UnpauseWhenYouHave".Translate() + ": " + this.bill.unpauseWhenYouHave.ToString("F0"), -1f); @@ -164,7 +158,7 @@ orderby bsm.listOrder } } listing_Standard.End(); - ThingFilterUI.DoThingFilterConfigWindow(rect4, ref this.scrollPosition, this.bill.ingredientFilter, this.bill.recipe.fixedIngredientFilter, 4, null, this.bill.recipe.forceHiddenSpecialFilters, this.bill.recipe.GetPremultipliedSmallIngredients()); + ThingFilterUI.DoThingFilterConfigWindow(rect4, ref this.scrollPosition, this.bill.ingredientFilter, this.bill.recipe.fixedIngredientFilter, 4, (IEnumerable)null, (IEnumerable)this.bill.recipe.forceHiddenSpecialFilters, this.bill.recipe.GetPremultipliedSmallIngredients()); StringBuilder stringBuilder = new StringBuilder(); if (this.bill.recipe.description != null) { @@ -182,24 +176,24 @@ orderby bsm.listOrder } } stringBuilder.AppendLine(); - string text4 = this.bill.recipe.IngredientValueGetter.ExtraDescriptionLine(this.bill.recipe); - if (text4 != null) + string text3 = this.bill.recipe.IngredientValueGetter.ExtraDescriptionLine(this.bill.recipe); + if (text3 != null) { - stringBuilder.AppendLine(text4); + stringBuilder.AppendLine(text3); stringBuilder.AppendLine(); } - if (!this.bill.recipe.skillRequirements.NullOrEmpty()) + if (!this.bill.recipe.skillRequirements.NullOrEmpty()) { stringBuilder.AppendLine("MinimumSkills".Translate()); stringBuilder.AppendLine(this.bill.recipe.MinSkillString); } Text.Font = GameFont.Small; - string text5 = stringBuilder.ToString(); - if (Text.CalcHeight(text5, rect2.width) > rect2.height) + string text4 = stringBuilder.ToString(); + if (Text.CalcHeight(text4, rect2.width) > rect2.height) { Text.Font = GameFont.Tiny; } - Widgets.Label(rect2, text5); + Widgets.Label(rect2, text4); Text.Font = GameFont.Small; if (this.bill.recipe.products.Count == 1) { diff --git a/Assembly-CSharp/RimWorld/Dialog_DefineBinding.cs b/Assembly-CSharp/RimWorld/Dialog_DefineBinding.cs index 82840e522..9354c66bf 100644 --- a/Assembly-CSharp/RimWorld/Dialog_DefineBinding.cs +++ b/Assembly-CSharp/RimWorld/Dialog_DefineBinding.cs @@ -35,9 +35,9 @@ public Dialog_DefineBinding(KeyPrefsData keyPrefsData, KeyBindingDef keyDef, Key this.keyDef = keyDef; this.slot = slot; this.keyPrefsData = keyPrefsData; - this.forcePause = true; - this.onlyOneOfTypeAllowed = true; - this.absorbInputAroundWindow = true; + base.forcePause = true; + base.onlyOneOfTypeAllowed = true; + base.absorbInputAroundWindow = true; } public override void DoWindowContents(Rect inRect) @@ -45,16 +45,13 @@ public override void DoWindowContents(Rect inRect) Text.Anchor = TextAnchor.MiddleCenter; Widgets.Label(inRect, "PressAnyKeyOrEsc".Translate()); Text.Anchor = TextAnchor.UpperLeft; - if (Event.current.isKey && Event.current.type == EventType.KeyDown && Event.current.keyCode != KeyCode.None) + if ((Event.current.isKey ? ((Event.current.type == EventType.KeyDown) ? Event.current.keyCode : KeyCode.None) : KeyCode.None) != 0) { if (Event.current.keyCode != KeyCode.Escape) { - this.keyPrefsData.EraseConflictingBindingsForKeyCode(this.keyDef, Event.current.keyCode, delegate(KeyBindingDef oldDef) + this.keyPrefsData.EraseConflictingBindingsForKeyCode(this.keyDef, Event.current.keyCode, (Action)delegate(KeyBindingDef oldDef) { - Messages.Message("KeyBindingOverwritten".Translate(new object[] - { - oldDef.label - }), MessageSound.Standard); + Messages.Message("KeyBindingOverwritten".Translate(oldDef.label), MessageSound.Standard); }); this.keyPrefsData.SetBinding(this.keyDef, this.slot, Event.current.keyCode); } diff --git a/Assembly-CSharp/RimWorld/Dialog_FactionDuringLanding.cs b/Assembly-CSharp/RimWorld/Dialog_FactionDuringLanding.cs index 02c5983ef..79c50f4ed 100644 --- a/Assembly-CSharp/RimWorld/Dialog_FactionDuringLanding.cs +++ b/Assembly-CSharp/RimWorld/Dialog_FactionDuringLanding.cs @@ -1,4 +1,3 @@ -using System; using UnityEngine; using Verse; @@ -20,10 +19,10 @@ public override Vector2 InitialSize public Dialog_FactionDuringLanding() { - this.doCloseButton = true; - this.closeOnEscapeKey = true; - this.forcePause = true; - this.absorbInputAroundWindow = true; + base.doCloseButton = true; + base.closeOnEscapeKey = true; + base.forcePause = true; + base.absorbInputAroundWindow = true; } public override void DoWindowContents(Rect inRect) diff --git a/Assembly-CSharp/RimWorld/Dialog_FileList.cs b/Assembly-CSharp/RimWorld/Dialog_FileList.cs index 4575ea4d8..9c3962ecd 100644 --- a/Assembly-CSharp/RimWorld/Dialog_FileList.cs +++ b/Assembly-CSharp/RimWorld/Dialog_FileList.cs @@ -60,71 +60,77 @@ protected virtual bool ShouldDoTypeInField public Dialog_FileList() { - this.closeOnEscapeKey = true; - this.doCloseButton = true; - this.doCloseX = true; - this.forcePause = true; - this.absorbInputAroundWindow = true; + base.closeOnEscapeKey = true; + base.doCloseButton = true; + base.doCloseX = true; + base.forcePause = true; + base.absorbInputAroundWindow = true; this.ReloadFiles(); } public override void DoWindowContents(Rect inRect) { - Vector2 vector = new Vector2(inRect.width - 16f, 36f); - Vector2 vector2 = new Vector2(100f, vector.y - 2f); + Vector2 vector = new Vector2((float)(inRect.width - 16.0), 36f); + Vector2 vector2 = new Vector2(100f, (float)(vector.y - 2.0)); inRect.height -= 45f; - float num = vector.y + 3f; + float num = (float)(vector.y + 3.0); float height = (float)this.files.Count * num; - Rect viewRect = new Rect(0f, 0f, inRect.width - 16f, height); + Rect viewRect = new Rect(0f, 0f, (float)(inRect.width - 16.0), height); Rect outRect = new Rect(inRect.AtZero()); outRect.height -= this.bottomAreaHeight; Widgets.BeginScrollView(outRect, ref this.scrollPosition, viewRect, true); float num2 = 0f; int num3 = 0; - foreach (SaveFileInfo current in this.files) + List.Enumerator enumerator = this.files.GetEnumerator(); + try { - Rect rect = new Rect(0f, num2, vector.x, vector.y); - if (num3 % 2 == 0) + while (enumerator.MoveNext()) { - Widgets.DrawAltRect(rect); - } - Rect position = rect.ContractedBy(1f); - GUI.BeginGroup(position); - string fileNameWithoutExtension = Path.GetFileNameWithoutExtension(current.FileInfo.Name); - GUI.color = this.FileNameColor(current); - Rect rect2 = new Rect(15f, 0f, position.width, position.height); - Text.Anchor = TextAnchor.MiddleLeft; - Text.Font = GameFont.Small; - Widgets.Label(rect2, fileNameWithoutExtension); - GUI.color = Color.white; - Rect rect3 = new Rect(270f, 0f, 200f, position.height); - Dialog_FileList.DrawDateAndVersion(current, rect3); - GUI.color = Color.white; - Text.Anchor = TextAnchor.UpperLeft; - Text.Font = GameFont.Small; - float num4 = vector.x - 2f - vector2.x - vector2.y; - Rect rect4 = new Rect(num4, 0f, vector2.x, vector2.y); - if (Widgets.ButtonText(rect4, this.interactButLabel, true, false, true)) - { - this.DoFileInteraction(Path.GetFileNameWithoutExtension(current.FileInfo.Name)); - } - Rect rect5 = new Rect(num4 + vector2.x + 5f, 0f, vector2.y, vector2.y); - if (Widgets.ButtonImage(rect5, TexButton.DeleteX)) - { - FileInfo localFile = current.FileInfo; - Find.WindowStack.Add(Dialog_MessageBox.CreateConfirmation("ConfirmDelete".Translate(new object[] + SaveFileInfo current = enumerator.Current; + Rect rect = new Rect(0f, num2, vector.x, vector.y); + if (num3 % 2 == 0) { - localFile.Name - }), delegate + Widgets.DrawAltRect(rect); + } + Rect position = rect.ContractedBy(1f); + GUI.BeginGroup(position); + string fileNameWithoutExtension = Path.GetFileNameWithoutExtension(current.FileInfo.Name); + GUI.color = this.FileNameColor(current); + Rect rect2 = new Rect(15f, 0f, position.width, position.height); + Text.Anchor = TextAnchor.MiddleLeft; + Text.Font = GameFont.Small; + Widgets.Label(rect2, fileNameWithoutExtension); + GUI.color = Color.white; + Rect rect3 = new Rect(270f, 0f, 200f, position.height); + Dialog_FileList.DrawDateAndVersion(current, rect3); + GUI.color = Color.white; + Text.Anchor = TextAnchor.UpperLeft; + Text.Font = GameFont.Small; + float num4 = (float)(vector.x - 2.0 - vector2.x - vector2.y); + Rect rect4 = new Rect(num4, 0f, vector2.x, vector2.y); + if (Widgets.ButtonText(rect4, this.interactButLabel, true, false, true)) { - localFile.Delete(); - this.ReloadFiles(); - }, true, null)); + this.DoFileInteraction(Path.GetFileNameWithoutExtension(current.FileInfo.Name)); + } + Rect rect5 = new Rect((float)(num4 + vector2.x + 5.0), 0f, vector2.y, vector2.y); + if (Widgets.ButtonImage(rect5, TexButton.DeleteX)) + { + FileInfo localFile = current.FileInfo; + Find.WindowStack.Add(Dialog_MessageBox.CreateConfirmation("ConfirmDelete".Translate(localFile.Name), (Action)delegate + { + localFile.Delete(); + this.ReloadFiles(); + }, true, (string)null)); + } + TooltipHandler.TipRegion(rect5, "DeleteThisSavegame".Translate()); + GUI.EndGroup(); + num2 = (float)(num2 + (vector.y + 3.0)); + num3++; } - TooltipHandler.TipRegion(rect5, "DeleteThisSavegame".Translate()); - GUI.EndGroup(); - num2 += vector.y + 3f; - num3++; + } + finally + { + ((IDisposable)(object)enumerator).Dispose(); } Widgets.EndScrollView(); if (this.ShouldDoTypeInField) @@ -141,7 +147,7 @@ protected virtual void DoTypeInField(Rect rect) { GUI.BeginGroup(rect); bool flag = Event.current.type == EventType.KeyDown && Event.current.keyCode == KeyCode.Return; - float y = rect.height - 52f; + float y = (float)(rect.height - 52.0); Text.Font = GameFont.Small; Text.Anchor = TextAnchor.MiddleLeft; GUI.SetNextControlName("MapNameField"); @@ -156,7 +162,7 @@ protected virtual void DoTypeInField(Rect rect) UI.FocusControl("MapNameField", this); this.focusedNameArea = true; } - Rect rect3 = new Rect(420f, y, rect.width - 400f - 20f, 35f); + Rect rect3 = new Rect(420f, y, (float)(rect.width - 400.0 - 20.0), 35f); if (Widgets.ButtonText(rect3, "SaveGameButton".Translate(), true, false, true) || flag) { if (this.typingName.NullOrEmpty()) @@ -182,10 +188,10 @@ public static void DrawDateAndVersion(SaveFileInfo sfi, Rect rect) GUI.BeginGroup(rect); Text.Font = GameFont.Tiny; Text.Anchor = TextAnchor.UpperLeft; - Rect rect2 = new Rect(0f, 2f, rect.width, rect.height / 2f); + Rect rect2 = new Rect(0f, 2f, rect.width, (float)(rect.height / 2.0)); GUI.color = SaveFileInfo.UnimportantTextColor; Widgets.Label(rect2, sfi.FileInfo.LastWriteTime.ToString("g")); - Rect rect3 = new Rect(0f, rect2.yMax, rect.width, rect.height / 2f); + Rect rect3 = new Rect(0f, rect2.yMax, rect.width, (float)(rect.height / 2.0)); GUI.color = sfi.VersionColor; Widgets.Label(rect3, sfi.GameVersion); TooltipHandler.TipRegion(rect3, sfi.CompatibilityTip); diff --git a/Assembly-CSharp/RimWorld/Dialog_FormCaravan.cs b/Assembly-CSharp/RimWorld/Dialog_FormCaravan.cs index 9ea4890d8..58d3329b1 100644 --- a/Assembly-CSharp/RimWorld/Dialog_FormCaravan.cs +++ b/Assembly-CSharp/RimWorld/Dialog_FormCaravan.cs @@ -12,9 +12,9 @@ public class Dialog_FormCaravan : Window { private enum Tab { - Pawns, - Items, - Config + Pawns = 0, + Items = 1, + Config = 2 } private const float TitleRectHeight = 40f; @@ -43,7 +43,7 @@ private enum Tab private TransferableOneWayWidget itemsTransfer; - private Dialog_FormCaravan.Tab tab; + private Tab tab; private float lastMassFlashTime = -9999f; @@ -165,10 +165,10 @@ private bool MostFoodWillRotSoon CompRottable compRottable = transferableOneWay.AnyThing.TryGetComp(); if (compRottable != null) { - num3 = (float)compRottable.ApproxTicksUntilRotWhenAtTempOfTile(this.CurrentTile) / 60000f; + num3 = (float)((float)compRottable.ApproxTicksUntilRotWhenAtTempOfTile(this.CurrentTile) / 60000.0); } float num4 = transferableOneWay.ThingDef.ingestible.nutrition * (float)transferableOneWay.CountToTransfer; - if (num3 < 5f) + if (num3 < 5.0) { num += num4; } @@ -178,7 +178,11 @@ private bool MostFoodWillRotSoon } } } - return (num != 0f || num2 != 0f) && num / (num + num2) >= 0.75f; + if (num == 0.0 && num2 == 0.0) + { + return false; + } + return num / (num + num2) >= 0.75; } } @@ -188,9 +192,9 @@ public Dialog_FormCaravan(Map map, bool reform = false, Action onClosed = null, this.reform = reform; this.onClosed = onClosed; this.showEstTimeToDestinationButton = showEstTimeToDestinationButton; - this.closeOnEscapeKey = true; - this.forcePause = true; - this.absorbInputAroundWindow = true; + base.closeOnEscapeKey = true; + base.forcePause = true; + base.absorbInputAroundWindow = true; } public override void PostOpen() @@ -208,7 +212,7 @@ public override void PostOpen() public override void PostClose() { base.PostClose(); - if (this.onClosed != null) + if ((object)this.onClosed != null) { this.onClosed(); } @@ -223,20 +227,20 @@ public override void DoWindowContents(Rect inRect) Text.Font = GameFont.Small; Text.Anchor = TextAnchor.UpperLeft; Dialog_FormCaravan.tabsList.Clear(); - Dialog_FormCaravan.tabsList.Add(new TabRecord("PawnsTab".Translate(), delegate + Dialog_FormCaravan.tabsList.Add(new TabRecord("PawnsTab".Translate(), (Action)delegate { - this.tab = Dialog_FormCaravan.Tab.Pawns; - }, this.tab == Dialog_FormCaravan.Tab.Pawns)); - Dialog_FormCaravan.tabsList.Add(new TabRecord("ItemsTab".Translate(), delegate + this.tab = Tab.Pawns; + }, this.tab == Tab.Pawns)); + Dialog_FormCaravan.tabsList.Add(new TabRecord("ItemsTab".Translate(), (Action)delegate { - this.tab = Dialog_FormCaravan.Tab.Items; - }, this.tab == Dialog_FormCaravan.Tab.Items)); + this.tab = Tab.Items; + }, this.tab == Tab.Items)); if (!this.reform) { - Dialog_FormCaravan.tabsList.Add(new TabRecord("CaravanConfigTab".Translate(), delegate + Dialog_FormCaravan.tabsList.Add(new TabRecord("CaravanConfigTab".Translate(), (Action)delegate { - this.tab = Dialog_FormCaravan.Tab.Config; - }, this.tab == Dialog_FormCaravan.Tab.Config)); + this.tab = Tab.Config; + }, this.tab == Tab.Config)); } inRect.yMin += 72f; Widgets.DrawMenuSection(inRect, true); @@ -244,13 +248,13 @@ public override void DoWindowContents(Rect inRect) inRect = inRect.ContractedBy(17f); GUI.BeginGroup(inRect); Rect rect2 = inRect.AtZero(); - if (this.tab != Dialog_FormCaravan.Tab.Config) + if (this.tab != Tab.Config) { Rect rect3 = rect2; - rect3.xMin += rect2.width - 515f; + rect3.xMin += (float)(rect2.width - 515.0); rect3.y += 32f; TransferableUIUtility.DrawMassInfo(rect3, this.MassUsage, this.MassCapacity, "CaravanMassUsageTooltip".Translate(), this.lastMassFlashTime, true); - CaravanUIUtility.DrawDaysWorthOfFoodInfo(new Rect(rect3.x, rect3.y + 19f, rect3.width, rect3.height), this.DaysWorthOfFood.First, this.DaysWorthOfFood.Second, this.EnvironmentAllowsEatingVirtualPlantsNow, true, 3.40282347E+38f); + CaravanUIUtility.DrawDaysWorthOfFoodInfo(new Rect(rect3.x, (float)(rect3.y + 19.0), rect3.width, rect3.height), this.DaysWorthOfFood.First, this.DaysWorthOfFood.Second, this.EnvironmentAllowsEatingVirtualPlantsNow, true, 3.40282347E+38f); } this.DoBottomButtons(rect2); Rect inRect2 = rect2; @@ -258,16 +262,22 @@ public override void DoWindowContents(Rect inRect) bool flag = false; switch (this.tab) { - case Dialog_FormCaravan.Tab.Pawns: + case Tab.Pawns: + { this.pawnsTransfer.OnGUI(inRect2, out flag); break; - case Dialog_FormCaravan.Tab.Items: + } + case Tab.Items: + { this.itemsTransfer.OnGUI(inRect2, out flag); break; - case Dialog_FormCaravan.Tab.Config: + } + case Tab.Config: + { this.DrawConfig(rect2); break; } + } if (flag) { this.CountToTransferChanged(); @@ -282,7 +292,7 @@ public override bool CausesMessageBackground() private void AddToTransferables(Thing t, bool setToTransferMax = false) { - TransferableOneWay transferableOneWay = TransferableUtility.TransferableMatching(t, this.transferables); + TransferableOneWay transferableOneWay = TransferableUtility.TransferableMatching(t, this.transferables); if (transferableOneWay == null) { transferableOneWay = new TransferableOneWay(); @@ -297,7 +307,14 @@ private void AddToTransferables(Thing t, bool setToTransferMax = false) private void DoBottomButtons(Rect rect) { - Rect rect2 = new Rect(rect.width / 2f - this.BottomButtonSize.x / 2f, rect.height - 55f, this.BottomButtonSize.x, this.BottomButtonSize.y); + double num = rect.width / 2.0; + Vector2 bottomButtonSize = this.BottomButtonSize; + double x2 = num - bottomButtonSize.x / 2.0; + double y = rect.height - 55.0; + Vector2 bottomButtonSize2 = this.BottomButtonSize; + float x3 = bottomButtonSize2.x; + Vector2 bottomButtonSize3 = this.BottomButtonSize; + Rect rect2 = new Rect((float)x2, (float)y, x3, bottomButtonSize3.y); if (Widgets.ButtonText(rect2, "AcceptButton".Translate(), true, false, true)) { if (this.reform) @@ -310,14 +327,11 @@ private void DoBottomButtons(Rect rect) } else { - string text = null; + string text = (string)null; Pair daysWorthOfFood = this.DaysWorthOfFood; - if (daysWorthOfFood.First < 5f) + if (daysWorthOfFood.First < 5.0) { - text = ((daysWorthOfFood.First >= 0.1f) ? "DaysWorthOfFoodWarningDialog".Translate(new object[] - { - daysWorthOfFood.First.ToString("0.#") - }) : "DaysWorthOfFoodWarningDialog_NoFood".Translate()); + text = ((!(daysWorthOfFood.First < 0.10000000149011612)) ? "DaysWorthOfFoodWarningDialog".Translate(daysWorthOfFood.First.ToString("0.#")) : "DaysWorthOfFoodWarningDialog_NoFood".Translate()); } else if (this.MostFoodWillRotSoon) { @@ -327,13 +341,13 @@ private void DoBottomButtons(Rect rect) { if (this.CheckForErrors(TransferableUtility.GetPawnsFromTransferables(this.transferables))) { - Find.WindowStack.Add(Dialog_MessageBox.CreateConfirmation(text, delegate + Find.WindowStack.Add(Dialog_MessageBox.CreateConfirmation(text, (Action)delegate { if (this.TryFormAndSendCaravan()) { this.Close(false); } - }, false, null)); + }, false, (string)null)); } } else if (this.TryFormAndSendCaravan()) @@ -343,24 +357,43 @@ private void DoBottomButtons(Rect rect) } } } - Rect rect3 = new Rect(rect2.x - 10f - this.BottomButtonSize.x, rect2.y, this.BottomButtonSize.x, this.BottomButtonSize.y); + double num2 = rect2.x - 10.0; + Vector2 bottomButtonSize4 = this.BottomButtonSize; + double x4 = num2 - bottomButtonSize4.x; + float y2 = rect2.y; + Vector2 bottomButtonSize5 = this.BottomButtonSize; + float x5 = bottomButtonSize5.x; + Vector2 bottomButtonSize6 = this.BottomButtonSize; + Rect rect3 = new Rect((float)x4, y2, x5, bottomButtonSize6.y); if (Widgets.ButtonText(rect3, "ResetButton".Translate(), true, false, true)) { SoundDefOf.TickLow.PlayOneShotOnCamera(null); this.CalculateAndRecacheTransferables(); } - Rect rect4 = new Rect(rect2.xMax + 10f, rect2.y, this.BottomButtonSize.x, this.BottomButtonSize.y); + double x6 = rect2.xMax + 10.0; + float y3 = rect2.y; + Vector2 bottomButtonSize7 = this.BottomButtonSize; + float x7 = bottomButtonSize7.x; + Vector2 bottomButtonSize8 = this.BottomButtonSize; + Rect rect4 = new Rect((float)x6, y3, x7, bottomButtonSize8.y); if (Widgets.ButtonText(rect4, "CancelButton".Translate(), true, false, true)) { this.Close(true); } if (this.showEstTimeToDestinationButton) { - Rect rect5 = new Rect(rect.width - this.BottomButtonSize.x, rect2.y, this.BottomButtonSize.x, this.BottomButtonSize.y); + float width = rect.width; + Vector2 bottomButtonSize9 = this.BottomButtonSize; + float x8 = width - bottomButtonSize9.x; + float y4 = rect2.y; + Vector2 bottomButtonSize10 = this.BottomButtonSize; + float x9 = bottomButtonSize10.x; + Vector2 bottomButtonSize11 = this.BottomButtonSize; + Rect rect5 = new Rect(x8, y4, x9, bottomButtonSize11.y); if (Widgets.ButtonText(rect5, "EstimatedTimeToDestinationButton".Translate(), true, false, true)) { List pawnsFromTransferables = TransferableUtility.GetPawnsFromTransferables(this.transferables); - if (!pawnsFromTransferables.Any((Pawn x) => CaravanUtility.IsOwner(x, Faction.OfPlayer) && !x.Downed)) + if (!pawnsFromTransferables.Any((Predicate)((Pawn x) => CaravanUtility.IsOwner(x, Faction.OfPlayer) && !x.Downed))) { Messages.Message("CaravanMustHaveAtLeastOneColonist".Translate(), MessageSound.RejectInput); } @@ -372,15 +405,16 @@ private void DoBottomButtons(Rect rect) } if (Prefs.DevMode) { - float width = 200f; - float num = this.BottomButtonSize.y / 2f; - Rect rect6 = new Rect(0f, rect.height - 55f, width, num); + float width2 = 200f; + Vector2 bottomButtonSize12 = this.BottomButtonSize; + float num3 = (float)(bottomButtonSize12.y / 2.0); + Rect rect6 = new Rect(0f, (float)(rect.height - 55.0), width2, num3); if (Widgets.ButtonText(rect6, "Dev: Send instantly", true, false, true) && this.DebugTryFormCaravanInstantly()) { SoundDefOf.TickHigh.PlayOneShotOnCamera(null); this.Close(false); } - Rect rect7 = new Rect(0f, rect.height - 55f + num, width, num); + Rect rect7 = new Rect(0f, (float)(rect.height - 55.0 + num3), width2, num3); if (Widgets.ButtonText(rect7, "Dev: Select everything", true, false, true)) { SoundDefOf.TickHigh.PlayOneShotOnCamera(null); @@ -394,16 +428,8 @@ private void CalculateAndRecacheTransferables() this.transferables = new List(); this.AddPawnsToTransferables(); this.AddItemsToTransferables(); - string sourceLabel; - if (this.reform) - { - sourceLabel = this.map.info.parent.LabelCap; - } - else - { - sourceLabel = Faction.OfPlayer.Name; - } - CaravanUIUtility.CreateCaravanTransferableWidgets(this.transferables, out this.pawnsTransfer, out this.itemsTransfer, sourceLabel, WorldObjectDefOf.Caravan.LabelCap, "FormCaravanColonyThingCountTip".Translate(), IgnorePawnsInventoryMode.IgnoreIfAssignedToUnload, () => this.MassCapacity - this.MassUsage, this.AutoStripCorpses, this.CurrentTile); + string sourceLabel = (!this.reform) ? Faction.OfPlayer.Name : this.map.info.parent.LabelCap; + CaravanUIUtility.CreateCaravanTransferableWidgets(this.transferables, out this.pawnsTransfer, out this.itemsTransfer, sourceLabel, WorldObjectDefOf.Caravan.LabelCap, "FormCaravanColonyThingCountTip".Translate(), IgnorePawnsInventoryMode.IgnoreIfAssignedToUnload, (Func)(() => this.MassCapacity - this.MassUsage), this.AutoStripCorpses, this.CurrentTile); this.CountToTransferChanged(); } @@ -414,20 +440,23 @@ private void DrawConfig(Rect rect) Widgets.Label(rect2, "ExitDirection".Translate()); Text.Font = GameFont.Small; List list = CaravanExitMapUtility.AvailableExitTilesAt(this.map); - if (list.Any()) + if (list.Any()) { for (int i = 0; i < list.Count; i++) { Direction8Way direction8WayFromTo = Find.WorldGrid.GetDirection8WayFromTo(this.CurrentTile, list[i]); - float y = rect.y + (float)i * this.ExitDirectionRadioSize.y + 30f + 4f; - Rect rect3 = new Rect(rect.x, y, this.ExitDirectionRadioSize.x, this.ExitDirectionRadioSize.y); + float y = rect.y; + float num = (float)i; + Vector2 exitDirectionRadioSize = this.ExitDirectionRadioSize; + float num2 = (float)(y + num * exitDirectionRadioSize.y + 30.0 + 4.0); + float x = rect.x; + float y2 = num2; + Vector2 exitDirectionRadioSize2 = this.ExitDirectionRadioSize; + float x2 = exitDirectionRadioSize2.x; + Vector2 exitDirectionRadioSize3 = this.ExitDirectionRadioSize; + Rect rect3 = new Rect(x, y2, x2, exitDirectionRadioSize3.y); Vector2 vector = Find.WorldGrid.LongLatOf(list[i]); - string labelText = "ExitDirectionRadioButtonLabel".Translate(new object[] - { - direction8WayFromTo.LabelShort(), - vector.y.ToStringLatitude(), - vector.x.ToStringLongitude() - }); + string labelText = "ExitDirectionRadioButtonLabel".Translate(direction8WayFromTo.LabelShort(), vector.y.ToStringLatitude(), vector.x.ToStringLongitude()); if (Widgets.RadioButtonLabeled(rect3, labelText, this.startingTile == list[i])) { this.startingTile = list[i]; @@ -437,7 +466,7 @@ private void DrawConfig(Rect rect) else { GUI.color = Color.gray; - Widgets.Label(new Rect(rect.x, rect.y + 30f + 4f, rect.width, 100f), "NoCaravanExitDirectionAvailable".Translate()); + Widgets.Label(new Rect(rect.x, (float)(rect.y + 30.0 + 4.0), rect.width, 100f), "NoCaravanExitDirectionAvailable".Translate()); GUI.color = Color.white; } } @@ -445,7 +474,7 @@ private void DrawConfig(Rect rect) private bool DebugTryFormCaravanInstantly() { List pawnsFromTransferables = TransferableUtility.GetPawnsFromTransferables(this.transferables); - if (!pawnsFromTransferables.Any((Pawn x) => CaravanUtility.IsOwner(x, Faction.OfPlayer))) + if (!pawnsFromTransferables.Any((Predicate)((Pawn x) => CaravanUtility.IsOwner(x, Faction.OfPlayer)))) { Messages.Message("CaravanMustHaveAtLeastOneColonist".Translate(), MessageSound.RejectInput); return false; @@ -468,33 +497,24 @@ private bool TryFormAndSendCaravan() return false; } Direction8Way direction8WayFromTo = Find.WorldGrid.GetDirection8WayFromTo(this.CurrentTile, this.startingTile); - IntVec3 intVec; + IntVec3 intVec = default(IntVec3); if (!this.TryFindExitSpot(pawnsFromTransferables, true, out intVec)) { if (!this.TryFindExitSpot(pawnsFromTransferables, false, out intVec)) { - Messages.Message("CaravanCouldNotFindExitSpot".Translate(new object[] - { - direction8WayFromTo.LabelShort() - }), MessageSound.RejectInput); + Messages.Message("CaravanCouldNotFindExitSpot".Translate(direction8WayFromTo.LabelShort()), MessageSound.RejectInput); return false; } - Messages.Message("CaravanCouldNotFindReachableExitSpot".Translate(new object[] - { - direction8WayFromTo.LabelShort() - }), new GlobalTargetInfo(intVec, this.map, false), MessageSound.Negative); + Messages.Message("CaravanCouldNotFindReachableExitSpot".Translate(direction8WayFromTo.LabelShort()), new GlobalTargetInfo(intVec, this.map, false), MessageSound.Negative); } - IntVec3 meetingPoint; + IntVec3 meetingPoint = default(IntVec3); if (!this.TryFindRandomPackingSpot(intVec, out meetingPoint)) { - Messages.Message("CaravanCouldNotFindPackingSpot".Translate(new object[] - { - direction8WayFromTo.LabelShort() - }), new GlobalTargetInfo(intVec, this.map, false), MessageSound.RejectInput); + Messages.Message("CaravanCouldNotFindPackingSpot".Translate(direction8WayFromTo.LabelShort()), new GlobalTargetInfo(intVec, this.map, false), MessageSound.RejectInput); return false; } CaravanFormingUtility.StartFormingCaravan(pawnsFromTransferables, Faction.OfPlayer, this.transferables, meetingPoint, intVec, this.startingTile); - Messages.Message("CaravanFormationProcessStarted".Translate(), pawnsFromTransferables[0], MessageSound.Benefit); + Messages.Message("CaravanFormationProcessStarted".Translate(), (Thing)pawnsFromTransferables[0], MessageSound.Benefit); return true; } @@ -508,16 +528,16 @@ private bool TryReformCaravan() this.AddItemsFromTransferablesToRandomInventories(pawnsFromTransferables); Caravan o = CaravanExitMapUtility.ExitMapAndCreateCaravan(pawnsFromTransferables, Faction.OfPlayer, this.CurrentTile); this.map.info.parent.CheckRemoveMapNow(); - Messages.Message("MessageReformedCaravan".Translate(), o, MessageSound.Benefit); + Messages.Message("MessageReformedCaravan".Translate(), (WorldObject)o, MessageSound.Benefit); return true; } private void AddItemsFromTransferablesToRandomInventories(List pawns) { - this.transferables.RemoveAll((TransferableOneWay x) => x.AnyThing is Pawn); + this.transferables.RemoveAll((Predicate)((TransferableOneWay x) => x.AnyThing is Pawn)); for (int i = 0; i < this.transferables.Count; i++) { - TransferableUtility.TransferNoSplit(this.transferables[i].things, this.transferables[i].CountToTransfer, delegate(Thing originalThing, int numToTake) + TransferableUtility.TransferNoSplit(this.transferables[i].things, this.transferables[i].CountToTransfer, (Action)delegate(Thing originalThing, int numToTake) { Corpse corpse = originalThing as Corpse; if (corpse != null && corpse.SpawnedOrAnyParentSpawned) @@ -567,7 +587,7 @@ private bool CheckForErrors(List pawns) Messages.Message("NoExitDirectionForCaravanChosen".Translate(), MessageSound.RejectInput); return false; } - if (!pawns.Any((Pawn x) => CaravanUtility.IsOwner(x, Faction.OfPlayer) && !x.Downed)) + if (!pawns.Any((Predicate)((Pawn x) => CaravanUtility.IsOwner(x, Faction.OfPlayer) && !x.Downed))) { Messages.Message("CaravanMustHaveAtLeastOneColonist".Translate(), MessageSound.RejectInput); return false; @@ -578,13 +598,10 @@ private bool CheckForErrors(List pawns) Messages.Message("TooBigCaravanMassUsage".Translate(), MessageSound.RejectInput); return false; } - Pawn pawn = pawns.Find((Pawn x) => !x.IsColonist && !pawns.Any((Pawn y) => y.IsColonist && y.CanReach(x, PathEndMode.Touch, Danger.Deadly, false, TraverseMode.ByPawn))); + Pawn pawn = pawns.Find((Predicate)((Pawn x) => !x.IsColonist && !pawns.Any((Predicate)((Pawn y) => y.IsColonist && y.CanReach((Thing)x, PathEndMode.Touch, Danger.Deadly, false, TraverseMode.ByPawn))))); if (pawn != null) { - Messages.Message("CaravanPawnIsUnreachable".Translate(new object[] - { - pawn.LabelShort - }).CapitalizeFirst(), pawn, MessageSound.RejectInput); + Messages.Message("CaravanPawnIsUnreachable".Translate(pawn.LabelShort).CapitalizeFirst(), (Thing)pawn, MessageSound.RejectInput); return false; } for (int i = 0; i < this.transferables.Count; i++) @@ -598,31 +615,22 @@ private bool CheckForErrors(List pawns) for (int j = 0; j < this.transferables[i].things.Count; j++) { Thing t = this.transferables[i].things[j]; - if (!t.Spawned || pawns.Any((Pawn x) => x.IsColonist && x.CanReach(t, PathEndMode.Touch, Danger.Deadly, false, TraverseMode.ByPawn))) + if (!t.Spawned || pawns.Any((Predicate)((Pawn x) => x.IsColonist && x.CanReach(t, PathEndMode.Touch, Danger.Deadly, false, TraverseMode.ByPawn)))) { num += t.stackCount; if (num >= countToTransfer) - { break; - } } } if (num < countToTransfer) { if (countToTransfer == 1) { - Messages.Message("CaravanItemIsUnreachableSingle".Translate(new object[] - { - this.transferables[i].ThingDef.label - }), MessageSound.RejectInput); + Messages.Message("CaravanItemIsUnreachableSingle".Translate(this.transferables[i].ThingDef.label), MessageSound.RejectInput); } else { - Messages.Message("CaravanItemIsUnreachableMulti".Translate(new object[] - { - countToTransfer, - this.transferables[i].ThingDef.label - }), MessageSound.RejectInput); + Messages.Message("CaravanItemIsUnreachableMulti".Translate(countToTransfer, this.transferables[i].ThingDef.label), MessageSound.RejectInput); } return false; } @@ -640,11 +648,11 @@ private bool TryFindExitSpot(List pawns, bool reachableForEveryColonist, o spot = IntVec3.Invalid; return false; } - Predicate validator = (IntVec3 x) => !x.Fogged(this.map) && x.Standable(this.map); + Predicate validator = (Predicate)((IntVec3 x) => !x.Fogged(this.map) && x.Standable(this.map)); Rot4 rotFromTo = Find.WorldGrid.GetRotFromTo(this.CurrentTile, this.startingTile); if (reachableForEveryColonist) { - return CellFinder.TryFindRandomEdgeCellWith(delegate(IntVec3 x) + return CellFinder.TryFindRandomEdgeCellWith((Predicate)delegate(IntVec3 x) { if (!validator(x)) { @@ -662,14 +670,14 @@ private bool TryFindExitSpot(List pawns, bool reachableForEveryColonist, o } IntVec3 intVec = IntVec3.Invalid; int num = -1; - foreach (IntVec3 current in CellRect.WholeMap(this.map).GetEdgeCells(rotFromTo).InRandomOrder(null)) + foreach (IntVec3 item in CellRect.WholeMap(this.map).GetEdgeCells(rotFromTo).InRandomOrder(null)) { - if (validator(current)) + if (validator(item)) { int num2 = 0; for (int i = 0; i < pawns.Count; i++) { - if (pawns[i].IsColonist && pawns[i].CanReach(current, PathEndMode.Touch, Danger.Deadly, false, TraverseMode.ByPawn)) + if (pawns[i].IsColonist && pawns[i].CanReach(item, PathEndMode.Touch, Danger.Deadly, false, TraverseMode.ByPawn)) { num2++; } @@ -677,7 +685,7 @@ private bool TryFindExitSpot(List pawns, bool reachableForEveryColonist, o if (num2 > num) { num = num2; - intVec = current; + intVec = item; } } } @@ -697,9 +705,9 @@ private bool TryFindRandomPackingSpot(IntVec3 exitSpot, out IntVec3 packingSpot) Dialog_FormCaravan.tmpPackingSpots.Add(list[i]); } } - if (Dialog_FormCaravan.tmpPackingSpots.Any()) + if (Dialog_FormCaravan.tmpPackingSpots.Any()) { - Thing thing = Dialog_FormCaravan.tmpPackingSpots.RandomElement(); + Thing thing = Dialog_FormCaravan.tmpPackingSpots.RandomElement(); Dialog_FormCaravan.tmpPackingSpots.Clear(); packingSpot = thing.Position; return true; diff --git a/Assembly-CSharp/RimWorld/Dialog_GiveName.cs b/Assembly-CSharp/RimWorld/Dialog_GiveName.cs index 4c4894ef2..67cb6afee 100644 --- a/Assembly-CSharp/RimWorld/Dialog_GiveName.cs +++ b/Assembly-CSharp/RimWorld/Dialog_GiveName.cs @@ -1,4 +1,3 @@ -using System; using UnityEngine; using Verse; @@ -28,7 +27,7 @@ private float Height { get { - return (!this.useSecondName) ? 200f : 330f; + return (float)((!this.useSecondName) ? 200.0 : 330.0); } } @@ -42,24 +41,24 @@ public override Vector2 InitialSize public Dialog_GiveName() { - if (Find.AnyPlayerHomeMap != null && Find.AnyPlayerHomeMap.mapPawns.FreeColonistsCount != 0) + if (((Find.AnyPlayerHomeMap != null) ? Find.AnyPlayerHomeMap.mapPawns.FreeColonistsCount : 0) != 0) { if (Find.AnyPlayerHomeMap.mapPawns.FreeColonistsSpawnedCount != 0) { - this.suggestingPawn = Find.AnyPlayerHomeMap.mapPawns.FreeColonistsSpawned.RandomElement(); + this.suggestingPawn = Find.AnyPlayerHomeMap.mapPawns.FreeColonistsSpawned.RandomElement(); } else { - this.suggestingPawn = Find.AnyPlayerHomeMap.mapPawns.FreeColonists.RandomElement(); + this.suggestingPawn = Find.AnyPlayerHomeMap.mapPawns.FreeColonists.RandomElement(); } } else { - this.suggestingPawn = PawnsFinder.AllMapsCaravansAndTravelingTransportPods_FreeColonists.RandomElement(); + this.suggestingPawn = PawnsFinder.AllMapsCaravansAndTravelingTransportPods_FreeColonists.RandomElement(); } - this.forcePause = true; - this.closeOnEscapeKey = false; - this.absorbInputAroundWindow = true; + base.forcePause = true; + base.closeOnEscapeKey = false; + base.absorbInputAroundWindow = true; } public override void DoWindowContents(Rect rect) @@ -74,64 +73,47 @@ public override void DoWindowContents(Rect rect) Rect rect2; if (!this.useSecondName) { - Widgets.Label(new Rect(0f, 0f, rect.width, rect.height), this.nameMessageKey.Translate(new object[] - { - this.suggestingPawn.NameStringShort - })); - this.curName = Widgets.TextField(new Rect(0f, rect.height - 35f, rect.width / 2f - 20f, 35f), this.curName); - rect2 = new Rect(rect.width / 2f + 20f, rect.height - 35f, rect.width / 2f - 20f, 35f); + Widgets.Label(new Rect(0f, 0f, rect.width, rect.height), this.nameMessageKey.Translate(this.suggestingPawn.NameStringShort)); + this.curName = Widgets.TextField(new Rect(0f, (float)(rect.height - 35.0), (float)(rect.width / 2.0 - 20.0), 35f), this.curName); + rect2 = new Rect((float)(rect.width / 2.0 + 20.0), (float)(rect.height - 35.0), (float)(rect.width / 2.0 - 20.0), 35f); } else { float num = 0f; - string text = this.nameMessageKey.Translate(new object[] - { - this.suggestingPawn.NameStringShort - }); + string text = this.nameMessageKey.Translate(this.suggestingPawn.NameStringShort); Widgets.Label(new Rect(0f, num, rect.width, rect.height), text); - num += Text.CalcHeight(text, rect.width) + 10f; - this.curName = Widgets.TextField(new Rect(0f, num, rect.width / 2f - 20f, 35f), this.curName); - num += 60f; - text = this.secondNameMessageKey.Translate(new object[] - { - this.suggestingPawn.NameStringShort - }); + num = (float)(num + (Text.CalcHeight(text, rect.width) + 10.0)); + this.curName = Widgets.TextField(new Rect(0f, num, (float)(rect.width / 2.0 - 20.0), 35f), this.curName); + num = (float)(num + 60.0); + text = this.secondNameMessageKey.Translate(this.suggestingPawn.NameStringShort); Widgets.Label(new Rect(0f, num, rect.width, rect.height), text); - num += Text.CalcHeight(text, rect.width) + 10f; - this.curSecondName = Widgets.TextField(new Rect(0f, num, rect.width / 2f - 20f, 35f), this.curSecondName); - num += 45f; - rect2 = new Rect(0f, rect.height - 35f, rect.width / 2f - 20f, 35f); + num = (float)(num + (Text.CalcHeight(text, rect.width) + 10.0)); + this.curSecondName = Widgets.TextField(new Rect(0f, num, (float)(rect.width / 2.0 - 20.0), 35f), this.curSecondName); + num = (float)(num + 45.0); + rect2 = new Rect(0f, (float)(rect.height - 35.0), (float)(rect.width / 2.0 - 20.0), 35f); } - if (Widgets.ButtonText(rect2, "OK".Translate(), true, false, true) || flag) + if (!Widgets.ButtonText(rect2, "OK".Translate(), true, false, true) && !flag) + return; + if (this.IsValidName(this.curName) && (!this.useSecondName || this.IsValidName(this.curSecondName))) { - if (this.IsValidName(this.curName) && (!this.useSecondName || this.IsValidName(this.curSecondName))) + if (this.useSecondName) { - if (this.useSecondName) - { - this.Named(this.curName); - this.NamedSecond(this.curSecondName); - Messages.Message(this.gainedNameMessageKey.Translate(new object[] - { - this.curName, - this.curSecondName - }), MessageSound.Benefit); - } - else - { - this.Named(this.curName); - Messages.Message(this.gainedNameMessageKey.Translate(new object[] - { - this.curName - }), MessageSound.Benefit); - } - Find.WindowStack.TryRemove(this, true); + this.Named(this.curName); + this.NamedSecond(this.curSecondName); + Messages.Message(this.gainedNameMessageKey.Translate(this.curName, this.curSecondName), MessageSound.Benefit); } else { - Messages.Message(this.invalidNameMessageKey.Translate(), MessageSound.RejectInput); + this.Named(this.curName); + Messages.Message(this.gainedNameMessageKey.Translate(this.curName), MessageSound.Benefit); } - Event.current.Use(); + Find.WindowStack.TryRemove(this, true); + } + else + { + Messages.Message(this.invalidNameMessageKey.Translate(), MessageSound.RejectInput); } + Event.current.Use(); } protected abstract bool IsValidName(string s); diff --git a/Assembly-CSharp/RimWorld/Dialog_KeyBindings.cs b/Assembly-CSharp/RimWorld/Dialog_KeyBindings.cs index de1efb041..8ad0b2d3c 100644 --- a/Assembly-CSharp/RimWorld/Dialog_KeyBindings.cs +++ b/Assembly-CSharp/RimWorld/Dialog_KeyBindings.cs @@ -40,18 +40,18 @@ protected override float Margin public Dialog_KeyBindings() { - this.forcePause = true; - this.onlyOneOfTypeAllowed = true; - this.absorbInputAroundWindow = true; + base.forcePause = true; + base.onlyOneOfTypeAllowed = true; + base.absorbInputAroundWindow = true; this.scrollPosition = new Vector2(0f, 0f); this.keyPrefsData = KeyPrefs.KeyPrefsData.Clone(); this.contentHeight = 0f; KeyBindingCategoryDef keyBindingCategoryDef = null; - foreach (KeyBindingDef current in DefDatabase.AllDefs) + foreach (KeyBindingDef allDef in DefDatabase.AllDefs) { - if (keyBindingCategoryDef != current.category) + if (keyBindingCategoryDef != allDef.category) { - keyBindingCategoryDef = current.category; + keyBindingCategoryDef = allDef.category; this.contentHeight += 44f; } this.contentHeight += 34f; @@ -63,9 +63,9 @@ public override void DoWindowContents(Rect inRect) Vector2 vector = new Vector2(120f, 40f); float y = vector.y; float num = 600f; - float num2 = (inRect.width - num) / 2f; - Rect position = new Rect(num2 + inRect.x, inRect.y, num, inRect.height - (y + 10f)).ContractedBy(10f); - Rect position2 = new Rect(position.x, position.y + position.height + 10f, position.width, y); + float num2 = (float)((inRect.width - num) / 2.0); + Rect position = new Rect(num2 + inRect.x, inRect.y, num, (float)(inRect.height - (y + 10.0))).ContractedBy(10f); + Rect position2 = new Rect(position.x, (float)(position.y + position.height + 10.0), position.width, y); GUI.BeginGroup(position); Rect rect = new Rect(0f, 0f, position.width, 40f); Text.Font = GameFont.Medium; @@ -74,35 +74,35 @@ public override void DoWindowContents(Rect inRect) GenUI.ResetLabelAlign(); Text.Font = GameFont.Small; Rect outRect = new Rect(0f, rect.height, position.width, position.height - rect.height); - Rect rect2 = new Rect(0f, 0f, outRect.width - 16f, this.contentHeight); + Rect rect2 = new Rect(0f, 0f, (float)(outRect.width - 16.0), this.contentHeight); Widgets.BeginScrollView(outRect, ref this.scrollPosition, rect2, true); float num3 = 0f; KeyBindingCategoryDef keyBindingCategoryDef = null; Dialog_KeyBindings.keyBindingsWorkingList.Clear(); Dialog_KeyBindings.keyBindingsWorkingList.AddRange(DefDatabase.AllDefs); - Dialog_KeyBindings.keyBindingsWorkingList.SortBy((KeyBindingDef x) => x.category.index, (KeyBindingDef x) => x.index); + Dialog_KeyBindings.keyBindingsWorkingList.SortBy((Func)((KeyBindingDef x) => x.category.index), (Func)((KeyBindingDef x) => x.index)); for (int i = 0; i < Dialog_KeyBindings.keyBindingsWorkingList.Count; i++) { KeyBindingDef keyBindingDef = Dialog_KeyBindings.keyBindingsWorkingList[i]; if (keyBindingCategoryDef != keyBindingDef.category) { - bool skipDrawing = num3 - this.scrollPosition.y + 40f < 0f || num3 - this.scrollPosition.y > outRect.height; + bool skipDrawing = num3 - this.scrollPosition.y + 40.0 < 0.0 || num3 - this.scrollPosition.y > outRect.height; keyBindingCategoryDef = keyBindingDef.category; this.DrawCategoryEntry(keyBindingCategoryDef, rect2.width, ref num3, skipDrawing); } - bool skipDrawing2 = num3 - this.scrollPosition.y + 34f < 0f || num3 - this.scrollPosition.y > outRect.height; + bool skipDrawing2 = num3 - this.scrollPosition.y + 34.0 < 0.0 || num3 - this.scrollPosition.y > outRect.height; this.DrawKeyEntry(keyBindingDef, rect2, ref num3, skipDrawing2); } Widgets.EndScrollView(); GUI.EndGroup(); GUI.BeginGroup(position2); int num4 = 3; - float num5 = vector.x * (float)num4 + 10f * (float)(num4 - 1); - float num6 = (position2.width - num5) / 2f; - float num7 = vector.x + 10f; + float num5 = (float)(vector.x * (float)num4 + 10.0 * (float)(num4 - 1)); + float num6 = (float)((position2.width - num5) / 2.0); + float num7 = (float)(vector.x + 10.0); Rect rect3 = new Rect(num6, 0f, vector.x, vector.y); Rect rect4 = new Rect(num6 + num7, 0f, vector.x, vector.y); - Rect rect5 = new Rect(num6 + num7 * 2f, 0f, vector.x, vector.y); + Rect rect5 = new Rect((float)(num6 + num7 * 2.0), 0f, vector.x, vector.y); if (Widgets.ButtonText(rect3, "ResetButton".Translate(), true, false, true)) { this.keyPrefsData.ResetToDefaults(); @@ -160,7 +160,7 @@ private void DrawKeyEntry(KeyBindingDef keyDef, Rect parentRect, ref float curY, GenUI.ResetLabelAlign(); float num = 4f; Vector2 vector = new Vector2(140f, 28f); - Rect rect2 = new Rect(rect.x + rect.width - vector.x * 2f - num, rect.y, vector.x, vector.y); + Rect rect2 = new Rect((float)(rect.x + rect.width - vector.x * 2.0 - num), rect.y, vector.x, vector.y); Rect rect3 = new Rect(rect.x + rect.width - vector.x, rect.y, vector.x, vector.y); TooltipHandler.TipRegion(rect2, new TipSignal("BindingButtonToolTip".Translate())); TooltipHandler.TipRegion(rect3, new TipSignal("BindingButtonToolTip".Translate())); @@ -186,12 +186,12 @@ private void SettingButtonClicked(KeyBindingDef keyDef, KeyPrefs.BindingSlot slo else if (Event.current.button == 1) { List list = new List(); - list.Add(new FloatMenuOption("ResetBinding".Translate(), delegate + list.Add(new FloatMenuOption("ResetBinding".Translate(), (Action)delegate() { - KeyCode keyCode = (slot != KeyPrefs.BindingSlot.A) ? keyDef.defaultKeyCodeB : keyDef.defaultKeyCodeA; + KeyCode keyCode = (slot != 0) ? keyDef.defaultKeyCodeB : keyDef.defaultKeyCodeA; this.keyPrefsData.SetBinding(keyDef, slot, keyCode); }, MenuOptionPriority.Default, null, null, 0f, null, null)); - list.Add(new FloatMenuOption("ClearBinding".Translate(), delegate + list.Add(new FloatMenuOption("ClearBinding".Translate(), (Action)delegate() { this.keyPrefsData.SetBinding(keyDef, slot, KeyCode.None); }, MenuOptionPriority.Default, null, null, 0f, null, null)); diff --git a/Assembly-CSharp/RimWorld/Dialog_LoadTransporters.cs b/Assembly-CSharp/RimWorld/Dialog_LoadTransporters.cs index f0cbe9cb5..57d0dfee4 100644 --- a/Assembly-CSharp/RimWorld/Dialog_LoadTransporters.cs +++ b/Assembly-CSharp/RimWorld/Dialog_LoadTransporters.cs @@ -14,8 +14,8 @@ public class Dialog_LoadTransporters : Window { private enum Tab { - Pawns, - Items + Pawns = 0, + Items = 1 } private const float TitleRectHeight = 40f; @@ -32,7 +32,7 @@ private enum Tab private TransferableOneWayWidget itemsTransfer; - private Dialog_LoadTransporters.Tab tab; + private Tab tab; private float lastMassFlashTime = -9999f; @@ -133,9 +133,9 @@ public Dialog_LoadTransporters(Map map, List transporters) this.map = map; this.transporters = new List(); this.transporters.AddRange(transporters); - this.closeOnEscapeKey = true; - this.forcePause = true; - this.absorbInputAroundWindow = true; + base.closeOnEscapeKey = true; + base.forcePause = true; + base.absorbInputAroundWindow = true; } public override void PostOpen() @@ -149,47 +149,45 @@ public override void DoWindowContents(Rect inRect) Rect rect = new Rect(0f, 0f, inRect.width, 40f); Text.Font = GameFont.Medium; Text.Anchor = TextAnchor.MiddleCenter; - Widgets.Label(rect, "LoadTransporters".Translate(new object[] - { - this.TransportersLabel - })); + Widgets.Label(rect, "LoadTransporters".Translate(this.TransportersLabel)); Text.Font = GameFont.Small; Text.Anchor = TextAnchor.UpperLeft; Dialog_LoadTransporters.tabsList.Clear(); - Dialog_LoadTransporters.tabsList.Add(new TabRecord("PawnsTab".Translate(), delegate + Dialog_LoadTransporters.tabsList.Add(new TabRecord("PawnsTab".Translate(), (Action)delegate { - this.tab = Dialog_LoadTransporters.Tab.Pawns; - }, this.tab == Dialog_LoadTransporters.Tab.Pawns)); - Dialog_LoadTransporters.tabsList.Add(new TabRecord("ItemsTab".Translate(), delegate + this.tab = Tab.Pawns; + }, this.tab == Tab.Pawns)); + Dialog_LoadTransporters.tabsList.Add(new TabRecord("ItemsTab".Translate(), (Action)delegate { - this.tab = Dialog_LoadTransporters.Tab.Items; - }, this.tab == Dialog_LoadTransporters.Tab.Items)); + this.tab = Tab.Items; + }, this.tab == Tab.Items)); inRect.yMin += 72f; Widgets.DrawMenuSection(inRect, true); TabDrawer.DrawTabs(inRect, Dialog_LoadTransporters.tabsList); inRect = inRect.ContractedBy(17f); GUI.BeginGroup(inRect); - Rect rect2 = inRect.AtZero(); - Rect rect3 = rect2; - rect3.xMin += rect2.width - 515f; - rect3.y += 32f; - TransferableUIUtility.DrawMassInfo(rect3, this.MassUsage, this.MassCapacity, "TransportersMassUsageTooltip".Translate(), this.lastMassFlashTime, true); - CaravanUIUtility.DrawDaysWorthOfFoodInfo(new Rect(rect3.x, rect3.y + 19f, rect3.width, rect3.height), this.DaysWorthOfFood.First, this.DaysWorthOfFood.Second, this.EnvironmentAllowsEatingVirtualPlantsNow, true, 3.40282347E+38f); - this.DoBottomButtons(rect2); - Rect inRect2 = rect2; + Rect rect2; + Rect rect3 = rect2 = inRect.AtZero(); + rect2.xMin += (float)(rect3.width - 515.0); + rect2.y += 32f; + TransferableUIUtility.DrawMassInfo(rect2, this.MassUsage, this.MassCapacity, "TransportersMassUsageTooltip".Translate(), this.lastMassFlashTime, true); + CaravanUIUtility.DrawDaysWorthOfFoodInfo(new Rect(rect2.x, (float)(rect2.y + 19.0), rect2.width, rect2.height), this.DaysWorthOfFood.First, this.DaysWorthOfFood.Second, this.EnvironmentAllowsEatingVirtualPlantsNow, true, 3.40282347E+38f); + this.DoBottomButtons(rect3); + Rect inRect2 = rect3; inRect2.yMax -= 59f; bool flag = false; - Dialog_LoadTransporters.Tab tab = this.tab; - if (tab != Dialog_LoadTransporters.Tab.Pawns) + switch (this.tab) { - if (tab == Dialog_LoadTransporters.Tab.Items) - { - this.itemsTransfer.OnGUI(inRect2, out flag); - } - } - else + case Tab.Pawns: { this.pawnsTransfer.OnGUI(inRect2, out flag); + break; + } + case Tab.Items: + { + this.itemsTransfer.OnGUI(inRect2, out flag); + break; + } } if (flag) { @@ -205,7 +203,7 @@ public override bool CausesMessageBackground() private void AddToTransferables(Thing t) { - TransferableOneWay transferableOneWay = TransferableUtility.TransferableMatching(t, this.transferables); + TransferableOneWay transferableOneWay = TransferableUtility.TransferableMatching(t, this.transferables); if (transferableOneWay == null) { transferableOneWay = new TransferableOneWay(); @@ -216,19 +214,38 @@ private void AddToTransferables(Thing t) private void DoBottomButtons(Rect rect) { - Rect rect2 = new Rect(rect.width / 2f - this.BottomButtonSize.x / 2f, rect.height - 55f, this.BottomButtonSize.x, this.BottomButtonSize.y); + double num = rect.width / 2.0; + Vector2 bottomButtonSize = this.BottomButtonSize; + double x = num - bottomButtonSize.x / 2.0; + double y = rect.height - 55.0; + Vector2 bottomButtonSize2 = this.BottomButtonSize; + float x2 = bottomButtonSize2.x; + Vector2 bottomButtonSize3 = this.BottomButtonSize; + Rect rect2 = new Rect((float)x, (float)y, x2, bottomButtonSize3.y); if (Widgets.ButtonText(rect2, "AcceptButton".Translate(), true, false, true) && this.TryAccept()) { SoundDefOf.TickHigh.PlayOneShotOnCamera(null); this.Close(false); } - Rect rect3 = new Rect(rect2.x - 10f - this.BottomButtonSize.x, rect2.y, this.BottomButtonSize.x, this.BottomButtonSize.y); + double num2 = rect2.x - 10.0; + Vector2 bottomButtonSize4 = this.BottomButtonSize; + double x3 = num2 - bottomButtonSize4.x; + float y2 = rect2.y; + Vector2 bottomButtonSize5 = this.BottomButtonSize; + float x4 = bottomButtonSize5.x; + Vector2 bottomButtonSize6 = this.BottomButtonSize; + Rect rect3 = new Rect((float)x3, y2, x4, bottomButtonSize6.y); if (Widgets.ButtonText(rect3, "ResetButton".Translate(), true, false, true)) { SoundDefOf.TickLow.PlayOneShotOnCamera(null); this.CalculateAndRecacheTransferables(); } - Rect rect4 = new Rect(rect2.xMax + 10f, rect2.y, this.BottomButtonSize.x, this.BottomButtonSize.y); + double x5 = rect2.xMax + 10.0; + float y3 = rect2.y; + Vector2 bottomButtonSize7 = this.BottomButtonSize; + float x6 = bottomButtonSize7.x; + Vector2 bottomButtonSize8 = this.BottomButtonSize; + Rect rect4 = new Rect((float)x5, y3, x6, bottomButtonSize8.y); if (Widgets.ButtonText(rect4, "CancelButton".Translate(), true, false, true)) { this.Close(true); @@ -236,14 +253,15 @@ private void DoBottomButtons(Rect rect) if (Prefs.DevMode) { float width = 200f; - float num = this.BottomButtonSize.y / 2f; - Rect rect5 = new Rect(0f, rect.height - 55f, width, num); + Vector2 bottomButtonSize9 = this.BottomButtonSize; + float num3 = (float)(bottomButtonSize9.y / 2.0); + Rect rect5 = new Rect(0f, (float)(rect.height - 55.0), width, num3); if (Widgets.ButtonText(rect5, "Dev: Load instantly", true, false, true) && this.DebugTryLoadInstantly()) { SoundDefOf.TickHigh.PlayOneShotOnCamera(null); this.Close(false); } - Rect rect6 = new Rect(0f, rect.height - 55f + num, width, num); + Rect rect6 = new Rect(0f, (float)(rect.height - 55.0 + num3), width, num3); if (Widgets.ButtonText(rect6, "Dev: Select everything", true, false, true)) { SoundDefOf.TickHigh.PlayOneShotOnCamera(null); @@ -257,11 +275,11 @@ private void CalculateAndRecacheTransferables() this.transferables = new List(); this.AddPawnsToTransferables(); this.AddItemsToTransferables(); - this.pawnsTransfer = new TransferableOneWayWidget(null, Faction.OfPlayer.Name, this.TransportersLabelCap, "FormCaravanColonyThingCountTip".Translate(), true, IgnorePawnsInventoryMode.IgnoreIfAssignedToUnload, true, () => this.MassCapacity - this.MassUsage, 24f, false, true, -1); + this.pawnsTransfer = new TransferableOneWayWidget(null, Faction.OfPlayer.Name, this.TransportersLabelCap, "FormCaravanColonyThingCountTip".Translate(), true, IgnorePawnsInventoryMode.IgnoreIfAssignedToUnload, true, (Func)(() => this.MassCapacity - this.MassUsage), 24f, false, true, -1); CaravanUIUtility.AddPawnsSections(this.pawnsTransfer, this.transferables); this.itemsTransfer = new TransferableOneWayWidget(from x in this.transferables where x.ThingDef.category != ThingCategory.Pawn - select x, Faction.OfPlayer.Name, this.TransportersLabelCap, "FormCaravanColonyThingCountTip".Translate(), true, IgnorePawnsInventoryMode.IgnoreIfAssignedToUnload, true, () => this.MassCapacity - this.MassUsage, 24f, false, true, this.map.Tile); + select x, Faction.OfPlayer.Name, this.TransportersLabelCap, "FormCaravanColonyThingCountTip".Translate(), true, IgnorePawnsInventoryMode.IgnoreIfAssignedToUnload, true, (Func)(() => this.MassCapacity - this.MassUsage), 24f, false, true, this.map.Tile); this.CountToTransferChanged(); } @@ -271,7 +289,7 @@ private bool DebugTryLoadInstantly() int i; for (i = 0; i < this.transferables.Count; i++) { - TransferableUtility.Transfer(this.transferables[i].things, this.transferables[i].CountToTransfer, delegate(Thing splitPiece, IThingHolder originalThing) + TransferableUtility.Transfer(this.transferables[i].things, this.transferables[i].CountToTransfer, (Action)delegate(Thing splitPiece, IThingHolder originalThing) { this.transporters[i % this.transporters.Count].GetDirectlyHeldThings().TryAdd(splitPiece, true); }); @@ -291,42 +309,39 @@ private bool TryAccept() IEnumerable enumerable = from x in pawnsFromTransferables where x.IsColonist && !x.Downed select x; - if (enumerable.Any()) + if (enumerable.Any()) { - foreach (Pawn current in enumerable) + foreach (Pawn item in enumerable) { - Lord lord = current.GetLord(); + Lord lord = item.GetLord(); if (lord != null) { - lord.Notify_PawnLost(current, PawnLostCondition.ForcedToJoinOtherLord); + lord.Notify_PawnLost(item, PawnLostCondition.ForcedToJoinOtherLord); } } LordMaker.MakeNewLord(Faction.OfPlayer, new LordJob_LoadAndEnterTransporters(transportersGroup), this.map, enumerable); - foreach (Pawn current2 in enumerable) + foreach (Pawn item2 in enumerable) { - if (current2.Spawned) + if (item2.Spawned) { - current2.jobs.EndCurrentJob(JobCondition.InterruptForced, true); + item2.jobs.EndCurrentJob(JobCondition.InterruptForced, true); } } } - Messages.Message("MessageTransportersLoadingProcessStarted".Translate(), this.transporters[0].parent, MessageSound.Benefit); + Messages.Message("MessageTransportersLoadingProcessStarted".Translate(), (Thing)this.transporters[0].parent, MessageSound.Benefit); return true; } private void AssignTransferablesToRandomTransporters() { - TransferableOneWay transferableOneWay = this.transferables.MaxBy((TransferableOneWay x) => x.CountToTransfer); + TransferableOneWay transferableOneWay = this.transferables.MaxBy((Func)((TransferableOneWay x) => x.CountToTransfer)); int num = 0; for (int i = 0; i < this.transferables.Count; i++) { - if (this.transferables[i] != transferableOneWay) + if (this.transferables[i] != transferableOneWay && this.transferables[i].CountToTransfer > 0) { - if (this.transferables[i].CountToTransfer > 0) - { - this.transporters[num % this.transporters.Count].AddToTheToLoadList(this.transferables[i], this.transferables[i].CountToTransfer); - num++; - } + this.transporters[num % this.transporters.Count].AddToTheToLoadList(this.transferables[i], this.transferables[i].CountToTransfer); + num++; } } if (num < this.transporters.Count) @@ -361,7 +376,7 @@ private int CreateAndAssignNewTransportersGroup() private bool CheckForErrors(List pawns) { - if (!this.transferables.Any((TransferableOneWay x) => x.CountToTransfer != 0)) + if (!this.transferables.Any((Predicate)((TransferableOneWay x) => x.CountToTransfer != 0))) { Messages.Message("CantSendEmptyTransportPods".Translate(), MessageSound.RejectInput); return false; @@ -372,13 +387,10 @@ private bool CheckForErrors(List pawns) Messages.Message("TooBigTransportersMassUsage".Translate(), MessageSound.RejectInput); return false; } - Pawn pawn = pawns.Find((Pawn x) => !x.MapHeld.reachability.CanReach(x.PositionHeld, this.transporters[0].parent, PathEndMode.Touch, TraverseParms.For(TraverseMode.PassDoors, Danger.Deadly, false))); + Pawn pawn = pawns.Find((Predicate)((Pawn x) => !x.MapHeld.reachability.CanReach(x.PositionHeld, (Thing)this.transporters[0].parent, PathEndMode.Touch, TraverseParms.For(TraverseMode.PassDoors, Danger.Deadly, false)))); if (pawn != null) { - Messages.Message("PawnCantReachTransporters".Translate(new object[] - { - pawn.LabelShort - }).CapitalizeFirst(), MessageSound.RejectInput); + Messages.Message("PawnCantReachTransporters".Translate(pawn.LabelShort).CapitalizeFirst(), MessageSound.RejectInput); return false; } Map map = this.transporters[0].parent.Map; @@ -393,31 +405,22 @@ private bool CheckForErrors(List pawns) for (int j = 0; j < this.transferables[i].things.Count; j++) { Thing thing = this.transferables[i].things[j]; - if (map.reachability.CanReach(thing.Position, this.transporters[0].parent, PathEndMode.Touch, TraverseParms.For(TraverseMode.PassDoors, Danger.Deadly, false))) + if (map.reachability.CanReach(thing.Position, (Thing)this.transporters[0].parent, PathEndMode.Touch, TraverseParms.For(TraverseMode.PassDoors, Danger.Deadly, false))) { num += thing.stackCount; if (num >= countToTransfer) - { break; - } } } if (num < countToTransfer) { if (countToTransfer == 1) { - Messages.Message("TransporterItemIsUnreachableSingle".Translate(new object[] - { - this.transferables[i].ThingDef.label - }), MessageSound.RejectInput); + Messages.Message("TransporterItemIsUnreachableSingle".Translate(this.transferables[i].ThingDef.label), MessageSound.RejectInput); } else { - Messages.Message("TransporterItemIsUnreachableMulti".Translate(new object[] - { - countToTransfer, - this.transferables[i].ThingDef.label - }), MessageSound.RejectInput); + Messages.Message("TransporterItemIsUnreachableMulti".Translate(countToTransfer, this.transferables[i].ThingDef.label), MessageSound.RejectInput); } return false; } diff --git a/Assembly-CSharp/RimWorld/Dialog_ManageAreas.cs b/Assembly-CSharp/RimWorld/Dialog_ManageAreas.cs index 46605adcc..733869b8b 100644 --- a/Assembly-CSharp/RimWorld/Dialog_ManageAreas.cs +++ b/Assembly-CSharp/RimWorld/Dialog_ManageAreas.cs @@ -1,4 +1,3 @@ -using System; using System.Collections.Generic; using System.Text.RegularExpressions; using UnityEngine; @@ -23,12 +22,12 @@ public override Vector2 InitialSize public Dialog_ManageAreas(Map map) { this.map = map; - this.forcePause = true; - this.doCloseX = true; - this.closeOnEscapeKey = true; - this.doCloseButton = true; - this.closeOnClickedOutside = true; - this.absorbInputAroundWindow = true; + base.forcePause = true; + base.doCloseX = true; + base.closeOnEscapeKey = true; + base.doCloseButton = true; + base.closeOnClickedOutside = true; + base.absorbInputAroundWindow = true; } public override void DoWindowContents(Rect inRect) @@ -46,15 +45,15 @@ public override void DoWindowContents(Rect inRect) listing_Standard.Gap(6f); } } - listing_Standard.ColumnWidth = inRect.width / 2f; - if (this.map.areaManager.CanMakeNewAllowed(AllowedAreaMode.Humanlike) && listing_Standard.ButtonText("NewArea".Translate(), null)) + listing_Standard.ColumnWidth = (float)(inRect.width / 2.0); + if (this.map.areaManager.CanMakeNewAllowed(AllowedAreaMode.Humanlike) && listing_Standard.ButtonText("NewArea".Translate(), (string)null)) { - Area_Allowed area_Allowed; + Area_Allowed area_Allowed = default(Area_Allowed); this.map.areaManager.TryMakeNewAllowed(AllowedAreaMode.Humanlike, out area_Allowed); } - if (this.map.areaManager.CanMakeNewAllowed(AllowedAreaMode.Animal) && listing_Standard.ButtonText("NewAreaAnimal".Translate(), null)) + if (this.map.areaManager.CanMakeNewAllowed(AllowedAreaMode.Animal) && listing_Standard.ButtonText("NewAreaAnimal".Translate(), (string)null)) { - Area_Allowed area_Allowed2; + Area_Allowed area_Allowed2 = default(Area_Allowed); this.map.areaManager.TryMakeNewAllowed(AllowedAreaMode.Animal, out area_Allowed2); } listing_Standard.End(); @@ -71,18 +70,18 @@ private static void DoAreaRow(Rect rect, Area area) } GUI.BeginGroup(rect); WidgetRow widgetRow = new WidgetRow(0f, 0f, UIDirection.RightThenUp, 99999f, 4f); - widgetRow.Icon(area.ColorTexture, null); + widgetRow.Icon(area.ColorTexture, (string)null); widgetRow.Gap(4f); widgetRow.Label(area.Label, 220f); - if (widgetRow.ButtonText("Rename".Translate(), null, true, false)) + if (widgetRow.ButtonText("Rename".Translate(), (string)null, true, false)) { Find.WindowStack.Add(new Dialog_RenameArea(area)); } - if (widgetRow.ButtonText("InvertArea".Translate(), null, true, false)) + if (widgetRow.ButtonText("InvertArea".Translate(), (string)null, true, false)) { area.Invert(); } - if (widgetRow.ButtonIcon(TexButton.DeleteX, null)) + if (widgetRow.ButtonIcon(TexButton.DeleteX, (string)null)) { area.Delete(); } diff --git a/Assembly-CSharp/RimWorld/Dialog_ManageDrugPolicies.cs b/Assembly-CSharp/RimWorld/Dialog_ManageDrugPolicies.cs index e8c21bf05..60cac1de5 100644 --- a/Assembly-CSharp/RimWorld/Dialog_ManageDrugPolicies.cs +++ b/Assembly-CSharp/RimWorld/Dialog_ManageDrugPolicies.cs @@ -62,12 +62,12 @@ public override Vector2 InitialSize public Dialog_ManageDrugPolicies(DrugPolicy selectedAssignedDrugs) { - this.forcePause = true; - this.doCloseX = true; - this.closeOnEscapeKey = true; - this.doCloseButton = true; - this.closeOnClickedOutside = true; - this.absorbInputAroundWindow = true; + base.forcePause = true; + base.doCloseX = true; + base.closeOnEscapeKey = true; + base.doCloseButton = true; + base.closeOnClickedOutside = true; + base.absorbInputAroundWindow = true; this.SelectedPolicy = selectedAssignedDrugs; } @@ -83,52 +83,73 @@ public override void DoWindowContents(Rect inRect) { float num = 0f; Rect rect = new Rect(0f, 0f, 150f, 35f); - num += 150f; + num = (float)(num + 150.0); if (Widgets.ButtonText(rect, "SelectDrugPolicy".Translate(), true, false, true)) { List list = new List(); - foreach (DrugPolicy current in Current.Game.drugPolicyDatabase.AllPolicies) + List.Enumerator enumerator = Current.Game.drugPolicyDatabase.AllPolicies.GetEnumerator(); + try { - DrugPolicy localAssignedDrugs = current; - list.Add(new FloatMenuOption(localAssignedDrugs.label, delegate + while (enumerator.MoveNext()) { - this.SelectedPolicy = localAssignedDrugs; - }, MenuOptionPriority.Default, null, null, 0f, null, null)); + DrugPolicy current = enumerator.Current; + DrugPolicy localAssignedDrugs = current; + list.Add(new FloatMenuOption(localAssignedDrugs.label, (Action)delegate + { + this.SelectedPolicy = localAssignedDrugs; + }, MenuOptionPriority.Default, null, null, 0f, null, null)); + } + } + finally + { + ((IDisposable)(object)enumerator).Dispose(); } Find.WindowStack.Add(new FloatMenu(list)); } - num += 10f; + num = (float)(num + 10.0); Rect rect2 = new Rect(num, 0f, 150f, 35f); - num += 150f; + num = (float)(num + 150.0); if (Widgets.ButtonText(rect2, "NewDrugPolicy".Translate(), true, false, true)) { this.SelectedPolicy = Current.Game.drugPolicyDatabase.MakeNewDrugPolicy(); } - num += 10f; + num = (float)(num + 10.0); Rect rect3 = new Rect(num, 0f, 150f, 35f); - num += 150f; + num = (float)(num + 150.0); if (Widgets.ButtonText(rect3, "DeleteDrugPolicy".Translate(), true, false, true)) { List list2 = new List(); - foreach (DrugPolicy current2 in Current.Game.drugPolicyDatabase.AllPolicies) + List.Enumerator enumerator2 = Current.Game.drugPolicyDatabase.AllPolicies.GetEnumerator(); + try { - DrugPolicy localAssignedDrugs = current2; - list2.Add(new FloatMenuOption(localAssignedDrugs.label, delegate + while (enumerator2.MoveNext()) { - AcceptanceReport acceptanceReport = Current.Game.drugPolicyDatabase.TryDelete(localAssignedDrugs); - if (!acceptanceReport.Accepted) + DrugPolicy current2 = enumerator2.Current; + DrugPolicy localAssignedDrugs2 = current2; + list2.Add(new FloatMenuOption(localAssignedDrugs2.label, (Action)delegate { - Messages.Message(acceptanceReport.Reason, MessageSound.RejectInput); - } - else if (localAssignedDrugs == this.SelectedPolicy) - { - this.SelectedPolicy = null; - } - }, MenuOptionPriority.Default, null, null, 0f, null, null)); + AcceptanceReport acceptanceReport = Current.Game.drugPolicyDatabase.TryDelete(localAssignedDrugs2); + if (!acceptanceReport.Accepted) + { + Messages.Message(acceptanceReport.Reason, MessageSound.RejectInput); + } + else if (localAssignedDrugs2 == this.SelectedPolicy) + { + this.SelectedPolicy = null; + } + }, MenuOptionPriority.Default, null, null, 0f, null, null)); + } + } + finally + { + ((IDisposable)(object)enumerator2).Dispose(); } Find.WindowStack.Add(new FloatMenu(list2)); } - Rect rect4 = new Rect(0f, 40f, inRect.width, inRect.height - 40f - this.CloseButSize.y).ContractedBy(10f); + float width = inRect.width; + double num2 = inRect.height - 40.0; + Vector2 closeButSize = base.CloseButSize; + Rect rect4 = new Rect(0f, 40f, width, (float)(num2 - closeButSize.y)).ContractedBy(10f); if (this.SelectedPolicy == null) { GUI.color = Color.grey; @@ -136,14 +157,16 @@ public override void DoWindowContents(Rect inRect) Widgets.Label(rect4, "NoDrugPolicySelected".Translate()); Text.Anchor = TextAnchor.UpperLeft; GUI.color = Color.white; - return; } - GUI.BeginGroup(rect4); - Rect rect5 = new Rect(0f, 0f, 200f, 30f); - Dialog_ManageDrugPolicies.DoNameInputRect(rect5, ref this.SelectedPolicy.label); - Rect rect6 = new Rect(0f, 40f, rect4.width, rect4.height - 45f - 10f); - this.DoPolicyConfigArea(rect6); - GUI.EndGroup(); + else + { + GUI.BeginGroup(rect4); + Rect rect5 = new Rect(0f, 0f, 200f, 30f); + Dialog_ManageDrugPolicies.DoNameInputRect(rect5, ref this.SelectedPolicy.label); + Rect rect6 = new Rect(0f, 40f, rect4.width, (float)(rect4.height - 45.0 - 10.0)); + this.DoPolicyConfigArea(rect6); + GUI.EndGroup(); + } } public override void PreClose() @@ -165,7 +188,7 @@ private void DoPolicyConfigArea(Rect rect) rect3.yMin = rect2.yMax; rect3.height -= 50f; Rect rect4 = rect; - rect4.yMin = rect4.yMax - 50f; + rect4.yMin = (float)(rect4.yMax - 50.0); this.DoColumnLabels(rect2); Widgets.DrawMenuSection(rect3, true); if (this.SelectedPolicy.Count == 0) @@ -178,13 +201,13 @@ private void DoPolicyConfigArea(Rect rect) } else { - float height = (float)this.SelectedPolicy.Count * 35f; - Rect viewRect = new Rect(0f, 0f, rect3.width - 16f, height); + float height = (float)((float)this.SelectedPolicy.Count * 35.0); + Rect viewRect = new Rect(0f, 0f, (float)(rect3.width - 16.0), height); Widgets.BeginScrollView(rect3, ref this.scrollPosition, viewRect, true); DrugPolicy selectedPolicy = this.SelectedPolicy; for (int i = 0; i < selectedPolicy.Count; i++) { - Rect rect5 = new Rect(0f, (float)i * 35f, viewRect.width, 35f); + Rect rect5 = new Rect(0f, (float)((float)i * 35.0), viewRect.width, 35f); this.DoEntryRow(rect5, selectedPolicy[i]); } Widgets.EndScrollView(); @@ -193,127 +216,113 @@ private void DoPolicyConfigArea(Rect rect) private void CalculateColumnsWidths(Rect rect, out float addictionWidth, out float allowJoyWidth, out float scheduledWidth, out float drugNameWidth, out float frequencyWidth, out float moodThresholdWidth, out float joyThresholdWidth, out float takeToInventoryWidth) { - float num = rect.width - 108f; - drugNameWidth = num * 0.2f; + float num = (float)(rect.width - 108.0); + drugNameWidth = (float)(num * 0.20000000298023224); addictionWidth = 36f; allowJoyWidth = 36f; scheduledWidth = 36f; - frequencyWidth = num * 0.35f; - moodThresholdWidth = num * 0.15f; - joyThresholdWidth = num * 0.15f; - takeToInventoryWidth = num * 0.15f; + frequencyWidth = (float)(num * 0.34999999403953552); + moodThresholdWidth = (float)(num * 0.15000000596046448); + joyThresholdWidth = (float)(num * 0.15000000596046448); + takeToInventoryWidth = (float)(num * 0.15000000596046448); } private void DoColumnLabels(Rect rect) { rect.width -= 16f; - float num; - float num2; - float num3; - float num4; - float num5; - float num6; - float num7; - float num8; + float num = default(float); + float num2 = default(float); + float num3 = default(float); + float num4 = default(float); + float num5 = default(float); + float num6 = default(float); + float num7 = default(float); + float num8 = default(float); this.CalculateColumnsWidths(rect, out num, out num2, out num3, out num4, out num5, out num6, out num7, out num8); - float num9 = rect.x; + float x = rect.x; Text.Anchor = TextAnchor.LowerCenter; - Rect rect2 = new Rect(num9 + 4f, rect.y, num4, rect.height); + Rect rect2 = new Rect((float)(x + 4.0), rect.y, num4, rect.height); Widgets.Label(rect2, "DrugColumnLabel".Translate()); TooltipHandler.TipRegion(rect2, "DrugNameColumnDesc".Translate()); - num9 += num4; + x += num4; Text.Anchor = TextAnchor.UpperCenter; - Rect rect3 = new Rect(num9, rect.y, num2 + num2, rect.height / 2f); + Rect rect3 = new Rect(x, rect.y, num2 + num2, (float)(rect.height / 2.0)); Widgets.Label(rect3, "DrugUsageColumnLabel".Translate()); TooltipHandler.TipRegion(rect3, "DrugUsageColumnDesc".Translate()); - Rect rect4 = new Rect(num9, rect.yMax - 24f, 24f, 24f); + Rect rect4 = new Rect(x, (float)(rect.yMax - 24.0), 24f, 24f); GUI.DrawTexture(rect4, Dialog_ManageDrugPolicies.IconForAddiction); TooltipHandler.TipRegion(rect4, "DrugUsageTipForAddiction".Translate()); - num9 += num; - Rect rect5 = new Rect(num9, rect.yMax - 24f, 24f, 24f); + x += num; + Rect rect5 = new Rect(x, (float)(rect.yMax - 24.0), 24f, 24f); GUI.DrawTexture(rect5, Dialog_ManageDrugPolicies.IconForJoy); TooltipHandler.TipRegion(rect5, "DrugUsageTipForJoy".Translate()); - num9 += num2; - Rect rect6 = new Rect(num9, rect.yMax - 24f, 24f, 24f); + x += num2; + Rect rect6 = new Rect(x, (float)(rect.yMax - 24.0), 24f, 24f); GUI.DrawTexture(rect6, Dialog_ManageDrugPolicies.IconScheduled); TooltipHandler.TipRegion(rect6, "DrugUsageTipScheduled".Translate()); - num9 += num3; + x += num3; Text.Anchor = TextAnchor.LowerCenter; - Rect rect7 = new Rect(num9, rect.y, num5, rect.height); + Rect rect7 = new Rect(x, rect.y, num5, rect.height); Widgets.Label(rect7, "FrequencyColumnLabel".Translate()); TooltipHandler.TipRegion(rect7, "FrequencyColumnDesc".Translate()); - num9 += num5; - Rect rect8 = new Rect(num9, rect.y, num6, rect.height); + x += num5; + Rect rect8 = new Rect(x, rect.y, num6, rect.height); Widgets.Label(rect8, "MoodThresholdColumnLabel".Translate()); TooltipHandler.TipRegion(rect8, "MoodThresholdColumnDesc".Translate()); - num9 += num6; - Rect rect9 = new Rect(num9, rect.y, num7, rect.height); + x += num6; + Rect rect9 = new Rect(x, rect.y, num7, rect.height); Widgets.Label(rect9, "JoyThresholdColumnLabel".Translate()); TooltipHandler.TipRegion(rect9, "JoyThresholdColumnDesc".Translate()); - num9 += num7; - Rect rect10 = new Rect(num9, rect.y, num8, rect.height); + x += num7; + Rect rect10 = new Rect(x, rect.y, num8, rect.height); Widgets.Label(rect10, "TakeToInventoryColumnLabel".Translate()); TooltipHandler.TipRegion(rect10, "TakeToInventoryColumnDesc".Translate()); - num9 += num8; + x += num8; Text.Anchor = TextAnchor.UpperLeft; } private void DoEntryRow(Rect rect, DrugPolicyEntry entry) { - float num; - float num2; - float num3; - float num4; - float num5; - float num6; - float num7; - float num8; + float num = default(float); + float num2 = default(float); + float num3 = default(float); + float num4 = default(float); + float num5 = default(float); + float num6 = default(float); + float num7 = default(float); + float num8 = default(float); this.CalculateColumnsWidths(rect, out num, out num2, out num3, out num4, out num5, out num6, out num7, out num8); Text.Anchor = TextAnchor.MiddleLeft; - float num9 = rect.x; - Widgets.Label(new Rect(num9, rect.y, num4, rect.height).ContractedBy(4f), entry.drug.LabelCap); - Widgets.InfoCardButton(num9 + Text.CalcSize(entry.drug.LabelCap).x + 5f, rect.y + (rect.height - 24f) / 2f, entry.drug); - num9 += num4; + float x = rect.x; + Widgets.Label(new Rect(x, rect.y, num4, rect.height).ContractedBy(4f), entry.drug.LabelCap); + float num9 = x; + Vector2 vector = Text.CalcSize(entry.drug.LabelCap); + Widgets.InfoCardButton((float)(num9 + vector.x + 5.0), (float)(rect.y + (rect.height - 24.0) / 2.0), entry.drug); + x += num4; if (entry.drug.IsAddictiveDrug) { - Widgets.Checkbox(num9, rect.y, ref entry.allowedForAddiction, 24f, false); + Widgets.Checkbox(x, rect.y, ref entry.allowedForAddiction, 24f, false); } - num9 += num; + x += num; if (entry.drug.IsPleasureDrug) { - Widgets.Checkbox(num9, rect.y, ref entry.allowedForJoy, 24f, false); + Widgets.Checkbox(x, rect.y, ref entry.allowedForJoy, 24f, false); } - num9 += num2; - Widgets.Checkbox(num9, rect.y, ref entry.allowScheduled, 24f, false); - num9 += num3; + x += num2; + Widgets.Checkbox(x, rect.y, ref entry.allowScheduled, 24f, false); + x += num3; if (entry.allowScheduled) { - entry.daysFrequency = Widgets.FrequencyHorizontalSlider(new Rect(num9, rect.y, num5, rect.height).ContractedBy(4f), entry.daysFrequency, 0.1f, 25f, true); - num9 += num5; - string label; - if (entry.onlyIfMoodBelow < 1f) - { - label = entry.onlyIfMoodBelow.ToStringPercent(); - } - else - { - label = "NoDrugUseRequirement".Translate(); - } - entry.onlyIfMoodBelow = Widgets.HorizontalSlider(new Rect(num9, rect.y, num6, rect.height).ContractedBy(4f), entry.onlyIfMoodBelow, 0.01f, 1f, true, label, null, null, -1f); - num9 += num6; - string label2; - if (entry.onlyIfJoyBelow < 1f) - { - label2 = entry.onlyIfJoyBelow.ToStringPercent(); - } - else - { - label2 = "NoDrugUseRequirement".Translate(); - } - entry.onlyIfJoyBelow = Widgets.HorizontalSlider(new Rect(num9, rect.y, num7, rect.height).ContractedBy(4f), entry.onlyIfJoyBelow, 0.01f, 1f, true, label2, null, null, -1f); - num9 += num7; - Widgets.TextFieldNumeric(new Rect(num9, rect.y, num8, rect.height).ContractedBy(4f), ref entry.takeToInventory, ref entry.takeToInventoryTempBuffer, 0f, 15f); - num9 += num8; + entry.daysFrequency = Widgets.FrequencyHorizontalSlider(new Rect(x, rect.y, num5, rect.height).ContractedBy(4f), entry.daysFrequency, 0.1f, 25f, true); + x += num5; + string label = (!(entry.onlyIfMoodBelow < 1.0)) ? "NoDrugUseRequirement".Translate() : entry.onlyIfMoodBelow.ToStringPercent(); + entry.onlyIfMoodBelow = Widgets.HorizontalSlider(new Rect(x, rect.y, num6, rect.height).ContractedBy(4f), entry.onlyIfMoodBelow, 0.01f, 1f, true, label, (string)null, (string)null, -1f); + x += num6; + string label2 = (!(entry.onlyIfJoyBelow < 1.0)) ? "NoDrugUseRequirement".Translate() : entry.onlyIfJoyBelow.ToStringPercent(); + entry.onlyIfJoyBelow = Widgets.HorizontalSlider(new Rect(x, rect.y, num7, rect.height).ContractedBy(4f), entry.onlyIfJoyBelow, 0.01f, 1f, true, label2, (string)null, (string)null, -1f); + x += num7; + Widgets.TextFieldNumeric(new Rect(x, rect.y, num8, rect.height).ContractedBy(4f), ref entry.takeToInventory, ref entry.takeToInventoryTempBuffer, 0f, 15f); + x += num8; } Text.Anchor = TextAnchor.UpperLeft; } diff --git a/Assembly-CSharp/RimWorld/Dialog_ManageOutfits.cs b/Assembly-CSharp/RimWorld/Dialog_ManageOutfits.cs index d202a0f99..bd22ebe13 100644 --- a/Assembly-CSharp/RimWorld/Dialog_ManageOutfits.cs +++ b/Assembly-CSharp/RimWorld/Dialog_ManageOutfits.cs @@ -1,6 +1,5 @@ using System; using System.Collections.Generic; -using System.Diagnostics; using UnityEngine; using Verse; @@ -43,12 +42,12 @@ public override Vector2 InitialSize public Dialog_ManageOutfits(Outfit selectedOutfit) { - this.forcePause = true; - this.doCloseX = true; - this.closeOnEscapeKey = true; - this.doCloseButton = true; - this.closeOnClickedOutside = true; - this.absorbInputAroundWindow = true; + base.forcePause = true; + base.doCloseX = true; + base.closeOnEscapeKey = true; + base.doCloseButton = true; + base.closeOnClickedOutside = true; + base.absorbInputAroundWindow = true; if (Dialog_ManageOutfits.apparelGlobalFilter == null) { Dialog_ManageOutfits.apparelGlobalFilter = new ThingFilter(); @@ -69,52 +68,73 @@ public override void DoWindowContents(Rect inRect) { float num = 0f; Rect rect = new Rect(0f, 0f, 150f, 35f); - num += 150f; + num = (float)(num + 150.0); if (Widgets.ButtonText(rect, "SelectOutfit".Translate(), true, false, true)) { List list = new List(); - foreach (Outfit current in Current.Game.outfitDatabase.AllOutfits) + List.Enumerator enumerator = Current.Game.outfitDatabase.AllOutfits.GetEnumerator(); + try { - Outfit localOut = current; - list.Add(new FloatMenuOption(localOut.label, delegate + while (enumerator.MoveNext()) { - this.SelectedOutfit = localOut; - }, MenuOptionPriority.Default, null, null, 0f, null, null)); + Outfit current = enumerator.Current; + Outfit localOut = current; + list.Add(new FloatMenuOption(localOut.label, (Action)delegate + { + this.SelectedOutfit = localOut; + }, MenuOptionPriority.Default, null, null, 0f, null, null)); + } + } + finally + { + ((IDisposable)(object)enumerator).Dispose(); } Find.WindowStack.Add(new FloatMenu(list)); } - num += 10f; + num = (float)(num + 10.0); Rect rect2 = new Rect(num, 0f, 150f, 35f); - num += 150f; + num = (float)(num + 150.0); if (Widgets.ButtonText(rect2, "NewOutfit".Translate(), true, false, true)) { this.SelectedOutfit = Current.Game.outfitDatabase.MakeNewOutfit(); } - num += 10f; + num = (float)(num + 10.0); Rect rect3 = new Rect(num, 0f, 150f, 35f); - num += 150f; + num = (float)(num + 150.0); if (Widgets.ButtonText(rect3, "DeleteOutfit".Translate(), true, false, true)) { List list2 = new List(); - foreach (Outfit current2 in Current.Game.outfitDatabase.AllOutfits) + List.Enumerator enumerator2 = Current.Game.outfitDatabase.AllOutfits.GetEnumerator(); + try { - Outfit localOut = current2; - list2.Add(new FloatMenuOption(localOut.label, delegate + while (enumerator2.MoveNext()) { - AcceptanceReport acceptanceReport = Current.Game.outfitDatabase.TryDelete(localOut); - if (!acceptanceReport.Accepted) - { - Messages.Message(acceptanceReport.Reason, MessageSound.RejectInput); - } - else if (localOut == this.SelectedOutfit) + Outfit current2 = enumerator2.Current; + Outfit localOut2 = current2; + list2.Add(new FloatMenuOption(localOut2.label, (Action)delegate { - this.SelectedOutfit = null; - } - }, MenuOptionPriority.Default, null, null, 0f, null, null)); + AcceptanceReport acceptanceReport = Current.Game.outfitDatabase.TryDelete(localOut2); + if (!acceptanceReport.Accepted) + { + Messages.Message(acceptanceReport.Reason, MessageSound.RejectInput); + } + else if (localOut2 == this.SelectedOutfit) + { + this.SelectedOutfit = null; + } + }, MenuOptionPriority.Default, null, null, 0f, null, null)); + } + } + finally + { + ((IDisposable)(object)enumerator2).Dispose(); } Find.WindowStack.Add(new FloatMenu(list2)); } - Rect rect4 = new Rect(0f, 40f, inRect.width, inRect.height - 40f - this.CloseButSize.y).ContractedBy(10f); + float width = inRect.width; + double num2 = inRect.height - 40.0; + Vector2 closeButSize = base.CloseButSize; + Rect rect4 = new Rect(0f, 40f, width, (float)(num2 - closeButSize.y)).ContractedBy(10f); if (this.SelectedOutfit == null) { GUI.color = Color.grey; @@ -122,24 +142,22 @@ public override void DoWindowContents(Rect inRect) Widgets.Label(rect4, "NoOutfitSelected".Translate()); Text.Anchor = TextAnchor.UpperLeft; GUI.color = Color.white; - return; } - GUI.BeginGroup(rect4); - Rect rect5 = new Rect(0f, 0f, 200f, 30f); - Dialog_ManageOutfits.DoNameInputRect(rect5, ref this.SelectedOutfit.label); - Rect rect6 = new Rect(0f, 40f, 300f, rect4.height - 45f - 10f); - IEnumerable forceHiddenFilters = this.HiddenSpecialThingFilters(); - ThingFilterUI.DoThingFilterConfigWindow(rect6, ref this.scrollPosition, this.SelectedOutfit.filter, Dialog_ManageOutfits.apparelGlobalFilter, 16, null, forceHiddenFilters, null); - GUI.EndGroup(); + else + { + GUI.BeginGroup(rect4); + Rect rect5 = new Rect(0f, 0f, 200f, 30f); + Dialog_ManageOutfits.DoNameInputRect(rect5, ref this.SelectedOutfit.label); + Rect rect6 = new Rect(0f, 40f, 300f, (float)(rect4.height - 45.0 - 10.0)); + IEnumerable forceHiddenFilters = this.HiddenSpecialThingFilters(); + ThingFilterUI.DoThingFilterConfigWindow(rect6, ref this.scrollPosition, this.SelectedOutfit.filter, Dialog_ManageOutfits.apparelGlobalFilter, 16, (IEnumerable)null, forceHiddenFilters, (List)null); + GUI.EndGroup(); + } } - [DebuggerHidden] private IEnumerable HiddenSpecialThingFilters() { - Dialog_ManageOutfits.c__Iterator195 c__Iterator = new Dialog_ManageOutfits.c__Iterator195(); - Dialog_ManageOutfits.c__Iterator195 expr_07 = c__Iterator; - expr_07.$PC = -2; - return expr_07; + yield return SpecialThingFilterDefOf.AllowNonDeadmansApparel; } public override void PreClose() diff --git a/Assembly-CSharp/RimWorld/Dialog_MedicalDefaults.cs b/Assembly-CSharp/RimWorld/Dialog_MedicalDefaults.cs index f1cf8db9b..ae7b3a29d 100644 --- a/Assembly-CSharp/RimWorld/Dialog_MedicalDefaults.cs +++ b/Assembly-CSharp/RimWorld/Dialog_MedicalDefaults.cs @@ -1,4 +1,3 @@ -using System; using UnityEngine; using Verse; @@ -22,12 +21,12 @@ public override Vector2 InitialSize public Dialog_MedicalDefaults() { - this.forcePause = true; - this.doCloseX = true; - this.closeOnEscapeKey = true; - this.doCloseButton = true; - this.closeOnClickedOutside = true; - this.absorbInputAroundWindow = true; + base.forcePause = true; + base.doCloseX = true; + base.closeOnEscapeKey = true; + base.doCloseButton = true; + base.closeOnClickedOutside = true; + base.absorbInputAroundWindow = true; } public override void DoWindowContents(Rect inRect) diff --git a/Assembly-CSharp/RimWorld/Dialog_ModSettings.cs b/Assembly-CSharp/RimWorld/Dialog_ModSettings.cs index d9dd7e01b..476c9dd43 100644 --- a/Assembly-CSharp/RimWorld/Dialog_ModSettings.cs +++ b/Assembly-CSharp/RimWorld/Dialog_ModSettings.cs @@ -26,12 +26,12 @@ public override Vector2 InitialSize public Dialog_ModSettings() { - this.forcePause = true; - this.doCloseX = true; - this.closeOnEscapeKey = true; - this.doCloseButton = true; - this.closeOnClickedOutside = true; - this.absorbInputAroundWindow = true; + base.forcePause = true; + base.doCloseX = true; + base.closeOnEscapeKey = true; + base.doCloseButton = true; + base.closeOnClickedOutside = true; + base.absorbInputAroundWindow = true; } public override void PreClose() @@ -51,15 +51,15 @@ public override void DoWindowContents(Rect inRect) if (Dialog_ModSettings.HasSettings()) { List list = new List(); - foreach (Mod current in from mod in LoadedModManager.ModHandles + foreach (Mod item in from mod in LoadedModManager.ModHandles where !mod.SettingsCategory().NullOrEmpty() orderby mod.SettingsCategory() select mod) { - Mod localMod = current; - if (!current.SettingsCategory().NullOrEmpty()) + Mod localMod = item; + if (!item.SettingsCategory().NullOrEmpty()) { - list.Add(new FloatMenuOption(current.SettingsCategory(), delegate + list.Add(new FloatMenuOption(item.SettingsCategory(), (Action)delegate { if (this.selMod != null) { @@ -81,9 +81,12 @@ orderby mod.SettingsCategory() if (this.selMod != null) { Text.Font = GameFont.Medium; - Widgets.Label(new Rect(167f, 0f, inRect.width - 150f - 17f, 35f), this.selMod.SettingsCategory()); + Widgets.Label(new Rect(167f, 0f, (float)(inRect.width - 150.0 - 17.0), 35f), this.selMod.SettingsCategory()); Text.Font = GameFont.Small; - Rect inRect2 = new Rect(0f, 40f, inRect.width, inRect.height - 40f - this.CloseButSize.y); + float width = inRect.width; + double num = inRect.height - 40.0; + Vector2 closeButSize = base.CloseButSize; + Rect inRect2 = new Rect(0f, 40f, width, (float)(num - closeButSize.y)); this.selMod.DoSettingsWindowContents(inRect2); } } @@ -92,7 +95,7 @@ public static bool HasSettings() { return (from mod in LoadedModManager.ModHandles where !mod.SettingsCategory().NullOrEmpty() - select mod).FirstOrDefault() != null; + select mod).FirstOrDefault() != null; } } } diff --git a/Assembly-CSharp/RimWorld/Dialog_NamePlayerFaction.cs b/Assembly-CSharp/RimWorld/Dialog_NamePlayerFaction.cs index 8514f9c63..329e06b64 100644 --- a/Assembly-CSharp/RimWorld/Dialog_NamePlayerFaction.cs +++ b/Assembly-CSharp/RimWorld/Dialog_NamePlayerFaction.cs @@ -6,10 +6,10 @@ public class Dialog_NamePlayerFaction : Dialog_GiveName { public Dialog_NamePlayerFaction() { - this.curName = NameGenerator.GenerateName(RulePackDefOf.NamerFactionPlayerRandomized, null, false); - this.nameMessageKey = "NamePlayerFactionMessage"; - this.gainedNameMessageKey = "PlayerFactionGainsName"; - this.invalidNameMessageKey = "PlayerFactionNameIsInvalid"; + base.curName = NameGenerator.GenerateName(RulePackDefOf.NamerFactionPlayerRandomized, (Predicate)null, false); + base.nameMessageKey = "NamePlayerFactionMessage"; + base.gainedNameMessageKey = "PlayerFactionGainsName"; + base.invalidNameMessageKey = "PlayerFactionNameIsInvalid"; } protected override bool IsValidName(string s) diff --git a/Assembly-CSharp/RimWorld/Dialog_NamePlayerFactionAndBase.cs b/Assembly-CSharp/RimWorld/Dialog_NamePlayerFactionAndBase.cs index 06fee6408..e722e98b9 100644 --- a/Assembly-CSharp/RimWorld/Dialog_NamePlayerFactionAndBase.cs +++ b/Assembly-CSharp/RimWorld/Dialog_NamePlayerFactionAndBase.cs @@ -11,18 +11,18 @@ public class Dialog_NamePlayerFactionAndBase : Dialog_GiveName public Dialog_NamePlayerFactionAndBase(FactionBase factionBase) { this.factionBase = factionBase; - if (factionBase.HasMap && factionBase.Map.mapPawns.FreeColonistsSpawnedCount != 0) + if ((factionBase.HasMap ? factionBase.Map.mapPawns.FreeColonistsSpawnedCount : 0) != 0) { - this.suggestingPawn = factionBase.Map.mapPawns.FreeColonistsSpawned.RandomElement(); + base.suggestingPawn = factionBase.Map.mapPawns.FreeColonistsSpawned.RandomElement(); } - this.curName = NameGenerator.GenerateName(RulePackDefOf.NamerFactionPlayerRandomized, null, false); - this.nameMessageKey = "NamePlayerFactionMessage"; - this.invalidNameMessageKey = "PlayerFactionNameIsInvalid"; - this.useSecondName = true; - this.curSecondName = NameGenerator.GenerateName(RulePackDefOf.NamerFactionBasePlayerRandomized, null, false); - this.secondNameMessageKey = "NamePlayerFactionBaseMessage_NameFactionContinuation"; - this.invalidSecondNameMessageKey = "PlayerFactionBaseNameIsInvalid"; - this.gainedNameMessageKey = "PlayerFactionAndBaseGainsName"; + base.curName = NameGenerator.GenerateName(RulePackDefOf.NamerFactionPlayerRandomized, (Predicate)null, false); + base.nameMessageKey = "NamePlayerFactionMessage"; + base.invalidNameMessageKey = "PlayerFactionNameIsInvalid"; + base.useSecondName = true; + base.curSecondName = NameGenerator.GenerateName(RulePackDefOf.NamerFactionBasePlayerRandomized, (Predicate)null, false); + base.secondNameMessageKey = "NamePlayerFactionBaseMessage_NameFactionContinuation"; + base.invalidSecondNameMessageKey = "PlayerFactionBaseNameIsInvalid"; + base.gainedNameMessageKey = "PlayerFactionAndBaseGainsName"; } public override void PostOpen() diff --git a/Assembly-CSharp/RimWorld/Dialog_NamePlayerFactionBase.cs b/Assembly-CSharp/RimWorld/Dialog_NamePlayerFactionBase.cs index 30678cdec..a9224572f 100644 --- a/Assembly-CSharp/RimWorld/Dialog_NamePlayerFactionBase.cs +++ b/Assembly-CSharp/RimWorld/Dialog_NamePlayerFactionBase.cs @@ -11,14 +11,14 @@ public class Dialog_NamePlayerFactionBase : Dialog_GiveName public Dialog_NamePlayerFactionBase(FactionBase factionBase) { this.factionBase = factionBase; - if (factionBase.HasMap && factionBase.Map.mapPawns.FreeColonistsSpawnedCount != 0) + if ((factionBase.HasMap ? factionBase.Map.mapPawns.FreeColonistsSpawnedCount : 0) != 0) { - this.suggestingPawn = factionBase.Map.mapPawns.FreeColonistsSpawned.RandomElement(); + base.suggestingPawn = factionBase.Map.mapPawns.FreeColonistsSpawned.RandomElement(); } - this.curName = NameGenerator.GenerateName(RulePackDefOf.NamerFactionBasePlayerRandomized, null, false); - this.nameMessageKey = "NamePlayerFactionBaseMessage"; - this.gainedNameMessageKey = "PlayerFactionBaseGainsName"; - this.invalidNameMessageKey = "PlayerFactionBaseNameIsInvalid"; + base.curName = NameGenerator.GenerateName(RulePackDefOf.NamerFactionBasePlayerRandomized, (Predicate)null, false); + base.nameMessageKey = "NamePlayerFactionBaseMessage"; + base.gainedNameMessageKey = "PlayerFactionBaseGainsName"; + base.invalidNameMessageKey = "PlayerFactionBaseNameIsInvalid"; } public override void PostOpen() diff --git a/Assembly-CSharp/RimWorld/Dialog_Negotiation.cs b/Assembly-CSharp/RimWorld/Dialog_Negotiation.cs index 66760615d..5af2b277a 100644 --- a/Assembly-CSharp/RimWorld/Dialog_Negotiation.cs +++ b/Assembly-CSharp/RimWorld/Dialog_Negotiation.cs @@ -1,4 +1,3 @@ -using System; using UnityEngine; using Verse; @@ -22,7 +21,7 @@ public override Vector2 InitialSize } } - public Dialog_Negotiation(Pawn negotiator, ICommunicable commTarget, DiaNode startNode, bool radioMode) : base(startNode, radioMode, false, null) + public Dialog_Negotiation(Pawn negotiator, ICommunicable commTarget, DiaNode startNode, bool radioMode) : base(startNode, radioMode, false, (string)null) { this.negotiator = negotiator; this.commTarget = commTarget; @@ -31,10 +30,10 @@ public Dialog_Negotiation(Pawn negotiator, ICommunicable commTarget, DiaNode sta public override void DoWindowContents(Rect inRect) { GUI.BeginGroup(inRect); - Rect rect = new Rect(0f, 0f, inRect.width / 2f, 70f); + Rect rect = new Rect(0f, 0f, (float)(inRect.width / 2.0), 70f); Rect rect2 = new Rect(0f, rect.yMax, rect.width, 60f); - Rect rect3 = new Rect(inRect.width / 2f, 0f, inRect.width / 2f, 70f); - Rect rect4 = new Rect(inRect.width / 2f, rect.yMax, rect.width, 60f); + Rect rect3 = new Rect((float)(inRect.width / 2.0), 0f, (float)(inRect.width / 2.0), 70f); + Rect rect4 = new Rect((float)(inRect.width / 2.0), rect.yMax, rect.width, 60f); Text.Font = GameFont.Medium; Widgets.Label(rect, this.negotiator.LabelCap); Text.Anchor = TextAnchor.UpperRight; @@ -42,10 +41,7 @@ public override void DoWindowContents(Rect inRect) Text.Anchor = TextAnchor.UpperLeft; Text.Font = GameFont.Small; GUI.color = new Color(1f, 1f, 1f, 0.7f); - Widgets.Label(rect2, "SocialSkillIs".Translate(new object[] - { - this.negotiator.skills.GetSkill(SkillDefOf.Social).Level - })); + Widgets.Label(rect2, "SocialSkillIs".Translate(this.negotiator.skills.GetSkill(SkillDefOf.Social).Level)); Text.Anchor = TextAnchor.UpperRight; Widgets.Label(rect4, this.commTarget.GetInfoText()); Text.Anchor = TextAnchor.UpperLeft; diff --git a/Assembly-CSharp/RimWorld/Dialog_Options.cs b/Assembly-CSharp/RimWorld/Dialog_Options.cs index 66c967906..d7be36df1 100644 --- a/Assembly-CSharp/RimWorld/Dialog_Options.cs +++ b/Assembly-CSharp/RimWorld/Dialog_Options.cs @@ -1,5 +1,4 @@ using System; -using System.Collections; using System.Collections.Generic; using System.Linq; using UnityEngine; @@ -12,7 +11,7 @@ public class Dialog_Options : Window { private const float SubOptionTabWidth = 40f; - private static readonly float[] UIScales = new float[] + private static readonly float[] UIScales = new float[9] { 1f, 1.25f, @@ -35,11 +34,11 @@ public override Vector2 InitialSize public Dialog_Options() { - this.closeOnEscapeKey = true; - this.doCloseButton = true; - this.doCloseX = true; - this.forcePause = true; - this.absorbInputAroundWindow = true; + base.closeOnEscapeKey = true; + base.doCloseButton = true; + base.doCloseX = true; + base.forcePause = true; + base.absorbInputAroundWindow = true; } public override void DoWindowContents(Rect inRect) @@ -47,7 +46,7 @@ public override void DoWindowContents(Rect inRect) Rect rect = inRect.AtZero(); rect.yMax -= 45f; Listing_Standard listing_Standard = new Listing_Standard(); - listing_Standard.ColumnWidth = (rect.width - 34f) / 3f; + listing_Standard.ColumnWidth = (float)((rect.width - 34.0) / 3.0); listing_Standard.Begin(rect); Text.Font = GameFont.Medium; listing_Standard.Label("Audiovisuals".Translate(), -1f); @@ -63,14 +62,14 @@ public override void DoWindowContents(Rect inRect) Find.WindowStack.Add(new Dialog_ResolutionPicker()); } bool customCursorEnabled = Prefs.CustomCursorEnabled; - listing_Standard.CheckboxLabeled("CustomCursor".Translate(), ref customCursorEnabled, null); + listing_Standard.CheckboxLabeled("CustomCursor".Translate(), ref customCursorEnabled, (string)null); Prefs.CustomCursorEnabled = customCursorEnabled; - bool fullScreen = Screen.fullScreen; - bool flag = fullScreen; - listing_Standard.CheckboxLabeled("Fullscreen".Translate(), ref fullScreen, null); - if (fullScreen != flag) + bool fullScreen; + bool flag = fullScreen = Screen.fullScreen; + listing_Standard.CheckboxLabeled("Fullscreen".Translate(), ref flag, (string)null); + if (flag != fullScreen) { - ResolutionUtility.SafeSetFullscreen(fullScreen); + ResolutionUtility.SafeSetFullscreen(flag); } listing_Standard.Label("UIScale".Translate(), -1f); float[] uIScales = Dialog_Options.UIScales; @@ -91,7 +90,7 @@ public override void DoWindowContents(Rect inRect) } listing_Standard.Gap(12f); bool hatsOnlyOnMap = Prefs.HatsOnlyOnMap; - listing_Standard.CheckboxLabeled("HatsShownOnlyOnMap".Translate(), ref hatsOnlyOnMap, null); + listing_Standard.CheckboxLabeled("HatsShownOnlyOnMap".Translate(), ref hatsOnlyOnMap, (string)null); if (hatsOnlyOnMap != Prefs.HatsOnlyOnMap) { PortraitsCache.Clear(); @@ -103,11 +102,11 @@ public override void DoWindowContents(Rect inRect) Text.Font = GameFont.Small; listing_Standard.Gap(12f); listing_Standard.Gap(12f); - if (listing_Standard.ButtonText("KeyboardConfig".Translate(), null)) + if (listing_Standard.ButtonText("KeyboardConfig".Translate(), (string)null)) { Find.WindowStack.Add(new Dialog_KeyBindings()); } - if (listing_Standard.ButtonText("ChooseLanguage".Translate(), null)) + if (listing_Standard.ButtonText("ChooseLanguage".Translate(), (string)null)) { if (Current.ProgramState == ProgramState.Playing) { @@ -116,10 +115,10 @@ public override void DoWindowContents(Rect inRect) else { List list = new List(); - foreach (LoadedLanguage current in LanguageDatabase.AllLoadedLanguages) + foreach (LoadedLanguage allLoadedLanguage in LanguageDatabase.AllLoadedLanguages) { - LoadedLanguage localLang = current; - list.Add(new FloatMenuOption(localLang.FriendlyNameNative, delegate + LoadedLanguage localLang = allLoadedLanguage; + list.Add(new FloatMenuOption(localLang.FriendlyNameNative, (Action)delegate { LanguageDatabase.SelectLanguage(localLang); }, MenuOptionPriority.Default, null, null, 0f, null, null)); @@ -127,41 +126,38 @@ public override void DoWindowContents(Rect inRect) Find.WindowStack.Add(new FloatMenu(list)); } } - if ((Application.platform == RuntimePlatform.WindowsPlayer || Application.platform == RuntimePlatform.WindowsEditor) && listing_Standard.ButtonText("OpenSaveGameDataFolder".Translate(), null)) + if ((Application.platform == RuntimePlatform.WindowsPlayer || Application.platform == RuntimePlatform.WindowsEditor) && listing_Standard.ButtonText("OpenSaveGameDataFolder".Translate(), (string)null)) { Application.OpenURL(GenFilePaths.SaveDataFolderPath); } bool adaptiveTrainingEnabled = Prefs.AdaptiveTrainingEnabled; - listing_Standard.CheckboxLabeled("LearningHelper".Translate(), ref adaptiveTrainingEnabled, null); + listing_Standard.CheckboxLabeled("LearningHelper".Translate(), ref adaptiveTrainingEnabled, (string)null); Prefs.AdaptiveTrainingEnabled = adaptiveTrainingEnabled; - if (listing_Standard.ButtonText("ResetAdaptiveTutor".Translate(), null)) + if (listing_Standard.ButtonText("ResetAdaptiveTutor".Translate(), (string)null)) { Messages.Message("AdaptiveTutorIsReset".Translate(), MessageSound.Benefit); PlayerKnowledgeDatabase.ResetPersistent(); } bool runInBackground = Prefs.RunInBackground; - listing_Standard.CheckboxLabeled("RunInBackground".Translate(), ref runInBackground, null); + listing_Standard.CheckboxLabeled("RunInBackground".Translate(), ref runInBackground, (string)null); Prefs.RunInBackground = runInBackground; bool edgeScreenScroll = Prefs.EdgeScreenScroll; - listing_Standard.CheckboxLabeled("EdgeScreenScroll".Translate(), ref edgeScreenScroll, null); + listing_Standard.CheckboxLabeled("EdgeScreenScroll".Translate(), ref edgeScreenScroll, (string)null); Prefs.EdgeScreenScroll = edgeScreenScroll; bool pauseOnLoad = Prefs.PauseOnLoad; - listing_Standard.CheckboxLabeled("PauseOnLoad".Translate(), ref pauseOnLoad, null); + listing_Standard.CheckboxLabeled("PauseOnLoad".Translate(), ref pauseOnLoad, (string)null); Prefs.PauseOnLoad = pauseOnLoad; bool pauseOnUrgentLetter = Prefs.PauseOnUrgentLetter; - listing_Standard.CheckboxLabeled("PauseOnUrgentLetter".Translate(), ref pauseOnUrgentLetter, null); + listing_Standard.CheckboxLabeled("PauseOnUrgentLetter".Translate(), ref pauseOnUrgentLetter, (string)null); Prefs.PauseOnUrgentLetter = pauseOnUrgentLetter; bool showRealtimeClock = Prefs.ShowRealtimeClock; - listing_Standard.CheckboxLabeled("ShowRealtimeClock".Translate(), ref showRealtimeClock, null); + listing_Standard.CheckboxLabeled("ShowRealtimeClock".Translate(), ref showRealtimeClock, (string)null); Prefs.ShowRealtimeClock = showRealtimeClock; bool plantWindSway = Prefs.PlantWindSway; - listing_Standard.CheckboxLabeled("PlantWindSway".Translate(), ref plantWindSway, null); + listing_Standard.CheckboxLabeled("PlantWindSway".Translate(), ref plantWindSway, (string)null); Prefs.PlantWindSway = plantWindSway; int maxNumberOfPlayerHomes = Prefs.MaxNumberOfPlayerHomes; - listing_Standard.Label("MaxNumberOfPlayerHomes".Translate(new object[] - { - maxNumberOfPlayerHomes - }), -1f); + listing_Standard.Label("MaxNumberOfPlayerHomes".Translate(maxNumberOfPlayerHomes), -1f); int num2 = Mathf.RoundToInt(listing_Standard.Slider((float)maxNumberOfPlayerHomes, 1f, 5f)); Prefs.MaxNumberOfPlayerHomes = num2; if (maxNumberOfPlayerHomes != num2 && num2 > 1) @@ -171,66 +167,59 @@ public override void DoWindowContents(Rect inRect) if (listing_Standard.ButtonTextLabeled("TemperatureMode".Translate(), Prefs.TemperatureMode.ToStringHuman())) { List list2 = new List(); - using (IEnumerator enumerator2 = Enum.GetValues(typeof(TemperatureDisplayMode)).GetEnumerator()) + foreach (byte value in Enum.GetValues(typeof(TemperatureDisplayMode))) { - while (enumerator2.MoveNext()) + TemperatureDisplayMode localTmode = (TemperatureDisplayMode)value; + list2.Add(new FloatMenuOption(((Enum)(object)localTmode).ToString(), (Action)delegate { - TemperatureDisplayMode localTmode2 = (TemperatureDisplayMode)((byte)enumerator2.Current); - TemperatureDisplayMode localTmode = localTmode2; - list2.Add(new FloatMenuOption(localTmode.ToString(), delegate - { - Prefs.TemperatureMode = localTmode; - }, MenuOptionPriority.Default, null, null, 0f, null, null)); - } + Prefs.TemperatureMode = localTmode; + }, MenuOptionPriority.Default, null, null, 0f, null, null)); } Find.WindowStack.Add(new FloatMenu(list2)); } float autosaveIntervalDays = Prefs.AutosaveIntervalDays; string text = "Days".Translate(); string text2 = "Day".Translate().ToLower(); - if (listing_Standard.ButtonTextLabeled("AutosaveInterval".Translate(), autosaveIntervalDays + " " + ((autosaveIntervalDays != 1f) ? text : text2))) + if (listing_Standard.ButtonTextLabeled("AutosaveInterval".Translate(), autosaveIntervalDays + " " + ((autosaveIntervalDays != 1.0) ? text : text2))) { List list3 = new List(); if (Prefs.DevMode) { - list3.Add(new FloatMenuOption("0.125 " + text + "(debug)", delegate + list3.Add(new FloatMenuOption("0.125 " + text + "(debug)", (Action)delegate { Prefs.AutosaveIntervalDays = 0.125f; }, MenuOptionPriority.Default, null, null, 0f, null, null)); - list3.Add(new FloatMenuOption("0.25 " + text + "(debug)", delegate + list3.Add(new FloatMenuOption("0.25 " + text + "(debug)", (Action)delegate { Prefs.AutosaveIntervalDays = 0.25f; }, MenuOptionPriority.Default, null, null, 0f, null, null)); } - list3.Add(new FloatMenuOption("0.5 " + text + string.Empty, delegate + list3.Add(new FloatMenuOption("0.5 " + text + string.Empty, (Action)delegate { Prefs.AutosaveIntervalDays = 0.5f; }, MenuOptionPriority.Default, null, null, 0f, null, null)); - list3.Add(new FloatMenuOption(1.ToString() + " " + text2, delegate + list3.Add(new FloatMenuOption(1.ToString() + " " + text2, (Action)delegate { Prefs.AutosaveIntervalDays = 1f; }, MenuOptionPriority.Default, null, null, 0f, null, null)); - list3.Add(new FloatMenuOption(3.ToString() + " " + text, delegate + list3.Add(new FloatMenuOption(3.ToString() + " " + text, (Action)delegate { Prefs.AutosaveIntervalDays = 3f; }, MenuOptionPriority.Default, null, null, 0f, null, null)); - list3.Add(new FloatMenuOption(7.ToString() + " " + text, delegate + list3.Add(new FloatMenuOption(7.ToString() + " " + text, (Action)delegate { Prefs.AutosaveIntervalDays = 7f; }, MenuOptionPriority.Default, null, null, 0f, null, null)); - list3.Add(new FloatMenuOption(14.ToString() + " " + text, delegate + list3.Add(new FloatMenuOption(14.ToString() + " " + text, (Action)delegate { Prefs.AutosaveIntervalDays = 14f; }, MenuOptionPriority.Default, null, null, 0f, null, null)); Find.WindowStack.Add(new FloatMenu(list3)); } - if (Current.ProgramState == ProgramState.Playing && Current.Game.Info.permadeathMode && Prefs.AutosaveIntervalDays > 1f) + if (Current.ProgramState == ProgramState.Playing && Current.Game.Info.permadeathMode && Prefs.AutosaveIntervalDays > 1.0) { GUI.color = Color.red; - listing_Standard.Label("MaxPermadeathAutosaveIntervalInfo".Translate(new object[] - { - 1f - }), -1f); + listing_Standard.Label("MaxPermadeathAutosaveIntervalInfo".Translate(1f), -1f); GUI.color = Color.white; } if (Current.ProgramState == ProgramState.Playing && listing_Standard.ButtonText("ChangeStoryteller".Translate(), "OptionsButton-ChooseStoryteller") && TutorSystem.AllowAction("ChooseStoryteller")) @@ -240,30 +229,26 @@ public override void DoWindowContents(Rect inRect) if (listing_Standard.ButtonTextLabeled("ShowAnimalNames".Translate(), Prefs.AnimalNameMode.ToStringHuman())) { List list4 = new List(); - using (IEnumerator enumerator3 = Enum.GetValues(typeof(AnimalNameDisplayMode)).GetEnumerator()) + foreach (byte value2 in Enum.GetValues(typeof(AnimalNameDisplayMode))) { - while (enumerator3.MoveNext()) + AnimalNameDisplayMode localMode = (AnimalNameDisplayMode)value2; + list4.Add(new FloatMenuOption(localMode.ToStringHuman(), (Action)delegate { - AnimalNameDisplayMode localMode2 = (AnimalNameDisplayMode)((byte)enumerator3.Current); - AnimalNameDisplayMode localMode = localMode2; - list4.Add(new FloatMenuOption(localMode.ToStringHuman(), delegate - { - Prefs.AnimalNameMode = localMode; - }, MenuOptionPriority.Default, null, null, 0f, null, null)); - } + Prefs.AnimalNameMode = localMode; + }, MenuOptionPriority.Default, null, null, 0f, null, null)); } Find.WindowStack.Add(new FloatMenu(list4)); } bool devMode = Prefs.DevMode; - listing_Standard.CheckboxLabeled("DevelopmentMode".Translate(), ref devMode, null); + listing_Standard.CheckboxLabeled("DevelopmentMode".Translate(), ref devMode, (string)null); Prefs.DevMode = devMode; if (Prefs.DevMode) { bool resetModsConfigOnCrash = Prefs.ResetModsConfigOnCrash; - listing_Standard.CheckboxLabeled("ResetModsConfigOnCrash".Translate(), ref resetModsConfigOnCrash, null); + listing_Standard.CheckboxLabeled("ResetModsConfigOnCrash".Translate(), ref resetModsConfigOnCrash, (string)null); Prefs.ResetModsConfigOnCrash = resetModsConfigOnCrash; bool logVerbose = Prefs.LogVerbose; - listing_Standard.CheckboxLabeled("LogVerbose".Translate(), ref logVerbose, null); + listing_Standard.CheckboxLabeled("LogVerbose".Translate(), ref logVerbose, (string)null); Prefs.LogVerbose = logVerbose; } listing_Standard.NewColumn(); @@ -272,48 +257,49 @@ public override void DoWindowContents(Rect inRect) Text.Font = GameFont.Small; listing_Standard.Gap(12f); listing_Standard.Gap(12f); - if (listing_Standard.ButtonText("ModSettings".Translate(), null)) + if (listing_Standard.ButtonText("ModSettings".Translate(), (string)null)) { Find.WindowStack.Add(new Dialog_ModSettings()); } listing_Standard.Label(string.Empty, -1f); listing_Standard.Label("NamesYouWantToSee".Translate(), -1f); - Prefs.PreferredNames.RemoveAll((string n) => n.NullOrEmpty()); + Prefs.PreferredNames.RemoveAll((Predicate)((string n) => n.NullOrEmpty())); for (int j = 0; j < Prefs.PreferredNames.Count; j++) { string name = Prefs.PreferredNames[j]; PawnBio pawnBio = (from b in SolidBioDatabase.allBios where b.name.ToString() == name - select b).FirstOrDefault(); + select b).FirstOrDefault(); if (pawnBio == null) { name += " [N]"; } else { - PawnBioType bioType = pawnBio.BioType; - if (bioType != PawnBioType.BackstoryInGame) + switch (pawnBio.BioType) { - if (bioType == PawnBioType.PirateKing) - { - name += " [PK]"; - } - } - else + case PawnBioType.BackstoryInGame: { name += " [B]"; + break; + } + case PawnBioType.PirateKing: + { + name += " [PK]"; + break; + } } } Rect rect2 = listing_Standard.GetRect(24f); Widgets.Label(rect2, name); - Rect butRect = new Rect(rect2.xMax - 24f, rect2.y, 24f, 24f); + Rect butRect = new Rect((float)(rect2.xMax - 24.0), rect2.y, 24f, 24f); if (Widgets.ButtonImage(butRect, TexButton.DeleteX)) { Prefs.PreferredNames.RemoveAt(j); SoundDefOf.TickLow.PlayOneShotOnCamera(null); } } - if (Prefs.PreferredNames.Count < 6 && listing_Standard.ButtonText("AddName".Translate() + "...", null)) + if (Prefs.PreferredNames.Count < 6 && listing_Standard.ButtonText("AddName".Translate() + "...", (string)null)) { Find.WindowStack.Add(new Dialog_AddPreferredName()); } diff --git a/Assembly-CSharp/RimWorld/Dialog_ResolutionPicker.cs b/Assembly-CSharp/RimWorld/Dialog_ResolutionPicker.cs index e33439cd2..0c675aeef 100644 --- a/Assembly-CSharp/RimWorld/Dialog_ResolutionPicker.cs +++ b/Assembly-CSharp/RimWorld/Dialog_ResolutionPicker.cs @@ -10,8 +10,8 @@ public class Dialog_ResolutionPicker : Dialog_OptionLister { public Dialog_ResolutionPicker() { - this.doCloseButton = true; - this.absorbInputAroundWindow = true; + base.doCloseButton = true; + base.absorbInputAroundWindow = true; } protected override void DoListingItems() @@ -19,7 +19,7 @@ protected override void DoListingItems() List list = (from r in Screen.resolutions where r.width >= 1024 && r.height >= 768 orderby r.width, r.height - select r).ToList(); + select r).ToList(); if (list.Count == 0) { for (int i = 0; i < 30; i++) @@ -31,21 +31,30 @@ protected override void DoListingItems() }); } } - foreach (Resolution current in list) + List.Enumerator enumerator = list.GetEnumerator(); + try { - if (this.listing.ButtonText(Dialog_Options.ResToString(current.width, current.height), null)) + while (enumerator.MoveNext()) { - if (!ResolutionUtility.UIScaleSafeWithResolution(Prefs.UIScale, current.width, current.height)) + Resolution current = enumerator.Current; + if (base.listing.ButtonText(Dialog_Options.ResToString(current.width, current.height), (string)null)) { - Messages.Message("MessageScreenResTooSmallForUIScale".Translate(), MessageSound.RejectInput); - } - else - { - Find.WindowStack.TryRemove(this, true); - ResolutionUtility.SafeSetResolution(current); + if (!ResolutionUtility.UIScaleSafeWithResolution(Prefs.UIScale, current.width, current.height)) + { + Messages.Message("MessageScreenResTooSmallForUIScale".Translate(), MessageSound.RejectInput); + } + else + { + Find.WindowStack.TryRemove(this, true); + ResolutionUtility.SafeSetResolution(current); + } } } } + finally + { + ((IDisposable)(object)enumerator).Dispose(); + } } } } diff --git a/Assembly-CSharp/RimWorld/Dialog_SaveFileList.cs b/Assembly-CSharp/RimWorld/Dialog_SaveFileList.cs index 2241b3c5c..58e2e950e 100644 --- a/Assembly-CSharp/RimWorld/Dialog_SaveFileList.cs +++ b/Assembly-CSharp/RimWorld/Dialog_SaveFileList.cs @@ -21,16 +21,16 @@ protected override Color FileNameColor(SaveFileInfo sfi) protected override void ReloadFiles() { - this.files.Clear(); - foreach (FileInfo current in GenFilePaths.AllSavedGameFiles) + base.files.Clear(); + foreach (FileInfo allSavedGameFile in GenFilePaths.AllSavedGameFiles) { try { - this.files.Add(new SaveFileInfo(current)); + base.files.Add(new SaveFileInfo(allSavedGameFile)); } catch (Exception ex) { - Log.Error("Exception loading " + current.Name + ": " + ex.ToString()); + Log.Error("Exception loading " + allSavedGameFile.Name + ": " + ex.ToString()); } } } diff --git a/Assembly-CSharp/RimWorld/Dialog_SaveFileList_Load.cs b/Assembly-CSharp/RimWorld/Dialog_SaveFileList_Load.cs index b693c7930..d3d5accdb 100644 --- a/Assembly-CSharp/RimWorld/Dialog_SaveFileList_Load.cs +++ b/Assembly-CSharp/RimWorld/Dialog_SaveFileList_Load.cs @@ -8,14 +8,14 @@ public class Dialog_SaveFileList_Load : Dialog_SaveFileList { public Dialog_SaveFileList_Load() { - this.interactButLabel = "LoadGameButton".Translate(); + base.interactButLabel = "LoadGameButton".Translate(); } protected override void DoFileInteraction(string saveFileName) { - PreLoadUtility.CheckVersionAndLoad(GenFilePaths.FilePathForSavedGame(saveFileName), ScribeMetaHeaderUtility.ScribeHeaderMode.Map, delegate + PreLoadUtility.CheckVersionAndLoad(GenFilePaths.FilePathForSavedGame(saveFileName), ScribeMetaHeaderUtility.ScribeHeaderMode.Map, (Action)delegate() { - Action preLoadLevelAction = delegate + Action preLoadLevelAction = (Action)delegate() { MemoryUtility.ClearAllMapsAndWorld(); Current.Game = new Game(); diff --git a/Assembly-CSharp/RimWorld/Dialog_SaveFileList_Save.cs b/Assembly-CSharp/RimWorld/Dialog_SaveFileList_Save.cs index 9dc0f9395..730bac1c3 100644 --- a/Assembly-CSharp/RimWorld/Dialog_SaveFileList_Save.cs +++ b/Assembly-CSharp/RimWorld/Dialog_SaveFileList_Save.cs @@ -15,28 +15,25 @@ protected override bool ShouldDoTypeInField public Dialog_SaveFileList_Save() { - this.interactButLabel = "OverwriteButton".Translate(); - this.bottomAreaHeight = 85f; + base.interactButLabel = "OverwriteButton".Translate(); + base.bottomAreaHeight = 85f; if (Faction.OfPlayer.HasName) { - this.typingName = Faction.OfPlayer.Name; + base.typingName = Faction.OfPlayer.Name; } else { - this.typingName = SaveGameFilesUtility.UnusedDefaultFileName(Faction.OfPlayer.def.LabelCap); + base.typingName = SaveGameFilesUtility.UnusedDefaultFileName(Faction.OfPlayer.def.LabelCap); } } protected override void DoFileInteraction(string mapName) { - LongEventHandler.QueueLongEvent(delegate + LongEventHandler.QueueLongEvent((Action)delegate() { GameDataSaveLoader.SaveGame(mapName); }, "SavingLongEvent", false, null); - Messages.Message("SavedAs".Translate(new object[] - { - mapName - }), MessageSound.Silent); + Messages.Message("SavedAs".Translate(mapName), MessageSound.Silent); PlayerKnowledgeDatabase.Save(); this.Close(true); } diff --git a/Assembly-CSharp/RimWorld/Dialog_ScenarioList.cs b/Assembly-CSharp/RimWorld/Dialog_ScenarioList.cs index 6f1e2b498..cae4d3cb3 100644 --- a/Assembly-CSharp/RimWorld/Dialog_ScenarioList.cs +++ b/Assembly-CSharp/RimWorld/Dialog_ScenarioList.cs @@ -8,16 +8,16 @@ public abstract class Dialog_ScenarioList : Dialog_FileList { protected override void ReloadFiles() { - this.files.Clear(); - foreach (FileInfo current in GenFilePaths.AllCustomScenarioFiles) + base.files.Clear(); + foreach (FileInfo allCustomScenarioFile in GenFilePaths.AllCustomScenarioFiles) { try { - this.files.Add(new SaveFileInfo(current)); + base.files.Add(new SaveFileInfo(allCustomScenarioFile)); } catch (Exception ex) { - Log.Error("Exception loading " + current.Name + ": " + ex.ToString()); + Log.Error("Exception loading " + allCustomScenarioFile.Name + ": " + ex.ToString()); } } } diff --git a/Assembly-CSharp/RimWorld/Dialog_ScenarioList_Load.cs b/Assembly-CSharp/RimWorld/Dialog_ScenarioList_Load.cs index c31277ee0..45e8b594c 100644 --- a/Assembly-CSharp/RimWorld/Dialog_ScenarioList_Load.cs +++ b/Assembly-CSharp/RimWorld/Dialog_ScenarioList_Load.cs @@ -9,14 +9,14 @@ public class Dialog_ScenarioList_Load : Dialog_ScenarioList public Dialog_ScenarioList_Load(Action scenarioReturner) { - this.interactButLabel = "LoadGameButton".Translate(); + base.interactButLabel = "LoadGameButton".Translate(); this.scenarioReturner = scenarioReturner; } protected override void DoFileInteraction(string fileName) { string filePath = GenFilePaths.AbsPathForScenario(fileName); - PreLoadUtility.CheckVersionAndLoad(filePath, ScribeMetaHeaderUtility.ScribeHeaderMode.Scenario, delegate + PreLoadUtility.CheckVersionAndLoad(filePath, ScribeMetaHeaderUtility.ScribeHeaderMode.Scenario, (Action)delegate { Scenario obj = null; if (GameDataSaveLoader.TryLoadScenario(filePath, ScenarioCategory.CustomLocal, out obj)) diff --git a/Assembly-CSharp/RimWorld/Dialog_ScenarioList_Save.cs b/Assembly-CSharp/RimWorld/Dialog_ScenarioList_Save.cs index c90113a68..f23ae9f45 100644 --- a/Assembly-CSharp/RimWorld/Dialog_ScenarioList_Save.cs +++ b/Assembly-CSharp/RimWorld/Dialog_ScenarioList_Save.cs @@ -17,22 +17,19 @@ protected override bool ShouldDoTypeInField public Dialog_ScenarioList_Save(Scenario scen) { - this.interactButLabel = "OverwriteButton".Translate(); - this.typingName = scen.name; + base.interactButLabel = "OverwriteButton".Translate(); + base.typingName = scen.name; this.savingScen = scen; } protected override void DoFileInteraction(string fileName) { string absPath = GenFilePaths.AbsPathForScenario(fileName); - LongEventHandler.QueueLongEvent(delegate + LongEventHandler.QueueLongEvent((Action)delegate { GameDataSaveLoader.SaveScenario(this.savingScen, absPath); }, "SavingLongEvent", false, null); - Messages.Message("SavedAs".Translate(new object[] - { - fileName - }), MessageSound.Silent); + Messages.Message("SavedAs".Translate(fileName), MessageSound.Silent); this.Close(true); } } diff --git a/Assembly-CSharp/RimWorld/Dialog_Trade.cs b/Assembly-CSharp/RimWorld/Dialog_Trade.cs index f23edc701..1a2a7af92 100644 --- a/Assembly-CSharp/RimWorld/Dialog_Trade.cs +++ b/Assembly-CSharp/RimWorld/Dialog_Trade.cs @@ -85,7 +85,7 @@ private float TopAreaHeight float num = 55f; if (this.playerIsCaravan) { - num += 28f; + num = (float)(num + 28.0); } return num; } @@ -105,7 +105,7 @@ private float MassUsage this.cachedMassUsage = CollectionsMassCalculator.MassUsageLeftAfterTradeableTransfer(this.playerCaravanAllPawnsAndItems, this.cachedTradeables, IgnorePawnsInventoryMode.Ignore, false, false); if (this.cachedCurrencyTradeable != null) { - this.cachedTradeables.RemoveLast(); + this.cachedTradeables.RemoveLast(); } } return this.cachedMassUsage; @@ -126,7 +126,7 @@ private float MassCapacity this.cachedMassCapacity = CollectionsMassCalculator.CapacityLeftAfterTradeableTransfer(this.playerCaravanAllPawnsAndItems, this.cachedTradeables); if (this.cachedCurrencyTradeable != null) { - this.cachedTradeables.RemoveLast(); + this.cachedTradeables.RemoveLast(); } } return this.cachedMassCapacity; @@ -151,14 +151,14 @@ public Dialog_Trade(Pawn playerNegotiator, ITrader trader) { TradeSession.SetupWith(trader, playerNegotiator); this.SetupPlayerCaravanVariables(); - this.closeOnEscapeKey = true; - this.forcePause = true; - this.absorbInputAroundWindow = true; - this.soundAppear = SoundDefOf.CommsWindow_Open; - this.soundClose = SoundDefOf.CommsWindow_Close; + base.closeOnEscapeKey = true; + base.forcePause = true; + base.absorbInputAroundWindow = true; + base.soundAppear = SoundDefOf.CommsWindow_Open; + base.soundClose = SoundDefOf.CommsWindow_Close; if (!(trader is Pawn)) { - this.soundAmbient = SoundDefOf.RadioComms_Ambience; + base.soundAmbient = SoundDefOf.RadioComms_Ambience; } this.sorter1 = TransferableSorterDefOf.Category; this.sorter2 = TransferableSorterDefOf.MarketValue; @@ -167,12 +167,9 @@ public Dialog_Trade(Pawn playerNegotiator, ITrader trader) public override void PostOpen() { base.PostOpen(); - if (TradeSession.playerNegotiator.health.capacities.GetLevel(PawnCapacityDefOf.Talking) < 0.99f) + if (TradeSession.playerNegotiator.health.capacities.GetLevel(PawnCapacityDefOf.Talking) < 0.99000000953674316) { - Find.WindowStack.Add(new Dialog_MessageBox("NegotiatorTalkingImpaired".Translate(new object[] - { - TradeSession.playerNegotiator.LabelShort - }), null, null, null, null, null, false)); + Find.WindowStack.Add(new Dialog_MessageBox("NegotiatorTalkingImpaired".Translate(TradeSession.playerNegotiator.LabelShort), (string)null, null, (string)null, null, (string)null, false)); } this.CacheTradeables(); } @@ -181,44 +178,45 @@ private void CacheTradeables() { this.cachedCurrencyTradeable = (from x in TradeSession.deal.AllTradeables where x.IsCurrency - select x).FirstOrDefault(); + select x).FirstOrDefault(); this.cachedTradeables = (from tr in TradeSession.deal.AllTradeables where !tr.IsCurrency - orderby (!tr.TraderWillTrade) ? -1 : 0 descending - select tr).ThenBy((Tradeable tr) => tr, this.sorter1.Comparer).ThenBy((Tradeable tr) => tr, this.sorter2.Comparer).ThenBy((Tradeable tr) => TransferableUIUtility.DefaultListOrderPriority(tr)).ThenBy((Tradeable tr) => tr.ThingDef.label).ThenBy(delegate(Tradeable tr) + orderby (!tr.TraderWillTrade) ? (-1) : 0 descending + select tr).ThenBy((Func)((Tradeable tr) => tr), this.sorter1.Comparer).ThenBy((Func)((Tradeable tr) => tr), this.sorter2.Comparer).ThenBy((Func)((Tradeable tr) => TransferableUIUtility.DefaultListOrderPriority(tr))).ThenBy((Func)((Tradeable tr) => tr.ThingDef.label)).ThenBy((Func)delegate(Tradeable tr) { - QualityCategory result; + QualityCategory result = default(QualityCategory); if (tr.AnyThing.TryGetQuality(out result)) { return (int)result; } return -1; - }).ThenBy((Tradeable tr) => tr.AnyThing.HitPoints).ToList(); + }).ThenBy((Func)((Tradeable tr) => tr.AnyThing.HitPoints)).ToList(); } public override void DoWindowContents(Rect inRect) { TradeSession.deal.UpdateCurrencyCount(); - TransferableUIUtility.DoTransferableSorters(this.sorter1, this.sorter2, delegate(TransferableSorterDef x) + TransferableUIUtility.DoTransferableSorters(this.sorter1, this.sorter2, (Action)delegate(TransferableSorterDef x) { this.sorter1 = x; this.CacheTradeables(); - }, delegate(TransferableSorterDef x) + }, (Action)delegate(TransferableSorterDef x) { this.sorter2 = x; this.CacheTradeables(); }); - float num = inRect.width - 590f; + float num = (float)(inRect.width - 590.0); Rect rect = new Rect(num, 0f, inRect.width - num, this.TopAreaHeight); GUI.BeginGroup(rect); Text.Font = GameFont.Medium; - Rect rect2 = new Rect(0f, 0f, rect.width / 2f, rect.height); + Rect rect2 = new Rect(0f, 0f, (float)(rect.width / 2.0), rect.height); Text.Anchor = TextAnchor.UpperLeft; Widgets.Label(rect2, Faction.OfPlayer.Name); - Rect rect3 = new Rect(rect.width / 2f, 0f, rect.width / 2f, rect.height); + Rect rect3 = new Rect((float)(rect.width / 2.0), 0f, (float)(rect.width / 2.0), rect.height); Text.Anchor = TextAnchor.UpperRight; string text = TradeSession.trader.TraderName; - if (Text.CalcSize(text).x > rect3.width) + Vector2 vector = Text.CalcSize(text); + if (vector.x > rect3.width) { Text.Font = GameFont.Small; text = text.Truncate(rect3.width, null); @@ -226,15 +224,15 @@ public override void DoWindowContents(Rect inRect) Widgets.Label(rect3, text); Text.Font = GameFont.Small; Text.Anchor = TextAnchor.UpperLeft; - Rect rect4 = new Rect(0f, 27f, rect.width / 2f, rect.height / 2f); + Rect rect4 = new Rect(0f, 27f, (float)(rect.width / 2.0), (float)(rect.height / 2.0)); Widgets.Label(rect4, "Negotiator".Translate() + ": " + TradeSession.playerNegotiator.LabelShort); Text.Anchor = TextAnchor.UpperRight; - Rect rect5 = new Rect(rect.width / 2f, 27f, rect.width / 2f, rect.height / 2f); + Rect rect5 = new Rect((float)(rect.width / 2.0), 27f, (float)(rect.width / 2.0), (float)(rect.height / 2.0)); Widgets.Label(rect5, TradeSession.trader.TraderKind.LabelCap); Text.Anchor = TextAnchor.UpperLeft; GUI.color = new Color(1f, 1f, 1f, 0.6f); Text.Font = GameFont.Tiny; - Rect rect6 = new Rect(rect.width / 2f - 100f - 30f, 0f, 200f, rect.height); + Rect rect6 = new Rect((float)(rect.width / 2.0 - 100.0 - 30.0), 0f, 200f, rect.height); Text.Anchor = TextAnchor.LowerCenter; Widgets.Label(rect6, "PositiveBuysNegativeSells".Translate()); Text.Anchor = TextAnchor.UpperLeft; @@ -247,28 +245,35 @@ public override void DoWindowContents(Rect inRect) Rect rect7 = rect.AtZero(); rect7.y = 45f; TransferableUIUtility.DrawMassInfo(rect7, massUsage, massCapacity, "TradeMassUsageTooltip".Translate(), -9999f, false); - CaravanUIUtility.DrawDaysWorthOfFoodInfo(new Rect(rect7.x, rect7.y + 19f, rect7.width, rect7.height), this.DaysWorthOfFood.First, this.DaysWorthOfFood.Second, this.EnvironmentAllowsEatingVirtualPlantsNow, false, 200f); + CaravanUIUtility.DrawDaysWorthOfFoodInfo(new Rect(rect7.x, (float)(rect7.y + 19.0), rect7.width, rect7.height), this.DaysWorthOfFood.First, this.DaysWorthOfFood.Second, this.EnvironmentAllowsEatingVirtualPlantsNow, false, 200f); } GUI.EndGroup(); float num2 = 0f; if (this.cachedCurrencyTradeable != null) { - float num3 = inRect.width - 16f; + float num3 = (float)(inRect.width - 16.0); Rect rect8 = new Rect(0f, this.TopAreaHeight, num3, 30f); TradeUI.DrawTradeableRow(rect8, this.cachedCurrencyTradeable, 1); GUI.color = Color.gray; - Widgets.DrawLineHorizontal(0f, this.TopAreaHeight + 30f - 1f, num3); + Widgets.DrawLineHorizontal(0f, (float)(this.TopAreaHeight + 30.0 - 1.0), num3); GUI.color = Color.white; num2 = 30f; } - Rect mainRect = new Rect(0f, this.TopAreaHeight + num2, inRect.width, inRect.height - this.TopAreaHeight - 38f - num2 - 20f); + Rect mainRect = new Rect(0f, this.TopAreaHeight + num2, inRect.width, (float)(inRect.height - this.TopAreaHeight - 38.0 - num2 - 20.0)); this.FillMainRect(mainRect); - Rect rect9 = new Rect(inRect.width / 2f - this.AcceptButtonSize.x / 2f, inRect.height - 55f, this.AcceptButtonSize.x, this.AcceptButtonSize.y); + double num4 = inRect.width / 2.0; + Vector2 acceptButtonSize = this.AcceptButtonSize; + double x2 = num4 - acceptButtonSize.x / 2.0; + double y = inRect.height - 55.0; + Vector2 acceptButtonSize2 = this.AcceptButtonSize; + float x3 = acceptButtonSize2.x; + Vector2 acceptButtonSize3 = this.AcceptButtonSize; + Rect rect9 = new Rect((float)x2, (float)y, x3, acceptButtonSize3.y); if (Widgets.ButtonText(rect9, "AcceptButton".Translate(), true, false, true)) { - Action action = delegate + Action action = (Action)delegate { - bool flag; + bool flag = default(bool); if (TradeSession.deal.TryExecute(out flag)) { if (flag) @@ -277,11 +282,7 @@ public override void DoWindowContents(Rect inRect) Pawn pawn = TradeSession.trader as Pawn; if (pawn != null) { - TaleRecorder.RecordTale(TaleDefOf.TradedWith, new object[] - { - TradeSession.playerNegotiator, - pawn - }); + TaleRecorder.RecordTale(TaleDefOf.TradedWith, TradeSession.playerNegotiator, pawn); } this.Close(false); } @@ -299,11 +300,18 @@ public override void DoWindowContents(Rect inRect) { this.FlashSilver(); SoundDefOf.ClickReject.PlayOneShotOnCamera(null); - Find.WindowStack.Add(Dialog_MessageBox.CreateConfirmation("ConfirmTraderShortFunds".Translate(), action, false, null)); + Find.WindowStack.Add(Dialog_MessageBox.CreateConfirmation("ConfirmTraderShortFunds".Translate(), action, false, (string)null)); } Event.current.Use(); } - Rect rect10 = new Rect(rect9.x - 10f - this.OtherBottomButtonSize.x, rect9.y, this.OtherBottomButtonSize.x, this.OtherBottomButtonSize.y); + double num5 = rect9.x - 10.0; + Vector2 otherBottomButtonSize = this.OtherBottomButtonSize; + double x4 = num5 - otherBottomButtonSize.x; + float y2 = rect9.y; + Vector2 otherBottomButtonSize2 = this.OtherBottomButtonSize; + float x5 = otherBottomButtonSize2.x; + Vector2 otherBottomButtonSize3 = this.OtherBottomButtonSize; + Rect rect10 = new Rect((float)x4, y2, x5, otherBottomButtonSize3.y); if (Widgets.ButtonText(rect10, "ResetButton".Translate(), true, false, true)) { SoundDefOf.TickLow.PlayOneShotOnCamera(null); @@ -312,7 +320,12 @@ public override void DoWindowContents(Rect inRect) this.CountToTransferChanged(); Event.current.Use(); } - Rect rect11 = new Rect(rect9.xMax + 10f, rect9.y, this.OtherBottomButtonSize.x, this.OtherBottomButtonSize.y); + double x6 = rect9.xMax + 10.0; + float y3 = rect9.y; + Vector2 otherBottomButtonSize4 = this.OtherBottomButtonSize; + float x7 = otherBottomButtonSize4.x; + Vector2 otherBottomButtonSize5 = this.OtherBottomButtonSize; + Rect rect11 = new Rect((float)x6, y3, x7, otherBottomButtonSize5.y); if (Widgets.ButtonText(rect11, "CancelButton".Translate(), true, false, true)) { this.Close(true); @@ -329,11 +342,11 @@ public override void Close(bool doCloseSound = true) private void FillMainRect(Rect mainRect) { Text.Font = GameFont.Small; - float height = 6f + (float)this.cachedTradeables.Count * 30f; - Rect viewRect = new Rect(0f, 0f, mainRect.width - 16f, height); + float height = (float)(6.0 + (float)this.cachedTradeables.Count * 30.0); + Rect viewRect = new Rect(0f, 0f, (float)(mainRect.width - 16.0), height); Widgets.BeginScrollView(mainRect, ref this.scrollPosition, viewRect, true); float num = 6f; - float num2 = this.scrollPosition.y - 30f; + float num2 = (float)(this.scrollPosition.y - 30.0); float num3 = this.scrollPosition.y + mainRect.height; int num4 = 0; for (int i = 0; i < this.cachedTradeables.Count; i++) @@ -348,7 +361,7 @@ private void FillMainRect(Rect mainRect) this.CountToTransferChanged(); } } - num += 30f; + num = (float)(num + 30.0); num4++; } Widgets.EndScrollView(); diff --git a/Assembly-CSharp/RimWorld/DifficultyDef.cs b/Assembly-CSharp/RimWorld/DifficultyDef.cs index 56069196a..a17daa562 100644 --- a/Assembly-CSharp/RimWorld/DifficultyDef.cs +++ b/Assembly-CSharp/RimWorld/DifficultyDef.cs @@ -1,4 +1,3 @@ -using System; using Verse; namespace RimWorld diff --git a/Assembly-CSharp/RimWorld/DifficultyDefOf.cs b/Assembly-CSharp/RimWorld/DifficultyDefOf.cs index ca1c182ef..2209960fc 100644 --- a/Assembly-CSharp/RimWorld/DifficultyDefOf.cs +++ b/Assembly-CSharp/RimWorld/DifficultyDefOf.cs @@ -1,5 +1,3 @@ -using System; - namespace RimWorld { [DefOf] diff --git a/Assembly-CSharp/RimWorld/DigUtility.cs b/Assembly-CSharp/RimWorld/DigUtility.cs index f16c49c1f..bc454fe05 100644 --- a/Assembly-CSharp/RimWorld/DigUtility.cs +++ b/Assembly-CSharp/RimWorld/DigUtility.cs @@ -1,4 +1,3 @@ -using System; using Verse; using Verse.AI; @@ -19,12 +18,11 @@ public static Job PassBlockerJob(Pawn pawn, Thing blocker, IntVec3 cellBeforeBlo Verb primaryVerb = pawn.equipment.PrimaryEq.PrimaryVerb; if (primaryVerb.verbProps.ai_IsBuildingDestroyer && (!primaryVerb.verbProps.ai_IsIncendiary || blocker.FlammableNow)) { - return new Job(JobDefOf.UseVerbOnThing) - { - targetA = blocker, - verbToUse = primaryVerb, - expiryInterval = JobGiver_AIFightEnemy.ExpiryInterval_ShooterSucceeded.RandomInRange - }; + Job job = new Job(JobDefOf.UseVerbOnThing); + job.targetA = blocker; + job.verbToUse = primaryVerb; + job.expiryInterval = JobGiver_AIFightEnemy.ExpiryInterval_ShooterSucceeded.RandomInRange; + return job; } } if (canMineNonMineables) @@ -40,12 +38,11 @@ private static Job MeleeOrWaitJob(Pawn pawn, Thing blocker, IntVec3 cellBeforeBl { return DigUtility.WaitNearJob(pawn, cellBeforeBlocker); } - return new Job(JobDefOf.AttackMelee, blocker) - { - ignoreDesignations = true, - expiryInterval = JobGiver_AIFightEnemy.ExpiryInterval_ShooterSucceeded.RandomInRange, - checkOverrideOnExpire = true - }; + Job job = new Job(JobDefOf.AttackMelee, blocker); + job.ignoreDesignations = true; + job.expiryInterval = JobGiver_AIFightEnemy.ExpiryInterval_ShooterSucceeded.RandomInRange; + job.checkOverrideOnExpire = true; + return job; } private static Job MineOrWaitJob(Pawn pawn, Thing blocker, IntVec3 cellBeforeBlocker) @@ -54,12 +51,11 @@ private static Job MineOrWaitJob(Pawn pawn, Thing blocker, IntVec3 cellBeforeBlo { return DigUtility.WaitNearJob(pawn, cellBeforeBlocker); } - return new Job(JobDefOf.Mine, blocker) - { - ignoreDesignations = true, - expiryInterval = JobGiver_AIFightEnemy.ExpiryInterval_ShooterSucceeded.RandomInRange, - checkOverrideOnExpire = true - }; + Job job = new Job(JobDefOf.Mine, blocker); + job.ignoreDesignations = true; + job.expiryInterval = JobGiver_AIFightEnemy.ExpiryInterval_ShooterSucceeded.RandomInRange; + job.checkOverrideOnExpire = true; + return job; } private static Job WaitNearJob(Pawn pawn, IntVec3 cellBeforeBlocker) diff --git a/Assembly-CSharp/RimWorld/DirectPawnRelation.cs b/Assembly-CSharp/RimWorld/DirectPawnRelation.cs index 0796494d0..8c6b242f5 100644 --- a/Assembly-CSharp/RimWorld/DirectPawnRelation.cs +++ b/Assembly-CSharp/RimWorld/DirectPawnRelation.cs @@ -1,4 +1,3 @@ -using System; using Verse; namespace RimWorld diff --git a/Assembly-CSharp/RimWorld/Direction8Way.cs b/Assembly-CSharp/RimWorld/Direction8Way.cs index 09daac9ea..00aecd920 100644 --- a/Assembly-CSharp/RimWorld/Direction8Way.cs +++ b/Assembly-CSharp/RimWorld/Direction8Way.cs @@ -1,16 +1,14 @@ -using System; - namespace RimWorld { public enum Direction8Way { - North, - NorthEast, - East, - SouthEast, - South, - SouthWest, - West, - NorthWest + North = 0, + NorthEast = 1, + East = 2, + SouthEast = 3, + South = 4, + SouthWest = 5, + West = 6, + NorthWest = 7 } } diff --git a/Assembly-CSharp/RimWorld/Direction8WayUtility.cs b/Assembly-CSharp/RimWorld/Direction8WayUtility.cs index 3c0e470c0..ecdf1e9c6 100644 --- a/Assembly-CSharp/RimWorld/Direction8WayUtility.cs +++ b/Assembly-CSharp/RimWorld/Direction8WayUtility.cs @@ -1,4 +1,3 @@ -using System; using Verse; namespace RimWorld @@ -10,24 +9,42 @@ public static string LabelShort(this Direction8Way dir) switch (dir) { case Direction8Way.North: + { return "Direction8Way_North_Short".Translate(); + } case Direction8Way.NorthEast: + { return "Direction8Way_NorthEast_Short".Translate(); + } case Direction8Way.East: + { return "Direction8Way_East_Short".Translate(); + } case Direction8Way.SouthEast: + { return "Direction8Way_SouthEast_Short".Translate(); + } case Direction8Way.South: + { return "Direction8Way_South_Short".Translate(); + } case Direction8Way.SouthWest: + { return "Direction8Way_SouthWest_Short".Translate(); + } case Direction8Way.West: + { return "Direction8Way_West_Short".Translate(); + } case Direction8Way.NorthWest: + { return "Direction8Way_NorthWest_Short".Translate(); + } default: + { return "Unknown Direction8Way"; } + } } } } diff --git a/Assembly-CSharp/RimWorld/DoorsDebugDrawer.cs b/Assembly-CSharp/RimWorld/DoorsDebugDrawer.cs index 2448dcd89..1e9f0b07d 100644 --- a/Assembly-CSharp/RimWorld/DoorsDebugDrawer.cs +++ b/Assembly-CSharp/RimWorld/DoorsDebugDrawer.cs @@ -1,4 +1,3 @@ -using System; using System.Collections.Generic; using UnityEngine; using Verse; @@ -9,29 +8,20 @@ public static class DoorsDebugDrawer { public static void DrawDebug() { - if (!DebugViewSettings.drawDoorsDebug) + if (DebugViewSettings.drawDoorsDebug) { - return; - } - CellRect currentViewRect = Find.CameraDriver.CurrentViewRect; - List list = Find.VisibleMap.listerThings.ThingsInGroup(ThingRequestGroup.BuildingArtificial); - for (int i = 0; i < list.Count; i++) - { - if (currentViewRect.Contains(list[i].Position)) + CellRect currentViewRect = Find.CameraDriver.CurrentViewRect; + List list = Find.VisibleMap.listerThings.ThingsInGroup(ThingRequestGroup.BuildingArtificial); + for (int i = 0; i < list.Count; i++) { - Building_Door building_Door = list[i] as Building_Door; - if (building_Door != null) + if (currentViewRect.Contains(list[i].Position)) { - Color col; - if (building_Door.FreePassage) - { - col = new Color(0f, 1f, 0f, 0.5f); - } - else + Building_Door building_Door = list[i] as Building_Door; + if (building_Door != null) { - col = new Color(1f, 0f, 0f, 0.5f); + Color col = (!building_Door.FreePassage) ? new Color(1f, 0f, 0f, 0.5f) : new Color(0f, 1f, 0f, 0.5f); + CellRenderer.RenderCell(building_Door.Position, SolidColorMaterials.SimpleSolidColorMaterial(col, false)); } - CellRenderer.RenderCell(building_Door.Position, SolidColorMaterials.SimpleSolidColorMaterial(col, false)); } } } diff --git a/Assembly-CSharp/RimWorld/DragBox.cs b/Assembly-CSharp/RimWorld/DragBox.cs index f547f2855..ae8300ccc 100644 --- a/Assembly-CSharp/RimWorld/DragBox.cs +++ b/Assembly-CSharp/RimWorld/DragBox.cs @@ -16,7 +16,9 @@ public float LeftX { get { - return Math.Min(this.start.x, UI.MouseMapPosition().x); + float x = this.start.x; + Vector3 vector = UI.MouseMapPosition(); + return Math.Min(x, vector.x); } } @@ -24,7 +26,9 @@ public float RightX { get { - return Math.Max(this.start.x, UI.MouseMapPosition().x); + float x = this.start.x; + Vector3 vector = UI.MouseMapPosition(); + return Math.Max(x, vector.x); } } @@ -32,7 +36,9 @@ public float BotZ { get { - return Math.Min(this.start.z, UI.MouseMapPosition().z); + float z = this.start.z; + Vector3 vector = UI.MouseMapPosition(); + return Math.Min(z, vector.z); } } @@ -40,7 +46,9 @@ public float TopZ { get { - return Math.Max(this.start.z, UI.MouseMapPosition().z); + float z = this.start.z; + Vector3 vector = UI.MouseMapPosition(); + return Math.Max(z, vector.z); } } @@ -76,7 +84,7 @@ public bool IsValid { get { - return (this.start - UI.MouseMapPosition()).magnitude > 0.5f; + return (this.start - UI.MouseMapPosition()).magnitude > 0.5; } } @@ -105,8 +113,7 @@ public bool Contains(Thing t) CellRect.CellRectIterator iterator = t.OccupiedRect().GetIterator(); while (!iterator.Done()) { - IntVec3 current = iterator.Current; - if (this.Contains(current.ToVector3Shifted())) + if (this.Contains(iterator.Current.ToVector3Shifted())) { return true; } @@ -117,7 +124,11 @@ public bool Contains(Thing t) public bool Contains(Vector3 v) { - return v.x + 0.5f > this.LeftX && v.x - 0.5f < this.RightX && v.z + 0.5f > this.BotZ && v.z - 0.5f < this.TopZ; + if (v.x + 0.5 > this.LeftX && v.x - 0.5 < this.RightX && v.z + 0.5 > this.BotZ && v.z - 0.5 < this.TopZ) + { + return true; + } + return false; } } } diff --git a/Assembly-CSharp/RimWorld/DrawTargetDefOf.cs b/Assembly-CSharp/RimWorld/DrawTargetDefOf.cs index 683db0f50..40a889c38 100644 --- a/Assembly-CSharp/RimWorld/DrawTargetDefOf.cs +++ b/Assembly-CSharp/RimWorld/DrawTargetDefOf.cs @@ -1,4 +1,3 @@ -using System; using Verse; namespace RimWorld diff --git a/Assembly-CSharp/RimWorld/DropCellFinder.cs b/Assembly-CSharp/RimWorld/DropCellFinder.cs index 29412f773..5aa357c61 100644 --- a/Assembly-CSharp/RimWorld/DropCellFinder.cs +++ b/Assembly-CSharp/RimWorld/DropCellFinder.cs @@ -11,7 +11,7 @@ public static class DropCellFinder { public static IntVec3 RandomDropSpot(Map map) { - return CellFinderLoose.RandomCellWith((IntVec3 c) => c.Standable(map) && !c.Roofed(map) && !c.Fogged(map), map, 1000); + return CellFinderLoose.RandomCellWith((Predicate)((IntVec3 c) => c.Standable(map) && !c.Roofed(map) && !c.Fogged(map)), map, 1000); } public static IntVec3 TradeDropSpot(Map map) @@ -22,33 +22,33 @@ where b.def.IsCommsConsole IEnumerable enumerable = from b in map.listerBuildings.allBuildingsColonist where b.def.IsOrbitalTradeBeacon select b; - Building building = enumerable.FirstOrDefault((Building b) => !map.roofGrid.Roofed(b.Position) && DropCellFinder.AnyAdjacentGoodDropSpot(b.Position, map, false, false)); - IntVec3 position; + Building building = enumerable.FirstOrDefault((Func)((Building b) => !map.roofGrid.Roofed(b.Position) && DropCellFinder.AnyAdjacentGoodDropSpot(b.Position, map, false, false))); + IntVec3 position = default(IntVec3); if (building != null) { position = building.Position; - IntVec3 result; + IntVec3 result = default(IntVec3); if (!DropCellFinder.TryFindDropSpotNear(position, map, out result, false, false)) { Log.Error("Could find no good TradeDropSpot near dropCenter " + position + ". Using a random standable unfogged cell."); - result = CellFinderLoose.RandomCellWith((IntVec3 c) => c.Standable(map) && !c.Fogged(map), map, 1000); + result = CellFinderLoose.RandomCellWith((Predicate)((IntVec3 c) => c.Standable(map) && !c.Fogged(map)), map, 1000); } return result; } List list = new List(); list.AddRange(enumerable); list.AddRange(collection); - list.RemoveAll(delegate(Building b) + list.RemoveAll((Predicate)delegate(Building b) { CompPowerTrader compPowerTrader = b.TryGetComp(); return compPowerTrader != null && !compPowerTrader.PowerOn; }); - Predicate validator = (IntVec3 c) => DropCellFinder.IsGoodDropSpot(c, map, false, false); - if (!list.Any()) + Predicate validator = (Predicate)((IntVec3 c) => DropCellFinder.IsGoodDropSpot(c, map, false, false)); + if (!list.Any()) { list.AddRange(map.listerBuildings.allBuildingsColonist); - list.Shuffle(); - if (!list.Any()) + list.Shuffle(); + if (!list.Any()) { return CellFinderLoose.RandomCellWith(validator, map, 1000); } @@ -64,14 +64,12 @@ where b.def.IsOrbitalTradeBeacon return position; } } - num = Mathf.RoundToInt((float)num * 1.1f); - if (num > map.Size.x) - { - goto Block_9; - } + num = Mathf.RoundToInt((float)((float)num * 1.1000000238418579)); + int num2 = num; + IntVec3 size = map.Size; + if (num2 > size.x) + break; } - return position; - Block_9: Log.Error("Failed to generate trade drop center. Giving random."); return CellFinderLoose.RandomCellWith(validator, map, 1000); } @@ -82,52 +80,68 @@ public static bool TryFindDropSpotNear(IntVec3 center, Map map, out IntVec3 resu { map.debugDrawer.FlashCell(center, 1f, "center"); } - Predicate validator = (IntVec3 c) => DropCellFinder.IsGoodDropSpot(c, map, allowFogged, canRoofPunch) && map.reachability.CanReach(center, c, PathEndMode.OnCell, TraverseMode.PassDoors, Danger.Deadly); - int num = 5; - while (!CellFinder.TryFindRandomCellNear(center, map, num, validator, out result)) + Predicate validator = (Predicate)delegate(IntVec3 c) { - num += 3; - if (num > 16) + if (!DropCellFinder.IsGoodDropSpot(c, map, allowFogged, canRoofPunch)) + { + return false; + } + if (!map.reachability.CanReach(center, c, PathEndMode.OnCell, TraverseMode.PassDoors, Danger.Deadly)) { - result = center; return false; } + return true; + }; + int num = 5; + while (true) + { + if (CellFinder.TryFindRandomCellNear(center, map, num, validator, out result)) + { + return true; + } + num += 3; + if (num > 16) + break; } - return true; + result = center; + return false; } public static bool IsGoodDropSpot(IntVec3 c, Map map, bool allowFogged, bool canRoofPunch) { - if (!c.InBounds(map) || !c.Standable(map)) + if (c.InBounds(map) && c.Standable(map)) { - return false; - } - if (!DropCellFinder.CanPhysicallyDropInto(c, map, canRoofPunch)) - { - if (DebugViewSettings.drawDestSearch) + if (!DropCellFinder.CanPhysicallyDropInto(c, map, canRoofPunch)) { - map.debugDrawer.FlashCell(c, 0f, "phys"); + if (DebugViewSettings.drawDestSearch) + { + map.debugDrawer.FlashCell(c, 0f, "phys"); + } + return false; } - return false; - } - if (Current.ProgramState == ProgramState.Playing && !allowFogged && c.Fogged(map)) - { - return false; - } - List thingList = c.GetThingList(map); - for (int i = 0; i < thingList.Count; i++) - { - Thing thing = thingList[i]; - if (thing is IActiveDropPod || thing.def.category == ThingCategory.Skyfaller) + if (Current.ProgramState == ProgramState.Playing && !allowFogged && c.Fogged(map)) { return false; } - if (thing.def.category != ThingCategory.Plant && GenSpawn.SpawningWipes(ThingDefOf.ActiveDropPod, thing.def)) + List thingList = c.GetThingList(map); + int num = 0; + while (num < thingList.Count) { + Thing thing = thingList[num]; + if (!(thing is IActiveDropPod) && thing.def.category != ThingCategory.Skyfaller) + { + if (thing.def.category != ThingCategory.Plant && GenSpawn.SpawningWipes(ThingDefOf.ActiveDropPod, thing.def)) + { + return false; + } + num++; + continue; + } return false; } + return true; } - return true; + return false; } private static bool AnyAdjacentGoodDropSpot(IntVec3 c, Map map, bool allowFogged, bool canRoofPunch) @@ -138,19 +152,14 @@ private static bool AnyAdjacentGoodDropSpot(IntVec3 c, Map map, bool allowFogged public static IntVec3 FindRaidDropCenterDistant(Map map) { Faction hostFaction = map.ParentFaction ?? Faction.OfPlayer; - IEnumerable enumerable = map.mapPawns.FreeHumanlikesSpawnedOfFaction(hostFaction).Cast(); - if (hostFaction == Faction.OfPlayer) - { - enumerable = enumerable.Concat(map.listerBuildings.allBuildingsColonist.Cast()); - } - else - { - enumerable = enumerable.Concat(from x in map.listerThings.ThingsInGroup(ThingRequestGroup.BuildingArtificial) - where x.Faction == hostFaction - select x); - } + IEnumerable first = map.mapPawns.FreeHumanlikesSpawnedOfFaction(hostFaction).Cast(); + first = ((hostFaction != Faction.OfPlayer) ? first.Concat(from x in map.listerThings.ThingsInGroup(ThingRequestGroup.BuildingArtificial) + where x.Faction == hostFaction + select x) : first.Concat(map.listerBuildings.allBuildingsColonist.Cast())); int num = 0; float num2 = 65f; + goto IL_0095; + IL_0095: IntVec3 intVec; while (true) { @@ -160,28 +169,28 @@ public static IntVec3 FindRaidDropCenterDistant(Map map) { if (num > 300) { - break; + return intVec; } if (!intVec.Roofed(map)) { - num2 -= 0.2f; + num2 = (float)(num2 - 0.20000000298023224); bool flag = false; - foreach (Thing current in enumerable) + foreach (Thing item in first) { - if ((float)(intVec - current.Position).LengthHorizontalSquared < num2 * num2) + if ((float)(intVec - item.Position).LengthHorizontalSquared < num2 * num2) { flag = true; break; } } if (!flag && map.reachability.CanReachFactionBase(intVec, hostFaction)) - { - return intVec; - } + break; } } } return intVec; + IL_016a: + goto IL_0095; } public static bool TryFindRaidDropCenterClose(out IntVec3 spot, Map map) @@ -191,32 +200,28 @@ public static bool TryFindRaidDropCenterClose(out IntVec3 spot, Map map) while (true) { IntVec3 root = IntVec3.Invalid; - if (map.mapPawns.FreeHumanlikesSpawnedOfFaction(faction).Count() > 0) + if (map.mapPawns.FreeHumanlikesSpawnedOfFaction(faction).Count() > 0) { - root = map.mapPawns.FreeHumanlikesSpawnedOfFaction(faction).RandomElement().Position; + root = map.mapPawns.FreeHumanlikesSpawnedOfFaction(faction).RandomElement().Position; } else { if (faction == Faction.OfPlayer) { List allBuildingsColonist = map.listerBuildings.allBuildingsColonist; - for (int i = 0; i < allBuildingsColonist.Count; i++) + int num2 = 0; + while (num2 < allBuildingsColonist.Count && !DropCellFinder.TryFindDropSpotNear(allBuildingsColonist[num2].Position, map, out root, true, true)) { - if (DropCellFinder.TryFindDropSpotNear(allBuildingsColonist[i].Position, map, out root, true, true)) - { - break; - } + num2++; } } else { List list = map.listerThings.ThingsInGroup(ThingRequestGroup.BuildingArtificial); - for (int j = 0; j < list.Count; j++) + int num3 = 0; + while (num3 < list.Count && (list[num3].Faction != faction || !DropCellFinder.TryFindDropSpotNear(list[num3].Position, map, out root, true, true))) { - if (list[j].Faction == faction && DropCellFinder.TryFindDropSpotNear(list[j].Position, map, out root, true, true)) - { - break; - } + num3++; } } if (!root.IsValid) @@ -227,17 +232,13 @@ public static bool TryFindRaidDropCenterClose(out IntVec3 spot, Map map) spot = CellFinder.RandomClosewalkCellNear(root, map, 10, null); if (DropCellFinder.CanPhysicallyDropInto(spot, map, true)) { - break; + return true; } num++; if (num > 300) - { - goto Block_9; - } + break; } - return true; - Block_9: - spot = CellFinderLoose.RandomCellWith((IntVec3 c) => DropCellFinder.CanPhysicallyDropInto(c, map, true), map, 1000); + spot = CellFinderLoose.RandomCellWith((Predicate)((IntVec3 c) => DropCellFinder.CanPhysicallyDropInto(c, map, true)), map, 1000); return false; } diff --git a/Assembly-CSharp/RimWorld/DropPodAnimationUtility.cs b/Assembly-CSharp/RimWorld/DropPodAnimationUtility.cs index 838889780..289bf57f1 100644 --- a/Assembly-CSharp/RimWorld/DropPodAnimationUtility.cs +++ b/Assembly-CSharp/RimWorld/DropPodAnimationUtility.cs @@ -1,4 +1,3 @@ -using System; using UnityEngine; using Verse; @@ -18,9 +17,9 @@ public static Vector3 DrawPosAt(int ticksToImpact, IntVec3 basePos) ticksToImpact = 0; } Vector3 result = basePos.ToVector3ShiftedWithAltitude(AltitudeLayer.FlyingItem); - float num = (float)(ticksToImpact * ticksToImpact) * 0.01f; - result.x -= num * 0.4f; - result.z += num * 0.6f; + float num = (float)((float)(ticksToImpact * ticksToImpact) * 0.0099999997764825821); + result.x -= (float)(num * 0.40000000596046448); + result.z += (float)(num * 0.60000002384185791); return result; } @@ -32,7 +31,7 @@ public static void DrawDropSpotShadow(Thing dropPod, int ticksToImpact) } Vector3 pos = dropPod.TrueCenter(); pos.y = Altitudes.AltitudeFor(AltitudeLayer.Shadows); - float num = 2f + (float)ticksToImpact / 100f; + float num = (float)(2.0 + (float)ticksToImpact / 100.0); Vector3 s = new Vector3(num, 1f, num); Color white = Color.white; if (ticksToImpact > 150) diff --git a/Assembly-CSharp/RimWorld/DropPodIncoming.cs b/Assembly-CSharp/RimWorld/DropPodIncoming.cs index a40b56c2a..ef90fb20d 100644 --- a/Assembly-CSharp/RimWorld/DropPodIncoming.cs +++ b/Assembly-CSharp/RimWorld/DropPodIncoming.cs @@ -75,7 +75,7 @@ public override void ExposeData() { base.ExposeData(); Scribe_Values.Look(ref this.ticksToImpact, "ticksToImpact", 0, false); - Scribe_Deep.Look(ref this.contents, "contents", new object[] + Scribe_Deep.Look(ref this.contents, "contents", new object[1] { this }); @@ -101,27 +101,30 @@ public override void Tick() private void HitRoof() { - if (!base.Position.Roofed(base.Map)) + if (base.Position.Roofed(base.Map)) { - return; - } - RoofCollapserImmediate.DropRoofInCells(this.OccupiedRect().ExpandedBy(1).Cells.Where(delegate(IntVec3 c) - { - if (!c.InBounds(base.Map)) - { - return false; - } - if (c == base.Position) + RoofCollapserImmediate.DropRoofInCells(this.OccupiedRect().ExpandedBy(1).Cells.Where((Func)delegate(IntVec3 c) { + if (!c.InBounds(base.Map)) + { + return false; + } + if (c == base.Position) + { + return true; + } + if (base.Map.thingGrid.CellContains(c, ThingCategory.Pawn)) + { + return false; + } + Building edifice = c.GetEdifice(base.Map); + if (edifice != null && edifice.def.holdsRoof) + { + return false; + } return true; - } - if (base.Map.thingGrid.CellContains(c, ThingCategory.Pawn)) - { - return false; - } - Building edifice = c.GetEdifice(base.Map); - return edifice == null || !edifice.def.holdsRoof; - }), base.Map); + }), base.Map); + } } public override void DrawAt(Vector3 drawLoc, bool flip = false) @@ -163,5 +166,11 @@ virtual IThingHolder get_ParentHolder() { return base.ParentHolder; } + + IThingHolder IThingHolder.get_ParentHolder() + { + //ILSpy generated this explicit interface implementation from .override directive in get_ParentHolder + return this.get_ParentHolder(); + } } } diff --git a/Assembly-CSharp/RimWorld/DropPodLeaving.cs b/Assembly-CSharp/RimWorld/DropPodLeaving.cs index 6f0c9ae40..b55432e96 100644 --- a/Assembly-CSharp/RimWorld/DropPodLeaving.cs +++ b/Assembly-CSharp/RimWorld/DropPodLeaving.cs @@ -1,5 +1,4 @@ using RimWorld.Planet; -using System; using System.Collections.Generic; using UnityEngine; using Verse; @@ -95,7 +94,7 @@ public override void ExposeData() Scribe_Values.Look(ref this.arriveMode, "arriveMode", PawnsArriveMode.Undecided, false); Scribe_Values.Look(ref this.attackOnArrival, "attackOnArrival", false, false); Scribe_Values.Look(ref this.ticksSinceStart, "ticksSinceStart", 0, false); - Scribe_Deep.Look(ref this.contents, "contents", new object[] + Scribe_Deep.Look(ref this.contents, "contents", new object[1] { this }); @@ -129,38 +128,39 @@ private void GroupLeftMap() { Log.Error("Drop pod left the map, but its group ID is " + this.groupID); this.Destroy(DestroyMode.Vanish); - return; } - if (this.destinationTile < 0) + else if (this.destinationTile < 0) { Log.Error("Drop pod left the map, but its destination tile is " + this.destinationTile); this.Destroy(DestroyMode.Vanish); - return; } - Lord lord = TransporterUtility.FindLord(this.groupID, base.Map); - if (lord != null) + else { - base.Map.lordManager.RemoveLord(lord); - } - TravelingTransportPods travelingTransportPods = (TravelingTransportPods)WorldObjectMaker.MakeWorldObject(WorldObjectDefOf.TravelingTransportPods); - travelingTransportPods.Tile = base.Map.Tile; - travelingTransportPods.SetFaction(Faction.OfPlayer); - travelingTransportPods.destinationTile = this.destinationTile; - travelingTransportPods.destinationCell = this.destinationCell; - travelingTransportPods.arriveMode = this.arriveMode; - travelingTransportPods.attackOnArrival = this.attackOnArrival; - Find.WorldObjects.Add(travelingTransportPods); - DropPodLeaving.tmpActiveDropPods.Clear(); - DropPodLeaving.tmpActiveDropPods.AddRange(base.Map.listerThings.ThingsInGroup(ThingRequestGroup.ActiveDropPod)); - for (int i = 0; i < DropPodLeaving.tmpActiveDropPods.Count; i++) - { - DropPodLeaving dropPodLeaving = DropPodLeaving.tmpActiveDropPods[i] as DropPodLeaving; - if (dropPodLeaving != null && dropPodLeaving.groupID == this.groupID) + Lord lord = TransporterUtility.FindLord(this.groupID, base.Map); + if (lord != null) + { + base.Map.lordManager.RemoveLord(lord); + } + TravelingTransportPods travelingTransportPods = (TravelingTransportPods)WorldObjectMaker.MakeWorldObject(WorldObjectDefOf.TravelingTransportPods); + travelingTransportPods.Tile = base.Map.Tile; + travelingTransportPods.SetFaction(Faction.OfPlayer); + travelingTransportPods.destinationTile = this.destinationTile; + travelingTransportPods.destinationCell = this.destinationCell; + travelingTransportPods.arriveMode = this.arriveMode; + travelingTransportPods.attackOnArrival = this.attackOnArrival; + Find.WorldObjects.Add(travelingTransportPods); + DropPodLeaving.tmpActiveDropPods.Clear(); + DropPodLeaving.tmpActiveDropPods.AddRange(base.Map.listerThings.ThingsInGroup(ThingRequestGroup.ActiveDropPod)); + for (int i = 0; i < DropPodLeaving.tmpActiveDropPods.Count; i++) { - dropPodLeaving.alreadyLeft = true; - travelingTransportPods.AddPod(dropPodLeaving.contents, true); - dropPodLeaving.contents = null; - dropPodLeaving.Destroy(DestroyMode.Vanish); + DropPodLeaving dropPodLeaving = DropPodLeaving.tmpActiveDropPods[i] as DropPodLeaving; + if (dropPodLeaving != null && dropPodLeaving.groupID == this.groupID) + { + dropPodLeaving.alreadyLeft = true; + travelingTransportPods.AddPod(dropPodLeaving.contents, true); + dropPodLeaving.contents = null; + dropPodLeaving.Destroy(DestroyMode.Vanish); + } } } } @@ -169,5 +169,11 @@ virtual IThingHolder get_ParentHolder() { return base.ParentHolder; } + + IThingHolder IThingHolder.get_ParentHolder() + { + //ILSpy generated this explicit interface implementation from .override directive in get_ParentHolder + return this.get_ParentHolder(); + } } } diff --git a/Assembly-CSharp/RimWorld/DropPodUtility.cs b/Assembly-CSharp/RimWorld/DropPodUtility.cs index 048bd50c3..c23f00297 100644 --- a/Assembly-CSharp/RimWorld/DropPodUtility.cs +++ b/Assembly-CSharp/RimWorld/DropPodUtility.cs @@ -18,10 +18,10 @@ public static void MakeDropPodAt(IntVec3 c, Map map, ActiveDropPodInfo info) public static void DropThingsNear(IntVec3 dropCenter, Map map, IEnumerable things, int openDelay = 110, bool canInstaDropDuringInit = false, bool leaveSlag = false, bool canRoofPunch = true) { - foreach (Thing current in things) + foreach (Thing item in things) { List list = new List(); - list.Add(current); + list.Add(item); DropPodUtility.tempList.Add(list); } DropPodUtility.DropThingGroupsNear(dropCenter, map, DropPodUtility.tempList, openDelay, canInstaDropDuringInit, leaveSlag, canRoofPunch); @@ -30,44 +30,64 @@ public static void DropThingsNear(IntVec3 dropCenter, Map map, IEnumerable> thingsGroups, int openDelay = 110, bool instaDrop = false, bool leaveSlag = false, bool canRoofPunch = true) { - foreach (List current in thingsGroups) + List>.Enumerator enumerator = thingsGroups.GetEnumerator(); + try { - IntVec3 intVec; - if (!DropCellFinder.TryFindDropSpotNear(dropCenter, map, out intVec, true, canRoofPunch)) + while (enumerator.MoveNext()) { - Log.Warning(string.Concat(new object[] + List current = enumerator.Current; + IntVec3 intVec = default(IntVec3); + if (!DropCellFinder.TryFindDropSpotNear(dropCenter, map, out intVec, true, canRoofPunch)) { - "DropThingsNear failed to find a place to drop ", - current.FirstOrDefault(), - " near ", - dropCenter, - ". Dropping on random square instead." - })); - intVec = CellFinderLoose.RandomCellWith((IntVec3 c) => c.Walkable(map), map, 1000); - } - for (int i = 0; i < current.Count; i++) - { - current[i].SetForbidden(true, false); - } - if (instaDrop) - { - foreach (Thing current2 in current) + Log.Warning("DropThingsNear failed to find a place to drop " + current.FirstOrDefault() + " near " + dropCenter + ". Dropping on random square instead."); + intVec = CellFinderLoose.RandomCellWith((Predicate)((IntVec3 c) => c.Walkable(map)), map, 1000); + } + for (int i = 0; i < current.Count; i++) { - GenPlace.TryPlaceThing(current2, intVec, map, ThingPlaceMode.Near, null); + current[i].SetForbidden(true, false); } - } - else - { - ActiveDropPodInfo activeDropPodInfo = new ActiveDropPodInfo(); - foreach (Thing current3 in current) + if (instaDrop) + { + List.Enumerator enumerator2 = current.GetEnumerator(); + try + { + while (enumerator2.MoveNext()) + { + Thing current2 = enumerator2.Current; + GenPlace.TryPlaceThing(current2, intVec, map, ThingPlaceMode.Near, null); + } + } + finally + { + ((IDisposable)(object)enumerator2).Dispose(); + } + } + else { - activeDropPodInfo.innerContainer.TryAdd(current3, true); + ActiveDropPodInfo activeDropPodInfo = new ActiveDropPodInfo(); + List.Enumerator enumerator3 = current.GetEnumerator(); + try + { + while (enumerator3.MoveNext()) + { + Thing current3 = enumerator3.Current; + activeDropPodInfo.innerContainer.TryAdd(current3, true); + } + } + finally + { + ((IDisposable)(object)enumerator3).Dispose(); + } + activeDropPodInfo.openDelay = openDelay; + activeDropPodInfo.leaveSlag = leaveSlag; + DropPodUtility.MakeDropPodAt(intVec, map, activeDropPodInfo); } - activeDropPodInfo.openDelay = openDelay; - activeDropPodInfo.leaveSlag = leaveSlag; - DropPodUtility.MakeDropPodAt(intVec, map, activeDropPodInfo); } } + finally + { + ((IDisposable)(object)enumerator).Dispose(); + } } } } diff --git a/Assembly-CSharp/RimWorld/DrugAIUtility.cs b/Assembly-CSharp/RimWorld/DrugAIUtility.cs index d6253c1ae..1b4a909d4 100644 --- a/Assembly-CSharp/RimWorld/DrugAIUtility.cs +++ b/Assembly-CSharp/RimWorld/DrugAIUtility.cs @@ -1,4 +1,3 @@ -using System; using UnityEngine; using Verse; using Verse.AI; @@ -10,12 +9,7 @@ public static class DrugAIUtility public static Job IngestAndTakeToInventoryJob(Thing drug, Pawn pawn, int maxNumToCarry = 9999) { Job job = new Job(JobDefOf.Ingest, drug); - job.count = Mathf.Min(new int[] - { - drug.stackCount, - drug.def.ingestible.maxNumToIngestAtOnce, - maxNumToCarry - }); + job.count = Mathf.Min(drug.stackCount, drug.def.ingestible.maxNumToIngestAtOnce, maxNumToCarry); if (drug.Spawned && pawn.drugs != null && !pawn.inventory.innerContainer.Contains(drug.def)) { DrugPolicyEntry drugPolicyEntry = pawn.drugs.CurrentPolicy[drug.def]; diff --git a/Assembly-CSharp/RimWorld/DrugCategory.cs b/Assembly-CSharp/RimWorld/DrugCategory.cs index a0739700b..0d23e5da4 100644 --- a/Assembly-CSharp/RimWorld/DrugCategory.cs +++ b/Assembly-CSharp/RimWorld/DrugCategory.cs @@ -1,13 +1,11 @@ -using System; - namespace RimWorld { public enum DrugCategory { - None, - Any, - Medical, - Social, - Hard + None = 0, + Any = 1, + Medical = 2, + Social = 3, + Hard = 4 } } diff --git a/Assembly-CSharp/RimWorld/DrugDesireCategory.cs b/Assembly-CSharp/RimWorld/DrugDesireCategory.cs index d7410f4a8..1ea8b8e5f 100644 --- a/Assembly-CSharp/RimWorld/DrugDesireCategory.cs +++ b/Assembly-CSharp/RimWorld/DrugDesireCategory.cs @@ -1,11 +1,9 @@ -using System; - namespace RimWorld { public enum DrugDesireCategory : byte { - Withdrawal, - Desire, - Satisfied + Withdrawal = 0, + Desire = 1, + Satisfied = 2 } } diff --git a/Assembly-CSharp/RimWorld/DrugPolicy.cs b/Assembly-CSharp/RimWorld/DrugPolicy.cs index 11e34ef56..a380257fa 100644 --- a/Assembly-CSharp/RimWorld/DrugPolicy.cs +++ b/Assembly-CSharp/RimWorld/DrugPolicy.cs @@ -60,29 +60,28 @@ public DrugPolicy(int uniqueId, string label) public void InitializeIfNeeded() { - if (this.entriesInt != null) + if (this.entriesInt == null) { - return; - } - this.entriesInt = new List(); - List allDefsListForReading = DefDatabase.AllDefsListForReading; - for (int i = 0; i < allDefsListForReading.Count; i++) - { - if (allDefsListForReading[i].category == ThingCategory.Item && allDefsListForReading[i].IsDrug) + this.entriesInt = new List(); + List allDefsListForReading = DefDatabase.AllDefsListForReading; + for (int i = 0; i < allDefsListForReading.Count; i++) { - DrugPolicyEntry drugPolicyEntry = new DrugPolicyEntry(); - drugPolicyEntry.drug = allDefsListForReading[i]; - drugPolicyEntry.allowedForAddiction = true; - this.entriesInt.Add(drugPolicyEntry); + if (allDefsListForReading[i].category == ThingCategory.Item && allDefsListForReading[i].IsDrug) + { + DrugPolicyEntry drugPolicyEntry = new DrugPolicyEntry(); + drugPolicyEntry.drug = allDefsListForReading[i]; + drugPolicyEntry.allowedForAddiction = true; + this.entriesInt.Add(drugPolicyEntry); + } } + this.entriesInt.SortBy((Func)((DrugPolicyEntry e) => e.drug.GetCompProperties().listOrder)); } - this.entriesInt.SortBy((DrugPolicyEntry e) => e.drug.GetCompProperties().listOrder); } public void ExposeData() { Scribe_Values.Look(ref this.uniqueId, "uniqueId", 0, false); - Scribe_Values.Look(ref this.label, "label", null, false); + Scribe_Values.Look(ref this.label, "label", (string)null, false); Scribe_Collections.Look(ref this.entriesInt, "drugs", LookMode.Deep, new object[0]); } diff --git a/Assembly-CSharp/RimWorld/DrugPolicyDatabase.cs b/Assembly-CSharp/RimWorld/DrugPolicyDatabase.cs index 7dc808732..35ada4a56 100644 --- a/Assembly-CSharp/RimWorld/DrugPolicyDatabase.cs +++ b/Assembly-CSharp/RimWorld/DrugPolicyDatabase.cs @@ -38,14 +38,11 @@ public DrugPolicy DefaultDrugPolicy() public AcceptanceReport TryDelete(DrugPolicy policy) { - foreach (Pawn current in PawnsFinder.AllMapsCaravansAndTravelingTransportPods) + foreach (Pawn allMapsCaravansAndTravelingTransportPod in PawnsFinder.AllMapsCaravansAndTravelingTransportPods) { - if (current.drugs != null && current.drugs.CurrentPolicy == policy) + if (allMapsCaravansAndTravelingTransportPod.drugs != null && allMapsCaravansAndTravelingTransportPod.drugs.CurrentPolicy == policy) { - return new AcceptanceReport("DrugPolicyInUse".Translate(new object[] - { - current - })); + return new AcceptanceReport("DrugPolicyInUse".Translate(allMapsCaravansAndTravelingTransportPod)); } } this.policies.Remove(policy); @@ -54,16 +51,7 @@ public AcceptanceReport TryDelete(DrugPolicy policy) public DrugPolicy MakeNewDrugPolicy() { - int arg_40_0; - if (this.policies.Any()) - { - arg_40_0 = this.policies.Max((DrugPolicy o) => o.uniqueId) + 1; - } - else - { - arg_40_0 = 1; - } - int uniqueId = arg_40_0; + int uniqueId = (!this.policies.Any()) ? 1 : (this.policies.Max((Func)((DrugPolicy o) => o.uniqueId)) + 1); DrugPolicy drugPolicy = new DrugPolicy(uniqueId, "DrugPolicy".Translate() + " " + uniqueId.ToString()); this.policies.Add(drugPolicy); return drugPolicy; diff --git a/Assembly-CSharp/RimWorld/DrugPolicyEntry.cs b/Assembly-CSharp/RimWorld/DrugPolicyEntry.cs index 29ea51d47..d04441638 100644 --- a/Assembly-CSharp/RimWorld/DrugPolicyEntry.cs +++ b/Assembly-CSharp/RimWorld/DrugPolicyEntry.cs @@ -1,4 +1,3 @@ -using System; using Verse; namespace RimWorld diff --git a/Assembly-CSharp/RimWorld/DrugTakeRecord.cs b/Assembly-CSharp/RimWorld/DrugTakeRecord.cs index 1fe48a35b..6176a1538 100644 --- a/Assembly-CSharp/RimWorld/DrugTakeRecord.cs +++ b/Assembly-CSharp/RimWorld/DrugTakeRecord.cs @@ -1,4 +1,3 @@ -using System; using Verse; namespace RimWorld diff --git a/Assembly-CSharp/RimWorld/DutyDefOf.cs b/Assembly-CSharp/RimWorld/DutyDefOf.cs index 8dff62e70..210d5efe3 100644 --- a/Assembly-CSharp/RimWorld/DutyDefOf.cs +++ b/Assembly-CSharp/RimWorld/DutyDefOf.cs @@ -1,4 +1,3 @@ -using System; using Verse.AI; namespace RimWorld diff --git a/Assembly-CSharp/RimWorld/EffecterDefOf.cs b/Assembly-CSharp/RimWorld/EffecterDefOf.cs index 64bf3f84e..5a7e3b89e 100644 --- a/Assembly-CSharp/RimWorld/EffecterDefOf.cs +++ b/Assembly-CSharp/RimWorld/EffecterDefOf.cs @@ -1,4 +1,3 @@ -using System; using Verse; namespace RimWorld diff --git a/Assembly-CSharp/RimWorld/EventPack.cs b/Assembly-CSharp/RimWorld/EventPack.cs index c35e6b662..951883e11 100644 --- a/Assembly-CSharp/RimWorld/EventPack.cs +++ b/Assembly-CSharp/RimWorld/EventPack.cs @@ -1,4 +1,3 @@ -using System; using System.Collections.Generic; using Verse; diff --git a/Assembly-CSharp/RimWorld/ExecutionUtility.cs b/Assembly-CSharp/RimWorld/ExecutionUtility.cs index ef2ddce21..00da5ee62 100644 --- a/Assembly-CSharp/RimWorld/ExecutionUtility.cs +++ b/Assembly-CSharp/RimWorld/ExecutionUtility.cs @@ -11,8 +11,8 @@ public static void DoExecutionByCut(Pawn executioner, Pawn victim) { Map map = victim.Map; IntVec3 position = victim.Position; - int num = Mathf.Max(GenMath.RoundRandom(victim.BodySize * 8f), 1); - for (int i = 0; i < num; i++) + int num = Mathf.Max(GenMath.RoundRandom((float)(victim.BodySize * 8.0)), 1); + for (int num2 = 0; num2 < num; num2++) { victim.health.DropBloodFilth(); } @@ -24,7 +24,7 @@ public static void DoExecutionByCut(Pawn executioner, Pawn victim) { victim.Kill(new DamageInfo?(damageInfo)); } - Thing thing = position.GetThingList(map).FirstOrDefault((Thing t) => t is Corpse && ((Corpse)t).InnerPawn == victim); + Thing thing = position.GetThingList(map).FirstOrDefault((Func)((Thing t) => t is Corpse && ((Corpse)t).InnerPawn == victim)); if (thing != null) { thing.SetForbiddenIfOutsideHomeArea(); @@ -33,33 +33,33 @@ public static void DoExecutionByCut(Pawn executioner, Pawn victim) private static BodyPartRecord ExecuteCutPart(Pawn pawn) { - BodyPartRecord bodyPartRecord = pawn.health.hediffSet.GetNotMissingParts(BodyPartHeight.Undefined, BodyPartDepth.Undefined).FirstOrDefault((BodyPartRecord x) => x.def == BodyPartDefOf.Neck); + BodyPartRecord bodyPartRecord = pawn.health.hediffSet.GetNotMissingParts(BodyPartHeight.Undefined, BodyPartDepth.Undefined).FirstOrDefault((Func)((BodyPartRecord x) => x.def == BodyPartDefOf.Neck)); if (bodyPartRecord != null) { return bodyPartRecord; } - bodyPartRecord = pawn.health.hediffSet.GetNotMissingParts(BodyPartHeight.Undefined, BodyPartDepth.Undefined).FirstOrDefault((BodyPartRecord x) => x.def == BodyPartDefOf.Head); + bodyPartRecord = pawn.health.hediffSet.GetNotMissingParts(BodyPartHeight.Undefined, BodyPartDepth.Undefined).FirstOrDefault((Func)((BodyPartRecord x) => x.def == BodyPartDefOf.Head)); if (bodyPartRecord != null) { return bodyPartRecord; } - bodyPartRecord = pawn.health.hediffSet.GetNotMissingParts(BodyPartHeight.Undefined, BodyPartDepth.Undefined).FirstOrDefault((BodyPartRecord x) => x.def == BodyPartDefOf.InsectHead); + bodyPartRecord = pawn.health.hediffSet.GetNotMissingParts(BodyPartHeight.Undefined, BodyPartDepth.Undefined).FirstOrDefault((Func)((BodyPartRecord x) => x.def == BodyPartDefOf.InsectHead)); if (bodyPartRecord != null) { return bodyPartRecord; } - bodyPartRecord = pawn.health.hediffSet.GetNotMissingParts(BodyPartHeight.Undefined, BodyPartDepth.Undefined).FirstOrDefault((BodyPartRecord x) => x.def == BodyPartDefOf.Body); + bodyPartRecord = pawn.health.hediffSet.GetNotMissingParts(BodyPartHeight.Undefined, BodyPartDepth.Undefined).FirstOrDefault((Func)((BodyPartRecord x) => x.def == BodyPartDefOf.Body)); if (bodyPartRecord != null) { return bodyPartRecord; } - bodyPartRecord = pawn.health.hediffSet.GetNotMissingParts(BodyPartHeight.Undefined, BodyPartDepth.Undefined).FirstOrDefault((BodyPartRecord x) => x.def == BodyPartDefOf.Torso); + bodyPartRecord = pawn.health.hediffSet.GetNotMissingParts(BodyPartHeight.Undefined, BodyPartDepth.Undefined).FirstOrDefault((Func)((BodyPartRecord x) => x.def == BodyPartDefOf.Torso)); if (bodyPartRecord != null) { return bodyPartRecord; } Log.Error("No good slaughter cut part found for " + pawn); - return pawn.health.hediffSet.GetNotMissingParts(BodyPartHeight.Undefined, BodyPartDepth.Undefined).RandomElementByWeight((BodyPartRecord x) => x.coverageAbsWithChildren); + return pawn.health.hediffSet.GetNotMissingParts(BodyPartHeight.Undefined, BodyPartDepth.Undefined).RandomElementByWeight((Func)((BodyPartRecord x) => x.coverageAbsWithChildren)); } } } diff --git a/Assembly-CSharp/RimWorld/ExternalHistory.cs b/Assembly-CSharp/RimWorld/ExternalHistory.cs index 6863bbef3..7a69fec0e 100644 --- a/Assembly-CSharp/RimWorld/ExternalHistory.cs +++ b/Assembly-CSharp/RimWorld/ExternalHistory.cs @@ -1,4 +1,3 @@ -using System; using System.Text; using Verse; @@ -43,12 +42,12 @@ public string AllInformation public void ExposeData() { - Scribe_Values.Look(ref this.gameVersion, "gameVersion", null, false); - Scribe_Values.Look(ref this.gameplayID, "gameplayID", null, false); - Scribe_Values.Look(ref this.userName, "userName", null, false); - Scribe_Values.Look(ref this.storytellerName, "storytellerName", null, false); - Scribe_Values.Look(ref this.realWorldDate, "realWorldDate", null, false); - Scribe_Values.Look(ref this.firstUploadDate, "firstUploadDate", null, false); + Scribe_Values.Look(ref this.gameVersion, "gameVersion", (string)null, false); + Scribe_Values.Look(ref this.gameplayID, "gameplayID", (string)null, false); + Scribe_Values.Look(ref this.userName, "userName", (string)null, false); + Scribe_Values.Look(ref this.storytellerName, "storytellerName", (string)null, false); + Scribe_Values.Look(ref this.realWorldDate, "realWorldDate", (string)null, false); + Scribe_Values.Look(ref this.firstUploadDate, "firstUploadDate", (string)null, false); Scribe_Values.Look(ref this.firstUploadTime, "firstUploadTime", 0, false); Scribe_Values.Look(ref this.devMode, "devMode", false, false); Scribe_Deep.Look(ref this.history, "history", new object[0]); diff --git a/Assembly-CSharp/RimWorld/ExternalHistoryUtility.cs b/Assembly-CSharp/RimWorld/ExternalHistoryUtility.cs index 18245314d..a20e3042f 100644 --- a/Assembly-CSharp/RimWorld/ExternalHistoryUtility.cs +++ b/Assembly-CSharp/RimWorld/ExternalHistoryUtility.cs @@ -19,10 +19,10 @@ public static IEnumerable Files { get { - ExternalHistoryUtility.<>c__IteratorA1 <>c__IteratorA = new ExternalHistoryUtility.<>c__IteratorA1(); - ExternalHistoryUtility.<>c__IteratorA1 expr_07 = <>c__IteratorA; - expr_07.$PC = -2; - return expr_07; + for (int i = 0; i < ExternalHistoryUtility.cachedFiles.Count; i++) + { + yield return ExternalHistoryUtility.cachedFiles[i]; + } } } @@ -32,7 +32,7 @@ static ExternalHistoryUtility() ExternalHistoryUtility.gameplayIDAvailableChars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890"; try { - ExternalHistoryUtility.cachedFiles = GenFilePaths.AllExternalHistoryFiles.ToList(); + ExternalHistoryUtility.cachedFiles = GenFilePaths.AllExternalHistoryFiles.ToList(); } catch (Exception ex) { @@ -49,21 +49,25 @@ public static ExternalHistory Load(string path) Scribe.loader.InitLoading(path); try { - Scribe_Deep.Look(ref result, "externalHistory", new object[0]); + Scribe_Deep.Look(ref result, "externalHistory"); Scribe.loader.FinalizeLoading(); + return result; } catch { Scribe.ForceStop(); throw; + IL_003c: + return result; } } catch (Exception ex) { Log.Error("Could not load external history (" + path + "): " + ex.Message); return null; + IL_0069: + return result; } - return result; } public static string GetRandomGameplayID() @@ -79,27 +83,30 @@ public static string GetRandomGameplayID() public static bool IsValidGameplayID(string ID) { - if (ID.NullOrEmpty() || ID.Length != ExternalHistoryUtility.gameplayIDLength) - { - return false; - } - for (int i = 0; i < ID.Length; i++) + if (!ID.NullOrEmpty() && ID.Length == ExternalHistoryUtility.gameplayIDLength) { - bool flag = false; - for (int j = 0; j < ExternalHistoryUtility.gameplayIDAvailableChars.Length; j++) + for (int i = 0; i < ID.Length; i++) { - if (ID[i] == ExternalHistoryUtility.gameplayIDAvailableChars[j]) + bool flag = false; + int num = 0; + while (num < ExternalHistoryUtility.gameplayIDAvailableChars.Length) { + if (ID[i] != ExternalHistoryUtility.gameplayIDAvailableChars[num]) + { + num++; + continue; + } flag = true; break; } + if (!flag) + { + return false; + } } - if (!flag) - { - return false; - } + return true; } - return true; + return false; } public static string GetCurrentUploadDate() diff --git a/Assembly-CSharp/RimWorld/FacilitiesUtility.cs b/Assembly-CSharp/RimWorld/FacilitiesUtility.cs index a7819e939..f3bcc88b4 100644 --- a/Assembly-CSharp/RimWorld/FacilitiesUtility.cs +++ b/Assembly-CSharp/RimWorld/FacilitiesUtility.cs @@ -1,4 +1,3 @@ -using System; using System.Collections.Generic; using UnityEngine; using Verse; @@ -18,44 +17,46 @@ public static void NotifyFacilitiesAboutChangedLOSBlockers(List affected if (FacilitiesUtility.working) { Log.Warning("Tried to update facilities while already updating."); - return; } - FacilitiesUtility.working = true; - ProfilerThreadCheck.BeginSample("NotifyFacilitiesAboutChangedLOSBlockers()"); - try + else { - FacilitiesUtility.visited.Clear(); - for (int i = 0; i < affectedRegions.Count; i++) + FacilitiesUtility.working = true; + ProfilerThreadCheck.BeginSample("NotifyFacilitiesAboutChangedLOSBlockers()"); + try { - if (!FacilitiesUtility.visited.Contains(affectedRegions[i])) + FacilitiesUtility.visited.Clear(); + for (int i = 0; i < affectedRegions.Count; i++) { - RegionTraverser.BreadthFirstTraverse(affectedRegions[i], (Region from, Region r) => !FacilitiesUtility.visited.Contains(r), delegate(Region x) + if (!FacilitiesUtility.visited.Contains(affectedRegions[i])) { - FacilitiesUtility.visited.Add(x); - List list = x.ListerThings.ThingsInGroup(ThingRequestGroup.BuildingArtificial); - for (int j = 0; j < list.Count; j++) + RegionTraverser.BreadthFirstTraverse(affectedRegions[i], (RegionEntryPredicate)((Region from, Region r) => !FacilitiesUtility.visited.Contains(r)), (RegionProcessor)delegate(Region x) { - CompFacility compFacility = list[j].TryGetComp(); - CompAffectedByFacilities compAffectedByFacilities = list[j].TryGetComp(); - if (compFacility != null) + FacilitiesUtility.visited.Add(x); + List list = x.ListerThings.ThingsInGroup(ThingRequestGroup.BuildingArtificial); + for (int j = 0; j < list.Count; j++) { - compFacility.Notify_LOSBlockerSpawnedOrDespawned(); + CompFacility compFacility = list[j].TryGetComp(); + CompAffectedByFacilities compAffectedByFacilities = list[j].TryGetComp(); + if (compFacility != null) + { + compFacility.Notify_LOSBlockerSpawnedOrDespawned(); + } + if (compAffectedByFacilities != null) + { + compAffectedByFacilities.Notify_LOSBlockerSpawnedOrDespawned(); + } } - if (compAffectedByFacilities != null) - { - compAffectedByFacilities.Notify_LOSBlockerSpawnedOrDespawned(); - } - } - return false; - }, FacilitiesUtility.RegionsToSearch, RegionType.Set_Passable); + return false; + }, FacilitiesUtility.RegionsToSearch, RegionType.Set_Passable); + } } } - } - finally - { - ProfilerThreadCheck.EndSample(); - FacilitiesUtility.working = false; - FacilitiesUtility.visited.Clear(); + finally + { + ProfilerThreadCheck.EndSample(); + FacilitiesUtility.working = false; + FacilitiesUtility.visited.Clear(); + } } } } diff --git a/Assembly-CSharp/RimWorld/Faction.cs b/Assembly-CSharp/RimWorld/Faction.cs index 91dd7696e..eecfd00ad 100644 --- a/Assembly-CSharp/RimWorld/Faction.cs +++ b/Assembly-CSharp/RimWorld/Faction.cs @@ -119,7 +119,7 @@ public Color Color { get { - if (this.def.colorSpectrum.NullOrEmpty()) + if (this.def.colorSpectrum.NullOrEmpty()) { return Color.white; } @@ -192,13 +192,13 @@ public void ExposeData() Scribe_Collections.Look(ref this.avoidGridsBasic, "avoidGridsBasic", LookMode.Reference, LookMode.Deep, ref this.avoidGridsBasicKeysWorkingList, ref this.avoidGridsBasicValuesWorkingList); Scribe_Collections.Look(ref this.avoidGridsSmart, "avoidGridsSmart", LookMode.Reference, LookMode.Deep, ref this.avoidGridsSmartKeysWorkingList, ref this.avoidGridsSmartValuesWorkingList); Scribe_Defs.Look(ref this.def, "def"); - Scribe_Values.Look(ref this.name, "name", null, false); + Scribe_Values.Look(ref this.name, "name", (string)null, false); Scribe_Values.Look(ref this.loadID, "loadID", 0, false); Scribe_Values.Look(ref this.randomKey, "randomKey", 0, false); Scribe_Values.Look(ref this.colorFromSpectrum, "colorFromSpectrum", 0f, false); Scribe_Collections.Look(ref this.relations, "relations", LookMode.Deep, new object[0]); Scribe_Deep.Look(ref this.tacticalMemoryInt, "tacticalMemory", new object[0]); - Scribe_Deep.Look(ref this.kidnapped, "kidnapped", new object[] + Scribe_Deep.Look(ref this.kidnapped, "kidnapped", new object[1] { this }); @@ -213,20 +213,20 @@ public void FactionTick() { if (this.PlayerGoodwill < this.def.naturalColonyGoodwill.min) { - this.AffectGoodwillWith(Faction.OfPlayer, this.def.goodwillDailyGain * 0f); + this.AffectGoodwillWith(Faction.OfPlayer, (float)(this.def.goodwillDailyGain * 0.0)); } else if (this.PlayerGoodwill > this.def.naturalColonyGoodwill.max) { - this.AffectGoodwillWith(Faction.OfPlayer, -this.def.goodwillDailyFall * 0f); + this.AffectGoodwillWith(Faction.OfPlayer, (float)((0.0 - this.def.goodwillDailyFall) * 0.0)); } } this.kidnapped.KidnappedPawnsTrackerTick(); - for (int i = this.predatorThreats.Count - 1; i >= 0; i--) + for (int num = this.predatorThreats.Count - 1; num >= 0; num--) { - PredatorThreat predatorThreat = this.predatorThreats[i]; + PredatorThreat predatorThreat = this.predatorThreats[num]; if (predatorThreat.Expired) { - this.predatorThreats.RemoveAt(i); + this.predatorThreats.RemoveAt(num); if (predatorThreat.predator.Spawned) { predatorThreat.predator.Map.attackTargetsCache.UpdateTarget(predatorThreat.predator); @@ -237,7 +237,7 @@ public void FactionTick() { if (NamePlayerFactionAndBaseUtility.CanNameFactionNow()) { - FactionBase factionBase = Find.WorldObjects.FactionBases.Find((FactionBase x) => NamePlayerFactionAndBaseUtility.CanNameFactionBaseSoon(x)); + FactionBase factionBase = Find.WorldObjects.FactionBases.Find((Predicate)((FactionBase x) => NamePlayerFactionAndBaseUtility.CanNameFactionBaseSoon(x))); if (factionBase != null) { Find.WindowStack.Add(new Dialog_NamePlayerFactionAndBase(factionBase)); @@ -249,7 +249,7 @@ public void FactionTick() } else { - FactionBase factionBase2 = Find.WorldObjects.FactionBases.Find((FactionBase x) => NamePlayerFactionAndBaseUtility.CanNameFactionBaseNow(x)); + FactionBase factionBase2 = Find.WorldObjects.FactionBases.Find((Predicate)((FactionBase x) => NamePlayerFactionAndBaseUtility.CanNameFactionBaseNow(x))); if (factionBase2 != null) { if (NamePlayerFactionAndBaseUtility.CanNameFactionSoon()) @@ -267,7 +267,7 @@ public void FactionTick() public ByteGrid GetAvoidGridBasic(Map map) { - ByteGrid result; + ByteGrid result = default(ByteGrid); if (this.avoidGridsBasic.TryGetValue(map, out result)) { return result; @@ -277,7 +277,7 @@ public ByteGrid GetAvoidGridBasic(Map map) public ByteGrid GetAvoidGridSmart(Map map) { - ByteGrid result; + ByteGrid result = default(ByteGrid); if (this.avoidGridsSmart.TryGetValue(map, out result)) { return result; @@ -294,31 +294,30 @@ public void Notify_MapRemoved(Map map) public void TryMakeInitialRelationsWith(Faction other) { - if (this.RelationWith(other, true) != null) + if (this.RelationWith(other, true) == null) { - return; - } - float a = this.def.startingGoodwill.RandomInRange; - if (this.IsPlayer) - { - a = 100f; - } - float b = other.def.startingGoodwill.RandomInRange; - if (other.IsPlayer) - { - b = 100f; + float a = this.def.startingGoodwill.RandomInRange; + if (this.IsPlayer) + { + a = 100f; + } + float b = other.def.startingGoodwill.RandomInRange; + if (other.IsPlayer) + { + b = 100f; + } + float num = Mathf.Min(a, b); + FactionRelation factionRelation = new FactionRelation(); + factionRelation.other = other; + factionRelation.goodwill = num; + factionRelation.hostile = (num < -40.0); + this.relations.Add(factionRelation); + FactionRelation factionRelation2 = new FactionRelation(); + factionRelation2.other = this; + factionRelation2.goodwill = num; + factionRelation2.hostile = (num < -40.0); + other.relations.Add(factionRelation2); } - float num = Mathf.Min(a, b); - FactionRelation factionRelation = new FactionRelation(); - factionRelation.other = other; - factionRelation.goodwill = num; - factionRelation.hostile = (num < -40f); - this.relations.Add(factionRelation); - FactionRelation factionRelation2 = new FactionRelation(); - factionRelation2.other = this; - factionRelation2.goodwill = num; - factionRelation2.hostile = (num < -40f); - other.relations.Add(factionRelation2); } public PawnKindDef RandomPawnKind() @@ -335,11 +334,11 @@ public PawnKindDef RandomPawnKind() } } } - if (!Faction.allPawnKinds.Any()) + if (!Faction.allPawnKinds.Any()) { return this.def.basicMemberKind; } - PawnKindDef result = Faction.allPawnKinds.RandomElement(); + PawnKindDef result = Faction.allPawnKinds.RandomElement(); Faction.allPawnKinds.Clear(); return result; } @@ -360,14 +359,7 @@ public FactionRelation RelationWith(Faction other, bool allowNull = false) } if (!allowNull) { - Log.Error(string.Concat(new object[] - { - "Faction ", - this.name, - " has null relation with ", - other, - ". Returning dummy relation." - })); + Log.Error("Faction " + this.name + " has null relation with " + other + ". Returning dummy relation."); return new FactionRelation(); } return null; @@ -380,102 +372,116 @@ public float GoodwillWith(Faction other) public bool AffectGoodwillWith(Faction other, float goodwillChange) { - if (this.def.hidden || other.def.hidden) + if (!this.def.hidden && !other.def.hidden) { - return false; - } - if (goodwillChange > 0f && !this.def.appreciative) - { - return false; - } - if (goodwillChange > 0f && ((this.IsPlayer && SettlementUtility.IsPlayerAttackingAnySettlementOf(other)) || (other.IsPlayer && SettlementUtility.IsPlayerAttackingAnySettlementOf(this)))) - { - return false; - } - float num = this.GoodwillWith(other); - float value = num + goodwillChange; - FactionRelation factionRelation = this.RelationWith(other, false); - factionRelation.goodwill = Mathf.Clamp(value, -100f, 100f); - if (!this.HostileTo(other) && this.GoodwillWith(other) < -80f) - { - this.SetHostileTo(other, true); - if (Current.ProgramState == ProgramState.Playing && Find.TickManager.TicksGame > 100 && other == Faction.OfPlayer) + if (goodwillChange > 0.0 && !this.def.appreciative) { - Find.LetterStack.ReceiveLetter("LetterLabelRelationsChangeBad".Translate(), "RelationsBrokenDown".Translate(new object[] + return false; + } + if (goodwillChange > 0.0) + { + if (this.IsPlayer && SettlementUtility.IsPlayerAttackingAnySettlementOf(other)) { - this.name - }), LetterDefOf.BadNonUrgent, null); + goto IL_0076; + } + if (other.IsPlayer && SettlementUtility.IsPlayerAttackingAnySettlementOf(this)) + goto IL_0076; } - } - if (this.HostileTo(other) && this.GoodwillWith(other) > 0f) - { - this.SetHostileTo(other, false); - if (Current.ProgramState == ProgramState.Playing && Find.TickManager.TicksGame > 100 && other == Faction.OfPlayer) + float num = this.GoodwillWith(other); + float value = num + goodwillChange; + FactionRelation factionRelation = this.RelationWith(other, false); + factionRelation.goodwill = Mathf.Clamp(value, -100f, 100f); + if (!this.HostileTo(other) && this.GoodwillWith(other) < -80.0) { - Find.LetterStack.ReceiveLetter("LetterLabelRelationsChangeGood".Translate(), "RelationsWarmed".Translate(new object[] + this.SetHostileTo(other, true); + if (Current.ProgramState == ProgramState.Playing && Find.TickManager.TicksGame > 100 && other == Faction.OfPlayer) { - this.name - }), LetterDefOf.BadNonUrgent, null); + Find.LetterStack.ReceiveLetter("LetterLabelRelationsChangeBad".Translate(), "RelationsBrokenDown".Translate(this.name), LetterDefOf.BadNonUrgent, (string)null); + } } + if (this.HostileTo(other) && this.GoodwillWith(other) > 0.0) + { + this.SetHostileTo(other, false); + if (Current.ProgramState == ProgramState.Playing && Find.TickManager.TicksGame > 100 && other == Faction.OfPlayer) + { + Find.LetterStack.ReceiveLetter("LetterLabelRelationsChangeGood".Translate(), "RelationsWarmed".Translate(this.name), LetterDefOf.BadNonUrgent, (string)null); + } + } + return this.def.appreciative && (goodwillChange > 0.0 || factionRelation.goodwill != num); } - return this.def.appreciative && (goodwillChange > 0f || factionRelation.goodwill != num); + return false; + IL_0076: + return false; } public void SetHostileTo(Faction other, bool hostile) { - if (this.def.hidden || other.def.hidden) - { - return; - } - FactionRelation factionRelation = this.RelationWith(other, false); - if (hostile) + if (!this.def.hidden && !other.def.hidden) { - if (Current.ProgramState == ProgramState.Playing) + FactionRelation factionRelation = this.RelationWith(other, false); + if (hostile) { - foreach (Pawn current in PawnsFinder.AllMapsAndWorld_Alive.ToList()) + if (Current.ProgramState == ProgramState.Playing) { - if ((current.Faction == this && current.HostFaction == other) || (current.Faction == other && current.HostFaction == this)) + List.Enumerator enumerator = PawnsFinder.AllMapsAndWorld_Alive.ToList().GetEnumerator(); + try + { + while (enumerator.MoveNext()) + { + Pawn current = enumerator.Current; + if (current.Faction == this && current.HostFaction == other) + { + goto IL_0088; + } + if (current.Faction == other && current.HostFaction == this) + goto IL_0088; + continue; + IL_0088: + current.guest.SetGuestStatus(current.HostFaction, true); + } + } + finally { - current.guest.SetGuestStatus(current.HostFaction, true); + ((IDisposable)(object)enumerator).Dispose(); } } - } - if (!factionRelation.hostile) - { - other.RelationWith(this, false).hostile = true; - factionRelation.hostile = true; - if (factionRelation.goodwill > -80f) + if (!factionRelation.hostile) { - factionRelation.goodwill = -80f; + other.RelationWith(this, false).hostile = true; + factionRelation.hostile = true; + if (factionRelation.goodwill > -80.0) + { + factionRelation.goodwill = -80f; + } } } - } - else if (factionRelation.hostile) - { - other.RelationWith(this, false).hostile = false; - factionRelation.hostile = false; - if (factionRelation.goodwill < 0f) + else if (factionRelation.hostile) { - factionRelation.goodwill = 0f; + other.RelationWith(this, false).hostile = false; + factionRelation.hostile = false; + if (factionRelation.goodwill < 0.0) + { + factionRelation.goodwill = 0f; + } } - } - if (Current.ProgramState == ProgramState.Playing) - { - List maps = Find.Maps; - for (int i = 0; i < maps.Count; i++) + if (Current.ProgramState == ProgramState.Playing) { - maps[i].attackTargetsCache.Notify_FactionHostilityChanged(this, other); - LordManager lordManager = maps[i].lordManager; - for (int j = 0; j < lordManager.lords.Count; j++) + List maps = Find.Maps; + for (int i = 0; i < maps.Count; i++) { - Lord lord = lordManager.lords[j]; - if (lord.faction == other) - { - lord.Notify_FactionRelationsChanged(this); - } - else if (lord.faction == this) + maps[i].attackTargetsCache.Notify_FactionHostilityChanged(this, other); + LordManager lordManager = maps[i].lordManager; + for (int j = 0; j < lordManager.lords.Count; j++) { - lord.Notify_FactionRelationsChanged(other); + Lord lord = lordManager.lords[j]; + if (lord.faction == other) + { + lord.Notify_FactionRelationsChanged(this); + } + else if (lord.faction == this) + { + lord.Notify_FactionRelationsChanged(other); + } } } } @@ -484,104 +490,87 @@ public void SetHostileTo(Faction other, bool hostile) public void RemoveAllRelations() { - foreach (Faction current in Find.FactionManager.AllFactionsListForReading) + List.Enumerator enumerator = Find.FactionManager.AllFactionsListForReading.GetEnumerator(); + try { - if (current != this) + while (enumerator.MoveNext()) { - current.relations.RemoveAll((FactionRelation x) => x.other == this); + Faction current = enumerator.Current; + if (current != this) + { + current.relations.RemoveAll((Predicate)((FactionRelation x) => x.other == this)); + } } } + finally + { + ((IDisposable)(object)enumerator).Dispose(); + } this.relations.Clear(); } public void Notify_MemberTookDamage(Pawn member, DamageInfo dinfo) { - if (dinfo.Instigator == null) - { - return; - } - Pawn pawn = dinfo.Instigator as Pawn; - if (pawn != null && pawn.CurJob != null && pawn.CurJob.def == JobDefOf.PredatorHunt) - { - this.TookDamageFromPredator(pawn); - } - if (dinfo.Instigator.Faction == null || !dinfo.Def.externalViolence || this.HostileTo(dinfo.Instigator.Faction)) - { - return; - } - if (member.InMentalState && member.MentalStateDef.IsAggro) - { - return; - } - Pawn pawn2 = dinfo.Instigator as Pawn; - if (pawn2 != null && pawn2.InMentalState && pawn2.MentalStateDef == MentalStateDefOf.Berserk) + if (dinfo.Instigator != null) { - return; - } - if (dinfo.Instigator.Faction == Faction.OfPlayer && PrisonBreakUtility.IsPrisonBreaking(member)) - { - return; - } - float num = (float)Mathf.Min(100, dinfo.Amount); - float goodwillChange = -1.3f * num; - if (dinfo.Instigator.Faction == Faction.OfPlayer && this != Faction.OfPlayer) - { - this.AffectGoodwillWith(dinfo.Instigator.Faction, goodwillChange); + Pawn pawn = dinfo.Instigator as Pawn; + if (pawn != null && pawn.CurJob != null && pawn.CurJob.def == JobDefOf.PredatorHunt) + { + this.TookDamageFromPredator(pawn); + } + if (dinfo.Instigator.Faction != null && dinfo.Def.externalViolence && !this.HostileTo(dinfo.Instigator.Faction) && (!member.InMentalState || !member.MentalStateDef.IsAggro)) + { + Pawn pawn2 = dinfo.Instigator as Pawn; + if (pawn2 != null && pawn2.InMentalState && pawn2.MentalStateDef == MentalStateDefOf.Berserk) + return; + if (dinfo.Instigator.Faction == Faction.OfPlayer && PrisonBreakUtility.IsPrisonBreaking(member)) + return; + float num = (float)Mathf.Min(100, dinfo.Amount); + float goodwillChange = (float)(-1.2999999523162842 * num); + if (dinfo.Instigator.Faction == Faction.OfPlayer && this != Faction.OfPlayer) + { + this.AffectGoodwillWith(dinfo.Instigator.Faction, goodwillChange); + } + } } } public void Notify_MemberCaptured(Pawn member, Faction violator) { - if (violator == this || this.HostileTo(violator) || member.Faction.def.hidden || violator.def.hidden) + if (violator != this && !this.HostileTo(violator) && !member.Faction.def.hidden && !violator.def.hidden) { - return; + this.SetHostileTo(violator, true); + Find.LetterStack.ReceiveLetter("LetterLabelRelationsChangeBad".Translate().CapitalizeFirst(), "RelationsBrokenCapture".Translate(member, this.name), LetterDefOf.BadNonUrgent, (Thing)member, (string)null); } - this.SetHostileTo(violator, true); - Find.LetterStack.ReceiveLetter("LetterLabelRelationsChangeBad".Translate().CapitalizeFirst(), "RelationsBrokenCapture".Translate(new object[] - { - member, - this.name - }), LetterDefOf.BadNonUrgent, member, null); } public void Notify_MemberDied(Pawn member, DamageInfo? dinfo, bool wasWorldPawn) { - if (this.IsPlayer) + if (!this.IsPlayer) { - return; - } - if (!wasWorldPawn && !PawnGenerator.IsBeingGenerated(member) && Current.ProgramState == ProgramState.Playing) - { - if (dinfo.HasValue && dinfo.Value.Category == DamageInfo.SourceCategory.Collapse) + if (!wasWorldPawn && !PawnGenerator.IsBeingGenerated(member) && Current.ProgramState == ProgramState.Playing) { - float num = member.RaceProps.body.corePart.def.GetMaxHealth(member) * 1.3f * 0.5f * -1f; - bool flag = this.AffectGoodwillWith(Faction.OfPlayer, num); - if (flag && MessagesRepeatAvoider.MessageShowAllowed("FactionRelationAdjustmentCrushed-" + this.Name, 5f)) + if (dinfo.HasValue && dinfo.Value.Category == DamageInfo.SourceCategory.Collapse) { - Messages.Message("MessageFactionPawnCrushed".Translate(new object[] + float num = (float)(member.RaceProps.body.corePart.def.GetMaxHealth(member) * 1.2999999523162842 * 0.5 * -1.0); + if (this.AffectGoodwillWith(Faction.OfPlayer, num) && MessagesRepeatAvoider.MessageShowAllowed("FactionRelationAdjustmentCrushed-" + this.Name, 5f)) { - this.Name, - Mathf.RoundToInt(num) - }), member, MessageSound.SeriousAlert); + Messages.Message("MessageFactionPawnCrushed".Translate(this.Name, Mathf.RoundToInt(num)), (Thing)member, MessageSound.SeriousAlert); + } } - } - else if (dinfo.HasValue && (dinfo.Value.Instigator == null || dinfo.Value.Instigator.Faction == null)) - { - float num2 = member.RaceProps.body.corePart.def.GetMaxHealth(member) * 1.3f * 0.1f * -1f; - if (this.AffectGoodwillWith(Faction.OfPlayer, num2)) + else if (dinfo.HasValue && (dinfo.Value.Instigator == null || dinfo.Value.Instigator.Faction == null)) { - Messages.Message("MessageFactionPawnLost".Translate(new object[] + float num2 = (float)(member.RaceProps.body.corePart.def.GetMaxHealth(member) * 1.2999999523162842 * 0.10000000149011612 * -1.0); + if (this.AffectGoodwillWith(Faction.OfPlayer, num2)) { - this.Name, - member.NameStringShort, - Mathf.RoundToInt(num2) - }), member, MessageSound.SeriousAlert); + Messages.Message("MessageFactionPawnLost".Translate(this.Name, member.NameStringShort, Mathf.RoundToInt(num2)), (Thing)member, MessageSound.SeriousAlert); + } } } - } - if (member == this.leader) - { - this.Notify_LeaderDied(); + if (member == this.leader) + { + this.Notify_LeaderDied(); + } } } @@ -589,34 +578,14 @@ public void Notify_LeaderDied() { Pawn pawn = this.leader; this.GenerateNewLeader(); - Find.LetterStack.ReceiveLetter("LetterLeadersDeathLabel".Translate(new object[] - { - this.name, - this.def.leaderTitle - }).CapitalizeFirst(), "LetterLeadersDeath".Translate(new object[] - { - pawn.Name.ToStringFull, - this.name, - this.leader.Name.ToStringFull, - this.def.leaderTitle - }).CapitalizeFirst(), LetterDefOf.Good, null); + Find.LetterStack.ReceiveLetter("LetterLeadersDeathLabel".Translate(this.name, this.def.leaderTitle).CapitalizeFirst(), "LetterLeadersDeath".Translate(pawn.Name.ToStringFull, this.name, this.leader.Name.ToStringFull, this.def.leaderTitle).CapitalizeFirst(), LetterDefOf.Good, (string)null); } public void Notify_LeaderLost() { Pawn pawn = this.leader; this.GenerateNewLeader(); - Find.LetterStack.ReceiveLetter("LetterLeaderChangedLabel".Translate(new object[] - { - this.name, - this.def.leaderTitle - }).CapitalizeFirst(), "LetterLeaderChanged".Translate(new object[] - { - pawn.Name.ToStringFull, - this.name, - this.leader.Name.ToStringFull, - this.def.leaderTitle - }).CapitalizeFirst(), LetterDefOf.Good, null); + Find.LetterStack.ReceiveLetter("LetterLeaderChangedLabel".Translate(this.name, this.def.leaderTitle).CapitalizeFirst(), "LetterLeaderChanged".Translate(pawn.Name.ToStringFull, this.name, this.leader.Name.ToStringFull, this.def.leaderTitle).CapitalizeFirst(), LetterDefOf.Good, (string)null); } public void GenerateNewLeader() @@ -624,20 +593,29 @@ public void GenerateNewLeader() List list = new List(); if (this.def.pawnGroupMakers != null) { - foreach (PawnGroupMaker current in from x in this.def.pawnGroupMakers + foreach (PawnGroupMaker item in from x in this.def.pawnGroupMakers where x.kindDef == PawnGroupKindDefOf.Normal select x) { - foreach (PawnGenOption current2 in current.options) + List.Enumerator enumerator2 = item.options.GetEnumerator(); + try { - if (current2.kind.factionLeader) + while (enumerator2.MoveNext()) { - list.Add(current2.kind); + PawnGenOption current2 = enumerator2.Current; + if (current2.kind.factionLeader) + { + list.Add(current2.kind); + } } } + finally + { + ((IDisposable)(object)enumerator2).Dispose(); + } } - PawnKindDef kindDef; - if (list.TryRandomElement(out kindDef)) + PawnKindDef kindDef = default(PawnKindDef); + if (((IEnumerable)list).TryRandomElement(out kindDef)) { this.leader = PawnGenerator.GeneratePawn(kindDef, this); if (this.leader.RaceProps.IsFlesh) @@ -659,25 +637,10 @@ public string GetCallLabel() public string GetInfoText() { - string text = this.def.LabelCap; - string text2 = text; - text = string.Concat(new string[] - { - text2, - "\n", - "ColonyGoodwill".Translate(), - ": ", - this.PlayerGoodwill.ToString("###0") - }); - if (this.HostileTo(Faction.OfPlayer)) - { - text = text + "\n" + "Hostile".Translate(); - } - else - { - text = text + "\n" + "Neutral".Translate(); - } - return text; + string labelCap; + string text = labelCap = this.def.LabelCap; + text = labelCap + "\n" + "ColonyGoodwill".Translate() + ": " + this.PlayerGoodwill.ToString("###0"); + return (!this.HostileTo(Faction.OfPlayer)) ? (text + "\n" + "Neutral".Translate()) : (text + "\n" + "Hostile".Translate()); } public void TryOpenComms(Pawn negotiator) @@ -747,7 +710,7 @@ public string DebugString() stringBuilder.Append("Avoidgrid pathcost at mouse: "); if (UI.MouseCell().InBounds(Find.VisibleMap)) { - stringBuilder.AppendLine(((int)(avoidGridSmart[UI.MouseCell()] * 8)).ToString()); + stringBuilder.AppendLine((avoidGridSmart[UI.MouseCell()] * 8).ToString()); } } return stringBuilder.ToString(); diff --git a/Assembly-CSharp/RimWorld/FactionDef.cs b/Assembly-CSharp/RimWorld/FactionDef.cs index 6bab4b575..c17d51442 100644 --- a/Assembly-CSharp/RimWorld/FactionDef.cs +++ b/Assembly-CSharp/RimWorld/FactionDef.cs @@ -1,6 +1,5 @@ using System; using System.Collections.Generic; -using System.Diagnostics; using System.Linq; using UnityEngine; using Verse; @@ -99,7 +98,11 @@ public bool CanEverBeNonHostile { get { - return this.startingGoodwill.max >= 0f || this.appreciative; + if (this.startingGoodwill.max < 0.0 && !this.appreciative) + { + return false; + } + return true; } } @@ -107,7 +110,7 @@ public Texture2D ExpandingIconTexture { get { - if (this.expandingIconTextureInt == null) + if ((UnityEngine.Object)this.expandingIconTextureInt == (UnityEngine.Object)null) { if (!this.expandingIconTexture.NullOrEmpty()) { @@ -131,16 +134,20 @@ public float MinPointsToGenerateNormalPawnGroup() IEnumerable source = from x in this.pawnGroupMakers where x.kindDef == PawnGroupKindDefOf.Normal select x; - if (!source.Any()) + if (!source.Any()) { return 2.14748365E+09f; } - return source.Min((PawnGroupMaker pgm) => pgm.MinPointsToGenerateAnything); + return source.Min((Func)((PawnGroupMaker pgm) => pgm.MinPointsToGenerateAnything)); } public bool CanUseStuffForApparel(ThingDef stuffDef) { - return this.apparelStuffFilter == null || this.apparelStuffFilter.Allows(stuffDef); + if (this.apparelStuffFilter == null) + { + return true; + } + return this.apparelStuffFilter.Allows(stuffDef); } public override void ResolveReferences() @@ -152,14 +159,31 @@ public override void ResolveReferences() } } - [DebuggerHidden] public override IEnumerable ConfigErrors() { - FactionDef.c__Iterator8E c__Iterator8E = new FactionDef.c__Iterator8E(); - c__Iterator8E.<>f__this = this; - FactionDef.c__Iterator8E expr_0E = c__Iterator8E; - expr_0E.$PC = -2; - return expr_0E; + foreach (string item in base.ConfigErrors()) + { + yield return item; + } + if (!this.isPlayer && this.factionNameMaker == null && this.fixedName == null) + { + yield return "FactionTypeDef " + base.defName + " lacks a factionNameMaker and a fixedName."; + } + if (this.techLevel == TechLevel.Undefined) + { + yield return base.defName + " has no tech level."; + } + if (this.humanlikeFaction) + { + if (this.backstoryCategory == null) + { + yield return base.defName + " is humanlikeFaction but has no backstory category."; + } + if (this.hairTags.Count == 0) + { + yield return base.defName + " is humanlikeFaction but has no hairTags."; + } + } } public static FactionDef Named(string defName) diff --git a/Assembly-CSharp/RimWorld/FactionDefOf.cs b/Assembly-CSharp/RimWorld/FactionDefOf.cs index 70e481f92..57a943e3a 100644 --- a/Assembly-CSharp/RimWorld/FactionDefOf.cs +++ b/Assembly-CSharp/RimWorld/FactionDefOf.cs @@ -1,5 +1,3 @@ -using System; - namespace RimWorld { [DefOf] diff --git a/Assembly-CSharp/RimWorld/FactionDialogMaker.cs b/Assembly-CSharp/RimWorld/FactionDialogMaker.cs index bda7eaac6..b53559a3e 100644 --- a/Assembly-CSharp/RimWorld/FactionDialogMaker.cs +++ b/Assembly-CSharp/RimWorld/FactionDialogMaker.cs @@ -1,7 +1,6 @@ using RimWorld.Planet; using System; using System.Collections.Generic; -using System.Diagnostics; using System.Linq; using UnityEngine; using Verse; @@ -37,20 +36,13 @@ public static DiaNode FactionDialogFor(Pawn negotiator, Faction faction) FactionDialogMaker.negotiator = negotiator; FactionDialogMaker.faction = faction; string text = (faction.leader != null) ? faction.leader.Name.ToStringFull : faction.Name; - if (faction.PlayerGoodwill < -70f) + if (faction.PlayerGoodwill < -70.0) { - FactionDialogMaker.root = new DiaNode("FactionGreetingHostile".Translate(new object[] - { - text - })); + FactionDialogMaker.root = new DiaNode("FactionGreetingHostile".Translate(text)); } - else if (faction.PlayerGoodwill < 40f) + else if (faction.PlayerGoodwill < 40.0) { - string text2 = "FactionGreetingWary".Translate(new object[] - { - text, - negotiator.LabelShort - }); + string text2 = "FactionGreetingWary".Translate(text, negotiator.LabelShort); text2 = text2.AdjustedFor(negotiator); FactionDialogMaker.root = new DiaNode(text2); if (!SettlementUtility.IsPlayerAttackingAnySettlementOf(faction)) @@ -64,11 +56,7 @@ public static DiaNode FactionDialogFor(Pawn negotiator, Faction faction) } else { - FactionDialogMaker.root = new DiaNode("FactionGreetingWarm".Translate(new object[] - { - text, - negotiator.LabelShort - })); + FactionDialogMaker.root = new DiaNode("FactionGreetingWarm".Translate(text, negotiator.LabelShort)); if (!SettlementUtility.IsPlayerAttackingAnySettlementOf(faction)) { FactionDialogMaker.root.options.Add(FactionDialogMaker.OfferGiftOption(negotiator.Map)); @@ -81,9 +69,9 @@ public static DiaNode FactionDialogFor(Pawn negotiator, Faction faction) } if (Prefs.DevMode) { - foreach (DiaOption current in FactionDialogMaker.DebugOptions()) + foreach (DiaOption item in FactionDialogMaker.DebugOptions()) { - FactionDialogMaker.root.options.Add(current); + FactionDialogMaker.root.options.Add(item); } } DiaOption diaOption = new DiaOption("(" + "Disconnect".Translate() + ")"); @@ -92,20 +80,31 @@ public static DiaNode FactionDialogFor(Pawn negotiator, Faction faction) return FactionDialogMaker.root; } - [DebuggerHidden] private static IEnumerable DebugOptions() { - FactionDialogMaker.c__IteratorED c__IteratorED = new FactionDialogMaker.c__IteratorED(); - FactionDialogMaker.c__IteratorED expr_07 = c__IteratorED; - expr_07.$PC = -2; - return expr_07; + yield return new DiaOption("(Debug) Goodwill +10") + { + action = (Action)delegate + { + FactionDialogMaker.faction.AffectGoodwillWith(Faction.OfPlayer, 10f); + }, + linkLateBind = (Func)(() => FactionDialogMaker.FactionDialogFor(FactionDialogMaker.negotiator, FactionDialogMaker.faction)) + }; + yield return new DiaOption("(Debug) Goodwill -10") + { + action = (Action)delegate + { + FactionDialogMaker.faction.AffectGoodwillWith(Faction.OfPlayer, -10f); + }, + linkLateBind = (Func)(() => FactionDialogMaker.FactionDialogFor(FactionDialogMaker.negotiator, FactionDialogMaker.faction)) + }; } private static int AmountSendableSilver(Map map) { return (from t in TradeUtility.AllLaunchableThings(map) where t.def == ThingDefOf.Silver - select t).Sum((Thing t) => t.stackCount); + select t).Sum((Func)((Thing t) => t.stackCount)); } private static DiaOption OfferGiftOption(Map map) @@ -113,51 +112,30 @@ private static DiaOption OfferGiftOption(Map map) if (FactionDialogMaker.AmountSendableSilver(map) < 300) { DiaOption diaOption = new DiaOption("OfferGift".Translate()); - diaOption.Disable("NeedSilverLaunchable".Translate(new object[] - { - 300 - })); + diaOption.Disable("NeedSilverLaunchable".Translate(300)); return diaOption; } - float goodwillDelta = 12f * FactionDialogMaker.negotiator.GetStatValue(StatDefOf.GiftImpact, true); - DiaOption diaOption2 = new DiaOption("OfferGift".Translate() + " (" + "SilverForGoodwill".Translate(new object[] - { - 300, - goodwillDelta.ToString("#####0") - }) + ")"); - diaOption2.action = delegate + float goodwillDelta = (float)(12.0 * FactionDialogMaker.negotiator.GetStatValue(StatDefOf.GiftImpact, true)); + DiaOption diaOption2 = new DiaOption("OfferGift".Translate() + " (" + "SilverForGoodwill".Translate(300, goodwillDelta.ToString("#####0")) + ")"); + diaOption2.action = (Action)delegate() { TradeUtility.LaunchThingsOfType(ThingDefOf.Silver, 300, map, null); FactionDialogMaker.faction.AffectGoodwillWith(Faction.OfPlayer, goodwillDelta); }; - string text = "SilverGiftSent".Translate(new object[] - { - FactionDialogMaker.faction.leader.LabelIndefinite(), - Mathf.RoundToInt(goodwillDelta) - }).CapitalizeFirst(); - diaOption2.link = new DiaNode(text) - { - options = - { - FactionDialogMaker.OKToRoot() - } - }; + string text = "SilverGiftSent".Translate(FactionDialogMaker.faction.leader.LabelIndefinite(), Mathf.RoundToInt(goodwillDelta)).CapitalizeFirst(); + DiaNode diaNode = new DiaNode(text); + diaNode.options.Add(FactionDialogMaker.OKToRoot()); + diaOption2.link = diaNode; return diaOption2; } private static DiaOption RequestTraderOption(Map map, int silverCost) { - string text = "RequestTrader".Translate(new object[] - { - silverCost.ToString() - }); + string text = "RequestTrader".Translate(silverCost.ToString()); if (FactionDialogMaker.AmountSendableSilver(map) < silverCost) { DiaOption diaOption = new DiaOption(text); - diaOption.Disable("NeedSilverLaunchable".Translate(new object[] - { - silverCost - })); + diaOption.Disable("NeedSilverLaunchable".Translate(silverCost)); return diaOption; } if (!FactionDialogMaker.faction.def.allowedArrivalTemperatureRange.ExpandedBy(-4f).Includes(map.mapTemperature.SeasonalTemp)) @@ -170,39 +148,39 @@ private static DiaOption RequestTraderOption(Map map, int silverCost) if (num > 0) { DiaOption diaOption3 = new DiaOption(text); - diaOption3.Disable("WaitTime".Translate(new object[] - { - num.ToStringTicksToPeriod(true, false, true) - })); + diaOption3.Disable("WaitTime".Translate(num.ToStringTicksToPeriod(true, false, true))); return diaOption3; } DiaOption diaOption4 = new DiaOption(text); - DiaNode diaNode = new DiaNode("TraderSent".Translate(new object[] - { - FactionDialogMaker.faction.leader.LabelIndefinite() - }).CapitalizeFirst()); + DiaNode diaNode = new DiaNode("TraderSent".Translate(FactionDialogMaker.faction.leader.LabelIndefinite()).CapitalizeFirst()); diaNode.options.Add(FactionDialogMaker.OKToRoot()); - DiaNode diaNode2 = new DiaNode("ChooseTraderKind".Translate(new object[] + DiaNode diaNode2 = new DiaNode("ChooseTraderKind".Translate(FactionDialogMaker.faction.leader.LabelIndefinite())); + List.Enumerator enumerator = FactionDialogMaker.faction.def.caravanTraderKinds.GetEnumerator(); + try { - FactionDialogMaker.faction.leader.LabelIndefinite() - })); - foreach (TraderKindDef current in FactionDialogMaker.faction.def.caravanTraderKinds) - { - TraderKindDef localTk = current; - DiaOption diaOption5 = new DiaOption(localTk.LabelCap); - diaOption5.action = delegate + while (enumerator.MoveNext()) { - IncidentParms incidentParms = new IncidentParms(); - incidentParms.target = map; - incidentParms.faction = FactionDialogMaker.faction; - incidentParms.traderKind = localTk; - incidentParms.forced = true; - Find.Storyteller.incidentQueue.Add(IncidentDefOf.TraderCaravanArrival, Find.TickManager.TicksGame + 120000, incidentParms); - FactionDialogMaker.faction.lastTraderRequestTick = Find.TickManager.TicksGame; - TradeUtility.LaunchThingsOfType(ThingDefOf.Silver, silverCost, map, null); - }; - diaOption5.link = diaNode; - diaNode2.options.Add(diaOption5); + TraderKindDef current = enumerator.Current; + TraderKindDef localTk = current; + DiaOption diaOption5 = new DiaOption(localTk.LabelCap); + diaOption5.action = (Action)delegate() + { + IncidentParms incidentParms = new IncidentParms(); + incidentParms.target = map; + incidentParms.faction = FactionDialogMaker.faction; + incidentParms.traderKind = localTk; + incidentParms.forced = true; + Find.Storyteller.incidentQueue.Add(IncidentDefOf.TraderCaravanArrival, Find.TickManager.TicksGame + 120000, incidentParms); + FactionDialogMaker.faction.lastTraderRequestTick = Find.TickManager.TicksGame; + TradeUtility.LaunchThingsOfType(ThingDefOf.Silver, silverCost, map, null); + }; + diaOption5.link = diaNode; + diaNode2.options.Add(diaOption5); + } + } + finally + { + ((IDisposable)(object)enumerator).Dispose(); } DiaOption diaOption6 = new DiaOption("GoBack".Translate()); diaOption6.linkLateBind = FactionDialogMaker.ResetToRoot(); @@ -213,10 +191,7 @@ private static DiaOption RequestTraderOption(Map map, int silverCost) private static DiaOption RequestMilitaryAidOption(Map map) { - string text = "RequestMilitaryAid".Translate(new object[] - { - -25f - }); + string text = "RequestMilitaryAid".Translate(-25f); if (!FactionDialogMaker.faction.def.allowedArrivalTemperatureRange.ExpandedBy(-4f).Includes(map.mapTemperature.SeasonalTemp)) { DiaOption diaOption = new DiaOption(text); @@ -224,56 +199,44 @@ private static DiaOption RequestMilitaryAidOption(Map map) return diaOption; } DiaOption diaOption2 = new DiaOption(text); - if (map.attackTargetsCache.TargetsHostileToColony.Any((IAttackTarget x) => !x.ThreatDisabled())) + if (map.attackTargetsCache.TargetsHostileToColony.Any((Func)((IAttackTarget x) => !x.ThreatDisabled())) && !map.attackTargetsCache.TargetsHostileToColony.Any((Func)((IAttackTarget p) => ((Thing)p).Faction != null && ((Thing)p).Faction.HostileTo(FactionDialogMaker.faction)))) { - if (!map.attackTargetsCache.TargetsHostileToColony.Any((IAttackTarget p) => ((Thing)p).Faction != null && ((Thing)p).Faction.HostileTo(FactionDialogMaker.faction))) + IEnumerable source = (from x in map.attackTargetsCache.TargetsHostileToColony + where !x.ThreatDisabled() + select x into pa + select ((Thing)pa).Faction into fa + where fa != null && !fa.HostileTo(FactionDialogMaker.faction) + select fa).Distinct(); + DiaNode diaNode = new DiaNode("MilitaryAidConfirmMutualEnemy".Translate(FactionDialogMaker.faction.Name, GenText.ToCommaList(from fa in source + select fa.Name, true))); + DiaOption diaOption3 = new DiaOption("CallConfirm".Translate()); + diaOption3.action = (Action)delegate() { - IEnumerable source = (from x in map.attackTargetsCache.TargetsHostileToColony - where !x.ThreatDisabled() - select x into pa - select ((Thing)pa).Faction into fa - where fa != null && !fa.HostileTo(FactionDialogMaker.faction) - select fa).Distinct(); - string arg_1B6_0 = "MilitaryAidConfirmMutualEnemy"; - object[] expr_17D = new object[2]; - expr_17D[0] = FactionDialogMaker.faction.Name; - expr_17D[1] = GenText.ToCommaList(from fa in source - select fa.Name, true); - DiaNode diaNode = new DiaNode(arg_1B6_0.Translate(expr_17D)); - DiaOption diaOption3 = new DiaOption("CallConfirm".Translate()); - diaOption3.action = delegate - { - FactionDialogMaker.CallForAid(map); - }; - diaOption3.link = FactionDialogMaker.FightersSent(); - DiaOption diaOption4 = new DiaOption("CallCancel".Translate()); - diaOption4.linkLateBind = FactionDialogMaker.ResetToRoot(); - diaNode.options.Add(diaOption3); - diaNode.options.Add(diaOption4); - diaOption2.link = diaNode; - return diaOption2; - } + FactionDialogMaker.CallForAid(map); + }; + diaOption3.link = FactionDialogMaker.FightersSent(); + DiaOption diaOption4 = new DiaOption("CallCancel".Translate()); + diaOption4.linkLateBind = FactionDialogMaker.ResetToRoot(); + diaNode.options.Add(diaOption3); + diaNode.options.Add(diaOption4); + diaOption2.link = diaNode; } - diaOption2.action = delegate + else { - FactionDialogMaker.CallForAid(map); - }; - diaOption2.link = FactionDialogMaker.FightersSent(); + diaOption2.action = (Action)delegate() + { + FactionDialogMaker.CallForAid(map); + }; + diaOption2.link = FactionDialogMaker.FightersSent(); + } return diaOption2; } private static DiaNode FightersSent() { - return new DiaNode("MilitaryAidSent".Translate(new object[] - { - FactionDialogMaker.faction.leader.LabelIndefinite() - }).CapitalizeFirst()) - { - options = - { - FactionDialogMaker.OKToRoot() - } - }; + DiaNode diaNode = new DiaNode("MilitaryAidSent".Translate(FactionDialogMaker.faction.leader.LabelIndefinite()).CapitalizeFirst()); + diaNode.options.Add(FactionDialogMaker.OKToRoot()); + return diaNode; } private static void CallForAid(Map map) @@ -288,15 +251,14 @@ private static void CallForAid(Map map) private static DiaOption OKToRoot() { - return new DiaOption("OK".Translate()) - { - linkLateBind = FactionDialogMaker.ResetToRoot() - }; + DiaOption diaOption = new DiaOption("OK".Translate()); + diaOption.linkLateBind = FactionDialogMaker.ResetToRoot(); + return diaOption; } private static Func ResetToRoot() { - return () => FactionDialogMaker.FactionDialogFor(FactionDialogMaker.negotiator, FactionDialogMaker.faction); + return (Func)(() => FactionDialogMaker.FactionDialogFor(FactionDialogMaker.negotiator, FactionDialogMaker.faction)); } } } diff --git a/Assembly-CSharp/RimWorld/FactionGenerator.cs b/Assembly-CSharp/RimWorld/FactionGenerator.cs index 54ea528cf..ad70d175d 100644 --- a/Assembly-CSharp/RimWorld/FactionGenerator.cs +++ b/Assembly-CSharp/RimWorld/FactionGenerator.cs @@ -16,34 +16,33 @@ public static class FactionGenerator public static void GenerateFactionsIntoWorld() { int i = 0; - foreach (FactionDef current in DefDatabase.AllDefs) + foreach (FactionDef allDef in DefDatabase.AllDefs) { - for (int j = 0; j < current.requiredCountAtGameStart; j++) + for (int j = 0; j < allDef.requiredCountAtGameStart; j++) { - Faction faction = FactionGenerator.NewGeneratedFaction(current); + Faction faction = FactionGenerator.NewGeneratedFaction(allDef); Find.FactionManager.Add(faction); - if (!current.hidden) + if (!allDef.hidden) { i++; } } } - while (i < 5) + for (; i < 5; i++) { FactionDef facDef = (from fa in DefDatabase.AllDefs - where fa.canMakeRandomly && Find.FactionManager.AllFactions.Count((Faction f) => f.def == fa) < fa.maxCountAtGameStart - select fa).RandomElement(); + where fa.canMakeRandomly && Find.FactionManager.AllFactions.Count((Func)((Faction f) => f.def == fa)) < fa.maxCountAtGameStart + select fa).RandomElement(); Faction faction2 = FactionGenerator.NewGeneratedFaction(facDef); Find.World.factionManager.Add(faction2); - i++; } - int num = GenMath.RoundRandom((float)Find.WorldGrid.TilesCount / 100000f * FactionGenerator.FactionBasesPer100kTiles.RandomInRange); + int num = GenMath.RoundRandom((float)((float)Find.WorldGrid.TilesCount / 100000.0 * FactionGenerator.FactionBasesPer100kTiles.RandomInRange)); num -= Find.WorldObjects.FactionBases.Count; - for (int k = 0; k < num; k++) + for (int num2 = 0; num2 < num; num2++) { Faction faction3 = (from x in Find.World.factionManager.AllFactionsListForReading where !x.def.isPlayer && !x.def.hidden - select x).RandomElementByWeight((Faction x) => x.def.baseSelectionWeight); + select x).RandomElementByWeight((Func)((Faction x) => x.def.baseSelectionWeight)); FactionBase factionBase = (FactionBase)WorldObjectMaker.MakeWorldObject(WorldObjectDefOf.FactionBase); factionBase.SetFaction(faction3); factionBase.Tile = TileFinder.RandomFactionBaseTileFor(faction3, false); @@ -54,18 +53,21 @@ public static void GenerateFactionsIntoWorld() public static void EnsureRequiredEnemies(Faction player) { - FactionGenerator.c__AnonStorey365 c__AnonStorey = new FactionGenerator.c__AnonStorey365(); - c__AnonStorey.player = player; - foreach (FactionDef facDef in DefDatabase.AllDefs) + using (IEnumerator enumerator = DefDatabase.AllDefs.GetEnumerator()) { - if (facDef.mustStartOneEnemy && Find.World.factionManager.AllFactions.Any((Faction f) => f.def == facDef) && !Find.World.factionManager.AllFactions.Any((Faction f) => f.def == facDef && f.HostileTo(c__AnonStorey.player))) + FactionDef facDef; + while (enumerator.MoveNext()) { - Faction faction = (from f in Find.World.factionManager.AllFactions - where f.def == facDef - select f).RandomElement(); - float goodwillChange = -(faction.GoodwillWith(c__AnonStorey.player) + 100f) * Rand.Range(0.8f, 0.9f); - faction.AffectGoodwillWith(c__AnonStorey.player, goodwillChange); - faction.SetHostileTo(c__AnonStorey.player, true); + facDef = enumerator.Current; + if (facDef.mustStartOneEnemy && Find.World.factionManager.AllFactions.Any((Func)((Faction f) => f.def == facDef)) && !Find.World.factionManager.AllFactions.Any((Func)((Faction f) => f.def == facDef && f.HostileTo(player)))) + { + Faction faction = (from f in Find.World.factionManager.AllFactions + where f.def == facDef + select f).RandomElement(); + float goodwillChange = (float)((0.0 - (faction.GoodwillWith(player) + 100.0)) * Rand.Range(0.8f, 0.9f)); + faction.AffectGoodwillWith(player, goodwillChange); + faction.SetHostileTo(player, true); + } } } } @@ -93,9 +95,18 @@ public static Faction NewGeneratedFaction(FactionDef facDef) select fac.Name, false); } } - foreach (Faction current in Find.FactionManager.AllFactionsListForReading) + List.Enumerator enumerator = Find.FactionManager.AllFactionsListForReading.GetEnumerator(); + try + { + while (enumerator.MoveNext()) + { + Faction current = enumerator.Current; + faction.TryMakeInitialRelationsWith(current); + } + } + finally { - faction.TryMakeInitialRelationsWith(current); + ((IDisposable)(object)enumerator).Dispose(); } if (!facDef.hidden && !facDef.isPlayer) { diff --git a/Assembly-CSharp/RimWorld/FactionManager.cs b/Assembly-CSharp/RimWorld/FactionManager.cs index 7cd7c61db..08a1733b0 100644 --- a/Assembly-CSharp/RimWorld/FactionManager.cs +++ b/Assembly-CSharp/RimWorld/FactionManager.cs @@ -41,7 +41,7 @@ public IEnumerable AllFactionsInViewOrder { return (from x in this.AllFactionsVisible orderby x.defeated - select x).ThenByDescending((Faction fa) => fa.def.startingGoodwill.Average); + select x).ThenByDescending((Func)((Faction fa) => fa.def.startingGoodwill.Average)); } } @@ -91,9 +91,9 @@ public bool TryGetRandomNonColonyHumanlikeFaction(out Faction faction, bool tryM IEnumerable source = from x in this.AllFactions where x != Faction.OfPlayer && !x.def.hidden && x.def.humanlikeFaction && (allowDefeated || !x.defeated) select x; - return source.TryRandomElementByWeight(delegate(Faction x) + return source.TryRandomElementByWeight((Func)delegate(Faction x) { - if (tryMedievalOrBetter && x.def.techLevel < TechLevel.Medieval) + if (tryMedievalOrBetter && (int)x.def.techLevel < 3) { return 0.1f; } @@ -103,10 +103,29 @@ public bool TryGetRandomNonColonyHumanlikeFaction(out Faction faction, bool tryM public Faction RandomEnemyFaction(bool allowHidden = false, bool allowDefeated = false, bool allowNonHumanlike = true) { - Faction result; - if ((from x in this.AllFactions - where (allowHidden || !x.def.hidden) && (allowDefeated || !x.defeated) && (allowNonHumanlike || x.def.humanlikeFaction) && x.HostileTo(Faction.OfPlayer) - select x).TryRandomElement(out result)) + Faction result = default(Faction); + if (this.AllFactions.Where((Func)delegate(Faction x) + { + if (!allowHidden && x.def.hidden) + { + goto IL_0059; + } + if (!allowDefeated && x.defeated) + { + goto IL_0059; + } + if (!allowNonHumanlike && !x.def.humanlikeFaction) + { + goto IL_0059; + } + int result2 = x.HostileTo(Faction.OfPlayer) ? 1 : 0; + goto IL_005a; + IL_005a: + return (byte)result2 != 0; + IL_0059: + result2 = 0; + goto IL_005a; + }).TryRandomElement(out result)) { return result; } @@ -115,10 +134,10 @@ public Faction RandomEnemyFaction(bool allowHidden = false, bool allowDefeated = public Faction RandomAlliedFaction(bool allowHidden = false, bool allowDefeated = false, bool allowNonHumanlike = true) { - Faction result; + Faction result = default(Faction); if ((from x in this.AllFactions where !x.IsPlayer && (allowHidden || !x.def.hidden) && (allowDefeated || !x.defeated) && (allowNonHumanlike || x.def.humanlikeFaction) && !x.HostileTo(Faction.OfPlayer) - select x).TryRandomElement(out result)) + select x).TryRandomElement(out result)) { return result; } diff --git a/Assembly-CSharp/RimWorld/FactionRelation.cs b/Assembly-CSharp/RimWorld/FactionRelation.cs index 092083ac2..d503e1315 100644 --- a/Assembly-CSharp/RimWorld/FactionRelation.cs +++ b/Assembly-CSharp/RimWorld/FactionRelation.cs @@ -1,4 +1,3 @@ -using System; using Verse; namespace RimWorld @@ -20,15 +19,7 @@ public void ExposeData() public override string ToString() { - return string.Concat(new object[] - { - "(", - this.other, - ", goodwill=", - this.goodwill.ToString("F1"), - (!this.hostile) ? string.Empty : " hostile", - ")" - }); + return "(" + this.other + ", goodwill=" + this.goodwill.ToString("F1") + ((!this.hostile) ? string.Empty : " hostile") + ")"; } } } diff --git a/Assembly-CSharp/RimWorld/FactionTacticalMemory.cs b/Assembly-CSharp/RimWorld/FactionTacticalMemory.cs index 0aebd438c..82bc6b1e4 100644 --- a/Assembly-CSharp/RimWorld/FactionTacticalMemory.cs +++ b/Assembly-CSharp/RimWorld/FactionTacticalMemory.cs @@ -17,18 +17,18 @@ public void ExposeData() public void Notify_MapRemoved(Map map) { - this.traps.RemoveAll((TrapMemory x) => x.map == map); + this.traps.RemoveAll((Predicate)((TrapMemory x) => x.map == map)); } public List TrapMemories() { - this.traps.RemoveAll((TrapMemory tl) => tl.Expired); + this.traps.RemoveAll((Predicate)((TrapMemory tl) => tl.Expired)); return this.traps; } public void TrapRevealed(IntVec3 c, Map map) { - if (Rand.Value < 0.2f) + if (Rand.Value < 0.20000000298023224) { this.traps.Add(new TrapMemory(c, map, Find.TickManager.TicksGame)); } diff --git a/Assembly-CSharp/RimWorld/FactionUIUtility.cs b/Assembly-CSharp/RimWorld/FactionUIUtility.cs index 4d618aa40..24fc5fcd1 100644 --- a/Assembly-CSharp/RimWorld/FactionUIUtility.cs +++ b/Assembly-CSharp/RimWorld/FactionUIUtility.cs @@ -1,4 +1,3 @@ -using System; using System.Text; using UnityEngine; using Verse; @@ -29,18 +28,18 @@ public static void DoWindowContents(Rect fillRect, ref Vector2 scrollPosition, r GUI.BeginGroup(position); Text.Font = GameFont.Small; GUI.color = Color.white; - Rect outRect = new Rect(0f, 50f, position.width, position.height - 50f); - Rect rect = new Rect(0f, 0f, position.width - 16f, scrollViewHeight); + Rect outRect = new Rect(0f, 50f, position.width, (float)(position.height - 50.0)); + Rect rect = new Rect(0f, 0f, (float)(position.width - 16.0), scrollViewHeight); Widgets.BeginScrollView(outRect, ref scrollPosition, rect, true); float num = 0f; - foreach (Faction current in Find.FactionManager.AllFactionsInViewOrder) + foreach (Faction item in Find.FactionManager.AllFactionsInViewOrder) { - if (!current.IsPlayer) + if (!item.IsPlayer) { GUI.color = new Color(1f, 1f, 1f, 0.2f); Widgets.DrawLineHorizontal(0f, num, rect.width); GUI.color = Color.white; - num += FactionUIUtility.DrawFactionRow(current, num, rect); + num += FactionUIUtility.DrawFactionRow(item, num, rect); } } if (Event.current.type == EventType.Layout) @@ -55,24 +54,18 @@ private static float DrawFactionRow(Faction faction, float rowY, Rect fillRect) { Rect rect = new Rect(35f, rowY, 220f, 80f); StringBuilder stringBuilder = new StringBuilder(); - foreach (Faction current in Find.FactionManager.AllFactionsVisible) + foreach (Faction item in Find.FactionManager.AllFactionsVisible) { - if (current != faction && !current.IsPlayer && !current.def.hidden) + if (item != faction && !item.IsPlayer && !item.def.hidden && faction.HostileTo(item)) { - if (faction.HostileTo(current)) - { - stringBuilder.AppendLine("HostileTo".Translate(new object[] - { - current.Name - })); - } + stringBuilder.AppendLine("HostileTo".Translate(item.Name)); } } string text = stringBuilder.ToString(); float width = fillRect.width - rect.xMax; float num = Text.CalcHeight(text, width); float num2 = Mathf.Max(80f, num); - Rect position = new Rect(10f, rowY + 10f, 15f, 15f); + Rect position = new Rect(10f, (float)(rowY + 10.0), 15f, 15f); Rect rect2 = new Rect(0f, rowY, fillRect.width, num2); if (Mouse.IsOver(rect2)) { @@ -81,14 +74,7 @@ private static float DrawFactionRow(Faction faction, float rowY, Rect fillRect) Text.Font = GameFont.Small; Text.Anchor = TextAnchor.UpperLeft; Widgets.DrawRectFast(position, faction.Color, null); - string label = string.Concat(new string[] - { - faction.Name, - "\n", - faction.def.LabelCap, - "\n", - (faction.leader == null) ? string.Empty : (faction.def.leaderTitle.CapitalizeFirst() + ": " + faction.leader.Name.ToStringFull) - }); + string label = faction.Name + "\n" + faction.def.LabelCap + "\n" + ((faction.leader == null) ? string.Empty : (faction.def.leaderTitle.CapitalizeFirst() + ": " + faction.leader.Name.ToStringFull)); Widgets.Label(rect, label); Rect rect3 = new Rect(rect.xMax, rowY, 60f, 80f); Widgets.InfoCardButton(rect3.x, rect3.y, faction.def); @@ -102,11 +88,11 @@ private static float DrawFactionRow(Faction faction, float rowY, Rect fillRect) { text2 = text2 + "\n(" + "DefeatedLower".Translate() + ")"; } - if (faction.PlayerGoodwill < 0f) + if (faction.PlayerGoodwill < 0.0) { GUI.color = Color.red; } - else if (faction.PlayerGoodwill == 0f) + else if (faction.PlayerGoodwill == 0.0) { GUI.color = Color.yellow; } diff --git a/Assembly-CSharp/RimWorld/FactionUtility.cs b/Assembly-CSharp/RimWorld/FactionUtility.cs index 20b66c6d8..65fbac51c 100644 --- a/Assembly-CSharp/RimWorld/FactionUtility.cs +++ b/Assembly-CSharp/RimWorld/FactionUtility.cs @@ -8,7 +8,11 @@ public static class FactionUtility { public static bool HostileTo(this Faction fac, Faction other) { - return fac != null && other != null && other != fac && fac.RelationWith(other, false).hostile; + if (fac != null && other != null && other != fac) + { + return fac.RelationWith(other, false).hostile; + } + return false; } public static Faction DefaultFactionFrom(FactionDef ft) @@ -21,10 +25,10 @@ public static Faction DefaultFactionFrom(FactionDef ft) { return Faction.OfPlayer; } - Faction result; + Faction result = default(Faction); if ((from fac in Find.FactionManager.AllFactions where fac.def == ft - select fac).TryRandomElement(out result)) + select fac).TryRandomElement(out result)) { return result; } diff --git a/Assembly-CSharp/RimWorld/FastIntComparer.cs b/Assembly-CSharp/RimWorld/FastIntComparer.cs index 6ca705350..6804f173e 100644 --- a/Assembly-CSharp/RimWorld/FastIntComparer.cs +++ b/Assembly-CSharp/RimWorld/FastIntComparer.cs @@ -1,4 +1,3 @@ -using System; using System.Collections.Generic; namespace RimWorld diff --git a/Assembly-CSharp/RimWorld/FeedPatientUtility.cs b/Assembly-CSharp/RimWorld/FeedPatientUtility.cs index c1abacc6b..25b99f136 100644 --- a/Assembly-CSharp/RimWorld/FeedPatientUtility.cs +++ b/Assembly-CSharp/RimWorld/FeedPatientUtility.cs @@ -1,4 +1,3 @@ -using System; using Verse; namespace RimWorld @@ -17,15 +16,15 @@ public static bool ShouldBeFed(Pawn p) { return false; } + goto IL_0063; } - else + Building_Bed building_Bed = p.CurrentBed(); + if (building_Bed != null && building_Bed.Faction == Faction.OfPlayer) { - Building_Bed building_Bed = p.CurrentBed(); - if (building_Bed == null || building_Bed.Faction != Faction.OfPlayer) - { - return false; - } + goto IL_0063; } + return false; + IL_0063: if (!HealthAIUtility.ShouldSeekMedicalRest(p)) { return false; diff --git a/Assembly-CSharp/RimWorld/FertilityGrid.cs b/Assembly-CSharp/RimWorld/FertilityGrid.cs index d156e57a3..382d6bbf4 100644 --- a/Assembly-CSharp/RimWorld/FertilityGrid.cs +++ b/Assembly-CSharp/RimWorld/FertilityGrid.cs @@ -1,4 +1,3 @@ -using System; using Verse; namespace RimWorld @@ -20,7 +19,7 @@ public float FertilityAt(IntVec3 loc) private float CalculateFertilityAt(IntVec3 loc) { Thing edifice = loc.GetEdifice(this.map); - if (edifice != null && edifice.def.fertility >= 0f) + if (edifice != null && edifice.def.fertility >= 0.0) { return edifice.def.fertility; } diff --git a/Assembly-CSharp/RimWorld/Filth.cs b/Assembly-CSharp/RimWorld/Filth.cs index c3aafcc02..599bc27c8 100644 --- a/Assembly-CSharp/RimWorld/Filth.cs +++ b/Assembly-CSharp/RimWorld/Filth.cs @@ -1,4 +1,3 @@ -using System; using System.Collections.Generic; using System.Text; using Verse; @@ -23,7 +22,7 @@ public bool CanFilthAttachNow { get { - return this.def.filth.canFilthAttach && this.thickness > 1 && Find.TickManager.TicksGame - this.growTick > 400; + return base.def.filth.canFilthAttach && this.thickness > 1 && Find.TickManager.TicksGame - this.growTick > 400; } } @@ -49,7 +48,7 @@ public override string Label { StringBuilder stringBuilder = new StringBuilder(); stringBuilder.Append(base.Label); - if (!this.sources.NullOrEmpty()) + if (!this.sources.NullOrEmpty()) { stringBuilder.Append(" " + "OfLower".Translate() + " "); stringBuilder.Append(GenText.ToCommaList(this.sources, true)); @@ -64,10 +63,9 @@ public override void ExposeData() base.ExposeData(); Scribe_Values.Look(ref this.thickness, "thickness", 1, false); Scribe_Values.Look(ref this.growTick, "growTick", 0, false); - if (Scribe.mode != LoadSaveMode.Saving || this.sources != null) - { - Scribe_Collections.Look(ref this.sources, "sources", LookMode.Value, new object[0]); - } + if (Scribe.mode == LoadSaveMode.Saving && this.sources == null) + return; + Scribe_Collections.Look(ref this.sources, "sources", LookMode.Value, new object[0]); } public override void SpawnSetup(Map map, bool respawningAfterLoad) @@ -103,12 +101,15 @@ public void AddSource(string newSource) { this.sources = new List(); } - for (int i = 0; i < this.sources.Count; i++) + int num = 0; + while (num < this.sources.Count) { - if (this.sources[i] == newSource) + if (!(this.sources[num] == newSource)) { - return; + num++; + continue; } + return; } while (this.sources.Count > 3) { @@ -119,20 +120,19 @@ public void AddSource(string newSource) public void AddSources(IEnumerable sources) { - if (sources == null) - { - return; - } - foreach (string current in sources) + if (sources != null) { - this.AddSource(current); + foreach (string item in sources) + { + this.AddSource(item); + } } } public virtual void ThickenFilth() { this.growTick = Find.TickManager.TicksGame; - if (this.thickness < this.def.filth.maxThickness) + if (this.thickness < base.def.filth.maxThickness) { this.thickness++; this.UpdateMesh(); @@ -166,7 +166,15 @@ private void UpdateMesh() public bool CanDropAt(IntVec3 c, Map map) { TerrainDef terrainDef = map.terrainGrid.TerrainAt(c); - return terrainDef.acceptFilth && (!this.def.filth.terrainSourced || terrainDef.acceptTerrainSourceFilth); + if (!terrainDef.acceptFilth) + { + return false; + } + if (base.def.filth.terrainSourced && !terrainDef.acceptTerrainSourceFilth) + { + return false; + } + return true; } } } diff --git a/Assembly-CSharp/RimWorld/FilthMaker.cs b/Assembly-CSharp/RimWorld/FilthMaker.cs index 08d380ce8..10951915d 100644 --- a/Assembly-CSharp/RimWorld/FilthMaker.cs +++ b/Assembly-CSharp/RimWorld/FilthMaker.cs @@ -9,7 +9,7 @@ public static class FilthMaker { public static void MakeFilth(IntVec3 c, Map map, ThingDef filthDef, int count = 1) { - for (int i = 0; i < count; i++) + for (int num = 0; num < count; num++) { FilthMaker.MakeFilth(c, map, filthDef, null, true); } @@ -18,9 +18,9 @@ public static void MakeFilth(IntVec3 c, Map map, ThingDef filthDef, int count = public static bool MakeFilth(IntVec3 c, Map map, ThingDef filthDef, string source, int count = 1) { bool flag = false; - for (int i = 0; i < count; i++) + for (int num = 0; num < count; num++) { - flag |= FilthMaker.MakeFilth(c, map, filthDef, Gen.YieldSingle(source), true); + flag |= FilthMaker.MakeFilth(c, map, filthDef, Gen.YieldSingle(source), true); } return flag; } @@ -34,42 +34,39 @@ private static bool MakeFilth(IntVec3 c, Map map, ThingDef filthDef, IEnumerable { Filth filth = (Filth)(from t in c.GetThingList(map) where t.def == filthDef - select t).FirstOrDefault(); - if (!c.Walkable(map) || (filth != null && !filth.CanBeThickened)) + select t).FirstOrDefault(); + if (c.Walkable(map) && (filth == null || filth.CanBeThickened)) { - if (shouldPropagate) - { - List list = GenAdj.AdjacentCells8WayRandomized(); - for (int i = 0; i < 8; i++) - { - IntVec3 c2 = c + list[i]; - if (c2.InBounds(map)) - { - if (FilthMaker.MakeFilth(c2, map, filthDef, sources, false)) - { - return true; - } - } - } - } if (filth != null) { + filth.ThickenFilth(); filth.AddSources(sources); } - return false; + else + { + Filth filth2 = (Filth)ThingMaker.MakeThing(filthDef, null); + filth2.AddSources(sources); + GenSpawn.Spawn(filth2, c, map); + } + return true; } - if (filth != null) + if (shouldPropagate) { - filth.ThickenFilth(); - filth.AddSources(sources); + List list = GenAdj.AdjacentCells8WayRandomized(); + for (int i = 0; i < 8; i++) + { + IntVec3 c2 = c + list[i]; + if (c2.InBounds(map) && FilthMaker.MakeFilth(c2, map, filthDef, sources, false)) + { + return true; + } + } } - else + if (filth != null) { - Filth filth2 = (Filth)ThingMaker.MakeThing(filthDef, null); - filth2.AddSources(sources); - GenSpawn.Spawn(filth2, c, map); + filth.AddSources(sources); } - return true; + return false; } } } diff --git a/Assembly-CSharp/RimWorld/FilthProperties.cs b/Assembly-CSharp/RimWorld/FilthProperties.cs index f1fbe9b5b..11482fb10 100644 --- a/Assembly-CSharp/RimWorld/FilthProperties.cs +++ b/Assembly-CSharp/RimWorld/FilthProperties.cs @@ -1,5 +1,3 @@ -using System; - namespace RimWorld { public class FilthProperties diff --git a/Assembly-CSharp/RimWorld/Fire.cs b/Assembly-CSharp/RimWorld/Fire.cs index 3768c5a37..486d1d5b4 100644 --- a/Assembly-CSharp/RimWorld/Fire.cs +++ b/Assembly-CSharp/RimWorld/Fire.cs @@ -72,12 +72,9 @@ public override string Label { get { - if (this.parent != null) + if (base.parent != null) { - return "FireOn".Translate(new object[] - { - this.parent.LabelCap - }); + return "FireOn".Translate(base.parent.LabelCap); } return "Fire".Translate(); } @@ -87,10 +84,7 @@ public override string InspectStringAddon { get { - return "Burning".Translate() + " (" + "FireSizeLower".Translate(new object[] - { - (this.fireSize * 100f).ToString("F0") - }) + ")"; + return "Burning".Translate() + " (" + "FireSizeLower".Translate(((float)(this.fireSize * 100.0)).ToString("F0")) + ")"; } } @@ -98,8 +92,8 @@ private float SpreadInterval { get { - float num = 150f - (this.fireSize - 1f) * 40f; - if (num < 75f) + float num = (float)(150.0 - (this.fireSize - 1.0) * 40.0); + if (num < 75.0) { num = 75f; } @@ -119,10 +113,10 @@ public override void SpawnSetup(Map map, bool respawningAfterLoad) this.RecalcPathsOnAndAroundMe(map); LessonAutoActivator.TeachOpportunity(ConceptDefOf.HomeArea, this, OpportunityType.Important); this.ticksSinceSpread = (int)(this.SpreadInterval * Rand.Value); - LongEventHandler.ExecuteWhenFinished(delegate + LongEventHandler.ExecuteWhenFinished((Action)delegate() { SoundDef def = SoundDef.Named("FireBurning"); - SoundInfo info = SoundInfo.InMap(new TargetInfo(this.Position, map, false), MaintenanceType.PerTick); + SoundInfo info = SoundInfo.InMap(new TargetInfo(base.Position, map, false), MaintenanceType.PerTick); this.sustainer = SustainerAggregatorUtility.AggregateOrSpawnSustainerFor(this, def, info); }); } @@ -163,10 +157,7 @@ public override void AttachTo(Thing parent) Pawn pawn = parent as Pawn; if (pawn != null) { - TaleRecorder.RecordTale(TaleDefOf.WasOnFire, new object[] - { - pawn - }); + TaleRecorder.RecordTale(TaleDefOf.WasOnFire, pawn); } } @@ -175,7 +166,7 @@ public override void Tick() this.ticksSinceSpawn++; if (Fire.lastFireCountUpdateTick != Find.TickManager.TicksGame) { - Fire.fireCount = base.Map.listerThings.ThingsOfDef(this.def).Count; + Fire.fireCount = base.Map.listerThings.ThingsOfDef(base.def).Count; Fire.lastFireCountUpdateTick = Find.TickManager.TicksGame; } if (this.sustainer != null) @@ -191,11 +182,11 @@ public override void Tick() { this.SpawnSmokeParticles(); } - if (Fire.fireCount < 15 && this.fireSize > 0.7f && Rand.Value < this.fireSize * 0.01f) + if (Fire.fireCount < 15 && this.fireSize > 0.699999988079071 && Rand.Value < this.fireSize * 0.0099999997764825821) { MoteMaker.ThrowMicroSparks(this.DrawPos, base.Map); } - if (this.fireSize > 1f) + if (this.fireSize > 1.0) { this.ticksSinceSpread++; if ((float)this.ticksSinceSpread >= this.SpreadInterval) @@ -220,17 +211,17 @@ private void SpawnSmokeParticles() { MoteMaker.ThrowSmoke(this.DrawPos, base.Map, this.fireSize); } - if (this.fireSize > 0.5f && this.parent == null) + if (this.fireSize > 0.5 && base.parent == null) { MoteMaker.ThrowFireGlow(base.Position, base.Map, this.fireSize); } - float num = this.fireSize / 2f; - if (num > 1f) + float num = (float)(this.fireSize / 2.0); + if (num > 1.0) { num = 1f; } - num = 1f - num; - this.ticksUntilSmoke = Fire.SmokeIntervalRange.Lerped(num) + (int)(10f * Rand.Value); + num = (float)(1.0 - num); + this.ticksUntilSmoke = Fire.SmokeIntervalRange.Lerped(num) + (int)(10.0 * Rand.Value); } private void DoComplexCalcs() @@ -240,7 +231,7 @@ private void DoComplexCalcs() this.flammabilityMax = 0f; if (!base.Position.GetTerrain(base.Map).HasTag("Water")) { - if (this.parent == null) + if (base.parent == null) { if (base.Position.TerrainFlammableNow(base.Map)) { @@ -255,86 +246,75 @@ private void DoComplexCalcs() flag = true; } float statValue = thing.GetStatValue(StatDefOf.Flammability, true); - if (statValue >= 0.01f) + if (!(statValue < 0.0099999997764825821)) { Fire.flammableList.Add(list[i]); if (statValue > this.flammabilityMax) { this.flammabilityMax = statValue; } - if (this.parent == null && this.fireSize > 0.4f && list[i].def.category == ThingCategory.Pawn) + if (base.parent == null && this.fireSize > 0.40000000596046448 && list[i].def.category == ThingCategory.Pawn) { - list[i].TryAttachFire(this.fireSize * 0.2f); + list[i].TryAttachFire((float)(this.fireSize * 0.20000000298023224)); } } } } else { - Fire.flammableList.Add(this.parent); - this.flammabilityMax = this.parent.GetStatValue(StatDefOf.Flammability, true); + Fire.flammableList.Add(base.parent); + this.flammabilityMax = base.parent.GetStatValue(StatDefOf.Flammability, true); } } - if (this.flammabilityMax < 0.01f) + if (this.flammabilityMax < 0.0099999997764825821) { this.Destroy(DestroyMode.Vanish); - return; - } - Thing thing2; - if (this.parent != null) - { - thing2 = this.parent; - } - else if (Fire.flammableList.Count > 0) - { - thing2 = Fire.flammableList.RandomElement(); } else { - thing2 = null; - } - if (thing2 != null && (this.fireSize >= 0.4f || thing2 == this.parent || thing2.def.category != ThingCategory.Pawn)) - { - this.DoFireDamage(thing2); - } - if (base.Spawned) - { - float num = this.fireSize * 160f; - if (flag) - { - num *= 0.15f; - } - GenTemperature.PushHeat(base.Position, base.Map, num); - if (Rand.Value < 0.4f) - { - float radius = this.fireSize * 3f; - SnowUtility.AddSnowRadial(base.Position, base.Map, radius, -(this.fireSize * 0.1f)); - } - this.fireSize += 0.00055f * this.flammabilityMax * 150f; - if (this.fireSize > 1.75f) + Thing thing2 = (base.parent == null) ? ((Fire.flammableList.Count <= 0) ? null : Fire.flammableList.RandomElement()) : base.parent; + if (thing2 != null && (!(this.fireSize < 0.40000000596046448) || thing2 == base.parent || thing2.def.category != ThingCategory.Pawn)) { - this.fireSize = 1.75f; + this.DoFireDamage(thing2); } - if (base.Map.weatherManager.RainRate > 0.01f && this.VulnerableToRain() && Rand.Value < 6f) + if (base.Spawned) { - base.TakeDamage(new DamageInfo(DamageDefOf.Extinguish, 10, -1f, null, null, null, DamageInfo.SourceCategory.ThingOrUnknown)); + float num = (float)(this.fireSize * 160.0); + if (flag) + { + num = (float)(num * 0.15000000596046448); + } + GenTemperature.PushHeat(base.Position, base.Map, num); + if (Rand.Value < 0.40000000596046448) + { + float radius = (float)(this.fireSize * 3.0); + SnowUtility.AddSnowRadial(base.Position, base.Map, radius, (float)(0.0 - this.fireSize * 0.10000000149011612)); + } + this.fireSize += (float)(0.00054999999701976776 * this.flammabilityMax * 150.0); + if (this.fireSize > 1.75) + { + this.fireSize = 1.75f; + } + if (base.Map.weatherManager.RainRate > 0.0099999997764825821 && this.VulnerableToRain() && Rand.Value < 6.0) + { + base.TakeDamage(new DamageInfo(DamageDefOf.Extinguish, 10, -1f, null, null, null, DamageInfo.SourceCategory.ThingOrUnknown)); + } } } } private void TryMakeFloorBurned() { - if (this.parent != null || !base.Spawned) + if (base.parent == null && base.Spawned) { - return; - } - Map map = base.Map; - TerrainGrid terrainGrid = map.terrainGrid; - TerrainDef terrain = base.Position.GetTerrain(map); - if (terrain.burnedDef != null && base.Position.TerrainFlammableNow(map)) - { - terrainGrid.RemoveTopLayer(base.Position, false); - terrainGrid.SetTerrain(base.Position, terrain.burnedDef); + Map map = base.Map; + TerrainGrid terrainGrid = map.terrainGrid; + TerrainDef terrain = base.Position.GetTerrain(map); + if (terrain.burnedDef != null && base.Position.TerrainFlammableNow(map)) + { + terrainGrid.RemoveTopLayer(base.Position, false); + terrainGrid.SetTerrain(base.Position, terrain.burnedDef); + } } } @@ -359,28 +339,28 @@ private bool VulnerableToRain() private void DoFireDamage(Thing targ) { - float num = 0.0125f + 0.0036f * this.fireSize; - num = Mathf.Clamp(num, 0.0125f, 0.05f); - int num2 = GenMath.RoundRandom(num * 150f); - if (num2 < 1) + float value = (float)(0.012500000186264515 + 0.003599999938160181 * this.fireSize); + value = Mathf.Clamp(value, 0.0125f, 0.05f); + int num = GenMath.RoundRandom((float)(value * 150.0)); + if (num < 1) { - num2 = 1; + num = 1; } Pawn pawn = targ as Pawn; if (pawn != null) { - DamageInfo dinfo = new DamageInfo(DamageDefOf.Flame, num2, -1f, this, null, null, DamageInfo.SourceCategory.ThingOrUnknown); + DamageInfo dinfo = new DamageInfo(DamageDefOf.Flame, num, -1f, this, null, null, DamageInfo.SourceCategory.ThingOrUnknown); dinfo.SetBodyRegion(BodyPartHeight.Undefined, BodyPartDepth.Outside); targ.TakeDamage(dinfo); - Apparel apparel; - if (pawn.apparel != null && pawn.apparel.WornApparel.TryRandomElement(out apparel)) + Apparel apparel = default(Apparel); + if (pawn.apparel != null && ((IEnumerable)pawn.apparel.WornApparel).TryRandomElement(out apparel)) { - apparel.TakeDamage(new DamageInfo(DamageDefOf.Flame, num2, -1f, this, null, null, DamageInfo.SourceCategory.ThingOrUnknown)); + apparel.TakeDamage(new DamageInfo(DamageDefOf.Flame, num, -1f, this, null, null, DamageInfo.SourceCategory.ThingOrUnknown)); } } else { - targ.TakeDamage(new DamageInfo(DamageDefOf.Flame, num2, -1f, this, null, null, DamageInfo.SourceCategory.ThingOrUnknown)); + targ.TakeDamage(new DamageInfo(DamageDefOf.Flame, num, -1f, this, null, null, DamageInfo.SourceCategory.ThingOrUnknown)); } } @@ -388,49 +368,43 @@ public override void PostApplyDamage(DamageInfo dinfo, float totalDamageDealt) { if (!base.Destroyed && dinfo.Def == DamageDefOf.Extinguish) { - this.fireSize -= (float)dinfo.Amount / 100f; - if (this.fireSize <= 0.1f) + this.fireSize -= (float)((float)dinfo.Amount / 100.0); + if (this.fireSize <= 0.10000000149011612) { this.Destroy(DestroyMode.Vanish); - return; } } } protected void TrySpread() { - IntVec3 intVec = base.Position; + IntVec3 position = base.Position; bool flag; if (Rand.Chance(0.8f)) { - intVec = base.Position + GenRadial.ManualRadialPattern[Rand.RangeInclusive(1, 8)]; + position = base.Position + GenRadial.ManualRadialPattern[Rand.RangeInclusive(1, 8)]; flag = true; } else { - intVec = base.Position + GenRadial.ManualRadialPattern[Rand.RangeInclusive(10, 20)]; + position = base.Position + GenRadial.ManualRadialPattern[Rand.RangeInclusive(10, 20)]; flag = false; } - if (!intVec.InBounds(base.Map)) - { - return; - } - if (Rand.Chance(FireUtility.ChanceToStartFireIn(intVec, base.Map))) + if (position.InBounds(base.Map) && Rand.Chance(FireUtility.ChanceToStartFireIn(position, base.Map))) { if (!flag) { CellRect startRect = CellRect.SingleCell(base.Position); - CellRect endRect = CellRect.SingleCell(intVec); - if (!GenSight.LineOfSight(base.Position, intVec, base.Map, startRect, endRect)) + CellRect endRect = CellRect.SingleCell(position); + if (GenSight.LineOfSight(base.Position, position, base.Map, startRect, endRect)) { - return; + Spark spark = (Spark)GenSpawn.Spawn(ThingDefOf.Spark, base.Position, base.Map); + spark.Launch(this, position, null); } - Spark spark = (Spark)GenSpawn.Spawn(ThingDefOf.Spark, base.Position, base.Map); - spark.Launch(this, intVec, null); } else { - FireUtility.TryStartFireIn(intVec, base.Map, 0.1f); + FireUtility.TryStartFireIn(position, base.Map, 0.1f); } } } diff --git a/Assembly-CSharp/RimWorld/FireUtility.cs b/Assembly-CSharp/RimWorld/FireUtility.cs index 441902e45..3675fdd54 100644 --- a/Assembly-CSharp/RimWorld/FireUtility.cs +++ b/Assembly-CSharp/RimWorld/FireUtility.cs @@ -1,4 +1,3 @@ -using System; using System.Collections.Generic; using Verse; using Verse.AI; @@ -9,13 +8,25 @@ public static class FireUtility { public static bool CanEverAttachFire(this Thing t) { - return !t.Destroyed && t.FlammableNow && t.def.category == ThingCategory.Pawn; + if (t.Destroyed) + { + return false; + } + if (!t.FlammableNow) + { + return false; + } + if (t.def.category != ThingCategory.Pawn) + { + return false; + } + return true; } public static float ChanceToStartFireIn(IntVec3 c, Map map) { List thingList = c.GetThingList(map); - float num = (!c.TerrainFlammableNow(map)) ? 0f : c.GetTerrain(map).GetStatValueAbstract(StatDefOf.Flammability, null); + float num = (float)((!c.TerrainFlammableNow(map)) ? 0.0 : c.GetTerrain(map).GetStatValueAbstract(StatDefOf.Flammability, null)); for (int i = 0; i < thingList.Count; i++) { if (thingList[i] is Fire) @@ -27,7 +38,7 @@ public static float ChanceToStartFireIn(IntVec3 c, Map map) num = 1f; } } - if (num > 0f) + if (num > 0.0) { Building edifice = c.GetEdifice(map); if (edifice != null && edifice.def.passability == Traversability.Impassable && edifice.OccupiedRect().ContractedBy(1).Contains(c)) @@ -49,34 +60,28 @@ public static float ChanceToStartFireIn(IntVec3 c, Map map) public static void TryStartFireIn(IntVec3 c, Map map, float fireSize) { float num = FireUtility.ChanceToStartFireIn(c, map); - if (num <= 0f) + if (!(num <= 0.0)) { - return; + Fire fire = (Fire)ThingMaker.MakeThing(ThingDefOf.Fire, null); + fire.fireSize = fireSize; + GenSpawn.Spawn(fire, c, map, Rot4.North, false); } - Fire fire = (Fire)ThingMaker.MakeThing(ThingDefOf.Fire, null); - fire.fireSize = fireSize; - GenSpawn.Spawn(fire, c, map, Rot4.North, false); } public static void TryAttachFire(this Thing t, float fireSize) { - if (!t.CanEverAttachFire()) - { - return; - } - if (t.HasAttachment(ThingDefOf.Fire)) - { - return; - } - Fire fire = ThingMaker.MakeThing(ThingDefOf.Fire, null) as Fire; - fire.fireSize = fireSize; - fire.AttachTo(t); - GenSpawn.Spawn(fire, t.Position, t.Map, Rot4.North, false); - Pawn pawn = t as Pawn; - if (pawn != null) + if (t.CanEverAttachFire() && !t.HasAttachment(ThingDefOf.Fire)) { - pawn.jobs.EndCurrentJob(JobCondition.InterruptForced, true); - pawn.records.Increment(RecordDefOf.TimesOnFire); + Fire fire = ThingMaker.MakeThing(ThingDefOf.Fire, null) as Fire; + fire.fireSize = fireSize; + fire.AttachTo(t); + GenSpawn.Spawn(fire, t.Position, t.Map, Rot4.North, false); + Pawn pawn = t as Pawn; + if (pawn != null) + { + pawn.jobs.EndCurrentJob(JobCondition.InterruptForced, true); + pawn.records.Increment(RecordDefOf.TimesOnFire); + } } } @@ -91,12 +96,16 @@ public static bool IsBurning(this TargetInfo t) public static bool IsBurning(this Thing t) { - if (t.Destroyed || !t.Spawned) - { - return false; - } - if (!(t.def.size == IntVec2.One)) + if (!t.Destroyed && t.Spawned) { + if (t.def.size == IntVec2.One) + { + if (t is Pawn) + { + return t.HasAttachment(ThingDefOf.Fire); + } + return t.Position.ContainsStaticFire(t.Map); + } CellRect.CellRectIterator iterator = t.OccupiedRect().GetIterator(); while (!iterator.Done()) { @@ -108,11 +117,7 @@ public static bool IsBurning(this Thing t) } return false; } - if (t is Pawn) - { - return t.HasAttachment(ThingDefOf.Fire); - } - return t.Position.ContainsStaticFire(t.Map); + return false; } public static bool ContainsStaticFire(this IntVec3 c, Map map) @@ -137,7 +142,7 @@ public static bool ContainsTrap(this IntVec3 c, Map map) public static bool Flammable(this TerrainDef terrain) { - return terrain.GetStatValueAbstract(StatDefOf.Flammability, null) > 0.01f; + return terrain.GetStatValueAbstract(StatDefOf.Flammability, null) > 0.0099999997764825821; } public static bool TerrainFlammableNow(this IntVec3 c, Map map) diff --git a/Assembly-CSharp/RimWorld/FireWatcher.cs b/Assembly-CSharp/RimWorld/FireWatcher.cs index eaf90451b..de3822fef 100644 --- a/Assembly-CSharp/RimWorld/FireWatcher.cs +++ b/Assembly-CSharp/RimWorld/FireWatcher.cs @@ -1,4 +1,3 @@ -using System; using System.Collections.Generic; using Verse; @@ -26,11 +25,11 @@ public bool LargeFireDangerPresent { get { - if (this.fireDanger < 0f) + if (this.fireDanger < 0.0) { this.UpdateObservations(); } - return this.fireDanger > 90f; + return this.fireDanger > 90.0; } } @@ -54,7 +53,7 @@ private void UpdateObservations() for (int i = 0; i < list.Count; i++) { Fire fire = list[i] as Fire; - this.fireDanger += 0.5f + fire.fireSize; + this.fireDanger += (float)(0.5 + fire.fireSize); } } } diff --git a/Assembly-CSharp/RimWorld/FiringIncident.cs b/Assembly-CSharp/RimWorld/FiringIncident.cs index b1ce47f17..fb777b23b 100644 --- a/Assembly-CSharp/RimWorld/FiringIncident.cs +++ b/Assembly-CSharp/RimWorld/FiringIncident.cs @@ -1,4 +1,3 @@ -using System; using Verse; namespace RimWorld @@ -34,8 +33,8 @@ public void ExposeData() public override string ToString() { string text = this.def.ToString(); - text = text.PadRight(17); - string text2 = text; + string text2; + text = (text2 = text.PadRight(17)); if (this.parms != null) { text2 = text2 + " " + this.parms.ToString(); diff --git a/Assembly-CSharp/RimWorld/FleshTypeDef.cs b/Assembly-CSharp/RimWorld/FleshTypeDef.cs index 6576abc31..32e0c995a 100644 --- a/Assembly-CSharp/RimWorld/FleshTypeDef.cs +++ b/Assembly-CSharp/RimWorld/FleshTypeDef.cs @@ -1,4 +1,3 @@ -using System; using Verse; namespace RimWorld diff --git a/Assembly-CSharp/RimWorld/FleshTypeDefOf.cs b/Assembly-CSharp/RimWorld/FleshTypeDefOf.cs index 764478efb..d6863147a 100644 --- a/Assembly-CSharp/RimWorld/FleshTypeDefOf.cs +++ b/Assembly-CSharp/RimWorld/FleshTypeDefOf.cs @@ -1,5 +1,3 @@ -using System; - namespace RimWorld { [DefOf] diff --git a/Assembly-CSharp/RimWorld/FlickUtility.cs b/Assembly-CSharp/RimWorld/FlickUtility.cs index 27ce86b77..14a483229 100644 --- a/Assembly-CSharp/RimWorld/FlickUtility.cs +++ b/Assembly-CSharp/RimWorld/FlickUtility.cs @@ -1,4 +1,3 @@ -using System; using Verse; namespace RimWorld @@ -41,7 +40,11 @@ public static bool WantsToBeOn(Thing t) return false; } CompSchedule compSchedule = t.TryGetComp(); - return compSchedule == null || compSchedule.Allowed; + if (compSchedule != null && !compSchedule.Allowed) + { + return false; + } + return true; } } } diff --git a/Assembly-CSharp/RimWorld/FloatMenuMakerMap.cs b/Assembly-CSharp/RimWorld/FloatMenuMakerMap.cs index d94b0eca9..d36d97106 100644 --- a/Assembly-CSharp/RimWorld/FloatMenuMakerMap.cs +++ b/Assembly-CSharp/RimWorld/FloatMenuMakerMap.cs @@ -18,87 +18,82 @@ private static bool CanTakeOrder(Pawn pawn) public static void TryMakeFloatMenu(Pawn pawn) { - if (!FloatMenuMakerMap.CanTakeOrder(pawn)) + if (FloatMenuMakerMap.CanTakeOrder(pawn)) { - return; - } - if (pawn.Downed) - { - Messages.Message("IsIncapped".Translate(new object[] + if (pawn.Downed) { - pawn.LabelCap - }), pawn, MessageSound.RejectInput); - return; - } - if (pawn.Map != Find.VisibleMap) - { - return; - } - List list = FloatMenuMakerMap.ChoicesAtFor(UI.MouseMapPosition(), pawn); - if (list.Count == 0) - { - return; - } - if (list.Count == 1 && list[0].autoTakeable) - { - list[0].Chosen(true); - return; + Messages.Message("IsIncapped".Translate(pawn.LabelCap), (Thing)pawn, MessageSound.RejectInput); + } + else if (pawn.Map == Find.VisibleMap) + { + List list = FloatMenuMakerMap.ChoicesAtFor(UI.MouseMapPosition(), pawn); + if (list.Count != 0) + { + if (list.Count == 1 && list[0].autoTakeable) + { + list[0].Chosen(true); + } + else + { + FloatMenuMap floatMenuMap = new FloatMenuMap(list, pawn.LabelCap, UI.MouseMapPosition()); + floatMenuMap.givesColonistOrders = true; + Find.WindowStack.Add(floatMenuMap); + } + } + } } - FloatMenuMap floatMenuMap = new FloatMenuMap(list, pawn.LabelCap, UI.MouseMapPosition()); - floatMenuMap.givesColonistOrders = true; - Find.WindowStack.Add(floatMenuMap); } public static List ChoicesAtFor(Vector3 clickPos, Pawn pawn) { IntVec3 intVec = IntVec3.FromVector3(clickPos); List list = new List(); - if (!intVec.InBounds(pawn.Map) || !FloatMenuMakerMap.CanTakeOrder(pawn)) - { - return list; - } - if (pawn.Map != Find.VisibleMap) + if (intVec.InBounds(pawn.Map) && FloatMenuMakerMap.CanTakeOrder(pawn)) { - return list; - } - DangerUtility.NotifyDirectOrderingThisFrame(pawn); - FloatMenuMakerMap.making = true; - try - { - if (intVec.Fogged(pawn.Map)) + if (pawn.Map != Find.VisibleMap) { - FloatMenuOption floatMenuOption = FloatMenuMakerMap.GotoLocationOption(intVec, pawn); - if (floatMenuOption != null && !floatMenuOption.Disabled) - { - list.Add(floatMenuOption); - } + return list; } - else + DangerUtility.NotifyDirectOrderingThisFrame(pawn); + FloatMenuMakerMap.making = true; + try { - if (pawn.Drafted) - { - FloatMenuMakerMap.AddDraftedOrders(clickPos, pawn, list); - } - if (pawn.RaceProps.Humanlike) - { - FloatMenuMakerMap.AddHumanlikeOrders(clickPos, pawn, list); - } - if (!pawn.Drafted) + if (intVec.Fogged(pawn.Map)) { - FloatMenuMakerMap.AddUndraftedOrders(clickPos, pawn, list); + FloatMenuOption floatMenuOption = FloatMenuMakerMap.GotoLocationOption(intVec, pawn); + if (floatMenuOption != null && !floatMenuOption.Disabled) + { + list.Add(floatMenuOption); + } } - foreach (FloatMenuOption current in pawn.GetExtraFloatMenuOptionsFor(intVec)) + else { - list.Add(current); + if (pawn.Drafted) + { + FloatMenuMakerMap.AddDraftedOrders(clickPos, pawn, list); + } + if (pawn.RaceProps.Humanlike) + { + FloatMenuMakerMap.AddHumanlikeOrders(clickPos, pawn, list); + } + if (!pawn.Drafted) + { + FloatMenuMakerMap.AddUndraftedOrders(clickPos, pawn, list); + } + foreach (FloatMenuOption item in pawn.GetExtraFloatMenuOptionsFor(intVec)) + { + list.Add(item); + } } } + finally + { + DangerUtility.DoneDirectOrdering(); + FloatMenuMakerMap.making = false; + } + FloatMenuMakerMap.DisableIfNotInterruptibleNow(list, pawn); + return list; } - finally - { - DangerUtility.DoneDirectOrdering(); - FloatMenuMakerMap.making = false; - } - FloatMenuMakerMap.DisableIfNotInterruptibleNow(list, pawn); return list; } @@ -106,15 +101,7 @@ private static void DisableIfNotInterruptibleNow(List opts, Paw { if (!pawn.jobs.IsCurrentJobPlayerInterruptible()) { - string str; - if (pawn.CurJob != null && pawn.CurJob.def == JobDefOf.Vomit) - { - str = "VomitingLower".Translate(); - } - else - { - str = "NotInterruptibleLower".Translate(); - } + string str = (pawn.CurJob == null || pawn.CurJob.def != JobDefOf.Vomit) ? "NotInterruptibleLower".Translate() : "VomitingLower".Translate(); for (int i = 0; i < opts.Count; i++) { if (!opts[i].Disabled) @@ -129,65 +116,47 @@ private static void DisableIfNotInterruptibleNow(List opts, Paw private static void AddDraftedOrders(Vector3 clickPos, Pawn pawn, List opts) { IntVec3 clickCell = IntVec3.FromVector3(clickPos); - foreach (LocalTargetInfo current in GenUI.TargetsAt(clickPos, TargetingParameters.ForAttackHostile(), true)) + foreach (LocalTargetInfo item in GenUI.TargetsAt(clickPos, TargetingParameters.ForAttackHostile(), true)) { - FloatMenuMakerMap.c__AnonStorey42E c__AnonStorey42E = new FloatMenuMakerMap.c__AnonStorey42E(); - c__AnonStorey42E.attackTarg = current; + LocalTargetInfo attackTarg = item; if (pawn.equipment.Primary != null && !pawn.equipment.PrimaryEq.PrimaryVerb.verbProps.MeleeRange) { - string str; - Action rangedAct = FloatMenuUtility.GetRangedAttackAction(pawn, c__AnonStorey42E.attackTarg, out str); - string text = "FireAt".Translate(new object[] - { - c__AnonStorey42E.attackTarg.Thing.Label - }); + string str = default(string); + Action rangedAct = FloatMenuUtility.GetRangedAttackAction(pawn, attackTarg, out str); + string text = "FireAt".Translate(attackTarg.Thing.Label); FloatMenuOption floatMenuOption = new FloatMenuOption(MenuOptionPriority.High); - if (rangedAct == null) + if ((object)rangedAct == null) { text = text + " (" + str + ")"; } else { floatMenuOption.autoTakeable = true; - floatMenuOption.action = delegate + floatMenuOption.action = (Action)delegate { - MoteMaker.MakeStaticMote(c__AnonStorey42E.attackTarg.Thing.DrawPos, c__AnonStorey42E.attackTarg.Thing.Map, ThingDefOf.Mote_FeedbackAttack, 1f); + MoteMaker.MakeStaticMote(attackTarg.Thing.DrawPos, attackTarg.Thing.Map, ThingDefOf.Mote_FeedbackAttack, 1f); rangedAct(); }; } floatMenuOption.Label = text; opts.Add(floatMenuOption); } - string str2; - Action meleeAct = FloatMenuUtility.GetMeleeAttackAction(pawn, c__AnonStorey42E.attackTarg, out str2); - Pawn pawn2 = c__AnonStorey42E.attackTarg.Thing as Pawn; - string text2; - if (pawn2 != null && pawn2.Downed) - { - text2 = "MeleeAttackToDeath".Translate(new object[] - { - c__AnonStorey42E.attackTarg.Thing.Label - }); - } - else - { - text2 = "MeleeAttack".Translate(new object[] - { - c__AnonStorey42E.attackTarg.Thing.Label - }); - } - MenuOptionPriority priority = (!c__AnonStorey42E.attackTarg.HasThing || !pawn.HostileTo(c__AnonStorey42E.attackTarg.Thing)) ? MenuOptionPriority.VeryLow : MenuOptionPriority.AttackEnemy; - Thing thing = c__AnonStorey42E.attackTarg.Thing; + string str2 = default(string); + Action meleeAct = FloatMenuUtility.GetMeleeAttackAction(pawn, attackTarg, out str2); + Pawn pawn2 = attackTarg.Thing as Pawn; + string text2 = (pawn2 == null || !pawn2.Downed) ? "MeleeAttack".Translate(attackTarg.Thing.Label) : "MeleeAttackToDeath".Translate(attackTarg.Thing.Label); + MenuOptionPriority priority = (MenuOptionPriority)((!attackTarg.HasThing || !pawn.HostileTo(attackTarg.Thing)) ? 1 : 6); + Thing thing = attackTarg.Thing; FloatMenuOption floatMenuOption2 = new FloatMenuOption(string.Empty, null, priority, null, thing, 0f, null, null); - if (meleeAct == null) + if ((object)meleeAct == null) { text2 = text2 + " (" + str2 + ")"; } else { - floatMenuOption2.action = delegate + floatMenuOption2.action = (Action)delegate { - MoteMaker.MakeStaticMote(c__AnonStorey42E.attackTarg.Thing.DrawPos, c__AnonStorey42E.attackTarg.Thing.Map, ThingDefOf.Mote_FeedbackAttack, 1f); + MoteMaker.MakeStaticMote(attackTarg.Thing.DrawPos, attackTarg.Thing.Map, ThingDefOf.Mote_FeedbackAttack, 1f); meleeAct(); }; } @@ -196,19 +165,19 @@ private static void AddDraftedOrders(Vector3 clickPos, Pawn pawn, List opts) { IntVec3 c = IntVec3.FromVector3(clickPos); - foreach (Thing current in c.GetThingList(pawn.Map)) + List.Enumerator enumerator = c.GetThingList(pawn.Map).GetEnumerator(); + try { - Thing t = current; - if (t.def.ingestible != null && pawn.RaceProps.CanEverEat(t) && t.IngestibleNow) + while (enumerator.MoveNext()) { - string text; - if (t.def.ingestible.ingestCommandString.NullOrEmpty()) + Thing current = enumerator.Current; + Thing t = current; + if (t.def.ingestible != null && pawn.RaceProps.CanEverEat(t) && t.IngestibleNow) { - text = "ConsumeThing".Translate(new object[] + string text = (!t.def.ingestible.ingestCommandString.NullOrEmpty()) ? string.Format(t.def.ingestible.ingestCommandString, t.LabelShort) : "ConsumeThing".Translate(t.LabelShort); + if (!t.IsSociallyProper(pawn)) { - t.LabelShort - }); - } - else - { - text = string.Format(t.def.ingestible.ingestCommandString, t.LabelShort); - } - if (!t.IsSociallyProper(pawn)) - { - text = text + " (" + "ReservedForPrisoners".Translate() + ")"; - } - FloatMenuOption item5; - if (t.def.IsPleasureDrug && pawn.IsTeetotaler()) - { - item5 = new FloatMenuOption(text + " (" + TraitDefOf.DrugDesire.DataAtDegree(-1).label + ")", null, MenuOptionPriority.Default, null, null, 0f, null, null); - } - else if (!pawn.CanReach(t, PathEndMode.OnCell, Danger.Deadly, false, TraverseMode.ByPawn)) - { - item5 = new FloatMenuOption(text + " (" + "NoPath".Translate() + ")", null, MenuOptionPriority.Default, null, null, 0f, null, null); - } - else - { - MenuOptionPriority priority = (!(t is Corpse)) ? MenuOptionPriority.Default : MenuOptionPriority.Low; - item5 = FloatMenuUtility.DecoratePrioritizedTask(new FloatMenuOption(text, delegate + text = text + " (" + "ReservedForPrisoners".Translate() + ")"; + } + FloatMenuOption item3; + if (t.def.IsPleasureDrug && pawn.IsTeetotaler()) + { + item3 = new FloatMenuOption(text + " (" + TraitDefOf.DrugDesire.DataAtDegree(-1).label + ")", null, MenuOptionPriority.Default, null, null, 0f, null, null); + } + else if (!pawn.CanReach(t, PathEndMode.OnCell, Danger.Deadly, false, TraverseMode.ByPawn)) { - t.SetForbidden(false, true); - Job job = new Job(JobDefOf.Ingest, t); - job.count = FoodUtility.WillIngestStackCountOf(pawn, t.def); - pawn.jobs.TryTakeOrderedJob(job, JobTag.Misc); - }, priority, null, null, 0f, null, null), pawn, t, "ReservedBy"); + item3 = new FloatMenuOption(text + " (" + "NoPath".Translate() + ")", null, MenuOptionPriority.Default, null, null, 0f, null, null); + } + else + { + MenuOptionPriority priority = (MenuOptionPriority)((!(t is Corpse)) ? 4 : 2); + item3 = FloatMenuUtility.DecoratePrioritizedTask(new FloatMenuOption(text, (Action)delegate() + { + t.SetForbidden(false, true); + Job job13 = new Job(JobDefOf.Ingest, t); + job13.count = FoodUtility.WillIngestStackCountOf(pawn, t.def); + pawn.jobs.TryTakeOrderedJob(job13, JobTag.Misc); + }, priority, null, null, 0f, null, null), pawn, t, "ReservedBy"); + } + opts.Add(item3); } - opts.Add(item5); } } + finally + { + ((IDisposable)(object)enumerator).Dispose(); + } if (pawn.health.capacities.CapableOf(PawnCapacityDefOf.Manipulation)) { - foreach (LocalTargetInfo current2 in GenUI.TargetsAt(clickPos, TargetingParameters.ForRescue(pawn), true)) + foreach (LocalTargetInfo item7 in GenUI.TargetsAt(clickPos, TargetingParameters.ForRescue(pawn), true)) { - Pawn victim = (Pawn)current2.Thing; - if (!victim.InBed() && pawn.CanReserveAndReach(victim, PathEndMode.OnCell, Danger.Deadly, 1, -1, null, true)) + Pawn victim = (Pawn)item7.Thing; + if (!victim.InBed() && pawn.CanReserveAndReach((Thing)victim, PathEndMode.OnCell, Danger.Deadly, 1, -1, null, true)) { if (!victim.IsPrisonerOfColony && !victim.InMentalState && (victim.Faction == Faction.OfPlayer || victim.Faction == null || !victim.Faction.HostileTo(Faction.OfPlayer))) { - Pawn victim2 = victim; - opts.Add(FloatMenuUtility.DecoratePrioritizedTask(new FloatMenuOption("Rescue".Translate(new object[] - { - victim.LabelCap - }), delegate + Pawn revalidateClickTarget = victim; + opts.Add(FloatMenuUtility.DecoratePrioritizedTask(new FloatMenuOption("Rescue".Translate(victim.LabelCap), (Action)delegate() { - Building_Bed building_Bed = RestUtility.FindBedFor(victim, pawn, false, false, false); - if (building_Bed == null) + Building_Bed building_Bed2 = RestUtility.FindBedFor(victim, pawn, false, false, false); + if (building_Bed2 == null) { - building_Bed = RestUtility.FindBedFor(victim, pawn, false, false, true); + building_Bed2 = RestUtility.FindBedFor(victim, pawn, false, false, true); } - if (building_Bed == null) + if (building_Bed2 == null) { - string str2; - if (victim.RaceProps.Animal) - { - str2 = "NoAnimalBed".Translate(); - } - else - { - str2 = "NoNonPrisonerBed".Translate(); - } - Messages.Message("CannotRescue".Translate() + ": " + str2, victim, MessageSound.RejectInput); - return; + string str2 = (!victim.RaceProps.Animal) ? "NoNonPrisonerBed".Translate() : "NoAnimalBed".Translate(); + Messages.Message("CannotRescue".Translate() + ": " + str2, (Thing)victim, MessageSound.RejectInput); } - Job job = new Job(JobDefOf.Rescue, victim, building_Bed); - job.count = 1; - pawn.jobs.TryTakeOrderedJob(job, JobTag.Misc); - PlayerKnowledgeDatabase.KnowledgeDemonstrated(ConceptDefOf.Rescuing, KnowledgeAmount.Total); - }, MenuOptionPriority.RescueOrCapture, null, victim2, 0f, null, null), pawn, victim, "ReservedBy")); + else + { + Job job12 = new Job(JobDefOf.Rescue, (Thing)victim, (Thing)building_Bed2); + job12.count = 1; + pawn.jobs.TryTakeOrderedJob(job12, JobTag.Misc); + PlayerKnowledgeDatabase.KnowledgeDemonstrated(ConceptDefOf.Rescuing, KnowledgeAmount.Total); + } + }, MenuOptionPriority.RescueOrCapture, null, revalidateClickTarget, 0f, null, null), pawn, (Thing)victim, "ReservedBy")); } if (victim.RaceProps.Humanlike && (victim.InMentalState || victim.Faction != Faction.OfPlayer || (victim.Downed && (victim.guilt.IsGuilty || victim.IsPrisonerOfColony)))) { - Pawn victim2 = victim; - opts.Add(FloatMenuUtility.DecoratePrioritizedTask(new FloatMenuOption("Capture".Translate(new object[] - { - victim.LabelCap - }), delegate + Pawn revalidateClickTarget = victim; + opts.Add(FloatMenuUtility.DecoratePrioritizedTask(new FloatMenuOption("Capture".Translate(victim.LabelCap), (Action)delegate() { Building_Bed building_Bed = RestUtility.FindBedFor(victim, pawn, true, false, false); if (building_Bed == null) @@ -343,132 +297,107 @@ private static void AddHumanlikeOrders(Vector3 clickPos, Pawn pawn, List thingList = c.GetThingList(pawn.Map); - for (int i = 0; i < thingList.Count; i++) + int num = 0; + while (num < thingList.Count) { - if (thingList[i].TryGetComp() != null) + if (thingList[num].TryGetComp() == null) { - equipment = (ThingWithComps)thingList[i]; - break; + num++; + continue; } + equipment = (ThingWithComps)thingList[num]; + break; } if (equipment != null) { string labelShort = equipment.LabelShort; - FloatMenuOption item3; + FloatMenuOption item5; if (equipment.def.IsWeapon && pawn.story.WorkTagIsDisabled(WorkTags.Violent)) { - item3 = new FloatMenuOption("CannotEquip".Translate(new object[] - { - labelShort - }) + " (" + "IsIncapableOfViolenceLower".Translate(new object[] - { - pawn.LabelShort - }) + ")", null, MenuOptionPriority.Default, null, null, 0f, null, null); + item5 = new FloatMenuOption("CannotEquip".Translate(labelShort) + " (" + "IsIncapableOfViolenceLower".Translate(pawn.LabelShort) + ")", null, MenuOptionPriority.Default, null, null, 0f, null, null); } - else if (!pawn.CanReach(equipment, PathEndMode.ClosestTouch, Danger.Deadly, false, TraverseMode.ByPawn)) + else if (!pawn.CanReach((Thing)equipment, PathEndMode.ClosestTouch, Danger.Deadly, false, TraverseMode.ByPawn)) { - item3 = new FloatMenuOption("CannotEquip".Translate(new object[] - { - labelShort - }) + " (" + "NoPath".Translate() + ")", null, MenuOptionPriority.Default, null, null, 0f, null, null); + item5 = new FloatMenuOption("CannotEquip".Translate(labelShort) + " (" + "NoPath".Translate() + ")", null, MenuOptionPriority.Default, null, null, 0f, null, null); } else if (!pawn.health.capacities.CapableOf(PawnCapacityDefOf.Manipulation)) { - item3 = new FloatMenuOption("CannotEquip".Translate(new object[] - { - labelShort - }) + " (" + "Incapable".Translate() + ")", null, MenuOptionPriority.Default, null, null, 0f, null, null); + item5 = new FloatMenuOption("CannotEquip".Translate(labelShort) + " (" + "Incapable".Translate() + ")", null, MenuOptionPriority.Default, null, null, 0f, null, null); } else { - string text2 = "Equip".Translate(new object[] - { - labelShort - }); + string text2 = "Equip".Translate(labelShort); if (equipment.def.IsRangedWeapon && pawn.story != null && pawn.story.traits.HasTrait(TraitDefOf.Brawler)) { text2 = text2 + " " + "EquipWarningBrawler".Translate(); } - item3 = FloatMenuUtility.DecoratePrioritizedTask(new FloatMenuOption(text2, delegate + item5 = FloatMenuUtility.DecoratePrioritizedTask(new FloatMenuOption(text2, (Action)delegate() { equipment.SetForbidden(false, true); - pawn.jobs.TryTakeOrderedJob(new Job(JobDefOf.Equip, equipment), JobTag.Misc); + pawn.jobs.TryTakeOrderedJob(new Job(JobDefOf.Equip, (Thing)equipment), JobTag.Misc); MoteMaker.MakeStaticMote(equipment.DrawPos, equipment.Map, ThingDefOf.Mote_FeedbackEquip, 1f); PlayerKnowledgeDatabase.KnowledgeDemonstrated(ConceptDefOf.EquippingWeapons, KnowledgeAmount.Total); - }, MenuOptionPriority.High, null, null, 0f, null, null), pawn, equipment, "ReservedBy"); + }, MenuOptionPriority.High, null, null, 0f, null, null), pawn, (Thing)equipment, "ReservedBy"); } - opts.Add(item3); + opts.Add(item5); } } if (pawn.apparel != null) @@ -476,34 +405,13 @@ private static void AddHumanlikeOrders(Vector3 clickPos, Pawn pawn, List(c); if (apparel != null) { - FloatMenuOption item4; - if (!pawn.CanReach(apparel, PathEndMode.ClosestTouch, Danger.Deadly, false, TraverseMode.ByPawn)) - { - item4 = new FloatMenuOption("CannotWear".Translate(new object[] - { - apparel.Label - }) + " (" + "NoPath".Translate() + ")", null, MenuOptionPriority.Default, null, null, 0f, null, null); - } - else if (!ApparelUtility.HasPartsToWear(pawn, apparel.def)) - { - item4 = new FloatMenuOption("CannotWear".Translate(new object[] - { - apparel.Label - }) + " (" + "CannotWearBecauseOfMissingBodyParts".Translate() + ")", null, MenuOptionPriority.Default, null, null, 0f, null, null); - } - else + FloatMenuOption item6 = pawn.CanReach((Thing)apparel, PathEndMode.ClosestTouch, Danger.Deadly, false, TraverseMode.ByPawn) ? (ApparelUtility.HasPartsToWear(pawn, apparel.def) ? FloatMenuUtility.DecoratePrioritizedTask(new FloatMenuOption("ForceWear".Translate(apparel.LabelShort), (Action)delegate() { - item4 = FloatMenuUtility.DecoratePrioritizedTask(new FloatMenuOption("ForceWear".Translate(new object[] - { - apparel.LabelShort - }), delegate - { - apparel.SetForbidden(false, true); - Job job = new Job(JobDefOf.Wear, apparel); - pawn.jobs.TryTakeOrderedJob(job, JobTag.Misc); - }, MenuOptionPriority.High, null, null, 0f, null, null), pawn, apparel, "ReservedBy"); - } - opts.Add(item4); + apparel.SetForbidden(false, true); + Job job9 = new Job(JobDefOf.Wear, (Thing)apparel); + pawn.jobs.TryTakeOrderedJob(job9, JobTag.Misc); + }, MenuOptionPriority.High, null, null, 0f, null, null), pawn, (Thing)apparel, "ReservedBy") : new FloatMenuOption("CannotWear".Translate(apparel.Label) + " (" + "CannotWearBecauseOfMissingBodyParts".Translate() + ")", null, MenuOptionPriority.Default, null, null, 0f, null, null)) : new FloatMenuOption("CannotWear".Translate(apparel.Label) + " (" + "NoPath".Translate() + ")", null, MenuOptionPriority.Default, null, null, 0f, null, null); + opts.Add(item6); } } if (!pawn.Map.IsPlayerHome) @@ -513,217 +421,160 @@ private static void AddHumanlikeOrders(Vector3 clickPos, Pawn pawn, List)delegate(int count) { item.SetForbidden(false, false); - Job job = new Job(JobDefOf.TakeInventory, item); - job.count = count; - pawn.jobs.TryTakeOrderedJob(job, JobTag.Misc); + Job job6 = new Job(JobDefOf.TakeInventory, item); + job6.count = count; + pawn.jobs.TryTakeOrderedJob(job6, JobTag.Misc); }, -2147483648); - Find.WindowStack.Add(window); + Find.WindowStack.Add(window2); }, MenuOptionPriority.High, null, null, 0f, null, null), pawn, item, "ReservedBy")); } } } if (!pawn.Map.IsPlayerHome) { - Thing item = c.GetFirstItem(pawn.Map); - if (item != null && item.def.EverHaulable) + Thing item2 = c.GetFirstItem(pawn.Map); + if (item2 != null && item2.def.EverHaulable) { Pawn bestPackAnimal = GiveToPackAnimalUtility.PackAnimalWithTheMostFreeSpace(pawn.Map, pawn.Faction); if (bestPackAnimal != null) { - if (!pawn.CanReach(item, PathEndMode.ClosestTouch, Danger.Deadly, false, TraverseMode.ByPawn)) + if (!pawn.CanReach(item2, PathEndMode.ClosestTouch, Danger.Deadly, false, TraverseMode.ByPawn)) { - opts.Add(new FloatMenuOption("CannotGiveToPackAnimal".Translate(new object[] - { - item.Label - }) + " (" + "NoPath".Translate() + ")", null, MenuOptionPriority.Default, null, null, 0f, null, null)); + opts.Add(new FloatMenuOption("CannotGiveToPackAnimal".Translate(item2.Label) + " (" + "NoPath".Translate() + ")", null, MenuOptionPriority.Default, null, null, 0f, null, null)); } - else if (MassUtility.WillBeOverEncumberedAfterPickingUp(bestPackAnimal, item, 1)) + else if (MassUtility.WillBeOverEncumberedAfterPickingUp(bestPackAnimal, item2, 1)) { - opts.Add(new FloatMenuOption("CannotGiveToPackAnimal".Translate(new object[] - { - item.Label - }) + " (" + "TooHeavy".Translate() + ")", null, MenuOptionPriority.Default, null, null, 0f, null, null)); + opts.Add(new FloatMenuOption("CannotGiveToPackAnimal".Translate(item2.Label) + " (" + "TooHeavy".Translate() + ")", null, MenuOptionPriority.Default, null, null, 0f, null, null)); } - else if (item.stackCount == 1) + else if (item2.stackCount == 1) { - opts.Add(FloatMenuUtility.DecoratePrioritizedTask(new FloatMenuOption("GiveToPackAnimal".Translate(new object[] - { - item.Label - }), delegate + opts.Add(FloatMenuUtility.DecoratePrioritizedTask(new FloatMenuOption("GiveToPackAnimal".Translate(item2.Label), (Action)delegate() { - item.SetForbidden(false, false); - Job job = new Job(JobDefOf.GiveToPackAnimal, item); - job.count = 1; - pawn.jobs.TryTakeOrderedJob(job, JobTag.Misc); - }, MenuOptionPriority.High, null, null, 0f, null, null), pawn, item, "ReservedBy")); + item2.SetForbidden(false, false); + Job job5 = new Job(JobDefOf.GiveToPackAnimal, item2); + job5.count = 1; + pawn.jobs.TryTakeOrderedJob(job5, JobTag.Misc); + }, MenuOptionPriority.High, null, null, 0f, null, null), pawn, item2, "ReservedBy")); } else { - if (MassUtility.WillBeOverEncumberedAfterPickingUp(bestPackAnimal, item, item.stackCount)) + if (MassUtility.WillBeOverEncumberedAfterPickingUp(bestPackAnimal, item2, item2.stackCount)) { - opts.Add(new FloatMenuOption("CannotGiveToPackAnimalAll".Translate(new object[] - { - item.Label - }) + " (" + "TooHeavy".Translate() + ")", null, MenuOptionPriority.Default, null, null, 0f, null, null)); + opts.Add(new FloatMenuOption("CannotGiveToPackAnimalAll".Translate(item2.Label) + " (" + "TooHeavy".Translate() + ")", null, MenuOptionPriority.Default, null, null, 0f, null, null)); } else { - opts.Add(FloatMenuUtility.DecoratePrioritizedTask(new FloatMenuOption("GiveToPackAnimalAll".Translate(new object[] - { - item.Label - }), delegate + opts.Add(FloatMenuUtility.DecoratePrioritizedTask(new FloatMenuOption("GiveToPackAnimalAll".Translate(item2.Label), (Action)delegate() { - item.SetForbidden(false, false); - Job job = new Job(JobDefOf.GiveToPackAnimal, item); - job.count = item.stackCount; - pawn.jobs.TryTakeOrderedJob(job, JobTag.Misc); - }, MenuOptionPriority.High, null, null, 0f, null, null), pawn, item, "ReservedBy")); + item2.SetForbidden(false, false); + Job job4 = new Job(JobDefOf.GiveToPackAnimal, item2); + job4.count = item2.stackCount; + pawn.jobs.TryTakeOrderedJob(job4, JobTag.Misc); + }, MenuOptionPriority.High, null, null, 0f, null, null), pawn, item2, "ReservedBy")); } - opts.Add(FloatMenuUtility.DecoratePrioritizedTask(new FloatMenuOption("GiveToPackAnimalSome".Translate(new object[] + opts.Add(FloatMenuUtility.DecoratePrioritizedTask(new FloatMenuOption("GiveToPackAnimalSome".Translate(item2.Label), (Action)delegate() { - item.Label - }), delegate - { - int to = Mathf.Min(MassUtility.CountToPickUpUntilOverEncumbered(bestPackAnimal, item), item.stackCount); - Dialog_Slider window = new Dialog_Slider("GiveToPackAnimalCount".Translate(new object[] - { - item.LabelShort - }), 1, to, delegate(int count) + int to = Mathf.Min(MassUtility.CountToPickUpUntilOverEncumbered(bestPackAnimal, item2), item2.stackCount); + Dialog_Slider window = new Dialog_Slider("GiveToPackAnimalCount".Translate(item2.LabelShort), 1, to, (Action)delegate(int count) { - item.SetForbidden(false, false); - Job job = new Job(JobDefOf.GiveToPackAnimal, item); - job.count = count; - pawn.jobs.TryTakeOrderedJob(job, JobTag.Misc); + item2.SetForbidden(false, false); + Job job3 = new Job(JobDefOf.GiveToPackAnimal, item2); + job3.count = count; + pawn.jobs.TryTakeOrderedJob(job3, JobTag.Misc); }, -2147483648); Find.WindowStack.Add(window); - }, MenuOptionPriority.High, null, null, 0f, null, null), pawn, item, "ReservedBy")); + }, MenuOptionPriority.High, null, null, 0f, null, null), pawn, item2, "ReservedBy")); } } } } if (!pawn.Map.IsPlayerHome && pawn.Map.exitMapGrid.MapUsesExitGrid) { - foreach (LocalTargetInfo current5 in GenUI.TargetsAt(clickPos, TargetingParameters.ForRescue(pawn), true)) + foreach (LocalTargetInfo item10 in GenUI.TargetsAt(clickPos, TargetingParameters.ForRescue(pawn), true)) { - Pawn p = (Pawn)current5.Thing; + Pawn p = (Pawn)item10.Thing; if (p.Faction == Faction.OfPlayer || p.HostFaction == Faction.OfPlayer) { - if (!pawn.CanReach(p, PathEndMode.ClosestTouch, Danger.Deadly, false, TraverseMode.ByPawn)) + IntVec3 exitSpot; + if (!pawn.CanReach((Thing)p, PathEndMode.ClosestTouch, Danger.Deadly, false, TraverseMode.ByPawn)) { - opts.Add(new FloatMenuOption("CannotCarryToExit".Translate(new object[] - { - p.Label - }) + " (" + "NoPath".Translate() + ")", null, MenuOptionPriority.Default, null, null, 0f, null, null)); + opts.Add(new FloatMenuOption("CannotCarryToExit".Translate(p.Label) + " (" + "NoPath".Translate() + ")", null, MenuOptionPriority.Default, null, null, 0f, null, null)); + } + else if (!RCellFinder.TryFindBestExitSpot(pawn, out exitSpot, TraverseMode.ByPawn)) + { + opts.Add(new FloatMenuOption("CannotCarryToExit".Translate(p.Label) + " (" + "NoPath".Translate() + ")", null, MenuOptionPriority.Default, null, null, 0f, null, null)); } else { - IntVec3 exitSpot; - if (!RCellFinder.TryFindBestExitSpot(pawn, out exitSpot, TraverseMode.ByPawn)) - { - opts.Add(new FloatMenuOption("CannotCarryToExit".Translate(new object[] - { - p.Label - }) + " (" + "NoPath".Translate() + ")", null, MenuOptionPriority.Default, null, null, 0f, null, null)); - } - else + opts.Add(FloatMenuUtility.DecoratePrioritizedTask(new FloatMenuOption("CarryToExit".Translate(p.Label), (Action)delegate() { - opts.Add(FloatMenuUtility.DecoratePrioritizedTask(new FloatMenuOption("CarryToExit".Translate(new object[] - { - p.Label - }), delegate - { - Job job = new Job(JobDefOf.CarryDownedPawnToExit, p, exitSpot); - job.count = 1; - pawn.jobs.TryTakeOrderedJob(job, JobTag.Misc); - }, MenuOptionPriority.High, null, null, 0f, null, null), pawn, current5, "ReservedBy")); - } + Job job2 = new Job(JobDefOf.CarryDownedPawnToExit, (Thing)p, exitSpot); + job2.count = 1; + pawn.jobs.TryTakeOrderedJob(job2, JobTag.Misc); + }, MenuOptionPriority.High, null, null, 0f, null, null), pawn, item10, "ReservedBy")); } } } } - if (pawn.equipment != null && pawn.equipment.Primary != null && GenUI.TargetsAt(clickPos, TargetingParameters.ForSelf(pawn), true).Any()) + if (pawn.equipment != null && pawn.equipment.Primary != null && GenUI.TargetsAt(clickPos, TargetingParameters.ForSelf(pawn), true).Any()) { - Action action2 = delegate + Action action2 = (Action)delegate() { - pawn.jobs.TryTakeOrderedJob(new Job(JobDefOf.DropEquipment, pawn.equipment.Primary), JobTag.Misc); + pawn.jobs.TryTakeOrderedJob(new Job(JobDefOf.DropEquipment, (Thing)pawn.equipment.Primary), JobTag.Misc); }; - opts.Add(new FloatMenuOption("Drop".Translate(new object[] - { - pawn.equipment.Primary.Label - }), action2, MenuOptionPriority.Default, null, null, 0f, null, null)); + opts.Add(new FloatMenuOption("Drop".Translate(pawn.equipment.Primary.Label), action2, MenuOptionPriority.Default, null, null, 0f, null, null)); } - foreach (LocalTargetInfo current6 in GenUI.TargetsAt(clickPos, TargetingParameters.ForTrade(), true)) + foreach (LocalTargetInfo item11 in GenUI.TargetsAt(clickPos, TargetingParameters.ForTrade(), true)) { - LocalTargetInfo dest = current6; - if (!pawn.CanReach(dest, PathEndMode.OnCell, Danger.Deadly, false, TraverseMode.ByPawn)) + LocalTargetInfo _ = item11; + if (!pawn.CanReach(item11, PathEndMode.OnCell, Danger.Deadly, false, TraverseMode.ByPawn)) { opts.Add(new FloatMenuOption("CannotTrade".Translate() + " (" + "NoPath".Translate() + ")", null, MenuOptionPriority.Default, null, null, 0f, null, null)); } else { - Pawn pTarg = (Pawn)dest.Thing; - Action action3 = delegate + Pawn pTarg = (Pawn)item11.Thing; + Action action3 = (Action)delegate() { - Job job = new Job(JobDefOf.TradeWithPawn, pTarg); + Job job = new Job(JobDefOf.TradeWithPawn, (Thing)pTarg); job.playerForced = true; pawn.jobs.TryTakeOrderedJob(job, JobTag.Misc); PlayerKnowledgeDatabase.KnowledgeDemonstrated(ConceptDefOf.InteractingWithTraders, KnowledgeAmount.Total); @@ -733,18 +584,15 @@ private static void AddHumanlikeOrders(Vector3 clickPos, Pawn pawn, List(); - if (jobGiver_Work != null) + else { - foreach (Thing current2 in pawn.Map.thingGrid.ThingsAt(clickCell)) + JobGiver_Work jobGiver_Work = pawn.thinker.TryGetMainTreeThinkNode(); + if (jobGiver_Work != null) { - foreach (WorkTypeDef current3 in DefDatabase.AllDefsListForReading) + foreach (Thing item2 in pawn.Map.thingGrid.ThingsAt(clickCell)) { - for (int i = 0; i < current3.workGiversByPriority.Count; i++) + List.Enumerator enumerator3 = DefDatabase.AllDefsListForReading.GetEnumerator(); + try { - WorkGiver_Scanner workGiver_Scanner = current3.workGiversByPriority[i].Worker as WorkGiver_Scanner; - if (workGiver_Scanner != null && workGiver_Scanner.def.directOrderable && !workGiver_Scanner.ShouldSkip(pawn)) + while (enumerator3.MoveNext()) { - JobFailReason.Clear(); - if (workGiver_Scanner.PotentialWorkThingRequest.Accepts(current2) || (workGiver_Scanner.PotentialWorkThingsGlobal(pawn) != null && workGiver_Scanner.PotentialWorkThingsGlobal(pawn).Contains(current2))) + WorkTypeDef current3 = enumerator3.Current; + for (int i = 0; i < current3.workGiversByPriority.Count; i++) { - string label = null; - Action action = null; - PawnCapacityDef pawnCapacityDef = workGiver_Scanner.MissingRequiredCapacity(pawn); - if (pawnCapacityDef != null) - { - label = "CannotMissingHealthActivities".Translate(new object[] - { - pawnCapacityDef.label - }); - } - else + WorkGiver_Scanner workGiver_Scanner = current3.workGiversByPriority[i].Worker as WorkGiver_Scanner; + string label; + Action action; + if (workGiver_Scanner != null && workGiver_Scanner.def.directOrderable && !workGiver_Scanner.ShouldSkip(pawn)) { - Job job; - if (!workGiver_Scanner.HasJobOnThing(pawn, current2, true)) + JobFailReason.Clear(); + if (!workGiver_Scanner.PotentialWorkThingRequest.Accepts(item2) && (workGiver_Scanner.PotentialWorkThingsGlobal(pawn) == null || !workGiver_Scanner.PotentialWorkThingsGlobal(pawn).Contains(item2))) { - job = null; + continue; } - else + label = (string)null; + action = null; + PawnCapacityDef pawnCapacityDef = workGiver_Scanner.MissingRequiredCapacity(pawn); + if (pawnCapacityDef != null) { - job = workGiver_Scanner.JobOnThing(pawn, current2, true); + label = "CannotMissingHealthActivities".Translate(pawnCapacityDef.label); } - if (job == null) + else { - if (!JobFailReason.HaveReason) + Job job = workGiver_Scanner.HasJobOnThing(pawn, item2, true) ? workGiver_Scanner.JobOnThing(pawn, item2, true) : null; + if (job == null) { - goto IL_5EF; + if (JobFailReason.HaveReason) + { + label = "CannotGenericWork".Translate(workGiver_Scanner.def.verb, item2.LabelShort) + " (" + JobFailReason.Reason + ")"; + goto IL_059c; + } + continue; } - label = "CannotGenericWork".Translate(new object[] - { - workGiver_Scanner.def.verb, - current2.LabelShort - }) + " (" + JobFailReason.Reason + ")"; - } - else - { WorkTypeDef workType = workGiver_Scanner.def.workType; if (pawn.story != null && pawn.story.WorkTagIsDisabled(workGiver_Scanner.def.workTags)) { - label = "CannotPrioritizeWorkGiverDisabled".Translate(new object[] - { - workGiver_Scanner.def.label - }); + label = "CannotPrioritizeWorkGiverDisabled".Translate(workGiver_Scanner.def.label); } else if (pawn.jobs.curJob != null && pawn.jobs.curJob.JobIsSameAs(job)) { - label = "CannotGenericAlreadyAm".Translate(new object[] - { - workType.gerundLabel, - current2.LabelShort - }); + label = "CannotGenericAlreadyAm".Translate(workType.gerundLabel, item2.LabelShort); } else if (pawn.workSettings.GetPriority(workType) == 0) { if (pawn.story.WorkTypeIsDisabled(workType)) { - label = "CannotPrioritizeWorkTypeDisabled".Translate(new object[] - { - workType.gerundLabel - }); + label = "CannotPrioritizeWorkTypeDisabled".Translate(workType.gerundLabel); } else if ("CannotPrioritizeNotAssignedToWorkType".CanTranslate()) { - label = "CannotPrioritizeNotAssignedToWorkType".Translate(new object[] - { - workType.gerundLabel - }); + label = "CannotPrioritizeNotAssignedToWorkType".Translate(workType.gerundLabel); } else { - label = "CannotPrioritizeIsNotA".Translate(new object[] - { - pawn.NameStringShort, - workType.pawnLabel - }); + label = "CannotPrioritizeIsNotA".Translate(pawn.NameStringShort, workType.pawnLabel); } } - else if (job.def == JobDefOf.Research && current2 is Building_ResearchBench) + else if (job.def == JobDefOf.Research && item2 is Building_ResearchBench) { label = "CannotPrioritizeResearch".Translate(); } - else if (current2.IsForbidden(pawn)) + else if (item2.IsForbidden(pawn)) { - if (!current2.Position.InAllowedArea(pawn)) + if (!item2.Position.InAllowedArea(pawn)) { - label = "CannotPrioritizeForbiddenOutsideAllowedArea".Translate(new object[] - { - current2.Label - }); + label = "CannotPrioritizeForbiddenOutsideAllowedArea".Translate(item2.Label); } else { - label = "CannotPrioritizeForbidden".Translate(new object[] - { - current2.Label - }); + label = "CannotPrioritizeForbidden".Translate(item2.Label); } } - else if (!pawn.CanReach(current2, workGiver_Scanner.PathEndMode, Danger.Deadly, false, TraverseMode.ByPawn)) + else if (!pawn.CanReach(item2, workGiver_Scanner.PathEndMode, Danger.Deadly, false, TraverseMode.ByPawn)) { - label = (current2.Label + ": " + "NoPath".Translate()).CapitalizeFirst(); + label = (item2.Label + ": " + "NoPath".Translate()).CapitalizeFirst(); } else { - label = "PrioritizeGeneric".Translate(new object[] - { - workGiver_Scanner.def.gerund, - current2.Label - }); + label = "PrioritizeGeneric".Translate(workGiver_Scanner.def.gerund, item2.Label); Job localJob = job; WorkGiver_Scanner localScanner = workGiver_Scanner; - action = delegate + action = (Action)delegate() { pawn.jobs.TryTakeOrderedJobPrioritizedWork(localJob, localScanner, clickCell); }; } } + goto IL_059c; } - if (!opts.Any((FloatMenuOption op) => op.Label == label.TrimEnd(new char[0]))) + continue; + IL_059c: + if (!opts.Any((Predicate)((FloatMenuOption op) => op.Label == label.TrimEnd()))) { - opts.Add(FloatMenuUtility.DecoratePrioritizedTask(new FloatMenuOption(label, action, MenuOptionPriority.Default, null, null, 0f, null, null), pawn, current2, "ReservedBy")); + opts.Add(FloatMenuUtility.DecoratePrioritizedTask(new FloatMenuOption(label, action, MenuOptionPriority.Default, null, null, 0f, null, null), pawn, item2, "ReservedBy")); } } } - IL_5EF:; + } + finally + { + ((IDisposable)(object)enumerator3).Dispose(); } } - } - foreach (WorkTypeDef current4 in DefDatabase.AllDefsListForReading) - { - for (int j = 0; j < current4.workGiversByPriority.Count; j++) + List.Enumerator enumerator4 = DefDatabase.AllDefsListForReading.GetEnumerator(); + try { - WorkGiver_Scanner workGiver_Scanner2 = current4.workGiversByPriority[j].Worker as WorkGiver_Scanner; - if (workGiver_Scanner2 != null && workGiver_Scanner2.def.directOrderable && !workGiver_Scanner2.ShouldSkip(pawn)) + while (enumerator4.MoveNext()) { - JobFailReason.Clear(); - if (workGiver_Scanner2.PotentialWorkCellsGlobal(pawn).Contains(clickCell)) + WorkTypeDef current4 = enumerator4.Current; + for (int j = 0; j < current4.workGiversByPriority.Count; j++) { - Action action2 = null; - string label = null; - PawnCapacityDef pawnCapacityDef2 = workGiver_Scanner2.MissingRequiredCapacity(pawn); - if (pawnCapacityDef2 != null) - { - label = "CannotMissingHealthActivities".Translate(new object[] - { - pawnCapacityDef2.label - }); - } - else + WorkGiver_Scanner workGiver_Scanner2 = current4.workGiversByPriority[j].Worker as WorkGiver_Scanner; + Action action2; + string label2; + if (workGiver_Scanner2 != null && workGiver_Scanner2.def.directOrderable && !workGiver_Scanner2.ShouldSkip(pawn)) { - Job job2; - if (!workGiver_Scanner2.HasJobOnCell(pawn, clickCell)) - { - job2 = null; - } - else + JobFailReason.Clear(); + if (workGiver_Scanner2.PotentialWorkCellsGlobal(pawn).Contains(clickCell)) { - job2 = workGiver_Scanner2.JobOnCell(pawn, clickCell); - } - if (job2 == null) - { - if (!JobFailReason.HaveReason) + action2 = null; + label2 = (string)null; + PawnCapacityDef pawnCapacityDef2 = workGiver_Scanner2.MissingRequiredCapacity(pawn); + if (pawnCapacityDef2 != null) { - goto IL_A08; + label2 = "CannotMissingHealthActivities".Translate(pawnCapacityDef2.label); } - label = "CannotGenericWork".Translate(new object[] - { - workGiver_Scanner2.def.verb, - "AreaLower".Translate() - }) + " (" + JobFailReason.Reason + ")"; - } - else - { - WorkTypeDef workType2 = workGiver_Scanner2.def.workType; - if (pawn.jobs.curJob != null && pawn.jobs.curJob.JobIsSameAs(job2)) - { - label = "CannotGenericAlreadyAm".Translate(new object[] - { - workType2.gerundLabel, - "AreaLower".Translate() - }); - } - else if (pawn.workSettings.GetPriority(workType2) == 0) + else { - if (pawn.story.WorkTypeIsDisabled(workType2)) + Job job2 = workGiver_Scanner2.HasJobOnCell(pawn, clickCell) ? workGiver_Scanner2.JobOnCell(pawn, clickCell) : null; + if (job2 == null) { - label = "CannotPrioritizeWorkTypeDisabled".Translate(new object[] + if (JobFailReason.HaveReason) { - workType2.gerundLabel - }); + label2 = "CannotGenericWork".Translate(workGiver_Scanner2.def.verb, "AreaLower".Translate()) + " (" + JobFailReason.Reason + ")"; + goto IL_09b0; + } + continue; } - else if ("CannotPrioritizeNotAssignedToWorkType".CanTranslate()) + WorkTypeDef workType2 = workGiver_Scanner2.def.workType; + if (pawn.jobs.curJob != null && pawn.jobs.curJob.JobIsSameAs(job2)) { - label = "CannotPrioritizeNotAssignedToWorkType".Translate(new object[] - { - workType2.gerundLabel - }); + label2 = "CannotGenericAlreadyAm".Translate(workType2.gerundLabel, "AreaLower".Translate()); } - else + else if (pawn.workSettings.GetPriority(workType2) == 0) { - label = "CannotPrioritizeIsNotA".Translate(new object[] + if (pawn.story.WorkTypeIsDisabled(workType2)) { - pawn.NameStringShort, - workType2.pawnLabel - }); + label2 = "CannotPrioritizeWorkTypeDisabled".Translate(workType2.gerundLabel); + } + else if ("CannotPrioritizeNotAssignedToWorkType".CanTranslate()) + { + label2 = "CannotPrioritizeNotAssignedToWorkType".Translate(workType2.gerundLabel); + } + else + { + label2 = "CannotPrioritizeIsNotA".Translate(pawn.NameStringShort, workType2.pawnLabel); + } } - } - else if (!pawn.CanReach(clickCell, PathEndMode.Touch, Danger.Deadly, false, TraverseMode.ByPawn)) - { - label = "AreaLower".Translate().CapitalizeFirst() + ": " + "NoPath".Translate(); - } - else - { - label = "PrioritizeGeneric".Translate(new object[] + else if (!pawn.CanReach(clickCell, PathEndMode.Touch, Danger.Deadly, false, TraverseMode.ByPawn)) { - workGiver_Scanner2.def.gerund, - "AreaLower".Translate() - }); - Job localJob = job2; - WorkGiver_Scanner localScanner = workGiver_Scanner2; - action2 = delegate + label2 = "AreaLower".Translate().CapitalizeFirst() + ": " + "NoPath".Translate(); + } + else { - pawn.jobs.TryTakeOrderedJobPrioritizedWork(localJob, localScanner, clickCell); - }; + label2 = "PrioritizeGeneric".Translate(workGiver_Scanner2.def.gerund, "AreaLower".Translate()); + Job localJob2 = job2; + WorkGiver_Scanner localScanner2 = workGiver_Scanner2; + action2 = (Action)delegate() + { + pawn.jobs.TryTakeOrderedJobPrioritizedWork(localJob2, localScanner2, clickCell); + }; + } } + goto IL_09b0; } } - if (!opts.Any((FloatMenuOption op) => op.Label == label.TrimEnd(new char[0]))) + continue; + IL_09b0: + if (!opts.Any((Predicate)((FloatMenuOption op) => op.Label == label2.TrimEnd()))) { - opts.Add(FloatMenuUtility.DecoratePrioritizedTask(new FloatMenuOption(label, action2, MenuOptionPriority.Default, null, null, 0f, null, null), pawn, clickCell, "ReservedBy")); + opts.Add(FloatMenuUtility.DecoratePrioritizedTask(new FloatMenuOption(label2, action2, MenuOptionPriority.Default, null, null, 0f, null, null), pawn, clickCell, "ReservedBy")); } } } - IL_A08:; + } + finally + { + ((IDisposable)(object)enumerator4).Dispose(); } } } @@ -1024,42 +822,36 @@ private static void AddUndraftedOrders(Vector3 clickPos, Pawn pawn, List(IEnumerable objects, Func labelGetter, Func actionGetter) { List list = new List(); - foreach (T current in objects) + foreach (T item in objects) { - T arg = current; - list.Add(new FloatMenuOption(labelGetter(arg), actionGetter(arg), MenuOptionPriority.Default, null, null, 0f, null, null)); + T _ = item; + list.Add(new FloatMenuOption(labelGetter(item), actionGetter(item), MenuOptionPriority.Default, null, null, 0f, null, null)); } Find.WindowStack.Add(new FloatMenu(list)); } @@ -32,16 +32,15 @@ public static Action GetRangedAttackAction(Pawn pawn, LocalTargetInfo target, ou } if (!pawn.Drafted) { - failStr = "IsNotDraftedLower".Translate(new object[] - { - pawn.NameStringShort - }); + failStr = "IsNotDraftedLower".Translate(pawn.NameStringShort); + goto IL_017d; } - else if (!pawn.IsColonistPlayerControlled) + if (!pawn.IsColonistPlayerControlled) { failStr = "CannotOrderNonControlledLower".Translate(); + goto IL_017d; } - else if (target.IsValid && !pawn.equipment.PrimaryEq.PrimaryVerb.CanHitTarget(target)) + if (target.IsValid && !pawn.equipment.PrimaryEq.PrimaryVerb.CanHitTarget(target)) { if (!pawn.Position.InHorDistOf(target.Cell, primaryVerb.verbProps.range)) { @@ -51,22 +50,19 @@ public static Action GetRangedAttackAction(Pawn pawn, LocalTargetInfo target, ou { failStr = "CannotHitTarget".Translate(); } + goto IL_017d; } - else + if (pawn.story.WorkTagIsDisabled(WorkTags.Violent)) { - if (!pawn.story.WorkTagIsDisabled(WorkTags.Violent)) - { - return delegate - { - Job job = new Job(JobDefOf.AttackStatic, target); - pawn.jobs.TryTakeOrderedJob(job, JobTag.Misc); - }; - } - failStr = "IsIncapableOfViolenceLower".Translate(new object[] - { - pawn.NameStringShort - }); + failStr = "IsIncapableOfViolenceLower".Translate(pawn.NameStringShort); + goto IL_017d; } + return (Action)delegate() + { + Job job = new Job(JobDefOf.AttackStatic, target); + pawn.jobs.TryTakeOrderedJob(job, JobTag.Misc); + }; + IL_017d: return null; } @@ -75,43 +71,40 @@ public static Action GetMeleeAttackAction(Pawn pawn, LocalTargetInfo target, out failStr = string.Empty; if (!pawn.Drafted) { - failStr = "IsNotDraftedLower".Translate(new object[] - { - pawn.NameStringShort - }); + failStr = "IsNotDraftedLower".Translate(pawn.NameStringShort); + goto IL_011a; } - else if (!pawn.IsColonistPlayerControlled) + if (!pawn.IsColonistPlayerControlled) { failStr = "CannotOrderNonControlledLower".Translate(); + goto IL_011a; } - else if (target.IsValid && !pawn.CanReach(target, PathEndMode.Touch, Danger.Deadly, false, TraverseMode.ByPawn)) + if (target.IsValid && !pawn.CanReach(target, PathEndMode.Touch, Danger.Deadly, false, TraverseMode.ByPawn)) { failStr = "NoPath".Translate(); + goto IL_011a; } - else if (pawn.story.WorkTagIsDisabled(WorkTags.Violent)) + if (pawn.story.WorkTagIsDisabled(WorkTags.Violent)) { - failStr = "IsIncapableOfViolenceLower".Translate(new object[] - { - pawn.NameStringShort - }); + failStr = "IsIncapableOfViolenceLower".Translate(pawn.NameStringShort); + goto IL_011a; } - else + if (pawn.meleeVerbs.TryGetMeleeVerb() == null) { - if (pawn.meleeVerbs.TryGetMeleeVerb() != null) - { - return delegate - { - Job job = new Job(JobDefOf.AttackMelee, target); - Pawn pawn2 = target.Thing as Pawn; - if (pawn2 != null) - { - job.killIncappedTarget = pawn2.Downed; - } - pawn.jobs.TryTakeOrderedJob(job, JobTag.Misc); - }; - } failStr = "Incapable".Translate(); + goto IL_011a; } + return (Action)delegate() + { + Job job = new Job(JobDefOf.AttackMelee, target); + Pawn pawn2 = target.Thing as Pawn; + if (pawn2 != null) + { + job.killIncappedTarget = pawn2.Downed; + } + pawn.jobs.TryTakeOrderedJob(job, JobTag.Misc); + }; + IL_011a: return null; } @@ -126,7 +119,7 @@ public static Action GetAttackAction(Pawn pawn, LocalTargetInfo target, out stri public static FloatMenuOption DecoratePrioritizedTask(FloatMenuOption option, Pawn pawn, LocalTargetInfo target, string reservedText = "ReservedBy") { - if (option.action == null) + if ((object)option.action == null) { return option; } @@ -139,10 +132,7 @@ public static FloatMenuOption DecoratePrioritizedTask(FloatMenuOption option, Pa } if (pawn2 != null) { - option.Label = option.Label + " (" + reservedText.Translate(new object[] - { - pawn2.LabelShort - }) + ")"; + option.Label = option.Label + " (" + reservedText.Translate(pawn2.LabelShort) + ")"; } } return option; diff --git a/Assembly-CSharp/RimWorld/FoodPreferability.cs b/Assembly-CSharp/RimWorld/FoodPreferability.cs index 89277915a..111e29221 100644 --- a/Assembly-CSharp/RimWorld/FoodPreferability.cs +++ b/Assembly-CSharp/RimWorld/FoodPreferability.cs @@ -1,17 +1,15 @@ -using System; - namespace RimWorld { public enum FoodPreferability : byte { - Undefined, - NeverForNutrition, - DesperateOnly, - RawBad, - RawTasty, - MealAwful, - MealSimple, - MealFine, - MealLavish + Undefined = 0, + NeverForNutrition = 1, + DesperateOnly = 2, + RawBad = 3, + RawTasty = 4, + MealAwful = 5, + MealSimple = 6, + MealFine = 7, + MealLavish = 8 } } diff --git a/Assembly-CSharp/RimWorld/FoodTypeFlagsExtension.cs b/Assembly-CSharp/RimWorld/FoodTypeFlagsExtension.cs index bb8aa0dfd..ed97e168d 100644 --- a/Assembly-CSharp/RimWorld/FoodTypeFlagsExtension.cs +++ b/Assembly-CSharp/RimWorld/FoodTypeFlagsExtension.cs @@ -1,4 +1,3 @@ -using System; using Verse; namespace RimWorld @@ -8,11 +7,11 @@ public static class FoodTypeFlagsExtension public static string ToHumanString(this FoodTypeFlags ft) { string text = string.Empty; - if ((ft & FoodTypeFlags.VegetableOrFruit) != FoodTypeFlags.None) + if (((int)ft & 1) != 0) { text += "FoodTypeFlags_VegetableOrFruit".Translate(); } - if ((ft & FoodTypeFlags.Meat) != FoodTypeFlags.None) + if (((int)ft & 2) != 0) { if (text.Length > 0) { @@ -20,7 +19,7 @@ public static string ToHumanString(this FoodTypeFlags ft) } text += "FoodTypeFlags_Meat".Translate(); } - if ((ft & FoodTypeFlags.Corpse) != FoodTypeFlags.None) + if (((int)ft & 8) != 0) { if (text.Length > 0) { @@ -28,7 +27,7 @@ public static string ToHumanString(this FoodTypeFlags ft) } text += "FoodTypeFlags_Corpse".Translate(); } - if ((ft & FoodTypeFlags.Seed) != FoodTypeFlags.None) + if (((int)ft & 16) != 0) { if (text.Length > 0) { @@ -36,7 +35,7 @@ public static string ToHumanString(this FoodTypeFlags ft) } text += "FoodTypeFlags_Seed".Translate(); } - if ((ft & FoodTypeFlags.AnimalProduct) != FoodTypeFlags.None) + if (((int)ft & 32) != 0) { if (text.Length > 0) { @@ -44,7 +43,7 @@ public static string ToHumanString(this FoodTypeFlags ft) } text += "FoodTypeFlags_AnimalProduct".Translate(); } - if ((ft & FoodTypeFlags.Plant) != FoodTypeFlags.None) + if (((int)ft & 64) != 0) { if (text.Length > 0) { @@ -52,7 +51,7 @@ public static string ToHumanString(this FoodTypeFlags ft) } text += "FoodTypeFlags_Plant".Translate(); } - if ((ft & FoodTypeFlags.Tree) != FoodTypeFlags.None) + if (((int)ft & 128) != 0) { if (text.Length > 0) { @@ -60,7 +59,7 @@ public static string ToHumanString(this FoodTypeFlags ft) } text += "FoodTypeFlags_Tree".Translate(); } - if ((ft & FoodTypeFlags.Meal) != FoodTypeFlags.None) + if (((int)ft & 256) != 0) { if (text.Length > 0) { @@ -68,7 +67,7 @@ public static string ToHumanString(this FoodTypeFlags ft) } text += "FoodTypeFlags_Meal".Translate(); } - if ((ft & FoodTypeFlags.Processed) != FoodTypeFlags.None) + if (((int)ft & 512) != 0) { if (text.Length > 0) { @@ -76,7 +75,7 @@ public static string ToHumanString(this FoodTypeFlags ft) } text += "FoodTypeFlags_Processed".Translate(); } - if ((ft & FoodTypeFlags.Liquor) != FoodTypeFlags.None) + if (((int)ft & 1024) != 0) { if (text.Length > 0) { @@ -84,7 +83,7 @@ public static string ToHumanString(this FoodTypeFlags ft) } text += "FoodTypeFlags_Liquor".Translate(); } - if ((ft & FoodTypeFlags.Kibble) != FoodTypeFlags.None) + if (((int)ft & 2048) != 0) { if (text.Length > 0) { diff --git a/Assembly-CSharp/RimWorld/FoodUtility.cs b/Assembly-CSharp/RimWorld/FoodUtility.cs index ee0ca2a72..eaf006343 100644 --- a/Assembly-CSharp/RimWorld/FoodUtility.cs +++ b/Assembly-CSharp/RimWorld/FoodUtility.cs @@ -110,7 +110,7 @@ public static bool TryFindBestFoodSourceFor(Pawn getter, Pawn eater, bool desper } float num = FoodUtility.FoodSourceOptimality(eater, thing2, (float)(getter.Position - thing2.Position).LengthManhattan, false); float num2 = FoodUtility.FoodSourceOptimality(eater, thing, 0f, false); - num2 -= 32f; + num2 = (float)(num2 - 32.0); if (num > num2) { foodSource = thing2; @@ -137,7 +137,7 @@ public static ThingDef GetFinalIngestibleDef(Thing foodSource) return foodSource.def; } - public static Thing BestFoodInInventory(Pawn holder, Pawn eater = null, FoodPreferability minFoodPref = FoodPreferability.NeverForNutrition, FoodPreferability maxFoodPref = FoodPreferability.MealLavish, float minStackNutrition = 0f, bool allowDrug = false) + public static Thing BestFoodInInventory(Pawn holder, Pawn eater = null, FoodPreferability minFoodPref = FoodPreferability.NeverForNutrition, FoodPreferability maxFoodPref = FoodPreferability.MealLavish, float minStackNutrition = 0, bool allowDrug = false) { if (holder.inventory == null) { @@ -151,7 +151,7 @@ public static Thing BestFoodInInventory(Pawn holder, Pawn eater = null, FoodPref for (int i = 0; i < innerContainer.Count; i++) { Thing thing = innerContainer[i]; - if (thing.def.IsNutritionGivingIngestible && thing.IngestibleNow && eater.RaceProps.CanEverEat(thing) && thing.def.ingestible.preferability >= minFoodPref && thing.def.ingestible.preferability <= maxFoodPref && (allowDrug || !thing.def.IsDrug)) + if (thing.def.IsNutritionGivingIngestible && thing.IngestibleNow && eater.RaceProps.CanEverEat(thing) && (int)thing.def.ingestible.preferability >= (int)minFoodPref && (int)thing.def.ingestible.preferability <= (int)maxFoodPref && (allowDrug || !thing.def.IsDrug)) { float num = thing.def.ingestible.nutrition * (float)thing.stackCount; if (num >= minStackNutrition) @@ -168,15 +168,7 @@ public static Thing BestFoodSourceOnMap(Pawn getter, Pawn eater, bool desperate, bool getterCanManipulate = getter.RaceProps.ToolUser && getter.health.capacities.CapableOf(PawnCapacityDefOf.Manipulation); if (!getterCanManipulate && getter != eater) { - Log.Error(string.Concat(new object[] - { - getter, - " tried to find food to bring to ", - eater, - " but ", - getter, - " is incapable of Manipulation." - })); + Log.Error(getter + " tried to find food to bring to " + eater + " but " + getter + " is incapable of Manipulation."); return null; } FoodPreferability minPref; @@ -190,9 +182,9 @@ public static Thing BestFoodSourceOnMap(Pawn getter, Pawn eater, bool desperate, } else { - minPref = ((eater.needs.food.CurCategory <= HungerCategory.UrgentlyHungry) ? FoodPreferability.RawBad : FoodPreferability.MealAwful); + minPref = (FoodPreferability)(((int)eater.needs.food.CurCategory <= 2) ? 3 : 5); } - Predicate foodValidator = delegate(Thing t) + Predicate foodValidator = (Predicate)delegate(Thing t) { if (!allowForbidden && t.IsForbidden(getter)) { @@ -201,37 +193,29 @@ public static Thing BestFoodSourceOnMap(Pawn getter, Pawn eater, bool desperate, Building_NutrientPasteDispenser building_NutrientPasteDispenser = t as Building_NutrientPasteDispenser; if (building_NutrientPasteDispenser != null) { - if (!allowDispenserFull || ThingDefOf.MealNutrientPaste.ingestible.preferability < minPref || ThingDefOf.MealNutrientPaste.ingestible.preferability > maxPref || !getterCanManipulate || (t.Faction != getter.Faction && t.Faction != getter.HostFaction) || (!building_NutrientPasteDispenser.powerComp.PowerOn || (!allowDispenserEmpty && !building_NutrientPasteDispenser.HasEnoughFeedstockInHoppers())) || !FoodUtility.IsFoodSourceOnMapSociallyProper(t, getter, eater, allowSociallyImproper) || !t.InteractionCell.Standable(t.Map) || !getter.Map.reachability.CanReachNonLocal(getter.Position, new TargetInfo(t.InteractionCell, t.Map, false), PathEndMode.OnCell, TraverseParms.For(getter, Danger.Some, TraverseMode.ByPawn, false))) + if (allowDispenserFull && (int)ThingDefOf.MealNutrientPaste.ingestible.preferability >= (int)minPref && (int)ThingDefOf.MealNutrientPaste.ingestible.preferability <= (int)maxPref && getterCanManipulate && (t.Faction == getter.Faction || t.Faction == getter.HostFaction) && building_NutrientPasteDispenser.powerComp.PowerOn && (allowDispenserEmpty || building_NutrientPasteDispenser.HasEnoughFeedstockInHoppers()) && FoodUtility.IsFoodSourceOnMapSociallyProper(t, getter, eater, allowSociallyImproper) && t.InteractionCell.Standable(t.Map) && getter.Map.reachability.CanReachNonLocal(getter.Position, new TargetInfo(t.InteractionCell, t.Map, false), PathEndMode.OnCell, TraverseParms.For(getter, Danger.Some, TraverseMode.ByPawn, false))) { - return false; + goto IL_024e; } + return false; } - else + if ((int)t.def.ingestible.preferability < (int)minPref) { - if (t.def.ingestible.preferability < minPref) - { - return false; - } - if (t.def.ingestible.preferability > maxPref) - { - return false; - } - if (!t.IngestibleNow || !t.def.IsNutritionGivingIngestible || (!allowCorpse && t is Corpse) || (!allowDrug && t.def.IsDrug) || (!desperate && t.IsNotFresh()) || t.IsDessicated() || !eater.RaceProps.WillAutomaticallyEat(t) || !FoodUtility.IsFoodSourceOnMapSociallyProper(t, getter, eater, allowSociallyImproper) || !getter.AnimalAwareOf(t) || !getter.CanReserve(t, 1, -1, null, false)) - { - return false; - } + return false; } + if ((int)t.def.ingestible.preferability > (int)maxPref) + { + return false; + } + if (t.IngestibleNow && t.def.IsNutritionGivingIngestible && (allowCorpse || !(t is Corpse)) && (allowDrug || !t.def.IsDrug) && (desperate || !t.IsNotFresh()) && !t.IsDessicated() && eater.RaceProps.WillAutomaticallyEat(t) && FoodUtility.IsFoodSourceOnMapSociallyProper(t, getter, eater, allowSociallyImproper) && getter.AnimalAwareOf(t) && getter.CanReserve(t, 1, -1, null, false)) + { + goto IL_024e; + } + return false; + IL_024e: return true; }; - ThingRequest thingRequest; - if ((eater.RaceProps.foodType & (FoodTypeFlags.Plant | FoodTypeFlags.Tree)) != FoodTypeFlags.None && allowPlant) - { - thingRequest = ThingRequest.ForGroup(ThingRequestGroup.FoodSource); - } - else - { - thingRequest = ThingRequest.ForGroup(ThingRequestGroup.FoodSourceNotPlantOrTree); - } + ThingRequest thingRequest = (((int)eater.RaceProps.foodType & 192) == 0 || !allowPlant) ? ThingRequest.ForGroup(ThingRequestGroup.FoodSourceNotPlantOrTree) : ThingRequest.ForGroup(ThingRequestGroup.FoodSource); Thing thing; if (getter.RaceProps.Humanlike) { @@ -246,17 +230,32 @@ public static Thing BestFoodSourceOnMap(Pawn getter, Pawn eater, bool desperate, searchRegionsMax = 100; } FoodUtility.filtered.Clear(); - foreach (Thing current in GenRadial.RadialDistinctThingsAround(getter.Position, getter.Map, 2f, true)) + foreach (Thing item in GenRadial.RadialDistinctThingsAround(getter.Position, getter.Map, 2f, true)) { - Pawn pawn = current as Pawn; + Pawn pawn = item as Pawn; if (pawn != null && pawn != getter && pawn.RaceProps.Animal && pawn.CurJob != null && pawn.CurJob.def == JobDefOf.Ingest && pawn.CurJob.GetTarget(TargetIndex.A).HasThing) { FoodUtility.filtered.Add(pawn.CurJob.GetTarget(TargetIndex.A).Thing); } } bool flag = !allowForbidden && ForbidUtility.CaresAboutForbidden(getter, true) && getter.playerSettings != null && getter.playerSettings.EffectiveAreaRestrictionInPawnCurrentMap != null; - Predicate predicate = (Thing t) => foodValidator(t) && !FoodUtility.filtered.Contains(t) && t.def.ingestible.preferability > FoodPreferability.DesperateOnly && !t.IsNotFresh(); - Predicate validator = predicate; + Predicate validator; + Predicate predicate = validator = (Predicate)delegate(Thing t) + { + if (!foodValidator(t)) + { + return false; + } + if (FoodUtility.filtered.Contains(t)) + { + return false; + } + if ((int)t.def.ingestible.preferability > 2 && !t.IsNotFresh()) + { + return true; + } + return false; + }; bool ignoreEntirelyForbiddenRegions = flag; thing = GenClosest.ClosestThingReachable(getter.Position, getter.Map, thingRequest, PathEndMode.ClosestTouch, TraverseParms.For(getter, Danger.Deadly, TraverseMode.ByPawn, false), 9999f, validator, null, 0, searchRegionsMax, false, RegionType.Set_Passable, ignoreEntirelyForbiddenRegions); FoodUtility.filtered.Clear(); @@ -289,43 +288,46 @@ public static float FoodSourceOptimality(Pawn eater, Thing t, float dist, bool t float num = 300f; num -= dist; ThingDef thingDef = (!(t is Building_NutrientPasteDispenser)) ? t.def : ThingDefOf.MealNutrientPaste; - FoodPreferability preferability = thingDef.ingestible.preferability; - if (preferability != FoodPreferability.NeverForNutrition) + switch (thingDef.ingestible.preferability) { - if (preferability == FoodPreferability.DesperateOnly) - { - num -= 150f; - } - CompRottable compRottable = t.TryGetComp(); - if (compRottable != null) + case FoodPreferability.NeverForNutrition: + { + return -9999999f; + } + case FoodPreferability.DesperateOnly: + { + num = (float)(num - 150.0); + break; + } + } + CompRottable compRottable = t.TryGetComp(); + if (compRottable != null) + { + if (compRottable.Stage == RotStage.Dessicated) { - if (compRottable.Stage == RotStage.Dessicated) - { - return -9999999f; - } - if (!takingToInventory && compRottable.Stage == RotStage.Fresh && compRottable.TicksUntilRotAtCurrentTemp < 30000) - { - num += 12f; - } + return -9999999f; } - if (eater.needs != null && eater.needs.mood != null) + if (!takingToInventory && compRottable.Stage == RotStage.Fresh && compRottable.TicksUntilRotAtCurrentTemp < 30000) { - List list = FoodUtility.ThoughtsFromIngesting(eater, t); - for (int i = 0; i < list.Count; i++) - { - num += FoodUtility.FoodOptimalityEffectFromMoodCurve.Evaluate(list[i].stages[0].baseMoodEffect); - } + num = (float)(num + 12.0); } - if (thingDef.ingestible != null) + } + if (eater.needs != null && eater.needs.mood != null) + { + List list = FoodUtility.ThoughtsFromIngesting(eater, t); + for (int i = 0; i < list.Count; i++) { - num += thingDef.ingestible.optimalityOffset; + num += FoodUtility.FoodOptimalityEffectFromMoodCurve.Evaluate(list[i].stages[0].baseMoodEffect); } - return num; } - return -9999999f; + if (thingDef.ingestible != null) + { + num += thingDef.ingestible.optimalityOffset; + } + return num; } - private static Thing SpawnedFoodSearchInnerScan(Pawn eater, IntVec3 root, List searchSet, PathEndMode peMode, TraverseParms traverseParams, float maxDistance = 9999f, Predicate validator = null) + private static Thing SpawnedFoodSearchInnerScan(Pawn eater, IntVec3 root, List searchSet, PathEndMode peMode, TraverseParms traverseParams, float maxDistance = 9999, Predicate validator = null) { if (searchSet == null) { @@ -335,29 +337,21 @@ private static Thing SpawnedFoodSearchInnerScan(Pawn eater, IntVec3 root, List maxDistance)) { - float num5 = FoodUtility.FoodSourceOptimality(eater, thing, num4, false); - if (num5 >= num3) + num3 = FoodUtility.FoodSourceOptimality(eater, thing, num5, false); + if (!(num3 < num4) && pawn.Map.reachability.CanReach(root, thing, peMode, traverseParams) && thing.Spawned && ((object)validator == null || validator(thing))) { - if (pawn.Map.reachability.CanReach(root, thing, peMode, traverseParams)) - { - if (thing.Spawned) - { - if (validator == null || validator(thing)) - { - result = thing; - num3 = num5; - num++; - } - } - } + result = thing; + num4 = num3; + num++; } } } @@ -368,18 +362,13 @@ public static void DebugFoodSearchFromMouse_Update() { IntVec3 root = UI.MouseCell(); Pawn pawn = Find.Selector.SingleSelectedThing as Pawn; - if (pawn == null) - { - return; - } - if (pawn.Map != Find.VisibleMap) + if (pawn != null && pawn.Map == Find.VisibleMap) { - return; - } - Thing thing = FoodUtility.SpawnedFoodSearchInnerScan(pawn, root, Find.VisibleMap.listerThings.ThingsInGroup(ThingRequestGroup.FoodSourceNotPlantOrTree), PathEndMode.ClosestTouch, TraverseParms.For(TraverseMode.PassDoors, Danger.Deadly, false), 9999f, null); - if (thing != null) - { - GenDraw.DrawLineBetween(root.ToVector3Shifted(), thing.Position.ToVector3Shifted()); + Thing thing = FoodUtility.SpawnedFoodSearchInnerScan(pawn, root, Find.VisibleMap.listerThings.ThingsInGroup(ThingRequestGroup.FoodSourceNotPlantOrTree), PathEndMode.ClosestTouch, TraverseParms.For(TraverseMode.PassDoors, Danger.Deadly, false), 9999f, null); + if (thing != null) + { + GenDraw.DrawLineBetween(root.ToVector3Shifted(), thing.Position.ToVector3Shifted()); + } } } @@ -387,39 +376,35 @@ public static void DebugFoodSearchFromMouse_OnGUI() { IntVec3 a = UI.MouseCell(); Pawn pawn = Find.Selector.SingleSelectedThing as Pawn; - if (pawn == null) - { - return; - } - if (pawn.Map != Find.VisibleMap) - { - return; - } - Text.Anchor = TextAnchor.MiddleCenter; - Text.Font = GameFont.Tiny; - foreach (Thing current in Find.VisibleMap.listerThings.ThingsInGroup(ThingRequestGroup.FoodSourceNotPlantOrTree)) + if (pawn != null && pawn.Map == Find.VisibleMap) { - float num = FoodUtility.FoodSourceOptimality(pawn, current, (a - current.Position).LengthHorizontal, false); - Vector2 vector = current.DrawPos.MapToUIPosition(); - Rect rect = new Rect(vector.x - 100f, vector.y - 100f, 200f, 200f); - string text = num.ToString("F0"); - List list = FoodUtility.ThoughtsFromIngesting(pawn, current); - for (int i = 0; i < list.Count; i++) + Text.Anchor = TextAnchor.MiddleCenter; + Text.Font = GameFont.Tiny; + List.Enumerator enumerator = Find.VisibleMap.listerThings.ThingsInGroup(ThingRequestGroup.FoodSourceNotPlantOrTree).GetEnumerator(); + try { - string text2 = text; - text = string.Concat(new string[] + while (enumerator.MoveNext()) { - text2, - "\n", - list[i].defName, - "(", - FoodUtility.FoodOptimalityEffectFromMoodCurve.Evaluate(list[i].stages[0].baseMoodEffect).ToString("F0"), - ")" - }); + Thing current = enumerator.Current; + float num = FoodUtility.FoodSourceOptimality(pawn, current, (a - current.Position).LengthHorizontal, false); + Vector2 vector = current.DrawPos.MapToUIPosition(); + Rect rect = new Rect((float)(vector.x - 100.0), (float)(vector.y - 100.0), 200f, 200f); + string text = num.ToString("F0"); + List list = FoodUtility.ThoughtsFromIngesting(pawn, current); + for (int i = 0; i < list.Count; i++) + { + string text2 = text; + text = text2 + "\n" + list[i].defName + "(" + FoodUtility.FoodOptimalityEffectFromMoodCurve.Evaluate(list[i].stages[0].baseMoodEffect).ToString("F0") + ")"; + } + Widgets.Label(rect, text); + } } - Widgets.Label(rect, text); + finally + { + ((IDisposable)(object)enumerator).Dispose(); + } + Text.Anchor = TextAnchor.UpperLeft; } - Text.Anchor = TextAnchor.UpperLeft; } private static Pawn BestPawnToHuntForPredator(Pawn predator) @@ -430,7 +415,7 @@ private static Pawn BestPawnToHuntForPredator(Pawn predator) } bool flag = false; float summaryHealthPercent = predator.health.summaryHealth.SummaryHealthPercent; - if (summaryHealthPercent < 0.25f) + if (summaryHealthPercent < 0.25) { flag = true; } @@ -441,31 +426,13 @@ private static Pawn BestPawnToHuntForPredator(Pawn predator) for (int i = 0; i < allPawnsSpawned.Count; i++) { Pawn pawn2 = allPawnsSpawned[i]; - if (predator.GetRoom(RegionType.Set_Passable) == pawn2.GetRoom(RegionType.Set_Passable)) + if (predator.GetRoom(RegionType.Set_Passable) == pawn2.GetRoom(RegionType.Set_Passable) && predator != pawn2 && (!flag || pawn2.Downed) && FoodUtility.IsAcceptablePreyFor(predator, pawn2) && predator.CanReach((Thing)pawn2, PathEndMode.ClosestTouch, Danger.Deadly, false, TraverseMode.ByPawn) && !pawn2.IsForbidden(predator) && (!tutorialMode || pawn2.Faction != Faction.OfPlayer)) { - if (predator != pawn2) + float preyScoreFor = FoodUtility.GetPreyScoreFor(predator, pawn2); + if (preyScoreFor > num || pawn == null) { - if (!flag || pawn2.Downed) - { - if (FoodUtility.IsAcceptablePreyFor(predator, pawn2)) - { - if (predator.CanReach(pawn2, PathEndMode.ClosestTouch, Danger.Deadly, false, TraverseMode.ByPawn)) - { - if (!pawn2.IsForbidden(predator)) - { - if (!tutorialMode || pawn2.Faction != Faction.OfPlayer) - { - float preyScoreFor = FoodUtility.GetPreyScoreFor(predator, pawn2); - if (preyScoreFor > num || pawn == null) - { - num = preyScoreFor; - pawn = pawn2; - } - } - } - } - } - } + num = preyScoreFor; + pawn = pawn2; } } } @@ -488,18 +455,30 @@ public static bool IsAcceptablePreyFor(Pawn predator, Pawn prey) } if (!prey.Downed) { - if (prey.kindDef.combatPower > 2f * predator.kindDef.combatPower) + if (prey.kindDef.combatPower > 2.0 * predator.kindDef.combatPower) { return false; } float num = prey.kindDef.combatPower * prey.health.summaryHealth.SummaryHealthPercent * prey.ageTracker.CurLifeStage.bodySizeFactor; float num2 = predator.kindDef.combatPower * predator.health.summaryHealth.SummaryHealthPercent * predator.ageTracker.CurLifeStage.bodySizeFactor; - if (num > 0.85f * num2) + if (num > 0.85000002384185791 * num2) { return false; } } - return (predator.Faction == null || prey.Faction == null || predator.HostileTo(prey)) && (predator.Faction != Faction.OfPlayer || prey.Faction != Faction.OfPlayer) && (!predator.RaceProps.herdAnimal || predator.def != prey.def); + if (predator.Faction != null && prey.Faction != null && !predator.HostileTo(prey)) + { + return false; + } + if (predator.Faction == Faction.OfPlayer && prey.Faction == Faction.OfPlayer) + { + return false; + } + if (predator.RaceProps.herdAnimal && predator.def == prey.def) + { + return false; + } + return true; } public static float GetPreyScoreFor(Pawn predator, Pawn prey) @@ -512,10 +491,10 @@ public static float GetPreyScoreFor(Pawn predator, Pawn prey) { num2 = Mathf.Min(num2, 0.2f); } - float num3 = -lengthHorizontal - 56f * num2 * num2 * num * bodySizeFactor; + float num3 = (float)(0.0 - lengthHorizontal - 56.0 * num2 * num2 * num * bodySizeFactor); if (prey.RaceProps.Humanlike) { - num3 -= 35f; + num3 = (float)(num3 - 35.0); } return num3; } @@ -523,13 +502,9 @@ public static float GetPreyScoreFor(Pawn predator, Pawn prey) public static void DebugDrawPredatorFoodSource() { Pawn pawn = Find.Selector.SingleSelectedThing as Pawn; - if (pawn == null) - { - return; - } - Thing thing; - ThingDef thingDef; - if (FoodUtility.TryFindBestFoodSourceFor(pawn, pawn, true, out thing, out thingDef, false, false, false, true, false)) + Thing thing = default(Thing); + ThingDef thingDef = default(ThingDef); + if (pawn != null && FoodUtility.TryFindBestFoodSourceFor(pawn, pawn, true, out thing, out thingDef, false, false, false, true, false)) { GenDraw.DrawLineBetween(pawn.Position.ToVector3Shifted(), thing.Position.ToVector3Shifted()); if (!(thing is Pawn)) @@ -546,56 +521,60 @@ public static void DebugDrawPredatorFoodSource() public static List ThoughtsFromIngesting(Pawn ingester, Thing t) { FoodUtility.ingestThoughts.Clear(); - if (ingester.needs == null || ingester.needs.mood == null) - { - return FoodUtility.ingestThoughts; - } - ThingDef thingDef = t.def; - if (thingDef == ThingDefOf.NutrientPasteDispenser) - { - thingDef = ThingDefOf.MealNutrientPaste; - } - if (!ingester.story.traits.HasTrait(TraitDefOf.Ascetic) && thingDef.ingestible.tasteThought != null) + if (ingester.needs != null && ingester.needs.mood != null) { - FoodUtility.ingestThoughts.Add(thingDef.ingestible.tasteThought); - } - CompIngredients compIngredients = t.TryGetComp(); - if (FoodUtility.IsHumanlikeMeat(thingDef) && ingester.RaceProps.Humanlike) - { - FoodUtility.ingestThoughts.Add((!ingester.story.traits.HasTrait(TraitDefOf.Cannibal)) ? ThoughtDefOf.AteHumanlikeMeatDirect : ThoughtDefOf.AteHumanlikeMeatDirectCannibal); - } - else if (compIngredients != null) - { - for (int i = 0; i < compIngredients.ingredients.Count; i++) + ThingDef thingDef = t.def; + if (thingDef == ThingDefOf.NutrientPasteDispenser) + { + thingDef = ThingDefOf.MealNutrientPaste; + } + if (!ingester.story.traits.HasTrait(TraitDefOf.Ascetic) && thingDef.ingestible.tasteThought != null) + { + FoodUtility.ingestThoughts.Add(thingDef.ingestible.tasteThought); + } + CompIngredients compIngredients = t.TryGetComp(); + if (FoodUtility.IsHumanlikeMeat(thingDef) && ingester.RaceProps.Humanlike) { - ThingDef thingDef2 = compIngredients.ingredients[i]; - if (thingDef2.ingestible != null) + FoodUtility.ingestThoughts.Add((!ingester.story.traits.HasTrait(TraitDefOf.Cannibal)) ? ThoughtDefOf.AteHumanlikeMeatDirect : ThoughtDefOf.AteHumanlikeMeatDirectCannibal); + } + else if (compIngredients != null) + { + for (int i = 0; i < compIngredients.ingredients.Count; i++) { - if (ingester.RaceProps.Humanlike && FoodUtility.IsHumanlikeMeat(thingDef2)) - { - FoodUtility.ingestThoughts.Add((!ingester.story.traits.HasTrait(TraitDefOf.Cannibal)) ? ThoughtDefOf.AteHumanlikeMeatAsIngredient : ThoughtDefOf.AteHumanlikeMeatAsIngredientCannibal); - } - else if (thingDef2.ingestible.specialThoughtAsIngredient != null) + ThingDef thingDef2 = compIngredients.ingredients[i]; + if (thingDef2.ingestible != null) { - FoodUtility.ingestThoughts.Add(thingDef2.ingestible.specialThoughtAsIngredient); + if (ingester.RaceProps.Humanlike && FoodUtility.IsHumanlikeMeat(thingDef2)) + { + FoodUtility.ingestThoughts.Add((!ingester.story.traits.HasTrait(TraitDefOf.Cannibal)) ? ThoughtDefOf.AteHumanlikeMeatAsIngredient : ThoughtDefOf.AteHumanlikeMeatAsIngredientCannibal); + } + else if (thingDef2.ingestible.specialThoughtAsIngredient != null) + { + FoodUtility.ingestThoughts.Add(thingDef2.ingestible.specialThoughtAsIngredient); + } } } } - } - else if (thingDef.ingestible.specialThoughtDirect != null) - { - FoodUtility.ingestThoughts.Add(thingDef.ingestible.specialThoughtDirect); - } - if (t.IsNotFresh()) - { - FoodUtility.ingestThoughts.Add(ThoughtDefOf.AteRottenFood); + else if (thingDef.ingestible.specialThoughtDirect != null) + { + FoodUtility.ingestThoughts.Add(thingDef.ingestible.specialThoughtDirect); + } + if (t.IsNotFresh()) + { + FoodUtility.ingestThoughts.Add(ThoughtDefOf.AteRottenFood); + } + return FoodUtility.ingestThoughts; } return FoodUtility.ingestThoughts; } public static bool IsHumanlikeMeat(ThingDef def) { - return def.ingestible.sourceDef != null && def.ingestible.sourceDef.race != null && def.ingestible.sourceDef.race.Humanlike; + if (def.ingestible.sourceDef != null && def.ingestible.sourceDef.race != null && def.ingestible.sourceDef.race.Humanlike) + { + return true; + } + return false; } public static bool IsHumanlikeMeatOrHumanlikeCorpse(Thing thing) @@ -605,7 +584,11 @@ public static bool IsHumanlikeMeatOrHumanlikeCorpse(Thing thing) return true; } Corpse corpse = thing as Corpse; - return corpse != null && corpse.InnerPawn.RaceProps.Humanlike; + if (corpse != null && corpse.InnerPawn.RaceProps.Humanlike) + { + return true; + } + return false; } public static int WillIngestStackCountOf(Pawn ingester, ThingDef def) @@ -624,12 +607,12 @@ public static float GetBodyPartNutrition(Pawn pawn, BodyPartRecord part) { return 0f; } - return 5.2f * pawn.BodySize * pawn.health.hediffSet.GetCoverageOfNotMissingNaturalParts(part); + return (float)(5.1999998092651367 * pawn.BodySize * pawn.health.hediffSet.GetCoverageOfNotMissingNaturalParts(part)); } public static int StackCountForNutrition(ThingDef def, float nutrition) { - if (nutrition <= 0.0001f) + if (nutrition <= 9.9999997473787516E-05) { return 0; } @@ -643,14 +626,10 @@ public static bool ShouldBeFedBySomeone(Pawn pawn) public static void AddFoodPoisoningHediff(Pawn pawn, Thing ingestible) { - pawn.health.AddHediff(HediffMaker.MakeHediff(HediffDefOf.FoodPoisoning, pawn, null), null, null); + pawn.health.AddHediff(HediffMaker.MakeHediff(HediffDefOf.FoodPoisoning, pawn, null), null, default(DamageInfo?)); if (PawnUtility.ShouldSendNotificationAbout(pawn)) { - Messages.Message("MessageFoodPoisoning".Translate(new object[] - { - pawn.LabelShort, - ingestible.LabelCapNoCount - }).CapitalizeFirst(), pawn, MessageSound.Negative); + Messages.Message("MessageFoodPoisoning".Translate(pawn.LabelShort, ingestible.LabelCapNoCount).CapitalizeFirst(), (Thing)pawn, MessageSound.Negative); } } } diff --git a/Assembly-CSharp/RimWorld/ForbidUtility.cs b/Assembly-CSharp/RimWorld/ForbidUtility.cs index bdee40ed5..0462b8da5 100644 --- a/Assembly-CSharp/RimWorld/ForbidUtility.cs +++ b/Assembly-CSharp/RimWorld/ForbidUtility.cs @@ -1,4 +1,3 @@ -using System; using Verse; using Verse.AI.Group; @@ -14,27 +13,33 @@ public static void SetForbidden(this Thing t, bool value, bool warnOnFail = true { Log.Error("Tried to SetForbidden on null Thing."); } - return; } - ThingWithComps thingWithComps = t as ThingWithComps; - if (thingWithComps == null) + else { - if (warnOnFail) + ThingWithComps thingWithComps = t as ThingWithComps; + if (thingWithComps == null) { - Log.Error("Tried to SetForbidden on non-ThingWithComps Thing " + t); + if (warnOnFail) + { + Log.Error("Tried to SetForbidden on non-ThingWithComps Thing " + t); + } } - return; - } - CompForbiddable comp = thingWithComps.GetComp(); - if (comp == null) - { - if (warnOnFail) + else { - Log.Error("Tried to SetForbidden on non-Forbiddable Thing " + t); + CompForbiddable comp = thingWithComps.GetComp(); + if (comp == null) + { + if (warnOnFail) + { + Log.Error("Tried to SetForbidden on non-Forbiddable Thing " + t); + } + } + else + { + comp.Forbidden = value; + } } - return; } - comp.Forbidden = value; } public static void SetForbiddenIfOutsideHomeArea(this Thing t) @@ -43,7 +48,7 @@ public static void SetForbiddenIfOutsideHomeArea(this Thing t) { Log.Error("SetForbiddenIfOutsideHomeArea unspawned thing " + t); } - if (t.Position.InBounds(t.Map) && !t.Map.areaManager.Home[t.Position]) + if (t.Position.InBounds(t.Map) && !((Area)t.Map.areaManager.Home)[t.Position]) { t.SetForbidden(true, false); } @@ -51,7 +56,19 @@ public static void SetForbiddenIfOutsideHomeArea(this Thing t) public static bool CaresAboutForbidden(Pawn pawn, bool cellTarget) { - return pawn.HostFaction == null && !pawn.InMentalState && (!cellTarget || !ThinkNode_ConditionalShouldFollowMaster.ShouldFollowMaster(pawn)); + if (pawn.HostFaction != null) + { + return false; + } + if (pawn.InMentalState) + { + return false; + } + if (cellTarget && ThinkNode_ConditionalShouldFollowMaster.ShouldFollowMaster(pawn)) + { + return false; + } + return true; } public static bool InAllowedArea(this IntVec3 c, Pawn forPawn) @@ -82,17 +99,45 @@ public static bool IsForbidden(this Thing t, Pawn pawn) return true; } Lord lord = pawn.GetLord(); - return lord != null && lord.extraForbiddenThings.Contains(t); + if (lord != null && lord.extraForbiddenThings.Contains(t)) + { + return true; + } + return false; } public static bool IsForbiddenToPass(this Thing t, Pawn pawn) { - return ForbidUtility.CaresAboutForbidden(pawn, false) && ((t.Spawned && t.Position.IsForbidden(pawn) && !(t is Building_Door)) || t.IsForbidden(pawn.Faction)); + if (!ForbidUtility.CaresAboutForbidden(pawn, false)) + { + return false; + } + if (t.Spawned && t.Position.IsForbidden(pawn) && !(t is Building_Door)) + { + return true; + } + if (t.IsForbidden(pawn.Faction)) + { + return true; + } + return false; } public static bool IsForbidden(this IntVec3 c, Pawn pawn) { - return ForbidUtility.CaresAboutForbidden(pawn, true) && (!c.InAllowedArea(pawn) || (pawn.mindState.maxDistToSquadFlag > 0f && !c.InHorDistOf(pawn.DutyLocation(), pawn.mindState.maxDistToSquadFlag))); + if (!ForbidUtility.CaresAboutForbidden(pawn, true)) + { + return false; + } + if (!c.InAllowedArea(pawn)) + { + return true; + } + if (pawn.mindState.maxDistToSquadFlag > 0.0 && !c.InHorDistOf(pawn.DutyLocation(), pawn.mindState.maxDistToSquadFlag)) + { + return true; + } + return false; } public static bool IsForbiddenEntirely(this Region r, Pawn pawn) @@ -128,7 +173,11 @@ public static bool IsForbidden(this Thing t, Faction faction) return false; } CompForbiddable comp = thingWithComps.GetComp(); - return comp != null && comp.Forbidden; + if (comp == null) + { + return false; + } + return comp.Forbidden; } } } diff --git a/Assembly-CSharp/RimWorld/Frame.cs b/Assembly-CSharp/RimWorld/Frame.cs index c5816bcd5..6a4c4d534 100644 --- a/Assembly-CSharp/RimWorld/Frame.cs +++ b/Assembly-CSharp/RimWorld/Frame.cs @@ -1,6 +1,5 @@ using System; using System.Collections.Generic; -using System.Diagnostics; using System.Linq; using System.Text; using UnityEngine; @@ -37,7 +36,7 @@ public float WorkToMake { get { - return this.def.entityDefToBuild.GetStatValueAbstract(StatDefOf.WorkToBuild, base.Stuff); + return base.def.entityDefToBuild.GetStatValueAbstract(StatDefOf.WorkToBuild, base.Stuff); } } @@ -61,7 +60,7 @@ public override string Label { get { - string text = this.def.entityDefToBuild.label + "FrameLabelExtra".Translate(); + string text = base.def.entityDefToBuild.label + "FrameLabelExtra".Translate(); if (base.Stuff != null) { return base.Stuff.label + " " + text; @@ -74,9 +73,9 @@ public override Color DrawColor { get { - if (!this.def.MadeFromStuff) + if (!base.def.MadeFromStuff) { - List costList = this.def.entityDefToBuild.costList; + List costList = base.def.entityDefToBuild.costList; if (costList != null) { for (int i = 0; i < costList.Count; i++) @@ -102,9 +101,9 @@ public EffecterDef ConstructionEffect { return base.Stuff.stuffProps.constructEffect; } - if (this.def.entityDefToBuild.constructEffect != null) + if (base.def.entityDefToBuild.constructEffect != null) { - return this.def.entityDefToBuild.constructEffect; + return base.def.entityDefToBuild.constructEffect; } return EffecterDefOf.ConstructMetal; } @@ -114,7 +113,7 @@ private Material CornerMat { get { - if (this.cachedCornerMat == null) + if ((UnityEngine.Object)this.cachedCornerMat == (UnityEngine.Object)null) { this.cachedCornerMat = MaterialPool.MatFrom(Frame.CornerTex, ShaderDatabase.Cutout, this.DrawColor); } @@ -126,7 +125,7 @@ private Material TileMat { get { - if (this.cachedTileMat == null) + if ((UnityEngine.Object)this.cachedTileMat == (UnityEngine.Object)null) { this.cachedTileMat = MaterialPool.MatFrom(Frame.TileTex, ShaderDatabase.Cutout, this.DrawColor); } @@ -153,7 +152,7 @@ public override void ExposeData() { base.ExposeData(); Scribe_Values.Look(ref this.workDone, "workDone", 0f, false); - Scribe_Deep.Look(ref this.resourceContainer, "resourceContainer", new object[] + Scribe_Deep.Look(ref this.resourceContainer, "resourceContainer", new object[1] { this }); @@ -167,7 +166,7 @@ public ThingDef UIStuff() public List MaterialsNeeded() { this.cachedMaterialsNeeded.Clear(); - List list = this.def.entityDefToBuild.CostListAdjusted(base.Stuff, true); + List list = base.def.entityDefToBuild.CostListAdjusted(base.Stuff, true); for (int i = 0; i < list.Count; i++) { ThingCountClass thingCountClass = list[i]; @@ -186,11 +185,11 @@ public void CompleteConstruction(Pawn worker) this.resourceContainer.Clear(); Map map = base.Map; this.Destroy(DestroyMode.Vanish); - if (this.GetStatValue(StatDefOf.WorkToBuild, true) > 150f && this.def.entityDefToBuild is ThingDef && ((ThingDef)this.def.entityDefToBuild).category == ThingCategory.Building) + if (this.GetStatValue(StatDefOf.WorkToBuild, true) > 150.0 && base.def.entityDefToBuild is ThingDef && ((ThingDef)base.def.entityDefToBuild).category == ThingCategory.Building) { SoundDefOf.BuildingComplete.PlayOneShot(new TargetInfo(base.Position, map, false)); } - ThingDef thingDef = this.def.entityDefToBuild as ThingDef; + ThingDef thingDef = base.def.entityDefToBuild as ThingDef; Thing thing = null; if (thingDef != null) { @@ -216,23 +215,32 @@ public void CompleteConstruction(Pawn worker) } else { - map.terrainGrid.SetTerrain(base.Position, (TerrainDef)this.def.entityDefToBuild); + map.terrainGrid.SetTerrain(base.Position, (TerrainDef)base.def.entityDefToBuild); } if (thingDef != null && (thingDef.passability == Traversability.Impassable || thingDef.Fillage == FillCategory.Full) && (thing == null || !(thing is Building_Door))) { - foreach (IntVec3 current in GenAdj.CellsOccupiedBy(base.Position, base.Rotation, this.def.Size)) + foreach (IntVec3 item in GenAdj.CellsOccupiedBy(base.Position, base.Rotation, base.def.Size)) { - foreach (Thing current2 in map.thingGrid.ThingsAt(current).ToList()) + List.Enumerator enumerator2 = map.thingGrid.ThingsAt(item).ToList().GetEnumerator(); + try { - if (current2 is Plant) + while (enumerator2.MoveNext()) { - current2.Destroy(DestroyMode.KillFinalize); - } - else if (current2.def.category == ThingCategory.Item || current2 is Pawn) - { - GenPlace.TryMoveThing(current2, current2.Position, current2.Map); + Thing current2 = enumerator2.Current; + if (current2 is Plant) + { + current2.Destroy(DestroyMode.KillFinalize); + } + else if (current2.def.category == ThingCategory.Item || current2 is Pawn) + { + GenPlace.TryMoveThing(current2, current2.Position, current2.Map); + } } } + finally + { + ((IDisposable)(object)enumerator2).Dispose(); + } } } worker.records.Increment(RecordDefOf.ThingsConstructed); @@ -243,9 +251,9 @@ public void FailConstruction(Pawn worker) Map map = base.Map; this.Destroy(DestroyMode.FailConstruction); Blueprint_Build blueprint_Build = null; - if (this.def.entityDefToBuild.blueprintDef != null) + if (base.def.entityDefToBuild.blueprintDef != null) { - blueprint_Build = (Blueprint_Build)ThingMaker.MakeThing(this.def.entityDefToBuild.blueprintDef, null); + blueprint_Build = (Blueprint_Build)ThingMaker.MakeThing(base.def.entityDefToBuild.blueprintDef, null); blueprint_Build.stuffToUse = base.Stuff; blueprint_Build.SetFactionDirect(base.Faction); GenSpawn.Spawn(blueprint_Build, base.Position, map, base.Rotation, false); @@ -256,19 +264,15 @@ public void FailConstruction(Pawn worker) lord.Notify_ConstructionFailed(worker, this, blueprint_Build); } MoteMaker.ThrowText(this.DrawPos, map, "TextMote_ConstructionFail".Translate(), 6f); - if (base.Faction == Faction.OfPlayer && this.WorkToMake > 1400f) + if (base.Faction == Faction.OfPlayer && this.WorkToMake > 1400.0) { - Messages.Message("MessageConstructionFailed".Translate(new object[] - { - this.Label, - worker.LabelShort - }), new TargetInfo(base.Position, map, false), MessageSound.Negative); + Messages.Message("MessageConstructionFailed".Translate(this.Label, worker.LabelShort), new TargetInfo(base.Position, map, false), MessageSound.Negative); } } public override void Draw() { - Vector2 vector = new Vector2((float)this.def.size.x, (float)this.def.size.z); + Vector2 vector = new Vector2((float)base.def.size.x, (float)base.def.size.z); vector.x *= 1.15f; vector.y *= 1.15f; Vector3 s = new Vector3(vector.x, 1f, vector.y); @@ -276,48 +280,70 @@ public override void Draw() matrix.SetTRS(this.DrawPos, base.Rotation.AsQuat, s); Graphics.DrawMesh(MeshPool.plane10, matrix, Frame.UnderfieldMat, 0); int num = 4; - for (int i = 0; i < num; i++) + for (int num2 = 0; num2 < num; num2++) { - float num2 = (float)Mathf.Min(base.RotatedSize.x, base.RotatedSize.z); - float num3 = num2 * 0.38f; + IntVec2 rotatedSize = base.RotatedSize; + int x = rotatedSize.x; + IntVec2 rotatedSize2 = base.RotatedSize; + float num3 = (float)Mathf.Min(x, rotatedSize2.z); + float num4 = (float)(num3 * 0.37999999523162842); IntVec3 intVec = default(IntVec3); - if (i == 0) + switch (num2) + { + case 0: { intVec = new IntVec3(-1, 0, -1); + break; } - else if (i == 1) + case 1: { intVec = new IntVec3(-1, 0, 1); + break; } - else if (i == 2) + case 2: { intVec = new IntVec3(1, 0, 1); + break; } - else if (i == 3) + case 3: { intVec = new IntVec3(1, 0, -1); + break; + } } Vector3 b = default(Vector3); - b.x = (float)intVec.x * ((float)base.RotatedSize.x / 2f - num3 / 2f); - b.z = (float)intVec.z * ((float)base.RotatedSize.z / 2f - num3 / 2f); - Vector3 s2 = new Vector3(num3, 1f, num3); + float num5 = (float)intVec.x; + IntVec2 rotatedSize3 = base.RotatedSize; + b.x = (float)(num5 * ((float)rotatedSize3.x / 2.0 - num4 / 2.0)); + float num6 = (float)intVec.z; + IntVec2 rotatedSize4 = base.RotatedSize; + b.z = (float)(num6 * ((float)rotatedSize4.z / 2.0 - num4 / 2.0)); + Vector3 s2 = new Vector3(num4, 1f, num4); Matrix4x4 matrix2 = default(Matrix4x4); - Vector3 arg_1EB_1 = this.DrawPos + Vector3.up * 0.03f + b; - Rot4 rot = new Rot4(i); - matrix2.SetTRS(arg_1EB_1, rot.AsQuat, s2); + matrix2.SetTRS(this.DrawPos + Vector3.up * 0.03f + b, new Rot4(num2).AsQuat, s2); Graphics.DrawMesh(MeshPool.plane10, matrix2, this.CornerMat, 0); } - float num4 = this.PercentComplete / 1f; - int num5 = Mathf.CeilToInt(num4 * (float)base.RotatedSize.x * (float)base.RotatedSize.z * 4f); + float num7 = (float)(this.PercentComplete / 1.0); + float num8 = num7; + IntVec2 rotatedSize5 = base.RotatedSize; + float num9 = num8 * (float)rotatedSize5.x; + IntVec2 rotatedSize6 = base.RotatedSize; + int num10 = Mathf.CeilToInt((float)(num9 * (float)rotatedSize6.z * 4.0)); IntVec2 intVec2 = base.RotatedSize * 2; - for (int j = 0; j < num5; j++) + for (int num11 = 0; num11 < num10; num11++) { - IntVec2 intVec3 = default(IntVec2); - intVec3.z = j / intVec2.x; - intVec3.x = j - intVec3.z * intVec2.x; - Vector3 a = new Vector3((float)intVec3.x * 0.5f, 0f, (float)intVec3.z * 0.5f) + this.DrawPos; - a.x -= (float)base.RotatedSize.x * 0.5f - 0.25f; - a.z -= (float)base.RotatedSize.z * 0.5f - 0.25f; + IntVec2 intVec3 = new IntVec2 + { + z = num11 / intVec2.x + }; + intVec3.x = num11 - intVec3.z * intVec2.x; + Vector3 a = new Vector3((float)((float)intVec3.x * 0.5), 0f, (float)((float)intVec3.z * 0.5)) + this.DrawPos; + float x2 = a.x; + IntVec2 rotatedSize7 = base.RotatedSize; + a.x = (float)(x2 - ((float)rotatedSize7.x * 0.5 - 0.25)); + float z = a.z; + IntVec2 rotatedSize8 = base.RotatedSize; + a.z = (float)(z - ((float)rotatedSize8.z * 0.5 - 0.25)); Vector3 s3 = new Vector3(0.5f, 1f, 0.5f); Matrix4x4 matrix3 = default(Matrix4x4); matrix3.SetTRS(a + Vector3.up * 0.02f, Quaternion.identity, s3); @@ -326,14 +352,17 @@ public override void Draw() base.Comps_PostDraw(); } - [DebuggerHidden] public override IEnumerable GetGizmos() { - Frame.c__Iterator145 c__Iterator = new Frame.c__Iterator145(); - c__Iterator.<>f__this = this; - Frame.c__Iterator145 expr_0E = c__Iterator; - expr_0E.$PC = -2; - return expr_0E; + foreach (Gizmo gizmo in base.GetGizmos()) + { + yield return gizmo; + } + Command buildCopy = BuildCopyCommandUtility.BuildCopyCommand(base.def.entityDefToBuild, base.Stuff); + if (buildCopy != null) + { + yield return (Gizmo)buildCopy; + } } public override string GetInspectString() @@ -341,25 +370,18 @@ public override string GetInspectString() StringBuilder stringBuilder = new StringBuilder(); stringBuilder.Append(base.GetInspectString()); stringBuilder.AppendLine("ContainedResources".Translate() + ":"); - List list = this.def.entityDefToBuild.CostListAdjusted(base.Stuff, true); + List list = base.def.entityDefToBuild.CostListAdjusted(base.Stuff, true); for (int i = 0; i < list.Count; i++) { ThingCountClass need = list[i]; int num = need.count; - foreach (ThingCountClass current in from needed in this.MaterialsNeeded() + foreach (ThingCountClass item in from needed in this.MaterialsNeeded() where needed.thingDef == need.thingDef select needed) { - num -= current.count; + num -= item.count; } - stringBuilder.AppendLine(string.Concat(new object[] - { - need.thingDef.LabelCap, - ": ", - num, - " / ", - need.count - })); + stringBuilder.AppendLine(need.thingDef.LabelCap + ": " + num + " / " + need.count); } stringBuilder.Append("WorkLeft".Translate() + ": " + this.WorkLeft.ToStringWorkAmount()); return stringBuilder.ToString(); @@ -369,5 +391,11 @@ virtual IThingHolder get_ParentHolder() { return base.ParentHolder; } + + IThingHolder IThingHolder.get_ParentHolder() + { + //ILSpy generated this explicit interface implementation from .override directive in get_ParentHolder + return this.get_ParentHolder(); + } } } diff --git a/Assembly-CSharp/RimWorld/FuelingPortUtility.cs b/Assembly-CSharp/RimWorld/FuelingPortUtility.cs index eb66764de..7e5cd5544 100644 --- a/Assembly-CSharp/RimWorld/FuelingPortUtility.cs +++ b/Assembly-CSharp/RimWorld/FuelingPortUtility.cs @@ -1,4 +1,3 @@ -using System; using System.Collections.Generic; using Verse; diff --git a/Assembly-CSharp/RimWorld/GameCondition.cs b/Assembly-CSharp/RimWorld/GameCondition.cs index 0090f437a..5e101387e 100644 --- a/Assembly-CSharp/RimWorld/GameCondition.cs +++ b/Assembly-CSharp/RimWorld/GameCondition.cs @@ -1,4 +1,3 @@ -using System; using System.Collections.Generic; using UnityEngine; using Verse; @@ -82,51 +81,20 @@ public virtual string TooltipString { get { - string text = this.def.LabelCap; + string labelCap = this.def.LabelCap; if (this.Permanent) { - text = text + "\n" + "Permanent".Translate().CapitalizeFirst(); + labelCap = labelCap + "\n" + "Permanent".Translate().CapitalizeFirst(); } else { - Vector2 location; - if (this.Map != null) - { - location = Find.WorldGrid.LongLatOf(this.Map.Tile); - } - else if (Find.VisibleMap != null) - { - location = Find.WorldGrid.LongLatOf(Find.VisibleMap.Tile); - } - else if (Find.AnyPlayerHomeMap != null) - { - location = Find.WorldGrid.LongLatOf(Find.AnyPlayerHomeMap.Tile); - } - else - { - location = Vector2.zero; - } - string text2 = text; - text = string.Concat(new string[] - { - text2, - "\n", - "Started".Translate(), - ": ", - GenDate.DateFullStringAt((long)GenDate.TickGameToAbs(this.startTick), location) - }); - text2 = text; - text = string.Concat(new string[] - { - text2, - "\n", - "Lasted".Translate(), - ": ", - this.TicksPassed.ToStringTicksToPeriod(true, false, true) - }); + Vector2 location = (this.Map == null) ? ((Find.VisibleMap == null) ? ((Find.AnyPlayerHomeMap == null) ? Vector2.zero : Find.WorldGrid.LongLatOf(Find.AnyPlayerHomeMap.Tile)) : Find.WorldGrid.LongLatOf(Find.VisibleMap.Tile)) : Find.WorldGrid.LongLatOf(this.Map.Tile); + string text = labelCap; + labelCap = (text = text + "\n" + "Started".Translate() + ": " + GenDate.DateFullStringAt(GenDate.TickGameToAbs(this.startTick), location)); + labelCap = text + "\n" + "Lasted".Translate() + ": " + this.TicksPassed.ToStringTicksToPeriod(true, false, true); } - text += "\n"; - return text + "\n" + this.def.description; + labelCap += "\n"; + return labelCap + "\n" + this.def.description; } } @@ -170,7 +138,7 @@ public virtual float SkyTargetLerpFactor() public virtual SkyTarget? SkyTarget() { - return null; + return default(SkyTarget?); } public virtual float AnimalDensityFactor() diff --git a/Assembly-CSharp/RimWorld/GameConditionDefOf.cs b/Assembly-CSharp/RimWorld/GameConditionDefOf.cs index de1eecdbd..2108cc745 100644 --- a/Assembly-CSharp/RimWorld/GameConditionDefOf.cs +++ b/Assembly-CSharp/RimWorld/GameConditionDefOf.cs @@ -1,4 +1,3 @@ -using System; using Verse; namespace RimWorld diff --git a/Assembly-CSharp/RimWorld/GameConditionManager.cs b/Assembly-CSharp/RimWorld/GameConditionManager.cs index e26b088cc..1aac2258b 100644 --- a/Assembly-CSharp/RimWorld/GameConditionManager.cs +++ b/Assembly-CSharp/RimWorld/GameConditionManager.cs @@ -58,9 +58,9 @@ public void ExposeData() public void GameConditionManagerTick() { - for (int i = this.activeConditions.Count - 1; i >= 0; i--) + for (int num = this.activeConditions.Count - 1; num >= 0; num--) { - GameCondition gameCondition = this.activeConditions[i]; + GameCondition gameCondition = this.activeConditions[num]; if (gameCondition.Expired) { gameCondition.End(); @@ -74,9 +74,9 @@ public void GameConditionManagerTick() public void GameConditionManagerDraw() { - for (int i = this.activeConditions.Count - 1; i >= 0; i--) + for (int num = this.activeConditions.Count - 1; num >= 0; num--) { - this.activeConditions[i].GameConditionDraw(); + this.activeConditions[num].GameConditionDraw(); } if (this.Parent != null) { @@ -109,17 +109,17 @@ public T GetActiveCondition() where T : GameCondition { for (int i = 0; i < this.activeConditions.Count; i++) { - T t = this.activeConditions[i] as T; - if (t != null) + T val = (T)(this.activeConditions[i] as T); + if (val != null) { - return t; + return val; } } if (this.Parent != null) { return this.Parent.GetActiveCondition(); } - return (T)((object)null); + return (T)null; } public float TotalHeightAt(float width) @@ -142,13 +142,13 @@ public void DoConditionsUI(Rect rect) float num = 0f; for (int i = 0; i < this.activeConditions.Count; i++) { - float width = rect.width - 15f; + float width = (float)(rect.width - 15.0); Rect rect2 = new Rect(0f, num, width, Text.CalcHeight(this.activeConditions[i].LabelCap, width)); Text.Font = GameFont.Small; Text.Anchor = TextAnchor.MiddleRight; Widgets.Label(rect2, this.activeConditions[i].LabelCap); GameCondition localCond = this.activeConditions[i]; - TooltipHandler.TipRegion(rect2, () => localCond.TooltipString, i * 631); + TooltipHandler.TipRegion(rect2, (Func)(() => localCond.TooltipString), i * 631); num += rect2.height; } rect.yMin += num; @@ -165,7 +165,7 @@ internal float AggregateSkyTargetLerpFactor() float num = 0f; for (int i = 0; i < this.activeConditions.Count; i++) { - num += (1f - num) * this.activeConditions[i].SkyTargetLerpFactor(); + num = (float)(num + (1.0 - num) * this.activeConditions[i].SkyTargetLerpFactor()); } if (this.Parent != null) { @@ -179,9 +179,9 @@ internal float AggregateSkyTargetLerpFactor() SkyTarget value = default(SkyTarget); float num = 0f; this.AggregateSkyTargetWorker(ref value, ref num); - if (num == 0f) + if (num == 0.0) { - return null; + return default(SkyTarget?); } return new SkyTarget?(value); } @@ -192,9 +192,9 @@ private void AggregateSkyTargetWorker(ref SkyTarget total, ref float lfTotal) { GameCondition gameCondition = this.activeConditions[i]; float num = gameCondition.SkyTargetLerpFactor(); - if (num > 0f) + if (num > 0.0) { - if (lfTotal == 0f) + if (lfTotal == 0.0) { total = gameCondition.SkyTarget().Value; lfTotal = num; @@ -256,7 +256,7 @@ internal float AggregatePlantDensityFactor() internal bool AllowEnjoyableOutsideNow() { - GameConditionDef gameConditionDef; + GameConditionDef gameConditionDef = default(GameConditionDef); return this.AllowEnjoyableOutsideNow(out gameConditionDef); } @@ -272,15 +272,28 @@ internal bool AllowEnjoyableOutsideNow(out GameConditionDef reason) } } reason = null; - return this.Parent == null || this.Parent.AllowEnjoyableOutsideNow(out reason); + if (this.Parent != null) + { + return this.Parent.AllowEnjoyableOutsideNow(out reason); + } + return true; } public string DebugString() { StringBuilder stringBuilder = new StringBuilder(); - foreach (GameCondition current in this.activeConditions) + List.Enumerator enumerator = this.activeConditions.GetEnumerator(); + try + { + while (enumerator.MoveNext()) + { + GameCondition current = enumerator.Current; + stringBuilder.AppendLine(Scribe.saver.DebugOutputFor(current)); + } + } + finally { - stringBuilder.AppendLine(Scribe.saver.DebugOutputFor(current)); + ((IDisposable)(object)enumerator).Dispose(); } return stringBuilder.ToString(); } diff --git a/Assembly-CSharp/RimWorld/GameConditionUtility.cs b/Assembly-CSharp/RimWorld/GameConditionUtility.cs index f89234697..5896322bd 100644 --- a/Assembly-CSharp/RimWorld/GameConditionUtility.cs +++ b/Assembly-CSharp/RimWorld/GameConditionUtility.cs @@ -1,25 +1,12 @@ -using System; using UnityEngine; namespace RimWorld { public static class GameConditionUtility { - public static float LerpInOutValue(float timePassed, float timeLeft, float lerpTime, float lerpTarget = 1f) + public static float LerpInOutValue(float timePassed, float timeLeft, float lerpTime, float lerpTarget = 1) { - float t; - if (timePassed < lerpTime) - { - t = timePassed / lerpTime; - } - else if (timeLeft < lerpTime) - { - t = timeLeft / lerpTime; - } - else - { - t = 1f; - } + float t = (float)((!(timePassed < lerpTime)) ? ((!(timeLeft < lerpTime)) ? 1.0 : (timeLeft / lerpTime)) : (timePassed / lerpTime)); return Mathf.Lerp(0f, lerpTarget, t); } } diff --git a/Assembly-CSharp/RimWorld/GameCondition_ClimateCycle.cs b/Assembly-CSharp/RimWorld/GameCondition_ClimateCycle.cs index eefa61f4a..25fd2dfa5 100644 --- a/Assembly-CSharp/RimWorld/GameCondition_ClimateCycle.cs +++ b/Assembly-CSharp/RimWorld/GameCondition_ClimateCycle.cs @@ -1,4 +1,3 @@ -using System; using UnityEngine; using Verse; @@ -14,7 +13,7 @@ public class GameCondition_ClimateCycle : GameCondition public override void Init() { - this.ticksOffset = ((Rand.Value >= 0.5f) ? 7200000 : 0); + this.ticksOffset = ((!(Rand.Value < 0.5)) ? 7200000 : 0); } public override void ExposeData() @@ -25,7 +24,7 @@ public override void ExposeData() public override float TemperatureOffset() { - return Mathf.Sin(GenDate.YearsPassedFloat / 4f * 3.14159274f * 2f) * 20f; + return (float)(Mathf.Sin((float)(GenDate.YearsPassedFloat / 4.0 * 3.1415927410125732 * 2.0)) * 20.0); } } } diff --git a/Assembly-CSharp/RimWorld/GameCondition_ColdSnap.cs b/Assembly-CSharp/RimWorld/GameCondition_ColdSnap.cs index 25d151004..33fe2804d 100644 --- a/Assembly-CSharp/RimWorld/GameCondition_ColdSnap.cs +++ b/Assembly-CSharp/RimWorld/GameCondition_ColdSnap.cs @@ -1,5 +1,3 @@ -using System; - namespace RimWorld { public class GameCondition_ColdSnap : GameCondition diff --git a/Assembly-CSharp/RimWorld/GameCondition_Eclipse.cs b/Assembly-CSharp/RimWorld/GameCondition_Eclipse.cs index badaeaefa..20f3e0a85 100644 --- a/Assembly-CSharp/RimWorld/GameCondition_Eclipse.cs +++ b/Assembly-CSharp/RimWorld/GameCondition_Eclipse.cs @@ -1,4 +1,3 @@ -using System; using UnityEngine; using Verse; diff --git a/Assembly-CSharp/RimWorld/GameCondition_Flashstorm.cs b/Assembly-CSharp/RimWorld/GameCondition_Flashstorm.cs index 6c49201e1..a45b20bbf 100644 --- a/Assembly-CSharp/RimWorld/GameCondition_Flashstorm.cs +++ b/Assembly-CSharp/RimWorld/GameCondition_Flashstorm.cs @@ -1,6 +1,5 @@ using System; using System.Collections.Generic; -using System.Diagnostics; using UnityEngine; using Verse; @@ -59,18 +58,31 @@ public override void End() private void FindGoodCenterLocation() { - if (base.Map.Size.x <= 16 || base.Map.Size.z <= 16) + IntVec3 size = base.Map.Size; + if (size.x > 16) { - throw new Exception("Map too small for flashstorm."); - } - for (int i = 0; i < 10; i++) - { - this.centerLocation = new IntVec2(Rand.Range(8, base.Map.Size.x - 8), Rand.Range(8, base.Map.Size.z - 8)); - if (this.IsGoodCenterLocation(this.centerLocation)) + IntVec3 size2 = base.Map.Size; + if (size2.z <= 16) + goto IL_0034; + int num = 0; + while (num < 10) { + IntVec3 size3 = base.Map.Size; + int newX = Rand.Range(8, size3.x - 8); + IntVec3 size4 = base.Map.Size; + this.centerLocation = new IntVec2(newX, Rand.Range(8, size4.z - 8)); + if (!this.IsGoodCenterLocation(this.centerLocation)) + { + num++; + continue; + } break; } + return; } + goto IL_0034; + IL_0034: + throw new Exception("Map too small for flashstorm."); } private bool IsGoodLocationForStrike(IntVec3 loc) @@ -81,31 +93,31 @@ private bool IsGoodLocationForStrike(IntVec3 loc) private bool IsGoodCenterLocation(IntVec2 loc) { int num = 0; - int num2 = (int)(3.14159274f * (float)this.areaRadius * (float)this.areaRadius / 2f); - foreach (IntVec3 current in this.GetPotentiallyAffectedCells(loc)) + int num2 = (int)(3.1415927410125732 * (float)this.areaRadius * (float)this.areaRadius / 2.0); + foreach (IntVec3 potentiallyAffectedCell in this.GetPotentiallyAffectedCells(loc)) { - if (this.IsGoodLocationForStrike(current)) + if (this.IsGoodLocationForStrike(potentiallyAffectedCell)) { num++; } if (num >= num2) - { break; - } } return num >= num2; } - [DebuggerHidden] private IEnumerable GetPotentiallyAffectedCells(IntVec2 center) { - GameCondition_Flashstorm.c__IteratorA2 c__IteratorA = new GameCondition_Flashstorm.c__IteratorA2(); - c__IteratorA.center = center; - c__IteratorA.<$>center = center; - c__IteratorA.<>f__this = this; - GameCondition_Flashstorm.c__IteratorA2 expr_1C = c__IteratorA; - expr_1C.$PC = -2; - return expr_1C; + for (int x = center.x - this.areaRadius; x <= center.x + this.areaRadius; x++) + { + for (int z = center.z - this.areaRadius; z <= center.z + this.areaRadius; z++) + { + if ((center.x - x) * (center.x - x) + (center.z - z) * (center.z - z) <= this.areaRadius * this.areaRadius) + { + yield return new IntVec3(x, 0, z); + } + } + } } } } diff --git a/Assembly-CSharp/RimWorld/GameCondition_HeatWave.cs b/Assembly-CSharp/RimWorld/GameCondition_HeatWave.cs index 45e7e9a22..ad7d09846 100644 --- a/Assembly-CSharp/RimWorld/GameCondition_HeatWave.cs +++ b/Assembly-CSharp/RimWorld/GameCondition_HeatWave.cs @@ -1,5 +1,3 @@ -using System; - namespace RimWorld { public class GameCondition_HeatWave : GameCondition diff --git a/Assembly-CSharp/RimWorld/GameCondition_Planetkiller.cs b/Assembly-CSharp/RimWorld/GameCondition_Planetkiller.cs index c946f36e2..72cb771c9 100644 --- a/Assembly-CSharp/RimWorld/GameCondition_Planetkiller.cs +++ b/Assembly-CSharp/RimWorld/GameCondition_Planetkiller.cs @@ -1,4 +1,3 @@ -using System; using UnityEngine; using Verse; using Verse.Sound; @@ -17,27 +16,12 @@ public override string TooltipString { get { - string text = this.def.LabelCap; - text += "\n"; - text = text + "\n" + this.def.description; - string text2 = text; - text = string.Concat(new string[] - { - text2, - "\n", - "ImpactDate".Translate().CapitalizeFirst(), - ": ", - GenDate.DateFullStringAt((long)GenDate.TickGameToAbs(this.startTick + this.duration), Find.WorldGrid.LongLatOf(base.Map.Tile)) - }); - text2 = text; - return string.Concat(new string[] - { - text2, - "\n", - "TimeLeft".Translate().CapitalizeFirst(), - ": ", - base.TicksLeft.ToStringTicksToPeriod(true, false, true) - }); + string labelCap = base.def.LabelCap; + labelCap += "\n"; + string text; + labelCap = (text = labelCap + "\n" + base.def.description); + labelCap = (text = text + "\n" + "ImpactDate".Translate().CapitalizeFirst() + ": " + GenDate.DateFullStringAt(GenDate.TickGameToAbs(base.startTick + base.duration), Find.WorldGrid.LongLatOf(base.Map.Tile))); + return text + "\n" + "TimeLeft".Translate().CapitalizeFirst() + ": " + base.TicksLeft.ToStringTicksToPeriod(true, false, true); } } @@ -67,10 +51,7 @@ public override void End() private void Impact() { ScreenFader.SetColor(Color.clear); - GenGameEnd.EndGameDialogMessage("GameOverPlanetkillerImpact".Translate(new object[] - { - Find.World.info.name - }), false, GameCondition_Planetkiller.FadeColor); + GenGameEnd.EndGameDialogMessage("GameOverPlanetkillerImpact".Translate(Find.World.info.name), false, GameCondition_Planetkiller.FadeColor); } } } diff --git a/Assembly-CSharp/RimWorld/GameCondition_PsychicEmanation.cs b/Assembly-CSharp/RimWorld/GameCondition_PsychicEmanation.cs index 97b113d7c..05b2096de 100644 --- a/Assembly-CSharp/RimWorld/GameCondition_PsychicEmanation.cs +++ b/Assembly-CSharp/RimWorld/GameCondition_PsychicEmanation.cs @@ -11,7 +11,7 @@ public override string Label { get { - return this.def.label + " (" + this.gender.ToString().Translate().ToLower() + ")"; + return base.def.label + " (" + ((Enum)(object)this.gender).ToString().Translate().ToLower() + ")"; } } diff --git a/Assembly-CSharp/RimWorld/GameCondition_ToxicFallout.cs b/Assembly-CSharp/RimWorld/GameCondition_ToxicFallout.cs index c80f5cf21..7a67d9d4b 100644 --- a/Assembly-CSharp/RimWorld/GameCondition_ToxicFallout.cs +++ b/Assembly-CSharp/RimWorld/GameCondition_ToxicFallout.cs @@ -1,4 +1,3 @@ -using System; using System.Collections.Generic; using UnityEngine; using Verse; @@ -21,22 +20,12 @@ public class GameCondition_ToxicFallout : GameCondition private const float CorpseRotProgressAdd = 3000f; - private SkyColorSet ToxicFalloutColors; + private SkyColorSet ToxicFalloutColors = new SkyColorSet(new ColorInt(216, 255, 0).ToColor, new ColorInt(234, 200, 255).ToColor, new Color(0.6f, 0.8f, 0.5f), 0.85f); - private List overlays; - - public GameCondition_ToxicFallout() + private List overlays = new List { - ColorInt colorInt = new ColorInt(216, 255, 0); - Color arg_50_0 = colorInt.ToColor; - ColorInt colorInt2 = new ColorInt(234, 200, 255); - this.ToxicFalloutColors = new SkyColorSet(arg_50_0, colorInt2.ToColor, new Color(0.6f, 0.8f, 0.5f), 0.85f); - this.overlays = new List - { - new WeatherOverlay_Fallout() - }; - base..ctor(); - } + (SkyOverlay)new WeatherOverlay_Fallout() + }; public override void Init() { @@ -56,7 +45,7 @@ public override void GameConditionTick() { float num = 0.028758334f; num *= pawn.GetStatValue(StatDefOf.ToxicSensitivity, true); - if (num != 0f) + if (num != 0.0) { float num2 = Mathf.Lerp(0.85f, 1.15f, Rand.ValueSeeded(pawn.thingIDNumber ^ 74374237)); num *= num2; @@ -81,15 +70,15 @@ public override void DoCellSteadyEffects(IntVec3 c) Thing thing = thingList[i]; if (thing is Plant) { - if (Rand.Value < 0.0065f) + if (Rand.Value < 0.0065000001341104507) { - thing.Kill(null); + thing.Kill(default(DamageInfo?)); } } else if (thing.def.category == ThingCategory.Item) { CompRottable compRottable = thing.TryGetComp(); - if (compRottable != null && compRottable.Stage < RotStage.Dessicated) + if (compRottable != null && (int)compRottable.Stage < 2) { compRottable.RotProgress += 3000f; } diff --git a/Assembly-CSharp/RimWorld/GameCondition_VolcanicWinter.cs b/Assembly-CSharp/RimWorld/GameCondition_VolcanicWinter.cs index b6b848c94..e98cb7079 100644 --- a/Assembly-CSharp/RimWorld/GameCondition_VolcanicWinter.cs +++ b/Assembly-CSharp/RimWorld/GameCondition_VolcanicWinter.cs @@ -1,4 +1,3 @@ -using System; using UnityEngine; using Verse; @@ -16,14 +15,7 @@ public class GameCondition_VolcanicWinter : GameCondition private float MaxTempOffset = -7f; - private SkyColorSet VolcanicWinterColors; - - public GameCondition_VolcanicWinter() - { - ColorInt colorInt = new ColorInt(0, 0, 0); - this.VolcanicWinterColors = new SkyColorSet(colorInt.ToColor, Color.white, new Color(0.6f, 0.6f, 0.6f), 0.65f); - base..ctor(); - } + private SkyColorSet VolcanicWinterColors = new SkyColorSet(new ColorInt(0, 0, 0).ToColor, Color.white, new Color(0.6f, 0.6f, 0.6f), 0.65f); public override float SkyTargetLerpFactor() { @@ -42,7 +34,7 @@ public override float TemperatureOffset() public override float AnimalDensityFactor() { - return 1f - GameConditionUtility.LerpInOutValue((float)base.TicksPassed, (float)base.TicksLeft, (float)this.LerpTicks, 0.5f); + return (float)(1.0 - GameConditionUtility.LerpInOutValue((float)base.TicksPassed, (float)base.TicksLeft, (float)this.LerpTicks, 0.5f)); } public override bool AllowEnjoyableOutsideNow() diff --git a/Assembly-CSharp/RimWorld/GameEnder.cs b/Assembly-CSharp/RimWorld/GameEnder.cs index 68a1dcef3..eadf0aead 100644 --- a/Assembly-CSharp/RimWorld/GameEnder.cs +++ b/Assembly-CSharp/RimWorld/GameEnder.cs @@ -1,5 +1,4 @@ using RimWorld.Planet; -using System; using System.Collections.Generic; using Verse; @@ -21,40 +20,44 @@ public void ExposeData() public void CheckGameOver() { - if (Find.TickManager.TicksGame < 300) + if (Find.TickManager.TicksGame >= 300 && !this.gameEnding) { - return; - } - if (this.gameEnding) - { - return; - } - List maps = Find.Maps; - for (int i = 0; i < maps.Count; i++) - { - if (maps[i].mapPawns.FreeColonistsSpawnedOrInPlayerEjectablePodsCount >= 1) + List maps = Find.Maps; + int num = 0; + while (num < maps.Count) { + if (maps[num].mapPawns.FreeColonistsSpawnedOrInPlayerEjectablePodsCount < 1) + { + num++; + continue; + } return; } - } - List caravans = Find.WorldObjects.Caravans; - for (int j = 0; j < caravans.Count; j++) - { - if (this.IsPlayerControlledWithFreeColonist(caravans[j])) + List caravans = Find.WorldObjects.Caravans; + int num2 = 0; + while (num2 < caravans.Count) { + if (!this.IsPlayerControlledWithFreeColonist(caravans[num2])) + { + num2++; + continue; + } return; } - } - List travelingTransportPods = Find.WorldObjects.TravelingTransportPods; - for (int k = 0; k < travelingTransportPods.Count; k++) - { - if (travelingTransportPods[k].PodsHaveAnyFreeColonist) + List travelingTransportPods = Find.WorldObjects.TravelingTransportPods; + int num3 = 0; + while (num3 < travelingTransportPods.Count) { + if (!travelingTransportPods[num3].PodsHaveAnyFreeColonist) + { + num3++; + continue; + } return; } + this.gameEnding = true; + this.ticksToGameOver = 400; } - this.gameEnding = true; - this.ticksToGameOver = 400; } public void GameEndTick() diff --git a/Assembly-CSharp/RimWorld/GameVictoryUtility.cs b/Assembly-CSharp/RimWorld/GameVictoryUtility.cs index e4a993b8c..870f14fa7 100644 --- a/Assembly-CSharp/RimWorld/GameVictoryUtility.cs +++ b/Assembly-CSharp/RimWorld/GameVictoryUtility.cs @@ -1,5 +1,4 @@ using RimWorld.Planet; -using System; using System.Collections.Generic; using System.Text; using UnityEngine; @@ -21,9 +20,9 @@ public static void ShowCredits(string victoryText) public static string PawnsLeftBehind() { StringBuilder stringBuilder = new StringBuilder(); - foreach (Pawn current in PawnsFinder.AllMaps_FreeColonistsSpawned) + foreach (Pawn item in PawnsFinder.AllMaps_FreeColonistsSpawned) { - stringBuilder.AppendLine(" " + current.LabelCap); + stringBuilder.AppendLine(" " + item.LabelCap); } List caravans = Find.WorldObjects.Caravans; for (int i = 0; i < caravans.Count; i++) diff --git a/Assembly-CSharp/RimWorld/Gas.cs b/Assembly-CSharp/RimWorld/Gas.cs index 0b88bd661..6b7b213c8 100644 --- a/Assembly-CSharp/RimWorld/Gas.cs +++ b/Assembly-CSharp/RimWorld/Gas.cs @@ -1,4 +1,3 @@ -using System; using Verse; namespace RimWorld @@ -16,15 +15,16 @@ public override void SpawnSetup(Map map, bool respawningAfterLoad) while (true) { Thing gas = base.Position.GetGas(map); - if (gas == null) + if (gas != null) { - break; + gas.Destroy(DestroyMode.Vanish); + continue; } - gas.Destroy(DestroyMode.Vanish); + break; } base.SpawnSetup(map, respawningAfterLoad); - this.destroyTick = Find.TickManager.TicksGame + this.def.gas.expireSeconds.RandomInRange.SecondsToTicks(); - this.graphicRotationSpeed = Rand.Range(-this.def.gas.rotationSpeed, this.def.gas.rotationSpeed) / 60f; + this.destroyTick = Find.TickManager.TicksGame + base.def.gas.expireSeconds.RandomInRange.SecondsToTicks(); + this.graphicRotationSpeed = (float)(Rand.Range((float)(0.0 - base.def.gas.rotationSpeed), base.def.gas.rotationSpeed) / 60.0); } public override void Tick() diff --git a/Assembly-CSharp/RimWorld/GasProperties.cs b/Assembly-CSharp/RimWorld/GasProperties.cs index 7a716b2eb..f3fa1e028 100644 --- a/Assembly-CSharp/RimWorld/GasProperties.cs +++ b/Assembly-CSharp/RimWorld/GasProperties.cs @@ -1,4 +1,3 @@ -using System; using Verse; namespace RimWorld diff --git a/Assembly-CSharp/RimWorld/GatherAnimalsAndSlavesForCaravanUtility.cs b/Assembly-CSharp/RimWorld/GatherAnimalsAndSlavesForCaravanUtility.cs index dda378eea..cf36dcc90 100644 --- a/Assembly-CSharp/RimWorld/GatherAnimalsAndSlavesForCaravanUtility.cs +++ b/Assembly-CSharp/RimWorld/GatherAnimalsAndSlavesForCaravanUtility.cs @@ -14,7 +14,7 @@ public static bool IsFollowingAnyone(Pawn p) public static void SetFollower(Pawn p, Pawn follower) { - p.mindState.duty.focus = follower; + p.mindState.duty.focus = (Thing)follower; } public static void CheckArrived(Lord lord, IntVec3 meetingPoint, string memo, Predicate shouldCheckIfArrived, Predicate extraValidator = null) @@ -23,13 +23,10 @@ public static void CheckArrived(Lord lord, IntVec3 meetingPoint, string memo, Pr for (int i = 0; i < lord.ownedPawns.Count; i++) { Pawn pawn = lord.ownedPawns[i]; - if (shouldCheckIfArrived(pawn)) + if (shouldCheckIfArrived(pawn) && (!pawn.Position.InHorDistOf(meetingPoint, 10f) || !pawn.CanReach(meetingPoint, PathEndMode.ClosestTouch, Danger.Deadly, false, TraverseMode.ByPawn) || ((object)extraValidator != null && !extraValidator(pawn)))) { - if (!pawn.Position.InHorDistOf(meetingPoint, 10f) || !pawn.CanReach(meetingPoint, PathEndMode.ClosestTouch, Danger.Deadly, false, TraverseMode.ByPawn) || (extraValidator != null && !extraValidator(pawn))) - { - flag = false; - break; - } + flag = false; + break; } } if (flag) diff --git a/Assembly-CSharp/RimWorld/GatherItemsForCaravanUtility.cs b/Assembly-CSharp/RimWorld/GatherItemsForCaravanUtility.cs index 92ce198bb..aa5d557bb 100644 --- a/Assembly-CSharp/RimWorld/GatherItemsForCaravanUtility.cs +++ b/Assembly-CSharp/RimWorld/GatherItemsForCaravanUtility.cs @@ -27,11 +27,11 @@ public static Thing FindThingToHaul(Pawn p, Lord lord) } } } - if (!GatherItemsForCaravanUtility.neededItems.Any()) + if (!GatherItemsForCaravanUtility.neededItems.Any()) { return null; } - Predicate validator = (Thing x) => GatherItemsForCaravanUtility.neededItems.Contains(x) && p.CanReserve(x, 1, -1, null, false); + Predicate validator = (Predicate)((Thing x) => GatherItemsForCaravanUtility.neededItems.Contains(x) && p.CanReserve(x, 1, -1, null, false)); Thing result = GenClosest.ClosestThingReachable(p.Position, p.Map, ThingRequest.ForGroup(ThingRequestGroup.HaulableEver), PathEndMode.Touch, TraverseParms.For(p, Danger.Deadly, TraverseMode.ByPawn, false), 9999f, validator, null, 0, -1, false, RegionType.Set_Passable, false); GatherItemsForCaravanUtility.neededItems.Clear(); return result; @@ -39,11 +39,11 @@ public static Thing FindThingToHaul(Pawn p, Lord lord) public static int CountLeftToTransfer(Pawn pawn, TransferableOneWay transferable, Lord lord) { - if (transferable.CountToTransfer <= 0 || !transferable.HasAnyThing) + if (transferable.CountToTransfer > 0 && transferable.HasAnyThing) { - return 0; + return Mathf.Max(transferable.CountToTransfer - GatherItemsForCaravanUtility.TransferableCountHauledByOthers(pawn, transferable, lord), 0); } - return Mathf.Max(transferable.CountToTransfer - GatherItemsForCaravanUtility.TransferableCountHauledByOthers(pawn, transferable, lord), 0); + return 0; } private static int TransferableCountHauledByOthers(Pawn pawn, TransferableOneWay transferable, Lord lord) @@ -58,15 +58,12 @@ private static int TransferableCountHauledByOthers(Pawn pawn, TransferableOneWay for (int i = 0; i < allPawnsSpawned.Count; i++) { Pawn pawn2 = allPawnsSpawned[i]; - if (pawn2 != pawn) + if (pawn2 != pawn && pawn2.CurJob != null && pawn2.CurJob.def == JobDefOf.PrepareCaravan_GatherItems && pawn2.CurJob.lord == lord) { - if (pawn2.CurJob != null && pawn2.CurJob.def == JobDefOf.PrepareCaravan_GatherItems && pawn2.CurJob.lord == lord) + Thing toHaul = ((JobDriver_PrepareCaravan_GatherItems)pawn2.jobs.curDriver).ToHaul; + if (transferable.things.Contains(toHaul) || TransferableUtility.TransferAsOne(transferable.AnyThing, toHaul)) { - Thing toHaul = ((JobDriver_PrepareCaravan_GatherItems)pawn2.jobs.curDriver).ToHaul; - if (transferable.things.Contains(toHaul) || TransferableUtility.TransferAsOne(transferable.AnyThing, toHaul)) - { - num += toHaul.stackCount; - } + num += toHaul.stackCount; } } } diff --git a/Assembly-CSharp/RimWorld/GatherSpotLister.cs b/Assembly-CSharp/RimWorld/GatherSpotLister.cs index 6e49ffd89..4e6fea5b6 100644 --- a/Assembly-CSharp/RimWorld/GatherSpotLister.cs +++ b/Assembly-CSharp/RimWorld/GatherSpotLister.cs @@ -1,4 +1,3 @@ -using System; using System.Collections.Generic; namespace RimWorld diff --git a/Assembly-CSharp/RimWorld/GatheringsUtility.cs b/Assembly-CSharp/RimWorld/GatheringsUtility.cs index bba5745ea..77e5be9dc 100644 --- a/Assembly-CSharp/RimWorld/GatheringsUtility.cs +++ b/Assembly-CSharp/RimWorld/GatheringsUtility.cs @@ -1,4 +1,3 @@ -using System; using System.Collections.Generic; using Verse; using Verse.AI.Group; @@ -9,7 +8,39 @@ public static class GatheringsUtility { public static bool ShouldGuestKeepAttendingGathering(Pawn p) { - return !p.Downed && (p.needs == null || !p.needs.food.Starving) && p.health.hediffSet.BleedRateTotal <= 0f && p.needs.rest.CurCategory < RestCategory.Exhausted && !p.health.hediffSet.HasTendableNonInjuryNonMissingPartHediff(false) && p.Awake() && !p.InAggroMentalState && !p.IsPrisoner; + if (p.Downed) + { + return false; + } + if (p.needs != null && p.needs.food.Starving) + { + return false; + } + if (p.health.hediffSet.BleedRateTotal > 0.0) + { + return false; + } + if ((int)p.needs.rest.CurCategory >= 3) + { + return false; + } + if (p.health.hediffSet.HasTendableNonInjuryNonMissingPartHediff(false)) + { + return false; + } + if (!p.Awake()) + { + return false; + } + if (p.InAggroMentalState) + { + return false; + } + if (p.IsPrisoner) + { + return false; + } + return true; } public static bool AnyLordJobPreventsNewGatherings(Map map) diff --git a/Assembly-CSharp/RimWorld/GenCelestial.cs b/Assembly-CSharp/RimWorld/GenCelestial.cs index d144e9b1b..ca053d790 100644 --- a/Assembly-CSharp/RimWorld/GenCelestial.cs +++ b/Assembly-CSharp/RimWorld/GenCelestial.cs @@ -1,4 +1,3 @@ -using System; using System.Text; using UnityEngine; using Verse; @@ -19,34 +18,44 @@ private static int TicksAbsForSunPosInWorldSpace { get { - if (Current.ProgramState != ProgramState.Entry) + if (Current.ProgramState != 0) { return GenTicks.TicksAbs; } int startingTile = Find.GameInitData.startingTile; - float longitude = (startingTile < 0) ? 0f : Find.WorldGrid.LongLatOf(startingTile).x; - return Mathf.RoundToInt(2500f * (12f - GenDate.TimeZoneFloatAt(longitude))); + double num; + if (startingTile >= 0) + { + Vector2 vector = Find.WorldGrid.LongLatOf(startingTile); + num = vector.x; + } + else + { + num = 0.0; + } + float longitude = (float)num; + return Mathf.RoundToInt((float)(2500.0 * (12.0 - GenDate.TimeZoneFloatAt(longitude)))); } } public static float CurCelestialSunGlow(Map map) { - return GenCelestial.CelestialSunGlowPercent(Find.WorldGrid.LongLatOf(map.Tile).y, GenLocalDate.DayOfYear(map), GenLocalDate.DayPercent(map)); + Vector2 vector = Find.WorldGrid.LongLatOf(map.Tile); + return GenCelestial.CelestialSunGlowPercent(vector.y, GenLocalDate.DayOfYear(map), GenLocalDate.DayPercent(map)); } public static float CurShadowStrength(Map map) { - return Mathf.Clamp01(Mathf.Abs(GenCelestial.CurCelestialSunGlow(map) - 0.6f) / 0.15f); + return Mathf.Clamp01((float)(Mathf.Abs((float)(GenCelestial.CurCelestialSunGlow(map) - 0.60000002384185791)) / 0.15000000596046448)); } public static Vector2 CurShadowVector(Map map) { float num = GenLocalDate.DayPercent(map); - bool flag = GenCelestial.IsDaytime(GenCelestial.CurCelestialSunGlow(map)); float t; float num2; float num3; - if (flag) + if (GenCelestial.IsDaytime(GenCelestial.CurCelestialSunGlow(map))) { t = num; num2 = -1.5f; @@ -54,31 +63,24 @@ public static Vector2 CurShadowVector(Map map) } else { - if (num > 0.5f) - { - t = Mathf.InverseLerp(0.5f, 1f, num) * 0.5f; - } - else - { - t = 0.5f + Mathf.InverseLerp(0f, 0.5f, num) * 0.5f; - } + t = (float)((!(num > 0.5)) ? (0.5 + Mathf.InverseLerp(0f, 0.5f, num) * 0.5) : (Mathf.InverseLerp(0.5f, 1f, num) * 0.5)); num2 = -0.9f; num3 = 15f; } - float num4 = Mathf.Lerp(num3, -num3, t); - float y = num2 - 2.5f * (num4 * num4 / 100f); + float num4 = Mathf.Lerp(num3, (float)(0.0 - num3), t); + float y = (float)(num2 - 2.5 * (num4 * num4 / 100.0)); return new Vector2(num4, y); } public static Vector3 CurSunPositionInWorldSpace() { int ticksAbsForSunPosInWorldSpace = GenCelestial.TicksAbsForSunPosInWorldSpace; - return GenCelestial.SunPositionUnmodified((float)GenDate.DayOfYear((long)ticksAbsForSunPosInWorldSpace, 0f), GenDate.DayPercent((long)ticksAbsForSunPosInWorldSpace, 0f), new Vector3(0f, 0f, -1f)); + return GenCelestial.SunPositionUnmodified((float)GenDate.DayOfYear(ticksAbsForSunPosInWorldSpace, 0f), GenDate.DayPercent(ticksAbsForSunPosInWorldSpace, 0f), new Vector3(0f, 0f, -1f)); } public static bool IsDaytime(float glow) { - return glow > 0.6f; + return glow > 0.60000002384185791; } private static Vector3 SunPosition(float latitude, int dayOfYear, float dayPercent) @@ -87,9 +89,9 @@ private static Vector3 SunPosition(float latitude, int dayOfYear, float dayPerce Vector3 current = GenCelestial.SunPositionUnmodified((float)dayOfYear, dayPercent, new Vector3(1f, 0f, 0f)); current = Vector3.RotateTowards(current, target, 0.331612557f, 9999999f); float num = Mathf.InverseLerp(60f, 0f, Mathf.Abs(latitude)); - if (num > 0f) + if (num > 0.0) { - current = Vector3.RotateTowards(current, target, 6.28318548f * (17f * num / 360f), 9999999f); + current = Vector3.RotateTowards(current, target, (float)(6.2831854820251465 * (17.0 * num / 360.0)), 9999999f); } return current.normalized; } @@ -97,11 +99,11 @@ private static Vector3 SunPosition(float latitude, int dayOfYear, float dayPerce private static Vector3 SunPositionUnmodified(float dayOfYear, float dayPercent, Vector3 initialSunPos) { Vector3 point = initialSunPos * 100f; - float num = dayOfYear / 60f; - float f = num * 3.14159274f * 2f; - float num2 = -Mathf.Cos(f); - point.y += num2 * 20f; - float angle = (dayPercent - 0.5f) * 360f; + float num = (float)(dayOfYear / 60.0); + float f = (float)(num * 3.1415927410125732 * 2.0); + float num2 = (float)(0.0 - Mathf.Cos(f)); + point.y += (float)(num2 * 20.0); + float angle = (float)((dayPercent - 0.5) * 360.0); point = Quaternion.AngleAxis(angle, Vector3.up) * point; return point.normalized; } @@ -117,30 +119,29 @@ private static float CelestialSunGlowPercent(float latitude, int dayOfYear, floa private static Vector3 SurfaceNormal(float latitude) { - Vector3 vector = new Vector3(1f, 0f, 0f); - vector = Quaternion.AngleAxis(latitude, new Vector3(0f, 0f, 1f)) * vector; - return vector; + Vector3 point = new Vector3(1f, 0f, 0f); + return Quaternion.AngleAxis(latitude, new Vector3(0f, 0f, 1f)) * point; } public static void LogSunGlowForYear() { - for (int i = -90; i <= 90; i += 10) + for (int num = -90; num <= 90; num += 10) { StringBuilder stringBuilder = new StringBuilder(); - stringBuilder.AppendLine("Sun visibility percents for latitude " + i + ", for each hour of each day of the year"); + stringBuilder.AppendLine("Sun visibility percents for latitude " + num + ", for each hour of each day of the year"); stringBuilder.AppendLine("---------------------------------------"); stringBuilder.Append("Day/hr".PadRight(6)); - for (int j = 0; j < 24; j += 2) + for (int num2 = 0; num2 < 24; num2 += 2) { - stringBuilder.Append((j.ToString() + "h").PadRight(6)); + stringBuilder.Append((num2.ToString() + "h").PadRight(6)); } stringBuilder.AppendLine(); - for (int k = 0; k < 60; k += 5) + for (int num3 = 0; num3 < 60; num3 += 5) { - stringBuilder.Append(k.ToString().PadRight(6)); - for (int l = 0; l < 24; l += 2) + stringBuilder.Append(num3.ToString().PadRight(6)); + for (int num4 = 0; num4 < 24; num4 += 2) { - stringBuilder.Append(GenCelestial.CelestialSunGlowPercent((float)i, k, (float)l / 24f).ToString("F3").PadRight(6)); + stringBuilder.Append(GenCelestial.CelestialSunGlowPercent((float)num, num3, (float)((float)num4 / 24.0)).ToString("F3").PadRight(6)); } stringBuilder.AppendLine(); } diff --git a/Assembly-CSharp/RimWorld/GenConstruct.cs b/Assembly-CSharp/RimWorld/GenConstruct.cs index 85a4951dc..43e3334c8 100644 --- a/Assembly-CSharp/RimWorld/GenConstruct.cs +++ b/Assembly-CSharp/RimWorld/GenConstruct.cs @@ -89,18 +89,35 @@ public static bool CanConstruct(Thing t, Pawn p, bool forced = false) return false; } } - return p.CanReserveAndReach(t, PathEndMode.Touch, (!forced) ? p.NormalMaxDanger() : Danger.Deadly, 1, -1, null, forced) && !t.IsBurning(); + if (!p.CanReserveAndReach(t, PathEndMode.Touch, (!forced) ? p.NormalMaxDanger() : Danger.Deadly, 1, -1, null, forced)) + { + return false; + } + if (t.IsBurning()) + { + return false; + } + return true; } public static int AmountNeededByOf(IConstructible c, ThingDef resDef) { - foreach (ThingCountClass current in c.MaterialsNeeded()) + List.Enumerator enumerator = c.MaterialsNeeded().GetEnumerator(); + try { - if (current.thingDef == resDef) + while (enumerator.MoveNext()) { - return current.count; + ThingCountClass current = enumerator.Current; + if (current.thingDef == resDef) + { + return current.count; + } } } + finally + { + ((IDisposable)(object)enumerator).Dispose(); + } return 0; } @@ -129,22 +146,19 @@ public static AcceptanceReport CanPlaceBlueprintAt(BuildableDef entDef, IntVec3 for (int i = 0; i < thingList.Count; i++) { Thing thing = thingList[i]; - if (thing != thingToIgnore) + if (thing != thingToIgnore && thing.Position == center && thing.Rotation == rot) { - if (thing.Position == center && thing.Rotation == rot) + if (thing.def == entDef) { - if (thing.def == entDef) - { - return new AcceptanceReport("IdenticalThingExists".Translate()); - } - if (thing.def.entityDefToBuild == entDef) + return new AcceptanceReport("IdenticalThingExists".Translate()); + } + if (thing.def.entityDefToBuild == entDef) + { + if (thing is Blueprint) { - if (thing is Blueprint) - { - return new AcceptanceReport("IdenticalBlueprintExists".Translate()); - } - return new AcceptanceReport("IdenticalThingExists".Translate()); + return new AcceptanceReport("IdenticalBlueprintExists".Translate()); } + return new AcceptanceReport("IdenticalThingExists".Translate()); } } } @@ -163,59 +177,50 @@ public static AcceptanceReport CanPlaceBlueprintAt(BuildableDef entDef, IntVec3 { if (list[j].def.passability == Traversability.Impassable) { - return new AcceptanceReport("InteractionSpotBlocked".Translate(new object[] - { - list[j].LabelNoCount - }).CapitalizeFirst()); + return new AcceptanceReport("InteractionSpotBlocked".Translate(list[j].LabelNoCount).CapitalizeFirst()); } Blueprint blueprint = list[j] as Blueprint; if (blueprint != null && blueprint.def.entityDefToBuild.passability == Traversability.Impassable) { - return new AcceptanceReport("InteractionSpotWillBeBlocked".Translate(new object[] - { - blueprint.LabelNoCount - }).CapitalizeFirst()); + return new AcceptanceReport("InteractionSpotWillBeBlocked".Translate(blueprint.LabelNoCount).CapitalizeFirst()); } } } } - if (entDef.passability != Traversability.Standable) + if (entDef.passability != 0) { - foreach (IntVec3 current2 in GenAdj.CellsAdjacentCardinal(center, rot, entDef.Size)) + foreach (IntVec3 item in GenAdj.CellsAdjacentCardinal(center, rot, entDef.Size)) { - if (current2.InBounds(map)) + if (item.InBounds(map)) { - thingList = current2.GetThingList(map); + thingList = item.GetThingList(map); for (int k = 0; k < thingList.Count; k++) { Thing thing2 = thingList[k]; + ThingDef thingDef2; if (thing2 != thingToIgnore) { + thingDef2 = null; Blueprint blueprint2 = thing2 as Blueprint; - ThingDef thingDef3; if (blueprint2 != null) { - ThingDef thingDef2 = blueprint2.def.entityDefToBuild as ThingDef; - if (thingDef2 == null) + ThingDef thingDef3 = blueprint2.def.entityDefToBuild as ThingDef; + if (thingDef3 != null) { - goto IL_37E; + thingDef2 = thingDef3; + goto IL_0316; } - thingDef3 = thingDef2; - } - else - { - thingDef3 = thing2.def; - } - if (thingDef3.hasInteractionCell && cellRect.Contains(Thing.InteractionCellWhenAt(thingDef3, thing2.Position, thing2.Rotation, thing2.Map))) - { - return new AcceptanceReport("WouldBlockInteractionSpot".Translate(new object[] - { - entDef.label, - thingDef3.label - }).CapitalizeFirst()); + continue; } + thingDef2 = thing2.def; + goto IL_0316; + } + continue; + IL_0316: + if (thingDef2.hasInteractionCell && cellRect.Contains(Thing.InteractionCellWhenAt(thingDef2, thing2.Position, thing2.Rotation, thing2.Map))) + { + return new AcceptanceReport("WouldBlockInteractionSpot".Translate(entDef.label, thingDef2.label).CapitalizeFirst()); } - IL_37E:; } } } @@ -225,10 +230,7 @@ public static AcceptanceReport CanPlaceBlueprintAt(BuildableDef entDef, IntVec3 { if (map.terrainGrid.TerrainAt(center) == terrainDef) { - return new AcceptanceReport("TerrainIsAlready".Translate(new object[] - { - terrainDef.label - })); + return new AcceptanceReport("TerrainIsAlready".Translate(terrainDef.label)); } if (map.designationManager.DesignationAt(center, DesignationDefOf.SmoothFloor) != null) { @@ -248,12 +250,9 @@ public static AcceptanceReport CanPlaceBlueprintAt(BuildableDef entDef, IntVec3 for (int l = 0; l < thingList.Count; l++) { Thing thing3 = thingList[l]; - if (thing3 != thingToIgnore) + if (thing3 != thingToIgnore && !GenConstruct.CanPlaceBlueprintOver(entDef, thing3.def)) { - if (!GenConstruct.CanPlaceBlueprintOver(entDef, thing3.def)) - { - return new AcceptanceReport("SpaceAlreadyOccupied".Translate()); - } + return new AcceptanceReport("SpaceAlreadyOccupied".Translate()); } } iterator2.MoveNext(); @@ -307,59 +306,95 @@ public static bool CanPlaceBlueprintOver(BuildableDef newDef, ThingDef oldDef) { return false; } - if (oldDef.category == ThingCategory.Building || oldDef.IsBlueprint || oldDef.IsFrame) + if (oldDef.category != ThingCategory.Building && !oldDef.IsBlueprint && !oldDef.IsFrame) { - if (thingDef != null) + return true; + } + if (thingDef != null) + { + if (!thingDef.IsEdifice()) { - if (!thingDef.IsEdifice()) - { - return (oldDef.building == null || oldDef.building.canBuildNonEdificesUnder) && (!thingDef.EverTransmitsPower || !oldDef.EverTransmitsPower); - } - if (thingDef.IsEdifice() && oldDef != null && oldDef.category == ThingCategory.Building && !oldDef.IsEdifice()) + if (oldDef.building != null && !oldDef.building.canBuildNonEdificesUnder) { - return thingDef.building == null || thingDef.building.canBuildNonEdificesUnder; + return false; } - if (thingDef2 != null && thingDef2 == ThingDefOf.Wall && thingDef.building != null && thingDef.building.canPlaceOverWall) + if (thingDef.EverTransmitsPower && oldDef.EverTransmitsPower) { - return true; + return false; } - if (newDef != ThingDefOf.PowerConduit && buildableDef == ThingDefOf.PowerConduit) + return true; + } + if (thingDef.IsEdifice() && oldDef != null && oldDef.category == ThingCategory.Building && !oldDef.IsEdifice()) + { + if (thingDef.building != null && !thingDef.building.canBuildNonEdificesUnder) { - return true; + return false; } + return true; + } + if (thingDef2 != null && thingDef2 == ThingDefOf.Wall && thingDef.building != null && thingDef.building.canPlaceOverWall) + { + return true; + } + if (newDef != ThingDefOf.PowerConduit && buildableDef == ThingDefOf.PowerConduit) + { + return true; } - return (newDef is TerrainDef && buildableDef is ThingDef && ((ThingDef)buildableDef).CoexistsWithFloors) || (buildableDef is TerrainDef && !(newDef is TerrainDef)); } - return true; + if (newDef is TerrainDef && buildableDef is ThingDef && ((ThingDef)buildableDef).CoexistsWithFloors) + { + return true; + } + if (buildableDef is TerrainDef && !(newDef is TerrainDef)) + { + return true; + } + return false; } public static bool BlocksFramePlacement(Blueprint blue, Thing t) { if (t.def.category == ThingCategory.Plant) { - return t.def.plant.harvestWork >= 200f; - } - if (blue.def.entityDefToBuild is TerrainDef || blue.def.entityDefToBuild.passability == Traversability.Standable) - { - return false; - } - if (t.def == ThingDefOf.SteamGeyser && blue.def.entityDefToBuild.ForceAllowPlaceOver(t.def)) - { + if (t.def.plant.harvestWork >= 200.0) + { + return true; + } return false; } - ThingDef thingDef = blue.def.entityDefToBuild as ThingDef; - if (thingDef != null) + if (((!(blue.def.entityDefToBuild is TerrainDef)) ? blue.def.entityDefToBuild.passability : Traversability.Standable) != 0) { - if (thingDef.EverTransmitsPower && t.def == ThingDefOf.PowerConduit && thingDef != ThingDefOf.PowerConduit) + if (t.def == ThingDefOf.SteamGeyser && blue.def.entityDefToBuild.ForceAllowPlaceOver(t.def)) { return false; } - if (t.def == ThingDefOf.Wall && thingDef.building != null && thingDef.building.canPlaceOverWall) + ThingDef thingDef = blue.def.entityDefToBuild as ThingDef; + if (thingDef != null) + { + if (thingDef.EverTransmitsPower && t.def == ThingDefOf.PowerConduit && thingDef != ThingDefOf.PowerConduit) + { + return false; + } + if (t.def == ThingDefOf.Wall && thingDef.building != null && thingDef.building.canPlaceOverWall) + { + return false; + } + } + if (t.def.IsEdifice() && thingDef.IsEdifice()) + { + return true; + } + if (t.def.category != ThingCategory.Pawn && (t.def.category != ThingCategory.Item || blue.def.entityDefToBuild.passability != Traversability.Impassable)) { + if ((int)t.def.Fillage >= 1 && thingDef != null && (int)thingDef.Fillage >= 1) + { + return true; + } return false; } + return true; } - return (t.def.IsEdifice() && thingDef.IsEdifice()) || (t.def.category == ThingCategory.Pawn || (t.def.category == ThingCategory.Item && blue.def.entityDefToBuild.passability == Traversability.Impassable)) || (t.def.Fillage >= FillCategory.Partial && thingDef != null && thingDef.Fillage >= FillCategory.Partial); + return false; } public static bool TerrainCanSupport(CellRect rect, Map map, ThingDef thing) diff --git a/Assembly-CSharp/RimWorld/GenDate.cs b/Assembly-CSharp/RimWorld/GenDate.cs index 65993dd5d..1e25e92b4 100644 --- a/Assembly-CSharp/RimWorld/GenDate.cs +++ b/Assembly-CSharp/RimWorld/GenDate.cs @@ -66,7 +66,7 @@ public static float DaysPassedFloat { get { - return (float)GenDate.TicksGame / 60000f; + return (float)((float)GenDate.TicksGame / 60000.0); } } @@ -82,7 +82,7 @@ public static float TwelfthsPassedFloat { get { - return (float)GenDate.TicksGame / 300000f; + return (float)((float)GenDate.TicksGame / 300000.0); } } @@ -98,7 +98,7 @@ public static float YearsPassedFloat { get { - return (float)GenDate.TicksGame / 3600000f; + return (float)((float)GenDate.TicksGame / 3600000.0); } } @@ -135,13 +135,13 @@ private static long LocalTicksOffsetFromLongitude(float longitude) public static int HourOfDay(long absTicks, float longitude) { long num = absTicks + GenDate.LocalTicksOffsetFromLongitude(longitude); - return (int)(num % 60000L / 2500L); + return (int)(num % 60000 / 2500); } public static int DayOfTwelfth(long absTicks, float longitude) { long num = absTicks + GenDate.LocalTicksOffsetFromLongitude(longitude); - int num2 = (int)(num / 60000L % 5L); + int num2 = (int)(num / 60000 % 5); if (num2 < 0) { num2 += 5; @@ -152,7 +152,7 @@ public static int DayOfTwelfth(long absTicks, float longitude) public static int DayOfYear(long absTicks, float longitude) { long num = absTicks + GenDate.LocalTicksOffsetFromLongitude(longitude); - int num2 = (int)(num / 60000L) % 60; + int num2 = (int)(num / 60000) % 60; if (num2 < 0) { num2 += 60; @@ -163,12 +163,12 @@ public static int DayOfYear(long absTicks, float longitude) public static Twelfth Twelfth(long absTicks, float longitude) { long num = absTicks + GenDate.LocalTicksOffsetFromLongitude(longitude); - int num2 = (int)(num / 300000L % 12L); + int num2 = (int)(num / 300000 % 12); if (num2 < 0) { num2 += 12; } - return (Twelfth)num2; + return (Twelfth)(byte)num2; } public static Season Season(long absTicks, Vector2 longLat) @@ -191,8 +191,8 @@ public static Quadrum Quadrum(long absTicks, float longitude) public static int Year(long absTicks, float longitude) { long num = absTicks + GenDate.LocalTicksOffsetFromLongitude(longitude); - int num2 = (int)(num / 3600000L); - if (num < 0L) + int num2 = (int)(num / 3600000); + if (num < 0) { num2--; } @@ -202,106 +202,84 @@ public static int Year(long absTicks, float longitude) public static int DayOfSeason(long absTicks, float longitude) { int num = GenDate.DayOfYear(absTicks, longitude); - return (num - (int)(SeasonUtility.FirstSeason.GetFirstTwelfth(0f) * RimWorld.Twelfth.Sixth)) % 15; + return (num - (int)SeasonUtility.FirstSeason.GetFirstTwelfth(0f) * 5) % 15; } public static int DayOfQuadrum(long absTicks, float longitude) { int num = GenDate.DayOfYear(absTicks, longitude); - return (num - (int)(QuadrumUtility.FirstQuadrum.GetFirstTwelfth() * RimWorld.Twelfth.Sixth)) % 15; + return (num - (int)QuadrumUtility.FirstQuadrum.GetFirstTwelfth() * 5) % 15; } public static float DayPercent(long absTicks, float longitude) { long num = absTicks + GenDate.LocalTicksOffsetFromLongitude(longitude); - int num2 = (int)(num % 60000L); + int num2 = (int)(num % 60000); if (num2 == 0) { num2 = 1; } - return (float)num2 / 60000f; + return (float)((float)num2 / 60000.0); } public static int HourInteger(long absTicks, float longitude) { long num = absTicks + GenDate.LocalTicksOffsetFromLongitude(longitude); - int num2 = (int)(num % 60000L); + int num2 = (int)(num % 60000); return num2 / 2500; } public static float HourFloat(long absTicks, float longitude) { - return GenDate.DayPercent(absTicks, longitude) * 24f; + return (float)(GenDate.DayPercent(absTicks, longitude) * 24.0); } public static string DateFullStringAt(long absTicks, Vector2 location) { int num = GenDate.DayOfSeason(absTicks, location.x) + 1; string text = Find.ActiveLanguageWorker.OrdinalNumber(num); - return "FullDate".Translate(new object[] - { - text, - GenDate.Quadrum(absTicks, location.x).Label(), - GenDate.Year(absTicks, location.x), - num - }); + return "FullDate".Translate(text, GenDate.Quadrum(absTicks, location.x).Label(), GenDate.Year(absTicks, location.x), num); } public static string DateReadoutStringAt(long absTicks, Vector2 location) { int num = GenDate.DayOfSeason(absTicks, location.x) + 1; string text = Find.ActiveLanguageWorker.OrdinalNumber(num); - return "DateReadout".Translate(new object[] - { - text, - GenDate.Quadrum(absTicks, location.x).Label(), - GenDate.Year(absTicks, location.x), - num - }); + return "DateReadout".Translate(text, GenDate.Quadrum(absTicks, location.x).Label(), GenDate.Year(absTicks, location.x), num); } public static string SeasonDateStringAt(long absTicks, Vector2 longLat) { int num = GenDate.DayOfSeason(absTicks, longLat.x) + 1; string text = Find.ActiveLanguageWorker.OrdinalNumber(num); - return "SeasonFullDate".Translate(new object[] - { - text, - GenDate.Season(absTicks, longLat).Label(), - num - }); + return "SeasonFullDate".Translate(text, GenDate.Season(absTicks, longLat).Label(), num); } public static string SeasonDateStringAt(Twelfth twelfth, Vector2 longLat) { - return GenDate.SeasonDateStringAt((long)((int)twelfth * 300000 + 1), longLat); + return GenDate.SeasonDateStringAt((int)twelfth * 300000 + 1, longLat); } public static string QuadrumDateStringAt(long absTicks, float longitude) { int num = GenDate.DayOfQuadrum(absTicks, longitude) + 1; string text = Find.ActiveLanguageWorker.OrdinalNumber(num); - return "SeasonFullDate".Translate(new object[] - { - text, - GenDate.Quadrum(absTicks, longitude).Label(), - num - }); + return "SeasonFullDate".Translate(text, GenDate.Quadrum(absTicks, longitude).Label(), num); } public static string QuadrumDateStringAt(Quadrum quadrum) { - return GenDate.QuadrumDateStringAt((long)((int)quadrum * 900000 + 1), 0f); + return GenDate.QuadrumDateStringAt((int)quadrum * 900000 + 1, 0f); } public static string QuadrumDateStringAt(Twelfth twelfth) { - return GenDate.QuadrumDateStringAt((long)((int)twelfth * 300000 + 1), 0f); + return GenDate.QuadrumDateStringAt((int)twelfth * 300000 + 1, 0f); } public static float TicksToDays(this int numTicks) { - return (float)numTicks / 60000f; + return (float)((float)numTicks / 60000.0); } public static string ToStringTicksToDays(this int numTicks, string format = "F1") @@ -315,10 +293,10 @@ public static string ToStringTicksToPeriod(this int numTicks, bool allowHours = { return "0"; } - int num; - int num2; - int num3; - float num4; + int num = default(int); + int num2 = default(int); + int num3 = default(int); + float num4 = default(float); numTicks.TicksToPeriod(out num, out num2, out num3, out num4); if (!allowQuadrums) { @@ -327,139 +305,61 @@ public static string ToStringTicksToPeriod(this int numTicks, bool allowHours = } if (num > 0) { - string text; - if (num == 1) - { - text = "Period1Year".Translate(); - } - else - { - text = "PeriodYears".Translate(new object[] - { - num - }); - } + string text = (num != 1) ? "PeriodYears".Translate(num) : "Period1Year".Translate(); if (num2 > 0) { text += ", "; - if (num2 == 1) - { - text += "Period1Quadrum".Translate(); - } - else - { - text += "PeriodQuadrums".Translate(new object[] - { - num2 - }); - } + text = ((num2 != 1) ? (text + "PeriodQuadrums".Translate(num2)) : (text + "Period1Quadrum".Translate())); } return text; } if (num2 > 0) { - string text2; - if (num2 == 1) - { - text2 = "Period1Quadrum".Translate(); - } - else - { - text2 = "PeriodQuadrums".Translate(new object[] - { - num2 - }); - } + string text2 = (num2 != 1) ? "PeriodQuadrums".Translate(num2) : "Period1Quadrum".Translate(); if (num3 > 0) { text2 += ", "; - if (num3 == 1) - { - text2 += "Period1Day".Translate(); - } - else - { - text2 += "PeriodDays".Translate(new object[] - { - num3 - }); - } + text2 = ((num3 != 1) ? (text2 + "PeriodDays".Translate(num3)) : (text2 + "Period1Day".Translate())); } return text2; } if (num3 > 0) { - string text3; - if (num3 == 1) - { - text3 = "Period1Day".Translate(); - } - else - { - text3 = "PeriodDays".Translate(new object[] - { - num3 - }); - } + string text3 = (num3 != 1) ? "PeriodDays".Translate(num3) : "Period1Day".Translate(); int num5 = (int)num4; if (allowHours && num5 > 0) { text3 += ", "; - if (num5 == 1) - { - text3 += "Period1Hour".Translate(); - } - else - { - text3 += "PeriodHours".Translate(new object[] - { - num5 - }); - } + text3 = ((num5 != 1) ? (text3 + "PeriodHours".Translate(num5)) : (text3 + "Period1Hour".Translate())); } return text3; } - if (!allowHours) - { - return "LessThanADay".Translate(); - } - if (hoursMax1DecimalPlace) + if (allowHours) { - if (num4 > 1f) + if (hoursMax1DecimalPlace) { - int num6 = Mathf.RoundToInt(num4); - if (num6 == 1) + if (num4 > 1.0) { - return "Period1Hour".Translate(); + int num6 = Mathf.RoundToInt(num4); + if (num6 == 1) + { + return "Period1Hour".Translate(); + } + return "PeriodHours".Translate(num6); } - return "PeriodHours".Translate(new object[] - { - num6 - }); - } - else - { if (Math.Round((double)num4, 1) == 1.0) { return "Period1Hour".Translate(); } - return "PeriodHours".Translate(new object[] - { - num4.ToString("0.#") - }); + return "PeriodHours".Translate(num4.ToString("0.#")); } - } - else - { if (Math.Round((double)num4, 2) == 1.0) { return "Period1Hour".Translate(); } - return "PeriodHours".Translate(new object[] - { - num4.ToStringDecimalIfSmall() - }); + return "PeriodHours".Translate(num4.ToStringDecimalIfSmall()); } + return "LessThanADay".Translate(); } public static string ToStringTicksToPeriodVagueMax(this int numTicks) @@ -478,73 +378,58 @@ public static void TicksToPeriod(this int numTicks, out int years, out int quadr public static void TicksToPeriod(this long numTicks, out int years, out int quadrums, out int days, out float hoursFloat) { - years = (int)(numTicks / 3600000L); + years = (int)(numTicks / 3600000); long num = numTicks - (long)years * 3600000L; - quadrums = (int)(num / 900000L); + quadrums = (int)(num / 900000); num -= (long)quadrums * 900000L; - days = (int)(num / 60000L); + days = (int)(num / 60000); num -= (long)days * 60000L; - hoursFloat = (float)num / 2500f; + hoursFloat = (float)((float)num / 2500.0); } public static string ToStringApproxAge(this float yearsFloat) { - if (yearsFloat >= 1f) + if (yearsFloat >= 1.0) { return ((int)yearsFloat).ToStringCached(); } - int num = (int)(yearsFloat * 3600000f); - num = Mathf.Min(num, 3599999); - int num2; - int num3; - int num4; - float num5; - num.TicksToPeriod(out num2, out num3, out num4, out num5); - if (num2 > 0) + int a = (int)(yearsFloat * 3600000.0); + a = Mathf.Min(a, 3599999); + int num = default(int); + int num2 = default(int); + int num3 = default(int); + float num4 = default(float); + a.TicksToPeriod(out num, out num2, out num3, out num4); + if (num > 0) { - if (num2 == 1) + if (num == 1) { return "Period1Year".Translate(); } - return "PeriodYears".Translate(new object[] - { - num2 - }); + return "PeriodYears".Translate(num); } - else if (num3 > 0) + if (num2 > 0) { - if (num3 == 1) + if (num2 == 1) { return "Period1Quadrum".Translate(); } - return "PeriodQuadrums".Translate(new object[] - { - num3 - }); + return "PeriodQuadrums".Translate(num2); } - else if (num4 > 0) + if (num3 > 0) { - if (num4 == 1) + if (num3 == 1) { return "Period1Day".Translate(); } - return "PeriodDays".Translate(new object[] - { - num4 - }); + return "PeriodDays".Translate(num3); } - else + int num5 = (int)num4; + if (num5 == 1) { - int num6 = (int)num5; - if (num6 == 1) - { - return "Period1Hour".Translate(); - } - return "PeriodHours".Translate(new object[] - { - num6 - }); + return "Period1Hour".Translate(); } + return "PeriodHours".Translate(num5); } public static int TimeZoneAt(float longitude) @@ -554,7 +439,7 @@ public static int TimeZoneAt(float longitude) public static float TimeZoneFloatAt(float longitude) { - return longitude / 15f; + return (float)(longitude / 15.0); } } } diff --git a/Assembly-CSharp/RimWorld/GenGameEnd.cs b/Assembly-CSharp/RimWorld/GenGameEnd.cs index 4d533c2e9..42a9b4115 100644 --- a/Assembly-CSharp/RimWorld/GenGameEnd.cs +++ b/Assembly-CSharp/RimWorld/GenGameEnd.cs @@ -21,13 +21,13 @@ public static void EndGameDialogMessage(string msg, bool allowKeepPlaying, Color diaNode.options.Add(diaOption); } DiaOption diaOption2 = new DiaOption("GameOverMainMenu".Translate()); - diaOption2.action = delegate + diaOption2.action = (Action)delegate { GenScene.GoToMainMenu(); }; diaOption2.resolveTree = true; diaNode.options.Add(diaOption2); - Dialog_NodeTree dialog_NodeTree = new Dialog_NodeTree(diaNode, true, false, null); + Dialog_NodeTree dialog_NodeTree = new Dialog_NodeTree(diaNode, true, false, (string)null); dialog_NodeTree.screenFillColor = screenFillColor; dialog_NodeTree.silenceAmbientSound = !allowKeepPlaying; dialog_NodeTree.closeOnEscapeKey = allowKeepPlaying; diff --git a/Assembly-CSharp/RimWorld/GenGuest.cs b/Assembly-CSharp/RimWorld/GenGuest.cs index cda93838d..43a56c54a 100644 --- a/Assembly-CSharp/RimWorld/GenGuest.cs +++ b/Assembly-CSharp/RimWorld/GenGuest.cs @@ -1,4 +1,3 @@ -using System; using Verse; using Verse.AI; @@ -16,15 +15,17 @@ public static void PrisonerRelease(Pawn p) { p.needs.mood.thoughts.memories.TryGainMemory(ThoughtDefOf.WasImprisoned, null); p.guest.SetGuestStatus(null, false); - return; } - p.guest.released = true; - IntVec3 c; - if (RCellFinder.TryFindBestExitSpot(p, out c, TraverseMode.ByPawn)) + else { - Job job = new Job(JobDefOf.Goto, c); - job.exitMapOnArrival = true; - p.jobs.StartJob(job, JobCondition.None, null, false, true, null, null); + p.guest.released = true; + IntVec3 c = default(IntVec3); + if (RCellFinder.TryFindBestExitSpot(p, out c, TraverseMode.ByPawn)) + { + Job job = new Job(JobDefOf.Goto, c); + job.exitMapOnArrival = true; + p.jobs.StartJob(job, JobCondition.None, null, false, true, null, default(JobTag?)); + } } } } diff --git a/Assembly-CSharp/RimWorld/GenHostility.cs b/Assembly-CSharp/RimWorld/GenHostility.cs index 50b02c05f..eaa38da47 100644 --- a/Assembly-CSharp/RimWorld/GenHostility.cs +++ b/Assembly-CSharp/RimWorld/GenHostility.cs @@ -9,13 +9,71 @@ public static class GenHostility { public static bool HostileTo(this Thing a, Thing b) { - if (a.Destroyed || b.Destroyed || a == b) + if (!a.Destroyed && !b.Destroyed && a != b) { + Pawn pawn = a as Pawn; + Pawn pawn2 = b as Pawn; + if (pawn != null && pawn.MentalState != null && pawn.MentalState.ForceHostileTo(b)) + { + goto IL_0071; + } + if (pawn2 != null && pawn2.MentalState != null && pawn2.MentalState.ForceHostileTo(a)) + goto IL_0071; + if (pawn != null && pawn2 != null && (GenHostility.IsPredatorHostileTo(pawn, pawn2) || GenHostility.IsPredatorHostileTo(pawn2, pawn))) + { + return true; + } + if (a.Faction != null && pawn2 != null && pawn2.HostFaction == a.Faction && (pawn == null || pawn.HostFaction == null) && PrisonBreakUtility.IsPrisonBreaking(pawn2)) + { + goto IL_0115; + } + if (b.Faction != null && pawn != null && pawn.HostFaction == b.Faction && (pawn2 == null || pawn2.HostFaction == null) && PrisonBreakUtility.IsPrisonBreaking(pawn)) + goto IL_0115; + if (a.Faction != null && pawn2 != null && pawn2.HostFaction == a.Faction) + { + goto IL_015b; + } + if (b.Faction != null && pawn != null && pawn.HostFaction == b.Faction) + goto IL_015b; + if (pawn != null && pawn.IsPrisoner && pawn2 != null && pawn2.IsPrisoner) + { + return false; + } + if (pawn != null && pawn2 != null) + { + if (pawn.IsPrisoner && pawn.HostFaction == pawn2.HostFaction && !PrisonBreakUtility.IsPrisonBreaking(pawn)) + { + goto IL_01db; + } + if (pawn2.IsPrisoner && pawn2.HostFaction == pawn.HostFaction && !PrisonBreakUtility.IsPrisonBreaking(pawn2)) + goto IL_01db; + } + if (pawn != null && pawn2 != null) + { + if (pawn.HostFaction != null && pawn2.Faction != null && !pawn.HostFaction.HostileTo(pawn2.Faction) && !PrisonBreakUtility.IsPrisonBreaking(pawn)) + { + goto IL_0257; + } + if (pawn2.HostFaction != null && pawn.Faction != null && !pawn2.HostFaction.HostileTo(pawn.Faction) && !PrisonBreakUtility.IsPrisonBreaking(pawn2)) + goto IL_0257; + } + if (a.Faction != null && b.Faction != null) + { + return a.Faction.HostileTo(b.Faction); + } return false; } - Pawn pawn = a as Pawn; - Pawn pawn2 = b as Pawn; - return (pawn != null && pawn.MentalState != null && pawn.MentalState.ForceHostileTo(b)) || (pawn2 != null && pawn2.MentalState != null && pawn2.MentalState.ForceHostileTo(a)) || (pawn != null && pawn2 != null && (GenHostility.IsPredatorHostileTo(pawn, pawn2) || GenHostility.IsPredatorHostileTo(pawn2, pawn))) || ((a.Faction != null && pawn2 != null && pawn2.HostFaction == a.Faction && (pawn == null || pawn.HostFaction == null) && PrisonBreakUtility.IsPrisonBreaking(pawn2)) || (b.Faction != null && pawn != null && pawn.HostFaction == b.Faction && (pawn2 == null || pawn2.HostFaction == null) && PrisonBreakUtility.IsPrisonBreaking(pawn))) || ((a.Faction == null || pawn2 == null || pawn2.HostFaction != a.Faction) && (b.Faction == null || pawn == null || pawn.HostFaction != b.Faction) && (pawn == null || !pawn.IsPrisoner || pawn2 == null || !pawn2.IsPrisoner) && (pawn == null || pawn2 == null || ((!pawn.IsPrisoner || pawn.HostFaction != pawn2.HostFaction || PrisonBreakUtility.IsPrisonBreaking(pawn)) && (!pawn2.IsPrisoner || pawn2.HostFaction != pawn.HostFaction || PrisonBreakUtility.IsPrisonBreaking(pawn2)))) && (pawn == null || pawn2 == null || ((pawn.HostFaction == null || pawn2.Faction == null || pawn.HostFaction.HostileTo(pawn2.Faction) || PrisonBreakUtility.IsPrisonBreaking(pawn)) && (pawn2.HostFaction == null || pawn.Faction == null || pawn2.HostFaction.HostileTo(pawn.Faction) || PrisonBreakUtility.IsPrisonBreaking(pawn2)))) && a.Faction != null && b.Faction != null && a.Faction.HostileTo(b.Faction)); + return false; + IL_0257: + return false; + IL_0115: + return true; + IL_0071: + return true; + IL_015b: + return false; + IL_01db: + return false; } public static bool HostileTo(this Thing t, Faction fac) @@ -49,7 +107,11 @@ public static bool HostileTo(this Thing t, Faction fac) return false; } } - return t.Faction != null && t.Faction.HostileTo(fac); + if (t.Faction == null) + { + return false; + } + return t.Faction.HostileTo(fac); } private static bool IsPredatorHostileTo(Pawn predator, Pawn toPawn) @@ -63,12 +125,24 @@ private static bool IsPredatorHostileTo(Pawn predator, Pawn toPawn) return true; } Pawn preyOfMyFaction = GenHostility.GetPreyOfMyFaction(predator, toPawn.Faction); - return preyOfMyFaction != null && predator.Position.InHorDistOf(preyOfMyFaction.Position, 12f); + if (preyOfMyFaction != null && predator.Position.InHorDistOf(preyOfMyFaction.Position, 12f)) + { + return true; + } + return false; } private static bool IsPredatorHostileTo(Pawn predator, Faction toFaction) { - return toFaction.HasPredatorRecentlyAttackedAnyone(predator) || GenHostility.GetPreyOfMyFaction(predator, toFaction) != null; + if (toFaction.HasPredatorRecentlyAttackedAnyone(predator)) + { + return true; + } + if (GenHostility.GetPreyOfMyFaction(predator, toFaction) != null) + { + return true; + } + return false; } private static Pawn GetPreyOfMyFaction(Pawn predator, Faction myFaction) @@ -88,13 +162,22 @@ private static Pawn GetPreyOfMyFaction(Pawn predator, Faction myFaction) public static bool AnyHostileActiveThreat(Map map) { HashSet targetsHostileToColony = map.attackTargetsCache.TargetsHostileToColony; - foreach (IAttackTarget current in targetsHostileToColony) + HashSet.Enumerator enumerator = targetsHostileToColony.GetEnumerator(); + try { - if (GenHostility.IsActiveThreat(current)) + while (enumerator.MoveNext()) { - return true; + IAttackTarget current = enumerator.Current; + if (GenHostility.IsActiveThreat(current)) + { + return true; + } } } + finally + { + ((IDisposable)(object)enumerator).Dispose(); + } return false; } diff --git a/Assembly-CSharp/RimWorld/GenLabel.cs b/Assembly-CSharp/RimWorld/GenLabel.cs index 82126f31d..d0d034ce4 100644 --- a/Assembly-CSharp/RimWorld/GenLabel.cs +++ b/Assembly-CSharp/RimWorld/GenLabel.cs @@ -15,7 +15,7 @@ private class LabelElement public int count; } - private struct LabelRequest : IEquatable + private struct LabelRequest : IEquatable { public Thing thing; @@ -35,45 +35,49 @@ private struct LabelRequest : IEquatable public override bool Equals(object obj) { - return obj is GenLabel.LabelRequest && this.Equals((GenLabel.LabelRequest)obj); + if (!(obj is LabelRequest)) + { + return false; + } + return this.Equals((LabelRequest)obj); } - public bool Equals(GenLabel.LabelRequest other) + public bool Equals(LabelRequest other) { return this.thing == other.thing && this.entDef == other.entDef && this.stuffDef == other.stuffDef && this.stackCount == other.stackCount && this.quality == other.quality && this.health == other.health && this.maxHealth == other.maxHealth && this.wornByCorpse == other.wornByCorpse; } public override int GetHashCode() { - int num = 0; - num = Gen.HashCombine(num, this.thing); - num = Gen.HashCombine(num, this.entDef); - num = Gen.HashCombine(num, this.stuffDef); + int seed = 0; + seed = Gen.HashCombine(seed, this.thing); + seed = Gen.HashCombine(seed, this.entDef); + seed = Gen.HashCombine(seed, this.stuffDef); ThingDef thingDef = this.entDef as ThingDef; if (thingDef != null) { - num = Gen.HashCombineInt(num, this.stackCount); - QualityCategory qualityCategory; + seed = Gen.HashCombineInt(seed, this.stackCount); + QualityCategory qualityCategory = default(QualityCategory); if (this.thing != null && this.thing.TryGetQuality(out qualityCategory)) { - num = Gen.HashCombineStruct(num, this.quality); + seed = Gen.HashCombineStruct(seed, this.quality); } if (thingDef.useHitPoints) { - num = Gen.HashCombineInt(num, this.health); - num = Gen.HashCombineInt(num, this.maxHealth); + seed = Gen.HashCombineInt(seed, this.health); + seed = Gen.HashCombineInt(seed, this.maxHealth); } - num = Gen.HashCombineInt(num, (!this.wornByCorpse) ? 0 : 1); + seed = Gen.HashCombineInt(seed, this.wornByCorpse ? 1 : 0); } - return num; + return seed; } - public static bool operator ==(GenLabel.LabelRequest lhs, GenLabel.LabelRequest rhs) + public static bool operator ==(LabelRequest lhs, LabelRequest rhs) { return lhs.Equals(rhs); } - public static bool operator !=(GenLabel.LabelRequest lhs, GenLabel.LabelRequest rhs) + public static bool operator !=(LabelRequest lhs, LabelRequest rhs) { return !(lhs == rhs); } @@ -81,9 +85,9 @@ public override int GetHashCode() private const int LabelDictionaryMaxCount = 2000; - private static Dictionary labelDictionary = new Dictionary(); + private static Dictionary labelDictionary = new Dictionary(); - private static List tmpThingsLabelElements = new List(); + private static List tmpThingsLabelElements = new List(); public static void ClearCache() { @@ -92,11 +96,13 @@ public static void ClearCache() public static string ThingLabel(BuildableDef entDef, ThingDef stuffDef, int stackCount = 1) { - GenLabel.LabelRequest key = default(GenLabel.LabelRequest); - key.entDef = entDef; - key.stuffDef = stuffDef; - key.stackCount = stackCount; - string text; + LabelRequest key = new LabelRequest + { + entDef = entDef, + stuffDef = stuffDef, + stackCount = stackCount + }; + string text = default(string); if (!GenLabel.labelDictionary.TryGetValue(key, out text)) { if (GenLabel.labelDictionary.Count > 2000) @@ -111,19 +117,7 @@ public static string ThingLabel(BuildableDef entDef, ThingDef stuffDef, int stac private static string NewThingLabel(BuildableDef entDef, ThingDef stuffDef, int stackCount) { - string text; - if (stuffDef == null) - { - text = entDef.label; - } - else - { - text = "ThingMadeOfStuffLabel".Translate(new object[] - { - stuffDef.LabelAsStuff, - entDef.label - }); - } + string text = (stuffDef != null) ? "ThingMadeOfStuffLabel".Translate(stuffDef.LabelAsStuff, entDef.label) : entDef.label; if (stackCount != 1) { text = text + " x" + stackCount.ToStringCached(); @@ -133,11 +127,13 @@ private static string NewThingLabel(BuildableDef entDef, ThingDef stuffDef, int public static string ThingLabel(Thing t) { - GenLabel.LabelRequest key = default(GenLabel.LabelRequest); - key.thing = t; - key.entDef = t.def; - key.stuffDef = t.Stuff; - key.stackCount = t.stackCount; + LabelRequest key = new LabelRequest + { + thing = t, + entDef = t.def, + stuffDef = t.Stuff, + stackCount = t.stackCount + }; t.TryGetQuality(out key.quality); if (t.def.useHitPoints) { @@ -149,7 +145,7 @@ public static string ThingLabel(Thing t) { key.wornByCorpse = apparel.WornByCorpse; } - string text; + string text = default(string); if (!GenLabel.labelDictionary.TryGetValue(key, out text)) { if (GenLabel.labelDictionary.Count > 2000) @@ -165,7 +161,7 @@ public static string ThingLabel(Thing t) private static string NewThingLabel(Thing t) { string text = GenLabel.ThingLabel(t.def, t.Stuff, 1); - QualityCategory cat; + QualityCategory cat = default(QualityCategory); bool flag = t.TryGetQuality(out cat); int hitPoints = t.HitPoints; int maxHitPoints = t.MaxHitPoints; @@ -199,25 +195,35 @@ private static string NewThingLabel(Thing t) public static string ThingsLabel(List things) { GenLabel.tmpThingsLabelElements.Clear(); - foreach (Thing thing in things) + List.Enumerator enumerator = things.GetEnumerator(); + try { - GenLabel.LabelElement labelElement = (from elem in GenLabel.tmpThingsLabelElements - where thing.def.stackLimit > 1 && elem.thingTemplate.def == thing.def && elem.thingTemplate.Stuff == thing.Stuff - select elem).FirstOrDefault(); - if (labelElement != null) - { - labelElement.count += thing.stackCount; - } - else - { - GenLabel.tmpThingsLabelElements.Add(new GenLabel.LabelElement + Thing thing; + while (enumerator.MoveNext()) + { + thing = enumerator.Current; + LabelElement labelElement = (from elem in GenLabel.tmpThingsLabelElements + where thing.def.stackLimit > 1 && elem.thingTemplate.def == thing.def && elem.thingTemplate.Stuff == thing.Stuff + select elem).FirstOrDefault(); + if (labelElement != null) { - thingTemplate = thing, - count = thing.stackCount - }); + labelElement.count += thing.stackCount; + } + else + { + GenLabel.tmpThingsLabelElements.Add(new LabelElement + { + thingTemplate = thing, + count = thing.stackCount + }); + } } } - GenLabel.tmpThingsLabelElements.Sort(delegate(GenLabel.LabelElement lhs, GenLabel.LabelElement rhs) + finally + { + ((IDisposable)(object)enumerator).Dispose(); + } + GenLabel.tmpThingsLabelElements.Sort((Comparison)delegate(LabelElement lhs, LabelElement rhs) { int num = TransferableComparer_Category.Compare(lhs.thingTemplate.def, rhs.thingTemplate.def); if (num != 0) @@ -227,32 +233,35 @@ public static string ThingsLabel(List things) return lhs.thingTemplate.MarketValue.CompareTo(rhs.thingTemplate.MarketValue); }); StringBuilder stringBuilder = new StringBuilder(); - foreach (GenLabel.LabelElement current in GenLabel.tmpThingsLabelElements) + List.Enumerator enumerator2 = GenLabel.tmpThingsLabelElements.GetEnumerator(); + try { - string str = string.Empty; - if (current.thingTemplate.ParentHolder is Pawn_ApparelTracker) + while (enumerator2.MoveNext()) { - str = " (" + "WornBy".Translate(new object[] + LabelElement current = enumerator2.Current; + string str = string.Empty; + if (current.thingTemplate.ParentHolder is Pawn_ApparelTracker) { - (current.thingTemplate.ParentHolder.ParentHolder as Pawn).LabelShort - }) + ")"; - } - else if (current.thingTemplate.ParentHolder is Pawn_EquipmentTracker) - { - str = " (" + "EquippedBy".Translate(new object[] + str = " (" + "WornBy".Translate((current.thingTemplate.ParentHolder.ParentHolder as Pawn).LabelShort) + ")"; + } + else if (current.thingTemplate.ParentHolder is Pawn_EquipmentTracker) { - (current.thingTemplate.ParentHolder.ParentHolder as Pawn).LabelShort - }) + ")"; - } - if (current.count == 1) - { - stringBuilder.AppendLine(" " + current.thingTemplate.LabelCap + str); - } - else - { - stringBuilder.AppendLine(" " + GenLabel.ThingLabel(current.thingTemplate.def, current.thingTemplate.Stuff, current.count).CapitalizeFirst() + str); + str = " (" + "EquippedBy".Translate((current.thingTemplate.ParentHolder.ParentHolder as Pawn).LabelShort) + ")"; + } + if (current.count == 1) + { + stringBuilder.AppendLine(" " + current.thingTemplate.LabelCap + str); + } + else + { + stringBuilder.AppendLine(" " + GenLabel.ThingLabel(current.thingTemplate.def, current.thingTemplate.Stuff, current.count).CapitalizeFirst() + str); + } } } + finally + { + ((IDisposable)(object)enumerator2).Dispose(); + } GenLabel.tmpThingsLabelElements.Clear(); return stringBuilder.ToString(); } @@ -261,10 +270,11 @@ public static string BestKindLabel(Pawn pawn, bool mustNoteGender = false, bool { bool flag = false; bool flag2 = false; - string text = null; + string text = (string)null; switch (pawn.gender) { case Gender.None: + { if (plural && !pawn.RaceProps.Humanlike && pawn.ageTracker.CurKindLifeStage.labelPlural != null) { text = pawn.ageTracker.CurKindLifeStage.labelPlural; @@ -292,7 +302,9 @@ public static string BestKindLabel(Pawn pawn, bool mustNoteGender = false, bool } } break; + } case Gender.Male: + { if (plural && !pawn.RaceProps.Humanlike && pawn.ageTracker.CurKindLifeStage.labelMalePlural != null) { text = pawn.ageTracker.CurKindLifeStage.labelMalePlural; @@ -350,7 +362,9 @@ public static string BestKindLabel(Pawn pawn, bool mustNoteGender = false, bool } } break; + } case Gender.Female: + { if (plural && !pawn.RaceProps.Humanlike && pawn.ageTracker.CurKindLifeStage.labelFemalePlural != null) { text = pawn.ageTracker.CurKindLifeStage.labelFemalePlural; @@ -409,21 +423,14 @@ public static string BestKindLabel(Pawn pawn, bool mustNoteGender = false, bool } break; } - if (mustNoteGender && !flag && pawn.gender != Gender.None) + } + if ((mustNoteGender ? ((!flag) ? pawn.gender : Gender.None) : Gender.None) != 0) { - text = "PawnMainDescGendered".Translate(new object[] - { - pawn.gender.GetLabel(), - text - }); + text = "PawnMainDescGendered".Translate(pawn.gender.GetLabel(), text); } if (mustNoteLifeStage && !flag2 && pawn.ageTracker != null && pawn.ageTracker.CurLifeStage.visible) { - text = "PawnMainDescLifestageWrap".Translate(new object[] - { - text, - pawn.ageTracker.CurLifeStage.Adjective - }); + text = "PawnMainDescLifestageWrap".Translate(text, pawn.ageTracker.CurLifeStage.Adjective); } return text; } diff --git a/Assembly-CSharp/RimWorld/GenLeaving.cs b/Assembly-CSharp/RimWorld/GenLeaving.cs index 377b7b82d..5d90e21f4 100644 --- a/Assembly-CSharp/RimWorld/GenLeaving.cs +++ b/Assembly-CSharp/RimWorld/GenLeaving.cs @@ -25,132 +25,135 @@ public static void DoLeavingsFor(Thing diedThing, Map map, DestroyMode mode) public static void DoLeavingsFor(Thing diedThing, Map map, DestroyMode mode, CellRect leavingsRect) { - if (Current.ProgramState != ProgramState.Playing || mode == DestroyMode.Vanish) + if (Current.ProgramState == ProgramState.Playing) { - return; - } - if (mode == DestroyMode.KillFinalize && diedThing.def.filthLeaving != null) - { - for (int i = leavingsRect.minZ; i <= leavingsRect.maxZ; i++) + switch (mode) + { + case DestroyMode.Vanish: + return; + case DestroyMode.KillFinalize: { - for (int j = leavingsRect.minX; j <= leavingsRect.maxX; j++) + if (diedThing.def.filthLeaving != null) { - IntVec3 c = new IntVec3(j, 0, i); - FilthMaker.MakeFilth(c, map, diedThing.def.filthLeaving, Rand.RangeInclusive(1, 3)); + for (int i = leavingsRect.minZ; i <= leavingsRect.maxZ; i++) + { + for (int j = leavingsRect.minX; j <= leavingsRect.maxX; j++) + { + IntVec3 c = new IntVec3(j, 0, i); + FilthMaker.MakeFilth(c, map, diedThing.def.filthLeaving, Rand.RangeInclusive(1, 3)); + } + } } + break; } - } - ThingOwner thingOwner = new ThingOwner(); - if (mode == DestroyMode.KillFinalize && diedThing.def.killedLeavings != null) - { - for (int k = 0; k < diedThing.def.killedLeavings.Count; k++) - { - Thing thing = ThingMaker.MakeThing(diedThing.def.killedLeavings[k].thingDef, null); - thing.stackCount = diedThing.def.killedLeavings[k].count; - thingOwner.TryAdd(thing, true); } - } - if (GenLeaving.CanBuildingLeaveResources(diedThing, mode)) - { - Frame frame = diedThing as Frame; - if (frame != null) + ThingOwner thingOwner = new ThingOwner(); + if (mode == DestroyMode.KillFinalize && diedThing.def.killedLeavings != null) { - for (int l = 0; l < frame.resourceContainer.Count; l++) + for (int k = 0; k < diedThing.def.killedLeavings.Count; k++) { - int num = GenLeaving.GetBuildingResourcesLeaveCalculator(diedThing, mode)(frame.resourceContainer[l].stackCount); - if (num > 0) - { - thingOwner.TryAdd(frame.resourceContainer[l], num, true); - } + Thing thing = ThingMaker.MakeThing(diedThing.def.killedLeavings[k].thingDef, null); + thing.stackCount = diedThing.def.killedLeavings[k].count; + thingOwner.TryAdd(thing, true); } } - else + if (GenLeaving.CanBuildingLeaveResources(diedThing, mode)) { - List list = diedThing.CostListAdjusted(); - for (int m = 0; m < list.Count; m++) + Frame frame = diedThing as Frame; + if (frame != null) { - ThingCountClass thingCountClass = list[m]; - int num2 = GenLeaving.GetBuildingResourcesLeaveCalculator(diedThing, mode)(thingCountClass.count); - if (num2 > 0 && mode == DestroyMode.KillFinalize && thingCountClass.thingDef.slagDef != null) + for (int l = 0; l < frame.resourceContainer.Count; l++) { - int count = thingCountClass.thingDef.slagDef.smeltProducts.First((ThingCountClass pro) => pro.thingDef == ThingDefOf.Steel).count; - int num3 = num2 / 2 / 8; - for (int n = 0; n < num3; n++) + int num = GenLeaving.GetBuildingResourcesLeaveCalculator(diedThing, mode)(frame.resourceContainer[l].stackCount); + if (num > 0) { - thingOwner.TryAdd(ThingMaker.MakeThing(thingCountClass.thingDef.slagDef, null), true); + thingOwner.TryAdd(frame.resourceContainer[l], num, true); } - num2 -= num3 * count; } - if (num2 > 0) + } + else + { + List list = diedThing.CostListAdjusted(); + for (int m = 0; m < list.Count; m++) { - Thing thing2 = ThingMaker.MakeThing(thingCountClass.thingDef, null); - thing2.stackCount = num2; - thingOwner.TryAdd(thing2, true); + ThingCountClass thingCountClass = list[m]; + int num2 = GenLeaving.GetBuildingResourcesLeaveCalculator(diedThing, mode)(thingCountClass.count); + if (num2 > 0 && mode == DestroyMode.KillFinalize && thingCountClass.thingDef.slagDef != null) + { + int count = thingCountClass.thingDef.slagDef.smeltProducts.First((Func)((ThingCountClass pro) => pro.thingDef == ThingDefOf.Steel)).count; + int num3 = num2 / 2 / 8; + for (int num4 = 0; num4 < num3; num4++) + { + thingOwner.TryAdd(ThingMaker.MakeThing(thingCountClass.thingDef.slagDef, null), true); + } + num2 -= num3 * count; + } + if (num2 > 0) + { + Thing thing2 = ThingMaker.MakeThing(thingCountClass.thingDef, null); + thing2.stackCount = num2; + thingOwner.TryAdd(thing2, true); + } } } } - } - List list2 = leavingsRect.Cells.InRandomOrder(null).ToList(); - int num4 = 0; - while (thingOwner.Count > 0) - { - if (mode == DestroyMode.KillFinalize && !map.areaManager.Home[list2[num4]]) - { - thingOwner[0].SetForbidden(true, false); - } - Thing thing3; - if (!thingOwner.TryDrop(thingOwner[0], list2[num4], map, ThingPlaceMode.Near, out thing3, null)) + List list2 = leavingsRect.Cells.InRandomOrder(null).ToList(); + int num5 = 0; + while (true) { - Log.Warning(string.Concat(new object[] + if (thingOwner.Count > 0) { - "Failed to place all leavings for destroyed thing ", - diedThing, - " at ", - leavingsRect.CenterCell - })); + if (mode == DestroyMode.KillFinalize && !((Area)map.areaManager.Home)[list2[num5]]) + { + thingOwner[0].SetForbidden(true, false); + } + Thing thing3 = default(Thing); + if (thingOwner.TryDrop(thingOwner[0], list2[num5], map, ThingPlaceMode.Near, out thing3, (Action)null)) + { + num5++; + if (num5 >= list2.Count) + { + num5 = 0; + } + continue; + } + break; + } return; } - num4++; - if (num4 >= list2.Count) - { - num4 = 0; - } + Log.Warning("Failed to place all leavings for destroyed thing " + diedThing + " at " + leavingsRect.CenterCell); } } public static void DoLeavingsFor(TerrainDef terrain, IntVec3 cell, Map map) { - if (Current.ProgramState != ProgramState.Playing) + if (Current.ProgramState == ProgramState.Playing) { - return; - } - ThingOwner thingOwner = new ThingOwner(); - List list = terrain.CostListAdjusted(null, true); - for (int i = 0; i < list.Count; i++) - { - ThingCountClass thingCountClass = list[i]; - int num = GenMath.RoundRandom((float)thingCountClass.count * terrain.resourcesFractionWhenDeconstructed); - if (num > 0) + ThingOwner thingOwner = new ThingOwner(); + List list = terrain.CostListAdjusted(null, true); + for (int i = 0; i < list.Count; i++) { - Thing thing = ThingMaker.MakeThing(thingCountClass.thingDef, null); - thing.stackCount = num; - thingOwner.TryAdd(thing, true); + ThingCountClass thingCountClass = list[i]; + int num = GenMath.RoundRandom((float)thingCountClass.count * terrain.resourcesFractionWhenDeconstructed); + if (num > 0) + { + Thing thing = ThingMaker.MakeThing(thingCountClass.thingDef, null); + thing.stackCount = num; + thingOwner.TryAdd(thing, true); + } } - } - while (thingOwner.Count > 0) - { - Thing thing2; - if (!thingOwner.TryDrop(thingOwner[0], cell, map, ThingPlaceMode.Near, out thing2, null)) + while (true) { - Log.Warning(string.Concat(new object[] + if (thingOwner.Count > 0) { - "Failed to place all leavings for removed terrain ", - terrain, - " at ", - cell - })); + Thing thing2 = default(Thing); + if (!thingOwner.TryDrop(thingOwner[0], cell, map, ThingPlaceMode.Near, out thing2, (Action)null)) + break; + continue; + } return; } + Log.Warning("Failed to place all leavings for removed terrain " + terrain + " at " + cell); } } @@ -167,66 +170,88 @@ public static bool CanBuildingLeaveResources(Thing diedThing, DestroyMode mode) switch (mode) { case DestroyMode.Vanish: + { return false; + } case DestroyMode.KillFinalize: + { return true; + } case DestroyMode.Deconstruct: - return diedThing.def.resourcesFractionWhenDeconstructed != 0f; - case DestroyMode.FailConstruction: - return true; + { + return diedThing.def.resourcesFractionWhenDeconstructed != 0.0; + } case DestroyMode.Cancel: + { return true; + } + case DestroyMode.FailConstruction: + { + return true; + } default: + { throw new ArgumentException("Unknown destroy mode " + mode); } + } } public static Func GetBuildingResourcesLeaveCalculator(Thing diedThing, DestroyMode mode) { if (!GenLeaving.CanBuildingLeaveResources(diedThing, mode)) { - return (int count) => 0; + return (Func)((int count) => 0); } switch (mode) { case DestroyMode.Vanish: - return (int count) => 0; + { + return (Func)((int count) => 0); + } case DestroyMode.KillFinalize: - return (int count) => GenMath.RoundRandom((float)count * 0.5f); + { + return (Func)((int count) => GenMath.RoundRandom((float)((float)count * 0.5))); + } case DestroyMode.Deconstruct: - return (int count) => GenMath.RoundRandom(Mathf.Min((float)count * diedThing.def.resourcesFractionWhenDeconstructed, (float)(count - 1))); - case DestroyMode.FailConstruction: - return (int count) => GenMath.RoundRandom((float)count * 0.5f); + { + return (Func)((int count) => GenMath.RoundRandom(Mathf.Min((float)count * diedThing.def.resourcesFractionWhenDeconstructed, (float)(count - 1)))); + } case DestroyMode.Cancel: - return (int count) => GenMath.RoundRandom((float)count * 1f); + { + return (Func)((int count) => GenMath.RoundRandom((float)((float)count * 1.0))); + } + case DestroyMode.FailConstruction: + { + return (Func)((int count) => GenMath.RoundRandom((float)((float)count * 0.5))); + } default: + { throw new ArgumentException("Unknown destroy mode " + mode); } + } } public static void DropFilthDueToDamage(Thing t, float damageDealt) { - if (!t.def.useHitPoints || !t.Spawned || t.def.filthLeaving == null) - { - return; - } - CellRect cellRect = t.OccupiedRect().ExpandedBy(1); - GenLeaving.tmpCellsCandidates.Clear(); - foreach (IntVec3 current in cellRect) + if (t.def.useHitPoints && t.Spawned && t.def.filthLeaving != null) { - if (current.InBounds(t.Map) && current.Walkable(t.Map)) + CellRect cellRect = t.OccupiedRect().ExpandedBy(1); + GenLeaving.tmpCellsCandidates.Clear(); + foreach (IntVec3 item in cellRect) { - GenLeaving.tmpCellsCandidates.Add(current); + if (item.InBounds(t.Map) && item.Walkable(t.Map)) + { + GenLeaving.tmpCellsCandidates.Add(item); + } + } + if (GenLeaving.tmpCellsCandidates.Any()) + { + int num = GenMath.RoundRandom(damageDealt * Mathf.Min(0.0166666675f, (float)(1.0 / ((float)t.MaxHitPoints / 10.0)))); + for (int num2 = 0; num2 < num; num2++) + { + FilthMaker.MakeFilth(GenLeaving.tmpCellsCandidates.RandomElement(), t.Map, t.def.filthLeaving, 1); + } } - } - if (!GenLeaving.tmpCellsCandidates.Any()) - { - return; - } - int num = GenMath.RoundRandom(damageDealt * Mathf.Min(0.0166666675f, 1f / ((float)t.MaxHitPoints / 10f))); - for (int i = 0; i < num; i++) - { - FilthMaker.MakeFilth(GenLeaving.tmpCellsCandidates.RandomElement(), t.Map, t.def.filthLeaving, 1); } } } diff --git a/Assembly-CSharp/RimWorld/GenLocalDate.cs b/Assembly-CSharp/RimWorld/GenLocalDate.cs index e5ffd347d..76c5ac8bb 100644 --- a/Assembly-CSharp/RimWorld/GenLocalDate.cs +++ b/Assembly-CSharp/RimWorld/GenLocalDate.cs @@ -1,4 +1,3 @@ -using System; using UnityEngine; using Verse; @@ -77,29 +76,29 @@ public static int DayOfYear(Thing thing) { if (Current.ProgramState == ProgramState.Playing) { - return GenDate.DayOfYear((long)GenLocalDate.TicksAbs, GenLocalDate.LongitudeForDate(thing)); + return GenDate.DayOfYear(GenLocalDate.TicksAbs, GenLocalDate.LongitudeForDate(thing)); } return 0; } public static int HourOfDay(Thing thing) { - return GenDate.HourOfDay((long)GenLocalDate.TicksAbs, GenLocalDate.LongitudeForDate(thing)); + return GenDate.HourOfDay(GenLocalDate.TicksAbs, GenLocalDate.LongitudeForDate(thing)); } public static int DayOfTwelfth(Thing thing) { - return GenDate.DayOfTwelfth((long)GenLocalDate.TicksAbs, GenLocalDate.LongitudeForDate(thing)); + return GenDate.DayOfTwelfth(GenLocalDate.TicksAbs, GenLocalDate.LongitudeForDate(thing)); } public static Twelfth Twelfth(Thing thing) { - return GenDate.Twelfth((long)GenLocalDate.TicksAbs, GenLocalDate.LongitudeForDate(thing)); + return GenDate.Twelfth(GenLocalDate.TicksAbs, GenLocalDate.LongitudeForDate(thing)); } public static Season Season(Thing thing) { - return GenDate.Season((long)GenLocalDate.TicksAbs, GenLocalDate.LocationForDate(thing)); + return GenDate.Season(GenLocalDate.TicksAbs, GenLocalDate.LocationForDate(thing)); } public static int Year(Thing thing) @@ -108,61 +107,69 @@ public static int Year(Thing thing) { return 5500; } - return GenDate.Year((long)GenLocalDate.TicksAbs, GenLocalDate.LongitudeForDate(thing)); + return GenDate.Year(GenLocalDate.TicksAbs, GenLocalDate.LongitudeForDate(thing)); } public static int DayOfSeason(Thing thing) { - return GenDate.DayOfSeason((long)GenLocalDate.TicksAbs, GenLocalDate.LongitudeForDate(thing)); + return GenDate.DayOfSeason(GenLocalDate.TicksAbs, GenLocalDate.LongitudeForDate(thing)); } public static int DayOfQuadrum(Thing thing) { - return GenDate.DayOfQuadrum((long)GenLocalDate.TicksAbs, GenLocalDate.LongitudeForDate(thing)); + return GenDate.DayOfQuadrum(GenLocalDate.TicksAbs, GenLocalDate.LongitudeForDate(thing)); } public static float DayPercent(Thing thing) { - return GenDate.DayPercent((long)GenLocalDate.TicksAbs, GenLocalDate.LongitudeForDate(thing)); + return GenDate.DayPercent(GenLocalDate.TicksAbs, GenLocalDate.LongitudeForDate(thing)); } public static int HourInteger(Thing thing) { - return GenDate.HourInteger((long)GenLocalDate.TicksAbs, GenLocalDate.LongitudeForDate(thing)); + return GenDate.HourInteger(GenLocalDate.TicksAbs, GenLocalDate.LongitudeForDate(thing)); } public static float HourFloat(Thing thing) { - return GenDate.HourFloat((long)GenLocalDate.TicksAbs, GenLocalDate.LongitudeForDate(thing)); + return GenDate.HourFloat(GenLocalDate.TicksAbs, GenLocalDate.LongitudeForDate(thing)); } public static int DayOfYear(int tile) { if (Current.ProgramState == ProgramState.Playing) { - return GenDate.DayOfYear((long)GenLocalDate.TicksAbs, Find.WorldGrid.LongLatOf(tile).x); + long absTicks = GenLocalDate.TicksAbs; + Vector2 vector = Find.WorldGrid.LongLatOf(tile); + return GenDate.DayOfYear(absTicks, vector.x); } return 0; } public static int HourOfDay(int tile) { - return GenDate.HourOfDay((long)GenLocalDate.TicksAbs, Find.WorldGrid.LongLatOf(tile).x); + long absTicks = GenLocalDate.TicksAbs; + Vector2 vector = Find.WorldGrid.LongLatOf(tile); + return GenDate.HourOfDay(absTicks, vector.x); } public static int DayOfTwelfth(int tile) { - return GenDate.DayOfTwelfth((long)GenLocalDate.TicksAbs, Find.WorldGrid.LongLatOf(tile).x); + long absTicks = GenLocalDate.TicksAbs; + Vector2 vector = Find.WorldGrid.LongLatOf(tile); + return GenDate.DayOfTwelfth(absTicks, vector.x); } public static Twelfth Twelfth(int tile) { - return GenDate.Twelfth((long)GenLocalDate.TicksAbs, Find.WorldGrid.LongLatOf(tile).x); + long absTicks = GenLocalDate.TicksAbs; + Vector2 vector = Find.WorldGrid.LongLatOf(tile); + return GenDate.Twelfth(absTicks, vector.x); } public static Season Season(int tile) { - return GenDate.Season((long)GenLocalDate.TicksAbs, Find.WorldGrid.LongLatOf(tile)); + return GenDate.Season(GenLocalDate.TicksAbs, Find.WorldGrid.LongLatOf(tile)); } public static int Year(int tile) @@ -171,37 +178,50 @@ public static int Year(int tile) { return 5500; } - return GenDate.Year((long)GenLocalDate.TicksAbs, Find.WorldGrid.LongLatOf(tile).x); + long absTicks = GenLocalDate.TicksAbs; + Vector2 vector = Find.WorldGrid.LongLatOf(tile); + return GenDate.Year(absTicks, vector.x); } public static int DayOfSeason(int tile) { - return GenDate.DayOfSeason((long)GenLocalDate.TicksAbs, Find.WorldGrid.LongLatOf(tile).x); + long absTicks = GenLocalDate.TicksAbs; + Vector2 vector = Find.WorldGrid.LongLatOf(tile); + return GenDate.DayOfSeason(absTicks, vector.x); } public static int DayOfQuadrum(int tile) { - return GenDate.DayOfQuadrum((long)GenLocalDate.TicksAbs, Find.WorldGrid.LongLatOf(tile).x); + long absTicks = GenLocalDate.TicksAbs; + Vector2 vector = Find.WorldGrid.LongLatOf(tile); + return GenDate.DayOfQuadrum(absTicks, vector.x); } public static float DayPercent(int tile) { - return GenDate.DayPercent((long)GenLocalDate.TicksAbs, Find.WorldGrid.LongLatOf(tile).x); + long absTicks = GenLocalDate.TicksAbs; + Vector2 vector = Find.WorldGrid.LongLatOf(tile); + return GenDate.DayPercent(absTicks, vector.x); } public static int HourInteger(int tile) { - return GenDate.HourInteger((long)GenLocalDate.TicksAbs, Find.WorldGrid.LongLatOf(tile).x); + long absTicks = GenLocalDate.TicksAbs; + Vector2 vector = Find.WorldGrid.LongLatOf(tile); + return GenDate.HourInteger(absTicks, vector.x); } public static float HourFloat(int tile) { - return GenDate.HourFloat((long)GenLocalDate.TicksAbs, Find.WorldGrid.LongLatOf(tile).x); + long absTicks = GenLocalDate.TicksAbs; + Vector2 vector = Find.WorldGrid.LongLatOf(tile); + return GenDate.HourFloat(absTicks, vector.x); } private static float LongitudeForDate(Thing thing) { - return GenLocalDate.LocationForDate(thing).x; + Vector2 vector = GenLocalDate.LocationForDate(thing); + return vector.x; } private static Vector2 LocationForDate(Thing thing) diff --git a/Assembly-CSharp/RimWorld/GenPlant.cs b/Assembly-CSharp/RimWorld/GenPlant.cs index 3cb409fd7..49979ed94 100644 --- a/Assembly-CSharp/RimWorld/GenPlant.cs +++ b/Assembly-CSharp/RimWorld/GenPlant.cs @@ -1,6 +1,6 @@ using System; using System.Collections.Generic; -using System.Diagnostics; +using System.Linq; using System.Text; using Verse; @@ -20,12 +20,12 @@ public static bool GrowthSeasonNow(IntVec3 c, Map map) return map.weatherManager.growthSeasonMemory.GrowthSeasonOutdoorsNow; } float temperature = c.GetTemperature(map); - return temperature > 0f && temperature < 58f; + return temperature > 0.0 && temperature < 58.0; } public static bool SnowAllowsPlanting(IntVec3 c, Map map) { - return c.GetSnowDepth(map) < 0.2f; + return c.GetSnowDepth(map) < 0.20000000298023224; } public static bool CanEverPlantAt(this ThingDef plantDef, IntVec3 c, Map map) @@ -76,47 +76,40 @@ public static bool CanEverPlantAt(this ThingDef plantDef, IntVec3 c, Map map) public static void LogPlantProportions() { Dictionary dictionary = new Dictionary(); - foreach (ThingDef current in Find.VisibleMap.Biome.AllWildPlants) + foreach (ThingDef allWildPlant in Find.VisibleMap.Biome.AllWildPlants) { - dictionary.Add(current, 0f); + dictionary.Add(allWildPlant, 0f); } float num = 0f; - foreach (IntVec3 current2 in Find.VisibleMap.AllCells) + foreach (IntVec3 allCell in Find.VisibleMap.AllCells) { - Plant plant = current2.GetPlant(Find.VisibleMap); + Plant plant = allCell.GetPlant(Find.VisibleMap); if (plant != null && dictionary.ContainsKey(plant.def)) { Dictionary dictionary2; - Dictionary expr_9B = dictionary2 = dictionary; - ThingDef key; - ThingDef expr_A5 = key = plant.def; - float num2 = dictionary2[key]; - expr_9B[expr_A5] = num2 + 1f; - num += 1f; + Dictionary obj = dictionary2 = dictionary; + ThingDef def; + ThingDef key = def = plant.def; + float num2 = dictionary2[def]; + obj[key] = (float)(num2 + 1.0); + num = (float)(num + 1.0); } } - foreach (ThingDef current3 in Find.VisibleMap.Biome.AllWildPlants) + foreach (ThingDef allWildPlant2 in Find.VisibleMap.Biome.AllWildPlants) { Dictionary dictionary3; - Dictionary expr_10B = dictionary3 = dictionary; - ThingDef key; - ThingDef expr_110 = key = current3; - float num2 = dictionary3[key]; - expr_10B[expr_110] = num2 / num; + Dictionary obj2 = dictionary3 = dictionary; + ThingDef def; + ThingDef key2 = def = allWildPlant2; + float num2 = dictionary3[def]; + obj2[key2] = num2 / num; } Dictionary dictionary4 = GenPlant.CalculateDesiredPlantProportions(Find.VisibleMap.Biome); StringBuilder stringBuilder = new StringBuilder(); stringBuilder.AppendLine("PLANT EXPECTED FOUND"); - foreach (ThingDef current4 in Find.VisibleMap.Biome.AllWildPlants) + foreach (ThingDef allWildPlant3 in Find.VisibleMap.Biome.AllWildPlants) { - stringBuilder.AppendLine(string.Concat(new string[] - { - current4.LabelCap, - " ", - dictionary4[current4].ToStringPercent(), - " ", - dictionary[current4].ToStringPercent() - })); + stringBuilder.AppendLine(allWildPlant3.LabelCap + " " + dictionary4[allWildPlant3].ToStringPercent() + " " + dictionary[allWildPlant3].ToStringPercent()); } Log.Message(stringBuilder.ToString()); } @@ -125,36 +118,38 @@ public static Dictionary CalculateDesiredPlantProportions(Biome { Dictionary dictionary = new Dictionary(); float num = 0f; - foreach (ThingDef current in DefDatabase.AllDefs) + foreach (ThingDef allDef in DefDatabase.AllDefs) { - if (current.plant != null) + if (allDef.plant != null) { - float num2 = biome.CommonalityOfPlant(current); - dictionary.Add(current, num2); + float num2 = biome.CommonalityOfPlant(allDef); + dictionary.Add(allDef, num2); num += num2; } } - foreach (ThingDef current2 in biome.AllWildPlants) + foreach (ThingDef allWildPlant in biome.AllWildPlants) { Dictionary dictionary2; - Dictionary expr_7C = dictionary2 = dictionary; + Dictionary obj = dictionary2 = dictionary; ThingDef key; - ThingDef expr_81 = key = current2; + ThingDef key2 = key = allWildPlant; float num3 = dictionary2[key]; - expr_7C[expr_81] = num3 / num; + obj[key2] = num3 / num; } return dictionary; } - [DebuggerHidden] public static IEnumerable ValidPlantTypesForGrowers(List sel) { - GenPlant.c__Iterator1A9 c__Iterator1A = new GenPlant.c__Iterator1A9(); - c__Iterator1A.sel = sel; - c__Iterator1A.<$>sel = sel; - GenPlant.c__Iterator1A9 expr_15 = c__Iterator1A; - expr_15.$PC = -2; - return expr_15; + foreach (ThingDef item in from def in DefDatabase.AllDefs + where def.category == ThingCategory.Plant + select def) + { + if (sel.TrueForAll((Predicate)((IPlantToGrowSettable x) => GenPlant.CanSowOnGrower(((_003CValidPlantTypesForGrowers_003Ec__Iterator1A9)/*Error near IL_0080: stateMachine*/)._003CplantDef_003E__1, x)))) + { + yield return item; + } + } } public static bool CanSowOnGrower(ThingDef plantDef, object obj) @@ -164,7 +159,11 @@ public static bool CanSowOnGrower(ThingDef plantDef, object obj) return plantDef.plant.sowTags.Contains("Ground"); } Thing thing = obj as Thing; - return thing != null && thing.def.building != null && plantDef.plant.sowTags.Contains(thing.def.building.sowTag); + if (thing != null && thing.def.building != null) + { + return plantDef.plant.sowTags.Contains(thing.def.building.sowTag); + } + return false; } public static Thing AdjacentSowBlocker(ThingDef plantDef, IntVec3 c, Map map) @@ -188,23 +187,23 @@ internal static void LogPlantData() { StringBuilder stringBuilder = new StringBuilder(); stringBuilder.AppendLine("All plant data"); - foreach (ThingDef current in DefDatabase.AllDefs) + foreach (ThingDef allDef in DefDatabase.AllDefs) { - if (current.plant != null) + if (allDef.plant != null) { - float num = current.plant.growDays * 2f; - float num2 = current.plant.lifespanFraction / (current.plant.lifespanFraction - 1f); + float num = (float)(allDef.plant.growDays * 2.0); + float num2 = (float)(allDef.plant.lifespanFraction / (allDef.plant.lifespanFraction - 1.0)); float num3 = num2 * num; - float num4 = (num3 + num * 0.399999976f) / current.plant.reproduceMtbDays; - stringBuilder.AppendLine(current.defName); - stringBuilder.AppendLine(" lifeSpanDays:\t\t\t\t" + current.plant.LifespanDays.ToString("F2")); - stringBuilder.AppendLine(" daysToGrown:\t\t\t\t" + current.plant.growDays); + float num4 = (float)((num3 + num * 0.39999997615814209) / allDef.plant.reproduceMtbDays); + stringBuilder.AppendLine(allDef.defName); + stringBuilder.AppendLine(" lifeSpanDays:\t\t\t\t" + allDef.plant.LifespanDays.ToString("F2")); + stringBuilder.AppendLine(" daysToGrown:\t\t\t\t" + allDef.plant.growDays); stringBuilder.AppendLine(" guess days to grown:\t\t" + num.ToString("F2")); stringBuilder.AppendLine(" grown days before death:\t" + num3.ToString("F2")); stringBuilder.AppendLine(" percent of life grown:\t" + num2.ToStringPercent()); - if (current.plant.reproduces) + if (allDef.plant.reproduces) { - stringBuilder.AppendLine(" MTB seed emits (days):\t" + current.plant.reproduceMtbDays.ToString("F2")); + stringBuilder.AppendLine(" MTB seed emits (days):\t" + allDef.plant.reproduceMtbDays.ToString("F2")); stringBuilder.AppendLine(" average seeds emitted:\t" + num4.ToString("F2")); } stringBuilder.AppendLine(); diff --git a/Assembly-CSharp/RimWorld/GenPlantReproduction.cs b/Assembly-CSharp/RimWorld/GenPlantReproduction.cs index 6d3544362..da974871d 100644 --- a/Assembly-CSharp/RimWorld/GenPlantReproduction.cs +++ b/Assembly-CSharp/RimWorld/GenPlantReproduction.cs @@ -9,7 +9,7 @@ public static class GenPlantReproduction { public static Plant TryReproduceFrom(IntVec3 source, ThingDef plantDef, SeedTargFindMode mode, Map map) { - IntVec3 dest; + IntVec3 dest = default(IntVec3); if (!GenPlantReproduction.TryFindReproductionDestination(source, plantDef, mode, map, out dest)) { return null; @@ -33,17 +33,23 @@ public static Plant TryReproduceInto(IntVec3 dest, ThingDef plantDef, Map map) public static bool TryFindReproductionDestination(IntVec3 source, ThingDef plantDef, SeedTargFindMode mode, Map map, out IntVec3 foundCell) { float radius = -1f; - if (mode == SeedTargFindMode.Reproduce) + switch (mode) + { + case SeedTargFindMode.Reproduce: { radius = plantDef.plant.reproduceRadius; + break; } - else if (mode == SeedTargFindMode.MapGenCluster) + case SeedTargFindMode.MapGenCluster: { radius = plantDef.plant.WildClusterRadiusActual; + break; } - else if (mode == SeedTargFindMode.MapEdge) + case SeedTargFindMode.MapEdge: { radius = 40f; + break; + } } int num = 0; int num2 = 0; @@ -69,16 +75,15 @@ public static bool TryFindReproductionDestination(IntVec3 source, ThingDef plant } float num4 = num3 * map.Biome.plantDensity; bool flag = (float)num > num4; - bool flag2 = (float)num > num4 * 1.25f; - if (flag2) + if ((float)num > num4 * 1.25) { foundCell = IntVec3.Invalid; return false; } - if (mode != SeedTargFindMode.MapGenCluster) + if (mode != 0) { BiomeDef curBiome = map.Biome; - float num5 = curBiome.AllWildPlants.Sum((ThingDef pd) => curBiome.CommonalityOfPlant(pd)); + float num5 = curBiome.AllWildPlants.Sum((Func)((ThingDef pd) => curBiome.CommonalityOfPlant(pd))); float num6 = curBiome.CommonalityOfPlant(plantDef) / num5; float num7 = curBiome.CommonalityOfPlant(plantDef) * plantDef.plant.wildCommonalityMaxFraction / num5; float num8 = num4 * num7; @@ -88,14 +93,33 @@ public static bool TryFindReproductionDestination(IntVec3 source, ThingDef plant return false; } float num9 = num4 * num6; - bool flag3 = (float)num2 < num9 * 0.5f; - if (flag && !flag3) + bool flag2 = (float)num2 < num9 * 0.5; + if (flag && !flag2) { foundCell = IntVec3.Invalid; return false; } } - Predicate validator = (IntVec3 c) => plantDef.CanEverPlantAt(c, map) && GenPlant.SnowAllowsPlanting(c, map) && source.InHorDistOf(c, radius) && GenSight.LineOfSight(source, c, map, true, null, 0, 0); + Predicate validator = (Predicate)delegate(IntVec3 c) + { + if (!plantDef.CanEverPlantAt(c, map)) + { + return false; + } + if (!GenPlant.SnowAllowsPlanting(c, map)) + { + return false; + } + if (!source.InHorDistOf(c, radius)) + { + return false; + } + if (!GenSight.LineOfSight(source, c, map, true, null, 0, 0)) + { + return false; + } + return true; + }; return CellFinder.TryFindRandomCellNear(source, map, Mathf.CeilToInt(radius), validator, out foundCell); } } diff --git a/Assembly-CSharp/RimWorld/GenStep_Animals.cs b/Assembly-CSharp/RimWorld/GenStep_Animals.cs index 2b9d99f7b..1cf031266 100644 --- a/Assembly-CSharp/RimWorld/GenStep_Animals.cs +++ b/Assembly-CSharp/RimWorld/GenStep_Animals.cs @@ -1,4 +1,3 @@ -using System; using Verse; namespace RimWorld @@ -8,17 +7,22 @@ public class GenStep_Animals : GenStep public override void Generate(Map map) { int num = 0; - while (!map.wildSpawner.AnimalEcosystemFull) + while (true) { - num++; - if (num >= 10000) + if (!map.wildSpawner.AnimalEcosystemFull) { - Log.Error("Too many iterations."); + num++; + if (num < 10000) + { + IntVec3 loc = RCellFinder.RandomAnimalSpawnCell_MapGen(map); + map.wildSpawner.SpawnRandomWildAnimalAt(loc); + continue; + } break; } - IntVec3 loc = RCellFinder.RandomAnimalSpawnCell_MapGen(map); - map.wildSpawner.SpawnRandomWildAnimalAt(loc); + return; } + Log.Error("Too many iterations."); } } } diff --git a/Assembly-CSharp/RimWorld/GenStep_ElevationFertility.cs b/Assembly-CSharp/RimWorld/GenStep_ElevationFertility.cs index c3db214de..90dd724ce 100644 --- a/Assembly-CSharp/RimWorld/GenStep_ElevationFertility.cs +++ b/Assembly-CSharp/RimWorld/GenStep_ElevationFertility.cs @@ -1,5 +1,4 @@ using RimWorld.Planet; -using System; using UnityEngine; using Verse; using Verse.Noise; @@ -16,76 +15,97 @@ public class GenStep_ElevationFertility : GenStep public override void Generate(Map map) { - NoiseRenderer.renderSize = new IntVec2(map.Size.x, map.Size.z); - ModuleBase moduleBase = new Perlin(0.020999999716877937, 2.0, 0.5, 6, Rand.Range(0, 2147483647), QualityMode.High); - moduleBase = new ScaleBias(0.5, 0.5, moduleBase); - NoiseDebugUI.StoreNoiseRender(moduleBase, "elev base"); + IntVec3 size = map.Size; + int x = size.x; + IntVec3 size2 = map.Size; + NoiseRenderer.renderSize = new IntVec2(x, size2.z); + ModuleBase input = new Perlin(0.020999999716877937, 2.0, 0.5, 6, Rand.Range(0, 2147483647), QualityMode.High); + input = new ScaleBias(0.5, 0.5, input); + NoiseDebugUI.StoreNoiseRender(input, "elev base"); float num = 1f; switch (map.TileInfo.hilliness) { case Hilliness.Flat: + { num = MapGenTuning.ElevationFactorFlat; break; + } case Hilliness.SmallHills: + { num = MapGenTuning.ElevationFactorSmallHills; break; + } case Hilliness.LargeHills: + { num = MapGenTuning.ElevationFactorLargeHills; break; + } case Hilliness.Mountainous: + { num = MapGenTuning.ElevationFactorMountains; break; + } case Hilliness.Impassable: + { num = MapGenTuning.ElevationFactorImpassableMountains; break; } - moduleBase = new Multiply(moduleBase, new Const((double)num)); - NoiseDebugUI.StoreNoiseRender(moduleBase, "elev world-factored"); - if (map.TileInfo.hilliness == Hilliness.Mountainous || map.TileInfo.hilliness == Hilliness.Impassable) + } + input = new Multiply(input, new Const((double)num)); + NoiseDebugUI.StoreNoiseRender(input, "elev world-factored"); + if (map.TileInfo.hilliness != Hilliness.Mountainous && map.TileInfo.hilliness != Hilliness.Impassable) + { + goto IL_029c; + } + IntVec3 size3 = map.Size; + ModuleBase input2 = new DistFromAxis((float)((float)size3.x * 0.41999998688697815)); + input2 = new Clamp(0.0, 1.0, input2); + input2 = new Invert(input2); + input2 = new ScaleBias(1.0, 1.0, input2); + Rot4 random; + while (true) + { + random = Rot4.Random; + if (!(random == Find.World.CoastDirectionAt(map.Tile))) + break; + } + if (random == Rot4.North) + { + input2 = new Rotate(0.0, 90.0, 0.0, input2); + IntVec3 size4 = map.Size; + input2 = new Translate(0.0, 0.0, (double)(-size4.z), input2); + } + else if (random == Rot4.East) + { + IntVec3 size5 = map.Size; + input2 = new Translate((double)(-size5.x), 0.0, 0.0, input2); + } + else if (random == Rot4.South) { - ModuleBase moduleBase2 = new DistFromAxis((float)map.Size.x * 0.42f); - moduleBase2 = new Clamp(0.0, 1.0, moduleBase2); - moduleBase2 = new Invert(moduleBase2); - moduleBase2 = new ScaleBias(1.0, 1.0, moduleBase2); - Rot4 random; - do - { - random = Rot4.Random; - } - while (random == Find.World.CoastDirectionAt(map.Tile)); - if (random == Rot4.North) - { - moduleBase2 = new Rotate(0.0, 90.0, 0.0, moduleBase2); - moduleBase2 = new Translate(0.0, 0.0, (double)(-(double)map.Size.z), moduleBase2); - } - else if (random == Rot4.East) - { - moduleBase2 = new Translate((double)(-(double)map.Size.x), 0.0, 0.0, moduleBase2); - } - else if (random == Rot4.South) - { - moduleBase2 = new Rotate(0.0, 90.0, 0.0, moduleBase2); - } - else if (random == Rot4.West) - { - } - NoiseDebugUI.StoreNoiseRender(moduleBase2, "mountain"); - moduleBase = new Add(moduleBase, moduleBase2); - NoiseDebugUI.StoreNoiseRender(moduleBase, "elev + mountain"); + input2 = new Rotate(0.0, 90.0, 0.0, input2); } - float b = (!map.TileInfo.WaterCovered) ? 3.40282347E+38f : 0f; + else if (!(random == Rot4.West)) + goto IL_027e; + goto IL_027e; + IL_027e: + NoiseDebugUI.StoreNoiseRender(input2, "mountain"); + input = new Add(input, input2); + NoiseDebugUI.StoreNoiseRender(input, "elev + mountain"); + goto IL_029c; + IL_029c: + float b = (float)((!map.TileInfo.WaterCovered) ? 3.4028234663852886E+38 : 0.0); MapGenFloatGrid mapGenFloatGrid = MapGenerator.FloatGridNamed("Elevation", map); - foreach (IntVec3 current in map.AllCells) + foreach (IntVec3 allCell in map.AllCells) { - mapGenFloatGrid[current] = Mathf.Min(moduleBase.GetValue(current), b); + mapGenFloatGrid[allCell] = Mathf.Min(input.GetValue(allCell), b); } - ModuleBase moduleBase3 = new Perlin(0.020999999716877937, 2.0, 0.5, 6, Rand.Range(0, 2147483647), QualityMode.High); - moduleBase3 = new ScaleBias(0.5, 0.5, moduleBase3); - NoiseDebugUI.StoreNoiseRender(moduleBase3, "noiseFert base"); + ModuleBase input3 = new Perlin(0.020999999716877937, 2.0, 0.5, 6, Rand.Range(0, 2147483647), QualityMode.High); + input3 = new ScaleBias(0.5, 0.5, input3); + NoiseDebugUI.StoreNoiseRender(input3, "noiseFert base"); MapGenFloatGrid mapGenFloatGrid2 = MapGenerator.FloatGridNamed("Fertility", map); - foreach (IntVec3 current2 in map.AllCells) + foreach (IntVec3 allCell2 in map.AllCells) { - mapGenFloatGrid2[current2] = moduleBase3.GetValue(current2); + mapGenFloatGrid2[allCell2] = input3.GetValue(allCell2); } } } diff --git a/Assembly-CSharp/RimWorld/GenStep_FactionBase.cs b/Assembly-CSharp/RimWorld/GenStep_FactionBase.cs index 00520186e..31f6463b5 100644 --- a/Assembly-CSharp/RimWorld/GenStep_FactionBase.cs +++ b/Assembly-CSharp/RimWorld/GenStep_FactionBase.cs @@ -1,5 +1,4 @@ using RimWorld.BaseGen; -using System; using Verse; namespace RimWorld @@ -26,9 +25,17 @@ protected override bool CanScatterAt(IntVec3 c, Map map) { return false; } - int min = GenStep_FactionBase.FactionBaseSizeRange.min; + IntRange factionBaseSizeRange = GenStep_FactionBase.FactionBaseSizeRange; + int min = factionBaseSizeRange.min; CellRect cellRect = new CellRect(c.x - min / 2, c.z - min / 2, min, min); - return cellRect.FullyContainedWithin(new CellRect(0, 0, map.Size.x, map.Size.z)); + IntVec3 size = map.Size; + int x = size.x; + IntVec3 size2 = map.Size; + if (!cellRect.FullyContainedWithin(new CellRect(0, 0, x, size2.z))) + { + return false; + } + return true; } protected override void ScatterAt(IntVec3 c, Map map, int stackCount = 1) @@ -36,24 +43,18 @@ protected override void ScatterAt(IntVec3 c, Map map, int stackCount = 1) int randomInRange = GenStep_FactionBase.FactionBaseSizeRange.RandomInRange; int randomInRange2 = GenStep_FactionBase.FactionBaseSizeRange.RandomInRange; CellRect rect = new CellRect(c.x - randomInRange / 2, c.z - randomInRange2 / 2, randomInRange, randomInRange2); - Faction faction; - if (map.ParentFaction == null || map.ParentFaction == Faction.OfPlayer) - { - faction = Find.FactionManager.RandomEnemyFaction(false, false, true); - } - else - { - faction = map.ParentFaction; - } + Faction faction = (map.ParentFaction != null && map.ParentFaction != Faction.OfPlayer) ? map.ParentFaction : Find.FactionManager.RandomEnemyFaction(false, false, true); rect.ClipInsideMap(map); - ResolveParams resolveParams = default(ResolveParams); - resolveParams.rect = rect; - resolveParams.faction = faction; - BaseGen.globalSettings.map = map; - BaseGen.globalSettings.minBuildings = 1; - BaseGen.globalSettings.minBarracks = 1; - BaseGen.symbolStack.Push("factionBase", resolveParams); - BaseGen.Generate(); + ResolveParams resolveParams = new ResolveParams + { + rect = rect, + faction = faction + }; + RimWorld.BaseGen.BaseGen.globalSettings.map = map; + RimWorld.BaseGen.BaseGen.globalSettings.minBuildings = 1; + RimWorld.BaseGen.BaseGen.globalSettings.minBarracks = 1; + RimWorld.BaseGen.BaseGen.symbolStack.Push("factionBase", resolveParams); + RimWorld.BaseGen.BaseGen.Generate(); } } } diff --git a/Assembly-CSharp/RimWorld/GenStep_FindPlayerStartSpot.cs b/Assembly-CSharp/RimWorld/GenStep_FindPlayerStartSpot.cs index 88a48d679..dcd2dd63b 100644 --- a/Assembly-CSharp/RimWorld/GenStep_FindPlayerStartSpot.cs +++ b/Assembly-CSharp/RimWorld/GenStep_FindPlayerStartSpot.cs @@ -12,7 +12,7 @@ public override void Generate(Map map) DeepProfiler.Start("RebuildAllRegions"); map.regionAndRoomUpdater.RebuildAllRegionsAndRooms(); DeepProfiler.End(); - MapGenerator.PlayerStartSpot = CellFinderLoose.TryFindCentralCell(map, 7, 10, (IntVec3 x) => !x.Roofed(map)); + MapGenerator.PlayerStartSpot = CellFinderLoose.TryFindCentralCell(map, 7, 10, (Predicate)((IntVec3 x) => !x.Roofed(map))); } } } diff --git a/Assembly-CSharp/RimWorld/GenStep_Fog.cs b/Assembly-CSharp/RimWorld/GenStep_Fog.cs index 63cb42dae..06bce7bc5 100644 --- a/Assembly-CSharp/RimWorld/GenStep_Fog.cs +++ b/Assembly-CSharp/RimWorld/GenStep_Fog.cs @@ -1,4 +1,3 @@ -using System; using System.Collections.Generic; using Verse; diff --git a/Assembly-CSharp/RimWorld/GenStep_ItemStash.cs b/Assembly-CSharp/RimWorld/GenStep_ItemStash.cs index 210847fab..4d6953dd7 100644 --- a/Assembly-CSharp/RimWorld/GenStep_ItemStash.cs +++ b/Assembly-CSharp/RimWorld/GenStep_ItemStash.cs @@ -1,6 +1,5 @@ using RimWorld.BaseGen; using RimWorld.Planet; -using System; using System.Collections.Generic; using Verse; @@ -31,11 +30,12 @@ protected override bool CanScatterAt(IntVec3 c, Map map) CellRect.CellRectIterator iterator = CellRect.CenteredOn(c, 3).GetIterator(); while (!iterator.Done()) { - if (!iterator.Current.InBounds(map) || iterator.Current.GetEdifice(map) != null) + if (iterator.Current.InBounds(map) && iterator.Current.GetEdifice(map) == null) { - return false; + iterator.MoveNext(); + continue; } - iterator.MoveNext(); + return false; } return true; } @@ -43,10 +43,12 @@ protected override bool CanScatterAt(IntVec3 c, Map map) protected override void ScatterAt(IntVec3 loc, Map map, int count = 1) { CellRect cellRect = CellRect.CenteredOn(loc, 3).ClipInsideMap(map); - ResolveParams resolveParams = default(ResolveParams); - resolveParams.rect = cellRect; - resolveParams.faction = map.ParentFaction; - ItemStashContentsComp component = map.info.parent.GetComponent(); + ResolveParams resolveParams = new ResolveParams + { + rect = cellRect, + faction = map.ParentFaction + }; + ItemStashContentsComp component = ((WorldObject)map.info.parent).GetComponent(); if (component != null && component.contents.Any) { resolveParams.stockpileConcreteContents = component.contents; @@ -56,13 +58,13 @@ protected override void ScatterAt(IntVec3 loc, Map map, int count = 1) resolveParams.stockpileMarketValue = new float?(this.totalValueRange.RandomInRange); if (this.itemCollectionGeneratorDefs != null) { - resolveParams.itemCollectionGeneratorDef = this.itemCollectionGeneratorDefs.RandomElement(); + resolveParams.itemCollectionGeneratorDef = this.itemCollectionGeneratorDefs.RandomElement(); } } - BaseGen.globalSettings.map = map; - BaseGen.symbolStack.Push("storage", resolveParams); - BaseGen.Generate(); - MapGenerator.SetVar("RectOfInterest", cellRect); + RimWorld.BaseGen.BaseGen.globalSettings.map = map; + RimWorld.BaseGen.BaseGen.symbolStack.Push("storage", resolveParams); + RimWorld.BaseGen.BaseGen.Generate(); + MapGenerator.SetVar("RectOfInterest", cellRect); } } } diff --git a/Assembly-CSharp/RimWorld/GenStep_ManhunterPack.cs b/Assembly-CSharp/RimWorld/GenStep_ManhunterPack.cs index 1a068c4d6..60973fa87 100644 --- a/Assembly-CSharp/RimWorld/GenStep_ManhunterPack.cs +++ b/Assembly-CSharp/RimWorld/GenStep_ManhunterPack.cs @@ -13,21 +13,19 @@ public class GenStep_ManhunterPack : GenStep public override void Generate(Map map) { TraverseParms traverseParams = TraverseParms.For(TraverseMode.NoPassClosedDoors, Danger.Deadly, false); - IntVec3 root; - if (RCellFinder.TryFindRandomCellNearTheCenterOfTheMapWith((IntVec3 x) => x.Standable(map) && !x.Fogged(map) && map.reachability.CanReachMapEdge(x, traverseParams) && x.GetRoom(map, RegionType.Set_Passable).CellCount >= this.MinRoomCells, map, out root)) + IntVec3 root = default(IntVec3); + if (RCellFinder.TryFindRandomCellNearTheCenterOfTheMapWith((Predicate)((IntVec3 x) => x.Standable(map) && !x.Fogged(map) && map.reachability.CanReachMapEdge(x, traverseParams) && x.GetRoom(map, RegionType.Set_Passable).CellCount >= this.MinRoomCells), map, out root)) { float randomInRange = this.pointsRange.RandomInRange; - PawnKindDef animalKind; + PawnKindDef animalKind = default(PawnKindDef); if (!ManhunterPackIncidentUtility.TryFindManhunterAnimalKind(randomInRange, map.Tile, out animalKind) && !ManhunterPackIncidentUtility.TryFindManhunterAnimalKind(randomInRange, -1, out animalKind)) - { return; - } List list = ManhunterPackIncidentUtility.GenerateAnimals(animalKind, map.Tile, randomInRange); for (int i = 0; i < list.Count; i++) { IntVec3 loc = CellFinder.RandomSpawnCellForPawnNear(root, map, 10); GenSpawn.Spawn(list[i], loc, map, Rot4.Random, false); - list[i].mindState.mentalStateHandler.TryStartMentalState(MentalStateDefOf.ManhunterPermanent, null, false, false, null); + list[i].mindState.mentalStateHandler.TryStartMentalState(MentalStateDefOf.ManhunterPermanent, (string)null, false, false, null); } } } diff --git a/Assembly-CSharp/RimWorld/GenStep_Outpost.cs b/Assembly-CSharp/RimWorld/GenStep_Outpost.cs index fc94d9679..bee8e9716 100644 --- a/Assembly-CSharp/RimWorld/GenStep_Outpost.cs +++ b/Assembly-CSharp/RimWorld/GenStep_Outpost.cs @@ -13,45 +13,52 @@ public class GenStep_Outpost : GenStep public override void Generate(Map map) { - CellRect rectToDefend; + CellRect rectToDefend = default(CellRect); if (!MapGenerator.TryGetVar("RectOfInterest", out rectToDefend)) { rectToDefend = CellRect.SingleCell(map.Center); } - Faction faction; - if (map.ParentFaction == null || map.ParentFaction == Faction.OfPlayer) + Faction faction = (map.ParentFaction != null && map.ParentFaction != Faction.OfPlayer) ? map.ParentFaction : Find.FactionManager.RandomEnemyFaction(false, false, true); + ResolveParams resolveParams = new ResolveParams { - faction = Find.FactionManager.RandomEnemyFaction(false, false, true); - } - else - { - faction = map.ParentFaction; - } - ResolveParams resolveParams = default(ResolveParams); - resolveParams.rect = this.GetOutpostRect(rectToDefend, map); - resolveParams.faction = faction; - resolveParams.edgeDefenseWidth = new int?(2); - resolveParams.edgeDefenseTurretsCount = new int?(Rand.RangeInclusive(0, 1)); - resolveParams.edgeDefenseMortarsCount = new int?(0); - resolveParams.factionBasePawnGroupPointsFactor = new float?(0.4f); - BaseGen.globalSettings.map = map; - BaseGen.globalSettings.minBuildings = 1; - BaseGen.globalSettings.minBarracks = 1; - BaseGen.symbolStack.Push("factionBase", resolveParams); - BaseGen.Generate(); + rect = this.GetOutpostRect(rectToDefend, map), + faction = faction, + edgeDefenseWidth = new int?(2), + edgeDefenseTurretsCount = new int?(Rand.RangeInclusive(0, 1)), + edgeDefenseMortarsCount = new int?(0), + factionBasePawnGroupPointsFactor = new float?(0.4f) + }; + RimWorld.BaseGen.BaseGen.globalSettings.map = map; + RimWorld.BaseGen.BaseGen.globalSettings.minBuildings = 1; + RimWorld.BaseGen.BaseGen.globalSettings.minBarracks = 1; + RimWorld.BaseGen.BaseGen.symbolStack.Push("factionBase", resolveParams); + RimWorld.BaseGen.BaseGen.Generate(); } private CellRect GetOutpostRect(CellRect rectToDefend, Map map) { - GenStep_Outpost.possibleRects.Add(new CellRect(rectToDefend.minX - 1 - 16, rectToDefend.CenterCell.z - 8, 16, 16)); - GenStep_Outpost.possibleRects.Add(new CellRect(rectToDefend.maxX + 1, rectToDefend.CenterCell.z - 8, 16, 16)); - GenStep_Outpost.possibleRects.Add(new CellRect(rectToDefend.CenterCell.x - 8, rectToDefend.minZ - 1 - 16, 16, 16)); - GenStep_Outpost.possibleRects.Add(new CellRect(rectToDefend.CenterCell.x - 8, rectToDefend.maxZ + 1, 16, 16)); - CellRect mapRect = new CellRect(0, 0, map.Size.x, map.Size.z); - GenStep_Outpost.possibleRects.RemoveAll((CellRect x) => !x.FullyContainedWithin(mapRect)); - if (GenStep_Outpost.possibleRects.Any()) + List obj = GenStep_Outpost.possibleRects; + int minX = rectToDefend.minX - 1 - 16; + IntVec3 centerCell = rectToDefend.CenterCell; + obj.Add(new CellRect(minX, centerCell.z - 8, 16, 16)); + List obj2 = GenStep_Outpost.possibleRects; + int minX2 = rectToDefend.maxX + 1; + IntVec3 centerCell2 = rectToDefend.CenterCell; + obj2.Add(new CellRect(minX2, centerCell2.z - 8, 16, 16)); + List obj3 = GenStep_Outpost.possibleRects; + IntVec3 centerCell3 = rectToDefend.CenterCell; + obj3.Add(new CellRect(centerCell3.x - 8, rectToDefend.minZ - 1 - 16, 16, 16)); + List obj4 = GenStep_Outpost.possibleRects; + IntVec3 centerCell4 = rectToDefend.CenterCell; + obj4.Add(new CellRect(centerCell4.x - 8, rectToDefend.maxZ + 1, 16, 16)); + IntVec3 size = map.Size; + int x2 = size.x; + IntVec3 size2 = map.Size; + CellRect mapRect = new CellRect(0, 0, x2, size2.z); + GenStep_Outpost.possibleRects.RemoveAll((Predicate)((CellRect x) => !x.FullyContainedWithin(mapRect))); + if (GenStep_Outpost.possibleRects.Any()) { - return GenStep_Outpost.possibleRects.RandomElement(); + return GenStep_Outpost.possibleRects.RandomElement(); } return rectToDefend; } diff --git a/Assembly-CSharp/RimWorld/GenStep_Plants.cs b/Assembly-CSharp/RimWorld/GenStep_Plants.cs index a2b40353a..ef5bb2f47 100644 --- a/Assembly-CSharp/RimWorld/GenStep_Plants.cs +++ b/Assembly-CSharp/RimWorld/GenStep_Plants.cs @@ -20,50 +20,51 @@ public class GenStep_Plants : GenStep public override void Generate(Map map) { - GenStep_Plants.c__AnonStorey316 c__AnonStorey = new GenStep_Plants.c__AnonStorey316(); - c__AnonStorey.map = map; - c__AnonStorey.map.regionAndRoomUpdater.Enabled = false; - List list = c__AnonStorey.map.Biome.AllWildPlants.ToList(); + map.regionAndRoomUpdater.Enabled = false; + List list = map.Biome.AllWildPlants.ToList(); for (int i = 0; i < list.Count; i++) { GenStep_Plants.numExtant.Add(list[i], 0); } - GenStep_Plants.desiredProportions = GenPlant.CalculateDesiredPlantProportions(c__AnonStorey.map.Biome); - float num = c__AnonStorey.map.Biome.plantDensity * c__AnonStorey.map.gameConditionManager.AggregatePlantDensityFactor(); - foreach (IntVec3 c in c__AnonStorey.map.AllCells.InRandomOrder(null)) + GenStep_Plants.desiredProportions = GenPlant.CalculateDesiredPlantProportions(map.Biome); + float num = map.Biome.plantDensity * map.gameConditionManager.AggregatePlantDensityFactor(); + using (IEnumerator enumerator = map.AllCells.InRandomOrder(null).GetEnumerator()) { - if (c.GetEdifice(c__AnonStorey.map) == null && c.GetCover(c__AnonStorey.map) == null) + IntVec3 c; + while (enumerator.MoveNext()) { - float num2 = c__AnonStorey.map.fertilityGrid.FertilityAt(c); - float num3 = num2 * num; - if (Rand.Value < num3) + c = enumerator.Current; + if (c.GetEdifice(map) == null && c.GetCover(map) == null) { - IEnumerable source = from def in list - where def.CanEverPlantAt(c, c__AnonStorey.map) - select def; - if (source.Any()) + float num2 = map.fertilityGrid.FertilityAt(c); + float num3 = num2 * num; + if (!(Rand.Value >= num3)) { - ThingDef thingDef = source.RandomElementByWeight((ThingDef x) => GenStep_Plants.PlantChoiceWeight(x, c__AnonStorey.map)); - int randomInRange = thingDef.plant.wildClusterSizeRange.RandomInRange; - for (int j = 0; j < randomInRange; j++) + IEnumerable source = from def in list + where def.CanEverPlantAt(c, map) + select def; + if (source.Any()) { - IntVec3 c2; - if (j == 0) + ThingDef thingDef = source.RandomElementByWeight((Func)((ThingDef x) => GenStep_Plants.PlantChoiceWeight(x, map))); + int randomInRange = thingDef.plant.wildClusterSizeRange.RandomInRange; + for (int num4 = 0; num4 < randomInRange; num4++) { - c2 = c; + IntVec3 loc = default(IntVec3); + if (num4 == 0) + { + loc = c; + } + else if (!GenPlantReproduction.TryFindReproductionDestination(c, thingDef, SeedTargFindMode.MapGenCluster, map, out loc)) + break; + Plant plant = (Plant)ThingMaker.MakeThing(thingDef, null); + plant.Growth = Rand.Range(0.07f, 1f); + if (plant.def.plant.LimitedLifespan) + { + plant.Age = Rand.Range(0, Mathf.Max(plant.def.plant.LifespanTicks - 50, 0)); + } + GenSpawn.Spawn(plant, loc, map); + GenStep_Plants.RecordAdded(thingDef); } - else if (!GenPlantReproduction.TryFindReproductionDestination(c, thingDef, SeedTargFindMode.MapGenCluster, c__AnonStorey.map, out c2)) - { - break; - } - Plant plant = (Plant)ThingMaker.MakeThing(thingDef, null); - plant.Growth = Rand.Range(0.07f, 1f); - if (plant.def.plant.LimitedLifespan) - { - plant.Age = Rand.Range(0, Mathf.Max(plant.def.plant.LifespanTicks - 50, 0)); - } - GenSpawn.Spawn(plant, c2, c__AnonStorey.map); - GenStep_Plants.RecordAdded(thingDef); } } } @@ -72,7 +73,7 @@ where def.CanEverPlantAt(c, c__AnonStorey.map) GenStep_Plants.numExtant.Clear(); GenStep_Plants.desiredProportions.Clear(); GenStep_Plants.totalExtant = 0; - c__AnonStorey.map.regionAndRoomUpdater.Enabled = true; + map.regionAndRoomUpdater.Enabled = true; } private static float PlantChoiceWeight(ThingDef def, Map map) @@ -81,9 +82,9 @@ private static float PlantChoiceWeight(ThingDef def, Map map) if (GenStep_Plants.totalExtant > 100) { float num2 = (float)GenStep_Plants.numExtant[def] / (float)GenStep_Plants.totalExtant; - if (num2 < GenStep_Plants.desiredProportions[def] * 0.8f) + if (num2 < GenStep_Plants.desiredProportions[def] * 0.800000011920929) { - num *= 4f; + num = (float)(num * 4.0); } } return num / def.plant.wildClusterSizeRange.Average; @@ -93,9 +94,11 @@ private static void RecordAdded(ThingDef plantDef) { GenStep_Plants.totalExtant++; Dictionary dictionary; - Dictionary expr_11 = dictionary = GenStep_Plants.numExtant; - int num = dictionary[plantDef]; - expr_11[plantDef] = num + 1; + Dictionary obj = dictionary = GenStep_Plants.numExtant; + ThingDef key; + ThingDef key2 = key = plantDef; + int num = dictionary[key]; + obj[key2] = num + 1; } } } diff --git a/Assembly-CSharp/RimWorld/GenStep_Power.cs b/Assembly-CSharp/RimWorld/GenStep_Power.cs index 4ddf2038f..38e5cb919 100644 --- a/Assembly-CSharp/RimWorld/GenStep_Power.cs +++ b/Assembly-CSharp/RimWorld/GenStep_Power.cs @@ -67,17 +67,20 @@ private void EnsureBatteriesConnectedAndMakeSense(Map map) if (powerNet == null || !this.HasAnyPowerGenerator(powerNet)) { map.powerNetManager.UpdatePowerNetsAndConnections_First(); - PowerNet powerNet2; - IntVec3 dest; - Building building2; - if (this.TryFindClosestReachableNet(compPowerBattery.parent.Position, (PowerNet x) => this.HasAnyPowerGenerator(x), map, out powerNet2, out dest)) + PowerNet powerNet2 = default(PowerNet); + IntVec3 dest = default(IntVec3); + Building building2 = default(Building); + if (this.TryFindClosestReachableNet(compPowerBattery.parent.Position, (Predicate)((PowerNet x) => this.HasAnyPowerGenerator(x)), map, out powerNet2, out dest)) { map.floodFiller.ReconstructLastFloodFillPath(dest, this.tmpCells); if (this.canSpawnPowerGenerators) { int count = this.tmpCells.Count; - float chance = Mathf.InverseLerp((float)GenStep_Power.MaxDistanceBetweenBatteryAndTransmitter.min, (float)GenStep_Power.MaxDistanceBetweenBatteryAndTransmitter.max, (float)count); - Building building; + IntRange maxDistanceBetweenBatteryAndTransmitter = GenStep_Power.MaxDistanceBetweenBatteryAndTransmitter; + float a = (float)maxDistanceBetweenBatteryAndTransmitter.min; + IntRange maxDistanceBetweenBatteryAndTransmitter2 = GenStep_Power.MaxDistanceBetweenBatteryAndTransmitter; + float chance = Mathf.InverseLerp(a, (float)maxDistanceBetweenBatteryAndTransmitter2.max, (float)count); + Building building = default(Building); if (Rand.Chance(chance) && this.TrySpawnPowerGeneratorNear(compPowerBattery.parent.Position, map, compPowerBattery.parent.Faction, out building)) { this.SpawnTransmitters(compPowerBattery.parent.Position, building.Position, map, compPowerBattery.parent.Faction); @@ -115,10 +118,10 @@ private void EnsurePowerUsersConnected(Map map) else { map.powerNetManager.UpdatePowerNetsAndConnections_First(); - PowerNet powerNet2; - IntVec3 dest; - Building building; - if (this.TryFindClosestReachableNet(powerComp.parent.Position, (PowerNet x) => x.CurrentEnergyGainRate() - powerComp.Props.basePowerConsumption * CompPower.WattsToWattDaysPerTick > 1E-07f, map, out powerNet2, out dest)) + PowerNet powerNet2 = default(PowerNet); + IntVec3 dest = default(IntVec3); + Building building = default(Building); + if (this.TryFindClosestReachableNet(powerComp.parent.Position, (Predicate)((PowerNet x) => x.CurrentEnergyGainRate() - powerComp.Props.basePowerConsumption * CompPower.WattsToWattDaysPerTick > 1.0000000116860974E-07), map, out powerNet2, out dest)) { map.floodFiller.ReconstructLastFloodFillPath(dest, this.tmpCells); bool flag = false; @@ -136,7 +139,7 @@ private void EnsurePowerUsersConnected(Map map) { this.TryTurnOnImmediately(powerComp, map); } - else if (this.TryFindClosestReachableNet(powerComp.parent.Position, (PowerNet x) => x.CurrentStoredEnergy() > 1E-07f, map, out powerNet2, out dest)) + else if (this.TryFindClosestReachableNet(powerComp.parent.Position, (Predicate)((PowerNet x) => x.CurrentStoredEnergy() > 1.0000000116860974E-07), map, out powerNet2, out dest)) { map.floodFiller.ReconstructLastFloodFillPath(dest, this.tmpCells); this.SpawnTransmitters(this.tmpCells, map, this.tmpThings[i].Faction); @@ -144,7 +147,7 @@ private void EnsurePowerUsersConnected(Map map) else if (this.canSpawnBatteries && this.TrySpawnBatteryNear(this.tmpThings[i].Position, map, this.tmpThings[i].Faction, out building)) { this.SpawnTransmitters(this.tmpThings[i].Position, building.Position, map, this.tmpThings[i].Faction); - if (building.GetComp().StoredEnergy > 0f) + if (building.GetComp().StoredEnergy > 0.0) { this.TryTurnOnImmediately(powerComp, map); } @@ -166,9 +169,9 @@ private void EnsureGeneratorsConnectedAndMakeSense(Map map) if (powerNet == null || !this.HasAnyPowerUser(powerNet)) { map.powerNetManager.UpdatePowerNetsAndConnections_First(); - PowerNet powerNet2; - IntVec3 dest; - if (this.TryFindClosestReachableNet(this.tmpThings[i].Position, (PowerNet x) => this.HasAnyPowerUser(x), map, out powerNet2, out dest)) + PowerNet powerNet2 = default(PowerNet); + IntVec3 dest = default(IntVec3); + if (this.TryFindClosestReachableNet(this.tmpThings[i].Position, (Predicate)((PowerNet x) => this.HasAnyPowerUser(x)), map, out powerNet2, out dest)) { map.floodFiller.ReconstructLastFloodFillPath(dest, this.tmpCells); this.SpawnTransmitters(this.tmpCells, map, this.tmpThings[i].Faction); @@ -181,7 +184,7 @@ private void EnsureGeneratorsConnectedAndMakeSense(Map map) private bool IsPowerUser(Thing thing) { CompPowerTrader compPowerTrader = thing.TryGetComp(); - return compPowerTrader != null && (compPowerTrader.PowerOutput < 0f || (!compPowerTrader.PowerOn && compPowerTrader.Props.basePowerConsumption > 0f)); + return compPowerTrader != null && (compPowerTrader.PowerOutput < 0.0 || (!compPowerTrader.PowerOn && compPowerTrader.Props.basePowerConsumption > 0.0)); } private bool IsPowerGenerator(Thing thing) @@ -191,7 +194,7 @@ private bool IsPowerGenerator(Thing thing) return true; } CompPowerTrader compPowerTrader = thing.TryGetComp(); - return compPowerTrader != null && (compPowerTrader.PowerOutput > 0f || (!compPowerTrader.PowerOn && compPowerTrader.Props.basePowerConsumption < 0f)); + return compPowerTrader != null && (compPowerTrader.PowerOutput > 0.0 || (!compPowerTrader.PowerOn && compPowerTrader.Props.basePowerConsumption < 0.0)); } private bool HasAnyPowerGenerator(PowerNet net) @@ -225,7 +228,7 @@ private bool TryFindClosestReachableNet(IntVec3 root, Predicate predic this.tmpPowerNetPredicateResults.Clear(); PowerNet foundNetLocal = null; IntVec3 closestTransmitterLocal = IntVec3.Invalid; - map.floodFiller.FloodFill(root, (IntVec3 x) => this.EverPossibleToTransmitPowerAt(x, map), delegate(IntVec3 x) + map.floodFiller.FloodFill(root, (Predicate)((IntVec3 x) => this.EverPossibleToTransmitPowerAt(x, map)), (Func)delegate(IntVec3 x) { Building transmitter = x.GetTransmitter(map); PowerNet powerNet = (transmitter == null) ? null : transmitter.GetComp().PowerNet; @@ -233,7 +236,7 @@ private bool TryFindClosestReachableNet(IntVec3 root, Predicate predic { return false; } - bool flag; + bool flag = default(bool); if (!this.tmpPowerNetPredicateResults.TryGetValue(powerNet, out flag)) { flag = predicate(powerNet); @@ -274,7 +277,7 @@ private void SpawnTransmitters(List cells, Map map, Faction faction) private void SpawnTransmitters(IntVec3 start, IntVec3 end, Map map, Faction faction) { bool foundPath = false; - map.floodFiller.FloodFill(start, (IntVec3 x) => this.EverPossibleToTransmitPowerAt(x, map), delegate(IntVec3 x) + map.floodFiller.FloodFill(start, (Predicate)((IntVec3 x) => this.EverPossibleToTransmitPowerAt(x, map)), (Func)delegate(IntVec3 x) { if (x == end) { @@ -293,28 +296,29 @@ private void SpawnTransmitters(IntVec3 start, IntVec3 end, Map map, Faction fact private bool TrySpawnPowerTransmittingBuildingNear(IntVec3 position, Map map, Faction faction, ThingDef def, out Building newBuilding) { TraverseParms traverseParams = TraverseParms.For(TraverseMode.PassAllDestroyableThings, Danger.Deadly, false); - IntVec3 loc; - if (RCellFinder.TryFindRandomCellNearWith(position, delegate(IntVec3 x) + IntVec3 loc = default(IntVec3); + if (RCellFinder.TryFindRandomCellNearWith(position, (Predicate)delegate(IntVec3 x) { - if (!x.Standable(map) || x.Roofed(map) || !this.EverPossibleToTransmitPowerAt(x, map)) + if (x.Standable(map) && !x.Roofed(map) && this.EverPossibleToTransmitPowerAt(x, map)) { - return false; - } - if (!map.reachability.CanReach(position, x, PathEndMode.OnCell, traverseParams)) - { - return false; - } - CellRect.CellRectIterator iterator = GenAdj.OccupiedRect(x, Rot4.North, def.size).GetIterator(); - while (!iterator.Done()) - { - IntVec3 current = iterator.Current; - if (!current.InBounds(map) || current.Roofed(map) || current.GetEdifice(map) != null || current.GetFirstItem(map) != null || current.GetTransmitter(map) != null) + if (!map.reachability.CanReach(position, x, PathEndMode.OnCell, traverseParams)) { return false; } - iterator.MoveNext(); + CellRect.CellRectIterator iterator = GenAdj.OccupiedRect(x, Rot4.North, def.size).GetIterator(); + while (!iterator.Done()) + { + IntVec3 current = iterator.Current; + if (current.InBounds(map) && !current.Roofed(map) && current.GetEdifice(map) == null && current.GetFirstItem(map) == null && current.GetTransmitter(map) == null) + { + iterator.MoveNext(); + continue; + } + return false; + } + return true; } - return true; + return false; }, map, out loc, 8)) { newBuilding = (Building)GenSpawn.Spawn(ThingMaker.MakeThing(def, null), loc, map, Rot4.North, false); @@ -356,15 +360,15 @@ private bool TrySpawnPowerGeneratorAndBatteryIfCanAndConnect(Thing forThing, Map IntVec3 position = forThing.Position; if (this.canSpawnBatteries) { - float chance = (!(forThing is Building_Turret)) ? 0.1f : 1f; - Building building; + float chance = (float)((!(forThing is Building_Turret)) ? 0.10000000149011612 : 1.0); + Building building = default(Building); if (Rand.Chance(chance) && this.TrySpawnBatteryNear(forThing.Position, map, forThing.Faction, out building)) { this.SpawnTransmitters(forThing.Position, building.Position, map, forThing.Faction); position = building.Position; } } - Building building2; + Building building2 = default(Building); if (this.TrySpawnPowerGeneratorNear(position, map, forThing.Faction, out building2)) { this.SpawnTransmitters(position, building2.Position, map, forThing.Faction); @@ -380,14 +384,13 @@ private bool EverPossibleToTransmitPowerAt(IntVec3 c, Map map) private void TryTurnOnImmediately(CompPowerTrader powerComp, Map map) { - if (powerComp.PowerOn) - { - return; - } - map.powerNetManager.UpdatePowerNetsAndConnections_First(); - if (powerComp.PowerNet != null && powerComp.PowerNet.CurrentEnergyGainRate() > 1E-07f) + if (!powerComp.PowerOn) { - powerComp.PowerOn = true; + map.powerNetManager.UpdatePowerNetsAndConnections_First(); + if (powerComp.PowerNet != null && powerComp.PowerNet.CurrentEnergyGainRate() > 1.0000000116860974E-07) + { + powerComp.PowerOn = true; + } } } } diff --git a/Assembly-CSharp/RimWorld/GenStep_PreciousLump.cs b/Assembly-CSharp/RimWorld/GenStep_PreciousLump.cs index 32d941733..a34f24e1f 100644 --- a/Assembly-CSharp/RimWorld/GenStep_PreciousLump.cs +++ b/Assembly-CSharp/RimWorld/GenStep_PreciousLump.cs @@ -14,11 +14,11 @@ public class GenStep_PreciousLump : GenStep_ScatterLumpsMineable public override void Generate(Map map) { - this.forcedDefToScatter = this.mineables.RandomElement(); - this.count = 1; + base.forcedDefToScatter = this.mineables.RandomElement(); + base.count = 1; float randomInRange = this.totalValueRange.RandomInRange; - float baseMarketValue = this.forcedDefToScatter.building.mineableThing.BaseMarketValue; - this.forcedLumpSize = Mathf.Max(Mathf.RoundToInt(randomInRange / ((float)this.forcedDefToScatter.building.mineableYield * baseMarketValue)), 1); + float baseMarketValue = base.forcedDefToScatter.building.mineableThing.BaseMarketValue; + base.forcedLumpSize = Mathf.Max(Mathf.RoundToInt(randomInRange / ((float)base.forcedDefToScatter.building.mineableYield * baseMarketValue)), 1); base.Generate(map); } @@ -30,12 +30,12 @@ protected override bool CanScatterAt(IntVec3 c, Map map) protected override void ScatterAt(IntVec3 c, Map map, int stackCount = 1) { base.ScatterAt(c, map, stackCount); - int minX = this.recentLumpCells.Min((IntVec3 x) => x.x); - int minZ = this.recentLumpCells.Min((IntVec3 x) => x.z); - int maxX = this.recentLumpCells.Max((IntVec3 x) => x.x); - int maxZ = this.recentLumpCells.Max((IntVec3 x) => x.z); + int minX = base.recentLumpCells.Min((Func)((IntVec3 x) => x.x)); + int minZ = base.recentLumpCells.Min((Func)((IntVec3 x) => x.z)); + int maxX = base.recentLumpCells.Max((Func)((IntVec3 x) => x.x)); + int maxZ = base.recentLumpCells.Max((Func)((IntVec3 x) => x.z)); CellRect var = CellRect.FromLimits(minX, minZ, maxX, maxZ); - MapGenerator.SetVar("RectOfInterest", var); + MapGenerator.SetVar("RectOfInterest", var); } } } diff --git a/Assembly-CSharp/RimWorld/GenStep_Roads.cs b/Assembly-CSharp/RimWorld/GenStep_Roads.cs index a5950d090..2cea42586 100644 --- a/Assembly-CSharp/RimWorld/GenStep_Roads.cs +++ b/Assembly-CSharp/RimWorld/GenStep_Roads.cs @@ -37,7 +37,7 @@ private struct DistanceElement private const int CurveSampleMultiplier = 4; - private readonly float[] endcapSamples = new float[] + private readonly float[] endcapSamples = new float[5] { 0.75f, 0.8f, @@ -48,95 +48,124 @@ private struct DistanceElement public override void Generate(Map map) { - GenStep_Roads.c__AnonStorey30B c__AnonStorey30B = new GenStep_Roads.c__AnonStorey30B(); - c__AnonStorey30B.neededRoads = this.CalculateNeededRoads(map); - if (c__AnonStorey30B.neededRoads.Count == 0) + List neededRoads = this.CalculateNeededRoads(map); + if (neededRoads.Count != 0) { - return; - } - List list = new List(); - DeepProfiler.Start("RebuildAllRegions"); - map.regionAndRoomUpdater.RebuildAllRegionsAndRooms(); - DeepProfiler.End(); - TerrainDef rockDef = BaseGenUtility.RegionalRockTerrainDef(map.Tile, false); - IntVec3 intVec = CellFinderLoose.TryFindCentralCell(map, 3, 10, null); - RoadDef bestRoadType = (from rd in DefDatabase.AllDefs - where c__AnonStorey30B.neededRoads.Count((GenStep_Roads.NeededRoad nr) => nr.road == rd) >= 2 - select rd).MaxByWithFallback((RoadDef rd) => rd.priority, null); - if (bestRoadType != null) - { - GenStep_Roads.NeededRoad neededRoad = c__AnonStorey30B.neededRoads[c__AnonStorey30B.neededRoads.FindIndex((GenStep_Roads.NeededRoad nr) => nr.road == bestRoadType)]; - c__AnonStorey30B.neededRoads.RemoveAt(c__AnonStorey30B.neededRoads.FindIndex((GenStep_Roads.NeededRoad nr) => nr.road == bestRoadType)); - GenStep_Roads.NeededRoad neededRoad2 = c__AnonStorey30B.neededRoads[c__AnonStorey30B.neededRoads.FindIndex((GenStep_Roads.NeededRoad nr) => nr.road == bestRoadType)]; - c__AnonStorey30B.neededRoads.RemoveAt(c__AnonStorey30B.neededRoads.FindIndex((GenStep_Roads.NeededRoad nr) => nr.road == bestRoadType)); - RoadPathingDef pathingMode = neededRoad.road.pathingMode; - IntVec3 intVec2 = this.FindRoadExitCell(map, neededRoad.angle, intVec, ref pathingMode); - IntVec3 end = this.FindRoadExitCell(map, neededRoad2.angle, intVec2, ref pathingMode); - Action action = this.PrepDrawRoad(map, rockDef, intVec2, end, neededRoad.road, pathingMode, out intVec); - list.Add(new GenStep_Roads.DrawCommand - { - action = action, - roadDef = bestRoadType - }); - } - foreach (GenStep_Roads.NeededRoad current in c__AnonStorey30B.neededRoads) - { - RoadPathingDef pathingMode2 = current.road.pathingMode; - IntVec3 intVec3 = this.FindRoadExitCell(map, current.angle, intVec, ref pathingMode2); - if (!(intVec3 == IntVec3.Invalid)) + List list = new List(); + DeepProfiler.Start("RebuildAllRegions"); + map.regionAndRoomUpdater.RebuildAllRegionsAndRooms(); + DeepProfiler.End(); + TerrainDef rockDef = BaseGenUtility.RegionalRockTerrainDef(map.Tile, false); + IntVec3 intVec = CellFinderLoose.TryFindCentralCell(map, 3, 10, null); + RoadDef bestRoadType = (from rd in DefDatabase.AllDefs + where neededRoads.Count((Func)((NeededRoad nr) => nr.road == rd)) >= 2 + select rd).MaxByWithFallback((Func)((RoadDef rd) => rd.priority), (RoadDef)null); + if (bestRoadType != null) { - list.Add(new GenStep_Roads.DrawCommand + NeededRoad neededRoad = neededRoads[neededRoads.FindIndex((Predicate)((NeededRoad nr) => nr.road == bestRoadType))]; + neededRoads.RemoveAt(neededRoads.FindIndex((Predicate)((NeededRoad nr) => nr.road == bestRoadType))); + NeededRoad neededRoad2 = neededRoads[neededRoads.FindIndex((Predicate)((NeededRoad nr) => nr.road == bestRoadType))]; + neededRoads.RemoveAt(neededRoads.FindIndex((Predicate)((NeededRoad nr) => nr.road == bestRoadType))); + RoadPathingDef pathingMode = neededRoad.road.pathingMode; + IntVec3 intVec2 = this.FindRoadExitCell(map, neededRoad.angle, intVec, ref pathingMode); + IntVec3 end = this.FindRoadExitCell(map, neededRoad2.angle, intVec2, ref pathingMode); + Action action = this.PrepDrawRoad(map, rockDef, intVec2, end, neededRoad.road, pathingMode, out intVec); + list.Add(new DrawCommand { - action = this.PrepDrawRoad(map, rockDef, intVec, intVec3, current.road, pathingMode2), - roadDef = current.road + action = action, + roadDef = bestRoadType }); } - } - foreach (GenStep_Roads.DrawCommand current2 in from dc in list - orderby dc.roadDef.priority - select dc) - { - if (current2.action != null) + List.Enumerator enumerator = neededRoads.GetEnumerator(); + try + { + while (enumerator.MoveNext()) + { + NeededRoad current = enumerator.Current; + RoadPathingDef pathingMode2 = current.road.pathingMode; + IntVec3 intVec3 = this.FindRoadExitCell(map, current.angle, intVec, ref pathingMode2); + if (!(intVec3 == IntVec3.Invalid)) + { + list.Add(new DrawCommand + { + action = this.PrepDrawRoad(map, rockDef, intVec, intVec3, current.road, pathingMode2), + roadDef = current.road + }); + } + } + } + finally + { + ((IDisposable)(object)enumerator).Dispose(); + } + foreach (DrawCommand item in from dc in list + orderby dc.roadDef.priority + select dc) { - current2.action(); + DrawCommand current2 = item; + if ((object)current2.action != null) + { + current2.action(); + } } } } - private List CalculateNeededRoads(Map map) + private List CalculateNeededRoads(Map map) { List list = new List(); Find.WorldGrid.GetTileNeighbors(map.Tile, list); - List list2 = new List(); - foreach (int current in list) + List list2 = new List(); + List.Enumerator enumerator = list.GetEnumerator(); + try { - RoadDef roadDef = Find.WorldGrid.GetRoadDef(map.Tile, current, true); - if (roadDef != null) + while (enumerator.MoveNext()) { - list2.Add(new GenStep_Roads.NeededRoad + int current = enumerator.Current; + RoadDef roadDef = Find.WorldGrid.GetRoadDef(map.Tile, current, true); + if (roadDef != null) { - angle = Find.WorldGrid.GetHeadingFromTo(map.Tile, current), - road = roadDef - }); + list2.Add(new NeededRoad + { + angle = Find.WorldGrid.GetHeadingFromTo(map.Tile, current), + road = roadDef + }); + } } } + finally + { + ((IDisposable)(object)enumerator).Dispose(); + } if (list2.Count > 1) { Vector3 vector = Vector3.zero; - foreach (GenStep_Roads.NeededRoad current2 in list2) + List.Enumerator enumerator2 = list2.GetEnumerator(); + try + { + while (enumerator2.MoveNext()) + { + NeededRoad current2 = enumerator2.Current; + vector += Vector3Utility.HorizontalVectorFromAngle(current2.angle); + } + } + finally { - vector += Vector3Utility.HorizontalVectorFromAngle(current2.angle); + ((IDisposable)(object)enumerator2).Dispose(); } - vector /= (float)(-(float)list2.Count); + vector /= (float)(-list2.Count); vector += Rand.PointOnSphere * 1f / 6f; vector.y = 0f; for (int i = 0; i < list2.Count; i++) { - list2[i] = new GenStep_Roads.NeededRoad - { - angle = (Vector3Utility.HorizontalVectorFromAngle(list2[i].angle) + vector).AngleFlat(), - road = list2[i].road - }; + List obj = list2; + int index = i; + NeededRoad value = default(NeededRoad); + NeededRoad neededRoad = list2[i]; + value.angle = (Vector3Utility.HorizontalVectorFromAngle(neededRoad.angle) + vector).AngleFlat(); + NeededRoad neededRoad2 = list2[i]; + value.road = neededRoad2.road; + obj[index] = value; } } return list2; @@ -144,23 +173,23 @@ orderby dc.roadDef.priority private IntVec3 FindRoadExitCell(Map map, float angle, IntVec3 crossroads, ref RoadPathingDef pathingDef) { - Predicate tileValidator = delegate(IntVec3 pos) + Predicate tileValidator = (Predicate)delegate(IntVec3 pos) { - foreach (IntVec3 current in GenRadial.RadialCellsAround(pos, 8f, true)) + foreach (IntVec3 item in GenRadial.RadialCellsAround(pos, 8f, true)) { - if (current.InBounds(map) && current.GetTerrain(map).HasTag("Water")) + if (item.InBounds(map) && item.GetTerrain(map).HasTag("Water")) { return false; } } return true; }; - float validAngleSpan2; - for (validAngleSpan2 = 10f; validAngleSpan2 < 90f; validAngleSpan2 += 10f) + float validAngleSpan; + IntVec3 result = default(IntVec3); + for (validAngleSpan = 10f; validAngleSpan < 90.0; validAngleSpan += 10f) { - Predicate angleValidator = (IntVec3 pos) => GenGeo.AngleDifferenceBetween((pos - map.Center).AngleFlat, angle) < validAngleSpan2; - IntVec3 result; - if (CellFinder.TryFindRandomEdgeCellWith((IntVec3 x) => angleValidator(x) && tileValidator(x) && map.reachability.CanReach(crossroads, x, PathEndMode.OnCell, TraverseParms.For(TraverseMode.NoPassClosedDoors, Danger.Deadly, false)), map, 0f, out result)) + Predicate angleValidator = (Predicate)((IntVec3 pos) => GenGeo.AngleDifferenceBetween((pos - map.Center).AngleFlat, angle) < validAngleSpan); + if (CellFinder.TryFindRandomEdgeCellWith((Predicate)((IntVec3 x) => angleValidator(x) && tileValidator(x) && map.reachability.CanReach(crossroads, x, PathEndMode.OnCell, TraverseParms.For(TraverseMode.NoPassClosedDoors, Danger.Deadly, false))), map, 0f, out result)) { return result; } @@ -169,12 +198,11 @@ private IntVec3 FindRoadExitCell(Map map, float angle, IntVec3 crossroads, ref R { pathingDef = RoadPathingDefOf.Bulldoze; } - float validAngleSpan; - for (validAngleSpan = 10f; validAngleSpan < 90f; validAngleSpan += 10f) + float validAngleSpan2; + for (validAngleSpan2 = 10f; validAngleSpan2 < 90.0; validAngleSpan2 += 10f) { - Predicate angleValidator = (IntVec3 pos) => GenGeo.AngleDifferenceBetween((pos - map.Center).AngleFlat, angle) < validAngleSpan; - IntVec3 result; - if (CellFinder.TryFindRandomEdgeCellWith((IntVec3 x) => angleValidator(x) && tileValidator(x) && map.reachability.CanReach(crossroads, x, PathEndMode.OnCell, TraverseParms.For(TraverseMode.PassAllDestroyableThings, Danger.Deadly, false)), map, 0f, out result)) + Predicate angleValidator2 = (Predicate)((IntVec3 pos) => GenGeo.AngleDifferenceBetween((pos - map.Center).AngleFlat, angle) < validAngleSpan2); + if (CellFinder.TryFindRandomEdgeCellWith((Predicate)((IntVec3 x) => angleValidator2(x) && tileValidator(x) && map.reachability.CanReach(crossroads, x, PathEndMode.OnCell, TraverseParms.For(TraverseMode.PassAllDestroyableThings, Danger.Deadly, false))), map, 0f, out result)) { return result; } @@ -185,7 +213,7 @@ private IntVec3 FindRoadExitCell(Map map, float angle, IntVec3 crossroads, ref R private Action PrepDrawRoad(Map map, TerrainDef rockDef, IntVec3 start, IntVec3 end, RoadDef roadDef, RoadPathingDef pathingDef) { - IntVec3 intVec; + IntVec3 intVec = default(IntVec3); return this.PrepDrawRoad(map, rockDef, start, end, roadDef, pathingDef, out intVec); } @@ -203,85 +231,94 @@ private Action PrepDrawRoad(Map map, TerrainDef rockDef, IntVec3 start, IntVec3 } List list = this.RefinePath(pawnPath.NodesReversed, map); pawnPath.ReleaseToPool(); - GenStep_Roads.DistanceElement[,] distance = new GenStep_Roads.DistanceElement[map.Size.x, map.Size.z]; + IntVec3 size = map.Size; + int x = size.x; + IntVec3 size2 = map.Size; + DistanceElement[,] distance = new DistanceElement[x, size2.z]; int count = list.Count; int centerpointIndex = Mathf.RoundToInt(Rand.Range(0.3f, 0.7f) * (float)count); int num = Mathf.Max(1, GenMath.RoundRandom((float)count / (float)roadDef.tilesPerSegment)); - for (int i = 0; i < num; i++) + for (int num2 = 0; num2 < num; num2++) { - int pathStartIndex = Mathf.RoundToInt((float)(count - 1) / (float)num * (float)i); - int pathEndIndex = Mathf.RoundToInt((float)(count - 1) / (float)num * (float)(i + 1)); + int pathStartIndex = Mathf.RoundToInt((float)(count - 1) / (float)num * (float)num2); + int pathEndIndex = Mathf.RoundToInt((float)(count - 1) / (float)num * (float)(num2 + 1)); this.DrawCurveSegment(distance, list, pathStartIndex, pathEndIndex, pathingDef, map, centerpointIndex, ref centerpoint); } - return delegate + return (Action)delegate() { this.ApplyDistanceField(distance, map, rockDef, roadDef, pathingDef); }; } - private void DrawCurveSegment(GenStep_Roads.DistanceElement[,] distance, List path, int pathStartIndex, int pathEndIndex, RoadPathingDef pathing, Map map, int centerpointIndex, ref IntVec3 centerpoint) + private void DrawCurveSegment(DistanceElement[,] distance, List path, int pathStartIndex, int pathEndIndex, RoadPathingDef pathing, Map map, int centerpointIndex, ref IntVec3 centerpoint) { if (pathStartIndex == pathEndIndex) { Log.ErrorOnce("Zero-length segment drawn in road routine", 78187971); - return; } - GenMath.BezierCubicControls bcc = this.GenerateBezierControls(path, pathStartIndex, pathEndIndex); - List list = new List(); - int num = (pathEndIndex - pathStartIndex) * 4; - for (int i = 0; i <= num; i++) + else { - list.Add(GenMath.BezierCubicEvaluate((float)i / (float)num, bcc)); - } - int num2 = 0; - for (int j = pathStartIndex; j <= pathEndIndex; j++) - { - if (j > 0 && j <= path.Count && path[j].InBounds(map) && path[j].GetTerrain(map).HasTag("Water")) + GenMath.BezierCubicControls bcc = this.GenerateBezierControls(path, pathStartIndex, pathEndIndex); + List list = new List(); + int num = (pathEndIndex - pathStartIndex) * 4; + for (int num2 = 0; num2 <= num; num2++) { - num2++; + list.Add(GenMath.BezierCubicEvaluate((float)num2 / (float)num, bcc)); } - } - if (pathing == RoadPathingDefOf.Avoid && pathStartIndex + 1 < pathEndIndex) - { - for (int k = 0; k < list.Count; k++) + int num3 = 0; + for (int num4 = pathStartIndex; num4 <= pathEndIndex; num4++) { - IntVec3 intVec = list[k].ToIntVec3(); - bool flag = intVec.InBounds(map) && intVec.Impassable(map); - int num3 = 0; - int num4 = 0; - while (num4 < GenAdj.CardinalDirections.Length && !flag) + if (num4 > 0 && num4 <= path.Count && path[num4].InBounds(map) && path[num4].GetTerrain(map).HasTag("Water")) + { + num3++; + } + } + if (pathing == RoadPathingDefOf.Avoid && pathStartIndex + 1 < pathEndIndex) + { + int num5 = 0; + while (num5 < list.Count) { - IntVec3 c = intVec + GenAdj.CardinalDirections[num4]; - if (c.InBounds(map)) + IntVec3 intVec = list[num5].ToIntVec3(); + bool flag = intVec.InBounds(map) && intVec.Impassable(map); + int num6 = 0; + int num7 = 0; + while (num7 < GenAdj.CardinalDirections.Length && !flag) { - flag |= c.Impassable(map); - if (c.GetTerrain(map).HasTag("Water")) - { - num3++; - } - if (flag) + IntVec3 c = intVec + GenAdj.CardinalDirections[num7]; + if (c.InBounds(map)) { - break; + flag |= c.Impassable(map); + if (c.GetTerrain(map).HasTag("Water")) + { + num6++; + } + if (flag) + break; } + num7++; + } + if (!flag && !((float)num6 > (float)num3 * 1.5 + 2.0)) + { + num5++; + continue; } - num4++; - } - if (flag || (float)num3 > (float)num2 * 1.5f + 2f) - { this.DrawCurveSegment(distance, path, pathStartIndex, (pathStartIndex + pathEndIndex) / 2, pathing, map, centerpointIndex, ref centerpoint); this.DrawCurveSegment(distance, path, (pathStartIndex + pathEndIndex) / 2, pathEndIndex, pathing, map, centerpointIndex, ref centerpoint); return; } } - } - for (int l = 0; l < list.Count; l++) - { - this.FillDistanceField(distance, list[l].x, list[l].z, GenMath.LerpDouble(0f, (float)(list.Count - 1), (float)pathStartIndex, (float)pathEndIndex, (float)l), 10f); - } - if (centerpointIndex >= pathStartIndex && centerpointIndex < pathEndIndex) - { - centerpointIndex = Mathf.Clamp(Mathf.RoundToInt(GenMath.LerpDouble((float)pathStartIndex, (float)pathEndIndex, 0f, (float)list.Count, (float)centerpointIndex)), 0, list.Count - 1); - centerpoint = list[centerpointIndex].ToIntVec3(); + for (int i = 0; i < list.Count; i++) + { + Vector3 vector = list[i]; + float x = vector.x; + Vector3 vector2 = list[i]; + this.FillDistanceField(distance, x, vector2.z, GenMath.LerpDouble(0f, (float)(list.Count - 1), (float)pathStartIndex, (float)pathEndIndex, (float)i), 10f); + } + if (centerpointIndex >= pathStartIndex && centerpointIndex < pathEndIndex) + { + centerpointIndex = Mathf.Clamp(Mathf.RoundToInt(GenMath.LerpDouble((float)pathStartIndex, (float)pathEndIndex, 0f, (float)list.Count, (float)centerpointIndex)), 0, list.Count - 1); + centerpoint = list[centerpointIndex].ToIntVec3(); + } } } @@ -298,58 +335,73 @@ private GenMath.BezierCubicControls GenerateBezierControls(List path, i }; } - private void ApplyDistanceField(GenStep_Roads.DistanceElement[,] distance, Map map, TerrainDef rockDef, RoadDef roadDef, RoadPathingDef pathingDef) + private void ApplyDistanceField(DistanceElement[,] distance, Map map, TerrainDef rockDef, RoadDef roadDef, RoadPathingDef pathingDef) { - for (int i = 0; i < map.Size.x; i++) + int num = 0; + while (true) { - for (int j = 0; j < map.Size.z; j++) + int num2 = num; + IntVec3 size = map.Size; + if (num2 < size.x) { - GenStep_Roads.DistanceElement distanceElement = distance[i, j]; - if (distanceElement.touched) + int num3 = 0; + while (true) { - float b = Mathf.Abs(distanceElement.fromRoad + Rand.Value - 0.5f); - for (int k = 0; k < roadDef.roadGenSteps.Count; k++) + int num4 = num3; + IntVec3 size2 = map.Size; + if (num4 < size2.z) { - RoadDefGenStep roadDefGenStep = roadDef.roadGenSteps[k]; - float x = Mathf.LerpUnclamped(distanceElement.fromRoad, b, roadDefGenStep.antialiasingMultiplier); - float num = roadDefGenStep.chancePerPositionCurve.Evaluate(x); - if (num > 0f) + DistanceElement distanceElement = distance[num, num3]; + if (distanceElement.touched) { - if (roadDefGenStep.periodicSpacing == 0 || distanceElement.alongPath / (float)roadDefGenStep.periodicSpacing % 1f * (float)roadDefGenStep.periodicSpacing < 1f) + float b = Mathf.Abs((float)(distanceElement.fromRoad + Rand.Value - 0.5)); + for (int i = 0; i < roadDef.roadGenSteps.Count; i++) { - IntVec3 position = new IntVec3(i, 0, j); - if (Rand.Value < num) + RoadDefGenStep roadDefGenStep = roadDef.roadGenSteps[i]; + float x = Mathf.LerpUnclamped(distanceElement.fromRoad, b, roadDefGenStep.antialiasingMultiplier); + float num5 = roadDefGenStep.chancePerPositionCurve.Evaluate(x); + if (!(num5 <= 0.0) && (roadDefGenStep.periodicSpacing == 0 || !(distanceElement.alongPath / (float)roadDefGenStep.periodicSpacing % 1.0 * (float)roadDefGenStep.periodicSpacing >= 1.0))) { - roadDefGenStep.Place(map, position, rockDef); + IntVec3 position = new IntVec3(num, 0, num3); + if (Rand.Value < num5) + { + roadDefGenStep.Place(map, position, rockDef); + } } } } + num3++; + continue; } + break; } + num++; + continue; } + break; } } - private void FillDistanceField(GenStep_Roads.DistanceElement[,] field, float cx, float cz, float alongPath, float radius) + private void FillDistanceField(DistanceElement[,] field, float cx, float cz, float alongPath, float radius) { int num = Mathf.Clamp(Mathf.FloorToInt(cx - radius), 0, field.GetLength(0) - 1); int num2 = Mathf.Clamp(Mathf.FloorToInt(cx + radius), 0, field.GetLength(0) - 1); int num3 = Mathf.Clamp(Mathf.FloorToInt(cz - radius), 0, field.GetLength(1) - 1); int num4 = Mathf.Clamp(Mathf.FloorToInt(cz + radius), 0, field.GetLength(1) - 1); - for (int i = num; i <= num2; i++) + for (int num5 = num; num5 <= num2; num5++) { - float num5 = ((float)i + 0.5f - cx) * ((float)i + 0.5f - cx); - for (int j = num3; j <= num4; j++) + float num6 = (float)(((float)num5 + 0.5 - cx) * ((float)num5 + 0.5 - cx)); + for (int num7 = num3; num7 <= num4; num7++) { - float num6 = ((float)j + 0.5f - cz) * ((float)j + 0.5f - cz); - float num7 = Mathf.Sqrt(num5 + num6); - float fromRoad = field[i, j].fromRoad; - if (!field[i, j].touched || num7 < fromRoad) + float num8 = (float)(((float)num7 + 0.5 - cz) * ((float)num7 + 0.5 - cz)); + float num9 = Mathf.Sqrt(num6 + num8); + float fromRoad = field[num5, num7].fromRoad; + if (!field[num5, num7].touched || num9 < fromRoad) { - field[i, j].fromRoad = num7; - field[i, j].alongPath = alongPath; + field[num5, num7].fromRoad = num9; + field[num5, num7].alongPath = alongPath; } - field[i, j].touched = true; + field[num5, num7].touched = true; } } } @@ -383,48 +435,57 @@ private List RefineEndcap(List input, Map map) IntVec3 start = IntVec3.Invalid; for (int j = 0; j < 2; j++) { - Rot4 rot = new Rot4(j); - IntVec3 facingCell = rot.FacingCell; + IntVec3 facingCell = new Rot4(j).FacingCell; IntVec3 intVec = input[input.Count - 1]; bool flag = true; - if (Mathf.Abs(intVec.x * facingCell.x) > 5 && Mathf.Abs(intVec.x * facingCell.x - map.Size.x) > 5) + if (Mathf.Abs(intVec.x * facingCell.x) > 5) { - flag = false; + int num3 = intVec.x * facingCell.x; + IntVec3 size = map.Size; + if (Mathf.Abs(num3 - size.x) > 5) + { + flag = false; + } } - if (Mathf.Abs(intVec.z * facingCell.z) > 5 && Mathf.Abs(intVec.z * facingCell.z - map.Size.z) > 5) + if (Mathf.Abs(intVec.z * facingCell.z) > 5) { - flag = false; + int num4 = intVec.z * facingCell.z; + IntVec3 size2 = map.Size; + if (Mathf.Abs(num4 - size2.z) > 5) + { + flag = false; + } } if (flag) { for (int k = 0; k < this.endcapSamples.Length; k++) { - if (array[k] != 0f) + if (array[k] != 0.0) { - int num3 = Mathf.RoundToInt((float)input.Count * this.endcapSamples[k]); - IntVec3 intVec2 = input[num3]; - IntVec3 intVec3 = intVec2; + int num5 = Mathf.RoundToInt((float)input.Count * this.endcapSamples[k]); + IntVec3 intVec2; + IntVec3 intVec3 = intVec2 = input[num5]; if (facingCell.x != 0) { - intVec3.x = intVec.x; + intVec2.x = intVec.x; } else if (facingCell.z != 0) { - intVec3.z = intVec.z; + intVec2.z = intVec.z; } - PawnPath pawnPath2 = map.pathFinder.FindPath(input[num3], input[input.Count - 1], TraverseParms.For(TraverseMode.NoPassClosedDoors, Danger.Deadly, false), PathEndMode.OnCell); + PawnPath pawnPath2 = map.pathFinder.FindPath(input[num5], input[input.Count - 1], TraverseParms.For(TraverseMode.NoPassClosedDoors, Danger.Deadly, false), PathEndMode.OnCell); if (pawnPath2 == PawnPath.NotFound) { - pawnPath2 = map.pathFinder.FindPath(input[num3], input[input.Count - 1], TraverseParms.For(TraverseMode.PassAllDestroyableThings, Danger.Deadly, false), PathEndMode.OnCell); + pawnPath2 = map.pathFinder.FindPath(input[num5], input[input.Count - 1], TraverseParms.For(TraverseMode.PassAllDestroyableThings, Danger.Deadly, false), PathEndMode.OnCell); } if (pawnPath2 != PawnPath.NotFound) { - float num4 = array[k] / pawnPath2.TotalCost; - if (num4 > num) + float num6 = array[k] / pawnPath2.TotalCost; + if (num6 > num) { - num = num4; - num2 = num3; - start = intVec3; + num = num6; + num2 = num5; + start = intVec2; } pawnPath2.ReleaseToPool(); } @@ -439,6 +500,7 @@ private List RefineEndcap(List input, Map map) { input.RemoveRange(num2, input.Count - num2); input.AddRange(pawnPath3.NodesReversed); + return input; } } return input; diff --git a/Assembly-CSharp/RimWorld/GenStep_RockChunks.cs b/Assembly-CSharp/RimWorld/GenStep_RockChunks.cs index 53bb9e652..6e5d1d088 100644 --- a/Assembly-CSharp/RimWorld/GenStep_RockChunks.cs +++ b/Assembly-CSharp/RimWorld/GenStep_RockChunks.cs @@ -1,4 +1,3 @@ -using System; using System.Collections.Generic; using Verse; using Verse.Noise; @@ -17,54 +16,43 @@ public class GenStep_RockChunks : GenStep public override void Generate(Map map) { - if (map.TileInfo.WaterCovered) + if (!map.TileInfo.WaterCovered) { - return; - } - this.freqFactorNoise = new Perlin(0.014999999664723873, 2.0, 0.5, 6, Rand.Range(0, 999999), QualityMode.Medium); - this.freqFactorNoise = new ScaleBias(1.0, 1.0, this.freqFactorNoise); - NoiseDebugUI.StoreNoiseRender(this.freqFactorNoise, "rock_chunks_freq_factor"); - foreach (IntVec3 current in map.AllCells) - { - float num = 0.006f * this.freqFactorNoise.GetValue(current); - if (MapGenerator.Elevation[current] < 0.55f && Rand.Value < num) + this.freqFactorNoise = new Perlin(0.014999999664723873, 2.0, 0.5, 6, Rand.Range(0, 999999), QualityMode.Medium); + this.freqFactorNoise = new ScaleBias(1.0, 1.0, this.freqFactorNoise); + NoiseDebugUI.StoreNoiseRender(this.freqFactorNoise, "rock_chunks_freq_factor"); + foreach (IntVec3 allCell in map.AllCells) { - this.GrowLowRockFormationFrom(current, map); + float num = (float)(0.0060000000521540642 * this.freqFactorNoise.GetValue(allCell)); + if (MapGenerator.Elevation[allCell] < 0.550000011920929 && Rand.Value < num) + { + this.GrowLowRockFormationFrom(allCell, map); + } } + this.freqFactorNoise = null; } - this.freqFactorNoise = null; } private void GrowLowRockFormationFrom(IntVec3 root, Map map) { ThingDef rockRubble = ThingDefOf.RockRubble; - ThingDef mineableThing = Find.World.NaturalRockTypesIn(map.Tile).RandomElement().building.mineableThing; + ThingDef mineableThing = Find.World.NaturalRockTypesIn(map.Tile).RandomElement().building.mineableThing; Rot4 random = Rot4.Random; IntVec3 intVec = root; while (true) { Rot4 random2 = Rot4.Random; - if (!(random2 == random)) + if (random2 == random) + continue; + intVec += random2.FacingCell; + if (intVec.InBounds(map) && intVec.GetEdifice(map) == null && intVec.GetFirstItem(map) == null && !(MapGenerator.Elevation[intVec] > 0.550000011920929) && map.terrainGrid.TerrainAt(intVec).affordances.Contains(TerrainAffordance.Heavy)) { - intVec += random2.FacingCell; - if (!intVec.InBounds(map) || intVec.GetEdifice(map) != null || intVec.GetFirstItem(map) != null) - { - break; - } - if (MapGenerator.Elevation[intVec] > 0.55f) - { - return; - } - if (!map.terrainGrid.TerrainAt(intVec).affordances.Contains(TerrainAffordance.Heavy)) - { - return; - } GenSpawn.Spawn(mineableThing, intVec, map); IntVec3[] adjacentCellsAndInside = GenAdj.AdjacentCellsAndInside; for (int i = 0; i < adjacentCellsAndInside.Length; i++) { IntVec3 b = adjacentCellsAndInside[i]; - if (Rand.Value < 0.5f) + if (Rand.Value < 0.5) { IntVec3 c = intVec + b; if (c.InBounds(map)) @@ -87,7 +75,9 @@ private void GrowLowRockFormationFrom(IntVec3 root, Map map) } } } + continue; } + break; } } } diff --git a/Assembly-CSharp/RimWorld/GenStep_RocksFromGrid.cs b/Assembly-CSharp/RimWorld/GenStep_RocksFromGrid.cs index 549edeed0..0c81c326c 100644 --- a/Assembly-CSharp/RimWorld/GenStep_RocksFromGrid.cs +++ b/Assembly-CSharp/RimWorld/GenStep_RocksFromGrid.cs @@ -39,88 +39,95 @@ public static ThingDef RockDefAt(IntVec3 c) public override void Generate(Map map) { - if (map.TileInfo.WaterCovered) + if (!map.TileInfo.WaterCovered) { - return; - } - map.regionAndRoomUpdater.Enabled = false; - float num = 0.7f; - List list = new List(); - list.Add(new GenStep_RocksFromGrid.RoofThreshold - { - roofDef = RoofDefOf.RoofRockThick, - minGridVal = num * 1.14f - }); - list.Add(new GenStep_RocksFromGrid.RoofThreshold - { - roofDef = RoofDefOf.RoofRockThin, - minGridVal = num * 1.04f - }); - MapGenFloatGrid elevation = MapGenerator.Elevation; - foreach (IntVec3 current in map.AllCells) - { - float num2 = elevation[current]; - if (num2 > num) + map.regionAndRoomUpdater.Enabled = false; + float num = 0.7f; + List list = new List(); + RoofThreshold roofThreshold = new RoofThreshold(); + roofThreshold.roofDef = RoofDefOf.RoofRockThick; + roofThreshold.minGridVal = (float)(num * 1.1399999856948853); + list.Add(roofThreshold); + RoofThreshold roofThreshold2 = new RoofThreshold(); + roofThreshold2.roofDef = RoofDefOf.RoofRockThin; + roofThreshold2.minGridVal = (float)(num * 1.0399999618530273); + list.Add(roofThreshold2); + MapGenFloatGrid elevation = MapGenerator.Elevation; + foreach (IntVec3 allCell in map.AllCells) { - ThingDef def = GenStep_RocksFromGrid.RockDefAt(current); - GenSpawn.Spawn(def, current, map); - for (int i = 0; i < list.Count; i++) + float num2 = elevation[allCell]; + if (num2 > num) { - if (num2 > list[i].minGridVal) + ThingDef def = GenStep_RocksFromGrid.RockDefAt(allCell); + GenSpawn.Spawn(def, allCell, map); + int num3 = 0; + while (num3 < list.Count) { - map.roofGrid.SetRoof(current, list[i].roofDef); + if (!(num2 > list[num3].minGridVal)) + { + num3++; + continue; + } + map.roofGrid.SetRoof(allCell, list[num3].roofDef); break; } } } - } - BoolGrid visited = new BoolGrid(map); - List toRemove = new List(); - foreach (IntVec3 current2 in map.AllCells) - { - if (!visited[current2]) + BoolGrid visited = new BoolGrid(map); + List toRemove = new List(); + foreach (IntVec3 allCell2 in map.AllCells) { - if (this.IsNaturalRoofAt(current2, map)) + if (!visited[allCell2] && this.IsNaturalRoofAt(allCell2, map)) { toRemove.Clear(); - map.floodFiller.FloodFill(current2, (IntVec3 x) => this.IsNaturalRoofAt(x, map), delegate(IntVec3 x) + map.floodFiller.FloodFill(allCell2, (Predicate)((IntVec3 x) => this.IsNaturalRoofAt(x, map)), (Action)delegate(IntVec3 x) { visited[x] = true; toRemove.Add(x); }, false); if (toRemove.Count < 20) { - for (int j = 0; j < toRemove.Count; j++) + for (int i = 0; i < toRemove.Count; i++) { - map.roofGrid.SetRoof(toRemove[j], null); + map.roofGrid.SetRoof(toRemove[i], null); } } } } + GenStep_ScatterLumpsMineable genStep_ScatterLumpsMineable = new GenStep_ScatterLumpsMineable(); + float num4 = 10f; + switch (Find.WorldGrid[map.Tile].hilliness) + { + case Hilliness.Flat: + { + num4 = 4f; + break; + } + case Hilliness.SmallHills: + { + num4 = 8f; + break; + } + case Hilliness.LargeHills: + { + num4 = 11f; + break; + } + case Hilliness.Mountainous: + { + num4 = 15f; + break; + } + case Hilliness.Impassable: + { + num4 = 16f; + break; + } + } + genStep_ScatterLumpsMineable.countPer10kCellsRange = new FloatRange(num4, num4); + genStep_ScatterLumpsMineable.Generate(map); + map.regionAndRoomUpdater.Enabled = true; } - GenStep_ScatterLumpsMineable genStep_ScatterLumpsMineable = new GenStep_ScatterLumpsMineable(); - float num3 = 10f; - switch (Find.WorldGrid[map.Tile].hilliness) - { - case Hilliness.Flat: - num3 = 4f; - break; - case Hilliness.SmallHills: - num3 = 8f; - break; - case Hilliness.LargeHills: - num3 = 11f; - break; - case Hilliness.Mountainous: - num3 = 15f; - break; - case Hilliness.Impassable: - num3 = 16f; - break; - } - genStep_ScatterLumpsMineable.countPer10kCellsRange = new FloatRange(num3, num3); - genStep_ScatterLumpsMineable.Generate(map); - map.regionAndRoomUpdater.Enabled = true; } private bool IsNaturalRoofAt(IntVec3 c, Map map) diff --git a/Assembly-CSharp/RimWorld/GenStep_ScatterDeepResourceLumps.cs b/Assembly-CSharp/RimWorld/GenStep_ScatterDeepResourceLumps.cs index 0abf1b2ab..b6d6c25da 100644 --- a/Assembly-CSharp/RimWorld/GenStep_ScatterDeepResourceLumps.cs +++ b/Assembly-CSharp/RimWorld/GenStep_ScatterDeepResourceLumps.cs @@ -11,41 +11,47 @@ public class GenStep_ScatterDeepResourceLumps : GenStep_Scatterer public override void Generate(Map map) { - if (map.TileInfo.WaterCovered) + if (!map.TileInfo.WaterCovered) { - return; - } - int num = base.CalculateFinalCount(map); - for (int i = 0; i < num; i++) - { - IntVec3 intVec; - if (!this.TryFindScatterCell(map, out intVec)) + int num = base.CalculateFinalCount(map); + int num2 = 0; + while (num2 < num) { + IntVec3 intVec = default(IntVec3); + if (((GenStep_Scatterer)this).TryFindScatterCell(map, out intVec)) + { + this.ScatterAt(intVec, map, 1); + base.usedSpots.Add(intVec); + num2++; + continue; + } return; } - this.ScatterAt(intVec, map, 1); - this.usedSpots.Add(intVec); + base.usedSpots.Clear(); } - this.usedSpots.Clear(); } protected ThingDef ChooseThingDef() { - return DefDatabase.AllDefs.RandomElementByWeight((ThingDef def) => def.deepCommonality); + return DefDatabase.AllDefs.RandomElementByWeight((Func)((ThingDef def) => def.deepCommonality)); } protected override bool CanScatterAt(IntVec3 c, Map map) { - return !base.NearUsedSpot(c, this.minSpacing); + if (base.NearUsedSpot(c, base.minSpacing)) + { + return false; + } + return true; } protected override void ScatterAt(IntVec3 c, Map map, int stackCount = 1) { ThingDef thingDef = this.ChooseThingDef(); - int numCells = Mathf.CeilToInt((float)this.GetScatterLumpSizeRange(thingDef).RandomInRange * 1.6f); - foreach (IntVec3 current in GridShapeMaker.IrregularLump(c, map, numCells)) + int numCells = Mathf.CeilToInt((float)((float)this.GetScatterLumpSizeRange(thingDef).RandomInRange * 1.6000000238418579)); + foreach (IntVec3 item in GridShapeMaker.IrregularLump(c, map, numCells)) { - map.deepResourceGrid.SetAt(current, thingDef, thingDef.deepCountPerCell); + map.deepResourceGrid.SetAt(item, thingDef, thingDef.deepCountPerCell); } } diff --git a/Assembly-CSharp/RimWorld/GenStep_ScatterLumpsMineable.cs b/Assembly-CSharp/RimWorld/GenStep_ScatterLumpsMineable.cs index 37bc56b69..e1952bdcb 100644 --- a/Assembly-CSharp/RimWorld/GenStep_ScatterLumpsMineable.cs +++ b/Assembly-CSharp/RimWorld/GenStep_ScatterLumpsMineable.cs @@ -15,20 +15,23 @@ public class GenStep_ScatterLumpsMineable : GenStep_Scatterer public override void Generate(Map map) { - this.minSpacing = 5f; - this.warnOnFail = false; + base.minSpacing = 5f; + base.warnOnFail = false; int num = base.CalculateFinalCount(map); - for (int i = 0; i < num; i++) + int num2 = 0; + while (num2 < num) { - IntVec3 intVec; - if (!this.TryFindScatterCell(map, out intVec)) + IntVec3 intVec = default(IntVec3); + if (((GenStep_Scatterer)this).TryFindScatterCell(map, out intVec)) { - return; + this.ScatterAt(intVec, map, 1); + base.usedSpots.Add(intVec); + num2++; + continue; } - this.ScatterAt(intVec, map, 1); - this.usedSpots.Add(intVec); + return; } - this.usedSpots.Clear(); + base.usedSpots.Clear(); } protected ThingDef ChooseThingDef() @@ -37,7 +40,7 @@ protected ThingDef ChooseThingDef() { return this.forcedDefToScatter; } - return DefDatabase.AllDefs.RandomElementByWeight(delegate(ThingDef d) + return DefDatabase.AllDefs.RandomElementByWeight((Func)delegate(ThingDef d) { if (d.building == null) { @@ -49,12 +52,16 @@ protected ThingDef ChooseThingDef() protected override bool CanScatterAt(IntVec3 c, Map map) { - if (base.NearUsedSpot(c, this.minSpacing)) + if (base.NearUsedSpot(c, base.minSpacing)) { return false; } Building edifice = c.GetEdifice(map); - return edifice != null && edifice.def.building.isNaturalRock; + if (edifice != null && edifice.def.building.isNaturalRock) + { + return true; + } + return false; } protected override void ScatterAt(IntVec3 c, Map map, int stackCount = 1) @@ -62,10 +69,10 @@ protected override void ScatterAt(IntVec3 c, Map map, int stackCount = 1) ThingDef thingDef = this.ChooseThingDef(); int numCells = (this.forcedLumpSize <= 0) ? thingDef.building.mineableScatterLumpSizeRange.RandomInRange : this.forcedLumpSize; this.recentLumpCells.Clear(); - foreach (IntVec3 current in GridShapeMaker.IrregularLump(c, map, numCells)) + foreach (IntVec3 item in GridShapeMaker.IrregularLump(c, map, numCells)) { - GenSpawn.Spawn(thingDef, current, map); - this.recentLumpCells.Add(current); + GenSpawn.Spawn(thingDef, item, map); + this.recentLumpCells.Add(item); } } } diff --git a/Assembly-CSharp/RimWorld/GenStep_ScatterRuinsSimple.cs b/Assembly-CSharp/RimWorld/GenStep_ScatterRuinsSimple.cs index 66fd3beb9..69be68ced 100644 --- a/Assembly-CSharp/RimWorld/GenStep_ScatterRuinsSimple.cs +++ b/Assembly-CSharp/RimWorld/GenStep_ScatterRuinsSimple.cs @@ -1,5 +1,4 @@ using RimWorld.BaseGen; -using System; using System.Collections.Generic; using Verse; @@ -13,20 +12,29 @@ public class GenStep_ScatterRuinsSimple : GenStep_Scatterer protected override bool CanScatterAt(IntVec3 c, Map map) { - return base.CanScatterAt(c, map) && c.SupportsStructureType(map, TerrainAffordance.Heavy); + if (!base.CanScatterAt(c, map)) + { + return false; + } + if (!c.SupportsStructureType(map, TerrainAffordance.Heavy)) + { + return false; + } + return true; } protected bool CanPlaceAncientBuildingInRange(CellRect rect, Map map) { - foreach (IntVec3 current in rect.Cells) + foreach (IntVec3 cell in rect.Cells) { - if (current.InBounds(map)) + if (cell.InBounds(map)) { - TerrainDef terrainDef = map.terrainGrid.TerrainAt(current); - if (terrainDef.HasTag("River") || terrainDef.HasTag("Road")) + TerrainDef terrainDef = map.terrainGrid.TerrainAt(cell); + if (!terrainDef.HasTag("River") && !terrainDef.HasTag("Road")) { - return false; + continue; } + return false; } } return true; @@ -39,7 +47,7 @@ protected override void ScatterAt(IntVec3 c, Map map, int stackCount = 1) { bool @bool = Rand.Bool; int randomInRange = this.WallLengthRange.RandomInRange; - CellRect cellRect = new CellRect(c.x, c.z, (!@bool) ? 1 : randomInRange, (!@bool) ? randomInRange : 1); + CellRect cellRect = new CellRect(c.x, c.z, (!@bool) ? 1 : randomInRange, @bool ? 1 : randomInRange); if (this.CanPlaceAncientBuildingInRange(cellRect.ExpandedBy(1), map)) { this.MakeLongWall(c, map, this.WallLengthRange.RandomInRange, @bool, stuffDef); @@ -47,13 +55,12 @@ protected override void ScatterAt(IntVec3 c, Map map, int stackCount = 1) } else { - CellRect cellRect2 = new CellRect(c.x, c.z, this.ShedSizeRange.RandomInRange, this.ShedSizeRange.RandomInRange); - CellRect rect = cellRect2.ClipInsideMap(map); + CellRect rect = new CellRect(c.x, c.z, this.ShedSizeRange.RandomInRange, this.ShedSizeRange.RandomInRange).ClipInsideMap(map); if (this.CanPlaceAncientBuildingInRange(rect, map)) { - BaseGen.globalSettings.map = map; - BaseGen.symbolStack.Push("ancientRuins", rect); - BaseGen.Generate(); + RimWorld.BaseGen.BaseGen.globalSettings.map = map; + RimWorld.BaseGen.BaseGen.symbolStack.Push("ancientRuins", rect); + RimWorld.BaseGen.BaseGen.Generate(); } } } @@ -61,16 +68,19 @@ protected override void ScatterAt(IntVec3 c, Map map, int stackCount = 1) private void TrySetCellAsWall(IntVec3 c, Map map, ThingDef stuffDef) { List thingList = c.GetThingList(map); - for (int i = 0; i < thingList.Count; i++) + int num = 0; + while (num < thingList.Count) { - if (!thingList[i].def.destroyable) + if (thingList[num].def.destroyable) { - return; + num++; + continue; } + return; } - for (int j = thingList.Count - 1; j >= 0; j--) + for (int num2 = thingList.Count - 1; num2 >= 0; num2--) { - thingList[j].Destroy(DestroyMode.Vanish); + thingList[num2].Destroy(DestroyMode.Vanish); } map.terrainGrid.SetTerrain(c, BaseGenUtility.CorrespondingTerrainDef(stuffDef, true)); Thing newThing = ThingMaker.MakeThing(ThingDefOf.Wall, stuffDef); @@ -81,24 +91,18 @@ private void MakeLongWall(IntVec3 start, Map map, int extendDist, bool horizonta { TerrainDef newTerr = BaseGenUtility.CorrespondingTerrainDef(stuffDef, true); IntVec3 intVec = start; - for (int i = 0; i < extendDist; i++) + int num = 0; + while (num < extendDist && intVec.InBounds(map)) { - if (!intVec.InBounds(map)) - { - return; - } this.TrySetCellAsWall(intVec, map, stuffDef); if (Rand.Chance(0.4f)) { - for (int j = 0; j < 9; j++) + for (int i = 0; i < 9; i++) { - IntVec3 c = intVec + GenAdj.AdjacentCellsAndInside[j]; - if (c.InBounds(map)) + IntVec3 c = intVec + GenAdj.AdjacentCellsAndInside[i]; + if (c.InBounds(map) && Rand.Bool) { - if (Rand.Bool) - { - map.terrainGrid.SetTerrain(c, newTerr); - } + map.terrainGrid.SetTerrain(c, newTerr); } } } @@ -110,6 +114,7 @@ private void MakeLongWall(IntVec3 start, Map map, int extendDist, bool horizonta { intVec.z++; } + num++; } } } diff --git a/Assembly-CSharp/RimWorld/GenStep_ScatterShrines.cs b/Assembly-CSharp/RimWorld/GenStep_ScatterShrines.cs index 9136b4952..1cf7e3d48 100644 --- a/Assembly-CSharp/RimWorld/GenStep_ScatterShrines.cs +++ b/Assembly-CSharp/RimWorld/GenStep_ScatterShrines.cs @@ -1,5 +1,4 @@ using RimWorld.BaseGen; -using System; using System.Collections.Generic; using Verse; @@ -22,7 +21,11 @@ protected override bool CanScatterAt(IntVec3 c, Map map) return false; } Building edifice = c.GetEdifice(map); - return edifice != null && edifice.def.building.isNaturalRock; + if (edifice != null && edifice.def.building.isNaturalRock) + { + return true; + } + return false; } protected override void ScatterAt(IntVec3 loc, Map map, int stackCount = 1) @@ -38,38 +41,41 @@ protected override void ScatterAt(IntVec3 loc, Map map, int stackCount = 1) int num5 = num3 + 2 + randomInRange3; CellRect rect = new CellRect(loc.x, loc.z, num4, num5); rect.ClipInsideMap(map); - if (rect.Width != num4 || rect.Height != num5) + if (rect.Width == num4 && rect.Height == num5) { - return; - } - foreach (IntVec3 current in rect.Cells) - { - List list = map.thingGrid.ThingsListAt(current); - for (int i = 0; i < list.Count; i++) + foreach (IntVec3 cell in rect.Cells) { - if (list[i].def == ThingDefOf.AncientCryptosleepCasket) + List list = map.thingGrid.ThingsListAt(cell); + int num6 = 0; + while (num6 < list.Count) { + if (list[num6].def != ThingDefOf.AncientCryptosleepCasket) + { + num6++; + continue; + } return; } } + if (base.CanPlaceAncientBuildingInRange(rect, map)) + { + ResolveParams resolveParams = new ResolveParams + { + rect = rect, + disableSinglePawn = new bool?(true), + disableHives = new bool?(true), + ancientTempleEntranceHeight = new int?(randomInRange3) + }; + RimWorld.BaseGen.BaseGen.globalSettings.map = map; + RimWorld.BaseGen.BaseGen.symbolStack.Push("ancientTemple", resolveParams); + RimWorld.BaseGen.BaseGen.Generate(); + RectTrigger rectTrigger = (RectTrigger)ThingMaker.MakeThing(ThingDefOf.RectTrigger, null); + rectTrigger.Rect = rect.ExpandedBy(1).ClipInsideMap(map); + rectTrigger.letter = LetterMaker.MakeLetter("LetterLabelAncientShrineWarning".Translate(), "AncientShrineWarning".Translate(), LetterDefOf.BadNonUrgent, new TargetInfo(rect.CenterCell, map, false)); + rectTrigger.destroyIfUnfogged = true; + GenSpawn.Spawn(rectTrigger, rect.CenterCell, map); + } } - if (!base.CanPlaceAncientBuildingInRange(rect, map)) - { - return; - } - ResolveParams resolveParams = default(ResolveParams); - resolveParams.rect = rect; - resolveParams.disableSinglePawn = new bool?(true); - resolveParams.disableHives = new bool?(true); - resolveParams.ancientTempleEntranceHeight = new int?(randomInRange3); - BaseGen.globalSettings.map = map; - BaseGen.symbolStack.Push("ancientTemple", resolveParams); - BaseGen.Generate(); - RectTrigger rectTrigger = (RectTrigger)ThingMaker.MakeThing(ThingDefOf.RectTrigger, null); - rectTrigger.Rect = rect.ExpandedBy(1).ClipInsideMap(map); - rectTrigger.letter = LetterMaker.MakeLetter("LetterLabelAncientShrineWarning".Translate(), "AncientShrineWarning".Translate(), LetterDefOf.BadNonUrgent, new TargetInfo(rect.CenterCell, map, false)); - rectTrigger.destroyIfUnfogged = true; - GenSpawn.Spawn(rectTrigger, rect.CenterCell, map); } } } diff --git a/Assembly-CSharp/RimWorld/GenStep_ScenParts.cs b/Assembly-CSharp/RimWorld/GenStep_ScenParts.cs index f170d414e..beb325475 100644 --- a/Assembly-CSharp/RimWorld/GenStep_ScenParts.cs +++ b/Assembly-CSharp/RimWorld/GenStep_ScenParts.cs @@ -1,4 +1,3 @@ -using System; using Verse; namespace RimWorld diff --git a/Assembly-CSharp/RimWorld/GenStep_Snow.cs b/Assembly-CSharp/RimWorld/GenStep_Snow.cs index 2cc20d2fd..4124e6128 100644 --- a/Assembly-CSharp/RimWorld/GenStep_Snow.cs +++ b/Assembly-CSharp/RimWorld/GenStep_Snow.cs @@ -1,4 +1,3 @@ -using System; using Verse; namespace RimWorld @@ -8,16 +7,16 @@ public class GenStep_Snow : GenStep public override void Generate(Map map) { int num = 0; - for (int i = (int)(GenLocalDate.Twelfth(map) - Twelfth.Third); i <= (int)GenLocalDate.Twelfth(map); i++) + for (int i = (int)(GenLocalDate.Twelfth(map) - 2); i <= (int)GenLocalDate.Twelfth(map); i++) { int num2 = i; if (num2 < 0) { num2 += 12; } - Twelfth twelfth = (Twelfth)num2; + Twelfth twelfth = (Twelfth)(byte)num2; float num3 = GenTemperature.AverageTemperatureAtTileForTwelfth(map.Tile, twelfth); - if (num3 < 0f) + if (num3 < 0.0) { num++; } @@ -28,28 +27,33 @@ public override void Generate(Map map) case 0: return; case 1: + { num4 = 0.3f; break; + } case 2: + { num4 = 0.7f; break; + } case 3: + { num4 = 1f; break; } - if (map.mapTemperature.SeasonalTemp > 0f) - { - num4 *= 0.4f; } - if ((double)num4 < 0.3) + if (map.mapTemperature.SeasonalTemp > 0.0) { - return; + num4 = (float)(num4 * 0.40000000596046448); } - foreach (IntVec3 current in map.AllCells) + if (!((double)num4 < 0.3)) { - if (!current.Roofed(map)) + foreach (IntVec3 allCell in map.AllCells) { - map.steadyAtmosphereEffects.AddFallenSnowAt(current, num4); + if (!allCell.Roofed(map)) + { + map.steadyAtmosphereEffects.AddFallenSnowAt(allCell, num4); + } } } } diff --git a/Assembly-CSharp/RimWorld/GenStep_Terrain.cs b/Assembly-CSharp/RimWorld/GenStep_Terrain.cs index 100f18b0f..820d0d803 100644 --- a/Assembly-CSharp/RimWorld/GenStep_Terrain.cs +++ b/Assembly-CSharp/RimWorld/GenStep_Terrain.cs @@ -19,30 +19,32 @@ public override void Generate(Map map) MapGenFloatGrid mapGenFloatGrid = MapGenerator.FloatGridNamed("Elevation", map); MapGenFloatGrid mapGenFloatGrid2 = MapGenerator.FloatGridNamed("Fertility", map); TerrainGrid terrainGrid = map.terrainGrid; - foreach (IntVec3 current in map.AllCells) + foreach (IntVec3 allCell in map.AllCells) { - Building edifice = current.GetEdifice(map); - TerrainDef terrainDef; - if (edifice != null && edifice.def.Fillage == FillCategory.Full) - { - terrainDef = this.TerrainFrom(current, map, mapGenFloatGrid[current], mapGenFloatGrid2[current], river, true); - } - else - { - terrainDef = this.TerrainFrom(current, map, mapGenFloatGrid[current], mapGenFloatGrid2[current], river, false); - } + Building edifice = allCell.GetEdifice(map); + TerrainDef terrainDef = null; + terrainDef = ((edifice == null || edifice.def.Fillage != FillCategory.Full) ? this.TerrainFrom(allCell, map, mapGenFloatGrid[allCell], mapGenFloatGrid2[allCell], river, false) : this.TerrainFrom(allCell, map, mapGenFloatGrid[allCell], mapGenFloatGrid2[allCell], river, true)); if ((terrainDef == TerrainDefOf.WaterMovingShallow || terrainDef == TerrainDefOf.WaterMovingDeep) && edifice != null) { list.Add(edifice.Position); edifice.Destroy(DestroyMode.Vanish); } - terrainGrid.SetTerrain(current, terrainDef); + terrainGrid.SetTerrain(allCell, terrainDef); } RoofCollapseCellsFinder.RemoveBulkCollapsingRoofs(list, map); BeachMaker.Cleanup(); - foreach (TerrainPatchMaker current2 in map.Biome.terrainPatchMakers) + List.Enumerator enumerator2 = map.Biome.terrainPatchMakers.GetEnumerator(); + try + { + while (enumerator2.MoveNext()) + { + TerrainPatchMaker current2 = enumerator2.Current; + current2.Cleanup(); + } + } + finally { - current2.Cleanup(); + ((IDisposable)(object)enumerator2).Dispose(); } } @@ -62,82 +64,92 @@ private TerrainDef TerrainFrom(IntVec3 c, Map map, float elevation, float fertil { return terrainDef2; } - if (terrainDef == TerrainDefOf.WaterMovingShallow || terrainDef == TerrainDefOf.WaterMovingDeep) - { - return terrainDef; - } - if (terrainDef2 != null) - { - return terrainDef2; - } - if (terrainDef != null) - { - return terrainDef; - } - for (int i = 0; i < map.Biome.terrainPatchMakers.Count; i++) + if (terrainDef != TerrainDefOf.WaterMovingShallow && terrainDef != TerrainDefOf.WaterMovingDeep) { - terrainDef2 = map.Biome.terrainPatchMakers[i].TerrainAt(c, map); if (terrainDef2 != null) { return terrainDef2; } - } - if (elevation > 0.55f && elevation < 0.61f) - { - return TerrainDefOf.Gravel; - } - if (elevation >= 0.61f) - { - return GenStep_RocksFromGrid.RockDefAt(c).naturalTerrain; - } - terrainDef2 = TerrainThreshold.TerrainAtValue(map.Biome.terrainsByFertility, fertility); - if (terrainDef2 != null) - { - return terrainDef2; - } - if (!GenStep_Terrain.debug_WarnedMissingTerrain) - { - Log.Error(string.Concat(new object[] + if (terrainDef != null) + { + return terrainDef; + } + for (int i = 0; i < map.Biome.terrainPatchMakers.Count; i++) + { + terrainDef2 = map.Biome.terrainPatchMakers[i].TerrainAt(c, map); + if (terrainDef2 != null) + { + return terrainDef2; + } + } + if (elevation > 0.550000011920929 && elevation < 0.61000001430511475) + { + return TerrainDefOf.Gravel; + } + if (elevation >= 0.61000001430511475) + { + return GenStep_RocksFromGrid.RockDefAt(c).naturalTerrain; + } + terrainDef2 = TerrainThreshold.TerrainAtValue(map.Biome.terrainsByFertility, fertility); + if (terrainDef2 != null) + { + return terrainDef2; + } + if (!GenStep_Terrain.debug_WarnedMissingTerrain) { - "No terrain found in biome ", - map.Biome.defName, - " for elevation=", - elevation, - ", fertility=", - fertility - })); - GenStep_Terrain.debug_WarnedMissingTerrain = true; + Log.Error("No terrain found in biome " + map.Biome.defName + " for elevation=" + elevation + ", fertility=" + fertility); + GenStep_Terrain.debug_WarnedMissingTerrain = true; + } + return TerrainDefOf.Sand; } - return TerrainDefOf.Sand; + return terrainDef; } private RiverMaker GenerateRiver(Map map) { Tile tile = Find.WorldGrid[map.Tile]; List visibleRivers = tile.VisibleRivers; - if (visibleRivers == null || visibleRivers.Count == 0) - { - return null; - } - float headingFromTo; - float angleB; - if (visibleRivers.Count == 1) - { - headingFromTo = Find.WorldGrid.GetHeadingFromTo(map.Tile, visibleRivers[0].neighbor); - angleB = headingFromTo + 180f; - } - else + if (((visibleRivers != null) ? visibleRivers.Count : 0) != 0) { - List list = (from rl in visibleRivers + float num = 0f; + float num2 = 0f; + if (visibleRivers.Count == 1) + { + WorldGrid worldGrid = Find.WorldGrid; + int tile2 = map.Tile; + Tile.RiverLink riverLink = visibleRivers[0]; + num = worldGrid.GetHeadingFromTo(tile2, riverLink.neighbor); + num2 = (float)(num + 180.0); + } + else + { + List list = (from rl in visibleRivers + orderby -rl.river.degradeThreshold + select rl).ToList(); + WorldGrid worldGrid2 = Find.WorldGrid; + int tile3 = map.Tile; + Tile.RiverLink riverLink2 = list[0]; + num = worldGrid2.GetHeadingFromTo(tile3, riverLink2.neighbor); + WorldGrid worldGrid3 = Find.WorldGrid; + int tile4 = map.Tile; + Tile.RiverLink riverLink3 = list[1]; + num2 = worldGrid3.GetHeadingFromTo(tile4, riverLink3.neighbor); + } + float num3 = Rand.Range(0.3f, 0.7f); + IntVec3 size = map.Size; + float x = num3 * (float)size.x; + float num4 = Rand.Range(0.3f, 0.7f); + IntVec3 size2 = map.Size; + Vector3 vector = new Vector3(x, 0f, num4 * (float)size2.z); + Vector3 center = vector; + float angleA = num; + float angleB = num2; + Tile.RiverLink riverLink4 = (from rl in visibleRivers orderby -rl.river.degradeThreshold - select rl).ToList(); - headingFromTo = Find.WorldGrid.GetHeadingFromTo(map.Tile, list[0].neighbor); - angleB = Find.WorldGrid.GetHeadingFromTo(map.Tile, list[1].neighbor); + select rl).FirstOrDefault(); + return new RiverMaker(center, angleA, angleB, riverLink4.river); } - Vector3 center = new Vector3(Rand.Range(0.3f, 0.7f) * (float)map.Size.x, 0f, Rand.Range(0.3f, 0.7f) * (float)map.Size.z); - return new RiverMaker(center, headingFromTo, angleB, (from rl in visibleRivers - orderby -rl.river.degradeThreshold - select rl).FirstOrDefault().river); + return null; } } } diff --git a/Assembly-CSharp/RimWorld/GenStep_Turrets.cs b/Assembly-CSharp/RimWorld/GenStep_Turrets.cs index b89f801b3..f523d30d0 100644 --- a/Assembly-CSharp/RimWorld/GenStep_Turrets.cs +++ b/Assembly-CSharp/RimWorld/GenStep_Turrets.cs @@ -20,42 +20,39 @@ public class GenStep_Turrets : GenStep public override void Generate(Map map) { - CellRect cellRect; + CellRect cellRect = default(CellRect); if (!MapGenerator.TryGetVar("RectOfInterest", out cellRect)) { cellRect = this.FindRandomRectToDefend(map); } - Faction faction; - if (map.ParentFaction == null || map.ParentFaction == Faction.OfPlayer) - { - faction = (from x in Find.FactionManager.AllFactions - where !x.defeated && x.HostileTo(Faction.OfPlayer) && !x.def.hidden && x.def.techLevel >= TechLevel.Industrial - select x).RandomElementWithFallback(Find.FactionManager.RandomEnemyFaction(false, false, true)); - } - else - { - faction = map.ParentFaction; - } + Faction faction = (map.ParentFaction != null && map.ParentFaction != Faction.OfPlayer) ? map.ParentFaction : (from x in Find.FactionManager.AllFactions + where !x.defeated && x.HostileTo(Faction.OfPlayer) && !x.def.hidden && (int)x.def.techLevel >= 4 + select x).RandomElementWithFallback(Find.FactionManager.RandomEnemyFaction(false, false, true)); int randomInRange = this.widthRange.RandomInRange; CellRect rect = cellRect.ExpandedBy(7 + randomInRange).ClipInsideMap(map); - ResolveParams resolveParams = default(ResolveParams); - resolveParams.rect = rect; - resolveParams.faction = faction; - resolveParams.edgeDefenseWidth = new int?(randomInRange); - resolveParams.edgeDefenseTurretsCount = new int?(this.turretsCountRange.RandomInRange); - resolveParams.edgeDefenseMortarsCount = new int?(this.mortarsCountRange.RandomInRange); - resolveParams.edgeDefenseGuardsCount = new int?(this.guardsCountRange.RandomInRange); - BaseGen.globalSettings.map = map; - BaseGen.symbolStack.Push("edgeDefense", resolveParams); - BaseGen.Generate(); + ResolveParams resolveParams = new ResolveParams + { + rect = rect, + faction = faction, + edgeDefenseWidth = new int?(randomInRange), + edgeDefenseTurretsCount = new int?(this.turretsCountRange.RandomInRange), + edgeDefenseMortarsCount = new int?(this.mortarsCountRange.RandomInRange), + edgeDefenseGuardsCount = new int?(this.guardsCountRange.RandomInRange) + }; + RimWorld.BaseGen.BaseGen.globalSettings.map = map; + RimWorld.BaseGen.BaseGen.symbolStack.Push("edgeDefense", resolveParams); + RimWorld.BaseGen.BaseGen.Generate(); } private CellRect FindRandomRectToDefend(Map map) { - int rectRadius = Mathf.Max(Mathf.RoundToInt((float)Mathf.Min(map.Size.x, map.Size.z) * 0.07f), 1); + IntVec3 size = map.Size; + int x2 = size.x; + IntVec3 size2 = map.Size; + int rectRadius = Mathf.Max(Mathf.RoundToInt((float)((float)Mathf.Min(x2, size2.z) * 0.070000000298023224)), 1); TraverseParms traverseParams = TraverseParms.For(TraverseMode.PassDoors, Danger.Deadly, false); - IntVec3 center; - if (RCellFinder.TryFindRandomCellNearTheCenterOfTheMapWith(delegate(IntVec3 x) + IntVec3 center = default(IntVec3); + if (RCellFinder.TryFindRandomCellNearTheCenterOfTheMapWith((Predicate)delegate(IntVec3 x) { if (!map.reachability.CanReachMapEdge(x, traverseParams)) { @@ -76,12 +73,12 @@ private CellRect FindRandomRectToDefend(Map map) } iterator.MoveNext(); } - return (float)num / (float)cellRect.Area >= 0.6f; + return (float)num / (float)cellRect.Area >= 0.60000002384185791; }, map, out center)) { return CellRect.CenteredOn(center, rectRadius); } - if (RCellFinder.TryFindRandomCellNearTheCenterOfTheMapWith((IntVec3 x) => x.Standable(map), map, out center)) + if (RCellFinder.TryFindRandomCellNearTheCenterOfTheMapWith((Predicate)((IntVec3 x) => x.Standable(map)), map, out center)) { return CellRect.CenteredOn(center, rectRadius); } diff --git a/Assembly-CSharp/RimWorld/GenStuff.cs b/Assembly-CSharp/RimWorld/GenStuff.cs index 1632f3d41..4b8574865 100644 --- a/Assembly-CSharp/RimWorld/GenStuff.cs +++ b/Assembly-CSharp/RimWorld/GenStuff.cs @@ -1,6 +1,4 @@ -using System; using System.Collections.Generic; -using System.Diagnostics; using Verse; namespace RimWorld @@ -47,18 +45,23 @@ public static ThingDef RandomStuffFor(ThingDef td) { return null; } - return GenStuff.AllowedStuffsFor(td).RandomElement(); + return GenStuff.AllowedStuffsFor(td).RandomElement(); } - [DebuggerHidden] public static IEnumerable AllowedStuffsFor(ThingDef td) { - GenStuff.c__Iterator1AA c__Iterator1AA = new GenStuff.c__Iterator1AA(); - c__Iterator1AA.td = td; - c__Iterator1AA.<$>td = td; - GenStuff.c__Iterator1AA expr_15 = c__Iterator1AA; - expr_15.$PC = -2; - return expr_15; + if (td.MadeFromStuff) + { + List allDefs = DefDatabase.AllDefsListForReading; + for (int i = 0; i < allDefs.Count; i++) + { + ThingDef d = allDefs[i]; + if (d.IsStuff && d.stuffProps.CanMake(td)) + { + yield return d; + } + } + } } } } diff --git a/Assembly-CSharp/RimWorld/GenThing.cs b/Assembly-CSharp/RimWorld/GenThing.cs index e3d0931fb..850d0e91e 100644 --- a/Assembly-CSharp/RimWorld/GenThing.cs +++ b/Assembly-CSharp/RimWorld/GenThing.cs @@ -7,7 +7,7 @@ public static class GenThing { public static bool TryDropAndSetForbidden(Thing th, IntVec3 pos, Map map, ThingPlaceMode mode, out Thing resultingThing, bool forbidden) { - if (GenDrop.TryDropSpawn(th, pos, map, ThingPlaceMode.Near, out resultingThing, null)) + if (GenDrop.TryDropSpawn(th, pos, map, ThingPlaceMode.Near, out resultingThing, (Action)null)) { if (resultingThing != null) { diff --git a/Assembly-CSharp/RimWorld/GenWorld.cs b/Assembly-CSharp/RimWorld/GenWorld.cs index d5714354c..e5bf7fbaa 100644 --- a/Assembly-CSharp/RimWorld/GenWorld.cs +++ b/Assembly-CSharp/RimWorld/GenWorld.cs @@ -1,5 +1,4 @@ using RimWorld.Planet; -using System; using System.Collections.Generic; using UnityEngine; using Verse; @@ -37,7 +36,7 @@ public static int TileAt(Vector2 clickPos, bool snapToExpandableWorldObjects = f if (snapToExpandableWorldObjects) { ExpandableWorldObjectsUtility.GetExpandedWorldObjectUnderMouse(UI.MousePositionOnUI, GenWorld.tmpWorldObjectsUnderMouse); - if (GenWorld.tmpWorldObjectsUnderMouse.Any()) + if (GenWorld.tmpWorldObjectsUnderMouse.Any()) { int tile = GenWorld.tmpWorldObjectsUnderMouse[0].Tile; GenWorld.tmpWorldObjectsUnderMouse.Clear(); @@ -46,7 +45,7 @@ public static int TileAt(Vector2 clickPos, bool snapToExpandableWorldObjects = f } Ray ray = worldCamera.ScreenPointToRay(clickPos * Prefs.UIScale); int worldLayerMask = WorldCameraManager.WorldLayerMask; - RaycastHit hit; + RaycastHit hit = default(RaycastHit); if (Physics.Raycast(ray, out hit, 1500f, worldLayerMask)) { return Find.World.renderer.GetTileIDFromRayHit(hit); diff --git a/Assembly-CSharp/RimWorld/GenderPossibility.cs b/Assembly-CSharp/RimWorld/GenderPossibility.cs index 8e26a0871..c4823cddb 100644 --- a/Assembly-CSharp/RimWorld/GenderPossibility.cs +++ b/Assembly-CSharp/RimWorld/GenderPossibility.cs @@ -1,11 +1,9 @@ -using System; - namespace RimWorld { public enum GenderPossibility : byte { - Male, - Female, - Either + Male = 0, + Female = 1, + Either = 2 } } diff --git a/Assembly-CSharp/RimWorld/GiveToPackAnimalUtility.cs b/Assembly-CSharp/RimWorld/GiveToPackAnimalUtility.cs index 2e5a5cdc8..5ce423b10 100644 --- a/Assembly-CSharp/RimWorld/GiveToPackAnimalUtility.cs +++ b/Assembly-CSharp/RimWorld/GiveToPackAnimalUtility.cs @@ -1,4 +1,3 @@ -using System; using System.Collections.Generic; using Verse; diff --git a/Assembly-CSharp/RimWorld/Gizmo_EnergyShieldStatus.cs b/Assembly-CSharp/RimWorld/Gizmo_EnergyShieldStatus.cs index 0b33a44a3..71f74a255 100644 --- a/Assembly-CSharp/RimWorld/Gizmo_EnergyShieldStatus.cs +++ b/Assembly-CSharp/RimWorld/Gizmo_EnergyShieldStatus.cs @@ -24,20 +24,20 @@ public override float Width public override GizmoResult GizmoOnGUI(Vector2 topLeft) { Rect overRect = new Rect(topLeft.x, topLeft.y, this.Width, 75f); - Find.WindowStack.ImmediateWindow(984688, overRect, WindowLayer.GameUI, delegate + Find.WindowStack.ImmediateWindow(984688, overRect, WindowLayer.GameUI, (Action)delegate { - Rect rect = overRect.AtZero().ContractedBy(6f); - Rect rect2 = rect; - rect2.height = overRect.height / 2f; + Rect rect; + Rect rect2 = rect = overRect.AtZero().ContractedBy(6f); + rect.height = (float)(overRect.height / 2.0); Text.Font = GameFont.Tiny; - Widgets.Label(rect2, this.shield.LabelCap); - Rect rect3 = rect; - rect3.yMin = overRect.height / 2f; + Widgets.Label(rect, this.shield.LabelCap); + Rect rect3 = rect2; + rect3.yMin = (float)(overRect.height / 2.0); float fillPercent = this.shield.Energy / Mathf.Max(1f, this.shield.GetStatValue(StatDefOf.EnergyShieldEnergyMax, true)); Widgets.FillableBar(rect3, fillPercent, Gizmo_EnergyShieldStatus.FullShieldBarTex, Gizmo_EnergyShieldStatus.EmptyShieldBarTex, false); Text.Font = GameFont.Small; Text.Anchor = TextAnchor.MiddleCenter; - Widgets.Label(rect3, (this.shield.Energy * 100f).ToString("F0") + " / " + (this.shield.GetStatValue(StatDefOf.EnergyShieldEnergyMax, true) * 100f).ToString("F0")); + Widgets.Label(rect3, ((float)(this.shield.Energy * 100.0)).ToString("F0") + " / " + ((float)(this.shield.GetStatValue(StatDefOf.EnergyShieldEnergyMax, true) * 100.0)).ToString("F0")); Text.Anchor = TextAnchor.UpperLeft; }, true, false, 1f); return new GizmoResult(GizmoState.Clear); diff --git a/Assembly-CSharp/RimWorld/Gizmo_RefuelableFuelStatus.cs b/Assembly-CSharp/RimWorld/Gizmo_RefuelableFuelStatus.cs index f8bc1b538..7b7f3297f 100644 --- a/Assembly-CSharp/RimWorld/Gizmo_RefuelableFuelStatus.cs +++ b/Assembly-CSharp/RimWorld/Gizmo_RefuelableFuelStatus.cs @@ -28,23 +28,23 @@ public override float Width public override GizmoResult GizmoOnGUI(Vector2 topLeft) { Rect overRect = new Rect(topLeft.x, topLeft.y, this.Width, 75f); - Find.WindowStack.ImmediateWindow(1523289473, overRect, WindowLayer.GameUI, delegate + Find.WindowStack.ImmediateWindow(1523289473, overRect, WindowLayer.GameUI, (Action)delegate { - Rect rect = overRect.AtZero().ContractedBy(6f); - Rect rect2 = rect; - rect2.height = overRect.height / 2f; + Rect rect; + Rect rect2 = rect = overRect.AtZero().ContractedBy(6f); + rect.height = (float)(overRect.height / 2.0); Text.Font = GameFont.Tiny; - Widgets.Label(rect2, "FuelLevelGizmoLabel".Translate()); - Rect rect3 = rect; - rect3.yMin = overRect.height / 2f; + Widgets.Label(rect, "FuelLevelGizmoLabel".Translate()); + Rect rect3 = rect2; + rect3.yMin = (float)(overRect.height / 2.0); float fillPercent = this.refuelable.Fuel / this.refuelable.Props.fuelCapacity; Widgets.FillableBar(rect3, fillPercent, Gizmo_RefuelableFuelStatus.FullBarTex, Gizmo_RefuelableFuelStatus.EmptyBarTex, false); if (this.refuelable.Props.targetFuelLevelConfigurable) { float num = this.refuelable.TargetFuelLevel / this.refuelable.Props.fuelCapacity; - float x = rect3.x + num * rect3.width - (float)Gizmo_RefuelableFuelStatus.TargetLevelArrow.width * 0.5f / 2f; - float y = rect3.y - (float)Gizmo_RefuelableFuelStatus.TargetLevelArrow.height * 0.5f; - GUI.DrawTexture(new Rect(x, y, (float)Gizmo_RefuelableFuelStatus.TargetLevelArrow.width * 0.5f, (float)Gizmo_RefuelableFuelStatus.TargetLevelArrow.height * 0.5f), Gizmo_RefuelableFuelStatus.TargetLevelArrow); + float x = (float)(rect3.x + num * rect3.width - (float)Gizmo_RefuelableFuelStatus.TargetLevelArrow.width * 0.5 / 2.0); + float y = (float)(rect3.y - (float)Gizmo_RefuelableFuelStatus.TargetLevelArrow.height * 0.5); + GUI.DrawTexture(new Rect(x, y, (float)((float)Gizmo_RefuelableFuelStatus.TargetLevelArrow.width * 0.5), (float)((float)Gizmo_RefuelableFuelStatus.TargetLevelArrow.height * 0.5)), Gizmo_RefuelableFuelStatus.TargetLevelArrow); } Text.Font = GameFont.Small; Text.Anchor = TextAnchor.MiddleCenter; diff --git a/Assembly-CSharp/RimWorld/GlobalControls.cs b/Assembly-CSharp/RimWorld/GlobalControls.cs index 7e0cbf266..9f3587dae 100644 --- a/Assembly-CSharp/RimWorld/GlobalControls.cs +++ b/Assembly-CSharp/RimWorld/GlobalControls.cs @@ -1,4 +1,3 @@ -using System; using UnityEngine; using Verse; @@ -12,68 +11,80 @@ public class GlobalControls public void GlobalControlsOnGUI() { - if (Event.current.type == EventType.Layout) + if (Event.current.type != EventType.Layout) { - return; - } - float num = (float)UI.screenWidth - 200f; - float num2 = (float)UI.screenHeight; - num2 -= 35f; - GenUI.DrawTextWinterShadow(new Rect((float)(UI.screenWidth - 270), (float)(UI.screenHeight - 450), 270f, 450f)); - num2 -= 4f; - GlobalControlsUtility.DoPlaySettings(this.rowVisibility, false, ref num2); - num2 -= 4f; - GlobalControlsUtility.DoTimespeedControls(num, 200f, ref num2); - num2 -= 4f; - GlobalControlsUtility.DoDate(num, 200f, ref num2); - Rect rect = new Rect(num - 30f, num2 - 26f, 230f, 26f); - Find.VisibleMap.weatherManager.DoWeatherGUI(rect); - num2 -= rect.height; - Rect rect2 = new Rect(num - 100f, num2 - 26f, 293f, 26f); - Text.Anchor = TextAnchor.MiddleRight; - Widgets.Label(rect2, GlobalControls.TemperatureString()); - Text.Anchor = TextAnchor.UpperLeft; - num2 -= 26f; - float num3 = 230f; - float num4 = Find.VisibleMap.gameConditionManager.TotalHeightAt(num3 - 15f); - Rect rect3 = new Rect(num - 30f, num2 - num4, num3, num4); - Find.VisibleMap.gameConditionManager.DoConditionsUI(rect3); - num2 -= rect3.height; - if (Prefs.ShowRealtimeClock) - { - GlobalControlsUtility.DoRealtimeClock(num, 200f, ref num2); - } - if (Find.VisibleMap.info.parent.ForceExitAndRemoveMapCountdownActive) - { - Rect rect4 = new Rect(num, num2 - 26f, 193f, 26f); + float num = (float)((float)UI.screenWidth - 200.0); + float num2 = (float)UI.screenHeight; + num2 = (float)(num2 - 35.0); + GenUI.DrawTextWinterShadow(new Rect((float)(UI.screenWidth - 270), (float)(UI.screenHeight - 450), 270f, 450f)); + num2 = (float)(num2 - 4.0); + GlobalControlsUtility.DoPlaySettings(this.rowVisibility, false, ref num2); + num2 = (float)(num2 - 4.0); + GlobalControlsUtility.DoTimespeedControls(num, 200f, ref num2); + num2 = (float)(num2 - 4.0); + GlobalControlsUtility.DoDate(num, 200f, ref num2); + Rect rect = new Rect((float)(num - 30.0), (float)(num2 - 26.0), 230f, 26f); + Find.VisibleMap.weatherManager.DoWeatherGUI(rect); + num2 -= rect.height; + Rect rect2 = new Rect((float)(num - 100.0), (float)(num2 - 26.0), 293f, 26f); Text.Anchor = TextAnchor.MiddleRight; - GlobalControls.DoCountdownTimer(rect4); + Widgets.Label(rect2, GlobalControls.TemperatureString()); Text.Anchor = TextAnchor.UpperLeft; - num2 -= 26f; + num2 = (float)(num2 - 26.0); + float num3 = 230f; + float num4 = Find.VisibleMap.gameConditionManager.TotalHeightAt((float)(num3 - 15.0)); + Rect rect3 = new Rect((float)(num - 30.0), num2 - num4, num3, num4); + Find.VisibleMap.gameConditionManager.DoConditionsUI(rect3); + num2 -= rect3.height; + if (Prefs.ShowRealtimeClock) + { + GlobalControlsUtility.DoRealtimeClock(num, 200f, ref num2); + } + if (Find.VisibleMap.info.parent.ForceExitAndRemoveMapCountdownActive) + { + Rect rect4 = new Rect(num, (float)(num2 - 26.0), 193f, 26f); + Text.Anchor = TextAnchor.MiddleRight; + GlobalControls.DoCountdownTimer(rect4); + Text.Anchor = TextAnchor.UpperLeft; + num2 = (float)(num2 - 26.0); + } + num2 = (float)(num2 - 10.0); + Find.LetterStack.LettersOnGUI(num2); } - num2 -= 10f; - Find.LetterStack.LettersOnGUI(num2); } private static string TemperatureString() { - IntVec3 intVec = UI.MouseCell(); - IntVec3 c = intVec; + IntVec3 c; + IntVec3 intVec = c = UI.MouseCell(); Room room = intVec.GetRoom(Find.VisibleMap, RegionType.Set_All); if (room == null) { for (int i = 0; i < 9; i++) { IntVec3 intVec2 = intVec + GenAdj.AdjacentCellsAndInside[i]; + Room room2; if (intVec2.InBounds(Find.VisibleMap)) { - Room room2 = intVec2.GetRoom(Find.VisibleMap, RegionType.Set_All); - if (room2 != null && ((!room2.PsychologicallyOutdoors && !room2.UsesOutdoorTemperature) || (!room2.PsychologicallyOutdoors && (room == null || room.PsychologicallyOutdoors)) || (room2.PsychologicallyOutdoors && room == null))) + room2 = intVec2.GetRoom(Find.VisibleMap, RegionType.Set_All); + if (room2 != null) { - c = intVec2; - room = room2; + if (!room2.PsychologicallyOutdoors && !room2.UsesOutdoorTemperature) + { + goto IL_00a8; + } + if (!room2.PsychologicallyOutdoors && (room == null || room.PsychologicallyOutdoors)) + { + goto IL_00a8; + } + if (room2.PsychologicallyOutdoors && room == null) + goto IL_00a8; } } + continue; + IL_00a8: + c = intVec2; + room = room2; } } if (room == null && intVec.InBounds(Find.VisibleMap)) @@ -95,22 +106,7 @@ private static string TemperatureString() } } } - string str; - if (c.InBounds(Find.VisibleMap) && !c.Fogged(Find.VisibleMap) && room != null && !room.PsychologicallyOutdoors) - { - if (room.OpenRoofCount == 0) - { - str = "Indoors".Translate(); - } - else - { - str = "IndoorsUnroofed".Translate() + " (" + room.OpenRoofCount.ToStringCached() + ")"; - } - } - else - { - str = "Outdoors".Translate(); - } + string str = (!c.InBounds(Find.VisibleMap) || c.Fogged(Find.VisibleMap) || room == null || room.PsychologicallyOutdoors) ? "Outdoors".Translate() : ((room.OpenRoofCount != 0) ? ("IndoorsUnroofed".Translate() + " (" + room.OpenRoofCount.ToStringCached() + ")") : "Indoors".Translate()); float celsiusTemp = (room != null && !c.Fogged(Find.VisibleMap)) ? room.Temperature : Find.VisibleMap.mapTemperature.OutdoorTemp; return str + " " + celsiusTemp.ToStringTemperature("F0"); } @@ -118,20 +114,15 @@ private static string TemperatureString() private static void DoCountdownTimer(Rect rect) { string forceExitAndRemoveMapCountdownTimeLeftString = Find.VisibleMap.info.parent.ForceExitAndRemoveMapCountdownTimeLeftString; - string text = "ForceExitAndRemoveMapCountdown".Translate(new object[] - { - forceExitAndRemoveMapCountdownTimeLeftString - }); - float x = Text.CalcSize(text).x; + string text = "ForceExitAndRemoveMapCountdown".Translate(forceExitAndRemoveMapCountdownTimeLeftString); + Vector2 vector = Text.CalcSize(text); + float x = vector.x; Rect rect2 = new Rect(rect.xMax - x, rect.y, x, rect.height); if (Mouse.IsOver(rect2)) { Widgets.DrawHighlight(rect2); } - TooltipHandler.TipRegion(rect2, "ForceExitAndRemoveMapCountdownTip".Translate(new object[] - { - forceExitAndRemoveMapCountdownTimeLeftString - })); + TooltipHandler.TipRegion(rect2, "ForceExitAndRemoveMapCountdownTip".Translate(forceExitAndRemoveMapCountdownTimeLeftString)); Widgets.Label(rect2, text); } } diff --git a/Assembly-CSharp/RimWorld/GlobalControlsUtility.cs b/Assembly-CSharp/RimWorld/GlobalControlsUtility.cs index 21a28a860..fbb531e52 100644 --- a/Assembly-CSharp/RimWorld/GlobalControlsUtility.cs +++ b/Assembly-CSharp/RimWorld/GlobalControlsUtility.cs @@ -10,7 +10,9 @@ public static class GlobalControlsUtility public static void DoPlaySettings(WidgetRow rowVisibility, bool worldView, ref float curBaseY) { - float y = curBaseY - TimeControls.TimeButSize.y; + float num = curBaseY; + Vector2 timeButSize = TimeControls.TimeButSize; + float y = num - timeButSize.y; rowVisibility.Init((float)UI.screenWidth, y, UIDirection.LeftThenUp, 141f, 4f); Find.PlaySettings.DoPlaySettingsGlobalControls(rowVisibility, worldView); curBaseY = rowVisibility.FinalY; @@ -18,24 +20,25 @@ public static void DoPlaySettings(WidgetRow rowVisibility, bool worldView, ref f public static void DoTimespeedControls(float leftX, float width, ref float curBaseY) { - leftX += Mathf.Max(0f, width - 150f); + leftX += Mathf.Max(0f, (float)(width - 150.0)); width = Mathf.Min(width, 150f); - float y = TimeControls.TimeButSize.y; - Rect timerRect = new Rect(leftX + 16f, curBaseY - y, width, y); + Vector2 timeButSize = TimeControls.TimeButSize; + float y = timeButSize.y; + Rect timerRect = new Rect((float)(leftX + 16.0), curBaseY - y, width, y); TimeControls.DoTimeControlsGUI(timerRect); curBaseY -= timerRect.height; } public static void DoDate(float leftX, float width, ref float curBaseY) { - Rect dateRect = new Rect(leftX, curBaseY - 48f, width, 48f); + Rect dateRect = new Rect(leftX, (float)(curBaseY - 48.0), width, 48f); DateReadout.DateOnGUI(dateRect); curBaseY -= dateRect.height; } public static void DoRealtimeClock(float leftX, float width, ref float curBaseY) { - Rect rect = new Rect(leftX - 20f, curBaseY - 26f, width + 20f - 7f, 26f); + Rect rect = new Rect((float)(leftX - 20.0), (float)(curBaseY - 26.0), (float)(width + 20.0 - 7.0), 26f); Text.Anchor = TextAnchor.MiddleRight; Widgets.Label(rect, DateTime.Now.ToString("HH:mm")); Text.Anchor = TextAnchor.UpperLeft; diff --git a/Assembly-CSharp/RimWorld/Graphic_LinkedTransmitter.cs b/Assembly-CSharp/RimWorld/Graphic_LinkedTransmitter.cs index 7f8ba8ee4..1cef4d7ca 100644 --- a/Assembly-CSharp/RimWorld/Graphic_LinkedTransmitter.cs +++ b/Assembly-CSharp/RimWorld/Graphic_LinkedTransmitter.cs @@ -1,4 +1,3 @@ -using System; using UnityEngine; using Verse; @@ -12,7 +11,15 @@ public Graphic_LinkedTransmitter(Graphic subGraphic) : base(subGraphic) public override bool ShouldLinkWith(IntVec3 c, Thing parent) { - return c.InBounds(parent.Map) && (base.ShouldLinkWith(c, parent) || parent.Map.powerNetGrid.TransmittedPowerNetAt(c) != null); + if (!c.InBounds(parent.Map)) + { + return false; + } + if (!base.ShouldLinkWith(c, parent) && parent.Map.powerNetGrid.TransmittedPowerNetAt(c) == null) + { + return false; + } + return true; } public override void Print(SectionLayer layer, Thing thing) diff --git a/Assembly-CSharp/RimWorld/Graphic_LinkedTransmitterOverlay.cs b/Assembly-CSharp/RimWorld/Graphic_LinkedTransmitterOverlay.cs index 77fcd4e0d..f89c64e6a 100644 --- a/Assembly-CSharp/RimWorld/Graphic_LinkedTransmitterOverlay.cs +++ b/Assembly-CSharp/RimWorld/Graphic_LinkedTransmitterOverlay.cs @@ -1,4 +1,3 @@ -using System; using UnityEngine; using Verse; @@ -16,7 +15,15 @@ public Graphic_LinkedTransmitterOverlay(Graphic subGraphic) : base(subGraphic) public override bool ShouldLinkWith(IntVec3 c, Thing parent) { - return c.InBounds(parent.Map) && parent.Map.powerNetGrid.TransmittedPowerNetAt(c) != null; + if (!c.InBounds(parent.Map)) + { + return false; + } + if (parent.Map.powerNetGrid.TransmittedPowerNetAt(c) != null) + { + return true; + } + return false; } public override void Print(SectionLayer layer, Thing parent) diff --git a/Assembly-CSharp/RimWorld/GridShapeMaker.cs b/Assembly-CSharp/RimWorld/GridShapeMaker.cs index e0bbe3115..f5c51ae84 100644 --- a/Assembly-CSharp/RimWorld/GridShapeMaker.cs +++ b/Assembly-CSharp/RimWorld/GridShapeMaker.cs @@ -18,7 +18,7 @@ public static IEnumerable IrregularLump(IntVec3 center, Map map, int nu lumpCells.Add(intVec); } } - Func NumNeighbors = delegate(IntVec3 sq) + Func NumNeighbors = (Func)delegate(IntVec3 sq) { int num2 = 0; for (int k = 0; k < 4; k++) @@ -45,8 +45,8 @@ public static IEnumerable IrregularLump(IntVec3 center, Map map, int nu } List source = (from sq in lumpCells where NumNeighbors(sq) == fewestNeighbors - select sq).ToList(); - lumpCells.Remove(source.RandomElement()); + select sq).ToList(); + lumpCells.Remove(source.RandomElement()); } return lumpCells; } diff --git a/Assembly-CSharp/RimWorld/HairDef.cs b/Assembly-CSharp/RimWorld/HairDef.cs index 01985686f..3ea7d3e46 100644 --- a/Assembly-CSharp/RimWorld/HairDef.cs +++ b/Assembly-CSharp/RimWorld/HairDef.cs @@ -1,4 +1,3 @@ -using System; using System.Collections.Generic; using Verse; diff --git a/Assembly-CSharp/RimWorld/HairGender.cs b/Assembly-CSharp/RimWorld/HairGender.cs index f4fbba954..c5f8aad87 100644 --- a/Assembly-CSharp/RimWorld/HairGender.cs +++ b/Assembly-CSharp/RimWorld/HairGender.cs @@ -1,13 +1,11 @@ -using System; - namespace RimWorld { public enum HairGender : byte { - Male, - MaleUsually, - Any, - FemaleUsually, - Female + Male = 0, + MaleUsually = 1, + Any = 2, + FemaleUsually = 3, + Female = 4 } } diff --git a/Assembly-CSharp/RimWorld/HealthAIUtility.cs b/Assembly-CSharp/RimWorld/HealthAIUtility.cs index d1ebd267e..be026e4f1 100644 --- a/Assembly-CSharp/RimWorld/HealthAIUtility.cs +++ b/Assembly-CSharp/RimWorld/HealthAIUtility.cs @@ -19,17 +19,41 @@ public static bool ShouldSeekMedicalRest(Pawn pawn) public static bool ShouldBeTendedNowUrgent(Pawn pawn) { - return HealthAIUtility.ShouldBeTendedNow(pawn) && HealthUtility.TicksUntilDeathDueToBloodLoss(pawn) < 15000; + if (!HealthAIUtility.ShouldBeTendedNow(pawn)) + { + return false; + } + return HealthUtility.TicksUntilDeathDueToBloodLoss(pawn) < 15000; } public static bool ShouldBeTendedNow(Pawn pawn) { - return pawn.playerSettings != null && HealthAIUtility.ShouldEverReceiveMedicalCare(pawn) && pawn.health.HasHediffsNeedingTendByColony(false); + if (pawn.playerSettings == null) + { + return false; + } + if (!HealthAIUtility.ShouldEverReceiveMedicalCare(pawn)) + { + return false; + } + return pawn.health.HasHediffsNeedingTendByColony(false); } public static bool ShouldEverReceiveMedicalCare(Pawn pawn) { - return (pawn.playerSettings == null || pawn.playerSettings.medCare != MedicalCareCategory.NoCare) && (pawn.guest == null || pawn.guest.interactionMode != PrisonerInteractionModeDefOf.Execution) && pawn.Map.designationManager.DesignationOn(pawn, DesignationDefOf.Slaughter) == null; + if (pawn.playerSettings != null && pawn.playerSettings.medCare == MedicalCareCategory.NoCare) + { + return false; + } + if (pawn.guest != null && pawn.guest.interactionMode == PrisonerInteractionModeDefOf.Execution) + { + return false; + } + if (pawn.Map.designationManager.DesignationOn(pawn, DesignationDefOf.Slaughter) != null) + { + return false; + } + return true; } public static bool ShouldHaveSurgeryDoneNow(Pawn pawn) @@ -42,21 +66,9 @@ public static bool HasTendedImmunizableNonInjuryNonMissingPartHediff(Pawn pawn) List hediffs = pawn.health.hediffSet.hediffs; for (int i = 0; i < hediffs.Count; i++) { - if (!(hediffs[i] is Hediff_Injury)) + if (!(hediffs[i] is Hediff_Injury) && !(hediffs[i] is Hediff_MissingPart) && hediffs[i].Visible && hediffs[i].IsTended() && hediffs[i].def.PossibleToDevelopImmunityNaturally()) { - if (!(hediffs[i] is Hediff_MissingPart)) - { - if (hediffs[i].Visible) - { - if (hediffs[i].IsTended()) - { - if (hediffs[i].def.PossibleToDevelopImmunityNaturally()) - { - return true; - } - } - } - } + return true; } } return false; @@ -64,14 +76,21 @@ public static bool HasTendedImmunizableNonInjuryNonMissingPartHediff(Pawn pawn) public static Thing FindBestMedicine(Pawn healer, Pawn patient) { - if (patient.playerSettings == null || patient.playerSettings.medCare <= MedicalCareCategory.NoMeds) + if (patient.playerSettings != null && (int)patient.playerSettings.medCare > 1) { - return null; + Predicate predicate = (Predicate)delegate(Thing m) + { + if (!m.IsForbidden(healer) && patient.playerSettings.medCare.AllowsMedicine(m.def) && healer.CanReserve(m, 1, -1, null, false)) + { + return true; + } + return false; + }; + Func priorityGetter = (Func)((Thing t) => t.def.GetStatValueAbstract(StatDefOf.MedicalPotency, null)); + Predicate validator = predicate; + return GenClosest.ClosestThing_Global_Reachable(patient.Position, patient.Map, patient.Map.listerThings.ThingsInGroup(ThingRequestGroup.Medicine), PathEndMode.ClosestTouch, TraverseParms.For(healer, Danger.Deadly, TraverseMode.ByPawn, false), 9999f, validator, priorityGetter); } - Predicate predicate = (Thing m) => !m.IsForbidden(healer) && patient.playerSettings.medCare.AllowsMedicine(m.def) && healer.CanReserve(m, 1, -1, null, false); - Func priorityGetter = (Thing t) => t.def.GetStatValueAbstract(StatDefOf.MedicalPotency, null); - Predicate validator = predicate; - return GenClosest.ClosestThing_Global_Reachable(patient.Position, patient.Map, patient.Map.listerThings.ThingsInGroup(ThingRequestGroup.Medicine), PathEndMode.ClosestTouch, TraverseParms.For(healer, Danger.Deadly, TraverseMode.ByPawn, false), 9999f, validator, priorityGetter); + return null; } } } diff --git a/Assembly-CSharp/RimWorld/HealthCardUtility.cs b/Assembly-CSharp/RimWorld/HealthCardUtility.cs index 3102818ef..328a4c212 100644 --- a/Assembly-CSharp/RimWorld/HealthCardUtility.cs +++ b/Assembly-CSharp/RimWorld/HealthCardUtility.cs @@ -1,6 +1,5 @@ using System; using System.Collections.Generic; -using System.Diagnostics; using System.Linq; using System.Text; using UnityEngine; @@ -63,7 +62,7 @@ public static void DrawPawnHealthCard(Rect outRect, Pawn pawn, bool allowOperati allowOperations = false; } outRect = outRect.Rounded(); - Rect rect = new Rect(outRect.x, outRect.y, outRect.width * 0.375f, outRect.height).Rounded(); + Rect rect = new Rect(outRect.x, outRect.y, (float)(outRect.width * 0.375), outRect.height).Rounded(); Rect rect2 = new Rect(rect.xMax, outRect.y, outRect.width - rect.width, outRect.height); rect.yMin += 11f; HealthCardUtility.DrawHealthSummary(rect, pawn, allowOperations, thingForMedBills); @@ -79,20 +78,14 @@ public static void DrawHealthSummary(Rect rect, Pawn pawn, bool allowOperations, } Widgets.DrawMenuSection(rect, true); List list = new List(); - list.Add(new TabRecord("HealthOverview".Translate(), delegate + list.Add(new TabRecord("HealthOverview".Translate(), (Action)delegate { HealthCardUtility.onOperationTab = false; }, !HealthCardUtility.onOperationTab)); if (allowOperations) { - string label = (!pawn.RaceProps.IsMechanoid) ? "MedicalOperationsShort".Translate(new object[] - { - pawn.BillStack.Count - }) : "MedicalOperationsMechanoidsShort".Translate(new object[] - { - pawn.BillStack.Count - }); - list.Add(new TabRecord(label, delegate + string label = (!pawn.RaceProps.IsMechanoid) ? "MedicalOperationsShort".Translate(pawn.BillStack.Count) : "MedicalOperationsMechanoidsShort".Translate(pawn.BillStack.Count); + list.Add(new TabRecord(label, (Action)delegate { HealthCardUtility.onOperationTab = true; }, HealthCardUtility.onOperationTab)); @@ -129,7 +122,7 @@ public static void DrawHediffListing(Rect rect, Pawn pawn, bool showBloodLoss) GUI.BeginGroup(rect); float lineHeight = Text.LineHeight; Rect outRect = new Rect(0f, 0f, rect.width, rect.height - lineHeight); - Rect viewRect = new Rect(0f, 0f, rect.width - 16f, HealthCardUtility.scrollViewHeight); + Rect viewRect = new Rect(0f, 0f, (float)(rect.width - 16.0), HealthCardUtility.scrollViewHeight); Rect rect2 = rect; if (viewRect.height > outRect.height) { @@ -140,10 +133,10 @@ public static void DrawHediffListing(Rect rect, Pawn pawn, bool showBloodLoss) float num = 0f; HealthCardUtility.highlight = true; bool flag = false; - foreach (IGrouping current in HealthCardUtility.VisibleHediffGroupsInOrder(pawn, showBloodLoss)) + foreach (IGrouping item in HealthCardUtility.VisibleHediffGroupsInOrder(pawn, showBloodLoss)) { flag = true; - HealthCardUtility.DrawHediffRow(rect2, pawn, current, ref num); + HealthCardUtility.DrawHediffRow(rect2, pawn, item, ref num); } if (!flag) { @@ -159,46 +152,27 @@ public static void DrawHediffListing(Rect rect, Pawn pawn, bool showBloodLoss) } Widgets.EndScrollView(); float bleedRateTotal = pawn.health.hediffSet.BleedRateTotal; - if (bleedRateTotal > 0.01f) + if (bleedRateTotal > 0.0099999997764825821) { Rect rect4 = new Rect(0f, rect.height - lineHeight, rect.width, lineHeight); - string text = string.Concat(new string[] - { - "BleedingRate".Translate(), - ": ", - bleedRateTotal.ToStringPercent(), - "/", - "LetterDay".Translate() - }); + string str = "BleedingRate".Translate() + ": " + bleedRateTotal.ToStringPercent() + "/" + "LetterDay".Translate(); int num2 = HealthUtility.TicksUntilDeathDueToBloodLoss(pawn); - if (num2 < 60000) - { - text = text + " (" + "TimeToDeath".Translate(new object[] - { - num2.ToStringTicksToPeriod(true, false, true) - }) + ")"; - } - else - { - text = text + " (" + "WontBleedOutSoon".Translate() + ")"; - } - Widgets.Label(rect4, text); + str = ((num2 >= 60000) ? (str + " (" + "WontBleedOutSoon".Translate() + ")") : (str + " (" + "TimeToDeath".Translate(num2.ToStringTicksToPeriod(true, false, true)) + ")")); + Widgets.Label(rect4, str); } GUI.EndGroup(); GUI.color = Color.white; } - [DebuggerHidden] private static IEnumerable> VisibleHediffGroupsInOrder(Pawn pawn, bool showBloodLoss) { - HealthCardUtility.c__Iterator197 c__Iterator = new HealthCardUtility.c__Iterator197(); - c__Iterator.pawn = pawn; - c__Iterator.showBloodLoss = showBloodLoss; - c__Iterator.<$>pawn = pawn; - c__Iterator.<$>showBloodLoss = showBloodLoss; - HealthCardUtility.c__Iterator197 expr_23 = c__Iterator; - expr_23.$PC = -2; - return expr_23; + foreach (IGrouping item in from x in HealthCardUtility.VisibleHediffs(pawn, showBloodLoss) + group x by x.Part into x + orderby HealthCardUtility.GetListPriority(x.First().Part) descending + select x) + { + yield return item; + } } private static float GetListPriority(BodyPartRecord rec) @@ -210,39 +184,76 @@ private static float GetListPriority(BodyPartRecord rec) return (float)((int)rec.height * 10000) + rec.coverageAbsWithChildren; } - [DebuggerHidden] private static IEnumerable VisibleHediffs(Pawn pawn, bool showBloodLoss) { - HealthCardUtility.c__Iterator198 c__Iterator = new HealthCardUtility.c__Iterator198(); - c__Iterator.pawn = pawn; - c__Iterator.showBloodLoss = showBloodLoss; - c__Iterator.<$>pawn = pawn; - c__Iterator.<$>showBloodLoss = showBloodLoss; - HealthCardUtility.c__Iterator198 expr_23 = c__Iterator; - expr_23.$PC = -2; - return expr_23; + if (!HealthCardUtility.showAllHediffs) + { + List mpca = pawn.health.hediffSet.GetMissingPartsCommonAncestors(); + for (int i = 0; i < mpca.Count; i++) + { + yield return (Hediff)mpca[i]; + } + IEnumerable visibleDiffs = pawn.health.hediffSet.hediffs.Where((Func)delegate(Hediff d) + { + if (d is Hediff_MissingPart) + { + return false; + } + if (!d.Visible) + { + return false; + } + if (!((_003CVisibleHediffs_003Ec__Iterator198)/*Error near IL_00b9: stateMachine*/).showBloodLoss && d.def == HediffDefOf.BloodLoss) + { + return false; + } + return true; + }); + foreach (Hediff item in visibleDiffs) + { + yield return item; + } + } + else + { + List.Enumerator enumerator2 = pawn.health.hediffSet.hediffs.GetEnumerator(); + try + { + while (enumerator2.MoveNext()) + { + Hediff diff = enumerator2.Current; + yield return diff; + } + } + finally + { + ((IDisposable)(object)enumerator2).Dispose(); + } + } } private static float DrawMedOperationsTab(Rect leftRect, Pawn pawn, Thing thingForMedBills, float curY) { - curY += 2f; - Func> recipeOptionsMaker = delegate + curY = (float)(curY + 2.0); + Func> recipeOptionsMaker = (Func>)delegate() { List list = new List(); - foreach (RecipeDef current in thingForMedBills.def.AllRecipes) + List.Enumerator enumerator = thingForMedBills.def.AllRecipes.GetEnumerator(); + try { - if (current.AvailableNow) + while (enumerator.MoveNext()) { - IEnumerable enumerable = current.PotentiallyMissingIngredients(null, thingForMedBills.Map); - if (!enumerable.Any((ThingDef x) => x.isBodyPartOrImplant)) + RecipeDef current = enumerator.Current; + if (current.AvailableNow) { - if (!enumerable.Any((ThingDef x) => x.IsDrug)) + IEnumerable enumerable = current.PotentiallyMissingIngredients(null, thingForMedBills.Map); + if (!enumerable.Any((Func)((ThingDef x) => x.isBodyPartOrImplant)) && !enumerable.Any((Func)((ThingDef x) => x.IsDrug))) { if (current.targetsBodyPart) { - foreach (BodyPartRecord current2 in current.Worker.GetPartsToApplyOn(pawn, current)) + foreach (BodyPartRecord item in current.Worker.GetPartsToApplyOn(pawn, current)) { - list.Add(HealthCardUtility.GenerateSurgeryOption(pawn, thingForMedBills, current, enumerable, current2)); + list.Add(HealthCardUtility.GenerateSurgeryOption(pawn, thingForMedBills, current, enumerable, item)); } } else @@ -252,10 +263,14 @@ private static float DrawMedOperationsTab(Rect leftRect, Pawn pawn, Thing thingF } } } + return list; + } + finally + { + ((IDisposable)(object)enumerator).Dispose(); } - return list; }; - Rect rect = new Rect(leftRect.x - 9f, curY, leftRect.width, leftRect.height - curY - 20f); + Rect rect = new Rect((float)(leftRect.x - 9.0), curY, leftRect.width, (float)(leftRect.height - curY - 20.0)); ((IBillGiver)thingForMedBills).BillStack.DoListing(rect, recipeOptionsMaker, ref HealthCardUtility.billsScrollPosition, ref HealthCardUtility.billsScrollHeight); return curY; } @@ -267,74 +282,62 @@ private static FloatMenuOption GenerateSurgeryOption(Pawn pawn, Thing thingForMe { text = text + " (" + part.def.label + ")"; } - if (missingIngredients.Any()) + if (missingIngredients.Any()) { text += " ("; bool flag = true; - foreach (ThingDef current in missingIngredients) + foreach (ThingDef item in missingIngredients) { if (!flag) { text += ", "; } flag = false; - text += "MissingMedicalBillIngredient".Translate(new object[] - { - current.label - }); + text += "MissingMedicalBillIngredient".Translate(item.label); } text += ")"; return new FloatMenuOption(text, null, MenuOptionPriority.Default, null, null, 0f, null, null); } - Action action = delegate + Action action = (Action)delegate() { Pawn pawn2 = thingForMedBills as Pawn; - if (pawn2 == null) + if (pawn2 != null) { - return; - } - Bill_Medical bill_Medical = new Bill_Medical(recipe); - pawn2.BillStack.AddBill(bill_Medical); - bill_Medical.Part = part; - if (recipe.conceptLearned != null) - { - PlayerKnowledgeDatabase.KnowledgeDemonstrated(recipe.conceptLearned, KnowledgeAmount.Total); - } - Map map = thingForMedBills.Map; - if (!map.mapPawns.FreeColonists.Any((Pawn col) => recipe.PawnSatisfiesSkillRequirements(col))) - { - Bill.CreateNoPawnsWithSkillDialog(recipe); - } - if (!pawn2.InBed() && pawn2.RaceProps.IsFlesh) - { - if (pawn2.RaceProps.Humanlike) + Bill_Medical bill_Medical = new Bill_Medical(recipe); + pawn2.BillStack.AddBill(bill_Medical); + bill_Medical.Part = part; + if (recipe.conceptLearned != null) + { + PlayerKnowledgeDatabase.KnowledgeDemonstrated(recipe.conceptLearned, KnowledgeAmount.Total); + } + Map map = thingForMedBills.Map; + if (!map.mapPawns.FreeColonists.Any((Func)((Pawn col) => recipe.PawnSatisfiesSkillRequirements(col)))) + { + Bill.CreateNoPawnsWithSkillDialog(recipe); + } + if (!pawn2.InBed() && pawn2.RaceProps.IsFlesh) { - if (!map.listerBuildings.allBuildingsColonist.Any((Building x) => x is Building_Bed && RestUtility.CanUseBedEver(pawn, x.def) && ((Building_Bed)x).Medical)) + if (pawn2.RaceProps.Humanlike) { - Messages.Message("MessageNoMedicalBeds".Translate(), pawn2, MessageSound.Negative); + if (!map.listerBuildings.allBuildingsColonist.Any((Predicate)((Building x) => x is Building_Bed && RestUtility.CanUseBedEver(pawn, x.def) && ((Building_Bed)x).Medical))) + { + Messages.Message("MessageNoMedicalBeds".Translate(), (Thing)pawn2, MessageSound.Negative); + } + } + else if (!map.listerBuildings.allBuildingsColonist.Any((Predicate)((Building x) => x is Building_Bed && RestUtility.CanUseBedEver(pawn, x.def)))) + { + Messages.Message("MessageNoAnimalBeds".Translate(), (Thing)pawn2, MessageSound.Negative); } } - else if (!map.listerBuildings.allBuildingsColonist.Any((Building x) => x is Building_Bed && RestUtility.CanUseBedEver(pawn, x.def))) + if (pawn2.Faction != null && !pawn2.Faction.def.hidden && !pawn2.Faction.HostileTo(Faction.OfPlayer) && recipe.Worker.IsViolationOnPawn(pawn2, part, Faction.OfPlayer)) { - Messages.Message("MessageNoAnimalBeds".Translate(), pawn2, MessageSound.Negative); + Messages.Message("MessageMedicalOperationWillAngerFaction".Translate(pawn2.Faction), (Thing)pawn2, MessageSound.Negative); } - } - if (pawn2.Faction != null && !pawn2.Faction.def.hidden && !pawn2.Faction.HostileTo(Faction.OfPlayer) && recipe.Worker.IsViolationOnPawn(pawn2, part, Faction.OfPlayer)) - { - Messages.Message("MessageMedicalOperationWillAngerFaction".Translate(new object[] + ThingDef minRequiredMedicine = HealthCardUtility.GetMinRequiredMedicine(recipe); + if (minRequiredMedicine != null && pawn2.playerSettings != null && !pawn2.playerSettings.medCare.AllowsMedicine(minRequiredMedicine)) { - pawn2.Faction - }), pawn2, MessageSound.Negative); - } - ThingDef minRequiredMedicine = HealthCardUtility.GetMinRequiredMedicine(recipe); - if (minRequiredMedicine != null && pawn2.playerSettings != null && !pawn2.playerSettings.medCare.AllowsMedicine(minRequiredMedicine)) - { - Messages.Message("MessageTooLowMedCare".Translate(new object[] - { - minRequiredMedicine.label, - pawn2.LabelShort, - pawn2.playerSettings.medCare.GetLabel() - }), pawn2, MessageSound.Negative); + Messages.Message("MessageTooLowMedCare".Translate(minRequiredMedicine.label, pawn2.LabelShort, pawn2.playerSettings.medCare.GetLabel()), (Thing)pawn2, MessageSound.Negative); + } } }; return new FloatMenuOption(text, action, MenuOptionPriority.Default, null, null, 0f, null, null); @@ -351,7 +354,7 @@ private static ThingDef GetMinRequiredMedicine(RecipeDef recipe) HealthCardUtility.tmpMedicineBestToWorst.Add(allDefsListForReading[i]); } } - HealthCardUtility.tmpMedicineBestToWorst.SortByDescending((ThingDef x) => x.GetStatValueAbstract(StatDefOf.MedicalPotency, null)); + HealthCardUtility.tmpMedicineBestToWorst.SortByDescending((Func)((ThingDef x) => x.GetStatValueAbstract(StatDefOf.MedicalPotency, null))); ThingDef thingDef = null; for (int j = 0; j < recipe.ingredients.Count; j++) { @@ -374,37 +377,34 @@ private static ThingDef GetMinRequiredMedicine(RecipeDef recipe) private static float DrawOverviewTab(Rect leftRect, Pawn pawn, float curY) { - curY += 4f; + curY = (float)(curY + 4.0); Text.Font = GameFont.Tiny; Text.Anchor = TextAnchor.UpperLeft; GUI.color = new Color(0.9f, 0.9f, 0.9f); - string text = string.Empty; - if (pawn.gender != Gender.None) + string str = string.Empty; + if (pawn.gender != 0) { - text = pawn.gender.GetLabel() + " "; + str = pawn.gender.GetLabel() + " "; } - text = text + pawn.def.label + ", " + "AgeIndicator".Translate(new object[] - { - pawn.ageTracker.AgeNumberString - }); + str = str + pawn.def.label + ", " + "AgeIndicator".Translate(pawn.ageTracker.AgeNumberString); Rect rect = new Rect(0f, curY, leftRect.width, 34f); - Widgets.Label(rect, text.CapitalizeFirst()); - TooltipHandler.TipRegion(rect, () => pawn.ageTracker.AgeTooltipString, 73412); + Widgets.Label(rect, str.CapitalizeFirst()); + TooltipHandler.TipRegion(rect, (Func)(() => pawn.ageTracker.AgeTooltipString), 73412); if (Mouse.IsOver(rect)) { Widgets.DrawHighlight(rect); } GUI.color = Color.white; - curY += 34f; + curY = (float)(curY + 34.0); if (pawn.playerSettings != null && !pawn.Dead && Current.ProgramState == ProgramState.Playing) { Rect rect2 = new Rect(0f, curY, 140f, 28f); MedicalCareUtility.MedicalCareSetter(rect2, ref pawn.playerSettings.medCare); - if (Widgets.ButtonText(new Rect(leftRect.width - 70f, curY, 70f, 28f), "MedGroupDefaults".Translate(), true, false, true)) + if (Widgets.ButtonText(new Rect((float)(leftRect.width - 70.0), curY, 70f, 28f), "MedGroupDefaults".Translate(), true, false, true)) { Find.WindowStack.Add(new Dialog_MedicalDefaults()); } - curY += 32f; + curY = (float)(curY + 32.0); } Text.Font = GameFont.Small; if (pawn.def.race.IsFlesh) @@ -415,35 +415,21 @@ private static float DrawOverviewTab(Rect leftRect, Pawn pawn, float curY) } if (!pawn.Dead) { - IEnumerable source; - if (pawn.def.race.Humanlike) - { - source = from x in DefDatabase.AllDefs - where x.showOnHumanlikes - select x; - } - else if (pawn.def.race.Animal) - { - source = from x in DefDatabase.AllDefs - where x.showOnAnimals - select x; - } - else - { - source = from x in DefDatabase.AllDefs - where x.showOnMechanoids - select x; - } - foreach (PawnCapacityDef current in from act in source + IEnumerable source = (!pawn.def.race.Humanlike) ? ((!pawn.def.race.Animal) ? (from x in DefDatabase.AllDefs + where x.showOnMechanoids + select x) : DefDatabase.AllDefs.Where((Func)((PawnCapacityDef x) => x.showOnAnimals))) : (from x in DefDatabase.AllDefs + where x.showOnHumanlikes + select x); + foreach (PawnCapacityDef item in from act in source orderby act.listOrder select act) { - if (PawnCapacityUtility.BodyCanEverDoCapacity(pawn.RaceProps.body, current)) + if (PawnCapacityUtility.BodyCanEverDoCapacity(pawn.RaceProps.body, item)) { - PawnCapacityDef activityLocal = current; - Pair efficiencyLabel = HealthCardUtility.GetEfficiencyLabel(pawn, current); - Func textGetter = () => (!pawn.Dead) ? HealthCardUtility.GetPawnCapacityTip(pawn, activityLocal) : string.Empty; - curY = HealthCardUtility.DrawLeftRow(leftRect, curY, current.GetLabelFor(pawn.RaceProps.IsFlesh, pawn.RaceProps.Humanlike).CapitalizeFirst(), efficiencyLabel.First, efficiencyLabel.Second, new TipSignal(textGetter, pawn.thingIDNumber ^ (int)current.index)); + PawnCapacityDef activityLocal = item; + Pair efficiencyLabel = HealthCardUtility.GetEfficiencyLabel(pawn, item); + Func textGetter = (Func)(() => (!pawn.Dead) ? HealthCardUtility.GetPawnCapacityTip(pawn, activityLocal) : string.Empty); + curY = HealthCardUtility.DrawLeftRow(leftRect, curY, item.GetLabelFor(pawn.RaceProps.IsFlesh, pawn.RaceProps.Humanlike).CapitalizeFirst(), efficiencyLabel.First, efficiencyLabel.Second, new TipSignal(textGetter, pawn.thingIDNumber ^ item.index)); } } } @@ -451,31 +437,21 @@ orderby act.listOrder if (pawn.IsColonist) { bool selfTend = pawn.playerSettings.selfTend; - Rect rect3 = new Rect(0f, leftRect.height - 24f, leftRect.width, 24f); + Rect rect3 = new Rect(0f, (float)(leftRect.height - 24.0), leftRect.width, 24f); Widgets.CheckboxLabeled(rect3, "SelfTend".Translate(), ref pawn.playerSettings.selfTend, false); if (pawn.playerSettings.selfTend && !selfTend) { if (pawn.story.WorkTypeIsDisabled(WorkTypeDefOf.Doctor)) { pawn.playerSettings.selfTend = false; - Messages.Message("MessageCannotSelfTendEver".Translate(new object[] - { - pawn.LabelShort - }), MessageSound.RejectInput); + Messages.Message("MessageCannotSelfTendEver".Translate(pawn.LabelShort), MessageSound.RejectInput); } else if (pawn.workSettings.GetPriority(WorkTypeDefOf.Doctor) == 0) { - Messages.Message("MessageSelfTendUnsatisfied".Translate(new object[] - { - pawn.LabelShort - }), MessageSound.Standard); + Messages.Message("MessageSelfTendUnsatisfied".Translate(pawn.LabelShort), MessageSound.Standard); } } - TooltipHandler.TipRegion(rect3, "SelfTendTip".Translate(new object[] - { - Faction.OfPlayer.def.pawnsPlural, - 0.7f.ToStringPercent() - }).CapitalizeFirst()); + TooltipHandler.TipRegion(rect3, "SelfTendTip".Translate(Faction.OfPlayer.def.pawnsPlural, 0.7f.ToStringPercent()).CapitalizeFirst()); } return curY; } @@ -489,44 +465,36 @@ private static float DrawLeftRow(Rect leftRect, float curY, string leftLabel, st GUI.DrawTexture(rect, TexUI.HighlightTex); } GUI.color = Color.white; - Widgets.Label(new Rect(0f, curY, leftRect.width * 0.65f, 30f), leftLabel); + Widgets.Label(new Rect(0f, curY, (float)(leftRect.width * 0.64999997615814209), 30f), leftLabel); GUI.color = rightLabelColor; - Widgets.Label(new Rect(leftRect.width * 0.65f, curY, leftRect.width * 0.35f, 30f), rightLabel); + Widgets.Label(new Rect((float)(leftRect.width * 0.64999997615814209), curY, (float)(leftRect.width * 0.34999999403953552), 30f), rightLabel); TooltipHandler.TipRegion(new Rect(0f, curY, leftRect.width, 20f), tipSignal); - curY += 20f; + curY = (float)(curY + 20.0); return curY; } private static void DrawHediffRow(Rect rect, Pawn pawn, IEnumerable diffs, ref float curY) { - float num = rect.width * 0.375f; - float width = rect.width - num - 20f; - BodyPartRecord part = diffs.First().Part; - float a; - if (part == null) - { - a = Text.CalcHeight("WholeBody".Translate(), num); - } - else - { - a = Text.CalcHeight(part.def.LabelCap, num); - } - float b = 0f; - float num2 = curY; - float num3 = 0f; - foreach (IGrouping current in from x in diffs + float num = (float)(rect.width * 0.375); + float width = (float)(rect.width - num - 20.0); + BodyPartRecord part = diffs.First().Part; + float a = (part != null) ? Text.CalcHeight(part.def.LabelCap, num) : Text.CalcHeight("WholeBody".Translate(), num); + float num2 = 0f; + float num3 = curY; + float num4 = 0f; + foreach (IGrouping item in from x in diffs group x by x.UIGroupKey) { - int num4 = current.Count(); - string text = current.First().LabelCap; - if (num4 != 1) + int num5 = item.Count(); + string text = item.First().LabelCap; + if (num5 != 1) { - text = text + " x" + num4.ToString(); + text = text + " x" + num5.ToString(); } - num3 += Text.CalcHeight(text, width); + num4 += Text.CalcHeight(text, width); } - b = num3; - Rect rect2 = new Rect(0f, curY, rect.width, Mathf.Max(a, b)); + num2 = num4; + Rect rect2 = new Rect(0f, curY, rect.width, Mathf.Max(a, num2)); HealthCardUtility.DoRightRowHighlight(rect2); if (part != null) { @@ -539,42 +507,42 @@ private static void DrawHediffRow(Rect rect, Pawn pawn, IEnumerable diff Widgets.Label(new Rect(0f, curY, num, 100f), "WholeBody".Translate()); } GUI.color = Color.white; - foreach (IGrouping current2 in from x in diffs + foreach (IGrouping item2 in from x in diffs group x by x.UIGroupKey) { - int num5 = 0; + int num6 = 0; Hediff hediff = null; Texture2D texture2D = null; - TextureAndColor textureAndColor = null; - float num6 = 0f; - foreach (Hediff current3 in current2) + TextureAndColor textureAndColor = (Texture2D)null; + float num7 = 0f; + foreach (Hediff item3 in item2) { - if (num5 == 0) + if (num6 == 0) { - hediff = current3; + hediff = item3; } - textureAndColor = current3.StateIcon; - if (current3.Bleeding) + textureAndColor = item3.StateIcon; + if (item3.Bleeding) { texture2D = HealthCardUtility.BleedingIcon; } - num6 += current3.BleedRate; - num5++; + num7 += item3.BleedRate; + num6++; } string text2 = hediff.LabelCap; - if (num5 != 1) + if (num6 != 1) { - text2 = text2 + " x" + num5.ToStringCached(); + text2 = text2 + " x" + num6.ToStringCached(); } GUI.color = hediff.LabelColor; - float num7 = Text.CalcHeight(text2, width); - Rect rect3 = new Rect(num, curY, width, num7); + float num8 = Text.CalcHeight(text2, width); + Rect rect3 = new Rect(num, curY, width, num8); Widgets.Label(rect3, text2); GUI.color = Color.white; - Rect rect4 = new Rect(rect2.xMax - 20f, curY, 20f, 20f); - if (texture2D) + Rect rect4 = new Rect((float)(rect2.xMax - 20.0), curY, 20f, 20f); + if ((UnityEngine.Object)texture2D) { - Rect position = rect4.ContractedBy(GenMath.LerpDouble(0f, 0.6f, 5f, 0f, Mathf.Min(num6, 1f))); + Rect position = rect4.ContractedBy(GenMath.LerpDouble(0f, 0.6f, 5f, 0f, Mathf.Min(num7, 1f))); GUI.DrawTexture(position, texture2D); rect4.x -= rect4.width; } @@ -585,16 +553,16 @@ private static void DrawHediffRow(Rect rect, Pawn pawn, IEnumerable diff GUI.color = Color.white; rect4.x -= rect4.width; } - curY += num7; + curY += num8; } GUI.color = Color.white; - curY = num2 + Mathf.Max(a, b); - TooltipHandler.TipRegion(rect2, new TipSignal(() => HealthCardUtility.GetTooltip(diffs, pawn, part), (int)curY + 7857)); + curY = num3 + Mathf.Max(a, num2); + TooltipHandler.TipRegion(rect2, new TipSignal((Func)(() => HealthCardUtility.GetTooltip(diffs, pawn, part)), (int)curY + 7857)); } public static string GetPainTip(Pawn pawn) { - return "PainLevel".Translate() + ": " + (pawn.health.hediffSet.PainTotal * 100f).ToString("F0") + "%"; + return "PainLevel".Translate() + ": " + ((float)(pawn.health.hediffSet.PainTotal * 100.0)).ToString("F0") + "%"; } public static string GetPawnCapacityTip(Pawn pawn, PawnCapacityDef capacity) @@ -602,7 +570,7 @@ public static string GetPawnCapacityTip(Pawn pawn, PawnCapacityDef capacity) List list = new List(); float num = PawnCapacityUtility.CalculateCapacityLevel(pawn.health.hediffSet, capacity, list); StringBuilder stringBuilder = new StringBuilder(); - stringBuilder.AppendLine(capacity.LabelCap + ": " + (num * 100f).ToString("F0") + "%"); + stringBuilder.AppendLine(capacity.LabelCap + ": " + ((float)(num * 100.0)).ToString("F0") + "%"); if (list.Count > 0) { stringBuilder.AppendLine(); @@ -647,7 +615,7 @@ private static string GetTooltip(IEnumerable diffs, Pawn pawn, BodyPartR stringBuilder.Append(part.def.LabelCap + ": "); stringBuilder.AppendLine(" " + pawn.health.hediffSet.GetPartHealth(part).ToString() + " / " + part.def.GetMaxHealth(pawn).ToString()); float num = PawnCapacityUtility.CalculatePartEfficiency(pawn.health.hediffSet, part, false, null); - if (num != 1f) + if (num != 1.0) { stringBuilder.AppendLine("Efficiency".Translate() + ": " + num.ToStringPercent()); } @@ -657,34 +625,34 @@ private static string GetTooltip(IEnumerable diffs, Pawn pawn, BodyPartR stringBuilder.AppendLine("WholeBody".Translate()); } stringBuilder.AppendLine("------------------"); - foreach (IGrouping current in from x in diffs + foreach (IGrouping item in from x in diffs group x by x.UIGroupKey) { - foreach (Hediff current2 in current) + foreach (Hediff item2 in item) { - string severityLabel = current2.SeverityLabel; - bool flag = HealthCardUtility.showHediffsDebugInfo && !current2.DebugString().NullOrEmpty(); - if (!current2.Label.NullOrEmpty() || !severityLabel.NullOrEmpty() || !current2.CapMods.NullOrEmpty() || flag) + string severityLabel = item2.SeverityLabel; + bool flag = HealthCardUtility.showHediffsDebugInfo && !item2.DebugString().NullOrEmpty(); + if (!item2.Label.NullOrEmpty() || !severityLabel.NullOrEmpty() || !item2.CapMods.NullOrEmpty() || flag) { - stringBuilder.Append(current2.LabelCap); + stringBuilder.Append(item2.LabelCap); if (!severityLabel.NullOrEmpty()) { stringBuilder.Append(": " + severityLabel); } stringBuilder.AppendLine(); - string tipStringExtra = current2.TipStringExtra; + string tipStringExtra = item2.TipStringExtra; if (!tipStringExtra.NullOrEmpty()) { stringBuilder.AppendLine(tipStringExtra.TrimEndNewlines().Indented()); } if (flag) { - stringBuilder.AppendLine(current2.DebugString().TrimEndNewlines()); + stringBuilder.AppendLine(item2.DebugString().TrimEndNewlines()); } } } } - return stringBuilder.ToString().TrimEnd(new char[0]); + return stringBuilder.ToString().TrimEnd(); } private static void DoRightRowHighlight(Rect rowRect) @@ -704,221 +672,228 @@ private static void DoRightRowHighlight(Rect rowRect) private static void DoDebugOptions(Rect rightRect, Pawn pawn) { - Widgets.CheckboxLabeled(new Rect(rightRect.x, rightRect.y - 25f, 110f, 30f), "Dev: AllDiffs", ref HealthCardUtility.showAllHediffs, false); - Widgets.CheckboxLabeled(new Rect(rightRect.x + 115f, rightRect.y - 25f, 120f, 30f), "DiffsDebugInfo", ref HealthCardUtility.showHediffsDebugInfo, false); - if (Widgets.ButtonText(new Rect(rightRect.x + 240f, rightRect.y - 27f, 115f, 25f), "Debug info", true, false, true)) + Widgets.CheckboxLabeled(new Rect(rightRect.x, (float)(rightRect.y - 25.0), 110f, 30f), "Dev: AllDiffs", ref HealthCardUtility.showAllHediffs, false); + Widgets.CheckboxLabeled(new Rect((float)(rightRect.x + 115.0), (float)(rightRect.y - 25.0), 120f, 30f), "DiffsDebugInfo", ref HealthCardUtility.showHediffsDebugInfo, false); + if (Widgets.ButtonText(new Rect((float)(rightRect.x + 240.0), (float)(rightRect.y - 27.0), 115f, 25f), "Debug info", true, false, true)) { List list = new List(); - list.Add(new FloatMenuOption("Parts hit chance (this part or any child node)", delegate + list.Add(new FloatMenuOption("Parts hit chance (this part or any child node)", (Action)delegate() { - StringBuilder stringBuilder = new StringBuilder(); - foreach (BodyPartRecord current in from x in pawn.RaceProps.body.AllParts + StringBuilder stringBuilder13 = new StringBuilder(); + foreach (BodyPartRecord item in from x in pawn.RaceProps.body.AllParts orderby x.coverageAbsWithChildren descending select x) { - stringBuilder.AppendLine(current.def.LabelCap + " " + current.coverageAbsWithChildren.ToStringPercent()); + stringBuilder13.AppendLine(item.def.LabelCap + " " + item.coverageAbsWithChildren.ToStringPercent()); } - Find.WindowStack.Add(new Dialog_MessageBox(stringBuilder.ToString(), null, null, null, null, null, false)); + Find.WindowStack.Add(new Dialog_MessageBox(stringBuilder13.ToString(), (string)null, null, (string)null, null, (string)null, false)); }, MenuOptionPriority.Default, null, null, 0f, null, null)); - list.Add(new FloatMenuOption("Parts hit chance (exactly this part)", delegate + list.Add(new FloatMenuOption("Parts hit chance (exactly this part)", (Action)delegate() { - StringBuilder stringBuilder = new StringBuilder(); - float num = 0f; - foreach (BodyPartRecord current in from x in pawn.RaceProps.body.AllParts + StringBuilder stringBuilder12 = new StringBuilder(); + float num10 = 0f; + foreach (BodyPartRecord item in from x in pawn.RaceProps.body.AllParts orderby x.coverageAbs descending select x) { - stringBuilder.AppendLine(current.def.LabelCap + " " + current.coverageAbs.ToStringPercent()); - num += current.coverageAbs; + stringBuilder12.AppendLine(item.def.LabelCap + " " + item.coverageAbs.ToStringPercent()); + num10 += item.coverageAbs; } - stringBuilder.AppendLine(); - stringBuilder.AppendLine("Total " + num.ToStringPercent()); - Find.WindowStack.Add(new Dialog_MessageBox(stringBuilder.ToString(), null, null, null, null, null, false)); + stringBuilder12.AppendLine(); + stringBuilder12.AppendLine("Total " + num10.ToStringPercent()); + Find.WindowStack.Add(new Dialog_MessageBox(stringBuilder12.ToString(), (string)null, null, (string)null, null, (string)null, false)); }, MenuOptionPriority.Default, null, null, 0f, null, null)); - list.Add(new FloatMenuOption("Per-part efficiency", delegate + list.Add(new FloatMenuOption("Per-part efficiency", (Action)delegate() { - StringBuilder stringBuilder = new StringBuilder(); - foreach (BodyPartRecord current in pawn.RaceProps.body.AllParts) + StringBuilder stringBuilder11 = new StringBuilder(); + List.Enumerator enumerator12 = pawn.RaceProps.body.AllParts.GetEnumerator(); + try + { + while (enumerator12.MoveNext()) + { + BodyPartRecord current12 = enumerator12.Current; + stringBuilder11.AppendLine(current12.def.LabelCap + " " + PawnCapacityUtility.CalculatePartEfficiency(pawn.health.hediffSet, current12, false, null).ToStringPercent()); + } + } + finally { - stringBuilder.AppendLine(current.def.LabelCap + " " + PawnCapacityUtility.CalculatePartEfficiency(pawn.health.hediffSet, current, false, null).ToStringPercent()); + ((IDisposable)(object)enumerator12).Dispose(); } - Find.WindowStack.Add(new Dialog_MessageBox(stringBuilder.ToString(), null, null, null, null, null, false)); + Find.WindowStack.Add(new Dialog_MessageBox(stringBuilder11.ToString(), (string)null, null, (string)null, null, (string)null, false)); }, MenuOptionPriority.Default, null, null, 0f, null, null)); - list.Add(new FloatMenuOption("BodyPartGroup efficiency (of only natural parts)", delegate + list.Add(new FloatMenuOption("BodyPartGroup efficiency (of only natural parts)", (Action)delegate() { - StringBuilder stringBuilder = new StringBuilder(); - foreach (BodyPartGroupDef current in from x in DefDatabase.AllDefs - where pawn.RaceProps.body.AllParts.Any((BodyPartRecord y) => y.groups.Contains(x)) + StringBuilder stringBuilder10 = new StringBuilder(); + foreach (BodyPartGroupDef item in from x in DefDatabase.AllDefs + where pawn.RaceProps.body.AllParts.Any((Predicate)((BodyPartRecord y) => y.groups.Contains(x))) select x) { - stringBuilder.AppendLine(current.LabelCap + " " + PawnCapacityUtility.CalculateNaturalPartsAverageEfficiency(pawn.health.hediffSet, current).ToStringPercent()); + stringBuilder10.AppendLine(item.LabelCap + " " + PawnCapacityUtility.CalculateNaturalPartsAverageEfficiency(pawn.health.hediffSet, item).ToStringPercent()); } - Find.WindowStack.Add(new Dialog_MessageBox(stringBuilder.ToString(), null, null, null, null, null, false)); + Find.WindowStack.Add(new Dialog_MessageBox(stringBuilder10.ToString(), (string)null, null, (string)null, null, (string)null, false)); }, MenuOptionPriority.Default, null, null, 0f, null, null)); - list.Add(new FloatMenuOption("IsSolid", delegate + list.Add(new FloatMenuOption("IsSolid", (Action)delegate() { - StringBuilder stringBuilder = new StringBuilder(); - foreach (BodyPartRecord current in pawn.health.hediffSet.GetNotMissingParts(BodyPartHeight.Undefined, BodyPartDepth.Undefined)) + StringBuilder stringBuilder9 = new StringBuilder(); + foreach (BodyPartRecord notMissingPart in pawn.health.hediffSet.GetNotMissingParts(BodyPartHeight.Undefined, BodyPartDepth.Undefined)) { - stringBuilder.AppendLine(current.def.LabelCap + " " + current.def.IsSolid(current, pawn.health.hediffSet.hediffs)); + stringBuilder9.AppendLine(notMissingPart.def.LabelCap + " " + notMissingPart.def.IsSolid(notMissingPart, pawn.health.hediffSet.hediffs)); } - Find.WindowStack.Add(new Dialog_MessageBox(stringBuilder.ToString(), null, null, null, null, null, false)); + Find.WindowStack.Add(new Dialog_MessageBox(stringBuilder9.ToString(), (string)null, null, (string)null, null, (string)null, false)); }, MenuOptionPriority.Default, null, null, 0f, null, null)); - list.Add(new FloatMenuOption("IsSkinCovered", delegate + list.Add(new FloatMenuOption("IsSkinCovered", (Action)delegate() { - StringBuilder stringBuilder = new StringBuilder(); - foreach (BodyPartRecord current in pawn.health.hediffSet.GetNotMissingParts(BodyPartHeight.Undefined, BodyPartDepth.Undefined)) + StringBuilder stringBuilder8 = new StringBuilder(); + foreach (BodyPartRecord notMissingPart in pawn.health.hediffSet.GetNotMissingParts(BodyPartHeight.Undefined, BodyPartDepth.Undefined)) { - stringBuilder.AppendLine(current.def.LabelCap + " " + current.def.IsSkinCovered(current, pawn.health.hediffSet)); + stringBuilder8.AppendLine(notMissingPart.def.LabelCap + " " + notMissingPart.def.IsSkinCovered(notMissingPart, pawn.health.hediffSet)); } - Find.WindowStack.Add(new Dialog_MessageBox(stringBuilder.ToString(), null, null, null, null, null, false)); + Find.WindowStack.Add(new Dialog_MessageBox(stringBuilder8.ToString(), (string)null, null, (string)null, null, (string)null, false)); }, MenuOptionPriority.Default, null, null, 0f, null, null)); - list.Add(new FloatMenuOption("does have added parts", delegate + list.Add(new FloatMenuOption("does have added parts", (Action)delegate() { - StringBuilder stringBuilder = new StringBuilder(); - foreach (BodyPartRecord current in pawn.health.hediffSet.GetNotMissingParts(BodyPartHeight.Undefined, BodyPartDepth.Undefined)) + StringBuilder stringBuilder7 = new StringBuilder(); + foreach (BodyPartRecord notMissingPart in pawn.health.hediffSet.GetNotMissingParts(BodyPartHeight.Undefined, BodyPartDepth.Undefined)) { - stringBuilder.AppendLine(current.def.LabelCap + " " + pawn.health.hediffSet.PartOrAnyAncestorHasDirectlyAddedParts(current)); + stringBuilder7.AppendLine(notMissingPart.def.LabelCap + " " + pawn.health.hediffSet.PartOrAnyAncestorHasDirectlyAddedParts(notMissingPart)); } - Find.WindowStack.Add(new Dialog_MessageBox(stringBuilder.ToString(), null, null, null, null, null, false)); + Find.WindowStack.Add(new Dialog_MessageBox(stringBuilder7.ToString(), (string)null, null, (string)null, null, (string)null, false)); }, MenuOptionPriority.Default, null, null, 0f, null, null)); - list.Add(new FloatMenuOption("GetNotMissingParts", delegate + list.Add(new FloatMenuOption("GetNotMissingParts", (Action)delegate() { - StringBuilder stringBuilder = new StringBuilder(); - foreach (BodyPartRecord current in pawn.health.hediffSet.GetNotMissingParts(BodyPartHeight.Undefined, BodyPartDepth.Undefined)) + StringBuilder stringBuilder6 = new StringBuilder(); + foreach (BodyPartRecord notMissingPart in pawn.health.hediffSet.GetNotMissingParts(BodyPartHeight.Undefined, BodyPartDepth.Undefined)) { - stringBuilder.AppendLine(current.def.LabelCap); + stringBuilder6.AppendLine(notMissingPart.def.LabelCap); } - Find.WindowStack.Add(new Dialog_MessageBox(stringBuilder.ToString(), null, null, null, null, null, false)); + Find.WindowStack.Add(new Dialog_MessageBox(stringBuilder6.ToString(), (string)null, null, (string)null, null, (string)null, false)); }, MenuOptionPriority.Default, null, null, 0f, null, null)); - list.Add(new FloatMenuOption("GetCoverageOfNotMissingNaturalParts", delegate + list.Add(new FloatMenuOption("GetCoverageOfNotMissingNaturalParts", (Action)delegate() { - StringBuilder stringBuilder = new StringBuilder(); - foreach (BodyPartRecord current in from x in pawn.RaceProps.body.AllParts + StringBuilder stringBuilder5 = new StringBuilder(); + foreach (BodyPartRecord item in from x in pawn.RaceProps.body.AllParts orderby pawn.health.hediffSet.GetCoverageOfNotMissingNaturalParts(x) descending select x) { - stringBuilder.AppendLine(current.def.LabelCap + ": " + pawn.health.hediffSet.GetCoverageOfNotMissingNaturalParts(current).ToStringPercent()); + stringBuilder5.AppendLine(item.def.LabelCap + ": " + pawn.health.hediffSet.GetCoverageOfNotMissingNaturalParts(item).ToStringPercent()); } - Find.WindowStack.Add(new Dialog_MessageBox(stringBuilder.ToString(), null, null, null, null, null, false)); + Find.WindowStack.Add(new Dialog_MessageBox(stringBuilder5.ToString(), (string)null, null, (string)null, null, (string)null, false)); }, MenuOptionPriority.Default, null, null, 0f, null, null)); - list.Add(new FloatMenuOption("parts nutrition", delegate + list.Add(new FloatMenuOption("parts nutrition", (Action)delegate() { - StringBuilder stringBuilder = new StringBuilder(); - foreach (BodyPartRecord current in from x in pawn.RaceProps.body.AllParts + StringBuilder stringBuilder4 = new StringBuilder(); + foreach (BodyPartRecord item in from x in pawn.RaceProps.body.AllParts orderby FoodUtility.GetBodyPartNutrition(pawn, x) descending select x) { - stringBuilder.AppendLine(current.def.LabelCap + ": " + FoodUtility.GetBodyPartNutrition(pawn, current)); + stringBuilder4.AppendLine(item.def.LabelCap + ": " + FoodUtility.GetBodyPartNutrition(pawn, item)); } - Find.WindowStack.Add(new Dialog_MessageBox(stringBuilder.ToString(), null, null, null, null, null, false)); + Find.WindowStack.Add(new Dialog_MessageBox(stringBuilder4.ToString(), (string)null, null, (string)null, null, (string)null, false)); }, MenuOptionPriority.Default, null, null, 0f, null, null)); - list.Add(new FloatMenuOption("test old injury pain factor probability", delegate + list.Add(new FloatMenuOption("test old injury pain factor probability", (Action)delegate { - StringBuilder stringBuilder = new StringBuilder(); - int num = 0; - int num2 = 0; - int num3 = 0; - float num4 = 0f; - int num5 = 10000; - for (int i = 0; i < num5; i++) + StringBuilder stringBuilder3 = new StringBuilder(); + int num4 = 0; + int num5 = 0; + int num6 = 0; + float num7 = 0f; + int num8 = 10000; + for (int num9 = 0; num9 < num8; num9++) { float randomPainFactor = OldInjuryUtility.GetRandomPainFactor(); - if (randomPainFactor < 0f) + if (randomPainFactor < 0.0) { Log.Error("Pain factor < 0"); } - if (randomPainFactor == 0f) + if (randomPainFactor == 0.0) { - num++; + num4++; } - if (randomPainFactor < 1f) + if (randomPainFactor < 1.0) { - num2++; + num5++; } - if (randomPainFactor < 5f) + if (randomPainFactor < 5.0) { - num3++; + num6++; } - if (randomPainFactor > num4) + if (randomPainFactor > num7) { - num4 = randomPainFactor; + num7 = randomPainFactor; } } - stringBuilder.AppendLine("total: " + num5); - stringBuilder.AppendLine(string.Concat(new object[] - { - "0: ", - num, - " (", - ((float)num / (float)num5).ToStringPercent(), - ")" - })); - stringBuilder.AppendLine(string.Concat(new object[] - { - "< 1: ", - num2, - " (", - ((float)num2 / (float)num5).ToStringPercent(), - ")" - })); - stringBuilder.AppendLine(string.Concat(new object[] - { - "< 5: ", - num3, - " (", - ((float)num3 / (float)num5).ToStringPercent(), - ")" - })); - stringBuilder.AppendLine("max: " + num4); - Find.WindowStack.Add(new Dialog_MessageBox(stringBuilder.ToString(), null, null, null, null, null, false)); + stringBuilder3.AppendLine("total: " + num8); + stringBuilder3.AppendLine("0: " + num4 + " (" + ((float)num4 / (float)num8).ToStringPercent() + ")"); + stringBuilder3.AppendLine("< 1: " + num5 + " (" + ((float)num5 / (float)num8).ToStringPercent() + ")"); + stringBuilder3.AppendLine("< 5: " + num6 + " (" + ((float)num6 / (float)num8).ToStringPercent() + ")"); + stringBuilder3.AppendLine("max: " + num7); + Find.WindowStack.Add(new Dialog_MessageBox(stringBuilder3.ToString(), (string)null, null, (string)null, null, (string)null, false)); }, MenuOptionPriority.Default, null, null, 0f, null, null)); - list.Add(new FloatMenuOption("HediffGiver_Birthday chance at age", delegate + list.Add(new FloatMenuOption("HediffGiver_Birthday chance at age", (Action)delegate() { List list2 = new List(); - foreach (HediffGiverSetDef current in pawn.RaceProps.hediffGiverSets) + List.Enumerator enumerator3 = pawn.RaceProps.hediffGiverSets.GetEnumerator(); + try { - foreach (HediffGiver_Birthday current2 in current.hediffGivers.OfType()) + HediffGiver_Birthday hLocal; + while (enumerator3.MoveNext()) { - HediffGiver_Birthday hLocal = current2; - FloatMenuOption item = new FloatMenuOption(current.defName + " - " + current2.hediff.defName, delegate + HediffGiverSetDef current3 = enumerator3.Current; + foreach (HediffGiver_Birthday item2 in current3.hediffGivers.OfType()) { - StringBuilder stringBuilder = new StringBuilder(); - stringBuilder.AppendLine("% of pawns which will have at least 1 " + hLocal.hediff.label + " at age X:"); - stringBuilder.AppendLine(); - int num = 1; - while ((float)num < pawn.RaceProps.lifeExpectancy + 20f) + hLocal = item2; + FloatMenuOption item = new FloatMenuOption(current3.defName + " - " + item2.hediff.defName, (Action)delegate() { - stringBuilder.AppendLine(num + ": " + hLocal.DebugChanceToHaveAtAge(pawn, num).ToStringPercent()); - num++; - } - Find.WindowStack.Add(new Dialog_MessageBox(stringBuilder.ToString(), null, null, null, null, null, false)); - }, MenuOptionPriority.Default, null, null, 0f, null, null); - list2.Add(item); + StringBuilder stringBuilder2 = new StringBuilder(); + stringBuilder2.AppendLine("% of pawns which will have at least 1 " + hLocal.hediff.label + " at age X:"); + stringBuilder2.AppendLine(); + int num3 = 1; + while ((float)num3 < pawn.RaceProps.lifeExpectancy + 20.0) + { + stringBuilder2.AppendLine(num3 + ": " + hLocal.DebugChanceToHaveAtAge(pawn, num3).ToStringPercent()); + num3++; + } + Find.WindowStack.Add(new Dialog_MessageBox(stringBuilder2.ToString(), (string)null, null, (string)null, null, (string)null, false)); + }, MenuOptionPriority.Default, null, null, 0f, null, null); + list2.Add(item); + } } } + finally + { + ((IDisposable)(object)enumerator3).Dispose(); + } Find.WindowStack.Add(new FloatMenu(list2)); }, MenuOptionPriority.Default, null, null, 0f, null, null)); - list.Add(new FloatMenuOption("HediffGiver_Birthday count at age", delegate + list.Add(new FloatMenuOption("HediffGiver_Birthday count at age", (Action)delegate() { StringBuilder stringBuilder = new StringBuilder(); stringBuilder.AppendLine("Average hediffs count (from HediffGiver_Birthday) at age X:"); stringBuilder.AppendLine(); int num = 1; - while ((float)num < pawn.RaceProps.lifeExpectancy + 20f) + while ((float)num < pawn.RaceProps.lifeExpectancy + 20.0) { float num2 = 0f; - foreach (HediffGiverSetDef current in pawn.RaceProps.hediffGiverSets) + List.Enumerator enumerator = pawn.RaceProps.hediffGiverSets.GetEnumerator(); + try { - foreach (HediffGiver_Birthday current2 in current.hediffGivers.OfType()) + while (enumerator.MoveNext()) { - num2 += current2.DebugChanceToHaveAtAge(pawn, num); + HediffGiverSetDef current = enumerator.Current; + foreach (HediffGiver_Birthday item in current.hediffGivers.OfType()) + { + num2 += item.DebugChanceToHaveAtAge(pawn, num); + } } } + finally + { + ((IDisposable)(object)enumerator).Dispose(); + } stringBuilder.AppendLine(num + ": " + num2.ToStringDecimalIfSmall()); num++; } - Find.WindowStack.Add(new Dialog_MessageBox(stringBuilder.ToString(), null, null, null, null, null, false)); + Find.WindowStack.Add(new Dialog_MessageBox(stringBuilder.ToString(), (string)null, null, (string)null, null, (string)null, false)); }, MenuOptionPriority.Default, null, null, 0f, null, null)); Find.WindowStack.Add(new FloatMenu(list)); } @@ -927,72 +902,72 @@ orderby FoodUtility.GetBodyPartNutrition(pawn, x) descending public static Pair GetEfficiencyLabel(Pawn pawn, PawnCapacityDef activity) { float level = pawn.health.capacities.GetLevel(activity); - string first = string.Empty; - Color second = Color.white; - if (level <= 0f) + string empty = string.Empty; + Color white = Color.white; + if (level <= 0.0) { - first = "None".Translate(); - second = HealthUtility.DarkRedColor; + empty = "None".Translate(); + white = HealthUtility.DarkRedColor; } - else if (level < 0.4f) + else if (level < 0.40000000596046448) { - first = "VeryPoor".Translate(); - second = HealthCardUtility.VeryPoorColor; + empty = "VeryPoor".Translate(); + white = HealthCardUtility.VeryPoorColor; } - else if (level < 0.7f) + else if (level < 0.699999988079071) { - first = "Poor".Translate(); - second = HealthCardUtility.PoorColor; + empty = "Poor".Translate(); + white = HealthCardUtility.PoorColor; } - else if (level < 1f && !Mathf.Approximately(level, 1f)) + else if (level < 1.0 && !Mathf.Approximately(level, 1f)) { - first = "Weakened".Translate(); - second = HealthCardUtility.WeakenedColor; + empty = "Weakened".Translate(); + white = HealthCardUtility.WeakenedColor; } else if (Mathf.Approximately(level, 1f)) { - first = "GoodCondition".Translate(); - second = HealthUtility.GoodConditionColor; + empty = "GoodCondition".Translate(); + white = HealthUtility.GoodConditionColor; } else { - first = "Enhanced".Translate(); - second = HealthCardUtility.EnhancedColor; + empty = "Enhanced".Translate(); + white = HealthCardUtility.EnhancedColor; } - return new Pair(first, second); + return new Pair(empty, white); } public static Pair GetPainLabel(Pawn pawn) { float painTotal = pawn.health.hediffSet.PainTotal; - string first = string.Empty; - Color second = Color.white; + string empty = string.Empty; + Color white = Color.white; if (Mathf.Approximately(painTotal, 0f)) { - first = "NoPain".Translate(); - second = HealthUtility.GoodConditionColor; + empty = "NoPain".Translate(); + white = HealthUtility.GoodConditionColor; } - else if (painTotal < 0.15f) + else if (painTotal < 0.15000000596046448) { - first = "LittlePain".Translate(); - second = Color.gray; + empty = "LittlePain".Translate(); + white = Color.gray; } - else if (painTotal < 0.4f) + else if (painTotal < 0.40000000596046448) { - first = "MediumPain".Translate(); - second = HealthCardUtility.MediumPainColor; + empty = "MediumPain".Translate(); + white = HealthCardUtility.MediumPainColor; } - else if (painTotal < 0.8f) + else if (painTotal < 0.800000011920929) { - first = "SeverePain".Translate(); - second = HealthCardUtility.SeverePainColor; + empty = "SeverePain".Translate(); + white = HealthCardUtility.SeverePainColor; } else { - first = "ExtremePain".Translate(); - second = HealthUtility.DarkRedColor; + empty = "ExtremePain".Translate(); + white = HealthUtility.DarkRedColor; } - return new Pair(first, second); + return new Pair(empty, white); } } } diff --git a/Assembly-CSharp/RimWorld/HediffDefOf.cs b/Assembly-CSharp/RimWorld/HediffDefOf.cs index 13772273e..a52a91b09 100644 --- a/Assembly-CSharp/RimWorld/HediffDefOf.cs +++ b/Assembly-CSharp/RimWorld/HediffDefOf.cs @@ -1,4 +1,3 @@ -using System; using Verse; namespace RimWorld diff --git a/Assembly-CSharp/RimWorld/HediffGiverSetDef.cs b/Assembly-CSharp/RimWorld/HediffGiverSetDef.cs index cb4db233c..b2a66a3b8 100644 --- a/Assembly-CSharp/RimWorld/HediffGiverSetDef.cs +++ b/Assembly-CSharp/RimWorld/HediffGiverSetDef.cs @@ -1,4 +1,3 @@ -using System; using System.Collections.Generic; using Verse; diff --git a/Assembly-CSharp/RimWorld/Hediff_Addiction.cs b/Assembly-CSharp/RimWorld/Hediff_Addiction.cs index 52c527703..a3d46db01 100644 --- a/Assembly-CSharp/RimWorld/Hediff_Addiction.cs +++ b/Assembly-CSharp/RimWorld/Hediff_Addiction.cs @@ -1,4 +1,3 @@ -using System; using System.Collections.Generic; using Verse; @@ -14,14 +13,14 @@ public Need_Chemical Need { get { - if (this.pawn.Dead) + if (base.pawn.Dead) { return null; } - List allNeeds = this.pawn.needs.AllNeeds; + List allNeeds = base.pawn.needs.AllNeeds; for (int i = 0; i < allNeeds.Count; i++) { - if (allNeeds[i].def == this.def.causesNeed) + if (allNeeds[i].def == base.def.causesNeed) { return (Need_Chemical)allNeeds[i]; } @@ -37,7 +36,7 @@ public ChemicalDef Chemical List allDefsListForReading = DefDatabase.AllDefsListForReading; for (int i = 0; i < allDefsListForReading.Count; i++) { - if (allDefsListForReading[i].addictionHediff == this.def) + if (allDefsListForReading[i].addictionHediff == base.def) { return allDefsListForReading[i]; } @@ -50,9 +49,9 @@ public override string LabelInBrackets { get { - if (this.CurStageIndex == 1 && this.def.CompProps() != null) + if (this.CurStageIndex == 1 && base.def.CompProps() != null) { - return base.LabelInBrackets + " " + (1f - this.Severity).ToStringPercent(); + return base.LabelInBrackets + " " + ((float)(1.0 - this.Severity)).ToStringPercent(); } return base.LabelInBrackets; } @@ -63,17 +62,17 @@ public override int CurStageIndex get { Need_Chemical need = this.Need; - if (need == null || need.CurCategory != DrugDesireCategory.Withdrawal) + if (need != null && need.CurCategory == DrugDesireCategory.Withdrawal) { - return 0; + return 1; } - return 1; + return 0; } } public void Notify_NeedCategoryChanged() { - this.pawn.health.Notify_HediffChanged(this); + base.pawn.health.Notify_HediffChanged(this); } } } diff --git a/Assembly-CSharp/RimWorld/Hediff_HeartAttack.cs b/Assembly-CSharp/RimWorld/Hediff_HeartAttack.cs index 7436913b3..b17b71d7c 100644 --- a/Assembly-CSharp/RimWorld/Hediff_HeartAttack.cs +++ b/Assembly-CSharp/RimWorld/Hediff_HeartAttack.cs @@ -1,4 +1,3 @@ -using System; using Verse; namespace RimWorld @@ -28,7 +27,7 @@ public override void ExposeData() public override void Tick() { base.Tick(); - if (this.pawn.IsHashIntervalTick((int)(5000f * this.intervalFactor))) + if (base.pawn.IsHashIntervalTick((int)(5000.0 * this.intervalFactor))) { this.Severity += Rand.Range(-0.4f, 0.6f); } @@ -37,24 +36,18 @@ public override void Tick() public override void Tended(float quality, int batchPosition = 0) { base.Tended(quality, 0); - float num = 0.65f * quality; + float num = (float)(0.64999997615814209 * quality); if (Rand.Value < num) { - if (batchPosition == 0 && this.pawn.Spawned) + if (batchPosition == 0 && base.pawn.Spawned) { - MoteMaker.ThrowText(this.pawn.DrawPos, this.pawn.Map, "TextMote_TreatSuccess".Translate(new object[] - { - num.ToStringPercent() - }), 6.5f); + MoteMaker.ThrowText(base.pawn.DrawPos, base.pawn.Map, "TextMote_TreatSuccess".Translate(num.ToStringPercent()), 6.5f); } this.Severity -= 0.3f; } - else if (batchPosition == 0 && this.pawn.Spawned) + else if (batchPosition == 0 && base.pawn.Spawned) { - MoteMaker.ThrowText(this.pawn.DrawPos, this.pawn.Map, "TextMote_TreatFailed".Translate(new object[] - { - num.ToStringPercent() - }), 6.5f); + MoteMaker.ThrowText(base.pawn.DrawPos, base.pawn.Map, "TextMote_TreatFailed".Translate(num.ToStringPercent()), 6.5f); } } } diff --git a/Assembly-CSharp/RimWorld/History.cs b/Assembly-CSharp/RimWorld/History.cs index a81e0c9ed..76a040705 100644 --- a/Assembly-CSharp/RimWorld/History.cs +++ b/Assembly-CSharp/RimWorld/History.cs @@ -1,4 +1,3 @@ -using System; using System.Collections.Generic; using Verse; @@ -13,10 +12,12 @@ public sealed class History : IExposable public History() { this.autoRecorderGroups = new List(); - foreach (HistoryAutoRecorderGroupDef current in DefDatabase.AllDefs) + foreach (HistoryAutoRecorderGroupDef allDef in DefDatabase.AllDefs) { - HistoryAutoRecorderGroup historyAutoRecorderGroup = new HistoryAutoRecorderGroup(); - historyAutoRecorderGroup.def = current; + HistoryAutoRecorderGroup historyAutoRecorderGroup = new HistoryAutoRecorderGroup + { + def = allDef + }; historyAutoRecorderGroup.CreateRecorders(); this.autoRecorderGroups.Add(historyAutoRecorderGroup); } diff --git a/Assembly-CSharp/RimWorld/HistoryAutoRecorder.cs b/Assembly-CSharp/RimWorld/HistoryAutoRecorder.cs index e883a57a5..511a13f74 100644 --- a/Assembly-CSharp/RimWorld/HistoryAutoRecorder.cs +++ b/Assembly-CSharp/RimWorld/HistoryAutoRecorder.cs @@ -18,11 +18,10 @@ public HistoryAutoRecorder() public void Tick() { int ticksGame = Find.TickManager.TicksGame; - if (ticksGame % this.def.recordTicksFrequency == 0 || !this.records.Any()) - { - float item = this.def.Worker.PullRecord(); - this.records.Add(item); - } + if (ticksGame % this.def.recordTicksFrequency != 0 && this.records.Any()) + return; + float item = this.def.Worker.PullRecord(); + this.records.Add(item); } public void ExposeData() @@ -46,9 +45,9 @@ public void ExposeData() { int num = array.Length / 4; this.records.Clear(); - for (int k = 0; k < num; k++) + for (int num2 = 0; num2 < num; num2++) { - float item = BitConverter.ToSingle(array, k * 4); + float item = BitConverter.ToSingle(array, num2 * 4); this.records.Add(item); } } diff --git a/Assembly-CSharp/RimWorld/HistoryAutoRecorderGroup.cs b/Assembly-CSharp/RimWorld/HistoryAutoRecorderGroup.cs index 6346392ab..2850207c7 100644 --- a/Assembly-CSharp/RimWorld/HistoryAutoRecorderGroup.cs +++ b/Assembly-CSharp/RimWorld/HistoryAutoRecorderGroup.cs @@ -23,30 +23,48 @@ public HistoryAutoRecorderGroup() public void CreateRecorders() { - foreach (HistoryAutoRecorderDef current in this.def.historyAutoRecorderDefs) + List.Enumerator enumerator = this.def.historyAutoRecorderDefs.GetEnumerator(); + try { - HistoryAutoRecorder historyAutoRecorder = new HistoryAutoRecorder(); - historyAutoRecorder.def = current; - this.recorders.Add(historyAutoRecorder); + while (enumerator.MoveNext()) + { + HistoryAutoRecorderDef current = enumerator.Current; + HistoryAutoRecorder historyAutoRecorder = new HistoryAutoRecorder(); + historyAutoRecorder.def = current; + this.recorders.Add(historyAutoRecorder); + } + } + finally + { + ((IDisposable)(object)enumerator).Dispose(); } } public float GetMaxDay() { float num = 0f; - foreach (HistoryAutoRecorder current in this.recorders) + List.Enumerator enumerator = this.recorders.GetEnumerator(); + try { - int count = current.records.Count; - if (count != 0) + while (enumerator.MoveNext()) { - float num2 = (float)((count - 1) * current.def.recordTicksFrequency) / 60000f; - if (num2 > num) + HistoryAutoRecorder current = enumerator.Current; + int count = current.records.Count; + if (count != 0) { - num = num2; + float num2 = (float)((float)((count - 1) * current.def.recordTicksFrequency) / 60000.0); + if (num2 > num) + { + num = num2; + } } } + return num; + } + finally + { + ((IDisposable)(object)enumerator).Dispose(); } - return num; } public void Tick() @@ -73,7 +91,7 @@ public void DrawGraph(Rect graphRect, Rect legendRect, Vector2 section, SimpleCu simpleCurveDrawInfo.curve = new SimpleCurve(); for (int j = 0; j < historyAutoRecorder.records.Count; j++) { - simpleCurveDrawInfo.curve.Add(new CurvePoint((float)j * (float)historyAutoRecorder.def.recordTicksFrequency / 60000f, historyAutoRecorder.records[j]), false); + simpleCurveDrawInfo.curve.Add(new CurvePoint((float)((float)j * (float)historyAutoRecorder.def.recordTicksFrequency / 60000.0), historyAutoRecorder.records[j]), false); } simpleCurveDrawInfo.curve.SortPoints(); if (historyAutoRecorder.records.Count == 1) diff --git a/Assembly-CSharp/RimWorld/HistoryAutoRecorderGroupDef.cs b/Assembly-CSharp/RimWorld/HistoryAutoRecorderGroupDef.cs index 9ee608c44..79476ad3f 100644 --- a/Assembly-CSharp/RimWorld/HistoryAutoRecorderGroupDef.cs +++ b/Assembly-CSharp/RimWorld/HistoryAutoRecorderGroupDef.cs @@ -1,4 +1,3 @@ -using System; using System.Collections.Generic; using UnityEngine; using Verse; diff --git a/Assembly-CSharp/RimWorld/HistoryAutoRecorderWorker.cs b/Assembly-CSharp/RimWorld/HistoryAutoRecorderWorker.cs index a5a822a98..31f3d1d04 100644 --- a/Assembly-CSharp/RimWorld/HistoryAutoRecorderWorker.cs +++ b/Assembly-CSharp/RimWorld/HistoryAutoRecorderWorker.cs @@ -1,5 +1,3 @@ -using System; - namespace RimWorld { public class HistoryAutoRecorderWorker diff --git a/Assembly-CSharp/RimWorld/HistoryAutoRecorderWorker_ColonistMood.cs b/Assembly-CSharp/RimWorld/HistoryAutoRecorderWorker_ColonistMood.cs index d3c7fa03e..77f6f20e7 100644 --- a/Assembly-CSharp/RimWorld/HistoryAutoRecorderWorker_ColonistMood.cs +++ b/Assembly-CSharp/RimWorld/HistoryAutoRecorderWorker_ColonistMood.cs @@ -10,11 +10,11 @@ public class HistoryAutoRecorderWorker_ColonistMood : HistoryAutoRecorderWorker public override float PullRecord() { IEnumerable allMaps_FreeColonists = PawnsFinder.AllMaps_FreeColonists; - if (!allMaps_FreeColonists.Any()) + if (!allMaps_FreeColonists.Any()) { return 0f; } - return allMaps_FreeColonists.Average((Pawn x) => x.needs.mood.CurLevel * 100f); + return allMaps_FreeColonists.Average((Func)((Pawn x) => (float)(x.needs.mood.CurLevel * 100.0))); } } } diff --git a/Assembly-CSharp/RimWorld/HistoryAutoRecorderWorker_FreeColonists.cs b/Assembly-CSharp/RimWorld/HistoryAutoRecorderWorker_FreeColonists.cs index 0a1f6a3d5..4f0126375 100644 --- a/Assembly-CSharp/RimWorld/HistoryAutoRecorderWorker_FreeColonists.cs +++ b/Assembly-CSharp/RimWorld/HistoryAutoRecorderWorker_FreeColonists.cs @@ -1,6 +1,4 @@ -using System; using System.Linq; -using Verse; namespace RimWorld { @@ -8,7 +6,7 @@ public class HistoryAutoRecorderWorker_FreeColonists : HistoryAutoRecorderWorker { public override float PullRecord() { - return (float)PawnsFinder.AllMapsCaravansAndTravelingTransportPods_FreeColonists.Count(); + return (float)PawnsFinder.AllMapsCaravansAndTravelingTransportPods_FreeColonists.Count(); } } } diff --git a/Assembly-CSharp/RimWorld/HistoryAutoRecorderWorker_Prisoners.cs b/Assembly-CSharp/RimWorld/HistoryAutoRecorderWorker_Prisoners.cs index 0649e7bcf..2baa7ab3f 100644 --- a/Assembly-CSharp/RimWorld/HistoryAutoRecorderWorker_Prisoners.cs +++ b/Assembly-CSharp/RimWorld/HistoryAutoRecorderWorker_Prisoners.cs @@ -1,6 +1,4 @@ -using System; using System.Linq; -using Verse; namespace RimWorld { @@ -8,7 +6,7 @@ public class HistoryAutoRecorderWorker_Prisoners : HistoryAutoRecorderWorker { public override float PullRecord() { - return (float)PawnsFinder.AllMapsCaravansAndTravelingTransportPods_PrisonersOfColony.Count(); + return (float)PawnsFinder.AllMapsCaravansAndTravelingTransportPods_PrisonersOfColony.Count(); } } } diff --git a/Assembly-CSharp/RimWorld/HistoryAutoRecorderWorker_WealthBuildings.cs b/Assembly-CSharp/RimWorld/HistoryAutoRecorderWorker_WealthBuildings.cs index bffbaec17..1945d2c5f 100644 --- a/Assembly-CSharp/RimWorld/HistoryAutoRecorderWorker_WealthBuildings.cs +++ b/Assembly-CSharp/RimWorld/HistoryAutoRecorderWorker_WealthBuildings.cs @@ -1,4 +1,3 @@ -using System; using System.Collections.Generic; using Verse; diff --git a/Assembly-CSharp/RimWorld/HistoryAutoRecorderWorker_WealthItems.cs b/Assembly-CSharp/RimWorld/HistoryAutoRecorderWorker_WealthItems.cs index 4fe09b9dd..2ee2aa45d 100644 --- a/Assembly-CSharp/RimWorld/HistoryAutoRecorderWorker_WealthItems.cs +++ b/Assembly-CSharp/RimWorld/HistoryAutoRecorderWorker_WealthItems.cs @@ -1,4 +1,3 @@ -using System; using System.Collections.Generic; using Verse; diff --git a/Assembly-CSharp/RimWorld/HistoryAutoRecorderWorker_WealthTotal.cs b/Assembly-CSharp/RimWorld/HistoryAutoRecorderWorker_WealthTotal.cs index 7c2695829..e22c15a5d 100644 --- a/Assembly-CSharp/RimWorld/HistoryAutoRecorderWorker_WealthTotal.cs +++ b/Assembly-CSharp/RimWorld/HistoryAutoRecorderWorker_WealthTotal.cs @@ -1,4 +1,3 @@ -using System; using System.Collections.Generic; using Verse; diff --git a/Assembly-CSharp/RimWorld/Hive.cs b/Assembly-CSharp/RimWorld/Hive.cs index 37ec17876..bd1ced10b 100644 --- a/Assembly-CSharp/RimWorld/Hive.cs +++ b/Assembly-CSharp/RimWorld/Hive.cs @@ -1,6 +1,5 @@ using System; using System.Collections.Generic; -using System.Diagnostics; using System.Linq; using Verse; using Verse.AI.Group; @@ -37,7 +36,7 @@ private Lord Lord { get { - Predicate hasDefendHiveLord = delegate(Pawn x) + Predicate hasDefendHiveLord = (Predicate)delegate(Pawn x) { Lord lord = x.GetLord(); return lord != null && lord.LordJob is LordJob_DefendAndExpandHive; @@ -47,20 +46,17 @@ private Lord Lord { if (foundPawn == null) { - RegionTraverser.BreadthFirstTraverse(this.GetRegion(RegionType.Set_Passable), (Region from, Region to) => true, delegate(Region r) + RegionTraverser.BreadthFirstTraverse(this.GetRegion(RegionType.Set_Passable), (RegionEntryPredicate)((Region from, Region to) => true), (RegionProcessor)delegate(Region r) { List list = r.ListerThings.ThingsOfDef(ThingDefOf.Hive); for (int i = 0; i < list.Count; i++) { - if (list[i] != this) + if (list[i] != this && list[i].Faction == base.Faction) { - if (list[i].Faction == this.Faction) + foundPawn = ((Hive)list[i]).spawnedPawns.Find(hasDefendHiveLord); + if (foundPawn != null) { - foundPawn = ((Hive)list[i]).spawnedPawns.Find(hasDefendHiveLord); - if (foundPawn != null) - { - return true; - } + return true; } } } @@ -106,13 +102,11 @@ public override void SpawnSetup(Map map, bool respawningAfterLoad) private void SpawnInitialPawnsNow() { this.ticksToSpawnInitialPawns = -1; - while (this.SpawnedPawnsPoints < 200f) + while (this.SpawnedPawnsPoints < 200.0) { - Pawn pawn; + Pawn pawn = default(Pawn); if (!this.TrySpawnPawn(out pawn)) - { return; - } } this.CalculateNextPawnSpawnTick(); } @@ -139,14 +133,10 @@ public override void TickRare() } if (Find.TickManager.TicksGame >= this.nextPawnSpawnTick) { - if (this.SpawnedPawnsPoints < 500f) + Pawn pawn = default(Pawn); + if (this.SpawnedPawnsPoints < 500.0 && this.TrySpawnPawn(out pawn) && pawn.caller != null) { - Pawn pawn; - bool flag = this.TrySpawnPawn(out pawn); - if (flag && pawn.caller != null) - { - pawn.caller.DoCall(); - } + pawn.caller.DoCall(); } this.CalculateNextPawnSpawnTick(); } @@ -179,7 +169,7 @@ public override void PostApplyDamage(DamageInfo dinfo, float totalDamageDealt) lord.ReceiveMemo(Hive.MemoAttackedByEnemy); } } - if (dinfo.Def == DamageDefOf.Flame && (float)this.HitPoints < (float)base.MaxHitPoints * 0.3f) + if (dinfo.Def == DamageDefOf.Flame && (float)this.HitPoints < (float)base.MaxHitPoints * 0.30000001192092896) { Lord lord2 = this.Lord; if (lord2 != null) @@ -199,7 +189,7 @@ public override void ExposeData() Scribe_Values.Look(ref this.ticksToSpawnInitialPawns, "ticksToSpawnInitialPawns", 0, false); if (Scribe.mode == LoadSaveMode.PostLoadInit) { - this.spawnedPawns.RemoveAll((Pawn x) => x == null); + this.spawnedPawns.RemoveAll((Predicate)((Pawn x) => x == null)); } } @@ -217,16 +207,16 @@ private void Activate() private void CalculateNextPawnSpawnTick() { float num = GenMath.LerpDouble(0f, 5f, 1f, 0.5f, (float)this.spawnedPawns.Count); - this.nextPawnSpawnTick = Find.TickManager.TicksGame + (int)(Hive.PawnSpawnIntervalDays.RandomInRange * 60000f / (num * Find.Storyteller.difficulty.enemyReproductionRateFactor)); + this.nextPawnSpawnTick = Find.TickManager.TicksGame + (int)(Hive.PawnSpawnIntervalDays.RandomInRange * 60000.0 / (num * Find.Storyteller.difficulty.enemyReproductionRateFactor)); } private void FilterOutUnspawnedPawns() { - for (int i = this.spawnedPawns.Count - 1; i >= 0; i--) + for (int num = this.spawnedPawns.Count - 1; num >= 0; num--) { - if (!this.spawnedPawns[i].Spawned) + if (!this.spawnedPawns[num].Spawned) { - this.spawnedPawns.RemoveAt(i); + this.spawnedPawns.RemoveAt(num); } } } @@ -239,10 +229,10 @@ private bool TrySpawnPawn(out Pawn pawn) list.Add(PawnKindDefOf.Megaspider); float curPoints = this.SpawnedPawnsPoints; IEnumerable source = from x in list - where curPoints + x.combatPower <= 500f + where curPoints + x.combatPower <= 500.0 select x; - PawnKindDef kindDef; - if (!source.TryRandomElement(out kindDef)) + PawnKindDef kindDef = default(PawnKindDef); + if (!source.TryRandomElement(out kindDef)) { pawn = null; return false; @@ -259,27 +249,35 @@ private bool TrySpawnPawn(out Pawn pawn) return true; } - [DebuggerHidden] public override IEnumerable GetGizmos() { - Hive.c__Iterator160 c__Iterator = new Hive.c__Iterator160(); - c__Iterator.<>f__this = this; - Hive.c__Iterator160 expr_0E = c__Iterator; - expr_0E.$PC = -2; - return expr_0E; + foreach (Gizmo gizmo in base.GetGizmos()) + { + yield return gizmo; + } + if (Prefs.DevMode) + { + yield return (Gizmo)new Command_Action + { + defaultLabel = "DEBUG: Spawn pawn", + icon = TexCommand.ReleaseAnimals, + action = (Action)delegate + { + Pawn pawn = default(Pawn); + ((_003CGetGizmos_003Ec__Iterator160)/*Error near IL_00e5: stateMachine*/)._003C_003Ef__this.TrySpawnPawn(out pawn); + } + }; + } } public override bool PreventPlayerSellingThingsNearby(out string reason) { - if (this.spawnedPawns.Count > 0) + if (this.spawnedPawns.Count > 0 && this.spawnedPawns.Any((Predicate)((Pawn p) => !p.Downed))) { - if (this.spawnedPawns.Any((Pawn p) => !p.Downed)) - { - reason = this.def.label; - return true; - } + reason = base.def.label; + return true; } - reason = null; + reason = (string)null; return false; } diff --git a/Assembly-CSharp/RimWorld/HivesUtility.cs b/Assembly-CSharp/RimWorld/HivesUtility.cs index f2289e7ed..993ec1004 100644 --- a/Assembly-CSharp/RimWorld/HivesUtility.cs +++ b/Assembly-CSharp/RimWorld/HivesUtility.cs @@ -1,4 +1,3 @@ -using System; using System.Collections.Generic; using Verse; diff --git a/Assembly-CSharp/RimWorld/HoldOffset.cs b/Assembly-CSharp/RimWorld/HoldOffset.cs index 43bafaace..b9320869f 100644 --- a/Assembly-CSharp/RimWorld/HoldOffset.cs +++ b/Assembly-CSharp/RimWorld/HoldOffset.cs @@ -1,4 +1,3 @@ -using System; using UnityEngine; namespace RimWorld diff --git a/Assembly-CSharp/RimWorld/HoldOffsetSet.cs b/Assembly-CSharp/RimWorld/HoldOffsetSet.cs index df94744b4..538e4f230 100644 --- a/Assembly-CSharp/RimWorld/HoldOffsetSet.cs +++ b/Assembly-CSharp/RimWorld/HoldOffsetSet.cs @@ -1,4 +1,3 @@ -using System; using Verse; namespace RimWorld diff --git a/Assembly-CSharp/RimWorld/HostilityResponseMode.cs b/Assembly-CSharp/RimWorld/HostilityResponseMode.cs index 18c5e83dd..b504d816d 100644 --- a/Assembly-CSharp/RimWorld/HostilityResponseMode.cs +++ b/Assembly-CSharp/RimWorld/HostilityResponseMode.cs @@ -1,11 +1,9 @@ -using System; - namespace RimWorld { public enum HostilityResponseMode { - Ignore, - Attack, - Flee + Ignore = 0, + Attack = 1, + Flee = 2 } } diff --git a/Assembly-CSharp/RimWorld/HostilityResponseModeUtility.cs b/Assembly-CSharp/RimWorld/HostilityResponseModeUtility.cs index 94d5f890a..b4cb42b8f 100644 --- a/Assembly-CSharp/RimWorld/HostilityResponseModeUtility.cs +++ b/Assembly-CSharp/RimWorld/HostilityResponseModeUtility.cs @@ -1,4 +1,3 @@ -using System; using UnityEngine; using Verse; using Verse.Sound; @@ -19,14 +18,22 @@ public static Texture2D GetIcon(this HostilityResponseMode response) switch (response) { case HostilityResponseMode.Ignore: + { return HostilityResponseModeUtility.IgnoreIcon; + } case HostilityResponseMode.Attack: + { return HostilityResponseModeUtility.AttackIcon; + } case HostilityResponseMode.Flee: + { return HostilityResponseModeUtility.FleeIcon; + } default: + { return BaseContent.BadTex; } + } } public static HostilityResponseMode GetNextResponse(Pawn pawn) @@ -34,18 +41,26 @@ public static HostilityResponseMode GetNextResponse(Pawn pawn) switch (pawn.playerSettings.hostilityResponse) { case HostilityResponseMode.Ignore: + { if (pawn.story != null && pawn.story.WorkTagIsDisabled(WorkTags.Violent)) { return HostilityResponseMode.Flee; } return HostilityResponseMode.Attack; + } case HostilityResponseMode.Attack: + { return HostilityResponseMode.Flee; + } case HostilityResponseMode.Flee: + { return HostilityResponseMode.Ignore; + } default: + { return HostilityResponseMode.Ignore; } + } } public static string GetLabel(this HostilityResponseMode response) @@ -64,14 +79,7 @@ public static void DrawResponseButton(Vector2 pos, Pawn pawn) PlayerKnowledgeDatabase.KnowledgeDemonstrated(ConceptDefOf.HostilityResponse, KnowledgeAmount.SpecificInteraction); } UIHighlighter.HighlightOpportunity(rect, "HostilityResponse"); - TooltipHandler.TipRegion(rect, string.Concat(new string[] - { - "HostilityReponseTip".Translate(), - "\n\n", - "HostilityResponseCurrentMode".Translate(), - ": ", - pawn.playerSettings.hostilityResponse.GetLabel() - })); + TooltipHandler.TipRegion(rect, "HostilityReponseTip".Translate() + "\n\n" + "HostilityResponseCurrentMode".Translate() + ": " + pawn.playerSettings.hostilityResponse.GetLabel()); } } } diff --git a/Assembly-CSharp/RimWorld/HungerCategory.cs b/Assembly-CSharp/RimWorld/HungerCategory.cs index 583526af3..7673746a7 100644 --- a/Assembly-CSharp/RimWorld/HungerCategory.cs +++ b/Assembly-CSharp/RimWorld/HungerCategory.cs @@ -1,12 +1,10 @@ -using System; - namespace RimWorld { public enum HungerCategory : byte { - Fed, - Hungry, - UrgentlyHungry, - Starving + Fed = 0, + Hungry = 1, + UrgentlyHungry = 2, + Starving = 3 } } diff --git a/Assembly-CSharp/RimWorld/HungerLevelUtility.cs b/Assembly-CSharp/RimWorld/HungerLevelUtility.cs index 32deeb391..8c41d4867 100644 --- a/Assembly-CSharp/RimWorld/HungerLevelUtility.cs +++ b/Assembly-CSharp/RimWorld/HungerLevelUtility.cs @@ -9,17 +9,27 @@ public static string GetLabel(this HungerCategory hunger) { switch (hunger) { - case HungerCategory.Fed: - return "HungerLevel_Fed".Translate(); - case HungerCategory.Hungry: - return "HungerLevel_Hungry".Translate(); - case HungerCategory.UrgentlyHungry: - return "HungerLevel_UrgentlyHungry".Translate(); case HungerCategory.Starving: + { return "HungerLevel_Starving".Translate(); + } + case HungerCategory.UrgentlyHungry: + { + return "HungerLevel_UrgentlyHungry".Translate(); + } + case HungerCategory.Hungry: + { + return "HungerLevel_Hungry".Translate(); + } + case HungerCategory.Fed: + { + return "HungerLevel_Fed".Translate(); + } default: + { throw new InvalidOperationException(); } + } } } } diff --git a/Assembly-CSharp/RimWorld/HuntJobUtility.cs b/Assembly-CSharp/RimWorld/HuntJobUtility.cs index 56f0078be..d462ec768 100644 --- a/Assembly-CSharp/RimWorld/HuntJobUtility.cs +++ b/Assembly-CSharp/RimWorld/HuntJobUtility.cs @@ -1,4 +1,3 @@ -using System; using Verse; namespace RimWorld @@ -12,12 +11,12 @@ public static bool WasKilledByHunter(Pawn pawn, DamageInfo? dinfo) return false; } Pawn pawn2 = dinfo.Value.Instigator as Pawn; - if (pawn2 == null || pawn2.CurJob == null) + if (pawn2 != null && pawn2.CurJob != null) { - return false; + JobDriver_Hunt jobDriver_Hunt = pawn2.jobs.curDriver as JobDriver_Hunt; + return jobDriver_Hunt != null && jobDriver_Hunt.Victim == pawn; } - JobDriver_Hunt jobDriver_Hunt = pawn2.jobs.curDriver as JobDriver_Hunt; - return jobDriver_Hunt != null && jobDriver_Hunt.Victim == pawn; + return false; } } } diff --git a/Assembly-CSharp/RimWorld/IActiveDropPod.cs b/Assembly-CSharp/RimWorld/IActiveDropPod.cs index 7c22b1621..da81ce93b 100644 --- a/Assembly-CSharp/RimWorld/IActiveDropPod.cs +++ b/Assembly-CSharp/RimWorld/IActiveDropPod.cs @@ -1,4 +1,3 @@ -using System; using Verse; namespace RimWorld diff --git a/Assembly-CSharp/RimWorld/IAssignableBuilding.cs b/Assembly-CSharp/RimWorld/IAssignableBuilding.cs index a3b04e29b..86db91aa4 100644 --- a/Assembly-CSharp/RimWorld/IAssignableBuilding.cs +++ b/Assembly-CSharp/RimWorld/IAssignableBuilding.cs @@ -1,4 +1,3 @@ -using System; using System.Collections.Generic; using Verse; diff --git a/Assembly-CSharp/RimWorld/IBillGiver.cs b/Assembly-CSharp/RimWorld/IBillGiver.cs index 302f3e2a8..3abb22624 100644 --- a/Assembly-CSharp/RimWorld/IBillGiver.cs +++ b/Assembly-CSharp/RimWorld/IBillGiver.cs @@ -1,4 +1,3 @@ -using System; using System.Collections.Generic; using Verse; diff --git a/Assembly-CSharp/RimWorld/IBillGiverWithTickAction.cs b/Assembly-CSharp/RimWorld/IBillGiverWithTickAction.cs index 9e407ac64..e350b3465 100644 --- a/Assembly-CSharp/RimWorld/IBillGiverWithTickAction.cs +++ b/Assembly-CSharp/RimWorld/IBillGiverWithTickAction.cs @@ -1,5 +1,3 @@ -using System; - namespace RimWorld { public interface IBillGiverWithTickAction diff --git a/Assembly-CSharp/RimWorld/ICommunicable.cs b/Assembly-CSharp/RimWorld/ICommunicable.cs index 5c51e9d8c..7e201815f 100644 --- a/Assembly-CSharp/RimWorld/ICommunicable.cs +++ b/Assembly-CSharp/RimWorld/ICommunicable.cs @@ -1,4 +1,3 @@ -using System; using Verse; namespace RimWorld diff --git a/Assembly-CSharp/RimWorld/IConstructible.cs b/Assembly-CSharp/RimWorld/IConstructible.cs index 5555ff8d6..0152b89ab 100644 --- a/Assembly-CSharp/RimWorld/IConstructible.cs +++ b/Assembly-CSharp/RimWorld/IConstructible.cs @@ -1,4 +1,3 @@ -using System; using System.Collections.Generic; using Verse; diff --git a/Assembly-CSharp/RimWorld/IIncidentTarget.cs b/Assembly-CSharp/RimWorld/IIncidentTarget.cs index 011e4919b..caec73843 100644 --- a/Assembly-CSharp/RimWorld/IIncidentTarget.cs +++ b/Assembly-CSharp/RimWorld/IIncidentTarget.cs @@ -1,4 +1,3 @@ -using System; using Verse; namespace RimWorld diff --git a/Assembly-CSharp/RimWorld/IOpenable.cs b/Assembly-CSharp/RimWorld/IOpenable.cs index cdb620afb..d1e01fdea 100644 --- a/Assembly-CSharp/RimWorld/IOpenable.cs +++ b/Assembly-CSharp/RimWorld/IOpenable.cs @@ -1,5 +1,3 @@ -using System; - namespace RimWorld { public interface IOpenable diff --git a/Assembly-CSharp/RimWorld/IPlantToGrowSettable.cs b/Assembly-CSharp/RimWorld/IPlantToGrowSettable.cs index 14197d35b..e18d51c55 100644 --- a/Assembly-CSharp/RimWorld/IPlantToGrowSettable.cs +++ b/Assembly-CSharp/RimWorld/IPlantToGrowSettable.cs @@ -1,4 +1,3 @@ -using System; using Verse; namespace RimWorld diff --git a/Assembly-CSharp/RimWorld/ISlotGroupParent.cs b/Assembly-CSharp/RimWorld/ISlotGroupParent.cs index 11c1ed53e..ca8bdaf16 100644 --- a/Assembly-CSharp/RimWorld/ISlotGroupParent.cs +++ b/Assembly-CSharp/RimWorld/ISlotGroupParent.cs @@ -1,4 +1,3 @@ -using System; using System.Collections.Generic; using Verse; diff --git a/Assembly-CSharp/RimWorld/ISocialThought.cs b/Assembly-CSharp/RimWorld/ISocialThought.cs index 698284ec3..68dd98a02 100644 --- a/Assembly-CSharp/RimWorld/ISocialThought.cs +++ b/Assembly-CSharp/RimWorld/ISocialThought.cs @@ -1,4 +1,3 @@ -using System; using Verse; namespace RimWorld diff --git a/Assembly-CSharp/RimWorld/IStoreSettingsParent.cs b/Assembly-CSharp/RimWorld/IStoreSettingsParent.cs index 8279d2ca2..dddb4e9e4 100644 --- a/Assembly-CSharp/RimWorld/IStoreSettingsParent.cs +++ b/Assembly-CSharp/RimWorld/IStoreSettingsParent.cs @@ -1,5 +1,3 @@ -using System; - namespace RimWorld { public interface IStoreSettingsParent diff --git a/Assembly-CSharp/RimWorld/ITab.cs b/Assembly-CSharp/RimWorld/ITab.cs index df9910d7b..65dc4830e 100644 --- a/Assembly-CSharp/RimWorld/ITab.cs +++ b/Assembly-CSharp/RimWorld/ITab.cs @@ -1,4 +1,3 @@ -using System; using System.Linq; using Verse; diff --git a/Assembly-CSharp/RimWorld/ITab_Art.cs b/Assembly-CSharp/RimWorld/ITab_Art.cs index 45383af9c..1d9b1117e 100644 --- a/Assembly-CSharp/RimWorld/ITab_Art.cs +++ b/Assembly-CSharp/RimWorld/ITab_Art.cs @@ -1,4 +1,3 @@ -using System; using UnityEngine; using Verse; @@ -42,24 +41,27 @@ public override bool IsVisible public ITab_Art() { - this.size = ITab_Art.WinSize; - this.labelKey = "TabArt"; - this.tutorTag = "Art"; + base.size = ITab_Art.WinSize; + base.labelKey = "TabArt"; + base.tutorTag = "Art"; } protected override void FillTab() { - Rect rect = new Rect(0f, 0f, ITab_Art.WinSize.x, ITab_Art.WinSize.y).ContractedBy(10f); - Rect rect2 = rect; + Vector2 winSize = ITab_Art.WinSize; + float x = winSize.x; + Vector2 winSize2 = ITab_Art.WinSize; + Rect rect; + Rect rect2 = rect = new Rect(0f, 0f, x, winSize2.y).ContractedBy(10f); Text.Font = GameFont.Medium; - Widgets.Label(rect2, this.SelectedCompArt.Title); + Widgets.Label(rect, this.SelectedCompArt.Title); if (ITab_Art.cachedImageSource != this.SelectedCompArt || ITab_Art.cachedTaleRef != this.SelectedCompArt.TaleRef) { ITab_Art.cachedImageDescription = this.SelectedCompArt.GenerateImageDescription(); ITab_Art.cachedImageSource = this.SelectedCompArt; ITab_Art.cachedTaleRef = this.SelectedCompArt.TaleRef; } - Rect rect3 = rect; + Rect rect3 = rect2; rect3.yMin += 35f; Text.Font = GameFont.Small; Widgets.Label(rect3, ITab_Art.cachedImageDescription); diff --git a/Assembly-CSharp/RimWorld/ITab_Bills.cs b/Assembly-CSharp/RimWorld/ITab_Bills.cs index b3b4c4ef9..d4672e06c 100644 --- a/Assembly-CSharp/RimWorld/ITab_Bills.cs +++ b/Assembly-CSharp/RimWorld/ITab_Bills.cs @@ -26,16 +26,19 @@ protected Building_WorkTable SelTable public ITab_Bills() { - this.size = ITab_Bills.WinSize; - this.labelKey = "TabBills"; - this.tutorTag = "Bills"; + base.size = ITab_Bills.WinSize; + base.labelKey = "TabBills"; + base.tutorTag = "Bills"; } protected override void FillTab() { PlayerKnowledgeDatabase.KnowledgeDemonstrated(ConceptDefOf.BillsTab, KnowledgeAmount.FrameDisplayed); - Rect rect = new Rect(0f, 0f, ITab_Bills.WinSize.x, ITab_Bills.WinSize.y).ContractedBy(10f); - Func> recipeOptionsMaker = delegate + Vector2 winSize = ITab_Bills.WinSize; + float x = winSize.x; + Vector2 winSize2 = ITab_Bills.WinSize; + Rect rect = new Rect(0f, 0f, x, winSize2.y).ContractedBy(10f); + Func> recipeOptionsMaker = (Func>)delegate() { List list = new List(); for (int i = 0; i < this.SelTable.def.AllRecipes.Count; i++) @@ -43,9 +46,9 @@ protected override void FillTab() if (this.SelTable.def.AllRecipes[i].AvailableNow) { RecipeDef recipe = this.SelTable.def.AllRecipes[i]; - list.Add(new FloatMenuOption(recipe.LabelCap, delegate + list.Add(new FloatMenuOption(recipe.LabelCap, (Action)delegate() { - if (!this.SelTable.Map.mapPawns.FreeColonists.Any((Pawn col) => recipe.PawnSatisfiesSkillRequirements(col))) + if (!this.SelTable.Map.mapPawns.FreeColonists.Any((Func)((Pawn col) => recipe.PawnSatisfiesSkillRequirements(col)))) { Bill.CreateNoPawnsWithSkillDialog(recipe); } @@ -62,7 +65,7 @@ protected override void FillTab() }, MenuOptionPriority.Default, null, null, 0f, null, null)); } } - if (!list.Any()) + if (!list.Any()) { list.Add(new FloatMenuOption("NoneBrackets".Translate(), null, MenuOptionPriority.Default, null, null, 0f, null, null)); } diff --git a/Assembly-CSharp/RimWorld/ITab_Pawn_Character.cs b/Assembly-CSharp/RimWorld/ITab_Pawn_Character.cs index 55b419f88..22e79a4f1 100644 --- a/Assembly-CSharp/RimWorld/ITab_Pawn_Character.cs +++ b/Assembly-CSharp/RimWorld/ITab_Pawn_Character.cs @@ -1,4 +1,3 @@ -using System; using UnityEngine; using Verse; @@ -42,9 +41,9 @@ public override bool IsVisible public ITab_Pawn_Character() { - this.size = CharacterCardUtility.PawnCardSize + new Vector2(17f, 17f) * 2f; - this.labelKey = "TabCharacter"; - this.tutorTag = "Character"; + base.size = CharacterCardUtility.PawnCardSize + new Vector2(17f, 17f) * 2f; + base.labelKey = "TabCharacter"; + base.tutorTag = "Character"; } protected override void FillTab() diff --git a/Assembly-CSharp/RimWorld/ITab_Pawn_Gear.cs b/Assembly-CSharp/RimWorld/ITab_Pawn_Gear.cs index f50eaae7a..5150e3d3c 100644 --- a/Assembly-CSharp/RimWorld/ITab_Pawn_Gear.cs +++ b/Assembly-CSharp/RimWorld/ITab_Pawn_Gear.cs @@ -66,22 +66,22 @@ private Pawn SelPawnForGear public ITab_Pawn_Gear() { - this.size = new Vector2(460f, 450f); - this.labelKey = "TabGear"; - this.tutorTag = "Gear"; + base.size = new Vector2(460f, 450f); + base.labelKey = "TabGear"; + base.tutorTag = "Gear"; } protected override void FillTab() { Text.Font = GameFont.Small; - Rect rect = new Rect(0f, 20f, this.size.x, this.size.y - 20f); + Rect rect = new Rect(0f, 20f, base.size.x, (float)(base.size.y - 20.0)); Rect rect2 = rect.ContractedBy(10f); Rect position = new Rect(rect2.x, rect2.y, rect2.width, rect2.height); GUI.BeginGroup(position); Text.Font = GameFont.Small; GUI.color = Color.white; Rect outRect = new Rect(0f, 0f, position.width, position.height); - Rect viewRect = new Rect(0f, 0f, position.width - 16f, this.scrollViewHeight); + Rect viewRect = new Rect(0f, 0f, (float)(position.width - 16.0), this.scrollViewHeight); Widgets.BeginScrollView(outRect, ref this.scrollPosition, viewRect, true); float num = 0f; this.TryDrawMassInfo(ref num, viewRect.width); @@ -97,19 +97,28 @@ protected override void FillTab() if (this.SelPawnForGear.equipment != null) { Widgets.ListSeparator(ref num, viewRect.width, "Equipment".Translate()); - foreach (ThingWithComps current in this.SelPawnForGear.equipment.AllEquipmentListForReading) + List.Enumerator enumerator = this.SelPawnForGear.equipment.AllEquipmentListForReading.GetEnumerator(); + try { - this.DrawThingRow(ref num, viewRect.width, current, false); + while (enumerator.MoveNext()) + { + ThingWithComps current = enumerator.Current; + this.DrawThingRow(ref num, viewRect.width, current, false); + } + } + finally + { + ((IDisposable)(object)enumerator).Dispose(); } } if (this.SelPawnForGear.apparel != null) { Widgets.ListSeparator(ref num, viewRect.width, "Apparel".Translate()); - foreach (Apparel current2 in from ap in this.SelPawnForGear.apparel.WornApparel + foreach (Apparel item in from ap in this.SelPawnForGear.apparel.WornApparel orderby ap.def.apparel.bodyPartGroups[0].listOrder descending select ap) { - this.DrawThingRow(ref num, viewRect.width, current2, false); + this.DrawThingRow(ref num, viewRect.width, item, false); } } if (this.SelPawnForGear.inventory != null) @@ -124,7 +133,7 @@ orderby ap.def.apparel.bodyPartGroups[0].listOrder descending } if (Event.current.type == EventType.Layout) { - this.scrollViewHeight = num + 30f; + this.scrollViewHeight = (float)(num + 30.0); } Widgets.EndScrollView(); GUI.EndGroup(); @@ -135,11 +144,11 @@ orderby ap.def.apparel.bodyPartGroups[0].listOrder descending private void DrawThingRow(ref float y, float width, Thing thing, bool showDropButtonIfPrisoner = false) { Rect rect = new Rect(0f, y, width, 28f); - Widgets.InfoCardButton(rect.width - 24f, y, thing); + Widgets.InfoCardButton((float)(rect.width - 24.0), y, thing); rect.width -= 24f; if (this.CanControl || (this.SelPawnForGear.Faction == Faction.OfPlayer && this.SelPawnForGear.RaceProps.packAnimal) || (showDropButtonIfPrisoner && this.SelPawnForGear.IsPrisonerOfColony)) { - Rect rect2 = new Rect(rect.width - 24f, y, 24f, 24f); + Rect rect2 = new Rect((float)(rect.width - 24.0), y, 24f, 24f); TooltipHandler.TipRegion(rect2, "DropThing".Translate()); if (Widgets.ButtonImage(rect2, TexButton.Drop)) { @@ -152,11 +161,8 @@ private void DrawThingRow(ref float y, float width, Thing thing, bool showDropBu { if (thing.def.IsNutritionGivingIngestible && thing.IngestibleNow && base.SelPawn.RaceProps.CanEverEat(thing)) { - Rect rect3 = new Rect(rect.width - 24f, y, 24f, 24f); - TooltipHandler.TipRegion(rect3, "ConsumeThing".Translate(new object[] - { - thing.LabelNoCount - })); + Rect rect3 = new Rect((float)(rect.width - 24.0), y, 24f, 24f); + TooltipHandler.TipRegion(rect3, "ConsumeThing".Translate(thing.LabelNoCount)); if (Widgets.ButtonImage(rect3, TexButton.Ingest)) { SoundDefOf.TickHigh.PlayOneShotOnCamera(null); @@ -166,7 +172,7 @@ private void DrawThingRow(ref float y, float width, Thing thing, bool showDropBu rect.width -= 24f; } Rect rect4 = rect; - rect4.xMin = rect4.xMax - 60f; + rect4.xMin = (float)(rect4.xMax - 60.0); CaravanPeopleAndItemsTabUtility.TryDrawMass(thing, rect4); rect.width -= 60f; if (Mouse.IsOver(rect)) @@ -174,13 +180,13 @@ private void DrawThingRow(ref float y, float width, Thing thing, bool showDropBu GUI.color = ITab_Pawn_Gear.HighlightColor; GUI.DrawTexture(rect, TexUI.HighlightTex); } - if (thing.def.DrawMatSingle != null && thing.def.DrawMatSingle.mainTexture != null) + if ((UnityEngine.Object)thing.def.DrawMatSingle != (UnityEngine.Object)null && (UnityEngine.Object)thing.def.DrawMatSingle.mainTexture != (UnityEngine.Object)null) { Widgets.ThingIcon(new Rect(4f, y, 28f, 28f), thing, 1f); } Text.Anchor = TextAnchor.MiddleLeft; GUI.color = ITab_Pawn_Gear.ThingLabelColor; - Rect rect5 = new Rect(36f, y, rect.width - 36f, rect.height); + Rect rect5 = new Rect(36f, y, (float)(rect.width - 36.0), rect.height); string text = thing.LabelCap; Apparel apparel = thing as Apparel; if (apparel != null && this.SelPawnForGear.outfits != null && this.SelPawnForGear.outfits.forcedHandler.IsForced(apparel)) @@ -194,14 +200,7 @@ private void DrawThingRow(ref float y, float width, Thing thing, bool showDropBu if (thing.def.useHitPoints) { string text3 = text2; - text2 = string.Concat(new object[] - { - text3, - "\n", - thing.HitPoints, - " / ", - thing.MaxHitPoints - }); + text2 = text3 + "\n" + thing.HitPoints + " / " + thing.MaxHitPoints; } TooltipHandler.TipRegion(rect, text2); y += 28f; @@ -209,67 +208,53 @@ private void DrawThingRow(ref float y, float width, Thing thing, bool showDropBu private void TryDrawAverageArmor(ref float curY, float width, StatDef stat, string label, ref bool separatorDrawn) { - if (this.SelPawnForGear.RaceProps.body != BodyDefOf.Human) - { - return; - } - float num = 0f; - List wornApparel = this.SelPawnForGear.apparel.WornApparel; - for (int i = 0; i < wornApparel.Count; i++) - { - num += Mathf.Clamp01(wornApparel[i].GetStatValue(stat, true)) * wornApparel[i].def.apparel.HumanBodyCoverage; - } - num = Mathf.Clamp01(num); - if (num > 0.005f) + if (this.SelPawnForGear.RaceProps.body == BodyDefOf.Human) { - if (!separatorDrawn) + float num = 0f; + List wornApparel = this.SelPawnForGear.apparel.WornApparel; + for (int i = 0; i < wornApparel.Count; i++) { - separatorDrawn = true; - Widgets.ListSeparator(ref curY, width, "AverageArmor".Translate()); + num += Mathf.Clamp01(wornApparel[i].GetStatValue(stat, true)) * wornApparel[i].def.apparel.HumanBodyCoverage; + } + num = Mathf.Clamp01(num); + if (num > 0.004999999888241291) + { + if (!separatorDrawn) + { + separatorDrawn = true; + Widgets.ListSeparator(ref curY, width, "AverageArmor".Translate()); + } + Rect rect = new Rect(0f, curY, width, 100f); + Widgets.Label(rect, label); + rect.xMin += 100f; + Widgets.Label(rect, num.ToStringPercent()); + curY += 22f; } - Rect rect = new Rect(0f, curY, width, 100f); - Widgets.Label(rect, label); - rect.xMin += 100f; - Widgets.Label(rect, num.ToStringPercent()); - curY += 22f; } } private void TryDrawMassInfo(ref float curY, float width) { - if (this.SelPawnForGear.Dead) + if (!this.SelPawnForGear.Dead) { - return; + Rect rect = new Rect(0f, curY, width, 22f); + float num = MassUtility.GearAndInventoryMass(this.SelPawnForGear); + float num2 = MassUtility.Capacity(this.SelPawnForGear); + Widgets.Label(rect, "MassCarried".Translate(num.ToString("0.##"), num2.ToString("0.##"))); + curY += 22f; } - Rect rect = new Rect(0f, curY, width, 22f); - float num = MassUtility.GearAndInventoryMass(this.SelPawnForGear); - float num2 = MassUtility.Capacity(this.SelPawnForGear); - Widgets.Label(rect, "MassCarried".Translate(new object[] - { - num.ToString("0.##"), - num2.ToString("0.##") - })); - curY += 22f; } private void TryDrawComfyTemperatureRange(ref float curY, float width) { - if (this.SelPawnForGear.Dead) + if (!this.SelPawnForGear.Dead) { - return; + Rect rect = new Rect(0f, curY, width, 22f); + float statValue = this.SelPawnForGear.GetStatValue(StatDefOf.ComfyTemperatureMin, true); + float statValue2 = this.SelPawnForGear.GetStatValue(StatDefOf.ComfyTemperatureMax, true); + Widgets.Label(rect, "ComfyTemperatureRange".Translate() + ": " + statValue.ToStringTemperature("F0") + " ~ " + statValue2.ToStringTemperature("F0")); + curY += 22f; } - Rect rect = new Rect(0f, curY, width, 22f); - float statValue = this.SelPawnForGear.GetStatValue(StatDefOf.ComfyTemperatureMin, true); - float statValue2 = this.SelPawnForGear.GetStatValue(StatDefOf.ComfyTemperatureMax, true); - Widgets.Label(rect, string.Concat(new string[] - { - "ComfyTemperatureRange".Translate(), - ": ", - statValue.ToStringTemperature("F0"), - " ~ ", - statValue2.ToStringTemperature("F0") - })); - curY += 22f; } private void InterfaceDrop(Thing t) @@ -278,16 +263,16 @@ private void InterfaceDrop(Thing t) Apparel apparel = t as Apparel; if (apparel != null && this.SelPawnForGear.apparel != null && this.SelPawnForGear.apparel.WornApparel.Contains(apparel)) { - this.SelPawnForGear.jobs.TryTakeOrderedJob(new Job(JobDefOf.RemoveApparel, apparel), JobTag.Misc); + this.SelPawnForGear.jobs.TryTakeOrderedJob(new Job(JobDefOf.RemoveApparel, (Thing)apparel), JobTag.Misc); } else if (thingWithComps != null && this.SelPawnForGear.equipment != null && this.SelPawnForGear.equipment.AllEquipmentListForReading.Contains(thingWithComps)) { - this.SelPawnForGear.jobs.TryTakeOrderedJob(new Job(JobDefOf.DropEquipment, thingWithComps), JobTag.Misc); + this.SelPawnForGear.jobs.TryTakeOrderedJob(new Job(JobDefOf.DropEquipment, (Thing)thingWithComps), JobTag.Misc); } else if (!t.def.destroyOnDrop) { - Thing thing; - this.SelPawnForGear.inventory.innerContainer.TryDrop(t, this.SelPawnForGear.Position, this.SelPawnForGear.Map, ThingPlaceMode.Near, out thing, null); + Thing thing = default(Thing); + this.SelPawnForGear.inventory.innerContainer.TryDrop(t, this.SelPawnForGear.Position, this.SelPawnForGear.Map, ThingPlaceMode.Near, out thing, (Action)null); } } diff --git a/Assembly-CSharp/RimWorld/ITab_Pawn_Guest.cs b/Assembly-CSharp/RimWorld/ITab_Pawn_Guest.cs index 5e471bc7b..631384836 100644 --- a/Assembly-CSharp/RimWorld/ITab_Pawn_Guest.cs +++ b/Assembly-CSharp/RimWorld/ITab_Pawn_Guest.cs @@ -1,5 +1,3 @@ -using System; - namespace RimWorld { public class ITab_Pawn_Guest : ITab_Pawn_Visitor @@ -14,8 +12,8 @@ public override bool IsVisible public ITab_Pawn_Guest() { - this.labelKey = "TabGuest"; - this.tutorTag = "Guest"; + base.labelKey = "TabGuest"; + base.tutorTag = "Guest"; } } } diff --git a/Assembly-CSharp/RimWorld/ITab_Pawn_Health.cs b/Assembly-CSharp/RimWorld/ITab_Pawn_Health.cs index f31837141..b72b2c355 100644 --- a/Assembly-CSharp/RimWorld/ITab_Pawn_Health.cs +++ b/Assembly-CSharp/RimWorld/ITab_Pawn_Health.cs @@ -29,9 +29,9 @@ private Pawn PawnForHealth public ITab_Pawn_Health() { - this.size = new Vector2(630f, 430f); - this.labelKey = "TabHealth"; - this.tutorTag = "Health"; + base.size = new Vector2(630f, 430f); + base.labelKey = "TabHealth"; + base.tutorTag = "Health"; } protected override void FillTab() @@ -40,12 +40,14 @@ protected override void FillTab() if (pawnForHealth == null) { Log.Error("Health tab found no selected pawn to display."); - return; } - Corpse corpse = base.SelThing as Corpse; - bool showBloodLoss = corpse == null || corpse.Age < 60000; - Rect outRect = new Rect(0f, 20f, this.size.x, this.size.y - 20f); - HealthCardUtility.DrawPawnHealthCard(outRect, pawnForHealth, this.ShouldAllowOperations(), showBloodLoss, base.SelThing); + else + { + Corpse corpse = base.SelThing as Corpse; + bool showBloodLoss = corpse == null || corpse.Age < 60000; + Rect outRect = new Rect(0f, 20f, base.size.x, (float)(base.size.y - 20.0)); + HealthCardUtility.DrawPawnHealthCard(outRect, pawnForHealth, this.ShouldAllowOperations(), showBloodLoss, base.SelThing); + } } private bool ShouldAllowOperations() @@ -55,7 +57,27 @@ private bool ShouldAllowOperations() { return false; } - return base.SelThing.def.AllRecipes.Any((RecipeDef x) => x.AvailableNow) && (pawnForHealth.Faction == Faction.OfPlayer || (pawnForHealth.IsPrisonerOfColony || (pawnForHealth.HostFaction == Faction.OfPlayer && !pawnForHealth.health.capacities.CapableOf(PawnCapacityDefOf.Moving))) || ((!pawnForHealth.RaceProps.IsFlesh || pawnForHealth.Faction == null || !pawnForHealth.Faction.HostileTo(Faction.OfPlayer)) && (!pawnForHealth.RaceProps.Humanlike && pawnForHealth.Downed))); + if (!base.SelThing.def.AllRecipes.Any((Predicate)((RecipeDef x) => x.AvailableNow))) + { + return false; + } + if (pawnForHealth.Faction == Faction.OfPlayer) + { + return true; + } + if (!pawnForHealth.IsPrisonerOfColony && (pawnForHealth.HostFaction != Faction.OfPlayer || pawnForHealth.health.capacities.CapableOf(PawnCapacityDefOf.Moving))) + { + if (pawnForHealth.RaceProps.IsFlesh && pawnForHealth.Faction != null && pawnForHealth.Faction.HostileTo(Faction.OfPlayer)) + { + return false; + } + if (!pawnForHealth.RaceProps.Humanlike && pawnForHealth.Downed) + { + return true; + } + return false; + } + return true; } } } diff --git a/Assembly-CSharp/RimWorld/ITab_Pawn_Needs.cs b/Assembly-CSharp/RimWorld/ITab_Pawn_Needs.cs index 97172f4bc..a06329cb5 100644 --- a/Assembly-CSharp/RimWorld/ITab_Pawn_Needs.cs +++ b/Assembly-CSharp/RimWorld/ITab_Pawn_Needs.cs @@ -1,4 +1,3 @@ -using System; using UnityEngine; namespace RimWorld @@ -17,8 +16,8 @@ public override bool IsVisible public ITab_Pawn_Needs() { - this.labelKey = "TabNeeds"; - this.tutorTag = "Needs"; + base.labelKey = "TabNeeds"; + base.tutorTag = "Needs"; } public override void OnOpen() @@ -28,12 +27,12 @@ public override void OnOpen() protected override void FillTab() { - NeedsCardUtility.DoNeedsMoodAndThoughts(new Rect(0f, 0f, this.size.x, this.size.y), base.SelPawn, ref this.thoughtScrollPosition); + NeedsCardUtility.DoNeedsMoodAndThoughts(new Rect(0f, 0f, base.size.x, base.size.y), base.SelPawn, ref this.thoughtScrollPosition); } protected override void UpdateSize() { - this.size = NeedsCardUtility.GetSize(base.SelPawn); + base.size = NeedsCardUtility.GetSize(base.SelPawn); } } } diff --git a/Assembly-CSharp/RimWorld/ITab_Pawn_Prisoner.cs b/Assembly-CSharp/RimWorld/ITab_Pawn_Prisoner.cs index fd93375e4..0667e1bdd 100644 --- a/Assembly-CSharp/RimWorld/ITab_Pawn_Prisoner.cs +++ b/Assembly-CSharp/RimWorld/ITab_Pawn_Prisoner.cs @@ -1,5 +1,3 @@ -using System; - namespace RimWorld { public class ITab_Pawn_Prisoner : ITab_Pawn_Visitor @@ -14,8 +12,8 @@ public override bool IsVisible public ITab_Pawn_Prisoner() { - this.labelKey = "TabPrisoner"; - this.tutorTag = "Prisoner"; + base.labelKey = "TabPrisoner"; + base.tutorTag = "Prisoner"; } } } diff --git a/Assembly-CSharp/RimWorld/ITab_Pawn_Social.cs b/Assembly-CSharp/RimWorld/ITab_Pawn_Social.cs index f2aec53de..fa09dfc66 100644 --- a/Assembly-CSharp/RimWorld/ITab_Pawn_Social.cs +++ b/Assembly-CSharp/RimWorld/ITab_Pawn_Social.cs @@ -35,14 +35,14 @@ private Pawn SelPawnForSocialInfo public ITab_Pawn_Social() { - this.size = new Vector2(540f, 510f); - this.labelKey = "TabSocial"; - this.tutorTag = "Social"; + base.size = new Vector2(540f, 510f); + base.labelKey = "TabSocial"; + base.tutorTag = "Social"; } protected override void FillTab() { - SocialCardUtility.DrawSocialCard(new Rect(0f, 0f, this.size.x, this.size.y), this.SelPawnForSocialInfo); + SocialCardUtility.DrawSocialCard(new Rect(0f, 0f, base.size.x, base.size.y), this.SelPawnForSocialInfo); } } } diff --git a/Assembly-CSharp/RimWorld/ITab_Pawn_Training.cs b/Assembly-CSharp/RimWorld/ITab_Pawn_Training.cs index 64f40e4a1..741a01b33 100644 --- a/Assembly-CSharp/RimWorld/ITab_Pawn_Training.cs +++ b/Assembly-CSharp/RimWorld/ITab_Pawn_Training.cs @@ -1,4 +1,3 @@ -using System; using UnityEngine; using Verse; @@ -16,14 +15,14 @@ public override bool IsVisible public ITab_Pawn_Training() { - this.size = new Vector2(300f, 450f); - this.labelKey = "TabTraining"; - this.tutorTag = "Training"; + base.size = new Vector2(300f, 450f); + base.labelKey = "TabTraining"; + base.tutorTag = "Training"; } protected override void FillTab() { - Rect rect = new Rect(0f, 0f, this.size.x, this.size.y).ContractedBy(17f); + Rect rect = new Rect(0f, 0f, base.size.x, base.size.y).ContractedBy(17f); rect.yMin += 10f; TrainingCardUtility.DrawTrainingCard(rect, base.SelPawn); } diff --git a/Assembly-CSharp/RimWorld/ITab_Pawn_Visitor.cs b/Assembly-CSharp/RimWorld/ITab_Pawn_Visitor.cs index 3feb1c239..4a55fdc4b 100644 --- a/Assembly-CSharp/RimWorld/ITab_Pawn_Visitor.cs +++ b/Assembly-CSharp/RimWorld/ITab_Pawn_Visitor.cs @@ -13,14 +13,14 @@ public abstract class ITab_Pawn_Visitor : ITab public ITab_Pawn_Visitor() { - this.size = new Vector2(280f, 450f); + base.size = new Vector2(280f, 450f); } protected override void FillTab() { PlayerKnowledgeDatabase.KnowledgeDemonstrated(ConceptDefOf.PrisonerTab, KnowledgeAmount.FrameDisplayed); Text.Font = GameFont.Small; - Rect rect = new Rect(0f, 0f, this.size.x, this.size.y); + Rect rect = new Rect(0f, 0f, base.size.x, base.size.y); Rect rect2 = rect.ContractedBy(10f); rect2.yMin += 24f; bool isPrisonerOfColony = base.SelPawn.IsPrisonerOfColony; @@ -41,10 +41,7 @@ protected override void FillTab() listing_Standard.Label("RecruitmentDifficulty".Translate() + ": " + base.SelPawn.RecruitDifficulty(Faction.OfPlayer, false).ToStringPercent(), -1f); if (base.SelPawn.guilt.IsGuilty) { - listing_Standard.Label("ConsideredGuilty".Translate(new object[] - { - base.SelPawn.guilt.TicksUntilInnocent.ToStringTicksToPeriod(true, false, true) - }), -1f); + listing_Standard.Label("ConsideredGuilty".Translate(base.SelPawn.guilt.TicksUntilInnocent.ToStringTicksToPeriod(true, false, true)), -1f); } if (Prefs.DevMode) { @@ -55,16 +52,16 @@ protected override void FillTab() Rect position = rect5.ContractedBy(10f); GUI.BeginGroup(position); Rect rect6 = new Rect(0f, 0f, position.width, 30f); - foreach (PrisonerInteractionModeDef current in from pim in DefDatabase.AllDefs + foreach (PrisonerInteractionModeDef item in from pim in DefDatabase.AllDefs orderby pim.listOrder select pim) { - if (Widgets.RadioButtonLabeled(rect6, current.GetLabel(), base.SelPawn.guest.interactionMode == current)) + if (Widgets.RadioButtonLabeled(rect6, item.GetLabel(), base.SelPawn.guest.interactionMode == item)) { - base.SelPawn.guest.interactionMode = current; - if (current == PrisonerInteractionModeDefOf.Execution && base.SelPawn.MapHeld != null && !this.ColonyHasAnyWardenCapableOfViolence(base.SelPawn.MapHeld)) + base.SelPawn.guest.interactionMode = item; + if (item == PrisonerInteractionModeDefOf.Execution && base.SelPawn.MapHeld != null && !this.ColonyHasAnyWardenCapableOfViolence(base.SelPawn.MapHeld)) { - Messages.Message("MessageCantDoExecutionBecauseNoWardenCapableOfViolence".Translate(), base.SelPawn, MessageSound.SeriousAlert); + Messages.Message("MessageCantDoExecutionBecauseNoWardenCapableOfViolence".Translate(), (Thing)base.SelPawn, MessageSound.SeriousAlert); } } rect6.y += 28f; @@ -76,9 +73,9 @@ orderby pim.listOrder private bool ColonyHasAnyWardenCapableOfViolence(Map map) { - foreach (Pawn current in map.mapPawns.FreeColonistsSpawned) + foreach (Pawn item in map.mapPawns.FreeColonistsSpawned) { - if (current.workSettings.WorkIsActive(WorkTypeDefOf.Warden) && (current.story == null || !current.story.WorkTagIsDisabled(WorkTags.Violent))) + if (item.workSettings.WorkIsActive(WorkTypeDefOf.Warden) && (item.story == null || !item.story.WorkTagIsDisabled(WorkTags.Violent))) { return true; } diff --git a/Assembly-CSharp/RimWorld/ITab_Storage.cs b/Assembly-CSharp/RimWorld/ITab_Storage.cs index 35cfbbb7f..4aa43fb31 100644 --- a/Assembly-CSharp/RimWorld/ITab_Storage.cs +++ b/Assembly-CSharp/RimWorld/ITab_Storage.cs @@ -1,5 +1,4 @@ using System; -using System.Collections; using System.Collections.Generic; using UnityEngine; using Verse; @@ -32,35 +31,34 @@ public override bool IsVisible public ITab_Storage() { - this.size = ITab_Storage.WinSize; - this.labelKey = "TabStorage"; - this.tutorTag = "Storage"; + base.size = ITab_Storage.WinSize; + base.labelKey = "TabStorage"; + base.tutorTag = "Storage"; } protected override void FillTab() { IStoreSettingsParent selStoreSettingsParent = this.SelStoreSettingsParent; StorageSettings settings = selStoreSettingsParent.GetStoreSettings(); - Rect position = new Rect(0f, 0f, ITab_Storage.WinSize.x, ITab_Storage.WinSize.y).ContractedBy(10f); + Vector2 winSize = ITab_Storage.WinSize; + float x = winSize.x; + Vector2 winSize2 = ITab_Storage.WinSize; + Rect position = new Rect(0f, 0f, x, winSize2.y).ContractedBy(10f); GUI.BeginGroup(position); Text.Font = GameFont.Small; Rect rect = new Rect(0f, 0f, 160f, 29f); if (Widgets.ButtonText(rect, "Priority".Translate() + ": " + settings.Priority.Label(), true, false, true)) { List list = new List(); - using (IEnumerator enumerator = Enum.GetValues(typeof(StoragePriority)).GetEnumerator()) + foreach (byte value in Enum.GetValues(typeof(StoragePriority))) { - while (enumerator.MoveNext()) + if (value != 0) { - StoragePriority storagePriority = (StoragePriority)((byte)enumerator.Current); - if (storagePriority != StoragePriority.Unstored) + StoragePriority localPr = (StoragePriority)value; + list.Add(new FloatMenuOption(localPr.Label().CapitalizeFirst(), (Action)delegate { - StoragePriority localPr = storagePriority; - list.Add(new FloatMenuOption(localPr.Label().CapitalizeFirst(), delegate - { - settings.Priority = localPr; - }, MenuOptionPriority.Default, null, null, 0f, null, null)); - } + settings.Priority = localPr; + }, MenuOptionPriority.Default, null, null, 0f, null, null)); } } Find.WindowStack.Add(new FloatMenu(list)); @@ -71,8 +69,8 @@ protected override void FillTab() { parentFilter = selStoreSettingsParent.GetParentStoreSettings().filter; } - Rect rect2 = new Rect(0f, 35f, position.width, position.height - 35f); - ThingFilterUI.DoThingFilterConfigWindow(rect2, ref this.scrollPosition, settings.filter, parentFilter, 8, null, null, null); + Rect rect2 = new Rect(0f, 35f, position.width, (float)(position.height - 35.0)); + ThingFilterUI.DoThingFilterConfigWindow(rect2, ref this.scrollPosition, settings.filter, parentFilter, 8, (IEnumerable)null, (IEnumerable)null, (List)null); PlayerKnowledgeDatabase.KnowledgeDemonstrated(ConceptDefOf.StorageTab, KnowledgeAmount.FrameDisplayed); GUI.EndGroup(); } diff --git a/Assembly-CSharp/RimWorld/IThoughtGiver.cs b/Assembly-CSharp/RimWorld/IThoughtGiver.cs index 751abff91..edf731185 100644 --- a/Assembly-CSharp/RimWorld/IThoughtGiver.cs +++ b/Assembly-CSharp/RimWorld/IThoughtGiver.cs @@ -1,5 +1,3 @@ -using System; - namespace RimWorld { public interface IThoughtGiver diff --git a/Assembly-CSharp/RimWorld/ITrader.cs b/Assembly-CSharp/RimWorld/ITrader.cs index afe5bb8d0..0b25a0fe2 100644 --- a/Assembly-CSharp/RimWorld/ITrader.cs +++ b/Assembly-CSharp/RimWorld/ITrader.cs @@ -1,4 +1,3 @@ -using System; using System.Collections.Generic; using Verse; diff --git a/Assembly-CSharp/RimWorld/IgnorePawnsInventoryMode.cs b/Assembly-CSharp/RimWorld/IgnorePawnsInventoryMode.cs index b35eece80..83b52580f 100644 --- a/Assembly-CSharp/RimWorld/IgnorePawnsInventoryMode.cs +++ b/Assembly-CSharp/RimWorld/IgnorePawnsInventoryMode.cs @@ -1,11 +1,9 @@ -using System; - namespace RimWorld { public enum IgnorePawnsInventoryMode { - Ignore, - IgnoreIfAssignedToUnload, - DontIgnore + Ignore = 0, + IgnoreIfAssignedToUnload = 1, + DontIgnore = 2 } } diff --git a/Assembly-CSharp/RimWorld/ImpactSoundUtility.cs b/Assembly-CSharp/RimWorld/ImpactSoundUtility.cs index 03f1b0bcd..ca9884b5c 100644 --- a/Assembly-CSharp/RimWorld/ImpactSoundUtility.cs +++ b/Assembly-CSharp/RimWorld/ImpactSoundUtility.cs @@ -1,4 +1,3 @@ -using System; using Verse; using Verse.Sound; @@ -8,29 +7,23 @@ public static class ImpactSoundUtility { public static void PlayImpactSound(Thing hitThing, ImpactSoundTypeDef ist, Map map) { - if (ist == null) + if (ist != null) { - return; + if (map == null) + { + Log.Warning("Can't play impact sound because map is null."); + } + else + { + SoundDef soundDef = null; + soundDef = ((hitThing.Stuff == null) ? hitThing.def.soundImpactDefault : hitThing.Stuff.stuffProps.soundImpactStuff); + if (soundDef.NullOrUndefined()) + { + soundDef = SoundDefOf.BulletImpactGround; + } + soundDef.PlayOneShot(new TargetInfo(hitThing.PositionHeld, map, false)); + } } - if (map == null) - { - Log.Warning("Can't play impact sound because map is null."); - return; - } - SoundDef soundDef; - if (hitThing.Stuff != null) - { - soundDef = hitThing.Stuff.stuffProps.soundImpactStuff; - } - else - { - soundDef = hitThing.def.soundImpactDefault; - } - if (soundDef.NullOrUndefined()) - { - soundDef = SoundDefOf.BulletImpactGround; - } - soundDef.PlayOneShot(new TargetInfo(hitThing.PositionHeld, map, false)); } } } diff --git a/Assembly-CSharp/RimWorld/IncidentCategory.cs b/Assembly-CSharp/RimWorld/IncidentCategory.cs index b7e73e5ca..0c9b37b9d 100644 --- a/Assembly-CSharp/RimWorld/IncidentCategory.cs +++ b/Assembly-CSharp/RimWorld/IncidentCategory.cs @@ -1,19 +1,17 @@ -using System; - namespace RimWorld { public enum IncidentCategory : byte { - Undefined, - Misc, - ThreatSmall, - ThreatBig, - AllyArrival, - OrbitalVisitor, - ShipChunkDrop, - JourneyOffer, - Disease, - CaravanTarget, - AllyAssistance + Undefined = 0, + Misc = 1, + ThreatSmall = 2, + ThreatBig = 3, + AllyArrival = 4, + OrbitalVisitor = 5, + ShipChunkDrop = 6, + JourneyOffer = 7, + Disease = 8, + CaravanTarget = 9, + AllyAssistance = 10 } } diff --git a/Assembly-CSharp/RimWorld/IncidentCategoryEntry.cs b/Assembly-CSharp/RimWorld/IncidentCategoryEntry.cs index 577339b7d..f5ec8a166 100644 --- a/Assembly-CSharp/RimWorld/IncidentCategoryEntry.cs +++ b/Assembly-CSharp/RimWorld/IncidentCategoryEntry.cs @@ -1,4 +1,3 @@ -using System; using System.Xml; using Verse; @@ -12,7 +11,7 @@ public class IncidentCategoryEntry public void LoadDataFromXmlCustom(XmlNode xmlRoot) { - this.category = (IncidentCategory)((byte)ParseHelper.FromString(xmlRoot.Name, typeof(IncidentCategory))); + this.category = (IncidentCategory)(byte)ParseHelper.FromString(xmlRoot.Name, typeof(IncidentCategory)); this.weight = (float)ParseHelper.FromString(xmlRoot.FirstChild.Value, typeof(float)); } } diff --git a/Assembly-CSharp/RimWorld/IncidentDef.cs b/Assembly-CSharp/RimWorld/IncidentDef.cs index f3fd6bfe9..9625ffacf 100644 --- a/Assembly-CSharp/RimWorld/IncidentDef.cs +++ b/Assembly-CSharp/RimWorld/IncidentDef.cs @@ -1,6 +1,5 @@ using System; using System.Collections.Generic; -using System.Diagnostics; using Verse; namespace RimWorld @@ -142,19 +141,33 @@ private bool ShouldDoRefireCheckWith(IncidentDef other) return false; } - [DebuggerHidden] public override IEnumerable ConfigErrors() { - IncidentDef.c__Iterator8F c__Iterator8F = new IncidentDef.c__Iterator8F(); - c__Iterator8F.<>f__this = this; - IncidentDef.c__Iterator8F expr_0E = c__Iterator8F; - expr_0E.$PC = -2; - return expr_0E; + foreach (string item in base.ConfigErrors()) + { + yield return item; + } + if (this.category == IncidentCategory.Undefined) + { + yield return "category is undefined."; + } + if (this.targetType == IncidentTargetType.None) + { + yield return "no target type"; + } + if (this.TargetTypeAllowed(IncidentTargetType.World) && this.targetType != IncidentTargetType.World) + { + yield return "allows world target type along with other targets. World targeting incidents should only target the world."; + } + if (this.TargetTypeAllowed(IncidentTargetType.World) && this.allowedBiomes != null) + { + yield return "world-targeting incident has a biome restriction list"; + } } public bool TargetTypeAllowed(IncidentTargetType target) { - return (byte)(this.targetType & target) != 0; + return (this.targetType & target) != IncidentTargetType.None; } public bool TargetAllowed(IIncidentTarget target) diff --git a/Assembly-CSharp/RimWorld/IncidentDefOf.cs b/Assembly-CSharp/RimWorld/IncidentDefOf.cs index bc421ad35..6cc91f03c 100644 --- a/Assembly-CSharp/RimWorld/IncidentDefOf.cs +++ b/Assembly-CSharp/RimWorld/IncidentDefOf.cs @@ -1,5 +1,3 @@ -using System; - namespace RimWorld { [DefOf] diff --git a/Assembly-CSharp/RimWorld/IncidentParms.cs b/Assembly-CSharp/RimWorld/IncidentParms.cs index 44923026c..09bce565d 100644 --- a/Assembly-CSharp/RimWorld/IncidentParms.cs +++ b/Assembly-CSharp/RimWorld/IncidentParms.cs @@ -1,4 +1,3 @@ -using System; using Verse; namespace RimWorld @@ -52,35 +51,17 @@ public override string ToString() if (this.target != null) { string text2 = text; - text = string.Concat(new object[] - { - text2, - "target=", - this.target, - " " - }); + text = text2 + "target=" + this.target + " "; } - if (this.points >= 0f) + if (this.points >= 0.0) { string text2 = text; - text = string.Concat(new object[] - { - text2, - "points=", - this.points, - " " - }); + text = text2 + "points=" + this.points + " "; } if (this.generateFightersOnly) { string text2 = text; - text = string.Concat(new object[] - { - text2, - "generateFightersOnly=", - this.generateFightersOnly, - " " - }); + text = text2 + "generateFightersOnly=" + this.generateFightersOnly + " "; } if (this.raidStrategy != null) { diff --git a/Assembly-CSharp/RimWorld/IncidentParmsUtility.cs b/Assembly-CSharp/RimWorld/IncidentParmsUtility.cs index b1a739b71..48671d2e7 100644 --- a/Assembly-CSharp/RimWorld/IncidentParmsUtility.cs +++ b/Assembly-CSharp/RimWorld/IncidentParmsUtility.cs @@ -1,4 +1,3 @@ -using System; using UnityEngine; namespace RimWorld @@ -7,16 +6,15 @@ public static class IncidentParmsUtility { public static PawnGroupMakerParms GetDefaultPawnGroupMakerParms(IncidentParms parms) { - return new PawnGroupMakerParms - { - tile = parms.target.Tile, - points = parms.points, - faction = parms.faction, - traderKind = parms.traderKind, - generateFightersOnly = parms.generateFightersOnly, - raidStrategy = parms.raidStrategy, - forceOneIncap = parms.raidForceOneIncap - }; + PawnGroupMakerParms pawnGroupMakerParms = new PawnGroupMakerParms(); + pawnGroupMakerParms.tile = parms.target.Tile; + pawnGroupMakerParms.points = parms.points; + pawnGroupMakerParms.faction = parms.faction; + pawnGroupMakerParms.traderKind = parms.traderKind; + pawnGroupMakerParms.generateFightersOnly = parms.generateFightersOnly; + pawnGroupMakerParms.raidStrategy = parms.raidStrategy; + pawnGroupMakerParms.forceOneIncap = parms.raidForceOneIncap; + return pawnGroupMakerParms; } public static void AdjustPointsForGroupArrivalParams(IncidentParms parms) @@ -28,18 +26,24 @@ public static void AdjustPointsForGroupArrivalParams(IncidentParms parms) switch (parms.raidArrivalMode) { case PawnsArriveMode.EdgeWalkIn: + { parms.points *= 1f; break; + } case PawnsArriveMode.EdgeDrop: + { parms.points *= 1f; break; + } case PawnsArriveMode.CenterDrop: + { parms.points *= 0.45f; break; } + } if (parms.raidStrategy != null) { - parms.points = Mathf.Max(parms.points, parms.raidStrategy.Worker.MinimumPoints(parms.faction) * 1.05f); + parms.points = Mathf.Max(parms.points, (float)(parms.raidStrategy.Worker.MinimumPoints(parms.faction) * 1.0499999523162842)); } } } diff --git a/Assembly-CSharp/RimWorld/IncidentPopulationEffect.cs b/Assembly-CSharp/RimWorld/IncidentPopulationEffect.cs index f5eb74c45..61b11e744 100644 --- a/Assembly-CSharp/RimWorld/IncidentPopulationEffect.cs +++ b/Assembly-CSharp/RimWorld/IncidentPopulationEffect.cs @@ -1,10 +1,8 @@ -using System; - namespace RimWorld { public enum IncidentPopulationEffect : byte { - None, - Increase + None = 0, + Increase = 1 } } diff --git a/Assembly-CSharp/RimWorld/IncidentQueue.cs b/Assembly-CSharp/RimWorld/IncidentQueue.cs index 857769094..f5e50b844 100644 --- a/Assembly-CSharp/RimWorld/IncidentQueue.cs +++ b/Assembly-CSharp/RimWorld/IncidentQueue.cs @@ -1,7 +1,6 @@ using System; using System.Collections; using System.Collections.Generic; -using System.Diagnostics; using System.Text; using Verse; @@ -24,20 +23,38 @@ public string DebugQueueReadout get { StringBuilder stringBuilder = new StringBuilder(); - foreach (QueuedIncident current in this.queuedIncidents) + List.Enumerator enumerator = this.queuedIncidents.GetEnumerator(); + try { - stringBuilder.AppendLine(current.ToString() + " (in " + (current.FireTick - Find.TickManager.TicksGame).ToString() + " ticks)"); + while (enumerator.MoveNext()) + { + QueuedIncident current = enumerator.Current; + stringBuilder.AppendLine(current.ToString() + " (in " + (current.FireTick - Find.TickManager.TicksGame).ToString() + " ticks)"); + } + } + finally + { + ((IDisposable)(object)enumerator).Dispose(); } return stringBuilder.ToString(); } } - [DebuggerHidden] public IEnumerator GetEnumerator() { - IncidentQueue.c__IteratorA3 c__IteratorA = new IncidentQueue.c__IteratorA3(); - c__IteratorA.<>f__this = this; - return c__IteratorA; + List.Enumerator enumerator = this.queuedIncidents.GetEnumerator(); + try + { + while (enumerator.MoveNext()) + { + QueuedIncident inc = enumerator.Current; + yield return (object)inc; + } + } + finally + { + ((IDisposable)(object)enumerator).Dispose(); + } } public void Clear() @@ -53,7 +70,7 @@ public void ExposeData() public bool Add(QueuedIncident qi) { this.queuedIncidents.Add(qi); - this.queuedIncidents.Sort((QueuedIncident a, QueuedIncident b) => a.FireTick.CompareTo(b.FireTick)); + this.queuedIncidents.Sort((Comparison)((QueuedIncident a, QueuedIncident b) => a.FireTick.CompareTo(b.FireTick))); return true; } @@ -67,9 +84,9 @@ public bool Add(IncidentDef def, int fireTick, IncidentParms parms = null) public void IncidentQueueTick() { - for (int i = this.queuedIncidents.Count - 1; i >= 0; i--) + for (int num = this.queuedIncidents.Count - 1; num >= 0; num--) { - QueuedIncident queuedIncident = this.queuedIncidents[i]; + QueuedIncident queuedIncident = this.queuedIncidents[num]; if (queuedIncident.FireTick <= Find.TickManager.TicksGame) { Find.Storyteller.TryFire(queuedIncident.FiringIncident); diff --git a/Assembly-CSharp/RimWorld/IncidentWorker.cs b/Assembly-CSharp/RimWorld/IncidentWorker.cs index fcbd110e7..a60ba9888 100644 --- a/Assembly-CSharp/RimWorld/IncidentWorker.cs +++ b/Assembly-CSharp/RimWorld/IncidentWorker.cs @@ -1,5 +1,4 @@ using RimWorld.Planet; -using System; using System.Collections.Generic; using System.Linq; using Verse; @@ -28,7 +27,7 @@ public bool CanFireNow(IIncidentTarget target) { return false; } - if (PawnsFinder.AllMapsCaravansAndTravelingTransportPods_FreeColonists.Count() < this.def.minPopulation) + if (PawnsFinder.AllMapsCaravansAndTravelingTransportPods_FreeColonists.Count() < this.def.minPopulation) { return false; } @@ -54,10 +53,10 @@ public bool CanFireNow(IIncidentTarget target) } Dictionary lastFireTicks = target.StoryState.lastFireTicks; int ticksGame = Find.TickManager.TicksGame; - int num; + int num = default(int); if (lastFireTicks.TryGetValue(this.def, out num)) { - float num2 = (float)(ticksGame - num) / 60000f; + float num2 = (float)((float)(ticksGame - num) / 60000.0); if (num2 < this.def.minRefireDays) { return false; @@ -70,7 +69,7 @@ public bool CanFireNow(IIncidentTarget target) { if (lastFireTicks.TryGetValue(refireCheckIncidents[j], out num)) { - float num3 = (float)(ticksGame - num) / 60000f; + float num3 = (float)((float)(ticksGame - num) / 60000.0); if (num3 < this.def.minRefireDays) { return false; @@ -78,7 +77,11 @@ public bool CanFireNow(IIncidentTarget target) } } } - return this.CanFireNowSub(target); + if (!this.CanFireNowSub(target)) + { + return false; + } + return true; } protected virtual bool CanFireNowSub(IIncidentTarget target) @@ -98,7 +101,7 @@ protected void SendStandardLetter() { Log.Error("Sending standard incident letter with no label or text."); } - Find.LetterStack.ReceiveLetter(this.def.letterLabel, this.def.letterText, this.def.letterDef, null); + Find.LetterStack.ReceiveLetter(this.def.letterLabel, this.def.letterText, this.def.letterDef, (string)null); } protected void SendStandardLetter(GlobalTargetInfo target, params string[] textArgs) @@ -108,7 +111,7 @@ protected void SendStandardLetter(GlobalTargetInfo target, params string[] textA Log.Error("Sending standard incident letter with no label or text."); } string text = string.Format(this.def.letterText, textArgs).CapitalizeFirst(); - Find.LetterStack.ReceiveLetter(this.def.letterLabel, text, this.def.letterDef, target, null); + Find.LetterStack.ReceiveLetter(this.def.letterLabel, text, this.def.letterDef, target, (string)null); } } } diff --git a/Assembly-CSharp/RimWorld/IncidentWorker_Alphabeavers.cs b/Assembly-CSharp/RimWorld/IncidentWorker_Alphabeavers.cs index 19a74fb61..a89d3736d 100644 --- a/Assembly-CSharp/RimWorld/IncidentWorker_Alphabeavers.cs +++ b/Assembly-CSharp/RimWorld/IncidentWorker_Alphabeavers.cs @@ -9,19 +9,19 @@ public override bool TryExecute(IncidentParms parms) { Map map = (Map)parms.target; PawnKindDef alphabeaver = PawnKindDefOf.Alphabeaver; - IntVec3 intVec; - if (!RCellFinder.TryFindRandomPawnEntryCell(out intVec, map, CellFinder.EdgeRoadChance_Animal, null)) + IntVec3 intVec = default(IntVec3); + if (!RCellFinder.TryFindRandomPawnEntryCell(out intVec, map, CellFinder.EdgeRoadChance_Animal, (Predicate)null)) { return false; } int num = Rand.RangeInclusive(6, 12); - for (int i = 0; i < num; i++) + for (int num2 = 0; num2 < num; num2++) { IntVec3 loc = CellFinder.RandomClosewalkCellNear(intVec, map, 10, null); Pawn newThing = PawnGenerator.GeneratePawn(alphabeaver, null); GenSpawn.Spawn(newThing, loc, map); } - Find.LetterStack.ReceiveLetter("LetterLabelBeaversArrived".Translate(), "BeaversArrived".Translate(), LetterDefOf.BadNonUrgent, new TargetInfo(intVec, map, false), null); + Find.LetterStack.ReceiveLetter("LetterLabelBeaversArrived".Translate(), "BeaversArrived".Translate(), LetterDefOf.BadNonUrgent, new TargetInfo(intVec, map, false), (string)null); return true; } } diff --git a/Assembly-CSharp/RimWorld/IncidentWorker_AmbrosiaSprout.cs b/Assembly-CSharp/RimWorld/IncidentWorker_AmbrosiaSprout.cs index 9ba0d7fae..489c0640d 100644 --- a/Assembly-CSharp/RimWorld/IncidentWorker_AmbrosiaSprout.cs +++ b/Assembly-CSharp/RimWorld/IncidentWorker_AmbrosiaSprout.cs @@ -19,27 +19,28 @@ protected override bool CanFireNowSub(IIncidentTarget target) return false; } Map map = (Map)target; - IntVec3 intVec; - return map.weatherManager.growthSeasonMemory.GrowthSeasonOutdoorsNow && this.TryFindRootCell(map, out intVec); + if (!map.weatherManager.growthSeasonMemory.GrowthSeasonOutdoorsNow) + { + return false; + } + IntVec3 intVec = default(IntVec3); + return this.TryFindRootCell(map, out intVec); } public override bool TryExecute(IncidentParms parms) { Map map = (Map)parms.target; - IntVec3 root; + IntVec3 root = default(IntVec3); if (!this.TryFindRootCell(map, out root)) { return false; } Thing thing = null; int randomInRange = IncidentWorker_AmbrosiaSprout.CountRange.RandomInRange; - for (int i = 0; i < randomInRange; i++) + int num = 0; + IntVec3 intVec = default(IntVec3); + while (num < randomInRange && CellFinder.TryRandomClosewalkCellNear(root, map, 6, out intVec, (Predicate)((IntVec3 x) => this.CanSpawnAt(x, map)))) { - IntVec3 intVec; - if (!CellFinder.TryRandomClosewalkCellNear(root, map, 6, out intVec, (IntVec3 x) => this.CanSpawnAt(x, map))) - { - break; - } Plant plant = intVec.GetPlant(map); if (plant != null) { @@ -50,40 +51,41 @@ public override bool TryExecute(IncidentParms parms) { thing = thing2; } + num++; } if (thing == null) { return false; } - base.SendStandardLetter(thing, new string[0]); + base.SendStandardLetter(thing); return true; } private bool TryFindRootCell(Map map, out IntVec3 cell) { - return CellFinderLoose.TryFindRandomNotEdgeCellWith(10, (IntVec3 x) => this.CanSpawnAt(x, map) && x.GetRoom(map, RegionType.Set_Passable).CellCount >= 64, map, out cell); + return CellFinderLoose.TryFindRandomNotEdgeCellWith(10, (Predicate)((IntVec3 x) => this.CanSpawnAt(x, map) && x.GetRoom(map, RegionType.Set_Passable).CellCount >= 64), map, out cell); } private bool CanSpawnAt(IntVec3 c, Map map) { - if (!c.Standable(map) || c.Fogged(map) || map.fertilityGrid.FertilityAt(c) < ThingDefOf.PlantAmbrosia.plant.fertilityMin || !c.GetRoom(map, RegionType.Set_Passable).PsychologicallyOutdoors || c.GetEdifice(map) != null || !GenPlant.GrowthSeasonNow(c, map)) - { - return false; - } - Plant plant = c.GetPlant(map); - if (plant != null && plant.def.plant.growDays > 10f) - { - return false; - } - List thingList = c.GetThingList(map); - for (int i = 0; i < thingList.Count; i++) + if (c.Standable(map) && !c.Fogged(map) && !(map.fertilityGrid.FertilityAt(c) < ThingDefOf.PlantAmbrosia.plant.fertilityMin) && c.GetRoom(map, RegionType.Set_Passable).PsychologicallyOutdoors && c.GetEdifice(map) == null && GenPlant.GrowthSeasonNow(c, map)) { - if (thingList[i].def == ThingDefOf.PlantAmbrosia) + Plant plant = c.GetPlant(map); + if (plant != null && plant.def.plant.growDays > 10.0) { return false; } + List thingList = c.GetThingList(map); + for (int i = 0; i < thingList.Count; i++) + { + if (thingList[i].def == ThingDefOf.PlantAmbrosia) + { + return false; + } + } + return true; } - return true; + return false; } } } diff --git a/Assembly-CSharp/RimWorld/IncidentWorker_Ambush.cs b/Assembly-CSharp/RimWorld/IncidentWorker_Ambush.cs index 9d8f7261e..7bd18a6a4 100644 --- a/Assembly-CSharp/RimWorld/IncidentWorker_Ambush.cs +++ b/Assembly-CSharp/RimWorld/IncidentWorker_Ambush.cs @@ -22,7 +22,11 @@ protected virtual LordJob CreateLordJob(List generatedPawns, out Faction f protected override bool CanFireNowSub(IIncidentTarget target) { - return target is Map || CaravanIncidentUtility.CanFireIncidentWhichWantsToGenerateMapAt(target.Tile); + if (target is Map) + { + return true; + } + return CaravanIncidentUtility.CanFireIncidentWhichWantsToGenerateMapAt(target.Tile); } public override bool TryExecute(IncidentParms parms) @@ -31,7 +35,7 @@ public override bool TryExecute(IncidentParms parms) { return this.DoExecute(parms); } - LongEventHandler.QueueLongEvent(delegate + LongEventHandler.QueueLongEvent((Action)delegate() { this.DoExecute(parms); }, "GeneratingMapForNewEncounter", false, null); @@ -42,7 +46,7 @@ private bool DoExecute(IncidentParms parms) { Map map = parms.target as Map; IntVec3 invalid = IntVec3.Invalid; - if (map != null && !CellFinder.TryFindRandomEdgeCellWith((IntVec3 x) => x.Standable(map) && map.reachability.CanReachColony(x), map, CellFinder.EdgeRoadChance_Hostile, out invalid)) + if (map != null && !CellFinder.TryFindRandomEdgeCellWith((Predicate)((IntVec3 x) => x.Standable(map) && map.reachability.CanReachColony(x)), map, CellFinder.EdgeRoadChance_Hostile, out invalid)) { return false; } @@ -62,9 +66,9 @@ private bool DoExecute(IncidentParms parms) } } this.PostProcessGeneratedPawnsAfterSpawning(list); - Faction faction; + Faction faction = default(Faction); LordJob lordJob = this.CreateLordJob(list, out faction); - if (lordJob != null && list.Any()) + if (lordJob != null && list.Any()) { LordMaker.MakeNewLord(faction, lordJob, map, list); } diff --git a/Assembly-CSharp/RimWorld/IncidentWorker_Ambush_EnemyFaction.cs b/Assembly-CSharp/RimWorld/IncidentWorker_Ambush_EnemyFaction.cs index 9ed2167d7..f9d6e0fdf 100644 --- a/Assembly-CSharp/RimWorld/IncidentWorker_Ambush_EnemyFaction.cs +++ b/Assembly-CSharp/RimWorld/IncidentWorker_Ambush_EnemyFaction.cs @@ -1,4 +1,3 @@ -using System; using System.Collections.Generic; using System.Linq; using Verse; @@ -18,7 +17,7 @@ protected override List GeneratePawns(IIncidentTarget target, float points pawnGroupMakerParms.generateFightersOnly = true; pawnGroupMakerParms.faction = this.randomFaction; pawnGroupMakerParms.points = points; - return PawnGroupMakerUtility.GeneratePawns(PawnGroupKindDefOf.Normal, pawnGroupMakerParms, true).ToList(); + return PawnGroupMakerUtility.GeneratePawns(PawnGroupKindDefOf.Normal, pawnGroupMakerParms, true).ToList(); } protected override LordJob CreateLordJob(List generatedPawns, out Faction faction) @@ -31,11 +30,7 @@ protected override LordJob CreateLordJob(List generatedPawns, out Faction protected override void SendAmbushLetter(Pawn anyPawn, Faction enemyFaction) { - base.SendStandardLetter(anyPawn, new string[] - { - enemyFaction.def.pawnsPlural, - enemyFaction.Name - }); + base.SendStandardLetter((Thing)anyPawn, enemyFaction.def.pawnsPlural, enemyFaction.Name); } } } diff --git a/Assembly-CSharp/RimWorld/IncidentWorker_Ambush_ManhunterPack.cs b/Assembly-CSharp/RimWorld/IncidentWorker_Ambush_ManhunterPack.cs index c70904961..c35e367f0 100644 --- a/Assembly-CSharp/RimWorld/IncidentWorker_Ambush_ManhunterPack.cs +++ b/Assembly-CSharp/RimWorld/IncidentWorker_Ambush_ManhunterPack.cs @@ -1,4 +1,3 @@ -using System; using System.Collections.Generic; using Verse; @@ -8,16 +7,20 @@ public class IncidentWorker_Ambush_ManhunterPack : IncidentWorker_Ambush { public override bool TryExecute(IncidentParms parms) { - PawnKindDef pawnKindDef; - return ManhunterPackIncidentUtility.TryFindManhunterAnimalKind(parms.points, -1, out pawnKindDef) && base.TryExecute(parms); + PawnKindDef pawnKindDef = default(PawnKindDef); + if (!ManhunterPackIncidentUtility.TryFindManhunterAnimalKind(parms.points, -1, out pawnKindDef)) + { + return false; + } + return base.TryExecute(parms); } protected override List GeneratePawns(IIncidentTarget target, float points, int tile) { - PawnKindDef animalKind; + PawnKindDef animalKind = default(PawnKindDef); if (!ManhunterPackIncidentUtility.TryFindManhunterAnimalKind(points, tile, out animalKind) && !ManhunterPackIncidentUtility.TryFindManhunterAnimalKind(points, -1, out animalKind)) { - Log.Error("Could not find any valid animal kind for " + this.def + " incident."); + Log.Error("Could not find any valid animal kind for " + base.def + " incident."); return new List(); } return ManhunterPackIncidentUtility.GenerateAnimals(animalKind, tile, points); @@ -27,16 +30,13 @@ protected override void PostProcessGeneratedPawnsAfterSpawning(List genera { for (int i = 0; i < generatedPawns.Count; i++) { - generatedPawns[i].mindState.mentalStateHandler.TryStartMentalState(MentalStateDefOf.ManhunterPermanent, null, false, false, null); + generatedPawns[i].mindState.mentalStateHandler.TryStartMentalState(MentalStateDefOf.ManhunterPermanent, (string)null, false, false, null); } } protected override void SendAmbushLetter(Pawn anyPawn, Faction enemyFaction) { - base.SendStandardLetter(anyPawn, new string[] - { - anyPawn.KindLabelPlural - }); + base.SendStandardLetter((Thing)anyPawn, anyPawn.KindLabelPlural); } } } diff --git a/Assembly-CSharp/RimWorld/IncidentWorker_AnimalInsanityMass.cs b/Assembly-CSharp/RimWorld/IncidentWorker_AnimalInsanityMass.cs index 14ce43748..ce5d753bb 100644 --- a/Assembly-CSharp/RimWorld/IncidentWorker_AnimalInsanityMass.cs +++ b/Assembly-CSharp/RimWorld/IncidentWorker_AnimalInsanityMass.cs @@ -15,19 +15,19 @@ public static bool AnimalUsable(Pawn p) public static void DriveInsane(Pawn p) { - p.mindState.mentalStateHandler.TryStartMentalState(MentalStateDefOf.Manhunter, null, true, false, null); + p.mindState.mentalStateHandler.TryStartMentalState(MentalStateDefOf.Manhunter, (string)null, true, false, null); } public override bool TryExecute(IncidentParms parms) { Map map = (Map)parms.target; - if (parms.points <= 0f) + if (parms.points <= 0.0) { Log.Error("AnimalInsanity running without points."); - parms.points = (float)((int)(map.strengthWatcher.StrengthRating * 50f)); + parms.points = (float)(int)(map.strengthWatcher.StrengthRating * 50.0); } float adjustedPoints = parms.points; - if (adjustedPoints > 250f) + if (adjustedPoints > 250.0) { adjustedPoints -= 250f; adjustedPoints *= 0.5f; @@ -36,33 +36,43 @@ public override bool TryExecute(IncidentParms parms) IEnumerable source = from def in DefDatabase.AllDefs where def.RaceProps.Animal && def.combatPower <= adjustedPoints && (from p in map.mapPawns.AllPawnsSpawned where p.kindDef == def && IncidentWorker_AnimalInsanityMass.AnimalUsable(p) - select p).Count() >= 3 + select p).Count() >= 3 select def; PawnKindDef animalDef; - if (!source.TryRandomElement(out animalDef)) + if (!source.TryRandomElement(out animalDef)) { return false; } List list = (from p in map.mapPawns.AllPawnsSpawned where p.kindDef == animalDef && IncidentWorker_AnimalInsanityMass.AnimalUsable(p) - select p).ToList(); + select p).ToList(); float combatPower = animalDef.combatPower; float num = 0f; int num2 = 0; Pawn pawn = null; - list.Shuffle(); - foreach (Pawn current in list) + list.Shuffle(); + List.Enumerator enumerator = list.GetEnumerator(); + try { - if (num + combatPower > adjustedPoints) + while (enumerator.MoveNext()) { + Pawn current = enumerator.Current; + if (!(num + combatPower > adjustedPoints)) + { + IncidentWorker_AnimalInsanityMass.DriveInsane(current); + num += combatPower; + num2++; + pawn = current; + continue; + } break; } - IncidentWorker_AnimalInsanityMass.DriveInsane(current); - num += combatPower; - num2++; - pawn = current; } - if (num == 0f) + finally + { + ((IDisposable)(object)enumerator).Dispose(); + } + if (num == 0.0) { return false; } @@ -71,20 +81,14 @@ public override bool TryExecute(IncidentParms parms) if (num2 == 1) { label = "LetterLabelAnimalInsanitySingle".Translate() + ": " + pawn.LabelCap; - text = "AnimalInsanitySingle".Translate(new object[] - { - pawn.LabelShort - }); + text = "AnimalInsanitySingle".Translate(pawn.LabelShort); } else { label = "LetterLabelAnimalInsanityMultiple".Translate() + ": " + animalDef.LabelCap; - text = "AnimalInsanityMultiple".Translate(new object[] - { - animalDef.label - }); + text = "AnimalInsanityMultiple".Translate(animalDef.label); } - Find.LetterStack.ReceiveLetter(label, text, LetterDefOf.BadUrgent, pawn, null); + Find.LetterStack.ReceiveLetter(label, text, LetterDefOf.BadUrgent, (Thing)pawn, (string)null); SoundDefOf.PsychicPulseGlobal.PlayOneShotOnCamera(map); if (map == Find.VisibleMap) { diff --git a/Assembly-CSharp/RimWorld/IncidentWorker_AnimalInsanitySingle.cs b/Assembly-CSharp/RimWorld/IncidentWorker_AnimalInsanitySingle.cs index c85a58aca..540924765 100644 --- a/Assembly-CSharp/RimWorld/IncidentWorker_AnimalInsanitySingle.cs +++ b/Assembly-CSharp/RimWorld/IncidentWorker_AnimalInsanitySingle.cs @@ -19,18 +19,15 @@ public override bool TryExecute(IncidentParms parms) } List list = (from p in map.mapPawns.AllPawnsSpawned where p.RaceProps.Animal && p.kindDef.combatPower <= (float)maxPoints && IncidentWorker_AnimalInsanityMass.AnimalUsable(p) - select p).ToList(); + select p).ToList(); if (list.Count == 0) { return false; } - Pawn pawn = list.RandomElement(); + Pawn pawn = list.RandomElement(); IncidentWorker_AnimalInsanityMass.DriveInsane(pawn); - string text = "AnimalInsanitySingle".Translate(new object[] - { - pawn.Label - }); - Find.LetterStack.ReceiveLetter("LetterLabelAnimalInsanitySingle".Translate(), text, LetterDefOf.BadUrgent, pawn, null); + string text = "AnimalInsanitySingle".Translate(pawn.Label); + Find.LetterStack.ReceiveLetter("LetterLabelAnimalInsanitySingle".Translate(), text, LetterDefOf.BadUrgent, (Thing)pawn, (string)null); return true; } } diff --git a/Assembly-CSharp/RimWorld/IncidentWorker_CaravanDemand.cs b/Assembly-CSharp/RimWorld/IncidentWorker_CaravanDemand.cs index 09c833ef3..80ac302df 100644 --- a/Assembly-CSharp/RimWorld/IncidentWorker_CaravanDemand.cs +++ b/Assembly-CSharp/RimWorld/IncidentWorker_CaravanDemand.cs @@ -39,34 +39,31 @@ public override bool TryExecute(IncidentParms parms) pawnGroupMakerParms.generateFightersOnly = true; pawnGroupMakerParms.faction = faction; pawnGroupMakerParms.points = parms.points; - List attackers = PawnGroupMakerUtility.GeneratePawns(PawnGroupKindDefOf.Normal, pawnGroupMakerParms, true).ToList(); + List attackers = PawnGroupMakerUtility.GeneratePawns(PawnGroupKindDefOf.Normal, pawnGroupMakerParms, true).ToList(); List demands = this.GenerateDemands(caravan); if (demands.Count == 0) { return false; } - CameraJumper.TryJumpAndSelect(caravan); + CameraJumper.TryJumpAndSelect((WorldObject)caravan); DiaNode diaNode = new DiaNode(this.GenerateMessageText(faction, attackers.Count, demands)); DiaOption diaOption = new DiaOption("CaravanDemand_Give".Translate()); - diaOption.action = delegate + diaOption.action = (Action)delegate { this.ActionGive(caravan, demands, attackers); }; diaOption.resolveTree = true; diaNode.options.Add(diaOption); DiaOption diaOption2 = new DiaOption("CaravanDemand_Fight".Translate()); - diaOption2.action = delegate + diaOption2.action = (Action)delegate { this.ActionFight(caravan, attackers); }; diaOption2.resolveTree = true; diaNode.options.Add(diaOption2); - WindowStack arg_173_0 = Find.WindowStack; - string title = "CaravanDemandTitle".Translate(new object[] - { - faction.Name - }); - arg_173_0.Add(new Dialog_NodeTree(diaNode, true, false, title)); + WindowStack windowStack = Find.WindowStack; + string title = "CaravanDemandTitle".Translate(faction.Name); + windowStack.Add(new Dialog_NodeTree(diaNode, true, false, title)); return true; } @@ -75,20 +72,16 @@ private List GenerateDemands(Caravan caravan) List list = new List(); List list2 = new List(); list2.AddRange(caravan.PawnsListForReading.Cast()); - list2.AddRange(caravan.PawnsListForReading.SelectMany((Pawn pawn) => ThingOwnerUtility.GetAllThingsRecursively(pawn, false))); - float num = list2.Sum((Thing thing) => thing.MarketValue); + list2.AddRange(caravan.PawnsListForReading.SelectMany((Func>)((Pawn pawn) => ThingOwnerUtility.GetAllThingsRecursively(pawn, false)))); + float num = list2.Sum((Func)((Thing thing) => thing.MarketValue)); float num2 = IncidentWorker_CaravanDemand.DemandAsPercentageOfCaravan.RandomInRange * num; - while (num2 > 0f) + while (((num2 > 0.0) ? list2.Count : 0) != 0) { - if (list2.Count == 0) - { - break; - } - if (list2.Count((Thing thing) => thing is Pawn && (thing as Pawn).IsColonist) == 1) + if (list2.Count((Func)((Thing thing) => thing is Pawn && (thing as Pawn).IsColonist)) == 1) { - list2.RemoveAll((Thing thing) => thing is Pawn && (thing as Pawn).IsColonist); + list2.RemoveAll((Predicate)((Thing thing) => thing is Pawn && (thing as Pawn).IsColonist)); } - Thing thing2 = list2.RandomElementByWeight(delegate(Thing thing) + Thing thing2 = list2.RandomElementByWeight((Func)delegate(Thing thing) { if (thing.def == ThingDefOf.Silver) { @@ -96,16 +89,16 @@ private List GenerateDemands(Caravan caravan) } if (thing is Pawn) { - Pawn pawn = thing as Pawn; - if (pawn.RaceProps.Animal) + Pawn pawn2 = thing as Pawn; + if (pawn2.RaceProps.Animal) { return 1f; } - if (pawn.IsPrisoner) + if (pawn2.IsPrisoner) { return 1f; } - if (pawn.IsColonist) + if (pawn2.IsColonist) { return 0.2f; } @@ -121,13 +114,7 @@ private List GenerateDemands(Caravan caravan) private string GenerateMessageText(Faction enemyFaction, int attackerCount, List demands) { - return "CaravanDemand".Translate(new object[] - { - enemyFaction.Name, - attackerCount, - GenLabel.ThingsLabel(demands), - enemyFaction.def.pawnsPlural - }); + return "CaravanDemand".Translate(enemyFaction.Name, attackerCount, GenLabel.ThingsLabel(demands), enemyFaction.def.pawnsPlural); } private void TakeFromCaravan(Caravan caravan, List demands, Faction enemyFaction) @@ -140,10 +127,19 @@ private void TakeFromCaravan(Caravan caravan, List demands, Faction enemy { Pawn pawn = thing as Pawn; caravan.RemovePawn(pawn); - foreach (Thing current in ThingOwnerUtility.GetAllThingsRecursively(pawn, false)) + List.Enumerator enumerator = ThingOwnerUtility.GetAllThingsRecursively(pawn, false).GetEnumerator(); + try + { + while (enumerator.MoveNext()) + { + Thing current = enumerator.Current; + list.Add(current); + current.holdingOwner.Take(current); + } + } + finally { - list.Add(current); - current.holdingOwner.Take(current); + ((IDisposable)(object)enumerator).Dispose(); } enemyFaction.kidnapped.KidnapPawn(pawn, null); } @@ -177,7 +173,7 @@ private void ActionGive(Caravan caravan, List demands, List attacke private void ActionFight(Caravan caravan, List attackers) { Faction enemyFaction = attackers[0].Faction; - LongEventHandler.QueueLongEvent(delegate + LongEventHandler.QueueLongEvent((Action)delegate() { Map map = CaravanIncidentUtility.SetupCaravanAttackMap(caravan, attackers); LordJob_AssaultColony lordJob_AssaultColony = new LordJob_AssaultColony(enemyFaction, true, false, false, false, true); @@ -185,11 +181,7 @@ private void ActionFight(Caravan caravan, List attackers) { LordMaker.MakeNewLord(enemyFaction, lordJob_AssaultColony, map, attackers); } - this.SendStandardLetter(attackers[0], new string[] - { - enemyFaction.def.pawnsPlural, - enemyFaction.Name - }); + base.SendStandardLetter((Thing)attackers[0], enemyFaction.def.pawnsPlural, enemyFaction.Name); Find.TickManager.CurTimeSpeed = TimeSpeed.Paused; }, "GeneratingMapForNewEncounter", false, null); } diff --git a/Assembly-CSharp/RimWorld/IncidentWorker_CaravanMeeting.cs b/Assembly-CSharp/RimWorld/IncidentWorker_CaravanMeeting.cs index b93cdf9ab..21cb38a16 100644 --- a/Assembly-CSharp/RimWorld/IncidentWorker_CaravanMeeting.cs +++ b/Assembly-CSharp/RimWorld/IncidentWorker_CaravanMeeting.cs @@ -13,7 +13,11 @@ public class IncidentWorker_CaravanMeeting : IncidentWorker protected override bool CanFireNowSub(IIncidentTarget target) { - return target is Map || CaravanIncidentUtility.CanFireIncidentWhichWantsToGenerateMapAt(target.Tile); + if (target is Map) + { + return true; + } + return CaravanIncidentUtility.CanFireIncidentWhichWantsToGenerateMapAt(target.Tile); } public override bool TryExecute(IncidentParms parms) @@ -25,25 +29,21 @@ public override bool TryExecute(IncidentParms parms) Caravan caravan = (Caravan)parms.target; Faction faction; if (!(from x in Find.FactionManager.AllFactionsListForReading - where !x.IsPlayer && !x.HostileTo(Faction.OfPlayer) && !x.def.hidden && x.def.humanlikeFaction && x.def.caravanTraderKinds.Any() - select x).TryRandomElement(out faction)) + where !x.IsPlayer && !x.HostileTo(Faction.OfPlayer) && !x.def.hidden && x.def.humanlikeFaction && x.def.caravanTraderKinds.Any() + select x).TryRandomElement(out faction)) { return false; } - CameraJumper.TryJumpAndSelect(caravan); + CameraJumper.TryJumpAndSelect((WorldObject)caravan); List pawns = this.GenerateCaravanPawns(faction); Caravan metCaravan = CaravanMaker.MakeCaravan(pawns, faction, -1, false); - string text = "CaravanMeeting".Translate(new object[] - { - faction.Name, - PawnUtility.PawnKindsToCommaList(metCaravan.PawnsListForReading) - }); + string text = "CaravanMeeting".Translate(faction.Name, PawnUtility.PawnKindsToCommaList(metCaravan.PawnsListForReading)); DiaNode diaNode = new DiaNode(text); Pawn bestPlayerNegotiator = CaravanVisitUtility.BestNegotiator(caravan); if (bestPlayerNegotiator != null && metCaravan.CanTradeNow) { DiaOption diaOption = new DiaOption("CaravanMeeting_Trade".Translate()); - diaOption.action = delegate + diaOption.action = (Action)delegate { Find.WindowStack.Add(new Dialog_Trade(bestPlayerNegotiator, metCaravan)); string empty = string.Empty; @@ -51,15 +51,15 @@ public override bool TryExecute(IncidentParms parms) PawnRelationUtility.Notify_PawnsSeenByPlayer(metCaravan.Goods.OfType(), ref empty, ref empty2, "LetterRelatedPawnsTradingWithOtherCaravan".Translate(), false); if (!empty2.NullOrEmpty()) { - Find.LetterStack.ReceiveLetter(empty, empty2, LetterDefOf.Good, new GlobalTargetInfo(caravan.Tile), null); + Find.LetterStack.ReceiveLetter(empty, empty2, LetterDefOf.Good, new GlobalTargetInfo(caravan.Tile), (string)null); } }; diaNode.options.Add(diaOption); } DiaOption diaOption2 = new DiaOption("CaravanMeeting_Attack".Translate()); - diaOption2.action = delegate + diaOption2.action = (Action)delegate { - LongEventHandler.QueueLongEvent(delegate + LongEventHandler.QueueLongEvent((Action)delegate { if (!faction.HostileTo(Faction.OfPlayer)) { @@ -70,34 +70,28 @@ public override bool TryExecute(IncidentParms parms) IntVec3 playerSpot; IntVec3 enemySpot; MultipleCaravansCellFinder.FindStartingCellsFor2Groups(map, out playerSpot, out enemySpot); - CaravanEnterMapUtility.Enter(caravan, map, (Pawn p) => CellFinder.RandomClosewalkCellNear(playerSpot, map, 12, null), CaravanDropInventoryMode.DoNotDrop, true); - List list = metCaravan.PawnsListForReading.ToList(); - CaravanEnterMapUtility.Enter(metCaravan, map, (Pawn p) => CellFinder.RandomClosewalkCellNear(enemySpot, map, 12, null), CaravanDropInventoryMode.DoNotDrop, false); + CaravanEnterMapUtility.Enter(caravan, map, (Func)((Pawn p) => CellFinder.RandomClosewalkCellNear(playerSpot, map, 12, null)), CaravanDropInventoryMode.DoNotDrop, true); + List list = metCaravan.PawnsListForReading.ToList(); + CaravanEnterMapUtility.Enter(metCaravan, map, (Func)((Pawn p) => CellFinder.RandomClosewalkCellNear(enemySpot, map, 12, null)), CaravanDropInventoryMode.DoNotDrop, false); LordMaker.MakeNewLord(faction, new LordJob_DefendAttackedTraderCaravan(list[0].Position), map, list); Find.TickManager.CurTimeSpeed = TimeSpeed.Paused; - CameraJumper.TryJumpAndSelect(t); - Messages.Message("MessageAttackedCaravanIsNowHostile".Translate(new object[] - { - faction.Name - }), new GlobalTargetInfo(list[0].Position, list[0].Map, false), MessageSound.SeriousAlert); + CameraJumper.TryJumpAndSelect((Thing)t); + Messages.Message("MessageAttackedCaravanIsNowHostile".Translate(faction.Name), new GlobalTargetInfo(list[0].Position, list[0].Map, false), MessageSound.SeriousAlert); }, "GeneratingMapForNewEncounter", false, null); }; diaOption2.resolveTree = true; diaNode.options.Add(diaOption2); DiaOption diaOption3 = new DiaOption("CaravanMeeting_MoveOn".Translate()); - diaOption3.action = delegate + diaOption3.action = (Action)delegate { this.RemoveAllPawnsAndPassToWorld(metCaravan); }; diaOption3.resolveTree = true; diaNode.options.Add(diaOption3); - string text2 = "CaravanMeetingTitle".Translate(new object[] - { - caravan.Label - }); - WindowStack arg_1F8_0 = Find.WindowStack; + string text2 = "CaravanMeetingTitle".Translate(caravan.Label); + WindowStack windowStack = Find.WindowStack; string title = text2; - arg_1F8_0.Add(new Dialog_NodeTree(diaNode, true, false, title)); + windowStack.Add(new Dialog_NodeTree(diaNode, true, false, title)); return true; } @@ -106,7 +100,7 @@ private List GenerateCaravanPawns(Faction faction) PawnGroupMakerParms pawnGroupMakerParms = new PawnGroupMakerParms(); pawnGroupMakerParms.faction = faction; pawnGroupMakerParms.points = TraderCaravanUtility.GenerateGuardPoints(); - return PawnGroupMakerUtility.GeneratePawns(PawnGroupKindDefOf.Trader, pawnGroupMakerParms, true).ToList(); + return PawnGroupMakerUtility.GeneratePawns(PawnGroupKindDefOf.Trader, pawnGroupMakerParms, true).ToList(); } private void RemoveAllPawnsAndPassToWorld(Caravan caravan) diff --git a/Assembly-CSharp/RimWorld/IncidentWorker_CaravanRequest.cs b/Assembly-CSharp/RimWorld/IncidentWorker_CaravanRequest.cs index 0be9b8415..78adb3429 100644 --- a/Assembly-CSharp/RimWorld/IncidentWorker_CaravanRequest.cs +++ b/Assembly-CSharp/RimWorld/IncidentWorker_CaravanRequest.cs @@ -36,7 +36,11 @@ public class IncidentWorker_CaravanRequest : IncidentWorker protected override bool CanFireNowSub(IIncidentTarget target) { - return IncidentWorker_CaravanRequest.RandomNearbyTradeableSettlement(((Map)target).Tile) != null && base.CanFireNowSub(target); + if (IncidentWorker_CaravanRequest.RandomNearbyTradeableSettlement(((Map)target).Tile) == null) + { + return false; + } + return base.CanFireNowSub(target); } public override bool TryExecute(IncidentParms parms) @@ -46,18 +50,12 @@ public override bool TryExecute(IncidentParms parms) { return false; } - CaravanRequestComp component = settlement.GetComponent(); + CaravanRequestComp component = ((WorldObject)settlement).GetComponent(); if (!this.GenerateCaravanRequest(component, (Map)parms.target)) { return false; } - Find.LetterStack.ReceiveLetter("LetterLabelCaravanRequest".Translate(), "LetterCaravanRequest".Translate(new object[] - { - settlement.Label, - GenLabel.ThingLabel(component.requestThingDef, null, component.requestCount).CapitalizeFirst(), - component.rewards[0].LabelCap, - (component.expiration - Find.TickManager.TicksGame).ToStringTicksToDays("F0") - }), LetterDefOf.Good, settlement, null); + Find.LetterStack.ReceiveLetter("LetterLabelCaravanRequest".Translate(), "LetterCaravanRequest".Translate(settlement.Label, GenLabel.ThingLabel(component.requestThingDef, null, component.requestCount).CapitalizeFirst(), component.rewards[0].LabelCap, (component.expiration - Find.TickManager.TicksGame).ToStringTicksToDays("F0")), LetterDefOf.Good, (WorldObject)settlement, (string)null); return true; } @@ -83,16 +81,21 @@ public bool GenerateCaravanRequest(CaravanRequestComp target, Map map) public static Settlement RandomNearbyTradeableSettlement(int originTile) { - return (from settlement in Find.WorldObjects.Settlements - where settlement.Visitable && settlement.GetComponent() != null && !settlement.GetComponent().ActiveRequest && Find.WorldGrid.ApproxDistanceInTiles(originTile, settlement.Tile) < 36f && Find.WorldReachability.CanReach(originTile, settlement.Tile) - select settlement).RandomElementWithFallback(null); + return Find.WorldObjects.Settlements.Where((Func)delegate(Settlement settlement) + { + if (settlement.Visitable && ((WorldObject)settlement).GetComponent() != null && !((WorldObject)settlement).GetComponent().ActiveRequest) + { + return Find.WorldGrid.ApproxDistanceInTiles(originTile, settlement.Tile) < 36.0 && Find.WorldReachability.CanReach(originTile, settlement.Tile); + } + return false; + }).RandomElementWithFallback(null); } private static ThingDef RandomRequestedThingDef() { - Func globalValidator = delegate(ThingDef td) + Func globalValidator = (Func)delegate(ThingDef td) { - if (td.BaseMarketValue / td.BaseMass < 5f) + if (td.BaseMarketValue / td.BaseMass < 5.0) { return false; } @@ -101,22 +104,53 @@ private static ThingDef RandomRequestedThingDef() return false; } CompProperties_Rottable compProperties = td.GetCompProperties(); - return (compProperties == null || compProperties.daysToRotStart >= 10f) && td != ThingDefOf.Silver && td.PlayerAcquirable; + if (compProperties != null && compProperties.daysToRotStart < 10.0) + { + return false; + } + if (td == ThingDefOf.Silver) + { + return false; + } + if (!td.PlayerAcquirable) + { + return false; + } + return true; }; - if (Rand.Value < 0.8f) + if (Rand.Value < 0.800000011920929) { ThingDef result = null; - bool flag = (from td in DefDatabase.AllDefs - where (td.IsWithinCategory(ThingCategoryDefOf.FoodMeals) || td.IsWithinCategory(ThingCategoryDefOf.PlantFoodRaw) || td.IsWithinCategory(ThingCategoryDefOf.PlantMatter) || td.IsWithinCategory(ThingCategoryDefOf.ResourcesRaw)) && td.BaseMarketValue < 4f && globalValidator(td) - select td).TryRandomElement(out result); - if (flag) + if (DefDatabase.AllDefs.Where((Func)delegate(ThingDef td) + { + int result3; + if ((td.IsWithinCategory(ThingCategoryDefOf.FoodMeals) || td.IsWithinCategory(ThingCategoryDefOf.PlantFoodRaw) || td.IsWithinCategory(ThingCategoryDefOf.PlantMatter) || td.IsWithinCategory(ThingCategoryDefOf.ResourcesRaw)) && td.BaseMarketValue < 4.0) + { + result3 = (globalValidator(td) ? 1 : 0); + goto IL_005f; + } + result3 = 0; + goto IL_005f; + IL_005f: + return (byte)result3 != 0; + }).TryRandomElement(out result)) { return result; } } - return (from td in DefDatabase.AllDefs - where (td.IsWithinCategory(ThingCategoryDefOf.Medicine) || td.IsWithinCategory(ThingCategoryDefOf.Drugs) || td.IsWithinCategory(ThingCategoryDefOf.Weapons) || td.IsWithinCategory(ThingCategoryDefOf.Apparel) || td.IsWithinCategory(ThingCategoryDefOf.ResourcesRaw)) && td.BaseMarketValue >= 4f && globalValidator(td) - select td).RandomElementWithFallback(null); + return DefDatabase.AllDefs.Where((Func)delegate(ThingDef td) + { + int result2; + if ((td.IsWithinCategory(ThingCategoryDefOf.Medicine) || td.IsWithinCategory(ThingCategoryDefOf.Drugs) || td.IsWithinCategory(ThingCategoryDefOf.Weapons) || td.IsWithinCategory(ThingCategoryDefOf.Apparel) || td.IsWithinCategory(ThingCategoryDefOf.ResourcesRaw)) && td.BaseMarketValue >= 4.0) + { + result2 = (globalValidator(td) ? 1 : 0); + goto IL_006f; + } + result2 = 0; + goto IL_006f; + IL_006f: + return (byte)result2 != 0; + }).RandomElementWithFallback(null); } private static int RandomRequestCount(ThingDef thingDef, Map map) @@ -130,26 +164,30 @@ private static int RandomRequestCount(ThingDef thingDef, Map map) private static Thing GenerateRewardFor(ThingDef thingDef, int quantity, Faction faction) { TechLevel techLevel = (faction != null) ? faction.def.techLevel : TechLevel.Spacer; - ItemCollectionGeneratorParams parms = default(ItemCollectionGeneratorParams); - parms.count = 1; - parms.totalMarketValue = thingDef.BaseMarketValue * (float)quantity * Rand.Range(1f, 2f); - parms.techLevel = techLevel; - parms.validator = ((ThingDef td) => td != thingDef); + ItemCollectionGeneratorParams parms = new ItemCollectionGeneratorParams + { + count = 1, + totalMarketValue = thingDef.BaseMarketValue * (float)quantity * Rand.Range(1f, 2f), + techLevel = techLevel, + validator = (Predicate)((ThingDef td) => td != thingDef) + }; return ItemCollectionGeneratorDefOf.CaravanRequestRewards.Worker.Generate(parms)[0]; } private int RandomOfferDuration(int tileIdFrom, int tileIdTo) { - int num = IncidentWorker_CaravanRequest.OfferDurationRange.RandomInRange; - int num2 = CaravanArrivalTimeEstimator.EstimatedTicksToArrive(tileIdFrom, tileIdTo, null); - float num3 = (float)num2 / 60000f; - int b = Mathf.CeilToInt(Mathf.Max(num3 + 1f, num3 * 1.1f)); - num = Mathf.Max(num, b); - if (num > IncidentWorker_CaravanRequest.OfferDurationRange.max) + int randomInRange = IncidentWorker_CaravanRequest.OfferDurationRange.RandomInRange; + int num = CaravanArrivalTimeEstimator.EstimatedTicksToArrive(tileIdFrom, tileIdTo, null); + float num2 = (float)((float)num / 60000.0); + int b = Mathf.CeilToInt(Mathf.Max((float)(num2 + 1.0), (float)(num2 * 1.1000000238418579))); + randomInRange = Mathf.Max(randomInRange, b); + int num3 = randomInRange; + IntRange offerDurationRange = IncidentWorker_CaravanRequest.OfferDurationRange; + if (num3 > offerDurationRange.max) { return -1; } - return 60000 * num; + return 60000 * randomInRange; } } } diff --git a/Assembly-CSharp/RimWorld/IncidentWorker_ColdSnap.cs b/Assembly-CSharp/RimWorld/IncidentWorker_ColdSnap.cs index c6caba724..660a22510 100644 --- a/Assembly-CSharp/RimWorld/IncidentWorker_ColdSnap.cs +++ b/Assembly-CSharp/RimWorld/IncidentWorker_ColdSnap.cs @@ -1,4 +1,3 @@ -using System; using Verse; namespace RimWorld @@ -12,7 +11,7 @@ protected override bool CanFireNowSub(IIncidentTarget target) return false; } Map map = (Map)target; - return map.mapTemperature.SeasonalTemp > 0f && map.mapTemperature.SeasonalTemp < 15f; + return map.mapTemperature.SeasonalTemp > 0.0 && map.mapTemperature.SeasonalTemp < 15.0; } } } diff --git a/Assembly-CSharp/RimWorld/IncidentWorker_CropBlight.cs b/Assembly-CSharp/RimWorld/IncidentWorker_CropBlight.cs index e68d4d4f2..36ff58506 100644 --- a/Assembly-CSharp/RimWorld/IncidentWorker_CropBlight.cs +++ b/Assembly-CSharp/RimWorld/IncidentWorker_CropBlight.cs @@ -1,5 +1,4 @@ using RimWorld.Planet; -using System; using System.Collections.Generic; using Verse; @@ -17,30 +16,21 @@ public override bool TryExecute(IncidentParms parms) List list = map.listerThings.ThingsInGroup(ThingRequestGroup.Plant); bool flag = false; IntVec3 cell = IntVec3.Invalid; - for (int i = list.Count - 1; i >= 0; i--) + for (int num = list.Count - 1; num >= 0; num--) { - Plant plant = (Plant)list[i]; - if (map.Biome.CommonalityOfPlant(plant.def) == 0f) + Plant plant = (Plant)list[num]; + if (map.Biome.CommonalityOfPlant(plant.def) == 0.0 && !(plant.def.plant.growDays > 15.0) && plant.sown && (plant.LifeStage == PlantLifeStage.Growing || plant.LifeStage == PlantLifeStage.Mature) && Rand.Value < 0.800000011920929) { - if (plant.def.plant.growDays <= 15f) - { - if (plant.sown) - { - if ((plant.LifeStage == PlantLifeStage.Growing || plant.LifeStage == PlantLifeStage.Mature) && Rand.Value < 0.8f) - { - flag = true; - cell = plant.Position; - plant.CropBlighted(); - } - } - } + flag = true; + cell = plant.Position; + plant.CropBlighted(); } } if (!flag) { return false; } - Find.LetterStack.ReceiveLetter("LetterLabelCropBlight".Translate(), "CropBlight".Translate(), LetterDefOf.BadNonUrgent, new GlobalTargetInfo(cell, map, false), null); + Find.LetterStack.ReceiveLetter("LetterLabelCropBlight".Translate(), "CropBlight".Translate(), LetterDefOf.BadNonUrgent, new GlobalTargetInfo(cell, map, false), (string)null); return true; } } diff --git a/Assembly-CSharp/RimWorld/IncidentWorker_Disease.cs b/Assembly-CSharp/RimWorld/IncidentWorker_Disease.cs index 19db48cbe..cb46cd33e 100644 --- a/Assembly-CSharp/RimWorld/IncidentWorker_Disease.cs +++ b/Assembly-CSharp/RimWorld/IncidentWorker_Disease.cs @@ -10,25 +10,30 @@ public class IncidentWorker_Disease : IncidentWorker { private IEnumerable PotentialVictims(Map map) { - return map.mapPawns.FreeColonistsAndPrisoners.Where(delegate(Pawn p) + return map.mapPawns.FreeColonistsAndPrisoners.Where((Func)delegate(Pawn p) { if (p.ParentHolder is Building_CryptosleepCasket) { return false; } - if (!this.def.diseasePartsToAffect.NullOrEmpty()) + if (!base.def.diseasePartsToAffect.NullOrEmpty()) { - for (int i = 0; i < this.def.diseasePartsToAffect.Count; i++) + int num = 0; + while (true) { - if (IncidentWorker_Disease.CanAddHediffToAnyPartOfDef(p, this.def.diseaseIncident, this.def.diseasePartsToAffect[i])) + if (num < base.def.diseasePartsToAffect.Count) { - goto IL_76; + if (!IncidentWorker_Disease.CanAddHediffToAnyPartOfDef(p, base.def.diseaseIncident, base.def.diseasePartsToAffect[num])) + { + num++; + continue; + } + break; } + return false; } - return false; } - IL_76: - return p.health.immunity.DiseaseContractChanceFactor(this.def.diseaseIncident, null) > 0f; + return p.health.immunity.DiseaseContractChanceFactor(base.def.diseaseIncident, null) > 0.0; }); } @@ -48,24 +53,25 @@ private static bool CanAddHediffToAnyPartOfDef(Pawn pawn, HediffDef hediffDef, B protected override bool CanFireNowSub(IIncidentTarget target) { - return this.PotentialVictims((Map)target).Any(); + if (!this.PotentialVictims((Map)target).Any()) + { + return false; + } + return true; } public override bool TryExecute(IncidentParms parms) { Map map = (Map)parms.target; - int num = map.mapPawns.FreeColonistsAndPrisoners.Count(); - IntRange intRange = new IntRange(Mathf.RoundToInt((float)num * this.def.diseaseVictimFractionRange.min), Mathf.RoundToInt((float)num * this.def.diseaseVictimFractionRange.max)); - int num2 = intRange.RandomInRange; - num2 = Mathf.Clamp(num2, 1, this.def.diseaseMaxVictims); - for (int i = 0; i < num2; i++) + int num = map.mapPawns.FreeColonistsAndPrisoners.Count(); + int randomInRange = new IntRange(Mathf.RoundToInt((float)num * base.def.diseaseVictimFractionRange.min), Mathf.RoundToInt((float)num * base.def.diseaseVictimFractionRange.max)).RandomInRange; + randomInRange = Mathf.Clamp(randomInRange, 1, base.def.diseaseMaxVictims); + int num2 = 0; + while (num2 < randomInRange && this.PotentialVictims(map).Any()) { - if (!this.PotentialVictims(map).Any()) - { - break; - } - Pawn pawn = this.PotentialVictims(map).RandomElementByWeight((Pawn x) => x.health.immunity.DiseaseContractChanceFactor(this.def.diseaseIncident, null)); - HediffGiveUtility.TryApply(pawn, this.def.diseaseIncident, this.def.diseasePartsToAffect, false, 1, null); + Pawn pawn = this.PotentialVictims(map).RandomElementByWeight((Func)((Pawn x) => x.health.immunity.DiseaseContractChanceFactor(base.def.diseaseIncident, null))); + HediffGiveUtility.TryApply(pawn, base.def.diseaseIncident, base.def.diseasePartsToAffect, false, 1, null); + num2++; } return true; } diff --git a/Assembly-CSharp/RimWorld/IncidentWorker_FarmAnimalsWanderIn.cs b/Assembly-CSharp/RimWorld/IncidentWorker_FarmAnimalsWanderIn.cs index bb18d7eaa..9eb9c3b7a 100644 --- a/Assembly-CSharp/RimWorld/IncidentWorker_FarmAnimalsWanderIn.cs +++ b/Assembly-CSharp/RimWorld/IncidentWorker_FarmAnimalsWanderIn.cs @@ -14,33 +14,27 @@ public class IncidentWorker_FarmAnimalsWanderIn : IncidentWorker public override bool TryExecute(IncidentParms parms) { Map map = (Map)parms.target; - IntVec3 intVec; - if (!RCellFinder.TryFindRandomPawnEntryCell(out intVec, map, CellFinder.EdgeRoadChance_Animal, null)) + IntVec3 intVec = default(IntVec3); + if (!RCellFinder.TryFindRandomPawnEntryCell(out intVec, map, CellFinder.EdgeRoadChance_Animal, (Predicate)null)) { return false; } - PawnKindDef pawnKindDef; + PawnKindDef pawnKindDef = default(PawnKindDef); if (!(from x in DefDatabase.AllDefs - where x.RaceProps.Animal && x.RaceProps.wildness < 0.35f && map.mapTemperature.SeasonAndOutdoorTemperatureAcceptableFor(x.race) - select x).TryRandomElementByWeight((PawnKindDef k) => 0.420000017f - k.RaceProps.wildness, out pawnKindDef)) + where x.RaceProps.Animal && x.RaceProps.wildness < 0.34999999403953552 && map.mapTemperature.SeasonAndOutdoorTemperatureAcceptableFor(x.race) + select x).TryRandomElementByWeight((Func)((PawnKindDef k) => (float)(0.42000001668930054 - k.RaceProps.wildness)), out pawnKindDef)) { return false; } - int num = Mathf.Clamp(GenMath.RoundRandom(2.5f / pawnKindDef.RaceProps.baseBodySize), 2, 10); - for (int i = 0; i < num; i++) + int num = Mathf.Clamp(GenMath.RoundRandom((float)(2.5 / pawnKindDef.RaceProps.baseBodySize)), 2, 10); + for (int num2 = 0; num2 < num; num2++) { IntVec3 loc = CellFinder.RandomClosewalkCellNear(intVec, map, 12, null); Pawn pawn = PawnGenerator.GeneratePawn(pawnKindDef, null); GenSpawn.Spawn(pawn, loc, map, Rot4.Random, false); pawn.SetFaction(Faction.OfPlayer, null); } - Find.LetterStack.ReceiveLetter("LetterLabelFarmAnimalsWanderIn".Translate(new object[] - { - pawnKindDef.label - }).CapitalizeFirst(), "LetterFarmAnimalsWanderIn".Translate(new object[] - { - pawnKindDef.label - }), LetterDefOf.Good, new TargetInfo(intVec, map, false), null); + Find.LetterStack.ReceiveLetter("LetterLabelFarmAnimalsWanderIn".Translate(pawnKindDef.label).CapitalizeFirst(), "LetterFarmAnimalsWanderIn".Translate(pawnKindDef.label), LetterDefOf.Good, new TargetInfo(intVec, map, false), (string)null); return true; } } diff --git a/Assembly-CSharp/RimWorld/IncidentWorker_Flashstorm.cs b/Assembly-CSharp/RimWorld/IncidentWorker_Flashstorm.cs index 371684a25..43ef3ed92 100644 --- a/Assembly-CSharp/RimWorld/IncidentWorker_Flashstorm.cs +++ b/Assembly-CSharp/RimWorld/IncidentWorker_Flashstorm.cs @@ -1,4 +1,3 @@ -using System; using UnityEngine; using Verse; @@ -15,11 +14,11 @@ protected override bool CanFireNowSub(IIncidentTarget target) public override bool TryExecute(IncidentParms parms) { Map map = (Map)parms.target; - int duration = Mathf.RoundToInt(this.def.durationDays.RandomInRange * 60000f); + int duration = Mathf.RoundToInt((float)(base.def.durationDays.RandomInRange * 60000.0)); GameCondition_Flashstorm gameCondition_Flashstorm = (GameCondition_Flashstorm)GameConditionMaker.MakeCondition(GameConditionDefOf.Flashstorm, duration, 0); map.gameConditionManager.RegisterCondition(gameCondition_Flashstorm); - base.SendStandardLetter(new TargetInfo(gameCondition_Flashstorm.centerLocation.ToIntVec3, map, false), new string[0]); - if (map.weatherManager.curWeather.rainRate > 0.1f) + base.SendStandardLetter(new TargetInfo(gameCondition_Flashstorm.centerLocation.ToIntVec3, map, false)); + if (map.weatherManager.curWeather.rainRate > 0.10000000149011612) { map.weatherDecider.StartNextWeather(); } diff --git a/Assembly-CSharp/RimWorld/IncidentWorker_HeatWave.cs b/Assembly-CSharp/RimWorld/IncidentWorker_HeatWave.cs index d97593850..a41452eda 100644 --- a/Assembly-CSharp/RimWorld/IncidentWorker_HeatWave.cs +++ b/Assembly-CSharp/RimWorld/IncidentWorker_HeatWave.cs @@ -1,4 +1,3 @@ -using System; using Verse; namespace RimWorld @@ -12,7 +11,7 @@ protected override bool CanFireNowSub(IIncidentTarget target) return false; } Map map = (Map)target; - return map.mapTemperature.SeasonalTemp >= 20f; + return map.mapTemperature.SeasonalTemp >= 20.0; } } } diff --git a/Assembly-CSharp/RimWorld/IncidentWorker_Infestation.cs b/Assembly-CSharp/RimWorld/IncidentWorker_Infestation.cs index 5e2259bb6..284458e05 100644 --- a/Assembly-CSharp/RimWorld/IncidentWorker_Infestation.cs +++ b/Assembly-CSharp/RimWorld/IncidentWorker_Infestation.cs @@ -11,7 +11,7 @@ public class IncidentWorker_Infestation : IncidentWorker protected override bool CanFireNowSub(IIncidentTarget target) { Map map = (Map)target; - IntVec3 intVec; + IntVec3 intVec = default(IntVec3); return base.CanFireNowSub(target) && HivesUtility.TotalSpawnedHivesCount(map) < 30 && InfestationCellFinder.TryFindCell(out intVec, map); } @@ -19,20 +19,20 @@ public override bool TryExecute(IncidentParms parms) { Map map = (Map)parms.target; Hive t = null; - int num; - for (int i = Mathf.Max(GenMath.RoundRandom(parms.points / 400f), 1); i > 0; i -= num) + int num2; + for (int num = Mathf.Max(GenMath.RoundRandom((float)(parms.points / 400.0)), 1); num > 0; num -= num2) { - num = Mathf.Min(3, i); - t = this.SpawnHiveCluster(num, map); + num2 = Mathf.Min(3, num); + t = this.SpawnHiveCluster(num2, map); } - base.SendStandardLetter(t, new string[0]); + base.SendStandardLetter((Thing)t); Find.TickManager.slower.SignalForceNormalSpeedShort(); return true; } private Hive SpawnHiveCluster(int hiveCount, Map map) { - IntVec3 loc; + IntVec3 loc = default(IntVec3); if (!InfestationCellFinder.TryFindCell(out loc, map)) { return null; @@ -42,7 +42,7 @@ private Hive SpawnHiveCluster(int hiveCount, Map map) IncidentWorker_Infestation.SpawnInsectJellyInstantly(hive); for (int i = 0; i < hiveCount - 1; i++) { - Hive hive2; + Hive hive2 = default(Hive); if (hive.GetComp().TrySpawnChildHive(false, out hive2)) { IncidentWorker_Infestation.SpawnInsectJellyInstantly(hive2); @@ -54,7 +54,7 @@ private Hive SpawnHiveCluster(int hiveCount, Map map) private static void SpawnInsectJellyInstantly(Hive hive) { - CompSpawner compSpawner = (CompSpawner)hive.AllComps.Find(delegate(ThingComp x) + CompSpawner compSpawner = (CompSpawner)hive.AllComps.Find((Predicate)delegate(ThingComp x) { CompSpawner compSpawner2 = x as CompSpawner; return compSpawner2 != null && compSpawner2.PropsSpawner.thingToSpawn == ThingDefOf.InsectJelly; diff --git a/Assembly-CSharp/RimWorld/IncidentWorker_JourneyOffer.cs b/Assembly-CSharp/RimWorld/IncidentWorker_JourneyOffer.cs index 7a7341449..f8ddac1c6 100644 --- a/Assembly-CSharp/RimWorld/IncidentWorker_JourneyOffer.cs +++ b/Assembly-CSharp/RimWorld/IncidentWorker_JourneyOffer.cs @@ -16,18 +16,18 @@ public class IncidentWorker_JourneyOffer : IncidentWorker protected override bool CanFireNowSub(IIncidentTarget target) { this.FindPossibleRootTiles(); - return this.possibleRootTiles.Any(); + return this.possibleRootTiles.Any(); } public override bool TryExecute(IncidentParms parms) { this.FindPossibleRootTiles(); - if (!this.possibleRootTiles.Any()) + if (!this.possibleRootTiles.Any()) { return false; } - int tile; - if (!this.TryFindDestinationTile(this.possibleRootTiles.RandomElement(), out tile)) + int tile = default(int); + if (!this.TryFindDestinationTile(this.possibleRootTiles.RandomElement(), out tile)) { return false; } @@ -36,7 +36,7 @@ public override bool TryExecute(IncidentParms parms) Find.WorldObjects.Add(journeyDestination); DiaNode diaNode = new DiaNode("JourneyOffer".Translate()); DiaOption diaOption = new DiaOption("JumpToLocation".Translate()); - diaOption.action = delegate + diaOption.action = (Action)delegate { CameraJumper.TryJumpAndSelect(journeyDestination); }; @@ -45,7 +45,7 @@ public override bool TryExecute(IncidentParms parms) DiaOption diaOption2 = new DiaOption("OK".Translate()); diaOption2.resolveTree = true; diaNode.options.Add(diaOption2); - Find.WindowStack.Add(new Dialog_NodeTree(diaNode, true, true, null)); + Find.WindowStack.Add(new Dialog_NodeTree(diaNode, true, true, (string)null)); return true; } @@ -53,20 +53,19 @@ private void FindPossibleRootTiles() { this.possibleRootTiles.Clear(); List maps = Find.Maps; + int num = default(int); for (int i = 0; i < maps.Count; i++) { - int num; if (maps[i].IsPlayerHome && this.TryFindDestinationTileActual(maps[i].Tile, 200, out num)) { this.possibleRootTiles.Add(maps[i].Tile); } } - if (!this.possibleRootTiles.Any()) + if (!this.possibleRootTiles.Any()) { List caravans = Find.WorldObjects.Caravans; for (int j = 0; j < caravans.Count; j++) { - int num; if (caravans[j].IsPlayerControlled && this.TryFindDestinationTileActual(caravans[j].Tile, 200, out num)) { this.possibleRootTiles.Add(caravans[j].Tile); @@ -89,7 +88,7 @@ private bool TryFindDestinationTile(int rootTile, out int tile) { return true; } - if ((float)num <= 200.001f) + if ((float)num <= 200.00100708007812) { return false; } @@ -100,7 +99,7 @@ private bool TryFindDestinationTile(int rootTile, out int tile) private bool TryFindDestinationTileActual(int rootTile, int minDist, out int tile) { - return TileFinder.TryFindPassableTileWithTraversalDistance(rootTile, minDist, 800, out tile, (int x) => !Find.WorldObjects.AnyWorldObjectAt(x), true); + return TileFinder.TryFindPassableTileWithTraversalDistance(rootTile, minDist, 800, out tile, (Predicate)((int x) => !Find.WorldObjects.AnyWorldObjectAt(x)), true); } } } diff --git a/Assembly-CSharp/RimWorld/IncidentWorker_MakeGameCondition.cs b/Assembly-CSharp/RimWorld/IncidentWorker_MakeGameCondition.cs index 3ed5e44ef..cc6cfd178 100644 --- a/Assembly-CSharp/RimWorld/IncidentWorker_MakeGameCondition.cs +++ b/Assembly-CSharp/RimWorld/IncidentWorker_MakeGameCondition.cs @@ -1,4 +1,3 @@ -using System; using System.Collections.Generic; using UnityEngine; using Verse; @@ -15,14 +14,14 @@ protected override bool CanFireNowSub(IIncidentTarget target) Log.ErrorOnce(string.Format("Couldn't find condition manager for incident target {0}", target), 70849667); return false; } - if (gameConditionManager.ConditionIsActive(this.def.gameCondition)) + if (gameConditionManager.ConditionIsActive(base.def.gameCondition)) { return false; } List activeConditions = gameConditionManager.ActiveConditions; for (int i = 0; i < activeConditions.Count; i++) { - if (!this.def.gameCondition.CanCoexistWith(activeConditions[i].def)) + if (!base.def.gameCondition.CanCoexistWith(activeConditions[i].def)) { return false; } @@ -33,8 +32,8 @@ protected override bool CanFireNowSub(IIncidentTarget target) public override bool TryExecute(IncidentParms parms) { GameConditionManager gameConditionManager = parms.target.GameConditionManager; - int duration = Mathf.RoundToInt(this.def.durationDays.RandomInRange * 60000f); - GameCondition cond = GameConditionMaker.MakeCondition(this.def.gameCondition, duration, 0); + int duration = Mathf.RoundToInt((float)(base.def.durationDays.RandomInRange * 60000.0)); + GameCondition cond = GameConditionMaker.MakeCondition(base.def.gameCondition, duration, 0); gameConditionManager.RegisterCondition(cond); base.SendStandardLetter(); return true; diff --git a/Assembly-CSharp/RimWorld/IncidentWorker_ManhunterPack.cs b/Assembly-CSharp/RimWorld/IncidentWorker_ManhunterPack.cs index aadbfb5f0..96497cde3 100644 --- a/Assembly-CSharp/RimWorld/IncidentWorker_ManhunterPack.cs +++ b/Assembly-CSharp/RimWorld/IncidentWorker_ManhunterPack.cs @@ -15,30 +15,27 @@ public class IncidentWorker_ManhunterPack : IncidentWorker public override bool TryExecute(IncidentParms parms) { Map map = (Map)parms.target; - PawnKindDef pawnKindDef; + PawnKindDef pawnKindDef = default(PawnKindDef); if (!ManhunterPackIncidentUtility.TryFindManhunterAnimalKind(parms.points, map.Tile, out pawnKindDef)) { return false; } - IntVec3 intVec; - if (!RCellFinder.TryFindRandomPawnEntryCell(out intVec, map, CellFinder.EdgeRoadChance_Animal, null)) + IntVec3 intVec = default(IntVec3); + if (!RCellFinder.TryFindRandomPawnEntryCell(out intVec, map, CellFinder.EdgeRoadChance_Animal, (Predicate)null)) { return false; } - List list = ManhunterPackIncidentUtility.GenerateAnimals(pawnKindDef, map.Tile, parms.points * 1.4f); + List list = ManhunterPackIncidentUtility.GenerateAnimals(pawnKindDef, map.Tile, (float)(parms.points * 1.3999999761581421)); Rot4 rot = Rot4.FromAngleFlat((map.Center - intVec).AngleFlat); for (int i = 0; i < list.Count; i++) { Pawn pawn = list[i]; IntVec3 loc = CellFinder.RandomClosewalkCellNear(intVec, map, 10, null); GenSpawn.Spawn(pawn, loc, map, rot, false); - pawn.mindState.mentalStateHandler.TryStartMentalState(MentalStateDefOf.ManhunterPermanent, null, false, false, null); + pawn.mindState.mentalStateHandler.TryStartMentalState(MentalStateDefOf.ManhunterPermanent, (string)null, false, false, null); pawn.mindState.exitMapAfterTick = Find.TickManager.TicksGame + Rand.Range(60000, 135000); } - Find.LetterStack.ReceiveLetter("LetterLabelManhunterPackArrived".Translate(), "ManhunterPackArrived".Translate(new object[] - { - pawnKindDef.label - }), LetterDefOf.BadUrgent, list[0], null); + Find.LetterStack.ReceiveLetter("LetterLabelManhunterPackArrived".Translate(), "ManhunterPackArrived".Translate(pawnKindDef.label), LetterDefOf.BadUrgent, (Thing)list[0], (string)null); Find.TickManager.slower.SignalForceNormalSpeedShort(); LessonAutoActivator.TeachOpportunity(ConceptDefOf.ForbiddingDoors, OpportunityType.Critical); LessonAutoActivator.TeachOpportunity(ConceptDefOf.AllowedAreas, OpportunityType.Important); diff --git a/Assembly-CSharp/RimWorld/IncidentWorker_NeutralGroup.cs b/Assembly-CSharp/RimWorld/IncidentWorker_NeutralGroup.cs index 20923c8fb..fdc41e275 100644 --- a/Assembly-CSharp/RimWorld/IncidentWorker_NeutralGroup.cs +++ b/Assembly-CSharp/RimWorld/IncidentWorker_NeutralGroup.cs @@ -33,19 +33,27 @@ protected bool TryResolveParms(IncidentParms parms) protected virtual bool TryResolveParmsGeneral(IncidentParms parms) { Map map = (Map)parms.target; - return (parms.spawnCenter.IsValid || RCellFinder.TryFindRandomPawnEntryCell(out parms.spawnCenter, map, CellFinder.EdgeRoadChance_Neutral, null)) && (parms.faction != null || base.CandidateFactions(map, false).TryRandomElement(out parms.faction) || base.CandidateFactions(map, true).TryRandomElement(out parms.faction)); + if (!parms.spawnCenter.IsValid && !RCellFinder.TryFindRandomPawnEntryCell(out parms.spawnCenter, map, CellFinder.EdgeRoadChance_Neutral, (Predicate)null)) + { + return false; + } + if (parms.faction == null && !base.CandidateFactions(map, false).TryRandomElement(out parms.faction) && !base.CandidateFactions(map, true).TryRandomElement(out parms.faction)) + { + return false; + } + return true; } protected virtual void ResolveParmsPoints(IncidentParms parms) { - if (parms.points < 0f) + if (parms.points < 0.0) { float value = Rand.Value; - if (value < 0.4f) + if (value < 0.40000000596046448) { parms.points = (float)Rand.Range(40, 140); } - else if (value < 0.8f) + else if (value < 0.800000011920929) { parms.points = (float)Rand.Range(140, 200); } @@ -61,13 +69,22 @@ protected List SpawnPawns(IncidentParms parms) { Map map = (Map)parms.target; PawnGroupMakerParms defaultPawnGroupMakerParms = IncidentParmsUtility.GetDefaultPawnGroupMakerParms(parms); - List list = PawnGroupMakerUtility.GeneratePawns(this.PawnGroupKindDef, defaultPawnGroupMakerParms, false).ToList(); - foreach (Pawn current in list) + List list = PawnGroupMakerUtility.GeneratePawns(this.PawnGroupKindDef, defaultPawnGroupMakerParms, false).ToList(); + List.Enumerator enumerator = list.GetEnumerator(); + try + { + while (enumerator.MoveNext()) + { + Pawn current = enumerator.Current; + IntVec3 loc = CellFinder.RandomClosewalkCellNear(parms.spawnCenter, map, 5, null); + GenSpawn.Spawn(current, loc, map); + } + return list; + } + finally { - IntVec3 loc = CellFinder.RandomClosewalkCellNear(parms.spawnCenter, map, 5, null); - GenSpawn.Spawn(current, loc, map); + ((IDisposable)(object)enumerator).Dispose(); } - return list; } } } diff --git a/Assembly-CSharp/RimWorld/IncidentWorker_OrbitalTraderArrival.cs b/Assembly-CSharp/RimWorld/IncidentWorker_OrbitalTraderArrival.cs index 07b111c1e..ab6f91ee6 100644 --- a/Assembly-CSharp/RimWorld/IncidentWorker_OrbitalTraderArrival.cs +++ b/Assembly-CSharp/RimWorld/IncidentWorker_OrbitalTraderArrival.cs @@ -13,19 +13,15 @@ public override bool TryExecute(IncidentParms parms) { return false; } - TraderKindDef def; + TraderKindDef def = default(TraderKindDef); if ((from x in DefDatabase.AllDefs where x.orbital - select x).TryRandomElementByWeight((TraderKindDef traderDef) => traderDef.commonality, out def)) + select x).TryRandomElementByWeight((Func)((TraderKindDef traderDef) => traderDef.commonality), out def)) { TradeShip tradeShip = new TradeShip(def); - if (map.listerBuildings.allBuildingsColonist.Any((Building b) => b.def.IsCommsConsole && b.GetComp().PowerOn)) + if (map.listerBuildings.allBuildingsColonist.Any((Predicate)((Building b) => b.def.IsCommsConsole && b.GetComp().PowerOn))) { - Find.LetterStack.ReceiveLetter(tradeShip.def.LabelCap, "TraderArrival".Translate(new object[] - { - tradeShip.name, - tradeShip.def.label - }), LetterDefOf.Good, null); + Find.LetterStack.ReceiveLetter(tradeShip.def.LabelCap, "TraderArrival".Translate(tradeShip.name, tradeShip.def.label), LetterDefOf.Good, (string)null); } map.passingShipManager.AddShip(tradeShip); tradeShip.GenerateThings(); diff --git a/Assembly-CSharp/RimWorld/IncidentWorker_PawnsArrive.cs b/Assembly-CSharp/RimWorld/IncidentWorker_PawnsArrive.cs index 31ecaee7a..b18347456 100644 --- a/Assembly-CSharp/RimWorld/IncidentWorker_PawnsArrive.cs +++ b/Assembly-CSharp/RimWorld/IncidentWorker_PawnsArrive.cs @@ -17,26 +17,38 @@ where this.FactionCanBeGroupSource(f, map, desperate) protected virtual bool FactionCanBeGroupSource(Faction f, Map map, bool desperate = false) { - return !f.IsPlayer && !f.defeated && (desperate || (f.def.allowedArrivalTemperatureRange.Includes(map.mapTemperature.OutdoorTemp) && f.def.allowedArrivalTemperatureRange.Includes(map.mapTemperature.SeasonalTemp))); + if (f.IsPlayer) + { + return false; + } + if (f.defeated) + { + return false; + } + if (!desperate && (!f.def.allowedArrivalTemperatureRange.Includes(map.mapTemperature.OutdoorTemp) || !f.def.allowedArrivalTemperatureRange.Includes(map.mapTemperature.SeasonalTemp))) + { + return false; + } + return true; } protected override bool CanFireNowSub(IIncidentTarget target) { Map map = (Map)target; - return this.CandidateFactions(map, false).Any(); + return this.CandidateFactions(map, false).Any(); } public string DebugListingOfGroupSources() { StringBuilder stringBuilder = new StringBuilder(); - foreach (Faction current in Find.FactionManager.AllFactions) + foreach (Faction allFaction in Find.FactionManager.AllFactions) { - stringBuilder.Append(current.Name); - if (this.FactionCanBeGroupSource(current, Find.VisibleMap, false)) + stringBuilder.Append(allFaction.Name); + if (this.FactionCanBeGroupSource(allFaction, Find.VisibleMap, false)) { stringBuilder.Append(" YES"); } - else if (this.FactionCanBeGroupSource(current, Find.VisibleMap, true)) + else if (this.FactionCanBeGroupSource(allFaction, Find.VisibleMap, true)) { stringBuilder.Append(" YES-DESPERATE"); } diff --git a/Assembly-CSharp/RimWorld/IncidentWorker_PoisonShipPartCrash.cs b/Assembly-CSharp/RimWorld/IncidentWorker_PoisonShipPartCrash.cs index a32c1f656..764f72ac8 100644 --- a/Assembly-CSharp/RimWorld/IncidentWorker_PoisonShipPartCrash.cs +++ b/Assembly-CSharp/RimWorld/IncidentWorker_PoisonShipPartCrash.cs @@ -1,4 +1,3 @@ -using System; using Verse; namespace RimWorld diff --git a/Assembly-CSharp/RimWorld/IncidentWorker_PsychicDrone.cs b/Assembly-CSharp/RimWorld/IncidentWorker_PsychicDrone.cs index 8ba82cecf..5477a3e8c 100644 --- a/Assembly-CSharp/RimWorld/IncidentWorker_PsychicDrone.cs +++ b/Assembly-CSharp/RimWorld/IncidentWorker_PsychicDrone.cs @@ -10,11 +10,8 @@ protected override void DoConditionAndLetter(Map map, int duration, Gender gende GameCondition_PsychicEmanation gameCondition_PsychicEmanation = (GameCondition_PsychicEmanation)GameConditionMaker.MakeCondition(GameConditionDefOf.PsychicDrone, duration, 0); gameCondition_PsychicEmanation.gender = gender; map.gameConditionManager.RegisterCondition(gameCondition_PsychicEmanation); - string text = "LetterIncidentPsychicDrone".Translate(new object[] - { - gender.ToString().Translate().ToLower() - }); - Find.LetterStack.ReceiveLetter("LetterLabelPsychicDrone".Translate(), text, LetterDefOf.BadNonUrgent, null); + string text = "LetterIncidentPsychicDrone".Translate(((Enum)(object)gender).ToString().Translate().ToLower()); + Find.LetterStack.ReceiveLetter("LetterLabelPsychicDrone".Translate(), text, LetterDefOf.BadNonUrgent, (string)null); } } } diff --git a/Assembly-CSharp/RimWorld/IncidentWorker_PsychicEmanation.cs b/Assembly-CSharp/RimWorld/IncidentWorker_PsychicEmanation.cs index 228edf3ad..c45913074 100644 --- a/Assembly-CSharp/RimWorld/IncidentWorker_PsychicEmanation.cs +++ b/Assembly-CSharp/RimWorld/IncidentWorker_PsychicEmanation.cs @@ -1,4 +1,3 @@ -using System; using UnityEngine; using Verse; using Verse.Sound; @@ -10,13 +9,25 @@ public abstract class IncidentWorker_PsychicEmanation : IncidentWorker protected override bool CanFireNowSub(IIncidentTarget target) { Map map = (Map)target; - return !map.gameConditionManager.ConditionIsActive(GameConditionDefOf.PsychicDrone) && !map.gameConditionManager.ConditionIsActive(GameConditionDefOf.PsychicSoothe) && map.listerThings.ThingsOfDef(ThingDefOf.CrashedPsychicEmanatorShipPart).Count <= 0 && map.mapPawns.FreeColonistsCount != 0; + if (!map.gameConditionManager.ConditionIsActive(GameConditionDefOf.PsychicDrone) && !map.gameConditionManager.ConditionIsActive(GameConditionDefOf.PsychicSoothe)) + { + if (map.listerThings.ThingsOfDef(ThingDefOf.CrashedPsychicEmanatorShipPart).Count > 0) + { + return false; + } + if (map.mapPawns.FreeColonistsCount == 0) + { + return false; + } + return true; + } + return false; } public override bool TryExecute(IncidentParms parms) { Map map = (Map)parms.target; - this.DoConditionAndLetter(map, Mathf.RoundToInt(this.def.durationDays.RandomInRange * 60000f), map.mapPawns.FreeColonists.RandomElement().gender); + this.DoConditionAndLetter(map, Mathf.RoundToInt((float)(base.def.durationDays.RandomInRange * 60000.0)), map.mapPawns.FreeColonists.RandomElement().gender); SoundDefOf.PsychicPulseGlobal.PlayOneShotOnCamera(map); return true; } diff --git a/Assembly-CSharp/RimWorld/IncidentWorker_PsychicEmanatorShipPartCrash.cs b/Assembly-CSharp/RimWorld/IncidentWorker_PsychicEmanatorShipPartCrash.cs index 5094310d1..76e609fd4 100644 --- a/Assembly-CSharp/RimWorld/IncidentWorker_PsychicEmanatorShipPartCrash.cs +++ b/Assembly-CSharp/RimWorld/IncidentWorker_PsychicEmanatorShipPartCrash.cs @@ -1,4 +1,3 @@ -using System; using Verse; namespace RimWorld @@ -8,7 +7,11 @@ internal class IncidentWorker_PsychicEmanatorShipPartCrash : IncidentWorker_Ship protected override bool CanFireNowSub(IIncidentTarget target) { Map map = (Map)target; - return !map.gameConditionManager.ConditionIsActive(GameConditionDefOf.PsychicDrone) && base.CanFireNowSub(target); + if (map.gameConditionManager.ConditionIsActive(GameConditionDefOf.PsychicDrone)) + { + return false; + } + return base.CanFireNowSub(target); } } } diff --git a/Assembly-CSharp/RimWorld/IncidentWorker_PsychicSoothe.cs b/Assembly-CSharp/RimWorld/IncidentWorker_PsychicSoothe.cs index 546477418..4eb9d62f6 100644 --- a/Assembly-CSharp/RimWorld/IncidentWorker_PsychicSoothe.cs +++ b/Assembly-CSharp/RimWorld/IncidentWorker_PsychicSoothe.cs @@ -10,11 +10,8 @@ protected override void DoConditionAndLetter(Map map, int duration, Gender gende GameCondition_PsychicEmanation gameCondition_PsychicEmanation = (GameCondition_PsychicEmanation)GameConditionMaker.MakeCondition(GameConditionDefOf.PsychicSoothe, duration, 0); gameCondition_PsychicEmanation.gender = gender; map.gameConditionManager.RegisterCondition(gameCondition_PsychicEmanation); - string text = "LetterIncidentPsychicSoothe".Translate(new object[] - { - gender.ToString().Translate().ToLower() - }); - Find.LetterStack.ReceiveLetter("LetterLabelPsychicSoothe".Translate(), text, LetterDefOf.Good, null); + string text = "LetterIncidentPsychicSoothe".Translate(((Enum)(object)gender).ToString().Translate().ToLower()); + Find.LetterStack.ReceiveLetter("LetterLabelPsychicSoothe".Translate(), text, LetterDefOf.Good, (string)null); } } } diff --git a/Assembly-CSharp/RimWorld/IncidentWorker_QuestBanditCamp.cs b/Assembly-CSharp/RimWorld/IncidentWorker_QuestBanditCamp.cs index 4bfee940d..67fd01803 100644 --- a/Assembly-CSharp/RimWorld/IncidentWorker_QuestBanditCamp.cs +++ b/Assembly-CSharp/RimWorld/IncidentWorker_QuestBanditCamp.cs @@ -14,21 +14,21 @@ public class IncidentWorker_QuestBanditCamp : IncidentWorker protected override bool CanFireNowSub(IIncidentTarget target) { - Faction faction; - Faction faction2; - int num; + Faction faction = default(Faction); + Faction faction2 = default(Faction); + int num = default(int); return base.CanFireNowSub(target) && this.TryFindFactions(out faction, out faction2) && TileFinder.TryFindNewSiteTile(out num); } public override bool TryExecute(IncidentParms parms) { - Faction faction; - Faction faction2; + Faction faction = default(Faction); + Faction faction2 = default(Faction); if (!this.TryFindFactions(out faction, out faction2)) { return false; } - int tile; + int tile = default(int); if (!TileFinder.TryFindNewSiteTile(out tile)) { return false; @@ -39,24 +39,20 @@ public override bool TryExecute(IncidentParms parms) site.core = SiteCoreDefOf.Nothing; site.parts.Add(SitePartDefOf.Outpost); List list = this.GenerateRewards(faction); - site.GetComponent().StartQuest(faction, 8f, list); + ((WorldObject)site).GetComponent().StartQuest(faction, 8f, list); Find.WorldObjects.Add(site); - base.SendStandardLetter(site, new string[] - { - faction.leader.LabelShort, - faction.def.leaderTitle, - faction.Name, - list[0].LabelCap - }); + base.SendStandardLetter((WorldObject)site, faction.leader.LabelShort, faction.def.leaderTitle, faction.Name, list[0].LabelCap); return true; } private List GenerateRewards(Faction alliedFaction) { - ItemCollectionGeneratorParams parms = default(ItemCollectionGeneratorParams); - parms.count = 1; - parms.totalMarketValue = (float)IncidentWorker_QuestBanditCamp.RewardMarketValueRange.RandomInRange; - parms.techLevel = alliedFaction.def.techLevel; + ItemCollectionGeneratorParams parms = new ItemCollectionGeneratorParams + { + count = 1, + totalMarketValue = (float)IncidentWorker_QuestBanditCamp.RewardMarketValueRange.RandomInRange, + techLevel = alliedFaction.def.techLevel + }; return ItemCollectionGeneratorDefOf.BanditCampQuestRewards.Worker.Generate(parms); } @@ -64,7 +60,7 @@ private bool TryFindFactions(out Faction alliedFaction, out Faction enemyFaction { if ((from x in Find.FactionManager.AllFactions where !x.def.hidden && !x.defeated && !x.IsPlayer && !x.HostileTo(Faction.OfPlayer) && this.CommonHumanlikeEnemyFactionExists(Faction.OfPlayer, x) && !this.AnyQuestExistsFrom(x) - select x).TryRandomElement(out alliedFaction)) + select x).TryRandomElement(out alliedFaction)) { enemyFaction = this.CommonHumanlikeEnemyFaction(Faction.OfPlayer, alliedFaction); return true; @@ -79,7 +75,7 @@ private bool AnyQuestExistsFrom(Faction faction) List sites = Find.WorldObjects.Sites; for (int i = 0; i < sites.Count; i++) { - DefeatAllEnemiesQuestComp component = sites[i].GetComponent(); + DefeatAllEnemiesQuestComp component = ((WorldObject)sites[i]).GetComponent(); if (component != null && component.Active && component.requestingFaction == faction) { return true; @@ -95,10 +91,10 @@ private bool CommonHumanlikeEnemyFactionExists(Faction f1, Faction f2) private Faction CommonHumanlikeEnemyFaction(Faction f1, Faction f2) { - Faction result; + Faction result = default(Faction); if ((from x in Find.FactionManager.AllFactions where x != f1 && x != f2 && !x.def.hidden && x.def.humanlikeFaction && !x.defeated && x.HostileTo(f1) && x.HostileTo(f2) - select x).TryRandomElement(out result)) + select x).TryRandomElement(out result)) { return result; } diff --git a/Assembly-CSharp/RimWorld/IncidentWorker_QuestItemStash.cs b/Assembly-CSharp/RimWorld/IncidentWorker_QuestItemStash.cs index 4745e1c74..f5761ccf1 100644 --- a/Assembly-CSharp/RimWorld/IncidentWorker_QuestItemStash.cs +++ b/Assembly-CSharp/RimWorld/IncidentWorker_QuestItemStash.cs @@ -47,25 +47,25 @@ protected override bool CanFireNowSub(IIncidentTarget target) { return false; } - SitePartDef sitePartDef; - if (!SiteMaker.TryFindNewRandomSitePartFor(SiteCoreDefOf.ItemStash, null, this.PossibleSiteParts, null, out sitePartDef, true, null)) + SitePartDef sitePartDef = default(SitePartDef); + if (!SiteMaker.TryFindNewRandomSitePartFor(SiteCoreDefOf.ItemStash, (IEnumerable)null, (IEnumerable)this.PossibleSiteParts, (Faction)null, out sitePartDef, true, (Predicate)null)) { return false; } - IEnumerable arg_41_0; + object obj; if (sitePartDef != null) { - IEnumerable enumerable = Gen.YieldSingle(sitePartDef); - arg_41_0 = enumerable; + IEnumerable enumerable = Gen.YieldSingle(sitePartDef); + obj = enumerable; } else { - arg_41_0 = null; + obj = null; } - IEnumerable parts = arg_41_0; - int num; - Faction faction; - return Find.FactionManager.RandomAlliedFaction(false, false, false) != null && TileFinder.TryFindNewSiteTile(out num) && SiteMaker.TryFindRandomFactionFor(SiteCoreDefOf.ItemStash, parts, out faction, true, null); + IEnumerable parts = (IEnumerable)obj; + int num = default(int); + Faction faction = default(Faction); + return Find.FactionManager.RandomAlliedFaction(false, false, false) != null && TileFinder.TryFindNewSiteTile(out num) && SiteMaker.TryFindRandomFactionFor(SiteCoreDefOf.ItemStash, parts, out faction, true, (Predicate)null); } public override bool TryExecute(IncidentParms parms) @@ -75,29 +75,29 @@ public override bool TryExecute(IncidentParms parms) { return false; } - int tile; + int tile = default(int); if (!TileFinder.TryFindNewSiteTile(out tile)) { return false; } - SitePartDef sitePartDef; - if (!SiteMaker.TryFindNewRandomSitePartFor(SiteCoreDefOf.ItemStash, null, this.PossibleSiteParts, null, out sitePartDef, true, null)) + SitePartDef sitePartDef = default(SitePartDef); + if (!SiteMaker.TryFindNewRandomSitePartFor(SiteCoreDefOf.ItemStash, (IEnumerable)null, (IEnumerable)this.PossibleSiteParts, (Faction)null, out sitePartDef, true, (Predicate)null)) { return false; } - IEnumerable arg_57_0; + object obj; if (sitePartDef != null) { - IEnumerable enumerable = Gen.YieldSingle(sitePartDef); - arg_57_0 = enumerable; + IEnumerable enumerable = Gen.YieldSingle(sitePartDef); + obj = enumerable; } else { - arg_57_0 = null; + obj = null; } - IEnumerable parts = arg_57_0; - Faction siteFaction; - if (!SiteMaker.TryFindRandomFactionFor(SiteCoreDefOf.ItemStash, parts, out siteFaction, true, null)) + IEnumerable parts = (IEnumerable)obj; + Faction siteFaction = default(Faction); + if (!SiteMaker.TryFindRandomFactionFor(SiteCoreDefOf.ItemStash, parts, out siteFaction, true, (Predicate)null)) { return false; } @@ -109,12 +109,8 @@ public override bool TryExecute(IncidentParms parms) { Map map = TradeUtility.PlayerHomeMapWithMostLaunchableSilver(); int randomInRange2 = IncidentWorker_QuestItemStash.FeeRange.RandomInRange; - string text = letterText + "\n\n" + "ItemStashQuestFeeDemand".Translate(new object[] - { - faction.leader.LabelShort, - randomInRange2 - }).CapitalizeFirst(); - ChoiceLetter_ItemStashFeeDemand choiceLetter_ItemStashFeeDemand = (ChoiceLetter_ItemStashFeeDemand)LetterMaker.MakeLetter(this.def.letterLabel, text, LetterDefOf.ItemStashFeeDemand); + string text = letterText + "\n\n" + "ItemStashQuestFeeDemand".Translate(faction.leader.LabelShort, randomInRange2).CapitalizeFirst(); + ChoiceLetter_ItemStashFeeDemand choiceLetter_ItemStashFeeDemand = (ChoiceLetter_ItemStashFeeDemand)LetterMaker.MakeLetter(base.def.letterLabel, text, LetterDefOf.ItemStashFeeDemand); choiceLetter_ItemStashFeeDemand.title = "ItemStashQuestTitle".Translate(); choiceLetter_ItemStashFeeDemand.radioMode = true; choiceLetter_ItemStashFeeDemand.map = map; @@ -126,12 +122,12 @@ public override bool TryExecute(IncidentParms parms) choiceLetter_ItemStashFeeDemand.alliedFaction = faction; choiceLetter_ItemStashFeeDemand.sitePartsKnown = sitePartsKnown; choiceLetter_ItemStashFeeDemand.StartTimeout(60000); - Find.LetterStack.ReceiveLetter(choiceLetter_ItemStashFeeDemand, null); + Find.LetterStack.ReceiveLetter(choiceLetter_ItemStashFeeDemand, (string)null); } else { Site o = IncidentWorker_QuestItemStash.CreateSite(tile, sitePartDef, randomInRange, siteFaction, list, sitePartsKnown); - Find.LetterStack.ReceiveLetter(this.def.letterLabel, letterText, this.def.letterDef, o, null); + Find.LetterStack.ReceiveLetter(base.def.letterLabel, letterText, base.def.letterDef, (WorldObject)o, (string)null); } return true; } @@ -160,7 +156,7 @@ private string GetSitePartInfoKey(SitePartDef sitePart) private List GenerateItems(Faction siteFaction) { this.CalculatePossibleItemCollectionGenerators(siteFaction); - Pair pair = this.possibleItemCollectionGenerators.RandomElement>(); + Pair pair = this.possibleItemCollectionGenerators.RandomElement(); return pair.First.Worker.Generate(pair.Second); } @@ -168,24 +164,30 @@ private void CalculatePossibleItemCollectionGenerators(Faction siteFaction) { TechLevel techLevel = (siteFaction == null) ? TechLevel.Spacer : siteFaction.def.techLevel; this.possibleItemCollectionGenerators.Clear(); - if (Rand.Chance(0.25f) && techLevel >= ThingDefOf.AIPersonaCore.techLevel) + if (Rand.Chance(0.25f) && (int)techLevel >= (int)ThingDefOf.AIPersonaCore.techLevel) { ItemCollectionGeneratorDef aIPersonaCores = ItemCollectionGeneratorDefOf.AIPersonaCores; - ItemCollectionGeneratorParams second = default(ItemCollectionGeneratorParams); - second.count = 1; + ItemCollectionGeneratorParams second = new ItemCollectionGeneratorParams + { + count = 1 + }; this.possibleItemCollectionGenerators.Add(new Pair(aIPersonaCores, second)); } - if (techLevel >= ThingDefOf.Neurotrainer.techLevel) + if ((int)techLevel >= (int)ThingDefOf.Neurotrainer.techLevel) { ItemCollectionGeneratorDef neurotrainers = ItemCollectionGeneratorDefOf.Neurotrainers; - ItemCollectionGeneratorParams second2 = default(ItemCollectionGeneratorParams); - second2.count = IncidentWorker_QuestItemStash.NeurotrainersCountRange.RandomInRange; + ItemCollectionGeneratorParams second2 = new ItemCollectionGeneratorParams + { + count = IncidentWorker_QuestItemStash.NeurotrainersCountRange.RandomInRange + }; this.possibleItemCollectionGenerators.Add(new Pair(neurotrainers, second2)); } - ItemCollectionGeneratorParams second3 = default(ItemCollectionGeneratorParams); - second3.count = IncidentWorker_QuestItemStash.ThingsCountRange.RandomInRange; - second3.totalMarketValue = IncidentWorker_QuestItemStash.TotalMarketValueRange.RandomInRange; - second3.techLevel = techLevel; + ItemCollectionGeneratorParams second3 = new ItemCollectionGeneratorParams + { + count = IncidentWorker_QuestItemStash.ThingsCountRange.RandomInRange, + totalMarketValue = IncidentWorker_QuestItemStash.TotalMarketValueRange.RandomInRange, + techLevel = techLevel + }; this.possibleItemCollectionGenerators.Add(new Pair(ItemCollectionGeneratorDefOf.Weapons, second3)); this.possibleItemCollectionGenerators.Add(new Pair(ItemCollectionGeneratorDefOf.RawResources, second3)); this.possibleItemCollectionGenerators.Add(new Pair(ItemCollectionGeneratorDefOf.Apparel, second3)); @@ -202,38 +204,16 @@ public static Site CreateSite(int tile, SitePartDef sitePart, int days, Faction site.parts.Add(sitePart); } site.SetFaction(siteFaction); - site.GetComponent().StartTimeout(days * 60000); - site.GetComponent().contents.TryAddRange(items, false); + ((WorldObject)site).GetComponent().StartTimeout(days * 60000); + ((WorldObject)site).GetComponent().contents.TryAddRange(items, false); Find.WorldObjects.Add(site); return site; } private string GetLetterText(Faction alliedFaction, List items, int days, SitePartDef sitePart, bool sitePartsKnown) { - string text; - if (sitePartsKnown) - { - text = this.GetSitePartInfoKey(sitePart).Translate(new object[] - { - alliedFaction.leader.LabelShort - }).CapitalizeFirst(); - } - else - { - text = "ItemStashSitePart_Unknown".Translate(new object[] - { - alliedFaction.leader.LabelShort - }).CapitalizeFirst(); - } - return string.Format(this.def.letterText, new object[] - { - alliedFaction.leader.LabelShort, - alliedFaction.def.leaderTitle, - alliedFaction.Name, - GenLabel.ThingsLabel(items).TrimEndNewlines(), - days.ToString(), - text - }).CapitalizeFirst(); + string text = (!sitePartsKnown) ? "ItemStashSitePart_Unknown".Translate(alliedFaction.leader.LabelShort).CapitalizeFirst() : this.GetSitePartInfoKey(sitePart).Translate(alliedFaction.leader.LabelShort).CapitalizeFirst(); + return string.Format(base.def.letterText, alliedFaction.leader.LabelShort, alliedFaction.def.leaderTitle, alliedFaction.Name, GenLabel.ThingsLabel(items).TrimEndNewlines(), days.ToString(), text).CapitalizeFirst(); } private float FeeDemandChance(Faction faction) diff --git a/Assembly-CSharp/RimWorld/IncidentWorker_Raid.cs b/Assembly-CSharp/RimWorld/IncidentWorker_Raid.cs index 3b0f9a62a..86318dbec 100644 --- a/Assembly-CSharp/RimWorld/IncidentWorker_Raid.cs +++ b/Assembly-CSharp/RimWorld/IncidentWorker_Raid.cs @@ -26,30 +26,37 @@ public abstract class IncidentWorker_Raid : IncidentWorker_PawnsArrive protected virtual void ResolveRaidArriveMode(IncidentParms parms) { - if (parms.raidArrivalMode != PawnsArriveMode.Undecided) + if (parms.raidArrivalMode == PawnsArriveMode.Undecided) { - return; - } - if (parms.faction.def.techLevel < TechLevel.Spacer || parms.points < 240f) - { - parms.raidArrivalMode = PawnsArriveMode.EdgeWalkIn; - } - else - { - parms.raidArrivalMode = parms.raidStrategy.arriveModes.RandomElementByWeight(delegate(PawnsArriveMode am) + if ((int)parms.faction.def.techLevel < 5 || parms.points < 240.0) { - switch (am) + parms.raidArrivalMode = PawnsArriveMode.EdgeWalkIn; + } + else + { + parms.raidArrivalMode = parms.raidStrategy.arriveModes.RandomElementByWeight((Func)delegate(PawnsArriveMode am) { - case PawnsArriveMode.EdgeWalkIn: - return 70f; - case PawnsArriveMode.EdgeDrop: - return 20f; - case PawnsArriveMode.CenterDrop: - return 10f; - default: - throw new NotImplementedException(); - } - }); + switch (am) + { + case PawnsArriveMode.EdgeWalkIn: + { + return 70f; + } + case PawnsArriveMode.EdgeDrop: + { + return 20f; + } + case PawnsArriveMode.CenterDrop: + { + return 10f; + } + default: + { + throw new NotImplementedException(); + } + } + }); + } } } @@ -66,7 +73,7 @@ protected virtual bool ResolveRaidSpawnCenter(IncidentParms parms) { parms.raidPodOpenDelay = 520; parms.spawnRotation = Rot4.Random; - if (Rand.Value < 0.4f && map.listerBuildings.ColonistsHaveBuildingWithPowerOn(ThingDefOf.OrbitalTradeBeacon)) + if (Rand.Value < 0.40000000596046448 && map.listerBuildings.ColonistsHaveBuildingWithPowerOn(ThingDefOf.OrbitalTradeBeacon)) { parms.spawnCenter = DropCellFinder.TradeDropSpot(map); } @@ -84,7 +91,7 @@ protected virtual bool ResolveRaidSpawnCenter(IncidentParms parms) } else { - if (!RCellFinder.TryFindRandomPawnEntryCell(out parms.spawnCenter, map, CellFinder.EdgeRoadChance_Hostile, null)) + if (!RCellFinder.TryFindRandomPawnEntryCell(out parms.spawnCenter, map, CellFinder.EdgeRoadChance_Hostile, (Predicate)null)) { return false; } @@ -109,7 +116,7 @@ public override bool TryExecute(IncidentParms parms) } IncidentParmsUtility.AdjustPointsForGroupArrivalParams(parms); PawnGroupMakerParms defaultPawnGroupMakerParms = IncidentParmsUtility.GetDefaultPawnGroupMakerParms(parms); - List list = PawnGroupMakerUtility.GeneratePawns(PawnGroupKindDefOf.Normal, defaultPawnGroupMakerParms, true).ToList(); + List list = PawnGroupMakerUtility.GeneratePawns(PawnGroupKindDefOf.Normal, defaultPawnGroupMakerParms, true).ToList(); if (list.Count == 0) { Log.Error("Got no pawns spawning raid from parms " + parms); @@ -123,19 +130,37 @@ public override bool TryExecute(IncidentParms parms) } else { - foreach (Pawn current in list) + List.Enumerator enumerator = list.GetEnumerator(); + try { - IntVec3 loc = CellFinder.RandomClosewalkCellNear(parms.spawnCenter, map, 8, null); - GenSpawn.Spawn(current, loc, map, parms.spawnRotation, false); - target = current; + while (enumerator.MoveNext()) + { + Pawn current = enumerator.Current; + IntVec3 loc = CellFinder.RandomClosewalkCellNear(parms.spawnCenter, map, 8, null); + GenSpawn.Spawn(current, loc, map, parms.spawnRotation, false); + target = (Thing)current; + } + } + finally + { + ((IDisposable)(object)enumerator).Dispose(); } } StringBuilder stringBuilder = new StringBuilder(); stringBuilder.AppendLine("Points = " + parms.points.ToString("F0")); - foreach (Pawn current2 in list) + List.Enumerator enumerator2 = list.GetEnumerator(); + try { - string str = (current2.equipment == null || current2.equipment.Primary == null) ? "unarmed" : current2.equipment.Primary.LabelCap; - stringBuilder.AppendLine(current2.KindLabel + " - " + str); + while (enumerator2.MoveNext()) + { + Pawn current2 = enumerator2.Current; + string str = (current2.equipment == null || current2.equipment.Primary == null) ? "unarmed" : current2.equipment.Primary.LabelCap; + stringBuilder.AppendLine(current2.KindLabel + " - " + str); + } + } + finally + { + ((IDisposable)(object)enumerator2).Dispose(); } string letterLabel = this.GetLetterLabel(parms); string letterText = this.GetLetterText(parms, list); @@ -143,7 +168,7 @@ public override bool TryExecute(IncidentParms parms) Find.LetterStack.ReceiveLetter(letterLabel, letterText, this.GetLetterDef(), target, stringBuilder.ToString()); if (this.GetLetterDef() == LetterDefOf.BadUrgent) { - TaleRecorder.RecordTale(TaleDefOf.RaidArrived, new object[0]); + TaleRecorder.RecordTale(TaleDefOf.RaidArrived); } Lord lord = LordMaker.MakeNewLord(parms.faction, parms.raidStrategy.Worker.MakeLordJob(parms, map), map, list); AvoidGridMaker.RegenerateAvoidGridsFor(parms.faction, map); @@ -153,7 +178,7 @@ public override bool TryExecute(IncidentParms parms) for (int i = 0; i < list.Count; i++) { Pawn pawn = list[i]; - if (pawn.apparel.WornApparel.Any((Apparel ap) => ap is ShieldBelt)) + if (pawn.apparel.WornApparel.Any((Predicate)((Apparel ap) => ap is ShieldBelt))) { LessonAutoActivator.TeachOpportunity(ConceptDefOf.ShieldBelts, OpportunityType.Critical); break; @@ -162,14 +187,7 @@ public override bool TryExecute(IncidentParms parms) } if (DebugViewSettings.drawStealDebug && parms.faction.HostileTo(Faction.OfPlayer)) { - Log.Message(string.Concat(new object[] - { - "Market value threshold to start stealing: ", - StealAIUtility.StartStealingMarketValueThreshold(lord), - " (colony wealth = ", - map.wealthWatcher.WealthTotal, - ")" - })); + Log.Message("Market value threshold to start stealing: " + StealAIUtility.StartStealingMarketValueThreshold(lord) + " (colony wealth = " + map.wealthWatcher.WealthTotal + ")"); } return true; } diff --git a/Assembly-CSharp/RimWorld/IncidentWorker_RaidEnemy.cs b/Assembly-CSharp/RimWorld/IncidentWorker_RaidEnemy.cs index fddf0168a..ceff29ba6 100644 --- a/Assembly-CSharp/RimWorld/IncidentWorker_RaidEnemy.cs +++ b/Assembly-CSharp/RimWorld/IncidentWorker_RaidEnemy.cs @@ -31,27 +31,24 @@ protected override bool TryResolveRaidFaction(IncidentParms parms) return true; } float maxPoints = parms.points; - if (maxPoints <= 0f) + if (maxPoints <= 0.0) { maxPoints = 999999f; } if (!(from f in Find.FactionManager.AllFactions where this.FactionCanBeGroupSource(f, map, false) && maxPoints >= f.def.MinPointsToGenerateNormalPawnGroup() - select f).TryRandomElementByWeight((Faction f) => f.def.raidCommonality, out parms.faction)) + select f).TryRandomElementByWeight((Func)((Faction f) => f.def.raidCommonality), out parms.faction) && !(from f in Find.FactionManager.AllFactions + where this.FactionCanBeGroupSource(f, map, true) && maxPoints >= f.def.MinPointsToGenerateNormalPawnGroup() + select f).TryRandomElementByWeight((Func)((Faction f) => f.def.raidCommonality), out parms.faction)) { - if (!(from f in Find.FactionManager.AllFactions - where this.FactionCanBeGroupSource(f, map, true) && maxPoints >= f.def.MinPointsToGenerateNormalPawnGroup() - select f).TryRandomElementByWeight((Faction f) => f.def.raidCommonality, out parms.faction)) - { - return false; - } + return false; } return true; } protected override void ResolveRaidPoints(IncidentParms parms) { - if (parms.points <= 0f) + if (parms.points <= 0.0) { Log.Error("RaidEnemy is resolving raid points. They should always be set before initiating the incident."); parms.points = (float)Rand.Range(50, 300); @@ -60,14 +57,13 @@ protected override void ResolveRaidPoints(IncidentParms parms) protected override void ResolveRaidStrategy(IncidentParms parms) { - if (parms.raidStrategy != null) + if (parms.raidStrategy == null) { - return; + Map map = (Map)parms.target; + parms.raidStrategy = (from d in DefDatabase.AllDefs + where d.Worker.CanUseWith(parms) + select d).RandomElementByWeight((Func)((RaidStrategyDef d) => d.Worker.SelectionChance(map))); } - Map map = (Map)parms.target; - parms.raidStrategy = (from d in DefDatabase.AllDefs - where d.Worker.CanUseWith(parms) - select d).RandomElementByWeight((RaidStrategyDef d) => d.Worker.SelectionChance(map)); } protected override string GetLetterLabel(IncidentParms parms) @@ -77,44 +73,34 @@ protected override string GetLetterLabel(IncidentParms parms) protected override string GetLetterText(IncidentParms parms, List pawns) { - string text = null; + string str = (string)null; switch (parms.raidArrivalMode) { case PawnsArriveMode.EdgeWalkIn: - text = "EnemyRaidWalkIn".Translate(new object[] - { - parms.faction.def.pawnsPlural, - parms.faction.Name - }); + { + str = "EnemyRaidWalkIn".Translate(parms.faction.def.pawnsPlural, parms.faction.Name); break; + } case PawnsArriveMode.EdgeDrop: - text = "EnemyRaidEdgeDrop".Translate(new object[] - { - parms.faction.def.pawnsPlural, - parms.faction.Name - }); + { + str = "EnemyRaidEdgeDrop".Translate(parms.faction.def.pawnsPlural, parms.faction.Name); break; + } case PawnsArriveMode.CenterDrop: - text = "EnemyRaidCenterDrop".Translate(new object[] - { - parms.faction.def.pawnsPlural, - parms.faction.Name - }); + { + str = "EnemyRaidCenterDrop".Translate(parms.faction.def.pawnsPlural, parms.faction.Name); break; } - text += "\n\n"; - text += parms.raidStrategy.arrivalTextEnemy; - Pawn pawn = pawns.Find((Pawn x) => x.Faction.leader == x); + } + str += "\n\n"; + str += parms.raidStrategy.arrivalTextEnemy; + Pawn pawn = pawns.Find((Predicate)((Pawn x) => x.Faction.leader == x)); if (pawn != null) { - text += "\n\n"; - text += "EnemyRaidLeaderPresent".Translate(new object[] - { - pawn.Faction.def.pawnsPlural, - pawn.LabelShort - }); + str += "\n\n"; + str += "EnemyRaidLeaderPresent".Translate(pawn.Faction.def.pawnsPlural, pawn.LabelShort); } - return text; + return str; } protected override LetterDef GetLetterDef() @@ -124,10 +110,7 @@ protected override LetterDef GetLetterDef() protected override string GetRelatedPawnsInfoLetterText(IncidentParms parms) { - return "LetterRelatedPawnsRaidEnemy".Translate(new object[] - { - parms.faction.def.pawnsPlural - }); + return "LetterRelatedPawnsRaidEnemy".Translate(parms.faction.def.pawnsPlural); } } } diff --git a/Assembly-CSharp/RimWorld/IncidentWorker_RaidFriendly.cs b/Assembly-CSharp/RimWorld/IncidentWorker_RaidFriendly.cs index 40ee93cfd..4e84d8044 100644 --- a/Assembly-CSharp/RimWorld/IncidentWorker_RaidFriendly.cs +++ b/Assembly-CSharp/RimWorld/IncidentWorker_RaidFriendly.cs @@ -11,8 +11,8 @@ public class IncidentWorker_RaidFriendly : IncidentWorker_Raid protected override bool FactionCanBeGroupSource(Faction f, Map map, bool desperate = false) { IEnumerable source = (from p in map.attackTargetsCache.TargetsHostileToColony - select ((Thing)p).Faction).Distinct(); - return base.FactionCanBeGroupSource(f, map, desperate) && !f.def.hidden && !f.HostileTo(Faction.OfPlayer) && (!source.Any() || source.Any((Faction hf) => hf.HostileTo(f))); + select ((Thing)p).Faction).Distinct(); + return base.FactionCanBeGroupSource(f, map, desperate) && !f.def.hidden && !f.HostileTo(Faction.OfPlayer) && (!source.Any() || source.Any((Func)((Faction hf) => hf.HostileTo(f)))); } protected override bool CanFireNowSub(IIncidentTarget target) @@ -24,7 +24,7 @@ protected override bool CanFireNowSub(IIncidentTarget target) Map map = (Map)target; return (from p in map.attackTargetsCache.TargetsHostileToColony where !p.ThreatDisabled() - select p).Sum(delegate(IAttackTarget p) + select p).Sum((Func)delegate(IAttackTarget p) { Pawn pawn = p as Pawn; if (pawn != null) @@ -32,7 +32,7 @@ protected override bool CanFireNowSub(IIncidentTarget target) return pawn.kindDef.combatPower; } return 0f; - }) > 120f; + }) > 120.0; } protected override bool TryResolveRaidFaction(IncidentParms parms) @@ -42,21 +42,20 @@ protected override bool TryResolveRaidFaction(IncidentParms parms) { return true; } - if (!base.CandidateFactions(map, false).Any()) + if (!base.CandidateFactions(map, false).Any()) { return false; } - parms.faction = base.CandidateFactions(map, false).RandomElementByWeight((Faction fac) => fac.PlayerGoodwill + 120.000008f); + parms.faction = base.CandidateFactions(map, false).RandomElementByWeight((Func)((Faction fac) => (float)(fac.PlayerGoodwill + 120.00000762939453))); return true; } protected override void ResolveRaidStrategy(IncidentParms parms) { - if (parms.raidStrategy != null) + if (parms.raidStrategy == null) { - return; + parms.raidStrategy = RaidStrategyDefOf.ImmediateAttack; } - parms.raidStrategy = RaidStrategyDefOf.ImmediateAttack; } protected override void ResolveRaidPoints(IncidentParms parms) @@ -71,44 +70,34 @@ protected override string GetLetterLabel(IncidentParms parms) protected override string GetLetterText(IncidentParms parms, List pawns) { - string text = null; + string str = (string)null; switch (parms.raidArrivalMode) { case PawnsArriveMode.EdgeWalkIn: - text = "FriendlyRaidWalkIn".Translate(new object[] - { - parms.faction.def.pawnsPlural, - parms.faction.Name - }); + { + str = "FriendlyRaidWalkIn".Translate(parms.faction.def.pawnsPlural, parms.faction.Name); break; + } case PawnsArriveMode.EdgeDrop: - text = "FriendlyRaidEdgeDrop".Translate(new object[] - { - parms.faction.def.pawnsPlural, - parms.faction.Name - }); + { + str = "FriendlyRaidEdgeDrop".Translate(parms.faction.def.pawnsPlural, parms.faction.Name); break; + } case PawnsArriveMode.CenterDrop: - text = "FriendlyRaidCenterDrop".Translate(new object[] - { - parms.faction.def.pawnsPlural, - parms.faction.Name - }); + { + str = "FriendlyRaidCenterDrop".Translate(parms.faction.def.pawnsPlural, parms.faction.Name); break; } - text += "\n\n"; - text += parms.raidStrategy.arrivalTextFriendly; - Pawn pawn = pawns.Find((Pawn x) => x.Faction.leader == x); + } + str += "\n\n"; + str += parms.raidStrategy.arrivalTextFriendly; + Pawn pawn = pawns.Find((Predicate)((Pawn x) => x.Faction.leader == x)); if (pawn != null) { - text += "\n\n"; - text += "FriendlyRaidLeaderPresent".Translate(new object[] - { - pawn.Faction.def.pawnsPlural, - pawn.LabelShort - }); + str += "\n\n"; + str += "FriendlyRaidLeaderPresent".Translate(pawn.Faction.def.pawnsPlural, pawn.LabelShort); } - return text; + return str; } protected override LetterDef GetLetterDef() @@ -118,10 +107,7 @@ protected override LetterDef GetLetterDef() protected override string GetRelatedPawnsInfoLetterText(IncidentParms parms) { - return "LetterRelatedPawnsRaidFriendly".Translate(new object[] - { - parms.faction.def.pawnsPlural - }); + return "LetterRelatedPawnsRaidFriendly".Translate(parms.faction.def.pawnsPlural); } } } diff --git a/Assembly-CSharp/RimWorld/IncidentWorker_RansomDemand.cs b/Assembly-CSharp/RimWorld/IncidentWorker_RansomDemand.cs index 6c04f33a9..8b787c243 100644 --- a/Assembly-CSharp/RimWorld/IncidentWorker_RansomDemand.cs +++ b/Assembly-CSharp/RimWorld/IncidentWorker_RansomDemand.cs @@ -12,7 +12,11 @@ public class IncidentWorker_RansomDemand : IncidentWorker protected override bool CanFireNowSub(IIncidentTarget target) { - return this.RandomKidnappedColonist() != null && base.CanFireNowSub(target); + if (this.RandomKidnappedColonist() == null) + { + return false; + } + return base.CanFireNowSub(target); } public override bool TryExecute(IncidentParms parms) @@ -25,23 +29,15 @@ public override bool TryExecute(IncidentParms parms) } Faction faction = this.FactionWhichKidnapped(pawn); int num = this.RandomFee(pawn); - ChoiceLetter_RansomDemand choiceLetter_RansomDemand = (ChoiceLetter_RansomDemand)LetterMaker.MakeLetter(this.def.letterLabel, "RansomDemand".Translate(new object[] - { - pawn.LabelShort, - faction.Name, - num - }).AdjustedFor(pawn), this.def.letterDef); - choiceLetter_RansomDemand.title = "RansomDemandTitle".Translate(new object[] - { - map.info.parent.Label - }); + ChoiceLetter_RansomDemand choiceLetter_RansomDemand = (ChoiceLetter_RansomDemand)LetterMaker.MakeLetter(base.def.letterLabel, "RansomDemand".Translate(pawn.LabelShort, faction.Name, num).AdjustedFor(pawn), base.def.letterDef); + choiceLetter_RansomDemand.title = "RansomDemandTitle".Translate(map.info.parent.Label); choiceLetter_RansomDemand.radioMode = true; choiceLetter_RansomDemand.kidnapped = pawn; choiceLetter_RansomDemand.faction = faction; choiceLetter_RansomDemand.map = map; choiceLetter_RansomDemand.fee = num; choiceLetter_RansomDemand.StartTimeout(60000); - Find.LetterStack.ReceiveLetter(choiceLetter_RansomDemand, null); + Find.LetterStack.ReceiveLetter(choiceLetter_RansomDemand, (string)null); return true; } @@ -69,8 +65,8 @@ private Pawn RandomKidnappedColonist() IncidentWorker_RansomDemand.candidates.Remove(choiceLetter_RansomDemand.kidnapped); } } - Pawn result; - if (!IncidentWorker_RansomDemand.candidates.TryRandomElement(out result)) + Pawn result = default(Pawn); + if (!((IEnumerable)IncidentWorker_RansomDemand.candidates).TryRandomElement(out result)) { return null; } @@ -80,7 +76,7 @@ private Pawn RandomKidnappedColonist() private Faction FactionWhichKidnapped(Pawn pawn) { - return Find.FactionManager.AllFactionsListForReading.Find((Faction x) => x.kidnapped.KidnappedPawnsListForReading.Contains(pawn)); + return Find.FactionManager.AllFactionsListForReading.Find((Predicate)((Faction x) => x.kidnapped.KidnappedPawnsListForReading.Contains(pawn))); } private int RandomFee(Pawn pawn) diff --git a/Assembly-CSharp/RimWorld/IncidentWorker_RefugeeChased.cs b/Assembly-CSharp/RimWorld/IncidentWorker_RefugeeChased.cs index 198612de7..d8923013d 100644 --- a/Assembly-CSharp/RimWorld/IncidentWorker_RefugeeChased.cs +++ b/Assembly-CSharp/RimWorld/IncidentWorker_RefugeeChased.cs @@ -17,38 +17,31 @@ public override bool TryExecute(IncidentParms parms) { Map map = (Map)parms.target; IntVec3 spawnSpot; - if (!CellFinder.TryFindRandomEdgeCellWith((IntVec3 c) => map.reachability.CanReachColony(c), map, CellFinder.EdgeRoadChance_Neutral, out spawnSpot)) + if (!CellFinder.TryFindRandomEdgeCellWith((Predicate)((IntVec3 c) => map.reachability.CanReachColony(c)), map, CellFinder.EdgeRoadChance_Neutral, out spawnSpot)) { return false; } Faction faction = Find.FactionManager.FirstFactionOfDef(FactionDefOf.Spacer); - PawnGenerationRequest request = new PawnGenerationRequest(PawnKindDefOf.SpaceRefugee, faction, PawnGenerationContext.NonPlayer, -1, false, false, false, false, true, false, 20f, false, true, true, false, false, null, null, null, null, null, null); + PawnGenerationRequest request = new PawnGenerationRequest(PawnKindDefOf.SpaceRefugee, faction, PawnGenerationContext.NonPlayer, -1, false, false, false, false, true, false, 20f, false, true, true, false, false, null, default(float?), default(float?), default(Gender?), default(float?), (string)null); Pawn refugee = PawnGenerator.GeneratePawn(request); refugee.relations.everSeenByPlayer = true; Faction enemyFac; if (!(from f in Find.FactionManager.AllFactions where !f.def.hidden && f.HostileTo(Faction.OfPlayer) - select f).TryRandomElement(out enemyFac)) + select f).TryRandomElement(out enemyFac)) { return false; } - string text = "RefugeeChasedInitial".Translate(new object[] - { - refugee.Name.ToStringFull, - refugee.story.Title.ToLower(), - enemyFac.def.pawnsPlural, - enemyFac.Name, - refugee.ageTracker.AgeBiologicalYears - }); + string text = "RefugeeChasedInitial".Translate(refugee.Name.ToStringFull, refugee.story.Title.ToLower(), enemyFac.def.pawnsPlural, enemyFac.Name, refugee.ageTracker.AgeBiologicalYears); text = text.AdjustedFor(refugee); PawnRelationUtility.TryAppendRelationsWithColonistsInfo(ref text, refugee); DiaNode diaNode = new DiaNode(text); DiaOption diaOption = new DiaOption("RefugeeChasedInitial_Accept".Translate()); - diaOption.action = delegate + diaOption.action = (Action)delegate { GenSpawn.Spawn(refugee, spawnSpot, map); refugee.SetFaction(Faction.OfPlayer, null); - CameraJumper.TryJump(refugee); + CameraJumper.TryJump((Thing)refugee); IncidentParms incidentParms = StorytellerUtility.DefaultParmsNow(Find.Storyteller.def, IncidentCategory.ThreatBig, map); incidentParms.forced = true; incidentParms.faction = enemyFac; @@ -61,25 +54,19 @@ public override bool TryExecute(IncidentParms parms) }; diaOption.resolveTree = true; diaNode.options.Add(diaOption); - string text2 = "RefugeeChasedRejected".Translate(new object[] - { - refugee.NameStringShort - }); + string text2 = "RefugeeChasedRejected".Translate(refugee.NameStringShort); DiaNode diaNode2 = new DiaNode(text2); DiaOption diaOption2 = new DiaOption("OK".Translate()); diaOption2.resolveTree = true; diaNode2.options.Add(diaOption2); DiaOption diaOption3 = new DiaOption("RefugeeChasedInitial_Reject".Translate()); - diaOption3.action = delegate + diaOption3.action = (Action)delegate { Find.WorldPawns.PassToWorld(refugee, PawnDiscardDecideMode.Decide); }; diaOption3.link = diaNode2; diaNode.options.Add(diaOption3); - string title = "RefugeeChasedTitle".Translate(new object[] - { - map.info.parent.Label - }); + string title = "RefugeeChasedTitle".Translate(map.info.parent.Label); Find.WindowStack.Add(new Dialog_NodeTree(diaNode, true, true, title)); return true; } diff --git a/Assembly-CSharp/RimWorld/IncidentWorker_RefugeePodCrash.cs b/Assembly-CSharp/RimWorld/IncidentWorker_RefugeePodCrash.cs index 81eff0405..1b71888ab 100644 --- a/Assembly-CSharp/RimWorld/IncidentWorker_RefugeePodCrash.cs +++ b/Assembly-CSharp/RimWorld/IncidentWorker_RefugeePodCrash.cs @@ -1,4 +1,3 @@ -using System; using Verse; namespace RimWorld @@ -14,19 +13,18 @@ public override bool TryExecute(IncidentParms parms) Map map = (Map)parms.target; IntVec3 intVec = DropCellFinder.RandomDropSpot(map); Faction faction = Find.FactionManager.FirstFactionOfDef(FactionDefOf.Spacer); - PawnGenerationRequest request = new PawnGenerationRequest(PawnKindDefOf.SpaceRefugee, faction, PawnGenerationContext.NonPlayer, -1, false, false, false, false, true, false, 20f, false, true, true, false, false, null, null, null, null, null, null); + PawnGenerationRequest request = new PawnGenerationRequest(PawnKindDefOf.SpaceRefugee, faction, PawnGenerationContext.NonPlayer, -1, false, false, false, false, true, false, 20f, false, true, true, false, false, null, default(float?), default(float?), default(Gender?), default(float?), (string)null); Pawn pawn = PawnGenerator.GeneratePawn(request); HealthUtility.DamageUntilDowned(pawn); string label = "LetterLabelRefugeePodCrash".Translate(); string text = "RefugeePodCrash".Translate(); PawnRelationUtility.TryAppendRelationsWithColonistsInfo(ref text, ref label, pawn); - Find.LetterStack.ReceiveLetter(label, text, LetterDefOf.BadNonUrgent, new TargetInfo(intVec, map, false), null); - DropPodUtility.MakeDropPodAt(intVec, map, new ActiveDropPodInfo - { - SingleContainedThing = ((!pawn.Dead) ? pawn : pawn.Corpse), - openDelay = 180, - leaveSlag = true - }); + Find.LetterStack.ReceiveLetter(label, text, LetterDefOf.BadNonUrgent, new TargetInfo(intVec, map, false), (string)null); + ActiveDropPodInfo activeDropPodInfo = new ActiveDropPodInfo(); + activeDropPodInfo.SingleContainedThing = (Thing)((!pawn.Dead) ? ((object)pawn) : ((object)pawn.Corpse)); + activeDropPodInfo.openDelay = 180; + activeDropPodInfo.leaveSlag = true; + DropPodUtility.MakeDropPodAt(intVec, map, activeDropPodInfo); return true; } } diff --git a/Assembly-CSharp/RimWorld/IncidentWorker_ResourcePodCrash.cs b/Assembly-CSharp/RimWorld/IncidentWorker_ResourcePodCrash.cs index 88df18317..c625b5eda 100644 --- a/Assembly-CSharp/RimWorld/IncidentWorker_ResourcePodCrash.cs +++ b/Assembly-CSharp/RimWorld/IncidentWorker_ResourcePodCrash.cs @@ -20,26 +20,26 @@ public class IncidentWorker_ResourcePodCrash : IncidentWorker private static IEnumerable PossiblePodContentsDefs() { return from d in DefDatabase.AllDefs - where d.category == ThingCategory.Item && d.tradeability == Tradeability.Stockable && d.equipmentType == EquipmentType.None && d.BaseMarketValue >= 1f && d.BaseMarketValue < 40f && !d.HasComp(typeof(CompHatcher)) + where d.category == ThingCategory.Item && d.tradeability == Tradeability.Stockable && d.equipmentType == EquipmentType.None && d.BaseMarketValue >= 1.0 && d.BaseMarketValue < 40.0 && !d.HasComp(typeof(CompHatcher)) select d; } private static ThingDef RandomPodContentsDef() { - Func isLeather = (ThingDef d) => d.category == ThingCategory.Item && d.thingCategories != null && d.thingCategories.Contains(ThingCategoryDefOf.Leathers); - Func isMeat = (ThingDef d) => d.category == ThingCategory.Item && d.thingCategories != null && d.thingCategories.Contains(ThingCategoryDefOf.MeatRaw); - int numLeathers = DefDatabase.AllDefs.Where(isLeather).Count(); - int numMeats = DefDatabase.AllDefs.Where(isMeat).Count(); - return IncidentWorker_ResourcePodCrash.PossiblePodContentsDefs().RandomElementByWeight(delegate(ThingDef d) + Func isLeather = (Func)((ThingDef d) => d.category == ThingCategory.Item && d.thingCategories != null && d.thingCategories.Contains(ThingCategoryDefOf.Leathers)); + Func isMeat = (Func)((ThingDef d) => d.category == ThingCategory.Item && d.thingCategories != null && d.thingCategories.Contains(ThingCategoryDefOf.MeatRaw)); + int numLeathers = DefDatabase.AllDefs.Where(isLeather).Count(); + int numMeats = DefDatabase.AllDefs.Where(isMeat).Count(); + return IncidentWorker_ResourcePodCrash.PossiblePodContentsDefs().RandomElementByWeight((Func)delegate(ThingDef d) { float num = 100f; if (isLeather(d)) { - num *= 5f / (float)numLeathers; + num = (float)(num * (5.0 / (float)numLeathers)); } if (isMeat(d)) { - num *= 5f / (float)numMeats; + num = (float)(num * (5.0 / (float)numMeats)); } return num; }); @@ -51,7 +51,7 @@ public override bool TryExecute(IncidentParms parms) ThingDef thingDef = IncidentWorker_ResourcePodCrash.RandomPodContentsDef(); List list = new List(); float num = Rand.Range(150f, 600f); - do + while (true) { Thing thing = ThingMaker.MakeThing(thingDef, null); int num2 = Rand.Range(20, 40); @@ -70,11 +70,14 @@ public override bool TryExecute(IncidentParms parms) thing.stackCount = num2; list.Add(thing); num -= (float)num2 * thingDef.BaseMarketValue; + if (list.Count >= 7) + break; + if (num <= thingDef.BaseMarketValue) + break; } - while (list.Count < 7 && num > thingDef.BaseMarketValue); IntVec3 intVec = DropCellFinder.RandomDropSpot(map); DropPodUtility.DropThingsNear(intVec, map, list, 110, false, true, true); - Find.LetterStack.ReceiveLetter("LetterLabelCargoPodCrash".Translate(), "CargoPodCrash".Translate(), LetterDefOf.Good, new TargetInfo(intVec, map, false), null); + Find.LetterStack.ReceiveLetter("LetterLabelCargoPodCrash".Translate(), "CargoPodCrash".Translate(), LetterDefOf.Good, new TargetInfo(intVec, map, false), (string)null); return true; } @@ -82,9 +85,9 @@ public static void DebugLogPossiblePodContentsDefs() { StringBuilder stringBuilder = new StringBuilder(); stringBuilder.AppendLine("ThingDefs that can go in the resource pod crash incident."); - foreach (ThingDef current in IncidentWorker_ResourcePodCrash.PossiblePodContentsDefs()) + foreach (ThingDef item in IncidentWorker_ResourcePodCrash.PossiblePodContentsDefs()) { - stringBuilder.AppendLine(current.defName); + stringBuilder.AppendLine(item.defName); } Log.Message(stringBuilder.ToString()); } diff --git a/Assembly-CSharp/RimWorld/IncidentWorker_SelfTame.cs b/Assembly-CSharp/RimWorld/IncidentWorker_SelfTame.cs index 5a2aff6c5..8c24aba42 100644 --- a/Assembly-CSharp/RimWorld/IncidentWorker_SelfTame.cs +++ b/Assembly-CSharp/RimWorld/IncidentWorker_SelfTame.cs @@ -10,21 +10,21 @@ public class IncidentWorker_SelfTame : IncidentWorker private IEnumerable Candidates(Map map) { return from x in map.mapPawns.AllPawnsSpawned - where x.RaceProps.Animal && x.Faction == null && !x.Position.Fogged(x.Map) && !x.InMentalState && !x.Downed && x.RaceProps.wildness > 0f + where x.RaceProps.Animal && x.Faction == null && !x.Position.Fogged(x.Map) && !x.InMentalState && !x.Downed && x.RaceProps.wildness > 0.0 select x; } protected override bool CanFireNowSub(IIncidentTarget target) { Map map = (Map)target; - return this.Candidates(map).Any(); + return this.Candidates(map).Any(); } public override bool TryExecute(IncidentParms parms) { Map map = (Map)parms.target; Pawn pawn = null; - if (!this.Candidates(map).TryRandomElementByWeight((Pawn x) => x.RaceProps.wildness, out pawn)) + if (!this.Candidates(map).TryRandomElementByWeight((Func)((Pawn x) => x.RaceProps.wildness), out pawn)) { return false; } @@ -35,37 +35,8 @@ public override bool TryExecute(IncidentParms parms) string text = pawn.LabelIndefinite(); bool flag = pawn.Name != null; pawn.SetFaction(Faction.OfPlayer, null); - string text2; - if (!flag && pawn.Name != null) - { - if (pawn.Name.Numerical) - { - text2 = "LetterAnimalSelfTameAndNameNumerical".Translate(new object[] - { - text, - pawn.Name.ToStringFull - }).CapitalizeFirst(); - } - else - { - text2 = "LetterAnimalSelfTameAndName".Translate(new object[] - { - text, - pawn.Name.ToStringFull - }).CapitalizeFirst(); - } - } - else - { - text2 = "LetterAnimalSelfTame".Translate(new object[] - { - pawn.LabelIndefinite() - }).CapitalizeFirst(); - } - Find.LetterStack.ReceiveLetter("LetterLabelAnimalSelfTame".Translate(new object[] - { - GenLabel.BestKindLabel(pawn, false, false, false) - }).CapitalizeFirst(), text2, LetterDefOf.Good, pawn, null); + string text2 = (flag || pawn.Name == null) ? "LetterAnimalSelfTame".Translate(pawn.LabelIndefinite()).CapitalizeFirst() : ((!pawn.Name.Numerical) ? "LetterAnimalSelfTameAndName".Translate(text, pawn.Name.ToStringFull).CapitalizeFirst() : "LetterAnimalSelfTameAndNameNumerical".Translate(text, pawn.Name.ToStringFull).CapitalizeFirst()); + Find.LetterStack.ReceiveLetter("LetterLabelAnimalSelfTame".Translate(GenLabel.BestKindLabel(pawn, false, false, false)).CapitalizeFirst(), text2, LetterDefOf.Good, (Thing)pawn, (string)null); return true; } } diff --git a/Assembly-CSharp/RimWorld/IncidentWorker_ShipChunkDrop.cs b/Assembly-CSharp/RimWorld/IncidentWorker_ShipChunkDrop.cs index 4e1e713ee..ec99cbfd6 100644 --- a/Assembly-CSharp/RimWorld/IncidentWorker_ShipChunkDrop.cs +++ b/Assembly-CSharp/RimWorld/IncidentWorker_ShipChunkDrop.cs @@ -7,7 +7,7 @@ namespace RimWorld { public class IncidentWorker_ShipChunkDrop : IncidentWorker { - private static readonly Pair[] CountChance = new Pair[] + private static readonly Pair[] CountChance = new Pair[4] { new Pair(1, 1f), new Pair(2, 0.95f), @@ -19,9 +19,9 @@ private int RandomCountToDrop { get { - float x2 = (float)Find.TickManager.TicksGame / 3600000f; + float x2 = (float)((float)Find.TickManager.TicksGame / 3600000.0); float timePassedFactor = Mathf.Clamp(GenMath.LerpDouble(0f, 1.2f, 1f, 0.1f, x2), 0.1f, 1f); - return IncidentWorker_ShipChunkDrop.CountChance.RandomElementByWeight(delegate(Pair x) + return IncidentWorker_ShipChunkDrop.CountChance.RandomElementByWeight((Func, float>)delegate(Pair x) { if (x.First == 1) { @@ -35,7 +35,7 @@ private int RandomCountToDrop public override bool TryExecute(IncidentParms parms) { Map map = (Map)parms.target; - IntVec3 intVec; + IntVec3 intVec = default(IntVec3); if (!ShipChunkDropCellFinder.TryFindShipChunkDropCell(map.Center, map, 999999, out intVec)) { return false; @@ -50,7 +50,7 @@ private void SpawnShipChunks(IntVec3 firstChunkPos, Map map, int count) this.SpawnChunk(firstChunkPos, map); for (int i = 0; i < count - 1; i++) { - IntVec3 pos; + IntVec3 pos = default(IntVec3); if (ShipChunkDropCellFinder.TryFindShipChunkDropCell(firstChunkPos, map, 5, out pos)) { this.SpawnChunk(pos, map); @@ -60,17 +60,13 @@ private void SpawnShipChunks(IntVec3 firstChunkPos, Map map, int count) private void SpawnChunk(IntVec3 pos, Map map) { - IncidentWorker_ShipChunkDrop.c__AnonStorey2E2 c__AnonStorey2E = new IncidentWorker_ShipChunkDrop.c__AnonStorey2E2(); - c__AnonStorey2E.map = map; - c__AnonStorey2E.cr = CellRect.SingleCell(pos); - IncidentWorker_ShipChunkDrop.c__AnonStorey2E2 expr_1F_cp_0 = c__AnonStorey2E; - expr_1F_cp_0.cr.Width = expr_1F_cp_0.cr.Width + 1; - IncidentWorker_ShipChunkDrop.c__AnonStorey2E2 expr_32_cp_0 = c__AnonStorey2E; - expr_32_cp_0.cr.Height = expr_32_cp_0.cr.Height + 1; - RoofCollapserImmediate.DropRoofInCells(from c in c__AnonStorey2E.cr.ExpandedBy(1).ClipInsideMap(c__AnonStorey2E.map).Cells - where c__AnonStorey2E.cr.Contains(c) || !c__AnonStorey2E.map.thingGrid.CellContains(c, ThingCategory.Pawn) - select c, c__AnonStorey2E.map); - GenSpawn.Spawn(ThingDefOf.ShipChunk, pos, c__AnonStorey2E.map); + CellRect cr = CellRect.SingleCell(pos); + cr.Width++; + cr.Height++; + RoofCollapserImmediate.DropRoofInCells(from c in cr.ExpandedBy(1).ClipInsideMap(map).Cells + where cr.Contains(c) || !map.thingGrid.CellContains(c, ThingCategory.Pawn) + select c, map); + GenSpawn.Spawn(ThingDefOf.ShipChunk, pos, map); } } } diff --git a/Assembly-CSharp/RimWorld/IncidentWorker_ShipPartCrash.cs b/Assembly-CSharp/RimWorld/IncidentWorker_ShipPartCrash.cs index 6c88530ea..2fe255548 100644 --- a/Assembly-CSharp/RimWorld/IncidentWorker_ShipPartCrash.cs +++ b/Assembly-CSharp/RimWorld/IncidentWorker_ShipPartCrash.cs @@ -95,7 +95,11 @@ protected virtual int CountToSpawn protected override bool CanFireNowSub(IIncidentTarget target) { Map map = (Map)target; - return map.listerThings.ThingsOfDef(this.def.shipPart).Count <= 0; + if (map.listerThings.ThingsOfDef(base.def.shipPart).Count > 0) + { + return false; + } + return true; } public override bool TryExecute(IncidentParms parms) @@ -105,46 +109,51 @@ public override bool TryExecute(IncidentParms parms) int countToSpawn = this.CountToSpawn; IntVec3 cell = IntVec3.Invalid; float angle = Rand.Range(0f, 360f); - for (int i = 0; i < countToSpawn; i++) + int num2 = 0; + while (num2 < countToSpawn) { - Predicate validator = delegate(IntVec3 c) + Predicate validator = (Predicate)delegate(IntVec3 c) { if (c.Fogged(map)) { return false; } - foreach (IntVec3 current in GenAdj.CellsOccupiedBy(c, Rot4.North, this.def.shipPart.size)) + foreach (IntVec3 item in GenAdj.CellsOccupiedBy(c, Rot4.North, base.def.shipPart.size)) { - if (!current.Standable(map)) + if (!item.Standable(map)) { - bool result = false; - return result; + return false; } - if (map.roofGrid.Roofed(current)) + if (map.roofGrid.Roofed(item)) { - bool result = false; - return result; + return false; } } - return map.reachability.CanReachColony(c); + if (!map.reachability.CanReachColony(c)) + { + return false; + } + return true; }; - IntVec3 intVec; - if (!CellFinderLoose.TryFindRandomNotEdgeCellWith(14, validator, map, out intVec)) + IntVec3 intVec = default(IntVec3); + if (CellFinderLoose.TryFindRandomNotEdgeCellWith(14, validator, map, out intVec)) { - break; - } - GenExplosion.DoExplosion(intVec, map, 3f, DamageDefOf.Flame, null, null, null, null, null, 0f, 1, false, null, 0f, 1); - Building_CrashedShipPart building_CrashedShipPart = (Building_CrashedShipPart)GenSpawn.Spawn(this.def.shipPart, intVec, map); - building_CrashedShipPart.SetFaction(Faction.OfMechanoids, null); - building_CrashedShipPart.pointsLeft = parms.points * 0.9f; - if (building_CrashedShipPart.pointsLeft < 300f) - { - building_CrashedShipPart.pointsLeft = 300f; + GenExplosion.DoExplosion(intVec, map, 3f, DamageDefOf.Flame, null, null, null, null, null, 0f, 1, false, null, 0f, 1); + Building_CrashedShipPart building_CrashedShipPart = (Building_CrashedShipPart)GenSpawn.Spawn(base.def.shipPart, intVec, map); + building_CrashedShipPart.SetFaction(Faction.OfMechanoids, null); + building_CrashedShipPart.pointsLeft = (float)(parms.points * 0.89999997615814209); + if (building_CrashedShipPart.pointsLeft < 300.0) + { + building_CrashedShipPart.pointsLeft = 300f; + } + IncidentWorker_ShipPartCrash.SpawnShrapnel(ThingDefOf.ChunkSlagSteel, IncidentWorker_ShipPartCrash.ShrapnelMetal.RandomInRange, intVec, map, angle); + IncidentWorker_ShipPartCrash.SpawnShrapnel(ThingDefOf.SlagRubble, IncidentWorker_ShipPartCrash.ShrapnelRubble.RandomInRange, intVec, map, angle); + num++; + cell = intVec; + num2++; + continue; } - IncidentWorker_ShipPartCrash.SpawnShrapnel(ThingDefOf.ChunkSlagSteel, IncidentWorker_ShipPartCrash.ShrapnelMetal.RandomInRange, intVec, map, angle); - IncidentWorker_ShipPartCrash.SpawnShrapnel(ThingDefOf.SlagRubble, IncidentWorker_ShipPartCrash.ShrapnelRubble.RandomInRange, intVec, map, angle); - num++; - cell = intVec; + break; } if (num > 0) { @@ -152,30 +161,24 @@ public override bool TryExecute(IncidentParms parms) { Find.CameraDriver.shaker.DoShake(1f); } - base.SendStandardLetter(new TargetInfo(cell, map, false), new string[0]); + base.SendStandardLetter(new TargetInfo(cell, map, false)); } return num > 0; } public static void SpawnShrapnel(ThingDef def, int quantity, IntVec3 center, Map map, float angle) { - for (int i = 0; i < quantity; i++) + for (int num = 0; num < quantity; num++) { IntVec3 intVec = IncidentWorker_ShipPartCrash.GenerateShrapnelLocation(center, angle); - if (intVec.InBounds(map)) + if (intVec.InBounds(map) && !intVec.Impassable(map) && !intVec.Filled(map)) { - if (!intVec.Impassable(map) && !intVec.Filled(map)) + RoofDef roofDef = map.roofGrid.RoofAt(intVec); + if (roofDef == null && (from thing in intVec.GetThingList(map) + where thing.def == def + select thing).Count() <= 0) { - RoofDef roofDef = map.roofGrid.RoofAt(intVec); - if (roofDef == null) - { - if ((from thing in intVec.GetThingList(map) - where thing.def == def - select thing).Count() <= 0) - { - GenSpawn.Spawn(def, intVec, map); - } - } + GenSpawn.Spawn(def, intVec, map); } } } diff --git a/Assembly-CSharp/RimWorld/IncidentWorker_ShortCircuit.cs b/Assembly-CSharp/RimWorld/IncidentWorker_ShortCircuit.cs index 6eff6eac6..c22bf4951 100644 --- a/Assembly-CSharp/RimWorld/IncidentWorker_ShortCircuit.cs +++ b/Assembly-CSharp/RimWorld/IncidentWorker_ShortCircuit.cs @@ -19,12 +19,9 @@ private List BatteryCandidates(Map map) for (int i = 0; i < allBuildingsColonist.Count; i++) { Building_Battery building_Battery = allBuildingsColonist[i] as Building_Battery; - if (building_Battery != null && building_Battery.GetComp().StoredEnergy >= 50f) + if (building_Battery != null && !(building_Battery.GetComp().StoredEnergy < 50.0) && this.GetRandomConduit(building_Battery) != null) { - if (this.GetRandomConduit(building_Battery) != null) - { - IncidentWorker_ShortCircuit.tmpBatteries.Add(building_Battery); - } + IncidentWorker_ShortCircuit.tmpBatteries.Add(building_Battery); } } return IncidentWorker_ShortCircuit.tmpBatteries; @@ -33,18 +30,18 @@ private List BatteryCandidates(Map map) protected override bool CanFireNowSub(IIncidentTarget target) { Map map = (Map)target; - return this.BatteryCandidates(map).Any(); + return this.BatteryCandidates(map).Any(); } public override bool TryExecute(IncidentParms parms) { Map map = (Map)parms.target; List list = this.BatteryCandidates(map); - if (!list.Any()) + if (!list.Any()) { return false; } - Building_Battery building_Battery = list.RandomElement(); + Building_Battery building_Battery = list.RandomElement(); PowerNet powerNet = building_Battery.PowerComp.PowerNet; CompPower randomConduit = this.GetRandomConduit(building_Battery); if (randomConduit == null) @@ -52,21 +49,30 @@ public override bool TryExecute(IncidentParms parms) return false; } float num = 0f; - foreach (CompPowerBattery current in powerNet.batteryComps) + List.Enumerator enumerator = powerNet.batteryComps.GetEnumerator(); + try { - num += current.StoredEnergy; - current.DrawPower(current.StoredEnergy); + while (enumerator.MoveNext()) + { + CompPowerBattery current = enumerator.Current; + num += current.StoredEnergy; + current.DrawPower(current.StoredEnergy); + } } - float num2 = Mathf.Sqrt(num) * 0.05f; - if (num2 > 14.9f) + finally + { + ((IDisposable)(object)enumerator).Dispose(); + } + float num2 = (float)(Mathf.Sqrt(num) * 0.05000000074505806); + if (num2 > 14.899999618530273) { num2 = 14.9f; } ThingWithComps parent = randomConduit.parent; GenExplosion.DoExplosion(parent.Position, map, num2, DamageDefOf.Flame, null, null, null, null, null, 0f, 1, false, null, 0f, 1); - if (num2 > 3.5f) + if (num2 > 3.5) { - GenExplosion.DoExplosion(parent.Position, map, num2 * 0.3f, DamageDefOf.Bomb, null, null, null, null, null, 0f, 1, false, null, 0f, 1); + GenExplosion.DoExplosion(parent.Position, map, (float)(num2 * 0.30000001192092896), DamageDefOf.Bomb, null, null, null, null, null, 0f, 1, false, null, 0f, 1); } if (!parent.Destroyed) { @@ -78,24 +84,20 @@ public override bool TryExecute(IncidentParms parms) text = "AnElectricalConduit".Translate(); } StringBuilder stringBuilder = new StringBuilder(); - stringBuilder.Append("ShortCircuit".Translate(new object[] - { - text, - num.ToString("F0") - })); - if (num2 > 5f) + stringBuilder.Append("ShortCircuit".Translate(text, num.ToString("F0"))); + if (num2 > 5.0) { stringBuilder.AppendLine(); stringBuilder.AppendLine(); stringBuilder.Append("ShortCircuitWasLarge".Translate()); } - if (num2 > 8f) + if (num2 > 8.0) { stringBuilder.AppendLine(); stringBuilder.AppendLine(); stringBuilder.Append("ShortCircuitWasHuge".Translate()); } - Find.LetterStack.ReceiveLetter("LetterLabelShortCircuit".Translate(), stringBuilder.ToString(), LetterDefOf.BadNonUrgent, new TargetInfo(parent.Position, map, false), null); + Find.LetterStack.ReceiveLetter("LetterLabelShortCircuit".Translate(), stringBuilder.ToString(), LetterDefOf.BadNonUrgent, new TargetInfo(parent.Position, map, false), (string)null); return true; } @@ -110,11 +112,11 @@ private CompPower GetRandomConduit(Building_Battery battery) IncidentWorker_ShortCircuit.tmpConduits.Add(transmitters[i]); } } - if (!IncidentWorker_ShortCircuit.tmpConduits.Any()) + if (!IncidentWorker_ShortCircuit.tmpConduits.Any()) { return null; } - CompPower result = IncidentWorker_ShortCircuit.tmpConduits.RandomElement(); + CompPower result = IncidentWorker_ShortCircuit.tmpConduits.RandomElement(); IncidentWorker_ShortCircuit.tmpConduits.Clear(); return result; } diff --git a/Assembly-CSharp/RimWorld/IncidentWorker_ThrumboPasses.cs b/Assembly-CSharp/RimWorld/IncidentWorker_ThrumboPasses.cs index 7188c1a5e..bebb835b9 100644 --- a/Assembly-CSharp/RimWorld/IncidentWorker_ThrumboPasses.cs +++ b/Assembly-CSharp/RimWorld/IncidentWorker_ThrumboPasses.cs @@ -9,47 +9,45 @@ public class IncidentWorker_ThrumboPasses : IncidentWorker protected override bool CanFireNowSub(IIncidentTarget target) { Map map = (Map)target; - return !map.gameConditionManager.ConditionIsActive(GameConditionDefOf.ToxicFallout); + if (map.gameConditionManager.ConditionIsActive(GameConditionDefOf.ToxicFallout)) + { + return false; + } + return true; } public override bool TryExecute(IncidentParms parms) { Map map = (Map)parms.target; - IntVec3 intVec; - if (!RCellFinder.TryFindRandomPawnEntryCell(out intVec, map, CellFinder.EdgeRoadChance_Animal + 0.2f, null)) + IntVec3 intVec = default(IntVec3); + if (!RCellFinder.TryFindRandomPawnEntryCell(out intVec, map, (float)(CellFinder.EdgeRoadChance_Animal + 0.20000000298023224), (Predicate)null)) { return false; } PawnKindDef thrumbo = PawnKindDefOf.Thrumbo; float points = StorytellerUtility.DefaultParmsNow(Find.Storyteller.def, IncidentCategory.ThreatBig, map).points; - int num = GenMath.RoundRandom(points / thrumbo.combatPower); + int value = GenMath.RoundRandom(points / thrumbo.combatPower); int max = Rand.RangeInclusive(2, 4); - num = Mathf.Clamp(num, 1, max); - int num2 = Rand.RangeInclusive(90000, 150000); + value = Mathf.Clamp(value, 1, max); + int num = Rand.RangeInclusive(90000, 150000); IntVec3 invalid = IntVec3.Invalid; if (!RCellFinder.TryFindRandomCellOutsideColonyNearTheCenterOfTheMap(intVec, map, 10f, out invalid)) { invalid = IntVec3.Invalid; } Pawn pawn = null; - for (int i = 0; i < num; i++) + for (int num2 = 0; num2 < value; num2++) { IntVec3 loc = CellFinder.RandomClosewalkCellNear(intVec, map, 10, null); pawn = PawnGenerator.GeneratePawn(thrumbo, null); GenSpawn.Spawn(pawn, loc, map, Rot4.Random, false); - pawn.mindState.exitMapAfterTick = Find.TickManager.TicksGame + num2; + pawn.mindState.exitMapAfterTick = Find.TickManager.TicksGame + num; if (invalid.IsValid) { pawn.mindState.forcedGotoPosition = CellFinder.RandomClosewalkCellNear(invalid, map, 10, null); } } - Find.LetterStack.ReceiveLetter("LetterLabelThrumboPasses".Translate(new object[] - { - thrumbo.label - }).CapitalizeFirst(), "LetterThrumboPasses".Translate(new object[] - { - thrumbo.label - }), LetterDefOf.Good, pawn, null); + Find.LetterStack.ReceiveLetter("LetterLabelThrumboPasses".Translate(thrumbo.label).CapitalizeFirst(), "LetterThrumboPasses".Translate(thrumbo.label), LetterDefOf.Good, (Thing)pawn, (string)null); return true; } } diff --git a/Assembly-CSharp/RimWorld/IncidentWorker_TraderCaravanArrival.cs b/Assembly-CSharp/RimWorld/IncidentWorker_TraderCaravanArrival.cs index 42951ab75..039e0ebc1 100644 --- a/Assembly-CSharp/RimWorld/IncidentWorker_TraderCaravanArrival.cs +++ b/Assembly-CSharp/RimWorld/IncidentWorker_TraderCaravanArrival.cs @@ -1,4 +1,3 @@ -using System; using System.Collections.Generic; using Verse; using Verse.AI.Group; @@ -17,7 +16,7 @@ protected override PawnGroupKindDef PawnGroupKindDef protected override bool FactionCanBeGroupSource(Faction f, Map map, bool desperate = false) { - return base.FactionCanBeGroupSource(f, map, desperate) && f.def.caravanTraderKinds.Any(); + return base.FactionCanBeGroupSource(f, map, desperate) && f.def.caravanTraderKinds.Any(); } public override bool TryExecute(IncidentParms parms) @@ -53,19 +52,11 @@ public override bool TryExecute(IncidentParms parms) break; } } - string label = "LetterLabelTraderCaravanArrival".Translate(new object[] - { - parms.faction.Name, - traderKindDef.label - }).CapitalizeFirst(); - string text = "LetterTraderCaravanArrival".Translate(new object[] - { - parms.faction.Name, - traderKindDef.label - }).CapitalizeFirst(); + string label = "LetterLabelTraderCaravanArrival".Translate(parms.faction.Name, traderKindDef.label).CapitalizeFirst(); + string text = "LetterTraderCaravanArrival".Translate(parms.faction.Name, traderKindDef.label).CapitalizeFirst(); PawnRelationUtility.Notify_PawnsSeenByPlayer(list, ref label, ref text, "LetterRelatedPawnsNeutralGroup".Translate(), true); - Find.LetterStack.ReceiveLetter(label, text, LetterDefOf.Good, list[0], null); - IntVec3 chillSpot; + Find.LetterStack.ReceiveLetter(label, text, LetterDefOf.Good, (Thing)list[0], (string)null); + IntVec3 chillSpot = default(IntVec3); RCellFinder.TryFindRandomSpotJustOutsideColony(list[0], out chillSpot); LordJob_TradeWithColony lordJob = new LordJob_TradeWithColony(parms.faction, chillSpot); LordMaker.MakeNewLord(parms.faction, lordJob, map, list); diff --git a/Assembly-CSharp/RimWorld/IncidentWorker_TravelerGroup.cs b/Assembly-CSharp/RimWorld/IncidentWorker_TravelerGroup.cs index 8ba37ba1f..fd5a03294 100644 --- a/Assembly-CSharp/RimWorld/IncidentWorker_TravelerGroup.cs +++ b/Assembly-CSharp/RimWorld/IncidentWorker_TravelerGroup.cs @@ -1,4 +1,3 @@ -using System; using System.Collections.Generic; using Verse; using Verse.AI.Group; @@ -14,7 +13,7 @@ public override bool TryExecute(IncidentParms parms) { return false; } - IntVec3 travelDest; + IntVec3 travelDest = default(IntVec3); if (!RCellFinder.TryFindTravelDestFrom(parms.spawnCenter, map, out travelDest)) { Log.Warning("Failed to do traveler incident from " + parms.spawnCenter + ": couldn't find anywhere for the traveler to go."); @@ -28,22 +27,14 @@ public override bool TryExecute(IncidentParms parms) string text; if (list.Count == 1) { - text = "SingleTravelerPassing".Translate(new object[] - { - list[0].story.Title.ToLower(), - parms.faction.Name, - list[0].Name - }); + text = "SingleTravelerPassing".Translate(list[0].story.Title.ToLower(), parms.faction.Name, list[0].Name); text = text.AdjustedFor(list[0]); } else { - text = "GroupTravelersPassing".Translate(new object[] - { - parms.faction.Name - }); + text = "GroupTravelersPassing".Translate(parms.faction.Name); } - Messages.Message(text, list[0], MessageSound.Standard); + Messages.Message(text, (Thing)list[0], MessageSound.Standard); LordJob_TravelAndExit lordJob = new LordJob_TravelAndExit(travelDest); LordMaker.MakeNewLord(parms.faction, lordJob, map, list); string empty = string.Empty; @@ -51,7 +42,7 @@ public override bool TryExecute(IncidentParms parms) PawnRelationUtility.Notify_PawnsSeenByPlayer(list, ref empty, ref empty2, "LetterRelatedPawnsNeutralGroup".Translate(), true); if (!empty2.NullOrEmpty()) { - Find.LetterStack.ReceiveLetter(empty, empty2, LetterDefOf.Good, list[0], null); + Find.LetterStack.ReceiveLetter(empty, empty2, LetterDefOf.Good, (Thing)list[0], (string)null); } return true; } diff --git a/Assembly-CSharp/RimWorld/IncidentWorker_VisitorGroup.cs b/Assembly-CSharp/RimWorld/IncidentWorker_VisitorGroup.cs index 45fc69e75..c0c9c8af5 100644 --- a/Assembly-CSharp/RimWorld/IncidentWorker_VisitorGroup.cs +++ b/Assembly-CSharp/RimWorld/IncidentWorker_VisitorGroup.cs @@ -21,16 +21,16 @@ public override bool TryExecute(IncidentParms parms) { return false; } - IntVec3 chillSpot; + IntVec3 chillSpot = default(IntVec3); RCellFinder.TryFindRandomSpotJustOutsideColony(list[0], out chillSpot); LordJob_VisitColony lordJob = new LordJob_VisitColony(parms.faction, chillSpot); LordMaker.MakeNewLord(parms.faction, lordJob, map, list); bool flag = false; - if (Rand.Value < 0.75f) + if (Rand.Value < 0.75) { flag = this.TryConvertOnePawnToSmallTrader(list, parms.faction, map); } - Pawn pawn = list.Find((Pawn x) => parms.faction.leader == x); + Pawn pawn = list.Find((Predicate)((Pawn x) => parms.faction.leader == x)); string label; string text3; if (list.Count == 1) @@ -38,71 +38,67 @@ public override bool TryExecute(IncidentParms parms) string text = (!flag) ? string.Empty : "SingleVisitorArrivesTraderInfo".Translate(); string text2 = (pawn == null) ? string.Empty : "SingleVisitorArrivesLeaderInfo".Translate(); label = "LetterLabelSingleVisitorArrives".Translate(); - text3 = "SingleVisitorArrives".Translate(new object[] - { - list[0].story.Title.ToLower(), - parms.faction.Name, - list[0].Name, - text, - text2 - }); + text3 = "SingleVisitorArrives".Translate(list[0].story.Title.ToLower(), parms.faction.Name, list[0].Name, text, text2); text3 = text3.AdjustedFor(list[0]); } else { string text4 = (!flag) ? string.Empty : "GroupVisitorsArriveTraderInfo".Translate(); - string text5 = (pawn == null) ? string.Empty : "GroupVisitorsArriveLeaderInfo".Translate(new object[] - { - pawn.LabelShort - }); + string text5 = (pawn == null) ? string.Empty : "GroupVisitorsArriveLeaderInfo".Translate(pawn.LabelShort); label = "LetterLabelGroupVisitorsArrive".Translate(); - text3 = "GroupVisitorsArrive".Translate(new object[] - { - parms.faction.Name, - text4, - text5 - }); + text3 = "GroupVisitorsArrive".Translate(parms.faction.Name, text4, text5); } PawnRelationUtility.Notify_PawnsSeenByPlayer(list, ref label, ref text3, "LetterRelatedPawnsNeutralGroup".Translate(), true); - Find.LetterStack.ReceiveLetter(label, text3, LetterDefOf.Good, list[0], null); + Find.LetterStack.ReceiveLetter(label, text3, LetterDefOf.Good, (Thing)list[0], (string)null); return true; } private bool TryConvertOnePawnToSmallTrader(List pawns, Faction faction, Map map) { - if (faction.def.visitorTraderKinds.NullOrEmpty()) + if (faction.def.visitorTraderKinds.NullOrEmpty()) { return false; } - Pawn pawn = pawns.RandomElement(); + Pawn pawn = pawns.RandomElement(); Lord lord = pawn.GetLord(); pawn.mindState.wantsToTradeWithColony = true; PawnComponentsUtility.AddAndRemoveDynamicComponents(pawn, true); - TraderKindDef traderKindDef = faction.def.visitorTraderKinds.RandomElementByWeight((TraderKindDef traderDef) => traderDef.commonality); - pawn.trader.traderKind = traderKindDef; + List visitorTraderKinds = faction.def.visitorTraderKinds; + TraderKindDef traderDef2 = pawn.trader.traderKind = visitorTraderKinds.RandomElementByWeight((Func)((TraderKindDef traderDef) => traderDef.commonality)); pawn.inventory.DestroyAll(DestroyMode.Vanish); - ItemCollectionGeneratorParams parms = default(ItemCollectionGeneratorParams); - parms.traderDef = traderKindDef; - parms.forTile = map.Tile; - parms.forFaction = faction; - foreach (Thing current in ItemCollectionGeneratorDefOf.TraderStock.Worker.Generate(parms)) + ItemCollectionGeneratorParams parms = new ItemCollectionGeneratorParams { - Pawn pawn2 = current as Pawn; - if (pawn2 != null) + traderDef = traderDef2, + forTile = map.Tile, + forFaction = faction + }; + List.Enumerator enumerator = ItemCollectionGeneratorDefOf.TraderStock.Worker.Generate(parms).GetEnumerator(); + try + { + while (enumerator.MoveNext()) { - if (pawn2.Faction != pawn.Faction) + Thing current = enumerator.Current; + Pawn pawn2 = current as Pawn; + if (pawn2 != null) { - pawn2.SetFaction(pawn.Faction, null); + if (pawn2.Faction != pawn.Faction) + { + pawn2.SetFaction(pawn.Faction, null); + } + IntVec3 loc = CellFinder.RandomClosewalkCellNear(pawn.Position, map, 5, null); + GenSpawn.Spawn(pawn2, loc, map); + lord.AddPawn(pawn2); + } + else if (!pawn.inventory.innerContainer.TryAdd(current, true)) + { + current.Destroy(DestroyMode.Vanish); } - IntVec3 loc = CellFinder.RandomClosewalkCellNear(pawn.Position, map, 5, null); - GenSpawn.Spawn(pawn2, loc, map); - lord.AddPawn(pawn2); - } - else if (!pawn.inventory.innerContainer.TryAdd(current, true)) - { - current.Destroy(DestroyMode.Vanish); } } + finally + { + ((IDisposable)(object)enumerator).Dispose(); + } PawnInventoryGenerator.GiveRandomFood(pawn); return true; } diff --git a/Assembly-CSharp/RimWorld/IncidentWorker_WandererJoin.cs b/Assembly-CSharp/RimWorld/IncidentWorker_WandererJoin.cs index 29897c1d7..c157afc1d 100644 --- a/Assembly-CSharp/RimWorld/IncidentWorker_WandererJoin.cs +++ b/Assembly-CSharp/RimWorld/IncidentWorker_WandererJoin.cs @@ -11,27 +11,22 @@ public class IncidentWorker_WandererJoin : IncidentWorker public override bool TryExecute(IncidentParms parms) { Map map = (Map)parms.target; - IntVec3 loc; - if (!CellFinder.TryFindRandomEdgeCellWith((IntVec3 c) => map.reachability.CanReachColony(c), map, CellFinder.EdgeRoadChance_Neutral, out loc)) + IntVec3 loc = default(IntVec3); + if (!CellFinder.TryFindRandomEdgeCellWith((Predicate)((IntVec3 c) => map.reachability.CanReachColony(c)), map, CellFinder.EdgeRoadChance_Neutral, out loc)) { return false; } - PawnKindDef pawnKindDef = new List - { - PawnKindDefOf.Villager - }.RandomElement(); - PawnGenerationRequest request = new PawnGenerationRequest(pawnKindDef, Faction.OfPlayer, PawnGenerationContext.NonPlayer, -1, false, false, false, false, true, false, 20f, false, true, true, false, false, null, null, null, null, null, null); + List list = new List(); + list.Add(PawnKindDefOf.Villager); + PawnKindDef pawnKindDef = list.RandomElement(); + PawnGenerationRequest request = new PawnGenerationRequest(pawnKindDef, Faction.OfPlayer, PawnGenerationContext.NonPlayer, -1, false, false, false, false, true, false, 20f, false, true, true, false, false, null, default(float?), default(float?), default(Gender?), default(float?), (string)null); Pawn pawn = PawnGenerator.GeneratePawn(request); GenSpawn.Spawn(pawn, loc, map); - string text = "WandererJoin".Translate(new object[] - { - pawnKindDef.label, - pawn.story.Title.ToLower() - }); + string text = "WandererJoin".Translate(pawnKindDef.label, pawn.story.Title.ToLower()); text = text.AdjustedFor(pawn); string label = "LetterLabelWandererJoin".Translate(); PawnRelationUtility.TryAppendRelationsWithColonistsInfo(ref text, ref label, pawn); - Find.LetterStack.ReceiveLetter(label, text, LetterDefOf.Good, pawn, null); + Find.LetterStack.ReceiveLetter(label, text, LetterDefOf.Good, (Thing)pawn, (string)null); return true; } } diff --git a/Assembly-CSharp/RimWorld/IndividualThoughtToAdd.cs b/Assembly-CSharp/RimWorld/IndividualThoughtToAdd.cs index 457a1d876..078bb2f39 100644 --- a/Assembly-CSharp/RimWorld/IndividualThoughtToAdd.cs +++ b/Assembly-CSharp/RimWorld/IndividualThoughtToAdd.cs @@ -1,4 +1,3 @@ -using System; using UnityEngine; using Verse; @@ -18,7 +17,7 @@ public string LabelCap { string text = this.thought.LabelCap; float num = this.thought.MoodOffset(); - if (num != 0f) + if (num != 0.0) { text = text + " " + Mathf.RoundToInt(num).ToStringWithSign(); } diff --git a/Assembly-CSharp/RimWorld/InfestationCellFinder.cs b/Assembly-CSharp/RimWorld/InfestationCellFinder.cs index d6b58fb85..1c4a8e063 100644 --- a/Assembly-CSharp/RimWorld/InfestationCellFinder.cs +++ b/Assembly-CSharp/RimWorld/InfestationCellFinder.cs @@ -36,7 +36,7 @@ public LocationCandidate(IntVec3 cell, float score) private const float MaxDistanceToColonyBuilding = 30f; - private static List locationCandidates = new List(); + private static List locationCandidates = new List(); private static Dictionary regionsDistanceToUnroofed = new Dictionary(); @@ -53,8 +53,8 @@ public LocationCandidate(IntVec3 cell, float score) public static bool TryFindCell(out IntVec3 cell, Map map) { InfestationCellFinder.CalculateLocationCandidates(map); - InfestationCellFinder.LocationCandidate locationCandidate; - if (!InfestationCellFinder.locationCandidates.TryRandomElementByWeight((InfestationCellFinder.LocationCandidate x) => x.score, out locationCandidate)) + LocationCandidate locationCandidate = default(LocationCandidate); + if (!((IEnumerable)InfestationCellFinder.locationCandidates).TryRandomElementByWeight((Func)((LocationCandidate x) => x.score), out locationCandidate)) { cell = IntVec3.Invalid; return false; @@ -65,7 +65,7 @@ public static bool TryFindCell(out IntVec3 cell, Map map) private static float GetScoreAt(IntVec3 cell, Map map) { - if ((float)InfestationCellFinder.distToColonyBuilding[cell] > 30f) + if ((float)(int)InfestationCellFinder.distToColonyBuilding[cell] > 30.0) { return 0f; } @@ -81,51 +81,43 @@ private static float GetScoreAt(IntVec3 cell, Map map) { return 0f; } - if (!cell.Roofed(map) || !cell.GetRoof(map).isThickRoof) + if (cell.Roofed(map) && cell.GetRoof(map).isThickRoof) { - return 0f; - } - Region region = cell.GetRegion(map, RegionType.Set_Passable); - if (region == null) - { - return 0f; - } - if (InfestationCellFinder.closedAreaSize[cell] < 16) - { - return 0f; - } - float temperature = cell.GetTemperature(map); - if (temperature < -17f) - { - return 0f; - } - float mountainousnessScoreAt = InfestationCellFinder.GetMountainousnessScoreAt(cell, map); - if (mountainousnessScoreAt < 0.17f) - { - return 0f; - } - int num = InfestationCellFinder.StraightLineDistToUnroofed(cell, map); - float num2; - if (!InfestationCellFinder.regionsDistanceToUnroofed.TryGetValue(region, out num2)) - { - num2 = (float)num * 1.15f; - } - else - { - num2 = Mathf.Min(num2, (float)num * 4f); - } - num2 = Mathf.Pow(num2, 1.55f); - float num3 = Mathf.InverseLerp(0f, 12f, (float)num); - float num4 = Mathf.Lerp(1f, 0.18f, map.glowGrid.GameGlowAt(cell)); - float num5 = 1f - Mathf.Clamp(InfestationCellFinder.DistToBlocker(cell, map) / 11f, 0f, 0.6f); - float num6 = Mathf.InverseLerp(-17f, -7f, temperature); - float num7 = num2 * num3 * num5 * mountainousnessScoreAt * num4 * num6; - num7 = Mathf.Pow(num7, 1.2f); - if (num7 < 7.5f) - { - return 0f; + Region region = cell.GetRegion(map, RegionType.Set_Passable); + if (region == null) + { + return 0f; + } + if (InfestationCellFinder.closedAreaSize[cell] < 16) + { + return 0f; + } + float temperature = cell.GetTemperature(map); + if (temperature < -17.0) + { + return 0f; + } + float mountainousnessScoreAt = InfestationCellFinder.GetMountainousnessScoreAt(cell, map); + if (mountainousnessScoreAt < 0.17000000178813934) + { + return 0f; + } + int num = InfestationCellFinder.StraightLineDistToUnroofed(cell, map); + float num2 = (float)(InfestationCellFinder.regionsDistanceToUnroofed.TryGetValue(region, out num2) ? Mathf.Min(num2, (float)((float)num * 4.0)) : ((float)num * 1.1499999761581421)); + num2 = Mathf.Pow(num2, 1.55f); + float num3 = Mathf.InverseLerp(0f, 12f, (float)num); + float num4 = Mathf.Lerp(1f, 0.18f, map.glowGrid.GameGlowAt(cell)); + float num5 = (float)(1.0 - Mathf.Clamp((float)(InfestationCellFinder.DistToBlocker(cell, map) / 11.0), 0f, 0.6f)); + float num6 = Mathf.InverseLerp(-17f, -7f, temperature); + float f = num2 * num3 * num5 * mountainousnessScoreAt * num4 * num6; + f = Mathf.Pow(f, 1.2f); + if (f < 7.5) + { + return 0f; + } + return f; } - return num7; + return 0f; } public static void DebugDraw() @@ -140,33 +132,69 @@ public static void DebugDraw() InfestationCellFinder.CalculateClosedAreaSizeGrid(visibleMap); InfestationCellFinder.CalculateDistanceToColonyBuildingGrid(visibleMap); float num = 0.001f; - for (int i = 0; i < visibleMap.Size.z; i++) + int num2 = 0; + while (true) { - for (int j = 0; j < visibleMap.Size.x; j++) + int num3 = num2; + IntVec3 size = visibleMap.Size; + if (num3 < size.z) { - IntVec3 cell = new IntVec3(j, 0, i); - float scoreAt = InfestationCellFinder.GetScoreAt(cell, visibleMap); - if (scoreAt > num) + int num4 = 0; + while (true) { - num = scoreAt; + int num5 = num4; + IntVec3 size2 = visibleMap.Size; + if (num5 < size2.x) + { + IntVec3 cell = new IntVec3(num4, 0, num2); + float scoreAt = InfestationCellFinder.GetScoreAt(cell, visibleMap); + if (scoreAt > num) + { + num = scoreAt; + } + num4++; + continue; + } + break; } + num2++; + continue; } + break; } - for (int k = 0; k < visibleMap.Size.z; k++) + int num6 = 0; + while (true) { - for (int l = 0; l < visibleMap.Size.x; l++) + int num7 = num6; + IntVec3 size3 = visibleMap.Size; + if (num7 < size3.z) { - IntVec3 intVec = new IntVec3(l, 0, k); - if (cellRect.Contains(intVec)) + int num8 = 0; + while (true) { - float scoreAt2 = InfestationCellFinder.GetScoreAt(intVec, visibleMap); - if (scoreAt2 > 0f) + int num9 = num8; + IntVec3 size4 = visibleMap.Size; + if (num9 < size4.x) { - float a = GenMath.LerpDouble(7.5f, num, 0f, 1f, scoreAt2); - CellRenderer.RenderCell(intVec, SolidColorMaterials.SimpleSolidColorMaterial(new Color(0f, 0f, 1f, a), false)); + IntVec3 intVec = new IntVec3(num8, 0, num6); + if (cellRect.Contains(intVec)) + { + float scoreAt2 = InfestationCellFinder.GetScoreAt(intVec, visibleMap); + if (!(scoreAt2 <= 0.0)) + { + float a = GenMath.LerpDouble(7.5f, num, 0f, 1f, scoreAt2); + CellRenderer.RenderCell(intVec, SolidColorMaterials.SimpleSolidColorMaterial(new Color(0f, 0f, 1f, a), false)); + } + } + num8++; + continue; } + break; } + num6++; + continue; } + break; } } } @@ -177,17 +205,35 @@ private static void CalculateLocationCandidates(Map map) InfestationCellFinder.CalculateTraversalDistancesToUnroofed(map); InfestationCellFinder.CalculateClosedAreaSizeGrid(map); InfestationCellFinder.CalculateDistanceToColonyBuildingGrid(map); - for (int i = 0; i < map.Size.z; i++) + int num = 0; + while (true) { - for (int j = 0; j < map.Size.x; j++) + int num2 = num; + IntVec3 size = map.Size; + if (num2 < size.z) { - IntVec3 cell = new IntVec3(j, 0, i); - float scoreAt = InfestationCellFinder.GetScoreAt(cell, map); - if (scoreAt > 0f) + int num3 = 0; + while (true) { - InfestationCellFinder.locationCandidates.Add(new InfestationCellFinder.LocationCandidate(cell, scoreAt)); + int num4 = num3; + IntVec3 size2 = map.Size; + if (num4 < size2.x) + { + IntVec3 cell = new IntVec3(num3, 0, num); + float scoreAt = InfestationCellFinder.GetScoreAt(cell, map); + if (!(scoreAt <= 0.0)) + { + InfestationCellFinder.locationCandidates.Add(new LocationCandidate(cell, scoreAt)); + } + num3++; + continue; + } + break; } + num++; + continue; } + break; } } @@ -211,41 +257,38 @@ private static bool CellHasBlockingThings(IntVec3 cell, Map map) private static int StraightLineDistToUnroofed(IntVec3 cell, Map map) { int num = 2147483647; - int i = 0; - while (i < 4) + for (int i = 0; i < 4; i++) { - Rot4 rot = new Rot4(i); - IntVec3 facingCell = rot.FacingCell; int num2 = 0; - int num3; + IntVec3 facingCell = new Rot4(i).FacingCell; + int num3 = 0; while (true) { - IntVec3 intVec = cell + facingCell * num2; + IntVec3 intVec = cell + facingCell * num3; if (!intVec.InBounds(map)) { - goto Block_1; + num2 = 2147483647; } - num3 = num2; - if (InfestationCellFinder.NoRoofAroundAndWalkable(intVec, map)) + else { - break; + num2 = num3; + if (!InfestationCellFinder.NoRoofAroundAndWalkable(intVec, map)) + { + num3++; + continue; + } } - num2++; + break; } - IL_6F: - if (num3 < num) + if (num2 < num) { - num = num3; + num = num2; } - i++; - continue; - Block_1: - num3 = 2147483647; - goto IL_6F; } if (num == 2147483647) { - return map.Size.x; + IntVec3 size = map.Size; + return size.x; } return num; } @@ -256,28 +299,28 @@ private static float DistToBlocker(IntVec3 cell, Map map) int num2 = -2147483648; for (int i = 0; i < 4; i++) { - Rot4 rot = new Rot4(i); - IntVec3 facingCell = rot.FacingCell; int num3 = 0; - int num4; + IntVec3 facingCell = new Rot4(i).FacingCell; + int num4 = 0; while (true) { - IntVec3 c = cell + facingCell * num3; - num4 = num3; - if (!c.InBounds(map) || !c.Walkable(map)) + IntVec3 c = cell + facingCell * num4; + num3 = num4; + if (c.InBounds(map) && c.Walkable(map)) { - break; + num4++; + continue; } - num3++; + break; } - if (num4 > num) + if (num3 > num) { num2 = num; - num = num4; + num = num3; } - else if (num4 > num2) + else if (num3 > num2) { - num2 = num4; + num2 = num3; } } return (float)Mathf.Min(num, num2); @@ -295,8 +338,7 @@ private static bool NoRoofAroundAndWalkable(IntVec3 cell, Map map) } for (int i = 0; i < 4; i++) { - Rot4 rot = new Rot4(i); - IntVec3 c = rot.FacingCell + cell; + IntVec3 c = new Rot4(i).FacingCell + cell; if (c.InBounds(map) && c.Roofed(map)) { return false; @@ -309,19 +351,19 @@ private static float GetMountainousnessScoreAt(IntVec3 cell, Map map) { float num = 0f; int num2 = 0; - for (int i = 0; i < 700; i += 10) + for (int num3 = 0; num3 < 700; num3 += 10) { - IntVec3 c = cell + GenRadial.RadialPattern[i]; + IntVec3 c = cell + GenRadial.RadialPattern[num3]; if (c.InBounds(map)) { Building edifice = c.GetEdifice(map); if (edifice != null && edifice.def.category == ThingCategory.Building && edifice.def.building.isNaturalRock) { - num += 1f; + num = (float)(num + 1.0); } else if (c.Roofed(map) && c.GetRoof(map).isThickRoof) { - num += 0.5f; + num = (float)(num + 0.5); } num2++; } @@ -332,19 +374,37 @@ private static float GetMountainousnessScoreAt(IntVec3 cell, Map map) private static void CalculateTraversalDistancesToUnroofed(Map map) { InfestationCellFinder.tempUnroofedRegions.Clear(); - for (int i = 0; i < map.Size.z; i++) + int num = 0; + while (true) { - for (int j = 0; j < map.Size.x; j++) + int num2 = num; + IntVec3 size = map.Size; + if (num2 < size.z) { - IntVec3 intVec = new IntVec3(j, 0, i); - Region region = intVec.GetRegion(map, RegionType.Set_Passable); - if (region != null && InfestationCellFinder.NoRoofAroundAndWalkable(intVec, map)) + int num3 = 0; + while (true) { - InfestationCellFinder.tempUnroofedRegions.Add(region); + int num4 = num3; + IntVec3 size2 = map.Size; + if (num4 < size2.x) + { + IntVec3 intVec = new IntVec3(num3, 0, num); + Region region = intVec.GetRegion(map, RegionType.Set_Passable); + if (region != null && InfestationCellFinder.NoRoofAroundAndWalkable(intVec, map)) + { + InfestationCellFinder.tempUnroofedRegions.Add(region); + } + num3++; + continue; + } + break; } + num++; + continue; } + break; } - Dijkstra.Run(InfestationCellFinder.tempUnroofedRegions, (Region x) => x.Neighbors, (Region a, Region b) => Mathf.Sqrt((float)a.extentsClose.CenterCell.DistanceToSquared(b.extentsClose.CenterCell)), ref InfestationCellFinder.regionsDistanceToUnroofed); + Dijkstra.Run((IEnumerable)InfestationCellFinder.tempUnroofedRegions, (Func>)((Region x) => x.Neighbors), (Func)((Region a, Region b) => Mathf.Sqrt((float)a.extentsClose.CenterCell.DistanceToSquared(b.extentsClose.CenterCell))), ref InfestationCellFinder.regionsDistanceToUnroofed); InfestationCellFinder.tempUnroofedRegions.Clear(); } @@ -358,25 +418,43 @@ private static void CalculateClosedAreaSizeGrid(Map map) { InfestationCellFinder.closedAreaSize.ClearAndResizeTo(map); } - for (int i = 0; i < map.Size.z; i++) + int num = 0; + while (true) { - for (int j = 0; j < map.Size.x; j++) + int num2 = num; + IntVec3 size = map.Size; + if (num2 < size.z) { - IntVec3 intVec = new IntVec3(j, 0, i); - if (InfestationCellFinder.closedAreaSize[j, i] == 0 && !intVec.Impassable(map)) + int num3 = 0; + while (true) { - int area = 0; - map.floodFiller.FloodFill(intVec, (IntVec3 c) => !c.Impassable(map), delegate(IntVec3 c) + int num4 = num3; + IntVec3 size2 = map.Size; + if (num4 < size2.x) { - area++; - }, false); - area = Mathf.Min(area, 255); - map.floodFiller.FloodFill(intVec, (IntVec3 c) => !c.Impassable(map), delegate(IntVec3 c) - { - InfestationCellFinder.closedAreaSize[c] = (byte)area; - }, false); + IntVec3 intVec = new IntVec3(num3, 0, num); + if (InfestationCellFinder.closedAreaSize[num3, num] == 0 && !intVec.Impassable(map)) + { + int area = 0; + map.floodFiller.FloodFill(intVec, (Predicate)((IntVec3 c) => !c.Impassable(map)), (Action)delegate(IntVec3 c) + { + area++; + }, false); + area = Mathf.Min(area, 255); + map.floodFiller.FloodFill(intVec, (Predicate)((IntVec3 c) => !c.Impassable(map)), (Action)delegate(IntVec3 c) + { + InfestationCellFinder.closedAreaSize[c] = (byte)area; + }, false); + } + num3++; + continue; + } + break; } + num++; + continue; } + break; } } @@ -390,20 +468,20 @@ private static void CalculateDistanceToColonyBuildingGrid(Map map) { InfestationCellFinder.distToColonyBuilding.ClearAndResizeTo(map); } - InfestationCellFinder.distToColonyBuilding.Clear(255); + InfestationCellFinder.distToColonyBuilding.Clear((byte)255); InfestationCellFinder.tmpColonyBuildingsLocs.Clear(); List allBuildingsColonist = map.listerBuildings.allBuildingsColonist; for (int i = 0; i < allBuildingsColonist.Count; i++) { InfestationCellFinder.tmpColonyBuildingsLocs.Add(allBuildingsColonist[i].Position); } - Dijkstra.Run(InfestationCellFinder.tmpColonyBuildingsLocs, (IntVec3 x) => DijkstraUtility.AdjacentCellsNeighborsGetter(x, map), delegate(IntVec3 a, IntVec3 b) + Dijkstra.Run((IEnumerable)InfestationCellFinder.tmpColonyBuildingsLocs, (Func>)((IntVec3 x) => DijkstraUtility.AdjacentCellsNeighborsGetter(x, map)), (Func)delegate(IntVec3 a, IntVec3 b) { - if (a.x == b.x || a.z == b.z) + if (a.x != b.x && a.z != b.z) { - return 1f; + return 1.41421354f; } - return 1.41421354f; + return 1f; }, ref InfestationCellFinder.tmpDistanceResult); for (int j = 0; j < InfestationCellFinder.tmpDistanceResult.Count; j++) { diff --git a/Assembly-CSharp/RimWorld/IngestibleProperties.cs b/Assembly-CSharp/RimWorld/IngestibleProperties.cs index 43652c891..30d278911 100644 --- a/Assembly-CSharp/RimWorld/IngestibleProperties.cs +++ b/Assembly-CSharp/RimWorld/IngestibleProperties.cs @@ -1,6 +1,4 @@ -using System; using System.Collections.Generic; -using System.Diagnostics; using Verse; namespace RimWorld @@ -67,7 +65,7 @@ public bool HumanEdible { get { - return (FoodTypeFlags.OmnivoreHuman & this.foodType) != FoodTypeFlags.None; + return (3903 & (int)this.foodType) != 0; } } @@ -75,32 +73,54 @@ public bool IsMeal { get { - return this.preferability >= FoodPreferability.MealAwful && this.preferability <= FoodPreferability.MealLavish; + return (int)this.preferability >= 5 && (int)this.preferability <= 8; } } - [DebuggerHidden] public IEnumerable ConfigErrors(ThingDef parentDef) { - IngestibleProperties.c__Iterator7E c__Iterator7E = new IngestibleProperties.c__Iterator7E(); - c__Iterator7E.parentDef = parentDef; - c__Iterator7E.<$>parentDef = parentDef; - c__Iterator7E.<>f__this = this; - IngestibleProperties.c__Iterator7E expr_1C = c__Iterator7E; - expr_1C.$PC = -2; - return expr_1C; + if (this.preferability == FoodPreferability.Undefined) + { + yield return "undefined preferability"; + } + if (this.foodType == FoodTypeFlags.None) + { + yield return "no foodType"; + } + if (this.nutrition == 0.0 && this.preferability != FoodPreferability.NeverForNutrition) + { + yield return "nutrition == 0 but preferability is " + this.preferability + " instead of " + FoodPreferability.NeverForNutrition; + } + if (!parentDef.IsCorpse && (int)this.preferability > 2 && !parentDef.socialPropernessMatters && parentDef.EverHaulable) + { + yield return "ingestible preferability > DesperateOnly but socialPropernessMatters=false. This will cause bugs wherein wardens will look in prison cells for food to give to prisoners and so will repeatedly pick up and drop food inside the cell."; + } + if (this.joy > 0.0 && this.joyKind == null) + { + yield return "joy > 0 with no joy kind"; + } } - [DebuggerHidden] internal IEnumerable SpecialDisplayStats(ThingDef parentDef) { - IngestibleProperties.c__Iterator7F c__Iterator7F = new IngestibleProperties.c__Iterator7F(); - c__Iterator7F.parentDef = parentDef; - c__Iterator7F.<$>parentDef = parentDef; - c__Iterator7F.<>f__this = this; - IngestibleProperties.c__Iterator7F expr_1C = c__Iterator7F; - expr_1C.$PC = -2; - return expr_1C; + if (!parentDef.IsCorpse) + { + yield return new StatDrawEntry(StatCategoryDefOf.Basics, "Nutrition".Translate(), this.nutrition.ToString("0.##"), 0); + } + if (this.joy > 0.0) + { + yield return new StatDrawEntry(StatCategoryDefOf.Basics, "Joy".Translate(), this.joy.ToStringPercent("F2") + " (" + this.JoyKind.label + ")", 0); + } + if (this.outcomeDoers != null) + { + for (int i = 0; i < this.outcomeDoers.Count; i++) + { + foreach (StatDrawEntry item in this.outcomeDoers[i].SpecialDisplayStats(parentDef)) + { + yield return item; + } + } + } } } } diff --git a/Assembly-CSharp/RimWorld/IngestionOutcomeDoer.cs b/Assembly-CSharp/RimWorld/IngestionOutcomeDoer.cs index bc9533789..ed5357d1e 100644 --- a/Assembly-CSharp/RimWorld/IngestionOutcomeDoer.cs +++ b/Assembly-CSharp/RimWorld/IngestionOutcomeDoer.cs @@ -1,6 +1,4 @@ -using System; using System.Collections.Generic; -using System.Diagnostics; using Verse; namespace RimWorld @@ -21,13 +19,9 @@ public void DoIngestionOutcome(Pawn pawn, Thing ingested) protected abstract void DoIngestionOutcomeSpecial(Pawn pawn, Thing ingested); - [DebuggerHidden] public virtual IEnumerable SpecialDisplayStats(ThingDef parentDef) { - IngestionOutcomeDoer.c__Iterator80 c__Iterator = new IngestionOutcomeDoer.c__Iterator80(); - IngestionOutcomeDoer.c__Iterator80 expr_07 = c__Iterator; - expr_07.$PC = -2; - return expr_07; + yield break; } } } diff --git a/Assembly-CSharp/RimWorld/IngestionOutcomeDoer_GiveHediff.cs b/Assembly-CSharp/RimWorld/IngestionOutcomeDoer_GiveHediff.cs index 487c697c7..b8a9771a5 100644 --- a/Assembly-CSharp/RimWorld/IngestionOutcomeDoer_GiveHediff.cs +++ b/Assembly-CSharp/RimWorld/IngestionOutcomeDoer_GiveHediff.cs @@ -1,6 +1,4 @@ -using System; using System.Collections.Generic; -using System.Diagnostics; using Verse; namespace RimWorld @@ -18,34 +16,25 @@ public class IngestionOutcomeDoer_GiveHediff : IngestionOutcomeDoer protected override void DoIngestionOutcomeSpecial(Pawn pawn, Thing ingested) { Hediff hediff = HediffMaker.MakeHediff(this.hediffDef, pawn, null); - float num; - if (this.severity > 0f) - { - num = this.severity; - } - else - { - num = this.hediffDef.initialSeverity; - } + float num = (!(this.severity > 0.0)) ? this.hediffDef.initialSeverity : this.severity; if (this.divideByBodySize) { num /= pawn.BodySize; } AddictionUtility.ModifyChemicalEffectForToleranceAndBodySize(pawn, this.toleranceChemical, ref num); hediff.Severity = num; - pawn.health.AddHediff(hediff, null, null); + pawn.health.AddHediff(hediff, null, default(DamageInfo?)); } - [DebuggerHidden] public override IEnumerable SpecialDisplayStats(ThingDef parentDef) { - IngestionOutcomeDoer_GiveHediff.c__Iterator81 c__Iterator = new IngestionOutcomeDoer_GiveHediff.c__Iterator81(); - c__Iterator.parentDef = parentDef; - c__Iterator.<$>parentDef = parentDef; - c__Iterator.<>f__this = this; - IngestionOutcomeDoer_GiveHediff.c__Iterator81 expr_1C = c__Iterator; - expr_1C.$PC = -2; - return expr_1C; + if (parentDef.IsDrug && base.chance >= 1.0) + { + foreach (StatDrawEntry item in this.hediffDef.SpecialDisplayStats()) + { + yield return item; + } + } } } } diff --git a/Assembly-CSharp/RimWorld/IngestionOutcomeDoer_OffsetNeed.cs b/Assembly-CSharp/RimWorld/IngestionOutcomeDoer_OffsetNeed.cs index 491bfe90f..b2ee0d245 100644 --- a/Assembly-CSharp/RimWorld/IngestionOutcomeDoer_OffsetNeed.cs +++ b/Assembly-CSharp/RimWorld/IngestionOutcomeDoer_OffsetNeed.cs @@ -1,6 +1,4 @@ -using System; using System.Collections.Generic; -using System.Diagnostics; using Verse; namespace RimWorld @@ -15,28 +13,21 @@ public class IngestionOutcomeDoer_OffsetNeed : IngestionOutcomeDoer protected override void DoIngestionOutcomeSpecial(Pawn pawn, Thing ingested) { - if (pawn.needs == null) + if (pawn.needs != null) { - return; + Need need = pawn.needs.TryGetNeed(this.need); + if (need != null) + { + float num = this.offset; + AddictionUtility.ModifyChemicalEffectForToleranceAndBodySize(pawn, this.toleranceChemical, ref num); + need.CurLevel += num; + } } - Need need = pawn.needs.TryGetNeed(this.need); - if (need == null) - { - return; - } - float num = this.offset; - AddictionUtility.ModifyChemicalEffectForToleranceAndBodySize(pawn, this.toleranceChemical, ref num); - need.CurLevel += num; } - [DebuggerHidden] public override IEnumerable SpecialDisplayStats(ThingDef parentDef) { - IngestionOutcomeDoer_OffsetNeed.c__Iterator82 c__Iterator = new IngestionOutcomeDoer_OffsetNeed.c__Iterator82(); - c__Iterator.<>f__this = this; - IngestionOutcomeDoer_OffsetNeed.c__Iterator82 expr_0E = c__Iterator; - expr_0E.$PC = -2; - return expr_0E; + yield return new StatDrawEntry(StatCategoryDefOf.Basics, this.need.LabelCap, this.offset.ToStringPercent(), 0); } } } diff --git a/Assembly-CSharp/RimWorld/InspectGizmoGrid.cs b/Assembly-CSharp/RimWorld/InspectGizmoGrid.cs index 4b78d6f9b..398ecb1c2 100644 --- a/Assembly-CSharp/RimWorld/InspectGizmoGrid.cs +++ b/Assembly-CSharp/RimWorld/InspectGizmoGrid.cs @@ -1,5 +1,6 @@ using System; using System.Collections.Generic; +using UnityEngine; using Verse; namespace RimWorld @@ -24,9 +25,9 @@ public static void DrawInspectGizmoGridFor(IEnumerable selectedObjects) ISelectable selectable = InspectGizmoGrid.objList[i] as ISelectable; if (selectable != null) { - foreach (Gizmo current in selectable.GetGizmos()) + foreach (Gizmo gizmo in selectable.GetGizmos()) { - InspectGizmoGrid.gizmoList.Add(current); + InspectGizmoGrid.gizmoList.Add(gizmo); } } } @@ -45,14 +46,13 @@ public static void DrawInspectGizmoGridFor(IEnumerable selectedObjects) command_Action.defaultLabel = des.LabelCapReverseDesignating(t); command_Action.icon = des.IconReverseDesignating(t); command_Action.defaultDesc = des.DescReverseDesignating(t); - command_Action.action = delegate + command_Action.action = (Action)delegate { - if (!TutorSystem.AllowAction(des.TutorTagDesignate)) + if (TutorSystem.AllowAction(des.TutorTagDesignate)) { - return; + des.DesignateThing(t); + des.Finalize(true); } - des.DesignateThing(t); - des.Finalize(true); }; command_Action.hotKey = des.hotKey; command_Action.groupKey = des.groupKey; @@ -61,7 +61,9 @@ public static void DrawInspectGizmoGridFor(IEnumerable selectedObjects) } } } - GizmoGridDrawer.DrawGizmoGrid(InspectGizmoGrid.gizmoList, InspectPaneUtility.PaneSize.x + 20f, out InspectGizmoGrid.mouseoverGizmo); + List gizmos = InspectGizmoGrid.gizmoList; + Vector2 paneSize = InspectPaneUtility.PaneSize; + GizmoGridDrawer.DrawGizmoGrid((IEnumerable)gizmos, (float)(paneSize.x + 20.0), out InspectGizmoGrid.mouseoverGizmo); } catch (Exception ex) { diff --git a/Assembly-CSharp/RimWorld/InspectPaneFiller.cs b/Assembly-CSharp/RimWorld/InspectPaneFiller.cs index 03b46dcaf..52faa5ac6 100644 --- a/Assembly-CSharp/RimWorld/InspectPaneFiller.cs +++ b/Assembly-CSharp/RimWorld/InspectPaneFiller.cs @@ -14,28 +14,15 @@ internal class InspectPaneFiller private const float BarSpacing = 6f; - private static readonly Texture2D MoodTex; + private static readonly Texture2D MoodTex = SolidColorMaterials.NewSolidColorTexture(new ColorInt(26, 52, 52).ToColor); - private static readonly Texture2D BarBGTex; + private static readonly Texture2D BarBGTex = SolidColorMaterials.NewSolidColorTexture(new ColorInt(10, 10, 10).ToColor); - private static readonly Texture2D HealthTex; + private static readonly Texture2D HealthTex = SolidColorMaterials.NewSolidColorTexture(new ColorInt(35, 35, 35).ToColor); - private static bool debug_inspectLengthWarned; + private static bool debug_inspectLengthWarned = false; - private static bool debug_inspectStringExceptionErrored; - - static InspectPaneFiller() - { - // Note: this type is marked as 'beforefieldinit'. - ColorInt colorInt = new ColorInt(26, 52, 52); - InspectPaneFiller.MoodTex = SolidColorMaterials.NewSolidColorTexture(colorInt.ToColor); - ColorInt colorInt2 = new ColorInt(10, 10, 10); - InspectPaneFiller.BarBGTex = SolidColorMaterials.NewSolidColorTexture(colorInt2.ToColor); - ColorInt colorInt3 = new ColorInt(35, 35, 35); - InspectPaneFiller.HealthTex = SolidColorMaterials.NewSolidColorTexture(colorInt3.ToColor); - InspectPaneFiller.debug_inspectLengthWarned = false; - InspectPaneFiller.debug_inspectStringExceptionErrored = false; - } + private static bool debug_inspectStringExceptionErrored = false; public static void DoPaneContentsFor(ISelectable sel, Rect rect) { @@ -47,7 +34,7 @@ public static void DoPaneContentsFor(ISelectable sel, Rect rect) Pawn pawn = sel as Pawn; if (thing != null) { - num += 3f; + num = (float)(num + 3.0); WidgetRow row = new WidgetRow(0f, num, UIDirection.RightThenUp, 99999f, 4f); InspectPaneFiller.DrawHealth(row, thing); if (pawn != null) @@ -59,19 +46,13 @@ public static void DoPaneContentsFor(ISelectable sel, Rect rect) } InspectPaneFiller.DrawAreaAllowed(row, pawn); } - num += 18f; + num = (float)(num + 18.0); } InspectPaneFiller.DrawInspectStringFor(sel, ref num); } catch (Exception ex) { - Log.ErrorOnce(string.Concat(new object[] - { - "Error in DoPaneContentsFor ", - Find.Selector.FirstSelectedObject, - ": ", - ex.ToString() - }), 754672); + Log.ErrorOnce("Error in DoPaneContentsFor " + Find.Selector.FirstSelectedObject + ": " + ex.ToString(), 754672); } finally { @@ -86,47 +67,46 @@ public static void DrawHealth(WidgetRow row, Thing t) string label; if (pawn == null) { - if (!t.def.useHitPoints) - { - return; - } - if (t.HitPoints >= t.MaxHitPoints) - { - GUI.color = Color.white; - } - else if ((float)t.HitPoints > (float)t.MaxHitPoints * 0.5f) - { - GUI.color = Color.yellow; - } - else if (t.HitPoints > 0) - { - GUI.color = Color.red; - } - else + if (t.def.useHitPoints) { - GUI.color = Color.grey; + if (t.HitPoints >= t.MaxHitPoints) + { + GUI.color = Color.white; + } + else if ((float)t.HitPoints > (float)t.MaxHitPoints * 0.5) + { + GUI.color = Color.yellow; + } + else if (t.HitPoints > 0) + { + GUI.color = Color.red; + } + else + { + GUI.color = Color.grey; + } + fillPct = (float)t.HitPoints / (float)t.MaxHitPoints; + label = t.HitPoints.ToStringCached() + " / " + t.MaxHitPoints.ToStringCached(); + goto IL_00e4; } - fillPct = (float)t.HitPoints / (float)t.MaxHitPoints; - label = t.HitPoints.ToStringCached() + " / " + t.MaxHitPoints.ToStringCached(); - } - else - { - GUI.color = Color.white; - fillPct = pawn.health.summaryHealth.SummaryHealthPercent; - label = HealthUtility.GetGeneralConditionLabel(pawn, true); + return; } + GUI.color = Color.white; + fillPct = pawn.health.summaryHealth.SummaryHealthPercent; + label = HealthUtility.GetGeneralConditionLabel(pawn, true); + goto IL_00e4; + IL_00e4: row.FillableBar(93f, 16f, fillPct, label, InspectPaneFiller.HealthTex, InspectPaneFiller.BarBGTex); GUI.color = Color.white; } private static void DrawMood(WidgetRow row, Pawn pawn) { - if (pawn.needs == null || pawn.needs.mood == null) + if (pawn.needs != null && pawn.needs.mood != null) { - return; + row.Gap(6f); + row.FillableBar(93f, 16f, pawn.needs.mood.CurLevelPercentage, pawn.needs.mood.MoodString.CapitalizeFirst(), InspectPaneFiller.MoodTex, InspectPaneFiller.BarBGTex); } - row.Gap(6f); - row.FillableBar(93f, 16f, pawn.needs.mood.CurLevelPercentage, pawn.needs.mood.MoodString.CapitalizeFirst(), InspectPaneFiller.MoodTex, InspectPaneFiller.BarBGTex); } private static void DrawTimetableSetting(WidgetRow row, Pawn pawn) @@ -137,38 +117,29 @@ private static void DrawTimetableSetting(WidgetRow row, Pawn pawn) private static void DrawAreaAllowed(WidgetRow row, Pawn pawn) { - if (pawn.playerSettings == null || !pawn.playerSettings.RespectsAllowedArea) + if (pawn.playerSettings != null && pawn.playerSettings.RespectsAllowedArea) { - return; - } - row.Gap(6f); - bool flag = pawn.playerSettings != null && pawn.playerSettings.AreaRestriction != null; - Texture2D fillTex; - if (flag) - { - fillTex = pawn.playerSettings.AreaRestriction.ColorTexture; - } - else - { - fillTex = BaseContent.GreyTex; - } - Rect rect = row.FillableBar(93f, 16f, 1f, AreaUtility.AreaAllowedLabel(pawn), fillTex, null); - if (Mouse.IsOver(rect)) - { - if (flag) + row.Gap(6f); + bool flag = pawn.playerSettings != null && pawn.playerSettings.AreaRestriction != null; + Texture2D fillTex = (!flag) ? BaseContent.GreyTex : pawn.playerSettings.AreaRestriction.ColorTexture; + Rect rect = row.FillableBar(93f, 16f, 1f, AreaUtility.AreaAllowedLabel(pawn), fillTex, null); + if (Mouse.IsOver(rect)) { - pawn.playerSettings.AreaRestriction.MarkForDraw(); + if (flag) + { + pawn.playerSettings.AreaRestriction.MarkForDraw(); + } + Rect rect2 = rect.ContractedBy(-1f); + Widgets.DrawBox(rect2, 1); } - Rect rect2 = rect.ContractedBy(-1f); - Widgets.DrawBox(rect2, 1); - } - if (Widgets.ButtonInvisible(rect, false)) - { - AllowedAreaMode mode = (!pawn.RaceProps.Humanlike) ? AllowedAreaMode.Animal : AllowedAreaMode.Humanlike; - AreaUtility.MakeAllowedAreaListFloatMenu(delegate(Area a) + if (Widgets.ButtonInvisible(rect, false)) { - pawn.playerSettings.AreaRestriction = a; - }, mode, true, true, pawn.Map); + AllowedAreaMode mode = (AllowedAreaMode)(pawn.RaceProps.Humanlike ? 1 : 2); + AreaUtility.MakeAllowedAreaListFloatMenu((Action)delegate(Area a) + { + pawn.playerSettings.AreaRestriction = a; + }, mode, true, true, pawn.Map); + } } } @@ -209,19 +180,10 @@ public static void DrawInspectStringFor(ISelectable sel, ref float y) if (Prefs.DevMode) { text = text.Trim(); - if (!InspectPaneFiller.debug_inspectLengthWarned) + if (!InspectPaneFiller.debug_inspectLengthWarned && text.Count((Func)((char f) => f == '\n')) > 5) { - if (text.Count((char f) => f == '\n') > 5) - { - Log.ErrorOnce(string.Concat(new object[] - { - sel, - " gave an inspect string over six lines (some may be empty):\n", - text, - "END" - }), 778772); - InspectPaneFiller.debug_inspectLengthWarned = true; - } + Log.ErrorOnce(sel + " gave an inspect string over six lines (some may be empty):\n" + text + "END", 778772); + InspectPaneFiller.debug_inspectLengthWarned = true; } } } @@ -229,7 +191,9 @@ public static void DrawInspectStringFor(ISelectable sel, ref float y) public static void DrawInspectString(string str, ref float y) { Text.Font = GameFont.Small; - Rect rect = new Rect(0f, y, InspectPaneUtility.PaneInnerSize.x, 200f); + float y2 = y; + Vector2 paneInnerSize = InspectPaneUtility.PaneInnerSize; + Rect rect = new Rect(0f, y2, paneInnerSize.x, 200f); Widgets.Label(rect, str); } } diff --git a/Assembly-CSharp/RimWorld/InspectPaneUtility.cs b/Assembly-CSharp/RimWorld/InspectPaneUtility.cs index 7d73f3520..edc516ad4 100644 --- a/Assembly-CSharp/RimWorld/InspectPaneUtility.cs +++ b/Assembly-CSharp/RimWorld/InspectPaneUtility.cs @@ -26,7 +26,7 @@ public static class InspectPaneUtility public static readonly Vector2 PaneSize = new Vector2(432f, 165f); - public static readonly Vector2 PaneInnerSize = new Vector2(InspectPaneUtility.PaneSize.x - 24f, InspectPaneUtility.PaneSize.y - 24f); + public static readonly Vector2 PaneInnerSize = new Vector2((float)(InspectPaneUtility.PaneSize.x - 24.0), (float)(InspectPaneUtility.PaneSize.y - 24.0)); private static List selectedThings = new List(); @@ -39,12 +39,20 @@ public static bool CanInspectTogether(object A, object B) { Thing thing = A as Thing; Thing thing2 = B as Thing; - return thing != null && thing2 != null && thing.def.category != ThingCategory.Pawn && thing.def == thing2.def; + if (thing != null && thing2 != null) + { + if (thing.def.category == ThingCategory.Pawn) + { + return false; + } + return thing.def == thing2.def; + } + return false; } public static string AdjustedLabelFor(IEnumerable selected, Rect rect) { - Zone zone = selected.First() as Zone; + Zone zone = selected.First() as Zone; string str; if (zone != null) { @@ -53,9 +61,9 @@ public static string AdjustedLabelFor(IEnumerable selected, Rect rect) else { InspectPaneUtility.selectedThings.Clear(); - foreach (object current in selected) + foreach (object item in selected) { - Thing thing = current as Thing; + Thing thing = item as Thing; if (thing != null) { InspectPaneUtility.selectedThings.Add(thing); @@ -70,7 +78,7 @@ public static string AdjustedLabelFor(IEnumerable selected, Rect rect) IEnumerable> source = from th in InspectPaneUtility.selectedThings group th by th.LabelCapNoCount into g select g; - if (source.Count>() > 1) + if (source.Count() > 1) { str = "VariousLabel".Translate(); } @@ -105,15 +113,12 @@ public static void ExtraOnGUI(IInspectPane pane) public static void UpdateTabs(IInspectPane pane) { bool flag = false; - foreach (InspectTabBase current in pane.CurTabs) + foreach (InspectTabBase curTab in pane.CurTabs) { - if (current.IsVisible) + if (curTab.IsVisible && curTab.GetType() == pane.OpenTabType) { - if (current.GetType() == pane.OpenTabType) - { - current.TabUpdate(); - flag = true; - } + curTab.TabUpdate(); + flag = true; } } if (!flag) @@ -124,7 +129,8 @@ public static void UpdateTabs(IInspectPane pane) public static void InspectPaneOnGUI(Rect inRect, IInspectPane pane) { - pane.RecentHeight = InspectPaneUtility.PaneSize.y; + Vector2 paneSize = InspectPaneUtility.PaneSize; + pane.RecentHeight = paneSize.y; if (pane.AnythingSelected) { try @@ -136,16 +142,13 @@ public static void InspectPaneOnGUI(Rect inRect, IInspectPane pane) float num = 0f; if (pane.ShouldShowSelectNextInCellButton) { - Rect rect2 = new Rect(rect.width - 24f, 0f, 24f, 24f); + Rect rect2 = new Rect((float)(rect.width - 24.0), 0f, 24f, 24f); if (Widgets.ButtonImage(rect2, TexButton.SelectOverlappingNext)) { pane.SelectNextInCell(); } - num += 24f; - TooltipHandler.TipRegion(rect2, "SelectNextInSquareTip".Translate(new object[] - { - KeyBindingDefOf.SelectNextInCell.MainKeyLabel - })); + num = (float)(num + 24.0); + TooltipHandler.TipRegion(rect2, "SelectNextInSquareTip".Translate(KeyBindingDefOf.SelectNextInCell.MainKeyLabel)); } pane.DoInspectPaneButtons(rect, ref num); Rect rect3 = new Rect(0f, 0f, rect.width - num, 50f); @@ -176,33 +179,33 @@ private static void DoTabs(IInspectPane pane) { try { - float y = pane.PaneTopY - 30f; + float y = (float)(pane.PaneTopY - 30.0); float num = 360f; float width = 0f; bool flag = false; - foreach (InspectTabBase current in pane.CurTabs) + foreach (InspectTabBase curTab in pane.CurTabs) { - if (current.IsVisible) + if (curTab.IsVisible) { Rect rect = new Rect(num, y, 72f, 30f); width = num; Text.Font = GameFont.Small; - if (Widgets.ButtonText(rect, current.labelKey.Translate(), true, false, true)) + if (Widgets.ButtonText(rect, curTab.labelKey.Translate(), true, false, true)) { - InspectPaneUtility.InterfaceToggleTab(current, pane); + InspectPaneUtility.InterfaceToggleTab(curTab, pane); } - bool flag2 = current.GetType() == pane.OpenTabType; - if (!flag2 && !current.TutorHighlightTagClosed.NullOrEmpty()) + bool flag2 = curTab.GetType() == pane.OpenTabType; + if (!flag2 && !curTab.TutorHighlightTagClosed.NullOrEmpty()) { - UIHighlighter.HighlightOpportunity(rect, current.TutorHighlightTagClosed); + UIHighlighter.HighlightOpportunity(rect, curTab.TutorHighlightTagClosed); } if (flag2) { - current.DoTabGUI(); + curTab.DoTabGUI(); pane.RecentHeight = 700f; flag = true; } - num -= 72f; + num = (float)(num - 72.0); } } if (flag) @@ -239,9 +242,7 @@ private static void ToggleTab(InspectTabBase tab, IInspectPane pane) private static void InterfaceToggleTab(InspectTabBase tab, IInspectPane pane) { if (TutorSystem.TutorialMode && !InspectPaneUtility.IsOpen(tab, pane) && !TutorSystem.AllowAction("ITab-" + tab.tutorTag + "-Open")) - { return; - } InspectPaneUtility.ToggleTab(tab, pane); } } diff --git a/Assembly-CSharp/RimWorld/InstallBlueprintUtility.cs b/Assembly-CSharp/RimWorld/InstallBlueprintUtility.cs index 03eb9cfcc..8600c348c 100644 --- a/Assembly-CSharp/RimWorld/InstallBlueprintUtility.cs +++ b/Assembly-CSharp/RimWorld/InstallBlueprintUtility.cs @@ -1,4 +1,3 @@ -using System; using System.Collections.Generic; using Verse; diff --git a/Assembly-CSharp/RimWorld/InstallationDesignatorDatabase.cs b/Assembly-CSharp/RimWorld/InstallationDesignatorDatabase.cs index 4cfd3cb5c..fa4736bb0 100644 --- a/Assembly-CSharp/RimWorld/InstallationDesignatorDatabase.cs +++ b/Assembly-CSharp/RimWorld/InstallationDesignatorDatabase.cs @@ -1,4 +1,3 @@ -using System; using System.Collections.Generic; using Verse; @@ -10,7 +9,7 @@ public static class InstallationDesignatorDatabase public static Designator_Install DesignatorFor(ThingDef artDef) { - Designator_Install designator_Install; + Designator_Install designator_Install = default(Designator_Install); if (InstallationDesignatorDatabase.designators.TryGetValue(artDef, out designator_Install)) { return designator_Install; @@ -22,10 +21,9 @@ public static Designator_Install DesignatorFor(ThingDef artDef) private static Designator_Install NewDesignatorFor(ThingDef artDef) { - return new Designator_Install - { - hotKey = KeyBindingDefOf.Misc1 - }; + Designator_Install designator_Install = new Designator_Install(); + designator_Install.hotKey = KeyBindingDefOf.Misc1; + return designator_Install; } } } diff --git a/Assembly-CSharp/RimWorld/InstructionDef.cs b/Assembly-CSharp/RimWorld/InstructionDef.cs index 91bbc99b7..5391c5257 100644 --- a/Assembly-CSharp/RimWorld/InstructionDef.cs +++ b/Assembly-CSharp/RimWorld/InstructionDef.cs @@ -1,6 +1,5 @@ using System; using System.Collections.Generic; -using System.Diagnostics; using Verse; namespace RimWorld @@ -45,14 +44,24 @@ public class InstructionDef : Def public bool resetBuildDesignatorStuffs; - [DebuggerHidden] public override IEnumerable ConfigErrors() { - InstructionDef.c__Iterator9F c__Iterator9F = new InstructionDef.c__Iterator9F(); - c__Iterator9F.<>f__this = this; - InstructionDef.c__Iterator9F expr_0E = c__Iterator9F; - expr_0E.$PC = -2; - return expr_0E; + foreach (string item in base.ConfigErrors()) + { + yield return item; + } + if (this.instructionClass == null) + { + yield return "no instruction class"; + } + if (this.text.NullOrEmpty()) + { + yield return "no text"; + } + if (this.eventTagInitiate.NullOrEmpty()) + { + yield return "no eventTagInitiate"; + } } } } diff --git a/Assembly-CSharp/RimWorld/Instruction_AddBill.cs b/Assembly-CSharp/RimWorld/Instruction_AddBill.cs index 843e4b2a9..1d9d93896 100644 --- a/Assembly-CSharp/RimWorld/Instruction_AddBill.cs +++ b/Assembly-CSharp/RimWorld/Instruction_AddBill.cs @@ -1,6 +1,5 @@ using System; using System.Collections.Generic; -using System.Diagnostics; using System.Linq; using Verse; @@ -12,7 +11,7 @@ protected override float ProgressPercent { get { - int num = this.def.recipeTargetCount + 1; + int num = base.def.recipeTargetCount + 1; int num2 = 0; Bill_Production bill_Production = this.RelevantBill(); if (bill_Production != null) @@ -29,32 +28,32 @@ protected override float ProgressPercent private Bill_Production RelevantBill() { - if (Find.Selector.SingleSelectedThing != null && Find.Selector.SingleSelectedThing.def == this.def.thingDef) + if (Find.Selector.SingleSelectedThing != null && Find.Selector.SingleSelectedThing.def == base.def.thingDef) { IBillGiver billGiver = Find.Selector.SingleSelectedThing as IBillGiver; if (billGiver != null) { - return (Bill_Production)billGiver.BillStack.Bills.FirstOrDefault((Bill b) => b.recipe == this.def.recipeDef); + return (Bill_Production)billGiver.BillStack.Bills.FirstOrDefault((Func)((Bill b) => b.recipe == base.def.recipeDef)); } } return null; } - [DebuggerHidden] private IEnumerable ThingsToSelect() { - Instruction_AddBill.c__Iterator1A4 c__Iterator1A = new Instruction_AddBill.c__Iterator1A4(); - c__Iterator1A.<>f__this = this; - Instruction_AddBill.c__Iterator1A4 expr_0E = c__Iterator1A; - expr_0E.$PC = -2; - return expr_0E; + if (Find.Selector.SingleSelectedThing != null && Find.Selector.SingleSelectedThing.def == base.def.thingDef) + yield break; + foreach (Building item in base.Map.listerBuildings.AllBuildingsColonistOfDef(base.def.thingDef)) + { + yield return (Thing)item; + } } public override void LessonOnGUI() { - foreach (Thing current in this.ThingsToSelect()) + foreach (Thing item in this.ThingsToSelect()) { - TutorUtility.DrawLabelOnThingOnGUI(current, this.def.onMapInstruction); + TutorUtility.DrawLabelOnThingOnGUI(item, base.def.onMapInstruction); } if (this.RelevantBill() == null) { @@ -65,11 +64,11 @@ public override void LessonOnGUI() public override void LessonUpdate() { - foreach (Thing current in this.ThingsToSelect()) + foreach (Thing item in this.ThingsToSelect()) { - GenDraw.DrawArrowPointingAt(current.DrawPos, false); + GenDraw.DrawArrowPointingAt(item.DrawPos, false); } - if (this.ProgressPercent > 0.999f) + if (this.ProgressPercent > 0.99900001287460327) { Find.ActiveLesson.Deactivate(); } diff --git a/Assembly-CSharp/RimWorld/Instruction_Basic.cs b/Assembly-CSharp/RimWorld/Instruction_Basic.cs index 225a67398..db01a4e86 100644 --- a/Assembly-CSharp/RimWorld/Instruction_Basic.cs +++ b/Assembly-CSharp/RimWorld/Instruction_Basic.cs @@ -1,5 +1,3 @@ -using System; - namespace RimWorld { public class Instruction_Basic : Lesson_Instruction diff --git a/Assembly-CSharp/RimWorld/Instruction_BuildAtRoom.cs b/Assembly-CSharp/RimWorld/Instruction_BuildAtRoom.cs index 3405a6459..22ad30eeb 100644 --- a/Assembly-CSharp/RimWorld/Instruction_BuildAtRoom.cs +++ b/Assembly-CSharp/RimWorld/Instruction_BuildAtRoom.cs @@ -1,4 +1,3 @@ -using System; using Verse; namespace RimWorld @@ -14,20 +13,20 @@ protected override float ProgressPercent { get { - if (this.def.targetCount <= 1) + if (base.def.targetCount <= 1) { return -1f; } - return (float)this.NumPlaced() / (float)this.def.targetCount; + return (float)this.NumPlaced() / (float)base.def.targetCount; } } protected int NumPlaced() { int num = 0; - foreach (IntVec3 current in this.BuildableRect) + foreach (IntVec3 item in this.BuildableRect) { - if (TutorUtility.BuildingOrBlueprintOrFrameCenterExists(current, base.Map, this.def.thingDef)) + if (TutorUtility.BuildingOrBlueprintOrFrameCenterExists(item, base.Map, base.def.thingDef)) { num++; } @@ -37,7 +36,7 @@ protected int NumPlaced() public override void LessonOnGUI() { - TutorUtility.DrawCellRectOnGUI(this.BuildableRect.ContractedBy(1), this.def.onMapInstruction); + TutorUtility.DrawCellRectOnGUI(this.BuildableRect.ContractedBy(1), base.def.onMapInstruction); base.LessonOnGUI(); } @@ -48,7 +47,7 @@ public override void LessonUpdate() public override AcceptanceReport AllowAction(EventPack ep) { - if (ep.Tag == "Designate-" + this.def.thingDef.defName) + if (ep.Tag == "Designate-" + base.def.thingDef.defName) { return this.AllowBuildAt(ep.Cell); } @@ -62,7 +61,7 @@ protected virtual bool AllowBuildAt(IntVec3 c) public override void Notify_Event(EventPack ep) { - if (this.NumPlaced() >= this.def.targetCount) + if (this.NumPlaced() >= base.def.targetCount) { Find.ActiveLesson.Deactivate(); } diff --git a/Assembly-CSharp/RimWorld/Instruction_BuildInRoom.cs b/Assembly-CSharp/RimWorld/Instruction_BuildInRoom.cs index 67648fd8f..9b8ba3eec 100644 --- a/Assembly-CSharp/RimWorld/Instruction_BuildInRoom.cs +++ b/Assembly-CSharp/RimWorld/Instruction_BuildInRoom.cs @@ -1,4 +1,3 @@ -using System; using Verse; namespace RimWorld diff --git a/Assembly-CSharp/RimWorld/Instruction_BuildNearRoom.cs b/Assembly-CSharp/RimWorld/Instruction_BuildNearRoom.cs index c6c854492..a0ca82a6f 100644 --- a/Assembly-CSharp/RimWorld/Instruction_BuildNearRoom.cs +++ b/Assembly-CSharp/RimWorld/Instruction_BuildNearRoom.cs @@ -1,4 +1,3 @@ -using System; using Verse; namespace RimWorld @@ -15,7 +14,11 @@ protected override CellRect BuildableRect protected override bool AllowBuildAt(IntVec3 c) { - return base.AllowBuildAt(c) && !Find.TutorialState.roomRect.Contains(c); + if (!base.AllowBuildAt(c)) + { + return false; + } + return !Find.TutorialState.roomRect.Contains(c); } } } diff --git a/Assembly-CSharp/RimWorld/Instruction_BuildRoomDoor.cs b/Assembly-CSharp/RimWorld/Instruction_BuildRoomDoor.cs index d8b88e20e..437a124ef 100644 --- a/Assembly-CSharp/RimWorld/Instruction_BuildRoomDoor.cs +++ b/Assembly-CSharp/RimWorld/Instruction_BuildRoomDoor.cs @@ -20,13 +20,69 @@ private CellRect RoomRect public override void OnActivated() { base.OnActivated(); - this.allowedPlaceCells = this.RoomRect.EdgeCells.ToList(); - this.allowedPlaceCells.RemoveAll((IntVec3 c) => (c.x == this.RoomRect.minX && c.z == this.RoomRect.minZ) || (c.x == this.RoomRect.minX && c.z == this.RoomRect.maxZ) || (c.x == this.RoomRect.maxX && c.z == this.RoomRect.minZ) || (c.x == this.RoomRect.maxX && c.z == this.RoomRect.maxZ)); + this.allowedPlaceCells = this.RoomRect.EdgeCells.ToList(); + this.allowedPlaceCells.RemoveAll((Predicate)delegate(IntVec3 c) + { + int x = c.x; + CellRect roomRect = this.RoomRect; + if (x == roomRect.minX) + { + int z = c.z; + CellRect roomRect2 = this.RoomRect; + if (z != roomRect2.minZ) + goto IL_0034; + goto IL_00d6; + } + goto IL_0034; + IL_00d6: + int result = 1; + goto IL_00d7; + IL_0034: + int x2 = c.x; + CellRect roomRect3 = this.RoomRect; + if (x2 == roomRect3.minX) + { + int z2 = c.z; + CellRect roomRect4 = this.RoomRect; + if (z2 != roomRect4.maxZ) + goto IL_0068; + goto IL_00d6; + } + goto IL_0068; + IL_009e: + int x3 = c.x; + CellRect roomRect5 = this.RoomRect; + if (x3 == roomRect5.maxX) + { + int z3 = c.z; + CellRect roomRect6 = this.RoomRect; + result = ((z3 == roomRect6.maxZ) ? 1 : 0); + } + else + { + result = 0; + } + goto IL_00d7; + IL_0068: + int x4 = c.x; + CellRect roomRect7 = this.RoomRect; + if (x4 == roomRect7.maxX) + { + int z4 = c.z; + CellRect roomRect8 = this.RoomRect; + if (z4 != roomRect8.minZ) + goto IL_009e; + goto IL_00d6; + } + goto IL_009e; + IL_00d7: + return (byte)result != 0; + }); } public override void LessonOnGUI() { - TutorUtility.DrawCellRectOnGUI(this.RoomRect, this.def.onMapInstruction); + TutorUtility.DrawCellRectOnGUI(this.RoomRect, base.def.onMapInstruction); base.LessonOnGUI(); } diff --git a/Assembly-CSharp/RimWorld/Instruction_BuildRoomWalls.cs b/Assembly-CSharp/RimWorld/Instruction_BuildRoomWalls.cs index 83d681495..c0bb6a944 100644 --- a/Assembly-CSharp/RimWorld/Instruction_BuildRoomWalls.cs +++ b/Assembly-CSharp/RimWorld/Instruction_BuildRoomWalls.cs @@ -27,9 +27,9 @@ protected override float ProgressPercent { int num = 0; int num2 = 0; - foreach (IntVec3 current in this.RoomRect.EdgeCells) + foreach (IntVec3 edgeCell in this.RoomRect.EdgeCells) { - if (TutorUtility.BuildingOrBlueprintOrFrameCenterExists(current, base.Map, ThingDefOf.Wall)) + if (TutorUtility.BuildingOrBlueprintOrFrameCenterExists(edgeCell, base.Map, ThingDefOf.Wall)) { num2++; } @@ -47,7 +47,7 @@ public override void OnActivated() public override void LessonOnGUI() { - TutorUtility.DrawCellRectOnGUI(this.RoomRect, this.def.onMapInstruction); + TutorUtility.DrawCellRectOnGUI(this.RoomRect, base.def.onMapInstruction); base.LessonOnGUI(); } @@ -56,12 +56,12 @@ public override void LessonUpdate() this.cachedEdgeCells.Clear(); this.cachedEdgeCells.AddRange((from c in this.RoomRect.EdgeCells where !TutorUtility.BuildingOrBlueprintOrFrameCenterExists(c, base.Map, ThingDefOf.Wall) - select c).ToList()); + select c).ToList()); GenDraw.DrawFieldEdges((from c in this.cachedEdgeCells where c.GetEdifice(base.Map) == null - select c).ToList()); + select c).ToList()); GenDraw.DrawArrowPointingAt(this.RoomRect.CenterVector3, false); - if (this.ProgressPercent > 0.9999f) + if (this.ProgressPercent > 0.99989998340606689) { Find.ActiveLesson.Deactivate(); } diff --git a/Assembly-CSharp/RimWorld/Instruction_BuildSandbags.cs b/Assembly-CSharp/RimWorld/Instruction_BuildSandbags.cs index 81757cbdf..f620bab6c 100644 --- a/Assembly-CSharp/RimWorld/Instruction_BuildSandbags.cs +++ b/Assembly-CSharp/RimWorld/Instruction_BuildSandbags.cs @@ -15,13 +15,22 @@ protected override float ProgressPercent { int num = 0; int num2 = 0; - foreach (IntVec3 current in this.sandbagCells) + List.Enumerator enumerator = this.sandbagCells.GetEnumerator(); + try { - if (TutorUtility.BuildingOrBlueprintOrFrameCenterExists(current, base.Map, ThingDefOf.Sandbags)) + while (enumerator.MoveNext()) { - num2++; + IntVec3 current = enumerator.Current; + if (TutorUtility.BuildingOrBlueprintOrFrameCenterExists(current, base.Map, ThingDefOf.Sandbags)) + { + num2++; + } + num++; } - num++; + } + finally + { + ((IDisposable)(object)enumerator).Dispose(); } return (float)num2 / (float)num; } @@ -32,22 +41,30 @@ public override void OnActivated() base.OnActivated(); Find.TutorialState.sandbagsRect = TutorUtility.FindUsableRect(7, 7, base.Map, 0f, false); this.sandbagCells = new List(); - foreach (IntVec3 current in Find.TutorialState.sandbagsRect.EdgeCells) + foreach (IntVec3 edgeCell in Find.TutorialState.sandbagsRect.EdgeCells) { - if (current.x != Find.TutorialState.sandbagsRect.CenterCell.x && current.z != Find.TutorialState.sandbagsRect.CenterCell.z) + IntVec3 current = edgeCell; + int x = current.x; + IntVec3 centerCell = Find.TutorialState.sandbagsRect.CenterCell; + if (x != centerCell.x) { - this.sandbagCells.Add(current); + int z = current.z; + IntVec3 centerCell2 = Find.TutorialState.sandbagsRect.CenterCell; + if (z != centerCell2.z) + { + this.sandbagCells.Add(current); + } } } - foreach (IntVec3 current2 in Find.TutorialState.sandbagsRect.ContractedBy(1)) + foreach (IntVec3 item in Find.TutorialState.sandbagsRect.ContractedBy(1)) { - if (!Find.TutorialState.sandbagsRect.ContractedBy(2).Contains(current2)) + if (!Find.TutorialState.sandbagsRect.ContractedBy(2).Contains(item)) { - List thingList = current2.GetThingList(base.Map); - for (int i = thingList.Count - 1; i >= 0; i--) + List thingList = item.GetThingList(base.Map); + for (int num = thingList.Count - 1; num >= 0; num--) { - Thing thing = thingList[i]; - if (thing.def.passability != Traversability.Standable && (thing.def.category == ThingCategory.Plant || thing.def.category == ThingCategory.Item)) + Thing thing = thingList[num]; + if (thing.def.passability != 0 && (thing.def.category == ThingCategory.Plant || thing.def.category == ThingCategory.Item)) { thing.Destroy(DestroyMode.Vanish); } @@ -64,7 +81,7 @@ public override void ExposeData() public override void LessonOnGUI() { - TutorUtility.DrawLabelOnGUI(Gen.AveragePosition(this.sandbagCells), this.def.onMapInstruction); + TutorUtility.DrawLabelOnGUI(Gen.AveragePosition(this.sandbagCells), base.def.onMapInstruction); base.LessonOnGUI(); } @@ -72,10 +89,10 @@ public override void LessonUpdate() { List cells = (from c in this.sandbagCells where !TutorUtility.BuildingOrBlueprintOrFrameCenterExists(c, base.Map, ThingDefOf.Sandbags) - select c).ToList(); + select c).ToList(); GenDraw.DrawFieldEdges(cells); GenDraw.DrawArrowPointingAt(Gen.AveragePosition(this.sandbagCells), false); - if (this.ProgressPercent > 0.9999f) + if (this.ProgressPercent > 0.99989998340606689) { Find.ActiveLesson.Deactivate(); } diff --git a/Assembly-CSharp/RimWorld/Instruction_ChopWood.cs b/Assembly-CSharp/RimWorld/Instruction_ChopWood.cs index b96677a3b..e89ea03f8 100644 --- a/Assembly-CSharp/RimWorld/Instruction_ChopWood.cs +++ b/Assembly-CSharp/RimWorld/Instruction_ChopWood.cs @@ -12,13 +12,13 @@ protected override float ProgressPercent { return (float)(from d in base.Map.designationManager.SpawnedDesignationsOfDef(DesignationDefOf.HarvestPlant) where d.target.Thing.def.plant.IsTree - select d).Count() / (float)this.def.targetCount; + select d).Count() / (float)base.def.targetCount; } } public override void LessonUpdate() { - if (this.ProgressPercent > 0.999f) + if (this.ProgressPercent > 0.99900001287460327) { Find.ActiveLesson.Deactivate(); } diff --git a/Assembly-CSharp/RimWorld/Instruction_DownRaider.cs b/Assembly-CSharp/RimWorld/Instruction_DownRaider.cs index 314373124..e61d19280 100644 --- a/Assembly-CSharp/RimWorld/Instruction_DownRaider.cs +++ b/Assembly-CSharp/RimWorld/Instruction_DownRaider.cs @@ -21,11 +21,19 @@ public override void OnActivated() base.OnActivated(); CellRect cellRect = Find.TutorialState.sandbagsRect.ContractedBy(1); this.coverCells = new List(); - foreach (IntVec3 current in cellRect.EdgeCells) + foreach (IntVec3 edgeCell in cellRect.EdgeCells) { - if (current.x != cellRect.CenterCell.x && current.z != cellRect.CenterCell.z) + IntVec3 current = edgeCell; + int x = current.x; + IntVec3 centerCell = cellRect.CenterCell; + if (x != centerCell.x) { - this.coverCells.Add(current); + int z = current.z; + IntVec3 centerCell2 = cellRect.CenterCell; + if (z != centerCell2.z) + { + this.coverCells.Add(current); + } } } IncidentParms incidentParms = new IncidentParms(); @@ -40,9 +48,9 @@ public override void OnActivated() private bool AllColonistsInCover() { - foreach (Pawn current in base.Map.mapPawns.FreeColonistsSpawned) + foreach (Pawn item in base.Map.mapPawns.FreeColonistsSpawned) { - if (!this.coverCells.Contains(current.Position)) + if (!this.coverCells.Contains(item.Position)) { return false; } @@ -54,7 +62,7 @@ public override void LessonOnGUI() { if (!this.AllColonistsInCover()) { - TutorUtility.DrawCellRectOnGUI(Find.TutorialState.sandbagsRect, this.def.onMapInstruction); + TutorUtility.DrawCellRectOnGUI(Find.TutorialState.sandbagsRect, base.def.onMapInstruction); } base.LessonOnGUI(); } @@ -70,19 +78,19 @@ public override void LessonUpdate() } } IEnumerable source = base.Map.mapPawns.PawnsInFaction(Faction.OfPlayer); - if (source.Any((Pawn p) => p.Downed)) + if (source.Any((Func)((Pawn p) => p.Downed))) { - foreach (Pawn current in base.Map.mapPawns.AllPawns) + foreach (Pawn allPawn in base.Map.mapPawns.AllPawns) { - if (current.HostileTo(Faction.OfPlayer)) + if (allPawn.HostileTo(Faction.OfPlayer)) { - HealthUtility.DamageUntilDowned(current); + HealthUtility.DamageUntilDowned(allPawn); } } } if ((from p in base.Map.mapPawns.AllPawnsSpawned where p.HostileTo(Faction.OfPlayer) && !p.Downed - select p).Count() == 0) + select p).Count() == 0) { Find.ActiveLesson.Deactivate(); } diff --git a/Assembly-CSharp/RimWorld/Instruction_EquipWeapons.cs b/Assembly-CSharp/RimWorld/Instruction_EquipWeapons.cs index 534462295..8c3d3598b 100644 --- a/Assembly-CSharp/RimWorld/Instruction_EquipWeapons.cs +++ b/Assembly-CSharp/RimWorld/Instruction_EquipWeapons.cs @@ -13,7 +13,7 @@ protected override float ProgressPercent { return (float)(from c in base.Map.mapPawns.FreeColonists where c.equipment.Primary != null - select c).Count() / (float)base.Map.mapPawns.FreeColonistsCount; + select c).Count() / (float)base.Map.mapPawns.FreeColonistsCount; } } @@ -29,25 +29,25 @@ where Instruction_EquipWeapons.IsWeapon(it) && it.Spawned public static bool IsWeapon(Thing t) { - return t.def.IsWeapon && t.def.BaseMarketValue > 30f; + return t.def.IsWeapon && t.def.BaseMarketValue > 30.0; } public override void LessonOnGUI() { - foreach (Thing current in this.Weapons) + foreach (Thing weapon in this.Weapons) { - TutorUtility.DrawLabelOnThingOnGUI(current, this.def.onMapInstruction); + TutorUtility.DrawLabelOnThingOnGUI(weapon, base.def.onMapInstruction); } base.LessonOnGUI(); } public override void LessonUpdate() { - foreach (Thing current in this.Weapons) + foreach (Thing weapon in this.Weapons) { - GenDraw.DrawArrowPointingAt(current.DrawPos, true); + GenDraw.DrawArrowPointingAt(weapon.DrawPos, true); } - if (this.ProgressPercent > 0.9999f) + if (this.ProgressPercent > 0.99989998340606689) { Find.ActiveLesson.Deactivate(); } diff --git a/Assembly-CSharp/RimWorld/Instruction_ExpandArea.cs b/Assembly-CSharp/RimWorld/Instruction_ExpandArea.cs index 510eab98b..b08f197d6 100644 --- a/Assembly-CSharp/RimWorld/Instruction_ExpandArea.cs +++ b/Assembly-CSharp/RimWorld/Instruction_ExpandArea.cs @@ -1,4 +1,3 @@ -using System; using Verse; namespace RimWorld @@ -16,7 +15,7 @@ protected override float ProgressPercent { get { - return (float)(this.MyArea.TrueCount - this.startingAreaCount) / (float)this.def.targetCount; + return (float)(this.MyArea.TrueCount - this.startingAreaCount) / (float)base.def.targetCount; } } @@ -34,7 +33,7 @@ public override void ExposeData() public override void LessonUpdate() { - if (this.ProgressPercent > 0.999f) + if (this.ProgressPercent > 0.99900001287460327) { Find.ActiveLesson.Deactivate(); } diff --git a/Assembly-CSharp/RimWorld/Instruction_ExpandAreaBuildRoof.cs b/Assembly-CSharp/RimWorld/Instruction_ExpandAreaBuildRoof.cs index 53a2d1060..a2efdbd2c 100644 --- a/Assembly-CSharp/RimWorld/Instruction_ExpandAreaBuildRoof.cs +++ b/Assembly-CSharp/RimWorld/Instruction_ExpandAreaBuildRoof.cs @@ -1,4 +1,3 @@ -using System; using Verse; namespace RimWorld diff --git a/Assembly-CSharp/RimWorld/Instruction_ExpandAreaHome.cs b/Assembly-CSharp/RimWorld/Instruction_ExpandAreaHome.cs index 8041fc49c..600d407bb 100644 --- a/Assembly-CSharp/RimWorld/Instruction_ExpandAreaHome.cs +++ b/Assembly-CSharp/RimWorld/Instruction_ExpandAreaHome.cs @@ -1,4 +1,3 @@ -using System; using Verse; namespace RimWorld diff --git a/Assembly-CSharp/RimWorld/Instruction_FinishConstruction.cs b/Assembly-CSharp/RimWorld/Instruction_FinishConstruction.cs index fbce87e51..856d3ca29 100644 --- a/Assembly-CSharp/RimWorld/Instruction_FinishConstruction.cs +++ b/Assembly-CSharp/RimWorld/Instruction_FinishConstruction.cs @@ -15,13 +15,13 @@ protected override float ProgressPercent { if (this.initialBlueprintsCount < 0) { - this.initialBlueprintsCount = this.ConstructionNeeders().Count(); + this.initialBlueprintsCount = this.ConstructionNeeders().Count(); } if (this.initialBlueprintsCount == 0) { return 1f; } - return 1f - (float)this.ConstructionNeeders().Count() / (float)this.initialBlueprintsCount; + return (float)(1.0 - (float)this.ConstructionNeeders().Count() / (float)this.initialBlueprintsCount); } } @@ -35,14 +35,14 @@ private IEnumerable ConstructionNeeders() public override void LessonUpdate() { base.LessonUpdate(); - if (this.ConstructionNeeders().Count() < 3) + if (this.ConstructionNeeders().Count() < 3) { - foreach (Thing current in this.ConstructionNeeders()) + foreach (Thing item in this.ConstructionNeeders()) { - GenDraw.DrawArrowPointingAt(current.DrawPos, false); + GenDraw.DrawArrowPointingAt(item.DrawPos, false); } } - if (this.ProgressPercent > 0.9999f) + if (this.ProgressPercent > 0.99989998340606689) { Find.ActiveLesson.Deactivate(); } diff --git a/Assembly-CSharp/RimWorld/Instruction_LearnConcept.cs b/Assembly-CSharp/RimWorld/Instruction_LearnConcept.cs index 6a8e740a5..a0e0d5e98 100644 --- a/Assembly-CSharp/RimWorld/Instruction_LearnConcept.cs +++ b/Assembly-CSharp/RimWorld/Instruction_LearnConcept.cs @@ -1,4 +1,3 @@ -using System; using Verse; namespace RimWorld @@ -9,20 +8,20 @@ protected override float ProgressPercent { get { - return PlayerKnowledgeDatabase.GetKnowledge(this.def.concept); + return PlayerKnowledgeDatabase.GetKnowledge(base.def.concept); } } public override void OnActivated() { - PlayerKnowledgeDatabase.SetKnowledge(this.def.concept, 0f); + PlayerKnowledgeDatabase.SetKnowledge(base.def.concept, 0f); base.OnActivated(); } public override void LessonUpdate() { base.LessonUpdate(); - if (PlayerKnowledgeDatabase.IsComplete(this.def.concept)) + if (PlayerKnowledgeDatabase.IsComplete(base.def.concept)) { Find.ActiveLesson.Deactivate(); } diff --git a/Assembly-CSharp/RimWorld/Instruction_MineSteel.cs b/Assembly-CSharp/RimWorld/Instruction_MineSteel.cs index c87eb8b32..2d5cf2845 100644 --- a/Assembly-CSharp/RimWorld/Instruction_MineSteel.cs +++ b/Assembly-CSharp/RimWorld/Instruction_MineSteel.cs @@ -1,4 +1,3 @@ -using System; using System.Collections.Generic; using Verse; @@ -35,26 +34,25 @@ public override void OnActivated() { base.OnActivated(); CellRect cellRect = TutorUtility.FindUsableRect(10, 10, base.Map, 0f, true); - new GenStep_ScatterLumpsMineable - { - forcedDefToScatter = ThingDefOf.MineableSteel - }.ForceScatterAt(cellRect.CenterCell, base.Map); + GenStep_ScatterLumpsMineable genStep_ScatterLumpsMineable = new GenStep_ScatterLumpsMineable(); + genStep_ScatterLumpsMineable.forcedDefToScatter = ThingDefOf.MineableSteel; + genStep_ScatterLumpsMineable.ForceScatterAt(cellRect.CenterCell, base.Map); this.mineCells = new List(); - foreach (IntVec3 current in cellRect) + foreach (IntVec3 item in cellRect) { - Building edifice = current.GetEdifice(base.Map); + Building edifice = item.GetEdifice(base.Map); if (edifice != null && edifice.def == ThingDefOf.MineableSteel) { - this.mineCells.Add(current); + this.mineCells.Add(item); } } } public override void LessonOnGUI() { - if (!this.mineCells.NullOrEmpty()) + if (!this.mineCells.NullOrEmpty()) { - TutorUtility.DrawLabelOnGUI(Gen.AveragePosition(this.mineCells), this.def.onMapInstruction); + TutorUtility.DrawLabelOnGUI(Gen.AveragePosition(this.mineCells), base.def.onMapInstruction); } base.LessonOnGUI(); } @@ -75,7 +73,7 @@ public override AcceptanceReport AllowAction(EventPack ep) public override void Notify_Event(EventPack ep) { - if (ep.Tag == "Designate-Mine" && this.ProgressPercent > 0.999f) + if (ep.Tag == "Designate-Mine" && this.ProgressPercent > 0.99900001287460327) { Find.ActiveLesson.Deactivate(); } diff --git a/Assembly-CSharp/RimWorld/Instruction_PlaceGrowingZone.cs b/Assembly-CSharp/RimWorld/Instruction_PlaceGrowingZone.cs index 21874e7e0..c494e32b2 100644 --- a/Assembly-CSharp/RimWorld/Instruction_PlaceGrowingZone.cs +++ b/Assembly-CSharp/RimWorld/Instruction_PlaceGrowingZone.cs @@ -1,4 +1,3 @@ -using System; using System.Collections.Generic; using System.Linq; using Verse; @@ -21,12 +20,12 @@ public override void OnActivated() { base.OnActivated(); this.growingZoneRect = TutorUtility.FindUsableRect(10, 8, base.Map, 0.5f, false); - this.cachedCells = this.growingZoneRect.Cells.ToList(); + this.cachedCells = this.growingZoneRect.Cells.ToList(); } public override void LessonOnGUI() { - TutorUtility.DrawCellRectOnGUI(this.growingZoneRect, this.def.onMapInstruction); + TutorUtility.DrawCellRectOnGUI(this.growingZoneRect, base.def.onMapInstruction); base.LessonOnGUI(); } diff --git a/Assembly-CSharp/RimWorld/Instruction_PlaceStockpile.cs b/Assembly-CSharp/RimWorld/Instruction_PlaceStockpile.cs index e12d8a14c..33aa1e354 100644 --- a/Assembly-CSharp/RimWorld/Instruction_PlaceStockpile.cs +++ b/Assembly-CSharp/RimWorld/Instruction_PlaceStockpile.cs @@ -1,4 +1,3 @@ -using System; using System.Collections.Generic; using System.Linq; using Verse; @@ -23,7 +22,7 @@ public override void ExposeData() private void RecacheCells() { - this.cachedCells = this.stockpileRect.Cells.ToList(); + this.cachedCells = this.stockpileRect.Cells.ToList(); } public override void OnActivated() @@ -35,7 +34,7 @@ public override void OnActivated() public override void LessonOnGUI() { - TutorUtility.DrawCellRectOnGUI(this.stockpileRect, this.def.onMapInstruction); + TutorUtility.DrawCellRectOnGUI(this.stockpileRect, base.def.onMapInstruction); base.LessonOnGUI(); } diff --git a/Assembly-CSharp/RimWorld/Instruction_SetGrowingZonePlant.cs b/Assembly-CSharp/RimWorld/Instruction_SetGrowingZonePlant.cs index b93994ef1..7af0d1b36 100644 --- a/Assembly-CSharp/RimWorld/Instruction_SetGrowingZonePlant.cs +++ b/Assembly-CSharp/RimWorld/Instruction_SetGrowingZonePlant.cs @@ -10,13 +10,13 @@ private Zone_Growing GrowZone { get { - return (Zone_Growing)base.Map.zoneManager.AllZones.FirstOrDefault((Zone z) => z is Zone_Growing); + return (Zone_Growing)base.Map.zoneManager.AllZones.FirstOrDefault((Func)((Zone z) => z is Zone_Growing)); } } public override void LessonOnGUI() { - TutorUtility.DrawLabelOnGUI(Gen.AveragePosition(this.GrowZone.cells), this.def.onMapInstruction); + TutorUtility.DrawLabelOnGUI(Gen.AveragePosition(this.GrowZone.cells), base.def.onMapInstruction); base.LessonOnGUI(); } diff --git a/Assembly-CSharp/RimWorld/Instruction_UndraftAll.cs b/Assembly-CSharp/RimWorld/Instruction_UndraftAll.cs index 020cace19..c4eece572 100644 --- a/Assembly-CSharp/RimWorld/Instruction_UndraftAll.cs +++ b/Assembly-CSharp/RimWorld/Instruction_UndraftAll.cs @@ -11,7 +11,7 @@ protected override float ProgressPercent { get { - return 1f - (float)this.DraftedPawns().Count() / (float)base.Map.mapPawns.FreeColonistsSpawnedCount; + return (float)(1.0 - (float)this.DraftedPawns().Count() / (float)base.Map.mapPawns.FreeColonistsSpawnedCount); } } @@ -24,11 +24,11 @@ where p.Drafted public override void LessonUpdate() { - foreach (Pawn current in this.DraftedPawns()) + foreach (Pawn item in this.DraftedPawns()) { - GenDraw.DrawArrowPointingAt(current.DrawPos, false); + GenDraw.DrawArrowPointingAt(item.DrawPos, false); } - if (this.ProgressPercent > 0.9999f) + if (this.ProgressPercent > 0.99989998340606689) { Find.ActiveLesson.Deactivate(); } diff --git a/Assembly-CSharp/RimWorld/Instruction_UnforbidStartingResources.cs b/Assembly-CSharp/RimWorld/Instruction_UnforbidStartingResources.cs index ca1ab9c75..90ca3eef3 100644 --- a/Assembly-CSharp/RimWorld/Instruction_UnforbidStartingResources.cs +++ b/Assembly-CSharp/RimWorld/Instruction_UnforbidStartingResources.cs @@ -13,7 +13,7 @@ protected override float ProgressPercent { return (float)(from it in Find.TutorialState.startingItems where !it.IsForbidden(Faction.OfPlayer) || it.Destroyed - select it).Count() / (float)Find.TutorialState.startingItems.Count; + select it).Count() / (float)Find.TutorialState.startingItems.Count; } } @@ -27,27 +27,27 @@ where it.IsForbidden(Faction.OfPlayer) && !it.Destroyed public override void PostDeactivated() { base.PostDeactivated(); - Find.TutorialState.startingItems.RemoveAll((Thing it) => !Instruction_EquipWeapons.IsWeapon(it)); + Find.TutorialState.startingItems.RemoveAll((Predicate)((Thing it) => !Instruction_EquipWeapons.IsWeapon(it))); } public override void LessonOnGUI() { - foreach (Thing current in this.NeedUnforbidItems()) + foreach (Thing item in this.NeedUnforbidItems()) { - TutorUtility.DrawLabelOnThingOnGUI(current, this.def.onMapInstruction); + TutorUtility.DrawLabelOnThingOnGUI(item, base.def.onMapInstruction); } base.LessonOnGUI(); } public override void LessonUpdate() { - if (this.ProgressPercent > 0.9999f) + if (this.ProgressPercent > 0.99989998340606689) { Find.ActiveLesson.Deactivate(); } - foreach (Thing current in this.NeedUnforbidItems()) + foreach (Thing item in this.NeedUnforbidItems()) { - GenDraw.DrawArrowPointingAt(current.DrawPos, true); + GenDraw.DrawArrowPointingAt(item.DrawPos, true); } } } diff --git a/Assembly-CSharp/RimWorld/InteractionDef.cs b/Assembly-CSharp/RimWorld/InteractionDef.cs index 0dd6b48fb..fb7479da3 100644 --- a/Assembly-CSharp/RimWorld/InteractionDef.cs +++ b/Assembly-CSharp/RimWorld/InteractionDef.cs @@ -53,7 +53,7 @@ public Texture2D Symbol { get { - if (this.symbolTex == null) + if ((UnityEngine.Object)this.symbolTex == (UnityEngine.Object)null) { this.symbolTex = ContentFinder.Get(this.symbol, true); } diff --git a/Assembly-CSharp/RimWorld/InteractionDefOf.cs b/Assembly-CSharp/RimWorld/InteractionDefOf.cs index 30da025ff..72446b3ce 100644 --- a/Assembly-CSharp/RimWorld/InteractionDefOf.cs +++ b/Assembly-CSharp/RimWorld/InteractionDefOf.cs @@ -1,5 +1,3 @@ -using System; - namespace RimWorld { [DefOf] diff --git a/Assembly-CSharp/RimWorld/InteractionUtility.cs b/Assembly-CSharp/RimWorld/InteractionUtility.cs index 9ccb0bdcc..94cfad442 100644 --- a/Assembly-CSharp/RimWorld/InteractionUtility.cs +++ b/Assembly-CSharp/RimWorld/InteractionUtility.cs @@ -11,22 +11,62 @@ public static class InteractionUtility public static bool CanInitiateInteraction(Pawn pawn) { - return pawn.interactions != null && pawn.health.capacities.CapableOf(PawnCapacityDefOf.Talking) && pawn.Awake() && !pawn.IsBurning(); + if (pawn.interactions == null) + { + return false; + } + if (!pawn.health.capacities.CapableOf(PawnCapacityDefOf.Talking)) + { + return false; + } + if (!pawn.Awake()) + { + return false; + } + if (pawn.IsBurning()) + { + return false; + } + return true; } public static bool CanReceiveInteraction(Pawn pawn) { - return pawn.Awake() && !pawn.IsBurning(); + if (!pawn.Awake()) + { + return false; + } + if (pawn.IsBurning()) + { + return false; + } + return true; } public static bool CanInitiateRandomInteraction(Pawn p) { - return InteractionUtility.CanInitiateInteraction(p) && p.RaceProps.Humanlike && !p.Downed && !p.InAggroMentalState; + if (!InteractionUtility.CanInitiateInteraction(p)) + { + return false; + } + if (p.RaceProps.Humanlike && !p.Downed && !p.InAggroMentalState) + { + return true; + } + return false; } public static bool CanReceiveRandomInteraction(Pawn p) { - return InteractionUtility.CanReceiveInteraction(p) && p.RaceProps.Humanlike && !p.Downed && !p.InAggroMentalState; + if (!InteractionUtility.CanReceiveInteraction(p)) + { + return false; + } + if (p.RaceProps.Humanlike && !p.Downed && !p.InAggroMentalState) + { + return true; + } + return false; } public static bool HasAnyVerbForSocialFight(Pawn p) @@ -56,12 +96,12 @@ public static bool TryGetRandomVerbForSocialFight(Pawn p, out Verb verb) List allVerbs = p.verbTracker.AllVerbs; return (from x in allVerbs where x is Verb_MeleeAttack && x.IsStillUsableBy(p) - select x).TryRandomElementByWeight((Verb x) => (float)x.verbProps.AdjustedMeleeDamageAmount(x, p, null), out verb); + select x).TryRandomElementByWeight((Func)((Verb x) => (float)x.verbProps.AdjustedMeleeDamageAmount(x, p, null)), out verb); } public static bool HasAnySocialFightProvokingThought(Pawn pawn, Pawn otherPawn) { - Thought thought; + Thought thought = default(Thought); return InteractionUtility.TryGetRandomSocialFightProvokingThought(pawn, otherPawn, out thought); } @@ -73,12 +113,16 @@ public static bool TryGetRandomSocialFightProvokingThought(Pawn pawn, Pawn other return false; } pawn.needs.mood.thoughts.GetSocialThoughts(otherPawn, InteractionUtility.tmpSocialThoughts); - ISocialThought socialThought; - bool result = InteractionUtility.tmpSocialThoughts.Where(delegate(ISocialThought x) + ISocialThought socialThought = default(ISocialThought); + bool result = InteractionUtility.tmpSocialThoughts.Where((Func)delegate(ISocialThought x) { ThoughtDef def = ((Thought)x).def; - return def != ThoughtDefOf.HadAngeringFight && def != ThoughtDefOf.HadCatharticFight && x.OpinionOffset() < 0f; - }).TryRandomElementByWeight((ISocialThought x) => -x.OpinionOffset(), out socialThought); + if (def != ThoughtDefOf.HadAngeringFight && def != ThoughtDefOf.HadCatharticFight) + { + return x.OpinionOffset() < 0.0; + } + return false; + }).TryRandomElementByWeight((Func)((ISocialThought x) => (float)(0.0 - x.OpinionOffset())), out socialThought); InteractionUtility.tmpSocialThoughts.Clear(); thought = (Thought)socialThought; return result; diff --git a/Assembly-CSharp/RimWorld/InteractionWorker.cs b/Assembly-CSharp/RimWorld/InteractionWorker.cs index 2162af3d4..008a7b72e 100644 --- a/Assembly-CSharp/RimWorld/InteractionWorker.cs +++ b/Assembly-CSharp/RimWorld/InteractionWorker.cs @@ -1,4 +1,3 @@ -using System; using System.Collections.Generic; using Verse; diff --git a/Assembly-CSharp/RimWorld/InteractionWorker_Breakup.cs b/Assembly-CSharp/RimWorld/InteractionWorker_Breakup.cs index cf3190717..67b0bfbea 100644 --- a/Assembly-CSharp/RimWorld/InteractionWorker_Breakup.cs +++ b/Assembly-CSharp/RimWorld/InteractionWorker_Breakup.cs @@ -25,23 +25,23 @@ public override float RandomSelectionWeight(Pawn initiator, Pawn recipient) { num2 = 0.4f; } - return 0.02f * num * num2; + return (float)(0.019999999552965164 * num * num2); } public Thought RandomBreakupReason(Pawn initiator, Pawn recipient) { List list = (from m in initiator.needs.mood.thoughts.memories.Memories - where m != null && m.otherPawn == recipient && m.CurStage != null && m.CurStage.baseOpinionOffset < 0f - select m).ToList(); + where m != null && m.otherPawn == recipient && m.CurStage != null && m.CurStage.baseOpinionOffset < 0.0 + select m).ToList(); if (list.Count == 0) { return null; } - float worstMemoryOpinionOffset = list.Max((Thought_Memory m) => -m.CurStage.baseOpinionOffset); + float worstMemoryOpinionOffset = list.Max((Func)((Thought_Memory m) => (float)(0.0 - m.CurStage.baseOpinionOffset))); Thought_Memory result = null; (from m in list - where -m.CurStage.baseOpinionOffset >= worstMemoryOpinionOffset / 2f - select m).TryRandomElementByWeight((Thought_Memory m) => -m.CurStage.baseOpinionOffset, out result); + where 0.0 - m.CurStage.baseOpinionOffset >= worstMemoryOpinionOffset / 2.0 + select m).TryRandomElementByWeight((Func)((Thought_Memory m) => (float)(0.0 - m.CurStage.baseOpinionOffset)), out result); return result; } @@ -67,32 +67,20 @@ public override void Interacted(Pawn initiator, Pawn recipient, List= 0.5f) ? recipient : initiator; + Pawn pawn = (!(Rand.Value < 0.5)) ? recipient : initiator; pawn.ownership.UnclaimBed(); } - TaleRecorder.RecordTale(TaleDefOf.Breakup, new object[] - { - initiator, - recipient - }); + TaleRecorder.RecordTale(TaleDefOf.Breakup, initiator, recipient); StringBuilder stringBuilder = new StringBuilder(); - stringBuilder.AppendLine("LetterNoLongerLovers".Translate(new object[] - { - initiator.LabelShort, - recipient.LabelShort - })); + stringBuilder.AppendLine("LetterNoLongerLovers".Translate(initiator.LabelShort, recipient.LabelShort)); if (thought != null) { stringBuilder.AppendLine(); - stringBuilder.AppendLine("FinalStraw".Translate(new object[] - { - thought.CurStage.label - })); - } - if (PawnUtility.ShouldSendNotificationAbout(initiator) || PawnUtility.ShouldSendNotificationAbout(recipient)) - { - Find.LetterStack.ReceiveLetter("LetterLabelBreakup".Translate(), stringBuilder.ToString(), LetterDefOf.BadNonUrgent, initiator, null); + stringBuilder.AppendLine("FinalStraw".Translate(thought.CurStage.label)); } + if (!PawnUtility.ShouldSendNotificationAbout(initiator) && !PawnUtility.ShouldSendNotificationAbout(recipient)) + return; + Find.LetterStack.ReceiveLetter("LetterLabelBreakup".Translate(), stringBuilder.ToString(), LetterDefOf.BadNonUrgent, (Thing)initiator, (string)null); } } } diff --git a/Assembly-CSharp/RimWorld/InteractionWorker_Chitchat.cs b/Assembly-CSharp/RimWorld/InteractionWorker_Chitchat.cs index 8e7bc7ee1..6be846452 100644 --- a/Assembly-CSharp/RimWorld/InteractionWorker_Chitchat.cs +++ b/Assembly-CSharp/RimWorld/InteractionWorker_Chitchat.cs @@ -1,4 +1,3 @@ -using System; using Verse; namespace RimWorld diff --git a/Assembly-CSharp/RimWorld/InteractionWorker_DeepTalk.cs b/Assembly-CSharp/RimWorld/InteractionWorker_DeepTalk.cs index dc27cddf9..69f50bb44 100644 --- a/Assembly-CSharp/RimWorld/InteractionWorker_DeepTalk.cs +++ b/Assembly-CSharp/RimWorld/InteractionWorker_DeepTalk.cs @@ -1,4 +1,3 @@ -using System; using Verse; namespace RimWorld diff --git a/Assembly-CSharp/RimWorld/InteractionWorker_Insult.cs b/Assembly-CSharp/RimWorld/InteractionWorker_Insult.cs index 0be6413b1..56b6425d5 100644 --- a/Assembly-CSharp/RimWorld/InteractionWorker_Insult.cs +++ b/Assembly-CSharp/RimWorld/InteractionWorker_Insult.cs @@ -1,4 +1,3 @@ -using System; using Verse; namespace RimWorld @@ -9,7 +8,7 @@ public class InteractionWorker_Insult : InteractionWorker public override float RandomSelectionWeight(Pawn initiator, Pawn recipient) { - return 0.007f * NegativeInteractionUtility.NegativeInteractionChanceFactor(initiator, recipient); + return (float)(0.0070000002160668373 * NegativeInteractionUtility.NegativeInteractionChanceFactor(initiator, recipient)); } } } diff --git a/Assembly-CSharp/RimWorld/InteractionWorker_KindWords.cs b/Assembly-CSharp/RimWorld/InteractionWorker_KindWords.cs index 8e5643b45..000b8c07c 100644 --- a/Assembly-CSharp/RimWorld/InteractionWorker_KindWords.cs +++ b/Assembly-CSharp/RimWorld/InteractionWorker_KindWords.cs @@ -1,4 +1,3 @@ -using System; using Verse; namespace RimWorld diff --git a/Assembly-CSharp/RimWorld/InteractionWorker_MarriageProposal.cs b/Assembly-CSharp/RimWorld/InteractionWorker_MarriageProposal.cs index b6d4ba00b..39d726d25 100644 --- a/Assembly-CSharp/RimWorld/InteractionWorker_MarriageProposal.cs +++ b/Assembly-CSharp/RimWorld/InteractionWorker_MarriageProposal.cs @@ -1,4 +1,3 @@ -using System; using System.Collections.Generic; using System.Text; using UnityEngine; @@ -23,24 +22,28 @@ public override float RandomSelectionWeight(Pawn initiator, Pawn recipient) } Pawn spouse = recipient.GetSpouse(); Pawn spouse2 = initiator.GetSpouse(); - if ((spouse != null && !spouse.Dead) || (spouse2 != null && !spouse2.Dead)) + if (spouse != null && !spouse.Dead) { - return 0f; + goto IL_004e; } + if (spouse2 != null && !spouse2.Dead) + goto IL_004e; float num = 0.4f; int ticksGame = Find.TickManager.TicksGame; - float value = (float)(ticksGame - directRelation.startTicks) / 60000f; + float value = (float)((float)(ticksGame - directRelation.startTicks) / 60000.0); num *= Mathf.InverseLerp(0f, 60f, value); num *= Mathf.InverseLerp(0f, 60f, (float)initiator.relations.OpinionOf(recipient)); if (recipient.relations.OpinionOf(initiator) < 0) { - num *= 0.3f; + num = (float)(num * 0.30000001192092896); } if (initiator.gender == Gender.Female) { - num *= 0.2f; + num = (float)(num * 0.20000000298023224); } return num; + IL_004e: + return 0f; } public override void Interacted(Pawn initiator, Pawn recipient, List extraSentencePacks) @@ -65,7 +68,7 @@ public override void Interacted(Pawn initiator, Pawn recipient, List extraSentencePacks) { - if (recipient.mindState.CheckStartMentalStateBecauseRecruitAttempted(initiator)) + if (!recipient.mindState.CheckStartMentalStateBecauseRecruitAttempted(initiator)) { - return; - } - float num = 1f; - if (DebugSettings.instantRecruit) - { - num = 1f; - } - else - { - num *= ((!recipient.RaceProps.Humanlike) ? initiator.GetStatValue(StatDefOf.TameAnimalChance, true) : initiator.GetStatValue(StatDefOf.RecruitPrisonerChance, true)); - float num2 = (!recipient.RaceProps.Humanlike) ? InteractionWorker_RecruitAttempt.RecruitChanceFactorCurve_Wildness.Evaluate(recipient.RaceProps.wildness) : (1f - recipient.RecruitDifficulty(initiator.Faction, true)); - num *= num2; - if (recipient.RaceProps.Humanlike) + float num = 1f; + if (DebugSettings.instantRecruit) { - float x = (float)recipient.relations.OpinionOf(initiator); - num *= InteractionWorker_RecruitAttempt.RecruitChanceFactorCurve_Opinion.Evaluate(x); - if (recipient.needs.mood != null) - { - float curLevel = recipient.needs.mood.CurLevel; - num *= InteractionWorker_RecruitAttempt.RecruitChanceFactorCurve_Mood.Evaluate(curLevel); - } + num = 1f; } - if (initiator.relations.DirectRelationExists(PawnRelationDefOf.Bond, recipient)) + else { - num *= 4f; + num *= ((!recipient.RaceProps.Humanlike) ? initiator.GetStatValue(StatDefOf.TameAnimalChance, true) : initiator.GetStatValue(StatDefOf.RecruitPrisonerChance, true)); + float num2 = (float)((!recipient.RaceProps.Humanlike) ? InteractionWorker_RecruitAttempt.RecruitChanceFactorCurve_Wildness.Evaluate(recipient.RaceProps.wildness) : (1.0 - recipient.RecruitDifficulty(initiator.Faction, true))); + num *= num2; + if (recipient.RaceProps.Humanlike) + { + float x = (float)recipient.relations.OpinionOf(initiator); + num *= InteractionWorker_RecruitAttempt.RecruitChanceFactorCurve_Opinion.Evaluate(x); + if (recipient.needs.mood != null) + { + float curLevel = recipient.needs.mood.CurLevel; + num *= InteractionWorker_RecruitAttempt.RecruitChanceFactorCurve_Mood.Evaluate(curLevel); + } + } + if (initiator.relations.DirectRelationExists(PawnRelationDefOf.Bond, recipient)) + { + num = (float)(num * 4.0); + } + num = Mathf.Clamp(num, 0.005f, 1f); } - num = Mathf.Clamp(num, 0.005f, 1f); - } - if (Rand.Value < num) - { - InteractionWorker_RecruitAttempt.DoRecruit(initiator, recipient, num, true); - extraSentencePacks.Add(RulePackDefOf.Sentence_RecruitAttemptAccepted); - } - else - { - string text; - if (recipient.RaceProps.Humanlike) + if (Rand.Value < num) { - text = "TextMote_RecruitFail".Translate(new object[] - { - num.ToStringPercent() - }); + InteractionWorker_RecruitAttempt.DoRecruit(initiator, recipient, num, true); + extraSentencePacks.Add(RulePackDefOf.Sentence_RecruitAttemptAccepted); } else { - text = "TextMote_TameFail".Translate(new object[] - { - num.ToStringPercent() - }); + string text = (!recipient.RaceProps.Humanlike) ? "TextMote_TameFail".Translate(num.ToStringPercent()) : "TextMote_RecruitFail".Translate(num.ToStringPercent()); + MoteMaker.ThrowText((initiator.DrawPos + recipient.DrawPos) / 2f, initiator.Map, text, 8f); + extraSentencePacks.Add(RulePackDefOf.Sentence_RecruitAttemptRejected); } - MoteMaker.ThrowText((initiator.DrawPos + recipient.DrawPos) / 2f, initiator.Map, text, 8f); - extraSentencePacks.Add(RulePackDefOf.Sentence_RecruitAttemptRejected); } } @@ -142,18 +126,9 @@ public static void DoRecruit(Pawn recruiter, Pawn recruitee, float recruitChance { if (useAudiovisualEffects) { - Find.LetterStack.ReceiveLetter("LetterLabelMessageRecruitSuccess".Translate(), "MessageRecruitSuccess".Translate(new object[] - { - recruiter, - recruitee, - recruitChance.ToStringPercent() - }), LetterDefOf.Good, recruitee, null); + Find.LetterStack.ReceiveLetter("LetterLabelMessageRecruitSuccess".Translate(), "MessageRecruitSuccess".Translate(recruiter, recruitee, recruitChance.ToStringPercent()), LetterDefOf.Good, (Thing)recruitee, (string)null); } - TaleRecorder.RecordTale(TaleDefOf.Recruited, new object[] - { - recruiter, - recruitee - }); + TaleRecorder.RecordTale(TaleDefOf.Recruited, recruiter, recruitee); recruiter.records.Increment(RecordDefOf.PrisonersRecruited); recruitee.needs.mood.thoughts.memories.TryGainMemory(ThoughtDefOf.RecruitedMe, recruiter); } @@ -163,38 +138,20 @@ public static void DoRecruit(Pawn recruiter, Pawn recruitee, float recruitChance { if (!flag) { - Messages.Message("MessageTameAndNameSuccess".Translate(new object[] - { - recruiter.LabelShort, - text, - recruitChance.ToStringPercent(), - recruitee.Name.ToStringFull - }).AdjustedFor(recruitee), recruitee, MessageSound.Benefit); + Messages.Message("MessageTameAndNameSuccess".Translate(recruiter.LabelShort, text, recruitChance.ToStringPercent(), recruitee.Name.ToStringFull).AdjustedFor(recruitee), (Thing)recruitee, MessageSound.Benefit); } else { - Messages.Message("MessageTameSuccess".Translate(new object[] - { - recruiter.LabelShort, - text, - recruitChance.ToStringPercent() - }), recruitee, MessageSound.Benefit); + Messages.Message("MessageTameSuccess".Translate(recruiter.LabelShort, text, recruitChance.ToStringPercent()), (Thing)recruitee, MessageSound.Benefit); } - MoteMaker.ThrowText((recruiter.DrawPos + recruitee.DrawPos) / 2f, recruiter.Map, "TextMote_TameSuccess".Translate(new object[] - { - recruitChance.ToStringPercent() - }), 8f); + MoteMaker.ThrowText((recruiter.DrawPos + recruitee.DrawPos) / 2f, recruiter.Map, "TextMote_TameSuccess".Translate(recruitChance.ToStringPercent()), 8f); } recruiter.records.Increment(RecordDefOf.AnimalsTamed); RelationsUtility.TryDevelopBondRelation(recruiter, recruitee, 0.01f); float num = Mathf.Lerp(0.02f, 1f, recruitee.RaceProps.wildness); if (Rand.Value < num) { - TaleRecorder.RecordTale(TaleDefOf.TamedAnimal, new object[] - { - recruiter, - recruitee - }); + TaleRecorder.RecordTale(TaleDefOf.TamedAnimal, recruiter, recruitee); } } if (recruitee.caller != null) diff --git a/Assembly-CSharp/RimWorld/InteractionWorker_RomanceAttempt.cs b/Assembly-CSharp/RimWorld/InteractionWorker_RomanceAttempt.cs index 2bdf81d43..bcfae12dc 100644 --- a/Assembly-CSharp/RimWorld/InteractionWorker_RomanceAttempt.cs +++ b/Assembly-CSharp/RimWorld/InteractionWorker_RomanceAttempt.cs @@ -23,7 +23,7 @@ public override float RandomSelectionWeight(Pawn initiator, Pawn recipient) return 0f; } float num = initiator.relations.SecondaryRomanceChanceFactor(recipient); - if (num < 0.25f) + if (num < 0.25) { return 0f; } @@ -43,30 +43,11 @@ public override float RandomSelectionWeight(Pawn initiator, Pawn recipient) float value = (float)initiator.relations.OpinionOf(pawn); num3 = Mathf.InverseLerp(50f, -50f, value); } - float num4 = (!initiator.story.traits.HasTrait(TraitDefOf.Gay)) ? ((initiator.gender != Gender.Female) ? 1f : 0.15f) : 1f; + float num4 = (float)((!initiator.story.traits.HasTrait(TraitDefOf.Gay)) ? ((initiator.gender != Gender.Female) ? 1.0 : 0.15000000596046448) : 1.0); float num5 = Mathf.InverseLerp(0.25f, 1f, num); float num6 = Mathf.InverseLerp(5f, 100f, (float)num2); - float num7; - if (initiator.gender == recipient.gender) - { - if (initiator.story.traits.HasTrait(TraitDefOf.Gay) && recipient.story.traits.HasTrait(TraitDefOf.Gay)) - { - num7 = 1f; - } - else - { - num7 = 0.15f; - } - } - else if (!initiator.story.traits.HasTrait(TraitDefOf.Gay) && !recipient.story.traits.HasTrait(TraitDefOf.Gay)) - { - num7 = 1f; - } - else - { - num7 = 0.15f; - } - return 1.15f * num4 * num5 * num6 * num3 * num7; + float num7 = (float)((initiator.gender != recipient.gender) ? ((initiator.story.traits.HasTrait(TraitDefOf.Gay) || recipient.story.traits.HasTrait(TraitDefOf.Gay)) ? 0.15000000596046448 : 1.0) : ((!initiator.story.traits.HasTrait(TraitDefOf.Gay) || !recipient.story.traits.HasTrait(TraitDefOf.Gay)) ? 0.15000000596046448 : 1.0)); + return (float)(1.1499999761581421 * num4 * num5 * num6 * num3 * num7); } public float SuccessChance(Pawn initiator, Pawn recipient) @@ -76,12 +57,12 @@ public float SuccessChance(Pawn initiator, Pawn recipient) num *= Mathf.InverseLerp(5f, 100f, (float)recipient.relations.OpinionOf(initiator)); float num2 = 1f; Pawn pawn = null; - if (recipient.relations.GetFirstDirectRelationPawn(PawnRelationDefOf.Lover, (Pawn x) => !x.Dead) != null) + if (recipient.relations.GetFirstDirectRelationPawn(PawnRelationDefOf.Lover, (Predicate)((Pawn x) => !x.Dead)) != null) { pawn = recipient.relations.GetFirstDirectRelationPawn(PawnRelationDefOf.Lover, null); num2 = 0.6f; } - else if (recipient.relations.GetFirstDirectRelationPawn(PawnRelationDefOf.Fiance, (Pawn x) => !x.Dead) != null) + else if (recipient.relations.GetFirstDirectRelationPawn(PawnRelationDefOf.Fiance, (Predicate)((Pawn x) => !x.Dead)) != null) { pawn = recipient.relations.GetFirstDirectRelationPawn(PawnRelationDefOf.Fiance, null); num2 = 0.1f; @@ -94,7 +75,7 @@ public float SuccessChance(Pawn initiator, Pawn recipient) if (pawn != null) { num2 *= Mathf.InverseLerp(100f, 0f, (float)recipient.relations.OpinionOf(pawn)); - num2 *= Mathf.Clamp01(1f - recipient.relations.SecondaryRomanceChanceFactor(pawn)); + num2 *= Mathf.Clamp01((float)(1.0 - recipient.relations.SecondaryRomanceChanceFactor(pawn))); } num *= num2; return Mathf.Clamp01(num); @@ -104,9 +85,9 @@ public override void Interacted(Pawn initiator, Pawn recipient, List list; + List list = default(List); this.BreakLoverAndFianceRelations(initiator, out list); - List list2; + List list2 = default(List); this.BreakLoverAndFianceRelations(recipient, out list2); for (int i = 0; i < list.Count; i++) { @@ -118,11 +99,7 @@ public override void Interacted(Pawn initiator, Pawn recipient, List oldLoversAndFiances) { oldLoversAndFiances = new List(); + goto IL_0007; + IL_0007: while (true) { Pawn firstDirectRelationPawn = pawn.relations.GetFirstDirectRelationPawn(PawnRelationDefOf.Lover, null); @@ -164,62 +143,51 @@ private void BreakLoverAndFianceRelations(Pawn pawn, out List oldLoversAnd { Pawn firstDirectRelationPawn2 = pawn.relations.GetFirstDirectRelationPawn(PawnRelationDefOf.Fiance, null); if (firstDirectRelationPawn2 == null) - { break; - } pawn.relations.RemoveDirectRelation(PawnRelationDefOf.Fiance, firstDirectRelationPawn2); pawn.relations.AddDirectRelation(PawnRelationDefOf.ExLover, firstDirectRelationPawn2); oldLoversAndFiances.Add(firstDirectRelationPawn2); } } + return; + IL_009a: + goto IL_0007; } private void TryAddCheaterThought(Pawn pawn, Pawn cheater) { - if (pawn.Dead) + if (!pawn.Dead) { - return; + pawn.needs.mood.thoughts.memories.TryGainMemory(ThoughtDefOf.CheatedOnMe, cheater); } - pawn.needs.mood.thoughts.memories.TryGainMemory(ThoughtDefOf.CheatedOnMe, cheater); } private void SendNewLoversLetter(Pawn initiator, Pawn recipient, List initiatorOldLoversAndFiances, List recipientOldLoversAndFiances) { bool flag = false; - string label; - LetterDef textLetterDef; - Pawn t; - if ((initiator.GetSpouse() != null && !initiator.GetSpouse().Dead) || (recipient.GetSpouse() != null && !recipient.GetSpouse().Dead)) - { - label = "LetterLabelAffair".Translate(); - textLetterDef = LetterDefOf.BadNonUrgent; - if (initiator.GetSpouse() != null && !initiator.GetSpouse().Dead) - { - t = initiator; - } - else - { - t = recipient; - } - flag = true; - } - else - { - label = "LetterLabelNewLovers".Translate(); - textLetterDef = LetterDefOf.Good; - t = initiator; - } + if (initiator.GetSpouse() != null && !initiator.GetSpouse().Dead) + { + goto IL_0038; + } + if (recipient.GetSpouse() != null && !recipient.GetSpouse().Dead) + goto IL_0038; + string label = "LetterLabelNewLovers".Translate(); + LetterDef textLetterDef = LetterDefOf.Good; + Pawn t = initiator; + goto IL_0087; + IL_0038: + label = "LetterLabelAffair".Translate(); + textLetterDef = LetterDefOf.BadNonUrgent; + t = ((initiator.GetSpouse() == null || initiator.GetSpouse().Dead) ? recipient : initiator); + flag = true; + goto IL_0087; + IL_0087: StringBuilder stringBuilder = new StringBuilder(); if (flag) { if (initiator.GetSpouse() != null) { - stringBuilder.AppendLine("LetterAffair".Translate(new object[] - { - initiator.LabelShort, - initiator.GetSpouse().LabelShort, - recipient.LabelShort - })); + stringBuilder.AppendLine("LetterAffair".Translate(initiator.LabelShort, initiator.GetSpouse().LabelShort, recipient.LabelShort)); } if (recipient.GetSpouse() != null) { @@ -227,32 +195,19 @@ private void SendNewLoversLetter(Pawn initiator, Pawn recipient, List init { stringBuilder.AppendLine(); } - stringBuilder.AppendLine("LetterAffair".Translate(new object[] - { - recipient.LabelShort, - recipient.GetSpouse().LabelShort, - initiator.LabelShort - })); + stringBuilder.AppendLine("LetterAffair".Translate(recipient.LabelShort, recipient.GetSpouse().LabelShort, initiator.LabelShort)); } } else { - stringBuilder.AppendLine("LetterNewLovers".Translate(new object[] - { - initiator.LabelShort, - recipient.LabelShort - })); + stringBuilder.AppendLine("LetterNewLovers".Translate(initiator.LabelShort, recipient.LabelShort)); } for (int i = 0; i < initiatorOldLoversAndFiances.Count; i++) { if (!initiatorOldLoversAndFiances[i].Dead) { stringBuilder.AppendLine(); - stringBuilder.AppendLine("LetterNoLongerLovers".Translate(new object[] - { - initiator.LabelShort, - initiatorOldLoversAndFiances[i].LabelShort - })); + stringBuilder.AppendLine("LetterNoLongerLovers".Translate(initiator.LabelShort, initiatorOldLoversAndFiances[i].LabelShort)); } } for (int j = 0; j < recipientOldLoversAndFiances.Count; j++) @@ -260,14 +215,10 @@ private void SendNewLoversLetter(Pawn initiator, Pawn recipient, List init if (!recipientOldLoversAndFiances[j].Dead) { stringBuilder.AppendLine(); - stringBuilder.AppendLine("LetterNoLongerLovers".Translate(new object[] - { - recipient.LabelShort, - recipientOldLoversAndFiances[j].LabelShort - })); + stringBuilder.AppendLine("LetterNoLongerLovers".Translate(recipient.LabelShort, recipientOldLoversAndFiances[j].LabelShort)); } } - Find.LetterStack.ReceiveLetter(label, stringBuilder.ToString().TrimEndNewlines(), textLetterDef, t, null); + Find.LetterStack.ReceiveLetter(label, stringBuilder.ToString().TrimEndNewlines(), textLetterDef, (Thing)t, (string)null); } } } diff --git a/Assembly-CSharp/RimWorld/InteractionWorker_Slight.cs b/Assembly-CSharp/RimWorld/InteractionWorker_Slight.cs index 364a7f6fd..8fad61a9c 100644 --- a/Assembly-CSharp/RimWorld/InteractionWorker_Slight.cs +++ b/Assembly-CSharp/RimWorld/InteractionWorker_Slight.cs @@ -1,4 +1,3 @@ -using System; using Verse; namespace RimWorld @@ -9,7 +8,7 @@ public class InteractionWorker_Slight : InteractionWorker public override float RandomSelectionWeight(Pawn initiator, Pawn recipient) { - return 0.02f * NegativeInteractionUtility.NegativeInteractionChanceFactor(initiator, recipient); + return (float)(0.019999999552965164 * NegativeInteractionUtility.NegativeInteractionChanceFactor(initiator, recipient)); } } } diff --git a/Assembly-CSharp/RimWorld/IntermittentSteamSprayer.cs b/Assembly-CSharp/RimWorld/IntermittentSteamSprayer.cs index 127368d45..5bb03d772 100644 --- a/Assembly-CSharp/RimWorld/IntermittentSteamSprayer.cs +++ b/Assembly-CSharp/RimWorld/IntermittentSteamSprayer.cs @@ -35,7 +35,7 @@ public void SteamSprayerTick() if (this.sprayTicksLeft > 0) { this.sprayTicksLeft--; - if (Rand.Value < 0.6f) + if (Rand.Value < 0.60000002384185791) { MoteMaker.ThrowAirPuffUp(this.parent.TrueCenter(), this.parent.Map); } @@ -45,7 +45,7 @@ public void SteamSprayerTick() } if (this.sprayTicksLeft <= 0) { - if (this.endSprayCallback != null) + if ((object)this.endSprayCallback != null) { this.endSprayCallback(); } @@ -57,7 +57,7 @@ public void SteamSprayerTick() this.ticksUntilSpray--; if (this.ticksUntilSpray <= 0) { - if (this.startSprayCallback != null) + if ((object)this.startSprayCallback != null) { this.startSprayCallback(); } diff --git a/Assembly-CSharp/RimWorld/InventoryCalculatorsUtility.cs b/Assembly-CSharp/RimWorld/InventoryCalculatorsUtility.cs index 6bf071d13..4ed72326e 100644 --- a/Assembly-CSharp/RimWorld/InventoryCalculatorsUtility.cs +++ b/Assembly-CSharp/RimWorld/InventoryCalculatorsUtility.cs @@ -10,14 +10,22 @@ public static bool ShouldIgnoreInventoryOf(Pawn pawn, IgnorePawnsInventoryMode i switch (ignoreMode) { case IgnorePawnsInventoryMode.Ignore: + { return true; + } case IgnorePawnsInventoryMode.IgnoreIfAssignedToUnload: + { return pawn.Spawned && pawn.inventory.UnloadEverything; + } case IgnorePawnsInventoryMode.DontIgnore: + { return false; + } default: + { throw new NotImplementedException("IgnorePawnsInventoryMode"); } + } } } } diff --git a/Assembly-CSharp/RimWorld/ItemAvailability.cs b/Assembly-CSharp/RimWorld/ItemAvailability.cs index 0df537687..d1a78013d 100644 --- a/Assembly-CSharp/RimWorld/ItemAvailability.cs +++ b/Assembly-CSharp/RimWorld/ItemAvailability.cs @@ -1,4 +1,3 @@ -using System; using System.Collections.Generic; using Verse; @@ -22,8 +21,8 @@ public void Tick() public bool ThingsAvailableAnywhere(ThingCountClass need, Pawn pawn) { - int key = Gen.HashCombine(need.GetHashCode(), pawn.Faction); - bool flag; + int key = Gen.HashCombine(need.GetHashCode(), pawn.Faction); + bool flag = default(bool); if (!this.cachedResults.TryGetValue(key, out flag)) { List list = this.map.listerThings.ThingsOfDef(need.thingDef); @@ -34,9 +33,7 @@ public bool ThingsAvailableAnywhere(ThingCountClass need, Pawn pawn) { num += list[i].stackCount; if (num >= need.count) - { break; - } } } flag = (num >= need.count); diff --git a/Assembly-CSharp/RimWorld/ItemCollectionGenerator.cs b/Assembly-CSharp/RimWorld/ItemCollectionGenerator.cs index 09a414254..63c881051 100644 --- a/Assembly-CSharp/RimWorld/ItemCollectionGenerator.cs +++ b/Assembly-CSharp/RimWorld/ItemCollectionGenerator.cs @@ -24,18 +24,17 @@ public List Generate(ItemCollectionGeneratorParams parms) { Log.Error("thingsBeingGeneratedNow is not null. Nested calls are not allowed."); } - List list = new List(); - ItemCollectionGenerator.thingsBeingGeneratedNow = list; + List list = ItemCollectionGenerator.thingsBeingGeneratedNow = new List(); try { this.Generate(parms, list); this.PostProcess(list); + return list; } finally { ItemCollectionGenerator.thingsBeingGeneratedNow = null; } - return list; } public List GenerateRandomTestItems() @@ -47,7 +46,7 @@ public List GenerateRandomTestItems() private void PostProcess(List things) { - if (things.RemoveAll((Thing x) => x == null) != 0) + if (things.RemoveAll((Predicate)((Thing x) => x == null)) != 0) { Log.Error(this.def + " generated null things."); } diff --git a/Assembly-CSharp/RimWorld/ItemCollectionGeneratorDefOf.cs b/Assembly-CSharp/RimWorld/ItemCollectionGeneratorDefOf.cs index 7820431d3..4a187c937 100644 --- a/Assembly-CSharp/RimWorld/ItemCollectionGeneratorDefOf.cs +++ b/Assembly-CSharp/RimWorld/ItemCollectionGeneratorDefOf.cs @@ -1,5 +1,3 @@ -using System; - namespace RimWorld { [DefOf] diff --git a/Assembly-CSharp/RimWorld/ItemCollectionGeneratorUtility.cs b/Assembly-CSharp/RimWorld/ItemCollectionGeneratorUtility.cs index c8e1e433b..7ff6d7c2f 100644 --- a/Assembly-CSharp/RimWorld/ItemCollectionGeneratorUtility.cs +++ b/Assembly-CSharp/RimWorld/ItemCollectionGeneratorUtility.cs @@ -1,4 +1,3 @@ -using System; using System.Collections.Generic; using Verse; @@ -11,11 +10,11 @@ public static class ItemCollectionGeneratorUtility public static void Reset() { ItemCollectionGeneratorUtility.allGeneratableItems.Clear(); - foreach (ThingDef current in DefDatabase.AllDefs) + foreach (ThingDef allDef in DefDatabase.AllDefs) { - if ((current.category == ThingCategory.Item || current.Minifiable) && !current.isUnfinishedThing && !current.IsCorpse && current.PlayerAcquirable && current.graphicData != null && !typeof(MinifiedThing).IsAssignableFrom(current.thingClass)) + if ((allDef.category == ThingCategory.Item || allDef.Minifiable) && !allDef.isUnfinishedThing && !allDef.IsCorpse && allDef.PlayerAcquirable && allDef.graphicData != null && !typeof(MinifiedThing).IsAssignableFrom(allDef.thingClass)) { - ItemCollectionGeneratorUtility.allGeneratableItems.Add(current); + ItemCollectionGeneratorUtility.allGeneratableItems.Add(allDef); } } ItemCollectionGenerator_Weapons.Reset(); diff --git a/Assembly-CSharp/RimWorld/ItemCollectionGenerator_AncientPodContents.cs b/Assembly-CSharp/RimWorld/ItemCollectionGenerator_AncientPodContents.cs index 5ba2798a3..950c6e3a2 100644 --- a/Assembly-CSharp/RimWorld/ItemCollectionGenerator_AncientPodContents.cs +++ b/Assembly-CSharp/RimWorld/ItemCollectionGenerator_AncientPodContents.cs @@ -1,4 +1,3 @@ -using System; using System.Collections.Generic; using Verse; @@ -21,34 +20,46 @@ protected override void Generate(ItemCollectionGeneratorParams parms, List GenerateScarabs() { List list = new List(); int num = Rand.Range(3, 6); - for (int i = 0; i < num; i++) + for (int num2 = 0; num2 < num; num2++) { Pawn pawn = PawnGenerator.GeneratePawn(PawnKindDefOf.Megascarab, null); - pawn.mindState.mentalStateHandler.TryStartMentalState(MentalStateDefOf.Manhunter, null, false, false, null); + pawn.mindState.mentalStateHandler.TryStartMentalState(MentalStateDefOf.Manhunter, (string)null, false, false, null); list.Add(pawn); } return list; @@ -131,13 +142,12 @@ private void GiveRandomLootInventoryForTombPawn(Pawn p) private void MakeIntoContainer(ThingOwner container, ThingDef def, int count) { - if (count <= 0) + if (count > 0) { - return; + Thing thing = ThingMaker.MakeThing(def, null); + thing.stackCount = count; + container.TryAdd(thing, true); } - Thing thing = ThingMaker.MakeThing(def, null); - thing.stackCount = count; - container.TryAdd(thing, true); } } } diff --git a/Assembly-CSharp/RimWorld/ItemCollectionGenerator_AncientTempleContents.cs b/Assembly-CSharp/RimWorld/ItemCollectionGenerator_AncientTempleContents.cs index 7a93d96a5..bbd2feb76 100644 --- a/Assembly-CSharp/RimWorld/ItemCollectionGenerator_AncientTempleContents.cs +++ b/Assembly-CSharp/RimWorld/ItemCollectionGenerator_AncientTempleContents.cs @@ -1,4 +1,3 @@ -using System; using System.Collections.Generic; using Verse; @@ -25,9 +24,9 @@ protected override void Generate(ItemCollectionGeneratorParams parms, List(); + ThingDef def = ItemCollectionGenerator_Artifacts.artifacts.RandomElement(); Thing item = ThingMaker.MakeThing(def, null); outThings.Add(item); } diff --git a/Assembly-CSharp/RimWorld/ItemCollectionGenerator_Apparel.cs b/Assembly-CSharp/RimWorld/ItemCollectionGenerator_Apparel.cs index 444e73205..d819814b3 100644 --- a/Assembly-CSharp/RimWorld/ItemCollectionGenerator_Apparel.cs +++ b/Assembly-CSharp/RimWorld/ItemCollectionGenerator_Apparel.cs @@ -20,7 +20,7 @@ where x.IsApparel protected override IEnumerable AllowedDefs(ItemCollectionGeneratorParams parms) { return from x in ItemCollectionGenerator_Apparel.apparel - where x.techLevel <= parms.techLevel + where (int)x.techLevel <= (int)parms.techLevel select x; } } diff --git a/Assembly-CSharp/RimWorld/ItemCollectionGenerator_Artifacts.cs b/Assembly-CSharp/RimWorld/ItemCollectionGenerator_Artifacts.cs index 21103b3c1..c4f25b982 100644 --- a/Assembly-CSharp/RimWorld/ItemCollectionGenerator_Artifacts.cs +++ b/Assembly-CSharp/RimWorld/ItemCollectionGenerator_Artifacts.cs @@ -20,7 +20,7 @@ where x.HasComp(typeof(CompUseEffect_Artifact)) protected override IEnumerable AllowedDefs(ItemCollectionGeneratorParams parms) { return from x in ItemCollectionGenerator_Artifacts.artifacts - where x.techLevel <= parms.techLevel + where (int)x.techLevel <= (int)parms.techLevel select x; } } diff --git a/Assembly-CSharp/RimWorld/ItemCollectionGenerator_DebugCaravanInventory.cs b/Assembly-CSharp/RimWorld/ItemCollectionGenerator_DebugCaravanInventory.cs index 76d4da88e..ef0fef8be 100644 --- a/Assembly-CSharp/RimWorld/ItemCollectionGenerator_DebugCaravanInventory.cs +++ b/Assembly-CSharp/RimWorld/ItemCollectionGenerator_DebugCaravanInventory.cs @@ -1,4 +1,3 @@ -using System; using System.Collections.Generic; using Verse; diff --git a/Assembly-CSharp/RimWorld/ItemCollectionGenerator_RandomGeneralGoods.cs b/Assembly-CSharp/RimWorld/ItemCollectionGenerator_RandomGeneralGoods.cs index df233b2cc..f818115ae 100644 --- a/Assembly-CSharp/RimWorld/ItemCollectionGenerator_RandomGeneralGoods.cs +++ b/Assembly-CSharp/RimWorld/ItemCollectionGenerator_RandomGeneralGoods.cs @@ -11,21 +11,21 @@ public class ItemCollectionGenerator_RandomGeneralGoods : ItemCollectionGenerato { private enum GoodsType { - None, - Meals, - RawFood, - Medicine, - Drugs, - Resources + None = 0, + Meals = 1, + RawFood = 2, + Medicine = 3, + Drugs = 4, + Resources = 5 } - private static Pair[] GoodsWeights = new Pair[] + private static Pair[] GoodsWeights = new Pair[5] { - new Pair(ItemCollectionGenerator_RandomGeneralGoods.GoodsType.Meals, 1f), - new Pair(ItemCollectionGenerator_RandomGeneralGoods.GoodsType.RawFood, 0.75f), - new Pair(ItemCollectionGenerator_RandomGeneralGoods.GoodsType.Medicine, 0.234f), - new Pair(ItemCollectionGenerator_RandomGeneralGoods.GoodsType.Drugs, 0.234f), - new Pair(ItemCollectionGenerator_RandomGeneralGoods.GoodsType.Resources, 0.234f) + new Pair(GoodsType.Meals, 1f), + new Pair(GoodsType.RawFood, 0.75f), + new Pair(GoodsType.Medicine, 0.234f), + new Pair(GoodsType.Drugs, 0.234f), + new Pair(GoodsType.Resources, 0.234f) }; protected override ItemCollectionGeneratorParams RandomTestParams @@ -43,7 +43,7 @@ protected override void Generate(ItemCollectionGeneratorParams parms, List x) => x.Second).First; + GoodsType first = ItemCollectionGenerator_RandomGeneralGoods.GoodsWeights.RandomElementByWeight((Func, float>)((Pair x) => x.Second)).First; switch (first) { - case ItemCollectionGenerator_RandomGeneralGoods.GoodsType.Meals: + case GoodsType.Meals: + { return this.RandomMeals(techLevel); - case ItemCollectionGenerator_RandomGeneralGoods.GoodsType.RawFood: + } + case GoodsType.RawFood: + { return this.RandomRawFood(techLevel); - case ItemCollectionGenerator_RandomGeneralGoods.GoodsType.Medicine: + } + case GoodsType.Medicine: + { return this.RandomMedicine(techLevel); - case ItemCollectionGenerator_RandomGeneralGoods.GoodsType.Drugs: + } + case GoodsType.Drugs: + { return this.RandomDrugs(techLevel); - case ItemCollectionGenerator_RandomGeneralGoods.GoodsType.Resources: + } + case GoodsType.Resources: + { return this.RandomResources(techLevel); + } default: + { Log.Error("Goods type not handled: " + first); return null; } + } } private Thing RandomMeals(TechLevel techLevel) @@ -80,18 +92,7 @@ private Thing RandomMeals(TechLevel techLevel) else { float value = Rand.Value; - if (value < 0.5f) - { - thingDef = ThingDefOf.MealSimple; - } - else if ((double)value < 0.75) - { - thingDef = ThingDefOf.MealFine; - } - else - { - thingDef = ThingDefOf.MealSurvivalPack; - } + thingDef = ((!(value < 0.5)) ? ((!((double)value < 0.75)) ? ThingDefOf.MealSurvivalPack : ThingDefOf.MealFine) : ThingDefOf.MealSimple); } Thing thing = ThingMaker.MakeThing(thingDef, null); int num = Mathf.Min(thingDef.stackLimit, 10); @@ -101,10 +102,10 @@ private Thing RandomMeals(TechLevel techLevel) private Thing RandomRawFood(TechLevel techLevel) { - ThingDef thingDef; + ThingDef thingDef = default(ThingDef); if (!(from x in ItemCollectionGeneratorUtility.allGeneratableItems - where x.IsNutritionGivingIngestible && !x.IsCorpse && ThingDefOf.Human.race.CanEverEat(x) && !x.HasComp(typeof(CompHatcher)) && x.techLevel <= techLevel && x.ingestible.preferability < FoodPreferability.MealAwful - select x).TryRandomElement(out thingDef)) + where x.IsNutritionGivingIngestible && !x.IsCorpse && ThingDefOf.Human.race.CanEverEat(x) && !x.HasComp(typeof(CompHatcher)) && (int)x.techLevel <= (int)techLevel && (int)x.ingestible.preferability < 5 + select x).TryRandomElement(out thingDef)) { return null; } @@ -116,14 +117,14 @@ private Thing RandomRawFood(TechLevel techLevel) private Thing RandomMedicine(TechLevel techLevel) { - ThingDef herbalMedicine; + ThingDef herbalMedicine = default(ThingDef); if (techLevel.IsNeolithicOrWorse()) { herbalMedicine = ThingDefOf.HerbalMedicine; } else if (!(from x in ItemCollectionGeneratorUtility.allGeneratableItems - where x.IsMedicine && x.techLevel <= techLevel - select x).TryRandomElement(out herbalMedicine)) + where x.IsMedicine && (int)x.techLevel <= (int)techLevel + select x).TryRandomElement(out herbalMedicine)) { return null; } @@ -135,10 +136,10 @@ private Thing RandomMedicine(TechLevel techLevel) private Thing RandomDrugs(TechLevel techLevel) { - ThingDef thingDef; + ThingDef thingDef = default(ThingDef); if (!(from x in ItemCollectionGeneratorUtility.allGeneratableItems - where x.IsDrug && x.techLevel <= techLevel - select x).TryRandomElement(out thingDef)) + where x.IsDrug && (int)x.techLevel <= (int)techLevel + select x).TryRandomElement(out thingDef)) { return null; } diff --git a/Assembly-CSharp/RimWorld/ItemCollectionGenerator_RawResources.cs b/Assembly-CSharp/RimWorld/ItemCollectionGenerator_RawResources.cs index be2262879..a915f1706 100644 --- a/Assembly-CSharp/RimWorld/ItemCollectionGenerator_RawResources.cs +++ b/Assembly-CSharp/RimWorld/ItemCollectionGenerator_RawResources.cs @@ -20,7 +20,7 @@ where x.IsWithinCategory(ThingCategoryDefOf.ResourcesRaw) protected override IEnumerable AllowedDefs(ItemCollectionGeneratorParams parms) { return from x in ItemCollectionGenerator_RawResources.rawResources - where x.techLevel <= parms.techLevel + where (int)x.techLevel <= (int)parms.techLevel select x; } } diff --git a/Assembly-CSharp/RimWorld/ItemCollectionGenerator_Rewards.cs b/Assembly-CSharp/RimWorld/ItemCollectionGenerator_Rewards.cs index 5aef9ad06..66c7ba92f 100644 --- a/Assembly-CSharp/RimWorld/ItemCollectionGenerator_Rewards.cs +++ b/Assembly-CSharp/RimWorld/ItemCollectionGenerator_Rewards.cs @@ -35,7 +35,7 @@ protected override void Generate(ItemCollectionGeneratorParams parms, List validator = parms.validator; - for (int i = 0; i < count; i++) + for (int num = 0; num < count; num++) { outThings.Add(this.GenerateReward(totalMarketValue / (float)count, techLevel, validator)); } @@ -43,15 +43,15 @@ protected override void Generate(ItemCollectionGeneratorParams parms, List validator = null) { - if (Rand.Value < 0.5f) + if (Rand.Value < 0.5) { Thing thing = ThingMaker.MakeThing(ThingDefOf.Silver, null); thing.stackCount = Mathf.Max(GenMath.RoundRandom(value), 1); return thing; } - ItemCollectionGenerator_Rewards.Option option2 = (from option in ItemCollectionGeneratorUtility.allGeneratableItems.Select(delegate(ThingDef td) + Option option2 = (from option in ItemCollectionGeneratorUtility.allGeneratableItems.Select((Func)delegate(ThingDef td) { - if (td.techLevel > techLevel) + if ((int)td.techLevel > (int)techLevel) { return null; } @@ -59,29 +59,25 @@ private Thing GenerateReward(float value, TechLevel techLevel, Predicate((Func)((ThingDef st) => st.stuffProps.commonality), out stuff)) { - if (!(from x in GenStuff.AllowedStuffsFor(td) - where x.techLevel <= techLevel - select x).TryRandomElementByWeight((ThingDef st) => st.stuffProps.commonality, out stuff)) - { - return null; - } + return null; } - return new ItemCollectionGenerator_Rewards.Option - { - thingDef = td, - quality = ((!td.HasComp(typeof(CompQuality))) ? QualityCategory.Normal : QualityUtility.RandomQuality()), - stuff = stuff - }; + Option option3 = new Option(); + option3.thingDef = td; + option3.quality = ((!td.HasComp(typeof(CompQuality))) ? QualityCategory.Normal : QualityUtility.RandomQuality()); + option3.stuff = stuff; + return option3; }) where option != null - select option).MinBy(delegate(ItemCollectionGenerator_Rewards.Option option) + select option).MinBy((Func)delegate(Option option) { float value2 = StatDefOf.MarketValue.Worker.GetValue(StatRequest.For(option.thingDef, option.stuff, option.quality), true); return Mathf.Abs(value - value2); diff --git a/Assembly-CSharp/RimWorld/ItemCollectionGenerator_Standard.cs b/Assembly-CSharp/RimWorld/ItemCollectionGenerator_Standard.cs index 36feef3b0..ae630ee9f 100644 --- a/Assembly-CSharp/RimWorld/ItemCollectionGenerator_Standard.cs +++ b/Assembly-CSharp/RimWorld/ItemCollectionGenerator_Standard.cs @@ -21,7 +21,7 @@ protected override ItemCollectionGeneratorParams RandomTestParams ItemCollectionGeneratorParams randomTestParams = base.RandomTestParams; randomTestParams.count = Rand.RangeInclusive(5, 10); randomTestParams.techLevel = TechLevel.Transcendent; - if (this.def == ItemCollectionGeneratorDefOf.AIPersonaCores || this.def == ItemCollectionGeneratorDefOf.Neurotrainers) + if (base.def == ItemCollectionGeneratorDefOf.AIPersonaCores || base.def == ItemCollectionGeneratorDefOf.Neurotrainers) { randomTestParams.totalMarketValue = 0f; } @@ -35,7 +35,7 @@ protected override ItemCollectionGeneratorParams RandomTestParams protected virtual IEnumerable AllowedDefs(ItemCollectionGeneratorParams parms) { - return this.def.allowedDefs; + return base.def.allowedDefs; } protected override void Generate(ItemCollectionGeneratorParams parms, List outThings) @@ -44,28 +44,30 @@ protected override void Generate(ItemCollectionGeneratorParams parms, List enumerable = this.AllowedDefs(parms); - if (!enumerable.Any()) + if (enumerable.Any()) { - return; - } - if (totalMarketValue > 0f) - { - List list = this.GenerateDefsWithPossibleTotalMarketValue(count, totalMarketValue, enumerable, techLevel, 100); - for (int i = 0; i < list.Count; i++) + if (totalMarketValue > 0.0) { - outThings.Add(ThingMaker.MakeThing(list[i].thing, list[i].stuff)); + List list = this.GenerateDefsWithPossibleTotalMarketValue(count, totalMarketValue, enumerable, techLevel, 100); + for (int i = 0; i < list.Count; i++) + { + ThingStuffPair thingStuffPair = list[i]; + ThingDef thing = thingStuffPair.thing; + ThingStuffPair thingStuffPair2 = list[i]; + outThings.Add(ThingMaker.MakeThing(thing, thingStuffPair2.stuff)); + } + this.IncreaseStackCountsToMarketValue(outThings, totalMarketValue); } - this.IncreaseStackCountsToMarketValue(outThings, totalMarketValue); - } - else - { - for (int j = 0; j < count; j++) + else { - ThingDef thingDef = enumerable.RandomElement(); - outThings.Add(ThingMaker.MakeThing(thingDef, GenStuff.RandomStuffFor(thingDef))); + for (int num = 0; num < count; num++) + { + ThingDef thingDef = enumerable.RandomElement(); + outThings.Add(ThingMaker.MakeThing(thingDef, GenStuff.RandomStuffFor(thingDef))); + } } + ItemCollectionGeneratorUtility.AssignRandomBaseGenItemQuality(outThings); } - ItemCollectionGeneratorUtility.AssignRandomBaseGenItemQuality(outThings); } private List GenerateDefsWithPossibleTotalMarketValue(int count, float totalMarketValue, IEnumerable allowed, TechLevel techLevel, int tries = 100) @@ -73,75 +75,74 @@ private List GenerateDefsWithPossibleTotalMarketValue(int count, List list = new List(); ItemCollectionGenerator_Standard.allowedFiltered.Clear(); ItemCollectionGenerator_Standard.allowedFiltered.AddRange(allowed); - ItemCollectionGenerator_Standard.allowedFiltered.RemoveAll((ThingDef x) => x.techLevel > techLevel || (!x.MadeFromStuff && this.GetMinValue(new ThingStuffPair(x, null, 1f)) > totalMarketValue)); + ItemCollectionGenerator_Standard.allowedFiltered.RemoveAll((Predicate)delegate(ThingDef x) + { + if ((int)x.techLevel > (int)techLevel) + { + return true; + } + if (!x.MadeFromStuff && this.GetMinValue(new ThingStuffPair(x, null, 1f)) > totalMarketValue) + { + return true; + } + return false; + }); ItemCollectionGenerator_Standard.allowedStuff.Clear(); for (int i = 0; i < ItemCollectionGenerator_Standard.allowedFiltered.Count; i++) { ThingDef thingDef = ItemCollectionGenerator_Standard.allowedFiltered[i]; if (thingDef.MadeFromStuff) { - List list2; + List list2 = default(List); if (!ItemCollectionGenerator_Standard.allowedStuff.TryGetValue(thingDef, out list2)) { list2 = new List(); ItemCollectionGenerator_Standard.allowedStuff.Add(thingDef, list2); } - foreach (ThingDef current in GenStuff.AllowedStuffsFor(thingDef)) + foreach (ThingDef item in GenStuff.AllowedStuffsFor(thingDef)) { - if (current.stuffProps.commonality > 0f) + if (!(item.stuffProps.commonality <= 0.0) && (int)item.techLevel <= (int)techLevel && !(this.GetMinValue(new ThingStuffPair(thingDef, item, 1f)) > totalMarketValue)) { - if (current.techLevel <= techLevel) - { - if (this.GetMinValue(new ThingStuffPair(thingDef, current, 1f)) <= totalMarketValue) - { - list2.Add(current); - } - } + list2.Add(item); } } } } - ItemCollectionGenerator_Standard.allowedFiltered.RemoveAll((ThingDef x) => x.MadeFromStuff && !ItemCollectionGenerator_Standard.allowedStuff[x].Any()); - if (!ItemCollectionGenerator_Standard.allowedFiltered.Any()) + ItemCollectionGenerator_Standard.allowedFiltered.RemoveAll((Predicate)((ThingDef x) => x.MadeFromStuff && !ItemCollectionGenerator_Standard.allowedStuff[x].Any())); + if (!ItemCollectionGenerator_Standard.allowedFiltered.Any()) { return list; } float num = 0f; - for (int j = 0; j < tries; j++) + int num2 = 0; + while (num2 < tries) { - float num2 = 0f; float num3 = 0f; + float num4 = 0f; ItemCollectionGenerator_Standard.newCandidates.Clear(); - for (int k = 0; k < count; k++) + for (int num5 = 0; num5 < count; num5++) { - ThingDef thingDef2 = ItemCollectionGenerator_Standard.allowedFiltered.RandomElement(); - ThingDef arg_204_0; - if (thingDef2.MadeFromStuff) - { - arg_204_0 = ItemCollectionGenerator_Standard.allowedStuff[thingDef2].RandomElementByWeight((ThingDef x) => x.stuffProps.commonality); - } - else - { - arg_204_0 = null; - } - ThingDef stuff = arg_204_0; + ThingDef thingDef2 = ItemCollectionGenerator_Standard.allowedFiltered.RandomElement(); + ThingDef stuff = (!thingDef2.MadeFromStuff) ? null : ItemCollectionGenerator_Standard.allowedStuff[thingDef2].RandomElementByWeight((Func)((ThingDef x) => x.stuffProps.commonality)); ThingStuffPair thingStuffPair = new ThingStuffPair(thingDef2, stuff, 1f); ItemCollectionGenerator_Standard.newCandidates.Add(thingStuffPair); - num2 += this.GetMinValue(thingStuffPair); - num3 += this.GetMaxValue(thingStuffPair); + num3 += this.GetMinValue(thingStuffPair); + num4 += this.GetMaxValue(thingStuffPair); } - float num4 = (num2 > totalMarketValue) ? (num2 - totalMarketValue) : 0f; - float num5 = (num3 < totalMarketValue) ? (totalMarketValue - num3) : 0f; - if (!list.Any() || num > num4 + num5) + float num6 = (float)((!(num3 <= totalMarketValue)) ? (num3 - totalMarketValue) : 0.0); + float num7 = (float)((!(num4 >= totalMarketValue)) ? (totalMarketValue - num4) : 0.0); + if (!list.Any() || num > num6 + num7) { list.Clear(); list.AddRange(ItemCollectionGenerator_Standard.newCandidates); - num = num4 + num5; + num = num6 + num7; } - if (num <= 0f) + if (!(num <= 0.0)) { - break; + num2++; + continue; } + break; } return list; } @@ -153,35 +154,33 @@ private void IncreaseStackCountsToMarketValue(List things, float totalMar { num += things[i].MarketValue * (float)things[i].stackCount; } - if (num >= totalMarketValue) - { - return; - } - float num2 = (totalMarketValue - num) / (float)things.Count; - for (int j = 0; j < things.Count; j++) + if (!(num >= totalMarketValue)) { - float marketValue = things[j].MarketValue; - int a = Mathf.FloorToInt(num2 / marketValue); - int num3 = Mathf.Min(a, things[j].def.stackLimit - things[j].stackCount); - if (num3 > 0) + float num2 = (totalMarketValue - num) / (float)things.Count; + for (int j = 0; j < things.Count; j++) { - things[j].stackCount += num3; - num += marketValue * (float)num3; + float marketValue = things[j].MarketValue; + int a = Mathf.FloorToInt(num2 / marketValue); + int num3 = Mathf.Min(a, things[j].def.stackLimit - things[j].stackCount); + if (num3 > 0) + { + things[j].stackCount += num3; + num += marketValue * (float)num3; + } } - } - if (num >= totalMarketValue) - { - return; - } - for (int k = 0; k < things.Count; k++) - { - float marketValue2 = things[k].MarketValue; - int a2 = Mathf.FloorToInt((totalMarketValue - num) / marketValue2); - int num4 = Mathf.Min(a2, things[k].def.stackLimit - things[k].stackCount); - if (num4 > 0) + if (!(num >= totalMarketValue)) { - things[k].stackCount += num4; - num += marketValue2 * (float)num4; + for (int k = 0; k < things.Count; k++) + { + float marketValue2 = things[k].MarketValue; + int a2 = Mathf.FloorToInt((totalMarketValue - num) / marketValue2); + int num4 = Mathf.Min(a2, things[k].def.stackLimit - things[k].stackCount); + if (num4 > 0) + { + things[k].stackCount += num4; + num += marketValue2 * (float)num4; + } + } } } } diff --git a/Assembly-CSharp/RimWorld/ItemCollectionGenerator_TraderStock.cs b/Assembly-CSharp/RimWorld/ItemCollectionGenerator_TraderStock.cs index fadc8462c..3ae8929c1 100644 --- a/Assembly-CSharp/RimWorld/ItemCollectionGenerator_TraderStock.cs +++ b/Assembly-CSharp/RimWorld/ItemCollectionGenerator_TraderStock.cs @@ -12,8 +12,8 @@ protected override ItemCollectionGeneratorParams RandomTestParams get { ItemCollectionGeneratorParams randomTestParams = base.RandomTestParams; - randomTestParams.traderDef = DefDatabase.AllDefsListForReading.RandomElement(); - randomTestParams.forTile = ((Find.VisibleMap == null) ? -1 : Find.VisibleMap.Tile); + randomTestParams.traderDef = DefDatabase.AllDefsListForReading.RandomElement(); + randomTestParams.forTile = ((Find.VisibleMap == null) ? (-1) : Find.VisibleMap.Tile); randomTestParams.forFaction = (Find.FactionManager.RandomAlliedFaction(false, false, true) ?? Find.FactionManager.RandomEnemyFaction(false, false, true)); return randomTestParams; } @@ -27,22 +27,16 @@ protected override void Generate(ItemCollectionGeneratorParams parms, List.Enumerator enumerator = base.Generate(parms).GetEnumerator(); + try + { + while (enumerator.MoveNext()) + { + Thing current = enumerator.Current; + num += current.MarketValue * (float)current.stackCount; + } + } + finally { - num += current.MarketValue * (float)current.stackCount; + ((IDisposable)(object)enumerator).Dispose(); } } - return num / 50f; + return (float)(num / 50.0); } public string GenerationDataFor(TraderKindDef td) @@ -69,25 +74,28 @@ public string GenerationDataFor(TraderKindDef td) StringBuilder stringBuilder = new StringBuilder(); stringBuilder.AppendLine(td.defName); stringBuilder.AppendLine("Average total market value:" + this.AverageTotalStockValue(td).ToString("F0")); - ItemCollectionGeneratorParams parms = default(ItemCollectionGeneratorParams); - parms.traderDef = td; - parms.forTile = -1; + ItemCollectionGeneratorParams parms = new ItemCollectionGeneratorParams + { + traderDef = td, + forTile = -1 + }; stringBuilder.AppendLine("Example generated stock:\n\n"); - foreach (Thing current in base.Generate(parms)) + List.Enumerator enumerator = base.Generate(parms).GetEnumerator(); + try { - MinifiedThing minifiedThing = current as MinifiedThing; - Thing thing; - if (minifiedThing != null) - { - thing = minifiedThing.InnerThing; - } - else + while (enumerator.MoveNext()) { - thing = current; + Thing current = enumerator.Current; + MinifiedThing minifiedThing = current as MinifiedThing; + Thing thing = (minifiedThing == null) ? current : minifiedThing.InnerThing; + string labelCap = thing.LabelCap; + labelCap = labelCap + " [" + (thing.MarketValue * (float)thing.stackCount).ToString("F0") + "]"; + stringBuilder.AppendLine(labelCap); } - string text = thing.LabelCap; - text = text + " [" + (thing.MarketValue * (float)thing.stackCount).ToString("F0") + "]"; - stringBuilder.AppendLine(text); + } + finally + { + ((IDisposable)(object)enumerator).Dispose(); } return stringBuilder.ToString(); } diff --git a/Assembly-CSharp/RimWorld/ItemCollectionGenerator_Weapons.cs b/Assembly-CSharp/RimWorld/ItemCollectionGenerator_Weapons.cs index 91a3d579d..7bc3b7c0e 100644 --- a/Assembly-CSharp/RimWorld/ItemCollectionGenerator_Weapons.cs +++ b/Assembly-CSharp/RimWorld/ItemCollectionGenerator_Weapons.cs @@ -20,14 +20,14 @@ public static void Reset() protected override IEnumerable AllowedDefs(ItemCollectionGeneratorParams parms) { TechLevel techLevel = parms.techLevel; - if (techLevel >= TechLevel.Spacer) + if ((int)techLevel >= 5) { return from x in ItemCollectionGenerator_Weapons.weapons - where x.techLevel >= TechLevel.Industrial && x.techLevel <= techLevel + where (int)x.techLevel >= 4 && (int)x.techLevel <= (int)techLevel select x; } return from x in ItemCollectionGenerator_Weapons.weapons - where x.techLevel <= techLevel + where (int)x.techLevel <= (int)techLevel select x; } } diff --git a/Assembly-CSharp/RimWorld/Jetter.cs b/Assembly-CSharp/RimWorld/Jetter.cs index 454d5b11f..2ab4d84fc 100644 --- a/Assembly-CSharp/RimWorld/Jetter.cs +++ b/Assembly-CSharp/RimWorld/Jetter.cs @@ -1,4 +1,3 @@ -using System; using Verse; using Verse.Sound; @@ -8,16 +7,16 @@ public class Jetter : Thing { private enum JetterState { - Resting, - WickBurning, - Jetting + Resting = 0, + WickBurning = 1, + Jetting = 2 } private const int TicksBeforeBeginAccelerate = 25; private const int TicksBetweenMoves = 3; - private Jetter.JetterState JState; + private JetterState JState; private int WickTicksLeft; @@ -29,7 +28,7 @@ private enum JetterState public override void Tick() { - if (this.JState == Jetter.JetterState.WickBurning) + if (this.JState == JetterState.WickBurning) { base.Map.overlayDrawer.DrawOverlay(this, OverlayTypes.BurningWick); this.WickTicksLeft--; @@ -38,7 +37,7 @@ public override void Tick() this.StartJetting(); } } - else if (this.JState == Jetter.JetterState.Jetting) + else if (this.JState == JetterState.Jetting) { this.TicksUntilMove--; if (this.TicksUntilMove <= 0) @@ -51,7 +50,7 @@ public override void Tick() public override void PostApplyDamage(DamageInfo dinfo, float totalDamageDealt) { - if (!base.Destroyed && dinfo.Def.harmsHealth && this.JState == Jetter.JetterState.Resting) + if (!base.Destroyed && dinfo.Def.harmsHealth && this.JState == JetterState.Resting) { this.StartWick(); } @@ -59,19 +58,19 @@ public override void PostApplyDamage(DamageInfo dinfo, float totalDamageDealt) protected void StartWick() { - this.JState = Jetter.JetterState.WickBurning; + this.JState = JetterState.WickBurning; this.WickTicksLeft = 25; - SoundDef.Named("MetalHitImportant").PlayOneShot(this); - this.wickSoundSustainer = SoundDef.Named("HissSmall").TrySpawnSustainer(this); + SoundDef.Named("MetalHitImportant").PlayOneShot((Thing)this); + this.wickSoundSustainer = SoundDef.Named("HissSmall").TrySpawnSustainer((Thing)this); } protected void StartJetting() { - this.JState = Jetter.JetterState.Jetting; + this.JState = JetterState.Jetting; this.TicksUntilMove = 3; this.wickSoundSustainer.End(); this.wickSoundSustainer = null; - this.wickSoundSustainer = SoundDef.Named("HissJet").TrySpawnSustainer(this); + this.wickSoundSustainer = SoundDef.Named("HissJet").TrySpawnSustainer((Thing)this); } protected void MoveJetter() @@ -81,9 +80,11 @@ protected void MoveJetter() { this.Destroy(DestroyMode.Vanish); GenExplosion.DoExplosion(base.Position, base.Map, 2.9f, DamageDefOf.Bomb, null, null, null, null, null, 0f, 1, false, null, 0f, 1); - return; } - base.Position = intVec; + else + { + base.Position = intVec; + } } public override void Destroy(DestroyMode mode = DestroyMode.Vanish) diff --git a/Assembly-CSharp/RimWorld/JobDefOf.cs b/Assembly-CSharp/RimWorld/JobDefOf.cs index 74863a85e..4c06e87be 100644 --- a/Assembly-CSharp/RimWorld/JobDefOf.cs +++ b/Assembly-CSharp/RimWorld/JobDefOf.cs @@ -1,4 +1,3 @@ -using System; using Verse; namespace RimWorld diff --git a/Assembly-CSharp/RimWorld/JobDriver_AffectFloor.cs b/Assembly-CSharp/RimWorld/JobDriver_AffectFloor.cs index a2006d310..275000371 100644 --- a/Assembly-CSharp/RimWorld/JobDriver_AffectFloor.cs +++ b/Assembly-CSharp/RimWorld/JobDriver_AffectFloor.cs @@ -1,6 +1,5 @@ using System; using System.Collections.Generic; -using System.Diagnostics; using Verse; using Verse.AI; @@ -30,14 +29,53 @@ protected virtual StatDef SpeedStat } } - [DebuggerHidden] protected override IEnumerable MakeNewToils() { - JobDriver_AffectFloor.c__IteratorB c__IteratorB = new JobDriver_AffectFloor.c__IteratorB(); - c__IteratorB.<>f__this = this; - JobDriver_AffectFloor.c__IteratorB expr_0E = c__IteratorB; - expr_0E.$PC = -2; - return expr_0E; + this.FailOn((Func)delegate + { + if (!((_003CMakeNewToils_003Ec__IteratorB)/*Error near IL_002f: stateMachine*/)._003C_003Ef__this.CurJob.ignoreDesignations && ((_003CMakeNewToils_003Ec__IteratorB)/*Error near IL_002f: stateMachine*/)._003C_003Ef__this.Map.designationManager.DesignationAt(((_003CMakeNewToils_003Ec__IteratorB)/*Error near IL_002f: stateMachine*/)._003C_003Ef__this.TargetLocA, ((_003CMakeNewToils_003Ec__IteratorB)/*Error near IL_002f: stateMachine*/)._003C_003Ef__this.DesDef) == null) + { + return true; + } + return false; + }); + ReservationLayerDef floor = ReservationLayerDefOf.Floor; + yield return Toils_Reserve.Reserve(TargetIndex.A, 1, -1, floor); + yield return Toils_Goto.GotoCell(TargetIndex.A, PathEndMode.Touch); + Toil doWork = new Toil + { + initAction = (Action)delegate + { + ((_003CMakeNewToils_003Ec__IteratorB)/*Error near IL_008c: stateMachine*/)._003C_003Ef__this.workLeft = (float)((_003CMakeNewToils_003Ec__IteratorB)/*Error near IL_008c: stateMachine*/)._003C_003Ef__this.BaseWorkAmount; + }, + tickAction = (Action)delegate + { + float num = (float)((((_003CMakeNewToils_003Ec__IteratorB)/*Error near IL_00a3: stateMachine*/)._003C_003Ef__this.SpeedStat == null) ? 1.0 : ((_003CMakeNewToils_003Ec__IteratorB)/*Error near IL_00a3: stateMachine*/)._003CdoWork_003E__0.actor.GetStatValue(((_003CMakeNewToils_003Ec__IteratorB)/*Error near IL_00a3: stateMachine*/)._003C_003Ef__this.SpeedStat, true)); + ((_003CMakeNewToils_003Ec__IteratorB)/*Error near IL_00a3: stateMachine*/)._003C_003Ef__this.workLeft -= num; + if (((_003CMakeNewToils_003Ec__IteratorB)/*Error near IL_00a3: stateMachine*/)._003CdoWork_003E__0.actor.skills != null) + { + ((_003CMakeNewToils_003Ec__IteratorB)/*Error near IL_00a3: stateMachine*/)._003CdoWork_003E__0.actor.skills.Learn(SkillDefOf.Construction, 0.22f, false); + } + if (((_003CMakeNewToils_003Ec__IteratorB)/*Error near IL_00a3: stateMachine*/)._003C_003Ef__this.clearSnow) + { + ((_003CMakeNewToils_003Ec__IteratorB)/*Error near IL_00a3: stateMachine*/)._003C_003Ef__this.Map.snowGrid.SetDepth(((_003CMakeNewToils_003Ec__IteratorB)/*Error near IL_00a3: stateMachine*/)._003C_003Ef__this.TargetLocA, 0f); + } + if (((_003CMakeNewToils_003Ec__IteratorB)/*Error near IL_00a3: stateMachine*/)._003C_003Ef__this.workLeft <= 0.0) + { + ((_003CMakeNewToils_003Ec__IteratorB)/*Error near IL_00a3: stateMachine*/)._003C_003Ef__this.DoEffect(((_003CMakeNewToils_003Ec__IteratorB)/*Error near IL_00a3: stateMachine*/)._003C_003Ef__this.TargetLocA); + Designation designation = ((_003CMakeNewToils_003Ec__IteratorB)/*Error near IL_00a3: stateMachine*/)._003C_003Ef__this.Map.designationManager.DesignationAt(((_003CMakeNewToils_003Ec__IteratorB)/*Error near IL_00a3: stateMachine*/)._003C_003Ef__this.TargetLocA, ((_003CMakeNewToils_003Ec__IteratorB)/*Error near IL_00a3: stateMachine*/)._003C_003Ef__this.DesDef); + if (designation != null) + { + designation.Delete(); + } + ((_003CMakeNewToils_003Ec__IteratorB)/*Error near IL_00a3: stateMachine*/)._003C_003Ef__this.ReadyForNextToil(); + } + } + }; + doWork.FailOnCannotTouch(TargetIndex.A, PathEndMode.Touch); + doWork.WithProgressBar(TargetIndex.A, (Func)(() => (float)(1.0 - ((_003CMakeNewToils_003Ec__IteratorB)/*Error near IL_00c9: stateMachine*/)._003C_003Ef__this.workLeft / (float)((_003CMakeNewToils_003Ec__IteratorB)/*Error near IL_00c9: stateMachine*/)._003C_003Ef__this.BaseWorkAmount)), false, -0.5f); + doWork.defaultCompleteMode = ToilCompleteMode.Never; + yield return doWork; } protected abstract void DoEffect(IntVec3 c); diff --git a/Assembly-CSharp/RimWorld/JobDriver_AffectRoof.cs b/Assembly-CSharp/RimWorld/JobDriver_AffectRoof.cs index 1e1517dc0..4a41188fd 100644 --- a/Assembly-CSharp/RimWorld/JobDriver_AffectRoof.cs +++ b/Assembly-CSharp/RimWorld/JobDriver_AffectRoof.cs @@ -1,6 +1,5 @@ using System; using System.Collections.Generic; -using System.Diagnostics; using Verse; using Verse.AI; @@ -39,14 +38,37 @@ public override void ExposeData() Scribe_Values.Look(ref this.workLeft, "workLeft", 0f, false); } - [DebuggerHidden] protected override IEnumerable MakeNewToils() { - JobDriver_AffectRoof.c__IteratorC c__IteratorC = new JobDriver_AffectRoof.c__IteratorC(); - c__IteratorC.<>f__this = this; - JobDriver_AffectRoof.c__IteratorC expr_0E = c__IteratorC; - expr_0E.$PC = -2; - return expr_0E; + this.FailOnDespawnedOrNull(TargetIndex.B); + ReservationLayerDef ceiling = ReservationLayerDefOf.Ceiling; + yield return Toils_Reserve.Reserve(TargetIndex.A, 1, -1, ceiling); + yield return Toils_Goto.Goto(TargetIndex.B, this.PathEndMode); + Toil doWork = new Toil + { + initAction = (Action)delegate + { + ((_003CMakeNewToils_003Ec__IteratorC)/*Error near IL_008b: stateMachine*/)._003C_003Ef__this.workLeft = 65f; + }, + tickAction = (Action)delegate + { + float statValue = ((_003CMakeNewToils_003Ec__IteratorC)/*Error near IL_00a2: stateMachine*/)._003CdoWork_003E__0.actor.GetStatValue(StatDefOf.ConstructionSpeed, true); + ((_003CMakeNewToils_003Ec__IteratorC)/*Error near IL_00a2: stateMachine*/)._003C_003Ef__this.workLeft -= statValue; + if (((_003CMakeNewToils_003Ec__IteratorC)/*Error near IL_00a2: stateMachine*/)._003C_003Ef__this.workLeft <= 0.0) + { + ((_003CMakeNewToils_003Ec__IteratorC)/*Error near IL_00a2: stateMachine*/)._003C_003Ef__this.DoEffect(); + ((_003CMakeNewToils_003Ec__IteratorC)/*Error near IL_00a2: stateMachine*/)._003C_003Ef__this.ReadyForNextToil(); + } + } + }; + doWork.FailOnCannotTouch(TargetIndex.B, this.PathEndMode); + doWork.PlaySoundAtStart(SoundDefOf.RoofStart); + doWork.PlaySoundAtEnd(SoundDefOf.RoofFinish); + doWork.WithEffect(EffecterDefOf.RoofWork, TargetIndex.A); + doWork.FailOn(new Func(this.DoWorkFailOn)); + doWork.WithProgressBar(TargetIndex.A, (Func)(() => (float)(1.0 - ((_003CMakeNewToils_003Ec__IteratorC)/*Error near IL_0124: stateMachine*/)._003C_003Ef__this.workLeft / 65.0)), false, -0.5f); + doWork.defaultCompleteMode = ToilCompleteMode.Never; + yield return doWork; } } } diff --git a/Assembly-CSharp/RimWorld/JobDriver_BeatFire.cs b/Assembly-CSharp/RimWorld/JobDriver_BeatFire.cs index d5842c7b5..8a19f61e1 100644 --- a/Assembly-CSharp/RimWorld/JobDriver_BeatFire.cs +++ b/Assembly-CSharp/RimWorld/JobDriver_BeatFire.cs @@ -1,6 +1,5 @@ using System; using System.Collections.Generic; -using System.Diagnostics; using Verse; using Verse.AI; @@ -16,14 +15,57 @@ protected Fire TargetFire } } - [DebuggerHidden] protected override IEnumerable MakeNewToils() { - JobDriver_BeatFire.c__Iterator14 c__Iterator = new JobDriver_BeatFire.c__Iterator14(); - c__Iterator.<>f__this = this; - JobDriver_BeatFire.c__Iterator14 expr_0E = c__Iterator; - expr_0E.$PC = -2; - return expr_0E; + this.FailOnDespawnedOrNull(TargetIndex.A); + Toil beat = new Toil(); + Toil approach = new Toil + { + initAction = (Action)delegate + { + if (((_003CMakeNewToils_003Ec__Iterator14)/*Error near IL_004e: stateMachine*/)._003C_003Ef__this.Map.reservationManager.CanReserve(((_003CMakeNewToils_003Ec__Iterator14)/*Error near IL_004e: stateMachine*/)._003C_003Ef__this.pawn, (Thing)((_003CMakeNewToils_003Ec__Iterator14)/*Error near IL_004e: stateMachine*/)._003C_003Ef__this.TargetFire, 1, -1, null, false)) + { + ((_003CMakeNewToils_003Ec__Iterator14)/*Error near IL_004e: stateMachine*/)._003C_003Ef__this.pawn.Reserve((Thing)((_003CMakeNewToils_003Ec__Iterator14)/*Error near IL_004e: stateMachine*/)._003C_003Ef__this.TargetFire, 1, -1, null); + } + ((_003CMakeNewToils_003Ec__Iterator14)/*Error near IL_004e: stateMachine*/)._003C_003Ef__this.pawn.pather.StartPath((Thing)((_003CMakeNewToils_003Ec__Iterator14)/*Error near IL_004e: stateMachine*/)._003C_003Ef__this.TargetFire, PathEndMode.Touch); + }, + tickAction = (Action)delegate + { + if (((_003CMakeNewToils_003Ec__Iterator14)/*Error near IL_0065: stateMachine*/)._003C_003Ef__this.pawn.pather.Moving && ((_003CMakeNewToils_003Ec__Iterator14)/*Error near IL_0065: stateMachine*/)._003C_003Ef__this.pawn.pather.nextCell != ((_003CMakeNewToils_003Ec__Iterator14)/*Error near IL_0065: stateMachine*/)._003C_003Ef__this.TargetFire.Position) + { + ((_003CMakeNewToils_003Ec__Iterator14)/*Error near IL_0065: stateMachine*/)._003C_003Ef__this.StartBeatingFireIfAnyAt(((_003CMakeNewToils_003Ec__Iterator14)/*Error near IL_0065: stateMachine*/)._003C_003Ef__this.pawn.pather.nextCell, ((_003CMakeNewToils_003Ec__Iterator14)/*Error near IL_0065: stateMachine*/)._003Cbeat_003E__0); + } + if (((_003CMakeNewToils_003Ec__Iterator14)/*Error near IL_0065: stateMachine*/)._003C_003Ef__this.pawn.Position != ((_003CMakeNewToils_003Ec__Iterator14)/*Error near IL_0065: stateMachine*/)._003C_003Ef__this.TargetFire.Position) + { + ((_003CMakeNewToils_003Ec__Iterator14)/*Error near IL_0065: stateMachine*/)._003C_003Ef__this.StartBeatingFireIfAnyAt(((_003CMakeNewToils_003Ec__Iterator14)/*Error near IL_0065: stateMachine*/)._003C_003Ef__this.pawn.Position, ((_003CMakeNewToils_003Ec__Iterator14)/*Error near IL_0065: stateMachine*/)._003Cbeat_003E__0); + } + } + }; + approach.FailOnDespawnedOrNull(TargetIndex.A); + approach.defaultCompleteMode = ToilCompleteMode.PatherArrival; + approach.atomicWithPrevious = true; + yield return approach; + beat.tickAction = (Action)delegate + { + if (!((_003CMakeNewToils_003Ec__Iterator14)/*Error near IL_00b9: stateMachine*/)._003C_003Ef__this.pawn.CanReachImmediate((Thing)((_003CMakeNewToils_003Ec__Iterator14)/*Error near IL_00b9: stateMachine*/)._003C_003Ef__this.TargetFire, PathEndMode.Touch)) + { + ((_003CMakeNewToils_003Ec__Iterator14)/*Error near IL_00b9: stateMachine*/)._003C_003Ef__this.JumpToToil(((_003CMakeNewToils_003Ec__Iterator14)/*Error near IL_00b9: stateMachine*/)._003Capproach_003E__1); + } + else + { + if (((_003CMakeNewToils_003Ec__Iterator14)/*Error near IL_00b9: stateMachine*/)._003C_003Ef__this.pawn.Position != ((_003CMakeNewToils_003Ec__Iterator14)/*Error near IL_00b9: stateMachine*/)._003C_003Ef__this.TargetFire.Position && ((_003CMakeNewToils_003Ec__Iterator14)/*Error near IL_00b9: stateMachine*/)._003C_003Ef__this.StartBeatingFireIfAnyAt(((_003CMakeNewToils_003Ec__Iterator14)/*Error near IL_00b9: stateMachine*/)._003C_003Ef__this.pawn.Position, ((_003CMakeNewToils_003Ec__Iterator14)/*Error near IL_00b9: stateMachine*/)._003Cbeat_003E__0)) + return; + ((_003CMakeNewToils_003Ec__Iterator14)/*Error near IL_00b9: stateMachine*/)._003C_003Ef__this.pawn.natives.TryBeatFire(((_003CMakeNewToils_003Ec__Iterator14)/*Error near IL_00b9: stateMachine*/)._003C_003Ef__this.TargetFire); + if (((_003CMakeNewToils_003Ec__Iterator14)/*Error near IL_00b9: stateMachine*/)._003C_003Ef__this.TargetFire.Destroyed) + { + ((_003CMakeNewToils_003Ec__Iterator14)/*Error near IL_00b9: stateMachine*/)._003C_003Ef__this.pawn.records.Increment(RecordDefOf.FiresExtinguished); + ((_003CMakeNewToils_003Ec__Iterator14)/*Error near IL_00b9: stateMachine*/)._003C_003Ef__this.pawn.jobs.EndCurrentJob(JobCondition.Succeeded, true); + } + } + }; + beat.FailOnDespawnedOrNull(TargetIndex.A); + beat.defaultCompleteMode = ToilCompleteMode.Never; + yield return beat; } private bool StartBeatingFireIfAnyAt(IntVec3 cell, Toil nextToil) @@ -34,8 +76,8 @@ private bool StartBeatingFireIfAnyAt(IntVec3 cell, Toil nextToil) Fire fire = thingList[i] as Fire; if (fire != null && fire.parent == null) { - this.pawn.CurJob.targetA = fire; - this.pawn.pather.StopDead(); + base.pawn.CurJob.targetA = (Thing)fire; + base.pawn.pather.StopDead(); base.JumpToToil(nextToil); return true; } diff --git a/Assembly-CSharp/RimWorld/JobDriver_BuildRoof.cs b/Assembly-CSharp/RimWorld/JobDriver_BuildRoof.cs index 29ec869fd..6023eea76 100644 --- a/Assembly-CSharp/RimWorld/JobDriver_BuildRoof.cs +++ b/Assembly-CSharp/RimWorld/JobDriver_BuildRoof.cs @@ -1,6 +1,5 @@ using System; using System.Collections.Generic; -using System.Diagnostics; using Verse; using Verse.AI; @@ -18,14 +17,15 @@ protected override PathEndMode PathEndMode } } - [DebuggerHidden] protected override IEnumerable MakeNewToils() { - JobDriver_BuildRoof.c__IteratorD c__IteratorD = new JobDriver_BuildRoof.c__IteratorD(); - c__IteratorD.<>f__this = this; - JobDriver_BuildRoof.c__IteratorD expr_0E = c__IteratorD; - expr_0E.$PC = -2; - return expr_0E; + this.FailOn((Func)(() => !((Area)((_003CMakeNewToils_003Ec__IteratorD)/*Error near IL_0029: stateMachine*/)._003C_003Ef__this.Map.areaManager.BuildRoof)[((_003CMakeNewToils_003Ec__IteratorD)/*Error near IL_0029: stateMachine*/)._003C_003Ef__this.Cell])); + this.FailOn((Func)(() => !RoofCollapseUtility.WithinRangeOfRoofHolder(((_003CMakeNewToils_003Ec__IteratorD)/*Error near IL_0041: stateMachine*/)._003C_003Ef__this.Cell, ((_003CMakeNewToils_003Ec__IteratorD)/*Error near IL_0041: stateMachine*/)._003C_003Ef__this.Map))); + this.FailOn((Func)(() => !RoofCollapseUtility.ConnectedToRoofHolder(((_003CMakeNewToils_003Ec__IteratorD)/*Error near IL_0059: stateMachine*/)._003C_003Ef__this.Cell, ((_003CMakeNewToils_003Ec__IteratorD)/*Error near IL_0059: stateMachine*/)._003C_003Ef__this.Map, true))); + foreach (Toil item in base.MakeNewToils()) + { + yield return item; + } } protected override void DoEffect() @@ -34,14 +34,11 @@ protected override void DoEffect() for (int i = 0; i < 9; i++) { IntVec3 intVec = base.Cell + GenAdj.AdjacentCellsAndInside[i]; - if (intVec.InBounds(base.Map)) + if (intVec.InBounds(base.Map) && ((Area)base.Map.areaManager.BuildRoof)[intVec] && !intVec.Roofed(base.Map) && RoofCollapseUtility.WithinRangeOfRoofHolder(intVec, base.Map)) { - if (base.Map.areaManager.BuildRoof[intVec] && !intVec.Roofed(base.Map) && RoofCollapseUtility.WithinRangeOfRoofHolder(intVec, base.Map)) - { - base.Map.roofGrid.SetRoof(intVec, RoofDefOf.RoofConstructed); - MoteMaker.PlaceTempRoof(intVec, base.Map); - JobDriver_BuildRoof.builtRoofs.Add(intVec); - } + base.Map.roofGrid.SetRoof(intVec, RoofDefOf.RoofConstructed); + MoteMaker.PlaceTempRoof(intVec, base.Map); + JobDriver_BuildRoof.builtRoofs.Add(intVec); } } JobDriver_BuildRoof.builtRoofs.Clear(); diff --git a/Assembly-CSharp/RimWorld/JobDriver_BuildSnowman.cs b/Assembly-CSharp/RimWorld/JobDriver_BuildSnowman.cs index a8e530feb..8be7dfdcf 100644 --- a/Assembly-CSharp/RimWorld/JobDriver_BuildSnowman.cs +++ b/Assembly-CSharp/RimWorld/JobDriver_BuildSnowman.cs @@ -1,6 +1,5 @@ using System; using System.Collections.Generic; -using System.Diagnostics; using Verse; using Verse.AI; @@ -12,14 +11,36 @@ public class JobDriver_BuildSnowman : JobDriver private float workLeft = -1000f; - [DebuggerHidden] protected override IEnumerable MakeNewToils() { - JobDriver_BuildSnowman.c__Iterator1A c__Iterator1A = new JobDriver_BuildSnowman.c__Iterator1A(); - c__Iterator1A.<>f__this = this; - JobDriver_BuildSnowman.c__Iterator1A expr_0E = c__Iterator1A; - expr_0E.$PC = -2; - return expr_0E; + yield return Toils_Reserve.Reserve(TargetIndex.A, 1, -1, null); + yield return Toils_Goto.GotoCell(TargetIndex.A, PathEndMode.Touch); + Toil doWork = new Toil + { + initAction = (Action)delegate + { + ((_003CMakeNewToils_003Ec__Iterator1A)/*Error near IL_006e: stateMachine*/)._003C_003Ef__this.workLeft = 2300f; + }, + tickAction = (Action)delegate + { + ((_003CMakeNewToils_003Ec__Iterator1A)/*Error near IL_0085: stateMachine*/)._003C_003Ef__this.workLeft -= ((_003CMakeNewToils_003Ec__Iterator1A)/*Error near IL_0085: stateMachine*/)._003CdoWork_003E__0.actor.GetStatValue(StatDefOf.ConstructionSpeed, true); + if (((_003CMakeNewToils_003Ec__Iterator1A)/*Error near IL_0085: stateMachine*/)._003C_003Ef__this.workLeft <= 0.0) + { + Thing thing = ThingMaker.MakeThing(ThingDefOf.Snowman, null); + thing.SetFaction(((_003CMakeNewToils_003Ec__Iterator1A)/*Error near IL_0085: stateMachine*/)._003C_003Ef__this.pawn.Faction, null); + GenSpawn.Spawn(thing, ((_003CMakeNewToils_003Ec__Iterator1A)/*Error near IL_0085: stateMachine*/)._003C_003Ef__this.TargetLocA, ((_003CMakeNewToils_003Ec__Iterator1A)/*Error near IL_0085: stateMachine*/)._003C_003Ef__this.Map); + ((_003CMakeNewToils_003Ec__Iterator1A)/*Error near IL_0085: stateMachine*/)._003C_003Ef__this.ReadyForNextToil(); + } + else + { + JoyUtility.JoyTickCheckEnd(((_003CMakeNewToils_003Ec__Iterator1A)/*Error near IL_0085: stateMachine*/)._003C_003Ef__this.pawn, JoyTickFullJoyAction.EndJob, 1f); + } + }, + defaultCompleteMode = ToilCompleteMode.Never + }; + doWork.FailOn((Func)(() => !JoyUtility.EnjoyableOutsideNow(((_003CMakeNewToils_003Ec__Iterator1A)/*Error near IL_00a8: stateMachine*/)._003C_003Ef__this.pawn, null))); + doWork.FailOnCannotTouch(TargetIndex.A, PathEndMode.Touch); + yield return doWork; } public override void ExposeData() diff --git a/Assembly-CSharp/RimWorld/JobDriver_BuryCorpse.cs b/Assembly-CSharp/RimWorld/JobDriver_BuryCorpse.cs index 32578f15d..381eb29ea 100644 --- a/Assembly-CSharp/RimWorld/JobDriver_BuryCorpse.cs +++ b/Assembly-CSharp/RimWorld/JobDriver_BuryCorpse.cs @@ -1,6 +1,5 @@ using System; using System.Collections.Generic; -using System.Diagnostics; using Verse; using Verse.AI; @@ -30,17 +29,37 @@ private Building_Grave Grave public JobDriver_BuryCorpse() { - this.rotateToFace = TargetIndex.B; + base.rotateToFace = TargetIndex.B; } - [DebuggerHidden] protected override IEnumerable MakeNewToils() { - JobDriver_BuryCorpse.c__Iterator24 c__Iterator = new JobDriver_BuryCorpse.c__Iterator24(); - c__Iterator.<>f__this = this; - JobDriver_BuryCorpse.c__Iterator24 expr_0E = c__Iterator; - expr_0E.$PC = -2; - return expr_0E; + this.FailOnDestroyedNullOrForbidden(TargetIndex.A); + this.FailOnDestroyedNullOrForbidden(TargetIndex.B); + yield return Toils_Reserve.Reserve(TargetIndex.A, 1, -1, null); + yield return Toils_Reserve.Reserve(TargetIndex.B, 1, -1, null); + yield return Toils_Goto.GotoThing(TargetIndex.A, PathEndMode.ClosestTouch).FailOnSomeonePhysicallyInteracting(TargetIndex.A); + yield return Toils_Haul.StartCarryThing(TargetIndex.A, false, false); + yield return Toils_Haul.CarryHauledThingToContainer(); + Toil prepare = Toils_General.Wait(250); + prepare.WithProgressBarToilDelay(TargetIndex.B, false, -0.5f); + yield return prepare; + yield return new Toil + { + initAction = (Action)delegate + { + if (((_003CMakeNewToils_003Ec__Iterator24)/*Error near IL_0125: stateMachine*/)._003C_003Ef__this.pawn.carryTracker.CarriedThing == null) + { + Log.Error(((_003CMakeNewToils_003Ec__Iterator24)/*Error near IL_0125: stateMachine*/)._003C_003Ef__this.pawn + " tried to place hauled corpse in grave but is not hauling anything."); + } + else if (((_003CMakeNewToils_003Ec__Iterator24)/*Error near IL_0125: stateMachine*/)._003C_003Ef__this.Grave.TryAcceptThing(((_003CMakeNewToils_003Ec__Iterator24)/*Error near IL_0125: stateMachine*/)._003C_003Ef__this.Corpse, true)) + { + ((_003CMakeNewToils_003Ec__Iterator24)/*Error near IL_0125: stateMachine*/)._003C_003Ef__this.pawn.carryTracker.innerContainer.Remove(((_003CMakeNewToils_003Ec__Iterator24)/*Error near IL_0125: stateMachine*/)._003C_003Ef__this.Corpse); + ((_003CMakeNewToils_003Ec__Iterator24)/*Error near IL_0125: stateMachine*/)._003C_003Ef__this.Grave.Notify_CorpseBuried(((_003CMakeNewToils_003Ec__Iterator24)/*Error near IL_0125: stateMachine*/)._003C_003Ef__this.pawn); + ((_003CMakeNewToils_003Ec__Iterator24)/*Error near IL_0125: stateMachine*/)._003C_003Ef__this.pawn.records.Increment(RecordDefOf.CorpsesBuried); + } + } + }; } } } diff --git a/Assembly-CSharp/RimWorld/JobDriver_CarryToCryptosleepCasket.cs b/Assembly-CSharp/RimWorld/JobDriver_CarryToCryptosleepCasket.cs index f5f58dea5..fb52dcb94 100644 --- a/Assembly-CSharp/RimWorld/JobDriver_CarryToCryptosleepCasket.cs +++ b/Assembly-CSharp/RimWorld/JobDriver_CarryToCryptosleepCasket.cs @@ -1,6 +1,5 @@ using System; using System.Collections.Generic; -using System.Diagnostics; using Verse; using Verse.AI; @@ -28,14 +27,28 @@ protected Building_CryptosleepCasket DropPod } } - [DebuggerHidden] protected override IEnumerable MakeNewToils() { - JobDriver_CarryToCryptosleepCasket.c__Iterator25 c__Iterator = new JobDriver_CarryToCryptosleepCasket.c__Iterator25(); - c__Iterator.<>f__this = this; - JobDriver_CarryToCryptosleepCasket.c__Iterator25 expr_0E = c__Iterator; - expr_0E.$PC = -2; - return expr_0E; + this.FailOnDestroyedOrNull(TargetIndex.A); + this.FailOnDestroyedOrNull(TargetIndex.B); + this.FailOnAggroMentalState(TargetIndex.A); + yield return Toils_Reserve.Reserve(TargetIndex.A, 1, -1, null); + yield return Toils_Reserve.Reserve(TargetIndex.B, 1, -1, null); + yield return Toils_Goto.GotoThing(TargetIndex.A, PathEndMode.OnCell).FailOnDestroyedNullOrForbidden(TargetIndex.A).FailOnDespawnedNullOrForbidden(TargetIndex.B).FailOn((Func)(() => ((_003CMakeNewToils_003Ec__Iterator25)/*Error near IL_00aa: stateMachine*/)._003C_003Ef__this.DropPod.GetDirectlyHeldThings().Count > 0)).FailOn((Func)(() => !((_003CMakeNewToils_003Ec__Iterator25)/*Error near IL_00bb: stateMachine*/)._003C_003Ef__this.Takee.Downed)).FailOn((Func)(() => !((_003CMakeNewToils_003Ec__Iterator25)/*Error near IL_00cc: stateMachine*/)._003C_003Ef__this.pawn.CanReach((Thing)((_003CMakeNewToils_003Ec__Iterator25)/*Error near IL_00cc: stateMachine*/)._003C_003Ef__this.Takee, PathEndMode.OnCell, Danger.Deadly, false, TraverseMode.ByPawn))).FailOnSomeonePhysicallyInteracting(TargetIndex.A); + yield return Toils_Haul.StartCarryThing(TargetIndex.A, false, false); + yield return Toils_Goto.GotoThing(TargetIndex.B, PathEndMode.InteractionCell); + Toil prepare = Toils_General.Wait(500); + prepare.FailOnCannotTouch(TargetIndex.B, PathEndMode.InteractionCell); + prepare.WithProgressBarToilDelay(TargetIndex.B, false, -0.5f); + yield return prepare; + yield return new Toil + { + initAction = (Action)delegate + { + ((_003CMakeNewToils_003Ec__Iterator25)/*Error near IL_0181: stateMachine*/)._003C_003Ef__this.DropPod.TryAcceptThing(((_003CMakeNewToils_003Ec__Iterator25)/*Error near IL_0181: stateMachine*/)._003C_003Ef__this.Takee, true); + }, + defaultCompleteMode = ToilCompleteMode.Instant + }; } } } diff --git a/Assembly-CSharp/RimWorld/JobDriver_ChatWithPrisoner.cs b/Assembly-CSharp/RimWorld/JobDriver_ChatWithPrisoner.cs index 43ae3d563..a1cde5d21 100644 --- a/Assembly-CSharp/RimWorld/JobDriver_ChatWithPrisoner.cs +++ b/Assembly-CSharp/RimWorld/JobDriver_ChatWithPrisoner.cs @@ -1,6 +1,5 @@ using System; using System.Collections.Generic; -using System.Diagnostics; using Verse; using Verse.AI; @@ -16,14 +15,30 @@ protected Pawn Talkee } } - [DebuggerHidden] protected override IEnumerable MakeNewToils() { - JobDriver_ChatWithPrisoner.c__Iterator49 c__Iterator = new JobDriver_ChatWithPrisoner.c__Iterator49(); - c__Iterator.<>f__this = this; - JobDriver_ChatWithPrisoner.c__Iterator49 expr_0E = c__Iterator; - expr_0E.$PC = -2; - return expr_0E; + this.FailOnDespawnedOrNull(TargetIndex.A); + this.FailOnMentalState(TargetIndex.A); + this.FailOnNotAwake(TargetIndex.A); + this.FailOn((Func)(() => !((_003CMakeNewToils_003Ec__Iterator49)/*Error near IL_0086: stateMachine*/)._003C_003Ef__this.Talkee.IsPrisonerOfColony || !((_003CMakeNewToils_003Ec__Iterator49)/*Error near IL_0086: stateMachine*/)._003C_003Ef__this.Talkee.guest.PrisonerIsSecure)); + yield return Toils_Reserve.Reserve(TargetIndex.A, 1, -1, null); + yield return Toils_Interpersonal.GotoPrisoner(base.pawn, this.Talkee, this.Talkee.guest.interactionMode); + yield return Toils_Interpersonal.WaitToBeAbleToInteract(base.pawn); + yield return Toils_Interpersonal.ConvinceRecruitee(base.pawn, this.Talkee); + yield return Toils_Interpersonal.GotoPrisoner(base.pawn, this.Talkee, this.Talkee.guest.interactionMode); + yield return Toils_Interpersonal.ConvinceRecruitee(base.pawn, this.Talkee); + yield return Toils_Interpersonal.GotoPrisoner(base.pawn, this.Talkee, this.Talkee.guest.interactionMode); + yield return Toils_Interpersonal.ConvinceRecruitee(base.pawn, this.Talkee); + yield return Toils_Interpersonal.GotoPrisoner(base.pawn, this.Talkee, this.Talkee.guest.interactionMode); + yield return Toils_Interpersonal.ConvinceRecruitee(base.pawn, this.Talkee); + yield return Toils_Interpersonal.GotoPrisoner(base.pawn, this.Talkee, this.Talkee.guest.interactionMode); + yield return Toils_Interpersonal.ConvinceRecruitee(base.pawn, this.Talkee); + yield return Toils_Interpersonal.GotoPrisoner(base.pawn, this.Talkee, this.Talkee.guest.interactionMode); + yield return Toils_Interpersonal.SetLastInteractTime(TargetIndex.A); + if (base.CurJob.def == JobDefOf.PrisonerAttemptRecruit) + { + yield return Toils_Interpersonal.TryRecruit(TargetIndex.A); + } } } } diff --git a/Assembly-CSharp/RimWorld/JobDriver_CleanFilth.cs b/Assembly-CSharp/RimWorld/JobDriver_CleanFilth.cs index c4a3ecf3e..f97a7d628 100644 --- a/Assembly-CSharp/RimWorld/JobDriver_CleanFilth.cs +++ b/Assembly-CSharp/RimWorld/JobDriver_CleanFilth.cs @@ -1,6 +1,5 @@ using System; using System.Collections.Generic; -using System.Diagnostics; using Verse; using Verse.AI; @@ -24,14 +23,48 @@ private Filth Filth } } - [DebuggerHidden] protected override IEnumerable MakeNewToils() { - JobDriver_CleanFilth.c__Iterator26 c__Iterator = new JobDriver_CleanFilth.c__Iterator26(); - c__Iterator.<>f__this = this; - JobDriver_CleanFilth.c__Iterator26 expr_0E = c__Iterator; - expr_0E.$PC = -2; - return expr_0E; + yield return Toils_Reserve.ReserveQueue(TargetIndex.A, 1, -1, null); + Toil initExtractTargetFromQueue = Toils_JobTransforms.ClearDespawnedNullOrForbiddenQueuedTargets(TargetIndex.A); + yield return initExtractTargetFromQueue; + yield return Toils_JobTransforms.ExtractNextTargetFromQueue(TargetIndex.A); + Toil checkNextQueuedTarget = Toils_JobTransforms.ClearDespawnedNullOrForbiddenQueuedTargets(TargetIndex.A); + yield return Toils_Goto.GotoThing(TargetIndex.A, PathEndMode.Touch).JumpIfDespawnedOrNullOrForbidden(TargetIndex.A, checkNextQueuedTarget).JumpIfOutsideHomeArea(TargetIndex.A, checkNextQueuedTarget); + Toil clean = new Toil + { + initAction = (Action)delegate + { + ((_003CMakeNewToils_003Ec__Iterator26)/*Error near IL_00de: stateMachine*/)._003C_003Ef__this.cleaningWorkDone = 0f; + ((_003CMakeNewToils_003Ec__Iterator26)/*Error near IL_00de: stateMachine*/)._003C_003Ef__this.totalCleaningWorkDone = 0f; + ((_003CMakeNewToils_003Ec__Iterator26)/*Error near IL_00de: stateMachine*/)._003C_003Ef__this.totalCleaningWorkRequired = ((_003CMakeNewToils_003Ec__Iterator26)/*Error near IL_00de: stateMachine*/)._003C_003Ef__this.Filth.def.filth.cleaningWorkToReduceThickness * (float)((_003CMakeNewToils_003Ec__Iterator26)/*Error near IL_00de: stateMachine*/)._003C_003Ef__this.Filth.thickness; + }, + tickAction = (Action)delegate + { + Filth filth = ((_003CMakeNewToils_003Ec__Iterator26)/*Error near IL_00f5: stateMachine*/)._003C_003Ef__this.Filth; + ((_003CMakeNewToils_003Ec__Iterator26)/*Error near IL_00f5: stateMachine*/)._003C_003Ef__this.cleaningWorkDone += 1f; + ((_003CMakeNewToils_003Ec__Iterator26)/*Error near IL_00f5: stateMachine*/)._003C_003Ef__this.totalCleaningWorkDone += 1f; + if (((_003CMakeNewToils_003Ec__Iterator26)/*Error near IL_00f5: stateMachine*/)._003C_003Ef__this.cleaningWorkDone > filth.def.filth.cleaningWorkToReduceThickness) + { + filth.ThinFilth(); + ((_003CMakeNewToils_003Ec__Iterator26)/*Error near IL_00f5: stateMachine*/)._003C_003Ef__this.cleaningWorkDone = 0f; + if (filth.Destroyed) + { + ((_003CMakeNewToils_003Ec__Iterator26)/*Error near IL_00f5: stateMachine*/)._003Cclean_003E__2.actor.records.Increment(RecordDefOf.MessesCleaned); + ((_003CMakeNewToils_003Ec__Iterator26)/*Error near IL_00f5: stateMachine*/)._003C_003Ef__this.ReadyForNextToil(); + } + } + }, + defaultCompleteMode = ToilCompleteMode.Never + }; + clean.WithEffect(EffecterDefOf.Clean, TargetIndex.A); + clean.WithProgressBar(TargetIndex.A, (Func)(() => ((_003CMakeNewToils_003Ec__Iterator26)/*Error near IL_012b: stateMachine*/)._003C_003Ef__this.totalCleaningWorkDone / ((_003CMakeNewToils_003Ec__Iterator26)/*Error near IL_012b: stateMachine*/)._003C_003Ef__this.totalCleaningWorkRequired), true, -0.5f); + clean.PlaySustainerOrSound((Func)(() => SoundDefOf.Interact_CleanFilth)); + clean.JumpIfDespawnedOrNullOrForbidden(TargetIndex.A, checkNextQueuedTarget); + clean.JumpIfOutsideHomeArea(TargetIndex.A, checkNextQueuedTarget); + yield return clean; + yield return checkNextQueuedTarget; + yield return Toils_Jump.JumpIfHaveTargetInQueue(TargetIndex.A, initExtractTargetFromQueue); } public override void ExposeData() diff --git a/Assembly-CSharp/RimWorld/JobDriver_ClearSnow.cs b/Assembly-CSharp/RimWorld/JobDriver_ClearSnow.cs index b809b111f..ae96d95fd 100644 --- a/Assembly-CSharp/RimWorld/JobDriver_ClearSnow.cs +++ b/Assembly-CSharp/RimWorld/JobDriver_ClearSnow.cs @@ -1,6 +1,6 @@ using System; using System.Collections.Generic; -using System.Diagnostics; +using Verse; using Verse.AI; namespace RimWorld @@ -15,18 +15,35 @@ private float TotalNeededWork { get { - return 100f * base.Map.snowGrid.GetDepth(base.TargetLocA); + return (float)(100.0 * base.Map.snowGrid.GetDepth(base.TargetLocA)); } } - [DebuggerHidden] protected override IEnumerable MakeNewToils() { - JobDriver_ClearSnow.c__Iterator27 c__Iterator = new JobDriver_ClearSnow.c__Iterator27(); - c__Iterator.<>f__this = this; - JobDriver_ClearSnow.c__Iterator27 expr_0E = c__Iterator; - expr_0E.$PC = -2; - return expr_0E; + yield return Toils_Reserve.Reserve(TargetIndex.A, 1, -1, null); + yield return Toils_Goto.GotoCell(TargetIndex.A, PathEndMode.Touch); + Toil clearToil = new Toil + { + tickAction = (Action)delegate + { + Pawn actor = ((_003CMakeNewToils_003Ec__Iterator27)/*Error near IL_006e: stateMachine*/)._003CclearToil_003E__0.actor; + float statValue; + float num = statValue = actor.GetStatValue(StatDefOf.WorkSpeedGlobal, true); + ((_003CMakeNewToils_003Ec__Iterator27)/*Error near IL_006e: stateMachine*/)._003C_003Ef__this.workDone += statValue; + if (((_003CMakeNewToils_003Ec__Iterator27)/*Error near IL_006e: stateMachine*/)._003C_003Ef__this.workDone >= ((_003CMakeNewToils_003Ec__Iterator27)/*Error near IL_006e: stateMachine*/)._003C_003Ef__this.TotalNeededWork) + { + ((_003CMakeNewToils_003Ec__Iterator27)/*Error near IL_006e: stateMachine*/)._003C_003Ef__this.Map.snowGrid.SetDepth(((_003CMakeNewToils_003Ec__Iterator27)/*Error near IL_006e: stateMachine*/)._003C_003Ef__this.TargetLocA, 0f); + ((_003CMakeNewToils_003Ec__Iterator27)/*Error near IL_006e: stateMachine*/)._003C_003Ef__this.ReadyForNextToil(); + } + }, + defaultCompleteMode = ToilCompleteMode.Never + }; + clearToil.WithEffect(EffecterDefOf.ClearSnow, TargetIndex.A); + clearToil.PlaySustainerOrSound((Func)(() => SoundDefOf.Interact_ClearSnow)); + clearToil.WithProgressBar(TargetIndex.A, (Func)(() => ((_003CMakeNewToils_003Ec__Iterator27)/*Error near IL_00cd: stateMachine*/)._003C_003Ef__this.workDone / ((_003CMakeNewToils_003Ec__Iterator27)/*Error near IL_00cd: stateMachine*/)._003C_003Ef__this.TotalNeededWork), true, -0.5f); + clearToil.FailOnCannotTouch(TargetIndex.A, PathEndMode.Touch); + yield return clearToil; } } } diff --git a/Assembly-CSharp/RimWorld/JobDriver_ConstructFinishFrame.cs b/Assembly-CSharp/RimWorld/JobDriver_ConstructFinishFrame.cs index fd7578f2c..807771412 100644 --- a/Assembly-CSharp/RimWorld/JobDriver_ConstructFinishFrame.cs +++ b/Assembly-CSharp/RimWorld/JobDriver_ConstructFinishFrame.cs @@ -1,6 +1,7 @@ using System; using System.Collections.Generic; -using System.Diagnostics; +using UnityEngine; +using Verse; using Verse.AI; namespace RimWorld @@ -9,14 +10,54 @@ public class JobDriver_ConstructFinishFrame : JobDriver { private const int JobEndInterval = 5000; - [DebuggerHidden] protected override IEnumerable MakeNewToils() { - JobDriver_ConstructFinishFrame.c__IteratorE c__IteratorE = new JobDriver_ConstructFinishFrame.c__IteratorE(); - c__IteratorE.<>f__this = this; - JobDriver_ConstructFinishFrame.c__IteratorE expr_0E = c__IteratorE; - expr_0E.$PC = -2; - return expr_0E; + yield return Toils_Reserve.Reserve(TargetIndex.A, 1, -1, null); + yield return Toils_Goto.GotoThing(TargetIndex.A, PathEndMode.Touch).FailOnDespawnedNullOrForbidden(TargetIndex.A); + Toil build = new Toil + { + initAction = (Action)delegate + { + GenClamor.DoClamor(((_003CMakeNewToils_003Ec__IteratorE)/*Error near IL_0074: stateMachine*/)._003Cbuild_003E__0.actor, 15f, ClamorType.Construction); + }, + tickAction = (Action)delegate + { + Pawn actor = ((_003CMakeNewToils_003Ec__IteratorE)/*Error near IL_008b: stateMachine*/)._003Cbuild_003E__0.actor; + Frame frame = (Frame)actor.jobs.curJob.GetTarget(TargetIndex.A).Thing; + if (frame.resourceContainer.Count > 0) + { + actor.skills.Learn(SkillDefOf.Construction, 0.275f, false); + } + float statValue = actor.GetStatValue(StatDefOf.ConstructionSpeed, true); + float workToMake = frame.WorkToMake; + if (actor.Faction == Faction.OfPlayer) + { + float statValue2 = actor.GetStatValue(StatDefOf.ConstructSuccessChance, true); + if (Rand.Value < 1.0 - Mathf.Pow(statValue2, statValue / workToMake)) + { + frame.FailConstruction(actor); + ((_003CMakeNewToils_003Ec__IteratorE)/*Error near IL_008b: stateMachine*/)._003C_003Ef__this.ReadyForNextToil(); + return; + } + } + if (frame.def.entityDefToBuild is TerrainDef) + { + ((_003CMakeNewToils_003Ec__IteratorE)/*Error near IL_008b: stateMachine*/)._003C_003Ef__this.Map.snowGrid.SetDepth(frame.Position, 0f); + } + frame.workDone += statValue; + if (frame.workDone >= workToMake) + { + frame.CompleteConstruction(actor); + ((_003CMakeNewToils_003Ec__IteratorE)/*Error near IL_008b: stateMachine*/)._003C_003Ef__this.ReadyForNextToil(); + } + } + }; + build.WithEffect((Func)(() => ((Frame)((_003CMakeNewToils_003Ec__IteratorE)/*Error near IL_00a2: stateMachine*/)._003Cbuild_003E__0.actor.jobs.curJob.GetTarget(TargetIndex.A).Thing).ConstructionEffect), TargetIndex.A); + build.FailOnDespawnedNullOrForbidden(TargetIndex.A); + build.FailOnCannotTouch(TargetIndex.A, PathEndMode.Touch); + build.defaultCompleteMode = ToilCompleteMode.Delay; + build.defaultDuration = 5000; + yield return build; } } } diff --git a/Assembly-CSharp/RimWorld/JobDriver_Deconstruct.cs b/Assembly-CSharp/RimWorld/JobDriver_Deconstruct.cs index cc2be1f25..6e52274cd 100644 --- a/Assembly-CSharp/RimWorld/JobDriver_Deconstruct.cs +++ b/Assembly-CSharp/RimWorld/JobDriver_Deconstruct.cs @@ -1,4 +1,3 @@ -using System; using UnityEngine; using Verse; @@ -29,14 +28,14 @@ protected override int TotalNeededWork protected override void FinishedRemoving() { base.Target.Destroy(DestroyMode.Deconstruct); - this.pawn.records.Increment(RecordDefOf.ThingsDeconstructed); + base.pawn.records.Increment(RecordDefOf.ThingsDeconstructed); } protected override void TickAction() { if (base.Target.def.CostListAdjusted(base.Target.Stuff, true).Count > 0) { - this.pawn.skills.Learn(SkillDefOf.Construction, 0.275f, false); + base.pawn.skills.Learn(SkillDefOf.Construction, 0.275f, false); } } } diff --git a/Assembly-CSharp/RimWorld/JobDriver_DropEquipment.cs b/Assembly-CSharp/RimWorld/JobDriver_DropEquipment.cs index e027ecbbd..58fa0c6fe 100644 --- a/Assembly-CSharp/RimWorld/JobDriver_DropEquipment.cs +++ b/Assembly-CSharp/RimWorld/JobDriver_DropEquipment.cs @@ -1,6 +1,5 @@ using System; using System.Collections.Generic; -using System.Diagnostics; using Verse; using Verse.AI; @@ -18,14 +17,28 @@ private ThingWithComps TargetEquipment } } - [DebuggerHidden] protected override IEnumerable MakeNewToils() { - JobDriver_DropEquipment.c__Iterator52 c__Iterator = new JobDriver_DropEquipment.c__Iterator52(); - c__Iterator.<>f__this = this; - JobDriver_DropEquipment.c__Iterator52 expr_0E = c__Iterator; - expr_0E.$PC = -2; - return expr_0E; + yield return new Toil + { + initAction = (Action)delegate + { + ((_003CMakeNewToils_003Ec__Iterator52)/*Error near IL_0036: stateMachine*/)._003C_003Ef__this.pawn.pather.StopDead(); + }, + defaultCompleteMode = ToilCompleteMode.Delay, + defaultDuration = 30 + }; + yield return new Toil + { + initAction = (Action)delegate + { + ThingWithComps thingWithComps = default(ThingWithComps); + if (!((_003CMakeNewToils_003Ec__Iterator52)/*Error near IL_0089: stateMachine*/)._003C_003Ef__this.pawn.equipment.TryDropEquipment(((_003CMakeNewToils_003Ec__Iterator52)/*Error near IL_0089: stateMachine*/)._003C_003Ef__this.TargetEquipment, out thingWithComps, ((_003CMakeNewToils_003Ec__Iterator52)/*Error near IL_0089: stateMachine*/)._003C_003Ef__this.pawn.Position, true)) + { + ((_003CMakeNewToils_003Ec__Iterator52)/*Error near IL_0089: stateMachine*/)._003C_003Ef__this.EndJobWith(JobCondition.Incompletable); + } + } + }; } } } diff --git a/Assembly-CSharp/RimWorld/JobDriver_EnterCryptosleepCasket.cs b/Assembly-CSharp/RimWorld/JobDriver_EnterCryptosleepCasket.cs index c51a9c202..6a5bc8572 100644 --- a/Assembly-CSharp/RimWorld/JobDriver_EnterCryptosleepCasket.cs +++ b/Assembly-CSharp/RimWorld/JobDriver_EnterCryptosleepCasket.cs @@ -1,20 +1,52 @@ using System; using System.Collections.Generic; -using System.Diagnostics; +using Verse; using Verse.AI; namespace RimWorld { public class JobDriver_EnterCryptosleepCasket : JobDriver { - [DebuggerHidden] protected override IEnumerable MakeNewToils() { - JobDriver_EnterCryptosleepCasket.c__Iterator28 c__Iterator = new JobDriver_EnterCryptosleepCasket.c__Iterator28(); - c__Iterator.<>f__this = this; - JobDriver_EnterCryptosleepCasket.c__Iterator28 expr_0E = c__Iterator; - expr_0E.$PC = -2; - return expr_0E; + this.FailOnDespawnedOrNull(TargetIndex.A); + yield return Toils_Reserve.Reserve(TargetIndex.A, 1, -1, null); + yield return Toils_Goto.GotoThing(TargetIndex.A, PathEndMode.InteractionCell); + Toil prepare = Toils_General.Wait(500); + prepare.FailOnCannotTouch(TargetIndex.A, PathEndMode.InteractionCell); + prepare.WithProgressBarToilDelay(TargetIndex.A, false, -0.5f); + yield return prepare; + yield return new Toil + { + initAction = (Action)delegate + { + _003CMakeNewToils_003Ec__Iterator28 _003CMakeNewToils_003Ec__Iterator = (_003CMakeNewToils_003Ec__Iterator28)/*Error near IL_00c8: stateMachine*/; + Pawn actor = ((_003CMakeNewToils_003Ec__Iterator28)/*Error near IL_00c8: stateMachine*/)._003Center_003E__1.actor; + Building_CryptosleepCasket pod = (Building_CryptosleepCasket)actor.CurJob.targetA.Thing; + Action action = (Action)delegate + { + actor.DeSpawn(); + pod.TryAcceptThing(actor, true); + }; + if (!pod.def.building.isPlayerEjectable) + { + int freeColonistsSpawnedOrInPlayerEjectablePodsCount = ((_003CMakeNewToils_003Ec__Iterator28)/*Error near IL_00c8: stateMachine*/)._003C_003Ef__this.Map.mapPawns.FreeColonistsSpawnedOrInPlayerEjectablePodsCount; + if (freeColonistsSpawnedOrInPlayerEjectablePodsCount <= 1) + { + Find.WindowStack.Add(Dialog_MessageBox.CreateConfirmation("CasketWarning".Translate().AdjustedFor(actor), action, false, (string)null)); + } + else + { + action(); + } + } + else + { + action(); + } + }, + defaultCompleteMode = ToilCompleteMode.Instant + }; } } } diff --git a/Assembly-CSharp/RimWorld/JobDriver_EnterTransporter.cs b/Assembly-CSharp/RimWorld/JobDriver_EnterTransporter.cs index 21d749796..b3f9db6d2 100644 --- a/Assembly-CSharp/RimWorld/JobDriver_EnterTransporter.cs +++ b/Assembly-CSharp/RimWorld/JobDriver_EnterTransporter.cs @@ -1,6 +1,5 @@ using System; using System.Collections.Generic; -using System.Diagnostics; using Verse; using Verse.AI; @@ -23,14 +22,21 @@ private CompTransporter Transporter } } - [DebuggerHidden] protected override IEnumerable MakeNewToils() { - JobDriver_EnterTransporter.c__Iterator29 c__Iterator = new JobDriver_EnterTransporter.c__Iterator29(); - c__Iterator.<>f__this = this; - JobDriver_EnterTransporter.c__Iterator29 expr_0E = c__Iterator; - expr_0E.$PC = -2; - return expr_0E; + this.FailOnDespawnedOrNull(this.TransporterInd); + this.FailOn((Func)(() => !((_003CMakeNewToils_003Ec__Iterator29)/*Error near IL_0046: stateMachine*/)._003C_003Ef__this.Transporter.LoadingInProgressOrReadyToLaunch)); + yield return Toils_Reserve.Reserve(this.TransporterInd, 1, -1, null); + yield return Toils_Goto.GotoThing(this.TransporterInd, PathEndMode.Touch); + yield return new Toil + { + initAction = (Action)delegate + { + CompTransporter transporter = ((_003CMakeNewToils_003Ec__Iterator29)/*Error near IL_00b1: stateMachine*/)._003C_003Ef__this.Transporter; + ((_003CMakeNewToils_003Ec__Iterator29)/*Error near IL_00b1: stateMachine*/)._003C_003Ef__this.pawn.DeSpawn(); + transporter.GetDirectlyHeldThings().TryAdd(((_003CMakeNewToils_003Ec__Iterator29)/*Error near IL_00b1: stateMachine*/)._003C_003Ef__this.pawn, true); + } + }; } } } diff --git a/Assembly-CSharp/RimWorld/JobDriver_Execute.cs b/Assembly-CSharp/RimWorld/JobDriver_Execute.cs index e48abd892..eb4877fbf 100644 --- a/Assembly-CSharp/RimWorld/JobDriver_Execute.cs +++ b/Assembly-CSharp/RimWorld/JobDriver_Execute.cs @@ -1,6 +1,5 @@ using System; using System.Collections.Generic; -using System.Diagnostics; using Verse; using Verse.AI; @@ -16,14 +15,21 @@ protected Pawn Victim } } - [DebuggerHidden] protected override IEnumerable MakeNewToils() { - JobDriver_Execute.c__Iterator4A c__Iterator4A = new JobDriver_Execute.c__Iterator4A(); - c__Iterator4A.<>f__this = this; - JobDriver_Execute.c__Iterator4A expr_0E = c__Iterator4A; - expr_0E.$PC = -2; - return expr_0E; + this.FailOnAggroMentalState(TargetIndex.A); + yield return Toils_Reserve.Reserve(TargetIndex.A, 1, -1, null); + yield return Toils_Interpersonal.GotoPrisoner(base.pawn, this.Victim, PrisonerInteractionModeDefOf.Execution).FailOn((Func)(() => !((_003CMakeNewToils_003Ec__Iterator4A)/*Error near IL_0072: stateMachine*/)._003C_003Ef__this.Victim.IsPrisonerOfColony || !((_003CMakeNewToils_003Ec__Iterator4A)/*Error near IL_0072: stateMachine*/)._003C_003Ef__this.Victim.guest.PrisonerIsSecure)); + yield return new Toil + { + initAction = (Action)delegate + { + ExecutionUtility.DoExecutionByCut(((_003CMakeNewToils_003Ec__Iterator4A)/*Error near IL_00a5: stateMachine*/)._003Cexecute_003E__0.actor, ((_003CMakeNewToils_003Ec__Iterator4A)/*Error near IL_00a5: stateMachine*/)._003C_003Ef__this.Victim); + ThoughtUtility.GiveThoughtsForPawnExecuted(((_003CMakeNewToils_003Ec__Iterator4A)/*Error near IL_00a5: stateMachine*/)._003C_003Ef__this.Victim, PawnExecutionKind.GenericBrutal); + TaleRecorder.RecordTale(TaleDefOf.ExecutedPrisoner, ((_003CMakeNewToils_003Ec__Iterator4A)/*Error near IL_00a5: stateMachine*/)._003C_003Ef__this.pawn, ((_003CMakeNewToils_003Ec__Iterator4A)/*Error near IL_00a5: stateMachine*/)._003C_003Ef__this.Victim); + }, + defaultCompleteMode = ToilCompleteMode.Instant + }; } } } diff --git a/Assembly-CSharp/RimWorld/JobDriver_ExtinguishSelf.cs b/Assembly-CSharp/RimWorld/JobDriver_ExtinguishSelf.cs index ec12f61d1..eb30e9061 100644 --- a/Assembly-CSharp/RimWorld/JobDriver_ExtinguishSelf.cs +++ b/Assembly-CSharp/RimWorld/JobDriver_ExtinguishSelf.cs @@ -1,6 +1,5 @@ using System; using System.Collections.Generic; -using System.Diagnostics; using Verse; using Verse.AI; @@ -22,22 +21,33 @@ public override string GetReport() { if (this.TargetFire.parent != null) { - return "ReportExtinguishingFireOn".Translate(new object[] - { - this.TargetFire.parent.LabelCap - }); + return "ReportExtinguishingFireOn".Translate(this.TargetFire.parent.LabelCap); } return "ReportExtinguishingFire".Translate(); } - [DebuggerHidden] protected override IEnumerable MakeNewToils() { - JobDriver_ExtinguishSelf.c__Iterator15 c__Iterator = new JobDriver_ExtinguishSelf.c__Iterator15(); - c__Iterator.<>f__this = this; - JobDriver_ExtinguishSelf.c__Iterator15 expr_0E = c__Iterator; - expr_0E.$PC = -2; - return expr_0E; + yield return new Toil + { + initAction = (Action)delegate + { + }, + defaultCompleteMode = ToilCompleteMode.Delay, + defaultDuration = 150 + }; + yield return new Toil + { + initAction = (Action)delegate + { + if (!((_003CMakeNewToils_003Ec__Iterator15)/*Error near IL_009d: stateMachine*/)._003C_003Ef__this.TargetFire.Destroyed) + { + ((_003CMakeNewToils_003Ec__Iterator15)/*Error near IL_009d: stateMachine*/)._003C_003Ef__this.TargetFire.Destroy(DestroyMode.Vanish); + ((_003CMakeNewToils_003Ec__Iterator15)/*Error near IL_009d: stateMachine*/)._003C_003Ef__this.pawn.records.Increment(RecordDefOf.FiresExtinguished); + } + }, + defaultCompleteMode = ToilCompleteMode.Instant + }; } } } diff --git a/Assembly-CSharp/RimWorld/JobDriver_FillFermentingBarrel.cs b/Assembly-CSharp/RimWorld/JobDriver_FillFermentingBarrel.cs index 9d2650815..16e442b97 100644 --- a/Assembly-CSharp/RimWorld/JobDriver_FillFermentingBarrel.cs +++ b/Assembly-CSharp/RimWorld/JobDriver_FillFermentingBarrel.cs @@ -1,6 +1,5 @@ using System; using System.Collections.Generic; -using System.Diagnostics; using Verse; using Verse.AI; @@ -30,14 +29,26 @@ protected Thing Wort } } - [DebuggerHidden] protected override IEnumerable MakeNewToils() { - JobDriver_FillFermentingBarrel.c__Iterator2A c__Iterator2A = new JobDriver_FillFermentingBarrel.c__Iterator2A(); - c__Iterator2A.<>f__this = this; - JobDriver_FillFermentingBarrel.c__Iterator2A expr_0E = c__Iterator2A; - expr_0E.$PC = -2; - return expr_0E; + this.FailOnDespawnedNullOrForbidden(TargetIndex.A); + this.FailOnBurningImmobile(TargetIndex.A); + yield return Toils_Reserve.Reserve(TargetIndex.A, 1, -1, null); + Toil reserveWort = Toils_Reserve.Reserve(TargetIndex.B, 1, -1, null); + yield return reserveWort; + yield return Toils_Goto.GotoThing(TargetIndex.B, PathEndMode.ClosestTouch).FailOnDespawnedNullOrForbidden(TargetIndex.B).FailOnSomeonePhysicallyInteracting(TargetIndex.B); + yield return Toils_Haul.StartCarryThing(TargetIndex.B, false, true).FailOnDestroyedNullOrForbidden(TargetIndex.B); + yield return Toils_Haul.CheckForGetOpportunityDuplicate(reserveWort, TargetIndex.B, TargetIndex.None, true, null); + yield return Toils_Goto.GotoThing(TargetIndex.A, PathEndMode.Touch); + yield return Toils_General.Wait(200).FailOnDestroyedNullOrForbidden(TargetIndex.B).FailOnDestroyedNullOrForbidden(TargetIndex.A).FailOnCannotTouch(TargetIndex.A, PathEndMode.Touch).WithProgressBarToilDelay(TargetIndex.A, false, -0.5f); + yield return new Toil + { + initAction = (Action)delegate + { + ((_003CMakeNewToils_003Ec__Iterator2A)/*Error near IL_0164: stateMachine*/)._003C_003Ef__this.Barrel.AddWort(((_003CMakeNewToils_003Ec__Iterator2A)/*Error near IL_0164: stateMachine*/)._003C_003Ef__this.Wort); + }, + defaultCompleteMode = ToilCompleteMode.Instant + }; } } } diff --git a/Assembly-CSharp/RimWorld/JobDriver_FixBrokenDownBuilding.cs b/Assembly-CSharp/RimWorld/JobDriver_FixBrokenDownBuilding.cs index c846b3fe1..336662880 100644 --- a/Assembly-CSharp/RimWorld/JobDriver_FixBrokenDownBuilding.cs +++ b/Assembly-CSharp/RimWorld/JobDriver_FixBrokenDownBuilding.cs @@ -1,6 +1,6 @@ using System; using System.Collections.Generic; -using System.Diagnostics; +using UnityEngine; using Verse; using Verse.AI; @@ -30,14 +30,36 @@ private Thing Components } } - [DebuggerHidden] protected override IEnumerable MakeNewToils() { - JobDriver_FixBrokenDownBuilding.c__Iterator10 c__Iterator = new JobDriver_FixBrokenDownBuilding.c__Iterator10(); - c__Iterator.<>f__this = this; - JobDriver_FixBrokenDownBuilding.c__Iterator10 expr_0E = c__Iterator; - expr_0E.$PC = -2; - return expr_0E; + this.FailOnDespawnedNullOrForbidden(TargetIndex.A); + yield return Toils_Reserve.Reserve(TargetIndex.A, 1, -1, null); + yield return Toils_Reserve.Reserve(TargetIndex.B, 1, -1, null); + yield return Toils_Goto.GotoThing(TargetIndex.B, PathEndMode.Touch).FailOnDespawnedNullOrForbidden(TargetIndex.B).FailOnSomeonePhysicallyInteracting(TargetIndex.B); + yield return Toils_Haul.StartCarryThing(TargetIndex.B, false, false); + yield return Toils_Goto.GotoThing(TargetIndex.A, PathEndMode.Touch).FailOnDespawnedOrNull(TargetIndex.A); + Toil repair = Toils_General.Wait(1000); + repair.FailOnDespawnedOrNull(TargetIndex.A); + repair.FailOnCannotTouch(TargetIndex.A, PathEndMode.Touch); + repair.WithEffect(this.Building.def.repairEffect, TargetIndex.A); + repair.WithProgressBarToilDelay(TargetIndex.A, false, -0.5f); + yield return repair; + yield return new Toil + { + initAction = (Action)delegate + { + ((_003CMakeNewToils_003Ec__Iterator10)/*Error near IL_0163: stateMachine*/)._003C_003Ef__this.Components.Destroy(DestroyMode.Vanish); + if (Rand.Value > ((_003CMakeNewToils_003Ec__Iterator10)/*Error near IL_0163: stateMachine*/)._003C_003Ef__this.pawn.GetStatValue(StatDefOf.FixBrokenDownBuildingSuccessChance, true)) + { + Vector3 loc = (((_003CMakeNewToils_003Ec__Iterator10)/*Error near IL_0163: stateMachine*/)._003C_003Ef__this.pawn.DrawPos + ((_003CMakeNewToils_003Ec__Iterator10)/*Error near IL_0163: stateMachine*/)._003C_003Ef__this.Building.DrawPos) / 2f; + MoteMaker.ThrowText(loc, ((_003CMakeNewToils_003Ec__Iterator10)/*Error near IL_0163: stateMachine*/)._003C_003Ef__this.Map, "TextMote_FixBrokenDownBuildingFail".Translate(), 3.65f); + } + else + { + ((_003CMakeNewToils_003Ec__Iterator10)/*Error near IL_0163: stateMachine*/)._003C_003Ef__this.Building.GetComp().Notify_Repaired(); + } + } + }; } } } diff --git a/Assembly-CSharp/RimWorld/JobDriver_Flee.cs b/Assembly-CSharp/RimWorld/JobDriver_Flee.cs index 95440b0a3..969831a1b 100644 --- a/Assembly-CSharp/RimWorld/JobDriver_Flee.cs +++ b/Assembly-CSharp/RimWorld/JobDriver_Flee.cs @@ -1,6 +1,5 @@ using System; using System.Collections.Generic; -using System.Diagnostics; using Verse.AI; namespace RimWorld @@ -9,14 +8,22 @@ public class JobDriver_Flee : JobDriver { protected const TargetIndex DestInd = TargetIndex.A; - [DebuggerHidden] protected override IEnumerable MakeNewToils() { - JobDriver_Flee.c__Iterator2B c__Iterator2B = new JobDriver_Flee.c__Iterator2B(); - c__Iterator2B.<>f__this = this; - JobDriver_Flee.c__Iterator2B expr_0E = c__Iterator2B; - expr_0E.$PC = -2; - return expr_0E; + yield return new Toil + { + atomicWithPrevious = true, + defaultCompleteMode = ToilCompleteMode.Instant, + initAction = (Action)delegate + { + ((_003CMakeNewToils_003Ec__Iterator2B)/*Error near IL_004e: stateMachine*/)._003C_003Ef__this.Map.pawnDestinationManager.ReserveDestinationFor(((_003CMakeNewToils_003Ec__Iterator2B)/*Error near IL_004e: stateMachine*/)._003C_003Ef__this.pawn, ((_003CMakeNewToils_003Ec__Iterator2B)/*Error near IL_004e: stateMachine*/)._003C_003Ef__this.CurJob.GetTarget(TargetIndex.A).Cell); + if (((_003CMakeNewToils_003Ec__Iterator2B)/*Error near IL_004e: stateMachine*/)._003C_003Ef__this.pawn.IsColonist) + { + MoteMaker.MakeColonistActionOverlay(((_003CMakeNewToils_003Ec__Iterator2B)/*Error near IL_004e: stateMachine*/)._003C_003Ef__this.pawn, ThingDefOf.Mote_ColonistFleeing); + } + } + }; + yield return Toils_Goto.GotoCell(TargetIndex.A, PathEndMode.OnCell); } } } diff --git a/Assembly-CSharp/RimWorld/JobDriver_FleeAndCower.cs b/Assembly-CSharp/RimWorld/JobDriver_FleeAndCower.cs index 098a70343..caa960ffb 100644 --- a/Assembly-CSharp/RimWorld/JobDriver_FleeAndCower.cs +++ b/Assembly-CSharp/RimWorld/JobDriver_FleeAndCower.cs @@ -1,6 +1,5 @@ using System; using System.Collections.Generic; -using System.Diagnostics; using Verse; using Verse.AI; @@ -14,21 +13,31 @@ public class JobDriver_FleeAndCower : JobDriver_Flee public override string GetReport() { - if (this.pawn.Position != base.CurJob.GetTarget(TargetIndex.A).Cell) + if (base.pawn.Position != base.CurJob.GetTarget(TargetIndex.A).Cell) { return base.GetReport(); } return "ReportCowering".Translate(); } - [DebuggerHidden] protected override IEnumerable MakeNewToils() { - JobDriver_FleeAndCower.c__Iterator2C c__Iterator2C = new JobDriver_FleeAndCower.c__Iterator2C(); - c__Iterator2C.<>f__this = this; - JobDriver_FleeAndCower.c__Iterator2C expr_0E = c__Iterator2C; - expr_0E.$PC = -2; - return expr_0E; + foreach (Toil item in base.MakeNewToils()) + { + yield return item; + } + yield return new Toil + { + defaultCompleteMode = ToilCompleteMode.Delay, + defaultDuration = 1200, + tickAction = (Action)delegate + { + if (((_003CMakeNewToils_003Ec__Iterator2C)/*Error near IL_00d7: stateMachine*/)._003C_003Ef__this.pawn.IsHashIntervalTick(35) && SelfDefenseUtility.ShouldStartFleeing(((_003CMakeNewToils_003Ec__Iterator2C)/*Error near IL_00d7: stateMachine*/)._003C_003Ef__this.pawn)) + { + ((_003CMakeNewToils_003Ec__Iterator2C)/*Error near IL_00d7: stateMachine*/)._003C_003Ef__this.EndJobWith(JobCondition.InterruptForced); + } + } + }; } } } diff --git a/Assembly-CSharp/RimWorld/JobDriver_Flick.cs b/Assembly-CSharp/RimWorld/JobDriver_Flick.cs index 2a6ebb0f9..572655cf6 100644 --- a/Assembly-CSharp/RimWorld/JobDriver_Flick.cs +++ b/Assembly-CSharp/RimWorld/JobDriver_Flick.cs @@ -1,20 +1,49 @@ using System; using System.Collections.Generic; -using System.Diagnostics; +using Verse; using Verse.AI; namespace RimWorld { public class JobDriver_Flick : JobDriver { - [DebuggerHidden] protected override IEnumerable MakeNewToils() { - JobDriver_Flick.c__Iterator2D c__Iterator2D = new JobDriver_Flick.c__Iterator2D(); - c__Iterator2D.<>f__this = this; - JobDriver_Flick.c__Iterator2D expr_0E = c__Iterator2D; - expr_0E.$PC = -2; - return expr_0E; + this.FailOn((Func)delegate + { + Designation designation2 = ((_003CMakeNewToils_003Ec__Iterator2D)/*Error near IL_0033: stateMachine*/)._003C_003Ef__this.Map.designationManager.DesignationOn(((_003CMakeNewToils_003Ec__Iterator2D)/*Error near IL_0033: stateMachine*/)._003C_003Ef__this.TargetThingA, DesignationDefOf.Flick); + if (designation2 != null) + { + return false; + } + return true; + }); + yield return Toils_Reserve.Reserve(TargetIndex.A, 1, -1, null); + yield return Toils_Goto.GotoThing(TargetIndex.A, PathEndMode.Touch); + yield return Toils_General.Wait(15).FailOnCannotTouch(TargetIndex.A, PathEndMode.Touch); + yield return new Toil + { + initAction = (Action)delegate + { + Pawn actor = ((_003CMakeNewToils_003Ec__Iterator2D)/*Error near IL_00aa: stateMachine*/)._003Cfinalize_003E__0.actor; + ThingWithComps thingWithComps = (ThingWithComps)actor.CurJob.targetA.Thing; + for (int i = 0; i < thingWithComps.AllComps.Count; i++) + { + CompFlickable compFlickable = thingWithComps.AllComps[i] as CompFlickable; + if (compFlickable != null && compFlickable.WantsFlick()) + { + compFlickable.DoFlick(); + } + } + actor.records.Increment(RecordDefOf.SwitchesFlicked); + Designation designation = ((_003CMakeNewToils_003Ec__Iterator2D)/*Error near IL_00aa: stateMachine*/)._003C_003Ef__this.Map.designationManager.DesignationOn(thingWithComps, DesignationDefOf.Flick); + if (designation != null) + { + designation.Delete(); + } + }, + defaultCompleteMode = ToilCompleteMode.Instant + }; } } } diff --git a/Assembly-CSharp/RimWorld/JobDriver_FoodDeliver.cs b/Assembly-CSharp/RimWorld/JobDriver_FoodDeliver.cs index e1d26cf35..649c523fc 100644 --- a/Assembly-CSharp/RimWorld/JobDriver_FoodDeliver.cs +++ b/Assembly-CSharp/RimWorld/JobDriver_FoodDeliver.cs @@ -1,6 +1,5 @@ using System; using System.Collections.Generic; -using System.Diagnostics; using Verse; using Verse.AI; @@ -35,7 +34,7 @@ public override string GetReport() { if (base.CurJob.GetTarget(TargetIndex.A).Thing is Building_NutrientPasteDispenser) { - return base.CurJob.def.reportString.Replace("TargetA", ThingDefOf.MealNutrientPaste.label).Replace("TargetB", ((Pawn)((Thing)base.CurJob.targetB)).LabelShort); + return base.CurJob.def.reportString.Replace("TargetA", ThingDefOf.MealNutrientPaste.label).Replace("TargetB", ((Pawn)(Thing)base.CurJob.targetB).LabelShort); } return base.GetReport(); } @@ -44,17 +43,61 @@ public override void Notify_Starting() { base.Notify_Starting(); this.usingNutrientPasteDispenser = (base.TargetThingA is Building_NutrientPasteDispenser); - this.eatingFromInventory = (this.pawn.inventory != null && this.pawn.inventory.Contains(base.TargetThingA)); + this.eatingFromInventory = (base.pawn.inventory != null && base.pawn.inventory.Contains(base.TargetThingA)); } - [DebuggerHidden] protected override IEnumerable MakeNewToils() { - JobDriver_FoodDeliver.c__Iterator4B c__Iterator4B = new JobDriver_FoodDeliver.c__Iterator4B(); - c__Iterator4B.<>f__this = this; - JobDriver_FoodDeliver.c__Iterator4B expr_0E = c__Iterator4B; - expr_0E.$PC = -2; - return expr_0E; + yield return Toils_Reserve.Reserve(TargetIndex.B, 1, -1, null); + if (this.eatingFromInventory) + { + yield return Toils_Misc.TakeItemFromInventoryToCarrier(base.pawn, TargetIndex.A); + } + else if (this.usingNutrientPasteDispenser) + { + yield return Toils_Goto.GotoThing(TargetIndex.A, PathEndMode.InteractionCell).FailOnForbidden(TargetIndex.A); + yield return Toils_Ingest.TakeMealFromDispenser(TargetIndex.A, base.pawn); + } + else + { + yield return Toils_Reserve.Reserve(TargetIndex.A, 1, -1, null); + yield return Toils_Goto.GotoThing(TargetIndex.A, PathEndMode.ClosestTouch).FailOnForbidden(TargetIndex.A); + yield return Toils_Ingest.PickupIngestible(TargetIndex.A, this.Deliveree); + } + Toil toil = new Toil + { + initAction = (Action)delegate + { + Pawn actor = ((_003CMakeNewToils_003Ec__Iterator4B)/*Error near IL_0159: stateMachine*/)._003Ctoil_003E__0.actor; + Job curJob = actor.jobs.curJob; + actor.pather.StartPath(curJob.targetC, PathEndMode.OnCell); + }, + defaultCompleteMode = ToilCompleteMode.PatherArrival + }; + toil.FailOnDestroyedNullOrForbidden(TargetIndex.B); + toil.AddFailCondition((Func)delegate + { + Pawn pawn = (Pawn)((_003CMakeNewToils_003Ec__Iterator4B)/*Error near IL_0189: stateMachine*/)._003Ctoil_003E__0.actor.jobs.curJob.targetB.Thing; + if (!pawn.IsPrisonerOfColony) + { + return true; + } + if (!pawn.guest.CanBeBroughtFood) + { + return true; + } + return false; + }); + yield return toil; + yield return new Toil + { + initAction = (Action)delegate + { + Thing thing = default(Thing); + ((_003CMakeNewToils_003Ec__Iterator4B)/*Error near IL_01c3: stateMachine*/)._003C_003Ef__this.pawn.carryTracker.TryDropCarriedThing(((_003CMakeNewToils_003Ec__Iterator4B)/*Error near IL_01c3: stateMachine*/)._003Ctoil_003E__1.actor.jobs.curJob.targetC.Cell, ThingPlaceMode.Direct, out thing, (Action)null); + }, + defaultCompleteMode = ToilCompleteMode.Instant + }; } } } diff --git a/Assembly-CSharp/RimWorld/JobDriver_FoodFeedPatient.cs b/Assembly-CSharp/RimWorld/JobDriver_FoodFeedPatient.cs index 03aa486a9..3fab1bfb5 100644 --- a/Assembly-CSharp/RimWorld/JobDriver_FoodFeedPatient.cs +++ b/Assembly-CSharp/RimWorld/JobDriver_FoodFeedPatient.cs @@ -1,6 +1,5 @@ using System; using System.Collections.Generic; -using System.Diagnostics; using Verse; using Verse.AI; @@ -34,19 +33,34 @@ public override string GetReport() { if (base.CurJob.GetTarget(TargetIndex.A).Thing is Building_NutrientPasteDispenser) { - return base.CurJob.def.reportString.Replace("TargetA", ThingDefOf.MealNutrientPaste.label).Replace("TargetB", ((Pawn)((Thing)base.CurJob.targetB)).LabelShort); + return base.CurJob.def.reportString.Replace("TargetA", ThingDefOf.MealNutrientPaste.label).Replace("TargetB", ((Pawn)(Thing)base.CurJob.targetB).LabelShort); } return base.GetReport(); } - [DebuggerHidden] protected override IEnumerable MakeNewToils() { - JobDriver_FoodFeedPatient.c__Iterator4C c__Iterator4C = new JobDriver_FoodFeedPatient.c__Iterator4C(); - c__Iterator4C.<>f__this = this; - JobDriver_FoodFeedPatient.c__Iterator4C expr_0E = c__Iterator4C; - expr_0E.$PC = -2; - return expr_0E; + this.FailOnDespawnedNullOrForbidden(TargetIndex.B); + this.FailOn((Func)(() => !FoodUtility.ShouldBeFedBySomeone(((_003CMakeNewToils_003Ec__Iterator4C)/*Error near IL_0058: stateMachine*/)._003C_003Ef__this.Deliveree))); + yield return Toils_Reserve.Reserve(TargetIndex.B, 1, -1, null); + if (base.pawn.inventory != null && base.pawn.inventory.Contains(base.TargetThingA)) + { + yield return Toils_Misc.TakeItemFromInventoryToCarrier(base.pawn, TargetIndex.A); + } + else if (base.TargetThingA is Building_NutrientPasteDispenser) + { + yield return Toils_Goto.GotoThing(TargetIndex.A, PathEndMode.InteractionCell).FailOnForbidden(TargetIndex.A); + yield return Toils_Ingest.TakeMealFromDispenser(TargetIndex.A, base.pawn); + } + else + { + yield return Toils_Reserve.Reserve(TargetIndex.A, 1, -1, null); + yield return Toils_Goto.GotoThing(TargetIndex.A, PathEndMode.ClosestTouch).FailOnForbidden(TargetIndex.A); + yield return Toils_Ingest.PickupIngestible(TargetIndex.A, this.Deliveree); + } + yield return Toils_Goto.GotoThing(TargetIndex.B, PathEndMode.Touch); + yield return Toils_Ingest.ChewIngestible(this.Deliveree, 1.5f, TargetIndex.A, TargetIndex.None).FailOnCannotTouch(TargetIndex.B, PathEndMode.Touch); + yield return Toils_Ingest.FinalizeIngest(this.Deliveree, TargetIndex.A); } } } diff --git a/Assembly-CSharp/RimWorld/JobDriver_GatherAnimalBodyResources.cs b/Assembly-CSharp/RimWorld/JobDriver_GatherAnimalBodyResources.cs index bd581f64c..2f7da714f 100644 --- a/Assembly-CSharp/RimWorld/JobDriver_GatherAnimalBodyResources.cs +++ b/Assembly-CSharp/RimWorld/JobDriver_GatherAnimalBodyResources.cs @@ -1,6 +1,5 @@ using System; using System.Collections.Generic; -using System.Diagnostics; using Verse; using Verse.AI; @@ -25,14 +24,55 @@ public override void ExposeData() Scribe_Values.Look(ref this.gatherProgress, "gatherProgress", 0f, false); } - [DebuggerHidden] protected override IEnumerable MakeNewToils() { - JobDriver_GatherAnimalBodyResources.c__Iterator4 c__Iterator = new JobDriver_GatherAnimalBodyResources.c__Iterator4(); - c__Iterator.<>f__this = this; - JobDriver_GatherAnimalBodyResources.c__Iterator4 expr_0E = c__Iterator; - expr_0E.$PC = -2; - return expr_0E; + this.FailOnDespawnedNullOrForbidden(TargetIndex.A); + this.FailOnDowned(TargetIndex.A); + this.FailOnNotCasualInterruptible(TargetIndex.A); + yield return Toils_Reserve.Reserve(TargetIndex.A, 1, -1, null); + yield return Toils_Goto.GotoThing(TargetIndex.A, PathEndMode.Touch); + Toil wait = new Toil + { + initAction = (Action)delegate + { + Pawn actor2 = ((_003CMakeNewToils_003Ec__Iterator4)/*Error near IL_0095: stateMachine*/)._003Cwait_003E__0.actor; + Pawn pawn2 = (Pawn)((_003CMakeNewToils_003Ec__Iterator4)/*Error near IL_0095: stateMachine*/)._003Cwait_003E__0.actor.CurJob.GetTarget(TargetIndex.A).Thing; + actor2.pather.StopDead(); + PawnUtility.ForceWait(pawn2, 15000, null, true); + }, + tickAction = (Action)delegate + { + Pawn actor = ((_003CMakeNewToils_003Ec__Iterator4)/*Error near IL_00ac: stateMachine*/)._003Cwait_003E__0.actor; + actor.skills.Learn(SkillDefOf.Animals, 0.142999992f, false); + ((_003CMakeNewToils_003Ec__Iterator4)/*Error near IL_00ac: stateMachine*/)._003C_003Ef__this.gatherProgress += actor.GetStatValue(StatDefOf.AnimalGatherSpeed, true); + if (((_003CMakeNewToils_003Ec__Iterator4)/*Error near IL_00ac: stateMachine*/)._003C_003Ef__this.gatherProgress >= ((_003CMakeNewToils_003Ec__Iterator4)/*Error near IL_00ac: stateMachine*/)._003C_003Ef__this.WorkTotal) + { + ((_003CMakeNewToils_003Ec__Iterator4)/*Error near IL_00ac: stateMachine*/)._003C_003Ef__this.GetComp((Pawn)(Thing)((_003CMakeNewToils_003Ec__Iterator4)/*Error near IL_00ac: stateMachine*/)._003C_003Ef__this.CurJob.GetTarget(TargetIndex.A)).Gathered(((_003CMakeNewToils_003Ec__Iterator4)/*Error near IL_00ac: stateMachine*/)._003C_003Ef__this.pawn); + actor.jobs.EndCurrentJob(JobCondition.Succeeded, true); + } + } + }; + wait.AddFinishAction((Action)delegate + { + Pawn pawn = (Pawn)((_003CMakeNewToils_003Ec__Iterator4)/*Error near IL_00c3: stateMachine*/)._003Cwait_003E__0.actor.CurJob.GetTarget(TargetIndex.A).Thing; + if (pawn.jobs.curJob.def == JobDefOf.WaitMaintainPosture) + { + pawn.jobs.EndCurrentJob(JobCondition.InterruptForced, true); + } + }); + wait.FailOnDespawnedOrNull(TargetIndex.A); + wait.FailOnCannotTouch(TargetIndex.A, PathEndMode.Touch); + wait.AddEndCondition((Func)delegate + { + if (!((_003CMakeNewToils_003Ec__Iterator4)/*Error near IL_00f5: stateMachine*/)._003C_003Ef__this.GetComp((Pawn)(Thing)((_003CMakeNewToils_003Ec__Iterator4)/*Error near IL_00f5: stateMachine*/)._003C_003Ef__this.CurJob.GetTarget(TargetIndex.A)).ActiveAndFull) + { + return JobCondition.Incompletable; + } + return JobCondition.Ongoing; + }); + wait.defaultCompleteMode = ToilCompleteMode.Never; + wait.WithProgressBar(TargetIndex.A, (Func)(() => ((_003CMakeNewToils_003Ec__Iterator4)/*Error near IL_0119: stateMachine*/)._003C_003Ef__this.gatherProgress / ((_003CMakeNewToils_003Ec__Iterator4)/*Error near IL_0119: stateMachine*/)._003C_003Ef__this.WorkTotal), false, -0.5f); + yield return wait; } } } diff --git a/Assembly-CSharp/RimWorld/JobDriver_GiveToPackAnimal.cs b/Assembly-CSharp/RimWorld/JobDriver_GiveToPackAnimal.cs index a38e4fbba..f14d40605 100644 --- a/Assembly-CSharp/RimWorld/JobDriver_GiveToPackAnimal.cs +++ b/Assembly-CSharp/RimWorld/JobDriver_GiveToPackAnimal.cs @@ -1,6 +1,5 @@ using System; using System.Collections.Generic; -using System.Diagnostics; using UnityEngine; using Verse; using Verse.AI; @@ -29,45 +28,46 @@ private Pawn Animal } } - [DebuggerHidden] protected override IEnumerable MakeNewToils() { - JobDriver_GiveToPackAnimal.c__Iterator8 c__Iterator = new JobDriver_GiveToPackAnimal.c__Iterator8(); - c__Iterator.<>f__this = this; - JobDriver_GiveToPackAnimal.c__Iterator8 expr_0E = c__Iterator; - expr_0E.$PC = -2; - return expr_0E; + yield return Toils_Reserve.Reserve(TargetIndex.A, 1, -1, null); + yield return Toils_Goto.GotoThing(TargetIndex.A, PathEndMode.ClosestTouch); + yield return Toils_Haul.StartCarryThing(TargetIndex.A, false, false); + Toil findNearestCarrier = this.FindNearestCarrierToil(); + yield return findNearestCarrier; + yield return Toils_Goto.GotoThing(TargetIndex.B, PathEndMode.Touch).FailOnDespawnedNullOrForbidden(TargetIndex.B).JumpIf((Func)(() => !((_003CMakeNewToils_003Ec__Iterator8)/*Error near IL_00be: stateMachine*/)._003C_003Ef__this.CanCarryAtLeastOne(((_003CMakeNewToils_003Ec__Iterator8)/*Error near IL_00be: stateMachine*/)._003C_003Ef__this.Animal)), findNearestCarrier); + yield return this.GiveToCarrierAsMuchAsPossibleToil(); + yield return Toils_Jump.JumpIf(findNearestCarrier, (Func)(() => ((_003CMakeNewToils_003Ec__Iterator8)/*Error near IL_010a: stateMachine*/)._003C_003Ef__this.pawn.carryTracker.CarriedThing != null)); } private Toil FindNearestCarrierToil() { - return new Toil + Toil toil = new Toil(); + toil.initAction = (Action)delegate { - initAction = delegate + Pawn pawn = this.FindNearestCarrier(); + if (pawn == null) { - Pawn pawn = this.FindNearestCarrier(); - if (pawn == null) - { - this.pawn.jobs.EndCurrentJob(JobCondition.Incompletable, true); - } - else - { - base.CurJob.SetTarget(TargetIndex.B, pawn); - } + base.pawn.jobs.EndCurrentJob(JobCondition.Incompletable, true); + } + else + { + base.CurJob.SetTarget(TargetIndex.B, (Thing)pawn); } }; + return toil; } private Pawn FindNearestCarrier() { - List list = base.Map.mapPawns.SpawnedPawnsInFaction(this.pawn.Faction); + List list = base.Map.mapPawns.SpawnedPawnsInFaction(base.pawn.Faction); Pawn pawn = null; float num = -1f; for (int i = 0; i < list.Count; i++) { if (list[i].RaceProps.packAnimal && this.CanCarryAtLeastOne(list[i])) { - float num2 = (float)list[i].Position.DistanceToSquared(this.pawn.Position); + float num2 = (float)list[i].Position.DistanceToSquared(base.pawn.Position); if (pawn == null || num2 < num) { pawn = list[i]; @@ -85,21 +85,20 @@ private bool CanCarryAtLeastOne(Pawn carrier) private Toil GiveToCarrierAsMuchAsPossibleToil() { - return new Toil + Toil toil = new Toil(); + toil.initAction = (Action)delegate { - initAction = delegate + if (this.Item == null) { - if (this.Item == null) - { - this.pawn.jobs.EndCurrentJob(JobCondition.Incompletable, true); - } - else - { - int count = Mathf.Min(MassUtility.CountToPickUpUntilOverEncumbered(this.Animal, this.Item), this.Item.stackCount); - this.pawn.carryTracker.innerContainer.TryTransferToContainer(this.Item, this.Animal.inventory.innerContainer, count, true); - } + base.pawn.jobs.EndCurrentJob(JobCondition.Incompletable, true); + } + else + { + int count = Mathf.Min(MassUtility.CountToPickUpUntilOverEncumbered(this.Animal, this.Item), this.Item.stackCount); + base.pawn.carryTracker.innerContainer.TryTransferToContainer(this.Item, this.Animal.inventory.innerContainer, count, true); } }; + return toil; } } } diff --git a/Assembly-CSharp/RimWorld/JobDriver_GoForWalk.cs b/Assembly-CSharp/RimWorld/JobDriver_GoForWalk.cs index 13bbdce7f..bdbb44c30 100644 --- a/Assembly-CSharp/RimWorld/JobDriver_GoForWalk.cs +++ b/Assembly-CSharp/RimWorld/JobDriver_GoForWalk.cs @@ -1,20 +1,41 @@ using System; using System.Collections.Generic; -using System.Diagnostics; +using Verse; using Verse.AI; namespace RimWorld { public class JobDriver_GoForWalk : JobDriver { - [DebuggerHidden] protected override IEnumerable MakeNewToils() { - JobDriver_GoForWalk.c__Iterator1B c__Iterator1B = new JobDriver_GoForWalk.c__Iterator1B(); - c__Iterator1B.<>f__this = this; - JobDriver_GoForWalk.c__Iterator1B expr_0E = c__Iterator1B; - expr_0E.$PC = -2; - return expr_0E; + this.FailOn((Func)(() => !JoyUtility.EnjoyableOutsideNow(((_003CMakeNewToils_003Ec__Iterator1B)/*Error near IL_002b: stateMachine*/)._003C_003Ef__this.pawn, null))); + Toil goToil = Toils_Goto.GotoCell(TargetIndex.A, PathEndMode.OnCell); + goToil.tickAction = (Action)delegate + { + if (Find.TickManager.TicksGame > ((_003CMakeNewToils_003Ec__Iterator1B)/*Error near IL_0050: stateMachine*/)._003C_003Ef__this.startTick + ((_003CMakeNewToils_003Ec__Iterator1B)/*Error near IL_0050: stateMachine*/)._003C_003Ef__this.CurJob.def.joyDuration) + { + ((_003CMakeNewToils_003Ec__Iterator1B)/*Error near IL_0050: stateMachine*/)._003C_003Ef__this.EndJobWith(JobCondition.Succeeded); + } + else + { + JoyUtility.JoyTickCheckEnd(((_003CMakeNewToils_003Ec__Iterator1B)/*Error near IL_0050: stateMachine*/)._003C_003Ef__this.pawn, JoyTickFullJoyAction.EndJob, 1f); + } + }; + yield return goToil; + yield return new Toil + { + initAction = (Action)delegate + { + if (((_003CMakeNewToils_003Ec__Iterator1B)/*Error near IL_008a: stateMachine*/)._003C_003Ef__this.CurJob.targetQueueA.Count > 0) + { + LocalTargetInfo targetA = ((_003CMakeNewToils_003Ec__Iterator1B)/*Error near IL_008a: stateMachine*/)._003C_003Ef__this.CurJob.targetQueueA[0]; + ((_003CMakeNewToils_003Ec__Iterator1B)/*Error near IL_008a: stateMachine*/)._003C_003Ef__this.CurJob.targetQueueA.RemoveAt(0); + ((_003CMakeNewToils_003Ec__Iterator1B)/*Error near IL_008a: stateMachine*/)._003C_003Ef__this.CurJob.targetA = targetA; + ((_003CMakeNewToils_003Ec__Iterator1B)/*Error near IL_008a: stateMachine*/)._003C_003Ef__this.JumpToToil(((_003CMakeNewToils_003Ec__Iterator1B)/*Error near IL_008a: stateMachine*/)._003CgoToil_003E__0); + } + } + }; } } } diff --git a/Assembly-CSharp/RimWorld/JobDriver_Hunt.cs b/Assembly-CSharp/RimWorld/JobDriver_Hunt.cs index 988a2fc2e..806607391 100644 --- a/Assembly-CSharp/RimWorld/JobDriver_Hunt.cs +++ b/Assembly-CSharp/RimWorld/JobDriver_Hunt.cs @@ -1,6 +1,5 @@ using System; using System.Collections.Generic; -using System.Diagnostics; using Verse; using Verse.AI; @@ -50,50 +49,82 @@ public override string GetReport() return base.CurJob.def.reportString.Replace("TargetA", this.Victim.LabelShort); } - [DebuggerHidden] protected override IEnumerable MakeNewToils() { - JobDriver_Hunt.c__Iterator2E c__Iterator2E = new JobDriver_Hunt.c__Iterator2E(); - c__Iterator2E.<>f__this = this; - JobDriver_Hunt.c__Iterator2E expr_0E = c__Iterator2E; - expr_0E.$PC = -2; - return expr_0E; + this.FailOn((Func)delegate + { + if (!((_003CMakeNewToils_003Ec__Iterator2E)/*Error near IL_005b: stateMachine*/)._003C_003Ef__this.CurJob.ignoreDesignations) + { + Pawn victim = ((_003CMakeNewToils_003Ec__Iterator2E)/*Error near IL_005b: stateMachine*/)._003C_003Ef__this.Victim; + if (victim != null && !victim.Dead && ((_003CMakeNewToils_003Ec__Iterator2E)/*Error near IL_005b: stateMachine*/)._003C_003Ef__this.Map.designationManager.DesignationOn(victim, DesignationDefOf.Hunt) == null) + { + return true; + } + } + return false; + }); + yield return Toils_Reserve.Reserve(TargetIndex.A, 1, -1, null); + yield return new Toil + { + initAction = (Action)delegate + { + ((_003CMakeNewToils_003Ec__Iterator2E)/*Error near IL_0099: stateMachine*/)._003C_003Ef__this.jobStartTick = Find.TickManager.TicksGame; + } + }; + yield return Toils_Combat.TrySetJobToUseAttackVerb(); + Toil startCollectCorpse = this.StartCollectCorpseToil(); + Toil gotoCastPos = Toils_Combat.GotoCastPosition(TargetIndex.A, true).JumpIfDespawnedOrNull(TargetIndex.A, startCollectCorpse).FailOn((Func)(() => Find.TickManager.TicksGame > ((_003CMakeNewToils_003Ec__Iterator2E)/*Error near IL_00fe: stateMachine*/)._003C_003Ef__this.jobStartTick + 5000)); + yield return gotoCastPos; + Toil moveIfCannotHit = Toils_Jump.JumpIfTargetNotHittable(TargetIndex.A, gotoCastPos); + yield return moveIfCannotHit; + yield return Toils_Jump.JumpIfTargetDownedDistant(TargetIndex.A, gotoCastPos); + yield return Toils_Combat.CastVerb(TargetIndex.A, false).JumpIfDespawnedOrNull(TargetIndex.A, startCollectCorpse).FailOn((Func)(() => Find.TickManager.TicksGame > ((_003CMakeNewToils_003Ec__Iterator2E)/*Error near IL_0188: stateMachine*/)._003C_003Ef__this.jobStartTick + 5000)); + yield return Toils_Jump.JumpIfTargetDespawnedOrNull(TargetIndex.A, startCollectCorpse); + yield return Toils_Jump.Jump(moveIfCannotHit); + yield return startCollectCorpse; + yield return Toils_Goto.GotoCell(TargetIndex.A, PathEndMode.ClosestTouch).FailOnDespawnedNullOrForbidden(TargetIndex.A).FailOnSomeonePhysicallyInteracting(TargetIndex.A); + yield return Toils_Haul.StartCarryThing(TargetIndex.A, false, false); + Toil carryToCell = Toils_Haul.CarryHauledThingToCell(TargetIndex.B); + yield return carryToCell; + yield return Toils_Haul.PlaceHauledThingInCell(TargetIndex.B, carryToCell, true); } private Toil StartCollectCorpseToil() { Toil toil = new Toil(); - toil.initAction = delegate + toil.initAction = (Action)delegate { if (this.Victim == null) { toil.actor.jobs.EndCurrentJob(JobCondition.Incompletable, true); - return; - } - TaleRecorder.RecordTale(TaleDefOf.Hunted, new object[] - { - this.pawn, - this.Victim - }); - Corpse corpse = this.Victim.Corpse; - if (corpse == null || !this.pawn.CanReserveAndReach(corpse, PathEndMode.ClosestTouch, Danger.Deadly, 1, -1, null, false)) - { - this.pawn.jobs.EndCurrentJob(JobCondition.Incompletable, true); - return; } - corpse.SetForbidden(false, true); - IntVec3 c; - if (StoreUtility.TryFindBestBetterStoreCellFor(corpse, this.pawn, this.Map, StoragePriority.Unstored, this.pawn.Faction, out c, true)) + else { - this.pawn.Reserve(corpse, 1, -1, null); - this.pawn.Reserve(c, 1, -1, null); - this.pawn.CurJob.SetTarget(TargetIndex.B, c); - this.pawn.CurJob.SetTarget(TargetIndex.A, corpse); - this.pawn.CurJob.count = 1; - this.pawn.CurJob.haulMode = HaulMode.ToCellStorage; - return; + TaleRecorder.RecordTale(TaleDefOf.Hunted, base.pawn, this.Victim); + Corpse corpse = this.Victim.Corpse; + if (corpse == null || !base.pawn.CanReserveAndReach((Thing)corpse, PathEndMode.ClosestTouch, Danger.Deadly, 1, -1, null, false)) + { + base.pawn.jobs.EndCurrentJob(JobCondition.Incompletable, true); + } + else + { + corpse.SetForbidden(false, true); + IntVec3 c = default(IntVec3); + if (StoreUtility.TryFindBestBetterStoreCellFor((Thing)corpse, base.pawn, base.Map, StoragePriority.Unstored, base.pawn.Faction, out c, true)) + { + base.pawn.Reserve((Thing)corpse, 1, -1, null); + base.pawn.Reserve(c, 1, -1, null); + base.pawn.CurJob.SetTarget(TargetIndex.B, c); + base.pawn.CurJob.SetTarget(TargetIndex.A, (Thing)corpse); + base.pawn.CurJob.count = 1; + base.pawn.CurJob.haulMode = HaulMode.ToCellStorage; + } + else + { + base.pawn.jobs.EndCurrentJob(JobCondition.Succeeded, true); + } + } } - this.pawn.jobs.EndCurrentJob(JobCondition.Succeeded, true); }; return toil; } diff --git a/Assembly-CSharp/RimWorld/JobDriver_Ignite.cs b/Assembly-CSharp/RimWorld/JobDriver_Ignite.cs index 0b94758db..96cf2f176 100644 --- a/Assembly-CSharp/RimWorld/JobDriver_Ignite.cs +++ b/Assembly-CSharp/RimWorld/JobDriver_Ignite.cs @@ -1,20 +1,21 @@ using System; using System.Collections.Generic; -using System.Diagnostics; using Verse.AI; namespace RimWorld { public class JobDriver_Ignite : JobDriver { - [DebuggerHidden] protected override IEnumerable MakeNewToils() { - JobDriver_Ignite.c__Iterator2F c__Iterator2F = new JobDriver_Ignite.c__Iterator2F(); - c__Iterator2F.<>f__this = this; - JobDriver_Ignite.c__Iterator2F expr_0E = c__Iterator2F; - expr_0E.$PC = -2; - return expr_0E; + yield return Toils_Goto.GotoThing(TargetIndex.A, PathEndMode.Touch).FailOnBurningImmobile(TargetIndex.A); + yield return new Toil + { + initAction = (Action)delegate + { + ((_003CMakeNewToils_003Ec__Iterator2F)/*Error near IL_0055: stateMachine*/)._003C_003Ef__this.pawn.natives.TryStartIgnite(((_003CMakeNewToils_003Ec__Iterator2F)/*Error near IL_0055: stateMachine*/)._003C_003Ef__this.TargetThingA); + } + }; } } } diff --git a/Assembly-CSharp/RimWorld/JobDriver_Ingest.cs b/Assembly-CSharp/RimWorld/JobDriver_Ingest.cs index 64808f34c..b773e7ce8 100644 --- a/Assembly-CSharp/RimWorld/JobDriver_Ingest.cs +++ b/Assembly-CSharp/RimWorld/JobDriver_Ingest.cs @@ -1,6 +1,5 @@ using System; using System.Collections.Generic; -using System.Diagnostics; using UnityEngine; using Verse; using Verse.AI; @@ -38,7 +37,7 @@ private float ChewDurationMultiplier { return 1f; } - return 1f / this.pawn.GetStatValue(StatDefOf.EatingSpeed, true); + return (float)(1.0 / base.pawn.GetStatValue(StatDefOf.EatingSpeed, true)); } } @@ -55,10 +54,10 @@ public override string GetReport() { return base.CurJob.def.reportString.Replace("TargetA", ThingDefOf.MealNutrientPaste.label); } - Thing thing = this.pawn.CurJob.targetA.Thing; + Thing thing = base.pawn.CurJob.targetA.Thing; if (thing != null && thing.def.ingestible != null && !thing.def.ingestible.ingestReportString.NullOrEmpty()) { - return string.Format(thing.def.ingestible.ingestReportString, this.pawn.CurJob.targetA.Thing.LabelShort); + return string.Format(thing.def.ingestible.ingestReportString, base.pawn.CurJob.targetA.Thing.LabelShort); } return base.GetReport(); } @@ -67,17 +66,23 @@ public override void Notify_Starting() { base.Notify_Starting(); this.usingNutrientPasteDispenser = (this.IngestibleSource is Building_NutrientPasteDispenser); - this.eatingFromInventory = (this.pawn.inventory != null && this.pawn.inventory.Contains(this.IngestibleSource)); + this.eatingFromInventory = (base.pawn.inventory != null && base.pawn.inventory.Contains(this.IngestibleSource)); } - [DebuggerHidden] protected override IEnumerable MakeNewToils() { - JobDriver_Ingest.c__Iterator4D c__Iterator4D = new JobDriver_Ingest.c__Iterator4D(); - c__Iterator4D.<>f__this = this; - JobDriver_Ingest.c__Iterator4D expr_0E = c__Iterator4D; - expr_0E.$PC = -2; - return expr_0E; + if (!this.usingNutrientPasteDispenser) + { + this.FailOn((Func)(() => !((_003CMakeNewToils_003Ec__Iterator4D)/*Error near IL_0045: stateMachine*/)._003C_003Ef__this.IngestibleSource.Destroyed && !((_003CMakeNewToils_003Ec__Iterator4D)/*Error near IL_0045: stateMachine*/)._003C_003Ef__this.IngestibleSource.IngestibleNow)); + } + Toil chew = Toils_Ingest.ChewIngestible(base.pawn, this.ChewDurationMultiplier, TargetIndex.A, TargetIndex.B).FailOn((Func)((Toil x) => !((_003CMakeNewToils_003Ec__Iterator4D)/*Error near IL_0075: stateMachine*/)._003C_003Ef__this.IngestibleSource.Spawned && (((_003CMakeNewToils_003Ec__Iterator4D)/*Error near IL_0075: stateMachine*/)._003C_003Ef__this.pawn.carryTracker == null || ((_003CMakeNewToils_003Ec__Iterator4D)/*Error near IL_0075: stateMachine*/)._003C_003Ef__this.pawn.carryTracker.CarriedThing != ((_003CMakeNewToils_003Ec__Iterator4D)/*Error near IL_0075: stateMachine*/)._003C_003Ef__this.IngestibleSource))).FailOnCannotTouch(TargetIndex.A, PathEndMode.Touch); + foreach (Toil item in this.PrepareToIngestToils(chew)) + { + yield return item; + } + yield return chew; + yield return Toils_Ingest.FinalizeIngest(base.pawn, TargetIndex.A); + yield return Toils_Jump.JumpIf(chew, (Func)(() => ((_003CMakeNewToils_003Ec__Iterator4D)/*Error near IL_015d: stateMachine*/)._003C_003Ef__this.CurJob.GetTarget(TargetIndex.A).Thing is Corpse && ((_003CMakeNewToils_003Ec__Iterator4D)/*Error near IL_015d: stateMachine*/)._003C_003Ef__this.pawn.needs.food.CurLevelPercentage < 0.89999997615814209)); } private IEnumerable PrepareToIngestToils(Toil chewToil) @@ -86,79 +91,103 @@ private IEnumerable PrepareToIngestToils(Toil chewToil) { return this.PrepareToIngestToils_Dispenser(); } - if (this.pawn.RaceProps.ToolUser) + if (base.pawn.RaceProps.ToolUser) { return this.PrepareToIngestToils_ToolUser(chewToil); } return this.PrepareToIngestToils_NonToolUser(); } - [DebuggerHidden] private IEnumerable PrepareToIngestToils_Dispenser() { - JobDriver_Ingest.c__Iterator4E c__Iterator4E = new JobDriver_Ingest.c__Iterator4E(); - c__Iterator4E.<>f__this = this; - JobDriver_Ingest.c__Iterator4E expr_0E = c__Iterator4E; - expr_0E.$PC = -2; - return expr_0E; + yield return Toils_Goto.GotoThing(TargetIndex.A, PathEndMode.InteractionCell).FailOnDespawnedNullOrForbidden(TargetIndex.A); + yield return Toils_Ingest.TakeMealFromDispenser(TargetIndex.A, base.pawn); + yield return Toils_Ingest.CarryIngestibleToChewSpot(base.pawn, TargetIndex.A).FailOnDestroyedNullOrForbidden(TargetIndex.A); + yield return Toils_Ingest.FindAdjacentEatSurface(TargetIndex.B, TargetIndex.A); } - [DebuggerHidden] private IEnumerable PrepareToIngestToils_ToolUser(Toil chewToil) { - JobDriver_Ingest.c__Iterator4F c__Iterator4F = new JobDriver_Ingest.c__Iterator4F(); - c__Iterator4F.chewToil = chewToil; - c__Iterator4F.<$>chewToil = chewToil; - c__Iterator4F.<>f__this = this; - JobDriver_Ingest.c__Iterator4F expr_1C = c__Iterator4F; - expr_1C.$PC = -2; - return expr_1C; + if (this.eatingFromInventory) + { + yield return Toils_Misc.TakeItemFromInventoryToCarrier(base.pawn, TargetIndex.A); + } + else + { + yield return this.ReserveFoodIfWillIngestWholeStack(); + Toil gotoToPickup = Toils_Goto.GotoThing(TargetIndex.A, PathEndMode.ClosestTouch).FailOnDespawnedNullOrForbidden(TargetIndex.A); + yield return Toils_Jump.JumpIf(gotoToPickup, (Func)(() => ((_003CPrepareToIngestToils_ToolUser_003Ec__Iterator4F)/*Error near IL_00c4: stateMachine*/)._003C_003Ef__this.pawn.health.capacities.CapableOf(PawnCapacityDefOf.Manipulation))); + yield return Toils_Goto.GotoThing(TargetIndex.A, PathEndMode.Touch).FailOnDespawnedNullOrForbidden(TargetIndex.A); + yield return Toils_Jump.Jump(chewToil); + yield return gotoToPickup; + yield return Toils_Ingest.PickupIngestible(TargetIndex.A, base.pawn); + Toil reserveExtraFoodToCollect = Toils_Reserve.Reserve(TargetIndex.C, 1, -1, null); + Toil findExtraFoodToCollect = new Toil + { + initAction = (Action)delegate() + { + if (((_003CPrepareToIngestToils_ToolUser_003Ec__Iterator4F)/*Error near IL_017d: stateMachine*/)._003C_003Ef__this.pawn.inventory.innerContainer.TotalStackCountOfDef(((_003CPrepareToIngestToils_ToolUser_003Ec__Iterator4F)/*Error near IL_017d: stateMachine*/)._003C_003Ef__this.IngestibleSource.def) < ((_003CPrepareToIngestToils_ToolUser_003Ec__Iterator4F)/*Error near IL_017d: stateMachine*/)._003C_003Ef__this.CurJob.takeExtraIngestibles) + { + Predicate validator = (Predicate)((Thing x) => ((_003CPrepareToIngestToils_ToolUser_003Ec__Iterator4F)/*Error near IL_017d: stateMachine*/)._003C_003Ef__this.pawn.CanReserve(x, 1, -1, null, false) && !x.IsForbidden(((_003CPrepareToIngestToils_ToolUser_003Ec__Iterator4F)/*Error near IL_017d: stateMachine*/)._003C_003Ef__this.pawn) && x.IsSociallyProper(((_003CPrepareToIngestToils_ToolUser_003Ec__Iterator4F)/*Error near IL_017d: stateMachine*/)._003C_003Ef__this.pawn)); + Thing thing = GenClosest.ClosestThingReachable(((_003CPrepareToIngestToils_ToolUser_003Ec__Iterator4F)/*Error near IL_017d: stateMachine*/)._003C_003Ef__this.pawn.Position, ((_003CPrepareToIngestToils_ToolUser_003Ec__Iterator4F)/*Error near IL_017d: stateMachine*/)._003C_003Ef__this.pawn.Map, ThingRequest.ForDef(((_003CPrepareToIngestToils_ToolUser_003Ec__Iterator4F)/*Error near IL_017d: stateMachine*/)._003C_003Ef__this.IngestibleSource.def), PathEndMode.Touch, TraverseParms.For(((_003CPrepareToIngestToils_ToolUser_003Ec__Iterator4F)/*Error near IL_017d: stateMachine*/)._003C_003Ef__this.pawn, Danger.Deadly, TraverseMode.ByPawn, false), 12f, validator, null, 0, -1, false, RegionType.Set_Passable, false); + if (thing != null) + { + ((_003CPrepareToIngestToils_ToolUser_003Ec__Iterator4F)/*Error near IL_017d: stateMachine*/)._003C_003Ef__this.pawn.CurJob.SetTarget(TargetIndex.C, thing); + ((_003CPrepareToIngestToils_ToolUser_003Ec__Iterator4F)/*Error near IL_017d: stateMachine*/)._003C_003Ef__this.JumpToToil(((_003CPrepareToIngestToils_ToolUser_003Ec__Iterator4F)/*Error near IL_017d: stateMachine*/)._003CreserveExtraFoodToCollect_003E__1); + } + } + }, + defaultCompleteMode = ToilCompleteMode.Instant + }; + yield return Toils_Jump.Jump(findExtraFoodToCollect); + yield return reserveExtraFoodToCollect; + yield return Toils_Goto.GotoThing(TargetIndex.C, PathEndMode.Touch); + yield return Toils_Haul.TakeToInventory(TargetIndex.C, (Func)(() => ((_003CPrepareToIngestToils_ToolUser_003Ec__Iterator4F)/*Error near IL_01ec: stateMachine*/)._003C_003Ef__this.CurJob.takeExtraIngestibles - ((_003CPrepareToIngestToils_ToolUser_003Ec__Iterator4F)/*Error near IL_01ec: stateMachine*/)._003C_003Ef__this.pawn.inventory.innerContainer.TotalStackCountOfDef(((_003CPrepareToIngestToils_ToolUser_003Ec__Iterator4F)/*Error near IL_01ec: stateMachine*/)._003C_003Ef__this.IngestibleSource.def))); + yield return findExtraFoodToCollect; + } + yield return Toils_Ingest.CarryIngestibleToChewSpot(base.pawn, TargetIndex.A).FailOnDestroyedOrNull(TargetIndex.A); + yield return Toils_Ingest.FindAdjacentEatSurface(TargetIndex.B, TargetIndex.A); } - [DebuggerHidden] private IEnumerable PrepareToIngestToils_NonToolUser() { - JobDriver_Ingest.c__Iterator50 c__Iterator = new JobDriver_Ingest.c__Iterator50(); - c__Iterator.<>f__this = this; - JobDriver_Ingest.c__Iterator50 expr_0E = c__Iterator; - expr_0E.$PC = -2; - return expr_0E; + yield return this.ReserveFoodIfWillIngestWholeStack(); + yield return Toils_Goto.GotoThing(TargetIndex.A, PathEndMode.Touch); } private Toil ReserveFoodIfWillIngestWholeStack() { - return new Toil + Toil toil = new Toil(); + toil.initAction = (Action)delegate { - initAction = delegate + if (base.pawn.Faction != null) { - if (this.pawn.Faction == null) - { - return; - } - Thing thing = this.pawn.CurJob.GetTarget(TargetIndex.A).Thing; - if (this.pawn.carryTracker.CarriedThing == thing) + Thing thing = base.pawn.CurJob.GetTarget(TargetIndex.A).Thing; + if (base.pawn.carryTracker.CarriedThing != thing) { - return; - } - int num = FoodUtility.WillIngestStackCountOf(this.pawn, thing.def); - if (num >= thing.stackCount) - { - if (!thing.Spawned) + int num = FoodUtility.WillIngestStackCountOf(base.pawn, thing.def); + if (num >= thing.stackCount) { - this.pawn.jobs.EndCurrentJob(JobCondition.Incompletable, true); - return; + if (!thing.Spawned) + { + base.pawn.jobs.EndCurrentJob(JobCondition.Incompletable, true); + } + else + { + base.pawn.Reserve(thing, 1, -1, null); + } } - this.pawn.Reserve(thing, 1, -1, null); } - }, - defaultCompleteMode = ToilCompleteMode.Instant + } }; + toil.defaultCompleteMode = ToilCompleteMode.Instant; + return toil; } public override bool ModifyCarriedThingDrawPos(ref Vector3 drawPos, ref bool behind, ref bool flip) { IntVec3 cell = base.CurJob.GetTarget(TargetIndex.B).Cell; - return JobDriver_Ingest.ModifyCarriedThingDrawPosWorker(ref drawPos, ref behind, ref flip, cell, this.pawn); + return JobDriver_Ingest.ModifyCarriedThingDrawPosWorker(ref drawPos, ref behind, ref flip, cell, base.pawn); } public static bool ModifyCarriedThingDrawPosWorker(ref Vector3 drawPos, ref bool behind, ref bool flip, IntVec3 placeCell, Pawn pawn) @@ -168,25 +197,25 @@ public static bool ModifyCarriedThingDrawPosWorker(ref Vector3 drawPos, ref bool return false; } Thing carriedThing = pawn.carryTracker.CarriedThing; - if (carriedThing == null || !carriedThing.IngestibleNow) + if (carriedThing != null && carriedThing.IngestibleNow) { - return false; - } - if (placeCell.IsValid && placeCell.AdjacentToCardinal(pawn.Position) && placeCell.HasEatSurface(pawn.Map) && carriedThing.def.ingestible.ingestHoldUsesTable) - { - drawPos = new Vector3((float)placeCell.x + 0.5f, drawPos.y, (float)placeCell.z + 0.5f); - return true; - } - if (carriedThing.def.ingestible.ingestHoldOffsetStanding != null) - { - HoldOffset holdOffset = carriedThing.def.ingestible.ingestHoldOffsetStanding.Pick(pawn.Rotation); - if (holdOffset != null) + if (placeCell.IsValid && placeCell.AdjacentToCardinal(pawn.Position) && placeCell.HasEatSurface(pawn.Map) && carriedThing.def.ingestible.ingestHoldUsesTable) { - drawPos += holdOffset.offset; - behind = holdOffset.behind; - flip = holdOffset.flip; + drawPos = new Vector3((float)((float)placeCell.x + 0.5), drawPos.y, (float)((float)placeCell.z + 0.5)); return true; } + if (carriedThing.def.ingestible.ingestHoldOffsetStanding != null) + { + HoldOffset holdOffset = carriedThing.def.ingestible.ingestHoldOffsetStanding.Pick(pawn.Rotation); + if (holdOffset != null) + { + drawPos += holdOffset.offset; + behind = holdOffset.behind; + flip = holdOffset.flip; + return true; + } + } + return false; } return false; } diff --git a/Assembly-CSharp/RimWorld/JobDriver_InteractAnimal.cs b/Assembly-CSharp/RimWorld/JobDriver_InteractAnimal.cs index 1e853737e..869089a8e 100644 --- a/Assembly-CSharp/RimWorld/JobDriver_InteractAnimal.cs +++ b/Assembly-CSharp/RimWorld/JobDriver_InteractAnimal.cs @@ -1,6 +1,5 @@ using System; using System.Collections.Generic; -using System.Diagnostics; using UnityEngine; using Verse; using Verse.AI; @@ -43,38 +42,66 @@ public override void ExposeData() protected abstract Toil FinalInteractToil(); - [DebuggerHidden] protected override IEnumerable MakeNewToils() { - JobDriver_InteractAnimal.c__Iterator5 c__Iterator = new JobDriver_InteractAnimal.c__Iterator5(); - c__Iterator.<>f__this = this; - JobDriver_InteractAnimal.c__Iterator5 expr_0E = c__Iterator; - expr_0E.$PC = -2; - return expr_0E; + this.FailOnDespawnedNullOrForbidden(TargetIndex.A); + this.FailOnDowned(TargetIndex.A); + this.FailOnNotCasualInterruptible(TargetIndex.A); + yield return Toils_Reserve.Reserve(TargetIndex.A, 1, -1, null); + yield return Toils_Goto.GotoThing(TargetIndex.A, PathEndMode.Touch); + yield return Toils_Interpersonal.WaitToBeAbleToInteract(base.pawn); + yield return JobDriver_InteractAnimal.TalkToAnimal(TargetIndex.A); + yield return Toils_Goto.GotoThing(TargetIndex.A, PathEndMode.Touch); + yield return Toils_Interpersonal.WaitToBeAbleToInteract(base.pawn); + yield return JobDriver_InteractAnimal.TalkToAnimal(TargetIndex.A); + foreach (Toil item in this.FeedToils()) + { + yield return item; + } + yield return Toils_Goto.GotoThing(TargetIndex.A, PathEndMode.Touch); + yield return Toils_Interpersonal.WaitToBeAbleToInteract(base.pawn); + yield return JobDriver_InteractAnimal.TalkToAnimal(TargetIndex.A); + foreach (Toil item2 in this.FeedToils()) + { + yield return item2; + } + yield return Toils_Goto.GotoThing(TargetIndex.A, PathEndMode.Touch); + yield return Toils_Interpersonal.SetLastInteractTime(TargetIndex.A); + yield return Toils_Interpersonal.WaitToBeAbleToInteract(base.pawn); + yield return this.FinalInteractToil(); } public static float RequiredNutritionPerFeed(Pawn animal) { - return Mathf.Min(animal.needs.food.MaxLevel * 0.15f, 0.3f); + return Mathf.Min((float)(animal.needs.food.MaxLevel * 0.15000000596046448), 0.3f); } - [DebuggerHidden] private IEnumerable FeedToils() { - JobDriver_InteractAnimal.c__Iterator6 c__Iterator = new JobDriver_InteractAnimal.c__Iterator6(); - c__Iterator.<>f__this = this; - JobDriver_InteractAnimal.c__Iterator6 expr_0E = c__Iterator; - expr_0E.$PC = -2; - return expr_0E; + yield return new Toil + { + initAction = (Action)delegate + { + ((_003CFeedToils_003Ec__Iterator6)/*Error near IL_004a: stateMachine*/)._003C_003Ef__this.feedNutritionLeft = JobDriver_InteractAnimal.RequiredNutritionPerFeed(((_003CFeedToils_003Ec__Iterator6)/*Error near IL_004a: stateMachine*/)._003C_003Ef__this.Animal); + }, + defaultCompleteMode = ToilCompleteMode.Instant + }; + Toil gotoAnimal = Toils_Goto.GotoThing(TargetIndex.A, PathEndMode.Touch); + yield return gotoAnimal; + yield return this.StartFeedAnimal(TargetIndex.A); + yield return Toils_Ingest.FinalizeIngest(this.Animal, TargetIndex.B); + yield return Toils_General.PutCarriedThingInInventory(); + yield return Toils_General.ClearTarget(TargetIndex.B); + yield return Toils_Jump.JumpIf(gotoAnimal, (Func)(() => ((_003CFeedToils_003Ec__Iterator6)/*Error near IL_011b: stateMachine*/)._003C_003Ef__this.feedNutritionLeft > 0.0)); } private static Toil TalkToAnimal(TargetIndex tameeInd) { Toil toil = new Toil(); - toil.initAction = delegate + toil.initAction = (Action)delegate() { Pawn actor = toil.GetActor(); - Pawn recipient = (Pawn)((Thing)actor.CurJob.GetTarget(tameeInd)); + Pawn recipient = (Pawn)(Thing)actor.CurJob.GetTarget(tameeInd); actor.interactions.TryInteractWith(recipient, InteractionDefOf.AnimalChat); }; toil.defaultCompleteMode = ToilCompleteMode.Delay; @@ -85,36 +112,38 @@ private static Toil TalkToAnimal(TargetIndex tameeInd) private Toil StartFeedAnimal(TargetIndex tameeInd) { Toil toil = new Toil(); - toil.initAction = delegate + toil.initAction = (Action)delegate() { Pawn actor = toil.GetActor(); - Pawn pawn = (Pawn)((Thing)actor.CurJob.GetTarget(tameeInd)); + Pawn pawn = (Pawn)(Thing)actor.CurJob.GetTarget(tameeInd); PawnUtility.ForceWait(pawn, 270, actor, false); Thing thing = FoodUtility.BestFoodInInventory(actor, pawn, FoodPreferability.NeverForNutrition, FoodPreferability.RawTasty, 0f, false); if (thing == null) { actor.jobs.EndCurrentJob(JobCondition.Incompletable, true); - return; - } - actor.mindState.lastInventoryRawFoodUseTick = Find.TickManager.TicksGame; - int num = FoodUtility.StackCountForNutrition(thing.def, this.feedNutritionLeft); - int stackCount = thing.stackCount; - Thing thing2 = actor.inventory.innerContainer.Take(thing, Mathf.Min(num, stackCount)); - actor.carryTracker.TryStartCarry(thing2); - actor.CurJob.SetTarget(TargetIndex.B, thing2); - float num2 = (float)thing2.stackCount * thing2.def.ingestible.nutrition; - this.ticksLeftThisToil = Mathf.CeilToInt(270f * (num2 / JobDriver_InteractAnimal.RequiredNutritionPerFeed(pawn))); - if (num <= stackCount) - { - this.feedNutritionLeft = 0f; } else { - this.feedNutritionLeft -= num2; - if (this.feedNutritionLeft < 0.001f) + actor.mindState.lastInventoryRawFoodUseTick = Find.TickManager.TicksGame; + int num = FoodUtility.StackCountForNutrition(thing.def, this.feedNutritionLeft); + int stackCount = thing.stackCount; + Thing thing2 = actor.inventory.innerContainer.Take(thing, Mathf.Min(num, stackCount)); + actor.carryTracker.TryStartCarry(thing2); + actor.CurJob.SetTarget(TargetIndex.B, thing2); + float num2 = (float)thing2.stackCount * thing2.def.ingestible.nutrition; + base.ticksLeftThisToil = Mathf.CeilToInt((float)(270.0 * (num2 / JobDriver_InteractAnimal.RequiredNutritionPerFeed(pawn)))); + if (num <= stackCount) { this.feedNutritionLeft = 0f; } + else + { + this.feedNutritionLeft -= num2; + if (this.feedNutritionLeft < 0.0010000000474974513) + { + this.feedNutritionLeft = 0f; + } + } } }; toil.defaultCompleteMode = ToilCompleteMode.Delay; diff --git a/Assembly-CSharp/RimWorld/JobDriver_Kidnap.cs b/Assembly-CSharp/RimWorld/JobDriver_Kidnap.cs index a99ab4836..fc38cf9c7 100644 --- a/Assembly-CSharp/RimWorld/JobDriver_Kidnap.cs +++ b/Assembly-CSharp/RimWorld/JobDriver_Kidnap.cs @@ -1,6 +1,5 @@ using System; using System.Collections.Generic; -using System.Diagnostics; using Verse; using Verse.AI; @@ -18,21 +17,20 @@ protected Pawn Takee public override string GetReport() { - if (this.pawn.HostileTo(this.Takee)) + if (base.pawn.HostileTo(this.Takee)) { return base.GetReport(); } return JobDefOf.Rescue.reportString.Replace("TargetA", this.Takee.LabelShort); } - [DebuggerHidden] protected override IEnumerable MakeNewToils() { - JobDriver_Kidnap.c__Iterator31 c__Iterator = new JobDriver_Kidnap.c__Iterator31(); - c__Iterator.<>f__this = this; - JobDriver_Kidnap.c__Iterator31 expr_0E = c__Iterator; - expr_0E.$PC = -2; - return expr_0E; + this.FailOn((Func)(() => !((_003CMakeNewToils_003Ec__Iterator31)/*Error near IL_0029: stateMachine*/)._003C_003Ef__this.Takee.Downed && ((_003CMakeNewToils_003Ec__Iterator31)/*Error near IL_0029: stateMachine*/)._003C_003Ef__this.Takee.Awake())); + foreach (Toil item in base.MakeNewToils()) + { + yield return item; + } } } } diff --git a/Assembly-CSharp/RimWorld/JobDriver_LayDown.cs b/Assembly-CSharp/RimWorld/JobDriver_LayDown.cs index 57ef735a9..e2a3667b9 100644 --- a/Assembly-CSharp/RimWorld/JobDriver_LayDown.cs +++ b/Assembly-CSharp/RimWorld/JobDriver_LayDown.cs @@ -1,6 +1,4 @@ -using System; using System.Collections.Generic; -using System.Diagnostics; using Verse; using Verse.AI; @@ -18,19 +16,25 @@ public Building_Bed Bed } } - [DebuggerHidden] protected override IEnumerable MakeNewToils() { - JobDriver_LayDown.c__Iterator51 c__Iterator = new JobDriver_LayDown.c__Iterator51(); - c__Iterator.<>f__this = this; - JobDriver_LayDown.c__Iterator51 expr_0E = c__Iterator; - expr_0E.$PC = -2; - return expr_0E; + bool hasBed = base.pawn.CurJob.GetTarget(TargetIndex.A).HasThing; + if (hasBed) + { + yield return Toils_Reserve.Reserve(TargetIndex.A, this.Bed.SleepingSlotsCount, 0, null); + yield return Toils_Bed.ClaimBedIfNonMedical(TargetIndex.A, TargetIndex.None); + yield return Toils_Bed.GotoBed(TargetIndex.A); + } + else + { + yield return Toils_Goto.GotoCell(TargetIndex.A, PathEndMode.OnCell); + } + yield return Toils_LayDown.LayDown(TargetIndex.A, hasBed, true, true, true); } public override string GetReport() { - if (this.asleep) + if (base.asleep) { return "ReportSleeping".Translate(); } diff --git a/Assembly-CSharp/RimWorld/JobDriver_LayEgg.cs b/Assembly-CSharp/RimWorld/JobDriver_LayEgg.cs index a743599b7..e304cc319 100644 --- a/Assembly-CSharp/RimWorld/JobDriver_LayEgg.cs +++ b/Assembly-CSharp/RimWorld/JobDriver_LayEgg.cs @@ -1,6 +1,6 @@ using System; using System.Collections.Generic; -using System.Diagnostics; +using Verse; using Verse.AI; namespace RimWorld @@ -11,14 +11,24 @@ public class JobDriver_LayEgg : JobDriver private const TargetIndex LaySpotInd = TargetIndex.A; - [DebuggerHidden] protected override IEnumerable MakeNewToils() { - JobDriver_LayEgg.c__Iterator0 c__Iterator = new JobDriver_LayEgg.c__Iterator0(); - c__Iterator.<>f__this = this; - JobDriver_LayEgg.c__Iterator0 expr_0E = c__Iterator; - expr_0E.$PC = -2; - return expr_0E; + yield return Toils_Goto.GotoCell(TargetIndex.A, PathEndMode.OnCell); + yield return new Toil + { + defaultCompleteMode = ToilCompleteMode.Delay, + defaultDuration = 500 + }; + yield return new Toil + { + initAction = (Action)delegate + { + Pawn actor = ((_003CMakeNewToils_003Ec__Iterator0)/*Error near IL_0092: stateMachine*/)._003Cfinalize_003E__1.actor; + Thing forbiddenIfOutsideHomeArea = GenSpawn.Spawn(actor.GetComp().ProduceEgg(), actor.Position, ((_003CMakeNewToils_003Ec__Iterator0)/*Error near IL_0092: stateMachine*/)._003C_003Ef__this.Map); + forbiddenIfOutsideHomeArea.SetForbiddenIfOutsideHomeArea(); + }, + defaultCompleteMode = ToilCompleteMode.Instant + }; } } } diff --git a/Assembly-CSharp/RimWorld/JobDriver_Lovin.cs b/Assembly-CSharp/RimWorld/JobDriver_Lovin.cs index 3dd38d85b..a30d6d67f 100644 --- a/Assembly-CSharp/RimWorld/JobDriver_Lovin.cs +++ b/Assembly-CSharp/RimWorld/JobDriver_Lovin.cs @@ -1,6 +1,6 @@ using System; using System.Collections.Generic; -using System.Diagnostics; +using UnityEngine; using Verse; using Verse.AI; @@ -44,7 +44,7 @@ private Pawn Partner { get { - return (Pawn)((Thing)base.CurJob.GetTarget(this.PartnerInd)); + return (Pawn)(Thing)base.CurJob.GetTarget(this.PartnerInd); } } @@ -52,7 +52,7 @@ private Building_Bed Bed { get { - return (Building_Bed)((Thing)base.CurJob.GetTarget(this.BedInd)); + return (Building_Bed)(Thing)base.CurJob.GetTarget(this.BedInd); } } @@ -62,14 +62,55 @@ public override void ExposeData() Scribe_Values.Look(ref this.ticksLeft, "ticksLeft", 0, false); } - [DebuggerHidden] protected override IEnumerable MakeNewToils() { - JobDriver_Lovin.c__Iterator32 c__Iterator = new JobDriver_Lovin.c__Iterator32(); - c__Iterator.<>f__this = this; - JobDriver_Lovin.c__Iterator32 expr_0E = c__Iterator; - expr_0E.$PC = -2; - return expr_0E; + this.FailOnDespawnedOrNull(this.BedInd); + this.FailOnDespawnedOrNull(this.PartnerInd); + this.FailOn((Func)(() => !((_003CMakeNewToils_003Ec__Iterator32)/*Error near IL_0069: stateMachine*/)._003C_003Ef__this.Partner.health.capacities.CanBeAwake)); + this.KeepLyingDown(this.BedInd); + yield return Toils_Reserve.Reserve(this.PartnerInd, 1, -1, null); + yield return Toils_Reserve.Reserve(this.BedInd, this.Bed.SleepingSlotsCount, 0, null); + yield return Toils_Bed.ClaimBedIfNonMedical(this.BedInd, TargetIndex.None); + yield return Toils_Bed.GotoBed(this.BedInd); + yield return new Toil + { + initAction = (Action)delegate + { + if (((_003CMakeNewToils_003Ec__Iterator32)/*Error near IL_0140: stateMachine*/)._003C_003Ef__this.Partner.CurJob == null || ((_003CMakeNewToils_003Ec__Iterator32)/*Error near IL_0140: stateMachine*/)._003C_003Ef__this.Partner.CurJob.def != JobDefOf.Lovin) + { + Job newJob = new Job(JobDefOf.Lovin, (Thing)((_003CMakeNewToils_003Ec__Iterator32)/*Error near IL_0140: stateMachine*/)._003C_003Ef__this.pawn, (Thing)((_003CMakeNewToils_003Ec__Iterator32)/*Error near IL_0140: stateMachine*/)._003C_003Ef__this.Bed); + ((_003CMakeNewToils_003Ec__Iterator32)/*Error near IL_0140: stateMachine*/)._003C_003Ef__this.Partner.jobs.StartJob(newJob, JobCondition.InterruptForced, null, false, true, null, default(JobTag?)); + ((_003CMakeNewToils_003Ec__Iterator32)/*Error near IL_0140: stateMachine*/)._003C_003Ef__this.ticksLeft = (int)(2500.0 * Mathf.Clamp(Rand.Range(0.1f, 1.1f), 0.1f, 2f)); + } + else + { + ((_003CMakeNewToils_003Ec__Iterator32)/*Error near IL_0140: stateMachine*/)._003C_003Ef__this.ticksLeft = 9999999; + } + }, + defaultCompleteMode = ToilCompleteMode.Instant + }; + Toil doLovin = Toils_LayDown.LayDown(this.BedInd, true, false, false, false); + doLovin.FailOn((Func)(() => ((_003CMakeNewToils_003Ec__Iterator32)/*Error near IL_0195: stateMachine*/)._003C_003Ef__this.Partner.CurJob == null || ((_003CMakeNewToils_003Ec__Iterator32)/*Error near IL_0195: stateMachine*/)._003C_003Ef__this.Partner.CurJob.def != JobDefOf.Lovin)); + doLovin.AddPreTickAction((Action)delegate + { + ((_003CMakeNewToils_003Ec__Iterator32)/*Error near IL_01ad: stateMachine*/)._003C_003Ef__this.ticksLeft--; + if (((_003CMakeNewToils_003Ec__Iterator32)/*Error near IL_01ad: stateMachine*/)._003C_003Ef__this.ticksLeft <= 0) + { + ((_003CMakeNewToils_003Ec__Iterator32)/*Error near IL_01ad: stateMachine*/)._003C_003Ef__this.ReadyForNextToil(); + } + else if (((_003CMakeNewToils_003Ec__Iterator32)/*Error near IL_01ad: stateMachine*/)._003C_003Ef__this.pawn.IsHashIntervalTick(100)) + { + MoteMaker.ThrowMetaIcon(((_003CMakeNewToils_003Ec__Iterator32)/*Error near IL_01ad: stateMachine*/)._003C_003Ef__this.pawn.Position, ((_003CMakeNewToils_003Ec__Iterator32)/*Error near IL_01ad: stateMachine*/)._003C_003Ef__this.pawn.Map, ThingDefOf.Mote_Heart); + } + }); + doLovin.AddFinishAction((Action)delegate + { + Thought_Memory newThought = (Thought_Memory)ThoughtMaker.MakeThought(ThoughtDefOf.GotSomeLovin); + ((_003CMakeNewToils_003Ec__Iterator32)/*Error near IL_01c4: stateMachine*/)._003C_003Ef__this.pawn.needs.mood.thoughts.memories.TryGainMemory(newThought, ((_003CMakeNewToils_003Ec__Iterator32)/*Error near IL_01c4: stateMachine*/)._003C_003Ef__this.Partner); + ((_003CMakeNewToils_003Ec__Iterator32)/*Error near IL_01c4: stateMachine*/)._003C_003Ef__this.pawn.mindState.canLovinTick = Find.TickManager.TicksGame + ((_003CMakeNewToils_003Ec__Iterator32)/*Error near IL_01c4: stateMachine*/)._003C_003Ef__this.GenerateRandomMinTicksToNextLovin(((_003CMakeNewToils_003Ec__Iterator32)/*Error near IL_01c4: stateMachine*/)._003C_003Ef__this.pawn); + }); + doLovin.socialMode = RandomSocialMode.Off; + yield return doLovin; } private int GenerateRandomMinTicksToNextLovin(Pawn pawn) @@ -78,13 +119,13 @@ private int GenerateRandomMinTicksToNextLovin(Pawn pawn) { return 100; } - float num = JobDriver_Lovin.LovinIntervalHoursFromAgeCurve.Evaluate(pawn.ageTracker.AgeBiologicalYearsFloat); - num = Rand.Gaussian(num, 0.3f); - if (num < 0.5f) + float centerX = JobDriver_Lovin.LovinIntervalHoursFromAgeCurve.Evaluate(pawn.ageTracker.AgeBiologicalYearsFloat); + centerX = Rand.Gaussian(centerX, 0.3f); + if (centerX < 0.5) { - num = 0.5f; + centerX = 0.5f; } - return (int)(num * 2500f); + return (int)(centerX * 2500.0); } } } diff --git a/Assembly-CSharp/RimWorld/JobDriver_Maintain.cs b/Assembly-CSharp/RimWorld/JobDriver_Maintain.cs index 77c88a233..1db657cdb 100644 --- a/Assembly-CSharp/RimWorld/JobDriver_Maintain.cs +++ b/Assembly-CSharp/RimWorld/JobDriver_Maintain.cs @@ -1,6 +1,6 @@ using System; using System.Collections.Generic; -using System.Diagnostics; +using Verse; using Verse.AI; namespace RimWorld @@ -9,13 +9,25 @@ public class JobDriver_Maintain : JobDriver { private const int MaintainTicks = 180; - [DebuggerHidden] protected override IEnumerable MakeNewToils() { - JobDriver_Maintain.c__Iterator33 c__Iterator = new JobDriver_Maintain.c__Iterator33(); - JobDriver_Maintain.c__Iterator33 expr_07 = c__Iterator; - expr_07.$PC = -2; - return expr_07; + yield return Toils_Reserve.Reserve(TargetIndex.A, 1, -1, null); + yield return Toils_Goto.GotoThing(TargetIndex.A, PathEndMode.Touch); + Toil prepare = Toils_General.Wait(180); + prepare.WithProgressBarToilDelay(TargetIndex.A, false, -0.5f); + prepare.FailOnDespawnedNullOrForbidden(TargetIndex.A); + prepare.FailOnCannotTouch(TargetIndex.A, PathEndMode.Touch); + yield return prepare; + yield return new Toil + { + initAction = (Action)delegate + { + Pawn actor = ((_003CMakeNewToils_003Ec__Iterator33)/*Error near IL_00c8: stateMachine*/)._003Cmaintain_003E__1.actor; + CompMaintainable compMaintainable = actor.CurJob.targetA.Thing.TryGetComp(); + compMaintainable.Maintained(); + }, + defaultCompleteMode = ToilCompleteMode.Instant + }; } } } diff --git a/Assembly-CSharp/RimWorld/JobDriver_ManTurret.cs b/Assembly-CSharp/RimWorld/JobDriver_ManTurret.cs index 75d54b4bd..29a6dcac4 100644 --- a/Assembly-CSharp/RimWorld/JobDriver_ManTurret.cs +++ b/Assembly-CSharp/RimWorld/JobDriver_ManTurret.cs @@ -1,8 +1,8 @@ using System; using System.Collections.Generic; -using System.Diagnostics; using Verse; using Verse.AI; +using Verse.Sound; namespace RimWorld { @@ -15,23 +15,102 @@ public class JobDriver_ManTurret : JobDriver private static bool GunNeedsLoading(Building b) { Building_TurretGun building_TurretGun = b as Building_TurretGun; - return building_TurretGun != null && building_TurretGun.def.building.turretShellDef != null && !building_TurretGun.loaded; + if (building_TurretGun == null) + { + return false; + } + if (building_TurretGun.def.building.turretShellDef != null && !building_TurretGun.loaded) + { + return true; + } + return false; } public static Thing FindAmmoForTurret(Pawn pawn, Thing gun) { - Predicate validator = (Thing t) => !t.IsForbidden(pawn) && pawn.CanReserve(t, 10, 1, null, false); + Predicate validator = (Predicate)delegate(Thing t) + { + if (t.IsForbidden(pawn)) + { + return false; + } + if (!pawn.CanReserve(t, 10, 1, null, false)) + { + return false; + } + return true; + }; return GenClosest.ClosestThingReachable(gun.Position, gun.Map, ThingRequest.ForDef(gun.def.building.turretShellDef), PathEndMode.OnCell, TraverseParms.For(pawn, Danger.Deadly, TraverseMode.ByPawn, false), 40f, validator, null, 0, -1, false, RegionType.Set_Passable, false); } - [DebuggerHidden] protected override IEnumerable MakeNewToils() { - JobDriver_ManTurret.c__Iterator34 c__Iterator = new JobDriver_ManTurret.c__Iterator34(); - c__Iterator.<>f__this = this; - JobDriver_ManTurret.c__Iterator34 expr_0E = c__Iterator; - expr_0E.$PC = -2; - return expr_0E; + this.FailOnDespawnedNullOrForbidden(TargetIndex.A); + yield return Toils_Reserve.Reserve(TargetIndex.A, 1, -1, null); + Toil gotoTurret = Toils_Goto.GotoThing(TargetIndex.A, PathEndMode.InteractionCell); + yield return new Toil + { + initAction = (Action)delegate + { + Pawn actor3 = ((_003CMakeNewToils_003Ec__Iterator34)/*Error near IL_0087: stateMachine*/)._003CloadIfNeeded_003E__1.actor; + Building building3 = (Building)actor3.CurJob.targetA.Thing; + Building_TurretGun building_TurretGun2 = building3 as Building_TurretGun; + if (!JobDriver_ManTurret.GunNeedsLoading(building3)) + { + ((_003CMakeNewToils_003Ec__Iterator34)/*Error near IL_0087: stateMachine*/)._003C_003Ef__this.JumpToToil(((_003CMakeNewToils_003Ec__Iterator34)/*Error near IL_0087: stateMachine*/)._003CgotoTurret_003E__0); + } + else + { + Thing thing = JobDriver_ManTurret.FindAmmoForTurret(((_003CMakeNewToils_003Ec__Iterator34)/*Error near IL_0087: stateMachine*/)._003C_003Ef__this.pawn, building_TurretGun2); + if (thing == null) + { + if (actor3.Faction == Faction.OfPlayer) + { + Messages.Message("MessageOutOfNearbyShellsFor".Translate(actor3.LabelShort, building_TurretGun2.Label).CapitalizeFirst(), (Thing)building_TurretGun2, MessageSound.Negative); + } + actor3.jobs.EndCurrentJob(JobCondition.Incompletable, true); + } + actor3.CurJob.targetB = thing; + actor3.CurJob.count = 1; + } + } + }; + yield return Toils_Reserve.Reserve(TargetIndex.B, 10, 1, null); + yield return Toils_Goto.GotoThing(TargetIndex.B, PathEndMode.OnCell).FailOnSomeonePhysicallyInteracting(TargetIndex.B); + yield return Toils_Haul.StartCarryThing(TargetIndex.B, false, false); + yield return Toils_Goto.GotoThing(TargetIndex.A, PathEndMode.Touch); + yield return new Toil + { + initAction = (Action)delegate + { + Pawn actor2 = ((_003CMakeNewToils_003Ec__Iterator34)/*Error near IL_012f: stateMachine*/)._003CloadIfNeeded_003E__1.actor; + Building building2 = (Building)actor2.CurJob.targetA.Thing; + Building_TurretGun building_TurretGun = building2 as Building_TurretGun; + SoundDefOf.ArtilleryShellLoaded.PlayOneShot(new TargetInfo(building_TurretGun.Position, building_TurretGun.Map, false)); + building_TurretGun.loaded = true; + actor2.carryTracker.innerContainer.ClearAndDestroyContents(DestroyMode.Vanish); + } + }; + yield return gotoTurret; + Toil man = new Toil + { + tickAction = (Action)delegate + { + Pawn actor = ((_003CMakeNewToils_003Ec__Iterator34)/*Error near IL_0181: stateMachine*/)._003Cman_003E__3.actor; + Building building = (Building)actor.CurJob.targetA.Thing; + if (JobDriver_ManTurret.GunNeedsLoading(building)) + { + ((_003CMakeNewToils_003Ec__Iterator34)/*Error near IL_0181: stateMachine*/)._003C_003Ef__this.JumpToToil(((_003CMakeNewToils_003Ec__Iterator34)/*Error near IL_0181: stateMachine*/)._003CloadIfNeeded_003E__1); + } + else + { + building.GetComp().ManForATick(actor); + } + }, + defaultCompleteMode = ToilCompleteMode.Never + }; + man.FailOnCannotTouch(TargetIndex.A, PathEndMode.InteractionCell); + yield return man; } } } diff --git a/Assembly-CSharp/RimWorld/JobDriver_MarryAdjacentPawn.cs b/Assembly-CSharp/RimWorld/JobDriver_MarryAdjacentPawn.cs index 04e3e8b99..0fd8e7902 100644 --- a/Assembly-CSharp/RimWorld/JobDriver_MarryAdjacentPawn.cs +++ b/Assembly-CSharp/RimWorld/JobDriver_MarryAdjacentPawn.cs @@ -1,6 +1,5 @@ using System; using System.Collections.Generic; -using System.Diagnostics; using Verse; using Verse.AI; @@ -30,14 +29,40 @@ public int TicksLeftToMarry } } - [DebuggerHidden] protected override IEnumerable MakeNewToils() { - JobDriver_MarryAdjacentPawn.c__Iterator16 c__Iterator = new JobDriver_MarryAdjacentPawn.c__Iterator16(); - c__Iterator.<>f__this = this; - JobDriver_MarryAdjacentPawn.c__Iterator16 expr_0E = c__Iterator; - expr_0E.$PC = -2; - return expr_0E; + this.FailOnDespawnedOrNull(TargetIndex.A); + this.FailOn((Func)(() => ((_003CMakeNewToils_003Ec__Iterator16)/*Error near IL_0038: stateMachine*/)._003C_003Ef__this.OtherFiance.Drafted || !((_003CMakeNewToils_003Ec__Iterator16)/*Error near IL_0038: stateMachine*/)._003C_003Ef__this.pawn.Position.AdjacentTo8WayOrInside(((_003CMakeNewToils_003Ec__Iterator16)/*Error near IL_0038: stateMachine*/)._003C_003Ef__this.OtherFiance))); + Toil marry = new Toil + { + initAction = (Action)delegate + { + ((_003CMakeNewToils_003Ec__Iterator16)/*Error near IL_005b: stateMachine*/)._003C_003Ef__this.ticksLeftToMarry = 2500; + }, + tickAction = (Action)delegate + { + ((_003CMakeNewToils_003Ec__Iterator16)/*Error near IL_0072: stateMachine*/)._003C_003Ef__this.ticksLeftToMarry--; + if (((_003CMakeNewToils_003Ec__Iterator16)/*Error near IL_0072: stateMachine*/)._003C_003Ef__this.ticksLeftToMarry <= 0) + { + ((_003CMakeNewToils_003Ec__Iterator16)/*Error near IL_0072: stateMachine*/)._003C_003Ef__this.ticksLeftToMarry = 0; + ((_003CMakeNewToils_003Ec__Iterator16)/*Error near IL_0072: stateMachine*/)._003C_003Ef__this.ReadyForNextToil(); + } + }, + defaultCompleteMode = ToilCompleteMode.Never + }; + marry.FailOn((Func)(() => !((_003CMakeNewToils_003Ec__Iterator16)/*Error near IL_0095: stateMachine*/)._003C_003Ef__this.pawn.relations.DirectRelationExists(PawnRelationDefOf.Fiance, ((_003CMakeNewToils_003Ec__Iterator16)/*Error near IL_0095: stateMachine*/)._003C_003Ef__this.OtherFiance))); + yield return marry; + yield return new Toil + { + defaultCompleteMode = ToilCompleteMode.Instant, + initAction = (Action)delegate + { + if (((_003CMakeNewToils_003Ec__Iterator16)/*Error near IL_00dc: stateMachine*/)._003C_003Ef__this.pawn.thingIDNumber < ((_003CMakeNewToils_003Ec__Iterator16)/*Error near IL_00dc: stateMachine*/)._003C_003Ef__this.OtherFiance.thingIDNumber) + { + MarriageCeremonyUtility.Married(((_003CMakeNewToils_003Ec__Iterator16)/*Error near IL_00dc: stateMachine*/)._003C_003Ef__this.pawn, ((_003CMakeNewToils_003Ec__Iterator16)/*Error near IL_00dc: stateMachine*/)._003C_003Ef__this.OtherFiance); + } + } + }; } public override void ExposeData() diff --git a/Assembly-CSharp/RimWorld/JobDriver_Mate.cs b/Assembly-CSharp/RimWorld/JobDriver_Mate.cs index 791f13991..aeda5fdf7 100644 --- a/Assembly-CSharp/RimWorld/JobDriver_Mate.cs +++ b/Assembly-CSharp/RimWorld/JobDriver_Mate.cs @@ -1,6 +1,5 @@ using System; using System.Collections.Generic; -using System.Diagnostics; using Verse; using Verse.AI; @@ -22,14 +21,35 @@ private Pawn Female } } - [DebuggerHidden] protected override IEnumerable MakeNewToils() { - JobDriver_Mate.c__Iterator1 c__Iterator = new JobDriver_Mate.c__Iterator1(); - c__Iterator.<>f__this = this; - JobDriver_Mate.c__Iterator1 expr_0E = c__Iterator; - expr_0E.$PC = -2; - return expr_0E; + this.FailOnDespawnedNullOrForbidden(TargetIndex.A); + this.FailOnDowned(TargetIndex.A); + this.FailOnNotCasualInterruptible(TargetIndex.A); + yield return Toils_Goto.GotoThing(TargetIndex.A, PathEndMode.Touch); + Toil prepare = Toils_General.WaitWith(TargetIndex.A, 500, false, false); + prepare.tickAction = (Action)delegate + { + if (((_003CMakeNewToils_003Ec__Iterator1)/*Error near IL_0082: stateMachine*/)._003C_003Ef__this.pawn.IsHashIntervalTick(100)) + { + MoteMaker.ThrowMetaIcon(((_003CMakeNewToils_003Ec__Iterator1)/*Error near IL_0082: stateMachine*/)._003C_003Ef__this.pawn.Position, ((_003CMakeNewToils_003Ec__Iterator1)/*Error near IL_0082: stateMachine*/)._003C_003Ef__this.pawn.Map, ThingDefOf.Mote_Heart); + } + if (((_003CMakeNewToils_003Ec__Iterator1)/*Error near IL_0082: stateMachine*/)._003C_003Ef__this.Female.IsHashIntervalTick(100)) + { + MoteMaker.ThrowMetaIcon(((_003CMakeNewToils_003Ec__Iterator1)/*Error near IL_0082: stateMachine*/)._003C_003Ef__this.Female.Position, ((_003CMakeNewToils_003Ec__Iterator1)/*Error near IL_0082: stateMachine*/)._003C_003Ef__this.pawn.Map, ThingDefOf.Mote_Heart); + } + }; + yield return prepare; + yield return new Toil + { + initAction = (Action)delegate + { + Pawn actor = ((_003CMakeNewToils_003Ec__Iterator1)/*Error near IL_00bc: stateMachine*/)._003Cfinalize_003E__1.actor; + Pawn female = ((_003CMakeNewToils_003Ec__Iterator1)/*Error near IL_00bc: stateMachine*/)._003C_003Ef__this.Female; + PawnUtility.Mated(actor, female); + }, + defaultCompleteMode = ToilCompleteMode.Instant + }; } } } diff --git a/Assembly-CSharp/RimWorld/JobDriver_Milk.cs b/Assembly-CSharp/RimWorld/JobDriver_Milk.cs index 5a862acbb..5e8d7a64e 100644 --- a/Assembly-CSharp/RimWorld/JobDriver_Milk.cs +++ b/Assembly-CSharp/RimWorld/JobDriver_Milk.cs @@ -1,4 +1,3 @@ -using System; using Verse; namespace RimWorld diff --git a/Assembly-CSharp/RimWorld/JobDriver_Mine.cs b/Assembly-CSharp/RimWorld/JobDriver_Mine.cs index 0d6eabb47..61a36e530 100644 --- a/Assembly-CSharp/RimWorld/JobDriver_Mine.cs +++ b/Assembly-CSharp/RimWorld/JobDriver_Mine.cs @@ -1,6 +1,5 @@ using System; using System.Collections.Generic; -using System.Diagnostics; using Verse; using Verse.AI; @@ -26,24 +25,82 @@ private Thing MineTarget } } - [DebuggerHidden] protected override IEnumerable MakeNewToils() { - JobDriver_Mine.c__Iterator35 c__Iterator = new JobDriver_Mine.c__Iterator35(); - c__Iterator.<>f__this = this; - JobDriver_Mine.c__Iterator35 expr_0E = c__Iterator; - expr_0E.$PC = -2; - return expr_0E; + this.FailOnDespawnedNullOrForbidden(TargetIndex.A); + this.FailOnCellMissingDesignation(TargetIndex.A, DesignationDefOf.Mine); + yield return Toils_Reserve.Reserve(TargetIndex.A, 1, -1, null); + yield return Toils_Goto.GotoThing(TargetIndex.A, PathEndMode.Touch); + Toil mine = new Toil + { + tickAction = (Action)delegate + { + Pawn actor = ((_003CMakeNewToils_003Ec__Iterator35)/*Error near IL_008d: stateMachine*/)._003Cmine_003E__0.actor; + Thing mineTarget = ((_003CMakeNewToils_003Ec__Iterator35)/*Error near IL_008d: stateMachine*/)._003C_003Ef__this.MineTarget; + if (((_003CMakeNewToils_003Ec__Iterator35)/*Error near IL_008d: stateMachine*/)._003C_003Ef__this.ticksToPickHit < -100) + { + ((_003CMakeNewToils_003Ec__Iterator35)/*Error near IL_008d: stateMachine*/)._003C_003Ef__this.ResetTicksToPickHit(); + } + if (actor.skills != null) + { + actor.skills.Learn(SkillDefOf.Mining, 0.11f, false); + } + ((_003CMakeNewToils_003Ec__Iterator35)/*Error near IL_008d: stateMachine*/)._003C_003Ef__this.ticksToPickHit--; + if (((_003CMakeNewToils_003Ec__Iterator35)/*Error near IL_008d: stateMachine*/)._003C_003Ef__this.ticksToPickHit <= 0) + { + IntVec3 position = mineTarget.Position; + if (((_003CMakeNewToils_003Ec__Iterator35)/*Error near IL_008d: stateMachine*/)._003C_003Ef__this.effecter == null) + { + ((_003CMakeNewToils_003Ec__Iterator35)/*Error near IL_008d: stateMachine*/)._003C_003Ef__this.effecter = EffecterDefOf.Mine.Spawn(); + } + ((_003CMakeNewToils_003Ec__Iterator35)/*Error near IL_008d: stateMachine*/)._003C_003Ef__this.effecter.Trigger((Thing)actor, mineTarget); + int num = 80; + Mineable mineable = mineTarget as Mineable; + if (mineable == null || mineTarget.HitPoints > num) + { + Pawn actor2 = ((_003CMakeNewToils_003Ec__Iterator35)/*Error near IL_008d: stateMachine*/)._003Cmine_003E__0.actor; + DamageInfo dinfo = new DamageInfo(DamageDefOf.Mining, num, -1f, actor2, null, null, DamageInfo.SourceCategory.ThingOrUnknown); + mineTarget.TakeDamage(dinfo); + } + else + { + mineable.DestroyMined(actor); + } + if (mineTarget.Destroyed) + { + actor.Map.mineStrikeManager.CheckStruckOre(position, mineTarget.def, actor); + actor.records.Increment(RecordDefOf.CellsMined); + if (((_003CMakeNewToils_003Ec__Iterator35)/*Error near IL_008d: stateMachine*/)._003C_003Ef__this.pawn.Faction != Faction.OfPlayer) + { + List thingList = position.GetThingList(((_003CMakeNewToils_003Ec__Iterator35)/*Error near IL_008d: stateMachine*/)._003C_003Ef__this.Map); + for (int i = 0; i < thingList.Count; i++) + { + thingList[i].SetForbidden(true, false); + } + } + ((_003CMakeNewToils_003Ec__Iterator35)/*Error near IL_008d: stateMachine*/)._003C_003Ef__this.ReadyForNextToil(); + } + else + { + ((_003CMakeNewToils_003Ec__Iterator35)/*Error near IL_008d: stateMachine*/)._003C_003Ef__this.ResetTicksToPickHit(); + } + } + }, + defaultCompleteMode = ToilCompleteMode.Never + }; + mine.WithProgressBar(TargetIndex.A, (Func)(() => (float)(1.0 - (float)((_003CMakeNewToils_003Ec__Iterator35)/*Error near IL_00b1: stateMachine*/)._003C_003Ef__this.MineTarget.HitPoints / (float)((_003CMakeNewToils_003Ec__Iterator35)/*Error near IL_00b1: stateMachine*/)._003C_003Ef__this.MineTarget.MaxHitPoints)), false, -0.5f); + mine.FailOnCannotTouch(TargetIndex.A, PathEndMode.Touch); + yield return mine; } private void ResetTicksToPickHit() { - float num = this.pawn.GetStatValue(StatDefOf.MiningSpeed, true); - if (num < 0.5f && this.pawn.Faction != Faction.OfPlayer) + float num = base.pawn.GetStatValue(StatDefOf.MiningSpeed, true); + if (num < 0.5 && base.pawn.Faction != Faction.OfPlayer) { num = 0.5f; } - this.ticksToPickHit = (int)Math.Round((double)(120f / num)); + this.ticksToPickHit = (int)Math.Round(120.0 / num); } public override void ExposeData() diff --git a/Assembly-CSharp/RimWorld/JobDriver_Nuzzle.cs b/Assembly-CSharp/RimWorld/JobDriver_Nuzzle.cs index 9cdf69056..4a563cd2f 100644 --- a/Assembly-CSharp/RimWorld/JobDriver_Nuzzle.cs +++ b/Assembly-CSharp/RimWorld/JobDriver_Nuzzle.cs @@ -1,6 +1,6 @@ using System; using System.Collections.Generic; -using System.Diagnostics; +using Verse; using Verse.AI; namespace RimWorld @@ -9,14 +9,24 @@ public class JobDriver_Nuzzle : JobDriver { private const int NuzzleDuration = 100; - [DebuggerHidden] protected override IEnumerable MakeNewToils() { - JobDriver_Nuzzle.c__Iterator2 c__Iterator = new JobDriver_Nuzzle.c__Iterator2(); - c__Iterator.<>f__this = this; - JobDriver_Nuzzle.c__Iterator2 expr_0E = c__Iterator; - expr_0E.$PC = -2; - return expr_0E; + this.FailOnDespawnedNullOrForbidden(TargetIndex.A); + this.FailOnNotCasualInterruptible(TargetIndex.A); + yield return Toils_Goto.GotoThing(TargetIndex.A, PathEndMode.Touch); + yield return Toils_Interpersonal.WaitToBeAbleToInteract(base.pawn); + yield return Toils_Goto.GotoThing(TargetIndex.A, PathEndMode.Touch); + yield return Toils_General.WaitWith(TargetIndex.A, 100, false, true); + yield return new Toil + { + initAction = (Action)delegate + { + Pawn actor = ((_003CMakeNewToils_003Ec__Iterator2)/*Error near IL_00cc: stateMachine*/)._003Cfinalize_003E__0.actor; + Pawn recipient = (Pawn)actor.CurJob.targetA.Thing; + actor.interactions.TryInteractWith(recipient, InteractionDefOf.Nuzzle); + }, + defaultCompleteMode = ToilCompleteMode.Instant + }; } } } diff --git a/Assembly-CSharp/RimWorld/JobDriver_Open.cs b/Assembly-CSharp/RimWorld/JobDriver_Open.cs index 2917442f5..b6ad90dff 100644 --- a/Assembly-CSharp/RimWorld/JobDriver_Open.cs +++ b/Assembly-CSharp/RimWorld/JobDriver_Open.cs @@ -1,6 +1,6 @@ using System; using System.Collections.Generic; -using System.Diagnostics; +using Verse; using Verse.AI; namespace RimWorld @@ -17,14 +17,43 @@ private IOpenable Openable } } - [DebuggerHidden] protected override IEnumerable MakeNewToils() { - JobDriver_Open.c__Iterator36 c__Iterator = new JobDriver_Open.c__Iterator36(); - c__Iterator.<>f__this = this; - JobDriver_Open.c__Iterator36 expr_0E = c__Iterator; - expr_0E.$PC = -2; - return expr_0E; + yield return new Toil + { + initAction = (Action)delegate + { + if (!((_003CMakeNewToils_003Ec__Iterator36)/*Error near IL_0042: stateMachine*/)._003C_003Ef__this.Openable.CanOpen) + { + Designation designation2 = ((_003CMakeNewToils_003Ec__Iterator36)/*Error near IL_0042: stateMachine*/)._003C_003Ef__this.Map.designationManager.DesignationOn(((_003CMakeNewToils_003Ec__Iterator36)/*Error near IL_0042: stateMachine*/)._003C_003Ef__this.CurJob.targetA.Thing, DesignationDefOf.Open); + if (designation2 != null) + { + designation2.Delete(); + } + } + } + }.FailOnDestroyedOrNull(TargetIndex.A); + yield return Toils_Reserve.Reserve(TargetIndex.A, 1, -1, null); + yield return Toils_Goto.GotoThing(TargetIndex.A, PathEndMode.InteractionCell).FailOnThingMissingDesignation(TargetIndex.A, DesignationDefOf.Open).FailOnDestroyedOrNull(TargetIndex.A); + yield return Toils_General.Wait(300).WithProgressBarToilDelay(TargetIndex.A, false, -0.5f).FailOnDestroyedOrNull(TargetIndex.A).FailOnCannotTouch(TargetIndex.A, PathEndMode.InteractionCell); + yield return new Toil + { + initAction = (Action)delegate + { + Thing thing = ((_003CMakeNewToils_003Ec__Iterator36)/*Error near IL_00fc: stateMachine*/)._003C_003Ef__this.CurJob.targetA.Thing; + Designation designation = ((_003CMakeNewToils_003Ec__Iterator36)/*Error near IL_00fc: stateMachine*/)._003C_003Ef__this.Map.designationManager.DesignationOn(thing, DesignationDefOf.Open); + if (designation != null) + { + designation.Delete(); + } + if (((_003CMakeNewToils_003Ec__Iterator36)/*Error near IL_00fc: stateMachine*/)._003C_003Ef__this.Openable.CanOpen) + { + ((_003CMakeNewToils_003Ec__Iterator36)/*Error near IL_00fc: stateMachine*/)._003C_003Ef__this.Openable.Open(); + ((_003CMakeNewToils_003Ec__Iterator36)/*Error near IL_00fc: stateMachine*/)._003C_003Ef__this.pawn.records.Increment(RecordDefOf.ContainersOpened); + } + }, + defaultCompleteMode = ToilCompleteMode.Instant + }; } } } diff --git a/Assembly-CSharp/RimWorld/JobDriver_OperateDeepDrill.cs b/Assembly-CSharp/RimWorld/JobDriver_OperateDeepDrill.cs index 906300219..48a6e9681 100644 --- a/Assembly-CSharp/RimWorld/JobDriver_OperateDeepDrill.cs +++ b/Assembly-CSharp/RimWorld/JobDriver_OperateDeepDrill.cs @@ -1,20 +1,38 @@ using System; using System.Collections.Generic; -using System.Diagnostics; +using Verse; using Verse.AI; namespace RimWorld { public class JobDriver_OperateDeepDrill : JobDriver { - [DebuggerHidden] protected override IEnumerable MakeNewToils() { - JobDriver_OperateDeepDrill.c__Iterator37 c__Iterator = new JobDriver_OperateDeepDrill.c__Iterator37(); - c__Iterator.<>f__this = this; - JobDriver_OperateDeepDrill.c__Iterator37 expr_0E = c__Iterator; - expr_0E.$PC = -2; - return expr_0E; + this.FailOnDespawnedNullOrForbidden(TargetIndex.A); + this.FailOnBurningImmobile(TargetIndex.A); + this.FailOn((Func)delegate + { + CompDeepDrill compDeepDrill = ((_003CMakeNewToils_003Ec__Iterator37)/*Error near IL_0049: stateMachine*/)._003C_003Ef__this.CurJob.targetA.Thing.TryGetComp(); + return !compDeepDrill.CanDrillNow(); + }); + yield return Toils_Reserve.Reserve(TargetIndex.A, 1, -1, null); + yield return Toils_Goto.GotoThing(TargetIndex.A, PathEndMode.InteractionCell); + Toil work = new Toil + { + tickAction = (Action)delegate + { + Pawn actor = ((_003CMakeNewToils_003Ec__Iterator37)/*Error near IL_00a0: stateMachine*/)._003Cwork_003E__0.actor; + Building building = (Building)actor.CurJob.targetA.Thing; + CompDeepDrill comp = building.GetComp(); + comp.DrillWorkDone(actor); + actor.skills.Learn(SkillDefOf.Mining, 0.0714999959f, false); + }, + defaultCompleteMode = ToilCompleteMode.Never + }; + work.WithEffect(EffecterDefOf.Drill, TargetIndex.A); + work.FailOnCannotTouch(TargetIndex.A, PathEndMode.InteractionCell); + yield return work; } } } diff --git a/Assembly-CSharp/RimWorld/JobDriver_PlaceNoCostFrame.cs b/Assembly-CSharp/RimWorld/JobDriver_PlaceNoCostFrame.cs index 744a95d3b..29e8a2d0c 100644 --- a/Assembly-CSharp/RimWorld/JobDriver_PlaceNoCostFrame.cs +++ b/Assembly-CSharp/RimWorld/JobDriver_PlaceNoCostFrame.cs @@ -1,20 +1,17 @@ -using System; using System.Collections.Generic; -using System.Diagnostics; using Verse.AI; namespace RimWorld { public class JobDriver_PlaceNoCostFrame : JobDriver { - [DebuggerHidden] protected override IEnumerable MakeNewToils() { - JobDriver_PlaceNoCostFrame.c__Iterator11 c__Iterator = new JobDriver_PlaceNoCostFrame.c__Iterator11(); - c__Iterator.<>f__this = this; - JobDriver_PlaceNoCostFrame.c__Iterator11 expr_0E = c__Iterator; - expr_0E.$PC = -2; - return expr_0E; + this.FailOnDespawnedNullOrForbidden(TargetIndex.A); + yield return Toils_Reserve.Reserve(TargetIndex.A, 1, -1, null); + yield return Toils_Goto.GotoThing(TargetIndex.A, PathEndMode.Touch); + yield return Toils_Goto.MoveOffTargetBlueprint(TargetIndex.A); + yield return Toils_Construct.MakeSolidThingFromBlueprintIfNecessary(TargetIndex.A, TargetIndex.None); } } } diff --git a/Assembly-CSharp/RimWorld/JobDriver_PlantCut.cs b/Assembly-CSharp/RimWorld/JobDriver_PlantCut.cs index 507fb3486..f760caa0a 100644 --- a/Assembly-CSharp/RimWorld/JobDriver_PlantCut.cs +++ b/Assembly-CSharp/RimWorld/JobDriver_PlantCut.cs @@ -1,6 +1,4 @@ -using System; using System.Collections.Generic; -using System.Diagnostics; using Verse.AI; namespace RimWorld @@ -11,22 +9,21 @@ protected override void Init() { if (base.Plant.def.plant.harvestedThingDef != null && base.Plant.YieldNow() > 0) { - this.xpPerTick = 0.11f; + base.xpPerTick = 0.11f; } else { - this.xpPerTick = 0f; + base.xpPerTick = 0f; } } - [DebuggerHidden] protected override IEnumerable MakeNewToils() { - JobDriver_PlantCut.c__Iterator48 c__Iterator = new JobDriver_PlantCut.c__Iterator48(); - c__Iterator.<>f__this = this; - JobDriver_PlantCut.c__Iterator48 expr_0E = c__Iterator; - expr_0E.$PC = -2; - return expr_0E; + foreach (Toil item in base.MakeNewToils()) + { + yield return item; + } + yield return Toils_Interact.DestroyThing(TargetIndex.A); } } } diff --git a/Assembly-CSharp/RimWorld/JobDriver_PlantHarvest.cs b/Assembly-CSharp/RimWorld/JobDriver_PlantHarvest.cs index c5ddad798..cb7df8d82 100644 --- a/Assembly-CSharp/RimWorld/JobDriver_PlantHarvest.cs +++ b/Assembly-CSharp/RimWorld/JobDriver_PlantHarvest.cs @@ -1,6 +1,4 @@ -using System; using System.Collections.Generic; -using System.Diagnostics; using Verse.AI; namespace RimWorld @@ -9,17 +7,16 @@ public class JobDriver_PlantHarvest : JobDriver_PlantWork { protected override void Init() { - this.xpPerTick = 0.11f; + base.xpPerTick = 0.11f; } - [DebuggerHidden] protected override IEnumerable MakeNewToils() { - JobDriver_PlantHarvest.c__Iterator47 c__Iterator = new JobDriver_PlantHarvest.c__Iterator47(); - c__Iterator.<>f__this = this; - JobDriver_PlantHarvest.c__Iterator47 expr_0E = c__Iterator; - expr_0E.$PC = -2; - return expr_0E; + foreach (Toil item in base.MakeNewToils()) + { + yield return item; + } + yield return Toils_General.RemoveDesignationsOnThing(TargetIndex.A, DesignationDefOf.HarvestPlant); } } } diff --git a/Assembly-CSharp/RimWorld/JobDriver_PlantSow.cs b/Assembly-CSharp/RimWorld/JobDriver_PlantSow.cs index ae2e3265e..16bc080a8 100644 --- a/Assembly-CSharp/RimWorld/JobDriver_PlantSow.cs +++ b/Assembly-CSharp/RimWorld/JobDriver_PlantSow.cs @@ -1,6 +1,5 @@ using System; using System.Collections.Generic; -using System.Diagnostics; using Verse; using Verse.AI; @@ -24,14 +23,72 @@ public override void ExposeData() Scribe_Values.Look(ref this.sowWorkDone, "sowWorkDone", 0f, false); } - [DebuggerHidden] protected override IEnumerable MakeNewToils() { - JobDriver_PlantSow.c__Iterator45 c__Iterator = new JobDriver_PlantSow.c__Iterator45(); - c__Iterator.<>f__this = this; - JobDriver_PlantSow.c__Iterator45 expr_0E = c__Iterator; - expr_0E.$PC = -2; - return expr_0E; + yield return Toils_Reserve.Reserve(TargetIndex.A, 1, -1, null); + yield return Toils_Goto.GotoCell(TargetIndex.A, PathEndMode.Touch).FailOn((Func)(() => GenPlant.AdjacentSowBlocker(((_003CMakeNewToils_003Ec__Iterator45)/*Error near IL_0050: stateMachine*/)._003C_003Ef__this.CurJob.plantDefToSow, ((_003CMakeNewToils_003Ec__Iterator45)/*Error near IL_0050: stateMachine*/)._003C_003Ef__this.TargetA.Cell, ((_003CMakeNewToils_003Ec__Iterator45)/*Error near IL_0050: stateMachine*/)._003C_003Ef__this.Map) != null)).FailOn((Func)(() => !((_003CMakeNewToils_003Ec__Iterator45)/*Error near IL_0061: stateMachine*/)._003C_003Ef__this.CurJob.plantDefToSow.CanEverPlantAt(((_003CMakeNewToils_003Ec__Iterator45)/*Error near IL_0061: stateMachine*/)._003C_003Ef__this.TargetLocA, ((_003CMakeNewToils_003Ec__Iterator45)/*Error near IL_0061: stateMachine*/)._003C_003Ef__this.Map))); + Toil sowToil = new Toil + { + initAction = (Action)delegate + { + ((_003CMakeNewToils_003Ec__Iterator45)/*Error near IL_0094: stateMachine*/)._003C_003Ef__this.TargetThingA = GenSpawn.Spawn(((_003CMakeNewToils_003Ec__Iterator45)/*Error near IL_0094: stateMachine*/)._003C_003Ef__this.CurJob.plantDefToSow, ((_003CMakeNewToils_003Ec__Iterator45)/*Error near IL_0094: stateMachine*/)._003C_003Ef__this.TargetLocA, ((_003CMakeNewToils_003Ec__Iterator45)/*Error near IL_0094: stateMachine*/)._003C_003Ef__this.Map); + ((_003CMakeNewToils_003Ec__Iterator45)/*Error near IL_0094: stateMachine*/)._003C_003Ef__this.pawn.Reserve(((_003CMakeNewToils_003Ec__Iterator45)/*Error near IL_0094: stateMachine*/)._003C_003Ef__this.TargetThingA, 1, -1, null); + Plant plant3 = (Plant)((_003CMakeNewToils_003Ec__Iterator45)/*Error near IL_0094: stateMachine*/)._003C_003Ef__this.TargetThingA; + plant3.Growth = 0f; + plant3.sown = true; + }, + tickAction = (Action)delegate + { + Pawn actor = ((_003CMakeNewToils_003Ec__Iterator45)/*Error near IL_00ab: stateMachine*/)._003CsowToil_003E__0.actor; + if (actor.skills != null) + { + actor.skills.Learn(SkillDefOf.Growing, 0.11f, false); + } + float statValue; + float num = statValue = actor.GetStatValue(StatDefOf.PlantWorkSpeed, true); + Plant plant2 = ((_003CMakeNewToils_003Ec__Iterator45)/*Error near IL_00ab: stateMachine*/)._003C_003Ef__this.Plant; + if (plant2.LifeStage != 0) + { + Log.Error(((_003CMakeNewToils_003Ec__Iterator45)/*Error near IL_00ab: stateMachine*/)._003C_003Ef__this + " getting sowing work while not in Sowing life stage."); + } + ((_003CMakeNewToils_003Ec__Iterator45)/*Error near IL_00ab: stateMachine*/)._003C_003Ef__this.sowWorkDone += statValue; + if (((_003CMakeNewToils_003Ec__Iterator45)/*Error near IL_00ab: stateMachine*/)._003C_003Ef__this.sowWorkDone >= plant2.def.plant.sowWork) + { + plant2.Growth = 0.05f; + ((_003CMakeNewToils_003Ec__Iterator45)/*Error near IL_00ab: stateMachine*/)._003C_003Ef__this.Map.mapDrawer.MapMeshDirty(plant2.Position, MapMeshFlag.Things); + actor.records.Increment(RecordDefOf.PlantsSown); + ((_003CMakeNewToils_003Ec__Iterator45)/*Error near IL_00ab: stateMachine*/)._003C_003Ef__this.ReadyForNextToil(); + } + }, + defaultCompleteMode = ToilCompleteMode.Never + }; + sowToil.FailOnDespawnedNullOrForbidden(TargetIndex.A); + sowToil.FailOnCannotTouch(TargetIndex.A, PathEndMode.Touch); + sowToil.WithEffect(EffecterDefOf.Sow, TargetIndex.A); + sowToil.WithProgressBar(TargetIndex.A, (Func)(() => ((_003CMakeNewToils_003Ec__Iterator45)/*Error near IL_00fc: stateMachine*/)._003C_003Ef__this.sowWorkDone / ((_003CMakeNewToils_003Ec__Iterator45)/*Error near IL_00fc: stateMachine*/)._003C_003Ef__this.Plant.def.plant.sowWork), true, -0.5f); + sowToil.PlaySustainerOrSound((Func)(() => SoundDefOf.Interact_Sow)); + sowToil.AddFinishAction((Action)delegate + { + if (((_003CMakeNewToils_003Ec__Iterator45)/*Error near IL_0143: stateMachine*/)._003C_003Ef__this.TargetThingA != null) + { + Plant plant = (Plant)((_003CMakeNewToils_003Ec__Iterator45)/*Error near IL_0143: stateMachine*/)._003CsowToil_003E__0.actor.CurJob.GetTarget(TargetIndex.A).Thing; + if (((_003CMakeNewToils_003Ec__Iterator45)/*Error near IL_0143: stateMachine*/)._003C_003Ef__this.sowWorkDone < plant.def.plant.sowWork && !((_003CMakeNewToils_003Ec__Iterator45)/*Error near IL_0143: stateMachine*/)._003C_003Ef__this.TargetThingA.Destroyed) + { + ((_003CMakeNewToils_003Ec__Iterator45)/*Error near IL_0143: stateMachine*/)._003C_003Ef__this.TargetThingA.Destroy(DestroyMode.Vanish); + } + } + }); + yield return sowToil; + if (base.pawn.story.traits.HasTrait(TraitDefOf.GreenThumb)) + { + yield return new Toil + { + initAction = (Action)delegate + { + ((_003CMakeNewToils_003Ec__Iterator45)/*Error near IL_01a1: stateMachine*/)._003C_003Ef__this.pawn.needs.mood.thoughts.memories.TryGainMemory(ThoughtDefOf.GreenThumbHappy, null); + } + }; + } } } } diff --git a/Assembly-CSharp/RimWorld/JobDriver_PlantWork.cs b/Assembly-CSharp/RimWorld/JobDriver_PlantWork.cs index cda28b341..56ced522e 100644 --- a/Assembly-CSharp/RimWorld/JobDriver_PlantWork.cs +++ b/Assembly-CSharp/RimWorld/JobDriver_PlantWork.cs @@ -1,8 +1,9 @@ using System; using System.Collections.Generic; -using System.Diagnostics; +using UnityEngine; using Verse; using Verse.AI; +using Verse.Sound; namespace RimWorld { @@ -22,14 +23,70 @@ protected Plant Plant } } - [DebuggerHidden] protected override IEnumerable MakeNewToils() { - JobDriver_PlantWork.c__Iterator46 c__Iterator = new JobDriver_PlantWork.c__Iterator46(); - c__Iterator.<>f__this = this; - JobDriver_PlantWork.c__Iterator46 expr_0E = c__Iterator; - expr_0E.$PC = -2; - return expr_0E; + this.Init(); + yield return Toils_JobTransforms.MoveCurrentTargetIntoQueue(TargetIndex.A); + yield return Toils_Reserve.ReserveQueue(TargetIndex.A, 1, -1, null); + Toil initExtractTargetFromQueue = Toils_JobTransforms.ClearDespawnedNullOrForbiddenQueuedTargets(TargetIndex.A); + yield return initExtractTargetFromQueue; + yield return Toils_JobTransforms.ExtractNextTargetFromQueue(TargetIndex.A); + Toil checkNextQueuedTarget = Toils_JobTransforms.ClearDespawnedNullOrForbiddenQueuedTargets(TargetIndex.A); + yield return Toils_Goto.GotoThing(TargetIndex.A, PathEndMode.Touch).JumpIfDespawnedOrNullOrForbidden(TargetIndex.A, checkNextQueuedTarget); + Toil cut = new Toil + { + tickAction = (Action)delegate + { + Pawn actor = ((_003CMakeNewToils_003Ec__Iterator46)/*Error near IL_00f9: stateMachine*/)._003Ccut_003E__2.actor; + if (actor.skills != null) + { + actor.skills.Learn(SkillDefOf.Growing, ((_003CMakeNewToils_003Ec__Iterator46)/*Error near IL_00f9: stateMachine*/)._003C_003Ef__this.xpPerTick, false); + } + float statValue; + float num = statValue = actor.GetStatValue(StatDefOf.PlantWorkSpeed, true); + Plant plant = ((_003CMakeNewToils_003Ec__Iterator46)/*Error near IL_00f9: stateMachine*/)._003C_003Ef__this.Plant; + ((_003CMakeNewToils_003Ec__Iterator46)/*Error near IL_00f9: stateMachine*/)._003C_003Ef__this.workDone += statValue; + if (((_003CMakeNewToils_003Ec__Iterator46)/*Error near IL_00f9: stateMachine*/)._003C_003Ef__this.workDone >= plant.def.plant.harvestWork) + { + if (plant.def.plant.harvestedThingDef != null) + { + if (actor.RaceProps.Humanlike && plant.def.plant.harvestFailable && Rand.Value > actor.GetStatValue(StatDefOf.PlantHarvestYield, true)) + { + Vector3 loc = (((_003CMakeNewToils_003Ec__Iterator46)/*Error near IL_00f9: stateMachine*/)._003C_003Ef__this.pawn.DrawPos + plant.DrawPos) / 2f; + MoteMaker.ThrowText(loc, ((_003CMakeNewToils_003Ec__Iterator46)/*Error near IL_00f9: stateMachine*/)._003C_003Ef__this.Map, "TextMote_HarvestFailed".Translate(), 3.65f); + } + else + { + int num2 = plant.YieldNow(); + if (num2 > 0) + { + Thing thing = ThingMaker.MakeThing(plant.def.plant.harvestedThingDef, null); + thing.stackCount = num2; + if (actor.Faction != Faction.OfPlayer) + { + thing.SetForbidden(true, true); + } + GenPlace.TryPlaceThing(thing, actor.Position, ((_003CMakeNewToils_003Ec__Iterator46)/*Error near IL_00f9: stateMachine*/)._003C_003Ef__this.Map, ThingPlaceMode.Near, null); + actor.records.Increment(RecordDefOf.PlantsHarvested); + } + } + } + plant.def.plant.soundHarvestFinish.PlayOneShot((Thing)actor); + plant.PlantCollected(); + ((_003CMakeNewToils_003Ec__Iterator46)/*Error near IL_00f9: stateMachine*/)._003C_003Ef__this.workDone = 0f; + ((_003CMakeNewToils_003Ec__Iterator46)/*Error near IL_00f9: stateMachine*/)._003C_003Ef__this.ReadyForNextToil(); + } + } + }; + cut.FailOnDespawnedNullOrForbidden(TargetIndex.A); + cut.FailOnCannotTouch(TargetIndex.A, PathEndMode.Touch); + cut.defaultCompleteMode = ToilCompleteMode.Never; + cut.WithEffect(EffecterDefOf.Harvest, TargetIndex.A); + cut.WithProgressBar(TargetIndex.A, (Func)(() => ((_003CMakeNewToils_003Ec__Iterator46)/*Error near IL_014a: stateMachine*/)._003C_003Ef__this.workDone / ((_003CMakeNewToils_003Ec__Iterator46)/*Error near IL_014a: stateMachine*/)._003C_003Ef__this.Plant.def.plant.harvestWork), true, -0.5f); + cut.PlaySustainerOrSound((Func)(() => ((_003CMakeNewToils_003Ec__Iterator46)/*Error near IL_0168: stateMachine*/)._003C_003Ef__this.Plant.def.plant.soundHarvesting)); + yield return cut; + yield return checkNextQueuedTarget; + yield return Toils_Jump.JumpIfHaveTargetInQueue(TargetIndex.A, initExtractTargetFromQueue); } public override void ExposeData() diff --git a/Assembly-CSharp/RimWorld/JobDriver_PlayBilliards.cs b/Assembly-CSharp/RimWorld/JobDriver_PlayBilliards.cs index 4e4b6d0a5..138cfca70 100644 --- a/Assembly-CSharp/RimWorld/JobDriver_PlayBilliards.cs +++ b/Assembly-CSharp/RimWorld/JobDriver_PlayBilliards.cs @@ -1,7 +1,8 @@ using System; using System.Collections.Generic; -using System.Diagnostics; +using Verse; using Verse.AI; +using Verse.Sound; namespace RimWorld { @@ -9,14 +10,69 @@ public class JobDriver_PlayBilliards : JobDriver { private const int ShotDuration = 600; - [DebuggerHidden] protected override IEnumerable MakeNewToils() { - JobDriver_PlayBilliards.c__Iterator1C c__Iterator1C = new JobDriver_PlayBilliards.c__Iterator1C(); - c__Iterator1C.<>f__this = this; - JobDriver_PlayBilliards.c__Iterator1C expr_0E = c__Iterator1C; - expr_0E.$PC = -2; - return expr_0E; + this.EndOnDespawnedOrNull(TargetIndex.A, JobCondition.Incompletable); + yield return Toils_Reserve.Reserve(TargetIndex.A, base.CurJob.def.joyMaxParticipants, 0, null); + Toil chooseCell = new Toil + { + initAction = (Action)delegate + { + int num2 = 0; + while (true) + { + ((_003CMakeNewToils_003Ec__Iterator1C)/*Error near IL_0087: stateMachine*/)._003C_003Ef__this.CurJob.targetB = ((_003CMakeNewToils_003Ec__Iterator1C)/*Error near IL_0087: stateMachine*/)._003C_003Ef__this.CurJob.targetA.Thing.RandomAdjacentCell8Way(); + num2++; + if (num2 <= 100) + { + if (((_003CMakeNewToils_003Ec__Iterator1C)/*Error near IL_0087: stateMachine*/)._003C_003Ef__this.pawn.CanReserve((IntVec3)((_003CMakeNewToils_003Ec__Iterator1C)/*Error near IL_0087: stateMachine*/)._003C_003Ef__this.CurJob.targetB, 1, -1, null, false)) + return; + continue; + } + break; + } + Log.Error(((_003CMakeNewToils_003Ec__Iterator1C)/*Error near IL_0087: stateMachine*/)._003C_003Ef__this.pawn + " could not find cell adjacent to billiards table " + ((_003CMakeNewToils_003Ec__Iterator1C)/*Error near IL_0087: stateMachine*/)._003C_003Ef__this.TargetThingA); + ((_003CMakeNewToils_003Ec__Iterator1C)/*Error near IL_0087: stateMachine*/)._003C_003Ef__this.EndJobWith(JobCondition.Errored); + } + }; + yield return chooseCell; + yield return Toils_Reserve.Reserve(TargetIndex.B, 1, -1, null); + yield return Toils_Goto.GotoCell(TargetIndex.B, PathEndMode.OnCell); + Toil play = new Toil + { + initAction = (Action)delegate + { + ((_003CMakeNewToils_003Ec__Iterator1C)/*Error near IL_00f5: stateMachine*/)._003C_003Ef__this.CurJob.locomotionUrgency = LocomotionUrgency.Walk; + }, + tickAction = (Action)delegate + { + ((_003CMakeNewToils_003Ec__Iterator1C)/*Error near IL_010c: stateMachine*/)._003C_003Ef__this.pawn.Drawer.rotator.FaceCell(((_003CMakeNewToils_003Ec__Iterator1C)/*Error near IL_010c: stateMachine*/)._003C_003Ef__this.TargetA.Thing.OccupiedRect().ClosestCellTo(((_003CMakeNewToils_003Ec__Iterator1C)/*Error near IL_010c: stateMachine*/)._003C_003Ef__this.pawn.Position)); + if (((_003CMakeNewToils_003Ec__Iterator1C)/*Error near IL_010c: stateMachine*/)._003C_003Ef__this.pawn.jobs.curDriver.ticksLeftThisToil == 300) + { + SoundDefOf.PlayBilliards.PlayOneShot(new TargetInfo(((_003CMakeNewToils_003Ec__Iterator1C)/*Error near IL_010c: stateMachine*/)._003C_003Ef__this.pawn.Position, ((_003CMakeNewToils_003Ec__Iterator1C)/*Error near IL_010c: stateMachine*/)._003C_003Ef__this.pawn.Map, false)); + } + if (Find.TickManager.TicksGame > ((_003CMakeNewToils_003Ec__Iterator1C)/*Error near IL_010c: stateMachine*/)._003C_003Ef__this.startTick + ((_003CMakeNewToils_003Ec__Iterator1C)/*Error near IL_010c: stateMachine*/)._003C_003Ef__this.CurJob.def.joyDuration) + { + ((_003CMakeNewToils_003Ec__Iterator1C)/*Error near IL_010c: stateMachine*/)._003C_003Ef__this.EndJobWith(JobCondition.Succeeded); + } + else + { + float statValue; + float num = statValue = ((_003CMakeNewToils_003Ec__Iterator1C)/*Error near IL_010c: stateMachine*/)._003C_003Ef__this.TargetThingA.GetStatValue(StatDefOf.EntertainmentStrengthFactor, true); + JoyUtility.JoyTickCheckEnd(((_003CMakeNewToils_003Ec__Iterator1C)/*Error near IL_010c: stateMachine*/)._003C_003Ef__this.pawn, JoyTickFullJoyAction.EndJob, statValue); + } + }, + socialMode = RandomSocialMode.SuperActive, + defaultCompleteMode = ToilCompleteMode.Delay, + defaultDuration = 600 + }; + play.AddFinishAction((Action)delegate + { + JoyUtility.TryGainRecRoomThought(((_003CMakeNewToils_003Ec__Iterator1C)/*Error near IL_014b: stateMachine*/)._003C_003Ef__this.pawn); + }); + yield return play; + yield return Toils_Reserve.Release(TargetIndex.B); + yield return Toils_Jump.Jump(chooseCell); } } } diff --git a/Assembly-CSharp/RimWorld/JobDriver_PlayHorseshoes.cs b/Assembly-CSharp/RimWorld/JobDriver_PlayHorseshoes.cs index eb5d87a13..75e0b95e8 100644 --- a/Assembly-CSharp/RimWorld/JobDriver_PlayHorseshoes.cs +++ b/Assembly-CSharp/RimWorld/JobDriver_PlayHorseshoes.cs @@ -1,4 +1,3 @@ -using System; using Verse; namespace RimWorld @@ -9,9 +8,9 @@ public class JobDriver_PlayHorseshoes : JobDriver_WatchBuilding protected override void WatchTickAction() { - if (this.pawn.IsHashIntervalTick(400)) + if (base.pawn.IsHashIntervalTick(400)) { - MoteMaker.ThrowHorseshoe(this.pawn, base.TargetA.Cell); + MoteMaker.ThrowHorseshoe(base.pawn, base.TargetA.Cell); } base.WatchTickAction(); } diff --git a/Assembly-CSharp/RimWorld/JobDriver_PredatorHunt.cs b/Assembly-CSharp/RimWorld/JobDriver_PredatorHunt.cs index a779efdc4..703244421 100644 --- a/Assembly-CSharp/RimWorld/JobDriver_PredatorHunt.cs +++ b/Assembly-CSharp/RimWorld/JobDriver_PredatorHunt.cs @@ -1,6 +1,5 @@ using System; using System.Collections.Generic; -using System.Diagnostics; using Verse; using Verse.AI; @@ -54,14 +53,76 @@ public override string GetReport() return base.GetReport(); } - [DebuggerHidden] protected override IEnumerable MakeNewToils() { - JobDriver_PredatorHunt.c__Iterator3 c__Iterator = new JobDriver_PredatorHunt.c__Iterator3(); - c__Iterator.<>f__this = this; - JobDriver_PredatorHunt.c__Iterator3 expr_0E = c__Iterator; - expr_0E.$PC = -2; - return expr_0E; + base.AddFinishAction((Action)delegate + { + ((_003CMakeNewToils_003Ec__Iterator3)/*Error near IL_003f: stateMachine*/)._003C_003Ef__this.Map.attackTargetsCache.UpdateTarget(((_003CMakeNewToils_003Ec__Iterator3)/*Error near IL_003f: stateMachine*/)._003C_003Ef__this.pawn); + }); + Toil prepareToEatCorpse = new Toil + { + initAction = (Action)delegate + { + Pawn actor = ((_003CMakeNewToils_003Ec__Iterator3)/*Error near IL_0061: stateMachine*/)._003CprepareToEatCorpse_003E__0.actor; + Corpse corpse = ((_003CMakeNewToils_003Ec__Iterator3)/*Error near IL_0061: stateMachine*/)._003C_003Ef__this.Corpse; + if (corpse == null) + { + Pawn prey2 = ((_003CMakeNewToils_003Ec__Iterator3)/*Error near IL_0061: stateMachine*/)._003C_003Ef__this.Prey; + if (prey2 == null) + { + actor.jobs.EndCurrentJob(JobCondition.Incompletable, true); + return; + } + corpse = prey2.Corpse; + if (corpse == null) + { + actor.jobs.EndCurrentJob(JobCondition.Incompletable, true); + return; + } + } + if (actor.Faction == Faction.OfPlayer) + { + corpse.SetForbidden(false, false); + } + else + { + corpse.SetForbidden(true, false); + } + actor.CurJob.SetTarget(TargetIndex.A, (Thing)corpse); + } + }; + yield return new Toil + { + initAction = (Action)delegate + { + ((_003CMakeNewToils_003Ec__Iterator3)/*Error near IL_0083: stateMachine*/)._003C_003Ef__this.Map.attackTargetsCache.UpdateTarget(((_003CMakeNewToils_003Ec__Iterator3)/*Error near IL_0083: stateMachine*/)._003C_003Ef__this.pawn); + }, + atomicWithPrevious = true, + defaultCompleteMode = ToilCompleteMode.Instant + }; + Action onHitAction = (Action)delegate + { + Pawn prey = ((_003CMakeNewToils_003Ec__Iterator3)/*Error near IL_00c5: stateMachine*/)._003C_003Ef__this.Prey; + bool surpriseAttack = ((_003CMakeNewToils_003Ec__Iterator3)/*Error near IL_00c5: stateMachine*/)._003C_003Ef__this.firstHit && !prey.IsColonist; + if (((_003CMakeNewToils_003Ec__Iterator3)/*Error near IL_00c5: stateMachine*/)._003C_003Ef__this.pawn.meleeVerbs.TryMeleeAttack(prey, ((_003CMakeNewToils_003Ec__Iterator3)/*Error near IL_00c5: stateMachine*/)._003C_003Ef__this.CurJob.verbToUse, surpriseAttack)) + { + if (!((_003CMakeNewToils_003Ec__Iterator3)/*Error near IL_00c5: stateMachine*/)._003C_003Ef__this.notifiedPlayer && PawnUtility.ShouldSendNotificationAbout(prey)) + { + ((_003CMakeNewToils_003Ec__Iterator3)/*Error near IL_00c5: stateMachine*/)._003C_003Ef__this.notifiedPlayer = true; + Messages.Message("MessageAttackedByPredator".Translate(prey.LabelShort, ((_003CMakeNewToils_003Ec__Iterator3)/*Error near IL_00c5: stateMachine*/)._003C_003Ef__this.pawn.LabelIndefinite()).CapitalizeFirst(), (Thing)prey, MessageSound.SeriousAlert); + } + ((_003CMakeNewToils_003Ec__Iterator3)/*Error near IL_00c5: stateMachine*/)._003C_003Ef__this.Map.attackTargetsCache.UpdateTarget(((_003CMakeNewToils_003Ec__Iterator3)/*Error near IL_00c5: stateMachine*/)._003C_003Ef__this.pawn); + } + ((_003CMakeNewToils_003Ec__Iterator3)/*Error near IL_00c5: stateMachine*/)._003C_003Ef__this.firstHit = false; + }; + yield return Toils_Combat.FollowAndMeleeAttack(TargetIndex.A, onHitAction).JumpIfDespawnedOrNull(TargetIndex.A, prepareToEatCorpse).JumpIf((Func)(() => ((_003CMakeNewToils_003Ec__Iterator3)/*Error near IL_00ef: stateMachine*/)._003C_003Ef__this.Corpse != null), prepareToEatCorpse).FailOn((Func)(() => Find.TickManager.TicksGame > ((_003CMakeNewToils_003Ec__Iterator3)/*Error near IL_0106: stateMachine*/)._003C_003Ef__this.startTick + 5000 && (float)(((_003CMakeNewToils_003Ec__Iterator3)/*Error near IL_0106: stateMachine*/)._003C_003Ef__this.CurJob.GetTarget(TargetIndex.A).Cell - ((_003CMakeNewToils_003Ec__Iterator3)/*Error near IL_0106: stateMachine*/)._003C_003Ef__this.pawn.Position).LengthHorizontalSquared > 4.0)); + yield return prepareToEatCorpse; + Toil gotoCorpse = Toils_Goto.GotoThing(TargetIndex.A, PathEndMode.Touch); + yield return gotoCorpse; + float durationMultiplier = (float)(1.0 / base.pawn.GetStatValue(StatDefOf.EatingSpeed, true)); + yield return Toils_Ingest.ChewIngestible(base.pawn, durationMultiplier, TargetIndex.A, TargetIndex.None).FailOnDespawnedOrNull(TargetIndex.A).FailOnCannotTouch(TargetIndex.A, PathEndMode.Touch); + yield return Toils_Ingest.FinalizeIngest(base.pawn, TargetIndex.A); + yield return Toils_Jump.JumpIf(gotoCorpse, (Func)(() => ((_003CMakeNewToils_003Ec__Iterator3)/*Error near IL_01e8: stateMachine*/)._003C_003Ef__this.pawn.needs.food.CurLevelPercentage < 0.89999997615814209)); } } } diff --git a/Assembly-CSharp/RimWorld/JobDriver_PrepareCaravan_GatherItems.cs b/Assembly-CSharp/RimWorld/JobDriver_PrepareCaravan_GatherItems.cs index af7a65ac4..040c0f0a2 100644 --- a/Assembly-CSharp/RimWorld/JobDriver_PrepareCaravan_GatherItems.cs +++ b/Assembly-CSharp/RimWorld/JobDriver_PrepareCaravan_GatherItems.cs @@ -1,6 +1,5 @@ using System; using System.Collections.Generic; -using System.Diagnostics; using System.Linq; using UnityEngine; using Verse; @@ -54,126 +53,150 @@ private TransferableOneWay Transferable } } - [DebuggerHidden] protected override IEnumerable MakeNewToils() { - JobDriver_PrepareCaravan_GatherItems.c__Iterator9 c__Iterator = new JobDriver_PrepareCaravan_GatherItems.c__Iterator9(); - c__Iterator.<>f__this = this; - JobDriver_PrepareCaravan_GatherItems.c__Iterator9 expr_0E = c__Iterator; - expr_0E.$PC = -2; - return expr_0E; + this.FailOn((Func)(() => !((_003CMakeNewToils_003Ec__Iterator9)/*Error near IL_004b: stateMachine*/)._003C_003Ef__this.Map.lordManager.lords.Contains(((_003CMakeNewToils_003Ec__Iterator9)/*Error near IL_004b: stateMachine*/)._003C_003Ef__this.CurJob.lord))); + Toil reserve = Toils_Reserve.Reserve(TargetIndex.A, 1, -1, null); + yield return reserve; + yield return Toils_Goto.GotoThing(TargetIndex.A, PathEndMode.Touch); + yield return this.DetermineNumToHaul(); + yield return Toils_Haul.StartCarryThing(TargetIndex.A, false, true); + yield return this.AddCarriedThingToTransferables(); + yield return Toils_Haul.CheckForGetOpportunityDuplicate(reserve, TargetIndex.A, TargetIndex.None, true, (Predicate)((Thing x) => ((_003CMakeNewToils_003Ec__Iterator9)/*Error near IL_00fb: stateMachine*/)._003C_003Ef__this.Transferable.things.Contains(x))); + Toil findCarrier = this.FindCarrier(); + yield return findCarrier; + yield return Toils_Goto.GotoThing(TargetIndex.B, PathEndMode.Touch).JumpIf((Func)(() => !JobDriver_PrepareCaravan_GatherItems.IsUsableCarrier(((_003CMakeNewToils_003Ec__Iterator9)/*Error near IL_014e: stateMachine*/)._003C_003Ef__this.Carrier, ((_003CMakeNewToils_003Ec__Iterator9)/*Error near IL_014e: stateMachine*/)._003C_003Ef__this.pawn, true)), findCarrier); + yield return Toils_General.Wait(25).JumpIf((Func)(() => !JobDriver_PrepareCaravan_GatherItems.IsUsableCarrier(((_003CMakeNewToils_003Ec__Iterator9)/*Error near IL_017e: stateMachine*/)._003C_003Ef__this.Carrier, ((_003CMakeNewToils_003Ec__Iterator9)/*Error near IL_017e: stateMachine*/)._003C_003Ef__this.pawn, true)), findCarrier).WithProgressBarToilDelay(TargetIndex.B, false, -0.5f); + yield return this.PlaceTargetInCarrierInventory(); } private Toil DetermineNumToHaul() { - return new Toil + Toil toil = new Toil(); + toil.initAction = (Action)delegate { - initAction = delegate + int num = GatherItemsForCaravanUtility.CountLeftToTransfer(base.pawn, this.Transferable, base.CurJob.lord); + if (base.pawn.carryTracker.CarriedThing != null) { - int num = GatherItemsForCaravanUtility.CountLeftToTransfer(this.pawn, this.Transferable, base.CurJob.lord); - if (this.pawn.carryTracker.CarriedThing != null) - { - num -= this.pawn.carryTracker.CarriedThing.stackCount; - } - if (num <= 0) - { - this.pawn.jobs.EndCurrentJob(JobCondition.Succeeded, true); - } - else - { - base.CurJob.count = num; - } - }, - defaultCompleteMode = ToilCompleteMode.Instant, - atomicWithPrevious = true + num -= base.pawn.carryTracker.CarriedThing.stackCount; + } + if (num <= 0) + { + base.pawn.jobs.EndCurrentJob(JobCondition.Succeeded, true); + } + else + { + base.CurJob.count = num; + } }; + toil.defaultCompleteMode = ToilCompleteMode.Instant; + toil.atomicWithPrevious = true; + return toil; } private Toil AddCarriedThingToTransferables() { - return new Toil + Toil toil = new Toil(); + toil.initAction = (Action)delegate { - initAction = delegate + TransferableOneWay transferable = this.Transferable; + if (!transferable.things.Contains(base.pawn.carryTracker.CarriedThing)) { - TransferableOneWay transferable = this.Transferable; - if (!transferable.things.Contains(this.pawn.carryTracker.CarriedThing)) - { - transferable.things.Add(this.pawn.carryTracker.CarriedThing); - } - }, - defaultCompleteMode = ToilCompleteMode.Instant, - atomicWithPrevious = true + transferable.things.Add(base.pawn.carryTracker.CarriedThing); + } }; + toil.defaultCompleteMode = ToilCompleteMode.Instant; + toil.atomicWithPrevious = true; + return toil; } private Toil FindCarrier() { - return new Toil + Toil toil = new Toil(); + toil.initAction = (Action)delegate() { - initAction = delegate + Pawn pawn = this.FindBestCarrier(true); + if (pawn == null) { - Pawn pawn = this.FindBestCarrier(true); - if (pawn == null) + bool flag = base.pawn.GetLord() == base.CurJob.lord; + if (flag && !MassUtility.IsOverEncumbered(base.pawn)) { - bool flag = this.pawn.GetLord() == base.CurJob.lord; - if (flag && !MassUtility.IsOverEncumbered(this.pawn)) - { - pawn = this.pawn; - } - else + pawn = base.pawn; + } + else + { + pawn = this.FindBestCarrier(false); + if (pawn == null) { - pawn = this.FindBestCarrier(false); - if (pawn == null) + if (!flag) { - if (flag) + IEnumerable source = from x in base.CurJob.lord.ownedPawns + where JobDriver_PrepareCaravan_GatherItems.IsUsableCarrier(x, base.pawn, true) + select x; + if (source.Any()) { - pawn = this.pawn; - } - else - { - IEnumerable source = from x in base.CurJob.lord.ownedPawns - where JobDriver_PrepareCaravan_GatherItems.IsUsableCarrier(x, this.pawn, true) - select x; - if (!source.Any()) - { - base.EndJobWith(JobCondition.Incompletable); - return; - } - pawn = source.RandomElement(); + pawn = source.RandomElement(); + goto IL_00aa; } + base.EndJobWith(JobCondition.Incompletable); + return; } + pawn = base.pawn; } } - base.CurJob.SetTarget(TargetIndex.B, pawn); } + goto IL_00aa; + IL_00aa: + base.CurJob.SetTarget(TargetIndex.B, (Thing)pawn); }; + return toil; } private Toil PlaceTargetInCarrierInventory() { - return new Toil + Toil toil = new Toil(); + toil.initAction = (Action)delegate { - initAction = delegate - { - Pawn_CarryTracker carryTracker = this.pawn.carryTracker; - Thing carriedThing = carryTracker.CarriedThing; - this.Transferable.AdjustTo(Mathf.Max(this.Transferable.CountToTransfer - carriedThing.stackCount, 0)); - carryTracker.innerContainer.TryTransferToContainer(carriedThing, this.Carrier.inventory.innerContainer, carriedThing.stackCount, true); - } + Pawn_CarryTracker carryTracker = base.pawn.carryTracker; + Thing carriedThing = carryTracker.CarriedThing; + this.Transferable.AdjustTo(Mathf.Max(this.Transferable.CountToTransfer - carriedThing.stackCount, 0)); + carryTracker.innerContainer.TryTransferToContainer(carriedThing, this.Carrier.inventory.innerContainer, carriedThing.stackCount, true); }; + return toil; } public static bool IsUsableCarrier(Pawn p, Pawn forPawn, bool allowColonists) { - return p == forPawn || (!p.DestroyedOrNull() && p.Spawned && !p.inventory.UnloadEverything && forPawn.CanReach(p, PathEndMode.Touch, Danger.Deadly, false, TraverseMode.ByPawn) && ((allowColonists && p.IsColonist) || ((p.RaceProps.packAnimal || p.HostFaction == Faction.OfPlayer) && !p.IsBurning() && !p.Downed && !MassUtility.IsOverEncumbered(p)))); + if (p == forPawn) + { + return true; + } + int result; + if (!p.DestroyedOrNull() && p.Spawned && !p.inventory.UnloadEverything && forPawn.CanReach((Thing)p, PathEndMode.Touch, Danger.Deadly, false, TraverseMode.ByPawn)) + { + if (allowColonists && p.IsColonist) + { + return true; + } + if ((p.RaceProps.packAnimal || p.HostFaction == Faction.OfPlayer) && !p.IsBurning() && !p.Downed) + { + result = ((!MassUtility.IsOverEncumbered(p)) ? 1 : 0); + goto IL_009b; + } + result = 0; + goto IL_009b; + } + return false; + IL_009b: + return (byte)result != 0; } private float GetCarrierScore(Pawn p) { - float lengthHorizontal = (p.Position - this.pawn.Position).LengthHorizontal; + float lengthHorizontal = (p.Position - base.pawn.Position).LengthHorizontal; float num = MassUtility.EncumbrancePercent(p); - float num2 = 1f - num; - return num2 - lengthHorizontal / 10f * 0.2f; + float num2 = (float)(1.0 - num); + return (float)(num2 - lengthHorizontal / 10.0 * 0.20000000298023224); } private Pawn FindBestCarrier(bool onlyAnimals) @@ -186,19 +209,13 @@ private Pawn FindBestCarrier(bool onlyAnimals) for (int i = 0; i < lord.ownedPawns.Count; i++) { Pawn pawn2 = lord.ownedPawns[i]; - if (pawn2 != this.pawn) + if (pawn2 != base.pawn && (!onlyAnimals || pawn2.RaceProps.Animal) && JobDriver_PrepareCaravan_GatherItems.IsUsableCarrier(pawn2, base.pawn, false)) { - if (!onlyAnimals || pawn2.RaceProps.Animal) + float carrierScore = this.GetCarrierScore(pawn2); + if (pawn == null || carrierScore > num) { - if (JobDriver_PrepareCaravan_GatherItems.IsUsableCarrier(pawn2, this.pawn, false)) - { - float carrierScore = this.GetCarrierScore(pawn2); - if (pawn == null || carrierScore > num) - { - pawn = pawn2; - num = carrierScore; - } - } + pawn = pawn2; + num = carrierScore; } } } diff --git a/Assembly-CSharp/RimWorld/JobDriver_PrepareCaravan_GatherPawns.cs b/Assembly-CSharp/RimWorld/JobDriver_PrepareCaravan_GatherPawns.cs index 62a058ff0..78ea03be5 100644 --- a/Assembly-CSharp/RimWorld/JobDriver_PrepareCaravan_GatherPawns.cs +++ b/Assembly-CSharp/RimWorld/JobDriver_PrepareCaravan_GatherPawns.cs @@ -1,8 +1,8 @@ using System; using System.Collections.Generic; -using System.Diagnostics; using Verse; using Verse.AI; +using Verse.AI.Group; namespace RimWorld { @@ -18,27 +18,25 @@ private Pawn AnimalOrSlave } } - [DebuggerHidden] protected override IEnumerable MakeNewToils() { - JobDriver_PrepareCaravan_GatherPawns.c__IteratorA c__IteratorA = new JobDriver_PrepareCaravan_GatherPawns.c__IteratorA(); - c__IteratorA.<>f__this = this; - JobDriver_PrepareCaravan_GatherPawns.c__IteratorA expr_0E = c__IteratorA; - expr_0E.$PC = -2; - return expr_0E; + this.FailOn((Func)(() => !((_003CMakeNewToils_003Ec__IteratorA)/*Error near IL_002f: stateMachine*/)._003C_003Ef__this.Map.lordManager.lords.Contains(((_003CMakeNewToils_003Ec__IteratorA)/*Error near IL_002f: stateMachine*/)._003C_003Ef__this.CurJob.lord))); + this.FailOn((Func)(() => ((_003CMakeNewToils_003Ec__IteratorA)/*Error near IL_0047: stateMachine*/)._003C_003Ef__this.AnimalOrSlave.GetLord() != ((_003CMakeNewToils_003Ec__IteratorA)/*Error near IL_0047: stateMachine*/)._003C_003Ef__this.CurJob.lord)); + yield return Toils_Reserve.Reserve(TargetIndex.A, 1, -1, null); + yield return Toils_Goto.GotoThing(TargetIndex.A, PathEndMode.Touch).FailOnDespawnedOrNull(TargetIndex.A).FailOn((Func)(() => GatherAnimalsAndSlavesForCaravanUtility.IsFollowingAnyone(((_003CMakeNewToils_003Ec__IteratorA)/*Error near IL_0082: stateMachine*/)._003C_003Ef__this.AnimalOrSlave))); + yield return this.SetFollowerToil(); } private Toil SetFollowerToil() { - return new Toil + Toil toil = new Toil(); + toil.initAction = (Action)delegate { - initAction = delegate - { - GatherAnimalsAndSlavesForCaravanUtility.SetFollower(this.AnimalOrSlave, this.pawn); - RestUtility.WakeUp(this.pawn); - }, - defaultCompleteMode = ToilCompleteMode.Instant + GatherAnimalsAndSlavesForCaravanUtility.SetFollower(this.AnimalOrSlave, base.pawn); + RestUtility.WakeUp(base.pawn); }; + toil.defaultCompleteMode = ToilCompleteMode.Instant; + return toil; } } } diff --git a/Assembly-CSharp/RimWorld/JobDriver_RearmTrap.cs b/Assembly-CSharp/RimWorld/JobDriver_RearmTrap.cs index ab8e2d83d..19bd0f97f 100644 --- a/Assembly-CSharp/RimWorld/JobDriver_RearmTrap.cs +++ b/Assembly-CSharp/RimWorld/JobDriver_RearmTrap.cs @@ -1,6 +1,6 @@ using System; using System.Collections.Generic; -using System.Diagnostics; +using Verse; using Verse.AI; namespace RimWorld @@ -9,14 +9,37 @@ public class JobDriver_RearmTrap : JobDriver { private const int RearmTicks = 1125; - [DebuggerHidden] protected override IEnumerable MakeNewToils() { - JobDriver_RearmTrap.c__Iterator38 c__Iterator = new JobDriver_RearmTrap.c__Iterator38(); - c__Iterator.<>f__this = this; - JobDriver_RearmTrap.c__Iterator38 expr_0E = c__Iterator; - expr_0E.$PC = -2; - return expr_0E; + this.FailOnThingMissingDesignation(TargetIndex.A, DesignationDefOf.RearmTrap); + yield return Toils_Reserve.Reserve(TargetIndex.A, 1, -1, null); + Toil gotoThing = new Toil + { + initAction = (Action)delegate + { + ((_003CMakeNewToils_003Ec__Iterator38)/*Error near IL_006b: stateMachine*/)._003C_003Ef__this.pawn.pather.StartPath(((_003CMakeNewToils_003Ec__Iterator38)/*Error near IL_006b: stateMachine*/)._003C_003Ef__this.TargetThingA, PathEndMode.Touch); + }, + defaultCompleteMode = ToilCompleteMode.PatherArrival + }; + gotoThing.FailOnDespawnedNullOrForbidden(TargetIndex.A); + yield return gotoThing; + yield return Toils_General.Wait(1125).WithProgressBarToilDelay(TargetIndex.A, false, -0.5f); + yield return new Toil + { + initAction = (Action)delegate + { + Thing thing = ((_003CMakeNewToils_003Ec__Iterator38)/*Error near IL_00e6: stateMachine*/)._003C_003Ef__this.CurJob.targetA.Thing; + Designation designation = ((_003CMakeNewToils_003Ec__Iterator38)/*Error near IL_00e6: stateMachine*/)._003C_003Ef__this.Map.designationManager.DesignationOn(thing, DesignationDefOf.RearmTrap); + if (designation != null) + { + designation.Delete(); + } + Building_TrapRearmable building_TrapRearmable = thing as Building_TrapRearmable; + building_TrapRearmable.Rearm(); + ((_003CMakeNewToils_003Ec__Iterator38)/*Error near IL_00e6: stateMachine*/)._003C_003Ef__this.pawn.records.Increment(RecordDefOf.TrapsRearmed); + }, + defaultCompleteMode = ToilCompleteMode.Instant + }; } } } diff --git a/Assembly-CSharp/RimWorld/JobDriver_Refuel.cs b/Assembly-CSharp/RimWorld/JobDriver_Refuel.cs index a9fdb7f34..def6297b4 100644 --- a/Assembly-CSharp/RimWorld/JobDriver_Refuel.cs +++ b/Assembly-CSharp/RimWorld/JobDriver_Refuel.cs @@ -1,6 +1,5 @@ using System; using System.Collections.Generic; -using System.Diagnostics; using Verse; using Verse.AI; @@ -30,14 +29,31 @@ protected Thing Fuel } } - [DebuggerHidden] protected override IEnumerable MakeNewToils() { - JobDriver_Refuel.c__Iterator39 c__Iterator = new JobDriver_Refuel.c__Iterator39(); - c__Iterator.<>f__this = this; - JobDriver_Refuel.c__Iterator39 expr_0E = c__Iterator; - expr_0E.$PC = -2; - return expr_0E; + this.FailOnDespawnedNullOrForbidden(TargetIndex.A); + this.FailOn((Func)delegate + { + ThingWithComps thingWithComps = ((_003CMakeNewToils_003Ec__Iterator39)/*Error near IL_0050: stateMachine*/)._003C_003Ef__this.pawn.CurJob.GetTarget(TargetIndex.A).Thing as ThingWithComps; + if (thingWithComps != null) + { + CompFlickable comp = thingWithComps.GetComp(); + if (comp != null && !comp.SwitchIsOn) + { + return true; + } + } + return false; + }); + yield return Toils_Reserve.Reserve(TargetIndex.A, 1, -1, null); + Toil reserveFuel = Toils_Reserve.Reserve(TargetIndex.B, 1, -1, null); + yield return reserveFuel; + yield return Toils_Goto.GotoThing(TargetIndex.B, PathEndMode.ClosestTouch).FailOnDespawnedNullOrForbidden(TargetIndex.B).FailOnSomeonePhysicallyInteracting(TargetIndex.B); + yield return Toils_Haul.StartCarryThing(TargetIndex.B, false, true).FailOnDestroyedNullOrForbidden(TargetIndex.B); + yield return Toils_Haul.CheckForGetOpportunityDuplicate(reserveFuel, TargetIndex.B, TargetIndex.None, true, null); + yield return Toils_Goto.GotoThing(TargetIndex.A, PathEndMode.Touch); + yield return Toils_General.Wait(240).FailOnDestroyedNullOrForbidden(TargetIndex.B).FailOnDestroyedNullOrForbidden(TargetIndex.A).FailOnCannotTouch(TargetIndex.A, PathEndMode.Touch).WithProgressBarToilDelay(TargetIndex.A, false, -0.5f); + yield return Toils_Refuel.FinalizeRefueling(TargetIndex.A, TargetIndex.B); } } } diff --git a/Assembly-CSharp/RimWorld/JobDriver_RelaxAlone.cs b/Assembly-CSharp/RimWorld/JobDriver_RelaxAlone.cs index 2f08736a9..bb225ea5b 100644 --- a/Assembly-CSharp/RimWorld/JobDriver_RelaxAlone.cs +++ b/Assembly-CSharp/RimWorld/JobDriver_RelaxAlone.cs @@ -1,6 +1,5 @@ using System; using System.Collections.Generic; -using System.Diagnostics; using Verse; using Verse.AI; @@ -10,14 +9,25 @@ public class JobDriver_RelaxAlone : JobDriver { private Rot4 faceDir; - [DebuggerHidden] protected override IEnumerable MakeNewToils() { - JobDriver_RelaxAlone.c__Iterator1E c__Iterator1E = new JobDriver_RelaxAlone.c__Iterator1E(); - c__Iterator1E.<>f__this = this; - JobDriver_RelaxAlone.c__Iterator1E expr_0E = c__Iterator1E; - expr_0E.$PC = -2; - return expr_0E; + yield return Toils_Reserve.Reserve(TargetIndex.A, 1, -1, null); + yield return Toils_Goto.GotoCell(TargetIndex.A, PathEndMode.OnCell); + yield return new Toil + { + initAction = (Action)delegate + { + ((_003CMakeNewToils_003Ec__Iterator1E)/*Error near IL_006e: stateMachine*/)._003C_003Ef__this.faceDir = ((!((_003CMakeNewToils_003Ec__Iterator1E)/*Error near IL_006e: stateMachine*/)._003C_003Ef__this.CurJob.def.faceDir.IsValid) ? Rot4.Random : ((_003CMakeNewToils_003Ec__Iterator1E)/*Error near IL_006e: stateMachine*/)._003C_003Ef__this.CurJob.def.faceDir); + }, + tickAction = (Action)delegate + { + ((_003CMakeNewToils_003Ec__Iterator1E)/*Error near IL_0085: stateMachine*/)._003C_003Ef__this.pawn.Drawer.rotator.FaceCell(((_003CMakeNewToils_003Ec__Iterator1E)/*Error near IL_0085: stateMachine*/)._003C_003Ef__this.pawn.Position + ((_003CMakeNewToils_003Ec__Iterator1E)/*Error near IL_0085: stateMachine*/)._003C_003Ef__this.faceDir.FacingCell); + ((_003CMakeNewToils_003Ec__Iterator1E)/*Error near IL_0085: stateMachine*/)._003C_003Ef__this.pawn.GainComfortFromCellIfPossible(); + JoyUtility.JoyTickCheckEnd(((_003CMakeNewToils_003Ec__Iterator1E)/*Error near IL_0085: stateMachine*/)._003C_003Ef__this.pawn, JoyTickFullJoyAction.EndJob, 1f); + }, + defaultCompleteMode = ToilCompleteMode.Delay, + defaultDuration = base.CurJob.def.joyDuration + }; } public override void ExposeData() diff --git a/Assembly-CSharp/RimWorld/JobDriver_RemoveApparel.cs b/Assembly-CSharp/RimWorld/JobDriver_RemoveApparel.cs index 039b096a9..a546d7970 100644 --- a/Assembly-CSharp/RimWorld/JobDriver_RemoveApparel.cs +++ b/Assembly-CSharp/RimWorld/JobDriver_RemoveApparel.cs @@ -1,6 +1,6 @@ using System; using System.Collections.Generic; -using System.Diagnostics; +using Verse; using Verse.AI; namespace RimWorld @@ -17,14 +17,67 @@ private Apparel TargetApparel } } - [DebuggerHidden] protected override IEnumerable MakeNewToils() { - JobDriver_RemoveApparel.c__Iterator53 c__Iterator = new JobDriver_RemoveApparel.c__Iterator53(); - c__Iterator.<>f__this = this; - JobDriver_RemoveApparel.c__Iterator53 expr_0E = c__Iterator; - expr_0E.$PC = -2; - return expr_0E; + yield return new Toil + { + initAction = (Action)delegate + { + ((_003CMakeNewToils_003Ec__Iterator53)/*Error near IL_004a: stateMachine*/)._003C_003Ef__this.pawn.pather.StopDead(); + }, + defaultCompleteMode = ToilCompleteMode.Delay, + defaultDuration = 60 + }; + yield return new Toil + { + initAction = (Action)delegate + { + if (((_003CMakeNewToils_003Ec__Iterator53)/*Error near IL_009d: stateMachine*/)._003C_003Ef__this.pawn.apparel.WornApparel.Contains(((_003CMakeNewToils_003Ec__Iterator53)/*Error near IL_009d: stateMachine*/)._003C_003Ef__this.TargetApparel)) + { + Apparel apparel = default(Apparel); + if (((_003CMakeNewToils_003Ec__Iterator53)/*Error near IL_009d: stateMachine*/)._003C_003Ef__this.pawn.apparel.TryDrop(((_003CMakeNewToils_003Ec__Iterator53)/*Error near IL_009d: stateMachine*/)._003C_003Ef__this.TargetApparel, out apparel)) + { + ((_003CMakeNewToils_003Ec__Iterator53)/*Error near IL_009d: stateMachine*/)._003C_003Ef__this.CurJob.targetA = (Thing)apparel; + if (((_003CMakeNewToils_003Ec__Iterator53)/*Error near IL_009d: stateMachine*/)._003C_003Ef__this.CurJob.haulDroppedApparel) + { + apparel.SetForbidden(false, false); + StoragePriority currentPriority = HaulAIUtility.StoragePriorityAtFor(apparel.Position, apparel); + IntVec3 c = default(IntVec3); + if (StoreUtility.TryFindBestBetterStoreCellFor((Thing)apparel, ((_003CMakeNewToils_003Ec__Iterator53)/*Error near IL_009d: stateMachine*/)._003C_003Ef__this.pawn, ((_003CMakeNewToils_003Ec__Iterator53)/*Error near IL_009d: stateMachine*/)._003C_003Ef__this.Map, currentPriority, ((_003CMakeNewToils_003Ec__Iterator53)/*Error near IL_009d: stateMachine*/)._003C_003Ef__this.pawn.Faction, out c, true)) + { + ((_003CMakeNewToils_003Ec__Iterator53)/*Error near IL_009d: stateMachine*/)._003C_003Ef__this.CurJob.count = apparel.stackCount; + ((_003CMakeNewToils_003Ec__Iterator53)/*Error near IL_009d: stateMachine*/)._003C_003Ef__this.CurJob.targetB = c; + } + else + { + ((_003CMakeNewToils_003Ec__Iterator53)/*Error near IL_009d: stateMachine*/)._003C_003Ef__this.EndJobWith(JobCondition.Incompletable); + } + } + else + { + ((_003CMakeNewToils_003Ec__Iterator53)/*Error near IL_009d: stateMachine*/)._003C_003Ef__this.EndJobWith(JobCondition.Succeeded); + } + } + else + { + ((_003CMakeNewToils_003Ec__Iterator53)/*Error near IL_009d: stateMachine*/)._003C_003Ef__this.EndJobWith(JobCondition.Incompletable); + } + } + else + { + ((_003CMakeNewToils_003Ec__Iterator53)/*Error near IL_009d: stateMachine*/)._003C_003Ef__this.EndJobWith(JobCondition.Incompletable); + } + } + }; + if (base.CurJob.haulDroppedApparel) + { + yield return Toils_Reserve.Reserve(TargetIndex.B, 1, -1, null); + yield return Toils_Reserve.Reserve(TargetIndex.A, 1, -1, null); + yield return Toils_Haul.StartCarryThing(TargetIndex.A, false, false).FailOn((Func)(() => !((_003CMakeNewToils_003Ec__Iterator53)/*Error near IL_011a: stateMachine*/)._003C_003Ef__this.pawn.health.capacities.CapableOf(PawnCapacityDefOf.Manipulation))); + Toil carryToCell = Toils_Haul.CarryHauledThingToCell(TargetIndex.B); + yield return carryToCell; + yield return Toils_Haul.PlaceHauledThingInCell(TargetIndex.B, carryToCell, true); + } } } } diff --git a/Assembly-CSharp/RimWorld/JobDriver_RemoveBuilding.cs b/Assembly-CSharp/RimWorld/JobDriver_RemoveBuilding.cs index 215407def..fb8e746c4 100644 --- a/Assembly-CSharp/RimWorld/JobDriver_RemoveBuilding.cs +++ b/Assembly-CSharp/RimWorld/JobDriver_RemoveBuilding.cs @@ -1,6 +1,5 @@ using System; using System.Collections.Generic; -using System.Diagnostics; using Verse; using Verse.AI; @@ -45,14 +44,39 @@ public override void ExposeData() Scribe_Values.Look(ref this.totalNeededWork, "totalNeededWork", 0f, false); } - [DebuggerHidden] protected override IEnumerable MakeNewToils() { - JobDriver_RemoveBuilding.c__IteratorF c__IteratorF = new JobDriver_RemoveBuilding.c__IteratorF(); - c__IteratorF.<>f__this = this; - JobDriver_RemoveBuilding.c__IteratorF expr_0E = c__IteratorF; - expr_0E.$PC = -2; - return expr_0E; + this.FailOnThingMissingDesignation(TargetIndex.A, this.Designation); + this.FailOnForbidden(TargetIndex.A); + yield return Toils_Reserve.Reserve(TargetIndex.A, 1, -1, null); + yield return Toils_Goto.GotoThing(TargetIndex.A, PathEndMode.Touch); + Toil doWork = new Toil().FailOnDestroyedNullOrForbidden(TargetIndex.A).FailOnCannotTouch(TargetIndex.A, PathEndMode.Touch); + doWork.initAction = (Action)delegate + { + ((_003CMakeNewToils_003Ec__IteratorF)/*Error near IL_00a4: stateMachine*/)._003C_003Ef__this.totalNeededWork = (float)((_003CMakeNewToils_003Ec__IteratorF)/*Error near IL_00a4: stateMachine*/)._003C_003Ef__this.TotalNeededWork; + ((_003CMakeNewToils_003Ec__IteratorF)/*Error near IL_00a4: stateMachine*/)._003C_003Ef__this.workLeft = ((_003CMakeNewToils_003Ec__IteratorF)/*Error near IL_00a4: stateMachine*/)._003C_003Ef__this.totalNeededWork; + }; + doWork.tickAction = (Action)delegate + { + ((_003CMakeNewToils_003Ec__IteratorF)/*Error near IL_00bb: stateMachine*/)._003C_003Ef__this.workLeft -= ((_003CMakeNewToils_003Ec__IteratorF)/*Error near IL_00bb: stateMachine*/)._003C_003Ef__this.pawn.GetStatValue(StatDefOf.ConstructionSpeed, true); + ((_003CMakeNewToils_003Ec__IteratorF)/*Error near IL_00bb: stateMachine*/)._003C_003Ef__this.TickAction(); + if (((_003CMakeNewToils_003Ec__IteratorF)/*Error near IL_00bb: stateMachine*/)._003C_003Ef__this.workLeft <= 0.0) + { + ((_003CMakeNewToils_003Ec__IteratorF)/*Error near IL_00bb: stateMachine*/)._003CdoWork_003E__0.actor.jobs.curDriver.ReadyForNextToil(); + } + }; + doWork.defaultCompleteMode = ToilCompleteMode.Never; + doWork.WithProgressBar(TargetIndex.A, (Func)(() => (float)(1.0 - ((_003CMakeNewToils_003Ec__IteratorF)/*Error near IL_00df: stateMachine*/)._003C_003Ef__this.workLeft / ((_003CMakeNewToils_003Ec__IteratorF)/*Error near IL_00df: stateMachine*/)._003C_003Ef__this.totalNeededWork)), false, -0.5f); + yield return doWork; + yield return new Toil + { + initAction = (Action)delegate + { + ((_003CMakeNewToils_003Ec__IteratorF)/*Error near IL_0120: stateMachine*/)._003C_003Ef__this.FinishedRemoving(); + ((_003CMakeNewToils_003Ec__IteratorF)/*Error near IL_0120: stateMachine*/)._003C_003Ef__this.Map.designationManager.RemoveAllDesignationsOn(((_003CMakeNewToils_003Ec__IteratorF)/*Error near IL_0120: stateMachine*/)._003C_003Ef__this.Target, false); + }, + defaultCompleteMode = ToilCompleteMode.Instant + }; } protected virtual void FinishedRemoving() diff --git a/Assembly-CSharp/RimWorld/JobDriver_RemoveFloor.cs b/Assembly-CSharp/RimWorld/JobDriver_RemoveFloor.cs index 14d95735b..c2907cd52 100644 --- a/Assembly-CSharp/RimWorld/JobDriver_RemoveFloor.cs +++ b/Assembly-CSharp/RimWorld/JobDriver_RemoveFloor.cs @@ -1,4 +1,3 @@ -using System; using Verse; namespace RimWorld diff --git a/Assembly-CSharp/RimWorld/JobDriver_RemoveRoof.cs b/Assembly-CSharp/RimWorld/JobDriver_RemoveRoof.cs index 4ab697d61..c24686be4 100644 --- a/Assembly-CSharp/RimWorld/JobDriver_RemoveRoof.cs +++ b/Assembly-CSharp/RimWorld/JobDriver_RemoveRoof.cs @@ -1,6 +1,5 @@ using System; using System.Collections.Generic; -using System.Diagnostics; using Verse; using Verse.AI; @@ -18,14 +17,13 @@ protected override PathEndMode PathEndMode } } - [DebuggerHidden] protected override IEnumerable MakeNewToils() { - JobDriver_RemoveRoof.c__Iterator12 c__Iterator = new JobDriver_RemoveRoof.c__Iterator12(); - c__Iterator.<>f__this = this; - JobDriver_RemoveRoof.c__Iterator12 expr_0E = c__Iterator; - expr_0E.$PC = -2; - return expr_0E; + this.FailOn((Func)(() => !((Area)((_003CMakeNewToils_003Ec__Iterator12)/*Error near IL_0029: stateMachine*/)._003C_003Ef__this.Map.areaManager.NoRoof)[((_003CMakeNewToils_003Ec__Iterator12)/*Error near IL_0029: stateMachine*/)._003C_003Ef__this.Cell])); + foreach (Toil item in base.MakeNewToils()) + { + yield return item; + } } protected override void DoEffect() diff --git a/Assembly-CSharp/RimWorld/JobDriver_Repair.cs b/Assembly-CSharp/RimWorld/JobDriver_Repair.cs index 69a5bba68..23ce0c493 100644 --- a/Assembly-CSharp/RimWorld/JobDriver_Repair.cs +++ b/Assembly-CSharp/RimWorld/JobDriver_Repair.cs @@ -1,6 +1,7 @@ using System; using System.Collections.Generic; -using System.Diagnostics; +using UnityEngine; +using Verse; using Verse.AI; namespace RimWorld @@ -13,14 +14,41 @@ public class JobDriver_Repair : JobDriver protected float ticksToNextRepair; - [DebuggerHidden] protected override IEnumerable MakeNewToils() { - JobDriver_Repair.c__Iterator13 c__Iterator = new JobDriver_Repair.c__Iterator13(); - c__Iterator.<>f__this = this; - JobDriver_Repair.c__Iterator13 expr_0E = c__Iterator; - expr_0E.$PC = -2; - return expr_0E; + this.FailOnDespawnedNullOrForbidden(TargetIndex.A); + yield return Toils_Reserve.Reserve(TargetIndex.A, 1, -1, null); + yield return Toils_Goto.GotoThing(TargetIndex.A, PathEndMode.Touch); + Toil repair = new Toil + { + initAction = (Action)delegate + { + ((_003CMakeNewToils_003Ec__Iterator13)/*Error near IL_007b: stateMachine*/)._003C_003Ef__this.ticksToNextRepair = 80f; + }, + tickAction = (Action)delegate + { + Pawn actor = ((_003CMakeNewToils_003Ec__Iterator13)/*Error near IL_0092: stateMachine*/)._003Crepair_003E__0.actor; + actor.skills.Learn(SkillDefOf.Construction, 0.275f, false); + float statValue = actor.GetStatValue(StatDefOf.ConstructionSpeed, true); + ((_003CMakeNewToils_003Ec__Iterator13)/*Error near IL_0092: stateMachine*/)._003C_003Ef__this.ticksToNextRepair -= statValue; + if (((_003CMakeNewToils_003Ec__Iterator13)/*Error near IL_0092: stateMachine*/)._003C_003Ef__this.ticksToNextRepair <= 0.0) + { + ((_003CMakeNewToils_003Ec__Iterator13)/*Error near IL_0092: stateMachine*/)._003C_003Ef__this.ticksToNextRepair += 20f; + ((_003CMakeNewToils_003Ec__Iterator13)/*Error near IL_0092: stateMachine*/)._003C_003Ef__this.TargetThingA.HitPoints++; + ((_003CMakeNewToils_003Ec__Iterator13)/*Error near IL_0092: stateMachine*/)._003C_003Ef__this.TargetThingA.HitPoints = Mathf.Min(((_003CMakeNewToils_003Ec__Iterator13)/*Error near IL_0092: stateMachine*/)._003C_003Ef__this.TargetThingA.HitPoints, ((_003CMakeNewToils_003Ec__Iterator13)/*Error near IL_0092: stateMachine*/)._003C_003Ef__this.TargetThingA.MaxHitPoints); + ((_003CMakeNewToils_003Ec__Iterator13)/*Error near IL_0092: stateMachine*/)._003C_003Ef__this.Map.listerBuildingsRepairable.Notify_BuildingRepaired((Building)((_003CMakeNewToils_003Ec__Iterator13)/*Error near IL_0092: stateMachine*/)._003C_003Ef__this.TargetThingA); + if (((_003CMakeNewToils_003Ec__Iterator13)/*Error near IL_0092: stateMachine*/)._003C_003Ef__this.TargetThingA.HitPoints == ((_003CMakeNewToils_003Ec__Iterator13)/*Error near IL_0092: stateMachine*/)._003C_003Ef__this.TargetThingA.MaxHitPoints) + { + actor.records.Increment(RecordDefOf.ThingsRepaired); + actor.jobs.EndCurrentJob(JobCondition.Succeeded, true); + } + } + } + }; + repair.FailOnCannotTouch(TargetIndex.A, PathEndMode.Touch); + repair.WithEffect(base.TargetThingA.def.repairEffect, TargetIndex.A); + repair.defaultCompleteMode = ToilCompleteMode.Never; + yield return repair; } } } diff --git a/Assembly-CSharp/RimWorld/JobDriver_Research.cs b/Assembly-CSharp/RimWorld/JobDriver_Research.cs index ef00a9048..b139b7b77 100644 --- a/Assembly-CSharp/RimWorld/JobDriver_Research.cs +++ b/Assembly-CSharp/RimWorld/JobDriver_Research.cs @@ -1,6 +1,5 @@ using System; using System.Collections.Generic; -using System.Diagnostics; using Verse; using Verse.AI; @@ -26,14 +25,40 @@ private Building_ResearchBench ResearchBench } } - [DebuggerHidden] protected override IEnumerable MakeNewToils() { - JobDriver_Research.c__Iterator3B c__Iterator3B = new JobDriver_Research.c__Iterator3B(); - c__Iterator3B.<>f__this = this; - JobDriver_Research.c__Iterator3B expr_0E = c__Iterator3B; - expr_0E.$PC = -2; - return expr_0E; + this.FailOnDespawnedNullOrForbidden(TargetIndex.A); + yield return Toils_Reserve.Reserve(TargetIndex.A, 1, -1, null); + yield return Toils_Goto.GotoThing(TargetIndex.A, PathEndMode.InteractionCell); + Toil research = new Toil + { + tickAction = (Action)delegate + { + Pawn actor = ((_003CMakeNewToils_003Ec__Iterator3B)/*Error near IL_007f: stateMachine*/)._003Cresearch_003E__0.actor; + float statValue = actor.GetStatValue(StatDefOf.ResearchSpeed, true); + statValue *= ((_003CMakeNewToils_003Ec__Iterator3B)/*Error near IL_007f: stateMachine*/)._003C_003Ef__this.TargetThingA.GetStatValue(StatDefOf.ResearchSpeedFactor, true); + Find.ResearchManager.ResearchPerformed(statValue, actor); + actor.skills.Learn(SkillDefOf.Intellectual, 0.11f, false); + actor.GainComfortFromCellIfPossible(); + } + }; + research.FailOn((Func)(() => ((_003CMakeNewToils_003Ec__Iterator3B)/*Error near IL_0096: stateMachine*/)._003C_003Ef__this.Project == null)); + research.FailOn((Func)(() => !((_003CMakeNewToils_003Ec__Iterator3B)/*Error near IL_00ae: stateMachine*/)._003C_003Ef__this.Project.CanBeResearchedAt(((_003CMakeNewToils_003Ec__Iterator3B)/*Error near IL_00ae: stateMachine*/)._003C_003Ef__this.ResearchBench, false))); + research.FailOnCannotTouch(TargetIndex.A, PathEndMode.InteractionCell); + research.WithEffect(EffecterDefOf.Research, TargetIndex.A); + research.WithProgressBar(TargetIndex.A, (Func)delegate + { + ResearchProjectDef project = ((_003CMakeNewToils_003Ec__Iterator3B)/*Error near IL_00e7: stateMachine*/)._003C_003Ef__this.Project; + if (project == null) + { + return 0f; + } + return project.ProgressPercent; + }, false, -0.5f); + research.defaultCompleteMode = ToilCompleteMode.Delay; + research.defaultDuration = 4000; + yield return research; + yield return Toils_General.Wait(2); } } } diff --git a/Assembly-CSharp/RimWorld/JobDriver_Shear.cs b/Assembly-CSharp/RimWorld/JobDriver_Shear.cs index 0bc7ae6b8..afa98ba96 100644 --- a/Assembly-CSharp/RimWorld/JobDriver_Shear.cs +++ b/Assembly-CSharp/RimWorld/JobDriver_Shear.cs @@ -1,4 +1,3 @@ -using System; using Verse; namespace RimWorld diff --git a/Assembly-CSharp/RimWorld/JobDriver_SitFacingBuilding.cs b/Assembly-CSharp/RimWorld/JobDriver_SitFacingBuilding.cs index 89c32534a..6db154740 100644 --- a/Assembly-CSharp/RimWorld/JobDriver_SitFacingBuilding.cs +++ b/Assembly-CSharp/RimWorld/JobDriver_SitFacingBuilding.cs @@ -1,20 +1,36 @@ using System; using System.Collections.Generic; -using System.Diagnostics; using Verse.AI; namespace RimWorld { public class JobDriver_SitFacingBuilding : JobDriver { - [DebuggerHidden] protected override IEnumerable MakeNewToils() { - JobDriver_SitFacingBuilding.c__Iterator1F c__Iterator1F = new JobDriver_SitFacingBuilding.c__Iterator1F(); - c__Iterator1F.<>f__this = this; - JobDriver_SitFacingBuilding.c__Iterator1F expr_0E = c__Iterator1F; - expr_0E.$PC = -2; - return expr_0E; + this.EndOnDespawnedOrNull(TargetIndex.A, JobCondition.Incompletable); + this.EndOnDespawnedOrNull(TargetIndex.B, JobCondition.Incompletable); + yield return Toils_Reserve.Reserve(TargetIndex.A, base.CurJob.def.joyMaxParticipants, 0, null); + yield return Toils_Reserve.Reserve(TargetIndex.B, 1, -1, null); + yield return Toils_Goto.GotoThing(TargetIndex.B, PathEndMode.OnCell); + Toil play = new Toil + { + tickAction = (Action)delegate + { + ((_003CMakeNewToils_003Ec__Iterator1F)/*Error near IL_00bd: stateMachine*/)._003C_003Ef__this.pawn.Drawer.rotator.FaceCell(((_003CMakeNewToils_003Ec__Iterator1F)/*Error near IL_00bd: stateMachine*/)._003C_003Ef__this.TargetA.Cell); + ((_003CMakeNewToils_003Ec__Iterator1F)/*Error near IL_00bd: stateMachine*/)._003C_003Ef__this.pawn.GainComfortFromCellIfPossible(); + float statValue; + float num = statValue = ((_003CMakeNewToils_003Ec__Iterator1F)/*Error near IL_00bd: stateMachine*/)._003C_003Ef__this.TargetThingA.GetStatValue(StatDefOf.EntertainmentStrengthFactor, true); + JoyUtility.JoyTickCheckEnd(((_003CMakeNewToils_003Ec__Iterator1F)/*Error near IL_00bd: stateMachine*/)._003C_003Ef__this.pawn, JoyTickFullJoyAction.EndJob, statValue); + }, + defaultCompleteMode = ToilCompleteMode.Delay, + defaultDuration = base.CurJob.def.joyDuration + }; + play.AddFinishAction((Action)delegate + { + JoyUtility.TryGainRecRoomThought(((_003CMakeNewToils_003Ec__Iterator1F)/*Error near IL_0100: stateMachine*/)._003C_003Ef__this.pawn); + }); + yield return play; } } } diff --git a/Assembly-CSharp/RimWorld/JobDriver_Skygaze.cs b/Assembly-CSharp/RimWorld/JobDriver_Skygaze.cs index 56f562b9b..007c1b36e 100644 --- a/Assembly-CSharp/RimWorld/JobDriver_Skygaze.cs +++ b/Assembly-CSharp/RimWorld/JobDriver_Skygaze.cs @@ -1,6 +1,5 @@ using System; using System.Collections.Generic; -using System.Diagnostics; using Verse; using Verse.AI; @@ -14,18 +13,23 @@ public override PawnPosture Posture { get { - return (base.CurToil != this.gaze) ? PawnPosture.Standing : PawnPosture.LayingFaceUp; + return (PawnPosture)((base.CurToil == this.gaze) ? 1 : 0); } } - [DebuggerHidden] protected override IEnumerable MakeNewToils() { - JobDriver_Skygaze.c__Iterator20 c__Iterator = new JobDriver_Skygaze.c__Iterator20(); - c__Iterator.<>f__this = this; - JobDriver_Skygaze.c__Iterator20 expr_0E = c__Iterator; - expr_0E.$PC = -2; - return expr_0E; + yield return Toils_Goto.GotoCell(TargetIndex.A, PathEndMode.OnCell); + this.gaze = new Toil(); + this.gaze.tickAction = (Action)delegate + { + JoyUtility.JoyTickCheckEnd(((_003CMakeNewToils_003Ec__Iterator20)/*Error near IL_0059: stateMachine*/)._003C_003Ef__this.pawn, JoyTickFullJoyAction.EndJob, 1f); + }; + this.gaze.defaultCompleteMode = ToilCompleteMode.Delay; + this.gaze.defaultDuration = base.CurJob.def.joyDuration; + this.gaze.FailOn((Func)(() => ((_003CMakeNewToils_003Ec__Iterator20)/*Error near IL_00ab: stateMachine*/)._003C_003Ef__this.pawn.Position.Roofed(((_003CMakeNewToils_003Ec__Iterator20)/*Error near IL_00ab: stateMachine*/)._003C_003Ef__this.pawn.Map))); + this.gaze.FailOn((Func)(() => !JoyUtility.EnjoyableOutsideNow(((_003CMakeNewToils_003Ec__Iterator20)/*Error near IL_00c8: stateMachine*/)._003C_003Ef__this.pawn, null))); + yield return this.gaze; } public override string GetReport() @@ -35,19 +39,19 @@ public override string GetReport() return "WatchingEclipse".Translate(); } float num = GenCelestial.CurCelestialSunGlow(base.Map); - if (num < 0.1f) + if (num < 0.10000000149011612) { return "Stargazing".Translate(); } - if (num >= 0.65f) - { - return "CloudWatching".Translate(); - } - if (GenLocalDate.DayPercent(this.pawn) < 0.5f) + if (num < 0.64999997615814209) { - return "WatchingSunrise".Translate(); + if (GenLocalDate.DayPercent(base.pawn) < 0.5) + { + return "WatchingSunrise".Translate(); + } + return "WatchingSunset".Translate(); } - return "WatchingSunset".Translate(); + return "CloudWatching".Translate(); } } } diff --git a/Assembly-CSharp/RimWorld/JobDriver_Slaughter.cs b/Assembly-CSharp/RimWorld/JobDriver_Slaughter.cs index 8bd03b527..013072f7e 100644 --- a/Assembly-CSharp/RimWorld/JobDriver_Slaughter.cs +++ b/Assembly-CSharp/RimWorld/JobDriver_Slaughter.cs @@ -1,6 +1,5 @@ using System; using System.Collections.Generic; -using System.Diagnostics; using Verse; using Verse.AI; @@ -18,14 +17,22 @@ protected Pawn Victim } } - [DebuggerHidden] protected override IEnumerable MakeNewToils() { - JobDriver_Slaughter.c__Iterator7 c__Iterator = new JobDriver_Slaughter.c__Iterator7(); - c__Iterator.<>f__this = this; - JobDriver_Slaughter.c__Iterator7 expr_0E = c__Iterator; - expr_0E.$PC = -2; - return expr_0E; + this.FailOnAggroMentalState(TargetIndex.A); + this.FailOnThingMissingDesignation(TargetIndex.A, DesignationDefOf.Slaughter); + yield return Toils_Reserve.Reserve(TargetIndex.A, 1, -1, null); + yield return Toils_Goto.GotoThing(TargetIndex.A, PathEndMode.Touch); + yield return Toils_General.WaitWith(TargetIndex.A, 180, true, false); + yield return new Toil + { + initAction = (Action)delegate + { + ExecutionUtility.DoExecutionByCut(((_003CMakeNewToils_003Ec__Iterator7)/*Error near IL_00b0: stateMachine*/)._003Cexecute_003E__0.actor, ((_003CMakeNewToils_003Ec__Iterator7)/*Error near IL_00b0: stateMachine*/)._003C_003Ef__this.Victim); + ((_003CMakeNewToils_003Ec__Iterator7)/*Error near IL_00b0: stateMachine*/)._003C_003Ef__this.pawn.records.Increment(RecordDefOf.AnimalsSlaughtered); + }, + defaultCompleteMode = ToilCompleteMode.Instant + }; } } } diff --git a/Assembly-CSharp/RimWorld/JobDriver_SmoothFloor.cs b/Assembly-CSharp/RimWorld/JobDriver_SmoothFloor.cs index d0a71fa87..c38a0572c 100644 --- a/Assembly-CSharp/RimWorld/JobDriver_SmoothFloor.cs +++ b/Assembly-CSharp/RimWorld/JobDriver_SmoothFloor.cs @@ -1,4 +1,3 @@ -using System; using Verse; namespace RimWorld @@ -31,7 +30,7 @@ protected override StatDef SpeedStat public JobDriver_SmoothFloor() { - this.clearSnow = true; + base.clearSnow = true; } protected override void DoEffect(IntVec3 c) diff --git a/Assembly-CSharp/RimWorld/JobDriver_SocialRelax.cs b/Assembly-CSharp/RimWorld/JobDriver_SocialRelax.cs index c273f04a2..e3e53adb4 100644 --- a/Assembly-CSharp/RimWorld/JobDriver_SocialRelax.cs +++ b/Assembly-CSharp/RimWorld/JobDriver_SocialRelax.cs @@ -1,6 +1,5 @@ using System; using System.Collections.Generic; -using System.Diagnostics; using UnityEngine; using Verse; using Verse.AI; @@ -43,24 +42,54 @@ private IntVec3 ClosestGatherSpotParentCell { get { - return this.GatherSpotParent.OccupiedRect().ClosestCellTo(this.pawn.Position); + return this.GatherSpotParent.OccupiedRect().ClosestCellTo(base.pawn.Position); } } - [DebuggerHidden] protected override IEnumerable MakeNewToils() { - JobDriver_SocialRelax.c__Iterator21 c__Iterator = new JobDriver_SocialRelax.c__Iterator21(); - c__Iterator.<>f__this = this; - JobDriver_SocialRelax.c__Iterator21 expr_0E = c__Iterator; - expr_0E.$PC = -2; - return expr_0E; + this.EndOnDespawnedOrNull(TargetIndex.A, JobCondition.Incompletable); + if (this.HasChair) + { + this.EndOnDespawnedOrNull(TargetIndex.B, JobCondition.Incompletable); + } + yield return Toils_Reserve.Reserve(TargetIndex.B, 1, -1, null); + if (this.HasDrink) + { + this.FailOnDestroyedNullOrForbidden(TargetIndex.C); + yield return Toils_Reserve.Reserve(TargetIndex.C, 1, -1, null); + yield return Toils_Goto.GotoThing(TargetIndex.C, PathEndMode.OnCell).FailOnSomeonePhysicallyInteracting(TargetIndex.C); + yield return Toils_Haul.StartCarryThing(TargetIndex.C, false, false); + } + yield return Toils_Goto.GotoCell(TargetIndex.B, PathEndMode.OnCell); + Toil chew = new Toil + { + tickAction = (Action)delegate + { + ((_003CMakeNewToils_003Ec__Iterator21)/*Error near IL_011b: stateMachine*/)._003C_003Ef__this.pawn.Drawer.rotator.FaceCell(((_003CMakeNewToils_003Ec__Iterator21)/*Error near IL_011b: stateMachine*/)._003C_003Ef__this.ClosestGatherSpotParentCell); + ((_003CMakeNewToils_003Ec__Iterator21)/*Error near IL_011b: stateMachine*/)._003C_003Ef__this.pawn.GainComfortFromCellIfPossible(); + JoyUtility.JoyTickCheckEnd(((_003CMakeNewToils_003Ec__Iterator21)/*Error near IL_011b: stateMachine*/)._003C_003Ef__this.pawn, JoyTickFullJoyAction.GoToNextToil, 1f); + }, + defaultCompleteMode = ToilCompleteMode.Delay, + defaultDuration = base.CurJob.def.joyDuration + }; + chew.AddFinishAction((Action)delegate + { + JoyUtility.TryGainRecRoomThought(((_003CMakeNewToils_003Ec__Iterator21)/*Error near IL_015e: stateMachine*/)._003C_003Ef__this.pawn); + }); + chew.socialMode = RandomSocialMode.SuperActive; + Toils_Ingest.AddIngestionEffects(chew, base.pawn, TargetIndex.C, TargetIndex.None); + yield return chew; + if (this.HasDrink) + { + yield return Toils_Ingest.FinalizeIngest(base.pawn, TargetIndex.C); + } } public override bool ModifyCarriedThingDrawPos(ref Vector3 drawPos, ref bool behind, ref bool flip) { IntVec3 closestGatherSpotParentCell = this.ClosestGatherSpotParentCell; - return JobDriver_Ingest.ModifyCarriedThingDrawPosWorker(ref drawPos, ref behind, ref flip, closestGatherSpotParentCell, this.pawn); + return JobDriver_Ingest.ModifyCarriedThingDrawPosWorker(ref drawPos, ref behind, ref flip, closestGatherSpotParentCell, base.pawn); } } } diff --git a/Assembly-CSharp/RimWorld/JobDriver_Spectate.cs b/Assembly-CSharp/RimWorld/JobDriver_Spectate.cs index 71c7692a0..1f3981747 100644 --- a/Assembly-CSharp/RimWorld/JobDriver_Spectate.cs +++ b/Assembly-CSharp/RimWorld/JobDriver_Spectate.cs @@ -1,6 +1,6 @@ using System; using System.Collections.Generic; -using System.Diagnostics; +using Verse; using Verse.AI; namespace RimWorld @@ -11,14 +11,28 @@ public class JobDriver_Spectate : JobDriver private const TargetIndex WatchTargetInd = TargetIndex.B; - [DebuggerHidden] protected override IEnumerable MakeNewToils() { - JobDriver_Spectate.c__Iterator17 c__Iterator = new JobDriver_Spectate.c__Iterator17(); - c__Iterator.<>f__this = this; - JobDriver_Spectate.c__Iterator17 expr_0E = c__Iterator; - expr_0E.$PC = -2; - return expr_0E; + if (base.CurJob.GetTarget(TargetIndex.A).HasThing) + { + this.EndOnDespawnedOrNull(TargetIndex.A, JobCondition.Incompletable); + } + yield return Toils_Reserve.Reserve(TargetIndex.A, 1, -1, null); + yield return Toils_Goto.GotoCell(TargetIndex.A, PathEndMode.OnCell); + yield return new Toil + { + tickAction = (Action)delegate + { + ((_003CMakeNewToils_003Ec__Iterator17)/*Error near IL_00a6: stateMachine*/)._003C_003Ef__this.pawn.Drawer.rotator.FaceCell(((_003CMakeNewToils_003Ec__Iterator17)/*Error near IL_00a6: stateMachine*/)._003C_003Ef__this.CurJob.GetTarget(TargetIndex.B).Cell); + ((_003CMakeNewToils_003Ec__Iterator17)/*Error near IL_00a6: stateMachine*/)._003C_003Ef__this.pawn.GainComfortFromCellIfPossible(); + if (((_003CMakeNewToils_003Ec__Iterator17)/*Error near IL_00a6: stateMachine*/)._003C_003Ef__this.pawn.IsHashIntervalTick(100)) + { + ((_003CMakeNewToils_003Ec__Iterator17)/*Error near IL_00a6: stateMachine*/)._003C_003Ef__this.pawn.jobs.CheckForJobOverride(); + } + }, + defaultCompleteMode = ToilCompleteMode.Never, + handlingFacing = true + }; } } } diff --git a/Assembly-CSharp/RimWorld/JobDriver_StandAndBeSociallyActive.cs b/Assembly-CSharp/RimWorld/JobDriver_StandAndBeSociallyActive.cs index a7da206e4..dbb058a06 100644 --- a/Assembly-CSharp/RimWorld/JobDriver_StandAndBeSociallyActive.cs +++ b/Assembly-CSharp/RimWorld/JobDriver_StandAndBeSociallyActive.cs @@ -1,6 +1,5 @@ using System; using System.Collections.Generic; -using System.Diagnostics; using Verse; using Verse.AI; @@ -8,31 +7,37 @@ namespace RimWorld { public class JobDriver_StandAndBeSociallyActive : JobDriver { - [DebuggerHidden] protected override IEnumerable MakeNewToils() { - JobDriver_StandAndBeSociallyActive.c__Iterator18 c__Iterator = new JobDriver_StandAndBeSociallyActive.c__Iterator18(); - c__Iterator.<>f__this = this; - JobDriver_StandAndBeSociallyActive.c__Iterator18 expr_0E = c__Iterator; - expr_0E.$PC = -2; - return expr_0E; + yield return new Toil + { + tickAction = (Action)delegate + { + Pawn pawn = ((_003CMakeNewToils_003Ec__Iterator18)/*Error near IL_0032: stateMachine*/)._003C_003Ef__this.FindClosePawn(); + if (pawn != null) + { + ((_003CMakeNewToils_003Ec__Iterator18)/*Error near IL_0032: stateMachine*/)._003C_003Ef__this.pawn.Drawer.rotator.FaceCell(pawn.Position); + } + ((_003CMakeNewToils_003Ec__Iterator18)/*Error near IL_0032: stateMachine*/)._003C_003Ef__this.pawn.GainComfortFromCellIfPossible(); + }, + socialMode = RandomSocialMode.SuperActive, + defaultCompleteMode = ToilCompleteMode.Never, + handlingFacing = true + }; } private Pawn FindClosePawn() { - IntVec3 position = this.pawn.Position; + IntVec3 position = base.pawn.Position; for (int i = 0; i < 24; i++) { IntVec3 intVec = position + GenRadial.RadialPattern[i]; if (intVec.InBounds(base.Map)) { - Thing thing = intVec.GetThingList(base.Map).Find((Thing x) => x is Pawn); - if (thing != null && thing != this.pawn) + Thing thing = intVec.GetThingList(base.Map).Find((Predicate)((Thing x) => x is Pawn)); + if (thing != null && thing != base.pawn && GenSight.LineOfSight(position, intVec, base.Map, false, null, 0, 0)) { - if (GenSight.LineOfSight(position, intVec, base.Map, false, null, 0, 0)) - { - return (Pawn)thing; - } + return (Pawn)thing; } } } diff --git a/Assembly-CSharp/RimWorld/JobDriver_Strip.cs b/Assembly-CSharp/RimWorld/JobDriver_Strip.cs index e502577d0..3c216e9d5 100644 --- a/Assembly-CSharp/RimWorld/JobDriver_Strip.cs +++ b/Assembly-CSharp/RimWorld/JobDriver_Strip.cs @@ -1,6 +1,6 @@ using System; using System.Collections.Generic; -using System.Diagnostics; +using Verse; using Verse.AI; namespace RimWorld @@ -9,14 +9,41 @@ public class JobDriver_Strip : JobDriver { private const int StripTicks = 60; - [DebuggerHidden] protected override IEnumerable MakeNewToils() { - JobDriver_Strip.c__Iterator3C c__Iterator3C = new JobDriver_Strip.c__Iterator3C(); - c__Iterator3C.<>f__this = this; - JobDriver_Strip.c__Iterator3C expr_0E = c__Iterator3C; - expr_0E.$PC = -2; - return expr_0E; + this.FailOnAggroMentalState(TargetIndex.A); + this.FailOn((Func)(() => !StrippableUtility.CanBeStrippedByColony(((_003CMakeNewToils_003Ec__Iterator3C)/*Error near IL_0040: stateMachine*/)._003C_003Ef__this.TargetThingA))); + yield return Toils_Reserve.Reserve(TargetIndex.A, 1, -1, null); + Toil gotoThing = new Toil + { + initAction = (Action)delegate + { + ((_003CMakeNewToils_003Ec__Iterator3C)/*Error near IL_007e: stateMachine*/)._003C_003Ef__this.pawn.pather.StartPath(((_003CMakeNewToils_003Ec__Iterator3C)/*Error near IL_007e: stateMachine*/)._003C_003Ef__this.TargetThingA, PathEndMode.ClosestTouch); + }, + defaultCompleteMode = ToilCompleteMode.PatherArrival + }; + gotoThing.FailOnDespawnedNullOrForbidden(TargetIndex.A); + yield return gotoThing; + yield return Toils_General.Wait(60).WithProgressBarToilDelay(TargetIndex.A, false, -0.5f); + yield return new Toil + { + initAction = (Action)delegate + { + Thing thing = ((_003CMakeNewToils_003Ec__Iterator3C)/*Error near IL_00f6: stateMachine*/)._003C_003Ef__this.CurJob.targetA.Thing; + Designation designation = ((_003CMakeNewToils_003Ec__Iterator3C)/*Error near IL_00f6: stateMachine*/)._003C_003Ef__this.Map.designationManager.DesignationOn(thing, DesignationDefOf.Strip); + if (designation != null) + { + designation.Delete(); + } + IStrippable strippable = thing as IStrippable; + if (strippable != null) + { + strippable.Strip(); + } + ((_003CMakeNewToils_003Ec__Iterator3C)/*Error near IL_00f6: stateMachine*/)._003C_003Ef__this.pawn.records.Increment(RecordDefOf.BodiesStripped); + }, + defaultCompleteMode = ToilCompleteMode.Instant + }; } } } diff --git a/Assembly-CSharp/RimWorld/JobDriver_TakeAndExitMap.cs b/Assembly-CSharp/RimWorld/JobDriver_TakeAndExitMap.cs index 4f121a946..4a495340e 100644 --- a/Assembly-CSharp/RimWorld/JobDriver_TakeAndExitMap.cs +++ b/Assembly-CSharp/RimWorld/JobDriver_TakeAndExitMap.cs @@ -1,6 +1,5 @@ using System; using System.Collections.Generic; -using System.Diagnostics; using Verse; using Verse.AI; @@ -20,14 +19,32 @@ protected Thing Item } } - [DebuggerHidden] protected override IEnumerable MakeNewToils() { - JobDriver_TakeAndExitMap.c__Iterator30 c__Iterator = new JobDriver_TakeAndExitMap.c__Iterator30(); - c__Iterator.<>f__this = this; - JobDriver_TakeAndExitMap.c__Iterator30 expr_0E = c__Iterator; - expr_0E.$PC = -2; - return expr_0E; + this.FailOnDestroyedOrNull(TargetIndex.A); + yield return Toils_Reserve.Reserve(TargetIndex.A, 1, -1, null); + yield return Toils_Goto.GotoThing(TargetIndex.A, PathEndMode.ClosestTouch).FailOnSomeonePhysicallyInteracting(TargetIndex.A); + yield return Toils_Construct.UninstallIfMinifiable(TargetIndex.A).FailOnSomeonePhysicallyInteracting(TargetIndex.A); + yield return Toils_Haul.StartCarryThing(TargetIndex.A, false, false); + Toil gotoCell = Toils_Goto.GotoCell(TargetIndex.B, PathEndMode.OnCell); + gotoCell.AddPreTickAction((Action)delegate + { + if (((_003CMakeNewToils_003Ec__Iterator30)/*Error near IL_00c7: stateMachine*/)._003C_003Ef__this.Map.exitMapGrid.IsExitCell(((_003CMakeNewToils_003Ec__Iterator30)/*Error near IL_00c7: stateMachine*/)._003C_003Ef__this.pawn.Position)) + { + ((_003CMakeNewToils_003Ec__Iterator30)/*Error near IL_00c7: stateMachine*/)._003C_003Ef__this.pawn.ExitMap(true); + } + }); + yield return gotoCell; + yield return new Toil + { + initAction = (Action)delegate + { + if (!((_003CMakeNewToils_003Ec__Iterator30)/*Error near IL_0101: stateMachine*/)._003C_003Ef__this.pawn.Position.OnEdge(((_003CMakeNewToils_003Ec__Iterator30)/*Error near IL_0101: stateMachine*/)._003C_003Ef__this.pawn.Map) && !((_003CMakeNewToils_003Ec__Iterator30)/*Error near IL_0101: stateMachine*/)._003C_003Ef__this.pawn.Map.exitMapGrid.IsExitCell(((_003CMakeNewToils_003Ec__Iterator30)/*Error near IL_0101: stateMachine*/)._003C_003Ef__this.pawn.Position)) + return; + ((_003CMakeNewToils_003Ec__Iterator30)/*Error near IL_0101: stateMachine*/)._003C_003Ef__this.pawn.ExitMap(true); + }, + defaultCompleteMode = ToilCompleteMode.Instant + }; } } } diff --git a/Assembly-CSharp/RimWorld/JobDriver_TakeBeerOutOfFermentingBarrel.cs b/Assembly-CSharp/RimWorld/JobDriver_TakeBeerOutOfFermentingBarrel.cs index e3e8dcbbd..bed4418df 100644 --- a/Assembly-CSharp/RimWorld/JobDriver_TakeBeerOutOfFermentingBarrel.cs +++ b/Assembly-CSharp/RimWorld/JobDriver_TakeBeerOutOfFermentingBarrel.cs @@ -1,6 +1,5 @@ using System; using System.Collections.Generic; -using System.Diagnostics; using Verse; using Verse.AI; @@ -32,14 +31,41 @@ protected Thing Beer } } - [DebuggerHidden] protected override IEnumerable MakeNewToils() { - JobDriver_TakeBeerOutOfFermentingBarrel.c__Iterator3D c__Iterator3D = new JobDriver_TakeBeerOutOfFermentingBarrel.c__Iterator3D(); - c__Iterator3D.<>f__this = this; - JobDriver_TakeBeerOutOfFermentingBarrel.c__Iterator3D expr_0E = c__Iterator3D; - expr_0E.$PC = -2; - return expr_0E; + this.FailOnDespawnedNullOrForbidden(TargetIndex.A); + this.FailOnBurningImmobile(TargetIndex.A); + yield return Toils_Reserve.Reserve(TargetIndex.A, 1, -1, null); + yield return Toils_Goto.GotoThing(TargetIndex.A, PathEndMode.Touch); + yield return Toils_General.Wait(200).FailOnDestroyedNullOrForbidden(TargetIndex.A).FailOnCannotTouch(TargetIndex.A, PathEndMode.Touch).FailOn((Func)(() => !((_003CMakeNewToils_003Ec__Iterator3D)/*Error near IL_00ab: stateMachine*/)._003C_003Ef__this.Barrel.Fermented)).WithProgressBarToilDelay(TargetIndex.A, false, -0.5f); + yield return new Toil + { + initAction = (Action)delegate + { + Thing thing = ((_003CMakeNewToils_003Ec__Iterator3D)/*Error near IL_00ea: stateMachine*/)._003C_003Ef__this.Barrel.TakeOutBeer(); + GenPlace.TryPlaceThing(thing, ((_003CMakeNewToils_003Ec__Iterator3D)/*Error near IL_00ea: stateMachine*/)._003C_003Ef__this.pawn.Position, ((_003CMakeNewToils_003Ec__Iterator3D)/*Error near IL_00ea: stateMachine*/)._003C_003Ef__this.Map, ThingPlaceMode.Near, null); + StoragePriority currentPriority = HaulAIUtility.StoragePriorityAtFor(thing.Position, thing); + IntVec3 c = default(IntVec3); + if (StoreUtility.TryFindBestBetterStoreCellFor(thing, ((_003CMakeNewToils_003Ec__Iterator3D)/*Error near IL_00ea: stateMachine*/)._003C_003Ef__this.pawn, ((_003CMakeNewToils_003Ec__Iterator3D)/*Error near IL_00ea: stateMachine*/)._003C_003Ef__this.Map, currentPriority, ((_003CMakeNewToils_003Ec__Iterator3D)/*Error near IL_00ea: stateMachine*/)._003C_003Ef__this.pawn.Faction, out c, true)) + { + ((_003CMakeNewToils_003Ec__Iterator3D)/*Error near IL_00ea: stateMachine*/)._003C_003Ef__this.CurJob.SetTarget(TargetIndex.C, c); + ((_003CMakeNewToils_003Ec__Iterator3D)/*Error near IL_00ea: stateMachine*/)._003C_003Ef__this.CurJob.SetTarget(TargetIndex.B, thing); + ((_003CMakeNewToils_003Ec__Iterator3D)/*Error near IL_00ea: stateMachine*/)._003C_003Ef__this.CurJob.count = thing.stackCount; + } + else + { + ((_003CMakeNewToils_003Ec__Iterator3D)/*Error near IL_00ea: stateMachine*/)._003C_003Ef__this.EndJobWith(JobCondition.Incompletable); + } + }, + defaultCompleteMode = ToilCompleteMode.Instant + }; + yield return Toils_Reserve.Reserve(TargetIndex.B, 1, -1, null); + yield return Toils_Reserve.Reserve(TargetIndex.C, 1, -1, null); + yield return Toils_Goto.GotoThing(TargetIndex.B, PathEndMode.ClosestTouch); + yield return Toils_Haul.StartCarryThing(TargetIndex.B, false, false); + Toil carryToCell = Toils_Haul.CarryHauledThingToCell(TargetIndex.C); + yield return carryToCell; + yield return Toils_Haul.PlaceHauledThingInCell(TargetIndex.C, carryToCell, true); } } } diff --git a/Assembly-CSharp/RimWorld/JobDriver_TakeToBed.cs b/Assembly-CSharp/RimWorld/JobDriver_TakeToBed.cs index 3d0add1ce..d6ba30fa2 100644 --- a/Assembly-CSharp/RimWorld/JobDriver_TakeToBed.cs +++ b/Assembly-CSharp/RimWorld/JobDriver_TakeToBed.cs @@ -1,8 +1,8 @@ using System; using System.Collections.Generic; -using System.Diagnostics; using Verse; using Verse.AI; +using Verse.AI.Group; namespace RimWorld { @@ -28,14 +28,95 @@ protected Building_Bed DropBed } } - [DebuggerHidden] protected override IEnumerable MakeNewToils() { - JobDriver_TakeToBed.c__Iterator3E c__Iterator3E = new JobDriver_TakeToBed.c__Iterator3E(); - c__Iterator3E.<>f__this = this; - JobDriver_TakeToBed.c__Iterator3E expr_0E = c__Iterator3E; - expr_0E.$PC = -2; - return expr_0E; + this.FailOnDestroyedOrNull(TargetIndex.A); + this.FailOnDestroyedOrNull(TargetIndex.B); + this.FailOnAggroMentalState(TargetIndex.A); + this.FailOn((Func)delegate + { + if (((_003CMakeNewToils_003Ec__Iterator3E)/*Error near IL_0072: stateMachine*/)._003C_003Ef__this.CurJob.def.makeTargetPrisoner) + { + if (!((_003CMakeNewToils_003Ec__Iterator3E)/*Error near IL_0072: stateMachine*/)._003C_003Ef__this.DropBed.ForPrisoners) + { + return true; + } + } + else if (((_003CMakeNewToils_003Ec__Iterator3E)/*Error near IL_0072: stateMachine*/)._003C_003Ef__this.DropBed.ForPrisoners != ((_003CMakeNewToils_003Ec__Iterator3E)/*Error near IL_0072: stateMachine*/)._003C_003Ef__this.Takee.IsPrisoner) + { + return true; + } + return false; + }); + yield return Toils_Reserve.Reserve(TargetIndex.A, 1, -1, null); + yield return Toils_Reserve.Reserve(TargetIndex.B, this.DropBed.SleepingSlotsCount, 0, null); + yield return Toils_Bed.ClaimBedIfNonMedical(TargetIndex.B, TargetIndex.A); + base.AddFinishAction((Action)delegate + { + if (((_003CMakeNewToils_003Ec__Iterator3E)/*Error near IL_00e8: stateMachine*/)._003C_003Ef__this.CurJob.def.makeTargetPrisoner && ((_003CMakeNewToils_003Ec__Iterator3E)/*Error near IL_00e8: stateMachine*/)._003C_003Ef__this.Takee.ownership.OwnedBed == ((_003CMakeNewToils_003Ec__Iterator3E)/*Error near IL_00e8: stateMachine*/)._003C_003Ef__this.DropBed && ((_003CMakeNewToils_003Ec__Iterator3E)/*Error near IL_00e8: stateMachine*/)._003C_003Ef__this.Takee.Position != RestUtility.GetBedSleepingSlotPosFor(((_003CMakeNewToils_003Ec__Iterator3E)/*Error near IL_00e8: stateMachine*/)._003C_003Ef__this.Takee, ((_003CMakeNewToils_003Ec__Iterator3E)/*Error near IL_00e8: stateMachine*/)._003C_003Ef__this.DropBed)) + { + ((_003CMakeNewToils_003Ec__Iterator3E)/*Error near IL_00e8: stateMachine*/)._003C_003Ef__this.Takee.ownership.UnclaimBed(); + } + }); + yield return Toils_Goto.GotoThing(TargetIndex.A, PathEndMode.ClosestTouch).FailOnDespawnedNullOrForbidden(TargetIndex.A).FailOnDespawnedNullOrForbidden(TargetIndex.B).FailOnNonMedicalBedNotOwned(TargetIndex.B, TargetIndex.A).FailOn((Func)(() => ((_003CMakeNewToils_003Ec__Iterator3E)/*Error near IL_0114: stateMachine*/)._003C_003Ef__this.CurJob.def == JobDefOf.Arrest && !((_003CMakeNewToils_003Ec__Iterator3E)/*Error near IL_0114: stateMachine*/)._003C_003Ef__this.Takee.CanBeArrested())).FailOn((Func)(() => !((_003CMakeNewToils_003Ec__Iterator3E)/*Error near IL_0125: stateMachine*/)._003C_003Ef__this.pawn.CanReach((Thing)((_003CMakeNewToils_003Ec__Iterator3E)/*Error near IL_0125: stateMachine*/)._003C_003Ef__this.DropBed, PathEndMode.OnCell, Danger.Deadly, false, TraverseMode.ByPawn))).FailOn((Func)(() => ((_003CMakeNewToils_003Ec__Iterator3E)/*Error near IL_0136: stateMachine*/)._003C_003Ef__this.CurJob.def == JobDefOf.Rescue && !((_003CMakeNewToils_003Ec__Iterator3E)/*Error near IL_0136: stateMachine*/)._003C_003Ef__this.Takee.Downed)).FailOnSomeonePhysicallyInteracting(TargetIndex.A); + yield return new Toil + { + initAction = (Action)delegate + { + if (((_003CMakeNewToils_003Ec__Iterator3E)/*Error near IL_016f: stateMachine*/)._003C_003Ef__this.CurJob.def.makeTargetPrisoner) + { + Pawn pawn = (Pawn)((_003CMakeNewToils_003Ec__Iterator3E)/*Error near IL_016f: stateMachine*/)._003C_003Ef__this.CurJob.targetA.Thing; + Lord lord = pawn.GetLord(); + if (lord != null) + { + lord.Notify_PawnAttemptArrested(pawn); + } + GenClamor.DoClamor(pawn, 10f, ClamorType.Harm); + if (((_003CMakeNewToils_003Ec__Iterator3E)/*Error near IL_016f: stateMachine*/)._003C_003Ef__this.CurJob.def == JobDefOf.Arrest && !pawn.CheckAcceptArrest(((_003CMakeNewToils_003Ec__Iterator3E)/*Error near IL_016f: stateMachine*/)._003C_003Ef__this.pawn)) + { + ((_003CMakeNewToils_003Ec__Iterator3E)/*Error near IL_016f: stateMachine*/)._003C_003Ef__this.pawn.jobs.EndCurrentJob(JobCondition.Incompletable, true); + } + } + } + }; + Toil startCarrying = Toils_Haul.StartCarryThing(TargetIndex.A, false, false); + startCarrying.AddPreInitAction(new Action(this.CheckMakeTakeeGuest)); + yield return startCarrying; + yield return Toils_Goto.GotoThing(TargetIndex.B, PathEndMode.Touch); + yield return new Toil + { + initAction = (Action)delegate + { + ((_003CMakeNewToils_003Ec__Iterator3E)/*Error near IL_0204: stateMachine*/)._003C_003Ef__this.CheckMakeTakeePrisoner(); + if (((_003CMakeNewToils_003Ec__Iterator3E)/*Error near IL_0204: stateMachine*/)._003C_003Ef__this.Takee.playerSettings == null) + { + ((_003CMakeNewToils_003Ec__Iterator3E)/*Error near IL_0204: stateMachine*/)._003C_003Ef__this.Takee.playerSettings = new Pawn_PlayerSettings(((_003CMakeNewToils_003Ec__Iterator3E)/*Error near IL_0204: stateMachine*/)._003C_003Ef__this.Takee); + } + } + }; + yield return Toils_Reserve.Release(TargetIndex.B); + yield return new Toil + { + initAction = (Action)delegate + { + IntVec3 position = ((_003CMakeNewToils_003Ec__Iterator3E)/*Error near IL_0257: stateMachine*/)._003C_003Ef__this.DropBed.Position; + Thing thing = default(Thing); + ((_003CMakeNewToils_003Ec__Iterator3E)/*Error near IL_0257: stateMachine*/)._003C_003Ef__this.pawn.carryTracker.TryDropCarriedThing(position, ThingPlaceMode.Direct, out thing, (Action)null); + if (!((_003CMakeNewToils_003Ec__Iterator3E)/*Error near IL_0257: stateMachine*/)._003C_003Ef__this.DropBed.Destroyed && (((_003CMakeNewToils_003Ec__Iterator3E)/*Error near IL_0257: stateMachine*/)._003C_003Ef__this.DropBed.owners.Contains(((_003CMakeNewToils_003Ec__Iterator3E)/*Error near IL_0257: stateMachine*/)._003C_003Ef__this.Takee) || (((_003CMakeNewToils_003Ec__Iterator3E)/*Error near IL_0257: stateMachine*/)._003C_003Ef__this.DropBed.Medical && ((_003CMakeNewToils_003Ec__Iterator3E)/*Error near IL_0257: stateMachine*/)._003C_003Ef__this.DropBed.AnyUnoccupiedSleepingSlot) || ((_003CMakeNewToils_003Ec__Iterator3E)/*Error near IL_0257: stateMachine*/)._003C_003Ef__this.Takee.ownership == null)) + { + ((_003CMakeNewToils_003Ec__Iterator3E)/*Error near IL_0257: stateMachine*/)._003C_003Ef__this.Takee.jobs.Notify_TuckedIntoBed(((_003CMakeNewToils_003Ec__Iterator3E)/*Error near IL_0257: stateMachine*/)._003C_003Ef__this.DropBed); + if (((_003CMakeNewToils_003Ec__Iterator3E)/*Error near IL_0257: stateMachine*/)._003C_003Ef__this.Takee.RaceProps.Humanlike && ((_003CMakeNewToils_003Ec__Iterator3E)/*Error near IL_0257: stateMachine*/)._003C_003Ef__this.CurJob.def != JobDefOf.Arrest && !((_003CMakeNewToils_003Ec__Iterator3E)/*Error near IL_0257: stateMachine*/)._003C_003Ef__this.Takee.IsPrisonerOfColony) + { + ((_003CMakeNewToils_003Ec__Iterator3E)/*Error near IL_0257: stateMachine*/)._003C_003Ef__this.Takee.relations.Notify_RescuedBy(((_003CMakeNewToils_003Ec__Iterator3E)/*Error near IL_0257: stateMachine*/)._003C_003Ef__this.pawn); + } + } + if (((_003CMakeNewToils_003Ec__Iterator3E)/*Error near IL_0257: stateMachine*/)._003C_003Ef__this.Takee.IsPrisonerOfColony) + { + LessonAutoActivator.TeachOpportunity(ConceptDefOf.PrisonerTab, ((_003CMakeNewToils_003Ec__Iterator3E)/*Error near IL_0257: stateMachine*/)._003C_003Ef__this.Takee, OpportunityType.GoodToKnow); + } + }, + defaultCompleteMode = ToilCompleteMode.Instant + }; } private void CheckMakeTakeePrisoner() @@ -51,17 +132,13 @@ private void CheckMakeTakeePrisoner() { if (this.Takee.Faction != null) { - this.Takee.Faction.Notify_MemberCaptured(this.Takee, this.pawn.Faction); + this.Takee.Faction.Notify_MemberCaptured(this.Takee, base.pawn.Faction); } this.Takee.guest.SetGuestStatus(Faction.OfPlayer, true); if (this.Takee.guest.IsPrisoner) { - TaleRecorder.RecordTale(TaleDefOf.Captured, new object[] - { - this.pawn, - this.Takee - }); - this.pawn.records.Increment(RecordDefOf.PeopleCaptured); + TaleRecorder.RecordTale(TaleDefOf.Captured, base.pawn, this.Takee); + base.pawn.records.Increment(RecordDefOf.PeopleCaptured); } } } diff --git a/Assembly-CSharp/RimWorld/JobDriver_Tame.cs b/Assembly-CSharp/RimWorld/JobDriver_Tame.cs index 27c85530b..6a5a6ebc9 100644 --- a/Assembly-CSharp/RimWorld/JobDriver_Tame.cs +++ b/Assembly-CSharp/RimWorld/JobDriver_Tame.cs @@ -1,4 +1,3 @@ -using System; using Verse.AI; namespace RimWorld diff --git a/Assembly-CSharp/RimWorld/JobDriver_TendPatient.cs b/Assembly-CSharp/RimWorld/JobDriver_TendPatient.cs index 4766caab9..ab2e66c14 100644 --- a/Assembly-CSharp/RimWorld/JobDriver_TendPatient.cs +++ b/Assembly-CSharp/RimWorld/JobDriver_TendPatient.cs @@ -1,6 +1,5 @@ using System; using System.Collections.Generic; -using System.Diagnostics; using Verse; using Verse.AI; @@ -40,14 +39,75 @@ public override void Notify_Starting() this.usesMedicine = (this.MedicineUsed != null); } - [DebuggerHidden] protected override IEnumerable MakeNewToils() { - JobDriver_TendPatient.c__Iterator19 c__Iterator = new JobDriver_TendPatient.c__Iterator19(); - c__Iterator.<>f__this = this; - JobDriver_TendPatient.c__Iterator19 expr_0E = c__Iterator; - expr_0E.$PC = -2; - return expr_0E; + this.FailOnDespawnedNullOrForbidden(TargetIndex.A); + this.FailOn((Func)delegate + { + if (!WorkGiver_Tend.GoodLayingStatusForTend(((_003CMakeNewToils_003Ec__Iterator19)/*Error near IL_0058: stateMachine*/)._003C_003Ef__this.Deliveree, ((_003CMakeNewToils_003Ec__Iterator19)/*Error near IL_0058: stateMachine*/)._003C_003Ef__this.pawn)) + { + return true; + } + if (((_003CMakeNewToils_003Ec__Iterator19)/*Error near IL_0058: stateMachine*/)._003C_003Ef__this.MedicineUsed != null) + { + if (((_003CMakeNewToils_003Ec__Iterator19)/*Error near IL_0058: stateMachine*/)._003C_003Ef__this.Deliveree.playerSettings == null) + { + return true; + } + if (!((_003CMakeNewToils_003Ec__Iterator19)/*Error near IL_0058: stateMachine*/)._003C_003Ef__this.Deliveree.playerSettings.medCare.AllowsMedicine(((_003CMakeNewToils_003Ec__Iterator19)/*Error near IL_0058: stateMachine*/)._003C_003Ef__this.MedicineUsed.def)) + { + return true; + } + } + if (((_003CMakeNewToils_003Ec__Iterator19)/*Error near IL_0058: stateMachine*/)._003C_003Ef__this.pawn == ((_003CMakeNewToils_003Ec__Iterator19)/*Error near IL_0058: stateMachine*/)._003C_003Ef__this.Deliveree && (((_003CMakeNewToils_003Ec__Iterator19)/*Error near IL_0058: stateMachine*/)._003C_003Ef__this.pawn.playerSettings == null || !((_003CMakeNewToils_003Ec__Iterator19)/*Error near IL_0058: stateMachine*/)._003C_003Ef__this.pawn.playerSettings.selfTend)) + { + return true; + } + return false; + }); + this.AddEndCondition((Func)delegate + { + if (HealthAIUtility.ShouldBeTendedNow(((_003CMakeNewToils_003Ec__Iterator19)/*Error near IL_0070: stateMachine*/)._003C_003Ef__this.Deliveree)) + { + return JobCondition.Ongoing; + } + return JobCondition.Succeeded; + }); + this.FailOnAggroMentalState(TargetIndex.A); + yield return Toils_Reserve.Reserve(TargetIndex.A, 1, -1, null); + if (this.usesMedicine) + { + Toil reserveMedicine = Toils_Reserve.Reserve(TargetIndex.B, 1, -1, null).FailOnDespawnedNullOrForbidden(TargetIndex.B); + yield return reserveMedicine; + yield return Toils_Goto.GotoThing(TargetIndex.B, PathEndMode.ClosestTouch).FailOnDespawnedNullOrForbidden(TargetIndex.B); + yield return Toils_Tend.PickupMedicine(TargetIndex.B, this.Deliveree).FailOnDestroyedOrNull(TargetIndex.B); + yield return Toils_Haul.CheckForGetOpportunityDuplicate(reserveMedicine, TargetIndex.B, TargetIndex.None, true, null); + } + PathEndMode interactionCell = (PathEndMode)((this.Deliveree == base.pawn) ? 1 : 4); + Toil gotoToil = Toils_Goto.GotoThing(TargetIndex.A, interactionCell); + yield return gotoToil; + int duration = (int)(1.0 / base.pawn.GetStatValue(StatDefOf.MedicalTendSpeed, true) * 600.0); + yield return Toils_General.Wait(duration).FailOnCannotTouch(TargetIndex.A, interactionCell).WithProgressBarToilDelay(TargetIndex.A, false, -0.5f).PlaySustainerOrSound(SoundDefOf.Interact_Tend); + yield return Toils_Tend.FinalizeTend(this.Deliveree); + if (this.usesMedicine) + { + yield return new Toil + { + initAction = (Action)delegate + { + if (((_003CMakeNewToils_003Ec__Iterator19)/*Error near IL_0253: stateMachine*/)._003C_003Ef__this.MedicineUsed.DestroyedOrNull() && Medicine.GetMedicineCountToFullyHeal(((_003CMakeNewToils_003Ec__Iterator19)/*Error near IL_0253: stateMachine*/)._003C_003Ef__this.Deliveree) > 0) + { + Thing thing = HealthAIUtility.FindBestMedicine(((_003CMakeNewToils_003Ec__Iterator19)/*Error near IL_0253: stateMachine*/)._003C_003Ef__this.pawn, ((_003CMakeNewToils_003Ec__Iterator19)/*Error near IL_0253: stateMachine*/)._003C_003Ef__this.Deliveree); + if (thing != null) + { + ((_003CMakeNewToils_003Ec__Iterator19)/*Error near IL_0253: stateMachine*/)._003C_003Ef__this.CurJob.targetB = thing; + ((_003CMakeNewToils_003Ec__Iterator19)/*Error near IL_0253: stateMachine*/)._003C_003Ef__this.JumpToToil(((_003CMakeNewToils_003Ec__Iterator19)/*Error near IL_0253: stateMachine*/)._003CreserveMedicine_003E__0); + } + } + } + }; + } + yield return Toils_Jump.Jump(gotoToil); } } } diff --git a/Assembly-CSharp/RimWorld/JobDriver_TradeWithPawn.cs b/Assembly-CSharp/RimWorld/JobDriver_TradeWithPawn.cs index 49881adb8..16bf2f85e 100644 --- a/Assembly-CSharp/RimWorld/JobDriver_TradeWithPawn.cs +++ b/Assembly-CSharp/RimWorld/JobDriver_TradeWithPawn.cs @@ -1,6 +1,5 @@ using System; using System.Collections.Generic; -using System.Diagnostics; using Verse; using Verse.AI; @@ -16,14 +15,22 @@ private Pawn Trader } } - [DebuggerHidden] protected override IEnumerable MakeNewToils() { - JobDriver_TradeWithPawn.c__Iterator3F c__Iterator3F = new JobDriver_TradeWithPawn.c__Iterator3F(); - c__Iterator3F.<>f__this = this; - JobDriver_TradeWithPawn.c__Iterator3F expr_0E = c__Iterator3F; - expr_0E.$PC = -2; - return expr_0E; + this.FailOnDespawnedOrNull(TargetIndex.A); + yield return Toils_Reserve.Reserve(TargetIndex.A, 1, -1, null); + yield return Toils_Goto.GotoThing(TargetIndex.A, PathEndMode.Touch).FailOn((Func)(() => !((_003CMakeNewToils_003Ec__Iterator3F)/*Error near IL_0059: stateMachine*/)._003C_003Ef__this.Trader.CanTradeNow)); + yield return new Toil + { + initAction = (Action)delegate + { + Pawn actor = ((_003CMakeNewToils_003Ec__Iterator3F)/*Error near IL_008c: stateMachine*/)._003Ctrade_003E__0.actor; + if (((_003CMakeNewToils_003Ec__Iterator3F)/*Error near IL_008c: stateMachine*/)._003C_003Ef__this.Trader.CanTradeNow) + { + Find.WindowStack.Add(new Dialog_Trade(actor, ((_003CMakeNewToils_003Ec__Iterator3F)/*Error near IL_008c: stateMachine*/)._003C_003Ef__this.Trader)); + } + } + }; } } } diff --git a/Assembly-CSharp/RimWorld/JobDriver_Train.cs b/Assembly-CSharp/RimWorld/JobDriver_Train.cs index 2f3ae6d9b..ac60bfe86 100644 --- a/Assembly-CSharp/RimWorld/JobDriver_Train.cs +++ b/Assembly-CSharp/RimWorld/JobDriver_Train.cs @@ -1,4 +1,3 @@ -using System; using Verse.AI; namespace RimWorld diff --git a/Assembly-CSharp/RimWorld/JobDriver_Uninstall.cs b/Assembly-CSharp/RimWorld/JobDriver_Uninstall.cs index 3939ada57..f1a0625a9 100644 --- a/Assembly-CSharp/RimWorld/JobDriver_Uninstall.cs +++ b/Assembly-CSharp/RimWorld/JobDriver_Uninstall.cs @@ -1,4 +1,3 @@ -using System; using Verse; namespace RimWorld @@ -26,7 +25,7 @@ protected override int TotalNeededWork protected override void FinishedRemoving() { base.Building.Uninstall(); - this.pawn.records.Increment(RecordDefOf.ThingsUninstalled); + base.pawn.records.Increment(RecordDefOf.ThingsUninstalled); } } } diff --git a/Assembly-CSharp/RimWorld/JobDriver_UnloadInventory.cs b/Assembly-CSharp/RimWorld/JobDriver_UnloadInventory.cs index b91a8a43d..b22a10e87 100644 --- a/Assembly-CSharp/RimWorld/JobDriver_UnloadInventory.cs +++ b/Assembly-CSharp/RimWorld/JobDriver_UnloadInventory.cs @@ -1,6 +1,5 @@ using System; using System.Collections.Generic; -using System.Diagnostics; using Verse; using Verse.AI; @@ -24,14 +23,51 @@ private Pawn OtherPawn } } - [DebuggerHidden] protected override IEnumerable MakeNewToils() { - JobDriver_UnloadInventory.c__Iterator40 c__Iterator = new JobDriver_UnloadInventory.c__Iterator40(); - c__Iterator.<>f__this = this; - JobDriver_UnloadInventory.c__Iterator40 expr_0E = c__Iterator; - expr_0E.$PC = -2; - return expr_0E; + this.FailOnDespawnedOrNull(TargetIndex.A); + yield return Toils_Reserve.Reserve(TargetIndex.A, 1, -1, null); + yield return Toils_Goto.GotoThing(TargetIndex.A, PathEndMode.Touch); + yield return Toils_General.Wait(10); + yield return new Toil + { + initAction = (Action)delegate + { + Pawn otherPawn = ((_003CMakeNewToils_003Ec__Iterator40)/*Error near IL_00a4: stateMachine*/)._003C_003Ef__this.OtherPawn; + if (!otherPawn.inventory.UnloadEverything) + { + ((_003CMakeNewToils_003Ec__Iterator40)/*Error near IL_00a4: stateMachine*/)._003C_003Ef__this.EndJobWith(JobCondition.Succeeded); + } + else + { + ThingStackPart firstUnloadableThing = otherPawn.inventory.FirstUnloadableThing; + IntVec3 c = default(IntVec3); + if (!firstUnloadableThing.Thing.def.EverStoreable || !((_003CMakeNewToils_003Ec__Iterator40)/*Error near IL_00a4: stateMachine*/)._003C_003Ef__this.pawn.health.capacities.CapableOf(PawnCapacityDefOf.Manipulation) || !StoreUtility.TryFindStoreCellNearColonyDesperate(firstUnloadableThing.Thing, ((_003CMakeNewToils_003Ec__Iterator40)/*Error near IL_00a4: stateMachine*/)._003C_003Ef__this.pawn, out c)) + { + Thing thing = default(Thing); + ((ThingOwner)otherPawn.inventory.innerContainer).TryDrop(firstUnloadableThing.Thing, ThingPlaceMode.Near, firstUnloadableThing.Count, out thing, (Action)null); + ((_003CMakeNewToils_003Ec__Iterator40)/*Error near IL_00a4: stateMachine*/)._003C_003Ef__this.EndJobWith(JobCondition.Succeeded); + if (thing != null) + { + thing.SetForbidden(false, false); + } + } + else + { + Thing thing2 = default(Thing); + otherPawn.inventory.innerContainer.TryTransferToContainer(firstUnloadableThing.Thing, (ThingOwner)((_003CMakeNewToils_003Ec__Iterator40)/*Error near IL_00a4: stateMachine*/)._003C_003Ef__this.pawn.carryTracker.innerContainer, firstUnloadableThing.Count, out thing2, true); + ((_003CMakeNewToils_003Ec__Iterator40)/*Error near IL_00a4: stateMachine*/)._003C_003Ef__this.CurJob.count = thing2.stackCount; + ((_003CMakeNewToils_003Ec__Iterator40)/*Error near IL_00a4: stateMachine*/)._003C_003Ef__this.CurJob.SetTarget(TargetIndex.B, thing2); + ((_003CMakeNewToils_003Ec__Iterator40)/*Error near IL_00a4: stateMachine*/)._003C_003Ef__this.CurJob.SetTarget(TargetIndex.C, c); + firstUnloadableThing.Thing.SetForbidden(false, false); + } + } + } + }; + yield return Toils_Reserve.Reserve(TargetIndex.C, 1, -1, null); + Toil carryToCell = Toils_Haul.CarryHauledThingToCell(TargetIndex.C); + yield return carryToCell; + yield return Toils_Haul.PlaceHauledThingInCell(TargetIndex.C, carryToCell, true); } } } diff --git a/Assembly-CSharp/RimWorld/JobDriver_UnloadYourInventory.cs b/Assembly-CSharp/RimWorld/JobDriver_UnloadYourInventory.cs index f5267147f..3fdbbbd54 100644 --- a/Assembly-CSharp/RimWorld/JobDriver_UnloadYourInventory.cs +++ b/Assembly-CSharp/RimWorld/JobDriver_UnloadYourInventory.cs @@ -1,6 +1,5 @@ using System; using System.Collections.Generic; -using System.Diagnostics; using Verse; using Verse.AI; @@ -22,14 +21,67 @@ public override void ExposeData() Scribe_Values.Look(ref this.countToDrop, "countToDrop", -1, false); } - [DebuggerHidden] protected override IEnumerable MakeNewToils() { - JobDriver_UnloadYourInventory.c__Iterator41 c__Iterator = new JobDriver_UnloadYourInventory.c__Iterator41(); - c__Iterator.<>f__this = this; - JobDriver_UnloadYourInventory.c__Iterator41 expr_0E = c__Iterator; - expr_0E.$PC = -2; - return expr_0E; + yield return Toils_General.Wait(10); + yield return new Toil + { + initAction = (Action)delegate + { + if (!((_003CMakeNewToils_003Ec__Iterator41)/*Error near IL_0063: stateMachine*/)._003C_003Ef__this.pawn.inventory.UnloadEverything) + { + ((_003CMakeNewToils_003Ec__Iterator41)/*Error near IL_0063: stateMachine*/)._003C_003Ef__this.EndJobWith(JobCondition.Succeeded); + } + else + { + ThingStackPart firstUnloadableThing = ((_003CMakeNewToils_003Ec__Iterator41)/*Error near IL_0063: stateMachine*/)._003C_003Ef__this.pawn.inventory.FirstUnloadableThing; + IntVec3 c = default(IntVec3); + if (!StoreUtility.TryFindStoreCellNearColonyDesperate(firstUnloadableThing.Thing, ((_003CMakeNewToils_003Ec__Iterator41)/*Error near IL_0063: stateMachine*/)._003C_003Ef__this.pawn, out c)) + { + Thing thing2 = default(Thing); + ((ThingOwner)((_003CMakeNewToils_003Ec__Iterator41)/*Error near IL_0063: stateMachine*/)._003C_003Ef__this.pawn.inventory.innerContainer).TryDrop(firstUnloadableThing.Thing, ThingPlaceMode.Near, firstUnloadableThing.Count, out thing2, (Action)null); + ((_003CMakeNewToils_003Ec__Iterator41)/*Error near IL_0063: stateMachine*/)._003C_003Ef__this.EndJobWith(JobCondition.Succeeded); + } + else + { + ((_003CMakeNewToils_003Ec__Iterator41)/*Error near IL_0063: stateMachine*/)._003C_003Ef__this.CurJob.SetTarget(TargetIndex.A, firstUnloadableThing.Thing); + ((_003CMakeNewToils_003Ec__Iterator41)/*Error near IL_0063: stateMachine*/)._003C_003Ef__this.CurJob.SetTarget(TargetIndex.B, c); + ((_003CMakeNewToils_003Ec__Iterator41)/*Error near IL_0063: stateMachine*/)._003C_003Ef__this.countToDrop = firstUnloadableThing.Count; + } + } + } + }; + yield return Toils_Reserve.Reserve(TargetIndex.B, 1, -1, null); + yield return Toils_Goto.GotoCell(TargetIndex.B, PathEndMode.Touch); + yield return new Toil + { + initAction = (Action)delegate + { + Thing thing = ((_003CMakeNewToils_003Ec__Iterator41)/*Error near IL_00d1: stateMachine*/)._003C_003Ef__this.CurJob.GetTarget(TargetIndex.A).Thing; + if (thing == null || !((_003CMakeNewToils_003Ec__Iterator41)/*Error near IL_00d1: stateMachine*/)._003C_003Ef__this.pawn.inventory.innerContainer.Contains(thing)) + { + ((_003CMakeNewToils_003Ec__Iterator41)/*Error near IL_00d1: stateMachine*/)._003C_003Ef__this.EndJobWith(JobCondition.Incompletable); + } + else + { + if (!((_003CMakeNewToils_003Ec__Iterator41)/*Error near IL_00d1: stateMachine*/)._003C_003Ef__this.pawn.health.capacities.CapableOf(PawnCapacityDefOf.Manipulation) || !thing.def.EverStoreable) + { + ((ThingOwner)((_003CMakeNewToils_003Ec__Iterator41)/*Error near IL_00d1: stateMachine*/)._003C_003Ef__this.pawn.inventory.innerContainer).TryDrop(thing, ThingPlaceMode.Near, ((_003CMakeNewToils_003Ec__Iterator41)/*Error near IL_00d1: stateMachine*/)._003C_003Ef__this.countToDrop, out thing, (Action)null); + ((_003CMakeNewToils_003Ec__Iterator41)/*Error near IL_00d1: stateMachine*/)._003C_003Ef__this.EndJobWith(JobCondition.Succeeded); + } + else + { + ((_003CMakeNewToils_003Ec__Iterator41)/*Error near IL_00d1: stateMachine*/)._003C_003Ef__this.pawn.inventory.innerContainer.TryTransferToContainer(thing, (ThingOwner)((_003CMakeNewToils_003Ec__Iterator41)/*Error near IL_00d1: stateMachine*/)._003C_003Ef__this.pawn.carryTracker.innerContainer, ((_003CMakeNewToils_003Ec__Iterator41)/*Error near IL_00d1: stateMachine*/)._003C_003Ef__this.countToDrop, out thing, true); + ((_003CMakeNewToils_003Ec__Iterator41)/*Error near IL_00d1: stateMachine*/)._003C_003Ef__this.CurJob.count = ((_003CMakeNewToils_003Ec__Iterator41)/*Error near IL_00d1: stateMachine*/)._003C_003Ef__this.countToDrop; + ((_003CMakeNewToils_003Ec__Iterator41)/*Error near IL_00d1: stateMachine*/)._003C_003Ef__this.CurJob.SetTarget(TargetIndex.A, thing); + } + thing.SetForbidden(false, false); + } + } + }; + Toil carryToCell = Toils_Haul.CarryHauledThingToCell(TargetIndex.B); + yield return carryToCell; + yield return Toils_Haul.PlaceHauledThingInCell(TargetIndex.B, carryToCell, true); } } } diff --git a/Assembly-CSharp/RimWorld/JobDriver_UseCommsConsole.cs b/Assembly-CSharp/RimWorld/JobDriver_UseCommsConsole.cs index 869a8a0b1..de7f898fa 100644 --- a/Assembly-CSharp/RimWorld/JobDriver_UseCommsConsole.cs +++ b/Assembly-CSharp/RimWorld/JobDriver_UseCommsConsole.cs @@ -1,19 +1,32 @@ using System; using System.Collections.Generic; -using System.Diagnostics; +using Verse; using Verse.AI; namespace RimWorld { public class JobDriver_UseCommsConsole : JobDriver { - [DebuggerHidden] protected override IEnumerable MakeNewToils() { - JobDriver_UseCommsConsole.c__Iterator42 c__Iterator = new JobDriver_UseCommsConsole.c__Iterator42(); - JobDriver_UseCommsConsole.c__Iterator42 expr_07 = c__Iterator; - expr_07.$PC = -2; - return expr_07; + yield return Toils_Reserve.Reserve(TargetIndex.A, 1, -1, null); + yield return Toils_Goto.GotoCell(TargetIndex.A, PathEndMode.InteractionCell).FailOn((Func)delegate(Toil to) + { + Building_CommsConsole building_CommsConsole2 = (Building_CommsConsole)to.actor.jobs.curJob.GetTarget(TargetIndex.A).Thing; + return !building_CommsConsole2.CanUseCommsNow; + }); + yield return new Toil + { + initAction = (Action)delegate + { + Pawn actor = ((_003CMakeNewToils_003Ec__Iterator42)/*Error near IL_0090: stateMachine*/)._003CopenComms_003E__0.actor; + Building_CommsConsole building_CommsConsole = (Building_CommsConsole)actor.jobs.curJob.GetTarget(TargetIndex.A).Thing; + if (building_CommsConsole.CanUseCommsNow) + { + actor.jobs.curJob.commTarget.TryOpenComms(actor); + } + } + }; } } } diff --git a/Assembly-CSharp/RimWorld/JobDriver_UseItem.cs b/Assembly-CSharp/RimWorld/JobDriver_UseItem.cs index 704762a3e..330cd98fe 100644 --- a/Assembly-CSharp/RimWorld/JobDriver_UseItem.cs +++ b/Assembly-CSharp/RimWorld/JobDriver_UseItem.cs @@ -1,19 +1,31 @@ using System; using System.Collections.Generic; -using System.Diagnostics; +using Verse; using Verse.AI; namespace RimWorld { public class JobDriver_UseItem : JobDriver { - [DebuggerHidden] protected override IEnumerable MakeNewToils() { - JobDriver_UseItem.c__Iterator43 c__Iterator = new JobDriver_UseItem.c__Iterator43(); - JobDriver_UseItem.c__Iterator43 expr_07 = c__Iterator; - expr_07.$PC = -2; - return expr_07; + yield return Toils_Reserve.Reserve(TargetIndex.A, 1, -1, null); + yield return Toils_Goto.GotoThing(TargetIndex.A, PathEndMode.Touch); + Toil prepare = Toils_General.Wait(100); + prepare.WithProgressBarToilDelay(TargetIndex.A, false, -0.5f); + prepare.FailOnDespawnedNullOrForbidden(TargetIndex.A); + prepare.FailOnCannotTouch(TargetIndex.A, PathEndMode.Touch); + yield return prepare; + yield return new Toil + { + initAction = (Action)delegate + { + Pawn actor = ((_003CMakeNewToils_003Ec__Iterator43)/*Error near IL_00c5: stateMachine*/)._003Cuse_003E__1.actor; + CompUsable compUsable = actor.CurJob.targetA.Thing.TryGetComp(); + compUsable.UsedBy(actor); + }, + defaultCompleteMode = ToilCompleteMode.Instant + }; } } } diff --git a/Assembly-CSharp/RimWorld/JobDriver_ViewArt.cs b/Assembly-CSharp/RimWorld/JobDriver_ViewArt.cs index 0c44b29c4..d3f8cf875 100644 --- a/Assembly-CSharp/RimWorld/JobDriver_ViewArt.cs +++ b/Assembly-CSharp/RimWorld/JobDriver_ViewArt.cs @@ -16,14 +16,14 @@ private Thing ArtThing protected override Action GetWaitTickAction() { - return delegate + return (Action)delegate { - float num = this.ArtThing.GetStatValue(StatDefOf.EntertainmentStrengthFactor, true); - float num2 = this.ArtThing.GetStatValue(StatDefOf.Beauty, true) / this.ArtThing.def.GetStatValueAbstract(StatDefOf.Beauty, null); - num *= ((num2 <= 0f) ? 0f : num2); - this.pawn.GainComfortFromCellIfPossible(); - float extraJoyGainFactor = num; - JoyUtility.JoyTickCheckEnd(this.pawn, JoyTickFullJoyAction.EndJob, extraJoyGainFactor); + float statValue = this.ArtThing.GetStatValue(StatDefOf.EntertainmentStrengthFactor, true); + float num = this.ArtThing.GetStatValue(StatDefOf.Beauty, true) / this.ArtThing.def.GetStatValueAbstract(StatDefOf.Beauty, null); + statValue = (float)(statValue * ((!(num > 0.0)) ? 0.0 : num)); + base.pawn.GainComfortFromCellIfPossible(); + float extraJoyGainFactor = statValue; + JoyUtility.JoyTickCheckEnd(base.pawn, JoyTickFullJoyAction.EndJob, extraJoyGainFactor); }; } } diff --git a/Assembly-CSharp/RimWorld/JobDriver_VisitGrave.cs b/Assembly-CSharp/RimWorld/JobDriver_VisitGrave.cs index 25a1a17d1..e008bafa3 100644 --- a/Assembly-CSharp/RimWorld/JobDriver_VisitGrave.cs +++ b/Assembly-CSharp/RimWorld/JobDriver_VisitGrave.cs @@ -16,17 +16,17 @@ private Building_Grave Grave protected override Action GetWaitTickAction() { - return delegate + return (Action)delegate { float num = this.Grave.GetStatValue(StatDefOf.EntertainmentStrengthFactor, true); - Room room = this.pawn.GetRoom(RegionType.Set_Passable); + Room room = base.pawn.GetRoom(RegionType.Set_Passable); if (room != null) { num *= room.GetStat(RoomStatDefOf.GraveVisitingJoyGainFactor); } - this.pawn.GainComfortFromCellIfPossible(); + base.pawn.GainComfortFromCellIfPossible(); float extraJoyGainFactor = num; - JoyUtility.JoyTickCheckEnd(this.pawn, JoyTickFullJoyAction.EndJob, extraJoyGainFactor); + JoyUtility.JoyTickCheckEnd(base.pawn, JoyTickFullJoyAction.EndJob, extraJoyGainFactor); }; } } diff --git a/Assembly-CSharp/RimWorld/JobDriver_VisitJoyThing.cs b/Assembly-CSharp/RimWorld/JobDriver_VisitJoyThing.cs index 2a0ff5adf..84debbf6a 100644 --- a/Assembly-CSharp/RimWorld/JobDriver_VisitJoyThing.cs +++ b/Assembly-CSharp/RimWorld/JobDriver_VisitJoyThing.cs @@ -1,6 +1,5 @@ using System; using System.Collections.Generic; -using System.Diagnostics; using Verse.AI; namespace RimWorld @@ -9,14 +8,15 @@ public abstract class JobDriver_VisitJoyThing : JobDriver { protected const TargetIndex TargetThingIndex = TargetIndex.A; - [DebuggerHidden] protected override IEnumerable MakeNewToils() { - JobDriver_VisitJoyThing.c__Iterator22 c__Iterator = new JobDriver_VisitJoyThing.c__Iterator22(); - c__Iterator.<>f__this = this; - JobDriver_VisitJoyThing.c__Iterator22 expr_0E = c__Iterator; - expr_0E.$PC = -2; - return expr_0E; + this.FailOnDestroyedNullOrForbidden(TargetIndex.A); + yield return Toils_Reserve.Reserve(TargetIndex.A, 1, -1, null); + yield return Toils_Goto.GotoThing(TargetIndex.A, PathEndMode.Touch); + Toil wait = Toils_General.Wait(base.CurJob.def.joyDuration); + wait.FailOnCannotTouch(TargetIndex.A, PathEndMode.Touch); + wait.tickAction = this.GetWaitTickAction(); + yield return wait; } protected abstract Action GetWaitTickAction(); diff --git a/Assembly-CSharp/RimWorld/JobDriver_VisitSickPawn.cs b/Assembly-CSharp/RimWorld/JobDriver_VisitSickPawn.cs index cc23bcdc2..de7301d52 100644 --- a/Assembly-CSharp/RimWorld/JobDriver_VisitSickPawn.cs +++ b/Assembly-CSharp/RimWorld/JobDriver_VisitSickPawn.cs @@ -1,6 +1,5 @@ using System; using System.Collections.Generic; -using System.Diagnostics; using Verse; using Verse.AI; @@ -28,14 +27,47 @@ private Thing Chair } } - [DebuggerHidden] protected override IEnumerable MakeNewToils() { - JobDriver_VisitSickPawn.c__Iterator23 c__Iterator = new JobDriver_VisitSickPawn.c__Iterator23(); - c__Iterator.<>f__this = this; - JobDriver_VisitSickPawn.c__Iterator23 expr_0E = c__Iterator; - expr_0E.$PC = -2; - return expr_0E; + this.FailOnDespawnedNullOrForbidden(TargetIndex.A); + this.FailOn((Func)(() => !((_003CMakeNewToils_003Ec__Iterator23)/*Error near IL_0048: stateMachine*/)._003C_003Ef__this.Patient.InBed() || !((_003CMakeNewToils_003Ec__Iterator23)/*Error near IL_0048: stateMachine*/)._003C_003Ef__this.Patient.Awake())); + if (this.Chair != null) + { + this.FailOnDespawnedNullOrForbidden(TargetIndex.B); + } + yield return Toils_Reserve.Reserve(TargetIndex.A, 1, -1, null); + if (this.Chair != null) + { + yield return Toils_Reserve.Reserve(TargetIndex.B, 1, -1, null); + yield return Toils_Goto.GotoThing(TargetIndex.B, PathEndMode.OnCell); + } + else + { + yield return Toils_Goto.GotoThing(TargetIndex.A, PathEndMode.InteractionCell); + } + yield return Toils_Interpersonal.WaitToBeAbleToInteract(base.pawn); + yield return new Toil + { + tickAction = (Action)delegate + { + ((_003CMakeNewToils_003Ec__Iterator23)/*Error near IL_0127: stateMachine*/)._003C_003Ef__this.Patient.needs.joy.GainJoy((float)(((_003CMakeNewToils_003Ec__Iterator23)/*Error near IL_0127: stateMachine*/)._003C_003Ef__this.CurJob.def.joyGainRate * 0.00014400000509340316), ((_003CMakeNewToils_003Ec__Iterator23)/*Error near IL_0127: stateMachine*/)._003C_003Ef__this.CurJob.def.joyKind); + if (((_003CMakeNewToils_003Ec__Iterator23)/*Error near IL_0127: stateMachine*/)._003C_003Ef__this.pawn.IsHashIntervalTick(320)) + { + InteractionDef intDef = (!(Rand.Value < 0.800000011920929)) ? InteractionDefOf.DeepTalk : InteractionDefOf.Chitchat; + ((_003CMakeNewToils_003Ec__Iterator23)/*Error near IL_0127: stateMachine*/)._003C_003Ef__this.pawn.interactions.TryInteractWith(((_003CMakeNewToils_003Ec__Iterator23)/*Error near IL_0127: stateMachine*/)._003C_003Ef__this.Patient, intDef); + } + ((_003CMakeNewToils_003Ec__Iterator23)/*Error near IL_0127: stateMachine*/)._003C_003Ef__this.pawn.Drawer.rotator.FaceCell(((_003CMakeNewToils_003Ec__Iterator23)/*Error near IL_0127: stateMachine*/)._003C_003Ef__this.Patient.Position); + ((_003CMakeNewToils_003Ec__Iterator23)/*Error near IL_0127: stateMachine*/)._003C_003Ef__this.pawn.GainComfortFromCellIfPossible(); + JoyUtility.JoyTickCheckEnd(((_003CMakeNewToils_003Ec__Iterator23)/*Error near IL_0127: stateMachine*/)._003C_003Ef__this.pawn, JoyTickFullJoyAction.None, 1f); + if (((_003CMakeNewToils_003Ec__Iterator23)/*Error near IL_0127: stateMachine*/)._003C_003Ef__this.pawn.needs.joy.CurLevelPercentage > 0.99989998340606689 && ((_003CMakeNewToils_003Ec__Iterator23)/*Error near IL_0127: stateMachine*/)._003C_003Ef__this.Patient.needs.joy.CurLevelPercentage > 0.99989998340606689) + { + ((_003CMakeNewToils_003Ec__Iterator23)/*Error near IL_0127: stateMachine*/)._003C_003Ef__this.pawn.jobs.EndCurrentJob(JobCondition.Succeeded, true); + } + }, + socialMode = RandomSocialMode.Off, + defaultCompleteMode = ToilCompleteMode.Delay, + defaultDuration = base.CurJob.def.joyDuration + }; } } } diff --git a/Assembly-CSharp/RimWorld/JobDriver_Vomit.cs b/Assembly-CSharp/RimWorld/JobDriver_Vomit.cs index 1f04a899d..58215d0af 100644 --- a/Assembly-CSharp/RimWorld/JobDriver_Vomit.cs +++ b/Assembly-CSharp/RimWorld/JobDriver_Vomit.cs @@ -1,6 +1,5 @@ using System; using System.Collections.Generic; -using System.Diagnostics; using Verse; using Verse.AI; @@ -23,7 +22,7 @@ public override PawnPosture Posture public override void Notify_LastPosture(PawnPosture posture, LayingDownState layingDown) { this.lastPosture = posture; - this.layingDown = layingDown; + base.layingDown = layingDown; } public override void ExposeData() @@ -33,14 +32,53 @@ public override void ExposeData() Scribe_Values.Look(ref this.lastPosture, "lastPosture", PawnPosture.Standing, false); } - [DebuggerHidden] protected override IEnumerable MakeNewToils() { - JobDriver_Vomit.c__Iterator44 c__Iterator = new JobDriver_Vomit.c__Iterator44(); - c__Iterator.<>f__this = this; - JobDriver_Vomit.c__Iterator44 expr_0E = c__Iterator; - expr_0E.$PC = -2; - return expr_0E; + Toil to = new Toil + { + initAction = (Action)delegate + { + ((_003CMakeNewToils_003Ec__Iterator44)/*Error near IL_0032: stateMachine*/)._003C_003Ef__this.ticksLeft = Rand.Range(300, 900); + int num = 0; + IntVec3 c; + while (true) + { + c = ((_003CMakeNewToils_003Ec__Iterator44)/*Error near IL_0032: stateMachine*/)._003C_003Ef__this.pawn.Position + GenAdj.AdjacentCellsAndInside[Rand.Range(0, 9)]; + num++; + if (num > 12) + { + c = ((_003CMakeNewToils_003Ec__Iterator44)/*Error near IL_0032: stateMachine*/)._003C_003Ef__this.pawn.Position; + break; + } + if (c.InBounds(((_003CMakeNewToils_003Ec__Iterator44)/*Error near IL_0032: stateMachine*/)._003C_003Ef__this.pawn.Map) && c.Standable(((_003CMakeNewToils_003Ec__Iterator44)/*Error near IL_0032: stateMachine*/)._003C_003Ef__this.pawn.Map)) + break; + } + ((_003CMakeNewToils_003Ec__Iterator44)/*Error near IL_0032: stateMachine*/)._003C_003Ef__this.pawn.CurJob.targetA = c; + ((_003CMakeNewToils_003Ec__Iterator44)/*Error near IL_0032: stateMachine*/)._003C_003Ef__this.pawn.Drawer.rotator.FaceCell(c); + ((_003CMakeNewToils_003Ec__Iterator44)/*Error near IL_0032: stateMachine*/)._003C_003Ef__this.pawn.pather.StopDead(); + }, + tickAction = (Action)delegate + { + if (((_003CMakeNewToils_003Ec__Iterator44)/*Error near IL_0049: stateMachine*/)._003C_003Ef__this.ticksLeft % 150 == 149) + { + FilthMaker.MakeFilth(((_003CMakeNewToils_003Ec__Iterator44)/*Error near IL_0049: stateMachine*/)._003C_003Ef__this.pawn.CurJob.targetA.Cell, ((_003CMakeNewToils_003Ec__Iterator44)/*Error near IL_0049: stateMachine*/)._003C_003Ef__this.Map, ThingDefOf.FilthVomit, ((_003CMakeNewToils_003Ec__Iterator44)/*Error near IL_0049: stateMachine*/)._003C_003Ef__this.pawn.LabelIndefinite(), 1); + if (((_003CMakeNewToils_003Ec__Iterator44)/*Error near IL_0049: stateMachine*/)._003C_003Ef__this.pawn.needs.food.CurLevelPercentage > 0.10000000149011612) + { + ((_003CMakeNewToils_003Ec__Iterator44)/*Error near IL_0049: stateMachine*/)._003C_003Ef__this.pawn.needs.food.CurLevel -= (float)(((_003CMakeNewToils_003Ec__Iterator44)/*Error near IL_0049: stateMachine*/)._003C_003Ef__this.pawn.needs.food.MaxLevel * 0.039999999105930328); + } + } + ((_003CMakeNewToils_003Ec__Iterator44)/*Error near IL_0049: stateMachine*/)._003C_003Ef__this.ticksLeft--; + if (((_003CMakeNewToils_003Ec__Iterator44)/*Error near IL_0049: stateMachine*/)._003C_003Ef__this.ticksLeft <= 0) + { + ((_003CMakeNewToils_003Ec__Iterator44)/*Error near IL_0049: stateMachine*/)._003C_003Ef__this.ReadyForNextToil(); + TaleRecorder.RecordTale(TaleDefOf.Vomited, ((_003CMakeNewToils_003Ec__Iterator44)/*Error near IL_0049: stateMachine*/)._003C_003Ef__this.pawn); + } + }, + defaultCompleteMode = ToilCompleteMode.Never + }; + to.WithEffect(EffecterDefOf.Vomit, TargetIndex.A); + to.PlaySustainerOrSound((Func)(() => SoundDef.Named("Vomit"))); + yield return to; } } } diff --git a/Assembly-CSharp/RimWorld/JobDriver_WatchBuilding.cs b/Assembly-CSharp/RimWorld/JobDriver_WatchBuilding.cs index acf8ba0e5..e3e384110 100644 --- a/Assembly-CSharp/RimWorld/JobDriver_WatchBuilding.cs +++ b/Assembly-CSharp/RimWorld/JobDriver_WatchBuilding.cs @@ -1,29 +1,55 @@ using System; using System.Collections.Generic; -using System.Diagnostics; using Verse.AI; namespace RimWorld { public class JobDriver_WatchBuilding : JobDriver { - [DebuggerHidden] protected override IEnumerable MakeNewToils() { - JobDriver_WatchBuilding.c__Iterator1D c__Iterator1D = new JobDriver_WatchBuilding.c__Iterator1D(); - c__Iterator1D.<>f__this = this; - JobDriver_WatchBuilding.c__Iterator1D expr_0E = c__Iterator1D; - expr_0E.$PC = -2; - return expr_0E; + this.EndOnDespawnedOrNull(TargetIndex.A, JobCondition.Incompletable); + yield return Toils_Reserve.Reserve(TargetIndex.A, base.CurJob.def.joyMaxParticipants, 0, null); + yield return Toils_Reserve.Reserve(TargetIndex.B, 1, -1, null); + Toil watch; + if (base.TargetC.HasThing && base.TargetC.Thing is Building_Bed) + { + this.KeepLyingDown(TargetIndex.C); + yield return Toils_Reserve.Reserve(TargetIndex.C, ((Building_Bed)base.TargetC.Thing).SleepingSlotsCount, 0, null); + yield return Toils_Bed.ClaimBedIfNonMedical(TargetIndex.C, TargetIndex.None); + yield return Toils_Bed.GotoBed(TargetIndex.C); + watch = Toils_LayDown.LayDown(TargetIndex.C, true, false, true, true); + watch.AddFailCondition((Func)(() => !((_003CMakeNewToils_003Ec__Iterator1D)/*Error near IL_0166: stateMachine*/)._003Cwatch_003E__1.actor.Awake())); + } + else + { + if (base.TargetC.HasThing) + { + yield return Toils_Reserve.Reserve(TargetIndex.C, 1, -1, null); + } + yield return Toils_Goto.GotoCell(TargetIndex.B, PathEndMode.OnCell); + watch = new Toil(); + } + watch.AddPreTickAction((Action)delegate + { + ((_003CMakeNewToils_003Ec__Iterator1D)/*Error near IL_01da: stateMachine*/)._003C_003Ef__this.WatchTickAction(); + }); + watch.AddFinishAction((Action)delegate + { + JoyUtility.TryGainRecRoomThought(((_003CMakeNewToils_003Ec__Iterator1D)/*Error near IL_01f1: stateMachine*/)._003C_003Ef__this.pawn); + }); + watch.defaultCompleteMode = ToilCompleteMode.Delay; + watch.defaultDuration = base.CurJob.def.joyDuration; + yield return watch; } protected virtual void WatchTickAction() { - this.pawn.Drawer.rotator.FaceCell(base.TargetA.Cell); - this.pawn.GainComfortFromCellIfPossible(); - float statValue = base.TargetThingA.GetStatValue(StatDefOf.EntertainmentStrengthFactor, true); - float extraJoyGainFactor = statValue; - JoyUtility.JoyTickCheckEnd(this.pawn, JoyTickFullJoyAction.EndJob, extraJoyGainFactor); + base.pawn.Drawer.rotator.FaceCell(base.TargetA.Cell); + base.pawn.GainComfortFromCellIfPossible(); + float statValue; + float num = statValue = base.TargetThingA.GetStatValue(StatDefOf.EntertainmentStrengthFactor, true); + JoyUtility.JoyTickCheckEnd(base.pawn, JoyTickFullJoyAction.EndJob, statValue); } } } diff --git a/Assembly-CSharp/RimWorld/JobDriver_WatchTelevision.cs b/Assembly-CSharp/RimWorld/JobDriver_WatchTelevision.cs index fa98e4c07..a97adb3fa 100644 --- a/Assembly-CSharp/RimWorld/JobDriver_WatchTelevision.cs +++ b/Assembly-CSharp/RimWorld/JobDriver_WatchTelevision.cs @@ -1,4 +1,3 @@ -using System; using Verse; using Verse.AI; @@ -12,9 +11,11 @@ protected override void WatchTickAction() if (!thing.TryGetComp().PowerOn) { base.EndJobWith(JobCondition.Incompletable); - return; } - base.WatchTickAction(); + else + { + base.WatchTickAction(); + } } } } diff --git a/Assembly-CSharp/RimWorld/JobDriver_Wear.cs b/Assembly-CSharp/RimWorld/JobDriver_Wear.cs index 8d6d89c56..94a9de548 100644 --- a/Assembly-CSharp/RimWorld/JobDriver_Wear.cs +++ b/Assembly-CSharp/RimWorld/JobDriver_Wear.cs @@ -1,6 +1,5 @@ using System; using System.Collections.Generic; -using System.Diagnostics; using Verse.AI; namespace RimWorld @@ -9,14 +8,40 @@ public class JobDriver_Wear : JobDriver { private const int DurationTicks = 60; - [DebuggerHidden] protected override IEnumerable MakeNewToils() { - JobDriver_Wear.c__Iterator54 c__Iterator = new JobDriver_Wear.c__Iterator54(); - c__Iterator.<>f__this = this; - JobDriver_Wear.c__Iterator54 expr_0E = c__Iterator; - expr_0E.$PC = -2; - return expr_0E; + yield return Toils_Reserve.Reserve(TargetIndex.A, 1, -1, null); + Toil gotoApparel = new Toil + { + initAction = (Action)delegate + { + ((_003CMakeNewToils_003Ec__Iterator54)/*Error near IL_0059: stateMachine*/)._003C_003Ef__this.pawn.pather.StartPath(((_003CMakeNewToils_003Ec__Iterator54)/*Error near IL_0059: stateMachine*/)._003C_003Ef__this.TargetThingA, PathEndMode.ClosestTouch); + }, + defaultCompleteMode = ToilCompleteMode.PatherArrival + }; + gotoApparel.FailOnDespawnedNullOrForbidden(TargetIndex.A); + yield return gotoApparel; + Toil prepare = new Toil + { + defaultCompleteMode = ToilCompleteMode.Delay, + defaultDuration = 60 + }; + prepare.WithProgressBarToilDelay(TargetIndex.A, false, -0.5f); + prepare.FailOnDespawnedNullOrForbidden(TargetIndex.A); + yield return prepare; + yield return new Toil + { + initAction = (Action)delegate + { + Apparel apparel = (Apparel)((_003CMakeNewToils_003Ec__Iterator54)/*Error near IL_0108: stateMachine*/)._003C_003Ef__this.CurJob.targetA.Thing; + ((_003CMakeNewToils_003Ec__Iterator54)/*Error near IL_0108: stateMachine*/)._003C_003Ef__this.pawn.apparel.Wear(apparel, true); + if (((_003CMakeNewToils_003Ec__Iterator54)/*Error near IL_0108: stateMachine*/)._003C_003Ef__this.pawn.outfits != null && ((_003CMakeNewToils_003Ec__Iterator54)/*Error near IL_0108: stateMachine*/)._003C_003Ef__this.CurJob.playerForced) + { + ((_003CMakeNewToils_003Ec__Iterator54)/*Error near IL_0108: stateMachine*/)._003C_003Ef__this.pawn.outfits.forcedHandler.SetForced(apparel, true); + } + }, + defaultCompleteMode = ToilCompleteMode.Instant + }; } } } diff --git a/Assembly-CSharp/RimWorld/JobGiver_AIDefendEscortee.cs b/Assembly-CSharp/RimWorld/JobGiver_AIDefendEscortee.cs index d68923abe..ab8ba90fc 100644 --- a/Assembly-CSharp/RimWorld/JobGiver_AIDefendEscortee.cs +++ b/Assembly-CSharp/RimWorld/JobGiver_AIDefendEscortee.cs @@ -1,4 +1,3 @@ -using System; using Verse; namespace RimWorld diff --git a/Assembly-CSharp/RimWorld/JobGiver_AIDefendMaster.cs b/Assembly-CSharp/RimWorld/JobGiver_AIDefendMaster.cs index fef058f63..06b9efdfb 100644 --- a/Assembly-CSharp/RimWorld/JobGiver_AIDefendMaster.cs +++ b/Assembly-CSharp/RimWorld/JobGiver_AIDefendMaster.cs @@ -1,4 +1,3 @@ -using System; using Verse; namespace RimWorld diff --git a/Assembly-CSharp/RimWorld/JobGiver_AIDefendPawn.cs b/Assembly-CSharp/RimWorld/JobGiver_AIDefendPawn.cs index 692fcbcf8..ad9d6e5e1 100644 --- a/Assembly-CSharp/RimWorld/JobGiver_AIDefendPawn.cs +++ b/Assembly-CSharp/RimWorld/JobGiver_AIDefendPawn.cs @@ -1,4 +1,3 @@ -using System; using Verse; using Verse.AI; @@ -20,11 +19,11 @@ public override ThinkNode DeepCopy(bool resolve = true) protected override IntVec3 GetFlagPosition(Pawn pawn) { Pawn defendee = this.GetDefendee(pawn); - if (defendee.Spawned || defendee.CarriedBy != null) + if (!defendee.Spawned && defendee.CarriedBy == null) { - return defendee.PositionHeld; + return IntVec3.Invalid; } - return IntVec3.Invalid; + return defendee.PositionHeld; } protected override Job TryGiveJob(Pawn pawn) @@ -33,15 +32,18 @@ protected override Job TryGiveJob(Pawn pawn) Pawn carriedBy = defendee.CarriedBy; if (carriedBy != null) { - if (!pawn.CanReach(carriedBy, PathEndMode.OnCell, Danger.Deadly, false, TraverseMode.ByPawn)) + if (!pawn.CanReach((Thing)carriedBy, PathEndMode.OnCell, Danger.Deadly, false, TraverseMode.ByPawn)) { return null; } + goto IL_0053; } - else if (!defendee.Spawned || !pawn.CanReach(defendee, PathEndMode.OnCell, Danger.Deadly, false, TraverseMode.ByPawn)) + if (defendee.Spawned && pawn.CanReach((Thing)defendee, PathEndMode.OnCell, Danger.Deadly, false, TraverseMode.ByPawn)) { - return null; + goto IL_0053; } + return null; + IL_0053: return base.TryGiveJob(pawn); } @@ -50,7 +52,7 @@ protected override Thing FindAttackTarget(Pawn pawn) if (this.attackMeleeThreatEvenIfNotHostile) { Pawn defendee = this.GetDefendee(pawn); - if (defendee.Spawned && !defendee.InMentalState && defendee.mindState.meleeThreat != null && defendee.mindState.meleeThreat != pawn && pawn.CanReach(defendee.mindState.meleeThreat, PathEndMode.Touch, Danger.Deadly, false, TraverseMode.ByPawn)) + if (defendee.Spawned && !defendee.InMentalState && defendee.mindState.meleeThreat != null && defendee.mindState.meleeThreat != pawn && pawn.CanReach((Thing)defendee.mindState.meleeThreat, PathEndMode.Touch, Danger.Deadly, false, TraverseMode.ByPawn)) { return defendee.mindState.meleeThreat; } @@ -74,7 +76,7 @@ protected override bool TryFindShootingPosition(Pawn pawn, out IntVec3 dest) maxRangeFromTarget = 9999f, locus = this.GetDefendee(pawn).PositionHeld, maxRangeFromLocus = this.GetFlagRadius(pawn), - wantCoverFromTarget = (verb.verbProps.range > 7f), + wantCoverFromTarget = (verb.verbProps.range > 7.0), maxRegionsRadius = 50 }, out dest); } diff --git a/Assembly-CSharp/RimWorld/JobGiver_AIDefendPoint.cs b/Assembly-CSharp/RimWorld/JobGiver_AIDefendPoint.cs index cc697d049..fc3c726f9 100644 --- a/Assembly-CSharp/RimWorld/JobGiver_AIDefendPoint.cs +++ b/Assembly-CSharp/RimWorld/JobGiver_AIDefendPoint.cs @@ -1,4 +1,3 @@ -using System; using Verse; using Verse.AI; @@ -22,7 +21,7 @@ protected override bool TryFindShootingPosition(Pawn pawn, out IntVec3 dest) maxRangeFromTarget = 9999f, locus = (IntVec3)pawn.mindState.duty.focus, maxRangeFromLocus = pawn.mindState.duty.radius, - wantCoverFromTarget = (verb.verbProps.range > 7f) + wantCoverFromTarget = (verb.verbProps.range > 7.0) }, out dest); } } diff --git a/Assembly-CSharp/RimWorld/JobGiver_AIDefendSelf.cs b/Assembly-CSharp/RimWorld/JobGiver_AIDefendSelf.cs index 6b879aa86..8a5950343 100644 --- a/Assembly-CSharp/RimWorld/JobGiver_AIDefendSelf.cs +++ b/Assembly-CSharp/RimWorld/JobGiver_AIDefendSelf.cs @@ -1,4 +1,3 @@ -using System; using Verse; namespace RimWorld diff --git a/Assembly-CSharp/RimWorld/JobGiver_AIFightEnemies.cs b/Assembly-CSharp/RimWorld/JobGiver_AIFightEnemies.cs index 0155f9c00..e37d6244f 100644 --- a/Assembly-CSharp/RimWorld/JobGiver_AIFightEnemies.cs +++ b/Assembly-CSharp/RimWorld/JobGiver_AIFightEnemies.cs @@ -1,4 +1,3 @@ -using System; using Verse; using Verse.AI; @@ -21,7 +20,7 @@ protected override bool TryFindShootingPosition(Pawn pawn, out IntVec3 dest) target = pawn.mindState.enemyTarget, verb = verb, maxRangeFromTarget = verb.verbProps.range, - wantCoverFromTarget = (verb.verbProps.range > 5f) + wantCoverFromTarget = (verb.verbProps.range > 5.0) }, out dest); } } diff --git a/Assembly-CSharp/RimWorld/JobGiver_AIFightEnemy.cs b/Assembly-CSharp/RimWorld/JobGiver_AIFightEnemy.cs index 33eb848cc..f632d1a9d 100644 --- a/Assembly-CSharp/RimWorld/JobGiver_AIFightEnemy.cs +++ b/Assembly-CSharp/RimWorld/JobGiver_AIFightEnemy.cs @@ -69,15 +69,17 @@ protected override Job TryGiveJob(Pawn pawn) { return this.MeleeAttackJob(enemyTarget); } - bool flag = CoverUtility.CalculateOverallBlockChance(pawn.Position, enemyTarget.Position, pawn.Map) > 0.01f; + bool flag = CoverUtility.CalculateOverallBlockChance(pawn.Position, enemyTarget.Position, pawn.Map) > 0.0099999997764825821; bool flag2 = pawn.Position.Standable(pawn.Map); bool flag3 = verb.CanHitTarget(enemyTarget); bool flag4 = (pawn.Position - enemyTarget.Position).LengthHorizontalSquared < 25; - if ((flag && flag2 && flag3) || (flag4 && flag3)) + if (flag && flag2 && flag3) { - return new Job(JobDefOf.WaitCombat, JobGiver_AIFightEnemy.ExpiryInterval_ShooterSucceeded.RandomInRange, true); + goto IL_00cf; } - IntVec3 intVec; + if (flag4 && flag3) + goto IL_00cf; + IntVec3 intVec = default(IntVec3); if (!this.TryFindShootingPosition(pawn, out intVec)) { return null; @@ -87,21 +89,21 @@ protected override Job TryGiveJob(Pawn pawn) return new Job(JobDefOf.WaitCombat, JobGiver_AIFightEnemy.ExpiryInterval_ShooterSucceeded.RandomInRange, true); } pawn.Map.pawnDestinationManager.ReserveDestinationFor(pawn, intVec); - return new Job(JobDefOf.Goto, intVec) - { - expiryInterval = JobGiver_AIFightEnemy.ExpiryInterval_ShooterSucceeded.RandomInRange, - checkOverrideOnExpire = true - }; + Job job = new Job(JobDefOf.Goto, intVec); + job.expiryInterval = JobGiver_AIFightEnemy.ExpiryInterval_ShooterSucceeded.RandomInRange; + job.checkOverrideOnExpire = true; + return job; + IL_00cf: + return new Job(JobDefOf.WaitCombat, JobGiver_AIFightEnemy.ExpiryInterval_ShooterSucceeded.RandomInRange, true); } protected virtual Job MeleeAttackJob(Thing enemyTarget) { - return new Job(JobDefOf.AttackMelee, enemyTarget) - { - expiryInterval = JobGiver_AIFightEnemy.ExpiryInterval_Melee.RandomInRange, - checkOverrideOnExpire = true, - expireRequiresEnemiesNearby = true - }; + Job job = new Job(JobDefOf.AttackMelee, enemyTarget); + job.expiryInterval = JobGiver_AIFightEnemy.ExpiryInterval_Melee.RandomInRange; + job.checkOverrideOnExpire = true; + job.expireRequiresEnemiesNearby = true; + return job; } protected virtual void UpdateEnemyTarget(Pawn pawn) @@ -159,13 +161,13 @@ protected virtual Thing FindAttackTarget(Pawn pawn) TargetScanFlags targetScanFlags = TargetScanFlags.NeedLOSToPawns | TargetScanFlags.NeedReachableIfCantHitFromMyPos | TargetScanFlags.NeedThreat; if (this.needLOSToAcquireNonPawnTargets) { - targetScanFlags |= TargetScanFlags.NeedLOSToNonPawns; + targetScanFlags = (TargetScanFlags)(byte)((int)targetScanFlags | 2); } if (this.PrimaryVerbIsIncendiary(pawn)) { - targetScanFlags |= TargetScanFlags.NeedNonBurning; + targetScanFlags = (TargetScanFlags)(byte)((int)targetScanFlags | 16); } - return (Thing)AttackTargetFinder.BestAttackTarget(pawn, targetScanFlags, (Thing x) => this.ExtraTargetValidator(pawn, x), 0f, this.targetAcquireRadius, this.GetFlagPosition(pawn), this.GetFlagRadius(pawn), false); + return (Thing)AttackTargetFinder.BestAttackTarget(pawn, targetScanFlags, (Predicate)((Thing x) => this.ExtraTargetValidator(pawn, x)), 0f, this.targetAcquireRadius, this.GetFlagPosition(pawn), this.GetFlagRadius(pawn), false); } private bool PrimaryVerbIsIncendiary(Pawn pawn) diff --git a/Assembly-CSharp/RimWorld/JobGiver_AIFollowEscortee.cs b/Assembly-CSharp/RimWorld/JobGiver_AIFollowEscortee.cs index 49ed83d76..a08b46497 100644 --- a/Assembly-CSharp/RimWorld/JobGiver_AIFollowEscortee.cs +++ b/Assembly-CSharp/RimWorld/JobGiver_AIFollowEscortee.cs @@ -1,4 +1,3 @@ -using System; using Verse; namespace RimWorld diff --git a/Assembly-CSharp/RimWorld/JobGiver_AIFollowMaster.cs b/Assembly-CSharp/RimWorld/JobGiver_AIFollowMaster.cs index e85cade6f..e98092185 100644 --- a/Assembly-CSharp/RimWorld/JobGiver_AIFollowMaster.cs +++ b/Assembly-CSharp/RimWorld/JobGiver_AIFollowMaster.cs @@ -1,4 +1,3 @@ -using System; using Verse; namespace RimWorld diff --git a/Assembly-CSharp/RimWorld/JobGiver_AIFollowPawn.cs b/Assembly-CSharp/RimWorld/JobGiver_AIFollowPawn.cs index 3afdd1031..7c7af66f4 100644 --- a/Assembly-CSharp/RimWorld/JobGiver_AIFollowPawn.cs +++ b/Assembly-CSharp/RimWorld/JobGiver_AIFollowPawn.cs @@ -1,4 +1,3 @@ -using System; using UnityEngine; using Verse; using Verse.AI; @@ -32,20 +31,20 @@ protected override Job TryGiveJob(Pawn pawn) return null; } float radius = this.GetRadius(pawn); - if ((!followee.pather.Moving || (float)followee.pather.Destination.Cell.DistanceToSquared(pawn.Position) <= radius * radius) && (followee.GetRoom(RegionType.Set_Passable) == pawn.GetRoom(RegionType.Set_Passable) || GenSight.LineOfSight(pawn.Position, followee.Position, followee.Map, false, null, 0, 0)) && (float)followee.Position.DistanceToSquared(pawn.Position) <= radius * radius) + if (followee.pather.Moving && (float)followee.pather.Destination.Cell.DistanceToSquared(pawn.Position) > radius * radius) { - return null; - } - IntVec3 root; - if (followee.pather.Moving && followee.pather.curPath != null) - { - root = followee.pather.curPath.FinalWalkableNonDoorCell(followee.Map); + goto IL_00c0; } - else + if (followee.GetRoom(RegionType.Set_Passable) != pawn.GetRoom(RegionType.Set_Passable) && !GenSight.LineOfSight(pawn.Position, followee.Position, followee.Map, false, null, 0, 0)) { - root = followee.Position; + goto IL_00c0; } - IntVec3 intVec = CellFinder.RandomClosewalkCellNear(root, followee.Map, Mathf.RoundToInt(radius * 0.7f), null); + if ((float)followee.Position.DistanceToSquared(pawn.Position) > radius * radius) + goto IL_00c0; + return null; + IL_00c0: + IntVec3 root = (!followee.pather.Moving || followee.pather.curPath == null) ? followee.Position : followee.pather.curPath.FinalWalkableNonDoorCell(followee.Map); + IntVec3 intVec = CellFinder.RandomClosewalkCellNear(root, followee.Map, Mathf.RoundToInt((float)(radius * 0.699999988079071)), null); if (intVec == pawn.Position) { return null; @@ -53,7 +52,7 @@ protected override Job TryGiveJob(Pawn pawn) Job job = new Job(JobDefOf.Goto, intVec); job.expiryInterval = this.FollowJobExpireInterval; job.checkOverrideOnExpire = true; - if (pawn.mindState.duty != null && pawn.mindState.duty.locomotion != LocomotionUrgency.None) + if (((pawn.mindState.duty != null) ? pawn.mindState.duty.locomotion : LocomotionUrgency.None) != 0) { job.locomotionUrgency = pawn.mindState.duty.locomotion; } diff --git a/Assembly-CSharp/RimWorld/JobGiver_AIGotoNearestHostile.cs b/Assembly-CSharp/RimWorld/JobGiver_AIGotoNearestHostile.cs index 999956f20..2811c56e2 100644 --- a/Assembly-CSharp/RimWorld/JobGiver_AIGotoNearestHostile.cs +++ b/Assembly-CSharp/RimWorld/JobGiver_AIGotoNearestHostile.cs @@ -1,4 +1,3 @@ -using System; using System.Collections.Generic; using Verse; using Verse.AI; @@ -28,12 +27,11 @@ protected override Job TryGiveJob(Pawn pawn) } if (thing != null) { - return new Job(JobDefOf.Goto, thing) - { - checkOverrideOnExpire = true, - expiryInterval = 500, - collideWithPawns = true - }; + Job job = new Job(JobDefOf.Goto, thing); + job.checkOverrideOnExpire = true; + job.expiryInterval = 500; + job.collideWithPawns = true; + return job; } return null; } diff --git a/Assembly-CSharp/RimWorld/JobGiver_AISapper.cs b/Assembly-CSharp/RimWorld/JobGiver_AISapper.cs index 130eaa02e..036023a37 100644 --- a/Assembly-CSharp/RimWorld/JobGiver_AISapper.cs +++ b/Assembly-CSharp/RimWorld/JobGiver_AISapper.cs @@ -24,17 +24,17 @@ public override ThinkNode DeepCopy(bool resolve = true) protected override Job TryGiveJob(Pawn pawn) { IntVec3 intVec = (IntVec3)pawn.mindState.duty.focus; - if (intVec.IsValid && (float)intVec.DistanceToSquared(pawn.Position) < 100f && intVec.GetRoom(pawn.Map, RegionType.Set_Passable) == pawn.GetRoom(RegionType.Set_Passable) && intVec.WithinRegions(pawn.Position, pawn.Map, 9, TraverseMode.NoPassClosedDoors, RegionType.Set_Passable)) + if (intVec.IsValid && (float)intVec.DistanceToSquared(pawn.Position) < 100.0 && intVec.GetRoom(pawn.Map, RegionType.Set_Passable) == pawn.GetRoom(RegionType.Set_Passable) && intVec.WithinRegions(pawn.Position, pawn.Map, 9, TraverseMode.NoPassClosedDoors, RegionType.Set_Passable)) { pawn.GetLord().Notify_ReachedDutyLocation(pawn); return null; } if (!intVec.IsValid) { - IAttackTarget attackTarget; + IAttackTarget attackTarget = default(IAttackTarget); if (!(from x in pawn.Map.attackTargetsCache.GetPotentialTargetsFor(pawn) where !x.ThreatDisabled() && x.Thing.Faction == Faction.OfPlayer && pawn.CanReach(x.Thing, PathEndMode.OnCell, Danger.Deadly, false, TraverseMode.PassAllDestroyableThings) - select x).TryRandomElement(out attackTarget)) + select x).TryRandomElement(out attackTarget)) { return null; } @@ -44,10 +44,10 @@ protected override Job TryGiveJob(Pawn pawn) { return null; } - using (PawnPath pawnPath = pawn.Map.pathFinder.FindPath(pawn.Position, intVec, TraverseParms.For(pawn, Danger.Deadly, TraverseMode.PassAllDestroyableThings, false), PathEndMode.OnCell)) + using (PawnPath path = pawn.Map.pathFinder.FindPath(pawn.Position, intVec, TraverseParms.For(pawn, Danger.Deadly, TraverseMode.PassAllDestroyableThings, false), PathEndMode.OnCell)) { - IntVec3 cellBeforeBlocker; - Thing thing = pawnPath.FirstBlockingBuilding(out cellBeforeBlocker, pawn); + IntVec3 cellBeforeBlocker = default(IntVec3); + Thing thing = path.FirstBlockingBuilding(out cellBeforeBlocker, pawn); if (thing != null) { Job job = DigUtility.PassBlockerJob(pawn, thing, cellBeforeBlocker, this.canMineNonMineables); diff --git a/Assembly-CSharp/RimWorld/JobGiver_AITrashBuildingsDistant.cs b/Assembly-CSharp/RimWorld/JobGiver_AITrashBuildingsDistant.cs index 368002d00..e5da3064a 100644 --- a/Assembly-CSharp/RimWorld/JobGiver_AITrashBuildingsDistant.cs +++ b/Assembly-CSharp/RimWorld/JobGiver_AITrashBuildingsDistant.cs @@ -1,4 +1,3 @@ -using System; using System.Collections.Generic; using Verse; using Verse.AI; diff --git a/Assembly-CSharp/RimWorld/JobGiver_AITrashColonyClose.cs b/Assembly-CSharp/RimWorld/JobGiver_AITrashColonyClose.cs index 06398ef63..86909a791 100644 --- a/Assembly-CSharp/RimWorld/JobGiver_AITrashColonyClose.cs +++ b/Assembly-CSharp/RimWorld/JobGiver_AITrashColonyClose.cs @@ -1,4 +1,3 @@ -using System; using Verse; using Verse.AI; diff --git a/Assembly-CSharp/RimWorld/JobGiver_Berserk.cs b/Assembly-CSharp/RimWorld/JobGiver_Berserk.cs index eb3b5df0e..fb7cb734f 100644 --- a/Assembly-CSharp/RimWorld/JobGiver_Berserk.cs +++ b/Assembly-CSharp/RimWorld/JobGiver_Berserk.cs @@ -18,12 +18,11 @@ public class JobGiver_Berserk : ThinkNode_JobGiver protected override Job TryGiveJob(Pawn pawn) { - if (Rand.Value < 0.5f) + if (Rand.Value < 0.5) { - return new Job(JobDefOf.WaitCombat) - { - expiryInterval = 90 - }; + Job job = new Job(JobDefOf.WaitCombat); + job.expiryInterval = 90; + return job; } if (pawn.TryGetAttackVerb(false) == null) { @@ -32,19 +31,18 @@ protected override Job TryGiveJob(Pawn pawn) Pawn pawn2 = this.FindPawnTarget(pawn); if (pawn2 != null) { - return new Job(JobDefOf.AttackMelee, pawn2) - { - maxNumMeleeAttacks = 1, - expiryInterval = Rand.Range(420, 900), - canBash = true - }; + Job job2 = new Job(JobDefOf.AttackMelee, (Thing)pawn2); + job2.maxNumMeleeAttacks = 1; + job2.expiryInterval = Rand.Range(420, 900); + job2.canBash = true; + return job2; } return null; } private Pawn FindPawnTarget(Pawn pawn) { - return (Pawn)AttackTargetFinder.BestAttackTarget(pawn, TargetScanFlags.NeedReachable | TargetScanFlags.NeedThreat, (Thing x) => x is Pawn, 0f, 30f, default(IntVec3), 3.40282347E+38f, true); + return (Pawn)AttackTargetFinder.BestAttackTarget(pawn, TargetScanFlags.NeedReachable | TargetScanFlags.NeedThreat, (Predicate)((Thing x) => x is Pawn), 0f, 30f, default(IntVec3), 3.40282347E+38f, true); } } } diff --git a/Assembly-CSharp/RimWorld/JobGiver_Binge.cs b/Assembly-CSharp/RimWorld/JobGiver_Binge.cs index b766811ff..7c4344727 100644 --- a/Assembly-CSharp/RimWorld/JobGiver_Binge.cs +++ b/Assembly-CSharp/RimWorld/JobGiver_Binge.cs @@ -1,4 +1,3 @@ -using System; using Verse; using Verse.AI; @@ -35,12 +34,11 @@ private Job IngestJob(Pawn pawn) return null; } ThingDef finalIngestibleDef = FoodUtility.GetFinalIngestibleDef(thing); - return new Job(JobDefOf.Ingest, thing) - { - count = finalIngestibleDef.ingestible.maxNumToIngestAtOnce, - ignoreForbidden = this.IgnoreForbid(pawn), - overeat = true - }; + Job job = new Job(JobDefOf.Ingest, thing); + job.count = finalIngestibleDef.ingestible.maxNumToIngestAtOnce; + job.ignoreForbidden = this.IgnoreForbid(pawn); + job.overeat = true; + return job; } protected abstract Thing BestIngestTarget(Pawn pawn); diff --git a/Assembly-CSharp/RimWorld/JobGiver_BingeDrug.cs b/Assembly-CSharp/RimWorld/JobGiver_BingeDrug.cs index 9aa5bd13a..7495de9b5 100644 --- a/Assembly-CSharp/RimWorld/JobGiver_BingeDrug.cs +++ b/Assembly-CSharp/RimWorld/JobGiver_BingeDrug.cs @@ -66,9 +66,10 @@ protected override Thing BestIngestTarget(Pawn pawn) return null; } Hediff overdose = pawn.health.hediffSet.GetFirstHediffOfDef(HediffDefOf.DrugOverdose, false); - Predicate predicate = delegate(Thing t) + Predicate validator; + Predicate predicate = validator = (Predicate)delegate(Thing t) { - if (!this.IgnoreForbid(pawn) && t.IsForbidden(pawn)) + if (!base.IgnoreForbid(pawn) && t.IsForbidden(pawn)) { return false; } @@ -77,9 +78,20 @@ protected override Thing BestIngestTarget(Pawn pawn) return false; } CompDrug compDrug = t.TryGetComp(); - return compDrug.Props.chemical == chemical && (overdose == null || !compDrug.Props.CanCauseOverdose || overdose.Severity + compDrug.Props.overdoseSeverityOffset.max < 0.786f) && (pawn.Position.InHorDistOf(t.Position, 60f) || t.Position.Roofed(t.Map) || pawn.Map.areaManager.Home[t.Position] || t.GetSlotGroup() != null); + if (compDrug.Props.chemical != chemical) + { + return false; + } + if (overdose != null && compDrug.Props.CanCauseOverdose && overdose.Severity + compDrug.Props.overdoseSeverityOffset.max >= 0.78600001335144043) + { + return false; + } + if (!pawn.Position.InHorDistOf(t.Position, 60f) && !t.Position.Roofed(t.Map) && !((Area)pawn.Map.areaManager.Home)[t.Position] && t.GetSlotGroup() == null) + { + return false; + } + return true; }; - Predicate validator = predicate; return GenClosest.ClosestThingReachable(pawn.Position, pawn.Map, ThingRequest.ForGroup(ThingRequestGroup.Drug), PathEndMode.OnCell, TraverseParms.For(pawn, Danger.Deadly, TraverseMode.ByPawn, false), 9999f, validator, null, 0, -1, false, RegionType.Set_Passable, false); } diff --git a/Assembly-CSharp/RimWorld/JobGiver_BingeFood.cs b/Assembly-CSharp/RimWorld/JobGiver_BingeFood.cs index bef2afdce..928d0aa4a 100644 --- a/Assembly-CSharp/RimWorld/JobGiver_BingeFood.cs +++ b/Assembly-CSharp/RimWorld/JobGiver_BingeFood.cs @@ -1,4 +1,3 @@ -using System; using Verse; namespace RimWorld @@ -14,8 +13,8 @@ protected override int IngestInterval(Pawn pawn) protected override Thing BestIngestTarget(Pawn pawn) { - Thing result; - ThingDef thingDef; + Thing result = default(Thing); + ThingDef thingDef = default(ThingDef); if (FoodUtility.TryFindBestFoodSourceFor(pawn, pawn, true, out result, out thingDef, false, true, true, true, true)) { return result; diff --git a/Assembly-CSharp/RimWorld/JobGiver_ConfigurableHostilityResponse.cs b/Assembly-CSharp/RimWorld/JobGiver_ConfigurableHostilityResponse.cs index 43ec6b246..919299a42 100644 --- a/Assembly-CSharp/RimWorld/JobGiver_ConfigurableHostilityResponse.cs +++ b/Assembly-CSharp/RimWorld/JobGiver_ConfigurableHostilityResponse.cs @@ -1,4 +1,3 @@ -using System; using System.Collections.Generic; using UnityEngine; using Verse; @@ -12,25 +11,33 @@ public class JobGiver_ConfigurableHostilityResponse : ThinkNode_JobGiver protected override Job TryGiveJob(Pawn pawn) { - if (pawn.playerSettings == null || !pawn.playerSettings.UsesConfigurableHostilityResponse) + if (pawn.playerSettings != null && pawn.playerSettings.UsesConfigurableHostilityResponse) { - return null; - } - if (PawnUtility.PlayerForcedJobNowOrSoon(pawn)) - { - return null; - } - switch (pawn.playerSettings.hostilityResponse) - { - case HostilityResponseMode.Ignore: - return null; - case HostilityResponseMode.Attack: - return this.TryGetAttackNearbyEnemyJob(pawn); - case HostilityResponseMode.Flee: - return this.TryGetFleeJob(pawn); - default: - return null; + if (PawnUtility.PlayerForcedJobNowOrSoon(pawn)) + { + return null; + } + switch (pawn.playerSettings.hostilityResponse) + { + case HostilityResponseMode.Ignore: + { + return null; + } + case HostilityResponseMode.Attack: + { + return this.TryGetAttackNearbyEnemyJob(pawn); + } + case HostilityResponseMode.Flee: + { + return this.TryGetFleeJob(pawn); + } + default: + { + return null; + } + } } + return null; } private Job TryGetAttackNearbyEnemyJob(Pawn pawn) @@ -43,7 +50,7 @@ private Job TryGetAttackNearbyEnemyJob(Pawn pawn) float num = 8f; if (!flag) { - num = Mathf.Clamp(pawn.equipment.PrimaryEq.PrimaryVerb.verbProps.range * 0.66f, 2f, 20f); + num = Mathf.Clamp((float)(pawn.equipment.PrimaryEq.PrimaryVerb.verbProps.range * 0.6600000262260437), 2f, 20f); } float maxDist = num; Thing thing = (Thing)AttackTargetFinder.BestAttackTarget(pawn, TargetScanFlags.NeedLOSToPawns | TargetScanFlags.NeedLOSToNonPawns | TargetScanFlags.NeedReachableIfCantHitFromMyPos | TargetScanFlags.NeedThreat, null, 0f, maxDist, default(IntVec3), 3.40282347E+38f, false); @@ -51,15 +58,14 @@ private Job TryGetAttackNearbyEnemyJob(Pawn pawn) { return null; } - if (flag || pawn.CanReachImmediate(thing, PathEndMode.Touch)) + if (!flag && !pawn.CanReachImmediate(thing, PathEndMode.Touch)) { - return new Job(JobDefOf.AttackMelee, thing); + Job job = new Job(JobDefOf.AttackStatic, thing); + job.maxNumStaticAttacks = 2; + job.expiryInterval = 1800; + return job; } - return new Job(JobDefOf.AttackStatic, thing) - { - maxNumStaticAttacks = 2, - expiryInterval = 1800 - }; + return new Job(JobDefOf.AttackMelee, thing); } private Job TryGetFleeJob(Pawn pawn) @@ -85,7 +91,7 @@ private Job TryGetFleeJob(Pawn pawn) JobGiver_ConfigurableHostilityResponse.tmpThreats.Add((Thing)attackTarget); } } - if (!JobGiver_ConfigurableHostilityResponse.tmpThreats.Any()) + if (!JobGiver_ConfigurableHostilityResponse.tmpThreats.Any()) { Log.Warning(pawn.LabelShort + " decided to flee but there is no any threat around."); return null; diff --git a/Assembly-CSharp/RimWorld/JobGiver_DoLovin.cs b/Assembly-CSharp/RimWorld/JobGiver_DoLovin.cs index 6ac3bcdcc..821c6f68e 100644 --- a/Assembly-CSharp/RimWorld/JobGiver_DoLovin.cs +++ b/Assembly-CSharp/RimWorld/JobGiver_DoLovin.cs @@ -1,4 +1,3 @@ -using System; using Verse; using Verse.AI; @@ -12,22 +11,22 @@ protected override Job TryGiveJob(Pawn pawn) { return null; } - if (pawn.CurrentBed() == null || pawn.CurrentBed().Medical || !pawn.health.capacities.CanBeAwake) + if (pawn.CurrentBed() != null && !pawn.CurrentBed().Medical && pawn.health.capacities.CanBeAwake) { + Pawn partnerInMyBed = LovePartnerRelationUtility.GetPartnerInMyBed(pawn); + if (partnerInMyBed != null && partnerInMyBed.health.capacities.CanBeAwake && Find.TickManager.TicksGame >= partnerInMyBed.mindState.canLovinTick) + { + if (pawn.CanReserve((Thing)partnerInMyBed, 1, -1, null, false) && partnerInMyBed.CanReserve((Thing)pawn, 1, -1, null, false)) + { + pawn.mindState.awokeVoluntarily = true; + partnerInMyBed.mindState.awokeVoluntarily = true; + return new Job(JobDefOf.Lovin, (Thing)partnerInMyBed, (Thing)pawn.CurrentBed()); + } + return null; + } return null; } - Pawn partnerInMyBed = LovePartnerRelationUtility.GetPartnerInMyBed(pawn); - if (partnerInMyBed == null || !partnerInMyBed.health.capacities.CanBeAwake || Find.TickManager.TicksGame < partnerInMyBed.mindState.canLovinTick) - { - return null; - } - if (!pawn.CanReserve(partnerInMyBed, 1, -1, null, false) || !partnerInMyBed.CanReserve(pawn, 1, -1, null, false)) - { - return null; - } - pawn.mindState.awokeVoluntarily = true; - partnerInMyBed.mindState.awokeVoluntarily = true; - return new Job(JobDefOf.Lovin, partnerInMyBed, pawn.CurrentBed()); + return null; } } } diff --git a/Assembly-CSharp/RimWorld/JobGiver_DropUnusedInventory.cs b/Assembly-CSharp/RimWorld/JobGiver_DropUnusedInventory.cs index 4998505f8..2f292a376 100644 --- a/Assembly-CSharp/RimWorld/JobGiver_DropUnusedInventory.cs +++ b/Assembly-CSharp/RimWorld/JobGiver_DropUnusedInventory.cs @@ -14,7 +14,7 @@ protected override Job TryGiveJob(Pawn pawn) { return null; } - if (!pawn.Map.areaManager.Home[pawn.Position]) + if (!((Area)pawn.Map.areaManager.Home)[pawn.Position]) { return null; } @@ -24,18 +24,18 @@ protected override Job TryGiveJob(Pawn pawn) } if (Find.TickManager.TicksGame > pawn.mindState.lastInventoryRawFoodUseTick + 150000) { - for (int i = pawn.inventory.innerContainer.Count - 1; i >= 0; i--) + for (int num = pawn.inventory.innerContainer.Count - 1; num >= 0; num--) { - Thing thing = pawn.inventory.innerContainer[i]; - if (thing.def.IsIngestible && !thing.def.IsDrug && thing.def.ingestible.preferability <= FoodPreferability.RawTasty) + Thing thing = pawn.inventory.innerContainer[num]; + if (thing.def.IsIngestible && !thing.def.IsDrug && (int)thing.def.ingestible.preferability <= 4) { this.Drop(pawn, thing); } } } - for (int j = pawn.inventory.innerContainer.Count - 1; j >= 0; j--) + for (int num2 = pawn.inventory.innerContainer.Count - 1; num2 >= 0; num2--) { - Thing thing2 = pawn.inventory.innerContainer[j]; + Thing thing2 = pawn.inventory.innerContainer[num2]; if (thing2.def.IsDrug && pawn.drugs != null && !pawn.drugs.AllowedToTakeScheduledEver(thing2.def) && pawn.drugs.HasEverTaken(thing2.def) && !AddictionUtility.IsAddicted(pawn, thing2)) { this.Drop(pawn, thing2); @@ -46,8 +46,8 @@ protected override Job TryGiveJob(Pawn pawn) private void Drop(Pawn pawn, Thing thing) { - Thing thing2; - pawn.inventory.innerContainer.TryDrop(thing, pawn.Position, pawn.Map, ThingPlaceMode.Near, out thing2, null); + Thing thing2 = default(Thing); + pawn.inventory.innerContainer.TryDrop(thing, pawn.Position, pawn.Map, ThingPlaceMode.Near, out thing2, (Action)null); } } } diff --git a/Assembly-CSharp/RimWorld/JobGiver_EatInPartyArea.cs b/Assembly-CSharp/RimWorld/JobGiver_EatInPartyArea.cs index d65af61c8..b7f97f9b5 100644 --- a/Assembly-CSharp/RimWorld/JobGiver_EatInPartyArea.cs +++ b/Assembly-CSharp/RimWorld/JobGiver_EatInPartyArea.cs @@ -24,15 +24,53 @@ protected override Job TryGiveJob(Pawn pawn) { return null; } - return new Job(JobDefOf.Ingest, thing) - { - count = FoodUtility.WillIngestStackCountOf(pawn, thing.def) - }; + Job job = new Job(JobDefOf.Ingest, thing); + job.count = FoodUtility.WillIngestStackCountOf(pawn, thing.def); + return job; } private Thing FindFood(Pawn pawn, IntVec3 partySpot) { - Predicate validator = (Thing x) => x.IngestibleNow && x.def.IsNutritionGivingIngestible && PartyUtility.InPartyArea(x.Position, partySpot, pawn.Map) && !x.def.IsDrug && x.def.ingestible.preferability > FoodPreferability.RawBad && pawn.RaceProps.WillAutomaticallyEat(x) && !x.IsForbidden(pawn) && x.IsSociallyProper(pawn) && pawn.CanReserve(x, 1, -1, null, false); + Predicate validator = (Predicate)delegate(Thing x) + { + if (!x.IngestibleNow) + { + return false; + } + if (!x.def.IsNutritionGivingIngestible) + { + return false; + } + if (!PartyUtility.InPartyArea(x.Position, partySpot, pawn.Map)) + { + return false; + } + if (x.def.IsDrug) + { + return false; + } + if ((int)x.def.ingestible.preferability <= 3) + { + return false; + } + if (!pawn.RaceProps.WillAutomaticallyEat(x)) + { + return false; + } + if (x.IsForbidden(pawn)) + { + return false; + } + if (!x.IsSociallyProper(pawn)) + { + return false; + } + if (!pawn.CanReserve(x, 1, -1, null, false)) + { + return false; + } + return true; + }; return GenClosest.ClosestThingReachable(pawn.Position, pawn.Map, ThingRequest.ForGroup(ThingRequestGroup.FoodSourceNotPlantOrTree), PathEndMode.ClosestTouch, TraverseParms.For(TraverseMode.NoPassClosedDoors, Danger.Deadly, false), 14f, validator, null, 0, 12, false, RegionType.Set_Passable, false); } } diff --git a/Assembly-CSharp/RimWorld/JobGiver_EatRandom.cs b/Assembly-CSharp/RimWorld/JobGiver_EatRandom.cs index 8ddf3bd46..f53b5e2c0 100644 --- a/Assembly-CSharp/RimWorld/JobGiver_EatRandom.cs +++ b/Assembly-CSharp/RimWorld/JobGiver_EatRandom.cs @@ -12,7 +12,22 @@ protected override Job TryGiveJob(Pawn pawn) { return null; } - Predicate validator = (Thing t) => t.def.category == ThingCategory.Item && t.IngestibleNow && pawn.RaceProps.CanEverEat(t); + Predicate validator = (Predicate)delegate(Thing t) + { + if (t.def.category != ThingCategory.Item) + { + return false; + } + if (!t.IngestibleNow) + { + return false; + } + if (!pawn.RaceProps.CanEverEat(t)) + { + return false; + } + return true; + }; Thing thing = GenClosest.ClosestThingReachable(pawn.Position, pawn.Map, ThingRequest.ForGroup(ThingRequestGroup.HaulableAlways), PathEndMode.OnCell, TraverseParms.For(pawn, Danger.Deadly, TraverseMode.ByPawn, false), 10f, validator, null, 0, -1, false, RegionType.Set_Passable, false); if (thing == null) { diff --git a/Assembly-CSharp/RimWorld/JobGiver_EnterTransporter.cs b/Assembly-CSharp/RimWorld/JobGiver_EnterTransporter.cs index 3ec50955a..30fe8a808 100644 --- a/Assembly-CSharp/RimWorld/JobGiver_EnterTransporter.cs +++ b/Assembly-CSharp/RimWorld/JobGiver_EnterTransporter.cs @@ -1,4 +1,3 @@ -using System; using System.Collections.Generic; using Verse; using Verse.AI; @@ -14,11 +13,11 @@ protected override Job TryGiveJob(Pawn pawn) int transportersGroup = pawn.mindState.duty.transportersGroup; TransporterUtility.GetTransportersInGroup(transportersGroup, pawn.Map, JobGiver_EnterTransporter.tmpTransporters); CompTransporter compTransporter = this.FindMyTransporter(JobGiver_EnterTransporter.tmpTransporters, pawn); - if (compTransporter == null || !pawn.CanReserveAndReach(compTransporter.parent, PathEndMode.Touch, Danger.Deadly, 1, -1, null, false)) + if (compTransporter != null && pawn.CanReserveAndReach((Thing)compTransporter.parent, PathEndMode.Touch, Danger.Deadly, 1, -1, null, false)) { - return null; + return new Job(JobDefOf.EnterTransporter, (Thing)compTransporter.parent); } - return new Job(JobDefOf.EnterTransporter, compTransporter.parent); + return null; } private CompTransporter FindMyTransporter(List transporters, Pawn me) diff --git a/Assembly-CSharp/RimWorld/JobGiver_ExtinguishSelf.cs b/Assembly-CSharp/RimWorld/JobGiver_ExtinguishSelf.cs index bd1f7ed96..ca3c60b2d 100644 --- a/Assembly-CSharp/RimWorld/JobGiver_ExtinguishSelf.cs +++ b/Assembly-CSharp/RimWorld/JobGiver_ExtinguishSelf.cs @@ -1,4 +1,3 @@ -using System; using Verse; using Verse.AI; @@ -10,12 +9,12 @@ public class JobGiver_ExtinguishSelf : ThinkNode_JobGiver protected override Job TryGiveJob(Pawn pawn) { - if (Rand.Value < 0.1f) + if (Rand.Value < 0.10000000149011612) { Fire fire = (Fire)pawn.GetAttachment(ThingDefOf.Fire); if (fire != null) { - return new Job(JobDefOf.ExtinguishSelf, fire); + return new Job(JobDefOf.ExtinguishSelf, (Thing)fire); } } return null; diff --git a/Assembly-CSharp/RimWorld/JobGiver_FightFiresNearPoint.cs b/Assembly-CSharp/RimWorld/JobGiver_FightFiresNearPoint.cs index e99087ff4..0ee5a115e 100644 --- a/Assembly-CSharp/RimWorld/JobGiver_FightFiresNearPoint.cs +++ b/Assembly-CSharp/RimWorld/JobGiver_FightFiresNearPoint.cs @@ -18,10 +18,22 @@ public override ThinkNode DeepCopy(bool resolve = true) protected override Job TryGiveJob(Pawn pawn) { - Predicate validator = delegate(Thing t) + Predicate validator = (Predicate)delegate(Thing t) { Pawn pawn2 = ((AttachableThing)t).parent as Pawn; - return pawn2 == null && pawn.CanReserve(t, 1, -1, null, false) && !pawn.story.WorkTagIsDisabled(WorkTags.Firefighting); + if (pawn2 != null) + { + return false; + } + if (!pawn.CanReserve(t, 1, -1, null, false)) + { + return false; + } + if (pawn.story.WorkTagIsDisabled(WorkTags.Firefighting)) + { + return false; + } + return true; }; Thing thing = GenClosest.ClosestThingReachable(pawn.GetLord().CurLordToil.FlagLoc, pawn.Map, ThingRequest.ForDef(ThingDefOf.Fire), PathEndMode.Touch, TraverseParms.For(pawn, Danger.Deadly, TraverseMode.ByPawn, false), this.maxDistFromPoint, validator, null, 0, -1, false, RegionType.Set_Passable, false); if (thing != null) diff --git a/Assembly-CSharp/RimWorld/JobGiver_FireStartingSpree.cs b/Assembly-CSharp/RimWorld/JobGiver_FireStartingSpree.cs index 2b37c0567..3f664da35 100644 --- a/Assembly-CSharp/RimWorld/JobGiver_FireStartingSpree.cs +++ b/Assembly-CSharp/RimWorld/JobGiver_FireStartingSpree.cs @@ -29,7 +29,7 @@ protected override Job TryGiveJob(Pawn pawn) pawn.mindState.nextMoveOrderIsWait = false; return job; } - if (Rand.Value < 0.75f) + if (Rand.Value < 0.75) { Thing thing = this.TryFindRandomIgniteTarget(pawn); if (thing != null) @@ -50,8 +50,8 @@ protected override Job TryGiveJob(Pawn pawn) private Thing TryFindRandomIgniteTarget(Pawn pawn) { - Region region; - if (!CellFinder.TryFindClosestRegionWith(pawn.GetRegion(RegionType.Set_Passable), TraverseParms.For(pawn, Danger.Deadly, TraverseMode.ByPawn, false), (Region candidateRegion) => !candidateRegion.IsForbiddenEntirely(pawn), 100, out region, RegionType.Set_Passable)) + Region region = default(Region); + if (!CellFinder.TryFindClosestRegionWith(pawn.GetRegion(RegionType.Set_Passable), TraverseParms.For(pawn, Danger.Deadly, TraverseMode.ByPawn, false), (Predicate)((Region candidateRegion) => !candidateRegion.IsForbiddenEntirely(pawn)), 100, out region, RegionType.Set_Passable)) { return null; } @@ -65,11 +65,11 @@ private Thing TryFindRandomIgniteTarget(Pawn pawn) JobGiver_FireStartingSpree.potentialTargets.Add(thing); } } - if (JobGiver_FireStartingSpree.potentialTargets.NullOrEmpty()) + if (JobGiver_FireStartingSpree.potentialTargets.NullOrEmpty()) { return null; } - return JobGiver_FireStartingSpree.potentialTargets.RandomElement(); + return JobGiver_FireStartingSpree.potentialTargets.RandomElement(); } } } diff --git a/Assembly-CSharp/RimWorld/JobGiver_FleeExplosion.cs b/Assembly-CSharp/RimWorld/JobGiver_FleeExplosion.cs index 262132be1..f070da4eb 100644 --- a/Assembly-CSharp/RimWorld/JobGiver_FleeExplosion.cs +++ b/Assembly-CSharp/RimWorld/JobGiver_FleeExplosion.cs @@ -1,4 +1,3 @@ -using System; using Verse; using Verse.AI; @@ -10,7 +9,7 @@ public class JobGiver_FleeExplosion : ThinkNode_JobGiver protected override Job TryGiveJob(Pawn pawn) { - if (pawn.RaceProps.intelligence < Intelligence.Humanlike) + if ((int)pawn.RaceProps.intelligence < 2) { return null; } @@ -28,19 +27,18 @@ protected override Job TryGiveJob(Pawn pawn) return null; } Thing knownExploder = pawn.mindState.knownExploder; - if ((float)(pawn.Position - knownExploder.Position).LengthHorizontalSquared > 81f) + if ((float)(pawn.Position - knownExploder.Position).LengthHorizontalSquared > 81.0) { return null; } - IntVec3 c; + IntVec3 c = default(IntVec3); if (!RCellFinder.TryFindDirectFleeDestination(knownExploder.Position, 9f, pawn, out c)) { return null; } - return new Job(JobDefOf.Goto, c) - { - locomotionUrgency = LocomotionUrgency.Sprint - }; + Job job = new Job(JobDefOf.Goto, c); + job.locomotionUrgency = LocomotionUrgency.Sprint; + return job; } } } diff --git a/Assembly-CSharp/RimWorld/JobGiver_GetFood.cs b/Assembly-CSharp/RimWorld/JobGiver_GetFood.cs index 84c065566..b498ce6ac 100644 --- a/Assembly-CSharp/RimWorld/JobGiver_GetFood.cs +++ b/Assembly-CSharp/RimWorld/JobGiver_GetFood.cs @@ -1,4 +1,3 @@ -using System; using Verse; using Verse.AI; @@ -22,11 +21,11 @@ public override float GetPriority(Pawn pawn) { return 0f; } - if (pawn.needs.food.CurCategory < HungerCategory.Starving && FoodUtility.ShouldBeFedBySomeone(pawn)) + if ((int)pawn.needs.food.CurCategory < 3 && FoodUtility.ShouldBeFedBySomeone(pawn)) { return 0f; } - if (food.CurCategory < this.minCategory) + if ((int)food.CurCategory < (int)this.minCategory) { return 0f; } @@ -40,60 +39,58 @@ public override float GetPriority(Pawn pawn) protected override Job TryGiveJob(Pawn pawn) { Need_Food food = pawn.needs.food; - if (food == null || food.CurCategory < this.minCategory) + if (food != null && (int)food.CurCategory >= (int)this.minCategory) { - return null; - } - bool flag; - if (pawn.RaceProps.Animal) - { - flag = true; - } - else - { - Hediff firstHediffOfDef = pawn.health.hediffSet.GetFirstHediffOfDef(HediffDefOf.Malnutrition, false); - flag = (firstHediffOfDef != null && firstHediffOfDef.Severity > 0.4f); - } - bool desperate = pawn.needs.food.CurCategory == HungerCategory.Starving; - bool allowCorpse = flag; - Thing thing; - ThingDef def; - if (!FoodUtility.TryFindBestFoodSourceFor(pawn, pawn, desperate, out thing, out def, true, true, false, allowCorpse, false)) - { - return null; - } - Pawn pawn2 = thing as Pawn; - if (pawn2 != null) - { - return new Job(JobDefOf.PredatorHunt, pawn2) + bool flag; + if (pawn.RaceProps.Animal) { - killIncappedTarget = true - }; - } - Building_NutrientPasteDispenser building_NutrientPasteDispenser = thing as Building_NutrientPasteDispenser; - if (building_NutrientPasteDispenser != null && !building_NutrientPasteDispenser.HasEnoughFeedstockInHoppers()) - { - Building building = building_NutrientPasteDispenser.AdjacentReachableHopper(pawn); - if (building != null) + flag = true; + } + else { - ISlotGroupParent hopperSgp = building as ISlotGroupParent; - Job job = WorkGiver_CookFillHopper.HopperFillFoodJob(pawn, hopperSgp); - if (job != null) - { - return job; - } + Hediff firstHediffOfDef = pawn.health.hediffSet.GetFirstHediffOfDef(HediffDefOf.Malnutrition, false); + flag = (firstHediffOfDef != null && firstHediffOfDef.Severity > 0.40000000596046448); } - thing = FoodUtility.BestFoodSourceOnMap(pawn, pawn, desperate, FoodPreferability.MealLavish, false, !pawn.IsTeetotaler(), false, false, false, false, false); - if (thing == null) + bool desperate = pawn.needs.food.CurCategory == HungerCategory.Starving; + bool allowCorpse = flag; + Thing thing = default(Thing); + ThingDef def = default(ThingDef); + if (!FoodUtility.TryFindBestFoodSourceFor(pawn, pawn, desperate, out thing, out def, true, true, false, allowCorpse, false)) { return null; } - def = thing.def; + Pawn pawn2 = thing as Pawn; + if (pawn2 != null) + { + Job job = new Job(JobDefOf.PredatorHunt, (Thing)pawn2); + job.killIncappedTarget = true; + return job; + } + Building_NutrientPasteDispenser building_NutrientPasteDispenser = thing as Building_NutrientPasteDispenser; + if (building_NutrientPasteDispenser != null && !building_NutrientPasteDispenser.HasEnoughFeedstockInHoppers()) + { + Building building = building_NutrientPasteDispenser.AdjacentReachableHopper(pawn); + if (building != null) + { + ISlotGroupParent hopperSgp = building as ISlotGroupParent; + Job job2 = WorkGiver_CookFillHopper.HopperFillFoodJob(pawn, hopperSgp); + if (job2 != null) + { + return job2; + } + } + thing = FoodUtility.BestFoodSourceOnMap(pawn, pawn, desperate, FoodPreferability.MealLavish, false, !pawn.IsTeetotaler(), false, false, false, false, false); + if (thing == null) + { + return null; + } + def = thing.def; + } + Job job3 = new Job(JobDefOf.Ingest, thing); + job3.count = FoodUtility.WillIngestStackCountOf(pawn, def); + return job3; } - return new Job(JobDefOf.Ingest, thing) - { - count = FoodUtility.WillIngestStackCountOf(pawn, def) - }; + return null; } } } diff --git a/Assembly-CSharp/RimWorld/JobGiver_GetJoy.cs b/Assembly-CSharp/RimWorld/JobGiver_GetJoy.cs index 5a7417ab9..fe665fde7 100644 --- a/Assembly-CSharp/RimWorld/JobGiver_GetJoy.cs +++ b/Assembly-CSharp/RimWorld/JobGiver_GetJoy.cs @@ -44,41 +44,35 @@ protected override Job TryGiveJob(Pawn pawn) { JoyGiverDef joyGiverDef = allDefsListForReading[i]; this.joyGiverChances[joyGiverDef] = 0f; - if (this.JoyGiverAllowed(joyGiverDef)) + if (this.JoyGiverAllowed(joyGiverDef) && joyGiverDef.Worker.MissingRequiredCapacity(pawn) == null) { - if (joyGiverDef.Worker.MissingRequiredCapacity(pawn) == null) + if (joyGiverDef.pctPawnsEverDo < 1.0) { - if (joyGiverDef.pctPawnsEverDo < 1f) + Rand.PushState(pawn.thingIDNumber ^ 63216713); + if (Rand.Value >= joyGiverDef.pctPawnsEverDo) { - Rand.PushState(pawn.thingIDNumber ^ 63216713); - if (Rand.Value >= joyGiverDef.pctPawnsEverDo) - { - Rand.PopState(); - goto IL_FB; - } Rand.PopState(); + continue; } - float num = joyGiverDef.Worker.GetChance(pawn); - float num2 = 1f - tolerances[joyGiverDef.joyKind]; - num *= num2 * num2; - this.joyGiverChances[joyGiverDef] = num; + Rand.PopState(); } + float chance = joyGiverDef.Worker.GetChance(pawn); + float num = (float)(1.0 - tolerances[joyGiverDef.joyKind]); + chance *= num * num; + this.joyGiverChances[joyGiverDef] = chance; } - IL_FB:; } - for (int j = 0; j < this.joyGiverChances.Count; j++) + int num2 = 0; + JoyGiverDef def = default(JoyGiverDef); + while (num2 < this.joyGiverChances.Count && ((IEnumerable)allDefsListForReading).TryRandomElementByWeight((Func)((JoyGiverDef d) => this.joyGiverChances[d]), out def)) { - JoyGiverDef def; - if (!allDefsListForReading.TryRandomElementByWeight((JoyGiverDef d) => this.joyGiverChances[d], out def)) - { - break; - } Job job = this.TryGiveJobFromJoyGiverDefDirect(def, pawn); if (job != null) { return job; } this.joyGiverChances[def] = 0f; + num2++; } return null; } diff --git a/Assembly-CSharp/RimWorld/JobGiver_GetJoyInBed.cs b/Assembly-CSharp/RimWorld/JobGiver_GetJoyInBed.cs index d131b981d..d2633ab8e 100644 --- a/Assembly-CSharp/RimWorld/JobGiver_GetJoyInBed.cs +++ b/Assembly-CSharp/RimWorld/JobGiver_GetJoyInBed.cs @@ -1,4 +1,3 @@ -using System; using Verse; using Verse.AI; @@ -28,16 +27,16 @@ protected override Job TryGiveJobFromJoyGiverDefDirect(JoyGiverDef def, Pawn paw protected override Job TryGiveJob(Pawn pawn) { - if (pawn.CurJob == null || pawn.CurrentBed() == null || !pawn.Awake() || pawn.needs.joy == null) + if (pawn.CurJob != null && pawn.CurrentBed() != null && pawn.Awake() && pawn.needs.joy != null) { - return null; + float curLevel = pawn.needs.joy.CurLevel; + if (curLevel > 0.5) + { + return null; + } + return base.TryGiveJob(pawn); } - float curLevel = pawn.needs.joy.CurLevel; - if (curLevel > 0.5f) - { - return null; - } - return base.TryGiveJob(pawn); + return null; } } } diff --git a/Assembly-CSharp/RimWorld/JobGiver_GetJoyInPartyArea.cs b/Assembly-CSharp/RimWorld/JobGiver_GetJoyInPartyArea.cs index 67e4ff5ce..c99d4a09c 100644 --- a/Assembly-CSharp/RimWorld/JobGiver_GetJoyInPartyArea.cs +++ b/Assembly-CSharp/RimWorld/JobGiver_GetJoyInPartyArea.cs @@ -1,4 +1,3 @@ -using System; using Verse; using Verse.AI; @@ -17,7 +16,7 @@ protected override Job TryGiveJobFromJoyGiverDefDirect(JoyGiverDef def, Pawn paw return null; } float curLevelPercentage = pawn.needs.joy.CurLevelPercentage; - if (curLevelPercentage > 0.92f) + if (curLevelPercentage > 0.92000001668930054) { return null; } diff --git a/Assembly-CSharp/RimWorld/JobGiver_GetRest.cs b/Assembly-CSharp/RimWorld/JobGiver_GetRest.cs index a7a2ede47..0129ffe41 100644 --- a/Assembly-CSharp/RimWorld/JobGiver_GetRest.cs +++ b/Assembly-CSharp/RimWorld/JobGiver_GetRest.cs @@ -23,7 +23,7 @@ public override float GetPriority(Pawn pawn) { return 0f; } - if (rest.CurCategory < this.minCategory) + if ((int)rest.CurCategory < (int)this.minCategory) { return 0f; } @@ -44,79 +44,58 @@ public override float GetPriority(Pawn pawn) else { int num = GenLocalDate.HourOfDay(pawn); - if (num < 7 || num > 21) - { - timeAssignmentDef = TimeAssignmentDefOf.Sleep; - } - else - { - timeAssignmentDef = TimeAssignmentDefOf.Anything; - } + timeAssignmentDef = ((num >= 7 && num <= 21) ? TimeAssignmentDefOf.Anything : TimeAssignmentDefOf.Sleep); } float curLevel = rest.CurLevel; if (timeAssignmentDef == TimeAssignmentDefOf.Anything) { - if (curLevel < 0.3f) + if (curLevel < 0.30000001192092896) { return 8f; } return 0f; } - else + if (timeAssignmentDef == TimeAssignmentDefOf.Work) { - if (timeAssignmentDef == TimeAssignmentDefOf.Work) - { - return 0f; - } - if (timeAssignmentDef == TimeAssignmentDefOf.Joy) + return 0f; + } + if (timeAssignmentDef == TimeAssignmentDefOf.Joy) + { + if (curLevel < 0.30000001192092896) { - if (curLevel < 0.3f) - { - return 8f; - } - return 0f; + return 8f; } - else + return 0f; + } + if (timeAssignmentDef == TimeAssignmentDefOf.Sleep) + { + if (curLevel < RestUtility.FallAsleepMaxLevel(pawn)) { - if (timeAssignmentDef != TimeAssignmentDefOf.Sleep) - { - throw new NotImplementedException(); - } - if (curLevel < RestUtility.FallAsleepMaxLevel(pawn)) - { - return 8f; - } - return 0f; + return 8f; } + return 0f; } + throw new NotImplementedException(); } protected override Job TryGiveJob(Pawn pawn) { Need_Rest rest = pawn.needs.rest; - if (rest == null || rest.CurCategory < this.minCategory) - { - return null; - } - if (RestUtility.DisturbancePreventsLyingDown(pawn)) - { - return null; - } - Lord lord = pawn.GetLord(); - Building_Bed building_Bed; - if (lord != null && lord.CurLordToil != null && !lord.CurLordToil.AllowRestingInBed) + if (rest != null && (int)rest.CurCategory >= (int)this.minCategory) { - building_Bed = null; - } - else - { - building_Bed = RestUtility.FindBedFor(pawn); - } - if (building_Bed != null) - { - return new Job(JobDefOf.LayDown, building_Bed); + if (RestUtility.DisturbancePreventsLyingDown(pawn)) + { + return null; + } + Lord lord = pawn.GetLord(); + Building_Bed building_Bed = (lord == null || lord.CurLordToil == null || lord.CurLordToil.AllowRestingInBed) ? RestUtility.FindBedFor(pawn) : null; + if (building_Bed != null) + { + return new Job(JobDefOf.LayDown, (Thing)building_Bed); + } + return new Job(JobDefOf.LayDown, this.FindGroundSleepSpotFor(pawn)); } - return new Job(JobDefOf.LayDown, this.FindGroundSleepSpotFor(pawn)); + return null; } private IntVec3 FindGroundSleepSpotFor(Pawn pawn) @@ -125,8 +104,8 @@ private IntVec3 FindGroundSleepSpotFor(Pawn pawn) for (int i = 0; i < 2; i++) { int radius = (i != 0) ? 12 : 4; - IntVec3 result; - if (CellFinder.TryRandomClosewalkCellNear(pawn.Position, map, radius, out result, (IntVec3 x) => !x.IsForbidden(pawn) && !x.GetTerrain(map).avoidWander)) + IntVec3 result = default(IntVec3); + if (CellFinder.TryRandomClosewalkCellNear(pawn.Position, map, radius, out result, (Predicate)((IntVec3 x) => !x.IsForbidden(pawn) && !x.GetTerrain(map).avoidWander))) { return result; } diff --git a/Assembly-CSharp/RimWorld/JobGiver_GotoTravelDestination.cs b/Assembly-CSharp/RimWorld/JobGiver_GotoTravelDestination.cs index 03d5e9cf9..83da4a3e7 100644 --- a/Assembly-CSharp/RimWorld/JobGiver_GotoTravelDestination.cs +++ b/Assembly-CSharp/RimWorld/JobGiver_GotoTravelDestination.cs @@ -1,4 +1,3 @@ -using System; using Verse; using Verse.AI; @@ -31,10 +30,9 @@ protected override Job TryGiveJob(Pawn pawn) pawn.mindState.nextMoveOrderIsWait = !pawn.mindState.nextMoveOrderIsWait; if (pawn.mindState.nextMoveOrderIsWait && !this.exactCell) { - return new Job(JobDefOf.WaitWander) - { - expiryInterval = this.WaitTicks.RandomInRange - }; + Job job = new Job(JobDefOf.WaitWander); + job.expiryInterval = this.WaitTicks.RandomInRange; + return job; } IntVec3 cell = pawn.mindState.duty.focus.Cell; if (!pawn.CanReach(cell, PathEndMode.OnCell, PawnUtility.ResolveMaxDanger(pawn, this.maxDanger), false, TraverseMode.ByPawn)) @@ -50,11 +48,10 @@ protected override Job TryGiveJob(Pawn pawn) { c = CellFinder.RandomClosewalkCellNear(cell, pawn.Map, 6, null); } - return new Job(JobDefOf.Goto, c) - { - locomotionUrgency = PawnUtility.ResolveLocomotion(pawn, this.locomotionUrgency), - expiryInterval = this.jobMaxDuration - }; + Job job2 = new Job(JobDefOf.Goto, c); + job2.locomotionUrgency = PawnUtility.ResolveLocomotion(pawn, this.locomotionUrgency); + job2.expiryInterval = this.jobMaxDuration; + return job2; } } } diff --git a/Assembly-CSharp/RimWorld/JobGiver_Haul.cs b/Assembly-CSharp/RimWorld/JobGiver_Haul.cs index a6222a7b2..1ba5a4958 100644 --- a/Assembly-CSharp/RimWorld/JobGiver_Haul.cs +++ b/Assembly-CSharp/RimWorld/JobGiver_Haul.cs @@ -8,10 +8,26 @@ public class JobGiver_Haul : ThinkNode_JobGiver { protected override Job TryGiveJob(Pawn pawn) { - Predicate validator = delegate(Thing t) + Predicate validator = (Predicate)delegate(Thing t) { - IntVec3 intVec; - return !t.IsForbidden(pawn) && HaulAIUtility.PawnCanAutomaticallyHaulFast(pawn, t, false) && pawn.carryTracker.MaxStackSpaceEver(t.def) > 0 && StoreUtility.TryFindBestBetterStoreCellFor(t, pawn, pawn.Map, HaulAIUtility.StoragePriorityAtFor(t.Position, t), pawn.Faction, out intVec, true); + if (t.IsForbidden(pawn)) + { + return false; + } + if (!HaulAIUtility.PawnCanAutomaticallyHaulFast(pawn, t, false)) + { + return false; + } + if (pawn.carryTracker.MaxStackSpaceEver(t.def) <= 0) + { + return false; + } + IntVec3 intVec = default(IntVec3); + if (!StoreUtility.TryFindBestBetterStoreCellFor(t, pawn, pawn.Map, HaulAIUtility.StoragePriorityAtFor(t.Position, t), pawn.Faction, out intVec, true)) + { + return false; + } + return true; }; Thing thing = GenClosest.ClosestThing_Global_Reachable(pawn.Position, pawn.Map, pawn.Map.listerHaulables.ThingsPotentiallyNeedingHauling(), PathEndMode.OnCell, TraverseParms.For(pawn, Danger.Deadly, TraverseMode.ByPawn, false), 9999f, validator, null); if (thing != null) diff --git a/Assembly-CSharp/RimWorld/JobGiver_HiveDefense.cs b/Assembly-CSharp/RimWorld/JobGiver_HiveDefense.cs index e1c9bcfa1..b38a8ede8 100644 --- a/Assembly-CSharp/RimWorld/JobGiver_HiveDefense.cs +++ b/Assembly-CSharp/RimWorld/JobGiver_HiveDefense.cs @@ -1,4 +1,3 @@ -using System; using Verse; using Verse.AI; diff --git a/Assembly-CSharp/RimWorld/JobGiver_IdleJoy.cs b/Assembly-CSharp/RimWorld/JobGiver_IdleJoy.cs index 14435158a..4339e2f47 100644 --- a/Assembly-CSharp/RimWorld/JobGiver_IdleJoy.cs +++ b/Assembly-CSharp/RimWorld/JobGiver_IdleJoy.cs @@ -1,4 +1,3 @@ -using System; using Verse; using Verse.AI; @@ -18,11 +17,11 @@ protected override Job TryGiveJob(Pawn pawn) { return null; } - if (JoyUtility.LordPreventsGettingJoy(pawn) || JoyUtility.TimetablePreventsGettingJoy(pawn)) + if (!JoyUtility.LordPreventsGettingJoy(pawn) && !JoyUtility.TimetablePreventsGettingJoy(pawn)) { - return null; + return base.TryGiveJob(pawn); } - return base.TryGiveJob(pawn); + return null; } } } diff --git a/Assembly-CSharp/RimWorld/JobGiver_KeepLyingDown.cs b/Assembly-CSharp/RimWorld/JobGiver_KeepLyingDown.cs index ace3747e8..38bfab834 100644 --- a/Assembly-CSharp/RimWorld/JobGiver_KeepLyingDown.cs +++ b/Assembly-CSharp/RimWorld/JobGiver_KeepLyingDown.cs @@ -1,4 +1,3 @@ -using System; using Verse; using Verse.AI; @@ -8,7 +7,7 @@ public class JobGiver_KeepLyingDown : ThinkNode_JobGiver { protected override Job TryGiveJob(Pawn pawn) { - if (pawn.CurJob != null && pawn.jobs.curDriver.layingDown != LayingDownState.NotLaying) + if (((pawn.CurJob != null) ? pawn.jobs.curDriver.layingDown : LayingDownState.NotLaying) != 0) { return pawn.CurJob; } diff --git a/Assembly-CSharp/RimWorld/JobGiver_Kidnap.cs b/Assembly-CSharp/RimWorld/JobGiver_Kidnap.cs index 5421f0c8a..61fd3ff56 100644 --- a/Assembly-CSharp/RimWorld/JobGiver_Kidnap.cs +++ b/Assembly-CSharp/RimWorld/JobGiver_Kidnap.cs @@ -1,4 +1,4 @@ -using System; +using System.Collections.Generic; using Verse; using Verse.AI; @@ -12,20 +12,19 @@ public class JobGiver_Kidnap : ThinkNode_JobGiver protected override Job TryGiveJob(Pawn pawn) { - IntVec3 c; + IntVec3 c = default(IntVec3); if (!RCellFinder.TryFindBestExitSpot(pawn, out c, TraverseMode.ByPawn)) { return null; } - Pawn t; - if (KidnapAIUtility.TryFindGoodKidnapVictim(pawn, 18f, out t, null) && !GenAI.InDangerousCombat(pawn)) + Pawn t = default(Pawn); + if (KidnapAIUtility.TryFindGoodKidnapVictim(pawn, 18f, out t, (List)null) && !GenAI.InDangerousCombat(pawn)) { - return new Job(JobDefOf.Kidnap) - { - targetA = t, - targetB = c, - count = 1 - }; + Job job = new Job(JobDefOf.Kidnap); + job.targetA = (Thing)t; + job.targetB = c; + job.count = 1; + return job; } return null; } diff --git a/Assembly-CSharp/RimWorld/JobGiver_LayEgg.cs b/Assembly-CSharp/RimWorld/JobGiver_LayEgg.cs index 175c0e218..c6300c4b8 100644 --- a/Assembly-CSharp/RimWorld/JobGiver_LayEgg.cs +++ b/Assembly-CSharp/RimWorld/JobGiver_LayEgg.cs @@ -1,4 +1,3 @@ -using System; using Verse; using Verse.AI; @@ -11,12 +10,12 @@ public class JobGiver_LayEgg : ThinkNode_JobGiver protected override Job TryGiveJob(Pawn pawn) { CompEggLayer compEggLayer = pawn.TryGetComp(); - if (compEggLayer == null || !compEggLayer.CanLayNow) + if (compEggLayer != null && compEggLayer.CanLayNow) { - return null; + IntVec3 c = RCellFinder.RandomWanderDestFor(pawn, pawn.Position, 5f, null, Danger.Some); + return new Job(JobDefOf.LayEgg, c); } - IntVec3 c = RCellFinder.RandomWanderDestFor(pawn, pawn.Position, 5f, null, Danger.Some); - return new Job(JobDefOf.LayEgg, c); + return null; } } } diff --git a/Assembly-CSharp/RimWorld/JobGiver_LoadTransporters.cs b/Assembly-CSharp/RimWorld/JobGiver_LoadTransporters.cs index 9216acdec..68ee4b7ca 100644 --- a/Assembly-CSharp/RimWorld/JobGiver_LoadTransporters.cs +++ b/Assembly-CSharp/RimWorld/JobGiver_LoadTransporters.cs @@ -1,4 +1,3 @@ -using System; using System.Collections.Generic; using Verse; using Verse.AI; diff --git a/Assembly-CSharp/RimWorld/JobGiver_MaintainHives.cs b/Assembly-CSharp/RimWorld/JobGiver_MaintainHives.cs index 2c4cce892..293d93e29 100644 --- a/Assembly-CSharp/RimWorld/JobGiver_MaintainHives.cs +++ b/Assembly-CSharp/RimWorld/JobGiver_MaintainHives.cs @@ -1,4 +1,3 @@ -using System; using Verse; using Verse.AI; @@ -15,18 +14,15 @@ protected override Job TryGiveJob(Pawn pawn) while ((float)num < JobGiver_MaintainHives.CellsInScanRadius) { IntVec3 intVec = pawn.Position + GenRadial.RadialPattern[num]; - if (intVec.InBounds(pawn.Map)) + if (intVec.InBounds(pawn.Map) && intVec.GetRoom(pawn.Map, RegionType.Set_Passable) == room) { - if (intVec.GetRoom(pawn.Map, RegionType.Set_Passable) == room) + Hive hive = (Hive)pawn.Map.thingGrid.ThingAt(intVec, ThingDefOf.Hive); + if (hive != null) { - Hive hive = (Hive)pawn.Map.thingGrid.ThingAt(intVec, ThingDefOf.Hive); - if (hive != null) + CompMaintainable compMaintainable = hive.TryGetComp(); + if (compMaintainable.CurStage != 0) { - CompMaintainable compMaintainable = hive.TryGetComp(); - if (compMaintainable.CurStage != MaintainableStage.Healthy) - { - return new Job(JobDefOf.Maintain, hive); - } + return new Job(JobDefOf.Maintain, (Thing)hive); } } } diff --git a/Assembly-CSharp/RimWorld/JobGiver_ManTurrets.cs b/Assembly-CSharp/RimWorld/JobGiver_ManTurrets.cs index 04b4f7940..68fb4bb64 100644 --- a/Assembly-CSharp/RimWorld/JobGiver_ManTurrets.cs +++ b/Assembly-CSharp/RimWorld/JobGiver_ManTurrets.cs @@ -17,31 +17,45 @@ public override ThinkNode DeepCopy(bool resolve = true) protected override Job TryGiveJob(Pawn pawn) { - Predicate validator = delegate(Thing t) + Predicate validator = (Predicate)delegate(Thing t) { if (!t.def.hasInteractionCell) { return false; } bool flag = false; - for (int i = 0; i < t.def.comps.Count; i++) + int num = 0; + while (num < t.def.comps.Count) { - if (t.def.comps[i].compClass == typeof(CompMannable)) + if (t.def.comps[num].compClass != typeof(CompMannable)) { - flag = true; - break; + num++; + continue; } + flag = true; + break; } - return flag && pawn.CanReserve(t, 1, -1, null, false) && JobDriver_ManTurret.FindAmmoForTurret(pawn, t) != null; + if (!flag) + { + return false; + } + if (!pawn.CanReserve(t, 1, -1, null, false)) + { + return false; + } + if (JobDriver_ManTurret.FindAmmoForTurret(pawn, t) == null) + { + return false; + } + return true; }; Thing thing = GenClosest.ClosestThingReachable(this.GetRoot(pawn), pawn.Map, ThingRequest.ForGroup(ThingRequestGroup.BuildingArtificial), PathEndMode.InteractionCell, TraverseParms.For(pawn, Danger.Deadly, TraverseMode.ByPawn, false), this.maxDistFromPoint, validator, null, 0, -1, false, RegionType.Set_Passable, false); if (thing != null) { - return new Job(JobDefOf.ManTurret, thing) - { - expiryInterval = 2000, - checkOverrideOnExpire = true - }; + Job job = new Job(JobDefOf.ManTurret, thing); + job.expiryInterval = 2000; + job.checkOverrideOnExpire = true; + return job; } return null; } diff --git a/Assembly-CSharp/RimWorld/JobGiver_ManTurretsNearPoint.cs b/Assembly-CSharp/RimWorld/JobGiver_ManTurretsNearPoint.cs index 0f16665fe..4480edb45 100644 --- a/Assembly-CSharp/RimWorld/JobGiver_ManTurretsNearPoint.cs +++ b/Assembly-CSharp/RimWorld/JobGiver_ManTurretsNearPoint.cs @@ -1,4 +1,3 @@ -using System; using Verse; using Verse.AI.Group; diff --git a/Assembly-CSharp/RimWorld/JobGiver_ManTurretsNearSelf.cs b/Assembly-CSharp/RimWorld/JobGiver_ManTurretsNearSelf.cs index 55268c897..639b2a13e 100644 --- a/Assembly-CSharp/RimWorld/JobGiver_ManTurretsNearSelf.cs +++ b/Assembly-CSharp/RimWorld/JobGiver_ManTurretsNearSelf.cs @@ -1,4 +1,3 @@ -using System; using Verse; namespace RimWorld diff --git a/Assembly-CSharp/RimWorld/JobGiver_Manhunter.cs b/Assembly-CSharp/RimWorld/JobGiver_Manhunter.cs index 7a7142e16..337effb30 100644 --- a/Assembly-CSharp/RimWorld/JobGiver_Manhunter.cs +++ b/Assembly-CSharp/RimWorld/JobGiver_Manhunter.cs @@ -23,7 +23,7 @@ protected override Job TryGiveJob(Pawn pawn) return null; } Pawn pawn2 = this.FindPawnTarget(pawn); - if (pawn2 != null && pawn.CanReach(pawn2, PathEndMode.Touch, Danger.Deadly, false, TraverseMode.ByPawn)) + if (pawn2 != null && pawn.CanReach((Thing)pawn2, PathEndMode.Touch, Danger.Deadly, false, TraverseMode.ByPawn)) { return this.MeleeAttackJob(pawn, pawn2); } @@ -36,27 +36,23 @@ protected override Job TryGiveJob(Pawn pawn) { using (PawnPath pawnPath = pawn.Map.pathFinder.FindPath(pawn.Position, pawn2.Position, TraverseParms.For(pawn, Danger.Deadly, TraverseMode.PassDoors, false), PathEndMode.OnCell)) { - Job result; if (!pawnPath.Found) { - result = null; - return result; + return null; } - IntVec3 loc; + IntVec3 loc = default(IntVec3); if (!pawnPath.TryFindLastCellBeforeBlockingDoor(pawn, out loc)) { Log.Error(pawn + " did TryFindLastCellBeforeDoor but found none when it should have been one. Target: " + pawn2.LabelCap); - result = null; - return result; + return null; } IntVec3 randomCell = CellFinder.RandomRegionNear(loc.GetRegion(pawn.Map, RegionType.Set_Passable), 9, TraverseParms.For(pawn, Danger.Deadly, TraverseMode.ByPawn, false), null, null, RegionType.Set_Passable).RandomCell; if (randomCell == pawn.Position) { - result = new Job(JobDefOf.Wait, 30, false); - return result; + return new Job(JobDefOf.Wait, 30, false); } - result = new Job(JobDefOf.Goto, randomCell); - return result; + return new Job(JobDefOf.Goto, randomCell); + IL_0127:; } } return null; @@ -64,22 +60,21 @@ protected override Job TryGiveJob(Pawn pawn) private Job MeleeAttackJob(Pawn pawn, Thing target) { - return new Job(JobDefOf.AttackMelee, target) - { - maxNumMeleeAttacks = 1, - expiryInterval = Rand.Range(420, 900), - attackDoorIfTargetLost = true - }; + Job job = new Job(JobDefOf.AttackMelee, target); + job.maxNumMeleeAttacks = 1; + job.expiryInterval = Rand.Range(420, 900); + job.attackDoorIfTargetLost = true; + return job; } private Pawn FindPawnTarget(Pawn pawn) { - return (Pawn)AttackTargetFinder.BestAttackTarget(pawn, TargetScanFlags.NeedThreat, (Thing x) => x is Pawn && x.def.race.intelligence >= Intelligence.ToolUser, 0f, 9999f, default(IntVec3), 3.40282347E+38f, true); + return (Pawn)AttackTargetFinder.BestAttackTarget(pawn, TargetScanFlags.NeedThreat, (Predicate)((Thing x) => x is Pawn && (int)x.def.race.intelligence >= 1), 0f, 9999f, default(IntVec3), 3.40282347E+38f, true); } private Building FindTurretTarget(Pawn pawn) { - return (Building)AttackTargetFinder.BestAttackTarget(pawn, TargetScanFlags.NeedLOSToPawns | TargetScanFlags.NeedLOSToNonPawns | TargetScanFlags.NeedReachable | TargetScanFlags.NeedThreat, (Thing t) => t is Building, 0f, 70f, default(IntVec3), 3.40282347E+38f, false); + return (Building)AttackTargetFinder.BestAttackTarget(pawn, TargetScanFlags.NeedLOSToPawns | TargetScanFlags.NeedLOSToNonPawns | TargetScanFlags.NeedReachable | TargetScanFlags.NeedThreat, (Predicate)((Thing t) => t is Building), 0f, 70f, default(IntVec3), 3.40282347E+38f, false); } } } diff --git a/Assembly-CSharp/RimWorld/JobGiver_MarryAdjacentPawn.cs b/Assembly-CSharp/RimWorld/JobGiver_MarryAdjacentPawn.cs index ec051f7ff..822371c69 100644 --- a/Assembly-CSharp/RimWorld/JobGiver_MarryAdjacentPawn.cs +++ b/Assembly-CSharp/RimWorld/JobGiver_MarryAdjacentPawn.cs @@ -17,7 +17,7 @@ protected override Job TryGiveJob(Pawn pawn) IntVec3 c = pawn.Position + GenAdj.CardinalDirections[i]; if (c.InBounds(pawn.Map)) { - Thing thing = c.GetThingList(pawn.Map).Find((Thing x) => x is Pawn && this.CanMarry(pawn, (Pawn)x)); + Thing thing = c.GetThingList(pawn.Map).Find((Predicate)((Thing x) => x is Pawn && this.CanMarry(pawn, (Pawn)x))); if (thing != null) { return new Job(JobDefOf.MarryAdjacentPawn, thing); diff --git a/Assembly-CSharp/RimWorld/JobGiver_Mate.cs b/Assembly-CSharp/RimWorld/JobGiver_Mate.cs index 5d1c57d33..915ad73df 100644 --- a/Assembly-CSharp/RimWorld/JobGiver_Mate.cs +++ b/Assembly-CSharp/RimWorld/JobGiver_Mate.cs @@ -8,21 +8,37 @@ public class JobGiver_Mate : ThinkNode_JobGiver { protected override Job TryGiveJob(Pawn pawn) { - if (pawn.gender != Gender.Male || !pawn.ageTracker.CurLifeStage.reproductive) + if (pawn.gender == Gender.Male && pawn.ageTracker.CurLifeStage.reproductive) { - return null; + Predicate validator = (Predicate)delegate(Thing t) + { + Pawn pawn3 = t as Pawn; + if (pawn3.Downed) + { + return false; + } + if (pawn3.CanCasuallyInteractNow(false) && !pawn3.IsForbidden(pawn)) + { + if (pawn3.Faction != pawn.Faction) + { + return false; + } + if (!PawnUtility.FertileMateTarget(pawn, pawn3)) + { + return false; + } + return true; + } + return false; + }; + Pawn pawn2 = (Pawn)GenClosest.ClosestThingReachable(pawn.Position, pawn.Map, ThingRequest.ForDef(pawn.def), PathEndMode.Touch, TraverseParms.For(pawn, Danger.Deadly, TraverseMode.ByPawn, false), 30f, validator, null, 0, -1, false, RegionType.Set_Passable, false); + if (pawn2 == null) + { + return null; + } + return new Job(JobDefOf.Mate, (Thing)pawn2); } - Predicate validator = delegate(Thing t) - { - Pawn pawn3 = t as Pawn; - return !pawn3.Downed && pawn3.CanCasuallyInteractNow(false) && !pawn3.IsForbidden(pawn) && pawn3.Faction == pawn.Faction && PawnUtility.FertileMateTarget(pawn, pawn3); - }; - Pawn pawn2 = (Pawn)GenClosest.ClosestThingReachable(pawn.Position, pawn.Map, ThingRequest.ForDef(pawn.def), PathEndMode.Touch, TraverseParms.For(pawn, Danger.Deadly, TraverseMode.ByPawn, false), 30f, validator, null, 0, -1, false, RegionType.Set_Passable, false); - if (pawn2 == null) - { - return null; - } - return new Job(JobDefOf.Mate, pawn2); + return null; } } } diff --git a/Assembly-CSharp/RimWorld/JobGiver_MineRandom.cs b/Assembly-CSharp/RimWorld/JobGiver_MineRandom.cs index e3bece823..b1df7a7fb 100644 --- a/Assembly-CSharp/RimWorld/JobGiver_MineRandom.cs +++ b/Assembly-CSharp/RimWorld/JobGiver_MineRandom.cs @@ -1,4 +1,3 @@ -using System; using Verse; using Verse.AI; @@ -20,12 +19,11 @@ protected override Job TryGiveJob(Pawn pawn) { IntVec3 c = randomCell + GenAdj.CardinalDirections[j]; Building edifice = c.GetEdifice(pawn.Map); - if (edifice != null && (edifice.def.passability == Traversability.Impassable || edifice.def.IsDoor) && edifice.def.size == IntVec2.One && edifice.def != ThingDefOf.CollapsedRocks && pawn.CanReserve(edifice, 1, -1, null, false)) + if (edifice != null && (edifice.def.passability == Traversability.Impassable || edifice.def.IsDoor) && edifice.def.size == IntVec2.One && edifice.def != ThingDefOf.CollapsedRocks && pawn.CanReserve((Thing)edifice, 1, -1, null, false)) { - return new Job(JobDefOf.Mine, edifice) - { - ignoreDesignations = true - }; + Job job = new Job(JobDefOf.Mine, (Thing)edifice); + job.ignoreDesignations = true; + return job; } } } diff --git a/Assembly-CSharp/RimWorld/JobGiver_Nuzzle.cs b/Assembly-CSharp/RimWorld/JobGiver_Nuzzle.cs index 2d0823af0..58be4b42d 100644 --- a/Assembly-CSharp/RimWorld/JobGiver_Nuzzle.cs +++ b/Assembly-CSharp/RimWorld/JobGiver_Nuzzle.cs @@ -12,23 +12,22 @@ public class JobGiver_Nuzzle : ThinkNode_JobGiver protected override Job TryGiveJob(Pawn pawn) { - if (pawn.RaceProps.nuzzleMtbHours <= 0f) + if (pawn.RaceProps.nuzzleMtbHours <= 0.0) { return null; } List source = pawn.Map.mapPawns.SpawnedPawnsInFaction(pawn.Faction); - Pawn t; + Pawn t = default(Pawn); if (!(from p in source where p.RaceProps.Humanlike && p.Position.InHorDistOf(pawn.Position, 15f) && pawn.GetRoom(RegionType.Set_Passable) == p.GetRoom(RegionType.Set_Passable) && !p.Position.IsForbidden(pawn) && p.CanCasuallyInteractNow(false) - select p).TryRandomElement(out t)) + select p).TryRandomElement(out t)) { return null; } - return new Job(JobDefOf.Nuzzle, t) - { - locomotionUrgency = LocomotionUrgency.Walk, - expiryInterval = 3000 - }; + Job job = new Job(JobDefOf.Nuzzle, (Thing)t); + job.locomotionUrgency = LocomotionUrgency.Walk; + job.expiryInterval = 3000; + return job; } } } diff --git a/Assembly-CSharp/RimWorld/JobGiver_OptimizeApparel.cs b/Assembly-CSharp/RimWorld/JobGiver_OptimizeApparel.cs index ac2c06d0b..a781a9503 100644 --- a/Assembly-CSharp/RimWorld/JobGiver_OptimizeApparel.cs +++ b/Assembly-CSharp/RimWorld/JobGiver_OptimizeApparel.cs @@ -1,4 +1,3 @@ -using System; using System.Collections.Generic; using System.Text; using UnityEngine; @@ -63,7 +62,7 @@ public class JobGiver_OptimizeApparel : ThinkNode_JobGiver private void SetNextOptimizeTick(Pawn pawn) { - pawn.mindState.nextApparelOptimizeTick = Find.TickManager.TicksGame + UnityEngine.Random.Range(6000, 9000); + pawn.mindState.nextApparelOptimizeTick = Find.TickManager.TicksGame + Random.Range(6000, 9000); } protected override Job TryGiveJob(Pawn pawn) @@ -88,28 +87,21 @@ protected override Job TryGiveJob(Pawn pawn) else { JobGiver_OptimizeApparel.debugSb = new StringBuilder(); - JobGiver_OptimizeApparel.debugSb.AppendLine(string.Concat(new object[] - { - "Scanning for ", - pawn, - " at ", - pawn.Position - })); + JobGiver_OptimizeApparel.debugSb.AppendLine("Scanning for " + pawn + " at " + pawn.Position); } Outfit currentOutfit = pawn.outfits.CurrentOutfit; List wornApparel = pawn.apparel.WornApparel; - for (int i = wornApparel.Count - 1; i >= 0; i--) + for (int num = wornApparel.Count - 1; num >= 0; num--) { - if (!currentOutfit.filter.Allows(wornApparel[i]) && pawn.outfits.forcedHandler.AllowedToAutomaticallyDrop(wornApparel[i])) + if (!currentOutfit.filter.Allows(wornApparel[num]) && pawn.outfits.forcedHandler.AllowedToAutomaticallyDrop(wornApparel[num])) { - return new Job(JobDefOf.RemoveApparel, wornApparel[i]) - { - haulDroppedApparel = true - }; + Job job = new Job(JobDefOf.RemoveApparel, (Thing)wornApparel[num]); + job.haulDroppedApparel = true; + return job; } } Thing thing = null; - float num = 0f; + float num2 = 0f; List list = pawn.Map.listerThings.ThingsInGroup(ThingRequestGroup.Apparel); if (list.Count == 0) { @@ -117,31 +109,23 @@ protected override Job TryGiveJob(Pawn pawn) return null; } JobGiver_OptimizeApparel.neededWarmth = PawnApparelGenerator.CalculateNeededWarmth(pawn, pawn.Map.Tile, GenLocalDate.Twelfth(pawn)); - for (int j = 0; j < list.Count; j++) + for (int i = 0; i < list.Count; i++) { - Apparel apparel = (Apparel)list[j]; + Apparel apparel = (Apparel)list[i]; if (currentOutfit.filter.Allows(apparel)) { - if (apparel.Map.slotGroupManager.SlotGroupAt(apparel.Position) != null) + SlotGroup slotGroup = apparel.Map.slotGroupManager.SlotGroupAt(apparel.Position); + if (slotGroup != null && !apparel.IsForbidden(pawn)) { - if (!apparel.IsForbidden(pawn)) + float num3 = JobGiver_OptimizeApparel.ApparelScoreGain(pawn, apparel); + if (DebugViewSettings.debugApparelOptimize) + { + JobGiver_OptimizeApparel.debugSb.AppendLine(apparel.LabelCap + ": " + num3.ToString("F2")); + } + if (!(num3 < 0.05000000074505806) && !(num3 < num2) && ApparelUtility.HasPartsToWear(pawn, apparel.def) && pawn.CanReserveAndReach((Thing)apparel, PathEndMode.OnCell, pawn.NormalMaxDanger(), 1, -1, null, false)) { - float num2 = JobGiver_OptimizeApparel.ApparelScoreGain(pawn, apparel); - if (DebugViewSettings.debugApparelOptimize) - { - JobGiver_OptimizeApparel.debugSb.AppendLine(apparel.LabelCap + ": " + num2.ToString("F2")); - } - if (num2 >= 0.05f && num2 >= num) - { - if (ApparelUtility.HasPartsToWear(pawn, apparel.def)) - { - if (pawn.CanReserveAndReach(apparel, PathEndMode.OnCell, pawn.NormalMaxDanger(), 1, -1, null, false)) - { - thing = apparel; - num = num2; - } - } - } + thing = apparel; + num2 = num3; } } } @@ -183,7 +167,7 @@ public static float ApparelScoreGain(Pawn pawn, Apparel ap) } if (!flag) { - num *= 10f; + num = (float)(num * 10.0); } return num; } @@ -208,25 +192,25 @@ public static float ApparelScoreRaw(Pawn pawn, Apparel ap) num *= num3; if (ap.WornByCorpse && (pawn == null || ThoughtUtility.CanGetThought(pawn, ThoughtDefOf.DeadMansApparel))) { - num -= 0.5f; - if (num > 0f) + num = (float)(num - 0.5); + if (num > 0.0) { - num *= 0.1f; + num = (float)(num * 0.10000000149011612); } } if (ap.Stuff == ThingDefOf.Human.race.leatherDef) { if (pawn == null || ThoughtUtility.CanGetThought(pawn, ThoughtDefOf.HumanLeatherApparelSad)) { - num -= 0.5f; - if (num > 0f) + num = (float)(num - 0.5); + if (num > 0.0) { - num *= 0.1f; + num = (float)(num * 0.10000000149011612); } } if (pawn != null && ThoughtUtility.CanGetThought(pawn, ThoughtDefOf.HumanLeatherApparelHappy)) { - num += 0.12f; + num = (float)(num + 0.11999999731779099); } } return num; diff --git a/Assembly-CSharp/RimWorld/JobGiver_PackFood.cs b/Assembly-CSharp/RimWorld/JobGiver_PackFood.cs index 365fb0d53..dd410152f 100644 --- a/Assembly-CSharp/RimWorld/JobGiver_PackFood.cs +++ b/Assembly-CSharp/RimWorld/JobGiver_PackFood.cs @@ -23,39 +23,38 @@ protected override Job TryGiveJob(Pawn pawn) for (int i = 0; i < innerContainer.Count; i++) { Thing thing = innerContainer[i]; - if (thing.def.ingestible != null && thing.def.ingestible.nutrition > 0.3f && thing.def.ingestible.preferability >= FoodPreferability.MealAwful && pawn.RaceProps.CanEverEat(thing)) + if (thing.def.ingestible != null && thing.def.ingestible.nutrition > 0.30000001192092896 && (int)thing.def.ingestible.preferability >= 5 && pawn.RaceProps.CanEverEat(thing)) { return null; } } - if (pawn.Map.resourceCounter.TotalHumanEdibleNutrition < (float)pawn.Map.mapPawns.ColonistsSpawnedCount * 1.5f) + if (pawn.Map.resourceCounter.TotalHumanEdibleNutrition < (float)pawn.Map.mapPawns.ColonistsSpawnedCount * 1.5) { return null; } - Thing thing2 = GenClosest.ClosestThing_Regionwise_ReachablePrioritized(pawn.Position, pawn.Map, ThingRequest.ForGroup(ThingRequestGroup.FoodSourceNotPlantOrTree), PathEndMode.ClosestTouch, TraverseParms.For(pawn, Danger.Deadly, TraverseMode.ByPawn, false), 20f, delegate(Thing t) + Thing thing2 = GenClosest.ClosestThing_Regionwise_ReachablePrioritized(pawn.Position, pawn.Map, ThingRequest.ForGroup(ThingRequestGroup.FoodSourceNotPlantOrTree), PathEndMode.ClosestTouch, TraverseParms.For(pawn, Danger.Deadly, TraverseMode.ByPawn, false), 20f, (Predicate)delegate(Thing t) { - if (t.def.category != ThingCategory.Item || t.def.ingestible == null || t.def.ingestible.nutrition < 0.3f || t.IsForbidden(pawn) || t is Corpse || !pawn.CanReserve(t, 1, -1, null, false) || !t.IsSociallyProper(pawn) || !pawn.RaceProps.CanEverEat(t)) + if (t.def.category == ThingCategory.Item && t.def.ingestible != null && !(t.def.ingestible.nutrition < 0.30000001192092896) && !t.IsForbidden(pawn) && !(t is Corpse) && pawn.CanReserve(t, 1, -1, null, false) && t.IsSociallyProper(pawn) && pawn.RaceProps.CanEverEat(t)) { - return false; - } - List list = FoodUtility.ThoughtsFromIngesting(pawn, t); - for (int j = 0; j < list.Count; j++) - { - if (list[j].stages[0].baseMoodEffect < 0f) + List list = FoodUtility.ThoughtsFromIngesting(pawn, t); + for (int j = 0; j < list.Count; j++) { - return false; + if (list[j].stages[0].baseMoodEffect < 0.0) + { + return false; + } } + return true; } - return true; - }, (Thing x) => FoodUtility.FoodSourceOptimality(pawn, x, 0f, false), 24, 30); + return false; + }, (Func)((Thing x) => FoodUtility.FoodSourceOptimality(pawn, x, 0f, false)), 24, 30); if (thing2 == null) { return null; } - return new Job(JobDefOf.TakeInventory, thing2) - { - count = 1 - }; + Job job = new Job(JobDefOf.TakeInventory, thing2); + job.count = 1; + return job; } } } diff --git a/Assembly-CSharp/RimWorld/JobGiver_PatientGoToBed.cs b/Assembly-CSharp/RimWorld/JobGiver_PatientGoToBed.cs index 08492a251..16d305443 100644 --- a/Assembly-CSharp/RimWorld/JobGiver_PatientGoToBed.cs +++ b/Assembly-CSharp/RimWorld/JobGiver_PatientGoToBed.cs @@ -1,4 +1,3 @@ -using System; using Verse; using Verse.AI; @@ -26,7 +25,7 @@ public override ThinkResult TryIssueJobPackage(Pawn pawn, JobIssueParams jobPara return ThinkResult.NoJob; } Job job = new Job(JobDefOf.LayDown, thing); - return new ThinkResult(job, this, null); + return new ThinkResult(job, this, default(JobTag?)); } } } diff --git a/Assembly-CSharp/RimWorld/JobGiver_PickUpOpportunisticWeapon.cs b/Assembly-CSharp/RimWorld/JobGiver_PickUpOpportunisticWeapon.cs index c21f6f745..f18402485 100644 --- a/Assembly-CSharp/RimWorld/JobGiver_PickUpOpportunisticWeapon.cs +++ b/Assembly-CSharp/RimWorld/JobGiver_PickUpOpportunisticWeapon.cs @@ -15,15 +15,18 @@ private float MinMeleeWeaponDamageThreshold { List verbs = ThingDefOf.Human.Verbs; float num = 0f; - for (int i = 0; i < verbs.Count; i++) + int num2 = 0; + while (num2 < verbs.Count) { - if (verbs[i].linkedBodyPartsGroup == BodyPartGroupDefOf.LeftHand || verbs[i].linkedBodyPartsGroup == BodyPartGroupDefOf.RightHand) + if (verbs[num2].linkedBodyPartsGroup != BodyPartGroupDefOf.LeftHand && verbs[num2].linkedBodyPartsGroup != BodyPartGroupDefOf.RightHand) { - num = (float)verbs[i].meleeDamageBaseAmount; - break; + num2++; + continue; } + num = (float)verbs[num2].meleeDamageBaseAmount; + break; } - return num + 3f; + return (float)(num + 3.0); } } @@ -52,11 +55,12 @@ protected override Job TryGiveJob(Pawn pawn) { return null; } - if (pawn.GetRegion(RegionType.Set_Passable) == null) + Region region = pawn.GetRegion(RegionType.Set_Passable); + if (region == null) { return null; } - Thing thing = GenClosest.ClosestThingReachable(pawn.Position, pawn.Map, ThingRequest.ForGroup(ThingRequestGroup.Weapon), PathEndMode.OnCell, TraverseParms.For(pawn, Danger.Deadly, TraverseMode.ByPawn, false), 8f, (Thing x) => pawn.CanReserve(x, 1, -1, null, false) && this.ShouldEquip(x, pawn), null, 0, 15, false, RegionType.Set_Passable, false); + Thing thing = GenClosest.ClosestThingReachable(pawn.Position, pawn.Map, ThingRequest.ForGroup(ThingRequestGroup.Weapon), PathEndMode.OnCell, TraverseParms.For(pawn, Danger.Deadly, TraverseMode.ByPawn, false), 8f, (Predicate)((Thing x) => pawn.CanReserve(x, 1, -1, null, false) && this.ShouldEquip(x, pawn)), null, 0, 15, false, RegionType.Set_Passable, false); if (thing != null) { return new Job(JobDefOf.Equip, thing); diff --git a/Assembly-CSharp/RimWorld/JobGiver_PrepareCaravan_GatherItems.cs b/Assembly-CSharp/RimWorld/JobGiver_PrepareCaravan_GatherItems.cs index 04dfce26d..03be34d7e 100644 --- a/Assembly-CSharp/RimWorld/JobGiver_PrepareCaravan_GatherItems.cs +++ b/Assembly-CSharp/RimWorld/JobGiver_PrepareCaravan_GatherItems.cs @@ -1,4 +1,3 @@ -using System; using Verse; using Verse.AI; using Verse.AI.Group; @@ -19,10 +18,9 @@ protected override Job TryGiveJob(Pawn pawn) { return null; } - return new Job(JobDefOf.PrepareCaravan_GatherItems, thing) - { - lord = lord - }; + Job job = new Job(JobDefOf.PrepareCaravan_GatherItems, thing); + job.lord = lord; + return job; } } } diff --git a/Assembly-CSharp/RimWorld/JobGiver_PrepareCaravan_GatherPawns.cs b/Assembly-CSharp/RimWorld/JobGiver_PrepareCaravan_GatherPawns.cs index e746d1f10..f0a4a5b0b 100644 --- a/Assembly-CSharp/RimWorld/JobGiver_PrepareCaravan_GatherPawns.cs +++ b/Assembly-CSharp/RimWorld/JobGiver_PrepareCaravan_GatherPawns.cs @@ -1,4 +1,3 @@ -using System; using Verse; using Verse.AI; using Verse.AI.Group; @@ -14,10 +13,9 @@ protected override Job TryGiveJob(Pawn pawn) { return null; } - return new Job(JobDefOf.PrepareCaravan_GatherPawns, pawn2) - { - lord = pawn.GetLord() - }; + Job job = new Job(JobDefOf.PrepareCaravan_GatherPawns, (Thing)pawn2); + job.lord = pawn.GetLord(); + return job; } private Pawn FindPawn(Pawn pawn) @@ -32,28 +30,13 @@ private Pawn FindPawn(Pawn pawn) for (int i = 0; i < lord.ownedPawns.Count; i++) { Pawn pawn3 = lord.ownedPawns[i]; - if (pawn3 != pawn) + if (pawn3 != pawn && !pawn3.IsColonist && (pawn.mindState.duty.pawnsToGather != PawnsToGather.Slaves || !pawn3.RaceProps.Animal) && (pawn.mindState.duty.pawnsToGather != PawnsToGather.Animals || pawn3.RaceProps.Animal) && !GatherAnimalsAndSlavesForCaravanUtility.IsFollowingAnyone(pawn3)) { - if (!pawn3.IsColonist) + float num2 = (float)pawn.Position.DistanceToSquared(pawn3.Position); + if ((pawn2 == null || num2 < num) && pawn.CanReserveAndReach((Thing)pawn3, PathEndMode.Touch, Danger.Deadly, 1, -1, null, false)) { - if (pawn.mindState.duty.pawnsToGather != PawnsToGather.Slaves || !pawn3.RaceProps.Animal) - { - if (pawn.mindState.duty.pawnsToGather != PawnsToGather.Animals || pawn3.RaceProps.Animal) - { - if (!GatherAnimalsAndSlavesForCaravanUtility.IsFollowingAnyone(pawn3)) - { - float num2 = (float)pawn.Position.DistanceToSquared(pawn3.Position); - if (pawn2 == null || num2 < num) - { - if (pawn.CanReserveAndReach(pawn3, PathEndMode.Touch, Danger.Deadly, 1, -1, null, false)) - { - pawn2 = pawn3; - num = num2; - } - } - } - } - } + pawn2 = pawn3; + num = num2; } } } diff --git a/Assembly-CSharp/RimWorld/JobGiver_PrisonerEscape.cs b/Assembly-CSharp/RimWorld/JobGiver_PrisonerEscape.cs index 796b024c2..4df85504a 100644 --- a/Assembly-CSharp/RimWorld/JobGiver_PrisonerEscape.cs +++ b/Assembly-CSharp/RimWorld/JobGiver_PrisonerEscape.cs @@ -1,4 +1,3 @@ -using System; using Verse; using Verse.AI; @@ -10,46 +9,53 @@ public class JobGiver_PrisonerEscape : ThinkNode_JobGiver protected override Job TryGiveJob(Pawn pawn) { - IntVec3 c; + IntVec3 c = default(IntVec3); if (this.ShouldStartEscaping(pawn) && RCellFinder.TryFindBestExitSpot(pawn, out c, TraverseMode.ByPawn)) { if (!pawn.guest.released) { - Messages.Message("MessagePrisonerIsEscaping".Translate(new object[] - { - pawn.NameStringShort - }), pawn, MessageSound.SeriousAlert); + Messages.Message("MessagePrisonerIsEscaping".Translate(pawn.NameStringShort), (Thing)pawn, MessageSound.SeriousAlert); } - return new Job(JobDefOf.Goto, c) - { - exitMapOnArrival = true - }; + Job job = new Job(JobDefOf.Goto, c); + job.exitMapOnArrival = true; + return job; } return null; } private bool ShouldStartEscaping(Pawn pawn) { - if (!pawn.guest.IsPrisoner || pawn.guest.HostFaction != Faction.OfPlayer || !pawn.guest.PrisonerIsSecure) - { - return false; - } - Room room = pawn.GetRoom(RegionType.Set_Passable); - if (room.TouchesMapEdge) - { - return true; - } - bool found = false; - RegionTraverser.BreadthFirstTraverse(room.Regions[0], (Region from, Region reg) => reg.portal == null || reg.portal.FreePassage, delegate(Region reg) + if (pawn.guest.IsPrisoner && pawn.guest.HostFaction == Faction.OfPlayer && pawn.guest.PrisonerIsSecure) { - if (reg.Room.TouchesMapEdge) + Room room = pawn.GetRoom(RegionType.Set_Passable); + if (room.TouchesMapEdge) + { + return true; + } + bool found = false; + RegionTraverser.BreadthFirstTraverse(room.Regions[0], (RegionEntryPredicate)delegate(Region from, Region reg) + { + if (reg.portal != null && !reg.portal.FreePassage) + { + return false; + } + return true; + }, (RegionProcessor)delegate(Region reg) + { + if (reg.Room.TouchesMapEdge) + { + found = true; + return true; + } + return false; + }, 25, RegionType.Set_Passable); + if (found) { - found = true; return true; } return false; - }, 25, RegionType.Set_Passable); - return found; + } + return false; } } } diff --git a/Assembly-CSharp/RimWorld/JobGiver_PrisonerGetDressed.cs b/Assembly-CSharp/RimWorld/JobGiver_PrisonerGetDressed.cs index 7d26ef476..2098c409b 100644 --- a/Assembly-CSharp/RimWorld/JobGiver_PrisonerGetDressed.cs +++ b/Assembly-CSharp/RimWorld/JobGiver_PrisonerGetDressed.cs @@ -1,4 +1,3 @@ -using System; using System.Collections.Generic; using Verse; using Verse.AI; @@ -16,10 +15,9 @@ protected override Job TryGiveJob(Pawn pawn) Apparel apparel = this.FindGarmentCoveringPart(pawn, BodyPartGroupDefOf.Legs); if (apparel != null) { - return new Job(JobDefOf.Wear, apparel) - { - ignoreForbidden = true - }; + Job job = new Job(JobDefOf.Wear, (Thing)apparel); + job.ignoreForbidden = true; + return job; } } if (!pawn.apparel.BodyPartGroupIsCovered(BodyPartGroupDefOf.Torso)) @@ -27,10 +25,9 @@ protected override Job TryGiveJob(Pawn pawn) Apparel apparel2 = this.FindGarmentCoveringPart(pawn, BodyPartGroupDefOf.Torso); if (apparel2 != null) { - return new Job(JobDefOf.Wear, apparel2) - { - ignoreForbidden = true - }; + Job job2 = new Job(JobDefOf.Wear, (Thing)apparel2); + job2.ignoreForbidden = true; + return job2; } } } @@ -42,13 +39,13 @@ private Apparel FindGarmentCoveringPart(Pawn pawn, BodyPartGroupDef bodyPartGrou Room room = pawn.GetRoom(RegionType.Set_Passable); if (room.isPrisonCell) { - foreach (IntVec3 current in room.Cells) + foreach (IntVec3 cell in room.Cells) { - List thingList = current.GetThingList(pawn.Map); + List thingList = cell.GetThingList(pawn.Map); for (int i = 0; i < thingList.Count; i++) { Apparel apparel = thingList[i] as Apparel; - if (apparel != null && apparel.def.apparel.bodyPartGroups.Contains(bodyPartGroupDef) && pawn.CanReserve(apparel, 1, -1, null, false) && ApparelUtility.HasPartsToWear(pawn, apparel.def)) + if (apparel != null && apparel.def.apparel.bodyPartGroups.Contains(bodyPartGroupDef) && pawn.CanReserve((Thing)apparel, 1, -1, null, false) && ApparelUtility.HasPartsToWear(pawn, apparel.def)) { return apparel; } diff --git a/Assembly-CSharp/RimWorld/JobGiver_PrisonerWaitInsteadOfEscaping.cs b/Assembly-CSharp/RimWorld/JobGiver_PrisonerWaitInsteadOfEscaping.cs index 924f296aa..04afae7cf 100644 --- a/Assembly-CSharp/RimWorld/JobGiver_PrisonerWaitInsteadOfEscaping.cs +++ b/Assembly-CSharp/RimWorld/JobGiver_PrisonerWaitInsteadOfEscaping.cs @@ -1,4 +1,3 @@ -using System; using Verse; using Verse.AI; @@ -8,20 +7,20 @@ public class JobGiver_PrisonerWaitInsteadOfEscaping : JobGiver_Wander { protected override Job TryGiveJob(Pawn pawn) { - if (pawn.guest == null || !pawn.guest.ShouldWaitInsteadOfEscaping) + if (pawn.guest != null && pawn.guest.ShouldWaitInsteadOfEscaping) { - return null; - } - IntVec3 spotToWaitInsteadOfEscaping = pawn.guest.spotToWaitInsteadOfEscaping; - if (!spotToWaitInsteadOfEscaping.IsValid || !pawn.CanReach(spotToWaitInsteadOfEscaping, PathEndMode.OnCell, Danger.Deadly, false, TraverseMode.ByPawn)) - { - if (!RCellFinder.TryFindRandomSpotJustOutsideColony(pawn, out spotToWaitInsteadOfEscaping)) + IntVec3 spotToWaitInsteadOfEscaping = pawn.guest.spotToWaitInsteadOfEscaping; + if (!spotToWaitInsteadOfEscaping.IsValid || !pawn.CanReach(spotToWaitInsteadOfEscaping, PathEndMode.OnCell, Danger.Deadly, false, TraverseMode.ByPawn)) { - return null; + if (!RCellFinder.TryFindRandomSpotJustOutsideColony(pawn, out spotToWaitInsteadOfEscaping)) + { + return null; + } + pawn.guest.spotToWaitInsteadOfEscaping = spotToWaitInsteadOfEscaping; } - pawn.guest.spotToWaitInsteadOfEscaping = spotToWaitInsteadOfEscaping; + return base.TryGiveJob(pawn); } - return base.TryGiveJob(pawn); + return null; } protected override IntVec3 GetWanderRoot(Pawn pawn) diff --git a/Assembly-CSharp/RimWorld/JobGiver_ReactToCloseMeleeThreat.cs b/Assembly-CSharp/RimWorld/JobGiver_ReactToCloseMeleeThreat.cs index b3a25ac6b..7c7c8fb81 100644 --- a/Assembly-CSharp/RimWorld/JobGiver_ReactToCloseMeleeThreat.cs +++ b/Assembly-CSharp/RimWorld/JobGiver_ReactToCloseMeleeThreat.cs @@ -1,4 +1,3 @@ -using System; using Verse; using Verse.AI; @@ -36,11 +35,10 @@ protected override Job TryGiveJob(Pawn pawn) { return null; } - return new Job(JobDefOf.AttackMelee, meleeThreat) - { - maxNumMeleeAttacks = 1, - expiryInterval = 200 - }; + Job job = new Job(JobDefOf.AttackMelee, (Thing)meleeThreat); + job.maxNumMeleeAttacks = 1; + job.expiryInterval = 200; + return job; } private bool IsHunting(Pawn pawn, Pawn prey) @@ -55,7 +53,11 @@ private bool IsHunting(Pawn pawn, Pawn prey) return jobDriver_Hunt.Victim == prey; } JobDriver_PredatorHunt jobDriver_PredatorHunt = pawn.jobs.curDriver as JobDriver_PredatorHunt; - return jobDriver_PredatorHunt != null && jobDriver_PredatorHunt.Prey == prey; + if (jobDriver_PredatorHunt != null) + { + return jobDriver_PredatorHunt.Prey == prey; + } + return false; } } } diff --git a/Assembly-CSharp/RimWorld/JobGiver_RescueNearby.cs b/Assembly-CSharp/RimWorld/JobGiver_RescueNearby.cs index 2421ed962..e14436240 100644 --- a/Assembly-CSharp/RimWorld/JobGiver_RescueNearby.cs +++ b/Assembly-CSharp/RimWorld/JobGiver_RescueNearby.cs @@ -19,10 +19,14 @@ public override ThinkNode DeepCopy(bool resolve = true) protected override Job TryGiveJob(Pawn pawn) { - Predicate validator = delegate(Thing t) + Predicate validator = (Predicate)delegate(Thing t) { Pawn pawn3 = (Pawn)t; - return pawn3.Downed && pawn3.Faction == pawn.Faction && !pawn3.InBed() && pawn.CanReserve(pawn3, 1, -1, null, false) && !pawn3.IsForbidden(pawn) && !GenAI.EnemyIsNear(pawn3, 25f); + if (pawn3.Downed && pawn3.Faction == pawn.Faction && !pawn3.InBed() && pawn.CanReserve((Thing)pawn3, 1, -1, null, false) && !pawn3.IsForbidden(pawn) && !GenAI.EnemyIsNear(pawn3, 25f)) + { + return true; + } + return false; }; Pawn pawn2 = (Pawn)GenClosest.ClosestThingReachable(pawn.Position, pawn.Map, ThingRequest.ForGroup(ThingRequestGroup.Pawn), PathEndMode.OnCell, TraverseParms.For(pawn, Danger.Deadly, TraverseMode.ByPawn, false), this.radius, validator, null, 0, -1, false, RegionType.Set_Passable, false); if (pawn2 == null) @@ -30,14 +34,13 @@ protected override Job TryGiveJob(Pawn pawn) return null; } Building_Bed building_Bed = RestUtility.FindBedFor(pawn2, pawn, pawn2.HostFaction == pawn.Faction, false, false); - if (building_Bed == null || !pawn2.CanReserve(building_Bed, 1, -1, null, false)) + if (building_Bed != null && pawn2.CanReserve((Thing)building_Bed, 1, -1, null, false)) { - return null; + Job job = new Job(JobDefOf.Rescue, (Thing)pawn2, (Thing)building_Bed); + job.count = 1; + return job; } - return new Job(JobDefOf.Rescue, pawn2, building_Bed) - { - count = 1 - }; + return null; } } } diff --git a/Assembly-CSharp/RimWorld/JobGiver_SatisfyChemicalNeed.cs b/Assembly-CSharp/RimWorld/JobGiver_SatisfyChemicalNeed.cs index 5425ba031..8c2f680ad 100644 --- a/Assembly-CSharp/RimWorld/JobGiver_SatisfyChemicalNeed.cs +++ b/Assembly-CSharp/RimWorld/JobGiver_SatisfyChemicalNeed.cs @@ -11,7 +11,7 @@ public class JobGiver_SatisfyChemicalNeed : ThinkNode_JobGiver public override float GetPriority(Pawn pawn) { - if (pawn.needs.AllNeeds.Any((Need x) => this.ShouldSatisfy(x))) + if (pawn.needs.AllNeeds.Any((Predicate)((Need x) => this.ShouldSatisfy(x)))) { return 9.25f; } @@ -29,11 +29,11 @@ protected override Job TryGiveJob(Pawn pawn) JobGiver_SatisfyChemicalNeed.tmpChemicalNeeds.Add((Need_Chemical)allNeeds[i]); } } - if (!JobGiver_SatisfyChemicalNeed.tmpChemicalNeeds.Any()) + if (!JobGiver_SatisfyChemicalNeed.tmpChemicalNeeds.Any()) { return null; } - JobGiver_SatisfyChemicalNeed.tmpChemicalNeeds.SortBy((Need_Chemical x) => x.CurLevel); + JobGiver_SatisfyChemicalNeed.tmpChemicalNeeds.SortBy((Func)((Need_Chemical x) => x.CurLevel)); for (int j = 0; j < JobGiver_SatisfyChemicalNeed.tmpChemicalNeeds.Count; j++) { Thing thing = this.FindDrugFor(pawn, JobGiver_SatisfyChemicalNeed.tmpChemicalNeeds[j]); @@ -50,7 +50,11 @@ protected override Job TryGiveJob(Pawn pawn) private bool ShouldSatisfy(Need need) { Need_Chemical need_Chemical = need as Need_Chemical; - return need_Chemical != null && need_Chemical.CurCategory <= DrugDesireCategory.Desire; + if (need_Chemical != null && (int)need_Chemical.CurCategory <= 1) + { + return true; + } + return false; } private Thing FindDrugFor(Pawn pawn, Need_Chemical need) @@ -68,7 +72,7 @@ private Thing FindDrugFor(Pawn pawn, Need_Chemical need) return innerContainer[i]; } } - Predicate validator = (Thing x) => this.DrugValidator(pawn, addictionHediff, x); + Predicate validator = (Predicate)((Thing x) => this.DrugValidator(pawn, addictionHediff, x)); return GenClosest.ClosestThingReachable(pawn.Position, pawn.Map, ThingRequest.ForGroup(ThingRequestGroup.Drug), PathEndMode.ClosestTouch, TraverseParms.For(pawn, Danger.Deadly, TraverseMode.ByPawn, false), 9999f, validator, null, 0, -1, false, RegionType.Set_Passable, false); } @@ -94,23 +98,23 @@ private bool DrugValidator(Pawn pawn, Hediff_Addiction addiction, Thing drug) } } CompDrug compDrug = drug.TryGetComp(); - if (compDrug == null || compDrug.Props.chemical == null) - { - return false; - } - if (compDrug.Props.chemical.addictionHediff != addiction.def) + if (compDrug != null && compDrug.Props.chemical != null) { - return false; - } - if (pawn.drugs != null && !pawn.drugs.CurrentPolicy[drug.def].allowedForAddiction && pawn.story != null) - { - int num = pawn.story.traits.DegreeOfTrait(TraitDefOf.DrugDesire); - if (num <= 0 && !pawn.InMentalState) + if (compDrug.Props.chemical.addictionHediff != addiction.def) { return false; } + if (pawn.drugs != null && !pawn.drugs.CurrentPolicy[drug.def].allowedForAddiction && pawn.story != null) + { + int num = pawn.story.traits.DegreeOfTrait(TraitDefOf.DrugDesire); + if (num <= 0 && !pawn.InMentalState) + { + return false; + } + } + return true; } - return true; + return false; } } } diff --git a/Assembly-CSharp/RimWorld/JobGiver_SeekAllowedArea.cs b/Assembly-CSharp/RimWorld/JobGiver_SeekAllowedArea.cs index c4e3454ae..2a7e27b3f 100644 --- a/Assembly-CSharp/RimWorld/JobGiver_SeekAllowedArea.cs +++ b/Assembly-CSharp/RimWorld/JobGiver_SeekAllowedArea.cs @@ -18,9 +18,9 @@ protected override Job TryGiveJob(Pawn pawn) return null; } TraverseParms traverseParms = TraverseParms.For(pawn, Danger.Deadly, TraverseMode.ByPawn, false); - RegionEntryPredicate entryCondition = (Region from, Region r) => r.Allows(traverseParms, false); + RegionEntryPredicate entryCondition = (RegionEntryPredicate)((Region from, Region r) => r.Allows(traverseParms, false)); Region reg = null; - RegionProcessor regionProcessor = delegate(Region r) + RegionProcessor regionProcessor = (RegionProcessor)delegate(Region r) { if (r.portal != null) { @@ -34,16 +34,16 @@ protected override Job TryGiveJob(Pawn pawn) return false; }; RegionTraverser.BreadthFirstTraverse(region, entryCondition, regionProcessor, 9999, RegionType.Set_Passable); - if (reg == null) + if (reg != null) { - return null; - } - IntVec3 c; - if (!reg.TryFindRandomCellInRegionUnforbidden(pawn, null, out c)) - { - return null; + IntVec3 c = default(IntVec3); + if (!reg.TryFindRandomCellInRegionUnforbidden(pawn, (Predicate)null, out c)) + { + return null; + } + return new Job(JobDefOf.Goto, c); } - return new Job(JobDefOf.Goto, c); + return null; } } } diff --git a/Assembly-CSharp/RimWorld/JobGiver_SeekSafeTemperature.cs b/Assembly-CSharp/RimWorld/JobGiver_SeekSafeTemperature.cs index 895d18791..16f5fa6d3 100644 --- a/Assembly-CSharp/RimWorld/JobGiver_SeekSafeTemperature.cs +++ b/Assembly-CSharp/RimWorld/JobGiver_SeekSafeTemperature.cs @@ -1,4 +1,3 @@ -using System; using Verse; using Verse.AI; @@ -32,9 +31,9 @@ private static Region ClosestRegionWithinTemperatureRange(IntVec3 root, Map map, { return null; } - RegionEntryPredicate entryCondition = (Region from, Region r) => r.Allows(traverseParms, false); + RegionEntryPredicate entryCondition = (RegionEntryPredicate)((Region from, Region r) => r.Allows(traverseParms, false)); Region foundReg = null; - RegionProcessor regionProcessor = delegate(Region r) + RegionProcessor regionProcessor = (RegionProcessor)delegate(Region r) { if (r.portal != null) { diff --git a/Assembly-CSharp/RimWorld/JobGiver_SocialFighting.cs b/Assembly-CSharp/RimWorld/JobGiver_SocialFighting.cs index 3c193aa44..48590e3d1 100644 --- a/Assembly-CSharp/RimWorld/JobGiver_SocialFighting.cs +++ b/Assembly-CSharp/RimWorld/JobGiver_SocialFighting.cs @@ -1,4 +1,3 @@ -using System; using Verse; using Verse.AI; @@ -13,16 +12,15 @@ protected override Job TryGiveJob(Pawn pawn) return null; } Pawn otherPawn = ((MentalState_SocialFighting)pawn.MentalState).otherPawn; - Verb verbToUse; + Verb verbToUse = default(Verb); if (!InteractionUtility.TryGetRandomVerbForSocialFight(pawn, out verbToUse)) { return null; } - return new Job(JobDefOf.SocialFight, otherPawn) - { - maxNumMeleeAttacks = 1, - verbToUse = verbToUse - }; + Job job = new Job(JobDefOf.SocialFight, (Thing)otherPawn); + job.maxNumMeleeAttacks = 1; + job.verbToUse = verbToUse; + return job; } } } diff --git a/Assembly-CSharp/RimWorld/JobGiver_SpectateDutySpectateRect.cs b/Assembly-CSharp/RimWorld/JobGiver_SpectateDutySpectateRect.cs index 116edce5c..358f14475 100644 --- a/Assembly-CSharp/RimWorld/JobGiver_SpectateDutySpectateRect.cs +++ b/Assembly-CSharp/RimWorld/JobGiver_SpectateDutySpectateRect.cs @@ -1,4 +1,4 @@ -using System; +using System.Collections.Generic; using Verse; using Verse.AI; @@ -13,16 +13,16 @@ protected override Job TryGiveJob(Pawn pawn) { return null; } - IntVec3 c; - if (!SpectatorCellFinder.TryFindSpectatorCellFor(pawn, duty.spectateRect, pawn.Map, out c, duty.spectateRectAllowedSides, 1, null)) + IntVec3 c = default(IntVec3); + if (!SpectatorCellFinder.TryFindSpectatorCellFor(pawn, duty.spectateRect, pawn.Map, out c, duty.spectateRectAllowedSides, 1, (List)null)) { return null; } IntVec3 centerCell = duty.spectateRect.CenterCell; Building edifice = c.GetEdifice(pawn.Map); - if (edifice != null && edifice.def.category == ThingCategory.Building && edifice.def.building.isSittable && pawn.CanReserve(edifice, 1, -1, null, false)) + if (edifice != null && edifice.def.category == ThingCategory.Building && edifice.def.building.isSittable && pawn.CanReserve((Thing)edifice, 1, -1, null, false)) { - return new Job(JobDefOf.SpectateCeremony, edifice, centerCell); + return new Job(JobDefOf.SpectateCeremony, (Thing)edifice, centerCell); } return new Job(JobDefOf.SpectateCeremony, c, centerCell); } diff --git a/Assembly-CSharp/RimWorld/JobGiver_StandAndBeSociallyActive.cs b/Assembly-CSharp/RimWorld/JobGiver_StandAndBeSociallyActive.cs index c601c8da1..fc09152f6 100644 --- a/Assembly-CSharp/RimWorld/JobGiver_StandAndBeSociallyActive.cs +++ b/Assembly-CSharp/RimWorld/JobGiver_StandAndBeSociallyActive.cs @@ -1,4 +1,3 @@ -using System; using Verse; using Verse.AI; @@ -17,10 +16,9 @@ public override ThinkNode DeepCopy(bool resolve = true) protected override Job TryGiveJob(Pawn pawn) { - return new Job(JobDefOf.StandAndBeSociallyActive) - { - expiryInterval = this.ticksRange.RandomInRange - }; + Job job = new Job(JobDefOf.StandAndBeSociallyActive); + job.expiryInterval = this.ticksRange.RandomInRange; + return job; } } } diff --git a/Assembly-CSharp/RimWorld/JobGiver_Steal.cs b/Assembly-CSharp/RimWorld/JobGiver_Steal.cs index 6a29134d9..bac10d387 100644 --- a/Assembly-CSharp/RimWorld/JobGiver_Steal.cs +++ b/Assembly-CSharp/RimWorld/JobGiver_Steal.cs @@ -1,4 +1,4 @@ -using System; +using System.Collections.Generic; using UnityEngine; using Verse; using Verse.AI; @@ -13,20 +13,19 @@ public class JobGiver_Steal : ThinkNode_JobGiver protected override Job TryGiveJob(Pawn pawn) { - IntVec3 c; + IntVec3 c = default(IntVec3); if (!RCellFinder.TryFindBestExitSpot(pawn, out c, TraverseMode.ByPawn)) { return null; } - Thing thing; - if (StealAIUtility.TryFindBestItemToSteal(pawn.Position, pawn.Map, 12f, out thing, pawn, null) && !GenAI.InDangerousCombat(pawn)) + Thing thing = default(Thing); + if (StealAIUtility.TryFindBestItemToSteal(pawn.Position, pawn.Map, 12f, out thing, pawn, (List)null) && !GenAI.InDangerousCombat(pawn)) { - return new Job(JobDefOf.Steal) - { - targetA = thing, - targetB = c, - count = Mathf.Min(thing.stackCount, (int)(pawn.GetStatValue(StatDefOf.CarryingCapacity, true) / thing.def.VolumePerUnit)) - }; + Job job = new Job(JobDefOf.Steal); + job.targetA = thing; + job.targetB = c; + job.count = Mathf.Min(thing.stackCount, (int)(pawn.GetStatValue(StatDefOf.CarryingCapacity, true) / thing.def.VolumePerUnit)); + return job; } return null; } diff --git a/Assembly-CSharp/RimWorld/JobGiver_TakeCombatEnhancingDrug.cs b/Assembly-CSharp/RimWorld/JobGiver_TakeCombatEnhancingDrug.cs index 816ca05d8..cd0383928 100644 --- a/Assembly-CSharp/RimWorld/JobGiver_TakeCombatEnhancingDrug.cs +++ b/Assembly-CSharp/RimWorld/JobGiver_TakeCombatEnhancingDrug.cs @@ -1,4 +1,3 @@ -using System; using UnityEngine; using Verse; using Verse.AI; @@ -54,9 +53,7 @@ protected override Job TryGiveJob(Pawn pawn) { num++; if (num >= num2) - { break; - } } } if (num < num2) @@ -65,10 +62,9 @@ protected override Job TryGiveJob(Pawn pawn) } } } - return new Job(JobDefOf.Ingest, thing) - { - count = 1 - }; + Job job = new Job(JobDefOf.Ingest, thing); + job.count = 1; + return job; } private bool HarmedRecently(Pawn pawn) @@ -82,12 +78,9 @@ private Thing FindCombatEnhancingDrug(Pawn pawn) { Thing thing = pawn.inventory.innerContainer[i]; CompDrug compDrug = thing.TryGetComp(); - if (compDrug != null) + if (compDrug != null && compDrug.Props.isCombatEnhancingDrug) { - if (compDrug.Props.isCombatEnhancingDrug) - { - return thing; - } + return thing; } } return null; diff --git a/Assembly-CSharp/RimWorld/JobGiver_TakeDrugsForDrugPolicy.cs b/Assembly-CSharp/RimWorld/JobGiver_TakeDrugsForDrugPolicy.cs index b336f724e..a424c8f69 100644 --- a/Assembly-CSharp/RimWorld/JobGiver_TakeDrugsForDrugPolicy.cs +++ b/Assembly-CSharp/RimWorld/JobGiver_TakeDrugsForDrugPolicy.cs @@ -46,7 +46,7 @@ private Thing FindDrugFor(Pawn pawn, ThingDef drugDef) return innerContainer[i]; } } - Predicate validator = (Thing x) => this.DrugValidator(pawn, x); + Predicate validator = (Predicate)((Thing x) => this.DrugValidator(pawn, x)); return GenClosest.ClosestThingReachable(pawn.Position, pawn.Map, ThingRequest.ForDef(drugDef), PathEndMode.ClosestTouch, TraverseParms.For(pawn, Danger.Deadly, TraverseMode.ByPawn, false), 9999f, validator, null, 0, -1, false, RegionType.Set_Passable, false); } diff --git a/Assembly-CSharp/RimWorld/JobGiver_TakeWoundedGuest.cs b/Assembly-CSharp/RimWorld/JobGiver_TakeWoundedGuest.cs index 55fb3817a..ca16d8069 100644 --- a/Assembly-CSharp/RimWorld/JobGiver_TakeWoundedGuest.cs +++ b/Assembly-CSharp/RimWorld/JobGiver_TakeWoundedGuest.cs @@ -1,4 +1,3 @@ -using System; using Verse; using Verse.AI; @@ -8,7 +7,7 @@ public class JobGiver_TakeWoundedGuest : ThinkNode_JobGiver { protected override Job TryGiveJob(Pawn pawn) { - IntVec3 c; + IntVec3 c = default(IntVec3); if (!RCellFinder.TryFindBestExitSpot(pawn, out c, TraverseMode.ByPawn)) { return null; @@ -18,12 +17,11 @@ protected override Job TryGiveJob(Pawn pawn) { return null; } - return new Job(JobDefOf.Kidnap) - { - targetA = pawn2, - targetB = c, - count = 1 - }; + Job job = new Job(JobDefOf.Kidnap); + job.targetA = (Thing)pawn2; + job.targetB = c; + job.count = 1; + return job; } } } diff --git a/Assembly-CSharp/RimWorld/JobGiver_UnloadYourInventory.cs b/Assembly-CSharp/RimWorld/JobGiver_UnloadYourInventory.cs index a83fc06ec..00385002d 100644 --- a/Assembly-CSharp/RimWorld/JobGiver_UnloadYourInventory.cs +++ b/Assembly-CSharp/RimWorld/JobGiver_UnloadYourInventory.cs @@ -1,4 +1,3 @@ -using System; using Verse; using Verse.AI; diff --git a/Assembly-CSharp/RimWorld/JobGiver_WanderColony.cs b/Assembly-CSharp/RimWorld/JobGiver_WanderColony.cs index d13683dff..2100bbc78 100644 --- a/Assembly-CSharp/RimWorld/JobGiver_WanderColony.cs +++ b/Assembly-CSharp/RimWorld/JobGiver_WanderColony.cs @@ -12,9 +12,9 @@ public class JobGiver_WanderColony : JobGiver_Wander public JobGiver_WanderColony() { - this.wanderRadius = 7f; - this.ticksBetweenWandersRange = new IntRange(125, 200); - this.wanderDestValidator = ((Pawn pawn, IntVec3 loc) => true); + base.wanderRadius = 7f; + base.ticksBetweenWandersRange = new IntRange(125, 200); + base.wanderDestValidator = (Func)((Pawn pawn, IntVec3 loc) => true); } protected override IntVec3 GetWanderRoot(Pawn pawn) @@ -32,44 +32,47 @@ protected override IntVec3 GetWanderRoot(Pawn pawn) } if (JobGiver_WanderColony.gatherSpots.Count > 0) { - return JobGiver_WanderColony.gatherSpots.RandomElement(); + return JobGiver_WanderColony.gatherSpots.RandomElement(); } } List allBuildingsColonist = pawn.Map.listerBuildings.allBuildingsColonist; - if (allBuildingsColonist.Count != 0) + if (allBuildingsColonist.Count == 0) { - int num = 0; - while (true) + Pawn pawn2 = default(Pawn); + if ((from c in pawn.Map.mapPawns.FreeColonistsSpawned + where !c.Position.IsForbidden(pawn) && pawn.CanReach(c.Position, PathEndMode.Touch, Danger.None, false, TraverseMode.ByPawn) + select c).TryRandomElement(out pawn2)) { - num++; - if (num > 20) - { - break; - } - Building building = allBuildingsColonist.RandomElement(); - if (!building.Position.IsForbidden(pawn) && pawn.Map.areaManager.Home[building.Position]) - { - int num2 = 15 + num * 2; - if ((pawn.Position - building.Position).LengthHorizontalSquared <= num2 * num2) - { - IntVec3 intVec = GenAdjFast.AdjacentCells8Way(building).RandomElement(); - if (intVec.Standable(building.Map) && !intVec.IsForbidden(pawn) && pawn.CanReach(intVec, PathEndMode.OnCell, Danger.None, false, TraverseMode.ByPawn) && !intVec.IsInPrisonCell(pawn.Map)) - { - return intVec; - } - } - } + return pawn2.Position; } return pawn.Position; } - Pawn pawn2; - if ((from c in pawn.Map.mapPawns.FreeColonistsSpawned - where !c.Position.IsForbidden(pawn) && pawn.CanReach(c.Position, PathEndMode.Touch, Danger.None, false, TraverseMode.ByPawn) - select c).TryRandomElement(out pawn2)) + int num = 0; + goto IL_0142; + IL_0142: + IntVec3 intVec; + while (true) { - return pawn2.Position; + num++; + if (num > 20) + { + return pawn.Position; + } + Building building = allBuildingsColonist.RandomElement(); + if (!building.Position.IsForbidden(pawn) && ((Area)pawn.Map.areaManager.Home)[building.Position]) + { + int num2 = 15 + num * 2; + if ((pawn.Position - building.Position).LengthHorizontalSquared <= num2 * num2) + { + intVec = GenAdjFast.AdjacentCells8Way((Thing)building).RandomElement(); + if (intVec.Standable(building.Map) && !intVec.IsForbidden(pawn) && pawn.CanReach(intVec, PathEndMode.OnCell, Danger.None, false, TraverseMode.ByPawn) && !intVec.IsInPrisonCell(pawn.Map)) + break; + } + } } - return pawn.Position; + return intVec; + IL_0258: + goto IL_0142; } } } diff --git a/Assembly-CSharp/RimWorld/JobGiver_WanderHive.cs b/Assembly-CSharp/RimWorld/JobGiver_WanderHive.cs index ceefd5a45..5c9195a02 100644 --- a/Assembly-CSharp/RimWorld/JobGiver_WanderHive.cs +++ b/Assembly-CSharp/RimWorld/JobGiver_WanderHive.cs @@ -1,4 +1,3 @@ -using System; using Verse; using Verse.AI; @@ -8,18 +7,18 @@ public class JobGiver_WanderHive : JobGiver_Wander { public JobGiver_WanderHive() { - this.wanderRadius = 7.5f; - this.ticksBetweenWandersRange = new IntRange(125, 200); + base.wanderRadius = 7.5f; + base.ticksBetweenWandersRange = new IntRange(125, 200); } protected override IntVec3 GetWanderRoot(Pawn pawn) { Hive hive = pawn.mindState.duty.focus.Thing as Hive; - if (hive == null || !hive.Spawned) + if (hive != null && hive.Spawned) { - return pawn.Position; + return hive.Position; } - return hive.Position; + return pawn.Position; } } } diff --git a/Assembly-CSharp/RimWorld/JobGiver_WanderInPartyArea.cs b/Assembly-CSharp/RimWorld/JobGiver_WanderInPartyArea.cs index b5381602d..42b9877c4 100644 --- a/Assembly-CSharp/RimWorld/JobGiver_WanderInPartyArea.cs +++ b/Assembly-CSharp/RimWorld/JobGiver_WanderInPartyArea.cs @@ -8,7 +8,7 @@ public class JobGiver_WanderInPartyArea : JobGiver_Wander { protected override IntVec3 GetExactWanderDest(Pawn pawn) { - IntVec3 result; + IntVec3 result = default(IntVec3); if (!PartyUtility.TryFindRandomCellInPartyArea(pawn, out result)) { return IntVec3.Invalid; diff --git a/Assembly-CSharp/RimWorld/JobGiver_Work.cs b/Assembly-CSharp/RimWorld/JobGiver_Work.cs index 3664640ec..b389c2d61 100644 --- a/Assembly-CSharp/RimWorld/JobGiver_Work.cs +++ b/Assembly-CSharp/RimWorld/JobGiver_Work.cs @@ -18,28 +18,28 @@ public override ThinkNode DeepCopy(bool resolve = true) public override float GetPriority(Pawn pawn) { - if (pawn.workSettings == null || !pawn.workSettings.EverWork) + if (pawn.workSettings != null && pawn.workSettings.EverWork) { - return 0f; - } - TimeAssignmentDef timeAssignmentDef = (pawn.timetable != null) ? pawn.timetable.CurrentAssignment : TimeAssignmentDefOf.Anything; - if (timeAssignmentDef == TimeAssignmentDefOf.Anything) - { - return 5.5f; - } - if (timeAssignmentDef == TimeAssignmentDefOf.Work) - { - return 9f; - } - if (timeAssignmentDef == TimeAssignmentDefOf.Sleep) - { - return 2f; - } - if (timeAssignmentDef == TimeAssignmentDefOf.Joy) - { - return 2f; + TimeAssignmentDef timeAssignmentDef = (pawn.timetable != null) ? pawn.timetable.CurrentAssignment : TimeAssignmentDefOf.Anything; + if (timeAssignmentDef == TimeAssignmentDefOf.Anything) + { + return 5.5f; + } + if (timeAssignmentDef == TimeAssignmentDefOf.Work) + { + return 9f; + } + if (timeAssignmentDef == TimeAssignmentDefOf.Sleep) + { + return 2f; + } + if (timeAssignmentDef == TimeAssignmentDefOf.Joy) + { + return 2f; + } + throw new NotImplementedException(); } - throw new NotImplementedException(); + return 0f; } public override ThinkResult TryIssueJobPackage(Pawn pawn, JobIssueParams jobParams) @@ -63,13 +63,12 @@ public override ThinkResult TryIssueJobPackage(Pawn pawn, JobIssueParams jobPara int num = -999; TargetInfo targetInfo = TargetInfo.Invalid; WorkGiver_Scanner workGiver_Scanner = null; + WorkGiver_Scanner scanner; for (int j = 0; j < list.Count; j++) { WorkGiver workGiver = list[j]; if (workGiver.def.priorityInType != num && targetInfo.IsValid) - { break; - } if (this.PawnCanUseWorkGiver(pawn, workGiver)) { try @@ -79,12 +78,12 @@ public override ThinkResult TryIssueJobPackage(Pawn pawn, JobIssueParams jobPara { return new ThinkResult(job2, this, new JobTag?(list[j].def.tagToGive)); } - WorkGiver_Scanner scanner = workGiver as WorkGiver_Scanner; + scanner = (workGiver as WorkGiver_Scanner); if (scanner != null) { if (workGiver.def.scanThings) { - Predicate predicate = (Thing t) => !t.IsForbidden(pawn) && scanner.HasJobOnThing(pawn, t, false); + Predicate predicate = (Predicate)((Thing t) => !t.IsForbidden(pawn) && scanner.HasJobOnThing(pawn, t, false)); IEnumerable enumerable = scanner.PotentialWorkThingsGlobal(pawn); Thing thing; if (scanner.Prioritized) @@ -95,7 +94,7 @@ public override ThinkResult TryIssueJobPackage(Pawn pawn, JobIssueParams jobPara enumerable2 = pawn.Map.listerThings.ThingsMatching(scanner.PotentialWorkThingRequest); } Predicate validator = predicate; - thing = GenClosest.ClosestThing_Global_Reachable(pawn.Position, pawn.Map, enumerable2, scanner.PathEndMode, TraverseParms.For(pawn, Danger.Deadly, TraverseMode.ByPawn, false), 9999f, validator, (Thing x) => scanner.GetPriority(pawn, x)); + thing = GenClosest.ClosestThing_Global_Reachable(pawn.Position, pawn.Map, enumerable2, scanner.PathEndMode, TraverseParms.For(pawn, Danger.Deadly, TraverseMode.ByPawn, false), 9999f, validator, (Func)((Thing x) => scanner.GetPriority(pawn, x))); } else { @@ -115,15 +114,15 @@ public override ThinkResult TryIssueJobPackage(Pawn pawn, JobIssueParams jobPara float num2 = 99999f; float num3 = -3.40282347E+38f; bool prioritized = scanner.Prioritized; - foreach (IntVec3 current in scanner.PotentialWorkCellsGlobal(pawn)) + foreach (IntVec3 item in scanner.PotentialWorkCellsGlobal(pawn)) { bool flag = false; - float num4 = (float)(current - position).LengthHorizontalSquared; + float num4 = (float)(item - position).LengthHorizontalSquared; if (prioritized) { - if (!current.IsForbidden(pawn) && scanner.HasJobOnCell(pawn, current)) + if (!item.IsForbidden(pawn) && scanner.HasJobOnCell(pawn, item)) { - float priority = scanner.GetPriority(pawn, current); + float priority = scanner.GetPriority(pawn, item); if (priority > num3 || (priority == num3 && num4 < num2)) { flag = true; @@ -131,13 +130,13 @@ public override ThinkResult TryIssueJobPackage(Pawn pawn, JobIssueParams jobPara } } } - else if (num4 < num2 && !current.IsForbidden(pawn) && scanner.HasJobOnCell(pawn, current)) + else if (num4 < num2 && !item.IsForbidden(pawn) && scanner.HasJobOnCell(pawn, item)) { flag = true; } if (flag) { - targetInfo = new TargetInfo(current, pawn.Map, false); + targetInfo = new TargetInfo(item, pawn.Map, false); workGiver_Scanner = scanner; num2 = num4; } @@ -147,14 +146,7 @@ public override ThinkResult TryIssueJobPackage(Pawn pawn, JobIssueParams jobPara } catch (Exception ex) { - Log.Error(string.Concat(new object[] - { - pawn, - " threw exception in WorkGiver ", - workGiver.def.defName, - ": ", - ex.ToString() - })); + Log.Error(pawn + " threw exception in WorkGiver " + workGiver.def.defName + ": " + ex.ToString()); } finally { @@ -162,38 +154,42 @@ public override ThinkResult TryIssueJobPackage(Pawn pawn, JobIssueParams jobPara if (targetInfo.IsValid) { pawn.mindState.lastGivenWorkType = workGiver.def.workType; - Job job3; - if (targetInfo.HasThing) - { - job3 = workGiver_Scanner.JobOnThing(pawn, targetInfo.Thing, false); - } - else + Job job3 = (!targetInfo.HasThing) ? workGiver_Scanner.JobOnCell(pawn, targetInfo.Cell) : workGiver_Scanner.JobOnThing(pawn, targetInfo.Thing, false); + if (job3 == null) { - job3 = workGiver_Scanner.JobOnCell(pawn, targetInfo.Cell); + Log.ErrorOnce(workGiver_Scanner + " provided target " + targetInfo + " but yielded no actual job for pawn " + pawn + ". The CanGiveJob and JobOnX methods may not be synchronized.", 6112651); + goto IL_05c2; } - if (job3 != null) - { - return new ThinkResult(job3, this, new JobTag?(list[j].def.tagToGive)); - } - Log.ErrorOnce(string.Concat(new object[] - { - workGiver_Scanner, - " provided target ", - targetInfo, - " but yielded no actual job for pawn ", - pawn, - ". The CanGiveJob and JobOnX methods may not be synchronized." - }), 6112651); + return new ThinkResult(job3, this, new JobTag?(list[j].def.tagToGive)); } - num = workGiver.def.priorityInType; + goto IL_05c2; } + continue; + IL_05c2: + num = workGiver.def.priorityInType; } return ThinkResult.NoJob; } private bool PawnCanUseWorkGiver(Pawn pawn, WorkGiver giver) { - return !giver.ShouldSkip(pawn) && (giver.def.canBeDoneByNonColonists || pawn.IsColonist) && (pawn.story == null || !pawn.story.WorkTagIsDisabled(giver.def.workTags)) && giver.MissingRequiredCapacity(pawn) == null; + if (giver.ShouldSkip(pawn)) + { + return false; + } + if (!giver.def.canBeDoneByNonColonists && !pawn.IsColonist) + { + return false; + } + if (pawn.story != null && pawn.story.WorkTagIsDisabled(giver.def.workTags)) + { + return false; + } + if (giver.MissingRequiredCapacity(pawn) != null) + { + return false; + } + return true; } private Job GiverTryGiveJobPrioritized(Pawn pawn, WorkGiver giver, IntVec3 cell) @@ -207,15 +203,14 @@ private Job GiverTryGiveJobPrioritized(Pawn pawn, WorkGiver giver, IntVec3 cell) Job job = giver.NonScanJob(pawn); if (job != null) { - Job result = job; - return result; + return job; } WorkGiver_Scanner scanner = giver as WorkGiver_Scanner; if (scanner != null) { if (giver.def.scanThings) { - Predicate predicate = (Thing t) => !t.IsForbidden(pawn) && scanner.HasJobOnThing(pawn, t, false); + Predicate predicate = (Predicate)((Thing t) => !t.IsForbidden(pawn) && scanner.HasJobOnThing(pawn, t, false)); List thingList = cell.GetThingList(pawn.Map); for (int i = 0; i < thingList.Count; i++) { @@ -223,29 +218,20 @@ private Job GiverTryGiveJobPrioritized(Pawn pawn, WorkGiver giver, IntVec3 cell) if (scanner.PotentialWorkThingRequest.Accepts(thing) && predicate(thing)) { pawn.mindState.lastGivenWorkType = giver.def.workType; - Job result = scanner.JobOnThing(pawn, thing, false); - return result; + return scanner.JobOnThing(pawn, thing, false); } } } if (giver.def.scanCells && !cell.IsForbidden(pawn) && scanner.HasJobOnCell(pawn, cell)) { pawn.mindState.lastGivenWorkType = giver.def.workType; - Job result = scanner.JobOnCell(pawn, cell); - return result; + return scanner.JobOnCell(pawn, cell); } } } catch (Exception ex) { - Log.Error(string.Concat(new object[] - { - pawn, - " threw exception in GiverTryGiveJobTargeted on WorkGiver ", - giver.def.defName, - ": ", - ex.ToString() - })); + Log.Error(pawn + " threw exception in GiverTryGiveJobTargeted on WorkGiver " + giver.def.defName + ": " + ex.ToString()); } return null; } diff --git a/Assembly-CSharp/RimWorld/JobInBedUtility.cs b/Assembly-CSharp/RimWorld/JobInBedUtility.cs index b8163bfdf..e58b8842d 100644 --- a/Assembly-CSharp/RimWorld/JobInBedUtility.cs +++ b/Assembly-CSharp/RimWorld/JobInBedUtility.cs @@ -8,12 +8,12 @@ public static class JobInBedUtility { public static void KeepLyingDown(this JobDriver driver, TargetIndex bedIndex) { - driver.AddFinishAction(delegate + driver.AddFinishAction((Action)delegate() { Pawn pawn = driver.pawn; if (!pawn.Drafted) { - pawn.jobs.jobQueue.EnqueueFirst(new Job(JobDefOf.LayDown, pawn.CurJob.GetTarget(bedIndex)), null); + pawn.jobs.jobQueue.EnqueueFirst(new Job(JobDefOf.LayDown, pawn.CurJob.GetTarget(bedIndex)), default(JobTag?)); } }); } diff --git a/Assembly-CSharp/RimWorld/JoyCategory.cs b/Assembly-CSharp/RimWorld/JoyCategory.cs index fefd84569..9f9976cb6 100644 --- a/Assembly-CSharp/RimWorld/JoyCategory.cs +++ b/Assembly-CSharp/RimWorld/JoyCategory.cs @@ -1,14 +1,12 @@ -using System; - namespace RimWorld { public enum JoyCategory : byte { - Empty, - VeryLow, - Low, - Satisfied, - High, - Extreme + Empty = 0, + VeryLow = 1, + Low = 2, + Satisfied = 3, + High = 4, + Extreme = 5 } } diff --git a/Assembly-CSharp/RimWorld/JoyGiver.cs b/Assembly-CSharp/RimWorld/JoyGiver.cs index cc9397291..9fb452777 100644 --- a/Assembly-CSharp/RimWorld/JoyGiver.cs +++ b/Assembly-CSharp/RimWorld/JoyGiver.cs @@ -1,4 +1,3 @@ -using System; using System.Collections.Generic; using Verse; using Verse.AI; diff --git a/Assembly-CSharp/RimWorld/JoyGiverDef.cs b/Assembly-CSharp/RimWorld/JoyGiverDef.cs index 6d4e48e11..98a04ccb4 100644 --- a/Assembly-CSharp/RimWorld/JoyGiverDef.cs +++ b/Assembly-CSharp/RimWorld/JoyGiverDef.cs @@ -1,6 +1,5 @@ using System; using System.Collections.Generic; -using System.Diagnostics; using Verse; namespace RimWorld @@ -42,14 +41,16 @@ public JoyGiver Worker } } - [DebuggerHidden] public override IEnumerable ConfigErrors() { - JoyGiverDef.c__Iterator90 c__Iterator = new JoyGiverDef.c__Iterator90(); - c__Iterator.<>f__this = this; - JoyGiverDef.c__Iterator90 expr_0E = c__Iterator; - expr_0E.$PC = -2; - return expr_0E; + foreach (string item in base.ConfigErrors()) + { + yield return item; + } + if (this.jobDef != null && this.jobDef.joyKind != this.joyKind) + { + yield return "jobDef " + this.jobDef + " has joyKind " + this.jobDef.joyKind + " which does not match our joyKind " + this.joyKind; + } } } } diff --git a/Assembly-CSharp/RimWorld/JoyGiver_BuildSnowman.cs b/Assembly-CSharp/RimWorld/JoyGiver_BuildSnowman.cs index b2e3e405f..229ba03a6 100644 --- a/Assembly-CSharp/RimWorld/JoyGiver_BuildSnowman.cs +++ b/Assembly-CSharp/RimWorld/JoyGiver_BuildSnowman.cs @@ -14,7 +14,7 @@ public override Job TryGiveJob(Pawn pawn) { return null; } - if (pawn.Map.snowGrid.TotalDepth < 200f) + if (pawn.Map.snowGrid.TotalDepth < 200.0) { return null; } @@ -23,18 +23,18 @@ public override Job TryGiveJob(Pawn pawn) { return null; } - return new Job(this.def.jobDef, c); + return new Job(base.def.jobDef, c); } private static IntVec3 TryFindSnowmanBuildCell(Pawn pawn) { Region rootReg; - if (!CellFinder.TryFindClosestRegionWith(pawn.GetRegion(RegionType.Set_Passable), TraverseParms.For(pawn, Danger.Deadly, TraverseMode.ByPawn, false), (Region r) => r.Room.PsychologicallyOutdoors, 100, out rootReg, RegionType.Set_Passable)) + if (!CellFinder.TryFindClosestRegionWith(pawn.GetRegion(RegionType.Set_Passable), TraverseParms.For(pawn, Danger.Deadly, TraverseMode.ByPawn, false), (Predicate)((Region r) => r.Room.PsychologicallyOutdoors), 100, out rootReg, RegionType.Set_Passable)) { return IntVec3.Invalid; } IntVec3 result = IntVec3.Invalid; - RegionTraverser.BreadthFirstTraverse(rootReg, (Region from, Region r) => r.Room == rootReg.Room, delegate(Region r) + RegionTraverser.BreadthFirstTraverse(rootReg, (RegionEntryPredicate)((Region from, Region r) => r.Room == rootReg.Room), (RegionProcessor)delegate(Region r) { for (int i = 0; i < 5; i++) { @@ -52,7 +52,7 @@ private static IntVec3 TryFindSnowmanBuildCell(Pawn pawn) private static bool IsGoodSnowmanCell(IntVec3 c, Pawn pawn) { - if (pawn.Map.snowGrid.GetDepth(c) < 0.5f) + if (pawn.Map.snowGrid.GetDepth(c) < 0.5) { return false; } diff --git a/Assembly-CSharp/RimWorld/JoyGiver_GoForWalk.cs b/Assembly-CSharp/RimWorld/JoyGiver_GoForWalk.cs index f6890b937..e84be867a 100644 --- a/Assembly-CSharp/RimWorld/JoyGiver_GoForWalk.cs +++ b/Assembly-CSharp/RimWorld/JoyGiver_GoForWalk.cs @@ -17,28 +17,25 @@ public override Job TryGiveJob(Pawn pawn) { return null; } - Predicate cellValidator = (IntVec3 x) => !PawnUtility.KnownDangerAt(x, pawn); - Predicate validator = delegate(Region x) - { - IntVec3 intVec; - return x.Room.PsychologicallyOutdoors && !x.IsForbiddenEntirely(pawn) && x.TryFindRandomCellInRegionUnforbidden(pawn, cellValidator, out intVec); - }; - Region reg; + Predicate cellValidator = (Predicate)((IntVec3 x) => !PawnUtility.KnownDangerAt(x, pawn)); + IntVec3 intVec = default(IntVec3); + Predicate validator = (Predicate)((Region x) => x.Room.PsychologicallyOutdoors && !x.IsForbiddenEntirely(pawn) && x.TryFindRandomCellInRegionUnforbidden(pawn, cellValidator, out intVec)); + Region reg = default(Region); if (!CellFinder.TryFindClosestRegionWith(pawn.GetRegion(RegionType.Set_Passable), TraverseParms.For(pawn, Danger.Deadly, TraverseMode.ByPawn, false), validator, 100, out reg, RegionType.Set_Passable)) { return null; } - IntVec3 root; + IntVec3 root = default(IntVec3); if (!reg.TryFindRandomCellInRegionUnforbidden(pawn, cellValidator, out root)) { return null; } - List list; + List list = default(List); if (!WalkPathFinder.TryFindWalkPath(pawn, root, out list)) { return null; } - Job job = new Job(this.def.jobDef, list[0]); + Job job = new Job(base.def.jobDef, list[0]); job.targetQueueA = new List(); for (int i = 1; i < list.Count; i++) { diff --git a/Assembly-CSharp/RimWorld/JoyGiver_InPrivateRoom.cs b/Assembly-CSharp/RimWorld/JoyGiver_InPrivateRoom.cs index 18b84cc83..9a39408e5 100644 --- a/Assembly-CSharp/RimWorld/JoyGiver_InPrivateRoom.cs +++ b/Assembly-CSharp/RimWorld/JoyGiver_InPrivateRoom.cs @@ -18,14 +18,14 @@ public override Job TryGiveJob(Pawn pawn) { return null; } - IntVec3 c2; + IntVec3 c2 = default(IntVec3); if (!(from c in ownedRoom.Cells where c.Standable(pawn.Map) && !c.IsForbidden(pawn) && pawn.CanReserveAndReach(c, PathEndMode.OnCell, Danger.None, 1, -1, null, false) - select c).TryRandomElement(out c2)) + select c).TryRandomElement(out c2)) { return null; } - return new Job(this.def.jobDef, c2); + return new Job(base.def.jobDef, c2); } } } diff --git a/Assembly-CSharp/RimWorld/JoyGiver_Ingest.cs b/Assembly-CSharp/RimWorld/JoyGiver_Ingest.cs index 827f53fda..1e6cf3647 100644 --- a/Assembly-CSharp/RimWorld/JoyGiver_Ingest.cs +++ b/Assembly-CSharp/RimWorld/JoyGiver_Ingest.cs @@ -15,7 +15,7 @@ public override Job TryGiveJob(Pawn pawn) public override Job TryGiveJobInPartyArea(Pawn pawn, IntVec3 partySpot) { - return this.TryGiveJobInternal(pawn, (Thing x) => !x.Spawned || PartyUtility.InPartyArea(x.Position, partySpot, pawn.Map)); + return this.TryGiveJobInternal(pawn, (Predicate)((Thing x) => !x.Spawned || PartyUtility.InPartyArea(x.Position, partySpot, pawn.Map))); } private Job TryGiveJobInternal(Pawn pawn, Predicate extraValidator) @@ -30,7 +30,18 @@ private Job TryGiveJobInternal(Pawn pawn, Predicate extraValidator) protected virtual Thing BestIngestItem(Pawn pawn, Predicate extraValidator) { - Predicate predicate = (Thing t) => this.CanIngestForJoy(pawn, t) && (extraValidator == null || extraValidator(t)); + Predicate predicate = (Predicate)delegate(Thing t) + { + if (!this.CanIngestForJoy(pawn, t)) + { + return false; + } + if ((object)extraValidator != null && !extraValidator(t)) + { + return false; + } + return true; + }; ThingOwner innerContainer = pawn.inventory.innerContainer; for (int i = 0; i < innerContainer.Count; i++) { @@ -50,47 +61,50 @@ protected virtual Thing BestIngestItem(Pawn pawn, Predicate extraValidato protected virtual bool CanIngestForJoy(Pawn pawn, Thing t) { - if (!t.def.IsIngestible || t.def.ingestible.joyKind == null || t.def.ingestible.joy <= 0f) - { - return false; - } - if (t.Spawned) + if (t.def.IsIngestible && t.def.ingestible.joyKind != null && !(t.def.ingestible.joy <= 0.0)) { - if (!pawn.CanReserve(t, 1, -1, null, false)) - { - return false; - } - if (t.IsForbidden(pawn)) + if (t.Spawned) { - return false; + if (!pawn.CanReserve(t, 1, -1, null, false)) + { + return false; + } + if (t.IsForbidden(pawn)) + { + return false; + } + if (!t.IsSociallyProper(pawn)) + { + return false; + } } - if (!t.IsSociallyProper(pawn)) + if (t.def.IsDrug && pawn.drugs != null && !pawn.drugs.CurrentPolicy[t.def].allowedForJoy && pawn.story != null) { - return false; + int num = pawn.story.traits.DegreeOfTrait(TraitDefOf.DrugDesire); + if (num <= 0 && !pawn.InMentalState) + { + return false; + } } + return true; } - if (t.def.IsDrug && pawn.drugs != null && !pawn.drugs.CurrentPolicy[t.def].allowedForJoy && pawn.story != null) - { - int num = pawn.story.traits.DegreeOfTrait(TraitDefOf.DrugDesire); - if (num <= 0 && !pawn.InMentalState) - { - return false; - } - } - return true; + return false; } protected virtual bool SearchSetWouldInclude(Thing thing) { - return this.def.thingDefs != null && this.def.thingDefs.Contains(thing.def); + if (base.def.thingDefs == null) + { + return false; + } + return base.def.thingDefs.Contains(thing.def); } protected virtual Job CreateIngestJob(Thing ingestible, Pawn pawn) { - return new Job(JobDefOf.Ingest, ingestible) - { - count = Mathf.Min(ingestible.stackCount, ingestible.def.ingestible.maxNumToIngestAtOnce) - }; + Job job = new Job(JobDefOf.Ingest, ingestible); + job.count = Mathf.Min(ingestible.stackCount, ingestible.def.ingestible.maxNumToIngestAtOnce); + return job; } } } diff --git a/Assembly-CSharp/RimWorld/JoyGiver_InteractBuilding.cs b/Assembly-CSharp/RimWorld/JoyGiver_InteractBuilding.cs index 87cbb0509..4a18c5c71 100644 --- a/Assembly-CSharp/RimWorld/JoyGiver_InteractBuilding.cs +++ b/Assembly-CSharp/RimWorld/JoyGiver_InteractBuilding.cs @@ -52,11 +52,11 @@ public override Job TryGiveJobInPartyArea(Pawn pawn, IntVec3 partySpot) private Thing FindBestGame(Pawn pawn, bool inBed, IntVec3 partySpot) { List searchSet = this.GetSearchSet(pawn); - Predicate predicate = (Thing t) => this.CanInteractWith(pawn, t, inBed); + Predicate predicate = (Predicate)((Thing t) => this.CanInteractWith(pawn, t, inBed)); if (partySpot.IsValid) { Predicate oldValidator = predicate; - predicate = ((Thing x) => PartyUtility.InPartyArea(x.Position, partySpot, pawn.Map) && oldValidator(x)); + predicate = (Predicate)((Thing x) => PartyUtility.InPartyArea(x.Position, partySpot, pawn.Map) && oldValidator(x)); } Predicate validator = predicate; return GenClosest.ClosestThing_Global_Reachable(pawn.Position, pawn.Map, searchSet, PathEndMode.OnCell, TraverseParms.For(pawn, Danger.Deadly, TraverseMode.ByPawn, false), 9999f, validator, null); @@ -64,7 +64,7 @@ private Thing FindBestGame(Pawn pawn, bool inBed, IntVec3 partySpot) protected virtual bool CanInteractWith(Pawn pawn, Thing t, bool inBed) { - if (!pawn.CanReserve(t, this.def.jobDef.joyMaxParticipants, -1, null, false)) + if (!pawn.CanReserve(t, base.def.jobDef.joyMaxParticipants, -1, null, false)) { return false; } @@ -77,7 +77,15 @@ protected virtual bool CanInteractWith(Pawn pawn, Thing t, bool inBed) return false; } CompPowerTrader compPowerTrader = t.TryGetComp(); - return (compPowerTrader == null || compPowerTrader.PowerOn) && (!this.def.unroofedOnly || !t.Position.Roofed(t.Map)); + if (compPowerTrader != null && !compPowerTrader.PowerOn) + { + return false; + } + if (base.def.unroofedOnly && t.Position.Roofed(t.Map)) + { + return false; + } + return true; } protected abstract Job TryGivePlayJob(Pawn pawn, Thing bestGame); @@ -85,7 +93,7 @@ protected virtual bool CanInteractWith(Pawn pawn, Thing t, bool inBed) protected virtual Job TryGivePlayJobWhileInBed(Pawn pawn, Thing bestGame) { Building_Bed t = pawn.CurrentBed(); - return new Job(this.def.jobDef, bestGame, pawn.Position, t); + return new Job(base.def.jobDef, bestGame, pawn.Position, (Thing)t); } } } diff --git a/Assembly-CSharp/RimWorld/JoyGiver_InteractBuildingInteractionCell.cs b/Assembly-CSharp/RimWorld/JoyGiver_InteractBuildingInteractionCell.cs index b2fd535db..b847d4e84 100644 --- a/Assembly-CSharp/RimWorld/JoyGiver_InteractBuildingInteractionCell.cs +++ b/Assembly-CSharp/RimWorld/JoyGiver_InteractBuildingInteractionCell.cs @@ -1,4 +1,3 @@ -using System; using Verse; using Verse.AI; @@ -10,7 +9,7 @@ protected override Job TryGivePlayJob(Pawn pawn, Thing t) { if (t.InteractionCell.Standable(t.Map) && !t.IsForbidden(pawn) && !t.InteractionCell.IsForbidden(pawn) && !pawn.Map.pawnDestinationManager.DestinationIsReserved(t.InteractionCell)) { - return new Job(this.def.jobDef, t, t.InteractionCell); + return new Job(base.def.jobDef, t, t.InteractionCell); } return null; } diff --git a/Assembly-CSharp/RimWorld/JoyGiver_InteractBuildingSitAdjacent.cs b/Assembly-CSharp/RimWorld/JoyGiver_InteractBuildingSitAdjacent.cs index cf274688e..f7584b12f 100644 --- a/Assembly-CSharp/RimWorld/JoyGiver_InteractBuildingSitAdjacent.cs +++ b/Assembly-CSharp/RimWorld/JoyGiver_InteractBuildingSitAdjacent.cs @@ -1,4 +1,3 @@ -using System; using Verse; using Verse.AI; @@ -15,7 +14,7 @@ protected override Job TryGivePlayJob(Pawn pawn, Thing t) if (!c.IsForbidden(pawn)) { Building edifice = c.GetEdifice(pawn.Map); - if (edifice != null && edifice.def.building.isSittable && pawn.CanReserve(edifice, 1, -1, null, false)) + if (edifice != null && edifice.def.building.isSittable && pawn.CanReserve((Thing)edifice, 1, -1, null, false)) { thing = edifice; break; @@ -26,7 +25,7 @@ protected override Job TryGivePlayJob(Pawn pawn, Thing t) { return null; } - return new Job(this.def.jobDef, t, thing); + return new Job(base.def.jobDef, t, thing); } } } diff --git a/Assembly-CSharp/RimWorld/JoyGiver_PlayBilliards.cs b/Assembly-CSharp/RimWorld/JoyGiver_PlayBilliards.cs index 878f4056d..7b9b0adc5 100644 --- a/Assembly-CSharp/RimWorld/JoyGiver_PlayBilliards.cs +++ b/Assembly-CSharp/RimWorld/JoyGiver_PlayBilliards.cs @@ -1,4 +1,3 @@ -using System; using Verse; using Verse.AI; @@ -20,7 +19,7 @@ protected override Job TryGivePlayJob(Pawn pawn, Thing t) { return null; } - return new Job(this.def.jobDef, t); + return new Job(base.def.jobDef, t); } public static bool ThingHasStandableSpaceOnAllSides(Thing t) @@ -30,12 +29,9 @@ public static bool ThingHasStandableSpaceOnAllSides(Thing t) while (!iterator.Done()) { IntVec3 current = iterator.Current; - if (!cellRect.Contains(current)) + if (!cellRect.Contains(current) && !current.Standable(t.Map)) { - if (!current.Standable(t.Map)) - { - return false; - } + return false; } iterator.MoveNext(); } diff --git a/Assembly-CSharp/RimWorld/JoyGiver_Skygaze.cs b/Assembly-CSharp/RimWorld/JoyGiver_Skygaze.cs index 108a16be3..0a5af2518 100644 --- a/Assembly-CSharp/RimWorld/JoyGiver_Skygaze.cs +++ b/Assembly-CSharp/RimWorld/JoyGiver_Skygaze.cs @@ -1,4 +1,3 @@ -using System; using Verse; using Verse.AI; @@ -8,16 +7,16 @@ public class JoyGiver_Skygaze : JoyGiver { public override Job TryGiveJob(Pawn pawn) { - if (!JoyUtility.EnjoyableOutsideNow(pawn, null) || pawn.Map.weatherManager.curWeather.rainRate > 0.1f) + if (JoyUtility.EnjoyableOutsideNow(pawn, null) && !(pawn.Map.weatherManager.curWeather.rainRate > 0.10000000149011612)) { - return null; + IntVec3 c = default(IntVec3); + if (!RCellFinder.TryFindSkygazeCell(pawn.Position, pawn, out c)) + { + return null; + } + return new Job(base.def.jobDef, c); } - IntVec3 c; - if (!RCellFinder.TryFindSkygazeCell(pawn.Position, pawn, out c)) - { - return null; - } - return new Job(this.def.jobDef, c); + return null; } } } diff --git a/Assembly-CSharp/RimWorld/JoyGiver_SocialRelax.cs b/Assembly-CSharp/RimWorld/JoyGiver_SocialRelax.cs index d5c97bfe6..ef185502e 100644 --- a/Assembly-CSharp/RimWorld/JoyGiver_SocialRelax.cs +++ b/Assembly-CSharp/RimWorld/JoyGiver_SocialRelax.cs @@ -16,8 +16,8 @@ public class JoyGiver_SocialRelax : JoyGiver private static readonly int NumRadiusCells = GenRadial.NumCellsInRadius(3.9f); private static readonly List RadialPatternMiddleOutward = (from c in GenRadial.RadialPattern.Take(JoyGiver_SocialRelax.NumRadiusCells) - orderby Mathf.Abs((c - IntVec3.Zero).LengthHorizontal - 1.95f) - select c).ToList(); + orderby Mathf.Abs((float)((c - IntVec3.Zero).LengthHorizontal - 1.9500000476837158)) + select c).ToList(); private static List nurseableDrugs = new List(); @@ -28,7 +28,7 @@ public override Job TryGiveJob(Pawn pawn) public override Job TryGiveJobInPartyArea(Pawn pawn, IntVec3 partySpot) { - return this.TryGiveJobInt(pawn, (CompGatherSpot x) => PartyUtility.InPartyArea(x.parent.Position, partySpot, pawn.Map)); + return this.TryGiveJobInt(pawn, (Predicate)((CompGatherSpot x) => PartyUtility.InPartyArea(x.parent.Position, partySpot, pawn.Map))); } private Job TryGiveJobInt(Pawn pawn, Predicate gatherSpotValidator) @@ -42,46 +42,54 @@ private Job TryGiveJobInt(Pawn pawn, Predicate gatherSpotValidat { JoyGiver_SocialRelax.workingSpots.Add(pawn.Map.gatherSpotLister.activeSpots[i]); } - CompGatherSpot compGatherSpot; - while (JoyGiver_SocialRelax.workingSpots.TryRandomElement(out compGatherSpot)) + CompGatherSpot compGatherSpot = default(CompGatherSpot); + while (true) { + if (!((IEnumerable)JoyGiver_SocialRelax.workingSpots).TryRandomElement(out compGatherSpot)) + { + return null; + } JoyGiver_SocialRelax.workingSpots.Remove(compGatherSpot); - if (!compGatherSpot.parent.IsForbidden(pawn) && pawn.CanReach(compGatherSpot.parent, PathEndMode.Touch, Danger.None, false, TraverseMode.ByPawn) && compGatherSpot.parent.IsSociallyProper(pawn) && (gatherSpotValidator == null || gatherSpotValidator(compGatherSpot))) + if (!compGatherSpot.parent.IsForbidden(pawn) && pawn.CanReach((Thing)compGatherSpot.parent, PathEndMode.Touch, Danger.None, false, TraverseMode.ByPawn) && compGatherSpot.parent.IsSociallyProper(pawn)) { - Job job; - Thing t2; - if (compGatherSpot.parent.def.surfaceType == SurfaceType.Eat) - { - Thing t; - if (!JoyGiver_SocialRelax.TryFindChairBesideTable(compGatherSpot.parent, pawn, out t)) - { - return null; - } - job = new Job(JobDefOf.SocialRelax, compGatherSpot.parent, t); - } - else if (JoyGiver_SocialRelax.TryFindChairNear(compGatherSpot.parent.Position, pawn, out t2)) - { - job = new Job(JobDefOf.SocialRelax, compGatherSpot.parent, t2); - } - else - { - IntVec3 c; - if (!JoyGiver_SocialRelax.TryFindSitSpotOnGroundNear(compGatherSpot.parent.Position, pawn, out c)) - { - return null; - } - job = new Job(JobDefOf.SocialRelax, compGatherSpot.parent, c); - } - Thing thing; - if (pawn.health.capacities.CapableOf(PawnCapacityDefOf.Manipulation) && JoyGiver_SocialRelax.TryFindIngestibleToNurse(compGatherSpot.parent.Position, pawn, out thing)) - { - job.targetC = thing; - job.count = Mathf.Min(thing.stackCount, thing.def.ingestible.maxNumToIngestAtOnce); - } - return job; + if ((object)gatherSpotValidator == null) + break; + if (gatherSpotValidator(compGatherSpot)) + break; } } + Job job; + if (compGatherSpot.parent.def.surfaceType == SurfaceType.Eat) + { + Thing t = default(Thing); + if (JoyGiver_SocialRelax.TryFindChairBesideTable((Thing)compGatherSpot.parent, pawn, out t)) + { + job = new Job(JobDefOf.SocialRelax, (Thing)compGatherSpot.parent, t); + goto IL_01a0; + } + return null; + } + Thing t2 = default(Thing); + if (JoyGiver_SocialRelax.TryFindChairNear(compGatherSpot.parent.Position, pawn, out t2)) + { + job = new Job(JobDefOf.SocialRelax, (Thing)compGatherSpot.parent, t2); + goto IL_01a0; + } + IntVec3 c = default(IntVec3); + if (JoyGiver_SocialRelax.TryFindSitSpotOnGroundNear(compGatherSpot.parent.Position, pawn, out c)) + { + job = new Job(JobDefOf.SocialRelax, (Thing)compGatherSpot.parent, c); + goto IL_01a0; + } return null; + IL_01a0: + Thing thing = default(Thing); + if (pawn.health.capacities.CapableOf(PawnCapacityDefOf.Manipulation) && JoyGiver_SocialRelax.TryFindIngestibleToNurse(compGatherSpot.parent.Position, pawn, out thing)) + { + job.targetC = thing; + job.count = Mathf.Min(thing.stackCount, thing.def.ingestible.maxNumToIngestAtOnce); + } + return job; } private static bool TryFindIngestibleToNurse(IntVec3 center, Pawn ingester, out Thing ingestible) @@ -105,13 +113,13 @@ private static bool TryFindIngestibleToNurse(IntVec3 center, Pawn ingester, out JoyGiver_SocialRelax.nurseableDrugs.Add(currentPolicy[i].drug); } } - JoyGiver_SocialRelax.nurseableDrugs.Shuffle(); + JoyGiver_SocialRelax.nurseableDrugs.Shuffle(); for (int j = 0; j < JoyGiver_SocialRelax.nurseableDrugs.Count; j++) { List list = ingester.Map.listerThings.ThingsOfDef(JoyGiver_SocialRelax.nurseableDrugs[j]); if (list.Count > 0) { - Predicate validator = (Thing t) => ingester.CanReserve(t, 1, -1, null, false) && !t.IsForbidden(ingester); + Predicate validator = (Predicate)((Thing t) => ingester.CanReserve(t, 1, -1, null, false) && !t.IsForbidden(ingester)); ingestible = GenClosest.ClosestThing_Global_Reachable(center, ingester.Map, list, PathEndMode.OnCell, TraverseParms.For(ingester, Danger.Deadly, TraverseMode.ByPawn, false), 40f, validator, null); if (ingestible != null) { @@ -129,7 +137,7 @@ private static bool TryFindChairBesideTable(Thing table, Pawn sitter, out Thing { IntVec3 c = table.RandomAdjacentCellCardinal(); Building edifice = c.GetEdifice(table.Map); - if (edifice != null && edifice.def.building.isSittable && sitter.CanReserve(edifice, 1, -1, null, false)) + if (edifice != null && edifice.def.building.isSittable && sitter.CanReserve((Thing)edifice, 1, -1, null, false)) { chair = edifice; return true; @@ -145,7 +153,7 @@ private static bool TryFindChairNear(IntVec3 center, Pawn sitter, out Thing chai { IntVec3 c = center + JoyGiver_SocialRelax.RadialPatternMiddleOutward[i]; Building edifice = c.GetEdifice(sitter.Map); - if (edifice != null && edifice.def.building.isSittable && sitter.CanReserve(edifice, 1, -1, null, false) && !edifice.IsForbidden(sitter) && GenSight.LineOfSight(center, edifice.Position, sitter.Map, true, null, 0, 0)) + if (edifice != null && edifice.def.building.isSittable && sitter.CanReserve((Thing)edifice, 1, -1, null, false) && !edifice.IsForbidden(sitter) && GenSight.LineOfSight(center, edifice.Position, sitter.Map, true, null, 0, 0)) { chair = edifice; return true; diff --git a/Assembly-CSharp/RimWorld/JoyGiver_TakeDrug.cs b/Assembly-CSharp/RimWorld/JoyGiver_TakeDrug.cs index 49f3f4023..4ff4a5912 100644 --- a/Assembly-CSharp/RimWorld/JoyGiver_TakeDrug.cs +++ b/Assembly-CSharp/RimWorld/JoyGiver_TakeDrug.cs @@ -11,7 +11,18 @@ public class JoyGiver_TakeDrug : JoyGiver_Ingest protected override Thing BestIngestItem(Pawn pawn, Predicate extraValidator) { - Predicate predicate = (Thing t) => this.CanIngestForJoy(pawn, t) && (extraValidator == null || extraValidator(t)); + Predicate predicate = (Predicate)delegate(Thing t) + { + if (!this.CanIngestForJoy(pawn, t)) + { + return false; + } + if ((object)extraValidator != null && !extraValidator(t)) + { + return false; + } + return true; + }; ThingOwner innerContainer = pawn.inventory.innerContainer; for (int i = 0; i < innerContainer.Count; i++) { @@ -29,7 +40,7 @@ protected override Thing BestIngestItem(Pawn pawn, Predicate extraValidat JoyGiver_TakeDrug.takeableDrugs.Add(currentPolicy[j].drug); } } - JoyGiver_TakeDrug.takeableDrugs.Shuffle(); + JoyGiver_TakeDrug.takeableDrugs.Shuffle(); for (int k = 0; k < JoyGiver_TakeDrug.takeableDrugs.Count; k++) { List list = pawn.Map.listerThings.ThingsOfDef(JoyGiver_TakeDrug.takeableDrugs[k]); @@ -57,14 +68,14 @@ public override float GetChance(Pawn pawn) { return 0f; } - float num2 = this.def.baseChance; + float num2 = base.def.baseChance; if (num == 1) { - num2 *= 2f; + num2 = (float)(num2 * 2.0); } if (num == 2) { - num2 *= 5f; + num2 = (float)(num2 * 5.0); } return num2; } diff --git a/Assembly-CSharp/RimWorld/JoyGiver_ViewArt.cs b/Assembly-CSharp/RimWorld/JoyGiver_ViewArt.cs index b69a7f236..b229d27b9 100644 --- a/Assembly-CSharp/RimWorld/JoyGiver_ViewArt.cs +++ b/Assembly-CSharp/RimWorld/JoyGiver_ViewArt.cs @@ -14,43 +14,55 @@ public class JoyGiver_ViewArt : JoyGiver public override Job TryGiveJob(Pawn pawn) { bool allowedOutside = JoyUtility.EnjoyableOutsideNow(pawn, null); - Job result; try { - JoyGiver_ViewArt.candidates.AddRange(pawn.Map.listerThings.ThingsInGroup(ThingRequestGroup.Art).Where(delegate(Thing thing) + JoyGiver_ViewArt.candidates.AddRange(pawn.Map.listerThings.ThingsInGroup(ThingRequestGroup.Art).Where((Func)delegate(Thing thing) { - if (thing.Faction != Faction.OfPlayer || thing.IsForbidden(pawn) || (!allowedOutside && !thing.Position.Roofed(thing.Map)) || !pawn.CanReserveAndReach(thing, PathEndMode.Touch, Danger.None, 1, -1, null, false)) + if (thing.Faction == Faction.OfPlayer && !thing.IsForbidden(pawn) && (allowedOutside || thing.Position.Roofed(thing.Map)) && pawn.CanReserveAndReach(thing, PathEndMode.Touch, Danger.None, 1, -1, null, false)) { + CompArt compArt = thing.TryGetComp(); + if (compArt == null) + { + Log.Error("No CompArt on thing being considered for viewing: " + thing); + return false; + } + if (compArt.CanShowArt && compArt.Props.canBeEnjoyedAsArt) + { + Room room = thing.GetRoom(RegionType.Set_Passable); + if (room == null) + { + return false; + } + if (room.Role != RoomRoleDefOf.Bedroom && room.Role != RoomRoleDefOf.Barracks && room.Role != RoomRoleDefOf.PrisonCell && room.Role != RoomRoleDefOf.PrisonBarracks && room.Role != RoomRoleDefOf.Hospital) + { + goto IL_0139; + } + if (pawn.ownership != null && pawn.ownership.OwnedRoom != null && pawn.ownership.OwnedRoom == room) + { + goto IL_0139; + } + return false; + } return false; } - CompArt compArt = thing.TryGetComp(); - if (compArt == null) - { - Log.Error("No CompArt on thing being considered for viewing: " + thing); - return false; - } - if (!compArt.CanShowArt || !compArt.Props.canBeEnjoyedAsArt) - { - return false; - } - Room room = thing.GetRoom(RegionType.Set_Passable); - return room != null && ((room.Role != RoomRoleDefOf.Bedroom && room.Role != RoomRoleDefOf.Barracks && room.Role != RoomRoleDefOf.PrisonCell && room.Role != RoomRoleDefOf.PrisonBarracks && room.Role != RoomRoleDefOf.Hospital) || (pawn.ownership != null && pawn.ownership.OwnedRoom != null && pawn.ownership.OwnedRoom == room)); + return false; + IL_0139: + return true; })); - Thing t; - if (!JoyGiver_ViewArt.candidates.TryRandomElementByWeight((Thing target) => Mathf.Max(target.GetStatValue(StatDefOf.Beauty, true), 0.5f), out t)) - { - result = null; - } - else + Thing t = default(Thing); + if (!((IEnumerable)JoyGiver_ViewArt.candidates).TryRandomElementByWeight((Func)((Thing target) => Mathf.Max(target.GetStatValue(StatDefOf.Beauty, true), 0.5f)), out t)) { - result = new Job(this.def.jobDef, t); + return null; } + return new Job(base.def.jobDef, t); + IL_00a2: + Job result; + return result; } finally { JoyGiver_ViewArt.candidates.Clear(); } - return result; } } } diff --git a/Assembly-CSharp/RimWorld/JoyGiver_VisitGrave.cs b/Assembly-CSharp/RimWorld/JoyGiver_VisitGrave.cs index 65bd8d69f..93a7f94b5 100644 --- a/Assembly-CSharp/RimWorld/JoyGiver_VisitGrave.cs +++ b/Assembly-CSharp/RimWorld/JoyGiver_VisitGrave.cs @@ -12,21 +12,21 @@ public class JoyGiver_VisitGrave : JoyGiver public override Job TryGiveJob(Pawn pawn) { bool allowedOutside = JoyUtility.EnjoyableOutsideNow(pawn, null); - IEnumerable source = pawn.Map.listerThings.ThingsInGroup(ThingRequestGroup.Grave).Where(delegate(Thing x) + IEnumerable source = pawn.Map.listerThings.ThingsInGroup(ThingRequestGroup.Grave).Where((Func)delegate(Thing x) { Building_Grave building_Grave = (Building_Grave)x; return x.Faction == Faction.OfPlayer && building_Grave.HasCorpse && !building_Grave.IsForbidden(pawn) && building_Grave.Corpse.InnerPawn.Faction == Faction.OfPlayer && (allowedOutside || building_Grave.Position.Roofed(building_Grave.Map)) && pawn.CanReserveAndReach(x, PathEndMode.Touch, Danger.None, 1, -1, null, false); }); - Thing t; - if (!source.TryRandomElementByWeight(delegate(Thing x) + Thing t = default(Thing); + if (!source.TryRandomElementByWeight((Func)delegate(Thing x) { float lengthHorizontal = (x.Position - pawn.Position).LengthHorizontal; - return Mathf.Max(150f - lengthHorizontal, 5f); + return Mathf.Max((float)(150.0 - lengthHorizontal), 5f); }, out t)) { return null; } - return new Job(this.def.jobDef, t); + return new Job(base.def.jobDef, t); } } } diff --git a/Assembly-CSharp/RimWorld/JoyGiver_VisitSickPawn.cs b/Assembly-CSharp/RimWorld/JoyGiver_VisitSickPawn.cs index 73e876a88..4a2c48608 100644 --- a/Assembly-CSharp/RimWorld/JoyGiver_VisitSickPawn.cs +++ b/Assembly-CSharp/RimWorld/JoyGiver_VisitSickPawn.cs @@ -1,4 +1,3 @@ -using System; using Verse; using Verse.AI; @@ -17,7 +16,7 @@ public override Job TryGiveJob(Pawn pawn) { return null; } - return new Job(this.def.jobDef, pawn2, SickPawnVisitUtility.FindChair(pawn, pawn2)); + return new Job(base.def.jobDef, (Thing)pawn2, SickPawnVisitUtility.FindChair(pawn, pawn2)); } } } diff --git a/Assembly-CSharp/RimWorld/JoyGiver_WatchBuilding.cs b/Assembly-CSharp/RimWorld/JoyGiver_WatchBuilding.cs index 4c1314910..cf992f511 100644 --- a/Assembly-CSharp/RimWorld/JoyGiver_WatchBuilding.cs +++ b/Assembly-CSharp/RimWorld/JoyGiver_WatchBuilding.cs @@ -1,4 +1,3 @@ -using System; using Verse; using Verse.AI; @@ -22,13 +21,13 @@ protected override bool CanInteractWith(Pawn pawn, Thing t, bool inBed) protected override Job TryGivePlayJob(Pawn pawn, Thing t) { - IntVec3 c; - Building t2; - if (!WatchBuildingUtility.TryFindBestWatchCell(t, pawn, this.def.desireSit, out c, out t2)) + IntVec3 c = default(IntVec3); + Building t2 = default(Building); + if (!WatchBuildingUtility.TryFindBestWatchCell(t, pawn, base.def.desireSit, out c, out t2)) { return null; } - return new Job(this.def.jobDef, t, c, t2); + return new Job(base.def.jobDef, t, c, (Thing)t2); } } } diff --git a/Assembly-CSharp/RimWorld/JoyKindDef.cs b/Assembly-CSharp/RimWorld/JoyKindDef.cs index 899b72d97..853b79c14 100644 --- a/Assembly-CSharp/RimWorld/JoyKindDef.cs +++ b/Assembly-CSharp/RimWorld/JoyKindDef.cs @@ -1,4 +1,3 @@ -using System; using Verse; namespace RimWorld diff --git a/Assembly-CSharp/RimWorld/JoyKindDefOf.cs b/Assembly-CSharp/RimWorld/JoyKindDefOf.cs index 05a5ae777..7a780752d 100644 --- a/Assembly-CSharp/RimWorld/JoyKindDefOf.cs +++ b/Assembly-CSharp/RimWorld/JoyKindDefOf.cs @@ -1,5 +1,3 @@ -using System; - namespace RimWorld { [DefOf] diff --git a/Assembly-CSharp/RimWorld/JoyTickFullJoyAction.cs b/Assembly-CSharp/RimWorld/JoyTickFullJoyAction.cs index 712bf2eec..549f78aa5 100644 --- a/Assembly-CSharp/RimWorld/JoyTickFullJoyAction.cs +++ b/Assembly-CSharp/RimWorld/JoyTickFullJoyAction.cs @@ -1,11 +1,9 @@ -using System; - namespace RimWorld { public enum JoyTickFullJoyAction { - EndJob, - GoToNextToil, - None + EndJob = 0, + GoToNextToil = 1, + None = 2 } } diff --git a/Assembly-CSharp/RimWorld/JoyToleranceSet.cs b/Assembly-CSharp/RimWorld/JoyToleranceSet.cs index c89509ae5..cd0ecd4ce 100644 --- a/Assembly-CSharp/RimWorld/JoyToleranceSet.cs +++ b/Assembly-CSharp/RimWorld/JoyToleranceSet.cs @@ -1,4 +1,3 @@ -using System; using System.Collections.Generic; using System.Text; using UnityEngine; @@ -29,12 +28,12 @@ public void ExposeData() public void Notify_JoyGained(float amount, JoyKindDef joyKind) { - this.tolerances[joyKind] = Mathf.Min(this.tolerances[joyKind] + amount * 0.4f, 1f); + this.tolerances[joyKind] = Mathf.Min((float)(this.tolerances[joyKind] + amount * 0.40000000596046448), 1f); } public float JoyFactorFromTolerance(JoyKindDef joyKind) { - return 1f - this.tolerances[joyKind]; + return (float)(1.0 - this.tolerances[joyKind]); } public void NeedInterval() @@ -42,8 +41,8 @@ public void NeedInterval() for (int i = 0; i < this.tolerances.Count; i++) { float num = this.tolerances[i]; - num -= 0.000208333338f; - if (num < 0f) + num = (float)(num - 0.00020833333837799728); + if (num < 0.0) { num = 0f; } @@ -60,7 +59,7 @@ public string TolerancesString() { JoyKindDef joyKindDef = allDefsListForReading[i]; float num = this.tolerances[joyKindDef]; - if (num > 0.01f) + if (num > 0.0099999997764825821) { stringBuilder.AppendLine(" -" + joyKindDef.label + ": " + num.ToStringPercent()); } diff --git a/Assembly-CSharp/RimWorld/JoyUtility.cs b/Assembly-CSharp/RimWorld/JoyUtility.cs index 71a1a8a37..cb44d74b8 100644 --- a/Assembly-CSharp/RimWorld/JoyUtility.cs +++ b/Assembly-CSharp/RimWorld/JoyUtility.cs @@ -1,4 +1,3 @@ -using System; using System.Text; using Verse; using Verse.AI; @@ -12,7 +11,7 @@ public static class JoyUtility public static bool EnjoyableOutsideNow(Map map, StringBuilder outFailReason = null) { - if (map.weatherManager.RainRate >= 0.25f) + if (map.weatherManager.RainRate >= 0.25) { if (outFailReason != null) { @@ -20,7 +19,7 @@ public static bool EnjoyableOutsideNow(Map map, StringBuilder outFailReason = nu } return false; } - GameConditionDef gameConditionDef; + GameConditionDef gameConditionDef = default(GameConditionDef); if (!map.gameConditionManager.AllowEnjoyableOutsideNow(out gameConditionDef)) { if (outFailReason != null) @@ -60,26 +59,33 @@ public static void JoyTickCheckEnd(Pawn pawn, JoyTickFullJoyAction fullJoyAction if (curJob.def.joyKind == null) { Log.Warning("This method can only be called for jobs with joyKind."); - return; } - pawn.needs.joy.GainJoy(extraJoyGainFactor * curJob.def.joyGainRate * 0.000144f, curJob.def.joyKind); - if (curJob.def.joySkill != null) + else { - pawn.skills.GetSkill(curJob.def.joySkill).Learn(curJob.def.joyXpPerTick, false); - } - if (!curJob.ignoreJoyTimeAssignment && !pawn.GetTimeAssignment().allowJoy) - { - pawn.jobs.curDriver.EndJobWith(JobCondition.InterruptForced); - } - if (pawn.needs.joy.CurLevel > 0.9999f) - { - if (fullJoyAction == JoyTickFullJoyAction.EndJob) + pawn.needs.joy.GainJoy((float)(extraJoyGainFactor * curJob.def.joyGainRate * 0.00014400000509340316), curJob.def.joyKind); + if (curJob.def.joySkill != null) + { + pawn.skills.GetSkill(curJob.def.joySkill).Learn(curJob.def.joyXpPerTick, false); + } + if (!curJob.ignoreJoyTimeAssignment && !pawn.GetTimeAssignment().allowJoy) { - pawn.jobs.curDriver.EndJobWith(JobCondition.Succeeded); + pawn.jobs.curDriver.EndJobWith(JobCondition.InterruptForced); } - else if (fullJoyAction == JoyTickFullJoyAction.GoToNextToil) + if (pawn.needs.joy.CurLevel > 0.99989998340606689) { - pawn.jobs.curDriver.ReadyForNextToil(); + switch (fullJoyAction) + { + case JoyTickFullJoyAction.EndJob: + { + pawn.jobs.curDriver.EndJobWith(JobCondition.Succeeded); + break; + } + case JoyTickFullJoyAction.GoToNextToil: + { + pawn.jobs.curDriver.ReadyForNextToil(); + break; + } + } } } } @@ -100,13 +106,21 @@ public static void TryGainRecRoomThought(Pawn pawn) public static bool LordPreventsGettingJoy(Pawn pawn) { Lord lord = pawn.GetLord(); - return lord != null && !lord.CurLordToil.AllowSatisfyLongNeeds; + if (lord != null && !lord.CurLordToil.AllowSatisfyLongNeeds) + { + return true; + } + return false; } public static bool TimetablePreventsGettingJoy(Pawn pawn) { TimeAssignmentDef timeAssignmentDef = (pawn.timetable != null) ? pawn.timetable.CurrentAssignment : TimeAssignmentDefOf.Anything; - return !timeAssignmentDef.allowJoy; + if (!timeAssignmentDef.allowJoy) + { + return true; + } + return false; } } } diff --git a/Assembly-CSharp/RimWorld/KeyBindingCategoryDefOf.cs b/Assembly-CSharp/RimWorld/KeyBindingCategoryDefOf.cs index b53ed9190..a0f602c50 100644 --- a/Assembly-CSharp/RimWorld/KeyBindingCategoryDefOf.cs +++ b/Assembly-CSharp/RimWorld/KeyBindingCategoryDefOf.cs @@ -1,4 +1,3 @@ -using System; using Verse; namespace RimWorld diff --git a/Assembly-CSharp/RimWorld/KeyBindingDefOf.cs b/Assembly-CSharp/RimWorld/KeyBindingDefOf.cs index f2e0b06a5..12cfd9794 100644 --- a/Assembly-CSharp/RimWorld/KeyBindingDefOf.cs +++ b/Assembly-CSharp/RimWorld/KeyBindingDefOf.cs @@ -1,4 +1,3 @@ -using System; using Verse; namespace RimWorld diff --git a/Assembly-CSharp/RimWorld/KidnapAIUtility.cs b/Assembly-CSharp/RimWorld/KidnapAIUtility.cs index 5b50d1869..e5aee7602 100644 --- a/Assembly-CSharp/RimWorld/KidnapAIUtility.cs +++ b/Assembly-CSharp/RimWorld/KidnapAIUtility.cs @@ -9,18 +9,42 @@ public static class KidnapAIUtility { public static bool TryFindGoodKidnapVictim(Pawn kidnapper, float maxDist, out Pawn victim, List disallowed = null) { - if (!kidnapper.health.capacities.CapableOf(PawnCapacityDefOf.Manipulation) || !kidnapper.Map.reachability.CanReachMapEdge(kidnapper.Position, TraverseParms.For(kidnapper, Danger.Some, TraverseMode.ByPawn, false))) + if (kidnapper.health.capacities.CapableOf(PawnCapacityDefOf.Manipulation) && kidnapper.Map.reachability.CanReachMapEdge(kidnapper.Position, TraverseParms.For(kidnapper, Danger.Some, TraverseMode.ByPawn, false))) { - victim = null; - return false; + Predicate validator = (Predicate)delegate(Thing t) + { + Pawn pawn = t as Pawn; + if (!pawn.RaceProps.Humanlike) + { + return false; + } + if (!pawn.Downed) + { + return false; + } + if (pawn.Faction != Faction.OfPlayer) + { + return false; + } + if (!pawn.Faction.HostileTo(kidnapper.Faction)) + { + return false; + } + if (!kidnapper.CanReserve((Thing)pawn, 1, -1, null, false)) + { + return false; + } + if (disallowed != null && disallowed.Contains(pawn)) + { + return false; + } + return true; + }; + victim = (Pawn)GenClosest.ClosestThingReachable(kidnapper.Position, kidnapper.Map, ThingRequest.ForGroup(ThingRequestGroup.Pawn), PathEndMode.OnCell, TraverseParms.For(TraverseMode.NoPassClosedDoors, Danger.Some, false), maxDist, validator, null, 0, -1, false, RegionType.Set_Passable, false); + return victim != null; } - Predicate validator = delegate(Thing t) - { - Pawn pawn = t as Pawn; - return pawn.RaceProps.Humanlike && pawn.Downed && pawn.Faction == Faction.OfPlayer && pawn.Faction.HostileTo(kidnapper.Faction) && kidnapper.CanReserve(pawn, 1, -1, null, false) && (disallowed == null || !disallowed.Contains(pawn)); - }; - victim = (Pawn)GenClosest.ClosestThingReachable(kidnapper.Position, kidnapper.Map, ThingRequest.ForGroup(ThingRequestGroup.Pawn), PathEndMode.OnCell, TraverseParms.For(TraverseMode.NoPassClosedDoors, Danger.Some, false), maxDist, validator, null, 0, -1, false, RegionType.Set_Passable, false); - return victim != null; + victim = null; + return false; } public static Pawn ReachableWoundedGuest(Pawn searcher) @@ -29,7 +53,7 @@ public static Pawn ReachableWoundedGuest(Pawn searcher) for (int i = 0; i < list.Count; i++) { Pawn pawn = list[i]; - if (pawn.guest != null && !pawn.IsPrisoner && pawn.Downed && searcher.CanReserveAndReach(pawn, PathEndMode.OnCell, Danger.Some, 1, -1, null, false)) + if (pawn.guest != null && !pawn.IsPrisoner && pawn.Downed && searcher.CanReserveAndReach((Thing)pawn, PathEndMode.OnCell, Danger.Some, 1, -1, null, false)) { return pawn; } diff --git a/Assembly-CSharp/RimWorld/KidnappedPawnsTracker.cs b/Assembly-CSharp/RimWorld/KidnappedPawnsTracker.cs index 625f32cc7..2839b5450 100644 --- a/Assembly-CSharp/RimWorld/KidnappedPawnsTracker.cs +++ b/Assembly-CSharp/RimWorld/KidnappedPawnsTracker.cs @@ -33,7 +33,7 @@ public void ExposeData() { if (Scribe.mode == LoadSaveMode.Saving) { - this.kidnappedPawns.RemoveAll((Pawn x) => x.Destroyed); + this.kidnappedPawns.RemoveAll((Predicate)((Pawn x) => x.Destroyed)); } Scribe_Collections.Look(ref this.kidnappedPawns, "kidnappedPawns", LookMode.Reference, new object[0]); } @@ -43,26 +43,27 @@ public void KidnapPawn(Pawn pawn, Pawn kidnapper) if (this.kidnappedPawns.Contains(pawn)) { Log.Error("Tried to kidnap already kidnapped pawn " + pawn); - return; } - if (pawn.Faction == this.faction) + else if (pawn.Faction == this.faction) { Log.Error("Tried to kidnap pawn with the same faction: " + pawn); - return; } - pawn.PreKidnapped(kidnapper); - if (pawn.Spawned) + else { - pawn.DeSpawn(); - } - this.kidnappedPawns.Add(pawn); - if (!Find.WorldPawns.Contains(pawn)) - { - Find.WorldPawns.PassToWorld(pawn, PawnDiscardDecideMode.Decide); + pawn.PreKidnapped(kidnapper); + if (pawn.Spawned) + { + pawn.DeSpawn(); + } + this.kidnappedPawns.Add(pawn); if (!Find.WorldPawns.Contains(pawn)) { - Log.Error("WorldPawns discarded kidnapped pawn."); - this.kidnappedPawns.Remove(pawn); + Find.WorldPawns.PassToWorld(pawn, PawnDiscardDecideMode.Decide); + if (!Find.WorldPawns.Contains(pawn)) + { + Log.Error("WorldPawns discarded kidnapped pawn."); + this.kidnappedPawns.Remove(pawn); + } } } } @@ -88,15 +89,15 @@ public void LogKidnappedPawns() public void KidnappedPawnsTrackerTick() { - this.kidnappedPawns.RemoveAll((Pawn x) => x.DestroyedOrNull()); + this.kidnappedPawns.RemoveAll((Predicate)((Pawn x) => x.DestroyedOrNull())); if (Find.TickManager.TicksGame % 15051 == 0) { - for (int i = this.kidnappedPawns.Count - 1; i >= 0; i--) + for (int num = this.kidnappedPawns.Count - 1; num >= 0; num--) { if (Rand.MTBEventOccurs(30f, 60000f, 15051f)) { - this.kidnappedPawns[i].SetFaction(this.faction, null); - this.kidnappedPawns.RemoveAt(i); + this.kidnappedPawns[num].SetFaction(this.faction, null); + this.kidnappedPawns.RemoveAt(num); } } } diff --git a/Assembly-CSharp/RimWorld/KnowledgeAmount.cs b/Assembly-CSharp/RimWorld/KnowledgeAmount.cs index 16925fca9..65aac963f 100644 --- a/Assembly-CSharp/RimWorld/KnowledgeAmount.cs +++ b/Assembly-CSharp/RimWorld/KnowledgeAmount.cs @@ -1,17 +1,15 @@ -using System; - namespace RimWorld { public enum KnowledgeAmount : byte { - None, - FrameDisplayed, - FrameInteraction, - TinyInteraction, - SmallInteraction, - SpecificInteraction, - Total, - NoteClosed, - NoteTaught + None = 0, + FrameDisplayed = 1, + FrameInteraction = 2, + TinyInteraction = 3, + SmallInteraction = 4, + SpecificInteraction = 5, + Total = 6, + NoteClosed = 7, + NoteTaught = 8 } } diff --git a/Assembly-CSharp/RimWorld/LastPlayedVersion.cs b/Assembly-CSharp/RimWorld/LastPlayedVersion.cs index 09628a89d..45f5e7511 100644 --- a/Assembly-CSharp/RimWorld/LastPlayedVersion.cs +++ b/Assembly-CSharp/RimWorld/LastPlayedVersion.cs @@ -21,44 +21,43 @@ public static Version Version public static void InitializeIfNeeded() { - if (LastPlayedVersion.initialized) + if (!LastPlayedVersion.initialized) { - return; - } - try - { - string text = null; - if (File.Exists(GenFilePaths.LastPlayedVersionFilePath)) + try { - try - { - text = File.ReadAllText(GenFilePaths.LastPlayedVersionFilePath); - } - catch (Exception ex) + string text = (string)null; + if (File.Exists(GenFilePaths.LastPlayedVersionFilePath)) { - Log.Error("Exception getting last played version data. Path: " + GenFilePaths.LastPlayedVersionFilePath + ". Exception: " + ex.ToString()); + try + { + text = File.ReadAllText(GenFilePaths.LastPlayedVersionFilePath); + } + catch (Exception ex) + { + Log.Error("Exception getting last played version data. Path: " + GenFilePaths.LastPlayedVersionFilePath + ". Exception: " + ex.ToString()); + } } - } - if (text != null) - { - try + if (text != null) { - LastPlayedVersion.lastPlayedVersionInt = VersionControl.VersionFromString(text); + try + { + LastPlayedVersion.lastPlayedVersionInt = VersionControl.VersionFromString(text); + } + catch (Exception ex2) + { + Log.Error("Exception parsing last version from string '" + text + "': " + ex2.ToString()); + } } - catch (Exception ex2) + if (LastPlayedVersion.lastPlayedVersionInt != VersionControl.CurrentVersion) { - Log.Error("Exception parsing last version from string '" + text + "': " + ex2.ToString()); + File.WriteAllText(GenFilePaths.LastPlayedVersionFilePath, VersionControl.CurrentVersionString); } } - if (LastPlayedVersion.lastPlayedVersionInt != VersionControl.CurrentVersion) + finally { - File.WriteAllText(GenFilePaths.LastPlayedVersionFilePath, VersionControl.CurrentVersionString); + LastPlayedVersion.initialized = true; } } - finally - { - LastPlayedVersion.initialized = true; - } } } } diff --git a/Assembly-CSharp/RimWorld/LatestVersionGetter.cs b/Assembly-CSharp/RimWorld/LatestVersionGetter.cs index c9b894821..55efe3875 100644 --- a/Assembly-CSharp/RimWorld/LatestVersionGetter.cs +++ b/Assembly-CSharp/RimWorld/LatestVersionGetter.cs @@ -1,4 +1,3 @@ -using System; using UnityEngine; namespace RimWorld diff --git a/Assembly-CSharp/RimWorld/LearnRates.cs b/Assembly-CSharp/RimWorld/LearnRates.cs index 75f1bc1d9..e73934c59 100644 --- a/Assembly-CSharp/RimWorld/LearnRates.cs +++ b/Assembly-CSharp/RimWorld/LearnRates.cs @@ -1,5 +1,3 @@ -using System; - namespace RimWorld { public static class LearnRates diff --git a/Assembly-CSharp/RimWorld/LearningReadout.cs b/Assembly-CSharp/RimWorld/LearningReadout.cs index f92a03fe6..7696bdfde 100644 --- a/Assembly-CSharp/RimWorld/LearningReadout.cs +++ b/Assembly-CSharp/RimWorld/LearningReadout.cs @@ -62,7 +62,7 @@ public void ExposeData() Scribe_Defs.Look(ref this.selectedConcept, "selectedConcept"); if (Scribe.mode == LoadSaveMode.PostLoadInit) { - this.activeConcepts.RemoveAll((ConceptDef c) => PlayerKnowledgeDatabase.IsComplete(c)); + this.activeConcepts.RemoveAll((Predicate)((ConceptDef c) => PlayerKnowledgeDatabase.IsComplete(c))); } } @@ -119,132 +119,125 @@ private string FilterSearchStringInput(string input) public void LearningReadoutOnGUI() { - if (TutorSystem.TutorialMode || !TutorSystem.AdaptiveTrainingEnabled) + if (!TutorSystem.TutorialMode && (TutorSystem.AdaptiveTrainingEnabled ? (Find.PlaySettings.showLearningHelper ? 1 : this.activeConcepts.Count) : 0) != 0 && !Find.WindowStack.IsOpen()) { - return; - } - if (!Find.PlaySettings.showLearningHelper && this.activeConcepts.Count == 0) - { - return; - } - if (Find.WindowStack.IsOpen()) - { - return; - } - float b = (float)UI.screenHeight / 2f; - float a = this.contentHeight + 14f; - Rect outRect = new Rect((float)UI.screenWidth - 8f - 200f, 8f, 200f, Mathf.Min(a, b)); - Rect outRect2 = outRect; - Find.WindowStack.ImmediateWindow(76136312, outRect, WindowLayer.Super, delegate - { - outRect = outRect.AtZero(); - Rect rect = outRect.ContractedBy(7f); - Rect viewRect = rect.AtZero(); - bool flag = this.contentHeight > rect.height; - Widgets.DrawWindowBackgroundTutor(outRect); - if (flag) - { - viewRect.height = this.contentHeight + 40f; - viewRect.width -= 20f; - this.scrollPosition = GUI.BeginScrollView(rect, this.scrollPosition, viewRect); - } - else + float b = (float)((float)UI.screenHeight / 2.0); + float a = (float)(this.contentHeight + 14.0); + Rect outRect = new Rect((float)((float)UI.screenWidth - 8.0 - 200.0), 8f, 200f, Mathf.Min(a, b)); + Rect rect = outRect; + Find.WindowStack.ImmediateWindow(76136312, outRect, WindowLayer.Super, (Action)delegate() { - GUI.BeginGroup(rect); - } - float num2 = 0f; - Text.Font = GameFont.Small; - Rect rect2 = new Rect(0f, 0f, viewRect.width - 24f, 24f); - Widgets.Label(rect2, "LearningHelper".Translate()); - num2 = rect2.yMax; - Rect butRect = new Rect(rect2.xMax, rect2.y, 24f, 24f); - if (Widgets.ButtonImage(butRect, this.showAllMode ? TexButton.Minus : TexButton.Plus)) - { - this.showAllMode = !this.showAllMode; + Rect outRect2 = outRect.AtZero(); + Rect rect2 = outRect2.ContractedBy(7f); + Rect viewRect = rect2.AtZero(); + bool flag = this.contentHeight > rect2.height; + Widgets.DrawWindowBackgroundTutor(outRect2); + if (flag) + { + viewRect.height = (float)(this.contentHeight + 40.0); + viewRect.width -= 20f; + this.scrollPosition = GUI.BeginScrollView(rect2, this.scrollPosition, viewRect); + } + else + { + GUI.BeginGroup(rect2); + } + float num2 = 0f; + Text.Font = GameFont.Small; + Rect rect3 = new Rect(0f, 0f, (float)(viewRect.width - 24.0), 24f); + Widgets.Label(rect3, "LearningHelper".Translate()); + num2 = rect3.yMax; + Rect butRect = new Rect(rect3.xMax, rect3.y, 24f, 24f); + if (Widgets.ButtonImage(butRect, this.showAllMode ? TexButton.Minus : TexButton.Plus)) + { + this.showAllMode = !this.showAllMode; + if (this.showAllMode) + { + SoundDefOf.TickHigh.PlayOneShotOnCamera(null); + } + else + { + SoundDefOf.TickLow.PlayOneShotOnCamera(null); + } + } if (this.showAllMode) { - SoundDefOf.TickHigh.PlayOneShotOnCamera(null); + Rect rect4 = new Rect(0f, num2, (float)(viewRect.width - 20.0 - 2.0), 28f); + this.searchString = this.FilterSearchStringInput(Widgets.TextField(rect4, this.searchString)); + if (this.searchString == string.Empty) + { + GUI.color = new Color(0.6f, 0.6f, 0.6f, 1f); + Text.Anchor = TextAnchor.MiddleLeft; + Rect rect5 = rect4; + rect5.xMin += 7f; + Widgets.Label(rect5, "Filter".Translate() + "..."); + Text.Anchor = TextAnchor.UpperLeft; + GUI.color = Color.white; + } + Rect butRect2 = new Rect((float)(viewRect.width - 20.0), (float)(num2 + 14.0 - 10.0), 20f, 20f); + if (Widgets.ButtonImage(butRect2, TexButton.CloseXSmall)) + { + this.searchString = string.Empty; + SoundDefOf.TickTiny.PlayOneShotOnCamera(null); + } + num2 = (float)(rect4.yMax + 4.0); + } + object obj; + if (!this.showAllMode) + { + IEnumerable enumerable = this.activeConcepts; + obj = enumerable; } else { - SoundDefOf.TickLow.PlayOneShotOnCamera(null); + obj = DefDatabase.AllDefs; } - } - if (this.showAllMode) - { - Rect rect3 = new Rect(0f, num2, viewRect.width - 20f - 2f, 28f); - this.searchString = this.FilterSearchStringInput(Widgets.TextField(rect3, this.searchString)); - if (this.searchString == string.Empty) + IEnumerable enumerable2 = (IEnumerable)obj; + if (enumerable2.Any()) { - GUI.color = new Color(0.6f, 0.6f, 0.6f, 1f); - Text.Anchor = TextAnchor.MiddleLeft; - Rect rect4 = rect3; - rect4.xMin += 7f; - Widgets.Label(rect4, "Filter".Translate() + "..."); - Text.Anchor = TextAnchor.UpperLeft; + GUI.color = new Color(1f, 1f, 1f, 0.5f); + Widgets.DrawLineHorizontal(0f, num2, viewRect.width); GUI.color = Color.white; + num2 = (float)(num2 + 4.0); } - Rect butRect2 = new Rect(viewRect.width - 20f, num2 + 14f - 10f, 20f, 20f); - if (Widgets.ButtonImage(butRect2, TexButton.CloseXSmall)) + if (this.showAllMode) { - this.searchString = string.Empty; - SoundDefOf.TickTiny.PlayOneShotOnCamera(null); + enumerable2 = from c in enumerable2 + orderby this.DisplayPriority(c) descending, c.label + select c; } - num2 = rect3.yMax + 4f; - } - IEnumerable arg_2E3_0; - if (!this.showAllMode) - { - IEnumerable enumerable = this.activeConcepts; - arg_2E3_0 = enumerable; - } - else - { - arg_2E3_0 = DefDatabase.AllDefs; - } - IEnumerable enumerable2 = arg_2E3_0; - if (enumerable2.Any()) - { - GUI.color = new Color(1f, 1f, 1f, 0.5f); - Widgets.DrawLineHorizontal(0f, num2, viewRect.width); - GUI.color = Color.white; - num2 += 4f; - } - if (this.showAllMode) - { - enumerable2 = from c in enumerable2 - orderby this.DisplayPriority(c) descending, c.label - select c; - } - foreach (ConceptDef current in enumerable2) - { - if (!current.TriggeredDirect) + foreach (ConceptDef item in enumerable2) + { + if (!item.TriggeredDirect) + { + num2 = this.DrawConceptListRow(0f, num2, viewRect.width, item).yMax; + } + } + this.contentHeight = num2; + if (flag) { - num2 = this.DrawConceptListRow(0f, num2, viewRect.width, current).yMax; + GUI.EndScrollView(); } - } - this.contentHeight = num2; - if (flag) + else + { + GUI.EndGroup(); + } + }, false, false, 1f); + float num = Time.realtimeSinceStartup - this.lastConceptActivateRealTime; + if (num < 1.0 && num > 0.0) { - GUI.EndScrollView(); + float x = rect.x; + Vector2 center = rect.center; + GenUI.DrawFlash(x, center.y, (float)((float)UI.screenWidth * 0.60000002384185791), (float)(Pulser.PulseBrightness(1f, 1f, num) * 0.85000002384185791), new Color(0.8f, 0.77f, 0.53f)); } - else + ConceptDef conceptDef = (this.selectedConcept == null) ? this.mouseoverConcept : this.selectedConcept; + if (conceptDef != null) { - GUI.EndGroup(); + this.DrawInfoPane(conceptDef); + conceptDef.HighlightAllTags(); } - }, false, false, 1f); - float num = Time.realtimeSinceStartup - this.lastConceptActivateRealTime; - if (num < 1f && num > 0f) - { - GenUI.DrawFlash(outRect2.x, outRect2.center.y, (float)UI.screenWidth * 0.6f, Pulser.PulseBrightness(1f, 1f, num) * 0.85f, new Color(0.8f, 0.77f, 0.53f)); - } - ConceptDef conceptDef = (this.selectedConcept == null) ? this.mouseoverConcept : this.selectedConcept; - if (conceptDef != null) - { - this.DrawInfoPane(conceptDef); - conceptDef.HighlightAllTags(); + this.mouseoverConcept = null; } - this.mouseoverConcept = null; } private int DisplayPriority(ConceptDef conc) @@ -266,7 +259,7 @@ private Rect DrawConceptListRow(float x, float y, float width, ConceptDef conc) { float knowledge = PlayerKnowledgeDatabase.GetKnowledge(conc); bool flag = PlayerKnowledgeDatabase.IsComplete(conc); - bool flag2 = !flag && knowledge > 0f; + bool flag2 = !flag && knowledge > 0.0; float num = Text.CalcHeight(conc.LabelCap, width); if (flag2) { @@ -317,23 +310,23 @@ private Rect DrawInfoPane(ConceptDef conc) { float knowledge = PlayerKnowledgeDatabase.GetKnowledge(conc); bool complete = PlayerKnowledgeDatabase.IsComplete(conc); - bool drawProgressBar = !complete && knowledge > 0f; + bool drawProgressBar = !complete && knowledge > 0.0; Text.Font = GameFont.Medium; float titleHeight = Text.CalcHeight(conc.LabelCap, 276f); Text.Font = GameFont.Small; float textHeight = Text.CalcHeight(conc.HelpTextAdjusted, 296f); - float num = titleHeight + textHeight + 14f + 5f; + float num = (float)(titleHeight + textHeight + 14.0 + 5.0); if (this.selectedConcept == conc) { - num += 40f; + num = (float)(num + 40.0); } if (drawProgressBar) { - num += 30f; + num = (float)(num + 30.0); } - Rect outRect = new Rect((float)UI.screenWidth - 8f - 200f - 8f - 310f, 8f, 310f, num); - Rect outRect2 = outRect; - Find.WindowStack.ImmediateWindow(987612111, outRect, WindowLayer.Super, delegate + Rect outRect = new Rect((float)((float)UI.screenWidth - 8.0 - 200.0 - 8.0 - 310.0), 8f, 310f, num); + Rect result = outRect; + Find.WindowStack.ImmediateWindow(987612111, outRect, WindowLayer.Super, (Action)delegate() { outRect = outRect.AtZero(); Rect rect = outRect.ContractedBy(7f); @@ -341,7 +334,7 @@ private Rect DrawInfoPane(ConceptDef conc) Widgets.DrawWindowBackgroundTutor(outRect); Rect rect2 = rect; rect2.width -= 20f; - rect2.height = titleHeight + 5f; + rect2.height = (float)(titleHeight + 5.0); Text.Font = GameFont.Medium; Widgets.Label(rect2, conc.LabelCap); Text.Font = GameFont.Small; @@ -363,7 +356,8 @@ private Rect DrawInfoPane(ConceptDef conc) this.selectedConcept = null; SoundDefOf.PageChange.PlayOneShotOnCamera(null); } - Rect rect5 = new Rect(rect.center.x - 70f, rect.yMax - 30f, 140f, 30f); + Vector2 center = rect.center; + Rect rect5 = new Rect((float)(center.x - 70.0), (float)(rect.yMax - 30.0), 140f, 30f); if (!complete) { if (Widgets.ButtonText(rect5, "MarkLearned".Translate(), true, false, true)) @@ -383,7 +377,7 @@ private Rect DrawInfoPane(ConceptDef conc) } } }, false, false, 1f); - return outRect2; + return result; } } } diff --git a/Assembly-CSharp/RimWorld/Lesson.cs b/Assembly-CSharp/RimWorld/Lesson.cs index d3553e646..bbef8cee8 100644 --- a/Assembly-CSharp/RimWorld/Lesson.cs +++ b/Assembly-CSharp/RimWorld/Lesson.cs @@ -1,4 +1,3 @@ -using System; using UnityEngine; using Verse; @@ -14,7 +13,7 @@ protected float AgeSeconds { get { - if (this.startRealTime < 0f) + if (this.startRealTime < 0.0) { this.startRealTime = Time.realtimeSinceStartup; } @@ -42,7 +41,7 @@ public virtual string DefaultRejectInputMessage { get { - return null; + return (string)null; } } diff --git a/Assembly-CSharp/RimWorld/LessonAutoActivator.cs b/Assembly-CSharp/RimWorld/LessonAutoActivator.cs index ee9034d14..4dfad221c 100644 --- a/Assembly-CSharp/RimWorld/LessonAutoActivator.cs +++ b/Assembly-CSharp/RimWorld/LessonAutoActivator.cs @@ -39,7 +39,7 @@ private static float RelaxDesire { get { - return 100f - LessonAutoActivator.SecondsSinceLesson * 0.111111112f; + return (float)(100.0 - LessonAutoActivator.SecondsSinceLesson * 0.1111111119389534); } } @@ -55,29 +55,35 @@ public static void TeachOpportunity(ConceptDef conc, OpportunityType opp) public static void TeachOpportunity(ConceptDef conc, Thing subject, OpportunityType opp) { - if (!TutorSystem.AdaptiveTrainingEnabled || PlayerKnowledgeDatabase.IsComplete(conc)) - { - return; - } - float value = 999f; - switch (opp) - { - case OpportunityType.GoodToKnow: - value = 60f; - break; - case OpportunityType.Important: - value = 80f; - break; - case OpportunityType.Critical: - value = 100f; - break; - default: - Log.Error("Unknown need"); - break; - } - LessonAutoActivator.opportunities[conc] = value; - if (opp >= OpportunityType.Important || Find.Tutor.learningReadout.ActiveConceptsCount < 4) + if (TutorSystem.AdaptiveTrainingEnabled && !PlayerKnowledgeDatabase.IsComplete(conc)) { + float value = 999f; + switch (opp) + { + case OpportunityType.GoodToKnow: + { + value = 60f; + break; + } + case OpportunityType.Important: + { + value = 80f; + break; + } + case OpportunityType.Critical: + { + value = 100f; + break; + } + default: + { + Log.Error("Unknown need"); + break; + } + } + LessonAutoActivator.opportunities[conc] = value; + if ((int)opp < 1 && Find.Tutor.learningReadout.ActiveConceptsCount >= 4) + return; LessonAutoActivator.TryInitiateLesson(conc); } } @@ -92,63 +98,67 @@ public static void Notify_KnowledgeDemonstrated(ConceptDef conc) public static void LessonAutoActivatorUpdate() { - if (!TutorSystem.AdaptiveTrainingEnabled || Current.Game == null || Find.Tutor.learningReadout.ShowAllMode) - { - return; - } - LessonAutoActivator.timeSinceLastLesson += RealTime.realDeltaTime; - if (Current.ProgramState == ProgramState.Playing && (Time.timeSinceLevelLoad < 8f || Find.WindowStack.SecondsSinceClosedGameStartDialog < 8f || Find.TickManager.NotPlaying)) + if (TutorSystem.AdaptiveTrainingEnabled && Current.Game != null && !Find.Tutor.learningReadout.ShowAllMode) { - return; - } - for (int i = LessonAutoActivator.alertingConcepts.Count - 1; i >= 0; i--) - { - if (PlayerKnowledgeDatabase.IsComplete(LessonAutoActivator.alertingConcepts[i])) + LessonAutoActivator.timeSinceLastLesson += RealTime.realDeltaTime; + if (Current.ProgramState == ProgramState.Playing) { - LessonAutoActivator.alertingConcepts.RemoveAt(i); + if (Time.timeSinceLevelLoad < 8.0) + return; + if (Find.WindowStack.SecondsSinceClosedGameStartDialog < 8.0) + return; + if (Find.TickManager.NotPlaying) + return; } - } - if (Time.frameCount % 15 == 0 && Find.ActiveLesson.Current == null) - { - for (int j = 0; j < DefDatabase.AllDefsListForReading.Count; j++) + for (int num = LessonAutoActivator.alertingConcepts.Count - 1; num >= 0; num--) { - ConceptDef conceptDef = DefDatabase.AllDefsListForReading[j]; - if (!PlayerKnowledgeDatabase.IsComplete(conceptDef)) + if (PlayerKnowledgeDatabase.IsComplete(LessonAutoActivator.alertingConcepts[num])) { - float num = PlayerKnowledgeDatabase.GetKnowledge(conceptDef); - num -= 0.00015f * Time.deltaTime * 15f; - if (num < 0f) - { - num = 0f; - } - PlayerKnowledgeDatabase.SetKnowledge(conceptDef, num); - if (conceptDef.opportunityDecays) + LessonAutoActivator.alertingConcepts.RemoveAt(num); + } + } + if (Time.frameCount % 15 == 0 && Find.ActiveLesson.Current == null) + { + for (int i = 0; i < DefDatabase.AllDefsListForReading.Count; i++) + { + ConceptDef conceptDef = DefDatabase.AllDefsListForReading[i]; + if (!PlayerKnowledgeDatabase.IsComplete(conceptDef)) { - float num2 = LessonAutoActivator.GetOpportunity(conceptDef); - num2 -= 0.4f * Time.deltaTime * 15f; - if (num2 < 0f) + float knowledge = PlayerKnowledgeDatabase.GetKnowledge(conceptDef); + knowledge = (float)(knowledge - 0.0001500000071246177 * Time.deltaTime * 15.0); + if (knowledge < 0.0) { - num2 = 0f; + knowledge = 0f; + } + PlayerKnowledgeDatabase.SetKnowledge(conceptDef, knowledge); + if (conceptDef.opportunityDecays) + { + float opportunity = LessonAutoActivator.GetOpportunity(conceptDef); + opportunity = (float)(opportunity - 0.40000000596046448 * Time.deltaTime * 15.0); + if (opportunity < 0.0) + { + opportunity = 0f; + } + LessonAutoActivator.opportunities[conceptDef] = opportunity; } - LessonAutoActivator.opportunities[conceptDef] = num2; } } - } - if (Find.Tutor.learningReadout.ActiveConceptsCount < 3) - { - ConceptDef conceptDef2 = LessonAutoActivator.MostDesiredConcept(); - if (conceptDef2 != null) + if (Find.Tutor.learningReadout.ActiveConceptsCount < 3) { - float desire = LessonAutoActivator.GetDesire(conceptDef2); - if (desire > 0.1f && LessonAutoActivator.RelaxDesire < desire) + ConceptDef conceptDef2 = LessonAutoActivator.MostDesiredConcept(); + if (conceptDef2 != null) { - LessonAutoActivator.TryInitiateLesson(conceptDef2); + float desire = LessonAutoActivator.GetDesire(conceptDef2); + if (desire > 0.10000000149011612 && LessonAutoActivator.RelaxDesire < desire) + { + LessonAutoActivator.TryInitiateLesson(conceptDef2); + } } } - } - else - { - LessonAutoActivator.SetLastLessonTimeToNow(); + else + { + LessonAutoActivator.SetLastLessonTimeToNow(); + } } } } @@ -162,16 +172,10 @@ private static ConceptDef MostDesiredConcept() { ConceptDef conceptDef = allDefsListForReading[i]; float desire = LessonAutoActivator.GetDesire(conceptDef); - if (desire > num) + if (desire > num && (!conceptDef.needsOpportunity || !(LessonAutoActivator.GetOpportunity(conceptDef) < 0.10000000149011612)) && !(PlayerKnowledgeDatabase.GetKnowledge(conceptDef) > 0.15000000596046448)) { - if (!conceptDef.needsOpportunity || LessonAutoActivator.GetOpportunity(conceptDef) >= 0.1f) - { - if (PlayerKnowledgeDatabase.GetKnowledge(conceptDef) <= 0.15f) - { - num = desire; - result = conceptDef; - } - } + num = desire; + result = conceptDef; } } return result; @@ -191,19 +195,19 @@ private static float GetDesire(ConceptDef conc) { return 0f; } - if (conc.needsOpportunity && LessonAutoActivator.GetOpportunity(conc) < 0.1f) + if (conc.needsOpportunity && LessonAutoActivator.GetOpportunity(conc) < 0.10000000149011612) { return 0f; } float num = 0f; num += conc.priority; - num += LessonAutoActivator.GetOpportunity(conc) / 100f * 60f; - return num * (1f - PlayerKnowledgeDatabase.GetKnowledge(conc)); + num = (float)(num + LessonAutoActivator.GetOpportunity(conc) / 100.0 * 60.0); + return (float)(num * (1.0 - PlayerKnowledgeDatabase.GetKnowledge(conc))); } private static float GetOpportunity(ConceptDef conc) { - float result; + float result = default(float); if (LessonAutoActivator.opportunities.TryGetValue(conc, out result)) { return result; @@ -234,26 +238,17 @@ public static string DebugString() { StringBuilder stringBuilder = new StringBuilder(); stringBuilder.AppendLine("RelaxDesire: " + LessonAutoActivator.RelaxDesire); - foreach (ConceptDef current in from co in DefDatabase.AllDefs + foreach (ConceptDef item in from co in DefDatabase.AllDefs orderby LessonAutoActivator.GetDesire(co) descending select co) { - if (PlayerKnowledgeDatabase.IsComplete(current)) + if (PlayerKnowledgeDatabase.IsComplete(item)) { - stringBuilder.AppendLine(current.defName + " complete"); + stringBuilder.AppendLine(item.defName + " complete"); } else { - stringBuilder.AppendLine(string.Concat(new string[] - { - current.defName, - "\n know ", - PlayerKnowledgeDatabase.GetKnowledge(current).ToString("F3"), - "\n need ", - LessonAutoActivator.opportunities[current].ToString("F3"), - "\n des ", - LessonAutoActivator.GetDesire(current).ToString("F3") - })); + stringBuilder.AppendLine(item.defName + "\n know " + PlayerKnowledgeDatabase.GetKnowledge(item).ToString("F3") + "\n need " + LessonAutoActivator.opportunities[item].ToString("F3") + "\n des " + LessonAutoActivator.GetDesire(item).ToString("F3")); } } return stringBuilder.ToString(); @@ -263,7 +258,7 @@ public static void DebugForceInitiateBestLessonNow() { LessonAutoActivator.TryInitiateLesson((from def in DefDatabase.AllDefs orderby LessonAutoActivator.GetDesire(def) descending - select def).First()); + select def).First()); } } } diff --git a/Assembly-CSharp/RimWorld/Lesson_Instruction.cs b/Assembly-CSharp/RimWorld/Lesson_Instruction.cs index fb46fc65b..522228cef 100644 --- a/Assembly-CSharp/RimWorld/Lesson_Instruction.cs +++ b/Assembly-CSharp/RimWorld/Lesson_Instruction.cs @@ -33,7 +33,7 @@ protected virtual bool ShowProgressBar { get { - return this.ProgressPercent >= 0f; + return this.ProgressPercent >= 0.0; } } @@ -62,11 +62,11 @@ public override void OnActivated() } if (this.def.resetBuildDesignatorStuffs) { - foreach (DesignationCategoryDef current in DefDatabase.AllDefs) + foreach (DesignationCategoryDef allDef in DefDatabase.AllDefs) { - foreach (Designator current2 in current.ResolvedAllowedDesignators) + foreach (Designator resolvedAllowedDesignator in allDef.ResolvedAllowedDesignators) { - Designator_Build designator_Build = current2 as Designator_Build; + Designator_Build designator_Build = resolvedAllowedDesignator as Designator_Build; if (designator_Build != null) { designator_Build.ResetStuffToDefault(); @@ -81,34 +81,34 @@ public override void LessonOnGUI() Text.Font = GameFont.Small; string textAdj = this.def.text.AdjustedForKeys(); float num = Text.CalcHeight(textAdj, 290f); - float num2 = num + 20f; + float num2 = (float)(num + 20.0); if (this.ShowProgressBar) { - num2 += 47f; + num2 = (float)(num2 + 47.0); } - Vector2 b = new Vector2((float)UI.screenWidth - 17f - 155f, 17f + num2 / 2f); + Vector2 b = new Vector2((float)((float)UI.screenWidth - 17.0 - 155.0), (float)(17.0 + num2 / 2.0)); if (!Find.TutorialState.introDone) { float screenOverlayAlpha = 0f; if (this.def.startCentered) { Vector2 vector = new Vector2((float)(UI.screenWidth / 2), (float)(UI.screenHeight / 2)); - if (base.AgeSeconds < 4f) + if (base.AgeSeconds < 4.0) { b = vector; screenOverlayAlpha = 0.9f; } - else if (base.AgeSeconds < 5f) + else if (base.AgeSeconds < 5.0) { - float t = (base.AgeSeconds - 4f) / 1f; + float t = (float)((base.AgeSeconds - 4.0) / 1.0); b = Vector2.Lerp(vector, b, t); screenOverlayAlpha = Mathf.Lerp(0.9f, 0f, t); } } - if (screenOverlayAlpha > 0f) + if (screenOverlayAlpha > 0.0) { Rect fullScreenRect = new Rect(0f, 0f, (float)UI.screenWidth, (float)UI.screenHeight); - Find.WindowStack.ImmediateWindow(972651, fullScreenRect, WindowLayer.SubSuper, delegate + Find.WindowStack.ImmediateWindow(972651, fullScreenRect, WindowLayer.SubSuper, (Action)delegate { GUI.color = new Color(1f, 1f, 1f, screenOverlayAlpha); GUI.DrawTexture(fullScreenRect, BaseContent.BlackTex); @@ -120,8 +120,8 @@ public override void LessonOnGUI() Find.TutorialState.introDone = true; } } - Rect mainRect = new Rect(b.x - 155f, b.y - num2 / 2f - 10f, 310f, num2); - Find.WindowStack.ImmediateWindow(177706, mainRect, WindowLayer.Super, delegate + Rect mainRect = new Rect((float)(b.x - 155.0), (float)(b.y - num2 / 2.0 - 10.0), 310f, num2); + Find.WindowStack.ImmediateWindow(177706, mainRect, WindowLayer.Super, (Action)delegate { Rect rect = mainRect.AtZero(); Widgets.DrawWindowBackgroundTutor(rect); @@ -135,12 +135,12 @@ public override void LessonOnGUI() Widgets.Label(rect3, textAdj); if (this.ShowProgressBar) { - Rect rect4 = new Rect(rect2.x, rect2.yMax - 30f, rect2.width, 30f); + Rect rect4 = new Rect(rect2.x, (float)(rect2.yMax - 30.0), rect2.width, 30f); Widgets.FillableBar(rect4, this.ProgressPercent, LearningReadout.ProgressBarFillTex); } - if (this.AgeSeconds < 0.5f) + if (base.AgeSeconds < 0.5) { - GUI.color = new Color(1f, 1f, 1f, Mathf.Lerp(1f, 0f, this.AgeSeconds / 0.5f)); + GUI.color = new Color(1f, 1f, 1f, Mathf.Lerp(1f, 0f, (float)(base.AgeSeconds / 0.5))); GUI.DrawTexture(rect, BaseContent.WhiteTex); GUI.color = Color.white; } diff --git a/Assembly-CSharp/RimWorld/Lesson_Note.cs b/Assembly-CSharp/RimWorld/Lesson_Note.cs index a74f8a2f3..0394cefa7 100644 --- a/Assembly-CSharp/RimWorld/Lesson_Note.cs +++ b/Assembly-CSharp/RimWorld/Lesson_Note.cs @@ -31,7 +31,7 @@ public bool Expiring { get { - return this.expiryTime < 3.40282347E+38f; + return this.expiryTime < 3.4028234663852886E+38; } } @@ -40,8 +40,9 @@ public Rect MainRect get { float num = Text.CalcHeight(this.def.HelpTextAdjusted, 432f); - float height = num + 20f; - return new Rect(Messages.MessagesTopLeftStandard.x, 0f, 500f, height); + float height = (float)(num + 20.0); + Vector2 messagesTopLeftStandard = Messages.MessagesTopLeftStandard; + return new Rect(messagesTopLeftStandard.x, 0f, 500f, height); } } @@ -79,19 +80,19 @@ public override void LessonOnGUI() float alpha = 1f; if (this.doFadeIn) { - alpha = Mathf.Clamp01(base.AgeSeconds / 0.4f); + alpha = Mathf.Clamp01((float)(base.AgeSeconds / 0.40000000596046448)); } if (this.Expiring) { float num = this.expiryTime - Time.timeSinceLevelLoad; - if (num < 1.1f) + if (num < 1.1000000238418579) { - alpha = num / 1.1f; + alpha = (float)(num / 1.1000000238418579); } } - WindowStack arg_9D_0 = Find.WindowStack; - float alpha2 = alpha; - arg_9D_0.ImmediateWindow(134706, mainRect, WindowLayer.Super, delegate + WindowStack windowStack = Find.WindowStack; + float shadowAlpha = alpha; + windowStack.ImmediateWindow(134706, mainRect, WindowLayer.Super, (Action)delegate { Rect rect = mainRect.AtZero(); Text.Font = GameFont.Small; @@ -107,16 +108,8 @@ public override void LessonOnGUI() Rect rect2 = rect.ContractedBy(10f); rect2.width = 432f; Widgets.Label(rect2, this.def.HelpTextAdjusted); - Rect butRect = new Rect(rect.xMax - 32f - 8f, rect.y + 8f, 32f, 32f); - Texture2D tex; - if (this.Expiring) - { - tex = Widgets.CheckboxOnTex; - } - else - { - tex = TexButton.CloseXBig; - } + Rect butRect = new Rect((float)(rect.xMax - 32.0 - 8.0), (float)(rect.y + 8.0), 32f, 32f); + Texture2D tex = (!this.Expiring) ? TexButton.CloseXBig : Widgets.CheckboxOnTex; if (Widgets.ButtonImage(butRect, tex, new Color(0.95f, 0.95f, 0.95f), new Color(0.8352941f, 0.6666667f, 0.274509817f))) { SoundDefOf.Click.PlayOneShotOnCamera(null); @@ -127,21 +120,21 @@ public override void LessonOnGUI() this.CloseButtonClicked(); } GUI.color = Color.white; - }, false, false, alpha2); + }, false, false, shadowAlpha); } private void CloseButtonClicked() { - KnowledgeAmount know = (!this.def.noteTeaches) ? KnowledgeAmount.NoteClosed : KnowledgeAmount.NoteTaught; + KnowledgeAmount know = (KnowledgeAmount)((!this.def.noteTeaches) ? 7 : 8); PlayerKnowledgeDatabase.KnowledgeDemonstrated(this.def, know); Find.ActiveLesson.Deactivate(); } public override void Notify_KnowledgeDemonstrated(ConceptDef conc) { - if (this.def == conc && PlayerKnowledgeDatabase.GetKnowledge(conc) > 0.2f && !this.Expiring) + if (this.def == conc && PlayerKnowledgeDatabase.GetKnowledge(conc) > 0.20000000298023224 && !this.Expiring) { - this.expiryTime = Time.timeSinceLevelLoad + 2.1f; + this.expiryTime = (float)(Time.timeSinceLevelLoad + 2.0999999046325684); } } } diff --git a/Assembly-CSharp/RimWorld/LetterDefOf.cs b/Assembly-CSharp/RimWorld/LetterDefOf.cs index ac0941f60..aafd879bc 100644 --- a/Assembly-CSharp/RimWorld/LetterDefOf.cs +++ b/Assembly-CSharp/RimWorld/LetterDefOf.cs @@ -1,4 +1,3 @@ -using System; using Verse; namespace RimWorld diff --git a/Assembly-CSharp/RimWorld/LifeStageDef.cs b/Assembly-CSharp/RimWorld/LifeStageDef.cs index 1b4988fb3..489afffd9 100644 --- a/Assembly-CSharp/RimWorld/LifeStageDef.cs +++ b/Assembly-CSharp/RimWorld/LifeStageDef.cs @@ -42,7 +42,7 @@ public string Adjective { get { - return this.adjective ?? this.label; + return this.adjective ?? base.label; } } @@ -51,7 +51,7 @@ public override void ResolveReferences() base.ResolveReferences(); if (!this.icon.NullOrEmpty()) { - LongEventHandler.ExecuteWhenFinished(delegate + LongEventHandler.ExecuteWhenFinished((Action)delegate { this.iconTex = ContentFinder.Get(this.icon, true); }); diff --git a/Assembly-CSharp/RimWorld/LightningBoltMeshMaker.cs b/Assembly-CSharp/RimWorld/LightningBoltMeshMaker.cs index 9b72c18ba..911893ab4 100644 --- a/Assembly-CSharp/RimWorld/LightningBoltMeshMaker.cs +++ b/Assembly-CSharp/RimWorld/LightningBoltMeshMaker.cs @@ -37,11 +37,11 @@ public static Mesh NewBoltMesh() private static void MakeVerticesBase() { - int num = (int)Math.Ceiling((double)((Vector2.zero - LightningBoltMeshMaker.lightningTop).magnitude / 0.25f)); + int num = (int)Math.Ceiling((Vector2.zero - LightningBoltMeshMaker.lightningTop).magnitude / 0.25); Vector2 b = LightningBoltMeshMaker.lightningTop / (float)num; LightningBoltMeshMaker.verts2D = new List(); Vector2 vector = Vector2.zero; - for (int i = 0; i < num; i++) + for (int num2 = 0; num2 < num; num2++) { LightningBoltMeshMaker.verts2D.Add(vector); vector += b; @@ -51,11 +51,11 @@ private static void MakeVerticesBase() private static void PeturbVerticesRandomly() { Perlin perlin = new Perlin(0.0070000002160668373, 2.0, 0.5, 6, Rand.Range(0, 2147483647), QualityMode.High); - List list = LightningBoltMeshMaker.verts2D.ListFullCopy(); + List list = LightningBoltMeshMaker.verts2D.ListFullCopy(); LightningBoltMeshMaker.verts2D.Clear(); for (int i = 0; i < list.Count; i++) { - float d = 12f * (float)perlin.GetValue((double)i, 0.0, 0.0); + float d = (float)(12.0 * (float)perlin.GetValue((double)i, 0.0, 0.0)); Vector2 item = list[i] + d * Vector2.right; LightningBoltMeshMaker.verts2D.Add(item); } @@ -63,7 +63,7 @@ private static void PeturbVerticesRandomly() private static void DoubleVertices() { - List list = LightningBoltMeshMaker.verts2D.ListFullCopy(); + List list = LightningBoltMeshMaker.verts2D.ListFullCopy(); Vector3 vector = default(Vector3); Vector2 a = default(Vector2); LightningBoltMeshMaker.verts2D.Clear(); @@ -87,34 +87,37 @@ private static Mesh MeshFromVerts() Vector3[] array = new Vector3[LightningBoltMeshMaker.verts2D.Count]; for (int i = 0; i < array.Length; i++) { - array[i] = new Vector3(LightningBoltMeshMaker.verts2D[i].x, 0f, LightningBoltMeshMaker.verts2D[i].y); + ref Vector3 val = ref array[i]; + Vector2 vector = LightningBoltMeshMaker.verts2D[i]; + float x = vector.x; + Vector2 vector2 = LightningBoltMeshMaker.verts2D[i]; + val = new Vector3(x, 0f, vector2.y); } float num = 0f; Vector2[] array2 = new Vector2[LightningBoltMeshMaker.verts2D.Count]; - for (int j = 0; j < LightningBoltMeshMaker.verts2D.Count; j += 2) + for (int num2 = 0; num2 < LightningBoltMeshMaker.verts2D.Count; num2 += 2) { - array2[j] = new Vector2(0f, num); - array2[j + 1] = new Vector2(1f, num); - num += 0.04f; + array2[num2] = new Vector2(0f, num); + array2[num2 + 1] = new Vector2(1f, num); + num = (float)(num + 0.039999999105930328); } int[] array3 = new int[LightningBoltMeshMaker.verts2D.Count * 3]; - for (int k = 0; k < LightningBoltMeshMaker.verts2D.Count - 2; k += 2) + for (int num3 = 0; num3 < LightningBoltMeshMaker.verts2D.Count - 2; num3 += 2) { - int num2 = k * 3; - array3[num2] = k; - array3[num2 + 1] = k + 1; - array3[num2 + 2] = k + 2; - array3[num2 + 3] = k + 2; - array3[num2 + 4] = k + 1; - array3[num2 + 5] = k + 3; + int num4 = num3 * 3; + array3[num4] = num3; + array3[num4 + 1] = num3 + 1; + array3[num4 + 2] = num3 + 2; + array3[num4 + 3] = num3 + 2; + array3[num4 + 4] = num3 + 1; + array3[num4 + 5] = num3 + 3; } - return new Mesh - { - vertices = array, - uv = array2, - triangles = array3, - name = "MeshFromVerts()" - }; + Mesh mesh = new Mesh(); + mesh.vertices = array; + mesh.uv = array2; + mesh.triangles = array3; + mesh.name = "MeshFromVerts()"; + return mesh; } } } diff --git a/Assembly-CSharp/RimWorld/LightningBoltMeshPool.cs b/Assembly-CSharp/RimWorld/LightningBoltMeshPool.cs index 2cfd27ca9..46ff48da6 100644 --- a/Assembly-CSharp/RimWorld/LightningBoltMeshPool.cs +++ b/Assembly-CSharp/RimWorld/LightningBoltMeshPool.cs @@ -1,4 +1,3 @@ -using System; using System.Collections.Generic; using UnityEngine; using Verse; @@ -21,7 +20,7 @@ public static Mesh RandomBoltMesh LightningBoltMeshPool.boltMeshes.Add(mesh); return mesh; } - return LightningBoltMeshPool.boltMeshes.RandomElement(); + return LightningBoltMeshPool.boltMeshes.RandomElement(); } } } diff --git a/Assembly-CSharp/RimWorld/LiquidFuel.cs b/Assembly-CSharp/RimWorld/LiquidFuel.cs index c7878cce5..593fc92dd 100644 --- a/Assembly-CSharp/RimWorld/LiquidFuel.cs +++ b/Assembly-CSharp/RimWorld/LiquidFuel.cs @@ -1,4 +1,3 @@ -using System; using Verse; namespace RimWorld diff --git a/Assembly-CSharp/RimWorld/ListerBuildingsRepairable.cs b/Assembly-CSharp/RimWorld/ListerBuildingsRepairable.cs index f818bf5ff..1fb93a30b 100644 --- a/Assembly-CSharp/RimWorld/ListerBuildingsRepairable.cs +++ b/Assembly-CSharp/RimWorld/ListerBuildingsRepairable.cs @@ -23,67 +23,62 @@ public bool Contains(Faction fac, Building b) public void Notify_BuildingSpawned(Building b) { - if (b.Faction == null) + if (b.Faction != null) { - return; + this.UpdateBuilding(b); } - this.UpdateBuilding(b); } public void Notify_BuildingDeSpawned(Building b) { - if (b.Faction == null) + if (b.Faction != null) { - return; + this.ListFor(b.Faction).Remove(b); + this.HashSetFor(b.Faction).Remove(b); } - this.ListFor(b.Faction).Remove(b); - this.HashSetFor(b.Faction).Remove(b); } public void Notify_BuildingTookDamage(Building b) { - if (b.Faction == null) + if (b.Faction != null) { - return; + this.UpdateBuilding(b); } - this.UpdateBuilding(b); } public void Notify_BuildingRepaired(Building b) { - if (b.Faction == null) + if (b.Faction != null) { - return; + this.UpdateBuilding(b); } - this.UpdateBuilding(b); } private void UpdateBuilding(Building b) { - if (b.Faction == null || !b.def.building.repairable) + if (b.Faction != null && b.def.building.repairable) { - return; - } - List list = this.ListFor(b.Faction); - HashSet hashSet = this.HashSetFor(b.Faction); - if (b.HitPoints < b.MaxHitPoints) - { - if (!list.Contains(b)) + List list = this.ListFor(b.Faction); + HashSet hashSet = this.HashSetFor(b.Faction); + if (b.HitPoints < b.MaxHitPoints) { - list.Add(b); + if (!list.Contains(b)) + { + list.Add(b); + } + hashSet.Add(b); + } + else + { + list.Remove(b); + hashSet.Remove(b); } - hashSet.Add(b); - } - else - { - list.Remove(b); - hashSet.Remove(b); } } private List ListFor(Faction fac) { - List list; + List list = default(List); if (!this.repairables.TryGetValue(fac, out list)) { list = new List(); @@ -94,7 +89,7 @@ private List ListFor(Faction fac) private HashSet HashSetFor(Faction fac) { - HashSet hashSet; + HashSet hashSet = default(HashSet); if (!this.repairablesSet.TryGetValue(fac, out hashSet)) { hashSet = new HashSet(); @@ -106,22 +101,24 @@ private HashSet HashSetFor(Faction fac) internal string DebugString() { StringBuilder stringBuilder = new StringBuilder(); - foreach (Faction current in Find.FactionManager.AllFactions) + foreach (Faction allFaction in Find.FactionManager.AllFactions) { - List list = this.ListFor(current); - if (!list.NullOrEmpty()) + List list = this.ListFor(allFaction); + if (!list.NullOrEmpty()) { - stringBuilder.AppendLine(string.Concat(new object[] + stringBuilder.AppendLine("=======" + allFaction.Name + " (" + allFaction.def + ")"); + List.Enumerator enumerator2 = list.GetEnumerator(); + try { - "=======", - current.Name, - " (", - current.def, - ")" - })); - foreach (Thing current2 in list) + while (enumerator2.MoveNext()) + { + Thing current2 = enumerator2.Current; + stringBuilder.AppendLine(current2.ThingID); + } + } + finally { - stringBuilder.AppendLine(current2.ThingID); + ((IDisposable)(object)enumerator2).Dispose(); } } } diff --git a/Assembly-CSharp/RimWorld/ListerFilthInHomeArea.cs b/Assembly-CSharp/RimWorld/ListerFilthInHomeArea.cs index fb2f19895..420df6539 100644 --- a/Assembly-CSharp/RimWorld/ListerFilthInHomeArea.cs +++ b/Assembly-CSharp/RimWorld/ListerFilthInHomeArea.cs @@ -27,15 +27,15 @@ public ListerFilthInHomeArea(Map map) public void RebuildAll() { this.filthInHomeArea.Clear(); - foreach (IntVec3 current in this.map.AllCells) + foreach (IntVec3 allCell in this.map.AllCells) { - this.Notify_HomeAreaChanged(current); + this.Notify_HomeAreaChanged(allCell); } } public void Notify_FilthSpawned(Filth f) { - if (this.map.areaManager.Home[f.Position]) + if (((Area)this.map.areaManager.Home)[f.Position]) { this.filthInHomeArea.Add(f); } @@ -43,19 +43,26 @@ public void Notify_FilthSpawned(Filth f) public void Notify_FilthDespawned(Filth f) { - for (int i = 0; i < this.filthInHomeArea.Count; i++) + int num = 0; + while (true) { - if (this.filthInHomeArea[i] == f) + if (num < this.filthInHomeArea.Count) { - this.filthInHomeArea.RemoveAt(i); - return; + if (this.filthInHomeArea[num] != f) + { + num++; + continue; + } + break; } + return; } + this.filthInHomeArea.RemoveAt(num); } public void Notify_HomeAreaChanged(IntVec3 c) { - if (this.map.areaManager.Home[c]) + if (((Area)this.map.areaManager.Home)[c]) { List thingList = c.GetThingList(this.map); for (int i = 0; i < thingList.Count; i++) @@ -69,11 +76,11 @@ public void Notify_HomeAreaChanged(IntVec3 c) } else { - for (int j = this.filthInHomeArea.Count - 1; j >= 0; j--) + for (int num = this.filthInHomeArea.Count - 1; num >= 0; num--) { - if (this.filthInHomeArea[j].Position == c) + if (this.filthInHomeArea[num].Position == c) { - this.filthInHomeArea.RemoveAt(j); + this.filthInHomeArea.RemoveAt(num); } } } @@ -83,9 +90,18 @@ internal string DebugString() { StringBuilder stringBuilder = new StringBuilder(); stringBuilder.AppendLine("======= Filth in home area"); - foreach (Thing current in this.filthInHomeArea) + List.Enumerator enumerator = this.filthInHomeArea.GetEnumerator(); + try + { + while (enumerator.MoveNext()) + { + Thing current = enumerator.Current; + stringBuilder.AppendLine(current.ThingID + " " + current.Position); + } + } + finally { - stringBuilder.AppendLine(current.ThingID + " " + current.Position); + ((IDisposable)(object)enumerator).Dispose(); } return stringBuilder.ToString(); } diff --git a/Assembly-CSharp/RimWorld/ListerHaulables.cs b/Assembly-CSharp/RimWorld/ListerHaulables.cs index e769e1bfd..2094294b2 100644 --- a/Assembly-CSharp/RimWorld/ListerHaulables.cs +++ b/Assembly-CSharp/RimWorld/ListerHaulables.cs @@ -79,35 +79,37 @@ public void ListerHaulablesTick() ListerHaulables.groupCycleIndex = 0; } List allGroupsListForReading = this.map.slotGroupManager.AllGroupsListForReading; - if (allGroupsListForReading.Count == 0) + if (allGroupsListForReading.Count != 0) { - return; - } - int num = ListerHaulables.groupCycleIndex % allGroupsListForReading.Count; - SlotGroup slotGroup = allGroupsListForReading[ListerHaulables.groupCycleIndex % allGroupsListForReading.Count]; - while (this.cellCycleIndices.Count <= num) - { - this.cellCycleIndices.Add(0); - } - if (this.cellCycleIndices[num] >= 2147473647) - { - this.cellCycleIndices[num] = 0; - } - for (int i = 0; i < 4; i++) - { - List list; - List expr_B0 = list = this.cellCycleIndices; - int num2; - int expr_B4 = num2 = num; - num2 = list[num2]; - expr_B0[expr_B4] = num2 + 1; - IntVec3 c = slotGroup.CellsList[this.cellCycleIndices[num] % slotGroup.CellsList.Count]; - List thingList = c.GetThingList(this.map); - for (int j = 0; j < thingList.Count; j++) + int num = ListerHaulables.groupCycleIndex % allGroupsListForReading.Count; + SlotGroup slotGroup = allGroupsListForReading[ListerHaulables.groupCycleIndex % allGroupsListForReading.Count]; + while (this.cellCycleIndices.Count <= num) + { + this.cellCycleIndices.Add(0); + } + if (this.cellCycleIndices[num] >= 2147473647) { - if (thingList[j].def.EverHaulable) + this.cellCycleIndices[num] = 0; + } + for (int i = 0; i < 4; i++) + { + List list; + List obj = list = this.cellCycleIndices; + int index; + int index2 = index = num; + index = list[index]; + obj[index2] = index + 1; + IntVec3 c = slotGroup.CellsList[this.cellCycleIndices[num] % slotGroup.CellsList.Count]; + List thingList = c.GetThingList(this.map); + int num2 = 0; + while (num2 < thingList.Count) { - this.Check(thingList[j]); + if (!thingList[num2].def.EverHaulable) + { + num2++; + continue; + } + this.Check(thingList[num2]); break; } } @@ -155,7 +157,11 @@ private bool ShouldBeHaulable(Thing t) return false; } } - return !t.IsInValidBestStorage(); + if (t.IsInValidBestStorage()) + { + return false; + } + return true; } private void CheckAdd(Thing t) @@ -181,15 +187,22 @@ internal string DebugString() StringBuilder stringBuilder = new StringBuilder(); stringBuilder.AppendLine("======= All haulables (Count " + this.haulables.Count + ")"); int num = 0; - foreach (Thing current in this.haulables) + List.Enumerator enumerator = this.haulables.GetEnumerator(); + try { - stringBuilder.AppendLine(current.ThingID); - num++; - if (num > 200) + while (enumerator.MoveNext()) { - break; + Thing current = enumerator.Current; + stringBuilder.AppendLine(current.ThingID); + num++; + if (num > 200) + break; } } + finally + { + ((IDisposable)(object)enumerator).Dispose(); + } this.debugOutput = stringBuilder.ToString(); } return this.debugOutput; diff --git a/Assembly-CSharp/RimWorld/Listing_ResourceReadout.cs b/Assembly-CSharp/RimWorld/Listing_ResourceReadout.cs index a36b36854..b3c895125 100644 --- a/Assembly-CSharp/RimWorld/Listing_ResourceReadout.cs +++ b/Assembly-CSharp/RimWorld/Listing_ResourceReadout.cs @@ -1,4 +1,5 @@ using System; +using System.Collections.Generic; using UnityEngine; using Verse; @@ -27,83 +28,94 @@ public Listing_ResourceReadout(Map map) public void DoCategory(TreeNode_ThingCategory node, int nestLevel, int openMask) { int countIn = this.map.resourceCounter.GetCountIn(node.catDef); - if (countIn == 0) + if (countIn != 0) { - return; - } - base.OpenCloseWidget(node, nestLevel, openMask); - Rect rect = new Rect(0f, this.curY, this.LabelWidth, this.lineHeight); - rect.xMin = base.XAtIndentLevel(nestLevel) + 18f; - Rect position = rect; - position.width = 80f; - position.yMax -= 3f; - position.yMin += 3f; - GUI.DrawTexture(position, Listing_ResourceReadout.SolidCategoryBG); - if (Mouse.IsOver(rect)) - { - GUI.DrawTexture(rect, TexUI.HighlightTex); - } - TooltipHandler.TipRegion(rect, new TipSignal(node.catDef.LabelCap, node.catDef.GetHashCode())); - Rect position2 = new Rect(rect); - float num = 28f; - position2.height = num; - position2.width = num; - position2.y = rect.y + rect.height / 2f - position2.height / 2f; - GUI.DrawTexture(position2, node.catDef.icon); - Widgets.Label(new Rect(rect) - { - xMin = position2.xMax + 6f - }, countIn.ToStringCached()); - base.EndLine(); - if (node.IsOpen(openMask)) - { - this.DoCategoryChildren(node, nestLevel + 1, openMask); + base.OpenCloseWidget(node, nestLevel, openMask); + Rect rect = new Rect(0f, base.curY, this.LabelWidth, base.lineHeight) + { + xMin = (float)(base.XAtIndentLevel(nestLevel) + 18.0) + }; + Rect position = rect; + position.width = 80f; + position.yMax -= 3f; + position.yMin += 3f; + GUI.DrawTexture(position, Listing_ResourceReadout.SolidCategoryBG); + if (Mouse.IsOver(rect)) + { + GUI.DrawTexture(rect, TexUI.HighlightTex); + } + TooltipHandler.TipRegion(rect, new TipSignal(node.catDef.LabelCap, node.catDef.GetHashCode())); + Rect position2 = new Rect(rect); + float num = 28f; + position2.height = num; + position2.width = num; + position2.y = (float)(rect.y + rect.height / 2.0 - position2.height / 2.0); + GUI.DrawTexture(position2, node.catDef.icon); + Widgets.Label(new Rect(rect) + { + xMin = (float)(position2.xMax + 6.0) + }, countIn.ToStringCached()); + base.EndLine(); + if (node.IsOpen(openMask)) + { + this.DoCategoryChildren(node, nestLevel + 1, openMask); + } } } public void DoCategoryChildren(TreeNode_ThingCategory node, int indentLevel, int openMask) { - foreach (TreeNode_ThingCategory current in node.ChildCategoryNodes) + foreach (TreeNode_ThingCategory childCategoryNode in node.ChildCategoryNodes) { - if (!current.catDef.resourceReadoutRoot) + if (!childCategoryNode.catDef.resourceReadoutRoot) { - this.DoCategory(current, indentLevel, openMask); + this.DoCategory(childCategoryNode, indentLevel, openMask); } } - foreach (ThingDef current2 in node.catDef.childThingDefs) + List.Enumerator enumerator2 = node.catDef.childThingDefs.GetEnumerator(); + try { - if (!current2.menuHidden) + while (enumerator2.MoveNext()) { - this.DoThingDef(current2, indentLevel + 1); + ThingDef current2 = enumerator2.Current; + if (!current2.menuHidden) + { + this.DoThingDef(current2, indentLevel + 1); + } } } + finally + { + ((IDisposable)(object)enumerator2).Dispose(); + } } private void DoThingDef(ThingDef thingDef, int nestLevel) { int count = this.map.resourceCounter.GetCount(thingDef); - if (count == 0) - { - return; - } - Rect rect = new Rect(0f, this.curY, this.LabelWidth, this.lineHeight); - rect.xMin = base.XAtIndentLevel(nestLevel) + 18f; - if (Mouse.IsOver(rect)) + if (count != 0) { - GUI.DrawTexture(rect, TexUI.HighlightTex); + Rect rect = new Rect(0f, base.curY, this.LabelWidth, base.lineHeight) + { + xMin = (float)(base.XAtIndentLevel(nestLevel) + 18.0) + }; + if (Mouse.IsOver(rect)) + { + GUI.DrawTexture(rect, TexUI.HighlightTex); + } + TooltipHandler.TipRegion(rect, new TipSignal((Func)(() => thingDef.LabelCap + ": " + thingDef.description), thingDef.shortHash)); + Rect rect2 = new Rect(rect); + float num = 28f; + rect2.height = num; + rect2.width = num; + rect2.y = (float)(rect.y + rect.height / 2.0 - rect2.height / 2.0); + Widgets.ThingIcon(rect2, thingDef); + Widgets.Label(new Rect(rect) + { + xMin = (float)(rect2.xMax + 6.0) + }, count.ToStringCached()); + base.EndLine(); } - TooltipHandler.TipRegion(rect, new TipSignal(() => thingDef.LabelCap + ": " + thingDef.description, (int)thingDef.shortHash)); - Rect rect2 = new Rect(rect); - float num = 28f; - rect2.height = num; - rect2.width = num; - rect2.y = rect.y + rect.height / 2f - rect2.height / 2f; - Widgets.ThingIcon(rect2, thingDef); - Widgets.Label(new Rect(rect) - { - xMin = rect2.xMax + 6f - }, count.ToStringCached()); - base.EndLine(); } } } diff --git a/Assembly-CSharp/RimWorld/LoadTransportersJobUtility.cs b/Assembly-CSharp/RimWorld/LoadTransportersJobUtility.cs index 78b377a95..acaddf949 100644 --- a/Assembly-CSharp/RimWorld/LoadTransportersJobUtility.cs +++ b/Assembly-CSharp/RimWorld/LoadTransportersJobUtility.cs @@ -13,13 +13,34 @@ public static class LoadTransportersJobUtility public static bool HasJobOnTransporter(Pawn pawn, CompTransporter transporter) { - return !transporter.parent.IsForbidden(pawn) && transporter.AnythingLeftToLoad && pawn.health.capacities.CapableOf(PawnCapacityDefOf.Manipulation) && pawn.CanReserveAndReach(transporter.parent, PathEndMode.Touch, pawn.NormalMaxDanger(), 1, -1, null, false) && LoadTransportersJobUtility.FindThingToLoad(pawn, transporter) != null; + if (transporter.parent.IsForbidden(pawn)) + { + return false; + } + if (!transporter.AnythingLeftToLoad) + { + return false; + } + if (!pawn.health.capacities.CapableOf(PawnCapacityDefOf.Manipulation)) + { + return false; + } + if (!pawn.CanReserveAndReach((Thing)transporter.parent, PathEndMode.Touch, pawn.NormalMaxDanger(), 1, -1, null, false)) + { + return false; + } + Thing thing = LoadTransportersJobUtility.FindThingToLoad(pawn, transporter); + if (thing == null) + { + return false; + } + return true; } public static Job JobOnTransporter(Pawn p, CompTransporter transporter) { Thing thing = LoadTransportersJobUtility.FindThingToLoad(p, transporter); - Job job = new Job(JobDefOf.HaulToContainer, thing, transporter.parent); + Job job = new Job(JobDefOf.HaulToContainer, thing, (Thing)transporter.parent); int countToTransfer = TransferableUtility.TransferableMatchingDesperate(thing, transporter.leftToLoad).CountToTransfer; job.count = Mathf.Min(countToTransfer, thing.stackCount); job.ignoreForbidden = true; @@ -44,22 +65,31 @@ private static Thing FindThingToLoad(Pawn p, CompTransporter transporter) } } } - if (!LoadTransportersJobUtility.neededThings.Any()) + if (!LoadTransportersJobUtility.neededThings.Any()) { return null; } - Predicate validator = (Thing x) => LoadTransportersJobUtility.neededThings.Contains(x) && p.CanReserve(x, 1, -1, null, false); + Predicate validator = (Predicate)((Thing x) => LoadTransportersJobUtility.neededThings.Contains(x) && p.CanReserve(x, 1, -1, null, false)); Thing thing = GenClosest.ClosestThingReachable(p.Position, p.Map, ThingRequest.ForGroup(ThingRequestGroup.HaulableEver), PathEndMode.Touch, TraverseParms.For(p, Danger.Deadly, TraverseMode.ByPawn, false), 9999f, validator, null, 0, -1, false, RegionType.Set_Passable, false); if (thing == null) { - foreach (Thing current in LoadTransportersJobUtility.neededThings) + HashSet.Enumerator enumerator = LoadTransportersJobUtility.neededThings.GetEnumerator(); + try { - Pawn pawn = current as Pawn; - if (pawn != null && (!pawn.IsColonist || pawn.Downed) && p.CanReserveAndReach(pawn, PathEndMode.Touch, Danger.Deadly, 1, -1, null, false)) + while (enumerator.MoveNext()) { - return pawn; + Thing current = enumerator.Current; + Pawn pawn = current as Pawn; + if (pawn != null && (!pawn.IsColonist || pawn.Downed) && p.CanReserveAndReach((Thing)pawn, PathEndMode.Touch, Danger.Deadly, 1, -1, null, false)) + { + return pawn; + } } } + finally + { + ((IDisposable)(object)enumerator).Dispose(); + } } LoadTransportersJobUtility.neededThings.Clear(); return thing; diff --git a/Assembly-CSharp/RimWorld/LordJob_AssaultColony.cs b/Assembly-CSharp/RimWorld/LordJob_AssaultColony.cs index 690d0e6ca..ff621c699 100644 --- a/Assembly-CSharp/RimWorld/LordJob_AssaultColony.cs +++ b/Assembly-CSharp/RimWorld/LordJob_AssaultColony.cs @@ -1,4 +1,3 @@ -using System; using Verse; using Verse.AI; using Verse.AI.Group; @@ -86,25 +85,16 @@ public override StateGraph CreateGraph() transition4.AddSource(lordToil); } transition4.AddTrigger(new Trigger_TicksPassed((!this.sappers) ? LordJob_AssaultColony.AssaultTimeBeforeGiveUp.RandomInRange : LordJob_AssaultColony.SapTimeBeforeGiveUp.RandomInRange)); - transition4.AddPreAction(new TransitionAction_Message("MessageRaidersGivenUpLeaving".Translate(new object[] - { - this.assaulterFaction.def.pawnsPlural.CapitalizeFirst(), - this.assaulterFaction.Name - }))); + transition4.AddPreAction(new TransitionAction_Message("MessageRaidersGivenUpLeaving".Translate(this.assaulterFaction.def.pawnsPlural.CapitalizeFirst(), this.assaulterFaction.Name))); stateGraph.AddTransition(transition4); Transition transition5 = new Transition(lordToil3, lordToil_ExitMap); if (lordToil != null) { transition5.AddSource(lordToil); } - FloatRange floatRange = new FloatRange(0.25f, 0.35f); - float randomInRange = floatRange.RandomInRange; + float randomInRange = new FloatRange(0.25f, 0.35f).RandomInRange; transition5.AddTrigger(new Trigger_FractionColonyDamageTaken(randomInRange, 900f)); - transition5.AddPreAction(new TransitionAction_Message("MessageRaidersSatisfiedLeaving".Translate(new object[] - { - this.assaulterFaction.def.pawnsPlural.CapitalizeFirst(), - this.assaulterFaction.Name - }))); + transition5.AddPreAction(new TransitionAction_Message("MessageRaidersSatisfiedLeaving".Translate(this.assaulterFaction.def.pawnsPlural.CapitalizeFirst(), this.assaulterFaction.Name))); stateGraph.AddTransition(transition5); } if (this.canKidnap) @@ -115,11 +105,7 @@ public override StateGraph CreateGraph() { transition6.AddSource(lordToil); } - transition6.AddPreAction(new TransitionAction_Message("MessageRaidersKidnapping".Translate(new object[] - { - this.assaulterFaction.def.pawnsPlural.CapitalizeFirst(), - this.assaulterFaction.Name - }))); + transition6.AddPreAction(new TransitionAction_Message("MessageRaidersKidnapping".Translate(this.assaulterFaction.def.pawnsPlural.CapitalizeFirst(), this.assaulterFaction.Name))); transition6.AddTrigger(new Trigger_KidnapVictimPresent()); stateGraph.AddTransition(transition6); } @@ -131,11 +117,7 @@ public override StateGraph CreateGraph() { transition7.AddSource(lordToil); } - transition7.AddPreAction(new TransitionAction_Message("MessageRaidersStealing".Translate(new object[] - { - this.assaulterFaction.def.pawnsPlural.CapitalizeFirst(), - this.assaulterFaction.Name - }))); + transition7.AddPreAction(new TransitionAction_Message("MessageRaidersStealing".Translate(this.assaulterFaction.def.pawnsPlural.CapitalizeFirst(), this.assaulterFaction.Name))); transition7.AddTrigger(new Trigger_HighValueThingsAround()); stateGraph.AddTransition(transition7); } @@ -146,11 +128,7 @@ public override StateGraph CreateGraph() transition8.AddSource(lordToil); } transition8.AddTrigger(new Trigger_BecameColonyAlly()); - transition8.AddPreAction(new TransitionAction_Message("MessageRaidersLeaving".Translate(new object[] - { - this.assaulterFaction.def.pawnsPlural.CapitalizeFirst(), - this.assaulterFaction.Name - }))); + transition8.AddPreAction(new TransitionAction_Message("MessageRaidersLeaving".Translate(this.assaulterFaction.def.pawnsPlural.CapitalizeFirst(), this.assaulterFaction.Name))); stateGraph.AddTransition(transition8); return stateGraph; } diff --git a/Assembly-CSharp/RimWorld/LordJob_AssistColony.cs b/Assembly-CSharp/RimWorld/LordJob_AssistColony.cs index ed970b603..aae258673 100644 --- a/Assembly-CSharp/RimWorld/LordJob_AssistColony.cs +++ b/Assembly-CSharp/RimWorld/LordJob_AssistColony.cs @@ -1,4 +1,3 @@ -using System; using Verse; using Verse.AI; using Verse.AI.Group; @@ -33,22 +32,14 @@ public override StateGraph CreateGraph() stateGraph.AddToil(lordToil_ExitMap); Transition transition = new Transition(startingToil, startingToil2); transition.AddSource(lordToil_HuntEnemies); - transition.AddPreAction(new TransitionAction_Message("MessageVisitorsDangerousTemperature".Translate(new object[] - { - this.faction.def.pawnsPlural.CapitalizeFirst(), - this.faction.Name - }))); + transition.AddPreAction(new TransitionAction_Message("MessageVisitorsDangerousTemperature".Translate(this.faction.def.pawnsPlural.CapitalizeFirst(), this.faction.Name))); transition.AddPreAction(new TransitionAction_EnsureHaveExitDestination()); transition.AddTrigger(new Trigger_PawnExperiencingDangerousTemperatures()); stateGraph.AddTransition(transition); Transition transition2 = new Transition(startingToil, lordToil_ExitMap); transition2.AddSource(lordToil_HuntEnemies); transition2.AddSources(stateGraph2.lordToils); - transition2.AddPreAction(new TransitionAction_Message("MessageVisitorsTrappedLeaving".Translate(new object[] - { - this.faction.def.pawnsPlural.CapitalizeFirst(), - this.faction.Name - }))); + transition2.AddPreAction(new TransitionAction_Message("MessageVisitorsTrappedLeaving".Translate(this.faction.def.pawnsPlural.CapitalizeFirst(), this.faction.Name))); transition2.AddTrigger(new Trigger_PawnCannotReachMapEdge()); stateGraph.AddTransition(transition2); Transition transition3 = new Transition(lordToil_ExitMap, startingToil2); @@ -59,11 +50,7 @@ public override StateGraph CreateGraph() transition4.AddTrigger(new Trigger_Memo("TravelArrived")); stateGraph.AddTransition(transition4); Transition transition5 = new Transition(lordToil_HuntEnemies, startingToil2); - transition5.AddPreAction(new TransitionAction_Message("MessageFriendlyFightersLeaving".Translate(new object[] - { - this.faction.def.pawnsPlural.CapitalizeFirst(), - this.faction.Name - }))); + transition5.AddPreAction(new TransitionAction_Message("MessageFriendlyFightersLeaving".Translate(this.faction.def.pawnsPlural.CapitalizeFirst(), this.faction.Name))); transition5.AddTrigger(new Trigger_TicksPassed(25000)); stateGraph.AddTransition(transition5); return stateGraph; diff --git a/Assembly-CSharp/RimWorld/LordJob_DefendAndExpandHive.cs b/Assembly-CSharp/RimWorld/LordJob_DefendAndExpandHive.cs index d685a677e..0a63727bd 100644 --- a/Assembly-CSharp/RimWorld/LordJob_DefendAndExpandHive.cs +++ b/Assembly-CSharp/RimWorld/LordJob_DefendAndExpandHive.cs @@ -1,4 +1,3 @@ -using System; using Verse; using Verse.AI.Group; @@ -29,13 +28,7 @@ public override StateGraph CreateGraph() transition2.AddTrigger(new Trigger_Memo(Hive.MemoDestroyed)); stateGraph.AddTransition(transition2); Transition transition3 = new Transition(lordToil_AssaultColony, lordToil_DefendAndExpandHive); - transition3.AddTrigger(new Trigger_TicksPassedWithoutHarmOrMemos(1200, new string[] - { - Hive.MemoAttackedByEnemy, - Hive.MemoBurnedBadly, - Hive.MemoDestroyed, - HediffGiver_Heat.MemoPawnBurnedByAir - })); + transition3.AddTrigger(new Trigger_TicksPassedWithoutHarmOrMemos(1200, Hive.MemoAttackedByEnemy, Hive.MemoBurnedBadly, Hive.MemoDestroyed, HediffGiver_Heat.MemoPawnBurnedByAir)); transition3.AddPostAction(new TransitionAction_EndAttackBuildingJobs()); stateGraph.AddTransition(transition3); return stateGraph; diff --git a/Assembly-CSharp/RimWorld/LordJob_DefendAttackedTraderCaravan.cs b/Assembly-CSharp/RimWorld/LordJob_DefendAttackedTraderCaravan.cs index 0fa082b25..e97a8e1b3 100644 --- a/Assembly-CSharp/RimWorld/LordJob_DefendAttackedTraderCaravan.cs +++ b/Assembly-CSharp/RimWorld/LordJob_DefendAttackedTraderCaravan.cs @@ -1,4 +1,3 @@ -using System; using Verse; using Verse.AI; using Verse.AI.Group; diff --git a/Assembly-CSharp/RimWorld/LordJob_DefendBase.cs b/Assembly-CSharp/RimWorld/LordJob_DefendBase.cs index 0793de766..3b1b2cdd4 100644 --- a/Assembly-CSharp/RimWorld/LordJob_DefendBase.cs +++ b/Assembly-CSharp/RimWorld/LordJob_DefendBase.cs @@ -1,4 +1,3 @@ -using System; using Verse; using Verse.AI.Group; @@ -45,12 +44,7 @@ public override StateGraph CreateGraph() transition3.AddTrigger(new Trigger_UrgentlyHungry()); transition3.AddTrigger(new Trigger_ChanceOnPlayerHarmNPCBuilding(0.4f)); transition3.AddPostAction(new TransitionAction_WakeAll()); - string message = "MessageDefendersAttacking".Translate(new object[] - { - this.faction.def.pawnsPlural, - this.faction.Name, - Faction.OfPlayer.def.pawnsPlural - }).CapitalizeFirst(); + string message = "MessageDefendersAttacking".Translate(this.faction.def.pawnsPlural, this.faction.Name, Faction.OfPlayer.def.pawnsPlural).CapitalizeFirst(); transition3.AddPreAction(new TransitionAction_Message(message, MessageSound.SeriousAlert)); stateGraph.AddTransition(transition3); return stateGraph; diff --git a/Assembly-CSharp/RimWorld/LordJob_FormAndSendCaravan.cs b/Assembly-CSharp/RimWorld/LordJob_FormAndSendCaravan.cs index 9d086669d..a34736d2f 100644 --- a/Assembly-CSharp/RimWorld/LordJob_FormAndSendCaravan.cs +++ b/Assembly-CSharp/RimWorld/LordJob_FormAndSendCaravan.cs @@ -26,7 +26,7 @@ public bool GatheringItemsNow { get { - return this.lord.CurLordToil == this.gatherItems; + return base.lord.CurLordToil == this.gatherItems; } } @@ -93,11 +93,11 @@ public override StateGraph CreateGraph() transition.AddSource(lordToil_PrepareCaravan_Pause3); transition.AddSource(lordToil_PrepareCaravan_Pause4); transition.AddSource(lordToil_PrepareCaravan_Pause5); - transition.AddTrigger(new Trigger_Custom((TriggerSignal x) => x.type == TriggerSignalType.PawnLost && !this.caravanSent)); + transition.AddTrigger(new Trigger_Custom((Func)((TriggerSignal x) => x.type == TriggerSignalType.PawnLost && !this.caravanSent))); transition.AddPreAction(new TransitionAction_Message("MessageFailedToSendCaravanBecausePawnLost".Translate(), MessageSound.Negative)); - transition.AddPostAction(new TransitionAction_Custom(delegate + transition.AddPostAction(new TransitionAction_Custom((Action)delegate { - CaravanFormingUtility.Notify_FormAndSendCaravanLordFailed(this.lord); + CaravanFormingUtility.Notify_FormAndSendCaravanLordFailed(base.lord); })); stateGraph.AddTransition(transition); Transition transition2 = new Transition(lordToil_PrepareCaravan_GatherAnimals, this.gatherItems); @@ -174,7 +174,7 @@ public override void ExposeData() private void SendCaravan() { this.caravanSent = true; - CaravanFormingUtility.FormAndCreateCaravan(this.lord.ownedPawns, this.lord.faction, base.Map.Tile, this.startingTile); + CaravanFormingUtility.FormAndCreateCaravan(base.lord.ownedPawns, base.lord.faction, base.Map.Tile, this.startingTile); } public override void Notify_PawnAdded(Pawn p) diff --git a/Assembly-CSharp/RimWorld/LordJob_Joinable_MarriageCeremony.cs b/Assembly-CSharp/RimWorld/LordJob_Joinable_MarriageCeremony.cs index 1fe5a0648..2ea21387c 100644 --- a/Assembly-CSharp/RimWorld/LordJob_Joinable_MarriageCeremony.cs +++ b/Assembly-CSharp/RimWorld/LordJob_Joinable_MarriageCeremony.cs @@ -54,78 +54,94 @@ public override StateGraph CreateGraph() LordToil_End lordToil_End = new LordToil_End(); stateGraph.AddToil(lordToil_End); Transition transition = new Transition(lordToil_Party, lordToil_MarriageCeremony); - transition.AddTrigger(new Trigger_TickCondition(() => this.lord.ticksInToil >= 5000 && this.AreFiancesInPartyArea())); - transition.AddPreAction(new TransitionAction_Message("MessageMarriageCeremonyStarts".Translate(new object[] - { - this.firstPawn.LabelShort, - this.secondPawn.LabelShort - }), MessageSound.Benefit, this.firstPawn)); + transition.AddTrigger(new Trigger_TickCondition((Func)(() => base.lord.ticksInToil >= 5000 && this.AreFiancesInPartyArea()))); + transition.AddPreAction(new TransitionAction_Message("MessageMarriageCeremonyStarts".Translate(this.firstPawn.LabelShort, this.secondPawn.LabelShort), MessageSound.Benefit, (Thing)this.firstPawn)); stateGraph.AddTransition(transition); Transition transition2 = new Transition(lordToil_MarriageCeremony, lordToil_Party2); - transition2.AddTrigger(new Trigger_TickCondition(() => this.firstPawn.relations.DirectRelationExists(PawnRelationDefOf.Spouse, this.secondPawn))); - transition2.AddPreAction(new TransitionAction_Message("MessageNewlyMarried".Translate(new object[] - { - this.firstPawn.LabelShort, - this.secondPawn.LabelShort - }), MessageSound.Benefit, new TargetInfo(this.spot, base.Map, false))); - transition2.AddPreAction(new TransitionAction_Custom(delegate + transition2.AddTrigger(new Trigger_TickCondition((Func)(() => this.firstPawn.relations.DirectRelationExists(PawnRelationDefOf.Spouse, this.secondPawn)))); + transition2.AddPreAction(new TransitionAction_Message("MessageNewlyMarried".Translate(this.firstPawn.LabelShort, this.secondPawn.LabelShort), MessageSound.Benefit, new TargetInfo(this.spot, base.Map, false))); + transition2.AddPreAction(new TransitionAction_Custom((Action)delegate { this.AddAttendedWeddingThoughts(); })); stateGraph.AddTransition(transition2); Transition transition3 = new Transition(lordToil_Party2, lordToil_End); - transition3.AddTrigger(new Trigger_TickCondition(() => this.ShouldAfterPartyBeCalledOff())); + transition3.AddTrigger(new Trigger_TickCondition((Func)(() => this.ShouldAfterPartyBeCalledOff()))); transition3.AddTrigger(new Trigger_PawnLostViolently()); - transition3.AddPreAction(new TransitionAction_Message("MessageMarriageCeremonyCalledOff".Translate(new object[] - { - this.firstPawn.LabelShort, - this.secondPawn.LabelShort - }), MessageSound.Negative, new TargetInfo(this.spot, base.Map, false))); + transition3.AddPreAction(new TransitionAction_Message("MessageMarriageCeremonyCalledOff".Translate(this.firstPawn.LabelShort, this.secondPawn.LabelShort), MessageSound.Negative, new TargetInfo(this.spot, base.Map, false))); stateGraph.AddTransition(transition3); this.afterPartyTimeoutTrigger = new Trigger_TicksPassed(7500); Transition transition4 = new Transition(lordToil_Party2, lordToil_End); transition4.AddTrigger(this.afterPartyTimeoutTrigger); - transition4.AddPreAction(new TransitionAction_Message("MessageMarriageCeremonyAfterPartyFinished".Translate(new object[] - { - this.firstPawn.LabelShort, - this.secondPawn.LabelShort - }), MessageSound.Benefit, this.firstPawn)); + transition4.AddPreAction(new TransitionAction_Message("MessageMarriageCeremonyAfterPartyFinished".Translate(this.firstPawn.LabelShort, this.secondPawn.LabelShort), MessageSound.Benefit, (Thing)this.firstPawn)); stateGraph.AddTransition(transition4); Transition transition5 = new Transition(lordToil_MarriageCeremony, lordToil_End); transition5.AddSource(lordToil_Party); - transition5.AddTrigger(new Trigger_TickCondition(() => this.lord.ticksInToil >= 120000 && (this.firstPawn.Drafted || this.secondPawn.Drafted || !this.firstPawn.Position.InHorDistOf(this.spot, 4f) || !this.secondPawn.Position.InHorDistOf(this.spot, 4f)))); - transition5.AddPreAction(new TransitionAction_Message("MessageMarriageCeremonyCalledOff".Translate(new object[] - { - this.firstPawn.LabelShort, - this.secondPawn.LabelShort - }), MessageSound.Negative, new TargetInfo(this.spot, base.Map, false))); + transition5.AddTrigger(new Trigger_TickCondition((Func)(() => base.lord.ticksInToil >= 120000 && (this.firstPawn.Drafted || this.secondPawn.Drafted || !this.firstPawn.Position.InHorDistOf(this.spot, 4f) || !this.secondPawn.Position.InHorDistOf(this.spot, 4f))))); + transition5.AddPreAction(new TransitionAction_Message("MessageMarriageCeremonyCalledOff".Translate(this.firstPawn.LabelShort, this.secondPawn.LabelShort), MessageSound.Negative, new TargetInfo(this.spot, base.Map, false))); stateGraph.AddTransition(transition5); Transition transition6 = new Transition(lordToil_MarriageCeremony, lordToil_End); transition6.AddSource(lordToil_Party); - transition6.AddTrigger(new Trigger_TickCondition(() => this.ShouldCeremonyBeCalledOff())); + transition6.AddTrigger(new Trigger_TickCondition((Func)(() => this.ShouldCeremonyBeCalledOff()))); transition6.AddTrigger(new Trigger_PawnLostViolently()); - transition6.AddPreAction(new TransitionAction_Message("MessageMarriageCeremonyCalledOff".Translate(new object[] - { - this.firstPawn.LabelShort, - this.secondPawn.LabelShort - }), MessageSound.Negative, new TargetInfo(this.spot, base.Map, false))); + transition6.AddPreAction(new TransitionAction_Message("MessageMarriageCeremonyCalledOff".Translate(this.firstPawn.LabelShort, this.secondPawn.LabelShort), MessageSound.Negative, new TargetInfo(this.spot, base.Map, false))); stateGraph.AddTransition(transition6); return stateGraph; } private bool AreFiancesInPartyArea() { - return this.lord.ownedPawns.Contains(this.firstPawn) && this.lord.ownedPawns.Contains(this.secondPawn) && this.firstPawn.Map == base.Map && PartyUtility.InPartyArea(this.firstPawn.Position, this.spot, base.Map) && this.secondPawn.Map == base.Map && PartyUtility.InPartyArea(this.secondPawn.Position, this.spot, base.Map); + if (base.lord.ownedPawns.Contains(this.firstPawn) && base.lord.ownedPawns.Contains(this.secondPawn)) + { + if (this.firstPawn.Map == base.Map && PartyUtility.InPartyArea(this.firstPawn.Position, this.spot, base.Map)) + { + if (this.secondPawn.Map == base.Map && PartyUtility.InPartyArea(this.secondPawn.Position, this.spot, base.Map)) + { + return true; + } + return false; + } + return false; + } + return false; } private bool ShouldCeremonyBeCalledOff() { - return this.firstPawn.Destroyed || this.secondPawn.Destroyed || !this.firstPawn.relations.DirectRelationExists(PawnRelationDefOf.Fiance, this.secondPawn) || (this.spot.GetDangerFor(this.firstPawn, base.Map) != Danger.None || this.spot.GetDangerFor(this.secondPawn, base.Map) != Danger.None) || (!MarriageCeremonyUtility.AcceptableGameConditionsToContinueCeremony(base.Map) || !MarriageCeremonyUtility.FianceCanContinueCeremony(this.firstPawn) || !MarriageCeremonyUtility.FianceCanContinueCeremony(this.secondPawn)); + if (!this.firstPawn.Destroyed && !this.secondPawn.Destroyed) + { + if (!this.firstPawn.relations.DirectRelationExists(PawnRelationDefOf.Fiance, this.secondPawn)) + { + return true; + } + if (this.spot.GetDangerFor(this.firstPawn, base.Map) == Danger.None && this.spot.GetDangerFor(this.secondPawn, base.Map) == Danger.None) + { + if (MarriageCeremonyUtility.AcceptableGameConditionsToContinueCeremony(base.Map) && MarriageCeremonyUtility.FianceCanContinueCeremony(this.firstPawn) && MarriageCeremonyUtility.FianceCanContinueCeremony(this.secondPawn)) + { + return false; + } + return true; + } + return true; + } + return true; } private bool ShouldAfterPartyBeCalledOff() { - return this.firstPawn.Destroyed || this.secondPawn.Destroyed || (this.spot.GetDangerFor(this.firstPawn, base.Map) != Danger.None || this.spot.GetDangerFor(this.secondPawn, base.Map) != Danger.None) || !PartyUtility.AcceptableGameConditionsToContinueParty(base.Map); + if (!this.firstPawn.Destroyed && !this.secondPawn.Destroyed) + { + if (this.spot.GetDangerFor(this.firstPawn, base.Map) == Danger.None && this.spot.GetDangerFor(this.secondPawn, base.Map) == Danger.None) + { + if (!PartyUtility.AcceptableGameConditionsToContinueParty(base.Map)) + { + return true; + } + return false; + } + return true; + } + return true; } public override float VoluntaryJoinPriorityFor(Pawn p) @@ -138,31 +154,28 @@ public override float VoluntaryJoinPriorityFor(Pawn p) } return VoluntarilyJoinableLordJobJoinPriorities.MarriageCeremonyFiance; } - else + if (this.IsGuest(p)) { - if (!this.IsGuest(p)) - { - return 0f; - } if (!MarriageCeremonyUtility.ShouldGuestKeepAttendingCeremony(p)) { return 0f; } - if (!this.lord.ownedPawns.Contains(p)) + if (!base.lord.ownedPawns.Contains(p)) { if (this.IsCeremonyAboutToEnd()) { return 0f; } - LordToil_MarriageCeremony lordToil_MarriageCeremony = this.lord.CurLordToil as LordToil_MarriageCeremony; - IntVec3 intVec; - if (lordToil_MarriageCeremony != null && !SpectatorCellFinder.TryFindSpectatorCellFor(p, lordToil_MarriageCeremony.Data.spectateRect, base.Map, out intVec, lordToil_MarriageCeremony.Data.spectateRectAllowedSides, 1, null)) + LordToil_MarriageCeremony lordToil_MarriageCeremony = base.lord.CurLordToil as LordToil_MarriageCeremony; + IntVec3 intVec = default(IntVec3); + if (lordToil_MarriageCeremony != null && !SpectatorCellFinder.TryFindSpectatorCellFor(p, lordToil_MarriageCeremony.Data.spectateRect, base.Map, out intVec, lordToil_MarriageCeremony.Data.spectateRectAllowedSides, 1, (List)null)) { return 0f; } } return VoluntarilyJoinableLordJobJoinPriorities.MarriageCeremonyGuest; } + return 0f; } public override void ExposeData() @@ -179,7 +192,11 @@ public override string GetReport() private bool IsCeremonyAboutToEnd() { - return this.afterPartyTimeoutTrigger.TicksLeft < 1200; + if (this.afterPartyTimeoutTrigger.TicksLeft < 1200) + { + return true; + } + return false; } private bool IsFiance(Pawn p) @@ -189,20 +206,25 @@ private bool IsFiance(Pawn p) private bool IsGuest(Pawn p) { - return p.RaceProps.Humanlike && p != this.firstPawn && p != this.secondPawn && (p.Faction == this.firstPawn.Faction || p.Faction == this.secondPawn.Faction); + if (!p.RaceProps.Humanlike) + { + return false; + } + if (p != this.firstPawn && p != this.secondPawn) + { + return p.Faction == this.firstPawn.Faction || p.Faction == this.secondPawn.Faction; + } + return false; } private void AddAttendedWeddingThoughts() { - List ownedPawns = this.lord.ownedPawns; + List ownedPawns = base.lord.ownedPawns; for (int i = 0; i < ownedPawns.Count; i++) { - if (ownedPawns[i] != this.firstPawn && ownedPawns[i] != this.secondPawn) + if (ownedPawns[i] != this.firstPawn && ownedPawns[i] != this.secondPawn && (this.firstPawn.Position.InHorDistOf(ownedPawns[i].Position, 18f) || this.secondPawn.Position.InHorDistOf(ownedPawns[i].Position, 18f))) { - if (this.firstPawn.Position.InHorDistOf(ownedPawns[i].Position, 18f) || this.secondPawn.Position.InHorDistOf(ownedPawns[i].Position, 18f)) - { - ownedPawns[i].needs.mood.thoughts.memories.TryGainMemory(ThoughtDefOf.AttendedWedding, null); - } + ownedPawns[i].needs.mood.thoughts.memories.TryGainMemory(ThoughtDefOf.AttendedWedding, null); } } } diff --git a/Assembly-CSharp/RimWorld/LordJob_Joinable_Party.cs b/Assembly-CSharp/RimWorld/LordJob_Joinable_Party.cs index d394e57c8..a8dc78e1c 100644 --- a/Assembly-CSharp/RimWorld/LordJob_Joinable_Party.cs +++ b/Assembly-CSharp/RimWorld/LordJob_Joinable_Party.cs @@ -35,7 +35,7 @@ public override StateGraph CreateGraph() LordToil_End lordToil_End = new LordToil_End(); stateGraph.AddToil(lordToil_End); Transition transition = new Transition(lordToil_Party, lordToil_End); - transition.AddTrigger(new Trigger_TickCondition(() => this.ShouldBeCalledOff())); + transition.AddTrigger(new Trigger_TickCondition((Func)(() => this.ShouldBeCalledOff()))); transition.AddTrigger(new Trigger_PawnLostViolently()); transition.AddPreAction(new TransitionAction_Message("MessagePartyCalledOff".Translate(), MessageSound.Negative, new TargetInfo(this.spot, base.Map, false))); stateGraph.AddTransition(transition); @@ -49,24 +49,32 @@ public override StateGraph CreateGraph() private bool ShouldBeCalledOff() { - return !PartyUtility.AcceptableGameConditionsToContinueParty(base.Map) || (!this.spot.Roofed(base.Map) && !JoyUtility.EnjoyableOutsideNow(base.Map, null)); - } - - public override float VoluntaryJoinPriorityFor(Pawn p) - { - if (!this.IsInvited(p)) + if (!PartyUtility.AcceptableGameConditionsToContinueParty(base.Map)) { - return 0f; + return true; } - if (!PartyUtility.ShouldPawnKeepPartying(p)) + if (!this.spot.Roofed(base.Map) && !JoyUtility.EnjoyableOutsideNow(base.Map, null)) { - return 0f; + return true; } - if (!this.lord.ownedPawns.Contains(p) && this.IsPartyAboutToEnd()) + return false; + } + + public override float VoluntaryJoinPriorityFor(Pawn p) + { + if (this.IsInvited(p)) { - return 0f; + if (!PartyUtility.ShouldPawnKeepPartying(p)) + { + return 0f; + } + if (!base.lord.ownedPawns.Contains(p) && this.IsPartyAboutToEnd()) + { + return 0f; + } + return VoluntarilyJoinableLordJobJoinPriorities.PartyGuest; } - return VoluntarilyJoinableLordJobJoinPriorities.PartyGuest; + return 0f; } public override void ExposeData() @@ -81,12 +89,16 @@ public override string GetReport() private bool IsPartyAboutToEnd() { - return this.timeoutTrigger.TicksLeft < 1200; + if (this.timeoutTrigger.TicksLeft < 1200) + { + return true; + } + return false; } private bool IsInvited(Pawn p) { - return p.Faction == this.lord.faction; + return p.Faction == base.lord.faction; } } } diff --git a/Assembly-CSharp/RimWorld/LordJob_Kidnap.cs b/Assembly-CSharp/RimWorld/LordJob_Kidnap.cs index cade54f82..9c49fb73b 100644 --- a/Assembly-CSharp/RimWorld/LordJob_Kidnap.cs +++ b/Assembly-CSharp/RimWorld/LordJob_Kidnap.cs @@ -1,4 +1,3 @@ -using System; using Verse.AI.Group; namespace RimWorld diff --git a/Assembly-CSharp/RimWorld/LordJob_LoadAndEnterTransporters.cs b/Assembly-CSharp/RimWorld/LordJob_LoadAndEnterTransporters.cs index 92ef090a4..483bb8eae 100644 --- a/Assembly-CSharp/RimWorld/LordJob_LoadAndEnterTransporters.cs +++ b/Assembly-CSharp/RimWorld/LordJob_LoadAndEnterTransporters.cs @@ -48,16 +48,24 @@ public override StateGraph CreateGraph() private void CancelLoadingProcess() { - List list = this.lord.Map.listerThings.ThingsInGroup(ThingRequestGroup.Transporter); - for (int i = 0; i < list.Count; i++) + List list = base.lord.Map.listerThings.ThingsInGroup(ThingRequestGroup.Transporter); + int num = 0; + CompTransporter compTransporter; + while (true) { - CompTransporter compTransporter = list[i].TryGetComp(); - if (compTransporter.groupID == this.transportersGroup) + if (num < list.Count) { - compTransporter.CancelLoad(); + compTransporter = list[num].TryGetComp(); + if (compTransporter.groupID != this.transportersGroup) + { + num++; + continue; + } break; } + return; } + compTransporter.CancelLoad(); } } } diff --git a/Assembly-CSharp/RimWorld/LordJob_ManTurrets.cs b/Assembly-CSharp/RimWorld/LordJob_ManTurrets.cs index bbf459e7d..afb525c5a 100644 --- a/Assembly-CSharp/RimWorld/LordJob_ManTurrets.cs +++ b/Assembly-CSharp/RimWorld/LordJob_ManTurrets.cs @@ -1,4 +1,3 @@ -using System; using Verse.AI.Group; namespace RimWorld @@ -7,10 +6,9 @@ public class LordJob_ManTurrets : LordJob { public override StateGraph CreateGraph() { - return new StateGraph - { - StartingToil = new LordToil_ManClosestTurrets() - }; + StateGraph stateGraph = new StateGraph(); + stateGraph.StartingToil = new LordToil_ManClosestTurrets(); + return stateGraph; } } } diff --git a/Assembly-CSharp/RimWorld/LordJob_MechanoidsDefendShip.cs b/Assembly-CSharp/RimWorld/LordJob_MechanoidsDefendShip.cs index 69cc7097f..6eeb6e7e8 100644 --- a/Assembly-CSharp/RimWorld/LordJob_MechanoidsDefendShip.cs +++ b/Assembly-CSharp/RimWorld/LordJob_MechanoidsDefendShip.cs @@ -1,4 +1,3 @@ -using System; using Verse; using Verse.AI; using Verse.AI.Group; @@ -45,11 +44,7 @@ public override StateGraph CreateGraph() LordToil_ExitMap lordToil_ExitMap = new LordToil_ExitMap(LocomotionUrgency.Walk, true); stateGraph.AddToil(lordToil_ExitMap); Transition transition = new Transition(lordToil_DefendPoint, lordToil_ExitMap); - transition.AddSources(new LordToil[] - { - lordToil_AssaultColony2, - lordToil_AssaultColony - }); + transition.AddSources(lordToil_AssaultColony2, lordToil_AssaultColony); transition.AddTrigger(new Trigger_PawnCannotReachMapEdge()); stateGraph.AddTransition(transition); Transition transition2 = new Transition(lordToil_ExitMap, lordToil_AssaultColony2); @@ -63,10 +58,7 @@ public override StateGraph CreateGraph() transition3.AddPostAction(new TransitionAction_EndAllJobs()); stateGraph.AddTransition(transition3); Transition transition4 = new Transition(lordToil_AssaultColony, lordToil_DefendPoint); - transition4.AddTrigger(new Trigger_TicksPassedWithoutHarmOrMemos(1380, new string[] - { - Building_CrashedShipPart.MemoDamaged - })); + transition4.AddTrigger(new Trigger_TicksPassedWithoutHarmOrMemos(1380, Building_CrashedShipPart.MemoDamaged)); transition4.AddPostAction(new TransitionAction_EndAttackBuildingJobs()); stateGraph.AddTransition(transition4); Transition transition5 = new Transition(lordToil_DefendPoint, lordToil_AssaultColony2); diff --git a/Assembly-CSharp/RimWorld/LordJob_PrisonBreak.cs b/Assembly-CSharp/RimWorld/LordJob_PrisonBreak.cs index 290110c60..1a0b9a014 100644 --- a/Assembly-CSharp/RimWorld/LordJob_PrisonBreak.cs +++ b/Assembly-CSharp/RimWorld/LordJob_PrisonBreak.cs @@ -1,4 +1,3 @@ -using System; using Verse; using Verse.AI; using Verse.AI.Group; @@ -48,11 +47,7 @@ public override StateGraph CreateGraph() LordToil_ExitMap lordToil_ExitMap2 = new LordToil_ExitMap(LocomotionUrgency.Jog, true); stateGraph.AddToil(lordToil_ExitMap2); Transition transition = new Transition(lordToil_Travel, lordToil_ExitMap2); - transition.AddSources(new LordToil[] - { - lordToil_PrisonerEscape, - lordToil_ExitMap - }); + transition.AddSources(lordToil_PrisonerEscape, lordToil_ExitMap); transition.AddTrigger(new Trigger_PawnCannotReachMapEdge()); stateGraph.AddTransition(transition); Transition transition2 = new Transition(lordToil_ExitMap2, lordToil_ExitMap); diff --git a/Assembly-CSharp/RimWorld/LordJob_Siege.cs b/Assembly-CSharp/RimWorld/LordJob_Siege.cs index 430145139..eb4a2c02d 100644 --- a/Assembly-CSharp/RimWorld/LordJob_Siege.cs +++ b/Assembly-CSharp/RimWorld/LordJob_Siege.cs @@ -1,4 +1,3 @@ -using System; using Verse; using Verse.AI.Group; @@ -39,12 +38,8 @@ public override StateGraph CreateGraph() transition2.AddTrigger(new Trigger_Memo("NoArtillery")); transition2.AddTrigger(new Trigger_PawnHarmed(0.08f, false)); transition2.AddTrigger(new Trigger_FractionPawnsLost(0.3f)); - transition2.AddTrigger(new Trigger_TicksPassed((int)(60000f * Rand.Range(1.5f, 3f)))); - transition2.AddPreAction(new TransitionAction_Message("MessageSiegersAssaulting".Translate(new object[] - { - this.faction.def.pawnsPlural, - this.faction - }), MessageSound.SeriousAlert)); + transition2.AddTrigger(new Trigger_TicksPassed((int)(60000.0 * Rand.Range(1.5f, 3f)))); + transition2.AddPreAction(new TransitionAction_Message("MessageSiegersAssaulting".Translate(this.faction.def.pawnsPlural, this.faction), MessageSound.SeriousAlert)); transition2.AddPostAction(new TransitionAction_WakeAll()); stateGraph.AddTransition(transition2); return stateGraph; diff --git a/Assembly-CSharp/RimWorld/LordJob_StageThenAttack.cs b/Assembly-CSharp/RimWorld/LordJob_StageThenAttack.cs index 09dc6c7ac..640ee8194 100644 --- a/Assembly-CSharp/RimWorld/LordJob_StageThenAttack.cs +++ b/Assembly-CSharp/RimWorld/LordJob_StageThenAttack.cs @@ -1,4 +1,3 @@ -using System; using Verse; using Verse.AI.Group; @@ -29,11 +28,7 @@ public override StateGraph CreateGraph() Transition transition = new Transition(lordToil_Stage, startingToil); transition.AddTrigger(new Trigger_TicksPassed(Rand.Range(5000, 15000))); transition.AddTrigger(new Trigger_FractionPawnsLost(0.3f)); - transition.AddPreAction(new TransitionAction_Message("MessageRaidersBeginningAssault".Translate(new object[] - { - this.faction.def.pawnsPlural.CapitalizeFirst(), - this.faction.Name - }), MessageSound.SeriousAlert)); + transition.AddPreAction(new TransitionAction_Message("MessageRaidersBeginningAssault".Translate(this.faction.def.pawnsPlural.CapitalizeFirst(), this.faction.Name), MessageSound.SeriousAlert)); transition.AddPostAction(new TransitionAction_WakeAll()); stateGraph.AddTransition(transition); return stateGraph; diff --git a/Assembly-CSharp/RimWorld/LordJob_Steal.cs b/Assembly-CSharp/RimWorld/LordJob_Steal.cs index 86a46e8ff..98d47c13b 100644 --- a/Assembly-CSharp/RimWorld/LordJob_Steal.cs +++ b/Assembly-CSharp/RimWorld/LordJob_Steal.cs @@ -1,4 +1,3 @@ -using System; using Verse.AI.Group; namespace RimWorld diff --git a/Assembly-CSharp/RimWorld/LordJob_TradeWithColony.cs b/Assembly-CSharp/RimWorld/LordJob_TradeWithColony.cs index 16faf868c..4e39553f7 100644 --- a/Assembly-CSharp/RimWorld/LordJob_TradeWithColony.cs +++ b/Assembly-CSharp/RimWorld/LordJob_TradeWithColony.cs @@ -1,4 +1,3 @@ -using System; using Verse; using Verse.AI; using Verse.AI.Group; @@ -39,34 +38,15 @@ public override StateGraph CreateGraph() LordToil_ExitMapTraderFighting lordToil_ExitMapTraderFighting = new LordToil_ExitMapTraderFighting(); stateGraph.AddToil(lordToil_ExitMapTraderFighting); Transition transition = new Transition(lordToil_Travel, lordToil_ExitMapAndEscortCarriers); - transition.AddSources(new LordToil[] - { - lordToil_DefendTraderCaravan, - lordToil_DefendTraderCaravan2 - }); - transition.AddPreAction(new TransitionAction_Message("MessageVisitorsDangerousTemperature".Translate(new object[] - { - this.faction.def.pawnsPlural.CapitalizeFirst(), - this.faction.Name - }))); + transition.AddSources(lordToil_DefendTraderCaravan, lordToil_DefendTraderCaravan2); + transition.AddPreAction(new TransitionAction_Message("MessageVisitorsDangerousTemperature".Translate(this.faction.def.pawnsPlural.CapitalizeFirst(), this.faction.Name))); transition.AddPostAction(new TransitionAction_WakeAll()); transition.AddTrigger(new Trigger_PawnExperiencingDangerousTemperatures()); stateGraph.AddTransition(transition); Transition transition2 = new Transition(lordToil_Travel, lordToil_ExitMap2); - transition2.AddSources(new LordToil[] - { - lordToil_DefendTraderCaravan, - lordToil_DefendTraderCaravan2, - lordToil_ExitMapAndEscortCarriers, - lordToil_ExitMap, - lordToil_ExitMapTraderFighting - }); + transition2.AddSources(lordToil_DefendTraderCaravan, lordToil_DefendTraderCaravan2, lordToil_ExitMapAndEscortCarriers, lordToil_ExitMap, lordToil_ExitMapTraderFighting); transition2.AddTrigger(new Trigger_PawnCannotReachMapEdge()); - transition2.AddPostAction(new TransitionAction_Message("MessageVisitorsTrappedLeaving".Translate(new object[] - { - this.faction.def.pawnsPlural.CapitalizeFirst(), - this.faction.Name - }))); + transition2.AddPostAction(new TransitionAction_Message("MessageVisitorsTrappedLeaving".Translate(this.faction.def.pawnsPlural.CapitalizeFirst(), this.faction.Name))); transition2.AddPostAction(new TransitionAction_WakeAll()); transition2.AddPostAction(new TransitionAction_EndAllJobs()); stateGraph.AddTransition(transition2); @@ -75,13 +55,7 @@ public override StateGraph CreateGraph() transition3.AddPostAction(new TransitionAction_EndAllJobs()); stateGraph.AddTransition(transition3); Transition transition4 = new Transition(lordToil_Travel, lordToil_ExitMapTraderFighting); - transition4.AddSources(new LordToil[] - { - lordToil_DefendTraderCaravan, - lordToil_DefendTraderCaravan2, - lordToil_ExitMapAndEscortCarriers, - lordToil_ExitMap - }); + transition4.AddSources(lordToil_DefendTraderCaravan, lordToil_DefendTraderCaravan2, lordToil_ExitMapAndEscortCarriers, lordToil_ExitMap); transition4.AddTrigger(new Trigger_FractionPawnsLost(0.2f)); transition4.AddPostAction(new TransitionAction_EndAllJobs()); stateGraph.AddTransition(transition4); @@ -99,10 +73,7 @@ public override StateGraph CreateGraph() stateGraph.AddTransition(transition7); Transition transition8 = new Transition(lordToil_DefendTraderCaravan2, lordToil_ExitMapAndEscortCarriers); transition8.AddTrigger(new Trigger_TicksPassed(Rand.Range(27000, 45000))); - transition8.AddPreAction(new TransitionAction_Message("MessageTraderCaravanLeaving".Translate(new object[] - { - this.faction.Name - }))); + transition8.AddPreAction(new TransitionAction_Message("MessageTraderCaravanLeaving".Translate(this.faction.Name))); transition8.AddPostAction(new TransitionAction_WakeAll()); stateGraph.AddTransition(transition8); Transition transition9 = new Transition(lordToil_ExitMapAndEscortCarriers, lordToil_ExitMapAndEscortCarriers); @@ -114,11 +85,7 @@ public override StateGraph CreateGraph() transition10.AddPostAction(new TransitionAction_WakeAll()); stateGraph.AddTransition(transition10); Transition transition11 = new Transition(lordToil_DefendTraderCaravan2, lordToil_ExitMapAndEscortCarriers); - transition11.AddSources(new LordToil[] - { - lordToil_Travel, - lordToil_DefendTraderCaravan - }); + transition11.AddSources(lordToil_Travel, lordToil_DefendTraderCaravan); transition11.AddTrigger(new Trigger_ImportantTraderCaravanPeopleLost()); transition11.AddTrigger(new Trigger_BecameColonyEnemy()); transition11.AddPostAction(new TransitionAction_WakeAll()); diff --git a/Assembly-CSharp/RimWorld/LordJob_VisitColony.cs b/Assembly-CSharp/RimWorld/LordJob_VisitColony.cs index 5b294ff74..934e5d71b 100644 --- a/Assembly-CSharp/RimWorld/LordJob_VisitColony.cs +++ b/Assembly-CSharp/RimWorld/LordJob_VisitColony.cs @@ -1,4 +1,3 @@ -using System; using Verse; using Verse.AI; using Verse.AI.Group; @@ -36,32 +35,17 @@ public override StateGraph CreateGraph() LordToil_ExitMap lordToil_ExitMap = new LordToil_ExitMap(LocomotionUrgency.Walk, true); stateGraph.AddToil(lordToil_ExitMap); Transition transition = new Transition(startingToil, startingToil2); - transition.AddSources(new LordToil[] - { - lordToil_DefendPoint - }); + transition.AddSources(lordToil_DefendPoint); transition.AddTrigger(new Trigger_PawnExperiencingDangerousTemperatures()); - transition.AddPreAction(new TransitionAction_Message("MessageVisitorsDangerousTemperature".Translate(new object[] - { - this.faction.def.pawnsPlural.CapitalizeFirst(), - this.faction.Name - }))); + transition.AddPreAction(new TransitionAction_Message("MessageVisitorsDangerousTemperature".Translate(this.faction.def.pawnsPlural.CapitalizeFirst(), this.faction.Name))); transition.AddPreAction(new TransitionAction_EnsureHaveExitDestination()); transition.AddPostAction(new TransitionAction_WakeAll()); stateGraph.AddTransition(transition); Transition transition2 = new Transition(startingToil, lordToil_ExitMap); - transition2.AddSources(new LordToil[] - { - lordToil_DefendPoint, - lordToil_TakeWoundedGuest - }); + transition2.AddSources(lordToil_DefendPoint, lordToil_TakeWoundedGuest); transition2.AddSources(stateGraph2.lordToils); transition2.AddTrigger(new Trigger_PawnCannotReachMapEdge()); - transition2.AddPreAction(new TransitionAction_Message("MessageVisitorsTrappedLeaving".Translate(new object[] - { - this.faction.def.pawnsPlural.CapitalizeFirst(), - this.faction.Name - }))); + transition2.AddPreAction(new TransitionAction_Message("MessageVisitorsTrappedLeaving".Translate(this.faction.def.pawnsPlural.CapitalizeFirst(), this.faction.Name))); stateGraph.AddTransition(transition2); Transition transition3 = new Transition(lordToil_ExitMap, startingToil2); transition3.AddTrigger(new Trigger_PawnCanReachMapEdge()); @@ -73,18 +57,10 @@ public override StateGraph CreateGraph() stateGraph.AddTransition(transition4); Transition transition5 = new Transition(lordToil_DefendPoint, lordToil_TakeWoundedGuest); transition5.AddTrigger(new Trigger_WoundedGuestPresent()); - transition5.AddPreAction(new TransitionAction_Message("MessageVisitorsTakingWounded".Translate(new object[] - { - this.faction.def.pawnsPlural.CapitalizeFirst(), - this.faction.Name - }))); + transition5.AddPreAction(new TransitionAction_Message("MessageVisitorsTakingWounded".Translate(this.faction.def.pawnsPlural.CapitalizeFirst(), this.faction.Name))); stateGraph.AddTransition(transition5); Transition transition6 = new Transition(lordToil_DefendPoint, target); - transition6.AddSources(new LordToil[] - { - lordToil_TakeWoundedGuest, - startingToil - }); + transition6.AddSources(lordToil_TakeWoundedGuest, startingToil); transition6.AddTrigger(new Trigger_BecameColonyEnemy()); transition6.AddPreAction(new TransitionAction_SetDefendLocalGroup()); transition6.AddPostAction(new TransitionAction_WakeAll()); @@ -92,10 +68,7 @@ public override StateGraph CreateGraph() stateGraph.AddTransition(transition6); Transition transition7 = new Transition(lordToil_DefendPoint, startingToil2); transition7.AddTrigger(new Trigger_TicksPassed(Rand.Range(8000, 22000))); - transition7.AddPreAction(new TransitionAction_Message("VisitorsLeaving".Translate(new object[] - { - this.faction.Name - }))); + transition7.AddPreAction(new TransitionAction_Message("VisitorsLeaving".Translate(this.faction.Name))); transition7.AddPostAction(new TransitionAction_WakeAll()); transition7.AddPreAction(new TransitionAction_EnsureHaveExitDestination()); stateGraph.AddTransition(transition7); diff --git a/Assembly-CSharp/RimWorld/LordJob_VoluntarilyJoinable.cs b/Assembly-CSharp/RimWorld/LordJob_VoluntarilyJoinable.cs index 8f1e84078..136564d38 100644 --- a/Assembly-CSharp/RimWorld/LordJob_VoluntarilyJoinable.cs +++ b/Assembly-CSharp/RimWorld/LordJob_VoluntarilyJoinable.cs @@ -1,4 +1,3 @@ -using System; using Verse; using Verse.AI.Group; diff --git a/Assembly-CSharp/RimWorld/LordToilData_AssaultColonySappers.cs b/Assembly-CSharp/RimWorld/LordToilData_AssaultColonySappers.cs index 4f02767e6..5f9873856 100644 --- a/Assembly-CSharp/RimWorld/LordToilData_AssaultColonySappers.cs +++ b/Assembly-CSharp/RimWorld/LordToilData_AssaultColonySappers.cs @@ -1,4 +1,3 @@ -using System; using Verse; using Verse.AI.Group; diff --git a/Assembly-CSharp/RimWorld/LordToilData_DefendAndExpandHive.cs b/Assembly-CSharp/RimWorld/LordToilData_DefendAndExpandHive.cs index 4c40ab6d2..ec6e73b96 100644 --- a/Assembly-CSharp/RimWorld/LordToilData_DefendAndExpandHive.cs +++ b/Assembly-CSharp/RimWorld/LordToilData_DefendAndExpandHive.cs @@ -13,12 +13,12 @@ public override void ExposeData() { if (Scribe.mode == LoadSaveMode.Saving) { - this.assignedHives.RemoveAll((KeyValuePair x) => x.Key.Destroyed); + this.assignedHives.RemoveAll((Predicate>)((KeyValuePair x) => x.Key.Destroyed)); } Scribe_Collections.Look(ref this.assignedHives, "assignedHives", LookMode.Reference, LookMode.Reference); if (Scribe.mode == LoadSaveMode.PostLoadInit) { - this.assignedHives.RemoveAll((KeyValuePair x) => x.Value == null); + this.assignedHives.RemoveAll((Predicate>)((KeyValuePair x) => x.Value == null)); } } } diff --git a/Assembly-CSharp/RimWorld/LordToilData_HuntEnemies.cs b/Assembly-CSharp/RimWorld/LordToilData_HuntEnemies.cs index 7f58158b8..fb9124b66 100644 --- a/Assembly-CSharp/RimWorld/LordToilData_HuntEnemies.cs +++ b/Assembly-CSharp/RimWorld/LordToilData_HuntEnemies.cs @@ -1,4 +1,3 @@ -using System; using Verse; using Verse.AI.Group; diff --git a/Assembly-CSharp/RimWorld/LordToilData_MarriageCeremony.cs b/Assembly-CSharp/RimWorld/LordToilData_MarriageCeremony.cs index d0b35dd45..ff0b98b27 100644 --- a/Assembly-CSharp/RimWorld/LordToilData_MarriageCeremony.cs +++ b/Assembly-CSharp/RimWorld/LordToilData_MarriageCeremony.cs @@ -1,4 +1,3 @@ -using System; using Verse; using Verse.AI.Group; diff --git a/Assembly-CSharp/RimWorld/LordToilData_Party.cs b/Assembly-CSharp/RimWorld/LordToilData_Party.cs index d60d72d12..840c1a66d 100644 --- a/Assembly-CSharp/RimWorld/LordToilData_Party.cs +++ b/Assembly-CSharp/RimWorld/LordToilData_Party.cs @@ -1,4 +1,3 @@ -using System; using Verse; using Verse.AI.Group; diff --git a/Assembly-CSharp/RimWorld/LordToilData_Siege.cs b/Assembly-CSharp/RimWorld/LordToilData_Siege.cs index a6b144910..6a7fbf316 100644 --- a/Assembly-CSharp/RimWorld/LordToilData_Siege.cs +++ b/Assembly-CSharp/RimWorld/LordToilData_Siege.cs @@ -25,7 +25,7 @@ public override void ExposeData() Scribe_Values.Look(ref this.desiredBuilderFraction, "desiredBuilderFraction", 0.5f, false); if (Scribe.mode == LoadSaveMode.Saving) { - this.blueprints.RemoveAll((Blueprint blue) => blue.Destroyed); + this.blueprints.RemoveAll((Predicate)((Blueprint blue) => blue.Destroyed)); } Scribe_Collections.Look(ref this.blueprints, "blueprints", LookMode.Reference, new object[0]); } diff --git a/Assembly-CSharp/RimWorld/LordToilData_Stage.cs b/Assembly-CSharp/RimWorld/LordToilData_Stage.cs index 4023d54e9..fb91024c6 100644 --- a/Assembly-CSharp/RimWorld/LordToilData_Stage.cs +++ b/Assembly-CSharp/RimWorld/LordToilData_Stage.cs @@ -1,4 +1,3 @@ -using System; using Verse; using Verse.AI.Group; diff --git a/Assembly-CSharp/RimWorld/LordToil_AssaultColony.cs b/Assembly-CSharp/RimWorld/LordToil_AssaultColony.cs index 5f4a4fca2..0d077b07d 100644 --- a/Assembly-CSharp/RimWorld/LordToil_AssaultColony.cs +++ b/Assembly-CSharp/RimWorld/LordToil_AssaultColony.cs @@ -1,4 +1,3 @@ -using System; using Verse.AI; using Verse.AI.Group; @@ -22,9 +21,9 @@ public override void Init() public override void UpdateAllDuties() { - for (int i = 0; i < this.lord.ownedPawns.Count; i++) + for (int i = 0; i < base.lord.ownedPawns.Count; i++) { - this.lord.ownedPawns[i].mindState.duty = new PawnDuty(DutyDefOf.AssaultColony); + base.lord.ownedPawns[i].mindState.duty = new PawnDuty(DutyDefOf.AssaultColony); } } } diff --git a/Assembly-CSharp/RimWorld/LordToil_AssaultColonySappers.cs b/Assembly-CSharp/RimWorld/LordToil_AssaultColonySappers.cs index 5a7844ab2..50b2329d2 100644 --- a/Assembly-CSharp/RimWorld/LordToil_AssaultColonySappers.cs +++ b/Assembly-CSharp/RimWorld/LordToil_AssaultColonySappers.cs @@ -1,4 +1,3 @@ -using System; using System.Collections.Generic; using Verse; using Verse.AI; @@ -16,7 +15,7 @@ private LordToilData_AssaultColonySappers Data { get { - return (LordToilData_AssaultColonySappers)this.data; + return (LordToilData_AssaultColonySappers)base.data; } } @@ -30,7 +29,7 @@ public override bool AllowSatisfyLongNeeds public LordToil_AssaultColonySappers() { - this.data = new LordToilData_AssaultColonySappers(); + base.data = new LordToilData_AssaultColonySappers(); } public override void Init() @@ -41,46 +40,38 @@ public override void Init() public override void UpdateAllDuties() { - if (!this.Data.sapperDest.IsValid && this.lord.ownedPawns.Any()) + if (!this.Data.sapperDest.IsValid && base.lord.ownedPawns.Any()) { - this.Data.sapperDest = GenAI.RandomRaidDest(this.lord.ownedPawns[0].Position, base.Map); + this.Data.sapperDest = GenAI.RandomRaidDest(base.lord.ownedPawns[0].Position, base.Map); } List list = null; if (this.Data.sapperDest.IsValid) { list = new List(); - for (int i = 0; i < this.lord.ownedPawns.Count; i++) + for (int i = 0; i < base.lord.ownedPawns.Count; i++) { - Pawn pawn = this.lord.ownedPawns[i]; + Pawn pawn = base.lord.ownedPawns[i]; if (pawn.equipment.Primary != null && pawn.equipment.Primary.def.Verbs[0].ai_IsBuildingDestroyer) { list.Add(pawn); } } - if (list.Count == 0 && this.lord.ownedPawns.Count >= 2) + if (list.Count == 0 && base.lord.ownedPawns.Count >= 2) { - list.Add(this.lord.ownedPawns[0]); + list.Add(base.lord.ownedPawns[0]); } } - for (int j = 0; j < this.lord.ownedPawns.Count; j++) + for (int j = 0; j < base.lord.ownedPawns.Count; j++) { - Pawn pawn2 = this.lord.ownedPawns[j]; + Pawn pawn2 = base.lord.ownedPawns[j]; if (list != null && list.Contains(pawn2)) { pawn2.mindState.duty = new PawnDuty(DutyDefOf.Sapper, this.Data.sapperDest, -1f); } - else if (!list.NullOrEmpty()) + else if (!list.NullOrEmpty()) { - float randomInRange; - if (pawn2.equipment != null && pawn2.equipment.Primary != null && pawn2.equipment.Primary.def.IsRangedWeapon) - { - randomInRange = LordToil_AssaultColonySappers.EscortRadiusRanged.RandomInRange; - } - else - { - randomInRange = LordToil_AssaultColonySappers.EscortRadiusMelee.RandomInRange; - } - pawn2.mindState.duty = new PawnDuty(DutyDefOf.Escort, list.RandomElement(), randomInRange); + float radius = (pawn2.equipment == null || pawn2.equipment.Primary == null || !pawn2.equipment.Primary.def.IsRangedWeapon) ? LordToil_AssaultColonySappers.EscortRadiusMelee.RandomInRange : LordToil_AssaultColonySappers.EscortRadiusRanged.RandomInRange; + pawn2.mindState.duty = new PawnDuty(DutyDefOf.Escort, (Thing)list.RandomElement(), radius); } else { diff --git a/Assembly-CSharp/RimWorld/LordToil_DefendAndExpandHive.cs b/Assembly-CSharp/RimWorld/LordToil_DefendAndExpandHive.cs index ca62d0d6a..820fc0101 100644 --- a/Assembly-CSharp/RimWorld/LordToil_DefendAndExpandHive.cs +++ b/Assembly-CSharp/RimWorld/LordToil_DefendAndExpandHive.cs @@ -14,34 +14,33 @@ private LordToilData_DefendAndExpandHive Data { get { - return (LordToilData_DefendAndExpandHive)this.data; + return (LordToilData_DefendAndExpandHive)base.data; } } public LordToil_DefendAndExpandHive() { - this.data = new LordToilData_DefendAndExpandHive(); + base.data = new LordToilData_DefendAndExpandHive(); } public override void UpdateAllDuties() { this.FilterOutUnspawnedHives(); - for (int i = 0; i < this.lord.ownedPawns.Count; i++) + for (int i = 0; i < base.lord.ownedPawns.Count; i++) { - Hive hiveFor = this.GetHiveFor(this.lord.ownedPawns[i]); - PawnDuty duty = new PawnDuty(DutyDefOf.DefendAndExpandHive, hiveFor, this.distToHiveToAttack); - this.lord.ownedPawns[i].mindState.duty = duty; + Hive hiveFor = this.GetHiveFor(base.lord.ownedPawns[i]); + PawnDuty pawnDuty = base.lord.ownedPawns[i].mindState.duty = new PawnDuty(DutyDefOf.DefendAndExpandHive, (Thing)hiveFor, this.distToHiveToAttack); } } private void FilterOutUnspawnedHives() { - this.Data.assignedHives.RemoveAll((KeyValuePair x) => x.Value == null || !x.Value.Spawned); + this.Data.assignedHives.RemoveAll((Predicate>)((KeyValuePair x) => x.Value == null || !x.Value.Spawned)); } private Hive GetHiveFor(Pawn pawn) { - Hive hive; + Hive hive = default(Hive); if (this.Data.assignedHives.TryGetValue(pawn, out hive)) { return hive; @@ -56,7 +55,7 @@ private Hive GetHiveFor(Pawn pawn) private Hive FindClosestHive(Pawn pawn) { - return (Hive)GenClosest.ClosestThingReachable(pawn.Position, pawn.Map, ThingRequest.ForDef(ThingDefOf.Hive), PathEndMode.Touch, TraverseParms.For(pawn, Danger.Deadly, TraverseMode.ByPawn, false), 30f, (Thing x) => x.Faction == pawn.Faction, null, 0, 30, false, RegionType.Set_Passable, false); + return (Hive)GenClosest.ClosestThingReachable(pawn.Position, pawn.Map, ThingRequest.ForDef(ThingDefOf.Hive), PathEndMode.Touch, TraverseParms.For(pawn, Danger.Deadly, TraverseMode.ByPawn, false), 30f, (Predicate)((Thing x) => x.Faction == pawn.Faction), null, 0, 30, false, RegionType.Set_Passable, false); } } } diff --git a/Assembly-CSharp/RimWorld/LordToil_DefendBase.cs b/Assembly-CSharp/RimWorld/LordToil_DefendBase.cs index 6e2d83a5a..927167c3f 100644 --- a/Assembly-CSharp/RimWorld/LordToil_DefendBase.cs +++ b/Assembly-CSharp/RimWorld/LordToil_DefendBase.cs @@ -1,4 +1,3 @@ -using System; using Verse; using Verse.AI; using Verse.AI.Group; @@ -24,9 +23,9 @@ public LordToil_DefendBase(IntVec3 baseCenter) public override void UpdateAllDuties() { - for (int i = 0; i < this.lord.ownedPawns.Count; i++) + for (int i = 0; i < base.lord.ownedPawns.Count; i++) { - this.lord.ownedPawns[i].mindState.duty = new PawnDuty(DutyDefOf.DefendBase, this.baseCenter, -1f); + base.lord.ownedPawns[i].mindState.duty = new PawnDuty(DutyDefOf.DefendBase, this.baseCenter, -1f); } } } diff --git a/Assembly-CSharp/RimWorld/LordToil_DefendTraderCaravan.cs b/Assembly-CSharp/RimWorld/LordToil_DefendTraderCaravan.cs index c7f33b49f..f499a7bdc 100644 --- a/Assembly-CSharp/RimWorld/LordToil_DefendTraderCaravan.cs +++ b/Assembly-CSharp/RimWorld/LordToil_DefendTraderCaravan.cs @@ -1,4 +1,3 @@ -using System; using Verse; using Verse.AI; using Verse.AI.Group; @@ -34,29 +33,34 @@ public LordToil_DefendTraderCaravan(IntVec3 defendPoint) : base(defendPoint, 28f public override void UpdateAllDuties() { LordToilData_DefendPoint data = base.Data; - Pawn pawn = TraderCaravanUtility.FindTrader(this.lord); + Pawn pawn = TraderCaravanUtility.FindTrader(base.lord); if (pawn != null) { pawn.mindState.duty = new PawnDuty(DutyDefOf.Defend, data.defendPoint, data.defendRadius); - for (int i = 0; i < this.lord.ownedPawns.Count; i++) + for (int i = 0; i < base.lord.ownedPawns.Count; i++) { - Pawn pawn2 = this.lord.ownedPawns[i]; + Pawn pawn2 = base.lord.ownedPawns[i]; switch (pawn2.GetTraderCaravanRole()) { case TraderCaravanRole.Carrier: - pawn2.mindState.duty = new PawnDuty(DutyDefOf.Follow, pawn, 5f); + { + pawn2.mindState.duty = new PawnDuty(DutyDefOf.Follow, (Thing)pawn, 5f); pawn2.mindState.duty.locomotion = LocomotionUrgency.Walk; break; - case TraderCaravanRole.Guard: - pawn2.mindState.duty = new PawnDuty(DutyDefOf.Defend, data.defendPoint, data.defendRadius); - break; + } case TraderCaravanRole.Chattel: - pawn2.mindState.duty = new PawnDuty(DutyDefOf.Escort, pawn, 5f); + { + pawn2.mindState.duty = new PawnDuty(DutyDefOf.Escort, (Thing)pawn, 5f); pawn2.mindState.duty.locomotion = LocomotionUrgency.Walk; break; } + case TraderCaravanRole.Guard: + { + pawn2.mindState.duty = new PawnDuty(DutyDefOf.Defend, data.defendPoint, data.defendRadius); + break; + } + } } - return; } } } diff --git a/Assembly-CSharp/RimWorld/LordToil_DoOpportunisticTaskOrCover.cs b/Assembly-CSharp/RimWorld/LordToil_DoOpportunisticTaskOrCover.cs index 371219553..10d979425 100644 --- a/Assembly-CSharp/RimWorld/LordToil_DoOpportunisticTaskOrCover.cs +++ b/Assembly-CSharp/RimWorld/LordToil_DoOpportunisticTaskOrCover.cs @@ -1,4 +1,3 @@ -using System; using System.Collections.Generic; using Verse; using Verse.AI; @@ -28,9 +27,9 @@ protected abstract DutyDef DutyDef public override void UpdateAllDuties() { List list = null; - for (int i = 0; i < this.lord.ownedPawns.Count; i++) + for (int i = 0; i < base.lord.ownedPawns.Count; i++) { - Pawn pawn = this.lord.ownedPawns[i]; + Pawn pawn = base.lord.ownedPawns[i]; Thing item = null; if (!this.cover || (this.TryFindGoodOpportunisticTaskTarget(pawn, out item, list) && !GenAI.InDangerousCombat(pawn))) { @@ -57,13 +56,13 @@ public override void LordToilTick() if (this.cover && Find.TickManager.TicksGame % 181 == 0) { List list = null; - for (int i = 0; i < this.lord.ownedPawns.Count; i++) + for (int i = 0; i < base.lord.ownedPawns.Count; i++) { - Pawn pawn = this.lord.ownedPawns[i]; + Pawn pawn = base.lord.ownedPawns[i]; if (!pawn.Downed && pawn.mindState.duty.def == DutyDefOf.AssaultColony) { Thing thing = null; - if (this.TryFindGoodOpportunisticTaskTarget(pawn, out thing, list) && !base.Map.reservationManager.IsReserved(thing, this.lord.faction) && !GenAI.InDangerousCombat(pawn)) + if (this.TryFindGoodOpportunisticTaskTarget(pawn, out thing, list) && !base.Map.reservationManager.IsReserved(thing, base.lord.faction) && !GenAI.InDangerousCombat(pawn)) { pawn.mindState.duty = new PawnDuty(this.DutyDef); pawn.jobs.EndCurrentJob(JobCondition.InterruptForced, true); diff --git a/Assembly-CSharp/RimWorld/LordToil_ExitMapAndEscortCarriers.cs b/Assembly-CSharp/RimWorld/LordToil_ExitMapAndEscortCarriers.cs index 9c1e2567e..9222bed5f 100644 --- a/Assembly-CSharp/RimWorld/LordToil_ExitMapAndEscortCarriers.cs +++ b/Assembly-CSharp/RimWorld/LordToil_ExitMapAndEscortCarriers.cs @@ -17,12 +17,12 @@ public override bool AllowSatisfyLongNeeds public override void UpdateAllDuties() { - Pawn trader; + Pawn trader = default(Pawn); this.UpdateTraderDuty(out trader); this.UpdateCarriersDuties(trader); - for (int i = 0; i < this.lord.ownedPawns.Count; i++) + for (int i = 0; i < base.lord.ownedPawns.Count; i++) { - Pawn p = this.lord.ownedPawns[i]; + Pawn p = base.lord.ownedPawns[i]; TraderCaravanRole traderCaravanRole = p.GetTraderCaravanRole(); if (traderCaravanRole != TraderCaravanRole.Carrier && traderCaravanRole != TraderCaravanRole.Trader) { @@ -33,7 +33,7 @@ public override void UpdateAllDuties() private void UpdateTraderDuty(out Pawn trader) { - trader = TraderCaravanUtility.FindTrader(this.lord); + trader = TraderCaravanUtility.FindTrader(base.lord); if (trader != null) { trader.mindState.duty = new PawnDuty(DutyDefOf.ExitMapBestAndDefendSelf); @@ -44,14 +44,14 @@ private void UpdateTraderDuty(out Pawn trader) private void UpdateCarriersDuties(Pawn trader) { - for (int i = 0; i < this.lord.ownedPawns.Count; i++) + for (int i = 0; i < base.lord.ownedPawns.Count; i++) { - Pawn pawn = this.lord.ownedPawns[i]; + Pawn pawn = base.lord.ownedPawns[i]; if (pawn.GetTraderCaravanRole() == TraderCaravanRole.Carrier) { if (trader != null) { - pawn.mindState.duty = new PawnDuty(DutyDefOf.Follow, trader, 5f); + pawn.mindState.duty = new PawnDuty(DutyDefOf.Follow, (Thing)trader, 5f); } else { @@ -69,7 +69,7 @@ private void UpdateDutyForChattelOrGuard(Pawn p, Pawn trader) { if (trader != null) { - p.mindState.duty = new PawnDuty(DutyDefOf.Escort, trader, 14f); + p.mindState.duty = new PawnDuty(DutyDefOf.Escort, (Thing)trader, 14f); } else if (!this.TryToDefendClosestCarrier(p, 14f)) { @@ -82,7 +82,7 @@ private void UpdateDutyForChattelOrGuard(Pawn p, Pawn trader) { if (trader != null) { - p.mindState.duty = new PawnDuty(DutyDefOf.Escort, trader, 26f); + p.mindState.duty = new PawnDuty(DutyDefOf.Escort, (Thing)trader, 26f); } else { @@ -96,12 +96,12 @@ private void UpdateDutyForChattelOrGuard(Pawn p, Pawn trader) private bool TryToDefendClosestCarrier(Pawn p, float escortRadius) { Pawn closestCarrier = this.GetClosestCarrier(p); - Thing thing = GenClosest.ClosestThingReachable(p.Position, p.Map, ThingRequest.ForGroup(ThingRequestGroup.Corpse), PathEndMode.ClosestTouch, TraverseParms.For(p, Danger.Deadly, TraverseMode.ByPawn, false), 20f, delegate(Thing x) + Thing thing = GenClosest.ClosestThingReachable(p.Position, p.Map, ThingRequest.ForGroup(ThingRequestGroup.Corpse), PathEndMode.ClosestTouch, TraverseParms.For(p, Danger.Deadly, TraverseMode.ByPawn, false), 20f, (Predicate)delegate(Thing x) { Pawn innerPawn = ((Corpse)x).InnerPawn; return innerPawn.Faction == p.Faction && innerPawn.GetTraderCaravanRole() == TraderCaravanRole.Carrier; }, null, 0, 15, false, RegionType.Set_Passable, false); - Thing thing2 = GenClosest.ClosestThingReachable(p.Position, p.Map, ThingRequest.ForGroup(ThingRequestGroup.Pawn), PathEndMode.ClosestTouch, TraverseParms.For(p, Danger.Deadly, TraverseMode.ByPawn, false), 20f, delegate(Thing x) + Thing thing2 = GenClosest.ClosestThingReachable(p.Position, p.Map, ThingRequest.ForGroup(ThingRequestGroup.Pawn), PathEndMode.ClosestTouch, TraverseParms.For(p, Danger.Deadly, TraverseMode.ByPawn, false), 20f, (Predicate)delegate(Thing x) { Pawn pawn = (Pawn)x; return pawn.Downed && pawn.Faction == p.Faction && pawn.GetTraderCaravanRole() == TraderCaravanRole.Carrier; @@ -138,9 +138,9 @@ private Pawn GetClosestCarrier(Pawn closestTo) { Pawn pawn = null; float num = 0f; - for (int i = 0; i < this.lord.ownedPawns.Count; i++) + for (int i = 0; i < base.lord.ownedPawns.Count; i++) { - Pawn pawn2 = this.lord.ownedPawns[i]; + Pawn pawn2 = base.lord.ownedPawns[i]; if (pawn2.GetTraderCaravanRole() == TraderCaravanRole.Carrier) { float num2 = (float)pawn2.Position.DistanceToSquared(closestTo.Position); diff --git a/Assembly-CSharp/RimWorld/LordToil_HuntEnemies.cs b/Assembly-CSharp/RimWorld/LordToil_HuntEnemies.cs index f196398c2..deb63cbb6 100644 --- a/Assembly-CSharp/RimWorld/LordToil_HuntEnemies.cs +++ b/Assembly-CSharp/RimWorld/LordToil_HuntEnemies.cs @@ -1,4 +1,3 @@ -using System; using Verse; using Verse.AI; using Verse.AI.Group; @@ -11,25 +10,25 @@ private LordToilData_HuntEnemies Data { get { - return (LordToilData_HuntEnemies)this.data; + return (LordToilData_HuntEnemies)base.data; } } public LordToil_HuntEnemies(IntVec3 fallbackLocation) { - this.data = new LordToilData_HuntEnemies(); + base.data = new LordToilData_HuntEnemies(); this.Data.fallbackLocation = fallbackLocation; } public override void UpdateAllDuties() { LordToilData_HuntEnemies data = this.Data; - for (int i = 0; i < this.lord.ownedPawns.Count; i++) + for (int i = 0; i < base.lord.ownedPawns.Count; i++) { - Pawn pawn = this.lord.ownedPawns[i]; + Pawn pawn = base.lord.ownedPawns[i]; if (!data.fallbackLocation.IsValid) { - RCellFinder.TryFindRandomSpotJustOutsideColony(this.lord.ownedPawns[0], out data.fallbackLocation); + RCellFinder.TryFindRandomSpotJustOutsideColony(base.lord.ownedPawns[0], out data.fallbackLocation); } pawn.mindState.duty = new PawnDuty(DutyDefOf.HuntEnemiesIndividual); pawn.mindState.duty.focusSecond = data.fallbackLocation; diff --git a/Assembly-CSharp/RimWorld/LordToil_KidnapCover.cs b/Assembly-CSharp/RimWorld/LordToil_KidnapCover.cs index beda1003e..395924a12 100644 --- a/Assembly-CSharp/RimWorld/LordToil_KidnapCover.cs +++ b/Assembly-CSharp/RimWorld/LordToil_KidnapCover.cs @@ -1,4 +1,3 @@ -using System; using System.Collections.Generic; using Verse; using Verse.AI; @@ -22,7 +21,7 @@ protected override bool TryFindGoodOpportunisticTaskTarget(Pawn pawn, out Thing target = pawn.carryTracker.CarriedThing; return true; } - Pawn pawn2; + Pawn pawn2 = default(Pawn); bool result = KidnapAIUtility.TryFindGoodKidnapVictim(pawn, 8f, out pawn2, alreadyTakenTargets); target = pawn2; return result; diff --git a/Assembly-CSharp/RimWorld/LordToil_LoadAndEnterTransporters.cs b/Assembly-CSharp/RimWorld/LordToil_LoadAndEnterTransporters.cs index 29930cc01..c0a4fdc22 100644 --- a/Assembly-CSharp/RimWorld/LordToil_LoadAndEnterTransporters.cs +++ b/Assembly-CSharp/RimWorld/LordToil_LoadAndEnterTransporters.cs @@ -1,4 +1,3 @@ -using System; using Verse.AI; using Verse.AI.Group; @@ -23,11 +22,11 @@ public LordToil_LoadAndEnterTransporters(int transportersGroup) public override void UpdateAllDuties() { - for (int i = 0; i < this.lord.ownedPawns.Count; i++) + for (int i = 0; i < base.lord.ownedPawns.Count; i++) { PawnDuty pawnDuty = new PawnDuty(DutyDefOf.LoadAndEnterTransporters); pawnDuty.transportersGroup = this.transportersGroup; - this.lord.ownedPawns[i].mindState.duty = pawnDuty; + base.lord.ownedPawns[i].mindState.duty = pawnDuty; } } } diff --git a/Assembly-CSharp/RimWorld/LordToil_ManClosestTurrets.cs b/Assembly-CSharp/RimWorld/LordToil_ManClosestTurrets.cs index f4d7a1914..d1eb12611 100644 --- a/Assembly-CSharp/RimWorld/LordToil_ManClosestTurrets.cs +++ b/Assembly-CSharp/RimWorld/LordToil_ManClosestTurrets.cs @@ -1,4 +1,3 @@ -using System; using Verse.AI; using Verse.AI.Group; @@ -8,9 +7,9 @@ public class LordToil_ManClosestTurrets : LordToil { public override void UpdateAllDuties() { - for (int i = 0; i < this.lord.ownedPawns.Count; i++) + for (int i = 0; i < base.lord.ownedPawns.Count; i++) { - this.lord.ownedPawns[i].mindState.duty = new PawnDuty(DutyDefOf.ManClosestTurret, this.lord.ownedPawns[i].Position, -1f); + base.lord.ownedPawns[i].mindState.duty = new PawnDuty(DutyDefOf.ManClosestTurret, base.lord.ownedPawns[i].Position, -1f); } } } diff --git a/Assembly-CSharp/RimWorld/LordToil_MarriageCeremony.cs b/Assembly-CSharp/RimWorld/LordToil_MarriageCeremony.cs index 0050407ff..34423320e 100644 --- a/Assembly-CSharp/RimWorld/LordToil_MarriageCeremony.cs +++ b/Assembly-CSharp/RimWorld/LordToil_MarriageCeremony.cs @@ -19,7 +19,7 @@ public LordToilData_MarriageCeremony Data { get { - return (LordToilData_MarriageCeremony)this.data; + return (LordToilData_MarriageCeremony)base.data; } } @@ -28,7 +28,7 @@ public LordToil_MarriageCeremony(Pawn firstPawn, Pawn secondPawn, IntVec3 spot) this.firstPawn = firstPawn; this.secondPawn = secondPawn; this.spot = spot; - this.data = new LordToilData_MarriageCeremony(); + base.data = new LordToilData_MarriageCeremony(); } public override void Init() @@ -58,9 +58,9 @@ public override ThinkTreeDutyHook VoluntaryJoinDutyHookFor(Pawn p) public override void UpdateAllDuties() { - for (int i = 0; i < this.lord.ownedPawns.Count; i++) + for (int i = 0; i < base.lord.ownedPawns.Count; i++) { - Pawn pawn = this.lord.ownedPawns[i]; + Pawn pawn = base.lord.ownedPawns[i]; if (this.IsFiance(pawn)) { pawn.mindState.duty = new PawnDuty(DutyDefOf.MarryPawn, this.FianceStandingSpotFor(pawn), -1f); @@ -82,20 +82,20 @@ private bool IsFiance(Pawn p) public IntVec3 FianceStandingSpotFor(Pawn pawn) { - Pawn pawn2; + Pawn pawn2 = null; if (this.firstPawn == pawn) { pawn2 = this.secondPawn; + goto IL_0042; } - else + if (this.secondPawn == pawn) { - if (this.secondPawn != pawn) - { - Log.Warning("Called ExactStandingSpotFor but it's not this pawn's ceremony."); - return IntVec3.Invalid; - } pawn2 = this.firstPawn; + goto IL_0042; } + Log.Warning("Called ExactStandingSpotFor but it's not this pawn's ceremony."); + return IntVec3.Invalid; + IL_0042: if (pawn.thingIDNumber < pawn2.thingIDNumber) { return this.spot; @@ -109,7 +109,7 @@ public IntVec3 FianceStandingSpotFor(Pawn pawn) private Thing GetMarriageSpotAt(IntVec3 cell) { - return cell.GetThingList(base.Map).Find((Thing x) => x.def == ThingDefOf.MarriageSpot); + return cell.GetThingList(base.Map).Find((Predicate)((Thing x) => x.def == ThingDefOf.MarriageSpot)); } private IntVec3 FindCellForOtherPawnAtMarriageSpot(IntVec3 cell) @@ -118,12 +118,15 @@ private IntVec3 FindCellForOtherPawnAtMarriageSpot(IntVec3 cell) CellRect cellRect = marriageSpotAt.OccupiedRect(); for (int i = cellRect.minX; i <= cellRect.maxX; i++) { - for (int j = cellRect.minZ; j <= cellRect.maxZ; j++) + int num = cellRect.minZ; + while (num <= cellRect.maxZ) { - if (cell.x != i || cell.z != j) + if (cell.x == i && cell.z == num) { - return new IntVec3(i, 0, j); + num++; + continue; } + return new IntVec3(i, 0, num); } } Log.Warning("Marriage spot is 1x1. There's no place for 2 pawns."); diff --git a/Assembly-CSharp/RimWorld/LordToil_PanicFlee.cs b/Assembly-CSharp/RimWorld/LordToil_PanicFlee.cs index 9f12a558d..37392fd6c 100644 --- a/Assembly-CSharp/RimWorld/LordToil_PanicFlee.cs +++ b/Assembly-CSharp/RimWorld/LordToil_PanicFlee.cs @@ -1,4 +1,3 @@ -using System; using Verse; using Verse.AI; using Verse.AI.Group; @@ -18,21 +17,21 @@ public override bool AllowSatisfyLongNeeds public override void Init() { base.Init(); - for (int i = 0; i < this.lord.ownedPawns.Count; i++) + for (int i = 0; i < base.lord.ownedPawns.Count; i++) { - Pawn pawn = this.lord.ownedPawns[i]; + Pawn pawn = base.lord.ownedPawns[i]; if (!this.HasFleeingDuty(pawn) || pawn.mindState.duty.def == DutyDefOf.ExitMapRandom) { - pawn.mindState.mentalStateHandler.TryStartMentalState(MentalStateDefOf.PanicFlee, null, false, false, null); + pawn.mindState.mentalStateHandler.TryStartMentalState(MentalStateDefOf.PanicFlee, (string)null, false, false, null); } } } public override void UpdateAllDuties() { - for (int i = 0; i < this.lord.ownedPawns.Count; i++) + for (int i = 0; i < base.lord.ownedPawns.Count; i++) { - Pawn pawn = this.lord.ownedPawns[i]; + Pawn pawn = base.lord.ownedPawns[i]; if (!this.HasFleeingDuty(pawn)) { pawn.mindState.duty = new PawnDuty(DutyDefOf.ExitMapRandom); @@ -42,7 +41,15 @@ public override void UpdateAllDuties() private bool HasFleeingDuty(Pawn pawn) { - return pawn.mindState.duty != null && (pawn.mindState.duty.def == DutyDefOf.ExitMapRandom || pawn.mindState.duty.def == DutyDefOf.Steal || pawn.mindState.duty.def == DutyDefOf.Kidnap); + if (pawn.mindState.duty == null) + { + return false; + } + if (pawn.mindState.duty.def != DutyDefOf.ExitMapRandom && pawn.mindState.duty.def != DutyDefOf.Steal && pawn.mindState.duty.def != DutyDefOf.Kidnap) + { + return false; + } + return true; } } } diff --git a/Assembly-CSharp/RimWorld/LordToil_Party.cs b/Assembly-CSharp/RimWorld/LordToil_Party.cs index 9db50b7ec..c687f2b0d 100644 --- a/Assembly-CSharp/RimWorld/LordToil_Party.cs +++ b/Assembly-CSharp/RimWorld/LordToil_Party.cs @@ -1,4 +1,3 @@ -using System; using System.Collections.Generic; using Verse; using Verse.AI; @@ -16,14 +15,14 @@ private LordToilData_Party Data { get { - return (LordToilData_Party)this.data; + return (LordToilData_Party)base.data; } } public LordToil_Party(IntVec3 spot) { this.spot = spot; - this.data = new LordToilData_Party(); + base.data = new LordToilData_Party(); this.Data.ticksToNextPulse = 600; } @@ -34,9 +33,9 @@ public override ThinkTreeDutyHook VoluntaryJoinDutyHookFor(Pawn p) public override void UpdateAllDuties() { - for (int i = 0; i < this.lord.ownedPawns.Count; i++) + for (int i = 0; i < base.lord.ownedPawns.Count; i++) { - this.lord.ownedPawns[i].mindState.duty = new PawnDuty(DutyDefOf.Party, this.spot, -1f); + base.lord.ownedPawns[i].mindState.duty = new PawnDuty(DutyDefOf.Party, this.spot, -1f); } } @@ -45,7 +44,7 @@ public override void LordToilTick() if (--this.Data.ticksToNextPulse <= 0) { this.Data.ticksToNextPulse = 600; - List ownedPawns = this.lord.ownedPawns; + List ownedPawns = base.lord.ownedPawns; for (int i = 0; i < ownedPawns.Count; i++) { if (PartyUtility.InPartyArea(ownedPawns[i].Position, this.spot, base.Map)) diff --git a/Assembly-CSharp/RimWorld/LordToil_PrepareCaravan_GatherAnimals.cs b/Assembly-CSharp/RimWorld/LordToil_PrepareCaravan_GatherAnimals.cs index 532e61eba..1be6e6066 100644 --- a/Assembly-CSharp/RimWorld/LordToil_PrepareCaravan_GatherAnimals.cs +++ b/Assembly-CSharp/RimWorld/LordToil_PrepareCaravan_GatherAnimals.cs @@ -32,9 +32,9 @@ public LordToil_PrepareCaravan_GatherAnimals(IntVec3 meetingPoint) public override void UpdateAllDuties() { - for (int i = 0; i < this.lord.ownedPawns.Count; i++) + for (int i = 0; i < base.lord.ownedPawns.Count; i++) { - Pawn pawn = this.lord.ownedPawns[i]; + Pawn pawn = base.lord.ownedPawns[i]; if (pawn.IsColonist || pawn.RaceProps.Animal) { pawn.mindState.duty = new PawnDuty(DutyDefOf.PrepareCaravan_GatherPawns, this.meetingPoint, -1f); @@ -51,7 +51,7 @@ public override void LordToilTick() { if (Find.TickManager.TicksGame % 100 == 0) { - GatherAnimalsAndSlavesForCaravanUtility.CheckArrived(this.lord, this.meetingPoint, "AllAnimalsGathered", (Pawn x) => x.RaceProps.Animal, (Pawn x) => GatherAnimalsAndSlavesForCaravanUtility.IsFollowingAnyone(x)); + GatherAnimalsAndSlavesForCaravanUtility.CheckArrived(base.lord, this.meetingPoint, "AllAnimalsGathered", (Predicate)((Pawn x) => x.RaceProps.Animal), (Predicate)((Pawn x) => GatherAnimalsAndSlavesForCaravanUtility.IsFollowingAnyone(x))); } } } diff --git a/Assembly-CSharp/RimWorld/LordToil_PrepareCaravan_GatherItems.cs b/Assembly-CSharp/RimWorld/LordToil_PrepareCaravan_GatherItems.cs index 1d8612b33..b35844eef 100644 --- a/Assembly-CSharp/RimWorld/LordToil_PrepareCaravan_GatherItems.cs +++ b/Assembly-CSharp/RimWorld/LordToil_PrepareCaravan_GatherItems.cs @@ -1,4 +1,3 @@ -using System; using System.Collections.Generic; using Verse; using Verse.AI; @@ -33,9 +32,9 @@ public LordToil_PrepareCaravan_GatherItems(IntVec3 meetingPoint) public override void UpdateAllDuties() { - for (int i = 0; i < this.lord.ownedPawns.Count; i++) + for (int i = 0; i < base.lord.ownedPawns.Count; i++) { - Pawn pawn = this.lord.ownedPawns[i]; + Pawn pawn = base.lord.ownedPawns[i]; if (pawn.IsColonist) { pawn.mindState.duty = new PawnDuty(DutyDefOf.PrepareCaravan_GatherItems); @@ -57,9 +56,9 @@ public override void LordToilTick() if (Find.TickManager.TicksGame % 120 == 0) { bool flag = true; - for (int i = 0; i < this.lord.ownedPawns.Count; i++) + for (int i = 0; i < base.lord.ownedPawns.Count; i++) { - Pawn pawn = this.lord.ownedPawns[i]; + Pawn pawn = base.lord.ownedPawns[i]; if (pawn.IsColonist && pawn.mindState.lastJobTag != JobTag.WaitingForOthersToFinishGatheringItems) { flag = false; @@ -69,18 +68,21 @@ public override void LordToilTick() if (flag) { List allPawnsSpawned = base.Map.mapPawns.AllPawnsSpawned; - for (int j = 0; j < allPawnsSpawned.Count; j++) + int num = 0; + while (num < allPawnsSpawned.Count) { - if (allPawnsSpawned[j].CurJob != null && allPawnsSpawned[j].jobs.curDriver is JobDriver_PrepareCaravan_GatherItems && allPawnsSpawned[j].CurJob.lord == this.lord) + if (allPawnsSpawned[num].CurJob == null || !(allPawnsSpawned[num].jobs.curDriver is JobDriver_PrepareCaravan_GatherItems) || allPawnsSpawned[num].CurJob.lord != base.lord) { - flag = false; - break; + num++; + continue; } + flag = false; + break; } } if (flag) { - this.lord.ReceiveMemo("AllItemsGathered"); + base.lord.ReceiveMemo("AllItemsGathered"); } } } diff --git a/Assembly-CSharp/RimWorld/LordToil_PrepareCaravan_GatherSlaves.cs b/Assembly-CSharp/RimWorld/LordToil_PrepareCaravan_GatherSlaves.cs index 8a651f20e..d53ef278c 100644 --- a/Assembly-CSharp/RimWorld/LordToil_PrepareCaravan_GatherSlaves.cs +++ b/Assembly-CSharp/RimWorld/LordToil_PrepareCaravan_GatherSlaves.cs @@ -32,9 +32,9 @@ public LordToil_PrepareCaravan_GatherSlaves(IntVec3 meetingPoint) public override void UpdateAllDuties() { - for (int i = 0; i < this.lord.ownedPawns.Count; i++) + for (int i = 0; i < base.lord.ownedPawns.Count; i++) { - Pawn pawn = this.lord.ownedPawns[i]; + Pawn pawn = base.lord.ownedPawns[i]; if (!pawn.RaceProps.Animal) { pawn.mindState.duty = new PawnDuty(DutyDefOf.PrepareCaravan_GatherPawns, this.meetingPoint, -1f); @@ -51,7 +51,7 @@ public override void LordToilTick() { if (Find.TickManager.TicksGame % 100 == 0) { - GatherAnimalsAndSlavesForCaravanUtility.CheckArrived(this.lord, this.meetingPoint, "AllSlavesGathered", (Pawn x) => !x.IsColonist && !x.RaceProps.Animal, (Pawn x) => GatherAnimalsAndSlavesForCaravanUtility.IsFollowingAnyone(x)); + GatherAnimalsAndSlavesForCaravanUtility.CheckArrived(base.lord, this.meetingPoint, "AllSlavesGathered", (Predicate)((Pawn x) => !x.IsColonist && !x.RaceProps.Animal), (Predicate)((Pawn x) => GatherAnimalsAndSlavesForCaravanUtility.IsFollowingAnyone(x))); } } } diff --git a/Assembly-CSharp/RimWorld/LordToil_PrepareCaravan_Leave.cs b/Assembly-CSharp/RimWorld/LordToil_PrepareCaravan_Leave.cs index 134b57354..0b8ac8acd 100644 --- a/Assembly-CSharp/RimWorld/LordToil_PrepareCaravan_Leave.cs +++ b/Assembly-CSharp/RimWorld/LordToil_PrepareCaravan_Leave.cs @@ -40,9 +40,9 @@ public LordToil_PrepareCaravan_Leave(IntVec3 exitSpot) public override void UpdateAllDuties() { - for (int i = 0; i < this.lord.ownedPawns.Count; i++) + for (int i = 0; i < base.lord.ownedPawns.Count; i++) { - Pawn pawn = this.lord.ownedPawns[i]; + Pawn pawn = base.lord.ownedPawns[i]; pawn.mindState.duty = new PawnDuty(DutyDefOf.Travel, this.exitSpot, -1f); pawn.mindState.duty.locomotion = LocomotionUrgency.Jog; } @@ -52,7 +52,7 @@ public override void LordToilTick() { if (Find.TickManager.TicksGame % 100 == 0) { - GatherAnimalsAndSlavesForCaravanUtility.CheckArrived(this.lord, this.exitSpot, "ReadyToExitMap", (Pawn x) => true, null); + GatherAnimalsAndSlavesForCaravanUtility.CheckArrived(base.lord, this.exitSpot, "ReadyToExitMap", (Predicate)((Pawn x) => true), null); } } } diff --git a/Assembly-CSharp/RimWorld/LordToil_PrepareCaravan_Pause.cs b/Assembly-CSharp/RimWorld/LordToil_PrepareCaravan_Pause.cs index 8af24d6d3..545f9aec3 100644 --- a/Assembly-CSharp/RimWorld/LordToil_PrepareCaravan_Pause.cs +++ b/Assembly-CSharp/RimWorld/LordToil_PrepareCaravan_Pause.cs @@ -1,4 +1,3 @@ -using System; using Verse.AI; using Verse.AI.Group; @@ -8,9 +7,9 @@ public class LordToil_PrepareCaravan_Pause : LordToil { public override void UpdateAllDuties() { - for (int i = 0; i < this.lord.ownedPawns.Count; i++) + for (int i = 0; i < base.lord.ownedPawns.Count; i++) { - this.lord.ownedPawns[i].mindState.duty = new PawnDuty(DutyDefOf.PrepareCaravan_Pause); + base.lord.ownedPawns[i].mindState.duty = new PawnDuty(DutyDefOf.PrepareCaravan_Pause); } } } diff --git a/Assembly-CSharp/RimWorld/LordToil_PrepareCaravan_Wait.cs b/Assembly-CSharp/RimWorld/LordToil_PrepareCaravan_Wait.cs index 10094df01..ddaba2f44 100644 --- a/Assembly-CSharp/RimWorld/LordToil_PrepareCaravan_Wait.cs +++ b/Assembly-CSharp/RimWorld/LordToil_PrepareCaravan_Wait.cs @@ -1,4 +1,3 @@ -using System; using Verse; using Verse.AI; using Verse.AI.Group; @@ -32,9 +31,9 @@ public LordToil_PrepareCaravan_Wait(IntVec3 meetingPoint) public override void UpdateAllDuties() { - for (int i = 0; i < this.lord.ownedPawns.Count; i++) + for (int i = 0; i < base.lord.ownedPawns.Count; i++) { - this.lord.ownedPawns[i].mindState.duty = new PawnDuty(DutyDefOf.PrepareCaravan_Wait, this.meetingPoint, -1f); + base.lord.ownedPawns[i].mindState.duty = new PawnDuty(DutyDefOf.PrepareCaravan_Wait, this.meetingPoint, -1f); } } } diff --git a/Assembly-CSharp/RimWorld/LordToil_PrisonerEscape.cs b/Assembly-CSharp/RimWorld/LordToil_PrisonerEscape.cs index 50c69792b..625d0e43b 100644 --- a/Assembly-CSharp/RimWorld/LordToil_PrisonerEscape.cs +++ b/Assembly-CSharp/RimWorld/LordToil_PrisonerEscape.cs @@ -1,4 +1,3 @@ -using System; using Verse; using Verse.AI; using Verse.AI.Group; @@ -21,7 +20,7 @@ private LordToilData_Travel Data { get { - return (LordToilData_Travel)this.data; + return (LordToilData_Travel)base.data; } } @@ -50,9 +49,9 @@ public override void UpdateAllDuties() { LordToilData_Travel data = this.Data; Pawn leader = this.GetLeader(); - for (int i = 0; i < this.lord.ownedPawns.Count; i++) + for (int i = 0; i < base.lord.ownedPawns.Count; i++) { - Pawn pawn = this.lord.ownedPawns[i]; + Pawn pawn = base.lord.ownedPawns[i]; if (this.IsSapper(pawn)) { pawn.mindState.duty = new PawnDuty(DutyDefOf.PrisonerEscapeSapper, data.dest, -1f); @@ -63,7 +62,7 @@ public override void UpdateAllDuties() } else { - pawn.mindState.duty = new PawnDuty(DutyDefOf.PrisonerEscape, leader, 10f); + pawn.mindState.duty = new PawnDuty(DutyDefOf.PrisonerEscape, (Thing)leader, 10f); } } } @@ -71,27 +70,27 @@ public override void UpdateAllDuties() public override void LordToilTick() { base.LordToilTick(); - for (int i = 0; i < this.lord.ownedPawns.Count; i++) + for (int i = 0; i < base.lord.ownedPawns.Count; i++) { - Pawn pawn = this.lord.ownedPawns[i]; + Pawn pawn = base.lord.ownedPawns[i]; pawn.guilt.Notify_Guilty(); } } private Pawn GetLeader() { - for (int i = 0; i < this.lord.ownedPawns.Count; i++) + for (int i = 0; i < base.lord.ownedPawns.Count; i++) { - if (!this.lord.ownedPawns[i].Downed && this.IsSapper(this.lord.ownedPawns[i])) + if (!base.lord.ownedPawns[i].Downed && this.IsSapper(base.lord.ownedPawns[i])) { - return this.lord.ownedPawns[i]; + return base.lord.ownedPawns[i]; } } - for (int j = 0; j < this.lord.ownedPawns.Count; j++) + for (int j = 0; j < base.lord.ownedPawns.Count; j++) { - if (!this.lord.ownedPawns[j].Downed) + if (!base.lord.ownedPawns[j].Downed) { - return this.lord.ownedPawns[j]; + return base.lord.ownedPawns[j]; } } return null; diff --git a/Assembly-CSharp/RimWorld/LordToil_Siege.cs b/Assembly-CSharp/RimWorld/LordToil_Siege.cs index e18e270c9..6990cced3 100644 --- a/Assembly-CSharp/RimWorld/LordToil_Siege.cs +++ b/Assembly-CSharp/RimWorld/LordToil_Siege.cs @@ -46,7 +46,7 @@ private LordToilData_Siege Data { get { - return (LordToilData_Siege)this.data; + return (LordToilData_Siege)base.data; } } @@ -54,17 +54,26 @@ private IEnumerable Frames { get { - LordToil_Siege.<>c__Iterator68 <>c__Iterator = new LordToil_Siege.<>c__Iterator68(); - <>c__Iterator.<>f__this = this; - LordToil_Siege.<>c__Iterator68 expr_0E = <>c__Iterator; - expr_0E.$PC = -2; - return expr_0E; + LordToilData_Siege data = this.Data; + float radSquared = (float)((data.baseRadius + 10.0) * (data.baseRadius + 10.0)); + List framesList = base.Map.listerThings.ThingsInGroup(ThingRequestGroup.BuildingFrame); + if (framesList.Count != 0) + { + for (int i = 0; i < framesList.Count; i++) + { + Frame frame = (Frame)framesList[i]; + if (frame.Faction == base.lord.faction && (float)(frame.Position - data.siegeCenter).LengthHorizontalSquared < radSquared) + { + yield return frame; + } + } + } } } public LordToil_Siege(IntVec3 siegeCenter, float blueprintPoints) { - this.data = new LordToilData_Siege(); + base.data = new LordToilData_Siege(); this.Data.siegeCenter = siegeCenter; this.Data.blueprintPoints = blueprintPoints; } @@ -73,27 +82,37 @@ public override void Init() { base.Init(); LordToilData_Siege data = this.Data; - data.baseRadius = Mathf.InverseLerp(14f, 25f, (float)this.lord.ownedPawns.Count / 50f); + data.baseRadius = Mathf.InverseLerp(14f, 25f, (float)((float)base.lord.ownedPawns.Count / 50.0)); data.baseRadius = Mathf.Clamp(data.baseRadius, 14f, 25f); List list = new List(); - foreach (Blueprint_Build current in SiegeBlueprintPlacer.PlaceBlueprints(data.siegeCenter, base.Map, this.lord.faction, data.blueprintPoints)) + foreach (Blueprint_Build item2 in SiegeBlueprintPlacer.PlaceBlueprints(data.siegeCenter, base.Map, base.lord.faction, data.blueprintPoints)) { - data.blueprints.Add(current); - foreach (ThingCountClass cost in current.MaterialsNeeded()) + data.blueprints.Add(item2); + List.Enumerator enumerator2 = item2.MaterialsNeeded().GetEnumerator(); + try { - Thing thing = list.FirstOrDefault((Thing t) => t.def == cost.thingDef); - if (thing != null) - { - thing.stackCount += cost.count; - } - else + ThingCountClass cost; + while (enumerator2.MoveNext()) { - Thing thing2 = ThingMaker.MakeThing(cost.thingDef, null); - thing2.stackCount = cost.count; - list.Add(thing2); + cost = enumerator2.Current; + Thing thing = list.FirstOrDefault((Func)((Thing t) => t.def == cost.thingDef)); + if (thing != null) + { + thing.stackCount += cost.count; + } + else + { + Thing thing2 = ThingMaker.MakeThing(cost.thingDef, null); + thing2.stackCount = cost.count; + list.Add(thing2); + } } } - ThingDef thingDef = current.def.entityDefToBuild as ThingDef; + finally + { + ((IDisposable)(object)enumerator2).Dispose(); + } + ThingDef thingDef = item2.def.entityDefToBuild as ThingDef; if (thingDef != null && thingDef.building != null && thingDef.building.turretShellDef != null) { Thing thing3 = ThingMaker.MakeThing(thingDef.building.turretShellDef, null); @@ -128,8 +147,8 @@ public override void Init() } } List list4 = new List(); - int num2 = Mathf.RoundToInt(LordToil_Siege.MealCountRangePerRaider.RandomInRange * (float)this.lord.ownedPawns.Count); - for (int l = 0; l < num2; l++) + int num2 = Mathf.RoundToInt(LordToil_Siege.MealCountRangePerRaider.RandomInRange * (float)base.lord.ownedPawns.Count); + for (int num3 = 0; num3 < num2; num3++) { Thing item = ThingMaker.MakeThing(ThingDefOf.MealSurvivalPack, null); list4.Add(item); @@ -142,32 +161,32 @@ public override void Init() public override void UpdateAllDuties() { LordToilData_Siege data = this.Data; - if (this.lord.ticksInToil < 450) + if (base.lord.ticksInToil < 450) { - for (int i = 0; i < this.lord.ownedPawns.Count; i++) + for (int i = 0; i < base.lord.ownedPawns.Count; i++) { - this.SetAsDefender(this.lord.ownedPawns[i]); + this.SetAsDefender(base.lord.ownedPawns[i]); } } else { this.rememberedDuties.Clear(); - int num = Mathf.RoundToInt((float)this.lord.ownedPawns.Count * data.desiredBuilderFraction); + int num = Mathf.RoundToInt((float)base.lord.ownedPawns.Count * data.desiredBuilderFraction); if (num <= 0) { num = 1; } int num2 = (from b in base.Map.listerThings.ThingsInGroup(ThingRequestGroup.BuildingArtificial) - where b.def.hasInteractionCell && b.Faction == this.lord.faction && b.Position.InHorDistOf(this.FlagLoc, data.baseRadius) - select b).Count(); + where b.def.hasInteractionCell && b.Faction == base.lord.faction && b.Position.InHorDistOf(this.FlagLoc, data.baseRadius) + select b).Count(); if (num < num2) { num = num2; } int num3 = 0; - for (int j = 0; j < this.lord.ownedPawns.Count; j++) + for (int j = 0; j < base.lord.ownedPawns.Count; j++) { - Pawn pawn = this.lord.ownedPawns[j]; + Pawn pawn = base.lord.ownedPawns[j]; if (pawn.mindState.duty.def == DutyDefOf.Build) { this.rememberedDuties.Add(pawn, DutyDefOf.Build); @@ -176,21 +195,21 @@ public override void UpdateAllDuties() } } int num4 = num - num3; - for (int k = 0; k < num4; k++) + for (int num5 = 0; num5 < num4; num5++) { - Pawn pawn2; - if ((from pa in this.lord.ownedPawns + Pawn pawn2 = default(Pawn); + if ((from pa in base.lord.ownedPawns where !this.rememberedDuties.ContainsKey(pa) && this.CanBeBuilder(pa) - select pa).TryRandomElement(out pawn2)) + select pa).TryRandomElement(out pawn2)) { this.rememberedDuties.Add(pawn2, DutyDefOf.Build); this.SetAsBuilder(pawn2); num3++; } } - for (int l = 0; l < this.lord.ownedPawns.Count; l++) + for (int k = 0; k < base.lord.ownedPawns.Count; k++) { - Pawn pawn3 = this.lord.ownedPawns[l]; + Pawn pawn3 = base.lord.ownedPawns[k]; if (!this.rememberedDuties.ContainsKey(pawn3)) { this.SetAsDefender(pawn3); @@ -199,8 +218,7 @@ public override void UpdateAllDuties() } if (num3 == 0) { - this.lord.ReceiveMemo("NoBuilders"); - return; + base.lord.ReceiveMemo("NoBuilders"); } } } @@ -214,7 +232,7 @@ public override void Notify_PawnLost(Pawn victim, PawnLostCondition cond) public override void Notify_ConstructionFailed(Pawn pawn, Frame frame, Blueprint_Build newBlueprint) { base.Notify_ConstructionFailed(pawn, frame, newBlueprint); - if (frame.Faction == this.lord.faction && newBlueprint != null) + if (frame.Faction == base.lord.faction && newBlueprint != null) { this.Data.blueprints.Add(newBlueprint); } @@ -222,7 +240,11 @@ public override void Notify_ConstructionFailed(Pawn pawn, Frame frame, Blueprint private bool CanBeBuilder(Pawn p) { - return !p.story.WorkTypeIsDisabled(WorkTypeDefOf.Construction) && !p.story.WorkTypeIsDisabled(WorkTypeDefOf.Firefighter); + if (!p.story.WorkTypeIsDisabled(WorkTypeDefOf.Construction) && !p.story.WorkTypeIsDisabled(WorkTypeDefOf.Firefighter)) + { + return true; + } + return false; } private void SetAsBuilder(Pawn p) @@ -257,11 +279,11 @@ public override void LordToilTick() { base.LordToilTick(); LordToilData_Siege data = this.Data; - if (this.lord.ticksInToil == 450) + if (base.lord.ticksInToil == 450) { - this.lord.CurLordToil.UpdateAllDuties(); + base.lord.CurLordToil.UpdateAllDuties(); } - if (this.lord.ticksInToil > 450 && this.lord.ticksInToil % 500 == 0) + if (base.lord.ticksInToil > 450 && base.lord.ticksInToil % 500 == 0) { this.UpdateAllDuties(); } @@ -269,45 +291,44 @@ public override void LordToilTick() { if (!(from frame in this.Frames where !frame.Destroyed - select frame).Any()) + select frame).Any() && !(from blue in data.blueprints + where !blue.Destroyed + select blue).Any() && !base.Map.listerThings.ThingsInGroup(ThingRequestGroup.BuildingArtificial).Any((Predicate)((Thing b) => b.Faction == base.lord.faction && b.def.building.buildingTags.Contains("Artillery")))) { - if (!(from blue in data.blueprints - where !blue.Destroyed - select blue).Any() && !base.Map.listerThings.ThingsInGroup(ThingRequestGroup.BuildingArtificial).Any((Thing b) => b.Faction == this.lord.faction && b.def.building.buildingTags.Contains("Artillery"))) - { - this.lord.ReceiveMemo("NoArtillery"); - return; - } + base.lord.ReceiveMemo("NoArtillery"); } - int num = GenRadial.NumCellsInRadius(20f); - int num2 = 0; - int num3 = 0; - for (int i = 0; i < num; i++) + else { - IntVec3 c = data.siegeCenter + GenRadial.RadialPattern[i]; - if (c.InBounds(base.Map)) + int num = GenRadial.NumCellsInRadius(20f); + int num2 = 0; + int num3 = 0; + for (int num4 = 0; num4 < num; num4++) { - List thingList = c.GetThingList(base.Map); - for (int j = 0; j < thingList.Count; j++) + IntVec3 c = data.siegeCenter + GenRadial.RadialPattern[num4]; + if (c.InBounds(base.Map)) { - if (thingList[j].def == ThingDefOf.MortarShell) - { - num2 += thingList[j].stackCount; - } - if (thingList[j].def == ThingDefOf.MealSurvivalPack) + List thingList = c.GetThingList(base.Map); + for (int i = 0; i < thingList.Count; i++) { - num3 += thingList[j].stackCount; + if (thingList[i].def == ThingDefOf.MortarShell) + { + num2 += thingList[i].stackCount; + } + if (thingList[i].def == ThingDefOf.MealSurvivalPack) + { + num3 += thingList[i].stackCount; + } } } } - } - if (num2 < 4) - { - this.DropSupplies(ThingDefOf.MortarShell, 10); - } - if (num3 < 5) - { - this.DropSupplies(ThingDefOf.MealSurvivalPack, 12); + if (num2 < 4) + { + this.DropSupplies(ThingDefOf.MortarShell, 10); + } + if (num3 < 5) + { + this.DropSupplies(ThingDefOf.MealSurvivalPack, 12); + } } } } @@ -324,14 +345,23 @@ private void DropSupplies(ThingDef thingDef, int count) public override void Cleanup() { LordToilData_Siege data = this.Data; - data.blueprints.RemoveAll((Blueprint blue) => blue.Destroyed); + data.blueprints.RemoveAll((Predicate)((Blueprint blue) => blue.Destroyed)); for (int i = 0; i < data.blueprints.Count; i++) { data.blueprints[i].Destroy(DestroyMode.Cancel); } - foreach (Frame current in this.Frames.ToList()) + List.Enumerator enumerator = this.Frames.ToList().GetEnumerator(); + try + { + while (enumerator.MoveNext()) + { + Frame current = enumerator.Current; + current.Destroy(DestroyMode.Cancel); + } + } + finally { - current.Destroy(DestroyMode.Cancel); + ((IDisposable)(object)enumerator).Dispose(); } } } diff --git a/Assembly-CSharp/RimWorld/LordToil_Stage.cs b/Assembly-CSharp/RimWorld/LordToil_Stage.cs index ad4d159df..08d6b54db 100644 --- a/Assembly-CSharp/RimWorld/LordToil_Stage.cs +++ b/Assembly-CSharp/RimWorld/LordToil_Stage.cs @@ -1,4 +1,3 @@ -using System; using Verse; using Verse.AI; using Verse.AI.Group; @@ -19,23 +18,23 @@ private LordToilData_Stage Data { get { - return (LordToilData_Stage)this.data; + return (LordToilData_Stage)base.data; } } public LordToil_Stage(IntVec3 stagingLoc) { - this.data = new LordToilData_Stage(); + base.data = new LordToilData_Stage(); this.Data.stagingPoint = stagingLoc; } public override void UpdateAllDuties() { LordToilData_Stage data = this.Data; - for (int i = 0; i < this.lord.ownedPawns.Count; i++) + for (int i = 0; i < base.lord.ownedPawns.Count; i++) { - this.lord.ownedPawns[i].mindState.duty = new PawnDuty(DutyDefOf.Defend, data.stagingPoint, -1f); - this.lord.ownedPawns[i].mindState.duty.radius = 28f; + base.lord.ownedPawns[i].mindState.duty = new PawnDuty(DutyDefOf.Defend, data.stagingPoint, -1f); + base.lord.ownedPawns[i].mindState.duty.radius = 28f; } } } diff --git a/Assembly-CSharp/RimWorld/LordToil_StealCover.cs b/Assembly-CSharp/RimWorld/LordToil_StealCover.cs index e58110a4e..70407f37b 100644 --- a/Assembly-CSharp/RimWorld/LordToil_StealCover.cs +++ b/Assembly-CSharp/RimWorld/LordToil_StealCover.cs @@ -1,4 +1,3 @@ -using System; using System.Collections.Generic; using Verse; using Verse.AI; diff --git a/Assembly-CSharp/RimWorld/LordToil_TakeWoundedGuest.cs b/Assembly-CSharp/RimWorld/LordToil_TakeWoundedGuest.cs index e749505cf..9d596f631 100644 --- a/Assembly-CSharp/RimWorld/LordToil_TakeWoundedGuest.cs +++ b/Assembly-CSharp/RimWorld/LordToil_TakeWoundedGuest.cs @@ -1,4 +1,3 @@ -using System; using Verse.AI; using Verse.AI.Group; @@ -16,9 +15,9 @@ public override bool AllowSatisfyLongNeeds public override void UpdateAllDuties() { - for (int i = 0; i < this.lord.ownedPawns.Count; i++) + for (int i = 0; i < base.lord.ownedPawns.Count; i++) { - this.lord.ownedPawns[i].mindState.duty = new PawnDuty(DutyDefOf.TakeWoundedGuest); + base.lord.ownedPawns[i].mindState.duty = new PawnDuty(DutyDefOf.TakeWoundedGuest); } } } diff --git a/Assembly-CSharp/RimWorld/LovePartnerRelationUtility.cs b/Assembly-CSharp/RimWorld/LovePartnerRelationUtility.cs index b291959c0..9d1bc57c4 100644 --- a/Assembly-CSharp/RimWorld/LovePartnerRelationUtility.cs +++ b/Assembly-CSharp/RimWorld/LovePartnerRelationUtility.cs @@ -28,22 +28,22 @@ public static bool IsExLovePartnerRelation(PawnRelationDef relation) public static bool HasAnyLovePartnerOfTheSameGender(Pawn pawn) { - return pawn.relations.DirectRelations.Find((DirectPawnRelation x) => LovePartnerRelationUtility.IsLovePartnerRelation(x.def) && x.otherPawn.gender == pawn.gender) != null; + return pawn.relations.DirectRelations.Find((Predicate)((DirectPawnRelation x) => LovePartnerRelationUtility.IsLovePartnerRelation(x.def) && x.otherPawn.gender == pawn.gender)) != null; } public static bool HasAnyExLovePartnerOfTheSameGender(Pawn pawn) { - return pawn.relations.DirectRelations.Find((DirectPawnRelation x) => LovePartnerRelationUtility.IsExLovePartnerRelation(x.def) && x.otherPawn.gender == pawn.gender) != null; + return pawn.relations.DirectRelations.Find((Predicate)((DirectPawnRelation x) => LovePartnerRelationUtility.IsExLovePartnerRelation(x.def) && x.otherPawn.gender == pawn.gender)) != null; } public static bool HasAnyLovePartnerOfTheOppositeGender(Pawn pawn) { - return pawn.relations.DirectRelations.Find((DirectPawnRelation x) => LovePartnerRelationUtility.IsLovePartnerRelation(x.def) && x.otherPawn.gender != pawn.gender) != null; + return pawn.relations.DirectRelations.Find((Predicate)((DirectPawnRelation x) => LovePartnerRelationUtility.IsLovePartnerRelation(x.def) && x.otherPawn.gender != pawn.gender)) != null; } public static bool HasAnyExLovePartnerOfTheOppositeGender(Pawn pawn) { - return pawn.relations.DirectRelations.Find((DirectPawnRelation x) => LovePartnerRelationUtility.IsExLovePartnerRelation(x.def) && x.otherPawn.gender != pawn.gender) != null; + return pawn.relations.DirectRelations.Find((Predicate)((DirectPawnRelation x) => LovePartnerRelationUtility.IsExLovePartnerRelation(x.def) && x.otherPawn.gender != pawn.gender)) != null; } public static Pawn ExistingLovePartner(Pawn pawn) @@ -78,46 +78,35 @@ public static bool ExLovePartnerRelationExists(Pawn first, Pawn second) public static void GiveRandomExLoverOrExSpouseRelation(Pawn first, Pawn second) { - PawnRelationDef def; - if (Rand.Value < 0.5f) - { - def = PawnRelationDefOf.ExLover; - } - else - { - def = PawnRelationDefOf.ExSpouse; - } + PawnRelationDef def = (!(Rand.Value < 0.5)) ? PawnRelationDefOf.ExSpouse : PawnRelationDefOf.ExLover; first.relations.AddDirectRelation(def, second); } public static Pawn GetPartnerInMyBed(Pawn pawn) { - if (pawn.CurJob == null || pawn.jobs.curDriver.layingDown == LayingDownState.NotLaying) + if (((pawn.CurJob != null) ? pawn.jobs.curDriver.layingDown : LayingDownState.NotLaying) != 0) { - return null; - } - Building_Bed building_Bed = pawn.CurrentBed(); - if (building_Bed == null) - { - return null; - } - if (building_Bed.SleepingSlotsCount <= 1) - { - return null; - } - if (!LovePartnerRelationUtility.HasAnyLovePartner(pawn)) - { - return null; - } - foreach (Pawn current in building_Bed.CurOccupants) - { - if (current != pawn) + Building_Bed building_Bed = pawn.CurrentBed(); + if (building_Bed == null) + { + return null; + } + if (building_Bed.SleepingSlotsCount <= 1) + { + return null; + } + if (!LovePartnerRelationUtility.HasAnyLovePartner(pawn)) + { + return null; + } + foreach (Pawn curOccupant in building_Bed.CurOccupants) { - if (LovePartnerRelationUtility.LovePartnerRelationExists(pawn, current)) + if (curOccupant != pawn && LovePartnerRelationUtility.LovePartnerRelationExists(pawn, curOccupant)) { - return current; + return curOccupant; } } + return null; } return null; } @@ -143,16 +132,13 @@ public static DirectPawnRelation ExistingMostLikedLovePartnerRel(Pawn p, bool al List directRelations = p.relations.DirectRelations; for (int i = 0; i < directRelations.Count; i++) { - if (allowDead || !directRelations[i].otherPawn.Dead) + if ((allowDead || !directRelations[i].otherPawn.Dead) && LovePartnerRelationUtility.IsLovePartnerRelation(directRelations[i].def)) { - if (LovePartnerRelationUtility.IsLovePartnerRelation(directRelations[i].def)) + int num2 = p.relations.OpinionOf(directRelations[i].otherPawn); + if (directPawnRelation == null || num2 > num) { - int num2 = p.relations.OpinionOf(directRelations[i].otherPawn); - if (directPawnRelation == null || num2 > num) - { - directPawnRelation = directRelations[i]; - num = num2; - } + directPawnRelation = directRelations[i]; + num = num2; } } } @@ -161,60 +147,59 @@ public static DirectPawnRelation ExistingMostLikedLovePartnerRel(Pawn p, bool al public static float GetLovinMtbHours(Pawn pawn, Pawn partner) { - if (pawn.Dead || partner.Dead) - { - return -1f; - } - if (DebugSettings.alwaysDoLovin) - { - return 0.1f; - } - if (pawn.needs.food.Starving || partner.needs.food.Starving) - { - return -1f; - } - if (pawn.health.hediffSet.BleedRateTotal > 0f || partner.health.hediffSet.BleedRateTotal > 0f) - { - return -1f; - } - float num = LovePartnerRelationUtility.LovinMtbSinglePawnFactor(pawn); - if (num <= 0f) - { - return -1f; - } - float num2 = LovePartnerRelationUtility.LovinMtbSinglePawnFactor(partner); - if (num2 <= 0f) + if (!pawn.Dead && !partner.Dead) { + if (DebugSettings.alwaysDoLovin) + { + return 0.1f; + } + if (!pawn.needs.food.Starving && !partner.needs.food.Starving) + { + if (!(pawn.health.hediffSet.BleedRateTotal > 0.0) && !(partner.health.hediffSet.BleedRateTotal > 0.0)) + { + float num = LovePartnerRelationUtility.LovinMtbSinglePawnFactor(pawn); + if (num <= 0.0) + { + return -1f; + } + float num2 = LovePartnerRelationUtility.LovinMtbSinglePawnFactor(partner); + if (num2 <= 0.0) + { + return -1f; + } + float num3 = 12f; + num3 *= num; + num3 *= num2; + num3 /= Mathf.Max(pawn.relations.SecondaryRomanceChanceFactor(partner), 0.1f); + num3 /= Mathf.Max(partner.relations.SecondaryRomanceChanceFactor(pawn), 0.1f); + num3 *= GenMath.LerpDouble(-100f, 100f, 1.3f, 0.7f, (float)pawn.relations.OpinionOf(partner)); + return num3 * GenMath.LerpDouble(-100f, 100f, 1.3f, 0.7f, (float)partner.relations.OpinionOf(pawn)); + } + return -1f; + } return -1f; } - float num3 = 12f; - num3 *= num; - num3 *= num2; - num3 /= Mathf.Max(pawn.relations.SecondaryRomanceChanceFactor(partner), 0.1f); - num3 /= Mathf.Max(partner.relations.SecondaryRomanceChanceFactor(pawn), 0.1f); - num3 *= GenMath.LerpDouble(-100f, 100f, 1.3f, 0.7f, (float)pawn.relations.OpinionOf(partner)); - return num3 * GenMath.LerpDouble(-100f, 100f, 1.3f, 0.7f, (float)partner.relations.OpinionOf(pawn)); + return -1f; } private static float LovinMtbSinglePawnFactor(Pawn pawn) { float num = 1f; - num /= 1f - pawn.health.hediffSet.PainTotal; + num = (float)(num / (1.0 - pawn.health.hediffSet.PainTotal)); float level = pawn.health.capacities.GetLevel(PawnCapacityDefOf.Consciousness); - if (level < 0.5f) + if (level < 0.5) { - num /= level * 2f; + num = (float)(num / (level * 2.0)); } return num / GenMath.FlatHill(0f, 14f, 16f, 25f, 80f, 0.2f, pawn.ageTracker.AgeBiologicalYearsFloat); } public static void TryToShareBed(Pawn first, Pawn second) { - if (LovePartnerRelationUtility.TryToShareBed_Int(first, second)) + if (!LovePartnerRelationUtility.TryToShareBed_Int(first, second)) { - return; + LovePartnerRelationUtility.TryToShareBed_Int(second, first); } - LovePartnerRelationUtility.TryToShareBed_Int(second, first); } private static bool TryToShareBed_Int(Pawn bedOwner, Pawn otherPawn) @@ -230,11 +215,11 @@ private static bool TryToShareBed_Int(Pawn bedOwner, Pawn otherPawn) public static float LovePartnerRelationGenerationChance(Pawn generated, Pawn other, PawnGenerationRequest request, bool ex) { - if (generated.ageTracker.AgeBiologicalYearsFloat < 14f) + if (generated.ageTracker.AgeBiologicalYearsFloat < 14.0) { return 0f; } - if (other.ageTracker.AgeBiologicalYearsFloat < 14f) + if (other.ageTracker.AgeBiologicalYearsFloat < 14.0) { return 0f; } @@ -264,24 +249,17 @@ public static float LovePartnerRelationGenerationChance(Pawn generated, Pawn oth { return 0f; } - float num3 = (generated.gender != other.gender) ? 1f : 0.01f; + float num3 = (float)((generated.gender != other.gender) ? 1.0 : 0.0099999997764825821); float generationChanceAgeFactor = LovePartnerRelationUtility.GetGenerationChanceAgeFactor(generated); float generationChanceAgeFactor2 = LovePartnerRelationUtility.GetGenerationChanceAgeFactor(other); float generationChanceAgeGapFactor = LovePartnerRelationUtility.GetGenerationChanceAgeGapFactor(generated, other, ex); float num4 = 1f; - if (generated.GetRelations(other).Any((PawnRelationDef x) => x.familyByBloodRelation)) + if (generated.GetRelations(other).Any((Func)((PawnRelationDef x) => x.familyByBloodRelation))) { num4 = 0.01f; } - float num5; - if (request.FixedMelanin.HasValue) - { - num5 = ChildRelationUtility.GetMelaninSimilarityFactor(request.FixedMelanin.Value, other.story.melanin); - } - else - { - num5 = PawnSkinColors.GetMelaninCommonalityFactor(other.story.melanin); - } + float num5 = 1f; + num5 = ((!request.FixedMelanin.HasValue) ? PawnSkinColors.GetMelaninCommonalityFactor(other.story.melanin) : ChildRelationUtility.GetMelaninSimilarityFactor(request.FixedMelanin.Value, other.story.melanin)); return num * generationChanceAgeFactor * generationChanceAgeFactor2 * generationChanceAgeGapFactor * num3 * num5 * num4; } @@ -297,17 +275,17 @@ private static float GetGenerationChanceAgeGapFactor(Pawn p1, Pawn p2, bool ex) if (ex) { float num2 = LovePartnerRelationUtility.MinPossibleAgeGapAtMinAgeToGenerateAsLovers(p1, p2); - if (num2 >= 0f) + if (num2 >= 0.0) { num = Mathf.Min(num, num2); } float num3 = LovePartnerRelationUtility.MinPossibleAgeGapAtMinAgeToGenerateAsLovers(p2, p1); - if (num3 >= 0f) + if (num3 >= 0.0) { num = Mathf.Min(num, num3); } } - if (num > 40f) + if (num > 40.0) { return 0f; } @@ -317,58 +295,57 @@ private static float GetGenerationChanceAgeGapFactor(Pawn p1, Pawn p2, bool ex) private static float MinPossibleAgeGapAtMinAgeToGenerateAsLovers(Pawn p1, Pawn p2) { - float num = p1.ageTracker.AgeChronologicalYearsFloat - 14f; - if (num < 0f) + float num = (float)(p1.ageTracker.AgeChronologicalYearsFloat - 14.0); + if (num < 0.0) { Log.Warning("at < 0"); return 0f; } float num2 = PawnRelationUtility.MaxPossibleBioAgeAt(p2.ageTracker.AgeBiologicalYearsFloat, p2.ageTracker.AgeChronologicalYearsFloat, num); float num3 = PawnRelationUtility.MinPossibleBioAgeAt(p2.ageTracker.AgeBiologicalYearsFloat, num); - if (num2 < 0f) + if (num2 < 0.0) { return -1f; } - if (num2 < 14f) + if (num2 < 14.0) { return -1f; } - if (num3 <= 14f) + if (num3 <= 14.0) { return 0f; } - return num3 - 14f; + return (float)(num3 - 14.0); } public static void TryToShareChildrenForGeneratedLovePartner(Pawn generated, Pawn other, PawnGenerationRequest request, float extraChanceFactor) { - if (generated.gender == other.gender) - { - return; - } - List list = other.relations.Children.ToList(); - for (int i = 0; i < list.Count; i++) + if (generated.gender != other.gender) { - Pawn pawn = list[i]; - float num = 1f; - if (generated.gender == Gender.Male) - { - num = ChildRelationUtility.ChanceOfBecomingChildOf(pawn, generated, other, null, new PawnGenerationRequest?(request), null); - } - else if (generated.gender == Gender.Female) - { - num = ChildRelationUtility.ChanceOfBecomingChildOf(pawn, other, generated, null, null, new PawnGenerationRequest?(request)); - } - num *= extraChanceFactor; - if (Rand.Value < num) + List list = other.relations.Children.ToList(); + for (int i = 0; i < list.Count; i++) { + Pawn pawn = list[i]; + float num = 1f; if (generated.gender == Gender.Male) { - pawn.SetFather(generated); + num = ChildRelationUtility.ChanceOfBecomingChildOf(pawn, generated, other, default(PawnGenerationRequest?), new PawnGenerationRequest?(request), default(PawnGenerationRequest?)); } else if (generated.gender == Gender.Female) { - pawn.SetMother(generated); + num = ChildRelationUtility.ChanceOfBecomingChildOf(pawn, other, generated, default(PawnGenerationRequest?), default(PawnGenerationRequest?), new PawnGenerationRequest?(request)); + } + num *= extraChanceFactor; + if (Rand.Value < num) + { + if (generated.gender == Gender.Male) + { + pawn.SetFather(generated); + } + else if (generated.gender == Gender.Female) + { + pawn.SetMother(generated); + } } } } @@ -379,12 +356,13 @@ public static void ChangeSpouseRelationsToExSpouse(Pawn pawn) while (true) { Pawn firstDirectRelationPawn = pawn.relations.GetFirstDirectRelationPawn(PawnRelationDefOf.Spouse, null); - if (firstDirectRelationPawn == null) + if (firstDirectRelationPawn != null) { - break; + pawn.relations.RemoveDirectRelation(PawnRelationDefOf.Spouse, firstDirectRelationPawn); + pawn.relations.AddDirectRelation(PawnRelationDefOf.ExSpouse, firstDirectRelationPawn); + continue; } - pawn.relations.RemoveDirectRelation(PawnRelationDefOf.Spouse, firstDirectRelationPawn); - pawn.relations.AddDirectRelation(PawnRelationDefOf.ExSpouse, firstDirectRelationPawn); + break; } } @@ -399,16 +377,13 @@ public static Pawn GetMostDislikedNonPartnerBedOwner(Pawn p) int num = 0; for (int i = 0; i < ownedBed.owners.Count; i++) { - if (ownedBed.owners[i] != p) + if (ownedBed.owners[i] != p && !LovePartnerRelationUtility.LovePartnerRelationExists(p, ownedBed.owners[i])) { - if (!LovePartnerRelationUtility.LovePartnerRelationExists(p, ownedBed.owners[i])) + int num2 = p.relations.OpinionOf(ownedBed.owners[i]); + if (pawn == null || num2 < num) { - int num2 = p.relations.OpinionOf(ownedBed.owners[i]); - if (pawn == null || num2 < num) - { - pawn = ownedBed.owners[i]; - num = num2; - } + pawn = ownedBed.owners[i]; + num = num2; } } } @@ -421,20 +396,14 @@ public static float IncestOpinionOffsetFor(Pawn other, Pawn pawn) List directRelations = other.relations.DirectRelations; for (int i = 0; i < directRelations.Count; i++) { - if (LovePartnerRelationUtility.IsLovePartnerRelation(directRelations[i].def)) + if (LovePartnerRelationUtility.IsLovePartnerRelation(directRelations[i].def) && directRelations[i].otherPawn != pawn && !directRelations[i].otherPawn.Dead) { - if (directRelations[i].otherPawn != pawn) + foreach (PawnRelationDef relation in other.GetRelations(directRelations[i].otherPawn)) { - if (!directRelations[i].otherPawn.Dead) + float incestOpinionOffset = relation.incestOpinionOffset; + if (incestOpinionOffset < num) { - foreach (PawnRelationDef current in other.GetRelations(directRelations[i].otherPawn)) - { - float incestOpinionOffset = current.incestOpinionOffset; - if (incestOpinionOffset < num) - { - num = incestOpinionOffset; - } - } + num = incestOpinionOffset; } } } diff --git a/Assembly-CSharp/RimWorld/MTBByBiome.cs b/Assembly-CSharp/RimWorld/MTBByBiome.cs index f4b92c30e..778bbaeb8 100644 --- a/Assembly-CSharp/RimWorld/MTBByBiome.cs +++ b/Assembly-CSharp/RimWorld/MTBByBiome.cs @@ -1,4 +1,3 @@ -using System; using System.Xml; using Verse; @@ -15,10 +14,12 @@ public void LoadDataFromXmlCustom(XmlNode xmlRoot) if (xmlRoot.ChildNodes.Count != 1) { Log.Error("Misconfigured MTBByBiome: " + xmlRoot.OuterXml); - return; } - DirectXmlCrossRefLoader.RegisterObjectWantsCrossRef(this, "biome", xmlRoot.Name); - this.mtbDays = (float)ParseHelper.FromString(xmlRoot.FirstChild.Value, typeof(float)); + else + { + DirectXmlCrossRefLoader.RegisterObjectWantsCrossRef(this, "biome", xmlRoot.Name); + this.mtbDays = (float)ParseHelper.FromString(xmlRoot.FirstChild.Value, typeof(float)); + } } } } diff --git a/Assembly-CSharp/RimWorld/MainButtonDef.cs b/Assembly-CSharp/RimWorld/MainButtonDef.cs index 23d2ff716..2bbb14db4 100644 --- a/Assembly-CSharp/RimWorld/MainButtonDef.cs +++ b/Assembly-CSharp/RimWorld/MainButtonDef.cs @@ -66,7 +66,7 @@ public MainTabWindow TabWindow public override void PostLoad() { base.PostLoad(); - this.cachedHighlightTagClosed = "MainTab-" + this.defName + "-Closed"; + this.cachedHighlightTagClosed = "MainTab-" + base.defName + "-Closed"; } public void Notify_SwitchedMap() diff --git a/Assembly-CSharp/RimWorld/MainButtonDefOf.cs b/Assembly-CSharp/RimWorld/MainButtonDefOf.cs index 247678c4e..a15ad9617 100644 --- a/Assembly-CSharp/RimWorld/MainButtonDefOf.cs +++ b/Assembly-CSharp/RimWorld/MainButtonDefOf.cs @@ -1,5 +1,3 @@ -using System; - namespace RimWorld { [DefOf] diff --git a/Assembly-CSharp/RimWorld/MainButtonWorker.cs b/Assembly-CSharp/RimWorld/MainButtonWorker.cs index bdc1f9f06..7b13f42bc 100644 --- a/Assembly-CSharp/RimWorld/MainButtonWorker.cs +++ b/Assembly-CSharp/RimWorld/MainButtonWorker.cs @@ -1,4 +1,3 @@ -using System; using UnityEngine; using Verse; @@ -21,9 +20,7 @@ public virtual float ButtonBarPercent public virtual void InterfaceTryActivate() { if (TutorSystem.TutorialMode && this.def.canBeTutorDenied && Find.MainTabsRoot.OpenTab != this.def && !TutorSystem.AllowAction("MainTab-" + this.def.defName + "-Open")) - { return; - } this.Activate(); } @@ -38,22 +35,20 @@ public virtual void DoButton(Rect rect) { Event.current.Use(); } + return; } - else + SoundDef mouseoverCategory = SoundDefOf.MouseoverCategory; + if (Widgets.ButtonTextSubtle(rect, labelCap, this.ButtonBarPercent, -1f, mouseoverCategory)) { - SoundDef mouseoverCategory = SoundDefOf.MouseoverCategory; - if (Widgets.ButtonTextSubtle(rect, labelCap, this.ButtonBarPercent, -1f, mouseoverCategory)) - { - this.InterfaceTryActivate(); - } - if (Find.MainTabsRoot.OpenTab != this.def && !Find.WindowStack.NonImmediateDialogWindowOpen) - { - UIHighlighter.HighlightOpportunity(rect, this.def.cachedHighlightTagClosed); - } - if (!this.def.description.NullOrEmpty()) - { - TooltipHandler.TipRegion(rect, this.def.description); - } + this.InterfaceTryActivate(); + } + if (Find.MainTabsRoot.OpenTab != this.def && !Find.WindowStack.NonImmediateDialogWindowOpen) + { + UIHighlighter.HighlightOpportunity(rect, this.def.cachedHighlightTagClosed); + } + if (!this.def.description.NullOrEmpty()) + { + TooltipHandler.TipRegion(rect, this.def.description); } } } diff --git a/Assembly-CSharp/RimWorld/MainButtonWorker_ToggleResearchTab.cs b/Assembly-CSharp/RimWorld/MainButtonWorker_ToggleResearchTab.cs index ccdd95eca..89eae42fa 100644 --- a/Assembly-CSharp/RimWorld/MainButtonWorker_ToggleResearchTab.cs +++ b/Assembly-CSharp/RimWorld/MainButtonWorker_ToggleResearchTab.cs @@ -1,4 +1,3 @@ -using System; using Verse; namespace RimWorld diff --git a/Assembly-CSharp/RimWorld/MainButtonWorker_ToggleTab.cs b/Assembly-CSharp/RimWorld/MainButtonWorker_ToggleTab.cs index de6d25a2d..51e00e46f 100644 --- a/Assembly-CSharp/RimWorld/MainButtonWorker_ToggleTab.cs +++ b/Assembly-CSharp/RimWorld/MainButtonWorker_ToggleTab.cs @@ -1,4 +1,3 @@ -using System; using Verse; namespace RimWorld @@ -7,7 +6,7 @@ public class MainButtonWorker_ToggleTab : MainButtonWorker { public override void Activate() { - Find.MainTabsRoot.ToggleTab(this.def, true); + Find.MainTabsRoot.ToggleTab(base.def, true); } } } diff --git a/Assembly-CSharp/RimWorld/MainButtonWorker_ToggleWorld.cs b/Assembly-CSharp/RimWorld/MainButtonWorker_ToggleWorld.cs index 96743b72e..9d49d7f96 100644 --- a/Assembly-CSharp/RimWorld/MainButtonWorker_ToggleWorld.cs +++ b/Assembly-CSharp/RimWorld/MainButtonWorker_ToggleWorld.cs @@ -1,5 +1,4 @@ using RimWorld.Planet; -using System; using Verse; using Verse.Sound; diff --git a/Assembly-CSharp/RimWorld/MainButtonsRoot.cs b/Assembly-CSharp/RimWorld/MainButtonsRoot.cs index 06dee1678..8f66638f5 100644 --- a/Assembly-CSharp/RimWorld/MainButtonsRoot.cs +++ b/Assembly-CSharp/RimWorld/MainButtonsRoot.cs @@ -33,24 +33,28 @@ public MainButtonsRoot() { this.allButtonsInOrder = (from x in DefDatabase.AllDefs orderby x.order - select x).ToList(); + select x).ToList(); } public void MainButtonsOnGUI() { - if (Event.current.type == EventType.Layout) + if (Event.current.type != EventType.Layout) { - return; - } - this.DoButtons(); - for (int i = 0; i < this.allButtonsInOrder.Count; i++) - { - if ((this.allButtonsInOrder[i].validWithoutMap || Find.VisibleMap != null) && this.allButtonsInOrder[i].hotKey != null && this.allButtonsInOrder[i].hotKey.KeyDownEvent) + this.DoButtons(); + int num = 0; + while (true) { - Event.current.Use(); - this.allButtonsInOrder[i].Worker.InterfaceTryActivate(); - break; + if (num < this.allButtonsInOrder.Count) + { + if ((this.allButtonsInOrder[num].validWithoutMap || Find.VisibleMap != null) && this.allButtonsInOrder[num].hotKey != null && this.allButtonsInOrder[num].hotKey.KeyDownEvent) + break; + num++; + continue; + } + return; } + Event.current.Use(); + this.allButtonsInOrder[num].Worker.InterfaceTryActivate(); } } @@ -69,7 +73,7 @@ private void DoButtons() GUI.color = Color.white; int visibleButtonsCount = this.VisibleButtonsCount; int num = (int)((float)UI.screenWidth / (float)visibleButtonsCount); - int num2 = this.allButtonsInOrder.FindLastIndex((MainButtonDef x) => x.buttonVisible); + int num2 = this.allButtonsInOrder.FindLastIndex((Predicate)((MainButtonDef x) => x.buttonVisible)); int num3 = 0; for (int i = 0; i < this.allButtonsInOrder.Count; i++) { diff --git a/Assembly-CSharp/RimWorld/MainMenuDrawer.cs b/Assembly-CSharp/RimWorld/MainMenuDrawer.cs index b1f95d7b3..70dedb81b 100644 --- a/Assembly-CSharp/RimWorld/MainMenuDrawer.cs +++ b/Assembly-CSharp/RimWorld/MainMenuDrawer.cs @@ -1,6 +1,5 @@ using System; using System.Collections.Generic; -using System.IO; using System.Linq; using UnityEngine; using Verse; @@ -35,22 +34,33 @@ public static void Init() { PlayerKnowledgeDatabase.Save(); ShipCountdown.CancelCountdown(); - MainMenuDrawer.anyMapFiles = GenFilePaths.AllSavedGameFiles.Any(); + MainMenuDrawer.anyMapFiles = GenFilePaths.AllSavedGameFiles.Any(); } public static void MainMenuOnGUI() { VersionControl.DrawInfoInCorner(); - Rect rect = new Rect((float)(UI.screenWidth / 2) - MainMenuDrawer.PaneSize.x / 2f, (float)(UI.screenHeight / 2) - MainMenuDrawer.PaneSize.y / 2f + 50f, MainMenuDrawer.PaneSize.x, MainMenuDrawer.PaneSize.y); - rect.x = (float)UI.screenWidth - rect.width - 30f; - Rect rect2 = new Rect(0f, rect.y - 30f, (float)UI.screenWidth - 85f, 30f); + float num = (float)(UI.screenWidth / 2); + Vector2 paneSize = MainMenuDrawer.PaneSize; + double x = num - paneSize.x / 2.0; + float num2 = (float)(UI.screenHeight / 2); + Vector2 paneSize2 = MainMenuDrawer.PaneSize; + double y = num2 - paneSize2.y / 2.0 + 50.0; + Vector2 paneSize3 = MainMenuDrawer.PaneSize; + float x2 = paneSize3.x; + Vector2 paneSize4 = MainMenuDrawer.PaneSize; + Rect rect = new Rect((float)x, (float)y, x2, paneSize4.y); + rect.x = (float)((float)UI.screenWidth - rect.width - 30.0); + Rect rect2 = new Rect(0f, (float)(rect.y - 30.0), (float)((float)UI.screenWidth - 85.0), 30f); Text.Font = GameFont.Medium; Text.Anchor = TextAnchor.UpperRight; string text = "MainPageCredit".Translate(); if (UI.screenWidth < 990) { Rect position = rect2; - position.xMin = position.xMax - Text.CalcSize(text).x; + float xMax = position.xMax; + Vector2 vector = Text.CalcSize(text); + position.xMin = xMax - vector.x; position.xMin -= 4f; position.xMax += 4f; GUI.color = new Color(0.2f, 0.2f, 0.2f, 0.5f); @@ -66,10 +76,16 @@ public static void MainMenuOnGUI() a *= (float)UI.screenWidth / a.x; } a *= 0.7f; - Rect position2 = new Rect((float)UI.screenWidth - a.x - 50f, rect2.y - a.y, a.x, a.y); + Rect position2 = new Rect((float)((float)UI.screenWidth - a.x - 50.0), rect2.y - a.y, a.x, a.y); GUI.DrawTexture(position2, MainMenuDrawer.TexTitle, ScaleMode.StretchToFill, true); GUI.color = new Color(1f, 1f, 1f, 0.5f); - Rect position3 = new Rect((float)(UI.screenWidth - 8) - MainMenuDrawer.LudeonLogoSize.x, 8f, MainMenuDrawer.LudeonLogoSize.x, MainMenuDrawer.LudeonLogoSize.y); + float num3 = (float)(UI.screenWidth - 8); + Vector2 ludeonLogoSize = MainMenuDrawer.LudeonLogoSize; + float x3 = num3 - ludeonLogoSize.x; + Vector2 ludeonLogoSize2 = MainMenuDrawer.LudeonLogoSize; + float x4 = ludeonLogoSize2.x; + Vector2 ludeonLogoSize3 = MainMenuDrawer.LudeonLogoSize; + Rect position3 = new Rect(x3, 8f, x4, ludeonLogoSize3.y); GUI.DrawTexture(position3, MainMenuDrawer.TexLudeonLogo, ScaleMode.StretchToFill, true); GUI.color = Color.white; rect.yMin += 17f; @@ -80,57 +96,49 @@ public static void DoMainMenuControls(Rect rect, bool anyMapFiles) { GUI.BeginGroup(rect); Rect rect2 = new Rect(0f, 0f, 170f, rect.height); - Rect rect3 = new Rect(rect2.xMax + 17f, 0f, 145f, rect.height); + Rect rect3 = new Rect((float)(rect2.xMax + 17.0), 0f, 145f, rect.height); Text.Font = GameFont.Small; List list = new List(); if (Current.ProgramState == ProgramState.Entry) { - string label; - if (!"Tutorial".CanTranslate()) - { - label = "LearnToPlay".Translate(); - } - else - { - label = "Tutorial".Translate(); - } - list.Add(new ListableOption(label, delegate + string label = "Tutorial".CanTranslate() ? "Tutorial".Translate() : "LearnToPlay".Translate(); + list.Add(new ListableOption(label, (Action)delegate { MainMenuDrawer.InitLearnToPlay(); - }, null)); - list.Add(new ListableOption("NewColony".Translate(), delegate + }, (string)null)); + list.Add(new ListableOption("NewColony".Translate(), (Action)delegate { Find.WindowStack.Add(new Page_SelectScenario()); - }, null)); + }, (string)null)); } if (Current.ProgramState == ProgramState.Playing && !Current.Game.Info.permadeathMode) { - list.Add(new ListableOption("Save".Translate(), delegate + list.Add(new ListableOption("Save".Translate(), (Action)delegate { MainMenuDrawer.CloseMainTab(); Find.WindowStack.Add(new Dialog_SaveFileList_Save()); - }, null)); + }, (string)null)); } ListableOption item; if (anyMapFiles && (Current.ProgramState != ProgramState.Playing || !Current.Game.Info.permadeathMode)) { - item = new ListableOption("LoadGame".Translate(), delegate + item = new ListableOption("LoadGame".Translate(), (Action)delegate { MainMenuDrawer.CloseMainTab(); Find.WindowStack.Add(new Dialog_SaveFileList_Load()); - }, null); + }, (string)null); list.Add(item); } if (Current.ProgramState == ProgramState.Playing) { - list.Add(new ListableOption("ReviewScenario".Translate(), delegate + list.Add(new ListableOption("ReviewScenario".Translate(), (Action)delegate { - WindowStack arg_25_0 = Find.WindowStack; + WindowStack windowStack = Find.WindowStack; string name = Find.Scenario.name; - arg_25_0.Add(new Dialog_MessageBox(Find.Scenario.GetFullInformationText(), null, null, null, null, name, false)); - }, null)); + windowStack.Add(new Dialog_MessageBox(Find.Scenario.GetFullInformationText(), (string)null, null, (string)null, null, name, false)); + }, (string)null)); } - item = new ListableOption("Options".Translate(), delegate + item = new ListableOption("Options".Translate(), (Action)delegate { MainMenuDrawer.CloseMainTab(); Find.WindowStack.Add(new Dialog_Options()); @@ -138,85 +146,85 @@ public static void DoMainMenuControls(Rect rect, bool anyMapFiles) list.Add(item); if (Current.ProgramState == ProgramState.Entry) { - item = new ListableOption("Mods".Translate(), delegate + item = new ListableOption("Mods".Translate(), (Action)delegate { Find.WindowStack.Add(new Page_ModsConfig()); - }, null); + }, (string)null); list.Add(item); - item = new ListableOption("Credits".Translate(), delegate + item = new ListableOption("Credits".Translate(), (Action)delegate { Find.WindowStack.Add(new Screen_Credits()); - }, null); + }, (string)null); list.Add(item); } if (Current.ProgramState == ProgramState.Playing) { if (Current.Game.Info.permadeathMode) { - item = new ListableOption("SaveAndQuitToMainMenu".Translate(), delegate + item = new ListableOption("SaveAndQuitToMainMenu".Translate(), (Action)delegate { - LongEventHandler.QueueLongEvent(delegate + LongEventHandler.QueueLongEvent((Action)delegate { GameDataSaveLoader.SaveGame(Current.Game.Info.permadeathModeUniqueName); MemoryUtility.ClearAllMapsAndWorld(); }, "Entry", "SavingLongEvent", false, null); - }, null); + }, (string)null); list.Add(item); - item = new ListableOption("SaveAndQuitToOS".Translate(), delegate + item = new ListableOption("SaveAndQuitToOS".Translate(), (Action)delegate { - LongEventHandler.QueueLongEvent(delegate + LongEventHandler.QueueLongEvent((Action)delegate { GameDataSaveLoader.SaveGame(Current.Game.Info.permadeathModeUniqueName); - LongEventHandler.ExecuteWhenFinished(delegate + LongEventHandler.ExecuteWhenFinished((Action)delegate { Root.Shutdown(); }); }, "SavingLongEvent", false, null); - }, null); + }, (string)null); list.Add(item); } else { - Action action = delegate + Action action = (Action)delegate { if (GameDataSaveLoader.CurrentGameStateIsValuable) { - Find.WindowStack.Add(Dialog_MessageBox.CreateConfirmation("ConfirmQuit".Translate(), delegate + Find.WindowStack.Add(Dialog_MessageBox.CreateConfirmation("ConfirmQuit".Translate(), (Action)delegate { GenScene.GoToMainMenu(); - }, true, null)); + }, true, (string)null)); } else { GenScene.GoToMainMenu(); } }; - item = new ListableOption("QuitToMainMenu".Translate(), action, null); + item = new ListableOption("QuitToMainMenu".Translate(), action, (string)null); list.Add(item); - Action action2 = delegate + Action action2 = (Action)delegate { if (GameDataSaveLoader.CurrentGameStateIsValuable) { - Find.WindowStack.Add(Dialog_MessageBox.CreateConfirmation("ConfirmQuit".Translate(), delegate + Find.WindowStack.Add(Dialog_MessageBox.CreateConfirmation("ConfirmQuit".Translate(), (Action)delegate { Root.Shutdown(); - }, true, null)); + }, true, (string)null)); } else { Root.Shutdown(); } }; - item = new ListableOption("QuitToOS".Translate(), action2, null); + item = new ListableOption("QuitToOS".Translate(), action2, (string)null); list.Add(item); } } else { - item = new ListableOption("QuitToOS".Translate(), delegate + item = new ListableOption("QuitToOS".Translate(), (Action)delegate { Root.Shutdown(); - }, null); + }, (string)null); list.Add(item); } OptionListingUtility.DrawOptionListing(rect2, list); @@ -240,13 +248,13 @@ public static void DoMainMenuControls(Rect rect, bool anyMapFiles) list2.Add(item2); float num = OptionListingUtility.DrawOptionListing(rect3, list2); GUI.BeginGroup(rect3); - if (Current.ProgramState == ProgramState.Entry && Widgets.ButtonImage(new Rect(0f, num + 10f, 64f, 32f), LanguageDatabase.activeLanguage.icon)) + if (Current.ProgramState == ProgramState.Entry && Widgets.ButtonImage(new Rect(0f, (float)(num + 10.0), 64f, 32f), LanguageDatabase.activeLanguage.icon)) { List list3 = new List(); - foreach (LoadedLanguage current in LanguageDatabase.AllLoadedLanguages) + foreach (LoadedLanguage allLoadedLanguage in LanguageDatabase.AllLoadedLanguages) { - LoadedLanguage localLang = current; - list3.Add(new FloatMenuOption(localLang.FriendlyNameNative, delegate + LoadedLanguage localLang = allLoadedLanguage; + list3.Add(new FloatMenuOption(localLang.FriendlyNameNative, (Action)delegate { LanguageDatabase.SelectLanguage(localLang); Prefs.Save(); diff --git a/Assembly-CSharp/RimWorld/MainTabWindow.cs b/Assembly-CSharp/RimWorld/MainTabWindow.cs index 71581dbe5..93205111d 100644 --- a/Assembly-CSharp/RimWorld/MainTabWindow.cs +++ b/Assembly-CSharp/RimWorld/MainTabWindow.cs @@ -1,4 +1,3 @@ -using System; using UnityEngine; using Verse; @@ -43,13 +42,13 @@ public override Vector2 InitialSize public MainTabWindow() { - this.layer = WindowLayer.GameUI; - this.soundAppear = null; - this.soundClose = null; - this.doCloseButton = false; - this.doCloseX = false; - this.closeOnEscapeKey = true; - this.preventCameraMotion = false; + base.layer = WindowLayer.GameUI; + base.soundAppear = null; + base.soundClose = null; + base.doCloseButton = false; + base.doCloseX = false; + base.closeOnEscapeKey = true; + base.preventCameraMotion = false; } public override void DoWindowContents(Rect inRect) @@ -62,13 +61,13 @@ protected override void SetInitialSizeAndPosition() base.SetInitialSizeAndPosition(); if (this.Anchor == MainTabWindowAnchor.Left) { - this.windowRect.x = 0f; + base.windowRect.x = 0f; } else { - this.windowRect.x = (float)UI.screenWidth - this.windowRect.width; + base.windowRect.x = (float)UI.screenWidth - base.windowRect.width; } - this.windowRect.y = (float)(UI.screenHeight - 35) - this.windowRect.height; + base.windowRect.y = (float)(UI.screenHeight - 35) - base.windowRect.height; } } } diff --git a/Assembly-CSharp/RimWorld/MainTabWindowAnchor.cs b/Assembly-CSharp/RimWorld/MainTabWindowAnchor.cs index b05cabcd2..cb65ed8c1 100644 --- a/Assembly-CSharp/RimWorld/MainTabWindowAnchor.cs +++ b/Assembly-CSharp/RimWorld/MainTabWindowAnchor.cs @@ -1,10 +1,8 @@ -using System; - namespace RimWorld { public enum MainTabWindowAnchor { - Left, - Right + Left = 0, + Right = 1 } } diff --git a/Assembly-CSharp/RimWorld/MainTabWindow_Architect.cs b/Assembly-CSharp/RimWorld/MainTabWindow_Architect.cs index 5d30e1def..c2b152788 100644 --- a/Assembly-CSharp/RimWorld/MainTabWindow_Architect.cs +++ b/Assembly-CSharp/RimWorld/MainTabWindow_Architect.cs @@ -26,7 +26,7 @@ public float WinHeight { this.CacheDesPanels(); } - return (float)Mathf.CeilToInt((float)this.desPanelsCached.Count / 2f) * 32f; + return (float)((float)Mathf.CeilToInt((float)((float)this.desPanelsCached.Count / 2.0)) * 32.0); } } @@ -79,14 +79,14 @@ public override void DoWindowContents(Rect inRect) { base.DoWindowContents(inRect); Text.Font = GameFont.Small; - float num = inRect.width / 2f; + float num = (float)(inRect.width / 2.0); float num2 = 0f; float num3 = 0f; for (int i = 0; i < this.desPanelsCached.Count; i++) { - Rect rect = new Rect(num2 * num, num3 * 32f, num, 32f); + Rect rect = new Rect(num2 * num, (float)(num3 * 32.0), num, 32f); rect.height += 1f; - if (num2 == 0f) + if (num2 == 0.0) { rect.width += 1f; } @@ -98,11 +98,11 @@ public override void DoWindowContents(Rect inRect) { UIHighlighter.HighlightOpportunity(rect, this.desPanelsCached[i].def.cachedHighlightClosedTag); } - num2 += 1f; - if (num2 > 1f) + num2 = (float)(num2 + 1.0); + if (num2 > 1.0) { num2 = 0f; - num3 += 1f; + num3 = (float)(num3 + 1.0); } } } @@ -110,11 +110,11 @@ public override void DoWindowContents(Rect inRect) private void CacheDesPanels() { this.desPanelsCached = new List(); - foreach (DesignationCategoryDef current in from dc in DefDatabase.AllDefs + foreach (DesignationCategoryDef item in from dc in DefDatabase.AllDefs orderby dc.order descending select dc) { - this.desPanelsCached.Add(new ArchitectCategoryTab(current)); + this.desPanelsCached.Add(new ArchitectCategoryTab(item)); } } diff --git a/Assembly-CSharp/RimWorld/MainTabWindow_Assign.cs b/Assembly-CSharp/RimWorld/MainTabWindow_Assign.cs index 6d747f44c..c5972b3d8 100644 --- a/Assembly-CSharp/RimWorld/MainTabWindow_Assign.cs +++ b/Assembly-CSharp/RimWorld/MainTabWindow_Assign.cs @@ -1,5 +1,4 @@ using RimWorld.Planet; -using System; using Verse; namespace RimWorld diff --git a/Assembly-CSharp/RimWorld/MainTabWindow_Factions.cs b/Assembly-CSharp/RimWorld/MainTabWindow_Factions.cs index 97c2936db..e2fe64fbf 100644 --- a/Assembly-CSharp/RimWorld/MainTabWindow_Factions.cs +++ b/Assembly-CSharp/RimWorld/MainTabWindow_Factions.cs @@ -1,4 +1,3 @@ -using System; using UnityEngine; namespace RimWorld diff --git a/Assembly-CSharp/RimWorld/MainTabWindow_History.cs b/Assembly-CSharp/RimWorld/MainTabWindow_History.cs index dcf522056..7f4441645 100644 --- a/Assembly-CSharp/RimWorld/MainTabWindow_History.cs +++ b/Assembly-CSharp/RimWorld/MainTabWindow_History.cs @@ -11,11 +11,11 @@ public class MainTabWindow_History : MainTabWindow { private enum HistoryTab : byte { - Graph, - Statistics + Graph = 0, + Statistics = 1 } - private MainTabWindow_History.HistoryTab curTab; + private HistoryTab curTab; private HistoryAutoRecorderGroup historyAutoRecorderGroup; @@ -34,10 +34,10 @@ public override Vector2 RequestedTabSize public override void PreOpen() { base.PreOpen(); - this.historyAutoRecorderGroup = Find.History.Groups().FirstOrDefault(); + this.historyAutoRecorderGroup = Find.History.Groups().FirstOrDefault(); if (this.historyAutoRecorderGroup != null) { - this.graphSection = new Vector2(0f, (float)Find.TickManager.TicksGame / 60000f); + this.graphSection = new Vector2(0f, (float)((float)Find.TickManager.TicksGame / 60000.0)); } List maps = Find.Maps; for (int i = 0; i < maps.Count; i++) @@ -52,26 +52,27 @@ public override void DoWindowContents(Rect rect) Rect rect2 = rect; rect2.yMin += 45f; List list = new List(); - list.Add(new TabRecord("Graph".Translate(), delegate + list.Add(new TabRecord("Graph".Translate(), (Action)delegate { - this.curTab = MainTabWindow_History.HistoryTab.Graph; - }, this.curTab == MainTabWindow_History.HistoryTab.Graph)); - list.Add(new TabRecord("Statistics".Translate(), delegate + this.curTab = HistoryTab.Graph; + }, this.curTab == HistoryTab.Graph)); + list.Add(new TabRecord("Statistics".Translate(), (Action)delegate { - this.curTab = MainTabWindow_History.HistoryTab.Statistics; - }, this.curTab == MainTabWindow_History.HistoryTab.Statistics)); + this.curTab = HistoryTab.Statistics; + }, this.curTab == HistoryTab.Statistics)); TabDrawer.DrawTabs(rect2, list); - MainTabWindow_History.HistoryTab historyTab = this.curTab; - if (historyTab != MainTabWindow_History.HistoryTab.Graph) + switch (this.curTab) { - if (historyTab == MainTabWindow_History.HistoryTab.Statistics) - { - this.DoStatisticsPage(rect2); - } - } - else + case HistoryTab.Graph: { this.DoGraphPage(rect2); + break; + } + case HistoryTab.Statistics: + { + this.DoStatisticsPage(rect2); + break; + } } } @@ -81,22 +82,7 @@ private void DoStatisticsPage(Rect rect) GUI.BeginGroup(rect); StringBuilder stringBuilder = new StringBuilder(); TimeSpan timeSpan = new TimeSpan(0, 0, (int)Find.GameInfo.RealPlayTimeInteracting); - stringBuilder.AppendLine(string.Concat(new object[] - { - "Playtime".Translate(), - ": ", - timeSpan.Days, - "LetterDay".Translate(), - " ", - timeSpan.Hours, - "LetterHour".Translate(), - " ", - timeSpan.Minutes, - "LetterMinute".Translate(), - " ", - timeSpan.Seconds, - "LetterSecond".Translate() - })); + stringBuilder.AppendLine("Playtime".Translate() + ": " + timeSpan.Days + "LetterDay".Translate() + " " + timeSpan.Hours + "LetterHour".Translate() + " " + timeSpan.Minutes + "LetterMinute".Translate() + " " + timeSpan.Seconds + "LetterSecond".Translate()); stringBuilder.AppendLine("Storyteller".Translate() + ": " + Find.Storyteller.def.label); DifficultyDef difficulty = Find.Storyteller.difficulty; stringBuilder.AppendLine("Difficulty".Translate() + ": " + difficulty.label); @@ -130,7 +116,7 @@ private void DoGraphPage(Rect rect) rect.yMin += 17f; GUI.BeginGroup(rect); Rect graphRect = new Rect(0f, 0f, rect.width, 450f); - Rect legendRect = new Rect(0f, graphRect.yMax, rect.width / 2f, 40f); + Rect legendRect = new Rect(0f, graphRect.yMax, (float)(rect.width / 2.0), 40f); Rect rect2 = new Rect(0f, legendRect.yMax, rect.width, 40f); if (this.historyAutoRecorderGroup != null) { @@ -141,27 +127,27 @@ private void DoGraphPage(Rect rect) Tale tale = allTalesListForReading[i]; if (tale.def.type == TaleType.PermanentHistorical) { - float x = (float)GenDate.TickAbsToGame(tale.date) / 60000f; + float x = (float)((float)GenDate.TickAbsToGame(tale.date) / 60000.0); MainTabWindow_History.marks.Add(new CurveMark(x, tale.ShortSummary, tale.def.historyGraphColor)); } } this.historyAutoRecorderGroup.DrawGraph(graphRect, legendRect, this.graphSection, Find.History.curveDrawerStyle, MainTabWindow_History.marks); } Text.Font = GameFont.Small; - float num = (float)Find.TickManager.TicksGame / 60000f; + float num = (float)((float)Find.TickManager.TicksGame / 60000.0); if (Widgets.ButtonText(new Rect(legendRect.xMin + legendRect.width, legendRect.yMin, 110f, 40f), "Last30Days".Translate(), true, false, true)) { - this.graphSection = new Vector2(Mathf.Max(0f, num - 30f), num); + this.graphSection = new Vector2(Mathf.Max(0f, (float)(num - 30.0)), num); } - if (Widgets.ButtonText(new Rect(legendRect.xMin + legendRect.width + 110f + 4f, legendRect.yMin, 110f, 40f), "Last100Days".Translate(), true, false, true)) + if (Widgets.ButtonText(new Rect((float)(legendRect.xMin + legendRect.width + 110.0 + 4.0), legendRect.yMin, 110f, 40f), "Last100Days".Translate(), true, false, true)) { - this.graphSection = new Vector2(Mathf.Max(0f, num - 100f), num); + this.graphSection = new Vector2(Mathf.Max(0f, (float)(num - 100.0)), num); } - if (Widgets.ButtonText(new Rect(legendRect.xMin + legendRect.width + 228f, legendRect.yMin, 110f, 40f), "Last300Days".Translate(), true, false, true)) + if (Widgets.ButtonText(new Rect((float)(legendRect.xMin + legendRect.width + 228.0), legendRect.yMin, 110f, 40f), "Last300Days".Translate(), true, false, true)) { - this.graphSection = new Vector2(Mathf.Max(0f, num - 300f), num); + this.graphSection = new Vector2(Mathf.Max(0f, (float)(num - 300.0)), num); } - if (Widgets.ButtonText(new Rect(legendRect.xMin + legendRect.width + 342f, legendRect.yMin, 110f, 40f), "AllDays".Translate(), true, false, true)) + if (Widgets.ButtonText(new Rect((float)(legendRect.xMin + legendRect.width + 342.0), legendRect.yMin, 110f, 40f), "AllDays".Translate(), true, false, true)) { this.graphSection = new Vector2(0f, num); } @@ -172,7 +158,7 @@ private void DoGraphPage(Rect rect) for (int j = 0; j < list2.Count; j++) { HistoryAutoRecorderGroup groupLocal = list2[j]; - list.Add(new FloatMenuOption(groupLocal.def.LabelCap, delegate + list.Add(new FloatMenuOption(groupLocal.def.LabelCap, (Action)delegate { this.historyAutoRecorderGroup = groupLocal; }, MenuOptionPriority.Default, null, null, 0f, null, null)); diff --git a/Assembly-CSharp/RimWorld/MainTabWindow_Inspect.cs b/Assembly-CSharp/RimWorld/MainTabWindow_Inspect.cs index ea41417fd..b6437eefc 100644 --- a/Assembly-CSharp/RimWorld/MainTabWindow_Inspect.cs +++ b/Assembly-CSharp/RimWorld/MainTabWindow_Inspect.cs @@ -91,7 +91,9 @@ public float PaneTopY { get { - return (float)UI.screenHeight - InspectPaneUtility.PaneSize.y - 35f; + float num = (float)UI.screenHeight; + Vector2 paneSize = InspectPaneUtility.PaneSize; + return (float)(num - paneSize.y - 35.0); } } @@ -140,7 +142,7 @@ public IEnumerable CurTabs public MainTabWindow_Inspect() { - this.closeOnEscapeKey = false; + base.closeOnEscapeKey = false; } public override void ExtraOnGUI() @@ -181,12 +183,12 @@ public void DoInspectPaneButtons(Rect rect, ref float lineEndWidth) Thing singleSelectedThing = Find.Selector.SingleSelectedThing; if (singleSelectedThing != null) { - Widgets.InfoCardButton(rect.width - 48f, 0f, Find.Selector.SingleSelectedThing); + Widgets.InfoCardButton((float)(rect.width - 48.0), 0f, Find.Selector.SingleSelectedThing); lineEndWidth += 24f; Pawn pawn = singleSelectedThing as Pawn; if (pawn != null && pawn.playerSettings != null && pawn.playerSettings.UsesConfigurableHostilityResponse) { - HostilityResponseModeUtility.DrawResponseButton(new Vector2(rect.width - 72f, 0f), pawn); + HostilityResponseModeUtility.DrawResponseButton(new Vector2((float)(rect.width - 72.0), 0f), pawn); lineEndWidth += 24f; } } @@ -195,26 +197,16 @@ public void DoInspectPaneButtons(Rect rect, ref float lineEndWidth) public void SelectNextInCell() { - if (this.NumSelected == 0) - { - return; - } - Selector selector = Find.Selector; - if (selector.SelectedZone == null || selector.SelectedZone.ContainsCell(MainTabWindow_Inspect.lastSelectCell)) + if (this.NumSelected != 0) { + Selector selector = Find.Selector; + if (selector.SelectedZone != null && !selector.SelectedZone.ContainsCell(MainTabWindow_Inspect.lastSelectCell)) + return; if (selector.SelectedZone == null) { MainTabWindow_Inspect.lastSelectCell = selector.SingleSelectedThing.Position; } - Map map; - if (selector.SingleSelectedThing != null) - { - map = selector.SingleSelectedThing.Map; - } - else - { - map = selector.SelectedZone.Map; - } + Map map = (selector.SingleSelectedThing == null) ? selector.SelectedZone.Map : selector.SingleSelectedThing.Map; selector.SelectNextAt(MainTabWindow_Inspect.lastSelectCell, map); } } diff --git a/Assembly-CSharp/RimWorld/MainTabWindow_Menu.cs b/Assembly-CSharp/RimWorld/MainTabWindow_Menu.cs index 27df2eaa2..716b6bcc0 100644 --- a/Assembly-CSharp/RimWorld/MainTabWindow_Menu.cs +++ b/Assembly-CSharp/RimWorld/MainTabWindow_Menu.cs @@ -1,5 +1,3 @@ -using System; -using System.IO; using System.Linq; using UnityEngine; using Verse; @@ -28,7 +26,7 @@ public override MainTabWindowAnchor Anchor public MainTabWindow_Menu() { - this.forcePause = true; + base.forcePause = true; } public override void PreOpen() @@ -36,7 +34,7 @@ public override void PreOpen() base.PreOpen(); PlayerKnowledgeDatabase.Save(); ShipCountdown.CancelCountdown(); - this.anyGameFiles = GenFilePaths.AllSavedGameFiles.Any(); + this.anyGameFiles = GenFilePaths.AllSavedGameFiles.Any(); } public override void ExtraOnGUI() diff --git a/Assembly-CSharp/RimWorld/MainTabWindow_PawnTable.cs b/Assembly-CSharp/RimWorld/MainTabWindow_PawnTable.cs index c7ef47f1e..6f3472bed 100644 --- a/Assembly-CSharp/RimWorld/MainTabWindow_PawnTable.cs +++ b/Assembly-CSharp/RimWorld/MainTabWindow_PawnTable.cs @@ -54,7 +54,10 @@ public override Vector2 RequestedTabSize { return Vector2.zero; } - return new Vector2(this.table.Size.x + this.Margin * 2f, this.table.Size.y + this.ExtraBottomSpace + this.ExtraTopSpace + this.Margin * 2f); + Vector2 size = this.table.Size; + double x = size.x + this.Margin * 2.0; + Vector2 size2 = this.table.Size; + return new Vector2((float)x, (float)(size2.y + this.ExtraBottomSpace + this.ExtraTopSpace + this.Margin * 2.0)); } } @@ -86,7 +89,7 @@ public override void Notify_ResolutionChanged() private PawnTable CreateTable() { - return new PawnTable(this.PawnTableDef, () => this.Pawns, 998, UI.screenWidth - (int)(this.Margin * 2f), 0, (int)((float)(UI.screenHeight - 35) - this.ExtraBottomSpace - this.ExtraTopSpace - this.Margin * 2f)); + return new PawnTable(this.PawnTableDef, (Func>)(() => this.Pawns), 998, UI.screenWidth - (int)(this.Margin * 2.0), 0, (int)((float)(UI.screenHeight - 35) - this.ExtraBottomSpace - this.ExtraTopSpace - this.Margin * 2.0)); } protected void SetDirty() diff --git a/Assembly-CSharp/RimWorld/MainTabWindow_Research.cs b/Assembly-CSharp/RimWorld/MainTabWindow_Research.cs index d49825be0..0a33115e1 100644 --- a/Assembly-CSharp/RimWorld/MainTabWindow_Research.cs +++ b/Assembly-CSharp/RimWorld/MainTabWindow_Research.cs @@ -70,15 +70,14 @@ private ResearchTabDef CurTab } set { - if (value == this.curTabInt) + if (value != this.curTabInt) { - return; + this.curTabInt = value; + Vector2 vector = this.ViewSize(this.CurTab); + this.rightViewWidth = vector.x; + this.rightViewHeight = vector.y; + this.rightScrollPosition = Vector2.zero; } - this.curTabInt = value; - Vector2 vector = this.ViewSize(this.CurTab); - this.rightViewWidth = vector.x; - this.rightViewHeight = vector.y; - this.rightScrollPosition = Vector2.zero; } } @@ -88,7 +87,11 @@ public override Vector2 InitialSize { Vector2 initialSize = base.InitialSize; float b = (float)(UI.screenHeight - 35); - float b2 = this.Margin + 10f + 32f + 10f + DefDatabase.AllDefs.Max((ResearchTabDef tab) => this.ViewSize(tab).y) + 10f + 10f + this.Margin; + float b2 = (float)(this.Margin + 10.0 + 32.0 + 10.0 + DefDatabase.AllDefs.Max((Func)delegate(ResearchTabDef tab) + { + Vector2 vector = this.ViewSize(tab); + return vector.y; + }) + 10.0 + 10.0 + this.Margin); float a = Mathf.Max(initialSize.y, b2); initialSize.y = Mathf.Min(a, b); return initialSize; @@ -108,11 +111,11 @@ private Vector2 ViewSize(ResearchTabDef tab) { Rect rect = new Rect(0f, 0f, 140f, 0f); Widgets.LabelCacheHeight(ref rect, this.GetLabel(researchProjectDef), false, false); - num = Mathf.Max(num, this.PosX(researchProjectDef) + 140f); + num = Mathf.Max(num, (float)(this.PosX(researchProjectDef) + 140.0)); num2 = Mathf.Max(num2, this.PosY(researchProjectDef) + rect.height); } } - return new Vector2(num + 20f, num2 + 20f); + return new Vector2((float)(num + 20.0), (float)(num2 + 20.0)); } public override void PreOpen() @@ -135,29 +138,32 @@ public override void PreOpen() public override void DoWindowContents(Rect inRect) { base.DoWindowContents(inRect); - this.windowRect.width = (float)UI.screenWidth; + base.windowRect.width = (float)UI.screenWidth; if (!this.noBenchWarned) { bool flag = false; List maps = Find.Maps; - for (int i = 0; i < maps.Count; i++) + int num = 0; + while (num < maps.Count) { - if (maps[i].listerBuildings.ColonistsHaveResearchBench()) + if (!maps[num].listerBuildings.ColonistsHaveResearchBench()) { - flag = true; - break; + num++; + continue; } + flag = true; + break; } if (!flag) { - Find.WindowStack.Add(new Dialog_MessageBox("ResearchMenuWithoutBench".Translate(), null, null, null, null, null, false)); + Find.WindowStack.Add(new Dialog_MessageBox("ResearchMenuWithoutBench".Translate(), (string)null, null, (string)null, null, (string)null, false)); } this.noBenchWarned = true; } Text.Anchor = TextAnchor.UpperLeft; Text.Font = GameFont.Small; Rect leftOutRect = new Rect(0f, 0f, 200f, inRect.height); - Rect rightOutRect = new Rect(leftOutRect.xMax + 10f, 0f, inRect.width - leftOutRect.width - 10f, inRect.height); + Rect rightOutRect = new Rect((float)(leftOutRect.xMax + 10.0), 0f, (float)(inRect.width - leftOutRect.width - 10.0), inRect.height); this.DrawLeftRect(leftOutRect); this.DrawRightRect(rightOutRect); } @@ -169,7 +175,7 @@ private void DrawLeftRect(Rect leftOutRect) if (this.selectedProject != null) { Rect outRect = new Rect(0f, 0f, position.width, 500f); - Rect viewRect = new Rect(0f, 0f, outRect.width - 16f, this.leftScrollViewHeight); + Rect viewRect = new Rect(0f, 0f, (float)(outRect.width - 16.0), this.leftScrollViewHeight); Widgets.BeginScrollView(outRect, ref this.leftScrollPosition, viewRect, true); float num = 0f; Text.Font = GameFont.Medium; @@ -181,52 +187,32 @@ private void DrawLeftRect(Rect leftOutRect) num += rect.height; Rect rect2 = new Rect(0f, num, viewRect.width, 0f); Widgets.LabelCacheHeight(ref rect2, this.selectedProject.description, true, false); - num += rect2.height + 10f; - string label = string.Concat(new string[] - { - "ProjectTechLevel".Translate().CapitalizeFirst(), - ": ", - this.selectedProject.techLevel.ToStringHuman(), - "\n", - "YourTechLevel".Translate().CapitalizeFirst(), - ": ", - Faction.OfPlayer.def.techLevel.ToStringHuman(), - "\n", - "ResearchCostMultiplier".Translate().CapitalizeFirst(), - ": ", - this.selectedProject.CostFactor(Faction.OfPlayer.def.techLevel).ToStringPercent(), - "\n", - "ResearchCostComparison".Translate(new object[] - { - this.selectedProject.baseCost.ToString("F0"), - this.selectedProject.CostApparent.ToString("F0") - }) - }); + num = (float)(num + (rect2.height + 10.0)); + string label = "ProjectTechLevel".Translate().CapitalizeFirst() + ": " + this.selectedProject.techLevel.ToStringHuman() + "\n" + "YourTechLevel".Translate().CapitalizeFirst() + ": " + Faction.OfPlayer.def.techLevel.ToStringHuman() + "\n" + "ResearchCostMultiplier".Translate().CapitalizeFirst() + ": " + this.selectedProject.CostFactor(Faction.OfPlayer.def.techLevel).ToStringPercent() + "\n" + "ResearchCostComparison".Translate(this.selectedProject.baseCost.ToString("F0"), this.selectedProject.CostApparent.ToString("F0")); Rect rect3 = new Rect(0f, num, viewRect.width, 0f); Widgets.LabelCacheHeight(ref rect3, label, true, false); - num = rect3.yMax + 10f; + num = (float)(rect3.yMax + 10.0); Rect rect4 = new Rect(0f, num, viewRect.width, 500f); float num2 = this.DrawResearchPrereqs(this.selectedProject, rect4); - if (num2 > 0f) + if (num2 > 0.0) { - num += num2 + 15f; + num = (float)(num + (num2 + 15.0)); } Rect rect5 = new Rect(0f, num, viewRect.width, 500f); num += this.DrawResearchBenchRequirements(this.selectedProject, rect5); - num += 3f; - this.leftScrollViewHeight = num; + num = (this.leftScrollViewHeight = (float)(num + 3.0)); Widgets.EndScrollView(); bool flag = Prefs.DevMode && this.selectedProject.PrerequisitesCompleted && this.selectedProject != Find.ResearchManager.currentProj && !this.selectedProject.IsFinished; Rect rect6 = new Rect(0f, 0f, 90f, 50f); if (flag) { - rect6.x = (outRect.width - (rect6.width * 2f + 20f)) / 2f; + rect6.x = (float)((outRect.width - (rect6.width * 2.0 + 20.0)) / 2.0); } else { - rect6.x = (outRect.width - rect6.width) / 2f; + rect6.x = (float)((outRect.width - rect6.width) / 2.0); } - rect6.y = outRect.y + outRect.height + 20f; + rect6.y = (float)(outRect.y + outRect.height + 20.0); if (this.selectedProject.IsFinished) { Widgets.DrawMenuSection(rect6, true); @@ -257,14 +243,14 @@ private void DrawLeftRect(Rect leftOutRect) if (flag) { Rect rect7 = rect6; - rect7.x += rect7.width + 20f; + rect7.x += (float)(rect7.width + 20.0); if (Widgets.ButtonText(rect7, "Debug Insta-finish", true, false, true)) { Find.ResearchManager.currentProj = this.selectedProject; Find.ResearchManager.InstantFinish(this.selectedProject, false); } } - Rect rect8 = new Rect(15f, rect6.y + rect6.height + 20f, position.width - 30f, 35f); + Rect rect8 = new Rect(15f, (float)(rect6.y + rect6.height + 20.0), (float)(position.width - 30.0), 35f); Widgets.FillableBar(rect8, this.selectedProject.ProgressPercent, MainTabWindow_Research.ResearchBarFillTex, MainTabWindow_Research.ResearchBarBGTex, true); Text.Anchor = TextAnchor.MiddleCenter; Widgets.Label(rect8, this.selectedProject.ProgressApparent.ToString("F0") + " / " + this.selectedProject.CostApparent.ToString("F0")); @@ -275,12 +261,12 @@ private void DrawLeftRect(Rect leftOutRect) private float CoordToPixelsX(float x) { - return x * 190f; + return (float)(x * 190.0); } private float CoordToPixelsY(float y) { - return y * 100f; + return (float)(y * 100.0); } private float PosX(ResearchProjectDef d) @@ -298,10 +284,10 @@ private void DrawRightRect(Rect rightOutRect) rightOutRect.yMin += 32f; Widgets.DrawMenuSection(rightOutRect, true); List list = new List(); - foreach (ResearchTabDef current in DefDatabase.AllDefs) + foreach (ResearchTabDef allDef in DefDatabase.AllDefs) { - ResearchTabDef localTabDef = current; - list.Add(new TabRecord(localTabDef.LabelCap, delegate + ResearchTabDef localTabDef = allDef; + list.Add(new TabRecord(localTabDef.LabelCap, (Action)delegate { this.CurTab = localTabDef; }, this.CurTab == localTabDef)); @@ -309,14 +295,14 @@ private void DrawRightRect(Rect rightOutRect) TabDrawer.DrawTabs(rightOutRect, list); Rect outRect = rightOutRect.ContractedBy(10f); Rect rect = new Rect(0f, 0f, this.rightViewWidth, this.rightViewHeight); - Rect position = rect.ContractedBy(10f); + Rect rect2 = rect.ContractedBy(10f); rect.width = this.rightViewWidth; - position = rect.ContractedBy(10f); + rect2 = rect.ContractedBy(10f); Vector2 start = default(Vector2); Vector2 end = default(Vector2); Widgets.ScrollHorizontal(outRect, ref this.rightScrollPosition, rect, 20f); Widgets.BeginScrollView(outRect, ref this.rightScrollPosition, rect, true); - GUI.BeginGroup(position); + GUI.BeginGroup(rect2); List allDefsListForReading = DefDatabase.AllDefsListForReading; for (int i = 0; i < 2; i++) { @@ -326,14 +312,14 @@ private void DrawRightRect(Rect rightOutRect) if (researchProjectDef.tab == this.CurTab) { start.x = this.PosX(researchProjectDef); - start.y = this.PosY(researchProjectDef) + 25f; - for (int k = 0; k < researchProjectDef.prerequisites.CountAllowNull(); k++) + start.y = (float)(this.PosY(researchProjectDef) + 25.0); + for (int k = 0; k < researchProjectDef.prerequisites.CountAllowNull(); k++) { ResearchProjectDef researchProjectDef2 = researchProjectDef.prerequisites[k]; if (researchProjectDef2 != null && researchProjectDef2.tab == this.CurTab) { - end.x = this.PosX(researchProjectDef2) + 140f; - end.y = this.PosY(researchProjectDef2) + 25f; + end.x = (float)(this.PosX(researchProjectDef2) + 140.0); + end.y = (float)(this.PosY(researchProjectDef2) + 25.0); if (this.selectedProject == researchProjectDef || this.selectedProject == researchProjectDef2) { if (i == 1) @@ -357,10 +343,10 @@ private void DrawRightRect(Rect rightOutRect) { Rect source = new Rect(this.PosX(researchProjectDef3), this.PosY(researchProjectDef3), 140f, 50f); string label = this.GetLabel(researchProjectDef3); - Rect rect2 = new Rect(source); + Rect rect3 = new Rect(source); Color textColor = Widgets.NormalOptionColor; Color color = default(Color); - Color borderColor = default(Color); + Color color2 = default(Color); bool flag = !researchProjectDef3.IsFinished && !researchProjectDef3.CanStartNow; if (researchProjectDef3 == Find.ResearchManager.currentProj) { @@ -381,36 +367,36 @@ private void DrawRightRect(Rect rightOutRect) if (this.selectedProject == researchProjectDef3) { color += TexUI.HighlightBgResearchColor; - borderColor = TexUI.HighlightBorderResearchColor; + color2 = TexUI.HighlightBorderResearchColor; } else { - borderColor = TexUI.DefaultBorderResearchColor; + color2 = TexUI.DefaultBorderResearchColor; } if (flag) { textColor = MainTabWindow_Research.ProjectWithMissingPrerequisiteLabelColor; } - for (int m = 0; m < researchProjectDef3.prerequisites.CountAllowNull(); m++) + for (int m = 0; m < researchProjectDef3.prerequisites.CountAllowNull(); m++) { ResearchProjectDef researchProjectDef4 = researchProjectDef3.prerequisites[m]; if (researchProjectDef4 != null && this.selectedProject == researchProjectDef4) { - borderColor = TexUI.HighlightLineResearchColor; + color2 = TexUI.HighlightLineResearchColor; } } if (this.requiredByThisFound) { - for (int n = 0; n < researchProjectDef3.requiredByThis.CountAllowNull(); n++) + for (int n = 0; n < researchProjectDef3.requiredByThis.CountAllowNull(); n++) { ResearchProjectDef researchProjectDef5 = researchProjectDef3.requiredByThis[n]; if (this.selectedProject == researchProjectDef5) { - borderColor = TexUI.HighlightLineResearchColor; + color2 = TexUI.HighlightLineResearchColor; } } } - if (Widgets.CustomButtonText(ref rect2, label, color, textColor, borderColor, true, 1, true, true)) + if (Widgets.CustomButtonText(ref rect3, label, color, textColor, color2, true, 1, true, true)) { SoundDefOf.Click.PlayOneShotOnCamera(null); this.selectedProject = researchProjectDef3; @@ -423,7 +409,7 @@ private void DrawRightRect(Rect rightOutRect) private float DrawResearchPrereqs(ResearchProjectDef project, Rect rect) { - if (project.prerequisites.NullOrEmpty()) + if (project.prerequisites.NullOrEmpty()) { return 0f; } @@ -447,13 +433,16 @@ private float DrawResearchBenchRequirements(ResearchProjectDef project, Rect rec { bool present = false; List maps = Find.Maps; - for (int i = 0; i < maps.Count; i++) + int num = 0; + while (num < maps.Count) { - if (maps[i].listerBuildings.allBuildingsColonist.Find((Building x) => x.def == project.requiredResearchBuilding) != null) + if (maps[num].listerBuildings.allBuildingsColonist.Find((Predicate)((Building x) => x.def == project.requiredResearchBuilding)) == null) { - present = true; - break; + num++; + continue; } + present = true; + break; } Widgets.LabelCacheHeight(ref rect, "RequiredResearchBench".Translate() + ":", true, false); rect.yMin += rect.height; @@ -462,7 +451,7 @@ private float DrawResearchBenchRequirements(ResearchProjectDef project, Rect rec rect.yMin += rect.height; GUI.color = Color.white; } - if (!project.requiredResearchFacilities.NullOrEmpty()) + if (!project.requiredResearchFacilities.NullOrEmpty()) { Widgets.LabelCacheHeight(ref rect, "RequiredResearchBenchFacilities".Translate() + ":", true, false); rect.yMin += rect.height; @@ -472,9 +461,9 @@ private float DrawResearchBenchRequirements(ResearchProjectDef project, Rect rec { bestMatchingBench = building_ResearchBench.TryGetComp(); } - for (int j = 0; j < project.requiredResearchFacilities.Count; j++) + for (int i = 0; i < project.requiredResearchFacilities.Count; i++) { - this.DrawResearchBenchFacilityRequirement(project.requiredResearchFacilities[j], bestMatchingBench, project, ref rect); + this.DrawResearchBenchFacilityRequirement(project.requiredResearchFacilities[i], bestMatchingBench, project, ref rect); rect.yMin += 15f; } } @@ -489,17 +478,16 @@ private string GetLabel(ResearchProjectDef r) private void SetPrerequisiteStatusColor(bool present, ResearchProjectDef project) { - if (project.IsFinished) - { - return; - } - if (present) - { - GUI.color = MainTabWindow_Research.FulfilledPrerequisiteColor; - } - else + if (!project.IsFinished) { - GUI.color = MainTabWindow_Research.MissingPrerequisiteColor; + if (present) + { + GUI.color = MainTabWindow_Research.FulfilledPrerequisiteColor; + } + else + { + GUI.color = MainTabWindow_Research.MissingPrerequisiteColor; + } } } @@ -509,8 +497,8 @@ private void DrawResearchBenchFacilityRequirement(ThingDef requiredFacility, Com Thing thing2 = null; if (bestMatchingBench != null) { - thing = bestMatchingBench.LinkedFacilitiesListForReading.Find((Thing x) => x.def == requiredFacility); - thing2 = bestMatchingBench.LinkedFacilitiesListForReading.Find((Thing x) => x.def == requiredFacility && bestMatchingBench.IsFacilityActive(x)); + thing = bestMatchingBench.LinkedFacilitiesListForReading.Find((Predicate)((Thing x) => x.def == requiredFacility)); + thing2 = bestMatchingBench.LinkedFacilitiesListForReading.Find((Predicate)((Thing x) => x.def == requiredFacility && bestMatchingBench.IsFacilityActive(x))); } this.SetPrerequisiteStatusColor(thing2 != null, project); string text = requiredFacility.LabelCap; @@ -534,16 +522,13 @@ private Building_ResearchBench FindBenchFulfillingMostRequirements(ThingDef requ for (int j = 0; j < MainTabWindow_Research.tmpAllBuildings.Count; j++) { Building_ResearchBench building_ResearchBench2 = MainTabWindow_Research.tmpAllBuildings[j] as Building_ResearchBench; - if (building_ResearchBench2 != null) + if (building_ResearchBench2 != null && (requiredResearchBench == null || building_ResearchBench2.def == requiredResearchBench)) { - if (requiredResearchBench == null || building_ResearchBench2.def == requiredResearchBench) + float researchBenchRequirementsScore = this.GetResearchBenchRequirementsScore(building_ResearchBench2, requiredFacilities); + if (building_ResearchBench == null || researchBenchRequirementsScore > num) { - float researchBenchRequirementsScore = this.GetResearchBenchRequirementsScore(building_ResearchBench2, requiredFacilities); - if (building_ResearchBench == null || researchBenchRequirementsScore > num) - { - num = researchBenchRequirementsScore; - building_ResearchBench = building_ResearchBench2; - } + num = researchBenchRequirementsScore; + building_ResearchBench = building_ResearchBench2; } } } @@ -561,13 +546,13 @@ private float GetResearchBenchRequirementsScore(Building_ResearchBench bench, Li if (benchComp != null) { List linkedFacilitiesListForReading = benchComp.LinkedFacilitiesListForReading; - if (linkedFacilitiesListForReading.Find((Thing x) => x.def == requiredFacilities[i] && benchComp.IsFacilityActive(x)) != null) + if (linkedFacilitiesListForReading.Find((Predicate)((Thing x) => x.def == requiredFacilities[i] && benchComp.IsFacilityActive(x))) != null) { - num += 1f; + num = (float)(num + 1.0); } - else if (linkedFacilitiesListForReading.Find((Thing x) => x.def == requiredFacilities[i]) != null) + else if (linkedFacilitiesListForReading.Find((Predicate)((Thing x) => x.def == requiredFacilities[i])) != null) { - num += 0.6f; + num = (float)(num + 0.60000002384185791); } } } diff --git a/Assembly-CSharp/RimWorld/MainTabWindow_Restrict.cs b/Assembly-CSharp/RimWorld/MainTabWindow_Restrict.cs index 4026f2e83..68e3ccb5b 100644 --- a/Assembly-CSharp/RimWorld/MainTabWindow_Restrict.cs +++ b/Assembly-CSharp/RimWorld/MainTabWindow_Restrict.cs @@ -1,5 +1,4 @@ using RimWorld.Planet; -using System; using UnityEngine; using Verse; diff --git a/Assembly-CSharp/RimWorld/MainTabWindow_Work.cs b/Assembly-CSharp/RimWorld/MainTabWindow_Work.cs index 21aa7f262..7a0a639b8 100644 --- a/Assembly-CSharp/RimWorld/MainTabWindow_Work.cs +++ b/Assembly-CSharp/RimWorld/MainTabWindow_Work.cs @@ -1,5 +1,4 @@ using RimWorld.Planet; -using System; using UnityEngine; using Verse; @@ -34,21 +33,20 @@ public override void PostOpen() public override void DoWindowContents(Rect rect) { base.DoWindowContents(rect); - if (Event.current.type == EventType.Layout) + if (Event.current.type != EventType.Layout) { - return; + this.DoManualPrioritiesCheckbox(); + GUI.color = new Color(1f, 1f, 1f, 0.5f); + Text.Anchor = TextAnchor.UpperCenter; + Text.Font = GameFont.Tiny; + Rect rect2 = new Rect(370f, (float)(rect.y + 5.0), 160f, 30f); + Widgets.Label(rect2, "<= " + "HigherPriority".Translate()); + Rect rect3 = new Rect(630f, (float)(rect.y + 5.0), 160f, 30f); + Widgets.Label(rect3, "LowerPriority".Translate() + " =>"); + GUI.color = Color.white; + Text.Font = GameFont.Small; + Text.Anchor = TextAnchor.UpperLeft; } - this.DoManualPrioritiesCheckbox(); - GUI.color = new Color(1f, 1f, 1f, 0.5f); - Text.Anchor = TextAnchor.UpperCenter; - Text.Font = GameFont.Tiny; - Rect rect2 = new Rect(370f, rect.y + 5f, 160f, 30f); - Widgets.Label(rect2, "<= " + "HigherPriority".Translate()); - Rect rect3 = new Rect(630f, rect.y + 5f, 160f, 30f); - Widgets.Label(rect3, "LowerPriority".Translate() + " =>"); - GUI.color = Color.white; - Text.Font = GameFont.Small; - Text.Anchor = TextAnchor.UpperLeft; } private void DoManualPrioritiesCheckbox() @@ -61,11 +59,11 @@ private void DoManualPrioritiesCheckbox() Widgets.CheckboxLabeled(rect, "ManualPriorities".Translate(), ref Current.Game.playSettings.useWorkPriorities, false); if (useWorkPriorities != Current.Game.playSettings.useWorkPriorities) { - foreach (Pawn current in PawnsFinder.AllMapsAndWorld_Alive) + foreach (Pawn item in PawnsFinder.AllMapsAndWorld_Alive) { - if (current.Faction == Faction.OfPlayer && current.workSettings != null) + if (item.Faction == Faction.OfPlayer && item.workSettings != null) { - current.workSettings.Notify_UseWorkPrioritiesChanged(); + item.workSettings.Notify_UseWorkPrioritiesChanged(); } } } diff --git a/Assembly-CSharp/RimWorld/MainTabsRoot.cs b/Assembly-CSharp/RimWorld/MainTabsRoot.cs index e1710be01..5b611c281 100644 --- a/Assembly-CSharp/RimWorld/MainTabsRoot.cs +++ b/Assembly-CSharp/RimWorld/MainTabsRoot.cs @@ -1,5 +1,4 @@ using RimWorld.Planet; -using System; using UnityEngine; using Verse; using Verse.Sound; @@ -50,19 +49,16 @@ public void EscapeCurrentTab(bool playSound = true) public void SetCurrentTab(MainButtonDef tab, bool playSound = true) { - if (tab == this.OpenTab) + if (tab != this.OpenTab) { - return; + this.ToggleTab(tab, playSound); } - this.ToggleTab(tab, playSound); } public void ToggleTab(MainButtonDef newTab, bool playSound = true) { if (this.OpenTab == null && newTab == null) - { return; - } if (this.OpenTab == newTab) { Find.WindowStack.TryRemove(this.OpenTab.TabWindow, true); diff --git a/Assembly-CSharp/RimWorld/MaintainableStage.cs b/Assembly-CSharp/RimWorld/MaintainableStage.cs index 62a0b696e..6bf7c44bf 100644 --- a/Assembly-CSharp/RimWorld/MaintainableStage.cs +++ b/Assembly-CSharp/RimWorld/MaintainableStage.cs @@ -1,11 +1,9 @@ -using System; - namespace RimWorld { public enum MaintainableStage { - Healthy, - NeedsMaintenance, - Damaging + Healthy = 0, + NeedsMaintenance = 1, + Damaging = 2 } } diff --git a/Assembly-CSharp/RimWorld/ManhunterPackIncidentUtility.cs b/Assembly-CSharp/RimWorld/ManhunterPackIncidentUtility.cs index e5afc4eb0..38092a9a8 100644 --- a/Assembly-CSharp/RimWorld/ManhunterPackIncidentUtility.cs +++ b/Assembly-CSharp/RimWorld/ManhunterPackIncidentUtility.cs @@ -23,16 +23,16 @@ public static bool TryFindManhunterAnimalKind(float points, int tile, out PawnKi { return (from k in DefDatabase.AllDefs where k.RaceProps.Animal && k.canArriveManhunter && (tile == -1 || Find.World.tileTemperatures.SeasonAndOutdoorTemperatureAcceptableFor(tile, k.race)) - select k).TryRandomElementByWeight((PawnKindDef k) => ManhunterPackIncidentUtility.ManhunterAnimalWeight(k, points), out animalKind); + select k).TryRandomElementByWeight((Func)((PawnKindDef k) => ManhunterPackIncidentUtility.ManhunterAnimalWeight(k, points)), out animalKind); } public static List GenerateAnimals(PawnKindDef animalKind, int tile, float points) { int num = Mathf.Max(Mathf.RoundToInt(points / animalKind.combatPower), 1); List list = new List(); - for (int i = 0; i < num; i++) + for (int num2 = 0; num2 < num; num2++) { - PawnGenerationRequest request = new PawnGenerationRequest(animalKind, null, PawnGenerationContext.NonPlayer, tile, false, false, false, false, true, false, 1f, false, true, true, false, false, null, null, null, null, null, null); + PawnGenerationRequest request = new PawnGenerationRequest(animalKind, null, PawnGenerationContext.NonPlayer, tile, false, false, false, false, true, false, 1f, false, true, true, false, false, null, default(float?), default(float?), default(Gender?), default(float?), (string)null); Pawn item = PawnGenerator.GeneratePawn(request); list.Add(item); } @@ -43,22 +43,22 @@ public static void DoTable_ManhunterResults() { List candidates = (from k in DefDatabase.AllDefs where k.RaceProps.Animal && k.canArriveManhunter - orderby -k.combatPower - select k).ToList(); + orderby (float)(0.0 - k.combatPower) + select k).ToList(); List list = new List(); for (int i = 0; i < 30; i++) { - list.Add(20f * Mathf.Pow(1.25f, (float)i)); + list.Add((float)(20.0 * Mathf.Pow(1.25f, (float)i))); } - DebugTables.MakeTablesDialog(list, (float points) => points.ToString("F0") + " pts", candidates, (PawnKindDef candidate) => candidate.defName + " (" + candidate.combatPower.ToString("F0") + ")", delegate(float points, PawnKindDef candidate) + DebugTables.MakeTablesDialog(list, (Func)((float points) => points.ToString("F0") + " pts"), candidates, (Func)((PawnKindDef candidate) => candidate.defName + " (" + candidate.combatPower.ToString("F0") + ")"), (Func)delegate(float points, PawnKindDef candidate) { - float num = candidates.Sum((PawnKindDef k) => ManhunterPackIncidentUtility.ManhunterAnimalWeight(k, points)); + float num = candidates.Sum((Func)((PawnKindDef k) => ManhunterPackIncidentUtility.ManhunterAnimalWeight(k, points))); float num2 = ManhunterPackIncidentUtility.ManhunterAnimalWeight(candidate, points); - if (num2 == 0f) + if (num2 == 0.0) { return "0%"; } - return string.Format("{0}%, {1}", (num2 * 100f / num).ToString("F0"), Mathf.Max(Mathf.RoundToInt(points / candidate.combatPower), 1)); + return string.Format("{0}%, {1}", ((float)(num2 * 100.0 / num)).ToString("F0"), Mathf.Max(Mathf.RoundToInt(points / candidate.combatPower), 1)); }, string.Empty); } } diff --git a/Assembly-CSharp/RimWorld/MannableUtility.cs b/Assembly-CSharp/RimWorld/MannableUtility.cs index 548029246..1873c7225 100644 --- a/Assembly-CSharp/RimWorld/MannableUtility.cs +++ b/Assembly-CSharp/RimWorld/MannableUtility.cs @@ -1,4 +1,3 @@ -using System; using Verse; namespace RimWorld @@ -12,11 +11,11 @@ public static Thing MannedThing(this Pawn pawn) return null; } Thing lastMannedThing = pawn.mindState.lastMannedThing; - if (lastMannedThing == null || lastMannedThing.TryGetComp().ManningPawn != pawn) + if (lastMannedThing != null && lastMannedThing.TryGetComp().ManningPawn == pawn) { - return null; + return lastMannedThing; } - return lastMannedThing; + return null; } } } diff --git a/Assembly-CSharp/RimWorld/MapGenTuning.cs b/Assembly-CSharp/RimWorld/MapGenTuning.cs index 3c7ac0135..0fb7648a4 100644 --- a/Assembly-CSharp/RimWorld/MapGenTuning.cs +++ b/Assembly-CSharp/RimWorld/MapGenTuning.cs @@ -1,5 +1,3 @@ -using System; - namespace RimWorld { public static class MapGenTuning diff --git a/Assembly-CSharp/RimWorld/MapGeneratorDefOf.cs b/Assembly-CSharp/RimWorld/MapGeneratorDefOf.cs index 1236f17d5..d489a68f6 100644 --- a/Assembly-CSharp/RimWorld/MapGeneratorDefOf.cs +++ b/Assembly-CSharp/RimWorld/MapGeneratorDefOf.cs @@ -1,4 +1,3 @@ -using System; using Verse; namespace RimWorld diff --git a/Assembly-CSharp/RimWorld/MapInterface.cs b/Assembly-CSharp/RimWorld/MapInterface.cs index bdf2c168e..d7e389c3a 100644 --- a/Assembly-CSharp/RimWorld/MapInterface.cs +++ b/Assembly-CSharp/RimWorld/MapInterface.cs @@ -1,5 +1,4 @@ using RimWorld.Planet; -using System; using System.Collections.Generic; using Verse; using Verse.AI; @@ -28,50 +27,45 @@ public class MapInterface public void MapInterfaceOnGUI_BeforeMainTabs() { - if (Find.VisibleMap == null) - { - return; - } - if (!WorldRendererUtility.WorldRenderedNow) + if (Find.VisibleMap != null) { - ScreenshotModeHandler screenshotMode = Find.UIRoot.screenshotMode; - this.thingOverlays.ThingOverlaysOnGUI(); - MapComponentUtility.MapComponentOnGUI(Find.VisibleMap); - if (!screenshotMode.FiltersCurrentEvent) - { - this.colonistBar.ColonistBarOnGUI(); - } - this.selector.dragBox.DragBoxOnGUI(); - this.designatorManager.DesignationManagerOnGUI(); - this.targeter.TargeterOnGUI(); - Find.VisibleMap.tooltipGiverList.DispenseAllThingTooltips(); - if (DebugViewSettings.drawFoodSearchFromMouse) - { - FoodUtility.DebugFoodSearchFromMouse_OnGUI(); - } - if (DebugViewSettings.drawAttackTargetScores) + if (!WorldRendererUtility.WorldRenderedNow) { - AttackTargetFinder.DebugDrawAttackTargetScores_OnGUI(); + ScreenshotModeHandler screenshotMode = Find.UIRoot.screenshotMode; + this.thingOverlays.ThingOverlaysOnGUI(); + MapComponentUtility.MapComponentOnGUI(Find.VisibleMap); + if (!screenshotMode.FiltersCurrentEvent) + { + this.colonistBar.ColonistBarOnGUI(); + } + this.selector.dragBox.DragBoxOnGUI(); + this.designatorManager.DesignationManagerOnGUI(); + this.targeter.TargeterOnGUI(); + Find.VisibleMap.tooltipGiverList.DispenseAllThingTooltips(); + if (DebugViewSettings.drawFoodSearchFromMouse) + { + FoodUtility.DebugFoodSearchFromMouse_OnGUI(); + } + if (DebugViewSettings.drawAttackTargetScores) + { + AttackTargetFinder.DebugDrawAttackTargetScores_OnGUI(); + } + if (!screenshotMode.FiltersCurrentEvent) + { + this.globalControls.GlobalControlsOnGUI(); + this.resourceReadout.ResourceReadoutOnGUI(); + } } - if (!screenshotMode.FiltersCurrentEvent) + else { - this.globalControls.GlobalControlsOnGUI(); - this.resourceReadout.ResourceReadoutOnGUI(); + this.targeter.StopTargeting(); } } - else - { - this.targeter.StopTargeting(); - } } public void MapInterfaceOnGUI_AfterMainTabs() { - if (Find.VisibleMap == null) - { - return; - } - if (!WorldRendererUtility.WorldRenderedNow) + if (Find.VisibleMap != null && !WorldRendererUtility.WorldRenderedNow) { ScreenshotModeHandler screenshotMode = Find.UIRoot.screenshotMode; if (!screenshotMode.FiltersCurrentEvent) @@ -85,11 +79,7 @@ public void MapInterfaceOnGUI_AfterMainTabs() public void HandleMapClicks() { - if (Find.VisibleMap == null) - { - return; - } - if (!WorldRendererUtility.WorldRenderedNow) + if (Find.VisibleMap != null && !WorldRendererUtility.WorldRenderedNow) { this.designatorManager.ProcessInputEvents(); this.targeter.ProcessInputEvents(); @@ -98,11 +88,7 @@ public void HandleMapClicks() public void HandleLowPriorityInput() { - if (Find.VisibleMap == null) - { - return; - } - if (!WorldRendererUtility.WorldRenderedNow) + if (Find.VisibleMap != null && !WorldRendererUtility.WorldRenderedNow) { this.selector.SelectorOnGUI(); Find.VisibleMap.lordManager.LordManagerOnGUI(); @@ -111,11 +97,7 @@ public void HandleLowPriorityInput() public void MapInterfaceUpdate() { - if (Find.VisibleMap == null) - { - return; - } - if (!WorldRendererUtility.WorldRenderedNow) + if (Find.VisibleMap != null && !WorldRendererUtility.WorldRenderedNow) { this.targeter.TargeterUpdate(); SelectionDrawer.DrawSelectionOverlays(); diff --git a/Assembly-CSharp/RimWorld/MarriageCeremonyUtility.cs b/Assembly-CSharp/RimWorld/MarriageCeremonyUtility.cs index bb11ae508..5a9d705c7 100644 --- a/Assembly-CSharp/RimWorld/MarriageCeremonyUtility.cs +++ b/Assembly-CSharp/RimWorld/MarriageCeremonyUtility.cs @@ -1,4 +1,3 @@ -using System; using System.Collections.Generic; using Verse; using Verse.AI.Group; @@ -13,42 +12,70 @@ public static bool AcceptableGameConditionsToStartCeremony(Map map) { return false; } - if (GenLocalDate.HourInteger(map) < 5 || GenLocalDate.HourInteger(map) > 16) + if (GenLocalDate.HourInteger(map) >= 5 && GenLocalDate.HourInteger(map) <= 16) { - return false; - } - if (GatheringsUtility.AnyLordJobPreventsNewGatherings(map)) - { - return false; - } - if (map.dangerWatcher.DangerRating != StoryDanger.None) - { - return false; - } - int num = 0; - foreach (Pawn current in map.mapPawns.FreeColonistsSpawned) - { - if (current.Drafted) + if (GatheringsUtility.AnyLordJobPreventsNewGatherings(map)) { - num++; + return false; } + if (map.dangerWatcher.DangerRating != 0) + { + return false; + } + int num = 0; + foreach (Pawn item in map.mapPawns.FreeColonistsSpawned) + { + if (item.Drafted) + { + num++; + } + } + if ((float)num / (float)map.mapPawns.FreeColonistsSpawnedCount >= 0.5) + { + return false; + } + return true; } - return (float)num / (float)map.mapPawns.FreeColonistsSpawnedCount < 0.5f; + return false; } public static bool AcceptableGameConditionsToContinueCeremony(Map map) { - return map.dangerWatcher.DangerRating != StoryDanger.High; + if (map.dangerWatcher.DangerRating == StoryDanger.High) + { + return false; + } + return true; } public static bool FianceReadyToStartCeremony(Pawn pawn) { - return MarriageCeremonyUtility.FianceCanContinueCeremony(pawn) && pawn.health.hediffSet.BleedRateTotal <= 0f && !HealthAIUtility.ShouldSeekMedicalRestUrgent(pawn) && !PawnUtility.WillSoonHaveBasicNeed(pawn) && !MarriageCeremonyUtility.IsCurrentlyMarryingSomeone(pawn) && (!pawn.Drafted && !pawn.InMentalState && pawn.Awake() && !pawn.IsBurning()) && !pawn.InBed(); + if (!MarriageCeremonyUtility.FianceCanContinueCeremony(pawn)) + { + return false; + } + if (pawn.health.hediffSet.BleedRateTotal > 0.0) + { + return false; + } + if (HealthAIUtility.ShouldSeekMedicalRestUrgent(pawn)) + { + return false; + } + if (PawnUtility.WillSoonHaveBasicNeed(pawn)) + { + return false; + } + if (MarriageCeremonyUtility.IsCurrentlyMarryingSomeone(pawn)) + { + return false; + } + return !pawn.Drafted && !pawn.InMentalState && pawn.Awake() && !pawn.IsBurning() && !pawn.InBed(); } public static bool FianceCanContinueCeremony(Pawn pawn) { - if (pawn.health.hediffSet.BleedRateTotal > 0.3f) + if (pawn.health.hediffSet.BleedRateTotal > 0.30000001192092896) { return false; } @@ -57,7 +84,11 @@ public static bool FianceCanContinueCeremony(Pawn pawn) return false; } Hediff firstHediffOfDef = pawn.health.hediffSet.GetFirstHediffOfDef(HediffDefOf.BloodLoss, false); - return (firstHediffOfDef == null || firstHediffOfDef.Severity <= 0.2f) && (pawn.Spawned && !pawn.Downed) && !pawn.InAggroMentalState; + if (firstHediffOfDef != null && firstHediffOfDef.Severity > 0.20000000298023224) + { + return false; + } + return pawn.Spawned && !pawn.Downed && !pawn.InAggroMentalState; } public static bool ShouldGuestKeepAttendingCeremony(Pawn p) @@ -77,11 +108,7 @@ public static void Married(Pawn firstPawn, Pawn secondPawn) firstPawn.needs.mood.thoughts.memories.RemoveMemoriesOfDefWhereOtherPawnIs(ThoughtDefOf.DivorcedMe, secondPawn); secondPawn.needs.mood.thoughts.memories.RemoveMemoriesOfDefWhereOtherPawnIs(ThoughtDefOf.DivorcedMe, firstPawn); LovePartnerRelationUtility.TryToShareBed(firstPawn, secondPawn); - TaleRecorder.RecordTale(TaleDefOf.Marriage, new object[] - { - firstPawn, - secondPawn - }); + TaleRecorder.RecordTale(TaleDefOf.Marriage, firstPawn, secondPawn); } private static void AddNewlyMarriedThoughts(Pawn pawn, Pawn otherPawn) diff --git a/Assembly-CSharp/RimWorld/MarriageSpotUtility.cs b/Assembly-CSharp/RimWorld/MarriageSpotUtility.cs index e253255c8..efe8207a1 100644 --- a/Assembly-CSharp/RimWorld/MarriageSpotUtility.cs +++ b/Assembly-CSharp/RimWorld/MarriageSpotUtility.cs @@ -1,4 +1,3 @@ -using System; using System.Text; using Verse; using Verse.AI; @@ -17,122 +16,108 @@ public static bool IsValidMarriageSpot(IntVec3 cell, Map map, StringBuilder outF } return false; } - return cell.Roofed(map) || JoyUtility.EnjoyableOutsideNow(map, outFailReason); + if (!cell.Roofed(map) && !JoyUtility.EnjoyableOutsideNow(map, outFailReason)) + { + return false; + } + return true; } public static bool IsValidMarriageSpotFor(IntVec3 cell, Pawn firstFiance, Pawn secondFiance, StringBuilder outFailReason = null) { - if (!firstFiance.Spawned || !secondFiance.Spawned) - { - Log.Warning("Can't check if a marriage spot is valid because one of the fiances isn't spawned."); - return false; - } - if (firstFiance.Map != secondFiance.Map) - { - return false; - } - if (!MarriageSpotUtility.IsValidMarriageSpot(cell, firstFiance.Map, outFailReason)) + if (firstFiance.Spawned && secondFiance.Spawned) { - return false; - } - if (!cell.Roofed(firstFiance.Map)) - { - if (!JoyUtility.EnjoyableOutsideNow(firstFiance, outFailReason)) + if (firstFiance.Map != secondFiance.Map) { return false; } - if (!JoyUtility.EnjoyableOutsideNow(secondFiance, outFailReason)) + if (!MarriageSpotUtility.IsValidMarriageSpot(cell, firstFiance.Map, outFailReason)) { return false; } - } - if (cell.GetDangerFor(firstFiance, firstFiance.Map) != Danger.None) - { - if (outFailReason != null) + if (!cell.Roofed(firstFiance.Map)) { - outFailReason.Append("MarriageSpotDangerous".Translate(new object[] + if (!JoyUtility.EnjoyableOutsideNow(firstFiance, outFailReason)) + { + return false; + } + if (!JoyUtility.EnjoyableOutsideNow(secondFiance, outFailReason)) { - firstFiance.LabelShort - })); + return false; + } } - return false; - } - if (cell.GetDangerFor(secondFiance, secondFiance.Map) != Danger.None) - { - if (outFailReason != null) + if (cell.GetDangerFor(firstFiance, firstFiance.Map) != Danger.None) { - outFailReason.Append("MarriageSpotDangerous".Translate(new object[] + if (outFailReason != null) { - secondFiance.LabelShort - })); + outFailReason.Append("MarriageSpotDangerous".Translate(firstFiance.LabelShort)); + } + return false; } - return false; - } - if (cell.IsForbidden(firstFiance)) - { - if (outFailReason != null) + if (cell.GetDangerFor(secondFiance, secondFiance.Map) != Danger.None) { - outFailReason.Append("MarriageSpotForbidden".Translate(new object[] + if (outFailReason != null) { - firstFiance.LabelShort - })); + outFailReason.Append("MarriageSpotDangerous".Translate(secondFiance.LabelShort)); + } + return false; } - return false; - } - if (cell.IsForbidden(secondFiance)) - { - if (outFailReason != null) + if (cell.IsForbidden(firstFiance)) { - outFailReason.Append("MarriageSpotForbidden".Translate(new object[] + if (outFailReason != null) { - secondFiance.LabelShort - })); + outFailReason.Append("MarriageSpotForbidden".Translate(firstFiance.LabelShort)); + } + return false; } - return false; - } - if (!firstFiance.CanReserve(cell, 1, -1, null, false) || !secondFiance.CanReserve(cell, 1, -1, null, false)) - { - if (outFailReason != null) + if (cell.IsForbidden(secondFiance)) { - outFailReason.Append("MarriageSpotReserved".Translate()); + if (outFailReason != null) + { + outFailReason.Append("MarriageSpotForbidden".Translate(secondFiance.LabelShort)); + } + return false; } - return false; - } - if (!firstFiance.CanReach(cell, PathEndMode.OnCell, Danger.None, false, TraverseMode.ByPawn)) - { - if (outFailReason != null) + if (firstFiance.CanReserve(cell, 1, -1, null, false) && secondFiance.CanReserve(cell, 1, -1, null, false)) { - outFailReason.Append("MarriageSpotUnreachable".Translate(new object[] + if (!firstFiance.CanReach(cell, PathEndMode.OnCell, Danger.None, false, TraverseMode.ByPawn)) + { + if (outFailReason != null) + { + outFailReason.Append("MarriageSpotUnreachable".Translate(firstFiance.LabelShort)); + } + return false; + } + if (!secondFiance.CanReach(cell, PathEndMode.OnCell, Danger.None, false, TraverseMode.ByPawn)) + { + if (outFailReason != null) + { + outFailReason.Append("MarriageSpotUnreachable".Translate(secondFiance.LabelShort)); + } + return false; + } + if (!firstFiance.IsPrisoner && !secondFiance.IsPrisoner) { - firstFiance.LabelShort - })); + Room room = cell.GetRoom(firstFiance.Map, RegionType.Set_Passable); + if (room != null && room.isPrisonCell) + { + if (outFailReason != null) + { + outFailReason.Append("MarriageSpotInPrisonCell".Translate()); + } + return false; + } + } + return true; } - return false; - } - if (!secondFiance.CanReach(cell, PathEndMode.OnCell, Danger.None, false, TraverseMode.ByPawn)) - { if (outFailReason != null) { - outFailReason.Append("MarriageSpotUnreachable".Translate(new object[] - { - secondFiance.LabelShort - })); + outFailReason.Append("MarriageSpotReserved".Translate()); } return false; } - if (!firstFiance.IsPrisoner && !secondFiance.IsPrisoner) - { - Room room = cell.GetRoom(firstFiance.Map, RegionType.Set_Passable); - if (room != null && room.isPrisonCell) - { - if (outFailReason != null) - { - outFailReason.Append("MarriageSpotInPrisonCell".Translate()); - } - return false; - } - } - return true; + Log.Warning("Can't check if a marriage spot is valid because one of the fiances isn't spawned."); + return false; } } } diff --git a/Assembly-CSharp/RimWorld/MassUtility.cs b/Assembly-CSharp/RimWorld/MassUtility.cs index 598257df4..c13d3ff93 100644 --- a/Assembly-CSharp/RimWorld/MassUtility.cs +++ b/Assembly-CSharp/RimWorld/MassUtility.cs @@ -21,7 +21,7 @@ public static float UnboundedEncumbrancePercent(Pawn pawn) public static bool IsOverEncumbered(Pawn pawn) { - return MassUtility.UnboundedEncumbrancePercent(pawn) > 1f; + return MassUtility.UnboundedEncumbrancePercent(pawn) > 1.0; } public static bool WillBeOverEncumberedAfterPickingUp(Pawn pawn, Thing thing, int count) @@ -57,9 +57,19 @@ public static float GearMass(Pawn p) } if (p.equipment != null) { - foreach (ThingWithComps current in p.equipment.AllEquipmentListForReading) + List.Enumerator enumerator = p.equipment.AllEquipmentListForReading.GetEnumerator(); + try { - num += current.GetStatValue(StatDefOf.Mass, true); + while (enumerator.MoveNext()) + { + ThingWithComps current = enumerator.Current; + num += current.GetStatValue(StatDefOf.Mass, true); + } + return num; + } + finally + { + ((IDisposable)(object)enumerator).Dispose(); } } return num; @@ -82,7 +92,7 @@ public static float Capacity(Pawn p) { return 0f; } - return p.BodySize * 35f; + return (float)(p.BodySize * 35.0); } public static bool CanEverCarryAnything(Pawn p) diff --git a/Assembly-CSharp/RimWorld/MedicalCareCategory.cs b/Assembly-CSharp/RimWorld/MedicalCareCategory.cs index 6b4d47f9d..80f3b7554 100644 --- a/Assembly-CSharp/RimWorld/MedicalCareCategory.cs +++ b/Assembly-CSharp/RimWorld/MedicalCareCategory.cs @@ -1,13 +1,11 @@ -using System; - namespace RimWorld { public enum MedicalCareCategory : byte { - NoCare, - NoMeds, - HerbalOrWorse, - NormalOrWorse, - Best + NoCare = 0, + NoMeds = 1, + HerbalOrWorse = 2, + NormalOrWorse = 3, + Best = 4 } } diff --git a/Assembly-CSharp/RimWorld/MedicalCareUtility.cs b/Assembly-CSharp/RimWorld/MedicalCareUtility.cs index 47e64fd74..5a8afcd29 100644 --- a/Assembly-CSharp/RimWorld/MedicalCareUtility.cs +++ b/Assembly-CSharp/RimWorld/MedicalCareUtility.cs @@ -16,7 +16,7 @@ public static class MedicalCareUtility public static void Reset() { - LongEventHandler.ExecuteWhenFinished(delegate + LongEventHandler.ExecuteWhenFinished((Action)delegate { MedicalCareUtility.careTextures = new Texture2D[5]; MedicalCareUtility.careTextures[0] = ContentFinder.Get("UI/Icons/Medical/NoCare", true); @@ -29,10 +29,10 @@ public static void Reset() public static void MedicalCareSetter(Rect rect, ref MedicalCareCategory medCare) { - Rect rect2 = new Rect(rect.x, rect.y, rect.width / 5f, rect.height); + Rect rect2 = new Rect(rect.x, rect.y, (float)(rect.width / 5.0), rect.height); for (int i = 0; i < 5; i++) { - MedicalCareCategory mc = (MedicalCareCategory)i; + MedicalCareCategory mc = (MedicalCareCategory)(byte)i; Widgets.DrawHighlightIfMouseover(rect2); GUI.DrawTexture(rect2, MedicalCareUtility.careTextures[i]); if (Widgets.ButtonInvisible(rect2, false)) @@ -44,7 +44,7 @@ public static void MedicalCareSetter(Rect rect, ref MedicalCareCategory medCare) { Widgets.DrawBox(rect2, 3); } - TooltipHandler.TipRegion(rect2, () => mc.GetLabel(), 632165 + i * 17); + TooltipHandler.TipRegion(rect2, (Func)(() => mc.GetLabel()), 632165 + i * 17); rect2.x += rect2.width; } } @@ -59,18 +59,30 @@ public static bool AllowsMedicine(this MedicalCareCategory cat, ThingDef meds) switch (cat) { case MedicalCareCategory.NoCare: + { return false; + } case MedicalCareCategory.NoMeds: + { return false; + } case MedicalCareCategory.HerbalOrWorse: + { return meds.GetStatValueAbstract(StatDefOf.MedicalPotency, null) <= ThingDefOf.HerbalMedicine.GetStatValueAbstract(StatDefOf.MedicalPotency, null); + } case MedicalCareCategory.NormalOrWorse: + { return meds.GetStatValueAbstract(StatDefOf.MedicalPotency, null) <= ThingDefOf.Medicine.GetStatValueAbstract(StatDefOf.MedicalPotency, null); + } case MedicalCareCategory.Best: + { return true; + } default: + { throw new InvalidOperationException(); } + } } } } diff --git a/Assembly-CSharp/RimWorld/MedicalRecipesUtility.cs b/Assembly-CSharp/RimWorld/MedicalRecipesUtility.cs index 259bdbc5f..8353d0c5f 100644 --- a/Assembly-CSharp/RimWorld/MedicalRecipesUtility.cs +++ b/Assembly-CSharp/RimWorld/MedicalRecipesUtility.cs @@ -9,14 +9,26 @@ internal class MedicalRecipesUtility { public static bool IsCleanAndDroppable(Pawn pawn, BodyPartRecord part) { - return !pawn.Dead && !pawn.RaceProps.Animal && part.def.spawnThingOnRemoved != null && MedicalRecipesUtility.IsClean(pawn, part); + if (pawn.Dead) + { + return false; + } + if (pawn.RaceProps.Animal) + { + return false; + } + return part.def.spawnThingOnRemoved != null && MedicalRecipesUtility.IsClean(pawn, part); } public static bool IsClean(Pawn pawn, BodyPartRecord part) { - return !pawn.Dead && !(from x in pawn.health.hediffSet.hediffs + if (pawn.Dead) + { + return false; + } + return !(from x in pawn.health.hediffSet.hediffs where x.Part == part - select x).Any(); + select x).Any(); } public static void RestorePartAndSpawnAllPreviousParts(Pawn pawn, BodyPartRecord part, IntVec3 pos, Map map) @@ -37,23 +49,22 @@ public static Thing SpawnNaturalPartIfClean(Pawn pawn, BodyPartRecord part, IntV public static void SpawnThingsFromHediffs(Pawn pawn, BodyPartRecord part, IntVec3 pos, Map map) { - if (!pawn.health.hediffSet.GetNotMissingParts(BodyPartHeight.Undefined, BodyPartDepth.Undefined).Contains(part)) + if (pawn.health.hediffSet.GetNotMissingParts(BodyPartHeight.Undefined, BodyPartDepth.Undefined).Contains(part)) { - return; - } - IEnumerable enumerable = from x in pawn.health.hediffSet.hediffs - where x.Part == part - select x; - foreach (Hediff current in enumerable) - { - if (current.def.spawnThingOnRemoved != null) + IEnumerable enumerable = from x in pawn.health.hediffSet.hediffs + where x.Part == part + select x; + foreach (Hediff item in enumerable) { - GenSpawn.Spawn(current.def.spawnThingOnRemoved, pos, map); + if (item.def.spawnThingOnRemoved != null) + { + GenSpawn.Spawn(item.def.spawnThingOnRemoved, pos, map); + } + } + for (int i = 0; i < part.parts.Count; i++) + { + MedicalRecipesUtility.SpawnThingsFromHediffs(pawn, part.parts[i], pos, map); } - } - for (int i = 0; i < part.parts.Count; i++) - { - MedicalRecipesUtility.SpawnThingsFromHediffs(pawn, part.parts[i], pos, map); } } } diff --git a/Assembly-CSharp/RimWorld/Medicine.cs b/Assembly-CSharp/RimWorld/Medicine.cs index 48c433f74..8db08399d 100644 --- a/Assembly-CSharp/RimWorld/Medicine.cs +++ b/Assembly-CSharp/RimWorld/Medicine.cs @@ -1,4 +1,3 @@ -using System; using System.Collections.Generic; using Verse; @@ -30,21 +29,18 @@ public static int GetMedicineCountToFullyHeal(Pawn pawn) num++; if (num > num2) { + Log.Error("Too many iterations."); break; } TendUtility.GetOptimalHediffsToTendWithSingleTreatment(pawn, true, Medicine.tmpHediffs, Medicine.tendableHediffsInTendPriorityOrder); - if (!Medicine.tmpHediffs.Any()) - { - goto IL_F6; - } + if (!Medicine.tmpHediffs.Any()) + break; num3++; for (int j = 0; j < Medicine.tmpHediffs.Count; j++) { Medicine.tendableHediffsInTendPriorityOrder.Remove(Medicine.tmpHediffs[j]); } } - Log.Error("Too many iterations."); - IL_F6: Medicine.tmpHediffs.Clear(); Medicine.tendableHediffsInTendPriorityOrder.Clear(); return num3; diff --git a/Assembly-CSharp/RimWorld/MemoryThoughtHandler.cs b/Assembly-CSharp/RimWorld/MemoryThoughtHandler.cs index 087f396e9..ae9228d3f 100644 --- a/Assembly-CSharp/RimWorld/MemoryThoughtHandler.cs +++ b/Assembly-CSharp/RimWorld/MemoryThoughtHandler.cs @@ -29,15 +29,15 @@ public void ExposeData() Scribe_Collections.Look(ref this.memories, "memories", LookMode.Deep, new object[0]); if (Scribe.mode == LoadSaveMode.PostLoadInit) { - for (int i = this.memories.Count - 1; i >= 0; i--) + for (int num = this.memories.Count - 1; num >= 0; num--) { - if (this.memories[i].def == null) + if (this.memories[num].def == null) { - this.memories.RemoveAt(i); + this.memories.RemoveAt(num); } else { - this.memories[i].pawn = this.pawn; + this.memories[num].pawn = this.pawn; } } } @@ -54,9 +54,9 @@ public void MemoryThoughtInterval() private void RemoveExpiredMemories() { - for (int i = this.memories.Count - 1; i >= 0; i--) + for (int num = this.memories.Count - 1; num >= 0; num--) { - Thought_Memory thought_Memory = this.memories[i]; + Thought_Memory thought_Memory = this.memories[num]; if (thought_Memory.ShouldDiscard) { this.RemoveMemory(thought_Memory); @@ -73,51 +73,54 @@ public void TryGainMemory(ThoughtDef def, Pawn otherPawn = null) if (!def.IsMemory) { Log.Error(def + " is not a memory thought."); - return; } - this.TryGainMemory((Thought_Memory)ThoughtMaker.MakeThought(def), otherPawn); + else + { + this.TryGainMemory((Thought_Memory)ThoughtMaker.MakeThought(def), otherPawn); + } } public void TryGainMemory(Thought_Memory newThought, Pawn otherPawn = null) { - if (!ThoughtUtility.CanGetThought(this.pawn, newThought.def)) + if (ThoughtUtility.CanGetThought(this.pawn, newThought.def)) { - return; - } - if (newThought is Thought_MemorySocial && newThought.otherPawn == null && otherPawn == null) - { - Log.Error("Can't gain social thought " + newThought.def + " because its otherPawn is null and otherPawn passed to this method is also null. Social thoughts must have otherPawn."); - return; - } - newThought.pawn = this.pawn; - newThought.otherPawn = otherPawn; - bool flag; - if (!newThought.TryMergeWithExistingMemory(out flag)) - { - this.memories.Add(newThought); - } - if (newThought.def.stackLimitPerPawn >= 0) - { - while (this.NumMemoriesInGroup(newThought) > newThought.def.stackLimitPerPawn) + if (newThought is Thought_MemorySocial && newThought.otherPawn == null && otherPawn == null) { - this.RemoveMemory(this.OldestMemoryInGroup(newThought)); + Log.Error("Can't gain social thought " + newThought.def + " because its otherPawn is null and otherPawn passed to this method is also null. Social thoughts must have otherPawn."); } - } - if (newThought.def.stackLimit >= 0) - { - while (this.NumMemoriesOfDef(newThought.def) > newThought.def.stackLimit) + else { - this.RemoveMemory(this.OldestMemoryOfDef(newThought.def)); + newThought.pawn = this.pawn; + newThought.otherPawn = otherPawn; + bool flag = default(bool); + if (!newThought.TryMergeWithExistingMemory(out flag)) + { + this.memories.Add(newThought); + } + if (newThought.def.stackLimitPerPawn >= 0) + { + while (this.NumMemoriesInGroup(newThought) > newThought.def.stackLimitPerPawn) + { + this.RemoveMemory(this.OldestMemoryInGroup(newThought)); + } + } + if (newThought.def.stackLimit >= 0) + { + while (this.NumMemoriesOfDef(newThought.def) > newThought.def.stackLimit) + { + this.RemoveMemory(this.OldestMemoryOfDef(newThought.def)); + } + } + if (newThought.def.thoughtToMake != null) + { + this.TryGainMemory(newThought.def.thoughtToMake, newThought.otherPawn); + } + if (flag && newThought.def.showBubble && this.pawn.Spawned) + { + MoteMaker.MakeMoodThoughtBubble(this.pawn, newThought); + } } } - if (newThought.def.thoughtToMake != null) - { - this.TryGainMemory(newThought.def.thoughtToMake, newThought.otherPawn); - } - if (flag && newThought.def.showBubble && this.pawn.Spawned) - { - MoteMaker.MakeMoodThoughtBubble(this.pawn, newThought); - } } public Thought_Memory OldestMemoryInGroup(Thought_Memory group) @@ -127,13 +130,10 @@ public Thought_Memory OldestMemoryInGroup(Thought_Memory group) for (int i = 0; i < this.memories.Count; i++) { Thought_Memory thought_Memory = this.memories[i]; - if (thought_Memory.GroupsWith(group)) + if (thought_Memory.GroupsWith(group) && thought_Memory.age > num) { - if (thought_Memory.age > num) - { - result = thought_Memory; - num = thought_Memory.age; - } + result = thought_Memory; + num = thought_Memory.age; } } return result; @@ -146,13 +146,10 @@ public Thought_Memory OldestMemoryOfDef(ThoughtDef def) for (int i = 0; i < this.memories.Count; i++) { Thought_Memory thought_Memory = this.memories[i]; - if (thought_Memory.def == def) + if (thought_Memory.def == def && thought_Memory.age > num) { - if (thought_Memory.age > num) - { - result = thought_Memory; - num = thought_Memory.age; - } + result = thought_Memory; + num = thought_Memory.age; } } return result; @@ -163,9 +160,8 @@ public void RemoveMemory(Thought_Memory th) if (!this.memories.Remove(th)) { Log.Warning("Tried to remove memory thought of def " + th.def.defName + " but it's not here."); - return; } - if (th.otherPawn != null && th.otherPawn.IsWorldPawn()) + else if (th.otherPawn != null && th.otherPawn.IsWorldPawn()) { Find.WorldPawns.DiscardIfUnimportant(th.otherPawn); } @@ -201,12 +197,24 @@ public void RemoveMemoriesOfDefWhereOtherPawnIs(ThoughtDef def, Pawn otherPawn) { while (true) { - Thought_Memory thought_Memory = this.memories.Find((Thought_Memory x) => x.def == def && x.otherPawn == otherPawn); - if (thought_Memory == null) + Thought_Memory thought_Memory = this.memories.Find((Predicate)delegate(Thought_Memory x) { - break; + if (x.def != def) + { + return false; + } + if (x.otherPawn == otherPawn) + { + return true; + } + return false; + }); + if (thought_Memory != null) + { + this.RemoveMemory(thought_Memory); + continue; } - this.RemoveMemory(thought_Memory); + break; } } @@ -215,16 +223,19 @@ public void RemoveMemoriesOfDef(ThoughtDef def) if (!def.IsMemory) { Log.Warning(def + " is not a memory thought."); - return; } - while (true) + else { - Thought_Memory thought_Memory = this.memories.Find((Thought_Memory x) => x.def == def); - if (thought_Memory == null) + while (true) { + Thought_Memory thought_Memory = this.memories.Find((Predicate)((Thought_Memory x) => x.def == def)); + if (thought_Memory != null) + { + this.RemoveMemory(thought_Memory); + continue; + } break; } - this.RemoveMemory(thought_Memory); } } @@ -233,16 +244,19 @@ public void RemoveMemoriesOfDefIf(ThoughtDef def, Func pre if (!def.IsMemory) { Log.Warning(def + " is not a memory thought."); - return; } - while (true) + else { - Thought_Memory thought_Memory = this.memories.Find((Thought_Memory x) => x.def == def && predicate(x)); - if (thought_Memory == null) + while (true) { + Thought_Memory thought_Memory = this.memories.Find((Predicate)((Thought_Memory x) => x.def == def && predicate(x))); + if (thought_Memory != null) + { + this.RemoveMemory(thought_Memory); + continue; + } break; } - this.RemoveMemory(thought_Memory); } } diff --git a/Assembly-CSharp/RimWorld/MentalStateDefOf.cs b/Assembly-CSharp/RimWorld/MentalStateDefOf.cs index 7bd2be5cb..c0fcb81a5 100644 --- a/Assembly-CSharp/RimWorld/MentalStateDefOf.cs +++ b/Assembly-CSharp/RimWorld/MentalStateDefOf.cs @@ -1,4 +1,3 @@ -using System; using Verse; namespace RimWorld diff --git a/Assembly-CSharp/RimWorld/MeshUtility.cs b/Assembly-CSharp/RimWorld/MeshUtility.cs index da1072c94..ed8ce3845 100644 --- a/Assembly-CSharp/RimWorld/MeshUtility.cs +++ b/Assembly-CSharp/RimWorld/MeshUtility.cs @@ -14,68 +14,72 @@ public static class MeshUtility public static void RemoveVertices(List verts, List tris, Predicate predicate) { - int i = 0; + int num = 0; int count = tris.Count; - while (i < count) + while (num < count) { - TriangleIndices triangleIndices = tris[i]; + TriangleIndices triangleIndices = tris[num]; if (predicate(verts[triangleIndices.v1]) || predicate(verts[triangleIndices.v2]) || predicate(verts[triangleIndices.v3])) { - tris[i] = new TriangleIndices(-1, -1, -1); + tris[num] = new TriangleIndices(-1, -1, -1); } - i++; + num++; } - tris.RemoveAll((TriangleIndices x) => x.v1 == -1); + tris.RemoveAll((Predicate)((TriangleIndices x) => x.v1 == -1)); MeshUtility.RemoveUnusedVertices(verts, tris); } public static void RemoveUnusedVertices(List verts, List tris) { MeshUtility.vertIsUsed.Clear(); - int i = 0; + int num = 0; int count = verts.Count; - while (i < count) + while (num < count) { MeshUtility.vertIsUsed.Add(false); - i++; + num++; } - int j = 0; + int num2 = 0; int count2 = tris.Count; - while (j < count2) + while (num2 < count2) { - TriangleIndices triangleIndices = tris[j]; + TriangleIndices triangleIndices = tris[num2]; MeshUtility.vertIsUsed[triangleIndices.v1] = true; MeshUtility.vertIsUsed[triangleIndices.v2] = true; MeshUtility.vertIsUsed[triangleIndices.v3] = true; - j++; + num2++; } - int num = 0; + int num3 = 0; MeshUtility.offsets.Clear(); - int k = 0; + int num4 = 0; int count3 = verts.Count; - while (k < count3) + while (num4 < count3) { - if (!MeshUtility.vertIsUsed[k]) + if (!MeshUtility.vertIsUsed[num4]) { - num++; + num3++; } - MeshUtility.offsets.Add(num); - k++; + MeshUtility.offsets.Add(num3); + num4++; } - int l = 0; + int num5 = 0; int count4 = tris.Count; - while (l < count4) + while (num5 < count4) { - TriangleIndices triangleIndices2 = tris[l]; - tris[l] = new TriangleIndices(triangleIndices2.v1 - MeshUtility.offsets[triangleIndices2.v1], triangleIndices2.v2 - MeshUtility.offsets[triangleIndices2.v2], triangleIndices2.v3 - MeshUtility.offsets[triangleIndices2.v3]); - l++; + TriangleIndices triangleIndices2 = tris[num5]; + tris[num5] = new TriangleIndices(triangleIndices2.v1 - MeshUtility.offsets[triangleIndices2.v1], triangleIndices2.v2 - MeshUtility.offsets[triangleIndices2.v2], triangleIndices2.v3 - MeshUtility.offsets[triangleIndices2.v3]); + num5++; } - verts.RemoveAll((Vector3 elem, int index) => !MeshUtility.vertIsUsed[index]); + verts.RemoveAll((Func)((Vector3 elem, int index) => !MeshUtility.vertIsUsed[index])); } public static bool Visible(Vector3 point, float radius, Vector3 viewCenter, float viewAngle) { - return viewAngle >= 180f || Vector3.Angle(viewCenter * radius, point) <= viewAngle; + if (viewAngle >= 180.0) + { + return true; + } + return Vector3.Angle(viewCenter * radius, point) <= viewAngle; } public static Color32 MutateAlpha(this Color32 input, byte newAlpha) diff --git a/Assembly-CSharp/RimWorld/MineStrikeManager.cs b/Assembly-CSharp/RimWorld/MineStrikeManager.cs index 1ecf5df53..64d10a27b 100644 --- a/Assembly-CSharp/RimWorld/MineStrikeManager.cs +++ b/Assembly-CSharp/RimWorld/MineStrikeManager.cs @@ -20,32 +20,26 @@ public void ExposeData() public void CheckStruckOre(IntVec3 justMinedPos, ThingDef justMinedDef, Thing miner) { - if (miner.Faction != Faction.OfPlayer) + if (miner.Faction == Faction.OfPlayer) { - return; - } - for (int i = 0; i < 4; i++) - { - IntVec3 intVec = justMinedPos + GenAdj.CardinalDirections[i]; - if (intVec.InBounds(miner.Map)) + for (int i = 0; i < 4; i++) { - Building edifice = intVec.GetEdifice(miner.Map); - if (edifice != null && edifice.def != justMinedDef && this.MineableIsWorthLetter(edifice.def) && !this.AlreadyVisibleNearby(intVec, miner.Map, edifice.def) && !this.RecentlyStruck(intVec, edifice.def)) + IntVec3 intVec = justMinedPos + GenAdj.CardinalDirections[i]; + if (intVec.InBounds(miner.Map)) { - StrikeRecord item = default(StrikeRecord); - item.cell = intVec; - item.def = edifice.def; - item.ticksGame = Find.TickManager.TicksGame; - this.strikeRecords.Add(item); - Messages.Message("StruckMineable".Translate(new object[] - { - edifice.def.label - }), edifice, MessageSound.Benefit); - TaleRecorder.RecordTale(TaleDefOf.StruckMineable, new object[] + Building edifice = intVec.GetEdifice(miner.Map); + if (edifice != null && edifice.def != justMinedDef && this.MineableIsWorthLetter(edifice.def) && !this.AlreadyVisibleNearby(intVec, miner.Map, edifice.def) && !this.RecentlyStruck(intVec, edifice.def)) { - miner, - edifice - }); + StrikeRecord item = new StrikeRecord + { + cell = intVec, + def = edifice.def, + ticksGame = Find.TickManager.TicksGame + }; + this.strikeRecords.Add(item); + Messages.Message("StruckMineable".Translate(edifice.def.label), (Thing)edifice, MessageSound.Benefit); + TaleRecorder.RecordTale(TaleDefOf.StruckMineable, miner, edifice); + } } } } @@ -71,15 +65,23 @@ public bool AlreadyVisibleNearby(IntVec3 center, Map map, ThingDef mineableDef) private bool RecentlyStruck(IntVec3 cell, ThingDef def) { - for (int i = this.strikeRecords.Count - 1; i >= 0; i--) + for (int num = this.strikeRecords.Count - 1; num >= 0; num--) { - if (this.strikeRecords[i].Expired) + if (this.strikeRecords[num].Expired) { - this.strikeRecords.RemoveAt(i); + this.strikeRecords.RemoveAt(num); } - else if (this.strikeRecords[i].def == def && this.strikeRecords[i].cell.InHorDistOf(cell, 12f)) + else { - return true; + StrikeRecord strikeRecord = this.strikeRecords[num]; + if (strikeRecord.def == def) + { + StrikeRecord strikeRecord2 = this.strikeRecords[num]; + if (strikeRecord2.cell.InHorDistOf(cell, 12f)) + { + return true; + } + } } } return false; @@ -87,15 +89,23 @@ private bool RecentlyStruck(IntVec3 cell, ThingDef def) private bool MineableIsWorthLetter(ThingDef mineableDef) { - return mineableDef.mineable && mineableDef.building.mineableThing.GetStatValueAbstract(StatDefOf.MarketValue, null) * (float)mineableDef.building.mineableYield > 10f; + return mineableDef.mineable && mineableDef.building.mineableThing.GetStatValueAbstract(StatDefOf.MarketValue, null) * (float)mineableDef.building.mineableYield > 10.0; } public string DebugStrikeRecords() { StringBuilder stringBuilder = new StringBuilder(); - foreach (StrikeRecord current in this.strikeRecords) + List.Enumerator enumerator = this.strikeRecords.GetEnumerator(); + try + { + while (enumerator.MoveNext()) + { + stringBuilder.AppendLine(enumerator.Current.ToString()); + } + } + finally { - stringBuilder.AppendLine(current.ToString()); + ((IDisposable)(object)enumerator).Dispose(); } return stringBuilder.ToString(); } diff --git a/Assembly-CSharp/RimWorld/MineUtility.cs b/Assembly-CSharp/RimWorld/MineUtility.cs index 0821c4bf9..b2c7357b5 100644 --- a/Assembly-CSharp/RimWorld/MineUtility.cs +++ b/Assembly-CSharp/RimWorld/MineUtility.cs @@ -1,4 +1,3 @@ -using System; using System.Collections.Generic; using Verse; diff --git a/Assembly-CSharp/RimWorld/Mineable.cs b/Assembly-CSharp/RimWorld/Mineable.cs index e21c46b3b..bf40d2ba0 100644 --- a/Assembly-CSharp/RimWorld/Mineable.cs +++ b/Assembly-CSharp/RimWorld/Mineable.cs @@ -1,4 +1,3 @@ -using System; using UnityEngine; using Verse; @@ -19,17 +18,16 @@ public override void ExposeData() public override void PreApplyDamage(DamageInfo dinfo, out bool absorbed) { base.PreApplyDamage(dinfo, out absorbed); - if (absorbed) + if (!absorbed) { - return; + if (base.def.building.mineableThing != null && base.def.building.mineableYieldWasteable && dinfo.Def == DamageDefOf.Mining && dinfo.Instigator != null && dinfo.Instigator is Pawn) + { + int num = Mathf.Min(dinfo.Amount, this.HitPoints); + float num2 = (float)num / (float)base.MaxHitPoints; + this.yieldPct += num2 * dinfo.Instigator.GetStatValue(StatDefOf.MiningYield, true); + } + absorbed = false; } - if (this.def.building.mineableThing != null && this.def.building.mineableYieldWasteable && dinfo.Def == DamageDefOf.Mining && dinfo.Instigator != null && dinfo.Instigator is Pawn) - { - int num = Mathf.Min(dinfo.Amount, this.HitPoints); - float num2 = (float)num / (float)base.MaxHitPoints; - this.yieldPct += num2 * dinfo.Instigator.GetStatValue(StatDefOf.MiningYield, true); - } - absorbed = false; } public void DestroyMined(Pawn pawn) @@ -51,22 +49,17 @@ public override void Destroy(DestroyMode mode) private void TrySpawnYield(Map map, float yieldChance, bool moteOnWaste) { - if (this.def.building.mineableThing == null) - { - return; - } - if (Rand.Value > this.def.building.mineableDropChance) - { - return; - } - int num = this.def.building.mineableYield; - if (this.def.building.mineableYieldWasteable) + if (base.def.building.mineableThing != null && !(Rand.Value > base.def.building.mineableDropChance)) { - num = Mathf.Max(1, GenMath.RoundRandom((float)num * this.yieldPct)); + int num = base.def.building.mineableYield; + if (base.def.building.mineableYieldWasteable) + { + num = Mathf.Max(1, GenMath.RoundRandom((float)num * this.yieldPct)); + } + Thing thing = ThingMaker.MakeThing(base.def.building.mineableThing, null); + thing.stackCount = num; + GenSpawn.Spawn(thing, base.Position, map); } - Thing thing = ThingMaker.MakeThing(this.def.building.mineableThing, null); - thing.stackCount = num; - GenSpawn.Spawn(thing, base.Position, map); } } } diff --git a/Assembly-CSharp/RimWorld/MinifiedThing.cs b/Assembly-CSharp/RimWorld/MinifiedThing.cs index 469bd9e9c..096e0862a 100644 --- a/Assembly-CSharp/RimWorld/MinifiedThing.cs +++ b/Assembly-CSharp/RimWorld/MinifiedThing.cs @@ -1,6 +1,4 @@ -using System; using System.Collections.Generic; -using System.Diagnostics; using UnityEngine; using Verse; using Verse.Sound; @@ -31,15 +29,14 @@ public Thing InnerThing } set { - if (value == this.InnerThing) + if (value != this.InnerThing) { - return; - } - if (this.innerContainer.Count != 0) - { - this.innerContainer.ClearAndDestroyContents(DestroyMode.Vanish); + if (this.innerContainer.Count != 0) + { + this.innerContainer.ClearAndDestroyContents(DestroyMode.Vanish); + } + this.innerContainer.TryAdd(value, true); } - this.innerContainer.TryAdd(value, true); } } @@ -50,7 +47,7 @@ public override Graphic Graphic if (this.cachedGraphic == null) { this.cachedGraphic = this.InnerThing.Graphic.ExtractInnerGraphicFor(this.InnerThing); - if ((float)this.InnerThing.def.size.x > 1.1f || (float)this.InnerThing.def.size.z > 1.1f) + if ((float)this.InnerThing.def.size.x > 1.1000000238418579 || (float)this.InnerThing.def.size.z > 1.1000000238418579) { Vector2 minifiedDrawSize = this.GetMinifiedDrawSize(this.InnerThing.def.size.ToVector2(), 1.1f); Vector2 newDrawSize = new Vector2(minifiedDrawSize.x / (float)this.InnerThing.def.size.x * this.cachedGraphic.drawSize.x, minifiedDrawSize.y / (float)this.InnerThing.def.size.z * this.cachedGraphic.drawSize.y); @@ -105,13 +102,17 @@ public override Thing SplitOff(int count) public override bool CanStackWith(Thing other) { MinifiedThing minifiedThing = other as MinifiedThing; - return minifiedThing != null && base.CanStackWith(other) && this.InnerThing.CanStackWith(minifiedThing.InnerThing); + if (minifiedThing == null) + { + return false; + } + return base.CanStackWith(other) && this.InnerThing.CanStackWith(minifiedThing.InnerThing); } public override void ExposeData() { base.ExposeData(); - Scribe_Deep.Look(ref this.innerContainer, "innerContainer", new object[] + Scribe_Deep.Look(ref this.innerContainer, "innerContainer", new object[1] { this }); @@ -166,14 +167,13 @@ public override void PreTraded(TradeAction action, Pawn playerNegotiator, ITrade InstallBlueprintUtility.CancelBlueprintsFor(this); } - [DebuggerHidden] public override IEnumerable GetGizmos() { - MinifiedThing.c__Iterator142 c__Iterator = new MinifiedThing.c__Iterator142(); - c__Iterator.<>f__this = this; - MinifiedThing.c__Iterator142 expr_0E = c__Iterator; - expr_0E.$PC = -2; - return expr_0E; + foreach (Gizmo gizmo in base.GetGizmos()) + { + yield return gizmo; + } + yield return (Gizmo)InstallationDesignatorDatabase.DesignatorFor(base.def); } public override string GetInspectString() @@ -186,7 +186,7 @@ public override string GetInspectString() private Vector2 GetMinifiedDrawSize(Vector2 drawSize, float maxSideLength) { float num = maxSideLength / Mathf.Max(drawSize.x, drawSize.y); - if (num >= 1f) + if (num >= 1.0) { return drawSize; } @@ -197,5 +197,11 @@ virtual IThingHolder get_ParentHolder() { return base.ParentHolder; } + + IThingHolder IThingHolder.get_ParentHolder() + { + //ILSpy generated this explicit interface implementation from .override directive in get_ParentHolder + return this.get_ParentHolder(); + } } } diff --git a/Assembly-CSharp/RimWorld/MinifyUtility.cs b/Assembly-CSharp/RimWorld/MinifyUtility.cs index 76dbcb0a4..e2e0127fb 100644 --- a/Assembly-CSharp/RimWorld/MinifyUtility.cs +++ b/Assembly-CSharp/RimWorld/MinifyUtility.cs @@ -1,4 +1,3 @@ -using System; using Verse; using Verse.Sound; @@ -31,14 +30,7 @@ public static MinifiedThing MakeMinified(this Thing thing) } if (minifiedThing.InnerThing.stackCount > 1) { - Log.Warning(string.Concat(new object[] - { - "Tried to minify ", - thing.LabelCap, - " with stack count ", - minifiedThing.InnerThing.stackCount, - ". Clamped stack count to 1." - })); + Log.Warning("Tried to minify " + thing.LabelCap + " with stack count " + minifiedThing.InnerThing.stackCount + ". Clamped stack count to 1."); minifiedThing.InnerThing.stackCount = 1; } return minifiedThing; diff --git a/Assembly-CSharp/RimWorld/MiscDebugDrawer.cs b/Assembly-CSharp/RimWorld/MiscDebugDrawer.cs index 6d2ac3b63..dfd35edbb 100644 --- a/Assembly-CSharp/RimWorld/MiscDebugDrawer.cs +++ b/Assembly-CSharp/RimWorld/MiscDebugDrawer.cs @@ -1,4 +1,5 @@ using System; +using System.Collections.Generic; using Verse; namespace RimWorld @@ -7,20 +8,26 @@ public static class MiscDebugDrawer { public static void DebugDrawInteractionCells() { - if (Find.VisibleMap == null) + Map visibleMap = Find.VisibleMap; + if (visibleMap != null && DebugViewSettings.drawInteractionCells) { - return; - } - if (DebugViewSettings.drawInteractionCells) - { - foreach (object current in Find.Selector.SelectedObjects) + List.Enumerator enumerator = Find.Selector.SelectedObjects.GetEnumerator(); + try { - Thing thing = current as Thing; - if (thing != null) + while (enumerator.MoveNext()) { - CellRenderer.RenderCell(thing.InteractionCell, 0.5f); + object current = enumerator.Current; + Thing thing = current as Thing; + if (thing != null) + { + CellRenderer.RenderCell(thing.InteractionCell, 0.5f); + } } } + finally + { + ((IDisposable)(object)enumerator).Dispose(); + } } } } diff --git a/Assembly-CSharp/RimWorld/MoteBubble.cs b/Assembly-CSharp/RimWorld/MoteBubble.cs index 4dff16cb1..81f70849b 100644 --- a/Assembly-CSharp/RimWorld/MoteBubble.cs +++ b/Assembly-CSharp/RimWorld/MoteBubble.cs @@ -1,4 +1,3 @@ -using System; using UnityEngine; using Verse; @@ -22,27 +21,30 @@ public void SetupMoteBubble(Texture2D icon, Pawn target) public override void Draw() { base.Draw(); - if (this.iconMat != null) + if ((Object)this.iconMat != (Object)null) { Vector3 drawPos = this.DrawPos; drawPos.y += 0.01f; float num = Graphic_Mote.CalculateMoteAlpha(this); - if (num <= 0f) + if (!(num <= 0.0)) { - return; + Color instanceColor = base.instanceColor; + instanceColor.a *= num; + Material material = this.iconMat; + if (instanceColor != material.color) + { + material = MaterialPool.MatFrom((Texture2D)material.mainTexture, material.shader, instanceColor); + } + Vector3 s = new Vector3((float)(base.def.graphicData.drawSize.x * 0.63999998569488525), 1f, (float)(base.def.graphicData.drawSize.y * 0.63999998569488525)); + Matrix4x4 matrix = default(Matrix4x4); + matrix.SetTRS(drawPos, Quaternion.identity, s); + Graphics.DrawMesh(MeshPool.plane10, matrix, material, 0); + goto IL_00f1; } - Color instanceColor = this.instanceColor; - instanceColor.a *= num; - Material material = this.iconMat; - if (instanceColor != material.color) - { - material = MaterialPool.MatFrom((Texture2D)material.mainTexture, material.shader, instanceColor); - } - Vector3 s = new Vector3(this.def.graphicData.drawSize.x * 0.64f, 1f, this.def.graphicData.drawSize.y * 0.64f); - Matrix4x4 matrix = default(Matrix4x4); - matrix.SetTRS(drawPos, Quaternion.identity, s); - Graphics.DrawMesh(MeshPool.plane10, matrix, material, 0); + return; } + goto IL_00f1; + IL_00f1: if (this.arrowTarget != null) { Vector3 a = this.arrowTarget.TrueCenter(); diff --git a/Assembly-CSharp/RimWorld/MoteMaker.cs b/Assembly-CSharp/RimWorld/MoteMaker.cs index f61d669c4..f018943b2 100644 --- a/Assembly-CSharp/RimWorld/MoteMaker.cs +++ b/Assembly-CSharp/RimWorld/MoteMaker.cs @@ -1,4 +1,3 @@ -using System; using System.Collections.Generic; using UnityEngine; using Verse; @@ -7,7 +6,7 @@ namespace RimWorld { public static class MoteMaker { - private static IntVec3[] UpRightPattern = new IntVec3[] + private static IntVec3[] UpRightPattern = new IntVec3[4] { new IntVec3(0, 0, 0), new IntVec3(1, 0, 0), @@ -17,19 +16,21 @@ public static class MoteMaker public static Mote ThrowMetaIcon(IntVec3 cell, Map map, ThingDef moteDef) { - if (!cell.ShouldSpawnMotesAt(map) || map.moteCounter.Saturated) + if (cell.ShouldSpawnMotesAt(map) && !map.moteCounter.Saturated) { - return null; + MoteThrown moteThrown = (MoteThrown)ThingMaker.MakeThing(moteDef, null); + moteThrown.Scale = 0.7f; + moteThrown.rotationRate = Rand.Range(-3f, 3f); + moteThrown.exactPosition = cell.ToVector3Shifted(); + MoteThrown obj = moteThrown; + obj.exactPosition += new Vector3(0.35f, 0f, 0.35f); + MoteThrown obj2 = moteThrown; + obj2.exactPosition += new Vector3(Rand.Value, 0f, Rand.Value) * 0.1f; + moteThrown.SetVelocity((float)Rand.Range(30, 60), 0.42f); + GenSpawn.Spawn(moteThrown, cell, map); + return moteThrown; } - MoteThrown moteThrown = (MoteThrown)ThingMaker.MakeThing(moteDef, null); - moteThrown.Scale = 0.7f; - moteThrown.rotationRate = Rand.Range(-3f, 3f); - moteThrown.exactPosition = cell.ToVector3Shifted(); - moteThrown.exactPosition += new Vector3(0.35f, 0f, 0.35f); - moteThrown.exactPosition += new Vector3(Rand.Value, 0f, Rand.Value) * 0.1f; - moteThrown.SetVelocity((float)Rand.Range(30, 60), 0.42f); - GenSpawn.Spawn(moteThrown, cell, map); - return moteThrown; + return null; } public static void MakeStaticMote(IntVec3 cell, Map map, ThingDef moteDef, float scale = 1f) @@ -39,38 +40,36 @@ public static void MakeStaticMote(IntVec3 cell, Map map, ThingDef moteDef, float public static void MakeStaticMote(Vector3 loc, Map map, ThingDef moteDef, float scale = 1f) { - if (!loc.ShouldSpawnMotesAt(map) || map.moteCounter.Saturated) + if (loc.ShouldSpawnMotesAt(map) && !map.moteCounter.Saturated) { - return; + Mote mote = (Mote)ThingMaker.MakeThing(moteDef, null); + mote.exactPosition = loc; + mote.Scale = scale; + GenSpawn.Spawn(mote, loc.ToIntVec3(), map); } - Mote mote = (Mote)ThingMaker.MakeThing(moteDef, null); - mote.exactPosition = loc; - mote.Scale = scale; - GenSpawn.Spawn(mote, loc.ToIntVec3(), map); } - public static void ThrowText(Vector3 loc, Map map, string text, float timeBeforeStartFadeout = -1f) + public static void ThrowText(Vector3 loc, Map map, string text, float timeBeforeStartFadeout = -1) { MoteMaker.ThrowText(loc, map, text, Color.white, timeBeforeStartFadeout); } - public static void ThrowText(Vector3 loc, Map map, string text, Color color, float timeBeforeStartFadeout = -1f) + public static void ThrowText(Vector3 loc, Map map, string text, Color color, float timeBeforeStartFadeout = -1) { IntVec3 intVec = loc.ToIntVec3(); - if (!intVec.InBounds(map)) - { - return; - } - MoteText moteText = (MoteText)ThingMaker.MakeThing(ThingDefOf.Mote_Text, null); - moteText.exactPosition = loc; - moteText.SetVelocity((float)Rand.Range(5, 35), Rand.Range(0.42f, 0.45f)); - moteText.text = text; - moteText.textColor = color; - if (timeBeforeStartFadeout >= 0f) + if (intVec.InBounds(map)) { - moteText.overrideTimeBeforeStartFadeout = timeBeforeStartFadeout; + MoteText moteText = (MoteText)ThingMaker.MakeThing(ThingDefOf.Mote_Text, null); + moteText.exactPosition = loc; + moteText.SetVelocity((float)Rand.Range(5, 35), Rand.Range(0.42f, 0.45f)); + moteText.text = text; + moteText.textColor = color; + if (timeBeforeStartFadeout >= 0.0) + { + moteText.overrideTimeBeforeStartFadeout = timeBeforeStartFadeout; + } + GenSpawn.Spawn(moteText, intVec, map); } - GenSpawn.Spawn(moteText, intVec, map); } public static void ThrowMetaPuffs(CellRect rect, Map map) @@ -91,7 +90,7 @@ public static void ThrowMetaPuffs(TargetInfo targ) { Vector3 a = (!targ.HasThing) ? targ.Cell.ToVector3Shifted() : targ.Thing.TrueCenter(); int num = Rand.RangeInclusive(4, 6); - for (int i = 0; i < num; i++) + for (int num2 = 0; num2 < num; num2++) { Vector3 loc = a + new Vector3(Rand.Range(-0.5f, 0.5f), 0f, Rand.Range(-0.5f, 0.5f)); MoteMaker.ThrowMetaPuff(loc, targ.Map); @@ -100,16 +99,15 @@ public static void ThrowMetaPuffs(TargetInfo targ) public static void ThrowMetaPuff(Vector3 loc, Map map) { - if (!loc.ShouldSpawnMotesAt(map)) + if (loc.ShouldSpawnMotesAt(map)) { - return; + MoteThrown moteThrown = (MoteThrown)ThingMaker.MakeThing(ThingDefOf.Mote_MetaPuff, null); + moteThrown.Scale = 1.9f; + moteThrown.rotationRate = (float)Rand.Range(-60, 60); + moteThrown.exactPosition = loc; + moteThrown.SetVelocity((float)Rand.Range(0, 360), Rand.Range(0.6f, 0.78f)); + GenSpawn.Spawn(moteThrown, loc.ToIntVec3(), map); } - MoteThrown moteThrown = (MoteThrown)ThingMaker.MakeThing(ThingDefOf.Mote_MetaPuff, null); - moteThrown.Scale = 1.9f; - moteThrown.rotationRate = (float)Rand.Range(-60, 60); - moteThrown.exactPosition = loc; - moteThrown.SetVelocity((float)Rand.Range(0, 360), Rand.Range(0.6f, 0.78f)); - GenSpawn.Spawn(moteThrown, loc.ToIntVec3(), map); } private static MoteThrown NewBaseAirPuff() @@ -122,30 +120,31 @@ private static MoteThrown NewBaseAirPuff() public static void ThrowAirPuffUp(Vector3 loc, Map map) { - if (!loc.ToIntVec3().ShouldSpawnMotesAt(map) || map.moteCounter.SaturatedLowPriority) + if (loc.ToIntVec3().ShouldSpawnMotesAt(map) && !map.moteCounter.SaturatedLowPriority) { - return; + MoteThrown moteThrown = MoteMaker.NewBaseAirPuff(); + moteThrown.exactPosition = loc; + MoteThrown obj = moteThrown; + obj.exactPosition += new Vector3(Rand.Range(-0.02f, 0.02f), 0f, Rand.Range(-0.02f, 0.02f)); + moteThrown.SetVelocity((float)Rand.Range(-45, 45), Rand.Range(1.2f, 1.5f)); + GenSpawn.Spawn(moteThrown, loc.ToIntVec3(), map); } - MoteThrown moteThrown = MoteMaker.NewBaseAirPuff(); - moteThrown.exactPosition = loc; - moteThrown.exactPosition += new Vector3(Rand.Range(-0.02f, 0.02f), 0f, Rand.Range(-0.02f, 0.02f)); - moteThrown.SetVelocity((float)Rand.Range(-45, 45), Rand.Range(1.2f, 1.5f)); - GenSpawn.Spawn(moteThrown, loc.ToIntVec3(), map); } internal static void ThrowBreathPuff(Vector3 loc, Map map, float throwAngle, Vector3 inheritVelocity) { - if (!loc.ToIntVec3().ShouldSpawnMotesAt(map) || map.moteCounter.SaturatedLowPriority) + if (loc.ToIntVec3().ShouldSpawnMotesAt(map) && !map.moteCounter.SaturatedLowPriority) { - return; + MoteThrown moteThrown = MoteMaker.NewBaseAirPuff(); + moteThrown.exactPosition = loc; + MoteThrown obj = moteThrown; + obj.exactPosition += new Vector3(Rand.Range(-0.005f, 0.005f), 0f, Rand.Range(-0.005f, 0.005f)); + moteThrown.SetVelocity(throwAngle + (float)Rand.Range(-10, 10), Rand.Range(0.1f, 0.8f)); + MoteThrown obj2 = moteThrown; + obj2.Velocity += inheritVelocity * 0.5f; + moteThrown.Scale = Rand.Range(0.6f, 0.7f); + GenSpawn.Spawn(moteThrown, loc.ToIntVec3(), map); } - MoteThrown moteThrown = MoteMaker.NewBaseAirPuff(); - moteThrown.exactPosition = loc; - moteThrown.exactPosition += new Vector3(Rand.Range(-0.005f, 0.005f), 0f, Rand.Range(-0.005f, 0.005f)); - moteThrown.SetVelocity(throwAngle + (float)Rand.Range(-10, 10), Rand.Range(0.1f, 0.8f)); - moteThrown.Velocity += inheritVelocity * 0.5f; - moteThrown.Scale = Rand.Range(0.6f, 0.7f); - GenSpawn.Spawn(moteThrown, loc.ToIntVec3(), map); } public static void ThrowDustPuff(IntVec3 cell, Map map, float scale) @@ -156,131 +155,124 @@ public static void ThrowDustPuff(IntVec3 cell, Map map, float scale) public static void ThrowDustPuff(Vector3 loc, Map map, float scale) { - if (!loc.ShouldSpawnMotesAt(map) || map.moteCounter.SaturatedLowPriority) + if (loc.ShouldSpawnMotesAt(map) && !map.moteCounter.SaturatedLowPriority) { - return; + MoteThrown moteThrown = (MoteThrown)ThingMaker.MakeThing(ThingDefOf.Mote_DustPuff, null); + moteThrown.Scale = (float)(1.8999999761581421 * scale); + moteThrown.rotationRate = (float)Rand.Range(-60, 60); + moteThrown.exactPosition = loc; + moteThrown.SetVelocity((float)Rand.Range(0, 360), Rand.Range(0.6f, 0.75f)); + GenSpawn.Spawn(moteThrown, loc.ToIntVec3(), map); } - MoteThrown moteThrown = (MoteThrown)ThingMaker.MakeThing(ThingDefOf.Mote_DustPuff, null); - moteThrown.Scale = 1.9f * scale; - moteThrown.rotationRate = (float)Rand.Range(-60, 60); - moteThrown.exactPosition = loc; - moteThrown.SetVelocity((float)Rand.Range(0, 360), Rand.Range(0.6f, 0.75f)); - GenSpawn.Spawn(moteThrown, loc.ToIntVec3(), map); } public static void ThrowSmoke(Vector3 loc, Map map, float size) { - if (!loc.ShouldSpawnMotesAt(map) || map.moteCounter.SaturatedLowPriority) + if (loc.ShouldSpawnMotesAt(map) && !map.moteCounter.SaturatedLowPriority) { - return; + MoteThrown moteThrown = (MoteThrown)ThingMaker.MakeThing(ThingDefOf.Mote_Smoke, null); + moteThrown.Scale = Rand.Range(1.5f, 2.5f) * size; + moteThrown.rotationRate = Rand.Range(-30f, 30f); + moteThrown.exactPosition = loc; + moteThrown.SetVelocity((float)Rand.Range(30, 40), Rand.Range(0.5f, 0.7f)); + GenSpawn.Spawn(moteThrown, loc.ToIntVec3(), map); } - MoteThrown moteThrown = (MoteThrown)ThingMaker.MakeThing(ThingDefOf.Mote_Smoke, null); - moteThrown.Scale = Rand.Range(1.5f, 2.5f) * size; - moteThrown.rotationRate = Rand.Range(-30f, 30f); - moteThrown.exactPosition = loc; - moteThrown.SetVelocity((float)Rand.Range(30, 40), Rand.Range(0.5f, 0.7f)); - GenSpawn.Spawn(moteThrown, loc.ToIntVec3(), map); } public static void ThrowFireGlow(IntVec3 c, Map map, float size) { Vector3 vector = c.ToVector3Shifted(); - if (!vector.ShouldSpawnMotesAt(map) || map.moteCounter.SaturatedLowPriority) + if (vector.ShouldSpawnMotesAt(map) && !map.moteCounter.SaturatedLowPriority) { - return; - } - vector += size * new Vector3(Rand.Value - 0.5f, 0f, Rand.Value - 0.5f); - if (!vector.InBounds(map)) - { - return; + vector += size * new Vector3((float)(Rand.Value - 0.5), 0f, (float)(Rand.Value - 0.5)); + if (vector.InBounds(map)) + { + MoteThrown moteThrown = (MoteThrown)ThingMaker.MakeThing(ThingDefOf.Mote_FireGlow, null); + moteThrown.Scale = Rand.Range(4f, 6f) * size; + moteThrown.rotationRate = Rand.Range(-3f, 3f); + moteThrown.exactPosition = vector; + moteThrown.SetVelocity((float)Rand.Range(0, 360), 0.12f); + GenSpawn.Spawn(moteThrown, vector.ToIntVec3(), map); + } } - MoteThrown moteThrown = (MoteThrown)ThingMaker.MakeThing(ThingDefOf.Mote_FireGlow, null); - moteThrown.Scale = Rand.Range(4f, 6f) * size; - moteThrown.rotationRate = Rand.Range(-3f, 3f); - moteThrown.exactPosition = vector; - moteThrown.SetVelocity((float)Rand.Range(0, 360), 0.12f); - GenSpawn.Spawn(moteThrown, vector.ToIntVec3(), map); } public static void ThrowHeatGlow(IntVec3 c, Map map, float size) { Vector3 vector = c.ToVector3Shifted(); - if (!vector.ShouldSpawnMotesAt(map) || map.moteCounter.SaturatedLowPriority) - { - return; - } - vector += size * new Vector3(Rand.Value - 0.5f, 0f, Rand.Value - 0.5f); - if (!vector.InBounds(map)) + if (vector.ShouldSpawnMotesAt(map) && !map.moteCounter.SaturatedLowPriority) { - return; + vector += size * new Vector3((float)(Rand.Value - 0.5), 0f, (float)(Rand.Value - 0.5)); + if (vector.InBounds(map)) + { + MoteThrown moteThrown = (MoteThrown)ThingMaker.MakeThing(ThingDefOf.Mote_HeatGlow, null); + moteThrown.Scale = Rand.Range(4f, 6f) * size; + moteThrown.rotationRate = Rand.Range(-3f, 3f); + moteThrown.exactPosition = vector; + moteThrown.SetVelocity((float)Rand.Range(0, 360), 0.12f); + GenSpawn.Spawn(moteThrown, vector.ToIntVec3(), map); + } } - MoteThrown moteThrown = (MoteThrown)ThingMaker.MakeThing(ThingDefOf.Mote_HeatGlow, null); - moteThrown.Scale = Rand.Range(4f, 6f) * size; - moteThrown.rotationRate = Rand.Range(-3f, 3f); - moteThrown.exactPosition = vector; - moteThrown.SetVelocity((float)Rand.Range(0, 360), 0.12f); - GenSpawn.Spawn(moteThrown, vector.ToIntVec3(), map); } public static void ThrowMicroSparks(Vector3 loc, Map map) { - if (!loc.ShouldSpawnMotesAt(map) || map.moteCounter.SaturatedLowPriority) + if (loc.ShouldSpawnMotesAt(map) && !map.moteCounter.SaturatedLowPriority) { - return; + MoteThrown moteThrown = (MoteThrown)ThingMaker.MakeThing(ThingDefOf.Mote_MicroSparks, null); + moteThrown.Scale = Rand.Range(0.8f, 1.2f); + moteThrown.rotationRate = Rand.Range(-12f, 12f); + moteThrown.exactPosition = loc; + MoteThrown obj = moteThrown; + obj.exactPosition -= new Vector3(0.5f, 0f, 0.5f); + MoteThrown obj2 = moteThrown; + obj2.exactPosition += new Vector3(Rand.Value, 0f, Rand.Value); + moteThrown.SetVelocity((float)Rand.Range(35, 45), 1.2f); + GenSpawn.Spawn(moteThrown, loc.ToIntVec3(), map); } - MoteThrown moteThrown = (MoteThrown)ThingMaker.MakeThing(ThingDefOf.Mote_MicroSparks, null); - moteThrown.Scale = Rand.Range(0.8f, 1.2f); - moteThrown.rotationRate = Rand.Range(-12f, 12f); - moteThrown.exactPosition = loc; - moteThrown.exactPosition -= new Vector3(0.5f, 0f, 0.5f); - moteThrown.exactPosition += new Vector3(Rand.Value, 0f, Rand.Value); - moteThrown.SetVelocity((float)Rand.Range(35, 45), 1.2f); - GenSpawn.Spawn(moteThrown, loc.ToIntVec3(), map); } public static void ThrowLightningGlow(Vector3 loc, Map map, float size) { - if (!loc.ShouldSpawnMotesAt(map) || map.moteCounter.SaturatedLowPriority) + if (loc.ShouldSpawnMotesAt(map) && !map.moteCounter.SaturatedLowPriority) { - return; + MoteThrown moteThrown = (MoteThrown)ThingMaker.MakeThing(ThingDefOf.Mote_LightningGlow, null); + moteThrown.Scale = Rand.Range(4f, 6f) * size; + moteThrown.rotationRate = Rand.Range(-3f, 3f); + moteThrown.exactPosition = loc + size * new Vector3((float)(Rand.Value - 0.5), 0f, (float)(Rand.Value - 0.5)); + moteThrown.SetVelocity((float)Rand.Range(0, 360), 1.2f); + GenSpawn.Spawn(moteThrown, loc.ToIntVec3(), map); } - MoteThrown moteThrown = (MoteThrown)ThingMaker.MakeThing(ThingDefOf.Mote_LightningGlow, null); - moteThrown.Scale = Rand.Range(4f, 6f) * size; - moteThrown.rotationRate = Rand.Range(-3f, 3f); - moteThrown.exactPosition = loc + size * new Vector3(Rand.Value - 0.5f, 0f, Rand.Value - 0.5f); - moteThrown.SetVelocity((float)Rand.Range(0, 360), 1.2f); - GenSpawn.Spawn(moteThrown, loc.ToIntVec3(), map); } public static void PlaceFootprint(Vector3 loc, Map map, float rot) { - if (!loc.ShouldSpawnMotesAt(map) || map.moteCounter.SaturatedLowPriority) + if (loc.ShouldSpawnMotesAt(map) && !map.moteCounter.SaturatedLowPriority) { - return; + MoteThrown moteThrown = (MoteThrown)ThingMaker.MakeThing(ThingDefOf.Mote_Footprint, null); + moteThrown.Scale = 0.5f; + moteThrown.exactRotation = rot; + moteThrown.exactPosition = loc; + GenSpawn.Spawn(moteThrown, loc.ToIntVec3(), map); } - MoteThrown moteThrown = (MoteThrown)ThingMaker.MakeThing(ThingDefOf.Mote_Footprint, null); - moteThrown.Scale = 0.5f; - moteThrown.exactRotation = rot; - moteThrown.exactPosition = loc; - GenSpawn.Spawn(moteThrown, loc.ToIntVec3(), map); } public static void ThrowHorseshoe(Pawn thrower, IntVec3 targetCell) { - if (!thrower.Position.ShouldSpawnMotesAt(thrower.Map) || thrower.Map.moteCounter.Saturated) + if (thrower.Position.ShouldSpawnMotesAt(thrower.Map) && !thrower.Map.moteCounter.Saturated) { - return; + float num = Rand.Range(3.8f, 5.6f); + Vector3 vector = targetCell.ToVector3Shifted() + Vector3Utility.RandomHorizontalOffset((float)((1.0 - (float)thrower.skills.GetSkill(SkillDefOf.Shooting).Level / 20.0) * 1.7999999523162842)); + Vector3 drawPos = thrower.DrawPos; + vector.y = drawPos.y; + MoteThrown moteThrown = (MoteThrown)ThingMaker.MakeThing(ThingDefOf.Mote_Horseshoe, null); + moteThrown.Scale = 1f; + moteThrown.rotationRate = (float)Rand.Range(-300, 300); + moteThrown.exactPosition = thrower.DrawPos; + moteThrown.SetVelocity((vector - moteThrown.exactPosition).AngleFlat(), num); + moteThrown.airTimeLeft = (float)Mathf.RoundToInt((moteThrown.exactPosition - vector).MagnitudeHorizontal() / num); + GenSpawn.Spawn(moteThrown, thrower.Position, thrower.Map); } - float num = Rand.Range(3.8f, 5.6f); - Vector3 vector = targetCell.ToVector3Shifted() + Vector3Utility.RandomHorizontalOffset((1f - (float)thrower.skills.GetSkill(SkillDefOf.Shooting).Level / 20f) * 1.8f); - vector.y = thrower.DrawPos.y; - MoteThrown moteThrown = (MoteThrown)ThingMaker.MakeThing(ThingDefOf.Mote_Horseshoe, null); - moteThrown.Scale = 1f; - moteThrown.rotationRate = (float)Rand.Range(-300, 300); - moteThrown.exactPosition = thrower.DrawPos; - moteThrown.SetVelocity((vector - moteThrown.exactPosition).AngleFlat(), num); - moteThrown.airTimeLeft = (float)Mathf.RoundToInt((moteThrown.exactPosition - vector).MagnitudeHorizontal() / num); - GenSpawn.Spawn(moteThrown, thrower.Position, thrower.Map); } public static Mote MakeStunOverlay(Thing stunnedThing) @@ -303,7 +295,7 @@ public static MoteDualAttached MakeInteractionOverlay(ThingDef moteDef, TargetIn public static void MakeColonistActionOverlay(Pawn pawn, ThingDef moteDef) { MoteThrownAttached moteThrownAttached = (MoteThrownAttached)ThingMaker.MakeThing(moteDef, null); - moteThrownAttached.Attach(pawn); + moteThrownAttached.Attach((Thing)pawn); moteThrownAttached.Scale = 1.5f; moteThrownAttached.SetVelocity(Rand.Range(20f, 25f), 0.4f); GenSpawn.Spawn(moteThrownAttached, pawn.Position, pawn.Map); @@ -325,7 +317,7 @@ private static MoteBubble ExistingMoteBubbleOn(Pawn pawn) { Thing thing = thingList[j]; MoteBubble moteBubble = thing as MoteBubble; - if (moteBubble != null && moteBubble.link1.Linked && moteBubble.link1.Target.HasThing && moteBubble.link1.Target == pawn) + if (moteBubble != null && moteBubble.link1.Linked && moteBubble.link1.Target.HasThing && moteBubble.link1.Target == (Thing)pawn) { return moteBubble; } @@ -346,7 +338,7 @@ public static MoteBubble MakeMoodThoughtBubble(Pawn pawn, Thought thought) return null; } float num = thought.MoodOffset(); - if (num == 0f) + if (num == 0.0) { return null; } @@ -362,10 +354,10 @@ public static MoteBubble MakeMoodThoughtBubble(Pawn pawn, Thought thought) moteBubble.Destroy(DestroyMode.Vanish); } } - ThingDef def = (num <= 0f) ? ThingDefOf.Mote_ThoughtBad : ThingDefOf.Mote_ThoughtGood; + ThingDef def = (!(num > 0.0)) ? ThingDefOf.Mote_ThoughtBad : ThingDefOf.Mote_ThoughtGood; MoteBubble moteBubble2 = (MoteBubble)ThingMaker.MakeThing(def, null); moteBubble2.SetupMoteBubble(thought.Icon, null); - moteBubble2.Attach(pawn); + moteBubble2.Attach((Thing)pawn); GenSpawn.Spawn(moteBubble2, pawn.Position, pawn.Map); return moteBubble2; } @@ -386,62 +378,58 @@ public static MoteBubble MakeInteractionBubble(Pawn initiator, Pawn recipient, T } MoteBubble moteBubble2 = (MoteBubble)ThingMaker.MakeThing(interactionMote, null); moteBubble2.SetupMoteBubble(symbol, recipient); - moteBubble2.Attach(initiator); + moteBubble2.Attach((Thing)initiator); GenSpawn.Spawn(moteBubble2, initiator.Position, initiator.Map); return moteBubble2; } public static void ThrowExplosionCell(IntVec3 cell, Map map, ThingDef moteDef, Color color) { - if (!cell.ShouldSpawnMotesAt(map)) + if (cell.ShouldSpawnMotesAt(map)) { - return; - } - Mote mote = (Mote)ThingMaker.MakeThing(moteDef, null); - mote.exactRotation = (float)(90 * Rand.RangeInclusive(0, 3)); - mote.exactPosition = cell.ToVector3Shifted(); - mote.instanceColor = color; - GenSpawn.Spawn(mote, cell, map); - if (Rand.Value < 0.7f) - { - MoteMaker.ThrowDustPuff(cell, map, 1.2f); + Mote mote = (Mote)ThingMaker.MakeThing(moteDef, null); + mote.exactRotation = (float)(90 * Rand.RangeInclusive(0, 3)); + mote.exactPosition = cell.ToVector3Shifted(); + mote.instanceColor = color; + GenSpawn.Spawn(mote, cell, map); + if (Rand.Value < 0.699999988079071) + { + MoteMaker.ThrowDustPuff(cell, map, 1.2f); + } } } public static void ThrowExplosionInteriorMote(Vector3 loc, Map map, ThingDef moteDef) { - if (!loc.ShouldSpawnMotesAt(map) || map.moteCounter.SaturatedLowPriority) + if (loc.ShouldSpawnMotesAt(map) && !map.moteCounter.SaturatedLowPriority) { - return; + MoteThrown moteThrown = (MoteThrown)ThingMaker.MakeThing(moteDef, null); + moteThrown.Scale = Rand.Range(3f, 4.5f); + moteThrown.rotationRate = Rand.Range(-30f, 30f); + moteThrown.exactPosition = loc; + moteThrown.SetVelocity((float)Rand.Range(0, 360), Rand.Range(0.48f, 0.72f)); + GenSpawn.Spawn(moteThrown, loc.ToIntVec3(), map); } - MoteThrown moteThrown = (MoteThrown)ThingMaker.MakeThing(moteDef, null); - moteThrown.Scale = Rand.Range(3f, 4.5f); - moteThrown.rotationRate = Rand.Range(-30f, 30f); - moteThrown.exactPosition = loc; - moteThrown.SetVelocity((float)Rand.Range(0, 360), Rand.Range(0.48f, 0.72f)); - GenSpawn.Spawn(moteThrown, loc.ToIntVec3(), map); } public static void MakeWaterSplash(Vector3 loc, Map map, float size, float velocity) { - if (!loc.ShouldSpawnMotesAt(map) || map.moteCounter.SaturatedLowPriority) + if (loc.ShouldSpawnMotesAt(map) && !map.moteCounter.SaturatedLowPriority) { - return; + MoteSplash moteSplash = (MoteSplash)ThingMaker.MakeThing(ThingDefOf.Mote_WaterSplash, null); + moteSplash.Initialize(loc, size, velocity); + GenSpawn.Spawn(moteSplash, loc.ToIntVec3(), map); } - MoteSplash moteSplash = (MoteSplash)ThingMaker.MakeThing(ThingDefOf.Mote_WaterSplash, null); - moteSplash.Initialize(loc, size, velocity); - GenSpawn.Spawn(moteSplash, loc.ToIntVec3(), map); } public static void PlaceTempRoof(IntVec3 cell, Map map) { - if (!cell.ShouldSpawnMotesAt(map)) + if (cell.ShouldSpawnMotesAt(map)) { - return; + Mote mote = (Mote)ThingMaker.MakeThing(ThingDefOf.Mote_TempRoof, null); + mote.exactPosition = cell.ToVector3Shifted(); + GenSpawn.Spawn(mote, cell, map); } - Mote mote = (Mote)ThingMaker.MakeThing(ThingDefOf.Mote_TempRoof, null); - mote.exactPosition = cell.ToVector3Shifted(); - GenSpawn.Spawn(mote, cell, map); } } } diff --git a/Assembly-CSharp/RimWorld/MoteProgressBar.cs b/Assembly-CSharp/RimWorld/MoteProgressBar.cs index a01a295fb..26cd98d42 100644 --- a/Assembly-CSharp/RimWorld/MoteProgressBar.cs +++ b/Assembly-CSharp/RimWorld/MoteProgressBar.cs @@ -1,4 +1,3 @@ -using System; using UnityEngine; using Verse; @@ -20,10 +19,12 @@ public override void Draw() base.UpdatePosition(); if (Find.CameraDriver.CurrentZoom == CameraZoomRange.Closest) { - GenDraw.FillableBarRequest r = default(GenDraw.FillableBarRequest); - r.center = this.exactPosition; - r.center.z = r.center.z + this.offsetZ; - r.size = new Vector2(this.exactScale.x, this.exactScale.z); + GenDraw.FillableBarRequest r = new GenDraw.FillableBarRequest + { + center = base.exactPosition + }; + r.center.z += this.offsetZ; + r.size = new Vector2(base.exactScale.x, base.exactScale.z); r.fillPercent = this.progress; r.filledMat = MoteProgressBar.FilledMat; r.unfilledMat = MoteProgressBar.UnfilledMat; diff --git a/Assembly-CSharp/RimWorld/MusicManagerEntry.cs b/Assembly-CSharp/RimWorld/MusicManagerEntry.cs index 87890904f..a54a969da 100644 --- a/Assembly-CSharp/RimWorld/MusicManagerEntry.cs +++ b/Assembly-CSharp/RimWorld/MusicManagerEntry.cs @@ -1,4 +1,3 @@ -using System; using UnityEngine; using Verse; @@ -20,7 +19,7 @@ private float CurVolume public void MusicManagerEntryUpdate() { - if (this.audioSource == null || !this.audioSource.isPlaying) + if ((Object)this.audioSource == (Object)null || !this.audioSource.isPlaying) { this.StartPlaying(); } @@ -29,32 +28,29 @@ public void MusicManagerEntryUpdate() private void StartPlaying() { - if (this.audioSource != null && !this.audioSource.isPlaying) + if ((Object)this.audioSource != (Object)null && !this.audioSource.isPlaying) { this.audioSource.Play(); - return; } - if (GameObject.Find("MusicAudioSourceDummy") != null) + else if ((Object)GameObject.Find("MusicAudioSourceDummy") != (Object)null) { Log.Error("MusicManagerEntry did StartPlaying but there is already a music source GameObject."); - return; } - this.audioSource = new GameObject("MusicAudioSourceDummy") + else { - transform = - { - parent = Camera.main.transform - } - }.AddComponent(); - this.audioSource.bypassEffects = true; - this.audioSource.bypassListenerEffects = true; - this.audioSource.bypassReverbZones = true; - this.audioSource.priority = 0; - this.audioSource.clip = SongDefOf.EntrySong.clip; - this.audioSource.volume = this.CurVolume; - this.audioSource.loop = true; - this.audioSource.spatialBlend = 0f; - this.audioSource.Play(); + GameObject gameObject = new GameObject("MusicAudioSourceDummy"); + gameObject.transform.parent = Camera.main.transform; + this.audioSource = gameObject.AddComponent(); + this.audioSource.bypassEffects = true; + this.audioSource.bypassListenerEffects = true; + this.audioSource.bypassReverbZones = true; + this.audioSource.priority = 0; + this.audioSource.clip = SongDefOf.EntrySong.clip; + this.audioSource.volume = this.CurVolume; + this.audioSource.loop = true; + this.audioSource.spatialBlend = 0f; + this.audioSource.Play(); + } } } } diff --git a/Assembly-CSharp/RimWorld/MusicManagerPlay.cs b/Assembly-CSharp/RimWorld/MusicManagerPlay.cs index 03b3ac348..24ec01715 100644 --- a/Assembly-CSharp/RimWorld/MusicManagerPlay.cs +++ b/Assembly-CSharp/RimWorld/MusicManagerPlay.cs @@ -11,15 +11,15 @@ public class MusicManagerPlay { private enum MusicManagerState { - Normal, - Fadeout + Normal = 0, + Fadeout = 1 } private const float FadeoutDuration = 10f; private AudioSource audioSource; - private MusicManagerPlay.MusicManagerState state; + private MusicManagerState state; private float fadeoutFactor = 1f; @@ -73,7 +73,7 @@ public float CurVolume { get { - float num = (!this.ignorePrefsVolumeThisSong) ? Prefs.VolumeMusic : 1f; + float num = (float)((!this.ignorePrefsVolumeThisSong) ? Prefs.VolumeMusic : 1.0); if (this.lastStartedSong == null) { return num; @@ -100,82 +100,87 @@ public void MusicUpdate() if (!this.gameObjectCreated) { this.gameObjectCreated = true; - this.audioSource = new GameObject("MusicAudioSourceDummy") - { - transform = - { - parent = Find.Root.soundRoot.sourcePool.sourcePoolCamera.cameraSourcesContainer.transform - } - }.AddComponent(); + GameObject gameObject = new GameObject("MusicAudioSourceDummy"); + gameObject.transform.parent = Find.Root.soundRoot.sourcePool.sourcePoolCamera.cameraSourcesContainer.transform; + this.audioSource = gameObject.AddComponent(); this.audioSource.bypassEffects = true; this.audioSource.bypassListenerEffects = true; this.audioSource.bypassReverbZones = true; this.audioSource.priority = 0; } this.UpdateSubtleAmbienceSoundVolumeMultiplier(); - if (this.disabled) - { - return; - } - if (this.songWasForced) - { - this.state = MusicManagerPlay.MusicManagerState.Normal; - this.fadeoutFactor = 1f; - } - if (this.audioSource.isPlaying && !this.songWasForced && ((this.DangerMusicMode && !this.lastStartedSong.tense) || (!this.DangerMusicMode && this.lastStartedSong.tense))) + if (!this.disabled) { - this.state = MusicManagerPlay.MusicManagerState.Fadeout; + if (this.songWasForced) + { + this.state = MusicManagerState.Normal; + this.fadeoutFactor = 1f; + } + if (this.audioSource.isPlaying && !this.songWasForced) + { + if (this.DangerMusicMode && !this.lastStartedSong.tense) + { + goto IL_0102; + } + if (!this.DangerMusicMode && this.lastStartedSong.tense) + goto IL_0102; + } + goto IL_0109; } + return; + IL_0109: this.audioSource.volume = this.CurVolume; if (this.audioSource.isPlaying) { - if (this.state == MusicManagerPlay.MusicManagerState.Fadeout) + if (this.state == MusicManagerState.Fadeout) { - this.fadeoutFactor -= Time.deltaTime / 10f; - if (this.fadeoutFactor <= 0f) + this.fadeoutFactor -= (float)(Time.deltaTime / 10.0); + if (this.fadeoutFactor <= 0.0) { this.audioSource.Stop(); this.ignorePrefsVolumeThisSong = false; - this.state = MusicManagerPlay.MusicManagerState.Normal; + this.state = MusicManagerState.Normal; this.fadeoutFactor = 1f; } } } else { - if (this.DangerMusicMode && this.nextSongStartTime > this.CurTime + MusicManagerPlay.SongIntervalTension.max) - { - this.nextSongStartTime = this.CurTime + MusicManagerPlay.SongIntervalTension.RandomInRange; - } - if (this.nextSongStartTime < this.CurTime - 5f) + if (this.DangerMusicMode) { - float randomInRange; - if (this.DangerMusicMode) - { - randomInRange = MusicManagerPlay.SongIntervalTension.RandomInRange; - } - else + float num = this.nextSongStartTime; + float curTime = this.CurTime; + FloatRange songIntervalTension = MusicManagerPlay.SongIntervalTension; + if (num > curTime + songIntervalTension.max) { - randomInRange = MusicManagerPlay.SongIntervalRelax.RandomInRange; + this.nextSongStartTime = this.CurTime + MusicManagerPlay.SongIntervalTension.RandomInRange; } - this.nextSongStartTime = this.CurTime + randomInRange; + } + if (this.nextSongStartTime < this.CurTime - 5.0) + { + float num2 = (!this.DangerMusicMode) ? MusicManagerPlay.SongIntervalRelax.RandomInRange : MusicManagerPlay.SongIntervalTension.RandomInRange; + this.nextSongStartTime = this.CurTime + num2; } if (this.CurTime >= this.nextSongStartTime) { this.StartNewSong(); } } + return; + IL_0102: + this.state = MusicManagerState.Fadeout; + goto IL_0109; } private void UpdateSubtleAmbienceSoundVolumeMultiplier() { - if (this.IsPlaying && this.CurVolume > 0.001f) + if (this.IsPlaying && this.CurVolume > 0.0010000000474974513) { - this.subtleAmbienceSoundVolumeMultiplier -= Time.deltaTime * 0.1f; + this.subtleAmbienceSoundVolumeMultiplier -= (float)(Time.deltaTime * 0.10000000149011612); } else { - this.subtleAmbienceSoundVolumeMultiplier += Time.deltaTime * 0.1f; + this.subtleAmbienceSoundVolumeMultiplier += (float)(Time.deltaTime * 0.10000000149011612); } this.subtleAmbienceSoundVolumeMultiplier = Mathf.Clamp01(this.subtleAmbienceSoundVolumeMultiplier); } @@ -214,17 +219,17 @@ where this.AppropriateNow(song) { this.recentSongs.Dequeue(); } - while (!source.Any() && this.recentSongs.Count > 0) + while (!source.Any() && this.recentSongs.Count > 0) { this.recentSongs.Dequeue(); } - if (!source.Any()) + if (!source.Any()) { Log.Error("Could not get any appropriate song. Getting random and logging song selection data."); this.LogSongSelectionData(); return DefDatabase.GetRandom(); } - return source.RandomElementByWeight((SongDef s) => s.commonality); + return source.RandomElementByWeight((Func)((SongDef s) => s.commonality)); } private bool AppropriateNow(SongDef song) @@ -245,7 +250,7 @@ private bool AppropriateNow(SongDef song) return false; } Map map = Find.AnyPlayerHomeMap ?? Find.VisibleMap; - if (!song.allowedSeasons.NullOrEmpty()) + if (!song.allowedSeasons.NullOrEmpty()) { if (map == null) { @@ -260,19 +265,19 @@ private bool AppropriateNow(SongDef song) { return false; } - if (song.allowedTimeOfDay == TimeOfDay.Any) - { - return true; - } - if (map == null) - { - return true; - } - if (song.allowedTimeOfDay == TimeOfDay.Night) + if (song.allowedTimeOfDay != TimeOfDay.Any) { - return GenLocalDate.DayPercent(map) < 0.2f || GenLocalDate.DayPercent(map) > 0.7f; + if (map == null) + { + return true; + } + if (song.allowedTimeOfDay == TimeOfDay.Night) + { + return GenLocalDate.DayPercent(map) < 0.20000000298023224 || GenLocalDate.DayPercent(map) > 0.699999988079071; + } + return GenLocalDate.DayPercent(map) > 0.20000000298023224 && GenLocalDate.DayPercent(map) < 0.699999988079071; } - return GenLocalDate.DayPercent(map) > 0.2f && GenLocalDate.DayPercent(map) < 0.7f; + return true; } public string DebugString() @@ -296,17 +301,26 @@ public void LogSongSelectionData() stringBuilder.AppendLine("Most recent song: " + ((this.lastStartedSong == null) ? "None" : this.lastStartedSong.defName)); stringBuilder.AppendLine(); stringBuilder.AppendLine("Songs appropriate to play now:"); - foreach (SongDef current in from s in DefDatabase.AllDefs + foreach (SongDef item in from s in DefDatabase.AllDefs where this.AppropriateNow(s) select s) { - stringBuilder.AppendLine(" " + current.defName); + stringBuilder.AppendLine(" " + item.defName); } stringBuilder.AppendLine(); stringBuilder.AppendLine("Recently played songs:"); - foreach (SongDef current2 in this.recentSongs) + Queue.Enumerator enumerator2 = this.recentSongs.GetEnumerator(); + try + { + while (enumerator2.MoveNext()) + { + SongDef current2 = enumerator2.Current; + stringBuilder.AppendLine(" " + current2.defName); + } + } + finally { - stringBuilder.AppendLine(" " + current2.defName); + ((IDisposable)(object)enumerator2).Dispose(); } Log.Message(stringBuilder.ToString()); } diff --git a/Assembly-CSharp/RimWorld/NameBank.cs b/Assembly-CSharp/RimWorld/NameBank.cs index da44ad870..e659b500d 100644 --- a/Assembly-CSharp/RimWorld/NameBank.cs +++ b/Assembly-CSharp/RimWorld/NameBank.cs @@ -19,11 +19,13 @@ private IEnumerable> AllNameLists { get { - NameBank.<>c__IteratorC7 <>c__IteratorC = new NameBank.<>c__IteratorC7(); - <>c__IteratorC.<>f__this = this; - NameBank.<>c__IteratorC7 expr_0E = <>c__IteratorC; - expr_0E.$PC = -2; - return expr_0E; + for (int j = 0; j < NameBank.numGenders; j++) + { + for (int i = 0; i < NameBank.numSlots; i++) + { + yield return this.names[j, i]; + } + } } } @@ -42,36 +44,54 @@ public NameBank(PawnNameCategory ID) public void ErrorCheck() { - foreach (List current in this.AllNameLists) + foreach (List allNameList in this.AllNameLists) { - List list = (from x in current + List list = (from x in allNameList group x by x into g - where g.Count() > 1 - select g.Key).ToList(); - foreach (string current2 in list) + where g.Count() > 1 + select g.Key).ToList(); + List.Enumerator enumerator2 = list.GetEnumerator(); + try { - Log.Error("Duplicated name: " + current2); + while (enumerator2.MoveNext()) + { + string current2 = enumerator2.Current; + Log.Error("Duplicated name: " + current2); + } + } + finally + { + ((IDisposable)(object)enumerator2).Dispose(); } - foreach (string current3 in current) + List.Enumerator enumerator3 = allNameList.GetEnumerator(); + try { - if (current3.Trim() != current3) + while (enumerator3.MoveNext()) { - Log.Error("Trimmable whitespace on name: [" + current3 + "]"); + string current3 = enumerator3.Current; + if (current3.Trim() != current3) + { + Log.Error("Trimmable whitespace on name: [" + current3 + "]"); + } } } + finally + { + ((IDisposable)(object)enumerator3).Dispose(); + } } } private List NamesFor(PawnNameSlot slot, Gender gender) { - return this.names[(int)gender, (int)slot]; + return this.names[(uint)gender, (uint)slot]; } public void AddNames(PawnNameSlot slot, Gender gender, IEnumerable namesToAdd) { - foreach (string current in namesToAdd) + foreach (string item in namesToAdd) { - this.NamesFor(slot, gender).Add(current); + this.NamesFor(slot, gender).Add(item); } } @@ -86,29 +106,20 @@ public string GetName(PawnNameSlot slot, Gender gender = Gender.None) int num = 0; if (list.Count == 0) { - Log.Error(string.Concat(new object[] - { - "Name list for gender=", - gender, - " slot=", - slot, - " is empty." - })); + Log.Error("Name list for gender=" + gender + " slot=" + slot + " is empty."); return "Errorname"; } string text; while (true) { - text = list.RandomElement(); + text = list.RandomElement(); if (!NameUseChecker.NameWordIsUsed(text)) { - break; + return text; } num++; if (num > 50) - { - return text; - } + break; } return text; } diff --git a/Assembly-CSharp/RimWorld/NameGenerator.cs b/Assembly-CSharp/RimWorld/NameGenerator.cs index ae89fcc33..0b52ce45a 100644 --- a/Assembly-CSharp/RimWorld/NameGenerator.cs +++ b/Assembly-CSharp/RimWorld/NameGenerator.cs @@ -10,38 +10,44 @@ public static class NameGenerator { public static string GenerateName(RulePackDef rootPack, IEnumerable extantNames, bool appendNumberIfNameUsed = false) { - return NameGenerator.GenerateName(rootPack, (string x) => !extantNames.Contains(x), appendNumberIfNameUsed); + return NameGenerator.GenerateName(rootPack, (Predicate)((string x) => !extantNames.Contains(x)), appendNumberIfNameUsed); } public static string GenerateName(RulePackDef rootPack, Predicate validator = null, bool appendNumberIfNameUsed = false) { - string text = null; + string text = (string)null; if (appendNumberIfNameUsed) { for (int i = 0; i < 100; i++) { - for (int j = 0; j < 5; j++) + int num = 0; + while (num < 5) { - text = GenText.ToTitleCaseSmart(GrammarResolver.Resolve(rootPack.Rules[0].keyword, rootPack.Rules, null)); + text = GenText.ToTitleCaseSmart(GrammarResolver.Resolve(rootPack.Rules[0].keyword, rootPack.Rules, (string)null)); if (i != 0) { text = text + " " + (i + 1); } - if (validator == null || validator(text)) + if ((object)validator != null && !validator(text)) { - return text; + num++; + continue; } + return text; } } - return GenText.ToTitleCaseSmart(GrammarResolver.Resolve(rootPack.Rules[0].keyword, rootPack.Rules, null)); + return GenText.ToTitleCaseSmart(GrammarResolver.Resolve(rootPack.Rules[0].keyword, rootPack.Rules, (string)null)); } - for (int k = 0; k < 150; k++) + int num2 = 0; + while (num2 < 150) { - text = GenText.ToTitleCaseSmart(GrammarResolver.Resolve(rootPack.Rules[0].keyword, rootPack.Rules, null)); - if (validator == null || validator(text)) + text = GenText.ToTitleCaseSmart(GrammarResolver.Resolve(rootPack.Rules[0].keyword, rootPack.Rules, (string)null)); + if ((object)validator != null && !validator(text)) { - return text; + num2++; + continue; } + return text; } Log.Error("Could not get new name."); return text; diff --git a/Assembly-CSharp/RimWorld/NamePlayerFactionAndBaseUtility.cs b/Assembly-CSharp/RimWorld/NamePlayerFactionAndBaseUtility.cs index 18c3f4fe4..83a4bc3cf 100644 --- a/Assembly-CSharp/RimWorld/NamePlayerFactionAndBaseUtility.cs +++ b/Assembly-CSharp/RimWorld/NamePlayerFactionAndBaseUtility.cs @@ -37,38 +37,42 @@ public static bool CanNameFactionBaseSoon(FactionBase factionBase) private static bool CanNameFaction(int ticksPassed) { - return !Faction.OfPlayer.HasName && (float)ticksPassed / 60000f >= 3f && NamePlayerFactionAndBaseUtility.CanNameAnythingNow(); + return !Faction.OfPlayer.HasName && (float)ticksPassed / 60000.0 >= 3.0 && NamePlayerFactionAndBaseUtility.CanNameAnythingNow(); } private static bool CanNameFactionBase(FactionBase factionBase, int ticksPassed) { - return factionBase.Faction == Faction.OfPlayer && !factionBase.namedByPlayer && (float)ticksPassed / 60000f >= 3f && factionBase.HasMap && factionBase.Map.dangerWatcher.DangerRating != StoryDanger.High && factionBase.Map.mapPawns.FreeColonistsSpawnedCount != 0 && NamePlayerFactionAndBaseUtility.CanNameAnythingNow(); + return ((factionBase.Faction == Faction.OfPlayer) ? ((!factionBase.namedByPlayer) ? (((float)ticksPassed / 60000.0 >= 3.0) ? (factionBase.HasMap ? ((factionBase.Map.dangerWatcher.DangerRating != StoryDanger.High) ? factionBase.Map.mapPawns.FreeColonistsSpawnedCount : 0) : 0) : 0) : 0) : 0) != 0 && NamePlayerFactionAndBaseUtility.CanNameAnythingNow(); } private static bool CanNameAnythingNow() { - if (Find.AnyPlayerHomeMap == null || Find.VisibleMap == null || !Find.VisibleMap.IsPlayerHome || Find.GameEnder.gameEnding) + if (Find.AnyPlayerHomeMap != null && Find.VisibleMap != null && Find.VisibleMap.IsPlayerHome && !Find.GameEnder.gameEnding) { - return false; - } - bool flag = false; - bool flag2 = false; - List maps = Find.Maps; - for (int i = 0; i < maps.Count; i++) - { - if (maps[i].IsPlayerHome) + bool flag = false; + bool flag2 = false; + List maps = Find.Maps; + for (int i = 0; i < maps.Count; i++) { - if (maps[i].mapPawns.FreeColonistsSpawnedCount >= 2) - { - flag = true; - } - if (!maps[i].attackTargetsCache.TargetsHostileToColony.Any((IAttackTarget x) => !x.ThreatDisabled())) + if (maps[i].IsPlayerHome) { - flag2 = true; + if (maps[i].mapPawns.FreeColonistsSpawnedCount >= 2) + { + flag = true; + } + if (!maps[i].attackTargetsCache.TargetsHostileToColony.Any((Func)((IAttackTarget x) => !x.ThreatDisabled()))) + { + flag2 = true; + } } } + if (flag && flag2) + { + return true; + } + return false; } - return flag && flag2; + return false; } } } diff --git a/Assembly-CSharp/RimWorld/NamePlayerFactionBaseDialogUtility.cs b/Assembly-CSharp/RimWorld/NamePlayerFactionBaseDialogUtility.cs index 3a5c6dcad..9f1c7a222 100644 --- a/Assembly-CSharp/RimWorld/NamePlayerFactionBaseDialogUtility.cs +++ b/Assembly-CSharp/RimWorld/NamePlayerFactionBaseDialogUtility.cs @@ -1,5 +1,4 @@ using RimWorld.Planet; -using System; namespace RimWorld { @@ -7,7 +6,11 @@ public static class NamePlayerFactionBaseDialogUtility { public static bool IsValidName(string s) { - return s.Length != 0; + if (s.Length == 0) + { + return false; + } + return true; } public static void Named(FactionBase factionBase, string s) diff --git a/Assembly-CSharp/RimWorld/NamePlayerFactionDialogUtility.cs b/Assembly-CSharp/RimWorld/NamePlayerFactionDialogUtility.cs index fe054de99..44f84ed11 100644 --- a/Assembly-CSharp/RimWorld/NamePlayerFactionDialogUtility.cs +++ b/Assembly-CSharp/RimWorld/NamePlayerFactionDialogUtility.cs @@ -1,4 +1,3 @@ -using System; using Verse; namespace RimWorld @@ -7,7 +6,15 @@ public static class NamePlayerFactionDialogUtility { public static bool IsValidName(string s) { - return s.Length != 0 && GenText.IsValidFilename(s); + if (s.Length == 0) + { + return false; + } + if (!GenText.IsValidFilename(s)) + { + return false; + } + return true; } public static void Named(string s) diff --git a/Assembly-CSharp/RimWorld/NameStyle.cs b/Assembly-CSharp/RimWorld/NameStyle.cs index bd154c1c4..9ff6f55e3 100644 --- a/Assembly-CSharp/RimWorld/NameStyle.cs +++ b/Assembly-CSharp/RimWorld/NameStyle.cs @@ -1,10 +1,8 @@ -using System; - namespace RimWorld { public enum NameStyle { - Full, - Numeric + Full = 0, + Numeric = 1 } } diff --git a/Assembly-CSharp/RimWorld/NativeVerbPropertiesDatabase.cs b/Assembly-CSharp/RimWorld/NativeVerbPropertiesDatabase.cs index 266908216..47ae64fea 100644 --- a/Assembly-CSharp/RimWorld/NativeVerbPropertiesDatabase.cs +++ b/Assembly-CSharp/RimWorld/NativeVerbPropertiesDatabase.cs @@ -11,14 +11,14 @@ public static class NativeVerbPropertiesDatabase static NativeVerbPropertiesDatabase() { - NativeVerbPropertiesDatabase.allVerbDefs = VerbDefsHardcodedNative.AllVerbDefs().ToList(); + NativeVerbPropertiesDatabase.allVerbDefs = VerbDefsHardcodedNative.AllVerbDefs().ToList(); } public static VerbProperties VerbWithCategory(VerbCategory id) { VerbProperties verbProperties = (from v in NativeVerbPropertiesDatabase.allVerbDefs where v.category == id - select v).FirstOrDefault(); + select v).FirstOrDefault(); if (verbProperties == null) { Log.Error("Failed to find Verb with id " + id); diff --git a/Assembly-CSharp/RimWorld/Need.cs b/Assembly-CSharp/RimWorld/Need.cs index f3eb7a88c..b917a16ef 100644 --- a/Assembly-CSharp/RimWorld/Need.cs +++ b/Assembly-CSharp/RimWorld/Need.cs @@ -91,7 +91,15 @@ protected bool IsFrozen { get { - return ThingOwnerUtility.ContentsFrozen(this.pawn.ParentHolder) || (this.def.freezeWhileSleeping && !this.pawn.Awake()) || !this.IsPawnInteractableOrVisible; + if (ThingOwnerUtility.ContentsFrozen(this.pawn.ParentHolder)) + { + return true; + } + if (this.def.freezeWhileSleeping && !this.pawn.Awake()) + { + return true; + } + return !this.IsPawnInteractableOrVisible; } } @@ -99,7 +107,19 @@ private bool IsPawnInteractableOrVisible { get { - return this.pawn.SpawnedOrAnyParentSpawned || this.pawn.IsCaravanMember() || PawnUtility.IsTravelingInTransportPodWorldObject(this.pawn); + if (this.pawn.SpawnedOrAnyParentSpawned) + { + return true; + } + if (this.pawn.IsCaravanMember()) + { + return true; + } + if (PawnUtility.IsTravelingInTransportPodWorldObject(this.pawn)) + { + return true; + } + return false; } } @@ -123,14 +143,7 @@ public virtual void ExposeData() public virtual string GetTipString() { - return string.Concat(new string[] - { - this.LabelCap, - ": ", - this.CurLevelPercentage.ToStringPercent(), - "\n", - this.def.description - }); + return this.LabelCap + ": " + this.CurLevelPercentage.ToStringPercent() + "\n" + this.def.description; } public virtual void SetInitialLevel() @@ -145,9 +158,9 @@ public void ForceSetLevel(float levelPercent) public virtual void DrawOnGUI(Rect rect, int maxThresholdMarkers = 2147483647, float customMargin = -1f, bool drawArrows = true, bool doTooltip = true) { - if (rect.height > 70f) + if (rect.height > 70.0) { - float num = (rect.height - 70f) / 2f; + float num = (float)((rect.height - 70.0) / 2.0); rect.height = 70f; rect.y += num; } @@ -157,21 +170,21 @@ public virtual void DrawOnGUI(Rect rect, int maxThresholdMarkers = 2147483647, f } if (doTooltip) { - TooltipHandler.TipRegion(rect, new TipSignal(() => this.GetTipString(), rect.GetHashCode())); + TooltipHandler.TipRegion(rect, new TipSignal((Func)(() => this.GetTipString()), rect.GetHashCode())); } float num2 = 14f; - float num3 = (customMargin < 0f) ? (num2 + 15f) : customMargin; - if (rect.height < 50f) + float num3 = (float)((!(customMargin >= 0.0)) ? (num2 + 15.0) : customMargin); + if (rect.height < 50.0) { num2 *= Mathf.InverseLerp(0f, 50f, rect.height); } - Text.Font = ((rect.height <= 55f) ? GameFont.Tiny : GameFont.Small); + Text.Font = (GameFont)((rect.height > 55.0) ? 1 : 0); Text.Anchor = TextAnchor.LowerLeft; - Rect rect2 = new Rect(rect.x + num3 + rect.width * 0.1f, rect.y, rect.width - num3 - rect.width * 0.1f, rect.height / 2f); + Rect rect2 = new Rect((float)(rect.x + num3 + rect.width * 0.10000000149011612), rect.y, (float)(rect.width - num3 - rect.width * 0.10000000149011612), (float)(rect.height / 2.0)); Widgets.Label(rect2, this.LabelCap); Text.Anchor = TextAnchor.UpperLeft; - Rect rect3 = new Rect(rect.x, rect.y + rect.height / 2f, rect.width, rect.height / 2f); - rect3 = new Rect(rect3.x + num3, rect3.y, rect3.width - num3 * 2f, rect3.height - num2); + Rect rect3 = new Rect(rect.x, (float)(rect.y + rect.height / 2.0), rect.width, (float)(rect.height / 2.0)); + rect3 = new Rect(rect3.x + num3, rect3.y, (float)(rect3.width - num3 * 2.0), rect3.height - num2); Widgets.FillableBar(rect3, this.CurLevelPercentage); if (drawArrows) { @@ -185,7 +198,7 @@ public virtual void DrawOnGUI(Rect rect, int maxThresholdMarkers = 2147483647, f } } float curInstantLevelPercentage = this.CurInstantLevelPercentage; - if (curInstantLevelPercentage >= 0f) + if (curInstantLevelPercentage >= 0.0) { this.DrawBarInstantMarkerAt(rect3, curInstantLevelPercentage); } @@ -198,24 +211,24 @@ public virtual void DrawOnGUI(Rect rect, int maxThresholdMarkers = 2147483647, f protected void DrawBarInstantMarkerAt(Rect barRect, float pct) { - if (pct > 1f) + if (pct > 1.0) { Log.ErrorOnce(this.def + " drawing bar percent > 1 : " + pct, 6932178); } float num = 12f; - if (barRect.width < 150f) + if (barRect.width < 150.0) { - num /= 2f; + num = (float)(num / 2.0); } Vector2 vector = new Vector2(barRect.x + barRect.width * pct, barRect.y + barRect.height); - Rect position = new Rect(vector.x - num / 2f, vector.y, num, num); + Rect position = new Rect((float)(vector.x - num / 2.0), vector.y, num, num); GUI.DrawTexture(position, Need.BarInstantMarkerTex); } private void DrawBarThreshold(Rect barRect, float threshPct) { - float num = (float)((barRect.width <= 60f) ? 1 : 2); - Rect position = new Rect(barRect.x + barRect.width * threshPct - (num - 1f), barRect.y + barRect.height / 2f, num, barRect.height / 2f); + float num = (float)((!(barRect.width > 60.0)) ? 1 : 2); + Rect position = new Rect((float)(barRect.x + barRect.width * threshPct - (num - 1.0)), (float)(barRect.y + barRect.height / 2.0), num, (float)(barRect.height / 2.0)); Texture2D image; if (threshPct < this.CurLevelPercentage) { diff --git a/Assembly-CSharp/RimWorld/NeedDef.cs b/Assembly-CSharp/RimWorld/NeedDef.cs index f39ec6cbd..04b8b8e00 100644 --- a/Assembly-CSharp/RimWorld/NeedDef.cs +++ b/Assembly-CSharp/RimWorld/NeedDef.cs @@ -1,6 +1,5 @@ using System; using System.Collections.Generic; -using System.Diagnostics; using Verse; namespace RimWorld @@ -39,14 +38,26 @@ public class NeedDef : Def public bool freezeWhileSleeping; - [DebuggerHidden] public override IEnumerable ConfigErrors() { - NeedDef.c__Iterator91 c__Iterator = new NeedDef.c__Iterator91(); - c__Iterator.<>f__this = this; - NeedDef.c__Iterator91 expr_0E = c__Iterator; - expr_0E.$PC = -2; - return expr_0E; + foreach (string item in base.ConfigErrors()) + { + yield return item; + } + if (base.description.NullOrEmpty()) + { + yield return "no description"; + } + if (this.needClass == null) + { + yield return "needClass is null"; + } + if (this.needClass == typeof(Need_Seeker)) + { + if (this.seekerRisePerHour != 0.0 && this.seekerFallPerHour != 0.0) + yield break; + yield return "seeker rise/fall rates not set"; + } } } } diff --git a/Assembly-CSharp/RimWorld/NeedDefOf.cs b/Assembly-CSharp/RimWorld/NeedDefOf.cs index 7c545b65f..bffca6245 100644 --- a/Assembly-CSharp/RimWorld/NeedDefOf.cs +++ b/Assembly-CSharp/RimWorld/NeedDefOf.cs @@ -1,5 +1,3 @@ -using System; - namespace RimWorld { [DefOf] diff --git a/Assembly-CSharp/RimWorld/NeedTunings.cs b/Assembly-CSharp/RimWorld/NeedTunings.cs index b35632a49..9c2f3c877 100644 --- a/Assembly-CSharp/RimWorld/NeedTunings.cs +++ b/Assembly-CSharp/RimWorld/NeedTunings.cs @@ -1,5 +1,3 @@ -using System; - namespace RimWorld { public static class NeedTunings diff --git a/Assembly-CSharp/RimWorld/Need_Beauty.cs b/Assembly-CSharp/RimWorld/Need_Beauty.cs index b0e39cea7..9bb8a2120 100644 --- a/Assembly-CSharp/RimWorld/Need_Beauty.cs +++ b/Assembly-CSharp/RimWorld/Need_Beauty.cs @@ -1,4 +1,3 @@ -using System; using System.Collections.Generic; using UnityEngine; using Verse; @@ -25,11 +24,11 @@ public override float CurInstantLevel { get { - if (!this.pawn.health.capacities.CapableOf(PawnCapacityDefOf.Sight)) + if (!base.pawn.health.capacities.CapableOf(PawnCapacityDefOf.Sight)) { return 0.5f; } - if (!this.pawn.Spawned) + if (!base.pawn.Spawned) { return 0.5f; } @@ -41,27 +40,27 @@ public BeautyCategory CurCategory { get { - if (this.CurLevel > 0.99f) + if (this.CurLevel > 0.99000000953674316) { return BeautyCategory.Beautiful; } - if (this.CurLevel > 0.85f) + if (this.CurLevel > 0.85000002384185791) { return BeautyCategory.VeryPretty; } - if (this.CurLevel > 0.65f) + if (this.CurLevel > 0.64999997615814209) { return BeautyCategory.Pretty; } - if (this.CurLevel > 0.35f) + if (this.CurLevel > 0.34999999403953552) { return BeautyCategory.Neutral; } - if (this.CurLevel > 0.15f) + if (this.CurLevel > 0.15000000596046448) { return BeautyCategory.Ugly; } - if (this.CurLevel > 0.01f) + if (this.CurLevel > 0.0099999997764825821) { return BeautyCategory.VeryUgly; } @@ -71,25 +70,25 @@ public BeautyCategory CurCategory public Need_Beauty(Pawn pawn) : base(pawn) { - this.threshPercents = new List(); - this.threshPercents.Add(0.15f); - this.threshPercents.Add(0.35f); - this.threshPercents.Add(0.65f); - this.threshPercents.Add(0.85f); + base.threshPercents = new List(); + base.threshPercents.Add(0.15f); + base.threshPercents.Add(0.35f); + base.threshPercents.Add(0.65f); + base.threshPercents.Add(0.85f); } private float LevelFromBeauty(float beauty) { - return Mathf.Clamp01(this.def.baseLevel + beauty * 0.1f); + return Mathf.Clamp01((float)(base.def.baseLevel + beauty * 0.10000000149011612)); } public float CurrentInstantBeauty() { - if (!this.pawn.SpawnedOrAnyParentSpawned) + if (!base.pawn.SpawnedOrAnyParentSpawned) { return 0.5f; } - return BeautyUtility.AverageBeautyPerceptible(this.pawn.PositionHeld, this.pawn.MapHeld); + return BeautyUtility.AverageBeautyPerceptible(base.pawn.PositionHeld, base.pawn.MapHeld); } } } diff --git a/Assembly-CSharp/RimWorld/Need_Chemical.cs b/Assembly-CSharp/RimWorld/Need_Chemical.cs index 0e4f7bdb9..6ea39feed 100644 --- a/Assembly-CSharp/RimWorld/Need_Chemical.cs +++ b/Assembly-CSharp/RimWorld/Need_Chemical.cs @@ -1,4 +1,3 @@ -using System; using System.Collections.Generic; using Verse; @@ -22,11 +21,11 @@ public DrugDesireCategory CurCategory { get { - if (this.CurLevel > 0.3f) + if (this.CurLevel > 0.30000001192092896) { return DrugDesireCategory.Satisfied; } - if (this.CurLevel > 0.01f) + if (this.CurLevel > 0.0099999997764825821) { return DrugDesireCategory.Desire; } @@ -55,11 +54,11 @@ public Hediff_Addiction AddictionHediff { get { - List hediffs = this.pawn.health.hediffSet.hediffs; + List hediffs = base.pawn.health.hediffSet.hediffs; for (int i = 0; i < hediffs.Count; i++) { Hediff_Addiction hediff_Addiction = hediffs[i] as Hediff_Addiction; - if (hediff_Addiction != null && hediff_Addiction.def.causesNeed == this.def) + if (hediff_Addiction != null && hediff_Addiction.def.causesNeed == base.def) { return hediff_Addiction; } @@ -72,14 +71,14 @@ private float ChemicalFallPerTick { get { - return this.def.fallPerDay / 60000f; + return (float)(base.def.fallPerDay / 60000.0); } } public Need_Chemical(Pawn pawn) : base(pawn) { - this.threshPercents = new List(); - this.threshPercents.Add(0.3f); + base.threshPercents = new List(); + base.threshPercents.Add(0.3f); } public override void SetInitialLevel() @@ -91,7 +90,7 @@ public override void NeedInterval() { if (!base.IsFrozen) { - this.CurLevel -= this.ChemicalFallPerTick * 150f; + this.CurLevel -= (float)(this.ChemicalFallPerTick * 150.0); } } diff --git a/Assembly-CSharp/RimWorld/Need_Comfort.cs b/Assembly-CSharp/RimWorld/Need_Comfort.cs index 5383e6877..eb7761880 100644 --- a/Assembly-CSharp/RimWorld/Need_Comfort.cs +++ b/Assembly-CSharp/RimWorld/Need_Comfort.cs @@ -1,4 +1,3 @@ -using System; using System.Collections.Generic; using UnityEngine; using Verse; @@ -27,7 +26,7 @@ public override float CurInstantLevel { get { - if (!this.pawn.Spawned) + if (!base.pawn.Spawned) { return 0.5f; } @@ -43,23 +42,23 @@ public ComfortCategory CurCategory { get { - if (this.CurLevel < 0.1f) + if (this.CurLevel < 0.10000000149011612) { return ComfortCategory.Uncomfortable; } - if (this.CurLevel < 0.6f) + if (this.CurLevel < 0.60000002384185791) { return ComfortCategory.Normal; } - if (this.CurLevel < 0.7f) + if (this.CurLevel < 0.699999988079071) { return ComfortCategory.Comfortable; } - if (this.CurLevel < 0.8f) + if (this.CurLevel < 0.800000011920929) { return ComfortCategory.VeryComfortable; } - if (this.CurLevel < 0.9f) + if (this.CurLevel < 0.89999997615814209) { return ComfortCategory.ExtremelyComfortable; } @@ -69,12 +68,12 @@ public ComfortCategory CurCategory public Need_Comfort(Pawn pawn) : base(pawn) { - this.threshPercents = new List(); - this.threshPercents.Add(0.1f); - this.threshPercents.Add(0.6f); - this.threshPercents.Add(0.7f); - this.threshPercents.Add(0.8f); - this.threshPercents.Add(0.9f); + base.threshPercents = new List(); + base.threshPercents.Add(0.1f); + base.threshPercents.Add(0.6f); + base.threshPercents.Add(0.7f); + base.threshPercents.Add(0.8f); + base.threshPercents.Add(0.9f); } public void ComfortUsed(float comfort) diff --git a/Assembly-CSharp/RimWorld/Need_Food.cs b/Assembly-CSharp/RimWorld/Need_Food.cs index f6e546983..a4a9f538b 100644 --- a/Assembly-CSharp/RimWorld/Need_Food.cs +++ b/Assembly-CSharp/RimWorld/Need_Food.cs @@ -1,4 +1,3 @@ -using System; using System.Collections.Generic; using UnityEngine; using Verse; @@ -27,7 +26,7 @@ public float PercentageThreshUrgentlyHungry { get { - return this.pawn.RaceProps.FoodLevelPercentageWantEat * 0.4f; + return (float)(base.pawn.RaceProps.FoodLevelPercentageWantEat * 0.40000000596046448); } } @@ -35,7 +34,7 @@ public float PercentageThreshHungry { get { - return this.pawn.RaceProps.FoodLevelPercentageWantEat * 0.8f; + return (float)(base.pawn.RaceProps.FoodLevelPercentageWantEat * 0.800000011920929); } } @@ -43,7 +42,7 @@ public float NutritionBetweenHungryAndFed { get { - return (1f - this.PercentageThreshHungry) * this.MaxLevel; + return (float)((1.0 - this.PercentageThreshHungry) * this.MaxLevel); } } @@ -51,7 +50,7 @@ public HungerCategory CurCategory { get { - if (base.CurLevelPercentage <= 0f) + if (base.CurLevelPercentage <= 0.0) { return HungerCategory.Starving; } @@ -95,7 +94,7 @@ public override float MaxLevel { get { - return this.pawn.BodySize * this.pawn.ageTracker.CurLifeStage.foodMaxFactor; + return base.pawn.BodySize * base.pawn.ageTracker.CurLifeStage.foodMaxFactor; } } @@ -111,8 +110,8 @@ private float HungerRate { get { - float num = this.pawn.ageTracker.CurLifeStage.hungerRateFactor * this.pawn.RaceProps.baseHungerRate; - List hediffs = this.pawn.health.hediffSet.hediffs; + float num = base.pawn.ageTracker.CurLifeStage.hungerRateFactor * base.pawn.RaceProps.baseHungerRate; + List hediffs = base.pawn.health.hediffSet.hediffs; for (int i = 0; i < hediffs.Count; i++) { HediffStage curStage = hediffs[i].CurStage; @@ -148,23 +147,33 @@ private float FoodFallPerTickAssumingCategory(HungerCategory cat) switch (cat) { case HungerCategory.Fed: - return 2.66666666E-05f * this.HungerRate; + { + return (float)(2.6666666599339806E-05 * this.HungerRate); + } case HungerCategory.Hungry: - return 2.66666666E-05f * this.HungerRate * 0.5f; + { + return (float)(2.6666666599339806E-05 * this.HungerRate * 0.5); + } case HungerCategory.UrgentlyHungry: - return 2.66666666E-05f * this.HungerRate * 0.25f; + { + return (float)(2.6666666599339806E-05 * this.HungerRate * 0.25); + } case HungerCategory.Starving: - return 2.66666666E-05f * this.HungerRate * 0.15f; + { + return (float)(2.6666666599339806E-05 * this.HungerRate * 0.15000000596046448); + } default: + { return 999f; } + } } public override void NeedInterval() { if (!base.IsFrozen) { - this.CurLevel -= this.FoodFallPerTick * 150f; + this.CurLevel -= (float)(this.FoodFallPerTick * 150.0); } if (!this.Starving) { @@ -174,18 +183,18 @@ public override void NeedInterval() { if (this.Starving) { - HealthUtility.AdjustSeverity(this.pawn, HediffDefOf.Malnutrition, 0.00113333331f); + HealthUtility.AdjustSeverity(base.pawn, HediffDefOf.Malnutrition, 0.00113333331f); } else { - HealthUtility.AdjustSeverity(this.pawn, HediffDefOf.Malnutrition, -0.00113333331f); + HealthUtility.AdjustSeverity(base.pawn, HediffDefOf.Malnutrition, -0.00113333331f); } } } public override void SetInitialLevel() { - if (this.pawn.RaceProps.Humanlike) + if (base.pawn.RaceProps.Humanlike) { base.CurLevelPercentage = 0.8f; } @@ -201,29 +210,18 @@ public override void SetInitialLevel() public override string GetTipString() { - return string.Concat(new string[] - { - base.LabelCap, - ": ", - base.CurLevelPercentage.ToStringPercent(), - " (", - this.CurLevel.ToString("0.##"), - " / ", - this.MaxLevel.ToString("0.##"), - ")\n", - this.def.description - }); + return base.LabelCap + ": " + base.CurLevelPercentage.ToStringPercent() + " (" + this.CurLevel.ToString("0.##") + " / " + this.MaxLevel.ToString("0.##") + ")\n" + base.def.description; } public override void DrawOnGUI(Rect rect, int maxThresholdMarkers = 2147483647, float customMargin = -1f, bool drawArrows = true, bool doTooltip = true) { - if (this.threshPercents == null) + if (base.threshPercents == null) { - this.threshPercents = new List(); + base.threshPercents = new List(); } - this.threshPercents.Clear(); - this.threshPercents.Add(this.PercentageThreshHungry); - this.threshPercents.Add(this.PercentageThreshUrgentlyHungry); + base.threshPercents.Clear(); + base.threshPercents.Add(this.PercentageThreshHungry); + base.threshPercents.Add(this.PercentageThreshUrgentlyHungry); base.DrawOnGUI(rect, maxThresholdMarkers, customMargin, drawArrows, doTooltip); } } diff --git a/Assembly-CSharp/RimWorld/Need_Joy.cs b/Assembly-CSharp/RimWorld/Need_Joy.cs index 6d05570fc..5b9065e10 100644 --- a/Assembly-CSharp/RimWorld/Need_Joy.cs +++ b/Assembly-CSharp/RimWorld/Need_Joy.cs @@ -27,23 +27,23 @@ public JoyCategory CurCategory { get { - if (this.CurLevel < 0.01f) + if (this.CurLevel < 0.0099999997764825821) { return JoyCategory.Empty; } - if (this.CurLevel < 0.15f) + if (this.CurLevel < 0.15000000596046448) { return JoyCategory.VeryLow; } - if (this.CurLevel < 0.3f) + if (this.CurLevel < 0.30000001192092896) { return JoyCategory.Low; } - if (this.CurLevel < 0.7f) + if (this.CurLevel < 0.699999988079071) { return JoyCategory.Satisfied; } - if (this.CurLevel < 0.85f) + if (this.CurLevel < 0.85000002384185791) { return JoyCategory.High; } @@ -58,20 +58,34 @@ private float FallPerTick switch (this.CurCategory) { case JoyCategory.Empty: + { return 1.00000007E-05f; + } case JoyCategory.VeryLow: + { return 4.00000044E-06f; + } case JoyCategory.Low: + { return 7.00000055E-06f; + } case JoyCategory.Satisfied: + { return 1.00000007E-05f; + } case JoyCategory.High: + { return 1.00000007E-05f; + } case JoyCategory.Extreme: + { return 1.00000007E-05f; + } default: + { throw new InvalidOperationException(); } + } } } @@ -79,7 +93,7 @@ public override int GUIChangeArrow { get { - return (!this.GainingJoy) ? -1 : 1; + return this.GainingJoy ? 1 : (-1); } } @@ -93,11 +107,11 @@ private bool GainingJoy public Need_Joy(Pawn pawn) : base(pawn) { - this.threshPercents = new List(); - this.threshPercents.Add(0.15f); - this.threshPercents.Add(0.3f); - this.threshPercents.Add(0.7f); - this.threshPercents.Add(0.85f); + base.threshPercents = new List(); + base.threshPercents.Add(0.15f); + base.threshPercents.Add(0.3f); + base.threshPercents.Add(0.7f); + base.threshPercents.Add(0.85f); } public override void ExposeData() @@ -121,8 +135,8 @@ public void GainJoy(float amount, JoyKindDef joyKind) { amount *= this.tolerances.JoyFactorFromTolerance(joyKind); } - amount = Mathf.Min(amount, 1f - this.CurLevel); - this.curLevelInt += amount; + amount = Mathf.Min(amount, (float)(1.0 - this.CurLevel)); + base.curLevelInt += amount; if (joyKind != null) { this.tolerances.Notify_JoyGained(amount, joyKind); @@ -137,9 +151,9 @@ public override void NeedInterval() this.tolerances.NeedInterval(); if (!this.GainingJoy) { - this.CurLevel -= this.FallPerTick * 150f; + this.CurLevel -= (float)(this.FallPerTick * 150.0); } - if (this.pawn.Downed && this.CurLevel < 0.25f) + if (base.pawn.Downed && this.CurLevel < 0.25) { this.CurLevel = 0.25f; } diff --git a/Assembly-CSharp/RimWorld/Need_Mood.cs b/Assembly-CSharp/RimWorld/Need_Mood.cs index b3f43927e..7be426221 100644 --- a/Assembly-CSharp/RimWorld/Need_Mood.cs +++ b/Assembly-CSharp/RimWorld/Need_Mood.cs @@ -1,4 +1,3 @@ -using System; using System.Collections.Generic; using System.Text; using UnityEngine; @@ -19,11 +18,11 @@ public override float CurInstantLevel get { float num = this.thoughts.TotalMoodOffset(); - if (this.pawn.IsColonist || this.pawn.IsPrisonerOfColony) + if (base.pawn.IsColonist || base.pawn.IsPrisonerOfColony) { num += Find.Storyteller.difficulty.colonistMoodOffset; } - return Mathf.Clamp01(this.def.baseLevel + num / 100f); + return Mathf.Clamp01((float)(base.def.baseLevel + num / 100.0)); } } @@ -31,28 +30,28 @@ public string MoodString { get { - if (this.pawn.MentalStateDef != null) + if (base.pawn.MentalStateDef != null) { return "Mood_MentalState".Translate(); } - float statValue = this.pawn.GetStatValue(StatDefOf.MentalBreakThreshold, true); + float statValue = base.pawn.GetStatValue(StatDefOf.MentalBreakThreshold, true); if (this.CurLevel < statValue) { return "Mood_AboutToBreak".Translate(); } - if (this.CurLevel < statValue + 0.05f) + if (this.CurLevel < statValue + 0.05000000074505806) { return "Mood_OnEdge".Translate(); } - if (this.CurLevel < 0.35f) + if (this.CurLevel < 0.34999999403953552) { return "Mood_Stressed".Translate(); } - if (this.CurLevel < 0.65f) + if (this.CurLevel < 0.64999997615814209) { return "Mood_Neutral".Translate(); } - if (this.CurLevel < 0.9f) + if (this.CurLevel < 0.89999997615814209) { return "Mood_Content".Translate(); } @@ -70,13 +69,13 @@ public Need_Mood(Pawn pawn) : base(pawn) public override void ExposeData() { base.ExposeData(); - Scribe_Deep.Look(ref this.thoughts, "thoughts", new object[] + Scribe_Deep.Look(ref this.thoughts, "thoughts", new object[1] { - this.pawn + base.pawn }); - Scribe_Deep.Look(ref this.recentMemory, "recentMemory", new object[] + Scribe_Deep.Look(ref this.recentMemory, "recentMemory", new object[1] { - this.pawn + base.pawn }); } @@ -93,22 +92,22 @@ public override string GetTipString() StringBuilder stringBuilder = new StringBuilder(); stringBuilder.AppendLine(base.GetTipString()); stringBuilder.AppendLine(); - stringBuilder.AppendLine("MentalBreakThresholdExtreme".Translate() + ": " + this.pawn.mindState.mentalBreaker.BreakThresholdExtreme.ToStringPercent()); - stringBuilder.AppendLine("MentalBreakThresholdMajor".Translate() + ": " + this.pawn.mindState.mentalBreaker.BreakThresholdMajor.ToStringPercent()); - stringBuilder.AppendLine("MentalBreakThresholdMinor".Translate() + ": " + this.pawn.mindState.mentalBreaker.BreakThresholdMinor.ToStringPercent()); + stringBuilder.AppendLine("MentalBreakThresholdExtreme".Translate() + ": " + base.pawn.mindState.mentalBreaker.BreakThresholdExtreme.ToStringPercent()); + stringBuilder.AppendLine("MentalBreakThresholdMajor".Translate() + ": " + base.pawn.mindState.mentalBreaker.BreakThresholdMajor.ToStringPercent()); + stringBuilder.AppendLine("MentalBreakThresholdMinor".Translate() + ": " + base.pawn.mindState.mentalBreaker.BreakThresholdMinor.ToStringPercent()); return stringBuilder.ToString(); } public override void DrawOnGUI(Rect rect, int maxThresholdMarkers = 2147483647, float customMargin = -1f, bool drawArrows = true, bool doTooltip = true) { - if (this.threshPercents == null) + if (base.threshPercents == null) { - this.threshPercents = new List(); + base.threshPercents = new List(); } - this.threshPercents.Clear(); - this.threshPercents.Add(this.pawn.mindState.mentalBreaker.BreakThresholdExtreme); - this.threshPercents.Add(this.pawn.mindState.mentalBreaker.BreakThresholdMajor); - this.threshPercents.Add(this.pawn.mindState.mentalBreaker.BreakThresholdMinor); + base.threshPercents.Clear(); + base.threshPercents.Add(base.pawn.mindState.mentalBreaker.BreakThresholdExtreme); + base.threshPercents.Add(base.pawn.mindState.mentalBreaker.BreakThresholdMajor); + base.threshPercents.Add(base.pawn.mindState.mentalBreaker.BreakThresholdMinor); base.DrawOnGUI(rect, maxThresholdMarkers, customMargin, drawArrows, doTooltip); } } diff --git a/Assembly-CSharp/RimWorld/Need_Rest.cs b/Assembly-CSharp/RimWorld/Need_Rest.cs index cc2a30bed..5a43f7b26 100644 --- a/Assembly-CSharp/RimWorld/Need_Rest.cs +++ b/Assembly-CSharp/RimWorld/Need_Rest.cs @@ -1,4 +1,3 @@ -using System; using System.Collections.Generic; using Verse; using Verse.AI; @@ -35,15 +34,15 @@ public RestCategory CurCategory { get { - if (this.CurLevel < 0.01f) + if (this.CurLevel < 0.0099999997764825821) { return RestCategory.Exhausted; } - if (this.CurLevel < 0.14f) + if (this.CurLevel < 0.14000000059604645) { return RestCategory.VeryTired; } - if (this.CurLevel < 0.28f) + if (this.CurLevel < 0.2800000011920929) { return RestCategory.Tired; } @@ -58,16 +57,26 @@ public float RestFallPerTick switch (this.CurCategory) { case RestCategory.Rested: - return 1.58333332E-05f * this.RestFallFactor; + { + return (float)(1.5833333236514591E-05 * this.RestFallFactor); + } case RestCategory.Tired: - return 1.58333332E-05f * this.RestFallFactor * 0.7f; + { + return (float)(1.5833333236514591E-05 * this.RestFallFactor * 0.699999988079071); + } case RestCategory.VeryTired: - return 1.58333332E-05f * this.RestFallFactor * 0.3f; + { + return (float)(1.5833333236514591E-05 * this.RestFallFactor * 0.30000001192092896); + } case RestCategory.Exhausted: - return 1.58333332E-05f * this.RestFallFactor * 0.6f; + { + return (float)(1.5833333236514591E-05 * this.RestFallFactor * 0.60000002384185791); + } default: + { return 999f; } + } } } @@ -76,7 +85,7 @@ private float RestFallFactor get { float num = 1f; - List hediffs = this.pawn.health.hediffSet.hediffs; + List hediffs = base.pawn.health.hediffSet.hediffs; for (int i = 0; i < hediffs.Count; i++) { HediffStage curStage = hediffs[i].CurStage; @@ -119,9 +128,9 @@ private bool Resting public Need_Rest(Pawn pawn) : base(pawn) { - this.threshPercents = new List(); - this.threshPercents.Add(0.28f); - this.threshPercents.Add(0.14f); + base.threshPercents = new List(); + base.threshPercents.Add(0.28f); + base.threshPercents.Add(0.14f); } public override void ExposeData() @@ -141,14 +150,14 @@ public override void NeedInterval() { if (this.Resting) { - this.CurLevel += 0.005714286f * this.lastRestEffectiveness; + this.CurLevel += (float)(0.0057142861187458038 * this.lastRestEffectiveness); } else { - this.CurLevel -= this.RestFallPerTick * 150f; + this.CurLevel -= (float)(this.RestFallPerTick * 150.0); } } - if (this.CurLevel < 0.0001f) + if (this.CurLevel < 9.9999997473787516E-05) { this.ticksAtZero += 150; } @@ -156,34 +165,15 @@ public override void NeedInterval() { this.ticksAtZero = 0; } - if (this.ticksAtZero > 1000 && this.pawn.Spawned) + if (this.ticksAtZero > 1000 && base.pawn.Spawned) { - float mtb; - if (this.ticksAtZero < 15000) - { - mtb = 0.25f; - } - else if (this.ticksAtZero < 30000) - { - mtb = 0.125f; - } - else if (this.ticksAtZero < 45000) - { - mtb = 0.0833333358f; - } - else - { - mtb = 0.0625f; - } + float mtb = (float)((this.ticksAtZero >= 15000) ? ((this.ticksAtZero >= 30000) ? ((this.ticksAtZero >= 45000) ? 0.0625 : 0.0833333358168602) : 0.125) : 0.25); if (Rand.MTBEventOccurs(mtb, 60000f, 150f)) { - this.pawn.jobs.StartJob(new Job(JobDefOf.LayDown, this.pawn.Position), JobCondition.InterruptForced, null, false, true, null, null); - if (PawnUtility.ShouldSendNotificationAbout(this.pawn)) + base.pawn.jobs.StartJob(new Job(JobDefOf.LayDown, base.pawn.Position), JobCondition.InterruptForced, null, false, true, null, default(JobTag?)); + if (PawnUtility.ShouldSendNotificationAbout(base.pawn)) { - Messages.Message("MessageInvoluntarySleep".Translate(new object[] - { - this.pawn.LabelShort - }), this.pawn, MessageSound.Negative); + Messages.Message("MessageInvoluntarySleep".Translate(base.pawn.LabelShort), (Thing)base.pawn, MessageSound.Negative); } } } diff --git a/Assembly-CSharp/RimWorld/Need_Seeker.cs b/Assembly-CSharp/RimWorld/Need_Seeker.cs index c5182f9ea..8f053bbbc 100644 --- a/Assembly-CSharp/RimWorld/Need_Seeker.cs +++ b/Assembly-CSharp/RimWorld/Need_Seeker.cs @@ -1,4 +1,3 @@ -using System; using UnityEngine; using Verse; @@ -12,16 +11,16 @@ public override int GUIChangeArrow { get { - if (!this.pawn.Awake()) + if (!base.pawn.Awake()) { return 0; } float curInstantLevelPercentage = base.CurInstantLevelPercentage; - if (curInstantLevelPercentage > base.CurLevelPercentage + 0.05f) + if (curInstantLevelPercentage > base.CurLevelPercentage + 0.05000000074505806) { return 1; } - if (curInstantLevelPercentage < base.CurLevelPercentage - 0.05f) + if (curInstantLevelPercentage < base.CurLevelPercentage - 0.05000000074505806) { return -1; } @@ -40,12 +39,12 @@ public override void NeedInterval() float curInstantLevel = this.CurInstantLevel; if (curInstantLevel > this.CurLevel) { - this.CurLevel += this.def.seekerRisePerHour * 0.06f; + this.CurLevel += (float)(base.def.seekerRisePerHour * 0.059999998658895493); this.CurLevel = Mathf.Min(this.CurLevel, curInstantLevel); } if (curInstantLevel < this.CurLevel) { - this.CurLevel -= this.def.seekerFallPerHour * 0.06f; + this.CurLevel -= (float)(base.def.seekerFallPerHour * 0.059999998658895493); this.CurLevel = Mathf.Max(this.CurLevel, curInstantLevel); } } diff --git a/Assembly-CSharp/RimWorld/Need_Space.cs b/Assembly-CSharp/RimWorld/Need_Space.cs index 1dbe68926..206cb0f51 100644 --- a/Assembly-CSharp/RimWorld/Need_Space.cs +++ b/Assembly-CSharp/RimWorld/Need_Space.cs @@ -1,4 +1,3 @@ -using System; using System.Collections.Generic; using Verse; @@ -52,15 +51,15 @@ public SpaceCategory CurCategory { get { - if (this.CurLevel < 0.01f) + if (this.CurLevel < 0.0099999997764825821) { return SpaceCategory.VeryCramped; } - if (this.CurLevel < 0.3f) + if (this.CurLevel < 0.30000001192092896) { return SpaceCategory.Cramped; } - if (this.CurLevel < 0.7f) + if (this.CurLevel < 0.699999988079071) { return SpaceCategory.Normal; } @@ -70,35 +69,32 @@ public SpaceCategory CurCategory public Need_Space(Pawn pawn) : base(pawn) { - this.threshPercents = new List(); - this.threshPercents.Add(0.3f); - this.threshPercents.Add(0.7f); + base.threshPercents = new List(); + base.threshPercents.Add(0.3f); + base.threshPercents.Add(0.7f); } public float SpacePerceptibleNow() { - if (!this.pawn.Spawned) + if (!base.pawn.Spawned) { return 1f; } - IntVec3 position = this.pawn.Position; + IntVec3 position = base.pawn.Position; Need_Space.tempScanRooms.Clear(); for (int i = 0; i < 5; i++) { IntVec3 loc = position + GenRadial.RadialPattern[i]; - Room room = loc.GetRoom(this.pawn.Map, RegionType.Set_Passable); + Room room = loc.GetRoom(base.pawn.Map, RegionType.Set_Passable); if (room != null) { if (i == 0 && room.PsychologicallyOutdoors) { return 1f; } - if (i == 0 || room.RegionType != RegionType.Portal) + if ((i == 0 || room.RegionType != RegionType.Portal) && !Need_Space.tempScanRooms.Contains(room)) { - if (!Need_Space.tempScanRooms.Contains(room)) - { - Need_Space.tempScanRooms.Add(room); - } + Need_Space.tempScanRooms.Add(room); } } } @@ -106,9 +102,9 @@ public float SpacePerceptibleNow() for (int j = 0; j < Need_Space.SampleNumCells; j++) { IntVec3 loc2 = position + GenRadial.RadialPattern[j]; - if (Need_Space.tempScanRooms.Contains(loc2.GetRoom(this.pawn.Map, RegionType.Set_Passable))) + if (Need_Space.tempScanRooms.Contains(loc2.GetRoom(base.pawn.Map, RegionType.Set_Passable))) { - num += 1f; + num = (float)(num + 1.0); } } Need_Space.tempScanRooms.Clear(); diff --git a/Assembly-CSharp/RimWorld/NeededWarmth.cs b/Assembly-CSharp/RimWorld/NeededWarmth.cs index eb7a2a2a1..230f7ee4c 100644 --- a/Assembly-CSharp/RimWorld/NeededWarmth.cs +++ b/Assembly-CSharp/RimWorld/NeededWarmth.cs @@ -1,11 +1,9 @@ -using System; - namespace RimWorld { public enum NeededWarmth : byte { - Any, - Warm, - Cool + Any = 0, + Warm = 1, + Cool = 2 } } diff --git a/Assembly-CSharp/RimWorld/NeedsCardUtility.cs b/Assembly-CSharp/RimWorld/NeedsCardUtility.cs index 3e8739dd1..a8680c9ca 100644 --- a/Assembly-CSharp/RimWorld/NeedsCardUtility.cs +++ b/Assembly-CSharp/RimWorld/NeedsCardUtility.cs @@ -41,7 +41,9 @@ public static Vector2 GetSize(Pawn pawn) { return NeedsCardUtility.FullSize; } - return new Vector2(225f, (float)NeedsCardUtility.displayNeeds.Count * Mathf.Min(70f, NeedsCardUtility.FullSize.y / (float)NeedsCardUtility.displayNeeds.Count)); + float num = (float)NeedsCardUtility.displayNeeds.Count; + Vector2 fullSize = NeedsCardUtility.FullSize; + return new Vector2(225f, num * Mathf.Min(70f, fullSize.y / (float)NeedsCardUtility.displayNeeds.Count)); } public static void DoNeedsMoodAndThoughts(Rect rect, Pawn pawn, ref Vector2 thoughtScrollPosition) @@ -70,7 +72,7 @@ public static void DoNeeds(Rect rect, Pawn pawn) rect2.y += 10f; } rect2.width *= 0.73f; - rect2.height = Mathf.Max(rect2.height * 0.666f, 30f); + rect2.height = Mathf.Max((float)(rect2.height * 0.66600000858306885), 30f); } need.DrawOnGUI(rect2, 2147483647, -1f, true, true); num = rect2.yMax; @@ -80,9 +82,9 @@ public static void DoNeeds(Rect rect, Pawn pawn) private static void DoMoodAndThoughts(Rect rect, Pawn pawn, ref Vector2 thoughtScrollPosition) { GUI.BeginGroup(rect); - Rect rect2 = new Rect(0f, 0f, rect.width * 0.8f, 70f); + Rect rect2 = new Rect(0f, 0f, (float)(rect.width * 0.800000011920929), 70f); pawn.needs.mood.DrawOnGUI(rect2, 2147483647, -1f, true, true); - Rect rect3 = new Rect(0f, 80f, rect.width, rect.height - 70f - 10f); + Rect rect3 = new Rect(0f, 80f, rect.width, (float)(rect.height - 70.0 - 10.0)); rect3 = rect3.ContractedBy(10f); NeedsCardUtility.DrawThoughtListing(rect3, pawn, ref thoughtScrollPosition); GUI.EndGroup(); @@ -104,26 +106,25 @@ private static void UpdateDisplayNeeds(Pawn pawn) private static void DrawThoughtListing(Rect listingRect, Pawn pawn, ref Vector2 thoughtScrollPosition) { - if (Event.current.type == EventType.Layout) + if (Event.current.type != EventType.Layout) { - return; - } - Text.Font = GameFont.Small; - PawnNeedsUIUtility.GetThoughtGroupsInDisplayOrder(pawn.needs.mood, NeedsCardUtility.thoughtGroupsPresent); - float height = (float)NeedsCardUtility.thoughtGroupsPresent.Count * 24f; - Widgets.BeginScrollView(listingRect, ref thoughtScrollPosition, new Rect(0f, 0f, listingRect.width - 16f, height), true); - Text.Anchor = TextAnchor.MiddleLeft; - float num = 0f; - for (int i = 0; i < NeedsCardUtility.thoughtGroupsPresent.Count; i++) - { - Rect rect = new Rect(0f, num, listingRect.width - 16f, 20f); - if (NeedsCardUtility.DrawThoughtGroup(rect, NeedsCardUtility.thoughtGroupsPresent[i], pawn)) + Text.Font = GameFont.Small; + PawnNeedsUIUtility.GetThoughtGroupsInDisplayOrder(pawn.needs.mood, NeedsCardUtility.thoughtGroupsPresent); + float height = (float)((float)NeedsCardUtility.thoughtGroupsPresent.Count * 24.0); + Widgets.BeginScrollView(listingRect, ref thoughtScrollPosition, new Rect(0f, 0f, (float)(listingRect.width - 16.0), height), true); + Text.Anchor = TextAnchor.MiddleLeft; + float num = 0f; + for (int i = 0; i < NeedsCardUtility.thoughtGroupsPresent.Count; i++) { - num += 24f; + Rect rect = new Rect(0f, num, (float)(listingRect.width - 16.0), 20f); + if (NeedsCardUtility.DrawThoughtGroup(rect, NeedsCardUtility.thoughtGroupsPresent[i], pawn)) + { + num = (float)(num + 24.0); + } } + Widgets.EndScrollView(); + Text.Anchor = TextAnchor.UpperLeft; } - Widgets.EndScrollView(); - Text.Anchor = TextAnchor.UpperLeft; } private static bool DrawThoughtGroup(Rect rect, Thought group, Pawn pawn) @@ -157,23 +158,14 @@ private static bool DrawThoughtGroup(Rect rect, Thought group, Pawn pawn) { if (NeedsCardUtility.thoughtGroup.Count == 1) { - stringBuilder.Append("ThoughtExpiresIn".Translate(new object[] - { - (group.def.DurationTicks - thought_Memory.age).ToStringTicksToPeriod(true, false, true) - })); + stringBuilder.Append("ThoughtExpiresIn".Translate((group.def.DurationTicks - thought_Memory.age).ToStringTicksToPeriod(true, false, true))); } else { Thought_Memory thought_Memory2 = (Thought_Memory)NeedsCardUtility.thoughtGroup[NeedsCardUtility.thoughtGroup.Count - 1]; - stringBuilder.Append("ThoughtStartsExpiringIn".Translate(new object[] - { - (group.def.DurationTicks - thought_Memory.age).ToStringTicksToPeriod(true, false, true) - })); + stringBuilder.Append("ThoughtStartsExpiringIn".Translate((group.def.DurationTicks - thought_Memory.age).ToStringTicksToPeriod(true, false, true))); stringBuilder.AppendLine(); - stringBuilder.Append("ThoughtFinishesExpiringIn".Translate(new object[] - { - (group.def.DurationTicks - thought_Memory2.age).ToStringTicksToPeriod(true, false, true) - })); + stringBuilder.Append("ThoughtFinishesExpiringIn".Translate((group.def.DurationTicks - thought_Memory2.age).ToStringTicksToPeriod(true, false, true))); } } } @@ -183,13 +175,16 @@ private static bool DrawThoughtGroup(Rect rect, Thought group, Pawn pawn) for (int i = 1; i < NeedsCardUtility.thoughtGroup.Count; i++) { bool flag2 = false; - for (int j = 0; j < i; j++) + int num = 0; + while (num < i) { - if (NeedsCardUtility.thoughtGroup[i].LabelCap == NeedsCardUtility.thoughtGroup[j].LabelCap) + if (!(NeedsCardUtility.thoughtGroup[i].LabelCap == NeedsCardUtility.thoughtGroup[num].LabelCap)) { - flag2 = true; - break; + num++; + continue; } + flag2 = true; + break; } if (!flag2) { @@ -206,7 +201,7 @@ private static bool DrawThoughtGroup(Rect rect, Thought group, Pawn pawn) TooltipHandler.TipRegion(rect, new TipSignal(stringBuilder.ToString(), 7291)); Text.WordWrap = false; Text.Anchor = TextAnchor.MiddleLeft; - Rect rect2 = new Rect(rect.x + 10f, rect.y, 225f, rect.height); + Rect rect2 = new Rect((float)(rect.x + 10.0), rect.y, 225f, rect.height); rect2.yMin -= 3f; rect2.yMax += 3f; string text = leadingThoughtInGroup.LabelCap; @@ -216,12 +211,12 @@ private static bool DrawThoughtGroup(Rect rect, Thought group, Pawn pawn) } Widgets.Label(rect2, text); Text.Anchor = TextAnchor.MiddleCenter; - float num = pawn.needs.mood.thoughts.MoodOffsetOfGroup(group); - if (num == 0f) + float num2 = pawn.needs.mood.thoughts.MoodOffsetOfGroup(group); + if (num2 == 0.0) { GUI.color = NeedsCardUtility.NoEffectColor; } - else if (num > 0f) + else if (num2 > 0.0) { GUI.color = NeedsCardUtility.MoodColor; } @@ -229,23 +224,15 @@ private static bool DrawThoughtGroup(Rect rect, Thought group, Pawn pawn) { GUI.color = NeedsCardUtility.MoodColorNegative; } - Rect rect3 = new Rect(rect.x + 235f, rect.y, 32f, rect.height); - Widgets.Label(rect3, num.ToString("##0")); + Rect rect3 = new Rect((float)(rect.x + 235.0), rect.y, 32f, rect.height); + Widgets.Label(rect3, num2.ToString("##0")); Text.Anchor = TextAnchor.UpperLeft; GUI.color = Color.white; Text.WordWrap = true; } catch (Exception ex) { - Log.ErrorOnce(string.Concat(new object[] - { - "Exception in DrawThoughtGroup for ", - group.def, - " on ", - pawn, - ": ", - ex.ToString() - }), 3452698); + Log.ErrorOnce("Exception in DrawThoughtGroup for " + group.def + " on " + pawn + ": " + ex.ToString(), 3452698); } return true; } diff --git a/Assembly-CSharp/RimWorld/NegativeInteractionUtility.cs b/Assembly-CSharp/RimWorld/NegativeInteractionUtility.cs index c027a014e..fc5c1526a 100644 --- a/Assembly-CSharp/RimWorld/NegativeInteractionUtility.cs +++ b/Assembly-CSharp/RimWorld/NegativeInteractionUtility.cs @@ -1,4 +1,3 @@ -using System; using Verse; namespace RimWorld @@ -78,7 +77,7 @@ public static float NegativeInteractionChanceFactor(Pawn initiator, Pawn recipie num *= NegativeInteractionUtility.CompatibilityFactorCurve.Evaluate(initiator.relations.CompatibilityWith(recipient)); if (initiator.story.traits.HasTrait(TraitDefOf.Abrasive)) { - num *= 2.3f; + num = (float)(num * 2.2999999523162842); } return num; } diff --git a/Assembly-CSharp/RimWorld/OpportunityType.cs b/Assembly-CSharp/RimWorld/OpportunityType.cs index 8a32b7b59..fd9d5d16a 100644 --- a/Assembly-CSharp/RimWorld/OpportunityType.cs +++ b/Assembly-CSharp/RimWorld/OpportunityType.cs @@ -1,11 +1,9 @@ -using System; - namespace RimWorld { public enum OpportunityType : byte { - GoodToKnow, - Important, - Critical + GoodToKnow = 0, + Important = 1, + Critical = 2 } } diff --git a/Assembly-CSharp/RimWorld/Outfit.cs b/Assembly-CSharp/RimWorld/Outfit.cs index 07e38fe30..11571eac2 100644 --- a/Assembly-CSharp/RimWorld/Outfit.cs +++ b/Assembly-CSharp/RimWorld/Outfit.cs @@ -1,4 +1,3 @@ -using System; using System.Text.RegularExpressions; using Verse; @@ -27,7 +26,7 @@ public Outfit(int uniqueId, string label) public void ExposeData() { Scribe_Values.Look(ref this.uniqueId, "uniqueId", 0, false); - Scribe_Values.Look(ref this.label, "label", null, false); + Scribe_Values.Look(ref this.label, "label", (string)null, false); Scribe_Deep.Look(ref this.filter, "filter", new object[0]); } diff --git a/Assembly-CSharp/RimWorld/OutfitDatabase.cs b/Assembly-CSharp/RimWorld/OutfitDatabase.cs index f65ba7ab2..aa0ab29d3 100644 --- a/Assembly-CSharp/RimWorld/OutfitDatabase.cs +++ b/Assembly-CSharp/RimWorld/OutfitDatabase.cs @@ -38,14 +38,11 @@ public Outfit DefaultOutfit() public AcceptanceReport TryDelete(Outfit outfit) { - foreach (Pawn current in PawnsFinder.AllMapsCaravansAndTravelingTransportPods) + foreach (Pawn allMapsCaravansAndTravelingTransportPod in PawnsFinder.AllMapsCaravansAndTravelingTransportPods) { - if (current.outfits != null && current.outfits.CurrentOutfit == outfit) + if (allMapsCaravansAndTravelingTransportPod.outfits != null && allMapsCaravansAndTravelingTransportPod.outfits.CurrentOutfit == outfit) { - return new AcceptanceReport("OutfitInUse".Translate(new object[] - { - current - })); + return new AcceptanceReport("OutfitInUse".Translate(allMapsCaravansAndTravelingTransportPod)); } } this.outfits.Remove(outfit); @@ -54,16 +51,7 @@ public AcceptanceReport TryDelete(Outfit outfit) public Outfit MakeNewOutfit() { - int arg_40_0; - if (this.outfits.Any()) - { - arg_40_0 = this.outfits.Max((Outfit o) => o.uniqueId) + 1; - } - else - { - arg_40_0 = 1; - } - int uniqueId = arg_40_0; + int uniqueId = (!this.outfits.Any()) ? 1 : (this.outfits.Max((Func)((Outfit o) => o.uniqueId)) + 1); Outfit outfit = new Outfit(uniqueId, "Outfit".Translate() + " " + uniqueId.ToString()); outfit.filter.SetAllow(ThingCategoryDefOf.Apparel, true, null, null); this.outfits.Add(outfit); @@ -78,33 +66,33 @@ private void GenerateStartingOutfits() outfit2.label = "OutfitWorker".Translate(); outfit2.filter.SetDisallowAll(null, null); outfit2.filter.SetAllow(SpecialThingFilterDefOf.AllowNonDeadmansApparel, true); - foreach (ThingDef current in DefDatabase.AllDefs) + foreach (ThingDef allDef in DefDatabase.AllDefs) { - if (current.apparel != null && current.apparel.defaultOutfitTags != null && current.apparel.defaultOutfitTags.Contains("Worker")) + if (allDef.apparel != null && allDef.apparel.defaultOutfitTags != null && allDef.apparel.defaultOutfitTags.Contains("Worker")) { - outfit2.filter.SetAllow(current, true); + outfit2.filter.SetAllow(allDef, true); } } Outfit outfit3 = this.MakeNewOutfit(); outfit3.label = "OutfitSoldier".Translate(); outfit3.filter.SetDisallowAll(null, null); outfit3.filter.SetAllow(SpecialThingFilterDefOf.AllowNonDeadmansApparel, true); - foreach (ThingDef current2 in DefDatabase.AllDefs) + foreach (ThingDef allDef2 in DefDatabase.AllDefs) { - if (current2.apparel != null && current2.apparel.defaultOutfitTags != null && current2.apparel.defaultOutfitTags.Contains("Soldier")) + if (allDef2.apparel != null && allDef2.apparel.defaultOutfitTags != null && allDef2.apparel.defaultOutfitTags.Contains("Soldier")) { - outfit3.filter.SetAllow(current2, true); + outfit3.filter.SetAllow(allDef2, true); } } Outfit outfit4 = this.MakeNewOutfit(); outfit4.label = "OutfitNudist".Translate(); outfit4.filter.SetDisallowAll(null, null); outfit4.filter.SetAllow(SpecialThingFilterDefOf.AllowNonDeadmansApparel, true); - foreach (ThingDef current3 in DefDatabase.AllDefs) + foreach (ThingDef allDef3 in DefDatabase.AllDefs) { - if (current3.apparel != null && !current3.apparel.bodyPartGroups.Contains(BodyPartGroupDefOf.Legs) && !current3.apparel.bodyPartGroups.Contains(BodyPartGroupDefOf.Torso)) + if (allDef3.apparel != null && !allDef3.apparel.bodyPartGroups.Contains(BodyPartGroupDefOf.Legs) && !allDef3.apparel.bodyPartGroups.Contains(BodyPartGroupDefOf.Torso)) { - outfit4.filter.SetAllow(current3, true); + outfit4.filter.SetAllow(allDef3, true); } } } diff --git a/Assembly-CSharp/RimWorld/OutfitForcedHandler.cs b/Assembly-CSharp/RimWorld/OutfitForcedHandler.cs index 9c7aadb14..a6aaa2d81 100644 --- a/Assembly-CSharp/RimWorld/OutfitForcedHandler.cs +++ b/Assembly-CSharp/RimWorld/OutfitForcedHandler.cs @@ -1,4 +1,3 @@ -using System; using System.Collections.Generic; using Verse; diff --git a/Assembly-CSharp/RimWorld/OverlayDrawHandler.cs b/Assembly-CSharp/RimWorld/OverlayDrawHandler.cs index 7b7c9cbca..c1fa6773c 100644 --- a/Assembly-CSharp/RimWorld/OverlayDrawHandler.cs +++ b/Assembly-CSharp/RimWorld/OverlayDrawHandler.cs @@ -1,4 +1,3 @@ -using System; using UnityEngine; using Verse; @@ -22,7 +21,15 @@ public static bool ShouldDrawZones { get { - return Find.PlaySettings.showZones || Time.frameCount <= OverlayDrawHandler.lastZoneDrawFrame + 1; + if (Find.PlaySettings.showZones) + { + return true; + } + if (Time.frameCount <= OverlayDrawHandler.lastZoneDrawFrame + 1) + { + return true; + } + return false; } } diff --git a/Assembly-CSharp/RimWorld/OverlayDrawer.cs b/Assembly-CSharp/RimWorld/OverlayDrawer.cs index c82508581..ba88adcce 100644 --- a/Assembly-CSharp/RimWorld/OverlayDrawer.cs +++ b/Assembly-CSharp/RimWorld/OverlayDrawer.cs @@ -63,9 +63,11 @@ public void DrawOverlay(Thing t, OverlayTypes overlayType) if (this.overlaysToDraw.ContainsKey(t)) { Dictionary dictionary; - Dictionary expr_17 = dictionary = this.overlaysToDraw; - OverlayTypes overlayTypes = dictionary[t]; - expr_17[t] = (overlayTypes | overlayType); + Dictionary obj = dictionary = this.overlaysToDraw; + Thing key; + Thing key2 = key = t; + OverlayTypes overlayTypes = dictionary[key]; + obj[key2] = (overlayTypes | overlayType); } else { @@ -75,68 +77,84 @@ public void DrawOverlay(Thing t, OverlayTypes overlayType) public void DrawAllOverlays() { - foreach (KeyValuePair current in this.overlaysToDraw) + Dictionary.Enumerator enumerator = this.overlaysToDraw.GetEnumerator(); + try { - this.curOffset = Vector3.zero; - Thing key = current.Key; - OverlayTypes value = current.Value; - if ((value & OverlayTypes.BurningWick) != (OverlayTypes)0) + while (enumerator.MoveNext()) { - this.RenderBurningWick(key); - } - else - { - OverlayTypes overlayTypes = OverlayTypes.NeedsPower | OverlayTypes.PowerOff; - int bitCountOf = Gen.GetBitCountOf((long)(value & overlayTypes)); - float num = this.StackOffsetFor(current.Key); - switch (bitCountOf) + KeyValuePair current = enumerator.Current; + this.curOffset = Vector3.zero; + Thing key = current.Key; + OverlayTypes value = current.Value; + if (((int)value & 4) != 0) { - case 1: - this.curOffset = Vector3.zero; - break; - case 2: - this.curOffset = new Vector3(-0.5f * num, 0f, 0f); - break; - case 3: - this.curOffset = new Vector3(-1.5f * num, 0f, 0f); - break; + this.RenderBurningWick(key); } - if ((value & OverlayTypes.NeedsPower) != (OverlayTypes)0) + else { - this.RenderNeedsPowerOverlay(key); + OverlayTypes overlayTypes = OverlayTypes.NeedsPower | OverlayTypes.PowerOff; + int bitCountOf = Gen.GetBitCountOf((long)(value & overlayTypes)); + float num = this.StackOffsetFor(current.Key); + switch (bitCountOf) + { + case 1: + { + this.curOffset = Vector3.zero; + break; + } + case 2: + { + this.curOffset = new Vector3((float)(-0.5 * num), 0f, 0f); + break; + } + case 3: + { + this.curOffset = new Vector3((float)(-1.5 * num), 0f, 0f); + break; + } + } + if (((int)value & 1) != 0) + { + this.RenderNeedsPowerOverlay(key); + } + if (((int)value & 2) != 0) + { + this.RenderPowerOffOverlay(key); + } + if (((int)value & 64) != 0) + { + this.RenderBrokenDownOverlay(key); + } + if (((int)value & 128) != 0) + { + this.RenderOutOfFuelOverlay(key); + } } - if ((value & OverlayTypes.PowerOff) != (OverlayTypes)0) + if (((int)value & 16) != 0) { - this.RenderPowerOffOverlay(key); + this.RenderForbiddenBigOverlay(key); } - if ((value & OverlayTypes.BrokenDown) != (OverlayTypes)0) + if (((int)value & 8) != 0) { - this.RenderBrokenDownOverlay(key); + this.RenderForbiddenOverlay(key); } - if ((value & OverlayTypes.OutOfFuel) != (OverlayTypes)0) + if (((int)value & 32) != 0) { - this.RenderOutOfFuelOverlay(key); + this.RenderQuestionMarkOverlay(key); } } - if ((value & OverlayTypes.ForbiddenBig) != (OverlayTypes)0) - { - this.RenderForbiddenBigOverlay(key); - } - if ((value & OverlayTypes.Forbidden) != (OverlayTypes)0) - { - this.RenderForbiddenOverlay(key); - } - if ((value & OverlayTypes.QuestionMark) != (OverlayTypes)0) - { - this.RenderQuestionMarkOverlay(key); - } + } + finally + { + ((IDisposable)(object)enumerator).Dispose(); } this.overlaysToDraw.Clear(); } private float StackOffsetFor(Thing t) { - return (float)t.RotatedSize.x * 0.25f; + IntVec2 rotatedSize = t.RotatedSize; + return (float)((float)rotatedSize.x * 0.25); } private void RenderNeedsPowerOverlay(Thing t) @@ -168,17 +186,17 @@ private void RenderPulsingOverlay(Thing thing, Material mat, int altInd) private void RenderPulsingOverlay(Thing thing, Material mat, int altInd, Mesh mesh) { Vector3 vector = thing.TrueCenter(); - vector.y = OverlayDrawer.BaseAlt + 0.046875f * (float)altInd; + vector.y = (float)(OverlayDrawer.BaseAlt + 0.046875 * (float)altInd); vector += this.curOffset; - this.curOffset.x = this.curOffset.x + this.StackOffsetFor(thing); + this.curOffset.x += this.StackOffsetFor(thing); this.RenderPulsingOverlay(thing, mat, vector, mesh); } private void RenderPulsingOverlay(Thing thing, Material mat, Vector3 drawPos, Mesh mesh) { - float num = (Time.realtimeSinceStartup + 397f * (float)(thing.thingIDNumber % 571)) * 4f; - float num2 = ((float)Math.Sin((double)num) + 1f) * 0.5f; - num2 = 0.3f + num2 * 0.7f; + float num = (float)((Time.realtimeSinceStartup + 397.0 * (float)(thing.thingIDNumber % 571)) * 4.0); + float num2 = (float)(((float)Math.Sin((double)num) + 1.0) * 0.5); + num2 = (float)(0.30000001192092896 + num2 * 0.699999988079071); Material material = FadedMaterialPool.FadedVersionOf(mat, num2); Graphics.DrawMesh(mesh, drawPos, Quaternion.identity, material, 0); } @@ -186,49 +204,44 @@ private void RenderPulsingOverlay(Thing thing, Material mat, Vector3 drawPos, Me private void RenderForbiddenOverlay(Thing t) { Vector3 drawPos = t.DrawPos; - if (t.RotatedSize.z == 1) + IntVec2 rotatedSize = t.RotatedSize; + if (rotatedSize.z == 1) { drawPos.z -= OverlayDrawer.SingleCellForbiddenOffset; } else { - drawPos.z -= (float)t.RotatedSize.z * 0.3f; + float z = drawPos.z; + IntVec2 rotatedSize2 = t.RotatedSize; + drawPos.z = (float)(z - (float)rotatedSize2.z * 0.30000001192092896); } - drawPos.y = OverlayDrawer.BaseAlt + 0.1875f; + drawPos.y = (float)(OverlayDrawer.BaseAlt + 0.1875); Graphics.DrawMesh(MeshPool.plane05, drawPos, Quaternion.identity, OverlayDrawer.ForbiddenMat, 0); } private void RenderForbiddenBigOverlay(Thing t) { Vector3 drawPos = t.DrawPos; - drawPos.y = OverlayDrawer.BaseAlt + 0.1875f; + drawPos.y = (float)(OverlayDrawer.BaseAlt + 0.1875); Graphics.DrawMesh(MeshPool.plane10, drawPos, Quaternion.identity, OverlayDrawer.ForbiddenMat, 0); } private void RenderBurningWick(Thing parent) { - Material material; - if (Rand.Value < 0.5f) - { - material = OverlayDrawer.WickMaterialA; - } - else - { - material = OverlayDrawer.WickMaterialB; - } + Material material = (!(Rand.Value < 0.5)) ? OverlayDrawer.WickMaterialB : OverlayDrawer.WickMaterialA; Vector3 drawPos = parent.DrawPos; - drawPos.y = OverlayDrawer.BaseAlt + 0.234375f; + drawPos.y = (float)(OverlayDrawer.BaseAlt + 0.234375); Graphics.DrawMesh(MeshPool.plane20, drawPos, Quaternion.identity, material, 0); } private void RenderQuestionMarkOverlay(Thing t) { Vector3 drawPos = t.DrawPos; - drawPos.y = OverlayDrawer.BaseAlt + 0.28125f; + drawPos.y = (float)(OverlayDrawer.BaseAlt + 0.28125); if (t is Pawn) { - drawPos.x += (float)t.def.size.x - 0.52f; - drawPos.z += (float)t.def.size.z - 0.45f; + drawPos.x += (float)((float)t.def.size.x - 0.51999998092651367); + drawPos.z += (float)((float)t.def.size.z - 0.44999998807907104); } this.RenderPulsingOverlay(t, OverlayDrawer.QuestionMarkMat, drawPos, MeshPool.plane05); } diff --git a/Assembly-CSharp/RimWorld/Page.cs b/Assembly-CSharp/RimWorld/Page.cs index 138f7bbda..a2f18a9a7 100644 --- a/Assembly-CSharp/RimWorld/Page.cs +++ b/Assembly-CSharp/RimWorld/Page.cs @@ -32,14 +32,14 @@ public virtual string PageTitle { get { - return null; + return (string)null; } } public Page() { - this.forcePause = true; - this.absorbInputAroundWindow = true; + base.forcePause = true; + base.absorbInputAroundWindow = true; } protected void DrawPageTitle(Rect rect) @@ -49,22 +49,27 @@ protected void DrawPageTitle(Rect rect) Text.Font = GameFont.Small; } - protected Rect GetMainRect(Rect rect, float extraTopSpace = 0f, bool ignoreTitle = false) + protected Rect GetMainRect(Rect rect, float extraTopSpace = 0, bool ignoreTitle = false) { float num = 0f; if (!ignoreTitle) { - num = 45f + extraTopSpace; + num = (float)(45.0 + extraTopSpace); } - return new Rect(0f, num, rect.width, rect.height - 38f - num - 17f); + return new Rect(0f, num, rect.width, (float)(rect.height - 38.0 - num - 17.0)); } protected void DoBottomButtons(Rect rect, string nextLabel = null, string midLabel = null, Action midAct = null, bool showNext = true) { - float y = rect.height - 38f; + float num = (float)(rect.height - 38.0); Text.Font = GameFont.Small; string label = "Back".Translate(); - Rect rect2 = new Rect(rect.x, y, Page.BottomButSize.x, Page.BottomButSize.y); + float x = rect.x; + float y = num; + Vector2 bottomButSize = Page.BottomButSize; + float x2 = bottomButSize.x; + Vector2 bottomButSize2 = Page.BottomButSize; + Rect rect2 = new Rect(x, y, x2, bottomButSize2.y); if (Widgets.ButtonText(rect2, label, true, false, true) && this.CanDoBack()) { this.DoBack(); @@ -75,16 +80,30 @@ protected void DoBottomButtons(Rect rect, string nextLabel = null, string midLab { nextLabel = "Next".Translate(); } - Rect rect3 = new Rect(rect.x + rect.width - Page.BottomButSize.x, y, Page.BottomButSize.x, Page.BottomButSize.y); + float num2 = rect.x + rect.width; + Vector2 bottomButSize3 = Page.BottomButSize; + float x3 = num2 - bottomButSize3.x; + float y2 = num; + Vector2 bottomButSize4 = Page.BottomButSize; + float x4 = bottomButSize4.x; + Vector2 bottomButSize5 = Page.BottomButSize; + Rect rect3 = new Rect(x3, y2, x4, bottomButSize5.y); if (Widgets.ButtonText(rect3, nextLabel, true, false, true) && this.CanDoNext()) { this.DoNext(); } UIHighlighter.HighlightOpportunity(rect3, "NextPage"); } - if (midAct != null) + if ((object)midAct != null) { - Rect rect4 = new Rect(rect.x + rect.width / 2f - Page.BottomButSize.x / 2f, y, Page.BottomButSize.x, Page.BottomButSize.y); + double num3 = rect.x + rect.width / 2.0; + Vector2 bottomButSize6 = Page.BottomButSize; + double x5 = num3 - bottomButSize6.x / 2.0; + float y3 = num; + Vector2 bottomButSize7 = Page.BottomButSize; + float x6 = bottomButSize7.x; + Vector2 bottomButSize8 = Page.BottomButSize; + Rect rect4 = new Rect((float)x5, y3, x6, bottomButSize8.y); if (Widgets.ButtonText(rect4, midLabel, true, false, true)) { midAct(); @@ -108,7 +127,7 @@ protected virtual void DoNext() { Find.WindowStack.Add(this.next); } - if (this.nextAct != null) + if ((object)this.nextAct != null) { this.nextAct(); } diff --git a/Assembly-CSharp/RimWorld/PageUtility.cs b/Assembly-CSharp/RimWorld/PageUtility.cs index a823da138..505bbbab6 100644 --- a/Assembly-CSharp/RimWorld/PageUtility.cs +++ b/Assembly-CSharp/RimWorld/PageUtility.cs @@ -9,7 +9,7 @@ public static class PageUtility { public static Page StitchedPages(IEnumerable pages) { - List list = pages.ToList(); + List list = pages.ToList(); if (list.Count == 0) { return null; @@ -30,7 +30,7 @@ public static Page StitchedPages(IEnumerable pages) public static void InitGameStart() { - Action preLoadLevelAction = delegate + Action preLoadLevelAction = (Action)delegate { Find.GameInitData.PrepForMapGen(); Find.GameInitData.startedFromEntry = true; diff --git a/Assembly-CSharp/RimWorld/Page_ConfigureStartingPawns.cs b/Assembly-CSharp/RimWorld/Page_ConfigureStartingPawns.cs index 7395f1c92..4c997e374 100644 --- a/Assembly-CSharp/RimWorld/Page_ConfigureStartingPawns.cs +++ b/Assembly-CSharp/RimWorld/Page_ConfigureStartingPawns.cs @@ -1,4 +1,5 @@ using System; +using System.Collections.Generic; using System.Linq; using UnityEngine; using Verse; @@ -46,20 +47,28 @@ public override void DoWindowContents(Rect rect) Rect mainRect = base.GetMainRect(rect, 30f, false); Widgets.DrawMenuSection(mainRect, true); TabDrawer.DrawTabs(mainRect, from c in Find.GameInitData.startingPawns - select new TabRecord(c.LabelCap, delegate + select new TabRecord(c.LabelCap, (Action)delegate() { this.SelectPawn(c); }, c == this.curPawn)); - Rect rect2 = mainRect.ContractedBy(17f); - Rect rect3 = rect2; - rect3.width = 100f; - GUI.DrawTexture(new Rect(rect3.xMin + (rect3.width - Page_ConfigureStartingPawns.PawnPortraitSize.x) / 2f - 10f, rect3.yMin + 20f, Page_ConfigureStartingPawns.PawnPortraitSize.x, Page_ConfigureStartingPawns.PawnPortraitSize.y), PortraitsCache.Get(this.curPawn, Page_ConfigureStartingPawns.PawnPortraitSize, default(Vector3), 1f)); - Rect rect4 = rect2; - rect4.xMin = rect3.xMax; + Rect rect2; + Rect rect3 = rect2 = mainRect.ContractedBy(17f); + rect2.width = 100f; + float xMin = rect2.xMin; + float width = rect2.width; + Vector2 pawnPortraitSize = Page_ConfigureStartingPawns.PawnPortraitSize; + double x = xMin + (width - pawnPortraitSize.x) / 2.0 - 10.0; + double y = rect2.yMin + 20.0; + Vector2 pawnPortraitSize2 = Page_ConfigureStartingPawns.PawnPortraitSize; + float x2 = pawnPortraitSize2.x; + Vector2 pawnPortraitSize3 = Page_ConfigureStartingPawns.PawnPortraitSize; + GUI.DrawTexture(new Rect((float)x, (float)y, x2, pawnPortraitSize3.y), PortraitsCache.Get(this.curPawn, Page_ConfigureStartingPawns.PawnPortraitSize, default(Vector3), 1f)); + Rect rect4 = rect3; + rect4.xMin = rect2.xMax; Rect rect5 = rect4; rect5.width = 475f; CharacterCardUtility.DrawCharacterCard(rect5, this.curPawn, new Action(this.RandomizeCurPawn)); - Rect rect6 = new Rect(rect5.xMax + 5f, rect4.y + 100f, rect4.width - rect5.width - 5f, 200f); + Rect rect6 = new Rect((float)(rect5.xMax + 5.0), (float)(rect4.y + 100.0), (float)(rect4.width - rect5.width - 5.0), 200f); Text.Font = GameFont.Medium; Widgets.Label(rect6, "Health".Translate()); Text.Font = GameFont.Small; @@ -71,32 +80,28 @@ public override void DoWindowContents(Rect rect) Text.Font = GameFont.Small; rect7.yMin += 35f; SocialCardUtility.DrawRelationsAndOpinions(rect7, this.curPawn); - base.DoBottomButtons(rect, "Start".Translate(), null, null, true); + base.DoBottomButtons(rect, "Start".Translate(), (string)null, null, true); } private void RandomizeCurPawn() { - if (!TutorSystem.AllowAction("RandomizePawn")) + if (TutorSystem.AllowAction("RandomizePawn")) { - return; - } - int num = 0; - while (true) - { - this.curPawn = StartingPawnUtility.RandomizeInPlace(this.curPawn); - num++; - if (num > 15) - { - break; - } - if (StartingPawnUtility.WorkTypeRequirementsSatisfied()) + int num = 0; + while (true) { - goto Block_3; + this.curPawn = StartingPawnUtility.RandomizeInPlace(this.curPawn); + num++; + if (num <= 15) + { + if (StartingPawnUtility.WorkTypeRequirementsSatisfied()) + break; + continue; + } + return; } + TutorSystem.Notify_Event("RandomizePawn"); } - return; - Block_3: - TutorSystem.Notify_Event("RandomizePawn"); } protected override bool CanDoNext() @@ -105,14 +110,23 @@ protected override bool CanDoNext() { return false; } - foreach (Pawn current in Find.GameInitData.startingPawns) + List.Enumerator enumerator = Find.GameInitData.startingPawns.GetEnumerator(); + try { - if (!current.Name.IsValid) + while (enumerator.MoveNext()) { - Messages.Message("EveryoneNeedsValidName".Translate(), MessageSound.RejectInput); - return false; + Pawn current = enumerator.Current; + if (!current.Name.IsValid) + { + Messages.Message("EveryoneNeedsValidName".Translate(), MessageSound.RejectInput); + return false; + } } } + finally + { + ((IDisposable)(object)enumerator).Dispose(); + } PortraitsCache.Clear(); return true; } diff --git a/Assembly-CSharp/RimWorld/Page_CreateWorldParams.cs b/Assembly-CSharp/RimWorld/Page_CreateWorldParams.cs index 9fd4621f8..e68bb71d8 100644 --- a/Assembly-CSharp/RimWorld/Page_CreateWorldParams.cs +++ b/Assembly-CSharp/RimWorld/Page_CreateWorldParams.cs @@ -20,14 +20,14 @@ public class Page_CreateWorldParams : Page private OverallTemperature temperature; - private static readonly float[] PlanetCoverages = new float[] + private static readonly float[] PlanetCoverages = new float[3] { 0.3f, 0.5f, 1f }; - private static readonly float[] PlanetCoveragesDev = new float[] + private static readonly float[] PlanetCoveragesDev = new float[4] { 0.3f, 0.5f, @@ -62,7 +62,7 @@ public override void PostOpen() public void Reset() { this.seedString = GenText.RandomSeedString(); - this.planetCoverage = ((Prefs.DevMode && UnityData.isEditor) ? 0.05f : 0.3f); + this.planetCoverage = (float)((Prefs.DevMode && UnityData.isEditor) ? 0.05000000074505806 : 0.30000001192092896); this.rainfall = OverallRainfall.Normal; this.temperature = OverallTemperature.Normal; } @@ -76,14 +76,14 @@ public override void DoWindowContents(Rect rect) Widgets.Label(new Rect(0f, num, 200f, 30f), "WorldSeed".Translate()); Rect rect2 = new Rect(200f, num, 200f, 30f); this.seedString = Widgets.TextField(rect2, this.seedString); - num += 40f; + num = (float)(num + 40.0); Rect rect3 = new Rect(200f, num, 200f, 30f); if (Widgets.ButtonText(rect3, "RandomizeSeed".Translate(), true, false, true)) { SoundDefOf.TickTiny.PlayOneShotOnCamera(null); this.seedString = GenText.RandomSeedString(); } - num += 40f; + num = (float)(num + 40.0); Widgets.Label(new Rect(0f, num, 200f, 30f), "PlanetCoverage".Translate()); Rect rect4 = new Rect(200f, num, 200f, 30f); if (Widgets.ButtonText(rect4, this.planetCoverage.ToStringPercent(), true, false, true)) @@ -94,16 +94,16 @@ public override void DoWindowContents(Rect rect) { float coverage = array[i]; string text = coverage.ToStringPercent(); - if (coverage <= 0.1f) + if (coverage <= 0.10000000149011612) { text += " (dev)"; } - FloatMenuOption item = new FloatMenuOption(text, delegate + FloatMenuOption item = new FloatMenuOption(text, (Action)delegate { if (this.planetCoverage != coverage) { this.planetCoverage = coverage; - if (this.planetCoverage == 1f) + if (this.planetCoverage == 1.0) { Messages.Message("MessageMaxPlanetCoveragePerformanceWarning".Translate(), MessageSound.Standard); } @@ -114,11 +114,11 @@ public override void DoWindowContents(Rect rect) Find.WindowStack.Add(new FloatMenu(list)); } TooltipHandler.TipRegion(new Rect(0f, num, rect4.xMax, rect4.height), "PlanetCoverageTip".Translate()); - num += 40f; + num = (float)(num + 40.0); Widgets.Label(new Rect(0f, num, 200f, 30f), "PlanetRainfall".Translate()); Rect rect5 = new Rect(200f, num, 200f, 30f); this.rainfall = (OverallRainfall)Mathf.RoundToInt(Widgets.HorizontalSlider(rect5, (float)this.rainfall, 0f, (float)(OverallRainfallUtility.EnumValuesCount - 1), true, "PlanetRainfall_Normal".Translate(), "PlanetRainfall_Low".Translate(), "PlanetRainfall_High".Translate(), 1f)); - num += 40f; + num = (float)(num + 40.0); Widgets.Label(new Rect(0f, num, 200f, 30f), "PlanetTemperature".Translate()); Rect rect6 = new Rect(200f, num, 200f, 30f); this.temperature = (OverallTemperature)Mathf.RoundToInt(Widgets.HorizontalSlider(rect6, (float)this.temperature, 0f, (float)(OverallTemperatureUtility.EnumValuesCount - 1), true, "PlanetTemperature_Normal".Translate(), "PlanetTemperature_Low".Translate(), "PlanetTemperature_High".Translate(), 1f)); @@ -132,15 +132,15 @@ protected override bool CanDoNext() { return false; } - LongEventHandler.QueueLongEvent(delegate + LongEventHandler.QueueLongEvent((Action)delegate { Find.GameInitData.ResetWorldRelatedMapInitData(); Current.Game.World = WorldGenerator.GenerateWorld(this.planetCoverage, this.seedString, this.rainfall, this.temperature); - LongEventHandler.ExecuteWhenFinished(delegate + LongEventHandler.ExecuteWhenFinished((Action)delegate { - if (this.next != null) + if (base.next != null) { - Find.WindowStack.Add(this.next); + Find.WindowStack.Add(base.next); } MemoryUtility.UnloadUnusedUnityAssets(); Find.World.renderer.RegenerateAllLayersNow(); diff --git a/Assembly-CSharp/RimWorld/Page_ModsConfig.cs b/Assembly-CSharp/RimWorld/Page_ModsConfig.cs index 9a52d8946..020d9d3a2 100644 --- a/Assembly-CSharp/RimWorld/Page_ModsConfig.cs +++ b/Assembly-CSharp/RimWorld/Page_ModsConfig.cs @@ -1,7 +1,6 @@ using Steamworks; using System; using System.Collections.Generic; -using System.Diagnostics; using System.Linq; using UnityEngine; using Verse; @@ -40,24 +39,32 @@ public class Page_ModsConfig : Page public Page_ModsConfig() { - this.doCloseButton = true; + base.doCloseButton = true; } public override void PreOpen() { base.PreOpen(); ModLister.RebuildModList(); - this.selectedMod = this.ModsInListOrder().FirstOrDefault(); + this.selectedMod = this.ModsInListOrder().FirstOrDefault(); this.activeModsWhenOpenedHash = ModLister.InstalledModsListHash(true); } - [DebuggerHidden] private IEnumerable ModsInListOrder() { - Page_ModsConfig.c__Iterator19C c__Iterator19C = new Page_ModsConfig.c__Iterator19C(); - Page_ModsConfig.c__Iterator19C expr_07 = c__Iterator19C; - expr_07.$PC = -2; - return expr_07; + foreach (ModMetaData item in ModsConfig.ActiveModsInLoadOrder) + { + yield return item; + } + foreach (ModMetaData item2 in from m in ModLister.AllInstalledMods + orderby m.VersionCompatible descending + select m) + { + if (!item2.Active) + { + yield return item2; + } + } } public override void DoWindowContents(Rect rect) @@ -71,32 +78,32 @@ public override void DoWindowContents(Rect rect) { SteamUtility.OpenSteamWorkshopPage(); } - num += 30f; + num = (float)(num + 30.0); Rect rect3 = new Rect(17f, num, 316f, 30f); if (Widgets.ButtonText(rect3, "GetModsFromForum".Translate(), true, false, true)) { Application.OpenURL("http://rimworldgame.com/getmods"); } - num += 30f; - num += 17f; + num = (float)(num + 30.0); + num = (float)(num + 17.0); Rect rect4 = new Rect(0f, num, 350f, mainRect.height - num); Widgets.DrawMenuSection(rect4, true); - float height = (float)(ModLister.AllInstalledMods.Count() * 34 + 300); - Rect rect5 = new Rect(0f, 0f, rect4.width - 16f, height); + float height = (float)(ModLister.AllInstalledMods.Count() * 34 + 300); + Rect rect5 = new Rect(0f, 0f, (float)(rect4.width - 16.0), height); Widgets.BeginScrollView(rect4, ref this.modListScrollPosition, rect5, true); Rect rect6 = rect5.ContractedBy(4f); Listing_Standard listing_Standard = new Listing_Standard(); listing_Standard.ColumnWidth = rect6.width; listing_Standard.Begin(rect6); - int reorderableGroup = ReorderableWidget.NewGroup(delegate(int from, int to) + int reorderableGroup = ReorderableWidget.NewGroup((Action)delegate(int from, int to) { ModsConfig.Reorder(from, to); SoundDefOf.TickHigh.PlayOneShotOnCamera(null); }); int num2 = 0; - foreach (ModMetaData current in this.ModsInListOrder()) + foreach (ModMetaData item in this.ModsInListOrder()) { - this.DoModRow(listing_Standard, current, num2, reorderableGroup); + this.DoModRow(listing_Standard, item, num2, reorderableGroup); num2++; } for (int i = 0; i < WorkshopItems.DownloadingItemsCount; i++) @@ -106,7 +113,7 @@ public override void DoWindowContents(Rect rect) } listing_Standard.End(); Widgets.EndScrollView(); - Rect position = new Rect(rect4.xMax + 17f, 0f, mainRect.width - rect4.width - 17f, mainRect.height); + Rect position = new Rect((float)(rect4.xMax + 17.0), 0f, (float)(mainRect.width - rect4.width - 17.0), mainRect.height); GUI.BeginGroup(position); if (this.selectedMod != null) { @@ -124,37 +131,36 @@ public override void DoWindowContents(Rect rect) { GUI.color = Color.red; } - Widgets.Label(rect8, "ModTargetVersion".Translate(new object[] - { - this.selectedMod.TargetVersion - })); + Widgets.Label(rect8, "ModTargetVersion".Translate(this.selectedMod.TargetVersion)); GUI.color = Color.white; Text.Anchor = TextAnchor.UpperLeft; Text.Font = GameFont.Small; } Rect position2 = new Rect(0f, rect7.yMax, 0f, 20f); - if (this.selectedMod.previewImage != null) + if ((UnityEngine.Object)this.selectedMod.previewImage != (UnityEngine.Object)null) { position2.width = Mathf.Min((float)this.selectedMod.previewImage.width, position.width); position2.height = (float)this.selectedMod.previewImage.height * (position2.width / (float)this.selectedMod.previewImage.width); - if (position2.height > 300f) + if (position2.height > 300.0) { - position2.width *= 300f / position2.height; + position2.width *= (float)(300.0 / position2.height); position2.height = 300f; } - position2.x = position.width / 2f - position2.width / 2f; + position2.x = (float)(position.width / 2.0 - position2.width / 2.0); GUI.DrawTexture(position2, this.selectedMod.previewImage, ScaleMode.ScaleToFit); } Text.Font = GameFont.Small; - float num3 = position2.yMax + 10f; + float num3 = (float)(position2.yMax + 10.0); if (!this.selectedMod.Author.NullOrEmpty()) { - Rect rect9 = new Rect(0f, num3, position.width / 2f, 25f); + Rect rect9 = new Rect(0f, num3, (float)(position.width / 2.0), 25f); Widgets.Label(rect9, "Author".Translate() + ": " + this.selectedMod.Author); } if (!this.selectedMod.Url.NullOrEmpty()) { - float num4 = Mathf.Min(position.width / 2f, Text.CalcSize(this.selectedMod.Url).x); + double a = position.width / 2.0; + Vector2 vector = Text.CalcSize(this.selectedMod.Url); + float num4 = Mathf.Min((float)a, vector.x); Rect rect10 = new Rect(position.width - num4, num3, num4, 25f); Text.WordWrap = false; if (Widgets.ButtonText(rect10, this.selectedMod.Url, false, false, true)) @@ -163,60 +169,54 @@ public override void DoWindowContents(Rect rect) } Text.WordWrap = true; } - WidgetRow widgetRow = new WidgetRow(position.width, num3 + 25f, UIDirection.LeftThenUp, 99999f, 4f); + WidgetRow widgetRow = new WidgetRow(position.width, (float)(num3 + 25.0), UIDirection.LeftThenUp, 99999f, 4f); if (SteamManager.Initialized && this.selectedMod.OnSteamWorkshop) { - if (widgetRow.ButtonText("Unsubscribe", null, true, false)) + if (widgetRow.ButtonText("Unsubscribe", (string)null, true, false)) { - Find.WindowStack.Add(Dialog_MessageBox.CreateConfirmation("ConfirmUnsubscribe".Translate(new object[] - { - this.selectedMod.Name - }), delegate + Find.WindowStack.Add(Dialog_MessageBox.CreateConfirmation("ConfirmUnsubscribe".Translate(this.selectedMod.Name), (Action)delegate { this.selectedMod.enabled = false; Workshop.Unsubscribe(this.selectedMod); this.Notify_SteamItemUnsubscribed(this.selectedMod.GetPublishedFileId()); - }, true, null)); + }, true, (string)null)); } - if (widgetRow.ButtonText("WorkshopPage".Translate(), null, true, false)) + if (widgetRow.ButtonText("WorkshopPage".Translate(), (string)null, true, false)) { SteamUtility.OpenWorkshopPage(this.selectedMod.GetPublishedFileId()); } } - float num5 = num3 + 25f + 24f; - Rect outRect = new Rect(0f, num5, position.width, position.height - num5 - 40f); - float width = outRect.width - 16f; + float num5 = (float)(num3 + 25.0 + 24.0); + Rect outRect = new Rect(0f, num5, position.width, (float)(position.height - num5 - 40.0)); + float width = (float)(outRect.width - 16.0); Rect rect11 = new Rect(0f, 0f, width, Text.CalcHeight(this.selectedMod.Description, width)); Widgets.BeginScrollView(outRect, ref this.modDescriptionScrollPosition, rect11, true); Widgets.Label(rect11, this.selectedMod.Description); Widgets.EndScrollView(); if (Prefs.DevMode && SteamManager.Initialized && this.selectedMod.CanToUploadToWorkshop()) { - Rect rect12 = new Rect(0f, position.yMax - 40f, 200f, 40f); + Rect rect12 = new Rect(0f, (float)(position.yMax - 40.0), 200f, 40f); if (Widgets.ButtonText(rect12, Workshop.UploadButtonLabel(this.selectedMod.GetPublishedFileId()), true, false, true)) { if (!VersionControl.IsWellFormattedVersionString(this.selectedMod.TargetVersion)) { - Messages.Message("MessageModNeedsWellFormattedTargetVersion".Translate(new object[] - { - VersionControl.CurrentVersionString - }), MessageSound.RejectInput); + Messages.Message("MessageModNeedsWellFormattedTargetVersion".Translate(VersionControl.CurrentVersionString), MessageSound.RejectInput); } else { - Find.WindowStack.Add(Dialog_MessageBox.CreateConfirmation("ConfirmSteamWorkshopUpload".Translate(), delegate + Find.WindowStack.Add(Dialog_MessageBox.CreateConfirmation("ConfirmSteamWorkshopUpload".Translate(), (Action)delegate { SoundDefOf.TickHigh.PlayOneShotOnCamera(null); - Dialog_MessageBox dialog_MessageBox = Dialog_MessageBox.CreateConfirmation("ConfirmContentAuthor".Translate(), delegate + Dialog_MessageBox dialog_MessageBox = Dialog_MessageBox.CreateConfirmation("ConfirmContentAuthor".Translate(), (Action)delegate { SoundDefOf.TickHigh.PlayOneShotOnCamera(null); Workshop.Upload(this.selectedMod); - }, true, null); + }, true, (string)null); dialog_MessageBox.buttonAText = "Yes".Translate(); dialog_MessageBox.buttonBText = "No".Translate(); dialog_MessageBox.interactionDelay = 6f; Find.WindowStack.Add(dialog_MessageBox); - }, true, null)); + }, true, (string)null)); } } } @@ -235,7 +235,7 @@ private void DoModRow(Listing_Standard listing, ModMetaData mod, int index, int Action clickAction = null; if (mod.Source == ContentSource.SteamWorkshop) { - clickAction = delegate + clickAction = (Action)delegate() { SteamUtility.OpenWorkshopPage(mod.GetPublishedFileId()); }; @@ -261,12 +261,12 @@ private void DoModRow(Listing_Standard listing, ModMetaData mod, int index, int { TooltipHandler.TipRegion(rect2, new TipSignal(text, mod.GetHashCode() * 3311)); } - float num = rect2.width - 24f; + float num = (float)(rect2.width - 24.0); if (mod.Active) { - Rect position = new Rect(rect2.xMax - 48f + 2f, rect2.y, 24f, 24f); + Rect position = new Rect((float)(rect2.xMax - 48.0 + 2.0), rect2.y, 24f, 24f); GUI.DrawTexture(position, TexButton.DragHash); - num -= 24f; + num = (float)(num - 24.0); } Text.Font = GameFont.Small; string label = mod.Name.Truncate(num, this.truncatedModNamesCache); @@ -277,11 +277,11 @@ private void DoModRow(Listing_Standard listing, ModMetaData mod, int index, int if (mod.Active && !active && mod.Name == ModContentPack.CoreModIdentifier) { ModMetaData coreMod = mod; - Find.WindowStack.Add(Dialog_MessageBox.CreateConfirmation("ConfirmDisableCoreMod".Translate(), delegate + Find.WindowStack.Add(Dialog_MessageBox.CreateConfirmation("ConfirmDisableCoreMod".Translate(), (Action)delegate { coreMod.Active = false; this.truncatedModNamesCache.Clear(); - }, false, null)); + }, false, (string)null)); } else { @@ -308,7 +308,7 @@ private void DoModRowDownloading(Listing_Standard listing, int index) public void Notify_ModsListChanged() { string selModId = this.selectedMod.Identifier; - this.selectedMod = ModLister.AllInstalledMods.FirstOrDefault((ModMetaData m) => m.Identifier == selModId); + this.selectedMod = ModLister.AllInstalledMods.FirstOrDefault((Func)((ModMetaData m) => m.Identifier == selModId)); } internal void Notify_SteamItemUnsubscribed(PublishedFileId_t pfid) @@ -324,12 +324,12 @@ public override void PostClose() ModsConfig.Save(); if (this.activeModsWhenOpenedHash != ModLister.InstalledModsListHash(true)) { - WindowStack arg_4E_0 = Find.WindowStack; - Action buttonAAction = delegate + WindowStack windowStack = Find.WindowStack; + Action buttonAAction = (Action)delegate { GenCommandLine.Restart(); }; - arg_4E_0.Add(new Dialog_MessageBox("ModsChanged".Translate(), null, buttonAAction, null, null, null, false)); + windowStack.Add(new Dialog_MessageBox("ModsChanged".Translate(), (string)null, buttonAAction, (string)null, null, (string)null, false)); } } } diff --git a/Assembly-CSharp/RimWorld/Page_ScenarioEditor.cs b/Assembly-CSharp/RimWorld/Page_ScenarioEditor.cs index 588e42c78..2cb96b3fb 100644 --- a/Assembly-CSharp/RimWorld/Page_ScenarioEditor.cs +++ b/Assembly-CSharp/RimWorld/Page_ScenarioEditor.cs @@ -59,9 +59,9 @@ public override void DoWindowContents(Rect rect) base.DrawPageTitle(rect); Rect mainRect = base.GetMainRect(rect, 0f, false); GUI.BeginGroup(mainRect); - Rect rect2 = new Rect(0f, 0f, mainRect.width * 0.35f, mainRect.height).Rounded(); + Rect rect2 = new Rect(0f, 0f, (float)(mainRect.width * 0.34999999403953552), mainRect.height).Rounded(); this.DoConfigControls(rect2); - Rect rect3 = new Rect(rect2.xMax + 17f, 0f, mainRect.width - rect2.width - 17f, mainRect.height).Rounded(); + Rect rect3 = new Rect((float)(rect2.xMax + 17.0), 0f, (float)(mainRect.width - rect2.width - 17.0), mainRect.height).Rounded(); if (!this.editMode) { ScenarioUI.DrawScenarioInfo(rect3, this.curScen, ref this.infoScrollPosition); @@ -71,7 +71,7 @@ public override void DoWindowContents(Rect rect) ScenarioUI.DrawScenarioEditInterface(rect3, this.curScen, ref this.infoScrollPosition); } GUI.EndGroup(); - base.DoBottomButtons(rect, null, null, null, true); + base.DoBottomButtons(rect, (string)null, (string)null, null, true); } private void RandomizeSeedAndScenario() @@ -85,19 +85,19 @@ private void DoConfigControls(Rect rect) Listing_Standard listing_Standard = new Listing_Standard(); listing_Standard.ColumnWidth = 200f; listing_Standard.Begin(rect); - if (listing_Standard.ButtonText("Load".Translate(), null)) + if (listing_Standard.ButtonText("Load".Translate(), (string)null)) { - Find.WindowStack.Add(new Dialog_ScenarioList_Load(delegate(Scenario loadedScen) + Find.WindowStack.Add(new Dialog_ScenarioList_Load((Action)delegate(Scenario loadedScen) { this.curScen = loadedScen; this.seedIsValid = false; })); } - if (listing_Standard.ButtonText("Save".Translate(), null) && Page_ScenarioEditor.CheckAllPartsCompatible(this.curScen)) + if (listing_Standard.ButtonText("Save".Translate(), (string)null) && Page_ScenarioEditor.CheckAllPartsCompatible(this.curScen)) { Find.WindowStack.Add(new Dialog_ScenarioList_Save(this.curScen)); } - if (listing_Standard.ButtonText("RandomizeSeed".Translate(), null)) + if (listing_Standard.ButtonText("RandomizeSeed".Translate(), (string)null)) { SoundDefOf.TickTiny.PlayOneShotOnCamera(null); this.RandomizeSeedAndScenario(); @@ -115,17 +115,17 @@ private void DoConfigControls(Rect rect) } else { - listing_Standard.Gap(Text.LineHeight + Text.LineHeight + 2f); + listing_Standard.Gap((float)(Text.LineHeight + Text.LineHeight + 2.0)); } - listing_Standard.CheckboxLabeled("EditMode".Translate().CapitalizeFirst(), ref this.editMode, null); + listing_Standard.CheckboxLabeled("EditMode".Translate().CapitalizeFirst(), ref this.editMode, (string)null); if (this.editMode) { this.seedIsValid = false; - if (listing_Standard.ButtonText("AddPart".Translate(), null)) + if (listing_Standard.ButtonText("AddPart".Translate(), (string)null)) { this.OpenAddScenPartMenu(); } - if (SteamManager.Initialized && (this.curScen.Category == ScenarioCategory.CustomLocal || this.curScen.Category == ScenarioCategory.SteamWorkshop) && listing_Standard.ButtonText(Workshop.UploadButtonLabel(this.curScen.GetPublishedFileId()), null) && Page_ScenarioEditor.CheckAllPartsCompatible(this.curScen)) + if (SteamManager.Initialized && (this.curScen.Category == ScenarioCategory.CustomLocal || this.curScen.Category == ScenarioCategory.SteamWorkshop) && listing_Standard.ButtonText(Workshop.UploadButtonLabel(this.curScen.GetPublishedFileId()), (string)null) && Page_ScenarioEditor.CheckAllPartsCompatible(this.curScen)) { AcceptanceReport acceptanceReport = this.curScen.TryUploadReport(); if (!acceptanceReport.Accepted) @@ -135,15 +135,15 @@ private void DoConfigControls(Rect rect) else { SoundDefOf.TickHigh.PlayOneShotOnCamera(null); - Find.WindowStack.Add(Dialog_MessageBox.CreateConfirmation("ConfirmSteamWorkshopUpload".Translate(), delegate + Find.WindowStack.Add(Dialog_MessageBox.CreateConfirmation("ConfirmSteamWorkshopUpload".Translate(), (Action)delegate { SoundDefOf.TickHigh.PlayOneShotOnCamera(null); - Find.WindowStack.Add(Dialog_MessageBox.CreateConfirmation("ConfirmContentAuthor".Translate(), delegate + Find.WindowStack.Add(Dialog_MessageBox.CreateConfirmation("ConfirmContentAuthor".Translate(), (Action)delegate { SoundDefOf.TickHigh.PlayOneShotOnCamera(null); Workshop.Upload(this.curScen); - }, true, null)); - }, true, null)); + }, true, (string)null)); + }, true, (string)null)); } } } @@ -152,36 +152,24 @@ private void DoConfigControls(Rect rect) private static bool CheckAllPartsCompatible(Scenario scen) { - foreach (ScenPart current in scen.AllParts) + foreach (ScenPart allPart in scen.AllParts) { int num = 0; - foreach (ScenPart current2 in scen.AllParts) + foreach (ScenPart allPart2 in scen.AllParts) { - if (current2.def == current.def) + if (allPart2.def == allPart.def) { num++; } - if (num > current.def.maxUses) + if (num > allPart.def.maxUses) { - Messages.Message("TooMany".Translate(new object[] - { - current.def.maxUses - }) + ": " + current.def.label, MessageSound.RejectInput); - bool result = false; - return result; + Messages.Message("TooMany".Translate(allPart.def.maxUses) + ": " + allPart.def.label, MessageSound.RejectInput); + return false; } - if (current != current2 && !current.CanCoexistWith(current2)) + if (allPart != allPart2 && !allPart.CanCoexistWith(allPart2)) { - Messages.Message(string.Concat(new string[] - { - "Incompatible".Translate(), - ": ", - current.def.label, - ", ", - current2.def.label - }), MessageSound.RejectInput); - bool result = false; - return result; + Messages.Message("Incompatible".Translate() + ": " + allPart.def.label + ", " + allPart2.def.label, MessageSound.RejectInput); + return false; } } } @@ -190,13 +178,13 @@ private static bool CheckAllPartsCompatible(Scenario scen) private void OpenAddScenPartMenu() { - FloatMenuUtility.MakeMenu(from p in ScenarioMaker.AddableParts(this.curScen) + FloatMenuUtility.MakeMenu(from p in ScenarioMaker.AddableParts(this.curScen) where p.category != ScenPartCategory.Fixed orderby p.label - select p, (ScenPartDef p) => p.LabelCap, (ScenPartDef p) => delegate + select p, (Func)((ScenPartDef p) => p.LabelCap), (Func)((ScenPartDef p) => (Action)delegate() { this.AddScenPart(p); - }); + })); } private void AddScenPart(ScenPartDef def) diff --git a/Assembly-CSharp/RimWorld/Page_SelectLandingSite.cs b/Assembly-CSharp/RimWorld/Page_SelectLandingSite.cs index 88f7a1e8a..f401d4aa4 100644 --- a/Assembly-CSharp/RimWorld/Page_SelectLandingSite.cs +++ b/Assembly-CSharp/RimWorld/Page_SelectLandingSite.cs @@ -39,9 +39,9 @@ protected override float Margin public Page_SelectLandingSite() { - this.absorbInputAroundWindow = false; - this.shadowAlpha = 0f; - this.preventCameraMotion = false; + base.absorbInputAroundWindow = false; + base.shadowAlpha = 0f; + base.preventCameraMotion = false; } public override void PreOpen() @@ -76,7 +76,7 @@ public override void DoWindowContents(Rect rect) { Find.GameInitData.startingTile = Find.WorldSelector.FirstSelectedObject.Tile; } - this.closeOnEscapeKey = !Find.WorldRoutePlanner.Active; + base.closeOnEscapeKey = !Find.WorldRoutePlanner.Active; } public override void ExtraOnGUI() @@ -107,7 +107,11 @@ protected override bool CanDoNext() return false; } Tile tile = Find.WorldGrid[selectedTile]; - return TutorSystem.AllowAction("ChooseBiome-" + tile.biome.defName + "-" + tile.hilliness.ToString()); + if (!TutorSystem.AllowAction("ChooseBiome-" + tile.biome.defName + "-" + ((Enum)(object)tile.hilliness).ToString())) + { + return false; + } + return true; } protected override void DoNext() @@ -119,62 +123,100 @@ protected override void DoNext() private void DoCustomBottomButtons() { int num = (!TutorSystem.TutorialMode) ? 5 : 4; - int num2; - if (num >= 4 && (float)UI.screenWidth < 1340f) - { - num2 = 2; - } - else - { - num2 = 1; - } + int num2 = (num < 4 || !((float)UI.screenWidth < 1340.0)) ? 1 : 2; int num3 = Mathf.CeilToInt((float)num / (float)num2); - float num4 = Page.BottomButSize.x * (float)num3 + 10f * (float)(num3 + 1); - float num5 = (float)num2 * Page.BottomButSize.y + 10f * (float)(num2 + 1); - Rect rect = new Rect(((float)UI.screenWidth - num4) / 2f, (float)UI.screenHeight - num5 - 4f, num4, num5); - if (Find.WindowStack.IsOpen() && rect.x < InspectPaneUtility.PaneSize.x + 4f) - { - rect.x = InspectPaneUtility.PaneSize.x + 4f; + Vector2 bottomButSize = Page.BottomButSize; + float num4 = (float)(bottomButSize.x * (float)num3 + 10.0 * (float)(num3 + 1)); + float num5 = (float)num2; + Vector2 bottomButSize2 = Page.BottomButSize; + float num6 = (float)(num5 * bottomButSize2.y + 10.0 * (float)(num2 + 1)); + Rect rect = new Rect((float)(((float)UI.screenWidth - num4) / 2.0), (float)((float)UI.screenHeight - num6 - 4.0), num4, num6); + if (Find.WindowStack.IsOpen()) + { + float x = rect.x; + Vector2 paneSize = InspectPaneUtility.PaneSize; + if (x < paneSize.x + 4.0) + { + Vector2 paneSize2 = InspectPaneUtility.PaneSize; + rect.x = (float)(paneSize2.x + 4.0); + } } Widgets.DrawWindowBackground(rect); - float num6 = rect.xMin + 10f; - float num7 = rect.yMin + 10f; + float num7 = (float)(rect.xMin + 10.0); + float num8 = (float)(rect.yMin + 10.0); Text.Font = GameFont.Small; - if (Widgets.ButtonText(new Rect(num6, num7, Page.BottomButSize.x, Page.BottomButSize.y), "Back".Translate(), true, false, true) && this.CanDoBack()) + float x2 = num7; + float y = num8; + Vector2 bottomButSize3 = Page.BottomButSize; + float x3 = bottomButSize3.x; + Vector2 bottomButSize4 = Page.BottomButSize; + if (Widgets.ButtonText(new Rect(x2, y, x3, bottomButSize4.y), "Back".Translate(), true, false, true) && this.CanDoBack()) { this.DoBack(); } - num6 += Page.BottomButSize.x + 10f; + float num9 = num7; + Vector2 bottomButSize5 = Page.BottomButSize; + num7 = (float)(num9 + (bottomButSize5.x + 10.0)); if (!TutorSystem.TutorialMode) { - if (Widgets.ButtonText(new Rect(num6, num7, Page.BottomButSize.x, Page.BottomButSize.y), "Advanced".Translate(), true, false, true)) + float x4 = num7; + float y2 = num8; + Vector2 bottomButSize6 = Page.BottomButSize; + float x5 = bottomButSize6.x; + Vector2 bottomButSize7 = Page.BottomButSize; + if (Widgets.ButtonText(new Rect(x4, y2, x5, bottomButSize7.y), "Advanced".Translate(), true, false, true)) { Find.WindowStack.Add(new Dialog_AdvancedGameConfig(Find.WorldInterface.SelectedTile)); } - num6 += Page.BottomButSize.x + 10f; + float num10 = num7; + Vector2 bottomButSize8 = Page.BottomButSize; + num7 = (float)(num10 + (bottomButSize8.x + 10.0)); } - if (Widgets.ButtonText(new Rect(num6, num7, Page.BottomButSize.x, Page.BottomButSize.y), "SelectRandomSite".Translate(), true, false, true)) + float x6 = num7; + float y3 = num8; + Vector2 bottomButSize9 = Page.BottomButSize; + float x7 = bottomButSize9.x; + Vector2 bottomButSize10 = Page.BottomButSize; + if (Widgets.ButtonText(new Rect(x6, y3, x7, bottomButSize10.y), "SelectRandomSite".Translate(), true, false, true)) { SoundDefOf.Click.PlayOneShotOnCamera(null); Find.WorldInterface.SelectedTile = TileFinder.RandomStartingTile(); Find.WorldCameraDriver.JumpTo(Find.WorldGrid.GetTileCenter(Find.WorldInterface.SelectedTile)); } - num6 += Page.BottomButSize.x + 10f; + float num11 = num7; + Vector2 bottomButSize11 = Page.BottomButSize; + num7 = (float)(num11 + (bottomButSize11.x + 10.0)); if (num2 == 2) { - num6 = rect.xMin + 10f; - num7 += Page.BottomButSize.y + 10f; + num7 = (float)(rect.xMin + 10.0); + float num12 = num8; + Vector2 bottomButSize12 = Page.BottomButSize; + num8 = (float)(num12 + (bottomButSize12.y + 10.0)); } - if (Widgets.ButtonText(new Rect(num6, num7, Page.BottomButSize.x, Page.BottomButSize.y), "WorldFactionsTab".Translate(), true, false, true)) + float x8 = num7; + float y4 = num8; + Vector2 bottomButSize13 = Page.BottomButSize; + float x9 = bottomButSize13.x; + Vector2 bottomButSize14 = Page.BottomButSize; + if (Widgets.ButtonText(new Rect(x8, y4, x9, bottomButSize14.y), "WorldFactionsTab".Translate(), true, false, true)) { Find.WindowStack.Add(new Dialog_FactionDuringLanding()); } - num6 += Page.BottomButSize.x + 10f; - if (Widgets.ButtonText(new Rect(num6, num7, Page.BottomButSize.x, Page.BottomButSize.y), "Next".Translate(), true, false, true) && this.CanDoNext()) + float num13 = num7; + Vector2 bottomButSize15 = Page.BottomButSize; + num7 = (float)(num13 + (bottomButSize15.x + 10.0)); + float x10 = num7; + float y5 = num8; + Vector2 bottomButSize16 = Page.BottomButSize; + float x11 = bottomButSize16.x; + Vector2 bottomButSize17 = Page.BottomButSize; + if (Widgets.ButtonText(new Rect(x10, y5, x11, bottomButSize17.y), "Next".Translate(), true, false, true) && this.CanDoNext()) { this.DoNext(); } - num6 += Page.BottomButSize.x + 10f; + float num14 = num7; + Vector2 bottomButSize18 = Page.BottomButSize; + num7 = (float)(num14 + (bottomButSize18.x + 10.0)); GenUI.AbsorbClicksInRect(rect); } } diff --git a/Assembly-CSharp/RimWorld/Page_SelectScenario.cs b/Assembly-CSharp/RimWorld/Page_SelectScenario.cs index a1f75284c..7d09a1bfa 100644 --- a/Assembly-CSharp/RimWorld/Page_SelectScenario.cs +++ b/Assembly-CSharp/RimWorld/Page_SelectScenario.cs @@ -45,18 +45,26 @@ public override void DoWindowContents(Rect rect) base.DrawPageTitle(rect); Rect mainRect = base.GetMainRect(rect, 0f, false); GUI.BeginGroup(mainRect); - Rect rect2 = new Rect(0f, 0f, mainRect.width * 0.35f, mainRect.height).Rounded(); + Rect rect2 = new Rect(0f, 0f, (float)(mainRect.width * 0.34999999403953552), mainRect.height).Rounded(); this.DoScenarioSelectionList(rect2); - Rect rect3 = new Rect(rect2.xMax + 17f, 0f, mainRect.width - rect2.width - 17f, mainRect.height).Rounded(); + Rect rect3 = new Rect((float)(rect2.xMax + 17.0), 0f, (float)(mainRect.width - rect2.width - 17.0), mainRect.height).Rounded(); ScenarioUI.DrawScenarioInfo(rect3, this.curScen, ref this.infoScrollPosition); GUI.EndGroup(); string midLabel = "ScenarioEditor".Translate(); - base.DoBottomButtons(rect, null, midLabel, new Action(this.GoToScenarioEditor), true); + base.DoBottomButtons(rect, (string)null, midLabel, new Action(this.GoToScenarioEditor), true); } private bool CanEditScenario(Scenario scen) { - return scen.Category == ScenarioCategory.CustomLocal || scen.CanToUploadToWorkshop(); + if (scen.Category == ScenarioCategory.CustomLocal) + { + return true; + } + if (scen.CanToUploadToWorkshop()) + { + return true; + } + return false; } private void GoToScenarioEditor() @@ -71,7 +79,7 @@ private void GoToScenarioEditor() private void DoScenarioSelectionList(Rect rect) { rect.xMax += 2f; - Rect rect2 = new Rect(0f, 0f, rect.width - 16f - 2f, this.totalScenarioListHeight + 250f); + Rect rect2 = new Rect(0f, 0f, (float)(rect.width - 16.0 - 2.0), (float)(this.totalScenarioListHeight + 250.0)); Widgets.BeginScrollView(rect, ref this.scenariosScrollPosition, rect2, true); Rect rect3 = rect2.AtZero(); rect3.height = 999999f; @@ -87,7 +95,7 @@ private void DoScenarioSelectionList(Rect rect) listing_Standard.Gap(12f); Text.Font = GameFont.Small; listing_Standard.Label("ScenariosSteamWorkshop".Translate(), -1f); - if (listing_Standard.ButtonText("OpenSteamWorkshop".Translate(), null)) + if (listing_Standard.ButtonText("OpenSteamWorkshop".Translate(), (string)null)) { SteamUtility.OpenSteamWorkshopPage(); } @@ -100,13 +108,13 @@ private void DoScenarioSelectionList(Rect rect) private void ListScenariosOnListing(Listing_Standard listing, IEnumerable scenarios) { bool flag = false; - foreach (Scenario current in scenarios) + foreach (Scenario item in scenarios) { if (flag) { listing.Gap(12f); } - Scenario scen = current; + Scenario scen = item; Rect rect = listing.GetRect(62f); this.DoScenarioListEntry(rect, scen); flag = true; @@ -143,21 +151,15 @@ private void DoScenarioListEntry(Rect rect, Scenario scen) WidgetRow widgetRow = new WidgetRow(rect.xMax, rect.y, UIDirection.LeftThenDown, 99999f, 4f); if (scen.Category == ScenarioCategory.CustomLocal && widgetRow.ButtonIcon(TexButton.DeleteX, "Delete".Translate())) { - Find.WindowStack.Add(Dialog_MessageBox.CreateConfirmation("ConfirmDelete".Translate(new object[] - { - scen.File.Name - }), delegate + Find.WindowStack.Add(Dialog_MessageBox.CreateConfirmation("ConfirmDelete".Translate(scen.File.Name), (Action)delegate() { scen.File.Delete(); ScenarioLister.MarkDirty(); - }, true, null)); + }, true, (string)null)); } if (scen.Category == ScenarioCategory.SteamWorkshop && widgetRow.ButtonIcon(TexButton.DeleteX, "Unsubscribe".Translate())) { - Find.WindowStack.Add(Dialog_MessageBox.CreateConfirmation("ConfirmUnsubscribe".Translate(new object[] - { - scen.File.Name - }), delegate + Find.WindowStack.Add(Dialog_MessageBox.CreateConfirmation("ConfirmUnsubscribe".Translate(scen.File.Name), (Action)delegate() { scen.enabled = false; if (this.curScen == scen) @@ -166,7 +168,7 @@ private void DoScenarioListEntry(Rect rect, Scenario scen) this.EnsureValidSelection(); } Workshop.Unsubscribe(scen); - }, true, null)); + }, true, (string)null)); } if (scen.GetPublishedFileId() != PublishedFileId_t.Invalid) { @@ -211,24 +213,25 @@ public static void BeginScenarioConfiguration(Scenario scen, Page originPage) if (firstConfigPage == null) { PageUtility.InitGameStart(); - return; } - originPage.next = firstConfigPage; - firstConfigPage.prev = originPage; + else + { + originPage.next = firstConfigPage; + firstConfigPage.prev = originPage; + } } private void EnsureValidSelection() { - if (this.curScen == null || !ScenarioLister.ScenarioIsListedAnywhere(this.curScen)) - { - this.curScen = ScenarioLister.ScenariosInCategory(ScenarioCategory.FromDef).FirstOrDefault(); - } + if (this.curScen != null && ScenarioLister.ScenarioIsListedAnywhere(this.curScen)) + return; + this.curScen = ScenarioLister.ScenariosInCategory(ScenarioCategory.FromDef).FirstOrDefault(); } internal void Notify_ScenarioListChanged() { PublishedFileId_t selModId = this.curScen.GetPublishedFileId(); - this.curScen = ScenarioLister.AllScenarios().FirstOrDefault((Scenario sc) => sc.GetPublishedFileId() == selModId); + this.curScen = ScenarioLister.AllScenarios().FirstOrDefault((Func)((Scenario sc) => sc.GetPublishedFileId() == selModId)); this.EnsureValidSelection(); } diff --git a/Assembly-CSharp/RimWorld/Page_SelectStoryteller.cs b/Assembly-CSharp/RimWorld/Page_SelectStoryteller.cs index 69b00bdf9..d8566b518 100644 --- a/Assembly-CSharp/RimWorld/Page_SelectStoryteller.cs +++ b/Assembly-CSharp/RimWorld/Page_SelectStoryteller.cs @@ -27,7 +27,7 @@ public override void PreOpen() this.storyteller = (from d in DefDatabase.AllDefs where d.listVisible orderby d.listOrder - select d).First(); + select d).First(); } public override void DoWindowContents(Rect rect) @@ -35,7 +35,7 @@ public override void DoWindowContents(Rect rect) base.DrawPageTitle(rect); Rect mainRect = base.GetMainRect(rect, 0f, false); StorytellerUI.DrawStorytellerSelectionInterface(mainRect, ref this.storyteller, ref this.difficulty, this.selectedStorytellerInfoListing); - base.DoBottomButtons(rect, null, null, null, true); + base.DoBottomButtons(rect, (string)null, (string)null, null, true); } protected override bool CanDoNext() diff --git a/Assembly-CSharp/RimWorld/Page_SelectStorytellerInGame.cs b/Assembly-CSharp/RimWorld/Page_SelectStorytellerInGame.cs index d50082793..72b8eeb03 100644 --- a/Assembly-CSharp/RimWorld/Page_SelectStorytellerInGame.cs +++ b/Assembly-CSharp/RimWorld/Page_SelectStorytellerInGame.cs @@ -1,4 +1,3 @@ -using System; using UnityEngine; using Verse; @@ -18,8 +17,8 @@ public override string PageTitle public Page_SelectStorytellerInGame() { - this.doCloseButton = true; - this.doCloseX = true; + base.doCloseButton = true; + base.doCloseX = true; } public override void DoWindowContents(Rect rect) diff --git a/Assembly-CSharp/RimWorld/ParentRelationUtility.cs b/Assembly-CSharp/RimWorld/ParentRelationUtility.cs index 3478cfd15..7aeb52262 100644 --- a/Assembly-CSharp/RimWorld/ParentRelationUtility.cs +++ b/Assembly-CSharp/RimWorld/ParentRelationUtility.cs @@ -12,7 +12,7 @@ public static Pawn GetFather(this Pawn pawn) { return null; } - return pawn.relations.GetFirstDirectRelationPawn(PawnRelationDefOf.Parent, (Pawn x) => x.gender != Gender.Female); + return pawn.relations.GetFirstDirectRelationPawn(PawnRelationDefOf.Parent, (Predicate)((Pawn x) => x.gender != Gender.Female)); } public static Pawn GetMother(this Pawn pawn) @@ -21,35 +21,28 @@ public static Pawn GetMother(this Pawn pawn) { return null; } - return pawn.relations.GetFirstDirectRelationPawn(PawnRelationDefOf.Parent, (Pawn x) => x.gender == Gender.Female); + return pawn.relations.GetFirstDirectRelationPawn(PawnRelationDefOf.Parent, (Predicate)((Pawn x) => x.gender == Gender.Female)); } public static void SetFather(this Pawn pawn, Pawn newFather) { if (newFather != null && newFather.gender == Gender.Female) { - Log.Warning(string.Concat(new object[] - { - "Tried to set ", - newFather, - " with gender ", - newFather.gender, - " as ", - pawn, - "'s father." - })); - return; + Log.Warning("Tried to set " + newFather + " with gender " + newFather.gender + " as " + pawn + "'s father."); } - Pawn father = pawn.GetFather(); - if (father != newFather) + else { - if (father != null) - { - pawn.relations.RemoveDirectRelation(PawnRelationDefOf.Parent, father); - } - if (newFather != null) + Pawn father = pawn.GetFather(); + if (father != newFather) { - pawn.relations.AddDirectRelation(PawnRelationDefOf.Parent, newFather); + if (father != null) + { + pawn.relations.RemoveDirectRelation(PawnRelationDefOf.Parent, father); + } + if (newFather != null) + { + pawn.relations.AddDirectRelation(PawnRelationDefOf.Parent, newFather); + } } } } @@ -58,60 +51,46 @@ public static void SetMother(this Pawn pawn, Pawn newMother) { if (newMother != null && newMother.gender != Gender.Female) { - Log.Warning(string.Concat(new object[] - { - "Tried to set ", - newMother, - " with gender ", - newMother.gender, - " as ", - pawn, - "'s mother." - })); - return; + Log.Warning("Tried to set " + newMother + " with gender " + newMother.gender + " as " + pawn + "'s mother."); } - Pawn mother = pawn.GetMother(); - if (mother != newMother) + else { - if (mother != null) - { - pawn.relations.RemoveDirectRelation(PawnRelationDefOf.Parent, mother); - } - if (newMother != null) + Pawn mother = pawn.GetMother(); + if (mother != newMother) { - pawn.relations.AddDirectRelation(PawnRelationDefOf.Parent, newMother); + if (mother != null) + { + pawn.relations.RemoveDirectRelation(PawnRelationDefOf.Parent, mother); + } + if (newMother != null) + { + pawn.relations.AddDirectRelation(PawnRelationDefOf.Parent, newMother); + } } } } - public static float GetRandomSecondParentSkinColor(float otherParentSkin, float childSkin, float? secondChildSkin = null) + public static float GetRandomSecondParentSkinColor(float otherParentSkin, float childSkin, float? secondChildSkin = default(float?)) { - float mirror; - if (secondChildSkin.HasValue) - { - mirror = (childSkin + secondChildSkin.Value) / 2f; - } - else - { - mirror = childSkin; - } - float reflectedSkin = ChildRelationUtility.GetReflectedSkin(otherParentSkin, mirror); - float num = childSkin; + float num = 0f; + num = (float)((!secondChildSkin.HasValue) ? childSkin : ((childSkin + secondChildSkin.Value) / 2.0)); + float reflectedSkin = ChildRelationUtility.GetReflectedSkin(otherParentSkin, num); float num2 = childSkin; + float num3 = childSkin; if (secondChildSkin.HasValue) { - num = Mathf.Min(num, secondChildSkin.Value); - num2 = Mathf.Max(num2, secondChildSkin.Value); + num2 = Mathf.Min(num2, secondChildSkin.Value); + num3 = Mathf.Max(num3, secondChildSkin.Value); } float clampMin = 0f; float clampMax = 1f; - if (reflectedSkin >= num2) + if (reflectedSkin >= num3) { - clampMin = num2; + clampMin = num3; } else { - clampMax = num; + clampMax = num2; } return PawnSkinColors.GetRandomMelaninSimilarTo(reflectedSkin, clampMin, clampMax); } diff --git a/Assembly-CSharp/RimWorld/PartyUtility.cs b/Assembly-CSharp/RimWorld/PartyUtility.cs index cb89ba7b2..4e76a8288 100644 --- a/Assembly-CSharp/RimWorld/PartyUtility.cs +++ b/Assembly-CSharp/RimWorld/PartyUtility.cs @@ -18,65 +18,72 @@ public static bool AcceptableGameConditionsToStartParty(Map map) { return false; } - if (GenLocalDate.HourInteger(map) < 4 || GenLocalDate.HourInteger(map) > 21) + if (GenLocalDate.HourInteger(map) >= 4 && GenLocalDate.HourInteger(map) <= 21) { - return false; - } - if (GatheringsUtility.AnyLordJobPreventsNewGatherings(map)) - { - return false; - } - if (map.dangerWatcher.DangerRating != StoryDanger.None) - { - return false; - } - int freeColonistsSpawnedCount = map.mapPawns.FreeColonistsSpawnedCount; - if (freeColonistsSpawnedCount < 4) - { - return false; - } - int num = 0; - foreach (Pawn current in map.mapPawns.FreeColonistsSpawned) - { - if (current.health.hediffSet.BleedRateTotal > 0f) + if (GatheringsUtility.AnyLordJobPreventsNewGatherings(map)) { - bool result = false; - return result; + return false; } - if (current.Drafted) + if (map.dangerWatcher.DangerRating != 0) { - num++; + return false; } - } - if ((float)num / (float)freeColonistsSpawnedCount >= 0.5f) - { - return false; - } - int num2 = Mathf.RoundToInt((float)map.mapPawns.FreeColonistsSpawnedCount * 0.65f); - num2 = Mathf.Clamp(num2, 2, 10); - int num3 = 0; - foreach (Pawn current2 in map.mapPawns.FreeColonistsSpawned) - { - if (PartyUtility.ShouldPawnKeepPartying(current2)) + int freeColonistsSpawnedCount = map.mapPawns.FreeColonistsSpawnedCount; + if (freeColonistsSpawnedCount < 4) { - num3++; + return false; } + int num = 0; + foreach (Pawn item in map.mapPawns.FreeColonistsSpawned) + { + if (item.health.hediffSet.BleedRateTotal > 0.0) + { + return false; + } + if (item.Drafted) + { + num++; + } + } + if ((float)num / (float)freeColonistsSpawnedCount >= 0.5) + { + return false; + } + int value = Mathf.RoundToInt((float)((float)map.mapPawns.FreeColonistsSpawnedCount * 0.64999997615814209)); + value = Mathf.Clamp(value, 2, 10); + int num2 = 0; + foreach (Pawn item2 in map.mapPawns.FreeColonistsSpawned) + { + if (PartyUtility.ShouldPawnKeepPartying(item2)) + { + num2++; + } + } + if (num2 < value) + { + return false; + } + return true; } - return num3 >= num2; + return false; } public static bool AcceptableGameConditionsToContinueParty(Map map) { - return map.dangerWatcher.DangerRating != StoryDanger.High; + if (map.dangerWatcher.DangerRating == StoryDanger.High) + { + return false; + } + return true; } public static Pawn FindRandomPartyOrganizer(Faction faction, Map map) { - Predicate validator = (Pawn x) => x.RaceProps.Humanlike && !x.InBed() && PartyUtility.ShouldPawnKeepPartying(x); - Pawn result; + Predicate validator = (Predicate)((Pawn x) => x.RaceProps.Humanlike && !x.InBed() && PartyUtility.ShouldPawnKeepPartying(x)); + Pawn result = default(Pawn); if ((from x in map.mapPawns.SpawnedPawnsInFaction(faction) where validator(x) - select x).TryRandomElement(out result)) + select x).TryRandomElement(out result)) { return result; } @@ -85,7 +92,15 @@ where validator(x) public static bool ShouldPawnKeepPartying(Pawn p) { - return (p.timetable == null || p.timetable.CurrentAssignment.allowJoy) && GatheringsUtility.ShouldGuestKeepAttendingGathering(p); + if (p.timetable != null && !p.timetable.CurrentAssignment.allowJoy) + { + return false; + } + if (!GatheringsUtility.ShouldGuestKeepAttendingGathering(p)) + { + return false; + } + return true; } public static bool InPartyArea(IntVec3 cell, IntVec3 partySpot, Map map) @@ -94,37 +109,41 @@ public static bool InPartyArea(IntVec3 cell, IntVec3 partySpot, Map map) { return true; } - if (!cell.InHorDistOf(partySpot, 10f)) - { - return false; - } - Building edifice = cell.GetEdifice(map); - TraverseParms traverseParams = TraverseParms.For(TraverseMode.NoPassClosedDoors, Danger.None, false); - if (edifice != null) + if (cell.InHorDistOf(partySpot, 10f)) { - return map.reachability.CanReach(partySpot, edifice, PathEndMode.ClosestTouch, traverseParams); + Building edifice = cell.GetEdifice(map); + TraverseParms traverseParams = TraverseParms.For(TraverseMode.NoPassClosedDoors, Danger.None, false); + if (edifice != null) + { + return map.reachability.CanReach(partySpot, (Thing)edifice, PathEndMode.ClosestTouch, traverseParams); + } + return map.reachability.CanReach(partySpot, cell, PathEndMode.ClosestTouch, traverseParams); } - return map.reachability.CanReach(partySpot, cell, PathEndMode.ClosestTouch, traverseParams); + return false; } public static bool TryFindRandomCellInPartyArea(Pawn pawn, out IntVec3 result) { IntVec3 cell = pawn.mindState.duty.focus.Cell; - Predicate validator = (IntVec3 x) => x.Standable(pawn.Map) && !x.IsForbidden(pawn) && pawn.CanReserveAndReach(x, PathEndMode.OnCell, Danger.None, 1, -1, null, false); + Predicate validator = (Predicate)((IntVec3 x) => x.Standable(pawn.Map) && !x.IsForbidden(pawn) && pawn.CanReserveAndReach(x, PathEndMode.OnCell, Danger.None, 1, -1, null, false)); if (PartyUtility.UseWholeRoomAsPartyArea(cell, pawn.Map)) { Room room = cell.GetRoom(pawn.Map, RegionType.Set_Passable); return (from x in room.Cells where validator(x) - select x).TryRandomElement(out result); + select x).TryRandomElement(out result); } - return CellFinder.TryFindRandomReachableCellNear(cell, pawn.Map, 10f, TraverseParms.For(TraverseMode.NoPassClosedDoors, Danger.Deadly, false), (IntVec3 x) => validator(x), null, out result, 10); + return CellFinder.TryFindRandomReachableCellNear(cell, pawn.Map, 10f, TraverseParms.For(TraverseMode.NoPassClosedDoors, Danger.Deadly, false), (Predicate)((IntVec3 x) => validator(x)), (Predicate)null, out result, 10); } public static bool UseWholeRoomAsPartyArea(IntVec3 partySpot, Map map) { Room room = partySpot.GetRoom(map, RegionType.Set_Passable); - return room != null && !room.IsHuge && !room.PsychologicallyOutdoors && room.CellCount <= 324; + if (room != null && !room.IsHuge && !room.PsychologicallyOutdoors && room.CellCount <= 324) + { + return true; + } + return false; } } } diff --git a/Assembly-CSharp/RimWorld/PassingShip.cs b/Assembly-CSharp/RimWorld/PassingShip.cs index cebfa41c1..703c86536 100644 --- a/Assembly-CSharp/RimWorld/PassingShip.cs +++ b/Assembly-CSharp/RimWorld/PassingShip.cs @@ -39,7 +39,7 @@ public Map Map public virtual void ExposeData() { - Scribe_Values.Look(ref this.name, "name", null, false); + Scribe_Values.Look(ref this.name, "name", (string)null, false); Scribe_Values.Look(ref this.loadID, "loadID", 0, false); Scribe_Values.Look(ref this.ticksUntilDeparture, "ticksUntilDeparture", 0, false); } @@ -55,12 +55,9 @@ public virtual void PassingShipTick() public virtual void Depart() { - if (this.Map.listerBuildings.ColonistsHaveBuilding((Thing b) => b.def.IsCommsConsole)) + if (this.Map.listerBuildings.ColonistsHaveBuilding((Func)((Thing b) => b.def.IsCommsConsole))) { - Messages.Message("MessageShipHasLeftCommsRange".Translate(new object[] - { - this.FullTitle - }), MessageSound.Silent); + Messages.Message("MessageShipHasLeftCommsRange".Translate(this.FullTitle), MessageSound.Silent); } this.passingShipManager.RemoveShip(this); } diff --git a/Assembly-CSharp/RimWorld/PassingShipManager.cs b/Assembly-CSharp/RimWorld/PassingShipManager.cs index 9f978ee02..9357cfae2 100644 --- a/Assembly-CSharp/RimWorld/PassingShipManager.cs +++ b/Assembly-CSharp/RimWorld/PassingShipManager.cs @@ -1,4 +1,3 @@ -using System; using System.Collections.Generic; using Verse; @@ -43,9 +42,9 @@ public void RemoveShip(PassingShip vis) public void PassingShipManagerTick() { - for (int i = this.passingShips.Count - 1; i >= 0; i--) + for (int num = this.passingShips.Count - 1; num >= 0; num--) { - this.passingShips[i].PassingShipTick(); + this.passingShips[num].PassingShipTick(); } } diff --git a/Assembly-CSharp/RimWorld/Passion.cs b/Assembly-CSharp/RimWorld/Passion.cs index a6b9b9885..3ee573030 100644 --- a/Assembly-CSharp/RimWorld/Passion.cs +++ b/Assembly-CSharp/RimWorld/Passion.cs @@ -1,11 +1,9 @@ -using System; - namespace RimWorld { public enum Passion : byte { - None, - Minor, - Major + None = 0, + Minor = 1, + Major = 2 } } diff --git a/Assembly-CSharp/RimWorld/PawnAddictionHediffsGenerator.cs b/Assembly-CSharp/RimWorld/PawnAddictionHediffsGenerator.cs index 9d9386ffb..9795f0ba2 100644 --- a/Assembly-CSharp/RimWorld/PawnAddictionHediffsGenerator.cs +++ b/Assembly-CSharp/RimWorld/PawnAddictionHediffsGenerator.cs @@ -17,21 +17,13 @@ public static class PawnAddictionHediffsGenerator public static void GenerateAddictionsAndTolerancesFor(Pawn pawn) { - if (!pawn.RaceProps.IsFlesh || !pawn.RaceProps.Humanlike) + if (pawn.RaceProps.IsFlesh && pawn.RaceProps.Humanlike && !pawn.IsTeetotaler()) { - return; - } - if (pawn.IsTeetotaler()) - { - return; - } - PawnAddictionHediffsGenerator.allDrugs.Clear(); - int i = 0; - while (i < 3) - { - if (Rand.Value < pawn.kindDef.chemicalAddictionChance) + PawnAddictionHediffsGenerator.allDrugs.Clear(); + int num = 0; + while (num < 3 && !(Rand.Value >= pawn.kindDef.chemicalAddictionChance)) { - if (!PawnAddictionHediffsGenerator.allDrugs.Any()) + if (!PawnAddictionHediffsGenerator.allDrugs.Any()) { PawnAddictionHediffsGenerator.allDrugs.AddRange(from x in DefDatabase.AllDefsListForReading where x.category == ThingCategory.Item && x.GetCompProperties() != null @@ -40,37 +32,50 @@ public static void GenerateAddictionsAndTolerancesFor(Pawn pawn) IEnumerable source = from x in DefDatabase.AllDefsListForReading where PawnAddictionHediffsGenerator.PossibleWithTechLevel(x, pawn.Faction) && !AddictionUtility.IsAddicted(pawn, x) select x; - ChemicalDef chemicalDef; - if (source.TryRandomElement(out chemicalDef)) + ChemicalDef chemicalDef = default(ChemicalDef); + if (source.TryRandomElement(out chemicalDef)) { Hediff hediff = HediffMaker.MakeHediff(chemicalDef.addictionHediff, pawn, null); hediff.Severity = PawnAddictionHediffsGenerator.GeneratedAddictionSeverityRange.RandomInRange; - pawn.health.AddHediff(hediff, null, null); + pawn.health.AddHediff(hediff, null, default(DamageInfo?)); if (chemicalDef.toleranceHediff != null && Rand.Value < chemicalDef.onGeneratedAddictedToleranceChance) { Hediff hediff2 = HediffMaker.MakeHediff(chemicalDef.toleranceHediff, pawn, null); hediff2.Severity = PawnAddictionHediffsGenerator.GeneratedToleranceSeverityRange.RandomInRange; - pawn.health.AddHediff(hediff2, null, null); + pawn.health.AddHediff(hediff2, null, default(DamageInfo?)); } if (chemicalDef.onGeneratedAddictedEvents != null) { - foreach (HediffGiver_Event current in chemicalDef.onGeneratedAddictedEvents) + List.Enumerator enumerator = chemicalDef.onGeneratedAddictedEvents.GetEnumerator(); + try { - current.EventOccurred(pawn); + while (enumerator.MoveNext()) + { + HediffGiver_Event current = enumerator.Current; + current.EventOccurred(pawn); + } + } + finally + { + ((IDisposable)(object)enumerator).Dispose(); } } PawnAddictionHediffsGenerator.DoIngestionOutcomeDoers(pawn, chemicalDef); - i++; + num++; continue; } + break; } - return; } } private static bool PossibleWithTechLevel(ChemicalDef chemical, Faction faction) { - return faction == null || PawnAddictionHediffsGenerator.allDrugs.Any((ThingDef x) => x.GetCompProperties().chemical == chemical && x.techLevel <= faction.def.techLevel); + if (faction == null) + { + return true; + } + return PawnAddictionHediffsGenerator.allDrugs.Any((Predicate)((ThingDef x) => x.GetCompProperties().chemical == chemical && (int)x.techLevel <= (int)faction.def.techLevel)); } private static void DoIngestionOutcomeDoers(Pawn pawn, ChemicalDef chemical) diff --git a/Assembly-CSharp/RimWorld/PawnApparelGenerator.cs b/Assembly-CSharp/RimWorld/PawnApparelGenerator.cs index 11ba24741..0331ea295 100644 --- a/Assembly-CSharp/RimWorld/PawnApparelGenerator.cs +++ b/Assembly-CSharp/RimWorld/PawnApparelGenerator.cs @@ -30,7 +30,7 @@ public float TotalPrice { get { - return this.aps.Sum((ThingStuffPair pa) => pa.Price); + return this.aps.Sum((Func)((ThingStuffPair pa) => pa.Price)); } } @@ -38,7 +38,7 @@ public float TotalInsulationCold { get { - return this.aps.Sum((ThingStuffPair a) => a.InsulationCold); + return this.aps.Sum((Func)((ThingStuffPair a) => a.InsulationCold)); } } @@ -51,7 +51,7 @@ public void Reset() public void Add(ThingStuffPair pair) { this.aps.Add(pair); - ApparelUtility.GenerateLayerGroupPairs(pair.thing, delegate(ApparelUtility.LayerGroupPair lgp) + ApparelUtility.GenerateLayerGroupPairs(pair.thing, (Action)delegate(ApparelUtility.LayerGroupPair lgp) { this.lgps.Add(lgp); }); @@ -60,7 +60,7 @@ public void Add(ThingStuffPair pair) public bool PairOverlapsAnything(ThingStuffPair pair) { bool conflicts = false; - ApparelUtility.GenerateLayerGroupPairs(pair.thing, delegate(ApparelUtility.LayerGroupPair lgp) + ApparelUtility.GenerateLayerGroupPairs(pair.thing, (Action)delegate(ApparelUtility.LayerGroupPair lgp) { conflicts |= this.lgps.Contains(lgp); }); @@ -73,19 +73,30 @@ public bool CoatButNoShirt() bool flag2 = false; for (int i = 0; i < this.aps.Count; i++) { - if (this.aps[i].thing.apparel.bodyPartGroups.Contains(BodyPartGroupDefOf.Torso)) + ThingStuffPair thingStuffPair = this.aps[i]; + if (thingStuffPair.thing.apparel.bodyPartGroups.Contains(BodyPartGroupDefOf.Torso)) { - for (int j = 0; j < this.aps[i].thing.apparel.layers.Count; j++) + int num = 0; + while (true) { - ApparelLayer apparelLayer = this.aps[i].thing.apparel.layers[j]; - if (apparelLayer == ApparelLayer.OnSkin) + int num2 = num; + ThingStuffPair thingStuffPair2 = this.aps[i]; + if (num2 < thingStuffPair2.thing.apparel.layers.Count) { - flag2 = true; - } - if (apparelLayer == ApparelLayer.Shell || apparelLayer == ApparelLayer.Middle) - { - flag = true; + ThingStuffPair thingStuffPair3 = this.aps[i]; + ApparelLayer apparelLayer = thingStuffPair3.thing.apparel.layers[num]; + if (apparelLayer == ApparelLayer.OnSkin) + { + flag2 = true; + } + if (apparelLayer == ApparelLayer.Shell || apparelLayer == ApparelLayer.Middle) + { + flag = true; + } + num++; + continue; } + break; } } } @@ -96,7 +107,8 @@ public bool Covers(BodyPartGroupDef bp) { for (int i = 0; i < this.aps.Count; i++) { - if (this.aps[i].thing.apparel.bodyPartGroups.Contains(bp)) + ThingStuffPair thingStuffPair = this.aps[i]; + if (thingStuffPair.thing.apparel.bodyPartGroups.Contains(bp)) { return true; } @@ -108,129 +120,148 @@ public bool IsNaked(Gender gender) { switch (gender) { - case Gender.None: - return false; case Gender.Male: + { return !this.Covers(BodyPartGroupDefOf.Legs); + } case Gender.Female: + { return !this.Covers(BodyPartGroupDefOf.Legs) || !this.Covers(BodyPartGroupDefOf.Torso); + } + case Gender.None: + { + return false; + } default: + { return false; } + } } public bool SatisfiesNeededWarmth(NeededWarmth warmth) { - if (warmth == NeededWarmth.Any) + switch (warmth) + { + case NeededWarmth.Any: { return true; } - if (warmth == NeededWarmth.Cool) + case NeededWarmth.Cool: { return true; } - if (warmth == NeededWarmth.Warm) + case NeededWarmth.Warm: { - float num = this.aps.Sum((ThingStuffPair a) => a.InsulationCold); - return num <= -52f; + float num = this.aps.Sum((Func)((ThingStuffPair a) => a.InsulationCold)); + return num <= -52.0; + } + default: + { + throw new NotImplementedException(); + } } - throw new NotImplementedException(); } public void AddFreeWarmthAsNeeded(NeededWarmth warmth) { - if (warmth == NeededWarmth.Any) + switch (warmth) { + case NeededWarmth.Any: return; - } - if (warmth == NeededWarmth.Cool) - { + case NeededWarmth.Cool: return; - } - if (DebugViewSettings.logApparelGeneration) - { - PawnApparelGenerator.debugSb.AppendLine(); - PawnApparelGenerator.debugSb.AppendLine("Trying to give free warm layer."); - } - if (!this.SatisfiesNeededWarmth(warmth)) + default: { if (DebugViewSettings.logApparelGeneration) { - PawnApparelGenerator.debugSb.AppendLine("Checking to give free torso-cover at max price " + PawnApparelGenerator.freeWarmParkaMaxPrice); + PawnApparelGenerator.debugSb.AppendLine(); + PawnApparelGenerator.debugSb.AppendLine("Trying to give free warm layer."); } - Predicate parkaPairValidator = (ThingStuffPair pa) => pa.Price <= PawnApparelGenerator.freeWarmParkaMaxPrice && pa.InsulationCold <= -40f; - ThingStuffPair parkaPair; - if ((from pa in PawnApparelGenerator.allApparelPairs - where parkaPairValidator(pa) - select pa).TryRandomElementByWeight((ThingStuffPair pa) => pa.Commonality / (pa.Price * pa.Price), out parkaPair)) + if (!this.SatisfiesNeededWarmth(warmth)) { if (DebugViewSettings.logApparelGeneration) { - PawnApparelGenerator.debugSb.AppendLine(string.Concat(new object[] + PawnApparelGenerator.debugSb.AppendLine("Checking to give free torso-cover at max price " + PawnApparelGenerator.freeWarmParkaMaxPrice); + } + Predicate parkaPairValidator = (Predicate)delegate(ThingStuffPair pa) + { + if (pa.Price > PawnApparelGenerator.freeWarmParkaMaxPrice) { - "Giving free torso-cover: ", - parkaPair, - " insulation=", - parkaPair.InsulationCold - })); - foreach (ThingStuffPair current in from a in this.aps - where !ApparelUtility.CanWearTogether(a.thing, parkaPair.thing) - select a) + return false; + } + if (pa.InsulationCold > -40.0) { - PawnApparelGenerator.debugSb.AppendLine(string.Concat(new object[] + return false; + } + return true; + }; + ThingStuffPair parkaPair; + if ((from pa in PawnApparelGenerator.allApparelPairs + where parkaPairValidator(pa) + select pa).TryRandomElementByWeight((Func)((ThingStuffPair pa) => pa.Commonality / (pa.Price * pa.Price)), out parkaPair)) + { + if (DebugViewSettings.logApparelGeneration) + { + PawnApparelGenerator.debugSb.AppendLine("Giving free torso-cover: " + parkaPair + " insulation=" + parkaPair.InsulationCold); + foreach (ThingStuffPair item in from a in this.aps + where !ApparelUtility.CanWearTogether(a.thing, parkaPair.thing) + select a) { - " -replaces ", - current.ToString(), - " InsulationCold=", - current.InsulationCold - })); + PawnApparelGenerator.debugSb.AppendLine(" -replaces " + item.ToString() + " InsulationCold=" + item.InsulationCold); + } } + this.aps.RemoveAll((Predicate)((ThingStuffPair pa) => !ApparelUtility.CanWearTogether(pa.thing, parkaPair.thing))); + this.aps.Add(parkaPair); } - this.aps.RemoveAll((ThingStuffPair pa) => !ApparelUtility.CanWearTogether(pa.thing, parkaPair.thing)); - this.aps.Add(parkaPair); } - } - if (!this.SatisfiesNeededWarmth(warmth)) - { - if (DebugViewSettings.logApparelGeneration) - { - PawnApparelGenerator.debugSb.AppendLine("Checking to give free hat at max price " + PawnApparelGenerator.freeWarmHatMaxPrice); - } - Predicate hatPairValidator = (ThingStuffPair pa) => pa.Price <= PawnApparelGenerator.freeWarmHatMaxPrice && pa.InsulationCold <= -7f && (pa.thing.apparel.bodyPartGroups.Contains(BodyPartGroupDefOf.FullHead) || pa.thing.apparel.bodyPartGroups.Contains(BodyPartGroupDefOf.UpperHead)); - ThingStuffPair hatPair; - if ((from pa in PawnApparelGenerator.allApparelPairs - where hatPairValidator(pa) - select pa).TryRandomElementByWeight((ThingStuffPair pa) => pa.Commonality / (pa.Price * pa.Price), out hatPair)) + if (!this.SatisfiesNeededWarmth(warmth)) { if (DebugViewSettings.logApparelGeneration) { - PawnApparelGenerator.debugSb.AppendLine(string.Concat(new object[] + PawnApparelGenerator.debugSb.AppendLine("Checking to give free hat at max price " + PawnApparelGenerator.freeWarmHatMaxPrice); + } + Predicate hatPairValidator = (Predicate)delegate(ThingStuffPair pa) + { + if (pa.Price > PawnApparelGenerator.freeWarmHatMaxPrice) { - "Giving free hat: ", - hatPair, - " insulation=", - hatPair.InsulationCold - })); - foreach (ThingStuffPair current2 in from a in this.aps - where !ApparelUtility.CanWearTogether(a.thing, hatPair.thing) - select a) + return false; + } + if (pa.InsulationCold > -7.0) + { + return false; + } + if (!pa.thing.apparel.bodyPartGroups.Contains(BodyPartGroupDefOf.FullHead) && !pa.thing.apparel.bodyPartGroups.Contains(BodyPartGroupDefOf.UpperHead)) { - PawnApparelGenerator.debugSb.AppendLine(string.Concat(new object[] + return false; + } + return true; + }; + ThingStuffPair hatPair; + if ((from pa in PawnApparelGenerator.allApparelPairs + where hatPairValidator(pa) + select pa).TryRandomElementByWeight((Func)((ThingStuffPair pa) => pa.Commonality / (pa.Price * pa.Price)), out hatPair)) + { + if (DebugViewSettings.logApparelGeneration) + { + PawnApparelGenerator.debugSb.AppendLine("Giving free hat: " + hatPair + " insulation=" + hatPair.InsulationCold); + foreach (ThingStuffPair item2 in from a in this.aps + where !ApparelUtility.CanWearTogether(a.thing, hatPair.thing) + select a) { - " -replaces ", - current2.ToString(), - " InsulationCold=", - current2.InsulationCold - })); + PawnApparelGenerator.debugSb.AppendLine(" -replaces " + item2.ToString() + " InsulationCold=" + item2.InsulationCold); + } } + this.aps.RemoveAll((Predicate)((ThingStuffPair pa) => !ApparelUtility.CanWearTogether(pa.thing, hatPair.thing))); + this.aps.Add(hatPair); } - this.aps.RemoveAll((ThingStuffPair pa) => !ApparelUtility.CanWearTogether(pa.thing, hatPair.thing)); - this.aps.Add(hatPair); } + if (DebugViewSettings.logApparelGeneration) + { + PawnApparelGenerator.debugSb.AppendLine("New TotalInsulationCold: " + this.TotalInsulationCold); + } + break; } - if (DebugViewSettings.logApparelGeneration) - { - PawnApparelGenerator.debugSb.AppendLine("New TotalInsulationCold: " + this.TotalInsulationCold); } } @@ -238,7 +269,10 @@ public void GiveToPawn(Pawn pawn) { for (int i = 0; i < this.aps.Count; i++) { - Apparel apparel = (Apparel)ThingMaker.MakeThing(this.aps[i].thing, this.aps[i].stuff); + ThingStuffPair thingStuffPair = this.aps[i]; + ThingDef thing = thingStuffPair.thing; + ThingStuffPair thingStuffPair2 = this.aps[i]; + Apparel apparel = (Apparel)ThingMaker.MakeThing(thing, thingStuffPair2.stuff); PawnGenerator.PostProcessGeneratedGear(apparel, pawn); if (ApparelUtility.HasPartsToWear(pawn, apparel.def)) { @@ -254,14 +288,7 @@ public void GiveToPawn(Pawn pawn) { if (j != k && !ApparelUtility.CanWearTogether(wornApparel[j].def, wornApparel[k].def)) { - Log.Error(string.Concat(new object[] - { - pawn, - " generated with apparel that cannot be worn together: ", - wornApparel[j], - ", ", - wornApparel[k] - })); + Log.Error(pawn + " generated with apparel that cannot be worn together: " + wornApparel[j] + ", " + wornApparel[k]); return; } } @@ -286,7 +313,7 @@ public override string ToString() private static float freeWarmHatMaxPrice; - private static PawnApparelGenerator.PossibleApparelSet workingSet; + private static PossibleApparelSet workingSet; private static List usableApparel; @@ -295,7 +322,7 @@ public override string ToString() static PawnApparelGenerator() { PawnApparelGenerator.allApparelPairs = new List(); - PawnApparelGenerator.workingSet = new PawnApparelGenerator.PossibleApparelSet(); + PawnApparelGenerator.workingSet = new PossibleApparelSet(); PawnApparelGenerator.usableApparel = new List(); PawnApparelGenerator.debugSb = null; PawnApparelGenerator.Reset(); @@ -303,150 +330,135 @@ static PawnApparelGenerator() public static void Reset() { - PawnApparelGenerator.allApparelPairs = ThingStuffPair.AllWith((ThingDef td) => td.IsApparel); - PawnApparelGenerator.freeWarmParkaMaxPrice = (float)((int)(StatDefOf.MarketValue.Worker.GetValueAbstract(ThingDefOf.Apparel_Parka, ThingDefOf.Cloth) * 1.3f)); - PawnApparelGenerator.freeWarmHatMaxPrice = (float)((int)(StatDefOf.MarketValue.Worker.GetValueAbstract(ThingDefOf.Apparel_Tuque, ThingDefOf.Cloth) * 1.3f)); + PawnApparelGenerator.allApparelPairs = ThingStuffPair.AllWith((Predicate)((ThingDef td) => td.IsApparel)); + PawnApparelGenerator.freeWarmParkaMaxPrice = (float)(int)(StatDefOf.MarketValue.Worker.GetValueAbstract(ThingDefOf.Apparel_Parka, ThingDefOf.Cloth) * 1.2999999523162842); + PawnApparelGenerator.freeWarmHatMaxPrice = (float)(int)(StatDefOf.MarketValue.Worker.GetValueAbstract(ThingDefOf.Apparel_Tuque, ThingDefOf.Cloth) * 1.2999999523162842); } public static void GenerateStartingApparelFor(Pawn pawn, PawnGenerationRequest request) { - if (!pawn.RaceProps.ToolUser || !pawn.RaceProps.IsFlesh) - { - return; - } - if (pawn.Faction == null) - { - Log.Error("Cannot generate apparel for faction-less pawn " + pawn); - return; - } - pawn.apparel.DestroyAll(DestroyMode.Vanish); - float randomInRange = pawn.kindDef.apparelMoney.RandomInRange; - NeededWarmth neededWarmth = PawnApparelGenerator.ApparelWarmthNeededNow(pawn, request); - bool flag = Rand.Value < pawn.kindDef.apparelAllowHeadwearChance; - PawnApparelGenerator.debugSb = null; - if (DebugViewSettings.logApparelGeneration) + if (pawn.RaceProps.ToolUser && pawn.RaceProps.IsFlesh) { - PawnApparelGenerator.debugSb = new StringBuilder(); - PawnApparelGenerator.debugSb.AppendLine("Generating apparel for " + pawn); - PawnApparelGenerator.debugSb.AppendLine("Money: " + randomInRange.ToString("F0")); - PawnApparelGenerator.debugSb.AppendLine("Needed warmth: " + neededWarmth); - PawnApparelGenerator.debugSb.AppendLine("Headwear allowed: " + flag); - } - if (randomInRange >= 0.001f) - { - int num = 0; - while (true) + if (pawn.Faction == null) { - PawnApparelGenerator.GenerateWorkingPossibleApparelSetFor(pawn, randomInRange, flag); - if (DebugViewSettings.logApparelGeneration) - { - PawnApparelGenerator.debugSb.Append(num.ToString().PadRight(5) + "Trying: " + PawnApparelGenerator.workingSet.ToString()); - } - if (num >= 10 || Rand.Value >= 0.85f) - { - goto IL_1F0; - } - float num2 = Rand.Range(0.45f, 0.8f); - float totalPrice = PawnApparelGenerator.workingSet.TotalPrice; - if (totalPrice >= randomInRange * num2) - { - goto IL_1F0; - } + Log.Error("Cannot generate apparel for faction-less pawn " + pawn); + } + else + { + pawn.apparel.DestroyAll(DestroyMode.Vanish); + float randomInRange = pawn.kindDef.apparelMoney.RandomInRange; + NeededWarmth neededWarmth = PawnApparelGenerator.ApparelWarmthNeededNow(pawn, request); + bool flag = Rand.Value < pawn.kindDef.apparelAllowHeadwearChance; + PawnApparelGenerator.debugSb = null; if (DebugViewSettings.logApparelGeneration) { - PawnApparelGenerator.debugSb.AppendLine(string.Concat(new string[] - { - " -- Failed: Spent $", - totalPrice.ToString("F0"), - ", < ", - (num2 * 100f).ToString("F0"), - "% of money." - })); + PawnApparelGenerator.debugSb = new StringBuilder(); + PawnApparelGenerator.debugSb.AppendLine("Generating apparel for " + pawn); + PawnApparelGenerator.debugSb.AppendLine("Money: " + randomInRange.ToString("F0")); + PawnApparelGenerator.debugSb.AppendLine("Needed warmth: " + neededWarmth); + PawnApparelGenerator.debugSb.AppendLine("Headwear allowed: " + flag); } - IL_354: - num++; - continue; - IL_1F0: - if (num < 20 && Rand.Value < 0.97f && !PawnApparelGenerator.workingSet.Covers(BodyPartGroupDefOf.Torso)) + if (randomInRange >= 0.0010000000474974513) { - if (DebugViewSettings.logApparelGeneration) + int num = 0; + while (true) { - PawnApparelGenerator.debugSb.AppendLine(" -- Failed: Does not cover torso."); + PawnApparelGenerator.GenerateWorkingPossibleApparelSetFor(pawn, randomInRange, flag); + if (DebugViewSettings.logApparelGeneration) + { + PawnApparelGenerator.debugSb.Append(num.ToString().PadRight(5) + "Trying: " + PawnApparelGenerator.workingSet.ToString()); + } + if (num < 10 && Rand.Value < 0.85000002384185791) + { + float num2 = Rand.Range(0.45f, 0.8f); + float totalPrice = PawnApparelGenerator.workingSet.TotalPrice; + if (totalPrice < randomInRange * num2) + { + if (DebugViewSettings.logApparelGeneration) + { + PawnApparelGenerator.debugSb.AppendLine(" -- Failed: Spent $" + totalPrice.ToString("F0") + ", < " + ((float)(num2 * 100.0)).ToString("F0") + "% of money."); + } + goto IL_0354; + } + } + if (num < 20 && Rand.Value < 0.97000002861022949 && !PawnApparelGenerator.workingSet.Covers(BodyPartGroupDefOf.Torso)) + { + if (DebugViewSettings.logApparelGeneration) + { + PawnApparelGenerator.debugSb.AppendLine(" -- Failed: Does not cover torso."); + } + } + else if (num < 30 && Rand.Value < 0.800000011920929 && PawnApparelGenerator.workingSet.CoatButNoShirt()) + { + if (DebugViewSettings.logApparelGeneration) + { + PawnApparelGenerator.debugSb.AppendLine(" -- Failed: Coat but no shirt."); + } + } + else if (num < 50 && !PawnApparelGenerator.workingSet.SatisfiesNeededWarmth(neededWarmth)) + { + if (DebugViewSettings.logApparelGeneration) + { + PawnApparelGenerator.debugSb.AppendLine(" -- Failed: Wrong warmth."); + } + } + else + { + if (num >= 80) + break; + if (!PawnApparelGenerator.workingSet.IsNaked(pawn.gender)) + break; + if (DebugViewSettings.logApparelGeneration) + { + PawnApparelGenerator.debugSb.AppendLine(" -- Failed: Naked."); + } + } + goto IL_0354; + IL_0354: + num++; } - goto IL_354; - } - if (num < 30 && Rand.Value < 0.8f && PawnApparelGenerator.workingSet.CoatButNoShirt()) - { if (DebugViewSettings.logApparelGeneration) { - PawnApparelGenerator.debugSb.AppendLine(" -- Failed: Coat but no shirt."); + PawnApparelGenerator.debugSb.Append(" -- Approved! Total price: $" + PawnApparelGenerator.workingSet.TotalPrice.ToString("F0") + ", TotalInsulationCold: " + PawnApparelGenerator.workingSet.TotalInsulationCold); } - goto IL_354; } - if (num < 50 && !PawnApparelGenerator.workingSet.SatisfiesNeededWarmth(neededWarmth)) + if ((!pawn.kindDef.apparelIgnoreSeasons || request.ForceAddFreeWarmLayerIfNeeded) && !PawnApparelGenerator.workingSet.SatisfiesNeededWarmth(neededWarmth)) { - if (DebugViewSettings.logApparelGeneration) - { - PawnApparelGenerator.debugSb.AppendLine(" -- Failed: Wrong warmth."); - } - goto IL_354; + PawnApparelGenerator.workingSet.AddFreeWarmthAsNeeded(neededWarmth); } - if (num < 80 && PawnApparelGenerator.workingSet.IsNaked(pawn.gender)) + if (DebugViewSettings.logApparelGeneration) { - if (DebugViewSettings.logApparelGeneration) - { - PawnApparelGenerator.debugSb.AppendLine(" -- Failed: Naked."); - } - goto IL_354; + Log.Message(PawnApparelGenerator.debugSb.ToString()); } - break; + PawnApparelGenerator.workingSet.GiveToPawn(pawn); + PawnApparelGenerator.workingSet.Reset(); } - if (DebugViewSettings.logApparelGeneration) - { - PawnApparelGenerator.debugSb.Append(string.Concat(new object[] - { - " -- Approved! Total price: $", - PawnApparelGenerator.workingSet.TotalPrice.ToString("F0"), - ", TotalInsulationCold: ", - PawnApparelGenerator.workingSet.TotalInsulationCold - })); - } - } - if ((!pawn.kindDef.apparelIgnoreSeasons || request.ForceAddFreeWarmLayerIfNeeded) && !PawnApparelGenerator.workingSet.SatisfiesNeededWarmth(neededWarmth)) - { - PawnApparelGenerator.workingSet.AddFreeWarmthAsNeeded(neededWarmth); } - if (DebugViewSettings.logApparelGeneration) - { - Log.Message(PawnApparelGenerator.debugSb.ToString()); - } - PawnApparelGenerator.workingSet.GiveToPawn(pawn); - PawnApparelGenerator.workingSet.Reset(); } private static void GenerateWorkingPossibleApparelSetFor(Pawn pawn, float money, bool headwearAllowed) { PawnApparelGenerator.workingSet.Reset(); - float moneyLeft = money; List reqApparel = pawn.kindDef.apparelRequired; if (reqApparel != null) { int i; + _003CGenerateWorkingPossibleApparelSetFor_003Ec__AnonStorey324 _003CGenerateWorkingPossibleApparelSetFor_003Ec__AnonStorey; for (i = 0; i < reqApparel.Count; i++) { ThingStuffPair pair = (from pa in PawnApparelGenerator.allApparelPairs - where pa.thing == reqApparel[i] - select pa).RandomElementByWeight((ThingStuffPair pa) => pa.Commonality); + where pa.thing == _003CGenerateWorkingPossibleApparelSetFor_003Ec__AnonStorey.reqApparel[i] + select pa).RandomElementByWeight((Func)((ThingStuffPair pa) => pa.Commonality)); PawnApparelGenerator.workingSet.Add(pair); - moneyLeft -= pair.Price; + money -= pair.Price; } } int specialSeed = Rand.Int; - while (Rand.Value >= 0.1f) + while (!(Rand.Value < 0.10000000149011612)) { - Predicate predicate = delegate(ThingStuffPair pa) + Predicate predicate = (Predicate)delegate(ThingStuffPair pa) { - if (pa.Price > moneyLeft) + if (pa.Price > money) { return false; } @@ -462,30 +474,40 @@ private static void GenerateWorkingPossibleApparelSetFor(Pawn pawn, float money, { return false; } - if (!pawn.kindDef.apparelTags.NullOrEmpty()) + if (!pawn.kindDef.apparelTags.NullOrEmpty()) { bool flag2 = false; - for (int i = 0; i < pawn.kindDef.apparelTags.Count; i++) + int num = 0; + while (num < pawn.kindDef.apparelTags.Count) { - for (int k = 0; k < pa.thing.apparel.tags.Count; k++) + int num2 = 0; + while (num2 < pa.thing.apparel.tags.Count) { - if (pawn.kindDef.apparelTags[i] == pa.thing.apparel.tags[k]) + if (!(pawn.kindDef.apparelTags[num] == pa.thing.apparel.tags[num2])) { - flag2 = true; - break; + num2++; + continue; } + flag2 = true; + break; } - if (flag2) + if (!flag2) { - break; + num++; + continue; } + break; } if (!flag2) { return false; } } - return pa.thing.generateAllowChance >= 1f || Rand.ValueSeeded(specialSeed ^ (int)pa.thing.index ^ 64128343) <= pa.thing.generateAllowChance; + if (pa.thing.generateAllowChance < 1.0 && Rand.ValueSeeded(specialSeed ^ pa.thing.index ^ 64128343) > pa.thing.generateAllowChance) + { + return false; + } + return true; }; for (int j = 0; j < PawnApparelGenerator.allApparelPairs.Count; j++) { @@ -494,15 +516,13 @@ private static void GenerateWorkingPossibleApparelSetFor(Pawn pawn, float money, PawnApparelGenerator.usableApparel.Add(PawnApparelGenerator.allApparelPairs[j]); } } - ThingStuffPair pair2; - bool flag = PawnApparelGenerator.usableApparel.TryRandomElementByWeight((ThingStuffPair pa) => pa.Commonality, out pair2); + ThingStuffPair pair2 = default(ThingStuffPair); + bool flag = ((IEnumerable)PawnApparelGenerator.usableApparel).TryRandomElementByWeight((Func)((ThingStuffPair pa) => pa.Commonality), out pair2); PawnApparelGenerator.usableApparel.Clear(); if (!flag) - { - return; - } + break; PawnApparelGenerator.workingSet.Add(pair2); - moneyLeft -= pair2.Price; + money -= pair2.Price; } } @@ -531,32 +551,32 @@ private static NeededWarmth ApparelWarmthNeededNow(Pawn pawn, PawnGenerationRequ for (int i = 0; i < 2; i++) { NeededWarmth neededWarmth2 = PawnApparelGenerator.CalculateNeededWarmth(pawn, tile, twelfth); - if (neededWarmth2 != NeededWarmth.Any) + if (neededWarmth2 != 0) { neededWarmth = neededWarmth2; break; } twelfth = twelfth.NextTwelfth(); } - if (!pawn.kindDef.apparelIgnoreSeasons) - { - return neededWarmth; - } - if (request.ForceAddFreeWarmLayerIfNeeded && neededWarmth == NeededWarmth.Warm) + if (pawn.kindDef.apparelIgnoreSeasons) { - return neededWarmth; + if (request.ForceAddFreeWarmLayerIfNeeded && neededWarmth == NeededWarmth.Warm) + { + return neededWarmth; + } + return NeededWarmth.Any; } - return NeededWarmth.Any; + return neededWarmth; } public static NeededWarmth CalculateNeededWarmth(Pawn pawn, int tile, Twelfth twelfth) { float num = GenTemperature.AverageTemperatureAtTileForTwelfth(tile, twelfth); - if (num < pawn.def.GetStatValueAbstract(StatDefOf.ComfyTemperatureMin, null) - 4f) + if (num < pawn.def.GetStatValueAbstract(StatDefOf.ComfyTemperatureMin, null) - 4.0) { return NeededWarmth.Warm; } - if (num > pawn.def.GetStatValueAbstract(StatDefOf.ComfyTemperatureMin, null) + 4f) + if (num > pawn.def.GetStatValueAbstract(StatDefOf.ComfyTemperatureMin, null) + 4.0) { return NeededWarmth.Cool; } @@ -565,17 +585,9 @@ public static NeededWarmth CalculateNeededWarmth(Pawn pawn, int tile, Twelfth tw internal static void MakeTableApparelPairs() { - IEnumerable arg_129_0 = from p in PawnApparelGenerator.allApparelPairs + DebugTables.MakeTablesDialog(from p in PawnApparelGenerator.allApparelPairs orderby p.thing.defName descending - select p; - TableDataGetter[] expr_2D = new TableDataGetter[6]; - expr_2D[0] = new TableDataGetter("thing", (ThingStuffPair p) => p.thing.defName); - expr_2D[1] = new TableDataGetter("stuff", (ThingStuffPair p) => (p.stuff == null) ? string.Empty : p.stuff.defName); - expr_2D[2] = new TableDataGetter("price", (ThingStuffPair p) => p.Price.ToString()); - expr_2D[3] = new TableDataGetter("commonality", (ThingStuffPair p) => (p.Commonality * 100f).ToString("F4")); - expr_2D[4] = new TableDataGetter("def-commonality", (ThingStuffPair p) => p.thing.generateCommonality.ToString("F4")); - expr_2D[5] = new TableDataGetter("insulationCold", (ThingStuffPair p) => (p.InsulationCold != 0f) ? p.InsulationCold.ToString() : string.Empty); - DebugTables.MakeTablesDialog(arg_129_0, expr_2D); + select p, new TableDataGetter("thing", (Func)((ThingStuffPair p) => p.thing.defName)), new TableDataGetter("stuff", (Func)((ThingStuffPair p) => (p.stuff == null) ? string.Empty : p.stuff.defName)), new TableDataGetter("price", (Func)((ThingStuffPair p) => p.Price.ToString())), new TableDataGetter("commonality", (Func)((ThingStuffPair p) => ((float)(p.Commonality * 100.0)).ToString("F4"))), new TableDataGetter("def-commonality", (Func)((ThingStuffPair p) => p.thing.generateCommonality.ToString("F4"))), new TableDataGetter("insulationCold", (Func)((ThingStuffPair p) => (p.InsulationCold != 0.0) ? p.InsulationCold.ToString() : string.Empty))); } public static void MakeTableApparelPairsByThing() @@ -587,11 +599,12 @@ internal static void LogHeadwearApparelPairs() { StringBuilder stringBuilder = new StringBuilder(); stringBuilder.AppendLine("Listing all entries in allApparelPairs of headwear"); - foreach (ThingStuffPair current in from pa in PawnApparelGenerator.allApparelPairs + foreach (ThingStuffPair item in from pa in PawnApparelGenerator.allApparelPairs where PawnApparelGenerator.IsHeadwear(pa.thing) orderby pa.thing.defName select pa) { + ThingStuffPair current = item; stringBuilder.AppendLine(current + " - " + current.commonalityMultiplier); } Log.Message(stringBuilder.ToString()); @@ -602,35 +615,37 @@ public static void MakeTablePairsByThing(List pairList) DefMap totalCommMult = new DefMap(); DefMap totalComm = new DefMap(); DefMap pairCount = new DefMap(); - foreach (ThingStuffPair current in pairList) + List.Enumerator enumerator = pairList.GetEnumerator(); + try + { + while (enumerator.MoveNext()) + { + ThingStuffPair current = enumerator.Current; + DefMap defMap; + DefMap obj = defMap = totalCommMult; + ThingDef thing; + ThingDef def = thing = current.thing; + float num = defMap[thing]; + obj[def] = num + current.commonalityMultiplier; + DefMap defMap2; + DefMap obj2 = defMap2 = totalComm; + ThingDef def2 = thing = current.thing; + num = defMap2[thing]; + obj2[def2] = num + current.Commonality; + DefMap defMap3; + DefMap obj3 = defMap3 = pairCount; + ThingDef def3 = thing = current.thing; + int num2 = defMap3[thing]; + obj3[def3] = num2 + 1; + } + } + finally { - DefMap totalCommMult2; - DefMap expr_4D = totalCommMult2 = totalCommMult; - ThingDef thing; - ThingDef expr_56 = thing = current.thing; - float num = totalCommMult2[thing]; - expr_4D[expr_56] = num + current.commonalityMultiplier; - DefMap totalComm2; - DefMap expr_78 = totalComm2 = totalComm; - ThingDef expr_82 = thing = current.thing; - num = totalComm2[thing]; - expr_78[expr_82] = num + current.Commonality; - DefMap pairCount2; - DefMap expr_A5 = pairCount2 = pairCount; - ThingDef expr_AF = thing = current.thing; - int num2 = pairCount2[thing]; - expr_A5[expr_AF] = num2 + 1; + ((IDisposable)(object)enumerator).Dispose(); } - IEnumerable arg_19E_0 = from d in DefDatabase.AllDefs - where pairList.Any((ThingStuffPair pa) => pa.thing == d) - select d; - TableDataGetter[] expr_FF = new TableDataGetter[5]; - expr_FF[0] = new TableDataGetter("thing", (ThingDef t) => t.defName); - expr_FF[1] = new TableDataGetter("pair count", (ThingDef t) => pairCount[t].ToString()); - expr_FF[2] = new TableDataGetter("total commonality multiplier ", (ThingDef t) => totalCommMult[t].ToString("F4")); - expr_FF[3] = new TableDataGetter("total commonality", (ThingDef t) => totalComm[t].ToString("F4")); - expr_FF[4] = new TableDataGetter("def-commonality", (ThingDef t) => t.generateCommonality.ToString("F4")); - DebugTables.MakeTablesDialog(arg_19E_0, expr_FF); + DebugTables.MakeTablesDialog(from d in DefDatabase.AllDefs + where pairList.Any((Predicate)((ThingStuffPair pa) => pa.thing == d)) + select d, new TableDataGetter("thing", (Func)((ThingDef t) => t.defName)), new TableDataGetter("pair count", (Func)((ThingDef t) => pairCount[t].ToString())), new TableDataGetter("total commonality multiplier ", (Func)((ThingDef t) => totalCommMult[t].ToString("F4"))), new TableDataGetter("total commonality", (Func)((ThingDef t) => totalComm[t].ToString("F4"))), new TableDataGetter("def-commonality", (Func)((ThingDef t) => t.generateCommonality.ToString("F4")))); } } } diff --git a/Assembly-CSharp/RimWorld/PawnBio.cs b/Assembly-CSharp/RimWorld/PawnBio.cs index cfcbe8957..d6896f2aa 100644 --- a/Assembly-CSharp/RimWorld/PawnBio.cs +++ b/Assembly-CSharp/RimWorld/PawnBio.cs @@ -1,6 +1,4 @@ -using System; using System.Collections.Generic; -using System.Diagnostics; using Verse; namespace RimWorld @@ -61,14 +59,22 @@ public void ResolveReferences() } } - [DebuggerHidden] public IEnumerable ConfigErrors() { - PawnBio.c__IteratorDF c__IteratorDF = new PawnBio.c__IteratorDF(); - c__IteratorDF.<>f__this = this; - PawnBio.c__IteratorDF expr_0E = c__IteratorDF; - expr_0E.$PC = -2; - return expr_0E; + if (this.childhood != null) + { + foreach (string item in this.childhood.ConfigErrors(true)) + { + yield return this.name + ", " + this.childhood.Title + ": " + item; + } + } + if (this.adulthood != null) + { + foreach (string item2 in this.adulthood.ConfigErrors(false)) + { + yield return this.name + ", " + this.adulthood.Title + ": " + item2; + } + } } public override string ToString() diff --git a/Assembly-CSharp/RimWorld/PawnBioAndNameGenerator.cs b/Assembly-CSharp/RimWorld/PawnBioAndNameGenerator.cs index 2100575fe..83a381e55 100644 --- a/Assembly-CSharp/RimWorld/PawnBioAndNameGenerator.cs +++ b/Assembly-CSharp/RimWorld/PawnBioAndNameGenerator.cs @@ -21,10 +21,8 @@ public static class PawnBioAndNameGenerator public static void GiveAppropriateBioAndNameTo(Pawn pawn, string requiredLastName) { - if ((Rand.Value < 0.25f || pawn.kindDef.factionLeader) && PawnBioAndNameGenerator.TryGiveSolidBioTo(pawn, requiredLastName)) - { + if ((Rand.Value < 0.25 || pawn.kindDef.factionLeader) && PawnBioAndNameGenerator.TryGiveSolidBioTo(pawn, requiredLastName)) return; - } PawnBioAndNameGenerator.GiveShuffledBioTo(pawn, pawn.Faction.def, requiredLastName); } @@ -32,7 +30,7 @@ private static void GiveShuffledBioTo(Pawn pawn, FactionDef factionType, string { pawn.Name = PawnBioAndNameGenerator.GeneratePawnName(pawn, NameStyle.Full, requiredLastName); PawnBioAndNameGenerator.SetBackstoryInSlot(pawn, BackstorySlot.Childhood, ref pawn.story.childhood, factionType); - if (pawn.ageTracker.AgeBiologicalYearsFloat >= 20f) + if (pawn.ageTracker.AgeBiologicalYearsFloat >= 20.0) { PawnBioAndNameGenerator.SetBackstoryInSlot(pawn, BackstorySlot.Adulthood, ref pawn.story.adulthood, factionType); } @@ -40,23 +38,24 @@ private static void GiveShuffledBioTo(Pawn pawn, FactionDef factionType, string private static void SetBackstoryInSlot(Pawn pawn, BackstorySlot slot, ref Backstory backstory, FactionDef factionType) { - if (!(from kvp in BackstoryDatabase.allBackstories - where kvp.Value.shuffleable && kvp.Value.spawnCategories.Contains(factionType.backstoryCategory) && kvp.Value.slot == slot && (slot != BackstorySlot.Adulthood || !kvp.Value.requiredWorkTags.OverlapsWithOnAnyWorkType(pawn.story.childhood.workDisables)) - select kvp.Value).TryRandomElement(out backstory)) + if (!(from kvp in BackstoryDatabase.allBackstories.Where((Func, bool>)delegate(KeyValuePair kvp) { - Log.Error(string.Concat(new object[] + if (kvp.Value.shuffleable && kvp.Value.spawnCategories.Contains(factionType.backstoryCategory) && kvp.Value.slot == slot) { - "No shuffled ", - slot, - " found for ", - pawn, - " of ", - factionType, - ". Defaulting." - })); + if (slot == BackstorySlot.Adulthood && kvp.Value.requiredWorkTags.OverlapsWithOnAnyWorkType(pawn.story.childhood.workDisables)) + { + return false; + } + return true; + } + return false; + }) + select kvp.Value).TryRandomElement(out backstory)) + { + Log.Error("No shuffled " + slot + " found for " + pawn + " of " + factionType + ". Defaulting."); backstory = (from kvp in BackstoryDatabase.allBackstories where kvp.Value.slot == slot - select kvp).RandomElement>().Value; + select kvp).RandomElement().Value; } } @@ -67,7 +66,7 @@ private static bool TryGiveSolidBioTo(Pawn pawn, string requiredLastName) { return false; } - if (pawnBio.name.First == "Tynan" && pawnBio.name.Last == "Sylvester" && Rand.Value < 0.5f) + if (pawnBio.name.First == "Tynan" && pawnBio.name.Last == "Sylvester" && Rand.Value < 0.5) { pawnBio = PawnBioAndNameGenerator.TryGetRandomUnusedSolidBioFor(pawn.Faction.def.backstoryCategory, pawn.kindDef, pawn.gender, requiredLastName); } @@ -77,7 +76,7 @@ private static bool TryGiveSolidBioTo(Pawn pawn, string requiredLastName) } pawn.Name = pawnBio.name; pawn.story.childhood = pawnBio.childhood; - if (pawn.ageTracker.AgeBiologicalYearsFloat >= 20f) + if (pawn.ageTracker.AgeBiologicalYearsFloat >= 20.0) { pawn.story.adulthood = pawnBio.adulthood; } @@ -87,7 +86,7 @@ private static bool TryGiveSolidBioTo(Pawn pawn, string requiredLastName) private static PawnBio TryGetRandomUnusedSolidBioFor(string backstoryCategory, PawnKindDef kind, Gender gender, string requiredLastName) { NameTriple prefName = null; - if (Rand.Value < 0.5f) + if (Rand.Value < 0.5) { prefName = Prefs.RandomPreferredName(); if (prefName != null && (prefName.UsedThisGame || (requiredLastName != null && prefName.Last != requiredLastName))) @@ -95,15 +94,15 @@ private static PawnBio TryGetRandomUnusedSolidBioFor(string backstoryCategory, P prefName = null; } } - SolidBioDatabase.allBios.Shuffle(); + SolidBioDatabase.allBios.Shuffle(); PawnBio pawnBio; while (true) { - pawnBio = SolidBioDatabase.allBios.FirstOrDefault(delegate(PawnBio bio) + pawnBio = SolidBioDatabase.allBios.FirstOrDefault((Func)delegate(PawnBio bio) { if (bio.gender != GenderPossibility.Either) { - if (gender == Gender.Male && bio.gender != GenderPossibility.Male) + if (((gender == Gender.Male) ? bio.gender : GenderPossibility.Male) != 0) { return false; } @@ -112,12 +111,32 @@ private static PawnBio TryGetRandomUnusedSolidBioFor(string backstoryCategory, P return false; } } - return (requiredLastName.NullOrEmpty() || !(bio.name.Last != requiredLastName)) && (prefName == null || bio.name.Equals(prefName)) && (!kind.factionLeader || bio.pirateKing) && bio.adulthood.spawnCategories.Contains(backstoryCategory) && !bio.name.UsedThisGame; + if (!requiredLastName.NullOrEmpty() && bio.name.Last != requiredLastName) + { + return false; + } + if (prefName != null && !bio.name.Equals(prefName)) + { + return false; + } + if (kind.factionLeader && !bio.pirateKing) + { + return false; + } + if (!bio.adulthood.spawnCategories.Contains(backstoryCategory)) + { + return false; + } + if (bio.name.UsedThisGame) + { + return false; + } + return true; }); - if (pawnBio != null || prefName == null) - { + if (pawnBio != null) + break; + if (prefName == null) break; - } prefName = null; } return pawnBio; @@ -126,7 +145,7 @@ private static PawnBio TryGetRandomUnusedSolidBioFor(string backstoryCategory, P public static NameTriple TryGetRandomUnusedSolidName(Gender gender, string requiredLastName = null) { NameTriple nameTriple = null; - if (Rand.Value < 0.5f) + if (Rand.Value < 0.5) { nameTriple = Prefs.RandomPreferredName(); if (nameTriple != null && (nameTriple.UsedThisGame || (requiredLastName != null && nameTriple.Last != requiredLastName))) @@ -136,16 +155,8 @@ public static NameTriple TryGetRandomUnusedSolidName(Gender gender, string requi } List listForGender = PawnNameDatabaseSolid.GetListForGender(GenderPossibility.Either); List list = (gender != Gender.Male) ? PawnNameDatabaseSolid.GetListForGender(GenderPossibility.Female) : PawnNameDatabaseSolid.GetListForGender(GenderPossibility.Male); - float num = ((float)listForGender.Count + 0.1f) / ((float)(listForGender.Count + list.Count) + 0.1f); - List list2; - if (Rand.Value < num) - { - list2 = listForGender; - } - else - { - list2 = list; - } + float num = (float)(((float)listForGender.Count + 0.10000000149011612) / ((float)(listForGender.Count + list.Count) + 0.10000000149011612)); + List list2 = (!(Rand.Value < num)) ? list : listForGender; if (list2.Count == 0) { Log.Error("Empty solid pawn name list for gender: " + gender + "."); @@ -155,25 +166,36 @@ public static NameTriple TryGetRandomUnusedSolidName(Gender gender, string requi { return nameTriple; } - list2.Shuffle(); - return (from name in list2 - where (requiredLastName == null || !(name.Last != requiredLastName)) && !name.UsedThisGame - select name).FirstOrDefault(); + list2.Shuffle(); + return list2.Where((Func)delegate(NameTriple name) + { + if (requiredLastName != null && name.Last != requiredLastName) + { + return false; + } + if (name.UsedThisGame) + { + return false; + } + return true; + }).FirstOrDefault(); } public static Name GeneratePawnName(Pawn pawn, NameStyle style = NameStyle.Full, string forcedLastName = null) { - if (style == NameStyle.Full) + switch (style) + { + case NameStyle.Full: { RulePackDef nameGenerator = pawn.RaceProps.GetNameGenerator(pawn.gender); if (nameGenerator != null) { - string name = NameGenerator.GenerateName(nameGenerator, (string x) => !new NameSingle(x, false).UsedThisGame, false); + string name = NameGenerator.GenerateName(nameGenerator, (Predicate)((string x) => !new NameSingle(x, false).UsedThisGame), false); return new NameSingle(name, false); } if (pawn.Faction != null && pawn.Faction.def.pawnNameMaker != null) { - string rawName = NameGenerator.GenerateName(pawn.Faction.def.pawnNameMaker, delegate(string x) + string rawName = NameGenerator.GenerateName(pawn.Faction.def.pawnNameMaker, (Predicate)delegate(string x) { NameTriple nameTriple4 = NameTriple.FromString(x); nameTriple4.ResolveMissingPieces(forcedLastName); @@ -184,9 +206,9 @@ public static Name GeneratePawnName(Pawn pawn, NameStyle style = NameStyle.Full, nameTriple.ResolveMissingPieces(forcedLastName); return nameTriple; } - if (pawn.RaceProps.nameCategory != PawnNameCategory.NoName) + if (pawn.RaceProps.nameCategory != 0) { - if (Rand.Value < 0.5f) + if (Rand.Value < 0.5) { NameTriple nameTriple2 = PawnBioAndNameGenerator.TryGetRandomUnusedSolidName(pawn.gender, forcedLastName); if (nameTriple2 != null) @@ -198,28 +220,27 @@ public static Name GeneratePawnName(Pawn pawn, NameStyle style = NameStyle.Full, } Log.Error("No name making method for " + pawn); NameTriple nameTriple3 = NameTriple.FromString(pawn.def.label); - nameTriple3.ResolveMissingPieces(null); + nameTriple3.ResolveMissingPieces((string)null); return nameTriple3; } - else + case NameStyle.Numeric: { - if (style == NameStyle.Numeric) + int num = 1; + string text; + while (true) { - int num = 1; - string text; - while (true) - { - text = pawn.KindLabel + " " + num.ToString(); - if (!NameUseChecker.NameSingleIsUsed(text)) - { - break; - } - num++; - } - return new NameSingle(text, true); + text = pawn.KindLabel + " " + num.ToString(); + if (!NameUseChecker.NameSingleIsUsed(text)) + break; + num++; } + return new NameSingle(text, true); + } + default: + { throw new InvalidOperationException(); } + } } private static NameTriple GeneratePawnName_Shuffled(Pawn pawn, string forcedLastName = null) @@ -232,30 +253,22 @@ private static NameTriple GeneratePawnName_Shuffled(Pawn pawn, string forcedLast } NameBank nameBank = PawnNameDatabaseShuffled.BankOf(pawnNameCategory); string name = nameBank.GetName(PawnNameSlot.First, pawn.gender); - string text; - if (forcedLastName != null) - { - text = forcedLastName; - } - else - { - text = nameBank.GetName(PawnNameSlot.Last, Gender.None); - } + string text = (forcedLastName == null) ? nameBank.GetName(PawnNameSlot.Last, Gender.None) : forcedLastName; int num = 0; string nick; - do + while (true) { num++; - if (Rand.Value < 0.15f) + if (Rand.Value < 0.15000000596046448) { Gender gender = pawn.gender; - if (Rand.Value < 0.5f) + if (Rand.Value < 0.5) { gender = Gender.None; } nick = nameBank.GetName(PawnNameSlot.Nick, gender); } - else if (Rand.Value < 0.5f) + else if (Rand.Value < 0.5) { nick = name; } @@ -263,12 +276,15 @@ private static NameTriple GeneratePawnName_Shuffled(Pawn pawn, string forcedLast { nick = text; } + if (num >= 50) + break; + if (!NameUseChecker.AllPawnsNamesEverUsed.Any((Func)delegate(Name x) + { + NameTriple nameTriple = x as NameTriple; + return nameTriple != null && nameTriple.Nick == nick; + })) + break; } - while (num < 50 && NameUseChecker.AllPawnsNamesEverUsed.Any(delegate(Name x) - { - NameTriple nameTriple = x as NameTriple; - return nameTriple != null && nameTriple.Nick == nick; - })); return new NameTriple(name, nick, text); } } diff --git a/Assembly-CSharp/RimWorld/PawnBioType.cs b/Assembly-CSharp/RimWorld/PawnBioType.cs index 96470c039..cb82aa46f 100644 --- a/Assembly-CSharp/RimWorld/PawnBioType.cs +++ b/Assembly-CSharp/RimWorld/PawnBioType.cs @@ -1,11 +1,9 @@ -using System; - namespace RimWorld { public enum PawnBioType { - Undefined, - BackstoryInGame, - PirateKing + Undefined = 0, + BackstoryInGame = 1, + PirateKing = 2 } } diff --git a/Assembly-CSharp/RimWorld/PawnBreathMoteMaker.cs b/Assembly-CSharp/RimWorld/PawnBreathMoteMaker.cs index 4e6b23387..fb5194162 100644 --- a/Assembly-CSharp/RimWorld/PawnBreathMoteMaker.cs +++ b/Assembly-CSharp/RimWorld/PawnBreathMoteMaker.cs @@ -1,4 +1,3 @@ -using System; using UnityEngine; using Verse; @@ -29,18 +28,17 @@ public PawnBreathMoteMaker(Pawn pawn) public void BreathMoteMakerTick() { - if (!this.pawn.RaceProps.Humanlike || this.pawn.RaceProps.IsMechanoid) + if (this.pawn.RaceProps.Humanlike && !this.pawn.RaceProps.IsMechanoid) { - return; - } - int num = (Find.TickManager.TicksGame + this.pawn.HashOffset()) % 320; - if (num == 0) - { - this.doThisBreath = (this.pawn.AmbientTemperature < 0f && this.pawn.GetPosture() != PawnPosture.Standing); - } - if (this.doThisBreath && num < 80 && num % 8 == 0) - { - this.TryMakeBreathMote(); + int num = (Find.TickManager.TicksGame + this.pawn.HashOffset()) % 320; + if (num == 0) + { + this.doThisBreath = (this.pawn.AmbientTemperature < 0.0 && this.pawn.GetPosture() != PawnPosture.Standing); + } + if (this.doThisBreath && num < 80 && num % 8 == 0) + { + this.TryMakeBreathMote(); + } } } diff --git a/Assembly-CSharp/RimWorld/PawnCapacityDefOf.cs b/Assembly-CSharp/RimWorld/PawnCapacityDefOf.cs index 4177648dd..89ac0f03f 100644 --- a/Assembly-CSharp/RimWorld/PawnCapacityDefOf.cs +++ b/Assembly-CSharp/RimWorld/PawnCapacityDefOf.cs @@ -1,4 +1,3 @@ -using System; using Verse; namespace RimWorld diff --git a/Assembly-CSharp/RimWorld/PawnCapacityFactor.cs b/Assembly-CSharp/RimWorld/PawnCapacityFactor.cs index 711719823..325b63932 100644 --- a/Assembly-CSharp/RimWorld/PawnCapacityFactor.cs +++ b/Assembly-CSharp/RimWorld/PawnCapacityFactor.cs @@ -1,4 +1,3 @@ -using System; using UnityEngine; using Verse; @@ -25,14 +24,7 @@ public float GetFactor(float capacityEfficiency) } if (this.useReciprocal) { - if (Mathf.Abs(num) < 0.001f) - { - num = 5f; - } - else - { - num = Mathf.Min(1f / num, 5f); - } + num = (float)((!(Mathf.Abs(num) < 0.0010000000474974513)) ? Mathf.Min((float)(1.0 / num), 5f) : 5.0); } return num; } diff --git a/Assembly-CSharp/RimWorld/PawnCapacityWorker_BloodFiltration.cs b/Assembly-CSharp/RimWorld/PawnCapacityWorker_BloodFiltration.cs index 1a7f253d8..f85c0b2b2 100644 --- a/Assembly-CSharp/RimWorld/PawnCapacityWorker_BloodFiltration.cs +++ b/Assembly-CSharp/RimWorld/PawnCapacityWorker_BloodFiltration.cs @@ -1,4 +1,3 @@ -using System; using System.Collections.Generic; using Verse; diff --git a/Assembly-CSharp/RimWorld/PawnCapacityWorker_BloodPumping.cs b/Assembly-CSharp/RimWorld/PawnCapacityWorker_BloodPumping.cs index a3156b685..4af8fc5e0 100644 --- a/Assembly-CSharp/RimWorld/PawnCapacityWorker_BloodPumping.cs +++ b/Assembly-CSharp/RimWorld/PawnCapacityWorker_BloodPumping.cs @@ -1,4 +1,3 @@ -using System; using System.Collections.Generic; using Verse; diff --git a/Assembly-CSharp/RimWorld/PawnCapacityWorker_Breathing.cs b/Assembly-CSharp/RimWorld/PawnCapacityWorker_Breathing.cs index 58150db5b..548125ba0 100644 --- a/Assembly-CSharp/RimWorld/PawnCapacityWorker_Breathing.cs +++ b/Assembly-CSharp/RimWorld/PawnCapacityWorker_Breathing.cs @@ -1,4 +1,3 @@ -using System; using System.Collections.Generic; using Verse; diff --git a/Assembly-CSharp/RimWorld/PawnCapacityWorker_Consciousness.cs b/Assembly-CSharp/RimWorld/PawnCapacityWorker_Consciousness.cs index 205b3b638..b5684e75d 100644 --- a/Assembly-CSharp/RimWorld/PawnCapacityWorker_Consciousness.cs +++ b/Assembly-CSharp/RimWorld/PawnCapacityWorker_Consciousness.cs @@ -1,4 +1,3 @@ -using System; using System.Collections.Generic; using UnityEngine; using Verse; diff --git a/Assembly-CSharp/RimWorld/PawnCapacityWorker_Eating.cs b/Assembly-CSharp/RimWorld/PawnCapacityWorker_Eating.cs index 967f850e4..209d83085 100644 --- a/Assembly-CSharp/RimWorld/PawnCapacityWorker_Eating.cs +++ b/Assembly-CSharp/RimWorld/PawnCapacityWorker_Eating.cs @@ -1,4 +1,3 @@ -using System; using System.Collections.Generic; using Verse; diff --git a/Assembly-CSharp/RimWorld/PawnCapacityWorker_Hearing.cs b/Assembly-CSharp/RimWorld/PawnCapacityWorker_Hearing.cs index a96ed9c69..d871f6ec8 100644 --- a/Assembly-CSharp/RimWorld/PawnCapacityWorker_Hearing.cs +++ b/Assembly-CSharp/RimWorld/PawnCapacityWorker_Hearing.cs @@ -1,4 +1,3 @@ -using System; using System.Collections.Generic; using Verse; diff --git a/Assembly-CSharp/RimWorld/PawnCapacityWorker_Manipulation.cs b/Assembly-CSharp/RimWorld/PawnCapacityWorker_Manipulation.cs index 97c9a25cb..2c5f3c9b3 100644 --- a/Assembly-CSharp/RimWorld/PawnCapacityWorker_Manipulation.cs +++ b/Assembly-CSharp/RimWorld/PawnCapacityWorker_Manipulation.cs @@ -1,4 +1,3 @@ -using System; using System.Collections.Generic; using Verse; diff --git a/Assembly-CSharp/RimWorld/PawnCapacityWorker_Metabolism.cs b/Assembly-CSharp/RimWorld/PawnCapacityWorker_Metabolism.cs index 71af0d056..f1ff67cb9 100644 --- a/Assembly-CSharp/RimWorld/PawnCapacityWorker_Metabolism.cs +++ b/Assembly-CSharp/RimWorld/PawnCapacityWorker_Metabolism.cs @@ -1,4 +1,3 @@ -using System; using System.Collections.Generic; using Verse; diff --git a/Assembly-CSharp/RimWorld/PawnCapacityWorker_Moving.cs b/Assembly-CSharp/RimWorld/PawnCapacityWorker_Moving.cs index d6605d62a..b399693ea 100644 --- a/Assembly-CSharp/RimWorld/PawnCapacityWorker_Moving.cs +++ b/Assembly-CSharp/RimWorld/PawnCapacityWorker_Moving.cs @@ -1,4 +1,3 @@ -using System; using System.Collections.Generic; using UnityEngine; using Verse; @@ -11,7 +10,7 @@ public override float CalculateCapacityLevel(HediffSet diffSet, List.Get(this.headerIcon, true); } @@ -70,7 +70,7 @@ public Vector2 HeaderIconSize return this.headerIconSize; } Texture2D texture2D = this.HeaderIcon; - if (texture2D != null) + if ((UnityEngine.Object)texture2D != (UnityEngine.Object)null) { return new Vector2((float)texture2D.width, (float)texture2D.height); } diff --git a/Assembly-CSharp/RimWorld/PawnColumnDefgenerator.cs b/Assembly-CSharp/RimWorld/PawnColumnDefgenerator.cs index ba2715172..d52801aef 100644 --- a/Assembly-CSharp/RimWorld/PawnColumnDefgenerator.cs +++ b/Assembly-CSharp/RimWorld/PawnColumnDefgenerator.cs @@ -1,18 +1,49 @@ using System; using System.Collections.Generic; -using System.Diagnostics; +using System.Linq; +using Verse; namespace RimWorld { public class PawnColumnDefgenerator { - [DebuggerHidden] public static IEnumerable ImpliedPawnColumnDefs() { - PawnColumnDefgenerator.c__Iterator6D c__Iterator6D = new PawnColumnDefgenerator.c__Iterator6D(); - PawnColumnDefgenerator.c__Iterator6D expr_07 = c__Iterator6D; - expr_07.$PC = -2; - return expr_07; + PawnTableDef animalsTable = PawnTableDefOf.Animals; + foreach (TrainableDef item in from td in DefDatabase.AllDefsListForReading + orderby td.listPriority descending + select td) + { + PawnColumnDef d3 = new PawnColumnDef + { + defName = "Trainable_" + item.defName, + trainable = item, + headerIcon = item.icon, + workerClass = typeof(PawnColumnWorker_Trainable), + sortable = true, + headerTip = item.LabelCap + }; + animalsTable.columns.Insert(animalsTable.columns.FindIndex((Predicate)((PawnColumnDef x) => x.Worker is PawnColumnWorker_Checkbox)) - 1, d3); + yield return d3; + } + PawnTableDef workTable = PawnTableDefOf.Work; + bool moveWorkTypeLabelDown = false; + foreach (WorkTypeDef item2 in (from d in WorkTypeDefsUtility.WorkTypeDefsInPriorityOrder + where d.visible + select d).Reverse()) + { + moveWorkTypeLabelDown = !moveWorkTypeLabelDown; + PawnColumnDef d2 = new PawnColumnDef + { + defName = "WorkPriority_" + item2.defName, + workType = item2, + moveWorkTypeLabelDown = moveWorkTypeLabelDown, + workerClass = typeof(PawnColumnWorker_WorkPriority), + sortable = true + }; + workTable.columns.Insert(workTable.columns.FindIndex((Predicate)((PawnColumnDef x) => x.Worker is PawnColumnWorker_CopyPasteWorkPriorities)) + 1, d2); + yield return d2; + } } } } diff --git a/Assembly-CSharp/RimWorld/PawnColumnWorker.cs b/Assembly-CSharp/RimWorld/PawnColumnWorker.cs index e378e7220..a53d3b557 100644 --- a/Assembly-CSharp/RimWorld/PawnColumnWorker.cs +++ b/Assembly-CSharp/RimWorld/PawnColumnWorker.cs @@ -1,4 +1,3 @@ -using System; using System.Text; using UnityEngine; using Verse; @@ -47,17 +46,17 @@ public virtual void DoHeader(Rect rect, PawnTable table) GUI.color = Color.white; Text.Font = GameFont.Small; } - else if (this.def.HeaderIcon != null) + else if ((Object)this.def.HeaderIcon != (Object)null) { Vector2 headerIconSize = this.def.HeaderIconSize; - int num = (int)((rect.width - headerIconSize.x) / 2f); + int num = (int)((rect.width - headerIconSize.x) / 2.0); Rect position = new Rect(rect.x + (float)num, rect.yMax - headerIconSize.y, headerIconSize.x, headerIconSize.y); GUI.DrawTexture(position, this.def.HeaderIcon); } if (table.SortingBy == this.def) { Texture2D texture2D = (!table.SortingDescending) ? PawnColumnWorker.SortingIcon : PawnColumnWorker.SortingDescendingIcon; - Rect position2 = new Rect(rect.xMax - (float)texture2D.width - 1f, rect.yMax - (float)texture2D.height - 1f, (float)texture2D.width, (float)texture2D.height); + Rect position2 = new Rect((float)(rect.xMax - (float)texture2D.width - 1.0), (float)(rect.yMax - (float)texture2D.height - 1.0), (float)texture2D.width, (float)texture2D.height); GUI.DrawTexture(position2, texture2D); } if (this.def.HeaderInteractable) @@ -86,13 +85,15 @@ public virtual int GetMinWidth(PawnTable table) if (!this.def.label.NullOrEmpty()) { Text.Font = this.DefaultHeaderFont; - int result = Mathf.CeilToInt(Text.CalcSize(this.def.LabelCap).x); + Vector2 vector = Text.CalcSize(this.def.LabelCap); + int result = Mathf.CeilToInt(vector.x); Text.Font = GameFont.Small; return result; } - if (this.def.HeaderIcon != null) + if ((Object)this.def.HeaderIcon != (Object)null) { - return Mathf.CeilToInt(this.def.HeaderIconSize.x); + Vector2 headerIconSize = this.def.HeaderIconSize; + return Mathf.CeilToInt(headerIconSize.x); } return 1; } @@ -117,13 +118,15 @@ public virtual int GetMinHeaderHeight(PawnTable table) if (!this.def.label.NullOrEmpty()) { Text.Font = this.DefaultHeaderFont; - int result = Mathf.CeilToInt(Text.CalcSize(this.def.LabelCap).y); + Vector2 vector = Text.CalcSize(this.def.LabelCap); + int result = Mathf.CeilToInt(vector.y); Text.Font = GameFont.Small; return result; } - if (this.def.HeaderIcon != null) + if ((Object)this.def.HeaderIcon != (Object)null) { - return Mathf.CeilToInt(this.def.HeaderIconSize.y); + Vector2 headerIconSize = this.def.HeaderIconSize; + return Mathf.CeilToInt(headerIconSize.y); } return 0; } diff --git a/Assembly-CSharp/RimWorld/PawnColumnWorker_AllowedArea.cs b/Assembly-CSharp/RimWorld/PawnColumnWorker_AllowedArea.cs index 7c4cec60c..1f3c9c3ec 100644 --- a/Assembly-CSharp/RimWorld/PawnColumnWorker_AllowedArea.cs +++ b/Assembly-CSharp/RimWorld/PawnColumnWorker_AllowedArea.cs @@ -1,4 +1,3 @@ -using System; using System.Collections.Generic; using UnityEngine; using Verse; @@ -37,18 +36,17 @@ public override int GetMinHeaderHeight(PawnTable table) public override void DoCell(Rect rect, Pawn pawn, PawnTable table) { - if (pawn.Faction != Faction.OfPlayer) + if (pawn.Faction == Faction.OfPlayer) { - return; + AllowedAreaMode mode = (AllowedAreaMode)(pawn.RaceProps.Humanlike ? 1 : 2); + AreaAllowedGUI.DoAllowedAreaSelectors(rect, pawn, mode); } - AllowedAreaMode mode = (!pawn.RaceProps.Humanlike) ? AllowedAreaMode.Animal : AllowedAreaMode.Humanlike; - AreaAllowedGUI.DoAllowedAreaSelectors(rect, pawn, mode); } public override void DoHeader(Rect rect, PawnTable table) { base.DoHeader(rect, table); - Rect rect2 = new Rect(rect.x, rect.y + (rect.height - 65f), Mathf.Min(rect.width, 360f), 32f); + Rect rect2 = new Rect(rect.x, (float)(rect.y + (rect.height - 65.0)), Mathf.Min(rect.width, 360f), 32f); if (Widgets.ButtonText(rect2, "ManageAreas".Translate(), true, false, true)) { Find.WindowStack.Add(new Dialog_ManageAreas(Find.VisibleMap)); @@ -67,7 +65,7 @@ private int GetValueToCompare(Pawn pawn) return -2147483648; } Area areaRestriction = pawn.playerSettings.AreaRestriction; - return (areaRestriction == null) ? -2147483647 : areaRestriction.ID; + return (areaRestriction == null) ? (-2147483647) : areaRestriction.ID; } protected override void HeaderClicked(Rect headerRect, PawnTable table) @@ -76,20 +74,23 @@ protected override void HeaderClicked(Rect headerRect, PawnTable table) if (Event.current.shift && Find.VisibleMap != null) { List pawnsListForReading = table.PawnsListForReading; - for (int i = 0; i < pawnsListForReading.Count; i++) + int num = 0; + while (num < pawnsListForReading.Count) { - if (pawnsListForReading[i].Faction != Faction.OfPlayer) - { - return; - } - if (Event.current.button == 0) - { - pawnsListForReading[i].playerSettings.AreaRestriction = Find.VisibleMap.areaManager.Home; - } - else if (Event.current.button == 1) + if (pawnsListForReading[num].Faction == Faction.OfPlayer) { - pawnsListForReading[i].playerSettings.AreaRestriction = null; + if (Event.current.button == 0) + { + pawnsListForReading[num].playerSettings.AreaRestriction = Find.VisibleMap.areaManager.Home; + } + else if (Event.current.button == 1) + { + pawnsListForReading[num].playerSettings.AreaRestriction = null; + } + num++; + continue; } + return; } if (Event.current.button == 0) { diff --git a/Assembly-CSharp/RimWorld/PawnColumnWorker_AllowedAreaWide.cs b/Assembly-CSharp/RimWorld/PawnColumnWorker_AllowedAreaWide.cs index a8090cbaf..18abbe2fe 100644 --- a/Assembly-CSharp/RimWorld/PawnColumnWorker_AllowedAreaWide.cs +++ b/Assembly-CSharp/RimWorld/PawnColumnWorker_AllowedAreaWide.cs @@ -1,4 +1,3 @@ -using System; using UnityEngine; namespace RimWorld diff --git a/Assembly-CSharp/RimWorld/PawnColumnWorker_Checkbox.cs b/Assembly-CSharp/RimWorld/PawnColumnWorker_Checkbox.cs index f9b1db817..4e0893c5c 100644 --- a/Assembly-CSharp/RimWorld/PawnColumnWorker_Checkbox.cs +++ b/Assembly-CSharp/RimWorld/PawnColumnWorker_Checkbox.cs @@ -1,4 +1,3 @@ -using System; using System.Collections.Generic; using UnityEngine; using Verse; @@ -12,28 +11,27 @@ public abstract class PawnColumnWorker_Checkbox : PawnColumnWorker public override void DoCell(Rect rect, Pawn pawn, PawnTable table) { - if (!this.HasCheckbox(pawn)) - { - return; - } - int num = (int)((rect.width - 24f) / 2f); - int num2 = Mathf.Max(3, 0); - Vector2 topLeft = new Vector2(rect.x + (float)num, rect.y + (float)num2); - Rect rect2 = new Rect(topLeft.x, topLeft.y, 24f, 24f); - bool value = this.GetValue(pawn); - bool flag = value; - Widgets.Checkbox(topLeft, ref value, 24f, false); - if (Mouse.IsOver(rect2)) + if (this.HasCheckbox(pawn)) { - string tip = this.GetTip(pawn); - if (!tip.NullOrEmpty()) + int num = (int)((rect.width - 24.0) / 2.0); + int num2 = Mathf.Max(3, 0); + Vector2 topLeft = new Vector2(rect.x + (float)num, rect.y + (float)num2); + Rect rect2 = new Rect(topLeft.x, topLeft.y, 24f, 24f); + bool value; + bool flag = value = this.GetValue(pawn); + Widgets.Checkbox(topLeft, ref flag, 24f, false); + if (Mouse.IsOver(rect2)) { - TooltipHandler.TipRegion(rect2, tip); + string tip = this.GetTip(pawn); + if (!tip.NullOrEmpty()) + { + TooltipHandler.TipRegion(rect2, tip); + } + } + if (flag != value) + { + this.SetValue(pawn, flag); } - } - if (value != flag) - { - this.SetValue(pawn, value); } } @@ -72,7 +70,7 @@ private int GetValueToCompare(Pawn pawn) protected virtual string GetTip(Pawn pawn) { - return null; + return (string)null; } protected virtual bool HasCheckbox(Pawn pawn) diff --git a/Assembly-CSharp/RimWorld/PawnColumnWorker_CopyPaste.cs b/Assembly-CSharp/RimWorld/PawnColumnWorker_CopyPaste.cs index bfc20f473..2ede19997 100644 --- a/Assembly-CSharp/RimWorld/PawnColumnWorker_CopyPaste.cs +++ b/Assembly-CSharp/RimWorld/PawnColumnWorker_CopyPaste.cs @@ -16,13 +16,13 @@ public override void DoCell(Rect rect, Pawn pawn, PawnTable table) Action pasteAction = null; if (this.AnythingInClipboard) { - pasteAction = delegate + pasteAction = (Action)delegate() { this.PasteTo(pawn); }; } Rect rect2 = new Rect(rect.x, rect.y, 36f, 30f); - CopyPasteUI.DoCopyPasteButtons(rect2, delegate + CopyPasteUI.DoCopyPasteButtons(rect2, (Action)delegate() { this.CopyFrom(pawn); }, pasteAction); diff --git a/Assembly-CSharp/RimWorld/PawnColumnWorker_CopyPasteTimetable.cs b/Assembly-CSharp/RimWorld/PawnColumnWorker_CopyPasteTimetable.cs index 3c8ff4f51..f046527d7 100644 --- a/Assembly-CSharp/RimWorld/PawnColumnWorker_CopyPasteTimetable.cs +++ b/Assembly-CSharp/RimWorld/PawnColumnWorker_CopyPasteTimetable.cs @@ -1,4 +1,3 @@ -using System; using System.Collections.Generic; using System.Linq; using UnityEngine; @@ -20,16 +19,15 @@ protected override bool AnythingInClipboard public override void DoCell(Rect rect, Pawn pawn, PawnTable table) { - if (pawn.timetable == null) + if (pawn.timetable != null) { - return; + base.DoCell(rect, pawn, table); } - base.DoCell(rect, pawn, table); } protected override void CopyFrom(Pawn p) { - PawnColumnWorker_CopyPasteTimetable.clipboard = p.timetable.times.ToList(); + PawnColumnWorker_CopyPasteTimetable.clipboard = p.timetable.times.ToList(); } protected override void PasteTo(Pawn p) diff --git a/Assembly-CSharp/RimWorld/PawnColumnWorker_CopyPasteWorkPriorities.cs b/Assembly-CSharp/RimWorld/PawnColumnWorker_CopyPasteWorkPriorities.cs index b47856f2f..d106bcd3b 100644 --- a/Assembly-CSharp/RimWorld/PawnColumnWorker_CopyPasteWorkPriorities.cs +++ b/Assembly-CSharp/RimWorld/PawnColumnWorker_CopyPasteWorkPriorities.cs @@ -1,4 +1,3 @@ -using System; using System.Collections.Generic; using UnityEngine; using Verse; @@ -19,11 +18,10 @@ protected override bool AnythingInClipboard public override void DoCell(Rect rect, Pawn pawn, PawnTable table) { - if (pawn.Dead || pawn.workSettings == null || !pawn.workSettings.EverWork) + if (!pawn.Dead && pawn.workSettings != null && pawn.workSettings.EverWork) { - return; + base.DoCell(rect, pawn, table); } - base.DoCell(rect, pawn, table); } protected override void CopyFrom(Pawn p) diff --git a/Assembly-CSharp/RimWorld/PawnColumnWorker_DrugPolicy.cs b/Assembly-CSharp/RimWorld/PawnColumnWorker_DrugPolicy.cs index 9f0bb4a1a..f1991134c 100644 --- a/Assembly-CSharp/RimWorld/PawnColumnWorker_DrugPolicy.cs +++ b/Assembly-CSharp/RimWorld/PawnColumnWorker_DrugPolicy.cs @@ -16,7 +16,7 @@ public class PawnColumnWorker_DrugPolicy : PawnColumnWorker public override void DoHeader(Rect rect, PawnTable table) { base.DoHeader(rect, table); - Rect rect2 = new Rect(rect.x, rect.y + (rect.height - 65f), Mathf.Min(rect.width, 360f), 32f); + Rect rect2 = new Rect(rect.x, (float)(rect.y + (rect.height - 65.0)), Mathf.Min(rect.width, 360f), 32f); if (Widgets.ButtonText(rect2, "ManageDrugPolicies".Translate(), true, false, true)) { Find.WindowStack.Add(new Dialog_ManageDrugPolicies(null)); @@ -28,49 +28,57 @@ public override void DoHeader(Rect rect, PawnTable table) public override void DoCell(Rect rect, Pawn pawn, PawnTable table) { - if (pawn.drugs == null) + if (pawn.drugs != null) { - return; - } - int num = Mathf.FloorToInt((rect.width - 4f) * 0.714285731f); - int num2 = Mathf.FloorToInt((rect.width - 4f) * 0.2857143f); - float num3 = rect.x; - Rect rect2 = new Rect(num3, rect.y + 2f, (float)num, rect.height - 4f); - string text = pawn.drugs.CurrentPolicy.label; - if (pawn.story != null && pawn.story.traits != null) - { - Trait trait = pawn.story.traits.GetTrait(TraitDefOf.DrugDesire); - if (trait != null) + int num = Mathf.FloorToInt((float)((rect.width - 4.0) * 0.71428573131561279)); + int num2 = Mathf.FloorToInt((float)((rect.width - 4.0) * 0.28571429848670959)); + float x = rect.x; + Rect rect2 = new Rect(x, (float)(rect.y + 2.0), (float)num, (float)(rect.height - 4.0)); + string text = pawn.drugs.CurrentPolicy.label; + if (pawn.story != null && pawn.story.traits != null) { - text = text + " (" + trait.Label + ")"; + Trait trait = pawn.story.traits.GetTrait(TraitDefOf.DrugDesire); + if (trait != null) + { + text = text + " (" + trait.Label + ")"; + } } - } - text = text.Truncate(rect2.width, null); - if (Widgets.ButtonText(rect2, text, true, false, true)) - { - List list = new List(); - foreach (DrugPolicy current in Current.Game.drugPolicyDatabase.AllPolicies) + text = text.Truncate(rect2.width, null); + if (Widgets.ButtonText(rect2, text, true, false, true)) { - DrugPolicy localAssignedDrugs = current; - list.Add(new FloatMenuOption(current.label, delegate + List list = new List(); + List.Enumerator enumerator = Current.Game.drugPolicyDatabase.AllPolicies.GetEnumerator(); + try + { + while (enumerator.MoveNext()) + { + DrugPolicy current = enumerator.Current; + DrugPolicy localAssignedDrugs = current; + list.Add(new FloatMenuOption(current.label, (Action)delegate() + { + pawn.drugs.CurrentPolicy = localAssignedDrugs; + }, MenuOptionPriority.Default, null, null, 0f, null, null)); + } + } + finally { - pawn.drugs.CurrentPolicy = localAssignedDrugs; - }, MenuOptionPriority.Default, null, null, 0f, null, null)); + ((IDisposable)(object)enumerator).Dispose(); + } + Find.WindowStack.Add(new FloatMenu(list)); + PlayerKnowledgeDatabase.KnowledgeDemonstrated(ConceptDefOf.DrugPolicies, KnowledgeAmount.Total); } - Find.WindowStack.Add(new FloatMenu(list)); - PlayerKnowledgeDatabase.KnowledgeDemonstrated(ConceptDefOf.DrugPolicies, KnowledgeAmount.Total); - } - num3 += (float)num; - num3 += 4f; - Rect rect3 = new Rect(num3, rect.y + 2f, (float)num2, rect.height - 4f); - if (Widgets.ButtonText(rect3, "AssignTabEdit".Translate(), true, false, true)) - { - Find.WindowStack.Add(new Dialog_ManageDrugPolicies(pawn.drugs.CurrentPolicy)); - PlayerKnowledgeDatabase.KnowledgeDemonstrated(ConceptDefOf.DrugPolicies, KnowledgeAmount.Total); + x += (float)num; + x = (float)(x + 4.0); + Rect rect3 = new Rect(x, (float)(rect.y + 2.0), (float)num2, (float)(rect.height - 4.0)); + if (Widgets.ButtonText(rect3, "AssignTabEdit".Translate(), true, false, true)) + { + Find.WindowStack.Add(new Dialog_ManageDrugPolicies(pawn.drugs.CurrentPolicy)); + PlayerKnowledgeDatabase.KnowledgeDemonstrated(ConceptDefOf.DrugPolicies, KnowledgeAmount.Total); + } + UIHighlighter.HighlightOpportunity(rect2, "ButtonAssignDrugs"); + UIHighlighter.HighlightOpportunity(rect3, "ButtonAssignDrugs"); + x += (float)num2; } - UIHighlighter.HighlightOpportunity(rect2, "ButtonAssignDrugs"); - UIHighlighter.HighlightOpportunity(rect3, "ButtonAssignDrugs"); - num3 += (float)num2; } public override int GetMinWidth(PawnTable table) @@ -95,7 +103,7 @@ public override int Compare(Pawn a, Pawn b) private int GetValueToCompare(Pawn pawn) { - return (pawn.drugs != null && pawn.drugs.CurrentPolicy != null) ? pawn.drugs.CurrentPolicy.uniqueId : -2147483648; + return (pawn.drugs != null && pawn.drugs.CurrentPolicy != null) ? pawn.drugs.CurrentPolicy.uniqueId : (-2147483648); } } } diff --git a/Assembly-CSharp/RimWorld/PawnColumnWorker_FollowDrafted.cs b/Assembly-CSharp/RimWorld/PawnColumnWorker_FollowDrafted.cs index e64a4f344..354bee4f9 100644 --- a/Assembly-CSharp/RimWorld/PawnColumnWorker_FollowDrafted.cs +++ b/Assembly-CSharp/RimWorld/PawnColumnWorker_FollowDrafted.cs @@ -1,4 +1,3 @@ -using System; using Verse; namespace RimWorld diff --git a/Assembly-CSharp/RimWorld/PawnColumnWorker_FollowFieldwork.cs b/Assembly-CSharp/RimWorld/PawnColumnWorker_FollowFieldwork.cs index febcdcdad..c97c13d90 100644 --- a/Assembly-CSharp/RimWorld/PawnColumnWorker_FollowFieldwork.cs +++ b/Assembly-CSharp/RimWorld/PawnColumnWorker_FollowFieldwork.cs @@ -1,4 +1,3 @@ -using System; using Verse; namespace RimWorld diff --git a/Assembly-CSharp/RimWorld/PawnColumnWorker_Gap.cs b/Assembly-CSharp/RimWorld/PawnColumnWorker_Gap.cs index 9b7f42edf..061aee114 100644 --- a/Assembly-CSharp/RimWorld/PawnColumnWorker_Gap.cs +++ b/Assembly-CSharp/RimWorld/PawnColumnWorker_Gap.cs @@ -1,4 +1,3 @@ -using System; using UnityEngine; using Verse; @@ -10,7 +9,7 @@ protected virtual int Width { get { - return this.def.gap; + return base.def.gap; } } diff --git a/Assembly-CSharp/RimWorld/PawnColumnWorker_Gender.cs b/Assembly-CSharp/RimWorld/PawnColumnWorker_Gender.cs index caf014234..fd80d36c7 100644 --- a/Assembly-CSharp/RimWorld/PawnColumnWorker_Gender.cs +++ b/Assembly-CSharp/RimWorld/PawnColumnWorker_Gender.cs @@ -1,4 +1,3 @@ -using System; using UnityEngine; using Verse; diff --git a/Assembly-CSharp/RimWorld/PawnColumnWorker_HostilityResponse.cs b/Assembly-CSharp/RimWorld/PawnColumnWorker_HostilityResponse.cs index 2d5827f10..f74bd5f2f 100644 --- a/Assembly-CSharp/RimWorld/PawnColumnWorker_HostilityResponse.cs +++ b/Assembly-CSharp/RimWorld/PawnColumnWorker_HostilityResponse.cs @@ -1,4 +1,3 @@ -using System; using UnityEngine; using Verse; @@ -12,12 +11,11 @@ public class PawnColumnWorker_HostilityResponse : PawnColumnWorker public override void DoCell(Rect rect, Pawn pawn, PawnTable table) { - if (!pawn.RaceProps.Humanlike) + if (pawn.RaceProps.Humanlike) { - return; + Vector2 pos = new Vector2(rect.x, (float)(rect.y + 3.0)); + HostilityResponseModeUtility.DrawResponseButton(pos, pawn); } - Vector2 pos = new Vector2(rect.x, rect.y + 3f); - HostilityResponseModeUtility.DrawResponseButton(pos, pawn); } public override int GetMinCellHeight(Pawn pawn) diff --git a/Assembly-CSharp/RimWorld/PawnColumnWorker_Icon.cs b/Assembly-CSharp/RimWorld/PawnColumnWorker_Icon.cs index 6e555aae2..e44d701d7 100644 --- a/Assembly-CSharp/RimWorld/PawnColumnWorker_Icon.cs +++ b/Assembly-CSharp/RimWorld/PawnColumnWorker_Icon.cs @@ -1,4 +1,3 @@ -using System; using UnityEngine; using Verse; @@ -17,11 +16,11 @@ protected virtual int Width public override void DoCell(Rect rect, Pawn pawn, PawnTable table) { Texture2D iconFor = this.GetIconFor(pawn); - if (iconFor != null) + if ((Object)iconFor != (Object)null) { Vector2 iconSize = this.GetIconSize(pawn); - int num = (int)((rect.width - iconSize.x) / 2f); - int num2 = Mathf.Max((int)((30f - iconSize.y) / 2f), 0); + int num = (int)((rect.width - iconSize.x) / 2.0); + int num2 = Mathf.Max((int)((30.0 - iconSize.y) / 2.0), 0); Rect rect2 = new Rect(rect.x + (float)num, rect.y + (float)num2, iconSize.x, iconSize.y); GUI.color = this.GetIconColor(pawn); GUI.DrawTexture(rect2, iconFor); @@ -53,7 +52,9 @@ public override int GetMaxWidth(PawnTable table) public override int GetMinCellHeight(Pawn pawn) { - return Mathf.Max(base.GetMinCellHeight(pawn), Mathf.CeilToInt(this.GetIconSize(pawn).y)); + int minCellHeight = base.GetMinCellHeight(pawn); + Vector2 iconSize = this.GetIconSize(pawn); + return Mathf.Max(minCellHeight, Mathf.CeilToInt(iconSize.y)); } public override int Compare(Pawn a, Pawn b) @@ -64,14 +65,14 @@ public override int Compare(Pawn a, Pawn b) private int GetValueToCompare(Pawn pawn) { Texture2D iconFor = this.GetIconFor(pawn); - return (!(iconFor != null)) ? -2147483648 : iconFor.GetInstanceID(); + return (!((Object)iconFor != (Object)null)) ? (-2147483648) : iconFor.GetInstanceID(); } protected abstract Texture2D GetIconFor(Pawn pawn); protected virtual string GetIconTip(Pawn pawn) { - return null; + return (string)null; } protected virtual Color GetIconColor(Pawn pawn) @@ -86,7 +87,7 @@ protected virtual void ClickedIcon(Pawn pawn) protected virtual Vector2 GetIconSize(Pawn pawn) { Texture2D iconFor = this.GetIconFor(pawn); - if (iconFor == null) + if ((Object)iconFor == (Object)null) { return Vector2.zero; } diff --git a/Assembly-CSharp/RimWorld/PawnColumnWorker_Label.cs b/Assembly-CSharp/RimWorld/PawnColumnWorker_Label.cs index 5b83ee5a3..ac2f51cd9 100644 --- a/Assembly-CSharp/RimWorld/PawnColumnWorker_Label.cs +++ b/Assembly-CSharp/RimWorld/PawnColumnWorker_Label.cs @@ -1,4 +1,3 @@ -using System; using System.Collections.Generic; using UnityEngine; using Verse; @@ -16,7 +15,7 @@ public class PawnColumnWorker_Label : PawnColumnWorker public override void DoCell(Rect rect, Pawn pawn, PawnTable table) { Rect rect2 = new Rect(rect.x, rect.y, rect.width, Mathf.Min(rect.height, 30f)); - if (pawn.health.summaryHealth.SummaryHealthPercent < 0.99f) + if (pawn.health.summaryHealth.SummaryHealthPercent < 0.99000000953674316) { Rect rect3 = new Rect(rect2); rect3.xMin -= 4f; @@ -28,15 +27,7 @@ public override void DoCell(Rect rect, Pawn pawn, PawnTable table) { GUI.DrawTexture(rect2, TexUI.HighlightTex); } - string str; - if (!pawn.RaceProps.Humanlike && pawn.Name != null && !pawn.Name.Numerical) - { - str = pawn.Name.ToStringShort.CapitalizeFirst() + ", " + pawn.KindLabel; - } - else - { - str = pawn.LabelCap; - } + string str = (pawn.RaceProps.Humanlike || pawn.Name == null || pawn.Name.Numerical) ? pawn.LabelCap : (pawn.Name.ToStringShort.CapitalizeFirst() + ", " + pawn.KindLabel); Rect rect4 = rect2; rect4.xMin += 3f; if (rect4.width != PawnColumnWorker_Label.labelCacheForWidth) @@ -52,12 +43,14 @@ public override void DoCell(Rect rect, Pawn pawn, PawnTable table) Text.Anchor = TextAnchor.UpperLeft; if (Widgets.ButtonInvisible(rect2, false)) { - CameraJumper.TryJumpAndSelect(pawn); - return; + CameraJumper.TryJumpAndSelect((Thing)pawn); + } + else + { + TipSignal tooltip = pawn.GetTooltip(); + tooltip.text = "ClickToJumpTo".Translate() + "\n\n" + tooltip.text; + TooltipHandler.TipRegion(rect2, tooltip); } - TipSignal tooltip = pawn.GetTooltip(); - tooltip.text = "ClickToJumpTo".Translate() + "\n\n" + tooltip.text; - TooltipHandler.TipRegion(rect2, tooltip); } public override int GetMinWidth(PawnTable table) diff --git a/Assembly-CSharp/RimWorld/PawnColumnWorker_LifeStage.cs b/Assembly-CSharp/RimWorld/PawnColumnWorker_LifeStage.cs index 273471edb..ef2286a5f 100644 --- a/Assembly-CSharp/RimWorld/PawnColumnWorker_LifeStage.cs +++ b/Assembly-CSharp/RimWorld/PawnColumnWorker_LifeStage.cs @@ -1,4 +1,3 @@ -using System; using UnityEngine; using Verse; diff --git a/Assembly-CSharp/RimWorld/PawnColumnWorker_Master.cs b/Assembly-CSharp/RimWorld/PawnColumnWorker_Master.cs index debf1721f..71aa50412 100644 --- a/Assembly-CSharp/RimWorld/PawnColumnWorker_Master.cs +++ b/Assembly-CSharp/RimWorld/PawnColumnWorker_Master.cs @@ -1,4 +1,3 @@ -using System; using UnityEngine; using Verse; @@ -26,15 +25,14 @@ public override int GetOptimalWidth(PawnTable table) public override void DoCell(Rect rect, Pawn pawn, PawnTable table) { - if (!this.CanAssignMaster(pawn)) - { - return; - } - Rect rect2 = rect.ContractedBy(2f); - string label = TrainableUtility.MasterString(pawn).Truncate(rect2.width, null); - if (Widgets.ButtonText(rect2, label, true, false, true)) + if (this.CanAssignMaster(pawn)) { - TrainableUtility.OpenMasterSelectMenu(pawn); + Rect rect2 = rect.ContractedBy(2f); + string label = TrainableUtility.MasterString(pawn).Truncate(rect2.width, null); + if (Widgets.ButtonText(rect2, label, true, false, true)) + { + TrainableUtility.OpenMasterSelectMenu(pawn); + } } } @@ -51,7 +49,15 @@ public override int Compare(Pawn a, Pawn b) private bool CanAssignMaster(Pawn pawn) { - return pawn.RaceProps.Animal && pawn.Faction == Faction.OfPlayer && pawn.training.IsCompleted(TrainableDefOf.Obedience); + if (pawn.RaceProps.Animal && pawn.Faction == Faction.OfPlayer) + { + if (!pawn.training.IsCompleted(TrainableDefOf.Obedience)) + { + return false; + } + return true; + } + return false; } private int GetValueToCompare1(Pawn pawn) diff --git a/Assembly-CSharp/RimWorld/PawnColumnWorker_Outfit.cs b/Assembly-CSharp/RimWorld/PawnColumnWorker_Outfit.cs index 00b12c52a..3b3ab3968 100644 --- a/Assembly-CSharp/RimWorld/PawnColumnWorker_Outfit.cs +++ b/Assembly-CSharp/RimWorld/PawnColumnWorker_Outfit.cs @@ -14,7 +14,7 @@ public class PawnColumnWorker_Outfit : PawnColumnWorker public override void DoHeader(Rect rect, PawnTable table) { base.DoHeader(rect, table); - Rect rect2 = new Rect(rect.x, rect.y + (rect.height - 65f), Mathf.Min(rect.width, 360f), 32f); + Rect rect2 = new Rect(rect.x, (float)(rect.y + (rect.height - 65.0)), Mathf.Min(rect.width, 360f), 32f); if (Widgets.ButtonText(rect2, "ManageOutfits".Translate(), true, false, true)) { Find.WindowStack.Add(new Dialog_ManageOutfits(null)); @@ -25,60 +25,77 @@ public override void DoHeader(Rect rect, PawnTable table) public override void DoCell(Rect rect, Pawn pawn, PawnTable table) { - if (pawn.outfits == null) + if (pawn.outfits != null) { - return; - } - int num = Mathf.FloorToInt((rect.width - 4f) * 0.714285731f); - int num2 = Mathf.FloorToInt((rect.width - 4f) * 0.2857143f); - float num3 = rect.x; - bool somethingIsForced = pawn.outfits.forcedHandler.SomethingIsForced; - Rect rect2 = new Rect(num3, rect.y + 2f, (float)num, rect.height - 4f); - if (somethingIsForced) - { - rect2.width -= 4f + (float)num2; - } - string label = pawn.outfits.CurrentOutfit.label.Truncate(rect2.width, null); - if (Widgets.ButtonText(rect2, label, true, false, true)) - { - List list = new List(); - foreach (Outfit current in Current.Game.outfitDatabase.AllOutfits) + int num = Mathf.FloorToInt((float)((rect.width - 4.0) * 0.71428573131561279)); + int num2 = Mathf.FloorToInt((float)((rect.width - 4.0) * 0.28571429848670959)); + float x = rect.x; + bool somethingIsForced = pawn.outfits.forcedHandler.SomethingIsForced; + Rect rect2 = new Rect(x, (float)(rect.y + 2.0), (float)num, (float)(rect.height - 4.0)); + if (somethingIsForced) { - Outfit localOut = current; - list.Add(new FloatMenuOption(localOut.label, delegate - { - pawn.outfits.CurrentOutfit = localOut; - }, MenuOptionPriority.Default, null, null, 0f, null, null)); + rect2.width -= (float)(4.0 + (float)num2); } - Find.WindowStack.Add(new FloatMenu(list)); - } - num3 += rect2.width; - num3 += 4f; - Rect rect3 = new Rect(num3, rect.y + 2f, (float)num2, rect.height - 4f); - if (somethingIsForced) - { - if (Widgets.ButtonText(rect3, "ClearForcedApparel".Translate(), true, false, true)) + string label = pawn.outfits.CurrentOutfit.label.Truncate(rect2.width, null); + if (Widgets.ButtonText(rect2, label, true, false, true)) { - pawn.outfits.forcedHandler.Reset(); + List list = new List(); + List.Enumerator enumerator = Current.Game.outfitDatabase.AllOutfits.GetEnumerator(); + try + { + while (enumerator.MoveNext()) + { + Outfit current = enumerator.Current; + Outfit localOut = current; + list.Add(new FloatMenuOption(localOut.label, (Action)delegate() + { + pawn.outfits.CurrentOutfit = localOut; + }, MenuOptionPriority.Default, null, null, 0f, null, null)); + } + } + finally + { + ((IDisposable)(object)enumerator).Dispose(); + } + Find.WindowStack.Add(new FloatMenu(list)); } - TooltipHandler.TipRegion(rect3, new TipSignal(delegate + x += rect2.width; + x = (float)(x + 4.0); + Rect rect3 = new Rect(x, (float)(rect.y + 2.0), (float)num2, (float)(rect.height - 4.0)); + if (somethingIsForced) { - string text = "ForcedApparel".Translate() + ":\n"; - foreach (Apparel current2 in pawn.outfits.forcedHandler.ForcedApparel) + if (Widgets.ButtonText(rect3, "ClearForcedApparel".Translate(), true, false, true)) { - text = text + "\n " + current2.LabelCap; + pawn.outfits.forcedHandler.Reset(); } - return text; - }, pawn.GetHashCode() * 612)); - num3 += (float)num2; - num3 += 4f; - } - Rect rect4 = new Rect(num3, rect.y + 2f, (float)num2, rect.height - 4f); - if (Widgets.ButtonText(rect4, "AssignTabEdit".Translate(), true, false, true)) - { - Find.WindowStack.Add(new Dialog_ManageOutfits(pawn.outfits.CurrentOutfit)); + TooltipHandler.TipRegion(rect3, new TipSignal((Func)delegate() + { + string text = "ForcedApparel".Translate() + ":\n"; + List.Enumerator enumerator2 = pawn.outfits.forcedHandler.ForcedApparel.GetEnumerator(); + try + { + while (enumerator2.MoveNext()) + { + Apparel current2 = enumerator2.Current; + text = text + "\n " + current2.LabelCap; + } + return text; + } + finally + { + ((IDisposable)(object)enumerator2).Dispose(); + } + }, pawn.GetHashCode() * 612)); + x += (float)num2; + x = (float)(x + 4.0); + } + Rect rect4 = new Rect(x, (float)(rect.y + 2.0), (float)num2, (float)(rect.height - 4.0)); + if (Widgets.ButtonText(rect4, "AssignTabEdit".Translate(), true, false, true)) + { + Find.WindowStack.Add(new Dialog_ManageOutfits(pawn.outfits.CurrentOutfit)); + } + x += (float)num2; } - num3 += (float)num2; } public override int GetMinWidth(PawnTable table) @@ -103,7 +120,7 @@ public override int Compare(Pawn a, Pawn b) private int GetValueToCompare(Pawn pawn) { - return (pawn.outfits != null && pawn.outfits.CurrentOutfit != null) ? pawn.outfits.CurrentOutfit.uniqueId : -2147483648; + return (pawn.outfits != null && pawn.outfits.CurrentOutfit != null) ? pawn.outfits.CurrentOutfit.uniqueId : (-2147483648); } } } diff --git a/Assembly-CSharp/RimWorld/PawnColumnWorker_Pregnant.cs b/Assembly-CSharp/RimWorld/PawnColumnWorker_Pregnant.cs index 9169dc5e5..67e2e4741 100644 --- a/Assembly-CSharp/RimWorld/PawnColumnWorker_Pregnant.cs +++ b/Assembly-CSharp/RimWorld/PawnColumnWorker_Pregnant.cs @@ -1,4 +1,3 @@ -using System; using UnityEngine; using Verse; @@ -19,13 +18,9 @@ protected override string GetIconTip(Pawn pawn) { Hediff_Pregnant pregnantHediff = this.GetPregnantHediff(pawn); float gestationProgress = pregnantHediff.GestationProgress; - int num = (int)(pawn.RaceProps.gestationPeriodDays * 60000f); + int num = (int)(pawn.RaceProps.gestationPeriodDays * 60000.0); int numTicks = (int)(gestationProgress * (float)num); - return "PregnantIconDesc".Translate(new object[] - { - numTicks.ToStringTicksToDays("F0"), - num.ToStringTicksToDays("F0") - }); + return "PregnantIconDesc".Translate(numTicks.ToStringTicksToDays("F0"), num.ToStringTicksToDays("F0")); } private Hediff_Pregnant GetPregnantHediff(Pawn pawn) diff --git a/Assembly-CSharp/RimWorld/PawnColumnWorker_RemainingSpace.cs b/Assembly-CSharp/RimWorld/PawnColumnWorker_RemainingSpace.cs index 543675bd6..5218a1868 100644 --- a/Assembly-CSharp/RimWorld/PawnColumnWorker_RemainingSpace.cs +++ b/Assembly-CSharp/RimWorld/PawnColumnWorker_RemainingSpace.cs @@ -1,4 +1,3 @@ -using System; using UnityEngine; using Verse; diff --git a/Assembly-CSharp/RimWorld/PawnColumnWorker_Slaughter.cs b/Assembly-CSharp/RimWorld/PawnColumnWorker_Slaughter.cs index ad98aacaa..c2d12cb6d 100644 --- a/Assembly-CSharp/RimWorld/PawnColumnWorker_Slaughter.cs +++ b/Assembly-CSharp/RimWorld/PawnColumnWorker_Slaughter.cs @@ -1,4 +1,3 @@ -using System; using Verse; namespace RimWorld @@ -22,21 +21,20 @@ protected override bool GetValue(Pawn pawn) protected override void SetValue(Pawn pawn, bool value) { - if (value == this.GetValue(pawn)) + if (value != this.GetValue(pawn)) { - return; - } - if (value) - { - pawn.MapHeld.designationManager.AddDesignation(new Designation(pawn, DesignationDefOf.Slaughter)); - SlaughterDesignatorUtility.CheckWarnAboutBondedAnimal(pawn); - } - else - { - Designation slaughterDesignation = this.GetSlaughterDesignation(pawn); - if (slaughterDesignation != null) + if (value) + { + pawn.MapHeld.designationManager.AddDesignation(new Designation((Thing)pawn, DesignationDefOf.Slaughter)); + SlaughterDesignatorUtility.CheckWarnAboutBondedAnimal(pawn); + } + else { - pawn.MapHeld.designationManager.RemoveDesignation(slaughterDesignation); + Designation slaughterDesignation = this.GetSlaughterDesignation(pawn); + if (slaughterDesignation != null) + { + pawn.MapHeld.designationManager.RemoveDesignation(slaughterDesignation); + } } } } diff --git a/Assembly-CSharp/RimWorld/PawnColumnWorker_Timetable.cs b/Assembly-CSharp/RimWorld/PawnColumnWorker_Timetable.cs index 087a0ab2b..36ae15945 100644 --- a/Assembly-CSharp/RimWorld/PawnColumnWorker_Timetable.cs +++ b/Assembly-CSharp/RimWorld/PawnColumnWorker_Timetable.cs @@ -9,19 +9,18 @@ public class PawnColumnWorker_Timetable : PawnColumnWorker { public override void DoCell(Rect rect, Pawn pawn, PawnTable table) { - if (pawn.timetable == null) - { - return; - } - float num = rect.x; - float num2 = rect.width / 24f; - for (int i = 0; i < 24; i++) + if (pawn.timetable != null) { - Rect rect2 = new Rect(num, rect.y, num2, rect.height); - this.DoTimeAssignment(rect2, pawn, i); - num += num2; + float num = rect.x; + float num2 = (float)(rect.width / 24.0); + for (int i = 0; i < 24; i++) + { + Rect rect2 = new Rect(num, rect.y, num2, rect.height); + this.DoTimeAssignment(rect2, pawn, i); + num += num2; + } + GUI.color = Color.white; } - GUI.color = Color.white; } public override void DoHeader(Rect rect, PawnTable table) @@ -29,10 +28,10 @@ public override void DoHeader(Rect rect, PawnTable table) float num = rect.x; Text.Font = GameFont.Tiny; Text.Anchor = TextAnchor.LowerCenter; - float num2 = rect.width / 24f; + float num2 = (float)(rect.width / 24.0); for (int i = 0; i < 24; i++) { - Rect rect2 = new Rect(num, rect.y, num2, rect.height + 3f); + Rect rect2 = new Rect(num, rect.y, num2, (float)(rect.height + 3.0)); Widgets.Label(rect2, i.ToString()); num += num2; } @@ -71,7 +70,7 @@ private int GetValueToCompare(Pawn pawn) { return -2147483648; } - return pawn.timetable.times.FirstIndexOf((TimeAssignmentDef x) => x == TimeAssignmentDefOf.Work); + return pawn.timetable.times.FirstIndexOf((Func)((TimeAssignmentDef x) => x == TimeAssignmentDefOf.Work)); } private void DoTimeAssignment(Rect rect, Pawn p, int hour) diff --git a/Assembly-CSharp/RimWorld/PawnColumnWorker_Trainable.cs b/Assembly-CSharp/RimWorld/PawnColumnWorker_Trainable.cs index 45a494885..0053c557f 100644 --- a/Assembly-CSharp/RimWorld/PawnColumnWorker_Trainable.cs +++ b/Assembly-CSharp/RimWorld/PawnColumnWorker_Trainable.cs @@ -1,4 +1,3 @@ -using System; using System.Collections.Generic; using UnityEngine; using Verse; @@ -10,20 +9,18 @@ public class PawnColumnWorker_Trainable : PawnColumnWorker { public override void DoCell(Rect rect, Pawn pawn, PawnTable table) { - if (pawn.training == null) - { - return; - } - bool flag; - AcceptanceReport canTrain = pawn.training.CanAssignToTrain(this.def.trainable, out flag); - if (!flag || !canTrain.Accepted) + if (pawn.training != null) { - return; + bool flag = default(bool); + AcceptanceReport canTrain = pawn.training.CanAssignToTrain(base.def.trainable, out flag); + if (flag && canTrain.Accepted) + { + int num = (int)((rect.width - 24.0) / 2.0); + int num2 = Mathf.Max(3, 0); + Rect rect2 = new Rect(rect.x + (float)num, rect.y + (float)num2, 24f, 24f); + TrainingCardUtility.DoTrainableCheckbox(rect2, pawn, base.def.trainable, canTrain, false, true); + } } - int num = (int)((rect.width - 24f) / 2f); - int num2 = Mathf.Max(3, 0); - Rect rect2 = new Rect(rect.x + (float)num, rect.y + (float)num2, 24f, 24f); - TrainingCardUtility.DoTrainableCheckbox(rect2, pawn, this.def.trainable, canTrain, false, true); } public override int GetMinWidth(PawnTable table) @@ -52,12 +49,12 @@ private int GetValueToCompare(Pawn pawn) { return -2147483648; } - if (pawn.training.IsCompleted(this.def.trainable)) + if (pawn.training.IsCompleted(base.def.trainable)) { return 4; } - bool flag; - AcceptanceReport acceptanceReport = pawn.training.CanAssignToTrain(this.def.trainable, out flag); + bool flag = default(bool); + AcceptanceReport acceptanceReport = pawn.training.CanAssignToTrain(base.def.trainable, out flag); if (!flag) { return 0; @@ -66,7 +63,7 @@ private int GetValueToCompare(Pawn pawn) { return 1; } - if (!pawn.training.GetWanted(this.def.trainable)) + if (!pawn.training.GetWanted(base.def.trainable)) { return 2; } @@ -81,23 +78,23 @@ protected override void HeaderClicked(Rect headerRect, PawnTable table) List pawnsListForReading = table.PawnsListForReading; for (int i = 0; i < pawnsListForReading.Count; i++) { - if (pawnsListForReading[i].training != null && !pawnsListForReading[i].training.IsCompleted(this.def.trainable)) + if (pawnsListForReading[i].training != null && !pawnsListForReading[i].training.IsCompleted(base.def.trainable)) { - bool flag; - AcceptanceReport acceptanceReport = pawnsListForReading[i].training.CanAssignToTrain(this.def.trainable, out flag); + bool flag = default(bool); + AcceptanceReport acceptanceReport = pawnsListForReading[i].training.CanAssignToTrain(base.def.trainable, out flag); if (flag && acceptanceReport.Accepted) { - bool wanted = pawnsListForReading[i].training.GetWanted(this.def.trainable); + bool wanted = pawnsListForReading[i].training.GetWanted(base.def.trainable); if (Event.current.button == 0) { if (!wanted) { - pawnsListForReading[i].training.SetWantedRecursive(this.def.trainable, true); + pawnsListForReading[i].training.SetWantedRecursive(base.def.trainable, true); } } else if (Event.current.button == 1 && wanted) { - pawnsListForReading[i].training.SetWantedRecursive(this.def.trainable, false); + pawnsListForReading[i].training.SetWantedRecursive(base.def.trainable, false); } } } diff --git a/Assembly-CSharp/RimWorld/PawnColumnWorker_WorkPriority.cs b/Assembly-CSharp/RimWorld/PawnColumnWorker_WorkPriority.cs index a692ddc2f..2937d7b04 100644 --- a/Assembly-CSharp/RimWorld/PawnColumnWorker_WorkPriority.cs +++ b/Assembly-CSharp/RimWorld/PawnColumnWorker_WorkPriority.cs @@ -15,18 +15,17 @@ public class PawnColumnWorker_WorkPriority : PawnColumnWorker public override void DoCell(Rect rect, Pawn pawn, PawnTable table) { - if (pawn.Dead || pawn.workSettings == null || !pawn.workSettings.EverWork) + if (!pawn.Dead && pawn.workSettings != null && pawn.workSettings.EverWork) { - return; + Text.Font = GameFont.Medium; + float x = (float)(rect.x + (rect.width - 25.0) / 2.0); + float y = (float)(rect.y + 2.5); + bool incapable = this.IsIncapableOfWholeWorkType(pawn, base.def.workType); + WidgetsWork.DrawWorkBoxFor(x, y, pawn, base.def.workType, incapable); + Rect rect2 = new Rect(x, y, 25f, 25f); + TooltipHandler.TipRegion(rect2, (Func)(() => WidgetsWork.TipForPawnWorker(pawn, base.def.workType, incapable)), pawn.thingIDNumber ^ base.def.workType.GetHashCode()); + Text.Font = GameFont.Small; } - Text.Font = GameFont.Medium; - float x = rect.x + (rect.width - 25f) / 2f; - float y = rect.y + 2.5f; - bool incapable = this.IsIncapableOfWholeWorkType(pawn, this.def.workType); - WidgetsWork.DrawWorkBoxFor(x, y, pawn, this.def.workType, incapable); - Rect rect2 = new Rect(x, y, 25f, 25f); - TooltipHandler.TipRegion(rect2, () => WidgetsWork.TipForPawnWorker(pawn, this.def.workType, incapable), pawn.thingIDNumber ^ this.def.workType.GetHashCode()); - Text.Font = GameFont.Small; } public override void DoHeader(Rect rect, PawnTable table) @@ -35,14 +34,16 @@ public override void DoHeader(Rect rect, PawnTable table) Text.Font = GameFont.Small; if (this.cachedWorkLabelSize == default(Vector2)) { - this.cachedWorkLabelSize = Text.CalcSize(this.def.workType.labelShort); + this.cachedWorkLabelSize = Text.CalcSize(base.def.workType.labelShort); } Rect labelRect = this.GetLabelRect(rect); Text.Anchor = TextAnchor.MiddleCenter; - Widgets.Label(labelRect, this.def.workType.labelShort); + Widgets.Label(labelRect, base.def.workType.labelShort); GUI.color = new Color(1f, 1f, 1f, 0.3f); - Widgets.DrawLineVertical(labelRect.center.x, labelRect.yMax - 3f, rect.y + 50f - labelRect.yMax + 3f); - Widgets.DrawLineVertical(labelRect.center.x + 1f, labelRect.yMax - 3f, rect.y + 50f - labelRect.yMax + 3f); + Vector2 center = labelRect.center; + Widgets.DrawLineVertical(center.x, (float)(labelRect.yMax - 3.0), (float)(rect.y + 50.0 - labelRect.yMax + 3.0)); + Vector2 center2 = labelRect.center; + Widgets.DrawLineVertical((float)(center2.x + 1.0), (float)(labelRect.yMax - 3.0), (float)(rect.y + 50.0 - labelRect.yMax + 3.0)); GUI.color = Color.white; Text.Anchor = TextAnchor.UpperLeft; } @@ -101,22 +102,23 @@ public override int Compare(Pawn a, Pawn b) private float GetValueToCompare(Pawn pawn) { - if (pawn.workSettings == null || !pawn.workSettings.EverWork) - { - return -2f; - } - if (pawn.story != null && pawn.story.WorkTypeIsDisabled(this.def.workType)) + if (pawn.workSettings != null && pawn.workSettings.EverWork) { - return -1f; + if (pawn.story != null && pawn.story.WorkTypeIsDisabled(base.def.workType)) + { + return -1f; + } + return pawn.skills.AverageOfRelevantSkillsFor(base.def.workType); } - return pawn.skills.AverageOfRelevantSkillsFor(this.def.workType); + return -2f; } private Rect GetLabelRect(Rect headerRect) { - float x = headerRect.center.x; - Rect result = new Rect(x - this.cachedWorkLabelSize.x / 2f, headerRect.y, this.cachedWorkLabelSize.x, this.cachedWorkLabelSize.y); - if (this.def.moveWorkTypeLabelDown) + Vector2 center = headerRect.center; + float x = center.x; + Rect result = new Rect((float)(x - this.cachedWorkLabelSize.x / 2.0), headerRect.y, this.cachedWorkLabelSize.x, this.cachedWorkLabelSize.y); + if (base.def.moveWorkTypeLabelDown) { result.y += 20f; } @@ -125,28 +127,13 @@ private Rect GetLabelRect(Rect headerRect) protected override string GetHeaderTip(PawnTable table) { - string text = string.Concat(new string[] - { - this.def.workType.gerundLabel, - "\n\n", - this.def.workType.description, - "\n\n", - PawnColumnWorker_WorkPriority.SpecificWorkListString(this.def.workType) - }); - text += "\n"; - if (this.def.sortable) - { - text = text + "\n" + "ClickToSortByThisColumn".Translate(); - } - if (Find.PlaySettings.useWorkPriorities) + string str = base.def.workType.gerundLabel + "\n\n" + base.def.workType.description + "\n\n" + PawnColumnWorker_WorkPriority.SpecificWorkListString(base.def.workType); + str += "\n"; + if (base.def.sortable) { - text = text + "\n" + "WorkPriorityShiftClickTip".Translate(); + str = str + "\n" + "ClickToSortByThisColumn".Translate(); } - else - { - text = text + "\n" + "WorkPriorityShiftClickEnableDisableTip".Translate(); - } - return text; + return (!Find.PlaySettings.useWorkPriorities) ? (str + "\n" + "WorkPriorityShiftClickEnableDisableTip".Translate()) : (str + "\n" + "WorkPriorityShiftClickTip".Translate()); } private static string SpecificWorkListString(WorkTypeDef def) @@ -176,44 +163,41 @@ protected override void HeaderClicked(Rect headerRect, PawnTable table) for (int i = 0; i < pawnsListForReading.Count; i++) { Pawn pawn = pawnsListForReading[i]; - if (pawn.workSettings != null && pawn.workSettings.EverWork) + if (pawn.workSettings != null && pawn.workSettings.EverWork && (pawn.story == null || !pawn.story.WorkTypeIsDisabled(base.def.workType))) { - if (pawn.story == null || !pawn.story.WorkTypeIsDisabled(this.def.workType)) + if (Find.PlaySettings.useWorkPriorities) { - if (Find.PlaySettings.useWorkPriorities) + int priority = pawn.workSettings.GetPriority(base.def.workType); + if (Event.current.button == 0 && priority != 1) { - int priority = pawn.workSettings.GetPriority(this.def.workType); - if (Event.current.button == 0 && priority != 1) - { - int num = priority - 1; - if (num < 0) - { - num = 4; - } - pawn.workSettings.SetPriority(this.def.workType, num); - } - if (Event.current.button == 1 && priority != 0) + int num = priority - 1; + if (num < 0) { - int num2 = priority + 1; - if (num2 > 4) - { - num2 = 0; - } - pawn.workSettings.SetPriority(this.def.workType, num2); + num = 4; } + pawn.workSettings.SetPriority(base.def.workType, num); } - else if (pawn.workSettings.GetPriority(this.def.workType) > 0) + if (((Event.current.button == 1) ? priority : 0) != 0) { - if (Event.current.button == 1) + int num2 = priority + 1; + if (num2 > 4) { - pawn.workSettings.SetPriority(this.def.workType, 0); + num2 = 0; } + pawn.workSettings.SetPriority(base.def.workType, num2); } - else if (Event.current.button == 0) + } + else if (pawn.workSettings.GetPriority(base.def.workType) > 0) + { + if (Event.current.button == 1) { - pawn.workSettings.SetPriority(this.def.workType, 3); + pawn.workSettings.SetPriority(base.def.workType, 0); } } + else if (Event.current.button == 0) + { + pawn.workSettings.SetPriority(base.def.workType, 3); + } } } if (Find.PlaySettings.useWorkPriorities) diff --git a/Assembly-CSharp/RimWorld/PawnComponentsUtility.cs b/Assembly-CSharp/RimWorld/PawnComponentsUtility.cs index 4a1ae0443..4b0068dfb 100644 --- a/Assembly-CSharp/RimWorld/PawnComponentsUtility.cs +++ b/Assembly-CSharp/RimWorld/PawnComponentsUtility.cs @@ -1,4 +1,3 @@ -using System; using Verse; using Verse.AI; @@ -64,7 +63,7 @@ public static void AddComponentsForSpawn(Pawn pawn) { pawn.filth = new Pawn_FilthTracker(pawn); } - if (pawn.RaceProps.intelligence <= Intelligence.ToolUser && pawn.caller == null) + if ((int)pawn.RaceProps.intelligence <= 1 && pawn.caller == null) { pawn.caller = new Pawn_CallTracker(pawn); } @@ -141,14 +140,11 @@ public static void AddAndRemoveDynamicComponents(Pawn pawn, bool actAsIfSpawned pawn.drafter = null; } } - if (flag || flag2) + if ((flag || flag2) && pawn.playerSettings == null) { - if (pawn.playerSettings == null) - { - pawn.playerSettings = new Pawn_PlayerSettings(pawn); - } + pawn.playerSettings = new Pawn_PlayerSettings(pawn); } - if (pawn.RaceProps.intelligence <= Intelligence.ToolUser && pawn.Faction != null && !pawn.RaceProps.IsMechanoid && pawn.training == null) + if ((int)pawn.RaceProps.intelligence <= 1 && pawn.Faction != null && !pawn.RaceProps.IsMechanoid && pawn.training == null) { pawn.training = new Pawn_TrainingTracker(pawn); } diff --git a/Assembly-CSharp/RimWorld/PawnDiedOrDownedThoughtsKind.cs b/Assembly-CSharp/RimWorld/PawnDiedOrDownedThoughtsKind.cs index 405b860f6..35e6df70a 100644 --- a/Assembly-CSharp/RimWorld/PawnDiedOrDownedThoughtsKind.cs +++ b/Assembly-CSharp/RimWorld/PawnDiedOrDownedThoughtsKind.cs @@ -1,12 +1,10 @@ -using System; - namespace RimWorld { public enum PawnDiedOrDownedThoughtsKind { - Died, - Abandoned, - AbandonedToDie, - Downed + Died = 0, + Abandoned = 1, + AbandonedToDie = 2, + Downed = 3 } } diff --git a/Assembly-CSharp/RimWorld/PawnDiedOrDownedThoughtsUtility.cs b/Assembly-CSharp/RimWorld/PawnDiedOrDownedThoughtsUtility.cs index 44e2230b4..33cc56c3f 100644 --- a/Assembly-CSharp/RimWorld/PawnDiedOrDownedThoughtsUtility.cs +++ b/Assembly-CSharp/RimWorld/PawnDiedOrDownedThoughtsUtility.cs @@ -19,29 +19,26 @@ public static void TryGiveThoughts(Pawn victim, DamageInfo? dinfo, PawnDiedOrDow { try { - if (!PawnGenerator.IsBeingGenerated(victim)) + if (!PawnGenerator.IsBeingGenerated(victim) && Current.ProgramState == ProgramState.Playing) { - if (Current.ProgramState == ProgramState.Playing) + PawnDiedOrDownedThoughtsUtility.GetThoughts(victim, dinfo, thoughtsKind, PawnDiedOrDownedThoughtsUtility.tmpIndividualThoughtsToAdd, PawnDiedOrDownedThoughtsUtility.tmpAllColonistsThoughts); + for (int i = 0; i < PawnDiedOrDownedThoughtsUtility.tmpIndividualThoughtsToAdd.Count; i++) { - PawnDiedOrDownedThoughtsUtility.GetThoughts(victim, dinfo, thoughtsKind, PawnDiedOrDownedThoughtsUtility.tmpIndividualThoughtsToAdd, PawnDiedOrDownedThoughtsUtility.tmpAllColonistsThoughts); - for (int i = 0; i < PawnDiedOrDownedThoughtsUtility.tmpIndividualThoughtsToAdd.Count; i++) - { - PawnDiedOrDownedThoughtsUtility.tmpIndividualThoughtsToAdd[i].Add(); - } - if (PawnDiedOrDownedThoughtsUtility.tmpAllColonistsThoughts.Any()) + PawnDiedOrDownedThoughtsUtility.tmpIndividualThoughtsToAdd[i].Add(); + } + if (PawnDiedOrDownedThoughtsUtility.tmpAllColonistsThoughts.Any()) + { + foreach (Pawn allMapsCaravansAndTravelingTransportPods_Colonist in PawnsFinder.AllMapsCaravansAndTravelingTransportPods_Colonists) { - foreach (Pawn current in PawnsFinder.AllMapsCaravansAndTravelingTransportPods_Colonists) + for (int j = 0; j < PawnDiedOrDownedThoughtsUtility.tmpAllColonistsThoughts.Count; j++) { - for (int j = 0; j < PawnDiedOrDownedThoughtsUtility.tmpAllColonistsThoughts.Count; j++) - { - ThoughtDef def = PawnDiedOrDownedThoughtsUtility.tmpAllColonistsThoughts[j]; - current.needs.mood.thoughts.memories.TryGainMemory(def, null); - } + ThoughtDef def = PawnDiedOrDownedThoughtsUtility.tmpAllColonistsThoughts[j]; + allMapsCaravansAndTravelingTransportPods_Colonist.needs.mood.thoughts.memories.TryGainMemory(def, null); } } - PawnDiedOrDownedThoughtsUtility.tmpIndividualThoughtsToAdd.Clear(); - PawnDiedOrDownedThoughtsUtility.tmpAllColonistsThoughts.Clear(); } + PawnDiedOrDownedThoughtsUtility.tmpIndividualThoughtsToAdd.Clear(); + PawnDiedOrDownedThoughtsUtility.tmpAllColonistsThoughts.Clear(); } } catch (Exception arg) @@ -52,9 +49,9 @@ public static void TryGiveThoughts(Pawn victim, DamageInfo? dinfo, PawnDiedOrDow public static void TryGiveThoughts(IEnumerable victims, PawnDiedOrDownedThoughtsKind thoughtsKind) { - foreach (Pawn current in victims) + foreach (Pawn item in victims) { - PawnDiedOrDownedThoughtsUtility.TryGiveThoughts(current, null, thoughtsKind); + PawnDiedOrDownedThoughtsUtility.TryGiveThoughts(item, default(DamageInfo?), thoughtsKind); } } @@ -75,7 +72,7 @@ public static void GetThoughts(Pawn victim, DamageInfo? dinfo, PawnDiedOrDownedT public static void BuildMoodThoughtsListString(Pawn victim, DamageInfo? dinfo, PawnDiedOrDownedThoughtsKind thoughtsKind, StringBuilder sb, string individualThoughtsHeader, string allColonistsThoughtsHeader) { PawnDiedOrDownedThoughtsUtility.GetThoughts(victim, dinfo, thoughtsKind, PawnDiedOrDownedThoughtsUtility.tmpIndividualThoughtsToAdd, PawnDiedOrDownedThoughtsUtility.tmpAllColonistsThoughts); - if (PawnDiedOrDownedThoughtsUtility.tmpAllColonistsThoughts.Any()) + if (PawnDiedOrDownedThoughtsUtility.tmpAllColonistsThoughts.Any()) { if (!allColonistsThoughtsHeader.NullOrEmpty()) { @@ -92,14 +89,14 @@ public static void BuildMoodThoughtsListString(Pawn victim, DamageInfo? dinfo, P sb.Append(" - " + thoughtDef.stages[0].label.CapitalizeFirst() + " " + Mathf.RoundToInt(thoughtDef.stages[0].baseMoodEffect).ToStringWithSign()); } } - if (PawnDiedOrDownedThoughtsUtility.tmpIndividualThoughtsToAdd.Any((IndividualThoughtToAdd x) => x.thought.MoodOffset() != 0f)) + if (PawnDiedOrDownedThoughtsUtility.tmpIndividualThoughtsToAdd.Any((Predicate)((IndividualThoughtToAdd x) => x.thought.MoodOffset() != 0.0))) { if (!individualThoughtsHeader.NullOrEmpty()) { sb.Append(individualThoughtsHeader); } - foreach (IGrouping current in from x in PawnDiedOrDownedThoughtsUtility.tmpIndividualThoughtsToAdd - where x.thought.MoodOffset() != 0f + foreach (IGrouping item in from x in PawnDiedOrDownedThoughtsUtility.tmpIndividualThoughtsToAdd + where x.thought.MoodOffset() != 0.0 group x by x.addTo) { if (sb.Length > 0) @@ -107,13 +104,13 @@ where x.thought.MoodOffset() != 0f sb.AppendLine(); sb.AppendLine(); } - string value = current.Key.KindLabel.CapitalizeFirst() + " " + current.Key.LabelShort; + string value = item.Key.KindLabel.CapitalizeFirst() + " " + item.Key.LabelShort; sb.Append(value); sb.Append(":"); - foreach (IndividualThoughtToAdd current2 in current) + foreach (IndividualThoughtToAdd item2 in item) { sb.AppendLine(); - sb.Append(" " + current2.LabelCap); + sb.Append(" " + item2.LabelCap); } } } @@ -121,29 +118,26 @@ where x.thought.MoodOffset() != 0f public static void BuildMoodThoughtsListString(IEnumerable victims, PawnDiedOrDownedThoughtsKind thoughtsKind, StringBuilder sb, string individualThoughtsHeader, string allColonistsThoughtsHeader, string victimLabelKey) { - foreach (Pawn current in victims) + foreach (Pawn item in victims) { - PawnDiedOrDownedThoughtsUtility.GetThoughts(current, null, thoughtsKind, PawnDiedOrDownedThoughtsUtility.tmpIndividualThoughtsToAdd, PawnDiedOrDownedThoughtsUtility.tmpAllColonistsThoughts); - if (PawnDiedOrDownedThoughtsUtility.tmpIndividualThoughtsToAdd.Any() || PawnDiedOrDownedThoughtsUtility.tmpAllColonistsThoughts.Any()) + PawnDiedOrDownedThoughtsUtility.GetThoughts(item, default(DamageInfo?), thoughtsKind, PawnDiedOrDownedThoughtsUtility.tmpIndividualThoughtsToAdd, PawnDiedOrDownedThoughtsUtility.tmpAllColonistsThoughts); + if (PawnDiedOrDownedThoughtsUtility.tmpIndividualThoughtsToAdd.Any() || PawnDiedOrDownedThoughtsUtility.tmpAllColonistsThoughts.Any()) { if (sb.Length > 0) { sb.AppendLine(); sb.AppendLine(); } - string text = current.KindLabel.CapitalizeFirst() + " " + current.LabelShort; + string text = item.KindLabel.CapitalizeFirst() + " " + item.LabelShort; if (victimLabelKey.NullOrEmpty()) { sb.Append(text + ":"); } else { - sb.Append(victimLabelKey.Translate(new object[] - { - text - })); + sb.Append(victimLabelKey.Translate(text)); } - PawnDiedOrDownedThoughtsUtility.BuildMoodThoughtsListString(current, null, thoughtsKind, sb, individualThoughtsHeader, allColonistsThoughtsHeader); + PawnDiedOrDownedThoughtsUtility.BuildMoodThoughtsListString(item, default(DamageInfo?), thoughtsKind, sb, individualThoughtsHeader, allColonistsThoughtsHeader); } } } @@ -152,8 +146,7 @@ private static void AppendThoughts_ForHumanlike(Pawn victim, DamageInfo? dinfo, { bool flag = dinfo.HasValue && dinfo.Value.Def.execution; bool flag2 = victim.IsPrisonerOfColony && !victim.guilt.IsGuilty && !victim.InAggroMentalState; - bool flag3 = dinfo.HasValue && dinfo.Value.Def.externalViolence && dinfo.Value.Instigator != null && dinfo.Value.Instigator is Pawn; - if (flag3) + if (dinfo.HasValue && dinfo.Value.Def.externalViolence && dinfo.Value.Instigator != null && dinfo.Value.Instigator is Pawn) { Pawn pawn = (Pawn)dinfo.Value.Instigator; if (!pawn.Dead && pawn.needs.mood != null && pawn.story != null && pawn != victim) @@ -168,7 +161,7 @@ private static void AppendThoughts_ForHumanlike(Pawn victim, DamageInfo? dinfo, { outIndividualThoughts.Add(new IndividualThoughtToAdd(ThoughtDefOf.DefeatedHostileFactionLeader, pawn, victim, 1f, 1f)); } - if (victim.kindDef.combatPower > 250f) + if (victim.kindDef.combatPower > 250.0) { outIndividualThoughts.Add(new IndividualThoughtToAdd(ThoughtDefOf.DefeatedMajorEnemy, pawn, victim, 1f, 1f)); } @@ -177,36 +170,33 @@ private static void AppendThoughts_ForHumanlike(Pawn victim, DamageInfo? dinfo, } if (thoughtsKind == PawnDiedOrDownedThoughtsKind.Died && !flag) { - foreach (Pawn current in PawnsFinder.AllMapsCaravansAndTravelingTransportPods) + foreach (Pawn allMapsCaravansAndTravelingTransportPod in PawnsFinder.AllMapsCaravansAndTravelingTransportPods) { - if (current != victim && current.needs.mood != null) + if (allMapsCaravansAndTravelingTransportPod != victim && allMapsCaravansAndTravelingTransportPod.needs.mood != null && (allMapsCaravansAndTravelingTransportPod.MentalStateDef != MentalStateDefOf.SocialFighting || ((MentalState_SocialFighting)allMapsCaravansAndTravelingTransportPod.MentalState).otherPawn != victim)) { - if (current.MentalStateDef != MentalStateDefOf.SocialFighting || ((MentalState_SocialFighting)current.MentalState).otherPawn != victim) + if (PawnDiedOrDownedThoughtsUtility.Witnessed(allMapsCaravansAndTravelingTransportPod, victim)) { - if (PawnDiedOrDownedThoughtsUtility.Witnessed(current, victim)) + if (allMapsCaravansAndTravelingTransportPod.Faction == victim.Faction) { - if (current.Faction == victim.Faction) - { - outIndividualThoughts.Add(new IndividualThoughtToAdd(ThoughtDefOf.WitnessedDeathAlly, current, null, 1f, 1f)); - } - else if (victim.Faction == null || !victim.Faction.HostileTo(current.Faction)) - { - outIndividualThoughts.Add(new IndividualThoughtToAdd(ThoughtDefOf.WitnessedDeathNonAlly, current, null, 1f, 1f)); - } - if (current.relations.FamilyByBlood.Contains(victim)) - { - outIndividualThoughts.Add(new IndividualThoughtToAdd(ThoughtDefOf.WitnessedDeathFamily, current, null, 1f, 1f)); - } - outIndividualThoughts.Add(new IndividualThoughtToAdd(ThoughtDefOf.WitnessedDeathBloodlust, current, null, 1f, 1f)); + outIndividualThoughts.Add(new IndividualThoughtToAdd(ThoughtDefOf.WitnessedDeathAlly, allMapsCaravansAndTravelingTransportPod, null, 1f, 1f)); } - else if (victim.Faction == Faction.OfPlayer && victim.Faction == current.Faction && victim.HostFaction != current.Faction) + else if (victim.Faction == null || !victim.Faction.HostileTo(allMapsCaravansAndTravelingTransportPod.Faction)) { - outIndividualThoughts.Add(new IndividualThoughtToAdd(ThoughtDefOf.KnowColonistDied, current, null, 1f, 1f)); + outIndividualThoughts.Add(new IndividualThoughtToAdd(ThoughtDefOf.WitnessedDeathNonAlly, allMapsCaravansAndTravelingTransportPod, null, 1f, 1f)); } - if (flag2 && current.Faction == Faction.OfPlayer && !current.IsPrisoner) + if (allMapsCaravansAndTravelingTransportPod.relations.FamilyByBlood.Contains(victim)) { - outIndividualThoughts.Add(new IndividualThoughtToAdd(ThoughtDefOf.KnowPrisonerDiedInnocent, current, null, 1f, 1f)); + outIndividualThoughts.Add(new IndividualThoughtToAdd(ThoughtDefOf.WitnessedDeathFamily, allMapsCaravansAndTravelingTransportPod, null, 1f, 1f)); } + outIndividualThoughts.Add(new IndividualThoughtToAdd(ThoughtDefOf.WitnessedDeathBloodlust, allMapsCaravansAndTravelingTransportPod, null, 1f, 1f)); + } + else if (victim.Faction == Faction.OfPlayer && victim.Faction == allMapsCaravansAndTravelingTransportPod.Faction && victim.HostFaction != allMapsCaravansAndTravelingTransportPod.Faction) + { + outIndividualThoughts.Add(new IndividualThoughtToAdd(ThoughtDefOf.KnowColonistDied, allMapsCaravansAndTravelingTransportPod, null, 1f, 1f)); + } + if (flag2 && allMapsCaravansAndTravelingTransportPod.Faction == Faction.OfPlayer && !allMapsCaravansAndTravelingTransportPod.IsPrisoner) + { + outIndividualThoughts.Add(new IndividualThoughtToAdd(ThoughtDefOf.KnowPrisonerDiedInnocent, allMapsCaravansAndTravelingTransportPod, null, 1f, 1f)); } } } @@ -235,92 +225,79 @@ private static void AppendThoughts_Relations(Pawn victim, DamageInfo? dinfo, Paw List directRelations = victim.relations.DirectRelations; for (int i = 0; i < directRelations.Count; i++) { - if (!directRelations[i].otherPawn.Dead && directRelations[i].otherPawn.needs.mood != null) + if (!directRelations[i].otherPawn.Dead && directRelations[i].otherPawn.needs.mood != null && PawnUtility.ShouldGetThoughtAbout(directRelations[i].otherPawn, victim) && directRelations[i].def == PawnRelationDefOf.Bond) { - if (PawnUtility.ShouldGetThoughtAbout(directRelations[i].otherPawn, victim)) - { - if (directRelations[i].def == PawnRelationDefOf.Bond) - { - outIndividualThoughts.Add(new IndividualThoughtToAdd(ThoughtDefOf.BondedAnimalAbandoned, directRelations[i].otherPawn, victim, 1f, 1f)); - } - } + outIndividualThoughts.Add(new IndividualThoughtToAdd(ThoughtDefOf.BondedAnimalAbandoned, directRelations[i].otherPawn, victim, 1f, 1f)); } } } - if (thoughtsKind == PawnDiedOrDownedThoughtsKind.Died || thoughtsKind == PawnDiedOrDownedThoughtsKind.AbandonedToDie) + if (thoughtsKind != 0 && thoughtsKind != PawnDiedOrDownedThoughtsKind.AbandonedToDie) + return; + foreach (Pawn potentiallyRelatedPawn in victim.relations.PotentiallyRelatedPawns) { - foreach (Pawn current in victim.relations.PotentiallyRelatedPawns) + if (!potentiallyRelatedPawn.Dead && potentiallyRelatedPawn.needs.mood != null && PawnUtility.ShouldGetThoughtAbout(potentiallyRelatedPawn, victim)) { - if (!current.Dead && current.needs.mood != null) + PawnRelationDef mostImportantRelation = potentiallyRelatedPawn.GetMostImportantRelation(victim); + if (mostImportantRelation != null) { - if (PawnUtility.ShouldGetThoughtAbout(current, victim)) + ThoughtDef genderSpecificDiedThought = mostImportantRelation.GetGenderSpecificDiedThought(victim); + if (genderSpecificDiedThought != null) { - PawnRelationDef mostImportantRelation = current.GetMostImportantRelation(victim); - if (mostImportantRelation != null) - { - ThoughtDef genderSpecificDiedThought = mostImportantRelation.GetGenderSpecificDiedThought(victim); - if (genderSpecificDiedThought != null) - { - outIndividualThoughts.Add(new IndividualThoughtToAdd(genderSpecificDiedThought, current, victim, 1f, 1f)); - } - } + outIndividualThoughts.Add(new IndividualThoughtToAdd(genderSpecificDiedThought, potentiallyRelatedPawn, victim, 1f, 1f)); } } } - if (dinfo.HasValue) + } + if (dinfo.HasValue) + { + Pawn pawn = dinfo.Value.Instigator as Pawn; + if (pawn != null && pawn != victim) { - Pawn pawn = dinfo.Value.Instigator as Pawn; - if (pawn != null && pawn != victim) + foreach (Pawn potentiallyRelatedPawn2 in victim.relations.PotentiallyRelatedPawns) { - foreach (Pawn current2 in victim.relations.PotentiallyRelatedPawns) + if (pawn != potentiallyRelatedPawn2 && !potentiallyRelatedPawn2.Dead && potentiallyRelatedPawn2.needs.mood != null) { - if (pawn != current2 && !current2.Dead && current2.needs.mood != null) + PawnRelationDef mostImportantRelation2 = potentiallyRelatedPawn2.GetMostImportantRelation(victim); + if (mostImportantRelation2 != null) { - PawnRelationDef mostImportantRelation2 = current2.GetMostImportantRelation(victim); - if (mostImportantRelation2 != null) + ThoughtDef genderSpecificKilledThought = mostImportantRelation2.GetGenderSpecificKilledThought(victim); + if (genderSpecificKilledThought != null) { - ThoughtDef genderSpecificKilledThought = mostImportantRelation2.GetGenderSpecificKilledThought(victim); - if (genderSpecificKilledThought != null) - { - outIndividualThoughts.Add(new IndividualThoughtToAdd(genderSpecificKilledThought, current2, pawn, 1f, 1f)); - } + outIndividualThoughts.Add(new IndividualThoughtToAdd(genderSpecificKilledThought, potentiallyRelatedPawn2, pawn, 1f, 1f)); } - if (current2.RaceProps.IsFlesh) + } + if (potentiallyRelatedPawn2.RaceProps.IsFlesh) + { + int num = potentiallyRelatedPawn2.relations.OpinionOf(victim); + if (num >= 20) { - int num = current2.relations.OpinionOf(victim); - if (num >= 20) - { - float opinionOffsetFactor = victim.relations.GetFriendDiedThoughtPowerFactor(num); - outIndividualThoughts.Add(new IndividualThoughtToAdd(ThoughtDefOf.KilledMyFriend, current2, pawn, 1f, opinionOffsetFactor)); - } - else if (num <= -20) - { - float opinionOffsetFactor = victim.relations.GetRivalDiedThoughtPowerFactor(num); - outIndividualThoughts.Add(new IndividualThoughtToAdd(ThoughtDefOf.KilledMyRival, current2, pawn, 1f, opinionOffsetFactor)); - } + float friendDiedThoughtPowerFactor = victim.relations.GetFriendDiedThoughtPowerFactor(num); + outIndividualThoughts.Add(new IndividualThoughtToAdd(ThoughtDefOf.KilledMyFriend, potentiallyRelatedPawn2, pawn, 1f, friendDiedThoughtPowerFactor)); + } + else if (num <= -20) + { + float friendDiedThoughtPowerFactor = victim.relations.GetRivalDiedThoughtPowerFactor(num); + outIndividualThoughts.Add(new IndividualThoughtToAdd(ThoughtDefOf.KilledMyRival, potentiallyRelatedPawn2, pawn, 1f, friendDiedThoughtPowerFactor)); } } } } } - if (victim.RaceProps.Humanlike) + } + if (victim.RaceProps.Humanlike) + { + foreach (Pawn allMapsCaravansAndTravelingTransportPod in PawnsFinder.AllMapsCaravansAndTravelingTransportPods) { - foreach (Pawn current3 in PawnsFinder.AllMapsCaravansAndTravelingTransportPods) + if (!allMapsCaravansAndTravelingTransportPod.Dead && allMapsCaravansAndTravelingTransportPod.RaceProps.IsFlesh && allMapsCaravansAndTravelingTransportPod.needs.mood != null && PawnUtility.ShouldGetThoughtAbout(allMapsCaravansAndTravelingTransportPod, victim)) { - if (!current3.Dead && current3.RaceProps.IsFlesh && current3.needs.mood != null) + int num2 = allMapsCaravansAndTravelingTransportPod.relations.OpinionOf(victim); + if (num2 >= 20) { - if (PawnUtility.ShouldGetThoughtAbout(current3, victim)) - { - int num2 = current3.relations.OpinionOf(victim); - if (num2 >= 20) - { - outIndividualThoughts.Add(new IndividualThoughtToAdd(ThoughtDefOf.PawnWithGoodOpinionDied, current3, victim, victim.relations.GetFriendDiedThoughtPowerFactor(num2), 1f)); - } - else if (num2 <= -20) - { - outIndividualThoughts.Add(new IndividualThoughtToAdd(ThoughtDefOf.PawnWithBadOpinionDied, current3, victim, victim.relations.GetRivalDiedThoughtPowerFactor(num2), 1f)); - } - } + outIndividualThoughts.Add(new IndividualThoughtToAdd(ThoughtDefOf.PawnWithGoodOpinionDied, allMapsCaravansAndTravelingTransportPod, victim, victim.relations.GetFriendDiedThoughtPowerFactor(num2), 1f)); + } + else if (num2 <= -20) + { + outIndividualThoughts.Add(new IndividualThoughtToAdd(ThoughtDefOf.PawnWithBadOpinionDied, allMapsCaravansAndTravelingTransportPod, victim, victim.relations.GetRivalDiedThoughtPowerFactor(num2), 1f)); } } } @@ -329,15 +306,27 @@ private static void AppendThoughts_Relations(Pawn victim, DamageInfo? dinfo, Paw private static bool Witnessed(Pawn p, Pawn victim) { - if (!p.Awake() || !p.health.capacities.CapableOf(PawnCapacityDefOf.Sight)) + if (p.Awake() && p.health.capacities.CapableOf(PawnCapacityDefOf.Sight)) { + if (victim.IsCaravanMember()) + { + return victim.GetCaravan() == p.GetCaravan(); + } + if (victim.Spawned && p.Spawned) + { + if (!p.Position.InHorDistOf(victim.Position, 12f)) + { + return false; + } + if (!GenSight.LineOfSight(victim.Position, p.Position, victim.Map, false, null, 0, 0)) + { + return false; + } + return true; + } return false; } - if (victim.IsCaravanMember()) - { - return victim.GetCaravan() == p.GetCaravan(); - } - return victim.Spawned && p.Spawned && p.Position.InHorDistOf(victim.Position, 12f) && GenSight.LineOfSight(victim.Position, p.Position, victim.Map, false, null, 0, 0); + return false; } } } diff --git a/Assembly-CSharp/RimWorld/PawnExecutionKind.cs b/Assembly-CSharp/RimWorld/PawnExecutionKind.cs index 79a885fda..663247986 100644 --- a/Assembly-CSharp/RimWorld/PawnExecutionKind.cs +++ b/Assembly-CSharp/RimWorld/PawnExecutionKind.cs @@ -1,11 +1,9 @@ -using System; - namespace RimWorld { public enum PawnExecutionKind { - GenericBrutal, - GenericHumane, - OrganHarvesting + GenericBrutal = 0, + GenericHumane = 1, + OrganHarvesting = 2 } } diff --git a/Assembly-CSharp/RimWorld/PawnFootprintMaker.cs b/Assembly-CSharp/RimWorld/PawnFootprintMaker.cs index f39528cec..292bb942f 100644 --- a/Assembly-CSharp/RimWorld/PawnFootprintMaker.cs +++ b/Assembly-CSharp/RimWorld/PawnFootprintMaker.cs @@ -1,4 +1,3 @@ -using System; using UnityEngine; using Verse; @@ -30,12 +29,12 @@ public void FootprintMakerTick() if (!this.pawn.RaceProps.makesFootprints) { TerrainDef terrain = this.pawn.Position.GetTerrain(this.pawn.Map); - if (terrain == null || !terrain.takeSplashes) - { + if (terrain == null) + return; + if (!terrain.takeSplashes) return; - } } - if ((this.pawn.Drawer.DrawPos - this.lastFootprintPlacePos).MagnitudeHorizontalSquared() > 0.399424046f) + if ((this.pawn.Drawer.DrawPos - this.lastFootprintPlacePos).MagnitudeHorizontalSquared() > 0.39942404627799988) { this.TryPlaceFootprint(); } @@ -46,7 +45,7 @@ private void TryPlaceFootprint() Vector3 drawPos = this.pawn.Drawer.DrawPos; Vector3 normalized = (drawPos - this.lastFootprintPlacePos).normalized; float rot = normalized.AngleFlat(); - float angle = (float)((!this.lastFootprintRight) ? -90 : 90); + float angle = (float)((!this.lastFootprintRight) ? (-90) : 90); Vector3 b = normalized.RotatedBy(angle) * 0.17f * Mathf.Sqrt(this.pawn.BodySize); Vector3 vector = drawPos + PawnFootprintMaker.FootprintOffset + b; IntVec3 c = vector.ToIntVec3(); @@ -57,9 +56,9 @@ private void TryPlaceFootprint() { if (terrain.takeSplashes) { - MoteMaker.MakeWaterSplash(vector, this.pawn.Map, Mathf.Sqrt(this.pawn.BodySize) * 2f, 1.5f); + MoteMaker.MakeWaterSplash(vector, this.pawn.Map, (float)(Mathf.Sqrt(this.pawn.BodySize) * 2.0), 1.5f); } - if (this.pawn.RaceProps.makesFootprints && terrain.takeFootprints && this.pawn.Map.snowGrid.GetDepth(this.pawn.Position) >= 0.4f) + if (this.pawn.RaceProps.makesFootprints && terrain.takeFootprints && this.pawn.Map.snowGrid.GetDepth(this.pawn.Position) >= 0.40000000596046448) { MoteMaker.PlaceFootprint(vector, this.pawn.Map, rot); } diff --git a/Assembly-CSharp/RimWorld/PawnGenOption.cs b/Assembly-CSharp/RimWorld/PawnGenOption.cs index 0694dc1af..07d9c6096 100644 --- a/Assembly-CSharp/RimWorld/PawnGenOption.cs +++ b/Assembly-CSharp/RimWorld/PawnGenOption.cs @@ -1,4 +1,3 @@ -using System; using System.Xml; using Verse; @@ -20,16 +19,7 @@ public float Cost public override string ToString() { - return string.Concat(new string[] - { - "(", - (this.kind == null) ? "null" : this.kind.ToString(), - " w=", - this.selectionWeight.ToString("F2"), - " c=", - (this.kind == null) ? "null" : this.Cost.ToString("F2"), - ")" - }); + return "(" + ((this.kind == null) ? "null" : this.kind.ToString()) + " w=" + this.selectionWeight.ToString("F2") + " c=" + ((this.kind == null) ? "null" : this.Cost.ToString("F2")) + ")"; } public void LoadDataFromXmlCustom(XmlNode xmlRoot) diff --git a/Assembly-CSharp/RimWorld/PawnGenerationContext.cs b/Assembly-CSharp/RimWorld/PawnGenerationContext.cs index b5a77ffa1..4b65a8112 100644 --- a/Assembly-CSharp/RimWorld/PawnGenerationContext.cs +++ b/Assembly-CSharp/RimWorld/PawnGenerationContext.cs @@ -1,11 +1,9 @@ -using System; - namespace RimWorld { public enum PawnGenerationContext { - All, - PlayerStarter, - NonPlayer + All = 0, + PlayerStarter = 1, + NonPlayer = 2 } } diff --git a/Assembly-CSharp/RimWorld/PawnGenerationContextUtility.cs b/Assembly-CSharp/RimWorld/PawnGenerationContextUtility.cs index 0d0fe4403..7568808f8 100644 --- a/Assembly-CSharp/RimWorld/PawnGenerationContextUtility.cs +++ b/Assembly-CSharp/RimWorld/PawnGenerationContextUtility.cs @@ -10,30 +10,50 @@ public static string ToStringHuman(this PawnGenerationContext context) switch (context) { case PawnGenerationContext.All: + { return "PawnGenerationContext_All".Translate(); + } case PawnGenerationContext.PlayerStarter: + { return "PawnGenerationContext_PlayerStarter".Translate(); + } case PawnGenerationContext.NonPlayer: + { return "PawnGenerationContext_NonPlayer".Translate(); + } default: + { throw new NotImplementedException(); } + } } public static bool Includes(this PawnGenerationContext includer, PawnGenerationContext other) { - return includer == PawnGenerationContext.All || includer == other; + if (includer == PawnGenerationContext.All) + { + return true; + } + return includer == other; } public static PawnGenerationContext GetRandom() { Array values = Enum.GetValues(typeof(PawnGenerationContext)); - return (PawnGenerationContext)((int)values.GetValue(Rand.Range(0, values.Length))); + return (PawnGenerationContext)(int)values.GetValue(Rand.Range(0, values.Length)); } public static bool OverlapsWith(this PawnGenerationContext a, PawnGenerationContext b) { - return a == PawnGenerationContext.All || b == PawnGenerationContext.All || a == b; + if (((a != 0) ? b : PawnGenerationContext.All) != 0) + { + if (a == b) + { + return true; + } + return false; + } + return true; } } } diff --git a/Assembly-CSharp/RimWorld/PawnGroupKindDefOf.cs b/Assembly-CSharp/RimWorld/PawnGroupKindDefOf.cs index b88152e42..d884f697e 100644 --- a/Assembly-CSharp/RimWorld/PawnGroupKindDefOf.cs +++ b/Assembly-CSharp/RimWorld/PawnGroupKindDefOf.cs @@ -1,5 +1,3 @@ -using System; - namespace RimWorld { [DefOf] diff --git a/Assembly-CSharp/RimWorld/PawnGroupKindWorker.cs b/Assembly-CSharp/RimWorld/PawnGroupKindWorker.cs index e18941cc4..23bdd0942 100644 --- a/Assembly-CSharp/RimWorld/PawnGroupKindWorker.cs +++ b/Assembly-CSharp/RimWorld/PawnGroupKindWorker.cs @@ -1,4 +1,3 @@ -using System; using System.Collections.Generic; using Verse; @@ -18,17 +17,16 @@ public List GeneratePawns(PawnGroupMakerParms parms, PawnGroupMaker groupM { Log.Error("pawnsBeingGeneratedNow is not null. Nested calls are not allowed."); } - List list = new List(); - PawnGroupKindWorker.pawnsBeingGeneratedNow = list; + List list = PawnGroupKindWorker.pawnsBeingGeneratedNow = new List(); try { this.GeneratePawns(parms, groupMaker, list, errorOnZeroResults); + return list; } finally { PawnGroupKindWorker.pawnsBeingGeneratedNow = null; } - return list; } protected abstract void GeneratePawns(PawnGroupMakerParms parms, PawnGroupMaker groupMaker, List outPawns, bool errorOnZeroResults = true); diff --git a/Assembly-CSharp/RimWorld/PawnGroupKindWorker_Normal.cs b/Assembly-CSharp/RimWorld/PawnGroupKindWorker_Normal.cs index d3d35a9cf..7e130cd7b 100644 --- a/Assembly-CSharp/RimWorld/PawnGroupKindWorker_Normal.cs +++ b/Assembly-CSharp/RimWorld/PawnGroupKindWorker_Normal.cs @@ -9,12 +9,20 @@ public class PawnGroupKindWorker_Normal : PawnGroupKindWorker { public override float MinPointsToGenerateAnything(PawnGroupMaker groupMaker) { - return groupMaker.options.Min((PawnGenOption g) => g.Cost); + return groupMaker.options.Min((Func)((PawnGenOption g) => g.Cost)); } public override bool CanGenerateFrom(PawnGroupMakerParms parms, PawnGroupMaker groupMaker) { - return base.CanGenerateFrom(parms, groupMaker) && PawnGroupMakerUtility.ChoosePawnGenOptionsByPoints(parms.points, groupMaker.options, parms).Any(); + if (!base.CanGenerateFrom(parms, groupMaker)) + { + return false; + } + if (!PawnGroupMakerUtility.ChoosePawnGenOptionsByPoints(parms.points, groupMaker.options, parms).Any()) + { + return false; + } + return true; } protected override void GeneratePawns(PawnGroupMakerParms parms, PawnGroupMaker groupMaker, List outPawns, bool errorOnZeroResults = true) @@ -23,33 +31,28 @@ protected override void GeneratePawns(PawnGroupMakerParms parms, PawnGroupMaker { if (errorOnZeroResults) { - Log.Error(string.Concat(new object[] - { - "Cannot generate pawns for ", - parms.faction, - " with ", - parms.points, - ". Defaulting to a single random cheap group." - })); + Log.Error("Cannot generate pawns for " + parms.faction + " with " + parms.points + ". Defaulting to a single random cheap group."); } - return; } - bool flag = parms.raidStrategy == null || parms.raidStrategy.pawnsCanBringFood; - bool flag2 = false; - foreach (PawnGenOption current in PawnGroupMakerUtility.ChoosePawnGenOptionsByPoints(parms.points, groupMaker.options, parms)) + else { - int tile = parms.tile; - bool allowFood = flag; - bool inhabitants = parms.inhabitants; - PawnGenerationRequest request = new PawnGenerationRequest(current.kind, parms.faction, PawnGenerationContext.NonPlayer, tile, false, false, false, false, true, true, 1f, false, true, allowFood, inhabitants, false, null, null, null, null, null, null); - Pawn pawn = PawnGenerator.GeneratePawn(request); - if (parms.forceOneIncap && !flag2) + bool flag = parms.raidStrategy == null || parms.raidStrategy.pawnsCanBringFood; + bool flag2 = false; + foreach (PawnGenOption item in PawnGroupMakerUtility.ChoosePawnGenOptionsByPoints(parms.points, groupMaker.options, parms)) { - pawn.health.forceIncap = true; - pawn.mindState.canFleeIndividual = false; - flag2 = true; + int tile = parms.tile; + bool allowFood = flag; + bool inhabitants = parms.inhabitants; + PawnGenerationRequest request = new PawnGenerationRequest(item.kind, parms.faction, PawnGenerationContext.NonPlayer, tile, false, false, false, false, true, true, 1f, false, true, allowFood, inhabitants, false, null, default(float?), default(float?), default(Gender?), default(float?), (string)null); + Pawn pawn = PawnGenerator.GeneratePawn(request); + if (parms.forceOneIncap && !flag2) + { + pawn.health.forceIncap = true; + pawn.mindState.canFleeIndividual = false; + flag2 = true; + } + outPawns.Add(pawn); } - outPawns.Add(pawn); } } } diff --git a/Assembly-CSharp/RimWorld/PawnGroupKindWorker_Trader.cs b/Assembly-CSharp/RimWorld/PawnGroupKindWorker_Trader.cs index cd11d5031..429d5e17a 100644 --- a/Assembly-CSharp/RimWorld/PawnGroupKindWorker_Trader.cs +++ b/Assembly-CSharp/RimWorld/PawnGroupKindWorker_Trader.cs @@ -1,6 +1,5 @@ using System; using System.Collections.Generic; -using System.Diagnostics; using System.Linq; using UnityEngine; using Verse; @@ -16,7 +15,7 @@ public override float MinPointsToGenerateAnything(PawnGroupMaker groupMaker) public override bool CanGenerateFrom(PawnGroupMakerParms parms, PawnGroupMaker groupMaker) { - return base.CanGenerateFrom(parms, groupMaker) && groupMaker.traders.Any() && (parms.tile == -1 || groupMaker.carriers.Any((PawnGenOption x) => Find.WorldGrid[parms.tile].biome.IsPackAnimalAllowed(x.kind.race))); + return base.CanGenerateFrom(parms, groupMaker) && groupMaker.traders.Any() && (parms.tile == -1 || groupMaker.carriers.Any((Predicate)((PawnGenOption x) => Find.WorldGrid[parms.tile].biome.IsPackAnimalAllowed(x.kind.race)))); } protected override void GeneratePawns(PawnGroupMakerParms parms, PawnGroupMaker groupMaker, List outPawns, bool errorOnZeroResults = true) @@ -27,68 +26,52 @@ protected override void GeneratePawns(PawnGroupMakerParms parms, PawnGroupMaker { Log.Error("Cannot generate trader caravan for " + parms.faction + "."); } - return; } - if (!parms.faction.def.caravanTraderKinds.Any()) + else if (!parms.faction.def.caravanTraderKinds.Any()) { Log.Error("Cannot generate trader caravan for " + parms.faction + " because it has no trader kinds."); - return; } - PawnGenOption pawnGenOption = groupMaker.traders.FirstOrDefault((PawnGenOption x) => !x.kind.trader); - if (pawnGenOption != null) + else { - Log.Error(string.Concat(new object[] + PawnGenOption pawnGenOption = groupMaker.traders.FirstOrDefault((Func)((PawnGenOption x) => !x.kind.trader)); + if (pawnGenOption != null) { - "Cannot generate arriving trader caravan for ", - parms.faction, - " because there is a pawn kind (", - pawnGenOption.kind.LabelCap, - ") who is not a trader but is in a traders list." - })); - return; - } - PawnGenOption pawnGenOption2 = groupMaker.carriers.FirstOrDefault((PawnGenOption x) => !x.kind.RaceProps.packAnimal); - if (pawnGenOption2 != null) - { - Log.Error(string.Concat(new object[] + Log.Error("Cannot generate arriving trader caravan for " + parms.faction + " because there is a pawn kind (" + pawnGenOption.kind.LabelCap + ") who is not a trader but is in a traders list."); + } + else { - "Cannot generate arriving trader caravan for ", - parms.faction, - " because there is a pawn kind (", - pawnGenOption2.kind.LabelCap, - ") who is not a carrier but is in a carriers list." - })); - return; - } - TraderKindDef arg_18A_0; - if (parms.traderKind != null) - { - arg_18A_0 = parms.traderKind; - } - else - { - arg_18A_0 = parms.faction.def.caravanTraderKinds.RandomElementByWeight((TraderKindDef traderDef) => traderDef.commonality); - } - TraderKindDef traderKindDef = arg_18A_0; - Pawn pawn = this.GenerateTrader(parms, groupMaker, traderKindDef); - outPawns.Add(pawn); - ItemCollectionGeneratorParams parms2 = default(ItemCollectionGeneratorParams); - parms2.traderDef = traderKindDef; - parms2.forTile = parms.tile; - parms2.forFaction = parms.faction; - List wares = ItemCollectionGeneratorDefOf.TraderStock.Worker.Generate(parms2).InRandomOrder(null).ToList(); - foreach (Pawn current in this.GetSlavesAndAnimalsFromWares(parms, pawn, wares)) - { - outPawns.Add(current); + PawnGenOption pawnGenOption2 = groupMaker.carriers.FirstOrDefault((Func)((PawnGenOption x) => !x.kind.RaceProps.packAnimal)); + if (pawnGenOption2 != null) + { + Log.Error("Cannot generate arriving trader caravan for " + parms.faction + " because there is a pawn kind (" + pawnGenOption2.kind.LabelCap + ") who is not a carrier but is in a carriers list."); + } + else + { + TraderKindDef traderKindDef = (parms.traderKind == null) ? parms.faction.def.caravanTraderKinds.RandomElementByWeight((Func)((TraderKindDef traderDef) => traderDef.commonality)) : parms.traderKind; + Pawn pawn = this.GenerateTrader(parms, groupMaker, traderKindDef); + outPawns.Add(pawn); + ItemCollectionGeneratorParams parms2 = new ItemCollectionGeneratorParams + { + traderDef = traderKindDef, + forTile = parms.tile, + forFaction = parms.faction + }; + List wares = ItemCollectionGeneratorDefOf.TraderStock.Worker.Generate(parms2).InRandomOrder(null).ToList(); + foreach (Pawn slavesAndAnimalsFromWare in this.GetSlavesAndAnimalsFromWares(parms, pawn, wares)) + { + outPawns.Add(slavesAndAnimalsFromWare); + } + this.GenerateCarriers(parms, groupMaker, pawn, wares, outPawns); + this.GenerateGuards(parms, groupMaker, pawn, wares, outPawns); + } + } } - this.GenerateCarriers(parms, groupMaker, pawn, wares, outPawns); - this.GenerateGuards(parms, groupMaker, pawn, wares, outPawns); } private Pawn GenerateTrader(PawnGroupMakerParms parms, PawnGroupMaker groupMaker, TraderKindDef traderKind) { int tile = parms.tile; - PawnGenerationRequest request = new PawnGenerationRequest(groupMaker.traders.RandomElementByWeight((PawnGenOption x) => (float)x.selectionWeight).kind, parms.faction, PawnGenerationContext.NonPlayer, tile, false, false, false, false, true, false, 1f, false, true, true, parms.inhabitants, false, null, null, null, null, null, null); + PawnGenerationRequest request = new PawnGenerationRequest(groupMaker.traders.RandomElementByWeight((Func)((PawnGenOption x) => (float)x.selectionWeight)).kind, parms.faction, PawnGenerationContext.NonPlayer, tile, false, false, false, false, true, false, 1f, false, true, true, parms.inhabitants, false, null, default(float?), default(float?), default(Gender?), default(float?), (string)null); Pawn pawn = PawnGenerator.GeneratePawn(request); pawn.mindState.wantsToTradeWithColony = true; PawnComponentsUtility.AddAndRemoveDynamicComponents(pawn, true); @@ -101,17 +84,17 @@ private void GenerateCarriers(PawnGroupMakerParms parms, PawnGroupMaker groupMak { List list = (from x in wares where !(x is Pawn) - select x).ToList(); + select x).ToList(); int i = 0; - int num = Mathf.CeilToInt((float)list.Count / 8f); + int num = Mathf.CeilToInt((float)((float)list.Count / 8.0)); PawnKindDef kind = (from x in groupMaker.carriers where parms.tile == -1 || Find.WorldGrid[parms.tile].biome.IsPackAnimalAllowed(x.kind.race) - select x).RandomElementByWeight((PawnGenOption x) => (float)x.selectionWeight).kind; + select x).RandomElementByWeight((Func)((PawnGenOption x) => (float)x.selectionWeight)).kind; List list2 = new List(); - for (int j = 0; j < num; j++) + for (int num2 = 0; num2 < num; num2++) { int tile = parms.tile; - PawnGenerationRequest request = new PawnGenerationRequest(kind, parms.faction, PawnGenerationContext.NonPlayer, tile, false, false, false, false, true, false, 1f, false, true, true, parms.inhabitants, false, null, null, null, null, null, null); + PawnGenerationRequest request = new PawnGenerationRequest(kind, parms.faction, PawnGenerationContext.NonPlayer, tile, false, false, false, false, true, false, 1f, false, true, true, parms.inhabitants, false, null, default(float?), default(float?), default(Gender?), default(float?), (string)null); Pawn pawn = PawnGenerator.GeneratePawn(request); if (i < list.Count) { @@ -121,40 +104,41 @@ private void GenerateCarriers(PawnGroupMakerParms parms, PawnGroupMaker groupMak list2.Add(pawn); outPawns.Add(pawn); } - while (i < list.Count) + for (; i < list.Count; i++) { - list2.RandomElement().inventory.innerContainer.TryAdd(list[i], true); - i++; + list2.RandomElement().inventory.innerContainer.TryAdd(list[i], true); } } - [DebuggerHidden] private IEnumerable GetSlavesAndAnimalsFromWares(PawnGroupMakerParms parms, Pawn trader, List wares) { - PawnGroupKindWorker_Trader.c__IteratorC8 c__IteratorC = new PawnGroupKindWorker_Trader.c__IteratorC8(); - c__IteratorC.wares = wares; - c__IteratorC.parms = parms; - c__IteratorC.<$>wares = wares; - c__IteratorC.<$>parms = parms; - PawnGroupKindWorker_Trader.c__IteratorC8 expr_23 = c__IteratorC; - expr_23.$PC = -2; - return expr_23; + for (int i = 0; i < wares.Count; i++) + { + Pawn p = wares[i] as Pawn; + if (p != null) + { + if (p.Faction != parms.faction) + { + p.SetFaction(parms.faction, null); + } + yield return p; + } + } } private void GenerateGuards(PawnGroupMakerParms parms, PawnGroupMaker groupMaker, Pawn trader, List wares, List outPawns) { - if (!groupMaker.guards.Any()) + if (groupMaker.guards.Any()) { - return; - } - float points = parms.points; - foreach (PawnGenOption current in PawnGroupMakerUtility.ChoosePawnGenOptionsByPoints(points, groupMaker.guards, parms)) - { - int tile = parms.tile; - bool inhabitants = parms.inhabitants; - PawnGenerationRequest request = new PawnGenerationRequest(current.kind, parms.faction, PawnGenerationContext.NonPlayer, tile, false, false, false, false, true, true, 1f, false, true, true, inhabitants, false, null, null, null, null, null, null); - Pawn item = PawnGenerator.GeneratePawn(request); - outPawns.Add(item); + float points = parms.points; + foreach (PawnGenOption item2 in PawnGroupMakerUtility.ChoosePawnGenOptionsByPoints(points, groupMaker.guards, parms)) + { + int tile = parms.tile; + bool inhabitants = parms.inhabitants; + PawnGenerationRequest request = new PawnGenerationRequest(item2.kind, parms.faction, PawnGenerationContext.NonPlayer, tile, false, false, false, false, true, true, 1f, false, true, true, inhabitants, false, null, default(float?), default(float?), default(Gender?), default(float?), (string)null); + Pawn item = PawnGenerator.GeneratePawn(request); + outPawns.Add(item); + } } } } diff --git a/Assembly-CSharp/RimWorld/PawnGroupMaker.cs b/Assembly-CSharp/RimWorld/PawnGroupMaker.cs index 110715c30..8b7961e06 100644 --- a/Assembly-CSharp/RimWorld/PawnGroupMaker.cs +++ b/Assembly-CSharp/RimWorld/PawnGroupMaker.cs @@ -1,4 +1,3 @@ -using System; using System.Collections.Generic; using Verse; @@ -35,7 +34,11 @@ public IEnumerable GeneratePawns(PawnGroupMakerParms parms, bool errorOnZe public bool CanGenerateFrom(PawnGroupMakerParms parms) { - return (this.disallowedStrategies == null || !this.disallowedStrategies.Contains(parms.raidStrategy)) && this.kindDef.Worker.CanGenerateFrom(parms, this); + if (this.disallowedStrategies != null && this.disallowedStrategies.Contains(parms.raidStrategy)) + { + return false; + } + return this.kindDef.Worker.CanGenerateFrom(parms, this); } } } diff --git a/Assembly-CSharp/RimWorld/PawnGroupMakerParms.cs b/Assembly-CSharp/RimWorld/PawnGroupMakerParms.cs index 8928d470f..e1aba63ce 100644 --- a/Assembly-CSharp/RimWorld/PawnGroupMakerParms.cs +++ b/Assembly-CSharp/RimWorld/PawnGroupMakerParms.cs @@ -1,5 +1,3 @@ -using System; - namespace RimWorld { public class PawnGroupMakerParms @@ -22,25 +20,7 @@ public class PawnGroupMakerParms public override string ToString() { - return string.Concat(new object[] - { - "tile=", - this.tile, - ", inhabitants=", - this.inhabitants, - ", points=", - this.points, - ", faction=", - this.faction, - ", traderKind=", - this.traderKind, - ", generateFightersOnly=", - this.generateFightersOnly, - ", raidStrategy=", - this.raidStrategy, - ", forceOneIncap=", - this.forceOneIncap - }); + return "tile=" + this.tile + ", inhabitants=" + this.inhabitants + ", points=" + this.points + ", faction=" + this.faction + ", traderKind=" + this.traderKind + ", generateFightersOnly=" + this.generateFightersOnly + ", raidStrategy=" + this.raidStrategy + ", forceOneIncap=" + this.forceOneIncap; } } } diff --git a/Assembly-CSharp/RimWorld/PawnGroupMakerUtility.cs b/Assembly-CSharp/RimWorld/PawnGroupMakerUtility.cs index 815da67f5..6a4c1adf7 100644 --- a/Assembly-CSharp/RimWorld/PawnGroupMakerUtility.cs +++ b/Assembly-CSharp/RimWorld/PawnGroupMakerUtility.cs @@ -1,6 +1,5 @@ using System; using System.Collections.Generic; -using System.Diagnostics; using System.Linq; using System.Text; using UnityEngine; @@ -74,19 +73,34 @@ public class PawnGroupMakerUtility } }; - [DebuggerHidden] public static IEnumerable GeneratePawns(PawnGroupKindDef groupKind, PawnGroupMakerParms parms, bool warnOnZeroResults = true) { - PawnGroupMakerUtility.c__IteratorC9 c__IteratorC = new PawnGroupMakerUtility.c__IteratorC9(); - c__IteratorC.groupKind = groupKind; - c__IteratorC.parms = parms; - c__IteratorC.warnOnZeroResults = warnOnZeroResults; - c__IteratorC.<$>groupKind = groupKind; - c__IteratorC.<$>parms = parms; - c__IteratorC.<$>warnOnZeroResults = warnOnZeroResults; - PawnGroupMakerUtility.c__IteratorC9 expr_31 = c__IteratorC; - expr_31.$PC = -2; - return expr_31; + if (groupKind == null) + { + Log.Error("Tried to generate pawns with null pawn group kind def. parms=" + parms); + } + else if (parms.faction.def.pawnGroupMakers == null) + { + Log.Error("Faction " + parms.faction + " of def " + parms.faction.def + " has no any PawnGroupMakers."); + } + else + { + IEnumerable usableGroupMakers = from gm in parms.faction.def.pawnGroupMakers + where gm.kindDef == ((_003CGeneratePawns_003Ec__IteratorC9)/*Error near IL_00c6: stateMachine*/).groupKind && gm.CanGenerateFrom(((_003CGeneratePawns_003Ec__IteratorC9)/*Error near IL_00c6: stateMachine*/).parms) + select gm; + PawnGroupMaker chosenGroupMaker; + if (!usableGroupMakers.TryRandomElementByWeight((Func)((PawnGroupMaker gm) => gm.commonality), out chosenGroupMaker)) + { + Log.Error("Faction " + parms.faction + " of def " + parms.faction.def + " has no usable PawnGroupMakers for parms " + parms); + } + else + { + foreach (Pawn item in chosenGroupMaker.GeneratePawns(parms, warnOnZeroResults)) + { + yield return item; + } + } + } } public static IEnumerable ChoosePawnGenOptionsByPoints(float points, List options, PawnGroupMakerParms parms) @@ -102,57 +116,38 @@ public static IEnumerable ChoosePawnGenOptionsByPoints(float poin for (int i = 0; i < options.Count; i++) { PawnGenOption pawnGenOption = options[i]; - if (pawnGenOption.Cost <= num2) + if (!(pawnGenOption.Cost > num2) && !(pawnGenOption.Cost > num) && (!parms.generateFightersOnly || pawnGenOption.kind.isFighter) && (parms.raidStrategy == null || parms.raidStrategy.Worker.CanUsePawnGenOption(pawnGenOption, list2)) && (!flag || !pawnGenOption.kind.factionLeader)) { - if (pawnGenOption.Cost <= num) - { - if (!parms.generateFightersOnly || pawnGenOption.kind.isFighter) - { - if (parms.raidStrategy == null || parms.raidStrategy.Worker.CanUsePawnGenOption(pawnGenOption, list2)) - { - if (!flag || !pawnGenOption.kind.factionLeader) - { - list.Add(pawnGenOption); - } - } - } - } + list.Add(pawnGenOption); } } - if (list.Count == 0) + if (list.Count != 0) { - break; - } - float desireToSuppressCount = PawnGroupMakerUtility.DesireToSuppressCountPerRaidPointsCurve.Evaluate(points); - Func weightSelector = delegate(PawnGenOption gr) - { - float num3 = (float)gr.selectionWeight; - if (desireToSuppressCount > 0f) + float desireToSuppressCount = PawnGroupMakerUtility.DesireToSuppressCountPerRaidPointsCurve.Evaluate(points); + Func weightSelector = (Func)delegate(PawnGenOption gr) + { + float num3 = (float)gr.selectionWeight; + if (desireToSuppressCount > 0.0) + { + float b = (float)(num3 * (gr.Cost / 100.0)); + num3 = Mathf.Lerp(num3, b, desireToSuppressCount); + } + return num3; + }; + PawnGenOption pawnGenOption2 = list.RandomElementByWeight(weightSelector); + list2.Add(pawnGenOption2); + num2 -= pawnGenOption2.Cost; + if (pawnGenOption2.kind.factionLeader) { - float b = num3 * (gr.Cost / 100f); - num3 = Mathf.Lerp(num3, b, desireToSuppressCount); + flag = true; } - return num3; - }; - PawnGenOption pawnGenOption2 = list.RandomElementByWeight(weightSelector); - list2.Add(pawnGenOption2); - num2 -= pawnGenOption2.Cost; - if (pawnGenOption2.kind.factionLeader) - { - flag = true; + continue; } + break; } - if (list2.Count == 1 && num2 > points / 2f) + if (list2.Count == 1 && num2 > points / 2.0) { - Log.Warning(string.Concat(new object[] - { - "Used only ", - points - num2, - " / ", - points, - " points generating for ", - parms.faction - })); + Log.Warning("Used only " + (points - num2) + " / " + points + " points generating for " + parms.faction); } return list2; } @@ -165,92 +160,57 @@ private static float MaxAllowedPawnGenOptionCost(Faction faction, float totalPoi { num = Mathf.Min(num, totalPoints / raidStrategy.minPawns); } - num = Mathf.Max(num, faction.def.MinPointsToGenerateNormalPawnGroup() * 1.2f); + num = Mathf.Max(num, (float)(faction.def.MinPointsToGenerateNormalPawnGroup() * 1.2000000476837158)); if (raidStrategy != null) { - num = Mathf.Max(num, raidStrategy.Worker.MinMaxAllowedPawnGenOptionCost(faction) * 1.2f); + num = Mathf.Max(num, (float)(raidStrategy.Worker.MinMaxAllowedPawnGenOptionCost(faction) * 1.2000000476837158)); } return num; } public static void LogPawnGroupsMade() { - foreach (Faction fac in Find.FactionManager.AllFactions) + using (IEnumerator enumerator = Find.FactionManager.AllFactions.GetEnumerator()) { - if (!fac.def.pawnGroupMakers.NullOrEmpty()) + Faction fac; + while (enumerator.MoveNext()) { - StringBuilder sb = new StringBuilder(); - sb.AppendLine(string.Concat(new object[] - { - "FACTION: ", - fac.Name, - " (", - fac.def.defName, - ") min=", - fac.def.MinPointsToGenerateNormalPawnGroup() - })); - Action action = delegate(float points) + fac = enumerator.Current; + if (!fac.def.pawnGroupMakers.NullOrEmpty()) { - if (points < fac.def.MinPointsToGenerateNormalPawnGroup()) + StringBuilder sb = new StringBuilder(); + sb.AppendLine("FACTION: " + fac.Name + " (" + fac.def.defName + ") min=" + fac.def.MinPointsToGenerateNormalPawnGroup()); + Action action = (Action)delegate(float points) { - return; - } - PawnGroupMakerParms pawnGroupMakerParms = new PawnGroupMakerParms(); - pawnGroupMakerParms.tile = Find.VisibleMap.Tile; - pawnGroupMakerParms.points = points; - pawnGroupMakerParms.faction = fac; - sb.AppendLine(string.Concat(new object[] - { - "Group with ", - pawnGroupMakerParms.points, - " points (max option cost: ", - PawnGroupMakerUtility.MaxAllowedPawnGenOptionCost(fac, points, RaidStrategyDefOf.ImmediateAttack), - ")" - })); - float num = 0f; - foreach (Pawn current in from pa in PawnGroupMakerUtility.GeneratePawns(PawnGroupKindDefOf.Normal, pawnGroupMakerParms, false) - orderby pa.kindDef.combatPower - select pa) - { - string text; - if (current.equipment.Primary != null) - { - text = current.equipment.Primary.Label; - } - else + if (!(points < fac.def.MinPointsToGenerateNormalPawnGroup())) { - text = "no-equipment"; - } - Apparel apparel = current.apparel.FirstApparelOnBodyPartGroup(BodyPartGroupDefOf.Torso); - string text2; - if (apparel != null) - { - text2 = apparel.LabelCap; - } - else - { - text2 = "shirtless"; + PawnGroupMakerParms pawnGroupMakerParms = new PawnGroupMakerParms(); + pawnGroupMakerParms.tile = Find.VisibleMap.Tile; + pawnGroupMakerParms.points = points; + pawnGroupMakerParms.faction = fac; + sb.AppendLine("Group with " + pawnGroupMakerParms.points + " points (max option cost: " + PawnGroupMakerUtility.MaxAllowedPawnGenOptionCost(fac, points, RaidStrategyDefOf.ImmediateAttack) + ")"); + float num = 0f; + foreach (Pawn item in from pa in PawnGroupMakerUtility.GeneratePawns(PawnGroupKindDefOf.Normal, pawnGroupMakerParms, false) + orderby pa.kindDef.combatPower + select pa) + { + string text = (item.equipment.Primary == null) ? "no-equipment" : item.equipment.Primary.Label; + Apparel apparel = item.apparel.FirstApparelOnBodyPartGroup(BodyPartGroupDefOf.Torso); + string text2 = (apparel == null) ? "shirtless" : apparel.LabelCap; + sb.AppendLine(" " + item.kindDef.combatPower.ToString("F0").PadRight(6) + item.kindDef.defName + ", " + text + ", " + text2); + num += item.kindDef.combatPower; + } + sb.AppendLine(" totalCost " + num); + sb.AppendLine(); } - sb.AppendLine(string.Concat(new string[] - { - " ", - current.kindDef.combatPower.ToString("F0").PadRight(6), - current.kindDef.defName, - ", ", - text, - ", ", - text2 - })); - num += current.kindDef.combatPower; + }; + foreach (float item2 in Dialog_DebugActionsMenu.PointsOptions()) + { + float obj = item2; + action(obj); } - sb.AppendLine(" totalCost " + num); - sb.AppendLine(); - }; - foreach (float obj in Dialog_DebugActionsMenu.PointsOptions()) - { - action(obj); + Log.Message(sb.ToString()); } - Log.Message(sb.ToString()); } } } diff --git a/Assembly-CSharp/RimWorld/PawnHairChooser.cs b/Assembly-CSharp/RimWorld/PawnHairChooser.cs index 99cb56d90..44c4854d4 100644 --- a/Assembly-CSharp/RimWorld/PawnHairChooser.cs +++ b/Assembly-CSharp/RimWorld/PawnHairChooser.cs @@ -12,7 +12,7 @@ public static HairDef RandomHairDefFor(Pawn pawn, FactionDef factionType) IEnumerable source = from hair in DefDatabase.AllDefs where hair.hairTags.SharesElementWith(factionType.hairTags) select hair; - return source.RandomElementByWeight((HairDef hair) => PawnHairChooser.HairChoiceLikelihoodFor(hair, pawn)); + return source.RandomElementByWeight((Func)((HairDef hair) => PawnHairChooser.HairChoiceLikelihoodFor(hair, pawn))); } private static float HairChoiceLikelihoodFor(HairDef hair, Pawn pawn) @@ -25,41 +25,55 @@ private static float HairChoiceLikelihoodFor(HairDef hair, Pawn pawn) { switch (hair.hairGender) { - case HairGender.Male: - return 70f; + case HairGender.Female: + { + return 1f; + } + case HairGender.FemaleUsually: + { + return 5f; + } case HairGender.MaleUsually: + { return 30f; + } + case HairGender.Male: + { + return 70f; + } case HairGender.Any: + { return 60f; - case HairGender.FemaleUsually: - return 5f; - case HairGender.Female: - return 1f; + } } } if (pawn.gender == Gender.Female) { switch (hair.hairGender) { - case HairGender.Male: - return 1f; + case HairGender.Female: + { + return 70f; + } + case HairGender.FemaleUsually: + { + return 30f; + } case HairGender.MaleUsually: + { return 5f; + } + case HairGender.Male: + { + return 1f; + } case HairGender.Any: + { return 60f; - case HairGender.FemaleUsually: - return 30f; - case HairGender.Female: - return 70f; + } } } - Log.Error(string.Concat(new object[] - { - "Unknown hair likelihood for ", - hair, - " with ", - pawn - })); + Log.Error("Unknown hair likelihood for " + hair + " with " + pawn); return 0f; } } diff --git a/Assembly-CSharp/RimWorld/PawnHairColors.cs b/Assembly-CSharp/RimWorld/PawnHairColors.cs index 010dfe1c0..a58d3ef25 100644 --- a/Assembly-CSharp/RimWorld/PawnHairColors.cs +++ b/Assembly-CSharp/RimWorld/PawnHairColors.cs @@ -1,4 +1,3 @@ -using System; using UnityEngine; using Verse; @@ -8,7 +7,7 @@ public static class PawnHairColors { public static Color RandomHairColor(Color skinColor, int ageYears) { - if (Rand.Value < 0.02f) + if (Rand.Value < 0.019999999552965164) { return new Color(Rand.Value, Rand.Value, Rand.Value); } @@ -21,40 +20,37 @@ public static Color RandomHairColor(Color skinColor, int ageYears) return new Color(num2, num2, num2); } } - if (PawnSkinColors.IsDarkSkin(skinColor) || Rand.Value < 0.5f) + if (!PawnSkinColors.IsDarkSkin(skinColor) && !(Rand.Value < 0.5)) { float value = Rand.Value; - if (value < 0.25f) - { - return new Color(0.2f, 0.2f, 0.2f); - } - if (value < 0.5f) - { - return new Color(0.31f, 0.28f, 0.26f); - } - if (value < 0.75f) - { - return new Color(0.25f, 0.2f, 0.15f); - } - return new Color(0.3f, 0.2f, 0.1f); - } - else - { - float value2 = Rand.Value; - if (value2 < 0.25f) + if (value < 0.25) { return new Color(0.3529412f, 0.227450982f, 0.1254902f); } - if (value2 < 0.5f) + if (value < 0.5) { return new Color(0.5176471f, 0.3254902f, 0.184313729f); } - if (value2 < 0.75f) + if (value < 0.75) { return new Color(0.75686276f, 0.572549045f, 0.333333343f); } return new Color(0.929411769f, 0.7921569f, 0.6117647f); } + float value2 = Rand.Value; + if (value2 < 0.25) + { + return new Color(0.2f, 0.2f, 0.2f); + } + if (value2 < 0.5) + { + return new Color(0.31f, 0.28f, 0.26f); + } + if (value2 < 0.75) + { + return new Color(0.25f, 0.2f, 0.15f); + } + return new Color(0.3f, 0.2f, 0.1f); } } } diff --git a/Assembly-CSharp/RimWorld/PawnInventoryGenerator.cs b/Assembly-CSharp/RimWorld/PawnInventoryGenerator.cs index 0bea12940..05fb31471 100644 --- a/Assembly-CSharp/RimWorld/PawnInventoryGenerator.cs +++ b/Assembly-CSharp/RimWorld/PawnInventoryGenerator.cs @@ -19,9 +19,9 @@ public static void GenerateInventoryFor(Pawn p, PawnGenerationRequest request) } if (p.kindDef.inventoryOptions != null) { - foreach (Thing current in p.kindDef.inventoryOptions.GenerateThings()) + foreach (Thing item in p.kindDef.inventoryOptions.GenerateThings()) { - p.inventory.innerContainer.TryAdd(current, true); + p.inventory.innerContainer.TryAdd(item, true); } } if (request.AllowFood) @@ -34,7 +34,7 @@ public static void GenerateInventoryFor(Pawn p, PawnGenerationRequest request) public static void GiveRandomFood(Pawn p) { - if (p.kindDef.invNutrition > 0.001f) + if (p.kindDef.invNutrition > 0.0010000000474974513) { ThingDef thingDef; if (p.kindDef.invFoodDef != null) @@ -44,18 +44,7 @@ public static void GiveRandomFood(Pawn p) else { float value = Rand.Value; - if (value < 0.5f) - { - thingDef = ThingDefOf.MealSimple; - } - else if ((double)value < 0.75) - { - thingDef = ThingDefOf.MealFine; - } - else - { - thingDef = ThingDefOf.MealSurvivalPack; - } + thingDef = ((!(value < 0.5)) ? ((!((double)value < 0.75)) ? ThingDefOf.MealSurvivalPack : ThingDefOf.MealFine) : ThingDefOf.MealSimple); } Thing thing = ThingMaker.MakeThing(thingDef, null); thing.stackCount = GenMath.RoundRandom(p.kindDef.invNutrition / thingDef.ingestible.nutrition); @@ -65,83 +54,79 @@ public static void GiveRandomFood(Pawn p) private static void GiveDrugsIfAddicted(Pawn p) { - PawnInventoryGenerator.c__AnonStorey333 c__AnonStorey = new PawnInventoryGenerator.c__AnonStorey333(); - c__AnonStorey.p = p; - if (!c__AnonStorey.p.RaceProps.Humanlike) - { - return; - } - IEnumerable hediffs = c__AnonStorey.p.health.hediffSet.GetHediffs(); - foreach (Hediff_Addiction addiction in hediffs) + if (p.RaceProps.Humanlike) { - IEnumerable source = DefDatabase.AllDefsListForReading.Where(delegate(ThingDef x) + IEnumerable hediffs = p.health.hediffSet.GetHediffs(); + using (IEnumerator enumerator = hediffs.GetEnumerator()) { - if (x.category != ThingCategory.Item) + Hediff_Addiction addiction; + while (enumerator.MoveNext()) { - return false; - } - if (c__AnonStorey.p.Faction != null && x.techLevel > c__AnonStorey.p.Faction.def.techLevel) - { - return false; + addiction = enumerator.Current; + IEnumerable source = DefDatabase.AllDefsListForReading.Where((Func)delegate(ThingDef x) + { + if (x.category != ThingCategory.Item) + { + return false; + } + if (p.Faction != null && (int)x.techLevel > (int)p.Faction.def.techLevel) + { + return false; + } + CompProperties_Drug compProperties = x.GetCompProperties(); + return compProperties != null && compProperties.chemical != null && compProperties.chemical.addictionHediff == addiction.def; + }); + ThingDef def = default(ThingDef); + if (source.TryRandomElement(out def)) + { + int stackCount = Rand.RangeInclusive(2, 5); + Thing thing = ThingMaker.MakeThing(def, null); + thing.stackCount = stackCount; + p.inventory.TryAddItemNotForSale(thing); + } } - CompProperties_Drug compProperties = x.GetCompProperties(); - return compProperties != null && compProperties.chemical != null && compProperties.chemical.addictionHediff == addiction.def; - }); - ThingDef def; - if (source.TryRandomElement(out def)) - { - int stackCount = Rand.RangeInclusive(2, 5); - Thing thing = ThingMaker.MakeThing(def, null); - thing.stackCount = stackCount; - c__AnonStorey.p.inventory.TryAddItemNotForSale(thing); } } } private static void GiveCombatEnhancingDrugs(Pawn pawn) { - if (Rand.Value >= pawn.kindDef.combatEnhancingDrugsChance) - { - return; - } - if (pawn.IsTeetotaler()) + if (!(Rand.Value >= pawn.kindDef.combatEnhancingDrugsChance) && !pawn.IsTeetotaler()) { - return; - } - for (int i = 0; i < pawn.inventory.innerContainer.Count; i++) - { - CompDrug compDrug = pawn.inventory.innerContainer[i].TryGetComp(); - if (compDrug != null && compDrug.Props.isCombatEnhancingDrug) - { - return; - } - } - int randomInRange = pawn.kindDef.combatEnhancingDrugsCount.RandomInRange; - if (randomInRange <= 0) - { - return; - } - IEnumerable source = DefDatabase.AllDefsListForReading.Where(delegate(ThingDef x) - { - if (x.category != ThingCategory.Item) + for (int i = 0; i < pawn.inventory.innerContainer.Count; i++) { - return false; + CompDrug compDrug = pawn.inventory.innerContainer[i].TryGetComp(); + if (compDrug != null && compDrug.Props.isCombatEnhancingDrug) + return; } - if (pawn.Faction != null && x.techLevel > pawn.Faction.def.techLevel) + int randomInRange = pawn.kindDef.combatEnhancingDrugsCount.RandomInRange; + if (randomInRange > 0) { - return false; - } - CompProperties_Drug compProperties = x.GetCompProperties(); - return compProperties != null && compProperties.isCombatEnhancingDrug; - }); - for (int j = 0; j < randomInRange; j++) - { - ThingDef def; - if (!source.TryRandomElement(out def)) - { - break; + IEnumerable source = DefDatabase.AllDefsListForReading.Where((Func)delegate(ThingDef x) + { + if (x.category != ThingCategory.Item) + { + return false; + } + if (pawn.Faction != null && (int)x.techLevel > (int)pawn.Faction.def.techLevel) + { + return false; + } + CompProperties_Drug compProperties = x.GetCompProperties(); + if (compProperties != null && compProperties.isCombatEnhancingDrug) + { + return true; + } + return false; + }); + int num = 0; + ThingDef def = default(ThingDef); + while (num < randomInRange && source.TryRandomElement(out def)) + { + pawn.inventory.innerContainer.TryAdd(ThingMaker.MakeThing(def, null), true); + num++; + } } - pawn.inventory.innerContainer.TryAdd(ThingMaker.MakeThing(def, null), true); } } } diff --git a/Assembly-CSharp/RimWorld/PawnKindDefOf.cs b/Assembly-CSharp/RimWorld/PawnKindDefOf.cs index 521bbe348..2ef13fd5b 100644 --- a/Assembly-CSharp/RimWorld/PawnKindDefOf.cs +++ b/Assembly-CSharp/RimWorld/PawnKindDefOf.cs @@ -1,4 +1,3 @@ -using System; using Verse; namespace RimWorld diff --git a/Assembly-CSharp/RimWorld/PawnNameCategory.cs b/Assembly-CSharp/RimWorld/PawnNameCategory.cs index 2bf9f9963..f2927ea79 100644 --- a/Assembly-CSharp/RimWorld/PawnNameCategory.cs +++ b/Assembly-CSharp/RimWorld/PawnNameCategory.cs @@ -1,10 +1,8 @@ -using System; - namespace RimWorld { public enum PawnNameCategory : byte { - NoName, - HumanStandard + NoName = 0, + HumanStandard = 1 } } diff --git a/Assembly-CSharp/RimWorld/PawnNameDatabaseShuffled.cs b/Assembly-CSharp/RimWorld/PawnNameDatabaseShuffled.cs index 6183f2011..179077f6e 100644 --- a/Assembly-CSharp/RimWorld/PawnNameDatabaseShuffled.cs +++ b/Assembly-CSharp/RimWorld/PawnNameDatabaseShuffled.cs @@ -1,5 +1,4 @@ using System; -using System.Collections; using System.Collections.Generic; using Verse; @@ -13,15 +12,11 @@ public static class PawnNameDatabaseShuffled static PawnNameDatabaseShuffled() { PawnNameDatabaseShuffled.banks = new Dictionary(); - using (IEnumerator enumerator = Enum.GetValues(typeof(PawnNameCategory)).GetEnumerator()) + foreach (byte value in Enum.GetValues(typeof(PawnNameCategory))) { - while (enumerator.MoveNext()) + if (value != 0) { - PawnNameCategory pawnNameCategory = (PawnNameCategory)((byte)enumerator.Current); - if (pawnNameCategory != PawnNameCategory.NoName) - { - PawnNameDatabaseShuffled.banks.Add(pawnNameCategory, new NameBank(pawnNameCategory)); - } + PawnNameDatabaseShuffled.banks.Add((PawnNameCategory)value, new NameBank((PawnNameCategory)value)); } } NameBank nameBank = PawnNameDatabaseShuffled.BankOf(PawnNameCategory.HumanStandard); @@ -31,9 +26,18 @@ static PawnNameDatabaseShuffled() nameBank.AddNamesFromFile(PawnNameSlot.Nick, Gender.Female, "Nick_Female"); nameBank.AddNamesFromFile(PawnNameSlot.Nick, Gender.None, "Nick_Unisex"); nameBank.AddNamesFromFile(PawnNameSlot.Last, Gender.None, "Last"); - foreach (NameBank current in PawnNameDatabaseShuffled.banks.Values) + Dictionary.ValueCollection.Enumerator enumerator2 = PawnNameDatabaseShuffled.banks.Values.GetEnumerator(); + try { - current.ErrorCheck(); + while (enumerator2.MoveNext()) + { + NameBank current = enumerator2.Current; + current.ErrorCheck(); + } + } + finally + { + ((IDisposable)(object)enumerator2).Dispose(); } } diff --git a/Assembly-CSharp/RimWorld/PawnNameDatabaseSolid.cs b/Assembly-CSharp/RimWorld/PawnNameDatabaseSolid.cs index 9ef2d155f..08a1555c5 100644 --- a/Assembly-CSharp/RimWorld/PawnNameDatabaseSolid.cs +++ b/Assembly-CSharp/RimWorld/PawnNameDatabaseSolid.cs @@ -1,7 +1,5 @@ using System; -using System.Collections; using System.Collections.Generic; -using System.Diagnostics; using Verse; namespace RimWorld @@ -15,13 +13,9 @@ public static class PawnNameDatabaseSolid static PawnNameDatabaseSolid() { PawnNameDatabaseSolid.solidNames = new Dictionary>(); - using (IEnumerator enumerator = Enum.GetValues(typeof(GenderPossibility)).GetEnumerator()) + foreach (byte value in Enum.GetValues(typeof(GenderPossibility))) { - while (enumerator.MoveNext()) - { - GenderPossibility key = (GenderPossibility)((byte)enumerator.Current); - PawnNameDatabaseSolid.solidNames.Add(key, new List()); - } + PawnNameDatabaseSolid.solidNames.Add((GenderPossibility)value, new List()); } } @@ -35,13 +29,32 @@ public static List GetListForGender(GenderPossibility gp) return PawnNameDatabaseSolid.solidNames[gp]; } - [DebuggerHidden] public static IEnumerable AllNames() { - PawnNameDatabaseSolid.c__IteratorE0 c__IteratorE = new PawnNameDatabaseSolid.c__IteratorE0(); - PawnNameDatabaseSolid.c__IteratorE0 expr_07 = c__IteratorE; - expr_07.$PC = -2; - return expr_07; + Dictionary>.Enumerator enumerator = PawnNameDatabaseSolid.solidNames.GetEnumerator(); + try + { + while (enumerator.MoveNext()) + { + List.Enumerator enumerator2 = enumerator.Current.Value.GetEnumerator(); + try + { + while (enumerator2.MoveNext()) + { + NameTriple name = enumerator2.Current; + yield return name; + } + } + finally + { + ((IDisposable)(object)enumerator2).Dispose(); + } + } + } + finally + { + ((IDisposable)(object)enumerator).Dispose(); + } } } } diff --git a/Assembly-CSharp/RimWorld/PawnNameSlot.cs b/Assembly-CSharp/RimWorld/PawnNameSlot.cs index 333d8d96a..953dca7bc 100644 --- a/Assembly-CSharp/RimWorld/PawnNameSlot.cs +++ b/Assembly-CSharp/RimWorld/PawnNameSlot.cs @@ -1,12 +1,10 @@ -using System; - namespace RimWorld { public enum PawnNameSlot : byte { - First, - Last, - Nick, - Only + First = 0, + Last = 1, + Nick = 2, + Only = 3 } } diff --git a/Assembly-CSharp/RimWorld/PawnNeedsUIUtility.cs b/Assembly-CSharp/RimWorld/PawnNeedsUIUtility.cs index 48ca83826..6be6c2351 100644 --- a/Assembly-CSharp/RimWorld/PawnNeedsUIUtility.cs +++ b/Assembly-CSharp/RimWorld/PawnNeedsUIUtility.cs @@ -8,7 +8,7 @@ public static class PawnNeedsUIUtility { public static void SortInDisplayOrder(List needs) { - needs.Sort((Need a, Need b) => b.def.listPriority.CompareTo(a.def.listPriority)); + needs.Sort((Comparison)((Need a, Need b) => b.def.listPriority.CompareTo(a.def.listPriority))); } public static Thought GetLeadingThoughtInGroup(List thoughtsInGroup) @@ -29,14 +29,14 @@ public static Thought GetLeadingThoughtInGroup(List thoughtsInGroup) public static void GetThoughtGroupsInDisplayOrder(Need_Mood mood, List outThoughtGroupsPresent) { mood.thoughts.GetDistinctMoodThoughtGroups(outThoughtGroupsPresent); - for (int i = outThoughtGroupsPresent.Count - 1; i >= 0; i--) + for (int num = outThoughtGroupsPresent.Count - 1; num >= 0; num--) { - if (!outThoughtGroupsPresent[i].VisibleInNeedsTab) + if (!outThoughtGroupsPresent[num].VisibleInNeedsTab) { - outThoughtGroupsPresent.RemoveAt(i); + outThoughtGroupsPresent.RemoveAt(num); } } - outThoughtGroupsPresent.SortByDescending((Thought t) => mood.thoughts.MoodOffsetOfGroup(t), (Thought t) => t.GetHashCode()); + outThoughtGroupsPresent.SortByDescending((Func)((Thought t) => mood.thoughts.MoodOffsetOfGroup(t)), (Func)((Thought t) => t.GetHashCode())); } } } diff --git a/Assembly-CSharp/RimWorld/PawnObserver.cs b/Assembly-CSharp/RimWorld/PawnObserver.cs index 42a6ea36d..1b7b2066d 100644 --- a/Assembly-CSharp/RimWorld/PawnObserver.cs +++ b/Assembly-CSharp/RimWorld/PawnObserver.cs @@ -1,4 +1,3 @@ -using System; using System.Collections.Generic; using Verse; @@ -22,53 +21,45 @@ public PawnObserver(Pawn pawn) public void ObserverInterval() { - if (!this.pawn.Spawned) + if (this.pawn.Spawned) { - return; - } - this.intervalsUntilObserve--; - if (this.intervalsUntilObserve <= 0) - { - this.ObserveSurroundingThings(); - this.intervalsUntilObserve = 4 + Rand.RangeInclusive(-1, 1); + this.intervalsUntilObserve--; + if (this.intervalsUntilObserve <= 0) + { + this.ObserveSurroundingThings(); + this.intervalsUntilObserve = 4 + Rand.RangeInclusive(-1, 1); + } } } private void ObserveSurroundingThings() { - if (!this.pawn.health.capacities.CapableOf(PawnCapacityDefOf.Sight)) - { - return; - } - RoomGroup roomGroup = this.pawn.GetRoomGroup(); - Map map = this.pawn.Map; - int num = 0; - while ((float)num < 100f) + if (this.pawn.health.capacities.CapableOf(PawnCapacityDefOf.Sight)) { - IntVec3 intVec = this.pawn.Position + GenRadial.RadialPattern[num]; - if (intVec.InBounds(map)) + RoomGroup roomGroup = this.pawn.GetRoomGroup(); + Map map = this.pawn.Map; + int num = 0; + while ((float)num < 100.0) { - if (intVec.GetRoomGroup(map) == roomGroup) + IntVec3 intVec = this.pawn.Position + GenRadial.RadialPattern[num]; + if (intVec.InBounds(map) && intVec.GetRoomGroup(map) == roomGroup && GenSight.LineOfSight(intVec, this.pawn.Position, map, true, null, 0, 0)) { - if (GenSight.LineOfSight(intVec, this.pawn.Position, map, true, null, 0, 0)) + List thingList = intVec.GetThingList(map); + for (int i = 0; i < thingList.Count; i++) { - List thingList = intVec.GetThingList(map); - for (int i = 0; i < thingList.Count; i++) + IThoughtGiver thoughtGiver = thingList[i] as IThoughtGiver; + if (thoughtGiver != null) { - IThoughtGiver thoughtGiver = thingList[i] as IThoughtGiver; - if (thoughtGiver != null) + Thought_Memory thought_Memory = thoughtGiver.GiveObservedThought(); + if (thought_Memory != null) { - Thought_Memory thought_Memory = thoughtGiver.GiveObservedThought(); - if (thought_Memory != null) - { - this.pawn.needs.mood.thoughts.memories.TryGainMemory(thought_Memory, null); - } + this.pawn.needs.mood.thoughts.memories.TryGainMemory(thought_Memory, null); } } } } + num++; } - num++; } } } diff --git a/Assembly-CSharp/RimWorld/PawnPosture.cs b/Assembly-CSharp/RimWorld/PawnPosture.cs index 0c1c99513..2af5e8e06 100644 --- a/Assembly-CSharp/RimWorld/PawnPosture.cs +++ b/Assembly-CSharp/RimWorld/PawnPosture.cs @@ -1,11 +1,9 @@ -using System; - namespace RimWorld { public enum PawnPosture : byte { - Standing, - LayingFaceUp, - LayingAny + Standing = 0, + LayingFaceUp = 1, + LayingAny = 2 } } diff --git a/Assembly-CSharp/RimWorld/PawnRecentMemory.cs b/Assembly-CSharp/RimWorld/PawnRecentMemory.cs index 325e27e79..78fd44f88 100644 --- a/Assembly-CSharp/RimWorld/PawnRecentMemory.cs +++ b/Assembly-CSharp/RimWorld/PawnRecentMemory.cs @@ -1,4 +1,3 @@ -using System; using Verse; namespace RimWorld @@ -40,17 +39,16 @@ public void ExposeData() public void RecentMemoryInterval() { - if (!this.pawn.Spawned) + if (this.pawn.Spawned) { - return; - } - if (this.pawn.Map.glowGrid.PsychGlowAt(this.pawn.Position) != PsychGlow.Dark) - { - this.lastLightTick = Find.TickManager.TicksGame; - } - if (this.Outdoors()) - { - this.lastOutdoorTick = Find.TickManager.TicksGame; + if (this.pawn.Map.glowGrid.PsychGlowAt(this.pawn.Position) != 0) + { + this.lastLightTick = Find.TickManager.TicksGame; + } + if (this.Outdoors()) + { + this.lastOutdoorTick = Find.TickManager.TicksGame; + } } } diff --git a/Assembly-CSharp/RimWorld/PawnRelationDef.cs b/Assembly-CSharp/RimWorld/PawnRelationDef.cs index 59d7bb4d7..d33e8ead0 100644 --- a/Assembly-CSharp/RimWorld/PawnRelationDef.cs +++ b/Assembly-CSharp/RimWorld/PawnRelationDef.cs @@ -1,6 +1,5 @@ using System; using System.Collections.Generic; -using System.Diagnostics; using Verse; namespace RimWorld @@ -60,7 +59,7 @@ public string GetGenderSpecificLabel(Pawn pawn) { return this.labelFemale; } - return this.label; + return base.label; } public string GetGenderSpecificLabelCap(Pawn pawn) @@ -86,14 +85,17 @@ public ThoughtDef GetGenderSpecificKilledThought(Pawn killed) return this.killedThought; } - [DebuggerHidden] public override IEnumerable ConfigErrors() { - PawnRelationDef.c__Iterator92 c__Iterator = new PawnRelationDef.c__Iterator92(); - c__Iterator.<>f__this = this; - PawnRelationDef.c__Iterator92 expr_0E = c__Iterator; - expr_0E.$PC = -2; - return expr_0E; + foreach (string item in base.ConfigErrors()) + { + yield return item; + } + if (this.implied && this.reflexive) + { + yield return base.defName + ": implied relations can't use the \"reflexive\" option."; + this.reflexive = false; + } } } } diff --git a/Assembly-CSharp/RimWorld/PawnRelationDefOf.cs b/Assembly-CSharp/RimWorld/PawnRelationDefOf.cs index 084e13557..4ab6b66ba 100644 --- a/Assembly-CSharp/RimWorld/PawnRelationDefOf.cs +++ b/Assembly-CSharp/RimWorld/PawnRelationDefOf.cs @@ -1,5 +1,3 @@ -using System; - namespace RimWorld { [DefOf] diff --git a/Assembly-CSharp/RimWorld/PawnRelationUtility.cs b/Assembly-CSharp/RimWorld/PawnRelationUtility.cs index 0726bd356..2da4236d3 100644 --- a/Assembly-CSharp/RimWorld/PawnRelationUtility.cs +++ b/Assembly-CSharp/RimWorld/PawnRelationUtility.cs @@ -1,6 +1,5 @@ using System; using System.Collections.Generic; -using System.Diagnostics; using System.Linq; using System.Text; using UnityEngine; @@ -10,27 +9,58 @@ namespace RimWorld { public static class PawnRelationUtility { - [DebuggerHidden] public static IEnumerable GetRelations(this Pawn me, Pawn other) { - PawnRelationUtility.c__IteratorDA c__IteratorDA = new PawnRelationUtility.c__IteratorDA(); - c__IteratorDA.me = me; - c__IteratorDA.other = other; - c__IteratorDA.<$>me = me; - c__IteratorDA.<$>other = other; - PawnRelationUtility.c__IteratorDA expr_23 = c__IteratorDA; - expr_23.$PC = -2; - return expr_23; + if (me != other && me.RaceProps.IsFlesh && other.RaceProps.IsFlesh && me.relations.RelatedToAnyoneOrAnyoneRelatedToMe && other.relations.RelatedToAnyoneOrAnyoneRelatedToMe) + { + ProfilerThreadCheck.BeginSample("GetRelations()"); + try + { + bool isKin = false; + bool anyNonKinFamilyByBloodRelation = false; + List defs = DefDatabase.AllDefsListForReading; + int i = 0; + int count = defs.Count; + while (i < count) + { + PawnRelationDef def = defs[i]; + if (def.Worker.InRelation(me, other)) + { + if (def == PawnRelationDefOf.Kin) + { + isKin = true; + } + else + { + if (def.familyByBloodRelation) + { + anyNonKinFamilyByBloodRelation = true; + } + yield return def; + } + } + i++; + } + if (isKin && !anyNonKinFamilyByBloodRelation) + { + yield return PawnRelationDefOf.Kin; + } + } + finally + { + ((_003CGetRelations_003Ec__IteratorDA)/*Error near IL_01ca: stateMachine*/)._003C_003E__Finally0(); + } + } } public static PawnRelationDef GetMostImportantRelation(this Pawn me, Pawn other) { PawnRelationDef pawnRelationDef = null; - foreach (PawnRelationDef current in me.GetRelations(other)) + foreach (PawnRelationDef relation in me.GetRelations(other)) { - if (pawnRelationDef == null || current.importance > pawnRelationDef.importance) + if (pawnRelationDef == null || relation.importance > pawnRelationDef.importance) { - pawnRelationDef = current; + pawnRelationDef = relation; } } return pawnRelationDef; @@ -52,14 +82,14 @@ where x.RaceProps.IsFlesh select x; } bool flag = false; - foreach (Pawn current in enumerable) + foreach (Pawn item in enumerable) { bool flag2 = false; - foreach (Pawn current2 in enumerable2) + foreach (Pawn item2 in enumerable2) { - if (current != current2) + if (item != item2) { - PawnRelationDef mostImportantRelation = current.GetMostImportantRelation(current2); + PawnRelationDef mostImportantRelation = item.GetMostImportantRelation(item2); if (mostImportantRelation != null) { if (!flag2) @@ -69,19 +99,11 @@ where x.RaceProps.IsFlesh { stringBuilder.AppendLine(); } - stringBuilder.AppendLine(current.KindLabel.CapitalizeFirst() + " " + current.LabelShort + ":"); + stringBuilder.AppendLine(item.KindLabel.CapitalizeFirst() + " " + item.LabelShort + ":"); } flag = true; - stringBuilder.AppendLine(string.Concat(new string[] - { - " ", - mostImportantRelation.GetGenderSpecificLabelCap(current2), - " - ", - current2.KindLabel, - " ", - current2.LabelShort - })); - current.relations.everSeenByPlayer = true; + stringBuilder.AppendLine(" " + mostImportantRelation.GetGenderSpecificLabelCap(item2) + " - " + item2.KindLabel + " " + item2.LabelShort); + item.relations.everSeenByPlayer = true; } } } @@ -92,13 +114,13 @@ where x.RaceProps.IsFlesh } else { - pawnRelationsInfo = null; + pawnRelationsInfo = (string)null; } } public static void Notify_PawnsSeenByPlayer(IEnumerable seenPawns, ref string letterLabel, ref string letterText, string relationsInfoHeader, bool informEvenIfSeenBefore = false) { - string text; + string text = default(string); PawnRelationUtility.Notify_PawnsSeenByPlayer(seenPawns, out text, informEvenIfSeenBefore); if (!text.NullOrEmpty()) { @@ -120,7 +142,7 @@ public static void Notify_PawnsSeenByPlayer(IEnumerable seenPawns, ref str public static bool TryAppendRelationsWithColonistsInfo(ref string text, Pawn pawn) { - string text2 = null; + string text2 = (string)null; return PawnRelationUtility.TryAppendRelationsWithColonistsInfo(ref text, ref text2, pawn); } @@ -136,24 +158,9 @@ public static bool TryAppendRelationsWithColonistsInfo(ref string text, ref stri title = title + " " + "RelationshipAppendedLetterSuffix".Translate(); } string genderSpecificLabel = mostImportantColonyRelative.GetMostImportantRelation(pawn).GetGenderSpecificLabel(pawn); - string text2 = "\n\n"; - if (mostImportantColonyRelative.IsColonist) - { - text2 += "RelationshipAppendedLetterTextColonist".Translate(new object[] - { - mostImportantColonyRelative.LabelShort, - genderSpecificLabel - }); - } - else - { - text2 += "RelationshipAppendedLetterTextPrisoner".Translate(new object[] - { - mostImportantColonyRelative.LabelShort, - genderSpecificLabel - }); - } - text += text2.AdjustedFor(pawn); + string str = "\n\n"; + str = ((!mostImportantColonyRelative.IsColonist) ? (str + "RelationshipAppendedLetterTextPrisoner".Translate(mostImportantColonyRelative.LabelShort, genderSpecificLabel)) : (str + "RelationshipAppendedLetterTextColonist".Translate(mostImportantColonyRelative.LabelShort, genderSpecificLabel))); + text += str.AdjustedFor(pawn); return true; } @@ -164,16 +171,13 @@ where x.relations.everSeenByPlayer select x; float num = 0f; Pawn pawn2 = null; - foreach (Pawn current in enumerable) + foreach (Pawn item in enumerable) { - PawnRelationDef mostImportantRelation = pawn.GetMostImportantRelation(current); - if (mostImportantRelation != null) + PawnRelationDef mostImportantRelation = pawn.GetMostImportantRelation(item); + if (mostImportantRelation != null && (pawn2 == null || mostImportantRelation.importance > num)) { - if (pawn2 == null || mostImportantRelation.importance > num) - { - num = mostImportantRelation.importance; - pawn2 = current; - } + num = mostImportantRelation.importance; + pawn2 = item; } } return pawn2; @@ -182,7 +186,7 @@ where x.relations.everSeenByPlayer public static float MaxPossibleBioAgeAt(float myBiologicalAge, float myChronologicalAge, float atChronologicalAge) { float num = Mathf.Min(myBiologicalAge, myChronologicalAge - atChronologicalAge); - if (num < 0f) + if (num < 0.0) { return -1f; } diff --git a/Assembly-CSharp/RimWorld/PawnRelationWorker.cs b/Assembly-CSharp/RimWorld/PawnRelationWorker.cs index 48e726da8..8e3c16690 100644 --- a/Assembly-CSharp/RimWorld/PawnRelationWorker.cs +++ b/Assembly-CSharp/RimWorld/PawnRelationWorker.cs @@ -36,27 +36,34 @@ public float BaseGenerationChanceFactor(Pawn generated, Pawn other, PawnGenerati float num = 1f; if (generated.Faction != other.Faction) { - num *= 0.65f; + num = (float)(num * 0.64999997615814209); } if (generated.HostileTo(other)) { - num *= 0.7f; + num = (float)(num * 0.699999988079071); } if (other.Faction != null && other.Faction.IsPlayer) { num *= request.ColonistRelationChanceFactor; } - TechLevel techLevel = (generated.Faction == null) ? TechLevel.Undefined : generated.Faction.def.techLevel; - TechLevel techLevel2 = (other.Faction == null) ? TechLevel.Undefined : other.Faction.def.techLevel; - if (techLevel != TechLevel.Undefined && techLevel2 != TechLevel.Undefined && techLevel != techLevel2) + TechLevel techLevel = (generated.Faction != null) ? generated.Faction.def.techLevel : TechLevel.Undefined; + TechLevel techLevel2 = (other.Faction != null) ? other.Faction.def.techLevel : TechLevel.Undefined; + if (techLevel != 0 && techLevel2 != 0 && techLevel != techLevel2) { - num *= 0.85f; + num = (float)(num * 0.85000002384185791); } - if ((techLevel.IsNeolithicOrWorse() && !techLevel2.IsNeolithicOrWorse()) || (!techLevel.IsNeolithicOrWorse() && techLevel2.IsNeolithicOrWorse())) + if (techLevel.IsNeolithicOrWorse() && !techLevel2.IsNeolithicOrWorse()) { - num *= 0.03f; + goto IL_00e3; } + if (!techLevel.IsNeolithicOrWorse() && techLevel2.IsNeolithicOrWorse()) + goto IL_00e3; + goto IL_00eb; + IL_00eb: return num; + IL_00e3: + num = (float)(num * 0.029999999329447746); + goto IL_00eb; } } } diff --git a/Assembly-CSharp/RimWorld/PawnRelationWorker_Child.cs b/Assembly-CSharp/RimWorld/PawnRelationWorker_Child.cs index 1cfbb8ba2..10e6c550d 100644 --- a/Assembly-CSharp/RimWorld/PawnRelationWorker_Child.cs +++ b/Assembly-CSharp/RimWorld/PawnRelationWorker_Child.cs @@ -1,4 +1,3 @@ -using System; using Verse; namespace RimWorld @@ -7,7 +6,11 @@ public class PawnRelationWorker_Child : PawnRelationWorker { public override bool InRelation(Pawn me, Pawn other) { - return me != other && (other.GetMother() == me || other.GetFather() == me); + if (me == other) + { + return false; + } + return other.GetMother() == me || other.GetFather() == me; } public override float GenerationChance(Pawn generated, Pawn other, PawnGenerationRequest request) @@ -15,11 +18,11 @@ public override float GenerationChance(Pawn generated, Pawn other, PawnGeneratio float num = 0f; if (generated.gender == Gender.Male) { - num = ChildRelationUtility.ChanceOfBecomingChildOf(other, generated, other.GetMother(), null, new PawnGenerationRequest?(request), null); + num = ChildRelationUtility.ChanceOfBecomingChildOf(other, generated, other.GetMother(), default(PawnGenerationRequest?), new PawnGenerationRequest?(request), default(PawnGenerationRequest?)); } else if (generated.gender == Gender.Female) { - num = ChildRelationUtility.ChanceOfBecomingChildOf(other, other.GetFather(), generated, null, null, new PawnGenerationRequest?(request)); + num = ChildRelationUtility.ChanceOfBecomingChildOf(other, other.GetFather(), generated, default(PawnGenerationRequest?), default(PawnGenerationRequest?), new PawnGenerationRequest?(request)); } return num * base.BaseGenerationChanceFactor(generated, other, request); } @@ -37,10 +40,10 @@ public override void CreateRelation(Pawn generated, Pawn other, ref PawnGenerati { generated.relations.AddDirectRelation(PawnRelationDefOf.ExLover, other.GetMother()); } - else if (Rand.Value < 0.85f && !LovePartnerRelationUtility.HasAnyLovePartner(other.GetMother())) + else if (Rand.Value < 0.85000002384185791 && !LovePartnerRelationUtility.HasAnyLovePartner(other.GetMother())) { generated.relations.AddDirectRelation(PawnRelationDefOf.Spouse, other.GetMother()); - if (request.FixedLastName == null && Rand.Value < 0.8f) + if (request.FixedLastName == null && Rand.Value < 0.800000011920929) { request.SetFixedLastName(((NameTriple)other.GetMother().Name).Last); } @@ -62,10 +65,10 @@ public override void CreateRelation(Pawn generated, Pawn other, ref PawnGenerati { generated.relations.AddDirectRelation(PawnRelationDefOf.ExLover, other.GetFather()); } - else if (Rand.Value < 0.85f && !LovePartnerRelationUtility.HasAnyLovePartner(other.GetFather())) + else if (Rand.Value < 0.85000002384185791 && !LovePartnerRelationUtility.HasAnyLovePartner(other.GetFather())) { generated.relations.AddDirectRelation(PawnRelationDefOf.Spouse, other.GetFather()); - if (request.FixedLastName == null && Rand.Value < 0.8f) + if (request.FixedLastName == null && Rand.Value < 0.800000011920929) { request.SetFixedLastName(((NameTriple)other.GetFather().Name).Last); } @@ -80,15 +83,7 @@ public override void CreateRelation(Pawn generated, Pawn other, ref PawnGenerati private static void ResolveMyName(ref PawnGenerationRequest request, Pawn child, Pawn otherParent) { - if (request.FixedLastName != null) - { - return; - } - if (ChildRelationUtility.DefinitelyHasNotBirthName(child)) - { - return; - } - if (ChildRelationUtility.ChildWantsNameOfAnyParent(child)) + if (request.FixedLastName == null && !ChildRelationUtility.DefinitelyHasNotBirthName(child) && ChildRelationUtility.ChildWantsNameOfAnyParent(child)) { if (otherParent == null) { @@ -112,17 +107,16 @@ private static void ResolveMyName(ref PawnGenerationRequest request, Pawn child, private static void ResolveMySkinColor(ref PawnGenerationRequest request, Pawn child, Pawn otherParent) { - if (request.FixedMelanin.HasValue) - { - return; - } - if (otherParent != null) + if (!request.FixedMelanin.HasValue) { - request.SetFixedMelanin(ParentRelationUtility.GetRandomSecondParentSkinColor(otherParent.story.melanin, child.story.melanin, null)); - } - else - { - request.SetFixedMelanin(PawnSkinColors.GetRandomMelaninSimilarTo(child.story.melanin, 0f, 1f)); + if (otherParent != null) + { + request.SetFixedMelanin(ParentRelationUtility.GetRandomSecondParentSkinColor(otherParent.story.melanin, child.story.melanin, default(float?))); + } + else + { + request.SetFixedMelanin(PawnSkinColors.GetRandomMelaninSimilarTo(child.story.melanin, 0f, 1f)); + } } } } diff --git a/Assembly-CSharp/RimWorld/PawnRelationWorker_ChildInLaw.cs b/Assembly-CSharp/RimWorld/PawnRelationWorker_ChildInLaw.cs index 68e420f1c..c64f805bf 100644 --- a/Assembly-CSharp/RimWorld/PawnRelationWorker_ChildInLaw.cs +++ b/Assembly-CSharp/RimWorld/PawnRelationWorker_ChildInLaw.cs @@ -1,4 +1,3 @@ -using System; using Verse; namespace RimWorld @@ -16,7 +15,11 @@ public override bool InRelation(Pawn me, Pawn other) return false; } PawnRelationWorker worker = PawnRelationDefOf.Child.Worker; - return !worker.InRelation(me, other) && worker.InRelation(me, other.GetSpouse()); + if (worker.InRelation(me, other)) + { + return false; + } + return worker.InRelation(me, other.GetSpouse()); } } } diff --git a/Assembly-CSharp/RimWorld/PawnRelationWorker_Cousin.cs b/Assembly-CSharp/RimWorld/PawnRelationWorker_Cousin.cs index a849f7395..734de9f44 100644 --- a/Assembly-CSharp/RimWorld/PawnRelationWorker_Cousin.cs +++ b/Assembly-CSharp/RimWorld/PawnRelationWorker_Cousin.cs @@ -1,4 +1,3 @@ -using System; using Verse; namespace RimWorld @@ -12,7 +11,15 @@ public override bool InRelation(Pawn me, Pawn other) return false; } PawnRelationWorker worker = PawnRelationDefOf.UncleOrAunt.Worker; - return (other.GetMother() != null && worker.InRelation(me, other.GetMother())) || (other.GetFather() != null && worker.InRelation(me, other.GetFather())); + if (other.GetMother() != null && worker.InRelation(me, other.GetMother())) + { + goto IL_004e; + } + if (other.GetFather() != null && worker.InRelation(me, other.GetFather())) + goto IL_004e; + return false; + IL_004e: + return true; } } } diff --git a/Assembly-CSharp/RimWorld/PawnRelationWorker_CousinOnceRemoved.cs b/Assembly-CSharp/RimWorld/PawnRelationWorker_CousinOnceRemoved.cs index 5562f8f43..49468e1a7 100644 --- a/Assembly-CSharp/RimWorld/PawnRelationWorker_CousinOnceRemoved.cs +++ b/Assembly-CSharp/RimWorld/PawnRelationWorker_CousinOnceRemoved.cs @@ -1,4 +1,3 @@ -using System; using Verse; namespace RimWorld @@ -12,12 +11,24 @@ public override bool InRelation(Pawn me, Pawn other) return false; } PawnRelationWorker worker = PawnRelationDefOf.Cousin.Worker; - if ((other.GetMother() != null && worker.InRelation(me, other.GetMother())) || (other.GetFather() != null && worker.InRelation(me, other.GetFather()))) + if (other.GetMother() != null && worker.InRelation(me, other.GetMother())) { - return true; + goto IL_004e; } + if (other.GetFather() != null && worker.InRelation(me, other.GetFather())) + goto IL_004e; PawnRelationWorker worker2 = PawnRelationDefOf.GranduncleOrGrandaunt.Worker; - return (other.GetMother() != null && worker2.InRelation(me, other.GetMother())) || (other.GetFather() != null && worker2.InRelation(me, other.GetFather())); + if (other.GetMother() != null && worker2.InRelation(me, other.GetMother())) + { + goto IL_0095; + } + if (other.GetFather() != null && worker2.InRelation(me, other.GetFather())) + goto IL_0095; + return false; + IL_0095: + return true; + IL_004e: + return true; } } } diff --git a/Assembly-CSharp/RimWorld/PawnRelationWorker_ExLover.cs b/Assembly-CSharp/RimWorld/PawnRelationWorker_ExLover.cs index c71d4ca06..f76ae4030 100644 --- a/Assembly-CSharp/RimWorld/PawnRelationWorker_ExLover.cs +++ b/Assembly-CSharp/RimWorld/PawnRelationWorker_ExLover.cs @@ -1,4 +1,3 @@ -using System; using Verse; namespace RimWorld @@ -19,11 +18,10 @@ public override void CreateRelation(Pawn generated, Pawn other, ref PawnGenerati private static void ResolveMySkinColor(ref PawnGenerationRequest request, Pawn generated, Pawn other) { - if (request.FixedMelanin.HasValue) + if (!request.FixedMelanin.HasValue) { - return; + request.SetFixedMelanin(PawnSkinColors.GetRandomMelaninSimilarTo(other.story.melanin, 0f, 1f)); } - request.SetFixedMelanin(PawnSkinColors.GetRandomMelaninSimilarTo(other.story.melanin, 0f, 1f)); } } } diff --git a/Assembly-CSharp/RimWorld/PawnRelationWorker_ExSpouse.cs b/Assembly-CSharp/RimWorld/PawnRelationWorker_ExSpouse.cs index 640de0baf..3b36a8157 100644 --- a/Assembly-CSharp/RimWorld/PawnRelationWorker_ExSpouse.cs +++ b/Assembly-CSharp/RimWorld/PawnRelationWorker_ExSpouse.cs @@ -1,4 +1,3 @@ -using System; using Verse; namespace RimWorld @@ -19,11 +18,10 @@ public override void CreateRelation(Pawn generated, Pawn other, ref PawnGenerati private static void ResolveMySkinColor(ref PawnGenerationRequest request, Pawn generated, Pawn other) { - if (request.FixedMelanin.HasValue) + if (!request.FixedMelanin.HasValue) { - return; + request.SetFixedMelanin(PawnSkinColors.GetRandomMelaninSimilarTo(other.story.melanin, 0f, 1f)); } - request.SetFixedMelanin(PawnSkinColors.GetRandomMelaninSimilarTo(other.story.melanin, 0f, 1f)); } } } diff --git a/Assembly-CSharp/RimWorld/PawnRelationWorker_Fiance.cs b/Assembly-CSharp/RimWorld/PawnRelationWorker_Fiance.cs index 79fdb5fac..69656aba4 100644 --- a/Assembly-CSharp/RimWorld/PawnRelationWorker_Fiance.cs +++ b/Assembly-CSharp/RimWorld/PawnRelationWorker_Fiance.cs @@ -1,4 +1,3 @@ -using System; using UnityEngine; using Verse; @@ -28,11 +27,10 @@ private float GetOldAgeFactor(Pawn pawn) private static void ResolveMySkinColor(ref PawnGenerationRequest request, Pawn generated, Pawn other) { - if (request.FixedMelanin.HasValue) + if (!request.FixedMelanin.HasValue) { - return; + request.SetFixedMelanin(PawnSkinColors.GetRandomMelaninSimilarTo(other.story.melanin, 0f, 1f)); } - request.SetFixedMelanin(PawnSkinColors.GetRandomMelaninSimilarTo(other.story.melanin, 0f, 1f)); } } } diff --git a/Assembly-CSharp/RimWorld/PawnRelationWorker_Grandchild.cs b/Assembly-CSharp/RimWorld/PawnRelationWorker_Grandchild.cs index f56e58814..7e11d734e 100644 --- a/Assembly-CSharp/RimWorld/PawnRelationWorker_Grandchild.cs +++ b/Assembly-CSharp/RimWorld/PawnRelationWorker_Grandchild.cs @@ -1,4 +1,3 @@ -using System; using Verse; namespace RimWorld @@ -12,7 +11,15 @@ public override bool InRelation(Pawn me, Pawn other) return false; } PawnRelationWorker worker = PawnRelationDefOf.Child.Worker; - return (other.GetMother() != null && worker.InRelation(me, other.GetMother())) || (other.GetFather() != null && worker.InRelation(me, other.GetFather())); + if (other.GetMother() != null && worker.InRelation(me, other.GetMother())) + { + goto IL_004e; + } + if (other.GetFather() != null && worker.InRelation(me, other.GetFather())) + goto IL_004e; + return false; + IL_004e: + return true; } } } diff --git a/Assembly-CSharp/RimWorld/PawnRelationWorker_GrandnephewOrGrandniece.cs b/Assembly-CSharp/RimWorld/PawnRelationWorker_GrandnephewOrGrandniece.cs index 82c2b25f0..7e8ff0c7b 100644 --- a/Assembly-CSharp/RimWorld/PawnRelationWorker_GrandnephewOrGrandniece.cs +++ b/Assembly-CSharp/RimWorld/PawnRelationWorker_GrandnephewOrGrandniece.cs @@ -1,4 +1,3 @@ -using System; using Verse; namespace RimWorld @@ -12,7 +11,15 @@ public override bool InRelation(Pawn me, Pawn other) return false; } PawnRelationWorker worker = PawnRelationDefOf.NephewOrNiece.Worker; - return (other.GetMother() != null && worker.InRelation(me, other.GetMother())) || (other.GetFather() != null && worker.InRelation(me, other.GetFather())); + if (other.GetMother() != null && worker.InRelation(me, other.GetMother())) + { + goto IL_004e; + } + if (other.GetFather() != null && worker.InRelation(me, other.GetFather())) + goto IL_004e; + return false; + IL_004e: + return true; } } } diff --git a/Assembly-CSharp/RimWorld/PawnRelationWorker_Grandparent.cs b/Assembly-CSharp/RimWorld/PawnRelationWorker_Grandparent.cs index cba9ef0a0..e06b0297c 100644 --- a/Assembly-CSharp/RimWorld/PawnRelationWorker_Grandparent.cs +++ b/Assembly-CSharp/RimWorld/PawnRelationWorker_Grandparent.cs @@ -1,4 +1,3 @@ -using System; using Verse; namespace RimWorld @@ -7,7 +6,11 @@ public class PawnRelationWorker_Grandparent : PawnRelationWorker { public override bool InRelation(Pawn me, Pawn other) { - return me != other && PawnRelationDefOf.Grandchild.Worker.InRelation(other, me); + if (me == other) + { + return false; + } + return PawnRelationDefOf.Grandchild.Worker.InRelation(other, me); } } } diff --git a/Assembly-CSharp/RimWorld/PawnRelationWorker_GranduncleOrGrandaunt.cs b/Assembly-CSharp/RimWorld/PawnRelationWorker_GranduncleOrGrandaunt.cs index f8ebdf633..e4e0e66f5 100644 --- a/Assembly-CSharp/RimWorld/PawnRelationWorker_GranduncleOrGrandaunt.cs +++ b/Assembly-CSharp/RimWorld/PawnRelationWorker_GranduncleOrGrandaunt.cs @@ -1,4 +1,3 @@ -using System; using Verse; namespace RimWorld @@ -16,7 +15,15 @@ public override bool InRelation(Pawn me, Pawn other) return false; } PawnRelationWorker worker = PawnRelationDefOf.GreatGrandparent.Worker; - return (other.GetMother() != null && worker.InRelation(me, other.GetMother())) || (other.GetFather() != null && worker.InRelation(me, other.GetFather())); + if (other.GetMother() != null && worker.InRelation(me, other.GetMother())) + { + goto IL_0066; + } + if (other.GetFather() != null && worker.InRelation(me, other.GetFather())) + goto IL_0066; + return false; + IL_0066: + return true; } } } diff --git a/Assembly-CSharp/RimWorld/PawnRelationWorker_GreatGrandchild.cs b/Assembly-CSharp/RimWorld/PawnRelationWorker_GreatGrandchild.cs index 7c6bdf7cb..4b09ca187 100644 --- a/Assembly-CSharp/RimWorld/PawnRelationWorker_GreatGrandchild.cs +++ b/Assembly-CSharp/RimWorld/PawnRelationWorker_GreatGrandchild.cs @@ -1,4 +1,3 @@ -using System; using Verse; namespace RimWorld @@ -12,7 +11,15 @@ public override bool InRelation(Pawn me, Pawn other) return false; } PawnRelationWorker worker = PawnRelationDefOf.Grandchild.Worker; - return (other.GetMother() != null && worker.InRelation(me, other.GetMother())) || (other.GetFather() != null && worker.InRelation(me, other.GetFather())); + if (other.GetMother() != null && worker.InRelation(me, other.GetMother())) + { + goto IL_004e; + } + if (other.GetFather() != null && worker.InRelation(me, other.GetFather())) + goto IL_004e; + return false; + IL_004e: + return true; } } } diff --git a/Assembly-CSharp/RimWorld/PawnRelationWorker_GreatGrandparent.cs b/Assembly-CSharp/RimWorld/PawnRelationWorker_GreatGrandparent.cs index 279d89b16..2a32ae2da 100644 --- a/Assembly-CSharp/RimWorld/PawnRelationWorker_GreatGrandparent.cs +++ b/Assembly-CSharp/RimWorld/PawnRelationWorker_GreatGrandparent.cs @@ -1,4 +1,3 @@ -using System; using Verse; namespace RimWorld @@ -7,7 +6,11 @@ public class PawnRelationWorker_GreatGrandparent : PawnRelationWorker { public override bool InRelation(Pawn me, Pawn other) { - return me != other && PawnRelationDefOf.GreatGrandchild.Worker.InRelation(other, me); + if (me == other) + { + return false; + } + return PawnRelationDefOf.GreatGrandchild.Worker.InRelation(other, me); } } } diff --git a/Assembly-CSharp/RimWorld/PawnRelationWorker_HalfSibling.cs b/Assembly-CSharp/RimWorld/PawnRelationWorker_HalfSibling.cs index 0a8d33537..b7440fb28 100644 --- a/Assembly-CSharp/RimWorld/PawnRelationWorker_HalfSibling.cs +++ b/Assembly-CSharp/RimWorld/PawnRelationWorker_HalfSibling.cs @@ -1,4 +1,3 @@ -using System; using Verse; namespace RimWorld @@ -7,7 +6,23 @@ public class PawnRelationWorker_HalfSibling : PawnRelationWorker { public override bool InRelation(Pawn me, Pawn other) { - return me != other && !PawnRelationDefOf.Sibling.Worker.InRelation(me, other) && ((me.GetMother() != null && me.GetMother() == other.GetMother()) || (me.GetFather() != null && me.GetFather() == other.GetFather())); + if (me == other) + { + return false; + } + if (PawnRelationDefOf.Sibling.Worker.InRelation(me, other)) + { + return false; + } + if (me.GetMother() != null && me.GetMother() == other.GetMother()) + { + goto IL_0059; + } + if (me.GetFather() != null && me.GetFather() == other.GetFather()) + goto IL_0059; + return false; + IL_0059: + return true; } } } diff --git a/Assembly-CSharp/RimWorld/PawnRelationWorker_Kin.cs b/Assembly-CSharp/RimWorld/PawnRelationWorker_Kin.cs index 073d02cce..a4c4cba25 100644 --- a/Assembly-CSharp/RimWorld/PawnRelationWorker_Kin.cs +++ b/Assembly-CSharp/RimWorld/PawnRelationWorker_Kin.cs @@ -1,4 +1,3 @@ -using System; using System.Linq; using Verse; @@ -8,7 +7,11 @@ public class PawnRelationWorker_Kin : PawnRelationWorker { public override bool InRelation(Pawn me, Pawn other) { - return me != other && me.relations.FamilyByBlood.Contains(other); + if (me == other) + { + return false; + } + return me.relations.FamilyByBlood.Contains(other); } } } diff --git a/Assembly-CSharp/RimWorld/PawnRelationWorker_Lover.cs b/Assembly-CSharp/RimWorld/PawnRelationWorker_Lover.cs index b84a0583d..b24a05674 100644 --- a/Assembly-CSharp/RimWorld/PawnRelationWorker_Lover.cs +++ b/Assembly-CSharp/RimWorld/PawnRelationWorker_Lover.cs @@ -1,4 +1,3 @@ -using System; using Verse; namespace RimWorld @@ -19,11 +18,10 @@ public override void CreateRelation(Pawn generated, Pawn other, ref PawnGenerati private static void ResolveMySkinColor(ref PawnGenerationRequest request, Pawn generated, Pawn other) { - if (request.FixedMelanin.HasValue) + if (!request.FixedMelanin.HasValue) { - return; + request.SetFixedMelanin(PawnSkinColors.GetRandomMelaninSimilarTo(other.story.melanin, 0f, 1f)); } - request.SetFixedMelanin(PawnSkinColors.GetRandomMelaninSimilarTo(other.story.melanin, 0f, 1f)); } } } diff --git a/Assembly-CSharp/RimWorld/PawnRelationWorker_NephewOrNiece.cs b/Assembly-CSharp/RimWorld/PawnRelationWorker_NephewOrNiece.cs index 0f4770846..99a276cf2 100644 --- a/Assembly-CSharp/RimWorld/PawnRelationWorker_NephewOrNiece.cs +++ b/Assembly-CSharp/RimWorld/PawnRelationWorker_NephewOrNiece.cs @@ -1,4 +1,3 @@ -using System; using Verse; namespace RimWorld @@ -17,7 +16,17 @@ public override bool InRelation(Pawn me, Pawn other) } PawnRelationWorker worker = PawnRelationDefOf.Sibling.Worker; PawnRelationWorker worker2 = PawnRelationDefOf.HalfSibling.Worker; - return (other.GetMother() != null && (worker.InRelation(me, other.GetMother()) || worker2.InRelation(me, other.GetMother()))) || (other.GetFather() != null && (worker.InRelation(me, other.GetFather()) || worker2.InRelation(me, other.GetFather()))); + if (other.GetMother() != null && (worker.InRelation(me, other.GetMother()) || worker2.InRelation(me, other.GetMother()))) + { + goto IL_0095; + } + if (other.GetFather() != null && (worker.InRelation(me, other.GetFather()) || worker2.InRelation(me, other.GetFather()))) + { + goto IL_0095; + } + return false; + IL_0095: + return true; } } } diff --git a/Assembly-CSharp/RimWorld/PawnRelationWorker_Parent.cs b/Assembly-CSharp/RimWorld/PawnRelationWorker_Parent.cs index d0b065417..72932ed73 100644 --- a/Assembly-CSharp/RimWorld/PawnRelationWorker_Parent.cs +++ b/Assembly-CSharp/RimWorld/PawnRelationWorker_Parent.cs @@ -1,4 +1,3 @@ -using System; using Verse; namespace RimWorld @@ -10,11 +9,11 @@ public override float GenerationChance(Pawn generated, Pawn other, PawnGeneratio float num = 0f; if (other.gender == Gender.Male) { - num = ChildRelationUtility.ChanceOfBecomingChildOf(generated, other, other.GetSpouseOppositeGender(), new PawnGenerationRequest?(request), null, null); + num = ChildRelationUtility.ChanceOfBecomingChildOf(generated, other, other.GetSpouseOppositeGender(), new PawnGenerationRequest?(request), default(PawnGenerationRequest?), default(PawnGenerationRequest?)); } else if (other.gender == Gender.Female) { - num = ChildRelationUtility.ChanceOfBecomingChildOf(generated, other.GetSpouseOppositeGender(), other, new PawnGenerationRequest?(request), null, null); + num = ChildRelationUtility.ChanceOfBecomingChildOf(generated, other.GetSpouseOppositeGender(), other, new PawnGenerationRequest?(request), default(PawnGenerationRequest?), default(PawnGenerationRequest?)); } return num * base.BaseGenerationChanceFactor(generated, other, request); } @@ -47,13 +46,9 @@ public override void CreateRelation(Pawn generated, Pawn other, ref PawnGenerati private static void ResolveMyName(ref PawnGenerationRequest request, Pawn generatedChild) { - if (request.FixedLastName != null) + if (request.FixedLastName == null && ChildRelationUtility.ChildWantsNameOfAnyParent(generatedChild)) { - return; - } - if (ChildRelationUtility.ChildWantsNameOfAnyParent(generatedChild)) - { - bool flag = Rand.Value < 0.5f || generatedChild.GetMother() == null; + bool flag = Rand.Value < 0.5 || generatedChild.GetMother() == null; if (generatedChild.GetFather() == null) { flag = false; @@ -71,21 +66,20 @@ private static void ResolveMyName(ref PawnGenerationRequest request, Pawn genera private static void ResolveMySkinColor(ref PawnGenerationRequest request, Pawn generatedChild) { - if (request.FixedMelanin.HasValue) - { - return; - } - if (generatedChild.GetFather() != null && generatedChild.GetMother() != null) - { - request.SetFixedMelanin(ChildRelationUtility.GetRandomChildSkinColor(generatedChild.GetFather().story.melanin, generatedChild.GetMother().story.melanin)); - } - else if (generatedChild.GetFather() != null) - { - request.SetFixedMelanin(PawnSkinColors.GetRandomMelaninSimilarTo(generatedChild.GetFather().story.melanin, 0f, 1f)); - } - else + if (!request.FixedMelanin.HasValue) { - request.SetFixedMelanin(PawnSkinColors.GetRandomMelaninSimilarTo(generatedChild.GetMother().story.melanin, 0f, 1f)); + if (generatedChild.GetFather() != null && generatedChild.GetMother() != null) + { + request.SetFixedMelanin(ChildRelationUtility.GetRandomChildSkinColor(generatedChild.GetFather().story.melanin, generatedChild.GetMother().story.melanin)); + } + else if (generatedChild.GetFather() != null) + { + request.SetFixedMelanin(PawnSkinColors.GetRandomMelaninSimilarTo(generatedChild.GetFather().story.melanin, 0f, 1f)); + } + else + { + request.SetFixedMelanin(PawnSkinColors.GetRandomMelaninSimilarTo(generatedChild.GetMother().story.melanin, 0f, 1f)); + } } } } diff --git a/Assembly-CSharp/RimWorld/PawnRelationWorker_ParentInLaw.cs b/Assembly-CSharp/RimWorld/PawnRelationWorker_ParentInLaw.cs index f5c34c6de..e29b1b27d 100644 --- a/Assembly-CSharp/RimWorld/PawnRelationWorker_ParentInLaw.cs +++ b/Assembly-CSharp/RimWorld/PawnRelationWorker_ParentInLaw.cs @@ -1,4 +1,3 @@ -using System; using Verse; namespace RimWorld @@ -16,7 +15,11 @@ public override bool InRelation(Pawn me, Pawn other) return false; } PawnRelationWorker worker = PawnRelationDefOf.Parent.Worker; - return !worker.InRelation(me, other) && worker.InRelation(me.GetSpouse(), other); + if (worker.InRelation(me, other)) + { + return false; + } + return worker.InRelation(me.GetSpouse(), other); } } } diff --git a/Assembly-CSharp/RimWorld/PawnRelationWorker_SecondCousin.cs b/Assembly-CSharp/RimWorld/PawnRelationWorker_SecondCousin.cs index 70823af23..d140bda77 100644 --- a/Assembly-CSharp/RimWorld/PawnRelationWorker_SecondCousin.cs +++ b/Assembly-CSharp/RimWorld/PawnRelationWorker_SecondCousin.cs @@ -1,4 +1,3 @@ -using System; using Verse; namespace RimWorld @@ -13,12 +12,30 @@ public override bool InRelation(Pawn me, Pawn other) } PawnRelationWorker worker = PawnRelationDefOf.GranduncleOrGrandaunt.Worker; Pawn mother = other.GetMother(); - if (mother != null && ((mother.GetMother() != null && worker.InRelation(me, mother.GetMother())) || (mother.GetFather() != null && worker.InRelation(me, mother.GetFather())))) + if (mother != null) { - return true; + if (mother.GetMother() != null && worker.InRelation(me, mother.GetMother())) + { + goto IL_005b; + } + if (mother.GetFather() != null && worker.InRelation(me, mother.GetFather())) + goto IL_005b; } Pawn father = other.GetFather(); - return father != null && ((father.GetMother() != null && worker.InRelation(me, father.GetMother())) || (father.GetFather() != null && worker.InRelation(me, father.GetFather()))); + if (father != null) + { + if (father.GetMother() != null && worker.InRelation(me, father.GetMother())) + { + goto IL_00a4; + } + if (father.GetFather() != null && worker.InRelation(me, father.GetFather())) + goto IL_00a4; + } + return false; + IL_005b: + return true; + IL_00a4: + return true; } } } diff --git a/Assembly-CSharp/RimWorld/PawnRelationWorker_Sibling.cs b/Assembly-CSharp/RimWorld/PawnRelationWorker_Sibling.cs index 25f0430a0..438a66e16 100644 --- a/Assembly-CSharp/RimWorld/PawnRelationWorker_Sibling.cs +++ b/Assembly-CSharp/RimWorld/PawnRelationWorker_Sibling.cs @@ -1,5 +1,4 @@ using RimWorld.Planet; -using System; using UnityEngine; using Verse; @@ -9,32 +8,36 @@ public class PawnRelationWorker_Sibling : PawnRelationWorker { public override bool InRelation(Pawn me, Pawn other) { - return me != other && (me.GetMother() != null && me.GetFather() != null && me.GetMother() == other.GetMother() && me.GetFather() == other.GetFather()); + if (me == other) + { + return false; + } + if (me.GetMother() != null && me.GetFather() != null && me.GetMother() == other.GetMother() && me.GetFather() == other.GetFather()) + { + return true; + } + return false; } public override float GenerationChance(Pawn generated, Pawn other, PawnGenerationRequest request) { float num = 1f; float num2 = 1f; - if (other.GetFather() != null || other.GetMother() != null) + if (other.GetFather() == null && other.GetMother() == null) { - num = ChildRelationUtility.ChanceOfBecomingChildOf(generated, other.GetFather(), other.GetMother(), new PawnGenerationRequest?(request), null, null); - } - else if (request.FixedMelanin.HasValue) - { - num2 = ChildRelationUtility.GetMelaninSimilarityFactor(request.FixedMelanin.Value, other.story.melanin); + num2 = ((!request.FixedMelanin.HasValue) ? PawnSkinColors.GetMelaninCommonalityFactor(other.story.melanin) : ChildRelationUtility.GetMelaninSimilarityFactor(request.FixedMelanin.Value, other.story.melanin)); } else { - num2 = PawnSkinColors.GetMelaninCommonalityFactor(other.story.melanin); + num = ChildRelationUtility.ChanceOfBecomingChildOf(generated, other.GetFather(), other.GetMother(), new PawnGenerationRequest?(request), default(PawnGenerationRequest?), default(PawnGenerationRequest?)); } float num3 = Mathf.Abs(generated.ageTracker.AgeChronologicalYearsFloat - other.ageTracker.AgeChronologicalYearsFloat); float num4 = 1f; - if (num3 > 40f) + if (num3 > 40.0) { num4 = 0.2f; } - else if (num3 > 10f) + else if (num3 > 10.0) { num4 = 0.65f; } @@ -45,7 +48,7 @@ public override void CreateRelation(Pawn generated, Pawn other, ref PawnGenerati { bool flag = other.GetMother() != null; bool flag2 = other.GetFather() != null; - bool flag3 = Rand.Value < 0.85f; + bool flag3 = Rand.Value < 0.85000002384185791; if (flag && LovePartnerRelationUtility.HasAnyLovePartner(other.GetMother())) { flag3 = false; @@ -68,8 +71,7 @@ public override void CreateRelation(Pawn generated, Pawn other, ref PawnGenerati generated.SetFather(other.GetFather()); if (!flag || !flag2) { - bool flag4 = other.GetMother().story.traits.HasTrait(TraitDefOf.Gay) || other.GetFather().story.traits.HasTrait(TraitDefOf.Gay); - if (flag4) + if (other.GetMother().story.traits.HasTrait(TraitDefOf.Gay) || other.GetFather().story.traits.HasTrait(TraitDefOf.Gay)) { other.GetFather().relations.AddDirectRelation(PawnRelationDefOf.ExLover, other.GetMother()); } @@ -90,19 +92,19 @@ private static Pawn GenerateParent(Pawn generatedChild, Pawn existingChild, Gend { float ageChronologicalYearsFloat = generatedChild.ageTracker.AgeChronologicalYearsFloat; float ageChronologicalYearsFloat2 = existingChild.ageTracker.AgeChronologicalYearsFloat; - float num = (genderToGenerate != Gender.Male) ? 16f : 14f; - float num2 = (genderToGenerate != Gender.Male) ? 45f : 50f; - float num3 = (genderToGenerate != Gender.Male) ? 27f : 30f; + float num = (float)((genderToGenerate != Gender.Male) ? 16.0 : 14.0); + float num2 = (float)((genderToGenerate != Gender.Male) ? 45.0 : 50.0); + float num3 = (float)((genderToGenerate != Gender.Male) ? 27.0 : 30.0); float num4 = Mathf.Max(ageChronologicalYearsFloat, ageChronologicalYearsFloat2) + num; float maxChronologicalAge = num4 + (num2 - num); float midChronologicalAge = num4 + (num3 - num); - float value; - float value2; - float value3; - string last; + float value = default(float); + float value2 = default(float); + float value3 = default(float); + string last = default(string); PawnRelationWorker_Sibling.GenerateParentParams(num4, maxChronologicalAge, midChronologicalAge, num, generatedChild, existingChild, childRequest, out value, out value2, out value3, out last); bool allowGay = true; - if (newlyGeneratedParentsWillBeSpousesIfNotGay && last.NullOrEmpty() && Rand.Value < 0.8f) + if (newlyGeneratedParentsWillBeSpousesIfNotGay && last.NullOrEmpty() && Rand.Value < 0.800000011920929) { if (genderToGenerate == Gender.Male && existingChild.GetMother() != null && !existingChild.GetMother().story.traits.HasTrait(TraitDefOf.Gay)) { @@ -118,7 +120,7 @@ private static Pawn GenerateParent(Pawn generatedChild, Pawn existingChild, Gend Faction faction = existingChild.Faction; if (faction == null || faction.IsPlayer) { - bool tryMedievalOrBetter = faction != null && faction.def.techLevel >= TechLevel.Medieval; + bool tryMedievalOrBetter = faction != null && (int)faction.def.techLevel >= 3; Find.FactionManager.TryGetRandomNonColonyHumanlikeFaction(out faction, tryMedievalOrBetter, true); } Gender? fixedGender = new Gender?(genderToGenerate); @@ -135,7 +137,7 @@ private static Pawn GenerateParent(Pawn generatedChild, Pawn existingChild, Gend private static void GenerateParentParams(float minChronologicalAge, float maxChronologicalAge, float midChronologicalAge, float minBioAgeToHaveChildren, Pawn generatedChild, Pawn existingChild, PawnGenerationRequest childRequest, out float biologicalAge, out float chronologicalAge, out float melanin, out string lastName) { - chronologicalAge = Rand.GaussianAsymmetric(midChronologicalAge, (midChronologicalAge - minChronologicalAge) / 2f, (maxChronologicalAge - midChronologicalAge) / 2f); + chronologicalAge = Rand.GaussianAsymmetric(midChronologicalAge, (float)((midChronologicalAge - minChronologicalAge) / 2.0), (float)((maxChronologicalAge - midChronologicalAge) / 2.0)); chronologicalAge = Mathf.Clamp(chronologicalAge, minChronologicalAge, maxChronologicalAge); biologicalAge = Rand.Range(minBioAgeToHaveChildren, Mathf.Min(existingChild.RaceProps.lifeExpectancy, chronologicalAge)); if (existingChild.GetFather() != null) @@ -154,7 +156,7 @@ private static void GenerateParentParams(float minChronologicalAge, float maxChr { float num = Mathf.Min(childRequest.FixedMelanin.Value, existingChild.story.melanin); float num2 = Mathf.Max(childRequest.FixedMelanin.Value, existingChild.story.melanin); - if (Rand.Value < 0.5f) + if (Rand.Value < 0.5) { melanin = PawnSkinColors.GetRandomMelaninSimilarTo(num, 0f, num); } @@ -163,12 +165,12 @@ private static void GenerateParentParams(float minChronologicalAge, float maxChr melanin = PawnSkinColors.GetRandomMelaninSimilarTo(num2, num2, 1f); } } - lastName = null; + lastName = (string)null; if (!ChildRelationUtility.DefinitelyHasNotBirthName(existingChild) && ChildRelationUtility.ChildWantsNameOfAnyParent(existingChild)) { if (existingChild.GetMother() == null && existingChild.GetFather() == null) { - if (Rand.Value < 0.5f) + if (Rand.Value < 0.5) { lastName = ((NameTriple)existingChild.Name).Last; } @@ -176,7 +178,7 @@ private static void GenerateParentParams(float minChronologicalAge, float maxChr else { string last = ((NameTriple)existingChild.Name).Last; - string b = null; + string b = (string)null; if (existingChild.GetMother() != null) { b = ((NameTriple)existingChild.GetMother().Name).Last; @@ -195,13 +197,9 @@ private static void GenerateParentParams(float minChronologicalAge, float maxChr private static void ResolveMyName(ref PawnGenerationRequest request, Pawn generated) { - if (request.FixedLastName != null) - { - return; - } - if (ChildRelationUtility.ChildWantsNameOfAnyParent(generated)) + if (request.FixedLastName == null && ChildRelationUtility.ChildWantsNameOfAnyParent(generated)) { - if (Rand.Value < 0.5f) + if (Rand.Value < 0.5) { request.SetFixedLastName(((NameTriple)generated.GetFather().Name).Last); } @@ -214,11 +212,10 @@ private static void ResolveMyName(ref PawnGenerationRequest request, Pawn genera private static void ResolveMySkinColor(ref PawnGenerationRequest request, Pawn generated) { - if (request.FixedMelanin.HasValue) + if (!request.FixedMelanin.HasValue) { - return; + request.SetFixedMelanin(ChildRelationUtility.GetRandomChildSkinColor(generated.GetFather().story.melanin, generated.GetMother().story.melanin)); } - request.SetFixedMelanin(ChildRelationUtility.GetRandomChildSkinColor(generated.GetFather().story.melanin, generated.GetMother().story.melanin)); } } } diff --git a/Assembly-CSharp/RimWorld/PawnRelationWorker_Spouse.cs b/Assembly-CSharp/RimWorld/PawnRelationWorker_Spouse.cs index ed882f9fb..970cb18ed 100644 --- a/Assembly-CSharp/RimWorld/PawnRelationWorker_Spouse.cs +++ b/Assembly-CSharp/RimWorld/PawnRelationWorker_Spouse.cs @@ -1,4 +1,3 @@ -using System; using Verse; namespace RimWorld @@ -20,11 +19,7 @@ public override void CreateRelation(Pawn generated, Pawn other, ref PawnGenerati private static void ResolveMyName(ref PawnGenerationRequest request, Pawn generated) { - if (request.FixedLastName != null) - { - return; - } - if (Rand.Value < 0.8f) + if (request.FixedLastName == null && Rand.Value < 0.800000011920929) { request.SetFixedLastName(((NameTriple)generated.GetSpouse().Name).Last); } @@ -32,11 +27,10 @@ private static void ResolveMyName(ref PawnGenerationRequest request, Pawn genera private static void ResolveMySkinColor(ref PawnGenerationRequest request, Pawn generated, Pawn other) { - if (request.FixedMelanin.HasValue) + if (!request.FixedMelanin.HasValue) { - return; + request.SetFixedMelanin(PawnSkinColors.GetRandomMelaninSimilarTo(other.story.melanin, 0f, 1f)); } - request.SetFixedMelanin(PawnSkinColors.GetRandomMelaninSimilarTo(other.story.melanin, 0f, 1f)); } } } diff --git a/Assembly-CSharp/RimWorld/PawnRelationWorker_Stepchild.cs b/Assembly-CSharp/RimWorld/PawnRelationWorker_Stepchild.cs index 8d78dca72..c65dbcf97 100644 --- a/Assembly-CSharp/RimWorld/PawnRelationWorker_Stepchild.cs +++ b/Assembly-CSharp/RimWorld/PawnRelationWorker_Stepchild.cs @@ -1,4 +1,3 @@ -using System; using Verse; namespace RimWorld @@ -16,7 +15,11 @@ public override bool InRelation(Pawn me, Pawn other) return false; } PawnRelationWorker worker = PawnRelationDefOf.Child.Worker; - return !worker.InRelation(me, other) && worker.InRelation(me.GetSpouse(), other); + if (worker.InRelation(me, other)) + { + return false; + } + return worker.InRelation(me.GetSpouse(), other); } } } diff --git a/Assembly-CSharp/RimWorld/PawnRelationWorker_Stepparent.cs b/Assembly-CSharp/RimWorld/PawnRelationWorker_Stepparent.cs index 7e00ca333..f1e0a6428 100644 --- a/Assembly-CSharp/RimWorld/PawnRelationWorker_Stepparent.cs +++ b/Assembly-CSharp/RimWorld/PawnRelationWorker_Stepparent.cs @@ -1,4 +1,3 @@ -using System; using Verse; namespace RimWorld @@ -16,7 +15,15 @@ public override bool InRelation(Pawn me, Pawn other) return false; } PawnRelationWorker worker = PawnRelationDefOf.Spouse.Worker; - return (me.GetMother() != null && worker.InRelation(me.GetMother(), other)) || (me.GetFather() != null && worker.InRelation(me.GetFather(), other)); + if (me.GetMother() != null && worker.InRelation(me.GetMother(), other)) + { + return true; + } + if (me.GetFather() != null && worker.InRelation(me.GetFather(), other)) + { + return true; + } + return false; } } } diff --git a/Assembly-CSharp/RimWorld/PawnRelationWorker_UncleOrAunt.cs b/Assembly-CSharp/RimWorld/PawnRelationWorker_UncleOrAunt.cs index 296da9091..0369c672c 100644 --- a/Assembly-CSharp/RimWorld/PawnRelationWorker_UncleOrAunt.cs +++ b/Assembly-CSharp/RimWorld/PawnRelationWorker_UncleOrAunt.cs @@ -1,4 +1,3 @@ -using System; using Verse; namespace RimWorld @@ -16,7 +15,15 @@ public override bool InRelation(Pawn me, Pawn other) return false; } PawnRelationWorker worker = PawnRelationDefOf.Grandparent.Worker; - return (other.GetMother() != null && worker.InRelation(me, other.GetMother())) || (other.GetFather() != null && worker.InRelation(me, other.GetFather())); + if (other.GetMother() != null && worker.InRelation(me, other.GetMother())) + { + goto IL_0066; + } + if (other.GetFather() != null && worker.InRelation(me, other.GetFather())) + goto IL_0066; + return false; + IL_0066: + return true; } } } diff --git a/Assembly-CSharp/RimWorld/PawnSkinColors.cs b/Assembly-CSharp/RimWorld/PawnSkinColors.cs index 2246a74f0..d54f721fa 100644 --- a/Assembly-CSharp/RimWorld/PawnSkinColors.cs +++ b/Assembly-CSharp/RimWorld/PawnSkinColors.cs @@ -1,4 +1,3 @@ -using System; using UnityEngine; using Verse; @@ -22,20 +21,20 @@ public SkinColorData(float melanin, float selector, Color color) } } - private static readonly PawnSkinColors.SkinColorData[] SkinColors = new PawnSkinColors.SkinColorData[] + private static readonly SkinColorData[] SkinColors = new SkinColorData[6] { - new PawnSkinColors.SkinColorData(0f, 0f, new Color(0.9490196f, 0.929411769f, 0.8784314f)), - new PawnSkinColors.SkinColorData(0.25f, 0.215f, new Color(1f, 0.9372549f, 0.8352941f)), - new PawnSkinColors.SkinColorData(0.5f, 0.715f, new Color(1f, 0.9372549f, 0.7411765f)), - new PawnSkinColors.SkinColorData(0.75f, 0.8f, new Color(0.894117653f, 0.619607866f, 0.3529412f)), - new PawnSkinColors.SkinColorData(0.9f, 0.95f, new Color(0.509803951f, 0.356862754f, 0.1882353f)), - new PawnSkinColors.SkinColorData(1f, 1f, new Color(0.3882353f, 0.274509817f, 0.141176477f)) + new SkinColorData(0f, 0f, new Color(0.9490196f, 0.929411769f, 0.8784314f)), + new SkinColorData(0.25f, 0.215f, new Color(1f, 0.9372549f, 0.8352941f)), + new SkinColorData(0.5f, 0.715f, new Color(1f, 0.9372549f, 0.7411765f)), + new SkinColorData(0.75f, 0.8f, new Color(0.894117653f, 0.619607866f, 0.3529412f)), + new SkinColorData(0.9f, 0.95f, new Color(0.509803951f, 0.356862754f, 0.1882353f)), + new SkinColorData(1f, 1f, new Color(0.3882353f, 0.274509817f, 0.141176477f)) }; public static bool IsDarkSkin(Color color) { Color skinColor = PawnSkinColors.GetSkinColor(0.5f); - return color.r + color.g + color.b <= skinColor.r + skinColor.g + skinColor.b + 0.01f; + return color.r + color.g + color.b <= skinColor.r + skinColor.g + skinColor.b + 0.0099999997764825821; } public static Color GetSkinColor(float melanin) @@ -53,13 +52,11 @@ public static float RandomMelanin() { float value = Rand.Value; int num = 0; - for (int i = 0; i < PawnSkinColors.SkinColors.Length; i++) + int num2 = 0; + while (num2 < PawnSkinColors.SkinColors.Length && value >= PawnSkinColors.SkinColors[num2].selector) { - if (value < PawnSkinColors.SkinColors[i].selector) - { - break; - } - num = i; + num = num2; + num2++; } if (num == PawnSkinColors.SkinColors.Length - 1) { @@ -104,15 +101,15 @@ private static float GetTotalAreaWhereClosestToSelector(int skinDataIndex) } else if (PawnSkinColors.SkinColors.Length > 1) { - num += (PawnSkinColors.SkinColors[skinDataIndex].selector - PawnSkinColors.SkinColors[skinDataIndex - 1].selector) / 2f; + num = (float)(num + (PawnSkinColors.SkinColors[skinDataIndex].selector - PawnSkinColors.SkinColors[skinDataIndex - 1].selector) / 2.0); } if (skinDataIndex == PawnSkinColors.SkinColors.Length - 1) { - num += 1f - PawnSkinColors.SkinColors[skinDataIndex].selector; + num = (float)(num + (1.0 - PawnSkinColors.SkinColors[skinDataIndex].selector)); } else if (PawnSkinColors.SkinColors.Length > 1) { - num += (PawnSkinColors.SkinColors[skinDataIndex + 1].selector - PawnSkinColors.SkinColors[skinDataIndex].selector) / 2f; + num = (float)(num + (PawnSkinColors.SkinColors[skinDataIndex + 1].selector - PawnSkinColors.SkinColors[skinDataIndex].selector) / 2.0); } return num; } @@ -120,13 +117,11 @@ private static float GetTotalAreaWhereClosestToSelector(int skinDataIndex) private static int GetSkinDataIndexOfMelanin(float melanin) { int result = 0; - for (int i = 0; i < PawnSkinColors.SkinColors.Length; i++) + int num = 0; + while (num < PawnSkinColors.SkinColors.Length && melanin >= PawnSkinColors.SkinColors[num].melanin) { - if (melanin < PawnSkinColors.SkinColors[i].melanin) - { - break; - } - result = i; + result = num; + num++; } return result; } diff --git a/Assembly-CSharp/RimWorld/PawnTable.cs b/Assembly-CSharp/RimWorld/PawnTable.cs index 1f5ceebf8..8d702ca91 100644 --- a/Assembly-CSharp/RimWorld/PawnTable.cs +++ b/Assembly-CSharp/RimWorld/PawnTable.cs @@ -26,9 +26,9 @@ public class PawnTable private bool dirty; - private List columnAtMaxWidth; + private List columnAtMaxWidth = new List(); - private List columnAtOptimalWidth; + private List columnAtOptimalWidth = new List(); private Vector2 scrollPosition; @@ -38,11 +38,11 @@ public class PawnTable private Vector2 cachedSize; - private List cachedPawns; + private List cachedPawns = new List(); - private List cachedColumnWidths; + private List cachedColumnWidths = new List(); - private List cachedRowHeights; + private List cachedRowHeights = new List(); private float cachedHeaderHeight; @@ -114,13 +114,7 @@ public PawnTable(PawnTableDef table, Func> pawnsGetter, int mi public PawnTable(IEnumerable columns, Func> pawnsGetter, int minTableWidth, int maxTableWidth, int minTableHeight, int maxTableHeight) { - this.columnAtMaxWidth = new List(); - this.columnAtOptimalWidth = new List(); - this.cachedPawns = new List(); - this.cachedColumnWidths = new List(); - this.cachedRowHeights = new List(); - base..ctor(); - this.columns = columns.ToList(); + this.columns = columns.ToList(); this.pawnsGetter = pawnsGetter; this.SetMinMaxSize(minTableWidth, maxTableWidth, minTableHeight, maxTableHeight); this.SetDirty(); @@ -132,13 +126,7 @@ public PawnTable(PawnTableDef table, Func> pawnsGetter, Vector public PawnTable(IEnumerable columns, Func> pawnsGetter, Vector2 size) { - this.columnAtMaxWidth = new List(); - this.columnAtOptimalWidth = new List(); - this.cachedPawns = new List(); - this.cachedColumnWidths = new List(); - this.cachedRowHeights = new List(); - base..ctor(); - this.columns = columns.ToList(); + this.columns = columns.ToList(); this.pawnsGetter = pawnsGetter; this.SetFixedSize(this.fixedSize); this.SetDirty(); @@ -146,70 +134,54 @@ public PawnTable(IEnumerable columns, Func> paw public void PawnTableOnGUI(Vector2 position) { - if (Event.current.type == EventType.Layout) + if (Event.current.type != EventType.Layout) { - return; - } - this.RecacheIfDirty(); - float num = this.cachedSize.x - 16f; - int num2 = 0; - for (int i = 0; i < this.columns.Count; i++) - { - int num3; - if (i == this.columns.Count - 1) - { - num3 = (int)(num - (float)num2); - } - else + this.RecacheIfDirty(); + float num = (float)(this.cachedSize.x - 16.0); + int num2 = 0; + for (int i = 0; i < this.columns.Count; i++) { - num3 = (int)this.cachedColumnWidths[i]; + int num3 = (i != this.columns.Count - 1) ? ((int)this.cachedColumnWidths[i]) : ((int)(num - (float)num2)); + Rect rect = new Rect((float)((int)position.x + num2), (float)(int)position.y, (float)num3, (float)(int)this.cachedHeaderHeight); + this.columns[i].Worker.DoHeader(rect, this); + num2 += num3; } - Rect rect = new Rect((float)((int)position.x + num2), (float)((int)position.y), (float)num3, (float)((int)this.cachedHeaderHeight)); - this.columns[i].Worker.DoHeader(rect, this); - num2 += num3; - } - Rect outRect = new Rect((float)((int)position.x), (float)((int)position.y + (int)this.cachedHeaderHeight), (float)((int)this.cachedSize.x), (float)((int)this.cachedSize.y - (int)this.cachedHeaderHeight)); - Rect viewRect = new Rect(0f, 0f, outRect.width - 16f, (float)((int)this.cachedHeightNoScrollbar - (int)this.cachedHeaderHeight)); - Widgets.BeginScrollView(outRect, ref this.scrollPosition, viewRect, true); - int num4 = 0; - for (int j = 0; j < this.cachedPawns.Count; j++) - { - num2 = 0; - if ((float)num4 - this.scrollPosition.y + (float)((int)this.cachedRowHeights[j]) >= 0f && (float)num4 - this.scrollPosition.y <= outRect.height) + Rect outRect = new Rect((float)(int)position.x, (float)((int)position.y + (int)this.cachedHeaderHeight), (float)(int)this.cachedSize.x, (float)((int)this.cachedSize.y - (int)this.cachedHeaderHeight)); + Rect viewRect = new Rect(0f, 0f, (float)(outRect.width - 16.0), (float)((int)this.cachedHeightNoScrollbar - (int)this.cachedHeaderHeight)); + Widgets.BeginScrollView(outRect, ref this.scrollPosition, viewRect, true); + int num4 = 0; + for (int j = 0; j < this.cachedPawns.Count; j++) { - GUI.color = new Color(1f, 1f, 1f, 0.2f); - Widgets.DrawLineHorizontal(0f, (float)num4, viewRect.width); - GUI.color = Color.white; - Rect rect2 = new Rect(0f, (float)num4, viewRect.width, (float)((int)this.cachedRowHeights[j])); - if (Mouse.IsOver(rect2)) + num2 = 0; + if (!((float)num4 - this.scrollPosition.y + (float)(int)this.cachedRowHeights[j] < 0.0) && !((float)num4 - this.scrollPosition.y > outRect.height)) { - GUI.DrawTexture(rect2, TexUI.HighlightTex); - } - for (int k = 0; k < this.columns.Count; k++) - { - int num5; - if (k == this.columns.Count - 1) + GUI.color = new Color(1f, 1f, 1f, 0.2f); + Widgets.DrawLineHorizontal(0f, (float)num4, viewRect.width); + GUI.color = Color.white; + Rect rect2 = new Rect(0f, (float)num4, viewRect.width, (float)(int)this.cachedRowHeights[j]); + if (Mouse.IsOver(rect2)) { - num5 = (int)(num - (float)num2); + GUI.DrawTexture(rect2, TexUI.HighlightTex); } - else + for (int k = 0; k < this.columns.Count; k++) { - num5 = (int)this.cachedColumnWidths[k]; + int num5 = (k != this.columns.Count - 1) ? ((int)this.cachedColumnWidths[k]) : ((int)(num - (float)num2)); + Rect rect3 = new Rect((float)num2, (float)num4, (float)num5, (float)(int)this.cachedRowHeights[j]); + this.columns[k].Worker.DoCell(rect3, this.cachedPawns[j], this); + num2 += num5; + } + if (this.cachedPawns[j].Downed) + { + GUI.color = new Color(1f, 0f, 0f, 0.5f); + Vector2 center = rect2.center; + Widgets.DrawLineHorizontal(0f, center.y, viewRect.width); + GUI.color = Color.white; } - Rect rect3 = new Rect((float)num2, (float)num4, (float)num5, (float)((int)this.cachedRowHeights[j])); - this.columns[k].Worker.DoCell(rect3, this.cachedPawns[j], this); - num2 += num5; - } - if (this.cachedPawns[j].Downed) - { - GUI.color = new Color(1f, 0f, 0f, 0.5f); - Widgets.DrawLineHorizontal(0f, rect2.center.y, viewRect.width); - GUI.color = Color.white; } + num4 += (int)this.cachedRowHeights[j]; } - num4 += (int)this.cachedRowHeights[j]; + Widgets.EndScrollView(); } - Widgets.EndScrollView(); } public void SetDirty() @@ -243,17 +215,16 @@ public void SortBy(PawnColumnDef column, bool descending) private void RecacheIfDirty() { - if (!this.dirty) + if (this.dirty) { - return; + this.dirty = false; + this.RecachePawns(); + this.RecacheRowHeights(); + this.cachedHeaderHeight = this.CalculateHeaderHeight(); + this.cachedHeightNoScrollbar = this.CalculateTotalRequiredHeight(); + this.RecacheSize(); + this.RecacheColumnWidths(); } - this.dirty = false; - this.RecachePawns(); - this.RecacheRowHeights(); - this.cachedHeaderHeight = this.CalculateHeaderHeight(); - this.cachedHeightNoScrollbar = this.CalculateTotalRequiredHeight(); - this.RecacheSize(); - this.RecacheColumnWidths(); } private void RecachePawns() @@ -264,19 +235,19 @@ private void RecachePawns() { if (this.sortDescending) { - this.cachedPawns.Sort(delegate(Pawn a, Pawn b) + this.cachedPawns.Sort((Comparison)delegate(Pawn a, Pawn b) { - int num = this.sortByColumn.Worker.Compare(b, a); - if (num == 0) + int num2 = this.sortByColumn.Worker.Compare(b, a); + if (num2 == 0) { return b.Label.CompareTo(a.Label); } - return num; + return num2; }); } else { - this.cachedPawns.Sort(delegate(Pawn a, Pawn b) + this.cachedPawns.Sort((Comparison)delegate(Pawn a, Pawn b) { int num = this.sortByColumn.Worker.Compare(a, b); if (num == 0) @@ -291,26 +262,24 @@ private void RecachePawns() private void RecacheColumnWidths() { - float num = this.cachedSize.x - 16f; + float num = (float)(this.cachedSize.x - 16.0); float num2 = 0f; this.RecacheColumnWidths_StartWithMinWidths(out num2); - if (num2 == num) - { - return; - } - if (num2 > num) + if (num2 != num) { - this.SubtractProportionally(num2 - num, num2); - } - else - { - bool flag; - this.RecacheColumnWidths_DistributeUntilOptimal(num, ref num2, out flag); - if (flag) + if (num2 > num) { - return; + this.SubtractProportionally(num2 - num, num2); + } + else + { + bool flag = default(bool); + this.RecacheColumnWidths_DistributeUntilOptimal(num, ref num2, out flag); + if (!flag) + { + this.RecacheColumnWidths_DistributeAboveOptimal(num, ref num2); + } } - this.RecacheColumnWidths_DistributeAboveOptimal(num, ref num2); } } @@ -339,85 +308,75 @@ private void RecacheColumnWidths_DistributeUntilOptimal(float totalAvailableSpac num++; if (num >= 10000) { - break; + Log.Error("Too many iterations."); } - float num2 = -3.40282347E+38f; - for (int j = 0; j < this.columns.Count; j++) + else { - if (!this.columnAtOptimalWidth[j]) + float num2 = -3.40282347E+38f; + for (int j = 0; j < this.columns.Count; j++) { - num2 = Mathf.Max(num2, (float)this.columns[j].widthPriority); + if (!this.columnAtOptimalWidth[j]) + { + num2 = Mathf.Max(num2, (float)this.columns[j].widthPriority); + } } - } - float num3 = 0f; - for (int k = 0; k < this.cachedColumnWidths.Count; k++) - { - if (!this.columnAtOptimalWidth[k]) + float num3 = 0f; + for (int k = 0; k < this.cachedColumnWidths.Count; k++) { - if ((float)this.columns[k].widthPriority == num2) + if (!this.columnAtOptimalWidth[k] && (float)this.columns[k].widthPriority == num2) { num3 += this.GetOptimalWidth(this.columns[k]); } } - } - float num4 = totalAvailableSpaceForColumns - usedWidth; - bool flag = false; - bool flag2 = false; - for (int l = 0; l < this.cachedColumnWidths.Count; l++) - { - if (!this.columnAtOptimalWidth[l]) + float num4 = totalAvailableSpaceForColumns - usedWidth; + bool flag = false; + bool flag2 = false; + for (int l = 0; l < this.cachedColumnWidths.Count; l++) { - if ((float)this.columns[l].widthPriority != num2) - { - flag = true; - } - else + if (!this.columnAtOptimalWidth[l]) { - float num5 = num4 * this.GetOptimalWidth(this.columns[l]) / num3; - float num6 = this.GetOptimalWidth(this.columns[l]) - this.cachedColumnWidths[l]; - if (num5 >= num6) - { - num5 = num6; - this.columnAtOptimalWidth[l] = true; - flag2 = true; - } - else + if ((float)this.columns[l].widthPriority != num2) { flag = true; } - if (num5 > 0f) + else { - List list; - List expr_1FC = list = this.cachedColumnWidths; - int index; - int expr_201 = index = l; - float num7 = list[index]; - expr_1FC[expr_201] = num7 + num5; - usedWidth += num5; + float num5 = num4 * this.GetOptimalWidth(this.columns[l]) / num3; + float num6 = this.GetOptimalWidth(this.columns[l]) - this.cachedColumnWidths[l]; + if (num5 >= num6) + { + num5 = num6; + this.columnAtOptimalWidth[l] = true; + flag2 = true; + } + else + { + flag = true; + } + if (num5 > 0.0) + { + List list; + List obj = list = this.cachedColumnWidths; + int index; + int index2 = index = l; + float num7 = list[index]; + obj[index2] = num7 + num5; + usedWidth += num5; + } } } } + if (usedWidth >= totalAvailableSpaceForColumns - 0.10000000149011612) + { + noMoreFreeSpace = true; + } + else if (flag && flag2) + { + continue; + } } - if (usedWidth >= totalAvailableSpaceForColumns - 0.1f) - { - goto Block_13; - } - if (!flag) - { - goto Block_14; - } - if (!flag2) - { - goto Block_15; - } + break; } - Log.Error("Too many iterations."); - goto IL_26B; - Block_13: - noMoreFreeSpace = true; - Block_14: - Block_15: - IL_26B: noMoreFreeSpace = false; } @@ -434,58 +393,56 @@ private void RecacheColumnWidths_DistributeAboveOptimal(float totalAvailableSpac num++; if (num >= 10000) { - break; + Log.Error("Too many iterations."); } - float num2 = 0f; - for (int j = 0; j < this.columns.Count; j++) - { - if (!this.columnAtMaxWidth[j]) - { - num2 += Mathf.Max(this.GetOptimalWidth(this.columns[j]), 1f); - } - } - float num3 = totalAvailableSpaceForColumns - usedWidth; - bool flag = false; - for (int k = 0; k < this.columns.Count; k++) + else { - if (!this.columnAtMaxWidth[k]) + float num2 = 0f; + for (int j = 0; j < this.columns.Count; j++) { - float num4 = num3 * Mathf.Max(this.GetOptimalWidth(this.columns[k]), 1f) / num2; - float num5 = this.GetMaxWidth(this.columns[k]) - this.cachedColumnWidths[k]; - if (num4 >= num5) + if (!this.columnAtMaxWidth[j]) { - num4 = num5; - this.columnAtMaxWidth[k] = true; + num2 += Mathf.Max(this.GetOptimalWidth(this.columns[j]), 1f); } - else - { - flag = true; - } - if (num4 > 0f) + } + float num3 = totalAvailableSpaceForColumns - usedWidth; + bool flag = false; + for (int k = 0; k < this.columns.Count; k++) + { + if (!this.columnAtMaxWidth[k]) { - List list; - List expr_16B = list = this.cachedColumnWidths; - int index; - int expr_170 = index = k; - float num6 = list[index]; - expr_16B[expr_170] = num6 + num4; - usedWidth += num4; + float num4 = num3 * Mathf.Max(this.GetOptimalWidth(this.columns[k]), 1f) / num2; + float num5 = this.GetMaxWidth(this.columns[k]) - this.cachedColumnWidths[k]; + if (num4 >= num5) + { + num4 = num5; + this.columnAtMaxWidth[k] = true; + } + else + { + flag = true; + } + if (num4 > 0.0) + { + List list; + List obj = list = this.cachedColumnWidths; + int index; + int index2 = index = k; + float num6 = list[index]; + obj[index2] = num6 + num4; + usedWidth += num4; + } } } + if (!(usedWidth >= totalAvailableSpaceForColumns - 0.10000000149011612)) + { + if (!flag) + break; + continue; + } } - if (usedWidth >= totalAvailableSpaceForColumns - 0.1f) - { - goto Block_9; - } - if (!flag) - { - goto Block_10; - } + return; } - Log.Error("Too many iterations."); - Block_9: - return; - Block_10: this.DistributeRemainingWidthProportionallyAboveMax(totalAvailableSpaceForColumns - usedWidth); } @@ -514,11 +471,11 @@ private void RecacheSize() num += this.GetOptimalWidth(this.columns[i]); } } - float num2 = Mathf.Clamp(num + 16f, (float)this.minTableWidth, (float)this.maxTableWidth); - float num3 = Mathf.Clamp(this.cachedHeightNoScrollbar, (float)this.minTableHeight, (float)this.maxTableHeight); - num2 = Mathf.Min(num2, (float)UI.screenWidth); - num3 = Mathf.Min(num3, (float)UI.screenHeight); - this.cachedSize = new Vector2(num2, num3); + float a = Mathf.Clamp((float)(num + 16.0), (float)this.minTableWidth, (float)this.maxTableWidth); + float a2 = Mathf.Clamp(this.cachedHeightNoScrollbar, (float)this.minTableHeight, (float)this.maxTableHeight); + a = Mathf.Min(a, (float)UI.screenWidth); + a2 = Mathf.Min(a2, (float)UI.screenHeight); + this.cachedSize = new Vector2(a, a2); } } @@ -527,11 +484,11 @@ private void SubtractProportionally(float toSubtract, float totalUsedWidth) for (int i = 0; i < this.cachedColumnWidths.Count; i++) { List list; - List expr_0D = list = this.cachedColumnWidths; + List obj = list = this.cachedColumnWidths; int index; - int expr_10 = index = i; + int index2 = index = i; float num = list[index]; - expr_0D[expr_10] = num - toSubtract * this.cachedColumnWidths[i] / totalUsedWidth; + obj[index2] = num - toSubtract * this.cachedColumnWidths[i] / totalUsedWidth; } } @@ -545,11 +502,11 @@ private void DistributeRemainingWidthProportionallyAboveMax(float toDistribute) for (int j = 0; j < this.columns.Count; j++) { List list; - List expr_4E = list = this.cachedColumnWidths; + List obj = list = this.cachedColumnWidths; int index; - int expr_51 = index = j; + int index2 = index = j; float num2 = list[index]; - expr_4E[expr_51] = num2 + toDistribute * Mathf.Max(this.GetOptimalWidth(this.columns[j]), 1f) / num; + obj[index2] = num2 + toDistribute * Mathf.Max(this.GetOptimalWidth(this.columns[j]), 1f) / num; } } diff --git a/Assembly-CSharp/RimWorld/PawnTableDef.cs b/Assembly-CSharp/RimWorld/PawnTableDef.cs index c79276f7b..23a4792dd 100644 --- a/Assembly-CSharp/RimWorld/PawnTableDef.cs +++ b/Assembly-CSharp/RimWorld/PawnTableDef.cs @@ -1,4 +1,3 @@ -using System; using System.Collections.Generic; using Verse; diff --git a/Assembly-CSharp/RimWorld/PawnTableDefOf.cs b/Assembly-CSharp/RimWorld/PawnTableDefOf.cs index 955db80e7..601d58932 100644 --- a/Assembly-CSharp/RimWorld/PawnTableDefOf.cs +++ b/Assembly-CSharp/RimWorld/PawnTableDefOf.cs @@ -1,5 +1,3 @@ -using System; - namespace RimWorld { [DefOf] diff --git a/Assembly-CSharp/RimWorld/PawnTechHediffsGenerator.cs b/Assembly-CSharp/RimWorld/PawnTechHediffsGenerator.cs index 4d6fd184c..3d801a382 100644 --- a/Assembly-CSharp/RimWorld/PawnTechHediffsGenerator.cs +++ b/Assembly-CSharp/RimWorld/PawnTechHediffsGenerator.cs @@ -11,30 +11,25 @@ public static class PawnTechHediffsGenerator public static void GeneratePartsAndImplantsFor(Pawn pawn) { - if (pawn.kindDef.techHediffsTags == null) + if (pawn.kindDef.techHediffsTags != null && !(Rand.Value > pawn.kindDef.techHediffsChance)) { - return; - } - if (Rand.Value > pawn.kindDef.techHediffsChance) - { - return; - } - float partsMoney = pawn.kindDef.techHediffsMoney.RandomInRange; - IEnumerable source = from x in DefDatabase.AllDefs - where x.isBodyPartOrImplant && x.BaseMarketValue <= partsMoney && x.techHediffsTags != null && pawn.kindDef.techHediffsTags.Any((string tag) => x.techHediffsTags.Contains(tag)) - select x; - if (source.Any()) - { - ThingDef partDef = source.RandomElementByWeight((ThingDef w) => w.BaseMarketValue); - IEnumerable source2 = from x in DefDatabase.AllDefs - where x.IsIngredient(partDef) && pawn.def.AllRecipes.Contains(x) + float partsMoney = pawn.kindDef.techHediffsMoney.RandomInRange; + IEnumerable source = from x in DefDatabase.AllDefs + where x.isBodyPartOrImplant && x.BaseMarketValue <= partsMoney && x.techHediffsTags != null && pawn.kindDef.techHediffsTags.Any((Predicate)((string tag) => x.techHediffsTags.Contains(tag))) select x; - if (source2.Any()) + if (source.Any()) { - RecipeDef recipeDef = source2.RandomElement(); - if (recipeDef.Worker.GetPartsToApplyOn(pawn, recipeDef).Any()) + ThingDef partDef = source.RandomElementByWeight((Func)((ThingDef w) => w.BaseMarketValue)); + IEnumerable source2 = from x in DefDatabase.AllDefs + where x.IsIngredient(partDef) && pawn.def.AllRecipes.Contains(x) + select x; + if (source2.Any()) { - recipeDef.Worker.ApplyOnPawn(pawn, recipeDef.Worker.GetPartsToApplyOn(pawn, recipeDef).RandomElement(), null, PawnTechHediffsGenerator.emptyIngredientsList); + RecipeDef recipeDef = source2.RandomElement(); + if (recipeDef.Worker.GetPartsToApplyOn(pawn, recipeDef).Any()) + { + recipeDef.Worker.ApplyOnPawn(pawn, recipeDef.Worker.GetPartsToApplyOn(pawn, recipeDef).RandomElement(), null, PawnTechHediffsGenerator.emptyIngredientsList); + } } } } diff --git a/Assembly-CSharp/RimWorld/PawnUtility.cs b/Assembly-CSharp/RimWorld/PawnUtility.cs index fb7d8b453..ccf9d4f9b 100644 --- a/Assembly-CSharp/RimWorld/PawnUtility.cs +++ b/Assembly-CSharp/RimWorld/PawnUtility.cs @@ -1,7 +1,6 @@ using RimWorld.Planet; using System; using System.Collections.Generic; -using System.Diagnostics; using System.Linq; using UnityEngine; using Verse; @@ -64,7 +63,7 @@ public static bool ForSaleBySettlement(Pawn pawn) public static void TryDestroyStartingColonistFamily(Pawn pawn) { - if (!pawn.relations.RelatedPawns.Any((Pawn x) => Find.GameInitData.startingPawns.Contains(x))) + if (!pawn.relations.RelatedPawns.Any((Func)((Pawn x) => Find.GameInitData.startingPawns.Contains(x)))) { PawnUtility.DestroyStartingColonistFamily(pawn); } @@ -72,25 +71,34 @@ public static void TryDestroyStartingColonistFamily(Pawn pawn) public static void DestroyStartingColonistFamily(Pawn pawn) { - foreach (Pawn current in pawn.relations.RelatedPawns.ToList()) + List.Enumerator enumerator = pawn.relations.RelatedPawns.ToList().GetEnumerator(); + try { - if (!Find.GameInitData.startingPawns.Contains(current)) + while (enumerator.MoveNext()) { - WorldPawnSituation situation = Find.WorldPawns.GetSituation(current); - if (situation == WorldPawnSituation.Free || situation == WorldPawnSituation.Dead) + Pawn current = enumerator.Current; + if (!Find.GameInitData.startingPawns.Contains(current)) { - Find.WorldPawns.RemovePawn(current); - Find.WorldPawns.PassToWorld(current, PawnDiscardDecideMode.Discard); + WorldPawnSituation situation = Find.WorldPawns.GetSituation(current); + if (situation == WorldPawnSituation.Free || situation == WorldPawnSituation.Dead) + { + Find.WorldPawns.RemovePawn(current); + Find.WorldPawns.PassToWorld(current, PawnDiscardDecideMode.Discard); + } } } } + finally + { + ((IDisposable)(object)enumerator).Dispose(); + } } public static bool EnemiesAreNearby(Pawn pawn, int regionsToScan = 9, bool passDoors = false) { TraverseParms tp = (!passDoors) ? TraverseParms.For(pawn, Danger.Deadly, TraverseMode.ByPawn, false) : TraverseParms.For(TraverseMode.PassDoors, Danger.Deadly, false); bool foundEnemy = false; - RegionTraverser.BreadthFirstTraverse(pawn.Position, pawn.Map, (Region from, Region to) => to.Allows(tp, false), delegate(Region r) + RegionTraverser.BreadthFirstTraverse(pawn.Position, pawn.Map, (RegionEntryPredicate)((Region from, Region to) => to.Allows(tp, false)), (RegionProcessor)delegate(Region r) { List list = r.ListerThings.ThingsInGroup(ThingRequestGroup.AttackTarget); for (int i = 0; i < list.Count; i++) @@ -108,13 +116,25 @@ public static bool EnemiesAreNearby(Pawn pawn, int regionsToScan = 9, bool passD public static bool WillSoonHaveBasicNeed(Pawn p) { - return p.needs != null && ((p.needs.rest != null && p.needs.rest.CurLevel < 0.33f) || (p.needs.food != null && p.needs.food.CurLevelPercentage < p.needs.food.PercentageThreshHungry + 0.05f)); + if (p.needs == null) + { + return false; + } + if (p.needs.rest != null && p.needs.rest.CurLevel < 0.33000001311302185) + { + return true; + } + if (p.needs.food != null && p.needs.food.CurLevelPercentage < p.needs.food.PercentageThreshHungry + 0.05000000074505806) + { + return true; + } + return false; } public static float AnimalFilthChancePerCell(ThingDef def, float bodySize) { - float num = bodySize * 0.00125f; - return num * (1f - def.race.petness); + float num = (float)(bodySize * 0.0012499999720603228); + return (float)(num * (1.0 - def.race.petness)); } public static bool CanCasuallyInteractNow(this Pawn p, bool twoWayInteraction = false) @@ -136,40 +156,57 @@ public static bool CanCasuallyInteractNow(this Pawn p, bool twoWayInteraction = return false; } Job curJob = p.CurJob; - return curJob == null || !twoWayInteraction || (curJob.def.casualInterruptible && curJob.playerForced); + if (curJob != null && twoWayInteraction && (!curJob.def.casualInterruptible || !curJob.playerForced)) + { + return false; + } + return true; } - [DebuggerHidden] public static IEnumerable SpawnedMasteredPawns(Pawn master) { - PawnUtility.c__IteratorCA c__IteratorCA = new PawnUtility.c__IteratorCA(); - c__IteratorCA.master = master; - c__IteratorCA.<$>master = master; - PawnUtility.c__IteratorCA expr_15 = c__IteratorCA; - expr_15.$PC = -2; - return expr_15; + if (Current.ProgramState == ProgramState.Playing && master.Faction != null && master.RaceProps.Humanlike && master.Spawned) + { + List pawns = master.Map.mapPawns.SpawnedPawnsInFaction(master.Faction); + for (int i = 0; i < pawns.Count; i++) + { + if (pawns[i].playerSettings != null && pawns[i].playerSettings.master == master) + { + yield return pawns[i]; + } + } + } } public static bool InValidState(Pawn p) { - return p.health != null && (p.Dead || (p.stances != null && p.mindState != null && p.needs != null && p.ageTracker != null)); - } - - public static PawnPosture GetPosture(this Pawn p) - { - if (p.Downed || p.Dead) + if (p.health == null) { - return PawnPosture.LayingAny; + return false; } - if (p.jobs == null) + if (!p.Dead && (p.stances == null || p.mindState == null || p.needs == null || p.ageTracker == null)) { - return PawnPosture.Standing; + return false; } - if (p.jobs.curJob == null) + return true; + } + + public static PawnPosture GetPosture(this Pawn p) + { + if (!p.Downed && !p.Dead) { - return PawnPosture.Standing; + if (p.jobs == null) + { + return PawnPosture.Standing; + } + Job curJob = p.jobs.curJob; + if (curJob == null) + { + return PawnPosture.Standing; + } + return p.jobs.curDriver.Posture; } - return p.jobs.curDriver.Posture; + return PawnPosture.LayingAny; } public static void ForceWait(Pawn pawn, int ticks, Thing faceTarget = null, bool maintainPosture = false) @@ -180,21 +217,16 @@ public static void ForceWait(Pawn pawn, int ticks, Thing faceTarget = null, bool } Job job = new Job((!maintainPosture) ? JobDefOf.Wait : JobDefOf.WaitMaintainPosture, faceTarget); job.expiryInterval = ticks; - pawn.jobs.StartJob(job, JobCondition.InterruptForced, null, true, true, null, null); + pawn.jobs.StartJob(job, JobCondition.InterruptForced, null, true, true, null, default(JobTag?)); } public static void GiveNameBecauseOfNuzzle(Pawn namer, Pawn namee) { string text = (namee.Name != null) ? namee.Name.ToStringFull : namee.LabelIndefinite(); - namee.Name = PawnBioAndNameGenerator.GeneratePawnName(namee, NameStyle.Full, null); + namee.Name = PawnBioAndNameGenerator.GeneratePawnName(namee, NameStyle.Full, (string)null); if (namer.Faction == Faction.OfPlayer) { - Messages.Message("MessageNuzzledPawnGaveNameTo".Translate(new object[] - { - namer, - text, - namee.Name.ToStringFull - }), namee, MessageSound.Standard); + Messages.Message("MessageNuzzledPawnGaveNameTo".Translate(namer, text, namee.Name.ToStringFull), (Thing)namee, MessageSound.Standard); } } @@ -206,7 +238,7 @@ public static void GainComfortFromCellIfPossible(this Pawn p) if (edifice != null) { float statValue = edifice.GetStatValue(StatDefOf.Comfort, true); - if (statValue >= 0f && p.needs != null && p.needs.comfort != null) + if (statValue >= 0.0 && p.needs != null && p.needs.comfort != null) { p.needs.comfort.ComfortUsed(statValue); } @@ -221,55 +253,66 @@ public static float BodyResourceGrowthSpeed(Pawn pawn) switch (pawn.needs.food.CurCategory) { case HungerCategory.Fed: + { return 1f; + } case HungerCategory.Hungry: + { return 0.666f; + } case HungerCategory.UrgentlyHungry: + { return 0.333f; + } case HungerCategory.Starving: + { return 0f; } + } } return 1f; } public static bool FertileMateTarget(Pawn male, Pawn female) { - if (female.gender != Gender.Female || !female.ageTracker.CurLifeStage.reproductive) - { - return false; - } - CompEggLayer compEggLayer = female.TryGetComp(); - if (compEggLayer != null) + if (female.gender == Gender.Female && female.ageTracker.CurLifeStage.reproductive) { - return !compEggLayer.FullyFertilized; + CompEggLayer compEggLayer = female.TryGetComp(); + if (compEggLayer != null) + { + return !compEggLayer.FullyFertilized; + } + return !female.health.hediffSet.HasHediff(HediffDefOf.Pregnant); } - return !female.health.hediffSet.HasHediff(HediffDefOf.Pregnant); + return false; } public static void Mated(Pawn male, Pawn female) { - if (!female.ageTracker.CurLifeStage.reproductive) + if (female.ageTracker.CurLifeStage.reproductive) { - return; - } - CompEggLayer compEggLayer = female.TryGetComp(); - if (compEggLayer != null) - { - compEggLayer.Fertilize(male); - } - else if (Rand.Value < 0.5f && !female.health.hediffSet.HasHediff(HediffDefOf.Pregnant)) - { - Hediff_Pregnant hediff_Pregnant = (Hediff_Pregnant)HediffMaker.MakeHediff(HediffDefOf.Pregnant, female, null); - hediff_Pregnant.father = male; - female.health.AddHediff(hediff_Pregnant, null, null); + CompEggLayer compEggLayer = female.TryGetComp(); + if (compEggLayer != null) + { + compEggLayer.Fertilize(male); + } + else if (Rand.Value < 0.5 && !female.health.hediffSet.HasHediff(HediffDefOf.Pregnant)) + { + Hediff_Pregnant hediff_Pregnant = (Hediff_Pregnant)HediffMaker.MakeHediff(HediffDefOf.Pregnant, female, null); + hediff_Pregnant.father = male; + female.health.AddHediff(hediff_Pregnant, null, default(DamageInfo?)); + } } } public static bool PlayerForcedJobNowOrSoon(Pawn pawn) { Job curJob = pawn.CurJob; - return curJob != null && curJob.playerForced; + if (curJob != null && curJob.playerForced) + { + return true; + } + return false; } public static bool TrySpawnHatchedOrBornPawn(Pawn pawn, Thing motherOrEgg) @@ -324,32 +367,40 @@ public static ByteGrid GetAvoidGrid(this Pawn p) { return null; } - if (p.Faction == Faction.OfPlayer || !p.Faction.RelationWith(Faction.OfPlayer, false).hostile) - { - return null; - } - Lord lord = p.GetLord(); - if (lord != null) + if (p.Faction != Faction.OfPlayer && p.Faction.RelationWith(Faction.OfPlayer, false).hostile) { - if (lord.CurLordToil.avoidGridMode == AvoidGridMode.Ignore) + Lord lord = p.GetLord(); + if (lord != null) { - return null; - } - if (lord.CurLordToil.avoidGridMode == AvoidGridMode.Basic) - { - return p.Faction.GetAvoidGridBasic(p.Map); - } - if (lord.CurLordToil.avoidGridMode == AvoidGridMode.Smart) - { - return p.Faction.GetAvoidGridSmart(p.Map); + if (lord.CurLordToil.avoidGridMode == AvoidGridMode.Ignore) + { + return null; + } + if (lord.CurLordToil.avoidGridMode == AvoidGridMode.Basic) + { + return p.Faction.GetAvoidGridBasic(p.Map); + } + if (lord.CurLordToil.avoidGridMode == AvoidGridMode.Smart) + { + return p.Faction.GetAvoidGridSmart(p.Map); + } } + return p.Faction.GetAvoidGridBasic(p.Map); } - return p.Faction.GetAvoidGridBasic(p.Map); + return null; } public static bool ShouldCollideWithPawns(Pawn p) { - return !p.Downed && !p.Dead && p.mindState.anyCloseHostilesRecently; + if (!p.Downed && !p.Dead) + { + if (!p.mindState.anyCloseHostilesRecently) + { + return false; + } + return true; + } + return false; } public static bool AnyPawnBlockingPathAt(IntVec3 c, Pawn forPawn, bool actAsIfHadCollideWithPawnsJob = false, bool collideOnlyWithStandingPawns = false) @@ -384,52 +435,37 @@ public static Pawn PawnBlockingPathAt(IntVec3 c, Pawn forPawn, bool actAsIfHadCo for (int i = 0; i < thingList.Count; i++) { Pawn pawn = thingList[i] as Pawn; - if (pawn != null && pawn != forPawn && !pawn.Downed) + if (pawn != null && pawn != forPawn && !pawn.Downed && (!collideOnlyWithStandingPawns || (!pawn.pather.MovingNow && (!pawn.pather.Moving || !pawn.pather.MovedRecently(60)))) && !PawnUtility.PawnsCanShareCellBecauseOfBodySize(pawn, forPawn)) { - if (collideOnlyWithStandingPawns) + if (pawn.HostileTo(forPawn)) { - if (pawn.pather.MovingNow) - { - goto IL_13C; - } - if (pawn.pather.Moving && pawn.pather.MovedRecently(60)) - { - goto IL_13C; - } + return pawn; } - if (!PawnUtility.PawnsCanShareCellBecauseOfBodySize(pawn, forPawn)) + if (flag) { - if (pawn.HostileTo(forPawn)) + Job curJob2 = pawn.CurJob; + if (curJob2 != null && (curJob2.collideWithPawns || curJob2.def.collideWithPawns)) { return pawn; } - if (flag) - { - Job curJob2 = pawn.CurJob; - if (curJob2 != null && (curJob2.collideWithPawns || curJob2.def.collideWithPawns)) - { - return pawn; - } - } } } - IL_13C:; } return null; } private static bool PawnsCanShareCellBecauseOfBodySize(Pawn p1, Pawn p2) { - if (p1.BodySize >= 1.5f || p2.BodySize >= 1.5f) + if (!(p1.BodySize >= 1.5) && !(p2.BodySize >= 1.5)) { - return false; - } - float num = p1.BodySize / p2.BodySize; - if (num < 1f) - { - num = 1f / num; + float num = p1.BodySize / p2.BodySize; + if (num < 1.0) + { + num = (float)(1.0 / num); + } + return num > 3.5699999332427979; } - return num > 3.57f; + return false; } public static bool KnownDangerAt(IntVec3 c, Pawn forPawn) @@ -489,7 +525,7 @@ public static string PawnKindsToCommaList(List pawns) { PawnUtility.tmpPawns.Clear(); PawnUtility.tmpPawns.AddRange(pawns); - PawnUtility.tmpPawns.SortBy((Pawn x) => !x.RaceProps.Humanlike, (Pawn x) => x.KindLabelPlural); + PawnUtility.tmpPawns.SortBy((Func)((Pawn x) => !x.RaceProps.Humanlike), (Func)((Pawn x) => x.KindLabelPlural)); PawnUtility.tmpAddedPawnKinds.Clear(); PawnUtility.tmpPawnKinds.Clear(); for (int i = 0; i < PawnUtility.tmpPawns.Count; i++) @@ -520,7 +556,7 @@ public static string PawnKindsToCommaList(List pawns) public static LocomotionUrgency ResolveLocomotion(Pawn pawn, LocomotionUrgency secondPriority) { - if (!pawn.Dead && pawn.mindState.duty != null && pawn.mindState.duty.locomotion != LocomotionUrgency.None) + if (((!pawn.Dead) ? ((pawn.mindState.duty != null) ? pawn.mindState.duty.locomotion : LocomotionUrgency.None) : LocomotionUrgency.None) != 0) { return pawn.mindState.duty.locomotion; } @@ -530,7 +566,7 @@ public static LocomotionUrgency ResolveLocomotion(Pawn pawn, LocomotionUrgency s public static LocomotionUrgency ResolveLocomotion(Pawn pawn, LocomotionUrgency secondPriority, LocomotionUrgency thirdPriority) { LocomotionUrgency locomotionUrgency = PawnUtility.ResolveLocomotion(pawn, secondPriority); - if (locomotionUrgency != LocomotionUrgency.None) + if (locomotionUrgency != 0) { return locomotionUrgency; } @@ -539,7 +575,7 @@ public static LocomotionUrgency ResolveLocomotion(Pawn pawn, LocomotionUrgency s public static Danger ResolveMaxDanger(Pawn pawn, Danger secondPriority) { - if (!pawn.Dead && pawn.mindState.duty != null && pawn.mindState.duty.maxDanger != Danger.Unspecified) + if (((!pawn.Dead) ? ((pawn.mindState.duty != null) ? pawn.mindState.duty.maxDanger : Danger.Unspecified) : Danger.Unspecified) != 0) { return pawn.mindState.duty.maxDanger; } @@ -549,7 +585,7 @@ public static Danger ResolveMaxDanger(Pawn pawn, Danger secondPriority) public static Danger ResolveMaxDanger(Pawn pawn, Danger secondPriority, Danger thirdPriority) { Danger danger = PawnUtility.ResolveMaxDanger(pawn, secondPriority); - if (danger != Danger.Unspecified) + if (danger != 0) { return danger; } @@ -563,72 +599,89 @@ public static bool IsFighting(this Pawn pawn) public static float RecruitDifficulty(this Pawn pawn, Faction recruiterFaction, bool withPopIntent) { - float num = pawn.kindDef.baseRecruitDifficulty; + float baseRecruitDifficulty = pawn.kindDef.baseRecruitDifficulty; Rand.PushState(); Rand.Seed = pawn.HashOffset(); - num += Rand.Range(-0.2f, 0.2f); + baseRecruitDifficulty += Rand.Range(-0.2f, 0.2f); Rand.PopState(); if (pawn.Faction != null) { - int num2 = Mathf.Abs((int)(pawn.Faction.def.techLevel - recruiterFaction.def.techLevel)); - num += (float)num2 * 0.15f; + int num = Mathf.Abs(pawn.Faction.def.techLevel - recruiterFaction.def.techLevel); + baseRecruitDifficulty = (float)(baseRecruitDifficulty + (float)num * 0.15000000596046448); } if (withPopIntent) { - float popIntent = (Current.ProgramState != ProgramState.Playing) ? 1f : Find.Storyteller.intenderPopulation.PopulationIntent; - num = PawnUtility.PopIntentAdjustedRecruitDifficulty(num, popIntent); + float popIntent = (float)((Current.ProgramState != ProgramState.Playing) ? 1.0 : Find.Storyteller.intenderPopulation.PopulationIntent); + baseRecruitDifficulty = PawnUtility.PopIntentAdjustedRecruitDifficulty(baseRecruitDifficulty, popIntent); } - return Mathf.Clamp(num, 0.33f, 0.99f); + return Mathf.Clamp(baseRecruitDifficulty, 0.33f, 0.99f); } private static float PopIntentAdjustedRecruitDifficulty(float baseDifficulty, float popIntent) { float num = Mathf.Clamp(popIntent, 0.25f, 3f); - return 1f - (1f - baseDifficulty) * num; + return (float)(1.0 - (1.0 - baseDifficulty) * num); } public static void DoTable_PopIntentRecruitDifficulty() { List list = new List(); - for (float num = -1f; num < 3f; num += 0.1f) + for (float num = -1f; num < 3.0; num = (float)(num + 0.10000000149011612)) { list.Add(num); } - List colValues = new List - { - 0.1f, - 0.2f, - 0.3f, - 0.4f, - 0.5f, - 0.6f, - 0.7f, - 0.8f, - 0.9f, - 0.95f, - 0.99f - }; - DebugTables.MakeTablesDialog(colValues, (float d) => "d=" + d.ToString("F0"), list, (float rv) => rv.ToString("F1"), (float d, float pi) => PawnUtility.PopIntentAdjustedRecruitDifficulty(d, pi).ToStringPercent(), "intents"); + List list2 = new List(); + list2.Add(0.1f); + list2.Add(0.2f); + list2.Add(0.3f); + list2.Add(0.4f); + list2.Add(0.5f); + list2.Add(0.6f); + list2.Add(0.7f); + list2.Add(0.8f); + list2.Add(0.9f); + list2.Add(0.95f); + list2.Add(0.99f); + List colValues = list2; + DebugTables.MakeTablesDialog(colValues, (Func)((float d) => "d=" + d.ToString("F0")), list, (Func)((float rv) => rv.ToString("F1")), (Func)((float d, float pi) => PawnUtility.PopIntentAdjustedRecruitDifficulty(d, pi).ToStringPercent()), "intents"); } public static void GiveAllStartingPlayerPawnsThought(ThoughtDef thought) { - foreach (Pawn current in Find.GameInitData.startingPawns) + List.Enumerator enumerator = Find.GameInitData.startingPawns.GetEnumerator(); + try { - if (thought.IsSocial) + while (enumerator.MoveNext()) { - foreach (Pawn current2 in Find.GameInitData.startingPawns) + Pawn current = enumerator.Current; + if (thought.IsSocial) { - if (current2 != current) + List.Enumerator enumerator2 = Find.GameInitData.startingPawns.GetEnumerator(); + try { - current.needs.mood.thoughts.memories.TryGainMemory(thought, current2); + while (enumerator2.MoveNext()) + { + Pawn current2 = enumerator2.Current; + if (current2 != current) + { + current.needs.mood.thoughts.memories.TryGainMemory(thought, current2); + } + } + } + finally + { + ((IDisposable)(object)enumerator2).Dispose(); } } + else + { + current.needs.mood.thoughts.memories.TryGainMemory(thought, null); + } } - else - { - current.needs.mood.thoughts.memories.TryGainMemory(thought, null); - } + } + finally + { + ((IDisposable)(object)enumerator).Dispose(); } } diff --git a/Assembly-CSharp/RimWorld/PawnWeaponGenerator.cs b/Assembly-CSharp/RimWorld/PawnWeaponGenerator.cs index 675a739fa..5c51394e6 100644 --- a/Assembly-CSharp/RimWorld/PawnWeaponGenerator.cs +++ b/Assembly-CSharp/RimWorld/PawnWeaponGenerator.cs @@ -13,22 +13,29 @@ public static class PawnWeaponGenerator public static void Reset() { - Predicate isWeapon = (ThingDef td) => td.equipmentType == EquipmentType.Primary && td.canBeSpawningInventory && !td.weaponTags.NullOrEmpty(); + Predicate isWeapon = (Predicate)((ThingDef td) => td.equipmentType == EquipmentType.Primary && td.canBeSpawningInventory && !td.weaponTags.NullOrEmpty()); PawnWeaponGenerator.allWeaponPairs = ThingStuffPair.AllWith(isWeapon); - foreach (ThingDef thingDef in from td in DefDatabase.AllDefs + using (IEnumerator enumerator = (from td in DefDatabase.AllDefs where isWeapon(td) - select td) + select td).GetEnumerator()) { - float num = PawnWeaponGenerator.allWeaponPairs.Where((ThingStuffPair pa) => pa.thing == thingDef).Sum((ThingStuffPair pa) => pa.Commonality); - float num2 = thingDef.generateCommonality / num; - if (num2 != 1f) + ThingDef thingDef; + while (enumerator.MoveNext()) { - for (int i = 0; i < PawnWeaponGenerator.allWeaponPairs.Count; i++) + thingDef = enumerator.Current; + float num = (from pa in PawnWeaponGenerator.allWeaponPairs + where pa.thing == thingDef + select pa).Sum((Func)((ThingStuffPair pa) => pa.Commonality)); + float num2 = thingDef.generateCommonality / num; + if (num2 != 1.0) { - ThingStuffPair thingStuffPair = PawnWeaponGenerator.allWeaponPairs[i]; - if (thingStuffPair.thing == thingDef) + for (int i = 0; i < PawnWeaponGenerator.allWeaponPairs.Count; i++) { - PawnWeaponGenerator.allWeaponPairs[i] = new ThingStuffPair(thingStuffPair.thing, thingStuffPair.stuff, thingStuffPair.commonalityMultiplier * num2); + ThingStuffPair thingStuffPair = PawnWeaponGenerator.allWeaponPairs[i]; + if (thingStuffPair.thing == thingDef) + { + PawnWeaponGenerator.allWeaponPairs[i] = new ThingStuffPair(thingStuffPair.thing, thingStuffPair.stuff, thingStuffPair.commonalityMultiplier * num2); + } } } } @@ -37,50 +44,30 @@ where isWeapon(td) public static void TryGenerateWeaponFor(Pawn pawn) { - if (pawn.kindDef.weaponTags == null || pawn.kindDef.weaponTags.Count == 0) + if (pawn.kindDef.weaponTags != null && pawn.kindDef.weaponTags.Count != 0 && pawn.RaceProps.ToolUser && pawn.health.capacities.CapableOf(PawnCapacityDefOf.Manipulation) && (pawn.story == null || !pawn.story.WorkTagIsDisabled(WorkTags.Violent))) { - return; - } - if (!pawn.RaceProps.ToolUser) - { - return; - } - if (!pawn.health.capacities.CapableOf(PawnCapacityDefOf.Manipulation)) - { - return; - } - if (pawn.story != null && pawn.story.WorkTagIsDisabled(WorkTags.Violent)) - { - return; - } - float randomInRange = pawn.kindDef.weaponMoney.RandomInRange; - for (int i = 0; i < PawnWeaponGenerator.allWeaponPairs.Count; i++) - { - ThingStuffPair w = PawnWeaponGenerator.allWeaponPairs[i]; - if (w.Price <= randomInRange) + float randomInRange = pawn.kindDef.weaponMoney.RandomInRange; + for (int i = 0; i < PawnWeaponGenerator.allWeaponPairs.Count; i++) { - if (pawn.kindDef.weaponTags.Any((string tag) => w.thing.weaponTags.Contains(tag))) + ThingStuffPair w2 = PawnWeaponGenerator.allWeaponPairs[i]; + if (!(w2.Price > randomInRange) && pawn.kindDef.weaponTags.Any((Predicate)((string tag) => w2.thing.weaponTags.Contains(tag))) && (!(w2.thing.generateAllowChance < 1.0) || !(Rand.ValueSeeded(pawn.thingIDNumber ^ 28554824) > w2.thing.generateAllowChance))) { - if (w.thing.generateAllowChance >= 1f || Rand.ValueSeeded(pawn.thingIDNumber ^ 28554824) <= w.thing.generateAllowChance) - { - PawnWeaponGenerator.workingWeapons.Add(w); - } + PawnWeaponGenerator.workingWeapons.Add(w2); } } + if (PawnWeaponGenerator.workingWeapons.Count != 0) + { + pawn.equipment.DestroyAllEquipment(DestroyMode.Vanish); + ThingStuffPair thingStuffPair = default(ThingStuffPair); + if (((IEnumerable)PawnWeaponGenerator.workingWeapons).TryRandomElementByWeight((Func)((ThingStuffPair w) => w.Commonality * w.Price), out thingStuffPair)) + { + ThingWithComps thingWithComps = (ThingWithComps)ThingMaker.MakeThing(thingStuffPair.thing, thingStuffPair.stuff); + PawnGenerator.PostProcessGeneratedGear(thingWithComps, pawn); + pawn.equipment.AddEquipment(thingWithComps); + } + PawnWeaponGenerator.workingWeapons.Clear(); + } } - if (PawnWeaponGenerator.workingWeapons.Count == 0) - { - return; - } - pawn.equipment.DestroyAllEquipment(DestroyMode.Vanish); - ThingStuffPair thingStuffPair; - if (PawnWeaponGenerator.workingWeapons.TryRandomElementByWeight((ThingStuffPair w) => w.Commonality * w.Price, out thingStuffPair)) - { - ThingWithComps thingWithComps = (ThingWithComps)ThingMaker.MakeThing(thingStuffPair.thing, thingStuffPair.stuff); - PawnGenerator.PostProcessGeneratedGear(thingWithComps, pawn); - pawn.equipment.AddEquipment(thingWithComps); - } - PawnWeaponGenerator.workingWeapons.Clear(); } public static bool IsDerpWeapon(ThingDef thing, ThingDef stuff) @@ -91,12 +78,12 @@ public static bool IsDerpWeapon(ThingDef thing, ThingDef stuff) } if (thing.IsMeleeWeapon) { - if (thing.Verbs.NullOrEmpty()) + if (thing.Verbs.NullOrEmpty()) { return false; } DamageArmorCategoryDef armorCategory = thing.Verbs[0].meleeDamageDef.armorCategory; - if (armorCategory != null && armorCategory.multStat != null && stuff.GetStatValueAbstract(armorCategory.multStat, null) < 0.7f) + if (armorCategory != null && armorCategory.multStat != null && stuff.GetStatValueAbstract(armorCategory.multStat, null) < 0.699999988079071) { return true; } @@ -120,18 +107,9 @@ public static float CheapestNonDerpPriceFor(ThingDef weaponDef) internal static void MakeTableWeaponPairs() { - IEnumerable arg_153_0 = from p in PawnWeaponGenerator.allWeaponPairs + DebugTables.MakeTablesDialog(from p in PawnWeaponGenerator.allWeaponPairs orderby p.thing.defName descending - select p; - TableDataGetter[] expr_2D = new TableDataGetter[7]; - expr_2D[0] = new TableDataGetter("thing", (ThingStuffPair p) => p.thing.defName); - expr_2D[1] = new TableDataGetter("stuff", (ThingStuffPair p) => (p.stuff == null) ? string.Empty : p.stuff.defName); - expr_2D[2] = new TableDataGetter("price", (ThingStuffPair p) => p.Price.ToString()); - expr_2D[3] = new TableDataGetter("commonality", (ThingStuffPair p) => p.Commonality.ToString("F5")); - expr_2D[4] = new TableDataGetter("commMult", (ThingStuffPair p) => p.commonalityMultiplier.ToString("F5")); - expr_2D[5] = new TableDataGetter("def-commonality", (ThingStuffPair p) => p.thing.generateCommonality.ToString("F2")); - expr_2D[6] = new TableDataGetter("derp", (ThingStuffPair p) => (!PawnWeaponGenerator.IsDerpWeapon(p.thing, p.stuff)) ? string.Empty : "D"); - DebugTables.MakeTablesDialog(arg_153_0, expr_2D); + select p, new TableDataGetter("thing", (Func)((ThingStuffPair p) => p.thing.defName)), new TableDataGetter("stuff", (Func)((ThingStuffPair p) => (p.stuff == null) ? string.Empty : p.stuff.defName)), new TableDataGetter("price", (Func)((ThingStuffPair p) => p.Price.ToString())), new TableDataGetter("commonality", (Func)((ThingStuffPair p) => p.Commonality.ToString("F5"))), new TableDataGetter("commMult", (Func)((ThingStuffPair p) => p.commonalityMultiplier.ToString("F5"))), new TableDataGetter("def-commonality", (Func)((ThingStuffPair p) => p.thing.generateCommonality.ToString("F2"))), new TableDataGetter("derp", (Func)((ThingStuffPair p) => (!PawnWeaponGenerator.IsDerpWeapon(p.thing, p.stuff)) ? string.Empty : "D"))); } internal static void MakeTableWeaponPairsByThing() diff --git a/Assembly-CSharp/RimWorld/PawnWoundDrawer.cs b/Assembly-CSharp/RimWorld/PawnWoundDrawer.cs index 80d2bb5ce..12717f637 100644 --- a/Assembly-CSharp/RimWorld/PawnWoundDrawer.cs +++ b/Assembly-CSharp/RimWorld/PawnWoundDrawer.cs @@ -1,4 +1,3 @@ -using System; using System.Collections.Generic; using UnityEngine; using Verse; @@ -22,20 +21,20 @@ public Wound(Pawn pawn) { if (pawn.RaceProps.FleshType == FleshTypeDefOf.Normal) { - this.mat = PawnWoundDrawer.WoundOverlays_Flesh.RandomElement(); + this.mat = PawnWoundDrawer.WoundOverlays_Flesh.RandomElement(); } else if (pawn.RaceProps.FleshType == FleshTypeDefOf.Mechanoid) { - this.mat = PawnWoundDrawer.WoundOverlays_Mech.RandomElement(); + this.mat = PawnWoundDrawer.WoundOverlays_Mech.RandomElement(); } else if (pawn.RaceProps.FleshType == FleshTypeDefOf.Insectoid) { - this.mat = PawnWoundDrawer.WoundOverlays_Insect.RandomElement(); + this.mat = PawnWoundDrawer.WoundOverlays_Insect.RandomElement(); } else { Log.ErrorOnce(string.Format("No wound graphics data available for flesh type {0}", pawn.RaceProps.FleshType), 76591733); - this.mat = PawnWoundDrawer.WoundOverlays_Flesh.RandomElement(); + this.mat = PawnWoundDrawer.WoundOverlays_Flesh.RandomElement(); } this.quat = Quaternion.AngleAxis((float)Rand.Range(0, 360), Vector3.up); for (int i = 0; i < 4; i++) @@ -47,7 +46,13 @@ public Wound(Pawn pawn) public void DrawWound(Vector3 drawLoc, Quaternion bodyQuat, Rot4 bodyRot, bool forPortrait) { Vector2 vector = this.locsPerSide[bodyRot.AsInt]; - drawLoc += new Vector3((vector.x - 0.5f) * PawnWoundDrawer.Wound.WoundSpan.x, 0f, (vector.y - 0.5f) * PawnWoundDrawer.Wound.WoundSpan.y); + Vector3 a = drawLoc; + double num = vector.x - 0.5; + Vector2 woundSpan = Wound.WoundSpan; + double x = num * woundSpan.x; + double num2 = vector.y - 0.5; + Vector2 woundSpan2 = Wound.WoundSpan; + drawLoc = a + new Vector3((float)x, 0f, (float)(num2 * woundSpan2.y)); drawLoc.z -= 0.3f; GenDraw.DrawMeshNowOrLater(MeshPool.plane025, drawLoc, this.quat, this.mat, forPortrait); } @@ -55,7 +60,7 @@ public void DrawWound(Vector3 drawLoc, Quaternion bodyQuat, Rot4 bodyRot, bool f protected Pawn pawn; - private List wounds = new List(); + private List wounds = new List(); private int MaxDisplayWounds = 3; @@ -73,28 +78,20 @@ public void DrawWound(Vector3 drawLoc, Quaternion bodyQuat, Rot4 bodyRot, bool f MaterialPool.MatFrom("Things/Pawn/Wounds/WoundMechC") }; - private static readonly Color InsectWoundColor; + private static readonly Color InsectWoundColor = new ColorInt(60, 50, 40).ToColor; - private static readonly List WoundOverlays_Insect; + private static readonly List WoundOverlays_Insect = new List + { + MaterialPool.MatFrom("Things/Pawn/Wounds/WoundA", ShaderDatabase.Cutout, PawnWoundDrawer.InsectWoundColor), + MaterialPool.MatFrom("Things/Pawn/Wounds/WoundB", ShaderDatabase.Cutout, PawnWoundDrawer.InsectWoundColor), + MaterialPool.MatFrom("Things/Pawn/Wounds/WoundC", ShaderDatabase.Cutout, PawnWoundDrawer.InsectWoundColor) + }; public PawnWoundDrawer(Pawn pawn) { this.pawn = pawn; } - static PawnWoundDrawer() - { - // Note: this type is marked as 'beforefieldinit'. - ColorInt colorInt = new ColorInt(60, 50, 40); - PawnWoundDrawer.InsectWoundColor = colorInt.ToColor; - PawnWoundDrawer.WoundOverlays_Insect = new List - { - MaterialPool.MatFrom("Things/Pawn/Wounds/WoundA", ShaderDatabase.Cutout, PawnWoundDrawer.InsectWoundColor), - MaterialPool.MatFrom("Things/Pawn/Wounds/WoundB", ShaderDatabase.Cutout, PawnWoundDrawer.InsectWoundColor), - MaterialPool.MatFrom("Things/Pawn/Wounds/WoundC", ShaderDatabase.Cutout, PawnWoundDrawer.InsectWoundColor) - }; - } - public void RenderOverBody(Vector3 drawLoc, Mesh bodyMesh, Quaternion quat, bool forPortrait) { int num = 0; @@ -110,19 +107,19 @@ public void RenderOverBody(Vector3 drawLoc, Mesh bodyMesh, Quaternion quat, bool } } } - int num2 = Mathf.CeilToInt((float)num / 2f); + int num2 = Mathf.CeilToInt((float)((float)num / 2.0)); if (num2 > this.MaxDisplayWounds) { num2 = this.MaxDisplayWounds; } while (this.wounds.Count < num2) { - this.wounds.Add(new PawnWoundDrawer.Wound(this.pawn)); + this.wounds.Add(new Wound(this.pawn)); PortraitsCache.SetDirty(this.pawn); } while (this.wounds.Count > num2) { - this.wounds.Remove(this.wounds.RandomElement()); + this.wounds.Remove(this.wounds.RandomElement()); PortraitsCache.SetDirty(this.pawn); } for (int j = 0; j < this.wounds.Count; j++) diff --git a/Assembly-CSharp/RimWorld/Pawn_ApparelTracker.cs b/Assembly-CSharp/RimWorld/Pawn_ApparelTracker.cs index d318fc5be..1f75bdf25 100644 --- a/Assembly-CSharp/RimWorld/Pawn_ApparelTracker.cs +++ b/Assembly-CSharp/RimWorld/Pawn_ApparelTracker.cs @@ -1,6 +1,5 @@ using System; using System.Collections.Generic; -using System.Diagnostics; using UnityEngine; using Verse; @@ -40,11 +39,10 @@ public IEnumerable WornApparelInDrawOrder { get { - Pawn_ApparelTracker.<>c__IteratorE2 <>c__IteratorE = new Pawn_ApparelTracker.<>c__IteratorE2(); - <>c__IteratorE.<>f__this = this; - Pawn_ApparelTracker.<>c__IteratorE2 expr_0E = <>c__IteratorE; - expr_0E.$PC = -2; - return expr_0E; + for (int i = 0; i < this.wornApparel.Count; i++) + { + yield return this.wornApparel[i]; + } } } @@ -64,14 +62,18 @@ public bool PsychologicallyNude { return false; } - bool flag; - bool flag2; + bool flag = default(bool); + bool flag2 = default(bool); this.HasBasicApparel(out flag, out flag2); if (this.pawn.gender == Gender.Male) { return !flag; } - return this.pawn.gender == Gender.Female && (!flag || !flag2); + if (this.pawn.gender == Gender.Female) + { + return !flag || !flag2; + } + return false; } } @@ -83,7 +85,7 @@ public Pawn_ApparelTracker(Pawn pawn) public void ExposeData() { - Scribe_Deep.Look>(ref this.wornApparel, "wornApparel", new object[] + Scribe_Deep.Look>(ref this.wornApparel, "wornApparel", new object[1] { this }); @@ -116,10 +118,7 @@ public void ApparelTrackerTick() this.wornApparel.ThingOwnerTick(true); if (this.pawn.IsColonist && this.pawn.Spawned && !this.pawn.Dead && this.pawn.IsHashIntervalTick(60000) && this.PsychologicallyNude) { - TaleRecorder.RecordTale(TaleDefOf.WalkedNaked, new object[] - { - this.pawn - }); + TaleRecorder.RecordTale(TaleDefOf.WalkedNaked, this.pawn); } } @@ -132,13 +131,9 @@ private void TakeWearoutDamageForDay(Thing ap) } if (ap.Destroyed && PawnUtility.ShouldSendNotificationAbout(this.pawn) && !this.pawn.Dead) { - string text = "MessageWornApparelDeterioratedAway".Translate(new object[] - { - GenLabel.ThingLabel(ap.def, ap.Stuff, 1), - this.pawn - }); - text = text.CapitalizeFirst(); - Messages.Message(text, this.pawn, MessageSound.Negative); + string str = "MessageWornApparelDeterioratedAway".Translate(GenLabel.ThingLabel(ap.def, ap.Stuff, 1), this.pawn); + str = str.CapitalizeFirst(); + Messages.Message(str, (Thing)this.pawn, MessageSound.Negative); } } @@ -162,49 +157,37 @@ public void Wear(Apparel newApparel, bool dropReplacedApparel = true) } if (!ApparelUtility.HasPartsToWear(this.pawn, newApparel.def)) { - Log.Warning(string.Concat(new object[] - { - this.pawn, - " tried to wear ", - newApparel, - " but he has no body parts required to wear it." - })); - return; + Log.Warning(this.pawn + " tried to wear " + newApparel + " but he has no body parts required to wear it."); } - for (int i = this.wornApparel.Count - 1; i >= 0; i--) + else { - Apparel apparel = this.wornApparel[i]; - if (!ApparelUtility.CanWearTogether(newApparel.def, apparel.def)) + for (int num = this.wornApparel.Count - 1; num >= 0; num--) { - if (dropReplacedApparel) + Apparel apparel = this.wornApparel[num]; + if (!ApparelUtility.CanWearTogether(newApparel.def, apparel.def)) { - bool forbid = this.pawn.Faction.HostileTo(Faction.OfPlayer); - Apparel apparel2; - if (!this.TryDrop(apparel, out apparel2, this.pawn.Position, forbid)) + if (dropReplacedApparel) { - Log.Error(this.pawn + " could not drop " + apparel); - return; + bool forbid = this.pawn.Faction.HostileTo(Faction.OfPlayer); + Apparel apparel2 = default(Apparel); + if (!this.TryDrop(apparel, out apparel2, this.pawn.Position, forbid)) + { + Log.Error(this.pawn + " could not drop " + apparel); + return; + } + } + else + { + this.Remove(apparel); } - } - else - { - this.Remove(apparel); } } - } - if (newApparel.Wearer != null) - { - Log.Warning(string.Concat(new object[] + if (newApparel.Wearer != null) { - this.pawn, - " is trying to wear ", - newApparel, - " but this apparel already has a wearer (", - newApparel.Wearer, - "). This may or may not cause bugs." - })); + Log.Warning(this.pawn + " is trying to wear " + newApparel + " but this apparel already has a wearer (" + newApparel.Wearer + "). This may or may not cause bugs."); + } + this.wornApparel.TryAdd(newApparel, false); } - this.wornApparel.TryAdd(newApparel, false); } public void Remove(Apparel ap) @@ -219,7 +202,7 @@ public bool TryDrop(Apparel ap, out Apparel resultingAp) public bool TryDrop(Apparel ap, out Apparel resultingAp, IntVec3 pos, bool forbid = true) { - if (this.wornApparel.TryDrop(ap, pos, this.pawn.MapHeld, ThingPlaceMode.Near, out resultingAp, null)) + if (this.wornApparel.TryDrop((Thing)ap, pos, this.pawn.MapHeld, ThingPlaceMode.Near, out resultingAp, (Action)null)) { if (resultingAp != null) { @@ -239,7 +222,7 @@ public void DropAll(IntVec3 pos, bool forbid = true) } for (int j = 0; j < Pawn_ApparelTracker.tmpApparelList.Count; j++) { - Apparel apparel; + Apparel apparel = default(Apparel); this.TryDrop(Pawn_ApparelTracker.tmpApparelList[j], out apparel, pos, forbid); } } @@ -292,7 +275,7 @@ public void Notify_LostBodyPart() private void SortWornApparelIntoDrawOrder() { - this.wornApparel.InnerListForReading.Sort((Apparel a, Apparel b) => a.def.apparel.LastLayer.CompareTo(b.def.apparel.LastLayer)); + this.wornApparel.InnerListForReading.Sort((Comparison)((Apparel a, Apparel b) => ((Enum)(object)a.def.apparel.LastLayer).CompareTo((object)b.def.apparel.LastLayer))); } public void HasBasicApparel(out bool hasPants, out bool hasShirt) @@ -313,9 +296,7 @@ public void HasBasicApparel(out bool hasPants, out bool hasShirt) hasPants = true; } if (hasShirt && hasPants) - { return; - } } } } @@ -352,19 +333,20 @@ public bool BodyPartGroupIsCovered(BodyPartGroupDef bp) return false; } - [DebuggerHidden] public IEnumerable GetGizmos() { - Pawn_ApparelTracker.c__IteratorE3 c__IteratorE = new Pawn_ApparelTracker.c__IteratorE3(); - c__IteratorE.<>f__this = this; - Pawn_ApparelTracker.c__IteratorE3 expr_0E = c__IteratorE; - expr_0E.$PC = -2; - return expr_0E; + for (int i = 0; i < this.wornApparel.Count; i++) + { + foreach (Gizmo wornGizmo in this.wornApparel[i].GetWornGizmos()) + { + yield return wornGizmo; + } + } } private void ApparelChanged() { - LongEventHandler.ExecuteWhenFinished(delegate + LongEventHandler.ExecuteWhenFinished((Action)delegate { this.pawn.Drawer.renderer.graphics.ResolveApparelGraphics(); PortraitsCache.SetDirty(this.pawn); diff --git a/Assembly-CSharp/RimWorld/Pawn_DraftController.cs b/Assembly-CSharp/RimWorld/Pawn_DraftController.cs index c098c9034..c3af0db15 100644 --- a/Assembly-CSharp/RimWorld/Pawn_DraftController.cs +++ b/Assembly-CSharp/RimWorld/Pawn_DraftController.cs @@ -1,6 +1,5 @@ using System; using System.Collections.Generic; -using System.Diagnostics; using Verse; using Verse.AI; using Verse.AI.Group; @@ -25,36 +24,35 @@ public bool Drafted } set { - if (value == this.draftedInt) + if (value != this.draftedInt) { - return; - } - this.pawn.mindState.priorityWork.ClearPrioritizedWorkAndJobQueue(); - this.fireAtWillInt = true; - this.draftedInt = value; - if (!value && this.pawn.Spawned) - { - this.pawn.Map.pawnDestinationManager.UnreserveAllFor(this.pawn); - } - if (this.pawn.jobs.curJob != null && this.pawn.jobs.IsCurrentJobPlayerInterruptible()) - { - this.pawn.jobs.EndCurrentJob(JobCondition.InterruptForced, true); - } - if (this.draftedInt) - { - foreach (Pawn current in PawnUtility.SpawnedMasteredPawns(this.pawn)) + this.pawn.mindState.priorityWork.ClearPrioritizedWorkAndJobQueue(); + this.fireAtWillInt = true; + this.draftedInt = value; + if (!value && this.pawn.Spawned) { - current.jobs.Notify_MasterDrafted(); + this.pawn.Map.pawnDestinationManager.UnreserveAllFor(this.pawn); } - Lord lord = this.pawn.GetLord(); - if (lord != null && lord.LordJob is LordJob_VoluntarilyJoinable) + if (this.pawn.jobs.curJob != null && this.pawn.jobs.IsCurrentJobPlayerInterruptible()) { - lord.Notify_PawnLost(this.pawn, PawnLostCondition.Drafted); + this.pawn.jobs.EndCurrentJob(JobCondition.InterruptForced, true); + } + if (this.draftedInt) + { + foreach (Pawn item in PawnUtility.SpawnedMasteredPawns(this.pawn)) + { + item.jobs.Notify_MasterDrafted(); + } + Lord lord = this.pawn.GetLord(); + if (lord != null && lord.LordJob is LordJob_VoluntarilyJoinable) + { + lord.Notify_PawnLost(this.pawn, PawnLostCondition.Drafted); + } + } + else if (this.pawn.playerSettings != null) + { + this.pawn.playerSettings.animalsReleased = false; } - } - else if (this.pawn.playerSettings != null) - { - this.pawn.playerSettings.animalsReleased = false; } } } @@ -85,7 +83,7 @@ public void ExposeData() { Scribe_Values.Look(ref this.draftedInt, "drafted", false, false); Scribe_Values.Look(ref this.fireAtWillInt, "fireAtWill", true, false); - Scribe_Deep.Look(ref this.autoUndrafter, "autoUndrafter", new object[] + Scribe_Deep.Look(ref this.autoUndrafter, "autoUndrafter", new object[1] { this.pawn }); @@ -96,14 +94,55 @@ public void DraftControllerTick() this.autoUndrafter.AutoUndraftTick(); } - [DebuggerHidden] internal IEnumerable GetGizmos() { - Pawn_DraftController.c__IteratorE1 c__IteratorE = new Pawn_DraftController.c__IteratorE1(); - c__IteratorE.<>f__this = this; - Pawn_DraftController.c__IteratorE1 expr_0E = c__IteratorE; - expr_0E.$PC = -2; - return expr_0E; + Command_Toggle draft = new Command_Toggle + { + hotKey = KeyBindingDefOf.CommandColonistDraft, + isActive = (Func)(() => ((_003CGetGizmos_003Ec__IteratorE1)/*Error near IL_0046: stateMachine*/)._003C_003Ef__this.Drafted), + toggleAction = (Action)delegate + { + ((_003CGetGizmos_003Ec__IteratorE1)/*Error near IL_005d: stateMachine*/)._003C_003Ef__this.Drafted = !((_003CGetGizmos_003Ec__IteratorE1)/*Error near IL_005d: stateMachine*/)._003C_003Ef__this.Drafted; + PlayerKnowledgeDatabase.KnowledgeDemonstrated(ConceptDefOf.Drafting, KnowledgeAmount.SpecificInteraction); + }, + defaultDesc = "CommandToggleDraftDesc".Translate(), + icon = TexCommand.Draft, + turnOnSound = SoundDefOf.DraftOn, + turnOffSound = SoundDefOf.DraftOff + }; + if (!this.Drafted) + { + draft.defaultLabel = "CommandDraftLabel".Translate(); + } + if (this.pawn.Downed) + { + draft.Disable("IsIncapped".Translate(this.pawn.NameStringShort)); + } + if (!this.Drafted) + { + draft.tutorTag = "Draft"; + } + else + { + draft.tutorTag = "Undraft"; + } + yield return (Gizmo)draft; + if (this.Drafted && this.pawn.equipment.Primary != null && this.pawn.equipment.Primary.def.IsRangedWeapon) + { + yield return (Gizmo)new Command_Toggle + { + hotKey = KeyBindingDefOf.Misc6, + isActive = (Func)(() => ((_003CGetGizmos_003Ec__IteratorE1)/*Error near IL_01d7: stateMachine*/)._003C_003Ef__this.FireAtWill), + toggleAction = (Action)delegate + { + ((_003CGetGizmos_003Ec__IteratorE1)/*Error near IL_01ee: stateMachine*/)._003C_003Ef__this.FireAtWill = !((_003CGetGizmos_003Ec__IteratorE1)/*Error near IL_01ee: stateMachine*/)._003C_003Ef__this.FireAtWill; + }, + icon = TexCommand.FireAtWill, + defaultLabel = "CommandFireAtWillLabel".Translate(), + defaultDesc = "CommandFireAtWillDesc".Translate(), + tutorTag = "FireAtWillToggle" + }; + } } internal void Notify_PrimaryWeaponChanged() diff --git a/Assembly-CSharp/RimWorld/Pawn_DrugPolicyTracker.cs b/Assembly-CSharp/RimWorld/Pawn_DrugPolicyTracker.cs index e96d6e07b..653e11502 100644 --- a/Assembly-CSharp/RimWorld/Pawn_DrugPolicyTracker.cs +++ b/Assembly-CSharp/RimWorld/Pawn_DrugPolicyTracker.cs @@ -28,11 +28,10 @@ public DrugPolicy CurrentPolicy } set { - if (this.curPolicy == value) + if (this.curPolicy != value) { - return; + this.curPolicy = value; } - this.curPolicy = value; } } @@ -49,24 +48,24 @@ private float DayPercentNotSleeping return GenLocalDate.DayPercent(this.pawn); } float hoursPerDayNotSleeping = this.HoursPerDayNotSleeping; - if (hoursPerDayNotSleeping == 0f) + if (hoursPerDayNotSleeping == 0.0) { return 1f; } float num = 0f; int num2 = GenLocalDate.HourOfDay(this.pawn); - for (int i = 0; i < num2; i++) + for (int num3 = 0; num3 < num2; num3++) { - if (this.pawn.timetable.times[i] != TimeAssignmentDefOf.Sleep) + if (this.pawn.timetable.times[num3] != TimeAssignmentDefOf.Sleep) { - num += 1f; + num = (float)(num + 1.0); } } TimeAssignmentDef currentAssignment = this.pawn.timetable.CurrentAssignment; if (currentAssignment != TimeAssignmentDefOf.Sleep) { - float num3 = (float)(Find.TickManager.TicksAbs % 2500) / 2500f; - num += num3; + float num4 = (float)((float)(Find.TickManager.TicksAbs % 2500) / 2500.0); + num += num4; } return num / hoursPerDayNotSleeping; } @@ -114,7 +113,7 @@ public bool HasEverTaken(ThingDef drug) Log.Warning(drug + " is not a drug."); return false; } - return this.drugTakeRecords.Any((DrugTakeRecord x) => x.drug == drug); + return this.drugTakeRecords.Any((Predicate)((DrugTakeRecord x) => x.drug == drug)); } public bool AllowedToTakeScheduledEver(ThingDef thingDef) @@ -130,7 +129,15 @@ public bool AllowedToTakeScheduledEver(ThingDef thingDef) return false; } DrugPolicyEntry drugPolicyEntry = this.CurrentPolicy[thingDef]; - return drugPolicyEntry.allowScheduled && (!thingDef.IsPleasureDrug || !this.pawn.IsTeetotaler()); + if (!drugPolicyEntry.allowScheduled) + { + return false; + } + if (thingDef.IsPleasureDrug && this.pawn.IsTeetotaler()) + { + return false; + } + return true; } public bool AllowedToTakeScheduledNow(ThingDef thingDef) @@ -150,20 +157,20 @@ public bool AllowedToTakeScheduledNow(ThingDef thingDef) return false; } DrugPolicyEntry drugPolicyEntry = this.CurrentPolicy[thingDef]; - if (drugPolicyEntry.onlyIfMoodBelow < 1f && this.pawn.needs.mood != null && this.pawn.needs.mood.CurLevelPercentage >= drugPolicyEntry.onlyIfMoodBelow) + if (drugPolicyEntry.onlyIfMoodBelow < 1.0 && this.pawn.needs.mood != null && this.pawn.needs.mood.CurLevelPercentage >= drugPolicyEntry.onlyIfMoodBelow) { return false; } - if (drugPolicyEntry.onlyIfJoyBelow < 1f && this.pawn.needs.joy != null && this.pawn.needs.joy.CurLevelPercentage >= drugPolicyEntry.onlyIfJoyBelow) + if (drugPolicyEntry.onlyIfJoyBelow < 1.0 && this.pawn.needs.joy != null && this.pawn.needs.joy.CurLevelPercentage >= drugPolicyEntry.onlyIfJoyBelow) { return false; } - DrugTakeRecord drugTakeRecord = this.drugTakeRecords.Find((DrugTakeRecord x) => x.drug == thingDef); + DrugTakeRecord drugTakeRecord = this.drugTakeRecords.Find((Predicate)((DrugTakeRecord x) => x.drug == thingDef)); if (drugTakeRecord != null) { - if (drugPolicyEntry.daysFrequency < 1f) + if (drugPolicyEntry.daysFrequency < 1.0) { - int num = Mathf.RoundToInt(1f / drugPolicyEntry.daysFrequency); + int num = Mathf.RoundToInt((float)(1.0 / drugPolicyEntry.daysFrequency)); if (drugTakeRecord.TimesTakenThisDay >= num) { return false; @@ -193,7 +200,7 @@ public bool ShouldTryToTakeScheduledNow(ThingDef ingestible) return false; } Hediff firstHediffOfDef = this.pawn.health.hediffSet.GetFirstHediffOfDef(HediffDefOf.DrugOverdose, false); - if (firstHediffOfDef != null && firstHediffOfDef.Severity > 0.5f && this.CanCauseOverdose(ingestible)) + if (firstHediffOfDef != null && firstHediffOfDef.Severity > 0.5 && this.CanCauseOverdose(ingestible)) { int num = this.LastTicksWhenTakenDrugWhichCanCauseOverdose(); if (Find.TickManager.TicksGame - num < 1250) @@ -201,26 +208,34 @@ public bool ShouldTryToTakeScheduledNow(ThingDef ingestible) return false; } } - DrugTakeRecord drugTakeRecord = this.drugTakeRecords.Find((DrugTakeRecord x) => x.drug == ingestible); + DrugTakeRecord drugTakeRecord = this.drugTakeRecords.Find((Predicate)((DrugTakeRecord x) => x.drug == ingestible)); if (drugTakeRecord == null) { return true; } DrugPolicyEntry drugPolicyEntry = this.CurrentPolicy[ingestible]; - if (drugPolicyEntry.daysFrequency < 1f) + if (drugPolicyEntry.daysFrequency < 1.0) { - int num2 = Mathf.RoundToInt(1f / drugPolicyEntry.daysFrequency); - float num3 = 1f / (float)(num2 + 1); + int num2 = Mathf.RoundToInt((float)(1.0 / drugPolicyEntry.daysFrequency)); + float num3 = (float)(1.0 / (float)(num2 + 1)); int num4 = 0; float dayPercentNotSleeping = this.DayPercentNotSleeping; - for (int i = 0; i < num2; i++) + for (int num5 = 0; num5 < num2; num5++) { - if (dayPercentNotSleeping > (float)(i + 1) * num3 - num3 * 0.5f) + if (dayPercentNotSleeping > (float)(num5 + 1) * num3 - num3 * 0.5) { num4++; } } - return drugTakeRecord.TimesTakenThisDay < num4 && (drugTakeRecord.TimesTakenThisDay == 0 || (float)(Find.TickManager.TicksGame - drugTakeRecord.lastTakenTicks) / (this.HoursPerDayNotSleeping * 2500f) >= 0.6f * num3); + if (drugTakeRecord.TimesTakenThisDay >= num4) + { + return false; + } + if (drugTakeRecord.TimesTakenThisDay != 0 && (float)(Find.TickManager.TicksGame - drugTakeRecord.lastTakenTicks) / (this.HoursPerDayNotSleeping * 2500.0) < 0.60000002384185791 * num3) + { + return false; + } + return true; } float dayPercentNotSleeping2 = this.DayPercentNotSleeping; Rand.PushState(); @@ -232,7 +247,7 @@ public bool ShouldTryToTakeScheduledNow(ThingDef ingestible) public void Notify_DrugIngested(Thing drug) { - DrugTakeRecord drugTakeRecord = this.drugTakeRecords.Find((DrugTakeRecord x) => x.drug == drug.def); + DrugTakeRecord drugTakeRecord = this.drugTakeRecords.Find((Predicate)((DrugTakeRecord x) => x.drug == drug.def)); if (drugTakeRecord == null) { drugTakeRecord = new DrugTakeRecord(); @@ -259,7 +274,11 @@ private int LastTicksWhenTakenDrugWhichCanCauseOverdose() private bool CanCauseOverdose(ThingDef drug) { CompProperties_Drug compProperties = drug.GetCompProperties(); - return compProperties != null && compProperties.CanCauseOverdose; + if (compProperties == null) + { + return false; + } + return compProperties.CanCauseOverdose; } } } diff --git a/Assembly-CSharp/RimWorld/Pawn_FilthTracker.cs b/Assembly-CSharp/RimWorld/Pawn_FilthTracker.cs index ecfef30a2..ccb338069 100644 --- a/Assembly-CSharp/RimWorld/Pawn_FilthTracker.cs +++ b/Assembly-CSharp/RimWorld/Pawn_FilthTracker.cs @@ -51,11 +51,11 @@ public void ExposeData() public void Notify_EnteredNewCell() { - if (Rand.Value < 0.05f) + if (Rand.Value < 0.05000000074505806) { this.TryDropFilth(); } - if (Rand.Value < 0.25f) + if (Rand.Value < 0.25) { this.TryPickupFilth(); } @@ -70,25 +70,25 @@ private void TryPickupFilth() TerrainDef terrDef = this.pawn.Map.terrainGrid.TerrainAt(this.pawn.Position); if (terrDef.terrainFilthDef != null) { - for (int i = this.carriedFilth.Count - 1; i >= 0; i--) + for (int num = this.carriedFilth.Count - 1; num >= 0; num--) { - if (this.carriedFilth[i].def.filth.terrainSourced && this.carriedFilth[i].def != terrDef.terrainFilthDef) + if (this.carriedFilth[num].def.filth.terrainSourced && this.carriedFilth[num].def != terrDef.terrainFilthDef) { - this.ThinCarriedFilth(this.carriedFilth[i]); + this.ThinCarriedFilth(this.carriedFilth[num]); } } Filth filth = (from f in this.carriedFilth where f.def == terrDef.terrainFilthDef - select f).FirstOrDefault(); + select f).FirstOrDefault(); if (filth == null || filth.thickness < 1) { this.GainFilth(terrDef.terrainFilthDef); } } List thingList = this.pawn.Position.GetThingList(this.pawn.Map); - for (int j = thingList.Count - 1; j >= 0; j--) + for (int num2 = thingList.Count - 1; num2 >= 0; num2--) { - Filth filth2 = thingList[j] as Filth; + Filth filth2 = thingList[num2] as Filth; if (filth2 != null && filth2.CanFilthAttachNow) { this.GainFilth(filth2.def, filth2.sources); @@ -99,15 +99,14 @@ private void TryPickupFilth() private void TryDropFilth() { - if (this.carriedFilth.Count == 0) + if (this.carriedFilth.Count != 0) { - return; - } - for (int i = this.carriedFilth.Count - 1; i >= 0; i--) - { - if (this.carriedFilth[i].CanDropAt(this.pawn.Position, this.pawn.Map)) + for (int num = this.carriedFilth.Count - 1; num >= 0; num--) { - this.DropCarriedFilth(this.carriedFilth[i]); + if (this.carriedFilth[num].CanDropAt(this.pawn.Position, this.pawn.Map)) + { + this.DropCarriedFilth(this.carriedFilth[num]); + } } } } @@ -135,13 +134,16 @@ public void GainFilth(ThingDef filthDef) public void GainFilth(ThingDef filthDef, IEnumerable sources) { Filth filth = null; - for (int i = 0; i < this.carriedFilth.Count; i++) + int num = 0; + while (num < this.carriedFilth.Count) { - if (this.carriedFilth[i].def == filthDef) + if (this.carriedFilth[num].def != filthDef) { - filth = this.carriedFilth[i]; - break; + num++; + continue; } + filth = this.carriedFilth[num]; + break; } if (filth != null) { diff --git a/Assembly-CSharp/RimWorld/Pawn_GuestTracker.cs b/Assembly-CSharp/RimWorld/Pawn_GuestTracker.cs index c586ed225..105e36142 100644 --- a/Assembly-CSharp/RimWorld/Pawn_GuestTracker.cs +++ b/Assembly-CSharp/RimWorld/Pawn_GuestTracker.cs @@ -1,4 +1,3 @@ -using System; using Verse; using Verse.AI.Group; @@ -117,7 +116,15 @@ public bool ShouldWaitInsteadOfEscaping return false; } Map mapHeld = this.pawn.MapHeld; - return mapHeld != null && mapHeld.mapPawns.FreeColonistsSpawnedCount != 0 && Find.TickManager.TicksGame < this.ticksWhenAllowedToEscapeAgain; + if (mapHeld == null) + { + return false; + } + if (mapHeld.mapPawns.FreeColonistsSpawnedCount == 0) + { + return false; + } + return Find.TickManager.TicksGame < this.ticksWhenAllowedToEscapeAgain; } } @@ -135,7 +142,7 @@ public void GuestTrackerTick() if (this.pawn.IsHashIntervalTick(2500)) { float num = PrisonBreakUtility.InitiatePrisonBreakMtbDays(this.pawn); - if (num >= 0f && Rand.MTBEventOccurs(num, 60000f, 2500f)) + if (num >= 0.0 && Rand.MTBEventOccurs(num, 60000f, 2500f)) { PrisonBreakUtility.StartPrisonBreak(this.pawn); } @@ -160,69 +167,52 @@ public void SetGuestStatus(Faction newHost, bool prisoner = false) this.released = false; } if (newHost == this.HostFaction && prisoner == this.IsPrisoner) - { return; - } if (!prisoner && this.pawn.Faction.HostileTo(newHost)) { - Log.Error(string.Concat(new object[] - { - "Tried to make ", - this.pawn, - " a guest of ", - newHost, - " but their faction ", - this.pawn.Faction, - " is hostile to ", - newHost - })); - return; + Log.Error("Tried to make " + this.pawn + " a guest of " + newHost + " but their faction " + this.pawn.Faction + " is hostile to " + newHost); } - if (newHost != null && newHost == this.pawn.Faction && !prisoner) + else if (newHost != null && newHost == this.pawn.Faction && !prisoner) { - Log.Error(string.Concat(new object[] - { - "Tried to make ", - this.pawn, - " a guest of their own faction ", - this.pawn.Faction - })); - return; + Log.Error("Tried to make " + this.pawn + " a guest of their own faction " + this.pawn.Faction); } - bool flag = prisoner && (!this.IsPrisoner || this.HostFaction != newHost); - this.isPrisonerInt = prisoner; - this.hostFactionInt = newHost; - this.pawn.ClearMind(false); - this.pawn.ClearReservations(true); - if (flag) + else { - this.pawn.DropAndForbidEverything(false); - Lord lord = this.pawn.GetLord(); - if (lord != null) + bool flag = prisoner && (!this.IsPrisoner || this.HostFaction != newHost); + this.isPrisonerInt = prisoner; + this.hostFactionInt = newHost; + this.pawn.ClearMind(false); + this.pawn.ClearReservations(true); + if (flag) { - lord.Notify_PawnLost(this.pawn, PawnLostCondition.MadePrisoner); + this.pawn.DropAndForbidEverything(false); + Lord lord = this.pawn.GetLord(); + if (lord != null) + { + lord.Notify_PawnLost(this.pawn, PawnLostCondition.MadePrisoner); + } + if (this.pawn.Drafted) + { + this.pawn.drafter.Drafted = false; + } } - if (this.pawn.Drafted) + PawnComponentsUtility.AddAndRemoveDynamicComponents(this.pawn, false); + this.pawn.health.surgeryBills.Clear(); + if (this.pawn.ownership != null) { - this.pawn.drafter.Drafted = false; + this.pawn.ownership.Notify_ChangedGuestStatus(); + } + ReachabilityUtility.ClearCache(); + if (this.pawn.Spawned) + { + this.pawn.Map.mapPawns.UpdateRegistryForPawn(this.pawn); + this.pawn.Map.attackTargetsCache.UpdateTarget(this.pawn); + } + AddictionUtility.CheckDrugAddictionTeachOpportunity(this.pawn); + if (prisoner && this.pawn.playerSettings != null) + { + this.pawn.playerSettings.Notify_MadePrisoner(); } - } - PawnComponentsUtility.AddAndRemoveDynamicComponents(this.pawn, false); - this.pawn.health.surgeryBills.Clear(); - if (this.pawn.ownership != null) - { - this.pawn.ownership.Notify_ChangedGuestStatus(); - } - ReachabilityUtility.ClearCache(); - if (this.pawn.Spawned) - { - this.pawn.Map.mapPawns.UpdateRegistryForPawn(this.pawn); - this.pawn.Map.attackTargetsCache.UpdateTarget(this.pawn); - } - AddictionUtility.CheckDrugAddictionTeachOpportunity(this.pawn); - if (prisoner && this.pawn.playerSettings != null) - { - this.pawn.playerSettings.Notify_MadePrisoner(); } } @@ -233,35 +223,28 @@ public void WaitInsteadOfEscapingForDefaultTicks() public void WaitInsteadOfEscapingFor(int ticks) { - if (!this.IsPrisoner) + if (this.IsPrisoner) { - return; + this.ticksWhenAllowedToEscapeAgain = Find.TickManager.TicksGame + ticks; + this.spotToWaitInsteadOfEscaping = IntVec3.Invalid; } - this.ticksWhenAllowedToEscapeAgain = Find.TickManager.TicksGame + ticks; - this.spotToWaitInsteadOfEscaping = IntVec3.Invalid; } internal void Notify_PawnUndowned() { - if (this.pawn.RaceProps.Humanlike && this.HostFaction == Faction.OfPlayer && (this.pawn.Faction == null || this.pawn.Faction.def.rescueesCanJoin) && !this.IsPrisoner && this.pawn.SpawnedOrAnyParentSpawned) + if (this.pawn.RaceProps.Humanlike && this.HostFaction == Faction.OfPlayer) { - Map mapHeld = this.pawn.MapHeld; - float num; - if (!this.pawn.SafeTemperatureRange().Includes(mapHeld.mapTemperature.OutdoorTemp) || mapHeld.gameConditionManager.ConditionIsActive(GameConditionDefOf.ToxicFallout)) - { - num = 1f; - } - else - { - num = 0.5f; - } - if (Rand.ValueSeeded(this.pawn.thingIDNumber ^ 8976612) < num) + if (this.pawn.Faction != null && !this.pawn.Faction.def.rescueesCanJoin) + return; + if (!this.IsPrisoner && this.pawn.SpawnedOrAnyParentSpawned) { - this.pawn.SetFaction(Faction.OfPlayer, null); - Messages.Message("MessageRescueeJoined".Translate(new object[] + Map mapHeld = this.pawn.MapHeld; + float num = (float)((this.pawn.SafeTemperatureRange().Includes(mapHeld.mapTemperature.OutdoorTemp) && !mapHeld.gameConditionManager.ConditionIsActive(GameConditionDefOf.ToxicFallout)) ? 0.5 : 1.0); + if (Rand.ValueSeeded(this.pawn.thingIDNumber ^ 8976612) < num) { - this.pawn.LabelShort - }).AdjustedFor(this.pawn), this.pawn, MessageSound.Benefit); + this.pawn.SetFaction(Faction.OfPlayer, null); + Messages.Message("MessageRescueeJoined".Translate(this.pawn.LabelShort).AdjustedFor(this.pawn), (Thing)this.pawn, MessageSound.Benefit); + } } } } diff --git a/Assembly-CSharp/RimWorld/Pawn_GuiltTracker.cs b/Assembly-CSharp/RimWorld/Pawn_GuiltTracker.cs index 7f7580f2f..9efe69b8e 100644 --- a/Assembly-CSharp/RimWorld/Pawn_GuiltTracker.cs +++ b/Assembly-CSharp/RimWorld/Pawn_GuiltTracker.cs @@ -1,4 +1,3 @@ -using System; using UnityEngine; using Verse; diff --git a/Assembly-CSharp/RimWorld/Pawn_InteractionsTracker.cs b/Assembly-CSharp/RimWorld/Pawn_InteractionsTracker.cs index 621250ddf..2571e125d 100644 --- a/Assembly-CSharp/RimWorld/Pawn_InteractionsTracker.cs +++ b/Assembly-CSharp/RimWorld/Pawn_InteractionsTracker.cs @@ -77,44 +77,52 @@ public void ExposeData() public void InteractionsTrackerTick() { RandomSocialMode currentSocialMode = this.CurrentSocialMode; - if (currentSocialMode == RandomSocialMode.Off) + switch (currentSocialMode) + { + case RandomSocialMode.Off: { this.wantsRandomInteract = false; + return; } - else + case RandomSocialMode.Quiet: { - if (currentSocialMode == RandomSocialMode.Quiet) - { - this.wantsRandomInteract = false; - } - if (!this.wantsRandomInteract) + this.wantsRandomInteract = false; + break; + } + } + if (!this.wantsRandomInteract) + { + if (Find.TickManager.TicksGame > this.lastInteractionTime + 320 && this.pawn.IsHashIntervalTick(60)) { - if (Find.TickManager.TicksGame > this.lastInteractionTime + 320 && this.pawn.IsHashIntervalTick(60)) + int num = 0; + switch (currentSocialMode) { - int num = 0; - switch (currentSocialMode) - { - case RandomSocialMode.Quiet: - num = 22000; - break; - case RandomSocialMode.Normal: - num = 6600; - break; - case RandomSocialMode.SuperActive: - num = 550; - break; - } - if (Rand.MTBEventOccurs((float)num, 1f, 60f) && !this.TryInteractRandomly()) - { - this.wantsRandomInteract = true; - } + case RandomSocialMode.Quiet: + { + num = 22000; + break; + } + case RandomSocialMode.Normal: + { + num = 6600; + break; + } + case RandomSocialMode.SuperActive: + { + num = 550; + break; + } + } + if (Rand.MTBEventOccurs((float)num, 1f, 60f) && !this.TryInteractRandomly()) + { + this.wantsRandomInteract = true; } - } - else if (this.pawn.IsHashIntervalTick(91) && this.TryInteractRandomly()) - { - this.wantsRandomInteract = false; } } + else if (this.pawn.IsHashIntervalTick(91) && this.TryInteractRandomly()) + { + this.wantsRandomInteract = false; + } } public bool InteractedTooRecentlyToInteract() @@ -124,7 +132,23 @@ public bool InteractedTooRecentlyToInteract() private bool CanInteractNowWith(Pawn recipient) { - return recipient.Spawned && (float)(this.pawn.Position - recipient.Position).LengthHorizontalSquared <= 36f && InteractionUtility.CanInitiateInteraction(this.pawn) && InteractionUtility.CanReceiveInteraction(recipient) && GenSight.LineOfSight(this.pawn.Position, recipient.Position, this.pawn.Map, true, null, 0, 0); + if (!recipient.Spawned) + { + return false; + } + if ((float)(this.pawn.Position - recipient.Position).LengthHorizontalSquared > 36.0) + { + return false; + } + if (InteractionUtility.CanInitiateInteraction(this.pawn) && InteractionUtility.CanReceiveInteraction(recipient)) + { + if (!GenSight.LineOfSight(this.pawn.Position, recipient.Position, this.pawn.Map, true, null, 0, 0)) + { + return false; + } + return true; + } + return false; } public bool TryInteractWith(Pawn recipient, InteractionDef intDef) @@ -144,19 +168,7 @@ public bool TryInteractWith(Pawn recipient, InteractionDef intDef) } if (this.InteractedTooRecentlyToInteract()) { - Log.Error(string.Concat(new object[] - { - this.pawn, - " tried to do interaction ", - intDef, - " to ", - recipient, - " only ", - Find.TickManager.TicksGame - this.lastInteractionTime, - " ticks since last interaction (min is ", - 120, - ")." - })); + Log.Error(this.pawn + " tried to do interaction " + intDef + " to " + recipient + " only " + (Find.TickManager.TicksGame - this.lastInteractionTime) + " ticks since last interaction (min is " + 120 + ")."); return false; } List list = new List(); @@ -221,22 +233,19 @@ private bool TryInteractRandomly() List collection = this.pawn.Map.mapPawns.SpawnedPawnsInFaction(this.pawn.Faction); Pawn_InteractionsTracker.workingList.Clear(); Pawn_InteractionsTracker.workingList.AddRange(collection); - Pawn_InteractionsTracker.workingList.Shuffle(); + Pawn_InteractionsTracker.workingList.Shuffle(); List allDefsListForReading = DefDatabase.AllDefsListForReading; for (int i = 0; i < Pawn_InteractionsTracker.workingList.Count; i++) { Pawn p = Pawn_InteractionsTracker.workingList[i]; - if (p != this.pawn && this.CanInteractNowWith(p) && InteractionUtility.CanReceiveRandomInteraction(p) && !this.pawn.HostileTo(p)) + InteractionDef intDef = default(InteractionDef); + if (p != this.pawn && this.CanInteractNowWith(p) && InteractionUtility.CanReceiveRandomInteraction(p) && !this.pawn.HostileTo(p) && ((IEnumerable)allDefsListForReading).TryRandomElementByWeight((Func)((InteractionDef x) => x.Worker.RandomSelectionWeight(this.pawn, p)), out intDef)) { - InteractionDef intDef; - if (allDefsListForReading.TryRandomElementByWeight((InteractionDef x) => x.Worker.RandomSelectionWeight(this.pawn, p), out intDef)) + if (this.TryInteractWith(p, intDef)) { - if (this.TryInteractWith(p, intDef)) - { - return true; - } - Log.Error(this.pawn + " failed to interact with " + p); + return true; } + Log.Error(this.pawn + " failed to interact with " + p); } } return false; @@ -244,16 +253,16 @@ private bool TryInteractRandomly() public bool CheckSocialFightStart(InteractionDef interaction, Pawn initiator) { - if (this.pawn.needs.mood == null || TutorSystem.TutorialMode) - { - return false; - } - if (!InteractionUtility.HasAnySocialFightProvokingThought(this.pawn, initiator)) - { - return false; - } - if (DebugSettings.alwaysSocialFight || Rand.Value < this.SocialFightChance(interaction, initiator)) + if (this.pawn.needs.mood != null && !TutorSystem.TutorialMode) { + if (!InteractionUtility.HasAnySocialFightProvokingThought(this.pawn, initiator)) + { + return false; + } + if (!DebugSettings.alwaysSocialFight && !(Rand.Value < this.SocialFightChance(interaction, initiator))) + { + return false; + } this.StartSocialFight(initiator); return true; } @@ -264,92 +273,71 @@ public void StartSocialFight(Pawn otherPawn) { if (PawnUtility.ShouldSendNotificationAbout(this.pawn) || PawnUtility.ShouldSendNotificationAbout(otherPawn)) { - Thought thought; + Thought thought = default(Thought); if (!InteractionUtility.TryGetRandomSocialFightProvokingThought(this.pawn, otherPawn, out thought)) { - Log.Warning(string.Concat(new object[] - { - "Pawn ", - this.pawn, - " started a social fight with ", - otherPawn, - ", but he has no negative opinion thoughts towards ", - otherPawn, - "." - })); + Log.Warning("Pawn " + this.pawn + " started a social fight with " + otherPawn + ", but he has no negative opinion thoughts towards " + otherPawn + "."); } else { - Messages.Message("MessageSocialFight".Translate(new object[] - { - this.pawn.LabelShort, - otherPawn.LabelShort, - thought.LabelCapSocial - }), this.pawn, MessageSound.SeriousAlert); + Messages.Message("MessageSocialFight".Translate(this.pawn.LabelShort, otherPawn.LabelShort, thought.LabelCapSocial), (Thing)this.pawn, MessageSound.SeriousAlert); } } - this.pawn.mindState.mentalStateHandler.TryStartMentalState(MentalStateDefOf.SocialFighting, null, false, false, otherPawn); - MentalStateHandler arg_F1_0 = otherPawn.mindState.mentalStateHandler; + this.pawn.mindState.mentalStateHandler.TryStartMentalState(MentalStateDefOf.SocialFighting, (string)null, false, false, otherPawn); + MentalStateHandler mentalStateHandler = otherPawn.mindState.mentalStateHandler; Pawn otherPawn2 = this.pawn; - arg_F1_0.TryStartMentalState(MentalStateDefOf.SocialFighting, null, false, false, otherPawn2); + mentalStateHandler.TryStartMentalState(MentalStateDefOf.SocialFighting, (string)null, false, false, otherPawn2); } public float SocialFightChance(InteractionDef interaction, Pawn initiator) { - if (!this.pawn.RaceProps.Humanlike || !initiator.RaceProps.Humanlike) - { - return 0f; - } - if (!InteractionUtility.HasAnyVerbForSocialFight(this.pawn) || !InteractionUtility.HasAnyVerbForSocialFight(initiator)) + if (this.pawn.RaceProps.Humanlike && initiator.RaceProps.Humanlike) { - return 0f; - } - if (this.pawn.story.WorkTagIsDisabled(WorkTags.Violent)) - { - return 0f; - } - if (initiator.Downed || this.pawn.Downed) - { - return 0f; - } - float num = interaction.socialFightBaseChance; - num *= Mathf.InverseLerp(0.3f, 1f, this.pawn.health.capacities.GetLevel(PawnCapacityDefOf.Manipulation)); - num *= Mathf.InverseLerp(0.3f, 1f, this.pawn.health.capacities.GetLevel(PawnCapacityDefOf.Moving)); - List hediffs = this.pawn.health.hediffSet.hediffs; - for (int i = 0; i < hediffs.Count; i++) - { - if (hediffs[i].CurStage != null) + if (InteractionUtility.HasAnyVerbForSocialFight(this.pawn) && InteractionUtility.HasAnyVerbForSocialFight(initiator)) { - num *= hediffs[i].CurStage.socialFightChanceFactor; - } - } - float num2 = (float)this.pawn.relations.OpinionOf(initiator); - if (num2 < 0f) - { - num *= GenMath.LerpDouble(-100f, 0f, 4f, 1f, num2); - } - else - { - num *= GenMath.LerpDouble(0f, 100f, 1f, 0.6f, num2); - } - if (this.pawn.RaceProps.Humanlike) - { - List allTraits = this.pawn.story.traits.allTraits; - for (int j = 0; j < allTraits.Count; j++) - { - num *= allTraits[j].CurrentData.socialFightChanceFactor; - } - } - int num3 = Mathf.Abs(this.pawn.ageTracker.AgeBiologicalYears - initiator.ageTracker.AgeBiologicalYears); - if (num3 > 10) - { - if (num3 > 50) - { - num3 = 50; + if (this.pawn.story.WorkTagIsDisabled(WorkTags.Violent)) + { + return 0f; + } + if (!initiator.Downed && !this.pawn.Downed) + { + float socialFightBaseChance = interaction.socialFightBaseChance; + socialFightBaseChance *= Mathf.InverseLerp(0.3f, 1f, this.pawn.health.capacities.GetLevel(PawnCapacityDefOf.Manipulation)); + socialFightBaseChance *= Mathf.InverseLerp(0.3f, 1f, this.pawn.health.capacities.GetLevel(PawnCapacityDefOf.Moving)); + List hediffs = this.pawn.health.hediffSet.hediffs; + for (int i = 0; i < hediffs.Count; i++) + { + if (hediffs[i].CurStage != null) + { + socialFightBaseChance *= hediffs[i].CurStage.socialFightChanceFactor; + } + } + float num = (float)this.pawn.relations.OpinionOf(initiator); + socialFightBaseChance = ((!(num < 0.0)) ? (socialFightBaseChance * GenMath.LerpDouble(0f, 100f, 1f, 0.6f, num)) : (socialFightBaseChance * GenMath.LerpDouble(-100f, 0f, 4f, 1f, num))); + if (this.pawn.RaceProps.Humanlike) + { + List allTraits = this.pawn.story.traits.allTraits; + for (int j = 0; j < allTraits.Count; j++) + { + socialFightBaseChance *= allTraits[j].CurrentData.socialFightChanceFactor; + } + } + int num2 = Mathf.Abs(this.pawn.ageTracker.AgeBiologicalYears - initiator.ageTracker.AgeBiologicalYears); + if (num2 > 10) + { + if (num2 > 50) + { + num2 = 50; + } + socialFightBaseChance *= GenMath.LerpDouble(10f, 50f, 1f, 0.25f, (float)num2); + } + return Mathf.Clamp01(socialFightBaseChance); + } + return 0f; } - num *= GenMath.LerpDouble(10f, 50f, 1f, 0.25f, (float)num3); + return 0f; } - return Mathf.Clamp01(num); + return 0f; } } } diff --git a/Assembly-CSharp/RimWorld/Pawn_MeleeVerbs.cs b/Assembly-CSharp/RimWorld/Pawn_MeleeVerbs.cs index fc3446224..45d1b978f 100644 --- a/Assembly-CSharp/RimWorld/Pawn_MeleeVerbs.cs +++ b/Assembly-CSharp/RimWorld/Pawn_MeleeVerbs.cs @@ -40,7 +40,8 @@ private void ChooseMeleeVerb() } else { - this.SetCurMeleeVerb(updatedAvailableVerbsList.RandomElementByWeight((VerbEntry ve) => ve.SelectionWeight).verb); + VerbEntry verbEntry = updatedAvailableVerbsList.RandomElementByWeight((Func)((VerbEntry ve) => ve.SelectionWeight)); + this.SetCurMeleeVerb(verbEntry.verb); } } @@ -58,28 +59,11 @@ public bool TryMeleeAttack(Thing target, Verb verbToUse = null, bool surpriseAtt } if (!(verbToUse is Verb_MeleeAttack)) { - Log.Warning(string.Concat(new object[] - { - "Pawn ", - this.pawn, - " tried to melee attack ", - target, - " with non melee-attack verb ", - verbToUse, - "." - })); + Log.Warning("Pawn " + this.pawn + " tried to melee attack " + target + " with non melee-attack verb " + verbToUse + "."); return false; } } - Verb verb; - if (verbToUse != null) - { - verb = verbToUse; - } - else - { - verb = this.TryGetMeleeVerb(); - } + Verb verb = (verbToUse == null) ? this.TryGetMeleeVerb() : verbToUse; if (verb == null) { return false; @@ -93,7 +77,7 @@ public List GetUpdatedAvailableVerbsList() Pawn_MeleeVerbs.meleeVerbs.Clear(); if (this.pawn.equipment != null && this.pawn.equipment.Primary != null) { - Verb verb = this.pawn.equipment.PrimaryEq.AllVerbs.Find((Verb x) => x is Verb_MeleeAttack); + Verb verb = this.pawn.equipment.PrimaryEq.AllVerbs.Find((Predicate)((Verb x) => x is Verb_MeleeAttack)); if (verb != null) { Pawn_MeleeVerbs.meleeVerbs.Add(new VerbEntry(verb, this.pawn, this.pawn.equipment.Primary)); @@ -108,11 +92,11 @@ public List GetUpdatedAvailableVerbsList() Pawn_MeleeVerbs.meleeVerbs.Add(new VerbEntry(allVerbs[i], this.pawn, null)); } } - foreach (Verb current in this.pawn.health.hediffSet.GetHediffsVerbs()) + foreach (Verb hediffsVerb in this.pawn.health.hediffSet.GetHediffsVerbs()) { - if (current is Verb_MeleeAttack && current.IsStillUsableBy(this.pawn)) + if (hediffsVerb is Verb_MeleeAttack && hediffsVerb.IsStillUsableBy(this.pawn)) { - Pawn_MeleeVerbs.meleeVerbs.Add(new VerbEntry(current, this.pawn, null)); + Pawn_MeleeVerbs.meleeVerbs.Add(new VerbEntry(hediffsVerb, this.pawn, null)); } } return Pawn_MeleeVerbs.meleeVerbs; diff --git a/Assembly-CSharp/RimWorld/Pawn_NativeVerbs.cs b/Assembly-CSharp/RimWorld/Pawn_NativeVerbs.cs index e14ff3b9e..707466ef1 100644 --- a/Assembly-CSharp/RimWorld/Pawn_NativeVerbs.cs +++ b/Assembly-CSharp/RimWorld/Pawn_NativeVerbs.cs @@ -1,4 +1,3 @@ -using System; using Verse; namespace RimWorld @@ -56,32 +55,28 @@ public bool TryStartIgnite(Thing target) { if (this.IgniteVerb == null) { - Log.ErrorOnce(string.Concat(new object[] - { - this.pawn, - " tried to ignite ", - target, - " but has no ignite verb." - }), 76453432); + Log.ErrorOnce(this.pawn + " tried to ignite " + target + " but has no ignite verb.", 76453432); + return false; + } + if (this.pawn.stances.FullBodyBusy) + { return false; } - return !this.pawn.stances.FullBodyBusy && this.IgniteVerb.TryStartCastOn(target, false, true); + return this.IgniteVerb.TryStartCastOn(target, false, true); } public bool TryBeatFire(Fire targetFire) { if (this.BeatFireVerb == null) { - Log.ErrorOnce(string.Concat(new object[] - { - this.pawn, - " tried to beat fire ", - targetFire, - " but has no beat fire verb." - }), 935137531); + Log.ErrorOnce(this.pawn + " tried to beat fire " + targetFire + " but has no beat fire verb.", 935137531); + return false; + } + if (this.pawn.stances.FullBodyBusy) + { return false; } - return !this.pawn.stances.FullBodyBusy && this.BeatFireVerb.TryStartCastOn(targetFire, false, true); + return this.BeatFireVerb.TryStartCastOn((Thing)targetFire, false, true); } public void ExposeData() @@ -96,7 +91,7 @@ public void ExposeData() private void CreateVerbs() { - if (this.pawn.RaceProps.intelligence >= Intelligence.ToolUser) + if ((int)this.pawn.RaceProps.intelligence >= 1) { UniqueIDsManager uniqueIDsManager = Find.World.uniqueIDsManager; this.beatFireVerb = new Verb_BeatFire(); diff --git a/Assembly-CSharp/RimWorld/Pawn_NeedsTracker.cs b/Assembly-CSharp/RimWorld/Pawn_NeedsTracker.cs index 0bbf30147..8352a5d64 100644 --- a/Assembly-CSharp/RimWorld/Pawn_NeedsTracker.cs +++ b/Assembly-CSharp/RimWorld/Pawn_NeedsTracker.cs @@ -44,7 +44,7 @@ public Pawn_NeedsTracker(Pawn newPawn) public void ExposeData() { - Scribe_Collections.Look(ref this.needs, "needs", LookMode.Deep, new object[] + Scribe_Collections.Look(ref this.needs, "needs", LookMode.Deep, new object[1] { this.pawn }); @@ -79,10 +79,10 @@ public T TryGetNeed() where T : Need { if (this.needs[i].GetType() == typeof(T)) { - return (T)((object)this.needs[i]); + return (T)this.needs[i]; } } - return (T)((object)null); + return (T)null; } public Need TryGetNeed(NeedDef def) @@ -127,7 +127,7 @@ public void AddOrRemoveNeedsAsAppropriate() private bool ShouldHaveNeed(NeedDef nd) { - if (this.pawn.RaceProps.intelligence < nd.minIntelligence) + if ((int)this.pawn.RaceProps.intelligence < (int)nd.minIntelligence) { return false; } @@ -139,7 +139,7 @@ private bool ShouldHaveNeed(NeedDef nd) { return false; } - if (nd.onlyIfCausedByHediff && !this.pawn.health.hediffSet.hediffs.Any((Hediff x) => x.def.causesNeed == nd)) + if (nd.onlyIfCausedByHediff && !this.pawn.health.hediffSet.hediffs.Any((Predicate)((Hediff x) => x.def.causesNeed == nd))) { return false; } @@ -151,15 +151,16 @@ private bool ShouldHaveNeed(NeedDef nd) { return this.pawn.RaceProps.EatsFood; } - return nd != NeedDefOf.Rest || this.pawn.RaceProps.needsRest; + if (nd == NeedDefOf.Rest) + { + return this.pawn.RaceProps.needsRest; + } + return true; } private void AddNeed(NeedDef nd) { - Need need = (Need)Activator.CreateInstance(nd.needClass, new object[] - { - this.pawn - }); + Need need = (Need)Activator.CreateInstance(nd.needClass, this.pawn); need.def = nd; this.needs.Add(need); need.SetInitialLevel(); diff --git a/Assembly-CSharp/RimWorld/Pawn_OutfitTracker.cs b/Assembly-CSharp/RimWorld/Pawn_OutfitTracker.cs index aa6d5fb06..a0d21da77 100644 --- a/Assembly-CSharp/RimWorld/Pawn_OutfitTracker.cs +++ b/Assembly-CSharp/RimWorld/Pawn_OutfitTracker.cs @@ -1,4 +1,3 @@ -using System; using Verse; namespace RimWorld @@ -23,12 +22,11 @@ public Outfit CurrentOutfit } set { - if (this.curOutfit == value) + if (this.curOutfit != value) { - return; + this.curOutfit = value; + this.pawn.mindState.Notify_OutfitChanged(); } - this.curOutfit = value; - this.pawn.mindState.Notify_OutfitChanged(); } } diff --git a/Assembly-CSharp/RimWorld/Pawn_Ownership.cs b/Assembly-CSharp/RimWorld/Pawn_Ownership.cs index b57e6217b..c3f7a45a6 100644 --- a/Assembly-CSharp/RimWorld/Pawn_Ownership.cs +++ b/Assembly-CSharp/RimWorld/Pawn_Ownership.cs @@ -1,4 +1,3 @@ -using System; using System.Linq; using Verse; @@ -62,7 +61,7 @@ public void ExposeData() { Building_Grave assignedGrave = this.AssignedGrave; Scribe_References.Look(ref this.intOwnedBed, "ownedBed", false); - Scribe_References.Look(ref assignedGrave, "assignedGrave", false); + Scribe_References.Look(ref assignedGrave, "assignedGrave", false); this.AssignedGrave = assignedGrave; if (Scribe.mode == LoadSaveMode.PostLoadInit) { @@ -80,22 +79,21 @@ public void ExposeData() public void ClaimBedIfNonMedical(Building_Bed newBed) { - if (newBed.owners.Contains(this.pawn) || newBed.Medical) + if (!newBed.owners.Contains(this.pawn) && !newBed.Medical) { - return; - } - this.UnclaimBed(); - if (newBed.owners.Count == newBed.SleepingSlotsCount) - { - newBed.owners[newBed.owners.Count - 1].ownership.UnclaimBed(); - } - newBed.owners.Add(this.pawn); - newBed.SortOwners(); - this.OwnedBed = newBed; - if (newBed.Medical) - { - Log.Warning(this.pawn.LabelCap + " claimed medical bed."); this.UnclaimBed(); + if (newBed.owners.Count == newBed.SleepingSlotsCount) + { + newBed.owners[newBed.owners.Count - 1].ownership.UnclaimBed(); + } + newBed.owners.Add(this.pawn); + newBed.SortOwners(); + this.OwnedBed = newBed; + if (newBed.Medical) + { + Log.Warning(this.pawn.LabelCap + " claimed medical bed."); + this.UnclaimBed(); + } } } @@ -110,17 +108,16 @@ public void UnclaimBed() public void ClaimGrave(Building_Grave newGrave) { - if (newGrave.assignedPawn == this.pawn) + if (newGrave.assignedPawn != this.pawn) { - return; - } - this.UnclaimGrave(); - if (newGrave.assignedPawn != null) - { - newGrave.assignedPawn.ownership.UnclaimBed(); + this.UnclaimGrave(); + if (newGrave.assignedPawn != null) + { + newGrave.assignedPawn.ownership.UnclaimBed(); + } + newGrave.assignedPawn = this.pawn; + this.AssignedGrave = newGrave; } - newGrave.assignedPawn = this.pawn; - this.AssignedGrave = newGrave; } public void UnclaimGrave() @@ -140,8 +137,15 @@ public void UnclaimAll() public void Notify_ChangedGuestStatus() { - if (this.OwnedBed != null && ((this.OwnedBed.ForPrisoners && !this.pawn.IsPrisoner) || (!this.OwnedBed.ForPrisoners && this.pawn.IsPrisoner))) + if (this.OwnedBed != null) { + if (!this.OwnedBed.ForPrisoners || this.pawn.IsPrisoner) + { + if (this.OwnedBed.ForPrisoners) + return; + if (!this.pawn.IsPrisoner) + return; + } this.UnclaimBed(); } } diff --git a/Assembly-CSharp/RimWorld/Pawn_PlayerSettings.cs b/Assembly-CSharp/RimWorld/Pawn_PlayerSettings.cs index 1b29947e9..f24cdb73c 100644 --- a/Assembly-CSharp/RimWorld/Pawn_PlayerSettings.cs +++ b/Assembly-CSharp/RimWorld/Pawn_PlayerSettings.cs @@ -1,7 +1,8 @@ using System; using System.Collections.Generic; -using System.Diagnostics; +using System.Linq; using Verse; +using Verse.AI; using Verse.AI.Group; namespace RimWorld @@ -68,7 +69,11 @@ public bool RespectsAllowedArea { get { - return this.pawn.GetLord() == null && this.pawn.Faction == Faction.OfPlayer && this.pawn.HostFaction == null; + if (this.pawn.GetLord() != null) + { + return false; + } + return this.pawn.Faction == Faction.OfPlayer && this.pawn.HostFaction == null; } } @@ -107,14 +112,34 @@ public void ExposeData() Scribe_Values.Look(ref this.selfTend, "selfTend", false, false); } - [DebuggerHidden] public IEnumerable GetGizmos() { - Pawn_PlayerSettings.c__IteratorE6 c__IteratorE = new Pawn_PlayerSettings.c__IteratorE6(); - c__IteratorE.<>f__this = this; - Pawn_PlayerSettings.c__IteratorE6 expr_0E = c__IteratorE; - expr_0E.$PC = -2; - return expr_0E; + if (this.pawn.Drafted && PawnUtility.SpawnedMasteredPawns(this.pawn).Any((Func)((Pawn p) => p.training.IsCompleted(TrainableDefOf.Release)))) + { + yield return (Gizmo)new Command_Toggle + { + defaultLabel = "CommandReleaseAnimalsLabel".Translate(), + defaultDesc = "CommandReleaseAnimalsDesc".Translate(), + icon = TexCommand.ReleaseAnimals, + hotKey = KeyBindingDefOf.Misc7, + isActive = (Func)(() => ((_003CGetGizmos_003Ec__IteratorE6)/*Error near IL_00c8: stateMachine*/)._003C_003Ef__this.animalsReleased), + toggleAction = (Action)delegate + { + ((_003CGetGizmos_003Ec__IteratorE6)/*Error near IL_00df: stateMachine*/)._003C_003Ef__this.animalsReleased = !((_003CGetGizmos_003Ec__IteratorE6)/*Error near IL_00df: stateMachine*/)._003C_003Ef__this.animalsReleased; + if (((_003CGetGizmos_003Ec__IteratorE6)/*Error near IL_00df: stateMachine*/)._003C_003Ef__this.animalsReleased) + { + foreach (Pawn item in PawnUtility.SpawnedMasteredPawns(((_003CGetGizmos_003Ec__IteratorE6)/*Error near IL_00df: stateMachine*/)._003C_003Ef__this.pawn)) + { + if (item.caller != null) + { + item.caller.Notify_Released(); + } + item.jobs.EndCurrentJob(JobCondition.InterruptForced, true); + } + } + } + }; + } } public void Notify_FactionChanged() @@ -129,40 +154,39 @@ public void Notify_MadePrisoner() public void ResetMedicalCare() { - if (Scribe.mode == LoadSaveMode.LoadingVars) + if (Scribe.mode != LoadSaveMode.LoadingVars) { - return; - } - if (this.pawn.Faction == Faction.OfPlayer) - { - if (!this.pawn.RaceProps.Animal) + if (this.pawn.Faction == Faction.OfPlayer) { - if (!this.pawn.IsPrisoner) + if (!this.pawn.RaceProps.Animal) { - this.medCare = Find.World.settings.defaultCareForColonyHumanlike; + if (!this.pawn.IsPrisoner) + { + this.medCare = Find.World.settings.defaultCareForColonyHumanlike; + } + else + { + this.medCare = Find.World.settings.defaultCareForColonyPrisoner; + } } else { - this.medCare = Find.World.settings.defaultCareForColonyPrisoner; + this.medCare = Find.World.settings.defaultCareForColonyAnimal; } } + else if (this.pawn.Faction == null && this.pawn.RaceProps.Animal) + { + this.medCare = Find.World.settings.defaultCareForNeutralAnimal; + } + else if (this.pawn.Faction == null || !this.pawn.Faction.HostileTo(Faction.OfPlayer)) + { + this.medCare = Find.World.settings.defaultCareForNeutralFaction; + } else { - this.medCare = Find.World.settings.defaultCareForColonyAnimal; + this.medCare = Find.World.settings.defaultCareForHostileFaction; } } - else if (this.pawn.Faction == null && this.pawn.RaceProps.Animal) - { - this.medCare = Find.World.settings.defaultCareForNeutralAnimal; - } - else if (this.pawn.Faction == null || !this.pawn.Faction.HostileTo(Faction.OfPlayer)) - { - this.medCare = Find.World.settings.defaultCareForNeutralFaction; - } - else - { - this.medCare = Find.World.settings.defaultCareForHostileFaction; - } } public void Notify_AreaRemoved(Area area) diff --git a/Assembly-CSharp/RimWorld/Pawn_RecordsTracker.cs b/Assembly-CSharp/RimWorld/Pawn_RecordsTracker.cs index 2a6dd15f7..00c8b95d2 100644 --- a/Assembly-CSharp/RimWorld/Pawn_RecordsTracker.cs +++ b/Assembly-CSharp/RimWorld/Pawn_RecordsTracker.cs @@ -1,4 +1,3 @@ -using System; using System.Collections.Generic; using UnityEngine; using Verse; @@ -20,11 +19,7 @@ public Pawn_RecordsTracker(Pawn pawn) public void RecordsTick() { - if (this.pawn.Dead) - { - return; - } - if (this.pawn.IsHashIntervalTick(80)) + if (!this.pawn.Dead && this.pawn.IsHashIntervalTick(80)) { List allDefsListForReading = DefDatabase.AllDefsListForReading; for (int i = 0; i < allDefsListForReading.Count; i++) @@ -32,11 +27,11 @@ public void RecordsTick() if (allDefsListForReading[i].type == RecordType.Time && allDefsListForReading[i].Worker.ShouldMeasureTimeNow(this.pawn)) { DefMap defMap; - DefMap expr_63 = defMap = this.records; + DefMap obj = defMap = this.records; RecordDef def; - RecordDef expr_6C = def = allDefsListForReading[i]; + RecordDef def2 = def = allDefsListForReading[i]; float num = defMap[def]; - expr_63[expr_6C] = num + 80f; + obj[def2] = (float)(num + 80.0); } } } @@ -46,17 +41,12 @@ public void Increment(RecordDef def) { if (def.type != RecordType.Int) { - Log.Error(string.Concat(new object[] - { - "Tried to increment record \"", - def.defName, - "\" whose record type is \"", - def.type, - "\"." - })); - return; + Log.Error("Tried to increment record \"" + def.defName + "\" whose record type is \"" + def.type + "\"."); + } + else + { + this.records[def] = Mathf.Round((float)(this.records[def] + 1.0)); } - this.records[def] = Mathf.Round(this.records[def] + 1f); } public void AddTo(RecordDef def, float value) @@ -65,35 +55,29 @@ public void AddTo(RecordDef def, float value) { this.records[def] = Mathf.Round(this.records[def] + Mathf.Round(value)); } - else + else if (def.type == RecordType.Float) { - if (def.type != RecordType.Float) - { - Log.Error(string.Concat(new object[] - { - "Tried to add value to record \"", - def.defName, - "\" whose record type is \"", - def.type, - "\"." - })); - return; - } DefMap defMap; - DefMap expr_47 = defMap = this.records; - float num = defMap[def]; - expr_47[def] = num + value; + DefMap obj = defMap = this.records; + RecordDef def2; + RecordDef def3 = def2 = def; + float num = defMap[def2]; + obj[def3] = num + value; + } + else + { + Log.Error("Tried to add value to record \"" + def.defName + "\" whose record type is \"" + def.type + "\"."); } } public float GetValue(RecordDef def) { float num = this.records[def]; - if (def.type == RecordType.Int || def.type == RecordType.Time) + if (((def.type != RecordType.Int) ? def.type : RecordType.Time) != 0) { - return Mathf.Round(num); + return num; } - return num; + return Mathf.Round(num); } public int GetAsInt(RecordDef def) diff --git a/Assembly-CSharp/RimWorld/Pawn_RelationsTracker.cs b/Assembly-CSharp/RimWorld/Pawn_RelationsTracker.cs index c1608dc1b..54a59c285 100644 --- a/Assembly-CSharp/RimWorld/Pawn_RelationsTracker.cs +++ b/Assembly-CSharp/RimWorld/Pawn_RelationsTracker.cs @@ -43,11 +43,22 @@ public IEnumerable Children { get { - Pawn_RelationsTracker.<>c__IteratorE7 <>c__IteratorE = new Pawn_RelationsTracker.<>c__IteratorE7(); - <>c__IteratorE.<>f__this = this; - Pawn_RelationsTracker.<>c__IteratorE7 expr_0E = <>c__IteratorE; - expr_0E.$PC = -2; - return expr_0E; + HashSet.Enumerator enumerator = this.pawnsWithDirectRelationsWithMe.GetEnumerator(); + try + { + while (enumerator.MoveNext()) + { + Pawn p = enumerator.Current; + if (p.relations.directRelations.Find((Predicate)((DirectPawnRelation x) => x.otherPawn == ((_003C_003Ec__IteratorE7)/*Error near IL_006e: stateMachine*/)._003C_003Ef__this.pawn && x.def == PawnRelationDefOf.Parent)) != null) + { + yield return p; + } + } + } + finally + { + ((IDisposable)(object)enumerator).Dispose(); + } } } @@ -55,7 +66,7 @@ public int ChildrenCount { get { - return this.Children.Count(); + return this.Children.Count(); } } @@ -63,7 +74,7 @@ public bool RelatedToAnyoneOrAnyoneRelatedToMe { get { - return this.directRelations.Any() || this.pawnsWithDirectRelationsWithMe.Any(); + return this.directRelations.Any() || this.pawnsWithDirectRelationsWithMe.Any(); } } @@ -71,11 +82,60 @@ public IEnumerable FamilyByBlood { get { - Pawn_RelationsTracker.<>c__IteratorE8 <>c__IteratorE = new Pawn_RelationsTracker.<>c__IteratorE8(); - <>c__IteratorE.<>f__this = this; - Pawn_RelationsTracker.<>c__IteratorE8 expr_0E = <>c__IteratorE; - expr_0E.$PC = -2; - return expr_0E; + if (this.RelatedToAnyoneOrAnyoneRelatedToMe) + { + try + { + Stack familyStack = SimplePool>.Get(); + Stack familyChildrenStack = SimplePool>.Get(); + HashSet familyVisited = SimplePool>.Get(); + familyStack.Push(this.pawn); + familyVisited.Add(this.pawn); + while (familyStack.Any()) + { + Pawn p = familyStack.Pop(); + if (p != this.pawn) + { + yield return p; + } + Pawn father = p.GetFather(); + if (father != null && !familyVisited.Contains(father)) + { + familyStack.Push(father); + familyVisited.Add(father); + } + Pawn mother = p.GetMother(); + if (mother != null && !familyVisited.Contains(mother)) + { + familyStack.Push(mother); + familyVisited.Add(mother); + } + familyChildrenStack.Clear(); + familyChildrenStack.Push(p); + while (familyChildrenStack.Any()) + { + Pawn child = familyChildrenStack.Pop(); + if (child != p && child != this.pawn) + { + yield return child; + } + IEnumerable children = child.relations.Children; + foreach (Pawn item in children) + { + if (!familyVisited.Contains(item)) + { + familyChildrenStack.Push(item); + familyVisited.Add(item); + } + } + } + } + } + finally + { + ((_003C_003Ec__IteratorE8)/*Error near IL_02de: stateMachine*/)._003C_003E__Finally0(); + } + } } } @@ -83,11 +143,54 @@ public IEnumerable PotentiallyRelatedPawns { get { - Pawn_RelationsTracker.<>c__IteratorE9 <>c__IteratorE = new Pawn_RelationsTracker.<>c__IteratorE9(); - <>c__IteratorE.<>f__this = this; - Pawn_RelationsTracker.<>c__IteratorE9 expr_0E = <>c__IteratorE; - expr_0E.$PC = -2; - return expr_0E; + if (this.RelatedToAnyoneOrAnyoneRelatedToMe) + { + try + { + Stack stack = SimplePool>.Get(); + HashSet visited = SimplePool>.Get(); + stack.Push(this.pawn); + visited.Add(this.pawn); + while (stack.Any()) + { + Pawn p = stack.Pop(); + if (p != this.pawn) + { + yield return p; + } + for (int i = 0; i < p.relations.directRelations.Count; i++) + { + Pawn other = p.relations.directRelations[i].otherPawn; + if (!visited.Contains(other)) + { + stack.Push(other); + visited.Add(other); + } + } + HashSet.Enumerator enumerator = p.relations.pawnsWithDirectRelationsWithMe.GetEnumerator(); + try + { + while (enumerator.MoveNext()) + { + Pawn other2 = enumerator.Current; + if (!visited.Contains(other2)) + { + stack.Push(other2); + visited.Add(other2); + } + } + } + finally + { + ((IDisposable)(object)enumerator).Dispose(); + } + } + } + finally + { + ((_003C_003Ec__IteratorE9)/*Error near IL_0220: stateMachine*/)._003C_003E__Finally0(); + } + } } } @@ -96,7 +199,7 @@ public IEnumerable RelatedPawns get { return from x in this.PotentiallyRelatedPawns - where this.pawn.GetRelations(x).Any() + where this.pawn.GetRelations(x).Any() select x; } } @@ -115,17 +218,10 @@ public void ExposeData() { if (this.directRelations[i].otherPawn == null) { - Log.Warning(string.Concat(new object[] - { - "Pawn ", - this.pawn, - " has relation \"", - this.directRelations[i].def.defName, - "\" with null pawn after loading. This means that we forgot to serialize pawns somewhere (e.g. pawns from passing trade ships)." - })); + Log.Warning("Pawn " + this.pawn + " has relation \"" + this.directRelations[i].def.defName + "\" with null pawn after loading. This means that we forgot to serialize pawns somewhere (e.g. pawns from passing trade ships)."); } } - this.directRelations.RemoveAll((DirectPawnRelation x) => x.otherPawn == null); + this.directRelations.RemoveAll((Predicate)((DirectPawnRelation x) => x.otherPawn == null)); for (int j = 0; j < this.directRelations.Count; j++) { this.directRelations[j].otherPawn.relations.pawnsWithDirectRelationsWithMe.Add(this.pawn); @@ -137,12 +233,11 @@ public void ExposeData() public void SocialTrackerTick() { - if (this.pawn.Dead) + if (!this.pawn.Dead) { - return; + this.Tick_CheckStartMarriageCeremony(); + this.Tick_CheckDevelopBondRelation(); } - this.Tick_CheckStartMarriageCeremony(); - this.Tick_CheckDevelopBondRelation(); } public DirectPawnRelation GetDirectRelation(PawnRelationDef def, Pawn otherPawn) @@ -152,7 +247,7 @@ public DirectPawnRelation GetDirectRelation(PawnRelationDef def, Pawn otherPawn) Log.Warning(def + " is not a direct relation."); return null; } - return this.directRelations.Find((DirectPawnRelation x) => x.def == def && x.otherPawn == otherPawn); + return this.directRelations.Find((Predicate)((DirectPawnRelation x) => x.def == def && x.otherPawn == otherPawn)); } public Pawn GetFirstDirectRelationPawn(PawnRelationDef def, Predicate predicate = null) @@ -165,7 +260,7 @@ public Pawn GetFirstDirectRelationPawn(PawnRelationDef def, Predicate pred for (int i = 0; i < this.directRelations.Count; i++) { DirectPawnRelation directPawnRelation = this.directRelations[i]; - if (directPawnRelation.def == def && (predicate == null || predicate(directPawnRelation.otherPawn))) + if (directPawnRelation.def == def && ((object)predicate == null || predicate(directPawnRelation.otherPawn))) { return directPawnRelation.otherPawn; } @@ -195,51 +290,29 @@ public void AddDirectRelation(PawnRelationDef def, Pawn otherPawn) { if (def.implied) { - Log.Warning(string.Concat(new object[] - { - "Tried to directly add implied pawn relation ", - def, - ", pawn=", - this.pawn, - ", otherPawn=", - otherPawn - })); - return; + Log.Warning("Tried to directly add implied pawn relation " + def + ", pawn=" + this.pawn + ", otherPawn=" + otherPawn); } - if (otherPawn == this.pawn) + else if (otherPawn == this.pawn) { - Log.Warning(string.Concat(new object[] - { - "Tried to add pawn relation ", - def, - " with self, pawn=", - this.pawn - })); - return; + Log.Warning("Tried to add pawn relation " + def + " with self, pawn=" + this.pawn); } - if (this.DirectRelationExists(def, otherPawn)) + else if (this.DirectRelationExists(def, otherPawn)) { - Log.Warning(string.Concat(new object[] - { - "Tried to add the same relation twice: ", - def, - ", pawn=", - this.pawn, - ", otherPawn=", - otherPawn - })); - return; + Log.Warning("Tried to add the same relation twice: " + def + ", pawn=" + this.pawn + ", otherPawn=" + otherPawn); } - int startTicks = (Current.ProgramState != ProgramState.Playing) ? 0 : Find.TickManager.TicksGame; - this.directRelations.Add(new DirectPawnRelation(def, otherPawn, startTicks)); - otherPawn.relations.pawnsWithDirectRelationsWithMe.Add(this.pawn); - if (def.reflexive) + else { - otherPawn.relations.directRelations.Add(new DirectPawnRelation(def, this.pawn, startTicks)); - this.pawnsWithDirectRelationsWithMe.Add(otherPawn); + int startTicks = (Current.ProgramState == ProgramState.Playing) ? Find.TickManager.TicksGame : 0; + this.directRelations.Add(new DirectPawnRelation(def, otherPawn, startTicks)); + otherPawn.relations.pawnsWithDirectRelationsWithMe.Add(this.pawn); + if (def.reflexive) + { + otherPawn.relations.directRelations.Add(new DirectPawnRelation(def, this.pawn, startTicks)); + this.pawnsWithDirectRelationsWithMe.Add(otherPawn); + } + this.GainedOrLostDirectRelation(); + otherPawn.relations.GainedOrLostDirectRelation(); } - this.GainedOrLostDirectRelation(); - otherPawn.relations.GainedOrLostDirectRelation(); } public void RemoveDirectRelation(DirectPawnRelation relation) @@ -251,15 +324,7 @@ public void RemoveDirectRelation(PawnRelationDef def, Pawn otherPawn) { if (!this.TryRemoveDirectRelation(def, otherPawn)) { - Log.Warning(string.Concat(new object[] - { - "Could not remove relation ", - def, - " because it's not here. pawn=", - this.pawn, - ", otherPawn=", - otherPawn - })); + Log.Warning("Could not remove relation " + def + " because it's not here. pawn=" + this.pawn + ", otherPawn=" + otherPawn); } } @@ -267,15 +332,7 @@ public bool TryRemoveDirectRelation(PawnRelationDef def, Pawn otherPawn) { if (def.implied) { - Log.Warning(string.Concat(new object[] - { - "Tried to remove implied pawn relation ", - def, - ", pawn=", - this.pawn, - ", otherPawn=", - otherPawn - })); + Log.Warning("Tried to remove implied pawn relation " + def + ", pawn=" + this.pawn + ", otherPawn=" + otherPawn); return false; } for (int i = 0; i < this.directRelations.Count; i++) @@ -285,15 +342,15 @@ public bool TryRemoveDirectRelation(PawnRelationDef def, Pawn otherPawn) if (def.reflexive) { List list = otherPawn.relations.directRelations; - DirectPawnRelation item = list.Find((DirectPawnRelation x) => x.def == def && x.otherPawn == this.pawn); + DirectPawnRelation item = list.Find((Predicate)((DirectPawnRelation x) => x.def == def && x.otherPawn == this.pawn)); list.Remove(item); - if (list.Find((DirectPawnRelation x) => x.otherPawn == this.pawn) == null) + if (list.Find((Predicate)((DirectPawnRelation x) => x.otherPawn == this.pawn)) == null) { this.pawnsWithDirectRelationsWithMe.Remove(otherPawn); } } this.directRelations.RemoveAt(i); - if (this.directRelations.Find((DirectPawnRelation x) => x.otherPawn == otherPawn) == null) + if (this.directRelations.Find((Predicate)((DirectPawnRelation x) => x.otherPawn == otherPawn)) == null) { otherPawn.relations.pawnsWithDirectRelationsWithMe.Remove(this.pawn); } @@ -307,220 +364,210 @@ public bool TryRemoveDirectRelation(PawnRelationDef def, Pawn otherPawn) public int OpinionOf(Pawn other) { - if (!other.RaceProps.Humanlike || this.pawn == other) - { - return 0; - } - if (this.pawn.Dead) + if (other.RaceProps.Humanlike && this.pawn != other) { - return 0; - } - ProfilerThreadCheck.BeginSample("OpinionOf()"); - int num = 0; - foreach (PawnRelationDef current in this.pawn.GetRelations(other)) - { - num += current.opinionOffset; - } - if (this.pawn.RaceProps.Humanlike) - { - num += this.pawn.needs.mood.thoughts.TotalOpinionOffset(other); - } - if (num != 0) - { - float num2 = 1f; - List hediffs = this.pawn.health.hediffSet.hediffs; - for (int i = 0; i < hediffs.Count; i++) + if (this.pawn.Dead) + { + return 0; + } + ProfilerThreadCheck.BeginSample("OpinionOf()"); + int num = 0; + foreach (PawnRelationDef relation in this.pawn.GetRelations(other)) + { + num += relation.opinionOffset; + } + if (this.pawn.RaceProps.Humanlike) + { + num += this.pawn.needs.mood.thoughts.TotalOpinionOffset(other); + } + if (num != 0) { - if (hediffs[i].CurStage != null) + float num2 = 1f; + List hediffs = this.pawn.health.hediffSet.hediffs; + for (int i = 0; i < hediffs.Count; i++) { - num2 *= hediffs[i].CurStage.opinionOfOthersFactor; + if (hediffs[i].CurStage != null) + { + num2 *= hediffs[i].CurStage.opinionOfOthersFactor; + } } + num = Mathf.RoundToInt((float)num * num2); } - num = Mathf.RoundToInt((float)num * num2); - } - if (num > 0 && this.pawn.HostileTo(other)) - { - num = 0; + if (num > 0 && this.pawn.HostileTo(other)) + { + num = 0; + } + ProfilerThreadCheck.EndSample(); + return Mathf.Clamp(num, -100, 100); } - ProfilerThreadCheck.EndSample(); - return Mathf.Clamp(num, -100, 100); + return 0; } public string OpinionExplanation(Pawn other) { - if (!other.RaceProps.Humanlike || this.pawn == other) - { - return string.Empty; - } - StringBuilder stringBuilder = new StringBuilder(); - stringBuilder.AppendLine("OpinionOf".Translate(new object[] - { - other.LabelShort - }) + ": " + this.OpinionOf(other).ToStringWithSign()); - string pawnSituationLabel = SocialCardUtility.GetPawnSituationLabel(other, this.pawn); - if (!pawnSituationLabel.NullOrEmpty()) - { - stringBuilder.AppendLine(pawnSituationLabel); - } - stringBuilder.AppendLine("--------------"); - bool flag = false; - if (this.pawn.Dead) - { - stringBuilder.AppendLine("IAmDead".Translate()); - flag = true; - } - else + if (other.RaceProps.Humanlike && this.pawn != other) { - IEnumerable relations = this.pawn.GetRelations(other); - foreach (PawnRelationDef current in relations) + StringBuilder stringBuilder = new StringBuilder(); + stringBuilder.AppendLine("OpinionOf".Translate(other.LabelShort) + ": " + this.OpinionOf(other).ToStringWithSign()); + string pawnSituationLabel = SocialCardUtility.GetPawnSituationLabel(other, this.pawn); + if (!pawnSituationLabel.NullOrEmpty()) + { + stringBuilder.AppendLine(pawnSituationLabel); + } + stringBuilder.AppendLine("--------------"); + bool flag = false; + if (this.pawn.Dead) { - stringBuilder.AppendLine(current.GetGenderSpecificLabelCap(other) + ": " + current.opinionOffset.ToStringWithSign()); + stringBuilder.AppendLine("IAmDead".Translate()); flag = true; } - if (this.pawn.RaceProps.Humanlike) + else { - ThoughtHandler thoughts = this.pawn.needs.mood.thoughts; - thoughts.GetDistinctSocialThoughtGroups(other, Pawn_RelationsTracker.tmpSocialThoughts); - for (int i = 0; i < Pawn_RelationsTracker.tmpSocialThoughts.Count; i++) + IEnumerable relations = this.pawn.GetRelations(other); + foreach (PawnRelationDef item in relations) { - ISocialThought socialThought = Pawn_RelationsTracker.tmpSocialThoughts[i]; - int num = 1; - Thought thought = (Thought)socialThought; - if (thought.def.IsMemory) - { - num = thoughts.memories.NumMemoriesInGroup((Thought_MemorySocial)socialThought); - } - stringBuilder.Append(thought.LabelCapSocial); - if (num != 1) - { - stringBuilder.Append(" x" + num); - } - stringBuilder.AppendLine(": " + thoughts.OpinionOffsetOfGroup(socialThought, other).ToStringWithSign()); + stringBuilder.AppendLine(item.GetGenderSpecificLabelCap(other) + ": " + item.opinionOffset.ToStringWithSign()); flag = true; } - } - List hediffs = this.pawn.health.hediffSet.hediffs; - for (int j = 0; j < hediffs.Count; j++) - { - HediffStage curStage = hediffs[j].CurStage; - if (curStage != null && curStage.opinionOfOthersFactor != 1f) + if (this.pawn.RaceProps.Humanlike) { - stringBuilder.Append(hediffs[j].LabelBase.CapitalizeFirst()); - if (curStage.opinionOfOthersFactor != 0f) + ThoughtHandler thoughts = this.pawn.needs.mood.thoughts; + thoughts.GetDistinctSocialThoughtGroups(other, Pawn_RelationsTracker.tmpSocialThoughts); + for (int i = 0; i < Pawn_RelationsTracker.tmpSocialThoughts.Count; i++) { - stringBuilder.AppendLine(": x" + curStage.opinionOfOthersFactor.ToStringPercent()); + ISocialThought socialThought = Pawn_RelationsTracker.tmpSocialThoughts[i]; + int num = 1; + Thought thought = (Thought)socialThought; + if (thought.def.IsMemory) + { + num = thoughts.memories.NumMemoriesInGroup((Thought_MemorySocial)socialThought); + } + stringBuilder.Append(thought.LabelCapSocial); + if (num != 1) + { + stringBuilder.Append(" x" + num); + } + stringBuilder.AppendLine(": " + thoughts.OpinionOffsetOfGroup(socialThought, other).ToStringWithSign()); + flag = true; } - else + } + List hediffs = this.pawn.health.hediffSet.hediffs; + for (int j = 0; j < hediffs.Count; j++) + { + HediffStage curStage = hediffs[j].CurStage; + if (curStage != null && curStage.opinionOfOthersFactor != 1.0) { - stringBuilder.AppendLine(); + stringBuilder.Append(hediffs[j].LabelBase.CapitalizeFirst()); + if (curStage.opinionOfOthersFactor != 0.0) + { + stringBuilder.AppendLine(": x" + curStage.opinionOfOthersFactor.ToStringPercent()); + } + else + { + stringBuilder.AppendLine(); + } + flag = true; } + } + if (this.pawn.HostileTo(other)) + { + stringBuilder.AppendLine("Hostile".Translate()); flag = true; } } - if (this.pawn.HostileTo(other)) + if (!flag) { - stringBuilder.AppendLine("Hostile".Translate()); - flag = true; + stringBuilder.AppendLine("NoneBrackets".Translate()); } + return stringBuilder.ToString().TrimEndNewlines(); } - if (!flag) - { - stringBuilder.AppendLine("NoneBrackets".Translate()); - } - return stringBuilder.ToString().TrimEndNewlines(); + return string.Empty; } public float SecondaryRomanceChanceFactor(Pawn otherPawn) { - if (this.pawn.def != otherPawn.def || this.pawn == otherPawn) + if (this.pawn.def == otherPawn.def && this.pawn != otherPawn) { - return 0f; - } - if (Rand.ValueSeeded(this.pawn.thingIDNumber ^ 3273711) >= 0.015f) - { - if (this.pawn.RaceProps.Humanlike && this.pawn.story.traits.HasTrait(TraitDefOf.Gay)) + if (!(Rand.ValueSeeded(this.pawn.thingIDNumber ^ 3273711) < 0.014999999664723873)) { - if (otherPawn.gender != this.pawn.gender) + if (this.pawn.RaceProps.Humanlike && this.pawn.story.traits.HasTrait(TraitDefOf.Gay)) + { + if (otherPawn.gender != this.pawn.gender) + { + return 0f; + } + } + else if (otherPawn.gender == this.pawn.gender) { return 0f; } } - else if (otherPawn.gender == this.pawn.gender) + float ageBiologicalYearsFloat = this.pawn.ageTracker.AgeBiologicalYearsFloat; + float ageBiologicalYearsFloat2 = otherPawn.ageTracker.AgeBiologicalYearsFloat; + float num = 1f; + if (this.pawn.gender == Gender.Male) { - return 0f; + if (ageBiologicalYearsFloat2 < 16.0) + { + return 0f; + } + float min = Mathf.Max(16f, (float)(ageBiologicalYearsFloat - 30.0)); + float lower = Mathf.Max(20f, (float)(ageBiologicalYearsFloat - 10.0)); + num = GenMath.FlatHill(0.15f, min, lower, ageBiologicalYearsFloat, (float)(ageBiologicalYearsFloat + 10.0), 0.15f, ageBiologicalYearsFloat2); } - } - float ageBiologicalYearsFloat = this.pawn.ageTracker.AgeBiologicalYearsFloat; - float ageBiologicalYearsFloat2 = otherPawn.ageTracker.AgeBiologicalYearsFloat; - float num = 1f; - if (this.pawn.gender == Gender.Male) - { - if (ageBiologicalYearsFloat2 < 16f) + else if (this.pawn.gender == Gender.Female) { - return 0f; + if (ageBiologicalYearsFloat2 < 16.0) + { + return 0f; + } + if (ageBiologicalYearsFloat2 < ageBiologicalYearsFloat - 10.0) + { + return 0.15f; + } + num = (float)((!(ageBiologicalYearsFloat2 < ageBiologicalYearsFloat - 3.0)) ? GenMath.FlatHill(0.3f, (float)(ageBiologicalYearsFloat - 3.0), ageBiologicalYearsFloat, (float)(ageBiologicalYearsFloat + 10.0), (float)(ageBiologicalYearsFloat + 30.0), 0.15f, ageBiologicalYearsFloat2) : (Mathf.InverseLerp((float)(ageBiologicalYearsFloat - 10.0), (float)(ageBiologicalYearsFloat - 3.0), ageBiologicalYearsFloat2) * 0.30000001192092896)); } - float min = Mathf.Max(16f, ageBiologicalYearsFloat - 30f); - float lower = Mathf.Max(20f, ageBiologicalYearsFloat - 10f); - num = GenMath.FlatHill(0.15f, min, lower, ageBiologicalYearsFloat, ageBiologicalYearsFloat + 10f, 0.15f, ageBiologicalYearsFloat2); - } - else if (this.pawn.gender == Gender.Female) - { - if (ageBiologicalYearsFloat2 < 16f) + float num2 = 1f; + num2 *= Mathf.Lerp(0.2f, 1f, otherPawn.health.capacities.GetLevel(PawnCapacityDefOf.Talking)); + num2 *= Mathf.Lerp(0.2f, 1f, otherPawn.health.capacities.GetLevel(PawnCapacityDefOf.Manipulation)); + num2 *= Mathf.Lerp(0.2f, 1f, otherPawn.health.capacities.GetLevel(PawnCapacityDefOf.Moving)); + float num3 = 1f; + foreach (PawnRelationDef relation in this.pawn.GetRelations(otherPawn)) { - return 0f; + num3 *= relation.attractionFactor; } - if (ageBiologicalYearsFloat2 < ageBiologicalYearsFloat - 10f) + int num4 = 0; + if (otherPawn.RaceProps.Humanlike) { - return 0.15f; + num4 = otherPawn.story.traits.DegreeOfTrait(TraitDefOf.Beauty); } - if (ageBiologicalYearsFloat2 < ageBiologicalYearsFloat - 3f) + float num5 = 1f; + if (num4 < 0) { - num = Mathf.InverseLerp(ageBiologicalYearsFloat - 10f, ageBiologicalYearsFloat - 3f, ageBiologicalYearsFloat2) * 0.3f; + num5 = 0.3f; } - else + else if (num4 > 0) { - num = GenMath.FlatHill(0.3f, ageBiologicalYearsFloat - 3f, ageBiologicalYearsFloat, ageBiologicalYearsFloat + 10f, ageBiologicalYearsFloat + 30f, 0.15f, ageBiologicalYearsFloat2); + num5 = 2.3f; } + float num6 = Mathf.InverseLerp(15f, 18f, ageBiologicalYearsFloat); + float num7 = Mathf.InverseLerp(15f, 18f, ageBiologicalYearsFloat2); + return num * num2 * num3 * num6 * num7 * num5; } - float num2 = 1f; - num2 *= Mathf.Lerp(0.2f, 1f, otherPawn.health.capacities.GetLevel(PawnCapacityDefOf.Talking)); - num2 *= Mathf.Lerp(0.2f, 1f, otherPawn.health.capacities.GetLevel(PawnCapacityDefOf.Manipulation)); - num2 *= Mathf.Lerp(0.2f, 1f, otherPawn.health.capacities.GetLevel(PawnCapacityDefOf.Moving)); - float num3 = 1f; - foreach (PawnRelationDef current in this.pawn.GetRelations(otherPawn)) - { - num3 *= current.attractionFactor; - } - int num4 = 0; - if (otherPawn.RaceProps.Humanlike) - { - num4 = otherPawn.story.traits.DegreeOfTrait(TraitDefOf.Beauty); - } - float num5 = 1f; - if (num4 < 0) - { - num5 = 0.3f; - } - else if (num4 > 0) - { - num5 = 2.3f; - } - float num6 = Mathf.InverseLerp(15f, 18f, ageBiologicalYearsFloat); - float num7 = Mathf.InverseLerp(15f, 18f, ageBiologicalYearsFloat2); - return num * num2 * num3 * num6 * num7 * num5; + return 0f; } public float CompatibilityWith(Pawn otherPawn) { - if (this.pawn.def != otherPawn.def || this.pawn == otherPawn) + if (this.pawn.def == otherPawn.def && this.pawn != otherPawn) { - return 0f; + float x = Mathf.Abs(this.pawn.ageTracker.AgeBiologicalYearsFloat - otherPawn.ageTracker.AgeBiologicalYearsFloat); + float value = GenMath.LerpDouble(0f, 20f, 0.45f, -0.45f, x); + value = Mathf.Clamp(value, -0.45f, 0.45f); + float num = this.ConstantPerPawnsPairCompatibilityOffset(otherPawn.thingIDNumber); + return value + num; } - float x = Mathf.Abs(this.pawn.ageTracker.AgeBiologicalYearsFloat - otherPawn.ageTracker.AgeBiologicalYearsFloat); - float num = GenMath.LerpDouble(0f, 20f, 0.45f, -0.45f, x); - num = Mathf.Clamp(num, -0.45f, 0.45f); - float num2 = this.ConstantPerPawnsPairCompatibilityOffset(otherPawn.thingIDNumber); - return num + num2; + return 0f; } public float ConstantPerPawnsPairCompatibilityOffset(int otherPawnID) @@ -534,15 +581,15 @@ public float ConstantPerPawnsPairCompatibilityOffset(int otherPawnID) public void ClearAllRelations() { - List list = this.directRelations.ToList(); + List list = this.directRelations.ToList(); for (int i = 0; i < list.Count; i++) { this.RemoveDirectRelation(list[i]); } - List list2 = this.pawnsWithDirectRelationsWithMe.ToList(); + List list2 = this.pawnsWithDirectRelationsWithMe.ToList(); for (int j = 0; j < list2.Count; j++) { - List list3 = list2[j].relations.directRelations.ToList(); + List list3 = list2[j].relations.directRelations.ToList(); for (int k = 0; k < list3.Count; k++) { if (list3[k].otherPawn == this.pawn) @@ -555,11 +602,11 @@ public void ClearAllRelations() internal void Notify_PawnKilled(DamageInfo? dinfo, Map mapBeforeDeath) { - foreach (Pawn current in this.PotentiallyRelatedPawns) + foreach (Pawn potentiallyRelatedPawn in this.PotentiallyRelatedPawns) { - if (!current.Dead && current.needs.mood != null) + if (!potentiallyRelatedPawn.Dead && potentiallyRelatedPawn.needs.mood != null) { - current.needs.mood.thoughts.situational.Notify_SituationalThoughtsDirty(); + potentiallyRelatedPawn.needs.mood.thoughts.situational.Notify_SituationalThoughtsDirty(); } } this.RemoveMySpouseMarriageRelatedThoughts(); @@ -578,14 +625,14 @@ internal void Notify_PawnKilled(DamageInfo? dinfo, Map mapBeforeDeath) public void Notify_PawnSold(Pawn playerNegotiator) { - foreach (Pawn current in this.PotentiallyRelatedPawns) + foreach (Pawn potentiallyRelatedPawn in this.PotentiallyRelatedPawns) { - if (!current.Dead && current.needs.mood != null) + if (!potentiallyRelatedPawn.Dead && potentiallyRelatedPawn.needs.mood != null) { - PawnRelationDef mostImportantRelation = current.GetMostImportantRelation(this.pawn); + PawnRelationDef mostImportantRelation = potentiallyRelatedPawn.GetMostImportantRelation(this.pawn); if (mostImportantRelation != null && mostImportantRelation.soldThought != null) { - current.needs.mood.thoughts.memories.TryGainMemory(mostImportantRelation.soldThought, playerNegotiator); + potentiallyRelatedPawn.needs.mood.thoughts.memories.TryGainMemory(mostImportantRelation.soldThought, playerNegotiator); } } } @@ -629,7 +676,18 @@ private void RemoveMySpouseMarriageRelatedThoughts() private void SendBondedAnimalDiedLetter(Map mapBeforeDeath) { - Predicate isAffected = (Pawn x) => !x.Dead && (!x.RaceProps.Humanlike || !x.story.traits.HasTrait(TraitDefOf.Psychopath)); + Predicate isAffected = (Predicate)delegate(Pawn x) + { + if (x.Dead) + { + return false; + } + if (x.RaceProps.Humanlike && x.story.traits.HasTrait(TraitDefOf.Psychopath)) + { + return false; + } + return true; + }; int num = 0; for (int i = 0; i < this.directRelations.Count; i++) { @@ -638,33 +696,18 @@ private void SendBondedAnimalDiedLetter(Map mapBeforeDeath) num++; } } - if (num == 0) + string str; + switch (num) { + case 0: return; - } - string str; - if (num == 1) + case 1: { - Pawn firstDirectRelationPawn = this.GetFirstDirectRelationPawn(PawnRelationDefOf.Bond, (Pawn x) => isAffected(x)); - if (this.pawn.Name != null) - { - str = "LetterNamedBondedAnimalDied".Translate(new object[] - { - this.pawn.KindLabel, - this.pawn.Name.ToStringShort, - firstDirectRelationPawn.LabelShort - }); - } - else - { - str = "LetterBondedAnimalDied".Translate(new object[] - { - this.pawn.KindLabel, - firstDirectRelationPawn.LabelShort - }); - } + Pawn firstDirectRelationPawn = this.GetFirstDirectRelationPawn(PawnRelationDefOf.Bond, (Predicate)((Pawn x) => isAffected(x))); + str = ((this.pawn.Name == null) ? "LetterBondedAnimalDied".Translate(this.pawn.KindLabel, firstDirectRelationPawn.LabelShort) : "LetterNamedBondedAnimalDied".Translate(this.pawn.KindLabel, this.pawn.Name.ToStringShort, firstDirectRelationPawn.LabelShort)); + break; } - else + default: { StringBuilder stringBuilder = new StringBuilder(); for (int j = 0; j < this.directRelations.Count; j++) @@ -674,26 +717,12 @@ private void SendBondedAnimalDiedLetter(Map mapBeforeDeath) stringBuilder.AppendLine(" - " + this.directRelations[j].otherPawn.LabelShort); } } - if (this.pawn.Name != null) - { - str = "LetterNamedBondedAnimalDiedMulti".Translate(new object[] - { - this.pawn.KindLabel, - this.pawn.Name.ToStringShort, - stringBuilder.ToString().TrimEndNewlines() - }); - } - else - { - str = "LetterBondedAnimalDiedMulti".Translate(new object[] - { - this.pawn.KindLabel, - stringBuilder.ToString().TrimEndNewlines() - }); - } + str = ((this.pawn.Name == null) ? "LetterBondedAnimalDiedMulti".Translate(this.pawn.KindLabel, stringBuilder.ToString().TrimEndNewlines()) : "LetterNamedBondedAnimalDiedMulti".Translate(this.pawn.KindLabel, this.pawn.Name.ToStringShort, stringBuilder.ToString().TrimEndNewlines())); + break; + } } TargetInfo target = (mapBeforeDeath == null) ? TargetInfo.Invalid : new TargetInfo(this.pawn.Position, mapBeforeDeath, false); - Find.LetterStack.ReceiveLetter("LetterLabelBondedAnimalDied".Translate(), str.CapitalizeFirst(), LetterDefOf.BadNonUrgent, target, null); + Find.LetterStack.ReceiveLetter("LetterLabelBondedAnimalDied".Translate(), str.CapitalizeFirst(), LetterDefOf.BadNonUrgent, target, (string)null); } private void AffectBondedAnimalsOnMyDeath() @@ -707,71 +736,35 @@ private void AffectBondedAnimalsOnMyDeath() pawn = this.directRelations[i].otherPawn; num++; float value = Rand.Value; - MentalStateDef stateDef; - if (value < 0.25f) - { - stateDef = MentalStateDefOf.WanderSad; - } - if (value < 0.5f) + MentalStateDef wanderSad; + if (value < 0.25) { - stateDef = MentalStateDefOf.WanderPsychotic; + wanderSad = MentalStateDefOf.WanderSad; } - else if (value < 0.75f) - { - stateDef = MentalStateDefOf.Berserk; - } - else - { - stateDef = MentalStateDefOf.Manhunter; - } - this.directRelations[i].otherPawn.mindState.mentalStateHandler.TryStartMentalState(stateDef, null, true, false, null); + wanderSad = ((!(value < 0.5)) ? ((!(value < 0.75)) ? MentalStateDefOf.Manhunter : MentalStateDefOf.Berserk) : MentalStateDefOf.WanderPsychotic); + this.directRelations[i].otherPawn.mindState.mentalStateHandler.TryStartMentalState(wanderSad, (string)null, true, false, null); } } if (num == 1) { - string str; - if (pawn.Name != null && !pawn.Name.Numerical) - { - str = "MessageNamedBondedAnimalMentalBreak".Translate(new object[] - { - pawn.KindLabel, - pawn.Name.ToStringShort, - this.pawn.LabelShort - }); - } - else - { - str = "MessageBondedAnimalMentalBreak".Translate(new object[] - { - pawn.KindLabel, - this.pawn.LabelShort - }); - } - Messages.Message(str.CapitalizeFirst(), pawn, MessageSound.SeriousAlert); + string str = (pawn.Name == null || pawn.Name.Numerical) ? "MessageBondedAnimalMentalBreak".Translate(pawn.KindLabel, this.pawn.LabelShort) : "MessageNamedBondedAnimalMentalBreak".Translate(pawn.KindLabel, pawn.Name.ToStringShort, this.pawn.LabelShort); + Messages.Message(str.CapitalizeFirst(), (Thing)pawn, MessageSound.SeriousAlert); } else if (num > 1) { - Messages.Message("MessageBondedAnimalsMentalBreak".Translate(new object[] - { - num, - this.pawn.LabelShort - }).CapitalizeFirst(), pawn, MessageSound.SeriousAlert); + Messages.Message("MessageBondedAnimalsMentalBreak".Translate(num, this.pawn.LabelShort).CapitalizeFirst(), (Thing)pawn, MessageSound.SeriousAlert); } } private void Tick_CheckStartMarriageCeremony() { - if (!this.pawn.Spawned || this.pawn.RaceProps.Animal) - { - return; - } - if (this.pawn.IsHashIntervalTick(1017)) + if (this.pawn.Spawned && !this.pawn.RaceProps.Animal && this.pawn.IsHashIntervalTick(1017)) { int ticksGame = Find.TickManager.TicksGame; for (int i = 0; i < this.directRelations.Count; i++) { - float num = (float)(ticksGame - this.directRelations[i].startTicks) / 60000f; - if (this.directRelations[i].def == PawnRelationDefOf.Fiance && this.pawn.thingIDNumber < this.directRelations[i].otherPawn.thingIDNumber && num > 10f && Rand.MTBEventOccurs(2f, 60000f, 1017f) && this.pawn.Map == this.directRelations[i].otherPawn.Map && this.pawn.Map.IsPlayerHome && MarriageCeremonyUtility.AcceptableGameConditionsToStartCeremony(this.pawn.Map) && MarriageCeremonyUtility.FianceReadyToStartCeremony(this.pawn) && MarriageCeremonyUtility.FianceReadyToStartCeremony(this.directRelations[i].otherPawn)) + float num = (float)((float)(ticksGame - this.directRelations[i].startTicks) / 60000.0); + if (this.directRelations[i].def == PawnRelationDefOf.Fiance && this.pawn.thingIDNumber < this.directRelations[i].otherPawn.thingIDNumber && num > 10.0 && Rand.MTBEventOccurs(2f, 60000f, 1017f) && this.pawn.Map == this.directRelations[i].otherPawn.Map && this.pawn.Map.IsPlayerHome && MarriageCeremonyUtility.AcceptableGameConditionsToStartCeremony(this.pawn.Map) && MarriageCeremonyUtility.FianceReadyToStartCeremony(this.pawn) && MarriageCeremonyUtility.FianceReadyToStartCeremony(this.directRelations[i].otherPawn)) { this.pawn.Map.lordsStarter.TryStartMarriageCeremony(this.pawn, this.directRelations[i].otherPawn); } @@ -781,14 +774,13 @@ private void Tick_CheckStartMarriageCeremony() private void Tick_CheckDevelopBondRelation() { - if (!this.pawn.Spawned || !this.pawn.RaceProps.Animal || this.pawn.Faction != Faction.OfPlayer || this.pawn.playerSettings.master == null) + if (this.pawn.Spawned && this.pawn.RaceProps.Animal && this.pawn.Faction == Faction.OfPlayer && this.pawn.playerSettings.master != null) { - return; - } - Pawn master = this.pawn.playerSettings.master; - if (this.pawn.IsHashIntervalTick(2500) && this.pawn.Position.InHorDistOf(master.Position, 12f) && GenSight.LineOfSight(this.pawn.Position, master.Position, this.pawn.Map, false, null, 0, 0)) - { - RelationsUtility.TryDevelopBondRelation(master, this.pawn, 0.001f); + Pawn master = this.pawn.playerSettings.master; + if (this.pawn.IsHashIntervalTick(2500) && this.pawn.Position.InHorDistOf(master.Position, 12f) && GenSight.LineOfSight(this.pawn.Position, master.Position, this.pawn.Map, false, null, 0, 0)) + { + RelationsUtility.TryDevelopBondRelation(master, this.pawn, 0.001f); + } } } diff --git a/Assembly-CSharp/RimWorld/Pawn_SkillTracker.cs b/Assembly-CSharp/RimWorld/Pawn_SkillTracker.cs index 1cff6866e..85c5a2de1 100644 --- a/Assembly-CSharp/RimWorld/Pawn_SkillTracker.cs +++ b/Assembly-CSharp/RimWorld/Pawn_SkillTracker.cs @@ -1,4 +1,3 @@ -using System; using System.Collections.Generic; using Verse; @@ -15,15 +14,15 @@ public class Pawn_SkillTracker : IExposable public Pawn_SkillTracker(Pawn newPawn) { this.pawn = newPawn; - foreach (SkillDef current in DefDatabase.AllDefs) + foreach (SkillDef allDef in DefDatabase.AllDefs) { - this.skills.Add(new SkillRecord(this.pawn, current)); + this.skills.Add(new SkillRecord(this.pawn, allDef)); } } public void ExposeData() { - Scribe_Collections.Look(ref this.skills, "skills", LookMode.Deep, new object[] + Scribe_Collections.Look(ref this.skills, "skills", LookMode.Deep, new object[1] { this.pawn }); @@ -39,13 +38,7 @@ public SkillRecord GetSkill(SkillDef skillDef) return this.skills[i]; } } - Log.Error(string.Concat(new object[] - { - "Did not find skill of def ", - skillDef, - ", returning ", - this.skills[0] - })); + Log.Error("Did not find skill of def " + skillDef + ", returning " + this.skills[0]); return this.skills[0]; } @@ -97,7 +90,7 @@ public Passion MaxPassionOfRelevantSkillsFor(WorkTypeDef workDef) for (int i = 0; i < workDef.relevantSkills.Count; i++) { Passion passion2 = this.GetSkill(workDef.relevantSkills[i]).passion; - if (passion2 > passion) + if ((int)passion2 > (int)passion) { passion = passion2; } diff --git a/Assembly-CSharp/RimWorld/Pawn_StoryTracker.cs b/Assembly-CSharp/RimWorld/Pawn_StoryTracker.cs index 4ab98b6ff..b304c09b1 100644 --- a/Assembly-CSharp/RimWorld/Pawn_StoryTracker.cs +++ b/Assembly-CSharp/RimWorld/Pawn_StoryTracker.cs @@ -1,4 +1,3 @@ -using System; using System.Collections.Generic; using UnityEngine; using Verse; @@ -65,11 +64,14 @@ public IEnumerable AllBackstories { get { - Pawn_StoryTracker.<>c__IteratorDE <>c__IteratorDE = new Pawn_StoryTracker.<>c__IteratorDE(); - <>c__IteratorDE.<>f__this = this; - Pawn_StoryTracker.<>c__IteratorDE expr_0E = <>c__IteratorDE; - expr_0E.$PC = -2; - return expr_0E; + if (this.childhood != null) + { + yield return this.childhood; + } + if (this.adulthood != null) + { + yield return this.adulthood; + } } } @@ -92,23 +94,23 @@ public List DisabledWorkTypes if (this.cachedDisabledWorkTypes == null) { this.cachedDisabledWorkTypes = new List(); - foreach (Backstory current in this.AllBackstories) + foreach (Backstory allBackstory in this.AllBackstories) { - foreach (WorkTypeDef current2 in current.DisabledWorkTypes) + foreach (WorkTypeDef disabledWorkType in allBackstory.DisabledWorkTypes) { - if (!this.cachedDisabledWorkTypes.Contains(current2)) + if (!this.cachedDisabledWorkTypes.Contains(disabledWorkType)) { - this.cachedDisabledWorkTypes.Add(current2); + this.cachedDisabledWorkTypes.Add(disabledWorkType); } } } for (int i = 0; i < this.traits.allTraits.Count; i++) { - foreach (WorkTypeDef current3 in this.traits.allTraits[i].GetDisabledWorkTypes()) + foreach (WorkTypeDef disabledWorkType2 in this.traits.allTraits[i].GetDisabledWorkTypes()) { - if (!this.cachedDisabledWorkTypes.Contains(current3)) + if (!this.cachedDisabledWorkTypes.Contains(disabledWorkType2)) { - this.cachedDisabledWorkTypes.Add(current3); + this.cachedDisabledWorkTypes.Add(disabledWorkType2); } } } @@ -147,14 +149,14 @@ public Pawn_StoryTracker(Pawn pawn) public void ExposeData() { string text = (this.childhood == null) ? null : this.childhood.identifier; - Scribe_Values.Look(ref text, "childhood", null, false); + Scribe_Values.Look(ref text, "childhood", (string)null, false); if (Scribe.mode == LoadSaveMode.LoadingVars && !text.NullOrEmpty() && !BackstoryDatabase.TryGetWithIdentifier(text, out this.childhood)) { Log.Error("Couldn't load child backstory with identifier " + text + ". Giving random."); this.childhood = BackstoryDatabase.RandomBackstory(BackstorySlot.Childhood); } string text2 = (this.adulthood == null) ? null : this.adulthood.identifier; - Scribe_Values.Look(ref text2, "adulthood", null, false); + Scribe_Values.Look(ref text2, "adulthood", (string)null, false); if (Scribe.mode == LoadSaveMode.LoadingVars && !text2.NullOrEmpty() && !BackstoryDatabase.TryGetWithIdentifier(text2, out this.adulthood)) { Log.Error("Couldn't load adult backstory with identifier " + text2 + ". Giving random."); @@ -162,17 +164,17 @@ public void ExposeData() } Scribe_Values.Look(ref this.bodyType, "bodyType", BodyType.Undefined, false); Scribe_Values.Look(ref this.crownType, "crownType", CrownType.Undefined, false); - Scribe_Values.Look(ref this.headGraphicPath, "headGraphicPath", null, false); + Scribe_Values.Look(ref this.headGraphicPath, "headGraphicPath", (string)null, false); Scribe_Defs.Look(ref this.hairDef, "hairDef"); Scribe_Values.Look(ref this.hairColor, "hairColor", default(Color), false); Scribe_Values.Look(ref this.melanin, "melanin", 0f, false); - Scribe_Deep.Look(ref this.traits, "traits", new object[] + Scribe_Deep.Look(ref this.traits, "traits", new object[1] { this.pawn }); if (Scribe.mode == LoadSaveMode.PostLoadInit && this.hairDef == null) { - this.hairDef = DefDatabase.AllDefs.RandomElement(); + this.hairDef = DefDatabase.AllDefs.RandomElement(); } } diff --git a/Assembly-CSharp/RimWorld/Pawn_TimetableTracker.cs b/Assembly-CSharp/RimWorld/Pawn_TimetableTracker.cs index fc8a46092..699489230 100644 --- a/Assembly-CSharp/RimWorld/Pawn_TimetableTracker.cs +++ b/Assembly-CSharp/RimWorld/Pawn_TimetableTracker.cs @@ -1,4 +1,3 @@ -using System; using System.Collections.Generic; using Verse; @@ -24,15 +23,7 @@ public Pawn_TimetableTracker(Pawn pawn) this.times = new List(24); for (int i = 0; i < 24; i++) { - TimeAssignmentDef item; - if (i <= 5 || i > 21) - { - item = TimeAssignmentDefOf.Sleep; - } - else - { - item = TimeAssignmentDefOf.Anything; - } + TimeAssignmentDef item = (i > 5 && i <= 21) ? TimeAssignmentDefOf.Anything : TimeAssignmentDefOf.Sleep; this.times.Add(item); } } diff --git a/Assembly-CSharp/RimWorld/Pawn_TraderTracker.cs b/Assembly-CSharp/RimWorld/Pawn_TraderTracker.cs index 5752cf752..41a4020f9 100644 --- a/Assembly-CSharp/RimWorld/Pawn_TraderTracker.cs +++ b/Assembly-CSharp/RimWorld/Pawn_TraderTracker.cs @@ -1,6 +1,5 @@ using System; using System.Collections.Generic; -using System.Diagnostics; using System.Linq; using Verse; using Verse.AI; @@ -20,11 +19,44 @@ public IEnumerable Goods { get { - Pawn_TraderTracker.<>c__IteratorE4 <>c__IteratorE = new Pawn_TraderTracker.<>c__IteratorE4(); - <>c__IteratorE.<>f__this = this; - Pawn_TraderTracker.<>c__IteratorE4 expr_0E = <>c__IteratorE; - expr_0E.$PC = -2; - return expr_0E; + Lord lord = this.pawn.GetLord(); + if (lord == null || !(lord.LordJob is LordJob_TradeWithColony)) + { + for (int k = 0; k < this.pawn.inventory.innerContainer.Count; k++) + { + Thing t = this.pawn.inventory.innerContainer[k]; + if (!this.pawn.inventory.NotForSale(t)) + { + yield return t; + } + } + } + if (lord != null) + { + for (int j = 0; j < lord.ownedPawns.Count; j++) + { + Pawn p = lord.ownedPawns[j]; + switch (p.GetTraderCaravanRole()) + { + case TraderCaravanRole.Carrier: + { + for (int i = 0; i < p.inventory.innerContainer.Count; i++) + { + yield return p.inventory.innerContainer[i]; + } + break; + } + case TraderCaravanRole.Chattel: + { + if (!this.soldPrisoners.Contains(p)) + { + yield return (Thing)p; + } + break; + } + } + } + } } } @@ -48,7 +80,7 @@ public bool CanTradeNow { get { - return !this.pawn.Dead && this.pawn.Spawned && this.pawn.mindState.wantsToTradeWithColony && this.pawn.CanCasuallyInteractNow(false) && !this.pawn.Downed && !this.pawn.IsPrisoner && this.pawn.Faction != Faction.OfPlayer && (this.pawn.Faction == null || !this.pawn.Faction.HostileTo(Faction.OfPlayer)) && this.Goods.Any((Thing x) => this.traderKind.WillTrade(x.def)); + return !this.pawn.Dead && this.pawn.Spawned && this.pawn.mindState.wantsToTradeWithColony && this.pawn.CanCasuallyInteractNow(false) && !this.pawn.Downed && !this.pawn.IsPrisoner && this.pawn.Faction != Faction.OfPlayer && (this.pawn.Faction == null || !this.pawn.Faction.HostileTo(Faction.OfPlayer)) && this.Goods.Any((Func)((Thing x) => this.traderKind.WillTrade(x.def))); } } @@ -63,18 +95,28 @@ public void ExposeData() Scribe_Collections.Look(ref this.soldPrisoners, "soldPrisoners", LookMode.Reference, new object[0]); if (Scribe.mode == LoadSaveMode.PostLoadInit) { - this.soldPrisoners.RemoveAll((Pawn x) => x == null); + this.soldPrisoners.RemoveAll((Predicate)((Pawn x) => x == null)); } } - [DebuggerHidden] public IEnumerable ColonyThingsWillingToBuy(Pawn playerNegotiator) { - Pawn_TraderTracker.c__IteratorE5 c__IteratorE = new Pawn_TraderTracker.c__IteratorE5(); - c__IteratorE.<>f__this = this; - Pawn_TraderTracker.c__IteratorE5 expr_0E = c__IteratorE; - expr_0E.$PC = -2; - return expr_0E; + IEnumerable items = from x in this.pawn.Map.listerThings.AllThings + where TradeUtility.EverTradeable(x.def) && x.def.category == ThingCategory.Item && !x.Position.Fogged(x.Map) && (((Area)((_003CColonyThingsWillingToBuy_003Ec__IteratorE5)/*Error near IL_0042: stateMachine*/)._003C_003Ef__this.pawn.Map.areaManager.Home)[x.Position] || x.IsInAnyStorage()) && TradeUtility.TradeableNow(x) && ((_003CColonyThingsWillingToBuy_003Ec__IteratorE5)/*Error near IL_0042: stateMachine*/)._003C_003Ef__this.ReachableForTrade(x) + select x; + foreach (Thing item in items) + { + yield return item; + } + if (this.pawn.GetLord() != null) + { + foreach (Pawn item2 in from x in TradeUtility.AllSellableColonyPawns(this.pawn.Map) + where !x.Downed && ((_003CColonyThingsWillingToBuy_003Ec__IteratorE5)/*Error near IL_0113: stateMachine*/)._003C_003Ef__this.ReachableForTrade(x) + select x) + { + yield return (Thing)item2; + } + } } public void GiveSoldThingToTrader(Thing toGive, int countToGive, Pawn playerNegotiator) @@ -82,29 +124,31 @@ public void GiveSoldThingToTrader(Thing toGive, int countToGive, Pawn playerNego if (this.Goods.Contains(toGive)) { Log.Error("Tried to add " + toGive + " to stock (pawn's trader tracker), but it's already here."); - return; - } - Pawn pawn = toGive as Pawn; - if (pawn != null) - { - pawn.PreTraded(TradeAction.PlayerSells, playerNegotiator, this.pawn); - this.AddPawnToStock(pawn); } else { - Thing thing = toGive.SplitOff(countToGive); - thing.PreTraded(TradeAction.PlayerSells, playerNegotiator, this.pawn); - Thing thing2 = TradeUtility.ThingFromStockToMergeWith(this.pawn, thing); - if (thing2 != null) + Pawn pawn = toGive as Pawn; + if (pawn != null) { - if (!thing2.TryAbsorbStack(thing, false)) - { - thing.Destroy(DestroyMode.Vanish); - } + pawn.PreTraded(TradeAction.PlayerSells, playerNegotiator, this.pawn); + this.AddPawnToStock(pawn); } else { - this.AddThingToRandomInventory(thing); + Thing thing = toGive.SplitOff(countToGive); + thing.PreTraded(TradeAction.PlayerSells, playerNegotiator, this.pawn); + Thing thing2 = TradeUtility.ThingFromStockToMergeWith(this.pawn, thing); + if (thing2 != null) + { + if (!thing2.TryAbsorbStack(thing, false)) + { + thing.Destroy(DestroyMode.Vanish); + } + } + else + { + this.AddThingToRandomInventory(thing); + } } } } @@ -141,13 +185,7 @@ public void GiveSoldThingToPlayer(Thing toGive, int countToGive, Pawn playerNego } else { - Log.Error(string.Concat(new object[] - { - "Could not place bought thing ", - thing, - " at ", - positionHeld - })); + Log.Error("Could not place bought thing " + thing + " at " + positionHeld); thing.Destroy(DestroyMode.Vanish); } } @@ -171,23 +209,16 @@ private void AddPawnToStock(Pawn newPawn) if (lord == null) { newPawn.Destroy(DestroyMode.Vanish); - Log.Error(string.Concat(new object[] - { - "Tried to sell pawn ", - newPawn, - " to ", - this.pawn, - ", but ", - this.pawn, - " has no lord. Traders without lord can't buy pawns." - })); - return; + Log.Error("Tried to sell pawn " + newPawn + " to " + this.pawn + ", but " + this.pawn + " has no lord. Traders without lord can't buy pawns."); } - if (newPawn.RaceProps.Humanlike) + else { - this.soldPrisoners.Add(newPawn); + if (newPawn.RaceProps.Humanlike) + { + this.soldPrisoners.Add(newPawn); + } + lord.AddPawn(newPawn); } - lord.AddPawn(newPawn); } private void AddThingToRandomInventory(Thing thing) @@ -200,9 +231,9 @@ private void AddThingToRandomInventory(Thing thing) where x.GetTraderCaravanRole() == TraderCaravanRole.Carrier select x; } - if (source.Any()) + if (source.Any()) { - if (!source.RandomElement().inventory.innerContainer.TryAdd(thing, true)) + if (!source.RandomElement().inventory.innerContainer.TryAdd(thing, true)) { thing.Destroy(DestroyMode.Vanish); } @@ -215,7 +246,11 @@ where x.GetTraderCaravanRole() == TraderCaravanRole.Carrier private bool ReachableForTrade(Thing thing) { - return this.pawn.Map == thing.Map && this.pawn.Map.reachability.CanReach(this.pawn.Position, thing, PathEndMode.Touch, TraverseMode.PassDoors, Danger.Some); + if (this.pawn.Map != thing.Map) + { + return false; + } + return this.pawn.Map.reachability.CanReach(this.pawn.Position, thing, PathEndMode.Touch, TraverseMode.PassDoors, Danger.Some); } } } diff --git a/Assembly-CSharp/RimWorld/Pawn_TrainingTracker.cs b/Assembly-CSharp/RimWorld/Pawn_TrainingTracker.cs index 96a0571c8..26fd46947 100644 --- a/Assembly-CSharp/RimWorld/Pawn_TrainingTracker.cs +++ b/Assembly-CSharp/RimWorld/Pawn_TrainingTracker.cs @@ -59,26 +59,10 @@ public AcceptanceReport CanAssignToTrain(TrainableDef td, out bool visible) } if (this.pawn.RaceProps.trainableTags != null) { - int j = 0; - while (j < this.pawn.RaceProps.trainableTags.Count) + for (int j = 0; j < this.pawn.RaceProps.trainableTags.Count; j++) { if (td.MatchesTag(this.pawn.RaceProps.trainableTags[j])) - { - if (this.pawn.BodySize < td.minBodySize) - { - visible = true; - return new AcceptanceReport("CannotTrainTooSmall".Translate(new object[] - { - this.pawn.LabelCapNoCount - })); - } - visible = true; - return true; - } - else - { - j++; - } + goto IL_00a3; } } if (!td.defaultTrainable) @@ -89,18 +73,20 @@ public AcceptanceReport CanAssignToTrain(TrainableDef td, out bool visible) if (this.pawn.BodySize < td.minBodySize) { visible = true; - return new AcceptanceReport("CannotTrainTooSmall".Translate(new object[] - { - this.pawn.LabelCapNoCount - })); + return new AcceptanceReport("CannotTrainTooSmall".Translate(this.pawn.LabelCapNoCount)); } if (this.pawn.RaceProps.TrainableIntelligence.intelligenceOrder < td.requiredTrainableIntelligence.intelligenceOrder) { visible = true; - return new AcceptanceReport("CannotTrainNotSmartEnough".Translate(new object[] - { - td.requiredTrainableIntelligence - })); + return new AcceptanceReport("CannotTrainNotSmartEnough".Translate(td.requiredTrainableIntelligence)); + } + visible = true; + return true; + IL_00a3: + if (this.pawn.BodySize < td.minBodySize) + { + visible = true; + return new AcceptanceReport("CannotTrainTooSmall".Translate(this.pawn.LabelCapNoCount)); } visible = true; return true; @@ -122,9 +108,11 @@ public TrainableDef NextTrainableToTrain() public void Train(TrainableDef td, Pawn trainer) { DefMap defMap; - DefMap expr_06 = defMap = this.steps; - int num = defMap[td]; - expr_06[td] = num + 1; + DefMap obj = defMap = this.steps; + TrainableDef def; + TrainableDef def2 = def = td; + int num = defMap[def]; + obj[def2] = num + 1; if (this.IsCompleted(td) && td == TrainableDefOf.Obedience) { this.pawn.playerSettings.master = trainer; @@ -149,9 +137,9 @@ public void SetWantedRecursive(TrainableDef td, bool checkOn) IEnumerable enumerable = from t in DefDatabase.AllDefsListForReading where t.prerequisites != null && t.prerequisites.Contains(td) select t; - foreach (TrainableDef current in enumerable) + foreach (TrainableDef item in enumerable) { - this.SetWantedRecursive(current, false); + this.SetWantedRecursive(item, false); } } } diff --git a/Assembly-CSharp/RimWorld/Pawn_WorkSettings.cs b/Assembly-CSharp/RimWorld/Pawn_WorkSettings.cs index 17741d385..688ddb2ca 100644 --- a/Assembly-CSharp/RimWorld/Pawn_WorkSettings.cs +++ b/Assembly-CSharp/RimWorld/Pawn_WorkSettings.cs @@ -80,30 +80,37 @@ public void EnableAndInitialize() } this.priorities.SetAll(0); int num = 0; - foreach (WorkTypeDef current in from w in DefDatabase.AllDefs + foreach (WorkTypeDef item in from w in DefDatabase.AllDefs where !w.alwaysStartActive && !this.pawn.story.WorkTypeIsDisabled(w) orderby this.pawn.skills.AverageOfRelevantSkillsFor(w) descending select w) { - this.SetPriority(current, 3); + this.SetPriority(item, 3); num++; if (num >= 6) - { break; - } } - foreach (WorkTypeDef current2 in from w in DefDatabase.AllDefs + foreach (WorkTypeDef item2 in from w in DefDatabase.AllDefs where w.alwaysStartActive select w) { - if (!this.pawn.story.WorkTypeIsDisabled(current2)) + if (!this.pawn.story.WorkTypeIsDisabled(item2)) { - this.SetPriority(current2, 3); + this.SetPriority(item2, 3); } } - foreach (WorkTypeDef current3 in this.pawn.story.DisabledWorkTypes) + List.Enumerator enumerator3 = this.pawn.story.DisabledWorkTypes.GetEnumerator(); + try { - this.Disable(current3); + while (enumerator3.MoveNext()) + { + WorkTypeDef current3 = enumerator3.Current; + this.Disable(current3); + } + } + finally + { + ((IDisposable)(object)enumerator3).Dispose(); } } @@ -121,25 +128,21 @@ public void SetPriority(WorkTypeDef w, int priority) this.ConfirmInitializedDebug(); if (priority != 0 && this.pawn.story.WorkTypeIsDisabled(w)) { - Log.Error(string.Concat(new object[] - { - "Tried to change priority on disabled worktype ", - w, - " for pawn ", - this.pawn - })); - return; - } - if (priority < 0 || priority > 4) - { - Log.Message("Trying to set work to invalid priority " + priority); + Log.Error("Tried to change priority on disabled worktype " + w + " for pawn " + this.pawn); } - this.priorities[w] = priority; - if (priority == 0) + else { - this.pawn.mindState.Notify_WorkPriorityDisabled(w); + if (priority < 0 || priority > 4) + { + Log.Message("Trying to set work to invalid priority " + priority); + } + this.priorities[w] = priority; + if (priority == 0) + { + this.pawn.mindState.Notify_WorkPriorityDisabled(w); + } + this.workGiversDirty = true; } - this.workGiversDirty = true; } public int GetPriority(WorkTypeDef w) @@ -179,13 +182,21 @@ public void Notify_UseWorkPrioritiesChanged() public void Notify_GainedTrait() { - if (this.priorities == null) - { - return; - } - foreach (WorkTypeDef current in this.pawn.story.DisabledWorkTypes) + if (this.priorities != null) { - this.Disable(current); + List.Enumerator enumerator = this.pawn.story.DisabledWorkTypes.GetEnumerator(); + try + { + while (enumerator.MoveNext()) + { + WorkTypeDef current = enumerator.Current; + this.Disable(current); + } + } + finally + { + ((IDisposable)(object)enumerator).Dispose(); + } } } @@ -200,17 +211,14 @@ private void CacheWorkGiversInOrder() int priority = this.GetPriority(workTypeDef); if (priority > 0) { - if (priority < num) + if (priority < num && workTypeDef.workGiversByPriority.Any((Predicate)((WorkGiverDef wg) => !wg.emergency))) { - if (workTypeDef.workGiversByPriority.Any((WorkGiverDef wg) => !wg.emergency)) - { - num = priority; - } + num = priority; } Pawn_WorkSettings.wtsByPrio.Add(workTypeDef); } } - Pawn_WorkSettings.wtsByPrio.InsertionSort(delegate(WorkTypeDef a, WorkTypeDef b) + Pawn_WorkSettings.wtsByPrio.InsertionSort((Comparison)delegate(WorkTypeDef a, WorkTypeDef b) { float value = (float)(a.naturalPriority + (4 - this.GetPriority(a)) * 100000); return ((float)(b.naturalPriority + (4 - this.GetPriority(b)) * 100000)).CompareTo(value); @@ -251,42 +259,19 @@ public string DebugString() stringBuilder.AppendLine("Cached emergency WorkGivers in order:"); for (int i = 0; i < this.WorkGiversInOrderEmergency.Count; i++) { - stringBuilder.AppendLine(string.Concat(new object[] - { - " ", - i, - ": ", - this.DebugStringFor(this.WorkGiversInOrderEmergency[i].def) - })); + stringBuilder.AppendLine(" " + i + ": " + this.DebugStringFor(this.WorkGiversInOrderEmergency[i].def)); } stringBuilder.AppendLine("Cached normal WorkGivers in order:"); for (int j = 0; j < this.WorkGiversInOrderNormal.Count; j++) { - stringBuilder.AppendLine(string.Concat(new object[] - { - " ", - j, - ": ", - this.DebugStringFor(this.WorkGiversInOrderNormal[j].def) - })); + stringBuilder.AppendLine(" " + j + ": " + this.DebugStringFor(this.WorkGiversInOrderNormal[j].def)); } return stringBuilder.ToString(); } private string DebugStringFor(WorkGiverDef wg) { - return string.Concat(new object[] - { - "[", - this.GetPriority(wg.workType), - " ", - wg.workType.defName, - "] - ", - wg.defName, - " (", - wg.priorityInType, - ")" - }); + return "[" + this.GetPriority(wg.workType) + " " + wg.workType.defName + "] - " + wg.defName + " (" + wg.priorityInType + ")"; } } } diff --git a/Assembly-CSharp/RimWorld/PawnsArriveMode.cs b/Assembly-CSharp/RimWorld/PawnsArriveMode.cs index 476d1e91f..627ece2b7 100644 --- a/Assembly-CSharp/RimWorld/PawnsArriveMode.cs +++ b/Assembly-CSharp/RimWorld/PawnsArriveMode.cs @@ -1,12 +1,10 @@ -using System; - namespace RimWorld { public enum PawnsArriveMode : byte { - Undecided, - EdgeWalkIn, - EdgeDrop, - CenterDrop + Undecided = 0, + EdgeWalkIn = 1, + EdgeDrop = 2, + CenterDrop = 3 } } diff --git a/Assembly-CSharp/RimWorld/PawnsFinder.cs b/Assembly-CSharp/RimWorld/PawnsFinder.cs index f07c9f1c7..663e9dd08 100644 --- a/Assembly-CSharp/RimWorld/PawnsFinder.cs +++ b/Assembly-CSharp/RimWorld/PawnsFinder.cs @@ -1,6 +1,5 @@ -using System; +using RimWorld.Planet; using System.Collections.Generic; -using System.Diagnostics; using Verse; namespace RimWorld @@ -11,10 +10,40 @@ public static IEnumerable AllMapsAndWorld_AliveOrDead { get { - PawnsFinder.<>c__IteratorCB <>c__IteratorCB = new PawnsFinder.<>c__IteratorCB(); - PawnsFinder.<>c__IteratorCB expr_07 = <>c__IteratorCB; - expr_07.$PC = -2; - return expr_07; + foreach (Pawn item in PawnsFinder.AllMapsAndWorld_Alive) + { + yield return item; + } + if (Find.World != null) + { + foreach (Pawn item2 in Find.WorldPawns.AllPawnsDead) + { + yield return item2; + } + } + List makingPawns = PawnGroupKindWorker.pawnsBeingGeneratedNow; + if (makingPawns != null) + { + for (int j = 0; j < makingPawns.Count; j++) + { + if (makingPawns[j].Dead) + { + yield return makingPawns[j]; + } + } + } + List makingThings = ItemCollectionGenerator.thingsBeingGeneratedNow; + if (makingThings != null) + { + for (int i = 0; i < makingThings.Count; i++) + { + Pawn p = makingThings[i] as Pawn; + if (p != null && p.Dead) + { + yield return p; + } + } + } } } @@ -22,10 +51,51 @@ public static IEnumerable AllMapsAndWorld_Alive { get { - PawnsFinder.<>c__IteratorCC <>c__IteratorCC = new PawnsFinder.<>c__IteratorCC(); - PawnsFinder.<>c__IteratorCC expr_07 = <>c__IteratorCC; - expr_07.$PC = -2; - return expr_07; + List makingPawns = PawnGroupKindWorker.pawnsBeingGeneratedNow; + if (makingPawns != null) + { + for (int k = 0; k < makingPawns.Count; k++) + { + if (!makingPawns[k].Dead) + { + yield return makingPawns[k]; + } + } + } + List makingThings = ItemCollectionGenerator.thingsBeingGeneratedNow; + if (makingThings != null) + { + for (int j = 0; j < makingThings.Count; j++) + { + Pawn p3 = makingThings[j] as Pawn; + if (p3 != null && !p3.Dead) + { + yield return p3; + } + } + } + if (Find.World != null) + { + foreach (Pawn item in Find.WorldPawns.AllPawnsAlive) + { + yield return item; + } + foreach (Pawn allMap in PawnsFinder.AllMaps) + { + yield return allMap; + } + } + if (Current.ProgramState != ProgramState.Playing && Find.GameInitData != null && Find.GameInitData != null) + { + List startingPawns = Find.GameInitData.startingPawns; + for (int i = 0; i < startingPawns.Count; i++) + { + if (startingPawns[i] != null) + { + yield return startingPawns[i]; + } + } + } } } @@ -33,10 +103,14 @@ public static IEnumerable AllMaps { get { - PawnsFinder.<>c__IteratorCD <>c__IteratorCD = new PawnsFinder.<>c__IteratorCD(); - PawnsFinder.<>c__IteratorCD expr_07 = <>c__IteratorCD; - expr_07.$PC = -2; - return expr_07; + List maps = Find.Maps; + for (int i = 0; i < maps.Count; i++) + { + foreach (Pawn allPawn in maps[i].mapPawns.AllPawns) + { + yield return allPawn; + } + } } } @@ -44,10 +118,15 @@ public static IEnumerable AllMaps_Spawned { get { - PawnsFinder.<>c__IteratorCE <>c__IteratorCE = new PawnsFinder.<>c__IteratorCE(); - PawnsFinder.<>c__IteratorCE expr_07 = <>c__IteratorCE; - expr_07.$PC = -2; - return expr_07; + List maps = Find.Maps; + for (int j = 0; j < maps.Count; j++) + { + List spawned = maps[j].mapPawns.AllPawnsSpawned; + for (int i = 0; i < spawned.Count; i++) + { + yield return spawned[i]; + } + } } } @@ -55,10 +134,30 @@ public static IEnumerable AllMapsCaravansAndTravelingTransportPods { get { - PawnsFinder.<>c__IteratorCF <>c__IteratorCF = new PawnsFinder.<>c__IteratorCF(); - PawnsFinder.<>c__IteratorCF expr_07 = <>c__IteratorCF; - expr_07.$PC = -2; - return expr_07; + foreach (Pawn allMap in PawnsFinder.AllMaps) + { + yield return allMap; + } + if (Find.World != null) + { + List caravans = Find.WorldObjects.Caravans; + for (int k = 0; k < caravans.Count; k++) + { + List pawns = caravans[k].PawnsListForReading; + for (int i = 0; i < pawns.Count; i++) + { + yield return pawns[i]; + } + } + List travelingTransportPods = Find.WorldObjects.TravelingTransportPods; + for (int j = 0; j < travelingTransportPods.Count; j++) + { + foreach (Pawn pawn in travelingTransportPods[j].Pawns) + { + yield return pawn; + } + } + } } } @@ -66,10 +165,13 @@ public static IEnumerable AllMapsCaravansAndTravelingTransportPods_Colonis { get { - PawnsFinder.<>c__IteratorD0 <>c__IteratorD = new PawnsFinder.<>c__IteratorD0(); - PawnsFinder.<>c__IteratorD0 expr_07 = <>c__IteratorD; - expr_07.$PC = -2; - return expr_07; + foreach (Pawn allMapsCaravansAndTravelingTransportPod in PawnsFinder.AllMapsCaravansAndTravelingTransportPods) + { + if (allMapsCaravansAndTravelingTransportPod.IsColonist) + { + yield return allMapsCaravansAndTravelingTransportPod; + } + } } } @@ -77,10 +179,13 @@ public static IEnumerable AllMapsCaravansAndTravelingTransportPods_FreeCol { get { - PawnsFinder.<>c__IteratorD1 <>c__IteratorD = new PawnsFinder.<>c__IteratorD1(); - PawnsFinder.<>c__IteratorD1 expr_07 = <>c__IteratorD; - expr_07.$PC = -2; - return expr_07; + foreach (Pawn allMapsCaravansAndTravelingTransportPod in PawnsFinder.AllMapsCaravansAndTravelingTransportPods) + { + if (allMapsCaravansAndTravelingTransportPod.IsColonist && allMapsCaravansAndTravelingTransportPod.HostFaction == null) + { + yield return allMapsCaravansAndTravelingTransportPod; + } + } } } @@ -88,10 +193,13 @@ public static IEnumerable AllMapsCaravansAndTravelingTransportPods_Prisone { get { - PawnsFinder.<>c__IteratorD2 <>c__IteratorD = new PawnsFinder.<>c__IteratorD2(); - PawnsFinder.<>c__IteratorD2 expr_07 = <>c__IteratorD; - expr_07.$PC = -2; - return expr_07; + foreach (Pawn allMapsCaravansAndTravelingTransportPod in PawnsFinder.AllMapsCaravansAndTravelingTransportPods) + { + if (allMapsCaravansAndTravelingTransportPod.IsPrisonerOfColony) + { + yield return allMapsCaravansAndTravelingTransportPod; + } + } } } @@ -99,10 +207,15 @@ public static IEnumerable AllMaps_PrisonersOfColonySpawned { get { - PawnsFinder.<>c__IteratorD3 <>c__IteratorD = new PawnsFinder.<>c__IteratorD3(); - PawnsFinder.<>c__IteratorD3 expr_07 = <>c__IteratorD; - expr_07.$PC = -2; - return expr_07; + List maps = Find.Maps; + for (int j = 0; j < maps.Count; j++) + { + List prisonersOfColonySpawned = maps[j].mapPawns.PrisonersOfColonySpawned; + for (int i = 0; i < prisonersOfColonySpawned.Count; i++) + { + yield return prisonersOfColonySpawned[i]; + } + } } } @@ -110,10 +223,14 @@ public static IEnumerable AllMaps_PrisonersOfColony { get { - PawnsFinder.<>c__IteratorD4 <>c__IteratorD = new PawnsFinder.<>c__IteratorD4(); - PawnsFinder.<>c__IteratorD4 expr_07 = <>c__IteratorD; - expr_07.$PC = -2; - return expr_07; + List maps = Find.Maps; + for (int i = 0; i < maps.Count; i++) + { + foreach (Pawn item in maps[i].mapPawns.PrisonersOfColony) + { + yield return item; + } + } } } @@ -121,10 +238,14 @@ public static IEnumerable AllMaps_FreeColonists { get { - PawnsFinder.<>c__IteratorD5 <>c__IteratorD = new PawnsFinder.<>c__IteratorD5(); - PawnsFinder.<>c__IteratorD5 expr_07 = <>c__IteratorD; - expr_07.$PC = -2; - return expr_07; + List maps = Find.Maps; + for (int i = 0; i < maps.Count; i++) + { + foreach (Pawn freeColonist in maps[i].mapPawns.FreeColonists) + { + yield return freeColonist; + } + } } } @@ -132,10 +253,14 @@ public static IEnumerable AllMaps_FreeColonistsSpawned { get { - PawnsFinder.<>c__IteratorD6 <>c__IteratorD = new PawnsFinder.<>c__IteratorD6(); - PawnsFinder.<>c__IteratorD6 expr_07 = <>c__IteratorD; - expr_07.$PC = -2; - return expr_07; + List maps = Find.Maps; + for (int i = 0; i < maps.Count; i++) + { + foreach (Pawn item in maps[i].mapPawns.FreeColonistsSpawned) + { + yield return item; + } + } } } @@ -143,10 +268,14 @@ public static IEnumerable AllMaps_FreeColonistsAndPrisonersSpawned { get { - PawnsFinder.<>c__IteratorD7 <>c__IteratorD = new PawnsFinder.<>c__IteratorD7(); - PawnsFinder.<>c__IteratorD7 expr_07 = <>c__IteratorD; - expr_07.$PC = -2; - return expr_07; + List maps = Find.Maps; + for (int i = 0; i < maps.Count; i++) + { + foreach (Pawn item in maps[i].mapPawns.FreeColonistsAndPrisonersSpawned) + { + yield return item; + } + } } } @@ -154,22 +283,28 @@ public static IEnumerable AllMaps_FreeColonistsAndPrisoners { get { - PawnsFinder.<>c__IteratorD8 <>c__IteratorD = new PawnsFinder.<>c__IteratorD8(); - PawnsFinder.<>c__IteratorD8 expr_07 = <>c__IteratorD; - expr_07.$PC = -2; - return expr_07; + List maps = Find.Maps; + for (int i = 0; i < maps.Count; i++) + { + foreach (Pawn freeColonistsAndPrisoner in maps[i].mapPawns.FreeColonistsAndPrisoners) + { + yield return freeColonistsAndPrisoner; + } + } } } - [DebuggerHidden] public static IEnumerable AllMaps_SpawnedPawnsInFaction(Faction faction) { - PawnsFinder.c__IteratorD9 c__IteratorD = new PawnsFinder.c__IteratorD9(); - c__IteratorD.faction = faction; - c__IteratorD.<$>faction = faction; - PawnsFinder.c__IteratorD9 expr_15 = c__IteratorD; - expr_15.$PC = -2; - return expr_15; + List maps = Find.Maps; + for (int j = 0; j < maps.Count; j++) + { + List spawnedPawnsInFaction = maps[j].mapPawns.SpawnedPawnsInFaction(faction); + for (int i = 0; i < spawnedPawnsInFaction.Count; i++) + { + yield return spawnedPawnsInFaction[i]; + } + } } } } diff --git a/Assembly-CSharp/RimWorld/PawnsToGather.cs b/Assembly-CSharp/RimWorld/PawnsToGather.cs index 158b60333..16278ccec 100644 --- a/Assembly-CSharp/RimWorld/PawnsToGather.cs +++ b/Assembly-CSharp/RimWorld/PawnsToGather.cs @@ -1,11 +1,9 @@ -using System; - namespace RimWorld { public enum PawnsToGather { - None, - Animals, - Slaves + None = 0, + Animals = 1, + Slaves = 2 } } diff --git a/Assembly-CSharp/RimWorld/PlaceWorker_Conduit.cs b/Assembly-CSharp/RimWorld/PlaceWorker_Conduit.cs index b9a5a89bb..514123e3d 100644 --- a/Assembly-CSharp/RimWorld/PlaceWorker_Conduit.cs +++ b/Assembly-CSharp/RimWorld/PlaceWorker_Conduit.cs @@ -1,4 +1,3 @@ -using System; using System.Collections.Generic; using Verse; diff --git a/Assembly-CSharp/RimWorld/PlaceWorker_Cooler.cs b/Assembly-CSharp/RimWorld/PlaceWorker_Cooler.cs index d8eeb715f..5ea89d695 100644 --- a/Assembly-CSharp/RimWorld/PlaceWorker_Cooler.cs +++ b/Assembly-CSharp/RimWorld/PlaceWorker_Cooler.cs @@ -1,4 +1,3 @@ -using System; using System.Collections.Generic; using System.Linq; using UnityEngine; @@ -12,31 +11,29 @@ public override void DrawGhost(ThingDef def, IntVec3 center, Rot4 rot) { IntVec3 intVec = center + IntVec3.South.RotatedBy(rot); IntVec3 intVec2 = center + IntVec3.North.RotatedBy(rot); - GenDraw.DrawFieldEdges(new List - { - intVec - }, GenTemperature.ColorSpotCold); - GenDraw.DrawFieldEdges(new List - { - intVec2 - }, GenTemperature.ColorSpotHot); + List list = new List(); + list.Add(intVec); + GenDraw.DrawFieldEdges(list, GenTemperature.ColorSpotCold); + list = new List(); + list.Add(intVec2); + GenDraw.DrawFieldEdges(list, GenTemperature.ColorSpotHot); RoomGroup roomGroup = intVec2.GetRoomGroup(base.Map); RoomGroup roomGroup2 = intVec.GetRoomGroup(base.Map); if (roomGroup != null && roomGroup2 != null) { if (roomGroup == roomGroup2 && !roomGroup.UsesOutdoorTemperature) { - GenDraw.DrawFieldEdges(roomGroup.Cells.ToList(), new Color(1f, 0.7f, 0f, 0.5f)); + GenDraw.DrawFieldEdges(roomGroup.Cells.ToList(), new Color(1f, 0.7f, 0f, 0.5f)); } else { if (!roomGroup.UsesOutdoorTemperature) { - GenDraw.DrawFieldEdges(roomGroup.Cells.ToList(), GenTemperature.ColorRoomHot); + GenDraw.DrawFieldEdges(roomGroup.Cells.ToList(), GenTemperature.ColorRoomHot); } if (!roomGroup2.UsesOutdoorTemperature) { - GenDraw.DrawFieldEdges(roomGroup2.Cells.ToList(), GenTemperature.ColorRoomCold); + GenDraw.DrawFieldEdges(roomGroup2.Cells.ToList(), GenTemperature.ColorRoomCold); } } } @@ -46,11 +43,11 @@ public override AcceptanceReport AllowsPlacing(BuildableDef def, IntVec3 center, { IntVec3 c = center + IntVec3.South.RotatedBy(rot); IntVec3 c2 = center + IntVec3.North.RotatedBy(rot); - if (c.Impassable(base.Map) || c2.Impassable(base.Map)) + if (!c.Impassable(base.Map) && !c2.Impassable(base.Map)) { - return "MustPlaceCoolerWithFreeSpaces".Translate(); + return true; } - return true; + return "MustPlaceCoolerWithFreeSpaces".Translate(); } } } diff --git a/Assembly-CSharp/RimWorld/PlaceWorker_CoolerSimple.cs b/Assembly-CSharp/RimWorld/PlaceWorker_CoolerSimple.cs index 7531160b3..a85488075 100644 --- a/Assembly-CSharp/RimWorld/PlaceWorker_CoolerSimple.cs +++ b/Assembly-CSharp/RimWorld/PlaceWorker_CoolerSimple.cs @@ -1,4 +1,3 @@ -using System; using System.Linq; using Verse; @@ -11,7 +10,7 @@ public override void DrawGhost(ThingDef def, IntVec3 center, Rot4 rot) RoomGroup roomGroup = center.GetRoomGroup(base.Map); if (roomGroup != null && !roomGroup.UsesOutdoorTemperature) { - GenDraw.DrawFieldEdges(roomGroup.Cells.ToList(), GenTemperature.ColorRoomCold); + GenDraw.DrawFieldEdges(roomGroup.Cells.ToList(), GenTemperature.ColorRoomCold); } } } diff --git a/Assembly-CSharp/RimWorld/PlaceWorker_DoorLearnOpeningSpeed.cs b/Assembly-CSharp/RimWorld/PlaceWorker_DoorLearnOpeningSpeed.cs index ae5a9f9b3..5148fb2d2 100644 --- a/Assembly-CSharp/RimWorld/PlaceWorker_DoorLearnOpeningSpeed.cs +++ b/Assembly-CSharp/RimWorld/PlaceWorker_DoorLearnOpeningSpeed.cs @@ -8,8 +8,8 @@ public class PlaceWorker_DoorLearnOpeningSpeed : PlaceWorker { public override void PostPlace(Map map, BuildableDef def, IntVec3 loc, Rot4 rot) { - Blueprint_Door blueprint_Door = (Blueprint_Door)loc.GetThingList(map).FirstOrDefault((Thing t) => t is Blueprint_Door); - if (blueprint_Door != null && blueprint_Door.def.entityDefToBuild.GetStatValueAbstract(StatDefOf.DoorOpenSpeed, blueprint_Door.stuffToUse) < 0.65f) + Blueprint_Door blueprint_Door = (Blueprint_Door)loc.GetThingList(map).FirstOrDefault((Func)((Thing t) => t is Blueprint_Door)); + if (blueprint_Door != null && blueprint_Door.def.entityDefToBuild.GetStatValueAbstract(StatDefOf.DoorOpenSpeed, blueprint_Door.stuffToUse) < 0.64999997615814209) { LessonAutoActivator.TeachOpportunity(ConceptDefOf.DoorOpenSpeed, OpportunityType.Important); } diff --git a/Assembly-CSharp/RimWorld/PlaceWorker_FuelingPort.cs b/Assembly-CSharp/RimWorld/PlaceWorker_FuelingPort.cs index 001b46545..306b9cc3a 100644 --- a/Assembly-CSharp/RimWorld/PlaceWorker_FuelingPort.cs +++ b/Assembly-CSharp/RimWorld/PlaceWorker_FuelingPort.cs @@ -1,4 +1,3 @@ -using System; using UnityEngine; using Verse; @@ -11,15 +10,10 @@ public class PlaceWorker_FuelingPort : PlaceWorker public override void DrawGhost(ThingDef def, IntVec3 center, Rot4 rot) { - if (def.building == null || !def.building.hasFuelingPort) + if (def.building != null && def.building.hasFuelingPort && FuelingPortUtility.GetFuelingPortCell(center, rot).Standable(Find.VisibleMap)) { - return; + PlaceWorker_FuelingPort.DrawFuelingPortCell(center, rot); } - if (!FuelingPortUtility.GetFuelingPortCell(center, rot).Standable(Find.VisibleMap)) - { - return; - } - PlaceWorker_FuelingPort.DrawFuelingPortCell(center, rot); } public static void DrawFuelingPortCell(IntVec3 center, Rot4 rot) diff --git a/Assembly-CSharp/RimWorld/PlaceWorker_HeadOnShipBeam.cs b/Assembly-CSharp/RimWorld/PlaceWorker_HeadOnShipBeam.cs index 10821eabe..b3389ad0e 100644 --- a/Assembly-CSharp/RimWorld/PlaceWorker_HeadOnShipBeam.cs +++ b/Assembly-CSharp/RimWorld/PlaceWorker_HeadOnShipBeam.cs @@ -1,4 +1,3 @@ -using System; using Verse; namespace RimWorld @@ -13,11 +12,11 @@ public override AcceptanceReport AllowsPlacing(BuildableDef checkingDef, IntVec3 return false; } Building edifice = c.GetEdifice(base.Map); - if (edifice == null || edifice.def != ThingDefOf.Ship_Beam) + if (edifice != null && edifice.def == ThingDefOf.Ship_Beam) { - return "MustPlaceHeadOnShipBeam".Translate(); + return true; } - return true; + return "MustPlaceHeadOnShipBeam".Translate(); } } } diff --git a/Assembly-CSharp/RimWorld/PlaceWorker_Heater.cs b/Assembly-CSharp/RimWorld/PlaceWorker_Heater.cs index 071bfaf14..f56efb2ae 100644 --- a/Assembly-CSharp/RimWorld/PlaceWorker_Heater.cs +++ b/Assembly-CSharp/RimWorld/PlaceWorker_Heater.cs @@ -1,4 +1,3 @@ -using System; using System.Linq; using Verse; @@ -11,7 +10,7 @@ public override void DrawGhost(ThingDef def, IntVec3 center, Rot4 rot) RoomGroup roomGroup = center.GetRoomGroup(base.Map); if (roomGroup != null && !roomGroup.UsesOutdoorTemperature) { - GenDraw.DrawFieldEdges(roomGroup.Cells.ToList(), GenTemperature.ColorRoomHot); + GenDraw.DrawFieldEdges(roomGroup.Cells.ToList(), GenTemperature.ColorRoomHot); } } } diff --git a/Assembly-CSharp/RimWorld/PlaceWorker_NeedsFuelingPort.cs b/Assembly-CSharp/RimWorld/PlaceWorker_NeedsFuelingPort.cs index e65f2e486..e22b4c06c 100644 --- a/Assembly-CSharp/RimWorld/PlaceWorker_NeedsFuelingPort.cs +++ b/Assembly-CSharp/RimWorld/PlaceWorker_NeedsFuelingPort.cs @@ -1,4 +1,3 @@ -using System; using System.Collections.Generic; using Verse; @@ -8,7 +7,8 @@ public class PlaceWorker_NeedsFuelingPort : PlaceWorker { public override AcceptanceReport AllowsPlacing(BuildableDef def, IntVec3 center, Rot4 rot, Thing thingToIgnore = null) { - if (FuelingPortUtility.FuelingPortGiverAtFuelingPortCell(center, Find.VisibleMap) == null) + Building building = FuelingPortUtility.FuelingPortGiverAtFuelingPortCell(center, Find.VisibleMap); + if (building == null) { return "MustPlaceNearFuelingPort".Translate(); } diff --git a/Assembly-CSharp/RimWorld/PlaceWorker_NeverAdjacentUnstandable.cs b/Assembly-CSharp/RimWorld/PlaceWorker_NeverAdjacentUnstandable.cs index 99723348f..2d10e38cc 100644 --- a/Assembly-CSharp/RimWorld/PlaceWorker_NeverAdjacentUnstandable.cs +++ b/Assembly-CSharp/RimWorld/PlaceWorker_NeverAdjacentUnstandable.cs @@ -1,4 +1,3 @@ -using System; using System.Collections.Generic; using System.Linq; using UnityEngine; @@ -10,19 +9,23 @@ public class PlaceWorker_NeverAdjacentUnstandable : PlaceWorker { public override void DrawGhost(ThingDef def, IntVec3 center, Rot4 rot) { - GenDraw.DrawFieldEdges(GenAdj.OccupiedRect(center, rot, def.size).ExpandedBy(1).Cells.ToList(), Color.white); + CellRect cellRect = GenAdj.OccupiedRect(center, rot, def.size); + cellRect = cellRect.ExpandedBy(1); + GenDraw.DrawFieldEdges(cellRect.Cells.ToList(), Color.white); } public override AcceptanceReport AllowsPlacing(BuildableDef def, IntVec3 center, Rot4 rot, Thing thingToIgnore = null) { - CellRect.CellRectIterator iterator = GenAdj.OccupiedRect(center, rot, def.Size).ExpandedBy(1).GetIterator(); + CellRect cellRect = GenAdj.OccupiedRect(center, rot, def.Size); + cellRect = cellRect.ExpandedBy(1); + CellRect.CellRectIterator iterator = cellRect.GetIterator(); while (!iterator.Done()) { IntVec3 current = iterator.Current; List list = base.Map.thingGrid.ThingsListAt(current); for (int i = 0; i < list.Count; i++) { - if (list[i] != thingToIgnore && list[i].def.passability != Traversability.Standable) + if (((list[i] != thingToIgnore) ? list[i].def.passability : Traversability.Standable) != 0) { return "MustPlaceAdjacentStandable".Translate(); } diff --git a/Assembly-CSharp/RimWorld/PlaceWorker_NextToHopperAccepter.cs b/Assembly-CSharp/RimWorld/PlaceWorker_NextToHopperAccepter.cs index 1e59e5723..35e8228eb 100644 --- a/Assembly-CSharp/RimWorld/PlaceWorker_NextToHopperAccepter.cs +++ b/Assembly-CSharp/RimWorld/PlaceWorker_NextToHopperAccepter.cs @@ -1,4 +1,3 @@ -using System; using System.Collections.Generic; using Verse; @@ -18,12 +17,9 @@ public override AcceptanceReport AllowsPlacing(BuildableDef checkingDef, IntVec3 { Thing thing = thingList[j]; ThingDef thingDef = GenConstruct.BuiltDefOf(thing.def) as ThingDef; - if (thingDef != null && thingDef.building != null) + if (thingDef != null && thingDef.building != null && thingDef.building.wantsHopperAdjacent) { - if (thingDef.building.wantsHopperAdjacent) - { - return true; - } + return true; } } } diff --git a/Assembly-CSharp/RimWorld/PlaceWorker_NotUnderRoof.cs b/Assembly-CSharp/RimWorld/PlaceWorker_NotUnderRoof.cs index 17a0de39d..a41818847 100644 --- a/Assembly-CSharp/RimWorld/PlaceWorker_NotUnderRoof.cs +++ b/Assembly-CSharp/RimWorld/PlaceWorker_NotUnderRoof.cs @@ -1,4 +1,3 @@ -using System; using Verse; namespace RimWorld diff --git a/Assembly-CSharp/RimWorld/PlaceWorker_OnSteamGeyser.cs b/Assembly-CSharp/RimWorld/PlaceWorker_OnSteamGeyser.cs index 579694c1e..2927c062f 100644 --- a/Assembly-CSharp/RimWorld/PlaceWorker_OnSteamGeyser.cs +++ b/Assembly-CSharp/RimWorld/PlaceWorker_OnSteamGeyser.cs @@ -1,4 +1,3 @@ -using System; using Verse; namespace RimWorld @@ -8,11 +7,11 @@ public class PlaceWorker_OnSteamGeyser : PlaceWorker public override AcceptanceReport AllowsPlacing(BuildableDef checkingDef, IntVec3 loc, Rot4 rot, Thing thingToIgnore = null) { Thing thing = base.Map.thingGrid.ThingAt(loc, ThingDefOf.SteamGeyser); - if (thing == null || thing.Position != loc) + if (thing != null && !(thing.Position != loc)) { - return "MustPlaceOnSteamGeyser".Translate(); + return true; } - return true; + return "MustPlaceOnSteamGeyser".Translate(); } public override bool ForceAllowPlaceOver(BuildableDef otherDef) diff --git a/Assembly-CSharp/RimWorld/PlaceWorker_ReportWorkSpeedPenalties.cs b/Assembly-CSharp/RimWorld/PlaceWorker_ReportWorkSpeedPenalties.cs index 138b20869..26f99552e 100644 --- a/Assembly-CSharp/RimWorld/PlaceWorker_ReportWorkSpeedPenalties.cs +++ b/Assembly-CSharp/RimWorld/PlaceWorker_ReportWorkSpeedPenalties.cs @@ -1,4 +1,3 @@ -using System; using Verse; namespace RimWorld @@ -8,32 +7,27 @@ public class PlaceWorker_ReportWorkSpeedPenalties : PlaceWorker public override void PostPlace(Map map, BuildableDef def, IntVec3 loc, Rot4 rot) { ThingDef thingDef = def as ThingDef; - if (thingDef == null) + if (thingDef != null) { - return; - } - bool flag = StatPart_WorkTableOutdoors.Applies(thingDef, map, loc); - bool flag2 = StatPart_WorkTableTemperature.Applies(thingDef, map, loc); - if (flag || flag2) - { - string text = "WillGetWorkSpeedPenalty".Translate(new object[] - { - def.label - }).CapitalizeFirst() + ": "; + bool flag = StatPart_WorkTableOutdoors.Applies(thingDef, map, loc); + bool flag2 = StatPart_WorkTableTemperature.Applies(thingDef, map, loc); + if (!flag && !flag2) + return; + string str = "WillGetWorkSpeedPenalty".Translate(def.label).CapitalizeFirst() + ": "; if (flag) { - text += "Outdoors".Translate().ToLower(); + str += "Outdoors".Translate().ToLower(); } if (flag2) { if (flag) { - text += ", "; + str += ", "; } - text += "BadTemperature".Translate().ToLower(); + str += "BadTemperature".Translate().ToLower(); } - text += "."; - Messages.Message(text, MessageSound.Negative); + str += "."; + Messages.Message(str, MessageSound.Negative); } } } diff --git a/Assembly-CSharp/RimWorld/PlaceWorker_ShowDeepResources.cs b/Assembly-CSharp/RimWorld/PlaceWorker_ShowDeepResources.cs index b0e7bfb39..1c821f7c7 100644 --- a/Assembly-CSharp/RimWorld/PlaceWorker_ShowDeepResources.cs +++ b/Assembly-CSharp/RimWorld/PlaceWorker_ShowDeepResources.cs @@ -1,4 +1,3 @@ -using System; using System.Collections.Generic; using Verse; diff --git a/Assembly-CSharp/RimWorld/PlaceWorker_ShowFacilitiesConnections.cs b/Assembly-CSharp/RimWorld/PlaceWorker_ShowFacilitiesConnections.cs index 78b8b7cdb..45d73b655 100644 --- a/Assembly-CSharp/RimWorld/PlaceWorker_ShowFacilitiesConnections.cs +++ b/Assembly-CSharp/RimWorld/PlaceWorker_ShowFacilitiesConnections.cs @@ -1,4 +1,3 @@ -using System; using Verse; namespace RimWorld diff --git a/Assembly-CSharp/RimWorld/PlaceWorker_ShowTradeBeaconRadius.cs b/Assembly-CSharp/RimWorld/PlaceWorker_ShowTradeBeaconRadius.cs index 168ea1b65..1e3deaf41 100644 --- a/Assembly-CSharp/RimWorld/PlaceWorker_ShowTradeBeaconRadius.cs +++ b/Assembly-CSharp/RimWorld/PlaceWorker_ShowTradeBeaconRadius.cs @@ -1,4 +1,3 @@ -using System; using Verse; namespace RimWorld diff --git a/Assembly-CSharp/RimWorld/PlaceWorker_Vent.cs b/Assembly-CSharp/RimWorld/PlaceWorker_Vent.cs index 3908db7c3..d03f96198 100644 --- a/Assembly-CSharp/RimWorld/PlaceWorker_Vent.cs +++ b/Assembly-CSharp/RimWorld/PlaceWorker_Vent.cs @@ -1,4 +1,3 @@ -using System; using System.Collections.Generic; using System.Linq; using UnityEngine; @@ -12,31 +11,29 @@ public override void DrawGhost(ThingDef def, IntVec3 center, Rot4 rot) { IntVec3 intVec = center + IntVec3.South.RotatedBy(rot); IntVec3 intVec2 = center + IntVec3.North.RotatedBy(rot); - GenDraw.DrawFieldEdges(new List - { - intVec - }, Color.white); - GenDraw.DrawFieldEdges(new List - { - intVec2 - }, Color.white); + List list = new List(); + list.Add(intVec); + GenDraw.DrawFieldEdges(list, Color.white); + list = new List(); + list.Add(intVec2); + GenDraw.DrawFieldEdges(list, Color.white); RoomGroup roomGroup = intVec2.GetRoomGroup(base.Map); RoomGroup roomGroup2 = intVec.GetRoomGroup(base.Map); if (roomGroup != null && roomGroup2 != null) { if (roomGroup == roomGroup2 && !roomGroup.UsesOutdoorTemperature) { - GenDraw.DrawFieldEdges(roomGroup.Cells.ToList(), Color.white); + GenDraw.DrawFieldEdges(roomGroup.Cells.ToList(), Color.white); } else { if (!roomGroup.UsesOutdoorTemperature) { - GenDraw.DrawFieldEdges(roomGroup.Cells.ToList(), Color.white); + GenDraw.DrawFieldEdges(roomGroup.Cells.ToList(), Color.white); } if (!roomGroup2.UsesOutdoorTemperature) { - GenDraw.DrawFieldEdges(roomGroup2.Cells.ToList(), Color.white); + GenDraw.DrawFieldEdges(roomGroup2.Cells.ToList(), Color.white); } } } @@ -46,11 +43,11 @@ public override AcceptanceReport AllowsPlacing(BuildableDef def, IntVec3 center, { IntVec3 c = center + IntVec3.South.RotatedBy(rot); IntVec3 c2 = center + IntVec3.North.RotatedBy(rot); - if (c.Impassable(base.Map) || c2.Impassable(base.Map)) + if (!c.Impassable(base.Map) && !c2.Impassable(base.Map)) { - return "MustPlaceVentWithFreeSpaces".Translate(); + return true; } - return true; + return "MustPlaceVentWithFreeSpaces".Translate(); } } } diff --git a/Assembly-CSharp/RimWorld/PlaceWorker_WatchArea.cs b/Assembly-CSharp/RimWorld/PlaceWorker_WatchArea.cs index 7f4ee4cc0..2dd2e3dc0 100644 --- a/Assembly-CSharp/RimWorld/PlaceWorker_WatchArea.cs +++ b/Assembly-CSharp/RimWorld/PlaceWorker_WatchArea.cs @@ -1,4 +1,3 @@ -using System; using System.Linq; using Verse; @@ -8,7 +7,7 @@ public class PlaceWorker_WatchArea : PlaceWorker { public override void DrawGhost(ThingDef def, IntVec3 center, Rot4 rot) { - GenDraw.DrawFieldEdges(WatchBuildingUtility.CalculateWatchCells(def, center, rot, base.Map).ToList()); + GenDraw.DrawFieldEdges(WatchBuildingUtility.CalculateWatchCells(def, center, rot, base.Map).ToList()); } } } diff --git a/Assembly-CSharp/RimWorld/PlaceWorker_WindTurbine.cs b/Assembly-CSharp/RimWorld/PlaceWorker_WindTurbine.cs index 3aeb002d1..a551f1229 100644 --- a/Assembly-CSharp/RimWorld/PlaceWorker_WindTurbine.cs +++ b/Assembly-CSharp/RimWorld/PlaceWorker_WindTurbine.cs @@ -1,4 +1,3 @@ -using System; using System.Linq; using Verse; @@ -8,7 +7,7 @@ public class PlaceWorker_WindTurbine : PlaceWorker { public override void DrawGhost(ThingDef def, IntVec3 center, Rot4 rot) { - GenDraw.DrawFieldEdges(WindTurbineUtility.CalculateWindCells(center, rot, def.size).ToList()); + GenDraw.DrawFieldEdges(WindTurbineUtility.CalculateWindCells(center, rot, def.size).ToList()); } } } diff --git a/Assembly-CSharp/RimWorld/Plant.cs b/Assembly-CSharp/RimWorld/Plant.cs index aa1427350..5d628157b 100644 --- a/Assembly-CSharp/RimWorld/Plant.cs +++ b/Assembly-CSharp/RimWorld/Plant.cs @@ -1,4 +1,3 @@ -using System; using System.Text; using UnityEngine; using Verse; @@ -59,7 +58,7 @@ public virtual float Growth set { this.growthInt = value; - this.cachedLabelMouseover = null; + this.cachedLabelMouseover = (string)null; } } @@ -72,7 +71,7 @@ public virtual int Age set { this.ageInt = value; - this.cachedLabelMouseover = null; + this.cachedLabelMouseover = (string)null; } } @@ -80,7 +79,7 @@ public virtual bool HarvestableNow { get { - return this.def.plant.Harvestable && this.growthInt > this.def.plant.harvestMinGrowth; + return base.def.plant.Harvestable && this.growthInt > base.def.plant.harvestMinGrowth; } } @@ -88,7 +87,27 @@ public override bool IngestibleNow { get { - return base.IngestibleNow && (this.def.plant.IsTree || (this.growthInt >= this.def.plant.harvestMinGrowth && !this.LeaflessNow && (!base.Spawned || base.Position.GetSnowDepth(base.Map) <= this.def.hideAtSnowDepth))); + if (!base.IngestibleNow) + { + return false; + } + if (base.def.plant.IsTree) + { + return true; + } + if (this.growthInt < base.def.plant.harvestMinGrowth) + { + return false; + } + if (this.LeaflessNow) + { + return false; + } + if (base.Spawned && base.Position.GetSnowDepth(base.Map) > base.def.hideAtSnowDepth) + { + return false; + } + return true; } } @@ -96,7 +115,15 @@ public virtual bool Dying { get { - return (this.def.plant.LimitedLifespan && this.ageInt > this.def.plant.LifespanTicks) || this.unlitTicks > 450000; + if (base.def.plant.LimitedLifespan && this.ageInt > base.def.plant.LifespanTicks) + { + return true; + } + if (this.unlitTicks > 450000) + { + return true; + } + return false; } } @@ -104,7 +131,7 @@ protected virtual bool Resting { get { - return GenLocalDate.DayPercent(this) < 0.25f || GenLocalDate.DayPercent(this) > 0.8f; + return GenLocalDate.DayPercent(this) < 0.25 || GenLocalDate.DayPercent(this) > 0.800000011920929; } } @@ -120,12 +147,12 @@ protected float GrowthPerTick { get { - if (this.LifeStage != PlantLifeStage.Growing || this.Resting) + if (this.LifeStage == PlantLifeStage.Growing && !this.Resting) { - return 0f; + float num = (float)(1.0 / (60000.0 * base.def.plant.growDays)); + return num * this.GrowthRate; } - float num = 1f / (60000f * this.def.plant.growDays); - return num * this.GrowthRate; + return 0f; } } @@ -133,7 +160,7 @@ public float GrowthRateFactor_Fertility { get { - return base.Map.fertilityGrid.FertilityAt(base.Position) * this.def.plant.fertilitySensitivity + (1f - this.def.plant.fertilitySensitivity); + return (float)(base.Map.fertilityGrid.FertilityAt(base.Position) * base.def.plant.fertilitySensitivity + (1.0 - base.def.plant.fertilitySensitivity)); } } @@ -141,7 +168,7 @@ public float GrowthRateFactor_Light { get { - float value = Mathf.InverseLerp(this.def.plant.growMinGlow, this.def.plant.growOptimalGlow, base.Map.glowGrid.GameGlowAt(base.Position)); + float value = Mathf.InverseLerp(base.def.plant.growMinGlow, base.def.plant.growOptimalGlow, base.Map.glowGrid.GameGlowAt(base.Position)); return Mathf.Clamp01(value); } } @@ -150,16 +177,16 @@ public float GrowthRateFactor_Temperature { get { - float num; + float num = default(float); if (!GenTemperature.TryGetTemperatureForCell(base.Position, base.Map, out num)) { return 1f; } - if (num < 10f) + if (num < 10.0) { return Mathf.InverseLerp(0f, 10f, num); } - if (num > 42f) + if (num > 42.0) { return Mathf.InverseLerp(58f, 42f, num); } @@ -171,16 +198,16 @@ protected int TicksUntilFullyGrown { get { - if (this.growthInt > 0.9999f) + if (this.growthInt > 0.99989998340606689) { return 0; } float growthPerTick = this.GrowthPerTick; - if (growthPerTick == 0f) + if (growthPerTick == 0.0) { return 2147483647; } - return (int)((1f - this.growthInt) / growthPerTick); + return (int)((1.0 - this.growthInt) / growthPerTick); } } @@ -188,7 +215,7 @@ protected string GrowthPercentString { get { - return (this.growthInt + 0.0001f).ToStringPercent(); + return ((float)(this.growthInt + 9.9999997473787516E-05)).ToStringPercent(); } } @@ -199,11 +226,8 @@ public override string LabelMouseover if (this.cachedLabelMouseover == null) { StringBuilder stringBuilder = new StringBuilder(); - stringBuilder.Append(this.def.LabelCap); - stringBuilder.Append(" (" + "PercentGrowth".Translate(new object[] - { - this.GrowthPercentString - })); + stringBuilder.Append(base.def.LabelCap); + stringBuilder.Append(" (" + "PercentGrowth".Translate(this.GrowthPercentString)); if (this.Dying) { stringBuilder.Append(", " + "DyingLower".Translate()); @@ -219,7 +243,7 @@ protected virtual bool HasEnoughLightToGrow { get { - return this.GrowthRateFactor_Light > 0.001f; + return this.GrowthRateFactor_Light > 0.0010000000474974513; } } @@ -227,11 +251,11 @@ public virtual PlantLifeStage LifeStage { get { - if (this.growthInt < 0.001f) + if (this.growthInt < 0.0010000000474974513) { return PlantLifeStage.Sowing; } - if (this.growthInt > 0.999f) + if (this.growthInt > 0.99900001287460327) { return PlantLifeStage.Mature; } @@ -247,13 +271,13 @@ public override Graphic Graphic { return Plant.GraphicSowing; } - if (this.def.plant.leaflessGraphic != null && this.LeaflessNow && !this.HarvestableNow) + if (base.def.plant.leaflessGraphic != null && this.LeaflessNow && !this.HarvestableNow) { - return this.def.plant.leaflessGraphic; + return base.def.plant.leaflessGraphic; } - if (this.def.plant.immatureGraphic != null && !this.HarvestableNow) + if (base.def.plant.immatureGraphic != null && !this.HarvestableNow) { - return this.def.plant.immatureGraphic; + return base.def.plant.immatureGraphic; } return base.Graphic; } @@ -263,7 +287,11 @@ public bool LeaflessNow { get { - return Find.TickManager.TicksGame - this.madeLeaflessTick < 60000; + if (Find.TickManager.TicksGame - this.madeLeaflessTick < 60000) + { + return true; + } + return false; } } @@ -272,7 +300,7 @@ protected virtual float LeaflessTemperatureThresh get { float num = 8f; - return (float)this.HashOffset() * 0.01f % num - num + -2f; + return (float)((float)this.HashOffset() * 0.0099999997764825821 % num - num + -2.0); } } @@ -280,7 +308,7 @@ public bool IsCrop { get { - if (!this.def.plant.Sowable) + if (!base.def.plant.Sowable) { return false; } @@ -289,7 +317,7 @@ public bool IsCrop Log.Warning("Can't determine if crop when unspawned."); return false; } - return this.def == WorkGiver_Grower.CalculateWantedPlantDef(base.Position, base.Map); + return base.def == WorkGiver_Grower.CalculateWantedPlantDef(base.Position, base.Map); } } @@ -318,23 +346,16 @@ public override void PostMapInit() protected override void IngestedCalculateAmounts(Pawn ingester, float nutritionWanted, out int numTaken, out float nutritionIngested) { - float num = this.def.ingestible.nutrition; - if (this.def.plant.Sowable) - { - num *= this.growthInt; - } - else - { - num *= Mathf.Lerp(0.5f, 1f, this.growthInt); - } - if (this.def.plant.HarvestDestroys) + float nutrition = base.def.ingestible.nutrition; + nutrition = ((!base.def.plant.Sowable) ? (nutrition * Mathf.Lerp(0.5f, 1f, this.growthInt)) : (nutrition * this.growthInt)); + if (base.def.plant.HarvestDestroys) { numTaken = 1; } else { this.growthInt -= 0.3f; - if (this.growthInt < 0.08f) + if (this.growthInt < 0.079999998211860657) { this.growthInt = 0.08f; } @@ -344,18 +365,18 @@ protected override void IngestedCalculateAmounts(Pawn ingester, float nutritionW } numTaken = 0; } - nutritionIngested = num; + nutritionIngested = nutrition; } public virtual void PlantCollected() { - if (this.def.plant.HarvestDestroys) + if (base.def.plant.HarvestDestroys) { this.Destroy(DestroyMode.Vanish); } else { - this.growthInt = this.def.plant.harvestAfterGrowth; + this.growthInt = base.def.plant.harvestAfterGrowth; base.Map.mapDrawer.MapMeshDirty(base.Position, MapMeshFlag.Things); } } @@ -373,14 +394,11 @@ public virtual void MakeLeafless(bool causedByCold = false) bool flag = !this.LeaflessNow; Map map = base.Map; this.madeLeaflessTick = Find.TickManager.TicksGame; - if (this.def.plant.dieIfLeafless) + if (base.def.plant.dieIfLeafless) { - if (causedByCold && this.IsCrop && MessagesRepeatAvoider.MessageShowAllowed("MessagePlantDiedOfCold-" + this.def.defName, 240f)) + if (causedByCold && this.IsCrop && MessagesRepeatAvoider.MessageShowAllowed("MessagePlantDiedOfCold-" + base.def.defName, 240f)) { - Messages.Message("MessagePlantDiedOfCold".Translate(new object[] - { - this.Label - }).CapitalizeFirst(), new TargetInfo(base.Position, map, false), MessageSound.Negative); + Messages.Message("MessagePlantDiedOfCold".Translate(this.Label).CapitalizeFirst(), new TargetInfo(base.Position, map, false), MessageSound.Negative); } base.TakeDamage(new DamageInfo(DamageDefOf.Rotting, 99999, -1f, null, null, null, DamageInfo.SourceCategory.ThingOrUnknown)); } @@ -393,68 +411,79 @@ public virtual void MakeLeafless(bool causedByCold = false) public override void TickLong() { this.CheckTemperatureMakeLeafless(); - if (base.Destroyed) - { - return; - } - if (GenPlant.GrowthSeasonNow(base.Position, base.Map)) + if (!base.Destroyed) { - if (!this.HasEnoughLightToGrow) - { - this.unlitTicks += 2000; - } - else - { - this.unlitTicks = 0; - } - float num = this.growthInt; - bool flag = this.LifeStage == PlantLifeStage.Mature; - this.growthInt += this.GrowthPerTick * 2000f; - if (this.growthInt > 1f) - { - this.growthInt = 1f; - } - if (((!flag && this.LifeStage == PlantLifeStage.Mature) || (int)(num * 10f) != (int)(this.growthInt * 10f)) && this.CurrentlyCultivated()) + if (GenPlant.GrowthSeasonNow(base.Position, base.Map)) { - base.Map.mapDrawer.MapMeshDirty(base.Position, MapMeshFlag.Things); + if (!this.HasEnoughLightToGrow) + { + this.unlitTicks += 2000; + } + else + { + this.unlitTicks = 0; + } + float num = this.growthInt; + bool flag = this.LifeStage == PlantLifeStage.Mature; + this.growthInt += (float)(this.GrowthPerTick * 2000.0); + if (this.growthInt > 1.0) + { + this.growthInt = 1f; + } + if (!flag && this.LifeStage == PlantLifeStage.Mature) + { + goto IL_00c4; + } + if ((int)(num * 10.0) != (int)(this.growthInt * 10.0)) + goto IL_00c4; + goto IL_00e6; } - if (this.def.plant.LimitedLifespan) + goto IL_0249; + } + return; + IL_0249: + this.cachedLabelMouseover = (string)null; + return; + IL_00c4: + if (this.CurrentlyCultivated()) + { + base.Map.mapDrawer.MapMeshDirty(base.Position, MapMeshFlag.Things); + } + goto IL_00e6; + IL_00e6: + if (base.def.plant.LimitedLifespan) + { + this.ageInt += 2000; + if (this.Dying) { - this.ageInt += 2000; - if (this.Dying) + Map map = base.Map; + bool isCrop = this.IsCrop; + int amount = Mathf.CeilToInt(10f); + base.TakeDamage(new DamageInfo(DamageDefOf.Rotting, amount, -1f, null, null, null, DamageInfo.SourceCategory.ThingOrUnknown)); + if (base.Destroyed) { - Map map = base.Map; - bool isCrop = this.IsCrop; - int amount = Mathf.CeilToInt(10f); - base.TakeDamage(new DamageInfo(DamageDefOf.Rotting, amount, -1f, null, null, null, DamageInfo.SourceCategory.ThingOrUnknown)); - if (base.Destroyed) + if (isCrop && base.def.plant.Harvestable && MessagesRepeatAvoider.MessageShowAllowed("MessagePlantDiedOfRot-" + base.def.defName, 240f)) { - if (isCrop && this.def.plant.Harvestable && MessagesRepeatAvoider.MessageShowAllowed("MessagePlantDiedOfRot-" + this.def.defName, 240f)) - { - Messages.Message("MessagePlantDiedOfRot".Translate(new object[] - { - this.Label - }).CapitalizeFirst(), new TargetInfo(base.Position, map, false), MessageSound.Negative); - } - return; + Messages.Message("MessagePlantDiedOfRot".Translate(this.Label).CapitalizeFirst(), new TargetInfo(base.Position, map, false), MessageSound.Negative); } + return; } } - if (this.def.plant.reproduces && this.growthInt >= 0.6f && Rand.MTBEventOccurs(this.def.plant.reproduceMtbDays, 60000f, 2000f)) + } + if (base.def.plant.reproduces && this.growthInt >= 0.60000002384185791 && Rand.MTBEventOccurs(base.def.plant.reproduceMtbDays, 60000f, 2000f)) + { + if (!GenPlant.SnowAllowsPlanting(base.Position, base.Map)) { - if (!GenPlant.SnowAllowsPlanting(base.Position, base.Map)) - { - return; - } - GenPlantReproduction.TryReproduceFrom(base.Position, this.def, SeedTargFindMode.Reproduce, base.Map); + return; } + GenPlantReproduction.TryReproduceFrom(base.Position, base.def, SeedTargFindMode.Reproduce, base.Map); } - this.cachedLabelMouseover = null; + goto IL_0249; } protected virtual bool CurrentlyCultivated() { - if (!this.def.plant.Sowable) + if (!base.def.plant.Sowable) { return false; } @@ -468,7 +497,11 @@ protected virtual bool CurrentlyCultivated() return true; } Building edifice = base.Position.GetEdifice(base.Map); - return edifice != null && edifice.def.building.SupportsPlants; + if (edifice != null && edifice.def.building.SupportsPlants) + { + return true; + } + return false; } public virtual int YieldNow() @@ -477,17 +510,17 @@ public virtual int YieldNow() { return 0; } - if (this.def.plant.harvestYield <= 0f) + if (base.def.plant.harvestYield <= 0.0) { return 0; } - float num = this.def.plant.harvestYield; - float num2 = Mathf.InverseLerp(this.def.plant.harvestMinGrowth, 1f, this.growthInt); - num2 = 0.5f + num2 * 0.5f; - num *= num2; - num *= Mathf.Lerp(0.5f, 1f, (float)this.HitPoints / (float)base.MaxHitPoints); - num *= Find.Storyteller.difficulty.cropYieldFactor; - return GenMath.RoundRandom(num); + float harvestYield = base.def.plant.harvestYield; + float num = Mathf.InverseLerp(base.def.plant.harvestMinGrowth, 1f, this.growthInt); + num = (float)(0.5 + num * 0.5); + harvestYield *= num; + harvestYield *= Mathf.Lerp(0.5f, 1f, (float)this.HitPoints / (float)base.MaxHitPoints); + harvestYield *= Find.Storyteller.difficulty.cropYieldFactor; + return GenMath.RoundRandom(harvestYield); } public override void Print(SectionLayer layer) @@ -495,113 +528,102 @@ public override void Print(SectionLayer layer) Vector3 a = this.TrueCenter(); Rand.PushState(); Rand.Seed = base.Position.GetHashCode(); - float num; - if (this.def.plant.maxMeshCount == 1) - { - num = 0.05f; - } - else - { - num = 0.5f; - } - int num2 = Mathf.CeilToInt(this.growthInt * (float)this.def.plant.maxMeshCount); + float num = (float)((base.def.plant.maxMeshCount != 1) ? 0.5 : 0.05000000074505806); + int num2 = Mathf.CeilToInt(this.growthInt * (float)base.def.plant.maxMeshCount); if (num2 < 1) { num2 = 1; } int num3 = 1; - int maxMeshCount = this.def.plant.maxMeshCount; - switch (maxMeshCount) + switch (base.def.plant.maxMeshCount) { case 1: + { num3 = 1; - goto IL_F8; - case 2: - case 3: - IL_9B: - if (maxMeshCount == 9) - { - num3 = 3; - goto IL_F8; - } - if (maxMeshCount == 16) - { - num3 = 4; - goto IL_F8; - } - if (maxMeshCount != 25) - { - Log.Error(this.def + " must have plant.MaxMeshCount that is a perfect square."); - goto IL_F8; - } - num3 = 5; - goto IL_F8; + break; + } case 4: + { num3 = 2; - goto IL_F8; + break; + } + case 9: + { + num3 = 3; + break; + } + case 16: + { + num3 = 4; + break; + } + case 25: + { + num3 = 5; + break; + } + default: + { + Log.Error(base.def + " must have plant.MaxMeshCount that is a perfect square."); + break; + } } - goto IL_9B; - IL_F8: - float num4 = 1f / (float)num3; + float num4 = (float)(1.0 / (float)num3); Vector3 vector = Vector3.zero; - Vector2 zero = Vector2.zero; + Vector2 size = Vector2.zero; int num5 = 0; int[] positionIndices = PlantPosIndices.GetPositionIndices(this); - for (int i = 0; i < positionIndices.Length; i++) + int num6 = 0; + while (num6 < positionIndices.Length) { - int num6 = positionIndices[i]; - float num7 = this.def.plant.visualSizeRange.LerpThroughRange(this.growthInt); - if (this.def.plant.maxMeshCount == 1) + int num7 = positionIndices[num6]; + float num8 = base.def.plant.visualSizeRange.LerpThroughRange(this.growthInt); + if (base.def.plant.maxMeshCount == 1) { - vector = a + new Vector3(Rand.Range(-num, num), 0f, Rand.Range(-num, num)); - float num8 = Mathf.Floor(a.z); - if (vector.z - num7 / 2f < num8) + vector = a + new Vector3(Rand.Range((float)(0.0 - num), num), 0f, Rand.Range((float)(0.0 - num), num)); + float num9 = Mathf.Floor(a.z); + if (vector.z - num8 / 2.0 < num9) { - vector.z = num8 + num7 / 2f; + vector.z = (float)(num9 + num8 / 2.0); } } else { vector = base.Position.ToVector3(); - vector.y = this.def.Altitude; - vector.x += 0.5f * num4; - vector.z += 0.5f * num4; - int num9 = num6 / num3; - int num10 = num6 % num3; - vector.x += (float)num9 * num4; - vector.z += (float)num10 * num4; - float num11 = num4 * 0.3f; - vector += new Vector3(Rand.Range(-num11, num11), 0f, Rand.Range(-num11, num11)); - } - bool flag = Rand.Value < 0.5f; + vector.y = base.def.Altitude; + vector.x += (float)(0.5 * num4); + vector.z += (float)(0.5 * num4); + int num10 = num7 / num3; + int num11 = num7 % num3; + vector.x += (float)num10 * num4; + vector.z += (float)num11 * num4; + float num12 = (float)(num4 * 0.30000001192092896); + vector += new Vector3(Rand.Range((float)(0.0 - num12), num12), 0f, Rand.Range((float)(0.0 - num12), num12)); + } + bool flag = Rand.Value < 0.5; Material matSingle = this.Graphic.MatSingle; - Plant.workingColors[1].a = (Plant.workingColors[2].a = (byte)(255f * this.def.plant.topWindExposure)); - Plant.workingColors[0].a = (Plant.workingColors[3].a = 0); - num7 *= this.def.graphicData.drawSize.x; - zero = new Vector2(num7, num7); + Plant.workingColors[1].a = (Plant.workingColors[2].a = (byte)(255.0 * base.def.plant.topWindExposure)); + Plant.workingColors[0].a = (Plant.workingColors[3].a = (byte)0); + num8 *= base.def.graphicData.drawSize.x; + size = new Vector2(num8, num8); bool flipUv = flag; - Printer_Plane.PrintPlane(layer, vector, zero, matSingle, 0f, flipUv, null, Plant.workingColors, 0.1f); + Printer_Plane.PrintPlane(layer, vector, size, matSingle, 0f, flipUv, null, Plant.workingColors, 0.1f); num5++; - if (num5 >= num2) + if (num5 < num2) { - break; + num6++; + continue; } + break; } - if (this.def.graphicData.shadowData != null) + if (base.def.graphicData.shadowData != null) { - float num12; - if (zero.y < 1f) - { - num12 = 0.6f; - } - else - { - num12 = 0.81f; - } + float num13 = 0.85f; + num13 = (float)((!(size.y < 1.0)) ? 0.81000000238418579 : 0.60000002384185791); Vector3 center = vector; - center.z -= zero.y / 2f * num12; + center.z -= (float)(size.y / 2.0 * num13); center.y -= 0.046875f; - Printer_Shadow.PrintShadow(layer, center, this.def.graphicData.shadowData, Rot4.North); + Printer_Shadow.PrintShadow(layer, center, base.def.graphicData.shadowData, Rot4.North); } Rand.PopState(); } @@ -612,10 +634,7 @@ public override string GetInspectString() stringBuilder.Append(base.GetInspectString()); if (this.LifeStage == PlantLifeStage.Growing) { - stringBuilder.AppendLine("PercentGrowth".Translate(new object[] - { - this.GrowthPercentString - })); + stringBuilder.AppendLine("PercentGrowth".Translate(this.GrowthPercentString)); stringBuilder.AppendLine("GrowthRate".Translate() + ": " + this.GrowthRate.ToStringPercent()); if (this.Resting) { @@ -623,27 +642,24 @@ public override string GetInspectString() } if (!this.HasEnoughLightToGrow) { - stringBuilder.AppendLine("PlantNeedsLightLevel".Translate() + ": " + this.def.plant.growMinGlow.ToStringPercent()); + stringBuilder.AppendLine("PlantNeedsLightLevel".Translate() + ": " + base.def.plant.growMinGlow.ToStringPercent()); } float growthRateFactor_Temperature = this.GrowthRateFactor_Temperature; - if (growthRateFactor_Temperature < 0.99f) + if (growthRateFactor_Temperature < 0.99000000953674316) { - if (growthRateFactor_Temperature < 0.01f) + if (growthRateFactor_Temperature < 0.0099999997764825821) { stringBuilder.AppendLine("OutOfIdealTemperatureRangeNotGrowing".Translate()); } else { - stringBuilder.AppendLine("OutOfIdealTemperatureRange".Translate(new object[] - { - Mathf.RoundToInt(growthRateFactor_Temperature * 100f).ToString() - })); + stringBuilder.AppendLine("OutOfIdealTemperatureRange".Translate(Mathf.RoundToInt((float)(growthRateFactor_Temperature * 100.0)).ToString())); } } } else if (this.LifeStage == PlantLifeStage.Mature) { - if (this.def.plant.Harvestable) + if (base.def.plant.Harvestable) { stringBuilder.AppendLine("ReadyToHarvest".Translate()); } @@ -657,7 +673,7 @@ public override string GetInspectString() public virtual void CropBlighted() { - if (Rand.Value < 0.85f) + if (Rand.Value < 0.85000002384185791) { this.Destroy(DestroyMode.Vanish); } diff --git a/Assembly-CSharp/RimWorld/PlantBiomeRecord.cs b/Assembly-CSharp/RimWorld/PlantBiomeRecord.cs index 291a59f5a..066525a25 100644 --- a/Assembly-CSharp/RimWorld/PlantBiomeRecord.cs +++ b/Assembly-CSharp/RimWorld/PlantBiomeRecord.cs @@ -1,4 +1,3 @@ -using System; using System.Xml; using Verse; diff --git a/Assembly-CSharp/RimWorld/PlantLifeStage.cs b/Assembly-CSharp/RimWorld/PlantLifeStage.cs index 13391a460..85c176ac0 100644 --- a/Assembly-CSharp/RimWorld/PlantLifeStage.cs +++ b/Assembly-CSharp/RimWorld/PlantLifeStage.cs @@ -1,11 +1,9 @@ -using System; - namespace RimWorld { public enum PlantLifeStage : byte { - Sowing, - Growing, - Mature + Sowing = 0, + Growing = 1, + Mature = 2 } } diff --git a/Assembly-CSharp/RimWorld/PlantPosIndices.cs b/Assembly-CSharp/RimWorld/PlantPosIndices.cs index 69311bac1..2986c0cd1 100644 --- a/Assembly-CSharp/RimWorld/PlantPosIndices.cs +++ b/Assembly-CSharp/RimWorld/PlantPosIndices.cs @@ -1,4 +1,3 @@ -using System; using Verse; namespace RimWorld @@ -18,11 +17,11 @@ static PlantPosIndices() for (int j = 0; j < 8; j++) { int[] array = new int[i + 1]; - for (int k = 0; k < i; k++) + for (int num = 0; num < i; num++) { - array[k] = k; + array[num] = num; } - array.Shuffle(); + array.Shuffle(); PlantPosIndices.rootList[i][j] = array; } } diff --git a/Assembly-CSharp/RimWorld/PlantProperties.cs b/Assembly-CSharp/RimWorld/PlantProperties.cs index 7f0320ca3..10c73ddf5 100644 --- a/Assembly-CSharp/RimWorld/PlantProperties.cs +++ b/Assembly-CSharp/RimWorld/PlantProperties.cs @@ -1,6 +1,5 @@ using System; using System.Collections.Generic; -using System.Diagnostics; using Verse; namespace RimWorld @@ -85,7 +84,7 @@ public bool Sowable { get { - return !this.sowTags.NullOrEmpty(); + return !this.sowTags.NullOrEmpty(); } } @@ -93,7 +92,7 @@ public bool Harvestable { get { - return this.harvestYield > 0.001f; + return this.harvestYield > 0.0010000000474974513; } } @@ -101,7 +100,7 @@ public bool HarvestDestroys { get { - return this.harvestAfterGrowth <= 0f; + return this.harvestAfterGrowth <= 0.0; } } @@ -109,7 +108,7 @@ public float WildClusterRadiusActual { get { - if (this.wildClusterRadius > 0f) + if (this.wildClusterRadius > 0.0) { return this.wildClusterRadius; } @@ -137,7 +136,7 @@ public int LifespanTicks { get { - return (int)(this.LifespanDays * 60000f); + return (int)(this.LifespanDays * 60000.0); } } @@ -145,7 +144,7 @@ public bool LimitedLifespan { get { - return this.lifespanFraction > 0f; + return this.lifespanFraction > 0.0; } } @@ -153,38 +152,66 @@ public void PostLoadSpecial(ThingDef parentDef) { if (!this.leaflessGraphicPath.NullOrEmpty()) { - LongEventHandler.ExecuteWhenFinished(delegate + LongEventHandler.ExecuteWhenFinished((Action)delegate() { this.leaflessGraphic = GraphicDatabase.Get(parentDef.graphicData.graphicClass, this.leaflessGraphicPath, parentDef.graphic.Shader, parentDef.graphicData.drawSize, parentDef.graphicData.color, parentDef.graphicData.colorTwo); }); } if (!this.immatureGraphicPath.NullOrEmpty()) { - LongEventHandler.ExecuteWhenFinished(delegate + LongEventHandler.ExecuteWhenFinished((Action)delegate() { this.immatureGraphic = GraphicDatabase.Get(parentDef.graphicData.graphicClass, this.immatureGraphicPath, parentDef.graphic.Shader, parentDef.graphicData.drawSize, parentDef.graphicData.color, parentDef.graphicData.colorTwo); }); } } - [DebuggerHidden] public IEnumerable ConfigErrors() { - PlantProperties.c__Iterator83 c__Iterator = new PlantProperties.c__Iterator83(); - c__Iterator.<>f__this = this; - PlantProperties.c__Iterator83 expr_0E = c__Iterator; - expr_0E.$PC = -2; - return expr_0E; + if (this.maxMeshCount > 25) + { + yield return "maxMeshCount > MaxMaxMeshCount"; + } } - [DebuggerHidden] internal IEnumerable SpecialDisplayStats() { - PlantProperties.c__Iterator84 c__Iterator = new PlantProperties.c__Iterator84(); - c__Iterator.<>f__this = this; - PlantProperties.c__Iterator84 expr_0E = c__Iterator; - expr_0E.$PC = -2; - return expr_0E; + if (this.sowMinSkill > 0) + { + yield return new StatDrawEntry(StatCategoryDefOf.Basics, "MinGrowingSkillToSow".Translate(), this.sowMinSkill.ToString(), 0); + } + string attributes = string.Empty; + if (this.Harvestable) + { + if (!attributes.NullOrEmpty()) + { + attributes += ", "; + } + attributes += "Harvestable".Translate(); + } + if (this.LimitedLifespan) + { + if (!attributes.NullOrEmpty()) + { + attributes += ", "; + } + attributes += "LimitedLifespan".Translate(); + } + yield return new StatDrawEntry(StatCategoryDefOf.Basics, "GrowingTime".Translate(), this.growDays.ToString("0.##") + " " + "Days".Translate(), 0) + { + overrideReportText = "GrowingTimeDesc".Translate() + }; + yield return new StatDrawEntry(StatCategoryDefOf.Basics, "FertilityRequirement".Translate(), this.fertilityMin.ToStringPercent(), 0); + yield return new StatDrawEntry(StatCategoryDefOf.Basics, "FertilitySensitivity".Translate(), this.fertilitySensitivity.ToStringPercent(), 0); + yield return new StatDrawEntry(StatCategoryDefOf.Basics, "LightRequirement".Translate(), this.growMinGlow.ToStringPercent(), 0); + if (!attributes.NullOrEmpty()) + { + yield return new StatDrawEntry(StatCategoryDefOf.Basics, "Attributes".Translate(), attributes, 0); + } + if (this.LimitedLifespan) + { + yield return new StatDrawEntry(StatCategoryDefOf.Basics, "LifeSpan".Translate(), this.LifespanDays.ToString("0.##") + " " + "Days".Translate(), 0); + } } } } diff --git a/Assembly-CSharp/RimWorld/PlantToGrowSettableUtility.cs b/Assembly-CSharp/RimWorld/PlantToGrowSettableUtility.cs index 3fa0434f9..28b302869 100644 --- a/Assembly-CSharp/RimWorld/PlantToGrowSettableUtility.cs +++ b/Assembly-CSharp/RimWorld/PlantToGrowSettableUtility.cs @@ -1,4 +1,3 @@ -using System; using Verse; namespace RimWorld @@ -7,12 +6,11 @@ public static class PlantToGrowSettableUtility { public static Command_SetPlantToGrow SetPlantToGrowCommand(IPlantToGrowSettable settable) { - return new Command_SetPlantToGrow - { - defaultDesc = "CommandSelectPlantToGrowDesc".Translate(), - hotKey = KeyBindingDefOf.Misc1, - settable = settable - }; + Command_SetPlantToGrow command_SetPlantToGrow = new Command_SetPlantToGrow(); + command_SetPlantToGrow.defaultDesc = "CommandSelectPlantToGrowDesc".Translate(); + command_SetPlantToGrow.hotKey = KeyBindingDefOf.Misc1; + command_SetPlantToGrow.settable = settable; + return command_SetPlantToGrow; } } } diff --git a/Assembly-CSharp/RimWorld/PlaySettings.cs b/Assembly-CSharp/RimWorld/PlaySettings.cs index e692349c4..c7c2216f5 100644 --- a/Assembly-CSharp/RimWorld/PlaySettings.cs +++ b/Assembly-CSharp/RimWorld/PlaySettings.cs @@ -1,4 +1,3 @@ -using System; using Verse; namespace RimWorld @@ -46,31 +45,31 @@ public void DoPlaySettingsGlobalControls(WidgetRow row, bool worldView) { if (Current.ProgramState == ProgramState.Playing) { - row.ToggleableIcon(ref this.showColonistBar, TexButton.ShowColonistBar, "ShowColonistBarToggleButton".Translate(), SoundDefOf.MouseoverToggle, null); + row.ToggleableIcon(ref this.showColonistBar, TexButton.ShowColonistBar, "ShowColonistBarToggleButton".Translate(), SoundDefOf.MouseoverToggle, (string)null); } bool flag2 = this.lockNorthUp; - row.ToggleableIcon(ref this.lockNorthUp, TexButton.LockNorthUp, "LockNorthUpToggleButton".Translate(), SoundDefOf.MouseoverToggle, null); + row.ToggleableIcon(ref this.lockNorthUp, TexButton.LockNorthUp, "LockNorthUpToggleButton".Translate(), SoundDefOf.MouseoverToggle, (string)null); if (flag2 != this.lockNorthUp && this.lockNorthUp) { Find.WorldCameraDriver.RotateSoNorthIsUp(true); } - row.ToggleableIcon(ref this.usePlanetDayNightSystem, TexButton.UsePlanetDayNightSystem, "UsePlanetDayNightSystemToggleButton".Translate(), SoundDefOf.MouseoverToggle, null); - row.ToggleableIcon(ref this.expandingIcons, TexButton.ExpandingIcons, "ExpandingIconsToggleButton".Translate(), SoundDefOf.MouseoverToggle, null); + row.ToggleableIcon(ref this.usePlanetDayNightSystem, TexButton.UsePlanetDayNightSystem, "UsePlanetDayNightSystemToggleButton".Translate(), SoundDefOf.MouseoverToggle, (string)null); + row.ToggleableIcon(ref this.expandingIcons, TexButton.ExpandingIcons, "ExpandingIconsToggleButton".Translate(), SoundDefOf.MouseoverToggle, (string)null); } else { - row.ToggleableIcon(ref this.showLearningHelper, TexButton.ShowLearningHelper, "ShowLearningHelperWhenEmptyToggleButton".Translate(), SoundDefOf.MouseoverToggle, null); - row.ToggleableIcon(ref this.showZones, TexButton.ShowZones, "ZoneVisibilityToggleButton".Translate(), SoundDefOf.MouseoverToggle, null); + row.ToggleableIcon(ref this.showLearningHelper, TexButton.ShowLearningHelper, "ShowLearningHelperWhenEmptyToggleButton".Translate(), SoundDefOf.MouseoverToggle, (string)null); + row.ToggleableIcon(ref this.showZones, TexButton.ShowZones, "ZoneVisibilityToggleButton".Translate(), SoundDefOf.MouseoverToggle, (string)null); row.ToggleableIcon(ref this.showEnvironment, TexButton.ShowEnvironment, "ShowEnvironmentToggleButton".Translate(), SoundDefOf.MouseoverToggle, "InspectRoomStats"); - row.ToggleableIcon(ref this.showColonistBar, TexButton.ShowColonistBar, "ShowColonistBarToggleButton".Translate(), SoundDefOf.MouseoverToggle, null); - row.ToggleableIcon(ref this.showRoofOverlay, TexButton.ShowRoofOverlay, "ShowRoofOverlayToggleButton".Translate(), SoundDefOf.MouseoverToggle, null); - row.ToggleableIcon(ref this.autoHomeArea, TexButton.AutoHomeArea, "AutoHomeAreaToggleButton".Translate(), SoundDefOf.MouseoverToggle, null); - bool resourceReadoutCategorized = Prefs.ResourceReadoutCategorized; - bool flag3 = resourceReadoutCategorized; - row.ToggleableIcon(ref resourceReadoutCategorized, TexButton.CategorizedResourceReadout, "CategorizedResourceReadoutToggleButton".Translate(), SoundDefOf.MouseoverToggle, null); - if (resourceReadoutCategorized != flag3) + row.ToggleableIcon(ref this.showColonistBar, TexButton.ShowColonistBar, "ShowColonistBarToggleButton".Translate(), SoundDefOf.MouseoverToggle, (string)null); + row.ToggleableIcon(ref this.showRoofOverlay, TexButton.ShowRoofOverlay, "ShowRoofOverlayToggleButton".Translate(), SoundDefOf.MouseoverToggle, (string)null); + row.ToggleableIcon(ref this.autoHomeArea, TexButton.AutoHomeArea, "AutoHomeAreaToggleButton".Translate(), SoundDefOf.MouseoverToggle, (string)null); + bool resourceReadoutCategorized; + bool flag3 = resourceReadoutCategorized = Prefs.ResourceReadoutCategorized; + row.ToggleableIcon(ref flag3, TexButton.CategorizedResourceReadout, "CategorizedResourceReadoutToggleButton".Translate(), SoundDefOf.MouseoverToggle, (string)null); + if (flag3 != resourceReadoutCategorized) { - Prefs.ResourceReadoutCategorized = resourceReadoutCategorized; + Prefs.ResourceReadoutCategorized = flag3; } } if (flag != this.showColonistBar) diff --git a/Assembly-CSharp/RimWorld/PlayerKnowledgeDatabase.cs b/Assembly-CSharp/RimWorld/PlayerKnowledgeDatabase.cs index 34f183f00..13c089711 100644 --- a/Assembly-CSharp/RimWorld/PlayerKnowledgeDatabase.cs +++ b/Assembly-CSharp/RimWorld/PlayerKnowledgeDatabase.cs @@ -15,14 +15,14 @@ private class ConceptKnowledge public ConceptKnowledge() { - foreach (ConceptDef current in DefDatabase.AllDefs) + foreach (ConceptDef allDef in DefDatabase.AllDefs) { - this.knowledge.Add(current, 0f); + this.knowledge.Add(allDef, 0f); } } } - private static PlayerKnowledgeDatabase.ConceptKnowledge data; + private static ConceptKnowledge data; static PlayerKnowledgeDatabase() { @@ -31,13 +31,13 @@ static PlayerKnowledgeDatabase() public static void ReloadAndRebind() { - PlayerKnowledgeDatabase.data = DirectXmlLoader.ItemFromXmlFile(GenFilePaths.ConceptKnowledgeFilePath, true); - foreach (ConceptDef current in DefDatabase.AllDefs) + PlayerKnowledgeDatabase.data = DirectXmlLoader.ItemFromXmlFile(GenFilePaths.ConceptKnowledgeFilePath, true); + foreach (ConceptDef allDef in DefDatabase.AllDefs) { - if (!PlayerKnowledgeDatabase.data.knowledge.ContainsKey(current)) + if (!PlayerKnowledgeDatabase.data.knowledge.ContainsKey(allDef)) { - Log.Warning("Knowledge data was missing key " + current + ". Adding it..."); - PlayerKnowledgeDatabase.data.knowledge.Add(current, 0f); + Log.Warning("Knowledge data was missing key " + allDef + ". Adding it..."); + PlayerKnowledgeDatabase.data.knowledge.Add(allDef, 0f); } } } @@ -49,7 +49,7 @@ public static void ResetPersistent() { fileInfo.Delete(); } - PlayerKnowledgeDatabase.data = new PlayerKnowledgeDatabase.ConceptKnowledge(); + PlayerKnowledgeDatabase.data = new ConceptKnowledge(); } public static void Save() @@ -57,17 +57,13 @@ public static void Save() try { XDocument xDocument = new XDocument(); - XElement content = DirectXmlSaver.XElementFromObject(PlayerKnowledgeDatabase.data, typeof(PlayerKnowledgeDatabase.ConceptKnowledge)); + XElement content = DirectXmlSaver.XElementFromObject(PlayerKnowledgeDatabase.data, typeof(ConceptKnowledge)); xDocument.Add(content); xDocument.Save(GenFilePaths.ConceptKnowledgeFilePath); } catch (Exception ex) { - GenUI.ErrorDialog("ProblemSavingFile".Translate(new object[] - { - GenFilePaths.ConceptKnowledgeFilePath, - ex.ToString() - })); + GenUI.ErrorDialog("ProblemSavingFile".Translate(GenFilePaths.ConceptKnowledgeFilePath, ex.ToString())); Log.Error("Exception saving knowledge database: " + ex); } } @@ -82,7 +78,7 @@ public static void SetKnowledge(ConceptDef def, float value) float num = PlayerKnowledgeDatabase.data.knowledge[def]; float num2 = Mathf.Clamp01(value); PlayerKnowledgeDatabase.data.knowledge[def] = num2; - if (num < 0.999f && num2 >= 0.999f) + if (num < 0.99900001287460327 && num2 >= 0.99900001287460327) { PlayerKnowledgeDatabase.NewlyLearned(def); } @@ -90,7 +86,7 @@ public static void SetKnowledge(ConceptDef def, float value) public static bool IsComplete(ConceptDef conc) { - return PlayerKnowledgeDatabase.data.knowledge[conc] > 0.999f; + return PlayerKnowledgeDatabase.data.knowledge[conc] > 0.99900001287460327; } private static void NewlyLearned(ConceptDef conc) @@ -108,32 +104,50 @@ public static void KnowledgeDemonstrated(ConceptDef conc, KnowledgeAmount know) switch (know) { case KnowledgeAmount.FrameDisplayed: + { num = 0.002f; break; + } case KnowledgeAmount.FrameInteraction: + { num = 0.008f; break; + } case KnowledgeAmount.TinyInteraction: + { num = 0.03f; break; + } case KnowledgeAmount.SmallInteraction: + { num = 0.1f; break; + } case KnowledgeAmount.SpecificInteraction: + { num = 0.4f; break; + } case KnowledgeAmount.Total: + { num = 1f; break; + } case KnowledgeAmount.NoteClosed: + { num = 0.5f; break; + } case KnowledgeAmount.NoteTaught: + { num = 1f; break; + } default: + { throw new NotImplementedException(); } + } PlayerKnowledgeDatabase.SetKnowledge(conc, PlayerKnowledgeDatabase.GetKnowledge(conc) + num); LessonAutoActivator.Notify_KnowledgeDemonstrated(conc); if (Find.ActiveLesson != null) diff --git a/Assembly-CSharp/RimWorld/PlayerPawnsArriveMethod.cs b/Assembly-CSharp/RimWorld/PlayerPawnsArriveMethod.cs index eafe01830..d6981a421 100644 --- a/Assembly-CSharp/RimWorld/PlayerPawnsArriveMethod.cs +++ b/Assembly-CSharp/RimWorld/PlayerPawnsArriveMethod.cs @@ -1,10 +1,8 @@ -using System; - namespace RimWorld { public enum PlayerPawnsArriveMethod { - Standing, - DropPods + Standing = 0, + DropPods = 1 } } diff --git a/Assembly-CSharp/RimWorld/PlayerPawnsArriveMethodExtension.cs b/Assembly-CSharp/RimWorld/PlayerPawnsArriveMethodExtension.cs index 351b8198a..4e561a67a 100644 --- a/Assembly-CSharp/RimWorld/PlayerPawnsArriveMethodExtension.cs +++ b/Assembly-CSharp/RimWorld/PlayerPawnsArriveMethodExtension.cs @@ -7,15 +7,21 @@ public static class PlayerPawnsArriveMethodExtension { public static string ToStringHuman(this PlayerPawnsArriveMethod method) { - if (method == PlayerPawnsArriveMethod.Standing) + switch (method) + { + case PlayerPawnsArriveMethod.Standing: { return "PlayerPawnsArriveMethod_Standing".Translate(); } - if (method != PlayerPawnsArriveMethod.DropPods) + case PlayerPawnsArriveMethod.DropPods: + { + return "PlayerPawnsArriveMethod_DropPods".Translate(); + } + default: { throw new NotImplementedException(); } - return "PlayerPawnsArriveMethod_DropPods".Translate(); + } } } } diff --git a/Assembly-CSharp/RimWorld/PodContentsType.cs b/Assembly-CSharp/RimWorld/PodContentsType.cs index e020173d4..55947d3dc 100644 --- a/Assembly-CSharp/RimWorld/PodContentsType.cs +++ b/Assembly-CSharp/RimWorld/PodContentsType.cs @@ -1,14 +1,12 @@ -using System; - namespace RimWorld { public enum PodContentsType { - Empty, - SpacerFriendly, - SpacerIncapped, - SpacerHalfEaten, - SpacerHostile, - Slave + Empty = 0, + SpacerFriendly = 1, + SpacerIncapped = 2, + SpacerHalfEaten = 3, + SpacerHostile = 4, + Slave = 5 } } diff --git a/Assembly-CSharp/RimWorld/PortraitCameraManager.cs b/Assembly-CSharp/RimWorld/PortraitCameraManager.cs index 9c9a4361e..7e811d076 100644 --- a/Assembly-CSharp/RimWorld/PortraitCameraManager.cs +++ b/Assembly-CSharp/RimWorld/PortraitCameraManager.cs @@ -1,4 +1,3 @@ -using System; using UnityEngine; using Verse; @@ -29,18 +28,15 @@ public static PortraitRenderer PortraitRenderer static PortraitCameraManager() { PortraitCameraManager.portraitCameraInt = PortraitCameraManager.CreatePortraitCamera(); - PortraitCameraManager.portraitRendererInt = PortraitCameraManager.portraitCameraInt.GetComponent(); + PortraitCameraManager.portraitRendererInt = ((Component)PortraitCameraManager.portraitCameraInt).GetComponent(); } private static Camera CreatePortraitCamera() { - GameObject gameObject = new GameObject("PortraitCamera", new Type[] - { - typeof(Camera) - }); + GameObject gameObject = new GameObject("PortraitCamera", typeof(Camera)); gameObject.SetActive(false); gameObject.AddComponent(); - UnityEngine.Object.DontDestroyOnLoad(gameObject); + Object.DontDestroyOnLoad(gameObject); Camera component = gameObject.GetComponent(); component.transform.position = new Vector3(0f, 15f, 0f); component.transform.rotation = Quaternion.Euler(90f, 0f, 0f); diff --git a/Assembly-CSharp/RimWorld/PortraitRenderer.cs b/Assembly-CSharp/RimWorld/PortraitRenderer.cs index 3cd0af6ba..597272528 100644 --- a/Assembly-CSharp/RimWorld/PortraitRenderer.cs +++ b/Assembly-CSharp/RimWorld/PortraitRenderer.cs @@ -1,4 +1,3 @@ -using System; using UnityEngine; using Verse; @@ -14,8 +13,9 @@ public void RenderPortrait(Pawn pawn, RenderTexture renderTexture, Vector3 camer portraitCamera.targetTexture = renderTexture; Vector3 position = portraitCamera.transform.position; float orthographicSize = portraitCamera.orthographicSize; - portraitCamera.transform.position += cameraOffset; - portraitCamera.orthographicSize = 1f / cameraZoom; + Transform transform = portraitCamera.transform; + transform.position += cameraOffset; + portraitCamera.orthographicSize = (float)(1.0 / cameraZoom); this.pawn = pawn; portraitCamera.Render(); portraitCamera.transform.position = position; diff --git a/Assembly-CSharp/RimWorld/PortraitsCache.cs b/Assembly-CSharp/RimWorld/PortraitsCache.cs index a826712ef..47e2286b1 100644 --- a/Assembly-CSharp/RimWorld/PortraitsCache.cs +++ b/Assembly-CSharp/RimWorld/PortraitsCache.cs @@ -36,7 +36,7 @@ public bool Expired { get { - return Time.time - this.LastUseTime > 1f; + return Time.time - this.LastUseTime > 1.0; } } @@ -51,7 +51,7 @@ public CachedPortrait(RenderTexture renderTexture, bool dirty, float lastUseTime [StructLayout(LayoutKind.Sequential, Size = 1)] private struct CachedPortraitsWithParams { - public Dictionary CachedPortraits + public Dictionary CachedPortraits { get; private set; @@ -77,7 +77,7 @@ public float CameraZoom public CachedPortraitsWithParams(Vector2 size, Vector3 cameraOffset, float cameraZoom) { - this.CachedPortraits = new Dictionary(); + this.CachedPortraits = new Dictionary(); this.Size = size; this.CameraOffset = cameraOffset; this.CameraZoom = cameraZoom; @@ -86,7 +86,7 @@ public CachedPortraitsWithParams(Vector2 size, Vector3 cameraOffset, float camer private static List renderTexturesPool = new List(); - private static List cachedPortraits = new List(); + private static List cachedPortraits = new List(); private static List toRemove = new List(); @@ -94,8 +94,8 @@ public CachedPortraitsWithParams(Vector2 size, Vector3 cameraOffset, float camer public static RenderTexture Get(Pawn pawn, Vector2 size, Vector3 cameraOffset = default(Vector3), float cameraZoom = 1f) { - Dictionary dictionary = PortraitsCache.GetOrCreateCachedPortraitsWithParams(size, cameraOffset, cameraZoom).CachedPortraits; - PortraitsCache.CachedPortrait cachedPortrait; + Dictionary dictionary = PortraitsCache.GetOrCreateCachedPortraitsWithParams(size, cameraOffset, cameraZoom).CachedPortraits; + CachedPortrait cachedPortrait = default(CachedPortrait); if (dictionary.TryGetValue(pawn, out cachedPortrait)) { if (!cachedPortrait.RenderTexture.IsCreated()) @@ -108,12 +108,12 @@ public CachedPortraitsWithParams(Vector2 size, Vector3 cameraOffset, float camer PortraitsCache.RenderPortrait(pawn, cachedPortrait.RenderTexture, cameraOffset, cameraZoom); } dictionary.Remove(pawn); - dictionary.Add(pawn, new PortraitsCache.CachedPortrait(cachedPortrait.RenderTexture, false, Time.time)); + dictionary.Add(pawn, new CachedPortrait(cachedPortrait.RenderTexture, false, Time.time)); return cachedPortrait.RenderTexture; } RenderTexture renderTexture = PortraitsCache.NewRenderTexture(size); PortraitsCache.RenderPortrait(pawn, renderTexture, cameraOffset, cameraZoom); - dictionary.Add(pawn, new PortraitsCache.CachedPortrait(renderTexture, false, Time.time)); + dictionary.Add(pawn, new CachedPortrait(renderTexture, false, Time.time)); return renderTexture; } @@ -121,12 +121,12 @@ public static void SetDirty(Pawn pawn) { for (int i = 0; i < PortraitsCache.cachedPortraits.Count; i++) { - Dictionary dictionary = PortraitsCache.cachedPortraits[i].CachedPortraits; - PortraitsCache.CachedPortrait cachedPortrait; + Dictionary dictionary = PortraitsCache.cachedPortraits[i].CachedPortraits; + CachedPortrait cachedPortrait = default(CachedPortrait); if (dictionary.TryGetValue(pawn, out cachedPortrait) && !cachedPortrait.Dirty) { dictionary.Remove(pawn); - dictionary.Add(pawn, new PortraitsCache.CachedPortrait(cachedPortrait.RenderTexture, true, cachedPortrait.LastUseTime)); + dictionary.Add(pawn, new CachedPortrait(cachedPortrait.RenderTexture, true, cachedPortrait.LastUseTime)); } } } @@ -141,9 +141,17 @@ public static void Clear() { for (int i = 0; i < PortraitsCache.cachedPortraits.Count; i++) { - foreach (KeyValuePair current in PortraitsCache.cachedPortraits[i].CachedPortraits) + Dictionary.Enumerator enumerator = PortraitsCache.cachedPortraits[i].CachedPortraits.GetEnumerator(); + try { - PortraitsCache.DestroyRenderTexture(current.Value.RenderTexture); + while (enumerator.MoveNext()) + { + PortraitsCache.DestroyRenderTexture(enumerator.Current.Value.RenderTexture); + } + } + finally + { + ((IDisposable)(object)enumerator).Dispose(); } } PortraitsCache.cachedPortraits.Clear(); @@ -154,7 +162,7 @@ public static void Clear() PortraitsCache.renderTexturesPool.Clear(); } - private static PortraitsCache.CachedPortraitsWithParams GetOrCreateCachedPortraitsWithParams(Vector2 size, Vector3 cameraOffset, float cameraZoom) + private static CachedPortraitsWithParams GetOrCreateCachedPortraitsWithParams(Vector2 size, Vector3 cameraOffset, float cameraZoom) { for (int i = 0; i < PortraitsCache.cachedPortraits.Count; i++) { @@ -163,7 +171,7 @@ private static PortraitsCache.CachedPortraitsWithParams GetOrCreateCachedPortrai return PortraitsCache.cachedPortraits[i]; } } - PortraitsCache.CachedPortraitsWithParams cachedPortraitsWithParams = new PortraitsCache.CachedPortraitsWithParams(size, cameraOffset, cameraZoom); + CachedPortraitsWithParams cachedPortraitsWithParams = new CachedPortraitsWithParams(size, cameraOffset, cameraZoom); PortraitsCache.cachedPortraits.Add(cachedPortraitsWithParams); return cachedPortraitsWithParams; } @@ -178,16 +186,25 @@ private static void RemoveExpiredCachedPortraits() { for (int i = 0; i < PortraitsCache.cachedPortraits.Count; i++) { - Dictionary dictionary = PortraitsCache.cachedPortraits[i].CachedPortraits; + Dictionary dictionary = PortraitsCache.cachedPortraits[i].CachedPortraits; PortraitsCache.toRemove.Clear(); - foreach (KeyValuePair current in dictionary) + Dictionary.Enumerator enumerator = dictionary.GetEnumerator(); + try { - if (current.Value.Expired) + while (enumerator.MoveNext()) { - PortraitsCache.toRemove.Add(current.Key); - PortraitsCache.renderTexturesPool.Add(current.Value.RenderTexture); + KeyValuePair current = enumerator.Current; + if (current.Value.Expired) + { + PortraitsCache.toRemove.Add(current.Key); + PortraitsCache.renderTexturesPool.Add(current.Value.RenderTexture); + } } } + finally + { + ((IDisposable)(object)enumerator).Dispose(); + } for (int j = 0; j < PortraitsCache.toRemove.Count; j++) { dictionary.Remove(PortraitsCache.toRemove[j]); @@ -200,20 +217,29 @@ private static void SetAnimatedPortraitsDirty() { for (int i = 0; i < PortraitsCache.cachedPortraits.Count; i++) { - Dictionary dictionary = PortraitsCache.cachedPortraits[i].CachedPortraits; + Dictionary dictionary = PortraitsCache.cachedPortraits[i].CachedPortraits; PortraitsCache.toSetDirty.Clear(); - foreach (KeyValuePair current in dictionary) + Dictionary.Enumerator enumerator = dictionary.GetEnumerator(); + try { - if (PortraitsCache.IsAnimated(current.Key) && !current.Value.Dirty) + while (enumerator.MoveNext()) { - PortraitsCache.toSetDirty.Add(current.Key); + KeyValuePair current = enumerator.Current; + if (PortraitsCache.IsAnimated(current.Key) && !current.Value.Dirty) + { + PortraitsCache.toSetDirty.Add(current.Key); + } } } + finally + { + ((IDisposable)(object)enumerator).Dispose(); + } for (int j = 0; j < PortraitsCache.toSetDirty.Count; j++) { - PortraitsCache.CachedPortrait cachedPortrait = dictionary[PortraitsCache.toSetDirty[j]]; + CachedPortrait cachedPortrait = dictionary[PortraitsCache.toSetDirty[j]]; dictionary.Remove(PortraitsCache.toSetDirty[j]); - dictionary.Add(PortraitsCache.toSetDirty[j], new PortraitsCache.CachedPortrait(cachedPortrait.RenderTexture, true, cachedPortrait.LastUseTime)); + dictionary.Add(PortraitsCache.toSetDirty[j], new CachedPortrait(cachedPortrait.RenderTexture, true, cachedPortrait.LastUseTime)); } PortraitsCache.toSetDirty.Clear(); } @@ -221,7 +247,7 @@ private static void SetAnimatedPortraitsDirty() private static RenderTexture NewRenderTexture(Vector2 size) { - int num = PortraitsCache.renderTexturesPool.FindLastIndex((RenderTexture x) => x.width == (int)size.x && x.height == (int)size.y); + int num = PortraitsCache.renderTexturesPool.FindLastIndex((Predicate)((RenderTexture x) => x.width == (int)size.x && x.height == (int)size.y)); if (num != -1) { RenderTexture result = PortraitsCache.renderTexturesPool[num]; @@ -238,7 +264,11 @@ private static void RenderPortrait(Pawn pawn, RenderTexture renderTexture, Vecto private static bool IsAnimated(Pawn pawn) { - return Current.ProgramState == ProgramState.Playing && pawn.Drawer.renderer.graphics.flasher.FlashingNowOrRecently; + if (Current.ProgramState == ProgramState.Playing && pawn.Drawer.renderer.graphics.flasher.FlashingNowOrRecently) + { + return true; + } + return false; } } } diff --git a/Assembly-CSharp/RimWorld/PowerConnectionMaker.cs b/Assembly-CSharp/RimWorld/PowerConnectionMaker.cs index 28a4fce4e..9ec5605f5 100644 --- a/Assembly-CSharp/RimWorld/PowerConnectionMaker.cs +++ b/Assembly-CSharp/RimWorld/PowerConnectionMaker.cs @@ -1,6 +1,4 @@ -using System; using System.Collections.Generic; -using System.Diagnostics; using Verse; namespace RimWorld @@ -11,85 +9,94 @@ public static class PowerConnectionMaker public static void ConnectAllConnectorsToTransmitter(CompPower newTransmitter) { - foreach (CompPower current in PowerConnectionMaker.PotentialConnectorsForTransmitter(newTransmitter)) + foreach (CompPower item in PowerConnectionMaker.PotentialConnectorsForTransmitter(newTransmitter)) { - if (current.connectParent == null) + if (item.connectParent == null) { - current.ConnectToTransmitter(newTransmitter, false); + item.ConnectToTransmitter(newTransmitter, false); } } } public static void DisconnectAllFromTransmitterAndSetWantConnect(CompPower deadPc, Map map) { - if (deadPc.connectChildren == null) + if (deadPc.connectChildren != null) { - return; - } - for (int i = 0; i < deadPc.connectChildren.Count; i++) - { - CompPower compPower = deadPc.connectChildren[i]; - compPower.connectParent = null; - CompPowerTrader compPowerTrader = compPower as CompPowerTrader; - if (compPowerTrader != null) + for (int i = 0; i < deadPc.connectChildren.Count; i++) { - compPowerTrader.PowerOn = false; + CompPower compPower = deadPc.connectChildren[i]; + compPower.connectParent = null; + CompPowerTrader compPowerTrader = compPower as CompPowerTrader; + if (compPowerTrader != null) + { + compPowerTrader.PowerOn = false; + } + map.powerNetManager.Notify_ConnectorWantsConnect(compPower); } - map.powerNetManager.Notify_ConnectorWantsConnect(compPower); } } public static void TryConnectToAnyPowerNet(CompPower pc, List disallowedNets = null) { - if (pc.connectParent != null) - { - return; - } - if (!pc.parent.Spawned) - { - return; - } - CompPower compPower = PowerConnectionMaker.BestTransmitterForConnector(pc.parent.Position, pc.parent.Map, disallowedNets); - if (compPower != null) - { - pc.ConnectToTransmitter(compPower, false); - } - else + if (pc.connectParent == null && pc.parent.Spawned) { - pc.connectParent = null; + CompPower compPower = PowerConnectionMaker.BestTransmitterForConnector(pc.parent.Position, pc.parent.Map, disallowedNets); + if (compPower != null) + { + pc.ConnectToTransmitter(compPower, false); + } + else + { + pc.connectParent = null; + } } } public static void DisconnectFromPowerNet(CompPower pc) { - if (pc.connectParent == null) - { - return; - } - if (pc.PowerNet != null) - { - pc.PowerNet.DeregisterConnector(pc); - } - if (pc.connectParent.connectChildren != null) + if (pc.connectParent != null) { - pc.connectParent.connectChildren.Remove(pc); - if (pc.connectParent.connectChildren.Count == 0) + if (pc.PowerNet != null) { - pc.connectParent.connectChildren = null; + pc.PowerNet.DeregisterConnector(pc); + } + if (pc.connectParent.connectChildren != null) + { + pc.connectParent.connectChildren.Remove(pc); + if (pc.connectParent.connectChildren.Count == 0) + { + pc.connectParent.connectChildren = null; + } } + pc.connectParent = null; } - pc.connectParent = null; } - [DebuggerHidden] private static IEnumerable PotentialConnectorsForTransmitter(CompPower b) { - PowerConnectionMaker.c__IteratorB6 c__IteratorB = new PowerConnectionMaker.c__IteratorB6(); - c__IteratorB.b = b; - c__IteratorB.<$>b = b; - PowerConnectionMaker.c__IteratorB6 expr_15 = c__IteratorB; - expr_15.$PC = -2; - return expr_15; + if (!b.parent.Spawned) + { + Log.Warning("Can't check potential connectors for " + b + " because it's unspawned."); + } + else + { + CellRect rect = b.parent.OccupiedRect().ExpandedBy(6).ClipInsideMap(b.parent.Map); + for (int z = rect.minZ; z <= rect.maxZ; z++) + { + for (int x = rect.minX; x <= rect.maxX; x++) + { + IntVec3 c = new IntVec3(x, 0, z); + List thingList = b.parent.Map.thingGrid.ThingsListAt(c); + for (int i = 0; i < thingList.Count; i++) + { + if (thingList[i].def.ConnectToPower) + { + yield return ((Building)thingList[i]).PowerComp; + } + } + } + } + } } public static CompPower BestTransmitterForConnector(IntVec3 connectorPos, Map map, List disallowedNets = null) @@ -107,16 +114,13 @@ public static CompPower BestTransmitterForConnector(IntVec3 connectorPos, Map ma if (transmitter != null && !transmitter.Destroyed) { CompPower powerComp = transmitter.PowerComp; - if (powerComp != null && powerComp.TransmitsPowerNow && (transmitter.def.building == null || transmitter.def.building.allowWireConnection)) + if (powerComp != null && powerComp.TransmitsPowerNow && (transmitter.def.building == null || transmitter.def.building.allowWireConnection) && (disallowedNets == null || !disallowedNets.Contains(powerComp.transNet))) { - if (disallowedNets == null || !disallowedNets.Contains(powerComp.transNet)) + float num2 = (float)(transmitter.Position - connectorPos).LengthHorizontalSquared; + if (num2 < num) { - float num2 = (float)(transmitter.Position - connectorPos).LengthHorizontalSquared; - if (num2 < num) - { - num = num2; - result = powerComp; - } + num = num2; + result = powerComp; } } } diff --git a/Assembly-CSharp/RimWorld/PowerNet.cs b/Assembly-CSharp/RimWorld/PowerNet.cs index 56e04a20a..ef46baf1a 100644 --- a/Assembly-CSharp/RimWorld/PowerNet.cs +++ b/Assembly-CSharp/RimWorld/PowerNet.cs @@ -44,14 +44,14 @@ public class PowerNet public PowerNet(IEnumerable newTransmitters) { - foreach (CompPower current in newTransmitters) + foreach (CompPower item in newTransmitters) { - this.transmitters.Add(current); - current.transNet = this; - this.RegisterAllComponentsOf(current.parent); - if (current.connectChildren != null) + this.transmitters.Add(item); + item.transNet = this; + this.RegisterAllComponentsOf(item.parent); + if (item.connectChildren != null) { - List connectChildren = current.connectChildren; + List connectChildren = item.connectChildren; for (int i = 0; i < connectChildren.Count; i++) { this.RegisterConnector(connectChildren[i]); @@ -59,19 +59,34 @@ public PowerNet(IEnumerable newTransmitters) } } this.hasPowerSource = false; - for (int j = 0; j < this.transmitters.Count; j++) + int num = 0; + while (true) { - if (this.IsPowerSource(this.transmitters[j])) + if (num < this.transmitters.Count) { - this.hasPowerSource = true; + if (!this.IsPowerSource(this.transmitters[num])) + { + num++; + continue; + } break; } + return; } + this.hasPowerSource = true; } private bool IsPowerSource(CompPower cp) { - return cp is CompPowerBattery || (cp is CompPowerTrader && cp.Props.basePowerConsumption < 0f); + if (cp is CompPowerBattery) + { + return true; + } + if (cp is CompPowerTrader && cp.Props.basePowerConsumption < 0.0) + { + return true; + } + return false; } public void RegisterConnector(CompPower b) @@ -79,10 +94,12 @@ public void RegisterConnector(CompPower b) if (this.connectors.Contains(b)) { Log.Error("PowerNet registered connector it already had: " + b); - return; } - this.connectors.Add(b); - this.RegisterAllComponentsOf(b.parent); + else + { + this.connectors.Add(b); + this.RegisterAllComponentsOf(b.parent); + } } public void DeregisterConnector(CompPower b) @@ -164,24 +181,16 @@ public void PowerNetTick() { float num = this.CurrentEnergyGainRate(); float num2 = this.CurrentStoredEnergy(); - if (num2 + num >= -1E-07f && !this.powerNetManager.map.gameConditionManager.ConditionIsActive(GameConditionDefOf.SolarFlare)) + if (num2 + num >= -1.0000000116860974E-07 && !this.powerNetManager.map.gameConditionManager.ConditionIsActive(GameConditionDefOf.SolarFlare)) { - float num3; - if (this.batteryComps.Count > 0 && num2 >= 0.1f) - { - num3 = num2 - 5f; - } - else - { - num3 = num2; - } + float num3 = (float)((this.batteryComps.Count <= 0 || !(num2 >= 0.10000000149011612)) ? num2 : (num2 - 5.0)); if (UnityData.isDebugBuild) { this.debugLastApparentStoredEnergy = num3; this.debugLastCreatedEnergy = num; this.debugLastRawStoredEnergy = num2; } - if (num3 + num >= 0f) + if (num3 + num >= 0.0) { PowerNet.partsWantingPowerOn.Clear(); for (int i = 0; i < this.powerComps.Count; i++) @@ -200,8 +209,8 @@ public void PowerNetTick() } if (Find.TickManager.TicksGame % num4 == 0) { - CompPowerTrader compPowerTrader = PowerNet.partsWantingPowerOn.RandomElement(); - if (num + num2 >= -(compPowerTrader.EnergyOutputPerTick + 1E-07f)) + CompPowerTrader compPowerTrader = PowerNet.partsWantingPowerOn.RandomElement(); + if (num + num2 >= 0.0 - (compPowerTrader.EnergyOutputPerTick + 1.0000000116860974E-07)) { compPowerTrader.PowerOn = true; num += compPowerTrader.EnergyOutputPerTick; @@ -216,56 +225,57 @@ public void PowerNetTick() PowerNet.potentialShutdownParts.Clear(); for (int j = 0; j < this.powerComps.Count; j++) { - if (this.powerComps[j].PowerOn && this.powerComps[j].EnergyOutputPerTick < 0f) + if (this.powerComps[j].PowerOn && this.powerComps[j].EnergyOutputPerTick < 0.0) { PowerNet.potentialShutdownParts.Add(this.powerComps[j]); } } if (PowerNet.potentialShutdownParts.Count > 0) { - PowerNet.potentialShutdownParts.RandomElement().PowerOn = false; + PowerNet.potentialShutdownParts.RandomElement().PowerOn = false; } } } private void ChangeStoredEnergy(float extra) { - if (extra > 0f) + if (extra > 0.0) { this.DistributeEnergyAmongBatteries(extra); } else { - float num = -extra; + float num = (float)(0.0 - extra); this.givingBats.Clear(); for (int i = 0; i < this.batteryComps.Count; i++) { - if (this.batteryComps[i].StoredEnergy > 1E-07f) + if (this.batteryComps[i].StoredEnergy > 1.0000000116860974E-07) { this.givingBats.Add(this.batteryComps[i]); } } float a = num / (float)this.givingBats.Count; int num2 = 0; - while (num > 1E-07f) + while (num > 1.0000000116860974E-07) { - for (int j = 0; j < this.givingBats.Count; j++) + int num3 = 0; + while (num3 < this.givingBats.Count) { - float num3 = Mathf.Min(a, this.givingBats[j].StoredEnergy); - this.givingBats[j].DrawPower(num3); - num -= num3; - if (num < 1E-07f) + float num4 = Mathf.Min(a, this.givingBats[num3].StoredEnergy); + this.givingBats[num3].DrawPower(num4); + num -= num4; + if (!(num < 1.0000000116860974E-07)) { - return; + num3++; + continue; } + return; } num2++; if (num2 > 10) - { break; - } } - if (num > 1E-07f) + if (num > 1.0000000116860974E-07) { Log.Warning("Drew energy from a PowerNet that didn't have it."); } @@ -274,61 +284,59 @@ private void ChangeStoredEnergy(float extra) private void DistributeEnergyAmongBatteries(float energy) { - if (energy <= 0f || !this.batteryComps.Any()) + if (!(energy <= 0.0) && this.batteryComps.Any()) { - return; - } - PowerNet.batteriesShuffled.Clear(); - PowerNet.batteriesShuffled.AddRange(this.batteryComps); - PowerNet.batteriesShuffled.Shuffle(); - int num = 0; - while (true) - { - num++; - if (num > 10000) - { - break; - } - float num2 = 3.40282347E+38f; - for (int i = 0; i < PowerNet.batteriesShuffled.Count; i++) + PowerNet.batteriesShuffled.Clear(); + PowerNet.batteriesShuffled.AddRange(this.batteryComps); + PowerNet.batteriesShuffled.Shuffle(); + int num = 0; + while (true) { - num2 = Mathf.Min(num2, PowerNet.batteriesShuffled[i].AmountCanAccept); - } - if (energy < num2 * (float)PowerNet.batteriesShuffled.Count) - { - goto IL_12F; - } - for (int j = PowerNet.batteriesShuffled.Count - 1; j >= 0; j--) - { - float amountCanAccept = PowerNet.batteriesShuffled[j].AmountCanAccept; - bool flag = amountCanAccept <= 0f || amountCanAccept == num2; - if (num2 > 0f) + num++; + if (num > 10000) { - PowerNet.batteriesShuffled[j].AddEnergy(num2); - energy -= num2; + Log.Error("Too many iterations."); } - if (flag) + else { - PowerNet.batteriesShuffled.RemoveAt(j); + float num2 = 3.40282347E+38f; + for (int i = 0; i < PowerNet.batteriesShuffled.Count; i++) + { + num2 = Mathf.Min(num2, PowerNet.batteriesShuffled[i].AmountCanAccept); + } + if (energy >= num2 * (float)PowerNet.batteriesShuffled.Count) + { + for (int num3 = PowerNet.batteriesShuffled.Count - 1; num3 >= 0; num3--) + { + float amountCanAccept = PowerNet.batteriesShuffled[num3].AmountCanAccept; + bool flag = amountCanAccept <= 0.0 || amountCanAccept == num2; + if (num2 > 0.0) + { + PowerNet.batteriesShuffled[num3].AddEnergy(num2); + energy -= num2; + } + if (flag) + { + PowerNet.batteriesShuffled.RemoveAt(num3); + } + } + if (energy < 0.00050000002374872565) + break; + if (!PowerNet.batteriesShuffled.Any()) + break; + continue; + } + float amount = energy / (float)PowerNet.batteriesShuffled.Count; + for (int j = 0; j < PowerNet.batteriesShuffled.Count; j++) + { + PowerNet.batteriesShuffled[j].AddEnergy(amount); + } + energy = 0f; } + break; } - if (energy < 0.0005f || !PowerNet.batteriesShuffled.Any()) - { - goto IL_196; - } + PowerNet.batteriesShuffled.Clear(); } - Log.Error("Too many iterations."); - goto IL_1A0; - IL_12F: - float amount = energy / (float)PowerNet.batteriesShuffled.Count; - for (int k = 0; k < PowerNet.batteriesShuffled.Count; k++) - { - PowerNet.batteriesShuffled[k].AddEnergy(amount); - } - energy = 0f; - IL_196: - IL_1A0: - PowerNet.batteriesShuffled.Clear(); } public string DebugString() @@ -340,24 +348,60 @@ public string DebugString() stringBuilder.AppendLine(" Apparent stored energy: " + this.debugLastApparentStoredEnergy); stringBuilder.AppendLine(" hasPowerSource: " + this.hasPowerSource); stringBuilder.AppendLine(" Connectors: "); - foreach (CompPower current in this.connectors) + List.Enumerator enumerator = this.connectors.GetEnumerator(); + try + { + while (enumerator.MoveNext()) + { + CompPower current = enumerator.Current; + stringBuilder.AppendLine(" " + current.parent); + } + } + finally { - stringBuilder.AppendLine(" " + current.parent); + ((IDisposable)(object)enumerator).Dispose(); } stringBuilder.AppendLine(" Transmitters: "); - foreach (CompPower current2 in this.transmitters) + List.Enumerator enumerator2 = this.transmitters.GetEnumerator(); + try + { + while (enumerator2.MoveNext()) + { + CompPower current2 = enumerator2.Current; + stringBuilder.AppendLine(" " + current2.parent); + } + } + finally { - stringBuilder.AppendLine(" " + current2.parent); + ((IDisposable)(object)enumerator2).Dispose(); } stringBuilder.AppendLine(" powerComps: "); - foreach (CompPowerTrader current3 in this.powerComps) + List.Enumerator enumerator3 = this.powerComps.GetEnumerator(); + try { - stringBuilder.AppendLine(" " + current3.parent); + while (enumerator3.MoveNext()) + { + CompPowerTrader current3 = enumerator3.Current; + stringBuilder.AppendLine(" " + current3.parent); + } + } + finally + { + ((IDisposable)(object)enumerator3).Dispose(); } stringBuilder.AppendLine(" batteryComps: "); - foreach (CompPowerBattery current4 in this.batteryComps) + List.Enumerator enumerator4 = this.batteryComps.GetEnumerator(); + try + { + while (enumerator4.MoveNext()) + { + CompPowerBattery current4 = enumerator4.Current; + stringBuilder.AppendLine(" " + current4.parent); + } + } + finally { - stringBuilder.AppendLine(" " + current4.parent); + ((IDisposable)(object)enumerator4).Dispose(); } return stringBuilder.ToString(); } diff --git a/Assembly-CSharp/RimWorld/PowerNetGraphics.cs b/Assembly-CSharp/RimWorld/PowerNetGraphics.cs index f9628b8d4..203d1e8a7 100644 --- a/Assembly-CSharp/RimWorld/PowerNetGraphics.cs +++ b/Assembly-CSharp/RimWorld/PowerNetGraphics.cs @@ -1,4 +1,3 @@ -using System; using UnityEngine; using Verse; diff --git a/Assembly-CSharp/RimWorld/PowerNetGrid.cs b/Assembly-CSharp/RimWorld/PowerNetGrid.cs index abb06dfea..7589321af 100644 --- a/Assembly-CSharp/RimWorld/PowerNetGrid.cs +++ b/Assembly-CSharp/RimWorld/PowerNetGrid.cs @@ -1,4 +1,3 @@ -using System; using System.Collections.Generic; using Verse; @@ -42,18 +41,7 @@ public void Notify_PowerNetCreated(PowerNet newNet) int num = this.map.cellIndices.CellToIndex(k, j); if (this.netGrid[num] != null) { - Log.Warning(string.Concat(new object[] - { - "Two power nets on the same cell (", - k, - ", ", - j, - "). First transmitters: ", - newNet.transmitters[0].parent.LabelCap, - " and ", - (!this.netGrid[num].transmitters.NullOrEmpty()) ? this.netGrid[num].transmitters[0].parent.LabelCap : "[none]", - "." - })); + Log.Warning("Two power nets on the same cell (" + k + ", " + j + "). First transmitters: " + newNet.transmitters[0].parent.LabelCap + " and " + ((!this.netGrid[num].transmitters.NullOrEmpty()) ? this.netGrid[num].transmitters[0].parent.LabelCap : "[none]") + "."); } this.netGrid[num] = newNet; list.Add(new IntVec3(k, 0, j)); @@ -64,52 +52,45 @@ public void Notify_PowerNetCreated(PowerNet newNet) public void Notify_PowerNetDeleted(PowerNet deadNet) { - List list; + List list = default(List); if (!this.powerNetCells.TryGetValue(deadNet, out list)) { Log.Warning("Net " + deadNet + " does not exist in PowerNetGrid's dictionary."); - return; } - for (int i = 0; i < list.Count; i++) + else { - int num = this.map.cellIndices.CellToIndex(list[i]); - if (this.netGrid[num] == deadNet) + for (int i = 0; i < list.Count; i++) { - this.netGrid[num] = null; - } - else - { - Log.Warning("Multiple nets on the same cell " + list[i] + ". This is probably a result of an earlier error."); + int num = this.map.cellIndices.CellToIndex(list[i]); + if (this.netGrid[num] == deadNet) + { + this.netGrid[num] = null; + } + else + { + Log.Warning("Multiple nets on the same cell " + list[i] + ". This is probably a result of an earlier error."); + } } + this.powerNetCells.Remove(deadNet); } - this.powerNetCells.Remove(deadNet); } public void DrawDebugPowerNetGrid() { - if (!DebugViewSettings.drawPowerNetGrid) - { - return; - } - if (Current.ProgramState != ProgramState.Playing) - { - return; - } - if (this.map != Find.VisibleMap) + if (DebugViewSettings.drawPowerNetGrid && Current.ProgramState == ProgramState.Playing && this.map == Find.VisibleMap) { - return; - } - Rand.PushState(); - foreach (IntVec3 current in Find.CameraDriver.CurrentViewRect.ClipInsideMap(this.map)) - { - PowerNet powerNet = this.netGrid[this.map.cellIndices.CellToIndex(current)]; - if (powerNet != null) + Rand.PushState(); + foreach (IntVec3 item in Find.CameraDriver.CurrentViewRect.ClipInsideMap(this.map)) { - Rand.Seed = powerNet.GetHashCode(); - CellRenderer.RenderCell(current, Rand.Value); + PowerNet powerNet = this.netGrid[this.map.cellIndices.CellToIndex(item)]; + if (powerNet != null) + { + Rand.Seed = powerNet.GetHashCode(); + CellRenderer.RenderCell(item, Rand.Value); + } } + Rand.PopState(); } - Rand.PopState(); } } } diff --git a/Assembly-CSharp/RimWorld/PowerNetMaker.cs b/Assembly-CSharp/RimWorld/PowerNetMaker.cs index 09458bc95..341d19a86 100644 --- a/Assembly-CSharp/RimWorld/PowerNetMaker.cs +++ b/Assembly-CSharp/RimWorld/PowerNetMaker.cs @@ -18,43 +18,56 @@ private static IEnumerable ContiguousPowerBuildings(Building root) PowerNetMaker.closedSet.Clear(); PowerNetMaker.currentSet.Clear(); PowerNetMaker.openSet.Add(root); - do + while (true) { - foreach (Building current in PowerNetMaker.openSet) + HashSet.Enumerator enumerator = PowerNetMaker.openSet.GetEnumerator(); + try { - PowerNetMaker.closedSet.Add(current); + while (enumerator.MoveNext()) + { + Building current = enumerator.Current; + PowerNetMaker.closedSet.Add(current); + } + } + finally + { + ((IDisposable)(object)enumerator).Dispose(); } HashSet hashSet = PowerNetMaker.currentSet; PowerNetMaker.currentSet = PowerNetMaker.openSet; PowerNetMaker.openSet = hashSet; PowerNetMaker.openSet.Clear(); - foreach (Building current2 in PowerNetMaker.currentSet) + HashSet.Enumerator enumerator2 = PowerNetMaker.currentSet.GetEnumerator(); + try { - foreach (IntVec3 current3 in GenAdj.CellsAdjacentCardinal(current2)) + while (enumerator2.MoveNext()) { - if (current3.InBounds(current2.Map)) + Building current2 = enumerator2.Current; + foreach (IntVec3 item in GenAdj.CellsAdjacentCardinal(current2)) { - List thingList = current3.GetThingList(current2.Map); - for (int i = 0; i < thingList.Count; i++) + if (item.InBounds(current2.Map)) { - Building building = thingList[i] as Building; - if (building != null) + List thingList = item.GetThingList(current2.Map); + for (int i = 0; i < thingList.Count; i++) { - if (building.TransmitsPowerNow) + Building building = thingList[i] as Building; + if (building != null && building.TransmitsPowerNow && !PowerNetMaker.openSet.Contains(building) && !PowerNetMaker.currentSet.Contains(building) && !PowerNetMaker.closedSet.Contains(building)) { - if (!PowerNetMaker.openSet.Contains(building) && !PowerNetMaker.currentSet.Contains(building) && !PowerNetMaker.closedSet.Contains(building)) - { - PowerNetMaker.openSet.Add(building); - break; - } + PowerNetMaker.openSet.Add(building); + break; } } } } } } + finally + { + ((IDisposable)(object)enumerator2).Dispose(); + } + if (PowerNetMaker.openSet.Count <= 0) + break; } - while (PowerNetMaker.openSet.Count > 0); return from b in PowerNetMaker.closedSet select b.PowerComp; } diff --git a/Assembly-CSharp/RimWorld/PowerNetManager.cs b/Assembly-CSharp/RimWorld/PowerNetManager.cs index 1c96fb0a7..3c8817426 100644 --- a/Assembly-CSharp/RimWorld/PowerNetManager.cs +++ b/Assembly-CSharp/RimWorld/PowerNetManager.cs @@ -9,19 +9,19 @@ public class PowerNetManager { private enum DelayedActionType { - RegisterTransmitter, - DeregisterTransmitter, - RegisterConnector, - DeregisterConnector + RegisterTransmitter = 0, + DeregisterTransmitter = 1, + RegisterConnector = 2, + DeregisterConnector = 3 } private struct DelayedAction { - public PowerNetManager.DelayedActionType type; + public DelayedActionType type; public CompPower compPower; - public DelayedAction(PowerNetManager.DelayedActionType type, CompPower compPower) + public DelayedAction(DelayedActionType type, CompPower compPower) { this.type = type; this.compPower = compPower; @@ -32,7 +32,7 @@ public DelayedAction(PowerNetManager.DelayedActionType type, CompPower compPower private List allNets = new List(); - private List delayedActions = new List(); + private List delayedActions = new List(); public List AllNetsListForReading { @@ -49,39 +49,38 @@ public PowerNetManager(Map map) public void Notify_TransmitterSpawned(CompPower newTransmitter) { - this.delayedActions.Add(new PowerNetManager.DelayedAction(PowerNetManager.DelayedActionType.RegisterTransmitter, newTransmitter)); + this.delayedActions.Add(new DelayedAction(DelayedActionType.RegisterTransmitter, newTransmitter)); this.NotifyDrawersForWireUpdate(newTransmitter.parent.Position); } public void Notify_TransmitterDespawned(CompPower oldTransmitter) { - this.delayedActions.Add(new PowerNetManager.DelayedAction(PowerNetManager.DelayedActionType.DeregisterTransmitter, oldTransmitter)); + this.delayedActions.Add(new DelayedAction(DelayedActionType.DeregisterTransmitter, oldTransmitter)); this.NotifyDrawersForWireUpdate(oldTransmitter.parent.Position); } public void Notfiy_TransmitterTransmitsPowerNowChanged(CompPower transmitter) { - if (!transmitter.parent.Spawned) + if (transmitter.parent.Spawned) { - return; + this.delayedActions.Add(new DelayedAction(DelayedActionType.DeregisterTransmitter, transmitter)); + this.delayedActions.Add(new DelayedAction(DelayedActionType.RegisterTransmitter, transmitter)); + this.NotifyDrawersForWireUpdate(transmitter.parent.Position); } - this.delayedActions.Add(new PowerNetManager.DelayedAction(PowerNetManager.DelayedActionType.DeregisterTransmitter, transmitter)); - this.delayedActions.Add(new PowerNetManager.DelayedAction(PowerNetManager.DelayedActionType.RegisterTransmitter, transmitter)); - this.NotifyDrawersForWireUpdate(transmitter.parent.Position); } public void Notify_ConnectorWantsConnect(CompPower wantingCon) { if (Scribe.mode == LoadSaveMode.Inactive && !this.HasRegisterConnectorDuplicate(wantingCon)) { - this.delayedActions.Add(new PowerNetManager.DelayedAction(PowerNetManager.DelayedActionType.RegisterConnector, wantingCon)); + this.delayedActions.Add(new DelayedAction(DelayedActionType.RegisterConnector, wantingCon)); } this.NotifyDrawersForWireUpdate(wantingCon.parent.Position); } public void Notify_ConnectorDespawned(CompPower oldCon) { - this.delayedActions.Add(new PowerNetManager.DelayedAction(PowerNetManager.DelayedActionType.DeregisterConnector, oldCon)); + this.delayedActions.Add(new DelayedAction(DelayedActionType.DeregisterConnector, oldCon)); this.NotifyDrawersForWireUpdate(oldCon.parent.Position); } @@ -116,68 +115,65 @@ public void PowerNetsTick() public void UpdatePowerNetsAndConnections_First() { int count = this.delayedActions.Count; - for (int i = 0; i < count; i++) + for (int num = 0; num < count; num++) { - PowerNetManager.DelayedAction delayedAction = this.delayedActions[i]; - PowerNetManager.DelayedActionType type = this.delayedActions[i].type; - if (type != PowerNetManager.DelayedActionType.RegisterTransmitter) + DelayedAction delayedAction = this.delayedActions[num]; + DelayedAction delayedAction2 = this.delayedActions[num]; + switch (delayedAction2.type) { - if (type == PowerNetManager.DelayedActionType.DeregisterTransmitter) - { - this.TryDestroyNetAt(delayedAction.compPower.parent.Position); - PowerConnectionMaker.DisconnectAllFromTransmitterAndSetWantConnect(delayedAction.compPower, this.map); - delayedAction.compPower.ResetPowerVars(); - } - } - else + case DelayedActionType.RegisterTransmitter: { ThingWithComps parent = delayedAction.compPower.parent; if (this.map.powerNetGrid.TransmittedPowerNetAt(parent.Position) != null) { - Log.Warning(string.Concat(new object[] - { - "Tried to register trasmitter ", - parent, - " at ", - parent.Position, - ", but there is already a power net here. There can't be two transmitters on the same cell." - })); + Log.Warning("Tried to register trasmitter " + parent + " at " + parent.Position + ", but there is already a power net here. There can't be two transmitters on the same cell."); } delayedAction.compPower.SetUpPowerVars(); - foreach (IntVec3 current in GenAdj.CellsAdjacentCardinal(parent)) + foreach (IntVec3 item in GenAdj.CellsAdjacentCardinal(parent)) { - this.TryDestroyNetAt(current); + this.TryDestroyNetAt(item); } + break; + } + case DelayedActionType.DeregisterTransmitter: + { + this.TryDestroyNetAt(delayedAction.compPower.parent.Position); + PowerConnectionMaker.DisconnectAllFromTransmitterAndSetWantConnect(delayedAction.compPower, this.map); + delayedAction.compPower.ResetPowerVars(); + break; + } } } - for (int j = 0; j < count; j++) + for (int num2 = 0; num2 < count; num2++) { - PowerNetManager.DelayedAction delayedAction2 = this.delayedActions[j]; - if (delayedAction2.type == PowerNetManager.DelayedActionType.RegisterTransmitter || delayedAction2.type == PowerNetManager.DelayedActionType.DeregisterTransmitter) + DelayedAction delayedAction3 = this.delayedActions[num2]; + if (delayedAction3.type == DelayedActionType.RegisterTransmitter || delayedAction3.type == DelayedActionType.DeregisterTransmitter) { - this.TryCreateNetAt(delayedAction2.compPower.parent.Position); - foreach (IntVec3 current2 in GenAdj.CellsAdjacentCardinal(delayedAction2.compPower.parent)) + this.TryCreateNetAt(delayedAction3.compPower.parent.Position); + foreach (IntVec3 item2 in GenAdj.CellsAdjacentCardinal(delayedAction3.compPower.parent)) { - this.TryCreateNetAt(current2); + this.TryCreateNetAt(item2); } } } - for (int k = 0; k < count; k++) + for (int num3 = 0; num3 < count; num3++) { - PowerNetManager.DelayedAction delayedAction3 = this.delayedActions[k]; - PowerNetManager.DelayedActionType type = this.delayedActions[k].type; - if (type != PowerNetManager.DelayedActionType.RegisterConnector) + DelayedAction delayedAction4 = this.delayedActions[num3]; + DelayedAction delayedAction5 = this.delayedActions[num3]; + switch (delayedAction5.type) { - if (type == PowerNetManager.DelayedActionType.DeregisterConnector) - { - PowerConnectionMaker.DisconnectFromPowerNet(delayedAction3.compPower); - delayedAction3.compPower.ResetPowerVars(); - } + case DelayedActionType.RegisterConnector: + { + delayedAction4.compPower.SetUpPowerVars(); + PowerConnectionMaker.TryConnectToAnyPowerNet(delayedAction4.compPower, null); + break; } - else + case DelayedActionType.DeregisterConnector: { - delayedAction3.compPower.SetUpPowerVars(); - PowerConnectionMaker.TryConnectToAnyPowerNet(delayedAction3.compPower, null); + PowerConnectionMaker.DisconnectFromPowerNet(delayedAction4.compPower); + delayedAction4.compPower.ResetPowerVars(); + break; + } } } this.delayedActions.RemoveRange(0, count); @@ -189,15 +185,18 @@ public void UpdatePowerNetsAndConnections_First() private bool HasRegisterConnectorDuplicate(CompPower compPower) { - for (int i = this.delayedActions.Count - 1; i >= 0; i--) + for (int num = this.delayedActions.Count - 1; num >= 0; num--) { - if (this.delayedActions[i].compPower == compPower) + DelayedAction delayedAction = this.delayedActions[num]; + if (delayedAction.compPower == compPower) { - if (this.delayedActions[i].type == PowerNetManager.DelayedActionType.DeregisterConnector) + DelayedAction delayedAction2 = this.delayedActions[num]; + if (delayedAction2.type == DelayedActionType.DeregisterConnector) { return false; } - if (this.delayedActions[i].type == PowerNetManager.DelayedActionType.RegisterConnector) + DelayedAction delayedAction3 = this.delayedActions[num]; + if (delayedAction3.type == DelayedActionType.RegisterConnector) { return true; } @@ -208,11 +207,7 @@ private bool HasRegisterConnectorDuplicate(CompPower compPower) private void TryCreateNetAt(IntVec3 cell) { - if (!cell.InBounds(this.map)) - { - return; - } - if (this.map.powerNetGrid.TransmittedPowerNetAt(cell) == null) + if (cell.InBounds(this.map) && this.map.powerNetGrid.TransmittedPowerNetAt(cell) == null) { Building transmitter = cell.GetTransmitter(this.map); if (transmitter != null && transmitter.TransmitsPowerNow) @@ -229,34 +224,41 @@ private void TryCreateNetAt(IntVec3 cell) private void TryDestroyNetAt(IntVec3 cell) { - if (!cell.InBounds(this.map)) - { - return; - } - PowerNet powerNet = this.map.powerNetGrid.TransmittedPowerNetAt(cell); - if (powerNet != null) + if (cell.InBounds(this.map)) { - this.DeletePowerNet(powerNet); + PowerNet powerNet = this.map.powerNetGrid.TransmittedPowerNetAt(cell); + if (powerNet != null) + { + this.DeletePowerNet(powerNet); + } } } private void DrawDebugPowerNets() { - if (Current.ProgramState != ProgramState.Playing) + if (Current.ProgramState == ProgramState.Playing) { - return; - } - int num = 0; - foreach (PowerNet current in this.allNets) - { - foreach (CompPower current2 in current.transmitters.Concat(current.connectors)) + int num = 0; + List.Enumerator enumerator = this.allNets.GetEnumerator(); + try { - foreach (IntVec3 current3 in GenAdj.CellsOccupiedBy(current2.parent)) + while (enumerator.MoveNext()) { - CellRenderer.RenderCell(current3, (float)num * 0.44f); + PowerNet current = enumerator.Current; + foreach (CompPower item in current.transmitters.Concat(current.connectors)) + { + foreach (IntVec3 item2 in GenAdj.CellsOccupiedBy(item.parent)) + { + CellRenderer.RenderCell(item2, (float)((float)num * 0.43999999761581421)); + } + } + num++; } } - num++; + finally + { + ((IDisposable)(object)enumerator).Dispose(); + } } } } diff --git a/Assembly-CSharp/RimWorld/PowerOverlayMats.cs b/Assembly-CSharp/RimWorld/PowerOverlayMats.cs index bfce39971..907a1b49e 100644 --- a/Assembly-CSharp/RimWorld/PowerOverlayMats.cs +++ b/Assembly-CSharp/RimWorld/PowerOverlayMats.cs @@ -1,4 +1,3 @@ -using System; using UnityEngine; using Verse; diff --git a/Assembly-CSharp/RimWorld/PredatorThreat.cs b/Assembly-CSharp/RimWorld/PredatorThreat.cs index 76b92ac2a..dd1b28033 100644 --- a/Assembly-CSharp/RimWorld/PredatorThreat.cs +++ b/Assembly-CSharp/RimWorld/PredatorThreat.cs @@ -1,4 +1,3 @@ -using System; using Verse; namespace RimWorld @@ -15,7 +14,11 @@ public bool Expired { get { - return !this.predator.Spawned || Find.TickManager.TicksGame >= this.lastAttackTicks + 600; + if (!this.predator.Spawned) + { + return true; + } + return Find.TickManager.TicksGame >= this.lastAttackTicks + 600; } } diff --git a/Assembly-CSharp/RimWorld/PriceType.cs b/Assembly-CSharp/RimWorld/PriceType.cs index e990ccc32..4549c5f7e 100644 --- a/Assembly-CSharp/RimWorld/PriceType.cs +++ b/Assembly-CSharp/RimWorld/PriceType.cs @@ -1,14 +1,12 @@ -using System; - namespace RimWorld { public enum PriceType : byte { - Undefined, - VeryCheap, - Cheap, - Normal, - Expensive, - Exorbitant + Undefined = 0, + VeryCheap = 1, + Cheap = 2, + Normal = 3, + Expensive = 4, + Exorbitant = 5 } } diff --git a/Assembly-CSharp/RimWorld/PriceTypeUtlity.cs b/Assembly-CSharp/RimWorld/PriceTypeUtlity.cs index e81386d03..6a2eda1bc 100644 --- a/Assembly-CSharp/RimWorld/PriceTypeUtlity.cs +++ b/Assembly-CSharp/RimWorld/PriceTypeUtlity.cs @@ -1,5 +1,4 @@ using System; -using System.Collections; using UnityEngine; namespace RimWorld @@ -11,35 +10,43 @@ public static float PriceMultiplier(this PriceType pType) switch (pType) { case PriceType.VeryCheap: + { return 0.4f; + } case PriceType.Cheap: + { return 0.7f; + } case PriceType.Normal: + { return 1f; + } case PriceType.Expensive: + { return 2f; + } case PriceType.Exorbitant: + { return 5f; + } default: + { return -1f; } + } } public static PriceType ClosestPriceType(float priceFactor) { float num = 99999f; PriceType priceType = PriceType.Undefined; - using (IEnumerator enumerator = Enum.GetValues(typeof(PriceType)).GetEnumerator()) + foreach (byte value in Enum.GetValues(typeof(PriceType))) { - while (enumerator.MoveNext()) + float num2 = Mathf.Abs(priceFactor - ((PriceType)value).PriceMultiplier()); + if (num2 < num) { - PriceType priceType2 = (PriceType)((byte)enumerator.Current); - float num2 = Mathf.Abs(priceFactor - priceType2.PriceMultiplier()); - if (num2 < num) - { - num = num2; - priceType = priceType2; - } + num = num2; + priceType = (PriceType)value; } } if (priceType == PriceType.Undefined) diff --git a/Assembly-CSharp/RimWorld/PriceUtility.cs b/Assembly-CSharp/RimWorld/PriceUtility.cs index e76de30db..048c0f3ca 100644 --- a/Assembly-CSharp/RimWorld/PriceUtility.cs +++ b/Assembly-CSharp/RimWorld/PriceUtility.cs @@ -37,18 +37,11 @@ public static float PawnQualityPriceFactor(Pawn pawn) List allDefsListForReading = DefDatabase.AllDefsListForReading; for (int i = 0; i < allDefsListForReading.Count; i++) { - if (!pawn.health.capacities.CapableOf(allDefsListForReading[i])) - { - num *= 0.6f; - } - else - { - num *= Mathf.Lerp(0.5f, 1f, pawn.health.capacities.GetLevel(allDefsListForReading[i])); - } + num = (float)(pawn.health.capacities.CapableOf(allDefsListForReading[i]) ? (num * Mathf.Lerp(0.5f, 1f, pawn.health.capacities.GetLevel(allDefsListForReading[i]))) : (num * 0.60000002384185791)); } if (pawn.skills != null) { - num *= PriceUtility.AverageSkillCurve.Evaluate(pawn.skills.skills.Average((SkillRecord sk) => (float)sk.Level)); + num *= PriceUtility.AverageSkillCurve.Evaluate(pawn.skills.skills.Average((Func)((SkillRecord sk) => (float)sk.Level))); } return num * pawn.ageTracker.CurLifeStage.marketValueFactor; } diff --git a/Assembly-CSharp/RimWorld/PrisonBreakUtility.cs b/Assembly-CSharp/RimWorld/PrisonBreakUtility.cs index 889ca5c3d..d6c580f2a 100644 --- a/Assembly-CSharp/RimWorld/PrisonBreakUtility.cs +++ b/Assembly-CSharp/RimWorld/PrisonBreakUtility.cs @@ -38,33 +38,49 @@ public static float InitiatePrisonBreakMtbDays(Pawn pawn) return -1f; } Room room = pawn.GetRoom(RegionType.Set_Passable); - if (room == null || !room.isPrisonCell) + if (room != null && room.isPrisonCell) { - return -1f; + float num = 45f; + return num / Mathf.Min(pawn.health.capacities.GetLevel(PawnCapacityDefOf.Moving), 1f); } - float num = 45f; - return num / Mathf.Min(pawn.health.capacities.GetLevel(PawnCapacityDefOf.Moving), 1f); + return -1f; } public static bool CanParticipateInPrisonBreak(Pawn pawn) { - return !pawn.Downed && pawn.IsPrisoner && !PrisonBreakUtility.IsPrisonBreaking(pawn); + if (pawn.Downed) + { + return false; + } + if (!pawn.IsPrisoner) + { + return false; + } + if (PrisonBreakUtility.IsPrisonBreaking(pawn)) + { + return false; + } + return true; } public static bool IsPrisonBreaking(Pawn pawn) { Lord lord = pawn.GetLord(); - return lord != null && lord.LordJob is LordJob_PrisonBreak; + if (lord != null && lord.LordJob is LordJob_PrisonBreak) + { + return true; + } + return false; } public static void StartPrisonBreak(Pawn initiator) { PrisonBreakUtility.participatingRooms.Clear(); - foreach (IntVec3 current in GenRadial.RadialCellsAround(initiator.Position, 20f, true)) + foreach (IntVec3 item in GenRadial.RadialCellsAround(initiator.Position, 20f, true)) { - if (current.InBounds(initiator.Map)) + if (item.InBounds(initiator.Map)) { - Room room = current.GetRoom(initiator.Map, RegionType.Set_Passable); + Room room = item.GetRoom(initiator.Map, RegionType.Set_Passable); if (room != null && room.isPrisonCell) { PrisonBreakUtility.participatingRooms.Add(room); @@ -73,17 +89,26 @@ public static void StartPrisonBreak(Pawn initiator) } PrisonBreakUtility.RemoveRandomRooms(PrisonBreakUtility.participatingRooms, initiator); int sapperThingID = -1; - if (Rand.Value < 0.5f) + if (Rand.Value < 0.5) { sapperThingID = initiator.thingIDNumber; } PrisonBreakUtility.allEscapingPrisoners.Clear(); - foreach (Room current2 in PrisonBreakUtility.participatingRooms) + HashSet.Enumerator enumerator2 = PrisonBreakUtility.participatingRooms.GetEnumerator(); + try + { + while (enumerator2.MoveNext()) + { + Room current2 = enumerator2.Current; + PrisonBreakUtility.StartPrisonBreakIn(current2, PrisonBreakUtility.allEscapingPrisoners, sapperThingID, PrisonBreakUtility.participatingRooms); + } + } + finally { - PrisonBreakUtility.StartPrisonBreakIn(current2, PrisonBreakUtility.allEscapingPrisoners, sapperThingID, PrisonBreakUtility.participatingRooms); + ((IDisposable)(object)enumerator2).Dispose(); } PrisonBreakUtility.participatingRooms.Clear(); - if (PrisonBreakUtility.allEscapingPrisoners.Any()) + if (PrisonBreakUtility.allEscapingPrisoners.Any()) { PrisonBreakUtility.SendPrisonBreakLetter(PrisonBreakUtility.allEscapingPrisoners); } @@ -94,16 +119,22 @@ private static void RemoveRandomRooms(HashSet participatingRooms, Pawn ini { Room room = initiator.GetRoom(RegionType.Set_Passable); PrisonBreakUtility.tmpToRemove.Clear(); - foreach (Room current in participatingRooms) + HashSet.Enumerator enumerator = participatingRooms.GetEnumerator(); + try { - if (current != room) + while (enumerator.MoveNext()) { - if (Rand.Value >= 0.5f) + Room current = enumerator.Current; + if (current != room && !(Rand.Value < 0.5)) { PrisonBreakUtility.tmpToRemove.Add(current); } } } + finally + { + ((IDisposable)(object)enumerator).Dispose(); + } for (int i = 0; i < PrisonBreakUtility.tmpToRemove.Count; i++) { participatingRooms.Remove(PrisonBreakUtility.tmpToRemove[i]); @@ -115,57 +146,66 @@ private static void StartPrisonBreakIn(Room room, List outAllEscapingPriso { PrisonBreakUtility.escapingPrisonersGroup.Clear(); PrisonBreakUtility.AddPrisonersFrom(room, PrisonBreakUtility.escapingPrisonersGroup); - if (!PrisonBreakUtility.escapingPrisonersGroup.Any()) - { - return; - } - foreach (Room current in participatingRooms) + if (PrisonBreakUtility.escapingPrisonersGroup.Any()) { - if (current != room) + HashSet.Enumerator enumerator = participatingRooms.GetEnumerator(); + try { - if (PrisonBreakUtility.RoomsAreCloseToEachOther(room, current)) + while (enumerator.MoveNext()) { - PrisonBreakUtility.AddPrisonersFrom(current, PrisonBreakUtility.escapingPrisonersGroup); + Room current = enumerator.Current; + if (current != room && PrisonBreakUtility.RoomsAreCloseToEachOther(room, current)) + { + PrisonBreakUtility.AddPrisonersFrom(current, PrisonBreakUtility.escapingPrisonersGroup); + } } } - } - IntVec3 exitPoint; - if (!RCellFinder.TryFindRandomExitSpot(PrisonBreakUtility.escapingPrisonersGroup[0], out exitPoint, TraverseMode.PassDoors)) - { - return; - } - IntVec3 groupUpLoc; - if (!PrisonBreakUtility.TryFindGroupUpLoc(PrisonBreakUtility.escapingPrisonersGroup, exitPoint, out groupUpLoc)) - { - return; - } - LordMaker.MakeNewLord(PrisonBreakUtility.escapingPrisonersGroup[0].Faction, new LordJob_PrisonBreak(groupUpLoc, exitPoint, sapperThingID), room.Map, PrisonBreakUtility.escapingPrisonersGroup); - for (int i = 0; i < PrisonBreakUtility.escapingPrisonersGroup.Count; i++) - { - Pawn pawn = PrisonBreakUtility.escapingPrisonersGroup[i]; - if (pawn.CurJob != null && pawn.jobs.curDriver.layingDown != LayingDownState.NotLaying) + finally { - pawn.jobs.EndCurrentJob(JobCondition.InterruptForced, true); + ((IDisposable)(object)enumerator).Dispose(); } - else + IntVec3 exitPoint = default(IntVec3); + IntVec3 groupUpLoc = default(IntVec3); + if (RCellFinder.TryFindRandomExitSpot(PrisonBreakUtility.escapingPrisonersGroup[0], out exitPoint, TraverseMode.PassDoors) && PrisonBreakUtility.TryFindGroupUpLoc(PrisonBreakUtility.escapingPrisonersGroup, exitPoint, out groupUpLoc)) { - pawn.jobs.CheckForJobOverride(); + LordMaker.MakeNewLord(PrisonBreakUtility.escapingPrisonersGroup[0].Faction, new LordJob_PrisonBreak(groupUpLoc, exitPoint, sapperThingID), room.Map, PrisonBreakUtility.escapingPrisonersGroup); + for (int i = 0; i < PrisonBreakUtility.escapingPrisonersGroup.Count; i++) + { + Pawn pawn = PrisonBreakUtility.escapingPrisonersGroup[i]; + if (((pawn.CurJob != null) ? pawn.jobs.curDriver.layingDown : LayingDownState.NotLaying) != 0) + { + pawn.jobs.EndCurrentJob(JobCondition.InterruptForced, true); + } + else + { + pawn.jobs.CheckForJobOverride(); + } + outAllEscapingPrisoners.Add(pawn); + } + PrisonBreakUtility.escapingPrisonersGroup.Clear(); } - outAllEscapingPrisoners.Add(pawn); } - PrisonBreakUtility.escapingPrisonersGroup.Clear(); } private static void AddPrisonersFrom(Room room, List outEscapingPrisoners) { - foreach (Thing current in room.ContainedAndAdjacentThings) + List.Enumerator enumerator = room.ContainedAndAdjacentThings.GetEnumerator(); + try { - Pawn pawn = current as Pawn; - if (pawn != null && PrisonBreakUtility.CanParticipateInPrisonBreak(pawn)) + while (enumerator.MoveNext()) { - outEscapingPrisoners.Add(pawn); + Thing current = enumerator.Current; + Pawn pawn = current as Pawn; + if (pawn != null && PrisonBreakUtility.CanParticipateInPrisonBreak(pawn)) + { + outEscapingPrisoners.Add(pawn); + } } } + finally + { + ((IDisposable)(object)enumerator).Dispose(); + } } private static bool TryFindGroupUpLoc(List escapingPrisoners, IntVec3 exitPoint, out IntVec3 groupUpLoc) @@ -183,15 +223,9 @@ private static bool TryFindGroupUpLoc(List escapingPrisoners, IntVec3 exit { IntVec3 intVec = pawnPath.Peek(pawnPath.NodesLeftCount - i - 1); Room room = intVec.GetRoom(map, RegionType.Set_Passable); - if (room != null) + if (room != null && !room.isPrisonCell && (room.TouchesMapEdge || room.IsHuge || room.Cells.Count((Func)((IntVec3 x) => x.Standable(map))) >= 5)) { - if (!room.isPrisonCell) - { - if (room.TouchesMapEdge || room.IsHuge || room.Cells.Count((IntVec3 x) => x.Standable(map)) >= 5) - { - groupUpLoc = CellFinder.RandomClosewalkCellNear(intVec, map, 3, null); - } - } + groupUpLoc = CellFinder.RandomClosewalkCellNear(intVec, map, 3, null); } } } @@ -214,19 +248,17 @@ private static bool RoomsAreCloseToEachOther(Room a, Room b) { return false; } - bool result; using (PawnPath pawnPath = a.Map.pathFinder.FindPath(anyCell, anyCell2, TraverseParms.For(TraverseMode.PassDoors, Danger.Deadly, false), PathEndMode.OnCell)) { if (!pawnPath.Found) { - result = false; - } - else - { - result = (pawnPath.NodesLeftCount < 24); + return false; } + return pawnPath.NodesLeftCount < 24; + IL_0099: + bool result; + return result; } - return result; } private static void SendPrisonBreakLetter(List escapingPrisoners) @@ -236,10 +268,7 @@ private static void SendPrisonBreakLetter(List escapingPrisoners) { stringBuilder.AppendLine(" " + escapingPrisoners[i].LabelShort); } - Find.LetterStack.ReceiveLetter("LetterLabelPrisonBreak".Translate(), "LetterPrisonBreak".Translate(new object[] - { - stringBuilder.ToString().TrimEndNewlines() - }), LetterDefOf.BadUrgent, PrisonBreakUtility.allEscapingPrisoners[0], null); + Find.LetterStack.ReceiveLetter("LetterLabelPrisonBreak".Translate(), "LetterPrisonBreak".Translate(stringBuilder.ToString().TrimEndNewlines()), LetterDefOf.BadUrgent, (Thing)PrisonBreakUtility.allEscapingPrisoners[0], (string)null); } } } diff --git a/Assembly-CSharp/RimWorld/PrisonerInteractionModeDef.cs b/Assembly-CSharp/RimWorld/PrisonerInteractionModeDef.cs index 10eb1c11f..ed0331684 100644 --- a/Assembly-CSharp/RimWorld/PrisonerInteractionModeDef.cs +++ b/Assembly-CSharp/RimWorld/PrisonerInteractionModeDef.cs @@ -1,4 +1,3 @@ -using System; using Verse; namespace RimWorld diff --git a/Assembly-CSharp/RimWorld/PrisonerInteractionModeDefOf.cs b/Assembly-CSharp/RimWorld/PrisonerInteractionModeDefOf.cs index 6b6e347b1..a6dfd5fc9 100644 --- a/Assembly-CSharp/RimWorld/PrisonerInteractionModeDefOf.cs +++ b/Assembly-CSharp/RimWorld/PrisonerInteractionModeDefOf.cs @@ -1,5 +1,3 @@ -using System; - namespace RimWorld { [DefOf] diff --git a/Assembly-CSharp/RimWorld/PrisonerInteractionModeUtility.cs b/Assembly-CSharp/RimWorld/PrisonerInteractionModeUtility.cs index 439e92a97..c3abab724 100644 --- a/Assembly-CSharp/RimWorld/PrisonerInteractionModeUtility.cs +++ b/Assembly-CSharp/RimWorld/PrisonerInteractionModeUtility.cs @@ -1,4 +1,3 @@ -using System; using Verse; namespace RimWorld diff --git a/Assembly-CSharp/RimWorld/Projectile_DoomsdayRocket.cs b/Assembly-CSharp/RimWorld/Projectile_DoomsdayRocket.cs index e0026cee0..b864cf168 100644 --- a/Assembly-CSharp/RimWorld/Projectile_DoomsdayRocket.cs +++ b/Assembly-CSharp/RimWorld/Projectile_DoomsdayRocket.cs @@ -1,4 +1,3 @@ -using System; using Verse; namespace RimWorld @@ -9,8 +8,8 @@ protected override void Impact(Thing hitThing) { Map map = base.Map; base.Impact(hitThing); - ThingDef def = this.def; - GenExplosion.DoExplosion(base.Position, map, this.def.projectile.explosionRadius, DamageDefOf.Bomb, this.launcher, null, def, this.equipmentDef, null, 0f, 1, false, null, 0f, 1); + ThingDef def = base.def; + GenExplosion.DoExplosion(base.Position, map, base.def.projectile.explosionRadius, DamageDefOf.Bomb, base.launcher, null, def, base.equipmentDef, null, 0f, 1, false, null, 0f, 1); CellRect cellRect = CellRect.CenteredOn(base.Position, 10); cellRect.ClipInsideMap(map); for (int i = 0; i < 5; i++) @@ -22,8 +21,8 @@ protected override void Impact(Thing hitThing) protected void FireExplosion(IntVec3 pos, Map map, float radius) { - ThingDef def = this.def; - GenExplosion.DoExplosion(pos, map, radius, DamageDefOf.Flame, this.launcher, null, def, this.equipmentDef, ThingDefOf.FilthFuel, 0.2f, 1, false, null, 0f, 1); + ThingDef def = base.def; + GenExplosion.DoExplosion(pos, map, radius, DamageDefOf.Flame, base.launcher, null, def, base.equipmentDef, ThingDefOf.FilthFuel, 0.2f, 1, false, null, 0f, 1); } } } diff --git a/Assembly-CSharp/RimWorld/PsychicDroneLevel.cs b/Assembly-CSharp/RimWorld/PsychicDroneLevel.cs index d7232517f..41eafb210 100644 --- a/Assembly-CSharp/RimWorld/PsychicDroneLevel.cs +++ b/Assembly-CSharp/RimWorld/PsychicDroneLevel.cs @@ -1,14 +1,12 @@ -using System; - namespace RimWorld { public enum PsychicDroneLevel : byte { - None, - GoodMedium, - BadLow, - BadMedium, - BadHigh, - BadExtreme + None = 0, + GoodMedium = 1, + BadLow = 2, + BadMedium = 3, + BadHigh = 4, + BadExtreme = 5 } } diff --git a/Assembly-CSharp/RimWorld/Quadrum.cs b/Assembly-CSharp/RimWorld/Quadrum.cs index 03f38df88..2e432f595 100644 --- a/Assembly-CSharp/RimWorld/Quadrum.cs +++ b/Assembly-CSharp/RimWorld/Quadrum.cs @@ -1,13 +1,11 @@ -using System; - namespace RimWorld { public enum Quadrum : byte { - Aprimay, - Jugust, - Septober, - Decembary, - Undefined + Aprimay = 0, + Jugust = 1, + Septober = 2, + Decembary = 3, + Undefined = 4 } } diff --git a/Assembly-CSharp/RimWorld/QuadrumUtility.cs b/Assembly-CSharp/RimWorld/QuadrumUtility.cs index 29994476e..07fe1bc0d 100644 --- a/Assembly-CSharp/RimWorld/QuadrumUtility.cs +++ b/Assembly-CSharp/RimWorld/QuadrumUtility.cs @@ -1,4 +1,3 @@ -using System; using System.Collections.Generic; using Verse; @@ -19,16 +18,26 @@ public static Twelfth GetFirstTwelfth(this Quadrum quadrum) switch (quadrum) { case Quadrum.Aprimay: + { return Twelfth.First; + } case Quadrum.Jugust: + { return Twelfth.Fourth; + } case Quadrum.Septober: + { return Twelfth.Seventh; + } case Quadrum.Decembary: + { return Twelfth.Tenth; + } default: + { return Twelfth.Undefined; } + } } public static string Label(this Quadrum quadrum) @@ -36,16 +45,26 @@ public static string Label(this Quadrum quadrum) switch (quadrum) { case Quadrum.Aprimay: + { return "QuadrumAprimay".Translate(); + } case Quadrum.Jugust: + { return "QuadrumJugust".Translate(); + } case Quadrum.Septober: + { return "QuadrumSeptober".Translate(); + } case Quadrum.Decembary: + { return "QuadrumDecembary".Translate(); + } default: + { return "Unknown quadrum"; } + } } public static Season GetSeason(this Quadrum q, float latitude) @@ -67,7 +86,7 @@ public static string QuadrumsRangeLabel(List twelfths) string text = string.Empty; for (int i = 0; i < 12; i++) { - Twelfth twelfth = (Twelfth)i; + Twelfth twelfth = (Twelfth)(byte)i; if (twelfths.Contains(twelfth)) { if (!text.NullOrEmpty()) @@ -84,23 +103,17 @@ private static string QuadrumsContinuousRangeLabel(List twelfths, Twelf { Twelfth leftMostTwelfth = TwelfthUtility.GetLeftMostTwelfth(twelfths, rootTwelfth); Twelfth rightMostTwelfth = TwelfthUtility.GetRightMostTwelfth(twelfths, rootTwelfth); - for (Twelfth twelfth = leftMostTwelfth; twelfth != rightMostTwelfth; twelfth = TwelfthUtility.TwelfthAfter(twelfth)) + Twelfth twelfth = leftMostTwelfth; + while (twelfth != rightMostTwelfth) { - if (!twelfths.Contains(twelfth)) + if (twelfths.Contains(twelfth)) { - Log.Error(string.Concat(new object[] - { - "Twelfths doesn't contain ", - twelfth, - " (", - leftMostTwelfth, - "..", - rightMostTwelfth, - ")" - })); - break; + twelfths.Remove(twelfth); + twelfth = TwelfthUtility.TwelfthAfter(twelfth); + continue; } - twelfths.Remove(twelfth); + Log.Error("Twelfths doesn't contain " + twelfth + " (" + leftMostTwelfth + ".." + rightMostTwelfth + ")"); + break; } twelfths.Remove(rightMostTwelfth); return GenDate.QuadrumDateStringAt(leftMostTwelfth) + " - " + GenDate.QuadrumDateStringAt(rightMostTwelfth); diff --git a/Assembly-CSharp/RimWorld/QualityCategory.cs b/Assembly-CSharp/RimWorld/QualityCategory.cs index b0367eb88..e2777e955 100644 --- a/Assembly-CSharp/RimWorld/QualityCategory.cs +++ b/Assembly-CSharp/RimWorld/QualityCategory.cs @@ -1,17 +1,15 @@ -using System; - namespace RimWorld { public enum QualityCategory : byte { - Awful, - Shoddy, - Poor, - Normal, - Good, - Superior, - Excellent, - Masterwork, - Legendary + Awful = 0, + Shoddy = 1, + Poor = 2, + Normal = 3, + Good = 4, + Superior = 5, + Excellent = 6, + Masterwork = 7, + Legendary = 8 } } diff --git a/Assembly-CSharp/RimWorld/QualityRange.cs b/Assembly-CSharp/RimWorld/QualityRange.cs index 33220a24f..c11c741f6 100644 --- a/Assembly-CSharp/RimWorld/QualityRange.cs +++ b/Assembly-CSharp/RimWorld/QualityRange.cs @@ -25,27 +25,23 @@ public QualityRange(QualityCategory min, QualityCategory max) public bool Includes(QualityCategory p) { - return p >= this.min && p <= this.max; + return (int)p >= (int)this.min && (int)p <= (int)this.max; } public static QualityRange FromString(string s) { - string[] array = s.Split(new char[] - { - '~' - }); - QualityRange result = new QualityRange((QualityCategory)((byte)ParseHelper.FromString(array[0], typeof(QualityCategory))), (QualityCategory)((byte)ParseHelper.FromString(array[1], typeof(QualityCategory)))); - return result; + string[] array = s.Split('~'); + return new QualityRange((QualityCategory)(byte)ParseHelper.FromString(array[0], typeof(QualityCategory)), (QualityCategory)(byte)ParseHelper.FromString(array[1], typeof(QualityCategory))); } public override string ToString() { - return this.min.ToString() + "~" + this.max.ToString(); + return ((Enum)(object)this.min).ToString() + "~" + ((Enum)(object)this.max).ToString(); } public override int GetHashCode() { - return Gen.HashCombineStruct(this.min.GetHashCode(), this.max); + return Gen.HashCombineStruct(((Enum)(object)this.min).GetHashCode(), this.max); } public override bool Equals(object obj) diff --git a/Assembly-CSharp/RimWorld/QualityUtility.cs b/Assembly-CSharp/RimWorld/QualityUtility.cs index d4195feef..e2a3c3824 100644 --- a/Assembly-CSharp/RimWorld/QualityUtility.cs +++ b/Assembly-CSharp/RimWorld/QualityUtility.cs @@ -1,5 +1,4 @@ using System; -using System.Collections; using System.Collections.Generic; using System.Linq; using System.Text; @@ -15,13 +14,9 @@ public static class QualityUtility static QualityUtility() { QualityUtility.AllQualityCategories = new List(); - using (IEnumerator enumerator = Enum.GetValues(typeof(QualityCategory)).GetEnumerator()) + foreach (byte value in Enum.GetValues(typeof(QualityCategory))) { - while (enumerator.MoveNext()) - { - QualityCategory item = (QualityCategory)((byte)enumerator.Current); - QualityUtility.AllQualityCategories.Add(item); - } + QualityUtility.AllQualityCategories.Add((QualityCategory)value); } } @@ -43,26 +38,46 @@ public static string GetLabel(this QualityCategory cat) switch (cat) { case QualityCategory.Awful: + { return "QualityCategory_Awful".Translate(); + } case QualityCategory.Shoddy: + { return "QualityCategory_Shoddy".Translate(); + } case QualityCategory.Poor: + { return "QualityCategory_Poor".Translate(); + } case QualityCategory.Normal: + { return "QualityCategory_Normal".Translate(); + } case QualityCategory.Good: + { return "QualityCategory_Good".Translate(); - case QualityCategory.Superior: - return "QualityCategory_Superior".Translate(); + } case QualityCategory.Excellent: + { return "QualityCategory_Excellent".Translate(); + } + case QualityCategory.Superior: + { + return "QualityCategory_Superior".Translate(); + } case QualityCategory.Masterwork: + { return "QualityCategory_Masterwork".Translate(); + } case QualityCategory.Legendary: + { return "QualityCategory_Legendary".Translate(); + } default: + { throw new ArgumentException(); } + } } public static string GetLabelShort(this QualityCategory cat) @@ -70,36 +85,64 @@ public static string GetLabelShort(this QualityCategory cat) switch (cat) { case QualityCategory.Awful: + { return "QualityCategoryShort_Awful".Translate(); + } case QualityCategory.Shoddy: + { return "QualityCategoryShort_Shoddy".Translate(); + } case QualityCategory.Poor: + { return "QualityCategoryShort_Poor".Translate(); + } case QualityCategory.Normal: + { return "QualityCategoryShort_Normal".Translate(); + } case QualityCategory.Good: + { return "QualityCategoryShort_Good".Translate(); - case QualityCategory.Superior: - return "QualityCategoryShort_Superior".Translate(); + } case QualityCategory.Excellent: + { return "QualityCategoryShort_Excellent".Translate(); + } + case QualityCategory.Superior: + { + return "QualityCategoryShort_Superior".Translate(); + } case QualityCategory.Masterwork: + { return "QualityCategoryShort_Masterwork".Translate(); + } case QualityCategory.Legendary: + { return "QualityCategoryShort_Legendary".Translate(); + } default: + { throw new ArgumentException(); } + } } public static bool FollowQualityThingFilter(this ThingDef def) { - return def.stackLimit == 1 || def.HasComp(typeof(CompQuality)); + if (def.stackLimit == 1) + { + return true; + } + if (def.HasComp(typeof(CompQuality))) + { + return true; + } + return false; } public static QualityCategory RandomQuality() { - return QualityUtility.AllQualityCategories.RandomElement(); + return QualityUtility.AllQualityCategories.RandomElement(); } public static QualityCategory RandomCreationQuality(int relevantSkillLevel) @@ -108,83 +151,125 @@ public static QualityCategory RandomCreationQuality(int relevantSkillLevel) switch (relevantSkillLevel) { case 0: + { centerX = 0.167f; break; + } case 1: + { centerX = 0.5f; break; + } case 2: + { centerX = 0.833f; break; + } case 3: + { centerX = 1.166f; break; + } case 4: + { centerX = 1.5f; break; + } case 5: + { centerX = 1.833f; break; + } case 6: + { centerX = 2.166f; break; + } case 7: + { centerX = 2.5f; break; + } case 8: + { centerX = 2.833f; break; + } case 9: + { centerX = 3.166f; break; + } case 10: + { centerX = 3.5f; break; + } case 11: + { centerX = 3.75f; break; + } case 12: + { centerX = 4f; break; + } case 13: + { centerX = 4.25f; break; + } case 14: + { centerX = 4.5f; break; + } case 15: + { centerX = 4.7f; break; + } case 16: + { centerX = 4.9f; break; + } case 17: + { centerX = 5.1f; break; + } case 18: + { centerX = 5.3f; break; + } case 19: + { centerX = 5.5f; break; + } case 20: + { centerX = 5.7f; break; } - float num = Rand.Gaussian(centerX, 1.25f); - num = Mathf.Clamp(num, 0f, (float)QualityUtility.AllQualityCategories.Count - 0.5f); - return (QualityCategory)((int)num); + } + float value = Rand.Gaussian(centerX, 1.25f); + value = Mathf.Clamp(value, 0f, (float)((float)QualityUtility.AllQualityCategories.Count - 0.5)); + return (QualityCategory)(byte)(int)value; } public static QualityCategory RandomTraderItemQuality() { - if (Rand.Value < 0.25f) + if (Rand.Value < 0.25) { return QualityCategory.Normal; } - float num = Rand.Gaussian(3.5f, 1.13f); - num = Mathf.Clamp(num, 0f, (float)QualityUtility.AllQualityCategories.Count - 0.5f); - return (QualityCategory)((int)num); + float value = Rand.Gaussian(3.5f, 1.13f); + value = Mathf.Clamp(value, 0f, (float)((float)QualityUtility.AllQualityCategories.Count - 0.5)); + return (QualityCategory)(byte)(int)value; } public static QualityCategory RandomBaseGenItemQuality() @@ -198,28 +283,33 @@ public static QualityCategory RandomGeneratedGearQuality(PawnKindDef pawnKind) { return QualityCategory.Normal; } - if (Rand.Value < 0.25f) + if (Rand.Value < 0.25) { return pawnKind.itemQuality; } - float centerX = (float)pawnKind.itemQuality + 0.5f; - float num = Rand.GaussianAsymmetric(centerX, 1.25f, 1.07f); - num = Mathf.Clamp(num, 0f, (float)QualityUtility.AllQualityCategories.Count - 0.5f); - return (QualityCategory)((int)num); + float centerX = (float)((float)(int)pawnKind.itemQuality + 0.5); + float value = Rand.GaussianAsymmetric(centerX, 1.25f, 1.07f); + value = Mathf.Clamp(value, 0f, (float)((float)QualityUtility.AllQualityCategories.Count - 0.5)); + return (QualityCategory)(byte)(int)value; } internal static void LogGenerationData() { StringBuilder stringBuilder = new StringBuilder(); stringBuilder.AppendLine("Qualities for trader items"); - stringBuilder.AppendLine(QualityUtility.DebugQualitiesString(() => QualityUtility.RandomTraderItemQuality())); - foreach (PawnKindDef pk in DefDatabase.AllDefs) + stringBuilder.AppendLine(QualityUtility.DebugQualitiesString((Func)(() => QualityUtility.RandomTraderItemQuality()))); + using (IEnumerator enumerator = DefDatabase.AllDefs.GetEnumerator()) { - if (pk.RaceProps.Humanlike) + PawnKindDef pk; + while (enumerator.MoveNext()) { - stringBuilder.AppendLine("Qualities for items generated for pawn kind " + pk.defName); - stringBuilder.Append(QualityUtility.DebugQualitiesString(() => QualityUtility.RandomGeneratedGearQuality(pk))); - stringBuilder.AppendLine(); + pk = enumerator.Current; + if (pk.RaceProps.Humanlike) + { + stringBuilder.AppendLine("Qualities for items generated for pawn kind " + pk.defName); + stringBuilder.Append(QualityUtility.DebugQualitiesString((Func)(() => QualityUtility.RandomGeneratedGearQuality(pk)))); + stringBuilder.AppendLine(); + } } } int level; @@ -227,7 +317,7 @@ internal static void LogGenerationData() { stringBuilder.AppendLine(); stringBuilder.AppendLine("Creation qualities for worker at level " + level); - stringBuilder.Append(QualityUtility.DebugQualitiesString(() => QualityUtility.RandomCreationQuality(level))); + stringBuilder.Append(QualityUtility.DebugQualitiesString((Func)(() => QualityUtility.RandomCreationQuality(level)))); } Log.Message(stringBuilder.ToString()); } @@ -240,11 +330,21 @@ private static string DebugQualitiesString(Func qualityGenerato { list.Add(qualityGenerator()); } - foreach (QualityCategory qu in QualityUtility.AllQualityCategories) + List.Enumerator enumerator = QualityUtility.AllQualityCategories.GetEnumerator(); + try + { + QualityCategory qu; + while (enumerator.MoveNext()) + { + qu = enumerator.Current; + stringBuilder.AppendLine(((Enum)(object)qu).ToString() + " - " + (from q in list + where q == qu + select q).Count().ToString()); + } + } + finally { - stringBuilder.AppendLine(qu.ToString() + " - " + (from q in list - where q == qu - select q).Count().ToString()); + ((IDisposable)(object)enumerator).Dispose(); } return stringBuilder.ToString(); } diff --git a/Assembly-CSharp/RimWorld/QueuedIncident.cs b/Assembly-CSharp/RimWorld/QueuedIncident.cs index b72e04c68..c3bd24c6f 100644 --- a/Assembly-CSharp/RimWorld/QueuedIncident.cs +++ b/Assembly-CSharp/RimWorld/QueuedIncident.cs @@ -1,4 +1,3 @@ -using System; using Verse; namespace RimWorld diff --git a/Assembly-CSharp/RimWorld/RCellFinder.cs b/Assembly-CSharp/RimWorld/RCellFinder.cs index 6fa31df4e..952d32f98 100644 --- a/Assembly-CSharp/RimWorld/RCellFinder.cs +++ b/Assembly-CSharp/RimWorld/RCellFinder.cs @@ -16,7 +16,7 @@ public static class RCellFinder public static IntVec3 BestOrderedGotoDestNear(IntVec3 root, Pawn searcher) { Map map = searcher.Map; - Predicate predicate = (IntVec3 c) => !map.pawnDestinationManager.DestinationIsReserved(c, searcher) && c.Standable(map) && searcher.CanReach(c, PathEndMode.OnCell, Danger.Deadly, false, TraverseMode.ByPawn); + Predicate predicate = (Predicate)((IntVec3 c) => !map.pawnDestinationManager.DestinationIsReserved(c, searcher) && c.Standable(map) && searcher.CanReach(c, PathEndMode.OnCell, Danger.Deadly, false, TraverseMode.ByPawn)); if (predicate(root)) { return root; @@ -39,9 +39,7 @@ public static IntVec3 BestOrderedGotoDestNear(IntVec3 root, Pawn searcher) } } if (num >= 8 && flag) - { break; - } num++; } return result; @@ -51,7 +49,7 @@ public static bool TryFindBestExitSpot(Pawn pawn, out IntVec3 spot, TraverseMode { if (mode == TraverseMode.PassAllDestroyableThings && !pawn.Map.reachability.CanReachMapEdge(pawn.Position, TraverseParms.For(pawn, Danger.Deadly, TraverseMode.ByPawn, true))) { - return RCellFinder.TryFindRandomPawnEntryCell(out spot, pawn.Map, 0f, delegate(IntVec3 x) + return RCellFinder.TryFindRandomPawnEntryCell(out spot, pawn.Map, 0f, (Predicate)delegate(IntVec3 x) { TraverseMode mode2 = mode; return pawn.CanReach(x, PathEndMode.OnCell, Danger.Deadly, false, mode2); @@ -65,38 +63,41 @@ public static bool TryFindBestExitSpot(Pawn pawn, out IntVec3 spot, TraverseMode num2++; if (num2 > 30) { - break; + spot = pawn.Position; + return false; } - IntVec3 intVec; - bool flag = CellFinder.TryFindRandomCellNear(pawn.Position, pawn.Map, num, null, out intVec); + IntVec3 intVec = default(IntVec3); + bool flag = CellFinder.TryFindRandomCellNear(pawn.Position, pawn.Map, num, (Predicate)null, out intVec); num += 4; if (flag) { int num3 = intVec.x; intVec2 = new IntVec3(0, 0, intVec.z); - if (pawn.Map.Size.z - intVec.z < num3) + IntVec3 size = pawn.Map.Size; + if (size.z - intVec.z < num3) { - num3 = pawn.Map.Size.z - intVec.z; - intVec2 = new IntVec3(intVec.x, 0, pawn.Map.Size.z - 1); + IntVec3 size2 = pawn.Map.Size; + num3 = size2.z - intVec.z; + int x2 = intVec.x; + IntVec3 size3 = pawn.Map.Size; + intVec2 = new IntVec3(x2, 0, size3.z - 1); } - if (pawn.Map.Size.x - intVec.x < num3) + IntVec3 size4 = pawn.Map.Size; + if (size4.x - intVec.x < num3) { - num3 = pawn.Map.Size.x - intVec.x; - intVec2 = new IntVec3(pawn.Map.Size.x - 1, 0, intVec.z); + IntVec3 size5 = pawn.Map.Size; + num3 = size5.x - intVec.x; + IntVec3 size6 = pawn.Map.Size; + intVec2 = new IntVec3(size6.x - 1, 0, intVec.z); } if (intVec.z < num3) { intVec2 = new IntVec3(intVec.x, 0, 0); } if (intVec2.Standable(pawn.Map) && pawn.CanReach(intVec2, PathEndMode.OnCell, Danger.Deadly, true, mode)) - { - goto Block_9; - } + break; } } - spot = pawn.Position; - return false; - Block_9: spot = intVec2; return true; } @@ -105,13 +106,16 @@ public static bool TryFindRandomExitSpot(Pawn pawn, out IntVec3 spot, TraverseMo { Danger maxDanger = Danger.Some; int num = 0; + goto IL_0004; + IL_0004: IntVec3 intVec; while (true) { num++; if (num > 40) { - break; + spot = pawn.Position; + return false; } if (num > 15) { @@ -125,7 +129,8 @@ public static bool TryFindRandomExitSpot(Pawn pawn, out IntVec3 spot, TraverseMo } if (num2 == 1) { - intVec.x = pawn.Map.Size.x - 1; + IntVec3 size = pawn.Map.Size; + intVec.x = size.x - 1; } if (num2 == 2) { @@ -133,42 +138,30 @@ public static bool TryFindRandomExitSpot(Pawn pawn, out IntVec3 spot, TraverseMo } if (num2 == 3) { - intVec.z = pawn.Map.Size.z - 1; - } - if (intVec.Standable(pawn.Map)) - { - if (pawn.CanReach(intVec, PathEndMode.OnCell, maxDanger, false, mode)) - { - goto IL_D5; - } + IntVec3 size2 = pawn.Map.Size; + intVec.z = size2.z - 1; } + if (intVec.Standable(pawn.Map) && pawn.CanReach(intVec, PathEndMode.OnCell, maxDanger, false, mode)) + break; } - spot = pawn.Position; - return false; - IL_D5: spot = intVec; return true; + IL_00de: + goto IL_0004; } public static IntVec3 RandomWanderDestFor(Pawn pawn, IntVec3 root, float radius, Func validator, Danger maxDanger) { - if (radius > 12f) + if (radius > 12.0) { - Log.Warning(string.Concat(new object[] - { - "wanderRadius of ", - radius, - " is greater than Region.GridSize of ", - 12, - " and will break." - })); + Log.Warning("wanderRadius of " + radius + " is greater than Region.GridSize of " + 12 + " and will break."); } if (root.GetRegion(pawn.Map, RegionType.Set_Passable) == null) { return root; } int maxRegions = Mathf.Max((int)radius / 3, 13); - CellFinder.AllRegionsNear(RCellFinder.regions, root.GetRegion(pawn.Map, RegionType.Set_Passable), maxRegions, TraverseParms.For(pawn, Danger.Deadly, TraverseMode.ByPawn, false), (Region reg) => reg.extentsClose.ClosestDistSquaredTo(root) <= radius * radius, null, RegionType.Set_Passable); + CellFinder.AllRegionsNear(RCellFinder.regions, root.GetRegion(pawn.Map, RegionType.Set_Passable), maxRegions, TraverseParms.For(pawn, Danger.Deadly, TraverseMode.ByPawn, false), (Predicate)((Region reg) => reg.extentsClose.ClosestDistSquaredTo(root) <= radius * radius), null, RegionType.Set_Passable); bool flag = UnityData.isDebugBuild && DebugViewSettings.drawDestSearch; if (flag) { @@ -178,33 +171,32 @@ public static IntVec3 RandomWanderDestFor(Pawn pawn, IntVec3 root, float radius, { for (int i = 0; i < 20; i++) { - IntVec3 randomCell = RCellFinder.regions.RandomElementByWeightWithFallback((Region reg) => (float)reg.CellCount, null).RandomCell; + IntVec3 randomCell = RCellFinder.regions.RandomElementByWeightWithFallback((Func)((Region reg) => (float)reg.CellCount), null).RandomCell; if ((float)randomCell.DistanceToSquared(root) > radius * radius) { if (flag) { pawn.Map.debugDrawer.FlashCell(randomCell, 0.32f, "distance"); } + continue; } - else + if (!RCellFinder.CanWanderToCell(randomCell, pawn, root, validator, i, maxDanger)) { - if (RCellFinder.CanWanderToCell(randomCell, pawn, root, validator, i, maxDanger)) - { - if (flag) - { - pawn.Map.debugDrawer.FlashCell(randomCell, 0.9f, "go!"); - } - return randomCell; - } if (flag) { pawn.Map.debugDrawer.FlashCell(randomCell, 0.6f, "validation"); } + continue; } + if (flag) + { + pawn.Map.debugDrawer.FlashCell(randomCell, 0.9f, "go!"); + } + return randomCell; } } - IntVec3 position; - if (!CellFinder.TryFindRandomCellNear(root, pawn.Map, 20, (IntVec3 c) => c.InBounds(pawn.Map) && pawn.CanReach(c, PathEndMode.OnCell, Danger.None, false, TraverseMode.ByPawn) && !c.IsForbidden(pawn), out position) && !CellFinder.TryFindRandomCellNear(root, pawn.Map, 30, (IntVec3 c) => c.InBounds(pawn.Map) && pawn.CanReach(c, PathEndMode.OnCell, Danger.Deadly, false, TraverseMode.ByPawn), out position) && !CellFinder.TryFindRandomCellNear(pawn.Position, pawn.Map, 5, (IntVec3 c) => c.InBounds(pawn.Map) && pawn.CanReach(c, PathEndMode.OnCell, Danger.Deadly, false, TraverseMode.ByPawn), out position)) + IntVec3 position = default(IntVec3); + if (!CellFinder.TryFindRandomCellNear(root, pawn.Map, 20, (Predicate)((IntVec3 c) => c.InBounds(pawn.Map) && pawn.CanReach(c, PathEndMode.OnCell, Danger.None, false, TraverseMode.ByPawn) && !c.IsForbidden(pawn)), out position) && !CellFinder.TryFindRandomCellNear(root, pawn.Map, 30, (Predicate)((IntVec3 c) => c.InBounds(pawn.Map) && pawn.CanReach(c, PathEndMode.OnCell, Danger.Deadly, false, TraverseMode.ByPawn)), out position) && !CellFinder.TryFindRandomCellNear(pawn.Position, pawn.Map, 5, (Predicate)((IntVec3 c) => c.InBounds(pawn.Map) && pawn.CanReach(c, PathEndMode.OnCell, Danger.Deadly, false, TraverseMode.ByPawn)), out position)) { position = pawn.Position; } @@ -276,7 +268,7 @@ private static bool CanWanderToCell(IntVec3 c, Pawn pawn, IntVec3 root, Func Danger.None) + if ((int)c.GetDangerFor(pawn, pawn.Map) > 1) { if (flag) { @@ -301,7 +293,7 @@ private static bool CanWanderToCell(IntVec3 c, Pawn pawn, IntVec3 root, Func extraValidator = null) { - return CellFinder.TryFindRandomEdgeCellWith((IntVec3 c) => c.Standable(map) && !map.roofGrid.Roofed(c) && map.reachability.CanReachColony(c) && c.GetRoom(map, RegionType.Set_Passable).TouchesMapEdge && (extraValidator == null || extraValidator(c)), map, roadChance, out result); + return CellFinder.TryFindRandomEdgeCellWith((Predicate)((IntVec3 c) => c.Standable(map) && !map.roofGrid.Roofed(c) && map.reachability.CanReachColony(c) && c.GetRoom(map, RegionType.Set_Passable).TouchesMapEdge && ((object)extraValidator == null || extraValidator(c))), map, roadChance, out result); } public static bool TryFindPrisonerReleaseCell(Pawn prisoner, Pawn warden, out IntVec3 result) @@ -387,7 +377,7 @@ public static bool TryFindPrisonerReleaseCell(Pawn prisoner, Pawn warden, out In TraverseParms traverseParms = TraverseParms.For(warden, Danger.Deadly, TraverseMode.ByPawn, false); bool needMapEdge = prisoner.Faction != warden.Faction; IntVec3 foundResult = IntVec3.Invalid; - RegionProcessor regionProcessor = delegate(Region r) + RegionProcessor regionProcessor = (RegionProcessor)delegate(Region r) { if (needMapEdge) { @@ -403,7 +393,7 @@ public static bool TryFindPrisonerReleaseCell(Pawn prisoner, Pawn warden, out In foundResult = r.RandomCell; return true; }; - RegionTraverser.BreadthFirstTraverse(region, (Region from, Region r) => r.Allows(traverseParms, false), regionProcessor, 999, RegionType.Set_Passable); + RegionTraverser.BreadthFirstTraverse(region, (RegionEntryPredicate)((Region from, Region r) => r.Allows(traverseParms, false)), regionProcessor, 999, RegionType.Set_Passable); if (foundResult.IsValid) { result = foundResult; @@ -415,7 +405,7 @@ public static bool TryFindPrisonerReleaseCell(Pawn prisoner, Pawn warden, out In public static bool TryFindRandomCellToPlantInFromOffMap(ThingDef plantDef, Map map, out IntVec3 plantCell) { - Predicate validator = delegate(IntVec3 c) + Predicate validator = (Predicate)delegate(IntVec3 c) { if (c.Roofed(map)) { @@ -426,7 +416,11 @@ public static bool TryFindRandomCellToPlantInFromOffMap(ThingDef plantDef, Map m return false; } Room room = c.GetRoom(map, RegionType.Set_Passable); - return room != null && room.TouchesMapEdge; + if (room != null && room.TouchesMapEdge) + { + return true; + } + return false; }; return CellFinder.TryFindRandomEdgeCellWith(validator, map, CellFinder.EdgeRoadChance_Animal, out plantCell); } @@ -436,7 +430,7 @@ public static IntVec3 RandomAnimalSpawnCell_MapGen(Map map) int numStand = 0; int numRoom = 0; int numTouch = 0; - Predicate validator = delegate(IntVec3 c) + Predicate validator = (Predicate)delegate(IntVec3 c) { if (!c.Standable(map)) { @@ -460,34 +454,22 @@ public static IntVec3 RandomAnimalSpawnCell_MapGen(Map map) } return true; }; - IntVec3 intVec; + IntVec3 intVec = default(IntVec3); if (!CellFinderLoose.TryGetRandomCellWith(validator, map, 1000, out intVec)) { intVec = CellFinder.RandomCell(map); - Log.Warning(string.Concat(new object[] - { - "RandomAnimalSpawnCell_MapGen failed: numStand=", - numStand, - ", numRoom=", - numRoom, - ", numTouch=", - numTouch, - ". PlayerStartSpot=", - MapGenerator.PlayerStartSpot, - ". Returning ", - intVec - })); + Log.Warning("RandomAnimalSpawnCell_MapGen failed: numStand=" + numStand + ", numRoom=" + numRoom + ", numTouch=" + numTouch + ". PlayerStartSpot=" + MapGenerator.PlayerStartSpot + ". Returning " + intVec); } return intVec; } public static bool TryFindSkygazeCell(IntVec3 root, Pawn searcher, out IntVec3 result) { - Predicate cellValidator = (IntVec3 c) => !c.Roofed(searcher.Map) && !c.GetTerrain(searcher.Map).avoidWander; + Predicate cellValidator = (Predicate)((IntVec3 c) => !c.Roofed(searcher.Map) && !c.GetTerrain(searcher.Map).avoidWander); IntVec3 unused; - Predicate validator = (Region r) => r.Room.PsychologicallyOutdoors && !r.IsForbiddenEntirely(searcher) && r.TryFindRandomCellInRegionUnforbidden(searcher, cellValidator, out unused); + Predicate validator = (Predicate)((Region r) => r.Room.PsychologicallyOutdoors && !r.IsForbiddenEntirely(searcher) && r.TryFindRandomCellInRegionUnforbidden(searcher, cellValidator, out unused)); TraverseParms traverseParms = TraverseParms.For(searcher, Danger.Deadly, TraverseMode.ByPawn, false); - Region root2; + Region root2 = default(Region); if (!CellFinder.TryFindClosestRegionWith(root.GetRegion(searcher.Map, RegionType.Set_Passable), traverseParms, validator, 300, out root2, RegionType.Set_Passable)) { result = root; @@ -501,188 +483,221 @@ public static bool TryFindTravelDestFrom(IntVec3 root, Map map, out IntVec3 trav { travelDest = root; bool flag = false; - Predicate cellValidator = (IntVec3 c) => map.reachability.CanReach(root, c, PathEndMode.OnCell, TraverseMode.NoPassClosedDoors, Danger.None) && !map.roofGrid.Roofed(c); + Predicate cellValidator = (Predicate)((IntVec3 c) => map.reachability.CanReach(root, c, PathEndMode.OnCell, TraverseMode.NoPassClosedDoors, Danger.None) && !map.roofGrid.Roofed(c)); if (root.x == 0) { - flag = CellFinder.TryFindRandomEdgeCellWith((IntVec3 c) => c.x == map.Size.x - 1 && cellValidator(c), map, CellFinder.EdgeRoadChance_Always, out travelDest); - } - else if (root.x == map.Size.x - 1) - { - flag = CellFinder.TryFindRandomEdgeCellWith((IntVec3 c) => c.x == 0 && cellValidator(c), map, CellFinder.EdgeRoadChance_Always, out travelDest); - } - else if (root.z == 0) - { - flag = CellFinder.TryFindRandomEdgeCellWith((IntVec3 c) => c.z == map.Size.z - 1 && cellValidator(c), map, CellFinder.EdgeRoadChance_Always, out travelDest); + flag = CellFinder.TryFindRandomEdgeCellWith((Predicate)delegate(IntVec3 c) + { + int x2 = c.x; + IntVec3 size4 = map.Size; + return x2 == size4.x - 1 && cellValidator(c); + }, map, CellFinder.EdgeRoadChance_Always, out travelDest); } - else if (root.z == map.Size.z - 1) + else { - flag = CellFinder.TryFindRandomEdgeCellWith((IntVec3 c) => c.z == 0 && cellValidator(c), map, CellFinder.EdgeRoadChance_Always, out travelDest); + int x = root.x; + IntVec3 size = map.Size; + if (x == size.x - 1) + { + flag = CellFinder.TryFindRandomEdgeCellWith((Predicate)((IntVec3 c) => c.x == 0 && cellValidator(c)), map, CellFinder.EdgeRoadChance_Always, out travelDest); + } + else if (root.z == 0) + { + flag = CellFinder.TryFindRandomEdgeCellWith((Predicate)delegate(IntVec3 c) + { + int z2 = c.z; + IntVec3 size3 = map.Size; + return z2 == size3.z - 1 && cellValidator(c); + }, map, CellFinder.EdgeRoadChance_Always, out travelDest); + } + else + { + int z = root.z; + IntVec3 size2 = map.Size; + if (z == size2.z - 1) + { + flag = CellFinder.TryFindRandomEdgeCellWith((Predicate)((IntVec3 c) => c.z == 0 && cellValidator(c)), map, CellFinder.EdgeRoadChance_Always, out travelDest); + } + } } if (!flag) { - flag = CellFinder.TryFindRandomEdgeCellWith((IntVec3 c) => (c - root).LengthHorizontalSquared > 10000 && cellValidator(c), map, CellFinder.EdgeRoadChance_Always, out travelDest); + flag = CellFinder.TryFindRandomEdgeCellWith((Predicate)((IntVec3 c) => (c - root).LengthHorizontalSquared > 10000 && cellValidator(c)), map, CellFinder.EdgeRoadChance_Always, out travelDest); } if (!flag) { - flag = CellFinder.TryFindRandomEdgeCellWith((IntVec3 c) => (c - root).LengthHorizontalSquared > 2500 && cellValidator(c), map, CellFinder.EdgeRoadChance_Always, out travelDest); + flag = CellFinder.TryFindRandomEdgeCellWith((Predicate)((IntVec3 c) => (c - root).LengthHorizontalSquared > 2500 && cellValidator(c)), map, CellFinder.EdgeRoadChance_Always, out travelDest); } return flag; } public static bool TryFindRandomSpotJustOutsideColony(IntVec3 originCell, Map map, out IntVec3 result) { - return RCellFinder.TryFindRandomSpotJustOutsideColony(originCell, map, null, out result, null); + return RCellFinder.TryFindRandomSpotJustOutsideColony(originCell, map, (Pawn)null, out result, (Predicate)null); } public static bool TryFindRandomSpotJustOutsideColony(Pawn searcher, out IntVec3 result) { - return RCellFinder.TryFindRandomSpotJustOutsideColony(searcher.Position, searcher.Map, searcher, out result, null); + return RCellFinder.TryFindRandomSpotJustOutsideColony(searcher.Position, searcher.Map, searcher, out result, (Predicate)null); } public static bool TryFindRandomSpotJustOutsideColony(IntVec3 root, Map map, Pawn searcher, out IntVec3 result, Predicate extraValidator = null) { bool desperate = false; int minColonyBuildingsLOS = 0; - Predicate validator = delegate(IntVec3 c) + Predicate validator = (Predicate)delegate(IntVec3 c) { if (!c.Standable(map)) { return false; } Room room = c.GetRoom(map, RegionType.Set_Passable); - if (!room.PsychologicallyOutdoors || !room.TouchesMapEdge) - { - return false; - } - if (room == null || room.CellCount < 25) + if (room.PsychologicallyOutdoors && room.TouchesMapEdge) { - return false; - } - if (!desperate && !map.reachability.CanReachColony(c)) - { - return false; - } - if (extraValidator != null && !extraValidator(c)) - { - return false; - } - if (minColonyBuildingsLOS > 0) - { - int colonyBuildingsLOSFound = 0; - RCellFinder.tmpBuildings.Clear(); - RegionTraverser.BreadthFirstTraverse(c, map, (Region from, Region to) => true, delegate(Region reg) + if (room != null && room.CellCount >= 25) { - Faction ofPlayer = Faction.OfPlayer; - List list = reg.ListerThings.ThingsInGroup(ThingRequestGroup.BuildingArtificial); - for (int l = 0; l < list.Count; l++) + if (!desperate && !map.reachability.CanReachColony(c)) + { + return false; + } + if ((object)extraValidator != null && !extraValidator(c)) { - Thing thing = list[l]; - if (thing.Faction == ofPlayer && thing.Position.InHorDistOf(c, 16f) && GenSight.LineOfSight(thing.Position, c, map, true, null, 0, 0) && !RCellFinder.tmpBuildings.Contains(thing)) + return false; + } + if (minColonyBuildingsLOS > 0) + { + int colonyBuildingsLOSFound = 0; + RCellFinder.tmpBuildings.Clear(); + RegionTraverser.BreadthFirstTraverse(c, map, (RegionEntryPredicate)((Region from, Region to) => true), (RegionProcessor)delegate(Region reg) { - RCellFinder.tmpBuildings.Add(thing); - colonyBuildingsLOSFound++; - if (colonyBuildingsLOSFound >= minColonyBuildingsLOS) + Faction ofPlayer = Faction.OfPlayer; + List list = reg.ListerThings.ThingsInGroup(ThingRequestGroup.BuildingArtificial); + for (int i = 0; i < list.Count; i++) { - return true; + Thing thing = list[i]; + if (thing.Faction == ofPlayer && thing.Position.InHorDistOf(c, 16f) && GenSight.LineOfSight(thing.Position, c, map, true, null, 0, 0) && !RCellFinder.tmpBuildings.Contains(thing)) + { + RCellFinder.tmpBuildings.Add(thing); + colonyBuildingsLOSFound++; + if (colonyBuildingsLOSFound >= minColonyBuildingsLOS) + { + return true; + } + } } + return false; + }, 12, RegionType.Set_Passable); + RCellFinder.tmpBuildings.Clear(); + if (colonyBuildingsLOSFound < minColonyBuildingsLOS) + { + return false; } } - return false; - }, 12, RegionType.Set_Passable); - RCellFinder.tmpBuildings.Clear(); - if (colonyBuildingsLOSFound < minColonyBuildingsLOS) - { - return false; - } - } - if (root.IsValid) - { - TraverseParms traverseParams = (searcher == null) ? TraverseMode.PassDoors : TraverseParms.For(searcher, Danger.Deadly, TraverseMode.ByPawn, false); - if (!map.reachability.CanReach(root, c, PathEndMode.Touch, traverseParams)) - { - return false; + if (root.IsValid) + { + TraverseParms traverseParams = (searcher == null) ? TraverseMode.PassDoors : TraverseParms.For(searcher, Danger.Deadly, TraverseMode.ByPawn, false); + if (!map.reachability.CanReach(root, c, PathEndMode.Touch, traverseParams)) + { + return false; + } + } + return true; } + return false; } - return true; + return false; }; - for (int i = 0; i < 100; i++) + int num = 0; + while (num < 100) { Building building = null; - if (!(from b in map.listerBuildings.allBuildingsColonist + if ((from b in map.listerBuildings.allBuildingsColonist where b.def.designationCategory != DesignationCategoryDefOf.Structure && b.def.building.ai_chillDestination - select b).TryRandomElement(out building)) - { - break; - } - if (i < 10) - { - minColonyBuildingsLOS = 4; - } - else if (i < 25) - { - minColonyBuildingsLOS = 3; - } - else if (i < 40) - { - minColonyBuildingsLOS = 2; - } - else - { - minColonyBuildingsLOS = 1; - } - int squareRadius = 10 + i / 5; - desperate = (i > 60); - if (CellFinder.TryFindRandomCellNear(building.Position, map, squareRadius, validator, out result)) + select b).TryRandomElement(out building)) { - return true; + if (num < 10) + { + minColonyBuildingsLOS = 4; + } + else if (num < 25) + { + minColonyBuildingsLOS = 3; + } + else if (num < 40) + { + minColonyBuildingsLOS = 2; + } + else + { + minColonyBuildingsLOS = 1; + } + int squareRadius = 10 + num / 5; + desperate = (num > 60); + if (CellFinder.TryFindRandomCellNear(building.Position, map, squareRadius, validator, out result)) + { + return true; + } + num++; + continue; } + break; } - for (int j = 0; j < 50; j++) + int num2 = 0; + while (num2 < 50) { Building building2 = null; - if (!map.listerBuildings.allBuildingsColonist.TryRandomElement(out building2)) - { - break; - } - if (j < 10) - { - minColonyBuildingsLOS = 3; - } - else if (j < 20) - { - minColonyBuildingsLOS = 2; - } - else if (j < 30) - { - minColonyBuildingsLOS = 1; - } - else - { - minColonyBuildingsLOS = 0; - } - desperate = (j > 20); - if (CellFinder.TryFindRandomCellNear(building2.Position, map, 14, validator, out result)) + if (((IEnumerable)map.listerBuildings.allBuildingsColonist).TryRandomElement(out building2)) { - return true; + if (num2 < 10) + { + minColonyBuildingsLOS = 3; + } + else if (num2 < 20) + { + minColonyBuildingsLOS = 2; + } + else if (num2 < 30) + { + minColonyBuildingsLOS = 1; + } + else + { + minColonyBuildingsLOS = 0; + } + desperate = (num2 > 20); + if (CellFinder.TryFindRandomCellNear(building2.Position, map, 14, validator, out result)) + { + return true; + } + num2++; + continue; } + break; } - for (int k = 0; k < 100; k++) + int num3 = 0; + while (num3 < 100) { Pawn pawn = null; - if (!map.mapPawns.FreeColonistsAndPrisonersSpawned.TryRandomElement(out pawn)) - { - break; - } - minColonyBuildingsLOS = 0; - desperate = (k > 50); - if (CellFinder.TryFindRandomCellNear(pawn.Position, map, 14, validator, out result)) + if (map.mapPawns.FreeColonistsAndPrisonersSpawned.TryRandomElement(out pawn)) { - return true; + minColonyBuildingsLOS = 0; + desperate = (num3 > 50); + if (CellFinder.TryFindRandomCellNear(pawn.Position, map, 14, validator, out result)) + { + return true; + } + num3++; + continue; } + break; } desperate = true; minColonyBuildingsLOS = 0; - return CellFinderLoose.TryGetRandomCellWith(validator, map, 1000, out result); + if (CellFinderLoose.TryGetRandomCellWith(validator, map, 1000, out result)) + { + return true; + } + return false; } public static bool TryFindRandomCellInRegionUnforbidden(this Region reg, Pawn pawn, Predicate validator, out IntVec3 result) @@ -696,7 +711,7 @@ public static bool TryFindRandomCellInRegionUnforbidden(this Region reg, Pawn pa result = IntVec3.Invalid; return false; } - return reg.TryFindRandomCellInRegion((IntVec3 c) => !c.IsForbidden(pawn) && (validator == null || validator(c)), out result); + return reg.TryFindRandomCellInRegion((Predicate)((IntVec3 c) => !c.IsForbidden(pawn) && ((object)validator == null || validator(c))), out result); } public static bool TryFindDirectFleeDestination(IntVec3 root, float dist, Pawn pawn, out IntVec3 result) @@ -716,9 +731,9 @@ public static bool TryFindDirectFleeDestination(IntVec3 root, float dist, Pawn p IntVec3 randomCell = region2.RandomCell; if (randomCell.Walkable(pawn.Map) && (float)(root - randomCell).LengthHorizontalSquared > dist * dist) { - using (PawnPath pawnPath = pawn.Map.pathFinder.FindPath(pawn.Position, randomCell, pawn, PathEndMode.OnCell)) + using (PawnPath path = pawn.Map.pathFinder.FindPath(pawn.Position, randomCell, pawn, PathEndMode.OnCell)) { - if (PawnPathUtility.TryFindCellAtIndex(pawnPath, (int)dist + 3, out result)) + if (PawnPathUtility.TryFindCellAtIndex(path, (int)dist + 3, out result)) { return true; } @@ -735,65 +750,83 @@ public static bool TryFindRandomCellOutsideColonyNearTheCenterOfTheMap(IntVec3 p CellRect cellRect = CellRect.CenteredOn(map.Center, num); cellRect.ClipInsideMap(map); List list = new List(); - if (minDistToColony > 0f) + if (minDistToColony > 0.0) { - foreach (Pawn current in map.mapPawns.FreeColonistsSpawned) + foreach (Pawn item in map.mapPawns.FreeColonistsSpawned) { - list.Add(current.Position); + list.Add(item.Position); } - foreach (Building current2 in map.listerBuildings.allBuildingsColonist) + List.Enumerator enumerator2 = map.listerBuildings.allBuildingsColonist.GetEnumerator(); + try { - list.Add(current2.Position); + while (enumerator2.MoveNext()) + { + Building current2 = enumerator2.Current; + list.Add(current2.Position); + } + } + finally + { + ((IDisposable)(object)enumerator2).Dispose(); } } float num2 = minDistToColony * minDistToColony; int num3 = 0; - IntVec3 randomCell; + goto IL_00c6; + IL_00c6: while (true) { num3++; if (num3 > 50) { - if (num > map.Size.x) + int num4 = num; + IntVec3 size = map.Size; + if (num4 <= size.x) { - break; + num = (int)((float)num * 1.5); + cellRect = CellRect.CenteredOn(map.Center, num); + cellRect.ClipInsideMap(map); + num3 = 0; + goto IL_0112; } - num = (int)((float)num * 1.5f); - cellRect = CellRect.CenteredOn(map.Center, num); - cellRect.ClipInsideMap(map); - num3 = 0; + break; } - randomCell = cellRect.RandomCell; - if (randomCell.Standable(map)) - { - if (map.reachability.CanReach(randomCell, pos, PathEndMode.ClosestTouch, TraverseMode.NoPassClosedDoors, Danger.Deadly)) + goto IL_0112; + IL_0112: + IntVec3 randomCell = cellRect.RandomCell; + if (!randomCell.Standable(map)) + continue; + if (!map.reachability.CanReach(randomCell, pos, PathEndMode.ClosestTouch, TraverseMode.NoPassClosedDoors, Danger.Deadly)) + continue; + bool flag = false; + int num5 = 0; + while (num5 < list.Count) + { + if (!((float)(list[num5] - randomCell).LengthHorizontalSquared < num2)) { - bool flag = false; - for (int i = 0; i < list.Count; i++) - { - if ((float)(list[i] - randomCell).LengthHorizontalSquared < num2) - { - flag = true; - break; - } - } - if (!flag) - { - goto IL_19F; - } + num5++; + continue; } + flag = true; + break; } + if (flag) + continue; + result = randomCell; + return true; } result = pos; return false; - IL_19F: - result = randomCell; - return true; + IL_01a9: + goto IL_00c6; } public static bool TryFindRandomCellNearTheCenterOfTheMapWith(Predicate validator, Map map, out IntVec3 result) { - int startingSearchRadius = Mathf.Clamp(Mathf.Max(map.Size.x, map.Size.z) / 20, 3, 25); + IntVec3 size = map.Size; + int x = size.x; + IntVec3 size2 = map.Size; + int startingSearchRadius = Mathf.Clamp(Mathf.Max(x, size2.z) / 20, 3, 25); return RCellFinder.TryFindRandomCellNearWith(map.Center, validator, map, out result, startingSearchRadius); } @@ -803,32 +836,37 @@ public static bool TryFindRandomCellNearWith(IntVec3 near, Predicate va CellRect cellRect = CellRect.CenteredOn(near, num); cellRect.ClipInsideMap(map); int num2 = 0; - IntVec3 randomCell; + goto IL_0016; + IL_0016: while (true) { num2++; if (num2 > 30) { - if (num > map.Size.x * 2 && num > map.Size.z * 2) + int num3 = num; + IntVec3 size = map.Size; + if (num3 > size.x * 2) { - break; + int num4 = num; + IntVec3 size2 = map.Size; + if (num4 > size2.z * 2) + break; } - num = (int)((float)num * 1.5f); + num = (int)((float)num * 1.5); cellRect = CellRect.CenteredOn(near, num); cellRect.ClipInsideMap(map); num2 = 0; } - randomCell = cellRect.RandomCell; - if (validator(randomCell)) - { - goto IL_8B; - } + IntVec3 randomCell = cellRect.RandomCell; + if (!validator(randomCell)) + continue; + result = randomCell; + return true; } result = near; return false; - IL_8B: - result = randomCell; - return true; + IL_0094: + goto IL_0016; } public static IntVec3 SpotToChewStandingNear(Pawn pawn, Thing ingestible) @@ -838,7 +876,7 @@ public static IntVec3 SpotToChewStandingNear(Pawn pawn, Thing ingestible) bool desperate = false; bool ignoreDanger = false; float maxDist = 4f; - Predicate validator = delegate(IntVec3 c) + Predicate validator = (Predicate)delegate(IntVec3 c) { if ((float)(root - c).LengthHorizontalSquared > maxDist * maxDist) { @@ -863,54 +901,81 @@ public static IntVec3 SpotToChewStandingNear(Pawn pawn, Thing ingestible) return false; } } - IntVec3 intVec2; - return (ignoreDanger || c.GetDangerFor(pawn, pawn.Map) == Danger.None) && !c.ContainsStaticFire(pawn.Map) && !c.ContainsTrap(pawn.Map) && !pawn.Map.pawnDestinationManager.DestinationIsReserved(c, pawn) && Toils_Ingest.TryFindAdjacentIngestionPlaceSpot(c, ingestible.def, pawn, out intVec2); + if (!ignoreDanger && c.GetDangerFor(pawn, pawn.Map) != Danger.None) + { + return false; + } + if (!c.ContainsStaticFire(pawn.Map) && !c.ContainsTrap(pawn.Map)) + { + if (pawn.Map.pawnDestinationManager.DestinationIsReserved(c, pawn)) + { + return false; + } + IntVec3 intVec2 = default(IntVec3); + if (!Toils_Ingest.TryFindAdjacentIngestionPlaceSpot(c, ingestible.def, pawn, out intVec2)) + { + return false; + } + return true; + } + return false; }; int maxRegions = 1; Region region = pawn.GetRegion(RegionType.Set_Passable); for (int i = 0; i < 30; i++) { - if (i == 1) + switch (i) + { + case 1: { desperate = true; + break; } - else if (i == 2) + case 2: { desperate = false; maxRegions = 4; + break; } - else if (i == 6) + case 6: { desperate = true; + break; } - else if (i == 10) + case 10: { desperate = false; maxDist = 8f; maxRegions = 12; + break; } - else if (i == 15) + case 15: { desperate = true; + break; } - else if (i == 20) + case 20: { maxDist = 15f; maxRegions = 16; + break; } - else if (i == 26) + case 26: { maxDist = 5f; maxRegions = 4; ignoreDanger = true; + break; } - else if (i == 29) + case 29: { maxDist = 15f; maxRegions = 16; + break; + } } Region reg = CellFinder.RandomRegionNear(region, maxRegions, TraverseParms.For(pawn, Danger.Deadly, TraverseMode.ByPawn, false), null, null, RegionType.Set_Passable); - IntVec3 intVec; + IntVec3 intVec = default(IntVec3); if (reg.TryFindRandomCellInRegionUnforbidden(pawn, validator, out intVec)) { if (DebugViewSettings.drawDestSearch) @@ -929,7 +994,7 @@ public static IntVec3 SpotToChewStandingNear(Pawn pawn, Thing ingestible) public static bool TryFindMarriageSite(Pawn firstFiance, Pawn secondFiance, out IntVec3 result) { - if (!firstFiance.CanReach(secondFiance, PathEndMode.ClosestTouch, Danger.Deadly, false, TraverseMode.ByPawn)) + if (!firstFiance.CanReach((Thing)secondFiance, PathEndMode.ClosestTouch, Danger.Deadly, false, TraverseMode.ByPawn)) { result = IntVec3.Invalid; return false; @@ -937,42 +1002,45 @@ public static bool TryFindMarriageSite(Pawn firstFiance, Pawn secondFiance, out Map map = firstFiance.Map; if ((from x in map.listerBuildings.AllBuildingsColonistOfDef(ThingDefOf.MarriageSpot) where MarriageSpotUtility.IsValidMarriageSpotFor(x.Position, firstFiance, secondFiance, null) - select x.Position).TryRandomElement(out result)) + select x.Position).TryRandomElement(out result)) { return true; } - Predicate noMarriageSpotValidator = delegate(IntVec3 cell) + Predicate noMarriageSpotValidator = (Predicate)delegate(IntVec3 cell) { IntVec3 c = cell + LordToil_MarriageCeremony.OtherFianceNoMarriageSpotCellOffset; if (!c.InBounds(map)) { return false; } - if (c.IsForbidden(firstFiance) || c.IsForbidden(secondFiance)) - { - return false; - } - if (!c.Standable(map)) + if (!c.IsForbidden(firstFiance) && !c.IsForbidden(secondFiance)) { - return false; + if (!c.Standable(map)) + { + return false; + } + Room room = cell.GetRoom(map, RegionType.Set_Passable); + if (room != null && !room.IsHuge && !room.PsychologicallyOutdoors && room.CellCount < 10) + { + return false; + } + return true; } - Room room = cell.GetRoom(map, RegionType.Set_Passable); - return room == null || room.IsHuge || room.PsychologicallyOutdoors || room.CellCount >= 10; + return false; }; - foreach (CompGatherSpot current in map.gatherSpotLister.activeSpots.InRandomOrder(null)) + foreach (CompGatherSpot item in map.gatherSpotLister.activeSpots.InRandomOrder(null)) { for (int i = 0; i < 10; i++) { - IntVec3 intVec = CellFinder.RandomClosewalkCellNear(current.parent.Position, current.parent.Map, 4, null); + IntVec3 intVec = CellFinder.RandomClosewalkCellNear(item.parent.Position, item.parent.Map, 4, null); if (MarriageSpotUtility.IsValidMarriageSpotFor(intVec, firstFiance, secondFiance, null) && noMarriageSpotValidator(intVec)) { result = intVec; - bool result2 = true; - return result2; + return true; } } } - if (CellFinder.TryFindRandomCellNear(firstFiance.Position, firstFiance.Map, 25, (IntVec3 cell) => MarriageSpotUtility.IsValidMarriageSpotFor(cell, firstFiance, secondFiance, null) && noMarriageSpotValidator(cell), out result)) + if (CellFinder.TryFindRandomCellNear(firstFiance.Position, firstFiance.Map, 25, (Predicate)((IntVec3 cell) => MarriageSpotUtility.IsValidMarriageSpotFor(cell, firstFiance, secondFiance, null) && noMarriageSpotValidator(cell)), out result)) { return true; } @@ -984,7 +1052,7 @@ public static bool TryFindPartySpot(Pawn organizer, out IntVec3 result) { bool enjoyableOutside = JoyUtility.EnjoyableOutsideNow(organizer, null); Map map = organizer.Map; - Predicate baseValidator = delegate(IntVec3 cell) + Predicate baseValidator = (Predicate)delegate(IntVec3 cell) { if (!cell.Standable(map)) { @@ -1006,35 +1074,42 @@ public static bool TryFindPartySpot(Pawn organizer, out IntVec3 result) { return false; } - Room room = cell.GetRoom(map, RegionType.Set_Passable); - bool flag = room != null && room.isPrisonCell; - return organizer.IsPrisoner == flag; + Room room2 = cell.GetRoom(map, RegionType.Set_Passable); + bool flag = room2 != null && room2.isPrisonCell; + if (organizer.IsPrisoner != flag) + { + return false; + } + return true; }; if ((from x in map.listerBuildings.AllBuildingsColonistOfDef(ThingDefOf.PartySpot) where baseValidator(x.Position) - select x.Position).TryRandomElement(out result)) + select x.Position).TryRandomElement(out result)) { return true; } - Predicate noPartySpotValidator = delegate(IntVec3 cell) + Predicate noPartySpotValidator = (Predicate)delegate(IntVec3 cell) { Room room = cell.GetRoom(map, RegionType.Set_Passable); - return room == null || room.IsHuge || room.PsychologicallyOutdoors || room.CellCount >= 10; + if (room != null && !room.IsHuge && !room.PsychologicallyOutdoors && room.CellCount < 10) + { + return false; + } + return true; }; - foreach (CompGatherSpot current in map.gatherSpotLister.activeSpots.InRandomOrder(null)) + foreach (CompGatherSpot item in map.gatherSpotLister.activeSpots.InRandomOrder(null)) { for (int i = 0; i < 10; i++) { - IntVec3 intVec = CellFinder.RandomClosewalkCellNear(current.parent.Position, current.parent.Map, 4, null); + IntVec3 intVec = CellFinder.RandomClosewalkCellNear(item.parent.Position, item.parent.Map, 4, null); if (baseValidator(intVec) && noPartySpotValidator(intVec)) { result = intVec; - bool result2 = true; - return result2; + return true; } } } - if (CellFinder.TryFindRandomCellNear(organizer.Position, organizer.Map, 25, (IntVec3 cell) => baseValidator(cell) && noPartySpotValidator(cell), out result)) + if (CellFinder.TryFindRandomCellNear(organizer.Position, organizer.Map, 25, (Predicate)((IntVec3 cell) => baseValidator(cell) && noPartySpotValidator(cell)), out result)) { return true; } @@ -1044,21 +1119,15 @@ where baseValidator(x.Position) internal static IntVec3 FindSiegePositionFrom(IntVec3 entrySpot, Map map) { - for (int i = 70; i >= 20; i -= 10) + for (int num = 70; num >= 20; num -= 10) { - IntVec3 result; - if (RCellFinder.TryFindSiegePosition(entrySpot, (float)i, map, out result)) + IntVec3 result = default(IntVec3); + if (RCellFinder.TryFindSiegePosition(entrySpot, (float)num, map, out result)) { return result; } } - Log.Error(string.Concat(new object[] - { - "Could not find siege spot from ", - entrySpot, - ", using ", - entrySpot - })); + Log.Error("Could not find siege spot from " + entrySpot + ", using " + entrySpot); return entrySpot; } @@ -1068,59 +1137,68 @@ private static bool TryFindSiegePosition(IntVec3 entrySpot, float minDistToColon cellRect.ClipInsideMap(map); cellRect = cellRect.ContractedBy(14); List list = new List(); - foreach (Pawn current in map.mapPawns.FreeColonistsSpawned) + foreach (Pawn item in map.mapPawns.FreeColonistsSpawned) { - list.Add(current.Position); + list.Add(item.Position); } - foreach (Building current2 in map.listerBuildings.allBuildingsColonistCombatTargets) + HashSet.Enumerator enumerator2 = map.listerBuildings.allBuildingsColonistCombatTargets.GetEnumerator(); + try { - list.Add(current2.Position); + while (enumerator2.MoveNext()) + { + Building current2 = enumerator2.Current; + list.Add(current2.Position); + } + } + finally + { + ((IDisposable)(object)enumerator2).Dispose(); } float num = minDistToColony * minDistToColony; int num2 = 0; - IntVec3 randomCell; + goto IL_00b9; + IL_00b9: while (true) { num2++; - if (num2 > 200) - { - break; - } - randomCell = cellRect.RandomCell; - if (randomCell.Standable(map)) - { - if (randomCell.SupportsStructureType(map, TerrainAffordance.Heavy) && randomCell.SupportsStructureType(map, TerrainAffordance.Light)) + if (num2 <= 200) + { + IntVec3 randomCell = cellRect.RandomCell; + if (!randomCell.Standable(map)) + continue; + if (!randomCell.SupportsStructureType(map, TerrainAffordance.Heavy)) + continue; + if (!randomCell.SupportsStructureType(map, TerrainAffordance.Light)) + continue; + if (!map.reachability.CanReach(randomCell, entrySpot, PathEndMode.OnCell, TraverseMode.NoPassClosedDoors, Danger.Some)) + continue; + if (!map.reachability.CanReachColony(randomCell)) + continue; + bool flag = false; + int num3 = 0; + while (num3 < list.Count) { - if (map.reachability.CanReach(randomCell, entrySpot, PathEndMode.OnCell, TraverseMode.NoPassClosedDoors, Danger.Some)) + if (!((float)(list[num3] - randomCell).LengthHorizontalSquared < num)) { - if (map.reachability.CanReachColony(randomCell)) - { - bool flag = false; - for (int i = 0; i < list.Count; i++) - { - if ((float)(list[i] - randomCell).LengthHorizontalSquared < num) - { - flag = true; - break; - } - } - if (!flag) - { - if (!randomCell.Roofed(map)) - { - goto IL_1A7; - } - } - } + num3++; + continue; } + flag = true; + break; } + if (flag) + continue; + if (randomCell.Roofed(map)) + continue; + result = randomCell; + return true; } + break; } result = IntVec3.Invalid; return false; - IL_1A7: - result = randomCell; - return true; + IL_01b1: + goto IL_00b9; } } } diff --git a/Assembly-CSharp/RimWorld/RaidStrategyDefOf.cs b/Assembly-CSharp/RimWorld/RaidStrategyDefOf.cs index cb17f341d..2428ff377 100644 --- a/Assembly-CSharp/RimWorld/RaidStrategyDefOf.cs +++ b/Assembly-CSharp/RimWorld/RaidStrategyDefOf.cs @@ -1,5 +1,3 @@ -using System; - namespace RimWorld { [DefOf] diff --git a/Assembly-CSharp/RimWorld/RaidStrategyWorker.cs b/Assembly-CSharp/RimWorld/RaidStrategyWorker.cs index c4891a2e6..ef64adbff 100644 --- a/Assembly-CSharp/RimWorld/RaidStrategyWorker.cs +++ b/Assembly-CSharp/RimWorld/RaidStrategyWorker.cs @@ -1,4 +1,3 @@ -using System; using System.Collections.Generic; using Verse; using Verse.AI.Group; @@ -18,7 +17,15 @@ public virtual float SelectionChance(Map map) public virtual bool CanUseWith(IncidentParms parms) { - return (float)GenDate.DaysPassed >= this.def.minDaysPassed && parms.points >= this.MinimumPoints(parms.faction); + if ((float)GenDate.DaysPassed < this.def.minDaysPassed) + { + return false; + } + if (parms.points < this.MinimumPoints(parms.faction)) + { + return false; + } + return true; } public virtual float MinimumPoints(Faction faction) diff --git a/Assembly-CSharp/RimWorld/RaidStrategyWorker_ImmediateAttack.cs b/Assembly-CSharp/RimWorld/RaidStrategyWorker_ImmediateAttack.cs index f22fdb8cc..20a3ec872 100644 --- a/Assembly-CSharp/RimWorld/RaidStrategyWorker_ImmediateAttack.cs +++ b/Assembly-CSharp/RimWorld/RaidStrategyWorker_ImmediateAttack.cs @@ -1,4 +1,3 @@ -using System; using Verse; using Verse.AI.Group; @@ -12,7 +11,7 @@ public override LordJob MakeLordJob(IncidentParms parms, Map map) { return new LordJob_AssaultColony(parms.faction, true, true, false, false, true); } - IntVec3 fallbackLocation; + IntVec3 fallbackLocation = default(IntVec3); RCellFinder.TryFindRandomSpotJustOutsideColony(parms.spawnCenter, map, out fallbackLocation); return new LordJob_AssistColony(parms.faction, fallbackLocation); } diff --git a/Assembly-CSharp/RimWorld/RaidStrategyWorker_ImmediateAttackSappers.cs b/Assembly-CSharp/RimWorld/RaidStrategyWorker_ImmediateAttackSappers.cs index bc2bee910..b83345a99 100644 --- a/Assembly-CSharp/RimWorld/RaidStrategyWorker_ImmediateAttackSappers.cs +++ b/Assembly-CSharp/RimWorld/RaidStrategyWorker_ImmediateAttackSappers.cs @@ -29,7 +29,19 @@ public override float SelectionChance(Map map) public override bool CanUseWith(IncidentParms parms) { - return parms.faction.def.humanlikeFaction && parms.faction.def.techLevel >= TechLevel.Industrial && this.PawnGenOptionsWithSappers(parms.faction).Any() && base.CanUseWith(parms); + if (parms.faction.def.humanlikeFaction && (int)parms.faction.def.techLevel >= 4) + { + if (!this.PawnGenOptionsWithSappers(parms.faction).Any()) + { + return false; + } + if (!base.CanUseWith(parms)) + { + return false; + } + return true; + } + return false; } public override float MinimumPoints(Faction faction) @@ -45,28 +57,21 @@ public override float MinMaxAllowedPawnGenOptionCost(Faction faction) private float CheapestSapperCost(Faction faction) { IEnumerable enumerable = this.PawnGenOptionsWithSappers(faction); - if (!enumerable.Any()) + if (!enumerable.Any()) { - Log.Error(string.Concat(new string[] - { - "Tried to get MinimumPoints for ", - base.GetType().ToString(), - " for faction ", - faction.ToString(), - " but the faction has no groups with sappers." - })); + Log.Error("Tried to get MinimumPoints for " + base.GetType().ToString() + " for faction " + faction.ToString() + " but the faction has no groups with sappers."); return 99999f; } float num = 9999999f; - foreach (PawnGroupMaker current in enumerable) + foreach (PawnGroupMaker item in enumerable) { - foreach (PawnGenOption current2 in from op in current.options + foreach (PawnGenOption item2 in from op in item.options where RaidStrategyWorker_ImmediateAttackSappers.CanBeSapper(op.kind) select op) { - if (current2.Cost < num) + if (item2.Cost < num) { - num = current2.Cost; + num = item2.Cost; } } } @@ -75,29 +80,23 @@ where RaidStrategyWorker_ImmediateAttackSappers.CanBeSapper(op.kind) public override bool CanUsePawnGenOption(PawnGenOption opt, List chosenOpts) { - return chosenOpts.Count != 0 || (opt.kind.weaponTags.Count == 1 && RaidStrategyWorker_ImmediateAttackSappers.CanBeSapper(opt.kind)); + if (chosenOpts.Count == 0 && (opt.kind.weaponTags.Count != 1 || !RaidStrategyWorker_ImmediateAttackSappers.CanBeSapper(opt.kind))) + { + return false; + } + return true; } private IEnumerable PawnGenOptionsWithSappers(Faction faction) { - return faction.def.pawnGroupMakers.Where(delegate(PawnGroupMaker gm) - { - bool arg_3B_0; - if (gm.kindDef == PawnGroupKindDefOf.Normal) - { - arg_3B_0 = gm.options.Any((PawnGenOption op) => RaidStrategyWorker_ImmediateAttackSappers.CanBeSapper(op.kind)); - } - else - { - arg_3B_0 = false; - } - return arg_3B_0; - }); + return from gm in faction.def.pawnGroupMakers + where gm.kindDef == PawnGroupKindDefOf.Normal && gm.options.Any((Predicate)((PawnGenOption op) => RaidStrategyWorker_ImmediateAttackSappers.CanBeSapper(op.kind))) + select gm; } public static bool CanBeSapper(PawnKindDef kind) { - return !kind.weaponTags.NullOrEmpty() && kind.weaponTags[0] == "GrenadeDestructive"; + return !kind.weaponTags.NullOrEmpty() && kind.weaponTags[0] == "GrenadeDestructive"; } public override LordJob MakeLordJob(IncidentParms parms, Map map) diff --git a/Assembly-CSharp/RimWorld/RaidStrategyWorker_ImmediateAttackSmart.cs b/Assembly-CSharp/RimWorld/RaidStrategyWorker_ImmediateAttackSmart.cs index 6676a1a83..2e2aed98f 100644 --- a/Assembly-CSharp/RimWorld/RaidStrategyWorker_ImmediateAttackSmart.cs +++ b/Assembly-CSharp/RimWorld/RaidStrategyWorker_ImmediateAttackSmart.cs @@ -1,4 +1,3 @@ -using System; using Verse; using Verse.AI.Group; @@ -13,7 +12,15 @@ public override LordJob MakeLordJob(IncidentParms parms, Map map) public override bool CanUseWith(IncidentParms parms) { - return base.CanUseWith(parms) && parms.faction.def.canUseAvoidGrid; + if (!base.CanUseWith(parms)) + { + return false; + } + if (!parms.faction.def.canUseAvoidGrid) + { + return false; + } + return true; } } } diff --git a/Assembly-CSharp/RimWorld/RaidStrategyWorker_Siege.cs b/Assembly-CSharp/RimWorld/RaidStrategyWorker_Siege.cs index a1c9d96a3..37e30bd8f 100644 --- a/Assembly-CSharp/RimWorld/RaidStrategyWorker_Siege.cs +++ b/Assembly-CSharp/RimWorld/RaidStrategyWorker_Siege.cs @@ -1,4 +1,3 @@ -using System; using UnityEngine; using Verse; using Verse.AI.Group; @@ -13,7 +12,7 @@ public override LordJob MakeLordJob(IncidentParms parms, Map map) { IntVec3 siegeSpot = RCellFinder.FindSiegePositionFrom(parms.spawnCenter, map); float num = parms.points * Rand.Range(0.2f, 0.3f); - if (num < 60f) + if (num < 60.0) { num = 60f; } @@ -27,7 +26,11 @@ public override float MinimumPoints(Faction fac) public override bool CanUseWith(IncidentParms parms) { - return base.CanUseWith(parms) && parms.faction.def.canSiege; + if (!base.CanUseWith(parms)) + { + return false; + } + return parms.faction.def.canSiege; } } } diff --git a/Assembly-CSharp/RimWorld/RaidStrategyWorker_StageThenAttack.cs b/Assembly-CSharp/RimWorld/RaidStrategyWorker_StageThenAttack.cs index 898e49257..e8872ec52 100644 --- a/Assembly-CSharp/RimWorld/RaidStrategyWorker_StageThenAttack.cs +++ b/Assembly-CSharp/RimWorld/RaidStrategyWorker_StageThenAttack.cs @@ -1,4 +1,3 @@ -using System; using Verse; using Verse.AI.Group; @@ -14,7 +13,11 @@ public override LordJob MakeLordJob(IncidentParms parms, Map map) public override bool CanUseWith(IncidentParms parms) { - return base.CanUseWith(parms) && parms.faction.def.canStageAttacks; + if (!base.CanUseWith(parms)) + { + return false; + } + return parms.faction.def.canStageAttacks; } } } diff --git a/Assembly-CSharp/RimWorld/RandomSocialMode.cs b/Assembly-CSharp/RimWorld/RandomSocialMode.cs index 2b47972d7..ba2fab1e9 100644 --- a/Assembly-CSharp/RimWorld/RandomSocialMode.cs +++ b/Assembly-CSharp/RimWorld/RandomSocialMode.cs @@ -1,12 +1,10 @@ -using System; - namespace RimWorld { public enum RandomSocialMode { - Off, - Quiet, - Normal, - SuperActive + Off = 0, + Quiet = 1, + Normal = 2, + SuperActive = 3 } } diff --git a/Assembly-CSharp/RimWorld/RecipeDefGenerator.cs b/Assembly-CSharp/RimWorld/RecipeDefGenerator.cs index 94650f6a9..414006fb3 100644 --- a/Assembly-CSharp/RimWorld/RecipeDefGenerator.cs +++ b/Assembly-CSharp/RimWorld/RecipeDefGenerator.cs @@ -1,37 +1,106 @@ using System; using System.Collections.Generic; -using System.Diagnostics; +using System.Linq; using Verse; namespace RimWorld { internal static class RecipeDefGenerator { - [DebuggerHidden] public static IEnumerable ImpliedRecipeDefs() { - RecipeDefGenerator.c__Iterator6E c__Iterator6E = new RecipeDefGenerator.c__Iterator6E(); - RecipeDefGenerator.c__Iterator6E expr_07 = c__Iterator6E; - expr_07.$PC = -2; - return expr_07; + foreach (RecipeDef item in RecipeDefGenerator.DefsFromRecipeMakers().Concat(RecipeDefGenerator.DrugAdministerDefs())) + { + yield return item; + } } - [DebuggerHidden] private static IEnumerable DefsFromRecipeMakers() { - RecipeDefGenerator.c__Iterator6F c__Iterator6F = new RecipeDefGenerator.c__Iterator6F(); - RecipeDefGenerator.c__Iterator6F expr_07 = c__Iterator6F; - expr_07.$PC = -2; - return expr_07; + foreach (ThingDef item in from d in DefDatabase.AllDefs + where d.recipeMaker != null + select d) + { + RecipeMakerProperties rm = item.recipeMaker; + RecipeDef r = new RecipeDef + { + defName = "Make_" + item.defName, + label = "RecipeMake".Translate(item.label), + jobString = "RecipeMakeJobString".Translate(item.label), + workAmount = (float)rm.workAmount, + workSpeedStat = rm.workSpeedStat, + efficiencyStat = rm.efficiencyStat + }; + if (item.MadeFromStuff) + { + IngredientCount ic2 = new IngredientCount(); + ic2.SetBaseCount((float)item.costStuffCount); + ic2.filter.SetAllowAllWhoCanMake(item); + r.ingredients.Add(ic2); + r.fixedIngredientFilter.SetAllowAllWhoCanMake(item); + r.productHasIngredientStuff = true; + } + if (item.costList != null) + { + List.Enumerator enumerator2 = item.costList.GetEnumerator(); + try + { + while (enumerator2.MoveNext()) + { + ThingCountClass c = enumerator2.Current; + IngredientCount ic = new IngredientCount(); + ic.SetBaseCount((float)c.count); + ic.filter.SetAllow(c.thingDef, true); + r.ingredients.Add(ic); + } + } + finally + { + ((IDisposable)(object)enumerator2).Dispose(); + } + } + r.defaultIngredientFilter = rm.defaultIngredientFilter; + r.products.Add(new ThingCountClass(item, rm.productCount)); + r.skillRequirements = rm.skillRequirements.ListFullCopyOrNull(); + r.workSkill = rm.workSkill; + r.workSkillLearnFactor = rm.workSkillLearnPerTick; + r.unfinishedThingDef = rm.unfinishedThingDef; + r.recipeUsers = rm.recipeUsers.ListFullCopyOrNull(); + r.effectWorking = rm.effectWorking; + r.soundWorking = rm.soundWorking; + r.researchPrerequisite = rm.researchPrerequisite; + yield return r; + } } - [DebuggerHidden] private static IEnumerable DrugAdministerDefs() { - RecipeDefGenerator.c__Iterator70 c__Iterator = new RecipeDefGenerator.c__Iterator70(); - RecipeDefGenerator.c__Iterator70 expr_07 = c__Iterator; - expr_07.$PC = -2; - return expr_07; + foreach (ThingDef item in from d in DefDatabase.AllDefs + where d.IsDrug + select d) + { + RecipeDef r = new RecipeDef + { + defName = "Administer_" + item.defName, + label = "RecipeAdminister".Translate(item.label), + jobString = "RecipeAdministerJobString".Translate(item.label), + workerClass = typeof(Recipe_AdministerIngestible), + targetsBodyPart = false, + anesthetize = false, + workAmount = (float)item.ingestible.baseIngestTicks + }; + IngredientCount ic = new IngredientCount(); + ic.SetBaseCount(1f); + ic.filter.SetAllow(item, true); + r.ingredients.Add(ic); + r.fixedIngredientFilter.SetAllow(item, true); + r.recipeUsers = new List(); + foreach (ThingDef item2 in DefDatabase.AllDefs.Where((Func)((ThingDef d) => d.category == ThingCategory.Pawn && d.race.IsFlesh))) + { + r.recipeUsers.Add(item2); + } + yield return r; + } } } } diff --git a/Assembly-CSharp/RimWorld/RecipeDefOf.cs b/Assembly-CSharp/RimWorld/RecipeDefOf.cs index 4bbb5678d..1fd836fc4 100644 --- a/Assembly-CSharp/RimWorld/RecipeDefOf.cs +++ b/Assembly-CSharp/RimWorld/RecipeDefOf.cs @@ -1,4 +1,3 @@ -using System; using Verse; namespace RimWorld diff --git a/Assembly-CSharp/RimWorld/Recipe_AdministerIngestible.cs b/Assembly-CSharp/RimWorld/Recipe_AdministerIngestible.cs index 71db97d25..0b4a31018 100644 --- a/Assembly-CSharp/RimWorld/Recipe_AdministerIngestible.cs +++ b/Assembly-CSharp/RimWorld/Recipe_AdministerIngestible.cs @@ -1,4 +1,3 @@ -using System; using System.Collections.Generic; using System.Linq; using Verse; @@ -26,18 +25,30 @@ public override void ConsumeIngredient(Thing ingredient, RecipeDef recipe, Map m public override bool IsViolationOnPawn(Pawn pawn, BodyPartRecord part, Faction billDoerFaction) { - return pawn.Faction != billDoerFaction && this.recipe.ingredients[0].filter.AllowedThingDefs.First().ingestible.drugCategory != DrugCategory.Medical; + if (pawn.Faction == billDoerFaction) + { + return false; + } + return base.recipe.ingredients[0].filter.AllowedThingDefs.First().ingestible.drugCategory != DrugCategory.Medical; } public override string GetLabelWhenUsedOn(Pawn pawn, BodyPartRecord part) { - if (pawn.IsTeetotaler() && this.recipe.ingredients[0].filter.BestThingRequest.singleDef.IsDrug) + if (pawn.IsTeetotaler()) { - return base.GetLabelWhenUsedOn(pawn, part) + " (" + "TeetotalerUnhappy".Translate() + ")"; + ThingRequest bestThingRequest = base.recipe.ingredients[0].filter.BestThingRequest; + if (bestThingRequest.singleDef.IsDrug) + { + return base.GetLabelWhenUsedOn(pawn, part) + " (" + "TeetotalerUnhappy".Translate() + ")"; + } } - if (pawn.IsProsthophobe() && this.recipe.ingredients[0].filter.BestThingRequest.singleDef == ThingDefOf.Luciferium) + if (pawn.IsProsthophobe()) { - return base.GetLabelWhenUsedOn(pawn, part) + " (" + "ProsthophobeUnhappy".Translate() + ")"; + ThingRequest bestThingRequest2 = base.recipe.ingredients[0].filter.BestThingRequest; + if (bestThingRequest2.singleDef == ThingDefOf.Luciferium) + { + return base.GetLabelWhenUsedOn(pawn, part) + " (" + "ProsthophobeUnhappy".Translate() + ")"; + } } return base.GetLabelWhenUsedOn(pawn, part); } diff --git a/Assembly-CSharp/RimWorld/Recipe_ExecuteByCut.cs b/Assembly-CSharp/RimWorld/Recipe_ExecuteByCut.cs index ee762d4ac..fa54f8e95 100644 --- a/Assembly-CSharp/RimWorld/Recipe_ExecuteByCut.cs +++ b/Assembly-CSharp/RimWorld/Recipe_ExecuteByCut.cs @@ -1,4 +1,3 @@ -using System; using System.Collections.Generic; using Verse; diff --git a/Assembly-CSharp/RimWorld/Recipe_InstallArtificialBodyPart.cs b/Assembly-CSharp/RimWorld/Recipe_InstallArtificialBodyPart.cs index ccafb2b79..9f260fd28 100644 --- a/Assembly-CSharp/RimWorld/Recipe_InstallArtificialBodyPart.cs +++ b/Assembly-CSharp/RimWorld/Recipe_InstallArtificialBodyPart.cs @@ -1,41 +1,48 @@ using System; using System.Collections.Generic; -using System.Diagnostics; +using System.Linq; using Verse; namespace RimWorld { public class Recipe_InstallArtificialBodyPart : Recipe_Surgery { - [DebuggerHidden] public override IEnumerable GetPartsToApplyOn(Pawn pawn, RecipeDef recipe) { - Recipe_InstallArtificialBodyPart.c__IteratorC0 c__IteratorC = new Recipe_InstallArtificialBodyPart.c__IteratorC0(); - c__IteratorC.recipe = recipe; - c__IteratorC.pawn = pawn; - c__IteratorC.<$>recipe = recipe; - c__IteratorC.<$>pawn = pawn; - Recipe_InstallArtificialBodyPart.c__IteratorC0 expr_23 = c__IteratorC; - expr_23.$PC = -2; - return expr_23; + for (int j = 0; j < recipe.appliedOnFixedBodyParts.Count; j++) + { + BodyPartDef part = recipe.appliedOnFixedBodyParts[j]; + List bpList = pawn.RaceProps.body.AllParts; + for (int i = 0; i < bpList.Count; i++) + { + BodyPartRecord record = bpList[i]; + if (record.def == part) + { + IEnumerable diffs = from x in pawn.health.hediffSet.hediffs + where x.Part == ((_003CGetPartsToApplyOn_003Ec__IteratorC0)/*Error near IL_00b8: stateMachine*/)._003Crecord_003E__4 + select x; + if ((diffs.Count() != 1 || diffs.First().def != recipe.addsHediff) && (record.parent == null || pawn.health.hediffSet.GetNotMissingParts(BodyPartHeight.Undefined, BodyPartDepth.Undefined).Contains(record.parent)) && (!pawn.health.hediffSet.PartOrAnyAncestorHasDirectlyAddedParts(record) || pawn.health.hediffSet.HasDirectlyAddedPartFor(record))) + { + yield return record; + } + } + } + } } public override void ApplyOnPawn(Pawn pawn, BodyPartRecord part, Pawn billDoer, List ingredients) { if (billDoer != null) { - if (base.CheckSurgeryFail(billDoer, pawn, ingredients, part)) + if (!base.CheckSurgeryFail(billDoer, pawn, ingredients, part)) { - return; + TaleRecorder.RecordTale(TaleDefOf.DidSurgery, billDoer, pawn); + MedicalRecipesUtility.RestorePartAndSpawnAllPreviousParts(pawn, part, billDoer.Position, billDoer.Map); + goto IL_0078; } - TaleRecorder.RecordTale(TaleDefOf.DidSurgery, new object[] - { - billDoer, - pawn - }); - MedicalRecipesUtility.RestorePartAndSpawnAllPreviousParts(pawn, part, billDoer.Position, billDoer.Map); + return; } - else if (pawn.Map != null) + if (pawn.Map != null) { MedicalRecipesUtility.RestorePartAndSpawnAllPreviousParts(pawn, part, pawn.Position, pawn.Map); } @@ -43,7 +50,9 @@ public override void ApplyOnPawn(Pawn pawn, BodyPartRecord part, Pawn billDoer, { pawn.health.RestorePart(part, null, true); } - pawn.health.AddHediff(this.recipe.addsHediff, part, null); + goto IL_0078; + IL_0078: + pawn.health.AddHediff(base.recipe.addsHediff, part, default(DamageInfo?)); } } } diff --git a/Assembly-CSharp/RimWorld/Recipe_InstallImplant.cs b/Assembly-CSharp/RimWorld/Recipe_InstallImplant.cs index a7830b694..ef370e058 100644 --- a/Assembly-CSharp/RimWorld/Recipe_InstallImplant.cs +++ b/Assembly-CSharp/RimWorld/Recipe_InstallImplant.cs @@ -1,23 +1,27 @@ using System; using System.Collections.Generic; -using System.Diagnostics; +using System.Linq; using Verse; namespace RimWorld { public class Recipe_InstallImplant : Recipe_Surgery { - [DebuggerHidden] public override IEnumerable GetPartsToApplyOn(Pawn pawn, RecipeDef recipe) { - Recipe_InstallImplant.c__IteratorC1 c__IteratorC = new Recipe_InstallImplant.c__IteratorC1(); - c__IteratorC.recipe = recipe; - c__IteratorC.pawn = pawn; - c__IteratorC.<$>recipe = recipe; - c__IteratorC.<$>pawn = pawn; - Recipe_InstallImplant.c__IteratorC1 expr_23 = c__IteratorC; - expr_23.$PC = -2; - return expr_23; + for (int j = 0; j < recipe.appliedOnFixedBodyParts.Count; j++) + { + BodyPartDef part = recipe.appliedOnFixedBodyParts[j]; + List bpList = pawn.RaceProps.body.AllParts; + for (int i = 0; i < bpList.Count; i++) + { + BodyPartRecord record = bpList[i]; + if (record.def == part && pawn.health.hediffSet.GetNotMissingParts(BodyPartHeight.Undefined, BodyPartDepth.Undefined).Contains(record) && !pawn.health.hediffSet.PartOrAnyAncestorHasDirectlyAddedParts(record) && !pawn.health.hediffSet.hediffs.Any((Predicate)((Hediff x) => x.Part == ((_003CGetPartsToApplyOn_003Ec__IteratorC1)/*Error near IL_0108: stateMachine*/)._003Crecord_003E__4 && x.def == ((_003CGetPartsToApplyOn_003Ec__IteratorC1)/*Error near IL_0108: stateMachine*/).recipe.addsHediff))) + { + yield return record; + } + } + } } public override void ApplyOnPawn(Pawn pawn, BodyPartRecord part, Pawn billDoer, List ingredients) @@ -28,13 +32,9 @@ public override void ApplyOnPawn(Pawn pawn, BodyPartRecord part, Pawn billDoer, { return; } - TaleRecorder.RecordTale(TaleDefOf.DidSurgery, new object[] - { - billDoer, - pawn - }); + TaleRecorder.RecordTale(TaleDefOf.DidSurgery, billDoer, pawn); } - pawn.health.AddHediff(this.recipe.addsHediff, part, null); + pawn.health.AddHediff(base.recipe.addsHediff, part, default(DamageInfo?)); } } } diff --git a/Assembly-CSharp/RimWorld/Recipe_InstallNaturalBodyPart.cs b/Assembly-CSharp/RimWorld/Recipe_InstallNaturalBodyPart.cs index 90a6a5fa0..88bc62629 100644 --- a/Assembly-CSharp/RimWorld/Recipe_InstallNaturalBodyPart.cs +++ b/Assembly-CSharp/RimWorld/Recipe_InstallNaturalBodyPart.cs @@ -1,38 +1,34 @@ using System; using System.Collections.Generic; -using System.Diagnostics; +using System.Linq; using Verse; namespace RimWorld { public class Recipe_InstallNaturalBodyPart : Recipe_Surgery { - [DebuggerHidden] public override IEnumerable GetPartsToApplyOn(Pawn pawn, RecipeDef recipe) { - Recipe_InstallNaturalBodyPart.c__IteratorC2 c__IteratorC = new Recipe_InstallNaturalBodyPart.c__IteratorC2(); - c__IteratorC.recipe = recipe; - c__IteratorC.pawn = pawn; - c__IteratorC.<$>recipe = recipe; - c__IteratorC.<$>pawn = pawn; - Recipe_InstallNaturalBodyPart.c__IteratorC2 expr_23 = c__IteratorC; - expr_23.$PC = -2; - return expr_23; + for (int j = 0; j < recipe.appliedOnFixedBodyParts.Count; j++) + { + BodyPartDef recipePart = recipe.appliedOnFixedBodyParts[j]; + List bpList = pawn.RaceProps.body.AllParts; + for (int i = 0; i < bpList.Count; i++) + { + BodyPartRecord record = bpList[i]; + if (record.def == recipePart && pawn.health.hediffSet.hediffs.Any((Predicate)((Hediff x) => x.Part == ((_003CGetPartsToApplyOn_003Ec__IteratorC2)/*Error near IL_00b7: stateMachine*/)._003Crecord_003E__4)) && (record.parent == null || pawn.health.hediffSet.GetNotMissingParts(BodyPartHeight.Undefined, BodyPartDepth.Undefined).Contains(record.parent)) && (!pawn.health.hediffSet.PartOrAnyAncestorHasDirectlyAddedParts(record) || pawn.health.hediffSet.HasDirectlyAddedPartFor(record))) + { + yield return record; + } + } + } } public override void ApplyOnPawn(Pawn pawn, BodyPartRecord part, Pawn billDoer, List ingredients) { - if (billDoer != null) + if (billDoer != null && !base.CheckSurgeryFail(billDoer, pawn, ingredients, part)) { - if (base.CheckSurgeryFail(billDoer, pawn, ingredients, part)) - { - return; - } - TaleRecorder.RecordTale(TaleDefOf.DidSurgery, new object[] - { - billDoer, - pawn - }); + TaleRecorder.RecordTale(TaleDefOf.DidSurgery, billDoer, pawn); MedicalRecipesUtility.RestorePartAndSpawnAllPreviousParts(pawn, part, billDoer.Position, billDoer.Map); } } diff --git a/Assembly-CSharp/RimWorld/Recipe_RemoveBodyPart.cs b/Assembly-CSharp/RimWorld/Recipe_RemoveBodyPart.cs index 4be4420db..6d01aece4 100644 --- a/Assembly-CSharp/RimWorld/Recipe_RemoveBodyPart.cs +++ b/Assembly-CSharp/RimWorld/Recipe_RemoveBodyPart.cs @@ -1,6 +1,5 @@ using System; using System.Collections.Generic; -using System.Diagnostics; using Verse; namespace RimWorld @@ -9,20 +8,37 @@ internal class Recipe_RemoveBodyPart : Recipe_Surgery { private const float ViolationGoodwillImpact = 20f; - [DebuggerHidden] public override IEnumerable GetPartsToApplyOn(Pawn pawn, RecipeDef recipe) { - Recipe_RemoveBodyPart.c__IteratorC4 c__IteratorC = new Recipe_RemoveBodyPart.c__IteratorC4(); - c__IteratorC.pawn = pawn; - c__IteratorC.<$>pawn = pawn; - Recipe_RemoveBodyPart.c__IteratorC4 expr_15 = c__IteratorC; - expr_15.$PC = -2; - return expr_15; + IEnumerable parts = pawn.health.hediffSet.GetNotMissingParts(BodyPartHeight.Undefined, BodyPartDepth.Undefined); + foreach (BodyPartRecord item in parts) + { + if (pawn.health.hediffSet.HasDirectlyAddedPartFor(item)) + { + yield return item; + } + else if (MedicalRecipesUtility.IsCleanAndDroppable(pawn, item)) + { + yield return item; + } + else if (item != pawn.RaceProps.body.corePart && !item.def.dontSuggestAmputation && pawn.health.hediffSet.hediffs.Any((Predicate)((Hediff d) => !(d is Hediff_Injury) && d.def.isBad && d.Visible && d.Part == ((_003CGetPartsToApplyOn_003Ec__IteratorC4)/*Error near IL_0144: stateMachine*/)._003Cpart_003E__2))) + { + yield return item; + } + } } public override bool IsViolationOnPawn(Pawn pawn, BodyPartRecord part, Faction billDoerFaction) { - return pawn.Faction != billDoerFaction && HealthUtility.PartRemovalIntent(pawn, part) == BodyPartRemovalIntent.Harvest; + if (pawn.Faction == billDoerFaction) + { + return false; + } + if (HealthUtility.PartRemovalIntent(pawn, part) == BodyPartRemovalIntent.Harvest) + { + return true; + } + return false; } public override void ApplyOnPawn(Pawn pawn, BodyPartRecord part, Pawn billDoer, List ingredients) @@ -35,11 +51,7 @@ public override void ApplyOnPawn(Pawn pawn, BodyPartRecord part, Pawn billDoer, { return; } - TaleRecorder.RecordTale(TaleDefOf.DidSurgery, new object[] - { - billDoer, - pawn - }); + TaleRecorder.RecordTale(TaleDefOf.DidSurgery, billDoer, pawn); MedicalRecipesUtility.SpawnNaturalPartIfClean(pawn, part, billDoer.Position, billDoer.Map); MedicalRecipesUtility.SpawnThingsFromHediffs(pawn, part, billDoer.Position, billDoer.Map); } @@ -63,24 +75,29 @@ public override void ApplyOnPawn(Pawn pawn, BodyPartRecord part, Pawn billDoer, public override string GetLabelWhenUsedOn(Pawn pawn, BodyPartRecord part) { - if (pawn.RaceProps.IsMechanoid || pawn.health.hediffSet.PartOrAnyAncestorHasDirectlyAddedParts(part)) + if (!pawn.RaceProps.IsMechanoid && !pawn.health.hediffSet.PartOrAnyAncestorHasDirectlyAddedParts(part)) { - return RecipeDefOf.RemoveBodyPart.LabelCap; - } - BodyPartRemovalIntent bodyPartRemovalIntent = HealthUtility.PartRemovalIntent(pawn, part); - if (bodyPartRemovalIntent == BodyPartRemovalIntent.Harvest) - { - return "Harvest".Translate(); - } - if (bodyPartRemovalIntent != BodyPartRemovalIntent.Amputate) - { - throw new InvalidOperationException(); - } - if (part.depth == BodyPartDepth.Inside || part.def.useDestroyedOutLabel) - { - return "RemoveOrgan".Translate(); + switch (HealthUtility.PartRemovalIntent(pawn, part)) + { + case BodyPartRemovalIntent.Amputate: + { + if (part.depth != BodyPartDepth.Inside && !part.def.useDestroyedOutLabel) + { + return "Amputate".Translate(); + } + return "RemoveOrgan".Translate(); + } + case BodyPartRemovalIntent.Harvest: + { + return "Harvest".Translate(); + } + default: + { + throw new InvalidOperationException(); + } + } } - return "Amputate".Translate(); + return RecipeDefOf.RemoveBodyPart.LabelCap; } } } diff --git a/Assembly-CSharp/RimWorld/Recipe_RemoveHediff.cs b/Assembly-CSharp/RimWorld/Recipe_RemoveHediff.cs index 3e2e4aedf..995c1af34 100644 --- a/Assembly-CSharp/RimWorld/Recipe_RemoveHediff.cs +++ b/Assembly-CSharp/RimWorld/Recipe_RemoveHediff.cs @@ -1,23 +1,21 @@ using System; using System.Collections.Generic; -using System.Diagnostics; using Verse; namespace RimWorld { public class Recipe_RemoveHediff : Recipe_Surgery { - [DebuggerHidden] public override IEnumerable GetPartsToApplyOn(Pawn pawn, RecipeDef recipe) { - Recipe_RemoveHediff.c__IteratorC5 c__IteratorC = new Recipe_RemoveHediff.c__IteratorC5(); - c__IteratorC.pawn = pawn; - c__IteratorC.recipe = recipe; - c__IteratorC.<$>pawn = pawn; - c__IteratorC.<$>recipe = recipe; - Recipe_RemoveHediff.c__IteratorC5 expr_23 = c__IteratorC; - expr_23.$PC = -2; - return expr_23; + List allHediffs = pawn.health.hediffSet.hediffs; + for (int i = 0; i < allHediffs.Count; i++) + { + if (allHediffs[i].Part != null && allHediffs[i].def == recipe.removesHediff && allHediffs[i].Visible) + { + yield return allHediffs[i].Part; + } + } } public override void ApplyOnPawn(Pawn pawn, BodyPartRecord part, Pawn billDoer, List ingredients) @@ -28,31 +26,14 @@ public override void ApplyOnPawn(Pawn pawn, BodyPartRecord part, Pawn billDoer, { return; } - TaleRecorder.RecordTale(TaleDefOf.DidSurgery, new object[] - { - billDoer, - pawn - }); + TaleRecorder.RecordTale(TaleDefOf.DidSurgery, billDoer, pawn); if (PawnUtility.ShouldSendNotificationAbout(pawn) || PawnUtility.ShouldSendNotificationAbout(billDoer)) { - string text; - if (!this.recipe.successfullyRemovedHediffMessage.NullOrEmpty()) - { - text = string.Format(this.recipe.successfullyRemovedHediffMessage, billDoer.LabelShort, pawn.LabelShort); - } - else - { - text = "MessageSuccessfullyRemovedHediff".Translate(new object[] - { - billDoer.LabelShort, - pawn.LabelShort, - this.recipe.removesHediff.label - }); - } - Messages.Message(text, pawn, MessageSound.Benefit); + string text = base.recipe.successfullyRemovedHediffMessage.NullOrEmpty() ? "MessageSuccessfullyRemovedHediff".Translate(billDoer.LabelShort, pawn.LabelShort, base.recipe.removesHediff.label) : string.Format(base.recipe.successfullyRemovedHediffMessage, billDoer.LabelShort, pawn.LabelShort); + Messages.Message(text, (Thing)pawn, MessageSound.Benefit); } } - Hediff hediff = pawn.health.hediffSet.hediffs.Find((Hediff x) => x.def == this.recipe.removesHediff && x.Part == part && x.Visible); + Hediff hediff = pawn.health.hediffSet.hediffs.Find((Predicate)((Hediff x) => x.def == base.recipe.removesHediff && x.Part == part && x.Visible)); if (hediff != null) { pawn.health.RemoveHediff(hediff); diff --git a/Assembly-CSharp/RimWorld/Recipe_ShutDown.cs b/Assembly-CSharp/RimWorld/Recipe_ShutDown.cs index 008a4076c..89fade35a 100644 --- a/Assembly-CSharp/RimWorld/Recipe_ShutDown.cs +++ b/Assembly-CSharp/RimWorld/Recipe_ShutDown.cs @@ -1,26 +1,22 @@ -using System; using System.Collections.Generic; -using System.Diagnostics; using Verse; namespace RimWorld { internal class Recipe_ShutDown : RecipeWorker { - [DebuggerHidden] public override IEnumerable GetPartsToApplyOn(Pawn pawn, RecipeDef recipe) { - Recipe_ShutDown.c__IteratorC3 c__IteratorC = new Recipe_ShutDown.c__IteratorC3(); - c__IteratorC.pawn = pawn; - c__IteratorC.<$>pawn = pawn; - Recipe_ShutDown.c__IteratorC3 expr_15 = c__IteratorC; - expr_15.$PC = -2; - return expr_15; + BodyPartRecord brain = pawn.health.hediffSet.GetBrain(); + if (brain != null) + { + yield return brain; + } } public override void ApplyOnPawn(Pawn pawn, BodyPartRecord part, Pawn billDoer, List ingredients) { - pawn.health.AddHediff(this.recipe.addsHediff, part, null); + pawn.health.AddHediff(base.recipe.addsHediff, part, default(DamageInfo?)); ThoughtUtility.GiveThoughtsForPawnExecuted(pawn, PawnExecutionKind.GenericHumane); } } diff --git a/Assembly-CSharp/RimWorld/Recipe_Surgery.cs b/Assembly-CSharp/RimWorld/Recipe_Surgery.cs index 07bf5e111..5f9f8d502 100644 --- a/Assembly-CSharp/RimWorld/Recipe_Surgery.cs +++ b/Assembly-CSharp/RimWorld/Recipe_Surgery.cs @@ -1,4 +1,3 @@ -using System; using System.Collections.Generic; using Verse; @@ -20,10 +19,10 @@ protected bool CheckSurgeryFail(Pawn surgeon, Pawn patient, List ingredie num *= room.GetStat(RoomStatDefOf.SurgerySuccessChanceFactor); } num *= this.GetAverageMedicalPotency(ingredients); - num *= this.recipe.surgerySuccessChanceFactor; + num *= base.recipe.surgerySuccessChanceFactor; if (Rand.Value > num) { - if (Rand.Value < this.recipe.deathOnFailedSurgeryChance) + if (Rand.Value < base.recipe.deathOnFailedSurgeryChance) { int num2 = 0; while (!patient.Dead) @@ -37,34 +36,22 @@ protected bool CheckSurgeryFail(Pawn surgeon, Pawn patient, List ingredie } } } - else if (Rand.Value < 0.5f) + else if (Rand.Value < 0.5) { - if (Rand.Value < 0.1f) + if (Rand.Value < 0.10000000149011612) { - Messages.Message("MessageMedicalOperationFailureRidiculous".Translate(new object[] - { - surgeon.LabelShort, - patient.LabelShort - }), patient, MessageSound.SeriousAlert); + Messages.Message("MessageMedicalOperationFailureRidiculous".Translate(surgeon.LabelShort, patient.LabelShort), (Thing)patient, MessageSound.SeriousAlert); HealthUtility.GiveInjuriesOperationFailureRidiculous(patient); } else { - Messages.Message("MessageMedicalOperationFailureCatastrophic".Translate(new object[] - { - surgeon.LabelShort, - patient.LabelShort - }), patient, MessageSound.SeriousAlert); + Messages.Message("MessageMedicalOperationFailureCatastrophic".Translate(surgeon.LabelShort, patient.LabelShort), (Thing)patient, MessageSound.SeriousAlert); HealthUtility.GiveInjuriesOperationFailureCatastrophic(patient, part); } } else { - Messages.Message("MessageMedicalOperationFailureMinor".Translate(new object[] - { - surgeon.LabelShort, - patient.LabelShort - }), patient, MessageSound.Negative); + Messages.Message("MessageMedicalOperationFailureMinor".Translate(surgeon.LabelShort, patient.LabelShort), (Thing)patient, MessageSound.Negative); HealthUtility.GiveInjuriesOperationFailureMinor(patient, part); } if (!patient.Dead) @@ -78,16 +65,15 @@ protected bool CheckSurgeryFail(Pawn surgeon, Pawn patient, List ingredie private void TryGainBotchedSurgeryThought(Pawn patient, Pawn surgeon) { - if (!patient.RaceProps.Humanlike) + if (patient.RaceProps.Humanlike) { - return; + patient.needs.mood.thoughts.memories.TryGainMemory(ThoughtDefOf.BotchedMySurgery, surgeon); } - patient.needs.mood.thoughts.memories.TryGainMemory(ThoughtDefOf.BotchedMySurgery, surgeon); } private float GetAverageMedicalPotency(List ingredients) { - if (ingredients.NullOrEmpty()) + if (ingredients.NullOrEmpty()) { return 1f; } diff --git a/Assembly-CSharp/RimWorld/RecordDefOf.cs b/Assembly-CSharp/RimWorld/RecordDefOf.cs index d157759b1..369a0e6b5 100644 --- a/Assembly-CSharp/RimWorld/RecordDefOf.cs +++ b/Assembly-CSharp/RimWorld/RecordDefOf.cs @@ -1,5 +1,3 @@ -using System; - namespace RimWorld { [DefOf] diff --git a/Assembly-CSharp/RimWorld/RecordType.cs b/Assembly-CSharp/RimWorld/RecordType.cs index 9c4be0fe6..570ce6db1 100644 --- a/Assembly-CSharp/RimWorld/RecordType.cs +++ b/Assembly-CSharp/RimWorld/RecordType.cs @@ -1,11 +1,9 @@ -using System; - namespace RimWorld { public enum RecordType { - Time, - Int, - Float + Time = 0, + Int = 1, + Float = 2 } } diff --git a/Assembly-CSharp/RimWorld/RecordWorker.cs b/Assembly-CSharp/RimWorld/RecordWorker.cs index 902ac5edb..1d5c20cd7 100644 --- a/Assembly-CSharp/RimWorld/RecordWorker.cs +++ b/Assembly-CSharp/RimWorld/RecordWorker.cs @@ -1,4 +1,3 @@ -using System; using Verse; using Verse.AI; diff --git a/Assembly-CSharp/RimWorld/RecordWorker_TimeAsColonistOrColonyAnimal.cs b/Assembly-CSharp/RimWorld/RecordWorker_TimeAsColonistOrColonyAnimal.cs index 5c6426ad3..075b1e1c7 100644 --- a/Assembly-CSharp/RimWorld/RecordWorker_TimeAsColonistOrColonyAnimal.cs +++ b/Assembly-CSharp/RimWorld/RecordWorker_TimeAsColonistOrColonyAnimal.cs @@ -1,4 +1,3 @@ -using System; using Verse; namespace RimWorld diff --git a/Assembly-CSharp/RimWorld/RecordWorker_TimeAsPrisoner.cs b/Assembly-CSharp/RimWorld/RecordWorker_TimeAsPrisoner.cs index c1f2f873c..bb613dd45 100644 --- a/Assembly-CSharp/RimWorld/RecordWorker_TimeAsPrisoner.cs +++ b/Assembly-CSharp/RimWorld/RecordWorker_TimeAsPrisoner.cs @@ -1,4 +1,3 @@ -using System; using Verse; namespace RimWorld diff --git a/Assembly-CSharp/RimWorld/RecordWorker_TimeDowned.cs b/Assembly-CSharp/RimWorld/RecordWorker_TimeDowned.cs index 3613496b2..497d62a17 100644 --- a/Assembly-CSharp/RimWorld/RecordWorker_TimeDowned.cs +++ b/Assembly-CSharp/RimWorld/RecordWorker_TimeDowned.cs @@ -1,4 +1,3 @@ -using System; using Verse; namespace RimWorld diff --git a/Assembly-CSharp/RimWorld/RecordWorker_TimeDrafted.cs b/Assembly-CSharp/RimWorld/RecordWorker_TimeDrafted.cs index 602442f0b..303283186 100644 --- a/Assembly-CSharp/RimWorld/RecordWorker_TimeDrafted.cs +++ b/Assembly-CSharp/RimWorld/RecordWorker_TimeDrafted.cs @@ -1,4 +1,3 @@ -using System; using Verse; namespace RimWorld diff --git a/Assembly-CSharp/RimWorld/RecordWorker_TimeGettingJoy.cs b/Assembly-CSharp/RimWorld/RecordWorker_TimeGettingJoy.cs index f24805037..545188437 100644 --- a/Assembly-CSharp/RimWorld/RecordWorker_TimeGettingJoy.cs +++ b/Assembly-CSharp/RimWorld/RecordWorker_TimeGettingJoy.cs @@ -1,4 +1,3 @@ -using System; using Verse; using Verse.AI; diff --git a/Assembly-CSharp/RimWorld/RecordWorker_TimeHauling.cs b/Assembly-CSharp/RimWorld/RecordWorker_TimeHauling.cs index 2164982ac..42f08585e 100644 --- a/Assembly-CSharp/RimWorld/RecordWorker_TimeHauling.cs +++ b/Assembly-CSharp/RimWorld/RecordWorker_TimeHauling.cs @@ -1,4 +1,3 @@ -using System; using Verse; namespace RimWorld diff --git a/Assembly-CSharp/RimWorld/RecordWorker_TimeInBed.cs b/Assembly-CSharp/RimWorld/RecordWorker_TimeInBed.cs index 244f9eaee..ce35984ec 100644 --- a/Assembly-CSharp/RimWorld/RecordWorker_TimeInBed.cs +++ b/Assembly-CSharp/RimWorld/RecordWorker_TimeInBed.cs @@ -1,4 +1,3 @@ -using System; using Verse; namespace RimWorld diff --git a/Assembly-CSharp/RimWorld/RecordWorker_TimeInBedForMedicalReasons.cs b/Assembly-CSharp/RimWorld/RecordWorker_TimeInBedForMedicalReasons.cs index 2e6462e21..97c7f4a9a 100644 --- a/Assembly-CSharp/RimWorld/RecordWorker_TimeInBedForMedicalReasons.cs +++ b/Assembly-CSharp/RimWorld/RecordWorker_TimeInBedForMedicalReasons.cs @@ -1,4 +1,3 @@ -using System; using Verse; namespace RimWorld @@ -7,7 +6,11 @@ public class RecordWorker_TimeInBedForMedicalReasons : RecordWorker { public override bool ShouldMeasureTimeNow(Pawn pawn) { - return pawn.InBed() && (HealthAIUtility.ShouldSeekMedicalRestUrgent(pawn) || (HealthAIUtility.ShouldSeekMedicalRest(pawn) && (pawn.needs.rest.CurLevel >= 1f || pawn.CurJob.restUntilHealed))); + if (!pawn.InBed()) + { + return false; + } + return HealthAIUtility.ShouldSeekMedicalRestUrgent(pawn) || (HealthAIUtility.ShouldSeekMedicalRest(pawn) && (pawn.needs.rest.CurLevel >= 1.0 || pawn.CurJob.restUntilHealed)); } } } diff --git a/Assembly-CSharp/RimWorld/RecordWorker_TimeInMentalState.cs b/Assembly-CSharp/RimWorld/RecordWorker_TimeInMentalState.cs index 6df718153..98570e6c4 100644 --- a/Assembly-CSharp/RimWorld/RecordWorker_TimeInMentalState.cs +++ b/Assembly-CSharp/RimWorld/RecordWorker_TimeInMentalState.cs @@ -1,4 +1,3 @@ -using System; using Verse; namespace RimWorld diff --git a/Assembly-CSharp/RimWorld/RecordWorker_TimeOnFire.cs b/Assembly-CSharp/RimWorld/RecordWorker_TimeOnFire.cs index 4ca3af232..9a4e2e11c 100644 --- a/Assembly-CSharp/RimWorld/RecordWorker_TimeOnFire.cs +++ b/Assembly-CSharp/RimWorld/RecordWorker_TimeOnFire.cs @@ -1,4 +1,3 @@ -using System; using Verse; namespace RimWorld diff --git a/Assembly-CSharp/RimWorld/RecordWorker_TimeUnderRoof.cs b/Assembly-CSharp/RimWorld/RecordWorker_TimeUnderRoof.cs index 15b2deb9b..7bf44ebf8 100644 --- a/Assembly-CSharp/RimWorld/RecordWorker_TimeUnderRoof.cs +++ b/Assembly-CSharp/RimWorld/RecordWorker_TimeUnderRoof.cs @@ -1,4 +1,3 @@ -using System; using Verse; namespace RimWorld @@ -7,7 +6,11 @@ public class RecordWorker_TimeUnderRoof : RecordWorker { public override bool ShouldMeasureTimeNow(Pawn pawn) { - return pawn.Spawned && pawn.Position.Roofed(pawn.Map); + if (!pawn.Spawned) + { + return false; + } + return pawn.Position.Roofed(pawn.Map); } } } diff --git a/Assembly-CSharp/RimWorld/RecordsCardUtility.cs b/Assembly-CSharp/RimWorld/RecordsCardUtility.cs index c3ef2f541..85c1f1852 100644 --- a/Assembly-CSharp/RimWorld/RecordsCardUtility.cs +++ b/Assembly-CSharp/RimWorld/RecordsCardUtility.cs @@ -16,7 +16,7 @@ public static class RecordsCardUtility public static void DrawRecordsCard(Rect rect, Pawn pawn) { Text.Font = GameFont.Small; - Rect rect2 = new Rect(0f, 0f, rect.width - 16f, RecordsCardUtility.listHeight); + Rect rect2 = new Rect(0f, 0f, (float)(rect.width - 16.0), RecordsCardUtility.listHeight); Widgets.BeginScrollView(rect, ref RecordsCardUtility.scrollPosition, rect2, true); Rect leftRect = rect2; leftRect.width *= 0.5f; @@ -27,7 +27,7 @@ public static void DrawRecordsCard(Rect rect, Pawn pawn) rightRect.xMin += 6f; float a = RecordsCardUtility.DrawTimeRecords(leftRect, pawn); float b = RecordsCardUtility.DrawMiscRecords(rightRect, pawn); - RecordsCardUtility.listHeight = Mathf.Max(a, b) + 100f; + RecordsCardUtility.listHeight = (float)(Mathf.Max(a, b) + 100.0); Widgets.EndScrollView(); } @@ -41,7 +41,7 @@ private static float DrawTimeRecords(Rect leftRect, Pawn pawn) { if (allDefsListForReading[i].type == RecordType.Time) { - num += RecordsCardUtility.DrawRecord(8f, num, leftRect.width - 8f, allDefsListForReading[i], pawn); + num += RecordsCardUtility.DrawRecord(8f, num, (float)(leftRect.width - 8.0), allDefsListForReading[i], pawn); } } GUI.EndGroup(); @@ -58,7 +58,7 @@ private static float DrawMiscRecords(Rect rightRect, Pawn pawn) { if (allDefsListForReading[i].type == RecordType.Int || allDefsListForReading[i].type == RecordType.Float) { - num += RecordsCardUtility.DrawRecord(8f, num, rightRect.width - 8f, allDefsListForReading[i], pawn); + num += RecordsCardUtility.DrawRecord(8f, num, (float)(rightRect.width - 8.0), allDefsListForReading[i], pawn); } } GUI.EndGroup(); @@ -67,16 +67,8 @@ private static float DrawMiscRecords(Rect rightRect, Pawn pawn) private static float DrawRecord(float x, float y, float width, RecordDef record, Pawn pawn) { - float num = width * 0.45f; - string text; - if (record.type == RecordType.Time) - { - text = pawn.records.GetAsInt(record).ToStringTicksToPeriod(true, false, true); - } - else - { - text = pawn.records.GetValue(record).ToString("0.##"); - } + float num = (float)(width * 0.44999998807907104); + string text = (record.type != 0) ? pawn.records.GetValue(record).ToString("0.##") : pawn.records.GetAsInt(record).ToStringTicksToPeriod(true, false, true); Rect rect = new Rect(8f, y, width, Text.CalcHeight(text, num)); if (Mouse.IsOver(rect)) { @@ -89,7 +81,7 @@ private static float DrawRecord(float x, float y, float width, RecordDef record, rect3.x = rect2.xMax; rect3.width = num; Widgets.Label(rect3, text); - TooltipHandler.TipRegion(rect, new TipSignal(() => record.description, record.GetHashCode())); + TooltipHandler.TipRegion(rect, new TipSignal((Func)(() => record.description), record.GetHashCode())); return rect.height; } } diff --git a/Assembly-CSharp/RimWorld/RecordsUtility.cs b/Assembly-CSharp/RimWorld/RecordsUtility.cs index 54b8c09cc..e1b5ed8b8 100644 --- a/Assembly-CSharp/RimWorld/RecordsUtility.cs +++ b/Assembly-CSharp/RimWorld/RecordsUtility.cs @@ -1,4 +1,3 @@ -using System; using System.Collections.Generic; using Verse; @@ -46,7 +45,7 @@ public static void Notify_BillDone(Pawn billDoer, List products) { for (int i = 0; i < products.Count; i++) { - if (products[i].def.IsNutritionGivingIngestible && products[i].def.ingestible.preferability >= FoodPreferability.MealAwful) + if (products[i].def.IsNutritionGivingIngestible && (int)products[i].def.ingestible.preferability >= 5) { billDoer.records.Increment(RecordDefOf.MealsCooked); } diff --git a/Assembly-CSharp/RimWorld/RelationsUtility.cs b/Assembly-CSharp/RimWorld/RelationsUtility.cs index 06924fe46..1d9e287ca 100644 --- a/Assembly-CSharp/RimWorld/RelationsUtility.cs +++ b/Assembly-CSharp/RimWorld/RelationsUtility.cs @@ -9,7 +9,27 @@ public static class RelationsUtility { public static bool PawnsKnowEachOther(Pawn p1, Pawn p2) { - return (p1.Faction != null && p1.Faction == p2.Faction) || (p1.RaceProps.IsFlesh && p1.relations.DirectRelations.Find((DirectPawnRelation x) => x.otherPawn == p2) != null) || (p2.RaceProps.IsFlesh && p2.relations.DirectRelations.Find((DirectPawnRelation x) => x.otherPawn == p1) != null) || RelationsUtility.HasAnySocialMemoryWith(p1, p2) || RelationsUtility.HasAnySocialMemoryWith(p2, p1); + if (p1.Faction != null && p1.Faction == p2.Faction) + { + return true; + } + if (p1.RaceProps.IsFlesh && p1.relations.DirectRelations.Find((Predicate)((DirectPawnRelation x) => x.otherPawn == p2)) != null) + { + return true; + } + if (p2.RaceProps.IsFlesh && p2.relations.DirectRelations.Find((Predicate)((DirectPawnRelation x) => x.otherPawn == p1)) != null) + { + return true; + } + if (RelationsUtility.HasAnySocialMemoryWith(p1, p2)) + { + return true; + } + if (RelationsUtility.HasAnySocialMemoryWith(p2, p1)) + { + return true; + } + return false; } public static bool IsDisfigured(Pawn pawn) @@ -17,12 +37,9 @@ public static bool IsDisfigured(Pawn pawn) List hediffs = pawn.health.hediffSet.hediffs; for (int i = 0; i < hediffs.Count; i++) { - if (hediffs[i].Part != null && hediffs[i].Part.def.beautyRelated) + if (hediffs[i].Part != null && hediffs[i].Part.def.beautyRelated && (hediffs[i] is Hediff_MissingPart || hediffs[i] is Hediff_Injury)) { - if (hediffs[i] is Hediff_MissingPart || hediffs[i] is Hediff_Injury) - { - return true; - } + return true; } } return false; @@ -42,7 +59,7 @@ public static bool TryDevelopBondRelation(Pawn humanlike, Pawn animal, float bas { return false; } - if (animal.relations.GetFirstDirectRelationPawn(PawnRelationDefOf.Bond, (Pawn x) => x.Spawned) != null) + if (animal.relations.GetFirstDirectRelationPawn(PawnRelationDefOf.Bond, (Predicate)((Pawn x) => x.Spawned)) != null) { return false; } @@ -80,41 +97,20 @@ public static bool TryDevelopBondRelation(Pawn humanlike, Pawn animal, float bas } if (humanlike.Faction == Faction.OfPlayer || animal.Faction == Faction.OfPlayer) { - TaleRecorder.RecordTale(TaleDefOf.BondedWithAnimal, new object[] - { - humanlike, - animal - }); + TaleRecorder.RecordTale(TaleDefOf.BondedWithAnimal, humanlike, animal); } bool flag = false; - string text = null; + string text = (string)null; if (animal.Name == null || animal.Name.Numerical) { flag = true; text = ((animal.Name != null) ? animal.Name.ToStringFull : animal.LabelIndefinite()); - animal.Name = PawnBioAndNameGenerator.GeneratePawnName(animal, NameStyle.Full, null); + animal.Name = PawnBioAndNameGenerator.GeneratePawnName(animal, NameStyle.Full, (string)null); } if (PawnUtility.ShouldSendNotificationAbout(humanlike) || PawnUtility.ShouldSendNotificationAbout(animal)) { - string text2; - if (flag) - { - text2 = "MessageNewBondRelationNewName".Translate(new object[] - { - humanlike.LabelShort, - text, - animal.Name.ToStringFull - }).AdjustedFor(animal).CapitalizeFirst(); - } - else - { - text2 = "MessageNewBondRelation".Translate(new object[] - { - humanlike.LabelShort, - animal.LabelShort - }).CapitalizeFirst(); - } - Messages.Message(text2, humanlike, MessageSound.Benefit); + string text2 = (!flag) ? "MessageNewBondRelation".Translate(humanlike.LabelShort, animal.LabelShort).CapitalizeFirst() : "MessageNewBondRelationNewName".Translate(humanlike.LabelShort, text, animal.Name.ToStringFull).AdjustedFor(animal).CapitalizeFirst(); + Messages.Message(text2, (Thing)humanlike, MessageSound.Benefit); } return true; } @@ -133,22 +129,22 @@ public static string LabelWithBondInfo(Pawn humanlike, Pawn animal) private static bool HasAnySocialMemoryWith(Pawn p, Pawn otherPawn) { - if (!p.RaceProps.Humanlike || !otherPawn.RaceProps.Humanlike) + if (p.RaceProps.Humanlike && otherPawn.RaceProps.Humanlike) { - return false; - } - if (p.Dead) - { - return false; - } - List memories = p.needs.mood.thoughts.memories.Memories; - for (int i = 0; i < memories.Count; i++) - { - Thought_MemorySocial thought_MemorySocial = memories[i] as Thought_MemorySocial; - if (thought_MemorySocial != null && thought_MemorySocial.OtherPawn() == otherPawn) + if (p.Dead) { - return true; + return false; } + List memories = p.needs.mood.thoughts.memories.Memories; + for (int i = 0; i < memories.Count; i++) + { + Thought_MemorySocial thought_MemorySocial = memories[i] as Thought_MemorySocial; + if (thought_MemorySocial != null && thought_MemorySocial.OtherPawn() == otherPawn) + { + return true; + } + } + return false; } return false; } diff --git a/Assembly-CSharp/RimWorld/ResearchManager.cs b/Assembly-CSharp/RimWorld/ResearchManager.cs index 4db466842..37928f857 100644 --- a/Assembly-CSharp/RimWorld/ResearchManager.cs +++ b/Assembly-CSharp/RimWorld/ResearchManager.cs @@ -16,7 +16,7 @@ public bool AnyProjectIsAvailable { get { - return DefDatabase.AllDefsListForReading.Find((ResearchProjectDef x) => x.CanStartNow) != null; + return DefDatabase.AllDefsListForReading.Find((Predicate)((ResearchProjectDef x) => x.CanStartNow)) != null; } } @@ -28,7 +28,7 @@ public void ExposeData() public float GetProgress(ResearchProjectDef proj) { - float result; + float result = default(float); if (this.progress.TryGetValue(proj, out result)) { return result; @@ -42,47 +42,45 @@ public void ResearchPerformed(float amount, Pawn researcher) if (this.currentProj == null) { Log.Error("Researched without having an active project."); - return; } - amount *= this.GlobalProgressFactor; - if (researcher != null && researcher.Faction != null) + else { - amount /= this.currentProj.CostFactor(researcher.Faction.def.techLevel); - } - if (DebugSettings.fastResearch) - { - amount *= 500f; - } - if (researcher != null) - { - researcher.records.AddTo(RecordDefOf.ResearchPointsResearched, amount); - } - float num = this.GetProgress(this.currentProj); - num += amount; - this.progress[this.currentProj] = num; - if (this.currentProj.IsFinished) - { - this.ReapplyAllMods(); - this.DoCompletionDialog(this.currentProj, researcher); + amount *= this.GlobalProgressFactor; + if (researcher != null && researcher.Faction != null) + { + amount /= this.currentProj.CostFactor(researcher.Faction.def.techLevel); + } + if (DebugSettings.fastResearch) + { + amount = (float)(amount * 500.0); + } if (researcher != null) { - TaleRecorder.RecordTale(TaleDefOf.FinishedResearchProject, new object[] + researcher.records.AddTo(RecordDefOf.ResearchPointsResearched, amount); + } + float num = this.GetProgress(this.currentProj); + num += amount; + this.progress[this.currentProj] = num; + if (this.currentProj.IsFinished) + { + this.ReapplyAllMods(); + this.DoCompletionDialog(this.currentProj, researcher); + if (researcher != null) { - researcher, - this.currentProj - }); + TaleRecorder.RecordTale(TaleDefOf.FinishedResearchProject, researcher, this.currentProj); + } + this.currentProj = null; } - this.currentProj = null; } } public void ReapplyAllMods() { - foreach (ResearchProjectDef current in DefDatabase.AllDefs) + foreach (ResearchProjectDef allDef in DefDatabase.AllDefs) { - if (current.IsFinished) + if (allDef.IsFinished) { - current.ReapplyAllMods(); + allDef.ReapplyAllMods(); } } } @@ -109,28 +107,25 @@ public void InstantFinish(ResearchProjectDef proj, bool doCompletionDialog = fal private void DoCompletionDialog(ResearchProjectDef proj, Pawn researcher) { - string text = "ResearchFinished".Translate(new object[] - { - this.currentProj.LabelCap - }) + "\n\n" + this.currentProj.DescriptionDiscovered; + string text = "ResearchFinished".Translate(this.currentProj.LabelCap) + "\n\n" + this.currentProj.DescriptionDiscovered; DiaNode diaNode = new DiaNode(text); diaNode.options.Add(DiaOption.DefaultOK); DiaOption diaOption = new DiaOption("ResearchScreen".Translate()); diaOption.resolveTree = true; - diaOption.action = delegate + diaOption.action = (Action)delegate { Find.MainTabsRoot.SetCurrentTab(MainButtonDefOf.Research, true); }; diaNode.options.Add(diaOption); - Find.WindowStack.Add(new Dialog_NodeTree(diaNode, true, false, null)); + Find.WindowStack.Add(new Dialog_NodeTree(diaNode, true, false, (string)null)); } public void DebugSetAllProjectsFinished() { this.progress.Clear(); - foreach (ResearchProjectDef current in DefDatabase.AllDefs) + foreach (ResearchProjectDef allDef in DefDatabase.AllDefs) { - this.progress.Add(current, current.baseCost); + this.progress.Add(allDef, allDef.baseCost); } this.ReapplyAllMods(); } diff --git a/Assembly-CSharp/RimWorld/ResearchProjectDefOf.cs b/Assembly-CSharp/RimWorld/ResearchProjectDefOf.cs index a4e17ca6c..2f9368edc 100644 --- a/Assembly-CSharp/RimWorld/ResearchProjectDefOf.cs +++ b/Assembly-CSharp/RimWorld/ResearchProjectDefOf.cs @@ -1,4 +1,3 @@ -using System; using Verse; namespace RimWorld diff --git a/Assembly-CSharp/RimWorld/ResearchTabDef.cs b/Assembly-CSharp/RimWorld/ResearchTabDef.cs index 048f10ed5..60fec819b 100644 --- a/Assembly-CSharp/RimWorld/ResearchTabDef.cs +++ b/Assembly-CSharp/RimWorld/ResearchTabDef.cs @@ -1,4 +1,3 @@ -using System; using Verse; namespace RimWorld diff --git a/Assembly-CSharp/RimWorld/ResearchTabDefOf.cs b/Assembly-CSharp/RimWorld/ResearchTabDefOf.cs index 71788ca23..c53c122cc 100644 --- a/Assembly-CSharp/RimWorld/ResearchTabDefOf.cs +++ b/Assembly-CSharp/RimWorld/ResearchTabDefOf.cs @@ -1,5 +1,3 @@ -using System; - namespace RimWorld { [DefOf] diff --git a/Assembly-CSharp/RimWorld/ReservationLayerDefOf.cs b/Assembly-CSharp/RimWorld/ReservationLayerDefOf.cs index 444605ef4..87724d2df 100644 --- a/Assembly-CSharp/RimWorld/ReservationLayerDefOf.cs +++ b/Assembly-CSharp/RimWorld/ReservationLayerDefOf.cs @@ -1,4 +1,3 @@ -using System; using Verse; namespace RimWorld diff --git a/Assembly-CSharp/RimWorld/ResolutionUtility.cs b/Assembly-CSharp/RimWorld/ResolutionUtility.cs index 922ac3a40..094af5c3f 100644 --- a/Assembly-CSharp/RimWorld/ResolutionUtility.cs +++ b/Assembly-CSharp/RimWorld/ResolutionUtility.cs @@ -1,4 +1,3 @@ -using System; using UnityEngine; using Verse; @@ -13,9 +12,7 @@ public static class ResolutionUtility public static void SafeSetResolution(Resolution res) { if (Screen.width == res.width && Screen.height == res.height) - { return; - } IntVec2 oldRes = new IntVec2(Screen.width, Screen.height); Screen.SetResolution(res.width, res.height, Screen.fullScreen); Find.WindowStack.Add(new Dialog_ResolutionConfirm(oldRes)); @@ -23,29 +20,27 @@ public static void SafeSetResolution(Resolution res) public static void SafeSetFullscreen(bool fullScreen) { - if (Screen.fullScreen == fullScreen) + if (Screen.fullScreen != fullScreen) { - return; + bool fullScreen2 = Screen.fullScreen; + Screen.fullScreen = fullScreen; + Find.WindowStack.Add(new Dialog_ResolutionConfirm(fullScreen2)); } - bool fullScreen2 = Screen.fullScreen; - Screen.fullScreen = fullScreen; - Find.WindowStack.Add(new Dialog_ResolutionConfirm(fullScreen2)); } public static void SafeSetUIScale(float newScale) { - if (Prefs.UIScale == newScale) + if (Prefs.UIScale != newScale) { - return; + float uIScale = Prefs.UIScale; + Prefs.UIScale = newScale; + Find.WindowStack.Add(new Dialog_ResolutionConfirm(uIScale)); } - float uIScale = Prefs.UIScale; - Prefs.UIScale = newScale; - Find.WindowStack.Add(new Dialog_ResolutionConfirm(uIScale)); } public static bool UIScaleSafeWithResolution(float scale, int w, int h) { - return (float)w / scale >= 1024f && (float)h / scale >= 768f; + return (float)w / scale >= 1024.0 && (float)h / scale >= 768.0; } } } diff --git a/Assembly-CSharp/RimWorld/ResourceCounter.cs b/Assembly-CSharp/RimWorld/ResourceCounter.cs index da449aa94..3c2709cd9 100644 --- a/Assembly-CSharp/RimWorld/ResourceCounter.cs +++ b/Assembly-CSharp/RimWorld/ResourceCounter.cs @@ -34,14 +34,23 @@ public float TotalHumanEdibleNutrition get { float num = 0f; - foreach (KeyValuePair current in this.countedAmounts) + Dictionary.Enumerator enumerator = this.countedAmounts.GetEnumerator(); + try { - if (current.Key.IsNutritionGivingIngestible && current.Key.ingestible.HumanEdible) + while (enumerator.MoveNext()) { - num += current.Key.ingestible.nutrition * (float)current.Value; + KeyValuePair current = enumerator.Current; + if (current.Key.IsNutritionGivingIngestible && current.Key.ingestible.HumanEdible) + { + num += current.Key.ingestible.nutrition * (float)current.Value; + } } + return num; + } + finally + { + ((IDisposable)(object)enumerator).Dispose(); } - return num; } } @@ -83,7 +92,7 @@ public int GetCount(ThingDef rDef) { return 0; } - int result; + int result = default(int); if (this.countedAmounts.TryGetValue(rDef, out result)) { return result; @@ -96,14 +105,23 @@ public int GetCount(ThingDef rDef) public int GetCountIn(ThingRequestGroup group) { int num = 0; - foreach (KeyValuePair current in this.countedAmounts) + Dictionary.Enumerator enumerator = this.countedAmounts.GetEnumerator(); + try { - if (group.Includes(current.Key)) + while (enumerator.MoveNext()) { - num += current.Value; + KeyValuePair current = enumerator.Current; + if (group.Includes(current.Key)) + { + num += current.Value; + } } + return num; + } + finally + { + ((IDisposable)(object)enumerator).Dispose(); } - return num; } public int GetCountIn(ThingCategoryDef cat) @@ -138,16 +156,16 @@ public void UpdateResourceCounts() for (int i = 0; i < allGroupsListForReading.Count; i++) { SlotGroup slotGroup = allGroupsListForReading[i]; - foreach (Thing current in slotGroup.HeldThings) + foreach (Thing heldThing in slotGroup.HeldThings) { - if (current.def.CountAsResource && this.ShouldCount(current)) + if (heldThing.def.CountAsResource && this.ShouldCount(heldThing)) { Dictionary dictionary; - Dictionary expr_62 = dictionary = this.countedAmounts; + Dictionary obj = dictionary = this.countedAmounts; ThingDef def; - ThingDef expr_6B = def = current.def; + ThingDef key = def = heldThing.def; int num = dictionary[def]; - expr_62[expr_6B] = num + current.stackCount; + obj[key] = num + heldThing.stackCount; } } } @@ -155,7 +173,11 @@ public void UpdateResourceCounts() private bool ShouldCount(Thing t) { - return !t.IsNotFresh(); + if (t.IsNotFresh()) + { + return false; + } + return true; } } } diff --git a/Assembly-CSharp/RimWorld/ResourceReadout.cs b/Assembly-CSharp/RimWorld/ResourceReadout.cs index fa3e0e253..c12229dc3 100644 --- a/Assembly-CSharp/RimWorld/ResourceReadout.cs +++ b/Assembly-CSharp/RimWorld/ResourceReadout.cs @@ -24,52 +24,43 @@ public ResourceReadout() { this.RootThingCategories = (from cat in DefDatabase.AllDefs where cat.resourceReadoutRoot - select cat).ToList(); + select cat).ToList(); } public void ResourceReadoutOnGUI() { - if (Event.current.type == EventType.Layout) + if (Event.current.type != EventType.Layout && Current.ProgramState == ProgramState.Playing && Find.MainTabsRoot.OpenTab != MainButtonDefOf.Menu) { - return; - } - if (Current.ProgramState != ProgramState.Playing) - { - return; - } - if (Find.MainTabsRoot.OpenTab == MainButtonDefOf.Menu) - { - return; - } - GenUI.DrawTextWinterShadow(new Rect(256f, 512f, -256f, -512f)); - Text.Font = GameFont.Small; - Rect rect = (!Prefs.ResourceReadoutCategorized) ? new Rect(7f, 7f, 110f, (float)(UI.screenHeight - 7) - 200f) : new Rect(2f, 7f, 124f, (float)(UI.screenHeight - 7) - 200f); - Rect rect2 = new Rect(0f, 0f, rect.width, this.lastDrawnHeight); - bool flag = rect2.height > rect.height; - if (flag) - { - Widgets.BeginScrollView(rect, ref this.scrollPosition, rect2, false); - } - else - { - this.scrollPosition = Vector2.zero; - GUI.BeginGroup(rect); - } - if (!Prefs.ResourceReadoutCategorized) - { - this.DoReadoutSimple(rect2, rect.height); - } - else - { - this.DoReadoutCategorized(rect2); - } - if (flag) - { - Widgets.EndScrollView(); - } - else - { - GUI.EndGroup(); + GenUI.DrawTextWinterShadow(new Rect(256f, 512f, -256f, -512f)); + Text.Font = GameFont.Small; + Rect rect = (!Prefs.ResourceReadoutCategorized) ? new Rect(7f, 7f, 110f, (float)((float)(UI.screenHeight - 7) - 200.0)) : new Rect(2f, 7f, 124f, (float)((float)(UI.screenHeight - 7) - 200.0)); + Rect rect2 = new Rect(0f, 0f, rect.width, this.lastDrawnHeight); + bool flag = rect2.height > rect.height; + if (flag) + { + Widgets.BeginScrollView(rect, ref this.scrollPosition, rect2, false); + } + else + { + this.scrollPosition = Vector2.zero; + GUI.BeginGroup(rect); + } + if (!Prefs.ResourceReadoutCategorized) + { + this.DoReadoutSimple(rect2, rect.height); + } + else + { + this.DoReadoutCategorized(rect2); + } + if (flag) + { + Widgets.EndScrollView(); + } + else + { + GUI.EndGroup(); + } } } @@ -93,18 +84,27 @@ private void DoReadoutSimple(Rect rect, float outRectHeight) GUI.BeginGroup(rect); Text.Anchor = TextAnchor.MiddleLeft; float num = 0f; - foreach (KeyValuePair current in Find.VisibleMap.resourceCounter.AllCountedAmounts) + Dictionary.Enumerator enumerator = Find.VisibleMap.resourceCounter.AllCountedAmounts.GetEnumerator(); + try { - if (current.Value > 0 || current.Key.resourceReadoutAlwaysShow) + while (enumerator.MoveNext()) { - Rect rect2 = new Rect(0f, num, 999f, 24f); - if (rect2.yMax >= this.scrollPosition.y && rect2.y <= this.scrollPosition.y + outRectHeight) + KeyValuePair current = enumerator.Current; + if (current.Value > 0 || current.Key.resourceReadoutAlwaysShow) { - this.DrawResourceSimple(rect2, current.Key); + Rect rect2 = new Rect(0f, num, 999f, 24f); + if (rect2.yMax >= this.scrollPosition.y && rect2.y <= this.scrollPosition.y + outRectHeight) + { + this.DrawResourceSimple(rect2, current.Key); + } + num = (float)(num + 24.0); } - num += 24f; } } + finally + { + ((IDisposable)(object)enumerator).Dispose(); + } Text.Anchor = TextAnchor.UpperLeft; this.lastDrawnHeight = num; GUI.EndGroup(); @@ -115,7 +115,7 @@ public void DrawResourceSimple(Rect rect, ThingDef thingDef) this.DrawIcon(rect.x, rect.y, thingDef); rect.y += 2f; int count = Find.VisibleMap.resourceCounter.GetCount(thingDef); - Rect rect2 = new Rect(34f, rect.y, rect.width - 34f, rect.height); + Rect rect2 = new Rect(34f, rect.y, (float)(rect.width - 34.0), rect.height); Widgets.Label(rect2, count.ToStringCached()); } @@ -126,7 +126,7 @@ private void DrawIcon(float x, float y, ThingDef thingDef) GUI.color = thingDef.graphicData.color; GUI.DrawTexture(rect, thingDef.uiIcon); GUI.color = color; - TooltipHandler.TipRegion(rect, new TipSignal(() => thingDef.LabelCap + ": " + thingDef.description, thingDef.GetHashCode())); + TooltipHandler.TipRegion(rect, new TipSignal((Func)(() => thingDef.LabelCap + ": " + thingDef.description), thingDef.GetHashCode())); } } } diff --git a/Assembly-CSharp/RimWorld/ResourceReadoutMode.cs b/Assembly-CSharp/RimWorld/ResourceReadoutMode.cs index 838617aa2..7d1aa2c79 100644 --- a/Assembly-CSharp/RimWorld/ResourceReadoutMode.cs +++ b/Assembly-CSharp/RimWorld/ResourceReadoutMode.cs @@ -1,10 +1,8 @@ -using System; - namespace RimWorld { public enum ResourceReadoutMode : byte { - Simple, - Categorized + Simple = 0, + Categorized = 1 } } diff --git a/Assembly-CSharp/RimWorld/RestCategory.cs b/Assembly-CSharp/RimWorld/RestCategory.cs index 08d14d9c7..618d2559a 100644 --- a/Assembly-CSharp/RimWorld/RestCategory.cs +++ b/Assembly-CSharp/RimWorld/RestCategory.cs @@ -1,12 +1,10 @@ -using System; - namespace RimWorld { public enum RestCategory : byte { - Rested, - Tired, - VeryTired, - Exhausted + Rested = 0, + Tired = 1, + VeryTired = 2, + Exhausted = 3 } } diff --git a/Assembly-CSharp/RimWorld/RestCategoryUtility.cs b/Assembly-CSharp/RimWorld/RestCategoryUtility.cs index 16c2a4b7c..19700d1f6 100644 --- a/Assembly-CSharp/RimWorld/RestCategoryUtility.cs +++ b/Assembly-CSharp/RimWorld/RestCategoryUtility.cs @@ -9,17 +9,27 @@ public static string GetLabel(this RestCategory fatigue) { switch (fatigue) { - case RestCategory.Rested: - return "HungerLevel_Rested".Translate(); - case RestCategory.Tired: - return "HungerLevel_Tired".Translate(); - case RestCategory.VeryTired: - return "HungerLevel_VeryTired".Translate(); case RestCategory.Exhausted: + { return "HungerLevel_Exhausted".Translate(); + } + case RestCategory.VeryTired: + { + return "HungerLevel_VeryTired".Translate(); + } + case RestCategory.Tired: + { + return "HungerLevel_Tired".Translate(); + } + case RestCategory.Rested: + { + return "HungerLevel_Rested".Translate(); + } default: + { throw new InvalidOperationException(); } + } } } } diff --git a/Assembly-CSharp/RimWorld/RestUtility.cs b/Assembly-CSharp/RimWorld/RestUtility.cs index bc738570d..0ab9dbd41 100644 --- a/Assembly-CSharp/RimWorld/RestUtility.cs +++ b/Assembly-CSharp/RimWorld/RestUtility.cs @@ -27,11 +27,11 @@ public static void Reset() RestUtility.bedDefsBestToWorst_RestEffectiveness = (from d in DefDatabase.AllDefs where d.IsBed orderby d.building.bed_maxBodySize, d.GetStatValueAbstract(StatDefOf.BedRestEffectiveness, null) descending - select d).ToList(); + select d).ToList(); RestUtility.bedDefsBestToWorst_Medical = (from d in DefDatabase.AllDefs where d.IsBed orderby d.building.bed_maxBodySize, d.GetStatValueAbstract(StatDefOf.MedicalTendQualityOffset, null) descending, d.GetStatValueAbstract(StatDefOf.BedRestEffectiveness, null) descending - select d).ToList(); + select d).ToList(); } public static bool IsValidBedFor(Thing bedThing, Pawn sleeper, Pawn traveler, bool sleeperWillBePrisoner, bool checkSocialProperness, bool allowMedBedEvenIfSetToNoCare = false, bool ignoreOtherReservations = false) @@ -41,7 +41,7 @@ public static bool IsValidBedFor(Thing bedThing, Pawn sleeper, Pawn traveler, bo { return false; } - if (!traveler.CanReserveAndReach(building_Bed, PathEndMode.OnCell, Danger.Some, building_Bed.SleepingSlotsCount, -1, null, ignoreOtherReservations)) + if (!traveler.CanReserveAndReach((Thing)building_Bed, PathEndMode.OnCell, Danger.Some, building_Bed.SleepingSlotsCount, -1, null, ignoreOtherReservations)) { return false; } @@ -98,27 +98,27 @@ public static bool IsValidBedFor(Thing bedThing, Pawn sleeper, Pawn traveler, bo return false; } } - else if (building_Bed.owners.Any() && !building_Bed.owners.Contains(sleeper)) + else if (building_Bed.owners.Any() && !building_Bed.owners.Contains(sleeper)) { - if (sleeper.IsPrisoner || sleeperWillBePrisoner) + if (!sleeper.IsPrisoner && !sleeperWillBePrisoner) { - if (!building_Bed.AnyUnownedSleepingSlot) + if (RestUtility.IsAnyOwnerLovePartnerOf(building_Bed, sleeper)) { - return false; + if (!building_Bed.AnyUnownedSleepingSlot) + { + return false; + } + goto IL_018f; } + return false; } - else + if (!building_Bed.AnyUnownedSleepingSlot) { - if (!RestUtility.IsAnyOwnerLovePartnerOf(building_Bed, sleeper)) - { - return false; - } - if (!building_Bed.AnyUnownedSleepingSlot) - { - return false; - } + return false; } } + goto IL_018f; + IL_018f: return true; } @@ -153,19 +153,19 @@ public static Building_Bed FindBedFor(Pawn sleeper, Pawn traveler, bool sleeperW } for (int i = 0; i < RestUtility.bedDefsBestToWorst_Medical.Count; i++) { - Predicate validator = delegate(Thing b) + Predicate validator = (Predicate)delegate(Thing b) { - bool arg_3A_0; + int result2; if (((Building_Bed)b).Medical) { - bool ignoreOtherReservations3 = ignoreOtherReservations; - arg_3A_0 = RestUtility.IsValidBedFor(b, sleeper, traveler, sleeperWillBePrisoner, checkSocialProperness, false, ignoreOtherReservations3); + bool ignoreOtherReservations4 = ignoreOtherReservations; + result2 = (RestUtility.IsValidBedFor(b, sleeper, traveler, sleeperWillBePrisoner, checkSocialProperness, false, ignoreOtherReservations4) ? 1 : 0); } else { - arg_3A_0 = false; + result2 = 0; } - return arg_3A_0; + return (byte)result2 != 0; }; Building_Bed building_Bed = (Building_Bed)GenClosest.ClosestThingReachable(sleeper.Position, sleeper.Map, ThingRequest.ForDef(RestUtility.bedDefsBestToWorst_Medical[i]), PathEndMode.OnCell, TraverseParms.For(traveler, Danger.Deadly, TraverseMode.ByPawn, false), 9999f, validator, null, 0, -1, false, RegionType.Set_Passable, false); if (building_Bed != null) @@ -200,19 +200,19 @@ public static Building_Bed FindBedFor(Pawn sleeper, Pawn traveler, bool sleeperW ThingDef thingDef = RestUtility.bedDefsBestToWorst_RestEffectiveness[j]; if (RestUtility.CanUseBedEver(sleeper, thingDef)) { - Predicate validator = delegate(Thing b) + Predicate validator = (Predicate)delegate(Thing b) { - bool arg_3A_0; + int result; if (!((Building_Bed)b).Medical) { bool ignoreOtherReservations3 = ignoreOtherReservations; - arg_3A_0 = RestUtility.IsValidBedFor(b, sleeper, traveler, sleeperWillBePrisoner, checkSocialProperness, false, ignoreOtherReservations3); + result = (RestUtility.IsValidBedFor(b, sleeper, traveler, sleeperWillBePrisoner, checkSocialProperness, false, ignoreOtherReservations3) ? 1 : 0); } else { - arg_3A_0 = false; + result = 0; } - return arg_3A_0; + return (byte)result != 0; }; Building_Bed building_Bed2 = (Building_Bed)GenClosest.ClosestThingReachable(sleeper.Position, sleeper.Map, ThingRequest.ForDef(thingDef), PathEndMode.OnCell, TraverseParms.For(traveler, Danger.Deadly, TraverseMode.ByPawn, false), 9999f, validator, null, 0, -1, false, RegionType.Set_Passable, false); if (building_Bed2 != null) @@ -226,10 +226,22 @@ public static Building_Bed FindBedFor(Pawn sleeper, Pawn traveler, bool sleeperW public static Building_Bed FindPatientBedFor(Pawn pawn) { - Predicate predicate = delegate(Thing t) + Predicate predicate = (Predicate)delegate(Thing t) { Building_Bed building_Bed2 = t as Building_Bed; - return building_Bed2 != null && (building_Bed2.Medical || !building_Bed2.def.building.bed_humanlike) && RestUtility.IsValidBedFor(building_Bed2, pawn, pawn, pawn.IsPrisoner, false, true, false); + if (building_Bed2 == null) + { + return false; + } + if (!building_Bed2.Medical && building_Bed2.def.building.bed_humanlike) + { + return false; + } + if (!RestUtility.IsValidBedFor(building_Bed2, pawn, pawn, pawn.IsPrisoner, false, true, false)) + { + return false; + } + return true; }; if (pawn.InBed() && predicate(pawn.CurrentBed())) { @@ -275,12 +287,24 @@ public static IntVec3 GetBedSleepingSlotPosFor(Pawn pawn, Building_Bed bed) public static bool CanUseBedEver(Pawn p, ThingDef bedDef) { - return p.BodySize <= bedDef.building.bed_maxBodySize && p.RaceProps.Humanlike == bedDef.building.bed_humanlike; + if (p.BodySize > bedDef.building.bed_maxBodySize) + { + return false; + } + if (p.RaceProps.Humanlike != bedDef.building.bed_humanlike) + { + return false; + } + return true; } public static bool TimetablePreventsLayDown(Pawn pawn) { - return pawn.timetable != null && !pawn.timetable.CurrentAssignment.allowRest && pawn.needs.rest.CurLevel >= 0.2f; + if (pawn.timetable != null && !pawn.timetable.CurrentAssignment.allowRest && pawn.needs.rest.CurLevel >= 0.20000000298023224) + { + return true; + } + return false; } public static bool DisturbancePreventsLyingDown(Pawn pawn) @@ -295,35 +319,46 @@ public static float PawnHealthRestEffectivenessFactor(Pawn pawn) public static bool Awake(this Pawn p) { - return p.health.capacities.CanBeAwake && (!p.Spawned || p.CurJob == null || !p.jobs.curDriver.asleep); + if (!p.health.capacities.CanBeAwake) + { + return false; + } + if (!p.Spawned) + { + return true; + } + return p.CurJob == null || !p.jobs.curDriver.asleep; } public static Building_Bed CurrentBed(this Pawn p) { - if (!p.Spawned || p.CurJob == null || p.jobs.curDriver.layingDown != LayingDownState.LayingInBed) - { - return null; - } - Building_Bed building_Bed = null; - List thingList = p.Position.GetThingList(p.Map); - for (int i = 0; i < thingList.Count; i++) + if (p.Spawned && p.CurJob != null && p.jobs.curDriver.layingDown == LayingDownState.LayingInBed) { - building_Bed = (thingList[i] as Building_Bed); - if (building_Bed != null) + Building_Bed building_Bed = null; + List thingList = p.Position.GetThingList(p.Map); + int num = 0; + while (num < thingList.Count) { + building_Bed = (thingList[num] as Building_Bed); + if (building_Bed == null) + { + num++; + continue; + } break; } - } - if (building_Bed == null) - { - return null; - } - for (int j = 0; j < building_Bed.SleepingSlotsCount; j++) - { - if (building_Bed.GetCurOccupant(j) == p) + if (building_Bed == null) { - return building_Bed; + return null; } + for (int i = 0; i < building_Bed.SleepingSlotsCount; i++) + { + if (building_Bed.GetCurOccupant(i) == p) + { + return building_Bed; + } + } + return null; } return null; } @@ -335,7 +370,7 @@ public static bool InBed(this Pawn p) public static void WakeUp(Pawn p) { - if (p.CurJob != null && p.jobs.curDriver.layingDown != LayingDownState.NotLaying && !p.Downed) + if (p.CurJob != null && p.jobs.curDriver.layingDown != 0 && !p.Downed) { p.jobs.EndCurrentJob(JobCondition.InterruptForced, true); } @@ -353,7 +388,7 @@ public static float WakeThreshold(Pawn p) public static float FallAsleepMaxLevel(Pawn p) { - return Mathf.Min(0.75f, RestUtility.WakeThreshold(p) - 0.01f); + return Mathf.Min(0.75f, (float)(RestUtility.WakeThreshold(p) - 0.0099999997764825821)); } } } diff --git a/Assembly-CSharp/RimWorld/RestraintsUtility.cs b/Assembly-CSharp/RimWorld/RestraintsUtility.cs index 46a50e821..b25685491 100644 --- a/Assembly-CSharp/RimWorld/RestraintsUtility.cs +++ b/Assembly-CSharp/RimWorld/RestraintsUtility.cs @@ -1,4 +1,3 @@ -using System; using Verse; using Verse.AI.Group; @@ -17,7 +16,11 @@ public static bool InRestraints(Pawn pawn) return false; } Lord lord = pawn.GetLord(); - return lord == null || lord.LordJob == null || !lord.LordJob.NeverInRestraints; + if (lord != null && lord.LordJob != null && lord.LordJob.NeverInRestraints) + { + return false; + } + return true; } public static bool ShouldShowRestraintsInfo(Pawn pawn) diff --git a/Assembly-CSharp/RimWorld/RiverDef.cs b/Assembly-CSharp/RimWorld/RiverDef.cs index adedaeef1..fa5319c01 100644 --- a/Assembly-CSharp/RimWorld/RiverDef.cs +++ b/Assembly-CSharp/RimWorld/RiverDef.cs @@ -1,4 +1,3 @@ -using System; using System.Collections.Generic; using Verse; @@ -23,7 +22,7 @@ public class Branch public RiverDef degradeChild; - public List branches; + public List branches; public float widthOnWorld = 0.5f; diff --git a/Assembly-CSharp/RimWorld/RiverMaker.cs b/Assembly-CSharp/RimWorld/RiverMaker.cs index eb5d5b79b..64ecd9571 100644 --- a/Assembly-CSharp/RimWorld/RiverMaker.cs +++ b/Assembly-CSharp/RimWorld/RiverMaker.cs @@ -1,4 +1,3 @@ -using System; using UnityEngine; using Verse; using Verse.Noise; @@ -15,17 +14,17 @@ internal class RiverMaker public RiverMaker(Vector3 center, float angleA, float angleB, RiverDef riverDef) { - this.surfaceLevel = riverDef.widthOnMap / 2f; + this.surfaceLevel = (float)(riverDef.widthOnMap / 2.0); this.generator = new DistFromAxis(1f); - this.generator = new Bend((angleB - (angleA + 180f) + 360f) % 360f, 50f, this.generator); - this.generator = new Rotate(0.0, (double)(-(double)angleA), 0.0, this.generator); - this.generator = new Translate((double)(-(double)center.x), 0.0, (double)(-(double)center.z), this.generator); - ModuleBase moduleBase = new Perlin(0.029999999329447746, 2.0, 0.5, 3, Rand.Range(0, 2147483647), QualityMode.Medium); - ModuleBase moduleBase2 = new Perlin(0.029999999329447746, 2.0, 0.5, 3, Rand.Range(0, 2147483647), QualityMode.Medium); + this.generator = new Bend((float)((angleB - (angleA + 180.0) + 360.0) % 360.0), 50f, this.generator); + this.generator = new Rotate(0.0, 0.0 - angleA, 0.0, this.generator); + this.generator = new Translate(0.0 - center.x, 0.0, 0.0 - center.z, this.generator); + ModuleBase lhs = new Perlin(0.029999999329447746, 2.0, 0.5, 3, Rand.Range(0, 2147483647), QualityMode.Medium); + ModuleBase lhs2 = new Perlin(0.029999999329447746, 2.0, 0.5, 3, Rand.Range(0, 2147483647), QualityMode.Medium); ModuleBase rhs = new Const(8.0); - moduleBase = new Multiply(moduleBase, rhs); - moduleBase2 = new Multiply(moduleBase2, rhs); - this.generator = new Displace(this.generator, moduleBase, new Const(0.0), moduleBase2); + lhs = new Multiply(lhs, rhs); + lhs2 = new Multiply(lhs2, rhs); + this.generator = new Displace(this.generator, lhs, new Const(0.0), lhs2); this.shallowizer = new Perlin(0.029999999329447746, 2.0, 0.5, 3, Rand.Range(0, 2147483647), QualityMode.Medium); this.shallowizer = new Abs(this.shallowizer); } @@ -33,7 +32,7 @@ public RiverMaker(Vector3 center, float angleA, float angleB, RiverDef riverDef) public TerrainDef TerrainAt(IntVec3 loc) { float value = this.generator.GetValue(loc); - if (value < this.surfaceLevel - 2f && this.shallowizer.GetValue(loc) > 0.2f) + if (value < this.surfaceLevel - 2.0 && this.shallowizer.GetValue(loc) > 0.20000000298023224) { return TerrainDefOf.WaterMovingDeep; } diff --git a/Assembly-CSharp/RimWorld/RoadDef.cs b/Assembly-CSharp/RimWorld/RoadDef.cs index f5a952f02..b4016537a 100644 --- a/Assembly-CSharp/RimWorld/RoadDef.cs +++ b/Assembly-CSharp/RimWorld/RoadDef.cs @@ -25,7 +25,7 @@ public class WorldRenderStep public List roadGenSteps; - public List worldRenderSteps; + public List worldRenderSteps; public string worldTransitionGroup = string.Empty; @@ -46,17 +46,26 @@ public float GetLayerWidth(RoadWorldLayerDef def) RoadWorldLayerDef roadWorldLayerDef = DefDatabase.AllDefsListForReading[i]; if (this.worldRenderSteps != null) { - foreach (RoadDef.WorldRenderStep current in this.worldRenderSteps) + List.Enumerator enumerator = this.worldRenderSteps.GetEnumerator(); + try { - if (current.layer == roadWorldLayerDef) + while (enumerator.MoveNext()) { - this.cachedLayerWidth[(int)roadWorldLayerDef.index] = current.width; + WorldRenderStep current = enumerator.Current; + if (current.layer == roadWorldLayerDef) + { + this.cachedLayerWidth[roadWorldLayerDef.index] = current.width; + } } } + finally + { + ((IDisposable)(object)enumerator).Dispose(); + } } } } - return this.cachedLayerWidth[(int)def.index]; + return this.cachedLayerWidth[def.index]; } public override void ClearCachedData() diff --git a/Assembly-CSharp/RimWorld/RoadDefGenStep.cs b/Assembly-CSharp/RimWorld/RoadDefGenStep.cs index cba7d0044..558f2e4ff 100644 --- a/Assembly-CSharp/RimWorld/RoadDefGenStep.cs +++ b/Assembly-CSharp/RimWorld/RoadDefGenStep.cs @@ -1,4 +1,3 @@ -using System; using Verse; namespace RimWorld diff --git a/Assembly-CSharp/RimWorld/RoadDefGenStep_Bulldoze.cs b/Assembly-CSharp/RimWorld/RoadDefGenStep_Bulldoze.cs index a28e67e54..32fd67911 100644 --- a/Assembly-CSharp/RimWorld/RoadDefGenStep_Bulldoze.cs +++ b/Assembly-CSharp/RimWorld/RoadDefGenStep_Bulldoze.cs @@ -1,4 +1,5 @@ using System; +using System.Collections.Generic; using Verse; namespace RimWorld @@ -9,14 +10,23 @@ public override void Place(Map map, IntVec3 tile, TerrainDef rockDef) { while (tile.Impassable(map)) { - foreach (Thing current in tile.GetThingList(map)) + List.Enumerator enumerator = tile.GetThingList(map).GetEnumerator(); + try { - if (current.def.passability == Traversability.Impassable) + while (enumerator.MoveNext()) { - current.Destroy(DestroyMode.Vanish); - break; + Thing current = enumerator.Current; + if (current.def.passability == Traversability.Impassable) + { + current.Destroy(DestroyMode.Vanish); + break; + } } } + finally + { + ((IDisposable)(object)enumerator).Dispose(); + } } } } diff --git a/Assembly-CSharp/RimWorld/RoadDefGenStep_DryWithFallback.cs b/Assembly-CSharp/RimWorld/RoadDefGenStep_DryWithFallback.cs index 158ac4497..3d534cf29 100644 --- a/Assembly-CSharp/RimWorld/RoadDefGenStep_DryWithFallback.cs +++ b/Assembly-CSharp/RimWorld/RoadDefGenStep_DryWithFallback.cs @@ -1,4 +1,3 @@ -using System; using Verse; namespace RimWorld @@ -19,10 +18,9 @@ public static void PlaceWorker(Map map, IntVec3 position, TerrainDef fallback) map.terrainGrid.SetTerrain(position, map.terrainGrid.TerrainAt(position).driesTo); } TerrainDef terrainDef = map.terrainGrid.TerrainAt(position); - if (terrainDef.passability == Traversability.Impassable || terrainDef == TerrainDefOf.WaterDeep || terrainDef == TerrainDefOf.WaterMovingShallow || terrainDef == TerrainDefOf.WaterMovingDeep) - { - map.terrainGrid.SetTerrain(position, fallback); - } + if (terrainDef.passability != Traversability.Impassable && terrainDef != TerrainDefOf.WaterDeep && terrainDef != TerrainDefOf.WaterMovingShallow && terrainDef != TerrainDefOf.WaterMovingDeep) + return; + map.terrainGrid.SetTerrain(position, fallback); } } } diff --git a/Assembly-CSharp/RimWorld/RoadDefGenStep_Place.cs b/Assembly-CSharp/RimWorld/RoadDefGenStep_Place.cs index 701b55337..5297194ca 100644 --- a/Assembly-CSharp/RimWorld/RoadDefGenStep_Place.cs +++ b/Assembly-CSharp/RimWorld/RoadDefGenStep_Place.cs @@ -1,4 +1,3 @@ -using System; using Verse; namespace RimWorld @@ -37,9 +36,7 @@ public override void Place(Map map, IntVec3 position, TerrainDef rockDef) else if (this.place is ThingDef) { if (this.proximitySpacing > 0 && GenClosest.ClosestThing_Global(position, map.listerThings.ThingsOfDef(this.place as ThingDef), (float)this.proximitySpacing, null) != null) - { return; - } while (position.GetThingList(map).Count > 0) { position.GetThingList(map)[0].Destroy(DestroyMode.Vanish); diff --git a/Assembly-CSharp/RimWorld/RoadDefOf.cs b/Assembly-CSharp/RimWorld/RoadDefOf.cs index 2d76a3fda..688687459 100644 --- a/Assembly-CSharp/RimWorld/RoadDefOf.cs +++ b/Assembly-CSharp/RimWorld/RoadDefOf.cs @@ -1,5 +1,3 @@ -using System; - namespace RimWorld { [DefOf] diff --git a/Assembly-CSharp/RimWorld/RoadPathingDef.cs b/Assembly-CSharp/RimWorld/RoadPathingDef.cs index e39b46f80..4f91efd2c 100644 --- a/Assembly-CSharp/RimWorld/RoadPathingDef.cs +++ b/Assembly-CSharp/RimWorld/RoadPathingDef.cs @@ -1,4 +1,3 @@ -using System; using Verse; namespace RimWorld diff --git a/Assembly-CSharp/RimWorld/RoadPathingDefOf.cs b/Assembly-CSharp/RimWorld/RoadPathingDefOf.cs index 6e2fe6311..69f3b1381 100644 --- a/Assembly-CSharp/RimWorld/RoadPathingDefOf.cs +++ b/Assembly-CSharp/RimWorld/RoadPathingDefOf.cs @@ -1,5 +1,3 @@ -using System; - namespace RimWorld { [DefOf] diff --git a/Assembly-CSharp/RimWorld/RoadWorldLayerDef.cs b/Assembly-CSharp/RimWorld/RoadWorldLayerDef.cs index e0edaf2b2..7e75c0325 100644 --- a/Assembly-CSharp/RimWorld/RoadWorldLayerDef.cs +++ b/Assembly-CSharp/RimWorld/RoadWorldLayerDef.cs @@ -1,4 +1,3 @@ -using System; using UnityEngine; using Verse; diff --git a/Assembly-CSharp/RimWorld/RoofDefOf.cs b/Assembly-CSharp/RimWorld/RoofDefOf.cs index 8adb8e279..2aefe95f4 100644 --- a/Assembly-CSharp/RimWorld/RoofDefOf.cs +++ b/Assembly-CSharp/RimWorld/RoofDefOf.cs @@ -1,4 +1,3 @@ -using System; using Verse; namespace RimWorld diff --git a/Assembly-CSharp/RimWorld/RoomOutline.cs b/Assembly-CSharp/RimWorld/RoomOutline.cs index d8f6c9741..c2019dda4 100644 --- a/Assembly-CSharp/RimWorld/RoomOutline.cs +++ b/Assembly-CSharp/RimWorld/RoomOutline.cs @@ -1,4 +1,3 @@ -using System; using Verse; namespace RimWorld @@ -11,11 +10,11 @@ public int CellsCountIgnoringWalls { get { - if (this.rect.Width <= 2 || this.rect.Height <= 2) + if (this.rect.Width > 2 && this.rect.Height > 2) { - return 0; + return (this.rect.Width - 2) * (this.rect.Height - 2); } - return (this.rect.Width - 2) * (this.rect.Height - 2); + return 0; } } diff --git a/Assembly-CSharp/RimWorld/RoomOutlinesGenerator.cs b/Assembly-CSharp/RimWorld/RoomOutlinesGenerator.cs index 3ab865be5..19e50c41e 100644 --- a/Assembly-CSharp/RimWorld/RoomOutlinesGenerator.cs +++ b/Assembly-CSharp/RimWorld/RoomOutlinesGenerator.cs @@ -26,13 +26,11 @@ public static List GenerateRoomOutlines(CellRect initialRect, Map m } if (num2 >= minTotalRoomsNonWallCellsCount) { - break; + return list; } num++; if (num > 15) - { - return list; - } + break; } return list; } @@ -41,35 +39,30 @@ public static List GenerateRoomOutlines(CellRect initialRect, Map m { List list = new List(); list.Add(new RoomOutline(initialRect)); - for (int i = 0; i < divisionsCount; i++) + int num = 0; + RoomOutline roomOutline = default(RoomOutline); + while (num < divisionsCount && (from x in list + where x.CellsCountIgnoringWalls >= 32 + select x).TryRandomElementByWeight((Func)((RoomOutline x) => (float)Mathf.Max(x.rect.Width, x.rect.Height)), out roomOutline)) { - RoomOutline roomOutline; - if (!(from x in list - where x.CellsCountIgnoringWalls >= 32 - select x).TryRandomElementByWeight((RoomOutline x) => (float)Mathf.Max(x.rect.Width, x.rect.Height), out roomOutline)) - { - break; - } bool flag = roomOutline.rect.Height > roomOutline.rect.Width; - if (!flag || roomOutline.rect.Height > 6) + if ((!flag || roomOutline.rect.Height > 6) && (flag || roomOutline.rect.Width > 6)) { - if (flag || roomOutline.rect.Width > 6) - { - RoomOutlinesGenerator.Split(roomOutline, list, flag); - } + RoomOutlinesGenerator.Split(roomOutline, list, flag); } + num++; } - while (list.Any((RoomOutline x) => x.CellsCountIgnoringWalls > maxRoomCells)) + while (list.Any((Predicate)((RoomOutline x) => x.CellsCountIgnoringWalls > maxRoomCells))) { RoomOutline roomOutline2 = (from x in list where x.CellsCountIgnoringWalls > maxRoomCells - select x).RandomElement(); + select x).RandomElement(); bool horizontalWall = roomOutline2.rect.Height > roomOutline2.rect.Width; RoomOutlinesGenerator.Split(roomOutline2, list, horizontalWall); } while (list.Count > finalRoomsCount) { - list.Remove(list.RandomElement()); + list.Remove(list.RandomElement()); } return list; } @@ -79,13 +72,15 @@ private static void Split(RoomOutline room, List allRooms, bool hor allRooms.Remove(room); if (horizontalWall) { - int z = room.rect.CenterCell.z; + IntVec3 centerCell = room.rect.CenterCell; + int z = centerCell.z; allRooms.Add(new RoomOutline(new CellRect(room.rect.minX, room.rect.minZ, room.rect.Width, z - room.rect.minZ + 1))); allRooms.Add(new RoomOutline(new CellRect(room.rect.minX, z, room.rect.Width, room.rect.maxZ - z + 1))); } else { - int x = room.rect.CenterCell.x; + IntVec3 centerCell2 = room.rect.CenterCell; + int x = centerCell2.x; allRooms.Add(new RoomOutline(new CellRect(room.rect.minX, room.rect.minZ, x - room.rect.minX + 1, room.rect.Height))); allRooms.Add(new RoomOutline(new CellRect(x, room.rect.minZ, room.rect.maxX - x + 1, room.rect.Height))); } diff --git a/Assembly-CSharp/RimWorld/RoomRoleDefOf.cs b/Assembly-CSharp/RimWorld/RoomRoleDefOf.cs index a82786db1..659cb13ac 100644 --- a/Assembly-CSharp/RimWorld/RoomRoleDefOf.cs +++ b/Assembly-CSharp/RimWorld/RoomRoleDefOf.cs @@ -1,4 +1,3 @@ -using System; using Verse; namespace RimWorld diff --git a/Assembly-CSharp/RimWorld/RoomRoleWorker_Barn.cs b/Assembly-CSharp/RimWorld/RoomRoleWorker_Barn.cs index 1c9413be2..7ececf008 100644 --- a/Assembly-CSharp/RimWorld/RoomRoleWorker_Barn.cs +++ b/Assembly-CSharp/RimWorld/RoomRoleWorker_Barn.cs @@ -1,4 +1,3 @@ -using System; using System.Collections.Generic; using Verse; @@ -19,7 +18,7 @@ public override float GetScore(Room room) num++; } } - return (float)num * 7.6f; + return (float)((float)num * 7.5999999046325684); } } } diff --git a/Assembly-CSharp/RimWorld/RoomRoleWorker_Barracks.cs b/Assembly-CSharp/RimWorld/RoomRoleWorker_Barracks.cs index efd2ad7aa..643d3e496 100644 --- a/Assembly-CSharp/RimWorld/RoomRoleWorker_Barracks.cs +++ b/Assembly-CSharp/RimWorld/RoomRoleWorker_Barracks.cs @@ -1,4 +1,3 @@ -using System; using System.Collections.Generic; using Verse; @@ -32,7 +31,7 @@ public override float GetScore(Room room) { return 0f; } - return (float)num2 * 100100f; + return (float)((float)num2 * 100100.0); } } } diff --git a/Assembly-CSharp/RimWorld/RoomRoleWorker_Bedroom.cs b/Assembly-CSharp/RimWorld/RoomRoleWorker_Bedroom.cs index 2b017c2ad..255464abd 100644 --- a/Assembly-CSharp/RimWorld/RoomRoleWorker_Bedroom.cs +++ b/Assembly-CSharp/RimWorld/RoomRoleWorker_Bedroom.cs @@ -1,4 +1,3 @@ -using System; using System.Collections.Generic; using Verse; diff --git a/Assembly-CSharp/RimWorld/RoomRoleWorker_DiningRoom.cs b/Assembly-CSharp/RimWorld/RoomRoleWorker_DiningRoom.cs index 36904e130..7e31d127f 100644 --- a/Assembly-CSharp/RimWorld/RoomRoleWorker_DiningRoom.cs +++ b/Assembly-CSharp/RimWorld/RoomRoleWorker_DiningRoom.cs @@ -1,4 +1,3 @@ -using System; using System.Collections.Generic; using Verse; @@ -18,7 +17,7 @@ public override float GetScore(Room room) num++; } } - return (float)num * 8f; + return (float)((float)num * 8.0); } } } diff --git a/Assembly-CSharp/RimWorld/RoomRoleWorker_Hospital.cs b/Assembly-CSharp/RimWorld/RoomRoleWorker_Hospital.cs index bce3a06bc..449aa3952 100644 --- a/Assembly-CSharp/RimWorld/RoomRoleWorker_Hospital.cs +++ b/Assembly-CSharp/RimWorld/RoomRoleWorker_Hospital.cs @@ -1,4 +1,3 @@ -using System; using System.Collections.Generic; using Verse; @@ -26,7 +25,7 @@ public override float GetScore(Room room) } } } - return (float)num * 100000f; + return (float)((float)num * 100000.0); } } } diff --git a/Assembly-CSharp/RimWorld/RoomRoleWorker_Kitchen.cs b/Assembly-CSharp/RimWorld/RoomRoleWorker_Kitchen.cs index 53c89d812..04fa2ac99 100644 --- a/Assembly-CSharp/RimWorld/RoomRoleWorker_Kitchen.cs +++ b/Assembly-CSharp/RimWorld/RoomRoleWorker_Kitchen.cs @@ -1,4 +1,3 @@ -using System; using System.Collections.Generic; using Verse; @@ -22,16 +21,16 @@ public override float GetScore(Room room) { ThingDef thingDef = recipeDef.products[k].thingDef; if (thingDef.IsNutritionGivingIngestible && thingDef.ingestible.HumanEdible) - { - num++; - goto IL_C7; - } + goto IL_0088; } + continue; + IL_0088: + num++; + break; } } - IL_C7:; } - return (float)num * 14f; + return (float)((float)num * 14.0); } } } diff --git a/Assembly-CSharp/RimWorld/RoomRoleWorker_Laboratory.cs b/Assembly-CSharp/RimWorld/RoomRoleWorker_Laboratory.cs index 0290c462a..908d8a612 100644 --- a/Assembly-CSharp/RimWorld/RoomRoleWorker_Laboratory.cs +++ b/Assembly-CSharp/RimWorld/RoomRoleWorker_Laboratory.cs @@ -1,4 +1,3 @@ -using System; using System.Collections.Generic; using Verse; @@ -18,7 +17,7 @@ public override float GetScore(Room room) num++; } } - return 30f * (float)num; + return (float)(30.0 * (float)num); } } } diff --git a/Assembly-CSharp/RimWorld/RoomRoleWorker_None.cs b/Assembly-CSharp/RimWorld/RoomRoleWorker_None.cs index 87e4f59a4..a394fc11e 100644 --- a/Assembly-CSharp/RimWorld/RoomRoleWorker_None.cs +++ b/Assembly-CSharp/RimWorld/RoomRoleWorker_None.cs @@ -1,4 +1,3 @@ -using System; using Verse; namespace RimWorld diff --git a/Assembly-CSharp/RimWorld/RoomRoleWorker_PrisonBarracks.cs b/Assembly-CSharp/RimWorld/RoomRoleWorker_PrisonBarracks.cs index 413dbfca6..550f2049c 100644 --- a/Assembly-CSharp/RimWorld/RoomRoleWorker_PrisonBarracks.cs +++ b/Assembly-CSharp/RimWorld/RoomRoleWorker_PrisonBarracks.cs @@ -1,4 +1,3 @@ -using System; using System.Collections.Generic; using Verse; @@ -35,7 +34,7 @@ public override float GetScore(Room room) { return 0f; } - return (float)num2 * 100100f + (float)num * 50001f; + return (float)((float)num2 * 100100.0 + (float)num * 50001.0); } } } diff --git a/Assembly-CSharp/RimWorld/RoomRoleWorker_PrisonCell.cs b/Assembly-CSharp/RimWorld/RoomRoleWorker_PrisonCell.cs index e1561bba5..907aa52b0 100644 --- a/Assembly-CSharp/RimWorld/RoomRoleWorker_PrisonCell.cs +++ b/Assembly-CSharp/RimWorld/RoomRoleWorker_PrisonCell.cs @@ -1,4 +1,3 @@ -using System; using System.Collections.Generic; using Verse; diff --git a/Assembly-CSharp/RimWorld/RoomRoleWorker_RecRoom.cs b/Assembly-CSharp/RimWorld/RoomRoleWorker_RecRoom.cs index 359b8c13a..002590c96 100644 --- a/Assembly-CSharp/RimWorld/RoomRoleWorker_RecRoom.cs +++ b/Assembly-CSharp/RimWorld/RoomRoleWorker_RecRoom.cs @@ -1,4 +1,3 @@ -using System; using System.Collections.Generic; using Verse; @@ -16,17 +15,20 @@ public override float GetScore(Room room) if (thing.def.category == ThingCategory.Building) { List allDefsListForReading = DefDatabase.AllDefsListForReading; - for (int j = 0; j < allDefsListForReading.Count; j++) + int num2 = 0; + while (num2 < allDefsListForReading.Count) { - if (allDefsListForReading[j].thingDefs != null && allDefsListForReading[j].thingDefs.Contains(thing.def)) + if (allDefsListForReading[num2].thingDefs == null || !allDefsListForReading[num2].thingDefs.Contains(thing.def)) { - num++; - break; + num2++; + continue; } + num++; + break; } } } - return (float)num * 5f; + return (float)((float)num * 5.0); } } } diff --git a/Assembly-CSharp/RimWorld/RoomRoleWorker_Room.cs b/Assembly-CSharp/RimWorld/RoomRoleWorker_Room.cs index 1b0e35d7b..940452017 100644 --- a/Assembly-CSharp/RimWorld/RoomRoleWorker_Room.cs +++ b/Assembly-CSharp/RimWorld/RoomRoleWorker_Room.cs @@ -1,4 +1,3 @@ -using System; using Verse; namespace RimWorld diff --git a/Assembly-CSharp/RimWorld/RoomRoleWorker_Tomb.cs b/Assembly-CSharp/RimWorld/RoomRoleWorker_Tomb.cs index 1dfa0f8eb..ce4503c56 100644 --- a/Assembly-CSharp/RimWorld/RoomRoleWorker_Tomb.cs +++ b/Assembly-CSharp/RimWorld/RoomRoleWorker_Tomb.cs @@ -1,4 +1,3 @@ -using System; using System.Collections.Generic; using Verse; @@ -17,7 +16,7 @@ public override float GetScore(Room room) num++; } } - return 50f * (float)num; + return (float)(50.0 * (float)num); } } } diff --git a/Assembly-CSharp/RimWorld/RoomRoleWorker_Workshop.cs b/Assembly-CSharp/RimWorld/RoomRoleWorker_Workshop.cs index 596e6f857..2b141b22f 100644 --- a/Assembly-CSharp/RimWorld/RoomRoleWorker_Workshop.cs +++ b/Assembly-CSharp/RimWorld/RoomRoleWorker_Workshop.cs @@ -1,4 +1,3 @@ -using System; using System.Collections.Generic; using Verse; @@ -17,7 +16,7 @@ public override float GetScore(Room room) num++; } } - return 13.5f * (float)num; + return (float)(13.5 * (float)num); } } } diff --git a/Assembly-CSharp/RimWorld/RoomStatDefOf.cs b/Assembly-CSharp/RimWorld/RoomStatDefOf.cs index b2a742513..35c7af8d0 100644 --- a/Assembly-CSharp/RimWorld/RoomStatDefOf.cs +++ b/Assembly-CSharp/RimWorld/RoomStatDefOf.cs @@ -1,4 +1,3 @@ -using System; using Verse; namespace RimWorld diff --git a/Assembly-CSharp/RimWorld/RoomStatWorker_Beauty.cs b/Assembly-CSharp/RimWorld/RoomStatWorker_Beauty.cs index 70d88425b..119716539 100644 --- a/Assembly-CSharp/RimWorld/RoomStatWorker_Beauty.cs +++ b/Assembly-CSharp/RimWorld/RoomStatWorker_Beauty.cs @@ -1,4 +1,3 @@ -using System; using System.Collections.Generic; using Verse; @@ -31,9 +30,9 @@ public override float GetScore(Room room) float num = 0f; int num2 = 0; RoomStatWorker_Beauty.countedThings.Clear(); - foreach (IntVec3 current in room.Cells) + foreach (IntVec3 cell in room.Cells) { - num += BeautyUtility.CellBeauty(current, room.Map, RoomStatWorker_Beauty.countedThings); + num += BeautyUtility.CellBeauty(cell, room.Map, RoomStatWorker_Beauty.countedThings); num2++; } RoomStatWorker_Beauty.countedAdjCells.Clear(); diff --git a/Assembly-CSharp/RimWorld/RoomStatWorker_Cleanliness.cs b/Assembly-CSharp/RimWorld/RoomStatWorker_Cleanliness.cs index 0d830a1d8..bc125636b 100644 --- a/Assembly-CSharp/RimWorld/RoomStatWorker_Cleanliness.cs +++ b/Assembly-CSharp/RimWorld/RoomStatWorker_Cleanliness.cs @@ -1,4 +1,3 @@ -using System; using System.Collections.Generic; using Verse; @@ -18,9 +17,9 @@ public override float GetScore(Room room) num += (float)thing.stackCount * thing.GetStatValue(StatDefOf.Cleanliness, true); } } - foreach (IntVec3 current in room.Cells) + foreach (IntVec3 cell in room.Cells) { - num += current.GetTerrain(room.Map).GetStatValueAbstract(StatDefOf.Cleanliness, null); + num += cell.GetTerrain(room.Map).GetStatValueAbstract(StatDefOf.Cleanliness, null); } return num / (float)room.CellCount; } diff --git a/Assembly-CSharp/RimWorld/RoomStatWorker_FoodPoisonChanceFactor.cs b/Assembly-CSharp/RimWorld/RoomStatWorker_FoodPoisonChanceFactor.cs index 5e9db94b6..0c539aec8 100644 --- a/Assembly-CSharp/RimWorld/RoomStatWorker_FoodPoisonChanceFactor.cs +++ b/Assembly-CSharp/RimWorld/RoomStatWorker_FoodPoisonChanceFactor.cs @@ -1,4 +1,3 @@ -using System; using UnityEngine; using Verse; @@ -9,7 +8,7 @@ public class RoomStatWorker_FoodPoisonChanceFactor : RoomStatWorker public override float GetScore(Room room) { float stat = room.GetStat(RoomStatDefOf.Cleanliness); - float value = 1f / GenMath.UnboundedValueToFactor(stat * 0.21f); + float value = (float)(1.0 / GenMath.UnboundedValueToFactor((float)(stat * 0.20999999344348907))); return Mathf.Clamp(value, 0.7f, 1.6f); } } diff --git a/Assembly-CSharp/RimWorld/RoomStatWorker_GraveVisitingJoyGainFactor.cs b/Assembly-CSharp/RimWorld/RoomStatWorker_GraveVisitingJoyGainFactor.cs index 8eb4e1a11..d87a837c8 100644 --- a/Assembly-CSharp/RimWorld/RoomStatWorker_GraveVisitingJoyGainFactor.cs +++ b/Assembly-CSharp/RimWorld/RoomStatWorker_GraveVisitingJoyGainFactor.cs @@ -1,4 +1,3 @@ -using System; using UnityEngine; using Verse; diff --git a/Assembly-CSharp/RimWorld/RoomStatWorker_Impressiveness.cs b/Assembly-CSharp/RimWorld/RoomStatWorker_Impressiveness.cs index 4db15253b..33dc3cc63 100644 --- a/Assembly-CSharp/RimWorld/RoomStatWorker_Impressiveness.cs +++ b/Assembly-CSharp/RimWorld/RoomStatWorker_Impressiveness.cs @@ -1,4 +1,3 @@ -using System; using UnityEngine; using Verse; @@ -8,32 +7,32 @@ public class RoomStatWorker_Impressiveness : RoomStatWorker { public override float GetScore(Room room) { - float factor = this.GetFactor(room.GetStat(RoomStatDefOf.Wealth) / 1500f); - float factor2 = this.GetFactor(room.GetStat(RoomStatDefOf.Beauty) / 3f); - float factor3 = this.GetFactor(room.GetStat(RoomStatDefOf.Space) / 125f); - float factor4 = this.GetFactor(1f + room.GetStat(RoomStatDefOf.Cleanliness) / 2.5f); - float a = (factor + factor2 + factor3 + factor4) / 4f; + float factor = this.GetFactor((float)(room.GetStat(RoomStatDefOf.Wealth) / 1500.0)); + float factor2 = this.GetFactor((float)(room.GetStat(RoomStatDefOf.Beauty) / 3.0)); + float factor3 = this.GetFactor((float)(room.GetStat(RoomStatDefOf.Space) / 125.0)); + float factor4 = this.GetFactor((float)(1.0 + room.GetStat(RoomStatDefOf.Cleanliness) / 2.5)); + float a = (float)((factor + factor2 + factor3 + factor4) / 4.0); float b = Mathf.Min(factor, Mathf.Min(factor2, Mathf.Min(factor3, factor4))); float num = Mathf.Lerp(a, b, 0.35f); - float num2 = factor3 * 5f; + float num2 = (float)(factor3 * 5.0); if (num > num2) { num = Mathf.Lerp(num, num2, 0.75f); } - return num * 100f; + return (float)(num * 100.0); } private float GetFactor(float baseFactor) { - if (Mathf.Abs(baseFactor) < 1f) + if (Mathf.Abs(baseFactor) < 1.0) { return baseFactor; } - if (baseFactor > 0f) + if (baseFactor > 0.0) { - return 1f + Mathf.Log(baseFactor); + return (float)(1.0 + Mathf.Log(baseFactor)); } - return -1f - Mathf.Log(-baseFactor); + return (float)(-1.0 - Mathf.Log((float)(0.0 - baseFactor))); } } } diff --git a/Assembly-CSharp/RimWorld/RoomStatWorker_InfectionChanceFactor.cs b/Assembly-CSharp/RimWorld/RoomStatWorker_InfectionChanceFactor.cs index d7707310c..184b3adc6 100644 --- a/Assembly-CSharp/RimWorld/RoomStatWorker_InfectionChanceFactor.cs +++ b/Assembly-CSharp/RimWorld/RoomStatWorker_InfectionChanceFactor.cs @@ -1,4 +1,3 @@ -using System; using UnityEngine; using Verse; @@ -9,15 +8,7 @@ public class RoomStatWorker_InfectionChanceFactor : RoomStatWorker public override float GetScore(Room room) { float stat = room.GetStat(RoomStatDefOf.Cleanliness); - float value; - if (stat >= 0f) - { - value = GenMath.LerpDouble(0f, 1f, 0.5f, 0.2f, stat); - } - else - { - value = GenMath.LerpDouble(-5f, 0f, 1f, 0.5f, stat); - } + float value = (!(stat >= 0.0)) ? GenMath.LerpDouble(-5f, 0f, 1f, 0.5f, stat) : GenMath.LerpDouble(0f, 1f, 0.5f, 0.2f, stat); return Mathf.Clamp(value, 0.2f, 1f); } } diff --git a/Assembly-CSharp/RimWorld/RoomStatWorker_ResearchSpeedFactor.cs b/Assembly-CSharp/RimWorld/RoomStatWorker_ResearchSpeedFactor.cs index d6f0cedc4..3644bf4ec 100644 --- a/Assembly-CSharp/RimWorld/RoomStatWorker_ResearchSpeedFactor.cs +++ b/Assembly-CSharp/RimWorld/RoomStatWorker_ResearchSpeedFactor.cs @@ -1,4 +1,3 @@ -using System; using Verse; namespace RimWorld diff --git a/Assembly-CSharp/RimWorld/RoomStatWorker_Space.cs b/Assembly-CSharp/RimWorld/RoomStatWorker_Space.cs index 5185e4dcb..d4370e86f 100644 --- a/Assembly-CSharp/RimWorld/RoomStatWorker_Space.cs +++ b/Assembly-CSharp/RimWorld/RoomStatWorker_Space.cs @@ -1,4 +1,3 @@ -using System; using UnityEngine; using Verse; @@ -13,15 +12,15 @@ public override float GetScore(Room room) return 350f; } float num = 0f; - foreach (IntVec3 current in room.Cells) + foreach (IntVec3 cell in room.Cells) { - if (current.Standable(room.Map)) + if (cell.Standable(room.Map)) { - num += 1.4f; + num = (float)(num + 1.3999999761581421); } - else if (current.Walkable(room.Map)) + else if (cell.Walkable(room.Map)) { - num += 0.5f; + num = (float)(num + 0.5); } } return Mathf.Min(num, 350f); diff --git a/Assembly-CSharp/RimWorld/RoomStatWorker_SurgerySuccessChanceFactor.cs b/Assembly-CSharp/RimWorld/RoomStatWorker_SurgerySuccessChanceFactor.cs index b60b28e1f..feb27f580 100644 --- a/Assembly-CSharp/RimWorld/RoomStatWorker_SurgerySuccessChanceFactor.cs +++ b/Assembly-CSharp/RimWorld/RoomStatWorker_SurgerySuccessChanceFactor.cs @@ -1,4 +1,3 @@ -using System; using UnityEngine; using Verse; diff --git a/Assembly-CSharp/RimWorld/RoomStatWorker_Wealth.cs b/Assembly-CSharp/RimWorld/RoomStatWorker_Wealth.cs index 1c59a9209..d25c8c4d3 100644 --- a/Assembly-CSharp/RimWorld/RoomStatWorker_Wealth.cs +++ b/Assembly-CSharp/RimWorld/RoomStatWorker_Wealth.cs @@ -1,4 +1,3 @@ -using System; using System.Collections.Generic; using Verse; @@ -18,9 +17,9 @@ public override float GetScore(Room room) num += (float)thing.stackCount * thing.GetInnerIfMinified().MarketValue; } } - foreach (IntVec3 current in room.Cells) + foreach (IntVec3 cell in room.Cells) { - num += current.GetTerrain(room.Map).GetStatValueAbstract(StatDefOf.MarketValue, null); + num += cell.GetTerrain(room.Map).GetStatValueAbstract(StatDefOf.MarketValue, null); } return num; } diff --git a/Assembly-CSharp/RimWorld/RotStage.cs b/Assembly-CSharp/RimWorld/RotStage.cs index e40dbf570..fa7faa6c0 100644 --- a/Assembly-CSharp/RimWorld/RotStage.cs +++ b/Assembly-CSharp/RimWorld/RotStage.cs @@ -1,11 +1,9 @@ -using System; - namespace RimWorld { public enum RotStage : byte { - Fresh, - Rotting, - Dessicated + Fresh = 0, + Rotting = 1, + Dessicated = 2 } } diff --git a/Assembly-CSharp/RimWorld/RottableUtility.cs b/Assembly-CSharp/RimWorld/RottableUtility.cs index c56f1b72c..92803ffde 100644 --- a/Assembly-CSharp/RimWorld/RottableUtility.cs +++ b/Assembly-CSharp/RimWorld/RottableUtility.cs @@ -1,4 +1,3 @@ -using System; using Verse; namespace RimWorld diff --git a/Assembly-CSharp/RimWorld/RuleDef.cs b/Assembly-CSharp/RimWorld/RuleDef.cs index b1a90ace7..ddb68f455 100644 --- a/Assembly-CSharp/RimWorld/RuleDef.cs +++ b/Assembly-CSharp/RimWorld/RuleDef.cs @@ -1,5 +1,4 @@ using RimWorld.BaseGen; -using System; using System.Collections.Generic; using Verse; diff --git a/Assembly-CSharp/RimWorld/RulePackDefOf.cs b/Assembly-CSharp/RimWorld/RulePackDefOf.cs index 509a11c2f..ed0e102d0 100644 --- a/Assembly-CSharp/RimWorld/RulePackDefOf.cs +++ b/Assembly-CSharp/RimWorld/RulePackDefOf.cs @@ -1,4 +1,3 @@ -using System; using Verse; namespace RimWorld diff --git a/Assembly-CSharp/RimWorld/ScenPart.cs b/Assembly-CSharp/RimWorld/ScenPart.cs index 70f608415..f7bc38f88 100644 --- a/Assembly-CSharp/RimWorld/ScenPart.cs +++ b/Assembly-CSharp/RimWorld/ScenPart.cs @@ -1,6 +1,4 @@ -using System; using System.Collections.Generic; -using System.Diagnostics; using Verse; namespace RimWorld @@ -56,13 +54,9 @@ public virtual string Summary(Scenario scen) return this.def.description; } - [DebuggerHidden] public virtual IEnumerable GetSummaryListEntries(string tag) { - ScenPart.c__Iterator111 c__Iterator = new ScenPart.c__Iterator111(); - ScenPart.c__Iterator111 expr_07 = c__Iterator; - expr_07.$PC = -2; - return expr_07; + yield break; } public virtual void Randomize() @@ -79,13 +73,9 @@ public virtual bool CanCoexistWith(ScenPart other) return true; } - [DebuggerHidden] public virtual IEnumerable GetConfigPages() { - ScenPart.c__Iterator112 c__Iterator = new ScenPart.c__Iterator112(); - ScenPart.c__Iterator112 expr_07 = c__Iterator; - expr_07.$PC = -2; - return expr_07; + yield break; } public virtual bool AllowPlayerStartingPawn(Pawn pawn) @@ -113,13 +103,9 @@ public virtual void PreMapGenerate() { } - [DebuggerHidden] public virtual IEnumerable PlayerStartingThings() { - ScenPart.c__Iterator113 c__Iterator = new ScenPart.c__Iterator113(); - ScenPart.c__Iterator113 expr_07 = c__Iterator; - expr_07.$PC = -2; - return expr_07; + yield break; } public virtual void GenerateIntoMap(Map map) @@ -138,14 +124,12 @@ public virtual void Tick() { } - [DebuggerHidden] public virtual IEnumerable ConfigErrors() { - ScenPart.c__Iterator114 c__Iterator = new ScenPart.c__Iterator114(); - c__Iterator.<>f__this = this; - ScenPart.c__Iterator114 expr_0E = c__Iterator; - expr_0E.$PC = -2; - return expr_0E; + if (this.def == null) + { + yield return base.GetType().ToString() + " has null def."; + } } } } diff --git a/Assembly-CSharp/RimWorld/ScenPartCategory.cs b/Assembly-CSharp/RimWorld/ScenPartCategory.cs index db2e4cc6c..6dd9cb221 100644 --- a/Assembly-CSharp/RimWorld/ScenPartCategory.cs +++ b/Assembly-CSharp/RimWorld/ScenPartCategory.cs @@ -1,18 +1,16 @@ -using System; - namespace RimWorld { public enum ScenPartCategory { - Undefined, - Fixed, - StartingImportant, - PlayerPawnFilter, - PlayerPawnModifier, - GameCondition, - Rule, - StartingItem, - WorldThing, - Misc + Undefined = 0, + Fixed = 1, + StartingImportant = 2, + PlayerPawnFilter = 3, + PlayerPawnModifier = 4, + GameCondition = 5, + Rule = 6, + StartingItem = 7, + WorldThing = 8, + Misc = 9 } } diff --git a/Assembly-CSharp/RimWorld/ScenPartDef.cs b/Assembly-CSharp/RimWorld/ScenPartDef.cs index c1a419fb9..68c7e2587 100644 --- a/Assembly-CSharp/RimWorld/ScenPartDef.cs +++ b/Assembly-CSharp/RimWorld/ScenPartDef.cs @@ -1,6 +1,5 @@ using System; using System.Collections.Generic; -using System.Diagnostics; using Verse; namespace RimWorld @@ -33,14 +32,16 @@ public bool PlayerAddRemovable } } - [DebuggerHidden] public override IEnumerable ConfigErrors() { - ScenPartDef.c__Iterator93 c__Iterator = new ScenPartDef.c__Iterator93(); - c__Iterator.<>f__this = this; - ScenPartDef.c__Iterator93 expr_0E = c__Iterator; - expr_0E.$PC = -2; - return expr_0E; + foreach (string item in base.ConfigErrors()) + { + yield return item; + } + if (this.scenPartClass == null) + { + yield return "scenPartClass is null"; + } } } } diff --git a/Assembly-CSharp/RimWorld/ScenPartDefOf.cs b/Assembly-CSharp/RimWorld/ScenPartDefOf.cs index 736f9acd3..f2ba9a588 100644 --- a/Assembly-CSharp/RimWorld/ScenPartDefOf.cs +++ b/Assembly-CSharp/RimWorld/ScenPartDefOf.cs @@ -1,5 +1,3 @@ -using System; - namespace RimWorld { [DefOf] diff --git a/Assembly-CSharp/RimWorld/ScenPart_ConfigPage.cs b/Assembly-CSharp/RimWorld/ScenPart_ConfigPage.cs index cf10d7121..ad819b9b0 100644 --- a/Assembly-CSharp/RimWorld/ScenPart_ConfigPage.cs +++ b/Assembly-CSharp/RimWorld/ScenPart_ConfigPage.cs @@ -1,20 +1,14 @@ using System; using System.Collections.Generic; -using System.Diagnostics; using Verse; namespace RimWorld { public class ScenPart_ConfigPage : ScenPart { - [DebuggerHidden] public override IEnumerable GetConfigPages() { - ScenPart_ConfigPage.c__Iterator120 c__Iterator = new ScenPart_ConfigPage.c__Iterator120(); - c__Iterator.<>f__this = this; - ScenPart_ConfigPage.c__Iterator120 expr_0E = c__Iterator; - expr_0E.$PC = -2; - return expr_0E; + yield return (Page)Activator.CreateInstance(base.def.pageClass); } public override void DoEditInterface(Listing_ScenEdit listing) diff --git a/Assembly-CSharp/RimWorld/ScenPart_ConfigPage_ConfigureStartingPawns.cs b/Assembly-CSharp/RimWorld/ScenPart_ConfigPage_ConfigureStartingPawns.cs index 612517483..88434fb41 100644 --- a/Assembly-CSharp/RimWorld/ScenPart_ConfigPage_ConfigureStartingPawns.cs +++ b/Assembly-CSharp/RimWorld/ScenPart_ConfigPage_ConfigureStartingPawns.cs @@ -1,4 +1,3 @@ -using System; using UnityEngine; using Verse; @@ -27,10 +26,7 @@ public override void ExposeData() public override string Summary(Scenario scen) { - return "ScenPart_StartWithPawns".Translate(new object[] - { - this.pawnCount - }); + return "ScenPart_StartWithPawns".Translate(this.pawnCount); } public override void Randomize() @@ -49,14 +45,11 @@ public override void PostWorldGenerate() Find.GameInitData.startingPawns.Add(StartingPawnUtility.NewGeneratedStartingPawn()); } num++; - if (num > 20) - { - break; - } - if (StartingPawnUtility.WorkTypeRequirementsSatisfied()) + if (num <= 20 && !StartingPawnUtility.WorkTypeRequirementsSatisfied()) { - return; + continue; } + break; } } } diff --git a/Assembly-CSharp/RimWorld/ScenPart_CreateIncident.cs b/Assembly-CSharp/RimWorld/ScenPart_CreateIncident.cs index b0f08681f..1c19f08d0 100644 --- a/Assembly-CSharp/RimWorld/ScenPart_CreateIncident.cs +++ b/Assembly-CSharp/RimWorld/ScenPart_CreateIncident.cs @@ -1,6 +1,5 @@ using System; using System.Collections.Generic; -using System.Diagnostics; using System.Linq; using UnityEngine; using Verse; @@ -35,7 +34,7 @@ private float IntervalTicks { get { - return 60000f * this.intervalDays; + return (float)(60000.0 * this.intervalDays); } } @@ -50,10 +49,10 @@ public override void ExposeData() public override void DoEditInterface(Listing_ScenEdit listing) { - Rect scenPartRect = listing.GetScenPartRect(this, ScenPart.RowHeight * 3f); - Rect rect = new Rect(scenPartRect.x, scenPartRect.y, scenPartRect.width, scenPartRect.height / 3f); - Rect rect2 = new Rect(scenPartRect.x, scenPartRect.y + scenPartRect.height / 3f, scenPartRect.width, scenPartRect.height / 3f); - Rect rect3 = new Rect(scenPartRect.x, scenPartRect.y + scenPartRect.height * 2f / 3f, scenPartRect.width, scenPartRect.height / 3f); + Rect scenPartRect = listing.GetScenPartRect(this, (float)(ScenPart.RowHeight * 3.0)); + Rect rect = new Rect(scenPartRect.x, scenPartRect.y, scenPartRect.width, (float)(scenPartRect.height / 3.0)); + Rect rect2 = new Rect(scenPartRect.x, (float)(scenPartRect.y + scenPartRect.height / 3.0), scenPartRect.width, (float)(scenPartRect.height / 3.0)); + Rect rect3 = new Rect(scenPartRect.x, (float)(scenPartRect.y + scenPartRect.height * 2.0 / 3.0), scenPartRect.width, (float)(scenPartRect.height / 3.0)); base.DoIncidentEditInterface(rect); Widgets.TextFieldNumericLabeled(rect2, "intervalDays".Translate(), ref this.intervalDays, ref this.intervalDaysBuffer, 0f, 1E+09f); Widgets.CheckboxLabeled(rect3, "repeat".Translate(), ref this.repeat, false); @@ -62,21 +61,19 @@ public override void DoEditInterface(Listing_ScenEdit listing) public override void Randomize() { base.Randomize(); - this.intervalDays = 15f * Rand.Gaussian(0f, 1f) + 30f; - if (this.intervalDays < 0f) + this.intervalDays = (float)(15.0 * Rand.Gaussian(0f, 1f) + 30.0); + if (this.intervalDays < 0.0) { this.intervalDays = 0f; } this.repeat = (Rand.Range(0, 100) < 50); } - [DebuggerHidden] protected override IEnumerable RandomizableIncidents() { - ScenPart_CreateIncident.c__Iterator11A c__Iterator11A = new ScenPart_CreateIncident.c__Iterator11A(); - ScenPart_CreateIncident.c__Iterator11A expr_07 = c__Iterator11A; - expr_07.$PC = -2; - return expr_07; + yield return IncidentDefOf.Eclipse; + yield return IncidentDefOf.ToxicFallout; + yield return IncidentDefOf.SolarFlare; } public override void PostGameStart() @@ -88,37 +85,30 @@ public override void PostGameStart() public override void Tick() { base.Tick(); - if (Find.AnyPlayerHomeMap == null) + if (Find.AnyPlayerHomeMap != null && !this.isFinished) { - return; - } - if (this.isFinished) - { - return; - } - if (this.incident == null) - { - Log.Error("Trying to tick ScenPart_CreateIncident but the incident is null"); - this.isFinished = true; - return; - } - if ((float)Find.TickManager.TicksGame >= this.occurTick) - { - IncidentParms parms = StorytellerUtility.DefaultParmsNow(Find.Storyteller.def, this.incident.category, (from x in Find.Maps - where x.IsPlayerHome - select x).RandomElement()); - if (!this.incident.Worker.TryExecute(parms)) + if (base.incident == null) { + Log.Error("Trying to tick ScenPart_CreateIncident but the incident is null"); this.isFinished = true; - return; - } - if (this.repeat && this.intervalDays > 0f) - { - this.occurTick += this.IntervalTicks; } - else + else if ((float)Find.TickManager.TicksGame >= this.occurTick) { - this.isFinished = true; + IncidentParms parms = StorytellerUtility.DefaultParmsNow(Find.Storyteller.def, base.incident.category, (from x in Find.Maps + where x.IsPlayerHome + select x).RandomElement()); + if (!base.incident.Worker.TryExecute(parms)) + { + this.isFinished = true; + } + else if (this.repeat && this.intervalDays > 0.0) + { + this.occurTick += this.IntervalTicks; + } + else + { + this.isFinished = true; + } } } } diff --git a/Assembly-CSharp/RimWorld/ScenPart_DisableIncident.cs b/Assembly-CSharp/RimWorld/ScenPart_DisableIncident.cs index 9c726eee0..451ca9798 100644 --- a/Assembly-CSharp/RimWorld/ScenPart_DisableIncident.cs +++ b/Assembly-CSharp/RimWorld/ScenPart_DisableIncident.cs @@ -1,6 +1,4 @@ -using System; using System.Collections.Generic; -using System.Diagnostics; namespace RimWorld { @@ -14,13 +12,14 @@ protected override string IncidentTag } } - [DebuggerHidden] protected override IEnumerable RandomizableIncidents() { - ScenPart_DisableIncident.c__Iterator11B c__Iterator11B = new ScenPart_DisableIncident.c__Iterator11B(); - ScenPart_DisableIncident.c__Iterator11B expr_07 = c__Iterator11B; - expr_07.$PC = -2; - return expr_07; + yield return IncidentDefOf.TraderCaravanArrival; + yield return IncidentDefOf.OrbitalTraderArrival; + yield return IncidentDefOf.WandererJoin; + yield return IncidentDefOf.Eclipse; + yield return IncidentDefOf.ToxicFallout; + yield return IncidentDefOf.SolarFlare; } } } diff --git a/Assembly-CSharp/RimWorld/ScenPart_DisallowBuilding.cs b/Assembly-CSharp/RimWorld/ScenPart_DisallowBuilding.cs index b3322bb89..cf7fb89da 100644 --- a/Assembly-CSharp/RimWorld/ScenPart_DisallowBuilding.cs +++ b/Assembly-CSharp/RimWorld/ScenPart_DisallowBuilding.cs @@ -1,6 +1,5 @@ using System; using System.Collections.Generic; -using System.Diagnostics; using System.Linq; using UnityEngine; using Verse; @@ -23,16 +22,12 @@ public override string Summary(Scenario scen) return ScenSummaryList.SummaryWithList(scen, "DisallowBuilding", "ScenPart_DisallowBuilding".Translate()); } - [DebuggerHidden] public override IEnumerable GetSummaryListEntries(string tag) { - ScenPart_DisallowBuilding.c__Iterator117 c__Iterator = new ScenPart_DisallowBuilding.c__Iterator117(); - c__Iterator.tag = tag; - c__Iterator.<$>tag = tag; - c__Iterator.<>f__this = this; - ScenPart_DisallowBuilding.c__Iterator117 expr_1C = c__Iterator; - expr_1C.$PC = -2; - return expr_1C; + if (tag == "DisallowBuilding") + { + yield return this.building.LabelCap; + } } public override void ExposeData() @@ -43,7 +38,7 @@ public override void ExposeData() public override void Randomize() { - this.building = this.RandomizableBuildingDefs().RandomElement(); + this.building = this.RandomizableBuildingDefs().RandomElement(); } public override void DoEditInterface(Listing_ScenEdit listing) @@ -52,12 +47,12 @@ public override void DoEditInterface(Listing_ScenEdit listing) if (Widgets.ButtonText(scenPartRect, this.building.LabelCap, true, false, true)) { List list = new List(); - foreach (ThingDef current in from t in this.PossibleBuildingDefs() + foreach (ThingDef item in from t in this.PossibleBuildingDefs() orderby t.label select t) { - ThingDef localTd = current; - list.Add(new FloatMenuOption(localTd.LabelCap, delegate + ThingDef localTd = item; + list.Add(new FloatMenuOption(localTd.LabelCap, (Action)delegate { this.building = localTd; }, MenuOptionPriority.Default, null, null, 0f, null, null)); @@ -69,7 +64,11 @@ orderby t.label public override bool TryMerge(ScenPart other) { ScenPart_DisallowBuilding scenPart_DisallowBuilding = other as ScenPart_DisallowBuilding; - return scenPart_DisallowBuilding != null && scenPart_DisallowBuilding.building == this.building; + if (scenPart_DisallowBuilding != null && scenPart_DisallowBuilding.building == this.building) + { + return true; + } + return false; } protected virtual IEnumerable PossibleBuildingDefs() @@ -79,13 +78,15 @@ protected virtual IEnumerable PossibleBuildingDefs() select d; } - [DebuggerHidden] private IEnumerable RandomizableBuildingDefs() { - ScenPart_DisallowBuilding.c__Iterator118 c__Iterator = new ScenPart_DisallowBuilding.c__Iterator118(); - ScenPart_DisallowBuilding.c__Iterator118 expr_07 = c__Iterator; - expr_07.$PC = -2; - return expr_07; + yield return ThingDefOf.Wall; + yield return ThingDefOf.TurretGun; + yield return ThingDefOf.OrbitalTradeBeacon; + yield return ThingDefOf.Battery; + yield return ThingDefOf.TrapDeadfall; + yield return ThingDefOf.Cooler; + yield return ThingDefOf.Heater; } } } diff --git a/Assembly-CSharp/RimWorld/ScenPart_ForcedHediff.cs b/Assembly-CSharp/RimWorld/ScenPart_ForcedHediff.cs index fad04aa4a..46b538701 100644 --- a/Assembly-CSharp/RimWorld/ScenPart_ForcedHediff.cs +++ b/Assembly-CSharp/RimWorld/ScenPart_ForcedHediff.cs @@ -16,16 +16,16 @@ private float MaxSeverity { get { - return (this.hediff.lethalSeverity <= 0f) ? 1f : (this.hediff.lethalSeverity * 0.99f); + return (float)((!(this.hediff.lethalSeverity > 0.0)) ? 1.0 : (this.hediff.lethalSeverity * 0.99000000953674316)); } } public override void DoEditInterface(Listing_ScenEdit listing) { - Rect scenPartRect = listing.GetScenPartRect(this, ScenPart.RowHeight * 3f + 31f); + Rect scenPartRect = listing.GetScenPartRect(this, (float)(ScenPart.RowHeight * 3.0 + 31.0)); if (Widgets.ButtonText(scenPartRect.TopPartPixels(ScenPart.RowHeight), this.hediff.LabelCap, true, false, true)) { - FloatMenuUtility.MakeMenu(this.PossibleHediffs(), (HediffDef hd) => hd.LabelCap, (HediffDef hd) => delegate + FloatMenuUtility.MakeMenu(this.PossibleHediffs(), (Func)((HediffDef hd) => hd.LabelCap), (Func)((HediffDef hd) => (Action)delegate() { this.hediff = hd; if (this.severityRange.max > this.MaxSeverity) @@ -36,10 +36,10 @@ public override void DoEditInterface(Listing_ScenEdit listing) { this.severityRange.min = this.MaxSeverity; } - }); + })); } Widgets.FloatRange(new Rect(scenPartRect.x, scenPartRect.y + ScenPart.RowHeight, scenPartRect.width, 31f), listing.CurHeight.GetHashCode(), ref this.severityRange, 0f, this.MaxSeverity, "ConfigurableSeverity", ToStringStyle.FloatTwo); - base.DoPawnModifierEditInterface(scenPartRect.BottomPartPixels(ScenPart.RowHeight * 2f)); + base.DoPawnModifierEditInterface(scenPartRect.BottomPartPixels((float)(ScenPart.RowHeight * 2.0))); } private IEnumerable PossibleHediffs() @@ -58,19 +58,14 @@ public override void ExposeData() public override string Summary(Scenario scen) { - return "ScenPart_PawnsHaveHediff".Translate(new object[] - { - this.context.ToStringHuman(), - this.chance.ToStringPercent(), - this.hediff.label - }).CapitalizeFirst(); + return "ScenPart_PawnsHaveHediff".Translate(base.context.ToStringHuman(), base.chance.ToStringPercent(), this.hediff.label).CapitalizeFirst(); } public override void Randomize() { base.Randomize(); - this.hediff = this.PossibleHediffs().RandomElement(); - this.severityRange.max = Rand.Range(this.MaxSeverity * 0.2f, this.MaxSeverity * 0.95f); + this.hediff = this.PossibleHediffs().RandomElement(); + this.severityRange.max = Rand.Range((float)(this.MaxSeverity * 0.20000000298023224), (float)(this.MaxSeverity * 0.949999988079071)); this.severityRange.min = this.severityRange.max * Rand.Range(0f, 0.95f); } @@ -79,7 +74,7 @@ public override bool TryMerge(ScenPart other) ScenPart_ForcedHediff scenPart_ForcedHediff = other as ScenPart_ForcedHediff; if (scenPart_ForcedHediff != null && this.hediff == scenPart_ForcedHediff.hediff) { - this.chance = GenMath.ChanceEitherHappens(this.chance, scenPart_ForcedHediff.chance); + base.chance = GenMath.ChanceEitherHappens(base.chance, scenPart_ForcedHediff.chance); return true; } return false; @@ -87,11 +82,11 @@ public override bool TryMerge(ScenPart other) protected override void ModifyPawn(Pawn p) { - if (Rand.Value < this.chance) + if (Rand.Value < base.chance) { Hediff hediff = HediffMaker.MakeHediff(this.hediff, p, null); hediff.Severity = this.severityRange.RandomInRange; - p.health.AddHediff(hediff, null, null); + p.health.AddHediff(hediff, null, default(DamageInfo?)); } } } diff --git a/Assembly-CSharp/RimWorld/ScenPart_ForcedTrait.cs b/Assembly-CSharp/RimWorld/ScenPart_ForcedTrait.cs index 84f79ad1f..6a0fe5e21 100644 --- a/Assembly-CSharp/RimWorld/ScenPart_ForcedTrait.cs +++ b/Assembly-CSharp/RimWorld/ScenPart_ForcedTrait.cs @@ -21,23 +21,32 @@ public override void ExposeData() public override void DoEditInterface(Listing_ScenEdit listing) { - Rect scenPartRect = listing.GetScenPartRect(this, ScenPart.RowHeight * 3f); + Rect scenPartRect = listing.GetScenPartRect(this, (float)(ScenPart.RowHeight * 3.0)); if (Widgets.ButtonText(scenPartRect.TopPart(0.333f), this.trait.DataAtDegree(this.degree).label.CapitalizeFirst(), true, false, true)) { List list = new List(); - foreach (TraitDef current in from td in DefDatabase.AllDefs + foreach (TraitDef item in from td in DefDatabase.AllDefs orderby td.label select td) { - foreach (TraitDegreeData current2 in current.degreeDatas) + List.Enumerator enumerator2 = item.degreeDatas.GetEnumerator(); + try { - TraitDef localDef = current; - TraitDegreeData localDeg = current2; - list.Add(new FloatMenuOption(localDeg.label.CapitalizeFirst(), delegate + while (enumerator2.MoveNext()) { - this.trait = localDef; - this.degree = localDeg.degree; - }, MenuOptionPriority.Default, null, null, 0f, null, null)); + TraitDegreeData current2 = enumerator2.Current; + TraitDef localDef = item; + TraitDegreeData localDeg = current2; + list.Add(new FloatMenuOption(localDeg.label.CapitalizeFirst(), (Action)delegate + { + this.trait = localDef; + this.degree = localDeg.degree; + }, MenuOptionPriority.Default, null, null, 0f, null, null)); + } + } + finally + { + ((IDisposable)(object)enumerator2).Dispose(); } } Find.WindowStack.Add(new FloatMenu(list)); @@ -47,71 +56,69 @@ orderby td.label public override string Summary(Scenario scen) { - return "ScenPart_PawnsHaveTrait".Translate(new object[] - { - this.context.ToStringHuman(), - this.chance.ToStringPercent(), - this.trait.DataAtDegree(this.degree).label.CapitalizeFirst() - }).CapitalizeFirst(); + return "ScenPart_PawnsHaveTrait".Translate(base.context.ToStringHuman(), base.chance.ToStringPercent(), this.trait.DataAtDegree(this.degree).label.CapitalizeFirst()).CapitalizeFirst(); } public override void Randomize() { base.Randomize(); this.trait = DefDatabase.GetRandom(); - this.degree = this.trait.degreeDatas.RandomElement().degree; + this.degree = this.trait.degreeDatas.RandomElement().degree; } public override bool CanCoexistWith(ScenPart other) { ScenPart_ForcedTrait scenPart_ForcedTrait = other as ScenPart_ForcedTrait; - return scenPart_ForcedTrait == null || this.trait != scenPart_ForcedTrait.trait || !this.context.OverlapsWith(scenPart_ForcedTrait.context); + if (scenPart_ForcedTrait != null && this.trait == scenPart_ForcedTrait.trait && base.context.OverlapsWith(scenPart_ForcedTrait.context)) + { + return false; + } + return true; } protected override void ModifyPawn(Pawn pawn) { - if (Rand.Value > this.chance) - { - return; - } - if (pawn.story == null || pawn.story.traits == null) - { - return; - } - if (pawn.story.traits.HasTrait(this.trait) && pawn.story.traits.DegreeOfTrait(this.trait) == this.degree) + if (!(Rand.Value > base.chance) && pawn.story != null && pawn.story.traits != null && (!pawn.story.traits.HasTrait(this.trait) || pawn.story.traits.DegreeOfTrait(this.trait) != this.degree)) { - return; - } - if (pawn.story.traits.HasTrait(this.trait)) - { - pawn.story.traits.allTraits.RemoveAll((Trait tr) => tr.def == this.trait); - } - else - { - IEnumerable source = from tr in pawn.story.traits.allTraits - where !tr.ScenForced && !ScenPart_ForcedTrait.PawnHasTraitForcedByBackstory(pawn, tr.def) - select tr; - if (source.Any()) + if (pawn.story.traits.HasTrait(this.trait)) { - Trait trait = (from tr in source - where tr.def.conflictingTraits.Contains(this.trait) - select tr).FirstOrDefault(); - if (trait != null) - { - pawn.story.traits.allTraits.Remove(trait); - } - else + pawn.story.traits.allTraits.RemoveAll((Predicate)((Trait tr) => tr.def == this.trait)); + } + else + { + IEnumerable source = from tr in pawn.story.traits.allTraits + where !tr.ScenForced && !ScenPart_ForcedTrait.PawnHasTraitForcedByBackstory(pawn, tr.def) + select tr; + if (source.Any()) { - pawn.story.traits.allTraits.Remove(source.RandomElement()); + Trait trait = (from tr in source + where tr.def.conflictingTraits.Contains(this.trait) + select tr).FirstOrDefault(); + if (trait != null) + { + pawn.story.traits.allTraits.Remove(trait); + } + else + { + pawn.story.traits.allTraits.Remove(source.RandomElement()); + } } } + pawn.story.traits.GainTrait(new Trait(this.trait, this.degree, true)); } - pawn.story.traits.GainTrait(new Trait(this.trait, this.degree, true)); } private static bool PawnHasTraitForcedByBackstory(Pawn pawn, TraitDef trait) { - return (pawn.story.childhood != null && pawn.story.childhood.forcedTraits != null && pawn.story.childhood.forcedTraits.Any((TraitEntry te) => te.def == trait)) || (pawn.story.adulthood != null && pawn.story.adulthood.forcedTraits != null && pawn.story.adulthood.forcedTraits.Any((TraitEntry te) => te.def == trait)); + if (pawn.story.childhood != null && pawn.story.childhood.forcedTraits != null && pawn.story.childhood.forcedTraits.Any((Predicate)((TraitEntry te) => te.def == trait))) + { + return true; + } + if (pawn.story.adulthood != null && pawn.story.adulthood.forcedTraits != null && pawn.story.adulthood.forcedTraits.Any((Predicate)((TraitEntry te) => te.def == trait))) + { + return true; + } + return false; } } } diff --git a/Assembly-CSharp/RimWorld/ScenPart_GameCondition.cs b/Assembly-CSharp/RimWorld/ScenPart_GameCondition.cs index 143121b94..bf8508fc4 100644 --- a/Assembly-CSharp/RimWorld/ScenPart_GameCondition.cs +++ b/Assembly-CSharp/RimWorld/ScenPart_GameCondition.cs @@ -1,4 +1,3 @@ -using System; using UnityEngine; using Verse; @@ -14,7 +13,7 @@ public override string Label { get { - return this.def.gameCondition.LabelCap; + return base.def.gameCondition.LabelCap; } } @@ -26,20 +25,12 @@ public override void ExposeData() public override string Summary(Scenario scen) { - return string.Concat(new string[] - { - this.def.gameCondition.LabelCap, - ": ", - this.def.gameCondition.description, - " (", - ((int)(this.durationDays * 60000f)).ToStringTicksToDays("F1"), - ")" - }); + return base.def.gameCondition.LabelCap + ": " + base.def.gameCondition.description + " (" + ((int)(this.durationDays * 60000.0)).ToStringTicksToDays("F1") + ")"; } public override void Randomize() { - this.durationDays = Mathf.Round(this.def.durationRandomRange.RandomInRange); + this.durationDays = Mathf.Round(base.def.durationRandomRange.RandomInRange); } public override void DoEditInterface(Listing_ScenEdit listing) @@ -50,18 +41,21 @@ public override void DoEditInterface(Listing_ScenEdit listing) public override void GenerateIntoMap(Map map) { - if (Find.GameInitData == null) + if (Find.GameInitData != null) { - return; + GameCondition cond = GameConditionMaker.MakeCondition(base.def.gameCondition, (int)(this.durationDays * 60000.0), 0); + map.gameConditionManager.RegisterCondition(cond); } - GameCondition cond = GameConditionMaker.MakeCondition(this.def.gameCondition, (int)(this.durationDays * 60000f), 0); - map.gameConditionManager.RegisterCondition(cond); } public override bool CanCoexistWith(ScenPart other) { ScenPart_GameCondition scenPart_GameCondition = other as ScenPart_GameCondition; - return scenPart_GameCondition == null || scenPart_GameCondition.def.gameCondition.CanCoexistWith(this.def.gameCondition); + if (scenPart_GameCondition != null && !scenPart_GameCondition.def.gameCondition.CanCoexistWith(base.def.gameCondition)) + { + return false; + } + return true; } } } diff --git a/Assembly-CSharp/RimWorld/ScenPart_GameStartDialog.cs b/Assembly-CSharp/RimWorld/ScenPart_GameStartDialog.cs index 0ec156fcc..eecf4ea26 100644 --- a/Assembly-CSharp/RimWorld/ScenPart_GameStartDialog.cs +++ b/Assembly-CSharp/RimWorld/ScenPart_GameStartDialog.cs @@ -14,15 +14,15 @@ public class ScenPart_GameStartDialog : ScenPart public override void DoEditInterface(Listing_ScenEdit listing) { - Rect scenPartRect = listing.GetScenPartRect(this, ScenPart.RowHeight * 5f); + Rect scenPartRect = listing.GetScenPartRect(this, (float)(ScenPart.RowHeight * 5.0)); this.text = Widgets.TextArea(scenPartRect, this.text, false); } public override void ExposeData() { base.ExposeData(); - Scribe_Values.Look(ref this.text, "text", null, false); - Scribe_Values.Look(ref this.textKey, "textKey", null, false); + Scribe_Values.Look(ref this.text, "text", (string)null, false); + Scribe_Values.Look(ref this.textKey, "textKey", (string)null, false); Scribe_Defs.Look(ref this.closeSound, "closeSound"); } @@ -37,9 +37,9 @@ public override void PostGameStart() diaOption.resolveTree = true; diaOption.clickSound = null; diaNode.options.Add(diaOption); - Dialog_NodeTree dialog_NodeTree = new Dialog_NodeTree(diaNode, false, false, null); + Dialog_NodeTree dialog_NodeTree = new Dialog_NodeTree(diaNode, false, false, (string)null); dialog_NodeTree.soundClose = ((this.closeSound == null) ? SoundDefOf.GameStartSting : this.closeSound); - dialog_NodeTree.closeAction = delegate + dialog_NodeTree.closeAction = (Action)delegate { Find.MusicManagerPlay.ForceSilenceFor(7f); Find.MusicManagerPlay.disabled = false; diff --git a/Assembly-CSharp/RimWorld/ScenPart_IncidentBase.cs b/Assembly-CSharp/RimWorld/ScenPart_IncidentBase.cs index 254c5da0b..3b58bdba4 100644 --- a/Assembly-CSharp/RimWorld/ScenPart_IncidentBase.cs +++ b/Assembly-CSharp/RimWorld/ScenPart_IncidentBase.cs @@ -1,6 +1,5 @@ using System; using System.Collections.Generic; -using System.Diagnostics; using System.Linq; using UnityEngine; using Verse; @@ -42,33 +41,37 @@ public override string Summary(Scenario scen) return ScenSummaryList.SummaryWithList(scen, this.IncidentTag, key.Translate()); } - [DebuggerHidden] public override IEnumerable GetSummaryListEntries(string tag) { - ScenPart_IncidentBase.c__Iterator119 c__Iterator = new ScenPart_IncidentBase.c__Iterator119(); - c__Iterator.tag = tag; - c__Iterator.<$>tag = tag; - c__Iterator.<>f__this = this; - ScenPart_IncidentBase.c__Iterator119 expr_1C = c__Iterator; - expr_1C.$PC = -2; - return expr_1C; + if (tag == this.IncidentTag) + { + yield return this.incident.LabelCap; + } } public override void Randomize() { - this.incident = this.RandomizableIncidents().RandomElement(); + this.incident = this.RandomizableIncidents().RandomElement(); } public override bool TryMerge(ScenPart other) { ScenPart_IncidentBase scenPart_IncidentBase = other as ScenPart_IncidentBase; - return scenPart_IncidentBase != null && scenPart_IncidentBase.Incident == this.incident; + if (scenPart_IncidentBase != null && scenPart_IncidentBase.Incident == this.incident) + { + return true; + } + return false; } public override bool CanCoexistWith(ScenPart other) { ScenPart_IncidentBase scenPart_IncidentBase = other as ScenPart_IncidentBase; - return scenPart_IncidentBase == null || scenPart_IncidentBase.Incident != this.incident; + if (scenPart_IncidentBase != null && scenPart_IncidentBase.Incident == this.incident) + { + return false; + } + return true; } protected virtual IEnumerable RandomizableIncidents() @@ -80,10 +83,10 @@ protected void DoIncidentEditInterface(Rect rect) { if (Widgets.ButtonText(rect, this.incident.LabelCap, true, false, true)) { - FloatMenuUtility.MakeMenu(DefDatabase.AllDefs, (IncidentDef id) => id.LabelCap, (IncidentDef id) => delegate + FloatMenuUtility.MakeMenu(DefDatabase.AllDefs, (Func)((IncidentDef id) => id.LabelCap), (Func)((IncidentDef id) => (Action)delegate() { this.incident = id; - }); + })); } } } diff --git a/Assembly-CSharp/RimWorld/ScenPart_OnPawnDeathExplode.cs b/Assembly-CSharp/RimWorld/ScenPart_OnPawnDeathExplode.cs index f95064785..b1aee9fd4 100644 --- a/Assembly-CSharp/RimWorld/ScenPart_OnPawnDeathExplode.cs +++ b/Assembly-CSharp/RimWorld/ScenPart_OnPawnDeathExplode.cs @@ -1,6 +1,5 @@ using System; using System.Collections.Generic; -using System.Diagnostics; using UnityEngine; using Verse; @@ -16,8 +15,8 @@ public class ScenPart_OnPawnDeathExplode : ScenPart public override void Randomize() { - this.radius = (float)Rand.RangeInclusive(3, 8) - 0.1f; - this.damage = this.PossibleDamageDefs().RandomElement(); + this.radius = (float)((float)Rand.RangeInclusive(3, 8) - 0.10000000149011612); + this.damage = this.PossibleDamageDefs().RandomElement(); } public override void ExposeData() @@ -29,23 +28,19 @@ public override void ExposeData() public override string Summary(Scenario scen) { - return "ScenPart_OnPawnDeathExplode".Translate(new object[] - { - this.damage.label, - this.radius.ToString() - }); + return "ScenPart_OnPawnDeathExplode".Translate(this.damage.label, this.radius.ToString()); } public override void DoEditInterface(Listing_ScenEdit listing) { - Rect scenPartRect = listing.GetScenPartRect(this, ScenPart.RowHeight * 2f); + Rect scenPartRect = listing.GetScenPartRect(this, (float)(ScenPart.RowHeight * 2.0)); Widgets.TextFieldNumericLabeled(scenPartRect.TopHalf(), "radius".Translate(), ref this.radius, ref this.radiusBuf, 0f, 1E+09f); if (Widgets.ButtonText(scenPartRect.BottomHalf(), this.damage.LabelCap, true, false, true)) { - FloatMenuUtility.MakeMenu(this.PossibleDamageDefs(), (DamageDef d) => d.LabelCap, (DamageDef d) => delegate + FloatMenuUtility.MakeMenu(this.PossibleDamageDefs(), (Func)((DamageDef d) => d.LabelCap), (Func)((DamageDef d) => (Action)delegate() { this.damage = d; - }); + })); } } @@ -57,13 +52,10 @@ public override void Notify_PawnDied(Corpse corpse) } } - [DebuggerHidden] private IEnumerable PossibleDamageDefs() { - ScenPart_OnPawnDeathExplode.c__Iterator116 c__Iterator = new ScenPart_OnPawnDeathExplode.c__Iterator116(); - ScenPart_OnPawnDeathExplode.c__Iterator116 expr_07 = c__Iterator; - expr_07.$PC = -2; - return expr_07; + yield return DamageDefOf.Bomb; + yield return DamageDefOf.Flame; } } } diff --git a/Assembly-CSharp/RimWorld/ScenPart_PawnFilter_Age.cs b/Assembly-CSharp/RimWorld/ScenPart_PawnFilter_Age.cs index d13b05a43..d5a6f0a5a 100644 --- a/Assembly-CSharp/RimWorld/ScenPart_PawnFilter_Age.cs +++ b/Assembly-CSharp/RimWorld/ScenPart_PawnFilter_Age.cs @@ -19,7 +19,7 @@ public class ScenPart_PawnFilter_Age : ScenPart public override void DoEditInterface(Listing_ScenEdit listing) { Rect scenPartRect = listing.GetScenPartRect(this, 31f); - Widgets.IntRange(scenPartRect, (int)listing.CurHeight, ref this.allowedAgeRange, 15, 120, null, 4); + Widgets.IntRange(scenPartRect, (int)listing.CurHeight, ref this.allowedAgeRange, 15, 120, (string)null, 4); } public override void ExposeData() @@ -34,28 +34,15 @@ public override string Summary(Scenario scen) { if (this.allowedAgeRange.max < 10000) { - return "ScenPart_StartingPawnAgeRange".Translate(new object[] - { - this.allowedAgeRange.min, - this.allowedAgeRange.max - }); + return "ScenPart_StartingPawnAgeRange".Translate(this.allowedAgeRange.min, this.allowedAgeRange.max); } - return "ScenPart_StartingPawnAgeMin".Translate(new object[] - { - this.allowedAgeRange.min - }); + return "ScenPart_StartingPawnAgeMin".Translate(this.allowedAgeRange.min); } - else + if (this.allowedAgeRange.max < 10000) { - if (this.allowedAgeRange.max < 10000) - { - return "ScenPart_StartingPawnAgeMax".Translate(new object[] - { - this.allowedAgeRange.max - }); - } - throw new Exception(); + return "ScenPart_StartingPawnAgeMax".Translate(this.allowedAgeRange.max); } + throw new Exception(); } public override bool AllowPlayerStartingPawn(Pawn pawn) @@ -69,16 +56,22 @@ public override void Randomize() switch (Rand.RangeInclusive(0, 2)) { case 0: + { this.allowedAgeRange.min = Rand.Range(20, 60); break; + } case 1: + { this.allowedAgeRange.max = Rand.Range(20, 60); break; + } case 2: + { this.allowedAgeRange.min = Rand.Range(20, 60); this.allowedAgeRange.max = Rand.Range(20, 60); break; } + } this.MakeAllowedAgeRangeValid(); } diff --git a/Assembly-CSharp/RimWorld/ScenPart_PawnModifier.cs b/Assembly-CSharp/RimWorld/ScenPart_PawnModifier.cs index 5ce82dc60..f9708b71b 100644 --- a/Assembly-CSharp/RimWorld/ScenPart_PawnModifier.cs +++ b/Assembly-CSharp/RimWorld/ScenPart_PawnModifier.cs @@ -1,5 +1,4 @@ using System; -using System.Collections; using System.Collections.Generic; using UnityEngine; using Verse; @@ -42,17 +41,13 @@ protected void DoPawnModifierEditInterface(Rect rect) if (Widgets.ButtonText(rect7, this.context.ToStringHuman(), true, false, true)) { List list = new List(); - using (IEnumerator enumerator = Enum.GetValues(typeof(PawnGenerationContext)).GetEnumerator()) + foreach (int value in Enum.GetValues(typeof(PawnGenerationContext))) { - while (enumerator.MoveNext()) + PawnGenerationContext localCont = (PawnGenerationContext)value; + list.Add(new FloatMenuOption(localCont.ToStringHuman(), (Action)delegate { - PawnGenerationContext localCont2 = (PawnGenerationContext)((int)enumerator.Current); - PawnGenerationContext localCont = localCont2; - list.Add(new FloatMenuOption(localCont.ToStringHuman(), delegate - { - this.context = localCont; - }, MenuOptionPriority.Default, null, null, 0f, null, null)); - } + this.context = localCont; + }, MenuOptionPriority.Default, null, null, 0f, null, null)); } Find.WindowStack.Add(new FloatMenu(list)); } @@ -68,9 +63,7 @@ public override void Randomize() public override void Notify_PawnGenerated(Pawn pawn, PawnGenerationContext context) { if (this.hideOffMap && PawnGenerationContext.PlayerStarter.Includes(context)) - { return; - } if (pawn.RaceProps.Humanlike && this.context.Includes(context)) { this.ModifyPawn(pawn); @@ -79,19 +72,26 @@ public override void Notify_PawnGenerated(Pawn pawn, PawnGenerationContext conte public override void PostMapGenerate(Map map) { - if (Find.GameInitData == null) - { - return; - } - if (this.hideOffMap && (this.context == PawnGenerationContext.PlayerStarter || this.context == PawnGenerationContext.All)) + if (Find.GameInitData != null && this.hideOffMap) { - foreach (Pawn current in Find.GameInitData.startingPawns) + if (((this.context != PawnGenerationContext.PlayerStarter) ? this.context : PawnGenerationContext.All) != 0) + return; + List.Enumerator enumerator = Find.GameInitData.startingPawns.GetEnumerator(); + try { - if (current.RaceProps.Humanlike) + while (enumerator.MoveNext()) { - this.ModifyPawn(current); + Pawn current = enumerator.Current; + if (current.RaceProps.Humanlike) + { + this.ModifyPawn(current); + } } } + finally + { + ((IDisposable)(object)enumerator).Dispose(); + } } } diff --git a/Assembly-CSharp/RimWorld/ScenPart_PermaGameCondition.cs b/Assembly-CSharp/RimWorld/ScenPart_PermaGameCondition.cs index 18fde08fc..84baf6416 100644 --- a/Assembly-CSharp/RimWorld/ScenPart_PermaGameCondition.cs +++ b/Assembly-CSharp/RimWorld/ScenPart_PermaGameCondition.cs @@ -1,6 +1,5 @@ using System; using System.Collections.Generic; -using System.Diagnostics; using System.Linq; using UnityEngine; using Verse; @@ -26,10 +25,10 @@ public override void DoEditInterface(Listing_ScenEdit listing) Rect scenPartRect = listing.GetScenPartRect(this, ScenPart.RowHeight); if (Widgets.ButtonText(scenPartRect, this.gameCondition.LabelCap, true, false, true)) { - FloatMenuUtility.MakeMenu(this.AllowedGameConditions(), (GameConditionDef d) => d.LabelCap, (GameConditionDef d) => delegate + FloatMenuUtility.MakeMenu(this.AllowedGameConditions(), (Func)((GameConditionDef d) => d.LabelCap), (Func)((GameConditionDef d) => (Action)delegate() { this.gameCondition = d; - }); + })); } } @@ -41,7 +40,7 @@ public override void ExposeData() public override void Randomize() { - this.gameCondition = this.AllowedGameConditions().RandomElement(); + this.gameCondition = this.AllowedGameConditions().RandomElement(); } private IEnumerable AllowedGameConditions() @@ -56,16 +55,12 @@ public override string Summary(Scenario scen) return ScenSummaryList.SummaryWithList(scen, "PermaGameCondition", "ScenPart_PermaGameCondition".Translate()); } - [DebuggerHidden] public override IEnumerable GetSummaryListEntries(string tag) { - ScenPart_PermaGameCondition.c__Iterator115 c__Iterator = new ScenPart_PermaGameCondition.c__Iterator115(); - c__Iterator.tag = tag; - c__Iterator.<$>tag = tag; - c__Iterator.<>f__this = this; - ScenPart_PermaGameCondition.c__Iterator115 expr_1C = c__Iterator; - expr_1C.$PC = -2; - return expr_1C; + if (tag == "PermaGameCondition") + { + yield return this.gameCondition.LabelCap + ": " + this.gameCondition.description; + } } public override void GenerateIntoMap(Map map) @@ -81,7 +76,11 @@ public override bool CanCoexistWith(ScenPart other) return true; } ScenPart_PermaGameCondition scenPart_PermaGameCondition = other as ScenPart_PermaGameCondition; - return scenPart_PermaGameCondition == null || this.gameCondition.CanCoexistWith(scenPart_PermaGameCondition.gameCondition); + if (scenPart_PermaGameCondition != null && !this.gameCondition.CanCoexistWith(scenPart_PermaGameCondition.gameCondition)) + { + return false; + } + return true; } } } diff --git a/Assembly-CSharp/RimWorld/ScenPart_PlayerFaction.cs b/Assembly-CSharp/RimWorld/ScenPart_PlayerFaction.cs index dec6b7fec..9e7eadd84 100644 --- a/Assembly-CSharp/RimWorld/ScenPart_PlayerFaction.cs +++ b/Assembly-CSharp/RimWorld/ScenPart_PlayerFaction.cs @@ -1,7 +1,6 @@ using RimWorld.Planet; using System; using System.Collections.Generic; -using System.Diagnostics; using System.Linq; using UnityEngine; using Verse; @@ -24,12 +23,12 @@ public override void DoEditInterface(Listing_ScenEdit listing) if (Widgets.ButtonText(scenPartRect, this.factionDef.LabelCap, true, false, true)) { List list = new List(); - foreach (FactionDef current in from d in DefDatabase.AllDefs + foreach (FactionDef item in from d in DefDatabase.AllDefs where d.isPlayer select d) { - FactionDef localFd = current; - list.Add(new FloatMenuOption(localFd.LabelCap, delegate + FactionDef localFd = item; + list.Add(new FloatMenuOption(localFd.LabelCap, (Action)delegate { this.factionDef = localFd; }, MenuOptionPriority.Default, null, null, 0f, null, null)); @@ -40,17 +39,14 @@ where d.isPlayer public override string Summary(Scenario scen) { - return "ScenPart_PlayerFaction".Translate(new object[] - { - this.factionDef.label - }); + return "ScenPart_PlayerFaction".Translate(this.factionDef.label); } public override void Randomize() { this.factionDef = (from fd in DefDatabase.AllDefs where fd.isPlayer - select fd).RandomElement(); + select fd).RandomElement(); } public override void PostWorldGenerate() @@ -74,14 +70,12 @@ public override void PostGameStart() Find.GameInitData.playerFaction = null; } - [DebuggerHidden] public override IEnumerable ConfigErrors() { - ScenPart_PlayerFaction.c__Iterator11C c__Iterator11C = new ScenPart_PlayerFaction.c__Iterator11C(); - c__Iterator11C.<>f__this = this; - ScenPart_PlayerFaction.c__Iterator11C expr_0E = c__Iterator11C; - expr_0E.$PC = -2; - return expr_0E; + if (this.factionDef == null) + { + yield return "factionDef is null"; + } } } } diff --git a/Assembly-CSharp/RimWorld/ScenPart_PlayerPawnsArriveMethod.cs b/Assembly-CSharp/RimWorld/ScenPart_PlayerPawnsArriveMethod.cs index 113f2badb..7c95c45e8 100644 --- a/Assembly-CSharp/RimWorld/ScenPart_PlayerPawnsArriveMethod.cs +++ b/Assembly-CSharp/RimWorld/ScenPart_PlayerPawnsArriveMethod.cs @@ -1,5 +1,4 @@ using System; -using System.Collections; using System.Collections.Generic; using UnityEngine; using Verse; @@ -22,17 +21,13 @@ public override void DoEditInterface(Listing_ScenEdit listing) if (Widgets.ButtonText(scenPartRect, this.method.ToStringHuman(), true, false, true)) { List list = new List(); - using (IEnumerator enumerator = Enum.GetValues(typeof(PlayerPawnsArriveMethod)).GetEnumerator()) + foreach (int value in Enum.GetValues(typeof(PlayerPawnsArriveMethod))) { - while (enumerator.MoveNext()) + PlayerPawnsArriveMethod localM = (PlayerPawnsArriveMethod)value; + list.Add(new FloatMenuOption(localM.ToStringHuman(), (Action)delegate { - PlayerPawnsArriveMethod localM2 = (PlayerPawnsArriveMethod)((int)enumerator.Current); - PlayerPawnsArriveMethod localM = localM2; - list.Add(new FloatMenuOption(localM.ToStringHuman(), delegate - { - this.method = localM; - }, MenuOptionPriority.Default, null, null, 0f, null, null)); - } + this.method = localM; + }, MenuOptionPriority.Default, null, null, 0f, null, null)); } Find.WindowStack.Add(new FloatMenu(list)); } @@ -44,58 +39,70 @@ public override string Summary(Scenario scen) { return "ScenPart_ArriveInDropPods".Translate(); } - return null; + return (string)null; } public override void Randomize() { - this.method = ((Rand.Value >= 0.5f) ? PlayerPawnsArriveMethod.Standing : PlayerPawnsArriveMethod.DropPods); + this.method = (PlayerPawnsArriveMethod)((Rand.Value < 0.5) ? 1 : 0); } public override void GenerateIntoMap(Map map) { - if (Find.GameInitData == null) + if (Find.GameInitData != null) { - return; - } - List> list = new List>(); - foreach (Pawn current in Find.GameInitData.startingPawns) - { - list.Add(new List + List> list = new List>(); + List.Enumerator enumerator = Find.GameInitData.startingPawns.GetEnumerator(); + try { - current - }); - } - List list2 = new List(); - foreach (ScenPart current2 in Find.Scenario.AllParts) - { - list2.AddRange(current2.PlayerStartingThings()); - } - int num = 0; - foreach (Thing current3 in list2) - { - if (current3.def.CanHaveFaction) + while (enumerator.MoveNext()) + { + Pawn current = enumerator.Current; + List list2 = new List(); + list2.Add(current); + list.Add(list2); + } + } + finally + { + ((IDisposable)(object)enumerator).Dispose(); + } + List list3 = new List(); + foreach (ScenPart allPart in Find.Scenario.AllParts) { - current3.SetFactionDirect(Faction.OfPlayer); + list3.AddRange(allPart.PlayerStartingThings()); + } + int num = 0; + List.Enumerator enumerator3 = list3.GetEnumerator(); + try + { + while (enumerator3.MoveNext()) + { + Thing current3 = enumerator3.Current; + if (current3.def.CanHaveFaction) + { + current3.SetFactionDirect(Faction.OfPlayer); + } + list[num].Add(current3); + num++; + if (num >= list.Count) + { + num = 0; + } + } } - list[num].Add(current3); - num++; - if (num >= list.Count) + finally { - num = 0; + ((IDisposable)(object)enumerator3).Dispose(); } + bool instaDrop = Find.GameInitData.QuickStarted || this.method != PlayerPawnsArriveMethod.DropPods; + DropPodUtility.DropThingGroupsNear(MapGenerator.PlayerStartSpot, map, list, 110, instaDrop, true, true); } - bool instaDrop = Find.GameInitData.QuickStarted || this.method != PlayerPawnsArriveMethod.DropPods; - DropPodUtility.DropThingGroupsNear(MapGenerator.PlayerStartSpot, map, list, 110, instaDrop, true, true); } public override void PostMapGenerate(Map map) { - if (Find.GameInitData == null) - { - return; - } - if (this.method == PlayerPawnsArriveMethod.DropPods) + if (Find.GameInitData != null && this.method == PlayerPawnsArriveMethod.DropPods) { PawnUtility.GiveAllStartingPlayerPawnsThought(ThoughtDefOf.CrashedTogether); } diff --git a/Assembly-CSharp/RimWorld/ScenPart_Rule.cs b/Assembly-CSharp/RimWorld/ScenPart_Rule.cs index 8bd282b1e..fb5c11949 100644 --- a/Assembly-CSharp/RimWorld/ScenPart_Rule.cs +++ b/Assembly-CSharp/RimWorld/ScenPart_Rule.cs @@ -1,5 +1,3 @@ -using System; - namespace RimWorld { public abstract class ScenPart_Rule : ScenPart diff --git a/Assembly-CSharp/RimWorld/ScenPart_Rule_DisallowDesignator.cs b/Assembly-CSharp/RimWorld/ScenPart_Rule_DisallowDesignator.cs index 5640640b1..25e25acd1 100644 --- a/Assembly-CSharp/RimWorld/ScenPart_Rule_DisallowDesignator.cs +++ b/Assembly-CSharp/RimWorld/ScenPart_Rule_DisallowDesignator.cs @@ -1,4 +1,3 @@ -using System; using Verse; namespace RimWorld @@ -7,7 +6,7 @@ public class ScenPart_Rule_DisallowDesignator : ScenPart_Rule { protected override void ApplyRule() { - Current.Game.Rules.SetAllowDesignator(this.def.designatorType, false); + Current.Game.Rules.SetAllowDesignator(base.def.designatorType, false); } } } diff --git a/Assembly-CSharp/RimWorld/ScenPart_ScatterThings.cs b/Assembly-CSharp/RimWorld/ScenPart_ScatterThings.cs index 63c2f3d93..4b40dbcc8 100644 --- a/Assembly-CSharp/RimWorld/ScenPart_ScatterThings.cs +++ b/Assembly-CSharp/RimWorld/ScenPart_ScatterThings.cs @@ -1,4 +1,3 @@ -using System; using Verse; namespace RimWorld @@ -12,20 +11,18 @@ protected abstract bool NearPlayerStart public override void GenerateIntoMap(Map map) { - if (Find.GameInitData == null) + if (Find.GameInitData != null) { - return; + GenStep_ScatterThings genStep_ScatterThings = new GenStep_ScatterThings(); + genStep_ScatterThings.nearPlayerStart = this.NearPlayerStart; + genStep_ScatterThings.thingDef = base.thingDef; + genStep_ScatterThings.stuff = base.stuff; + genStep_ScatterThings.count = base.count; + genStep_ScatterThings.spotMustBeStandable = true; + genStep_ScatterThings.minSpacing = 5f; + genStep_ScatterThings.clusterSize = ((base.thingDef.category == ThingCategory.Building) ? 1 : 4); + genStep_ScatterThings.Generate(map); } - new GenStep_ScatterThings - { - nearPlayerStart = this.NearPlayerStart, - thingDef = this.thingDef, - stuff = this.stuff, - count = this.count, - spotMustBeStandable = true, - minSpacing = 5f, - clusterSize = ((this.thingDef.category != ThingCategory.Building) ? 4 : 1) - }.Generate(map); } } } diff --git a/Assembly-CSharp/RimWorld/ScenPart_ScatterThingsAnywhere.cs b/Assembly-CSharp/RimWorld/ScenPart_ScatterThingsAnywhere.cs index 4ac0dcaee..c5d8ac9c8 100644 --- a/Assembly-CSharp/RimWorld/ScenPart_ScatterThingsAnywhere.cs +++ b/Assembly-CSharp/RimWorld/ScenPart_ScatterThingsAnywhere.cs @@ -1,6 +1,4 @@ -using System; using System.Collections.Generic; -using System.Diagnostics; using Verse; namespace RimWorld @@ -22,16 +20,12 @@ public override string Summary(Scenario scen) return ScenSummaryList.SummaryWithList(scen, "MapScatteredWith", "ScenPart_MapScatteredWith".Translate()); } - [DebuggerHidden] public override IEnumerable GetSummaryListEntries(string tag) { - ScenPart_ScatterThingsAnywhere.c__Iterator121 c__Iterator = new ScenPart_ScatterThingsAnywhere.c__Iterator121(); - c__Iterator.tag = tag; - c__Iterator.<$>tag = tag; - c__Iterator.<>f__this = this; - ScenPart_ScatterThingsAnywhere.c__Iterator121 expr_1C = c__Iterator; - expr_1C.$PC = -2; - return expr_1C; + if (tag == "MapScatteredWith") + { + yield return GenLabel.ThingLabel(base.thingDef, base.stuff, base.count).CapitalizeFirst(); + } } } } diff --git a/Assembly-CSharp/RimWorld/ScenPart_ScatterThingsNearPlayerStart.cs b/Assembly-CSharp/RimWorld/ScenPart_ScatterThingsNearPlayerStart.cs index f94dbc21c..23056908e 100644 --- a/Assembly-CSharp/RimWorld/ScenPart_ScatterThingsNearPlayerStart.cs +++ b/Assembly-CSharp/RimWorld/ScenPart_ScatterThingsNearPlayerStart.cs @@ -1,6 +1,5 @@ -using System; using System.Collections.Generic; -using System.Diagnostics; +using Verse; namespace RimWorld { @@ -19,16 +18,12 @@ public override string Summary(Scenario scen) return ScenSummaryList.SummaryWithList(scen, "PlayerStartsWith", ScenPart_StartingThing_Defined.PlayerStartWithIntro); } - [DebuggerHidden] public override IEnumerable GetSummaryListEntries(string tag) { - ScenPart_ScatterThingsNearPlayerStart.c__Iterator122 c__Iterator = new ScenPart_ScatterThingsNearPlayerStart.c__Iterator122(); - c__Iterator.tag = tag; - c__Iterator.<$>tag = tag; - c__Iterator.<>f__this = this; - ScenPart_ScatterThingsNearPlayerStart.c__Iterator122 expr_1C = c__Iterator; - expr_1C.$PC = -2; - return expr_1C; + if (tag == "PlayerStartsWith") + { + yield return GenLabel.ThingLabel(base.thingDef, base.stuff, base.count).CapitalizeFirst(); + } } } } diff --git a/Assembly-CSharp/RimWorld/ScenPart_SetNeedLevel.cs b/Assembly-CSharp/RimWorld/ScenPart_SetNeedLevel.cs index 6864d492d..2ce0ce5fe 100644 --- a/Assembly-CSharp/RimWorld/ScenPart_SetNeedLevel.cs +++ b/Assembly-CSharp/RimWorld/ScenPart_SetNeedLevel.cs @@ -14,16 +14,16 @@ public class ScenPart_SetNeedLevel : ScenPart_PawnModifier public override void DoEditInterface(Listing_ScenEdit listing) { - Rect scenPartRect = listing.GetScenPartRect(this, ScenPart.RowHeight * 3f + 31f); + Rect scenPartRect = listing.GetScenPartRect(this, (float)(ScenPart.RowHeight * 3.0 + 31.0)); if (Widgets.ButtonText(scenPartRect.TopPartPixels(ScenPart.RowHeight), this.need.LabelCap, true, false, true)) { - FloatMenuUtility.MakeMenu(this.PossibleNeeds(), (NeedDef hd) => hd.LabelCap, (NeedDef n) => delegate + FloatMenuUtility.MakeMenu(this.PossibleNeeds(), (Func)((NeedDef hd) => hd.LabelCap), (Func)((NeedDef n) => (Action)delegate() { this.need = n; - }); + })); } Widgets.FloatRange(new Rect(scenPartRect.x, scenPartRect.y + ScenPart.RowHeight, scenPartRect.width, 31f), listing.CurHeight.GetHashCode(), ref this.levelRange, 0f, 1f, "ConfigurableLevel", ToStringStyle.FloatTwo); - base.DoPawnModifierEditInterface(scenPartRect.BottomPartPixels(ScenPart.RowHeight * 2f)); + base.DoPawnModifierEditInterface(scenPartRect.BottomPartPixels((float)(ScenPart.RowHeight * 2.0))); } private IEnumerable PossibleNeeds() @@ -42,20 +42,13 @@ public override void ExposeData() public override string Summary(Scenario scen) { - return "ScenPart_SetNeed".Translate(new object[] - { - this.context.ToStringHuman(), - this.chance.ToStringPercent(), - this.need.label, - this.levelRange.min.ToStringPercent(), - this.levelRange.max.ToStringPercent() - }).CapitalizeFirst(); + return "ScenPart_SetNeed".Translate(base.context.ToStringHuman(), base.chance.ToStringPercent(), this.need.label, this.levelRange.min.ToStringPercent(), this.levelRange.max.ToStringPercent()).CapitalizeFirst(); } public override void Randomize() { base.Randomize(); - this.need = this.PossibleNeeds().RandomElement(); + this.need = this.PossibleNeeds().RandomElement(); this.levelRange.max = Rand.Range(0f, 1f); this.levelRange.min = this.levelRange.max * Rand.Range(0f, 0.95f); } @@ -65,7 +58,7 @@ public override bool TryMerge(ScenPart other) ScenPart_SetNeedLevel scenPart_SetNeedLevel = other as ScenPart_SetNeedLevel; if (scenPart_SetNeedLevel != null && this.need == scenPart_SetNeedLevel.need) { - this.chance = GenMath.ChanceEitherHappens(this.chance, scenPart_SetNeedLevel.chance); + base.chance = GenMath.ChanceEitherHappens(base.chance, scenPart_SetNeedLevel.chance); return true; } return false; @@ -73,7 +66,7 @@ public override bool TryMerge(ScenPart other) protected override void ModifyPawn(Pawn p) { - if (Rand.Value < this.chance && p.needs != null) + if (Rand.Value < base.chance && p.needs != null) { Need need = p.needs.TryGetNeed(this.need); if (need != null) diff --git a/Assembly-CSharp/RimWorld/ScenPart_StartingAnimal.cs b/Assembly-CSharp/RimWorld/ScenPart_StartingAnimal.cs index 504321632..d414c5497 100644 --- a/Assembly-CSharp/RimWorld/ScenPart_StartingAnimal.cs +++ b/Assembly-CSharp/RimWorld/ScenPart_StartingAnimal.cs @@ -1,6 +1,5 @@ using System; using System.Collections.Generic; -using System.Diagnostics; using System.Linq; using UnityEngine; using Verse; @@ -45,7 +44,7 @@ public override void ExposeData() public override void DoEditInterface(Listing_ScenEdit listing) { - Rect scenPartRect = listing.GetScenPartRect(this, ScenPart.RowHeight * 2f); + Rect scenPartRect = listing.GetScenPartRect(this, (float)(ScenPart.RowHeight * 2.0)); Listing_Standard listing_Standard = new Listing_Standard(); listing_Standard.Begin(scenPartRect.TopHalf()); listing_Standard.ColumnWidth = scenPartRect.width; @@ -54,14 +53,14 @@ public override void DoEditInterface(Listing_ScenEdit listing) if (Widgets.ButtonText(scenPartRect.BottomHalf(), this.CurrentAnimalLabel().CapitalizeFirst(), true, false, true)) { List list = new List(); - list.Add(new FloatMenuOption("RandomPet".Translate().CapitalizeFirst(), delegate + list.Add(new FloatMenuOption("RandomPet".Translate().CapitalizeFirst(), (Action)delegate { this.animalKind = null; }, MenuOptionPriority.Default, null, null, 0f, null, null)); - foreach (PawnKindDef current in this.PossibleAnimals()) + foreach (PawnKindDef item in this.PossibleAnimals()) { - PawnKindDef localKind = current; - list.Add(new FloatMenuOption(localKind.LabelCap, delegate + PawnKindDef localKind = item; + list.Add(new FloatMenuOption(localKind.LabelCap, (Action)delegate { this.animalKind = localKind; }, MenuOptionPriority.Default, null, null, 0f, null, null)); @@ -80,7 +79,7 @@ where td.RaceProps.Animal private IEnumerable RandomPets() { return from td in this.PossibleAnimals() - where td.RaceProps.petness > 0f + where td.RaceProps.petness > 0.0 select td; } @@ -94,29 +93,25 @@ public override string Summary(Scenario scen) return ScenSummaryList.SummaryWithList(scen, "PlayerStartsWith", ScenPart_StartingThing_Defined.PlayerStartWithIntro); } - [DebuggerHidden] public override IEnumerable GetSummaryListEntries(string tag) { - ScenPart_StartingAnimal.c__Iterator11D c__Iterator11D = new ScenPart_StartingAnimal.c__Iterator11D(); - c__Iterator11D.tag = tag; - c__Iterator11D.<$>tag = tag; - c__Iterator11D.<>f__this = this; - ScenPart_StartingAnimal.c__Iterator11D expr_1C = c__Iterator11D; - expr_1C.$PC = -2; - return expr_1C; + if (tag == "PlayerStartsWith") + { + yield return this.CurrentAnimalLabel().CapitalizeFirst() + " x" + this.count; + } } public override void Randomize() { - if (Rand.Value < 0.5f) + if (Rand.Value < 0.5) { this.animalKind = null; } else { - this.animalKind = this.PossibleAnimals().RandomElement(); + this.animalKind = this.PossibleAnimals().RandomElement(); } - this.count = ScenPart_StartingAnimal.PetCountChances.RandomElementByWeight((Pair pa) => pa.Second).First; + this.count = ScenPart_StartingAnimal.PetCountChances.RandomElementByWeight((Func, float>)((Pair pa) => pa.Second)).First; this.bondToRandomPlayerPawnChance = 0f; } @@ -131,14 +126,26 @@ public override bool TryMerge(ScenPart other) return false; } - [DebuggerHidden] public override IEnumerable PlayerStartingThings() { - ScenPart_StartingAnimal.c__Iterator11E c__Iterator11E = new ScenPart_StartingAnimal.c__Iterator11E(); - c__Iterator11E.<>f__this = this; - ScenPart_StartingAnimal.c__Iterator11E expr_0E = c__Iterator11E; - expr_0E.$PC = -2; - return expr_0E; + for (int i = 0; i < this.count; i++) + { + PawnKindDef kind = (this.animalKind == null) ? this.RandomPets().RandomElementByWeight((Func)((PawnKindDef td) => td.RaceProps.petness)) : this.animalKind; + Pawn animal = PawnGenerator.GeneratePawn(kind, Faction.OfPlayer); + if (animal.Name == null || animal.Name.Numerical) + { + animal.Name = PawnBioAndNameGenerator.GeneratePawnName(animal, NameStyle.Full, (string)null); + } + if (Rand.Value < this.bondToRandomPlayerPawnChance) + { + Pawn col = Find.GameInitData.startingPawns.RandomElement(); + if (!col.story.traits.HasTrait(TraitDefOf.Psychopath)) + { + col.relations.AddDirectRelation(PawnRelationDefOf.Bond, animal); + } + } + yield return (Thing)animal; + } } } } diff --git a/Assembly-CSharp/RimWorld/ScenPart_StartingResearch.cs b/Assembly-CSharp/RimWorld/ScenPart_StartingResearch.cs index 6e2097a09..8994db347 100644 --- a/Assembly-CSharp/RimWorld/ScenPart_StartingResearch.cs +++ b/Assembly-CSharp/RimWorld/ScenPart_StartingResearch.cs @@ -15,27 +15,27 @@ public override void DoEditInterface(Listing_ScenEdit listing) Rect scenPartRect = listing.GetScenPartRect(this, ScenPart.RowHeight); if (Widgets.ButtonText(scenPartRect, this.project.LabelCap, true, false, true)) { - FloatMenuUtility.MakeMenu(this.NonRedundantResearchProjects(), (ResearchProjectDef d) => d.LabelCap, (ResearchProjectDef d) => delegate + FloatMenuUtility.MakeMenu(this.NonRedundantResearchProjects(), (Func)((ResearchProjectDef d) => d.LabelCap), (Func)((ResearchProjectDef d) => (Action)delegate() { this.project = d; - }); + })); } } public override void Randomize() { - this.project = this.NonRedundantResearchProjects().RandomElement(); + this.project = this.NonRedundantResearchProjects().RandomElement(); } private IEnumerable NonRedundantResearchProjects() { - return DefDatabase.AllDefs.Where(delegate(ResearchProjectDef d) + return DefDatabase.AllDefs.Where((Func)delegate(ResearchProjectDef d) { - if (d.tags == null || Find.Scenario.playerFaction.factionDef.startingResearchTags == null) + if (d.tags != null && Find.Scenario.playerFaction.factionDef.startingResearchTags != null) { - return true; + return !d.tags.Any((Predicate)((string tag) => Find.Scenario.playerFaction.factionDef.startingResearchTags.Contains(tag))); } - return !d.tags.Any((string tag) => Find.Scenario.playerFaction.factionDef.startingResearchTags.Contains(tag)); + return true; }); } @@ -47,10 +47,7 @@ public override void ExposeData() public override string Summary(Scenario scen) { - return "ScenPart_StartingResearchFinished".Translate(new object[] - { - this.project.LabelCap - }); + return "ScenPart_StartingResearchFinished".Translate(this.project.LabelCap); } public override void PostGameStart() diff --git a/Assembly-CSharp/RimWorld/ScenPart_StartingThing_Defined.cs b/Assembly-CSharp/RimWorld/ScenPart_StartingThing_Defined.cs index 89bb1811f..3dad22dc0 100644 --- a/Assembly-CSharp/RimWorld/ScenPart_StartingThing_Defined.cs +++ b/Assembly-CSharp/RimWorld/ScenPart_StartingThing_Defined.cs @@ -1,6 +1,4 @@ -using System; using System.Collections.Generic; -using System.Diagnostics; using Verse; namespace RimWorld @@ -22,26 +20,23 @@ public override string Summary(Scenario scen) return ScenSummaryList.SummaryWithList(scen, "PlayerStartsWith", ScenPart_StartingThing_Defined.PlayerStartWithIntro); } - [DebuggerHidden] public override IEnumerable GetSummaryListEntries(string tag) { - ScenPart_StartingThing_Defined.c__Iterator123 c__Iterator = new ScenPart_StartingThing_Defined.c__Iterator123(); - c__Iterator.tag = tag; - c__Iterator.<$>tag = tag; - c__Iterator.<>f__this = this; - ScenPart_StartingThing_Defined.c__Iterator123 expr_1C = c__Iterator; - expr_1C.$PC = -2; - return expr_1C; + if (tag == "PlayerStartsWith") + { + yield return GenLabel.ThingLabel(base.thingDef, base.stuff, base.count).CapitalizeFirst(); + } } - [DebuggerHidden] public override IEnumerable PlayerStartingThings() { - ScenPart_StartingThing_Defined.c__Iterator124 c__Iterator = new ScenPart_StartingThing_Defined.c__Iterator124(); - c__Iterator.<>f__this = this; - ScenPart_StartingThing_Defined.c__Iterator124 expr_0E = c__Iterator; - expr_0E.$PC = -2; - return expr_0E; + Thing t = ThingMaker.MakeThing(base.thingDef, base.stuff); + if (base.thingDef.Minifiable) + { + t = t.MakeMinified(); + } + t.stackCount = base.count; + yield return t; } } } diff --git a/Assembly-CSharp/RimWorld/ScenPart_StatFactor.cs b/Assembly-CSharp/RimWorld/ScenPart_StatFactor.cs index 8c465975a..cb1cac6d2 100644 --- a/Assembly-CSharp/RimWorld/ScenPart_StatFactor.cs +++ b/Assembly-CSharp/RimWorld/ScenPart_StatFactor.cs @@ -1,6 +1,5 @@ using System; using System.Collections.Generic; -using System.Diagnostics; using UnityEngine; using Verse; @@ -23,15 +22,15 @@ public override void ExposeData() public override void DoEditInterface(Listing_ScenEdit listing) { - Rect scenPartRect = listing.GetScenPartRect(this, ScenPart.RowHeight * 2f); + Rect scenPartRect = listing.GetScenPartRect(this, (float)(ScenPart.RowHeight * 2.0)); Rect rect = scenPartRect.TopHalf(); if (Widgets.ButtonText(rect, this.stat.LabelCap, true, false, true)) { List list = new List(); - foreach (StatDef current in DefDatabase.AllDefs) + foreach (StatDef allDef in DefDatabase.AllDefs) { - StatDef localSd = current; - list.Add(new FloatMenuOption(localSd.LabelCap, delegate + StatDef localSd = allDef; + list.Add(new FloatMenuOption(localSd.LabelCap, (Action)delegate { this.stat = localSd; }, MenuOptionPriority.Default, null, null, 0f, null, null)); @@ -49,16 +48,12 @@ public override void DoEditInterface(Listing_ScenEdit listing) public override string Summary(Scenario scen) { - return "ScenPart_StatFactor".Translate(new object[] - { - this.stat.label, - this.factor.ToStringPercent() - }); + return "ScenPart_StatFactor".Translate(this.stat.label, this.factor.ToStringPercent()); } public override void Randomize() { - this.stat = this.RandomizableStats().RandomElement(); + this.stat = this.RandomizableStats().RandomElement(); this.factor = GenMath.RoundedHundredth(Rand.Range(0.1f, 3f)); } @@ -82,13 +77,35 @@ public float GetStatFactor(StatDef stat) return 1f; } - [DebuggerHidden] private IEnumerable RandomizableStats() { - ScenPart_StatFactor.c__Iterator11F c__Iterator11F = new ScenPart_StatFactor.c__Iterator11F(); - ScenPart_StatFactor.c__Iterator11F expr_07 = c__Iterator11F; - expr_07.$PC = -2; - return expr_07; + yield return StatDefOf.ComfyTemperatureMax; + yield return StatDefOf.ComfyTemperatureMin; + yield return StatDefOf.ConstructSuccessChance; + yield return StatDefOf.ConstructionSpeed; + yield return StatDefOf.DeteriorationRate; + yield return StatDefOf.Flammability; + yield return StatDefOf.GlobalLearningFactor; + yield return StatDefOf.PlantHarvestYield; + yield return StatDefOf.MedicalTendSpeed; + yield return StatDefOf.ImmunityGainSpeed; + yield return StatDefOf.MarketValue; + yield return StatDefOf.MaxHitPoints; + yield return StatDefOf.MentalBreakThreshold; + yield return StatDefOf.MiningSpeed; + yield return StatDefOf.MoveSpeed; + yield return StatDefOf.PsychicSensitivity; + yield return StatDefOf.ResearchSpeed; + yield return StatDefOf.ShootingAccuracy; + yield return StatDefOf.MedicalSurgerySuccessChance; + yield return StatDefOf.RecruitPrisonerChance; + yield return StatDefOf.TameAnimalChance; + yield return StatDefOf.TrainAnimalChance; + yield return StatDefOf.MeleeWeapon_DamageAmount; + yield return StatDefOf.RangedWeapon_Cooldown; + yield return StatDefOf.WorkSpeedGlobal; + yield return StatDefOf.WorkToMake; + yield return StatDefOf.WorkToBuild; } } } diff --git a/Assembly-CSharp/RimWorld/ScenPart_ThingCount.cs b/Assembly-CSharp/RimWorld/ScenPart_ThingCount.cs index fdd73c7e5..e7f526ce7 100644 --- a/Assembly-CSharp/RimWorld/ScenPart_ThingCount.cs +++ b/Assembly-CSharp/RimWorld/ScenPart_ThingCount.cs @@ -26,7 +26,7 @@ public override void ExposeData() public override void Randomize() { - this.thingDef = this.PossibleThingDefs().RandomElement(); + this.thingDef = this.PossibleThingDefs().RandomElement(); this.stuff = GenStuff.RandomStuffFor(this.thingDef); if (this.thingDef.statBases.StatListContains(StatDefOf.MarketValue)) { @@ -42,19 +42,19 @@ public override void Randomize() public override void DoEditInterface(Listing_ScenEdit listing) { - Rect scenPartRect = listing.GetScenPartRect(this, ScenPart.RowHeight * 3f); - Rect rect = new Rect(scenPartRect.x, scenPartRect.y, scenPartRect.width, scenPartRect.height / 3f); - Rect rect2 = new Rect(scenPartRect.x, scenPartRect.y + scenPartRect.height / 3f, scenPartRect.width, scenPartRect.height / 3f); - Rect rect3 = new Rect(scenPartRect.x, scenPartRect.y + scenPartRect.height * 2f / 3f, scenPartRect.width, scenPartRect.height / 3f); + Rect scenPartRect = listing.GetScenPartRect(this, (float)(ScenPart.RowHeight * 3.0)); + Rect rect = new Rect(scenPartRect.x, scenPartRect.y, scenPartRect.width, (float)(scenPartRect.height / 3.0)); + Rect rect2 = new Rect(scenPartRect.x, (float)(scenPartRect.y + scenPartRect.height / 3.0), scenPartRect.width, (float)(scenPartRect.height / 3.0)); + Rect rect3 = new Rect(scenPartRect.x, (float)(scenPartRect.y + scenPartRect.height * 2.0 / 3.0), scenPartRect.width, (float)(scenPartRect.height / 3.0)); if (Widgets.ButtonText(rect, this.thingDef.LabelCap, true, false, true)) { List list = new List(); - foreach (ThingDef current in from t in this.PossibleThingDefs() + foreach (ThingDef item in from t in this.PossibleThingDefs() orderby t.label select t) { - ThingDef localTd = current; - list.Add(new FloatMenuOption(localTd.LabelCap, delegate + ThingDef localTd = item; + list.Add(new FloatMenuOption(localTd.LabelCap, (Action)delegate { this.thingDef = localTd; this.stuff = GenStuff.DefaultStuffFor(localTd); @@ -65,12 +65,12 @@ orderby t.label if (this.thingDef.MadeFromStuff && Widgets.ButtonText(rect2, this.stuff.LabelCap, true, false, true)) { List list2 = new List(); - foreach (ThingDef current2 in from t in GenStuff.AllowedStuffsFor(this.thingDef) + foreach (ThingDef item2 in from t in GenStuff.AllowedStuffsFor(this.thingDef) orderby t.label select t) { - ThingDef localSd = current2; - list2.Add(new FloatMenuOption(localSd.LabelCap, delegate + ThingDef localSd = item2; + list2.Add(new FloatMenuOption(localSd.LabelCap, (Action)delegate { this.stuff = localSd; }, MenuOptionPriority.Default, null, null, 0f, null, null)); @@ -93,9 +93,24 @@ public override bool TryMerge(ScenPart other) protected virtual IEnumerable PossibleThingDefs() { - return from d in DefDatabase.AllDefs - where (d.category == ThingCategory.Item && d.scatterableOnMapGen && !d.destroyOnDrop) || (d.category == ThingCategory.Building && d.Minifiable) || (d.category == ThingCategory.Building && d.scatterableOnMapGen) - select d; + return DefDatabase.AllDefs.Where((Func)delegate(ThingDef d) + { + if (d.category == ThingCategory.Item && d.scatterableOnMapGen && !d.destroyOnDrop) + { + goto IL_0050; + } + if (d.category == ThingCategory.Building && d.Minifiable) + { + goto IL_0050; + } + int result = (d.category == ThingCategory.Building && d.scatterableOnMapGen) ? 1 : 0; + goto IL_0051; + IL_0051: + return (byte)result != 0; + IL_0050: + result = 1; + goto IL_0051; + }); } } } diff --git a/Assembly-CSharp/RimWorld/ScenSummaryList.cs b/Assembly-CSharp/RimWorld/ScenSummaryList.cs index c45181be5..6431a64a7 100644 --- a/Assembly-CSharp/RimWorld/ScenSummaryList.cs +++ b/Assembly-CSharp/RimWorld/ScenSummaryList.cs @@ -1,4 +1,3 @@ -using System; using System.Text; using Verse; @@ -13,25 +12,25 @@ public static string SummaryWithList(Scenario scen, string tag, string intro) { return "\n" + intro + ":\n" + text; } - return null; + return (string)null; } private static string SummaryList(Scenario scen, string tag) { StringBuilder stringBuilder = new StringBuilder(); bool flag = true; - foreach (ScenPart current in scen.AllParts) + foreach (ScenPart allPart in scen.AllParts) { - if (!current.summarized) + if (!allPart.summarized) { - foreach (string current2 in current.GetSummaryListEntries(tag)) + foreach (string summaryListEntry in allPart.GetSummaryListEntries(tag)) { if (!flag) { stringBuilder.Append("\n"); } - stringBuilder.Append(" -" + current2); - current.summarized = true; + stringBuilder.Append(" -" + summaryListEntry); + allPart.summarized = true; flag = false; } } diff --git a/Assembly-CSharp/RimWorld/Scenario.cs b/Assembly-CSharp/RimWorld/Scenario.cs index 2bc7b4661..d2d58d929 100644 --- a/Assembly-CSharp/RimWorld/Scenario.cs +++ b/Assembly-CSharp/RimWorld/Scenario.cs @@ -1,7 +1,6 @@ using Steamworks; using System; using System.Collections.Generic; -using System.Diagnostics; using System.IO; using System.Linq; using System.Text; @@ -52,11 +51,11 @@ public IEnumerable AllParts { get { - Scenario.<>c__Iterator125 <>c__Iterator = new Scenario.<>c__Iterator125(); - <>c__Iterator.<>f__this = this; - Scenario.<>c__Iterator125 expr_0E = <>c__Iterator; - expr_0E.$PC = -2; - return expr_0E; + yield return (ScenPart)this.playerFaction; + for (int i = 0; i < this.parts.Count; i++) + { + yield return this.parts[i]; + } } } @@ -78,55 +77,72 @@ public ScenarioCategory Category public void ExposeData() { - Scribe_Values.Look(ref this.name, "name", null, false); - Scribe_Values.Look(ref this.summary, "summary", null, false); - Scribe_Values.Look(ref this.description, "description", null, false); + Scribe_Values.Look(ref this.name, "name", (string)null, false); + Scribe_Values.Look(ref this.summary, "summary", (string)null, false); + Scribe_Values.Look(ref this.description, "description", (string)null, false); Scribe_Values.Look(ref this.publishedFileIdInt, "publishedFileId", PublishedFileId_t.Invalid, false); Scribe_Deep.Look(ref this.playerFaction, "playerFaction", new object[0]); Scribe_Collections.Look(ref this.parts, "parts", LookMode.Deep, new object[0]); } - [DebuggerHidden] public IEnumerable ConfigErrors() { - Scenario.c__Iterator126 c__Iterator = new Scenario.c__Iterator126(); - c__Iterator.<>f__this = this; - Scenario.c__Iterator126 expr_0E = c__Iterator; - expr_0E.$PC = -2; - return expr_0E; + if (this.name.NullOrEmpty()) + { + yield return "no title"; + } + if (this.parts.NullOrEmpty()) + { + yield return "no parts"; + } + if (this.playerFaction == null) + { + yield return "no playerFaction"; + } + foreach (ScenPart allPart in this.AllParts) + { + foreach (string item in allPart.ConfigErrors()) + { + yield return item; + } + } } public string GetFullInformationText() { - string result; try { StringBuilder stringBuilder = new StringBuilder(); stringBuilder.AppendLine(this.description); stringBuilder.AppendLine(); - foreach (ScenPart current in this.AllParts) + foreach (ScenPart allPart in this.AllParts) { - current.summarized = false; + allPart.summarized = false; } - foreach (ScenPart current2 in from p in this.AllParts + foreach (ScenPart item in from p in this.AllParts orderby p.def.summaryPriority descending, p.def.defName where p.visible select p) { - string text = current2.Summary(this); + string text = item.Summary(this); if (!text.NullOrEmpty()) { stringBuilder.AppendLine(text); } } - result = stringBuilder.ToString().TrimEndNewlines(); + return stringBuilder.ToString().TrimEndNewlines(); + IL_0122: + string result; + return result; } catch (Exception ex) { Log.ErrorOnce("Exception in Scenario.GetFullInformationText():\n" + ex.ToString(), 10395878); - result = "Cannot read data."; + return "Cannot read data."; + IL_0150: + string result; + return result; } - return result; } public string GetSummary() @@ -149,9 +165,9 @@ public Scenario CopyForEditing() public void PreConfigure() { - foreach (ScenPart current in this.AllParts) + foreach (ScenPart allPart in this.AllParts) { - current.PreConfigure(); + allPart.PreConfigure(); } } @@ -161,9 +177,9 @@ public Page GetFirstConfigPage() list.Add(new Page_SelectStoryteller()); list.Add(new Page_CreateWorldParams()); list.Add(new Page_SelectLandingSite()); - foreach (Page current in this.parts.SelectMany((ScenPart p) => p.GetConfigPages())) + foreach (Page item in this.parts.SelectMany((Func>)((ScenPart p) => p.GetConfigPages()))) { - list.Add(current); + list.Add(item); } Page page = PageUtility.StitchedPages(list); if (page != null) @@ -173,7 +189,7 @@ public Page GetFirstConfigPage() { page2 = page2.next; } - page2.nextAct = delegate + page2.nextAct = (Action)delegate { PageUtility.InitGameStart(); }; @@ -183,9 +199,9 @@ public Page GetFirstConfigPage() public bool AllowPlayerStartingPawn(Pawn pawn) { - foreach (ScenPart current in this.AllParts) + foreach (ScenPart allPart in this.AllParts) { - if (!current.AllowPlayerStartingPawn(pawn)) + if (!allPart.AllowPlayerStartingPawn(pawn)) { return false; } @@ -195,9 +211,9 @@ public bool AllowPlayerStartingPawn(Pawn pawn) public void Notify_PawnGenerated(Pawn pawn, PawnGenerationContext context) { - foreach (ScenPart current in this.AllParts) + foreach (ScenPart allPart in this.AllParts) { - current.Notify_PawnGenerated(pawn, context); + allPart.Notify_PawnGenerated(pawn, context); } } @@ -211,41 +227,41 @@ public void Notify_PawnDied(Corpse corpse) public void PostWorldGenerate() { - foreach (ScenPart current in this.AllParts) + foreach (ScenPart allPart in this.AllParts) { - current.PostWorldGenerate(); + allPart.PostWorldGenerate(); } } public void PreMapGenerate() { - foreach (ScenPart current in this.AllParts) + foreach (ScenPart allPart in this.AllParts) { - current.PreMapGenerate(); + allPart.PreMapGenerate(); } } public void GenerateIntoMap(Map map) { - foreach (ScenPart current in this.AllParts) + foreach (ScenPart allPart in this.AllParts) { - current.GenerateIntoMap(map); + allPart.GenerateIntoMap(map); } } public void PostMapGenerate(Map map) { - foreach (ScenPart current in this.AllParts) + foreach (ScenPart allPart in this.AllParts) { - current.PostMapGenerate(map); + allPart.PostMapGenerate(map); } } public void PostGameStart() { - foreach (ScenPart current in this.AllParts) + foreach (ScenPart allPart in this.AllParts) { - current.PostGameStart(); + allPart.PostGameStart(); } } @@ -287,15 +303,29 @@ public bool CanReorder(ScenPart part, ReorderDirection dir) return false; } int num = this.parts.IndexOf(part); - if (dir == ReorderDirection.Up) + switch (dir) + { + case ReorderDirection.Up: { - return num != 0 && (num <= 0 || this.parts[num - 1].def.PlayerAddRemovable); + if (num == 0) + { + return false; + } + if (num > 0 && !this.parts[num - 1].def.PlayerAddRemovable) + { + return false; + } + return true; } - if (dir == ReorderDirection.Down) + case ReorderDirection.Down: { return num != this.parts.Count - 1; } - throw new NotImplementedException(); + default: + { + throw new NotImplementedException(); + } + } } public void Reorder(ScenPart part, ReorderDirection dir) @@ -314,7 +344,19 @@ public void Reorder(ScenPart part, ReorderDirection dir) public bool CanToUploadToWorkshop() { - return this.Category != ScenarioCategory.FromDef && this.TryUploadReport().Accepted && !this.GetWorkshopItemHook().MayHaveAuthorNotCurrentUser; + if (this.Category == ScenarioCategory.FromDef) + { + return false; + } + if (!this.TryUploadReport().Accepted) + { + return false; + } + if (this.GetWorkshopItemHook().MayHaveAuthorNotCurrentUser) + { + return false; + } + return true; } public void PrepareForWorkshopUpload() @@ -327,18 +369,18 @@ public void PrepareForWorkshopUpload() directoryInfo.Delete(); } directoryInfo.Create(); - string text = Path.Combine(this.tempUploadDir, this.name); - text += ".rsc"; - GameDataSaveLoader.SaveScenario(this, text); + string str = Path.Combine(this.tempUploadDir, this.name); + str += ".rsc"; + GameDataSaveLoader.SaveScenario(this, str); } public AcceptanceReport TryUploadReport() { - if (this.name == null || this.name.Length < 3 || this.summary == null || this.summary.Length < 3 || this.description == null || this.description.Length < 3) + if (this.name != null && this.name.Length >= 3 && this.summary != null && this.summary.Length >= 3 && this.description != null && this.description.Length >= 3) { - return "TextFieldsMustBeFilled".Translate(); + return AcceptanceReport.WasAccepted; } - return AcceptanceReport.WasAccepted; + return "TextFieldsMustBeFilled".Translate(); } public PublishedFileId_t GetPublishedFileId() @@ -372,10 +414,9 @@ public string GetWorkshopPreviewImagePath() public IList GetWorkshopTags() { - return new List - { - "Scenario" - }; + List list = new List(); + list.Add("Scenario"); + return list; } public DirectoryInfo GetWorkshopUploadDirectory() diff --git a/Assembly-CSharp/RimWorld/ScenarioCategory.cs b/Assembly-CSharp/RimWorld/ScenarioCategory.cs index f8054213f..791203e93 100644 --- a/Assembly-CSharp/RimWorld/ScenarioCategory.cs +++ b/Assembly-CSharp/RimWorld/ScenarioCategory.cs @@ -1,12 +1,10 @@ -using System; - namespace RimWorld { public enum ScenarioCategory { - Undefined, - FromDef, - CustomLocal, - SteamWorkshop + Undefined = 0, + FromDef = 1, + CustomLocal = 2, + SteamWorkshop = 3 } } diff --git a/Assembly-CSharp/RimWorld/ScenarioDef.cs b/Assembly-CSharp/RimWorld/ScenarioDef.cs index a48daec55..79faa43a9 100644 --- a/Assembly-CSharp/RimWorld/ScenarioDef.cs +++ b/Assembly-CSharp/RimWorld/ScenarioDef.cs @@ -1,6 +1,4 @@ -using System; using System.Collections.Generic; -using System.Diagnostics; using Verse; namespace RimWorld @@ -14,23 +12,25 @@ public override void PostLoad() base.PostLoad(); if (this.scenario.name.NullOrEmpty()) { - this.scenario.name = this.label; + this.scenario.name = base.label; } if (this.scenario.description.NullOrEmpty()) { - this.scenario.description = this.description; + this.scenario.description = base.description; } this.scenario.Category = ScenarioCategory.FromDef; } - [DebuggerHidden] public override IEnumerable ConfigErrors() { - ScenarioDef.c__Iterator94 c__Iterator = new ScenarioDef.c__Iterator94(); - c__Iterator.<>f__this = this; - ScenarioDef.c__Iterator94 expr_0E = c__Iterator; - expr_0E.$PC = -2; - return expr_0E; + if (this.scenario == null) + { + yield return "null scenario"; + } + foreach (string item in this.scenario.ConfigErrors()) + { + yield return item; + } } } } diff --git a/Assembly-CSharp/RimWorld/ScenarioDefOf.cs b/Assembly-CSharp/RimWorld/ScenarioDefOf.cs index edefce551..ae1899ba7 100644 --- a/Assembly-CSharp/RimWorld/ScenarioDefOf.cs +++ b/Assembly-CSharp/RimWorld/ScenarioDefOf.cs @@ -1,5 +1,3 @@ -using System; - namespace RimWorld { [DefOf] diff --git a/Assembly-CSharp/RimWorld/ScenarioFiles.cs b/Assembly-CSharp/RimWorld/ScenarioFiles.cs index 6a4d65c68..6869296f1 100644 --- a/Assembly-CSharp/RimWorld/ScenarioFiles.cs +++ b/Assembly-CSharp/RimWorld/ScenarioFiles.cs @@ -1,4 +1,3 @@ -using System; using System.Collections.Generic; using System.IO; using Verse; @@ -31,18 +30,18 @@ public static IEnumerable AllScenariosWorkshop public static void RecacheData() { ScenarioFiles.scenariosLocal.Clear(); - foreach (FileInfo current in GenFilePaths.AllCustomScenarioFiles) + foreach (FileInfo allCustomScenarioFile in GenFilePaths.AllCustomScenarioFiles) { - Scenario item; - if (GameDataSaveLoader.TryLoadScenario(current.FullName, ScenarioCategory.CustomLocal, out item)) + Scenario item = default(Scenario); + if (GameDataSaveLoader.TryLoadScenario(allCustomScenarioFile.FullName, ScenarioCategory.CustomLocal, out item)) { ScenarioFiles.scenariosLocal.Add(item); } } ScenarioFiles.scenariosWorkshop.Clear(); - foreach (WorkshopItem current2 in WorkshopItems.AllSubscribedItems) + foreach (WorkshopItem allSubscribedItem in WorkshopItems.AllSubscribedItems) { - WorkshopItem_Scenario workshopItem_Scenario = current2 as WorkshopItem_Scenario; + WorkshopItem_Scenario workshopItem_Scenario = allSubscribedItem as WorkshopItem_Scenario; if (workshopItem_Scenario != null) { ScenarioFiles.scenariosWorkshop.Add(workshopItem_Scenario.GetScenario()); diff --git a/Assembly-CSharp/RimWorld/ScenarioLister.cs b/Assembly-CSharp/RimWorld/ScenarioLister.cs index 95c3da182..e6d2ac068 100644 --- a/Assembly-CSharp/RimWorld/ScenarioLister.cs +++ b/Assembly-CSharp/RimWorld/ScenarioLister.cs @@ -1,6 +1,4 @@ -using System; using System.Collections.Generic; -using System.Diagnostics; using Verse; namespace RimWorld @@ -9,43 +7,70 @@ public static class ScenarioLister { private static bool dirty = true; - [DebuggerHidden] public static IEnumerable AllScenarios() { - ScenarioLister.c__Iterator127 c__Iterator = new ScenarioLister.c__Iterator127(); - ScenarioLister.c__Iterator127 expr_07 = c__Iterator; - expr_07.$PC = -2; - return expr_07; + ScenarioLister.RecacheIfDirty(); + foreach (ScenarioDef allDef in DefDatabase.AllDefs) + { + yield return allDef.scenario; + } + foreach (Scenario item in ScenarioFiles.AllScenariosLocal) + { + yield return item; + } + foreach (Scenario item2 in ScenarioFiles.AllScenariosWorkshop) + { + yield return item2; + } } - [DebuggerHidden] public static IEnumerable ScenariosInCategory(ScenarioCategory cat) { - ScenarioLister.c__Iterator128 c__Iterator = new ScenarioLister.c__Iterator128(); - c__Iterator.cat = cat; - c__Iterator.<$>cat = cat; - ScenarioLister.c__Iterator128 expr_15 = c__Iterator; - expr_15.$PC = -2; - return expr_15; + ScenarioLister.RecacheIfDirty(); + switch (cat) + { + case ScenarioCategory.FromDef: + { + foreach (ScenarioDef allDef in DefDatabase.AllDefs) + { + yield return allDef.scenario; + } + break; + } + case ScenarioCategory.CustomLocal: + { + foreach (Scenario item in ScenarioFiles.AllScenariosLocal) + { + yield return item; + } + break; + } + case ScenarioCategory.SteamWorkshop: + { + foreach (Scenario item2 in ScenarioFiles.AllScenariosWorkshop) + { + yield return item2; + } + break; + } + } } public static bool ScenarioIsListedAnywhere(Scenario scen) { ScenarioLister.RecacheIfDirty(); - foreach (ScenarioDef current in DefDatabase.AllDefs) + foreach (ScenarioDef allDef in DefDatabase.AllDefs) { - if (current.scenario == scen) + if (allDef.scenario == scen) { - bool result = true; - return result; + return true; } } - foreach (Scenario current2 in ScenarioFiles.AllScenariosLocal) + foreach (Scenario item in ScenarioFiles.AllScenariosLocal) { - if (scen == current2) + if (scen == item) { - bool result = true; - return result; + return true; } } return false; @@ -82,9 +107,9 @@ private static void RecacheData() public static int ScenarioListHash() { int num = 9826121; - foreach (Scenario current in ScenarioLister.AllScenarios()) + foreach (Scenario item in ScenarioLister.AllScenarios()) { - num ^= 791 * current.GetHashCode() * 6121; + num ^= 791 * item.GetHashCode() * 6121; } return num; } diff --git a/Assembly-CSharp/RimWorld/ScenarioMaker.cs b/Assembly-CSharp/RimWorld/ScenarioMaker.cs index 00943b708..b50234f2d 100644 --- a/Assembly-CSharp/RimWorld/ScenarioMaker.cs +++ b/Assembly-CSharp/RimWorld/ScenarioMaker.cs @@ -1,6 +1,5 @@ using System; using System.Collections.Generic; -using System.Diagnostics; using System.Linq; using Verse; @@ -31,9 +30,9 @@ public static Scenario GenerateNewRandomScenario(string seed) int int2 = Rand.Int; ScenarioMaker.scen = new Scenario(); ScenarioMaker.scen.Category = ScenarioCategory.CustomLocal; - ScenarioMaker.scen.name = NameGenerator.GenerateName(RulePackDefOf.NamerScenario, null, false); - ScenarioMaker.scen.description = null; - ScenarioMaker.scen.summary = null; + ScenarioMaker.scen.name = NameGenerator.GenerateName(RulePackDefOf.NamerScenario, (Predicate)null, false); + ScenarioMaker.scen.description = (string)null; + ScenarioMaker.scen.summary = (string)null; Rand.Seed = @int; ScenarioMaker.scen.playerFaction = (ScenPart_PlayerFaction)ScenarioMaker.MakeScenPart(ScenPartDefOf.PlayerFaction); ScenarioMaker.scen.parts.Add(ScenarioMaker.MakeScenPart(ScenPartDefOf.ConfigPage_ConfigureStartingPawns)); @@ -53,24 +52,21 @@ public static Scenario GenerateNewRandomScenario(string seed) Rand.Seed = array[6]; ScenarioMaker.AddCategoryScenParts(ScenarioMaker.scen, ScenPartCategory.GameCondition, Rand.RangeInclusive(-1, 2)); Rand.Seed = int2; - foreach (ScenPart current in ScenarioMaker.scen.AllParts) + foreach (ScenPart allPart in ScenarioMaker.scen.AllParts) { - current.Randomize(); + allPart.Randomize(); } for (int j = 0; j < ScenarioMaker.scen.parts.Count; j++) { for (int k = 0; k < ScenarioMaker.scen.parts.Count; k++) { - if (j != k) + if (j != k && ScenarioMaker.scen.parts[j].TryMerge(ScenarioMaker.scen.parts[k])) { - if (ScenarioMaker.scen.parts[j].TryMerge(ScenarioMaker.scen.parts[k])) + ScenarioMaker.scen.parts.RemoveAt(k); + k--; + if (j > k) { - ScenarioMaker.scen.parts.RemoveAt(k); - k--; - if (j > k) - { - j--; - } + j--; } } } @@ -79,23 +75,20 @@ public static Scenario GenerateNewRandomScenario(string seed) { for (int m = 0; m < ScenarioMaker.scen.parts.Count; m++) { - if (l != m) + if (l != m && !ScenarioMaker.scen.parts[l].CanCoexistWith(ScenarioMaker.scen.parts[m])) { - if (!ScenarioMaker.scen.parts[l].CanCoexistWith(ScenarioMaker.scen.parts[m])) + ScenarioMaker.scen.parts.RemoveAt(m); + m--; + if (l > m) { - ScenarioMaker.scen.parts.RemoveAt(m); - m--; - if (l > m) - { - l--; - } + l--; } } } } - foreach (string current2 in ScenarioMaker.scen.ConfigErrors()) + foreach (string item in ScenarioMaker.scen.ConfigErrors()) { - Log.Error(current2); + Log.Error(item); } Rand.PopState(); Scenario result = ScenarioMaker.scen; @@ -108,25 +101,41 @@ private static void AddCategoryScenParts(Scenario scen, ScenPartCategory cat, in scen.parts.AddRange(ScenarioMaker.RandomScenPartsOfCategory(scen, cat, count)); } - [DebuggerHidden] private static IEnumerable RandomScenPartsOfCategory(Scenario scen, ScenPartCategory cat, int count) { - ScenarioMaker.c__Iterator129 c__Iterator = new ScenarioMaker.c__Iterator129(); - c__Iterator.count = count; - c__Iterator.scen = scen; - c__Iterator.cat = cat; - c__Iterator.<$>count = count; - c__Iterator.<$>scen = scen; - c__Iterator.<$>cat = cat; - ScenarioMaker.c__Iterator129 expr_31 = c__Iterator; - expr_31.$PC = -2; - return expr_31; + if (count > 0) + { + IEnumerable allowedParts = from d in ScenarioMaker.AddableParts(scen) + where d.category == ((_003CRandomScenPartsOfCategory_003Ec__Iterator129)/*Error near IL_003e: stateMachine*/).cat + select d; + int numYielded = 0; + int numTries = 0; + while (true) + { + if (numYielded < count && allowedParts.Any()) + { + ScenPartDef def = allowedParts.RandomElementByWeight((Func)((ScenPartDef d) => d.selectionWeight)); + ScenPart newPart = ScenarioMaker.MakeScenPart(def); + if (ScenarioMaker.CanAddPart(scen, newPart)) + { + yield return newPart; + numYielded++; + } + numTries++; + if (numTries > 100) + break; + continue; + } + yield break; + } + Log.Error("Could not add ScenPart of category " + cat + " to scenario " + scen + " after 50 tries."); + } } public static IEnumerable AddableParts(Scenario scen) { return from d in DefDatabase.AllDefs - where scen.AllParts.Count((ScenPart p) => p.def == d) < d.maxUses + where scen.AllParts.Count((Func)((ScenPart p) => p.def == d)) < d.maxUses select d; } diff --git a/Assembly-CSharp/RimWorld/ScenarioUI.cs b/Assembly-CSharp/RimWorld/ScenarioUI.cs index f1a629eeb..6e2d6117d 100644 --- a/Assembly-CSharp/RimWorld/ScenarioUI.cs +++ b/Assembly-CSharp/RimWorld/ScenarioUI.cs @@ -1,4 +1,3 @@ -using System; using UnityEngine; using Verse; @@ -12,52 +11,50 @@ public static void DrawScenarioInfo(Rect rect, Scenario scen, ref Vector2 infoSc { Widgets.DrawMenuSection(rect, true); rect = rect.GetInnerRect(); - if (scen == null) + if (scen != null) { - return; + string fullInformationText = scen.GetFullInformationText(); + float width = (float)(rect.width - 16.0); + float height = (float)(30.0 + Text.CalcHeight(fullInformationText, width) + 100.0); + Rect viewRect = new Rect(0f, 0f, width, height); + Widgets.BeginScrollView(rect, ref infoScrollPosition, viewRect, true); + Text.Font = GameFont.Medium; + Rect rect2 = new Rect(0f, 0f, viewRect.width, 30f); + Widgets.Label(rect2, scen.name); + Text.Font = GameFont.Small; + Rect rect3 = new Rect(0f, 30f, viewRect.width, (float)(viewRect.height - 30.0)); + Widgets.Label(rect3, fullInformationText); + Widgets.EndScrollView(); } - string fullInformationText = scen.GetFullInformationText(); - float width = rect.width - 16f; - float height = 30f + Text.CalcHeight(fullInformationText, width) + 100f; - Rect viewRect = new Rect(0f, 0f, width, height); - Widgets.BeginScrollView(rect, ref infoScrollPosition, viewRect, true); - Text.Font = GameFont.Medium; - Rect rect2 = new Rect(0f, 0f, viewRect.width, 30f); - Widgets.Label(rect2, scen.name); - Text.Font = GameFont.Small; - Rect rect3 = new Rect(0f, 30f, viewRect.width, viewRect.height - 30f); - Widgets.Label(rect3, fullInformationText); - Widgets.EndScrollView(); } public static void DrawScenarioEditInterface(Rect rect, Scenario scen, ref Vector2 infoScrollPosition) { Widgets.DrawMenuSection(rect, true); rect = rect.GetInnerRect(); - if (scen == null) + if (scen != null) { - return; + Rect viewRect = new Rect(0f, 0f, (float)(rect.width - 16.0), ScenarioUI.editViewHeight); + Widgets.BeginScrollView(rect, ref infoScrollPosition, viewRect, true); + Rect rect2 = new Rect(0f, 0f, viewRect.width, 99999f); + Listing_ScenEdit listing_ScenEdit = new Listing_ScenEdit(scen); + listing_ScenEdit.ColumnWidth = rect2.width; + listing_ScenEdit.Begin(rect2); + listing_ScenEdit.Label("Title".Translate(), -1f); + scen.name = listing_ScenEdit.TextEntry(scen.name, 1).TrimmedToLength(55); + listing_ScenEdit.Label("Summary".Translate(), -1f); + scen.summary = listing_ScenEdit.TextEntry(scen.summary, 2).TrimmedToLength(300); + listing_ScenEdit.Label("Description".Translate(), -1f); + scen.description = listing_ScenEdit.TextEntry(scen.description, 4).TrimmedToLength(1000); + listing_ScenEdit.Gap(12f); + foreach (ScenPart allPart in scen.AllParts) + { + allPart.DoEditInterface(listing_ScenEdit); + } + listing_ScenEdit.End(); + ScenarioUI.editViewHeight = (float)(listing_ScenEdit.CurHeight + 100.0); + Widgets.EndScrollView(); } - Rect viewRect = new Rect(0f, 0f, rect.width - 16f, ScenarioUI.editViewHeight); - Widgets.BeginScrollView(rect, ref infoScrollPosition, viewRect, true); - Rect rect2 = new Rect(0f, 0f, viewRect.width, 99999f); - Listing_ScenEdit listing_ScenEdit = new Listing_ScenEdit(scen); - listing_ScenEdit.ColumnWidth = rect2.width; - listing_ScenEdit.Begin(rect2); - listing_ScenEdit.Label("Title".Translate(), -1f); - scen.name = listing_ScenEdit.TextEntry(scen.name, 1).TrimmedToLength(55); - listing_ScenEdit.Label("Summary".Translate(), -1f); - scen.summary = listing_ScenEdit.TextEntry(scen.summary, 2).TrimmedToLength(300); - listing_ScenEdit.Label("Description".Translate(), -1f); - scen.description = listing_ScenEdit.TextEntry(scen.description, 4).TrimmedToLength(1000); - listing_ScenEdit.Gap(12f); - foreach (ScenPart current in scen.AllParts) - { - current.DoEditInterface(listing_ScenEdit); - } - listing_ScenEdit.End(); - ScenarioUI.editViewHeight = listing_ScenEdit.CurHeight + 100f; - Widgets.EndScrollView(); } } } diff --git a/Assembly-CSharp/RimWorld/Screen_Credits.cs b/Assembly-CSharp/RimWorld/Screen_Credits.cs index 45dedaa3a..61c4ef340 100644 --- a/Assembly-CSharp/RimWorld/Screen_Credits.cs +++ b/Assembly-CSharp/RimWorld/Screen_Credits.cs @@ -62,7 +62,7 @@ private float ViewHeight { GameFont font = Text.Font; Text.Font = GameFont.Medium; - float result = this.creds.Sum((CreditsEntry c) => c.DrawHeight(this.ViewWidth)) + 20f; + float result = (float)(this.creds.Sum((Func)((CreditsEntry c) => c.DrawHeight(this.ViewWidth))) + 20.0); Text.Font = font; return result; } @@ -72,7 +72,7 @@ private float MaxScrollPosition { get { - return Mathf.Max(this.ViewHeight - (float)UI.screenHeight / 2f, 0f); + return Mathf.Max((float)(this.ViewHeight - (float)UI.screenHeight / 2.0), 0f); } } @@ -82,7 +82,7 @@ private float AutoScrollRate { if (this.wonGame) { - float num = SongDefOf.EndCreditsSong.clip.length + 5f - 6f; + float num = (float)(SongDefOf.EndCreditsSong.clip.length + 5.0 - 6.0); return this.MaxScrollPosition / num; } return 30f; @@ -95,12 +95,12 @@ public Screen_Credits() : this(string.Empty) public Screen_Credits(string preCreditsMessage) { - this.doWindowBackground = false; - this.doCloseButton = false; - this.doCloseX = false; - this.closeOnEscapeKey = true; - this.forcePause = true; - this.creds = CreditsAssembler.AllCredits().ToList(); + base.doWindowBackground = false; + base.doCloseButton = false; + base.doCloseX = false; + base.closeOnEscapeKey = true; + base.forcePause = true; + this.creds = CreditsAssembler.AllCredits().ToList(); this.creds.Insert(0, new CreditRecord_Space(100f)); if (!preCreditsMessage.NullOrEmpty()) { @@ -129,7 +129,7 @@ public override void PreOpen() public override void WindowUpdate() { base.WindowUpdate(); - if (this.timeUntilAutoScroll > 0f) + if (this.timeUntilAutoScroll > 0.0) { this.timeUntilAutoScroll -= Time.deltaTime; } @@ -137,7 +137,7 @@ public override void WindowUpdate() { this.scrollPosition += this.AutoScrollRate * Time.deltaTime; } - if (this.wonGame && !this.playedMusic && Time.realtimeSinceStartup > this.creationRealtime + 5f) + if (this.wonGame && !this.playedMusic && Time.realtimeSinceStartup > this.creationRealtime + 5.0) { Find.MusicManagerPlay.ForceStartSong(SongDefOf.EndCreditsSong, true); this.playedMusic = true; @@ -151,7 +151,8 @@ public override void DoWindowContents(Rect inRect) Rect position = new Rect(rect); position.yMin += 30f; position.yMax -= 30f; - position.xMin = rect.center.x - 400f; + Vector2 center = rect.center; + position.xMin = (float)(center.x - 400.0); position.width = 800f; float viewWidth = this.ViewWidth; float viewHeight = this.ViewHeight; @@ -162,18 +163,28 @@ public override void DoWindowContents(Rect inRect) GUI.BeginGroup(position2); Text.Font = GameFont.Medium; float num = 0f; - foreach (CreditsEntry current in this.creds) + List.Enumerator enumerator = this.creds.GetEnumerator(); + try { - float num2 = current.DrawHeight(position2.width); - Rect rect2 = new Rect(0f, num, position2.width, num2); - current.Draw(rect2); - num += num2; + while (enumerator.MoveNext()) + { + CreditsEntry current = enumerator.Current; + float num2 = current.DrawHeight(position2.width); + Rect rect2 = new Rect(0f, num, position2.width, num2); + current.Draw(rect2); + num += num2; + } + } + finally + { + ((IDisposable)(object)enumerator).Dispose(); } GUI.EndGroup(); GUI.EndGroup(); if (Event.current.type == EventType.ScrollWheel) { - this.Scroll(Event.current.delta.y * 25f); + Vector2 delta = Event.current.delta; + this.Scroll((float)(delta.y * 25.0)); Event.current.Use(); } if (Event.current.type == EventType.KeyDown) diff --git a/Assembly-CSharp/RimWorld/Season.cs b/Assembly-CSharp/RimWorld/Season.cs index 7ab9bc4c4..7e92aeecb 100644 --- a/Assembly-CSharp/RimWorld/Season.cs +++ b/Assembly-CSharp/RimWorld/Season.cs @@ -1,13 +1,11 @@ -using System; - namespace RimWorld { public enum Season : byte { - Undefined, - Spring, - Summer, - Fall, - Winter + Undefined = 0, + Spring = 1, + Summer = 2, + Fall = 3, + Winter = 4 } } diff --git a/Assembly-CSharp/RimWorld/SeasonUtility.cs b/Assembly-CSharp/RimWorld/SeasonUtility.cs index 6a714aaec..f11e6b627 100644 --- a/Assembly-CSharp/RimWorld/SeasonUtility.cs +++ b/Assembly-CSharp/RimWorld/SeasonUtility.cs @@ -1,4 +1,3 @@ -using System; using System.Collections.Generic; using UnityEngine; using Verse; @@ -17,66 +16,98 @@ public static Season FirstSeason public static Twelfth GetFirstTwelfth(this Season season, float latitude) { - if (latitude >= 0f) + if (latitude >= 0.0) { switch (season) { case Season.Spring: + { return Twelfth.First; + } case Season.Summer: + { return Twelfth.Fourth; + } case Season.Fall: + { return Twelfth.Seventh; + } case Season.Winter: + { return Twelfth.Tenth; } + } } else { switch (season) { - case Season.Spring: - return Twelfth.Seventh; - case Season.Summer: - return Twelfth.Tenth; case Season.Fall: + { return Twelfth.First; + } case Season.Winter: + { return Twelfth.Fourth; } + case Season.Spring: + { + return Twelfth.Seventh; + } + case Season.Summer: + { + return Twelfth.Tenth; + } + } } return Twelfth.Undefined; } public static Twelfth GetMiddleTwelfth(this Season season, float latitude) { - if (latitude >= 0f) + if (latitude >= 0.0) { switch (season) { case Season.Spring: + { return Twelfth.Second; + } case Season.Summer: + { return Twelfth.Fifth; + } case Season.Fall: + { return Twelfth.Eighth; + } case Season.Winter: + { return Twelfth.Eleventh; } + } } else { switch (season) { - case Season.Spring: - return Twelfth.Eighth; - case Season.Summer: - return Twelfth.Eleventh; case Season.Fall: + { return Twelfth.Second; + } case Season.Winter: + { return Twelfth.Fifth; } + case Season.Spring: + { + return Twelfth.Eighth; + } + case Season.Summer: + { + return Twelfth.Eleventh; + } + } } return Twelfth.Undefined; } @@ -86,18 +117,30 @@ public static Season GetPreviousSeason(this Season season) switch (season) { case Season.Undefined: + { return Season.Undefined; + } case Season.Spring: + { return Season.Winter; + } case Season.Summer: + { return Season.Spring; + } case Season.Fall: + { return Season.Summer; + } case Season.Winter: + { return Season.Fall; + } default: + { return Season.Undefined; } + } } public static float GetMiddleYearPct(this Season season, float latitude) @@ -107,7 +150,7 @@ public static float GetMiddleYearPct(this Season season, float latitude) return 0.5f; } Twelfth middleTwelfth = season.GetMiddleTwelfth(latitude); - return ((float)middleTwelfth + 0.5f) / 12f; + return (float)(((float)(int)middleTwelfth + 0.5) / 12.0); } public static string Label(this Season season) @@ -115,16 +158,26 @@ public static string Label(this Season season) switch (season) { case Season.Spring: + { return "SeasonSpring".Translate(); + } case Season.Summer: + { return "SeasonSummer".Translate(); + } case Season.Fall: + { return "SeasonFall".Translate(); + } case Season.Winter: + { return "SeasonWinter".Translate(); + } default: + { return "Unknown season"; } + } } public static string LabelCap(this Season season) @@ -145,7 +198,7 @@ public static string SeasonsRangeLabel(List twelfths, Vector2 longLat) string text = string.Empty; for (int i = 0; i < 12; i++) { - Twelfth twelfth = (Twelfth)i; + Twelfth twelfth = (Twelfth)(byte)i; if (twelfths.Contains(twelfth)) { if (!text.NullOrEmpty()) @@ -162,23 +215,17 @@ private static string SeasonsContinuousRangeLabel(List twelfths, Twelft { Twelfth leftMostTwelfth = TwelfthUtility.GetLeftMostTwelfth(twelfths, rootTwelfth); Twelfth rightMostTwelfth = TwelfthUtility.GetRightMostTwelfth(twelfths, rootTwelfth); - for (Twelfth twelfth = leftMostTwelfth; twelfth != rightMostTwelfth; twelfth = TwelfthUtility.TwelfthAfter(twelfth)) + Twelfth twelfth = leftMostTwelfth; + while (twelfth != rightMostTwelfth) { - if (!twelfths.Contains(twelfth)) + if (twelfths.Contains(twelfth)) { - Log.Error(string.Concat(new object[] - { - "Twelfths doesn't contain ", - twelfth, - " (", - leftMostTwelfth, - "..", - rightMostTwelfth, - ")" - })); - break; - } - twelfths.Remove(twelfth); + twelfths.Remove(twelfth); + twelfth = TwelfthUtility.TwelfthAfter(twelfth); + continue; + } + Log.Error("Twelfths doesn't contain " + twelfth + " (" + leftMostTwelfth + ".." + rightMostTwelfth + ")"); + break; } twelfths.Remove(rightMostTwelfth); return GenDate.SeasonDateStringAt(leftMostTwelfth, longLat) + " - " + GenDate.SeasonDateStringAt(rightMostTwelfth, longLat); diff --git a/Assembly-CSharp/RimWorld/SectionLayerPhaseDefOf.cs b/Assembly-CSharp/RimWorld/SectionLayerPhaseDefOf.cs index ce667a4d8..b812fb9f6 100644 --- a/Assembly-CSharp/RimWorld/SectionLayerPhaseDefOf.cs +++ b/Assembly-CSharp/RimWorld/SectionLayerPhaseDefOf.cs @@ -1,4 +1,3 @@ -using System; using Verse; namespace RimWorld diff --git a/Assembly-CSharp/RimWorld/SectionLayer_ThingsPowerGrid.cs b/Assembly-CSharp/RimWorld/SectionLayer_ThingsPowerGrid.cs index 58c8c58e5..a9f837a18 100644 --- a/Assembly-CSharp/RimWorld/SectionLayer_ThingsPowerGrid.cs +++ b/Assembly-CSharp/RimWorld/SectionLayer_ThingsPowerGrid.cs @@ -1,4 +1,3 @@ -using System; using Verse; namespace RimWorld @@ -7,8 +6,8 @@ public class SectionLayer_ThingsPowerGrid : SectionLayer_Things { public SectionLayer_ThingsPowerGrid(Section section) : base(section) { - this.requireAddToMapMesh = false; - this.relevantChangeTypes = MapMeshFlag.PowerGrid; + base.requireAddToMapMesh = false; + base.relevantChangeTypes = MapMeshFlag.PowerGrid; } public override void DrawLayer() diff --git a/Assembly-CSharp/RimWorld/SeedTargFindMode.cs b/Assembly-CSharp/RimWorld/SeedTargFindMode.cs index 08227c5b4..b18b49137 100644 --- a/Assembly-CSharp/RimWorld/SeedTargFindMode.cs +++ b/Assembly-CSharp/RimWorld/SeedTargFindMode.cs @@ -1,11 +1,9 @@ -using System; - namespace RimWorld { public enum SeedTargFindMode : byte { - MapGenCluster, - Reproduce, - MapEdge + MapGenCluster = 0, + Reproduce = 1, + MapEdge = 2 } } diff --git a/Assembly-CSharp/RimWorld/SelectionDrawer.cs b/Assembly-CSharp/RimWorld/SelectionDrawer.cs index 679b14015..5d3d76280 100644 --- a/Assembly-CSharp/RimWorld/SelectionDrawer.cs +++ b/Assembly-CSharp/RimWorld/SelectionDrawer.cs @@ -34,15 +34,24 @@ public static void Clear() public static void DrawSelectionOverlays() { - foreach (object current in Find.Selector.SelectedObjects) + List.Enumerator enumerator = Find.Selector.SelectedObjects.GetEnumerator(); + try { - SelectionDrawer.DrawSelectionBracketFor(current); - Thing thing = current as Thing; - if (thing != null) + while (enumerator.MoveNext()) { - thing.DrawExtraSelectionOverlays(); + object current = enumerator.Current; + SelectionDrawer.DrawSelectionBracketFor(current); + Thing thing = current as Thing; + if (thing != null) + { + thing.DrawExtraSelectionOverlays(); + } } } + finally + { + ((IDisposable)(object)enumerator).Dispose(); + } } private static void DrawSelectionBracketFor(object obj) @@ -55,7 +64,7 @@ private static void DrawSelectionBracketFor(object obj) Thing thing = obj as Thing; if (thing != null) { - SelectionDrawerUtility.CalculateSelectionBracketPositionsWorld(SelectionDrawer.bracketLocs, thing, thing.DrawPos, thing.RotatedSize.ToVector2(), SelectionDrawer.selectTimes, Vector2.one, 1f); + SelectionDrawerUtility.CalculateSelectionBracketPositionsWorld(SelectionDrawer.bracketLocs, thing, thing.DrawPos, thing.RotatedSize.ToVector2(), SelectionDrawer.selectTimes, Vector2.one, 1f); int num = 0; for (int i = 0; i < 4; i++) { diff --git a/Assembly-CSharp/RimWorld/SelectionDrawerUtility.cs b/Assembly-CSharp/RimWorld/SelectionDrawerUtility.cs index 09930c3c2..9d65439bf 100644 --- a/Assembly-CSharp/RimWorld/SelectionDrawerUtility.cs +++ b/Assembly-CSharp/RimWorld/SelectionDrawerUtility.cs @@ -1,4 +1,3 @@ -using System; using System.Collections.Generic; using UnityEngine; using Verse; @@ -16,40 +15,40 @@ public static class SelectionDrawerUtility public static void CalculateSelectionBracketPositionsUI(Vector2[] bracketLocs, T obj, Rect rect, Dictionary selectTimes, Vector2 textureSize, float jumpDistanceFactor = 1f) { - float num; - float num2; - if (!selectTimes.TryGetValue(obj, out num)) - { - num2 = 1f; - } - else - { - num2 = Mathf.Max(0f, 1f - (Time.realtimeSinceStartup - num) / 0.07f); - } - float num3 = num2 * 0.2f * jumpDistanceFactor; - float num4 = 0.5f * (rect.width - textureSize.x) + num3; - float num5 = 0.5f * (rect.height - textureSize.y) + num3; - bracketLocs[0] = new Vector2(rect.center.x - num4, rect.center.y - num5); - bracketLocs[1] = new Vector2(rect.center.x + num4, rect.center.y - num5); - bracketLocs[2] = new Vector2(rect.center.x + num4, rect.center.y + num5); - bracketLocs[3] = new Vector2(rect.center.x - num4, rect.center.y + num5); + float num = default(float); + float num2 = (float)(selectTimes.TryGetValue(obj, out num) ? Mathf.Max(0f, (float)(1.0 - (Time.realtimeSinceStartup - num) / 0.070000000298023224)) : 1.0); + float num3 = (float)(num2 * 0.20000000298023224 * jumpDistanceFactor); + float num4 = (float)(0.5 * (rect.width - textureSize.x) + num3); + float num5 = (float)(0.5 * (rect.height - textureSize.y) + num3); + ref Vector2 val = ref bracketLocs[0]; + Vector2 center = rect.center; + float x = center.x - num4; + Vector2 center2 = rect.center; + val = new Vector2(x, center2.y - num5); + ref Vector2 val2 = ref bracketLocs[1]; + Vector2 center3 = rect.center; + float x2 = center3.x + num4; + Vector2 center4 = rect.center; + val2 = new Vector2(x2, center4.y - num5); + ref Vector2 val3 = ref bracketLocs[2]; + Vector2 center5 = rect.center; + float x3 = center5.x + num4; + Vector2 center6 = rect.center; + val3 = new Vector2(x3, center6.y + num5); + ref Vector2 val4 = ref bracketLocs[3]; + Vector2 center7 = rect.center; + float x4 = center7.x - num4; + Vector2 center8 = rect.center; + val4 = new Vector2(x4, center8.y + num5); } public static void CalculateSelectionBracketPositionsWorld(Vector3[] bracketLocs, T obj, Vector3 worldPos, Vector2 worldSize, Dictionary selectTimes, Vector2 textureSize, float jumpDistanceFactor = 1f) { - float num; - float num2; - if (!selectTimes.TryGetValue(obj, out num)) - { - num2 = 1f; - } - else - { - num2 = Mathf.Max(0f, 1f - (Time.realtimeSinceStartup - num) / 0.07f); - } - float num3 = num2 * 0.2f * jumpDistanceFactor; - float num4 = 0.5f * (worldSize.x - textureSize.x) + num3; - float num5 = 0.5f * (worldSize.y - textureSize.y) + num3; + float num = default(float); + float num2 = (float)(selectTimes.TryGetValue(obj, out num) ? Mathf.Max(0f, (float)(1.0 - (Time.realtimeSinceStartup - num) / 0.070000000298023224)) : 1.0); + float num3 = (float)(num2 * 0.20000000298023224 * jumpDistanceFactor); + float num4 = (float)(0.5 * (worldSize.x - textureSize.x) + num3); + float num5 = (float)(0.5 * (worldSize.y - textureSize.y) + num3); float y = Altitudes.AltitudeFor(AltitudeLayer.MetaOverlays); bracketLocs[0] = new Vector3(worldPos.x - num4, y, worldPos.z - num5); bracketLocs[1] = new Vector3(worldPos.x + num4, y, worldPos.z - num5); diff --git a/Assembly-CSharp/RimWorld/Selector.cs b/Assembly-CSharp/RimWorld/Selector.cs index 428403ab9..036ad6d0c 100644 --- a/Assembly-CSharp/RimWorld/Selector.cs +++ b/Assembly-CSharp/RimWorld/Selector.cs @@ -2,7 +2,6 @@ using System; using System.Collections; using System.Collections.Generic; -using System.Diagnostics; using System.Linq; using UnityEngine; using Verse; @@ -205,66 +204,67 @@ public void Select(object obj, bool playSound = true, bool forceDesignatorDesele if (obj == null) { Log.Error("Cannot select null."); - return; } - Thing thing = obj as Thing; - if (thing == null && !(obj is Zone)) - { - Log.Error("Tried to select " + obj + " which is neither a Thing nor a Zone."); - return; - } - if (thing != null && thing.Destroyed) - { - Log.Error("Cannot select destroyed thing."); - return; - } - Pawn pawn = obj as Pawn; - if (pawn != null && pawn.IsWorldPawn()) - { - Log.Error("Cannot select world pawns."); - return; - } - if (forceDesignatorDeselect) - { - Find.DesignatorManager.Deselect(); - } - if (this.SelectedZone != null && !(obj is Zone)) - { - this.ClearSelection(); - } - if (obj is Zone && this.SelectedZone == null) - { - this.ClearSelection(); - } - Map map = (thing == null) ? ((Zone)obj).Map : thing.Map; - for (int i = this.selected.Count - 1; i >= 0; i--) + else { - Thing thing2 = this.selected[i] as Thing; - Map map2 = (thing2 == null) ? ((Zone)this.selected[i]).Map : thing2.Map; - if (map2 != map) + Thing thing = obj as Thing; + if (thing == null && !(obj is Zone)) { - this.Deselect(this.selected[i]); + Log.Error("Tried to select " + obj + " which is neither a Thing nor a Zone."); } - } - if (this.selected.Count >= 80) - { - return; - } - if (!this.IsSelected(obj)) - { - if (map != Current.Game.VisibleMap) + else if (thing != null && thing.Destroyed) { - Current.Game.VisibleMap = map; - SoundDefOf.MapSelected.PlayOneShotOnCamera(null); - IntVec3 cell = (thing == null) ? ((Zone)obj).Cells[0] : thing.Position; - Find.CameraDriver.JumpToVisibleMapLoc(cell); + Log.Error("Cannot select destroyed thing."); } - if (playSound) + else { - this.PlaySelectionSoundFor(obj); + Pawn pawn = obj as Pawn; + if (pawn != null && pawn.IsWorldPawn()) + { + Log.Error("Cannot select world pawns."); + } + else + { + if (forceDesignatorDeselect) + { + Find.DesignatorManager.Deselect(); + } + if (this.SelectedZone != null && !(obj is Zone)) + { + this.ClearSelection(); + } + if (obj is Zone && this.SelectedZone == null) + { + this.ClearSelection(); + } + Map map = (thing == null) ? ((Zone)obj).Map : thing.Map; + for (int num = this.selected.Count - 1; num >= 0; num--) + { + Thing thing2 = this.selected[num] as Thing; + Map map2 = (thing2 == null) ? ((Zone)this.selected[num]).Map : thing2.Map; + if (map2 != map) + { + this.Deselect(this.selected[num]); + } + } + if (this.selected.Count < 80 && !this.IsSelected(obj)) + { + if (map != Current.Game.VisibleMap) + { + Current.Game.VisibleMap = map; + SoundDefOf.MapSelected.PlayOneShotOnCamera(null); + IntVec3 cell = (thing == null) ? ((Zone)obj).Cells[0] : thing.Position; + Find.CameraDriver.JumpToVisibleMapLoc(cell); + } + if (playSound) + { + this.PlaySelectionSoundFor(obj); + } + this.selected.Add(obj); + SelectionDrawer.Notify_Selected(obj); + } + } } - this.selected.Add(obj); - SelectionDrawer.Notify_Selected(obj); } } @@ -306,96 +306,132 @@ private void SelectInsideDragBox() selectedSomething = true; this.Select(list[i], true, true); } - if (selectedSomething) - { - return; - } - List list2 = Find.ColonistBar.CaravanMembersCaravansInScreenRect(this.dragBox.ScreenRect); - for (int j = 0; j < list2.Count; j++) + if (!selectedSomething) { - if (!selectedSomething) + List list2 = Find.ColonistBar.CaravanMembersCaravansInScreenRect(this.dragBox.ScreenRect); + for (int j = 0; j < list2.Count; j++) { - CameraJumper.TryJumpAndSelect(list2[j]); - selectedSomething = true; + if (!selectedSomething) + { + CameraJumper.TryJumpAndSelect((WorldObject)list2[j]); + selectedSomething = true; + } + else + { + Find.WorldSelector.Select(list2[j], true); + } } - else + if (!selectedSomething) { - Find.WorldSelector.Select(list2[j], true); + List boxThings = ThingSelectionUtility.MultiSelectableThingsInScreenRectDistinct(this.dragBox.ScreenRect).ToList(); + Func, bool> func = (Func, bool>)delegate(Predicate predicate) + { + foreach (Thing item in from t in boxThings + where predicate(t) + select t) + { + this.Select(item, true, true); + selectedSomething = true; + } + return selectedSomething; + }; + Predicate arg = (Predicate)((Thing t) => t.def.category == ThingCategory.Pawn && ((Pawn)t).RaceProps.Humanlike && t.Faction == Faction.OfPlayer); + if (!func(arg)) + { + Predicate arg2 = (Predicate)((Thing t) => t.def.category == ThingCategory.Pawn && ((Pawn)t).RaceProps.Humanlike); + if (!func(arg2)) + { + Predicate arg3 = (Predicate)((Thing t) => t.def.CountAsResource); + if (!func(arg3)) + { + Predicate arg4 = (Predicate)((Thing t) => t.def.category == ThingCategory.Pawn); + if (!func(arg4) && !func((Predicate)((Thing t) => t.def.selectable))) + { + List list3 = ThingSelectionUtility.MultiSelectableZonesInScreenRectDistinct(this.dragBox.ScreenRect).ToList(); + List.Enumerator enumerator = list3.GetEnumerator(); + try + { + while (enumerator.MoveNext()) + { + Zone current = enumerator.Current; + selectedSomething = true; + this.Select(current, true, true); + } + } + finally + { + ((IDisposable)(object)enumerator).Dispose(); + } + if (!selectedSomething) + { + this.SelectUnderMouse(); + } + } + } + } + } } } - if (selectedSomething) + } + + private IEnumerable SelectableObjectsUnderMouse() + { + Vector2 mousePos = UI.MousePositionOnUIInverted; + Thing colonistOrCorpse = Find.ColonistBar.ColonistOrCorpseAt(mousePos); + if (colonistOrCorpse != null && colonistOrCorpse.Spawned) { - return; + yield return (object)colonistOrCorpse; } - List boxThings = ThingSelectionUtility.MultiSelectableThingsInScreenRectDistinct(this.dragBox.ScreenRect).ToList(); - Func, bool> func = delegate(Predicate predicate) + else if (UI.MouseCell().InBounds(Find.VisibleMap)) { - foreach (Thing current2 in from t in boxThings - where predicate(t) - select t) + TargetingParameters selectParams = new TargetingParameters + { + mustBeSelectable = true, + canTargetPawns = true, + canTargetBuildings = true, + canTargetItems = true, + mapObjectTargetsMustBeAutoAttackable = false + }; + List selectableList = GenUI.ThingsUnderMouse(UI.MouseMapPosition(), 1f, selectParams); + if (selectableList.Count > 0 && selectableList[0] is Pawn && (selectableList[0].DrawPos - UI.MouseMapPosition()).MagnitudeHorizontal() < 0.40000000596046448) { - this.Select(current2, true, true); - selectedSomething = true; + for (int j = selectableList.Count - 1; j >= 0; j--) + { + Thing t = selectableList[j]; + if (t.def.category == ThingCategory.Pawn && (t.DrawPos - UI.MouseMapPosition()).MagnitudeHorizontal() > 0.40000000596046448) + { + selectableList.Remove(t); + } + } + } + for (int i = 0; i < selectableList.Count; i++) + { + yield return (object)selectableList[i]; + } + Zone z = Find.VisibleMap.zoneManager.ZoneAt(UI.MouseCell()); + if (z != null) + { + yield return (object)z; } - return selectedSomething; - }; - Predicate arg = (Thing t) => t.def.category == ThingCategory.Pawn && ((Pawn)t).RaceProps.Humanlike && t.Faction == Faction.OfPlayer; - if (func(arg)) - { - return; - } - Predicate arg2 = (Thing t) => t.def.category == ThingCategory.Pawn && ((Pawn)t).RaceProps.Humanlike; - if (func(arg2)) - { - return; - } - Predicate arg3 = (Thing t) => t.def.CountAsResource; - if (func(arg3)) - { - return; - } - Predicate arg4 = (Thing t) => t.def.category == ThingCategory.Pawn; - if (func(arg4)) - { - return; - } - if (func((Thing t) => t.def.selectable)) - { - return; - } - List list3 = ThingSelectionUtility.MultiSelectableZonesInScreenRectDistinct(this.dragBox.ScreenRect).ToList(); - foreach (Zone current in list3) - { - selectedSomething = true; - this.Select(current, true, true); - } - if (selectedSomething) - { - return; } - this.SelectUnderMouse(); } - [DebuggerHidden] - private IEnumerable SelectableObjectsUnderMouse() - { - Selector.c__Iterator1A2 c__Iterator1A = new Selector.c__Iterator1A2(); - Selector.c__Iterator1A2 expr_07 = c__Iterator1A; - expr_07.$PC = -2; - return expr_07; - } - - [DebuggerHidden] public static IEnumerable SelectableObjectsAt(IntVec3 c, Map map) { - Selector.c__Iterator1A3 c__Iterator1A = new Selector.c__Iterator1A3(); - c__Iterator1A.c = c; - c__Iterator1A.map = map; - c__Iterator1A.<$>c = c; - c__Iterator1A.<$>map = map; - Selector.c__Iterator1A3 expr_23 = c__Iterator1A; - expr_23.$PC = -2; - return expr_23; + List thingList = c.GetThingList(map); + for (int i = 0; i < thingList.Count; i++) + { + Thing t = thingList[i]; + if (ThingSelectionUtility.SelectableByMapClick(t)) + { + yield return (object)t; + } + } + Zone z = map.zoneManager.ZoneAt(c); + if (z != null) + { + yield return (object)z; + } } private void SelectUnderMouse() @@ -403,168 +439,197 @@ private void SelectUnderMouse() Caravan caravan = Find.ColonistBar.CaravanMemberCaravanAt(UI.MousePositionOnUIInverted); if (caravan != null) { - CameraJumper.TryJumpAndSelect(caravan); - return; - } - Thing thing = Find.ColonistBar.ColonistOrCorpseAt(UI.MousePositionOnUIInverted); - if (thing != null && !thing.Spawned) - { - CameraJumper.TryJump(thing); - return; + CameraJumper.TryJumpAndSelect((WorldObject)caravan); } - List list = this.SelectableObjectsUnderMouse().ToList(); - if (list.Count == 0) - { - if (!this.ShiftIsHeld) - { - this.ClearSelection(); - } - } - else if (list.Count == 1) + else { - object obj3 = list[0]; - if (!this.ShiftIsHeld) + Thing thing = Find.ColonistBar.ColonistOrCorpseAt(UI.MousePositionOnUIInverted); + if (thing != null && !thing.Spawned) { - this.ClearSelection(); - this.Select(obj3, true, true); - } - else if (!this.selected.Contains(obj3)) - { - this.Select(obj3, true, true); + CameraJumper.TryJump(thing); } else { - this.Deselect(obj3); - } - } - else if (list.Count > 1) - { - object obj2 = (from obj in list - where this.selected.Contains(obj) - select obj).FirstOrDefault(); - if (obj2 != null) - { - if (!this.ShiftIsHeld) + List list = this.SelectableObjectsUnderMouse().ToList(); + if (list.Count == 0) { - int num = list.IndexOf(obj2) + 1; - if (num >= list.Count) + if (!this.ShiftIsHeld) { - num -= list.Count; + this.ClearSelection(); } - this.ClearSelection(); - this.Select(list[num], true, true); } - else + else if (list.Count == 1) { - foreach (object current in list) + object obj2 = list[0]; + if (!this.ShiftIsHeld) { - if (this.selected.Contains(current)) - { - this.Deselect(current); - } + this.ClearSelection(); + this.Select(obj2, true, true); + } + else if (!this.selected.Contains(obj2)) + { + this.Select(obj2, true, true); + } + else + { + this.Deselect(obj2); } } - } - else - { - if (!this.ShiftIsHeld) + else if (list.Count > 1) { - this.ClearSelection(); + object obj3 = (from obj in list + where this.selected.Contains(obj) + select obj).FirstOrDefault(); + if (obj3 != null) + { + if (!this.ShiftIsHeld) + { + int num = list.IndexOf(obj3) + 1; + if (num >= list.Count) + { + num -= list.Count; + } + this.ClearSelection(); + this.Select(list[num], true, true); + } + else + { + List.Enumerator enumerator = list.GetEnumerator(); + try + { + while (enumerator.MoveNext()) + { + object current = enumerator.Current; + if (this.selected.Contains(current)) + { + this.Deselect(current); + } + } + } + finally + { + ((IDisposable)(object)enumerator).Dispose(); + } + } + } + else + { + if (!this.ShiftIsHeld) + { + this.ClearSelection(); + } + this.Select(list[0], true, true); + } } - this.Select(list[0], true, true); } } } public void SelectNextAt(IntVec3 c, Map map) { - if (this.SelectedObjects.Count() != 1) + if (this.SelectedObjects.Count() != 1) { Log.Error("Cannot select next at with < or > 1 selected."); - return; } - List list = Selector.SelectableObjectsAt(c, map).ToList(); - int num = list.IndexOf(this.SingleSelectedThing) + 1; - if (num >= list.Count) + else { - num -= list.Count; + List list = Selector.SelectableObjectsAt(c, map).ToList(); + int num = list.IndexOf(this.SingleSelectedThing) + 1; + if (num >= list.Count) + { + num -= list.Count; + } + this.ClearSelection(); + this.Select(list[num], true, true); } - this.ClearSelection(); - this.Select(list[num], true, true); } private void SelectAllMatchingObjectUnderMouseOnScreen() { - List list = this.SelectableObjectsUnderMouse().ToList(); - if (list.Count == 0) - { - return; - } - Thing clickedThing = list.FirstOrDefault((object o) => o is Pawn && ((Pawn)o).Faction == Faction.OfPlayer && !((Pawn)o).IsPrisoner) as Thing; - clickedThing = (list.FirstOrDefault((object o) => o is Pawn) as Thing); - if (clickedThing == null) + List list = this.SelectableObjectsUnderMouse().ToList(); + if (list.Count != 0) { - clickedThing = ((from o in list - where o is Thing && !((Thing)o).def.neverMultiSelect - select o).FirstOrDefault() as Thing); - } - Rect rect = new Rect(0f, 0f, (float)UI.screenWidth, (float)UI.screenHeight); - if (clickedThing != null) - { - IEnumerable enumerable = ThingSelectionUtility.MultiSelectableThingsInScreenRectDistinct(rect); - Predicate predicate = delegate(Thing t) + Thing clickedThing = list.FirstOrDefault((Func)((object o) => o is Pawn && ((Pawn)o).Faction == Faction.OfPlayer && !((Pawn)o).IsPrisoner)) as Thing; + clickedThing = (list.FirstOrDefault((Func)((object o) => o is Pawn)) as Thing); + if (clickedThing == null) { - if (t.def != clickedThing.def || t.Faction != clickedThing.Faction || this.IsSelected(t)) + clickedThing = ((from o in list + where o is Thing && !((Thing)o).def.neverMultiSelect + select o).FirstOrDefault() as Thing); + } + Rect rect = new Rect(0f, 0f, (float)UI.screenWidth, (float)UI.screenHeight); + if (clickedThing == null) + { + object obj = list.FirstOrDefault((Func)((object o) => o is Zone && ((Zone)o).IsMultiselectable)); + if (obj != null) { - return false; + IEnumerable enumerable = ThingSelectionUtility.MultiSelectableZonesInScreenRectDistinct(rect); + foreach (Zone item in enumerable) + { + if (!this.IsSelected(item)) + { + this.Select(item, true, true); + } + } } - Pawn pawn = clickedThing as Pawn; - if (pawn != null) + } + else + { + IEnumerable enumerable2 = ThingSelectionUtility.MultiSelectableThingsInScreenRectDistinct(rect); + Predicate predicate = (Predicate)delegate(Thing t) { - Pawn pawn2 = t as Pawn; - if (pawn2.RaceProps != pawn.RaceProps) + if (t.def == clickedThing.def && t.Faction == clickedThing.Faction && !this.IsSelected(t)) { - return false; + Pawn pawn = clickedThing as Pawn; + if (pawn != null) + { + Pawn pawn2 = t as Pawn; + if (pawn2.RaceProps != pawn.RaceProps) + { + return false; + } + if (pawn2.HostFaction != pawn.HostFaction) + { + return false; + } + } + return true; } - if (pawn2.HostFaction != pawn.HostFaction) + return false; + }; + foreach (Thing item2 in enumerable2) + { + if (predicate(item2)) { - return false; + this.Select(item2, true, true); } } - return true; - }; - foreach (Thing obj in enumerable) - { - if (predicate(obj)) - { - this.Select(obj, true, true); - } - } - return; - } - if (list.FirstOrDefault((object o) => o is Zone && ((Zone)o).IsMultiselectable) == null) - { - return; - } - IEnumerable enumerable2 = ThingSelectionUtility.MultiSelectableZonesInScreenRectDistinct(rect); - foreach (Zone current in enumerable2) - { - if (!this.IsSelected(current)) - { - this.Select(current, true, true); } } } private static void AutoOrderToCell(Pawn pawn, IntVec3 dest) { - foreach (FloatMenuOption current in FloatMenuMakerMap.ChoicesAtFor(dest.ToVector3Shifted(), pawn)) + List.Enumerator enumerator = FloatMenuMakerMap.ChoicesAtFor(dest.ToVector3Shifted(), pawn).GetEnumerator(); + try { - if (current.autoTakeable) + FloatMenuOption current; + while (true) { - current.Chosen(true); - break; + if (enumerator.MoveNext()) + { + current = enumerator.Current; + if (current.autoTakeable) + break; + continue; + } + return; } + current.Chosen(true); + } + finally + { + ((IDisposable)(object)enumerator).Dispose(); } } } diff --git a/Assembly-CSharp/RimWorld/SelfDefenseUtility.cs b/Assembly-CSharp/RimWorld/SelfDefenseUtility.cs index e6b580a02..9e5f6faff 100644 --- a/Assembly-CSharp/RimWorld/SelfDefenseUtility.cs +++ b/Assembly-CSharp/RimWorld/SelfDefenseUtility.cs @@ -1,4 +1,3 @@ -using System; using System.Collections.Generic; using Verse; using Verse.AI; @@ -17,12 +16,12 @@ public static bool ShouldStartFleeing(Pawn pawn) { return false; } - RegionTraverser.BreadthFirstTraverse(region, (Region from, Region reg) => reg.portal == null || reg.portal.Open, delegate(Region reg) + RegionTraverser.BreadthFirstTraverse(region, (RegionEntryPredicate)((Region from, Region reg) => reg.portal == null || reg.portal.Open), (RegionProcessor)delegate(Region reg) { List list = reg.ListerThings.ThingsInGroup(ThingRequestGroup.AttackTarget); for (int i = 0; i < list.Count; i++) { - if (list[i] != pawn && (float)list[i].Position.DistanceToSquared(pawn.Position) < 64f && list[i].HostileTo(pawn) && !((IAttackTarget)list[i]).ThreatDisabled() && GenSight.LineOfSight(pawn.Position, list[i].Position, pawn.Map, false, null, 0, 0)) + if (list[i] != pawn && (float)list[i].Position.DistanceToSquared(pawn.Position) < 64.0 && list[i].HostileTo(pawn) && !((IAttackTarget)list[i]).ThreatDisabled() && GenSight.LineOfSight(pawn.Position, list[i].Position, pawn.Map, false, null, 0, 0)) { foundThreat = true; } diff --git a/Assembly-CSharp/RimWorld/ShieldBelt.cs b/Assembly-CSharp/RimWorld/ShieldBelt.cs index 20391c513..ca72f9c02 100644 --- a/Assembly-CSharp/RimWorld/ShieldBelt.cs +++ b/Assembly-CSharp/RimWorld/ShieldBelt.cs @@ -1,6 +1,4 @@ -using System; using System.Collections.Generic; -using System.Diagnostics; using UnityEngine; using Verse; using Verse.AI; @@ -53,7 +51,7 @@ private float EnergyGainPerTick { get { - return this.GetStatValue(StatDefOf.EnergyShieldRechargeRate, true) / 60f; + return (float)(this.GetStatValue(StatDefOf.EnergyShieldRechargeRate, true) / 60.0); } } @@ -82,7 +80,27 @@ private bool ShouldDisplay get { Pawn wearer = base.Wearer; - return !wearer.Dead && !wearer.Downed && (!wearer.IsPrisonerOfColony || (wearer.MentalStateDef != null && wearer.MentalStateDef.IsAggro)) && (wearer.Drafted || wearer.Faction.HostileTo(Faction.OfPlayer) || Find.TickManager.TicksGame < this.lastKeepDisplayTick + this.KeepDisplayingTicks); + if (!wearer.Dead && !wearer.Downed) + { + if (wearer.IsPrisonerOfColony && (wearer.MentalStateDef == null || !wearer.MentalStateDef.IsAggro)) + { + return false; + } + if (wearer.Drafted) + { + return true; + } + if (wearer.Faction.HostileTo(Faction.OfPlayer)) + { + return true; + } + if (Find.TickManager.TicksGame < this.lastKeepDisplayTick + this.KeepDisplayingTicks) + { + return true; + } + return false; + } + return false; } } @@ -94,14 +112,15 @@ public override void ExposeData() Scribe_Values.Look(ref this.lastKeepDisplayTick, "lastKeepDisplayTick", 0, false); } - [DebuggerHidden] public override IEnumerable GetWornGizmos() { - ShieldBelt.c__Iterator161 c__Iterator = new ShieldBelt.c__Iterator161(); - c__Iterator.<>f__this = this; - ShieldBelt.c__Iterator161 expr_0E = c__Iterator; - expr_0E.$PC = -2; - return expr_0E; + if (Find.Selector.SingleSelectedThing == base.Wearer) + { + yield return (Gizmo)new Gizmo_EnergyShieldStatus + { + shield = this + }; + } } public override float GetSpecialApparelScoreOffset() @@ -115,9 +134,8 @@ public override void Tick() if (base.Wearer == null) { this.energy = 0f; - return; } - if (this.ShieldState == ShieldState.Resetting) + else if (this.ShieldState == ShieldState.Resetting) { this.ticksToReset--; if (this.ticksToReset <= 0) @@ -137,32 +155,39 @@ public override void Tick() public override bool CheckPreAbsorbDamage(DamageInfo dinfo) { - if (this.ShieldState == ShieldState.Active && ((dinfo.Instigator != null && !dinfo.Instigator.Position.AdjacentTo8WayOrInside(base.Wearer.Position)) || dinfo.Def.isExplosive)) + if (this.ShieldState == ShieldState.Active) { - if (dinfo.Instigator != null) + if (dinfo.Instigator != null && !dinfo.Instigator.Position.AdjacentTo8WayOrInside(base.Wearer.Position)) { - AttachableThing attachableThing = dinfo.Instigator as AttachableThing; - if (attachableThing != null && attachableThing.parent == base.Wearer) - { - return false; - } - } - this.energy -= (float)dinfo.Amount * this.EnergyLossPerDamage; - if (dinfo.Def == DamageDefOf.EMP) - { - this.energy = -1f; - } - if (this.energy < 0f) - { - this.Break(); + goto IL_0049; } - else + if (dinfo.Def.isExplosive) + goto IL_0049; + } + return false; + IL_0049: + if (dinfo.Instigator != null) + { + AttachableThing attachableThing = dinfo.Instigator as AttachableThing; + if (attachableThing != null && attachableThing.parent == base.Wearer) { - this.AbsorbedDamage(dinfo); + return false; } - return true; } - return false; + this.energy -= (float)dinfo.Amount * this.EnergyLossPerDamage; + if (dinfo.Def == DamageDefOf.EMP) + { + this.energy = -1f; + } + if (this.energy < 0.0) + { + this.Break(); + } + else + { + this.AbsorbedDamage(dinfo); + } + return true; } public void KeepDisplaying() @@ -175,10 +200,10 @@ private void AbsorbedDamage(DamageInfo dinfo) SoundDefOf.EnergyShieldAbsorbDamage.PlayOneShot(new TargetInfo(base.Wearer.Position, base.Wearer.Map, false)); this.impactAngleVect = Vector3Utility.HorizontalVectorFromAngle(dinfo.Angle); Vector3 loc = base.Wearer.TrueCenter() + this.impactAngleVect.RotatedBy(180f) * 0.5f; - float num = Mathf.Min(10f, 2f + (float)dinfo.Amount / 10f); + float num = Mathf.Min(10f, (float)(2.0 + (float)dinfo.Amount / 10.0)); MoteMaker.MakeStaticMote(loc, base.Wearer.Map, ThingDefOf.Mote_ExplosionFlash, num); int num2 = (int)num; - for (int i = 0; i < num2; i++) + for (int num3 = 0; num3 < num2; num3++) { MoteMaker.ThrowDustPuff(loc, base.Wearer.Map, Rand.Range(0.8f, 1.2f)); } @@ -220,7 +245,7 @@ public override void DrawWornExtras() int num2 = Find.TickManager.TicksGame - this.lastAbsorbDamageTick; if (num2 < 8) { - float num3 = (float)(8 - num2) / 8f * 0.05f; + float num3 = (float)((float)(8 - num2) / 8.0 * 0.05000000074505806); vector += this.impactAngleVect * num3; num -= num3; } diff --git a/Assembly-CSharp/RimWorld/ShieldState.cs b/Assembly-CSharp/RimWorld/ShieldState.cs index d9f9e7f72..5ef9e806e 100644 --- a/Assembly-CSharp/RimWorld/ShieldState.cs +++ b/Assembly-CSharp/RimWorld/ShieldState.cs @@ -1,10 +1,8 @@ -using System; - namespace RimWorld { public enum ShieldState : byte { - Active, - Resetting + Active = 0, + Resetting = 1 } } diff --git a/Assembly-CSharp/RimWorld/ShipChunkDropCellFinder.cs b/Assembly-CSharp/RimWorld/ShipChunkDropCellFinder.cs index 2b21a07e7..9f55d62ca 100644 --- a/Assembly-CSharp/RimWorld/ShipChunkDropCellFinder.cs +++ b/Assembly-CSharp/RimWorld/ShipChunkDropCellFinder.cs @@ -9,30 +9,28 @@ public static class ShipChunkDropCellFinder public static bool TryFindShipChunkDropCell(IntVec3 nearLoc, Map map, int maxDist, out IntVec3 pos) { ThingDef chunkDef = ThingDefOf.ShipChunk; - return CellFinder.TryFindRandomCellNear(nearLoc, map, maxDist, delegate(IntVec3 x) + return CellFinder.TryFindRandomCellNear(nearLoc, map, maxDist, (Predicate)delegate(IntVec3 x) { - foreach (IntVec3 current in GenAdj.OccupiedRect(x, Rot4.North, chunkDef.size)) + foreach (IntVec3 item in GenAdj.OccupiedRect(x, Rot4.North, chunkDef.size)) { - if (!current.InBounds(map) || current.Fogged(map) || !current.Standable(map) || (current.Roofed(map) && current.GetRoof(map).isThickRoof)) + if (item.InBounds(map) && !item.Fogged(map) && item.Standable(map) && (!item.Roofed(map) || !item.GetRoof(map).isThickRoof)) { - bool result = false; - return result; - } - if (!current.SupportsStructureType(map, chunkDef.terrainAffordanceNeeded)) - { - bool result = false; - return result; - } - List thingList = current.GetThingList(map); - for (int i = 0; i < thingList.Count; i++) - { - Thing thing = thingList[i]; - if (thing.def.category != ThingCategory.Plant && thing.def.category != ThingCategory.Filth && GenSpawn.SpawningWipes(chunkDef, thing.def)) + if (!item.SupportsStructureType(map, chunkDef.terrainAffordanceNeeded)) + { + return false; + } + List thingList = item.GetThingList(map); + for (int i = 0; i < thingList.Count; i++) { - bool result = false; - return result; + Thing thing = thingList[i]; + if (thing.def.category != ThingCategory.Plant && thing.def.category != ThingCategory.Filth && GenSpawn.SpawningWipes(chunkDef, thing.def)) + { + return false; + } } + continue; } + return false; } return true; }, out pos); diff --git a/Assembly-CSharp/RimWorld/ShipCountdown.cs b/Assembly-CSharp/RimWorld/ShipCountdown.cs index 14b29c13a..a87be7566 100644 --- a/Assembly-CSharp/RimWorld/ShipCountdown.cs +++ b/Assembly-CSharp/RimWorld/ShipCountdown.cs @@ -25,7 +25,7 @@ public static bool CountingDown { get { - return ShipCountdown.timeLeft >= 0f; + return ShipCountdown.timeLeft >= 0.0; } } @@ -40,10 +40,10 @@ public static void InitiateCountdown(Building launchingShipRoot, int journeyDest public static void ShipCountdownUpdate() { - if (ShipCountdown.timeLeft > 0f) + if (ShipCountdown.timeLeft > 0.0) { ShipCountdown.timeLeft -= Time.deltaTime; - if (ShipCountdown.timeLeft <= 0f) + if (ShipCountdown.timeLeft <= 0.0) { ShipCountdown.CountdownEnded(); } @@ -79,32 +79,33 @@ private static void CountdownEnded() { Find.WorldObjects.Remove(worldObject); } - string victoryText = "GameOverArrivedAtJourneyDestination".Translate(new object[] - { - stringBuilder.ToString(), - GameVictoryUtility.PawnsLeftBehind() - }); + string victoryText = "GameOverArrivedAtJourneyDestination".Translate(stringBuilder.ToString(), GameVictoryUtility.PawnsLeftBehind()); GameVictoryUtility.ShowCredits(victoryText); } else { - List list = ShipUtility.ShipBuildingsAttachedTo(ShipCountdown.shipRoot).ToList(); + List list = ShipUtility.ShipBuildingsAttachedTo(ShipCountdown.shipRoot).ToList(); StringBuilder stringBuilder2 = new StringBuilder(); - foreach (Building current in list) + List.Enumerator enumerator = list.GetEnumerator(); + try { - Building_CryptosleepCasket building_CryptosleepCasket = current as Building_CryptosleepCasket; - if (building_CryptosleepCasket != null && building_CryptosleepCasket.HasAnyContents) + while (enumerator.MoveNext()) { - stringBuilder2.AppendLine(" " + building_CryptosleepCasket.ContainedThing.LabelCap); - Find.StoryWatcher.statsRecord.colonistsLaunched++; + Building current = enumerator.Current; + Building_CryptosleepCasket building_CryptosleepCasket = current as Building_CryptosleepCasket; + if (building_CryptosleepCasket != null && building_CryptosleepCasket.HasAnyContents) + { + stringBuilder2.AppendLine(" " + building_CryptosleepCasket.ContainedThing.LabelCap); + Find.StoryWatcher.statsRecord.colonistsLaunched++; + } + current.Destroy(DestroyMode.Vanish); } - current.Destroy(DestroyMode.Vanish); } - string victoryText2 = "GameOverShipLaunched".Translate(new object[] + finally { - stringBuilder2.ToString(), - GameVictoryUtility.PawnsLeftBehind() - }); + ((IDisposable)(object)enumerator).Dispose(); + } + string victoryText2 = "GameOverShipLaunched".Translate(stringBuilder2.ToString(), GameVictoryUtility.PawnsLeftBehind()); GameVictoryUtility.ShowCredits(victoryText2); } } diff --git a/Assembly-CSharp/RimWorld/ShipUtility.cs b/Assembly-CSharp/RimWorld/ShipUtility.cs index 987f9573e..de53ab704 100644 --- a/Assembly-CSharp/RimWorld/ShipUtility.cs +++ b/Assembly-CSharp/RimWorld/ShipUtility.cs @@ -1,6 +1,6 @@ using System; using System.Collections.Generic; -using System.Diagnostics; +using System.Linq; using Verse; namespace RimWorld @@ -11,41 +11,83 @@ public static class ShipUtility private static List openSet = new List(); - [DebuggerHidden] public static IEnumerable LaunchFailReasons(Building rootBuilding) { - ShipUtility.c__Iterator171 c__Iterator = new ShipUtility.c__Iterator171(); - c__Iterator.rootBuilding = rootBuilding; - c__Iterator.<$>rootBuilding = rootBuilding; - ShipUtility.c__Iterator171 expr_15 = c__Iterator; - expr_15.$PC = -2; - return expr_15; + List shipParts = ShipUtility.ShipBuildingsAttachedTo(rootBuilding).ToList(); + List.Enumerator enumerator = new List + { + ThingDefOf.Ship_CryptosleepCasket, + ThingDefOf.Ship_ComputerCore, + ThingDefOf.Ship_Reactor, + ThingDefOf.Ship_Engine + }.GetEnumerator(); + try + { + while (enumerator.MoveNext()) + { + ThingDef partDef = enumerator.Current; + if (!shipParts.Any((Predicate)((Building pa) => pa.def == ((_003CLaunchFailReasons_003Ec__Iterator171)/*Error near IL_00c4: stateMachine*/)._003CpartDef_003E__3))) + { + yield return "ShipReportMissingPart".Translate() + ": " + partDef.label; + } + } + } + finally + { + ((IDisposable)(object)enumerator).Dispose(); + } + bool fullPodFound = false; + List.Enumerator enumerator2 = shipParts.GetEnumerator(); + try + { + while (enumerator2.MoveNext()) + { + Building part = enumerator2.Current; + if (part.def == ThingDefOf.Ship_CryptosleepCasket) + { + Building_CryptosleepCasket pod = part as Building_CryptosleepCasket; + if (pod != null && pod.HasAnyContents) + { + fullPodFound = true; + break; + } + } + } + } + finally + { + ((IDisposable)(object)enumerator2).Dispose(); + } + if (!fullPodFound) + { + yield return "ShipReportNoFullPods".Translate(); + } } public static List ShipBuildingsAttachedTo(Building root) { - if (root == null || root.Destroyed) - { - return new List(); - } - ShipUtility.closedSet.Clear(); - ShipUtility.openSet.Clear(); - ShipUtility.openSet.Add(root); - while (ShipUtility.openSet.Count > 0) + if (root != null && !root.Destroyed) { - Building building = ShipUtility.openSet[ShipUtility.openSet.Count - 1]; - ShipUtility.openSet.Remove(building); - ShipUtility.closedSet.Add(building); - foreach (IntVec3 current in GenAdj.CellsAdjacentCardinal(building)) + ShipUtility.closedSet.Clear(); + ShipUtility.openSet.Clear(); + ShipUtility.openSet.Add(root); + while (ShipUtility.openSet.Count > 0) { - Building edifice = current.GetEdifice(building.Map); - if (edifice != null && edifice.def.building.shipPart && !ShipUtility.closedSet.Contains(edifice) && !ShipUtility.openSet.Contains(edifice)) + Building building = ShipUtility.openSet[ShipUtility.openSet.Count - 1]; + ShipUtility.openSet.Remove(building); + ShipUtility.closedSet.Add(building); + foreach (IntVec3 item in GenAdj.CellsAdjacentCardinal(building)) { - ShipUtility.openSet.Add(edifice); + Building edifice = item.GetEdifice(building.Map); + if (edifice != null && edifice.def.building.shipPart && !ShipUtility.closedSet.Contains(edifice) && !ShipUtility.openSet.Contains(edifice)) + { + ShipUtility.openSet.Add(edifice); + } } } + return ShipUtility.closedSet; } - return ShipUtility.closedSet; + return new List(); } } } diff --git a/Assembly-CSharp/RimWorld/ShortcutKeys.cs b/Assembly-CSharp/RimWorld/ShortcutKeys.cs index 68ba93eee..7f8f54379 100644 --- a/Assembly-CSharp/RimWorld/ShortcutKeys.cs +++ b/Assembly-CSharp/RimWorld/ShortcutKeys.cs @@ -1,4 +1,3 @@ -using System; using UnityEngine; using Verse; diff --git a/Assembly-CSharp/RimWorld/SickPawnVisitUtility.cs b/Assembly-CSharp/RimWorld/SickPawnVisitUtility.cs index efc831885..6e08d8d18 100644 --- a/Assembly-CSharp/RimWorld/SickPawnVisitUtility.cs +++ b/Assembly-CSharp/RimWorld/SickPawnVisitUtility.cs @@ -14,8 +14,8 @@ public static Pawn FindRandomSickPawn(Pawn pawn, JoyCategory maxPatientJoy) IEnumerable source = from x in pawn.Map.mapPawns.FreeColonistsSpawned where SickPawnVisitUtility.CanVisit(pawn, x, maxPatientJoy) select x; - Pawn result; - if (!source.TryRandomElementByWeight((Pawn x) => SickPawnVisitUtility.VisitChanceScore(pawn, x), out result)) + Pawn result = default(Pawn); + if (!source.TryRandomElementByWeight((Func)((Pawn x) => SickPawnVisitUtility.VisitChanceScore(pawn, x)), out result)) { return null; } @@ -24,12 +24,12 @@ where SickPawnVisitUtility.CanVisit(pawn, x, maxPatientJoy) public static bool CanVisit(Pawn pawn, Pawn sick, JoyCategory maxPatientJoy) { - return sick.IsColonist && !sick.Dead && pawn != sick && sick.InBed() && sick.Awake() && !sick.IsForbidden(pawn) && sick.needs.joy != null && sick.needs.joy.CurCategory <= maxPatientJoy && InteractionUtility.CanReceiveInteraction(sick) && !sick.needs.food.Starving && sick.needs.rest.CurLevel > 0.33f && pawn.CanReserveAndReach(sick, PathEndMode.InteractionCell, Danger.None, 1, -1, null, false) && !SickPawnVisitUtility.AboutToRecover(sick); + return sick.IsColonist && !sick.Dead && pawn != sick && sick.InBed() && sick.Awake() && !sick.IsForbidden(pawn) && sick.needs.joy != null && (int)sick.needs.joy.CurCategory <= (int)maxPatientJoy && InteractionUtility.CanReceiveInteraction(sick) && !sick.needs.food.Starving && sick.needs.rest.CurLevel > 0.33000001311302185 && pawn.CanReserveAndReach((Thing)sick, PathEndMode.InteractionCell, Danger.None, 1, -1, null, false) && !SickPawnVisitUtility.AboutToRecover(sick); } public static Thing FindChair(Pawn forPawn, Pawn nearPawn) { - Predicate validator = delegate(Thing x) + Predicate validator = (Predicate)delegate(Thing x) { if (!x.def.building.isSittable) { @@ -50,7 +50,7 @@ public static Thing FindChair(Pawn forPawn, Pawn nearPawn) if (x.def.rotatable) { float num = GenGeo.AngleDifferenceBetween(x.Rotation.AsAngle, (nearPawn.Position - x.Position).AngleFlat); - if (num > 95f) + if (num > 95.0) { return false; } @@ -84,7 +84,7 @@ private static bool AboutToRecover(Pawn pawn) num += hediff_Injury.Severity; } } - return num < 8f * pawn.RaceProps.baseHealthScale; + return num < 8.0 * pawn.RaceProps.baseHealthScale; } private static float VisitChanceScore(Pawn pawn, Pawn sick) diff --git a/Assembly-CSharp/RimWorld/SiegeBlueprintPlacer.cs b/Assembly-CSharp/RimWorld/SiegeBlueprintPlacer.cs index 39fe27d92..757dbd483 100644 --- a/Assembly-CSharp/RimWorld/SiegeBlueprintPlacer.cs +++ b/Assembly-CSharp/RimWorld/SiegeBlueprintPlacer.cs @@ -1,6 +1,7 @@ using System; using System.Collections.Generic; -using System.Diagnostics; +using System.Linq; +using UnityEngine; using Verse; using Verse.AI; @@ -24,21 +25,18 @@ public static class SiegeBlueprintPlacer private static readonly IntRange SandbagLengthRange = new IntRange(2, 7); - [DebuggerHidden] public static IEnumerable PlaceBlueprints(IntVec3 placeCenter, Map map, Faction placeFaction, float points) { - SiegeBlueprintPlacer.c__Iterator69 c__Iterator = new SiegeBlueprintPlacer.c__Iterator69(); - c__Iterator.placeCenter = placeCenter; - c__Iterator.placeFaction = placeFaction; - c__Iterator.map = map; - c__Iterator.points = points; - c__Iterator.<$>placeCenter = placeCenter; - c__Iterator.<$>placeFaction = placeFaction; - c__Iterator.<$>map = map; - c__Iterator.<$>points = points; - SiegeBlueprintPlacer.c__Iterator69 expr_3F = c__Iterator; - expr_3F.$PC = -2; - return expr_3F; + SiegeBlueprintPlacer.center = placeCenter; + SiegeBlueprintPlacer.faction = placeFaction; + foreach (Blueprint_Build item in SiegeBlueprintPlacer.PlaceSandbagBlueprints(map)) + { + yield return item; + } + foreach (Blueprint_Build item2 in SiegeBlueprintPlacer.PlaceArtilleryBlueprints(points, map)) + { + yield return item2; + } } private static bool CanPlaceBlueprintAt(IntVec3 root, Rot4 rot, ThingDef buildingDef, Map map) @@ -46,45 +44,69 @@ private static bool CanPlaceBlueprintAt(IntVec3 root, Rot4 rot, ThingDef buildin return GenConstruct.CanPlaceBlueprintAt(buildingDef, root, rot, map, false, null).Accepted; } - [DebuggerHidden] private static IEnumerable PlaceSandbagBlueprints(Map map) { - SiegeBlueprintPlacer.c__Iterator6A c__Iterator6A = new SiegeBlueprintPlacer.c__Iterator6A(); - c__Iterator6A.map = map; - c__Iterator6A.<$>map = map; - SiegeBlueprintPlacer.c__Iterator6A expr_15 = c__Iterator6A; - expr_15.$PC = -2; - return expr_15; + SiegeBlueprintPlacer.placedSandbagLocs.Clear(); + int numSandbags = SiegeBlueprintPlacer.NumSandbagRange.RandomInRange; + int i = 0; + while (i < numSandbags) + { + IntVec3 bagRoot = SiegeBlueprintPlacer.FindSandbagRoot(map); + if (bagRoot.IsValid) + { + Rot4 growDirA = (bagRoot.x <= SiegeBlueprintPlacer.center.x) ? Rot4.East : Rot4.West; + Rot4 growDirB = (bagRoot.z <= SiegeBlueprintPlacer.center.z) ? Rot4.North : Rot4.South; + foreach (Blueprint_Build item in SiegeBlueprintPlacer.MakeSandbagLine(bagRoot, map, growDirA, SiegeBlueprintPlacer.SandbagLengthRange.RandomInRange)) + { + yield return item; + } + bagRoot += growDirB.FacingCell; + foreach (Blueprint_Build item2 in SiegeBlueprintPlacer.MakeSandbagLine(bagRoot, map, growDirB, SiegeBlueprintPlacer.SandbagLengthRange.RandomInRange)) + { + yield return item2; + } + i++; + continue; + } + break; + } } - [DebuggerHidden] private static IEnumerable MakeSandbagLine(IntVec3 root, Map map, Rot4 growDir, int maxLength) { - SiegeBlueprintPlacer.c__Iterator6B c__Iterator6B = new SiegeBlueprintPlacer.c__Iterator6B(); - c__Iterator6B.root = root; - c__Iterator6B.maxLength = maxLength; - c__Iterator6B.map = map; - c__Iterator6B.growDir = growDir; - c__Iterator6B.<$>root = root; - c__Iterator6B.<$>maxLength = maxLength; - c__Iterator6B.<$>map = map; - c__Iterator6B.<$>growDir = growDir; - SiegeBlueprintPlacer.c__Iterator6B expr_3F = c__Iterator6B; - expr_3F.$PC = -2; - return expr_3F; + IntVec3 cur = root; + int i = 0; + while (i < maxLength && SiegeBlueprintPlacer.CanPlaceBlueprintAt(cur, Rot4.North, ThingDefOf.Sandbags, map)) + { + yield return GenConstruct.PlaceBlueprintForBuild(ThingDefOf.Sandbags, cur, map, Rot4.North, SiegeBlueprintPlacer.faction, null); + SiegeBlueprintPlacer.placedSandbagLocs.Add(cur); + cur += growDir.FacingCell; + i++; + } } - [DebuggerHidden] private static IEnumerable PlaceArtilleryBlueprints(float points, Map map) { - SiegeBlueprintPlacer.c__Iterator6C c__Iterator6C = new SiegeBlueprintPlacer.c__Iterator6C(); - c__Iterator6C.points = points; - c__Iterator6C.map = map; - c__Iterator6C.<$>points = points; - c__Iterator6C.<$>map = map; - SiegeBlueprintPlacer.c__Iterator6C expr_23 = c__Iterator6C; - expr_23.$PC = -2; - return expr_23; + IEnumerable artyDefs = from def in DefDatabase.AllDefs + where def.building != null && def.building.buildingTags.Contains("Artillery_BaseDestroyer") + select def; + int numArtillery2 = Mathf.RoundToInt((float)(points / 60.0)); + numArtillery2 = Mathf.Clamp(numArtillery2, 1, 2); + int i = 0; + while (i < numArtillery2) + { + Rot4 rot = Rot4.Random; + ThingDef artyDef = artyDefs.RandomElement(); + IntVec3 artySpot = SiegeBlueprintPlacer.FindArtySpot(artyDef, rot, map); + if (artySpot.IsValid) + { + yield return GenConstruct.PlaceBlueprintForBuild(artyDef, artySpot, map, rot, SiegeBlueprintPlacer.faction, ThingDefOf.Steel); + points = (float)(points - 60.0); + i++; + continue; + } + break; + } } private static IntVec3 FindSandbagRoot(Map map) @@ -94,38 +116,35 @@ private static IntVec3 FindSandbagRoot(Map map) CellRect cellRect2 = CellRect.CenteredOn(SiegeBlueprintPlacer.center, 8); cellRect2.ClipInsideMap(map); int num = 0; + goto IL_002d; + IL_002d: + IntVec3 randomCell; while (true) { num++; if (num > 200) { - break; + return IntVec3.Invalid; } - IntVec3 randomCell = cellRect.RandomCell; - if (!cellRect2.Contains(randomCell)) + randomCell = cellRect.RandomCell; + if (!cellRect2.Contains(randomCell) && map.reachability.CanReach(randomCell, SiegeBlueprintPlacer.center, PathEndMode.OnCell, TraverseMode.NoPassClosedDoors, Danger.Deadly) && SiegeBlueprintPlacer.CanPlaceBlueprintAt(randomCell, Rot4.North, ThingDefOf.Sandbags, map)) { - if (map.reachability.CanReach(randomCell, SiegeBlueprintPlacer.center, PathEndMode.OnCell, TraverseMode.NoPassClosedDoors, Danger.Deadly)) + bool flag = false; + for (int i = 0; i < SiegeBlueprintPlacer.placedSandbagLocs.Count; i++) { - if (SiegeBlueprintPlacer.CanPlaceBlueprintAt(randomCell, Rot4.North, ThingDefOf.Sandbags, map)) + float num2 = (float)(SiegeBlueprintPlacer.placedSandbagLocs[i] - randomCell).LengthHorizontalSquared; + if (num2 < 36.0) { - bool flag = false; - for (int i = 0; i < SiegeBlueprintPlacer.placedSandbagLocs.Count; i++) - { - float num2 = (float)(SiegeBlueprintPlacer.placedSandbagLocs[i] - randomCell).LengthHorizontalSquared; - if (num2 < 36f) - { - flag = true; - } - } - if (!flag) - { - return randomCell; - } + flag = true; } } + if (!flag) + break; } } - return IntVec3.Invalid; + return randomCell; + IL_00f7: + goto IL_002d; } private static IntVec3 FindArtySpot(ThingDef artyDef, Rot4 rot, Map map) @@ -133,26 +152,23 @@ private static IntVec3 FindArtySpot(ThingDef artyDef, Rot4 rot, Map map) CellRect cellRect = CellRect.CenteredOn(SiegeBlueprintPlacer.center, 8); cellRect.ClipInsideMap(map); int num = 0; + goto IL_0017; + IL_0017: + IntVec3 randomCell; while (true) { num++; if (num > 200) { - break; - } - IntVec3 randomCell = cellRect.RandomCell; - if (map.reachability.CanReach(randomCell, SiegeBlueprintPlacer.center, PathEndMode.OnCell, TraverseMode.NoPassClosedDoors, Danger.Deadly)) - { - if (!randomCell.Roofed(map)) - { - if (SiegeBlueprintPlacer.CanPlaceBlueprintAt(randomCell, rot, artyDef, map)) - { - return randomCell; - } - } + return IntVec3.Invalid; } + randomCell = cellRect.RandomCell; + if (map.reachability.CanReach(randomCell, SiegeBlueprintPlacer.center, PathEndMode.OnCell, TraverseMode.NoPassClosedDoors, Danger.Deadly) && !randomCell.Roofed(map) && SiegeBlueprintPlacer.CanPlaceBlueprintAt(randomCell, rot, artyDef, map)) + break; } - return IntVec3.Invalid; + return randomCell; + IL_007d: + goto IL_0017; } } } diff --git a/Assembly-CSharp/RimWorld/SiteCoreDefOf.cs b/Assembly-CSharp/RimWorld/SiteCoreDefOf.cs index 78765e031..d9252f2d6 100644 --- a/Assembly-CSharp/RimWorld/SiteCoreDefOf.cs +++ b/Assembly-CSharp/RimWorld/SiteCoreDefOf.cs @@ -1,5 +1,3 @@ -using System; - namespace RimWorld { [DefOf] diff --git a/Assembly-CSharp/RimWorld/SiteCoreWorker.cs b/Assembly-CSharp/RimWorld/SiteCoreWorker.cs index 1256315f6..0115f29ae 100644 --- a/Assembly-CSharp/RimWorld/SiteCoreWorker.cs +++ b/Assembly-CSharp/RimWorld/SiteCoreWorker.cs @@ -1,7 +1,6 @@ using RimWorld.Planet; using System; using System.Collections.Generic; -using System.Diagnostics; using Verse; namespace RimWorld @@ -30,24 +29,32 @@ public virtual bool FactionCanOwn(Faction faction) return true; } - [DebuggerHidden] public IEnumerable GetFloatMenuOptions(Caravan caravan, Site site) { - SiteCoreWorker.c__Iterator95 c__Iterator = new SiteCoreWorker.c__Iterator95(); - c__Iterator.site = site; - c__Iterator.caravan = caravan; - c__Iterator.<$>site = site; - c__Iterator.<$>caravan = caravan; - SiteCoreWorker.c__Iterator95 expr_23 = c__Iterator; - expr_23.$PC = -2; - return expr_23; + if (!site.HasMap) + { + string label = (!site.KnownDanger) ? "VisitSite".Translate(site.Label) : "AttackSite".Translate(site.Label); + yield return new FloatMenuOption(label, (Action)delegate + { + ((_003CGetFloatMenuOptions_003Ec__Iterator95)/*Error near IL_009a: stateMachine*/).caravan.pather.StartPath(((_003CGetFloatMenuOptions_003Ec__Iterator95)/*Error near IL_009a: stateMachine*/).site.Tile, new CaravanArrivalAction_VisitSite(((_003CGetFloatMenuOptions_003Ec__Iterator95)/*Error near IL_009a: stateMachine*/).site), true); + }, MenuOptionPriority.Default, null, null, 0f, null, site); + if (Prefs.DevMode) + { + yield return new FloatMenuOption(label + " (Dev: instantly)", (Action)delegate + { + ((_003CGetFloatMenuOptions_003Ec__Iterator95)/*Error near IL_00e8: stateMachine*/).caravan.Tile = ((_003CGetFloatMenuOptions_003Ec__Iterator95)/*Error near IL_00e8: stateMachine*/).site.Tile; + ((_003CGetFloatMenuOptions_003Ec__Iterator95)/*Error near IL_00e8: stateMachine*/).caravan.pather.StopDead(); + new CaravanArrivalAction_VisitSite(((_003CGetFloatMenuOptions_003Ec__Iterator95)/*Error near IL_00e8: stateMachine*/).site).Arrived(((_003CGetFloatMenuOptions_003Ec__Iterator95)/*Error near IL_00e8: stateMachine*/).caravan); + }, MenuOptionPriority.Default, null, null, 0f, null, site); + } + } } protected void Enter(Caravan caravan, Site site) { if (!site.HasMap) { - LongEventHandler.QueueLongEvent(delegate + LongEventHandler.QueueLongEvent((Action)delegate() { this.DoEnter(caravan, site); }, "GeneratingMapForNewEncounter", false, null); @@ -69,10 +76,7 @@ private void DoEnter(Caravan caravan, Site site) { Find.TickManager.CurTimeSpeed = TimeSpeed.Paused; } - Messages.Message("MessageCaravanArrivedAtDestination".Translate(new object[] - { - caravan.Label - }).CapitalizeFirst(), t, MessageSound.Benefit); + Messages.Message("MessageCaravanArrivedAtDestination".Translate(caravan.Label).CapitalizeFirst(), (Thing)t, MessageSound.Benefit); } } } diff --git a/Assembly-CSharp/RimWorld/SiteDefBase.cs b/Assembly-CSharp/RimWorld/SiteDefBase.cs index b9c7d2969..ef7aa1e85 100644 --- a/Assembly-CSharp/RimWorld/SiteDefBase.cs +++ b/Assembly-CSharp/RimWorld/SiteDefBase.cs @@ -1,4 +1,3 @@ -using System; using System.Collections.Generic; using UnityEngine; using Verse; @@ -31,7 +30,7 @@ public Texture2D ExpandingIconTexture { get { - if (this.expandingIconTextureInt == null) + if ((Object)this.expandingIconTextureInt == (Object)null) { if (!this.expandingIconTexture.NullOrEmpty()) { @@ -68,7 +67,19 @@ public List ExtraGenSteps public virtual bool FactionCanOwn(Faction faction) { - return (!this.requiresFaction || faction != null) && (this.minFactionTechLevel == TechLevel.Undefined || (faction != null && faction.def.techLevel >= this.minFactionTechLevel)) && (faction == null || (!faction.IsPlayer && !faction.defeated && !faction.def.hidden)); + if (this.requiresFaction && faction == null) + { + return false; + } + if (this.minFactionTechLevel != 0 && (faction == null || (int)faction.def.techLevel < (int)this.minFactionTechLevel)) + { + return false; + } + if (faction != null && (faction.IsPlayer || faction.defeated || faction.def.hidden)) + { + return false; + } + return true; } } } diff --git a/Assembly-CSharp/RimWorld/SitePartDefOf.cs b/Assembly-CSharp/RimWorld/SitePartDefOf.cs index 786690112..369cb32fa 100644 --- a/Assembly-CSharp/RimWorld/SitePartDefOf.cs +++ b/Assembly-CSharp/RimWorld/SitePartDefOf.cs @@ -1,5 +1,3 @@ -using System; - namespace RimWorld { [DefOf] diff --git a/Assembly-CSharp/RimWorld/SitePartWorker.cs b/Assembly-CSharp/RimWorld/SitePartWorker.cs index 1b3e86922..ac792c75b 100644 --- a/Assembly-CSharp/RimWorld/SitePartWorker.cs +++ b/Assembly-CSharp/RimWorld/SitePartWorker.cs @@ -1,5 +1,4 @@ using RimWorld.Planet; -using System; using Verse; namespace RimWorld diff --git a/Assembly-CSharp/RimWorld/SituationalThoughtHandler.cs b/Assembly-CSharp/RimWorld/SituationalThoughtHandler.cs index 1ebbabd5f..890bec8b8 100644 --- a/Assembly-CSharp/RimWorld/SituationalThoughtHandler.cs +++ b/Assembly-CSharp/RimWorld/SituationalThoughtHandler.cs @@ -43,9 +43,9 @@ public bool ShouldRecalculateState private int lastMoodThoughtsRecalculationTick = -99999; - private Dictionary cachedSocialThoughts = new Dictionary(); + private Dictionary cachedSocialThoughts = new Dictionary(); - private Dictionary cachedSocialThoughtsAffectingMood = new Dictionary(); + private Dictionary cachedSocialThoughtsAffectingMood = new Dictionary(); private HashSet tmpCachedThoughts = new HashSet(); @@ -75,21 +75,30 @@ public void AppendMoodThoughts(List outThoughts) } } int ticksGame = Find.TickManager.TicksGame; - foreach (KeyValuePair current in this.cachedSocialThoughtsAffectingMood) + Dictionary.Enumerator enumerator = this.cachedSocialThoughtsAffectingMood.GetEnumerator(); + try { - current.Value.lastQueryTick = ticksGame; - List activeThoughts = current.Value.activeThoughts; - for (int j = 0; j < activeThoughts.Count; j++) + while (enumerator.MoveNext()) { - outThoughts.Add(activeThoughts[j]); + KeyValuePair current = enumerator.Current; + current.Value.lastQueryTick = ticksGame; + List activeThoughts = current.Value.activeThoughts; + for (int j = 0; j < activeThoughts.Count; j++) + { + outThoughts.Add(activeThoughts[j]); + } } } + finally + { + ((IDisposable)(object)enumerator).Dispose(); + } } public void AppendSocialThoughts(Pawn otherPawn, List outThoughts) { this.CheckRecalculateSocialThoughts(otherPawn); - SituationalThoughtHandler.CachedSocialThoughts cachedSocialThoughts = this.cachedSocialThoughts[otherPawn]; + CachedSocialThoughts cachedSocialThoughts = this.cachedSocialThoughts[otherPawn]; cachedSocialThoughts.lastQueryTick = Find.TickManager.TicksGame; List activeThoughts = cachedSocialThoughts.activeThoughts; for (int i = 0; i < activeThoughts.Count; i++) @@ -101,40 +110,39 @@ public void AppendSocialThoughts(Pawn otherPawn, List outThought private void CheckRecalculateMoodThoughts() { int ticksGame = Find.TickManager.TicksGame; - if (ticksGame - this.lastMoodThoughtsRecalculationTick < 100) + if (ticksGame - this.lastMoodThoughtsRecalculationTick >= 100) { - return; - } - this.lastMoodThoughtsRecalculationTick = ticksGame; - ProfilerThreadCheck.BeginSample("recalculating situational thoughts"); - try - { - this.tmpCachedThoughts.Clear(); - for (int i = 0; i < this.cachedThoughts.Count; i++) - { - this.cachedThoughts[i].RecalculateState(); - this.tmpCachedThoughts.Add(this.cachedThoughts[i].def); - } - List situationalNonSocialThoughtDefs = ThoughtUtility.situationalNonSocialThoughtDefs; - int j = 0; - int count = situationalNonSocialThoughtDefs.Count; - while (j < count) + this.lastMoodThoughtsRecalculationTick = ticksGame; + ProfilerThreadCheck.BeginSample("recalculating situational thoughts"); + try { - if (!this.tmpCachedThoughts.Contains(situationalNonSocialThoughtDefs[j])) + this.tmpCachedThoughts.Clear(); + for (int i = 0; i < this.cachedThoughts.Count; i++) + { + this.cachedThoughts[i].RecalculateState(); + this.tmpCachedThoughts.Add(this.cachedThoughts[i].def); + } + List situationalNonSocialThoughtDefs = ThoughtUtility.situationalNonSocialThoughtDefs; + int num = 0; + int count = situationalNonSocialThoughtDefs.Count; + while (num < count) { - Thought_Situational thought_Situational = this.TryCreateThought(situationalNonSocialThoughtDefs[j]); - if (thought_Situational != null) + if (!this.tmpCachedThoughts.Contains(situationalNonSocialThoughtDefs[num])) { - this.cachedThoughts.Add(thought_Situational); + Thought_Situational thought_Situational = this.TryCreateThought(situationalNonSocialThoughtDefs[num]); + if (thought_Situational != null) + { + this.cachedThoughts.Add(thought_Situational); + } } + num++; } - j++; + this.RecalculateSocialThoughtsAffectingMood(); + } + finally + { + ProfilerThreadCheck.EndSample(); } - this.RecalculateSocialThoughtsAffectingMood(); - } - finally - { - ProfilerThreadCheck.EndSample(); } } @@ -144,83 +152,113 @@ private void RecalculateSocialThoughtsAffectingMood() { this.tmpToAdd.Clear(); List situationalSocialThoughtDefs = ThoughtUtility.situationalSocialThoughtDefs; - int i = 0; + int num = 0; int count = situationalSocialThoughtDefs.Count; - while (i < count) + while (num < count) { - if (situationalSocialThoughtDefs[i].socialThoughtAffectingMood) + if (situationalSocialThoughtDefs[num].socialThoughtAffectingMood) { - foreach (Pawn current in situationalSocialThoughtDefs[i].Worker.PotentialPawnCandidates(this.pawn)) + foreach (Pawn item in situationalSocialThoughtDefs[num].Worker.PotentialPawnCandidates(this.pawn)) { - if (current != this.pawn) + if (item != this.pawn) { - this.tmpToAdd.Add(new Pair(situationalSocialThoughtDefs[i], current)); + this.tmpToAdd.Add(new Pair(situationalSocialThoughtDefs[num], item)); } } } - i++; + num++; } - foreach (KeyValuePair current2 in this.cachedSocialThoughtsAffectingMood) + Dictionary.Enumerator enumerator2 = this.cachedSocialThoughtsAffectingMood.GetEnumerator(); + try { - List thoughts = current2.Value.thoughts; - for (int j = thoughts.Count - 1; j >= 0; j--) + while (enumerator2.MoveNext()) { - if (!this.tmpToAdd.Contains(new Pair(thoughts[j].def, current2.Key))) + KeyValuePair current2 = enumerator2.Current; + List thoughts = current2.Value.thoughts; + for (int num2 = thoughts.Count - 1; num2 >= 0; num2--) { - thoughts.RemoveAt(j); + if (!this.tmpToAdd.Contains(new Pair(thoughts[num2].def, current2.Key))) + { + thoughts.RemoveAt(num2); + } } } } - foreach (Pair current3 in this.tmpToAdd) + finally + { + ((IDisposable)(object)enumerator2).Dispose(); + } + HashSet>.Enumerator enumerator3 = this.tmpToAdd.GetEnumerator(); + try { - ThoughtDef first = current3.First; - Pawn second = current3.Second; - SituationalThoughtHandler.CachedSocialThoughts cachedSocialThoughts; - bool flag = this.cachedSocialThoughtsAffectingMood.TryGetValue(second, out cachedSocialThoughts); - if (flag) + while (enumerator3.MoveNext()) { - bool flag2 = false; - for (int k = 0; k < cachedSocialThoughts.thoughts.Count; k++) + Pair current3 = enumerator3.Current; + ThoughtDef first = current3.First; + Pawn second = current3.Second; + CachedSocialThoughts cachedSocialThoughts = default(CachedSocialThoughts); + bool flag = this.cachedSocialThoughtsAffectingMood.TryGetValue(second, out cachedSocialThoughts); + if (flag) { - if (cachedSocialThoughts.thoughts[k].def == first) + bool flag2 = false; + int num3 = 0; + while (num3 < cachedSocialThoughts.thoughts.Count) { + if (cachedSocialThoughts.thoughts[num3].def != first) + { + num3++; + continue; + } flag2 = true; break; } - } - if (flag2) - { + if (!flag2) + goto IL_01e2; continue; } - } - Thought_SituationalSocial thought_SituationalSocial = this.TryCreateSocialThought(first, second); - if (thought_SituationalSocial != null) - { - if (!flag) + goto IL_01e2; + IL_01e2: + Thought_SituationalSocial thought_SituationalSocial = this.TryCreateSocialThought(first, second); + if (thought_SituationalSocial != null) { - cachedSocialThoughts = new SituationalThoughtHandler.CachedSocialThoughts(); - this.cachedSocialThoughtsAffectingMood.Add(second, cachedSocialThoughts); + if (!flag) + { + cachedSocialThoughts = new CachedSocialThoughts(); + this.cachedSocialThoughtsAffectingMood.Add(second, cachedSocialThoughts); + } + cachedSocialThoughts.thoughts.Add(thought_SituationalSocial); } - cachedSocialThoughts.thoughts.Add(thought_SituationalSocial); } } - this.cachedSocialThoughtsAffectingMood.RemoveAll((KeyValuePair x) => x.Value.thoughts.Count == 0); + finally + { + ((IDisposable)(object)enumerator3).Dispose(); + } + this.cachedSocialThoughtsAffectingMood.RemoveAll((Predicate>)((KeyValuePair x) => x.Value.thoughts.Count == 0)); int ticksGame = Find.TickManager.TicksGame; - foreach (KeyValuePair current4 in this.cachedSocialThoughtsAffectingMood) + Dictionary.Enumerator enumerator4 = this.cachedSocialThoughtsAffectingMood.GetEnumerator(); + try { - SituationalThoughtHandler.CachedSocialThoughts value = current4.Value; - List thoughts2 = value.thoughts; - value.activeThoughts.Clear(); - for (int l = 0; l < thoughts2.Count; l++) + while (enumerator4.MoveNext()) { - thoughts2[l].RecalculateState(); - value.lastRecalculationTick = ticksGame; - if (thoughts2[l].Active) + CachedSocialThoughts value = enumerator4.Current.Value; + List thoughts2 = value.thoughts; + value.activeThoughts.Clear(); + for (int i = 0; i < thoughts2.Count; i++) { - value.activeThoughts.Add(thoughts2[l]); + thoughts2[i].RecalculateState(); + value.lastRecalculationTick = ticksGame; + if (thoughts2[i].Active) + { + value.activeThoughts.Add(thoughts2[i]); + } } } } + finally + { + ((IDisposable)(object)enumerator4).Dispose(); + } } finally { @@ -233,10 +271,10 @@ private void CheckRecalculateSocialThoughts(Pawn otherPawn) ProfilerThreadCheck.BeginSample("recalculating situational social thoughts"); try { - SituationalThoughtHandler.CachedSocialThoughts cachedSocialThoughts; + CachedSocialThoughts cachedSocialThoughts = default(CachedSocialThoughts); if (!this.cachedSocialThoughts.TryGetValue(otherPawn, out cachedSocialThoughts)) { - cachedSocialThoughts = new SituationalThoughtHandler.CachedSocialThoughts(); + cachedSocialThoughts = new CachedSocialThoughts(); this.cachedSocialThoughts.Add(otherPawn, cachedSocialThoughts); } if (cachedSocialThoughts.ShouldRecalculateState) @@ -250,24 +288,24 @@ private void CheckRecalculateSocialThoughts(Pawn otherPawn) this.tmpCachedSocialThoughts.Add(thought_SituationalSocial.def); } List situationalSocialThoughtDefs = ThoughtUtility.situationalSocialThoughtDefs; - int j = 0; + int num = 0; int count = situationalSocialThoughtDefs.Count; - while (j < count) + while (num < count) { - if (!this.tmpCachedSocialThoughts.Contains(situationalSocialThoughtDefs[j])) + if (!this.tmpCachedSocialThoughts.Contains(situationalSocialThoughtDefs[num])) { - Thought_SituationalSocial thought_SituationalSocial2 = this.TryCreateSocialThought(situationalSocialThoughtDefs[j], otherPawn); + Thought_SituationalSocial thought_SituationalSocial2 = this.TryCreateSocialThought(situationalSocialThoughtDefs[num], otherPawn); if (thought_SituationalSocial2 != null) { cachedSocialThoughts.thoughts.Add(thought_SituationalSocial2); } } - j++; + num++; } cachedSocialThoughts.activeThoughts.Clear(); - for (int k = 0; k < cachedSocialThoughts.thoughts.Count; k++) + for (int j = 0; j < cachedSocialThoughts.thoughts.Count; j++) { - Thought_SituationalSocial thought_SituationalSocial3 = cachedSocialThoughts.thoughts[k]; + Thought_SituationalSocial thought_SituationalSocial3 = cachedSocialThoughts.thoughts[j]; if (thought_SituationalSocial3.Active) { cachedSocialThoughts.activeThoughts.Add(thought_SituationalSocial3); @@ -288,31 +326,22 @@ private Thought_Situational TryCreateThought(ThoughtDef def) { if (!ThoughtUtility.CanGetThought(this.pawn, def)) { - Thought_Situational result = null; - return result; + return null; } if (!def.Worker.CurrentState(this.pawn).Active) { - Thought_Situational result = null; - return result; + return null; } thought_Situational = (Thought_Situational)ThoughtMaker.MakeThought(def); thought_Situational.pawn = this.pawn; thought_Situational.RecalculateState(); + return thought_Situational; } catch (Exception ex) { - Log.Error(string.Concat(new object[] - { - "Exception while recalculating ", - def, - " thought state for pawn ", - this.pawn, - ": ", - ex - })); + Log.Error("Exception while recalculating " + def + " thought state for pawn " + this.pawn + ": " + ex); + return thought_Situational; } - return thought_Situational; } private Thought_SituationalSocial TryCreateSocialThought(ThoughtDef def, Pawn otherPawn) @@ -322,32 +351,23 @@ private Thought_SituationalSocial TryCreateSocialThought(ThoughtDef def, Pawn ot { if (!ThoughtUtility.CanGetThought(this.pawn, def)) { - Thought_SituationalSocial result = null; - return result; + return null; } if (!def.Worker.CurrentSocialState(this.pawn, otherPawn).Active) { - Thought_SituationalSocial result = null; - return result; + return null; } thought_SituationalSocial = (Thought_SituationalSocial)ThoughtMaker.MakeThought(def); thought_SituationalSocial.pawn = this.pawn; thought_SituationalSocial.otherPawn = otherPawn; thought_SituationalSocial.RecalculateState(); + return thought_SituationalSocial; } catch (Exception ex) { - Log.Error(string.Concat(new object[] - { - "Exception while recalculating ", - def, - " thought state for pawn ", - this.pawn, - ": ", - ex - })); + Log.Error("Exception while recalculating " + def + " thought state for pawn " + this.pawn + ": " + ex); + return thought_SituationalSocial; } - return thought_SituationalSocial; } public void Notify_SituationalThoughtsDirty() @@ -359,8 +379,8 @@ public void Notify_SituationalThoughtsDirty() private void RemoveExpiredThoughtsFromCache() { - this.cachedSocialThoughts.RemoveAll((KeyValuePair x) => x.Value.Expired || x.Key.Discarded); - this.cachedSocialThoughtsAffectingMood.RemoveAll((KeyValuePair x) => x.Value.Expired || x.Key.Discarded); + this.cachedSocialThoughts.RemoveAll((Predicate>)((KeyValuePair x) => x.Value.Expired || x.Key.Discarded)); + this.cachedSocialThoughtsAffectingMood.RemoveAll((Predicate>)((KeyValuePair x) => x.Value.Expired || x.Key.Discarded)); } } } diff --git a/Assembly-CSharp/RimWorld/SkillDef.cs b/Assembly-CSharp/RimWorld/SkillDef.cs index bdcabcc1d..cdb37f454 100644 --- a/Assembly-CSharp/RimWorld/SkillDef.cs +++ b/Assembly-CSharp/RimWorld/SkillDef.cs @@ -1,4 +1,3 @@ -using System; using System.Collections.Generic; using System.Linq; using Verse; @@ -15,20 +14,20 @@ public class SkillDef : Def public override void PostLoad() { - if (this.label == null) + if (base.label == null) { - this.label = this.skillLabel; + base.label = this.skillLabel; } } public bool IsDisabled(WorkTags combinedDisabledWorkTags, IEnumerable disabledWorkTypes) { - if ((combinedDisabledWorkTags & this.disablingWorkTags) != WorkTags.None) + if ((combinedDisabledWorkTags & this.disablingWorkTags) != 0) { return true; } List allDefsListForReading = DefDatabase.AllDefsListForReading; - bool result = false; + bool flag = false; for (int i = 0; i < allDefsListForReading.Count; i++) { WorkTypeDef workTypeDef = allDefsListForReading[i]; @@ -40,11 +39,15 @@ public bool IsDisabled(WorkTags combinedDisabledWorkTags, IEnumerable ConfigErrors() { - SkillNeed.c__Iterator85 c__Iterator = new SkillNeed.c__Iterator85(); - SkillNeed.c__Iterator85 expr_07 = c__Iterator; - expr_07.$PC = -2; - return expr_07; + yield break; } } } diff --git a/Assembly-CSharp/RimWorld/SkillNeed_BaseBonus.cs b/Assembly-CSharp/RimWorld/SkillNeed_BaseBonus.cs index ffb0df01c..894e9fb23 100644 --- a/Assembly-CSharp/RimWorld/SkillNeed_BaseBonus.cs +++ b/Assembly-CSharp/RimWorld/SkillNeed_BaseBonus.cs @@ -1,6 +1,4 @@ -using System; using System.Collections.Generic; -using System.Diagnostics; using Verse; namespace RimWorld @@ -17,7 +15,7 @@ public override float FactorFor(Pawn pawn) { return 1f; } - int level = pawn.skills.GetSkill(this.skill).Level; + int level = pawn.skills.GetSkill(base.skill).Level; return this.FactorAt(level); } @@ -26,14 +24,20 @@ private float FactorAt(int level) return this.baseFactor + this.bonusFactor * (float)level; } - [DebuggerHidden] public override IEnumerable ConfigErrors() { - SkillNeed_BaseBonus.c__Iterator86 c__Iterator = new SkillNeed_BaseBonus.c__Iterator86(); - c__Iterator.<>f__this = this; - SkillNeed_BaseBonus.c__Iterator86 expr_0E = c__Iterator; - expr_0E.$PC = -2; - return expr_0E; + foreach (string item in base.ConfigErrors()) + { + yield return item; + } + for (int i = 1; i <= 20; i++) + { + float factor = this.FactorAt(i); + if (factor <= 0.0) + { + yield return "SkillNeed yields factor < 0 at skill level " + i; + } + } } } } diff --git a/Assembly-CSharp/RimWorld/SkillNeed_Direct.cs b/Assembly-CSharp/RimWorld/SkillNeed_Direct.cs index 7241245c2..e732e5de4 100644 --- a/Assembly-CSharp/RimWorld/SkillNeed_Direct.cs +++ b/Assembly-CSharp/RimWorld/SkillNeed_Direct.cs @@ -1,4 +1,3 @@ -using System; using System.Collections.Generic; using Verse; @@ -14,7 +13,7 @@ public override float FactorFor(Pawn pawn) { return 1f; } - int level = pawn.skills.GetSkill(this.skill).Level; + int level = pawn.skills.GetSkill(base.skill).Level; if (this.factorsPerLevel.Count > level) { return this.factorsPerLevel[level]; diff --git a/Assembly-CSharp/RimWorld/SkillRecord.cs b/Assembly-CSharp/RimWorld/SkillRecord.cs index e64221ea9..5083a5c7e 100644 --- a/Assembly-CSharp/RimWorld/SkillRecord.cs +++ b/Assembly-CSharp/RimWorld/SkillRecord.cs @@ -87,7 +87,7 @@ public bool TotallyDisabled { if (this.cachedTotallyDisabled == BoolUnknown.Unknown) { - this.cachedTotallyDisabled = ((!this.CalculateTotallyDisabled()) ? BoolUnknown.False : BoolUnknown.True); + this.cachedTotallyDisabled = (BoolUnknown)((!this.CalculateTotallyDisabled()) ? 1 : 0); } return this.cachedTotallyDisabled == BoolUnknown.True; } @@ -100,50 +100,94 @@ public string LevelDescriptor switch (this.levelInt) { case 0: + { return "Skill0".Translate(); + } case 1: + { return "Skill1".Translate(); + } case 2: + { return "Skill2".Translate(); + } case 3: + { return "Skill3".Translate(); + } case 4: + { return "Skill4".Translate(); + } case 5: + { return "Skill5".Translate(); + } case 6: + { return "Skill6".Translate(); + } case 7: + { return "Skill7".Translate(); + } case 8: + { return "Skill8".Translate(); + } case 9: + { return "Skill9".Translate(); + } case 10: + { return "Skill10".Translate(); + } case 11: + { return "Skill11".Translate(); + } case 12: + { return "Skill12".Translate(); + } case 13: + { return "Skill13".Translate(); + } case 14: + { return "Skill14".Translate(); + } case 15: + { return "Skill15".Translate(); + } case 16: + { return "Skill16".Translate(); + } case 17: + { return "Skill17".Translate(); + } case 18: + { return "Skill18".Translate(); + } case 19: + { return "Skill19".Translate(); + } case 20: + { return "Skill20".Translate(); + } default: + { return "Unknown"; } + } } } @@ -151,7 +195,7 @@ public bool LearningSaturatedToday { get { - return this.xpSinceMidnight > 4000f; + return this.xpSinceMidnight > 4000.0; } } @@ -184,39 +228,61 @@ public void Interval() switch (this.levelInt) { case 10: + { this.Learn(-0.1f, false); break; + } case 11: + { this.Learn(-0.2f, false); break; + } case 12: + { this.Learn(-0.4f, false); break; + } case 13: + { this.Learn(-0.65f, false); break; + } case 14: + { this.Learn(-1f, false); break; + } case 15: + { this.Learn(-1.5f, false); break; + } case 16: + { this.Learn(-2f, false); break; + } case 17: + { this.Learn(-3f, false); break; + } case 18: + { this.Learn(-4f, false); break; + } case 19: + { this.Learn(-6f, false); break; + } case 20: + { this.Learn(-8f, false); break; } + } } public float XpRequiredToLevelUpFrom(int startingLevel) @@ -226,65 +292,69 @@ public float XpRequiredToLevelUpFrom(int startingLevel) public void Learn(float xp, bool direct = false) { - if (this.TotallyDisabled) - { - return; - } - if (xp < 0f && this.levelInt == 0) - { - return; - } - if (xp > 0f) + if (((!this.TotallyDisabled) ? ((!(xp < 0.0)) ? 1 : this.levelInt) : 0) != 0) { - if (this.pawn.needs.joy != null) + if (xp > 0.0) { - float amount = 0f; - switch (this.passion) + if (this.pawn.needs.joy != null) { - case Passion.None: - amount = 0f * xp; - break; - case Passion.Minor: - amount = 2E-05f * xp; - break; - case Passion.Major: - amount = 4E-05f * xp; - break; + float amount = 0f; + switch (this.passion) + { + case Passion.Minor: + { + amount = (float)(1.9999999494757503E-05 * xp); + break; + } + case Passion.Major: + { + amount = (float)(3.9999998989515007E-05 * xp); + break; + } + case Passion.None: + { + amount = (float)(0.0 * xp); + break; + } + } + this.pawn.needs.joy.GainJoy(amount, JoyKindDefOf.Work); } - this.pawn.needs.joy.GainJoy(amount, JoyKindDefOf.Work); + xp *= this.LearnRateFactor(direct); } - xp *= this.LearnRateFactor(direct); - } - this.xpSinceLastLevel += xp; - if (!direct) - { - this.xpSinceMidnight += xp; - } - if (this.levelInt == 20 && this.xpSinceLastLevel > this.XpRequiredForLevelUp - 1f) - { - this.xpSinceLastLevel = this.XpRequiredForLevelUp - 1f; - } - while (this.xpSinceLastLevel >= this.XpRequiredForLevelUp) - { - this.xpSinceLastLevel -= this.XpRequiredForLevelUp; - this.levelInt++; - if (this.levelInt >= 20) + this.xpSinceLastLevel += xp; + if (!direct) { - this.levelInt = 20; - this.xpSinceLastLevel = Mathf.Clamp(this.xpSinceLastLevel, 0f, this.XpRequiredForLevelUp - 1f); - break; + this.xpSinceMidnight += xp; } - } - while (this.xpSinceLastLevel < 0f) - { - this.levelInt--; - this.xpSinceLastLevel += this.XpRequiredForLevelUp; - if (this.levelInt <= 0) + if (this.levelInt == 20 && this.xpSinceLastLevel > this.XpRequiredForLevelUp - 1.0) { - this.levelInt = 0; - this.xpSinceLastLevel = 0f; - break; + this.xpSinceLastLevel = (float)(this.XpRequiredForLevelUp - 1.0); } + while (this.xpSinceLastLevel >= this.XpRequiredForLevelUp) + { + this.xpSinceLastLevel -= this.XpRequiredForLevelUp; + this.levelInt++; + if (this.levelInt >= 20) + { + this.levelInt = 20; + this.xpSinceLastLevel = Mathf.Clamp(this.xpSinceLastLevel, 0f, (float)(this.XpRequiredForLevelUp - 1.0)); + break; + } + } + while (true) + { + if (this.xpSinceLastLevel < 0.0) + { + this.levelInt--; + this.xpSinceLastLevel += this.XpRequiredForLevelUp; + if (this.levelInt <= 0) + break; + continue; + } + return; + } + this.levelInt = 0; + this.xpSinceLastLevel = 0f; } } @@ -298,23 +368,31 @@ public float LearnRateFactor(bool direct = false) switch (this.passion) { case Passion.None: + { num = 0.333f; break; + } case Passion.Minor: + { num = 1f; break; + } case Passion.Major: + { num = 1.5f; break; + } default: + { throw new NotImplementedException("Passion level " + this.passion); } + } if (!direct) { num *= this.pawn.GetStatValue(StatDefOf.GlobalLearningFactor, true); if (this.LearningSaturatedToday) { - num *= 0.2f; + num = (float)(num * 0.20000000298023224); } } return num; @@ -332,15 +410,7 @@ private bool CalculateTotallyDisabled() public override string ToString() { - return string.Concat(new object[] - { - this.def.defName, - ": ", - this.levelInt, - " (", - this.xpSinceLastLevel, - "xp)" - }); + return this.def.defName + ": " + this.levelInt + " (" + this.xpSinceLastLevel + "xp)"; } } } diff --git a/Assembly-CSharp/RimWorld/SkillUI.cs b/Assembly-CSharp/RimWorld/SkillUI.cs index c67e0fa1b..311a2f514 100644 --- a/Assembly-CSharp/RimWorld/SkillUI.cs +++ b/Assembly-CSharp/RimWorld/SkillUI.cs @@ -1,4 +1,3 @@ -using System; using System.Collections.Generic; using System.Text; using UnityEngine; @@ -11,8 +10,8 @@ public static class SkillUI { public enum SkillDrawMode : byte { - Gameplay, - Menu + Gameplay = 0, + Menu = 1 } private const float SkillWidth = 240f; @@ -37,13 +36,14 @@ public enum SkillDrawMode : byte private static Texture2D SkillBarFillTex = SolidColorMaterials.NewSolidColorTexture(new Color(1f, 1f, 1f, 0.1f)); - public static void DrawSkillsOf(Pawn p, Vector2 offset, SkillUI.SkillDrawMode mode) + public static void DrawSkillsOf(Pawn p, Vector2 offset, SkillDrawMode mode) { Text.Font = GameFont.Small; List allDefsListForReading = DefDatabase.AllDefsListForReading; for (int i = 0; i < allDefsListForReading.Count; i++) { - float x = Text.CalcSize(allDefsListForReading[i].skillLabel).x; + Vector2 vector = Text.CalcSize(allDefsListForReading[i].skillLabel); + float x = vector.x; if (x > SkillUI.levelLabelWidth) { SkillUI.levelLabelWidth = x; @@ -51,12 +51,12 @@ public static void DrawSkillsOf(Pawn p, Vector2 offset, SkillUI.SkillDrawMode mo } for (int j = 0; j < p.skills.skills.Count; j++) { - float y = (float)j * 27f + offset.y; + float y = (float)((float)j * 27.0 + offset.y); SkillUI.DrawSkill(p.skills.skills[j], new Vector2(offset.x, y), mode); } } - private static void DrawSkill(SkillRecord skill, Vector2 topLeft, SkillUI.SkillDrawMode mode) + private static void DrawSkill(SkillRecord skill, Vector2 topLeft, SkillDrawMode mode) { Rect rect = new Rect(topLeft.x, topLeft.y, 240f, 24f); if (Mouse.IsOver(rect)) @@ -65,10 +65,10 @@ private static void DrawSkill(SkillRecord skill, Vector2 topLeft, SkillUI.SkillD } GUI.BeginGroup(rect); Text.Anchor = TextAnchor.MiddleLeft; - Rect rect2 = new Rect(6f, 0f, SkillUI.levelLabelWidth + 6f, rect.height); + Rect rect2 = new Rect(6f, 0f, (float)(SkillUI.levelLabelWidth + 6.0), rect.height); Widgets.Label(rect2, skill.def.skillLabel); Rect position = new Rect(rect2.xMax, 0f, 24f, 24f); - if (skill.passion > Passion.None) + if ((int)skill.passion > 0) { Texture2D image = (skill.passion != Passion.Major) ? SkillUI.PassionMinorIcon : SkillUI.PassionMajorIcon; GUI.DrawTexture(position, image); @@ -76,10 +76,10 @@ private static void DrawSkill(SkillRecord skill, Vector2 topLeft, SkillUI.SkillD if (!skill.TotallyDisabled) { Rect rect3 = new Rect(position.xMax, 0f, rect.width - position.xMax, rect.height); - float fillPercent = Mathf.Max(0.01f, (float)skill.Level / 20f); + float fillPercent = Mathf.Max(0.01f, (float)((float)skill.Level / 20.0)); Widgets.FillableBar(rect3, fillPercent, SkillUI.SkillBarFillTex, null, false); } - Rect rect4 = new Rect(position.xMax + 4f, 0f, 999f, rect.height); + Rect rect4 = new Rect((float)(position.xMax + 4.0), 0f, 999f, rect.height); rect4.yMin += 3f; string label; if (skill.TotallyDisabled) @@ -108,57 +108,35 @@ private static string GetSkillDescription(SkillRecord sk) } else { - stringBuilder.AppendLine(string.Concat(new object[] - { - "Level".Translate(), - " ", - sk.Level, - ": ", - sk.LevelDescriptor - })); + stringBuilder.AppendLine("Level".Translate() + " " + sk.Level + ": " + sk.LevelDescriptor); if (Current.ProgramState == ProgramState.Playing) { string text = (sk.Level != 20) ? "ProgressToNextLevel".Translate() : "Experience".Translate(); - stringBuilder.AppendLine(string.Concat(new object[] - { - text, - ": ", - sk.xpSinceLastLevel.ToString("F0"), - " / ", - sk.XpRequiredForLevelUp - })); + stringBuilder.AppendLine(text + ": " + sk.xpSinceLastLevel.ToString("F0") + " / " + sk.XpRequiredForLevelUp); } stringBuilder.Append("Passion".Translate() + ": "); switch (sk.passion) { case Passion.None: - stringBuilder.Append("PassionNone".Translate(new object[] - { - 0.333f.ToStringPercent("F0") - })); + { + stringBuilder.Append("PassionNone".Translate(0.333f.ToStringPercent("F0"))); break; + } case Passion.Minor: - stringBuilder.Append("PassionMinor".Translate(new object[] - { - 1f.ToStringPercent("F0") - })); + { + stringBuilder.Append("PassionMinor".Translate(1f.ToStringPercent("F0"))); break; + } case Passion.Major: - stringBuilder.Append("PassionMajor".Translate(new object[] - { - 1.5f.ToStringPercent("F0") - })); + { + stringBuilder.Append("PassionMajor".Translate(1.5f.ToStringPercent("F0"))); break; } + } if (sk.LearningSaturatedToday) { stringBuilder.AppendLine(); - stringBuilder.Append("LearnedMaxToday".Translate(new object[] - { - sk.xpSinceMidnight, - 4000, - 0.2f.ToStringPercent("F0") - })); + stringBuilder.Append("LearnedMaxToday".Translate(sk.xpSinceMidnight, 4000, 0.2f.ToStringPercent("F0"))); } } stringBuilder.AppendLine(); diff --git a/Assembly-CSharp/RimWorld/SlaughterDesignatorUtility.cs b/Assembly-CSharp/RimWorld/SlaughterDesignatorUtility.cs index 924b2f87a..bf1c263a0 100644 --- a/Assembly-CSharp/RimWorld/SlaughterDesignatorUtility.cs +++ b/Assembly-CSharp/RimWorld/SlaughterDesignatorUtility.cs @@ -1,4 +1,3 @@ -using System; using Verse; namespace RimWorld @@ -7,18 +6,13 @@ public static class SlaughterDesignatorUtility { public static void CheckWarnAboutBondedAnimal(Pawn designated) { - if (!designated.RaceProps.IsFlesh) + if (designated.RaceProps.IsFlesh) { - return; - } - Pawn firstDirectRelationPawn = designated.relations.GetFirstDirectRelationPawn(PawnRelationDefOf.Bond, null); - if (firstDirectRelationPawn != null) - { - Messages.Message("MessageSlaughteringBondedAnimal".Translate(new object[] + Pawn firstDirectRelationPawn = designated.relations.GetFirstDirectRelationPawn(PawnRelationDefOf.Bond, null); + if (firstDirectRelationPawn != null) { - designated.LabelShort, - firstDirectRelationPawn.LabelShort - }), designated, MessageSound.Standard); + Messages.Message("MessageSlaughteringBondedAnimal".Translate(designated.LabelShort, firstDirectRelationPawn.LabelShort), (Thing)designated, MessageSound.Standard); + } } } } diff --git a/Assembly-CSharp/RimWorld/SlotGroup.cs b/Assembly-CSharp/RimWorld/SlotGroup.cs index 8571dbef5..788d630b1 100644 --- a/Assembly-CSharp/RimWorld/SlotGroup.cs +++ b/Assembly-CSharp/RimWorld/SlotGroup.cs @@ -1,6 +1,4 @@ -using System; using System.Collections.Generic; -using System.Diagnostics; using Verse; namespace RimWorld @@ -29,11 +27,18 @@ public IEnumerable HeldThings { get { - SlotGroup.<>c__Iterator14C <>c__Iterator14C = new SlotGroup.<>c__Iterator14C(); - <>c__Iterator14C.<>f__this = this; - SlotGroup.<>c__Iterator14C expr_0E = <>c__Iterator14C; - expr_0E.$PC = -2; - return expr_0E; + List cellsList = this.CellsList; + for (int j = 0; j < cellsList.Count; j++) + { + List thingList = this.Map.thingGrid.ThingsListAt(cellsList[j]); + for (int i = 0; i < thingList.Count; i++) + { + if (thingList[i].def.EverStoreable) + { + yield return thingList[i]; + } + } + } } } @@ -51,12 +56,12 @@ public SlotGroup(ISlotGroupParent parent) this.Map.slotGroupManager.AddGroup(this); } - [DebuggerHidden] public IEnumerator GetEnumerator() { - SlotGroup.c__Iterator14D c__Iterator14D = new SlotGroup.c__Iterator14D(); - c__Iterator14D.<>f__this = this; - return c__Iterator14D; + for (int i = 0; i < this.CellsList.Count; i++) + { + yield return this.CellsList[i]; + } } public void Notify_AddedCell(IntVec3 c) diff --git a/Assembly-CSharp/RimWorld/SlotGroupManager.cs b/Assembly-CSharp/RimWorld/SlotGroupManager.cs index 124813d44..81ee46195 100644 --- a/Assembly-CSharp/RimWorld/SlotGroupManager.cs +++ b/Assembly-CSharp/RimWorld/SlotGroupManager.cs @@ -41,18 +41,28 @@ public IEnumerable AllSlots { get { - SlotGroupManager.<>c__Iterator14E <>c__Iterator14E = new SlotGroupManager.<>c__Iterator14E(); - <>c__Iterator14E.<>f__this = this; - SlotGroupManager.<>c__Iterator14E expr_0E = <>c__Iterator14E; - expr_0E.$PC = -2; - return expr_0E; + for (int j = 0; j < this.allGroups.Count; j++) + { + List cellsList = this.allGroups[j].CellsList; + int i = 0; + while (i < cellsList.Count) + { + yield return cellsList[i]; + j++; + } + } } } public SlotGroupManager(Map map) { this.map = map; - this.groupGrid = new SlotGroup[map.Size.x, map.Size.y, map.Size.z]; + IntVec3 size = map.Size; + int x = size.x; + IntVec3 size2 = map.Size; + int y = size2.y; + IntVec3 size3 = map.Size; + this.groupGrid = new SlotGroup[x, y, size3.z]; } public void AddGroup(SlotGroup newGroup) @@ -60,23 +70,24 @@ public void AddGroup(SlotGroup newGroup) if (this.allGroups.Contains(newGroup)) { Log.Error("Double-added slot group. SlotGroup parent is " + newGroup.parent); - return; } - if ((from g in this.allGroups + else if ((from g in this.allGroups where g.parent == newGroup.parent - select g).Any()) + select g).Any()) { Log.Error("Added SlotGroup with a parent matching an existing one. Parent is " + newGroup.parent); - return; } - this.allGroups.Add(newGroup); - this.allGroups.InsertionSort(new Comparison(SlotGroupManager.CompareSlotGroupPrioritiesDescending)); - List cellsList = newGroup.CellsList; - for (int i = 0; i < cellsList.Count; i++) + else { - this.SetCellFor(cellsList[i], newGroup); + this.allGroups.Add(newGroup); + this.allGroups.InsertionSort(new Comparison(SlotGroupManager.CompareSlotGroupPrioritiesDescending)); + List cellsList = newGroup.CellsList; + for (int i = 0; i < cellsList.Count; i++) + { + this.SetCellFor(cellsList[i], newGroup); + } + this.map.listerHaulables.Notify_SlotGroupChanged(newGroup); } - this.map.listerHaulables.Notify_SlotGroupChanged(newGroup); } public void RemoveGroup(SlotGroup oldGroup) @@ -84,16 +95,18 @@ public void RemoveGroup(SlotGroup oldGroup) if (!this.allGroups.Contains(oldGroup)) { Log.Error("Removing SlotGroup that isn't registered."); - return; } - this.allGroups.Remove(oldGroup); - List cellsList = oldGroup.CellsList; - for (int i = 0; i < cellsList.Count; i++) + else { - IntVec3 intVec = cellsList[i]; - this.groupGrid[intVec.x, intVec.y, intVec.z] = null; + this.allGroups.Remove(oldGroup); + List cellsList = oldGroup.CellsList; + for (int i = 0; i < cellsList.Count; i++) + { + IntVec3 intVec = cellsList[i]; + this.groupGrid[intVec.x, intVec.y, intVec.z] = null; + } + this.map.listerHaulables.Notify_SlotGroupChanged(oldGroup); } - this.map.listerHaulables.Notify_SlotGroupChanged(oldGroup); } public void Notify_GroupChangedPriority() @@ -110,14 +123,7 @@ public void SetCellFor(IntVec3 c, SlotGroup group) { if (this.SlotGroupAt(c) != null) { - Log.Error(string.Concat(new object[] - { - group, - " overwriting slot group square ", - c, - " of ", - this.SlotGroupAt(c) - })); + Log.Error(group + " overwriting slot group square " + c + " of " + this.SlotGroupAt(c)); } this.groupGrid[c.x, c.y, c.z] = group; } @@ -126,14 +132,7 @@ public void ClearCellFor(IntVec3 c, SlotGroup group) { if (this.SlotGroupAt(c) != group) { - Log.Error(string.Concat(new object[] - { - group, - " clearing group grid square ", - c, - " containing ", - this.SlotGroupAt(c) - })); + Log.Error(group + " clearing group grid square " + c + " containing " + this.SlotGroupAt(c)); } this.groupGrid[c.x, c.y, c.z] = null; } diff --git a/Assembly-CSharp/RimWorld/SmokepopBelt.cs b/Assembly-CSharp/RimWorld/SmokepopBelt.cs index 24d38b043..52cab25fa 100644 --- a/Assembly-CSharp/RimWorld/SmokepopBelt.cs +++ b/Assembly-CSharp/RimWorld/SmokepopBelt.cs @@ -1,4 +1,3 @@ -using System; using Verse; namespace RimWorld diff --git a/Assembly-CSharp/RimWorld/SmoothFloorDesignatorUtility.cs b/Assembly-CSharp/RimWorld/SmoothFloorDesignatorUtility.cs index 9ce2ac06c..844887d15 100644 --- a/Assembly-CSharp/RimWorld/SmoothFloorDesignatorUtility.cs +++ b/Assembly-CSharp/RimWorld/SmoothFloorDesignatorUtility.cs @@ -1,4 +1,3 @@ -using System; using Verse; namespace RimWorld diff --git a/Assembly-CSharp/RimWorld/SocialCardUtility.cs b/Assembly-CSharp/RimWorld/SocialCardUtility.cs index 5d5760a6a..c0f434cb4 100644 --- a/Assembly-CSharp/RimWorld/SocialCardUtility.cs +++ b/Assembly-CSharp/RimWorld/SocialCardUtility.cs @@ -22,12 +22,12 @@ private class CachedSocialTabEntry public List relations = new List(); } - private class CachedSocialTabEntryComparer : IComparer + private class CachedSocialTabEntryComparer : IComparer { - public int Compare(SocialCardUtility.CachedSocialTabEntry a, SocialCardUtility.CachedSocialTabEntry b) + public int Compare(CachedSocialTabEntry a, CachedSocialTabEntry b) { - bool flag = a.relations.Any(); - bool flag2 = b.relations.Any(); + bool flag = a.relations.Any(); + bool flag2 = b.relations.Any(); if (flag != flag2) { return flag2.CompareTo(flag); @@ -77,7 +77,7 @@ public int Compare(SocialCardUtility.CachedSocialTabEntry a, SocialCardUtility.C private static bool showAllRelations; - private static List cachedEntries = new List(); + private static List cachedEntries = new List(); private static Pawn cachedForPawn; @@ -87,7 +87,7 @@ public int Compare(SocialCardUtility.CachedSocialTabEntry a, SocialCardUtility.C private static readonly Color HighlightColor = new Color(0.5f, 0.5f, 0.5f, 1f); - private static SocialCardUtility.CachedSocialTabEntryComparer CachedEntriesComparer = new SocialCardUtility.CachedSocialTabEntryComparer(); + private static CachedSocialTabEntryComparer CachedEntriesComparer = new CachedSocialTabEntryComparer(); private static HashSet tmpCached = new HashSet(); @@ -99,43 +99,42 @@ public static void DrawSocialCard(Rect rect, Pawn pawn) { GUI.BeginGroup(rect); Text.Font = GameFont.Small; - Rect rect2 = new Rect(0f, 20f, rect.width, rect.height - 20f); - Rect rect3 = rect2.ContractedBy(10f); - Rect rect4 = rect3; - Rect rect5 = rect3; - rect4.height *= 0.63f; - rect5.y = rect4.yMax + 17f; - rect5.yMax = rect3.yMax; + Rect rect2 = new Rect(0f, 20f, rect.width, (float)(rect.height - 20.0)); + Rect rect3; + Rect rect4 = rect3 = rect2.ContractedBy(10f); + Rect rect5 = rect4; + rect3.height *= 0.63f; + rect5.y = (float)(rect3.yMax + 17.0); + rect5.yMax = rect4.yMax; GUI.color = new Color(1f, 1f, 1f, 0.5f); - Widgets.DrawLineHorizontal(0f, (rect4.yMax + rect5.y) / 2f, rect.width); + Widgets.DrawLineHorizontal(0f, (float)((rect3.yMax + rect5.y) / 2.0), rect.width); GUI.color = Color.white; if (Prefs.DevMode) { Rect rect6 = new Rect(5f, 5f, rect.width, 22f); SocialCardUtility.DrawDebugOptions(rect6, pawn); } - SocialCardUtility.DrawRelationsAndOpinions(rect4, pawn); + SocialCardUtility.DrawRelationsAndOpinions(rect3, pawn); SocialCardUtility.DrawInteractionsLog(rect5, pawn); GUI.EndGroup(); } private static void CheckRecache(Pawn selPawnForSocialInfo) { - if (SocialCardUtility.cachedForPawn != selPawnForSocialInfo || Time.frameCount % 20 == 0) - { - SocialCardUtility.Recache(selPawnForSocialInfo); - } + if (((SocialCardUtility.cachedForPawn == selPawnForSocialInfo) ? (Time.frameCount % 20) : 0) != 0) + return; + SocialCardUtility.Recache(selPawnForSocialInfo); } private static void Recache(Pawn selPawnForSocialInfo) { SocialCardUtility.cachedForPawn = selPawnForSocialInfo; SocialCardUtility.tmpToCache.Clear(); - foreach (Pawn current in selPawnForSocialInfo.relations.RelatedPawns) + foreach (Pawn relatedPawn in selPawnForSocialInfo.relations.RelatedPawns) { - if (SocialCardUtility.ShouldShowPawnRelations(current, selPawnForSocialInfo)) + if (SocialCardUtility.ShouldShowPawnRelations(relatedPawn, selPawnForSocialInfo)) { - SocialCardUtility.tmpToCache.Add(current); + SocialCardUtility.tmpToCache.Add(relatedPawn); } } List list = null; @@ -152,30 +151,36 @@ private static void Recache(Pawn selPawnForSocialInfo) for (int i = 0; i < list.Count; i++) { Pawn pawn = list[i]; - if (pawn.RaceProps.Humanlike && pawn != selPawnForSocialInfo && SocialCardUtility.ShouldShowPawnRelations(pawn, selPawnForSocialInfo) && !SocialCardUtility.tmpToCache.Contains(pawn)) + if ((pawn.RaceProps.Humanlike ? ((pawn != selPawnForSocialInfo) ? (SocialCardUtility.ShouldShowPawnRelations(pawn, selPawnForSocialInfo) ? ((!SocialCardUtility.tmpToCache.Contains(pawn)) ? ((selPawnForSocialInfo.relations.OpinionOf(pawn) != 0) ? 1 : pawn.relations.OpinionOf(selPawnForSocialInfo)) : 0) : 0) : 0) : 0) != 0) { - if (selPawnForSocialInfo.relations.OpinionOf(pawn) != 0 || pawn.relations.OpinionOf(selPawnForSocialInfo) != 0) - { - SocialCardUtility.tmpToCache.Add(pawn); - } + SocialCardUtility.tmpToCache.Add(pawn); } } } - SocialCardUtility.cachedEntries.RemoveAll((SocialCardUtility.CachedSocialTabEntry x) => !SocialCardUtility.tmpToCache.Contains(x.otherPawn)); + SocialCardUtility.cachedEntries.RemoveAll((Predicate)((CachedSocialTabEntry x) => !SocialCardUtility.tmpToCache.Contains(x.otherPawn))); SocialCardUtility.tmpCached.Clear(); for (int j = 0; j < SocialCardUtility.cachedEntries.Count; j++) { SocialCardUtility.tmpCached.Add(SocialCardUtility.cachedEntries[j].otherPawn); } - foreach (Pawn current2 in SocialCardUtility.tmpToCache) + HashSet.Enumerator enumerator2 = SocialCardUtility.tmpToCache.GetEnumerator(); + try { - if (!SocialCardUtility.tmpCached.Contains(current2)) + while (enumerator2.MoveNext()) { - SocialCardUtility.CachedSocialTabEntry cachedSocialTabEntry = new SocialCardUtility.CachedSocialTabEntry(); - cachedSocialTabEntry.otherPawn = current2; - SocialCardUtility.cachedEntries.Add(cachedSocialTabEntry); + Pawn current2 = enumerator2.Current; + if (!SocialCardUtility.tmpCached.Contains(current2)) + { + CachedSocialTabEntry cachedSocialTabEntry = new CachedSocialTabEntry(); + cachedSocialTabEntry.otherPawn = current2; + SocialCardUtility.cachedEntries.Add(cachedSocialTabEntry); + } } } + finally + { + ((IDisposable)(object)enumerator2).Dispose(); + } SocialCardUtility.tmpCached.Clear(); SocialCardUtility.tmpToCache.Clear(); for (int k = 0; k < SocialCardUtility.cachedEntries.Count; k++) @@ -187,19 +192,27 @@ private static void Recache(Pawn selPawnForSocialInfo) private static bool ShouldShowPawnRelations(Pawn pawn, Pawn selPawnForSocialInfo) { - return SocialCardUtility.showAllRelations || pawn.relations.everSeenByPlayer; + if (SocialCardUtility.showAllRelations) + { + return true; + } + if (pawn.relations.everSeenByPlayer) + { + return true; + } + return false; } - private static void RecacheEntry(SocialCardUtility.CachedSocialTabEntry entry, Pawn selPawnForSocialInfo) + private static void RecacheEntry(CachedSocialTabEntry entry, Pawn selPawnForSocialInfo) { entry.opinionOfMe = entry.otherPawn.relations.OpinionOf(selPawnForSocialInfo); entry.opinionOfOtherPawn = selPawnForSocialInfo.relations.OpinionOf(entry.otherPawn); entry.relations.Clear(); - foreach (PawnRelationDef current in selPawnForSocialInfo.GetRelations(entry.otherPawn)) + foreach (PawnRelationDef relation in selPawnForSocialInfo.GetRelations(entry.otherPawn)) { - entry.relations.Add(current); + entry.relations.Add(relation); } - entry.relations.Sort((PawnRelationDef a, PawnRelationDef b) => b.importance.CompareTo(a.importance)); + entry.relations.Sort((Comparison)((PawnRelationDef a, PawnRelationDef b) => b.importance.CompareTo(a.importance))); } public static void DrawRelationsAndOpinions(Rect rect, Pawn selPawnForSocialInfo) @@ -213,7 +226,7 @@ public static void DrawRelationsAndOpinions(Rect rect, Pawn selPawnForSocialInfo Text.Font = GameFont.Small; GUI.color = Color.white; Rect outRect = new Rect(0f, 0f, rect.width, rect.height); - Rect viewRect = new Rect(0f, 0f, rect.width - 16f, SocialCardUtility.listScrollViewHeight); + Rect viewRect = new Rect(0f, 0f, (float)(rect.width - 16.0), SocialCardUtility.listScrollViewHeight); Widgets.BeginScrollView(outRect, ref SocialCardUtility.listScrollPosition, viewRect, true); float num = 0f; float y = SocialCardUtility.listScrollPosition.y; @@ -227,7 +240,7 @@ public static void DrawRelationsAndOpinions(Rect rect, Pawn selPawnForSocialInfo } num += rowHeight; } - if (!SocialCardUtility.cachedEntries.Any()) + if (!SocialCardUtility.cachedEntries.Any()) { GUI.color = Color.gray; Text.Anchor = TextAnchor.UpperCenter; @@ -237,14 +250,14 @@ public static void DrawRelationsAndOpinions(Rect rect, Pawn selPawnForSocialInfo } if (Event.current.type == EventType.Layout) { - SocialCardUtility.listScrollViewHeight = num + 30f; + SocialCardUtility.listScrollViewHeight = (float)(num + 30.0); } Widgets.EndScrollView(); GUI.EndGroup(); GUI.color = Color.white; } - private static void DrawPawnRow(float y, float width, SocialCardUtility.CachedSocialTabEntry entry, Pawn selPawnForSocialInfo) + private static void DrawPawnRow(float y, float width, CachedSocialTabEntry entry, Pawn selPawnForSocialInfo) { float rowHeight = SocialCardUtility.GetRowHeight(entry, width, selPawnForSocialInfo); Rect rect = new Rect(0f, y, width, rowHeight); @@ -254,28 +267,22 @@ private static void DrawPawnRow(float y, float width, SocialCardUtility.CachedSo GUI.color = SocialCardUtility.HighlightColor; GUI.DrawTexture(rect, TexUI.HighlightTex); } - TooltipHandler.TipRegion(rect, () => SocialCardUtility.GetPawnRowTooltip(entry, selPawnForSocialInfo), entry.otherPawn.thingIDNumber * 13 + selPawnForSocialInfo.thingIDNumber); + TooltipHandler.TipRegion(rect, (Func)(() => SocialCardUtility.GetPawnRowTooltip(entry, selPawnForSocialInfo)), entry.otherPawn.thingIDNumber * 13 + selPawnForSocialInfo.thingIDNumber); if (Widgets.ButtonInvisible(rect, false)) { if (Current.ProgramState == ProgramState.Playing) { if (otherPawn.Dead) { - Messages.Message("MessageCantSelectDeadPawn".Translate(new object[] - { - otherPawn.LabelShort - }).CapitalizeFirst(), MessageSound.RejectInput); + Messages.Message("MessageCantSelectDeadPawn".Translate(otherPawn.LabelShort).CapitalizeFirst(), MessageSound.RejectInput); } else if (otherPawn.SpawnedOrAnyParentSpawned || otherPawn.IsCaravanMember()) { - CameraJumper.TryJumpAndSelect(otherPawn); + CameraJumper.TryJumpAndSelect((Thing)otherPawn); } else { - Messages.Message("MessageCantSelectOffMapPawn".Translate(new object[] - { - otherPawn.LabelShort - }).CapitalizeFirst(), MessageSound.RejectInput); + Messages.Message("MessageCantSelectOffMapPawn".Translate(otherPawn.LabelShort).CapitalizeFirst(), MessageSound.RejectInput); } } else if (Find.GameInitData.startingPawns.Contains(otherPawn)) @@ -288,59 +295,59 @@ private static void DrawPawnRow(float y, float width, SocialCardUtility.CachedSo } } } - float width2; - float width3; - float width4; - float width5; - float width6; + float width2 = default(float); + float width3 = default(float); + float width4 = default(float); + float width5 = default(float); + float width6 = default(float); SocialCardUtility.CalculateColumnsWidths(width, out width2, out width3, out width4, out width5, out width6); - Rect rect2 = new Rect(5f, y + 3f, width2, rowHeight - 3f); + Rect rect2 = new Rect(5f, (float)(y + 3.0), width2, (float)(rowHeight - 3.0)); SocialCardUtility.DrawRelationLabel(entry, rect2, selPawnForSocialInfo); - Rect rect3 = new Rect(rect2.xMax, y + 3f, width3, rowHeight - 3f); + Rect rect3 = new Rect(rect2.xMax, (float)(y + 3.0), width3, (float)(rowHeight - 3.0)); SocialCardUtility.DrawPawnLabel(otherPawn, rect3); - Rect rect4 = new Rect(rect3.xMax, y + 3f, width4, rowHeight - 3f); + Rect rect4 = new Rect(rect3.xMax, (float)(y + 3.0), width4, (float)(rowHeight - 3.0)); SocialCardUtility.DrawMyOpinion(entry, rect4, selPawnForSocialInfo); - Rect rect5 = new Rect(rect4.xMax, y + 3f, width5, rowHeight - 3f); + Rect rect5 = new Rect(rect4.xMax, (float)(y + 3.0), width5, (float)(rowHeight - 3.0)); SocialCardUtility.DrawHisOpinion(entry, rect5, selPawnForSocialInfo); - Rect rect6 = new Rect(rect5.xMax, y + 3f, width6, rowHeight - 3f); + Rect rect6 = new Rect(rect5.xMax, (float)(y + 3.0), width6, (float)(rowHeight - 3.0)); SocialCardUtility.DrawPawnSituationLabel(entry.otherPawn, rect6, selPawnForSocialInfo); } - private static float GetRowHeight(SocialCardUtility.CachedSocialTabEntry entry, float rowWidth, Pawn selPawnForSocialInfo) + private static float GetRowHeight(CachedSocialTabEntry entry, float rowWidth, Pawn selPawnForSocialInfo) { - float width; - float width2; - float num; - float num2; - float num3; + float width = default(float); + float width2 = default(float); + float num = default(float); + float num2 = default(float); + float num3 = default(float); SocialCardUtility.CalculateColumnsWidths(rowWidth, out width, out width2, out num, out num2, out num3); - float num4 = 0f; - num4 = Mathf.Max(num4, Text.CalcHeight(SocialCardUtility.GetRelationsString(entry, selPawnForSocialInfo), width)); - num4 = Mathf.Max(num4, Text.CalcHeight(SocialCardUtility.GetPawnLabel(entry.otherPawn), width2)); - return num4 + 3f; + float a = 0f; + a = Mathf.Max(a, Text.CalcHeight(SocialCardUtility.GetRelationsString(entry, selPawnForSocialInfo), width)); + a = Mathf.Max(a, Text.CalcHeight(SocialCardUtility.GetPawnLabel(entry.otherPawn), width2)); + return (float)(a + 3.0); } private static void CalculateColumnsWidths(float rowWidth, out float relationsWidth, out float pawnLabelWidth, out float myOpinionWidth, out float hisOpinionWidth, out float pawnSituationLabelWidth) { - float num = rowWidth - 10f; - relationsWidth = num * 0.23f; - pawnLabelWidth = num * 0.41f; - myOpinionWidth = num * 0.075f; - hisOpinionWidth = num * 0.085f; - pawnSituationLabelWidth = num * 0.2f; - if (myOpinionWidth < 25f) - { - pawnLabelWidth -= 25f - myOpinionWidth; + float num = (float)(rowWidth - 10.0); + relationsWidth = (float)(num * 0.23000000417232513); + pawnLabelWidth = (float)(num * 0.40999999642372131); + myOpinionWidth = (float)(num * 0.075000002980232239); + hisOpinionWidth = (float)(num * 0.085000000894069672); + pawnSituationLabelWidth = (float)(num * 0.20000000298023224); + if (myOpinionWidth < 25.0) + { + pawnLabelWidth -= (float)(25.0 - myOpinionWidth); myOpinionWidth = 25f; } - if (hisOpinionWidth < 35f) + if (hisOpinionWidth < 35.0) { - pawnLabelWidth -= 35f - hisOpinionWidth; + pawnLabelWidth -= (float)(35.0 - hisOpinionWidth); hisOpinionWidth = 35f; } } - private static void DrawRelationLabel(SocialCardUtility.CachedSocialTabEntry entry, Rect rect, Pawn selPawnForSocialInfo) + private static void DrawRelationLabel(CachedSocialTabEntry entry, Rect rect, Pawn selPawnForSocialInfo) { string relationsString = SocialCardUtility.GetRelationsString(entry, selPawnForSocialInfo); if (!relationsString.NullOrEmpty()) @@ -356,27 +363,25 @@ private static void DrawPawnLabel(Pawn pawn, Rect rect) Widgets.Label(rect, SocialCardUtility.GetPawnLabel(pawn)); } - private static void DrawMyOpinion(SocialCardUtility.CachedSocialTabEntry entry, Rect rect, Pawn selPawnForSocialInfo) + private static void DrawMyOpinion(CachedSocialTabEntry entry, Rect rect, Pawn selPawnForSocialInfo) { - if (!entry.otherPawn.RaceProps.Humanlike || !selPawnForSocialInfo.RaceProps.Humanlike) + if (entry.otherPawn.RaceProps.Humanlike && selPawnForSocialInfo.RaceProps.Humanlike) { - return; + int opinionOfOtherPawn = entry.opinionOfOtherPawn; + GUI.color = SocialCardUtility.OpinionLabelColor(opinionOfOtherPawn); + Widgets.Label(rect, opinionOfOtherPawn.ToStringWithSign()); } - int opinionOfOtherPawn = entry.opinionOfOtherPawn; - GUI.color = SocialCardUtility.OpinionLabelColor(opinionOfOtherPawn); - Widgets.Label(rect, opinionOfOtherPawn.ToStringWithSign()); } - private static void DrawHisOpinion(SocialCardUtility.CachedSocialTabEntry entry, Rect rect, Pawn selPawnForSocialInfo) + private static void DrawHisOpinion(CachedSocialTabEntry entry, Rect rect, Pawn selPawnForSocialInfo) { - if (!entry.otherPawn.RaceProps.Humanlike || !selPawnForSocialInfo.RaceProps.Humanlike) + if (entry.otherPawn.RaceProps.Humanlike && selPawnForSocialInfo.RaceProps.Humanlike) { - return; + int opinionOfMe = entry.opinionOfMe; + Color color = SocialCardUtility.OpinionLabelColor(opinionOfMe); + GUI.color = new Color(color.r, color.g, color.b, 0.4f); + Widgets.Label(rect, "(" + opinionOfMe.ToStringWithSign() + ")"); } - int opinionOfMe = entry.opinionOfMe; - Color color = SocialCardUtility.OpinionLabelColor(opinionOfMe); - GUI.color = new Color(color.r, color.g, color.b, 0.4f); - Widgets.Label(rect, "(" + opinionOfMe.ToStringWithSign() + ")"); } private static void DrawPawnSituationLabel(Pawn pawn, Rect rect, Pawn selPawnForSocialInfo) @@ -431,62 +436,52 @@ public static string GetPawnSituationLabel(Pawn pawn, Pawn fromPOV) return "FactionLeader".Translate(); } Faction faction = pawn.Faction; - if (faction == fromPOV.Faction) - { - return string.Empty; - } - if (faction == null || fromPOV.Faction == null) + if (faction != fromPOV.Faction) { + if (faction != null && fromPOV.Faction != null) + { + if (!faction.HostileTo(fromPOV.Faction)) + { + return "Neutral".Translate() + ", " + faction.Name; + } + return "Hostile".Translate() + ", " + faction.Name; + } return "Neutral".Translate(); } - if (!faction.HostileTo(fromPOV.Faction)) - { - return "Neutral".Translate() + ", " + faction.Name; - } - return "Hostile".Translate() + ", " + faction.Name; + return string.Empty; } - private static string GetRelationsString(SocialCardUtility.CachedSocialTabEntry entry, Pawn selPawnForSocialInfo) + private static string GetRelationsString(CachedSocialTabEntry entry, Pawn selPawnForSocialInfo) { string text = string.Empty; - if (entry.relations.Count != 0) + if (entry.relations.Count == 0) { - for (int i = 0; i < entry.relations.Count; i++) + if (entry.opinionOfOtherPawn < -20) { - PawnRelationDef pawnRelationDef = entry.relations[i]; - if (!text.NullOrEmpty()) - { - text = text + ", " + pawnRelationDef.GetGenderSpecificLabel(entry.otherPawn); - } - else - { - text = pawnRelationDef.GetGenderSpecificLabelCap(entry.otherPawn); - } + return "Rival".Translate(); } - return text; - } - if (entry.opinionOfOtherPawn < -20) - { - return "Rival".Translate(); + if (entry.opinionOfOtherPawn > 20) + { + return "Friend".Translate(); + } + return "Acquaintance".Translate(); } - if (entry.opinionOfOtherPawn > 20) + for (int i = 0; i < entry.relations.Count; i++) { - return "Friend".Translate(); + PawnRelationDef pawnRelationDef = entry.relations[i]; + text = (text.NullOrEmpty() ? pawnRelationDef.GetGenderSpecificLabelCap(entry.otherPawn) : (text + ", " + pawnRelationDef.GetGenderSpecificLabel(entry.otherPawn))); } - return "Acquaintance".Translate(); + return text; } - private static string GetPawnRowTooltip(SocialCardUtility.CachedSocialTabEntry entry, Pawn selPawnForSocialInfo) + private static string GetPawnRowTooltip(CachedSocialTabEntry entry, Pawn selPawnForSocialInfo) { StringBuilder stringBuilder = new StringBuilder(); if (entry.otherPawn.RaceProps.Humanlike && selPawnForSocialInfo.RaceProps.Humanlike) { stringBuilder.AppendLine(selPawnForSocialInfo.relations.OpinionExplanation(entry.otherPawn)); stringBuilder.AppendLine(); - stringBuilder.Append("SomeonesOpinionOfMe".Translate(new object[] - { - entry.otherPawn.LabelShort - })); + stringBuilder.Append("SomeonesOpinionOfMe".Translate(entry.otherPawn.LabelShort)); stringBuilder.Append(": "); stringBuilder.Append(entry.opinionOfMe.ToStringWithSign()); } @@ -512,7 +507,7 @@ private static string GetPawnRowTooltip(SocialCardUtility.CachedSocialTabEntry e private static void DrawInteractionsLog(Rect rect, Pawn pawn) { - float width = rect.width - 26f - 3f; + float width = (float)(rect.width - 26.0 - 3.0); List allEntries = Find.PlayLog.AllEntries; SocialCardUtility.logStrings.Clear(); float num = 0f; @@ -526,12 +521,10 @@ private static void DrawInteractionsLog(Rect rect, Pawn pawn) num += Mathf.Max(26f, Text.CalcHeight(text, width)); num2++; if (num2 >= 12) - { break; - } } } - Rect viewRect = new Rect(0f, 0f, rect.width - 16f, num); + Rect viewRect = new Rect(0f, 0f, (float)(rect.width - 16.0), num); Widgets.BeginScrollView(rect, ref SocialCardUtility.logScrollPosition, viewRect, true); float num3 = 0f; for (int j = 0; j < SocialCardUtility.logStrings.Count; j++) @@ -543,7 +536,7 @@ private static void DrawInteractionsLog(Rect rect, Pawn pawn) GUI.color = new Color(1f, 1f, 1f, 0.5f); } float num4 = Mathf.Max(26f, Text.CalcHeight(first, width)); - if (entry.Icon != null) + if ((UnityEngine.Object)entry.Icon != (UnityEngine.Object)null) { Rect position = new Rect(0f, num3, 26f, 26f); GUI.DrawTexture(position, entry.Icon); @@ -551,7 +544,7 @@ private static void DrawInteractionsLog(Rect rect, Pawn pawn) Rect rect2 = new Rect(29f, num3, width, num4); Widgets.DrawHighlightIfMouseover(rect2); Widgets.Label(rect2, first); - TooltipHandler.TipRegion(rect2, () => entry.GetTipString(), 613261 + j * 611); + TooltipHandler.TipRegion(rect2, (Func)(() => entry.GetTipString()), 613261 + j * 611); if (Widgets.ButtonInvisible(rect2, false)) { entry.ClickedFromPOV(pawn); @@ -569,161 +562,119 @@ private static void DrawDebugOptions(Rect rect, Pawn pawn) if (Widgets.ButtonText(new Rect(150f, 0f, 115f, 22f), "Debug info", true, false, true)) { List list = new List(); - list.Add(new FloatMenuOption("AttractionTo", delegate + list.Add(new FloatMenuOption("AttractionTo", (Action)delegate() { - StringBuilder stringBuilder = new StringBuilder(); - stringBuilder.AppendLine("My gender: " + pawn.gender); - stringBuilder.AppendLine("My age: " + pawn.ageTracker.AgeBiologicalYears); - stringBuilder.AppendLine(); - IOrderedEnumerable orderedEnumerable = from x in pawn.Map.mapPawns.AllPawnsSpawned + StringBuilder stringBuilder5 = new StringBuilder(); + stringBuilder5.AppendLine("My gender: " + pawn.gender); + stringBuilder5.AppendLine("My age: " + pawn.ageTracker.AgeBiologicalYears); + stringBuilder5.AppendLine(); + IOrderedEnumerable orderedEnumerable4 = from x in pawn.Map.mapPawns.AllPawnsSpawned where x.def == pawn.def orderby pawn.relations.SecondaryRomanceChanceFactor(x) descending select x; - foreach (Pawn current in orderedEnumerable) + foreach (Pawn item in orderedEnumerable4) { - if (current != pawn) + if (item != pawn) { - stringBuilder.AppendLine(string.Concat(new object[] - { - current.LabelShort, - " (", - current.gender, - ", age: ", - current.ageTracker.AgeBiologicalYears, - ", compat: ", - pawn.relations.CompatibilityWith(current).ToString("F2"), - "): ", - pawn.relations.SecondaryRomanceChanceFactor(current).ToStringPercent("F0"), - " [vs ", - current.relations.SecondaryRomanceChanceFactor(pawn).ToStringPercent("F0"), - "]" - })); + stringBuilder5.AppendLine(item.LabelShort + " (" + item.gender + ", age: " + item.ageTracker.AgeBiologicalYears + ", compat: " + pawn.relations.CompatibilityWith(item).ToString("F2") + "): " + pawn.relations.SecondaryRomanceChanceFactor(item).ToStringPercent("F0") + " [vs " + item.relations.SecondaryRomanceChanceFactor(pawn).ToStringPercent("F0") + "]"); } } - Find.WindowStack.Add(new Dialog_MessageBox(stringBuilder.ToString(), null, null, null, null, null, false)); + Find.WindowStack.Add(new Dialog_MessageBox(stringBuilder5.ToString(), (string)null, null, (string)null, null, (string)null, false)); }, MenuOptionPriority.Default, null, null, 0f, null, null)); - list.Add(new FloatMenuOption("CompatibilityTo", delegate + list.Add(new FloatMenuOption("CompatibilityTo", (Action)delegate() { - StringBuilder stringBuilder = new StringBuilder(); - stringBuilder.AppendLine("My age: " + pawn.ageTracker.AgeBiologicalYears); - stringBuilder.AppendLine(); - IOrderedEnumerable orderedEnumerable = from x in pawn.Map.mapPawns.AllPawnsSpawned + StringBuilder stringBuilder4 = new StringBuilder(); + stringBuilder4.AppendLine("My age: " + pawn.ageTracker.AgeBiologicalYears); + stringBuilder4.AppendLine(); + IOrderedEnumerable orderedEnumerable3 = from x in pawn.Map.mapPawns.AllPawnsSpawned where x.def == pawn.def orderby pawn.relations.CompatibilityWith(x) descending select x; - foreach (Pawn current in orderedEnumerable) + foreach (Pawn item in orderedEnumerable3) { - if (current != pawn) + if (item != pawn) { - stringBuilder.AppendLine(string.Concat(new object[] - { - current.LabelShort, - " (", - current.KindLabel, - ", age: ", - current.ageTracker.AgeBiologicalYears, - "): ", - pawn.relations.CompatibilityWith(current).ToString("0.##") - })); + stringBuilder4.AppendLine(item.LabelShort + " (" + item.KindLabel + ", age: " + item.ageTracker.AgeBiologicalYears + "): " + pawn.relations.CompatibilityWith(item).ToString("0.##")); } } - Find.WindowStack.Add(new Dialog_MessageBox(stringBuilder.ToString(), null, null, null, null, null, false)); + Find.WindowStack.Add(new Dialog_MessageBox(stringBuilder4.ToString(), (string)null, null, (string)null, null, (string)null, false)); }, MenuOptionPriority.Default, null, null, 0f, null, null)); if (pawn.RaceProps.Humanlike) { - list.Add(new FloatMenuOption("Interaction chance", delegate + list.Add(new FloatMenuOption("Interaction chance", (Action)delegate() { - StringBuilder stringBuilder = new StringBuilder(); - stringBuilder.AppendLine("(selected pawn is the initiator)"); - stringBuilder.AppendLine("(\"fight chance\" is the chance that the receiver will start social fight)"); - stringBuilder.AppendLine("Interaction chance (real chance, not just weights):"); - IOrderedEnumerable orderedEnumerable = from x in pawn.Map.mapPawns.AllPawnsSpawned + StringBuilder stringBuilder3 = new StringBuilder(); + stringBuilder3.AppendLine("(selected pawn is the initiator)"); + stringBuilder3.AppendLine("(\"fight chance\" is the chance that the receiver will start social fight)"); + stringBuilder3.AppendLine("Interaction chance (real chance, not just weights):"); + IOrderedEnumerable orderedEnumerable2 = from x in pawn.Map.mapPawns.AllPawnsSpawned where x.RaceProps.Humanlike - orderby (x.Faction != null) ? x.Faction.loadID : -1 + orderby (x.Faction != null) ? x.Faction.loadID : (-1) select x; - foreach (Pawn c in orderedEnumerable) + using (IEnumerator enumerator2 = orderedEnumerable2.GetEnumerator()) { - if (c != pawn) + Pawn c; + while (enumerator2.MoveNext()) { - stringBuilder.AppendLine(); - stringBuilder.AppendLine(string.Concat(new object[] + c = enumerator2.Current; + if (c != pawn) { - c.LabelShort, - " (", - c.KindLabel, - ", ", - c.gender, - ", age: ", - c.ageTracker.AgeBiologicalYears, - ", compat: ", - pawn.relations.CompatibilityWith(c).ToString("F2"), - ", attr: ", - pawn.relations.SecondaryRomanceChanceFactor(c).ToStringPercent("F0"), - "):" - })); - List list2 = (from x in DefDatabase.AllDefs - where x.Worker.RandomSelectionWeight(pawn, c) > 0f - orderby x.Worker.RandomSelectionWeight(pawn, c) descending - select x).ToList(); - float num = list2.Sum((InteractionDef x) => x.Worker.RandomSelectionWeight(pawn, c)); - foreach (InteractionDef current in list2) - { - float f = c.interactions.SocialFightChance(current, pawn); - float f2 = current.Worker.RandomSelectionWeight(pawn, c) / num; - stringBuilder.AppendLine(string.Concat(new string[] - { - " ", - current.defName, - ": ", - f2.ToStringPercent(), - " (fight chance: ", - f.ToStringPercent("F2"), - ")" - })); - if (current == InteractionDefOf.RomanceAttempt) + stringBuilder3.AppendLine(); + stringBuilder3.AppendLine(c.LabelShort + " (" + c.KindLabel + ", " + c.gender + ", age: " + c.ageTracker.AgeBiologicalYears + ", compat: " + pawn.relations.CompatibilityWith(c).ToString("F2") + ", attr: " + pawn.relations.SecondaryRomanceChanceFactor(c).ToStringPercent("F0") + "):"); + List list2 = (from x in DefDatabase.AllDefs + where x.Worker.RandomSelectionWeight(pawn, c) > 0.0 + orderby x.Worker.RandomSelectionWeight(pawn, c) descending + select x).ToList(); + float num12 = list2.Sum((Func)((InteractionDef x) => x.Worker.RandomSelectionWeight(pawn, c))); + List.Enumerator enumerator3 = list2.GetEnumerator(); + try { - stringBuilder.AppendLine(" success chance: " + ((InteractionWorker_RomanceAttempt)current.Worker).SuccessChance(pawn, c).ToStringPercent()); + while (enumerator3.MoveNext()) + { + InteractionDef current2 = enumerator3.Current; + float f = c.interactions.SocialFightChance(current2, pawn); + float f2 = current2.Worker.RandomSelectionWeight(pawn, c) / num12; + stringBuilder3.AppendLine(" " + current2.defName + ": " + f2.ToStringPercent() + " (fight chance: " + f.ToStringPercent("F2") + ")"); + if (current2 == InteractionDefOf.RomanceAttempt) + { + stringBuilder3.AppendLine(" success chance: " + ((InteractionWorker_RomanceAttempt)current2.Worker).SuccessChance(pawn, c).ToStringPercent()); + } + else if (current2 == InteractionDefOf.MarriageProposal) + { + stringBuilder3.AppendLine(" acceptance chance: " + ((InteractionWorker_MarriageProposal)current2.Worker).AcceptanceChance(pawn, c).ToStringPercent()); + } + } } - else if (current == InteractionDefOf.MarriageProposal) + finally { - stringBuilder.AppendLine(" acceptance chance: " + ((InteractionWorker_MarriageProposal)current.Worker).AcceptanceChance(pawn, c).ToStringPercent()); + ((IDisposable)(object)enumerator3).Dispose(); } } } } - Find.WindowStack.Add(new Dialog_MessageBox(stringBuilder.ToString(), null, null, null, null, null, false)); + Find.WindowStack.Add(new Dialog_MessageBox(stringBuilder3.ToString(), (string)null, null, (string)null, null, (string)null, false)); }, MenuOptionPriority.Default, null, null, 0f, null, null)); - list.Add(new FloatMenuOption("Lovin' MTB", delegate + list.Add(new FloatMenuOption("Lovin' MTB", (Action)delegate() { - StringBuilder stringBuilder = new StringBuilder(); - stringBuilder.AppendLine("Lovin' MTB hours with pawn X."); - stringBuilder.AppendLine("Assuming both pawns are in bed and are partners."); - stringBuilder.AppendLine(); + StringBuilder stringBuilder2 = new StringBuilder(); + stringBuilder2.AppendLine("Lovin' MTB hours with pawn X."); + stringBuilder2.AppendLine("Assuming both pawns are in bed and are partners."); + stringBuilder2.AppendLine(); IOrderedEnumerable orderedEnumerable = from x in pawn.Map.mapPawns.AllPawnsSpawned where x.def == pawn.def orderby pawn.relations.SecondaryRomanceChanceFactor(x) descending select x; - foreach (Pawn current in orderedEnumerable) + foreach (Pawn item in orderedEnumerable) { - if (current != pawn) + if (item != pawn) { - stringBuilder.AppendLine(string.Concat(new object[] - { - current.LabelShort, - " (", - current.KindLabel, - ", age: ", - current.ageTracker.AgeBiologicalYears, - "): ", - LovePartnerRelationUtility.GetLovinMtbHours(pawn, current).ToString("F1"), - " h" - })); + stringBuilder2.AppendLine(item.LabelShort + " (" + item.KindLabel + ", age: " + item.ageTracker.AgeBiologicalYears + "): " + LovePartnerRelationUtility.GetLovinMtbHours(pawn, item).ToString("F1") + " h"); } } - Find.WindowStack.Add(new Dialog_MessageBox(stringBuilder.ToString(), null, null, null, null, null, false)); + Find.WindowStack.Add(new Dialog_MessageBox(stringBuilder2.ToString(), (string)null, null, (string)null, null, (string)null, false)); }, MenuOptionPriority.Default, null, null, 0f, null, null)); } - list.Add(new FloatMenuOption("Test per pawns pair compatibility factor probability", delegate + list.Add(new FloatMenuOption("Test per pawns pair compatibility factor probability", (Action)delegate() { StringBuilder stringBuilder = new StringBuilder(); int num = 0; @@ -740,31 +691,31 @@ orderby pawn.relations.SecondaryRomanceChanceFactor(x) descending { int otherPawnID = Rand.RangeInclusive(0, 30000); float num11 = pawn.relations.ConstantPerPawnsPairCompatibilityOffset(otherPawnID); - if (num11 < -3f) + if (num11 < -3.0) { num++; } - else if (num11 < -2f) + else if (num11 < -2.0) { num2++; } - else if (num11 < -1f) + else if (num11 < -1.0) { num3++; } - else if (num11 < 0f) + else if (num11 < 0.0) { num4++; } - else if (num11 < 1f) + else if (num11 < 1.0) { num5++; } - else if (num11 < 2f) + else if (num11 < 2.0) { num6++; } - else if (num11 < 3f) + else if (num11 < 3.0) { num7++; } @@ -781,19 +732,19 @@ orderby pawn.relations.SecondaryRomanceChanceFactor(x) descending num10 = num11; } } - stringBuilder.AppendLine("< -3: " + ((float)num / 10000f).ToStringPercent("F2")); - stringBuilder.AppendLine("< -2: " + ((float)num2 / 10000f).ToStringPercent("F2")); - stringBuilder.AppendLine("< -1: " + ((float)num3 / 10000f).ToStringPercent("F2")); - stringBuilder.AppendLine("< 0: " + ((float)num4 / 10000f).ToStringPercent("F2")); - stringBuilder.AppendLine("< 1: " + ((float)num5 / 10000f).ToStringPercent("F2")); - stringBuilder.AppendLine("< 2: " + ((float)num6 / 10000f).ToStringPercent("F2")); - stringBuilder.AppendLine("< 3: " + ((float)num7 / 10000f).ToStringPercent("F2")); - stringBuilder.AppendLine("> 3: " + ((float)num8 / 10000f).ToStringPercent("F2")); + stringBuilder.AppendLine("< -3: " + ((float)((float)num / 10000.0)).ToStringPercent("F2")); + stringBuilder.AppendLine("< -2: " + ((float)((float)num2 / 10000.0)).ToStringPercent("F2")); + stringBuilder.AppendLine("< -1: " + ((float)((float)num3 / 10000.0)).ToStringPercent("F2")); + stringBuilder.AppendLine("< 0: " + ((float)((float)num4 / 10000.0)).ToStringPercent("F2")); + stringBuilder.AppendLine("< 1: " + ((float)((float)num5 / 10000.0)).ToStringPercent("F2")); + stringBuilder.AppendLine("< 2: " + ((float)((float)num6 / 10000.0)).ToStringPercent("F2")); + stringBuilder.AppendLine("< 3: " + ((float)((float)num7 / 10000.0)).ToStringPercent("F2")); + stringBuilder.AppendLine("> 3: " + ((float)((float)num8 / 10000.0)).ToStringPercent("F2")); stringBuilder.AppendLine(); stringBuilder.AppendLine("trials: " + 10000); stringBuilder.AppendLine("min: " + num10); stringBuilder.AppendLine("max: " + num9); - Find.WindowStack.Add(new Dialog_MessageBox(stringBuilder.ToString(), null, null, null, null, null, false)); + Find.WindowStack.Add(new Dialog_MessageBox(stringBuilder.ToString(), (string)null, null, (string)null, null, (string)null, false)); }, MenuOptionPriority.Default, null, null, 0f, null, null)); Find.WindowStack.Add(new FloatMenu(list)); } diff --git a/Assembly-CSharp/RimWorld/SocialProperness.cs b/Assembly-CSharp/RimWorld/SocialProperness.cs index 5e2455206..2e95cc8de 100644 --- a/Assembly-CSharp/RimWorld/SocialProperness.cs +++ b/Assembly-CSharp/RimWorld/SocialProperness.cs @@ -1,4 +1,3 @@ -using System; using Verse; namespace RimWorld diff --git a/Assembly-CSharp/RimWorld/SolidBioDatabase.cs b/Assembly-CSharp/RimWorld/SolidBioDatabase.cs index 71872c34e..bed0b51d3 100644 --- a/Assembly-CSharp/RimWorld/SolidBioDatabase.cs +++ b/Assembly-CSharp/RimWorld/SolidBioDatabase.cs @@ -1,4 +1,3 @@ -using System; using System.Collections.Generic; using Verse; @@ -15,28 +14,28 @@ public static void Clear() public static void LoadAllBios() { - foreach (PawnBio current in DirectXmlLoader.LoadXmlDataInResourcesFolder("Backstories/Solid")) + foreach (PawnBio item in DirectXmlLoader.LoadXmlDataInResourcesFolder("Backstories/Solid")) { - current.name.ResolveMissingPieces(null); - if (current.childhood == null || current.adulthood == null) + item.name.ResolveMissingPieces((string)null); + if (item.childhood == null || item.adulthood == null) { - PawnNameDatabaseSolid.AddPlayerContentName(current.name, current.gender); + PawnNameDatabaseSolid.AddPlayerContentName(item.name, item.gender); } else { - current.PostLoad(); - current.ResolveReferences(); - foreach (string current2 in current.ConfigErrors()) + item.PostLoad(); + item.ResolveReferences(); + foreach (string item2 in item.ConfigErrors()) { - Log.Error(current2); + Log.Error(item2); } - SolidBioDatabase.allBios.Add(current); - current.childhood.shuffleable = false; - current.childhood.slot = BackstorySlot.Childhood; - current.adulthood.shuffleable = false; - current.adulthood.slot = BackstorySlot.Adulthood; - BackstoryDatabase.AddBackstory(current.childhood); - BackstoryDatabase.AddBackstory(current.adulthood); + SolidBioDatabase.allBios.Add(item); + item.childhood.shuffleable = false; + item.childhood.slot = BackstorySlot.Childhood; + item.adulthood.shuffleable = false; + item.adulthood.slot = BackstorySlot.Adulthood; + BackstoryDatabase.AddBackstory(item.childhood); + BackstoryDatabase.AddBackstory(item.adulthood); } } } diff --git a/Assembly-CSharp/RimWorld/SongDefOf.cs b/Assembly-CSharp/RimWorld/SongDefOf.cs index bd00a829f..77222c815 100644 --- a/Assembly-CSharp/RimWorld/SongDefOf.cs +++ b/Assembly-CSharp/RimWorld/SongDefOf.cs @@ -1,4 +1,3 @@ -using System; using Verse; namespace RimWorld diff --git a/Assembly-CSharp/RimWorld/SoundDefOf.cs b/Assembly-CSharp/RimWorld/SoundDefOf.cs index a07f413ef..c0564a8f5 100644 --- a/Assembly-CSharp/RimWorld/SoundDefOf.cs +++ b/Assembly-CSharp/RimWorld/SoundDefOf.cs @@ -1,4 +1,3 @@ -using System; using Verse; namespace RimWorld diff --git a/Assembly-CSharp/RimWorld/SoundParamSource_TimeOfDay.cs b/Assembly-CSharp/RimWorld/SoundParamSource_TimeOfDay.cs index a5b974de6..ee1ab8424 100644 --- a/Assembly-CSharp/RimWorld/SoundParamSource_TimeOfDay.cs +++ b/Assembly-CSharp/RimWorld/SoundParamSource_TimeOfDay.cs @@ -1,4 +1,3 @@ -using System; using Verse; using Verse.Sound; diff --git a/Assembly-CSharp/RimWorld/SpaceCategory.cs b/Assembly-CSharp/RimWorld/SpaceCategory.cs index 0779b5a22..b38dcb0ec 100644 --- a/Assembly-CSharp/RimWorld/SpaceCategory.cs +++ b/Assembly-CSharp/RimWorld/SpaceCategory.cs @@ -1,12 +1,10 @@ -using System; - namespace RimWorld { public enum SpaceCategory : byte { - VeryCramped, - Cramped, - Normal, - Spacious + VeryCramped = 0, + Cramped = 1, + Normal = 2, + Spacious = 3 } } diff --git a/Assembly-CSharp/RimWorld/Spark.cs b/Assembly-CSharp/RimWorld/Spark.cs index 835f8fed4..2ad7c98a8 100644 --- a/Assembly-CSharp/RimWorld/Spark.cs +++ b/Assembly-CSharp/RimWorld/Spark.cs @@ -1,4 +1,3 @@ -using System; using Verse; namespace RimWorld diff --git a/Assembly-CSharp/RimWorld/SpecialThingFilterDefOf.cs b/Assembly-CSharp/RimWorld/SpecialThingFilterDefOf.cs index 9f3550c75..cbaee0f82 100644 --- a/Assembly-CSharp/RimWorld/SpecialThingFilterDefOf.cs +++ b/Assembly-CSharp/RimWorld/SpecialThingFilterDefOf.cs @@ -1,4 +1,3 @@ -using System; using Verse; namespace RimWorld diff --git a/Assembly-CSharp/RimWorld/SpecialThingFilterWorker_CorpsesColonist.cs b/Assembly-CSharp/RimWorld/SpecialThingFilterWorker_CorpsesColonist.cs index fb339f63a..9b39e0c4e 100644 --- a/Assembly-CSharp/RimWorld/SpecialThingFilterWorker_CorpsesColonist.cs +++ b/Assembly-CSharp/RimWorld/SpecialThingFilterWorker_CorpsesColonist.cs @@ -1,4 +1,3 @@ -using System; using Verse; namespace RimWorld @@ -8,7 +7,15 @@ public class SpecialThingFilterWorker_CorpsesColonist : SpecialThingFilterWorker public override bool Matches(Thing t) { Corpse corpse = t as Corpse; - return corpse != null && corpse.InnerPawn.def.race.Humanlike && corpse.InnerPawn.Faction == Faction.OfPlayer; + if (corpse == null) + { + return false; + } + if (!corpse.InnerPawn.def.race.Humanlike) + { + return false; + } + return corpse.InnerPawn.Faction == Faction.OfPlayer; } } } diff --git a/Assembly-CSharp/RimWorld/SpecialThingFilterWorker_CorpsesStranger.cs b/Assembly-CSharp/RimWorld/SpecialThingFilterWorker_CorpsesStranger.cs index f166087e9..b1827dc06 100644 --- a/Assembly-CSharp/RimWorld/SpecialThingFilterWorker_CorpsesStranger.cs +++ b/Assembly-CSharp/RimWorld/SpecialThingFilterWorker_CorpsesStranger.cs @@ -1,4 +1,3 @@ -using System; using Verse; namespace RimWorld @@ -8,7 +7,15 @@ public class SpecialThingFilterWorker_CorpsesStranger : SpecialThingFilterWorker public override bool Matches(Thing t) { Corpse corpse = t as Corpse; - return corpse != null && corpse.InnerPawn.def.race.Humanlike && corpse.InnerPawn.Faction != Faction.OfPlayer; + if (corpse == null) + { + return false; + } + if (!corpse.InnerPawn.def.race.Humanlike) + { + return false; + } + return corpse.InnerPawn.Faction != Faction.OfPlayer; } } } diff --git a/Assembly-CSharp/RimWorld/SpecialThingFilterWorker_NonDeadmansApparel.cs b/Assembly-CSharp/RimWorld/SpecialThingFilterWorker_NonDeadmansApparel.cs index aa0f6403b..01178a778 100644 --- a/Assembly-CSharp/RimWorld/SpecialThingFilterWorker_NonDeadmansApparel.cs +++ b/Assembly-CSharp/RimWorld/SpecialThingFilterWorker_NonDeadmansApparel.cs @@ -1,4 +1,3 @@ -using System; using Verse; namespace RimWorld @@ -8,7 +7,11 @@ public class SpecialThingFilterWorker_NonDeadmansApparel : SpecialThingFilterWor public override bool Matches(Thing t) { Apparel apparel = t as Apparel; - return apparel != null && !apparel.WornByCorpse; + if (apparel != null) + { + return !apparel.WornByCorpse; + } + return false; } public override bool CanEverMatch(ThingDef def) diff --git a/Assembly-CSharp/RimWorld/SpecialThingFilterWorker_NonSmeltableWeapons.cs b/Assembly-CSharp/RimWorld/SpecialThingFilterWorker_NonSmeltableWeapons.cs index 2b16ed41e..3e2220997 100644 --- a/Assembly-CSharp/RimWorld/SpecialThingFilterWorker_NonSmeltableWeapons.cs +++ b/Assembly-CSharp/RimWorld/SpecialThingFilterWorker_NonSmeltableWeapons.cs @@ -1,4 +1,3 @@ -using System; using Verse; namespace RimWorld @@ -7,7 +6,11 @@ public class SpecialThingFilterWorker_NonSmeltableWeapons : SpecialThingFilterWo { public override bool Matches(Thing t) { - return this.CanEverMatch(t.def) && !t.Smeltable; + if (!this.CanEverMatch(t.def)) + { + return false; + } + return !t.Smeltable; } public override bool CanEverMatch(ThingDef def) @@ -16,7 +19,7 @@ public override bool CanEverMatch(ThingDef def) { return false; } - if (!def.thingCategories.NullOrEmpty()) + if (!def.thingCategories.NullOrEmpty()) { for (int i = 0; i < def.thingCategories.Count; i++) { diff --git a/Assembly-CSharp/RimWorld/SpecialThingFilterWorker_PlantFood.cs b/Assembly-CSharp/RimWorld/SpecialThingFilterWorker_PlantFood.cs index c6b5d2ddd..53cd0d1e9 100644 --- a/Assembly-CSharp/RimWorld/SpecialThingFilterWorker_PlantFood.cs +++ b/Assembly-CSharp/RimWorld/SpecialThingFilterWorker_PlantFood.cs @@ -1,4 +1,3 @@ -using System; using Verse; namespace RimWorld @@ -12,7 +11,7 @@ public override bool Matches(Thing t) public override bool AlwaysMatches(ThingDef def) { - return def.ingestible != null && (def.ingestible.foodType & FoodTypeFlags.Plant) != FoodTypeFlags.None; + return def.ingestible != null && ((int)def.ingestible.foodType & 64) != 0; } } } diff --git a/Assembly-CSharp/RimWorld/SpecialThingFilterWorker_Rotten.cs b/Assembly-CSharp/RimWorld/SpecialThingFilterWorker_Rotten.cs index 25534589d..e83b5aaab 100644 --- a/Assembly-CSharp/RimWorld/SpecialThingFilterWorker_Rotten.cs +++ b/Assembly-CSharp/RimWorld/SpecialThingFilterWorker_Rotten.cs @@ -1,4 +1,3 @@ -using System; using Verse; namespace RimWorld @@ -13,7 +12,11 @@ public override bool Matches(Thing t) return false; } CompRottable comp = thingWithComps.GetComp(); - return comp != null && !((CompProperties_Rottable)comp.props).rotDestroys && comp.Stage != RotStage.Fresh; + if (comp != null && !((CompProperties_Rottable)comp.props).rotDestroys) + { + return comp.Stage != RotStage.Fresh; + } + return false; } public override bool CanEverMatch(ThingDef def) diff --git a/Assembly-CSharp/RimWorld/SpecialThingFilterWorker_Smeltable.cs b/Assembly-CSharp/RimWorld/SpecialThingFilterWorker_Smeltable.cs index 3fcc4e13b..14aad0793 100644 --- a/Assembly-CSharp/RimWorld/SpecialThingFilterWorker_Smeltable.cs +++ b/Assembly-CSharp/RimWorld/SpecialThingFilterWorker_Smeltable.cs @@ -1,4 +1,3 @@ -using System; using Verse; namespace RimWorld @@ -7,7 +6,11 @@ public class SpecialThingFilterWorker_Smeltable : SpecialThingFilterWorker { public override bool Matches(Thing t) { - return this.CanEverMatch(t.def) && t.Smeltable; + if (!this.CanEverMatch(t.def)) + { + return false; + } + return t.Smeltable; } public override bool CanEverMatch(ThingDef def) diff --git a/Assembly-CSharp/RimWorld/SpectatorCellFinder.cs b/Assembly-CSharp/RimWorld/SpectatorCellFinder.cs index e448372c6..474113977 100644 --- a/Assembly-CSharp/RimWorld/SpectatorCellFinder.cs +++ b/Assembly-CSharp/RimWorld/SpectatorCellFinder.cs @@ -17,132 +17,148 @@ public static class SpectatorCellFinder public static bool TryFindSpectatorCellFor(Pawn p, CellRect spectateRect, Map map, out IntVec3 cell, SpectateRectSide allowedSides = SpectateRectSide.All, int margin = 1, List extraDisallowedCells = null) { spectateRect.ClipInsideMap(map); - if (spectateRect.Area == 0 || allowedSides == SpectateRectSide.None) + if (((spectateRect.Area != 0) ? allowedSides : SpectateRectSide.None) != 0) { - cell = IntVec3.Invalid; - return false; - } - CellRect rectWithMargin = spectateRect.ExpandedBy(margin).ClipInsideMap(map); - Predicate predicate = delegate(IntVec3 x) - { - if (!x.InBounds(map)) - { - return false; - } - if (!x.Standable(map)) - { - return false; - } - if (x.Fogged(map)) - { - return false; - } - if (rectWithMargin.Contains(x)) - { - return false; - } - if ((x.z <= rectWithMargin.maxZ || (allowedSides & SpectateRectSide.Up) != SpectateRectSide.Up) && (x.x <= rectWithMargin.maxX || (allowedSides & SpectateRectSide.Right) != SpectateRectSide.Right) && (x.z >= rectWithMargin.minZ || (allowedSides & SpectateRectSide.Down) != SpectateRectSide.Down) && (x.x >= rectWithMargin.minX || (allowedSides & SpectateRectSide.Left) != SpectateRectSide.Left)) - { - return false; - } - IntVec3 intVec3 = spectateRect.ClosestCellTo(x); - if ((float)intVec3.DistanceToSquared(x) > 210.25f) + CellRect rectWithMargin = spectateRect.ExpandedBy(margin).ClipInsideMap(map); + Predicate predicate = (Predicate)delegate(IntVec3 x) { - return false; - } - if (!GenSight.LineOfSight(intVec3, x, map, true, null, 0, 0)) - { - return false; - } - if (x.GetThingList(map).Find((Thing y) => y is Pawn && y != p) != null) - { - return false; - } - if (p != null) - { - if (!p.CanReserveAndReach(x, PathEndMode.OnCell, Danger.Some, 1, -1, null, false)) + if (!x.InBounds(map)) { return false; } - Building edifice = x.GetEdifice(map); - if (edifice != null && edifice.def.category == ThingCategory.Building && edifice.def.building.isSittable && !p.CanReserve(edifice, 1, -1, null, false)) + if (!x.Standable(map)) { return false; } - if (x.IsForbidden(p)) + if (x.Fogged(map)) { return false; } - if (x.GetDangerFor(p, map) != Danger.None) + CellRect rectWithMargin2; + if (rectWithMargin2.Contains(x)) { return false; } - } - if (extraDisallowedCells != null && extraDisallowedCells.Contains(x)) - { + if (x.z > rectWithMargin2.maxZ && ((int)allowedSides & 1) == 1) + { + goto IL_00e2; + } + if (x.x > rectWithMargin2.maxX && ((int)allowedSides & 2) == 2) + { + goto IL_00e2; + } + if (x.z < rectWithMargin2.minZ && ((int)allowedSides & 4) == 4) + { + goto IL_00e2; + } + if (x.x < rectWithMargin2.minX && ((int)allowedSides & 8) == 8) + { + goto IL_00e2; + } return false; - } - if (!SpectatorCellFinder.CorrectlyRotatedChairAt(x, map, spectateRect)) - { - int num = 0; - for (int k = 0; k < GenAdj.AdjacentCells.Length; k++) + IL_00e2: + CellRect spectateRect2; + IntVec3 intVec3 = spectateRect2.ClosestCellTo(x); + if ((float)intVec3.DistanceToSquared(x) > 210.25) { - IntVec3 x2 = x + GenAdj.AdjacentCells[k]; - if (SpectatorCellFinder.CorrectlyRotatedChairAt(x2, map, spectateRect)) - { - num++; - } + return false; } - if (num >= 3) + if (!GenSight.LineOfSight(intVec3, x, map, true, null, 0, 0)) { return false; } - int num2 = SpectatorCellFinder.DistanceToClosestChair(x, new IntVec3(-1, 0, 0), map, 4, spectateRect); - if (num2 >= 0) + if (x.GetThingList(map).Find((Predicate)((Thing y) => y is Pawn && y != p)) != null) { - int num3 = SpectatorCellFinder.DistanceToClosestChair(x, new IntVec3(1, 0, 0), map, 4, spectateRect); - if (num3 >= 0 && Mathf.Abs(num2 - num3) <= 1) + return false; + } + if (p != null) + { + if (!p.CanReserveAndReach(x, PathEndMode.OnCell, Danger.Some, 1, -1, null, false)) + { + return false; + } + Building edifice = x.GetEdifice(map); + if (edifice != null && edifice.def.category == ThingCategory.Building && edifice.def.building.isSittable && !p.CanReserve((Thing)edifice, 1, -1, null, false)) + { + return false; + } + if (x.IsForbidden(p)) + { + return false; + } + if (x.GetDangerFor(p, map) != Danger.None) { return false; } } - int num4 = SpectatorCellFinder.DistanceToClosestChair(x, new IntVec3(0, 0, 1), map, 4, spectateRect); - if (num4 >= 0) + if (extraDisallowedCells != null && extraDisallowedCells.Contains(x)) { - int num5 = SpectatorCellFinder.DistanceToClosestChair(x, new IntVec3(0, 0, -1), map, 4, spectateRect); - if (num5 >= 0 && Mathf.Abs(num4 - num5) <= 1) + return false; + } + if (!SpectatorCellFinder.CorrectlyRotatedChairAt(x, map, spectateRect2)) + { + int num = 0; + for (int k = 0; k < GenAdj.AdjacentCells.Length; k++) + { + IntVec3 x2 = x + GenAdj.AdjacentCells[k]; + if (SpectatorCellFinder.CorrectlyRotatedChairAt(x2, map, spectateRect2)) + { + num++; + } + } + if (num >= 3) { return false; } + int num2 = SpectatorCellFinder.DistanceToClosestChair(x, new IntVec3(-1, 0, 0), map, 4, spectateRect2); + if (num2 >= 0) + { + int num3 = SpectatorCellFinder.DistanceToClosestChair(x, new IntVec3(1, 0, 0), map, 4, spectateRect2); + if (num3 >= 0 && Mathf.Abs(num2 - num3) <= 1) + { + return false; + } + } + int num4 = SpectatorCellFinder.DistanceToClosestChair(x, new IntVec3(0, 0, 1), map, 4, spectateRect2); + if (num4 >= 0) + { + int num5 = SpectatorCellFinder.DistanceToClosestChair(x, new IntVec3(0, 0, -1), map, 4, spectateRect2); + if (num5 >= 0 && Mathf.Abs(num4 - num5) <= 1) + { + return false; + } + } } + return true; + }; + if (p != null && predicate(p.Position) && SpectatorCellFinder.CorrectlyRotatedChairAt(p.Position, map, spectateRect)) + { + cell = p.Position; + return true; } - return true; - }; - if (p != null && predicate(p.Position) && SpectatorCellFinder.CorrectlyRotatedChairAt(p.Position, map, spectateRect)) - { - cell = p.Position; - return true; - } - for (int i = 0; i < 1000; i++) - { - IntVec3 intVec = rectWithMargin.CenterCell + GenRadial.RadialPattern[i]; - if (predicate(intVec)) + for (int i = 0; i < 1000; i++) { - if (!SpectatorCellFinder.CorrectlyRotatedChairAt(intVec, map, spectateRect)) + IntVec3 intVec = rectWithMargin.CenterCell + GenRadial.RadialPattern[i]; + if (predicate(intVec)) { - for (int j = 0; j < 90; j++) + if (!SpectatorCellFinder.CorrectlyRotatedChairAt(intVec, map, spectateRect)) { - IntVec3 intVec2 = intVec + GenRadial.RadialPattern[j]; - if (SpectatorCellFinder.CorrectlyRotatedChairAt(intVec2, map, spectateRect) && predicate(intVec2)) + for (int j = 0; j < 90; j++) { - cell = intVec2; - return true; + IntVec3 intVec2 = intVec + GenRadial.RadialPattern[j]; + if (SpectatorCellFinder.CorrectlyRotatedChairAt(intVec2, map, spectateRect) && predicate(intVec2)) + { + cell = intVec2; + return true; + } } } + cell = intVec; + return true; } - cell = intVec; - return true; } + cell = IntVec3.Invalid; + return false; } cell = IntVec3.Invalid; return false; @@ -160,16 +176,16 @@ private static Building GetCorrectlyRotatedChairAt(IntVec3 x, Map map, CellRect return null; } Building edifice = x.GetEdifice(map); - if (edifice == null || edifice.def.category != ThingCategory.Building || !edifice.def.building.isSittable) - { - return null; - } - float num = GenGeo.AngleDifferenceBetween(edifice.Rotation.AsAngle, (spectateRect.ClosestCellTo(x) - edifice.Position).AngleFlat); - if (num > 75f) + if (edifice != null && edifice.def.category == ThingCategory.Building && edifice.def.building.isSittable) { - return null; + float num = GenGeo.AngleDifferenceBetween(edifice.Rotation.AsAngle, (spectateRect.ClosestCellTo(x) - edifice.Position).AngleFlat); + if (num > 75.0) + { + return null; + } + return edifice; } - return edifice; + return null; } private static int DistanceToClosestChair(IntVec3 from, IntVec3 step, Map map, int maxDist, CellRect spectateRect) @@ -182,7 +198,7 @@ private static int DistanceToClosestChair(IntVec3 from, IntVec3 step, Map map, i num++; if (!intVec.InBounds(map)) { - break; + return -1; } if (SpectatorCellFinder.CorrectlyRotatedChairAt(intVec, map, spectateRect)) { @@ -193,9 +209,7 @@ private static int DistanceToClosestChair(IntVec3 from, IntVec3 step, Map map, i return -1; } if (num >= maxDist) - { - return -1; - } + break; } return -1; } @@ -204,35 +218,41 @@ public static void DebugFlashPotentialSpectatorCells(CellRect spectateRect, Map { List list = new List(); int num = 50; - for (int i = 0; i < num; i++) + int num2 = 0; + IntVec3 intVec = default(IntVec3); + while (num2 < num && SpectatorCellFinder.TryFindSpectatorCellFor((Pawn)null, spectateRect, map, out intVec, allowedSides, margin, list)) { - IntVec3 intVec; - if (!SpectatorCellFinder.TryFindSpectatorCellFor(null, spectateRect, map, out intVec, allowedSides, margin, list)) - { - break; - } list.Add(intVec); - float a = Mathf.Lerp(1f, 0.08f, (float)i / (float)num); + float a = Mathf.Lerp(1f, 0.08f, (float)num2 / (float)num); Material mat = SolidColorMaterials.SimpleSolidColorMaterial(new Color(0f, 0.8f, 0f, a), false); - map.debugDrawer.FlashCell(intVec, mat, (i + 1).ToString()); + map.debugDrawer.FlashCell(intVec, mat, (num2 + 1).ToString()); + num2++; } SpectateRectSide spectateRectSide = SpectatorCellFinder.FindSingleBestSide(spectateRect, map, allowedSides, margin); IntVec3 centerCell = spectateRect.CenterCell; switch (spectateRectSide) { case SpectateRectSide.Up: + { centerCell.z += spectateRect.Height / 2 + 10; break; + } case SpectateRectSide.Right: + { centerCell.x += spectateRect.Width / 2 + 10; break; + } case SpectateRectSide.Down: + { centerCell.z -= spectateRect.Height / 2 + 10; break; + } case SpectateRectSide.Left: + { centerCell.x -= spectateRect.Width / 2 + 10; break; } + } map.debugDrawer.FlashLine(spectateRect.CenterCell, centerCell); } @@ -245,77 +265,82 @@ public static SpectateRectSide FindSingleBestSide(CellRect spectateRect, Map map SpectatorCellFinder.usedCells.Clear(); int num = 30; CellRect cellRect = spectateRect.ExpandedBy(margin).ClipInsideMap(map); - for (int j = 0; j < num; j++) + int num2 = 0; + IntVec3 intVec = default(IntVec3); + while (num2 < num && SpectatorCellFinder.TryFindSpectatorCellFor((Pawn)null, spectateRect, map, out intVec, allowedSides, margin, SpectatorCellFinder.usedCells)) { - IntVec3 intVec; - if (!SpectatorCellFinder.TryFindSpectatorCellFor(null, spectateRect, map, out intVec, allowedSides, margin, SpectatorCellFinder.usedCells)) - { - break; - } SpectatorCellFinder.usedCells.Add(intVec); - float num2 = Mathf.Lerp(1f, 0.35f, (float)j / (float)num); - float num3 = num2; + float num3; + float num4 = num3 = Mathf.Lerp(1f, 0.35f, (float)num2 / (float)num); Building correctlyRotatedChairAt = SpectatorCellFinder.GetCorrectlyRotatedChairAt(intVec, map, spectateRect); - if (intVec.z > cellRect.maxZ && (allowedSides & SpectateRectSide.Up) == SpectateRectSide.Up) + if (intVec.z > cellRect.maxZ && ((int)allowedSides & 1) == 1) { SpectatorCellFinder.scorePerSide[0] += num3; if (correctlyRotatedChairAt != null && correctlyRotatedChairAt.Rotation == Rot4.South) { - SpectatorCellFinder.scorePerSide[0] += 1.2f * num2; + SpectatorCellFinder.scorePerSide[0] += (float)(1.2000000476837158 * num4); } } - if (intVec.x > cellRect.maxX && (allowedSides & SpectateRectSide.Right) == SpectateRectSide.Right) + if (intVec.x > cellRect.maxX && ((int)allowedSides & 2) == 2) { SpectatorCellFinder.scorePerSide[1] += num3; if (correctlyRotatedChairAt != null && correctlyRotatedChairAt.Rotation == Rot4.West) { - SpectatorCellFinder.scorePerSide[1] += 1.2f * num2; + SpectatorCellFinder.scorePerSide[1] += (float)(1.2000000476837158 * num4); } } - if (intVec.z < cellRect.minZ && (allowedSides & SpectateRectSide.Down) == SpectateRectSide.Down) + if (intVec.z < cellRect.minZ && ((int)allowedSides & 4) == 4) { SpectatorCellFinder.scorePerSide[2] += num3; if (correctlyRotatedChairAt != null && correctlyRotatedChairAt.Rotation == Rot4.North) { - SpectatorCellFinder.scorePerSide[2] += 1.2f * num2; + SpectatorCellFinder.scorePerSide[2] += (float)(1.2000000476837158 * num4); } } - if (intVec.x < cellRect.minX && (allowedSides & SpectateRectSide.Left) == SpectateRectSide.Left) + if (intVec.x < cellRect.minX && ((int)allowedSides & 8) == 8) { SpectatorCellFinder.scorePerSide[3] += num3; if (correctlyRotatedChairAt != null && correctlyRotatedChairAt.Rotation == Rot4.East) { - SpectatorCellFinder.scorePerSide[3] += 1.2f * num2; + SpectatorCellFinder.scorePerSide[3] += (float)(1.2000000476837158 * num4); } } + num2++; } - float num4 = 0f; - int num5 = -1; - for (int k = 0; k < SpectatorCellFinder.scorePerSide.Length; k++) + float num5 = 0f; + int num6 = -1; + for (int j = 0; j < SpectatorCellFinder.scorePerSide.Length; j++) { - if (SpectatorCellFinder.scorePerSide[k] != 0f) + if (SpectatorCellFinder.scorePerSide[j] != 0.0 && (num6 < 0 || SpectatorCellFinder.scorePerSide[j] > num5)) { - if (num5 < 0 || SpectatorCellFinder.scorePerSide[k] > num4) - { - num5 = k; - num4 = SpectatorCellFinder.scorePerSide[k]; - } + num6 = j; + num5 = SpectatorCellFinder.scorePerSide[j]; } } SpectatorCellFinder.usedCells.Clear(); - switch (num5) + switch (num6) { case 0: + { return SpectateRectSide.Up; + } case 1: + { return SpectateRectSide.Right; + } case 2: + { return SpectateRectSide.Down; + } case 3: + { return SpectateRectSide.Left; + } default: + { return SpectateRectSide.None; } + } } } } diff --git a/Assembly-CSharp/RimWorld/SpouseRelationUtility.cs b/Assembly-CSharp/RimWorld/SpouseRelationUtility.cs index 1ccdae88b..bcf7507af 100644 --- a/Assembly-CSharp/RimWorld/SpouseRelationUtility.cs +++ b/Assembly-CSharp/RimWorld/SpouseRelationUtility.cs @@ -1,4 +1,3 @@ -using System; using Verse; namespace RimWorld @@ -23,11 +22,15 @@ public static Pawn GetSpouseOppositeGender(this Pawn pawn) { return null; } - if ((pawn.gender == Gender.Male && spouse.gender == Gender.Female) || (pawn.gender == Gender.Female && spouse.gender == Gender.Male)) + if (pawn.gender == Gender.Male && spouse.gender == Gender.Female) { - return spouse; + goto IL_003f; } + if (pawn.gender == Gender.Female && spouse.gender == Gender.Male) + goto IL_003f; return null; + IL_003f: + return spouse; } } } diff --git a/Assembly-CSharp/RimWorld/StatCategoryDef.cs b/Assembly-CSharp/RimWorld/StatCategoryDef.cs index ebe9b6ce3..0390315dc 100644 --- a/Assembly-CSharp/RimWorld/StatCategoryDef.cs +++ b/Assembly-CSharp/RimWorld/StatCategoryDef.cs @@ -1,4 +1,3 @@ -using System; using Verse; namespace RimWorld diff --git a/Assembly-CSharp/RimWorld/StatCategoryDefOf.cs b/Assembly-CSharp/RimWorld/StatCategoryDefOf.cs index 3d78a4c83..35dfd0539 100644 --- a/Assembly-CSharp/RimWorld/StatCategoryDefOf.cs +++ b/Assembly-CSharp/RimWorld/StatCategoryDefOf.cs @@ -1,5 +1,3 @@ -using System; - namespace RimWorld { [DefOf] diff --git a/Assembly-CSharp/RimWorld/StatDef.cs b/Assembly-CSharp/RimWorld/StatDef.cs index 652208b66..a532dcc3e 100644 --- a/Assembly-CSharp/RimWorld/StatDef.cs +++ b/Assembly-CSharp/RimWorld/StatDef.cs @@ -1,6 +1,5 @@ using System; using System.Collections.Generic; -using System.Diagnostics; using Verse; namespace RimWorld @@ -79,14 +78,41 @@ public StatWorker Worker } } - [DebuggerHidden] public override IEnumerable ConfigErrors() { - StatDef.c__Iterator96 c__Iterator = new StatDef.c__Iterator96(); - c__Iterator.<>f__this = this; - StatDef.c__Iterator96 expr_0E = c__Iterator; - expr_0E.$PC = -2; - return expr_0E; + foreach (string item in base.ConfigErrors()) + { + yield return item; + } + if (this.capacityFactors != null) + { + List.Enumerator enumerator2 = this.capacityFactors.GetEnumerator(); + try + { + while (enumerator2.MoveNext()) + { + PawnCapacityFactor afac = enumerator2.Current; + if (afac.weight > 1.0) + { + yield return base.defName + " has activity factor with weight > 1"; + } + } + } + finally + { + ((IDisposable)(object)enumerator2).Dispose(); + } + } + if (this.parts != null) + { + for (int i = 0; i < this.parts.Count; i++) + { + foreach (string item2 in this.parts[i].ConfigErrors()) + { + yield return base.defName + " has error in StatPart " + this.parts[i].ToString() + ": " + item2; + } + } + } } public string ValueToString(float val, ToStringNumberSense numberSense = ToStringNumberSense.Absolute) diff --git a/Assembly-CSharp/RimWorld/StatDefOf.cs b/Assembly-CSharp/RimWorld/StatDefOf.cs index 4cc41624f..cdeda35b9 100644 --- a/Assembly-CSharp/RimWorld/StatDefOf.cs +++ b/Assembly-CSharp/RimWorld/StatDefOf.cs @@ -1,5 +1,3 @@ -using System; - namespace RimWorld { [DefOf] diff --git a/Assembly-CSharp/RimWorld/StatDrawEntry.cs b/Assembly-CSharp/RimWorld/StatDrawEntry.cs index e6b85fac0..0472cdafb 100644 --- a/Assembly-CSharp/RimWorld/StatDrawEntry.cs +++ b/Assembly-CSharp/RimWorld/StatDrawEntry.cs @@ -31,7 +31,11 @@ public bool ShouldDisplay { get { - return this.stat == null || !Mathf.Approximately(this.value, this.stat.hideAtValue); + if (this.stat != null) + { + return !Mathf.Approximately(this.value, this.stat.hideAtValue); + } + return true; } } @@ -79,9 +83,9 @@ public StatDrawEntry(StatCategoryDef category, StatDef stat, float value, StatRe { this.category = category; this.stat = stat; - this.labelInt = null; + this.labelInt = (string)null; this.value = value; - this.valueStringInt = null; + this.valueStringInt = (string)null; this.displayOrderWithinCategory = 0; this.optionalReq = optionalReq; this.hasOptionalReq = true; @@ -131,7 +135,7 @@ public string GetExplanationText(StatRequest optionalReq) public float Draw(float x, float y, float width, bool selected, Action clickedCallback) { - float num = width * 0.45f; + float num = (float)(width * 0.44999998807907104); Rect rect = new Rect(8f, y, width, Text.CalcHeight(this.ValueString, num)); if (selected) { @@ -151,7 +155,7 @@ public float Draw(float x, float y, float width, bool selected, Action clickedCa if (this.stat != null) { StatDef localStat = this.stat; - TooltipHandler.TipRegion(rect, new TipSignal(() => localStat.LabelCap + ": " + localStat.description, this.stat.GetHashCode())); + TooltipHandler.TipRegion(rect, new TipSignal((Func)(() => localStat.LabelCap + ": " + localStat.description), this.stat.GetHashCode())); } if (Widgets.ButtonInvisible(rect, false)) { @@ -162,14 +166,7 @@ public float Draw(float x, float y, float width, bool selected, Action clickedCa public override string ToString() { - return string.Concat(new string[] - { - "(", - this.LabelCap, - ": ", - this.ValueString, - ")" - }); + return "(" + this.LabelCap + ": " + this.ValueString + ")"; } } } diff --git a/Assembly-CSharp/RimWorld/StatExtension.cs b/Assembly-CSharp/RimWorld/StatExtension.cs index a2f060c25..523e0c682 100644 --- a/Assembly-CSharp/RimWorld/StatExtension.cs +++ b/Assembly-CSharp/RimWorld/StatExtension.cs @@ -1,4 +1,3 @@ -using System; using Verse; namespace RimWorld diff --git a/Assembly-CSharp/RimWorld/StatModifier.cs b/Assembly-CSharp/RimWorld/StatModifier.cs index 4f2dcb552..bfbc08efb 100644 --- a/Assembly-CSharp/RimWorld/StatModifier.cs +++ b/Assembly-CSharp/RimWorld/StatModifier.cs @@ -1,4 +1,3 @@ -using System; using System.Xml; using Verse; diff --git a/Assembly-CSharp/RimWorld/StatPart.cs b/Assembly-CSharp/RimWorld/StatPart.cs index a56cca9f3..a5368a8f6 100644 --- a/Assembly-CSharp/RimWorld/StatPart.cs +++ b/Assembly-CSharp/RimWorld/StatPart.cs @@ -1,6 +1,4 @@ -using System; using System.Collections.Generic; -using System.Diagnostics; using Verse; namespace RimWorld @@ -14,13 +12,9 @@ public abstract class StatPart public abstract string ExplanationPart(StatRequest req); - [DebuggerHidden] public virtual IEnumerable ConfigErrors() { - StatPart.c__Iterator1AC c__Iterator1AC = new StatPart.c__Iterator1AC(); - StatPart.c__Iterator1AC expr_07 = c__Iterator1AC; - expr_07.$PC = -2; - return expr_07; + yield break; } } } diff --git a/Assembly-CSharp/RimWorld/StatPart_Age.cs b/Assembly-CSharp/RimWorld/StatPart_Age.cs index bff8b841b..33a9c2feb 100644 --- a/Assembly-CSharp/RimWorld/StatPart_Age.cs +++ b/Assembly-CSharp/RimWorld/StatPart_Age.cs @@ -1,6 +1,4 @@ -using System; using System.Collections.Generic; -using System.Diagnostics; using Verse; namespace RimWorld @@ -28,13 +26,10 @@ public override string ExplanationPart(StatRequest req) Pawn pawn = req.Thing as Pawn; if (pawn != null && pawn.ageTracker != null) { - return "StatsReport_AgeMultiplier".Translate(new object[] - { - pawn.ageTracker.AgeBiologicalYears - }) + ": x" + this.AgeMultiplier(pawn).ToStringPercent(); + return "StatsReport_AgeMultiplier".Translate(pawn.ageTracker.AgeBiologicalYears) + ": x" + this.AgeMultiplier(pawn).ToStringPercent(); } } - return null; + return (string)null; } private float AgeMultiplier(Pawn pawn) @@ -42,14 +37,12 @@ private float AgeMultiplier(Pawn pawn) return this.curve.Evaluate((float)pawn.ageTracker.AgeBiologicalYears / pawn.RaceProps.lifeExpectancy); } - [DebuggerHidden] public override IEnumerable ConfigErrors() { - StatPart_Age.c__Iterator1AD c__Iterator1AD = new StatPart_Age.c__Iterator1AD(); - c__Iterator1AD.<>f__this = this; - StatPart_Age.c__Iterator1AD expr_0E = c__Iterator1AD; - expr_0E.$PC = -2; - return expr_0E; + if (this.curve == null) + { + yield return "curve is null."; + } } } } diff --git a/Assembly-CSharp/RimWorld/StatPart_ApparelStatOffset.cs b/Assembly-CSharp/RimWorld/StatPart_ApparelStatOffset.cs index 2a09083f1..94eca50e2 100644 --- a/Assembly-CSharp/RimWorld/StatPart_ApparelStatOffset.cs +++ b/Assembly-CSharp/RimWorld/StatPart_ApparelStatOffset.cs @@ -1,4 +1,3 @@ -using System; using System.Text; using Verse; @@ -44,12 +43,12 @@ public override string ExplanationPart(StatRequest req) return stringBuilder.ToString(); } } - return null; + return (string)null; } private string InfoTextLineFrom(Thing gear) { - return " " + gear.LabelCap + ": " + gear.GetStatValue(this.apparelStat, true).ToStringByStyle(this.parentStat.toStringStyle, ToStringNumberSense.Offset); + return " " + gear.LabelCap + ": " + gear.GetStatValue(this.apparelStat, true).ToStringByStyle(base.parentStat.toStringStyle, ToStringNumberSense.Offset); } private bool PawnWearingRelevantGear(Pawn pawn) @@ -59,7 +58,7 @@ private bool PawnWearingRelevantGear(Pawn pawn) for (int i = 0; i < pawn.apparel.WornApparel.Count; i++) { Apparel thing = pawn.apparel.WornApparel[i]; - if (thing.GetStatValue(this.apparelStat, true) != 0f) + if (thing.GetStatValue(this.apparelStat, true) != 0.0) { return true; } diff --git a/Assembly-CSharp/RimWorld/StatPart_BedStat.cs b/Assembly-CSharp/RimWorld/StatPart_BedStat.cs index 884f27dec..e53316064 100644 --- a/Assembly-CSharp/RimWorld/StatPart_BedStat.cs +++ b/Assembly-CSharp/RimWorld/StatPart_BedStat.cs @@ -1,4 +1,3 @@ -using System; using Verse; namespace RimWorld @@ -29,7 +28,7 @@ public override string ExplanationPart(StatRequest req) return "StatsReport_InBed".Translate() + ": x" + this.BedMultiplier(pawn).ToStringPercent(); } } - return null; + return (string)null; } private float BedMultiplier(Pawn pawn) diff --git a/Assembly-CSharp/RimWorld/StatPart_BodySize.cs b/Assembly-CSharp/RimWorld/StatPart_BodySize.cs index 3adb10049..0203fbe3c 100644 --- a/Assembly-CSharp/RimWorld/StatPart_BodySize.cs +++ b/Assembly-CSharp/RimWorld/StatPart_BodySize.cs @@ -7,7 +7,7 @@ public class StatPart_BodySize : StatPart { public override void TransformValue(StatRequest req, ref float val) { - float num; + float num = default(float); if (this.TryGetBodySize(req, out num)) { val *= num; @@ -16,20 +16,17 @@ public override void TransformValue(StatRequest req, ref float val) public override string ExplanationPart(StatRequest req) { - float f; + float f = default(float); if (this.TryGetBodySize(req, out f)) { - return "StatsReport_BodySize".Translate(new object[] - { - f.ToString("F2") - }) + ": x" + f.ToStringPercent(); + return "StatsReport_BodySize".Translate(f.ToString("F2")) + ": x" + f.ToStringPercent(); } - return null; + return (string)null; } private bool TryGetBodySize(StatRequest req, out float bodySize) { - return PawnOrCorpseStatUtility.TryGetPawnOrCorpseStat(req, (Pawn x) => x.BodySize, (ThingDef x) => x.race.baseBodySize, out bodySize); + return PawnOrCorpseStatUtility.TryGetPawnOrCorpseStat(req, (Func)((Pawn x) => x.BodySize), (Func)((ThingDef x) => x.race.baseBodySize), out bodySize); } } } diff --git a/Assembly-CSharp/RimWorld/StatPart_Curve.cs b/Assembly-CSharp/RimWorld/StatPart_Curve.cs index cb9c34ca3..e6bb8dc77 100644 --- a/Assembly-CSharp/RimWorld/StatPart_Curve.cs +++ b/Assembly-CSharp/RimWorld/StatPart_Curve.cs @@ -1,4 +1,3 @@ -using System; using Verse; namespace RimWorld @@ -27,7 +26,7 @@ public override string ExplanationPart(StatRequest req) { return this.ExplanationLabel(req) + ": x" + this.curve.Evaluate(this.CurveXGetter(req)).ToStringPercent(); } - return null; + return (string)null; } } } diff --git a/Assembly-CSharp/RimWorld/StatPart_Difficulty.cs b/Assembly-CSharp/RimWorld/StatPart_Difficulty.cs index 109000bd8..7bdec9bb5 100644 --- a/Assembly-CSharp/RimWorld/StatPart_Difficulty.cs +++ b/Assembly-CSharp/RimWorld/StatPart_Difficulty.cs @@ -29,19 +29,31 @@ private float Multiplier(DifficultyDef d) { switch (d.index) { - case 0: + case (ushort)0: + { return this.factorRelax; - case 1: + } + case (ushort)1: + { return this.factorBasebuilder; - case 2: + } + case (ushort)2: + { return this.factorRough; - case 3: + } + case (ushort)3: + { return this.factorChallenge; - case 4: + } + case (ushort)4: + { return this.factorExtreme; + } default: + { throw new ArgumentOutOfRangeException(); } + } } } } diff --git a/Assembly-CSharp/RimWorld/StatPart_Food.cs b/Assembly-CSharp/RimWorld/StatPart_Food.cs index 36432dba1..2ed4a0796 100644 --- a/Assembly-CSharp/RimWorld/StatPart_Food.cs +++ b/Assembly-CSharp/RimWorld/StatPart_Food.cs @@ -35,24 +35,34 @@ public override string ExplanationPart(StatRequest req) return pawn.needs.food.CurCategory.GetLabel() + ": x" + this.FoodMultiplier(pawn.needs.food.CurCategory).ToStringPercent(); } } - return null; + return (string)null; } private float FoodMultiplier(HungerCategory hunger) { switch (hunger) { - case HungerCategory.Fed: - return this.factorFed; - case HungerCategory.Hungry: - return this.factorHungry; - case HungerCategory.UrgentlyHungry: - return this.factorUrgentlyHungry; case HungerCategory.Starving: + { return this.factorStarving; + } + case HungerCategory.UrgentlyHungry: + { + return this.factorUrgentlyHungry; + } + case HungerCategory.Hungry: + { + return this.factorHungry; + } + case HungerCategory.Fed: + { + return this.factorFed; + } default: + { throw new InvalidOperationException(); } + } } } } diff --git a/Assembly-CSharp/RimWorld/StatPart_GearAndInventoryMass.cs b/Assembly-CSharp/RimWorld/StatPart_GearAndInventoryMass.cs index 8783cc5c4..7befba4de 100644 --- a/Assembly-CSharp/RimWorld/StatPart_GearAndInventoryMass.cs +++ b/Assembly-CSharp/RimWorld/StatPart_GearAndInventoryMass.cs @@ -7,7 +7,7 @@ public class StatPart_GearAndInventoryMass : StatPart { public override void TransformValue(StatRequest req, ref float val) { - float num; + float num = default(float); if (this.TryGetValue(req, out num)) { val += num; @@ -16,17 +16,17 @@ public override void TransformValue(StatRequest req, ref float val) public override string ExplanationPart(StatRequest req) { - float mass; + float mass = default(float); if (this.TryGetValue(req, out mass)) { return "StatsReport_GearAndInventoryMass".Translate() + ": " + mass.ToStringMassOffset(); } - return null; + return (string)null; } private bool TryGetValue(StatRequest req, out float value) { - return PawnOrCorpseStatUtility.TryGetPawnOrCorpseStat(req, (Pawn x) => MassUtility.GearAndInventoryMass(x), (ThingDef x) => 0f, out value); + return PawnOrCorpseStatUtility.TryGetPawnOrCorpseStat(req, (Func)((Pawn x) => MassUtility.GearAndInventoryMass(x)), (Func)((ThingDef x) => 0f), out value); } } } diff --git a/Assembly-CSharp/RimWorld/StatPart_Health.cs b/Assembly-CSharp/RimWorld/StatPart_Health.cs index 878548de8..46ea34051 100644 --- a/Assembly-CSharp/RimWorld/StatPart_Health.cs +++ b/Assembly-CSharp/RimWorld/StatPart_Health.cs @@ -1,4 +1,3 @@ -using System; using Verse; namespace RimWorld @@ -17,10 +16,7 @@ protected override float CurveXGetter(StatRequest req) protected override string ExplanationLabel(StatRequest req) { - return "StatsReport_HealthMultiplier".Translate(new object[] - { - req.Thing.HitPoints + " / " + req.Thing.MaxHitPoints - }); + return "StatsReport_HealthMultiplier".Translate(req.Thing.HitPoints + " / " + req.Thing.MaxHitPoints); } } } diff --git a/Assembly-CSharp/RimWorld/StatPart_Mood.cs b/Assembly-CSharp/RimWorld/StatPart_Mood.cs index acb9c2b55..654f92cea 100644 --- a/Assembly-CSharp/RimWorld/StatPart_Mood.cs +++ b/Assembly-CSharp/RimWorld/StatPart_Mood.cs @@ -1,6 +1,4 @@ -using System; using System.Collections.Generic; -using System.Diagnostics; using Verse; namespace RimWorld @@ -9,14 +7,12 @@ public class StatPart_Mood : StatPart { private SimpleCurve curve; - [DebuggerHidden] public override IEnumerable ConfigErrors() { - StatPart_Mood.c__Iterator1AE c__Iterator1AE = new StatPart_Mood.c__Iterator1AE(); - c__Iterator1AE.<>f__this = this; - StatPart_Mood.c__Iterator1AE expr_0E = c__Iterator1AE; - expr_0E.$PC = -2; - return expr_0E; + if (this.curve == null) + { + yield return "curve is null."; + } } public override void TransformValue(StatRequest req, ref float val) @@ -38,13 +34,10 @@ public override string ExplanationPart(StatRequest req) Pawn pawn = req.Thing as Pawn; if (pawn != null && pawn.needs.mood != null) { - return "StatsReport_MoodMultiplier".Translate(new object[] - { - pawn.needs.mood.CurLevel.ToStringPercent() - }) + ": x" + this.MoodMultiplier(pawn.needs.mood.CurLevel).ToStringPercent(); + return "StatsReport_MoodMultiplier".Translate(pawn.needs.mood.CurLevel.ToStringPercent()) + ": x" + this.MoodMultiplier(pawn.needs.mood.CurLevel).ToStringPercent(); } } - return null; + return (string)null; } private float MoodMultiplier(float mood) diff --git a/Assembly-CSharp/RimWorld/StatPart_NaturalNotMissingBodyPartsCoverage.cs b/Assembly-CSharp/RimWorld/StatPart_NaturalNotMissingBodyPartsCoverage.cs index 377e8d813..836531893 100644 --- a/Assembly-CSharp/RimWorld/StatPart_NaturalNotMissingBodyPartsCoverage.cs +++ b/Assembly-CSharp/RimWorld/StatPart_NaturalNotMissingBodyPartsCoverage.cs @@ -7,7 +7,7 @@ public class StatPart_NaturalNotMissingBodyPartsCoverage : StatPart { public override void TransformValue(StatRequest req, ref float val) { - float num; + float num = default(float); if (this.TryGetValue(req, out num)) { val *= num; @@ -16,17 +16,17 @@ public override void TransformValue(StatRequest req, ref float val) public override string ExplanationPart(StatRequest req) { - float f; + float f = default(float); if (this.TryGetValue(req, out f)) { return "StatsReport_MissingBodyParts".Translate() + ": x" + f.ToStringPercent(); } - return null; + return (string)null; } private bool TryGetValue(StatRequest req, out float value) { - return PawnOrCorpseStatUtility.TryGetPawnOrCorpseStat(req, (Pawn x) => x.health.hediffSet.GetCoverageOfNotMissingNaturalParts(x.RaceProps.body.corePart), (ThingDef x) => 1f, out value); + return PawnOrCorpseStatUtility.TryGetPawnOrCorpseStat(req, (Func)((Pawn x) => x.health.hediffSet.GetCoverageOfNotMissingNaturalParts(x.RaceProps.body.corePart)), (Func)((ThingDef x) => 1f), out value); } } } diff --git a/Assembly-CSharp/RimWorld/StatPart_Outdoors.cs b/Assembly-CSharp/RimWorld/StatPart_Outdoors.cs index 9ac9192aa..3d35d56f5 100644 --- a/Assembly-CSharp/RimWorld/StatPart_Outdoors.cs +++ b/Assembly-CSharp/RimWorld/StatPart_Outdoors.cs @@ -1,4 +1,3 @@ -using System; using Verse; namespace RimWorld @@ -21,19 +20,11 @@ public override string ExplanationPart(StatRequest req) Room room = req.Thing.GetRoom(RegionType.Set_All); if (room != null) { - string str; - if (room.PsychologicallyOutdoors) - { - str = "Outdoors".Translate(); - } - else - { - str = "Indoors".Translate(); - } + string str = (!room.PsychologicallyOutdoors) ? "Indoors".Translate() : "Outdoors".Translate(); return str + ": x" + this.OutdoorsFactor(req).ToStringPercent(); } } - return null; + return (string)null; } private float OutdoorsFactor(StatRequest req) diff --git a/Assembly-CSharp/RimWorld/StatPart_Quality.cs b/Assembly-CSharp/RimWorld/StatPart_Quality.cs index 2d4c244af..560650d7c 100644 --- a/Assembly-CSharp/RimWorld/StatPart_Quality.cs +++ b/Assembly-CSharp/RimWorld/StatPart_Quality.cs @@ -27,25 +27,23 @@ public class StatPart_Quality : StatPart public override void TransformValue(StatRequest req, ref float val) { - if (val <= 0f && !this.alsoAppliesToNegativeValues) - { + if (val <= 0.0 && !this.alsoAppliesToNegativeValues) return; - } val *= this.QualityMultiplier(req.QualityCategory); } public override string ExplanationPart(StatRequest req) { - if (req.HasThing && !this.alsoAppliesToNegativeValues && req.Thing.GetStatValue(this.parentStat, true) <= 0f) + if (req.HasThing && !this.alsoAppliesToNegativeValues && req.Thing.GetStatValue(base.parentStat, true) <= 0.0) { - return null; + return (string)null; } - QualityCategory qc; + QualityCategory qc = default(QualityCategory); if (req.HasThing && req.Thing.TryGetQuality(out qc)) { return "StatsReport_QualityMultiplier".Translate() + ": x" + this.QualityMultiplier(qc).ToStringPercent(); } - return null; + return (string)null; } private float QualityMultiplier(QualityCategory qc) @@ -53,26 +51,46 @@ private float QualityMultiplier(QualityCategory qc) switch (qc) { case QualityCategory.Awful: + { return this.factorAwful; + } case QualityCategory.Shoddy: + { return this.factorShoddy; + } case QualityCategory.Poor: + { return this.factorPoor; + } case QualityCategory.Normal: + { return this.factorNormal; + } case QualityCategory.Good: + { return this.factorGood; + } case QualityCategory.Superior: + { return this.factorSuperior; + } case QualityCategory.Excellent: + { return this.factorExcellent; + } case QualityCategory.Masterwork: + { return this.factorMasterwork; + } case QualityCategory.Legendary: + { return this.factorLegendary; + } default: + { throw new ArgumentOutOfRangeException(); } + } } } } diff --git a/Assembly-CSharp/RimWorld/StatPart_Rest.cs b/Assembly-CSharp/RimWorld/StatPart_Rest.cs index 0ac061350..6254d2755 100644 --- a/Assembly-CSharp/RimWorld/StatPart_Rest.cs +++ b/Assembly-CSharp/RimWorld/StatPart_Rest.cs @@ -35,24 +35,34 @@ public override string ExplanationPart(StatRequest req) return pawn.needs.rest.CurCategory.GetLabel() + ": x" + this.RestMultiplier(pawn.needs.rest.CurCategory).ToStringPercent(); } } - return null; + return (string)null; } private float RestMultiplier(RestCategory fatigue) { switch (fatigue) { - case RestCategory.Rested: - return this.factorRested; - case RestCategory.Tired: - return this.factorTired; - case RestCategory.VeryTired: - return this.factorVeryTired; case RestCategory.Exhausted: + { return this.factorExhausted; + } + case RestCategory.VeryTired: + { + return this.factorVeryTired; + } + case RestCategory.Tired: + { + return this.factorTired; + } + case RestCategory.Rested: + { + return this.factorRested; + } default: + { throw new InvalidOperationException(); } + } } } } diff --git a/Assembly-CSharp/RimWorld/StatPart_RoomStat.cs b/Assembly-CSharp/RimWorld/StatPart_RoomStat.cs index d338bdda8..1f8cfcb43 100644 --- a/Assembly-CSharp/RimWorld/StatPart_RoomStat.cs +++ b/Assembly-CSharp/RimWorld/StatPart_RoomStat.cs @@ -1,4 +1,3 @@ -using System; using Verse; namespace RimWorld @@ -28,19 +27,11 @@ public override string ExplanationPart(StatRequest req) Room room = req.Thing.GetRoom(RegionType.Set_Passable); if (room != null) { - string labelCap; - if (!this.customLabel.NullOrEmpty()) - { - labelCap = this.customLabel; - } - else - { - labelCap = this.roomStat.LabelCap; - } - return labelCap + ": x" + room.GetStat(this.roomStat).ToStringPercent(); + string str = this.customLabel.NullOrEmpty() ? this.roomStat.LabelCap : this.customLabel; + return str + ": x" + room.GetStat(this.roomStat).ToStringPercent(); } } - return null; + return (string)null; } } } diff --git a/Assembly-CSharp/RimWorld/StatPart_UnfinishedThingIngredientsMass.cs b/Assembly-CSharp/RimWorld/StatPart_UnfinishedThingIngredientsMass.cs index 5b696c1cb..f2a26f3be 100644 --- a/Assembly-CSharp/RimWorld/StatPart_UnfinishedThingIngredientsMass.cs +++ b/Assembly-CSharp/RimWorld/StatPart_UnfinishedThingIngredientsMass.cs @@ -1,4 +1,3 @@ -using System; using Verse; namespace RimWorld @@ -7,7 +6,7 @@ public class StatPart_UnfinishedThingIngredientsMass : StatPart { public override void TransformValue(StatRequest req, ref float val) { - float num; + float num = default(float); if (this.TryGetValue(req, out num)) { val += num; @@ -16,12 +15,12 @@ public override void TransformValue(StatRequest req, ref float val) public override string ExplanationPart(StatRequest req) { - float mass; + float mass = default(float); if (this.TryGetValue(req, out mass)) { return "StatsReport_IngredientsMass".Translate() + ": " + mass.ToStringMassOffset(); } - return null; + return (string)null; } private bool TryGetValue(StatRequest req, out float value) diff --git a/Assembly-CSharp/RimWorld/StatPart_WorkTableOutdoors.cs b/Assembly-CSharp/RimWorld/StatPart_WorkTableOutdoors.cs index 3afbcab57..7195f828f 100644 --- a/Assembly-CSharp/RimWorld/StatPart_WorkTableOutdoors.cs +++ b/Assembly-CSharp/RimWorld/StatPart_WorkTableOutdoors.cs @@ -1,4 +1,3 @@ -using System; using Verse; namespace RimWorld @@ -21,7 +20,7 @@ public override string ExplanationPart(StatRequest req) { return "Outdoors".Translate() + ": x" + 0.8f.ToStringPercent(); } - return null; + return (string)null; } public static bool Applies(Thing t) @@ -31,16 +30,16 @@ public static bool Applies(Thing t) public static bool Applies(ThingDef def, Map map, IntVec3 c) { - if (def.building == null || !def.building.workSpeedPenaltyOutdoors) + if (def.building != null && def.building.workSpeedPenaltyOutdoors) { - return false; + if (map == null) + { + return false; + } + Room room = c.GetRoom(map, RegionType.Set_All); + return room != null && room.PsychologicallyOutdoors; } - if (map == null) - { - return false; - } - Room room = c.GetRoom(map, RegionType.Set_All); - return room != null && room.PsychologicallyOutdoors; + return false; } } } diff --git a/Assembly-CSharp/RimWorld/StatPart_WorkTableTemperature.cs b/Assembly-CSharp/RimWorld/StatPart_WorkTableTemperature.cs index 7454aaa05..127d31f99 100644 --- a/Assembly-CSharp/RimWorld/StatPart_WorkTableTemperature.cs +++ b/Assembly-CSharp/RimWorld/StatPart_WorkTableTemperature.cs @@ -1,4 +1,3 @@ -using System; using Verse; namespace RimWorld @@ -25,12 +24,16 @@ public override string ExplanationPart(StatRequest req) { return "BadTemperature".Translate().CapitalizeFirst() + ": x" + 0.6f.ToStringPercent(); } - return null; + return (string)null; } public static bool Applies(Thing t) { - return t.Spawned && StatPart_WorkTableTemperature.Applies(t.def, t.Map, t.Position); + if (!t.Spawned) + { + return false; + } + return StatPart_WorkTableTemperature.Applies(t.def, t.Map, t.Position); } public static bool Applies(ThingDef tDef, Map map, IntVec3 c) @@ -39,12 +42,12 @@ public static bool Applies(ThingDef tDef, Map map, IntVec3 c) { return false; } - if (tDef.building == null || !tDef.building.workSpeedPenaltyTemperature) + if (tDef.building != null && tDef.building.workSpeedPenaltyTemperature) { - return false; + float temperatureForCell = GenTemperature.GetTemperatureForCell(c, map); + return temperatureForCell < 5.0 || temperatureForCell > 35.0; } - float temperatureForCell = GenTemperature.GetTemperatureForCell(c, map); - return temperatureForCell < 5f || temperatureForCell > 35f; + return false; } } } diff --git a/Assembly-CSharp/RimWorld/StatPart_WorkTableUnpowered.cs b/Assembly-CSharp/RimWorld/StatPart_WorkTableUnpowered.cs index 0237df54f..7eaff2d12 100644 --- a/Assembly-CSharp/RimWorld/StatPart_WorkTableUnpowered.cs +++ b/Assembly-CSharp/RimWorld/StatPart_WorkTableUnpowered.cs @@ -1,4 +1,3 @@ -using System; using Verse; namespace RimWorld @@ -20,17 +19,21 @@ public override string ExplanationPart(StatRequest req) float unpoweredWorkTableWorkSpeedFactor = req.Thing.def.building.unpoweredWorkTableWorkSpeedFactor; return "NoPower".Translate() + ": x" + unpoweredWorkTableWorkSpeedFactor.ToStringPercent(); } - return null; + return (string)null; } public static bool Applies(Thing th) { - if (th.def.building.unpoweredWorkTableWorkSpeedFactor == 0f) + if (th.def.building.unpoweredWorkTableWorkSpeedFactor == 0.0) { return false; } CompPowerTrader compPowerTrader = th.TryGetComp(); - return compPowerTrader != null && !compPowerTrader.PowerOn; + if (compPowerTrader != null && !compPowerTrader.PowerOn) + { + return true; + } + return false; } } } diff --git a/Assembly-CSharp/RimWorld/StatPart_WornByCorpse.cs b/Assembly-CSharp/RimWorld/StatPart_WornByCorpse.cs index c6079b8e8..72c45adac 100644 --- a/Assembly-CSharp/RimWorld/StatPart_WornByCorpse.cs +++ b/Assembly-CSharp/RimWorld/StatPart_WornByCorpse.cs @@ -1,4 +1,3 @@ -using System; using Verse; namespace RimWorld @@ -29,7 +28,7 @@ public override string ExplanationPart(StatRequest req) return "StatsReport_WornByCorpse".Translate() + ": x" + 0.1f.ToStringPercent(); } } - return null; + return (string)null; } } } diff --git a/Assembly-CSharp/RimWorld/StatRequest.cs b/Assembly-CSharp/RimWorld/StatRequest.cs index aff51964f..421307eed 100644 --- a/Assembly-CSharp/RimWorld/StatRequest.cs +++ b/Assembly-CSharp/RimWorld/StatRequest.cs @@ -68,10 +68,12 @@ public static StatRequest For(Thing thing) Log.Error("StatRequest for null thing."); return StatRequest.ForEmpty(); } - StatRequest result = default(StatRequest); - result.thingInt = thing; - result.defInt = thing.def; - result.stuffDefInt = thing.Stuff; + StatRequest result = new StatRequest + { + thingInt = thing, + defInt = thing.def, + stuffDefInt = thing.Stuff + }; thing.TryGetQuality(out result.qualityCategoryInt); return result; } @@ -109,29 +111,22 @@ public override string ToString() { return "(" + this.Thing + ")"; } - return string.Concat(new object[] - { - "(", - this.Thing, - ", ", - (this.StuffDef == null) ? "null" : this.StuffDef.defName, - ")" - }); + return "(" + this.Thing + ", " + ((this.StuffDef == null) ? "null" : this.StuffDef.defName) + ")"; } public override int GetHashCode() { - int num = 0; - num = Gen.HashCombineInt(num, (int)this.defInt.shortHash); + int seed = 0; + seed = Gen.HashCombineInt(seed, this.defInt.shortHash); if (this.thingInt != null) { - num = Gen.HashCombineInt(num, this.thingInt.thingIDNumber); + seed = Gen.HashCombineInt(seed, this.thingInt.thingIDNumber); } if (this.stuffDefInt != null) { - num = Gen.HashCombineInt(num, (int)this.stuffDefInt.shortHash); + seed = Gen.HashCombineInt(seed, this.stuffDefInt.shortHash); } - return num; + return seed; } public override bool Equals(object obj) diff --git a/Assembly-CSharp/RimWorld/StatUtility.cs b/Assembly-CSharp/RimWorld/StatUtility.cs index 9e3b43445..57f89b962 100644 --- a/Assembly-CSharp/RimWorld/StatUtility.cs +++ b/Assembly-CSharp/RimWorld/StatUtility.cs @@ -1,4 +1,3 @@ -using System; using System.Collections.Generic; namespace RimWorld diff --git a/Assembly-CSharp/RimWorld/StatWorker.cs b/Assembly-CSharp/RimWorld/StatWorker.cs index 49dc75c87..bfeca5a34 100644 --- a/Assembly-CSharp/RimWorld/StatWorker.cs +++ b/Assembly-CSharp/RimWorld/StatWorker.cs @@ -1,6 +1,5 @@ using System; using System.Collections.Generic; -using System.Diagnostics; using System.Linq; using System.Text; using UnityEngine; @@ -76,7 +75,7 @@ public virtual float GetValueUnfinalized(StatRequest req, bool applyPostProcess } num *= pawn.ageTracker.CurLifeStage.statFactors.GetStatFactorFromList(this.stat); } - if (req.StuffDef != null && (num > 0f || this.stat.applyFactorsIfNegative)) + if (req.StuffDef != null && (num > 0.0 || this.stat.applyFactorsIfNegative)) { num += req.StuffDef.stuffProps.statOffsets.GetStatOffsetFromList(this.stat); num *= req.StuffDef.stuffProps.statFactors.GetStatFactorFromList(this.stat); @@ -107,7 +106,7 @@ public virtual float GetValueUnfinalized(StatRequest req, bool applyPostProcess } } } - else if (this.stat.noSkillFactor != 1f) + else if (this.stat.noSkillFactor != 1.0) { num *= this.stat.noSkillFactor; } @@ -134,16 +133,16 @@ public virtual string GetExplanation(StatRequest req, ToStringNumberSense number Pawn pawn = req.Thing as Pawn; if (pawn != null) { - if (pawn.RaceProps.intelligence >= Intelligence.ToolUser) + if ((int)pawn.RaceProps.intelligence >= 1) { if (pawn.story != null && pawn.story.traits != null) { List list = (from tr in pawn.story.traits.allTraits - where tr.CurrentData.statOffsets != null && tr.CurrentData.statOffsets.Any((StatModifier se) => se.stat == this.stat) - select tr).ToList(); + where tr.CurrentData.statOffsets != null && tr.CurrentData.statOffsets.Any((Predicate)((StatModifier se) => se.stat == this.stat)) + select tr).ToList(); List list2 = (from tr in pawn.story.traits.allTraits - where tr.CurrentData.statFactors != null && tr.CurrentData.statFactors.Any((StatModifier se) => se.stat == this.stat) - select tr).ToList(); + where tr.CurrentData.statFactors != null && tr.CurrentData.statFactors.Any((Predicate)((StatModifier se) => se.stat == this.stat)) + select tr).ToList(); if (list.Count > 0 || list2.Count > 0) { stringBuilder.AppendLine(); @@ -151,18 +150,18 @@ public virtual string GetExplanation(StatRequest req, ToStringNumberSense number for (int i = 0; i < list.Count; i++) { Trait trait = list[i]; - string toStringAsOffset = trait.CurrentData.statOffsets.First((StatModifier se) => se.stat == this.stat).ToStringAsOffset; + string toStringAsOffset = trait.CurrentData.statOffsets.First((Func)((StatModifier se) => se.stat == this.stat)).ToStringAsOffset; stringBuilder.AppendLine(" " + trait.LabelCap + ": " + toStringAsOffset); } for (int j = 0; j < list2.Count; j++) { Trait trait2 = list2[j]; - string toStringAsFactor = trait2.CurrentData.statFactors.First((StatModifier se) => se.stat == this.stat).ToStringAsFactor; + string toStringAsFactor = trait2.CurrentData.statFactors.First((Func)((StatModifier se) => se.stat == this.stat)).ToStringAsFactor; stringBuilder.AppendLine(" " + trait2.LabelCap + ": " + toStringAsFactor); } } } - if (StatWorker.RelevantGear(pawn, this.stat).Any()) + if (StatWorker.RelevantGear(pawn, this.stat).Any()) { stringBuilder.AppendLine(); stringBuilder.AppendLine("StatsReport_RelevantGear".Translate()); @@ -188,7 +187,7 @@ public virtual string GetExplanation(StatRequest req, ToStringNumberSense number if (curStage != null) { float statOffsetFromList = curStage.statOffsets.GetStatOffsetFromList(this.stat); - if (statOffsetFromList != 0f) + if (statOffsetFromList != 0.0) { if (!flag) { @@ -201,46 +200,25 @@ public virtual string GetExplanation(StatRequest req, ToStringNumberSense number } } float statFactorFromList = pawn.ageTracker.CurLifeStage.statFactors.GetStatFactorFromList(this.stat); - if (statFactorFromList != 1f) + if (statFactorFromList != 1.0) { stringBuilder.AppendLine(); - stringBuilder.AppendLine(string.Concat(new string[] - { - "StatsReport_LifeStage".Translate(), - " (", - pawn.ageTracker.CurLifeStage.label, - "): ", - statFactorFromList.ToStringByStyle(ToStringStyle.PercentZero, ToStringNumberSense.Factor) - })); + stringBuilder.AppendLine("StatsReport_LifeStage".Translate() + " (" + pawn.ageTracker.CurLifeStage.label + "): " + statFactorFromList.ToStringByStyle(ToStringStyle.PercentZero, ToStringNumberSense.Factor)); } } - if (req.StuffDef != null && (baseValueFor > 0f || this.stat.applyFactorsIfNegative)) + if (req.StuffDef != null && (baseValueFor > 0.0 || this.stat.applyFactorsIfNegative)) { float statOffsetFromList2 = req.StuffDef.stuffProps.statOffsets.GetStatOffsetFromList(this.stat); - if (statOffsetFromList2 != 0f) + if (statOffsetFromList2 != 0.0) { stringBuilder.AppendLine(); - stringBuilder.AppendLine(string.Concat(new string[] - { - "StatsReport_Material".Translate(), - " (", - req.StuffDef.LabelCap, - "): ", - statOffsetFromList2.ToStringByStyle(this.stat.toStringStyle, ToStringNumberSense.Offset) - })); + stringBuilder.AppendLine("StatsReport_Material".Translate() + " (" + req.StuffDef.LabelCap + "): " + statOffsetFromList2.ToStringByStyle(this.stat.toStringStyle, ToStringNumberSense.Offset)); } float statFactorFromList2 = req.StuffDef.stuffProps.statFactors.GetStatFactorFromList(this.stat); - if (statFactorFromList2 != 1f) + if (statFactorFromList2 != 1.0) { stringBuilder.AppendLine(); - stringBuilder.AppendLine(string.Concat(new string[] - { - "StatsReport_Material".Translate(), - " (", - req.StuffDef.LabelCap, - "): ", - statFactorFromList2.ToStringByStyle(ToStringStyle.PercentZero, ToStringNumberSense.Factor) - })); + stringBuilder.AppendLine("StatsReport_Material".Translate() + " (" + req.StuffDef.LabelCap + "): " + statFactorFromList2.ToStringByStyle(ToStringStyle.PercentZero, ToStringNumberSense.Factor)); } } CompAffectedByFacilities compAffectedByFacilities = req.Thing.TryGetComp(); @@ -270,19 +248,11 @@ public virtual string GetExplanation(StatRequest req, ToStringNumberSense number { SkillNeed skillNeed = this.stat.skillNeedFactors[n]; int level = pawn.skills.GetSkill(skillNeed.skill).Level; - stringBuilder.AppendLine(string.Concat(new object[] - { - " ", - skillNeed.skill.LabelCap, - " (", - level, - "): x", - skillNeed.FactorFor(pawn).ToStringPercent() - })); + stringBuilder.AppendLine(" " + skillNeed.skill.LabelCap + " (" + level + "): x" + skillNeed.FactorFor(pawn).ToStringPercent()); } } } - else if (this.stat.noSkillFactor != 1f) + else if (this.stat.noSkillFactor != 1.0) { stringBuilder.AppendLine(); stringBuilder.AppendLine("StatsReport_Skills".Translate()); @@ -294,34 +264,19 @@ public virtual string GetExplanation(StatRequest req, ToStringNumberSense number stringBuilder.AppendLine("StatsReport_HealthFactors".Translate()); if (this.stat.capacityFactors != null) { - foreach (PawnCapacityFactor current in from hfa in this.stat.capacityFactors + foreach (PawnCapacityFactor item in from hfa in this.stat.capacityFactors orderby hfa.capacity.listOrder select hfa) { - string text = current.capacity.GetLabelFor(pawn).CapitalizeFirst(); - float factor = current.GetFactor(pawn.health.capacities.GetLevel(current.capacity)); + string text = item.capacity.GetLabelFor(pawn).CapitalizeFirst(); + float factor = item.GetFactor(pawn.health.capacities.GetLevel(item.capacity)); string text2 = factor.ToStringPercent(); - string text3 = "HealthFactorPercentImpact".Translate(new object[] + string text3 = "HealthFactorPercentImpact".Translate(item.weight.ToStringPercent()); + if (item.max < 100.0) { - current.weight.ToStringPercent() - }); - if (current.max < 100f) - { - text3 = text3 + ", " + "HealthFactorMaxImpact".Translate(new object[] - { - current.max.ToStringPercent() - }); + text3 = text3 + ", " + "HealthFactorMaxImpact".Translate(item.max.ToStringPercent()); } - stringBuilder.AppendLine(string.Concat(new string[] - { - " ", - text, - ": x", - text2, - " (", - text3, - ")" - })); + stringBuilder.AppendLine(" " + text + ": x" + text2 + " (" + text3 + ")"); } } } @@ -348,7 +303,7 @@ public virtual void FinalizeValue(StatRequest req, ref float val, bool applyPost } if (Mathf.Abs(val) > this.stat.roundToFiveOver) { - val = Mathf.Round(val / 5f) * 5f; + val = (float)(Mathf.Round((float)(val / 5.0)) * 5.0); } val = Mathf.Clamp(val, this.stat.minValue, this.stat.maxValue); if (this.stat.roundValue) @@ -379,19 +334,12 @@ public virtual void FinalizeExplanation(StringBuilder sb, StatRequest req, ToStr { string text2 = this.stat.ValueToString(value, numberSense); string text3 = this.stat.ValueToString(value2, numberSense); - sb.AppendLine(string.Concat(new string[] - { - "StatsReport_PostProcessed".Translate(), - ": ", - text2, - " -> ", - text3 - })); + sb.AppendLine("StatsReport_PostProcessed".Translate() + ": " + text2 + " -> " + text3); sb.AppendLine(); } } float statFactor = Find.Scenario.GetStatFactor(this.stat); - if (statFactor != 1f) + if (statFactor != 1.0) { sb.AppendLine("StatsReport_ScenarioFactor".Translate() + ": " + statFactor.ToStringPercent()); sb.AppendLine(); @@ -425,53 +373,44 @@ public virtual bool ShouldShowFor(BuildableDef eDef) return false; } } - if (this.stat.category == StatCategoryDefOf.BasicsPawn || this.stat.category == StatCategoryDefOf.PawnCombat) - { - return thingDef != null && thingDef.category == ThingCategory.Pawn; - } - if (this.stat.category == StatCategoryDefOf.PawnMisc || this.stat.category == StatCategoryDefOf.PawnSocial || this.stat.category == StatCategoryDefOf.PawnWork) - { - return thingDef != null && thingDef.category == ThingCategory.Pawn && thingDef.race.Humanlike; - } - if (this.stat.category == StatCategoryDefOf.Building) + if (this.stat.category != StatCategoryDefOf.BasicsPawn && this.stat.category != StatCategoryDefOf.PawnCombat) { - if (thingDef == null) + if (this.stat.category != StatCategoryDefOf.PawnMisc && this.stat.category != StatCategoryDefOf.PawnSocial && this.stat.category != StatCategoryDefOf.PawnWork) { + if (this.stat.category == StatCategoryDefOf.Building) + { + if (thingDef == null) + { + return false; + } + if (this.stat == StatDefOf.DoorOpenSpeed) + { + return thingDef.IsDoor; + } + return thingDef.category == ThingCategory.Building; + } + if (this.stat.category == StatCategoryDefOf.Apparel) + { + return thingDef != null && (thingDef.IsApparel || thingDef.category == ThingCategory.Pawn); + } + if (this.stat.category == StatCategoryDefOf.Weapon) + { + return thingDef != null && (thingDef.IsMeleeWeapon || thingDef.IsRangedWeapon); + } + if (this.stat.category == StatCategoryDefOf.BasicsNonPawn) + { + return thingDef == null || thingDef.category != ThingCategory.Pawn; + } + if (this.stat.category.displayAllByDefault) + { + return true; + } + Log.Error("Unhandled case: " + this.stat + ", " + eDef); return false; } - if (this.stat == StatDefOf.DoorOpenSpeed) - { - return thingDef.IsDoor; - } - return thingDef.category == ThingCategory.Building; - } - else - { - if (this.stat.category == StatCategoryDefOf.Apparel) - { - return thingDef != null && (thingDef.IsApparel || thingDef.category == ThingCategory.Pawn); - } - if (this.stat.category == StatCategoryDefOf.Weapon) - { - return thingDef != null && (thingDef.IsMeleeWeapon || thingDef.IsRangedWeapon); - } - if (this.stat.category == StatCategoryDefOf.BasicsNonPawn) - { - return thingDef == null || thingDef.category != ThingCategory.Pawn; - } - if (this.stat.category.displayAllByDefault) - { - return true; - } - Log.Error(string.Concat(new object[] - { - "Unhandled case: ", - this.stat, - ", ", - eDef - })); - return false; + return thingDef != null && thingDef.category == ThingCategory.Pawn && thingDef.race.Humanlike; } + return thingDef != null && thingDef.category == ThingCategory.Pawn; } public virtual string GetStatDrawEntryLabel(StatDef stat, float value, ToStringNumberSense numberSense, StatRequest optionalReq) @@ -490,17 +429,46 @@ private static float StatOffsetFromGear(Thing gear, StatDef stat) return gear.def.equippedStatOffsets.GetStatOffsetFromList(stat); } - [DebuggerHidden] private static IEnumerable RelevantGear(Pawn pawn, StatDef stat) { - StatWorker.c__Iterator1AF c__Iterator1AF = new StatWorker.c__Iterator1AF(); - c__Iterator1AF.pawn = pawn; - c__Iterator1AF.stat = stat; - c__Iterator1AF.<$>pawn = pawn; - c__Iterator1AF.<$>stat = stat; - StatWorker.c__Iterator1AF expr_23 = c__Iterator1AF; - expr_23.$PC = -2; - return expr_23; + if (pawn.apparel != null) + { + List.Enumerator enumerator = pawn.apparel.WornApparel.GetEnumerator(); + try + { + while (enumerator.MoveNext()) + { + Apparel t2 = enumerator.Current; + if (StatWorker.GearAffectsStat(t2.def, stat)) + { + yield return (Thing)t2; + } + } + } + finally + { + ((IDisposable)(object)enumerator).Dispose(); + } + } + if (pawn.equipment != null) + { + List.Enumerator enumerator2 = pawn.equipment.AllEquipmentListForReading.GetEnumerator(); + try + { + while (enumerator2.MoveNext()) + { + ThingWithComps t = enumerator2.Current; + if (StatWorker.GearAffectsStat(t.def, stat)) + { + yield return (Thing)t; + } + } + } + finally + { + ((IDisposable)(object)enumerator2).Dispose(); + } + } } private static bool GearAffectsStat(ThingDef gearDef, StatDef stat) @@ -509,7 +477,7 @@ private static bool GearAffectsStat(ThingDef gearDef, StatDef stat) { for (int i = 0; i < gearDef.equippedStatOffsets.Count; i++) { - if (gearDef.equippedStatOffsets[i].stat == stat && gearDef.equippedStatOffsets[i].value != 0f) + if (gearDef.equippedStatOffsets[i].stat == stat && gearDef.equippedStatOffsets[i].value != 0.0) { return true; } @@ -523,13 +491,16 @@ private float GetBaseValueFor(BuildableDef def) float result = this.stat.defaultBaseValue; if (def.statBases != null) { - for (int i = 0; i < def.statBases.Count; i++) + int num = 0; + while (num < def.statBases.Count) { - if (def.statBases[i].stat == this.stat) + if (def.statBases[num].stat != this.stat) { - result = def.statBases[i].value; - break; + num++; + continue; } + result = def.statBases[num].value; + break; } } return result; diff --git a/Assembly-CSharp/RimWorld/StatWorker_MarketValue.cs b/Assembly-CSharp/RimWorld/StatWorker_MarketValue.cs index 7948409a5..80bbc8166 100644 --- a/Assembly-CSharp/RimWorld/StatWorker_MarketValue.cs +++ b/Assembly-CSharp/RimWorld/StatWorker_MarketValue.cs @@ -1,4 +1,3 @@ -using System; using System.Text; using UnityEngine; using Verse; @@ -31,17 +30,10 @@ public override float GetValueUnfinalized(StatRequest req, bool applyPostProcess } if (req.Def.costStuffCount > 0) { - if (req.StuffDef != null) - { - num += (float)req.Def.costStuffCount / req.StuffDef.VolumePerUnit * req.StuffDef.GetStatValueAbstract(StatDefOf.MarketValue, null); - } - else - { - num += (float)req.Def.costStuffCount * 2f; - } + num = (float)((req.StuffDef == null) ? (num + (float)req.Def.costStuffCount * 2.0) : (num + (float)req.Def.costStuffCount / req.StuffDef.VolumePerUnit * req.StuffDef.GetStatValueAbstract(StatDefOf.MarketValue, null))); } float num2 = Mathf.Max(req.Def.GetStatValueAbstract(StatDefOf.WorkToMake, req.StuffDef), req.Def.GetStatValueAbstract(StatDefOf.WorkToBuild, req.StuffDef)); - return num + num2 * 0.003f; + return (float)(num + num2 * 0.0030000000260770321); } public override string GetExplanation(StatRequest req, ToStringNumberSense numberSense) @@ -67,7 +59,11 @@ public override string GetExplanation(StatRequest req, ToStringNumberSense numbe public override bool ShouldShowFor(BuildableDef def) { ThingDef thingDef = def as ThingDef; - return thingDef != null && (TradeUtility.EverTradeable(thingDef) || thingDef.category == ThingCategory.Building); + if (thingDef == null) + { + return false; + } + return TradeUtility.EverTradeable(thingDef) || thingDef.category == ThingCategory.Building; } } } diff --git a/Assembly-CSharp/RimWorld/StatWorker_MeleeDPS.cs b/Assembly-CSharp/RimWorld/StatWorker_MeleeDPS.cs index bddcea8bc..352bb7911 100644 --- a/Assembly-CSharp/RimWorld/StatWorker_MeleeDPS.cs +++ b/Assembly-CSharp/RimWorld/StatWorker_MeleeDPS.cs @@ -1,4 +1,3 @@ -using System; using System.Collections.Generic; using System.Text; using Verse; @@ -21,10 +20,7 @@ public override string GetExplanation(StatRequest req, ToStringNumberSense numbe stringBuilder.AppendLine(" " + this.GetMeleeDamage(req, true).ToString("0.##")); stringBuilder.AppendLine(); stringBuilder.AppendLine("StatsReport_Cooldown".Translate() + " (" + "AverageOfAllAttacks".Translate() + ")"); - stringBuilder.AppendLine(" " + "StatsReport_CooldownFormat".Translate(new object[] - { - this.GetMeleeCooldown(req, true).ToString("0.##") - })); + stringBuilder.AppendLine(" " + "StatsReport_CooldownFormat".Translate(this.GetMeleeCooldown(req, true).ToString("0.##"))); stringBuilder.AppendLine(); stringBuilder.AppendLine("StatsReport_MeleeHitChance".Translate()); stringBuilder.AppendLine(); @@ -34,39 +30,39 @@ public override string GetExplanation(StatRequest req, ToStringNumberSense numbe public override string GetStatDrawEntryLabel(StatDef stat, float value, ToStringNumberSense numberSense, StatRequest optionalReq) { - return string.Format("{0} ( {1} x {2} / {3} )", new object[] - { - value.ToStringByStyle(stat.toStringStyle, numberSense), - this.GetMeleeDamage(optionalReq, true).ToString("0.##"), - StatDefOf.MeleeHitChance.ValueToString(this.GetMeleeHitChance(optionalReq, true), ToStringNumberSense.Absolute), - this.GetMeleeCooldown(optionalReq, true).ToString("0.##") - }); + return string.Format("{0} ( {1} x {2} / {3} )", value.ToStringByStyle(stat.toStringStyle, numberSense), this.GetMeleeDamage(optionalReq, true).ToString("0.##"), StatDefOf.MeleeHitChance.ValueToString(this.GetMeleeHitChance(optionalReq, true), ToStringNumberSense.Absolute), this.GetMeleeCooldown(optionalReq, true).ToString("0.##")); } private float GetMeleeDamage(StatRequest req, bool applyPostProcess = true) { Pawn pawn = req.Thing as Pawn; - if (pawn == null) - { - return 0f; - } - List updatedAvailableVerbsList = pawn.meleeVerbs.GetUpdatedAvailableVerbsList(); - if (updatedAvailableVerbsList.Count == 0) - { - return 0f; - } - float num = 0f; - for (int i = 0; i < updatedAvailableVerbsList.Count; i++) - { - num += updatedAvailableVerbsList[i].SelectionWeight; - } - float num2 = 0f; - for (int j = 0; j < updatedAvailableVerbsList.Count; j++) + if (pawn != null) { - ThingWithComps ownerEquipment = updatedAvailableVerbsList[j].verb.ownerEquipment; - num2 += updatedAvailableVerbsList[j].SelectionWeight / num * (float)updatedAvailableVerbsList[j].verb.verbProps.AdjustedMeleeDamageAmount(updatedAvailableVerbsList[j].verb, pawn, ownerEquipment); + List updatedAvailableVerbsList = pawn.meleeVerbs.GetUpdatedAvailableVerbsList(); + if (updatedAvailableVerbsList.Count == 0) + { + return 0f; + } + float num = 0f; + for (int i = 0; i < updatedAvailableVerbsList.Count; i++) + { + num += updatedAvailableVerbsList[i].SelectionWeight; + } + float num2 = 0f; + for (int j = 0; j < updatedAvailableVerbsList.Count; j++) + { + VerbEntry verbEntry = updatedAvailableVerbsList[j]; + ThingWithComps ownerEquipment = verbEntry.verb.ownerEquipment; + float num3 = num2; + float num4 = updatedAvailableVerbsList[j].SelectionWeight / num; + VerbEntry verbEntry2 = updatedAvailableVerbsList[j]; + VerbProperties verbProps = verbEntry2.verb.verbProps; + VerbEntry verbEntry3 = updatedAvailableVerbsList[j]; + num2 = num3 + num4 * (float)verbProps.AdjustedMeleeDamageAmount(verbEntry3.verb, pawn, ownerEquipment); + } + return num2; } - return num2; + return 0f; } private float GetMeleeHitChance(StatRequest req, bool applyPostProcess = true) @@ -81,27 +77,31 @@ private float GetMeleeHitChance(StatRequest req, bool applyPostProcess = true) private float GetMeleeCooldown(StatRequest req, bool applyPostProcess = true) { Pawn pawn = req.Thing as Pawn; - if (pawn == null) + if (pawn != null) { - return 1f; + List updatedAvailableVerbsList = pawn.meleeVerbs.GetUpdatedAvailableVerbsList(); + if (updatedAvailableVerbsList.Count == 0) + { + return 1f; + } + float num = 0f; + for (int i = 0; i < updatedAvailableVerbsList.Count; i++) + { + num += updatedAvailableVerbsList[i].SelectionWeight; + } + float num2 = 0f; + for (int j = 0; j < updatedAvailableVerbsList.Count; j++) + { + VerbEntry verbEntry = updatedAvailableVerbsList[j]; + ThingWithComps ownerEquipment = verbEntry.verb.ownerEquipment; + float num3 = num2; + float num4 = updatedAvailableVerbsList[j].SelectionWeight / num; + VerbEntry verbEntry2 = updatedAvailableVerbsList[j]; + num2 = num3 + num4 * (float)verbEntry2.verb.verbProps.AdjustedCooldownTicks(ownerEquipment); + } + return (float)(num2 / 60.0); } - List updatedAvailableVerbsList = pawn.meleeVerbs.GetUpdatedAvailableVerbsList(); - if (updatedAvailableVerbsList.Count == 0) - { - return 1f; - } - float num = 0f; - for (int i = 0; i < updatedAvailableVerbsList.Count; i++) - { - num += updatedAvailableVerbsList[i].SelectionWeight; - } - float num2 = 0f; - for (int j = 0; j < updatedAvailableVerbsList.Count; j++) - { - ThingWithComps ownerEquipment = updatedAvailableVerbsList[j].verb.ownerEquipment; - num2 += updatedAvailableVerbsList[j].SelectionWeight / num * (float)updatedAvailableVerbsList[j].verb.verbProps.AdjustedCooldownTicks(ownerEquipment); - } - return num2 / 60f; + return 1f; } private string GetMeleeHitChanceExplanation(StatRequest req) @@ -110,10 +110,7 @@ private string GetMeleeHitChanceExplanation(StatRequest req) stringBuilder.AppendLine(StatDefOf.MeleeHitChance.Worker.GetExplanation(req, StatDefOf.MeleeHitChance.toStringNumberSense)); StatDefOf.MeleeHitChance.Worker.FinalizeExplanation(stringBuilder, req, StatDefOf.MeleeHitChance.toStringNumberSense, this.GetMeleeHitChance(req, true)); StringBuilder stringBuilder2 = new StringBuilder(); - string[] array = stringBuilder.ToString().Split(new char[] - { - '\n' - }); + string[] array = stringBuilder.ToString().Split('\n'); for (int i = 0; i < array.Length; i++) { stringBuilder2.Append(" "); diff --git a/Assembly-CSharp/RimWorld/StatWorker_MeleeDamageAmount.cs b/Assembly-CSharp/RimWorld/StatWorker_MeleeDamageAmount.cs index 37b8554ca..b81ad79cc 100644 --- a/Assembly-CSharp/RimWorld/StatWorker_MeleeDamageAmount.cs +++ b/Assembly-CSharp/RimWorld/StatWorker_MeleeDamageAmount.cs @@ -1,4 +1,3 @@ -using System; using System.Text; using Verse; diff --git a/Assembly-CSharp/RimWorld/StatWorker_MeleeDamageAmountTrap.cs b/Assembly-CSharp/RimWorld/StatWorker_MeleeDamageAmountTrap.cs index 82edd1804..0b45f86f6 100644 --- a/Assembly-CSharp/RimWorld/StatWorker_MeleeDamageAmountTrap.cs +++ b/Assembly-CSharp/RimWorld/StatWorker_MeleeDamageAmountTrap.cs @@ -1,4 +1,3 @@ -using System; using Verse; namespace RimWorld diff --git a/Assembly-CSharp/RimWorld/StatWorker_MeleeDamageAmountWeapon.cs b/Assembly-CSharp/RimWorld/StatWorker_MeleeDamageAmountWeapon.cs index dc58a6cb4..a9712dec0 100644 --- a/Assembly-CSharp/RimWorld/StatWorker_MeleeDamageAmountWeapon.cs +++ b/Assembly-CSharp/RimWorld/StatWorker_MeleeDamageAmountWeapon.cs @@ -1,4 +1,3 @@ -using System; using Verse; namespace RimWorld diff --git a/Assembly-CSharp/RimWorld/StatWorker_MinimumHandlingSkill.cs b/Assembly-CSharp/RimWorld/StatWorker_MinimumHandlingSkill.cs index 91c0a232a..260c9c8c0 100644 --- a/Assembly-CSharp/RimWorld/StatWorker_MinimumHandlingSkill.cs +++ b/Assembly-CSharp/RimWorld/StatWorker_MinimumHandlingSkill.cs @@ -1,4 +1,3 @@ -using System; using UnityEngine; using Verse; @@ -14,14 +13,7 @@ public override float GetValueUnfinalized(StatRequest req, bool applyPostProcess public override string GetExplanation(StatRequest req, ToStringNumberSense numberSense) { float wildness = ((ThingDef)req.Def).race.wildness; - return string.Concat(new string[] - { - "Wildness".Translate(), - " ", - wildness.ToStringPercent(), - ": ", - this.ValueFromReq(req).ToString("F0") - }); + return "Wildness".Translate() + " " + wildness.ToStringPercent() + ": " + this.ValueFromReq(req).ToString("F0"); } private float ValueFromReq(StatRequest req) diff --git a/Assembly-CSharp/RimWorld/StatsRecord.cs b/Assembly-CSharp/RimWorld/StatsRecord.cs index b37b64be9..ab3542055 100644 --- a/Assembly-CSharp/RimWorld/StatsRecord.cs +++ b/Assembly-CSharp/RimWorld/StatsRecord.cs @@ -1,4 +1,3 @@ -using System; using Verse; namespace RimWorld diff --git a/Assembly-CSharp/RimWorld/StatsReportUtility.cs b/Assembly-CSharp/RimWorld/StatsReportUtility.cs index 387eee0f7..e93dc1188 100644 --- a/Assembly-CSharp/RimWorld/StatsReportUtility.cs +++ b/Assembly-CSharp/RimWorld/StatsReportUtility.cs @@ -1,7 +1,6 @@ using RimWorld.Planet; using System; using System.Collections.Generic; -using System.Diagnostics; using System.Linq; using UnityEngine; using Verse; @@ -28,7 +27,7 @@ public static void Reset() public static void DrawStatsReport(Rect rect, Def def, ThingDef stuff) { - if (StatsReportUtility.cachedDrawEntries.NullOrEmpty()) + if (StatsReportUtility.cachedDrawEntries.NullOrEmpty()) { StatsReportUtility.cachedDrawEntries.AddRange(def.SpecialDisplayStats()); StatsReportUtility.cachedDrawEntries.AddRange(from r in StatsReportUtility.StatsToDraw(def, stuff) @@ -41,13 +40,13 @@ where r.ShouldDisplay public static void DrawStatsReport(Rect rect, Thing thing) { - if (StatsReportUtility.cachedDrawEntries.NullOrEmpty()) + if (StatsReportUtility.cachedDrawEntries.NullOrEmpty()) { StatsReportUtility.cachedDrawEntries.AddRange(thing.def.SpecialDisplayStats()); StatsReportUtility.cachedDrawEntries.AddRange(from r in StatsReportUtility.StatsToDraw(thing) where r.ShouldDisplay select r); - StatsReportUtility.cachedDrawEntries.RemoveAll((StatDrawEntry de) => de.stat != null && !de.stat.showNonAbstract); + StatsReportUtility.cachedDrawEntries.RemoveAll((Predicate)((StatDrawEntry de) => de.stat != null && !de.stat.showNonAbstract)); StatsReportUtility.FinalizeCachedDrawEntries(StatsReportUtility.cachedDrawEntries); } StatsReportUtility.DrawStatsWorker(rect, thing, null); @@ -55,58 +54,98 @@ where r.ShouldDisplay public static void DrawStatsReport(Rect rect, WorldObject worldObject) { - if (StatsReportUtility.cachedDrawEntries.NullOrEmpty()) + if (StatsReportUtility.cachedDrawEntries.NullOrEmpty()) { StatsReportUtility.cachedDrawEntries.AddRange(worldObject.def.SpecialDisplayStats()); StatsReportUtility.cachedDrawEntries.AddRange(from r in StatsReportUtility.StatsToDraw(worldObject) where r.ShouldDisplay select r); - StatsReportUtility.cachedDrawEntries.RemoveAll((StatDrawEntry de) => de.stat != null && !de.stat.showNonAbstract); + StatsReportUtility.cachedDrawEntries.RemoveAll((Predicate)((StatDrawEntry de) => de.stat != null && !de.stat.showNonAbstract)); StatsReportUtility.FinalizeCachedDrawEntries(StatsReportUtility.cachedDrawEntries); } StatsReportUtility.DrawStatsWorker(rect, null, worldObject); } - [DebuggerHidden] private static IEnumerable StatsToDraw(Def def, ThingDef stuff) { - StatsReportUtility.c__Iterator199 c__Iterator = new StatsReportUtility.c__Iterator199(); - c__Iterator.def = def; - c__Iterator.stuff = stuff; - c__Iterator.<$>def = def; - c__Iterator.<$>stuff = stuff; - StatsReportUtility.c__Iterator199 expr_23 = c__Iterator; - expr_23.$PC = -2; - return expr_23; + yield return StatsReportUtility.DescriptionEntry(def); + BuildableDef eDef = def as BuildableDef; + if (eDef != null) + { + foreach (StatDef item in from st in DefDatabase.AllDefs + where st.Worker.ShouldShowFor(((_003CStatsToDraw_003Ec__Iterator199)/*Error near IL_0066: stateMachine*/)._003CeDef_003E__0) + select st) + { + yield return new StatDrawEntry(item.category, item, eDef.GetStatValueAbstract(item, stuff), StatRequest.For(eDef, stuff, QualityCategory.Normal), ToStringNumberSense.Undefined); + } + } } - [DebuggerHidden] private static IEnumerable StatsToDraw(Thing thing) { - StatsReportUtility.c__Iterator19A c__Iterator19A = new StatsReportUtility.c__Iterator19A(); - c__Iterator19A.thing = thing; - c__Iterator19A.<$>thing = thing; - StatsReportUtility.c__Iterator19A expr_15 = c__Iterator19A; - expr_15.$PC = -2; - return expr_15; + yield return StatsReportUtility.DescriptionEntry(thing); + StatDrawEntry qe = StatsReportUtility.QualityEntry(thing); + if (qe != null) + { + yield return qe; + } + foreach (StatDef item in from st in DefDatabase.AllDefs + where st.Worker.ShouldShowFor(((_003CStatsToDraw_003Ec__Iterator19A)/*Error near IL_0096: stateMachine*/).thing.def) + select st) + { + yield return new StatDrawEntry(item.category, item, thing.GetStatValue(item, true), StatRequest.For(thing), ToStringNumberSense.Undefined); + } + if (thing.def.useHitPoints) + { + yield return new StatDrawEntry(StatCategoryDefOf.BasicsNonPawn, "HitPointsBasic".Translate().CapitalizeFirst(), thing.HitPoints.ToString() + " / " + thing.MaxHitPoints.ToString(), 0) + { + overrideReportText = "HitPointsBasic".Translate().CapitalizeFirst() + ":\n\n" + thing.HitPoints.ToString() + "\n\n" + StatDefOf.MaxHitPoints.LabelCap + ":\n\n" + StatDefOf.MaxHitPoints.Worker.GetExplanation(StatRequest.For(thing), ToStringNumberSense.Absolute) + }; + } + foreach (StatDrawEntry specialDisplayStat in thing.SpecialDisplayStats) + { + yield return specialDisplayStat; + } + if (!thing.def.equippedStatOffsets.NullOrEmpty()) + { + for (int k = 0; k < thing.def.equippedStatOffsets.Count; k++) + { + yield return new StatDrawEntry(StatCategoryDefOf.EquippedStatOffsets, thing.def.equippedStatOffsets[k].stat, thing.def.equippedStatOffsets[k].value, StatRequest.ForEmpty(), ToStringNumberSense.Offset); + } + } + if (thing.def.IsStuff) + { + if (!thing.def.stuffProps.statFactors.NullOrEmpty()) + { + for (int j = 0; j < thing.def.stuffProps.statFactors.Count; j++) + { + yield return new StatDrawEntry(StatCategoryDefOf.StuffStatFactors, thing.def.stuffProps.statFactors[j].stat, thing.def.stuffProps.statFactors[j].value, StatRequest.ForEmpty(), ToStringNumberSense.Factor); + } + } + if (!thing.def.stuffProps.statOffsets.NullOrEmpty()) + { + for (int i = 0; i < thing.def.stuffProps.statOffsets.Count; i++) + { + yield return new StatDrawEntry(StatCategoryDefOf.StuffStatOffsets, thing.def.stuffProps.statOffsets[i].stat, thing.def.stuffProps.statOffsets[i].value, StatRequest.ForEmpty(), ToStringNumberSense.Offset); + } + } + } } - [DebuggerHidden] private static IEnumerable StatsToDraw(WorldObject worldObject) { - StatsReportUtility.c__Iterator19B c__Iterator19B = new StatsReportUtility.c__Iterator19B(); - c__Iterator19B.worldObject = worldObject; - c__Iterator19B.<$>worldObject = worldObject; - StatsReportUtility.c__Iterator19B expr_15 = c__Iterator19B; - expr_15.$PC = -2; - return expr_15; + yield return StatsReportUtility.DescriptionEntry(worldObject); + foreach (StatDrawEntry specialDisplayStat in worldObject.SpecialDisplayStats) + { + yield return specialDisplayStat; + } } private static void FinalizeCachedDrawEntries(IEnumerable original) { StatsReportUtility.cachedDrawEntries = (from sd in original orderby sd.category.displayOrder, sd.DisplayPriorityWithinCategory descending, sd.LabelCap - select sd).ToList(); + select sd).ToList(); if (StatsReportUtility.cachedDrawEntries.Count > 0) { StatsReportUtility.SelectEntry(StatsReportUtility.cachedDrawEntries[0], false); @@ -115,39 +154,35 @@ private static void FinalizeCachedDrawEntries(IEnumerable origina private static StatDrawEntry DescriptionEntry(Def def) { - return new StatDrawEntry(StatCategoryDefOf.Basics, "Description".Translate(), string.Empty, 99999) - { - overrideReportText = def.description - }; + StatDrawEntry statDrawEntry = new StatDrawEntry(StatCategoryDefOf.Basics, "Description".Translate(), string.Empty, 99999); + statDrawEntry.overrideReportText = def.description; + return statDrawEntry; } private static StatDrawEntry DescriptionEntry(Thing thing) { - return new StatDrawEntry(StatCategoryDefOf.Basics, "Description".Translate(), string.Empty, 99999) - { - overrideReportText = thing.GetDescription() - }; + StatDrawEntry statDrawEntry = new StatDrawEntry(StatCategoryDefOf.Basics, "Description".Translate(), string.Empty, 99999); + statDrawEntry.overrideReportText = thing.GetDescription(); + return statDrawEntry; } private static StatDrawEntry DescriptionEntry(WorldObject worldObject) { - return new StatDrawEntry(StatCategoryDefOf.Basics, "Description".Translate(), string.Empty, 99999) - { - overrideReportText = worldObject.GetDescription() - }; + StatDrawEntry statDrawEntry = new StatDrawEntry(StatCategoryDefOf.Basics, "Description".Translate(), string.Empty, 99999); + statDrawEntry.overrideReportText = worldObject.GetDescription(); + return statDrawEntry; } private static StatDrawEntry QualityEntry(Thing t) { - QualityCategory cat; + QualityCategory cat = default(QualityCategory); if (!t.TryGetQuality(out cat)) { return null; } - return new StatDrawEntry(StatCategoryDefOf.Basics, "Quality".Translate(), cat.GetLabel().CapitalizeFirst(), 99999) - { - overrideReportText = "QualityDescription".Translate() - }; + StatDrawEntry statDrawEntry = new StatDrawEntry(StatCategoryDefOf.Basics, "Quality".Translate(), cat.GetLabel().CapitalizeFirst(), 99999); + statDrawEntry.overrideReportText = "QualityDescription".Translate(); + return statDrawEntry; } private static void SelectEntry(StatDrawEntry rec, bool playSound = true) @@ -163,45 +198,45 @@ private static void DrawStatsWorker(Rect rect, Thing optionalThing, WorldObject { Rect outRect = new Rect(rect); outRect.width *= 0.5f; - Rect rect2 = new Rect(rect); - rect2.x = outRect.xMax; + Rect rect2 = new Rect(rect) + { + x = outRect.xMax + }; rect2.width = rect.xMax - rect2.x; Text.Font = GameFont.Small; - Rect viewRect = new Rect(0f, 0f, outRect.width - 16f, StatsReportUtility.listHeight); + Rect viewRect = new Rect(0f, 0f, (float)(outRect.width - 16.0), StatsReportUtility.listHeight); Widgets.BeginScrollView(outRect, ref StatsReportUtility.scrollPosition, viewRect, true); float num = 0f; - string b = null; - foreach (StatDrawEntry ent in StatsReportUtility.cachedDrawEntries) + string b = (string)null; + List.Enumerator enumerator = StatsReportUtility.cachedDrawEntries.GetEnumerator(); + try { - if (ent.category.LabelCap != b) + StatDrawEntry ent; + while (enumerator.MoveNext()) { - Widgets.ListSeparator(ref num, viewRect.width, ent.category.LabelCap); - b = ent.category.LabelCap; + ent = enumerator.Current; + if (ent.category.LabelCap != b) + { + Widgets.ListSeparator(ref num, viewRect.width, ent.category.LabelCap); + b = ent.category.LabelCap; + } + num += ent.Draw(8f, num, (float)(viewRect.width - 8.0), StatsReportUtility.selectedEntry == ent, (Action)delegate + { + StatsReportUtility.SelectEntry(ent, true); + }); } - num += ent.Draw(8f, num, viewRect.width - 8f, StatsReportUtility.selectedEntry == ent, delegate - { - StatsReportUtility.SelectEntry(ent, true); - }); } - StatsReportUtility.listHeight = num + 100f; + finally + { + ((IDisposable)(object)enumerator).Dispose(); + } + StatsReportUtility.listHeight = (float)(num + 100.0); Widgets.EndScrollView(); Rect rect3 = rect2.ContractedBy(10f); GUI.BeginGroup(rect3); if (StatsReportUtility.selectedEntry != null) { - StatRequest optionalReq; - if (StatsReportUtility.selectedEntry.hasOptionalReq) - { - optionalReq = StatsReportUtility.selectedEntry.optionalReq; - } - else if (optionalThing != null) - { - optionalReq = StatRequest.For(optionalThing); - } - else - { - optionalReq = StatRequest.ForEmpty(); - } + StatRequest optionalReq = (!StatsReportUtility.selectedEntry.hasOptionalReq) ? ((optionalThing == null) ? StatRequest.ForEmpty() : StatRequest.For(optionalThing)) : StatsReportUtility.selectedEntry.optionalReq; string explanationText = StatsReportUtility.selectedEntry.GetExplanationText(optionalReq); Rect rect4 = rect3.AtZero(); Widgets.Label(rect4, explanationText); diff --git a/Assembly-CSharp/RimWorld/SteadyAtmosphereEffects.cs b/Assembly-CSharp/RimWorld/SteadyAtmosphereEffects.cs index eaed51001..1d6f688ca 100644 --- a/Assembly-CSharp/RimWorld/SteadyAtmosphereEffects.cs +++ b/Assembly-CSharp/RimWorld/SteadyAtmosphereEffects.cs @@ -1,4 +1,3 @@ -using System; using System.Collections.Generic; using UnityEngine; using Verse; @@ -47,7 +46,7 @@ public SteadyAtmosphereEffects(Map map) public void SteadyAtmosphereEffectsTick() { - if ((float)Find.TickManager.TicksGame % 97f == 0f && Rand.Value < 0.02f) + if ((float)Find.TickManager.TicksGame % 97.0 == 0.0 && Rand.Value < 0.019999999552965164) { this.RollForRainFire(); } @@ -55,9 +54,9 @@ public void SteadyAtmosphereEffectsTick() this.snowRate = this.map.weatherManager.SnowRate; this.rainRate = this.map.weatherManager.RainRate; this.deteriorationRate = Mathf.Lerp(1f, 5f, this.rainRate); - int num = Mathf.RoundToInt((float)this.map.Area * 0.0006f); + int num = Mathf.RoundToInt((float)((float)this.map.Area * 0.00060000002849847078)); int area = this.map.Area; - for (int i = 0; i < num; i++) + for (int num2 = 0; num2 < num; num2++) { if (this.cycleIndex >= area) { @@ -76,13 +75,13 @@ private void DoCellSteadyEffects(IntVec3 c) bool flag2 = room != null && room.UsesOutdoorTemperature; if (room == null || flag2) { - if (this.outdoorMeltAmount > 0f) + if (this.outdoorMeltAmount > 0.0) { - this.map.snowGrid.AddDepth(c, -this.outdoorMeltAmount); + this.map.snowGrid.AddDepth(c, (float)(0.0 - this.outdoorMeltAmount)); } - if (!flag && this.snowRate > 0.001f) + if (!flag && this.snowRate > 0.0010000000474974513) { - this.AddFallenSnowAt(c, 0.046f * this.map.weatherManager.SnowRate); + this.AddFallenSnowAt(c, (float)(0.046000000089406967 * this.map.weatherManager.SnowRate)); } } if (room != null) @@ -122,23 +121,28 @@ private void DoCellSteadyEffects(IntVec3 c) else { float temperature = room.Temperature; - if (temperature > 0f) + if (temperature > 0.0) { float num = this.MeltAmountAt(temperature); - if (num > 0f) + if (num > 0.0) { - this.map.snowGrid.AddDepth(c, -num); + this.map.snowGrid.AddDepth(c, (float)(0.0 - num)); } - if (room.RegionType.Passable() && temperature > SteadyAtmosphereEffects.AutoIgnitionTemperatureRange.min) + if (room.RegionType.Passable()) { - float value = Rand.Value; - if (value < SteadyAtmosphereEffects.AutoIgnitionTemperatureRange.InverseLerpThroughRange(temperature) * 0.7f && Rand.Chance(FireUtility.ChanceToStartFireIn(c, this.map))) + float num2 = temperature; + FloatRange autoIgnitionTemperatureRange = SteadyAtmosphereEffects.AutoIgnitionTemperatureRange; + if (num2 > autoIgnitionTemperatureRange.min) { - FireUtility.TryStartFireIn(c, this.map, 0.1f); - } - if (value < 0.33f) - { - MoteMaker.ThrowHeatGlow(c, this.map, 2.3f); + float value = Rand.Value; + if (value < SteadyAtmosphereEffects.AutoIgnitionTemperatureRange.InverseLerpThroughRange(temperature) * 0.699999988079071 && Rand.Chance(FireUtility.ChanceToStartFireIn(c, this.map))) + { + FireUtility.TryStartFireIn(c, this.map, 0.1f); + } + if (value < 0.33000001311302185) + { + MoteMaker.ThrowHeatGlow(c, this.map, 2.3f); + } } } } @@ -153,26 +157,38 @@ private void DoCellSteadyEffects(IntVec3 c) public static bool InDeterioratingPosition(Thing t) { - return !t.Position.Roofed(t.Map) && !SteadyAtmosphereEffects.ProtectedByEdifice(t.Position, t.Map); + if (t.Position.Roofed(t.Map)) + { + return false; + } + if (SteadyAtmosphereEffects.ProtectedByEdifice(t.Position, t.Map)) + { + return false; + } + return true; } private static bool ProtectedByEdifice(IntVec3 c, Map map) { Building edifice = c.GetEdifice(map); - return edifice != null && edifice.def.building != null && edifice.def.building.preventDeterioration; + if (edifice != null && edifice.def.building != null && edifice.def.building.preventDeterioration) + { + return true; + } + return false; } private float MeltAmountAt(float temperature) { - if (temperature < 0f) + if (temperature < 0.0) { return 0f; } - if (temperature < 10f) + if (temperature < 10.0) { - return temperature * temperature * 0.0058f * 0.1f; + return (float)(temperature * temperature * 0.0057999999262392521 * 0.10000000149011612); } - return temperature * 0.0058f; + return (float)(temperature * 0.0057999999262392521); } public void AddFallenSnowAt(IntVec3 c, float baseAmount) @@ -181,14 +197,14 @@ public void AddFallenSnowAt(IntVec3 c, float baseAmount) { this.snowNoise = new Perlin(0.039999999105930328, 2.0, 0.5, 5, Rand.Range(0, 651431), QualityMode.Medium); } - float num = this.snowNoise.GetValue(c); - num += 1f; - num *= 0.5f; - if (num < 0.5f) + float value = this.snowNoise.GetValue(c); + value = (float)(value + 1.0); + value = (float)(value * 0.5); + if (value < 0.5) { - num = 0.5f; + value = 0.5f; } - float depthToAdd = baseAmount * num; + float depthToAdd = baseAmount * value; this.map.snowGrid.AddDepth(c, depthToAdd); } @@ -204,36 +220,37 @@ public static float FinalDeteriorationRate(Thing t) private void TryDoDeteriorate(Thing t, IntVec3 c, bool checkEdifice) { float num = SteadyAtmosphereEffects.FinalDeteriorationRate(t); - if (num < 0.001f) - { - return; - } - float num2 = this.deteriorationRate * num / 36f; - if (Rand.Value < num2 && (!checkEdifice || !SteadyAtmosphereEffects.ProtectedByEdifice(c, t.Map))) + if (!(num < 0.0010000000474974513)) { - t.TakeDamage(new DamageInfo(DamageDefOf.Deterioration, 1, -1f, null, null, null, DamageInfo.SourceCategory.ThingOrUnknown)); + float num2 = (float)(this.deteriorationRate * num / 36.0); + if (Rand.Value < num2) + { + if (checkEdifice && SteadyAtmosphereEffects.ProtectedByEdifice(c, t.Map)) + return; + t.TakeDamage(new DamageInfo(DamageDefOf.Deterioration, 1, -1f, null, null, null, DamageInfo.SourceCategory.ThingOrUnknown)); + } } } private void RollForRainFire() { - float num = 0.2f * (float)this.map.listerBuildings.allBuildingsColonistElecFire.Count * this.map.weatherManager.RainRate; - if (Rand.Value > num) + float num = (float)(0.20000000298023224 * (float)this.map.listerBuildings.allBuildingsColonistElecFire.Count * this.map.weatherManager.RainRate); + if (!(Rand.Value > num)) { - return; - } - Building building = this.map.listerBuildings.allBuildingsColonistElecFire.RandomElement(); - if (!this.map.roofGrid.Roofed(building.Position)) - { - ThingWithComps thingWithComps = building; - CompPowerTrader comp = thingWithComps.GetComp(); - if ((comp != null && comp.PowerOn && comp.Props.shortCircuitInRain) || (thingWithComps.GetComp() != null && thingWithComps.GetComp().StoredEnergy > 100f)) + Building building = this.map.listerBuildings.allBuildingsColonistElecFire.RandomElement(); + if (!this.map.roofGrid.Roofed(building.Position)) { - GenExplosion.DoExplosion(building.OccupiedRect().RandomCell, this.map, 1.9f, DamageDefOf.Flame, null, null, null, null, null, 0f, 1, false, null, 0f, 1); - Find.LetterStack.ReceiveLetter("LetterLabelShortCircuit".Translate(), "ShortCircuitRain".Translate(new object[] + ThingWithComps thingWithComps = building; + CompPowerTrader comp = thingWithComps.GetComp(); + if (comp == null || !comp.PowerOn || !comp.Props.shortCircuitInRain) { - building.Label - }), LetterDefOf.BadUrgent, new TargetInfo(building.Position, building.Map, false), null); + if (thingWithComps.GetComp() == null) + return; + if (!(thingWithComps.GetComp().StoredEnergy > 100.0)) + return; + } + GenExplosion.DoExplosion(building.OccupiedRect().RandomCell, this.map, 1.9f, DamageDefOf.Flame, null, null, null, null, null, 0f, 1, false, null, 0f, 1); + Find.LetterStack.ReceiveLetter("LetterLabelShortCircuit".Translate(), "ShortCircuitRain".Translate(building.Label), LetterDefOf.BadUrgent, new TargetInfo(building.Position, building.Map, false), (string)null); } } } diff --git a/Assembly-CSharp/RimWorld/StealAIDebugDrawer.cs b/Assembly-CSharp/RimWorld/StealAIDebugDrawer.cs index c90083e1c..bf4526129 100644 --- a/Assembly-CSharp/RimWorld/StealAIDebugDrawer.cs +++ b/Assembly-CSharp/RimWorld/StealAIDebugDrawer.cs @@ -1,4 +1,3 @@ -using System; using System.Collections.Generic; using Verse; using Verse.AI.Group; @@ -18,69 +17,67 @@ public static void DebugDraw() if (!DebugViewSettings.drawStealDebug) { StealAIDebugDrawer.debugDrawLord = null; - return; } - Lord lord = StealAIDebugDrawer.debugDrawLord; - StealAIDebugDrawer.debugDrawLord = StealAIDebugDrawer.FindHostileLord(); - if (StealAIDebugDrawer.debugDrawLord == null) - { - return; - } - StealAIDebugDrawer.CheckInitDebugDrawGrid(); - float num = StealAIUtility.StartStealingMarketValueThreshold(StealAIDebugDrawer.debugDrawLord); - if (lord != StealAIDebugDrawer.debugDrawLord) - { - foreach (IntVec3 current in Find.VisibleMap.AllCells) - { - StealAIDebugDrawer.debugDrawGrid[current] = (StealAIDebugDrawer.TotalMarketValueAround(current, Find.VisibleMap, StealAIDebugDrawer.debugDrawLord.ownedPawns.Count) > num); - } - } - foreach (IntVec3 current2 in Find.VisibleMap.AllCells) - { - if (StealAIDebugDrawer.debugDrawGrid[current2]) - { - CellRenderer.RenderCell(current2, 0.5f); - } - } - StealAIDebugDrawer.tmpToSteal.Clear(); - for (int i = 0; i < StealAIDebugDrawer.debugDrawLord.ownedPawns.Count; i++) + else { - Pawn pawn = StealAIDebugDrawer.debugDrawLord.ownedPawns[i]; - Thing thing; - if (StealAIUtility.TryFindBestItemToSteal(pawn.Position, pawn.Map, 7f, out thing, pawn, StealAIDebugDrawer.tmpToSteal)) + Lord lord = StealAIDebugDrawer.debugDrawLord; + StealAIDebugDrawer.debugDrawLord = StealAIDebugDrawer.FindHostileLord(); + if (StealAIDebugDrawer.debugDrawLord != null) { - GenDraw.DrawLineBetween(pawn.TrueCenter(), thing.TrueCenter()); - StealAIDebugDrawer.tmpToSteal.Add(thing); + StealAIDebugDrawer.CheckInitDebugDrawGrid(); + float num = StealAIUtility.StartStealingMarketValueThreshold(StealAIDebugDrawer.debugDrawLord); + if (lord != StealAIDebugDrawer.debugDrawLord) + { + foreach (IntVec3 allCell in Find.VisibleMap.AllCells) + { + StealAIDebugDrawer.debugDrawGrid[allCell] = (StealAIDebugDrawer.TotalMarketValueAround(allCell, Find.VisibleMap, StealAIDebugDrawer.debugDrawLord.ownedPawns.Count) > num); + } + } + foreach (IntVec3 allCell2 in Find.VisibleMap.AllCells) + { + if (StealAIDebugDrawer.debugDrawGrid[allCell2]) + { + CellRenderer.RenderCell(allCell2, 0.5f); + } + } + StealAIDebugDrawer.tmpToSteal.Clear(); + for (int i = 0; i < StealAIDebugDrawer.debugDrawLord.ownedPawns.Count; i++) + { + Pawn pawn = StealAIDebugDrawer.debugDrawLord.ownedPawns[i]; + Thing thing = default(Thing); + if (StealAIUtility.TryFindBestItemToSteal(pawn.Position, pawn.Map, 7f, out thing, pawn, StealAIDebugDrawer.tmpToSteal)) + { + GenDraw.DrawLineBetween(pawn.TrueCenter(), thing.TrueCenter()); + StealAIDebugDrawer.tmpToSteal.Add(thing); + } + } + StealAIDebugDrawer.tmpToSteal.Clear(); } } - StealAIDebugDrawer.tmpToSteal.Clear(); } public static void Notify_ThingChanged(Thing thing) { - if (StealAIDebugDrawer.debugDrawLord == null) - { - return; - } - StealAIDebugDrawer.CheckInitDebugDrawGrid(); - if (thing.def.category != ThingCategory.Building && thing.def.category != ThingCategory.Item && thing.def.passability != Traversability.Impassable) - { - return; - } - if (thing.def.passability == Traversability.Impassable) + if (StealAIDebugDrawer.debugDrawLord != null) { - StealAIDebugDrawer.debugDrawLord = null; - } - else - { - int num = GenRadial.NumCellsInRadius(8f); - float num2 = StealAIUtility.StartStealingMarketValueThreshold(StealAIDebugDrawer.debugDrawLord); - for (int i = 0; i < num; i++) + StealAIDebugDrawer.CheckInitDebugDrawGrid(); + if (thing.def.category != ThingCategory.Building && thing.def.category != ThingCategory.Item && thing.def.passability != Traversability.Impassable) + return; + if (thing.def.passability == Traversability.Impassable) { - IntVec3 intVec = thing.Position + GenRadial.RadialPattern[i]; - if (intVec.InBounds(thing.Map)) + StealAIDebugDrawer.debugDrawLord = null; + } + else + { + int num = GenRadial.NumCellsInRadius(8f); + float num2 = StealAIUtility.StartStealingMarketValueThreshold(StealAIDebugDrawer.debugDrawLord); + for (int num3 = 0; num3 < num; num3++) { - StealAIDebugDrawer.debugDrawGrid[intVec] = (StealAIDebugDrawer.TotalMarketValueAround(intVec, Find.VisibleMap, StealAIDebugDrawer.debugDrawLord.ownedPawns.Count) > num2); + IntVec3 intVec = thing.Position + GenRadial.RadialPattern[num3]; + if (intVec.InBounds(thing.Map)) + { + StealAIDebugDrawer.debugDrawGrid[intVec] = (StealAIDebugDrawer.TotalMarketValueAround(intVec, Find.VisibleMap, StealAIDebugDrawer.debugDrawLord.ownedPawns.Count) > num2); + } } } } @@ -94,15 +91,15 @@ private static float TotalMarketValueAround(IntVec3 center, Map map, int pawnsCo } float num = 0f; StealAIDebugDrawer.tmpToSteal.Clear(); - for (int i = 0; i < pawnsCount; i++) + for (int num2 = 0; num2 < pawnsCount; num2++) { - IntVec3 intVec = center + GenRadial.RadialPattern[i]; + IntVec3 intVec = center + GenRadial.RadialPattern[num2]; if (!intVec.InBounds(map) || intVec.Impassable(map) || !GenSight.LineOfSight(center, intVec, map, false, null, 0, 0)) { intVec = center; } - Thing thing; - if (StealAIUtility.TryFindBestItemToSteal(intVec, map, 7f, out thing, null, StealAIDebugDrawer.tmpToSteal)) + Thing thing = default(Thing); + if (StealAIUtility.TryFindBestItemToSteal(intVec, map, 7f, out thing, (Pawn)null, StealAIDebugDrawer.tmpToSteal)) { num += StealAIUtility.GetValue(thing); StealAIDebugDrawer.tmpToSteal.Add(thing); @@ -118,12 +115,9 @@ private static Lord FindHostileLord() List lords = Find.VisibleMap.lordManager.lords; for (int i = 0; i < lords.Count; i++) { - if (lords[i].faction.HostileTo(Faction.OfPlayer)) + if (lords[i].faction.HostileTo(Faction.OfPlayer) && (lord == null || lords[i].ownedPawns.Count > lord.ownedPawns.Count)) { - if (lord == null || lords[i].ownedPawns.Count > lord.ownedPawns.Count) - { - lord = lords[i]; - } + lord = lords[i]; } } return lord; diff --git a/Assembly-CSharp/RimWorld/StealAIUtility.cs b/Assembly-CSharp/RimWorld/StealAIUtility.cs index 00aedc25a..c46f8ab3d 100644 --- a/Assembly-CSharp/RimWorld/StealAIUtility.cs +++ b/Assembly-CSharp/RimWorld/StealAIUtility.cs @@ -24,18 +24,41 @@ public static bool TryFindBestItemToSteal(IntVec3 root, Map map, float maxDist, item = null; return false; } - if ((thief != null && !map.reachability.CanReachMapEdge(thief.Position, TraverseParms.For(thief, Danger.Some, TraverseMode.ByPawn, false))) || (thief == null && !map.reachability.CanReachMapEdge(root, TraverseParms.For(TraverseMode.PassDoors, Danger.Some, false)))) + if (thief != null && !map.reachability.CanReachMapEdge(thief.Position, TraverseParms.For(thief, Danger.Some, TraverseMode.ByPawn, false))) { - item = null; - return false; + goto IL_009d; } - Predicate validator = (Thing t) => (thief == null || thief.CanReserve(t, 1, -1, null, false)) && (disallowed == null || !disallowed.Contains(t)) && t.def.stealable && !t.IsBurning(); - item = GenClosest.ClosestThing_Regionwise_ReachablePrioritized(root, map, ThingRequest.ForGroup(ThingRequestGroup.HaulableEverOrMinifiable), PathEndMode.ClosestTouch, TraverseParms.For(TraverseMode.NoPassClosedDoors, Danger.Some, false), maxDist, validator, (Thing x) => StealAIUtility.GetValue(x), 15, 15); - if (item != null && StealAIUtility.GetValue(item) < 320f) + if (thief == null && !map.reachability.CanReachMapEdge(root, TraverseParms.For(TraverseMode.PassDoors, Danger.Some, false))) + goto IL_009d; + Predicate validator = (Predicate)delegate(Thing t) + { + if (thief != null && !thief.CanReserve(t, 1, -1, null, false)) + { + return false; + } + if (disallowed != null && disallowed.Contains(t)) + { + return false; + } + if (!t.def.stealable) + { + return false; + } + if (t.IsBurning()) + { + return false; + } + return true; + }; + item = GenClosest.ClosestThing_Regionwise_ReachablePrioritized(root, map, ThingRequest.ForGroup(ThingRequestGroup.HaulableEverOrMinifiable), PathEndMode.ClosestTouch, TraverseParms.For(TraverseMode.NoPassClosedDoors, Danger.Some, false), maxDist, validator, (Func)((Thing x) => StealAIUtility.GetValue(x)), 15, 15); + if (item != null && StealAIUtility.GetValue(item) < 320.0) { item = null; } return item != null; + IL_009d: + item = null; + return false; } public static float TotalMarketValueAround(List pawns) @@ -44,14 +67,11 @@ public static float TotalMarketValueAround(List pawns) StealAIUtility.tmpToSteal.Clear(); for (int i = 0; i < pawns.Count; i++) { - if (pawns[i].Spawned) + Thing thing = default(Thing); + if (pawns[i].Spawned && StealAIUtility.TryFindBestItemToSteal(pawns[i].Position, pawns[i].Map, 7f, out thing, pawns[i], StealAIUtility.tmpToSteal)) { - Thing thing; - if (StealAIUtility.TryFindBestItemToSteal(pawns[i].Position, pawns[i].Map, 7f, out thing, pawns[i], StealAIUtility.tmpToSteal)) - { - num += StealAIUtility.GetValue(thing); - StealAIUtility.tmpToSteal.Add(thing); - } + num += StealAIUtility.GetValue(thing); + StealAIUtility.tmpToSteal.Add(thing); } } StealAIUtility.tmpToSteal.Clear(); diff --git a/Assembly-CSharp/RimWorld/StockGenerator.cs b/Assembly-CSharp/RimWorld/StockGenerator.cs index e03091fe9..4cbff94cf 100644 --- a/Assembly-CSharp/RimWorld/StockGenerator.cs +++ b/Assembly-CSharp/RimWorld/StockGenerator.cs @@ -1,6 +1,4 @@ -using System; using System.Collections.Generic; -using System.Diagnostics; using UnityEngine; using Verse; @@ -26,13 +24,9 @@ public virtual void ResolveReferences(TraderKindDef trader) this.trader = trader; } - [DebuggerHidden] public virtual IEnumerable ConfigErrors(TraderKindDef parentDef) { - StockGenerator.c__Iterator174 c__Iterator = new StockGenerator.c__Iterator174(); - StockGenerator.c__Iterator174 expr_07 = c__Iterator; - expr_07.$PC = -2; - return expr_07; + yield break; } public abstract IEnumerable GenerateThings(int forTile); @@ -52,26 +46,26 @@ public bool TryGetPriceType(ThingDef thingDef, TradeAction action, out PriceType protected int RandomCountOf(ThingDef def) { - if (this.countRange.max > 0 && this.totalPriceRange.max <= 0f) + if (this.countRange.max > 0 && this.totalPriceRange.max <= 0.0) { return this.countRange.RandomInRange; } - if (this.countRange.max <= 0 && this.totalPriceRange.max > 0f) + if (this.countRange.max <= 0 && this.totalPriceRange.max > 0.0) { return Mathf.RoundToInt(this.totalPriceRange.RandomInRange / def.BaseMarketValue); } int num = 0; int randomInRange; - do + while (true) { randomInRange = this.countRange.RandomInRange; num++; - if (num > 100) + if (num <= 100 && !this.totalPriceRange.Includes((float)randomInRange * def.BaseMarketValue)) { - break; + continue; } + break; } - while (!this.totalPriceRange.Includes((float)randomInRange * def.BaseMarketValue)); return randomInRange; } } diff --git a/Assembly-CSharp/RimWorld/StockGeneratorUtility.cs b/Assembly-CSharp/RimWorld/StockGeneratorUtility.cs index 0095a2d71..004e15438 100644 --- a/Assembly-CSharp/RimWorld/StockGeneratorUtility.cs +++ b/Assembly-CSharp/RimWorld/StockGeneratorUtility.cs @@ -1,6 +1,5 @@ using System; using System.Collections.Generic; -using System.Diagnostics; using System.Linq; using Verse; @@ -8,17 +7,27 @@ namespace RimWorld { public class StockGeneratorUtility { - [DebuggerHidden] public static IEnumerable TryMakeForStock(ThingDef thingDef, int count) { - StockGeneratorUtility.c__Iterator175 c__Iterator = new StockGeneratorUtility.c__Iterator175(); - c__Iterator.thingDef = thingDef; - c__Iterator.count = count; - c__Iterator.<$>thingDef = thingDef; - c__Iterator.<$>count = count; - StockGeneratorUtility.c__Iterator175 expr_23 = c__Iterator; - expr_23.$PC = -2; - return expr_23; + if (thingDef.MadeFromStuff) + { + for (int i = 0; i < count; i++) + { + Thing th2 = StockGeneratorUtility.TryMakeForStockSingle(thingDef, 1); + if (th2 != null) + { + yield return th2; + } + } + } + else + { + Thing th = StockGeneratorUtility.TryMakeForStockSingle(thingDef, count); + if (th != null) + { + yield return th; + } + } } public static Thing TryMakeForStockSingle(ThingDef thingDef, int stackCount) @@ -37,7 +46,7 @@ public static Thing TryMakeForStockSingle(ThingDef thingDef, int stackCount) { stuff = (from st in DefDatabase.AllDefs where st.IsStuff && st.stuffProps.CanMake(thingDef) - select st).RandomElementByWeight((ThingDef st) => st.stuffProps.commonality); + select st).RandomElementByWeight((Func)((ThingDef st) => st.stuffProps.commonality)); } Thing thing = ThingMaker.MakeThing(thingDef, stuff); thing.stackCount = stackCount; diff --git a/Assembly-CSharp/RimWorld/StockGenerator_Animals.cs b/Assembly-CSharp/RimWorld/StockGenerator_Animals.cs index 38d14a4f9..7d40ae20c 100644 --- a/Assembly-CSharp/RimWorld/StockGenerator_Animals.cs +++ b/Assembly-CSharp/RimWorld/StockGenerator_Animals.cs @@ -1,6 +1,6 @@ using System; using System.Collections.Generic; -using System.Diagnostics; +using System.Linq; using System.Text; using Verse; @@ -42,16 +42,28 @@ public class StockGenerator_Animals : StockGenerator } }; - [DebuggerHidden] public override IEnumerable GenerateThings(int forTile) { - StockGenerator_Animals.c__Iterator17F c__Iterator17F = new StockGenerator_Animals.c__Iterator17F(); - c__Iterator17F.forTile = forTile; - c__Iterator17F.<$>forTile = forTile; - c__Iterator17F.<>f__this = this; - StockGenerator_Animals.c__Iterator17F expr_1C = c__Iterator17F; - expr_1C.$PC = -2; - return expr_1C; + int numKinds = this.kindCountRange.RandomInRange; + int count = base.countRange.RandomInRange; + List kinds = new List(); + int i = 0; + PawnKindDef kind; + while (i < numKinds && (from k in DefDatabase.AllDefs + where !((_003CGenerateThings_003Ec__Iterator17F)/*Error near IL_0069: stateMachine*/)._003Ckinds_003E__2.Contains(k) && ((_003CGenerateThings_003Ec__Iterator17F)/*Error near IL_0069: stateMachine*/)._003C_003Ef__this.PawnKindAllowed(k, ((_003CGenerateThings_003Ec__Iterator17F)/*Error near IL_0069: stateMachine*/).forTile) + select k).TryRandomElementByWeight((Func)((PawnKindDef k) => ((_003CGenerateThings_003Ec__Iterator17F)/*Error near IL_007a: stateMachine*/)._003C_003Ef__this.SelectionChance(k)), out kind)) + { + kinds.Add(kind); + i++; + } + int j = 0; + PawnKindDef kind2; + while (j < count && ((IEnumerable)kinds).TryRandomElement(out kind2)) + { + PawnGenerationRequest request = new PawnGenerationRequest(kind2, null, PawnGenerationContext.NonPlayer, forTile, false, false, false, false, true, false, 1f, false, true, true, false, false, null, default(float?), default(float?), default(Gender?), default(float?), (string)null); + yield return (Thing)PawnGenerator.GeneratePawn(request); + j++; + } } private float SelectionChance(PawnKindDef k) @@ -66,46 +78,50 @@ public override bool HandlesThingDef(ThingDef thingDef) private bool PawnKindAllowed(PawnKindDef kind, int forTile) { - if (!kind.RaceProps.Animal || kind.RaceProps.wildness < this.minWildness || kind.RaceProps.wildness > this.maxWildness || kind.RaceProps.wildness > 1f) - { - return false; - } - if (this.checkTemperature) + if (kind.RaceProps.Animal && !(kind.RaceProps.wildness < this.minWildness) && !(kind.RaceProps.wildness > this.maxWildness) && !(kind.RaceProps.wildness > 1.0)) { - int num = forTile; - if (num == -1 && Find.AnyPlayerHomeMap != null) + if (this.checkTemperature) { - num = Find.AnyPlayerHomeMap.Tile; + int num = forTile; + if (num == -1 && Find.AnyPlayerHomeMap != null) + { + num = Find.AnyPlayerHomeMap.Tile; + } + if (num != -1 && !Find.World.tileTemperatures.SeasonAndOutdoorTemperatureAcceptableFor(num, kind.race)) + { + return false; + } } - if (num != -1 && !Find.World.tileTemperatures.SeasonAndOutdoorTemperatureAcceptableFor(num, kind.race)) + if (kind.race.tradeTags == null) { return false; } + if (this.tradeTags.Find((Predicate)((string x) => kind.race.tradeTags.Contains(x))) == null) + { + return false; + } + return true; } - return kind.race.tradeTags != null && this.tradeTags.Find((string x) => kind.race.tradeTags.Contains(x)) != null; + return false; } public void LogAnimalChances() { StringBuilder stringBuilder = new StringBuilder(); - foreach (PawnKindDef current in DefDatabase.AllDefs) + foreach (PawnKindDef allDef in DefDatabase.AllDefs) { - stringBuilder.AppendLine(current.defName + ": " + this.SelectionChance(current).ToString("F2")); + stringBuilder.AppendLine(allDef.defName + ": " + this.SelectionChance(allDef).ToString("F2")); } Log.Message(stringBuilder.ToString()); } internal static void LogStockGeneration() { - new StockGenerator_Animals - { - tradeTags = new List(), - tradeTags = - { - "StandardAnimal", - "BadassAnimal" - } - }.LogAnimalChances(); + StockGenerator_Animals stockGenerator_Animals = new StockGenerator_Animals(); + stockGenerator_Animals.tradeTags = new List(); + stockGenerator_Animals.tradeTags.Add("StandardAnimal"); + stockGenerator_Animals.tradeTags.Add("BadassAnimal"); + stockGenerator_Animals.LogAnimalChances(); } } } diff --git a/Assembly-CSharp/RimWorld/StockGenerator_Armor.cs b/Assembly-CSharp/RimWorld/StockGenerator_Armor.cs index 0b0a42a6c..f99db18f5 100644 --- a/Assembly-CSharp/RimWorld/StockGenerator_Armor.cs +++ b/Assembly-CSharp/RimWorld/StockGenerator_Armor.cs @@ -1,4 +1,3 @@ -using System; using Verse; namespace RimWorld @@ -29,7 +28,15 @@ public class StockGenerator_Armor : StockGenerator_MiscItems public override bool HandlesThingDef(ThingDef td) { - return td == ThingDefOf.Apparel_ShieldBelt || td == ThingDefOf.Apparel_SmokepopBelt || (base.HandlesThingDef(td) && td.IsApparel && (td.GetStatValueAbstract(StatDefOf.ArmorRating_Blunt, null) > 0.15f || td.GetStatValueAbstract(StatDefOf.ArmorRating_Sharp, null) > 0.15f)); + if (td == ThingDefOf.Apparel_ShieldBelt) + { + return true; + } + if (td == ThingDefOf.Apparel_SmokepopBelt) + { + return true; + } + return base.HandlesThingDef(td) && td.IsApparel && (td.GetStatValueAbstract(StatDefOf.ArmorRating_Blunt, null) > 0.15000000596046448 || td.GetStatValueAbstract(StatDefOf.ArmorRating_Sharp, null) > 0.15000000596046448); } protected override float SelectionWeight(ThingDef thingDef) diff --git a/Assembly-CSharp/RimWorld/StockGenerator_Art.cs b/Assembly-CSharp/RimWorld/StockGenerator_Art.cs index a886af89b..d90d818c1 100644 --- a/Assembly-CSharp/RimWorld/StockGenerator_Art.cs +++ b/Assembly-CSharp/RimWorld/StockGenerator_Art.cs @@ -1,4 +1,3 @@ -using System; using Verse; namespace RimWorld diff --git a/Assembly-CSharp/RimWorld/StockGenerator_BuyArt.cs b/Assembly-CSharp/RimWorld/StockGenerator_BuyArt.cs index 44a4d8511..7113a5e9f 100644 --- a/Assembly-CSharp/RimWorld/StockGenerator_BuyArt.cs +++ b/Assembly-CSharp/RimWorld/StockGenerator_BuyArt.cs @@ -1,19 +1,13 @@ -using System; using System.Collections.Generic; -using System.Diagnostics; using Verse; namespace RimWorld { public class StockGenerator_BuyArt : StockGenerator { - [DebuggerHidden] public override IEnumerable GenerateThings(int forTile) { - StockGenerator_BuyArt.c__Iterator176 c__Iterator = new StockGenerator_BuyArt.c__Iterator176(); - StockGenerator_BuyArt.c__Iterator176 expr_07 = c__Iterator; - expr_07.$PC = -2; - return expr_07; + yield break; } public override bool HandlesThingDef(ThingDef thingDef) diff --git a/Assembly-CSharp/RimWorld/StockGenerator_BuyExpensiveSimple.cs b/Assembly-CSharp/RimWorld/StockGenerator_BuyExpensiveSimple.cs index 84f98f5e8..b8b5c45e4 100644 --- a/Assembly-CSharp/RimWorld/StockGenerator_BuyExpensiveSimple.cs +++ b/Assembly-CSharp/RimWorld/StockGenerator_BuyExpensiveSimple.cs @@ -1,6 +1,4 @@ -using System; using System.Collections.Generic; -using System.Diagnostics; using Verse; namespace RimWorld @@ -9,13 +7,9 @@ public class StockGenerator_BuyExpensiveSimple : StockGenerator { public float minValuePerUnit = 15f; - [DebuggerHidden] public override IEnumerable GenerateThings(int forTile) { - StockGenerator_BuyExpensiveSimple.c__Iterator178 c__Iterator = new StockGenerator_BuyExpensiveSimple.c__Iterator178(); - StockGenerator_BuyExpensiveSimple.c__Iterator178 expr_07 = c__Iterator; - expr_07.$PC = -2; - return expr_07; + yield break; } public override bool HandlesThingDef(ThingDef thingDef) diff --git a/Assembly-CSharp/RimWorld/StockGenerator_BuySingleDef.cs b/Assembly-CSharp/RimWorld/StockGenerator_BuySingleDef.cs index 68d274c14..926399738 100644 --- a/Assembly-CSharp/RimWorld/StockGenerator_BuySingleDef.cs +++ b/Assembly-CSharp/RimWorld/StockGenerator_BuySingleDef.cs @@ -1,6 +1,4 @@ -using System; using System.Collections.Generic; -using System.Diagnostics; using Verse; namespace RimWorld @@ -9,13 +7,9 @@ public class StockGenerator_BuySingleDef : StockGenerator { public ThingDef thingDef; - [DebuggerHidden] public override IEnumerable GenerateThings(int forTile) { - StockGenerator_BuySingleDef.c__Iterator179 c__Iterator = new StockGenerator_BuySingleDef.c__Iterator179(); - StockGenerator_BuySingleDef.c__Iterator179 expr_07 = c__Iterator; - expr_07.$PC = -2; - return expr_07; + yield break; } public override bool HandlesThingDef(ThingDef thingDef) diff --git a/Assembly-CSharp/RimWorld/StockGenerator_BuyWeirdOrganic.cs b/Assembly-CSharp/RimWorld/StockGenerator_BuyWeirdOrganic.cs index e20a6f11c..1f68adc15 100644 --- a/Assembly-CSharp/RimWorld/StockGenerator_BuyWeirdOrganic.cs +++ b/Assembly-CSharp/RimWorld/StockGenerator_BuyWeirdOrganic.cs @@ -1,19 +1,13 @@ -using System; using System.Collections.Generic; -using System.Diagnostics; using Verse; namespace RimWorld { public class StockGenerator_BuyWeirdOrganic : StockGenerator { - [DebuggerHidden] public override IEnumerable GenerateThings(int forTile) { - StockGenerator_BuyWeirdOrganic.c__Iterator177 c__Iterator = new StockGenerator_BuyWeirdOrganic.c__Iterator177(); - StockGenerator_BuyWeirdOrganic.c__Iterator177 expr_07 = c__Iterator; - expr_07.$PC = -2; - return expr_07; + yield break; } public override bool HandlesThingDef(ThingDef thingDef) diff --git a/Assembly-CSharp/RimWorld/StockGenerator_Category.cs b/Assembly-CSharp/RimWorld/StockGenerator_Category.cs index a817b52dd..eb920efa5 100644 --- a/Assembly-CSharp/RimWorld/StockGenerator_Category.cs +++ b/Assembly-CSharp/RimWorld/StockGenerator_Category.cs @@ -1,6 +1,5 @@ using System; using System.Collections.Generic; -using System.Diagnostics; using System.Linq; using Verse; @@ -16,19 +15,31 @@ public class StockGenerator_Category : StockGenerator private List excludedCategories; - [DebuggerHidden] public override IEnumerable GenerateThings(int forTile) { - StockGenerator_Category.c__Iterator17C c__Iterator17C = new StockGenerator_Category.c__Iterator17C(); - c__Iterator17C.<>f__this = this; - StockGenerator_Category.c__Iterator17C expr_0E = c__Iterator17C; - expr_0E.$PC = -2; - return expr_0E; + List generatedDefs = new List(); + int numThingDefsToUse = this.thingDefCountRange.RandomInRange; + int i = 0; + _003CGenerateThings_003Ec__Iterator17C _003CGenerateThings_003Ec__Iterator17C; + ThingDef chosenThingDef; + while (i < numThingDefsToUse && this.categoryDef.DescendantThingDefs.Where((Func)delegate(ThingDef t) + { + _003CGenerateThings_003Ec__Iterator17C = (_003CGenerateThings_003Ec__Iterator17C)/*Error near IL_0060: stateMachine*/; + return t.tradeability == Tradeability.Stockable && (int)t.techLevel <= (int)((_003CGenerateThings_003Ec__Iterator17C)/*Error near IL_0060: stateMachine*/)._003C_003Ef__this.maxTechLevelGenerate && !((_003CGenerateThings_003Ec__Iterator17C)/*Error near IL_0060: stateMachine*/)._003CgeneratedDefs_003E__0.Contains(t) && (((_003CGenerateThings_003Ec__Iterator17C)/*Error near IL_0060: stateMachine*/)._003C_003Ef__this.excludedThingDefs == null || !((_003CGenerateThings_003Ec__Iterator17C)/*Error near IL_0060: stateMachine*/)._003C_003Ef__this.excludedThingDefs.Contains(t)) && (((_003CGenerateThings_003Ec__Iterator17C)/*Error near IL_0060: stateMachine*/)._003C_003Ef__this.excludedCategories == null || !((_003CGenerateThings_003Ec__Iterator17C)/*Error near IL_0060: stateMachine*/)._003C_003Ef__this.excludedCategories.Any((Predicate)((ThingCategoryDef c) => c.DescendantThingDefs.Contains(t)))); + }).TryRandomElement(out chosenThingDef)) + { + foreach (Thing item in StockGeneratorUtility.TryMakeForStock(chosenThingDef, base.RandomCountOf(chosenThingDef))) + { + yield return item; + } + generatedDefs.Add(chosenThingDef); + i++; + } } public override bool HandlesThingDef(ThingDef t) { - return this.categoryDef.DescendantThingDefs.Contains(t) && t.techLevel <= this.maxTechLevelBuy && (this.excludedThingDefs == null || !this.excludedThingDefs.Contains(t)) && (this.excludedCategories == null || !this.excludedCategories.Any((ThingCategoryDef c) => c.DescendantThingDefs.Contains(t))); + return this.categoryDef.DescendantThingDefs.Contains(t) && (int)t.techLevel <= (int)base.maxTechLevelBuy && (this.excludedThingDefs == null || !this.excludedThingDefs.Contains(t)) && (this.excludedCategories == null || !this.excludedCategories.Any((Predicate)((ThingCategoryDef c) => c.DescendantThingDefs.Contains(t)))); } } } diff --git a/Assembly-CSharp/RimWorld/StockGenerator_Clothes.cs b/Assembly-CSharp/RimWorld/StockGenerator_Clothes.cs index 29cf196d1..0a4bb0dd9 100644 --- a/Assembly-CSharp/RimWorld/StockGenerator_Clothes.cs +++ b/Assembly-CSharp/RimWorld/StockGenerator_Clothes.cs @@ -1,4 +1,3 @@ -using System; using Verse; namespace RimWorld @@ -27,7 +26,11 @@ public class StockGenerator_Clothes : StockGenerator_MiscItems public override bool HandlesThingDef(ThingDef td) { - return td != ThingDefOf.Apparel_ShieldBelt && (base.HandlesThingDef(td) && td.IsApparel) && (td.GetStatValueAbstract(StatDefOf.ArmorRating_Blunt, null) < 0.15f || td.GetStatValueAbstract(StatDefOf.ArmorRating_Sharp, null) < 0.15f); + if (td == ThingDefOf.Apparel_ShieldBelt) + { + return false; + } + return base.HandlesThingDef(td) && td.IsApparel && (td.GetStatValueAbstract(StatDefOf.ArmorRating_Blunt, null) < 0.15000000596046448 || td.GetStatValueAbstract(StatDefOf.ArmorRating_Sharp, null) < 0.15000000596046448); } protected override float SelectionWeight(ThingDef thingDef) diff --git a/Assembly-CSharp/RimWorld/StockGenerator_MiscItems.cs b/Assembly-CSharp/RimWorld/StockGenerator_MiscItems.cs index 24fd431a7..7becc18f6 100644 --- a/Assembly-CSharp/RimWorld/StockGenerator_MiscItems.cs +++ b/Assembly-CSharp/RimWorld/StockGenerator_MiscItems.cs @@ -1,20 +1,24 @@ using System; using System.Collections.Generic; -using System.Diagnostics; +using System.Linq; using Verse; namespace RimWorld { public abstract class StockGenerator_MiscItems : StockGenerator { - [DebuggerHidden] public override IEnumerable GenerateThings(int forTile) { - StockGenerator_MiscItems.c__Iterator180 c__Iterator = new StockGenerator_MiscItems.c__Iterator180(); - c__Iterator.<>f__this = this; - StockGenerator_MiscItems.c__Iterator180 expr_0E = c__Iterator; - expr_0E.$PC = -2; - return expr_0E; + int count = base.countRange.RandomInRange; + int i = 0; + ThingDef finalDef; + while (i < count && (from t in DefDatabase.AllDefs + where ((_003CGenerateThings_003Ec__Iterator180)/*Error near IL_0048: stateMachine*/)._003C_003Ef__this.HandlesThingDef(t) && (int)t.techLevel <= (int)((_003CGenerateThings_003Ec__Iterator180)/*Error near IL_0048: stateMachine*/)._003C_003Ef__this.maxTechLevelGenerate + select t).TryRandomElementByWeight(new Func(this.SelectionWeight), out finalDef)) + { + yield return this.MakeThing(finalDef); + i++; + } } protected virtual Thing MakeThing(ThingDef def) @@ -24,7 +28,7 @@ protected virtual Thing MakeThing(ThingDef def) public override bool HandlesThingDef(ThingDef thingDef) { - return thingDef.tradeability == Tradeability.Stockable && thingDef.techLevel <= this.maxTechLevelBuy; + return thingDef.tradeability == Tradeability.Stockable && (int)thingDef.techLevel <= (int)base.maxTechLevelBuy; } protected virtual float SelectionWeight(ThingDef thingDef) diff --git a/Assembly-CSharp/RimWorld/StockGenerator_MultiDef.cs b/Assembly-CSharp/RimWorld/StockGenerator_MultiDef.cs index 0bd86e209..12aa3e5bc 100644 --- a/Assembly-CSharp/RimWorld/StockGenerator_MultiDef.cs +++ b/Assembly-CSharp/RimWorld/StockGenerator_MultiDef.cs @@ -1,6 +1,4 @@ -using System; using System.Collections.Generic; -using System.Diagnostics; using Verse; namespace RimWorld @@ -9,14 +7,13 @@ public class StockGenerator_MultiDef : StockGenerator { private List thingDefs = new List(); - [DebuggerHidden] public override IEnumerable GenerateThings(int forTile) { - StockGenerator_MultiDef.c__Iterator17B c__Iterator17B = new StockGenerator_MultiDef.c__Iterator17B(); - c__Iterator17B.<>f__this = this; - StockGenerator_MultiDef.c__Iterator17B expr_0E = c__Iterator17B; - expr_0E.$PC = -2; - return expr_0E; + ThingDef td = this.thingDefs.RandomElement(); + foreach (Thing item in StockGeneratorUtility.TryMakeForStock(td, base.RandomCountOf(td))) + { + yield return item; + } } public override bool HandlesThingDef(ThingDef thingDef) diff --git a/Assembly-CSharp/RimWorld/StockGenerator_SingleDef.cs b/Assembly-CSharp/RimWorld/StockGenerator_SingleDef.cs index 943ecedca..ec46b65ea 100644 --- a/Assembly-CSharp/RimWorld/StockGenerator_SingleDef.cs +++ b/Assembly-CSharp/RimWorld/StockGenerator_SingleDef.cs @@ -1,6 +1,4 @@ -using System; using System.Collections.Generic; -using System.Diagnostics; using Verse; namespace RimWorld @@ -9,14 +7,12 @@ public class StockGenerator_SingleDef : StockGenerator { private ThingDef thingDef; - [DebuggerHidden] public override IEnumerable GenerateThings(int forTile) { - StockGenerator_SingleDef.c__Iterator17A c__Iterator17A = new StockGenerator_SingleDef.c__Iterator17A(); - c__Iterator17A.<>f__this = this; - StockGenerator_SingleDef.c__Iterator17A expr_0E = c__Iterator17A; - expr_0E.$PC = -2; - return expr_0E; + foreach (Thing item in StockGeneratorUtility.TryMakeForStock(this.thingDef, base.RandomCountOf(this.thingDef))) + { + yield return item; + } } public override bool HandlesThingDef(ThingDef thingDef) diff --git a/Assembly-CSharp/RimWorld/StockGenerator_Slaves.cs b/Assembly-CSharp/RimWorld/StockGenerator_Slaves.cs index f3fb36bcb..d7d40873c 100644 --- a/Assembly-CSharp/RimWorld/StockGenerator_Slaves.cs +++ b/Assembly-CSharp/RimWorld/StockGenerator_Slaves.cs @@ -1,22 +1,28 @@ using System; using System.Collections.Generic; -using System.Diagnostics; +using System.Linq; using Verse; namespace RimWorld { public class StockGenerator_Slaves : StockGenerator { - [DebuggerHidden] public override IEnumerable GenerateThings(int forTile) { - StockGenerator_Slaves.c__Iterator17E c__Iterator17E = new StockGenerator_Slaves.c__Iterator17E(); - c__Iterator17E.forTile = forTile; - c__Iterator17E.<$>forTile = forTile; - c__Iterator17E.<>f__this = this; - StockGenerator_Slaves.c__Iterator17E expr_1C = c__Iterator17E; - expr_1C.$PC = -2; - return expr_1C; + if (!(Rand.Value > Find.Storyteller.intenderPopulation.PopulationIntent)) + { + int count = base.countRange.RandomInRange; + int i = 0; + Faction slaveFaction; + while (i < count && (from fac in Find.FactionManager.AllFactionsVisible + where fac != Faction.OfPlayer && fac.def.humanlikeFaction + select fac).TryRandomElement(out slaveFaction)) + { + PawnGenerationRequest request = new PawnGenerationRequest(PawnKindDefOf.Slave, slaveFaction, PawnGenerationContext.NonPlayer, forTile, false, false, false, false, true, false, 1f, !base.trader.orbital, true, true, false, false, null, default(float?), default(float?), default(Gender?), default(float?), (string)null); + yield return (Thing)PawnGenerator.GeneratePawn(request); + i++; + } + } } public override bool HandlesThingDef(ThingDef thingDef) diff --git a/Assembly-CSharp/RimWorld/StockGenerator_Tag.cs b/Assembly-CSharp/RimWorld/StockGenerator_Tag.cs index 2eb9fbc88..4afd0c0bf 100644 --- a/Assembly-CSharp/RimWorld/StockGenerator_Tag.cs +++ b/Assembly-CSharp/RimWorld/StockGenerator_Tag.cs @@ -1,6 +1,6 @@ using System; using System.Collections.Generic; -using System.Diagnostics; +using System.Linq; using Verse; namespace RimWorld @@ -11,19 +11,28 @@ public class StockGenerator_Tag : StockGenerator private IntRange thingDefCountRange = IntRange.one; - [DebuggerHidden] public override IEnumerable GenerateThings(int forTile) { - StockGenerator_Tag.c__Iterator17D c__Iterator17D = new StockGenerator_Tag.c__Iterator17D(); - c__Iterator17D.<>f__this = this; - StockGenerator_Tag.c__Iterator17D expr_0E = c__Iterator17D; - expr_0E.$PC = -2; - return expr_0E; + List generatedDefs = new List(); + int numThingDefsToUse = this.thingDefCountRange.RandomInRange; + int i = 0; + ThingDef chosenThingDef; + while (i < numThingDefsToUse && (from d in DefDatabase.AllDefs + where ((_003CGenerateThings_003Ec__Iterator17D)/*Error near IL_0055: stateMachine*/)._003C_003Ef__this.HandlesThingDef(d) && !((_003CGenerateThings_003Ec__Iterator17D)/*Error near IL_0055: stateMachine*/)._003CgeneratedDefs_003E__0.Contains(d) + select d).TryRandomElement(out chosenThingDef)) + { + foreach (Thing item in StockGeneratorUtility.TryMakeForStock(chosenThingDef, base.RandomCountOf(chosenThingDef))) + { + yield return item; + } + generatedDefs.Add(chosenThingDef); + i++; + } } public override bool HandlesThingDef(ThingDef thingDef) { - return thingDef.tradeTags != null && thingDef.tradeability == Tradeability.Stockable && thingDef.techLevel <= this.maxTechLevelBuy && thingDef.tradeTags.Contains(this.tradeTag); + return thingDef.tradeTags != null && thingDef.tradeability == Tradeability.Stockable && (int)thingDef.techLevel <= (int)base.maxTechLevelBuy && thingDef.tradeTags.Contains(this.tradeTag); } } } diff --git a/Assembly-CSharp/RimWorld/StockGenerator_WeaponsRanged.cs b/Assembly-CSharp/RimWorld/StockGenerator_WeaponsRanged.cs index 923880120..88f344d1e 100644 --- a/Assembly-CSharp/RimWorld/StockGenerator_WeaponsRanged.cs +++ b/Assembly-CSharp/RimWorld/StockGenerator_WeaponsRanged.cs @@ -1,4 +1,3 @@ -using System; using Verse; namespace RimWorld diff --git a/Assembly-CSharp/RimWorld/StoragePriority.cs b/Assembly-CSharp/RimWorld/StoragePriority.cs index e62258a78..12b429a76 100644 --- a/Assembly-CSharp/RimWorld/StoragePriority.cs +++ b/Assembly-CSharp/RimWorld/StoragePriority.cs @@ -1,14 +1,12 @@ -using System; - namespace RimWorld { public enum StoragePriority : byte { - Unstored, - Low, - Normal, - Preferred, - Important, - Critical + Unstored = 0, + Low = 1, + Normal = 2, + Preferred = 3, + Important = 4, + Critical = 5 } } diff --git a/Assembly-CSharp/RimWorld/StoragePriorityHelper.cs b/Assembly-CSharp/RimWorld/StoragePriorityHelper.cs index eff5ccaa2..4bc00f330 100644 --- a/Assembly-CSharp/RimWorld/StoragePriorityHelper.cs +++ b/Assembly-CSharp/RimWorld/StoragePriorityHelper.cs @@ -1,4 +1,3 @@ -using System; using Verse; namespace RimWorld @@ -10,20 +9,34 @@ public static string Label(this StoragePriority p) switch (p) { case StoragePriority.Unstored: + { return "StoragePriorityUnstored".Translate(); + } case StoragePriority.Low: + { return "StoragePriorityLow".Translate(); + } case StoragePriority.Normal: + { return "StoragePriorityNormal".Translate(); + } case StoragePriority.Preferred: + { return "StoragePriorityPreferred".Translate(); + } case StoragePriority.Important: + { return "StoragePriorityImportant".Translate(); + } case StoragePriority.Critical: + { return "StoragePriorityCritical".Translate(); + } default: + { return "Unknown"; } + } } } } diff --git a/Assembly-CSharp/RimWorld/StorageSettingsClipboard.cs b/Assembly-CSharp/RimWorld/StorageSettingsClipboard.cs index 9d1e626de..80419c529 100644 --- a/Assembly-CSharp/RimWorld/StorageSettingsClipboard.cs +++ b/Assembly-CSharp/RimWorld/StorageSettingsClipboard.cs @@ -1,7 +1,8 @@ using System; using System.Collections.Generic; -using System.Diagnostics; +using UnityEngine; using Verse; +using Verse.Sound; namespace RimWorld { @@ -30,15 +31,37 @@ public static void PasteInto(StorageSettings s) s.CopyFrom(StorageSettingsClipboard.clipboard); } - [DebuggerHidden] public static IEnumerable CopyPasteGizmosFor(StorageSettings s) { - StorageSettingsClipboard.c__Iterator14F c__Iterator14F = new StorageSettingsClipboard.c__Iterator14F(); - c__Iterator14F.s = s; - c__Iterator14F.<$>s = s; - StorageSettingsClipboard.c__Iterator14F expr_15 = c__Iterator14F; - expr_15.$PC = -2; - return expr_15; + yield return (Gizmo)new Command_Action + { + icon = ContentFinder.Get("UI/Commands/CopySettings", true), + defaultLabel = "CommandCopyZoneSettingsLabel".Translate(), + defaultDesc = "CommandCopyZoneSettingsDesc".Translate(), + action = (Action)delegate + { + SoundDefOf.TickHigh.PlayOneShotOnCamera(null); + StorageSettingsClipboard.Copy(((_003CCopyPasteGizmosFor_003Ec__Iterator14F)/*Error near IL_0076: stateMachine*/).s); + }, + hotKey = KeyBindingDefOf.Misc4 + }; + Command_Action paste = new Command_Action + { + icon = ContentFinder.Get("UI/Commands/PasteSettings", true), + defaultLabel = "CommandPasteZoneSettingsLabel".Translate(), + defaultDesc = "CommandPasteZoneSettingsDesc".Translate(), + action = (Action)delegate + { + SoundDefOf.TickHigh.PlayOneShotOnCamera(null); + StorageSettingsClipboard.PasteInto(((_003CCopyPasteGizmosFor_003Ec__Iterator14F)/*Error near IL_0100: stateMachine*/).s); + }, + hotKey = KeyBindingDefOf.Misc5 + }; + if (!StorageSettingsClipboard.HasCopiedSettings) + { + paste.Disable((string)null); + } + yield return (Gizmo)paste; } } } diff --git a/Assembly-CSharp/RimWorld/StorageSettingsPreset.cs b/Assembly-CSharp/RimWorld/StorageSettingsPreset.cs index 3def3a240..0d58f1d5d 100644 --- a/Assembly-CSharp/RimWorld/StorageSettingsPreset.cs +++ b/Assembly-CSharp/RimWorld/StorageSettingsPreset.cs @@ -1,10 +1,8 @@ -using System; - namespace RimWorld { public enum StorageSettingsPreset : byte { - DefaultStockpile, - DumpingStockpile + DefaultStockpile = 0, + DumpingStockpile = 1 } } diff --git a/Assembly-CSharp/RimWorld/StoreUtility.cs b/Assembly-CSharp/RimWorld/StoreUtility.cs index b4814d51d..9b3c0b023 100644 --- a/Assembly-CSharp/RimWorld/StoreUtility.cs +++ b/Assembly-CSharp/RimWorld/StoreUtility.cs @@ -25,7 +25,11 @@ public static bool IsInValidStorage(this Thing t) return false; } SlotGroup slotGroup = t.GetSlotGroup(); - return slotGroup != null && slotGroup.Settings.AllowedToAccept(t); + if (slotGroup != null && slotGroup.Settings.AllowedToAccept(t)) + { + return true; + } + return false; } public static bool IsInValidBestStorage(this Thing t) @@ -35,8 +39,16 @@ public static bool IsInValidBestStorage(this Thing t) return false; } SlotGroup slotGroup = t.GetSlotGroup(); - IntVec3 intVec; - return slotGroup != null && slotGroup.Settings.AllowedToAccept(t) && !StoreUtility.TryFindBestBetterStoreCellFor(t, null, t.Map, slotGroup.Settings.Priority, Faction.OfPlayer, out intVec, false); + if (slotGroup != null && slotGroup.Settings.AllowedToAccept(t)) + { + IntVec3 intVec = default(IntVec3); + if (StoreUtility.TryFindBestBetterStoreCellFor(t, (Pawn)null, t.Map, slotGroup.Settings.Priority, Faction.OfPlayer, out intVec, false)) + { + return false; + } + return true; + } + return false; } public static Building StoringBuilding(this Thing t) @@ -46,15 +58,15 @@ public static Building StoringBuilding(this Thing t) return null; } SlotGroup slotGroup = t.GetSlotGroup(); - if (slotGroup == null) + if (slotGroup != null) { + Building building = slotGroup.parent as Building; + if (building != null) + { + return building; + } return null; } - Building building = slotGroup.parent as Building; - if (building != null) - { - return building; - } return null; } @@ -96,7 +108,11 @@ public static bool IsValidStorageFor(this IntVec3 c, Map map, Thing storable) return false; } SlotGroup slotGroup = c.GetSlotGroup(map); - return slotGroup != null && slotGroup.Settings.AllowedToAccept(storable); + if (slotGroup != null && slotGroup.Settings.AllowedToAccept(storable)) + { + return true; + } + return false; } private static bool NoStorageBlockersIn(IntVec3 c, Map map, Thing thing) @@ -116,11 +132,11 @@ private static bool NoStorageBlockersIn(IntVec3 c, Map map, Thing thing) return false; } } - if (thing2.def.entityDefToBuild != null && thing2.def.entityDefToBuild.passability != Traversability.Standable) + if (((thing2.def.entityDefToBuild != null) ? thing2.def.entityDefToBuild.passability : Traversability.Standable) != 0) { return false; } - if (thing2.def.surfaceType == SurfaceType.None && thing2.def.passability != Traversability.Standable) + if (((thing2.def.surfaceType == SurfaceType.None) ? thing2.def.passability : Traversability.Standable) != 0) { return false; } @@ -142,47 +158,37 @@ public static bool TryFindBestBetterStoreCellFor(Thing t, Pawn carrier, Map map, IntVec3 intVec = default(IntVec3); bool flag = false; int count = allGroupsListInPriorityOrder.Count; - for (int i = 0; i < count; i++) + int num2 = 0; + while (num2 < count) { - SlotGroup slotGroup = allGroupsListInPriorityOrder[i]; + SlotGroup slotGroup = allGroupsListInPriorityOrder[num2]; StoragePriority priority = slotGroup.Settings.Priority; - if (priority < storagePriority || priority <= currentPriority) - { - break; - } - if (slotGroup.Settings.AllowedToAccept(t)) + if ((int)priority >= (int)storagePriority && (int)priority > (int)currentPriority) { - List cellsList = slotGroup.CellsList; - int count2 = cellsList.Count; - int num2; - if (needAccurateResult) - { - num2 = Mathf.FloorToInt((float)count2 * Rand.Range(0.005f, 0.018f)); - } - else - { - num2 = 0; - } - for (int j = 0; j < count2; j++) + if (slotGroup.Settings.AllowedToAccept(t)) { - IntVec3 intVec2 = cellsList[j]; - float num3 = (float)(a - intVec2).LengthHorizontalSquared; - if (num3 <= num) + List cellsList = slotGroup.CellsList; + int count2 = cellsList.Count; + int num3 = needAccurateResult ? Mathf.FloorToInt((float)count2 * Rand.Range(0.005f, 0.018f)) : 0; + for (int num4 = 0; num4 < count2; num4++) { - if (StoreUtility.IsGoodStoreCell(intVec2, map, t, carrier, faction)) + IntVec3 intVec2 = cellsList[num4]; + float num5 = (float)(a - intVec2).LengthHorizontalSquared; + if (!(num5 > num) && StoreUtility.IsGoodStoreCell(intVec2, map, t, carrier, faction)) { flag = true; intVec = intVec2; - num = num3; + num = num5; storagePriority = priority; - if (j >= num2) - { + if (num4 >= num3) break; - } } } } + num2++; + continue; } + break; } if (!flag) { @@ -214,7 +220,15 @@ public static bool IsGoodStoreCell(IntVec3 c, Map map, Thing t, Pawn carrier, Fa { return false; } - return !c.ContainsStaticFire(map) && (carrier == null || carrier.Map.reachability.CanReach((!t.SpawnedOrAnyParentSpawned) ? carrier.PositionHeld : t.PositionHeld, c, PathEndMode.ClosestTouch, TraverseParms.For(carrier, Danger.Deadly, TraverseMode.ByPawn, false))); + if (c.ContainsStaticFire(map)) + { + return false; + } + if (carrier != null && !carrier.Map.reachability.CanReach((!t.SpawnedOrAnyParentSpawned) ? carrier.PositionHeld : t.PositionHeld, c, PathEndMode.ClosestTouch, TraverseParms.For(carrier, Danger.Deadly, TraverseMode.ByPawn, false))) + { + return false; + } + return true; } public static bool TryFindStoreCellNearColonyDesperate(Thing item, Pawn carrier, out IntVec3 storeCell) @@ -227,13 +241,13 @@ public static bool TryFindStoreCellNearColonyDesperate(Thing item, Pawn carrier, { int num = (i >= 0) ? i : Rand.RangeInclusive(0, 4); IntVec3 intVec = carrier.Position + GenRadial.RadialPattern[num]; - if (intVec.InBounds(carrier.Map) && carrier.Map.areaManager.Home[intVec] && carrier.CanReach(intVec, PathEndMode.ClosestTouch, Danger.Deadly, false, TraverseMode.ByPawn) && intVec.GetSlotGroup(carrier.Map) == null && StoreUtility.IsGoodStoreCell(intVec, carrier.Map, item, carrier, carrier.Faction)) + if (intVec.InBounds(carrier.Map) && ((Area)carrier.Map.areaManager.Home)[intVec] && carrier.CanReach(intVec, PathEndMode.ClosestTouch, Danger.Deadly, false, TraverseMode.ByPawn) && intVec.GetSlotGroup(carrier.Map) == null && StoreUtility.IsGoodStoreCell(intVec, carrier.Map, item, carrier, carrier.Faction)) { storeCell = intVec; return true; } } - if (RCellFinder.TryFindRandomSpotJustOutsideColony(carrier.Position, carrier.Map, carrier, out storeCell, (IntVec3 x) => x.GetSlotGroup(carrier.Map) == null && StoreUtility.IsGoodStoreCell(x, carrier.Map, item, carrier, carrier.Faction))) + if (RCellFinder.TryFindRandomSpotJustOutsideColony(carrier.Position, carrier.Map, carrier, out storeCell, (Predicate)((IntVec3 x) => x.GetSlotGroup(carrier.Map) == null && StoreUtility.IsGoodStoreCell(x, carrier.Map, item, carrier, carrier.Faction)))) { return true; } diff --git a/Assembly-CSharp/RimWorld/StoryDanger.cs b/Assembly-CSharp/RimWorld/StoryDanger.cs index 79e3ae285..a2be034c5 100644 --- a/Assembly-CSharp/RimWorld/StoryDanger.cs +++ b/Assembly-CSharp/RimWorld/StoryDanger.cs @@ -1,11 +1,9 @@ -using System; - namespace RimWorld { public enum StoryDanger : byte { - None, - Low, - High + None = 0, + Low = 1, + High = 2 } } diff --git a/Assembly-CSharp/RimWorld/StoryDangerUtility.cs b/Assembly-CSharp/RimWorld/StoryDangerUtility.cs index 1b64c1613..ebcec9b15 100644 --- a/Assembly-CSharp/RimWorld/StoryDangerUtility.cs +++ b/Assembly-CSharp/RimWorld/StoryDangerUtility.cs @@ -1,5 +1,3 @@ -using System; - namespace RimWorld { public static class StoryDangerUtility @@ -9,14 +7,22 @@ public static float Scale(this StoryDanger d) switch (d) { case StoryDanger.None: + { return 0f; + } case StoryDanger.Low: + { return 1f; + } case StoryDanger.High: + { return 2f; + } default: + { return 0f; } + } } } } diff --git a/Assembly-CSharp/RimWorld/StoryIntender_Population.cs b/Assembly-CSharp/RimWorld/StoryIntender_Population.cs index 6abe88a2e..dffecc989 100644 --- a/Assembly-CSharp/RimWorld/StoryIntender_Population.cs +++ b/Assembly-CSharp/RimWorld/StoryIntender_Population.cs @@ -41,8 +41,8 @@ public float AdjustedPopulation get { float num = 0f; - num += (float)PawnsFinder.AllMapsCaravansAndTravelingTransportPods_Colonists.Count(); - return num + (float)PawnsFinder.AllMapsCaravansAndTravelingTransportPods.Count((Pawn x) => x.IsPrisonerOfColony) * 0.5f; + num += (float)PawnsFinder.AllMapsCaravansAndTravelingTransportPods_Colonists.Count(); + return (float)(num + (float)PawnsFinder.AllMapsCaravansAndTravelingTransportPods.Count((Func)((Pawn x) => x.IsPrisonerOfColony)) * 0.5); } } @@ -85,9 +85,9 @@ public void Notify_PopulationGained() private static float CalculatePopulationIntent(StorytellerDef def, float curPop, int ticksSinceGain) { float num = def.populationIntentFromPopCurve.Evaluate(curPop); - if (num > 0f) + if (num > 0.0) { - float x = (float)ticksSinceGain / 60000f; + float x = (float)((float)ticksSinceGain / 60000.0); num *= def.populationIntentFromTimeCurve.Evaluate(x); } return num; @@ -101,11 +101,11 @@ public void DoTable_PopulationIntents() list.Add((float)i); } List list2 = new List(); - for (int j = 0; j < 40; j += 2) + for (int num = 0; num < 40; num += 2) { - list2.Add((float)j); + list2.Add((float)num); } - DebugTables.MakeTablesDialog(list2, (float ds) => "d-" + ds.ToString("F0"), list, (float rv) => rv.ToString("F2"), (float ds, float p) => StoryIntender_Population.CalculatePopulationIntent(this.Def, p, (int)(ds * 60000f)).ToString("F2"), "pop"); + DebugTables.MakeTablesDialog(list2, (Func)((float ds) => "d-" + ds.ToString("F0")), list, (Func)((float rv) => rv.ToString("F2")), (Func)((float ds, float p) => StoryIntender_Population.CalculatePopulationIntent(this.Def, p, (int)(ds * 60000.0)).ToString("F2")), "pop"); } } } diff --git a/Assembly-CSharp/RimWorld/StoryState.cs b/Assembly-CSharp/RimWorld/StoryState.cs index e5f1ce546..73b5b5b1b 100644 --- a/Assembly-CSharp/RimWorld/StoryState.cs +++ b/Assembly-CSharp/RimWorld/StoryState.cs @@ -18,14 +18,7 @@ public int LastThreatBigTick { if (this.lastThreatBigTick > Find.TickManager.TicksGame + 1000) { - Log.Error(string.Concat(new object[] - { - "Latest big threat queue time was ", - this.lastThreatBigTick, - " at tick ", - Find.TickManager.TicksGame, - ". This is too far in the future. Resetting." - })); + Log.Error("Latest big threat queue time was " + this.lastThreatBigTick + " at tick " + Find.TickManager.TicksGame + ". This is too far in the future. Resetting."); this.lastThreatBigTick = Find.TickManager.TicksGame - 1; } return this.lastThreatBigTick; @@ -45,30 +38,29 @@ public void ExposeData() public void Notify_IncidentFired(FiringIncident qi) { - if (qi.parms.forced || qi.parms.target != this.target) - { - return; - } - int ticksGame = Find.TickManager.TicksGame; - if (qi.def.category == IncidentCategory.ThreatBig) + if (!qi.parms.forced && qi.parms.target == this.target) { - if (this.lastThreatBigTick <= ticksGame) + int ticksGame = Find.TickManager.TicksGame; + if (qi.def.category == IncidentCategory.ThreatBig) + { + if (this.lastThreatBigTick <= ticksGame) + { + this.lastThreatBigTick = ticksGame; + } + else + { + Log.Error("Queueing threats backwards in time (" + qi + ")"); + } + Find.StoryWatcher.statsRecord.numThreatBigs++; + } + if (this.lastFireTicks.ContainsKey(qi.def)) { - this.lastThreatBigTick = ticksGame; + this.lastFireTicks[qi.def] = ticksGame; } else { - Log.Error("Queueing threats backwards in time (" + qi + ")"); + this.lastFireTicks.Add(qi.def, ticksGame); } - Find.StoryWatcher.statsRecord.numThreatBigs++; - } - if (this.lastFireTicks.ContainsKey(qi.def)) - { - this.lastFireTicks[qi.def] = ticksGame; - } - else - { - this.lastFireTicks.Add(qi.def, ticksGame); } } @@ -76,9 +68,18 @@ public void CopyTo(StoryState other) { other.lastThreatBigTick = this.lastThreatBigTick; other.lastFireTicks.Clear(); - foreach (KeyValuePair current in this.lastFireTicks) + Dictionary.Enumerator enumerator = this.lastFireTicks.GetEnumerator(); + try + { + while (enumerator.MoveNext()) + { + KeyValuePair current = enumerator.Current; + other.lastFireTicks.Add(current.Key, current.Value); + } + } + finally { - other.lastFireTicks.Add(current.Key, current.Value); + ((IDisposable)(object)enumerator).Dispose(); } } } diff --git a/Assembly-CSharp/RimWorld/StoryWatcher.cs b/Assembly-CSharp/RimWorld/StoryWatcher.cs index b3c797454..f6a799561 100644 --- a/Assembly-CSharp/RimWorld/StoryWatcher.cs +++ b/Assembly-CSharp/RimWorld/StoryWatcher.cs @@ -1,4 +1,3 @@ -using System; using System.Text; using Verse; diff --git a/Assembly-CSharp/RimWorld/StoryWatcher_RampUp.cs b/Assembly-CSharp/RimWorld/StoryWatcher_RampUp.cs index 6dbbd0e73..e906cf58a 100644 --- a/Assembly-CSharp/RimWorld/StoryWatcher_RampUp.cs +++ b/Assembly-CSharp/RimWorld/StoryWatcher_RampUp.cs @@ -1,4 +1,3 @@ -using System; using System.Linq; using Verse; @@ -46,96 +45,129 @@ public float LongTermFactor public void Notify_PlayerPawnIncappedOrKilled(Pawn p) { - if (!p.RaceProps.Humanlike) + if (p.RaceProps.Humanlike) { - return; - } - float num = this.shortTermFactor - 1f; - float num2 = this.longTermFactor - 1f; - switch (PawnsFinder.AllMapsCaravansAndTravelingTransportPods_FreeColonists.Count()) - { - case 0: - num *= 0f; - num2 *= 0f; - break; - case 1: - num *= 0f; - num2 *= 0f; - break; - case 2: - num *= 0f; - num2 *= 0f; - break; - case 3: - num *= 0f; - num2 *= 0.2f; - break; - case 4: - num *= 0.15f; - num2 *= 0.4f; - break; - case 5: - num *= 0.25f; - num2 *= 0.6f; - break; - case 6: - num *= 0.3f; - num2 *= 0.7f; - break; - case 7: - num *= 0.35f; - num2 *= 0.75f; - break; - case 8: - num *= 0.4f; - num2 *= 0.8f; - break; - case 9: - num *= 0.45f; - num2 *= 0.85f; - break; - case 10: - num *= 0.5f; - num2 *= 0.9f; - break; - case 11: - num *= 0.55f; - num2 *= 0.91f; - break; - case 12: - num *= 0.6f; - num2 *= 0.92f; - break; - case 13: - num *= 0.65f; - num2 *= 0.93f; - break; - case 14: - num *= 0.7f; - num2 *= 0.94f; - break; - case 15: - num *= 0.75f; - num2 *= 0.95f; - break; - default: - num *= 0.8f; - num2 *= 0.95f; - break; + float num = (float)(this.shortTermFactor - 1.0); + float num2 = (float)(this.longTermFactor - 1.0); + switch (PawnsFinder.AllMapsCaravansAndTravelingTransportPods_FreeColonists.Count()) + { + case 0: + { + num = (float)(num * 0.0); + num2 = (float)(num2 * 0.0); + break; + } + case 1: + { + num = (float)(num * 0.0); + num2 = (float)(num2 * 0.0); + break; + } + case 2: + { + num = (float)(num * 0.0); + num2 = (float)(num2 * 0.0); + break; + } + case 3: + { + num = (float)(num * 0.0); + num2 = (float)(num2 * 0.20000000298023224); + break; + } + case 4: + { + num = (float)(num * 0.15000000596046448); + num2 = (float)(num2 * 0.40000000596046448); + break; + } + case 5: + { + num = (float)(num * 0.25); + num2 = (float)(num2 * 0.60000002384185791); + break; + } + case 6: + { + num = (float)(num * 0.30000001192092896); + num2 = (float)(num2 * 0.699999988079071); + break; + } + case 7: + { + num = (float)(num * 0.34999999403953552); + num2 = (float)(num2 * 0.75); + break; + } + case 8: + { + num = (float)(num * 0.40000000596046448); + num2 = (float)(num2 * 0.800000011920929); + break; + } + case 9: + { + num = (float)(num * 0.44999998807907104); + num2 = (float)(num2 * 0.85000002384185791); + break; + } + case 10: + { + num = (float)(num * 0.5); + num2 = (float)(num2 * 0.89999997615814209); + break; + } + case 11: + { + num = (float)(num * 0.550000011920929); + num2 = (float)(num2 * 0.9100000262260437); + break; + } + case 12: + { + num = (float)(num * 0.60000002384185791); + num2 = (float)(num2 * 0.92000001668930054); + break; + } + case 13: + { + num = (float)(num * 0.64999997615814209); + num2 = (float)(num2 * 0.93000000715255737); + break; + } + case 14: + { + num = (float)(num * 0.699999988079071); + num2 = (float)(num2 * 0.93999999761581421); + break; + } + case 15: + { + num = (float)(num * 0.75); + num2 = (float)(num2 * 0.949999988079071); + break; + } + default: + { + num = (float)(num * 0.800000011920929); + num2 = (float)(num2 * 0.949999988079071); + break; + } + } + this.shortTermFactor = (float)(1.0 + num); + this.longTermFactor = (float)(1.0 + num2); } - this.shortTermFactor = 1f + num; - this.longTermFactor = 1f + num2; } public void RampUpWatcherTick() { if (Find.TickManager.TicksGame % 5000 == 0) { - if ((float)GenDate.DaysPassed >= 21f) + if ((float)GenDate.DaysPassed >= 21.0) { this.shortTermFactor += 0.000514403335f; } - if ((float)GenDate.DaysPassed >= 42f) + if ((float)GenDate.DaysPassed >= 42.0) { this.longTermFactor += 0.000231481492f; } diff --git a/Assembly-CSharp/RimWorld/Storyteller.cs b/Assembly-CSharp/RimWorld/Storyteller.cs index 098088fbe..938516381 100644 --- a/Assembly-CSharp/RimWorld/Storyteller.cs +++ b/Assembly-CSharp/RimWorld/Storyteller.cs @@ -1,7 +1,6 @@ using RimWorld.Planet; using System; using System.Collections.Generic; -using System.Diagnostics; using System.Text; using UnityEngine; using Verse; @@ -81,7 +80,7 @@ public void ExposeData() Scribe_Defs.Look(ref this.def, "def"); Scribe_Defs.Look(ref this.difficulty, "difficulty"); Scribe_Deep.Look(ref this.incidentQueue, "incidentQueue", new object[0]); - Scribe_Deep.Look(ref this.intenderPopulation, "intenderPopulation", new object[] + Scribe_Deep.Look(ref this.intenderPopulation, "intenderPopulation", new object[1] { this }); @@ -99,35 +98,49 @@ public void ExposeData() public void StorytellerTick() { this.incidentQueue.IncidentQueueTick(); - if (Find.TickManager.TicksGame % 1000 == 0) + if (Find.TickManager.TicksGame % 1000 == 0 && DebugSettings.enableStoryteller) { - if (!DebugSettings.enableStoryteller) + foreach (FiringIncident item in this.MakeIncidentsForInterval()) { - return; - } - foreach (FiringIncident current in this.MakeIncidentsForInterval()) - { - this.TryFire(current); + this.TryFire(item); } } } public void TryFire(FiringIncident fi) { - if ((fi.parms.forced || fi.def.Worker.CanFireNow(fi.parms.target)) && fi.def.Worker.TryExecute(fi.parms)) + if (!fi.parms.forced && !fi.def.Worker.CanFireNow(fi.parms.target)) + return; + if (fi.def.Worker.TryExecute(fi.parms)) { fi.parms.target.StoryState.Notify_IncidentFired(fi); } } - [DebuggerHidden] public IEnumerable MakeIncidentsForInterval() { - Storyteller.c__IteratorA4 c__IteratorA = new Storyteller.c__IteratorA4(); - c__IteratorA.<>f__this = this; - Storyteller.c__IteratorA4 expr_0E = c__IteratorA; - expr_0E.$PC = -2; - return expr_0E; + List targets = this.AllIncidentTargets; + for (int j = 0; j < this.storytellerComps.Count; j++) + { + StorytellerComp c = this.storytellerComps[j]; + if (!(GenDate.DaysPassedFloat <= c.props.minDaysPassed)) + { + for (int i = 0; i < targets.Count; i++) + { + IIncidentTarget targ = targets[i]; + if ((c.props.allowedTargetTypes & targ.Type) != 0) + { + foreach (FiringIncident item in c.MakeIntervalIncidents(targ)) + { + if (Find.Storyteller.difficulty.allowBigThreats || item.def.category != IncidentCategory.ThreatBig) + { + yield return item; + } + } + } + } + } + } } public void Notify_DefChanged() @@ -150,13 +163,7 @@ public string DebugString() for (int i = 0; i < this.storytellerComps.Count; i++) { IncidentParms incidentParms = this.storytellerComps[i].GenerateParms(IncidentCategory.ThreatBig, Find.VisibleMap); - stringBuilder.AppendLine(string.Concat(new object[] - { - " ", - this.storytellerComps[i].GetType(), - ": ", - incidentParms.points - })); + stringBuilder.AppendLine(" " + this.storytellerComps[i].GetType() + ": " + incidentParms.points); } if (Find.VisibleMap != null) { diff --git a/Assembly-CSharp/RimWorld/StorytellerComp.cs b/Assembly-CSharp/RimWorld/StorytellerComp.cs index 4d9bd8ae0..6dd57b1f2 100644 --- a/Assembly-CSharp/RimWorld/StorytellerComp.cs +++ b/Assembly-CSharp/RimWorld/StorytellerComp.cs @@ -30,50 +30,43 @@ protected float IncidentChanceFactor_CurrentPopulation(IncidentDef def) { return 1f; } - int num = PawnsFinder.AllMapsCaravansAndTravelingTransportPods_Colonists.Count(); + int num = PawnsFinder.AllMapsCaravansAndTravelingTransportPods_Colonists.Count(); return def.chanceFactorByPopulationCurve.Evaluate((float)num); } protected float IncidentChanceFactor_PopulationIntent(IncidentDef def) { - IncidentPopulationEffect populationEffect = def.populationEffect; - if (populationEffect == IncidentPopulationEffect.None) + switch (def.populationEffect) + { + case IncidentPopulationEffect.None: { return 1f; } - if (populationEffect != IncidentPopulationEffect.Increase) + case IncidentPopulationEffect.Increase: + { + return Mathf.Max(Find.Storyteller.intenderPopulation.PopulationIntent, this.props.minIncChancePopulationIntentFactor); + } + default: { throw new NotImplementedException(); } - return Mathf.Max(Find.Storyteller.intenderPopulation.PopulationIntent, this.props.minIncChancePopulationIntentFactor); + } } protected float IncidentChanceFinal(IncidentDef def) { - float num = def.Worker.AdjustedChance; - num *= this.IncidentChanceFactor_CurrentPopulation(def); - num *= this.IncidentChanceFactor_PopulationIntent(def); - return Mathf.Max(0f, num); + float adjustedChance = def.Worker.AdjustedChance; + adjustedChance *= this.IncidentChanceFactor_CurrentPopulation(def); + adjustedChance *= this.IncidentChanceFactor_PopulationIntent(def); + return Mathf.Max(0f, adjustedChance); } public virtual void DebugTablesIncidentChances(IncidentCategory cat) { - IEnumerable arg_192_0 = from d in DefDatabase.AllDefs + DebugTables.MakeTablesDialog(from d in DefDatabase.AllDefs where d.category == cat orderby this.IncidentChanceFinal(d) descending - select d; - TableDataGetter[] expr_42 = new TableDataGetter[10]; - expr_42[0] = new TableDataGetter("defName", (IncidentDef d) => d.defName); - expr_42[1] = new TableDataGetter("baseChance", (IncidentDef d) => d.baseChance.ToString()); - expr_42[2] = new TableDataGetter("AdjustedChance", (IncidentDef d) => d.Worker.AdjustedChance.ToString()); - expr_42[3] = new TableDataGetter("Factor-PopCurrent", (IncidentDef d) => this.IncidentChanceFactor_CurrentPopulation(d).ToString()); - expr_42[4] = new TableDataGetter("Factor-PopIntent", (IncidentDef d) => this.IncidentChanceFactor_PopulationIntent(d).ToString()); - expr_42[5] = new TableDataGetter("final chance", (IncidentDef d) => this.IncidentChanceFinal(d).ToString()); - expr_42[6] = new TableDataGetter("vismap-usable", (IncidentDef d) => (Find.VisibleMap != null) ? ((!this.UsableIncidentsInCategory(cat, Find.VisibleMap).Contains(d)) ? string.Empty : "V") : "-"); - expr_42[7] = new TableDataGetter("world-usable", (IncidentDef d) => (!this.UsableIncidentsInCategory(cat, Find.World).Contains(d)) ? string.Empty : "W"); - expr_42[8] = new TableDataGetter("pop-current", (IncidentDef d) => PawnsFinder.AllMapsCaravansAndTravelingTransportPods_Colonists.Count().ToString()); - expr_42[9] = new TableDataGetter("pop-intent", (IncidentDef d) => Find.Storyteller.intenderPopulation.PopulationIntent.ToString("F3")); - DebugTables.MakeTablesDialog(arg_192_0, expr_42); + select d, new TableDataGetter("defName", (Func)((IncidentDef d) => d.defName)), new TableDataGetter("baseChance", (Func)((IncidentDef d) => d.baseChance.ToString())), new TableDataGetter("AdjustedChance", (Func)((IncidentDef d) => d.Worker.AdjustedChance.ToString())), new TableDataGetter("Factor-PopCurrent", (Func)((IncidentDef d) => this.IncidentChanceFactor_CurrentPopulation(d).ToString())), new TableDataGetter("Factor-PopIntent", (Func)((IncidentDef d) => this.IncidentChanceFactor_PopulationIntent(d).ToString())), new TableDataGetter("final chance", (Func)((IncidentDef d) => this.IncidentChanceFinal(d).ToString())), new TableDataGetter("vismap-usable", (Func)((IncidentDef d) => (Find.VisibleMap != null) ? ((!this.UsableIncidentsInCategory(cat, Find.VisibleMap).Contains(d)) ? string.Empty : "V") : "-")), new TableDataGetter("world-usable", (Func)((IncidentDef d) => (!this.UsableIncidentsInCategory(cat, Find.World).Contains(d)) ? string.Empty : "W")), new TableDataGetter("pop-current", (Func)((IncidentDef d) => PawnsFinder.AllMapsCaravansAndTravelingTransportPods_Colonists.Count().ToString())), new TableDataGetter("pop-intent", (Func)((IncidentDef d) => Find.Storyteller.intenderPopulation.PopulationIntent.ToString("F3")))); } } } diff --git a/Assembly-CSharp/RimWorld/StorytellerCompProperties.cs b/Assembly-CSharp/RimWorld/StorytellerCompProperties.cs index c718583b4..71469f493 100644 --- a/Assembly-CSharp/RimWorld/StorytellerCompProperties.cs +++ b/Assembly-CSharp/RimWorld/StorytellerCompProperties.cs @@ -1,6 +1,5 @@ using System; using System.Collections.Generic; -using System.Diagnostics; namespace RimWorld { @@ -23,16 +22,12 @@ public StorytellerCompProperties(Type compClass) this.compClass = compClass; } - [DebuggerHidden] public virtual IEnumerable ConfigErrors(StorytellerDef parentDef) { - StorytellerCompProperties.c__Iterator98 c__Iterator = new StorytellerCompProperties.c__Iterator98(); - c__Iterator.parentDef = parentDef; - c__Iterator.<$>parentDef = parentDef; - c__Iterator.<>f__this = this; - StorytellerCompProperties.c__Iterator98 expr_1C = c__Iterator; - expr_1C.$PC = -2; - return expr_1C; + if (this.compClass == null) + { + yield return parentDef.defName + " has StorytellerCompProperties with null compClass."; + } } public virtual void ResolveReferences(StorytellerDef parentDef) diff --git a/Assembly-CSharp/RimWorld/StorytellerCompProperties_AllyAssistance.cs b/Assembly-CSharp/RimWorld/StorytellerCompProperties_AllyAssistance.cs index ead5dd43a..29af21a29 100644 --- a/Assembly-CSharp/RimWorld/StorytellerCompProperties_AllyAssistance.cs +++ b/Assembly-CSharp/RimWorld/StorytellerCompProperties_AllyAssistance.cs @@ -1,5 +1,3 @@ -using System; - namespace RimWorld { public class StorytellerCompProperties_AllyAssistance : StorytellerCompProperties @@ -8,7 +6,7 @@ public class StorytellerCompProperties_AllyAssistance : StorytellerCompPropertie public StorytellerCompProperties_AllyAssistance() { - this.compClass = typeof(StorytellerComp_AllyAssistance); + base.compClass = typeof(StorytellerComp_AllyAssistance); } } } diff --git a/Assembly-CSharp/RimWorld/StorytellerCompProperties_AllyInteraction.cs b/Assembly-CSharp/RimWorld/StorytellerCompProperties_AllyInteraction.cs index 2ae139b61..d65bdb18b 100644 --- a/Assembly-CSharp/RimWorld/StorytellerCompProperties_AllyInteraction.cs +++ b/Assembly-CSharp/RimWorld/StorytellerCompProperties_AllyInteraction.cs @@ -1,5 +1,3 @@ -using System; - namespace RimWorld { public class StorytellerCompProperties_AllyInteraction : StorytellerCompProperties @@ -8,7 +6,7 @@ public class StorytellerCompProperties_AllyInteraction : StorytellerCompProperti public StorytellerCompProperties_AllyInteraction() { - this.compClass = typeof(StorytellerComp_AllyInteraction); + base.compClass = typeof(StorytellerComp_AllyInteraction); } } } diff --git a/Assembly-CSharp/RimWorld/StorytellerCompProperties_CategoryIndividualMTBByBiome.cs b/Assembly-CSharp/RimWorld/StorytellerCompProperties_CategoryIndividualMTBByBiome.cs index bf311a668..d6df3daa7 100644 --- a/Assembly-CSharp/RimWorld/StorytellerCompProperties_CategoryIndividualMTBByBiome.cs +++ b/Assembly-CSharp/RimWorld/StorytellerCompProperties_CategoryIndividualMTBByBiome.cs @@ -1,5 +1,3 @@ -using System; - namespace RimWorld { public class StorytellerCompProperties_CategoryIndividualMTBByBiome : StorytellerCompProperties @@ -8,7 +6,7 @@ public class StorytellerCompProperties_CategoryIndividualMTBByBiome : Storytelle public StorytellerCompProperties_CategoryIndividualMTBByBiome() { - this.compClass = typeof(StorytellerComp_CategoryIndividualMTBByBiome); + base.compClass = typeof(StorytellerComp_CategoryIndividualMTBByBiome); } } } diff --git a/Assembly-CSharp/RimWorld/StorytellerCompProperties_CategoryMTB.cs b/Assembly-CSharp/RimWorld/StorytellerCompProperties_CategoryMTB.cs index 2b69bfa3f..da9021917 100644 --- a/Assembly-CSharp/RimWorld/StorytellerCompProperties_CategoryMTB.cs +++ b/Assembly-CSharp/RimWorld/StorytellerCompProperties_CategoryMTB.cs @@ -1,5 +1,3 @@ -using System; - namespace RimWorld { public class StorytellerCompProperties_CategoryMTB : StorytellerCompProperties @@ -10,7 +8,7 @@ public class StorytellerCompProperties_CategoryMTB : StorytellerCompProperties public StorytellerCompProperties_CategoryMTB() { - this.compClass = typeof(StorytellerComp_CategoryMTB); + base.compClass = typeof(StorytellerComp_CategoryMTB); } } } diff --git a/Assembly-CSharp/RimWorld/StorytellerCompProperties_ClassicIntro.cs b/Assembly-CSharp/RimWorld/StorytellerCompProperties_ClassicIntro.cs index 03c3c51b9..0494c87c5 100644 --- a/Assembly-CSharp/RimWorld/StorytellerCompProperties_ClassicIntro.cs +++ b/Assembly-CSharp/RimWorld/StorytellerCompProperties_ClassicIntro.cs @@ -1,12 +1,10 @@ -using System; - namespace RimWorld { public class StorytellerCompProperties_ClassicIntro : StorytellerCompProperties { public StorytellerCompProperties_ClassicIntro() { - this.compClass = typeof(StorytellerComp_ClassicIntro); + base.compClass = typeof(StorytellerComp_ClassicIntro); } } } diff --git a/Assembly-CSharp/RimWorld/StorytellerCompProperties_Disease.cs b/Assembly-CSharp/RimWorld/StorytellerCompProperties_Disease.cs index b6741a72a..1d9979451 100644 --- a/Assembly-CSharp/RimWorld/StorytellerCompProperties_Disease.cs +++ b/Assembly-CSharp/RimWorld/StorytellerCompProperties_Disease.cs @@ -1,12 +1,10 @@ -using System; - namespace RimWorld { public class StorytellerCompProperties_Disease : StorytellerCompProperties { public StorytellerCompProperties_Disease() { - this.compClass = typeof(StorytellerComp_Disease); + base.compClass = typeof(StorytellerComp_Disease); } } } diff --git a/Assembly-CSharp/RimWorld/StorytellerCompProperties_JourneyOffer.cs b/Assembly-CSharp/RimWorld/StorytellerCompProperties_JourneyOffer.cs index 7b6f04b9e..dfaeccd3a 100644 --- a/Assembly-CSharp/RimWorld/StorytellerCompProperties_JourneyOffer.cs +++ b/Assembly-CSharp/RimWorld/StorytellerCompProperties_JourneyOffer.cs @@ -1,12 +1,10 @@ -using System; - namespace RimWorld { public class StorytellerCompProperties_JourneyOffer : StorytellerCompProperties { public StorytellerCompProperties_JourneyOffer() { - this.compClass = typeof(StorytellerComp_JourneyOffer); + base.compClass = typeof(StorytellerComp_JourneyOffer); } } } diff --git a/Assembly-CSharp/RimWorld/StorytellerCompProperties_RandomMain.cs b/Assembly-CSharp/RimWorld/StorytellerCompProperties_RandomMain.cs index 3bc060ded..9af89e03d 100644 --- a/Assembly-CSharp/RimWorld/StorytellerCompProperties_RandomMain.cs +++ b/Assembly-CSharp/RimWorld/StorytellerCompProperties_RandomMain.cs @@ -1,4 +1,3 @@ -using System; using System.Collections.Generic; namespace RimWorld @@ -13,7 +12,7 @@ public class StorytellerCompProperties_RandomMain : StorytellerCompProperties public StorytellerCompProperties_RandomMain() { - this.compClass = typeof(StorytellerComp_RandomMain); + base.compClass = typeof(StorytellerComp_RandomMain); } } } diff --git a/Assembly-CSharp/RimWorld/StorytellerCompProperties_ShipChunkDrop.cs b/Assembly-CSharp/RimWorld/StorytellerCompProperties_ShipChunkDrop.cs index 851d462cb..4ef65bf61 100644 --- a/Assembly-CSharp/RimWorld/StorytellerCompProperties_ShipChunkDrop.cs +++ b/Assembly-CSharp/RimWorld/StorytellerCompProperties_ShipChunkDrop.cs @@ -1,12 +1,10 @@ -using System; - namespace RimWorld { public class StorytellerCompProperties_ShipChunkDrop : StorytellerCompProperties { public StorytellerCompProperties_ShipChunkDrop() { - this.compClass = typeof(StorytellerComp_ShipChunkDrop); + base.compClass = typeof(StorytellerComp_ShipChunkDrop); } } } diff --git a/Assembly-CSharp/RimWorld/StorytellerCompProperties_SingleMTB.cs b/Assembly-CSharp/RimWorld/StorytellerCompProperties_SingleMTB.cs index 49109b820..828fab10d 100644 --- a/Assembly-CSharp/RimWorld/StorytellerCompProperties_SingleMTB.cs +++ b/Assembly-CSharp/RimWorld/StorytellerCompProperties_SingleMTB.cs @@ -1,5 +1,3 @@ -using System; - namespace RimWorld { public class StorytellerCompProperties_SingleMTB : StorytellerCompProperties @@ -10,7 +8,7 @@ public class StorytellerCompProperties_SingleMTB : StorytellerCompProperties public StorytellerCompProperties_SingleMTB() { - this.compClass = typeof(StorytellerComp_SingleMTB); + base.compClass = typeof(StorytellerComp_SingleMTB); } } } diff --git a/Assembly-CSharp/RimWorld/StorytellerCompProperties_ThreatCycle.cs b/Assembly-CSharp/RimWorld/StorytellerCompProperties_ThreatCycle.cs index afb5dadb1..662b2d3a9 100644 --- a/Assembly-CSharp/RimWorld/StorytellerCompProperties_ThreatCycle.cs +++ b/Assembly-CSharp/RimWorld/StorytellerCompProperties_ThreatCycle.cs @@ -1,5 +1,3 @@ -using System; - namespace RimWorld { public class StorytellerCompProperties_ThreatCycle : StorytellerCompProperties @@ -24,7 +22,7 @@ public float ThreatCycleTotalDays public StorytellerCompProperties_ThreatCycle() { - this.compClass = typeof(StorytellerComp_ThreatCycle); + base.compClass = typeof(StorytellerComp_ThreatCycle); } } } diff --git a/Assembly-CSharp/RimWorld/StorytellerComp_AllyAssistance.cs b/Assembly-CSharp/RimWorld/StorytellerComp_AllyAssistance.cs index 4dd12fb2a..39e24c9d9 100644 --- a/Assembly-CSharp/RimWorld/StorytellerComp_AllyAssistance.cs +++ b/Assembly-CSharp/RimWorld/StorytellerComp_AllyAssistance.cs @@ -1,6 +1,6 @@ using System; using System.Collections.Generic; -using System.Diagnostics; +using Verse; namespace RimWorld { @@ -10,7 +10,7 @@ private StorytellerCompProperties_AllyAssistance Props { get { - return (StorytellerCompProperties_AllyAssistance)this.props; + return (StorytellerCompProperties_AllyAssistance)base.props; } } @@ -22,16 +22,21 @@ private float IncidentMTBDays } } - [DebuggerHidden] public override IEnumerable MakeIntervalIncidents(IIncidentTarget target) { - StorytellerComp_AllyAssistance.c__IteratorA5 c__IteratorA = new StorytellerComp_AllyAssistance.c__IteratorA5(); - c__IteratorA.target = target; - c__IteratorA.<$>target = target; - c__IteratorA.<>f__this = this; - StorytellerComp_AllyAssistance.c__IteratorA5 expr_1C = c__IteratorA; - expr_1C.$PC = -2; - return expr_1C; + float mtb = this.IncidentMTBDays; + if (!(mtb < 0.0) && Rand.MTBEventOccurs(mtb, 60000f, 1000f)) + { + Map map = target as Map; + if (map != null && (int)map.dangerWatcher.DangerRating >= 2) + { + IncidentDef incident = null; + if (this.UsableIncidentsInCategory(IncidentCategory.AllyAssistance, target).TryRandomElementByWeight((Func)((IncidentDef d) => d.baseChance), out incident)) + { + yield return new FiringIncident(incident, this, this.GenerateParms(incident.category, target)); + } + } + } } } } diff --git a/Assembly-CSharp/RimWorld/StorytellerComp_AllyInteraction.cs b/Assembly-CSharp/RimWorld/StorytellerComp_AllyInteraction.cs index 5ac8a55a9..16ad97994 100644 --- a/Assembly-CSharp/RimWorld/StorytellerComp_AllyInteraction.cs +++ b/Assembly-CSharp/RimWorld/StorytellerComp_AllyInteraction.cs @@ -1,6 +1,5 @@ using System; using System.Collections.Generic; -using System.Diagnostics; using Verse; namespace RimWorld @@ -13,7 +12,7 @@ private StorytellerCompProperties_AllyInteraction Props { get { - return (StorytellerCompProperties_AllyInteraction)this.props; + return (StorytellerCompProperties_AllyInteraction)base.props; } } @@ -25,16 +24,14 @@ private float IncidentMTBDays } } - [DebuggerHidden] public override IEnumerable MakeIntervalIncidents(IIncidentTarget target) { - StorytellerComp_AllyInteraction.c__IteratorA6 c__IteratorA = new StorytellerComp_AllyInteraction.c__IteratorA6(); - c__IteratorA.target = target; - c__IteratorA.<$>target = target; - c__IteratorA.<>f__this = this; - StorytellerComp_AllyInteraction.c__IteratorA6 expr_1C = c__IteratorA; - expr_1C.$PC = -2; - return expr_1C; + float mtb = this.IncidentMTBDays; + IncidentDef incDef; + if (!(mtb < 0.0) && Rand.MTBEventOccurs(mtb, 60000f, 1000f) && this.TryChooseIncident(target, out incDef)) + { + yield return new FiringIncident(incDef, this, this.GenerateParms(incDef.category, target)); + } } private bool TryChooseIncident(IIncidentTarget target, out IncidentDef result) @@ -44,7 +41,7 @@ private bool TryChooseIncident(IIncidentTarget target, out IncidentDef result) int num = 0; if (!target.StoryState.lastFireTicks.TryGetValue(IncidentDefOf.TraderCaravanArrival, out num)) { - num = (int)(this.props.minDaysPassed * 60000f); + num = (int)(base.props.minDaysPassed * 60000.0); } if (Find.TickManager.TicksGame > num + 780000) { @@ -52,7 +49,7 @@ private bool TryChooseIncident(IIncidentTarget target, out IncidentDef result) return true; } } - return this.UsableIncidentsInCategory(IncidentCategory.AllyArrival, target).TryRandomElementByWeight((IncidentDef d) => d.baseChance, out result); + return this.UsableIncidentsInCategory(IncidentCategory.AllyArrival, target).TryRandomElementByWeight((Func)((IncidentDef d) => d.baseChance), out result); } } } diff --git a/Assembly-CSharp/RimWorld/StorytellerComp_CategoryIndividualMTBByBiome.cs b/Assembly-CSharp/RimWorld/StorytellerComp_CategoryIndividualMTBByBiome.cs index 58a9499b9..4d1fbcda2 100644 --- a/Assembly-CSharp/RimWorld/StorytellerComp_CategoryIndividualMTBByBiome.cs +++ b/Assembly-CSharp/RimWorld/StorytellerComp_CategoryIndividualMTBByBiome.cs @@ -1,6 +1,7 @@ +using RimWorld.Planet; using System; using System.Collections.Generic; -using System.Diagnostics; +using Verse; namespace RimWorld { @@ -10,20 +11,32 @@ protected StorytellerCompProperties_CategoryIndividualMTBByBiome Props { get { - return (StorytellerCompProperties_CategoryIndividualMTBByBiome)this.props; + return (StorytellerCompProperties_CategoryIndividualMTBByBiome)base.props; } } - [DebuggerHidden] public override IEnumerable MakeIntervalIncidents(IIncidentTarget target) { - StorytellerComp_CategoryIndividualMTBByBiome.c__IteratorA7 c__IteratorA = new StorytellerComp_CategoryIndividualMTBByBiome.c__IteratorA7(); - c__IteratorA.target = target; - c__IteratorA.<$>target = target; - c__IteratorA.<>f__this = this; - StorytellerComp_CategoryIndividualMTBByBiome.c__IteratorA7 expr_1C = c__IteratorA; - expr_1C.$PC = -2; - return expr_1C; + if (!(target is World)) + { + List allIncidents = DefDatabase.AllDefsListForReading; + for (int i = 0; i < allIncidents.Count; i++) + { + IncidentDef inc = allIncidents[i]; + if (inc.category == this.Props.category) + { + BiomeDef biome = Find.WorldGrid[target.Tile].biome; + if (inc.mtbDaysByBiome != null) + { + MTBByBiome entry = inc.mtbDaysByBiome.Find((Predicate)((MTBByBiome x) => x.biome == ((_003CMakeIntervalIncidents_003Ec__IteratorA7)/*Error near IL_00c5: stateMachine*/)._003Cbiome_003E__3)); + if (entry != null && Rand.MTBEventOccurs(entry.mtbDays, 60000f, 1000f) && inc.Worker.CanFireNow(target)) + { + yield return new FiringIncident(inc, this, this.GenerateParms(inc.category, target)); + } + } + } + } + } } } } diff --git a/Assembly-CSharp/RimWorld/StorytellerComp_CategoryMTB.cs b/Assembly-CSharp/RimWorld/StorytellerComp_CategoryMTB.cs index 2f140bb9c..862d046ea 100644 --- a/Assembly-CSharp/RimWorld/StorytellerComp_CategoryMTB.cs +++ b/Assembly-CSharp/RimWorld/StorytellerComp_CategoryMTB.cs @@ -1,6 +1,6 @@ using System; using System.Collections.Generic; -using System.Diagnostics; +using Verse; namespace RimWorld { @@ -10,20 +10,17 @@ protected StorytellerCompProperties_CategoryMTB Props { get { - return (StorytellerCompProperties_CategoryMTB)this.props; + return (StorytellerCompProperties_CategoryMTB)base.props; } } - [DebuggerHidden] public override IEnumerable MakeIntervalIncidents(IIncidentTarget target) { - StorytellerComp_CategoryMTB.c__IteratorA8 c__IteratorA = new StorytellerComp_CategoryMTB.c__IteratorA8(); - c__IteratorA.target = target; - c__IteratorA.<$>target = target; - c__IteratorA.<>f__this = this; - StorytellerComp_CategoryMTB.c__IteratorA8 expr_1C = c__IteratorA; - expr_1C.$PC = -2; - return expr_1C; + IncidentDef selectedDef; + if (Rand.MTBEventOccurs(this.Props.mtbDays, 60000f, 1000f) && this.UsableIncidentsInCategory(this.Props.category, target).TryRandomElementByWeight((Func)((IncidentDef incDef) => ((_003CMakeIntervalIncidents_003Ec__IteratorA8)/*Error near IL_0066: stateMachine*/)._003C_003Ef__this.IncidentChanceFinal(incDef)), out selectedDef)) + { + yield return new FiringIncident(selectedDef, this, this.GenerateParms(selectedDef.category, target)); + } } } } diff --git a/Assembly-CSharp/RimWorld/StorytellerComp_ClassicIntro.cs b/Assembly-CSharp/RimWorld/StorytellerComp_ClassicIntro.cs index 632c7f8dd..a3bd6f864 100644 --- a/Assembly-CSharp/RimWorld/StorytellerComp_ClassicIntro.cs +++ b/Assembly-CSharp/RimWorld/StorytellerComp_ClassicIntro.cs @@ -1,6 +1,6 @@ using System; using System.Collections.Generic; -using System.Diagnostics; +using System.Linq; using Verse; namespace RimWorld @@ -15,16 +15,67 @@ protected int IntervalsPassed } } - [DebuggerHidden] public override IEnumerable MakeIntervalIncidents(IIncidentTarget target) { - StorytellerComp_ClassicIntro.c__IteratorA9 c__IteratorA = new StorytellerComp_ClassicIntro.c__IteratorA9(); - c__IteratorA.target = target; - c__IteratorA.<$>target = target; - c__IteratorA.<>f__this = this; - StorytellerComp_ClassicIntro.c__IteratorA9 expr_1C = c__IteratorA; - expr_1C.$PC = -2; - return expr_1C; + if (target == Find.Maps.Find((Predicate)((Map x) => x.IsPlayerHome))) + { + if (this.IntervalsPassed == 150) + { + IncidentDef inc2 = IncidentDefOf.VisitorGroup; + if (inc2.TargetAllowed(target)) + { + yield return new FiringIncident(inc2, this, null) + { + parms = + { + target = target, + points = (float)Rand.Range(40, 100) + } + }; + } + } + if (this.IntervalsPassed == 204) + { + IncidentCategory threatCategory = (IncidentCategory)((!Find.Storyteller.difficulty.allowIntroThreats) ? 1 : 2); + IncidentDef incDef2; + if ((from def in DefDatabase.AllDefs + where def.TargetAllowed(((_003CMakeIntervalIncidents_003Ec__IteratorA9)/*Error near IL_0135: stateMachine*/).target) && def.category == ((_003CMakeIntervalIncidents_003Ec__IteratorA9)/*Error near IL_0135: stateMachine*/)._003CthreatCategory_003E__2 + select def).TryRandomElementByWeight(new Func(base.IncidentChanceFinal), out incDef2)) + { + yield return new FiringIncident(incDef2, this, null) + { + parms = StorytellerUtility.DefaultParmsNow(Find.Storyteller.def, incDef2.category, target) + }; + } + } + IncidentDef incDef; + if (this.IntervalsPassed == 264 && (from def in DefDatabase.AllDefs + where def.TargetAllowed(((_003CMakeIntervalIncidents_003Ec__IteratorA9)/*Error near IL_01dc: stateMachine*/).target) && def.category == IncidentCategory.Misc + select def).TryRandomElementByWeight(new Func(base.IncidentChanceFinal), out incDef)) + { + yield return new FiringIncident(incDef, this, null) + { + parms = StorytellerUtility.DefaultParmsNow(Find.Storyteller.def, incDef.category, target) + }; + } + if (this.IntervalsPassed == 324) + { + IncidentDef inc = IncidentDefOf.RaidEnemy; + if (!Find.Storyteller.difficulty.allowIntroThreats) + { + inc = (from def in DefDatabase.AllDefs + where def.TargetAllowed(((_003CMakeIntervalIncidents_003Ec__IteratorA9)/*Error near IL_02a3: stateMachine*/).target) && def.category == IncidentCategory.Misc + select def).RandomElementByWeightWithFallback(new Func(base.IncidentChanceFinal), null); + } + if (inc != null && inc.TargetAllowed(target)) + { + yield return new FiringIncident(inc, this, null) + { + parms = this.GenerateParms(inc.category, target) + }; + } + } + } } } } diff --git a/Assembly-CSharp/RimWorld/StorytellerComp_Disease.cs b/Assembly-CSharp/RimWorld/StorytellerComp_Disease.cs index 1fc6c89f9..9ed586d82 100644 --- a/Assembly-CSharp/RimWorld/StorytellerComp_Disease.cs +++ b/Assembly-CSharp/RimWorld/StorytellerComp_Disease.cs @@ -1,21 +1,27 @@ using System; using System.Collections.Generic; -using System.Diagnostics; +using System.Linq; +using Verse; namespace RimWorld { public class StorytellerComp_Disease : StorytellerComp { - [DebuggerHidden] public override IEnumerable MakeIntervalIncidents(IIncidentTarget target) { - StorytellerComp_Disease.c__IteratorAA c__IteratorAA = new StorytellerComp_Disease.c__IteratorAA(); - c__IteratorAA.target = target; - c__IteratorAA.<$>target = target; - c__IteratorAA.<>f__this = this; - StorytellerComp_Disease.c__IteratorAA expr_1C = c__IteratorAA; - expr_1C.$PC = -2; - return expr_1C; + if (DebugSettings.enableRandomDiseases && target.Tile != -1) + { + BiomeDef biome = Find.WorldGrid[target.Tile].biome; + float mtb2 = biome.diseaseMtbDays; + mtb2 *= Find.Storyteller.difficulty.diseaseIntervalFactor; + IncidentDef inc; + if (Rand.MTBEventOccurs(mtb2, 60000f, 1000f) && (from d in DefDatabase.AllDefs + where d.TargetAllowed(((_003CMakeIntervalIncidents_003Ec__IteratorAA)/*Error near IL_00b2: stateMachine*/).target) && d.category == IncidentCategory.Disease + select d).TryRandomElementByWeight((Func)((IncidentDef d) => ((_003CMakeIntervalIncidents_003Ec__IteratorAA)/*Error near IL_00c3: stateMachine*/)._003Cbiome_003E__0.CommonalityOfDisease(d)), out inc)) + { + yield return new FiringIncident(inc, this, this.GenerateParms(inc.category, target)); + } + } } } } diff --git a/Assembly-CSharp/RimWorld/StorytellerComp_JourneyOffer.cs b/Assembly-CSharp/RimWorld/StorytellerComp_JourneyOffer.cs index 09f71186a..099e3e38f 100644 --- a/Assembly-CSharp/RimWorld/StorytellerComp_JourneyOffer.cs +++ b/Assembly-CSharp/RimWorld/StorytellerComp_JourneyOffer.cs @@ -1,6 +1,4 @@ -using System; using System.Collections.Generic; -using System.Diagnostics; using Verse; namespace RimWorld @@ -17,16 +15,17 @@ private int IntervalsPassed } } - [DebuggerHidden] public override IEnumerable MakeIntervalIncidents(IIncidentTarget target) { - StorytellerComp_JourneyOffer.c__IteratorAB c__IteratorAB = new StorytellerComp_JourneyOffer.c__IteratorAB(); - c__IteratorAB.target = target; - c__IteratorAB.<$>target = target; - c__IteratorAB.<>f__this = this; - StorytellerComp_JourneyOffer.c__IteratorAB expr_1C = c__IteratorAB; - expr_1C.$PC = -2; - return expr_1C; + if (this.IntervalsPassed == 840) + { + IncidentDef inc = IncidentDefOf.JourneyOffer; + if (inc.TargetAllowed(target)) + { + FiringIncident fi = new FiringIncident(inc, this, this.GenerateParms(inc.category, target)); + yield return fi; + } + } } } } diff --git a/Assembly-CSharp/RimWorld/StorytellerComp_RandomMain.cs b/Assembly-CSharp/RimWorld/StorytellerComp_RandomMain.cs index 10fc87569..80f8eb052 100644 --- a/Assembly-CSharp/RimWorld/StorytellerComp_RandomMain.cs +++ b/Assembly-CSharp/RimWorld/StorytellerComp_RandomMain.cs @@ -1,6 +1,5 @@ using System; using System.Collections.Generic; -using System.Diagnostics; using System.Linq; using Verse; @@ -12,20 +11,38 @@ protected StorytellerCompProperties_RandomMain Props { get { - return (StorytellerCompProperties_RandomMain)this.props; + return (StorytellerCompProperties_RandomMain)base.props; } } - [DebuggerHidden] public override IEnumerable MakeIntervalIncidents(IIncidentTarget target) { - StorytellerComp_RandomMain.c__IteratorAC c__IteratorAC = new StorytellerComp_RandomMain.c__IteratorAC(); - c__IteratorAC.target = target; - c__IteratorAC.<$>target = target; - c__IteratorAC.<>f__this = this; - StorytellerComp_RandomMain.c__IteratorAC expr_1C = c__IteratorAC; - expr_1C.$PC = -2; - return expr_1C; + if (Rand.MTBEventOccurs(this.Props.mtbDays, 60000f, 1000f)) + { + List triedCategories = new List(); + IEnumerable options; + while (true) + { + if (triedCategories.Count < this.Props.categoryWeights.Count) + { + IncidentCategory category = this.DecideCategory(target, triedCategories); + triedCategories.Add(category); + IncidentParms parms = this.GenerateParms(category, target); + options = from d in DefDatabase.AllDefs + where d.category == ((_003CMakeIntervalIncidents_003Ec__IteratorAC)/*Error near IL_00cb: stateMachine*/)._003Ccategory_003E__1 && d.Worker.CanFireNow(((_003CMakeIntervalIncidents_003Ec__IteratorAC)/*Error near IL_00cb: stateMachine*/).target) && (!d.NeedsParms || d.minThreatPoints <= ((_003CMakeIntervalIncidents_003Ec__IteratorAC)/*Error near IL_00cb: stateMachine*/)._003Cparms_003E__2.points) + select d; + if (options.Any()) + break; + continue; + } + yield break; + } + IncidentDef incDef; + if (options.TryRandomElementByWeight(new Func(base.IncidentChanceFinal), out incDef)) + { + yield return new FiringIncident(incDef, this, this.GenerateParms(incDef.category, target)); + } + } } private IncidentCategory DecideCategory(IIncidentTarget target, List skipCategories) @@ -33,14 +50,14 @@ private IncidentCategory DecideCategory(IIncidentTarget target, List 60000f * this.Props.maxThreatBigIntervalDays) + if ((float)num > 60000.0 * this.Props.maxThreatBigIntervalDays) { return IncidentCategory.ThreatBig; } } return (from cw in this.Props.categoryWeights where !skipCategories.Contains(cw.category) - select cw).RandomElementByWeight((IncidentCategoryEntry cw) => cw.weight).category; + select cw).RandomElementByWeight((Func)((IncidentCategoryEntry cw) => cw.weight)).category; } public override IncidentParms GenerateParms(IncidentCategory incCat, IIncidentTarget target) diff --git a/Assembly-CSharp/RimWorld/StorytellerComp_ShipChunkDrop.cs b/Assembly-CSharp/RimWorld/StorytellerComp_ShipChunkDrop.cs index de9728714..0fb2fe898 100644 --- a/Assembly-CSharp/RimWorld/StorytellerComp_ShipChunkDrop.cs +++ b/Assembly-CSharp/RimWorld/StorytellerComp_ShipChunkDrop.cs @@ -1,6 +1,4 @@ -using System; using System.Collections.Generic; -using System.Diagnostics; using UnityEngine; using Verse; @@ -14,25 +12,25 @@ private float ShipChunkDropMTBDays { get { - float num = (float)Find.TickManager.TicksGame / 3600000f; - if (num > 10f) + float num = (float)((float)Find.TickManager.TicksGame / 3600000.0); + if (num > 10.0) { num = 2.75f; } - return 20f * Mathf.Pow(2f, num); + return (float)(20.0 * Mathf.Pow(2f, num)); } } - [DebuggerHidden] public override IEnumerable MakeIntervalIncidents(IIncidentTarget target) { - StorytellerComp_ShipChunkDrop.c__IteratorAD c__IteratorAD = new StorytellerComp_ShipChunkDrop.c__IteratorAD(); - c__IteratorAD.target = target; - c__IteratorAD.<$>target = target; - c__IteratorAD.<>f__this = this; - StorytellerComp_ShipChunkDrop.c__IteratorAD expr_1C = c__IteratorAD; - expr_1C.$PC = -2; - return expr_1C; + if (Rand.MTBEventOccurs(this.ShipChunkDropMTBDays, 60000f, 1000f)) + { + IncidentDef def = IncidentDefOf.ShipChunkDrop; + if (def.TargetAllowed(target)) + { + yield return new FiringIncident(def, this, this.GenerateParms(def.category, target)); + } + } } } } diff --git a/Assembly-CSharp/RimWorld/StorytellerComp_SingleMTB.cs b/Assembly-CSharp/RimWorld/StorytellerComp_SingleMTB.cs index 55182d744..10e1ba598 100644 --- a/Assembly-CSharp/RimWorld/StorytellerComp_SingleMTB.cs +++ b/Assembly-CSharp/RimWorld/StorytellerComp_SingleMTB.cs @@ -1,6 +1,5 @@ -using System; using System.Collections.Generic; -using System.Diagnostics; +using Verse; namespace RimWorld { @@ -10,20 +9,16 @@ private StorytellerCompProperties_SingleMTB Props { get { - return (StorytellerCompProperties_SingleMTB)this.props; + return (StorytellerCompProperties_SingleMTB)base.props; } } - [DebuggerHidden] public override IEnumerable MakeIntervalIncidents(IIncidentTarget target) { - StorytellerComp_SingleMTB.c__IteratorAE c__IteratorAE = new StorytellerComp_SingleMTB.c__IteratorAE(); - c__IteratorAE.target = target; - c__IteratorAE.<$>target = target; - c__IteratorAE.<>f__this = this; - StorytellerComp_SingleMTB.c__IteratorAE expr_1C = c__IteratorAE; - expr_1C.$PC = -2; - return expr_1C; + if (this.Props.incident.TargetAllowed(target) && Rand.MTBEventOccurs(this.Props.mtbDays, 60000f, 1000f)) + { + yield return new FiringIncident(this.Props.incident, this, this.GenerateParms(this.Props.incident.category, target)); + } } } } diff --git a/Assembly-CSharp/RimWorld/StorytellerComp_ThreatCycle.cs b/Assembly-CSharp/RimWorld/StorytellerComp_ThreatCycle.cs index 05238a9c2..567d095bd 100644 --- a/Assembly-CSharp/RimWorld/StorytellerComp_ThreatCycle.cs +++ b/Assembly-CSharp/RimWorld/StorytellerComp_ThreatCycle.cs @@ -1,6 +1,5 @@ using System; using System.Collections.Generic; -using System.Diagnostics; using System.Linq; using Verse; @@ -12,7 +11,7 @@ protected StorytellerCompProperties_ThreatCycle Props { get { - return (StorytellerCompProperties_ThreatCycle)this.props; + return (StorytellerCompProperties_ThreatCycle)base.props; } } @@ -24,53 +23,67 @@ protected int QueueIntervalsPassed } } - [DebuggerHidden] public override IEnumerable MakeIntervalIncidents(IIncidentTarget target) { - StorytellerComp_ThreatCycle.c__IteratorAF c__IteratorAF = new StorytellerComp_ThreatCycle.c__IteratorAF(); - c__IteratorAF.target = target; - c__IteratorAF.<$>target = target; - c__IteratorAF.<>f__this = this; - StorytellerComp_ThreatCycle.c__IteratorAF expr_1C = c__IteratorAF; - expr_1C.$PC = -2; - return expr_1C; + float curCycleDays = (GenDate.DaysPassedFloat - this.Props.minDaysPassed) % this.Props.ThreatCycleTotalDays; + if (curCycleDays > this.Props.threatOffDays) + { + float daysSinceThreatBig = (float)((float)(Find.TickManager.TicksGame - target.StoryState.LastThreatBigTick) / 60000.0); + if (daysSinceThreatBig > this.Props.minDaysBetweenThreatBigs && ((daysSinceThreatBig > this.Props.ThreatCycleTotalDays * 0.89999997615814209 && curCycleDays > this.Props.ThreatCycleTotalDays * 0.949999988079071) || Rand.MTBEventOccurs(this.Props.mtbDaysThreatBig, 60000f, 1000f))) + { + FiringIncident bt = this.GenerateQueuedThreatBig(target); + if (bt != null) + { + yield return bt; + } + } + if (Rand.MTBEventOccurs(this.Props.mtbDaysThreatSmall, 60000f, 1000f)) + { + FiringIncident st = this.GenerateQueuedThreatSmall(target); + if (st != null) + { + yield return st; + } + } + } } private FiringIncident GenerateQueuedThreatSmall(IIncidentTarget target) { - IncidentDef incidentDef; - if (!this.UsableIncidentsInCategory(IncidentCategory.ThreatSmall, target).TryRandomElementByWeight(new Func(base.IncidentChanceFinal), out incidentDef)) + IncidentDef incidentDef = default(IncidentDef); + if (!this.UsableIncidentsInCategory(IncidentCategory.ThreatSmall, target).TryRandomElementByWeight(new Func(base.IncidentChanceFinal), out incidentDef)) { return null; } - return new FiringIncident(incidentDef, this, null) - { - parms = this.GenerateParms(incidentDef.category, target) - }; + FiringIncident firingIncident = new FiringIncident(incidentDef, this, null); + firingIncident.parms = this.GenerateParms(incidentDef.category, target); + return firingIncident; } private FiringIncident GenerateQueuedThreatBig(IIncidentTarget target) { IncidentParms parms = this.GenerateParms(IncidentCategory.ThreatBig, target); - IncidentDef raidEnemy; + IncidentDef raidEnemy = default(IncidentDef); if (GenDate.DaysPassed < 20) { - if (!IncidentDefOf.RaidEnemy.Worker.CanFireNow(target)) + if (IncidentDefOf.RaidEnemy.Worker.CanFireNow(target)) { - return null; + raidEnemy = IncidentDefOf.RaidEnemy; + goto IL_0088; } - raidEnemy = IncidentDefOf.RaidEnemy; + return null; } - else if (!(from def in DefDatabase.AllDefs + if (!(from def in DefDatabase.AllDefs where def.category == IncidentCategory.ThreatBig && parms.points >= def.minThreatPoints && def.Worker.CanFireNow(target) - select def).TryRandomElementByWeight(new Func(base.IncidentChanceFinal), out raidEnemy)) + select def).TryRandomElementByWeight(new Func(base.IncidentChanceFinal), out raidEnemy)) { return null; } - return new FiringIncident(raidEnemy, this, null) - { - parms = parms - }; + goto IL_0088; + IL_0088: + FiringIncident firingIncident = new FiringIncident(raidEnemy, this, null); + firingIncident.parms = parms; + return firingIncident; } } } diff --git a/Assembly-CSharp/RimWorld/StorytellerDef.cs b/Assembly-CSharp/RimWorld/StorytellerDef.cs index a36f703be..cb85b41e4 100644 --- a/Assembly-CSharp/RimWorld/StorytellerDef.cs +++ b/Assembly-CSharp/RimWorld/StorytellerDef.cs @@ -1,6 +1,5 @@ using System; using System.Collections.Generic; -using System.Diagnostics; using UnityEngine; using Verse; @@ -49,7 +48,7 @@ public class StorytellerDef : Def public override void ResolveReferences() { base.ResolveReferences(); - LongEventHandler.ExecuteWhenFinished(delegate + LongEventHandler.ExecuteWhenFinished((Action)delegate { if (!this.portraitTiny.NullOrEmpty()) { @@ -63,14 +62,19 @@ public override void ResolveReferences() } } - [DebuggerHidden] public override IEnumerable ConfigErrors() { - StorytellerDef.c__Iterator97 c__Iterator = new StorytellerDef.c__Iterator97(); - c__Iterator.<>f__this = this; - StorytellerDef.c__Iterator97 expr_0E = c__Iterator; - expr_0E.$PC = -2; - return expr_0E; + foreach (string item in base.ConfigErrors()) + { + yield return item; + } + for (int i = 0; i < this.comps.Count; i++) + { + foreach (string item2 in this.comps[i].ConfigErrors(this)) + { + yield return item2; + } + } } } } diff --git a/Assembly-CSharp/RimWorld/StorytellerDefOf.cs b/Assembly-CSharp/RimWorld/StorytellerDefOf.cs index faf0a0fc7..9e8402c2b 100644 --- a/Assembly-CSharp/RimWorld/StorytellerDefOf.cs +++ b/Assembly-CSharp/RimWorld/StorytellerDefOf.cs @@ -1,5 +1,3 @@ -using System; - namespace RimWorld { [DefOf] diff --git a/Assembly-CSharp/RimWorld/StorytellerUI.cs b/Assembly-CSharp/RimWorld/StorytellerUI.cs index ca0d1edef..d695b3446 100644 --- a/Assembly-CSharp/RimWorld/StorytellerUI.cs +++ b/Assembly-CSharp/RimWorld/StorytellerUI.cs @@ -17,59 +17,73 @@ internal static void DrawStorytellerSelectionInterface(Rect rect, ref Storytelle GUI.BeginGroup(rect); if (chosenStoryteller != null && chosenStoryteller.listVisible) { - Rect position = new Rect(390f, rect.height - Storyteller.PortraitSizeLarge.y - 1f, Storyteller.PortraitSizeLarge.x, Storyteller.PortraitSizeLarge.y); + float height = rect.height; + Vector2 portraitSizeLarge = Storyteller.PortraitSizeLarge; + double y = height - portraitSizeLarge.y - 1.0; + Vector2 portraitSizeLarge2 = Storyteller.PortraitSizeLarge; + float x = portraitSizeLarge2.x; + Vector2 portraitSizeLarge3 = Storyteller.PortraitSizeLarge; + Rect position = new Rect(390f, (float)y, x, portraitSizeLarge3.y); GUI.DrawTexture(position, chosenStoryteller.portraitLargeTex); Widgets.DrawLineHorizontal(0f, rect.height, rect.width); } - Rect outRect = new Rect(0f, 0f, Storyteller.PortraitSizeTiny.x + 16f, rect.height); - Rect viewRect = new Rect(0f, 0f, Storyteller.PortraitSizeTiny.x, (float)DefDatabase.AllDefs.Count() * (Storyteller.PortraitSizeTiny.y + 10f)); + Vector2 portraitSizeTiny = Storyteller.PortraitSizeTiny; + Rect outRect = new Rect(0f, 0f, (float)(portraitSizeTiny.x + 16.0), rect.height); + Vector2 portraitSizeTiny2 = Storyteller.PortraitSizeTiny; + float x2 = portraitSizeTiny2.x; + float num = (float)DefDatabase.AllDefs.Count(); + Vector2 portraitSizeTiny3 = Storyteller.PortraitSizeTiny; + Rect viewRect = new Rect(0f, 0f, x2, (float)(num * (portraitSizeTiny3.y + 10.0))); Widgets.BeginScrollView(outRect, ref StorytellerUI.scrollPosition, viewRect, true); - Rect rect2 = new Rect(0f, 0f, Storyteller.PortraitSizeTiny.x, Storyteller.PortraitSizeTiny.y); - foreach (StorytellerDef current in from tel in DefDatabase.AllDefs + Vector2 portraitSizeTiny4 = Storyteller.PortraitSizeTiny; + float x3 = portraitSizeTiny4.x; + Vector2 portraitSizeTiny5 = Storyteller.PortraitSizeTiny; + Rect rect2 = new Rect(0f, 0f, x3, portraitSizeTiny5.y); + foreach (StorytellerDef item in from tel in DefDatabase.AllDefs orderby tel.listOrder select tel) { - if (current.listVisible) + if (item.listVisible) { - if (Widgets.ButtonImage(rect2, current.portraitTinyTex)) + if (Widgets.ButtonImage(rect2, item.portraitTinyTex)) { TutorSystem.Notify_Event("ChooseStoryteller"); - chosenStoryteller = current; + chosenStoryteller = item; } - if (chosenStoryteller == current) + if (chosenStoryteller == item) { GUI.DrawTexture(rect2, StorytellerUI.StorytellerHighlightTex); } - rect2.y += rect2.height + 8f; + rect2.y += (float)(rect2.height + 8.0); } } Widgets.EndScrollView(); Text.Font = GameFont.Small; - Rect rect3 = new Rect(outRect.xMax + 8f, 0f, 240f, 999f); + Rect rect3 = new Rect((float)(outRect.xMax + 8.0), 0f, 240f, 999f); Widgets.Label(rect3, "HowStorytellersWork".Translate()); if (chosenStoryteller != null && chosenStoryteller.listVisible) { - Rect rect4 = new Rect(outRect.xMax + 8f, outRect.yMin + 200f, 290f, 0f); + Rect rect4 = new Rect((float)(outRect.xMax + 8.0), (float)(outRect.yMin + 200.0), 290f, 0f); rect4.height = rect.height - rect4.y; Text.Font = GameFont.Medium; - Rect rect5 = new Rect(rect4.x + 15f, rect4.y - 40f, 9999f, 40f); + Rect rect5 = new Rect((float)(rect4.x + 15.0), (float)(rect4.y - 40.0), 9999f, 40f); Widgets.Label(rect5, chosenStoryteller.label); Text.Anchor = TextAnchor.UpperLeft; Text.Font = GameFont.Small; selectedStorytellerInfoListing.Begin(rect4); selectedStorytellerInfoListing.Label(chosenStoryteller.description, 120f); selectedStorytellerInfoListing.Gap(6f); - foreach (DifficultyDef current2 in DefDatabase.AllDefs) + foreach (DifficultyDef allDef in DefDatabase.AllDefs) { Rect rect6 = selectedStorytellerInfoListing.GetRect(30f); if (Mouse.IsOver(rect6)) { Widgets.DrawHighlight(rect6); } - TooltipHandler.TipRegion(rect6, current2.description); - if (Widgets.RadioButtonLabeled(rect6, current2.LabelCap, difficulty == current2)) + TooltipHandler.TipRegion(rect6, allDef.description); + if (Widgets.RadioButtonLabeled(rect6, allDef.LabelCap, difficulty == allDef)) { - difficulty = current2; + difficulty = allDef; } } selectedStorytellerInfoListing.Gap(30f); diff --git a/Assembly-CSharp/RimWorld/StorytellerUtility.cs b/Assembly-CSharp/RimWorld/StorytellerUtility.cs index 83d1c78da..61e7d1e92 100644 --- a/Assembly-CSharp/RimWorld/StorytellerUtility.cs +++ b/Assembly-CSharp/RimWorld/StorytellerUtility.cs @@ -30,31 +30,34 @@ public static IncidentParms DefaultParmsNow(StorytellerDef tellerDef, IncidentCa { IncidentParms incidentParms = new IncidentParms(); incidentParms.target = target; - if (incCat == IncidentCategory.ThreatSmall || incCat == IncidentCategory.ThreatBig) + switch (incCat) + { + case IncidentCategory.ThreatSmall: + case IncidentCategory.ThreatBig: { Map map = target as Map; float num = 0f; if (map != null) { - num = map.wealthWatcher.WealthItems + map.wealthWatcher.WealthBuildings * 0.5f; + num = (float)(map.wealthWatcher.WealthItems + map.wealthWatcher.WealthBuildings * 0.5); } - num -= 2000f; - if (num < 0f) + num = (float)(num - 2000.0); + if (num < 0.0) { num = 0f; } - float num2 = num / 1000f * 10f; + float num2 = (float)(num / 1000.0 * 10.0); float num3 = 0f; if (map != null) { - num3 = (float)map.mapPawns.FreeColonistsCount * 42f; + num3 = (float)((float)map.mapPawns.FreeColonistsCount * 42.0); } else { Caravan caravan = target as Caravan; if (caravan != null) { - num3 = (float)caravan.PawnsListForReading.Count((Pawn x) => x.IsColonist && x.HostFaction == null) * 42f; + num3 = (float)((float)caravan.PawnsListForReading.Count((Func)((Pawn x) => x.IsColonist && x.HostFaction == null)) * 42.0); } } incidentParms.points = num2 + num3; @@ -63,40 +66,53 @@ public static IncidentParms DefaultParmsNow(StorytellerDef tellerDef, IncidentCa switch (Find.StoryWatcher.statsRecord.numThreatBigs) { case 0: + { incidentParms.points = 35f; incidentParms.raidForceOneIncap = true; incidentParms.raidNeverFleeIndividual = true; break; + } case 1: + { incidentParms.points *= 0.5f; break; + } case 2: + { incidentParms.points *= 0.7f; break; + } case 3: + { incidentParms.points *= 0.8f; break; + } case 4: + { incidentParms.points *= 0.9f; break; + } default: + { incidentParms.points *= 1f; break; } - if (incidentParms.points < 0f) + } + if (incidentParms.points < 0.0) { incidentParms.points = 0f; } - if (incidentParms.points > 1000f) + if (incidentParms.points > 1000.0) { - if (incidentParms.points > 2000f) + if (incidentParms.points > 2000.0) { - incidentParms.points = 2000f + (incidentParms.points - 2000f) * 0.5f; + incidentParms.points = (float)(2000.0 + (incidentParms.points - 2000.0) * 0.5); } - incidentParms.points = 1000f + (incidentParms.points - 1000f) * 0.5f; + incidentParms.points = (float)(1000.0 + (incidentParms.points - 1000.0) * 0.5); } + break; } - else if (incCat == IncidentCategory.CaravanTarget) + case IncidentCategory.CaravanTarget: { Caravan caravan2 = incidentParms.target as Caravan; IEnumerable playerPawns; @@ -112,6 +128,8 @@ public static IncidentParms DefaultParmsNow(StorytellerDef tellerDef, IncidentCa select x; } incidentParms.points = CaravanIncidentUtility.CalculateIncidentPoints(playerPawns); + break; + } } return incidentParms; } @@ -140,7 +158,7 @@ public static float AllyIncidentMTBMultiplier() return -1f; } float num3 = (float)num / Mathf.Max((float)num2, 1f); - return 1f / num3; + return (float)(1.0 / num3); } public static void DebugLogTestFutureIncidents(bool visibleMapOnly) @@ -162,30 +180,20 @@ public static void DebugLogTestFutureIncidents(bool visibleMapOnly) int num = 0; for (int j = 0; j < 6000; j++) { - foreach (FiringIncident current in Find.Storyteller.MakeIncidentsForInterval()) + foreach (FiringIncident item in Find.Storyteller.MakeIncidentsForInterval()) { - if (!visibleMapOnly || current.parms.target == Find.VisibleMap) + if (!visibleMapOnly || item.parms.target == Find.VisibleMap) { string text = " "; - if (current.def.category == IncidentCategory.ThreatBig) + if (item.def.category == IncidentCategory.ThreatBig) { num++; text = "T"; } - int num2 = Find.Storyteller.storytellerComps.IndexOf(current.source); + int num2 = Find.Storyteller.storytellerComps.IndexOf(item.source); array[num2]++; - stringBuilder.AppendLine(string.Concat(new object[] - { - "M", - num2, - " ", - text, - " ", - Find.TickManager.TicksGame.TicksToDays().ToString("F1"), - "d ", - current - })); - current.parms.target.StoryState.Notify_IncidentFired(current); + stringBuilder.AppendLine("M" + num2 + " " + text + " " + Find.TickManager.TicksGame.TicksToDays().ToString("F1") + "d " + item); + item.parms.target.StoryState.Notify_IncidentFired(item); } } Find.TickManager.DebugSetTicksGame(Find.TickManager.TicksGame + 1000); @@ -195,27 +203,14 @@ public static void DebugLogTestFutureIncidents(bool visibleMapOnly) for (int k = 0; k < array.Length; k++) { float f = (float)array[k] / (float)array.Sum(); - float num3 = (float)array[k] / 100f; - float num4 = 1f / num3; - stringBuilder.AppendLine(string.Concat(new object[] - { - " M", - k, - ": ", - array[k], - " (", - f.ToStringPercent("F2"), - " of total, avg ", - num3.ToString("F2"), - " per day, avg interval ", - num4, - ")" - })); + float num3 = (float)((float)array[k] / 100.0); + float num4 = (float)(1.0 / num3); + stringBuilder.AppendLine(" M" + k + ": " + array[k] + " (" + f.ToStringPercent("F2") + " of total, avg " + num3.ToString("F2") + " per day, avg interval " + num4 + ")"); } stringBuilder.AppendLine("Total threats: " + num); - stringBuilder.AppendLine("Total threats avg per day: " + ((float)num / 100f).ToString("F2")); + stringBuilder.AppendLine("Total threats avg per day: " + ((float)((float)num / 100.0)).ToString("F2")); stringBuilder.AppendLine("Overall: " + array.Sum()); - stringBuilder.AppendLine("Overall avg per day: " + ((float)array.Sum() / 100f).ToString("F2")); + stringBuilder.AppendLine("Overall avg per day: " + ((float)((float)array.Sum() / 100.0)).ToString("F2")); Log.Message(stringBuilder.ToString()); Find.TickManager.DebugSetTicksGame(ticksGame); Find.Storyteller.incidentQueue = incidentQueue; diff --git a/Assembly-CSharp/RimWorld/StrengthWatcher.cs b/Assembly-CSharp/RimWorld/StrengthWatcher.cs index b66eba92d..dd77765df 100644 --- a/Assembly-CSharp/RimWorld/StrengthWatcher.cs +++ b/Assembly-CSharp/RimWorld/StrengthWatcher.cs @@ -1,4 +1,5 @@ using System; +using System.Collections.Generic; using Verse; namespace RimWorld @@ -12,24 +13,33 @@ public float StrengthRating get { float num = 0f; - foreach (Pawn current in this.map.mapPawns.FreeColonists) + foreach (Pawn freeColonist in this.map.mapPawns.FreeColonists) { float num2 = 1f; - num2 *= current.health.summaryHealth.SummaryHealthPercent; - if (current.Downed) + num2 *= freeColonist.health.summaryHealth.SummaryHealthPercent; + if (freeColonist.Downed) { - num2 *= 0.3f; + num2 = (float)(num2 * 0.30000001192092896); } num += num2; } - foreach (Building current2 in this.map.listerBuildings.allBuildingsColonistCombatTargets) + HashSet.Enumerator enumerator2 = this.map.listerBuildings.allBuildingsColonistCombatTargets.GetEnumerator(); + try { - if (current2.def.building != null && current2.def.building.IsTurret) + while (enumerator2.MoveNext()) { - num += 0.3f; + Building current2 = enumerator2.Current; + if (current2.def.building != null && current2.def.building.IsTurret) + { + num = (float)(num + 0.30000001192092896); + } } + return num; + } + finally + { + ((IDisposable)(object)enumerator2).Dispose(); } - return num; } } diff --git a/Assembly-CSharp/RimWorld/StrikeRecord.cs b/Assembly-CSharp/RimWorld/StrikeRecord.cs index 50644995c..a30502977 100644 --- a/Assembly-CSharp/RimWorld/StrikeRecord.cs +++ b/Assembly-CSharp/RimWorld/StrikeRecord.cs @@ -1,4 +1,3 @@ -using System; using Verse; namespace RimWorld @@ -30,16 +29,7 @@ public void ExposeData() public override string ToString() { - return string.Concat(new object[] - { - "(", - this.cell, - ", ", - this.def, - ", ", - this.ticksGame, - ")" - }); + return "(" + this.cell + ", " + this.def + ", " + this.ticksGame + ")"; } } } diff --git a/Assembly-CSharp/RimWorld/StuffAppearanceDefOf.cs b/Assembly-CSharp/RimWorld/StuffAppearanceDefOf.cs index 935068935..1ec62bf1b 100644 --- a/Assembly-CSharp/RimWorld/StuffAppearanceDefOf.cs +++ b/Assembly-CSharp/RimWorld/StuffAppearanceDefOf.cs @@ -1,4 +1,3 @@ -using System; using Verse; namespace RimWorld diff --git a/Assembly-CSharp/RimWorld/StuffCategoryDef.cs b/Assembly-CSharp/RimWorld/StuffCategoryDef.cs index 9af7f79f4..0e35b0ae3 100644 --- a/Assembly-CSharp/RimWorld/StuffCategoryDef.cs +++ b/Assembly-CSharp/RimWorld/StuffCategoryDef.cs @@ -1,4 +1,3 @@ -using System; using Verse; namespace RimWorld diff --git a/Assembly-CSharp/RimWorld/StuffCategoryDefOf.cs b/Assembly-CSharp/RimWorld/StuffCategoryDefOf.cs index 748e4a838..e86eec83b 100644 --- a/Assembly-CSharp/RimWorld/StuffCategoryDefOf.cs +++ b/Assembly-CSharp/RimWorld/StuffCategoryDefOf.cs @@ -1,5 +1,3 @@ -using System; - namespace RimWorld { [DefOf] diff --git a/Assembly-CSharp/RimWorld/StunHandler.cs b/Assembly-CSharp/RimWorld/StunHandler.cs index 42f9bf181..5b380d990 100644 --- a/Assembly-CSharp/RimWorld/StunHandler.cs +++ b/Assembly-CSharp/RimWorld/StunHandler.cs @@ -1,4 +1,3 @@ -using System; using UnityEngine; using Verse; @@ -79,18 +78,23 @@ public void Notify_DamageApplied(DamageInfo dinfo, bool affectedByEMP) { if (dinfo.Def == DamageDefOf.Stun) { - this.StunFor(Mathf.RoundToInt((float)dinfo.Amount * 20f)); + this.StunFor(Mathf.RoundToInt((float)((float)dinfo.Amount * 20.0))); } else if (dinfo.Def == DamageDefOf.EMP && affectedByEMP) { if (this.EMPAdaptedTicksLeft <= 0) { - this.StunFor(Mathf.RoundToInt((float)dinfo.Amount * 15f)); + this.StunFor(Mathf.RoundToInt((float)((float)dinfo.Amount * 15.0))); this.EMPAdaptedTicksLeft = this.EMPAdaptationTicksDuration; } else { - Vector3 loc = new Vector3((float)this.parent.Position.x + 1f, (float)this.parent.Position.y, (float)this.parent.Position.z + 1f); + IntVec3 position = this.parent.Position; + double x = (float)position.x + 1.0; + IntVec3 position2 = this.parent.Position; + float y = (float)position2.y; + IntVec3 position3 = this.parent.Position; + Vector3 loc = new Vector3((float)x, y, (float)((float)position3.z + 1.0)); MoteMaker.ThrowText(loc, this.parent.Map, "Adapted".Translate(), Color.white, -1f); } } diff --git a/Assembly-CSharp/RimWorld/Tale.cs b/Assembly-CSharp/RimWorld/Tale.cs index 110a95279..899512017 100644 --- a/Assembly-CSharp/RimWorld/Tale.cs +++ b/Assembly-CSharp/RimWorld/Tale.cs @@ -1,6 +1,4 @@ -using System; using System.Collections.Generic; -using System.Diagnostics; using UnityEngine; using Verse; using Verse.Grammar; @@ -55,28 +53,34 @@ public float InterestLevel { get { - float num = this.def.baseInterest; - num /= (float)(1 + this.uses * 3); + float baseInterest = this.def.baseInterest; + baseInterest /= (float)(1 + this.uses * 3); float a = 0f; switch (this.def.type) { case TaleType.Volatile: + { a = 50f; break; - case TaleType.Expirable: - a = this.def.expireDays; - break; + } case TaleType.PermanentHistorical: + { a = 50f; break; } + case TaleType.Expirable: + { + a = this.def.expireDays; + break; + } + } float value = (float)(this.AgeTicks / 60000); - num *= Mathf.InverseLerp(a, 0f, value); - if (num < 0.01f) + baseInterest *= Mathf.InverseLerp(a, 0f, value); + if (baseInterest < 0.0099999997764825821) { - num = 0.01f; + baseInterest = 0.01f; } - return num; + return baseInterest; } } @@ -84,7 +88,15 @@ public bool Expired { get { - return this.Unused && this.def.type == TaleType.Expirable && (float)this.AgeTicks > this.def.expireDays * 60000f; + if (!this.Unused) + { + return false; + } + if (this.def.type != TaleType.Expirable) + { + return false; + } + return (float)this.AgeTicks > this.def.expireDays * 60000.0; } } @@ -134,28 +146,44 @@ public void Notify_ReferenceDestroyed() if (this.uses == 0) { Log.Warning("Called reference destroyed method on tale " + this + " but uses count is 0."); - return; } - this.uses--; + else + { + this.uses--; + } } - [DebuggerHidden] public IEnumerable GetTextGenerationRules() { - Tale.c__Iterator130 c__Iterator = new Tale.c__Iterator130(); - c__Iterator.<>f__this = this; - Tale.c__Iterator130 expr_0E = c__Iterator; - expr_0E.$PC = -2; - return expr_0E; + if (this.def.rulePack != null) + { + for (int i = 0; i < this.def.rulePack.Rules.Count; i++) + { + yield return this.def.rulePack.Rules[i]; + } + } + Vector2 location = Vector2.zero; + if (this.surroundings != null && this.surroundings.tile >= 0) + { + location = Find.WorldGrid.LongLatOf(this.surroundings.tile); + } + yield return (Rule)new Rule_String("date", GenDate.DateFullStringAt(this.date, location)); + if (this.surroundings != null) + { + foreach (Rule rule in this.surroundings.GetRules()) + { + yield return rule; + } + } + foreach (Rule item in this.SpecialTextGenerationRules()) + { + yield return item; + } } - [DebuggerHidden] protected virtual IEnumerable SpecialTextGenerationRules() { - Tale.c__Iterator131 c__Iterator = new Tale.c__Iterator131(); - Tale.c__Iterator131 expr_07 = c__Iterator; - expr_07.$PC = -2; - return expr_07; + yield break; } public string GetUniqueLoadID() @@ -170,17 +198,7 @@ public override int GetHashCode() public override string ToString() { - string str = string.Concat(new object[] - { - "(#", - this.id, - ": ", - this.ShortSummary, - "(age=", - ((float)this.AgeTicks / 60000f).ToString("F2"), - " interest=", - this.InterestLevel - }); + string str = "(#" + this.id + ": " + this.ShortSummary + "(age=" + ((float)((float)this.AgeTicks / 60000.0)).ToString("F2") + " interest=" + this.InterestLevel; if (this.Unused && this.def.type == TaleType.Expirable) { str = str + ", expireDays=" + this.def.expireDays.ToString("F2"); diff --git a/Assembly-CSharp/RimWorld/TaleData.cs b/Assembly-CSharp/RimWorld/TaleData.cs index d21497a87..f1b58206d 100644 --- a/Assembly-CSharp/RimWorld/TaleData.cs +++ b/Assembly-CSharp/RimWorld/TaleData.cs @@ -1,6 +1,4 @@ -using System; using System.Collections.Generic; -using System.Diagnostics; using Verse; using Verse.Grammar; @@ -10,24 +8,16 @@ public abstract class TaleData : IExposable { public abstract void ExposeData(); - [DebuggerHidden] public virtual IEnumerable GetRules(string prefix) { - TaleData.c__Iterator12A c__Iterator12A = new TaleData.c__Iterator12A(); - c__Iterator12A.<>f__this = this; - TaleData.c__Iterator12A expr_0E = c__Iterator12A; - expr_0E.$PC = -2; - return expr_0E; + Log.Error(base.GetType() + " cannot do GetRules with a prefix."); + yield break; } - [DebuggerHidden] public virtual IEnumerable GetRules() { - TaleData.c__Iterator12B c__Iterator12B = new TaleData.c__Iterator12B(); - c__Iterator12B.<>f__this = this; - TaleData.c__Iterator12B expr_0E = c__Iterator12B; - expr_0E.$PC = -2; - return expr_0E; + Log.Error(base.GetType() + " cannot do GetRules without a prefix."); + yield break; } } } diff --git a/Assembly-CSharp/RimWorld/TaleData_Def.cs b/Assembly-CSharp/RimWorld/TaleData_Def.cs index d9bed0dee..a79eb4890 100644 --- a/Assembly-CSharp/RimWorld/TaleData_Def.cs +++ b/Assembly-CSharp/RimWorld/TaleData_Def.cs @@ -1,6 +1,5 @@ using System; using System.Collections.Generic; -using System.Diagnostics; using Verse; using Verse.Grammar; @@ -21,32 +20,26 @@ public override void ExposeData() this.tmpDefName = this.def.defName; this.tmpDefType = this.def.GetType(); } - Scribe_Values.Look(ref this.tmpDefName, "defName", null, false); - Scribe_Values.Look(ref this.tmpDefType, "defType", null, false); + Scribe_Values.Look(ref this.tmpDefName, "defName", (string)null, false); + Scribe_Values.Look(ref this.tmpDefType, "defType", (Type)null, false); if (Scribe.mode == LoadSaveMode.LoadingVars) { this.def = GenDefDatabase.GetDef(this.tmpDefType, this.tmpDefName, true); } } - [DebuggerHidden] public override IEnumerable GetRules(string prefix) { - TaleData_Def.c__Iterator12C c__Iterator12C = new TaleData_Def.c__Iterator12C(); - c__Iterator12C.prefix = prefix; - c__Iterator12C.<$>prefix = prefix; - c__Iterator12C.<>f__this = this; - TaleData_Def.c__Iterator12C expr_1C = c__Iterator12C; - expr_1C.$PC = -2; - return expr_1C; + yield return (Rule)new Rule_String(prefix + "_label", this.def.label); + yield return (Rule)new Rule_String(prefix + "_labelDefinite", Find.ActiveLanguageWorker.WithDefiniteArticle(this.def.label)); + yield return (Rule)new Rule_String(prefix + "_labelIndefinite", Find.ActiveLanguageWorker.WithIndefiniteArticle(this.def.label)); } public static TaleData_Def GenerateFrom(Def def) { - return new TaleData_Def - { - def = def - }; + TaleData_Def taleData_Def = new TaleData_Def(); + taleData_Def.def = def; + return taleData_Def; } } } diff --git a/Assembly-CSharp/RimWorld/TaleData_Pawn.cs b/Assembly-CSharp/RimWorld/TaleData_Pawn.cs index 7f965f8e9..f169bc123 100644 --- a/Assembly-CSharp/RimWorld/TaleData_Pawn.cs +++ b/Assembly-CSharp/RimWorld/TaleData_Pawn.cs @@ -1,4 +1,3 @@ -using System; using System.Collections.Generic; using Verse; using Verse.Grammar; @@ -43,7 +42,7 @@ public static TaleData_Pawn GenerateFrom(Pawn pawn) taleData_Pawn.pawn = pawn; taleData_Pawn.kind = pawn.kindDef; taleData_Pawn.faction = pawn.Faction; - taleData_Pawn.gender = ((!pawn.RaceProps.hasGenders) ? Gender.None : pawn.gender); + taleData_Pawn.gender = (pawn.RaceProps.hasGenders ? pawn.gender : Gender.None); if (pawn.RaceProps.Humanlike) { taleData_Pawn.name = pawn.Name; @@ -51,8 +50,8 @@ public static TaleData_Pawn GenerateFrom(Pawn pawn) { taleData_Pawn.primaryEquipment = pawn.equipment.Primary.def; } - Apparel apparel; - if (pawn.apparel.WornApparel.TryRandomElement(out apparel)) + Apparel apparel = default(Apparel); + if (((IEnumerable)pawn.apparel.WornApparel).TryRandomElement(out apparel)) { taleData_Pawn.notableApparel = apparel.def; } diff --git a/Assembly-CSharp/RimWorld/TaleData_Surroundings.cs b/Assembly-CSharp/RimWorld/TaleData_Surroundings.cs index 3fe49b940..b1df4686d 100644 --- a/Assembly-CSharp/RimWorld/TaleData_Surroundings.cs +++ b/Assembly-CSharp/RimWorld/TaleData_Surroundings.cs @@ -1,6 +1,4 @@ -using System; using System.Collections.Generic; -using System.Diagnostics; using Verse; using Verse.Grammar; @@ -44,14 +42,24 @@ public override void ExposeData() Scribe_Values.Look(ref this.roomCleanliness, "roomCleanliness", 0f, false); } - [DebuggerHidden] public override IEnumerable GetRules() { - TaleData_Surroundings.c__Iterator12D c__Iterator12D = new TaleData_Surroundings.c__Iterator12D(); - c__Iterator12D.<>f__this = this; - TaleData_Surroundings.c__Iterator12D expr_0E = c__Iterator12D; - expr_0E.$PC = -2; - return expr_0E; + yield return (Rule)new Rule_String("biome", Find.WorldGrid[this.tile].biome.label); + if (this.roomRole != null && this.roomRole != RoomRoleDefOf.None) + { + yield return (Rule)new Rule_String("room_role", this.roomRole.label); + yield return (Rule)new Rule_String("room_roleDefinite", Find.ActiveLanguageWorker.WithDefiniteArticle(this.roomRole.label)); + yield return (Rule)new Rule_String("room_roleIndefinite", Find.ActiveLanguageWorker.WithIndefiniteArticle(this.roomRole.label)); + RoomStatScoreStage impressiveness = RoomStatDefOf.Impressiveness.GetScoreStage(this.roomImpressiveness); + RoomStatScoreStage beauty = RoomStatDefOf.Beauty.GetScoreStage(this.roomBeauty); + RoomStatScoreStage cleanliness = RoomStatDefOf.Cleanliness.GetScoreStage(this.roomCleanliness); + yield return (Rule)new Rule_String("room_impressiveness", impressiveness.label); + yield return (Rule)new Rule_String("room_impressivenessIndefinite", Find.ActiveLanguageWorker.WithIndefiniteArticle(impressiveness.label)); + yield return (Rule)new Rule_String("room_beauty", beauty.label); + yield return (Rule)new Rule_String("room_beautyIndefinite", Find.ActiveLanguageWorker.WithIndefiniteArticle(beauty.label)); + yield return (Rule)new Rule_String("room_cleanliness", cleanliness.label); + yield return (Rule)new Rule_String("room_cleanlinessIndefinite", Find.ActiveLanguageWorker.WithIndefiniteArticle(cleanliness.label)); + } } public static TaleData_Surroundings GenerateFrom(IntVec3 c, Map map) diff --git a/Assembly-CSharp/RimWorld/TaleData_Thing.cs b/Assembly-CSharp/RimWorld/TaleData_Thing.cs index f88ba870b..901e9548c 100644 --- a/Assembly-CSharp/RimWorld/TaleData_Thing.cs +++ b/Assembly-CSharp/RimWorld/TaleData_Thing.cs @@ -1,6 +1,5 @@ using System; using System.Collections.Generic; -using System.Diagnostics; using System.Linq; using Verse; using Verse.Grammar; @@ -24,20 +23,24 @@ public override void ExposeData() Scribe_Values.Look(ref this.thingID, "thingID", 0, false); Scribe_Defs.Look(ref this.thingDef, "thingDef"); Scribe_Defs.Look(ref this.stuff, "stuff"); - Scribe_Values.Look(ref this.title, "title", null, false); + Scribe_Values.Look(ref this.title, "title", (string)null, false); Scribe_Values.Look(ref this.quality, "quality", QualityCategory.Awful, false); } - [DebuggerHidden] public override IEnumerable GetRules(string prefix) { - TaleData_Thing.c__Iterator12E c__Iterator12E = new TaleData_Thing.c__Iterator12E(); - c__Iterator12E.prefix = prefix; - c__Iterator12E.<$>prefix = prefix; - c__Iterator12E.<>f__this = this; - TaleData_Thing.c__Iterator12E expr_1C = c__Iterator12E; - expr_1C.$PC = -2; - return expr_1C; + yield return (Rule)new Rule_String(prefix + "_label", this.thingDef.label); + yield return (Rule)new Rule_String(prefix + "_labelDefinite", Find.ActiveLanguageWorker.WithDefiniteArticle(this.thingDef.label)); + yield return (Rule)new Rule_String(prefix + "_labelIndefinite", Find.ActiveLanguageWorker.WithIndefiniteArticle(this.thingDef.label)); + if (this.stuff != null) + { + yield return (Rule)new Rule_String(prefix + "_stuffLabel", this.stuff.label); + } + if (this.title != null) + { + yield return (Rule)new Rule_String(prefix + "_title", this.title); + } + yield return (Rule)new Rule_String(prefix + "_quality", this.quality.GetLabel()); } public static TaleData_Thing GenerateFrom(Thing t) @@ -57,24 +60,14 @@ public static TaleData_Thing GenerateFrom(Thing t) public static TaleData_Thing GenerateRandom() { - ThingDef thingDef = DefDatabase.AllDefs.Where(delegate(ThingDef d) - { - bool arg_36_0; - if (d.comps != null) - { - arg_36_0 = d.comps.Any((CompProperties cp) => cp.compClass == typeof(CompArt)); - } - else - { - arg_36_0 = false; - } - return arg_36_0; - }).RandomElement(); + ThingDef thingDef = (from d in DefDatabase.AllDefs + where d.comps != null && d.comps.Any((Predicate)((CompProperties cp) => cp.compClass == typeof(CompArt))) + select d).RandomElement(); ThingDef thingDef2 = GenStuff.RandomStuffFor(thingDef); Thing thing = ThingMaker.MakeThing(thingDef, thingDef2); - ArtGenerationContext source = (Rand.Value >= 0.5f) ? ArtGenerationContext.Outsider : ArtGenerationContext.Colony; + ArtGenerationContext source = (ArtGenerationContext)((Rand.Value < 0.5) ? 1 : 0); CompQuality compQuality = thing.TryGetComp(); - if (compQuality != null && compQuality.Quality < thing.TryGetComp().Props.minQualityForArtistic) + if (compQuality != null && (int)compQuality.Quality < (int)thing.TryGetComp().Props.minQualityForArtistic) { compQuality.SetQuality(thing.TryGetComp().Props.minQualityForArtistic, source); } diff --git a/Assembly-CSharp/RimWorld/TaleData_Trader.cs b/Assembly-CSharp/RimWorld/TaleData_Trader.cs index a34c75172..645b58e51 100644 --- a/Assembly-CSharp/RimWorld/TaleData_Trader.cs +++ b/Assembly-CSharp/RimWorld/TaleData_Trader.cs @@ -1,6 +1,5 @@ using System; using System.Collections.Generic; -using System.Diagnostics; using System.Linq; using Verse; using Verse.Grammar; @@ -25,21 +24,21 @@ private bool IsPawn public override void ExposeData() { - Scribe_Values.Look(ref this.name, "name", null, false); + Scribe_Values.Look(ref this.name, "name", (string)null, false); Scribe_Values.Look(ref this.pawnID, "pawnID", -1, false); Scribe_Values.Look(ref this.gender, "gender", Gender.Male, false); } - [DebuggerHidden] public override IEnumerable GetRules(string prefix) { - TaleData_Trader.c__Iterator12F c__Iterator12F = new TaleData_Trader.c__Iterator12F(); - c__Iterator12F.prefix = prefix; - c__Iterator12F.<$>prefix = prefix; - c__Iterator12F.<>f__this = this; - TaleData_Trader.c__Iterator12F expr_1C = c__Iterator12F; - expr_1C.$PC = -2; - return expr_1C; + string nameFull = (!this.IsPawn) ? Find.ActiveLanguageWorker.WithIndefiniteArticle(this.name) : this.name; + yield return (Rule)new Rule_String(prefix + "_nameFull", nameFull); + string nameShortIndefinite = (!this.IsPawn) ? Find.ActiveLanguageWorker.WithIndefiniteArticle(this.name) : this.name; + yield return (Rule)new Rule_String(prefix + "_nameShortIndefinite", nameShortIndefinite); + string nameShortDefinite = (!this.IsPawn) ? Find.ActiveLanguageWorker.WithDefiniteArticle(this.name) : this.name; + yield return (Rule)new Rule_String(prefix + "_nameShortDefinite", nameShortDefinite); + yield return (Rule)new Rule_String(prefix + "_pronoun", this.gender.GetPronoun()); + yield return (Rule)new Rule_String(prefix + "_possessive", this.gender.GetPossessive()); } public static TaleData_Trader GenerateFrom(ITrader trader) @@ -59,7 +58,7 @@ public static TaleData_Trader GenerateRandom() { PawnKindDef pawnKindDef = (from d in DefDatabase.AllDefs where d.trader - select d).RandomElement(); + select d).RandomElement(); Pawn pawn = PawnGenerator.GeneratePawn(pawnKindDef, FactionUtility.DefaultFactionFrom(pawnKindDef.defaultFactionType)); pawn.mindState.wantsToTradeWithColony = true; PawnComponentsUtility.AddAndRemoveDynamicComponents(pawn, true); diff --git a/Assembly-CSharp/RimWorld/TaleDef.cs b/Assembly-CSharp/RimWorld/TaleDef.cs index 406caae5b..ce01ffcae 100644 --- a/Assembly-CSharp/RimWorld/TaleDef.cs +++ b/Assembly-CSharp/RimWorld/TaleDef.cs @@ -1,6 +1,5 @@ using System; using System.Collections.Generic; -using System.Diagnostics; using UnityEngine; using Verse; using Verse.Grammar; @@ -38,14 +37,31 @@ public class TaleDef : Def public Color historyGraphColor = Color.white; - [DebuggerHidden] public override IEnumerable ConfigErrors() { - TaleDef.c__Iterator99 c__Iterator = new TaleDef.c__Iterator99(); - c__Iterator.<>f__this = this; - TaleDef.c__Iterator99 expr_0E = c__Iterator; - expr_0E.$PC = -2; - return expr_0E; + foreach (string item in base.ConfigErrors()) + { + yield return item; + } + if (this.taleClass == null) + { + yield return base.defName + " taleClass is null."; + } + if (this.expireDays < 0.0) + { + if (this.type == TaleType.Expirable) + { + yield return "Expirable tale type is used but expireDays<0"; + } + } + else if (this.type != TaleType.Expirable) + { + yield return "Non expirable tale type is used but expireDays>=0"; + } + if (this.baseInterest > 9.9999999747524271E-07 && !this.usableForArt) + { + yield return "Non-zero baseInterest but not usable for art"; + } } public static TaleDef Named(string str) diff --git a/Assembly-CSharp/RimWorld/TaleDefOf.cs b/Assembly-CSharp/RimWorld/TaleDefOf.cs index 9b4f05649..aa6821447 100644 --- a/Assembly-CSharp/RimWorld/TaleDefOf.cs +++ b/Assembly-CSharp/RimWorld/TaleDefOf.cs @@ -1,5 +1,3 @@ -using System; - namespace RimWorld { [DefOf] diff --git a/Assembly-CSharp/RimWorld/TaleFactory.cs b/Assembly-CSharp/RimWorld/TaleFactory.cs index 8939655a6..a030fc543 100644 --- a/Assembly-CSharp/RimWorld/TaleFactory.cs +++ b/Assembly-CSharp/RimWorld/TaleFactory.cs @@ -21,9 +21,9 @@ public static Tale MakeRandomTestTale(TaleDef def = null) { def = (from d in DefDatabase.AllDefs where d.usableForArt - select d).RandomElement(); + select d).RandomElement(); } - Tale tale = TaleFactory.MakeRawTale(def, new object[0]); + Tale tale = TaleFactory.MakeRawTale(def); tale.GenerateTestData(); return tale; } diff --git a/Assembly-CSharp/RimWorld/TaleManager.cs b/Assembly-CSharp/RimWorld/TaleManager.cs index eba47a6ef..8aacfe5df 100644 --- a/Assembly-CSharp/RimWorld/TaleManager.cs +++ b/Assembly-CSharp/RimWorld/TaleManager.cs @@ -41,10 +41,12 @@ private void RemoveTale(Tale tale) if (!tale.Unused) { Log.Warning("Tried to remove used tale " + tale); - return; } - this.tales.Remove(tale); - tale.PostRemove(); + else + { + this.tales.Remove(tale); + tale.PostRemove(); + } } private void CheckCullTales(Tale addedTale) @@ -55,73 +57,68 @@ private void CheckCullTales(Tale addedTale) private void CheckCullUnusedVolatileTales() { - int i = 0; - for (int j = 0; j < this.tales.Count; j++) + int num = 0; + for (int i = 0; i < this.tales.Count; i++) { - if (this.tales[j].def.type == TaleType.Volatile && this.tales[j].Unused) + if (this.tales[i].def.type == TaleType.Volatile && this.tales[i].Unused) { - i++; + num++; } } - while (i > 350) + while (num > 350) { Tale tale = null; - float num = 3.40282347E+38f; - for (int k = 0; k < this.tales.Count; k++) + float num2 = 3.40282347E+38f; + for (int j = 0; j < this.tales.Count; j++) { - if (this.tales[k].def.type == TaleType.Volatile && this.tales[k].Unused && this.tales[k].InterestLevel < num) + if (this.tales[j].def.type == TaleType.Volatile && this.tales[j].Unused && this.tales[j].InterestLevel < num2) { - tale = this.tales[k]; - num = this.tales[k].InterestLevel; + tale = this.tales[j]; + num2 = this.tales[j].InterestLevel; } } this.RemoveTale(tale); - i--; + num--; } } private void CheckCullUnusedTalesWithMaxPerPawnLimit(Tale addedTale) { - if (addedTale.def.maxPerPawn < 0) - { - return; - } - if (addedTale.DominantPawn == null) + if (addedTale.def.maxPerPawn >= 0 && addedTale.DominantPawn != null) { - return; - } - int i = 0; - for (int j = 0; j < this.tales.Count; j++) - { - if (this.tales[j].Unused && this.tales[j].def == addedTale.def && this.tales[j].DominantPawn == addedTale.DominantPawn) + int num = 0; + for (int i = 0; i < this.tales.Count; i++) { - i++; + if (this.tales[i].Unused && this.tales[i].def == addedTale.def && this.tales[i].DominantPawn == addedTale.DominantPawn) + { + num++; + } } - } - while (i > addedTale.def.maxPerPawn) - { - Tale tale = null; - int num = -1; - for (int k = 0; k < this.tales.Count; k++) + while (num > addedTale.def.maxPerPawn) { - if (this.tales[k].Unused && this.tales[k].def == addedTale.def && this.tales[k].DominantPawn == addedTale.DominantPawn && this.tales[k].AgeTicks > num) + Tale tale = null; + int num2 = -1; + for (int j = 0; j < this.tales.Count; j++) { - tale = this.tales[k]; - num = this.tales[k].AgeTicks; + if (this.tales[j].Unused && this.tales[j].def == addedTale.def && this.tales[j].DominantPawn == addedTale.DominantPawn && this.tales[j].AgeTicks > num2) + { + tale = this.tales[j]; + num2 = this.tales[j].AgeTicks; + } } + this.RemoveTale(tale); + num--; } - this.RemoveTale(tale); - i--; } } private void RemoveExpiredTales() { - for (int i = this.tales.Count - 1; i >= 0; i--) + for (int num = this.tales.Count - 1; num >= 0; num--) { - if (this.tales[i].Expired) + if (this.tales[num].Expired) { - this.RemoveTale(this.tales[i]); + this.RemoveTale(this.tales[num]); } } } @@ -136,14 +133,14 @@ public TaleReference GetRandomTaleReferenceForArt(ArtGenerationContext source) { return TaleReference.Taleless; } - if (Rand.Value < 0.25f) + if (Rand.Value < 0.25) { return TaleReference.Taleless; } - Tale tale; + Tale tale = default(Tale); if (!(from x in this.tales where x.def.usableForArt - select x).TryRandomElementByWeight((Tale ta) => ta.InterestLevel, out tale)) + select x).TryRandomElementByWeight((Func)((Tale ta) => ta.InterestLevel), out tale)) { return TaleReference.Taleless; } @@ -157,10 +154,10 @@ public TaleReference GetRandomTaleReferenceForArtConcerning(Thing th) { return TaleReference.Taleless; } - Tale tale; + Tale tale = default(Tale); if (!(from x in this.tales where x.def.usableForArt && x.Concerns(th) - select x).TryRandomElementByWeight((Tale x) => x.InterestLevel, out tale)) + select x).TryRandomElementByWeight((Func)((Tale x) => x.InterestLevel), out tale)) { return TaleReference.Taleless; } @@ -185,39 +182,23 @@ public Tale GetLatestTale(TaleDef def, Pawn pawn) public void Notify_PawnDestroyed(Pawn pawn) { - for (int i = this.tales.Count - 1; i >= 0; i--) + for (int num = this.tales.Count - 1; num >= 0; num--) { - if (this.tales[i].Unused) + if (this.tales[num].Unused && !this.tales[num].def.usableForArt && this.tales[num].def.type != TaleType.PermanentHistorical && this.tales[num].DominantPawn == pawn) { - if (!this.tales[i].def.usableForArt) - { - if (this.tales[i].def.type != TaleType.PermanentHistorical) - { - if (this.tales[i].DominantPawn == pawn) - { - this.RemoveTale(this.tales[i]); - } - } - } + this.RemoveTale(this.tales[num]); } } } public void Notify_PawnDiscarded(Pawn p) { - for (int i = this.tales.Count - 1; i >= 0; i--) + for (int num = this.tales.Count - 1; num >= 0; num--) { - if (this.tales[i].Concerns(p)) + if (this.tales[num].Concerns(p)) { - Log.Warning(string.Concat(new object[] - { - "Discarding pawn ", - p, - ", but he is referenced by a tale ", - this.tales[i], - "." - })); - this.RemoveTale(this.tales[i]); + Log.Warning("Discarding pawn " + p + ", but he is referenced by a tale " + this.tales[num] + "."); + this.RemoveTale(this.tales[num]); } } } @@ -242,7 +223,7 @@ public float GetMaxHistoricalTaleDay() Tale tale = this.tales[i]; if (tale.def.type == TaleType.PermanentHistorical) { - float num2 = (float)GenDate.TickAbsToGame(tale.date) / 60000f; + float num2 = (float)((float)GenDate.TickAbsToGame(tale.date) / 60000.0); if (num2 > num) { num = num2; @@ -268,37 +249,30 @@ public void LogTales() where x.def.type == TaleType.Expirable && x.Unused select x; stringBuilder.AppendLine("All tales count: " + this.tales.Count); - stringBuilder.AppendLine("Used count: " + enumerable.Count()); - stringBuilder.AppendLine(string.Concat(new object[] - { - "Unused volatile count: ", - enumerable2.Count(), - " (max: ", - 350, - ")" - })); - stringBuilder.AppendLine("Unused permanent count: " + enumerable3.Count()); - stringBuilder.AppendLine("Unused expirable count: " + enumerable4.Count()); + stringBuilder.AppendLine("Used count: " + enumerable.Count()); + stringBuilder.AppendLine("Unused volatile count: " + enumerable2.Count() + " (max: " + 350 + ")"); + stringBuilder.AppendLine("Unused permanent count: " + enumerable3.Count()); + stringBuilder.AppendLine("Unused expirable count: " + enumerable4.Count()); stringBuilder.AppendLine(); stringBuilder.AppendLine("-------Used-------"); - foreach (Tale current in enumerable) + foreach (Tale item in enumerable) { - stringBuilder.AppendLine(current.ToString()); + stringBuilder.AppendLine(item.ToString()); } stringBuilder.AppendLine("-------Unused volatile-------"); - foreach (Tale current2 in enumerable2) + foreach (Tale item2 in enumerable2) { - stringBuilder.AppendLine(current2.ToString()); + stringBuilder.AppendLine(item2.ToString()); } stringBuilder.AppendLine("-------Unused permanent-------"); - foreach (Tale current3 in enumerable3) + foreach (Tale item3 in enumerable3) { - stringBuilder.AppendLine(current3.ToString()); + stringBuilder.AppendLine(item3.ToString()); } stringBuilder.AppendLine("-------Unused expirable-------"); - foreach (Tale current4 in enumerable4) + foreach (Tale item4 in enumerable4) { - stringBuilder.AppendLine(current4.ToString()); + stringBuilder.AppendLine(item4.ToString()); } Log.Message(stringBuilder.ToString()); } @@ -308,29 +282,22 @@ public void LogTaleInterestSummary() StringBuilder stringBuilder = new StringBuilder(); float num = (from t in this.tales where t.def.usableForArt - select t).Sum((Tale t) => t.InterestLevel); - TaleDef def; - Func defInterest = (TaleDef def) => (from t in this.tales + select t).Sum((Func)((Tale t) => t.InterestLevel)); + Func defInterest = (Func)((TaleDef def) => (from t in this.tales where t.def == def - select t).Sum((Tale t) => t.InterestLevel); + select t).Sum((Func)((Tale t) => t.InterestLevel))); using (IEnumerator enumerator = (from def in DefDatabase.AllDefs where def.usableForArt orderby defInterest(def) descending select def).GetEnumerator()) { + TaleDef def2; while (enumerator.MoveNext()) { - def = enumerator.Current; - stringBuilder.AppendLine(string.Concat(new object[] - { - def.label, - ": [", - (from t in this.tales - where t.def == def - select t).Count(), - "] ", - (defInterest(def) / num).ToStringPercent("F2") - })); + def2 = enumerator.Current; + stringBuilder.AppendLine(def2.label + ": [" + (from t in this.tales + where t.def == def2 + select t).Count() + "] " + (defInterest(def2) / num).ToStringPercent("F2")); } } Log.Message(stringBuilder.ToString()); diff --git a/Assembly-CSharp/RimWorld/TaleRecorder.cs b/Assembly-CSharp/RimWorld/TaleRecorder.cs index 1aa0b94d8..9eccc8770 100644 --- a/Assembly-CSharp/RimWorld/TaleRecorder.cs +++ b/Assembly-CSharp/RimWorld/TaleRecorder.cs @@ -1,4 +1,3 @@ -using System; using Verse; namespace RimWorld @@ -7,38 +6,35 @@ public static class TaleRecorder { public static void RecordTale(TaleDef def, params object[] args) { - if (Rand.Value < def.ignoreChance) + if (!(Rand.Value < def.ignoreChance)) { - return; - } - if (def.colonistOnly) - { - bool flag = false; - bool flag2 = false; - for (int i = 0; i < args.Length; i++) + if (def.colonistOnly) { - Pawn pawn = args[i] as Pawn; - if (pawn != null) + bool flag = false; + bool flag2 = false; + for (int i = 0; i < args.Length; i++) { - flag = true; - if (pawn.Faction == Faction.OfPlayer) + Pawn pawn = args[i] as Pawn; + if (pawn != null) { - flag2 = true; + flag = true; + if (pawn.Faction == Faction.OfPlayer) + { + flag2 = true; + } } } + if (flag && !flag2) + return; } - if (flag && !flag2) - { - return; - } - } - Find.TaleManager.Add(TaleFactory.MakeRawTale(def, args)); - for (int j = 0; j < args.Length; j++) - { - Pawn pawn2 = args[j] as Pawn; - if (pawn2 != null && !pawn2.Dead && pawn2.needs.mood != null) + Find.TaleManager.Add(TaleFactory.MakeRawTale(def, args)); + for (int j = 0; j < args.Length; j++) { - pawn2.needs.mood.thoughts.situational.Notify_SituationalThoughtsDirty(); + Pawn pawn2 = args[j] as Pawn; + if (pawn2 != null && !pawn2.Dead && pawn2.needs.mood != null) + { + pawn2.needs.mood.thoughts.situational.Notify_SituationalThoughtsDirty(); + } } } } diff --git a/Assembly-CSharp/RimWorld/TaleReference.cs b/Assembly-CSharp/RimWorld/TaleReference.cs index 9ca2f5f13..989df8a1e 100644 --- a/Assembly-CSharp/RimWorld/TaleReference.cs +++ b/Assembly-CSharp/RimWorld/TaleReference.cs @@ -1,4 +1,3 @@ -using System; using System.Collections.Generic; using Verse; using Verse.Grammar; @@ -51,14 +50,7 @@ public string GenerateText(TextGenerationPurpose purpose, List extraRules) public override string ToString() { - return string.Concat(new object[] - { - "TaleReference(tale=", - (this.tale != null) ? this.tale.ToString() : "null", - ", seed=", - this.seed, - ")" - }); + return "TaleReference(tale=" + ((this.tale != null) ? this.tale.ToString() : "null") + ", seed=" + this.seed + ")"; } } } diff --git a/Assembly-CSharp/RimWorld/TaleTester.cs b/Assembly-CSharp/RimWorld/TaleTester.cs index 796c78619..2c0bba078 100644 --- a/Assembly-CSharp/RimWorld/TaleTester.cs +++ b/Assembly-CSharp/RimWorld/TaleTester.cs @@ -12,7 +12,7 @@ public static class TaleTester public static void LogGeneratedTales(int count) { List list = new List(); - for (int i = 0; i < count; i++) + for (int num = 0; num < count; num++) { list.Add(TaleFactory.MakeRandomTestTale(null)); } @@ -22,7 +22,7 @@ public static void LogGeneratedTales(int count) public static void LogSpecificTale(TaleDef def, int count) { List list = new List(); - for (int i = 0; i < count; i++) + for (int num = 0; num < count; num++) { list.Add(TaleFactory.MakeRandomTestTale(def)); } @@ -50,9 +50,9 @@ private static void LogTales(IEnumerable tales) { StringBuilder stringBuilder = new StringBuilder(); int num = 0; - foreach (Tale current in tales) + foreach (Tale item in tales) { - TaleReference tr = new TaleReference(current); + TaleReference tr = new TaleReference(item); stringBuilder.AppendLine(TaleTester.RandomArtworkName(tr)); stringBuilder.AppendLine(TaleTester.RandomArtworkDescription(tr)); stringBuilder.AppendLine(); @@ -75,21 +75,31 @@ private static string RandomArtworkName(TaleReference tr) switch (Rand.RangeInclusive(0, 4)) { case 0: + { list.AddRange(RulePackDefOf.ArtName_Sculpture.Rules); break; + } case 1: + { list.AddRange(RulePackDefOf.ArtName_WeaponMelee.Rules); break; + } case 2: + { list.AddRange(RulePackDefOf.ArtName_WeaponGun.Rules); break; + } case 3: + { list.AddRange(RulePackDefOf.ArtName_Furniture.Rules); break; + } case 4: + { list.AddRange(RulePackDefOf.ArtName_SarcophagusPlate.Rules); break; } + } return tr.GenerateText(TextGenerationPurpose.ArtName, list); } @@ -99,21 +109,31 @@ private static string RandomArtworkDescription(TaleReference tr) switch (Rand.RangeInclusive(0, 4)) { case 0: + { list.AddRange(RulePackDefOf.ArtDescription_Sculpture.Rules); break; + } case 1: + { list.AddRange(RulePackDefOf.ArtDescription_WeaponMelee.Rules); break; + } case 2: + { list.AddRange(RulePackDefOf.ArtDescription_WeaponGun.Rules); break; + } case 3: + { list.AddRange(RulePackDefOf.ArtDescription_Furniture.Rules); break; + } case 4: + { list.AddRange(RulePackDefOf.ArtDescription_SarcophagusPlate.Rules); break; } + } return tr.GenerateText(TextGenerationPurpose.ArtDescription, list); } } diff --git a/Assembly-CSharp/RimWorld/TaleTextGenerator.cs b/Assembly-CSharp/RimWorld/TaleTextGenerator.cs index 28277197b..47e342d92 100644 --- a/Assembly-CSharp/RimWorld/TaleTextGenerator.cs +++ b/Assembly-CSharp/RimWorld/TaleTextGenerator.cs @@ -1,4 +1,3 @@ -using System; using System.Collections.Generic; using Verse; using Verse.Grammar; @@ -13,13 +12,15 @@ public static string GenerateTextFromTale(TextGenerationPurpose purpose, Tale ta { Rand.PushState(); Rand.Seed = seed; - string rootKeyword = null; + string rootKeyword = (string)null; List list = new List(); list.AddRange(extraRules); - if (purpose == TextGenerationPurpose.ArtDescription) + switch (purpose) + { + case TextGenerationPurpose.ArtDescription: { rootKeyword = "art_description_root"; - if (tale != null && Rand.Value > 0.2f) + if (tale != null && Rand.Value > 0.20000000298023224) { list.AddRange(RulePackDefOf.ArtDescriptionRoot_HasTale.Rules); list.AddRange(tale.GetTextGenerationRules()); @@ -30,14 +31,17 @@ public static string GenerateTextFromTale(TextGenerationPurpose purpose, Tale ta list.AddRange(RulePackDefOf.TalelessImages.Rules); } list.AddRange(RulePackDefOf.ArtDescriptionUtility_Global.Rules); + break; } - else if (purpose == TextGenerationPurpose.ArtName) + case TextGenerationPurpose.ArtName: { rootKeyword = "art_name"; if (tale != null) { list.AddRange(tale.GetTextGenerationRules()); } + break; + } } string result = GrammarResolver.Resolve(rootKeyword, list, (tale == null) ? "null_tale" : tale.def.defName); Rand.PopState(); diff --git a/Assembly-CSharp/RimWorld/TaleType.cs b/Assembly-CSharp/RimWorld/TaleType.cs index f77df1a86..95bbcd55d 100644 --- a/Assembly-CSharp/RimWorld/TaleType.cs +++ b/Assembly-CSharp/RimWorld/TaleType.cs @@ -1,11 +1,9 @@ -using System; - namespace RimWorld { public enum TaleType { - Volatile, - Expirable, - PermanentHistorical + Volatile = 0, + Expirable = 1, + PermanentHistorical = 2 } } diff --git a/Assembly-CSharp/RimWorld/Tale_DoublePawn.cs b/Assembly-CSharp/RimWorld/Tale_DoublePawn.cs index aa610e14b..0eb65add3 100644 --- a/Assembly-CSharp/RimWorld/Tale_DoublePawn.cs +++ b/Assembly-CSharp/RimWorld/Tale_DoublePawn.cs @@ -1,7 +1,5 @@ using RimWorld.Planet; -using System; using System.Collections.Generic; -using System.Diagnostics; using Verse; using Verse.Grammar; @@ -25,7 +23,7 @@ public override string ShortSummary { get { - string text = this.def.LabelCap + ": " + this.firstPawnData.name; + string text = base.def.LabelCap + ": " + this.firstPawnData.name; if (this.secondPawnData != null) { text = text + ", " + this.secondPawnData.name; @@ -47,13 +45,17 @@ public Tale_DoublePawn(Pawn firstPawn, Pawn secondPawn) } if (firstPawn.SpawnedOrAnyParentSpawned) { - this.surroundings = TaleData_Surroundings.GenerateFrom(firstPawn.PositionHeld, firstPawn.MapHeld); + base.surroundings = TaleData_Surroundings.GenerateFrom(firstPawn.PositionHeld, firstPawn.MapHeld); } } public override bool Concerns(Thing th) { - return (this.secondPawnData != null && this.secondPawnData.pawn == th) || base.Concerns(th) || this.firstPawnData.pawn == th; + if (this.secondPawnData != null && this.secondPawnData.pawn == th) + { + return true; + } + return base.Concerns(th) || this.firstPawnData.pawn == th; } public override void PostRemove() @@ -77,14 +79,27 @@ public override void ExposeData() Scribe_Deep.Look(ref this.secondPawnData, "secondPawnData", new object[0]); } - [DebuggerHidden] protected override IEnumerable SpecialTextGenerationRules() { - Tale_DoublePawn.c__Iterator132 c__Iterator = new Tale_DoublePawn.c__Iterator132(); - c__Iterator.<>f__this = this; - Tale_DoublePawn.c__Iterator132 expr_0E = c__Iterator; - expr_0E.$PC = -2; - return expr_0E; + foreach (Rule rule in this.firstPawnData.GetRules("anyPawn")) + { + yield return rule; + } + foreach (Rule rule2 in this.firstPawnData.GetRules(base.def.firstPawnSymbol)) + { + yield return rule2; + } + if (this.secondPawnData != null) + { + foreach (Rule rule3 in this.firstPawnData.GetRules("anyPawn")) + { + yield return rule3; + } + foreach (Rule rule4 in this.secondPawnData.GetRules(base.def.secondPawnSymbol)) + { + yield return rule4; + } + } } public override void GenerateTestData() diff --git a/Assembly-CSharp/RimWorld/Tale_DoublePawnAndDef.cs b/Assembly-CSharp/RimWorld/Tale_DoublePawnAndDef.cs index 04f266a06..4ac96701c 100644 --- a/Assembly-CSharp/RimWorld/Tale_DoublePawnAndDef.cs +++ b/Assembly-CSharp/RimWorld/Tale_DoublePawnAndDef.cs @@ -1,6 +1,4 @@ -using System; using System.Collections.Generic; -using System.Diagnostics; using Verse; using Verse.Grammar; @@ -25,14 +23,16 @@ public override void ExposeData() Scribe_Deep.Look(ref this.defData, "defData", new object[0]); } - [DebuggerHidden] protected override IEnumerable SpecialTextGenerationRules() { - Tale_DoublePawnAndDef.c__Iterator133 c__Iterator = new Tale_DoublePawnAndDef.c__Iterator133(); - c__Iterator.<>f__this = this; - Tale_DoublePawnAndDef.c__Iterator133 expr_0E = c__Iterator; - expr_0E.$PC = -2; - return expr_0E; + foreach (Rule item in base.SpecialTextGenerationRules()) + { + yield return item; + } + foreach (Rule rule in this.defData.GetRules(base.def.defSymbol)) + { + yield return rule; + } } public override void GenerateTestData() diff --git a/Assembly-CSharp/RimWorld/Tale_DoublePawnAndTrader.cs b/Assembly-CSharp/RimWorld/Tale_DoublePawnAndTrader.cs index 073f4cc88..3a3558200 100644 --- a/Assembly-CSharp/RimWorld/Tale_DoublePawnAndTrader.cs +++ b/Assembly-CSharp/RimWorld/Tale_DoublePawnAndTrader.cs @@ -1,6 +1,4 @@ -using System; using System.Collections.Generic; -using System.Diagnostics; using Verse; using Verse.Grammar; @@ -30,14 +28,16 @@ public override void ExposeData() Scribe_Deep.Look(ref this.traderData, "traderData", new object[0]); } - [DebuggerHidden] protected override IEnumerable SpecialTextGenerationRules() { - Tale_DoublePawnAndTrader.c__Iterator134 c__Iterator = new Tale_DoublePawnAndTrader.c__Iterator134(); - c__Iterator.<>f__this = this; - Tale_DoublePawnAndTrader.c__Iterator134 expr_0E = c__Iterator; - expr_0E.$PC = -2; - return expr_0E; + foreach (Rule item in base.SpecialTextGenerationRules()) + { + yield return item; + } + foreach (Rule rule in this.traderData.GetRules("trader")) + { + yield return rule; + } } public override void GenerateTestData() diff --git a/Assembly-CSharp/RimWorld/Tale_DoublePawnKilledBy.cs b/Assembly-CSharp/RimWorld/Tale_DoublePawnKilledBy.cs index 914b48b37..4f14f7ae0 100644 --- a/Assembly-CSharp/RimWorld/Tale_DoublePawnKilledBy.cs +++ b/Assembly-CSharp/RimWorld/Tale_DoublePawnKilledBy.cs @@ -1,4 +1,3 @@ -using System; using Verse; namespace RimWorld @@ -13,7 +12,7 @@ public Tale_DoublePawnKilledBy(Pawn victim, DamageInfo dinfo) : base(victim, nul { if (dinfo.Instigator != null && dinfo.Instigator is Pawn) { - this.secondPawnData = TaleData_Pawn.GenerateFrom((Pawn)dinfo.Instigator); + base.secondPawnData = TaleData_Pawn.GenerateFrom((Pawn)dinfo.Instigator); } } } diff --git a/Assembly-CSharp/RimWorld/Tale_SinglePawn.cs b/Assembly-CSharp/RimWorld/Tale_SinglePawn.cs index 90ef93d56..1c6f9906e 100644 --- a/Assembly-CSharp/RimWorld/Tale_SinglePawn.cs +++ b/Assembly-CSharp/RimWorld/Tale_SinglePawn.cs @@ -1,7 +1,5 @@ using RimWorld.Planet; -using System; using System.Collections.Generic; -using System.Diagnostics; using Verse; using Verse.Grammar; @@ -23,7 +21,7 @@ public override string ShortSummary { get { - return this.def.LabelCap + ": " + this.pawnData.name; + return base.def.LabelCap + ": " + this.pawnData.name; } } @@ -36,7 +34,7 @@ public Tale_SinglePawn(Pawn pawn) this.pawnData = TaleData_Pawn.GenerateFrom(pawn); if (pawn.SpawnedOrAnyParentSpawned) { - this.surroundings = TaleData_Surroundings.GenerateFrom(pawn.PositionHeld, pawn.MapHeld); + base.surroundings = TaleData_Surroundings.GenerateFrom(pawn.PositionHeld, pawn.MapHeld); } } @@ -61,14 +59,16 @@ public override void ExposeData() Scribe_Deep.Look(ref this.pawnData, "pawnData", new object[0]); } - [DebuggerHidden] protected override IEnumerable SpecialTextGenerationRules() { - Tale_SinglePawn.c__Iterator135 c__Iterator = new Tale_SinglePawn.c__Iterator135(); - c__Iterator.<>f__this = this; - Tale_SinglePawn.c__Iterator135 expr_0E = c__Iterator; - expr_0E.$PC = -2; - return expr_0E; + foreach (Rule rule in this.pawnData.GetRules("anyPawn")) + { + yield return rule; + } + foreach (Rule rule2 in this.pawnData.GetRules("pawn")) + { + yield return rule2; + } } public override void GenerateTestData() diff --git a/Assembly-CSharp/RimWorld/Tale_SinglePawnAndDef.cs b/Assembly-CSharp/RimWorld/Tale_SinglePawnAndDef.cs index 27f5140ea..9ea371d60 100644 --- a/Assembly-CSharp/RimWorld/Tale_SinglePawnAndDef.cs +++ b/Assembly-CSharp/RimWorld/Tale_SinglePawnAndDef.cs @@ -1,6 +1,4 @@ -using System; using System.Collections.Generic; -using System.Diagnostics; using Verse; using Verse.Grammar; @@ -25,14 +23,16 @@ public override void ExposeData() Scribe_Deep.Look(ref this.defData, "defData", new object[0]); } - [DebuggerHidden] protected override IEnumerable SpecialTextGenerationRules() { - Tale_SinglePawnAndDef.c__Iterator136 c__Iterator = new Tale_SinglePawnAndDef.c__Iterator136(); - c__Iterator.<>f__this = this; - Tale_SinglePawnAndDef.c__Iterator136 expr_0E = c__Iterator; - expr_0E.$PC = -2; - return expr_0E; + foreach (Rule item in base.SpecialTextGenerationRules()) + { + yield return item; + } + foreach (Rule rule in this.defData.GetRules(base.def.defSymbol)) + { + yield return rule; + } } public override void GenerateTestData() diff --git a/Assembly-CSharp/RimWorld/Tale_SinglePawnAndThing.cs b/Assembly-CSharp/RimWorld/Tale_SinglePawnAndThing.cs index c1d6baacf..ab8ba50ba 100644 --- a/Assembly-CSharp/RimWorld/Tale_SinglePawnAndThing.cs +++ b/Assembly-CSharp/RimWorld/Tale_SinglePawnAndThing.cs @@ -1,6 +1,4 @@ -using System; using System.Collections.Generic; -using System.Diagnostics; using Verse; using Verse.Grammar; @@ -30,14 +28,16 @@ public override void ExposeData() Scribe_Deep.Look(ref this.thingData, "thingData", new object[0]); } - [DebuggerHidden] protected override IEnumerable SpecialTextGenerationRules() { - Tale_SinglePawnAndThing.c__Iterator137 c__Iterator = new Tale_SinglePawnAndThing.c__Iterator137(); - c__Iterator.<>f__this = this; - Tale_SinglePawnAndThing.c__Iterator137 expr_0E = c__Iterator; - expr_0E.$PC = -2; - return expr_0E; + foreach (Rule item in base.SpecialTextGenerationRules()) + { + yield return item; + } + foreach (Rule rule in this.thingData.GetRules("thing")) + { + yield return rule; + } } public override void GenerateTestData() diff --git a/Assembly-CSharp/RimWorld/Tale_SinglePawnAndTrader.cs b/Assembly-CSharp/RimWorld/Tale_SinglePawnAndTrader.cs index e4f329c85..fe79f0635 100644 --- a/Assembly-CSharp/RimWorld/Tale_SinglePawnAndTrader.cs +++ b/Assembly-CSharp/RimWorld/Tale_SinglePawnAndTrader.cs @@ -1,6 +1,4 @@ -using System; using System.Collections.Generic; -using System.Diagnostics; using Verse; using Verse.Grammar; @@ -30,14 +28,16 @@ public override void ExposeData() Scribe_Deep.Look(ref this.traderData, "traderData", new object[0]); } - [DebuggerHidden] protected override IEnumerable SpecialTextGenerationRules() { - Tale_SinglePawnAndTrader.c__Iterator138 c__Iterator = new Tale_SinglePawnAndTrader.c__Iterator138(); - c__Iterator.<>f__this = this; - Tale_SinglePawnAndTrader.c__Iterator138 expr_0E = c__Iterator; - expr_0E.$PC = -2; - return expr_0E; + foreach (Rule item in base.SpecialTextGenerationRules()) + { + yield return item; + } + foreach (Rule rule in this.traderData.GetRules("trader")) + { + yield return rule; + } } public override void GenerateTestData() diff --git a/Assembly-CSharp/RimWorld/Targeter.cs b/Assembly-CSharp/RimWorld/Targeter.cs index c75f5b137..7da5ffc7d 100644 --- a/Assembly-CSharp/RimWorld/Targeter.cs +++ b/Assembly-CSharp/RimWorld/Targeter.cs @@ -28,7 +28,7 @@ public bool IsTargeting { get { - return this.targetingVerb != null || this.action != null; + return this.targetingVerb != null || (object)this.action != null; } } @@ -43,7 +43,7 @@ public void BeginTargeting(Verb verb) { Job job = new Job(JobDefOf.UseVerbOnThing); job.verbToUse = verb; - verb.CasterPawn.jobs.StartJob(job, JobCondition.None, null, false, true, null, null); + verb.CasterPawn.jobs.StartJob(job, JobCondition.None, null, false, true, null, default(JobTag?)); } this.action = null; this.caster = null; @@ -65,7 +65,7 @@ public void BeginTargeting(TargetingParameters targetParams, Action 0.2f && this.targetingVerb.TryFindShootLineFromTo(this.targetingVerb.caster.Position, targ, out shootLine)) + ShootLine shootLine = default(ShootLine); + if (this.targetingVerb.HighlightFieldRadiusAroundTarget() > 0.20000000298023224 && this.targetingVerb.TryFindShootLineFromTo(this.targetingVerb.caster.Position, targ, out shootLine)) { GenExplosion.RenderPredictedAreaOfEffect(shootLine.Dest, this.targetingVerb.HighlightFieldRadiusAroundTarget()); } } } - if (this.action != null) + if ((object)this.action != null) { LocalTargetInfo targ2 = this.CurrentTargetUnderMouse(false); if (targ2.IsValid) @@ -209,14 +198,21 @@ private void ConfirmStillValid() } else { - for (int i = 0; i < this.targetingVerbAdditionalPawns.Count; i++) + int num = 0; + while (true) { - if (this.targetingVerbAdditionalPawns[i].Destroyed || !selector.IsSelected(this.targetingVerbAdditionalPawns[i])) + if (num < this.targetingVerbAdditionalPawns.Count) { - this.StopTargeting(); + if (!this.targetingVerbAdditionalPawns[num].Destroyed && selector.IsSelected(this.targetingVerbAdditionalPawns[num])) + { + num++; + continue; + } break; } + return; } + this.StopTargeting(); } } } @@ -239,9 +235,9 @@ private void OrderVerbForceTarget() { int numSelected = Find.Selector.NumSelected; List selectedObjects = Find.Selector.SelectedObjects; - for (int j = 0; j < numSelected; j++) + for (int num = 0; num < numSelected; num++) { - Building_Turret building_Turret = selectedObjects[j] as Building_Turret; + Building_Turret building_Turret = selectedObjects[num] as Building_Turret; if (building_Turret != null && building_Turret.Map == Find.VisibleMap) { LocalTargetInfo targ = this.CurrentTargetUnderMouse(true); @@ -254,28 +250,27 @@ private void OrderVerbForceTarget() private void OrderPawnForceTarget(Verb verb) { LocalTargetInfo targetA = this.CurrentTargetUnderMouse(true); - if (!targetA.IsValid) - { - return; - } - if (verb.verbProps.MeleeRange) + if (targetA.IsValid) { - Job job = new Job(JobDefOf.AttackMelee, targetA); - job.playerForced = true; - Pawn pawn = targetA.Thing as Pawn; - if (pawn != null) + if (verb.verbProps.MeleeRange) + { + Job job = new Job(JobDefOf.AttackMelee, targetA); + job.playerForced = true; + Pawn pawn = targetA.Thing as Pawn; + if (pawn != null) + { + job.killIncappedTarget = pawn.Downed; + } + verb.CasterPawn.jobs.TryTakeOrderedJob(job, JobTag.Misc); + } + else { - job.killIncappedTarget = pawn.Downed; + JobDef def = (!verb.verbProps.ai_IsWeapon) ? JobDefOf.UseVerbOnThing : JobDefOf.AttackStatic; + Job job2 = new Job(def); + job2.verbToUse = verb; + job2.targetA = targetA; + verb.CasterPawn.jobs.TryTakeOrderedJob(job2, JobTag.Misc); } - verb.CasterPawn.jobs.TryTakeOrderedJob(job, JobTag.Misc); - } - else - { - JobDef def = (!verb.verbProps.ai_IsWeapon) ? JobDefOf.UseVerbOnThing : JobDefOf.AttackStatic; - Job job2 = new Job(def); - job2.verbToUse = verb; - job2.targetA = targetA; - verb.CasterPawn.jobs.TryTakeOrderedJob(job2, JobTag.Misc); } } @@ -291,13 +286,12 @@ private LocalTargetInfo CurrentTargetUnderMouse(bool mustBeHittableNowIfNotMelee { if (enumerator.MoveNext()) { - LocalTargetInfo current = enumerator.Current; - localTargetInfo = current; + LocalTargetInfo localTargetInfo2 = localTargetInfo = enumerator.Current; } } if (localTargetInfo.IsValid && mustBeHittableNowIfNotMelee && !(localTargetInfo.Thing is Pawn) && this.targetingVerb != null && !this.targetingVerb.verbProps.MeleeRange) { - if (this.targetingVerbAdditionalPawns != null && this.targetingVerbAdditionalPawns.Any()) + if (this.targetingVerbAdditionalPawns != null && this.targetingVerbAdditionalPawns.Any()) { bool flag = false; for (int i = 0; i < this.targetingVerbAdditionalPawns.Count; i++) @@ -324,7 +318,7 @@ private LocalTargetInfo CurrentTargetUnderMouse(bool mustBeHittableNowIfNotMelee private Verb GetTargetingVerb(Pawn pawn) { - return pawn.equipment.AllEquipmentVerbs.FirstOrDefault((Verb x) => x.verbProps == this.targetingVerb.verbProps); + return pawn.equipment.AllEquipmentVerbs.FirstOrDefault((Func)((Verb x) => x.verbProps == this.targetingVerb.verbProps)); } } } diff --git a/Assembly-CSharp/RimWorld/TargetingParameters.cs b/Assembly-CSharp/RimWorld/TargetingParameters.cs index 6568b9599..c04216dd9 100644 --- a/Assembly-CSharp/RimWorld/TargetingParameters.cs +++ b/Assembly-CSharp/RimWorld/TargetingParameters.cs @@ -43,7 +43,7 @@ public class TargetingParameters public bool CanTarget(TargetInfo targ) { - if (this.validator != null && !this.validator(targ)) + if ((object)this.validator != null && !this.validator(targ)) { return false; } @@ -88,43 +88,65 @@ public bool CanTarget(TargetInfo targ) { return false; } - return this.onlyTargetFactions == null || this.onlyTargetFactions.Contains(targ.Thing.Faction); + if (this.onlyTargetFactions != null && !this.onlyTargetFactions.Contains(targ.Thing.Faction)) + { + return false; + } + return true; } if (this.canTargetBuildings && targ.Thing.def.category == ThingCategory.Building) { - return (!this.onlyTargetThingsAffectingRegions || targ.Thing.def.AffectsRegions) && (this.onlyTargetFactions == null || this.onlyTargetFactions.Contains(targ.Thing.Faction)); + if (this.onlyTargetThingsAffectingRegions && !targ.Thing.def.AffectsRegions) + { + return false; + } + if (this.onlyTargetFactions != null && !this.onlyTargetFactions.Contains(targ.Thing.Faction)) + { + return false; + } + return true; + } + if (this.canTargetItems) + { + if (this.mapObjectTargetsMustBeAutoAttackable && !targ.Thing.def.isAutoAttackableMapObject) + { + return false; + } + return true; } - return this.canTargetItems && (!this.mapObjectTargetsMustBeAutoAttackable || targ.Thing.def.isAutoAttackableMapObject); + return false; } public static TargetingParameters ForSelf(Pawn p) { - return new TargetingParameters - { - targetSpecificThing = p, - canTargetPawns = false, - canTargetBuildings = false, - mapObjectTargetsMustBeAutoAttackable = false - }; + TargetingParameters targetingParameters = new TargetingParameters(); + targetingParameters.targetSpecificThing = p; + targetingParameters.canTargetPawns = false; + targetingParameters.canTargetBuildings = false; + targetingParameters.mapObjectTargetsMustBeAutoAttackable = false; + return targetingParameters; } public static TargetingParameters ForArrest(Pawn arrester) { - return new TargetingParameters + TargetingParameters targetingParameters = new TargetingParameters(); + targetingParameters.canTargetPawns = true; + targetingParameters.canTargetBuildings = false; + targetingParameters.mapObjectTargetsMustBeAutoAttackable = false; + targetingParameters.validator = (Predicate)delegate(TargetInfo targ) { - canTargetPawns = true, - canTargetBuildings = false, - mapObjectTargetsMustBeAutoAttackable = false, - validator = delegate(TargetInfo targ) + if (!targ.HasThing) { - if (!targ.HasThing) - { - return false; - } - Pawn pawn = targ.Thing as Pawn; - return pawn != null && pawn != arrester && pawn.CanBeArrested(); + return false; + } + Pawn pawn = targ.Thing as Pawn; + if (pawn != null && pawn != arrester && pawn.CanBeArrested()) + { + return true; } + return false; }; + return targetingParameters; } public static TargetingParameters ForAttackHostile() @@ -134,30 +156,28 @@ public static TargetingParameters ForAttackHostile() targetingParameters.canTargetBuildings = true; targetingParameters.canTargetItems = true; targetingParameters.mapObjectTargetsMustBeAutoAttackable = true; - targetingParameters.validator = ((TargetInfo targ) => targ.HasThing && (targ.Thing.HostileTo(Faction.OfPlayer) || (targ.Thing is Pawn && !((Pawn)targ.Thing).RaceProps.Humanlike))); + targetingParameters.validator = (Predicate)((TargetInfo targ) => targ.HasThing && (targ.Thing.HostileTo(Faction.OfPlayer) || (targ.Thing is Pawn && !((Pawn)targ.Thing).RaceProps.Humanlike))); return targetingParameters; } public static TargetingParameters ForAttackAny() { - return new TargetingParameters - { - canTargetPawns = true, - canTargetBuildings = true, - canTargetItems = true, - mapObjectTargetsMustBeAutoAttackable = true - }; + TargetingParameters targetingParameters = new TargetingParameters(); + targetingParameters.canTargetPawns = true; + targetingParameters.canTargetBuildings = true; + targetingParameters.canTargetItems = true; + targetingParameters.mapObjectTargetsMustBeAutoAttackable = true; + return targetingParameters; } public static TargetingParameters ForRescue(Pawn p) { - return new TargetingParameters - { - canTargetPawns = true, - onlyTargetIncapacitatedPawns = true, - canTargetBuildings = false, - mapObjectTargetsMustBeAutoAttackable = false - }; + TargetingParameters targetingParameters = new TargetingParameters(); + targetingParameters.canTargetPawns = true; + targetingParameters.onlyTargetIncapacitatedPawns = true; + targetingParameters.canTargetBuildings = false; + targetingParameters.mapObjectTargetsMustBeAutoAttackable = false; + return targetingParameters; } public static TargetingParameters ForStrip(Pawn p) @@ -166,7 +186,14 @@ public static TargetingParameters ForStrip(Pawn p) targetingParameters.canTargetPawns = true; targetingParameters.canTargetItems = true; targetingParameters.mapObjectTargetsMustBeAutoAttackable = false; - targetingParameters.validator = ((TargetInfo targ) => targ.HasThing && StrippableUtility.CanBeStrippedByColony(targ.Thing)); + targetingParameters.validator = (Predicate)delegate(TargetInfo targ) + { + if (!targ.HasThing) + { + return false; + } + return StrippableUtility.CanBeStrippedByColony(targ.Thing); + }; return targetingParameters; } @@ -176,10 +203,14 @@ public static TargetingParameters ForTrade() targetingParameters.canTargetPawns = true; targetingParameters.canTargetBuildings = false; targetingParameters.mapObjectTargetsMustBeAutoAttackable = false; - targetingParameters.validator = delegate(TargetInfo x) + targetingParameters.validator = (Predicate)delegate(TargetInfo x) { ITrader trader = x.Thing as ITrader; - return trader != null && trader.CanTradeNow; + if (trader == null) + { + return false; + } + return trader.CanTradeNow; }; return targetingParameters; } @@ -193,7 +224,7 @@ public static TargetingParameters ForDropPodsDestination() targetingParameters.canTargetFires = false; targetingParameters.canTargetBuildings = false; targetingParameters.canTargetItems = false; - targetingParameters.validator = ((TargetInfo x) => DropCellFinder.IsGoodDropSpot(x.Cell, x.Map, false, true)); + targetingParameters.validator = (Predicate)((TargetInfo x) => DropCellFinder.IsGoodDropSpot(x.Cell, x.Map, false, true)); return targetingParameters; } } diff --git a/Assembly-CSharp/RimWorld/TechLevel.cs b/Assembly-CSharp/RimWorld/TechLevel.cs index c0f9f9983..6977be4c6 100644 --- a/Assembly-CSharp/RimWorld/TechLevel.cs +++ b/Assembly-CSharp/RimWorld/TechLevel.cs @@ -1,16 +1,14 @@ -using System; - namespace RimWorld { public enum TechLevel : byte { - Undefined, - Animal, - Neolithic, - Medieval, - Industrial, - Spacer, - Ultra, - Transcendent + Undefined = 0, + Animal = 1, + Neolithic = 2, + Medieval = 3, + Industrial = 4, + Spacer = 5, + Ultra = 6, + Transcendent = 7 } } diff --git a/Assembly-CSharp/RimWorld/TechLevelUtility.cs b/Assembly-CSharp/RimWorld/TechLevelUtility.cs index fb2ff253a..cc624d45f 100644 --- a/Assembly-CSharp/RimWorld/TechLevelUtility.cs +++ b/Assembly-CSharp/RimWorld/TechLevelUtility.cs @@ -10,24 +10,42 @@ public static string ToStringHuman(this TechLevel tl) switch (tl) { case TechLevel.Undefined: + { return "Undefined".Translate(); + } case TechLevel.Animal: + { return "TechLevel_Animal".Translate(); + } case TechLevel.Neolithic: + { return "TechLevel_Neolithic".Translate(); + } case TechLevel.Medieval: + { return "TechLevel_Medieval".Translate(); + } case TechLevel.Industrial: + { return "TechLevel_Industrial".Translate(); + } case TechLevel.Spacer: + { return "TechLevel_Spacer".Translate(); + } case TechLevel.Ultra: + { return "TechLevel_Ultra".Translate(); + } case TechLevel.Transcendent: + { return "TechLevel_Transcendent".Translate(); + } default: + { throw new NotImplementedException(); } + } } public static bool CanSpawnWithEquipmentFrom(this TechLevel pawnLevel, TechLevel gearLevel) @@ -39,33 +57,48 @@ public static bool CanSpawnWithEquipmentFrom(this TechLevel pawnLevel, TechLevel switch (pawnLevel) { case TechLevel.Undefined: + { return false; + } case TechLevel.Neolithic: - return gearLevel <= TechLevel.Neolithic; + { + return (int)gearLevel <= 2; + } case TechLevel.Medieval: - return gearLevel <= TechLevel.Medieval; + { + return (int)gearLevel <= 3; + } case TechLevel.Industrial: + { return gearLevel == TechLevel.Industrial; + } case TechLevel.Spacer: + { return gearLevel == TechLevel.Spacer || gearLevel == TechLevel.Industrial; + } case TechLevel.Ultra: + { return gearLevel == TechLevel.Ultra || gearLevel == TechLevel.Spacer; + } case TechLevel.Transcendent: + { return gearLevel == TechLevel.Transcendent; } - Log.Error(string.Concat(new object[] + default: { - "Unknown tech levels ", - pawnLevel, - ", ", - gearLevel - })); - return true; + Log.Error("Unknown tech levels " + pawnLevel + ", " + gearLevel); + return true; + } + } } public static bool IsNeolithicOrWorse(this TechLevel techLevel) { - return techLevel != TechLevel.Undefined && techLevel <= TechLevel.Neolithic; + if (techLevel == TechLevel.Undefined) + { + return false; + } + return (int)techLevel <= 2; } } } diff --git a/Assembly-CSharp/RimWorld/TemperatureMemory.cs b/Assembly-CSharp/RimWorld/TemperatureMemory.cs index 9518f96b2..dfddfeae8 100644 --- a/Assembly-CSharp/RimWorld/TemperatureMemory.cs +++ b/Assembly-CSharp/RimWorld/TemperatureMemory.cs @@ -1,4 +1,3 @@ -using System; using Verse; namespace RimWorld @@ -17,7 +16,11 @@ public bool GrowthSeasonOutdoorsNow { get { - return (this.noGrowUntilTick <= 0 || Find.TickManager.TicksGame >= this.noGrowUntilTick) && Find.TickManager.TicksGame < this.growthSeasonUntilTick; + if (this.noGrowUntilTick > 0 && Find.TickManager.TicksGame < this.noGrowUntilTick) + { + return false; + } + return Find.TickManager.TicksGame < this.growthSeasonUntilTick; } } @@ -28,11 +31,11 @@ public TemperatureMemory(Map map) public void GrowthSeasonMemoryTick() { - if (this.map.mapTemperature.OutdoorTemp > 0f && this.map.mapTemperature.OutdoorTemp < 58f) + if (this.map.mapTemperature.OutdoorTemp > 0.0 && this.map.mapTemperature.OutdoorTemp < 58.0) { this.growthSeasonUntilTick = Find.TickManager.TicksGame + 30000; } - else if (this.map.mapTemperature.OutdoorTemp < -2f) + else if (this.map.mapTemperature.OutdoorTemp < -2.0) { this.growthSeasonUntilTick = -1; this.noGrowUntilTick = Find.TickManager.TicksGame + 30000; diff --git a/Assembly-CSharp/RimWorld/TendUtility.cs b/Assembly-CSharp/RimWorld/TendUtility.cs index 124570554..f08ac1e98 100644 --- a/Assembly-CSharp/RimWorld/TendUtility.cs +++ b/Assembly-CSharp/RimWorld/TendUtility.cs @@ -24,67 +24,58 @@ public static class TendUtility public static void DoTend(Pawn doctor, Pawn patient, Medicine medicine) { - if (!patient.health.HasHediffsNeedingTend(false)) + if (patient.health.HasHediffsNeedingTend(false)) { - return; - } - if (medicine != null && medicine.Destroyed) - { - Log.Warning("Tried to use destroyed medicine."); - medicine = null; - } - float num = (medicine == null) ? 0.3f : medicine.def.GetStatValueAbstract(StatDefOf.MedicalPotency, null); - float num2; - if (doctor != null) - { - num2 = doctor.GetStatValue(StatDefOf.MedicalTendQuality, true); - } - else - { - num2 = 0.75f; - } - num2 *= num; - Building_Bed building_Bed = patient.CurrentBed(); - if (building_Bed != null) - { - num2 += building_Bed.GetStatValue(StatDefOf.MedicalTendQualityOffset, true); - } - if (doctor == patient) - { - num2 *= 0.7f; - } - num2 = Mathf.Clamp01(num2); - TendUtility.GetOptimalHediffsToTendWithSingleTreatment(patient, medicine != null, TendUtility.tmpHediffsToTend, null); - for (int i = 0; i < TendUtility.tmpHediffsToTend.Count; i++) - { - TendUtility.tmpHediffsToTend[i].Tended(num2, i); - } - if (doctor != null && doctor.Faction != null && patient.HostFaction == null && patient.Faction != null && patient.Faction != doctor.Faction) - { - patient.Faction.AffectGoodwillWith(doctor.Faction, 0.3f); - } - if (doctor != null && doctor.RaceProps.Humanlike && patient.RaceProps.Animal && RelationsUtility.TryDevelopBondRelation(doctor, patient, 0.004f) && doctor.Faction != null && doctor.Faction != patient.Faction) - { - InteractionWorker_RecruitAttempt.DoRecruit(doctor, patient, 1f, false); - } - patient.records.Increment(RecordDefOf.TimesTendedTo); - if (doctor != null) - { - doctor.records.Increment(RecordDefOf.TimesTendedOther); - } - if (medicine != null) - { - if ((patient.Spawned || (doctor != null && doctor.Spawned)) && num > ThingDefOf.Medicine.GetStatValueAbstract(StatDefOf.MedicalPotency, null)) + if (medicine != null && medicine.Destroyed) + { + Log.Warning("Tried to use destroyed medicine."); + medicine = null; + } + float num = (float)((medicine == null) ? 0.30000001192092896 : medicine.def.GetStatValueAbstract(StatDefOf.MedicalPotency, null)); + float num2 = (float)((doctor == null) ? 0.75 : doctor.GetStatValue(StatDefOf.MedicalTendQuality, true)); + num2 *= num; + Building_Bed building_Bed = patient.CurrentBed(); + if (building_Bed != null) + { + num2 += building_Bed.GetStatValue(StatDefOf.MedicalTendQualityOffset, true); + } + if (doctor == patient) + { + num2 = (float)(num2 * 0.699999988079071); + } + num2 = Mathf.Clamp01(num2); + TendUtility.GetOptimalHediffsToTendWithSingleTreatment(patient, medicine != null, TendUtility.tmpHediffsToTend, null); + for (int i = 0; i < TendUtility.tmpHediffsToTend.Count; i++) { - SoundDefOf.TechMedicineUsed.PlayOneShot(new TargetInfo(patient.Position, patient.Map, false)); + TendUtility.tmpHediffsToTend[i].Tended(num2, i); } - if (medicine.stackCount > 1) + if (doctor != null && doctor.Faction != null && patient.HostFaction == null && patient.Faction != null && patient.Faction != doctor.Faction) { - medicine.stackCount--; + patient.Faction.AffectGoodwillWith(doctor.Faction, 0.3f); } - else if (!medicine.Destroyed) + if (doctor != null && doctor.RaceProps.Humanlike && patient.RaceProps.Animal && RelationsUtility.TryDevelopBondRelation(doctor, patient, 0.004f) && doctor.Faction != null && doctor.Faction != patient.Faction) { - medicine.Destroy(DestroyMode.Vanish); + InteractionWorker_RecruitAttempt.DoRecruit(doctor, patient, 1f, false); + } + patient.records.Increment(RecordDefOf.TimesTendedTo); + if (doctor != null) + { + doctor.records.Increment(RecordDefOf.TimesTendedOther); + } + if (medicine != null) + { + if ((patient.Spawned || (doctor != null && doctor.Spawned)) && num > ThingDefOf.Medicine.GetStatValueAbstract(StatDefOf.MedicalPotency, null)) + { + SoundDefOf.TechMedicineUsed.PlayOneShot(new TargetInfo(patient.Position, patient.Map, false)); + } + if (medicine.stackCount > 1) + { + medicine.stackCount--; + } + else if (!medicine.Destroyed) + { + medicine.Destroy(DestroyMode.Vanish); + } } } } @@ -109,64 +100,62 @@ public static void GetOptimalHediffsToTendWithSingleTreatment(Pawn patient, bool } TendUtility.SortByTendPriority(TendUtility.tmpHediffs); } - if (!TendUtility.tmpHediffs.Any()) + if (TendUtility.tmpHediffs.Any()) { - return; - } - Hediff hediff = TendUtility.tmpHediffs[0]; - outHediffsToTend.Add(hediff); - HediffCompProperties_TendDuration hediffCompProperties_TendDuration = hediff.def.CompProps(); - if (hediffCompProperties_TendDuration != null && hediffCompProperties_TendDuration.tendAllAtOnce) - { - for (int j = 0; j < TendUtility.tmpHediffs.Count; j++) + Hediff hediff = TendUtility.tmpHediffs[0]; + outHediffsToTend.Add(hediff); + HediffCompProperties_TendDuration hediffCompProperties_TendDuration = hediff.def.CompProps(); + if (hediffCompProperties_TendDuration != null && hediffCompProperties_TendDuration.tendAllAtOnce) { - if (TendUtility.tmpHediffs[j] != hediff && TendUtility.tmpHediffs[j].def == hediff.def) + for (int j = 0; j < TendUtility.tmpHediffs.Count; j++) { - outHediffsToTend.Add(TendUtility.tmpHediffs[j]); + if (TendUtility.tmpHediffs[j] != hediff && TendUtility.tmpHediffs[j].def == hediff.def) + { + outHediffsToTend.Add(TendUtility.tmpHediffs[j]); + } } } - } - else if (hediff is Hediff_Injury && usingMedicine) - { - float num = hediff.Severity; - for (int k = 0; k < TendUtility.tmpHediffs.Count; k++) + else if (hediff is Hediff_Injury && usingMedicine) { - if (TendUtility.tmpHediffs[k] != hediff) + float num = hediff.Severity; + for (int k = 0; k < TendUtility.tmpHediffs.Count; k++) { - Hediff_Injury hediff_Injury = TendUtility.tmpHediffs[k] as Hediff_Injury; - if (hediff_Injury != null) + if (TendUtility.tmpHediffs[k] != hediff) { - float severity = hediff_Injury.Severity; - if (num + severity <= 20f) + Hediff_Injury hediff_Injury = TendUtility.tmpHediffs[k] as Hediff_Injury; + if (hediff_Injury != null) { - num += severity; - outHediffsToTend.Add(hediff_Injury); + float severity = hediff_Injury.Severity; + if (num + severity <= 20.0) + { + num += severity; + outHediffsToTend.Add(hediff_Injury); + } } } } } + TendUtility.tmpHediffs.Clear(); } - TendUtility.tmpHediffs.Clear(); } public static void SortByTendPriority(List hediffs) { - if (hediffs.Count <= 1) + if (hediffs.Count > 1) { - return; - } - TendUtility.tmpHediffsWithTendPriority.Clear(); - for (int i = 0; i < hediffs.Count; i++) - { - TendUtility.tmpHediffsWithTendPriority.Add(new Pair(hediffs[i], hediffs[i].TendPriority)); - } - TendUtility.tmpHediffsWithTendPriority.SortByDescending((Pair x) => x.Second, (Pair x) => x.First.Severity); - hediffs.Clear(); - for (int j = 0; j < TendUtility.tmpHediffsWithTendPriority.Count; j++) - { - hediffs.Add(TendUtility.tmpHediffsWithTendPriority[j].First); + TendUtility.tmpHediffsWithTendPriority.Clear(); + for (int i = 0; i < hediffs.Count; i++) + { + TendUtility.tmpHediffsWithTendPriority.Add(new Pair(hediffs[i], hediffs[i].TendPriority)); + } + TendUtility.tmpHediffsWithTendPriority.SortByDescending((Func, float>)((Pair x) => x.Second), (Func, float>)((Pair x) => x.First.Severity)); + hediffs.Clear(); + for (int j = 0; j < TendUtility.tmpHediffsWithTendPriority.Count; j++) + { + hediffs.Add(TendUtility.tmpHediffsWithTendPriority[j].First); + } + TendUtility.tmpHediffsWithTendPriority.Clear(); } - TendUtility.tmpHediffsWithTendPriority.Clear(); } } } diff --git a/Assembly-CSharp/RimWorld/TerrainDefGenerator_Stone.cs b/Assembly-CSharp/RimWorld/TerrainDefGenerator_Stone.cs index c3e807a2c..693405368 100644 --- a/Assembly-CSharp/RimWorld/TerrainDefGenerator_Stone.cs +++ b/Assembly-CSharp/RimWorld/TerrainDefGenerator_Stone.cs @@ -1,19 +1,77 @@ using System; using System.Collections.Generic; -using System.Diagnostics; +using System.Linq; using Verse; namespace RimWorld { internal static class TerrainDefGenerator_Stone { - [DebuggerHidden] public static IEnumerable ImpliedTerrainDefs() { - TerrainDefGenerator_Stone.c__Iterator71 c__Iterator = new TerrainDefGenerator_Stone.c__Iterator71(); - TerrainDefGenerator_Stone.c__Iterator71 expr_07 = c__Iterator; - expr_07.$PC = -2; - return expr_07; + int i = 0; + foreach (ThingDef item in from def in DefDatabase.AllDefs + where def.building != null && def.building.isNaturalRock && !def.building.isResourceRock + select def) + { + TerrainDef rough = new TerrainDef(); + TerrainDef hewn = new TerrainDef(); + TerrainDef smooth = new TerrainDef(); + rough.texturePath = "Terrain/Surfaces/RoughStone"; + rough.edgeType = TerrainDef.TerrainEdgeType.FadeRough; + rough.pathCost = 1; + StatUtility.SetStatValueInList(ref rough.statBases, StatDefOf.Beauty, -1f); + rough.scatterType = "Rocky"; + rough.affordances = new List(); + rough.affordances.Add(TerrainAffordance.Light); + rough.affordances.Add(TerrainAffordance.Heavy); + rough.affordances.Add(TerrainAffordance.SmoothableStone); + rough.fertility = 0f; + rough.renderPrecedence = 190 + i; + rough.defName = item.defName + "_Rough"; + rough.label = "RoughStoneTerrainLabel".Translate(item.label); + rough.description = "RoughStoneTerrainDesc".Translate(item.label); + rough.color = item.graphicData.color; + item.naturalTerrain = rough; + hewn.texturePath = "Terrain/Surfaces/RoughHewnRock"; + hewn.edgeType = TerrainDef.TerrainEdgeType.FadeRough; + hewn.pathCost = 1; + StatUtility.SetStatValueInList(ref hewn.statBases, StatDefOf.Beauty, -1f); + hewn.scatterType = "Rocky"; + hewn.affordances = new List(); + hewn.affordances.Add(TerrainAffordance.Light); + hewn.affordances.Add(TerrainAffordance.Heavy); + hewn.affordances.Add(TerrainAffordance.SmoothableStone); + hewn.fertility = 0f; + hewn.renderPrecedence = 50 + i; + hewn.defName = item.defName + "_RoughHewn"; + hewn.label = "RoughHewnStoneTerrainLabel".Translate(item.label); + hewn.description = "RoughHewnStoneTerrainDesc".Translate(item.label); + hewn.color = item.graphicData.color; + item.leaveTerrain = hewn; + smooth.texturePath = "Terrain/Surfaces/SmoothStone"; + smooth.edgeType = TerrainDef.TerrainEdgeType.FadeRough; + smooth.pathCost = 0; + StatUtility.SetStatValueInList(ref smooth.statBases, StatDefOf.Beauty, 3f); + smooth.scatterType = "Rocky"; + smooth.affordances = new List(); + smooth.affordances.Add(TerrainAffordance.Light); + smooth.affordances.Add(TerrainAffordance.Heavy); + smooth.affordances.Add(TerrainAffordance.SmoothHard); + smooth.fertility = 0f; + smooth.acceptTerrainSourceFilth = true; + smooth.renderPrecedence = 140 + i; + smooth.defName = item.defName + "_Smooth"; + smooth.label = "SmoothStoneTerrainLabel".Translate(item.label); + smooth.description = "SmoothStoneTerrainDesc".Translate(item.label); + smooth.color = item.graphicData.color; + rough.smoothedTerrain = smooth; + hewn.smoothedTerrain = smooth; + yield return rough; + yield return hewn; + yield return smooth; + i++; + } } } } diff --git a/Assembly-CSharp/RimWorld/TerrainDefOf.cs b/Assembly-CSharp/RimWorld/TerrainDefOf.cs index 55c207c8f..f52f0a670 100644 --- a/Assembly-CSharp/RimWorld/TerrainDefOf.cs +++ b/Assembly-CSharp/RimWorld/TerrainDefOf.cs @@ -1,4 +1,3 @@ -using System; using Verse; namespace RimWorld diff --git a/Assembly-CSharp/RimWorld/TerrainPatchMaker.cs b/Assembly-CSharp/RimWorld/TerrainPatchMaker.cs index fa22ffbeb..c9c8f3704 100644 --- a/Assembly-CSharp/RimWorld/TerrainPatchMaker.cs +++ b/Assembly-CSharp/RimWorld/TerrainPatchMaker.cs @@ -1,4 +1,3 @@ -using System; using System.Collections.Generic; using Verse; using Verse.Noise; @@ -25,7 +24,10 @@ public class TerrainPatchMaker private void Init(Map map) { this.noise = new Perlin((double)this.perlinFrequency, (double)this.perlinLacunarity, (double)this.perlinPersistence, this.perlinOctaves, Rand.Range(0, 2147483647), QualityMode.Medium); - NoiseDebugUI.RenderSize = new IntVec2(map.Size.x, map.Size.z); + IntVec3 size = map.Size; + int x = size.x; + IntVec3 size2 = map.Size; + NoiseDebugUI.RenderSize = new IntVec2(x, size2.z); NoiseDebugUI.StoreNoiseRender(this.noise, "TerrainPatchMaker " + this.thresholds[0].terrain.defName); this.currentlyInitializedForMap = map; } diff --git a/Assembly-CSharp/RimWorld/TerrainThreshold.cs b/Assembly-CSharp/RimWorld/TerrainThreshold.cs index 20ac9501c..99e6b39c8 100644 --- a/Assembly-CSharp/RimWorld/TerrainThreshold.cs +++ b/Assembly-CSharp/RimWorld/TerrainThreshold.cs @@ -1,4 +1,3 @@ -using System; using System.Collections.Generic; using Verse; diff --git a/Assembly-CSharp/RimWorld/TexCommand.cs b/Assembly-CSharp/RimWorld/TexCommand.cs index 0b06b4212..c415bda04 100644 --- a/Assembly-CSharp/RimWorld/TexCommand.cs +++ b/Assembly-CSharp/RimWorld/TexCommand.cs @@ -1,4 +1,3 @@ -using System; using UnityEngine; using Verse; diff --git a/Assembly-CSharp/RimWorld/TextGenerationPurpose.cs b/Assembly-CSharp/RimWorld/TextGenerationPurpose.cs index b89a9dd42..e0b1f0f5a 100644 --- a/Assembly-CSharp/RimWorld/TextGenerationPurpose.cs +++ b/Assembly-CSharp/RimWorld/TextGenerationPurpose.cs @@ -1,10 +1,8 @@ -using System; - namespace RimWorld { public enum TextGenerationPurpose { - ArtDescription, - ArtName + ArtDescription = 0, + ArtName = 1 } } diff --git a/Assembly-CSharp/RimWorld/ThingAmount.cs b/Assembly-CSharp/RimWorld/ThingAmount.cs index e091f2629..ad5b0d781 100644 --- a/Assembly-CSharp/RimWorld/ThingAmount.cs +++ b/Assembly-CSharp/RimWorld/ThingAmount.cs @@ -1,4 +1,3 @@ -using System; using System.Collections.Generic; using Verse; @@ -18,23 +17,18 @@ public ThingAmount(Thing thing, int count) public override string ToString() { - return string.Concat(new object[] - { - "(", - this.count, - "x ", - (this.thing == null) ? "null" : this.thing.ThingID, - ")" - }); + return "(" + this.count + "x " + ((this.thing == null) ? "null" : this.thing.ThingID) + ")"; } public static int CountUsed(List list, Thing thing) { for (int i = 0; i < list.Count; i++) { - if (list[i].thing == thing) + ThingAmount thingAmount = list[i]; + if (thingAmount.thing == thing) { - return list[i].count; + ThingAmount thingAmount2 = list[i]; + return thingAmount2.count; } } return 0; @@ -44,9 +38,14 @@ public static void AddToList(List list, Thing thing, int countToAdd { for (int i = 0; i < list.Count; i++) { - if (list[i].thing == thing) + ThingAmount thingAmount = list[i]; + if (thingAmount.thing == thing) { - list[i] = new ThingAmount(list[i].thing, list[i].count + countToAdd); + int index = i; + ThingAmount thingAmount2 = list[i]; + Thing obj = thingAmount2.thing; + ThingAmount thingAmount3 = list[i]; + list[index] = new ThingAmount(obj, thingAmount3.count + countToAdd); return; } } diff --git a/Assembly-CSharp/RimWorld/ThingCategoryDefOf.cs b/Assembly-CSharp/RimWorld/ThingCategoryDefOf.cs index e24cfb377..f4e68c32a 100644 --- a/Assembly-CSharp/RimWorld/ThingCategoryDefOf.cs +++ b/Assembly-CSharp/RimWorld/ThingCategoryDefOf.cs @@ -1,4 +1,3 @@ -using System; using Verse; namespace RimWorld diff --git a/Assembly-CSharp/RimWorld/ThingDefGenerator_Buildings.cs b/Assembly-CSharp/RimWorld/ThingDefGenerator_Buildings.cs index 1b6325012..dbef4e59f 100644 --- a/Assembly-CSharp/RimWorld/ThingDefGenerator_Buildings.cs +++ b/Assembly-CSharp/RimWorld/ThingDefGenerator_Buildings.cs @@ -1,6 +1,6 @@ using System; using System.Collections.Generic; -using System.Diagnostics; +using System.Linq; using UnityEngine; using Verse; @@ -18,52 +18,70 @@ public static class ThingDefGenerator_Buildings private static Color BlueprintColor = new Color(0.5f, 0.5f, 1f, 0.35f); - [DebuggerHidden] public static IEnumerable ImpliedBlueprintAndFrameDefs() { - ThingDefGenerator_Buildings.c__Iterator72 c__Iterator = new ThingDefGenerator_Buildings.c__Iterator72(); - ThingDefGenerator_Buildings.c__Iterator72 expr_07 = c__Iterator; - expr_07.$PC = -2; - return expr_07; + List.Enumerator enumerator = DefDatabase.AllDefs.ToList().GetEnumerator(); + try + { + while (enumerator.MoveNext()) + { + ThingDef def = enumerator.Current; + ThingDef blueprint = null; + if (def.designationCategory != null) + { + blueprint = ThingDefGenerator_Buildings.NewBlueprintDef_Thing(def, false, null); + yield return blueprint; + yield return ThingDefGenerator_Buildings.NewFrameDef_Thing(def); + } + if (def.Minifiable) + { + yield return ThingDefGenerator_Buildings.NewBlueprintDef_Thing(def, true, blueprint); + } + } + } + finally + { + ((IDisposable)(object)enumerator).Dispose(); + } + foreach (TerrainDef allDef in DefDatabase.AllDefs) + { + if (allDef.designationCategory != null) + { + yield return ThingDefGenerator_Buildings.NewBlueprintDef_Terrain(allDef); + yield return ThingDefGenerator_Buildings.NewFrameDef_Terrain(allDef); + } + } } private static ThingDef BaseBlueprintDef() { - return new ThingDef - { - category = ThingCategory.Ethereal, - label = "Unspecified blueprint", - altitudeLayer = AltitudeLayer.Blueprint, - useHitPoints = false, - selectable = true, - seeThroughFog = true, - comps = - { - new CompProperties_Forbiddable() - }, - drawerType = DrawerType.MapMeshAndRealTime - }; + ThingDef thingDef = new ThingDef(); + thingDef.category = ThingCategory.Ethereal; + thingDef.label = "Unspecified blueprint"; + thingDef.altitudeLayer = AltitudeLayer.Blueprint; + thingDef.useHitPoints = false; + thingDef.selectable = true; + thingDef.seeThroughFog = true; + thingDef.comps.Add(new CompProperties_Forbiddable()); + thingDef.drawerType = DrawerType.MapMeshAndRealTime; + return thingDef; } private static ThingDef BaseFrameDef() { - return new ThingDef - { - isFrame = true, - category = ThingCategory.Building, - label = "Unspecified building frame", - thingClass = typeof(Frame), - altitudeLayer = AltitudeLayer.Building, - useHitPoints = true, - selectable = true, - building = new BuildingProperties(), - comps = - { - new CompProperties_Forbiddable() - }, - scatterableOnMapGen = false, - leaveResourcesWhenKilled = true - }; + ThingDef thingDef = new ThingDef(); + thingDef.isFrame = true; + thingDef.category = ThingCategory.Building; + thingDef.label = "Unspecified building frame"; + thingDef.thingClass = typeof(Frame); + thingDef.altitudeLayer = AltitudeLayer.Building; + thingDef.useHitPoints = true; + thingDef.selectable = true; + thingDef.building = new BuildingProperties(); + thingDef.comps.Add(new CompProperties_Forbiddable()); + thingDef.scatterableOnMapGen = false; + thingDef.leaveResourcesWhenKilled = true; + return thingDef; } private static ThingDef NewBlueprintDef_Thing(ThingDef def, bool isInstallBlueprint, ThingDef normalBlueprint = null) @@ -79,8 +97,8 @@ private static ThingDef NewBlueprintDef_Thing(ThingDef def, bool isInstallBluepr } if (isInstallBlueprint) { - ThingDef expr_72 = thingDef; - expr_72.defName += ThingDefGenerator_Buildings.InstallBlueprintDefNameSuffix; + ThingDef obj = thingDef; + obj.defName += ThingDefGenerator_Buildings.InstallBlueprintDefNameSuffix; } if (isInstallBlueprint && normalBlueprint != null) { @@ -151,13 +169,13 @@ private static ThingDef NewFrameDef_Thing(ThingDef def) thingDef.defName = def.defName + ThingDefGenerator_Buildings.BuildingFrameDefNameSuffix; thingDef.label = def.label + "FrameLabelExtra".Translate(); thingDef.size = def.size; - thingDef.SetStatBaseValue(StatDefOf.MaxHitPoints, (float)def.BaseMaxHitPoints * 0.25f); + thingDef.SetStatBaseValue(StatDefOf.MaxHitPoints, (float)((float)def.BaseMaxHitPoints * 0.25)); thingDef.SetStatBaseValue(StatDefOf.Beauty, -8f); thingDef.fillPercent = 0.2f; thingDef.pathCost = 10; thingDef.description = def.description; thingDef.passability = def.passability; - if (thingDef.passability > Traversability.PassThroughOnly) + if ((int)thingDef.passability > 1) { thingDef.passability = Traversability.PassThroughOnly; } diff --git a/Assembly-CSharp/RimWorld/ThingDefGenerator_Corpses.cs b/Assembly-CSharp/RimWorld/ThingDefGenerator_Corpses.cs index 19da290ad..702459b1e 100644 --- a/Assembly-CSharp/RimWorld/ThingDefGenerator_Corpses.cs +++ b/Assembly-CSharp/RimWorld/ThingDefGenerator_Corpses.cs @@ -1,6 +1,6 @@ using System; using System.Collections.Generic; -using System.Diagnostics; +using System.Linq; using Verse; namespace RimWorld @@ -15,13 +15,107 @@ public static class ThingDefGenerator_Corpses private const float DessicatedDamagePerDay = 0.7f; - [DebuggerHidden] public static IEnumerable ImpliedCorpseDefs() { - ThingDefGenerator_Corpses.c__Iterator73 c__Iterator = new ThingDefGenerator_Corpses.c__Iterator73(); - ThingDefGenerator_Corpses.c__Iterator73 expr_07 = c__Iterator; - expr_07.$PC = -2; - return expr_07; + List.Enumerator enumerator = DefDatabase.AllDefs.ToList().GetEnumerator(); + try + { + while (enumerator.MoveNext()) + { + ThingDef raceDef = enumerator.Current; + if (raceDef.category == ThingCategory.Pawn) + { + ThingDef d = new ThingDef + { + category = ThingCategory.Item, + thingClass = typeof(Corpse), + selectable = true, + tickerType = TickerType.Rare, + altitudeLayer = AltitudeLayer.ItemImportant, + scatterableOnMapGen = false + }; + d.SetStatBaseValue(StatDefOf.Beauty, -150f); + d.SetStatBaseValue(StatDefOf.DeteriorationRate, 2f); + d.alwaysHaulable = true; + d.soundDrop = SoundDef.Named("Corpse_Drop"); + d.pathCost = 15; + d.socialPropernessMatters = false; + d.tradeability = Tradeability.Never; + d.inspectorTabs = new List(); + d.inspectorTabs.Add(typeof(ITab_Pawn_Health)); + d.inspectorTabs.Add(typeof(ITab_Pawn_Character)); + d.inspectorTabs.Add(typeof(ITab_Pawn_Gear)); + d.inspectorTabs.Add(typeof(ITab_Pawn_Social)); + d.comps.Add(new CompProperties_Forbiddable()); + d.recipes = new List(); + if (raceDef.race.IsMechanoid) + { + d.recipes.Add(RecipeDefOf.RemoveMechanoidBodyPart); + } + else + { + d.recipes.Add(RecipeDefOf.RemoveBodyPart); + } + d.defName = raceDef.defName + "_Corpse"; + d.label = "CorpseLabel".Translate(raceDef.label); + d.description = "CorpseDesc".Translate(raceDef.label); + d.soundImpactDefault = raceDef.soundImpactDefault; + d.SetStatBaseValue(StatDefOf.Flammability, raceDef.GetStatValueAbstract(StatDefOf.Flammability, null)); + d.SetStatBaseValue(StatDefOf.MaxHitPoints, (float)raceDef.BaseMaxHitPoints); + d.SetStatBaseValue(StatDefOf.Mass, raceDef.statBases.GetStatOffsetFromList(StatDefOf.Mass)); + d.ingestible = new IngestibleProperties(); + IngestibleProperties ing = d.ingestible; + ing.foodType = FoodTypeFlags.Corpse; + ing.sourceDef = raceDef; + ing.preferability = FoodPreferability.DesperateOnly; + DirectXmlCrossRefLoader.RegisterObjectWantsCrossRef(ing, "tasteThought", ThoughtDefOf.AteCorpse.defName); + ing.nutrition = 1f; + ing.maxNumToIngestAtOnce = 1; + ing.ingestEffect = EffecterDefOf.EatMeat; + ing.ingestSound = SoundDefOf.RawMeat_Eat; + ing.specialThoughtDirect = raceDef.race.FleshType.ateDirect; + if (raceDef.race.IsFlesh) + { + CompProperties_Rottable rottable = new CompProperties_Rottable + { + daysToRotStart = 2.5f, + daysToDessicated = 5f, + rotDamagePerDay = 2f, + dessicatedDamagePerDay = 0.7f + }; + d.comps.Add(rottable); + CompProperties_SpawnerFilth corpseBileSpawner = new CompProperties_SpawnerFilth + { + filthDef = ThingDefOf.FilthCorpseBile, + spawnCountOnSpawn = 0, + spawnMtbHours = 0f, + spawnRadius = 0.1f, + spawnEveryDays = 1f, + requiredRotStage = new RotStage?(RotStage.Rotting) + }; + d.comps.Add(corpseBileSpawner); + } + if (d.thingCategories == null) + { + d.thingCategories = new List(); + } + if (raceDef.race.Humanlike) + { + DirectXmlCrossRefLoader.RegisterListWantsCrossRef(d.thingCategories, ThingCategoryDefOf.CorpsesHumanlike.defName); + } + else + { + DirectXmlCrossRefLoader.RegisterListWantsCrossRef(d.thingCategories, raceDef.race.FleshType.corpseCategory.defName); + } + raceDef.race.corpseDef = d; + yield return d; + } + } + } + finally + { + ((IDisposable)(object)enumerator).Dispose(); + } } } } diff --git a/Assembly-CSharp/RimWorld/ThingDefGenerator_Leather.cs b/Assembly-CSharp/RimWorld/ThingDefGenerator_Leather.cs index 003c8d459..dcd05f237 100644 --- a/Assembly-CSharp/RimWorld/ThingDefGenerator_Leather.cs +++ b/Assembly-CSharp/RimWorld/ThingDefGenerator_Leather.cs @@ -1,6 +1,6 @@ using System; using System.Collections.Generic; -using System.Diagnostics; +using System.Linq; using Verse; namespace RimWorld @@ -13,16 +13,107 @@ public static class ThingDefGenerator_Leather private static bool GeneratesLeather(ThingDef sourceDef) { - return sourceDef.category == ThingCategory.Pawn && sourceDef.GetStatValueAbstract(StatDefOf.LeatherAmount, null) > 0f; + return sourceDef.category == ThingCategory.Pawn && sourceDef.GetStatValueAbstract(StatDefOf.LeatherAmount, null) > 0.0; } - [DebuggerHidden] public static IEnumerable ImpliedLeatherDefs() { - ThingDefGenerator_Leather.c__Iterator74 c__Iterator = new ThingDefGenerator_Leather.c__Iterator74(); - ThingDefGenerator_Leather.c__Iterator74 expr_07 = c__Iterator; - expr_07.$PC = -2; - return expr_07; + int numLeathers = (from def in DefDatabase.AllDefs + where ThingDefGenerator_Leather.GeneratesLeather(def) + select def).Count(); + float eachLeatherCommonality = (float)(1.0 / (float)numLeathers); + List.Enumerator enumerator = DefDatabase.AllDefs.ToList().GetEnumerator(); + try + { + while (enumerator.MoveNext()) + { + ThingDef sourceDef = enumerator.Current; + if (ThingDefGenerator_Leather.GeneratesLeather(sourceDef) && sourceDef.race.useLeatherFrom == null) + { + ThingDef d = new ThingDef + { + resourceReadoutPriority = ResourceCountPriority.Middle, + category = ThingCategory.Item, + thingClass = typeof(ThingWithComps), + graphicData = new GraphicData(), + graphicData = + { + graphicClass = typeof(Graphic_Single) + }, + useHitPoints = true, + selectable = true + }; + d.SetStatBaseValue(StatDefOf.MaxHitPoints, 100f); + d.altitudeLayer = AltitudeLayer.Item; + d.stackLimit = 75; + d.comps.Add(new CompProperties_Forbiddable()); + d.SetStatBaseValue(StatDefOf.Beauty, -20f); + d.SetStatBaseValue(StatDefOf.DeteriorationRate, 2f); + d.alwaysHaulable = true; + d.drawGUIOverlay = true; + d.rotatable = false; + d.pathCost = 15; + d.category = ThingCategory.Item; + d.description = "LeatherDesc".Translate(sourceDef.label); + d.useHitPoints = true; + d.SetStatBaseValue(StatDefOf.MaxHitPoints, 60f); + d.SetStatBaseValue(StatDefOf.MarketValue, (float)(sourceDef.race.leatherMarketValueFactor * 2.0999999046325684)); + d.SetStatBaseValue(StatDefOf.Mass, 0.03f); + d.SetStatBaseValue(StatDefOf.Flammability, 1f); + if (d.thingCategories == null) + { + d.thingCategories = new List(); + } + DirectXmlCrossRefLoader.RegisterListWantsCrossRef(d.thingCategories, "Leathers"); + d.graphicData.texPath = "Things/Item/Resource/Cloth"; + d.stuffProps = new StuffProperties(); + DirectXmlCrossRefLoader.RegisterListWantsCrossRef(d.stuffProps.categories, "Leathery"); + StatUtility.SetStatValueInList(ref d.stuffProps.statFactors, StatDefOf.MarketValue, 1.3f); + StatUtility.SetStatValueInList(ref d.stuffProps.statFactors, StatDefOf.ArmorRating_Blunt, 1.5f); + StatUtility.SetStatValueInList(ref d.stuffProps.statFactors, StatDefOf.ArmorRating_Sharp, 1.5f); + StatUtility.SetStatValueInList(ref d.stuffProps.statFactors, StatDefOf.ArmorRating_Heat, 1.7f); + StatUtility.SetStatValueInList(ref d.stuffProps.statFactors, StatDefOf.ArmorRating_Electric, 4f); + d.defName = sourceDef.defName + "_Leather"; + if (!sourceDef.race.leatherLabel.NullOrEmpty()) + { + d.label = sourceDef.race.leatherLabel; + } + else + { + d.label = "LeatherLabel".Translate(sourceDef.label); + } + d.stuffProps.color = sourceDef.race.leatherColor; + d.graphicData.color = sourceDef.race.leatherColor; + d.graphicData.colorTwo = sourceDef.race.leatherColor; + d.stuffProps.commonality = (float)(1.2000000476837158 * eachLeatherCommonality * sourceDef.race.leatherCommonalityFactor); + StatUtility.SetStatValueInList(ref d.stuffProps.statFactors, StatDefOf.Insulation_Cold, sourceDef.race.leatherInsulation); + StatUtility.SetStatValueInList(ref d.stuffProps.statFactors, StatDefOf.Insulation_Heat, sourceDef.race.leatherInsulation); + List sfos = sourceDef.race.leatherStatFactors; + if (sfos != null) + { + List.Enumerator enumerator2 = sfos.GetEnumerator(); + try + { + while (enumerator2.MoveNext()) + { + StatModifier fo = enumerator2.Current; + StatUtility.SetStatValueInList(ref d.stuffProps.statFactors, fo.stat, fo.value); + } + } + finally + { + ((IDisposable)(object)enumerator2).Dispose(); + } + } + sourceDef.race.leatherDef = d; + yield return d; + } + } + } + finally + { + ((IDisposable)(object)enumerator).Dispose(); + } } } } diff --git a/Assembly-CSharp/RimWorld/ThingDefGenerator_Meat.cs b/Assembly-CSharp/RimWorld/ThingDefGenerator_Meat.cs index 3b514f17e..fb5b2985f 100644 --- a/Assembly-CSharp/RimWorld/ThingDefGenerator_Meat.cs +++ b/Assembly-CSharp/RimWorld/ThingDefGenerator_Meat.cs @@ -1,19 +1,117 @@ using System; using System.Collections.Generic; -using System.Diagnostics; +using System.Linq; using Verse; namespace RimWorld { public static class ThingDefGenerator_Meat { - [DebuggerHidden] public static IEnumerable ImpliedMeatDefs() { - ThingDefGenerator_Meat.c__Iterator75 c__Iterator = new ThingDefGenerator_Meat.c__Iterator75(); - ThingDefGenerator_Meat.c__Iterator75 expr_07 = c__Iterator; - expr_07.$PC = -2; - return expr_07; + List.Enumerator enumerator = DefDatabase.AllDefs.ToList().GetEnumerator(); + try + { + while (enumerator.MoveNext()) + { + ThingDef sourceDef = enumerator.Current; + if (sourceDef.category == ThingCategory.Pawn && sourceDef.race.useMeatFrom == null) + { + if (!sourceDef.race.IsFlesh) + { + DirectXmlCrossRefLoader.RegisterObjectWantsCrossRef(sourceDef.race, "meatDef", "Steel"); + } + else + { + ThingDef d = new ThingDef + { + resourceReadoutPriority = ResourceCountPriority.Middle, + category = ThingCategory.Item, + thingClass = typeof(ThingWithComps), + graphicData = new GraphicData(), + graphicData = + { + graphicClass = typeof(Graphic_Single) + }, + useHitPoints = true, + selectable = true + }; + d.SetStatBaseValue(StatDefOf.MaxHitPoints, 100f); + d.altitudeLayer = AltitudeLayer.Item; + d.stackLimit = 75; + d.comps.Add(new CompProperties_Forbiddable()); + CompProperties_Rottable rotProps = new CompProperties_Rottable + { + daysToRotStart = 2f, + rotDestroys = true + }; + d.comps.Add(rotProps); + d.comps.Add(new CompProperties_FoodPoisoningChance()); + d.tickerType = TickerType.Rare; + d.SetStatBaseValue(StatDefOf.Beauty, -20f); + d.alwaysHaulable = true; + d.rotatable = false; + d.pathCost = 15; + d.drawGUIOverlay = true; + d.socialPropernessMatters = true; + d.category = ThingCategory.Item; + d.description = "MeatDesc".Translate(sourceDef.label); + d.useHitPoints = true; + d.SetStatBaseValue(StatDefOf.MaxHitPoints, 60f); + d.SetStatBaseValue(StatDefOf.DeteriorationRate, 6f); + d.SetStatBaseValue(StatDefOf.Mass, 0.03f); + d.SetStatBaseValue(StatDefOf.Flammability, 0.5f); + d.BaseMarketValue = ThingDefGenerator_Meat.GetMeatMarketValue(sourceDef); + if (d.thingCategories == null) + { + d.thingCategories = new List(); + } + DirectXmlCrossRefLoader.RegisterListWantsCrossRef(d.thingCategories, "MeatRaw"); + d.ingestible = new IngestibleProperties(); + d.ingestible.foodType = FoodTypeFlags.Meat; + d.ingestible.preferability = FoodPreferability.RawBad; + DirectXmlCrossRefLoader.RegisterObjectWantsCrossRef(d.ingestible, "tasteThought", ThoughtDefOf.AteRawFood.defName); + d.ingestible.nutrition = 0.05f; + d.ingestible.ingestEffect = EffecterDefOf.EatMeat; + d.ingestible.ingestSound = SoundDef.Named("RawMeat_Eat"); + d.ingestible.specialThoughtDirect = sourceDef.race.FleshType.ateDirect; + d.ingestible.specialThoughtAsIngredient = sourceDef.race.FleshType.ateAsIngredient; + if (sourceDef.race.Humanlike) + { + d.graphicData.texPath = "Things/Item/Resource/MeatFoodRaw/MeatHuman"; + } + else + { + if (sourceDef.race.baseBodySize < 0.699999988079071) + { + d.graphicData.texPath = "Things/Item/Resource/MeatFoodRaw/MeatSmall"; + } + else + { + d.graphicData.texPath = "Things/Item/Resource/MeatFoodRaw/MeatBig"; + } + d.graphicData.color = sourceDef.race.meatColor; + } + d.defName = sourceDef.defName + "_Meat"; + if (sourceDef.race.meatLabel.NullOrEmpty()) + { + d.label = "MeatLabel".Translate(sourceDef.label); + } + else + { + d.label = sourceDef.race.meatLabel; + } + d.ingestible.sourceDef = sourceDef; + sourceDef.race.meatDef = d; + yield return d; + } + } + } + } + finally + { + ((IDisposable)(object)enumerator).Dispose(); + } } private static float GetMeatMarketValue(ThingDef sourceDef) diff --git a/Assembly-CSharp/RimWorld/ThingDefOf.cs b/Assembly-CSharp/RimWorld/ThingDefOf.cs index bc8f0659a..7b4c69007 100644 --- a/Assembly-CSharp/RimWorld/ThingDefOf.cs +++ b/Assembly-CSharp/RimWorld/ThingDefOf.cs @@ -1,4 +1,3 @@ -using System; using Verse; namespace RimWorld diff --git a/Assembly-CSharp/RimWorld/ThingSelectionUtility.cs b/Assembly-CSharp/RimWorld/ThingSelectionUtility.cs index 537a0f961..cd1d7c625 100644 --- a/Assembly-CSharp/RimWorld/ThingSelectionUtility.cs +++ b/Assembly-CSharp/RimWorld/ThingSelectionUtility.cs @@ -1,7 +1,6 @@ using RimWorld.Planet; using System; using System.Collections.Generic; -using System.Diagnostics; using System.Linq; using UnityEngine; using Verse; @@ -47,26 +46,47 @@ public static bool SelectableByHotkey(Thing t) return t.def.selectable && t.Spawned; } - [DebuggerHidden] public static IEnumerable MultiSelectableThingsInScreenRectDistinct(Rect rect) { - ThingSelectionUtility.c__Iterator1A0 c__Iterator1A = new ThingSelectionUtility.c__Iterator1A0(); - c__Iterator1A.rect = rect; - c__Iterator1A.<$>rect = rect; - ThingSelectionUtility.c__Iterator1A0 expr_15 = c__Iterator1A; - expr_15.$PC = -2; - return expr_15; + CellRect mapRect = ThingSelectionUtility.GetMapRect(rect); + ThingSelectionUtility.yieldedThings.Clear(); + foreach (IntVec3 item in mapRect) + { + if (item.InBounds(Find.VisibleMap)) + { + List cellThings = Find.VisibleMap.thingGrid.ThingsListAt(item); + if (cellThings != null) + { + for (int i = 0; i < cellThings.Count; i++) + { + Thing t = cellThings[i]; + if (ThingSelectionUtility.SelectableByMapClick(t) && !t.def.neverMultiSelect && !ThingSelectionUtility.yieldedThings.Contains(t)) + { + yield return t; + ThingSelectionUtility.yieldedThings.Add(t); + } + } + } + } + } } - [DebuggerHidden] public static IEnumerable MultiSelectableZonesInScreenRectDistinct(Rect rect) { - ThingSelectionUtility.c__Iterator1A1 c__Iterator1A = new ThingSelectionUtility.c__Iterator1A1(); - c__Iterator1A.rect = rect; - c__Iterator1A.<$>rect = rect; - ThingSelectionUtility.c__Iterator1A1 expr_15 = c__Iterator1A; - expr_15.$PC = -2; - return expr_15; + CellRect mapRect = ThingSelectionUtility.GetMapRect(rect); + ThingSelectionUtility.yieldedZones.Clear(); + foreach (IntVec3 item in mapRect) + { + if (item.InBounds(Find.VisibleMap)) + { + Zone zone = item.GetZone(Find.VisibleMap); + if (zone != null && zone.IsMultiselectable && !ThingSelectionUtility.yieldedZones.Contains(zone)) + { + yield return zone; + ThingSelectionUtility.yieldedZones.Add(zone); + } + } + } } private static CellRect GetMapRect(Rect rect) @@ -88,58 +108,68 @@ public static void SelectNextColonist() { ThingSelectionUtility.tmpColonists.Clear(); ThingSelectionUtility.tmpColonists.AddRange(Find.ColonistBar.GetColonistsInOrder().Where(new Func(ThingSelectionUtility.SelectableByHotkey))); - if (ThingSelectionUtility.tmpColonists.Count == 0) + if (ThingSelectionUtility.tmpColonists.Count != 0) { - return; - } - bool worldRenderedNow = WorldRendererUtility.WorldRenderedNow; - int num = -1; - for (int i = ThingSelectionUtility.tmpColonists.Count - 1; i >= 0; i--) - { - if ((!worldRenderedNow && Find.Selector.IsSelected(ThingSelectionUtility.tmpColonists[i])) || (worldRenderedNow && ThingSelectionUtility.tmpColonists[i].IsCaravanMember() && Find.WorldSelector.IsSelected(ThingSelectionUtility.tmpColonists[i].GetCaravan()))) + bool worldRenderedNow = WorldRendererUtility.WorldRenderedNow; + int num = -1; + int num2 = ThingSelectionUtility.tmpColonists.Count - 1; + while (num2 >= 0) { - num = i; + if (!worldRenderedNow && Find.Selector.IsSelected(ThingSelectionUtility.tmpColonists[num2])) + { + goto IL_00b3; + } + if (worldRenderedNow && ThingSelectionUtility.tmpColonists[num2].IsCaravanMember() && Find.WorldSelector.IsSelected(ThingSelectionUtility.tmpColonists[num2].GetCaravan())) + goto IL_00b3; + num2--; + continue; + IL_00b3: + num = num2; break; } + if (num == -1) + { + CameraJumper.TryJumpAndSelect((Thing)ThingSelectionUtility.tmpColonists[0]); + } + else + { + CameraJumper.TryJumpAndSelect((Thing)ThingSelectionUtility.tmpColonists[(num + 1) % ThingSelectionUtility.tmpColonists.Count]); + } + ThingSelectionUtility.tmpColonists.Clear(); } - if (num == -1) - { - CameraJumper.TryJumpAndSelect(ThingSelectionUtility.tmpColonists[0]); - } - else - { - CameraJumper.TryJumpAndSelect(ThingSelectionUtility.tmpColonists[(num + 1) % ThingSelectionUtility.tmpColonists.Count]); - } - ThingSelectionUtility.tmpColonists.Clear(); } public static void SelectPreviousColonist() { ThingSelectionUtility.tmpColonists.Clear(); ThingSelectionUtility.tmpColonists.AddRange(Find.ColonistBar.GetColonistsInOrder().Where(new Func(ThingSelectionUtility.SelectableByHotkey))); - if (ThingSelectionUtility.tmpColonists.Count == 0) + if (ThingSelectionUtility.tmpColonists.Count != 0) { - return; - } - bool worldRenderedNow = WorldRendererUtility.WorldRenderedNow; - int num = -1; - for (int i = 0; i < ThingSelectionUtility.tmpColonists.Count; i++) - { - if ((!worldRenderedNow && Find.Selector.IsSelected(ThingSelectionUtility.tmpColonists[i])) || (worldRenderedNow && ThingSelectionUtility.tmpColonists[i].IsCaravanMember() && Find.WorldSelector.IsSelected(ThingSelectionUtility.tmpColonists[i].GetCaravan()))) + bool worldRenderedNow = WorldRendererUtility.WorldRenderedNow; + int num = -1; + for (int i = 0; i < ThingSelectionUtility.tmpColonists.Count; i++) { + if (!worldRenderedNow && Find.Selector.IsSelected(ThingSelectionUtility.tmpColonists[i])) + { + goto IL_00a8; + } + if (worldRenderedNow && ThingSelectionUtility.tmpColonists[i].IsCaravanMember() && Find.WorldSelector.IsSelected(ThingSelectionUtility.tmpColonists[i].GetCaravan())) + goto IL_00a8; + continue; + IL_00a8: num = i; break; } + if (num == -1) + { + CameraJumper.TryJumpAndSelect((Thing)ThingSelectionUtility.tmpColonists[ThingSelectionUtility.tmpColonists.Count - 1]); + } + else + { + CameraJumper.TryJumpAndSelect((Thing)ThingSelectionUtility.tmpColonists[GenMath.PositiveMod(num - 1, ThingSelectionUtility.tmpColonists.Count)]); + } + ThingSelectionUtility.tmpColonists.Clear(); } - if (num == -1) - { - CameraJumper.TryJumpAndSelect(ThingSelectionUtility.tmpColonists[ThingSelectionUtility.tmpColonists.Count - 1]); - } - else - { - CameraJumper.TryJumpAndSelect(ThingSelectionUtility.tmpColonists[GenMath.PositiveMod(num - 1, ThingSelectionUtility.tmpColonists.Count)]); - } - ThingSelectionUtility.tmpColonists.Clear(); } } } diff --git a/Assembly-CSharp/RimWorld/ThingStuffPair.cs b/Assembly-CSharp/RimWorld/ThingStuffPair.cs index e44001db5..baf2137eb 100644 --- a/Assembly-CSharp/RimWorld/ThingStuffPair.cs +++ b/Assembly-CSharp/RimWorld/ThingStuffPair.cs @@ -45,7 +45,7 @@ public float Commonality } if (PawnWeaponGenerator.IsDerpWeapon(this.thing, this.stuff)) { - num *= 0.01f; + num = (float)(num * 0.0099999997764825821); } return num; } @@ -78,19 +78,19 @@ public static List AllWith(Predicate thingValidator) IEnumerable enumerable = from st in DefDatabase.AllDefs where st.IsStuff && st.stuffProps.CanMake(thingDef) select st; - int num = enumerable.Count(); - float num2 = enumerable.Average((ThingDef st) => st.stuffProps.commonality); - float num3 = 1f / (float)num / num2; - foreach (ThingDef current in enumerable) + int num = enumerable.Count(); + float num2 = enumerable.Average((Func)((ThingDef st) => st.stuffProps.commonality)); + float num3 = (float)(1.0 / (float)num / num2); + foreach (ThingDef item in enumerable) { - list.Add(new ThingStuffPair(thingDef, current, num3)); + list.Add(new ThingStuffPair(thingDef, item, num3)); } } } } return (from p in list orderby p.Price descending - select p).ToList(); + select p).ToList(); } public override string ToString() @@ -99,23 +99,8 @@ public override string ToString() { return "(null)"; } - string text; - if (this.stuff == null) - { - text = this.thing.label; - } - else - { - text = this.thing.label + " " + this.stuff.LabelAsStuff; - } - return string.Concat(new string[] - { - text, - " $", - this.Price.ToString("F0"), - " c=", - this.Commonality.ToString("F4") - }); + string text = (this.stuff != null) ? (this.thing.label + " " + this.stuff.LabelAsStuff) : this.thing.label; + return text + " $" + this.Price.ToString("F0") + " c=" + this.Commonality.ToString("F4"); } } } diff --git a/Assembly-CSharp/RimWorld/ThinkNode_Conditional.cs b/Assembly-CSharp/RimWorld/ThinkNode_Conditional.cs index 0381e87aa..ae183f1f8 100644 --- a/Assembly-CSharp/RimWorld/ThinkNode_Conditional.cs +++ b/Assembly-CSharp/RimWorld/ThinkNode_Conditional.cs @@ -1,4 +1,3 @@ -using System; using Verse; using Verse.AI; diff --git a/Assembly-CSharp/RimWorld/ThinkNode_ConditionalAnimalWrongSeason.cs b/Assembly-CSharp/RimWorld/ThinkNode_ConditionalAnimalWrongSeason.cs index 8fe5ca65f..33940d7f1 100644 --- a/Assembly-CSharp/RimWorld/ThinkNode_ConditionalAnimalWrongSeason.cs +++ b/Assembly-CSharp/RimWorld/ThinkNode_ConditionalAnimalWrongSeason.cs @@ -1,4 +1,3 @@ -using System; using Verse; namespace RimWorld diff --git a/Assembly-CSharp/RimWorld/ThinkNode_ConditionalAnyAutoJoinableCaravan.cs b/Assembly-CSharp/RimWorld/ThinkNode_ConditionalAnyAutoJoinableCaravan.cs index cfbcfc075..e6cb92055 100644 --- a/Assembly-CSharp/RimWorld/ThinkNode_ConditionalAnyAutoJoinableCaravan.cs +++ b/Assembly-CSharp/RimWorld/ThinkNode_ConditionalAnyAutoJoinableCaravan.cs @@ -1,5 +1,4 @@ using RimWorld.Planet; -using System; using Verse; namespace RimWorld diff --git a/Assembly-CSharp/RimWorld/ThinkNode_ConditionalAnyColonistTryingToExitMap.cs b/Assembly-CSharp/RimWorld/ThinkNode_ConditionalAnyColonistTryingToExitMap.cs index 5f50e9f53..86ea83af4 100644 --- a/Assembly-CSharp/RimWorld/ThinkNode_ConditionalAnyColonistTryingToExitMap.cs +++ b/Assembly-CSharp/RimWorld/ThinkNode_ConditionalAnyColonistTryingToExitMap.cs @@ -1,4 +1,3 @@ -using System; using Verse; using Verse.AI; @@ -13,9 +12,9 @@ protected override bool Satisfied(Pawn pawn) { return false; } - foreach (Pawn current in mapHeld.mapPawns.FreeColonistsSpawned) + foreach (Pawn item in mapHeld.mapPawns.FreeColonistsSpawned) { - Job curJob = current.CurJob; + Job curJob = item.CurJob; if (curJob != null && curJob.exitMapOnArrival) { return true; diff --git a/Assembly-CSharp/RimWorld/ThinkNode_ConditionalAnyUndownedColonistSpawnedNearby.cs b/Assembly-CSharp/RimWorld/ThinkNode_ConditionalAnyUndownedColonistSpawnedNearby.cs index c090975a5..a9dd5b3b4 100644 --- a/Assembly-CSharp/RimWorld/ThinkNode_ConditionalAnyUndownedColonistSpawnedNearby.cs +++ b/Assembly-CSharp/RimWorld/ThinkNode_ConditionalAnyUndownedColonistSpawnedNearby.cs @@ -8,16 +8,7 @@ public class ThinkNode_ConditionalAnyUndownedColonistSpawnedNearby : ThinkNode_C { protected override bool Satisfied(Pawn pawn) { - bool arg_40_0; - if (pawn.Spawned) - { - arg_40_0 = pawn.Map.mapPawns.FreeColonistsSpawned.Any((Pawn x) => !x.Downed); - } - else - { - arg_40_0 = false; - } - return arg_40_0; + return pawn.Spawned && pawn.Map.mapPawns.FreeColonistsSpawned.Any((Func)((Pawn x) => !x.Downed)); } } } diff --git a/Assembly-CSharp/RimWorld/ThinkNode_ConditionalAtDutyLocation.cs b/Assembly-CSharp/RimWorld/ThinkNode_ConditionalAtDutyLocation.cs index 3ccb54f20..9b23da732 100644 --- a/Assembly-CSharp/RimWorld/ThinkNode_ConditionalAtDutyLocation.cs +++ b/Assembly-CSharp/RimWorld/ThinkNode_ConditionalAtDutyLocation.cs @@ -1,4 +1,3 @@ -using System; using Verse; namespace RimWorld diff --git a/Assembly-CSharp/RimWorld/ThinkNode_ConditionalBleeding.cs b/Assembly-CSharp/RimWorld/ThinkNode_ConditionalBleeding.cs index bb77cb400..078bc58b0 100644 --- a/Assembly-CSharp/RimWorld/ThinkNode_ConditionalBleeding.cs +++ b/Assembly-CSharp/RimWorld/ThinkNode_ConditionalBleeding.cs @@ -1,4 +1,3 @@ -using System; using Verse; namespace RimWorld @@ -7,7 +6,7 @@ public class ThinkNode_ConditionalBleeding : ThinkNode_Conditional { protected override bool Satisfied(Pawn pawn) { - return pawn.health.hediffSet.BleedRateTotal > 0.001f; + return pawn.health.hediffSet.BleedRateTotal > 0.0010000000474974513; } } } diff --git a/Assembly-CSharp/RimWorld/ThinkNode_ConditionalBodySize.cs b/Assembly-CSharp/RimWorld/ThinkNode_ConditionalBodySize.cs index 3d54804a3..d5f3d2bb9 100644 --- a/Assembly-CSharp/RimWorld/ThinkNode_ConditionalBodySize.cs +++ b/Assembly-CSharp/RimWorld/ThinkNode_ConditionalBodySize.cs @@ -1,4 +1,3 @@ -using System; using Verse; namespace RimWorld diff --git a/Assembly-CSharp/RimWorld/ThinkNode_ConditionalBurning.cs b/Assembly-CSharp/RimWorld/ThinkNode_ConditionalBurning.cs index ed46a2e48..bff48072e 100644 --- a/Assembly-CSharp/RimWorld/ThinkNode_ConditionalBurning.cs +++ b/Assembly-CSharp/RimWorld/ThinkNode_ConditionalBurning.cs @@ -1,4 +1,3 @@ -using System; using Verse; namespace RimWorld diff --git a/Assembly-CSharp/RimWorld/ThinkNode_ConditionalCanDoConstantThinkTreeJobNow.cs b/Assembly-CSharp/RimWorld/ThinkNode_ConditionalCanDoConstantThinkTreeJobNow.cs index 6e9a989ce..4550a3d71 100644 --- a/Assembly-CSharp/RimWorld/ThinkNode_ConditionalCanDoConstantThinkTreeJobNow.cs +++ b/Assembly-CSharp/RimWorld/ThinkNode_ConditionalCanDoConstantThinkTreeJobNow.cs @@ -1,4 +1,3 @@ -using System; using Verse; namespace RimWorld diff --git a/Assembly-CSharp/RimWorld/ThinkNode_ConditionalCannotReachMapEdge.cs b/Assembly-CSharp/RimWorld/ThinkNode_ConditionalCannotReachMapEdge.cs index 8fdf028a0..8a2b58024 100644 --- a/Assembly-CSharp/RimWorld/ThinkNode_ConditionalCannotReachMapEdge.cs +++ b/Assembly-CSharp/RimWorld/ThinkNode_ConditionalCannotReachMapEdge.cs @@ -1,4 +1,3 @@ -using System; using Verse; namespace RimWorld diff --git a/Assembly-CSharp/RimWorld/ThinkNode_ConditionalCloseToDutyTarget.cs b/Assembly-CSharp/RimWorld/ThinkNode_ConditionalCloseToDutyTarget.cs index de956cd94..f3c1b80f7 100644 --- a/Assembly-CSharp/RimWorld/ThinkNode_ConditionalCloseToDutyTarget.cs +++ b/Assembly-CSharp/RimWorld/ThinkNode_ConditionalCloseToDutyTarget.cs @@ -1,4 +1,3 @@ -using System; using Verse; using Verse.AI; diff --git a/Assembly-CSharp/RimWorld/ThinkNode_ConditionalColonist.cs b/Assembly-CSharp/RimWorld/ThinkNode_ConditionalColonist.cs index 443bf4933..5aa3a3120 100644 --- a/Assembly-CSharp/RimWorld/ThinkNode_ConditionalColonist.cs +++ b/Assembly-CSharp/RimWorld/ThinkNode_ConditionalColonist.cs @@ -1,4 +1,3 @@ -using System; using Verse; namespace RimWorld diff --git a/Assembly-CSharp/RimWorld/ThinkNode_ConditionalColonyFaction.cs b/Assembly-CSharp/RimWorld/ThinkNode_ConditionalColonyFaction.cs index 375d73df6..762e2affb 100644 --- a/Assembly-CSharp/RimWorld/ThinkNode_ConditionalColonyFaction.cs +++ b/Assembly-CSharp/RimWorld/ThinkNode_ConditionalColonyFaction.cs @@ -1,4 +1,3 @@ -using System; using Verse; namespace RimWorld diff --git a/Assembly-CSharp/RimWorld/ThinkNode_ConditionalDangerousTemperature.cs b/Assembly-CSharp/RimWorld/ThinkNode_ConditionalDangerousTemperature.cs index 7596acad7..eef700ef6 100644 --- a/Assembly-CSharp/RimWorld/ThinkNode_ConditionalDangerousTemperature.cs +++ b/Assembly-CSharp/RimWorld/ThinkNode_ConditionalDangerousTemperature.cs @@ -1,4 +1,3 @@ -using System; using Verse; namespace RimWorld diff --git a/Assembly-CSharp/RimWorld/ThinkNode_ConditionalDowned.cs b/Assembly-CSharp/RimWorld/ThinkNode_ConditionalDowned.cs index 8ea422aee..e55fb3f5d 100644 --- a/Assembly-CSharp/RimWorld/ThinkNode_ConditionalDowned.cs +++ b/Assembly-CSharp/RimWorld/ThinkNode_ConditionalDowned.cs @@ -1,4 +1,3 @@ -using System; using Verse; namespace RimWorld diff --git a/Assembly-CSharp/RimWorld/ThinkNode_ConditionalDrafted.cs b/Assembly-CSharp/RimWorld/ThinkNode_ConditionalDrafted.cs index b5da40820..e77776b0c 100644 --- a/Assembly-CSharp/RimWorld/ThinkNode_ConditionalDrafted.cs +++ b/Assembly-CSharp/RimWorld/ThinkNode_ConditionalDrafted.cs @@ -1,4 +1,3 @@ -using System; using Verse; namespace RimWorld diff --git a/Assembly-CSharp/RimWorld/ThinkNode_ConditionalExhausted.cs b/Assembly-CSharp/RimWorld/ThinkNode_ConditionalExhausted.cs index bb2541ce2..6e45f664c 100644 --- a/Assembly-CSharp/RimWorld/ThinkNode_ConditionalExhausted.cs +++ b/Assembly-CSharp/RimWorld/ThinkNode_ConditionalExhausted.cs @@ -1,4 +1,3 @@ -using System; using Verse; namespace RimWorld @@ -7,7 +6,7 @@ public class ThinkNode_ConditionalExhausted : ThinkNode_Conditional { protected override bool Satisfied(Pawn pawn) { - return pawn.needs.rest != null && pawn.needs.rest.CurCategory >= RestCategory.Exhausted; + return pawn.needs.rest != null && (int)pawn.needs.rest.CurCategory >= 3; } } } diff --git a/Assembly-CSharp/RimWorld/ThinkNode_ConditionalExitTimedOut.cs b/Assembly-CSharp/RimWorld/ThinkNode_ConditionalExitTimedOut.cs index 8ba766f75..73279aa69 100644 --- a/Assembly-CSharp/RimWorld/ThinkNode_ConditionalExitTimedOut.cs +++ b/Assembly-CSharp/RimWorld/ThinkNode_ConditionalExitTimedOut.cs @@ -1,4 +1,3 @@ -using System; using Verse; namespace RimWorld diff --git a/Assembly-CSharp/RimWorld/ThinkNode_ConditionalForcedGoto.cs b/Assembly-CSharp/RimWorld/ThinkNode_ConditionalForcedGoto.cs index b8f9389b6..b69b5ca5e 100644 --- a/Assembly-CSharp/RimWorld/ThinkNode_ConditionalForcedGoto.cs +++ b/Assembly-CSharp/RimWorld/ThinkNode_ConditionalForcedGoto.cs @@ -1,4 +1,3 @@ -using System; using Verse; namespace RimWorld diff --git a/Assembly-CSharp/RimWorld/ThinkNode_ConditionalGuest.cs b/Assembly-CSharp/RimWorld/ThinkNode_ConditionalGuest.cs index db1e0c5e4..ee086055e 100644 --- a/Assembly-CSharp/RimWorld/ThinkNode_ConditionalGuest.cs +++ b/Assembly-CSharp/RimWorld/ThinkNode_ConditionalGuest.cs @@ -1,4 +1,3 @@ -using System; using Verse; namespace RimWorld diff --git a/Assembly-CSharp/RimWorld/ThinkNode_ConditionalHasDutyPawnTarget.cs b/Assembly-CSharp/RimWorld/ThinkNode_ConditionalHasDutyPawnTarget.cs index 87a3b3e7a..c2c9ccba9 100644 --- a/Assembly-CSharp/RimWorld/ThinkNode_ConditionalHasDutyPawnTarget.cs +++ b/Assembly-CSharp/RimWorld/ThinkNode_ConditionalHasDutyPawnTarget.cs @@ -1,4 +1,3 @@ -using System; using Verse; namespace RimWorld diff --git a/Assembly-CSharp/RimWorld/ThinkNode_ConditionalHasDutyTarget.cs b/Assembly-CSharp/RimWorld/ThinkNode_ConditionalHasDutyTarget.cs index 007a03fdb..c996719c1 100644 --- a/Assembly-CSharp/RimWorld/ThinkNode_ConditionalHasDutyTarget.cs +++ b/Assembly-CSharp/RimWorld/ThinkNode_ConditionalHasDutyTarget.cs @@ -1,4 +1,3 @@ -using System; using Verse; namespace RimWorld diff --git a/Assembly-CSharp/RimWorld/ThinkNode_ConditionalHasFaction.cs b/Assembly-CSharp/RimWorld/ThinkNode_ConditionalHasFaction.cs index 94b37cad1..f56714507 100644 --- a/Assembly-CSharp/RimWorld/ThinkNode_ConditionalHasFaction.cs +++ b/Assembly-CSharp/RimWorld/ThinkNode_ConditionalHasFaction.cs @@ -1,4 +1,3 @@ -using System; using Verse; namespace RimWorld diff --git a/Assembly-CSharp/RimWorld/ThinkNode_ConditionalHasLord.cs b/Assembly-CSharp/RimWorld/ThinkNode_ConditionalHasLord.cs index 64e0610eb..ce9f84b6f 100644 --- a/Assembly-CSharp/RimWorld/ThinkNode_ConditionalHasLord.cs +++ b/Assembly-CSharp/RimWorld/ThinkNode_ConditionalHasLord.cs @@ -1,4 +1,3 @@ -using System; using Verse; using Verse.AI.Group; diff --git a/Assembly-CSharp/RimWorld/ThinkNode_ConditionalHasVoluntarilyJoinableLord.cs b/Assembly-CSharp/RimWorld/ThinkNode_ConditionalHasVoluntarilyJoinableLord.cs index 69e9c216e..e8d596968 100644 --- a/Assembly-CSharp/RimWorld/ThinkNode_ConditionalHasVoluntarilyJoinableLord.cs +++ b/Assembly-CSharp/RimWorld/ThinkNode_ConditionalHasVoluntarilyJoinableLord.cs @@ -1,4 +1,3 @@ -using System; using Verse; using Verse.AI.Group; diff --git a/Assembly-CSharp/RimWorld/ThinkNode_ConditionalHerdAnimal.cs b/Assembly-CSharp/RimWorld/ThinkNode_ConditionalHerdAnimal.cs index 6384eeec4..aa727aed5 100644 --- a/Assembly-CSharp/RimWorld/ThinkNode_ConditionalHerdAnimal.cs +++ b/Assembly-CSharp/RimWorld/ThinkNode_ConditionalHerdAnimal.cs @@ -1,4 +1,3 @@ -using System; using Verse; namespace RimWorld diff --git a/Assembly-CSharp/RimWorld/ThinkNode_ConditionalInNonPlayerHomeMap.cs b/Assembly-CSharp/RimWorld/ThinkNode_ConditionalInNonPlayerHomeMap.cs index dce371dab..f16646907 100644 --- a/Assembly-CSharp/RimWorld/ThinkNode_ConditionalInNonPlayerHomeMap.cs +++ b/Assembly-CSharp/RimWorld/ThinkNode_ConditionalInNonPlayerHomeMap.cs @@ -1,4 +1,3 @@ -using System; using Verse; namespace RimWorld diff --git a/Assembly-CSharp/RimWorld/ThinkNode_ConditionalInPartyArea.cs b/Assembly-CSharp/RimWorld/ThinkNode_ConditionalInPartyArea.cs index 182eff22a..21a45215a 100644 --- a/Assembly-CSharp/RimWorld/ThinkNode_ConditionalInPartyArea.cs +++ b/Assembly-CSharp/RimWorld/ThinkNode_ConditionalInPartyArea.cs @@ -1,4 +1,3 @@ -using System; using Verse; namespace RimWorld diff --git a/Assembly-CSharp/RimWorld/ThinkNode_ConditionalLyingDown.cs b/Assembly-CSharp/RimWorld/ThinkNode_ConditionalLyingDown.cs index c60fb9df0..13e6cca98 100644 --- a/Assembly-CSharp/RimWorld/ThinkNode_ConditionalLyingDown.cs +++ b/Assembly-CSharp/RimWorld/ThinkNode_ConditionalLyingDown.cs @@ -1,4 +1,3 @@ -using System; using Verse; using Verse.AI; diff --git a/Assembly-CSharp/RimWorld/ThinkNode_ConditionalMustKeepLyingDown.cs b/Assembly-CSharp/RimWorld/ThinkNode_ConditionalMustKeepLyingDown.cs index cb8d80aba..fb51d3222 100644 --- a/Assembly-CSharp/RimWorld/ThinkNode_ConditionalMustKeepLyingDown.cs +++ b/Assembly-CSharp/RimWorld/ThinkNode_ConditionalMustKeepLyingDown.cs @@ -1,4 +1,3 @@ -using System; using Verse; using Verse.AI; @@ -8,29 +7,29 @@ public class ThinkNode_ConditionalMustKeepLyingDown : ThinkNode_Conditional { protected override bool Satisfied(Pawn pawn) { - if (pawn.CurJob == null || pawn.jobs.curDriver.layingDown == LayingDownState.NotLaying) + if (((pawn.CurJob != null) ? pawn.jobs.curDriver.layingDown : LayingDownState.NotLaying) != 0) { - return false; - } - if (!pawn.Downed) - { - if (RestUtility.DisturbancePreventsLyingDown(pawn)) + if (!pawn.Downed) { - return false; - } - if (!pawn.CurJob.restUntilHealed || !HealthAIUtility.ShouldSeekMedicalRest(pawn)) - { - if (!pawn.jobs.curDriver.asleep) + if (RestUtility.DisturbancePreventsLyingDown(pawn)) { return false; } - if (!pawn.CurJob.playerForced && RestUtility.TimetablePreventsLayDown(pawn)) + if (!pawn.CurJob.restUntilHealed || !HealthAIUtility.ShouldSeekMedicalRest(pawn)) { - return false; + if (!pawn.jobs.curDriver.asleep) + { + return false; + } + if (!pawn.CurJob.playerForced && RestUtility.TimetablePreventsLayDown(pawn)) + { + return false; + } } } + return true; } - return true; + return false; } } } diff --git a/Assembly-CSharp/RimWorld/ThinkNode_ConditionalNeedPercentageAbove.cs b/Assembly-CSharp/RimWorld/ThinkNode_ConditionalNeedPercentageAbove.cs index e1d76cf9a..8da036baa 100644 --- a/Assembly-CSharp/RimWorld/ThinkNode_ConditionalNeedPercentageAbove.cs +++ b/Assembly-CSharp/RimWorld/ThinkNode_ConditionalNeedPercentageAbove.cs @@ -1,4 +1,3 @@ -using System; using Verse; using Verse.AI; diff --git a/Assembly-CSharp/RimWorld/ThinkNode_ConditionalNeutralFaction.cs b/Assembly-CSharp/RimWorld/ThinkNode_ConditionalNeutralFaction.cs index 61dfdde66..78783345f 100644 --- a/Assembly-CSharp/RimWorld/ThinkNode_ConditionalNeutralFaction.cs +++ b/Assembly-CSharp/RimWorld/ThinkNode_ConditionalNeutralFaction.cs @@ -1,4 +1,3 @@ -using System; using Verse; namespace RimWorld diff --git a/Assembly-CSharp/RimWorld/ThinkNode_ConditionalOutdoorTemperature.cs b/Assembly-CSharp/RimWorld/ThinkNode_ConditionalOutdoorTemperature.cs index 42aaf22bb..787ce077a 100644 --- a/Assembly-CSharp/RimWorld/ThinkNode_ConditionalOutdoorTemperature.cs +++ b/Assembly-CSharp/RimWorld/ThinkNode_ConditionalOutdoorTemperature.cs @@ -1,4 +1,3 @@ -using System; using Verse; namespace RimWorld diff --git a/Assembly-CSharp/RimWorld/ThinkNode_ConditionalPrisoner.cs b/Assembly-CSharp/RimWorld/ThinkNode_ConditionalPrisoner.cs index 7622d4907..d0faf454c 100644 --- a/Assembly-CSharp/RimWorld/ThinkNode_ConditionalPrisoner.cs +++ b/Assembly-CSharp/RimWorld/ThinkNode_ConditionalPrisoner.cs @@ -1,4 +1,3 @@ -using System; using Verse; namespace RimWorld diff --git a/Assembly-CSharp/RimWorld/ThinkNode_ConditionalPrisonerInPrisonCell.cs b/Assembly-CSharp/RimWorld/ThinkNode_ConditionalPrisonerInPrisonCell.cs index f16b047e5..621efb0cf 100644 --- a/Assembly-CSharp/RimWorld/ThinkNode_ConditionalPrisonerInPrisonCell.cs +++ b/Assembly-CSharp/RimWorld/ThinkNode_ConditionalPrisonerInPrisonCell.cs @@ -1,4 +1,3 @@ -using System; using Verse; namespace RimWorld diff --git a/Assembly-CSharp/RimWorld/ThinkNode_ConditionalRandom.cs b/Assembly-CSharp/RimWorld/ThinkNode_ConditionalRandom.cs index f94cc99e3..ae14499e6 100644 --- a/Assembly-CSharp/RimWorld/ThinkNode_ConditionalRandom.cs +++ b/Assembly-CSharp/RimWorld/ThinkNode_ConditionalRandom.cs @@ -1,4 +1,3 @@ -using System; using Verse; using Verse.AI; diff --git a/Assembly-CSharp/RimWorld/ThinkNode_ConditionalReleased.cs b/Assembly-CSharp/RimWorld/ThinkNode_ConditionalReleased.cs index d0bc71397..37393b4c3 100644 --- a/Assembly-CSharp/RimWorld/ThinkNode_ConditionalReleased.cs +++ b/Assembly-CSharp/RimWorld/ThinkNode_ConditionalReleased.cs @@ -1,4 +1,3 @@ -using System; using Verse; namespace RimWorld diff --git a/Assembly-CSharp/RimWorld/ThinkNode_ConditionalShouldFollowMaster.cs b/Assembly-CSharp/RimWorld/ThinkNode_ConditionalShouldFollowMaster.cs index 239bb98f4..e90ee4c0b 100644 --- a/Assembly-CSharp/RimWorld/ThinkNode_ConditionalShouldFollowMaster.cs +++ b/Assembly-CSharp/RimWorld/ThinkNode_ConditionalShouldFollowMaster.cs @@ -1,4 +1,3 @@ -using System; using Verse; using Verse.AI; @@ -23,7 +22,23 @@ public static bool ShouldFollowMaster(Pawn pawn) return false; } Pawn carriedBy = master.CarriedBy; - return (master.Spawned || carriedBy != null) && ((carriedBy != null && carriedBy.HostileTo(master)) || (pawn.playerSettings.followDrafted && master.Drafted) || (pawn.playerSettings.followFieldwork && master.mindState.lastJobTag == JobTag.Fieldwork)); + if (!master.Spawned && carriedBy == null) + { + return false; + } + if (carriedBy != null && carriedBy.HostileTo(master)) + { + return true; + } + if (pawn.playerSettings.followDrafted && master.Drafted) + { + return true; + } + if (pawn.playerSettings.followFieldwork && master.mindState.lastJobTag == JobTag.Fieldwork) + { + return true; + } + return false; } } } diff --git a/Assembly-CSharp/RimWorld/ThinkNode_ConditionalStarving.cs b/Assembly-CSharp/RimWorld/ThinkNode_ConditionalStarving.cs index 8049475b9..bf2330f49 100644 --- a/Assembly-CSharp/RimWorld/ThinkNode_ConditionalStarving.cs +++ b/Assembly-CSharp/RimWorld/ThinkNode_ConditionalStarving.cs @@ -1,4 +1,3 @@ -using System; using Verse; namespace RimWorld @@ -7,7 +6,7 @@ public class ThinkNode_ConditionalStarving : ThinkNode_Conditional { protected override bool Satisfied(Pawn pawn) { - return pawn.needs.food != null && pawn.needs.food.CurCategory >= HungerCategory.Starving; + return pawn.needs.food != null && (int)pawn.needs.food.CurCategory >= 3; } } } diff --git a/Assembly-CSharp/RimWorld/ThinkNode_ConditionalTrainableCompleted.cs b/Assembly-CSharp/RimWorld/ThinkNode_ConditionalTrainableCompleted.cs index 5be691712..43852ff4a 100644 --- a/Assembly-CSharp/RimWorld/ThinkNode_ConditionalTrainableCompleted.cs +++ b/Assembly-CSharp/RimWorld/ThinkNode_ConditionalTrainableCompleted.cs @@ -1,4 +1,3 @@ -using System; using Verse; using Verse.AI; diff --git a/Assembly-CSharp/RimWorld/ThinkNode_Duty.cs b/Assembly-CSharp/RimWorld/ThinkNode_Duty.cs index e49be6acb..d4bee7a13 100644 --- a/Assembly-CSharp/RimWorld/ThinkNode_Duty.cs +++ b/Assembly-CSharp/RimWorld/ThinkNode_Duty.cs @@ -1,4 +1,3 @@ -using System; using Verse; using Verse.AI; using Verse.AI.Group; @@ -19,15 +18,15 @@ public override ThinkResult TryIssueJobPackage(Pawn pawn, JobIssueParams jobPara Log.Error(pawn + " doing ThinkNode_Duty with no duty."); return ThinkResult.NoJob; } - return this.subNodes[(int)pawn.mindState.duty.def.index].TryIssueJobPackage(pawn, jobParams); + return base.subNodes[pawn.mindState.duty.def.index].TryIssueJobPackage(pawn, jobParams); } protected override void ResolveSubnodes() { - foreach (DutyDef current in DefDatabase.AllDefs) + foreach (DutyDef allDef in DefDatabase.AllDefs) { - current.thinkNode.ResolveSubnodesAndRecur(); - this.subNodes.Add(current.thinkNode.DeepCopy(true)); + allDef.thinkNode.ResolveSubnodesAndRecur(); + base.subNodes.Add(allDef.thinkNode.DeepCopy(true)); } } } diff --git a/Assembly-CSharp/RimWorld/ThinkNode_DutyConstant.cs b/Assembly-CSharp/RimWorld/ThinkNode_DutyConstant.cs index 773ec4353..2f2d8acbb 100644 --- a/Assembly-CSharp/RimWorld/ThinkNode_DutyConstant.cs +++ b/Assembly-CSharp/RimWorld/ThinkNode_DutyConstant.cs @@ -1,4 +1,3 @@ -using System; using Verse; using Verse.AI; using Verse.AI.Group; @@ -31,20 +30,20 @@ public override ThinkResult TryIssueJobPackage(Pawn pawn, JobIssueParams jobPara { return ThinkResult.NoJob; } - return this.subNodes[num].TryIssueJobPackage(pawn, jobParams); + return base.subNodes[num].TryIssueJobPackage(pawn, jobParams); } protected override void ResolveSubnodes() { this.dutyDefToSubNode = new DefMap(); this.dutyDefToSubNode.SetAll(-1); - foreach (DutyDef current in DefDatabase.AllDefs) + foreach (DutyDef allDef in DefDatabase.AllDefs) { - if (current.constantThinkNode != null) + if (allDef.constantThinkNode != null) { - this.dutyDefToSubNode[current] = this.subNodes.Count; - current.constantThinkNode.ResolveSubnodesAndRecur(); - this.subNodes.Add(current.constantThinkNode.DeepCopy(true)); + this.dutyDefToSubNode[allDef] = base.subNodes.Count; + allDef.constantThinkNode.ResolveSubnodesAndRecur(); + base.subNodes.Add(allDef.constantThinkNode.DeepCopy(true)); } } } diff --git a/Assembly-CSharp/RimWorld/ThinkNode_JoinVoluntarilyJoinableLord.cs b/Assembly-CSharp/RimWorld/ThinkNode_JoinVoluntarilyJoinableLord.cs index cf2c9277f..e29b21b04 100644 --- a/Assembly-CSharp/RimWorld/ThinkNode_JoinVoluntarilyJoinableLord.cs +++ b/Assembly-CSharp/RimWorld/ThinkNode_JoinVoluntarilyJoinableLord.cs @@ -1,4 +1,3 @@ -using System; using System.Collections.Generic; using Verse; using Verse.AI; @@ -31,18 +30,13 @@ public override ThinkResult TryIssueJobPackage(Pawn pawn, JobIssueParams jobPara private void CheckLeaveCurrentVoluntarilyJoinableLord(Pawn pawn) { Lord lord = pawn.GetLord(); - if (lord == null) - { - return; - } - LordJob_VoluntarilyJoinable lordJob_VoluntarilyJoinable = lord.LordJob as LordJob_VoluntarilyJoinable; - if (lordJob_VoluntarilyJoinable == null) - { - return; - } - if (lordJob_VoluntarilyJoinable.VoluntaryJoinPriorityFor(pawn) <= 0f) + if (lord != null) { - lord.Notify_PawnLost(pawn, PawnLostCondition.LeftVoluntarily); + LordJob_VoluntarilyJoinable lordJob_VoluntarilyJoinable = lord.LordJob as LordJob_VoluntarilyJoinable; + if (lordJob_VoluntarilyJoinable != null && lordJob_VoluntarilyJoinable.VoluntaryJoinPriorityFor(pawn) <= 0.0) + { + lord.Notify_PawnLost(pawn, PawnLostCondition.LeftVoluntarily); + } } } @@ -55,9 +49,7 @@ private void JoinVoluntarilyJoinableLord(Pawn pawn) { LordJob_VoluntarilyJoinable lordJob_VoluntarilyJoinable = lord.LordJob as LordJob_VoluntarilyJoinable; if (lordJob_VoluntarilyJoinable == null) - { return; - } lord2 = lord; num = lordJob_VoluntarilyJoinable.VoluntaryJoinPriorityFor(pawn); } @@ -65,19 +57,13 @@ private void JoinVoluntarilyJoinableLord(Pawn pawn) for (int i = 0; i < lords.Count; i++) { LordJob_VoluntarilyJoinable lordJob_VoluntarilyJoinable2 = lords[i].LordJob as LordJob_VoluntarilyJoinable; - if (lordJob_VoluntarilyJoinable2 != null) + if (lordJob_VoluntarilyJoinable2 != null && lords[i].CurLordToil.VoluntaryJoinDutyHookFor(pawn) == this.dutyHook) { - if (lords[i].CurLordToil.VoluntaryJoinDutyHookFor(pawn) == this.dutyHook) + float num2 = lordJob_VoluntarilyJoinable2.VoluntaryJoinPriorityFor(pawn); + if (!(num2 <= 0.0) && (lord2 == null || num2 > num)) { - float num2 = lordJob_VoluntarilyJoinable2.VoluntaryJoinPriorityFor(pawn); - if (num2 > 0f) - { - if (lord2 == null || num2 > num) - { - lord2 = lords[i]; - num = num2; - } - } + lord2 = lords[i]; + num = num2; } } } diff --git a/Assembly-CSharp/RimWorld/ThinkNode_Priority_GetJoy.cs b/Assembly-CSharp/RimWorld/ThinkNode_Priority_GetJoy.cs index b52dd0095..b6fe37761 100644 --- a/Assembly-CSharp/RimWorld/ThinkNode_Priority_GetJoy.cs +++ b/Assembly-CSharp/RimWorld/ThinkNode_Priority_GetJoy.cs @@ -30,32 +30,29 @@ public override float GetPriority(Pawn pawn) } if (timeAssignmentDef == TimeAssignmentDefOf.Anything) { - if (curLevel < 0.35f) + if (curLevel < 0.34999999403953552) { return 6f; } return 0f; } - else if (timeAssignmentDef == TimeAssignmentDefOf.Joy) + if (timeAssignmentDef == TimeAssignmentDefOf.Joy) { - if (curLevel < 0.95f) + if (curLevel < 0.949999988079071) { return 7f; } return 0f; } - else + if (timeAssignmentDef == TimeAssignmentDefOf.Sleep) { - if (timeAssignmentDef != TimeAssignmentDefOf.Sleep) - { - throw new NotImplementedException(); - } - if (curLevel < 0.95f) + if (curLevel < 0.949999988079071) { return 2f; } return 0f; } + throw new NotImplementedException(); } } } diff --git a/Assembly-CSharp/RimWorld/ThinkNode_TraitBehaviors.cs b/Assembly-CSharp/RimWorld/ThinkNode_TraitBehaviors.cs index 965ec253d..295af17dc 100644 --- a/Assembly-CSharp/RimWorld/ThinkNode_TraitBehaviors.cs +++ b/Assembly-CSharp/RimWorld/ThinkNode_TraitBehaviors.cs @@ -1,4 +1,3 @@ -using System; using System.Collections.Generic; using Verse; using Verse.AI; diff --git a/Assembly-CSharp/RimWorld/Thought.cs b/Assembly-CSharp/RimWorld/Thought.cs index e29c3470c..729de8c0c 100644 --- a/Assembly-CSharp/RimWorld/Thought.cs +++ b/Assembly-CSharp/RimWorld/Thought.cs @@ -1,4 +1,3 @@ -using System; using UnityEngine; using Verse; @@ -81,11 +80,11 @@ public Texture2D Icon { get { - if (this.def.Icon != null) + if ((Object)this.def.Icon != (Object)null) { return this.def.Icon; } - if (this.MoodOffset() > 0f) + if (this.MoodOffset() > 0.0) { return Thought.DefaultGoodIcon; } @@ -102,13 +101,7 @@ public virtual float MoodOffset() { if (this.CurStage == null) { - Log.Error(string.Concat(new object[] - { - "CurStage is null while ShouldDiscard is false on ", - this.def.defName, - " for ", - this.pawn - })); + Log.Error("CurStage is null while ShouldDiscard is false on " + this.def.defName + " for " + this.pawn); return 0f; } float num = this.BaseMoodOffset; diff --git a/Assembly-CSharp/RimWorld/ThoughtDef.cs b/Assembly-CSharp/RimWorld/ThoughtDef.cs index 06e1fe674..6a35bbdc3 100644 --- a/Assembly-CSharp/RimWorld/ThoughtDef.cs +++ b/Assembly-CSharp/RimWorld/ThoughtDef.cs @@ -1,6 +1,5 @@ using System; using System.Collections.Generic; -using System.Diagnostics; using UnityEngine; using Verse; @@ -66,11 +65,11 @@ public string Label { get { - if (!this.label.NullOrEmpty()) + if (!base.label.NullOrEmpty()) { - return this.label; + return base.label; } - if (this.stages.NullOrEmpty()) + if (this.stages.NullOrEmpty()) { if (!this.stages[0].label.NullOrEmpty()) { @@ -81,8 +80,8 @@ public string Label return this.stages[0].labelSocial; } } - Log.Error("Cannot get good label for ThoughtDef " + this.defName); - return this.defName; + Log.Error("Cannot get good label for ThoughtDef " + base.defName); + return base.defName; } } @@ -90,7 +89,7 @@ public int DurationTicks { get { - return (int)(this.durationDays * 60000f); + return (int)(this.durationDays * 60000.0); } } @@ -98,7 +97,7 @@ public bool IsMemory { get { - return this.durationDays > 0f || typeof(Thought_Memory).IsAssignableFrom(this.thoughtClass); + return this.durationDays > 0.0 || typeof(Thought_Memory).IsAssignableFrom(this.thoughtClass); } } @@ -159,7 +158,7 @@ public Texture2D Icon { get { - if (this.iconInt == null) + if ((UnityEngine.Object)this.iconInt == (UnityEngine.Object)null) { if (this.icon == null) { @@ -171,14 +170,28 @@ public Texture2D Icon } } - [DebuggerHidden] public override IEnumerable ConfigErrors() { - ThoughtDef.c__Iterator9A c__Iterator9A = new ThoughtDef.c__Iterator9A(); - c__Iterator9A.<>f__this = this; - ThoughtDef.c__Iterator9A expr_0E = c__Iterator9A; - expr_0E.$PC = -2; - return expr_0E; + foreach (string item in base.ConfigErrors()) + { + yield return item; + } + if (this.stages.NullOrEmpty()) + { + yield return "no stages"; + } + if (this.workerClass != null && this.nextThought != null) + { + yield return "has a nextThought but also has a workerClass. nextThought only works for memories"; + } + if (this.IsMemory && this.workerClass != null) + { + yield return "has a workerClass but is a memory. workerClass only works for situational thoughts, not memories"; + } + if (!this.IsMemory && this.workerClass == null && this.IsSituational) + { + yield return "is a situational thought but has no workerClass. Situational thoughts require workerClasses to analyze the situation"; + } } public static ThoughtDef Named(string defName) diff --git a/Assembly-CSharp/RimWorld/ThoughtDefOf.cs b/Assembly-CSharp/RimWorld/ThoughtDefOf.cs index 036f8fed9..3f0f1753e 100644 --- a/Assembly-CSharp/RimWorld/ThoughtDefOf.cs +++ b/Assembly-CSharp/RimWorld/ThoughtDefOf.cs @@ -1,5 +1,3 @@ -using System; - namespace RimWorld { [DefOf] diff --git a/Assembly-CSharp/RimWorld/ThoughtHandler.cs b/Assembly-CSharp/RimWorld/ThoughtHandler.cs index 37c67ca53..947137f9d 100644 --- a/Assembly-CSharp/RimWorld/ThoughtHandler.cs +++ b/Assembly-CSharp/RimWorld/ThoughtHandler.cs @@ -30,7 +30,7 @@ public ThoughtHandler(Pawn pawn) public void ExposeData() { - Scribe_Deep.Look(ref this.memories, "memories", new object[] + Scribe_Deep.Look(ref this.memories, "memories", new object[1] { this.pawn }); @@ -49,7 +49,7 @@ public void GetAllMoodThoughts(List outThoughts) for (int i = 0; i < list.Count; i++) { Thought_Memory thought_Memory = list[i]; - if (thought_Memory.MoodOffset() != 0f) + if (thought_Memory.MoodOffset() != 0.0) { outThoughts.Add(thought_Memory); } @@ -60,11 +60,11 @@ public void GetAllMoodThoughts(List outThoughts) public void GetMoodThoughts(Thought group, List outThoughts) { this.GetAllMoodThoughts(outThoughts); - for (int i = outThoughts.Count - 1; i >= 0; i--) + for (int num = outThoughts.Count - 1; num >= 0; num--) { - if (!outThoughts[i].GroupsWith(group)) + if (!outThoughts[num].GroupsWith(group)) { - outThoughts.RemoveAt(i); + outThoughts.RemoveAt(num); } } } @@ -72,7 +72,7 @@ public void GetMoodThoughts(Thought group, List outThoughts) public float MoodOffsetOfGroup(Thought group) { this.GetMoodThoughts(group, ThoughtHandler.tmpThoughts); - if (!ThoughtHandler.tmpThoughts.Any()) + if (!ThoughtHandler.tmpThoughts.Any()) { return 0f; } @@ -94,16 +94,19 @@ public float MoodOffsetOfGroup(Thought group) public void GetDistinctMoodThoughtGroups(List outThoughts) { this.GetAllMoodThoughts(outThoughts); - for (int i = outThoughts.Count - 1; i >= 0; i--) + for (int num = outThoughts.Count - 1; num >= 0; num--) { - Thought other = outThoughts[i]; - for (int j = 0; j < i; j++) + Thought other = outThoughts[num]; + int num2 = 0; + while (num2 < num) { - if (outThoughts[j].GroupsWith(other)) + if (!outThoughts[num2].GroupsWith(other)) { - outThoughts.RemoveAt(i); - break; + num2++; + continue; } + outThoughts.RemoveAt(num); + break; } } } @@ -138,11 +141,11 @@ public void GetSocialThoughts(Pawn otherPawn, List outThoughts) public void GetSocialThoughts(Pawn otherPawn, ISocialThought group, List outThoughts) { this.GetSocialThoughts(otherPawn, outThoughts); - for (int i = outThoughts.Count - 1; i >= 0; i--) + for (int num = outThoughts.Count - 1; num >= 0; num--) { - if (!((Thought)outThoughts[i]).GroupsWith((Thought)group)) + if (!((Thought)outThoughts[num]).GroupsWith((Thought)group)) { - outThoughts.RemoveAt(i); + outThoughts.RemoveAt(num); } } } @@ -151,55 +154,58 @@ public int OpinionOffsetOfGroup(ISocialThought group, Pawn otherPawn) { ProfilerThreadCheck.BeginSample("OpinionOffsetOfGroup()"); this.GetSocialThoughts(otherPawn, group, ThoughtHandler.tmpSocialThoughts); - for (int i = ThoughtHandler.tmpSocialThoughts.Count - 1; i >= 0; i--) + for (int num = ThoughtHandler.tmpSocialThoughts.Count - 1; num >= 0; num--) { - if (ThoughtHandler.tmpSocialThoughts[i].OpinionOffset() == 0f) + if (ThoughtHandler.tmpSocialThoughts[num].OpinionOffset() == 0.0) { - ThoughtHandler.tmpSocialThoughts.RemoveAt(i); + ThoughtHandler.tmpSocialThoughts.RemoveAt(num); } } - if (!ThoughtHandler.tmpSocialThoughts.Any()) + if (!ThoughtHandler.tmpSocialThoughts.Any()) { return 0; } ThoughtDef def = ((Thought)group).def; - if (def.IsMemory && def.stackedEffectMultiplier != 1f) + if (def.IsMemory && def.stackedEffectMultiplier != 1.0) { - ThoughtHandler.tmpSocialThoughts.Sort((ISocialThought a, ISocialThought b) => ((Thought_Memory)a).age.CompareTo(((Thought_Memory)b).age)); + ThoughtHandler.tmpSocialThoughts.Sort((Comparison)((ISocialThought a, ISocialThought b) => ((Thought_Memory)a).age.CompareTo(((Thought_Memory)b).age))); } - float num = 0f; - float num2 = 1f; - for (int j = 0; j < ThoughtHandler.tmpSocialThoughts.Count; j++) + float num2 = 0f; + float num3 = 1f; + for (int i = 0; i < ThoughtHandler.tmpSocialThoughts.Count; i++) { - num += ThoughtHandler.tmpSocialThoughts[j].OpinionOffset() * num2; - num2 *= ((Thought)ThoughtHandler.tmpSocialThoughts[j]).def.stackedEffectMultiplier; + num2 += ThoughtHandler.tmpSocialThoughts[i].OpinionOffset() * num3; + num3 *= ((Thought)ThoughtHandler.tmpSocialThoughts[i]).def.stackedEffectMultiplier; } ThoughtHandler.tmpSocialThoughts.Clear(); ProfilerThreadCheck.EndSample(); - if (num == 0f) + if (num2 == 0.0) { return 0; } - if (num > 0f) + if (num2 > 0.0) { - return Mathf.Max(Mathf.RoundToInt(num), 1); + return Mathf.Max(Mathf.RoundToInt(num2), 1); } - return Mathf.Min(Mathf.RoundToInt(num), -1); + return Mathf.Min(Mathf.RoundToInt(num2), -1); } public void GetDistinctSocialThoughtGroups(Pawn otherPawn, List outThoughts) { this.GetSocialThoughts(otherPawn, outThoughts); - for (int i = outThoughts.Count - 1; i >= 0; i--) + for (int num = outThoughts.Count - 1; num >= 0; num--) { - ISocialThought socialThought = outThoughts[i]; - for (int j = 0; j < i; j++) + ISocialThought socialThought = outThoughts[num]; + int num2 = 0; + while (num2 < num) { - if (((Thought)outThoughts[j]).GroupsWith((Thought)socialThought)) + if (!((Thought)outThoughts[num2]).GroupsWith((Thought)socialThought)) { - outThoughts.RemoveAt(i); - break; + num2++; + continue; } + outThoughts.RemoveAt(num); + break; } } } diff --git a/Assembly-CSharp/RimWorld/ThoughtStage.cs b/Assembly-CSharp/RimWorld/ThoughtStage.cs index 448a62dee..10710bb94 100644 --- a/Assembly-CSharp/RimWorld/ThoughtStage.cs +++ b/Assembly-CSharp/RimWorld/ThoughtStage.cs @@ -1,4 +1,3 @@ -using System; using Verse; namespace RimWorld diff --git a/Assembly-CSharp/RimWorld/ThoughtState.cs b/Assembly-CSharp/RimWorld/ThoughtState.cs index 6ce5a0087..6632d4a8b 100644 --- a/Assembly-CSharp/RimWorld/ThoughtState.cs +++ b/Assembly-CSharp/RimWorld/ThoughtState.cs @@ -1,5 +1,3 @@ -using System; - namespace RimWorld { public struct ThoughtState diff --git a/Assembly-CSharp/RimWorld/ThoughtUtility.cs b/Assembly-CSharp/RimWorld/ThoughtUtility.cs index 3d730ba6b..5ccc47687 100644 --- a/Assembly-CSharp/RimWorld/ThoughtUtility.cs +++ b/Assembly-CSharp/RimWorld/ThoughtUtility.cs @@ -15,81 +15,77 @@ public static void Reset() { ThoughtUtility.situationalSocialThoughtDefs = (from x in DefDatabase.AllDefs where x.IsSituational && x.IsSocial - select x).ToList(); + select x).ToList(); ThoughtUtility.situationalNonSocialThoughtDefs = (from x in DefDatabase.AllDefs where x.IsSituational && !x.IsSocial - select x).ToList(); + select x).ToList(); } public static void GiveThoughtsForPawnExecuted(Pawn victim, PawnExecutionKind kind) { - if (!victim.RaceProps.Humanlike) + if (victim.RaceProps.Humanlike) { - return; - } - int forcedStage = 1; - if (victim.guilt.IsGuilty) - { - forcedStage = 0; - } - else - { - switch (kind) + int forcedStage = 1; + if (victim.guilt.IsGuilty) { - case PawnExecutionKind.GenericBrutal: - forcedStage = 2; - break; - case PawnExecutionKind.GenericHumane: - forcedStage = 1; - break; - case PawnExecutionKind.OrganHarvesting: - forcedStage = 3; - break; + forcedStage = 0; + } + else + { + switch (kind) + { + case PawnExecutionKind.GenericHumane: + { + forcedStage = 1; + break; + } + case PawnExecutionKind.GenericBrutal: + { + forcedStage = 2; + break; + } + case PawnExecutionKind.OrganHarvesting: + { + forcedStage = 3; + break; + } + } + } + ThoughtDef def = (!victim.IsColonist) ? ThoughtDefOf.KnowGuestExecuted : ThoughtDefOf.KnowColonistExecuted; + foreach (Pawn item in from x in PawnsFinder.AllMapsCaravansAndTravelingTransportPods + where x.IsColonist || x.IsPrisonerOfColony + select x) + { + item.needs.mood.thoughts.memories.TryGainMemory(ThoughtMaker.MakeThought(def, forcedStage), null); } - } - ThoughtDef def; - if (victim.IsColonist) - { - def = ThoughtDefOf.KnowColonistExecuted; - } - else - { - def = ThoughtDefOf.KnowGuestExecuted; - } - foreach (Pawn current in from x in PawnsFinder.AllMapsCaravansAndTravelingTransportPods - where x.IsColonist || x.IsPrisonerOfColony - select x) - { - current.needs.mood.thoughts.memories.TryGainMemory(ThoughtMaker.MakeThought(def, forcedStage), null); } } public static void GiveThoughtsForPawnOrganHarvested(Pawn victim) { - if (!victim.RaceProps.Humanlike) - { - return; - } - ThoughtDef thoughtDef = null; - if (victim.IsColonist) - { - thoughtDef = ThoughtDefOf.KnowColonistOrganHarvested; - } - else if (victim.HostFaction == Faction.OfPlayer) + if (victim.RaceProps.Humanlike) { - thoughtDef = ThoughtDefOf.KnowGuestOrganHarvested; - } - foreach (Pawn current in from x in PawnsFinder.AllMapsCaravansAndTravelingTransportPods - where x.IsColonist || x.IsPrisonerOfColony - select x) - { - if (current == victim) + ThoughtDef thoughtDef = null; + if (victim.IsColonist) + { + thoughtDef = ThoughtDefOf.KnowColonistOrganHarvested; + } + else if (victim.HostFaction == Faction.OfPlayer) { - current.needs.mood.thoughts.memories.TryGainMemory(ThoughtDefOf.MyOrganHarvested, null); + thoughtDef = ThoughtDefOf.KnowGuestOrganHarvested; } - else if (thoughtDef != null) + foreach (Pawn item in from x in PawnsFinder.AllMapsCaravansAndTravelingTransportPods + where x.IsColonist || x.IsPrisonerOfColony + select x) { - current.needs.mood.thoughts.memories.TryGainMemory(thoughtDef, null); + if (item == victim) + { + item.needs.mood.thoughts.memories.TryGainMemory(ThoughtDefOf.MyOrganHarvested, null); + } + else if (thoughtDef != null) + { + item.needs.mood.thoughts.memories.TryGainMemory(thoughtDef, null); + } } } } @@ -110,12 +106,12 @@ public static bool IsSituationalThoughtNullifiedByHediffs(ThoughtDef def, Pawn p num = curStage.pctConditionalThoughtsNullified; } } - if (num == 0f) + if (num == 0.0) { return false; } Rand.PushState(); - Rand.Seed = pawn.thingIDNumber * 31 + (int)(def.index * 139); + Rand.Seed = pawn.thingIDNumber * 31 + def.index * 139; bool result = Rand.Value < num; Rand.PopState(); return result; @@ -138,12 +134,11 @@ public static bool IsThoughtNullifiedByOwnTales(ThoughtDef def, Pawn pawn) public static void RemovePositiveBedroomThoughts(Pawn pawn) { - if (pawn.needs.mood == null) + if (pawn.needs.mood != null) { - return; + pawn.needs.mood.thoughts.memories.RemoveMemoriesOfDefIf(ThoughtDefOf.SleptInBedroom, (Func)((Thought_Memory thought) => thought.MoodOffset() > 0.0)); + pawn.needs.mood.thoughts.memories.RemoveMemoriesOfDefIf(ThoughtDefOf.SleptInBarracks, (Func)((Thought_Memory thought) => thought.MoodOffset() > 0.0)); } - pawn.needs.mood.thoughts.memories.RemoveMemoriesOfDefIf(ThoughtDefOf.SleptInBedroom, (Thought_Memory thought) => thought.MoodOffset() > 0f); - pawn.needs.mood.thoughts.memories.RemoveMemoriesOfDefIf(ThoughtDefOf.SleptInBarracks, (Thought_Memory thought) => thought.MoodOffset() > 0f); } public static bool CanGetThought(Pawn pawn, ThoughtDef def) @@ -153,8 +148,7 @@ public static bool CanGetThought(Pawn pawn, ThoughtDef def) { if (!def.validWhileDespawned && !pawn.Spawned && !def.IsMemory) { - bool result = false; - return result; + return false; } if (def.nullifyingTraits != null) { @@ -162,45 +156,40 @@ public static bool CanGetThought(Pawn pawn, ThoughtDef def) { if (pawn.story.traits.HasTrait(def.nullifyingTraits[i])) { - bool result = false; - return result; + return false; } } } - if (!def.requiredTraits.NullOrEmpty()) + if (!def.requiredTraits.NullOrEmpty()) { bool flag = false; - for (int j = 0; j < def.requiredTraits.Count; j++) + int num = 0; + while (num < def.requiredTraits.Count) { - if (pawn.story.traits.HasTrait(def.requiredTraits[j])) + if (!pawn.story.traits.HasTrait(def.requiredTraits[num]) || (def.RequiresSpecificTraitsDegree && def.requiredTraitsDegree != pawn.story.traits.DegreeOfTrait(def.requiredTraits[num]))) { - if (!def.RequiresSpecificTraitsDegree || def.requiredTraitsDegree == pawn.story.traits.DegreeOfTrait(def.requiredTraits[j])) - { - flag = true; - break; - } + num++; + continue; } + flag = true; + break; } if (!flag) { - bool result = false; - return result; + return false; } } if (def.nullifiedIfNotColonist && !pawn.IsColonist) { - bool result = false; - return result; + return false; } if (ThoughtUtility.IsSituationalThoughtNullifiedByHediffs(def, pawn)) { - bool result = false; - return result; + return false; } if (ThoughtUtility.IsThoughtNullifiedByOwnTales(def, pawn)) { - bool result = false; - return result; + return false; } } finally diff --git a/Assembly-CSharp/RimWorld/ThoughtWorker.cs b/Assembly-CSharp/RimWorld/ThoughtWorker.cs index 4060eab9a..ea356f5c8 100644 --- a/Assembly-CSharp/RimWorld/ThoughtWorker.cs +++ b/Assembly-CSharp/RimWorld/ThoughtWorker.cs @@ -27,14 +27,7 @@ private ThoughtState PostProcessedState(ThoughtState state) { if (this.def.invert) { - if (state.Active) - { - state = ThoughtState.Inactive; - } - else - { - state = ThoughtState.ActiveAtStage(0); - } + state = ((!state.Active) ? ThoughtState.ActiveAtStage(0) : ThoughtState.Inactive); } return state; } diff --git a/Assembly-CSharp/RimWorld/ThoughtWorker_Affair.cs b/Assembly-CSharp/RimWorld/ThoughtWorker_Affair.cs index f2a376d44..0b0be741f 100644 --- a/Assembly-CSharp/RimWorld/ThoughtWorker_Affair.cs +++ b/Assembly-CSharp/RimWorld/ThoughtWorker_Affair.cs @@ -1,4 +1,3 @@ -using System; using System.Collections.Generic; using Verse; @@ -15,15 +14,9 @@ protected override ThoughtState CurrentSocialStateInternal(Pawn p, Pawn otherPaw List directRelations = otherPawn.relations.DirectRelations; for (int i = 0; i < directRelations.Count; i++) { - if (directRelations[i].otherPawn != p) + if (directRelations[i].otherPawn != p && !directRelations[i].otherPawn.Dead && (directRelations[i].def == PawnRelationDefOf.Lover || directRelations[i].def == PawnRelationDefOf.Fiance)) { - if (!directRelations[i].otherPawn.Dead) - { - if (directRelations[i].def == PawnRelationDefOf.Lover || directRelations[i].def == PawnRelationDefOf.Fiance) - { - return true; - } - } + return true; } } return false; diff --git a/Assembly-CSharp/RimWorld/ThoughtWorker_AlwaysActive.cs b/Assembly-CSharp/RimWorld/ThoughtWorker_AlwaysActive.cs index 0ead8b2f0..451c74b3c 100644 --- a/Assembly-CSharp/RimWorld/ThoughtWorker_AlwaysActive.cs +++ b/Assembly-CSharp/RimWorld/ThoughtWorker_AlwaysActive.cs @@ -1,4 +1,3 @@ -using System; using Verse; namespace RimWorld diff --git a/Assembly-CSharp/RimWorld/ThoughtWorker_AnnoyingVoice.cs b/Assembly-CSharp/RimWorld/ThoughtWorker_AnnoyingVoice.cs index 290790587..c892a1db4 100644 --- a/Assembly-CSharp/RimWorld/ThoughtWorker_AnnoyingVoice.cs +++ b/Assembly-CSharp/RimWorld/ThoughtWorker_AnnoyingVoice.cs @@ -1,4 +1,3 @@ -using System; using Verse; namespace RimWorld @@ -7,19 +6,19 @@ public class ThoughtWorker_AnnoyingVoice : ThoughtWorker { protected override ThoughtState CurrentSocialStateInternal(Pawn pawn, Pawn other) { - if (!other.RaceProps.Humanlike || !RelationsUtility.PawnsKnowEachOther(pawn, other)) + if (other.RaceProps.Humanlike && RelationsUtility.PawnsKnowEachOther(pawn, other)) { - return false; + if (!other.story.traits.HasTrait(TraitDefOf.AnnoyingVoice)) + { + return false; + } + if (!pawn.health.capacities.CapableOf(PawnCapacityDefOf.Hearing)) + { + return false; + } + return true; } - if (!other.story.traits.HasTrait(TraitDefOf.AnnoyingVoice)) - { - return false; - } - if (!pawn.health.capacities.CapableOf(PawnCapacityDefOf.Hearing)) - { - return false; - } - return true; + return false; } } } diff --git a/Assembly-CSharp/RimWorld/ThoughtWorker_ApparelDamaged.cs b/Assembly-CSharp/RimWorld/ThoughtWorker_ApparelDamaged.cs index 8e5efbb13..e5cd8f629 100644 --- a/Assembly-CSharp/RimWorld/ThoughtWorker_ApparelDamaged.cs +++ b/Assembly-CSharp/RimWorld/ThoughtWorker_ApparelDamaged.cs @@ -1,4 +1,3 @@ -using System; using System.Collections.Generic; using Verse; @@ -23,13 +22,13 @@ protected override ThoughtState CurrentStateInternal(Pawn p) { num = num2; } - if (num < 0.2f) + if (num < 0.20000000298023224) { return ThoughtState.ActiveAtStage(1); } } } - if (num < 0.5f) + if (num < 0.5) { return ThoughtState.ActiveAtStage(0); } diff --git a/Assembly-CSharp/RimWorld/ThoughtWorker_Ascetic.cs b/Assembly-CSharp/RimWorld/ThoughtWorker_Ascetic.cs index 447499315..7d2ef51fb 100644 --- a/Assembly-CSharp/RimWorld/ThoughtWorker_Ascetic.cs +++ b/Assembly-CSharp/RimWorld/ThoughtWorker_Ascetic.cs @@ -1,4 +1,3 @@ -using System; using Verse; namespace RimWorld @@ -17,7 +16,7 @@ protected override ThoughtState CurrentStateInternal(Pawn p) return false; } int scoreStageIndex = RoomStatDefOf.Impressiveness.GetScoreStageIndex(ownedRoom.GetStat(RoomStatDefOf.Impressiveness)); - if (this.def.stages[scoreStageIndex] != null) + if (base.def.stages[scoreStageIndex] != null) { return ThoughtState.ActiveAtStage(scoreStageIndex); } diff --git a/Assembly-CSharp/RimWorld/ThoughtWorker_BedroomJealous.cs b/Assembly-CSharp/RimWorld/ThoughtWorker_BedroomJealous.cs index d218549d0..581a69bdb 100644 --- a/Assembly-CSharp/RimWorld/ThoughtWorker_BedroomJealous.cs +++ b/Assembly-CSharp/RimWorld/ThoughtWorker_BedroomJealous.cs @@ -1,4 +1,3 @@ -using System; using System.Collections.Generic; using UnityEngine; using Verse; @@ -28,7 +27,7 @@ protected override ThoughtState CurrentStateInternal(Pawn p) if (ownedRoom2 != null) { float stat = ownedRoom2.GetStat(RoomStatDefOf.Impressiveness); - if (stat - num >= Mathf.Abs(num * 0.1f)) + if (stat - num >= Mathf.Abs((float)(num * 0.10000000149011612))) { return ThoughtState.ActiveWithReason(list[i].LabelShort); } diff --git a/Assembly-CSharp/RimWorld/ThoughtWorker_BondedAnimalMaster.cs b/Assembly-CSharp/RimWorld/ThoughtWorker_BondedAnimalMaster.cs index 946b18755..98d3915b8 100644 --- a/Assembly-CSharp/RimWorld/ThoughtWorker_BondedAnimalMaster.cs +++ b/Assembly-CSharp/RimWorld/ThoughtWorker_BondedAnimalMaster.cs @@ -1,4 +1,3 @@ -using System; using System.Collections.Generic; using Verse; diff --git a/Assembly-CSharp/RimWorld/ThoughtWorker_CabinFever.cs b/Assembly-CSharp/RimWorld/ThoughtWorker_CabinFever.cs index ee9f9b442..2dd078940 100644 --- a/Assembly-CSharp/RimWorld/ThoughtWorker_CabinFever.cs +++ b/Assembly-CSharp/RimWorld/ThoughtWorker_CabinFever.cs @@ -1,4 +1,3 @@ -using System; using Verse; namespace RimWorld @@ -15,12 +14,12 @@ protected override ThoughtState CurrentStateInternal(Pawn p) { return ThoughtState.Inactive; } - float num = (float)p.needs.mood.recentMemory.TicksSinceOutdoors / 60000f; - if (num < 2.5f) + float num = (float)((float)p.needs.mood.recentMemory.TicksSinceOutdoors / 60000.0); + if (num < 2.5) { return ThoughtState.Inactive; } - if (num < 7.5f) + if (num < 7.5) { return ThoughtState.ActiveAtStage(0); } diff --git a/Assembly-CSharp/RimWorld/ThoughtWorker_ChemicalInterestVsTeetotaler.cs b/Assembly-CSharp/RimWorld/ThoughtWorker_ChemicalInterestVsTeetotaler.cs index e36270350..7a706a14c 100644 --- a/Assembly-CSharp/RimWorld/ThoughtWorker_ChemicalInterestVsTeetotaler.cs +++ b/Assembly-CSharp/RimWorld/ThoughtWorker_ChemicalInterestVsTeetotaler.cs @@ -1,4 +1,3 @@ -using System; using Verse; namespace RimWorld diff --git a/Assembly-CSharp/RimWorld/ThoughtWorker_Cold.cs b/Assembly-CSharp/RimWorld/ThoughtWorker_Cold.cs index f9068688d..1a2a584c7 100644 --- a/Assembly-CSharp/RimWorld/ThoughtWorker_Cold.cs +++ b/Assembly-CSharp/RimWorld/ThoughtWorker_Cold.cs @@ -1,4 +1,3 @@ -using System; using Verse; namespace RimWorld @@ -10,15 +9,15 @@ protected override ThoughtState CurrentStateInternal(Pawn p) float statValue = p.GetStatValue(StatDefOf.ComfyTemperatureMin, true); float ambientTemperature = p.AmbientTemperature; float num = statValue - ambientTemperature; - if (num <= 0f) + if (num <= 0.0) { return ThoughtState.Inactive; } - if (num < 10f) + if (num < 10.0) { return ThoughtState.ActiveAtStage(0); } - if (num < 20f) + if (num < 20.0) { return ThoughtState.ActiveAtStage(1); } diff --git a/Assembly-CSharp/RimWorld/ThoughtWorker_ColonistLeftUnburied.cs b/Assembly-CSharp/RimWorld/ThoughtWorker_ColonistLeftUnburied.cs index dca5fc5f9..3d04cc8a5 100644 --- a/Assembly-CSharp/RimWorld/ThoughtWorker_ColonistLeftUnburied.cs +++ b/Assembly-CSharp/RimWorld/ThoughtWorker_ColonistLeftUnburied.cs @@ -1,4 +1,3 @@ -using System; using System.Collections.Generic; using Verse; @@ -16,7 +15,7 @@ protected override ThoughtState CurrentStateInternal(Pawn p) for (int i = 0; i < list.Count; i++) { Corpse corpse = (Corpse)list[i]; - if ((float)corpse.Age > 90000f && corpse.InnerPawn.Faction == Faction.OfPlayer && corpse.InnerPawn.def.race.Humanlike && !corpse.IsInAnyStorage()) + if ((float)corpse.Age > 90000.0 && corpse.InnerPawn.Faction == Faction.OfPlayer && corpse.InnerPawn.def.race.Humanlike && !corpse.IsInAnyStorage()) { return true; } diff --git a/Assembly-CSharp/RimWorld/ThoughtWorker_CreepyBreathing.cs b/Assembly-CSharp/RimWorld/ThoughtWorker_CreepyBreathing.cs index 3281311e1..62f65bc41 100644 --- a/Assembly-CSharp/RimWorld/ThoughtWorker_CreepyBreathing.cs +++ b/Assembly-CSharp/RimWorld/ThoughtWorker_CreepyBreathing.cs @@ -1,4 +1,3 @@ -using System; using Verse; namespace RimWorld @@ -7,19 +6,19 @@ public class ThoughtWorker_CreepyBreathing : ThoughtWorker { protected override ThoughtState CurrentSocialStateInternal(Pawn pawn, Pawn other) { - if (!other.RaceProps.Humanlike || !RelationsUtility.PawnsKnowEachOther(pawn, other)) + if (other.RaceProps.Humanlike && RelationsUtility.PawnsKnowEachOther(pawn, other)) { - return false; + if (!other.story.traits.HasTrait(TraitDefOf.CreepyBreathing)) + { + return false; + } + if (!pawn.health.capacities.CapableOf(PawnCapacityDefOf.Hearing)) + { + return false; + } + return true; } - if (!other.story.traits.HasTrait(TraitDefOf.CreepyBreathing)) - { - return false; - } - if (!pawn.health.capacities.CapableOf(PawnCapacityDefOf.Hearing)) - { - return false; - } - return true; + return false; } } } diff --git a/Assembly-CSharp/RimWorld/ThoughtWorker_Dark.cs b/Assembly-CSharp/RimWorld/ThoughtWorker_Dark.cs index ba307afe6..47904c87f 100644 --- a/Assembly-CSharp/RimWorld/ThoughtWorker_Dark.cs +++ b/Assembly-CSharp/RimWorld/ThoughtWorker_Dark.cs @@ -1,4 +1,3 @@ -using System; using Verse; namespace RimWorld diff --git a/Assembly-CSharp/RimWorld/ThoughtWorker_DeadMansApparel.cs b/Assembly-CSharp/RimWorld/ThoughtWorker_DeadMansApparel.cs index d9e23bcd6..3e7f72a92 100644 --- a/Assembly-CSharp/RimWorld/ThoughtWorker_DeadMansApparel.cs +++ b/Assembly-CSharp/RimWorld/ThoughtWorker_DeadMansApparel.cs @@ -1,4 +1,3 @@ -using System; using System.Collections.Generic; using Verse; @@ -8,7 +7,7 @@ public class ThoughtWorker_DeadMansApparel : ThoughtWorker { protected override ThoughtState CurrentStateInternal(Pawn p) { - string text = null; + string text = (string)null; int num = 0; List wornApparel = p.apparel.WornApparel; for (int i = 0; i < wornApparel.Count; i++) diff --git a/Assembly-CSharp/RimWorld/ThoughtWorker_Disfigured.cs b/Assembly-CSharp/RimWorld/ThoughtWorker_Disfigured.cs index 27faf6907..c32d73a12 100644 --- a/Assembly-CSharp/RimWorld/ThoughtWorker_Disfigured.cs +++ b/Assembly-CSharp/RimWorld/ThoughtWorker_Disfigured.cs @@ -1,4 +1,3 @@ -using System; using Verse; namespace RimWorld @@ -7,23 +6,23 @@ public class ThoughtWorker_Disfigured : ThoughtWorker { protected override ThoughtState CurrentSocialStateInternal(Pawn pawn, Pawn other) { - if (!other.RaceProps.Humanlike || other.Dead) + if (other.RaceProps.Humanlike && !other.Dead) { - return false; + if (!RelationsUtility.PawnsKnowEachOther(pawn, other)) + { + return false; + } + if (!RelationsUtility.IsDisfigured(other)) + { + return false; + } + if (!pawn.health.capacities.CapableOf(PawnCapacityDefOf.Sight)) + { + return false; + } + return true; } - if (!RelationsUtility.PawnsKnowEachOther(pawn, other)) - { - return false; - } - if (!RelationsUtility.IsDisfigured(other)) - { - return false; - } - if (!pawn.health.capacities.CapableOf(PawnCapacityDefOf.Sight)) - { - return false; - } - return true; + return false; } } } diff --git a/Assembly-CSharp/RimWorld/ThoughtWorker_Drunk.cs b/Assembly-CSharp/RimWorld/ThoughtWorker_Drunk.cs index 55c4162b4..d7bf63625 100644 --- a/Assembly-CSharp/RimWorld/ThoughtWorker_Drunk.cs +++ b/Assembly-CSharp/RimWorld/ThoughtWorker_Drunk.cs @@ -1,4 +1,3 @@ -using System; using Verse; namespace RimWorld @@ -24,11 +23,11 @@ protected override ThoughtState CurrentSocialStateInternal(Pawn p, Pawn other) return false; } Hediff firstHediffOfDef = other.health.hediffSet.GetFirstHediffOfDef(HediffDefOf.AlcoholHigh, false); - if (firstHediffOfDef == null || !firstHediffOfDef.Visible) + if (firstHediffOfDef != null && firstHediffOfDef.Visible) { - return false; + return true; } - return true; + return false; } } } diff --git a/Assembly-CSharp/RimWorld/ThoughtWorker_Expectations.cs b/Assembly-CSharp/RimWorld/ThoughtWorker_Expectations.cs index 507f504b6..9901f847b 100644 --- a/Assembly-CSharp/RimWorld/ThoughtWorker_Expectations.cs +++ b/Assembly-CSharp/RimWorld/ThoughtWorker_Expectations.cs @@ -1,5 +1,4 @@ using RimWorld.Planet; -using System; using Verse; namespace RimWorld @@ -25,19 +24,19 @@ protected override ThoughtState CurrentStateInternal(Pawn p) return ThoughtState.Inactive; } float wealthTotal = p.MapHeld.wealthWatcher.WealthTotal; - if (wealthTotal < 10000f) + if (wealthTotal < 10000.0) { return ThoughtState.ActiveAtStage(3); } - if (wealthTotal < 50000f) + if (wealthTotal < 50000.0) { return ThoughtState.ActiveAtStage(2); } - if (wealthTotal < 150000f) + if (wealthTotal < 150000.0) { return ThoughtState.ActiveAtStage(1); } - if (wealthTotal < 300000f) + if (wealthTotal < 300000.0) { return ThoughtState.ActiveAtStage(0); } diff --git a/Assembly-CSharp/RimWorld/ThoughtWorker_Greedy.cs b/Assembly-CSharp/RimWorld/ThoughtWorker_Greedy.cs index 2882531ca..e9dbdcdc6 100644 --- a/Assembly-CSharp/RimWorld/ThoughtWorker_Greedy.cs +++ b/Assembly-CSharp/RimWorld/ThoughtWorker_Greedy.cs @@ -1,4 +1,3 @@ -using System; using Verse; namespace RimWorld @@ -17,7 +16,7 @@ protected override ThoughtState CurrentStateInternal(Pawn p) return ThoughtState.ActiveAtStage(0); } int scoreStageIndex = RoomStatDefOf.Impressiveness.GetScoreStageIndex(ownedRoom.GetStat(RoomStatDefOf.Impressiveness)); - if (this.def.stages[scoreStageIndex] != null) + if (base.def.stages[scoreStageIndex] != null) { return ThoughtState.ActiveAtStage(scoreStageIndex); } diff --git a/Assembly-CSharp/RimWorld/ThoughtWorker_HardWorkerVsLazy.cs b/Assembly-CSharp/RimWorld/ThoughtWorker_HardWorkerVsLazy.cs index 8ae2d39aa..cd5963ed3 100644 --- a/Assembly-CSharp/RimWorld/ThoughtWorker_HardWorkerVsLazy.cs +++ b/Assembly-CSharp/RimWorld/ThoughtWorker_HardWorkerVsLazy.cs @@ -1,4 +1,3 @@ -using System; using Verse; namespace RimWorld diff --git a/Assembly-CSharp/RimWorld/ThoughtWorker_HasBionicBodyPart.cs b/Assembly-CSharp/RimWorld/ThoughtWorker_HasBionicBodyPart.cs index 1523fb577..24197adee 100644 --- a/Assembly-CSharp/RimWorld/ThoughtWorker_HasBionicBodyPart.cs +++ b/Assembly-CSharp/RimWorld/ThoughtWorker_HasBionicBodyPart.cs @@ -1,4 +1,3 @@ -using System; using System.Collections.Generic; using Verse; diff --git a/Assembly-CSharp/RimWorld/ThoughtWorker_Hediff.cs b/Assembly-CSharp/RimWorld/ThoughtWorker_Hediff.cs index af095ab6c..7900346b3 100644 --- a/Assembly-CSharp/RimWorld/ThoughtWorker_Hediff.cs +++ b/Assembly-CSharp/RimWorld/ThoughtWorker_Hediff.cs @@ -1,4 +1,3 @@ -using System; using UnityEngine; using Verse; @@ -8,18 +7,13 @@ public class ThoughtWorker_Hediff : ThoughtWorker { protected override ThoughtState CurrentStateInternal(Pawn p) { - Hediff firstHediffOfDef = p.health.hediffSet.GetFirstHediffOfDef(this.def.hediff, false); - if (firstHediffOfDef == null || firstHediffOfDef.def.stages == null) + Hediff firstHediffOfDef = p.health.hediffSet.GetFirstHediffOfDef(base.def.hediff, false); + if (firstHediffOfDef != null && firstHediffOfDef.def.stages != null) { - return ThoughtState.Inactive; + int stageIndex = Mathf.Min(firstHediffOfDef.CurStageIndex, firstHediffOfDef.def.stages.Count - 1, base.def.stages.Count - 1); + return ThoughtState.ActiveAtStage(stageIndex); } - int stageIndex = Mathf.Min(new int[] - { - firstHediffOfDef.CurStageIndex, - firstHediffOfDef.def.stages.Count - 1, - this.def.stages.Count - 1 - }); - return ThoughtState.ActiveAtStage(stageIndex); + return ThoughtState.Inactive; } } } diff --git a/Assembly-CSharp/RimWorld/ThoughtWorker_HospitalPatientRoomStats.cs b/Assembly-CSharp/RimWorld/ThoughtWorker_HospitalPatientRoomStats.cs index 714e92e38..6e2546bc6 100644 --- a/Assembly-CSharp/RimWorld/ThoughtWorker_HospitalPatientRoomStats.cs +++ b/Assembly-CSharp/RimWorld/ThoughtWorker_HospitalPatientRoomStats.cs @@ -1,4 +1,3 @@ -using System; using Verse; namespace RimWorld @@ -8,20 +7,20 @@ public class ThoughtWorker_HospitalPatientRoomStats : ThoughtWorker protected override ThoughtState CurrentStateInternal(Pawn p) { Building_Bed building_Bed = p.CurrentBed(); - if (building_Bed == null || !building_Bed.Medical) + if (building_Bed != null && building_Bed.Medical) { + Room room = p.GetRoom(RegionType.Set_Passable); + if (room != null && room.Role == RoomRoleDefOf.Hospital) + { + int scoreStageIndex = RoomStatDefOf.Impressiveness.GetScoreStageIndex(room.GetStat(RoomStatDefOf.Impressiveness)); + if (base.def.stages[scoreStageIndex] != null) + { + return ThoughtState.ActiveAtStage(scoreStageIndex); + } + return ThoughtState.Inactive; + } return ThoughtState.Inactive; } - Room room = p.GetRoom(RegionType.Set_Passable); - if (room == null || room.Role != RoomRoleDefOf.Hospital) - { - return ThoughtState.Inactive; - } - int scoreStageIndex = RoomStatDefOf.Impressiveness.GetScoreStageIndex(room.GetStat(RoomStatDefOf.Impressiveness)); - if (this.def.stages[scoreStageIndex] != null) - { - return ThoughtState.ActiveAtStage(scoreStageIndex); - } return ThoughtState.Inactive; } } diff --git a/Assembly-CSharp/RimWorld/ThoughtWorker_Hot.cs b/Assembly-CSharp/RimWorld/ThoughtWorker_Hot.cs index bfd29a407..2e4ed8137 100644 --- a/Assembly-CSharp/RimWorld/ThoughtWorker_Hot.cs +++ b/Assembly-CSharp/RimWorld/ThoughtWorker_Hot.cs @@ -1,4 +1,3 @@ -using System; using Verse; namespace RimWorld @@ -10,19 +9,19 @@ protected override ThoughtState CurrentStateInternal(Pawn p) float statValue = p.GetStatValue(StatDefOf.ComfyTemperatureMax, true); float ambientTemperature = p.AmbientTemperature; float num = ambientTemperature - statValue; - if (num <= 0f) + if (num <= 0.0) { return ThoughtState.Inactive; } - if (num < 10f) + if (num < 10.0) { return ThoughtState.ActiveAtStage(0); } - if (num < 20f) + if (num < 20.0) { return ThoughtState.ActiveAtStage(1); } - if (num < 30f) + if (num < 30.0) { return ThoughtState.ActiveAtStage(2); } diff --git a/Assembly-CSharp/RimWorld/ThoughtWorker_HumanLeatherApparel.cs b/Assembly-CSharp/RimWorld/ThoughtWorker_HumanLeatherApparel.cs index 216c3e46e..3c0228e8e 100644 --- a/Assembly-CSharp/RimWorld/ThoughtWorker_HumanLeatherApparel.cs +++ b/Assembly-CSharp/RimWorld/ThoughtWorker_HumanLeatherApparel.cs @@ -1,4 +1,3 @@ -using System; using System.Collections.Generic; using Verse; @@ -8,7 +7,7 @@ public class ThoughtWorker_HumanLeatherApparel : ThoughtWorker { protected override ThoughtState CurrentStateInternal(Pawn p) { - string text = null; + string text = (string)null; int num = 0; List wornApparel = p.apparel.WornApparel; for (int i = 0; i < wornApparel.Count; i++) diff --git a/Assembly-CSharp/RimWorld/ThoughtWorker_Imprisoned.cs b/Assembly-CSharp/RimWorld/ThoughtWorker_Imprisoned.cs index baaf9e492..b51c58cd6 100644 --- a/Assembly-CSharp/RimWorld/ThoughtWorker_Imprisoned.cs +++ b/Assembly-CSharp/RimWorld/ThoughtWorker_Imprisoned.cs @@ -1,4 +1,3 @@ -using System; using Verse; namespace RimWorld diff --git a/Assembly-CSharp/RimWorld/ThoughtWorker_Incestuous.cs b/Assembly-CSharp/RimWorld/ThoughtWorker_Incestuous.cs index 989138d14..0f278a9a1 100644 --- a/Assembly-CSharp/RimWorld/ThoughtWorker_Incestuous.cs +++ b/Assembly-CSharp/RimWorld/ThoughtWorker_Incestuous.cs @@ -1,4 +1,3 @@ -using System; using Verse; namespace RimWorld @@ -15,7 +14,7 @@ protected override ThoughtState CurrentSocialStateInternal(Pawn pawn, Pawn other { return false; } - if (LovePartnerRelationUtility.IncestOpinionOffsetFor(other, pawn) == 0f) + if (LovePartnerRelationUtility.IncestOpinionOffsetFor(other, pawn) == 0.0) { return false; } diff --git a/Assembly-CSharp/RimWorld/ThoughtWorker_IsCarryingIncendiaryWeapon.cs b/Assembly-CSharp/RimWorld/ThoughtWorker_IsCarryingIncendiaryWeapon.cs index a60819602..cfeb87a8b 100644 --- a/Assembly-CSharp/RimWorld/ThoughtWorker_IsCarryingIncendiaryWeapon.cs +++ b/Assembly-CSharp/RimWorld/ThoughtWorker_IsCarryingIncendiaryWeapon.cs @@ -1,4 +1,3 @@ -using System; using System.Collections.Generic; using Verse; diff --git a/Assembly-CSharp/RimWorld/ThoughtWorker_IsCarryingRangedWeapon.cs b/Assembly-CSharp/RimWorld/ThoughtWorker_IsCarryingRangedWeapon.cs index 073fdda6d..ba9e5ee36 100644 --- a/Assembly-CSharp/RimWorld/ThoughtWorker_IsCarryingRangedWeapon.cs +++ b/Assembly-CSharp/RimWorld/ThoughtWorker_IsCarryingRangedWeapon.cs @@ -1,4 +1,3 @@ -using System; using Verse; namespace RimWorld diff --git a/Assembly-CSharp/RimWorld/ThoughtWorker_IsDayForNightOwl.cs b/Assembly-CSharp/RimWorld/ThoughtWorker_IsDayForNightOwl.cs index 6332e7108..01ef0b5b5 100644 --- a/Assembly-CSharp/RimWorld/ThoughtWorker_IsDayForNightOwl.cs +++ b/Assembly-CSharp/RimWorld/ThoughtWorker_IsDayForNightOwl.cs @@ -1,4 +1,3 @@ -using System; using Verse; namespace RimWorld diff --git a/Assembly-CSharp/RimWorld/ThoughtWorker_IsNightForNightOwl.cs b/Assembly-CSharp/RimWorld/ThoughtWorker_IsNightForNightOwl.cs index 2d69f2dfb..e011598c7 100644 --- a/Assembly-CSharp/RimWorld/ThoughtWorker_IsNightForNightOwl.cs +++ b/Assembly-CSharp/RimWorld/ThoughtWorker_IsNightForNightOwl.cs @@ -1,4 +1,3 @@ -using System; using Verse; namespace RimWorld diff --git a/Assembly-CSharp/RimWorld/ThoughtWorker_Man.cs b/Assembly-CSharp/RimWorld/ThoughtWorker_Man.cs index 12c991fa7..87f9c5a8f 100644 --- a/Assembly-CSharp/RimWorld/ThoughtWorker_Man.cs +++ b/Assembly-CSharp/RimWorld/ThoughtWorker_Man.cs @@ -1,4 +1,3 @@ -using System; using Verse; namespace RimWorld diff --git a/Assembly-CSharp/RimWorld/ThoughtWorker_NeedBeauty.cs b/Assembly-CSharp/RimWorld/ThoughtWorker_NeedBeauty.cs index 836ce64e5..a341ceed5 100644 --- a/Assembly-CSharp/RimWorld/ThoughtWorker_NeedBeauty.cs +++ b/Assembly-CSharp/RimWorld/ThoughtWorker_NeedBeauty.cs @@ -14,22 +14,38 @@ protected override ThoughtState CurrentStateInternal(Pawn p) switch (p.needs.beauty.CurCategory) { case BeautyCategory.Hideous: + { return ThoughtState.ActiveAtStage(0); + } case BeautyCategory.VeryUgly: + { return ThoughtState.ActiveAtStage(1); + } case BeautyCategory.Ugly: + { return ThoughtState.ActiveAtStage(2); + } case BeautyCategory.Neutral: + { return ThoughtState.Inactive; + } case BeautyCategory.Pretty: + { return ThoughtState.ActiveAtStage(3); + } case BeautyCategory.VeryPretty: + { return ThoughtState.ActiveAtStage(4); + } case BeautyCategory.Beautiful: + { return ThoughtState.ActiveAtStage(5); + } default: + { throw new InvalidOperationException("Unknown BeautyCategory"); } + } } } } diff --git a/Assembly-CSharp/RimWorld/ThoughtWorker_NeedComfort.cs b/Assembly-CSharp/RimWorld/ThoughtWorker_NeedComfort.cs index 59afe24b3..05655d46b 100644 --- a/Assembly-CSharp/RimWorld/ThoughtWorker_NeedComfort.cs +++ b/Assembly-CSharp/RimWorld/ThoughtWorker_NeedComfort.cs @@ -14,20 +14,34 @@ protected override ThoughtState CurrentStateInternal(Pawn p) switch (p.needs.comfort.CurCategory) { case ComfortCategory.Uncomfortable: + { return ThoughtState.ActiveAtStage(0); + } case ComfortCategory.Normal: + { return ThoughtState.Inactive; + } case ComfortCategory.Comfortable: + { return ThoughtState.ActiveAtStage(1); + } case ComfortCategory.VeryComfortable: + { return ThoughtState.ActiveAtStage(2); + } case ComfortCategory.ExtremelyComfortable: + { return ThoughtState.ActiveAtStage(3); + } case ComfortCategory.LuxuriantlyComfortable: + { return ThoughtState.ActiveAtStage(4); + } default: + { throw new NotImplementedException(); } + } } } } diff --git a/Assembly-CSharp/RimWorld/ThoughtWorker_NeedFood.cs b/Assembly-CSharp/RimWorld/ThoughtWorker_NeedFood.cs index d8fe1ed6c..302c83ff3 100644 --- a/Assembly-CSharp/RimWorld/ThoughtWorker_NeedFood.cs +++ b/Assembly-CSharp/RimWorld/ThoughtWorker_NeedFood.cs @@ -14,11 +14,17 @@ protected override ThoughtState CurrentStateInternal(Pawn p) switch (p.needs.food.CurCategory) { case HungerCategory.Fed: + { return ThoughtState.Inactive; + } case HungerCategory.Hungry: + { return ThoughtState.ActiveAtStage(0); + } case HungerCategory.UrgentlyHungry: + { return ThoughtState.ActiveAtStage(1); + } case HungerCategory.Starving: { Hediff firstHediffOfDef = p.health.hediffSet.GetFirstHediffOfDef(HediffDefOf.Malnutrition, false); @@ -26,8 +32,10 @@ protected override ThoughtState CurrentStateInternal(Pawn p) return ThoughtState.ActiveAtStage(2 + num); } default: + { throw new NotImplementedException(); } + } } } } diff --git a/Assembly-CSharp/RimWorld/ThoughtWorker_NeedJoy.cs b/Assembly-CSharp/RimWorld/ThoughtWorker_NeedJoy.cs index f3344f637..2564f4373 100644 --- a/Assembly-CSharp/RimWorld/ThoughtWorker_NeedJoy.cs +++ b/Assembly-CSharp/RimWorld/ThoughtWorker_NeedJoy.cs @@ -14,20 +14,34 @@ protected override ThoughtState CurrentStateInternal(Pawn p) switch (p.needs.joy.CurCategory) { case JoyCategory.Empty: + { return ThoughtState.ActiveAtStage(0); + } case JoyCategory.VeryLow: + { return ThoughtState.ActiveAtStage(1); + } case JoyCategory.Low: + { return ThoughtState.ActiveAtStage(2); + } case JoyCategory.Satisfied: + { return ThoughtState.Inactive; + } case JoyCategory.High: + { return ThoughtState.ActiveAtStage(3); + } case JoyCategory.Extreme: + { return ThoughtState.ActiveAtStage(4); + } default: + { throw new NotImplementedException(); } + } } } } diff --git a/Assembly-CSharp/RimWorld/ThoughtWorker_NeedRest.cs b/Assembly-CSharp/RimWorld/ThoughtWorker_NeedRest.cs index 1ca7c247f..5b7750ca2 100644 --- a/Assembly-CSharp/RimWorld/ThoughtWorker_NeedRest.cs +++ b/Assembly-CSharp/RimWorld/ThoughtWorker_NeedRest.cs @@ -14,16 +14,26 @@ protected override ThoughtState CurrentStateInternal(Pawn p) switch (p.needs.rest.CurCategory) { case RestCategory.Rested: + { return ThoughtState.Inactive; + } case RestCategory.Tired: + { return ThoughtState.ActiveAtStage(0); + } case RestCategory.VeryTired: + { return ThoughtState.ActiveAtStage(1); + } case RestCategory.Exhausted: + { return ThoughtState.ActiveAtStage(2); + } default: + { throw new NotImplementedException(); } + } } } } diff --git a/Assembly-CSharp/RimWorld/ThoughtWorker_NeedSpace.cs b/Assembly-CSharp/RimWorld/ThoughtWorker_NeedSpace.cs index 1296225e0..c5c5899d6 100644 --- a/Assembly-CSharp/RimWorld/ThoughtWorker_NeedSpace.cs +++ b/Assembly-CSharp/RimWorld/ThoughtWorker_NeedSpace.cs @@ -12,23 +12,33 @@ protected override ThoughtState CurrentStateInternal(Pawn p) return ThoughtState.Inactive; } Room room = p.GetRoom(RegionType.Set_Passable); - if (room == null || room.PsychologicallyOutdoors) + if (room != null && !room.PsychologicallyOutdoors) { - return ThoughtState.Inactive; - } - switch (p.needs.space.CurCategory) - { - case SpaceCategory.VeryCramped: - return ThoughtState.ActiveAtStage(0); - case SpaceCategory.Cramped: - return ThoughtState.ActiveAtStage(1); - case SpaceCategory.Normal: - return ThoughtState.Inactive; - case SpaceCategory.Spacious: - return ThoughtState.ActiveAtStage(2); - default: - throw new InvalidOperationException("Unknown SpaceCategory"); + switch (p.needs.space.CurCategory) + { + case SpaceCategory.VeryCramped: + { + return ThoughtState.ActiveAtStage(0); + } + case SpaceCategory.Cramped: + { + return ThoughtState.ActiveAtStage(1); + } + case SpaceCategory.Normal: + { + return ThoughtState.Inactive; + } + case SpaceCategory.Spacious: + { + return ThoughtState.ActiveAtStage(2); + } + default: + { + throw new InvalidOperationException("Unknown SpaceCategory"); + } + } } + return ThoughtState.Inactive; } } } diff --git a/Assembly-CSharp/RimWorld/ThoughtWorker_NotBondedAnimalMaster.cs b/Assembly-CSharp/RimWorld/ThoughtWorker_NotBondedAnimalMaster.cs index 53a6f9e7b..d8bac9757 100644 --- a/Assembly-CSharp/RimWorld/ThoughtWorker_NotBondedAnimalMaster.cs +++ b/Assembly-CSharp/RimWorld/ThoughtWorker_NotBondedAnimalMaster.cs @@ -1,4 +1,3 @@ -using System; using Verse; namespace RimWorld diff --git a/Assembly-CSharp/RimWorld/ThoughtWorker_NudistNude.cs b/Assembly-CSharp/RimWorld/ThoughtWorker_NudistNude.cs index c0fcd07db..ca07f94d4 100644 --- a/Assembly-CSharp/RimWorld/ThoughtWorker_NudistNude.cs +++ b/Assembly-CSharp/RimWorld/ThoughtWorker_NudistNude.cs @@ -1,4 +1,3 @@ -using System; using System.Collections.Generic; using Verse; diff --git a/Assembly-CSharp/RimWorld/ThoughtWorker_OpinionOfMyLover.cs b/Assembly-CSharp/RimWorld/ThoughtWorker_OpinionOfMyLover.cs index 327f8512b..787ecda02 100644 --- a/Assembly-CSharp/RimWorld/ThoughtWorker_OpinionOfMyLover.cs +++ b/Assembly-CSharp/RimWorld/ThoughtWorker_OpinionOfMyLover.cs @@ -1,5 +1,4 @@ using RimWorld.Planet; -using System; using Verse; namespace RimWorld @@ -13,11 +12,11 @@ protected override ThoughtState CurrentStateInternal(Pawn p) { return false; } - if (!directPawnRelation.otherPawn.IsColonist || directPawnRelation.otherPawn.IsWorldPawn() || !directPawnRelation.otherPawn.relations.everSeenByPlayer) + if (directPawnRelation.otherPawn.IsColonist && !directPawnRelation.otherPawn.IsWorldPawn() && directPawnRelation.otherPawn.relations.everSeenByPlayer) { - return false; + return p.relations.OpinionOf(directPawnRelation.otherPawn) != 0; } - return p.relations.OpinionOf(directPawnRelation.otherPawn) != 0; + return false; } } } diff --git a/Assembly-CSharp/RimWorld/ThoughtWorker_Pain.cs b/Assembly-CSharp/RimWorld/ThoughtWorker_Pain.cs index 7b8c2ebcd..49a421bd6 100644 --- a/Assembly-CSharp/RimWorld/ThoughtWorker_Pain.cs +++ b/Assembly-CSharp/RimWorld/ThoughtWorker_Pain.cs @@ -1,4 +1,3 @@ -using System; using Verse; namespace RimWorld @@ -8,19 +7,19 @@ public class ThoughtWorker_Pain : ThoughtWorker protected override ThoughtState CurrentStateInternal(Pawn p) { float painTotal = p.health.hediffSet.PainTotal; - if (painTotal < 0.0001f) + if (painTotal < 9.9999997473787516E-05) { return ThoughtState.Inactive; } - if (painTotal < 0.15f) + if (painTotal < 0.15000000596046448) { return ThoughtState.ActiveAtStage(0); } - if (painTotal < 0.4f) + if (painTotal < 0.40000000596046448) { return ThoughtState.ActiveAtStage(1); } - if (painTotal < 0.8f) + if (painTotal < 0.800000011920929) { return ThoughtState.ActiveAtStage(2); } diff --git a/Assembly-CSharp/RimWorld/ThoughtWorker_Pretty.cs b/Assembly-CSharp/RimWorld/ThoughtWorker_Pretty.cs index d59477c10..c751aff07 100644 --- a/Assembly-CSharp/RimWorld/ThoughtWorker_Pretty.cs +++ b/Assembly-CSharp/RimWorld/ThoughtWorker_Pretty.cs @@ -1,4 +1,3 @@ -using System; using Verse; namespace RimWorld @@ -7,26 +6,31 @@ public class ThoughtWorker_Pretty : ThoughtWorker { protected override ThoughtState CurrentSocialStateInternal(Pawn pawn, Pawn other) { - if (!other.RaceProps.Humanlike || !RelationsUtility.PawnsKnowEachOther(pawn, other)) + if (other.RaceProps.Humanlike && RelationsUtility.PawnsKnowEachOther(pawn, other)) { - return false; - } - if (RelationsUtility.IsDisfigured(other)) - { - return false; - } - if (!pawn.health.capacities.CapableOf(PawnCapacityDefOf.Sight)) - { - return false; - } - int num = other.story.traits.DegreeOfTrait(TraitDefOf.Beauty); - if (num == 1) - { - return ThoughtState.ActiveAtStage(0); - } - if (num == 2) - { - return ThoughtState.ActiveAtStage(1); + if (RelationsUtility.IsDisfigured(other)) + { + return false; + } + if (!pawn.health.capacities.CapableOf(PawnCapacityDefOf.Sight)) + { + return false; + } + switch (other.story.traits.DegreeOfTrait(TraitDefOf.Beauty)) + { + case 1: + { + return ThoughtState.ActiveAtStage(0); + } + case 2: + { + return ThoughtState.ActiveAtStage(1); + } + default: + { + return false; + } + } } return false; } diff --git a/Assembly-CSharp/RimWorld/ThoughtWorker_PrisonBarracksImpressiveness.cs b/Assembly-CSharp/RimWorld/ThoughtWorker_PrisonBarracksImpressiveness.cs index a3abb3b9c..fafe40302 100644 --- a/Assembly-CSharp/RimWorld/ThoughtWorker_PrisonBarracksImpressiveness.cs +++ b/Assembly-CSharp/RimWorld/ThoughtWorker_PrisonBarracksImpressiveness.cs @@ -1,4 +1,3 @@ -using System; using Verse; namespace RimWorld diff --git a/Assembly-CSharp/RimWorld/ThoughtWorker_PrisonCellImpressiveness.cs b/Assembly-CSharp/RimWorld/ThoughtWorker_PrisonCellImpressiveness.cs index ab974356d..af1a27407 100644 --- a/Assembly-CSharp/RimWorld/ThoughtWorker_PrisonCellImpressiveness.cs +++ b/Assembly-CSharp/RimWorld/ThoughtWorker_PrisonCellImpressiveness.cs @@ -1,4 +1,3 @@ -using System; using Verse; namespace RimWorld diff --git a/Assembly-CSharp/RimWorld/ThoughtWorker_PsychicDrone.cs b/Assembly-CSharp/RimWorld/ThoughtWorker_PsychicDrone.cs index 5dd945201..40c99cfd0 100644 --- a/Assembly-CSharp/RimWorld/ThoughtWorker_PsychicDrone.cs +++ b/Assembly-CSharp/RimWorld/ThoughtWorker_PsychicDrone.cs @@ -15,27 +15,41 @@ protected override ThoughtState CurrentStateInternal(Pawn p) psychicDroneLevel = building_PsychicEmanator.droneLevel; } GameCondition_PsychicEmanation activeCondition = p.Map.gameConditionManager.GetActiveCondition(); - if (activeCondition != null && activeCondition.gender == p.gender && activeCondition.def.droneLevel > psychicDroneLevel) + if (activeCondition != null && activeCondition.gender == p.gender && (int)activeCondition.def.droneLevel > (int)psychicDroneLevel) { psychicDroneLevel = activeCondition.def.droneLevel; } switch (psychicDroneLevel) { case PsychicDroneLevel.None: + { return false; + } case PsychicDroneLevel.GoodMedium: + { return ThoughtState.ActiveAtStage(0); + } case PsychicDroneLevel.BadLow: + { return ThoughtState.ActiveAtStage(1); + } case PsychicDroneLevel.BadMedium: + { return ThoughtState.ActiveAtStage(2); + } case PsychicDroneLevel.BadHigh: + { return ThoughtState.ActiveAtStage(3); + } case PsychicDroneLevel.BadExtreme: + { return ThoughtState.ActiveAtStage(4); + } default: + { throw new NotImplementedException(); } + } } private static Building_PsychicEmanator ExtantShipPart(Map map) diff --git a/Assembly-CSharp/RimWorld/ThoughtWorker_PsychologicallyNude.cs b/Assembly-CSharp/RimWorld/ThoughtWorker_PsychologicallyNude.cs index 6e90020bd..9b19691ae 100644 --- a/Assembly-CSharp/RimWorld/ThoughtWorker_PsychologicallyNude.cs +++ b/Assembly-CSharp/RimWorld/ThoughtWorker_PsychologicallyNude.cs @@ -1,4 +1,3 @@ -using System; using Verse; namespace RimWorld diff --git a/Assembly-CSharp/RimWorld/ThoughtWorker_RandomMood.cs b/Assembly-CSharp/RimWorld/ThoughtWorker_RandomMood.cs index 684ac232a..4f2524ed3 100644 --- a/Assembly-CSharp/RimWorld/ThoughtWorker_RandomMood.cs +++ b/Assembly-CSharp/RimWorld/ThoughtWorker_RandomMood.cs @@ -10,28 +10,50 @@ protected override ThoughtState CurrentStateInternal(Pawn p) switch ((p.GetHashCode() ^ (GenLocalDate.DayOfYear(p) + GenLocalDate.Year(p) * 60) * 391) % 10) { case 0: + { return ThoughtState.ActiveAtStage(0); + } case 1: + { return ThoughtState.ActiveAtStage(1); + } case 2: + { return ThoughtState.ActiveAtStage(1); + } case 3: + { return ThoughtState.ActiveAtStage(1); + } case 4: + { return ThoughtState.Inactive; + } case 5: + { return ThoughtState.Inactive; + } case 6: + { return ThoughtState.ActiveAtStage(2); + } case 7: + { return ThoughtState.ActiveAtStage(2); + } case 8: + { return ThoughtState.ActiveAtStage(2); + } case 9: + { return ThoughtState.ActiveAtStage(3); + } default: + { throw new NotImplementedException(); } + } } } } diff --git a/Assembly-CSharp/RimWorld/ThoughtWorker_RoomImpressiveness.cs b/Assembly-CSharp/RimWorld/ThoughtWorker_RoomImpressiveness.cs index 326a9ae47..09648a0d3 100644 --- a/Assembly-CSharp/RimWorld/ThoughtWorker_RoomImpressiveness.cs +++ b/Assembly-CSharp/RimWorld/ThoughtWorker_RoomImpressiveness.cs @@ -1,4 +1,3 @@ -using System; using Verse; namespace RimWorld @@ -17,7 +16,7 @@ protected override ThoughtState CurrentStateInternal(Pawn p) return ThoughtState.Inactive; } int scoreStageIndex = RoomStatDefOf.Impressiveness.GetScoreStageIndex(room.GetStat(RoomStatDefOf.Impressiveness)); - if (this.def.stages[scoreStageIndex] == null) + if (base.def.stages[scoreStageIndex] == null) { return ThoughtState.Inactive; } diff --git a/Assembly-CSharp/RimWorld/ThoughtWorker_SharedBed.cs b/Assembly-CSharp/RimWorld/ThoughtWorker_SharedBed.cs index 48123bbd7..9b3898edd 100644 --- a/Assembly-CSharp/RimWorld/ThoughtWorker_SharedBed.cs +++ b/Assembly-CSharp/RimWorld/ThoughtWorker_SharedBed.cs @@ -1,4 +1,3 @@ -using System; using Verse; namespace RimWorld diff --git a/Assembly-CSharp/RimWorld/ThoughtWorker_Sick.cs b/Assembly-CSharp/RimWorld/ThoughtWorker_Sick.cs index e9e19e51a..967bb3ae8 100644 --- a/Assembly-CSharp/RimWorld/ThoughtWorker_Sick.cs +++ b/Assembly-CSharp/RimWorld/ThoughtWorker_Sick.cs @@ -1,4 +1,3 @@ -using System; using Verse; namespace RimWorld diff --git a/Assembly-CSharp/RimWorld/ThoughtWorker_Tale.cs b/Assembly-CSharp/RimWorld/ThoughtWorker_Tale.cs index 39888267a..c08152445 100644 --- a/Assembly-CSharp/RimWorld/ThoughtWorker_Tale.cs +++ b/Assembly-CSharp/RimWorld/ThoughtWorker_Tale.cs @@ -1,4 +1,3 @@ -using System; using Verse; namespace RimWorld @@ -15,7 +14,7 @@ protected override ThoughtState CurrentSocialStateInternal(Pawn p, Pawn other) { return false; } - if (Find.TaleManager.GetLatestTale(this.def.taleDef, other) == null) + if (Find.TaleManager.GetLatestTale(base.def.taleDef, other) == null) { return false; } diff --git a/Assembly-CSharp/RimWorld/ThoughtWorker_TeetotalerVsAddict.cs b/Assembly-CSharp/RimWorld/ThoughtWorker_TeetotalerVsAddict.cs index be464c71a..9c5508344 100644 --- a/Assembly-CSharp/RimWorld/ThoughtWorker_TeetotalerVsAddict.cs +++ b/Assembly-CSharp/RimWorld/ThoughtWorker_TeetotalerVsAddict.cs @@ -1,4 +1,3 @@ -using System; using System.Collections.Generic; using Verse; diff --git a/Assembly-CSharp/RimWorld/ThoughtWorker_TeetotalerVsChemicalInterest.cs b/Assembly-CSharp/RimWorld/ThoughtWorker_TeetotalerVsChemicalInterest.cs index 83851a21e..b758bd97f 100644 --- a/Assembly-CSharp/RimWorld/ThoughtWorker_TeetotalerVsChemicalInterest.cs +++ b/Assembly-CSharp/RimWorld/ThoughtWorker_TeetotalerVsChemicalInterest.cs @@ -1,4 +1,3 @@ -using System; using Verse; namespace RimWorld diff --git a/Assembly-CSharp/RimWorld/ThoughtWorker_Ugly.cs b/Assembly-CSharp/RimWorld/ThoughtWorker_Ugly.cs index 58537a936..6ea0ce319 100644 --- a/Assembly-CSharp/RimWorld/ThoughtWorker_Ugly.cs +++ b/Assembly-CSharp/RimWorld/ThoughtWorker_Ugly.cs @@ -1,4 +1,3 @@ -using System; using Verse; namespace RimWorld @@ -7,22 +6,27 @@ public class ThoughtWorker_Ugly : ThoughtWorker { protected override ThoughtState CurrentSocialStateInternal(Pawn pawn, Pawn other) { - if (!other.RaceProps.Humanlike || !RelationsUtility.PawnsKnowEachOther(pawn, other)) + if (other.RaceProps.Humanlike && RelationsUtility.PawnsKnowEachOther(pawn, other)) { - return false; - } - if (!pawn.health.capacities.CapableOf(PawnCapacityDefOf.Sight)) - { - return false; - } - int num = other.story.traits.DegreeOfTrait(TraitDefOf.Beauty); - if (num == -1) - { - return ThoughtState.ActiveAtStage(0); - } - if (num == -2) - { - return ThoughtState.ActiveAtStage(1); + if (!pawn.health.capacities.CapableOf(PawnCapacityDefOf.Sight)) + { + return false; + } + switch (other.story.traits.DegreeOfTrait(TraitDefOf.Beauty)) + { + case -1: + { + return ThoughtState.ActiveAtStage(0); + } + case -2: + { + return ThoughtState.ActiveAtStage(1); + } + default: + { + return false; + } + } } return false; } diff --git a/Assembly-CSharp/RimWorld/ThoughtWorker_WantToSleepWithSpouseOrLover.cs b/Assembly-CSharp/RimWorld/ThoughtWorker_WantToSleepWithSpouseOrLover.cs index e785583be..4832840e9 100644 --- a/Assembly-CSharp/RimWorld/ThoughtWorker_WantToSleepWithSpouseOrLover.cs +++ b/Assembly-CSharp/RimWorld/ThoughtWorker_WantToSleepWithSpouseOrLover.cs @@ -1,5 +1,4 @@ using RimWorld.Planet; -using System; using Verse; namespace RimWorld @@ -13,19 +12,19 @@ protected override ThoughtState CurrentStateInternal(Pawn p) { return false; } - if (!directPawnRelation.otherPawn.IsColonist || directPawnRelation.otherPawn.IsWorldPawn() || !directPawnRelation.otherPawn.relations.everSeenByPlayer) + if (directPawnRelation.otherPawn.IsColonist && !directPawnRelation.otherPawn.IsWorldPawn() && directPawnRelation.otherPawn.relations.everSeenByPlayer) { - return false; - } - if (p.ownership.OwnedBed != null && p.ownership.OwnedBed == directPawnRelation.otherPawn.ownership.OwnedBed) - { - return false; - } - if (p.relations.OpinionOf(directPawnRelation.otherPawn) <= 0) - { - return false; + if (p.ownership.OwnedBed != null && p.ownership.OwnedBed == directPawnRelation.otherPawn.ownership.OwnedBed) + { + return false; + } + if (p.relations.OpinionOf(directPawnRelation.otherPawn) <= 0) + { + return false; + } + return true; } - return true; + return false; } } } diff --git a/Assembly-CSharp/RimWorld/ThoughtWorker_Woman.cs b/Assembly-CSharp/RimWorld/ThoughtWorker_Woman.cs index 08c4f91c6..1fb047bd4 100644 --- a/Assembly-CSharp/RimWorld/ThoughtWorker_Woman.cs +++ b/Assembly-CSharp/RimWorld/ThoughtWorker_Woman.cs @@ -1,4 +1,3 @@ -using System; using Verse; namespace RimWorld diff --git a/Assembly-CSharp/RimWorld/Thought_ChemicalInterestVsTeetotaler.cs b/Assembly-CSharp/RimWorld/Thought_ChemicalInterestVsTeetotaler.cs index e2185540e..f6a762083 100644 --- a/Assembly-CSharp/RimWorld/Thought_ChemicalInterestVsTeetotaler.cs +++ b/Assembly-CSharp/RimWorld/Thought_ChemicalInterestVsTeetotaler.cs @@ -1,13 +1,11 @@ -using System; - namespace RimWorld { public class Thought_ChemicalInterestVsTeetotaler : Thought_SituationalSocial { public override float OpinionOffset() { - int num = this.pawn.story.traits.DegreeOfTrait(TraitDefOf.DrugDesire); - int num2 = this.otherPawn.story.traits.DegreeOfTrait(TraitDefOf.DrugDesire); + int num = base.pawn.story.traits.DegreeOfTrait(TraitDefOf.DrugDesire); + int num2 = base.otherPawn.story.traits.DegreeOfTrait(TraitDefOf.DrugDesire); if (num2 >= 0) { return 0f; diff --git a/Assembly-CSharp/RimWorld/Thought_Dumb.cs b/Assembly-CSharp/RimWorld/Thought_Dumb.cs index 5416ce36d..26f9fa4de 100644 --- a/Assembly-CSharp/RimWorld/Thought_Dumb.cs +++ b/Assembly-CSharp/RimWorld/Thought_Dumb.cs @@ -1,4 +1,3 @@ -using System; using Verse; namespace RimWorld diff --git a/Assembly-CSharp/RimWorld/Thought_HardWorkerVsLazy.cs b/Assembly-CSharp/RimWorld/Thought_HardWorkerVsLazy.cs index 277683ed8..349648659 100644 --- a/Assembly-CSharp/RimWorld/Thought_HardWorkerVsLazy.cs +++ b/Assembly-CSharp/RimWorld/Thought_HardWorkerVsLazy.cs @@ -1,25 +1,29 @@ -using System; - namespace RimWorld { public class Thought_HardWorkerVsLazy : Thought_SituationalSocial { public override float OpinionOffset() { - int num = this.otherPawn.story.traits.DegreeOfTrait(TraitDefOf.Industriousness); + int num = base.otherPawn.story.traits.DegreeOfTrait(TraitDefOf.Industriousness); if (num > 0) { return 0f; } - if (num == 0) + switch (num) + { + case 0: { return -5f; } - if (num == -1) + case -1: { return -20f; } - return -30f; + default: + { + return -30f; + } + } } } } diff --git a/Assembly-CSharp/RimWorld/Thought_Incestuous.cs b/Assembly-CSharp/RimWorld/Thought_Incestuous.cs index d903184ce..c38125e0c 100644 --- a/Assembly-CSharp/RimWorld/Thought_Incestuous.cs +++ b/Assembly-CSharp/RimWorld/Thought_Incestuous.cs @@ -1,12 +1,10 @@ -using System; - namespace RimWorld { public class Thought_Incestuous : Thought_SituationalSocial { public override float OpinionOffset() { - return LovePartnerRelationUtility.IncestOpinionOffsetFor(this.otherPawn, this.pawn); + return LovePartnerRelationUtility.IncestOpinionOffsetFor(base.otherPawn, base.pawn); } } } diff --git a/Assembly-CSharp/RimWorld/Thought_Memory.cs b/Assembly-CSharp/RimWorld/Thought_Memory.cs index eb4607c01..dfa1ae1e1 100644 --- a/Assembly-CSharp/RimWorld/Thought_Memory.cs +++ b/Assembly-CSharp/RimWorld/Thought_Memory.cs @@ -1,4 +1,3 @@ -using System; using Verse; namespace RimWorld @@ -39,7 +38,7 @@ public virtual bool ShouldDiscard { get { - return this.age > this.def.DurationTicks; + return this.age > base.def.DurationTicks; } } @@ -90,8 +89,8 @@ public void Renew() public virtual bool TryMergeWithExistingMemory(out bool showBubble) { - ThoughtHandler thoughts = this.pawn.needs.mood.thoughts; - if (thoughts.memories.NumMemoriesInGroup(this) >= this.def.stackLimit) + ThoughtHandler thoughts = base.pawn.needs.mood.thoughts; + if (thoughts.memories.NumMemoriesInGroup(this) >= base.def.stackLimit) { Thought_Memory thought_Memory = thoughts.memories.OldestMemoryInGroup(this); if (thought_Memory != null) @@ -108,7 +107,11 @@ public virtual bool TryMergeWithExistingMemory(out bool showBubble) public override bool GroupsWith(Thought other) { Thought_Memory thought_Memory = other as Thought_Memory; - return thought_Memory != null && base.GroupsWith(other) && (this.otherPawn == thought_Memory.otherPawn || this.LabelCap == thought_Memory.LabelCap); + if (thought_Memory == null) + { + return false; + } + return base.GroupsWith(other) && (this.otherPawn == thought_Memory.otherPawn || this.LabelCap == thought_Memory.LabelCap); } public override float MoodOffset() @@ -119,16 +122,7 @@ public override float MoodOffset() public override string ToString() { - return string.Concat(new object[] - { - "(", - this.def.defName, - ", moodPowerFactor=", - this.moodPowerFactor, - ", age=", - this.age, - ")" - }); + return "(" + base.def.defName + ", moodPowerFactor=" + this.moodPowerFactor + ", age=" + this.age + ")"; } } } diff --git a/Assembly-CSharp/RimWorld/Thought_MemoryObservation.cs b/Assembly-CSharp/RimWorld/Thought_MemoryObservation.cs index d4584861f..40b146c71 100644 --- a/Assembly-CSharp/RimWorld/Thought_MemoryObservation.cs +++ b/Assembly-CSharp/RimWorld/Thought_MemoryObservation.cs @@ -1,4 +1,3 @@ -using System; using System.Collections.Generic; using Verse; @@ -24,13 +23,13 @@ public override void ExposeData() public override bool TryMergeWithExistingMemory(out bool showBubble) { - ThoughtHandler thoughts = this.pawn.needs.mood.thoughts; + ThoughtHandler thoughts = base.pawn.needs.mood.thoughts; Thought_MemoryObservation thought_MemoryObservation = null; List memories = thoughts.memories.Memories; for (int i = 0; i < memories.Count; i++) { Thought_MemoryObservation thought_MemoryObservation2 = memories[i] as Thought_MemoryObservation; - if (thought_MemoryObservation2 != null && thought_MemoryObservation2.def == this.def && thought_MemoryObservation2.targetThingID == this.targetThingID && (thought_MemoryObservation == null || thought_MemoryObservation2.age > thought_MemoryObservation.age)) + if (thought_MemoryObservation2 != null && thought_MemoryObservation2.def == base.def && thought_MemoryObservation2.targetThingID == this.targetThingID && (thought_MemoryObservation == null || thought_MemoryObservation2.age > thought_MemoryObservation.age)) { thought_MemoryObservation = thought_MemoryObservation2; } diff --git a/Assembly-CSharp/RimWorld/Thought_MemorySocial.cs b/Assembly-CSharp/RimWorld/Thought_MemorySocial.cs index e8d1f6437..387f3a412 100644 --- a/Assembly-CSharp/RimWorld/Thought_MemorySocial.cs +++ b/Assembly-CSharp/RimWorld/Thought_MemorySocial.cs @@ -1,4 +1,3 @@ -using System; using UnityEngine; using Verse; @@ -12,7 +11,7 @@ public override bool ShouldDiscard { get { - return this.otherPawn == null || this.opinionOffset == 0f || base.ShouldDiscard; + return base.otherPawn == null || this.opinionOffset == 0.0 || base.ShouldDiscard; } } @@ -20,7 +19,7 @@ public override bool VisibleInNeedsTab { get { - return base.VisibleInNeedsTab && this.MoodOffset() != 0f; + return base.VisibleInNeedsTab && this.MoodOffset() != 0.0; } } @@ -28,7 +27,7 @@ private float AgePct { get { - return (float)this.age / (float)this.def.DurationTicks; + return (float)base.age / (float)base.def.DurationTicks; } } @@ -36,7 +35,7 @@ private float AgeFactor { get { - return Mathf.InverseLerp(1f, this.def.lerpOpinionToZeroAfterDurationPct, this.AgePct); + return Mathf.InverseLerp(1f, base.def.lerpOpinionToZeroAfterDurationPct, this.AgePct); } } @@ -51,7 +50,7 @@ public virtual float OpinionOffset() public Pawn OtherPawn() { - return this.otherPawn; + return base.otherPawn; } public override void ExposeData() @@ -75,7 +74,11 @@ public override bool TryMergeWithExistingMemory(out bool showBubble) public override bool GroupsWith(Thought other) { Thought_MemorySocial thought_MemorySocial = other as Thought_MemorySocial; - return thought_MemorySocial != null && base.GroupsWith(other) && this.otherPawn == thought_MemorySocial.otherPawn; + if (thought_MemorySocial == null) + { + return false; + } + return base.GroupsWith(other) && base.otherPawn == thought_MemorySocial.otherPawn; } } } diff --git a/Assembly-CSharp/RimWorld/Thought_MemorySocialCumulative.cs b/Assembly-CSharp/RimWorld/Thought_MemorySocialCumulative.cs index 14f28d607..977b2d4b4 100644 --- a/Assembly-CSharp/RimWorld/Thought_MemorySocialCumulative.cs +++ b/Assembly-CSharp/RimWorld/Thought_MemorySocialCumulative.cs @@ -1,4 +1,3 @@ -using System; using System.Collections.Generic; using UnityEngine; @@ -12,7 +11,7 @@ public override bool ShouldDiscard { get { - return this.opinionOffset == 0f; + return base.opinionOffset == 0.0; } } @@ -22,46 +21,46 @@ public override float OpinionOffset() { return 0f; } - return Mathf.Min(this.opinionOffset, this.def.maxCumulatedOpinionOffset); + return Mathf.Min(base.opinionOffset, base.def.maxCumulatedOpinionOffset); } public override void ThoughtInterval() { base.ThoughtInterval(); - if (this.age >= 60000) + if (base.age >= 60000) { - if (this.opinionOffset < 0f) + if (base.opinionOffset < 0.0) { - this.opinionOffset += 1f; - if (this.opinionOffset > 0f) + base.opinionOffset += 1f; + if (base.opinionOffset > 0.0) { - this.opinionOffset = 0f; + base.opinionOffset = 0f; } } - else if (this.opinionOffset > 0f) + else if (base.opinionOffset > 0.0) { - this.opinionOffset -= 1f; - if (this.opinionOffset < 0f) + base.opinionOffset -= 1f; + if (base.opinionOffset < 0.0) { - this.opinionOffset = 0f; + base.opinionOffset = 0f; } } - this.age = 0; + base.age = 0; } } public override bool TryMergeWithExistingMemory(out bool showBubble) { showBubble = false; - List memories = this.pawn.needs.mood.thoughts.memories.Memories; + List memories = base.pawn.needs.mood.thoughts.memories.Memories; for (int i = 0; i < memories.Count; i++) { - if (memories[i].def == this.def) + if (memories[i].def == base.def) { Thought_MemorySocialCumulative thought_MemorySocialCumulative = (Thought_MemorySocialCumulative)memories[i]; - if (thought_MemorySocialCumulative.OtherPawn() == this.otherPawn) + if (thought_MemorySocialCumulative.OtherPawn() == base.otherPawn) { - thought_MemorySocialCumulative.opinionOffset += this.opinionOffset; + thought_MemorySocialCumulative.opinionOffset += base.opinionOffset; return true; } } diff --git a/Assembly-CSharp/RimWorld/Thought_OpinionOfMyLover.cs b/Assembly-CSharp/RimWorld/Thought_OpinionOfMyLover.cs index 7c762f79f..707fda3c7 100644 --- a/Assembly-CSharp/RimWorld/Thought_OpinionOfMyLover.cs +++ b/Assembly-CSharp/RimWorld/Thought_OpinionOfMyLover.cs @@ -1,4 +1,3 @@ -using System; using UnityEngine; using Verse; @@ -10,7 +9,7 @@ public override string LabelCap { get { - DirectPawnRelation directPawnRelation = LovePartnerRelationUtility.ExistingMostLikedLovePartnerRel(this.pawn, false); + DirectPawnRelation directPawnRelation = LovePartnerRelationUtility.ExistingMostLikedLovePartnerRel(base.pawn, false); return string.Format(base.CurStage.label, directPawnRelation.def.GetGenderSpecificLabel(directPawnRelation.otherPawn), directPawnRelation.otherPawn.LabelShort).CapitalizeFirst(); } } @@ -19,8 +18,8 @@ protected override float BaseMoodOffset { get { - float num = 0.1f * (float)this.pawn.relations.OpinionOf(LovePartnerRelationUtility.ExistingMostLikedLovePartnerRel(this.pawn, false).otherPawn); - if (num < 0f) + float num = (float)(0.10000000149011612 * (float)base.pawn.relations.OpinionOf(LovePartnerRelationUtility.ExistingMostLikedLovePartnerRel(base.pawn, false).otherPawn)); + if (num < 0.0) { return Mathf.Min(num, -1f); } diff --git a/Assembly-CSharp/RimWorld/Thought_SharedBed.cs b/Assembly-CSharp/RimWorld/Thought_SharedBed.cs index c17c45d7e..3a5648e9e 100644 --- a/Assembly-CSharp/RimWorld/Thought_SharedBed.cs +++ b/Assembly-CSharp/RimWorld/Thought_SharedBed.cs @@ -1,4 +1,3 @@ -using System; using UnityEngine; using Verse; @@ -10,12 +9,12 @@ protected override float BaseMoodOffset { get { - Pawn mostDislikedNonPartnerBedOwner = LovePartnerRelationUtility.GetMostDislikedNonPartnerBedOwner(this.pawn); + Pawn mostDislikedNonPartnerBedOwner = LovePartnerRelationUtility.GetMostDislikedNonPartnerBedOwner(base.pawn); if (mostDislikedNonPartnerBedOwner == null) { return 0f; } - return Mathf.Min(0.05f * (float)this.pawn.relations.OpinionOf(mostDislikedNonPartnerBedOwner) - 5f, 0f); + return Mathf.Min((float)(0.05000000074505806 * (float)base.pawn.relations.OpinionOf(mostDislikedNonPartnerBedOwner) - 5.0), 0f); } } } diff --git a/Assembly-CSharp/RimWorld/Thought_Situational.cs b/Assembly-CSharp/RimWorld/Thought_Situational.cs index f21399ebb..a4d6c8e64 100644 --- a/Assembly-CSharp/RimWorld/Thought_Situational.cs +++ b/Assembly-CSharp/RimWorld/Thought_Situational.cs @@ -1,4 +1,3 @@ -using System; using UnityEngine; using Verse; @@ -43,7 +42,7 @@ public void RecalculateState() ThoughtState thoughtState = this.CurrentStateInternal(); if (thoughtState.Active) { - this.curStageIndex = Mathf.Min(thoughtState.StageIndex, this.def.stages.Count - 1); + this.curStageIndex = Mathf.Min(thoughtState.StageIndex, base.def.stages.Count - 1); this.reason = thoughtState.Reason; } else @@ -54,7 +53,7 @@ public void RecalculateState() protected virtual ThoughtState CurrentStateInternal() { - return this.def.Worker.CurrentState(this.pawn); + return base.def.Worker.CurrentState(base.pawn); } } } diff --git a/Assembly-CSharp/RimWorld/Thought_SituationalSocial.cs b/Assembly-CSharp/RimWorld/Thought_SituationalSocial.cs index c8effcf9f..1c6cb33a8 100644 --- a/Assembly-CSharp/RimWorld/Thought_SituationalSocial.cs +++ b/Assembly-CSharp/RimWorld/Thought_SituationalSocial.cs @@ -1,4 +1,3 @@ -using System; using Verse; namespace RimWorld @@ -11,7 +10,7 @@ public override bool VisibleInNeedsTab { get { - return base.VisibleInNeedsTab && this.MoodOffset() != 0f; + return base.VisibleInNeedsTab && this.MoodOffset() != 0.0; } } @@ -28,12 +27,16 @@ public virtual float OpinionOffset() public override bool GroupsWith(Thought other) { Thought_SituationalSocial thought_SituationalSocial = other as Thought_SituationalSocial; - return thought_SituationalSocial != null && base.GroupsWith(other) && this.otherPawn == thought_SituationalSocial.otherPawn; + if (thought_SituationalSocial == null) + { + return false; + } + return base.GroupsWith(other) && this.otherPawn == thought_SituationalSocial.otherPawn; } protected override ThoughtState CurrentStateInternal() { - return this.def.Worker.CurrentSocialState(this.pawn, this.otherPawn); + return base.def.Worker.CurrentSocialState(base.pawn, this.otherPawn); } } } diff --git a/Assembly-CSharp/RimWorld/Thought_Tale.cs b/Assembly-CSharp/RimWorld/Thought_Tale.cs index 09527a436..44cb11e07 100644 --- a/Assembly-CSharp/RimWorld/Thought_Tale.cs +++ b/Assembly-CSharp/RimWorld/Thought_Tale.cs @@ -1,4 +1,3 @@ -using System; using UnityEngine; using Verse; @@ -8,14 +7,14 @@ public class Thought_Tale : Thought_SituationalSocial { public override float OpinionOffset() { - Tale latestTale = Find.TaleManager.GetLatestTale(this.def.taleDef, this.otherPawn); + Tale latestTale = Find.TaleManager.GetLatestTale(base.def.taleDef, base.otherPawn); if (latestTale != null) { float num = 1f; if (latestTale.def.type == TaleType.Expirable) { - float value = (float)latestTale.AgeTicks / (latestTale.def.expireDays * 60000f); - num = Mathf.InverseLerp(1f, this.def.lerpOpinionToZeroAfterDurationPct, value); + float value = (float)((float)latestTale.AgeTicks / (latestTale.def.expireDays * 60000.0)); + num = Mathf.InverseLerp(1f, base.def.lerpOpinionToZeroAfterDurationPct, value); } return base.CurStage.baseOpinionOffset * num; } diff --git a/Assembly-CSharp/RimWorld/Thought_TeetotalerVsChemicalInterest.cs b/Assembly-CSharp/RimWorld/Thought_TeetotalerVsChemicalInterest.cs index 61c50ee22..0dc3d9825 100644 --- a/Assembly-CSharp/RimWorld/Thought_TeetotalerVsChemicalInterest.cs +++ b/Assembly-CSharp/RimWorld/Thought_TeetotalerVsChemicalInterest.cs @@ -1,12 +1,10 @@ -using System; - namespace RimWorld { public class Thought_TeetotalerVsChemicalInterest : Thought_SituationalSocial { public override float OpinionOffset() { - int num = this.otherPawn.story.traits.DegreeOfTrait(TraitDefOf.DrugDesire); + int num = base.otherPawn.story.traits.DegreeOfTrait(TraitDefOf.DrugDesire); if (num <= 0) { return 0f; diff --git a/Assembly-CSharp/RimWorld/Thought_WantToSleepWithSpouseOrLover.cs b/Assembly-CSharp/RimWorld/Thought_WantToSleepWithSpouseOrLover.cs index 7bde974de..59e50564c 100644 --- a/Assembly-CSharp/RimWorld/Thought_WantToSleepWithSpouseOrLover.cs +++ b/Assembly-CSharp/RimWorld/Thought_WantToSleepWithSpouseOrLover.cs @@ -1,4 +1,3 @@ -using System; using UnityEngine; using Verse; @@ -10,7 +9,7 @@ public override string LabelCap { get { - DirectPawnRelation directPawnRelation = LovePartnerRelationUtility.ExistingMostLikedLovePartnerRel(this.pawn, false); + DirectPawnRelation directPawnRelation = LovePartnerRelationUtility.ExistingMostLikedLovePartnerRel(base.pawn, false); return string.Format(base.CurStage.label, directPawnRelation.otherPawn.LabelShort).CapitalizeFirst(); } } @@ -19,7 +18,7 @@ protected override float BaseMoodOffset { get { - float a = -0.05f * (float)this.pawn.relations.OpinionOf(LovePartnerRelationUtility.ExistingMostLikedLovePartnerRel(this.pawn, false).otherPawn); + float a = (float)(-0.05000000074505806 * (float)base.pawn.relations.OpinionOf(LovePartnerRelationUtility.ExistingMostLikedLovePartnerRel(base.pawn, false).otherPawn)); return Mathf.Min(a, -1f); } } diff --git a/Assembly-CSharp/RimWorld/TimeAssignmentDef.cs b/Assembly-CSharp/RimWorld/TimeAssignmentDef.cs index 2c44613a3..3f48fdae5 100644 --- a/Assembly-CSharp/RimWorld/TimeAssignmentDef.cs +++ b/Assembly-CSharp/RimWorld/TimeAssignmentDef.cs @@ -1,4 +1,3 @@ -using System; using UnityEngine; using Verse; @@ -18,7 +17,7 @@ public Texture2D ColorTexture { get { - if (this.colorTextureInt == null) + if ((Object)this.colorTextureInt == (Object)null) { this.colorTextureInt = SolidColorMaterials.NewSolidColorTexture(this.color); } diff --git a/Assembly-CSharp/RimWorld/TimeAssignmentDefOf.cs b/Assembly-CSharp/RimWorld/TimeAssignmentDefOf.cs index 96d340554..a8ae9de1a 100644 --- a/Assembly-CSharp/RimWorld/TimeAssignmentDefOf.cs +++ b/Assembly-CSharp/RimWorld/TimeAssignmentDefOf.cs @@ -1,5 +1,3 @@ -using System; - namespace RimWorld { [DefOf] diff --git a/Assembly-CSharp/RimWorld/TimeAssignmentSelector.cs b/Assembly-CSharp/RimWorld/TimeAssignmentSelector.cs index c616b68e3..522554e6a 100644 --- a/Assembly-CSharp/RimWorld/TimeAssignmentSelector.cs +++ b/Assembly-CSharp/RimWorld/TimeAssignmentSelector.cs @@ -1,4 +1,3 @@ -using System; using UnityEngine; using Verse; using Verse.Sound; @@ -13,8 +12,10 @@ public static void DrawTimeAssignmentSelectorGrid(Rect rect) { rect.yMax -= 2f; Rect rect2 = rect; - rect2.xMax = rect2.center.x; - rect2.yMax = rect2.center.y; + Vector2 center = rect2.center; + rect2.xMax = center.x; + Vector2 center2 = rect2.center; + rect2.yMax = center2.y; TimeAssignmentSelector.DrawTimeAssignmentSelectorFor(rect2, TimeAssignmentDefOf.Anything); rect2.x += rect2.width; TimeAssignmentSelector.DrawTimeAssignmentSelectorFor(rect2, TimeAssignmentDefOf.Work); diff --git a/Assembly-CSharp/RimWorld/TimeControls.cs b/Assembly-CSharp/RimWorld/TimeControls.cs index 912130dbd..85f2b48c8 100644 --- a/Assembly-CSharp/RimWorld/TimeControls.cs +++ b/Assembly-CSharp/RimWorld/TimeControls.cs @@ -9,7 +9,7 @@ public static class TimeControls { public static readonly Vector2 TimeButSize = new Vector2(32f, 24f); - private static readonly string[] SpeedSounds = new string[] + private static readonly string[] SpeedSounds = new string[5] { "ClockStop", "ClockNormal", @@ -22,20 +22,23 @@ public static class TimeControls private static void PlaySoundOf(TimeSpeed speed) { - SoundDef.Named(TimeControls.SpeedSounds[(int)speed]).PlayOneShotOnCamera(null); + SoundDef.Named(TimeControls.SpeedSounds[(uint)speed]).PlayOneShotOnCamera(null); } public static void DoTimeControlsGUI(Rect timerRect) { TickManager tickManager = Find.TickManager; GUI.BeginGroup(timerRect); - Rect rect = new Rect(0f, 0f, TimeControls.TimeButSize.x, TimeControls.TimeButSize.y); + Vector2 timeButSize = TimeControls.TimeButSize; + float x = timeButSize.x; + Vector2 timeButSize2 = TimeControls.TimeButSize; + Rect rect = new Rect(0f, 0f, x, timeButSize2.y); for (int i = 0; i < TimeControls.CachedTimeSpeedValues.Length; i++) { TimeSpeed timeSpeed = TimeControls.CachedTimeSpeedValues[i]; if (timeSpeed != TimeSpeed.Ultrafast) { - if (Widgets.ButtonImage(rect, TexButton.SpeedButtonTextures[(int)timeSpeed])) + if (Widgets.ButtonImage(rect, TexButton.SpeedButtonTextures[(uint)timeSpeed])) { if (timeSpeed == TimeSpeed.Paused) { @@ -58,7 +61,7 @@ public static void DoTimeControlsGUI(Rect timerRect) } if (Find.TickManager.slower.ForcedNormalSpeed) { - Widgets.DrawLineHorizontal(rect.width * 2f, rect.height / 2f, rect.width * 2f); + Widgets.DrawLineHorizontal((float)(rect.width * 2.0), (float)(rect.height / 2.0), (float)(rect.width * 2.0)); } GUI.EndGroup(); GenUI.AbsorbClicksInRect(timerRect); diff --git a/Assembly-CSharp/RimWorld/TimetableUtility.cs b/Assembly-CSharp/RimWorld/TimetableUtility.cs index 2d81cd7ff..dd05f595e 100644 --- a/Assembly-CSharp/RimWorld/TimetableUtility.cs +++ b/Assembly-CSharp/RimWorld/TimetableUtility.cs @@ -1,4 +1,3 @@ -using System; using Verse; namespace RimWorld diff --git a/Assembly-CSharp/RimWorld/Toils_Bed.cs b/Assembly-CSharp/RimWorld/Toils_Bed.cs index 3648d05c7..dd5bd940d 100644 --- a/Assembly-CSharp/RimWorld/Toils_Bed.cs +++ b/Assembly-CSharp/RimWorld/Toils_Bed.cs @@ -9,21 +9,21 @@ public static class Toils_Bed public static Toil GotoBed(TargetIndex bedIndex) { Toil gotoBed = new Toil(); - gotoBed.initAction = delegate + gotoBed.initAction = (Action)delegate() { - Pawn actor = gotoBed.actor; - Building_Bed bed = (Building_Bed)actor.CurJob.GetTarget(bedIndex).Thing; - IntVec3 bedSleepingSlotPosFor = RestUtility.GetBedSleepingSlotPosFor(actor, bed); - if (actor.Position == bedSleepingSlotPosFor) + Pawn actor2 = gotoBed.actor; + Building_Bed bed = (Building_Bed)actor2.CurJob.GetTarget(bedIndex).Thing; + IntVec3 bedSleepingSlotPosFor = RestUtility.GetBedSleepingSlotPosFor(actor2, bed); + if (actor2.Position == bedSleepingSlotPosFor) { - actor.jobs.curDriver.ReadyForNextToil(); + actor2.jobs.curDriver.ReadyForNextToil(); } else { - actor.pather.StartPath(RestUtility.GetBedSleepingSlotPosFor(actor, bed), PathEndMode.OnCell); + actor2.pather.StartPath(RestUtility.GetBedSleepingSlotPosFor(actor2, bed), PathEndMode.OnCell); } }; - gotoBed.tickAction = delegate + gotoBed.tickAction = (Action)delegate() { Pawn actor = gotoBed.actor; Building_Bed building_Bed = (Building_Bed)actor.CurJob.GetTarget(bedIndex).Thing; @@ -41,10 +41,10 @@ public static Toil GotoBed(TargetIndex bedIndex) public static Toil ClaimBedIfNonMedical(TargetIndex ind, TargetIndex claimantIndex = TargetIndex.None) { Toil claim = new Toil(); - claim.initAction = delegate + claim.initAction = (Action)delegate() { Pawn actor = claim.GetActor(); - Pawn pawn = (claimantIndex != TargetIndex.None) ? ((Pawn)actor.CurJob.GetTarget(claimantIndex).Thing) : actor; + Pawn pawn = (claimantIndex != 0) ? ((Pawn)actor.CurJob.GetTarget(claimantIndex).Thing) : actor; if (pawn.ownership != null) { pawn.ownership.ClaimBedIfNonMedical((Building_Bed)actor.CurJob.GetTarget(ind).Thing); @@ -56,10 +56,10 @@ public static Toil ClaimBedIfNonMedical(TargetIndex ind, TargetIndex claimantInd public static T FailOnNonMedicalBedNotOwned(this T f, TargetIndex bedIndex, TargetIndex claimantIndex = TargetIndex.None) where T : IJobEndable { - f.AddEndCondition(delegate + f.AddEndCondition((Func)delegate() { Pawn actor = f.GetActor(); - Pawn pawn = (claimantIndex != TargetIndex.None) ? ((Pawn)actor.CurJob.GetTarget(claimantIndex).Thing) : actor; + Pawn pawn = (claimantIndex != 0) ? ((Pawn)actor.CurJob.GetTarget(claimantIndex).Thing) : actor; if (pawn.ownership != null) { Building_Bed building_Bed = (Building_Bed)actor.CurJob.GetTarget(bedIndex).Thing; @@ -79,13 +79,16 @@ public static T FailOnNonMedicalBedNotOwned(this T f, TargetIndex bedIndex, T if (pawn.InBed() && pawn.CurrentBed() == building_Bed) { int curOccupantSlotIndex = building_Bed.GetCurOccupantSlotIndex(pawn); - if (curOccupantSlotIndex >= building_Bed.owners.Count || building_Bed.owners[curOccupantSlotIndex] != pawn) + if (curOccupantSlotIndex < building_Bed.owners.Count && building_Bed.owners[curOccupantSlotIndex] == pawn) { - return JobCondition.Incompletable; + goto IL_00f9; } + return JobCondition.Incompletable; } } } + goto IL_00f9; + IL_00f9: return JobCondition.Ongoing; }); return f; @@ -94,11 +97,11 @@ public static T FailOnNonMedicalBedNotOwned(this T f, TargetIndex bedIndex, T public static void FailOnBedNoLongerUsable(this Toil toil, TargetIndex bedIndex) { toil.FailOnDespawnedOrNull(bedIndex); - toil.FailOn(() => ((Building_Bed)toil.actor.CurJob.GetTarget(bedIndex).Thing).IsBurning()); - toil.FailOn(() => ((Building_Bed)toil.actor.CurJob.GetTarget(bedIndex).Thing).ForPrisoners != toil.actor.IsPrisoner); + toil.FailOn((Func)(() => ((Building_Bed)toil.actor.CurJob.GetTarget(bedIndex).Thing).IsBurning())); + toil.FailOn((Func)(() => ((Building_Bed)toil.actor.CurJob.GetTarget(bedIndex).Thing).ForPrisoners != toil.actor.IsPrisoner)); toil.FailOnNonMedicalBedNotOwned(bedIndex, TargetIndex.None); - toil.FailOn(() => !HealthAIUtility.ShouldSeekMedicalRest(toil.actor) && !HealthAIUtility.ShouldSeekMedicalRestUrgent(toil.actor) && ((Building_Bed)toil.actor.CurJob.GetTarget(bedIndex).Thing).Medical); - toil.FailOn(() => toil.actor.IsColonist && !toil.actor.CurJob.ignoreForbidden && !toil.actor.Downed && toil.actor.CurJob.GetTarget(bedIndex).Thing.IsForbidden(toil.actor)); + toil.FailOn((Func)(() => !HealthAIUtility.ShouldSeekMedicalRest(toil.actor) && !HealthAIUtility.ShouldSeekMedicalRestUrgent(toil.actor) && ((Building_Bed)toil.actor.CurJob.GetTarget(bedIndex).Thing).Medical)); + toil.FailOn((Func)(() => toil.actor.IsColonist && !toil.actor.CurJob.ignoreForbidden && !toil.actor.Downed && toil.actor.CurJob.GetTarget(bedIndex).Thing.IsForbidden(toil.actor))); } } } diff --git a/Assembly-CSharp/RimWorld/Toils_Construct.cs b/Assembly-CSharp/RimWorld/Toils_Construct.cs index 5a86091f0..dbec6399c 100644 --- a/Assembly-CSharp/RimWorld/Toils_Construct.cs +++ b/Assembly-CSharp/RimWorld/Toils_Construct.cs @@ -9,16 +9,16 @@ public static class Toils_Construct public static Toil MakeSolidThingFromBlueprintIfNecessary(TargetIndex blueTarget, TargetIndex targetToUpdate = TargetIndex.None) { Toil toil = new Toil(); - toil.initAction = delegate + toil.initAction = (Action)delegate() { Pawn actor = toil.actor; Job curJob = actor.jobs.curJob; Blueprint blueprint = curJob.GetTarget(blueTarget).Thing as Blueprint; if (blueprint != null) { - bool flag = targetToUpdate != TargetIndex.None && curJob.GetTarget(targetToUpdate).Thing == blueprint; - Thing thing; - bool flag2; + bool flag = targetToUpdate != 0 && curJob.GetTarget(targetToUpdate).Thing == blueprint; + Thing thing = default(Thing); + bool flag2 = default(bool); if (blueprint.TryReplaceWithSolidThing(actor, out thing, out flag2)) { curJob.SetTarget(blueTarget, thing); @@ -31,10 +31,8 @@ public static Toil MakeSolidThingFromBlueprintIfNecessary(TargetIndex blueTarget actor.Reserve(thing, 1, -1, null); } } - if (flag2) - { + if (!flag2) return; - } } }; return toil; @@ -43,38 +41,37 @@ public static Toil MakeSolidThingFromBlueprintIfNecessary(TargetIndex blueTarget public static Toil UninstallIfMinifiable(TargetIndex thingInd) { Toil uninstallIfMinifiable = new Toil().FailOnDestroyedNullOrForbidden(thingInd); - uninstallIfMinifiable.initAction = delegate + uninstallIfMinifiable.initAction = (Action)delegate() { - Pawn actor = uninstallIfMinifiable.actor; - JobDriver curDriver = actor.jobs.curDriver; - Thing thing = actor.CurJob.GetTarget(thingInd).Thing; - if (thing.def.Minifiable) + Pawn actor2 = uninstallIfMinifiable.actor; + JobDriver curDriver2 = actor2.jobs.curDriver; + Thing thing2 = actor2.CurJob.GetTarget(thingInd).Thing; + if (thing2.def.Minifiable) { - curDriver.uninstallWorkLeft = 90f; + curDriver2.uninstallWorkLeft = 90f; } else { - curDriver.ReadyForNextToil(); + curDriver2.ReadyForNextToil(); } }; - uninstallIfMinifiable.tickAction = delegate + uninstallIfMinifiable.tickAction = (Action)delegate() { Pawn actor = uninstallIfMinifiable.actor; JobDriver curDriver = actor.jobs.curDriver; Job curJob = actor.CurJob; curDriver.uninstallWorkLeft -= actor.GetStatValue(StatDefOf.ConstructionSpeed, true); - if (curDriver.uninstallWorkLeft <= 0f) + if (curDriver.uninstallWorkLeft <= 0.0) { Thing thing = curJob.GetTarget(thingInd).Thing; MinifiedThing minifiedThing = thing.MakeMinified(); GenSpawn.Spawn(minifiedThing, thing.Position, uninstallIfMinifiable.actor.Map); - curJob.SetTarget(thingInd, minifiedThing); + curJob.SetTarget(thingInd, (Thing)minifiedThing); actor.jobs.curDriver.ReadyForNextToil(); - return; } }; uninstallIfMinifiable.defaultCompleteMode = ToilCompleteMode.Never; - uninstallIfMinifiable.WithProgressBar(thingInd, () => 1f - uninstallIfMinifiable.actor.jobs.curDriver.uninstallWorkLeft / 90f, false, -0.5f); + uninstallIfMinifiable.WithProgressBar(thingInd, (Func)(() => (float)(1.0 - uninstallIfMinifiable.actor.jobs.curDriver.uninstallWorkLeft / 90.0)), false, -0.5f); return uninstallIfMinifiable; } } diff --git a/Assembly-CSharp/RimWorld/Toils_Ingest.cs b/Assembly-CSharp/RimWorld/Toils_Ingest.cs index ad6ef27cc..f67c94c0e 100644 --- a/Assembly-CSharp/RimWorld/Toils_Ingest.cs +++ b/Assembly-CSharp/RimWorld/Toils_Ingest.cs @@ -11,14 +11,14 @@ public class Toils_Ingest { private static List spotSearchList = new List(); - private static List cardinals = GenAdj.CardinalDirections.ToList(); + private static List cardinals = GenAdj.CardinalDirections.ToList(); - private static List diagonals = GenAdj.DiagonalDirections.ToList(); + private static List diagonals = GenAdj.DiagonalDirections.ToList(); public static Toil TakeMealFromDispenser(TargetIndex ind, Pawn eater) { Toil toil = new Toil(); - toil.initAction = delegate + toil.initAction = (Action)delegate() { Pawn actor = toil.actor; Job curJob = actor.jobs.curJob; @@ -27,10 +27,12 @@ public static Toil TakeMealFromDispenser(TargetIndex ind, Pawn eater) if (thing == null) { actor.jobs.curDriver.EndJobWith(JobCondition.Incompletable); - return; } - actor.carryTracker.TryStartCarry(thing); - actor.CurJob.SetTarget(ind, actor.carryTracker.CarriedThing); + else + { + actor.carryTracker.TryStartCarry(thing); + actor.CurJob.SetTarget(ind, actor.carryTracker.CarriedThing); + } }; toil.FailOnCannotTouch(ind, PathEndMode.Touch); toil.defaultCompleteMode = ToilCompleteMode.Delay; @@ -41,7 +43,7 @@ public static Toil TakeMealFromDispenser(TargetIndex ind, Pawn eater) public static Toil PickupIngestible(TargetIndex ind, Pawn eater) { Toil toil = new Toil(); - toil.initAction = delegate + toil.initAction = (Action)delegate() { Pawn actor = toil.actor; Job curJob = actor.jobs.curJob; @@ -50,15 +52,17 @@ public static Toil PickupIngestible(TargetIndex ind, Pawn eater) { Log.Error("Tried to do PickupIngestible toil with job.maxNumToCarry = " + curJob.count); actor.jobs.EndCurrentJob(JobCondition.Errored, true); - return; } - int count = Mathf.Min(thing.stackCount, curJob.count); - actor.carryTracker.TryStartCarry(thing, count); - if (thing != actor.carryTracker.CarriedThing && actor.Map.reservationManager.ReservedBy(thing, actor)) + else { - actor.Map.reservationManager.Release(thing, actor); + int count = Mathf.Min(thing.stackCount, curJob.count); + actor.carryTracker.TryStartCarry(thing, count); + if (thing != actor.carryTracker.CarriedThing && actor.Map.reservationManager.ReservedBy(thing, actor)) + { + actor.Map.reservationManager.Release(thing, actor); + } + actor.jobs.curJob.targetA = actor.carryTracker.CarriedThing; } - actor.jobs.curJob.targetA = actor.carryTracker.CarriedThing; }; toil.defaultCompleteMode = ToilCompleteMode.Instant; return toil; @@ -67,54 +71,58 @@ public static Toil PickupIngestible(TargetIndex ind, Pawn eater) public static Toil CarryIngestibleToChewSpot(Pawn pawn, TargetIndex ingestibleInd) { Toil toil = new Toil(); - toil.initAction = delegate + toil.initAction = (Action)delegate() { Pawn actor = toil.actor; IntVec3 intVec = IntVec3.Invalid; Thing thing = null; Thing thing2 = actor.CurJob.GetTarget(ingestibleInd).Thing; - Predicate baseChairValidator = delegate(Thing t) + Predicate baseChairValidator = (Predicate)delegate(Thing t) { - if (t.def.building == null || !t.def.building.isSittable) - { - return false; - } - if (t.IsForbidden(pawn)) - { - return false; - } - if (!actor.CanReserve(t, 1, -1, null, false)) - { - return false; - } - if (!t.IsSociallyProper(actor)) - { - return false; - } - if (t.IsBurning()) - { - return false; - } - if (t.HostileTo(pawn)) + if (t.def.building != null && t.def.building.isSittable) { - return false; - } - bool result = false; - for (int i = 0; i < 4; i++) - { - IntVec3 c = t.Position + GenAdj.CardinalDirections[i]; - Building edifice = c.GetEdifice(t.Map); - if (edifice != null && edifice.def.surfaceType == SurfaceType.Eat) + if (t.IsForbidden(pawn)) + { + return false; + } + if (!actor.CanReserve(t, 1, -1, null, false)) + { + return false; + } + if (!t.IsSociallyProper(actor)) + { + return false; + } + if (t.IsBurning()) { - result = true; - break; + return false; } + if (t.HostileTo(pawn)) + { + return false; + } + bool flag = false; + for (int i = 0; i < 4; i++) + { + IntVec3 c = t.Position + GenAdj.CardinalDirections[i]; + Building edifice = c.GetEdifice(t.Map); + if (edifice != null && edifice.def.surfaceType == SurfaceType.Eat) + { + flag = true; + break; + } + } + if (!flag) + { + return false; + } + return true; } - return result; + return false; }; - if (thing2.def.ingestible.chairSearchRadius > 0f) + if (thing2.def.ingestible.chairSearchRadius > 0.0) { - thing = GenClosest.ClosestThingReachable(actor.Position, actor.Map, ThingRequest.ForGroup(ThingRequestGroup.BuildingArtificial), PathEndMode.OnCell, TraverseParms.For(actor, Danger.Deadly, TraverseMode.ByPawn, false), thing2.def.ingestible.chairSearchRadius, (Thing t) => baseChairValidator(t) && t.Position.GetDangerFor(pawn, t.Map) == Danger.None, null, 0, -1, false, RegionType.Set_Passable, false); + thing = GenClosest.ClosestThingReachable(actor.Position, actor.Map, ThingRequest.ForGroup(ThingRequestGroup.BuildingArtificial), PathEndMode.OnCell, TraverseParms.For(actor, Danger.Deadly, TraverseMode.ByPawn, false), thing2.def.ingestible.chairSearchRadius, (Predicate)((Thing t) => baseChairValidator(t) && t.Position.GetDangerFor(pawn, t.Map) == Danger.None), null, 0, -1, false, RegionType.Set_Passable, false); } if (thing == null) { @@ -122,7 +130,7 @@ public static Toil CarryIngestibleToChewSpot(Pawn pawn, TargetIndex ingestibleIn Danger chewSpotDanger = intVec.GetDangerFor(pawn, actor.Map); if (chewSpotDanger != Danger.None) { - thing = GenClosest.ClosestThingReachable(actor.Position, actor.Map, ThingRequest.ForGroup(ThingRequestGroup.BuildingArtificial), PathEndMode.OnCell, TraverseParms.For(actor, Danger.Deadly, TraverseMode.ByPawn, false), thing2.def.ingestible.chairSearchRadius, (Thing t) => baseChairValidator(t) && t.Position.GetDangerFor(pawn, t.Map) <= chewSpotDanger, null, 0, -1, false, RegionType.Set_Passable, false); + thing = GenClosest.ClosestThingReachable(actor.Position, actor.Map, ThingRequest.ForGroup(ThingRequestGroup.BuildingArtificial), PathEndMode.OnCell, TraverseParms.For(actor, Danger.Deadly, TraverseMode.ByPawn, false), thing2.def.ingestible.chairSearchRadius, (Predicate)((Thing t) => baseChairValidator(t) && (int)t.Position.GetDangerFor(pawn, t.Map) <= (int)chewSpotDanger), null, 0, -1, false, RegionType.Set_Passable, false); } } if (thing != null) @@ -143,29 +151,23 @@ public static bool TryFindAdjacentIngestionPlaceSpot(IntVec3 root, ThingDef inge for (int i = 0; i < 4; i++) { IntVec3 intVec = root + GenAdj.CardinalDirections[i]; - if (intVec.HasEatSurface(pawn.Map)) + if (intVec.HasEatSurface(pawn.Map) && !(from t in pawn.Map.thingGrid.ThingsAt(intVec) + where t.def == ingestibleDef + select t).Any() && !intVec.IsForbidden(pawn)) { - if (!(from t in pawn.Map.thingGrid.ThingsAt(intVec) - where t.def == ingestibleDef - select t).Any()) - { - if (!intVec.IsForbidden(pawn)) - { - placeSpot = intVec; - return true; - } - } + placeSpot = intVec; + return true; } } if (!placeSpot.IsValid) { Toils_Ingest.spotSearchList.Clear(); - Toils_Ingest.cardinals.Shuffle(); + Toils_Ingest.cardinals.Shuffle(); for (int j = 0; j < 4; j++) { Toils_Ingest.spotSearchList.Add(Toils_Ingest.cardinals[j]); } - Toils_Ingest.diagonals.Shuffle(); + Toils_Ingest.diagonals.Shuffle(); for (int k = 0; k < 4; k++) { Toils_Ingest.spotSearchList.Add(Toils_Ingest.diagonals[k]); @@ -174,15 +176,12 @@ public static bool TryFindAdjacentIngestionPlaceSpot(IntVec3 root, ThingDef inge for (int l = 0; l < Toils_Ingest.spotSearchList.Count; l++) { IntVec3 intVec2 = root + Toils_Ingest.spotSearchList[l]; - if (intVec2.Walkable(pawn.Map) && !intVec2.IsForbidden(pawn)) + if (intVec2.Walkable(pawn.Map) && !intVec2.IsForbidden(pawn) && !(from t in pawn.Map.thingGrid.ThingsAt(intVec2) + where t.def == ingestibleDef + select t).Any()) { - if (!(from t in pawn.Map.thingGrid.ThingsAt(intVec2) - where t.def == ingestibleDef - select t).Any()) - { - placeSpot = intVec2; - return true; - } + placeSpot = intVec2; + return true; } } } @@ -192,26 +191,33 @@ public static bool TryFindAdjacentIngestionPlaceSpot(IntVec3 root, ThingDef inge public static Toil FindAdjacentEatSurface(TargetIndex eatSurfaceInd, TargetIndex foodInd) { Toil toil = new Toil(); - toil.initAction = delegate + toil.initAction = (Action)delegate() { Pawn actor = toil.actor; IntVec3 position = actor.Position; Map map = actor.Map; - for (int i = 0; i < 4; i++) + int num = 0; + IntVec3 intVec; + while (true) { - Rot4 rot = new Rot4(i); - IntVec3 intVec = position + rot.FacingCell; - if (intVec.HasEatSurface(map)) + if (num < 4) { - toil.actor.CurJob.SetTarget(eatSurfaceInd, intVec); - toil.actor.jobs.curDriver.rotateToFace = eatSurfaceInd; - Thing thing = toil.actor.CurJob.GetTarget(foodInd).Thing; - if (thing.def.rotatable) + intVec = position + new Rot4(num).FacingCell; + if (!intVec.HasEatSurface(map)) { - thing.Rotation = Rot4.FromIntVec3(intVec - toil.actor.Position); + num++; + continue; } - return; + break; } + return; + } + toil.actor.CurJob.SetTarget(eatSurfaceInd, intVec); + toil.actor.jobs.curDriver.rotateToFace = eatSurfaceInd; + Thing thing = toil.actor.CurJob.GetTarget(foodInd).Thing; + if (thing.def.rotatable) + { + thing.Rotation = Rot4.FromIntVec3(intVec - toil.actor.Position); } }; toil.defaultCompleteMode = ToilCompleteMode.Instant; @@ -221,56 +227,49 @@ public static Toil FindAdjacentEatSurface(TargetIndex eatSurfaceInd, TargetIndex public static Toil ChewIngestible(Pawn chewer, float durationMultiplier, TargetIndex ingestibleInd, TargetIndex eatSurfaceInd = TargetIndex.None) { Toil toil = new Toil(); - toil.initAction = delegate + toil.initAction = (Action)delegate() { - Pawn actor = toil.actor; - Thing thing = actor.CurJob.GetTarget(ingestibleInd).Thing; - actor.Drawer.rotator.FaceCell(chewer.Position); - if (!thing.IngestibleNow) + Pawn actor2 = toil.actor; + Thing thing3 = actor2.CurJob.GetTarget(ingestibleInd).Thing; + actor2.Drawer.rotator.FaceCell(chewer.Position); + if (!thing3.IngestibleNow) { chewer.jobs.EndCurrentJob(JobCondition.Incompletable, true); - return; } - actor.jobs.curDriver.ticksLeftThisToil = Mathf.RoundToInt((float)thing.def.ingestible.baseIngestTicks * durationMultiplier); - if (thing.Spawned) + else { - thing.Map.physicalInteractionReservationManager.Reserve(chewer, thing); + actor2.jobs.curDriver.ticksLeftThisToil = Mathf.RoundToInt((float)thing3.def.ingestible.baseIngestTicks * durationMultiplier); + if (thing3.Spawned) + { + thing3.Map.physicalInteractionReservationManager.Reserve(chewer, thing3); + } } }; - toil.tickAction = delegate + toil.tickAction = (Action)delegate { toil.actor.GainComfortFromCellIfPossible(); }; - toil.WithProgressBar(ingestibleInd, delegate + toil.WithProgressBar(ingestibleInd, (Func)delegate() { Pawn actor = toil.actor; - Thing thing = actor.CurJob.GetTarget(ingestibleInd).Thing; - if (thing == null) + Thing thing2 = actor.CurJob.GetTarget(ingestibleInd).Thing; + if (thing2 == null) { return 1f; } - return 1f - (float)toil.actor.jobs.curDriver.ticksLeftThisToil / Mathf.Round((float)thing.def.ingestible.baseIngestTicks * durationMultiplier); + return (float)(1.0 - (float)toil.actor.jobs.curDriver.ticksLeftThisToil / Mathf.Round((float)thing2.def.ingestible.baseIngestTicks * durationMultiplier)); }, false, -0.5f); toil.defaultCompleteMode = ToilCompleteMode.Delay; toil.FailOnDestroyedOrNull(ingestibleInd); - toil.AddFinishAction(delegate + toil.AddFinishAction((Action)delegate() { - if (chewer == null) + if (chewer != null && chewer.CurJob != null) { - return; - } - if (chewer.CurJob == null) - { - return; - } - Thing thing = chewer.CurJob.GetTarget(ingestibleInd).Thing; - if (thing == null) - { - return; - } - if (chewer.Map.physicalInteractionReservationManager.IsReservedBy(chewer, thing)) - { - chewer.Map.physicalInteractionReservationManager.Release(chewer, thing); + Thing thing = chewer.CurJob.GetTarget(ingestibleInd).Thing; + if (thing != null && chewer.Map.physicalInteractionReservationManager.IsReservedBy(chewer, thing)) + { + chewer.Map.physicalInteractionReservationManager.Release(chewer, thing); + } } }); Toils_Ingest.AddIngestionEffects(toil, chewer, ingestibleInd, eatSurfaceInd); @@ -279,37 +278,37 @@ public static Toil ChewIngestible(Pawn chewer, float durationMultiplier, TargetI public static Toil AddIngestionEffects(Toil toil, Pawn chewer, TargetIndex ingestibleInd, TargetIndex eatSurfaceInd) { - toil.WithEffect(delegate + toil.WithEffect((Func)delegate() { - LocalTargetInfo target = toil.actor.CurJob.GetTarget(ingestibleInd); - if (!target.HasThing) + LocalTargetInfo target2 = toil.actor.CurJob.GetTarget(ingestibleInd); + if (!target2.HasThing) { return null; } - EffecterDef result = target.Thing.def.ingestible.ingestEffect; - if (chewer.RaceProps.intelligence < Intelligence.ToolUser && target.Thing.def.ingestible.ingestEffectEat != null) + EffecterDef result = target2.Thing.def.ingestible.ingestEffect; + if ((int)chewer.RaceProps.intelligence < 1 && target2.Thing.def.ingestible.ingestEffectEat != null) { - result = target.Thing.def.ingestible.ingestEffectEat; + result = target2.Thing.def.ingestible.ingestEffectEat; } return result; - }, delegate + }, (Func)delegate() { if (!toil.actor.CurJob.GetTarget(ingestibleInd).HasThing) { - return null; + return (Thing)null; } Thing thing = toil.actor.CurJob.GetTarget(ingestibleInd).Thing; if (chewer != toil.actor) { - return chewer; + return (Thing)chewer; } - if (eatSurfaceInd != TargetIndex.None && toil.actor.CurJob.GetTarget(eatSurfaceInd).IsValid) + if (eatSurfaceInd != 0 && toil.actor.CurJob.GetTarget(eatSurfaceInd).IsValid) { return toil.actor.CurJob.GetTarget(eatSurfaceInd); } return thing; }); - toil.PlaySustainerOrSound(delegate + toil.PlaySustainerOrSound((Func)delegate() { if (!chewer.RaceProps.Humanlike) { @@ -328,12 +327,12 @@ public static Toil AddIngestionEffects(Toil toil, Pawn chewer, TargetIndex inges public static Toil FinalizeIngest(Pawn ingester, TargetIndex ingestibleInd) { Toil toil = new Toil(); - toil.initAction = delegate + toil.initAction = (Action)delegate() { Pawn actor = toil.actor; Job curJob = actor.jobs.curJob; Thing thing = curJob.GetTarget(ingestibleInd).Thing; - if (ingester.needs.mood != null && thing.def.IsNutritionGivingIngestible && thing.def.ingestible.chairSearchRadius > 10f) + if (ingester.needs.mood != null && thing.def.IsNutritionGivingIngestible && thing.def.ingestible.chairSearchRadius > 10.0) { if (!(ingester.Position + ingester.Rotation.FacingCell).HasEatSurface(actor.Map) && ingester.GetPosture() == PawnPosture.Standing) { diff --git a/Assembly-CSharp/RimWorld/Toils_Interpersonal.cs b/Assembly-CSharp/RimWorld/Toils_Interpersonal.cs index 4b7c2dc07..4eb5b20ef 100644 --- a/Assembly-CSharp/RimWorld/Toils_Interpersonal.cs +++ b/Assembly-CSharp/RimWorld/Toils_Interpersonal.cs @@ -10,11 +10,30 @@ public static class Toils_Interpersonal public static Toil GotoPrisoner(Pawn pawn, Pawn talkee, PrisonerInteractionModeDef mode) { Toil toil = new Toil(); - toil.initAction = delegate + toil.initAction = (Action)delegate() { - pawn.pather.StartPath(talkee, PathEndMode.Touch); + pawn.pather.StartPath((Thing)talkee, PathEndMode.Touch); }; - toil.AddFailCondition(() => talkee.Destroyed || (mode != PrisonerInteractionModeDefOf.Execution && !talkee.Awake()) || !talkee.IsPrisonerOfColony || (talkee.guest == null || talkee.guest.interactionMode != mode)); + toil.AddFailCondition((Func)delegate() + { + if (talkee.Destroyed) + { + return true; + } + if (mode != PrisonerInteractionModeDefOf.Execution && !talkee.Awake()) + { + return true; + } + if (!talkee.IsPrisonerOfColony) + { + return true; + } + if (talkee.guest != null && talkee.guest.interactionMode == mode) + { + return false; + } + return true; + }); toil.socialMode = RandomSocialMode.Off; toil.defaultCompleteMode = ToilCompleteMode.PatherArrival; return toil; @@ -22,52 +41,50 @@ public static Toil GotoPrisoner(Pawn pawn, Pawn talkee, PrisonerInteractionModeD public static Toil WaitToBeAbleToInteract(Pawn pawn) { - return new Toil + Toil toil = new Toil(); + toil.initAction = (Action)delegate() { - initAction = delegate + if (!pawn.interactions.InteractedTooRecentlyToInteract()) { - if (!pawn.interactions.InteractedTooRecentlyToInteract()) - { - pawn.jobs.curDriver.ReadyForNextToil(); - } - }, - tickAction = delegate + pawn.jobs.curDriver.ReadyForNextToil(); + } + }; + toil.tickAction = (Action)delegate() + { + if (!pawn.interactions.InteractedTooRecentlyToInteract()) { - if (!pawn.interactions.InteractedTooRecentlyToInteract()) - { - pawn.jobs.curDriver.ReadyForNextToil(); - } - }, - socialMode = RandomSocialMode.Off, - defaultCompleteMode = ToilCompleteMode.Never + pawn.jobs.curDriver.ReadyForNextToil(); + } }; + toil.socialMode = RandomSocialMode.Off; + toil.defaultCompleteMode = ToilCompleteMode.Never; + return toil; } public static Toil ConvinceRecruitee(Pawn pawn, Pawn talkee) { - return new Toil + Toil toil = new Toil(); + toil.initAction = (Action)delegate() { - initAction = delegate + if (!pawn.interactions.TryInteractWith(talkee, InteractionDefOf.BuildRapport)) { - if (!pawn.interactions.TryInteractWith(talkee, InteractionDefOf.BuildRapport)) - { - pawn.jobs.curDriver.ReadyForNextToil(); - } - else - { - pawn.records.Increment(RecordDefOf.PrisonersChatted); - } - }, - socialMode = RandomSocialMode.Off, - defaultCompleteMode = ToilCompleteMode.Delay, - defaultDuration = 350 + pawn.jobs.curDriver.ReadyForNextToil(); + } + else + { + pawn.records.Increment(RecordDefOf.PrisonersChatted); + } }; + toil.socialMode = RandomSocialMode.Off; + toil.defaultCompleteMode = ToilCompleteMode.Delay; + toil.defaultDuration = 350; + return toil; } public static Toil SetLastInteractTime(TargetIndex targetInd) { Toil toil = new Toil(); - toil.initAction = delegate + toil.initAction = (Action)delegate() { Pawn pawn = (Pawn)toil.actor.jobs.curJob.GetTarget(targetInd).Thing; pawn.mindState.lastAssignedInteractTime = Find.TickManager.TicksGame; @@ -79,16 +96,15 @@ public static Toil SetLastInteractTime(TargetIndex targetInd) public static Toil TryRecruit(TargetIndex recruiteeInd) { Toil toil = new Toil(); - toil.initAction = delegate + toil.initAction = (Action)delegate() { Pawn actor = toil.actor; Pawn pawn = (Pawn)actor.jobs.curJob.GetTarget(recruiteeInd).Thing; - if (!pawn.Spawned || !pawn.Awake()) + if (pawn.Spawned && pawn.Awake()) { - return; + InteractionDef intDef = (!pawn.def.race.Animal) ? InteractionDefOf.RecruitAttempt : InteractionDefOf.TameAttempt; + actor.interactions.TryInteractWith(pawn, intDef); } - InteractionDef intDef = (!pawn.def.race.Animal) ? InteractionDefOf.RecruitAttempt : InteractionDefOf.TameAttempt; - actor.interactions.TryInteractWith(pawn, intDef); }; toil.socialMode = RandomSocialMode.Off; toil.defaultCompleteMode = ToilCompleteMode.Delay; @@ -99,58 +115,38 @@ public static Toil TryRecruit(TargetIndex recruiteeInd) public static Toil TryTrain(TargetIndex traineeInd) { Toil toil = new Toil(); - toil.initAction = delegate + toil.initAction = (Action)delegate() { Pawn actor = toil.actor; Pawn pawn = (Pawn)actor.jobs.curJob.GetTarget(traineeInd).Thing; if (pawn.Spawned && pawn.Awake() && actor.interactions.TryInteractWith(pawn, InteractionDefOf.TrainAttempt)) { - float num = actor.GetStatValue(StatDefOf.TrainAnimalChance, true); - num *= Mathf.Max(0.05f, GenMath.LerpDouble(0f, 1f, 2f, 0f, pawn.RaceProps.wildness)); + float statValue = actor.GetStatValue(StatDefOf.TrainAnimalChance, true); + statValue *= Mathf.Max(0.05f, GenMath.LerpDouble(0f, 1f, 2f, 0f, pawn.RaceProps.wildness)); if (actor.relations.DirectRelationExists(PawnRelationDefOf.Bond, pawn)) { - num *= 1.5f; + statValue = (float)(statValue * 1.5); } - num = Mathf.Clamp01(num); + statValue = Mathf.Clamp01(statValue); TrainableDef trainableDef = pawn.training.NextTrainableToTrain(); string text; - if (Rand.Value < num) + if (Rand.Value < statValue) { pawn.training.Train(trainableDef, actor); if (pawn.caller != null) { pawn.caller.DoCall(); } - text = "TextMote_TrainSuccess".Translate(new object[] - { - trainableDef.LabelCap, - num.ToStringPercent() - }); + text = "TextMote_TrainSuccess".Translate(trainableDef.LabelCap, statValue.ToStringPercent()); RelationsUtility.TryDevelopBondRelation(actor, pawn, 0.007f); - TaleRecorder.RecordTale(TaleDefOf.TrainedAnimal, new object[] - { - actor, - pawn, - trainableDef - }); + TaleRecorder.RecordTale(TaleDefOf.TrainedAnimal, actor, pawn, trainableDef); } else { - text = "TextMote_TrainFail".Translate(new object[] - { - trainableDef.LabelCap, - num.ToStringPercent() - }); + text = "TextMote_TrainFail".Translate(trainableDef.LabelCap, statValue.ToStringPercent()); } string text2 = text; - text = string.Concat(new object[] - { - text2, - "\n", - pawn.training.GetSteps(trainableDef), - " / ", - trainableDef.steps - }); + text = text2 + "\n" + pawn.training.GetSteps(trainableDef) + " / " + trainableDef.steps; MoteMaker.ThrowText((actor.DrawPos + pawn.DrawPos) / 2f, actor.Map, text, 5f); } }; diff --git a/Assembly-CSharp/RimWorld/Toils_LayDown.cs b/Assembly-CSharp/RimWorld/Toils_LayDown.cs index 5ff67cfbe..f68ffd5b4 100644 --- a/Assembly-CSharp/RimWorld/Toils_LayDown.cs +++ b/Assembly-CSharp/RimWorld/Toils_LayDown.cs @@ -16,103 +16,93 @@ public static class Toils_LayDown public static Toil LayDown(TargetIndex bedOrRestSpotIndex, bool hasBed, bool lookForOtherJobs, bool canSleep = true, bool gainRestAndHealth = true) { Toil layDown = new Toil(); - layDown.initAction = delegate + layDown.initAction = (Action)delegate() { - Pawn actor = layDown.actor; - actor.pather.StopDead(); - JobDriver curDriver = actor.jobs.curDriver; + Pawn actor3 = layDown.actor; + actor3.pather.StopDead(); + JobDriver curDriver3 = actor3.jobs.curDriver; if (hasBed) { - Building_Bed t = (Building_Bed)actor.CurJob.GetTarget(bedOrRestSpotIndex).Thing; - if (!t.OccupiedRect().Contains(actor.Position)) + Building_Bed t = (Building_Bed)actor3.CurJob.GetTarget(bedOrRestSpotIndex).Thing; + if (!t.OccupiedRect().Contains(actor3.Position)) { - Log.Error("Can't start LayDown toil because pawn is not in the bed. pawn=" + actor); - actor.jobs.EndCurrentJob(JobCondition.Errored, true); + Log.Error("Can't start LayDown toil because pawn is not in the bed. pawn=" + actor3); + actor3.jobs.EndCurrentJob(JobCondition.Errored, true); return; } - curDriver.layingDown = LayingDownState.LayingInBed; + curDriver3.layingDown = LayingDownState.LayingInBed; } else { - curDriver.layingDown = LayingDownState.LayingSurface; + curDriver3.layingDown = LayingDownState.LayingSurface; } - curDriver.asleep = false; - actor.mindState.awokeVoluntarily = false; - if (actor.mindState.applyBedThoughtsTick == 0) + curDriver3.asleep = false; + actor3.mindState.awokeVoluntarily = false; + if (actor3.mindState.applyBedThoughtsTick == 0) { - actor.mindState.applyBedThoughtsTick = Find.TickManager.TicksGame + Rand.Range(2500, 10000); - actor.mindState.applyBedThoughtsOnLeave = false; + actor3.mindState.applyBedThoughtsTick = Find.TickManager.TicksGame + Rand.Range(2500, 10000); + actor3.mindState.applyBedThoughtsOnLeave = false; } - if (actor.ownership != null && actor.CurrentBed() != actor.ownership.OwnedBed) + if (actor3.ownership != null && actor3.CurrentBed() != actor3.ownership.OwnedBed) { - ThoughtUtility.RemovePositiveBedroomThoughts(actor); + ThoughtUtility.RemovePositiveBedroomThoughts(actor3); } }; - layDown.tickAction = delegate + layDown.tickAction = (Action)delegate() { - Pawn actor = layDown.actor; - Job curJob = actor.CurJob; - JobDriver curDriver = actor.jobs.curDriver; + Pawn actor2 = layDown.actor; + Job curJob = actor2.CurJob; + JobDriver curDriver2 = actor2.jobs.curDriver; Building_Bed building_Bed = (Building_Bed)curJob.GetTarget(bedOrRestSpotIndex).Thing; - actor.GainComfortFromCellIfPossible(); - if (!curDriver.asleep) + actor2.GainComfortFromCellIfPossible(); + if (!curDriver2.asleep) { - if (canSleep && actor.needs.rest.CurLevel < RestUtility.FallAsleepMaxLevel(actor)) + if (canSleep && actor2.needs.rest.CurLevel < RestUtility.FallAsleepMaxLevel(actor2)) { - curDriver.asleep = true; + curDriver2.asleep = true; } } - else if (!canSleep || actor.needs.rest.CurLevel >= RestUtility.WakeThreshold(actor)) + else if (!canSleep || actor2.needs.rest.CurLevel >= RestUtility.WakeThreshold(actor2)) { - curDriver.asleep = false; + curDriver2.asleep = false; } - if (curDriver.asleep && gainRestAndHealth) + if (curDriver2.asleep && gainRestAndHealth) { - float num; - if (building_Bed != null && building_Bed.def.statBases.StatListContains(StatDefOf.BedRestEffectiveness)) - { - num = building_Bed.GetStatValue(StatDefOf.BedRestEffectiveness, true); - } - else - { - num = 0.8f; - } - float num2 = RestUtility.PawnHealthRestEffectivenessFactor(actor); - num = 0.7f * num + 0.3f * num * num2; - actor.needs.rest.TickResting(num); + float num = (float)((building_Bed == null || !building_Bed.def.statBases.StatListContains(StatDefOf.BedRestEffectiveness)) ? 0.800000011920929 : building_Bed.GetStatValue(StatDefOf.BedRestEffectiveness, true)); + float num2 = RestUtility.PawnHealthRestEffectivenessFactor(actor2); + num = (float)(0.699999988079071 * num + 0.30000001192092896 * num * num2); + actor2.needs.rest.TickResting(num); } - if (actor.mindState.applyBedThoughtsTick != 0 && actor.mindState.applyBedThoughtsTick <= Find.TickManager.TicksGame) + if (actor2.mindState.applyBedThoughtsTick != 0 && actor2.mindState.applyBedThoughtsTick <= Find.TickManager.TicksGame) { - Toils_LayDown.ApplyBedThoughts(actor); - actor.mindState.applyBedThoughtsTick += 60000; - actor.mindState.applyBedThoughtsOnLeave = true; + Toils_LayDown.ApplyBedThoughts(actor2); + actor2.mindState.applyBedThoughtsTick += 60000; + actor2.mindState.applyBedThoughtsOnLeave = true; } - if (actor.IsHashIntervalTick(100) && !actor.Position.Fogged(actor.Map)) + if (actor2.IsHashIntervalTick(100) && !actor2.Position.Fogged(actor2.Map)) { - if (curDriver.asleep) + if (curDriver2.asleep) { - MoteMaker.ThrowMetaIcon(actor.Position, actor.Map, ThingDefOf.Mote_SleepZ); + MoteMaker.ThrowMetaIcon(actor2.Position, actor2.Map, ThingDefOf.Mote_SleepZ); } - if (gainRestAndHealth && actor.health.hediffSet.GetNaturallyHealingInjuredParts().Any()) + if (gainRestAndHealth && actor2.health.hediffSet.GetNaturallyHealingInjuredParts().Any()) { - MoteMaker.ThrowMetaIcon(actor.Position, actor.Map, ThingDefOf.Mote_HealingCross); + MoteMaker.ThrowMetaIcon(actor2.Position, actor2.Map, ThingDefOf.Mote_HealingCross); } } - if (actor.ownership != null && building_Bed != null && !building_Bed.Medical && !building_Bed.owners.Contains(actor)) + if (actor2.ownership != null && building_Bed != null && !building_Bed.Medical && !building_Bed.owners.Contains(actor2)) { - if (actor.Downed) + if (actor2.Downed) { - actor.Position = CellFinder.RandomClosewalkCellNear(actor.Position, actor.Map, 1, null); + actor2.Position = CellFinder.RandomClosewalkCellNear(actor2.Position, actor2.Map, 1, null); } - actor.jobs.EndCurrentJob(JobCondition.Incompletable, true); - return; + actor2.jobs.EndCurrentJob(JobCondition.Incompletable, true); } - if (lookForOtherJobs && actor.IsHashIntervalTick(211)) + else if (lookForOtherJobs && actor2.IsHashIntervalTick(211)) { - actor.mindState.awokeVoluntarily = true; - actor.jobs.CheckForJobOverride(); - actor.mindState.awokeVoluntarily = false; - return; + actor2.mindState.awokeVoluntarily = true; + actor2.jobs.CheckForJobOverride(); + actor2.mindState.awokeVoluntarily = false; } }; layDown.defaultCompleteMode = ToilCompleteMode.Never; @@ -120,7 +110,7 @@ public static Toil LayDown(TargetIndex bedOrRestSpotIndex, bool hasBed, bool loo { layDown.FailOnBedNoLongerUsable(bedOrRestSpotIndex); } - layDown.AddFinishAction(delegate + layDown.AddFinishAction((Action)delegate { Pawn actor = layDown.actor; JobDriver curDriver = actor.jobs.curDriver; @@ -140,50 +130,49 @@ public static Toil LayDown(TargetIndex bedOrRestSpotIndex, bool hasBed, bool loo private static void ApplyBedThoughts(Pawn actor) { - if (actor.needs.mood == null) - { - return; - } - Building_Bed building_Bed = actor.CurrentBed(); - actor.needs.mood.thoughts.memories.RemoveMemoriesOfDef(ThoughtDefOf.SleptInBedroom); - actor.needs.mood.thoughts.memories.RemoveMemoriesOfDef(ThoughtDefOf.SleptInBarracks); - actor.needs.mood.thoughts.memories.RemoveMemoriesOfDef(ThoughtDefOf.SleptOutside); - actor.needs.mood.thoughts.memories.RemoveMemoriesOfDef(ThoughtDefOf.SleptOnGround); - actor.needs.mood.thoughts.memories.RemoveMemoriesOfDef(ThoughtDefOf.SleptInCold); - actor.needs.mood.thoughts.memories.RemoveMemoriesOfDef(ThoughtDefOf.SleptInHeat); - if (actor.GetRoom(RegionType.Set_Passable).PsychologicallyOutdoors) - { - actor.needs.mood.thoughts.memories.TryGainMemory(ThoughtDefOf.SleptOutside, null); - } - if (building_Bed == null || building_Bed.CostListAdjusted().Count == 0) + if (actor.needs.mood != null) { - actor.needs.mood.thoughts.memories.TryGainMemory(ThoughtDefOf.SleptOnGround, null); - } - if (actor.AmbientTemperature < actor.def.GetStatValueAbstract(StatDefOf.ComfyTemperatureMin, null)) - { - actor.needs.mood.thoughts.memories.TryGainMemory(ThoughtDefOf.SleptInCold, null); - } - if (actor.AmbientTemperature > actor.def.GetStatValueAbstract(StatDefOf.ComfyTemperatureMax, null)) - { - actor.needs.mood.thoughts.memories.TryGainMemory(ThoughtDefOf.SleptInHeat, null); - } - if (building_Bed != null && building_Bed == actor.ownership.OwnedBed && !building_Bed.ForPrisoners && !actor.story.traits.HasTrait(TraitDefOf.Ascetic)) - { - ThoughtDef thoughtDef = null; - if (building_Bed.GetRoom(RegionType.Set_Passable).Role == RoomRoleDefOf.Bedroom) + Building_Bed building_Bed = actor.CurrentBed(); + actor.needs.mood.thoughts.memories.RemoveMemoriesOfDef(ThoughtDefOf.SleptInBedroom); + actor.needs.mood.thoughts.memories.RemoveMemoriesOfDef(ThoughtDefOf.SleptInBarracks); + actor.needs.mood.thoughts.memories.RemoveMemoriesOfDef(ThoughtDefOf.SleptOutside); + actor.needs.mood.thoughts.memories.RemoveMemoriesOfDef(ThoughtDefOf.SleptOnGround); + actor.needs.mood.thoughts.memories.RemoveMemoriesOfDef(ThoughtDefOf.SleptInCold); + actor.needs.mood.thoughts.memories.RemoveMemoriesOfDef(ThoughtDefOf.SleptInHeat); + if (actor.GetRoom(RegionType.Set_Passable).PsychologicallyOutdoors) + { + actor.needs.mood.thoughts.memories.TryGainMemory(ThoughtDefOf.SleptOutside, null); + } + if (building_Bed == null || building_Bed.CostListAdjusted().Count == 0) + { + actor.needs.mood.thoughts.memories.TryGainMemory(ThoughtDefOf.SleptOnGround, null); + } + if (actor.AmbientTemperature < actor.def.GetStatValueAbstract(StatDefOf.ComfyTemperatureMin, null)) { - thoughtDef = ThoughtDefOf.SleptInBedroom; + actor.needs.mood.thoughts.memories.TryGainMemory(ThoughtDefOf.SleptInCold, null); } - else if (building_Bed.GetRoom(RegionType.Set_Passable).Role == RoomRoleDefOf.Barracks) + if (actor.AmbientTemperature > actor.def.GetStatValueAbstract(StatDefOf.ComfyTemperatureMax, null)) { - thoughtDef = ThoughtDefOf.SleptInBarracks; + actor.needs.mood.thoughts.memories.TryGainMemory(ThoughtDefOf.SleptInHeat, null); } - if (thoughtDef != null) + if (building_Bed != null && building_Bed == actor.ownership.OwnedBed && !building_Bed.ForPrisoners && !actor.story.traits.HasTrait(TraitDefOf.Ascetic)) { - int scoreStageIndex = RoomStatDefOf.Impressiveness.GetScoreStageIndex(building_Bed.GetRoom(RegionType.Set_Passable).GetStat(RoomStatDefOf.Impressiveness)); - if (thoughtDef.stages[scoreStageIndex] != null) + ThoughtDef thoughtDef = null; + if (building_Bed.GetRoom(RegionType.Set_Passable).Role == RoomRoleDefOf.Bedroom) + { + thoughtDef = ThoughtDefOf.SleptInBedroom; + } + else if (building_Bed.GetRoom(RegionType.Set_Passable).Role == RoomRoleDefOf.Barracks) + { + thoughtDef = ThoughtDefOf.SleptInBarracks; + } + if (thoughtDef != null) { - actor.needs.mood.thoughts.memories.TryGainMemory(ThoughtMaker.MakeThought(thoughtDef, scoreStageIndex), null); + int scoreStageIndex = RoomStatDefOf.Impressiveness.GetScoreStageIndex(building_Bed.GetRoom(RegionType.Set_Passable).GetStat(RoomStatDefOf.Impressiveness)); + if (thoughtDef.stages[scoreStageIndex] != null) + { + actor.needs.mood.thoughts.memories.TryGainMemory(ThoughtMaker.MakeThought(thoughtDef, scoreStageIndex), null); + } } } } diff --git a/Assembly-CSharp/RimWorld/Toils_Misc.cs b/Assembly-CSharp/RimWorld/Toils_Misc.cs index a6d6d2fda..4ffa04bee 100644 --- a/Assembly-CSharp/RimWorld/Toils_Misc.cs +++ b/Assembly-CSharp/RimWorld/Toils_Misc.cs @@ -10,7 +10,7 @@ public static class Toils_Misc public static Toil Learn(SkillDef skill, float xp) { Toil toil = new Toil(); - toil.initAction = delegate + toil.initAction = (Action)delegate() { toil.actor.skills.Learn(skill, xp, false); }; @@ -20,7 +20,7 @@ public static Toil Learn(SkillDef skill, float xp) public static Toil SetForbidden(TargetIndex ind, bool forbidden) { Toil toil = new Toil(); - toil.initAction = delegate + toil.initAction = (Action)delegate() { toil.actor.CurJob.GetTarget(ind).Thing.SetForbidden(forbidden, true); }; @@ -29,23 +29,22 @@ public static Toil SetForbidden(TargetIndex ind, bool forbidden) public static Toil TakeItemFromInventoryToCarrier(Pawn pawn, TargetIndex itemInd) { - return new Toil + Toil toil = new Toil(); + toil.initAction = (Action)delegate() { - initAction = delegate - { - Job curJob = pawn.CurJob; - Thing thing = (Thing)curJob.GetTarget(itemInd); - int count = Mathf.Min(thing.stackCount, curJob.count); - pawn.inventory.innerContainer.TryTransferToContainer(thing, pawn.carryTracker.innerContainer, count, true); - curJob.SetTarget(itemInd, pawn.carryTracker.CarriedThing); - } + Job curJob = pawn.CurJob; + Thing thing = (Thing)curJob.GetTarget(itemInd); + int count = Mathf.Min(thing.stackCount, curJob.count); + pawn.inventory.innerContainer.TryTransferToContainer(thing, pawn.carryTracker.innerContainer, count, true); + curJob.SetTarget(itemInd, pawn.carryTracker.CarriedThing); }; + return toil; } public static Toil ThrowColonistAttackingMote(TargetIndex target) { Toil toil = new Toil(); - toil.initAction = delegate + toil.initAction = (Action)delegate() { Pawn actor = toil.actor; Job curJob = actor.CurJob; diff --git a/Assembly-CSharp/RimWorld/Toils_Refuel.cs b/Assembly-CSharp/RimWorld/Toils_Refuel.cs index 424dc5176..0e827613a 100644 --- a/Assembly-CSharp/RimWorld/Toils_Refuel.cs +++ b/Assembly-CSharp/RimWorld/Toils_Refuel.cs @@ -9,7 +9,7 @@ public class Toils_Refuel public static Toil FinalizeRefueling(TargetIndex refuelableInd, TargetIndex fuelInd) { Toil toil = new Toil(); - toil.initAction = delegate + toil.initAction = (Action)delegate() { Pawn actor = toil.actor; Job curJob = actor.CurJob; diff --git a/Assembly-CSharp/RimWorld/Toils_Tend.cs b/Assembly-CSharp/RimWorld/Toils_Tend.cs index c8584aaae..39ef8a3a5 100644 --- a/Assembly-CSharp/RimWorld/Toils_Tend.cs +++ b/Assembly-CSharp/RimWorld/Toils_Tend.cs @@ -10,7 +10,7 @@ public class Toils_Tend public static Toil PickupMedicine(TargetIndex ind, Pawn injured) { Toil toil = new Toil(); - toil.initAction = delegate + toil.initAction = (Action)delegate() { Pawn actor = toil.actor; Job curJob = actor.jobs.curJob; @@ -39,12 +39,12 @@ public static Toil PickupMedicine(TargetIndex ind, Pawn injured) public static Toil FinalizeTend(Pawn patient) { Toil toil = new Toil(); - toil.initAction = delegate + toil.initAction = (Action)delegate() { Pawn actor = toil.actor; Medicine medicine = (Medicine)actor.jobs.curJob.targetB.Thing; - float num = (!patient.RaceProps.Animal) ? 500f : 175f; - float num2 = (medicine != null) ? medicine.def.MedicineTendXpGainFactor : 0.5f; + float num = (float)((!patient.RaceProps.Animal) ? 500.0 : 175.0); + float num2 = (float)((medicine != null) ? medicine.def.MedicineTendXpGainFactor : 0.5); actor.skills.Learn(SkillDefOf.Medicine, num * num2, false); TendUtility.DoTend(actor, patient, medicine); if (medicine != null && medicine.Destroyed) diff --git a/Assembly-CSharp/RimWorld/TradeAction.cs b/Assembly-CSharp/RimWorld/TradeAction.cs index 562edd231..b7d094adf 100644 --- a/Assembly-CSharp/RimWorld/TradeAction.cs +++ b/Assembly-CSharp/RimWorld/TradeAction.cs @@ -1,11 +1,9 @@ -using System; - namespace RimWorld { public enum TradeAction : byte { - None, - PlayerBuys, - PlayerSells + None = 0, + PlayerBuys = 1, + PlayerSells = 2 } } diff --git a/Assembly-CSharp/RimWorld/TradeDeal.cs b/Assembly-CSharp/RimWorld/TradeDeal.cs index 381474c0a..58419e919 100644 --- a/Assembly-CSharp/RimWorld/TradeDeal.cs +++ b/Assembly-CSharp/RimWorld/TradeDeal.cs @@ -50,7 +50,7 @@ public TradeDeal() public IEnumerator GetEnumerator() { - return this.tradeables.GetEnumerator(); + return (IEnumerator)(object)this.tradeables.GetEnumerator(); } public void Reset() @@ -62,10 +62,10 @@ public void Reset() private void AddAllTradeables() { - foreach (Thing current in TradeSession.trader.ColonyThingsWillingToBuy(TradeSession.playerNegotiator)) + foreach (Thing item in TradeSession.trader.ColonyThingsWillingToBuy(TradeSession.playerNegotiator)) { - string text; - if (!TradeSession.playerNegotiator.IsWorldPawn() && !this.InSellablePosition(current, out text)) + string text = default(string); + if (!TradeSession.playerNegotiator.IsWorldPawn() && !this.InSellablePosition(item, out text)) { if (text != null && !this.cannotSellReasons.Contains(text)) { @@ -74,14 +74,14 @@ private void AddAllTradeables() } else { - this.AddToTradeables(current, Transactor.Colony); + this.AddToTradeables(item, Transactor.Colony); } } - foreach (Thing current2 in TradeSession.trader.Goods) + foreach (Thing good in TradeSession.trader.Goods) { - this.AddToTradeables(current2, Transactor.Trader); + this.AddToTradeables(good, Transactor.Trader); } - if (this.tradeables.Find((Tradeable x) => x.IsCurrency) == null) + if (this.tradeables.Find((Predicate)((Tradeable x) => x.IsCurrency)) == null) { Thing thing = ThingMaker.MakeThing(ThingDefOf.Silver, null); thing.stackCount = 0; @@ -93,27 +93,27 @@ private bool InSellablePosition(Thing t, out string reason) { if (!t.Spawned) { - reason = null; + reason = (string)null; return false; } if (t.Position.Fogged(t.Map)) { - reason = null; + reason = (string)null; return false; } Room room = t.GetRoom(RegionType.Set_Passable); if (room != null) { int num = GenRadial.NumCellsInRadius(6.9f); - for (int i = 0; i < num; i++) + for (int num2 = 0; num2 < num; num2++) { - IntVec3 intVec = t.Position + GenRadial.RadialPattern[i]; + IntVec3 intVec = t.Position + GenRadial.RadialPattern[num2]; if (intVec.InBounds(t.Map) && intVec.GetRoom(t.Map, RegionType.Set_Passable) == room) { List thingList = intVec.GetThingList(t.Map); - for (int j = 0; j < thingList.Count; j++) + for (int i = 0; i < thingList.Count; i++) { - if (thingList[j].PreventPlayerSellingThingsNearby(out reason)) + if (thingList[i].PreventPlayerSellingThingsNearby(out reason)) { return false; } @@ -121,24 +121,17 @@ private bool InSellablePosition(Thing t, out string reason) } } } - reason = null; + reason = (string)null; return true; } private void AddToTradeables(Thing t, Transactor trans) { - Tradeable tradeable = TransferableUtility.TransferableMatching(t, this.tradeables); + Tradeable tradeable = TransferableUtility.TransferableMatching(t, this.tradeables); if (tradeable == null) { Pawn pawn = t as Pawn; - if (pawn != null) - { - tradeable = new Tradeable_Pawn(); - } - else - { - tradeable = new Tradeable(); - } + tradeable = ((pawn == null) ? new Tradeable() : new Tradeable_Pawn()); this.tradeables.Add(tradeable); } tradeable.AddThing(t, trans); @@ -147,13 +140,22 @@ private void AddToTradeables(Thing t, Transactor trans) public void UpdateCurrencyCount() { float num = 0f; - foreach (Tradeable current in this.tradeables) + List.Enumerator enumerator = this.tradeables.GetEnumerator(); + try { - if (!current.IsCurrency) + while (enumerator.MoveNext()) { - num += current.CurTotalSilverCost; + Tradeable current = enumerator.Current; + if (!current.IsCurrency) + { + num += current.CurTotalSilverCost; + } } } + finally + { + ((IDisposable)(object)enumerator).Dispose(); + } this.SilverTradeable.ForceTo(-Mathf.RoundToInt(num)); } @@ -169,13 +171,22 @@ public bool TryExecute(out bool actuallyTraded) this.UpdateCurrencyCount(); this.LimitCurrencyCountToTraderFunds(); actuallyTraded = false; - foreach (Tradeable current in this.tradeables) + List.Enumerator enumerator = this.tradeables.GetEnumerator(); + try { - if (current.ActionToDo != TradeAction.None) + while (enumerator.MoveNext()) { - actuallyTraded = true; + Tradeable current = enumerator.Current; + if (current.ActionToDo != 0) + { + actuallyTraded = true; + } + current.ResolveTrade(); } - current.ResolveTrade(); + } + finally + { + ((IDisposable)(object)enumerator).Dispose(); } this.Reset(); return true; diff --git a/Assembly-CSharp/RimWorld/TradeSession.cs b/Assembly-CSharp/RimWorld/TradeSession.cs index 8addb15cd..e86ebb174 100644 --- a/Assembly-CSharp/RimWorld/TradeSession.cs +++ b/Assembly-CSharp/RimWorld/TradeSession.cs @@ -1,4 +1,3 @@ -using System; using Verse; namespace RimWorld diff --git a/Assembly-CSharp/RimWorld/TradeShip.cs b/Assembly-CSharp/RimWorld/TradeShip.cs index df39f36f9..2ca26e05b 100644 --- a/Assembly-CSharp/RimWorld/TradeShip.cs +++ b/Assembly-CSharp/RimWorld/TradeShip.cs @@ -1,6 +1,5 @@ using System; using System.Collections.Generic; -using System.Diagnostics; using System.Linq; using Verse; @@ -22,7 +21,7 @@ public override string FullTitle { get { - return this.name + " (" + this.def.label + ")"; + return base.name + " (" + this.def.label + ")"; } } @@ -62,7 +61,7 @@ public string TraderName { get { - return this.name; + return base.name; } } @@ -94,11 +93,14 @@ public IEnumerable Goods { get { - TradeShip.<>c__Iterator181 <>c__Iterator = new TradeShip.<>c__Iterator181(); - <>c__Iterator.<>f__this = this; - TradeShip.<>c__Iterator181 expr_0E = <>c__Iterator; - expr_0E.$PC = -2; - return expr_0E; + for (int i = 0; i < this.things.Count; i++) + { + Pawn p = this.things[i] as Pawn; + if (p == null || !this.soldPrisoners.Contains(p)) + { + yield return this.things[i]; + } + } } } @@ -117,35 +119,39 @@ public TradeShip(TraderKindDef def) TradeShip.tmpExtantNames.AddRange(from x in maps[i].passingShipManager.passingShips select x.name); } - this.name = NameGenerator.GenerateName(RulePackDefOf.NamerTraderGeneral, TradeShip.tmpExtantNames, false); + base.name = NameGenerator.GenerateName(RulePackDefOf.NamerTraderGeneral, TradeShip.tmpExtantNames, false); this.randomPriceFactorSeed = Rand.RangeInclusive(1, 10000000); - this.loadID = Find.World.uniqueIDsManager.GetNextPassingShipID(); + base.loadID = Find.World.uniqueIDsManager.GetNextPassingShipID(); } - [DebuggerHidden] public IEnumerable ColonyThingsWillingToBuy(Pawn playerNegotiator) { - TradeShip.c__Iterator182 c__Iterator = new TradeShip.c__Iterator182(); - c__Iterator.<>f__this = this; - TradeShip.c__Iterator182 expr_0E = c__Iterator; - expr_0E.$PC = -2; - return expr_0E; + foreach (Thing item in TradeUtility.AllLaunchableThings(base.Map)) + { + yield return item; + } + foreach (Pawn item2 in TradeUtility.AllSellableColonyPawns(base.Map)) + { + yield return (Thing)item2; + } } public void GenerateThings() { - ItemCollectionGeneratorParams parms = default(ItemCollectionGeneratorParams); - parms.traderDef = this.def; - parms.forTile = base.Map.Tile; + ItemCollectionGeneratorParams parms = new ItemCollectionGeneratorParams + { + traderDef = this.def, + forTile = base.Map.Tile + }; this.things.TryAddRange(ItemCollectionGeneratorDefOf.TraderStock.Worker.Generate(parms), true); } public override void PassingShipTick() { base.PassingShipTick(); - for (int i = this.things.Count - 1; i >= 0; i--) + for (int num = this.things.Count - 1; num >= 0; num--) { - Pawn pawn = this.things[i] as Pawn; + Pawn pawn = this.things[num] as Pawn; if (pawn != null) { pawn.Tick(); @@ -161,7 +167,7 @@ public override void ExposeData() { base.ExposeData(); Scribe_Defs.Look(ref this.def, "def"); - Scribe_Deep.Look(ref this.things, "things", new object[] + Scribe_Deep.Look(ref this.things, "things", new object[1] { this }); @@ -169,26 +175,25 @@ public override void ExposeData() Scribe_Values.Look(ref this.randomPriceFactorSeed, "randomPriceFactorSeed", 0, false); if (Scribe.mode == LoadSaveMode.PostLoadInit) { - this.soldPrisoners.RemoveAll((Pawn x) => x == null); + this.soldPrisoners.RemoveAll((Predicate)((Pawn x) => x == null)); } } public override void TryOpenComms(Pawn negotiator) { - if (!this.CanTradeNow) - { - return; - } - Find.WindowStack.Add(new Dialog_Trade(negotiator, this)); - LessonAutoActivator.TeachOpportunity(ConceptDefOf.BuildOrbitalTradeBeacon, OpportunityType.Critical); - string empty = string.Empty; - string empty2 = string.Empty; - PawnRelationUtility.Notify_PawnsSeenByPlayer(this.Goods.OfType(), ref empty, ref empty2, "LetterRelatedPawnsTradeShip".Translate(), false); - if (!empty2.NullOrEmpty()) + if (this.CanTradeNow) { - Find.LetterStack.ReceiveLetter(empty, empty2, LetterDefOf.Good, null); + Find.WindowStack.Add(new Dialog_Trade(negotiator, this)); + LessonAutoActivator.TeachOpportunity(ConceptDefOf.BuildOrbitalTradeBeacon, OpportunityType.Critical); + string empty = string.Empty; + string empty2 = string.Empty; + PawnRelationUtility.Notify_PawnsSeenByPlayer(this.Goods.OfType(), ref empty, ref empty2, "LetterRelatedPawnsTradeShip".Translate(), false); + if (!empty2.NullOrEmpty()) + { + Find.LetterStack.ReceiveLetter(empty, empty2, LetterDefOf.Good, (string)null); + } + TutorUtility.DoModalDialogIfNotKnown(ConceptDefOf.TradeGoodsMustBeNearBeacon); } - TutorUtility.DoModalDialogIfNotKnown(ConceptDefOf.TradeGoodsMustBeNearBeacon); } public override void Depart() @@ -200,7 +205,7 @@ public override void Depart() public override string GetCallLabel() { - return this.name + " (" + this.def.label + ")"; + return base.name + " (" + this.def.label + ")"; } public int CountHeldOf(ThingDef thingDef, ThingDef stuffDef = null) diff --git a/Assembly-CSharp/RimWorld/TradeUI.cs b/Assembly-CSharp/RimWorld/TradeUI.cs index 76e808cd7..4d6dcc087 100644 --- a/Assembly-CSharp/RimWorld/TradeUI.cs +++ b/Assembly-CSharp/RimWorld/TradeUI.cs @@ -27,11 +27,11 @@ public static void DrawTradeableRow(Rect rect, Tradeable trad, int index) } Text.Font = GameFont.Small; GUI.BeginGroup(rect); - float num = rect.width; - int num2 = trad.CountHeldBy(Transactor.Trader); - if (num2 != 0) + float width = rect.width; + int num = trad.CountHeldBy(Transactor.Trader); + if (num != 0) { - Rect rect2 = new Rect(num - 75f, 0f, 75f, rect.height); + Rect rect2 = new Rect((float)(width - 75.0), 0f, 75f, rect.height); if (Mouse.IsOver(rect2)) { Widgets.DrawHighlight(rect2); @@ -40,31 +40,31 @@ public static void DrawTradeableRow(Rect rect, Tradeable trad, int index) Rect rect3 = rect2; rect3.xMin += 5f; rect3.xMax -= 5f; - Widgets.Label(rect3, num2.ToStringCached()); + Widgets.Label(rect3, num.ToStringCached()); TooltipHandler.TipRegion(rect2, "TraderCount".Translate()); - Rect rect4 = new Rect(rect2.x - 100f, 0f, 100f, rect.height); + Rect rect4 = new Rect((float)(rect2.x - 100.0), 0f, 100f, rect.height); Text.Anchor = TextAnchor.MiddleRight; TradeUI.DrawPrice(rect4, trad, TradeAction.PlayerBuys); } - num -= 175f; - Rect rect5 = new Rect(num - 240f, 0f, 240f, rect.height); + width = (float)(width - 175.0); + Rect rect5 = new Rect((float)(width - 240.0), 0f, 240f, rect.height); if (trad.TraderWillTrade) { - bool flash = Time.time - Dialog_Trade.lastCurrencyFlashTime < 1f && trad.IsCurrency; + bool flash = Time.time - Dialog_Trade.lastCurrencyFlashTime < 1.0 && trad.IsCurrency; TransferableUIUtility.DoCountAdjustInterface(rect5, trad, index, -trad.CountHeldBy(Transactor.Colony), trad.CountHeldBy(Transactor.Trader), flash, null); } else { TradeUI.DrawWillNotTradeIndication(rect, trad); } - num -= 240f; - int num3 = trad.CountHeldBy(Transactor.Colony); - if (num3 != 0) + width = (float)(width - 240.0); + int num2 = trad.CountHeldBy(Transactor.Colony); + if (num2 != 0) { - Rect rect6 = new Rect(num - 100f, 0f, 100f, rect.height); + Rect rect6 = new Rect((float)(width - 100.0), 0f, 100f, rect.height); Text.Anchor = TextAnchor.MiddleLeft; TradeUI.DrawPrice(rect6, trad, TradeAction.PlayerSells); - Rect rect7 = new Rect(rect6.x - 75f, 0f, 75f, rect.height); + Rect rect7 = new Rect((float)(rect6.x - 75.0), 0f, 75f, rect.height); if (Mouse.IsOver(rect7)) { Widgets.DrawHighlight(rect7); @@ -73,11 +73,11 @@ public static void DrawTradeableRow(Rect rect, Tradeable trad, int index) Rect rect8 = rect7; rect8.xMin += 5f; rect8.xMax -= 5f; - Widgets.Label(rect8, num3.ToStringCached()); + Widgets.Label(rect8, num2.ToStringCached()); TooltipHandler.TipRegion(rect7, "ColonyCount".Translate()); } - num -= 175f; - Rect idRect = new Rect(0f, 0f, num, rect.height); + width = (float)(width - 175.0); + Rect idRect = new Rect(0f, 0f, width, rect.height); TransferableUIUtility.DrawTransferableInfo(trad, idRect, (!trad.TraderWillTrade) ? TradeUI.NoTradeColor : Color.white); GenUI.ResetLabelAlign(); GUI.EndGroup(); @@ -85,73 +85,92 @@ public static void DrawTradeableRow(Rect rect, Tradeable trad, int index) private static void DrawPrice(Rect rect, Tradeable trad, TradeAction action) { - if (trad.IsCurrency || !trad.TraderWillTrade) - { - return; - } - rect = rect.Rounded(); - if (Mouse.IsOver(rect)) + if (!trad.IsCurrency && trad.TraderWillTrade) { - Widgets.DrawHighlight(rect); - } - TooltipHandler.TipRegion(rect, new TipSignal(() => trad.GetPriceTooltip(action), trad.GetHashCode() * 297)); - if (action == TradeAction.PlayerBuys) - { - switch (trad.PriceTypeFor(action)) + rect = rect.Rounded(); + if (Mouse.IsOver(rect)) { - case PriceType.VeryCheap: - GUI.color = new Color(0f, 1f, 0f); - break; - case PriceType.Cheap: - GUI.color = new Color(0.5f, 1f, 0.5f); - break; - case PriceType.Normal: - GUI.color = Color.white; - break; - case PriceType.Expensive: - GUI.color = new Color(1f, 0.5f, 0.5f); - break; - case PriceType.Exorbitant: - GUI.color = new Color(1f, 0f, 0f); - break; + Widgets.DrawHighlight(rect); } - } - else - { - switch (trad.PriceTypeFor(action)) + TooltipHandler.TipRegion(rect, new TipSignal((Func)(() => trad.GetPriceTooltip(action)), trad.GetHashCode() * 297)); + if (action == TradeAction.PlayerBuys) { - case PriceType.VeryCheap: - GUI.color = new Color(1f, 0f, 0f); - break; - case PriceType.Cheap: - GUI.color = new Color(1f, 0.5f, 0.5f); - break; - case PriceType.Normal: - GUI.color = Color.white; - break; - case PriceType.Expensive: - GUI.color = new Color(0.5f, 1f, 0.5f); - break; - case PriceType.Exorbitant: - GUI.color = new Color(0f, 1f, 0f); - break; + switch (trad.PriceTypeFor(action)) + { + case PriceType.VeryCheap: + { + GUI.color = new Color(0f, 1f, 0f); + break; + } + case PriceType.Cheap: + { + GUI.color = new Color(0.5f, 1f, 0.5f); + break; + } + case PriceType.Normal: + { + GUI.color = Color.white; + break; + } + case PriceType.Expensive: + { + GUI.color = new Color(1f, 0.5f, 0.5f); + break; + } + case PriceType.Exorbitant: + { + GUI.color = new Color(1f, 0f, 0f); + break; + } + } } + else + { + switch (trad.PriceTypeFor(action)) + { + case PriceType.VeryCheap: + { + GUI.color = new Color(1f, 0f, 0f); + break; + } + case PriceType.Cheap: + { + GUI.color = new Color(1f, 0.5f, 0.5f); + break; + } + case PriceType.Normal: + { + GUI.color = Color.white; + break; + } + case PriceType.Expensive: + { + GUI.color = new Color(0.5f, 1f, 0.5f); + break; + } + case PriceType.Exorbitant: + { + GUI.color = new Color(0f, 1f, 0f); + break; + } + } + } + float priceFor = trad.GetPriceFor(action); + string label = priceFor.ToStringMoney(); + Rect rect2 = new Rect(rect); + rect2.xMax -= 5f; + rect2.xMin += 5f; + if (Text.Anchor == TextAnchor.MiddleLeft) + { + rect2.xMax += 300f; + } + if (Text.Anchor == TextAnchor.MiddleRight) + { + rect2.xMin -= 300f; + } + Widgets.Label(rect2, label); + GUI.color = Color.white; } - float priceFor = trad.GetPriceFor(action); - string label = priceFor.ToStringMoney(); - Rect rect2 = new Rect(rect); - rect2.xMax -= 5f; - rect2.xMin += 5f; - if (Text.Anchor == TextAnchor.MiddleLeft) - { - rect2.xMax += 300f; - } - if (Text.Anchor == TextAnchor.MiddleRight) - { - rect2.xMin -= 300f; - } - Widgets.Label(rect2, label); - GUI.color = Color.white; } private static void DrawWillNotTradeIndication(Rect rect, Tradeable trad) diff --git a/Assembly-CSharp/RimWorld/TradeUtility.cs b/Assembly-CSharp/RimWorld/TradeUtility.cs index d9209b171..a4ee7aca0 100644 --- a/Assembly-CSharp/RimWorld/TradeUtility.cs +++ b/Assembly-CSharp/RimWorld/TradeUtility.cs @@ -1,6 +1,5 @@ using System; using System.Collections.Generic; -using System.Diagnostics; using System.Linq; using Verse; using Verse.AI.Group; @@ -11,38 +10,80 @@ public static class TradeUtility { public static bool EverTradeable(ThingDef def) { - return def.tradeability != Tradeability.Never && ((def.category == ThingCategory.Item || def.category == ThingCategory.Pawn) && def.GetStatValueAbstract(StatDefOf.MarketValue, null) > 0f); + if (def.tradeability == Tradeability.Never) + { + return false; + } + if ((def.category == ThingCategory.Item || def.category == ThingCategory.Pawn) && def.GetStatValueAbstract(StatDefOf.MarketValue, null) > 0.0) + { + return true; + } + return false; } public static void SpawnDropPod(IntVec3 dropSpot, Map map, Thing t) { - DropPodUtility.MakeDropPodAt(dropSpot, map, new ActiveDropPodInfo - { - SingleContainedThing = t, - leaveSlag = false - }); + ActiveDropPodInfo activeDropPodInfo = new ActiveDropPodInfo(); + activeDropPodInfo.SingleContainedThing = t; + activeDropPodInfo.leaveSlag = false; + DropPodUtility.MakeDropPodAt(dropSpot, map, activeDropPodInfo); } - [DebuggerHidden] public static IEnumerable AllLaunchableThings(Map map) { - TradeUtility.c__Iterator183 c__Iterator = new TradeUtility.c__Iterator183(); - c__Iterator.map = map; - c__Iterator.<$>map = map; - TradeUtility.c__Iterator183 expr_15 = c__Iterator; - expr_15.$PC = -2; - return expr_15; + HashSet yieldedThings = new HashSet(); + foreach (Building_OrbitalTradeBeacon item in Building_OrbitalTradeBeacon.AllPowered(map)) + { + foreach (IntVec3 tradeableCell in item.TradeableCells) + { + List thingList = tradeableCell.GetThingList(map); + for (int i = 0; i < thingList.Count; i++) + { + Thing t = thingList[i]; + if (TradeUtility.EverTradeable(t.def) && t.def.category == ThingCategory.Item && !yieldedThings.Contains(t) && TradeUtility.TradeableNow(t)) + { + yieldedThings.Add(t); + yield return t; + } + } + } + } } - [DebuggerHidden] public static IEnumerable AllSellableColonyPawns(Map map) { - TradeUtility.c__Iterator184 c__Iterator = new TradeUtility.c__Iterator184(); - c__Iterator.map = map; - c__Iterator.<$>map = map; - TradeUtility.c__Iterator184 expr_15 = c__Iterator; - expr_15.$PC = -2; - return expr_15; + List.Enumerator enumerator = map.mapPawns.PrisonersOfColonySpawned.GetEnumerator(); + try + { + while (enumerator.MoveNext()) + { + Pawn p2 = enumerator.Current; + if (p2.guest.PrisonerIsSecure) + { + yield return p2; + } + } + } + finally + { + ((IDisposable)(object)enumerator).Dispose(); + } + List.Enumerator enumerator2 = map.mapPawns.SpawnedPawnsInFaction(Faction.OfPlayer).GetEnumerator(); + try + { + while (enumerator2.MoveNext()) + { + Pawn p = enumerator2.Current; + if (p.RaceProps.Animal && p.HostFaction == null && !p.InMentalState && !p.Downed && map.mapTemperature.SeasonAndOutdoorTemperatureAcceptableFor(p.def)) + { + yield return p; + } + } + } + finally + { + ((IDisposable)(object)enumerator2).Dispose(); + } } public static Thing ThingFromStockToMergeWith(ITrader trader, Thing thing) @@ -51,11 +92,11 @@ public static Thing ThingFromStockToMergeWith(ITrader trader, Thing thing) { return null; } - foreach (Thing current in trader.Goods) + foreach (Thing good in trader.Goods) { - if (TransferableUtility.TransferAsOne(current, thing)) + if (TransferableUtility.TransferAsOne(good, thing)) { - return current; + return good; } } return null; @@ -63,45 +104,56 @@ public static Thing ThingFromStockToMergeWith(ITrader trader, Thing thing) public static bool TradeableNow(Thing t) { - return !t.IsNotFresh(); + if (t.IsNotFresh()) + { + return false; + } + return true; } public static void LaunchThingsOfType(ThingDef resDef, int debt, Map map, TradeShip trader) { - while (debt > 0) + while (true) { - Thing thing = null; - foreach (Building_OrbitalTradeBeacon current in Building_OrbitalTradeBeacon.AllPowered(map)) + Thing thing; + if (debt > 0) { - foreach (IntVec3 current2 in current.TradeableCells) + thing = null; + foreach (Building_OrbitalTradeBeacon item in Building_OrbitalTradeBeacon.AllPowered(map)) { - foreach (Thing current3 in map.thingGrid.ThingsAt(current2)) + foreach (IntVec3 tradeableCell in item.TradeableCells) { - if (current3.def == resDef) + foreach (Thing item2 in map.thingGrid.ThingsAt(tradeableCell)) { - thing = current3; - goto IL_C6; + if (item2.def == resDef) + { + thing = item2; + goto IL_00c6; + } } } } + goto IL_00c6; } - IL_C6: - if (thing == null) - { - Log.Error("Could not find any " + resDef + " to transfer to trader."); - break; - } - int num = Math.Min(debt, thing.stackCount); - if (trader != null) - { - trader.GiveSoldThingToTrader(thing, num, TradeSession.playerNegotiator); - } - else + return; + IL_00c6: + if (thing != null) { - thing.SplitOff(num).Destroy(DestroyMode.Vanish); + int num = Math.Min(debt, thing.stackCount); + if (trader != null) + { + trader.GiveSoldThingToTrader(thing, num, TradeSession.playerNegotiator); + } + else + { + thing.SplitOff(num).Destroy(DestroyMode.Vanish); + } + debt -= num; + continue; } - debt -= num; + break; } + Log.Error("Could not find any " + resDef + " to transfer to trader."); } public static void LaunchSilver(Map map, int fee) @@ -113,28 +165,27 @@ public static Map PlayerHomeMapWithMostLaunchableSilver() { return (from x in Find.Maps where x.IsPlayerHome - select x).MaxBy((Map x) => (from t in TradeUtility.AllLaunchableThings(x) + select x).MaxBy((Func)((Map x) => (from t in TradeUtility.AllLaunchableThings(x) where t.def == ThingDefOf.Silver - select t).Sum((Thing t) => t.stackCount)); + select t).Sum((Func)((Thing t) => t.stackCount)))); } public static bool ColonyHasEnoughSilver(Map map, int fee) { return (from t in TradeUtility.AllLaunchableThings(map) where t.def == ThingDefOf.Silver - select t).Sum((Thing t) => t.stackCount) >= fee; + select t).Sum((Func)((Thing t) => t.stackCount)) >= fee; } public static void CheckInteractWithTradersTeachOpportunity(Pawn pawn) { - if (pawn.Dead) + if (!pawn.Dead) { - return; - } - Lord lord = pawn.GetLord(); - if (lord != null && lord.CurLordToil is LordToil_DefendTraderCaravan) - { - LessonAutoActivator.TeachOpportunity(ConceptDefOf.InteractingWithTraders, pawn, OpportunityType.Important); + Lord lord = pawn.GetLord(); + if (lord != null && lord.CurLordToil is LordToil_DefendTraderCaravan) + { + LessonAutoActivator.TeachOpportunity(ConceptDefOf.InteractingWithTraders, pawn, OpportunityType.Important); + } } } } diff --git a/Assembly-CSharp/RimWorld/Tradeable.cs b/Assembly-CSharp/RimWorld/Tradeable.cs index 243f94387..069efeaf0 100644 --- a/Assembly-CSharp/RimWorld/Tradeable.cs +++ b/Assembly-CSharp/RimWorld/Tradeable.cs @@ -164,7 +164,11 @@ public bool IsCurrency { get { - return !this.Bugged && this.ThingDef == ThingDefOf.Silver; + if (this.Bugged) + { + return false; + } + return this.ThingDef == ThingDefOf.Silver; } } @@ -238,33 +242,32 @@ public PriceType PriceTypeFor(TradeAction action) private void InitPriceDataIfNeeded() { - if (this.pricePlayerBuy > 0f) - { - return; - } - this.priceFactorBuy_TraderPriceType = this.PriceTypeFor(TradeAction.PlayerBuys).PriceMultiplier(); - this.priceFactorSell_TraderPriceType = this.PriceTypeFor(TradeAction.PlayerSells).PriceMultiplier(); - this.priceGain_PlayerNegotiator = TradeSession.playerNegotiator.GetStatValue(StatDefOf.TradePriceImprovement, true); - this.priceGain_FactionBase = TradeSession.trader.TradePriceImprovementOffsetForPlayer; - this.pricePlayerBuy = this.BaseMarketValue * 1.5f * this.priceFactorBuy_TraderPriceType * (1f + Find.Storyteller.difficulty.tradePriceFactorLoss); - this.pricePlayerBuy *= 1f - this.priceGain_PlayerNegotiator - this.priceGain_FactionBase; - this.pricePlayerBuy = Mathf.Max(this.pricePlayerBuy, 0.5f); - if (this.pricePlayerBuy > 99.5f) - { - this.pricePlayerBuy = Mathf.Round(this.pricePlayerBuy); - } - this.priceFactorSell_ItemSellPriceFactor = this.AnyThing.GetStatValue(StatDefOf.SellPriceFactor, true); - this.pricePlayerSell = this.BaseMarketValue * 0.5f * this.priceFactorSell_TraderPriceType * this.priceFactorSell_ItemSellPriceFactor * (1f - Find.Storyteller.difficulty.tradePriceFactorLoss); - this.pricePlayerSell *= 1f + this.priceGain_PlayerNegotiator + this.priceGain_FactionBase; - this.pricePlayerSell = Mathf.Max(this.pricePlayerSell, 0.01f); - if (this.pricePlayerSell > 99.5f) - { - this.pricePlayerSell = Mathf.Round(this.pricePlayerSell); - } - if (this.pricePlayerSell >= this.pricePlayerBuy) + if (!(this.pricePlayerBuy > 0.0)) { - Log.ErrorOnce("Trying to put player-sells price above player-buys price for " + this.AnyThing, 65387); - this.pricePlayerSell = this.pricePlayerBuy; + this.priceFactorBuy_TraderPriceType = this.PriceTypeFor(TradeAction.PlayerBuys).PriceMultiplier(); + this.priceFactorSell_TraderPriceType = this.PriceTypeFor(TradeAction.PlayerSells).PriceMultiplier(); + this.priceGain_PlayerNegotiator = TradeSession.playerNegotiator.GetStatValue(StatDefOf.TradePriceImprovement, true); + this.priceGain_FactionBase = TradeSession.trader.TradePriceImprovementOffsetForPlayer; + this.pricePlayerBuy = (float)(this.BaseMarketValue * 1.5 * this.priceFactorBuy_TraderPriceType * (1.0 + Find.Storyteller.difficulty.tradePriceFactorLoss)); + this.pricePlayerBuy *= (float)(1.0 - this.priceGain_PlayerNegotiator - this.priceGain_FactionBase); + this.pricePlayerBuy = Mathf.Max(this.pricePlayerBuy, 0.5f); + if (this.pricePlayerBuy > 99.5) + { + this.pricePlayerBuy = Mathf.Round(this.pricePlayerBuy); + } + this.priceFactorSell_ItemSellPriceFactor = this.AnyThing.GetStatValue(StatDefOf.SellPriceFactor, true); + this.pricePlayerSell = (float)(this.BaseMarketValue * 0.5 * this.priceFactorSell_TraderPriceType * this.priceFactorSell_ItemSellPriceFactor * (1.0 - Find.Storyteller.difficulty.tradePriceFactorLoss)); + this.pricePlayerSell *= (float)(1.0 + this.priceGain_PlayerNegotiator + this.priceGain_FactionBase); + this.pricePlayerSell = Mathf.Max(this.pricePlayerSell, 0.01f); + if (this.pricePlayerSell > 99.5) + { + this.pricePlayerSell = Mathf.Round(this.pricePlayerSell); + } + if (this.pricePlayerSell >= this.pricePlayerBuy) + { + Log.ErrorOnce("Trying to put player-sells price above player-buys price for " + this.AnyThing, 65387); + this.pricePlayerSell = this.pricePlayerBuy; + } } } @@ -275,159 +278,74 @@ public string GetPriceTooltip(TradeAction action) return string.Empty; } this.InitPriceDataIfNeeded(); - string text = (action != TradeAction.PlayerBuys) ? "SellPriceDesc".Translate() : "BuyPriceDesc".Translate(); - text += "\n\n"; - string text2 = text; - text = string.Concat(new object[] - { - text2, - StatDefOf.MarketValue.LabelCap, - ": ", - this.BaseMarketValue - }); + string str = (action != TradeAction.PlayerBuys) ? "SellPriceDesc".Translate() : "BuyPriceDesc".Translate(); + string text; + str = (text = str + "\n\n"); + str = text + StatDefOf.MarketValue.LabelCap + ": " + this.BaseMarketValue; if (action == TradeAction.PlayerBuys) { - text2 = text; - text = string.Concat(new string[] - { - text2, - "\n x ", - 1.5f.ToString("F2"), - " (", - "Buying".Translate(), - ")" - }); - if (this.priceFactorBuy_TraderPriceType != 1f) + text = str; + str = text + "\n x " + 1.5f.ToString("F2") + " (" + "Buying".Translate() + ")"; + if (this.priceFactorBuy_TraderPriceType != 1.0) { - text2 = text; - text = string.Concat(new string[] - { - text2, - "\n x ", - this.priceFactorBuy_TraderPriceType.ToString("F2"), - " (", - "TraderTypePrice".Translate(), - ")" - }); + text = str; + str = text + "\n x " + this.priceFactorBuy_TraderPriceType.ToString("F2") + " (" + "TraderTypePrice".Translate() + ")"; } - if (Find.Storyteller.difficulty.tradePriceFactorLoss != 0f) + if (Find.Storyteller.difficulty.tradePriceFactorLoss != 0.0) { - text2 = text; - text = string.Concat(new string[] - { - text2, - "\n x ", - (1f + Find.Storyteller.difficulty.tradePriceFactorLoss).ToString("F2"), - " (", - "DifficultyLevel".Translate(), - ")" - }); + text = str; + str = text + "\n x " + ((float)(1.0 + Find.Storyteller.difficulty.tradePriceFactorLoss)).ToString("F2") + " (" + "DifficultyLevel".Translate() + ")"; } - text += "\n"; - text2 = text; - text = string.Concat(new string[] + str = (text = str + "\n"); + str = text + "\n" + "YourNegotiatorBonus".Translate() + ": -" + this.priceGain_PlayerNegotiator.ToStringPercent(); + if (this.priceGain_FactionBase != 0.0) { - text2, - "\n", - "YourNegotiatorBonus".Translate(), - ": -", - this.priceGain_PlayerNegotiator.ToStringPercent() - }); - if (this.priceGain_FactionBase != 0f) - { - text2 = text; - text = string.Concat(new string[] - { - text2, - "\n", - "TradeWithFactionBaseBonus".Translate(), - ": -", - this.priceGain_FactionBase.ToStringPercent() - }); + text = str; + str = text + "\n" + "TradeWithFactionBaseBonus".Translate() + ": -" + this.priceGain_FactionBase.ToStringPercent(); } } else { - text2 = text; - text = string.Concat(new string[] - { - text2, - "\n x ", - 0.5f.ToString("F2"), - " (", - "Selling".Translate(), - ")" - }); - if (this.priceFactorSell_TraderPriceType != 1f) + text = str; + str = text + "\n x " + 0.5f.ToString("F2") + " (" + "Selling".Translate() + ")"; + if (this.priceFactorSell_TraderPriceType != 1.0) { - text2 = text; - text = string.Concat(new string[] - { - text2, - "\n x ", - this.priceFactorSell_TraderPriceType.ToString("F2"), - " (", - "TraderTypePrice".Translate(), - ")" - }); + text = str; + str = text + "\n x " + this.priceFactorSell_TraderPriceType.ToString("F2") + " (" + "TraderTypePrice".Translate() + ")"; } - if (this.priceFactorSell_ItemSellPriceFactor != 1f) + if (this.priceFactorSell_ItemSellPriceFactor != 1.0) { - text2 = text; - text = string.Concat(new string[] - { - text2, - "\n x ", - this.priceFactorSell_ItemSellPriceFactor.ToString("F2"), - " (", - "ItemSellPriceFactor".Translate(), - ")" - }); + text = str; + str = text + "\n x " + this.priceFactorSell_ItemSellPriceFactor.ToString("F2") + " (" + "ItemSellPriceFactor".Translate() + ")"; } - if (Find.Storyteller.difficulty.tradePriceFactorLoss != 0f) + if (Find.Storyteller.difficulty.tradePriceFactorLoss != 0.0) { - text2 = text; - text = string.Concat(new string[] - { - text2, - "\n x ", - (1f - Find.Storyteller.difficulty.tradePriceFactorLoss).ToString("F2"), - " (", - "DifficultyLevel".Translate(), - ")" - }); + text = str; + str = text + "\n x " + ((float)(1.0 - Find.Storyteller.difficulty.tradePriceFactorLoss)).ToString("F2") + " (" + "DifficultyLevel".Translate() + ")"; } - text += "\n"; - text2 = text; - text = string.Concat(new string[] + str = (text = str + "\n"); + str = text + "\n" + "YourNegotiatorBonus".Translate() + ": " + this.priceGain_PlayerNegotiator.ToStringPercent(); + if (this.priceGain_FactionBase != 0.0) { - text2, - "\n", - "YourNegotiatorBonus".Translate(), - ": ", - this.priceGain_PlayerNegotiator.ToStringPercent() - }); - if (this.priceGain_FactionBase != 0f) - { - text2 = text; - text = string.Concat(new string[] - { - text2, - "\n", - "TradeWithFactionBaseBonus".Translate(), - ": -", - this.priceGain_FactionBase.ToStringPercent() - }); + text = str; + str = text + "\n" + "TradeWithFactionBaseBonus".Translate() + ": -" + this.priceGain_FactionBase.ToStringPercent(); } } - text += "\n\n"; + str += "\n\n"; float priceFor = this.GetPriceFor(action); - text = text + "FinalPrice".Translate() + ": $" + priceFor.ToString("F2"); - if ((action == TradeAction.PlayerBuys && priceFor <= 0.5f) || (action == TradeAction.PlayerBuys && priceFor <= 0.01f)) + str = str + "FinalPrice".Translate() + ": $" + priceFor.ToString("F2"); + if (action == TradeAction.PlayerBuys && priceFor <= 0.5) { - text = text + " (" + "minimum".Translate() + ")"; + goto IL_049e; } - return text; + if (action == TradeAction.PlayerBuys && priceFor <= 0.0099999997764825821) + goto IL_049e; + goto IL_04b9; + IL_049e: + str = str + " (" + "minimum".Translate() + ")"; + goto IL_04b9; + IL_04b9: + return str; } public float GetPriceFor(TradeAction action) @@ -493,14 +411,14 @@ public virtual void ResolveTrade() { if (this.ActionToDo == TradeAction.PlayerSells) { - TransferableUtility.TransferNoSplit(this.thingsColony, -base.CountToTransfer, delegate(Thing thing, int countToTransfer) + TransferableUtility.TransferNoSplit(this.thingsColony, -base.CountToTransfer, (Action)delegate(Thing thing, int countToTransfer) { TradeSession.trader.GiveSoldThingToTrader(thing, countToTransfer, TradeSession.playerNegotiator); }, true, true); } else if (this.ActionToDo == TradeAction.PlayerBuys) { - TransferableUtility.TransferNoSplit(this.thingsTrader, base.CountToTransfer, delegate(Thing thing, int countToTransfer) + TransferableUtility.TransferNoSplit(this.thingsTrader, base.CountToTransfer, (Action)delegate(Thing thing, int countToTransfer) { this.CheckTeachOpportunity(thing, countToTransfer); TradeSession.trader.GiveSoldThingToPlayer(thing, countToTransfer, TradeSession.playerNegotiator); @@ -527,15 +445,7 @@ private void CheckTeachOpportunity(Thing boughtThing, int boughtCount) public override string ToString() { - return string.Concat(new object[] - { - base.GetType(), - "(", - this.ThingDef, - ", countToDrop=", - base.CountToTransfer, - ")" - }); + return base.GetType() + "(" + this.ThingDef + ", countToDrop=" + base.CountToTransfer + ")"; } public override int GetHashCode() diff --git a/Assembly-CSharp/RimWorld/Tradeable_Pawn.cs b/Assembly-CSharp/RimWorld/Tradeable_Pawn.cs index c9efb1172..496055da0 100644 --- a/Assembly-CSharp/RimWorld/Tradeable_Pawn.cs +++ b/Assembly-CSharp/RimWorld/Tradeable_Pawn.cs @@ -1,4 +1,3 @@ -using System; using System.Collections.Generic; using System.Linq; using Verse; @@ -25,15 +24,7 @@ public override string Label text = text + ", " + this.AnyPawn.def.label; } string text2 = text; - return string.Concat(new string[] - { - text2, - " (", - this.AnyPawn.gender.GetLabel(), - ", ", - this.AnyPawn.ageTracker.AgeBiologicalYearsFloat.ToString("F0"), - ")" - }); + return text2 + " (" + this.AnyPawn.gender.GetLabel() + ", " + this.AnyPawn.ageTracker.AgeBiologicalYearsFloat.ToString("F0") + ")"; } } @@ -58,7 +49,7 @@ public override void ResolveTrade() { if (base.ActionToDo == TradeAction.PlayerSells) { - List list = this.thingsColony.Take(-base.CountToTransfer).Cast().ToList(); + List list = base.thingsColony.Take(-base.CountToTransfer).Cast().ToList(); for (int i = 0; i < list.Count; i++) { TradeSession.trader.GiveSoldThingToTrader(list[i], 1, TradeSession.playerNegotiator); @@ -66,7 +57,7 @@ public override void ResolveTrade() } else if (base.ActionToDo == TradeAction.PlayerBuys) { - List list2 = this.thingsTrader.Take(base.CountToTransfer).Cast().ToList(); + List list2 = base.thingsTrader.Take(base.CountToTransfer).Cast().ToList(); for (int j = 0; j < list2.Count; j++) { TradeSession.trader.GiveSoldThingToPlayer(list2[j], 1, TradeSession.playerNegotiator); diff --git a/Assembly-CSharp/RimWorld/TraderCaravanRole.cs b/Assembly-CSharp/RimWorld/TraderCaravanRole.cs index 395302cb9..85655b535 100644 --- a/Assembly-CSharp/RimWorld/TraderCaravanRole.cs +++ b/Assembly-CSharp/RimWorld/TraderCaravanRole.cs @@ -1,13 +1,11 @@ -using System; - namespace RimWorld { public enum TraderCaravanRole { - None, - Trader, - Carrier, - Guard, - Chattel + None = 0, + Trader = 1, + Carrier = 2, + Guard = 3, + Chattel = 4 } } diff --git a/Assembly-CSharp/RimWorld/TraderCaravanUtility.cs b/Assembly-CSharp/RimWorld/TraderCaravanUtility.cs index 6dff97df1..f12f09ed3 100644 --- a/Assembly-CSharp/RimWorld/TraderCaravanUtility.cs +++ b/Assembly-CSharp/RimWorld/TraderCaravanUtility.cs @@ -1,4 +1,3 @@ -using System; using Verse; using Verse.AI.Group; diff --git a/Assembly-CSharp/RimWorld/TraderKindDef.cs b/Assembly-CSharp/RimWorld/TraderKindDef.cs index c16c162e9..c74885f9f 100644 --- a/Assembly-CSharp/RimWorld/TraderKindDef.cs +++ b/Assembly-CSharp/RimWorld/TraderKindDef.cs @@ -1,6 +1,5 @@ using System; using System.Collections.Generic; -using System.Diagnostics; using Verse; namespace RimWorld @@ -16,20 +15,43 @@ public class TraderKindDef : Def public override void ResolveReferences() { base.ResolveReferences(); - foreach (StockGenerator current in this.stockGenerators) + List.Enumerator enumerator = this.stockGenerators.GetEnumerator(); + try { - current.ResolveReferences(this); + while (enumerator.MoveNext()) + { + StockGenerator current = enumerator.Current; + current.ResolveReferences(this); + } + } + finally + { + ((IDisposable)(object)enumerator).Dispose(); } } - [DebuggerHidden] public override IEnumerable ConfigErrors() { - TraderKindDef.c__Iterator9B c__Iterator9B = new TraderKindDef.c__Iterator9B(); - c__Iterator9B.<>f__this = this; - TraderKindDef.c__Iterator9B expr_0E = c__Iterator9B; - expr_0E.$PC = -2; - return expr_0E; + foreach (string item in base.ConfigErrors()) + { + yield return item; + } + List.Enumerator enumerator2 = this.stockGenerators.GetEnumerator(); + try + { + while (enumerator2.MoveNext()) + { + StockGenerator stock = enumerator2.Current; + foreach (string item2 in stock.ConfigErrors(this)) + { + yield return item2; + } + } + } + finally + { + ((IDisposable)(object)enumerator2).Dispose(); + } } public bool WillTrade(ThingDef td) @@ -54,7 +76,7 @@ public PriceType PriceTypeFor(ThingDef thingDef, TradeAction action) { for (int i = 0; i < this.stockGenerators.Count; i++) { - PriceType result; + PriceType result = default(PriceType); if (this.stockGenerators[i].TryGetPriceType(thingDef, action, out result)) { return result; diff --git a/Assembly-CSharp/RimWorld/TrainableDef.cs b/Assembly-CSharp/RimWorld/TrainableDef.cs index cc9bd4cce..5c72008db 100644 --- a/Assembly-CSharp/RimWorld/TrainableDef.cs +++ b/Assembly-CSharp/RimWorld/TrainableDef.cs @@ -1,6 +1,4 @@ -using System; using System.Collections.Generic; -using System.Diagnostics; using UnityEngine; using Verse; @@ -37,7 +35,7 @@ public Texture2D Icon { get { - if (this.iconTex == null) + if ((Object)this.iconTex == (Object)null) { this.iconTex = ContentFinder.Get(this.icon, true); } @@ -47,7 +45,7 @@ public Texture2D Icon public bool MatchesTag(string tag) { - if (tag == this.defName) + if (tag == base.defName) { return true; } @@ -61,14 +59,16 @@ public bool MatchesTag(string tag) return false; } - [DebuggerHidden] public override IEnumerable ConfigErrors() { - TrainableDef.c__Iterator9C c__Iterator9C = new TrainableDef.c__Iterator9C(); - c__Iterator9C.<>f__this = this; - TrainableDef.c__Iterator9C expr_0E = c__Iterator9C; - expr_0E.$PC = -2; - return expr_0E; + foreach (string item in base.ConfigErrors()) + { + yield return item; + } + if (this.difficulty < 0.0) + { + yield return "difficulty not set"; + } } } } diff --git a/Assembly-CSharp/RimWorld/TrainableDefOf.cs b/Assembly-CSharp/RimWorld/TrainableDefOf.cs index cb9669f74..2f449571c 100644 --- a/Assembly-CSharp/RimWorld/TrainableDefOf.cs +++ b/Assembly-CSharp/RimWorld/TrainableDefOf.cs @@ -1,5 +1,3 @@ -using System; - namespace RimWorld { [DefOf] diff --git a/Assembly-CSharp/RimWorld/TrainableIntelligenceDefOf.cs b/Assembly-CSharp/RimWorld/TrainableIntelligenceDefOf.cs index b38791a85..5bd0d3f6d 100644 --- a/Assembly-CSharp/RimWorld/TrainableIntelligenceDefOf.cs +++ b/Assembly-CSharp/RimWorld/TrainableIntelligenceDefOf.cs @@ -1,4 +1,3 @@ -using System; using Verse; namespace RimWorld diff --git a/Assembly-CSharp/RimWorld/TrainableUtility.cs b/Assembly-CSharp/RimWorld/TrainableUtility.cs index ca9d5a9ec..6fa9ab5f3 100644 --- a/Assembly-CSharp/RimWorld/TrainableUtility.cs +++ b/Assembly-CSharp/RimWorld/TrainableUtility.cs @@ -24,32 +24,38 @@ public static void Reset() TrainableUtility.defsInListOrder.AddRange(from td in DefDatabase.AllDefsListForReading orderby td.listPriority descending select td); - bool flag; - do + while (true) { - flag = false; - for (int i = 0; i < TrainableUtility.defsInListOrder.Count; i++) + bool flag = false; + int num = 0; + while (num < TrainableUtility.defsInListOrder.Count) { - TrainableDef trainableDef = TrainableUtility.defsInListOrder[i]; + TrainableDef trainableDef = TrainableUtility.defsInListOrder[num]; if (trainableDef.prerequisites != null) { - for (int j = 0; j < trainableDef.prerequisites.Count; j++) + int num2 = 0; + while (num2 < trainableDef.prerequisites.Count) { - if (trainableDef.indent <= trainableDef.prerequisites[j].indent) + if (trainableDef.indent > trainableDef.prerequisites[num2].indent) { - trainableDef.indent = trainableDef.prerequisites[j].indent + 1; - flag = true; - break; + num2++; + continue; } + trainableDef.indent = trainableDef.prerequisites[num2].indent + 1; + flag = true; + break; } } - if (flag) + if (!flag) { - break; + num++; + continue; } + break; } + if (!flag) + break; } - while (flag); } public static string MasterString(Pawn pawn) @@ -60,20 +66,20 @@ public static string MasterString(Pawn pawn) public static void OpenMasterSelectMenu(Pawn p) { List list = new List(); - list.Add(new FloatMenuOption("(" + "NoneLower".Translate() + ")", delegate + list.Add(new FloatMenuOption("(" + "NoneLower".Translate() + ")", (Action)delegate() { p.playerSettings.master = null; }, MenuOptionPriority.Default, null, null, 0f, null, null)); - foreach (Pawn current in PawnsFinder.AllMaps_FreeColonistsSpawned) + foreach (Pawn item in PawnsFinder.AllMaps_FreeColonistsSpawned) { - string text = RelationsUtility.LabelWithBondInfo(current, p); - int level = current.skills.GetSkill(SkillDefOf.Animals).Level; + string text = RelationsUtility.LabelWithBondInfo(item, p); + int level = item.skills.GetSkill(SkillDefOf.Animals).Level; int num = TrainableUtility.MinimumHandlingSkill(p); Action action; if (level >= num) { - Pawn localCol = current; - action = delegate + Pawn localCol = item; + action = (Action)delegate() { p.playerSettings.master = localCol; }; @@ -81,12 +87,7 @@ public static void OpenMasterSelectMenu(Pawn p) else { action = null; - text = text + " (" + "SkillTooLow".Translate(new object[] - { - SkillDefOf.Animals.LabelCap, - level, - num - }) + ")"; + text = text + " (" + "SkillTooLow".Translate(SkillDefOf.Animals.LabelCap, level, num) + ")"; } list.Add(new FloatMenuOption(text, action, MenuOptionPriority.Default, null, null, 0f, null, null)); } diff --git a/Assembly-CSharp/RimWorld/TrainingCardUtility.cs b/Assembly-CSharp/RimWorld/TrainingCardUtility.cs index 994833b03..956973c04 100644 --- a/Assembly-CSharp/RimWorld/TrainingCardUtility.cs +++ b/Assembly-CSharp/RimWorld/TrainingCardUtility.cs @@ -23,7 +23,8 @@ public static void DrawTrainingCard(Rect rect, Pawn pawn) { Rect rect2 = new Rect(0f, 20f, rect.width, 25f); Widgets.Label(rect2, "Master".Translate() + ": "); - rect2.xMin = rect2.center.x; + Vector2 center = rect2.center; + rect2.xMin = center.x; string label2 = TrainableUtility.MasterString(pawn); if (Widgets.ButtonText(rect2, label2, true, false, true)) { @@ -36,7 +37,7 @@ public static void DrawTrainingCard(Rect rect, Pawn pawn) { if (TrainingCardUtility.TryDrawTrainableRow(new Rect(0f, num, rect.width, 28f), pawn, trainableDefsInListOrder[i])) { - num += 28f; + num = (float)(num + 28.0); } } GUI.EndGroup(); @@ -45,7 +46,7 @@ public static void DrawTrainingCard(Rect rect, Pawn pawn) private static bool TryDrawTrainableRow(Rect rect, Pawn pawn, TrainableDef td) { bool flag = pawn.training.IsCompleted(td); - bool flag2; + bool flag2 = default(bool); AcceptanceReport canTrain = pawn.training.CanAssignToTrain(td, out flag2); if (!flag2) { @@ -54,9 +55,9 @@ private static bool TryDrawTrainableRow(Rect rect, Pawn pawn, TrainableDef td) Widgets.DrawHighlightIfMouseover(rect); Rect rect2 = rect; rect2.width -= 50f; - rect2.xMin += (float)td.indent * 10f; + rect2.xMin += (float)((float)td.indent * 10.0); Rect rect3 = rect; - rect3.xMin = rect3.xMax - 50f + 17f; + rect3.xMin = (float)(rect3.xMax - 50.0 + 17.0); if (!flag) { TrainingCardUtility.DoTrainableCheckbox(rect2, pawn, td, canTrain, true, false); @@ -77,11 +78,11 @@ private static bool TryDrawTrainableRow(Rect rect, Pawn pawn, TrainableDef td) if (DebugSettings.godMode && !pawn.training.IsCompleted(td)) { Rect rect4 = rect3; - rect4.yMin = rect4.yMax - 10f; - rect4.xMin = rect4.xMax - 10f; + rect4.yMin = (float)(rect4.yMax - 10.0); + rect4.xMin = (float)(rect4.xMax - 10.0); if (Widgets.ButtonText(rect4, "+", true, false, true)) { - pawn.training.Train(td, pawn.Map.mapPawns.FreeColonistsSpawned.RandomElement()); + pawn.training.Train(td, pawn.Map.mapPawns.FreeColonistsSpawned.RandomElement()); } } TrainingCardUtility.DoTrainableTooltip(rect, pawn, td, canTrain); @@ -91,8 +92,7 @@ private static bool TryDrawTrainableRow(Rect rect, Pawn pawn, TrainableDef td) public static void DoTrainableCheckbox(Rect rect, Pawn pawn, TrainableDef td, AcceptanceReport canTrain, bool drawLabel, bool doTooltip) { - bool flag = pawn.training.IsCompleted(td); - if (flag) + if (pawn.training.IsCompleted(td)) { if (!drawLabel) { @@ -101,20 +101,20 @@ public static void DoTrainableCheckbox(Rect rect, Pawn pawn, TrainableDef td, Ac } else { - bool wanted = pawn.training.GetWanted(td); - bool flag2 = wanted; + bool wanted; + bool flag = wanted = pawn.training.GetWanted(td); if (drawLabel) { - Widgets.CheckboxLabeled(rect, td.LabelCap, ref wanted, !canTrain.Accepted); + Widgets.CheckboxLabeled(rect, td.LabelCap, ref flag, !canTrain.Accepted); } else { - Widgets.Checkbox(rect.position, ref wanted, rect.width, !canTrain.Accepted); + Widgets.Checkbox(rect.position, ref flag, rect.width, !canTrain.Accepted); } - if (wanted != flag2) + if (flag != wanted) { PlayerKnowledgeDatabase.KnowledgeDemonstrated(ConceptDefOf.AnimalTraining, KnowledgeAmount.Total); - pawn.training.SetWantedRecursive(td, wanted); + pawn.training.SetWantedRecursive(td, flag); } } if (doTooltip) @@ -125,29 +125,26 @@ public static void DoTrainableCheckbox(Rect rect, Pawn pawn, TrainableDef td, Ac private static void DoTrainableTooltip(Rect rect, Pawn pawn, TrainableDef td, AcceptanceReport canTrain) { - TooltipHandler.TipRegion(rect, delegate + TooltipHandler.TipRegion(rect, (Func)delegate() { string text = td.LabelCap + "\n\n" + td.description; if (!canTrain.Accepted) { text = text + "\n\n" + canTrain.Reason; } - else if (!td.prerequisites.NullOrEmpty()) + else if (!td.prerequisites.NullOrEmpty()) { text += "\n"; for (int i = 0; i < td.prerequisites.Count; i++) { if (!pawn.training.IsCompleted(td.prerequisites[i])) { - text = text + "\n" + "TrainingNeedsPrerequisite".Translate(new object[] - { - td.prerequisites[i].LabelCap - }); + text = text + "\n" + "TrainingNeedsPrerequisite".Translate(td.prerequisites[i].LabelCap); } } } return text; - }, (int)(rect.y * 612f + rect.x)); + }, (int)(rect.y * 612.0 + rect.x)); } } } diff --git a/Assembly-CSharp/RimWorld/Trait.cs b/Assembly-CSharp/RimWorld/Trait.cs index 5601cab20..e43277dcd 100644 --- a/Assembly-CSharp/RimWorld/Trait.cs +++ b/Assembly-CSharp/RimWorld/Trait.cs @@ -1,6 +1,5 @@ using System; using System.Collections.Generic; -using System.Diagnostics; using System.Linq; using System.Text; using Verse; @@ -124,29 +123,38 @@ public string TipString(Pawn pawn) stringBuilder.AppendLine(); } int num = 0; - foreach (KeyValuePair current in this.CurrentData.skillGains) + Dictionary.Enumerator enumerator = this.CurrentData.skillGains.GetEnumerator(); + try { - if (current.Value != 0) + while (enumerator.MoveNext()) { - string value = " " + current.Key.skillLabel + ": " + current.Value.ToString("+##;-##"); - if (num < count - 1) + KeyValuePair current = enumerator.Current; + if (current.Value != 0) { - stringBuilder.AppendLine(value); + string value = " " + current.Key.skillLabel + ": " + current.Value.ToString("+##;-##"); + if (num < count - 1) + { + stringBuilder.AppendLine(value); + } + else + { + stringBuilder.Append(value); + } + num++; } - else - { - stringBuilder.Append(value); - } - num++; } } - if (this.GetPermaThoughts().Any()) + finally + { + ((IDisposable)(object)enumerator).Dispose(); + } + if (this.GetPermaThoughts().Any()) { stringBuilder.AppendLine(); - foreach (ThoughtDef current2 in this.GetPermaThoughts()) + foreach (ThoughtDef permaThought in this.GetPermaThoughts()) { stringBuilder.AppendLine(); - stringBuilder.Append(" " + "PermanentMoodEffect".Translate() + " " + current2.stages[0].baseMoodEffect.ToStringByStyle(ToStringStyle.Integer, ToStringNumberSense.Offset)); + stringBuilder.Append(" " + "PermanentMoodEffect".Translate() + " " + permaThought.stages[0].baseMoodEffect.ToStringByStyle(ToStringStyle.Integer, ToStringNumberSense.Offset)); } } if (currentData.statOffsets != null) @@ -192,24 +200,20 @@ public string TipString(Pawn pawn) public override string ToString() { - return string.Concat(new object[] - { - "Trait(", - this.def.ToString(), - "-", - this.degree, - ")" - }); + return "Trait(" + this.def.ToString() + "-" + this.degree + ")"; } - [DebuggerHidden] private IEnumerable GetPermaThoughts() { - Trait.c__IteratorEA c__IteratorEA = new Trait.c__IteratorEA(); - c__IteratorEA.<>f__this = this; - Trait.c__IteratorEA expr_0E = c__IteratorEA; - expr_0E.$PC = -2; - return expr_0E; + TraitDegreeData degree = this.CurrentData; + List allThoughts = DefDatabase.AllDefsListForReading; + for (int i = 0; i < allThoughts.Count; i++) + { + if (allThoughts[i].IsSituational && allThoughts[i].Worker is ThoughtWorker_AlwaysActive && allThoughts[i].requiredTraits != null && allThoughts[i].requiredTraits.Contains(this.def) && (!allThoughts[i].RequiresSpecificTraitsDegree || allThoughts[i].requiredTraitsDegree == degree.degree)) + { + yield return allThoughts[i]; + } + } } private bool AllowsWorkType(WorkTypeDef workDef) @@ -217,14 +221,21 @@ private bool AllowsWorkType(WorkTypeDef workDef) return (this.def.disabledWorkTags & workDef.workTags) == WorkTags.None; } - [DebuggerHidden] public IEnumerable GetDisabledWorkTypes() { - Trait.c__IteratorEB c__IteratorEB = new Trait.c__IteratorEB(); - c__IteratorEB.<>f__this = this; - Trait.c__IteratorEB expr_0E = c__IteratorEB; - expr_0E.$PC = -2; - return expr_0E; + for (int j = 0; j < this.def.disabledWorkTypes.Count; j++) + { + yield return this.def.disabledWorkTypes[j]; + } + List workTypeDefList = DefDatabase.AllDefsListForReading; + for (int i = 0; i < workTypeDefList.Count; i++) + { + WorkTypeDef w = workTypeDefList[i]; + if (!this.AllowsWorkType(w)) + { + yield return w; + } + } } } } diff --git a/Assembly-CSharp/RimWorld/TraitDef.cs b/Assembly-CSharp/RimWorld/TraitDef.cs index 8ff22b97b..7655670a5 100644 --- a/Assembly-CSharp/RimWorld/TraitDef.cs +++ b/Assembly-CSharp/RimWorld/TraitDef.cs @@ -1,6 +1,6 @@ using System; using System.Collections.Generic; -using System.Diagnostics; +using System.Linq; using Verse; namespace RimWorld @@ -39,24 +39,34 @@ public TraitDegreeData DataAtDegree(int degree) return this.degreeDatas[i]; } } - Log.Error(string.Concat(new object[] - { - this.defName, - " found no data at degree ", - degree, - ", returning first defined." - })); + Log.Error(base.defName + " found no data at degree " + degree + ", returning first defined."); return this.degreeDatas[0]; } - [DebuggerHidden] public override IEnumerable ConfigErrors() { - TraitDef.c__Iterator9D c__Iterator9D = new TraitDef.c__Iterator9D(); - c__Iterator9D.<>f__this = this; - TraitDef.c__Iterator9D expr_0E = c__Iterator9D; - expr_0E.$PC = -2; - return expr_0E; + foreach (string item in base.ConfigErrors()) + { + yield return item; + } + if (this.commonality < 0.0010000000474974513 && this.commonalityFemale < 0.0010000000474974513) + { + yield return "TraitDef " + base.defName + " has 0 commonality."; + } + if (!this.degreeDatas.Any()) + { + yield return base.defName + " has no degree datas."; + } + for (int i = 0; i < this.degreeDatas.Count; i++) + { + TraitDegreeData dd3 = this.degreeDatas[i]; + if ((from dd2 in this.degreeDatas + where dd2.degree == ((_003CConfigErrors_003Ec__Iterator9D)/*Error near IL_0177: stateMachine*/)._003Cdd_003E__3.degree + select dd2).Count() > 1) + { + yield return ">1 datas for degree " + dd3.degree; + } + } } public bool ConflictsWith(Trait other) @@ -76,7 +86,7 @@ public bool ConflictsWith(Trait other) public float GetGenderSpecificCommonality(Pawn pawn) { - if (pawn.gender == Gender.Female && this.commonalityFemale >= 0f) + if (pawn.gender == Gender.Female && this.commonalityFemale >= 0.0) { return this.commonalityFemale; } diff --git a/Assembly-CSharp/RimWorld/TraitDefOf.cs b/Assembly-CSharp/RimWorld/TraitDefOf.cs index a45cf1a46..0959084dd 100644 --- a/Assembly-CSharp/RimWorld/TraitDefOf.cs +++ b/Assembly-CSharp/RimWorld/TraitDefOf.cs @@ -1,5 +1,3 @@ -using System; - namespace RimWorld { [DefOf] diff --git a/Assembly-CSharp/RimWorld/TraitDegreeData.cs b/Assembly-CSharp/RimWorld/TraitDegreeData.cs index 6da9dd14d..c08b81f60 100644 --- a/Assembly-CSharp/RimWorld/TraitDegreeData.cs +++ b/Assembly-CSharp/RimWorld/TraitDegreeData.cs @@ -1,4 +1,3 @@ -using System; using System.Collections.Generic; using UnityEngine; using Verse; @@ -41,25 +40,37 @@ public float Commonality { get { - if (this.commonality >= 0f) + if (this.commonality >= 0.0) { return this.commonality; } switch (Mathf.Abs(this.degree)) { case 0: + { return 1f; + } case 1: + { return 1f; + } case 2: + { return 0.4f; + } case 3: + { return 0.2f; + } case 4: + { return 0.1f; + } default: + { return 0.05f; } + } } } } diff --git a/Assembly-CSharp/RimWorld/TraitEntry.cs b/Assembly-CSharp/RimWorld/TraitEntry.cs index 2f3d9b692..1a07894ed 100644 --- a/Assembly-CSharp/RimWorld/TraitEntry.cs +++ b/Assembly-CSharp/RimWorld/TraitEntry.cs @@ -1,4 +1,3 @@ -using System; using System.Xml; using Verse; diff --git a/Assembly-CSharp/RimWorld/TraitSet.cs b/Assembly-CSharp/RimWorld/TraitSet.cs index f8abe46bf..509ea562f 100644 --- a/Assembly-CSharp/RimWorld/TraitSet.cs +++ b/Assembly-CSharp/RimWorld/TraitSet.cs @@ -1,4 +1,3 @@ -using System; using System.Collections.Generic; using Verse; @@ -14,11 +13,17 @@ public IEnumerable AllowedMentalBreaks { get { - TraitSet.<>c__IteratorEC <>c__IteratorEC = new TraitSet.<>c__IteratorEC(); - <>c__IteratorEC.<>f__this = this; - TraitSet.<>c__IteratorEC expr_0E = <>c__IteratorEC; - expr_0E.$PC = -2; - return expr_0E; + for (int j = 0; j < this.allTraits.Count; j++) + { + Trait trait = this.allTraits[j]; + if (trait.CurrentData.allowedMentalBreaks != null) + { + for (int i = 0; i < trait.CurrentData.allowedMentalBreaks.Count; i++) + { + yield return trait.CurrentData.allowedMentalBreaks[i]; + } + } + } } } @@ -37,21 +42,23 @@ public void GainTrait(Trait trait) if (this.HasTrait(trait.def)) { Log.Warning(this.pawn + " already has trait " + trait.def); - return; - } - this.allTraits.Add(trait); - if (this.pawn.workSettings != null) - { - this.pawn.workSettings.Notify_GainedTrait(); - } - this.pawn.story.Notify_TraitChanged(); - if (this.pawn.skills != null) - { - this.pawn.skills.Notify_SkillDisablesChanged(); } - if (!this.pawn.Dead && this.pawn.RaceProps.Humanlike) + else { - this.pawn.needs.mood.thoughts.situational.Notify_SituationalThoughtsDirty(); + this.allTraits.Add(trait); + if (this.pawn.workSettings != null) + { + this.pawn.workSettings.Notify_GainedTrait(); + } + this.pawn.story.Notify_TraitChanged(); + if (this.pawn.skills != null) + { + this.pawn.skills.Notify_SkillDisablesChanged(); + } + if (!this.pawn.Dead && this.pawn.RaceProps.Humanlike) + { + this.pawn.needs.mood.thoughts.situational.Notify_SituationalThoughtsDirty(); + } } } diff --git a/Assembly-CSharp/RimWorld/Transactor.cs b/Assembly-CSharp/RimWorld/Transactor.cs index 048cb5617..ec25fdf7b 100644 --- a/Assembly-CSharp/RimWorld/Transactor.cs +++ b/Assembly-CSharp/RimWorld/Transactor.cs @@ -1,10 +1,8 @@ -using System; - namespace RimWorld { public enum Transactor : byte { - Colony, - Trader + Colony = 0, + Trader = 1 } } diff --git a/Assembly-CSharp/RimWorld/Transferable.cs b/Assembly-CSharp/RimWorld/Transferable.cs index f4528fd1d..e56ac9f97 100644 --- a/Assembly-CSharp/RimWorld/Transferable.cs +++ b/Assembly-CSharp/RimWorld/Transferable.cs @@ -1,4 +1,3 @@ -using System; using UnityEngine; using Verse; @@ -117,9 +116,11 @@ public void AdjustTo(int destination) if (!this.CanAdjustTo(destination).Accepted) { Log.Error("Failed to adjust transferable counts"); - return; } - this.CountToTransfer = this.ClampAmount(destination); + else + { + this.CountToTransfer = this.ClampAmount(destination); + } } public void ForceTo(int destination) diff --git a/Assembly-CSharp/RimWorld/TransferableComparer.cs b/Assembly-CSharp/RimWorld/TransferableComparer.cs index eaddb626f..d496de4de 100644 --- a/Assembly-CSharp/RimWorld/TransferableComparer.cs +++ b/Assembly-CSharp/RimWorld/TransferableComparer.cs @@ -1,4 +1,3 @@ -using System; using System.Collections.Generic; namespace RimWorld diff --git a/Assembly-CSharp/RimWorld/TransferableComparer_Category.cs b/Assembly-CSharp/RimWorld/TransferableComparer_Category.cs index 2a33d737f..9f15fe4d3 100644 --- a/Assembly-CSharp/RimWorld/TransferableComparer_Category.cs +++ b/Assembly-CSharp/RimWorld/TransferableComparer_Category.cs @@ -14,7 +14,7 @@ public static int Compare(ThingDef lhsTh, ThingDef rhsTh) { if (lhsTh.category != rhsTh.category) { - return lhsTh.category.CompareTo(rhsTh.category); + return ((Enum)(object)lhsTh.category).CompareTo((object)rhsTh.category); } float num = TransferableUIUtility.DefaultListOrderPriority(lhsTh); float num2 = TransferableUIUtility.DefaultListOrderPriority(rhsTh); @@ -23,14 +23,14 @@ public static int Compare(ThingDef lhsTh, ThingDef rhsTh) return num.CompareTo(num2); } int num3 = 0; - if (!lhsTh.thingCategories.NullOrEmpty()) + if (!lhsTh.thingCategories.NullOrEmpty()) { - num3 = (int)lhsTh.thingCategories[0].index; + num3 = lhsTh.thingCategories[0].index; } int value = 0; - if (!rhsTh.thingCategories.NullOrEmpty()) + if (!rhsTh.thingCategories.NullOrEmpty()) { - value = (int)rhsTh.thingCategories[0].index; + value = rhsTh.thingCategories[0].index; } return num3.CompareTo(value); } diff --git a/Assembly-CSharp/RimWorld/TransferableComparer_HitPointsPercentage.cs b/Assembly-CSharp/RimWorld/TransferableComparer_HitPointsPercentage.cs index 522ab1ffb..395b93141 100644 --- a/Assembly-CSharp/RimWorld/TransferableComparer_HitPointsPercentage.cs +++ b/Assembly-CSharp/RimWorld/TransferableComparer_HitPointsPercentage.cs @@ -1,4 +1,3 @@ -using System; using Verse; namespace RimWorld diff --git a/Assembly-CSharp/RimWorld/TransferableComparer_MarketValue.cs b/Assembly-CSharp/RimWorld/TransferableComparer_MarketValue.cs index 99582e89c..93e38aec7 100644 --- a/Assembly-CSharp/RimWorld/TransferableComparer_MarketValue.cs +++ b/Assembly-CSharp/RimWorld/TransferableComparer_MarketValue.cs @@ -1,5 +1,3 @@ -using System; - namespace RimWorld { public class TransferableComparer_MarketValue : TransferableComparer diff --git a/Assembly-CSharp/RimWorld/TransferableComparer_Name.cs b/Assembly-CSharp/RimWorld/TransferableComparer_Name.cs index f3b9951ad..3e5778b43 100644 --- a/Assembly-CSharp/RimWorld/TransferableComparer_Name.cs +++ b/Assembly-CSharp/RimWorld/TransferableComparer_Name.cs @@ -1,5 +1,3 @@ -using System; - namespace RimWorld { public class TransferableComparer_Name : TransferableComparer diff --git a/Assembly-CSharp/RimWorld/TransferableComparer_None.cs b/Assembly-CSharp/RimWorld/TransferableComparer_None.cs index 73d5ddc57..9982cf701 100644 --- a/Assembly-CSharp/RimWorld/TransferableComparer_None.cs +++ b/Assembly-CSharp/RimWorld/TransferableComparer_None.cs @@ -1,5 +1,3 @@ -using System; - namespace RimWorld { public class TransferableComparer_None : TransferableComparer diff --git a/Assembly-CSharp/RimWorld/TransferableComparer_Quality.cs b/Assembly-CSharp/RimWorld/TransferableComparer_Quality.cs index ccedfb900..ed7f5576c 100644 --- a/Assembly-CSharp/RimWorld/TransferableComparer_Quality.cs +++ b/Assembly-CSharp/RimWorld/TransferableComparer_Quality.cs @@ -1,5 +1,3 @@ -using System; - namespace RimWorld { public class TransferableComparer_Quality : TransferableComparer @@ -11,7 +9,7 @@ public override int Compare(Transferable lhs, Transferable rhs) private int GetValueFor(Transferable t) { - QualityCategory result; + QualityCategory result = default(QualityCategory); if (!t.AnyThing.TryGetQuality(out result)) { return -1; diff --git a/Assembly-CSharp/RimWorld/TransferableCountToTransferStoppingPoint.cs b/Assembly-CSharp/RimWorld/TransferableCountToTransferStoppingPoint.cs index 7e654deb6..03f287b43 100644 --- a/Assembly-CSharp/RimWorld/TransferableCountToTransferStoppingPoint.cs +++ b/Assembly-CSharp/RimWorld/TransferableCountToTransferStoppingPoint.cs @@ -1,5 +1,3 @@ -using System; - namespace RimWorld { public struct TransferableCountToTransferStoppingPoint diff --git a/Assembly-CSharp/RimWorld/TransferableOneWay.cs b/Assembly-CSharp/RimWorld/TransferableOneWay.cs index 30a70c055..2dc54104e 100644 --- a/Assembly-CSharp/RimWorld/TransferableOneWay.cs +++ b/Assembly-CSharp/RimWorld/TransferableOneWay.cs @@ -96,18 +96,15 @@ public void ExposeData() { if (Scribe.mode == LoadSaveMode.Saving) { - this.things.RemoveAll((Thing x) => x.Destroyed); + this.things.RemoveAll((Predicate)((Thing x) => x.Destroyed)); } Scribe_Collections.Look(ref this.things, "things", LookMode.Reference, new object[0]); int countToTransfer = base.CountToTransfer; - Scribe_Values.Look(ref countToTransfer, "countToTransfer", 0, false); + Scribe_Values.Look(ref countToTransfer, "countToTransfer", 0, false); base.CountToTransfer = countToTransfer; - if (Scribe.mode == LoadSaveMode.PostLoadInit) + if (((Scribe.mode == LoadSaveMode.PostLoadInit) ? this.things.RemoveAll((Predicate)((Thing x) => x == null)) : 0) != 0) { - if (this.things.RemoveAll((Thing x) => x == null) != 0) - { - Log.Warning("Some of the things were null after loading."); - } + Log.Warning("Some of the things were null after loading."); } } } diff --git a/Assembly-CSharp/RimWorld/TransferableOneWayWidget.cs b/Assembly-CSharp/RimWorld/TransferableOneWayWidget.cs index 6a4c1512a..1cb45abf8 100644 --- a/Assembly-CSharp/RimWorld/TransferableOneWayWidget.cs +++ b/Assembly-CSharp/RimWorld/TransferableOneWayWidget.cs @@ -40,7 +40,7 @@ private struct Section public const float TopAreaWidth = 515f; - private List sections = new List(); + private List
sections = new List
(); private string sourceLabel; @@ -87,15 +87,15 @@ public float TotalNumbersColumnsWidths float num = 315f; if (this.drawMass) { - num += 100f; + num = (float)(num + 100.0); } if (this.drawMarketValue) { - num += 100f; + num = (float)(num + 100.0); } if (this.drawDaysUntilRotForTile >= 0) { - num += 75f; + num = (float)(num + 75.0); } return num; } @@ -111,7 +111,8 @@ private bool AnyTransferable } for (int i = 0; i < this.sections.Count; i++) { - if (this.sections[i].cachedTransferables.Any()) + Section section = this.sections[i]; + if (section.cachedTransferables.Any()) { return true; } @@ -124,7 +125,7 @@ public TransferableOneWayWidget(IEnumerable transferables, s { if (transferables != null) { - this.AddSection(null, transferables); + this.AddSection((string)null, transferables); } this.sourceLabel = sourceLabel; this.destinationLabel = destinationLabel; @@ -143,10 +144,12 @@ public TransferableOneWayWidget(IEnumerable transferables, s public void AddSection(string title, IEnumerable transferables) { - TransferableOneWayWidget.Section item = default(TransferableOneWayWidget.Section); - item.title = title; - item.transferables = transferables; - item.cachedTransferables = new List(); + Section item = new Section + { + title = title, + transferables = transferables, + cachedTransferables = new List() + }; this.sections.Add(item); this.transferablesCached = false; } @@ -156,15 +159,18 @@ private void CacheTransferables() this.transferablesCached = true; for (int i = 0; i < this.sections.Count; i++) { - List cachedTransferables = this.sections[i].cachedTransferables; + Section section = this.sections[i]; + List cachedTransferables = section.cachedTransferables; cachedTransferables.Clear(); - cachedTransferables.AddRange(this.sections[i].transferables.OrderBy((TransferableOneWay tr) => tr, this.sorter1.Comparer).ThenBy((TransferableOneWay tr) => tr, this.sorter2.Comparer).ThenBy((TransferableOneWay tr) => TransferableUIUtility.DefaultListOrderPriority(tr)).ToList()); + List obj = cachedTransferables; + Section section2 = this.sections[i]; + obj.AddRange(section2.transferables.OrderBy((Func)((TransferableOneWay tr) => tr), this.sorter1.Comparer).ThenBy((Func)((TransferableOneWay tr) => tr), this.sorter2.Comparer).ThenBy((Func)((TransferableOneWay tr) => TransferableUIUtility.DefaultListOrderPriority(tr))).ToList()); } } public void OnGUI(Rect inRect) { - bool flag; + bool flag = default(bool); this.OnGUI(inRect, out flag); } @@ -174,29 +180,29 @@ public void OnGUI(Rect inRect, out bool anythingChanged) { this.CacheTransferables(); } - TransferableUIUtility.DoTransferableSorters(this.sorter1, this.sorter2, delegate(TransferableSorterDef x) + TransferableUIUtility.DoTransferableSorters(this.sorter1, this.sorter2, (Action)delegate(TransferableSorterDef x) { this.sorter1 = x; this.CacheTransferables(); - }, delegate(TransferableSorterDef x) + }, (Action)delegate(TransferableSorterDef x) { this.sorter2 = x; this.CacheTransferables(); }); - float num = inRect.width - 515f; + float num = (float)(inRect.width - 515.0); Rect position = new Rect(inRect.x + num, inRect.y, inRect.width - num, 55f); GUI.BeginGroup(position); Text.Font = GameFont.Medium; - Rect rect = new Rect(0f, 0f, position.width / 2f, position.height); + Rect rect = new Rect(0f, 0f, (float)(position.width / 2.0), position.height); Text.Anchor = TextAnchor.UpperLeft; Widgets.Label(rect, this.sourceLabel); - Rect rect2 = new Rect(position.width / 2f, 0f, position.width / 2f, position.height); + Rect rect2 = new Rect((float)(position.width / 2.0), 0f, (float)(position.width / 2.0), position.height); Text.Anchor = TextAnchor.UpperRight; Widgets.Label(rect2, this.destinationLabel); Text.Font = GameFont.Small; Text.Anchor = TextAnchor.UpperLeft; GUI.EndGroup(); - Rect mainRect = new Rect(inRect.x, inRect.y + 55f + this.extraHeaderSpace, inRect.width, inRect.height - 55f - this.extraHeaderSpace); + Rect mainRect = new Rect(inRect.x, (float)(inRect.y + 55.0 + this.extraHeaderSpace), inRect.width, (float)(inRect.height - 55.0 - this.extraHeaderSpace)); this.FillMainRect(mainRect, out anythingChanged); } @@ -209,33 +215,40 @@ private void FillMainRect(Rect mainRect, out bool anythingChanged) float num = 6f; for (int i = 0; i < this.sections.Count; i++) { - num += (float)this.sections[i].cachedTransferables.Count * 30f; - if (this.sections[i].title != null) + float num2 = num; + Section section = this.sections[i]; + num = (float)(num2 + (float)section.cachedTransferables.Count * 30.0); + Section section2 = this.sections[i]; + if (section2.title != null) { - num += 30f; + num = (float)(num + 30.0); } } - float num2 = 6f; - float availableMass = (this.availableMassGetter == null) ? 3.40282347E+38f : this.availableMassGetter(); - Rect viewRect = new Rect(0f, 0f, mainRect.width - 16f, num); + float num3 = 6f; + float availableMass = (float)(((object)this.availableMassGetter == null) ? 3.4028234663852886E+38 : this.availableMassGetter()); + Rect viewRect = new Rect(0f, 0f, (float)(mainRect.width - 16.0), num); Widgets.BeginScrollView(mainRect, ref this.scrollPosition, viewRect, true); - float num3 = this.scrollPosition.y - 30f; - float num4 = this.scrollPosition.y + mainRect.height; + float num4 = (float)(this.scrollPosition.y - 30.0); + float num5 = this.scrollPosition.y + mainRect.height; for (int j = 0; j < this.sections.Count; j++) { - List cachedTransferables = this.sections[j].cachedTransferables; - if (cachedTransferables.Any()) + Section section3 = this.sections[j]; + List cachedTransferables = section3.cachedTransferables; + if (cachedTransferables.Any()) { - if (this.sections[j].title != null) + Section section4 = this.sections[j]; + if (section4.title != null) { - Widgets.ListSeparator(ref num2, viewRect.width, this.sections[j].title); - num2 += 5f; + float width = viewRect.width; + Section section5 = this.sections[j]; + Widgets.ListSeparator(ref num3, width, section5.title); + num3 = (float)(num3 + 5.0); } for (int k = 0; k < cachedTransferables.Count; k++) { - if (num2 > num3 && num2 < num4) + if (num3 > num4 && num3 < num5) { - Rect rect = new Rect(0f, num2, viewRect.width, 30f); + Rect rect = new Rect(0f, num3, viewRect.width, 30f); int countToTransfer = cachedTransferables[k].CountToTransfer; this.DoRow(rect, cachedTransferables[k], k, availableMass); if (countToTransfer != cachedTransferables[k].CountToTransfer) @@ -243,7 +256,7 @@ private void FillMainRect(Rect mainRect, out bool anythingChanged) anythingChanged = true; } } - num2 += 30f; + num3 = (float)(num3 + 30.0); } } } @@ -267,41 +280,41 @@ private void DoRow(Rect rect, TransferableOneWay trad, int index, float availabl } Text.Font = GameFont.Small; GUI.BeginGroup(rect); - float num = rect.width; + float width = rect.width; int maxCount = trad.MaxCount; - Rect rect2 = new Rect(num - 240f, 0f, 240f, rect.height); + Rect rect2 = new Rect((float)(width - 240.0), 0f, 240f, rect.height); TransferableOneWayWidget.stoppingPoints.Clear(); - if (this.availableMassGetter != null && (!(trad.AnyThing is Pawn) || this.includePawnsMassInMassUsage)) + if ((object)this.availableMassGetter != null && (!(trad.AnyThing is Pawn) || this.includePawnsMassInMassUsage)) { - float num2 = availableMass + this.GetMass(trad.AnyThing) * (float)trad.CountToTransfer; - int threshold = (num2 > 0f) ? Mathf.FloorToInt(num2 / this.GetMass(trad.AnyThing)) : 0; + float num = availableMass + this.GetMass(trad.AnyThing) * (float)trad.CountToTransfer; + int threshold = (!(num <= 0.0)) ? Mathf.FloorToInt(num / this.GetMass(trad.AnyThing)) : 0; TransferableOneWayWidget.stoppingPoints.Add(new TransferableCountToTransferStoppingPoint(threshold, "M<", ">M")); } List extraStoppingPoints = TransferableOneWayWidget.stoppingPoints; TransferableUIUtility.DoCountAdjustInterface(rect2, trad, index, 0, maxCount, false, extraStoppingPoints); - num -= 240f; + width = (float)(width - 240.0); if (this.drawMarketValue) { - Rect rect3 = new Rect(num - 100f, 0f, 100f, rect.height); + Rect rect3 = new Rect((float)(width - 100.0), 0f, 100f, rect.height); Text.Anchor = TextAnchor.MiddleLeft; this.DrawMarketValue(rect3, trad); - num -= 100f; + width = (float)(width - 100.0); } if (this.drawMass) { - Rect rect4 = new Rect(num - 100f, 0f, 100f, rect.height); + Rect rect4 = new Rect((float)(width - 100.0), 0f, 100f, rect.height); Text.Anchor = TextAnchor.MiddleLeft; this.DrawMass(rect4, trad, availableMass); - num -= 100f; + width = (float)(width - 100.0); } if (this.drawDaysUntilRotForTile >= 0) { - Rect rect5 = new Rect(num - 75f, 0f, 75f, rect.height); + Rect rect5 = new Rect((float)(width - 75.0), 0f, 75f, rect.height); Text.Anchor = TextAnchor.MiddleLeft; this.DrawDaysUntilRot(rect5, trad); - num -= 75f; + width = (float)(width - 75.0); } - Rect rect6 = new Rect(num - 75f, 0f, 75f, rect.height); + Rect rect6 = new Rect((float)(width - 75.0), 0f, 75f, rect.height); if (Mouse.IsOver(rect6)) { Widgets.DrawHighlight(rect6); @@ -312,8 +325,8 @@ private void DoRow(Rect rect, TransferableOneWay trad, int index, float availabl rect7.xMax -= 5f; Widgets.Label(rect7, maxCount.ToStringCached()); TooltipHandler.TipRegion(rect6, this.sourceCountDesc); - num -= 75f; - Rect idRect = new Rect(0f, 0f, num, rect.height); + width = (float)(width - 75.0); + Rect idRect = new Rect(0f, 0f, width, rect.height); TransferableUIUtility.DrawTransferableInfo(trad, idRect, Color.white); GenUI.ResetLabelAlign(); GUI.EndGroup(); @@ -321,118 +334,108 @@ private void DoRow(Rect rect, TransferableOneWay trad, int index, float availabl private void DrawDaysUntilRot(Rect rect, TransferableOneWay trad) { - if (!trad.HasAnyThing) - { - return; - } - if (!trad.ThingDef.IsNutritionGivingIngestible) + if (trad.HasAnyThing && trad.ThingDef.IsNutritionGivingIngestible) { - return; - } - int num = 2147483647; - for (int i = 0; i < trad.things.Count; i++) - { - CompRottable compRottable = trad.things[i].TryGetComp(); - if (compRottable != null) + int num = 2147483647; + for (int i = 0; i < trad.things.Count; i++) { - num = Mathf.Min(num, compRottable.ApproxTicksUntilRotWhenAtTempOfTile(this.drawDaysUntilRotForTile)); + CompRottable compRottable = trad.things[i].TryGetComp(); + if (compRottable != null) + { + num = Mathf.Min(num, compRottable.ApproxTicksUntilRotWhenAtTempOfTile(this.drawDaysUntilRotForTile)); + } + } + if (num < 36000000) + { + if (Mouse.IsOver(rect)) + { + Widgets.DrawHighlight(rect); + } + float num2 = (float)((float)num / 60000.0); + GUI.color = Color.yellow; + Widgets.Label(rect, num2.ToString("0.#")); + GUI.color = Color.white; + TooltipHandler.TipRegion(rect, "DaysUntilRotTip".Translate()); } } - if (num >= 36000000) - { - return; - } - if (Mouse.IsOver(rect)) - { - Widgets.DrawHighlight(rect); - } - float num2 = (float)num / 60000f; - GUI.color = Color.yellow; - Widgets.Label(rect, num2.ToString("0.#")); - GUI.color = Color.white; - TooltipHandler.TipRegion(rect, "DaysUntilRotTip".Translate()); } private void DrawMarketValue(Rect rect, TransferableOneWay trad) { - if (!trad.HasAnyThing) - { - return; - } - if (Mouse.IsOver(rect)) + if (trad.HasAnyThing) { - Widgets.DrawHighlight(rect); + if (Mouse.IsOver(rect)) + { + Widgets.DrawHighlight(rect); + } + Widgets.Label(rect, trad.AnyThing.GetInnerIfMinified().MarketValue.ToStringMoney()); + TooltipHandler.TipRegion(rect, "MarketValueTip".Translate()); } - Widgets.Label(rect, trad.AnyThing.GetInnerIfMinified().MarketValue.ToStringMoney()); - TooltipHandler.TipRegion(rect, "MarketValueTip".Translate()); } private void DrawMass(Rect rect, TransferableOneWay trad, float availableMass) { - if (!trad.HasAnyThing) - { - return; - } - Thing anyThing = trad.AnyThing; - Pawn pawn = anyThing as Pawn; - if (pawn != null && !this.includePawnsMassInMassUsage && !MassUtility.CanEverCarryAnything(pawn)) - { - return; - } - if (Mouse.IsOver(rect)) - { - Widgets.DrawHighlight(rect); - } - if (pawn == null || this.includePawnsMassInMassUsage) - { - float mass = this.GetMass(anyThing); - if (pawn != null) - { - float gearMass = 0f; - float invMass = 0f; - gearMass = MassUtility.GearMass(pawn); - if (!InventoryCalculatorsUtility.ShouldIgnoreInventoryOf(pawn, this.ignorePawnInventoryMass)) - { - invMass = MassUtility.InventoryMass(pawn); - } - TooltipHandler.TipRegion(rect, () => this.GetPawnMassTip(trad, 0f, mass - gearMass - invMass, gearMass, invMass), trad.GetHashCode() * 59); - } - else - { - TooltipHandler.TipRegion(rect, "ItemWeightTip".Translate()); - } - if (mass > availableMass) - { - GUI.color = Color.red; - } - else - { - GUI.color = TransferableOneWayWidget.ItemMassColor; - } - Widgets.Label(rect, mass.ToStringMass()); - } - else + if (trad.HasAnyThing) { - float cap = MassUtility.Capacity(pawn); - float gearMass = MassUtility.GearMass(pawn); - float invMass = (!InventoryCalculatorsUtility.ShouldIgnoreInventoryOf(pawn, this.ignorePawnInventoryMass)) ? MassUtility.InventoryMass(pawn) : 0f; - float num = cap - gearMass - invMass; - if (num > 0f) + Thing anyThing = trad.AnyThing; + Pawn pawn = anyThing as Pawn; + if (pawn != null && !this.includePawnsMassInMassUsage && !MassUtility.CanEverCarryAnything(pawn)) + return; + if (Mouse.IsOver(rect)) { - GUI.color = Color.green; + Widgets.DrawHighlight(rect); } - else if (num < 0f) + if (pawn == null || this.includePawnsMassInMassUsage) { - GUI.color = Color.red; + float mass = this.GetMass(anyThing); + if (pawn != null) + { + float gearMass = 0f; + float invMass = 0f; + gearMass = MassUtility.GearMass(pawn); + if (!InventoryCalculatorsUtility.ShouldIgnoreInventoryOf(pawn, this.ignorePawnInventoryMass)) + { + invMass = MassUtility.InventoryMass(pawn); + } + TooltipHandler.TipRegion(rect, (Func)(() => this.GetPawnMassTip(trad, 0f, mass - gearMass - invMass, gearMass, invMass)), trad.GetHashCode() * 59); + } + else + { + TooltipHandler.TipRegion(rect, "ItemWeightTip".Translate()); + } + if (mass > availableMass) + { + GUI.color = Color.red; + } + else + { + GUI.color = TransferableOneWayWidget.ItemMassColor; + } + Widgets.Label(rect, mass.ToStringMass()); } else { - GUI.color = Color.gray; + float cap = MassUtility.Capacity(pawn); + float gearMass2 = MassUtility.GearMass(pawn); + float invMass2 = (float)((!InventoryCalculatorsUtility.ShouldIgnoreInventoryOf(pawn, this.ignorePawnInventoryMass)) ? MassUtility.InventoryMass(pawn) : 0.0); + float num = cap - gearMass2 - invMass2; + if (num > 0.0) + { + GUI.color = Color.green; + } + else if (num < 0.0) + { + GUI.color = Color.red; + } + else + { + GUI.color = Color.gray; + } + Widgets.Label(rect, num.ToStringMassOffset()); + TooltipHandler.TipRegion(rect, (Func)(() => this.GetPawnMassTip(trad, cap, 0f, gearMass2, invMass2)), trad.GetHashCode() * 59); } - Widgets.Label(rect, num.ToStringMassOffset()); - TooltipHandler.TipRegion(rect, () => this.GetPawnMassTip(trad, cap, 0f, gearMass, invMass), trad.GetHashCode() * 59); + GUI.color = Color.white; } - GUI.color = Color.white; } private string GetPawnMassTip(TransferableOneWay trad, float capacity, float pawnMass, float gearMass, float invMass) @@ -442,7 +445,7 @@ private string GetPawnMassTip(TransferableOneWay trad, float capacity, float paw return string.Empty; } StringBuilder stringBuilder = new StringBuilder(); - if (capacity != 0f) + if (capacity != 0.0) { stringBuilder.Append("MassCapacity".Translate() + ": " + capacity.ToStringMass()); } @@ -450,12 +453,12 @@ private string GetPawnMassTip(TransferableOneWay trad, float capacity, float paw { stringBuilder.Append("Mass".Translate() + ": " + pawnMass.ToStringMass()); } - if (gearMass != 0f) + if (gearMass != 0.0) { stringBuilder.AppendLine(); stringBuilder.Append("EquipmentAndApparelMass".Translate() + ": " + gearMass.ToStringMass()); } - if (invMass != 0f) + if (invMass != 0.0) { stringBuilder.AppendLine(); stringBuilder.Append("InventoryMass".Translate() + ": " + invMass.ToStringMass()); diff --git a/Assembly-CSharp/RimWorld/TransferablePositiveCountDirection.cs b/Assembly-CSharp/RimWorld/TransferablePositiveCountDirection.cs index 836b1029a..794a35337 100644 --- a/Assembly-CSharp/RimWorld/TransferablePositiveCountDirection.cs +++ b/Assembly-CSharp/RimWorld/TransferablePositiveCountDirection.cs @@ -1,10 +1,8 @@ -using System; - namespace RimWorld { public enum TransferablePositiveCountDirection { - Source, - Destination + Source = 0, + Destination = 1 } } diff --git a/Assembly-CSharp/RimWorld/TransferableSorterDefOf.cs b/Assembly-CSharp/RimWorld/TransferableSorterDefOf.cs index 384b704de..e9a6778fc 100644 --- a/Assembly-CSharp/RimWorld/TransferableSorterDefOf.cs +++ b/Assembly-CSharp/RimWorld/TransferableSorterDefOf.cs @@ -1,5 +1,3 @@ -using System; - namespace RimWorld { [DefOf] diff --git a/Assembly-CSharp/RimWorld/TransferableUIUtility.cs b/Assembly-CSharp/RimWorld/TransferableUIUtility.cs index 6f59fcdc3..e63821830 100644 --- a/Assembly-CSharp/RimWorld/TransferableUIUtility.cs +++ b/Assembly-CSharp/RimWorld/TransferableUIUtility.cs @@ -36,15 +36,28 @@ public static void DoCountAdjustInterface(Rect rect, Transferable trad, int inde } for (int i = TransferableUIUtility.stoppingPoints.Count - 1; i >= 0; i--) { - if (TransferableUIUtility.stoppingPoints[i].threshold != 0 && (TransferableUIUtility.stoppingPoints[i].threshold <= min || TransferableUIUtility.stoppingPoints[i].threshold >= max)) + TransferableCountToTransferStoppingPoint transferableCountToTransferStoppingPoint = TransferableUIUtility.stoppingPoints[i]; + if (transferableCountToTransferStoppingPoint.threshold != 0) { - TransferableUIUtility.stoppingPoints.RemoveAt(i); + TransferableCountToTransferStoppingPoint transferableCountToTransferStoppingPoint2 = TransferableUIUtility.stoppingPoints[i]; + if (transferableCountToTransferStoppingPoint2.threshold > min) + { + TransferableCountToTransferStoppingPoint transferableCountToTransferStoppingPoint3 = TransferableUIUtility.stoppingPoints[i]; + if (transferableCountToTransferStoppingPoint3.threshold >= max) + goto IL_007c; + continue; + } + goto IL_007c; } + continue; + IL_007c: + TransferableUIUtility.stoppingPoints.RemoveAt(i); } bool flag = false; for (int j = 0; j < TransferableUIUtility.stoppingPoints.Count; j++) { - if (TransferableUIUtility.stoppingPoints[j].threshold == 0) + TransferableCountToTransferStoppingPoint transferableCountToTransferStoppingPoint4 = TransferableUIUtility.stoppingPoints[j]; + if (transferableCountToTransferStoppingPoint4.threshold == 0) { flag = true; break; @@ -60,7 +73,10 @@ public static void DoCountAdjustInterface(Rect rect, Transferable trad, int inde private static void DoCountAdjustInterfaceInternal(Rect rect, Transferable trad, int index, int min, int max, bool flash) { rect = rect.Rounded(); - Rect rect2 = new Rect(rect.center.x - 45f, rect.center.y - 12.5f, 90f, 25f).Rounded(); + Vector2 center = rect.center; + double x = center.x - 45.0; + Vector2 center2 = rect.center; + Rect rect2 = new Rect((float)x, (float)(center2.y - 12.5), 90f, 25f).Rounded(); if (flash) { GUI.DrawTexture(rect2, TransferableUIUtility.FlashTex); @@ -75,12 +91,12 @@ private static void DoCountAdjustInterfaceInternal(Rect rect, Transferable trad, } else if (flag) { - bool flag2 = trad.CountToTransfer != 0; - bool flag3 = flag2; - Widgets.Checkbox(rect2.position, ref flag3, 24f, false); - if (flag3 != flag2) + bool flag2; + bool flag3 = flag2 = (trad.CountToTransfer != 0); + Widgets.Checkbox(rect2.position, ref flag2, 24f, false); + if (flag2 != flag3) { - if (flag3) + if (flag2) { trad.AdjustTo(trad.GetMaximum()); } @@ -97,7 +113,7 @@ private static void DoCountAdjustInterfaceInternal(Rect rect, Transferable trad, rect3.xMin += 16f; int countToTransfer = trad.CountToTransfer; string editBuffer = trad.EditBuffer; - Widgets.TextFieldNumeric(rect3, ref countToTransfer, ref editBuffer, (float)min, (float)max); + Widgets.TextFieldNumeric(rect3, ref countToTransfer, ref editBuffer, (float)min, (float)max); trad.AdjustTo(countToTransfer); trad.EditBuffer = editBuffer; } @@ -106,12 +122,12 @@ private static void DoCountAdjustInterfaceInternal(Rect rect, Transferable trad, if (trad.Interactive && !flag) { TransferablePositiveCountDirection positiveCountDirection = trad.PositiveCountDirection; - int num = (positiveCountDirection != TransferablePositiveCountDirection.Source) ? -1 : 1; + int num = (positiveCountDirection == TransferablePositiveCountDirection.Source) ? 1 : (-1); int num2 = GenUI.CurrentAdjustmentMultiplier(); bool flag4 = trad.GetRange() == 1; if (trad.CanAdjustBy(num * num2).Accepted) { - Rect rect4 = new Rect(rect2.x - 30f, rect.y, 30f, rect.height); + Rect rect4 = new Rect((float)(rect2.x - 30.0), rect.y, 30f, rect.height); if (flag4) { rect4.x -= rect4.width; @@ -125,31 +141,31 @@ private static void DoCountAdjustInterfaceInternal(Rect rect, Transferable trad, if (!flag4) { string label = "<<"; - int? num3 = null; - int num4 = 0; + int? nullable = default(int?); + int num3 = 0; for (int i = 0; i < TransferableUIUtility.stoppingPoints.Count; i++) { TransferableCountToTransferStoppingPoint transferableCountToTransferStoppingPoint = TransferableUIUtility.stoppingPoints[i]; if (positiveCountDirection == TransferablePositiveCountDirection.Source) { - if (trad.CountToTransfer < transferableCountToTransferStoppingPoint.threshold && (transferableCountToTransferStoppingPoint.threshold < num4 || !num3.HasValue)) + if (trad.CountToTransfer < transferableCountToTransferStoppingPoint.threshold && (transferableCountToTransferStoppingPoint.threshold < num3 || !nullable.HasValue)) { label = transferableCountToTransferStoppingPoint.leftLabel; - num3 = new int?(transferableCountToTransferStoppingPoint.threshold); + nullable = new int?(transferableCountToTransferStoppingPoint.threshold); } } - else if (trad.CountToTransfer > transferableCountToTransferStoppingPoint.threshold && (transferableCountToTransferStoppingPoint.threshold > num4 || !num3.HasValue)) + else if (trad.CountToTransfer > transferableCountToTransferStoppingPoint.threshold && (transferableCountToTransferStoppingPoint.threshold > num3 || !nullable.HasValue)) { label = transferableCountToTransferStoppingPoint.leftLabel; - num3 = new int?(transferableCountToTransferStoppingPoint.threshold); + nullable = new int?(transferableCountToTransferStoppingPoint.threshold); } } rect4.x -= rect4.width; if (Widgets.ButtonText(rect4, label, true, false, true)) { - if (num3.HasValue) + if (nullable.HasValue) { - trad.AdjustTo(num3.Value); + trad.AdjustTo(nullable.Value); } else if (num == 1) { @@ -178,31 +194,31 @@ private static void DoCountAdjustInterfaceInternal(Rect rect, Transferable trad, if (!flag4) { string label2 = ">>"; - int? num5 = null; - int num6 = 0; + int? nullable2 = default(int?); + int num4 = 0; for (int j = 0; j < TransferableUIUtility.stoppingPoints.Count; j++) { TransferableCountToTransferStoppingPoint transferableCountToTransferStoppingPoint2 = TransferableUIUtility.stoppingPoints[j]; if (positiveCountDirection == TransferablePositiveCountDirection.Destination) { - if (trad.CountToTransfer < transferableCountToTransferStoppingPoint2.threshold && (transferableCountToTransferStoppingPoint2.threshold < num6 || !num5.HasValue)) + if (trad.CountToTransfer < transferableCountToTransferStoppingPoint2.threshold && (transferableCountToTransferStoppingPoint2.threshold < num4 || !nullable2.HasValue)) { label2 = transferableCountToTransferStoppingPoint2.rightLabel; - num5 = new int?(transferableCountToTransferStoppingPoint2.threshold); + nullable2 = new int?(transferableCountToTransferStoppingPoint2.threshold); } } - else if (trad.CountToTransfer > transferableCountToTransferStoppingPoint2.threshold && (transferableCountToTransferStoppingPoint2.threshold > num6 || !num5.HasValue)) + else if (trad.CountToTransfer > transferableCountToTransferStoppingPoint2.threshold && (transferableCountToTransferStoppingPoint2.threshold > num4 || !nullable2.HasValue)) { label2 = transferableCountToTransferStoppingPoint2.rightLabel; - num5 = new int?(transferableCountToTransferStoppingPoint2.threshold); + nullable2 = new int?(transferableCountToTransferStoppingPoint2.threshold); } } rect5.x += rect5.width; if (Widgets.ButtonText(rect5, label2, true, false, true)) { - if (num5.HasValue) + if (nullable2.HasValue) { - trad.AdjustTo(num5.Value); + trad.AdjustTo(nullable2.Value); } else if (num == 1) { @@ -217,17 +233,23 @@ private static void DoCountAdjustInterfaceInternal(Rect rect, Transferable trad, } } } - if (trad.CountToTransfer != 0) + if (trad.CountToTransfer == 0) + return; + Rect position = new Rect((float)(rect2.x + rect2.width / 2.0 - (float)(TransferableUIUtility.TradeArrow.width / 2)), (float)(rect2.y + rect2.height / 2.0 - (float)(TransferableUIUtility.TradeArrow.height / 2)), (float)TransferableUIUtility.TradeArrow.width, (float)TransferableUIUtility.TradeArrow.height); + TransferablePositiveCountDirection positiveCountDirection2 = trad.PositiveCountDirection; + if (positiveCountDirection2 == TransferablePositiveCountDirection.Source && trad.CountToTransfer > 0) { - Rect position = new Rect(rect2.x + rect2.width / 2f - (float)(TransferableUIUtility.TradeArrow.width / 2), rect2.y + rect2.height / 2f - (float)(TransferableUIUtility.TradeArrow.height / 2), (float)TransferableUIUtility.TradeArrow.width, (float)TransferableUIUtility.TradeArrow.height); - TransferablePositiveCountDirection positiveCountDirection2 = trad.PositiveCountDirection; - if ((positiveCountDirection2 == TransferablePositiveCountDirection.Source && trad.CountToTransfer > 0) || (positiveCountDirection2 == TransferablePositiveCountDirection.Destination && trad.CountToTransfer < 0)) - { - position.x += position.width; - position.width *= -1f; - } - GUI.DrawTexture(position, TransferableUIUtility.TradeArrow); + goto IL_0646; } + if (positiveCountDirection2 == TransferablePositiveCountDirection.Destination && trad.CountToTransfer < 0) + goto IL_0646; + goto IL_066e; + IL_0646: + position.x += position.width; + position.width *= -1f; + goto IL_066e; + IL_066e: + GUI.DrawTexture(position, TransferableUIUtility.TradeArrow); } public static void DrawMassInfo(Rect rect, float usedMass, float availableMass, string tip, float lastMassFlashTime = -9999f, bool alignRight = false) @@ -240,23 +262,10 @@ public static void DrawMassInfo(Rect rect, float usedMass, float availableMass, { GUI.color = Color.gray; } - string text = "MassUsageInfo".Translate(new object[] - { - usedMass.ToString("0.##"), - availableMass.ToString("0.##") - }); + string text = "MassUsageInfo".Translate(usedMass.ToString("0.##"), availableMass.ToString("0.##")); Vector2 vector = Text.CalcSize(text); - Rect rect2; - if (alignRight) - { - rect2 = new Rect(rect.xMax - vector.x, rect.y, vector.x, vector.y); - } - else - { - rect2 = new Rect(rect.x, rect.y, vector.x, vector.y); - } - bool flag = Time.time - lastMassFlashTime < 1f; - if (flag) + Rect rect2 = (!alignRight) ? new Rect(rect.x, rect.y, vector.x, vector.y) : new Rect(rect.xMax - vector.x, rect.y, vector.x, vector.y); + if (Time.time - lastMassFlashTime < 1.0) { GUI.DrawTexture(rect2, TransferableUIUtility.FlashTex); } @@ -267,33 +276,31 @@ public static void DrawMassInfo(Rect rect, float usedMass, float availableMass, public static void DrawTransferableInfo(Transferable trad, Rect idRect, Color labelColor) { - if (!trad.HasAnyThing) - { - return; - } - if (Mouse.IsOver(idRect)) - { - Widgets.DrawHighlight(idRect); - } - Rect rect = new Rect(0f, 0f, 27f, 27f); - Widgets.ThingIcon(rect, trad.AnyThing, 1f); - Widgets.InfoCardButton(40f, 0f, trad.AnyThing); - Text.Anchor = TextAnchor.MiddleLeft; - Rect rect2 = new Rect(80f, 0f, idRect.width - 80f, idRect.height); - Text.WordWrap = false; - GUI.color = labelColor; - Widgets.Label(rect2, trad.Label); - GUI.color = Color.white; - Text.WordWrap = true; - Transferable localTrad = trad; - TooltipHandler.TipRegion(idRect, new TipSignal(delegate + if (trad.HasAnyThing) { - if (!localTrad.HasAnyThing) + if (Mouse.IsOver(idRect)) { - return string.Empty; + Widgets.DrawHighlight(idRect); } - return localTrad.Label + ": " + localTrad.TipDescription; - }, localTrad.GetHashCode())); + Rect rect = new Rect(0f, 0f, 27f, 27f); + Widgets.ThingIcon(rect, trad.AnyThing, 1f); + Widgets.InfoCardButton(40f, 0f, trad.AnyThing); + Text.Anchor = TextAnchor.MiddleLeft; + Rect rect2 = new Rect(80f, 0f, (float)(idRect.width - 80.0), idRect.height); + Text.WordWrap = false; + GUI.color = labelColor; + Widgets.Label(rect2, trad.Label); + GUI.color = Color.white; + Text.WordWrap = true; + TooltipHandler.TipRegion(idRect, new TipSignal((Func)delegate() + { + if (!trad.HasAnyThing) + { + return string.Empty; + } + return trad.Label + ": " + trad.TipDescription; + }, trad.GetHashCode())); + } } public static float DefaultListOrderPriority(Transferable transferable) @@ -351,12 +358,12 @@ public static void DoTransferableSorters(TransferableSorterDef sorter1, Transfer Text.Anchor = TextAnchor.MiddleLeft; Widgets.Label(rect, "SortBy".Translate()); Text.Anchor = TextAnchor.UpperLeft; - Rect rect2 = new Rect(rect.xMax + 10f, 0f, 130f, 27f); + Rect rect2 = new Rect((float)(rect.xMax + 10.0), 0f, 130f, 27f); if (Widgets.ButtonText(rect2, sorter1.LabelCap, true, false, true)) { TransferableUIUtility.OpenSorterChangeFloatMenu(sorter1Setter); } - Rect rect3 = new Rect(rect2.xMax + 10f, 0f, 130f, 27f); + Rect rect3 = new Rect((float)(rect2.xMax + 10.0), 0f, 130f, 27f); if (Widgets.ButtonText(rect3, sorter2.LabelCap, true, false, true)) { TransferableUIUtility.OpenSorterChangeFloatMenu(sorter2Setter); @@ -371,7 +378,7 @@ private static void OpenSorterChangeFloatMenu(Action sort for (int i = 0; i < allDefsListForReading.Count; i++) { TransferableSorterDef def = allDefsListForReading[i]; - list.Add(new FloatMenuOption(def.LabelCap, delegate + list.Add(new FloatMenuOption(def.LabelCap, (Action)delegate() { sorterSetter(def); }, MenuOptionPriority.Default, null, null, 0f, null, null)); diff --git a/Assembly-CSharp/RimWorld/TransferableUtility.cs b/Assembly-CSharp/RimWorld/TransferableUtility.cs index dd001a48a..72d1a06c6 100644 --- a/Assembly-CSharp/RimWorld/TransferableUtility.cs +++ b/Assembly-CSharp/RimWorld/TransferableUtility.cs @@ -11,71 +11,65 @@ public static class TransferableUtility public static void Transfer(List things, int count, Action transferred) { - if (count <= 0) + if (count > 0) { - return; - } - TransferableUtility.tmpThings.Clear(); - TransferableUtility.tmpThings.AddRange(things); - int num = count; - for (int i = 0; i < TransferableUtility.tmpThings.Count; i++) - { - Thing thing = TransferableUtility.tmpThings[i]; - int num2 = Mathf.Min(num, thing.stackCount); - if (num2 > 0) + TransferableUtility.tmpThings.Clear(); + TransferableUtility.tmpThings.AddRange(things); + int num = count; + for (int i = 0; i < TransferableUtility.tmpThings.Count; i++) { - IThingHolder parentHolder = thing.ParentHolder; - Thing thing2 = thing.SplitOff(num2); - num -= num2; - if (thing2 == thing) + Thing thing = TransferableUtility.tmpThings[i]; + int num2 = Mathf.Min(num, thing.stackCount); + if (num2 > 0) { - things.Remove(thing); - } - transferred(thing2, parentHolder); - if (num <= 0) - { - break; + IThingHolder parentHolder = thing.ParentHolder; + Thing thing2 = thing.SplitOff(num2); + num -= num2; + if (thing2 == thing) + { + things.Remove(thing); + } + transferred(thing2, parentHolder); + if (num <= 0) + break; } } - } - TransferableUtility.tmpThings.Clear(); - if (num > 0) - { - Log.Error("Can't transfer things because there is nothing left."); + TransferableUtility.tmpThings.Clear(); + if (num > 0) + { + Log.Error("Can't transfer things because there is nothing left."); + } } } public static void TransferNoSplit(List things, int count, Action transfer, bool removeIfTakingEntireThing = true, bool errorIfNotEnoughThings = true) { - if (count <= 0) + if (count > 0) { - return; - } - TransferableUtility.tmpThings.Clear(); - TransferableUtility.tmpThings.AddRange(things); - int num = count; - for (int i = 0; i < TransferableUtility.tmpThings.Count; i++) - { - Thing thing = TransferableUtility.tmpThings[i]; - int num2 = Mathf.Min(num, thing.stackCount); - if (num2 > 0) + TransferableUtility.tmpThings.Clear(); + TransferableUtility.tmpThings.AddRange(things); + int num = count; + for (int i = 0; i < TransferableUtility.tmpThings.Count; i++) { - num -= num2; - if (removeIfTakingEntireThing && num2 >= thing.stackCount) + Thing thing = TransferableUtility.tmpThings[i]; + int num2 = Mathf.Min(num, thing.stackCount); + if (num2 > 0) { - things.Remove(thing); - } - transfer(thing, num2); - if (num <= 0) - { - break; + num -= num2; + if (removeIfTakingEntireThing && num2 >= thing.stackCount) + { + things.Remove(thing); + } + transfer(thing, num2); + if (num <= 0) + break; } } - } - TransferableUtility.tmpThings.Clear(); - if (num > 0 && errorIfNotEnoughThings) - { - Log.Error("Can't transfer things because there is nothing left."); + TransferableUtility.tmpThings.Clear(); + if (num > 0 && errorIfNotEnoughThings) + { + Log.Error("Can't transfer things because there is nothing left."); + } } } @@ -85,48 +79,88 @@ public static bool TransferAsOne(Thing a, Thing b) { return true; } - if (a.def.tradeNeverStack || b.def.tradeNeverStack) + if (!a.def.tradeNeverStack && !b.def.tradeNeverStack) { - return false; - } - float num = -1f; - CompRottable compRottable = a.TryGetComp(); - if (compRottable != null) - { - num = compRottable.RotProgressPct; - } - float num2 = -1f; - CompRottable compRottable2 = b.TryGetComp(); - if (compRottable2 != null) - { - num2 = compRottable2.RotProgressPct; - } - if (Mathf.Abs(num - num2) > 0.1f) - { - return false; - } - if (a is Corpse && b is Corpse) - { - Pawn innerPawn = ((Corpse)a).InnerPawn; - Pawn innerPawn2 = ((Corpse)b).InnerPawn; - return innerPawn.def == innerPawn2.def && innerPawn.kindDef == innerPawn2.kindDef && !innerPawn.RaceProps.Humanlike && !innerPawn2.RaceProps.Humanlike && (innerPawn.Name == null || innerPawn.Name.Numerical) && (innerPawn2.Name == null || innerPawn2.Name.Numerical); - } - if (a.def.category == ThingCategory.Pawn) - { - if (b.def != a.def) + float num = -1f; + CompRottable compRottable = a.TryGetComp(); + if (compRottable != null) + { + num = compRottable.RotProgressPct; + } + float num2 = -1f; + CompRottable compRottable2 = b.TryGetComp(); + if (compRottable2 != null) + { + num2 = compRottable2.RotProgressPct; + } + if (Mathf.Abs(num - num2) > 0.10000000149011612) { return false; } - if (a.def.race.Humanlike || b.def.race.Humanlike) + if (a is Corpse && b is Corpse) + { + Pawn innerPawn = ((Corpse)a).InnerPawn; + Pawn innerPawn2 = ((Corpse)b).InnerPawn; + if (innerPawn.def != innerPawn2.def) + { + return false; + } + if (innerPawn.kindDef != innerPawn2.kindDef) + { + return false; + } + if (!innerPawn.RaceProps.Humanlike && !innerPawn2.RaceProps.Humanlike) + { + if (innerPawn.Name != null && !innerPawn.Name.Numerical) + { + goto IL_012b; + } + if (innerPawn2.Name != null && !innerPawn2.Name.Numerical) + goto IL_012b; + return true; + } + return false; + } + if (a.def.category == ThingCategory.Pawn) { + if (b.def != a.def) + { + return false; + } + if (!a.def.race.Humanlike && !b.def.race.Humanlike) + { + Pawn pawn = (Pawn)a; + Pawn pawn2 = (Pawn)b; + if (pawn.kindDef != pawn2.kindDef) + { + return false; + } + if (!(pawn.health.summaryHealth.SummaryHealthPercent < 0.99989998340606689) && !(pawn2.health.summaryHealth.SummaryHealthPercent < 0.99989998340606689)) + { + if (pawn.gender != pawn2.gender) + { + return false; + } + if (pawn.Name != null && !pawn.Name.Numerical) + { + goto IL_022b; + } + if (pawn2.Name != null && !pawn2.Name.Numerical) + goto IL_022b; + if (pawn.ageTracker.CurLifeStageIndex != pawn2.ageTracker.CurLifeStageIndex) + { + return false; + } + if (Mathf.Abs(pawn.ageTracker.AgeBiologicalYearsFloat - pawn2.ageTracker.AgeBiologicalYearsFloat) > 1.0) + { + return false; + } + return true; + } + return false; + } return false; } - Pawn pawn = (Pawn)a; - Pawn pawn2 = (Pawn)b; - return pawn.kindDef == pawn2.kindDef && pawn.health.summaryHealth.SummaryHealthPercent >= 0.9999f && pawn2.health.summaryHealth.SummaryHealthPercent >= 0.9999f && pawn.gender == pawn2.gender && (pawn.Name == null || pawn.Name.Numerical) && (pawn2.Name == null || pawn2.Name.Numerical) && pawn.ageTracker.CurLifeStageIndex == pawn2.ageTracker.CurLifeStageIndex && Mathf.Abs(pawn.ageTracker.AgeBiologicalYearsFloat - pawn2.ageTracker.AgeBiologicalYearsFloat) <= 1f; - } - else - { Apparel apparel = a as Apparel; Apparel apparel2 = b as Apparel; if (apparel != null && apparel2 != null && apparel.WornByCorpse != apparel2.WornByCorpse) @@ -137,8 +171,8 @@ public static bool TransferAsOne(Thing a, Thing b) { return false; } - QualityCategory qualityCategory; - QualityCategory qualityCategory2; + QualityCategory qualityCategory = default(QualityCategory); + QualityCategory qualityCategory2 = default(QualityCategory); if (a.TryGetQuality(out qualityCategory) && b.TryGetQuality(out qualityCategory2) && qualityCategory != qualityCategory2) { return false; @@ -147,75 +181,62 @@ public static bool TransferAsOne(Thing a, Thing b) { return a.CanStackWith(b); } - Log.Error(string.Concat(new object[] - { - "Unknown TransferAsOne pair: ", - a, - ", ", - b - })); + Log.Error("Unknown TransferAsOne pair: " + a + ", " + b); return false; } + return false; + IL_022b: + return false; + IL_012b: + return false; } public static T TransferableMatching(Thing thing, List transferables) where T : Transferable { - if (thing == null || transferables == null) + if (thing != null && transferables != null) { - return (T)((object)null); - } - for (int i = 0; i < transferables.Count; i++) - { - T result = transferables[i]; - if (result.HasAnyThing) + for (int i = 0; i < transferables.Count; i++) { - if (TransferableUtility.TransferAsOne(thing, result.AnyThing)) + T result = transferables[i]; + if (result.HasAnyThing && TransferableUtility.TransferAsOne(thing, result.AnyThing)) { return result; } } + return (T)null; } - return (T)((object)null); + return (T)null; } public static TransferableOneWay TransferableMatchingDesperate(Thing thing, List transferables) { - if (thing == null || transferables == null) - { - return null; - } - for (int i = 0; i < transferables.Count; i++) + if (thing != null && transferables != null) { - TransferableOneWay transferableOneWay = transferables[i]; - if (transferableOneWay.HasAnyThing) + for (int i = 0; i < transferables.Count; i++) { - if (transferableOneWay.things.Contains(thing)) + TransferableOneWay transferableOneWay = transferables[i]; + if (transferableOneWay.HasAnyThing && transferableOneWay.things.Contains(thing)) { return transferableOneWay; } } - } - for (int j = 0; j < transferables.Count; j++) - { - TransferableOneWay transferableOneWay2 = transferables[j]; - if (transferableOneWay2.HasAnyThing) + for (int j = 0; j < transferables.Count; j++) { - if (TransferableUtility.TransferAsOne(thing, transferableOneWay2.AnyThing)) + TransferableOneWay transferableOneWay2 = transferables[j]; + if (transferableOneWay2.HasAnyThing && TransferableUtility.TransferAsOne(thing, transferableOneWay2.AnyThing)) { return transferableOneWay2; } } - } - for (int k = 0; k < transferables.Count; k++) - { - TransferableOneWay transferableOneWay3 = transferables[k]; - if (transferableOneWay3.HasAnyThing) + for (int k = 0; k < transferables.Count; k++) { - if (transferableOneWay3.ThingDef == thing.def) + TransferableOneWay transferableOneWay3 = transferables[k]; + if (transferableOneWay3.HasAnyThing && transferableOneWay3.ThingDef == thing.def) { return transferableOneWay3; } } + return null; } return null; } @@ -225,15 +246,12 @@ public static List GetPawnsFromTransferables(List tran List list = new List(); for (int i = 0; i < transferables.Count; i++) { - if (transferables[i].CountToTransfer > 0) + if (transferables[i].CountToTransfer > 0 && transferables[i].AnyThing is Pawn) { - if (transferables[i].AnyThing is Pawn) + for (int j = 0; j < transferables[i].CountToTransfer; j++) { - for (int j = 0; j < transferables[i].CountToTransfer; j++) - { - Pawn item = (Pawn)transferables[i].things[j]; - list.Add(item); - } + Pawn item = (Pawn)transferables[i].things[j]; + list.Add(item); } } } @@ -253,24 +271,32 @@ public static void SimulateTradeableTransfer(List all, List tr int num = -countToTransfer; if (countToTransfer > 0) { - TransferableUtility.TransferNoSplit(tradeables[j].thingsTrader, countToTransfer, delegate(Thing originalThing, int toTake) + TransferableUtility.TransferNoSplit(tradeables[j].thingsTrader, countToTransfer, (Action)delegate(Thing originalThing, int toTake) { outThingsAfterTransfer.Add(new ThingStackPart(originalThing, toTake)); }, false, false); } else if (num > 0) { - TransferableUtility.TransferNoSplit(tradeables[j].thingsColony, num, delegate(Thing originalThing, int toTake) + TransferableUtility.TransferNoSplit(tradeables[j].thingsColony, num, (Action)delegate(Thing originalThing, int toTake) { - for (int k = 0; k < outThingsAfterTransfer.Count; k++) + int num2 = 0; + ThingStackPart thingStackPart; + while (true) { - ThingStackPart thingStackPart = outThingsAfterTransfer[k]; - if (thingStackPart.Thing == originalThing) + if (num2 < outThingsAfterTransfer.Count) { - outThingsAfterTransfer[k] = thingStackPart.WithCount(thingStackPart.Count - toTake); + thingStackPart = outThingsAfterTransfer[num2]; + if (thingStackPart.Thing != originalThing) + { + num2++; + continue; + } break; } + return; } + outThingsAfterTransfer[num2] = thingStackPart.WithCount(thingStackPart.Count - toTake); }, false, false); } } diff --git a/Assembly-CSharp/RimWorld/TransporterUtility.cs b/Assembly-CSharp/RimWorld/TransporterUtility.cs index 0a1d57336..4042eaa27 100644 --- a/Assembly-CSharp/RimWorld/TransporterUtility.cs +++ b/Assembly-CSharp/RimWorld/TransporterUtility.cs @@ -1,4 +1,3 @@ -using System; using System.Collections.Generic; using Verse; using Verse.AI.Group; @@ -10,17 +9,16 @@ public static class TransporterUtility public static void GetTransportersInGroup(int transportersGroup, Map map, List outTransporters) { outTransporters.Clear(); - if (transportersGroup < 0) + if (transportersGroup >= 0) { - return; - } - List list = map.listerThings.ThingsInGroup(ThingRequestGroup.Transporter); - for (int i = 0; i < list.Count; i++) - { - CompTransporter compTransporter = list[i].TryGetComp(); - if (compTransporter.groupID == transportersGroup) + List list = map.listerThings.ThingsInGroup(ThingRequestGroup.Transporter); + for (int i = 0; i < list.Count; i++) { - outTransporters.Add(compTransporter); + CompTransporter compTransporter = list[i].TryGetComp(); + if (compTransporter.groupID == transportersGroup) + { + outTransporters.Add(compTransporter); + } } } } @@ -42,7 +40,11 @@ public static Lord FindLord(int transportersGroup, Map map) public static bool WasLoadingCanceled(Thing transporter) { CompTransporter compTransporter = transporter.TryGetComp(); - return compTransporter != null && !compTransporter.LoadingInProgressOrReadyToLaunch; + if (compTransporter != null && !compTransporter.LoadingInProgressOrReadyToLaunch) + { + return true; + } + return false; } } } diff --git a/Assembly-CSharp/RimWorld/TrapMemory.cs b/Assembly-CSharp/RimWorld/TrapMemory.cs index 55f64e1df..fb7cd50bd 100644 --- a/Assembly-CSharp/RimWorld/TrapMemory.cs +++ b/Assembly-CSharp/RimWorld/TrapMemory.cs @@ -1,4 +1,3 @@ -using System; using Verse; namespace RimWorld @@ -49,7 +48,7 @@ public float PowerPercent { get { - return 1f - (float)this.Age / 1680000f; + return (float)(1.0 - (float)this.Age / 1680000.0); } } diff --git a/Assembly-CSharp/RimWorld/TrashUtility.cs b/Assembly-CSharp/RimWorld/TrashUtility.cs index 8f59e7aae..4dfa50960 100644 --- a/Assembly-CSharp/RimWorld/TrashUtility.cs +++ b/Assembly-CSharp/RimWorld/TrashUtility.cs @@ -1,4 +1,3 @@ -using System; using Verse; using Verse.AI; @@ -12,21 +11,25 @@ internal static class TrashUtility public static bool ShouldTrashPlant(Pawn pawn, Plant p) { - if (!p.sown || p.def.plant.IsTree || !p.FlammableNow || !TrashUtility.CanTrash(pawn, p)) + if (p.sown && !p.def.plant.IsTree && p.FlammableNow && TrashUtility.CanTrash(pawn, p)) { - return false; - } - CellRect.CellRectIterator iterator = CellRect.CenteredOn(p.Position, 2).ClipInsideMap(p.Map).GetIterator(); - while (!iterator.Done()) - { - IntVec3 current = iterator.Current; - if (current.InBounds(p.Map) && current.ContainsStaticFire(p.Map)) + CellRect.CellRectIterator iterator = CellRect.CenteredOn(p.Position, 2).ClipInsideMap(p.Map).GetIterator(); + while (!iterator.Done()) + { + IntVec3 current = iterator.Current; + if (current.InBounds(p.Map) && current.ContainsStaticFire(p.Map)) + { + return false; + } + iterator.MoveNext(); + } + if (!p.Position.Roofed(p.Map) && p.Map.weatherManager.RainRate > 0.25) { return false; } - iterator.MoveNext(); + return true; } - return p.Position.Roofed(p.Map) || p.Map.weatherManager.RainRate <= 0.25f; + return false; } public static bool ShouldTrashBuilding(Pawn pawn, Building b) @@ -44,12 +47,24 @@ public static bool ShouldTrashBuilding(Pawn pawn, Building b) return false; } } - return (!b.def.building.isTrap || !((Building_Trap)b).Armed) && TrashUtility.CanTrash(pawn, b) && pawn.HostileTo(b); + if (b.def.building.isTrap && ((Building_Trap)b).Armed) + { + return false; + } + if (TrashUtility.CanTrash(pawn, b) && pawn.HostileTo(b)) + { + return true; + } + return false; } private static bool CanTrash(Pawn pawn, Thing t) { - return pawn.CanReach(t, PathEndMode.Touch, Danger.Some, false, TraverseMode.ByPawn) && !t.IsBurning(); + if (pawn.CanReach(t, PathEndMode.Touch, Danger.Some, false, TraverseMode.ByPawn) && !t.IsBurning()) + { + return true; + } + return false; } public static Job TrashJob(Pawn pawn, Thing t) @@ -61,29 +76,22 @@ public static Job TrashJob(Pawn pawn, Thing t) TrashUtility.FinalizeTrashJob(job); return job; } - if (pawn.equipment != null && Rand.Value < 0.7f) + if (pawn.equipment != null && Rand.Value < 0.699999988079071) { - foreach (Verb current in pawn.equipment.AllEquipmentVerbs) + foreach (Verb allEquipmentVerb in pawn.equipment.AllEquipmentVerbs) { - if (current.verbProps.ai_IsBuildingDestroyer) + if (allEquipmentVerb.verbProps.ai_IsBuildingDestroyer) { Job job2 = new Job(JobDefOf.UseVerbOnThing, t); - job2.verbToUse = current; + job2.verbToUse = allEquipmentVerb; TrashUtility.FinalizeTrashJob(job2); return job2; } } } + Job job3 = null; float value = Rand.Value; - Job job3; - if (value < 0.35f && pawn.natives.IgniteVerb != null && t.FlammableNow && !t.IsBurning() && !(t is Building_Door)) - { - job3 = new Job(JobDefOf.Ignite, t); - } - else - { - job3 = new Job(JobDefOf.AttackMelee, t); - } + job3 = ((!(value < 0.34999999403953552) || pawn.natives.IgniteVerb == null || !t.FlammableNow || t.IsBurning() || t is Building_Door) ? new Job(JobDefOf.AttackMelee, t) : new Job(JobDefOf.Ignite, t)); TrashUtility.FinalizeTrashJob(job3); return job3; } diff --git a/Assembly-CSharp/RimWorld/TriggerData_FractionColonyDamageTaken.cs b/Assembly-CSharp/RimWorld/TriggerData_FractionColonyDamageTaken.cs index ed65b34bb..c1eb8b9af 100644 --- a/Assembly-CSharp/RimWorld/TriggerData_FractionColonyDamageTaken.cs +++ b/Assembly-CSharp/RimWorld/TriggerData_FractionColonyDamageTaken.cs @@ -1,4 +1,3 @@ -using System; using Verse; using Verse.AI.Group; diff --git a/Assembly-CSharp/RimWorld/TriggerData_PawnCycleInd.cs b/Assembly-CSharp/RimWorld/TriggerData_PawnCycleInd.cs index 4b7a2e24c..07075740e 100644 --- a/Assembly-CSharp/RimWorld/TriggerData_PawnCycleInd.cs +++ b/Assembly-CSharp/RimWorld/TriggerData_PawnCycleInd.cs @@ -1,4 +1,3 @@ -using System; using Verse; using Verse.AI.Group; diff --git a/Assembly-CSharp/RimWorld/Trigger_FractionColonyDamageTaken.cs b/Assembly-CSharp/RimWorld/Trigger_FractionColonyDamageTaken.cs index e4f4a9405..baefb946a 100644 --- a/Assembly-CSharp/RimWorld/Trigger_FractionColonyDamageTaken.cs +++ b/Assembly-CSharp/RimWorld/Trigger_FractionColonyDamageTaken.cs @@ -1,4 +1,3 @@ -using System; using UnityEngine; using Verse.AI.Group; @@ -14,13 +13,13 @@ private TriggerData_FractionColonyDamageTaken Data { get { - return (TriggerData_FractionColonyDamageTaken)this.data; + return (TriggerData_FractionColonyDamageTaken)base.data; } } public Trigger_FractionColonyDamageTaken(float desiredColonyDamageFraction, float minDamage = 3.40282347E+38f) { - this.data = new TriggerData_FractionColonyDamageTaken(); + base.data = new TriggerData_FractionColonyDamageTaken(); this.desiredColonyDamageFraction = desiredColonyDamageFraction; this.minDamage = minDamage; } diff --git a/Assembly-CSharp/RimWorld/Trigger_HighValueThingsAround.cs b/Assembly-CSharp/RimWorld/Trigger_HighValueThingsAround.cs index 7faf3ae8f..20f5000dd 100644 --- a/Assembly-CSharp/RimWorld/Trigger_HighValueThingsAround.cs +++ b/Assembly-CSharp/RimWorld/Trigger_HighValueThingsAround.cs @@ -1,4 +1,3 @@ -using System; using Verse; using Verse.AI.Group; diff --git a/Assembly-CSharp/RimWorld/Trigger_KidnapVictimPresent.cs b/Assembly-CSharp/RimWorld/Trigger_KidnapVictimPresent.cs index d05a03c23..d9e4091d8 100644 --- a/Assembly-CSharp/RimWorld/Trigger_KidnapVictimPresent.cs +++ b/Assembly-CSharp/RimWorld/Trigger_KidnapVictimPresent.cs @@ -1,4 +1,4 @@ -using System; +using System.Collections.Generic; using Verse; using Verse.AI; using Verse.AI.Group; @@ -15,13 +15,13 @@ private TriggerData_PawnCycleInd Data { get { - return (TriggerData_PawnCycleInd)this.data; + return (TriggerData_PawnCycleInd)base.data; } } public Trigger_KidnapVictimPresent() { - this.data = new TriggerData_PawnCycleInd(); + base.data = new TriggerData_PawnCycleInd(); } public override bool ActivateOn(Lord lord, TriggerSignal signal) @@ -35,8 +35,8 @@ public override bool ActivateOn(Lord lord, TriggerSignal signal) data.pawnCycleInd = 0; } Pawn pawn = lord.ownedPawns[data.pawnCycleInd]; - Pawn pawn2; - if (pawn.Spawned && !pawn.Downed && pawn.MentalStateDef == null && KidnapAIUtility.TryFindGoodKidnapVictim(pawn, 8f, out pawn2, null) && !GenAI.InDangerousCombat(pawn)) + Pawn pawn2 = default(Pawn); + if (pawn.Spawned && !pawn.Downed && pawn.MentalStateDef == null && KidnapAIUtility.TryFindGoodKidnapVictim(pawn, 8f, out pawn2, (List)null) && !GenAI.InDangerousCombat(pawn)) { return true; } diff --git a/Assembly-CSharp/RimWorld/Trigger_WoundedGuestPresent.cs b/Assembly-CSharp/RimWorld/Trigger_WoundedGuestPresent.cs index b6b1a6cf7..fb745393a 100644 --- a/Assembly-CSharp/RimWorld/Trigger_WoundedGuestPresent.cs +++ b/Assembly-CSharp/RimWorld/Trigger_WoundedGuestPresent.cs @@ -1,4 +1,3 @@ -using System; using Verse; using Verse.AI.Group; @@ -12,13 +11,13 @@ private TriggerData_PawnCycleInd Data { get { - return (TriggerData_PawnCycleInd)this.data; + return (TriggerData_PawnCycleInd)base.data; } } public Trigger_WoundedGuestPresent() { - this.data = new TriggerData_PawnCycleInd(); + base.data = new TriggerData_PawnCycleInd(); } public override bool ActivateOn(Lord lord, TriggerSignal signal) diff --git a/Assembly-CSharp/RimWorld/Tunings.cs b/Assembly-CSharp/RimWorld/Tunings.cs index 5e091b7e3..9aae7d1ce 100644 --- a/Assembly-CSharp/RimWorld/Tunings.cs +++ b/Assembly-CSharp/RimWorld/Tunings.cs @@ -1,5 +1,3 @@ -using System; - namespace RimWorld { public static class Tunings diff --git a/Assembly-CSharp/RimWorld/TurretTop.cs b/Assembly-CSharp/RimWorld/TurretTop.cs index 2f6e63650..0b369a8bd 100644 --- a/Assembly-CSharp/RimWorld/TurretTop.cs +++ b/Assembly-CSharp/RimWorld/TurretTop.cs @@ -1,4 +1,3 @@ -using System; using UnityEngine; using Verse; @@ -33,11 +32,11 @@ private float CurRotation set { this.curRotationInt = value; - if (this.curRotationInt > 360f) + if (this.curRotationInt > 360.0) { this.curRotationInt -= 360f; } - if (this.curRotationInt < 0f) + if (this.curRotationInt < 0.0) { this.curRotationInt += 360f; } @@ -63,7 +62,7 @@ public void TurretTopTick() this.ticksUntilIdleTurn--; if (this.ticksUntilIdleTurn == 0) { - if (Rand.Value < 0.5f) + if (Rand.Value < 0.5) { this.idleTurnClockwise = true; } diff --git a/Assembly-CSharp/RimWorld/Tutor.cs b/Assembly-CSharp/RimWorld/Tutor.cs index 229d0fd43..f7739fc8b 100644 --- a/Assembly-CSharp/RimWorld/Tutor.cs +++ b/Assembly-CSharp/RimWorld/Tutor.cs @@ -1,4 +1,3 @@ -using System; using Verse; namespace RimWorld diff --git a/Assembly-CSharp/RimWorld/TutorSystem.cs b/Assembly-CSharp/RimWorld/TutorSystem.cs index 40aaa5f5e..cdeb596ba 100644 --- a/Assembly-CSharp/RimWorld/TutorSystem.cs +++ b/Assembly-CSharp/RimWorld/TutorSystem.cs @@ -1,4 +1,4 @@ -using System; +using System.Collections.Generic; using System.Linq; using Verse; @@ -18,7 +18,15 @@ public static bool AdaptiveTrainingEnabled { get { - return Prefs.AdaptiveTrainingEnabled && (Find.Storyteller == null || Find.Storyteller.def == null || !Find.Storyteller.def.disableAdaptiveTraining); + if (!Prefs.AdaptiveTrainingEnabled) + { + return false; + } + if (Find.Storyteller != null && Find.Storyteller.def != null && Find.Storyteller.def.disableAdaptiveTraining) + { + return false; + } + return true; } } @@ -29,28 +37,39 @@ public static void Notify_Event(string eventTag, IntVec3 cell) public static void Notify_Event(EventPack ep) { - if (!TutorSystem.TutorialMode) - { - return; - } - if (DebugViewSettings.logTutor) - { - Log.Message("Notify_Event: " + ep); - } - if (Current.Game == null) - { - return; - } - if (Find.ActiveLesson.Current != null) - { - Find.ActiveLesson.Current.Notify_Event(ep); - } - foreach (InstructionDef current in DefDatabase.AllDefs) + if (TutorSystem.TutorialMode) { - if (current.eventTagInitiate == ep.Tag && (TutorSystem.TutorialMode || !current.tutorialModeOnly)) + if (DebugViewSettings.logTutor) + { + Log.Message("Notify_Event: " + ep); + } + if (Current.Game != null) { - Find.ActiveLesson.Activate(current); - break; + if (Find.ActiveLesson.Current != null) + { + Find.ActiveLesson.Current.Notify_Event(ep); + } + using (IEnumerator enumerator = DefDatabase.AllDefs.GetEnumerator()) + { + InstructionDef current; + while (true) + { + if (enumerator.MoveNext()) + { + current = enumerator.Current; + if (current.eventTagInitiate == ep.Tag) + { + if (TutorSystem.TutorialMode) + break; + if (!current.tutorialModeOnly) + break; + } + continue; + } + return; + } + Find.ActiveLesson.Activate(current); + } } } } @@ -65,9 +84,9 @@ public static bool AllowAction(EventPack ep) { Log.Message("AllowAction: " + ep); } - if (ep.Cells != null && ep.Cells.Count() == 1) + if (ep.Cells != null && ep.Cells.Count() == 1) { - return TutorSystem.AllowAction(new EventPack(ep.Tag, ep.Cells.First())); + return TutorSystem.AllowAction(new EventPack(ep.Tag, ep.Cells.First())); } if (Find.ActiveLesson.Current != null) { diff --git a/Assembly-CSharp/RimWorld/TutorUtility.cs b/Assembly-CSharp/RimWorld/TutorUtility.cs index a8c22a36e..4c1a9fbfb 100644 --- a/Assembly-CSharp/RimWorld/TutorUtility.cs +++ b/Assembly-CSharp/RimWorld/TutorUtility.cs @@ -29,14 +29,14 @@ public static bool BuildingOrBlueprintOrFrameCenterExists(IntVec3 c, Map map, Th return false; } - public static CellRect FindUsableRect(int width, int height, Map map, float minFertility = 0f, bool noItems = false) + public static CellRect FindUsableRect(int width, int height, Map map, float minFertility = 0, bool noItems = false) { IntVec3 center = map.Center; float num = 1f; CellRect cellRect; while (true) { - IntVec3 center2 = center + new IntVec3((int)Rand.Range(-num, num), 0, (int)Rand.Range(-num, num)); + IntVec3 center2 = center + new IntVec3((int)Rand.Range((float)(0.0 - num), num), 0, (int)Rand.Range((float)(0.0 - num), num)); cellRect = CellRect.CenteredOn(center2, width / 2); cellRect.Width = width; cellRect.Height = height; @@ -46,18 +46,20 @@ public static CellRect FindUsableRect(int width, int height, Map map, float minF while (!iterator.Done()) { IntVec3 current = iterator.Current; - if (current.Fogged(map) || !current.Walkable(map) || !current.GetTerrain(map).affordances.Contains(TerrainAffordance.Heavy) || current.GetTerrain(map).fertility < minFertility || current.GetZone(map) != null || TutorUtility.ContainsBlockingThing(current, map, noItems) || current.InNoBuildEdgeArea(map) || current.InNoZoneEdgeArea(map)) + if (!current.Fogged(map) && current.Walkable(map) && current.GetTerrain(map).affordances.Contains(TerrainAffordance.Heavy) && !(current.GetTerrain(map).fertility < minFertility) && current.GetZone(map) == null && !TutorUtility.ContainsBlockingThing(current, map, noItems) && !current.InNoBuildEdgeArea(map) && !current.InNoZoneEdgeArea(map)) { - flag = false; - break; + iterator.MoveNext(); + continue; } - iterator.MoveNext(); + flag = false; + break; } - if (flag) + if (!flag) { - break; + num = (float)(num + 0.25); + continue; } - num += 0.25f; + break; } return cellRect.ContractedBy(1); } @@ -87,7 +89,7 @@ public static void DrawLabelOnThingOnGUI(Thing t, string label) { Vector2 vector = (t.DrawPos + new Vector3(0f, 0f, 0.5f)).MapToUIPosition(); Vector2 vector2 = Text.CalcSize(label); - Rect rect = new Rect(vector.x - vector2.x / 2f, vector.y - vector2.y / 2f, vector2.x, vector2.y); + Rect rect = new Rect((float)(vector.x - vector2.x / 2.0), (float)(vector.y - vector2.y / 2.0), vector2.x, vector2.y); GUI.DrawTexture(rect, TexUI.GrayTextBG); Text.Font = GameFont.Tiny; Text.Anchor = TextAnchor.MiddleCenter; @@ -99,7 +101,7 @@ public static void DrawLabelOnGUI(Vector3 mapPos, string label) { Vector2 vector = mapPos.MapToUIPosition(); Vector2 vector2 = Text.CalcSize(label); - Rect rect = new Rect(vector.x - vector2.x / 2f, vector.y - vector2.y / 2f, vector2.x, vector2.y); + Rect rect = new Rect((float)(vector.x - vector2.x / 2.0), (float)(vector.y - vector2.y / 2.0), vector2.x, vector2.y); GUI.DrawTexture(rect, TexUI.GrayTextBG); Text.Font = GameFont.Tiny; Text.Anchor = TextAnchor.MiddleCenter; @@ -131,7 +133,7 @@ public static void DoModalDialogIfNotKnown(ConceptDef conc) if (!PlayerKnowledgeDatabase.IsComplete(conc)) { string helpTextAdjusted = conc.HelpTextAdjusted; - Find.WindowStack.Add(new Dialog_MessageBox(helpTextAdjusted, null, null, null, null, null, false)); + Find.WindowStack.Add(new Dialog_MessageBox(helpTextAdjusted, (string)null, null, (string)null, null, (string)null, false)); PlayerKnowledgeDatabase.KnowledgeDemonstrated(conc, KnowledgeAmount.Total); } } @@ -147,9 +149,9 @@ public static bool EventCellsMatchExactly(EventPack ep, List targetCell return false; } int num = 0; - foreach (IntVec3 current in ep.Cells) + foreach (IntVec3 cell in ep.Cells) { - if (!targetCells.Contains(current)) + if (!targetCells.Contains(cell)) { return false; } @@ -164,7 +166,11 @@ public static bool EventCellsAreWithin(EventPack ep, List targetCells) { return targetCells.Contains(ep.Cell); } - return ep.Cells != null && !ep.Cells.Any((IntVec3 c) => !targetCells.Contains(c)); + if (ep.Cells != null) + { + return !ep.Cells.Any((Func)((IntVec3 c) => !targetCells.Contains(c))); + } + return false; } } } diff --git a/Assembly-CSharp/RimWorld/TutorialState.cs b/Assembly-CSharp/RimWorld/TutorialState.cs index d00f5cc16..de19a2ebf 100644 --- a/Assembly-CSharp/RimWorld/TutorialState.cs +++ b/Assembly-CSharp/RimWorld/TutorialState.cs @@ -20,7 +20,7 @@ public void ExposeData() { if (Scribe.mode == LoadSaveMode.Saving && this.startingItems != null) { - this.startingItems.RemoveAll((Thing it) => it == null || it.Destroyed || (it.Map == null && it.MapHeld == null)); + this.startingItems.RemoveAll((Predicate)((Thing it) => it == null || it.Destroyed || (it.Map == null && it.MapHeld == null))); } Scribe_Collections.Look(ref this.startingItems, "startingItems", LookMode.Reference, new object[0]); Scribe_Values.Look(ref this.roomRect, "roomRect", default(CellRect), false); @@ -29,7 +29,7 @@ public void ExposeData() Scribe_Values.Look(ref this.introDone, "introDone", false, false); if (this.startingItems != null) { - this.startingItems.RemoveAll((Thing it) => it == null); + this.startingItems.RemoveAll((Predicate)((Thing it) => it == null)); } } @@ -43,11 +43,10 @@ public void Notify_TutorialEnding() public void AddStartingItem(Thing t) { - if (this.startingItems.Contains(t)) + if (!this.startingItems.Contains(t)) { - return; + this.startingItems.Add(t); } - this.startingItems.Add(t); } } } diff --git a/Assembly-CSharp/RimWorld/Twelfth.cs b/Assembly-CSharp/RimWorld/Twelfth.cs index 6ed5ead58..b08df3d4a 100644 --- a/Assembly-CSharp/RimWorld/Twelfth.cs +++ b/Assembly-CSharp/RimWorld/Twelfth.cs @@ -1,21 +1,19 @@ -using System; - namespace RimWorld { public enum Twelfth : byte { - First, - Second, - Third, - Fourth, - Fifth, - Sixth, - Seventh, - Eighth, - Ninth, - Tenth, - Eleventh, - Twelfth, - Undefined + First = 0, + Second = 1, + Third = 2, + Fourth = 3, + Fifth = 4, + Sixth = 5, + Seventh = 6, + Eighth = 7, + Ninth = 8, + Tenth = 9, + Eleventh = 10, + Twelfth = 11, + Undefined = 12 } } diff --git a/Assembly-CSharp/RimWorld/TwelfthUtility.cs b/Assembly-CSharp/RimWorld/TwelfthUtility.cs index faf0f5cb8..3997d3839 100644 --- a/Assembly-CSharp/RimWorld/TwelfthUtility.cs +++ b/Assembly-CSharp/RimWorld/TwelfthUtility.cs @@ -1,5 +1,5 @@ -using System; using System.Collections.Generic; +using UnityEngine; using Verse; namespace RimWorld @@ -8,65 +8,113 @@ public static class TwelfthUtility { public static Season GetSeason(this Twelfth twelfth, float latitude) { - if (latitude >= 0f) + if (latitude >= 0.0) { switch (twelfth) { case Twelfth.First: + { return Season.Spring; + } case Twelfth.Second: + { return Season.Spring; + } case Twelfth.Third: + { return Season.Spring; + } case Twelfth.Fourth: + { return Season.Summer; + } case Twelfth.Fifth: + { return Season.Summer; + } case Twelfth.Sixth: + { return Season.Summer; + } case Twelfth.Seventh: + { return Season.Fall; + } case Twelfth.Eighth: + { return Season.Fall; + } case Twelfth.Ninth: + { return Season.Fall; + } case Twelfth.Tenth: + { return Season.Winter; + } case Twelfth.Eleventh: + { return Season.Winter; + } case Twelfth.Twelfth: + { return Season.Winter; } + } } else { switch (twelfth) { case Twelfth.First: + { return Season.Fall; + } case Twelfth.Second: + { return Season.Fall; + } case Twelfth.Third: + { return Season.Fall; + } case Twelfth.Fourth: + { return Season.Winter; + } case Twelfth.Fifth: + { return Season.Winter; + } case Twelfth.Sixth: + { return Season.Winter; + } case Twelfth.Seventh: + { return Season.Spring; + } case Twelfth.Eighth: + { return Season.Spring; + } case Twelfth.Ninth: + { return Season.Spring; + } case Twelfth.Tenth: + { return Season.Summer; + } case Twelfth.Eleventh: + { return Season.Summer; + } case Twelfth.Twelfth: + { return Season.Summer; } + } } return Season.Undefined; } @@ -76,32 +124,58 @@ public static Quadrum GetQuadrum(this Twelfth twelfth) switch (twelfth) { case Twelfth.First: + { return Quadrum.Aprimay; + } case Twelfth.Second: + { return Quadrum.Aprimay; + } case Twelfth.Third: + { return Quadrum.Aprimay; + } case Twelfth.Fourth: + { return Quadrum.Jugust; + } case Twelfth.Fifth: + { return Quadrum.Jugust; + } case Twelfth.Sixth: + { return Quadrum.Jugust; + } case Twelfth.Seventh: + { return Quadrum.Septober; + } case Twelfth.Eighth: + { return Quadrum.Septober; + } case Twelfth.Ninth: + { return Quadrum.Septober; + } case Twelfth.Tenth: + { return Quadrum.Decembary; + } case Twelfth.Eleventh: + { return Quadrum.Decembary; + } case Twelfth.Twelfth: + { return Quadrum.Decembary; + } default: + { return Quadrum.Undefined; } + } } public static Twelfth PreviousTwelfth(this Twelfth twelfth) @@ -110,12 +184,12 @@ public static Twelfth PreviousTwelfth(this Twelfth twelfth) { return Twelfth.Undefined; } - int num = (int)(twelfth - Twelfth.Second); + int num = (int)(twelfth - 1); if (num == -1) { num = 11; } - return (Twelfth)num; + return (Twelfth)(byte)num; } public static Twelfth NextTwelfth(this Twelfth twelfth) @@ -124,12 +198,12 @@ public static Twelfth NextTwelfth(this Twelfth twelfth) { return Twelfth.Undefined; } - return (twelfth + 1) % Twelfth.Undefined; + return (Twelfth)(byte)((int)(twelfth + 1) % 12); } public static float GetBeginningYearPct(this Twelfth twelfth) { - return (float)twelfth / 12f; + return (float)((float)(int)twelfth / 12.0); } public static Twelfth FindStartingWarmTwelfth(int tile) @@ -137,7 +211,8 @@ public static Twelfth FindStartingWarmTwelfth(int tile) Twelfth twelfth = GenTemperature.EarliestTwelfthInAverageTemperatureRange(tile, 16f, 9999f); if (twelfth == Twelfth.Undefined) { - twelfth = Season.Summer.GetFirstTwelfth(Find.WorldGrid.LongLatOf(tile).y); + Vector2 vector = Find.WorldGrid.LongLatOf(tile); + twelfth = Season.Summer.GetFirstTwelfth(vector.y); } return twelfth; } @@ -149,12 +224,13 @@ public static Twelfth GetLeftMostTwelfth(List twelfths, Twelfth rootTwe return Twelfth.Undefined; } Twelfth result; - do + while (true) { result = rootTwelfth; rootTwelfth = TwelfthUtility.TwelfthBefore(rootTwelfth); + if (!twelfths.Contains(rootTwelfth)) + break; } - while (twelfths.Contains(rootTwelfth)); return result; } @@ -165,12 +241,13 @@ public static Twelfth GetRightMostTwelfth(List twelfths, Twelfth rootTw return Twelfth.Undefined; } Twelfth m; - do + while (true) { m = rootTwelfth; rootTwelfth = TwelfthUtility.TwelfthAfter(rootTwelfth); + if (!twelfths.Contains(rootTwelfth)) + break; } - while (twelfths.Contains(rootTwelfth)); return TwelfthUtility.TwelfthAfter(m); } @@ -180,7 +257,7 @@ public static Twelfth TwelfthBefore(Twelfth m) { return Twelfth.Twelfth; } - return (Twelfth)(m - Twelfth.Second); + return m - 1; } public static Twelfth TwelfthAfter(Twelfth m) diff --git a/Assembly-CSharp/RimWorld/UIRoot_Play.cs b/Assembly-CSharp/RimWorld/UIRoot_Play.cs index df33714b8..8ca180680 100644 --- a/Assembly-CSharp/RimWorld/UIRoot_Play.cs +++ b/Assembly-CSharp/RimWorld/UIRoot_Play.cs @@ -24,17 +24,17 @@ public override void UIRootOnGUI() Find.GameInfo.GameInfoOnGUI(); Find.World.UI.WorldInterfaceOnGUI(); this.mapUI.MapInterfaceOnGUI_BeforeMainTabs(); - if (!this.screenshotMode.FiltersCurrentEvent) + if (!base.screenshotMode.FiltersCurrentEvent) { this.mainButtonsRoot.MainButtonsOnGUI(); this.alerts.AlertsReadoutOnGUI(); } this.mapUI.MapInterfaceOnGUI_AfterMainTabs(); - if (!this.screenshotMode.FiltersCurrentEvent) + if (!base.screenshotMode.FiltersCurrentEvent) { Find.Tutor.TutorOnGUI(); } - this.windows.WindowStackOnGUI(); + base.windows.WindowStackOnGUI(); ReorderableWidget.ReorderableWidgetOnGUI(); this.mapUI.HandleMapClicks(); if (Find.DesignatorManager.SelectedDesignator != null) diff --git a/Assembly-CSharp/RimWorld/UI_BackgroundMain.cs b/Assembly-CSharp/RimWorld/UI_BackgroundMain.cs index 486621a65..a34ef029e 100644 --- a/Assembly-CSharp/RimWorld/UI_BackgroundMain.cs +++ b/Assembly-CSharp/RimWorld/UI_BackgroundMain.cs @@ -1,4 +1,3 @@ -using System; using UnityEngine; using Verse; @@ -14,7 +13,12 @@ public class UI_BackgroundMain : UIMenuBackground public override void BackgroundOnGUI() { bool flag = true; - if ((float)UI.screenWidth > (float)UI.screenHeight * (UI_BackgroundMain.BGPlanetSize.x / UI_BackgroundMain.BGPlanetSize.y)) + float num = (float)UI.screenWidth; + float num2 = (float)UI.screenHeight; + Vector2 bGPlanetSize = UI_BackgroundMain.BGPlanetSize; + float x = bGPlanetSize.x; + Vector2 bGPlanetSize2 = UI_BackgroundMain.BGPlanetSize; + if (num > num2 * (x / bGPlanetSize2.y)) { flag = false; } @@ -22,14 +26,22 @@ public override void BackgroundOnGUI() if (flag) { float height = (float)UI.screenHeight; - float num = (float)UI.screenHeight * (UI_BackgroundMain.BGPlanetSize.x / UI_BackgroundMain.BGPlanetSize.y); - position = new Rect((float)(UI.screenWidth / 2) - num / 2f, 0f, num, height); + float num3 = (float)UI.screenHeight; + Vector2 bGPlanetSize3 = UI_BackgroundMain.BGPlanetSize; + float x2 = bGPlanetSize3.x; + Vector2 bGPlanetSize4 = UI_BackgroundMain.BGPlanetSize; + float num4 = num3 * (x2 / bGPlanetSize4.y); + position = new Rect((float)((float)(UI.screenWidth / 2) - num4 / 2.0), 0f, num4, height); } else { float width = (float)UI.screenWidth; - float num2 = (float)UI.screenWidth * (UI_BackgroundMain.BGPlanetSize.y / UI_BackgroundMain.BGPlanetSize.x); - position = new Rect(0f, (float)(UI.screenHeight / 2) - num2 / 2f, width, num2); + float num5 = (float)UI.screenWidth; + Vector2 bGPlanetSize5 = UI_BackgroundMain.BGPlanetSize; + float y = bGPlanetSize5.y; + Vector2 bGPlanetSize6 = UI_BackgroundMain.BGPlanetSize; + float num6 = num5 * (y / bGPlanetSize6.x); + position = new Rect(0f, (float)((float)(UI.screenHeight / 2) - num6 / 2.0), width, num6); } GUI.DrawTexture(position, UI_BackgroundMain.BGPlanet, ScaleMode.ScaleToFit); } diff --git a/Assembly-CSharp/RimWorld/UniqueIDsManager.cs b/Assembly-CSharp/RimWorld/UniqueIDsManager.cs index fcac7141e..d9923059d 100644 --- a/Assembly-CSharp/RimWorld/UniqueIDsManager.cs +++ b/Assembly-CSharp/RimWorld/UniqueIDsManager.cs @@ -1,4 +1,3 @@ -using System; using Verse; namespace RimWorld diff --git a/Assembly-CSharp/RimWorld/VerbDefsHardcodedNative.cs b/Assembly-CSharp/RimWorld/VerbDefsHardcodedNative.cs index 09198e7a2..209cfacf0 100644 --- a/Assembly-CSharp/RimWorld/VerbDefsHardcodedNative.cs +++ b/Assembly-CSharp/RimWorld/VerbDefsHardcodedNative.cs @@ -1,19 +1,46 @@ -using System; using System.Collections.Generic; -using System.Diagnostics; using Verse; namespace RimWorld { public static class VerbDefsHardcodedNative { - [DebuggerHidden] public static IEnumerable AllVerbDefs() { - VerbDefsHardcodedNative.c__Iterator1AB c__Iterator1AB = new VerbDefsHardcodedNative.c__Iterator1AB(); - VerbDefsHardcodedNative.c__Iterator1AB expr_07 = c__Iterator1AB; - expr_07.$PC = -2; - return expr_07; + yield return new VerbProperties + { + category = VerbCategory.BeatFire, + label = "Beat fire", + range = 1f, + noiseRadius = 3f, + targetParams = + { + canTargetFires = true, + canTargetPawns = false, + canTargetBuildings = false, + mapObjectTargetsMustBeAutoAttackable = false + }, + warmupTime = 0f, + defaultCooldownTime = 1.1f, + soundCast = SoundDef.Named("Interact_BeatFire") + }; + yield return new VerbProperties + { + category = VerbCategory.Ignite, + label = "Ignite", + range = 1f, + noiseRadius = 3f, + targetParams = + { + onlyTargetFlammables = true, + canTargetBuildings = true, + canTargetPawns = false, + mapObjectTargetsMustBeAutoAttackable = false + }, + warmupTime = 3f, + defaultCooldownTime = 1.3f, + soundCast = SoundDef.Named("Interact_Ignite") + }; } } } diff --git a/Assembly-CSharp/RimWorld/VerbEntry.cs b/Assembly-CSharp/RimWorld/VerbEntry.cs index d4ed5fa64..e5c8a2571 100644 --- a/Assembly-CSharp/RimWorld/VerbEntry.cs +++ b/Assembly-CSharp/RimWorld/VerbEntry.cs @@ -1,4 +1,3 @@ -using System; using Verse; namespace RimWorld diff --git a/Assembly-CSharp/RimWorld/Verb_BeatFire.cs b/Assembly-CSharp/RimWorld/Verb_BeatFire.cs index 7c8e93a03..09b83a049 100644 --- a/Assembly-CSharp/RimWorld/Verb_BeatFire.cs +++ b/Assembly-CSharp/RimWorld/Verb_BeatFire.cs @@ -1,4 +1,3 @@ -using System; using Verse; namespace RimWorld @@ -9,20 +8,20 @@ public class Verb_BeatFire : Verb public Verb_BeatFire() { - this.verbProps = NativeVerbPropertiesDatabase.VerbWithCategory(VerbCategory.BeatFire); + base.verbProps = NativeVerbPropertiesDatabase.VerbWithCategory(VerbCategory.BeatFire); } protected override bool TryCastShot() { - Fire fire = (Fire)this.currentTarget.Thing; + Fire fire = (Fire)base.currentTarget.Thing; Pawn casterPawn = base.CasterPawn; if (casterPawn.stances.FullBodyBusy) { return false; } - Thing arg_47_0 = fire; - Thing caster = this.caster; - arg_47_0.TakeDamage(new DamageInfo(DamageDefOf.Extinguish, 32, -1f, caster, null, null, DamageInfo.SourceCategory.ThingOrUnknown)); + Fire obj = fire; + Thing caster = base.caster; + obj.TakeDamage(new DamageInfo(DamageDefOf.Extinguish, 32, -1f, caster, null, null, DamageInfo.SourceCategory.ThingOrUnknown)); casterPawn.Drawer.Notify_MeleeAttackOn(fire); return true; } diff --git a/Assembly-CSharp/RimWorld/Verb_Ignite.cs b/Assembly-CSharp/RimWorld/Verb_Ignite.cs index 17f8fc239..eef7245e4 100644 --- a/Assembly-CSharp/RimWorld/Verb_Ignite.cs +++ b/Assembly-CSharp/RimWorld/Verb_Ignite.cs @@ -1,4 +1,3 @@ -using System; using Verse; namespace RimWorld @@ -7,12 +6,12 @@ public class Verb_Ignite : Verb { public Verb_Ignite() { - this.verbProps = NativeVerbPropertiesDatabase.VerbWithCategory(VerbCategory.Ignite); + base.verbProps = NativeVerbPropertiesDatabase.VerbWithCategory(VerbCategory.Ignite); } protected override bool TryCastShot() { - Thing thing = this.currentTarget.Thing; + Thing thing = base.currentTarget.Thing; Pawn casterPawn = base.CasterPawn; FireUtility.TryStartFireIn(thing.OccupiedRect().ClosestCellTo(casterPawn.Position), casterPawn.Map, 0.3f); casterPawn.Drawer.Notify_MeleeAttackOn(thing); diff --git a/Assembly-CSharp/RimWorld/Verb_MeleeAttack.cs b/Assembly-CSharp/RimWorld/Verb_MeleeAttack.cs index 41ba46c3d..d3e181010 100644 --- a/Assembly-CSharp/RimWorld/Verb_MeleeAttack.cs +++ b/Assembly-CSharp/RimWorld/Verb_MeleeAttack.cs @@ -1,6 +1,5 @@ -using System; using System.Collections.Generic; -using System.Diagnostics; +using UnityEngine; using Verse; using Verse.Sound; @@ -17,19 +16,13 @@ protected override bool TryCastShot() { return false; } - Thing thing = this.currentTarget.Thing; + Thing thing = base.currentTarget.Thing; if (!base.CanHitTarget(thing)) { - Log.Warning(string.Concat(new object[] - { - casterPawn, - " meleed ", - thing, - " from out of melee position." - })); + Log.Warning(casterPawn + " meleed " + thing + " from out of melee position."); } casterPawn.Drawer.rotator.Face(thing.DrawPos); - if (!this.IsTargetImmobile(this.currentTarget) && casterPawn.skills != null) + if (!this.IsTargetImmobile(base.currentTarget) && casterPawn.skills != null) { casterPawn.skills.Learn(SkillDefOf.Melee, 250f, false); } @@ -40,15 +33,8 @@ protected override bool TryCastShot() if (Rand.Value > this.GetDodgeChance(thing)) { result = true; - this.ApplyMeleeDamageToTarget(this.currentTarget); - if (thing.def.category == ThingCategory.Building) - { - soundDef = this.SoundHitBuilding(); - } - else - { - soundDef = this.SoundHitPawn(); - } + this.ApplyMeleeDamageToTarget(base.currentTarget); + soundDef = ((thing.def.category != ThingCategory.Building) ? this.SoundHitPawn() : this.SoundHitBuilding()); } else { @@ -82,21 +68,58 @@ protected override bool TryCastShot() return result; } - [DebuggerHidden] private IEnumerable DamageInfosToApply(LocalTargetInfo target) { - Verb_MeleeAttack.c__Iterator1B0 c__Iterator1B = new Verb_MeleeAttack.c__Iterator1B0(); - c__Iterator1B.target = target; - c__Iterator1B.<$>target = target; - c__Iterator1B.<>f__this = this; - Verb_MeleeAttack.c__Iterator1B0 expr_1C = c__Iterator1B; - expr_1C.$PC = -2; - return expr_1C; + float damAmount = (float)base.verbProps.AdjustedMeleeDamageAmount(this, base.CasterPawn, base.ownerEquipment); + DamageDef damDef = base.verbProps.meleeDamageDef; + BodyPartGroupDef bodyPartGroupDef = null; + HediffDef hediffDef = null; + if (base.CasterIsPawn) + { + if (damAmount >= 1.0) + { + bodyPartGroupDef = base.verbProps.linkedBodyPartsGroup; + if (base.ownerHediffComp != null) + { + hediffDef = base.ownerHediffComp.Def; + } + } + else + { + damAmount = 1f; + damDef = DamageDefOf.Blunt; + } + } + ThingDef source = (base.ownerEquipment == null) ? base.CasterPawn.def : base.ownerEquipment.def; + Vector3 direction = (target.Thing.Position - base.CasterPawn.Position).ToVector3(); + Thing caster = base.caster; + DamageInfo mainDinfo = new DamageInfo(damDef, GenMath.RoundRandom(damAmount), -1f, caster, null, source, DamageInfo.SourceCategory.ThingOrUnknown); + mainDinfo.SetBodyRegion(BodyPartHeight.Undefined, BodyPartDepth.Outside); + mainDinfo.SetWeaponBodyPartGroup(bodyPartGroupDef); + mainDinfo.SetWeaponHediff(hediffDef); + mainDinfo.SetAngle(direction); + yield return mainDinfo; + if (base.surpriseAttack && base.verbProps.surpriseAttack != null && base.verbProps.surpriseAttack.extraMeleeDamages != null) + { + List extraDamages = base.verbProps.surpriseAttack.extraMeleeDamages; + for (int i = 0; i < extraDamages.Count; i++) + { + ExtraMeleeDamage extraDamage = extraDamages[i]; + int amount = GenMath.RoundRandom((float)extraDamage.amount * base.GetDamageFactorFor(base.CasterPawn)); + caster = base.caster; + DamageInfo extraDinfo = new DamageInfo(extraDamage.def, amount, -1f, caster, null, source, DamageInfo.SourceCategory.ThingOrUnknown); + extraDinfo.SetBodyRegion(BodyPartHeight.Undefined, BodyPartDepth.Outside); + extraDinfo.SetWeaponBodyPartGroup(bodyPartGroupDef); + extraDinfo.SetWeaponHediff(hediffDef); + extraDinfo.SetAngle(direction); + yield return extraDinfo; + } + } } private float GetNonMissChance(LocalTargetInfo target) { - if (this.surpriseAttack) + if (base.surpriseAttack) { return 1f; } @@ -109,7 +132,7 @@ private float GetNonMissChance(LocalTargetInfo target) private float GetDodgeChance(LocalTargetInfo target) { - if (this.surpriseAttack) + if (base.surpriseAttack) { return 0f; } @@ -139,30 +162,31 @@ private bool IsTargetImmobile(LocalTargetInfo target) private void ApplyMeleeDamageToTarget(LocalTargetInfo target) { - foreach (DamageInfo current in this.DamageInfosToApply(target)) + foreach (DamageInfo item in this.DamageInfosToApply(target)) { - if (target.ThingDestroyed) + if (!target.ThingDestroyed) { - break; + target.Thing.TakeDamage(item); + continue; } - target.Thing.TakeDamage(current); + break; } } private SoundDef SoundHitPawn() { - if (this.ownerEquipment != null && this.ownerEquipment.Stuff != null) + if (base.ownerEquipment != null && base.ownerEquipment.Stuff != null) { - if (this.verbProps.meleeDamageDef.armorCategory == DamageArmorCategoryDefOf.Sharp) + if (base.verbProps.meleeDamageDef.armorCategory == DamageArmorCategoryDefOf.Sharp) { - if (!this.ownerEquipment.Stuff.stuffProps.soundMeleeHitSharp.NullOrUndefined()) + if (!base.ownerEquipment.Stuff.stuffProps.soundMeleeHitSharp.NullOrUndefined()) { - return this.ownerEquipment.Stuff.stuffProps.soundMeleeHitSharp; + return base.ownerEquipment.Stuff.stuffProps.soundMeleeHitSharp; } } - else if (!this.ownerEquipment.Stuff.stuffProps.soundMeleeHitBlunt.NullOrUndefined()) + else if (!base.ownerEquipment.Stuff.stuffProps.soundMeleeHitBlunt.NullOrUndefined()) { - return this.ownerEquipment.Stuff.stuffProps.soundMeleeHitBlunt; + return base.ownerEquipment.Stuff.stuffProps.soundMeleeHitBlunt; } } if (base.CasterPawn != null && !base.CasterPawn.def.race.soundMeleeHitPawn.NullOrUndefined()) @@ -174,18 +198,18 @@ private SoundDef SoundHitPawn() private SoundDef SoundHitBuilding() { - if (this.ownerEquipment != null && this.ownerEquipment.Stuff != null) + if (base.ownerEquipment != null && base.ownerEquipment.Stuff != null) { - if (this.verbProps.meleeDamageDef.armorCategory == DamageArmorCategoryDefOf.Sharp) + if (base.verbProps.meleeDamageDef.armorCategory == DamageArmorCategoryDefOf.Sharp) { - if (!this.ownerEquipment.Stuff.stuffProps.soundMeleeHitSharp.NullOrUndefined()) + if (!base.ownerEquipment.Stuff.stuffProps.soundMeleeHitSharp.NullOrUndefined()) { - return this.ownerEquipment.Stuff.stuffProps.soundMeleeHitSharp; + return base.ownerEquipment.Stuff.stuffProps.soundMeleeHitSharp; } } - else if (!this.ownerEquipment.Stuff.stuffProps.soundMeleeHitBlunt.NullOrUndefined()) + else if (!base.ownerEquipment.Stuff.stuffProps.soundMeleeHitBlunt.NullOrUndefined()) { - return this.ownerEquipment.Stuff.stuffProps.soundMeleeHitBlunt; + return base.ownerEquipment.Stuff.stuffProps.soundMeleeHitBlunt; } } if (base.CasterPawn != null && !base.CasterPawn.def.race.soundMeleeHitBuilding.NullOrUndefined()) diff --git a/Assembly-CSharp/RimWorld/Verb_ShootOneUse.cs b/Assembly-CSharp/RimWorld/Verb_ShootOneUse.cs index d17246e8b..aec21ef6f 100644 --- a/Assembly-CSharp/RimWorld/Verb_ShootOneUse.cs +++ b/Assembly-CSharp/RimWorld/Verb_ShootOneUse.cs @@ -1,4 +1,3 @@ -using System; using Verse; namespace RimWorld @@ -9,13 +8,13 @@ protected override bool TryCastShot() { if (base.TryCastShot()) { - if (this.burstShotsLeft <= 1) + if (base.burstShotsLeft <= 1) { this.SelfConsume(); } return true; } - if (this.burstShotsLeft < this.verbProps.burstShotCount) + if (base.burstShotsLeft < base.verbProps.burstShotCount) { this.SelfConsume(); } @@ -25,7 +24,7 @@ protected override bool TryCastShot() public override void Notify_EquipmentLost() { base.Notify_EquipmentLost(); - if (this.state == VerbState.Bursting && this.burstShotsLeft < this.verbProps.burstShotCount) + if (base.state == VerbState.Bursting && base.burstShotsLeft < base.verbProps.burstShotCount) { this.SelfConsume(); } @@ -33,9 +32,9 @@ public override void Notify_EquipmentLost() private void SelfConsume() { - if (this.ownerEquipment != null && !this.ownerEquipment.Destroyed) + if (base.ownerEquipment != null && !base.ownerEquipment.Destroyed) { - this.ownerEquipment.Destroy(DestroyMode.Vanish); + base.ownerEquipment.Destroy(DestroyMode.Vanish); } } } diff --git a/Assembly-CSharp/RimWorld/VersionControl.cs b/Assembly-CSharp/RimWorld/VersionControl.cs index 4c276f63f..278745b66 100644 --- a/Assembly-CSharp/RimWorld/VersionControl.cs +++ b/Assembly-CSharp/RimWorld/VersionControl.cs @@ -83,59 +83,33 @@ public static DateTime CurrentBuildDate static VersionControl() { Version version = Assembly.GetExecutingAssembly().GetName().Version; - DateTime dateTime = new DateTime(2000, 1, 1); - VersionControl.buildDate = dateTime.AddDays((double)version.Build); + VersionControl.buildDate = new DateTime(2000, 1, 1).AddDays((double)version.Build); int build = version.Build - 4805; int revision = version.Revision * 2 / 60; VersionControl.version = new Version(version.Major, version.Minor, build, revision); - VersionControl.versionStringWithRev = string.Concat(new object[] - { - VersionControl.version.Major, - ".", - VersionControl.version.Minor, - ".", - VersionControl.version.Build, - " rev", - VersionControl.version.Revision - }); - VersionControl.versionString = string.Concat(new object[] - { - VersionControl.version.Major, - ".", - VersionControl.version.Minor, - ".", - VersionControl.version.Build - }); + VersionControl.versionStringWithRev = VersionControl.version.Major + "." + VersionControl.version.Minor + "." + VersionControl.version.Build + " rev" + VersionControl.version.Revision; + VersionControl.versionString = VersionControl.version.Major + "." + VersionControl.version.Minor + "." + VersionControl.version.Build; } public static void DrawInfoInCorner() { Text.Font = GameFont.Small; GUI.color = new Color(1f, 1f, 1f, 0.5f); - string text = "VersionIndicator".Translate(new object[] - { - VersionControl.versionString - }); + string str = "VersionIndicator".Translate(VersionControl.versionString); if (UnityData.isDebugBuild) { - text = text + " (" + "DevelopmentBuildLower".Translate() + ")"; + str = str + " (" + "DevelopmentBuildLower".Translate() + ")"; } - text = text + "\n" + "CompiledOn".Translate(new object[] - { - VersionControl.buildDate.ToString("MMM d yyyy") - }); + str = str + "\n" + "CompiledOn".Translate(VersionControl.buildDate.ToString("MMM d yyyy")); if (SteamManager.Initialized) { - text = text + "\n" + "LoggedIntoSteamAs".Translate(new object[] - { - SteamUtility.SteamPersonaName - }); + str = str + "\n" + "LoggedIntoSteamAs".Translate(SteamUtility.SteamPersonaName); } - Rect rect = new Rect(10f, 10f, 330f, Text.CalcHeight(text, 330f)); - Widgets.Label(rect, text); + Rect rect = new Rect(10f, 10f, 330f, Text.CalcHeight(str, 330f)); + Widgets.Label(rect, str); GUI.color = Color.white; LatestVersionGetter component = Current.Root.gameObject.GetComponent(); - Rect rect2 = new Rect(10f, rect.yMax - 5f, 330f, 999f); + Rect rect2 = new Rect(10f, (float)(rect.yMax - 5.0), 330f, 999f); component.DrawAt(rect2); } @@ -146,17 +120,14 @@ public static void LogVersionNumber() public static bool IsWellFormattedVersionString(string str) { - string[] array = str.Split(new char[] - { - '.' - }); + string[] array = str.Split('.'); if (array.Length != 3) { return false; } for (int i = 0; i < 3; i++) { - int num; + int num = default(int); if (!int.TryParse(array[i], out num)) { return false; @@ -173,10 +144,7 @@ public static int BuildFromVersionString(string str) { str = VersionControl.VersionStringWithoutRev(str); int result = 0; - string[] array = str.Split(new char[] - { - '.' - }); + string[] array = str.Split('.'); if (array.Length < 3 || !int.TryParse(array[2], out result)) { Log.Warning("Could not get build from version string " + str); @@ -188,10 +156,7 @@ public static int MinorFromVersionString(string str) { str = VersionControl.VersionStringWithoutRev(str); int result = 0; - string[] array = str.Split(new char[] - { - '.' - }); + string[] array = str.Split('.'); if (array.Length < 2 || !int.TryParse(array[1], out result)) { Log.Warning("Could not get minor version from version string " + str); @@ -203,10 +168,7 @@ public static int MajorFromVersionString(string str) { str = VersionControl.VersionStringWithoutRev(str); int result = 0; - if (!int.TryParse(str.Split(new char[] - { - '.' - })[0], out result)) + if (!int.TryParse(str.Split('.')[0], out result)) { Log.Warning("Could not get major version from version string " + str); } @@ -215,10 +177,7 @@ public static int MajorFromVersionString(string str) public static string VersionStringWithoutRev(string str) { - return str.Split(new char[] - { - ' ' - })[0]; + return str.Split(' ')[0]; } public static Version VersionFromString(string str) @@ -227,10 +186,7 @@ public static Version VersionFromString(string str) { throw new ArgumentException("str"); } - string[] array = str.Split(new char[] - { - '.' - }); + string[] array = str.Split('.'); if (array.Length > 3) { throw new ArgumentException("str"); @@ -240,7 +196,7 @@ public static Version VersionFromString(string str) int build = 0; for (int i = 0; i < 3; i++) { - int num; + int num = default(int); if (!int.TryParse(array[i], out num)) { throw new ArgumentException("str"); @@ -252,15 +208,21 @@ public static Version VersionFromString(string str) switch (i) { case 0: + { major = num; break; + } case 1: + { minor = num; break; + } case 2: + { build = num; break; } + } } return new Version(major, minor, build); } diff --git a/Assembly-CSharp/RimWorld/VersionUpdateDialogMaker.cs b/Assembly-CSharp/RimWorld/VersionUpdateDialogMaker.cs index 1e4d9815b..048cc8ebe 100644 --- a/Assembly-CSharp/RimWorld/VersionUpdateDialogMaker.cs +++ b/Assembly-CSharp/RimWorld/VersionUpdateDialogMaker.cs @@ -9,8 +9,10 @@ public static class VersionUpdateDialogMaker public static void CreateVersionUpdateDialogIfNecessary() { - if (!VersionUpdateDialogMaker.dialogDone && LastPlayedVersion.Version != null && (VersionControl.CurrentMajor != LastPlayedVersion.Version.Major || VersionControl.CurrentMinor != LastPlayedVersion.Version.Minor)) + if (!VersionUpdateDialogMaker.dialogDone && LastPlayedVersion.Version != (Version)null) { + if (VersionControl.CurrentMajor == LastPlayedVersion.Version.Major && VersionControl.CurrentMinor == LastPlayedVersion.Version.Minor) + return; VersionUpdateDialogMaker.CreateNewVersionDialog(); } } @@ -19,23 +21,12 @@ private static void CreateNewVersionDialog() { string text = LastPlayedVersion.Version.Major + "." + LastPlayedVersion.Version.Minor; string text2 = VersionControl.CurrentMajor + "." + VersionControl.CurrentMinor; - string text3 = "GameUpdatedToNewVersionInitial".Translate(new object[] - { - text, - text2 - }); - text3 += "\n\n"; - if (BackCompatibility.IsSaveCompatibleWith(LastPlayedVersion.Version.ToString())) - { - text3 += "GameUpdatedToNewVersionSavesCompatible".Translate(); - } - else - { - text3 += "GameUpdatedToNewVersionSavesIncompatible".Translate(); - } - text3 += "\n\n"; - text3 += "GameUpdatedToNewVersionSteam".Translate(); - Find.WindowStack.Add(new Dialog_MessageBox(text3, null, null, null, null, null, false)); + string str = "GameUpdatedToNewVersionInitial".Translate(text, text2); + str += "\n\n"; + str = ((!BackCompatibility.IsSaveCompatibleWith(LastPlayedVersion.Version.ToString())) ? (str + "GameUpdatedToNewVersionSavesIncompatible".Translate()) : (str + "GameUpdatedToNewVersionSavesCompatible".Translate())); + str += "\n\n"; + str += "GameUpdatedToNewVersionSteam".Translate(); + Find.WindowStack.Add(new Dialog_MessageBox(str, (string)null, null, (string)null, null, (string)null, false)); VersionUpdateDialogMaker.dialogDone = true; } } diff --git a/Assembly-CSharp/RimWorld/VoluntarilyJoinableLordJobJoinPriorities.cs b/Assembly-CSharp/RimWorld/VoluntarilyJoinableLordJobJoinPriorities.cs index 10706554e..3919d2119 100644 --- a/Assembly-CSharp/RimWorld/VoluntarilyJoinableLordJobJoinPriorities.cs +++ b/Assembly-CSharp/RimWorld/VoluntarilyJoinableLordJobJoinPriorities.cs @@ -1,5 +1,3 @@ -using System; - namespace RimWorld { public static class VoluntarilyJoinableLordJobJoinPriorities diff --git a/Assembly-CSharp/RimWorld/VoluntarilyJoinableLordsStarter.cs b/Assembly-CSharp/RimWorld/VoluntarilyJoinableLordsStarter.cs index fab46ce05..b7fe413e4 100644 --- a/Assembly-CSharp/RimWorld/VoluntarilyJoinableLordsStarter.cs +++ b/Assembly-CSharp/RimWorld/VoluntarilyJoinableLordsStarter.cs @@ -1,4 +1,3 @@ -using System; using Verse; using Verse.AI.Group; @@ -23,17 +22,13 @@ public VoluntarilyJoinableLordsStarter(Map map) public bool TryStartMarriageCeremony(Pawn firstFiance, Pawn secondFiance) { - IntVec3 intVec; + IntVec3 intVec = default(IntVec3); if (!RCellFinder.TryFindMarriageSite(firstFiance, secondFiance, out intVec)) { return false; } LordMaker.MakeNewLord(firstFiance.Faction, new LordJob_Joinable_MarriageCeremony(firstFiance, secondFiance, intVec), this.map, null); - Messages.Message("MessageNewMarriageCeremony".Translate(new object[] - { - firstFiance.LabelShort, - secondFiance.LabelShort - }), new TargetInfo(intVec, this.map, false), MessageSound.Standard); + Messages.Message("MessageNewMarriageCeremony".Translate(firstFiance.LabelShort, secondFiance.LabelShort), new TargetInfo(intVec, this.map, false), MessageSound.Standard); this.lastLordStartTick = Find.TickManager.TicksGame; return true; } @@ -45,16 +40,13 @@ public bool TryStartParty() { return false; } - IntVec3 intVec; + IntVec3 intVec = default(IntVec3); if (!RCellFinder.TryFindPartySpot(pawn, out intVec)) { return false; } LordMaker.MakeNewLord(pawn.Faction, new LordJob_Joinable_Party(intVec), this.map, null); - Find.LetterStack.ReceiveLetter("LetterLabelNewParty".Translate(), "LetterNewParty".Translate(new object[] - { - pawn.LabelShort - }), LetterDefOf.Good, new TargetInfo(intVec, this.map, false), null); + Find.LetterStack.ReceiveLetter("LetterLabelNewParty".Translate(), "LetterNewParty".Translate(pawn.LabelShort), LetterDefOf.Good, new TargetInfo(intVec, this.map, false), (string)null); this.lastLordStartTick = Find.TickManager.TicksGame; this.startPartyASAP = false; return true; @@ -73,11 +65,7 @@ public void ExposeData() private void Tick_TryStartParty() { - if (!this.map.IsPlayerHome) - { - return; - } - if (Find.TickManager.TicksGame % 5000 == 0) + if (this.map.IsPlayerHome && Find.TickManager.TicksGame % 5000 == 0) { if (Rand.MTBEventOccurs(40f, 60000f, 5000f)) { diff --git a/Assembly-CSharp/RimWorld/WalkPathFinder.cs b/Assembly-CSharp/RimWorld/WalkPathFinder.cs index d40c11cb1..d6d526965 100644 --- a/Assembly-CSharp/RimWorld/WalkPathFinder.cs +++ b/Assembly-CSharp/RimWorld/WalkPathFinder.cs @@ -1,4 +1,3 @@ -using System; using System.Collections.Generic; using System.Linq; using UnityEngine; @@ -29,52 +28,52 @@ public static bool TryFindWalkPath(Pawn pawn, IntVec3 root, out List re { IntVec3 intVec2 = IntVec3.Invalid; float num = -1f; - for (int j = WalkPathFinder.StartRadialIndex; j > WalkPathFinder.EndRadialIndex; j -= WalkPathFinder.RadialIndexStride) + for (int num2 = WalkPathFinder.StartRadialIndex; num2 > WalkPathFinder.EndRadialIndex; num2 -= WalkPathFinder.RadialIndexStride) { - IntVec3 intVec3 = intVec + GenRadial.RadialPattern[j]; + IntVec3 intVec3 = intVec + GenRadial.RadialPattern[num2]; if (intVec3.InBounds(pawn.Map) && intVec3.Standable(pawn.Map) && !intVec3.IsForbidden(pawn) && GenSight.LineOfSight(intVec, intVec3, pawn.Map, false, null, 0, 0) && !intVec3.Roofed(pawn.Map) && !PawnUtility.KnownDangerAt(intVec3, pawn)) { - float num2 = 10000f; - for (int k = 0; k < list.Count; k++) + float num3 = 10000f; + for (int j = 0; j < list.Count; j++) { - num2 += (float)(list[k] - intVec3).LengthManhattan; + num3 += (float)(list[j] - intVec3).LengthManhattan; } - float num3 = (float)(intVec3 - root).LengthManhattan; - if (num3 > 40f) + float num4 = (float)(intVec3 - root).LengthManhattan; + if (num4 > 40.0) { - num2 *= Mathf.InverseLerp(70f, 40f, num3); + num3 *= Mathf.InverseLerp(70f, 40f, num4); } if (list.Count >= 2) { - float num4 = (list[list.Count - 1] - list[list.Count - 2]).AngleFlat; - float angleFlat = (intVec3 - intVec).AngleFlat; + float angleFlat = (list[list.Count - 1] - list[list.Count - 2]).AngleFlat; + float angleFlat2 = (intVec3 - intVec).AngleFlat; float num5; - if (angleFlat > num4) + if (angleFlat2 > angleFlat) { - num5 = angleFlat - num4; + num5 = angleFlat2 - angleFlat; } else { - num4 -= 360f; - num5 = angleFlat - num4; + angleFlat = (float)(angleFlat - 360.0); + num5 = angleFlat2 - angleFlat; } - if (num5 > 110f) + if (num5 > 110.0) { - num2 *= 0.01f; + num3 = (float)(num3 * 0.0099999997764825821); } } if (list.Count >= 4 && (intVec - root).LengthManhattan < (intVec3 - root).LengthManhattan) { - num2 *= 1E-05f; + num3 = (float)(num3 * 9.9999997473787516E-06); } - if (num2 > num) + if (num3 > num) { intVec2 = intVec3; - num = num2; + num = num3; } } } - if (num < 0f) + if (num < 0.0) { result = null; return false; @@ -90,18 +89,20 @@ public static bool TryFindWalkPath(Pawn pawn, IntVec3 root, out List re public static void DebugFlashWalkPath(IntVec3 root, int numEntries = 8) { Map visibleMap = Find.VisibleMap; - List list; - if (!WalkPathFinder.TryFindWalkPath(visibleMap.mapPawns.FreeColonistsSpawned.First(), root, out list)) + List list = default(List); + if (!WalkPathFinder.TryFindWalkPath(visibleMap.mapPawns.FreeColonistsSpawned.First(), root, out list)) { visibleMap.debugDrawer.FlashCell(root, 0.2f, "NOPATH"); - return; } - for (int i = 0; i < list.Count; i++) + else { - visibleMap.debugDrawer.FlashCell(list[i], (float)i / (float)numEntries, i.ToString()); - if (i > 0) + for (int i = 0; i < list.Count; i++) { - visibleMap.debugDrawer.FlashLine(list[i], list[i - 1]); + visibleMap.debugDrawer.FlashCell(list[i], (float)i / (float)numEntries, i.ToString()); + if (i > 0) + { + visibleMap.debugDrawer.FlashLine(list[i], list[i - 1]); + } } } } diff --git a/Assembly-CSharp/RimWorld/WardenFeedUtility.cs b/Assembly-CSharp/RimWorld/WardenFeedUtility.cs index 844d73eea..72ca990e2 100644 --- a/Assembly-CSharp/RimWorld/WardenFeedUtility.cs +++ b/Assembly-CSharp/RimWorld/WardenFeedUtility.cs @@ -1,4 +1,3 @@ -using System; using Verse; namespace RimWorld @@ -7,7 +6,23 @@ public static class WardenFeedUtility { public static bool ShouldBeFed(Pawn p) { - return p.IsPrisonerOfColony && p.InBed() && p.guest.CanBeBroughtFood && HealthAIUtility.ShouldSeekMedicalRest(p); + if (!p.IsPrisonerOfColony) + { + return false; + } + if (!p.InBed()) + { + return false; + } + if (!p.guest.CanBeBroughtFood) + { + return false; + } + if (!HealthAIUtility.ShouldSeekMedicalRest(p)) + { + return false; + } + return true; } } } diff --git a/Assembly-CSharp/RimWorld/WatchBuildingUtility.cs b/Assembly-CSharp/RimWorld/WatchBuildingUtility.cs index 3dd52b123..a95e68740 100644 --- a/Assembly-CSharp/RimWorld/WatchBuildingUtility.cs +++ b/Assembly-CSharp/RimWorld/WatchBuildingUtility.cs @@ -1,6 +1,4 @@ -using System; using System.Collections.Generic; -using System.Diagnostics; using UnityEngine; using Verse; using Verse.AI; @@ -11,21 +9,19 @@ public static class WatchBuildingUtility { private static List allowedDirections = new List(); - [DebuggerHidden] public static IEnumerable CalculateWatchCells(ThingDef def, IntVec3 center, Rot4 rot, Map map) { - WatchBuildingUtility.c__Iterator57 c__Iterator = new WatchBuildingUtility.c__Iterator57(); - c__Iterator.def = def; - c__Iterator.rot = rot; - c__Iterator.center = center; - c__Iterator.map = map; - c__Iterator.<$>def = def; - c__Iterator.<$>rot = rot; - c__Iterator.<$>center = center; - c__Iterator.<$>map = map; - WatchBuildingUtility.c__Iterator57 expr_3F = c__Iterator; - expr_3F.$PC = -2; - return expr_3F; + List allowedDirections = WatchBuildingUtility.CalculateAllowedDirections(def, rot); + for (int i = 0; i < allowedDirections.Count; i++) + { + foreach (IntVec3 item in WatchBuildingUtility.GetWatchCellRect(def, center, rot, allowedDirections[i])) + { + if (WatchBuildingUtility.EverPossibleToWatchFrom(item, center, map, true)) + { + yield return item; + } + } + } } public static bool TryFindBestWatchCell(Thing toWatch, Pawn pawn, bool desireSit, out IntVec3 result, out Building chair) @@ -37,9 +33,9 @@ public static bool TryFindBestWatchCell(Thing toWatch, Pawn pawn, bool desireSit CellRect watchCellRect = WatchBuildingUtility.GetWatchCellRect(toWatch.def, toWatch.Position, toWatch.Rotation, list[i]); IntVec3 centerCell = watchCellRect.CenterCell; int num = watchCellRect.Area * 4; - for (int j = 0; j < num; j++) + for (int num2 = 0; num2 < num; num2++) { - IntVec3 intVec2 = centerCell + GenRadial.RadialPattern[j]; + IntVec3 intVec2 = centerCell + GenRadial.RadialPattern[num2]; if (watchCellRect.Contains(intVec2)) { bool flag = false; @@ -49,7 +45,7 @@ public static bool TryFindBestWatchCell(Thing toWatch, Pawn pawn, bool desireSit if (desireSit) { building = intVec2.GetEdifice(pawn.Map); - if (building != null && building.def.building.isSittable && pawn.CanReserve(building, 1, -1, null, false)) + if (building != null && building.def.building.isSittable && pawn.CanReserve((Thing)building, 1, -1, null, false)) { flag = true; } @@ -61,22 +57,15 @@ public static bool TryFindBestWatchCell(Thing toWatch, Pawn pawn, bool desireSit } if (flag) { - if (desireSit) + if (!desireSit || !(building.Rotation != new Rot4(list[i]).Opposite)) { - Rot4 arg_15D_0 = building.Rotation; - Rot4 rot = new Rot4(list[i]); - if (arg_15D_0 != rot.Opposite) - { - intVec = intVec2; - goto IL_17E; - } + result = intVec2; + chair = building; + return true; } - result = intVec2; - chair = building; - return true; + intVec = intVec2; } } - IL_17E:; } } if (intVec.IsValid) @@ -100,21 +89,41 @@ public static bool CanWatchFromBed(Pawn pawn, Building_Bed bed, Thing toWatch) { Rot4 rotation = bed.Rotation; CellRect cellRect = toWatch.OccupiedRect(); - if (rotation == Rot4.North && cellRect.maxZ < pawn.Position.z) + if (rotation == Rot4.North) { - return false; + int maxZ = cellRect.maxZ; + IntVec3 position = pawn.Position; + if (maxZ < position.z) + { + return false; + } } - if (rotation == Rot4.South && cellRect.minZ > pawn.Position.z) + if (rotation == Rot4.South) { - return false; + int minZ = cellRect.minZ; + IntVec3 position2 = pawn.Position; + if (minZ > position2.z) + { + return false; + } } - if (rotation == Rot4.East && cellRect.maxX < pawn.Position.x) + if (rotation == Rot4.East) { - return false; + int maxX = cellRect.maxX; + IntVec3 position3 = pawn.Position; + if (maxX < position3.x) + { + return false; + } } - if (rotation == Rot4.West && cellRect.minX > pawn.Position.x) + if (rotation == Rot4.West) { - return false; + int minX = cellRect.minX; + IntVec3 position4 = pawn.Position; + if (minX > position4.x) + { + return false; + } } } List list = WatchBuildingUtility.CalculateAllowedDirections(toWatch.def, toWatch.Rotation); diff --git a/Assembly-CSharp/RimWorld/WaterSplash.cs b/Assembly-CSharp/RimWorld/WaterSplash.cs index 0c73959ba..66becc91a 100644 --- a/Assembly-CSharp/RimWorld/WaterSplash.cs +++ b/Assembly-CSharp/RimWorld/WaterSplash.cs @@ -10,16 +10,25 @@ protected override void Impact(Thing hitThing) { base.Impact(hitThing); List list = new List(); - foreach (Thing current in base.Map.thingGrid.ThingsAt(base.Position)) + foreach (Thing item in base.Map.thingGrid.ThingsAt(base.Position)) { - if (current.def == ThingDefOf.Fire) + if (item.def == ThingDefOf.Fire) { - list.Add(current); + list.Add(item); } } - foreach (Thing current2 in list) + List.Enumerator enumerator2 = list.GetEnumerator(); + try { - current2.Destroy(DestroyMode.Vanish); + while (enumerator2.MoveNext()) + { + Thing current2 = enumerator2.Current; + current2.Destroy(DestroyMode.Vanish); + } + } + finally + { + ((IDisposable)(object)enumerator2).Dispose(); } } } diff --git a/Assembly-CSharp/RimWorld/WealthWatcher.cs b/Assembly-CSharp/RimWorld/WealthWatcher.cs index 975ddb0c3..e5ab3feca 100644 --- a/Assembly-CSharp/RimWorld/WealthWatcher.cs +++ b/Assembly-CSharp/RimWorld/WealthWatcher.cs @@ -62,7 +62,7 @@ public WealthWatcher(Map map) private void RecountIfNeeded() { - if ((float)Find.TickManager.TicksGame - this.lastCountTick > 5000f) + if ((float)Find.TickManager.TicksGame - this.lastCountTick > 5000.0) { this.ForceRecount(false); } @@ -73,64 +73,80 @@ public void ForceRecount(bool allowDuringInit = false) if (!allowDuringInit && Current.ProgramState != ProgramState.Playing) { Log.Error("WealthWatcher recount in game mode " + Current.ProgramState); - return; } - this.wealthItems = 0f; - this.wealthBuildings = 0f; - this.totalHealth = 0; - List list = this.map.listerThings.ThingsInGroup(ThingRequestGroup.HaulableAlways); - for (int i = 0; i < list.Count; i++) + else { - Thing thing = list[i]; - if (!thing.Position.Fogged(thing.Map)) + this.wealthItems = 0f; + this.wealthBuildings = 0f; + this.totalHealth = 0; + List list = this.map.listerThings.ThingsInGroup(ThingRequestGroup.HaulableAlways); + for (int i = 0; i < list.Count; i++) { - this.wealthItems += (float)thing.stackCount * thing.MarketValue; + Thing thing = list[i]; + if (!thing.Position.Fogged(thing.Map)) + { + this.wealthItems += (float)thing.stackCount * thing.MarketValue; + } } - } - foreach (Pawn current in this.map.mapPawns.FreeColonists) - { - if (current.equipment != null) + foreach (Pawn freeColonist in this.map.mapPawns.FreeColonists) { - foreach (ThingWithComps current2 in current.equipment.AllEquipmentListForReading) + if (freeColonist.equipment != null) { - this.wealthItems += current2.MarketValue; + List.Enumerator enumerator2 = freeColonist.equipment.AllEquipmentListForReading.GetEnumerator(); + try + { + while (enumerator2.MoveNext()) + { + ThingWithComps current2 = enumerator2.Current; + this.wealthItems += current2.MarketValue; + } + } + finally + { + ((IDisposable)(object)enumerator2).Dispose(); + } + } + if (freeColonist.apparel != null) + { + List wornApparel = freeColonist.apparel.WornApparel; + for (int j = 0; j < wornApparel.Count; j++) + { + this.wealthItems += wornApparel[j].MarketValue; + } } } - if (current.apparel != null) + List.Enumerator enumerator3 = this.map.listerThings.ThingsInGroup(ThingRequestGroup.BuildingFrame).GetEnumerator(); + try { - List wornApparel = current.apparel.WornApparel; - for (int j = 0; j < wornApparel.Count; j++) + while (enumerator3.MoveNext()) { - this.wealthItems += wornApparel[j].MarketValue; + Frame frame = (Frame)enumerator3.Current; + foreach (Thing item in (IEnumerable)frame.resourceContainer) + { + this.wealthItems += (float)item.stackCount * item.MarketValue; + } } } - } - using (List.Enumerator enumerator3 = this.map.listerThings.ThingsInGroup(ThingRequestGroup.BuildingFrame).GetEnumerator()) - { - while (enumerator3.MoveNext()) + finally + { + ((IDisposable)(object)enumerator3).Dispose(); + } + List list2 = this.map.listerThings.ThingsInGroup(ThingRequestGroup.BuildingArtificial); + for (int k = 0; k < list2.Count; k++) { - Frame frame = (Frame)enumerator3.Current; - foreach (Thing current3 in ((IEnumerable)frame.resourceContainer)) + Thing thing2 = list2[k]; + if (thing2.Faction == Faction.OfPlayer) { - this.wealthItems += (float)current3.stackCount * current3.MarketValue; + this.wealthBuildings += thing2.MarketValue; + this.totalHealth += thing2.HitPoints; } } - } - List list2 = this.map.listerThings.ThingsInGroup(ThingRequestGroup.BuildingArtificial); - for (int k = 0; k < list2.Count; k++) - { - Thing thing2 = list2[k]; - if (thing2.Faction == Faction.OfPlayer) + foreach (Pawn freeColonist2 in this.map.mapPawns.FreeColonists) { - this.wealthBuildings += thing2.MarketValue; - this.totalHealth += thing2.HitPoints; + this.totalHealth += Mathf.RoundToInt((float)(freeColonist2.health.summaryHealth.SummaryHealthPercent * 100.0)); } + this.lastCountTick = (float)Find.TickManager.TicksGame; } - foreach (Pawn current4 in this.map.mapPawns.FreeColonists) - { - this.totalHealth += Mathf.RoundToInt(current4.health.summaryHealth.SummaryHealthPercent * 100f); - } - this.lastCountTick = (float)Find.TickManager.TicksGame; } } } diff --git a/Assembly-CSharp/RimWorld/WeatherCommonalityRecord.cs b/Assembly-CSharp/RimWorld/WeatherCommonalityRecord.cs index 11cd3d8f3..966e674fc 100644 --- a/Assembly-CSharp/RimWorld/WeatherCommonalityRecord.cs +++ b/Assembly-CSharp/RimWorld/WeatherCommonalityRecord.cs @@ -1,4 +1,3 @@ -using System; using System.Xml; using Verse; diff --git a/Assembly-CSharp/RimWorld/WeatherDecider.cs b/Assembly-CSharp/RimWorld/WeatherDecider.cs index 75861231f..851854a96 100644 --- a/Assembly-CSharp/RimWorld/WeatherDecider.cs +++ b/Assembly-CSharp/RimWorld/WeatherDecider.cs @@ -29,10 +29,9 @@ public void ExposeData() public void WeatherDeciderTick() { int num = this.curWeatherDuration; - bool flag = this.map.fireWatcher.LargeFireDangerPresent || !this.map.weatherManager.curWeather.temperatureRange.Includes(this.map.mapTemperature.OutdoorTemp); - if (flag) + if (this.map.fireWatcher.LargeFireDangerPresent || !this.map.weatherManager.curWeather.temperatureRange.Includes(this.map.mapTemperature.OutdoorTemp)) { - num = (int)((float)num * 0.25f); + num = (int)((float)num * 0.25); } if (this.map.weatherManager.curWeatherAge > num) { @@ -53,8 +52,8 @@ private WeatherDef ChooseNextWeather() { return WeatherDefOf.Clear; } - WeatherDef result; - if (!DefDatabase.AllDefs.TryRandomElementByWeight((WeatherDef w) => this.CurrentWeatherCommonality(w), out result)) + WeatherDef result = default(WeatherDef); + if (!DefDatabase.AllDefs.TryRandomElementByWeight((Func)((WeatherDef w) => this.CurrentWeatherCommonality(w)), out result)) { Log.Warning("All weather commonalities were zero. Defaulting to " + WeatherDefOf.Clear.defName + "."); return WeatherDefOf.Clear; @@ -77,20 +76,17 @@ private float CurrentWeatherCommonality(WeatherDef weather) { return 0f; } - if (weather.favorability < Favorability.Neutral && GenDate.DaysPassed < 8) + if ((int)weather.favorability < 2 && GenDate.DaysPassed < 8) { return 0f; } - if (weather.rainRate > 0.1f && Find.TickManager.TicksGame < this.ticksWhenRainAllowedAgain) + if (weather.rainRate > 0.10000000149011612 && Find.TickManager.TicksGame < this.ticksWhenRainAllowedAgain) { return 0f; } - if (weather.rainRate > 0.1f) + if (weather.rainRate > 0.10000000149011612 && this.map.gameConditionManager.ActiveConditions.Any((Predicate)((GameCondition x) => x.def.preventRain))) { - if (this.map.gameConditionManager.ActiveConditions.Any((GameCondition x) => x.def.preventRain)) - { - return 0f; - } + return 0f; } BiomeDef biome = this.map.Biome; for (int i = 0; i < biome.baseWeatherCommonalities.Count; i++) @@ -99,9 +95,9 @@ private float CurrentWeatherCommonality(WeatherDef weather) if (weatherCommonalityRecord.weather == weather) { float num = weatherCommonalityRecord.commonality; - if (this.map.fireWatcher.LargeFireDangerPresent && weather.rainRate > 0.1f) + if (this.map.fireWatcher.LargeFireDangerPresent && weather.rainRate > 0.10000000149011612) { - num *= 20f; + num = (float)(num * 20.0); } if (weatherCommonalityRecord.weather.commonalityRainfallFactor != null) { @@ -116,11 +112,11 @@ private float CurrentWeatherCommonality(WeatherDef weather) public void LogWeatherChances() { StringBuilder stringBuilder = new StringBuilder(); - foreach (WeatherDef current in from w in DefDatabase.AllDefs + foreach (WeatherDef item in from w in DefDatabase.AllDefs orderby this.CurrentWeatherCommonality(w) descending select w) { - stringBuilder.AppendLine(current.label + " - " + this.CurrentWeatherCommonality(current).ToString()); + stringBuilder.AppendLine(item.label + " - " + this.CurrentWeatherCommonality(item).ToString()); } Log.Message(stringBuilder.ToString()); } diff --git a/Assembly-CSharp/RimWorld/WeatherDefOf.cs b/Assembly-CSharp/RimWorld/WeatherDefOf.cs index bc736e41c..c272a33bc 100644 --- a/Assembly-CSharp/RimWorld/WeatherDefOf.cs +++ b/Assembly-CSharp/RimWorld/WeatherDefOf.cs @@ -1,4 +1,3 @@ -using System; using Verse; namespace RimWorld diff --git a/Assembly-CSharp/RimWorld/WeatherEvent_LightningFlash.cs b/Assembly-CSharp/RimWorld/WeatherEvent_LightningFlash.cs index f6ebd11de..b923858c8 100644 --- a/Assembly-CSharp/RimWorld/WeatherEvent_LightningFlash.cs +++ b/Assembly-CSharp/RimWorld/WeatherEvent_LightningFlash.cs @@ -1,4 +1,3 @@ -using System; using UnityEngine; using Verse; using Verse.Sound; @@ -61,9 +60,9 @@ protected float LightningBrightness { if (this.age <= 3) { - return (float)this.age / 3f; + return (float)((float)this.age / 3.0); } - return 1f - (float)this.age / (float)this.duration; + return (float)(1.0 - (float)this.age / (float)this.duration); } } @@ -75,7 +74,7 @@ public WeatherEvent_LightningFlash(Map map) : base(map) public override void FireEvent() { - SoundDefOf.Thunder_OffMap.PlayOneShotOnCamera(this.map); + SoundDefOf.Thunder_OffMap.PlayOneShotOnCamera(base.map); } public override void WeatherEventTick() diff --git a/Assembly-CSharp/RimWorld/WeatherEvent_LightningStrike.cs b/Assembly-CSharp/RimWorld/WeatherEvent_LightningStrike.cs index 8e34066ee..ffcc10237 100644 --- a/Assembly-CSharp/RimWorld/WeatherEvent_LightningStrike.cs +++ b/Assembly-CSharp/RimWorld/WeatherEvent_LightningStrike.cs @@ -28,18 +28,18 @@ public override void FireEvent() base.FireEvent(); if (!this.strikeLoc.IsValid) { - this.strikeLoc = CellFinderLoose.RandomCellWith((IntVec3 sq) => sq.Standable(this.map) && !this.map.roofGrid.Roofed(sq), this.map, 1000); + this.strikeLoc = CellFinderLoose.RandomCellWith((Predicate)((IntVec3 sq) => sq.Standable(base.map) && !base.map.roofGrid.Roofed(sq)), base.map, 1000); } this.boltMesh = LightningBoltMeshPool.RandomBoltMesh; - GenExplosion.DoExplosion(this.strikeLoc, this.map, 1.9f, DamageDefOf.Flame, null, null, null, null, null, 0f, 1, false, null, 0f, 1); + GenExplosion.DoExplosion(this.strikeLoc, base.map, 1.9f, DamageDefOf.Flame, null, null, null, null, null, 0f, 1, false, null, 0f, 1); Vector3 loc = this.strikeLoc.ToVector3Shifted(); for (int i = 0; i < 4; i++) { - MoteMaker.ThrowSmoke(loc, this.map, 1.5f); - MoteMaker.ThrowMicroSparks(loc, this.map); - MoteMaker.ThrowLightningGlow(loc, this.map, 1.5f); + MoteMaker.ThrowSmoke(loc, base.map, 1.5f); + MoteMaker.ThrowMicroSparks(loc, base.map); + MoteMaker.ThrowLightningGlow(loc, base.map, 1.5f); } - SoundInfo info = SoundInfo.InMap(new TargetInfo(this.strikeLoc, this.map, false), MaintenanceType.None); + SoundInfo info = SoundInfo.InMap(new TargetInfo(this.strikeLoc, base.map, false), MaintenanceType.None); SoundDefOf.Thunder_OnMap.PlayOneShot(info); } diff --git a/Assembly-CSharp/RimWorld/WeatherManager.cs b/Assembly-CSharp/RimWorld/WeatherManager.cs index 4a3517d35..24045644d 100644 --- a/Assembly-CSharp/RimWorld/WeatherManager.cs +++ b/Assembly-CSharp/RimWorld/WeatherManager.cs @@ -1,4 +1,3 @@ -using System; using System.Collections.Generic; using UnityEngine; using Verse; @@ -28,8 +27,8 @@ public float TransitionLerpFactor { get { - float num = (float)this.curWeatherAge / 4000f; - if (num > 1f) + float num = (float)((float)this.curWeatherAge / 4000.0); + if (num > 1.0) { num = 1f; } @@ -88,7 +87,7 @@ public void ExposeData() Scribe_Defs.Look(ref this.curWeather, "curWeather"); Scribe_Defs.Look(ref this.lastWeather, "lastWeather"); Scribe_Values.Look(ref this.curWeatherAge, "curWeatherAge", 0, true); - Scribe_Deep.Look(ref this.growthSeasonMemory, "growthSeasonMemory", new object[] + Scribe_Deep.Look(ref this.growthSeasonMemory, "growthSeasonMemory", new object[1] { this.map }); @@ -124,20 +123,23 @@ public void WeatherManagerTick() this.eventHandler.WeatherEventHandlerTick(); this.curWeatherAge++; this.curWeather.Worker.WeatherTick(this.map, this.TransitionLerpFactor); - this.lastWeather.Worker.WeatherTick(this.map, 1f - this.TransitionLerpFactor); + this.lastWeather.Worker.WeatherTick(this.map, (float)(1.0 - this.TransitionLerpFactor)); this.growthSeasonMemory.GrowthSeasonMemoryTick(); for (int i = 0; i < this.curWeather.ambientSounds.Count; i++) { bool flag = false; - for (int j = this.ambienceSustainers.Count - 1; j >= 0; j--) + int num = this.ambienceSustainers.Count - 1; + while (num >= 0) { - if (this.ambienceSustainers[j].def == this.curWeather.ambientSounds[i]) + if (this.ambienceSustainers[num].def != this.curWeather.ambientSounds[i]) { - flag = true; - break; + num--; + continue; } + flag = true; + break; } - if (!flag && this.VolumeOfAmbientSound(this.curWeather.ambientSounds[i]) > 0.0001f) + if (!flag && this.VolumeOfAmbientSound(this.curWeather.ambientSounds[i]) > 9.9999997473787516E-05) { SoundInfo info = SoundInfo.OnCamera(MaintenanceType.None); Sustainer sustainer = this.curWeather.ambientSounds[i].TrySpawnSustainer(info); @@ -165,17 +167,17 @@ public void EndAllSustainers() private void SetAmbienceSustainersVolume() { - for (int i = this.ambienceSustainers.Count - 1; i >= 0; i--) + for (int num = this.ambienceSustainers.Count - 1; num >= 0; num--) { - float num = this.VolumeOfAmbientSound(this.ambienceSustainers[i].def); - if (num > 0.0001f) + float num2 = this.VolumeOfAmbientSound(this.ambienceSustainers[num].def); + if (num2 > 9.9999997473787516E-05) { - this.ambienceSustainers[i].externalParams["LerpFactor"] = num; + this.ambienceSustainers[num].externalParams["LerpFactor"] = num2; } else { - this.ambienceSustainers[i].End(); - this.ambienceSustainers.RemoveAt(i); + this.ambienceSustainers[num].End(); + this.ambienceSustainers.RemoveAt(num); } } } @@ -198,7 +200,7 @@ private float VolumeOfAmbientSound(SoundDef soundDef) { if (this.lastWeather.ambientSounds[j] == soundDef) { - num += 1f - this.TransitionLerpFactor; + num = (float)(num + (1.0 - this.TransitionLerpFactor)); } } for (int k = 0; k < this.curWeather.ambientSounds.Count; k++) diff --git a/Assembly-CSharp/RimWorld/WeatherOverlay_Fallout.cs b/Assembly-CSharp/RimWorld/WeatherOverlay_Fallout.cs index 2c980bdd9..f9421c478 100644 --- a/Assembly-CSharp/RimWorld/WeatherOverlay_Fallout.cs +++ b/Assembly-CSharp/RimWorld/WeatherOverlay_Fallout.cs @@ -1,4 +1,3 @@ -using System; using UnityEngine; using Verse; @@ -11,13 +10,13 @@ public class WeatherOverlay_Fallout : SkyOverlay public WeatherOverlay_Fallout() { - this.worldOverlayMat = WeatherOverlay_Fallout.FalloutOverlayWorld; - this.worldOverlayPanSpeed1 = 0.0008f; - this.worldPanDir1 = new Vector2(-0.25f, -1f); - this.worldPanDir1.Normalize(); - this.worldOverlayPanSpeed2 = 0.0012f; - this.worldPanDir2 = new Vector2(-0.24f, -1f); - this.worldPanDir2.Normalize(); + base.worldOverlayMat = WeatherOverlay_Fallout.FalloutOverlayWorld; + base.worldOverlayPanSpeed1 = 0.0008f; + base.worldPanDir1 = new Vector2(-0.25f, -1f); + base.worldPanDir1.Normalize(); + base.worldOverlayPanSpeed2 = 0.0012f; + base.worldPanDir2 = new Vector2(-0.24f, -1f); + base.worldPanDir2.Normalize(); } } } diff --git a/Assembly-CSharp/RimWorld/WeatherOverlay_Fog.cs b/Assembly-CSharp/RimWorld/WeatherOverlay_Fog.cs index 5264f5ab8..f5e299ccc 100644 --- a/Assembly-CSharp/RimWorld/WeatherOverlay_Fog.cs +++ b/Assembly-CSharp/RimWorld/WeatherOverlay_Fog.cs @@ -1,4 +1,3 @@ -using System; using UnityEngine; using Verse; @@ -11,11 +10,11 @@ public class WeatherOverlay_Fog : SkyOverlay public WeatherOverlay_Fog() { - this.worldOverlayMat = WeatherOverlay_Fog.FogOverlayWorld; - this.worldOverlayPanSpeed1 = 0.0005f; - this.worldOverlayPanSpeed2 = 0.0004f; - this.worldPanDir1 = new Vector2(1f, 1f); - this.worldPanDir2 = new Vector2(1f, -1f); + base.worldOverlayMat = WeatherOverlay_Fog.FogOverlayWorld; + base.worldOverlayPanSpeed1 = 0.0005f; + base.worldOverlayPanSpeed2 = 0.0004f; + base.worldPanDir1 = new Vector2(1f, 1f); + base.worldPanDir2 = new Vector2(1f, -1f); } } } diff --git a/Assembly-CSharp/RimWorld/WeatherOverlay_Rain.cs b/Assembly-CSharp/RimWorld/WeatherOverlay_Rain.cs index 0005132a0..2cf2b1058 100644 --- a/Assembly-CSharp/RimWorld/WeatherOverlay_Rain.cs +++ b/Assembly-CSharp/RimWorld/WeatherOverlay_Rain.cs @@ -1,4 +1,3 @@ -using System; using UnityEngine; using Verse; @@ -11,13 +10,13 @@ public class WeatherOverlay_Rain : SkyOverlay public WeatherOverlay_Rain() { - this.worldOverlayMat = WeatherOverlay_Rain.RainOverlayWorld; - this.worldOverlayPanSpeed1 = 0.015f; - this.worldPanDir1 = new Vector2(-0.25f, -1f); - this.worldPanDir1.Normalize(); - this.worldOverlayPanSpeed2 = 0.022f; - this.worldPanDir2 = new Vector2(-0.24f, -1f); - this.worldPanDir2.Normalize(); + base.worldOverlayMat = WeatherOverlay_Rain.RainOverlayWorld; + base.worldOverlayPanSpeed1 = 0.015f; + base.worldPanDir1 = new Vector2(-0.25f, -1f); + base.worldPanDir1.Normalize(); + base.worldOverlayPanSpeed2 = 0.022f; + base.worldPanDir2 = new Vector2(-0.24f, -1f); + base.worldPanDir2.Normalize(); } } } diff --git a/Assembly-CSharp/RimWorld/WeatherOverlay_SnowGentle.cs b/Assembly-CSharp/RimWorld/WeatherOverlay_SnowGentle.cs index 54a8b3e24..3ca7763e8 100644 --- a/Assembly-CSharp/RimWorld/WeatherOverlay_SnowGentle.cs +++ b/Assembly-CSharp/RimWorld/WeatherOverlay_SnowGentle.cs @@ -1,4 +1,3 @@ -using System; using UnityEngine; using Verse; @@ -11,13 +10,13 @@ public class WeatherOverlay_SnowGentle : SkyOverlay public WeatherOverlay_SnowGentle() { - this.worldOverlayMat = WeatherOverlay_SnowGentle.SnowGentleOverlayWorld; - this.worldOverlayPanSpeed1 = 0.002f; - this.worldPanDir1 = new Vector2(-0.25f, -1f); - this.worldPanDir1.Normalize(); - this.worldOverlayPanSpeed2 = 0.003f; - this.worldPanDir2 = new Vector2(-0.24f, -1f); - this.worldPanDir2.Normalize(); + base.worldOverlayMat = WeatherOverlay_SnowGentle.SnowGentleOverlayWorld; + base.worldOverlayPanSpeed1 = 0.002f; + base.worldPanDir1 = new Vector2(-0.25f, -1f); + base.worldPanDir1.Normalize(); + base.worldOverlayPanSpeed2 = 0.003f; + base.worldPanDir2 = new Vector2(-0.24f, -1f); + base.worldPanDir2.Normalize(); } } } diff --git a/Assembly-CSharp/RimWorld/WeatherOverlay_SnowHard.cs b/Assembly-CSharp/RimWorld/WeatherOverlay_SnowHard.cs index 2a1375af6..208c6c2ca 100644 --- a/Assembly-CSharp/RimWorld/WeatherOverlay_SnowHard.cs +++ b/Assembly-CSharp/RimWorld/WeatherOverlay_SnowHard.cs @@ -1,4 +1,3 @@ -using System; using UnityEngine; using Verse; @@ -11,13 +10,13 @@ public class WeatherOverlay_SnowHard : SkyOverlay public WeatherOverlay_SnowHard() { - this.worldOverlayMat = WeatherOverlay_SnowHard.SnowOverlayWorld; - this.worldOverlayPanSpeed1 = 0.008f; - this.worldPanDir1 = new Vector2(-0.5f, -1f); - this.worldPanDir1.Normalize(); - this.worldOverlayPanSpeed2 = 0.009f; - this.worldPanDir2 = new Vector2(-0.48f, -1f); - this.worldPanDir2.Normalize(); + base.worldOverlayMat = WeatherOverlay_SnowHard.SnowOverlayWorld; + base.worldOverlayPanSpeed1 = 0.008f; + base.worldPanDir1 = new Vector2(-0.5f, -1f); + base.worldPanDir1.Normalize(); + base.worldOverlayPanSpeed2 = 0.009f; + base.worldPanDir2 = new Vector2(-0.48f, -1f); + base.worldPanDir2.Normalize(); } } } diff --git a/Assembly-CSharp/RimWorld/WeatherPartPool.cs b/Assembly-CSharp/RimWorld/WeatherPartPool.cs index 7ea22cf4c..afbc1f8a6 100644 --- a/Assembly-CSharp/RimWorld/WeatherPartPool.cs +++ b/Assembly-CSharp/RimWorld/WeatherPartPool.cs @@ -1,4 +1,3 @@ -using System; using System.Collections.Generic; using Verse; @@ -12,13 +11,13 @@ public static SkyOverlay GetInstanceOf() where T : SkyOverlay { for (int i = 0; i < WeatherPartPool.instances.Count; i++) { - T t = WeatherPartPool.instances[i] as T; - if (t != null) + T val = (T)(WeatherPartPool.instances[i] as T); + if (val != null) { - return t; + return (SkyOverlay)(object)val; } } - SkyOverlay skyOverlay = Activator.CreateInstance(); + SkyOverlay skyOverlay = (SkyOverlay)(object)new T(); WeatherPartPool.instances.Add(skyOverlay); return skyOverlay; } diff --git a/Assembly-CSharp/RimWorld/WidgetsWork.cs b/Assembly-CSharp/RimWorld/WidgetsWork.cs index 448deac95..7de427fff 100644 --- a/Assembly-CSharp/RimWorld/WidgetsWork.cs +++ b/Assembly-CSharp/RimWorld/WidgetsWork.cs @@ -1,4 +1,5 @@ using System; +using System.Collections.Generic; using System.Text; using UnityEngine; using Verse; @@ -38,99 +39,108 @@ private static Color ColorOfPriority(int prio) switch (prio) { case 1: + { return new Color(0f, 1f, 0f); + } case 2: + { return new Color(1f, 0.9f, 0.5f); + } case 3: + { return new Color(0.8f, 0.7f, 0.5f); + } case 4: + { return new Color(0.74f, 0.74f, 0.74f); + } default: + { return Color.grey; } + } } public static void DrawWorkBoxFor(float x, float y, Pawn p, WorkTypeDef wType, bool incapableBecauseOfCapacities) { - if (p.story == null || p.story.WorkTypeIsDisabled(wType)) + if (p.story != null && !p.story.WorkTypeIsDisabled(wType)) { - return; - } - Rect rect = new Rect(x, y, 25f, 25f); - if (incapableBecauseOfCapacities) - { - GUI.color = new Color(1f, 0.3f, 0.3f); - } - WidgetsWork.DrawWorkBoxBackground(rect, p, wType); - GUI.color = Color.white; - if (Find.PlaySettings.useWorkPriorities) - { - int priority = p.workSettings.GetPriority(wType); - if (priority > 0) + Rect rect = new Rect(x, y, 25f, 25f); + if (incapableBecauseOfCapacities) { - Text.Anchor = TextAnchor.MiddleCenter; - GUI.color = WidgetsWork.ColorOfPriority(priority); - Rect rect2 = rect.ContractedBy(-3f); - Widgets.Label(rect2, priority.ToStringCached()); - GUI.color = Color.white; - Text.Anchor = TextAnchor.UpperLeft; + GUI.color = new Color(1f, 0.3f, 0.3f); } - if (Event.current.type == EventType.MouseDown && Mouse.IsOver(rect)) + WidgetsWork.DrawWorkBoxBackground(rect, p, wType); + GUI.color = Color.white; + if (Find.PlaySettings.useWorkPriorities) { - bool flag = p.workSettings.WorkIsActive(wType); - if (Event.current.button == 0) + int priority = p.workSettings.GetPriority(wType); + if (priority > 0) { - int num = p.workSettings.GetPriority(wType) - 1; - if (num < 0) - { - num = 4; - } - p.workSettings.SetPriority(wType, num); - SoundDefOf.AmountIncrement.PlayOneShotOnCamera(null); + Text.Anchor = TextAnchor.MiddleCenter; + GUI.color = WidgetsWork.ColorOfPriority(priority); + Rect rect2 = rect.ContractedBy(-3f); + Widgets.Label(rect2, priority.ToStringCached()); + GUI.color = Color.white; + Text.Anchor = TextAnchor.UpperLeft; } - if (Event.current.button == 1) + if (Event.current.type == EventType.MouseDown && Mouse.IsOver(rect)) { - int num2 = p.workSettings.GetPriority(wType) + 1; - if (num2 > 4) + bool flag = p.workSettings.WorkIsActive(wType); + if (Event.current.button == 0) { - num2 = 0; + int num = p.workSettings.GetPriority(wType) - 1; + if (num < 0) + { + num = 4; + } + p.workSettings.SetPriority(wType, num); + SoundDefOf.AmountIncrement.PlayOneShotOnCamera(null); } - p.workSettings.SetPriority(wType, num2); - SoundDefOf.AmountDecrement.PlayOneShotOnCamera(null); - } - if (!flag && p.workSettings.WorkIsActive(wType) && p.skills.AverageOfRelevantSkillsFor(wType) <= 2f) - { - SoundDefOf.Crunch.PlayOneShotOnCamera(null); + if (Event.current.button == 1) + { + int num2 = p.workSettings.GetPriority(wType) + 1; + if (num2 > 4) + { + num2 = 0; + } + p.workSettings.SetPriority(wType, num2); + SoundDefOf.AmountDecrement.PlayOneShotOnCamera(null); + } + if (!flag && p.workSettings.WorkIsActive(wType) && p.skills.AverageOfRelevantSkillsFor(wType) <= 2.0) + { + SoundDefOf.Crunch.PlayOneShotOnCamera(null); + } + Event.current.Use(); + PlayerKnowledgeDatabase.KnowledgeDemonstrated(ConceptDefOf.WorkTab, KnowledgeAmount.SpecificInteraction); + PlayerKnowledgeDatabase.KnowledgeDemonstrated(ConceptDefOf.ManualWorkPriorities, KnowledgeAmount.SmallInteraction); } - Event.current.Use(); - PlayerKnowledgeDatabase.KnowledgeDemonstrated(ConceptDefOf.WorkTab, KnowledgeAmount.SpecificInteraction); - PlayerKnowledgeDatabase.KnowledgeDemonstrated(ConceptDefOf.ManualWorkPriorities, KnowledgeAmount.SmallInteraction); } - } - else - { - int priority2 = p.workSettings.GetPriority(wType); - if (priority2 > 0) - { - GUI.DrawTexture(rect, WidgetsWork.WorkBoxCheckTex); - } - if (Widgets.ButtonInvisible(rect, false)) + else { - if (p.workSettings.GetPriority(wType) > 0) + int priority2 = p.workSettings.GetPriority(wType); + if (priority2 > 0) { - p.workSettings.SetPriority(wType, 0); - SoundDefOf.CheckboxTurnedOff.PlayOneShotOnCamera(null); + GUI.DrawTexture(rect, WidgetsWork.WorkBoxCheckTex); } - else + if (Widgets.ButtonInvisible(rect, false)) { - p.workSettings.SetPriority(wType, 3); - SoundDefOf.CheckboxTurnedOn.PlayOneShotOnCamera(null); - if (p.skills.AverageOfRelevantSkillsFor(wType) <= 2f) + if (p.workSettings.GetPriority(wType) > 0) { - SoundDefOf.Crunch.PlayOneShotOnCamera(null); + p.workSettings.SetPriority(wType, 0); + SoundDefOf.CheckboxTurnedOff.PlayOneShotOnCamera(null); } + else + { + p.workSettings.SetPriority(wType, 3); + SoundDefOf.CheckboxTurnedOn.PlayOneShotOnCamera(null); + if (p.skills.AverageOfRelevantSkillsFor(wType) <= 2.0) + { + SoundDefOf.Crunch.PlayOneShotOnCamera(null); + } + } + PlayerKnowledgeDatabase.KnowledgeDemonstrated(ConceptDefOf.WorkTab, KnowledgeAmount.SpecificInteraction); } - PlayerKnowledgeDatabase.KnowledgeDemonstrated(ConceptDefOf.WorkTab, KnowledgeAmount.SpecificInteraction); } } } @@ -141,10 +151,7 @@ public static string TipForPawnWorker(Pawn p, WorkTypeDef wDef, bool incapableBe stringBuilder.AppendLine(wDef.gerundLabel); if (p.story.WorkTypeIsDisabled(wDef)) { - stringBuilder.Append("CannotDoThisWork".Translate(new object[] - { - p.NameStringShort - })); + stringBuilder.Append("CannotDoThisWork".Translate(p.NameStringShort)); } else { @@ -155,20 +162,24 @@ public static string TipForPawnWorker(Pawn p, WorkTypeDef wDef, bool incapableBe } else { - foreach (SkillDef current in wDef.relevantSkills) + List.Enumerator enumerator = wDef.relevantSkills.GetEnumerator(); + try + { + while (enumerator.MoveNext()) + { + SkillDef current = enumerator.Current; + text = text + current.skillLabel + ", "; + } + } + finally { - text = text + current.skillLabel + ", "; + ((IDisposable)(object)enumerator).Dispose(); } text = text.Substring(0, text.Length - 2); } if (wDef.relevantSkills.Count > 0) { - stringBuilder.AppendLine("RelevantSkills".Translate(new object[] - { - text, - p.skills.AverageOfRelevantSkillsFor(wDef).ToString(), - 20 - })); + stringBuilder.AppendLine("RelevantSkills".Translate(text, p.skills.AverageOfRelevantSkillsFor(wDef).ToString(), 20)); } stringBuilder.AppendLine(); stringBuilder.Append(wDef.description); @@ -188,41 +199,53 @@ private static void DrawWorkBoxBackground(Rect rect, Pawn p, WorkTypeDef workDef Texture2D image; Texture2D image2; float a; - if (num < 4f) + if (num < 4.0) { image = WidgetsWork.WorkBoxBGTex_Awful; image2 = WidgetsWork.WorkBoxBGTex_Bad; - a = num / 4f; + a = (float)(num / 4.0); } - else if (num <= 14f) + else if (num <= 14.0) { image = WidgetsWork.WorkBoxBGTex_Bad; image2 = WidgetsWork.WorkBoxBGTex_Mid; - a = (num - 4f) / 10f; + a = (float)((num - 4.0) / 10.0); } else { image = WidgetsWork.WorkBoxBGTex_Mid; image2 = WidgetsWork.WorkBoxBGTex_Excellent; - a = (num - 14f) / 6f; + a = (float)((num - 14.0) / 6.0); } GUI.DrawTexture(rect, image); - GUI.color = new Color(GUI.color.r, GUI.color.g, GUI.color.b, a); + Color color = GUI.color; + float r = color.r; + Color color2 = GUI.color; + float g = color2.g; + Color color3 = GUI.color; + GUI.color = new Color(r, g, color3.b, a); GUI.DrawTexture(rect, image2); Passion passion = p.skills.MaxPassionOfRelevantSkillsFor(workDef); - if (passion > Passion.None) + if ((int)passion > 0) { GUI.color = new Color(1f, 1f, 1f, 0.4f); Rect position = rect; - position.xMin = rect.center.x; - position.yMin = rect.center.y; - if (passion == Passion.Minor) + Vector2 center = rect.center; + position.xMin = center.x; + Vector2 center2 = rect.center; + position.yMin = center2.y; + switch (passion) + { + case Passion.Minor: { GUI.DrawTexture(position, WidgetsWork.PassionWorkboxMinorIcon); + break; } - else if (passion == Passion.Major) + case Passion.Major: { GUI.DrawTexture(position, WidgetsWork.PassionWorkboxMajorIcon); + break; + } } } GUI.color = Color.white; diff --git a/Assembly-CSharp/RimWorld/WildSpawner.cs b/Assembly-CSharp/RimWorld/WildSpawner.cs index 1875eace3..d7b260d22 100644 --- a/Assembly-CSharp/RimWorld/WildSpawner.cs +++ b/Assembly-CSharp/RimWorld/WildSpawner.cs @@ -20,20 +20,19 @@ private float DesiredAnimalDensity { get { - float num = this.map.Biome.animalDensity; + float animalDensity = this.map.Biome.animalDensity; + float num = 0f; float num2 = 0f; - float num3 = 0f; - foreach (PawnKindDef current in this.map.Biome.AllWildAnimals) + foreach (PawnKindDef allWildAnimal in this.map.Biome.AllWildAnimals) { - num3 += current.wildSpawn_EcoSystemWeight; - if (this.map.mapTemperature.SeasonAcceptableFor(current.race)) + num2 += allWildAnimal.wildSpawn_EcoSystemWeight; + if (this.map.mapTemperature.SeasonAcceptableFor(allWildAnimal.race)) { - num2 += current.wildSpawn_EcoSystemWeight; + num += allWildAnimal.wildSpawn_EcoSystemWeight; } } - num *= num2 / num3; - num *= this.map.gameConditionManager.AggregateAnimalDensityFactor(); - return num; + animalDensity *= num / num2; + return animalDensity * this.map.gameConditionManager.AggregateAnimalDensityFactor(); } } @@ -42,11 +41,11 @@ private float DesiredTotalAnimalWeight get { float desiredAnimalDensity = this.DesiredAnimalDensity; - if (desiredAnimalDensity == 0f) + if (desiredAnimalDensity == 0.0) { return 0f; } - float num = 10000f / desiredAnimalDensity; + float num = (float)(10000.0 / desiredAnimalDensity); return (float)this.map.Area / num; } } @@ -83,18 +82,21 @@ public WildSpawner(Map map) public void WildSpawnerTick() { - IntVec3 loc; - if (Find.TickManager.TicksGame % 1210 == 0 && !this.AnimalEcosystemFull && Rand.Value < 0.0268888883f * this.DesiredAnimalDensity && RCellFinder.TryFindRandomPawnEntryCell(out loc, this.map, CellFinder.EdgeRoadChance_Animal, null)) + IntVec3 loc = default(IntVec3); + if (Find.TickManager.TicksGame % 1210 == 0 && !this.AnimalEcosystemFull && Rand.Value < 0.026888888329267502 * this.DesiredAnimalDensity && RCellFinder.TryFindRandomPawnEntryCell(out loc, this.map, CellFinder.EdgeRoadChance_Animal, (Predicate)null)) { this.SpawnRandomWildAnimalAt(loc); } float num = this.map.gameConditionManager.AggregatePlantDensityFactor(); - if (num > 0.0001f) + if (num > 9.9999997473787516E-05) { - int num2 = this.map.Size.x * 2 + this.map.Size.z * 2; - float num3 = 650f / ((float)num2 / 100f); - int num4 = GenMath.RoundRandom(num3 / num); - if (Find.TickManager.TicksGame % num4 == 0) + IntVec3 size = this.map.Size; + int num2 = size.x * 2; + IntVec3 size2 = this.map.Size; + int num3 = num2 + size2.z * 2; + float num4 = (float)(650.0 / ((float)num3 / 100.0)); + int num5 = GenMath.RoundRandom(num4 / num); + if (Find.TickManager.TicksGame % num5 == 0) { this.TrySpawnPlantFromMapEdge(); } @@ -103,13 +105,9 @@ public void WildSpawnerTick() private void TrySpawnPlantFromMapEdge() { - ThingDef plantDef; - if (!this.map.Biome.AllWildPlants.TryRandomElementByWeight((ThingDef def) => this.map.Biome.CommonalityOfPlant(def), out plantDef)) - { - return; - } - IntVec3 source; - if (RCellFinder.TryFindRandomCellToPlantInFromOffMap(plantDef, this.map, out source)) + ThingDef plantDef = default(ThingDef); + IntVec3 source = default(IntVec3); + if (this.map.Biome.AllWildPlants.TryRandomElementByWeight((Func)((ThingDef def) => this.map.Biome.CommonalityOfPlant(def)), out plantDef) && RCellFinder.TryFindRandomCellToPlantInFromOffMap(plantDef, this.map, out source)) { GenPlantReproduction.TryReproduceFrom(source, plantDef, SeedTargFindMode.MapEdge, this.map); } @@ -119,33 +117,27 @@ public void SpawnRandomWildAnimalAt(IntVec3 loc) { PawnKindDef pawnKindDef = (from a in this.map.Biome.AllWildAnimals where this.map.mapTemperature.SeasonAcceptableFor(a.race) - select a).RandomElementByWeight((PawnKindDef def) => this.map.Biome.CommonalityOfAnimal(def) / def.wildSpawn_GroupSizeRange.Average); + select a).RandomElementByWeight((Func)((PawnKindDef def) => this.map.Biome.CommonalityOfAnimal(def) / def.wildSpawn_GroupSizeRange.Average)); if (pawnKindDef == null) { Log.Error("No spawnable animals right now."); - return; } - int randomInRange = pawnKindDef.wildSpawn_GroupSizeRange.RandomInRange; - int radius = Mathf.CeilToInt(Mathf.Sqrt((float)pawnKindDef.wildSpawn_GroupSizeRange.max)); - for (int i = 0; i < randomInRange; i++) + else { - IntVec3 loc2 = CellFinder.RandomClosewalkCellNear(loc, this.map, radius, null); - Pawn newThing = PawnGenerator.GeneratePawn(pawnKindDef, null); - GenSpawn.Spawn(newThing, loc2, this.map); + int randomInRange = pawnKindDef.wildSpawn_GroupSizeRange.RandomInRange; + int radius = Mathf.CeilToInt(Mathf.Sqrt((float)pawnKindDef.wildSpawn_GroupSizeRange.max)); + for (int num = 0; num < randomInRange; num++) + { + IntVec3 loc2 = CellFinder.RandomClosewalkCellNear(loc, this.map, radius, null); + Pawn newThing = PawnGenerator.GeneratePawn(pawnKindDef, null); + GenSpawn.Spawn(newThing, loc2, this.map); + } } } public string DebugString() { - return string.Concat(new object[] - { - "DesiredTotalAnimalWeight: ", - this.DesiredTotalAnimalWeight, - "\nCurrentTotalAnimalWeight: ", - this.CurrentTotalAnimalWeight, - "\nDesiredAnimalDensity: ", - this.DesiredAnimalDensity - }); + return "DesiredTotalAnimalWeight: " + this.DesiredTotalAnimalWeight + "\nCurrentTotalAnimalWeight: " + this.CurrentTotalAnimalWeight + "\nDesiredAnimalDensity: " + this.DesiredAnimalDensity; } } } diff --git a/Assembly-CSharp/RimWorld/WindTurbineUtility.cs b/Assembly-CSharp/RimWorld/WindTurbineUtility.cs index 92d93933e..409053fa9 100644 --- a/Assembly-CSharp/RimWorld/WindTurbineUtility.cs +++ b/Assembly-CSharp/RimWorld/WindTurbineUtility.cs @@ -1,23 +1,60 @@ -using System; using System.Collections.Generic; -using System.Diagnostics; using Verse; namespace RimWorld { public static class WindTurbineUtility { - [DebuggerHidden] public static IEnumerable CalculateWindCells(IntVec3 center, Rot4 rot, IntVec2 size) { - WindTurbineUtility.c__IteratorB5 c__IteratorB = new WindTurbineUtility.c__IteratorB5(); - c__IteratorB.rot = rot; - c__IteratorB.center = center; - c__IteratorB.<$>rot = rot; - c__IteratorB.<$>center = center; - WindTurbineUtility.c__IteratorB5 expr_23 = c__IteratorB; - expr_23.$PC = -2; - return expr_23; + CellRect rectA = default(CellRect); + CellRect rectB = default(CellRect); + int offset = 0; + int neDist; + int swDist; + if (!(rot == Rot4.North) && !(rot == Rot4.East)) + { + neDist = 5; + swDist = 9; + offset = -1; + } + else + { + neDist = 9; + swDist = 5; + } + if (rot.IsHorizontal) + { + rectA.minX = center.x + 2 + offset; + rectA.maxX = center.x + 2 + neDist + offset; + rectB.minX = center.x - 1 - swDist + offset; + rectB.maxX = center.x - 1 + offset; + rectB.minZ = (rectA.minZ = center.z - 2); + rectB.maxZ = (rectA.maxZ = center.z + 2); + } + else + { + rectA.minZ = center.z + 2 + offset; + rectA.maxZ = center.z + 2 + neDist + offset; + rectB.minZ = center.z - 1 - swDist + offset; + rectB.maxZ = center.z - 1 + offset; + rectB.minX = (rectA.minX = center.x - 2); + rectB.maxX = (rectA.maxX = center.x + 2); + } + for (int z2 = rectA.minZ; z2 <= rectA.maxZ; z2++) + { + for (int x = rectA.minX; x <= rectA.maxX; x++) + { + yield return new IntVec3(x, 0, z2); + } + } + for (int z = rectB.minZ; z <= rectB.maxZ; z++) + { + for (int x2 = rectB.minX; x2 <= rectB.maxX; x2++) + { + yield return new IntVec3(x2, 0, z); + } + } } } } diff --git a/Assembly-CSharp/RimWorld/WorkGiver.cs b/Assembly-CSharp/RimWorld/WorkGiver.cs index ab7537f57..f7385d2db 100644 --- a/Assembly-CSharp/RimWorld/WorkGiver.cs +++ b/Assembly-CSharp/RimWorld/WorkGiver.cs @@ -1,4 +1,3 @@ -using System; using Verse; using Verse.AI; diff --git a/Assembly-CSharp/RimWorld/WorkGiverDef.cs b/Assembly-CSharp/RimWorld/WorkGiverDef.cs index 61cd2deac..0bc0c45dc 100644 --- a/Assembly-CSharp/RimWorld/WorkGiverDef.cs +++ b/Assembly-CSharp/RimWorld/WorkGiverDef.cs @@ -1,6 +1,5 @@ using System; using System.Collections.Generic; -using System.Diagnostics; using Verse; using Verse.AI; @@ -76,14 +75,20 @@ public WorkGiver Worker } } - [DebuggerHidden] public override IEnumerable ConfigErrors() { - WorkGiverDef.c__Iterator1EA c__Iterator1EA = new WorkGiverDef.c__Iterator1EA(); - c__Iterator1EA.<>f__this = this; - WorkGiverDef.c__Iterator1EA expr_0E = c__Iterator1EA; - expr_0E.$PC = -2; - return expr_0E; + foreach (string item in base.ConfigErrors()) + { + yield return item; + } + if (this.verb.NullOrEmpty()) + { + yield return base.defName + " lacks a verb."; + } + if (this.gerund.NullOrEmpty()) + { + yield return base.defName + " lacks a gerund."; + } } } } diff --git a/Assembly-CSharp/RimWorld/WorkGiverUtility.cs b/Assembly-CSharp/RimWorld/WorkGiverUtility.cs index 9ed785641..57a4e3510 100644 --- a/Assembly-CSharp/RimWorld/WorkGiverUtility.cs +++ b/Assembly-CSharp/RimWorld/WorkGiverUtility.cs @@ -1,4 +1,3 @@ -using System; using Verse; using Verse.AI; @@ -8,15 +7,12 @@ public static class WorkGiverUtility { public static Job HaulStuffOffBillGiverJob(Pawn pawn, IBillGiver giver, Thing thingToIgnore) { - foreach (IntVec3 current in giver.IngredientStackCells) + foreach (IntVec3 ingredientStackCell in giver.IngredientStackCells) { - Thing thing = pawn.Map.thingGrid.ThingAt(current, ThingCategory.Item); - if (thing != null) + Thing thing = pawn.Map.thingGrid.ThingAt(ingredientStackCell, ThingCategory.Item); + if (thing != null && thing != thingToIgnore) { - if (thing != thingToIgnore) - { - return HaulAIUtility.HaulAsideJobFor(pawn, thing); - } + return HaulAIUtility.HaulAsideJobFor(pawn, thing); } } return null; diff --git a/Assembly-CSharp/RimWorld/WorkGiver_BuildRoof.cs b/Assembly-CSharp/RimWorld/WorkGiver_BuildRoof.cs index 11bdebec6..0eee75773 100644 --- a/Assembly-CSharp/RimWorld/WorkGiver_BuildRoof.cs +++ b/Assembly-CSharp/RimWorld/WorkGiver_BuildRoof.cs @@ -1,4 +1,3 @@ -using System; using System.Collections.Generic; using Verse; using Verse.AI; @@ -22,7 +21,7 @@ public override IEnumerable PotentialWorkCellsGlobal(Pawn pawn) public override bool HasJobOnCell(Pawn pawn, IntVec3 c) { - if (!pawn.Map.areaManager.BuildRoof[c]) + if (!((Area)pawn.Map.areaManager.BuildRoof)[c]) { return false; } @@ -31,7 +30,23 @@ public override bool HasJobOnCell(Pawn pawn, IntVec3 c) return false; } ReservationLayerDef ceiling = ReservationLayerDefOf.Ceiling; - return pawn.CanReserve(c, 1, -1, ceiling, false) && (pawn.CanReach(c, PathEndMode.Touch, pawn.NormalMaxDanger(), false, TraverseMode.ByPawn) || this.BuildingToTouchToBeAbleToBuildRoof(c, pawn) != null) && RoofCollapseUtility.WithinRangeOfRoofHolder(c, pawn.Map) && RoofCollapseUtility.ConnectedToRoofHolder(c, pawn.Map, true); + if (!pawn.CanReserve(c, 1, -1, ceiling, false)) + { + return false; + } + if (!pawn.CanReach(c, PathEndMode.Touch, pawn.NormalMaxDanger(), false, TraverseMode.ByPawn) && this.BuildingToTouchToBeAbleToBuildRoof(c, pawn) == null) + { + return false; + } + if (!RoofCollapseUtility.WithinRangeOfRoofHolder(c, pawn.Map)) + { + return false; + } + if (!RoofCollapseUtility.ConnectedToRoofHolder(c, pawn.Map, true)) + { + return false; + } + return true; } private Building BuildingToTouchToBeAbleToBuildRoof(IntVec3 c, Pawn pawn) @@ -45,7 +60,7 @@ private Building BuildingToTouchToBeAbleToBuildRoof(IntVec3 c, Pawn pawn) { return null; } - if (!pawn.CanReach(edifice, PathEndMode.Touch, pawn.NormalMaxDanger(), false, TraverseMode.ByPawn)) + if (!pawn.CanReach((Thing)edifice, PathEndMode.Touch, pawn.NormalMaxDanger(), false, TraverseMode.ByPawn)) { return null; } @@ -57,7 +72,7 @@ public override Job JobOnCell(Pawn pawn, IntVec3 c) LocalTargetInfo targetB = c; if (!pawn.CanReach(c, PathEndMode.Touch, pawn.NormalMaxDanger(), false, TraverseMode.ByPawn)) { - targetB = this.BuildingToTouchToBeAbleToBuildRoof(c, pawn); + targetB = (Thing)this.BuildingToTouchToBeAbleToBuildRoof(c, pawn); } return new Job(JobDefOf.BuildRoof, c, targetB); } diff --git a/Assembly-CSharp/RimWorld/WorkGiver_BuryCorpses.cs b/Assembly-CSharp/RimWorld/WorkGiver_BuryCorpses.cs index a691c9599..cd4d730cc 100644 --- a/Assembly-CSharp/RimWorld/WorkGiver_BuryCorpses.cs +++ b/Assembly-CSharp/RimWorld/WorkGiver_BuryCorpses.cs @@ -44,24 +44,34 @@ public override Job JobOnThing(Pawn pawn, Thing t, bool forced = false) JobFailReason.Is("NoEmptyGraveLower".Translate()); return null; } - return new Job(JobDefOf.BuryCorpse, t, building_Grave) - { - count = corpse.stackCount - }; + Job job = new Job(JobDefOf.BuryCorpse, t, (Thing)building_Grave); + job.count = corpse.stackCount; + return job; } private Building_Grave FindBestGrave(Pawn p, Corpse corpse) { - Predicate predicate = (Thing m) => !m.IsForbidden(p) && p.CanReserve(m, 1, -1, null, false) && ((Building_Grave)m).Accepts(corpse); + Predicate predicate = (Predicate)delegate(Thing m) + { + if (!m.IsForbidden(p) && p.CanReserve(m, 1, -1, null, false)) + { + if (!((Building_Grave)m).Accepts(corpse)) + { + return false; + } + return true; + } + return false; + }; if (corpse.InnerPawn.ownership != null && corpse.InnerPawn.ownership.AssignedGrave != null) { Building_Grave assignedGrave = corpse.InnerPawn.ownership.AssignedGrave; - if (predicate(assignedGrave) && p.Map.reachability.CanReach(corpse.Position, assignedGrave, PathEndMode.ClosestTouch, TraverseParms.For(p, Danger.Deadly, TraverseMode.ByPawn, false))) + if (predicate(assignedGrave) && p.Map.reachability.CanReach(corpse.Position, (Thing)assignedGrave, PathEndMode.ClosestTouch, TraverseParms.For(p, Danger.Deadly, TraverseMode.ByPawn, false))) { return assignedGrave; } } - Func priorityGetter = (Thing t) => (float)((IStoreSettingsParent)t).GetStoreSettings().Priority; + Func priorityGetter = (Func)((Thing t) => (float)(int)((IStoreSettingsParent)t).GetStoreSettings().Priority); Predicate validator = predicate; return (Building_Grave)GenClosest.ClosestThing_Global_Reachable(corpse.Position, corpse.Map, corpse.Map.listerThings.ThingsInGroup(ThingRequestGroup.Grave), PathEndMode.ClosestTouch, TraverseParms.For(p, Danger.Deadly, TraverseMode.ByPawn, false), 9999f, validator, priorityGetter); } diff --git a/Assembly-CSharp/RimWorld/WorkGiver_CleanFilth.cs b/Assembly-CSharp/RimWorld/WorkGiver_CleanFilth.cs index a1153c650..595024908 100644 --- a/Assembly-CSharp/RimWorld/WorkGiver_CleanFilth.cs +++ b/Assembly-CSharp/RimWorld/WorkGiver_CleanFilth.cs @@ -45,7 +45,23 @@ public override bool HasJobOnThing(Pawn pawn, Thing t, bool forced = false) return false; } Filth filth = t as Filth; - return filth != null && filth.Map.areaManager.Home[filth.Position] && pawn.CanReserveAndReach(t, PathEndMode.ClosestTouch, pawn.NormalMaxDanger(), 1, -1, null, forced) && filth.TicksSinceThickened >= this.MinTicksSinceThickened; + if (filth == null) + { + return false; + } + if (!((Area)filth.Map.areaManager.Home)[filth.Position]) + { + return false; + } + if (!pawn.CanReserveAndReach(t, PathEndMode.ClosestTouch, pawn.NormalMaxDanger(), 1, -1, null, forced)) + { + return false; + } + if (filth.TicksSinceThickened < this.MinTicksSinceThickened) + { + return false; + } + return true; } public override Job JobOnThing(Pawn pawn, Thing t, bool forced = false) @@ -70,14 +86,12 @@ public override Job JobOnThing(Pawn pawn, Thing t, bool forced = false) } } if (job.GetTargetQueue(TargetIndex.A).Count >= num) - { break; - } } } if (job.targetQueueA != null && job.targetQueueA.Count >= 5) { - job.targetQueueA.SortBy((LocalTargetInfo targ) => targ.Cell.DistanceToSquared(pawn.Position)); + job.targetQueueA.SortBy((Func)((LocalTargetInfo targ) => targ.Cell.DistanceToSquared(pawn.Position))); } return job; } diff --git a/Assembly-CSharp/RimWorld/WorkGiver_ClearSnow.cs b/Assembly-CSharp/RimWorld/WorkGiver_ClearSnow.cs index 23eb7c2ca..2d7dc51cc 100644 --- a/Assembly-CSharp/RimWorld/WorkGiver_ClearSnow.cs +++ b/Assembly-CSharp/RimWorld/WorkGiver_ClearSnow.cs @@ -1,4 +1,3 @@ -using System; using System.Collections.Generic; using Verse; using Verse.AI; @@ -27,7 +26,15 @@ public override bool ShouldSkip(Pawn pawn) public override bool HasJobOnCell(Pawn pawn, IntVec3 c) { - return pawn.Map.snowGrid.GetDepth(c) >= 0.2f && pawn.CanReserveAndReach(c, PathEndMode.Touch, pawn.NormalMaxDanger(), 1, -1, null, false); + if (pawn.Map.snowGrid.GetDepth(c) < 0.20000000298023224) + { + return false; + } + if (!pawn.CanReserveAndReach(c, PathEndMode.Touch, pawn.NormalMaxDanger(), 1, -1, null, false)) + { + return false; + } + return true; } public override Job JobOnCell(Pawn pawn, IntVec3 c) diff --git a/Assembly-CSharp/RimWorld/WorkGiver_ConstructAffectFloor.cs b/Assembly-CSharp/RimWorld/WorkGiver_ConstructAffectFloor.cs index 0d89e6afa..3d74bb0ab 100644 --- a/Assembly-CSharp/RimWorld/WorkGiver_ConstructAffectFloor.cs +++ b/Assembly-CSharp/RimWorld/WorkGiver_ConstructAffectFloor.cs @@ -1,6 +1,4 @@ -using System; using System.Collections.Generic; -using System.Diagnostics; using Verse; using Verse.AI; @@ -21,16 +19,15 @@ public override PathEndMode PathEndMode } } - [DebuggerHidden] public override IEnumerable PotentialWorkCellsGlobal(Pawn pawn) { - WorkGiver_ConstructAffectFloor.c__Iterator5D c__Iterator5D = new WorkGiver_ConstructAffectFloor.c__Iterator5D(); - c__Iterator5D.pawn = pawn; - c__Iterator5D.<$>pawn = pawn; - c__Iterator5D.<>f__this = this; - WorkGiver_ConstructAffectFloor.c__Iterator5D expr_1C = c__Iterator5D; - expr_1C.$PC = -2; - return expr_1C; + if (pawn.Faction == Faction.OfPlayer) + { + foreach (Designation item in pawn.Map.designationManager.SpawnedDesignationsOfDef(this.DesDef)) + { + yield return item.target.Cell; + } + } } public override bool HasJobOnCell(Pawn pawn, IntVec3 c) @@ -38,11 +35,12 @@ public override bool HasJobOnCell(Pawn pawn, IntVec3 c) if (pawn.Map.designationManager.DesignationAt(c, this.DesDef) != null) { ReservationLayerDef floor = ReservationLayerDefOf.Floor; - if (pawn.CanReserveAndReach(c, PathEndMode.Touch, pawn.NormalMaxDanger(), 1, -1, floor, false)) - { - return true; - } + if (!pawn.CanReserveAndReach(c, PathEndMode.Touch, pawn.NormalMaxDanger(), 1, -1, floor, false)) + goto IL_003e; + return true; } + goto IL_003e; + IL_003e: return false; } } diff --git a/Assembly-CSharp/RimWorld/WorkGiver_ConstructDeliverResources.cs b/Assembly-CSharp/RimWorld/WorkGiver_ConstructDeliverResources.cs index a31ab0aa2..c58a0b9a0 100644 --- a/Assembly-CSharp/RimWorld/WorkGiver_ConstructDeliverResources.cs +++ b/Assembly-CSharp/RimWorld/WorkGiver_ConstructDeliverResources.cs @@ -26,85 +26,99 @@ public WorkGiver_ConstructDeliverResources() private static bool ResourceValidator(Pawn pawn, ThingCountClass need, Thing th) { - return th.def == need.thingDef && !th.IsForbidden(pawn) && pawn.CanReserve(th, 1, -1, null, false); + if (th.def != need.thingDef) + { + return false; + } + if (th.IsForbidden(pawn)) + { + return false; + } + if (!pawn.CanReserve(th, 1, -1, null, false)) + { + return false; + } + return true; } protected Job ResourceDeliverJobFor(Pawn pawn, IConstructible c, bool canRemoveExistingFloorUnderNearbyNeeders = true) { - WorkGiver_ConstructDeliverResources.c__AnonStorey2AE c__AnonStorey2AE = new WorkGiver_ConstructDeliverResources.c__AnonStorey2AE(); - c__AnonStorey2AE.pawn = pawn; Blueprint_Install blueprint_Install = c as Blueprint_Install; if (blueprint_Install != null) { - return this.InstallJob(c__AnonStorey2AE.pawn, blueprint_Install); + return this.InstallJob(pawn, blueprint_Install); } bool flag = false; List list = c.MaterialsNeeded(); int count = list.Count; - int i = 0; - while (i < count) + for (int num = 0; num < count; num++) { - WorkGiver_ConstructDeliverResources.c__AnonStorey2AF c__AnonStorey2AF = new WorkGiver_ConstructDeliverResources.c__AnonStorey2AF(); - c__AnonStorey2AF.<>f__ref$686 = c__AnonStorey2AE; - c__AnonStorey2AF.need = list[i]; - if (!c__AnonStorey2AE.pawn.Map.itemAvailability.ThingsAvailableAnywhere(c__AnonStorey2AF.need, c__AnonStorey2AE.pawn)) + ThingCountClass need = list[num]; + if (!pawn.Map.itemAvailability.ThingsAvailableAnywhere(need, pawn)) { flag = true; break; } - WorkGiver_ConstructDeliverResources.c__AnonStorey2AF arg_EE_0 = c__AnonStorey2AF; - Predicate validator = (Thing r) => WorkGiver_ConstructDeliverResources.ResourceValidator(c__AnonStorey2AF.<>f__ref$686.pawn, c__AnonStorey2AF.need, r); - arg_EE_0.foundRes = GenClosest.ClosestThingReachable(c__AnonStorey2AE.pawn.Position, c__AnonStorey2AE.pawn.Map, ThingRequest.ForDef(c__AnonStorey2AF.need.thingDef), PathEndMode.ClosestTouch, TraverseParms.For(c__AnonStorey2AE.pawn, Danger.Deadly, TraverseMode.ByPawn, false), 9999f, validator, null, 0, -1, false, RegionType.Set_Passable, false); - if (c__AnonStorey2AF.foundRes != null) + Predicate validator = (Predicate)((Thing r) => WorkGiver_ConstructDeliverResources.ResourceValidator(pawn, need, r)); + Thing foundRes = GenClosest.ClosestThingReachable(pawn.Position, pawn.Map, ThingRequest.ForDef(need.thingDef), PathEndMode.ClosestTouch, TraverseParms.For(pawn, Danger.Deadly, TraverseMode.ByPawn, false), 9999f, validator, null, 0, -1, false, RegionType.Set_Passable, false); + if (foundRes != null) { - int resTotalAvailable; - this.FindAvailableNearbyResources(c__AnonStorey2AF.foundRes, c__AnonStorey2AE.pawn, out resTotalAvailable); - int num; - Job job; - HashSet hashSet = this.FindNearbyNeeders(c__AnonStorey2AE.pawn, c__AnonStorey2AF.need, c, resTotalAvailable, canRemoveExistingFloorUnderNearbyNeeders, out num, out job); + int resTotalAvailable = default(int); + this.FindAvailableNearbyResources(foundRes, pawn, out resTotalAvailable); + int num2 = default(int); + Job job = default(Job); + HashSet hashSet = this.FindNearbyNeeders(pawn, need, c, resTotalAvailable, canRemoveExistingFloorUnderNearbyNeeders, out num2, out job); if (job != null) { return job; } hashSet.Add((Thing)c); - Thing thing = hashSet.MinBy((Thing nee) => IntVec3Utility.ManhattanDistanceFlat(c__AnonStorey2AF.foundRes.Position, nee.Position)); + Thing thing = hashSet.MinBy((Func)((Thing nee) => IntVec3Utility.ManhattanDistanceFlat(foundRes.Position, nee.Position))); hashSet.Remove(thing); - int num2 = 0; - int j = 0; - do + int num3 = 0; + int num4 = 0; + while (true) { - num2 += WorkGiver_ConstructDeliverResources.resourcesAvailable[j].stackCount; - j++; + num3 += WorkGiver_ConstructDeliverResources.resourcesAvailable[num4].stackCount; + num4++; + if (num3 >= num2) + break; + if (num4 >= WorkGiver_ConstructDeliverResources.resourcesAvailable.Count) + break; } - while (num2 < num && j < WorkGiver_ConstructDeliverResources.resourcesAvailable.Count); - WorkGiver_ConstructDeliverResources.resourcesAvailable.RemoveRange(j, WorkGiver_ConstructDeliverResources.resourcesAvailable.Count - j); - WorkGiver_ConstructDeliverResources.resourcesAvailable.Remove(c__AnonStorey2AF.foundRes); + WorkGiver_ConstructDeliverResources.resourcesAvailable.RemoveRange(num4, WorkGiver_ConstructDeliverResources.resourcesAvailable.Count - num4); + WorkGiver_ConstructDeliverResources.resourcesAvailable.Remove(foundRes); Job job2 = new Job(JobDefOf.HaulToContainer); - job2.targetA = c__AnonStorey2AF.foundRes; + job2.targetA = foundRes; job2.targetQueueA = new List(); - for (j = 0; j < WorkGiver_ConstructDeliverResources.resourcesAvailable.Count; j++) + for (num4 = 0; num4 < WorkGiver_ConstructDeliverResources.resourcesAvailable.Count; num4++) { - job2.targetQueueA.Add(WorkGiver_ConstructDeliverResources.resourcesAvailable[j]); + job2.targetQueueA.Add(WorkGiver_ConstructDeliverResources.resourcesAvailable[num4]); } job2.targetB = thing; if (hashSet.Count > 0) { job2.targetQueueB = new List(); - foreach (Thing current in hashSet) + HashSet.Enumerator enumerator = hashSet.GetEnumerator(); + try + { + while (enumerator.MoveNext()) + { + Thing current = enumerator.Current; + job2.targetQueueB.Add(current); + } + } + finally { - job2.targetQueueB.Add(current); + ((IDisposable)(object)enumerator).Dispose(); } } job2.targetC = (Thing)c; - job2.count = num; + job2.count = num2; job2.haulMode = HaulMode.ToContainer; return job2; } - else - { - flag = true; - i++; - } + flag = true; } if (flag) { @@ -122,20 +136,18 @@ private void FindAvailableNearbyResources(Thing firstFoundResource, Pawn pawn, o resTotalAvailable += firstFoundResource.stackCount; if (resTotalAvailable < num) { - foreach (Thing current in GenRadial.RadialDistinctThingsAround(firstFoundResource.Position, firstFoundResource.Map, 5f, false)) + foreach (Thing item in GenRadial.RadialDistinctThingsAround(firstFoundResource.Position, firstFoundResource.Map, 5f, false)) { - if (resTotalAvailable >= num) - { - break; - } - if (current.def == firstFoundResource.def) + if (resTotalAvailable < num) { - if (GenAI.CanUseItemForWork(pawn, current)) + if (item.def == firstFoundResource.def && GenAI.CanUseItemForWork(pawn, item)) { - WorkGiver_ConstructDeliverResources.resourcesAvailable.Add(current); - resTotalAvailable += current.stackCount; + WorkGiver_ConstructDeliverResources.resourcesAvailable.Add(item); + resTotalAvailable += item.stackCount; } + continue; } + break; } } } @@ -145,34 +157,35 @@ private HashSet FindNearbyNeeders(Pawn pawn, ThingCountClass need, IConst neededTotal = need.count; HashSet hashSet = new HashSet(); Thing thing = (Thing)c; - foreach (Thing current in GenRadial.RadialDistinctThingsAround(thing.Position, thing.Map, 8f, false)) + foreach (Thing item in GenRadial.RadialDistinctThingsAround(thing.Position, thing.Map, 8f, false)) { - if (neededTotal >= resTotalAvailable) + if (neededTotal < resTotalAvailable) { - break; - } - if (this.IsNewValidNearbyNeeder(current, hashSet, c, pawn)) - { - Blueprint blueprint = current as Blueprint; - if (blueprint == null || !WorkGiver_ConstructDeliverResources.ShouldRemoveExistingFloorFirst(pawn, blueprint)) + if (this.IsNewValidNearbyNeeder(item, hashSet, c, pawn)) { - int num = GenConstruct.AmountNeededByOf((IConstructible)current, need.thingDef); - if (num > 0) + Blueprint blueprint = item as Blueprint; + if (blueprint == null || !WorkGiver_ConstructDeliverResources.ShouldRemoveExistingFloorFirst(pawn, blueprint)) { - hashSet.Add(current); - neededTotal += num; + int num = GenConstruct.AmountNeededByOf((IConstructible)item, need.thingDef); + if (num > 0) + { + hashSet.Add(item); + neededTotal += num; + } } } + continue; } + break; } Blueprint blueprint2 = c as Blueprint; if (blueprint2 != null && blueprint2.def.entityDefToBuild is TerrainDef && canRemoveExistingFloorUnderNearbyNeeders && neededTotal < resTotalAvailable) { - foreach (Thing current2 in GenRadial.RadialDistinctThingsAround(thing.Position, thing.Map, 3f, false)) + foreach (Thing item2 in GenRadial.RadialDistinctThingsAround(thing.Position, thing.Map, 3f, false)) { - if (this.IsNewValidNearbyNeeder(current2, hashSet, c, pawn)) + if (this.IsNewValidNearbyNeeder(item2, hashSet, c, pawn)) { - Blueprint blueprint3 = current2 as Blueprint; + Blueprint blueprint3 = item2 as Blueprint; if (blueprint3 != null) { Job job = this.RemoveExistingFloorJob(pawn, blueprint3); @@ -191,12 +204,24 @@ private HashSet FindNearbyNeeders(Pawn pawn, ThingCountClass need, IConst private bool IsNewValidNearbyNeeder(Thing t, HashSet nearbyNeeders, IConstructible constructible, Pawn pawn) { - return t is IConstructible && t != constructible && !(t is Blueprint_Install) && t.Faction == pawn.Faction && !t.IsForbidden(pawn) && !nearbyNeeders.Contains(t) && GenConstruct.CanConstruct(t, pawn, false); + if (t is IConstructible && t != constructible && !(t is Blueprint_Install) && t.Faction == pawn.Faction && !t.IsForbidden(pawn) && !nearbyNeeders.Contains(t) && GenConstruct.CanConstruct(t, pawn, false)) + { + return true; + } + return false; } private static bool ShouldRemoveExistingFloorFirst(Pawn pawn, Blueprint blue) { - return blue.def.entityDefToBuild is TerrainDef && pawn.Map.terrainGrid.CanRemoveTopLayerAt(blue.Position); + if (!(blue.def.entityDefToBuild is TerrainDef)) + { + return false; + } + if (!pawn.Map.terrainGrid.CanRemoveTopLayerAt(blue.Position)) + { + return false; + } + return true; } protected Job RemoveExistingFloorJob(Pawn pawn, Blueprint blue) @@ -210,26 +235,24 @@ protected Job RemoveExistingFloorJob(Pawn pawn, Blueprint blue) { return null; } - return new Job(JobDefOf.RemoveFloor, blue.Position) - { - ignoreDesignations = true - }; + Job job = new Job(JobDefOf.RemoveFloor, blue.Position); + job.ignoreDesignations = true; + return job; } private Job InstallJob(Pawn pawn, Blueprint_Install install) { Thing miniToInstallOrBuildingToReinstall = install.MiniToInstallOrBuildingToReinstall; - if (miniToInstallOrBuildingToReinstall.IsForbidden(pawn) || !pawn.CanReserveAndReach(miniToInstallOrBuildingToReinstall, PathEndMode.OnCell, pawn.NormalMaxDanger(), 1, -1, null, false)) + if (!miniToInstallOrBuildingToReinstall.IsForbidden(pawn) && pawn.CanReserveAndReach(miniToInstallOrBuildingToReinstall, PathEndMode.OnCell, pawn.NormalMaxDanger(), 1, -1, null, false)) { - return null; + Job job = new Job(JobDefOf.HaulToContainer); + job.targetA = miniToInstallOrBuildingToReinstall; + job.targetB = (Thing)install; + job.count = 1; + job.haulMode = HaulMode.ToContainer; + return job; } - return new Job(JobDefOf.HaulToContainer) - { - targetA = miniToInstallOrBuildingToReinstall, - targetB = install, - count = 1, - haulMode = HaulMode.ToContainer - }; + return null; } } } diff --git a/Assembly-CSharp/RimWorld/WorkGiver_ConstructDeliverResourcesToBlueprints.cs b/Assembly-CSharp/RimWorld/WorkGiver_ConstructDeliverResourcesToBlueprints.cs index e02210779..a93b74e71 100644 --- a/Assembly-CSharp/RimWorld/WorkGiver_ConstructDeliverResourcesToBlueprints.cs +++ b/Assembly-CSharp/RimWorld/WorkGiver_ConstructDeliverResourcesToBlueprints.cs @@ -1,4 +1,3 @@ -using System; using System.Collections.Generic; using Verse; using Verse.AI; @@ -43,15 +42,7 @@ public override Job JobOnThing(Pawn pawn, Thing t, bool forced = false) { return HaulAIUtility.HaulAsideJobFor(pawn, thing); } - Log.ErrorOnce(string.Concat(new object[] - { - "Never haulable ", - thing, - " blocking ", - t, - " at ", - t.Position - }), 6429262); + Log.ErrorOnce("Never haulable " + thing + " blocking " + t + " at " + t.Position, 6429262); } return null; } @@ -87,38 +78,46 @@ private Job DeconstructExistingBuildingJob(Pawn pawn, Blueprint blue) Thing thing = GenConstruct.MiniToInstallOrBuildingToReinstall(blue); Thing thing2 = null; CellRect cellRect = blue.OccupiedRect(); - for (int i = cellRect.minZ; i <= cellRect.maxZ; i++) + int num = cellRect.minZ; + while (num <= cellRect.maxZ) { - for (int j = cellRect.minX; j <= cellRect.maxX; j++) + int num2 = cellRect.minX; + while (num2 <= cellRect.maxX) { - IntVec3 c = new IntVec3(j, 0, i); + IntVec3 c = new IntVec3(num2, 0, num); List thingList = c.GetThingList(pawn.Map); - for (int k = 0; k < thingList.Count; k++) + int num3 = 0; + while (num3 < thingList.Count) { - if (thingList[k].def.category == ThingCategory.Building && thingList[k] != thing && GenSpawn.SpawningWipes(blue.def.entityDefToBuild, thingList[k].def)) + if (thingList[num3].def.category != ThingCategory.Building || thingList[num3] == thing || !GenSpawn.SpawningWipes(blue.def.entityDefToBuild, thingList[num3].def)) { - thing2 = thingList[k]; - break; + num3++; + continue; } + thing2 = thingList[num3]; + break; } - if (thing2 != null) + if (thing2 == null) { - break; + num2++; + continue; } + break; } - if (thing2 != null) + if (thing2 == null) { - break; + num++; + continue; } + break; } - if (thing2 == null || !pawn.CanReserve(thing2, 1, -1, null, false)) + if (thing2 != null && pawn.CanReserve(thing2, 1, -1, null, false)) { - return null; + Job job = new Job(JobDefOf.Deconstruct, thing2); + job.ignoreDesignations = true; + return job; } - return new Job(JobDefOf.Deconstruct, thing2) - { - ignoreDesignations = true - }; + return null; } private Job NoCostFrameMakeJobFor(Pawn pawn, IConstructible c) @@ -129,10 +128,9 @@ private Job NoCostFrameMakeJobFor(Pawn pawn, IConstructible c) } if (c is Blueprint && c.MaterialsNeeded().Count == 0) { - return new Job(JobDefOf.PlaceNoCostFrame) - { - targetA = (Thing)c - }; + Job job = new Job(JobDefOf.PlaceNoCostFrame); + job.targetA = (Thing)c; + return job; } return null; } diff --git a/Assembly-CSharp/RimWorld/WorkGiver_ConstructDeliverResourcesToFrames.cs b/Assembly-CSharp/RimWorld/WorkGiver_ConstructDeliverResourcesToFrames.cs index 02308a976..c3b91bc55 100644 --- a/Assembly-CSharp/RimWorld/WorkGiver_ConstructDeliverResourcesToFrames.cs +++ b/Assembly-CSharp/RimWorld/WorkGiver_ConstructDeliverResourcesToFrames.cs @@ -1,4 +1,3 @@ -using System; using Verse; using Verse.AI; @@ -21,15 +20,15 @@ public override Job JobOnThing(Pawn pawn, Thing t, bool forced = false) return null; } Frame frame = t as Frame; - if (frame == null) + if (frame != null) { - return null; - } - if (!GenConstruct.CanConstruct(frame, pawn, forced)) - { - return null; + if (!GenConstruct.CanConstruct(frame, pawn, forced)) + { + return null; + } + return base.ResourceDeliverJobFor(pawn, frame, true); } - return base.ResourceDeliverJobFor(pawn, frame, true); + return null; } } } diff --git a/Assembly-CSharp/RimWorld/WorkGiver_ConstructFinishFrames.cs b/Assembly-CSharp/RimWorld/WorkGiver_ConstructFinishFrames.cs index 27bc027a3..6b3d22453 100644 --- a/Assembly-CSharp/RimWorld/WorkGiver_ConstructFinishFrames.cs +++ b/Assembly-CSharp/RimWorld/WorkGiver_ConstructFinishFrames.cs @@ -1,4 +1,3 @@ -using System; using Verse; using Verse.AI; @@ -21,19 +20,19 @@ public override Job JobOnThing(Pawn pawn, Thing t, bool forced = false) return null; } Frame frame = t as Frame; - if (frame == null) + if (frame != null) { - return null; - } - if (!GenConstruct.CanConstruct(frame, pawn, forced)) - { - return null; - } - if (frame.MaterialsNeeded().Count > 0) - { - return null; + if (!GenConstruct.CanConstruct(frame, pawn, forced)) + { + return null; + } + if (frame.MaterialsNeeded().Count > 0) + { + return null; + } + return new Job(JobDefOf.FinishFrame, (Thing)frame); } - return new Job(JobDefOf.FinishFrame, frame); + return null; } } } diff --git a/Assembly-CSharp/RimWorld/WorkGiver_ConstructRemoveFloor.cs b/Assembly-CSharp/RimWorld/WorkGiver_ConstructRemoveFloor.cs index ebade1919..038a51c2f 100644 --- a/Assembly-CSharp/RimWorld/WorkGiver_ConstructRemoveFloor.cs +++ b/Assembly-CSharp/RimWorld/WorkGiver_ConstructRemoveFloor.cs @@ -1,4 +1,3 @@ -using System; using Verse; using Verse.AI; diff --git a/Assembly-CSharp/RimWorld/WorkGiver_ConstructSmoothFloor.cs b/Assembly-CSharp/RimWorld/WorkGiver_ConstructSmoothFloor.cs index e96698515..4232c5ab9 100644 --- a/Assembly-CSharp/RimWorld/WorkGiver_ConstructSmoothFloor.cs +++ b/Assembly-CSharp/RimWorld/WorkGiver_ConstructSmoothFloor.cs @@ -1,4 +1,3 @@ -using System; using Verse; using Verse.AI; diff --git a/Assembly-CSharp/RimWorld/WorkGiver_CookFillHopper.cs b/Assembly-CSharp/RimWorld/WorkGiver_CookFillHopper.cs index 694275cf2..c318f3321 100644 --- a/Assembly-CSharp/RimWorld/WorkGiver_CookFillHopper.cs +++ b/Assembly-CSharp/RimWorld/WorkGiver_CookFillHopper.cs @@ -1,4 +1,3 @@ -using System; using System.Collections.Generic; using Verse; using Verse.AI; @@ -79,11 +78,7 @@ public static Job HopperFillFoodJob(Pawn pawn, ISlotGroupParent hopperSgp) Thing firstItem = building.Position.GetFirstItem(building.Map); if (firstItem != null) { - if (Building_NutrientPasteDispenser.IsAcceptableFeedstock(firstItem.def)) - { - thingDef = firstItem.def; - } - else + if (!Building_NutrientPasteDispenser.IsAcceptableFeedstock(firstItem.def)) { if (firstItem.IsForbidden(pawn)) { @@ -91,43 +86,27 @@ public static Job HopperFillFoodJob(Pawn pawn, ISlotGroupParent hopperSgp) } return HaulAIUtility.HaulAsideJobFor(pawn, firstItem); } + thingDef = firstItem.def; } - List list; - if (thingDef == null) - { - list = pawn.Map.listerThings.ThingsInGroup(ThingRequestGroup.FoodSourceNotPlantOrTree); - } - else - { - list = pawn.Map.listerThings.ThingsOfDef(thingDef); - } + List list = (thingDef != null) ? pawn.Map.listerThings.ThingsOfDef(thingDef) : pawn.Map.listerThings.ThingsInGroup(ThingRequestGroup.FoodSourceNotPlantOrTree); bool flag = false; for (int i = 0; i < list.Count; i++) { Thing thing = list[i]; - if (thing.def.IsNutritionGivingIngestible) + if (thing.def.IsNutritionGivingIngestible && (thing.def.ingestible.preferability == FoodPreferability.RawBad || thing.def.ingestible.preferability == FoodPreferability.RawTasty) && HaulAIUtility.PawnCanAutomaticallyHaul(pawn, thing, false) && pawn.Map.slotGroupManager.SlotGroupAt(building.Position).Settings.AllowedToAccept(thing)) { - if (thing.def.ingestible.preferability == FoodPreferability.RawBad || thing.def.ingestible.preferability == FoodPreferability.RawTasty) + StoragePriority storagePriority = HaulAIUtility.StoragePriorityAtFor(thing.Position, thing); + if ((int)storagePriority >= (int)hopperSgp.GetSlotGroup().Settings.Priority) + { + flag = true; + JobFailReason.Is(WorkGiver_CookFillHopper.TheOnlyAvailableFoodIsInStorageOfHigherPriorityTrans); + } + else { - if (HaulAIUtility.PawnCanAutomaticallyHaul(pawn, thing, false)) + Job job = HaulAIUtility.HaulMaxNumToCellJob(pawn, thing, building.Position, true); + if (job != null) { - if (pawn.Map.slotGroupManager.SlotGroupAt(building.Position).Settings.AllowedToAccept(thing)) - { - StoragePriority storagePriority = HaulAIUtility.StoragePriorityAtFor(thing.Position, thing); - if (storagePriority >= hopperSgp.GetSlotGroup().Settings.Priority) - { - flag = true; - JobFailReason.Is(WorkGiver_CookFillHopper.TheOnlyAvailableFoodIsInStorageOfHigherPriorityTrans); - } - else - { - Job job = HaulAIUtility.HaulMaxNumToCellJob(pawn, thing, building.Position, true); - if (job != null) - { - return job; - } - } - } + return job; } } } diff --git a/Assembly-CSharp/RimWorld/WorkGiver_Deconstruct.cs b/Assembly-CSharp/RimWorld/WorkGiver_Deconstruct.cs index 1c17645b2..1b0549430 100644 --- a/Assembly-CSharp/RimWorld/WorkGiver_Deconstruct.cs +++ b/Assembly-CSharp/RimWorld/WorkGiver_Deconstruct.cs @@ -1,4 +1,3 @@ -using System; using Verse; namespace RimWorld diff --git a/Assembly-CSharp/RimWorld/WorkGiver_DeepDrill.cs b/Assembly-CSharp/RimWorld/WorkGiver_DeepDrill.cs index 3d21dc3c3..a844232bb 100644 --- a/Assembly-CSharp/RimWorld/WorkGiver_DeepDrill.cs +++ b/Assembly-CSharp/RimWorld/WorkGiver_DeepDrill.cs @@ -1,4 +1,3 @@ -using System; using System.Collections.Generic; using System.Linq; using Verse; @@ -37,10 +36,11 @@ public override bool ShouldSkip(Pawn pawn) if (allBuildingsColonist[i].def == ThingDefOf.DeepDrill) { CompPowerTrader comp = allBuildingsColonist[i].GetComp(); - if (comp == null || comp.PowerOn) + if (comp != null && !comp.PowerOn) { - return false; + continue; } + return false; } } return true; @@ -61,12 +61,20 @@ public override bool HasJobOnThing(Pawn pawn, Thing t, bool forced = false) { return false; } - if (!pawn.CanReserve(building, 1, -1, null, forced)) + if (!pawn.CanReserve((Thing)building, 1, -1, null, forced)) { return false; } CompDeepDrill compDeepDrill = building.TryGetComp(); - return compDeepDrill.CanDrillNow() && !building.IsBurning(); + if (!compDeepDrill.CanDrillNow()) + { + return false; + } + if (building.IsBurning()) + { + return false; + } + return true; } public override Job JobOnThing(Pawn pawn, Thing t, bool forced = false) diff --git a/Assembly-CSharp/RimWorld/WorkGiver_DoBill.cs b/Assembly-CSharp/RimWorld/WorkGiver_DoBill.cs index 806137d49..fbd1f2ccf 100644 --- a/Assembly-CSharp/RimWorld/WorkGiver_DoBill.cs +++ b/Assembly-CSharp/RimWorld/WorkGiver_DoBill.cs @@ -69,7 +69,7 @@ public ThingDef GetDef(int index) private void CheckRemove(int index) { - if (this.counts[index] == 0f) + if (this.counts[index] == 0.0) { this.counts.RemoveAt(index); this.defs.RemoveAt(index); @@ -87,10 +87,12 @@ public void GenerateFrom(List things) this.Clear(); for (int i = 0; i < things.Count; i++) { + DefCountList defCountList; + DefCountList obj = defCountList = this; ThingDef def; - ThingDef expr_1C = def = things[i].def; - float num = this[def]; - this[expr_1C] = num + (float)things[i].stackCount; + ThingDef def2 = def = things[i].def; + float num = defCountList[def]; + obj[def2] = num + (float)things[i].stackCount; } } } @@ -113,7 +115,7 @@ public void GenerateFrom(List things) private static List tmpMedicine = new List(); - private static WorkGiver_DoBill.DefCountList availableCounts = new WorkGiver_DoBill.DefCountList(); + private static DefCountList availableCounts = new DefCountList(); public override PathEndMode PathEndMode { @@ -127,9 +129,9 @@ public override ThingRequest PotentialWorkThingRequest { get { - if (this.def.fixedBillGiverDefs != null && this.def.fixedBillGiverDefs.Count == 1) + if (base.def.fixedBillGiverDefs != null && base.def.fixedBillGiverDefs.Count == 1) { - return ThingRequest.ForDef(this.def.fixedBillGiverDefs[0]); + return ThingRequest.ForDef(base.def.fixedBillGiverDefs[0]); } return ThingRequest.ForGroup(ThingRequestGroup.PotentialBillGiver); } @@ -150,22 +152,22 @@ public WorkGiver_DoBill() public override Job JobOnThing(Pawn pawn, Thing thing, bool forced = false) { IBillGiver billGiver = thing as IBillGiver; - if (billGiver == null || !this.ThingIsUsableBillGiver(thing) || !billGiver.CurrentlyUsable() || !billGiver.BillStack.AnyShouldDoNow || !pawn.CanReserve(thing, 1, -1, null, forced) || thing.IsBurning() || thing.IsForbidden(pawn)) + if (billGiver != null && this.ThingIsUsableBillGiver(thing) && billGiver.CurrentlyUsable() && billGiver.BillStack.AnyShouldDoNow && pawn.CanReserve(thing, 1, -1, null, forced) && !thing.IsBurning() && !thing.IsForbidden(pawn)) { - return null; - } - if (!pawn.CanReach(thing.InteractionCell, PathEndMode.OnCell, Danger.Some, false, TraverseMode.ByPawn)) - { - return null; + if (!pawn.CanReach(thing.InteractionCell, PathEndMode.OnCell, Danger.Some, false, TraverseMode.ByPawn)) + { + return null; + } + billGiver.BillStack.RemoveIncompletableBills(); + return this.StartOrResumeBillJob(pawn, billGiver); } - billGiver.BillStack.RemoveIncompletableBills(); - return this.StartOrResumeBillJob(pawn, billGiver); + return null; } private static UnfinishedThing ClosestUnfinishedThingForBill(Pawn pawn, Bill_ProductionWithUft bill) { - Predicate predicate = (Thing t) => !t.IsForbidden(pawn) && ((UnfinishedThing)t).Recipe == bill.recipe && ((UnfinishedThing)t).Creator == pawn && ((UnfinishedThing)t).ingredients.TrueForAll((Thing x) => bill.IsFixedOrAllowedIngredient(x.def)) && pawn.CanReserve(t, 1, -1, null, false); - Predicate validator = predicate; + Predicate validator; + Predicate predicate = validator = (Predicate)((Thing t) => !t.IsForbidden(pawn) && ((UnfinishedThing)t).Recipe == bill.recipe && ((UnfinishedThing)t).Creator == pawn && ((UnfinishedThing)t).ingredients.TrueForAll((Predicate)((Thing x) => bill.IsFixedOrAllowedIngredient(x.def))) && pawn.CanReserve(t, 1, -1, null, false)); return (UnfinishedThing)GenClosest.ClosestThingReachable(pawn.Position, pawn.Map, ThingRequest.ForDef(bill.recipe.unfinishedThingDef), PathEndMode.InteractionCell, TraverseParms.For(pawn, pawn.NormalMaxDanger(), TraverseMode.ByPawn, false), 9999f, validator, null, 0, -1, false, RegionType.Set_Passable, false); } @@ -173,15 +175,7 @@ private static Job FinishUftJob(Pawn pawn, UnfinishedThing uft, Bill_ProductionW { if (uft.Creator != pawn) { - Log.Error(string.Concat(new object[] - { - "Tried to get FinishUftJob for ", - pawn, - " finishing ", - uft, - " but its creator is ", - uft.Creator - })); + Log.Error("Tried to get FinishUftJob for " + pawn + " finishing " + uft + " but its creator is " + uft.Creator); return null; } Job job = WorkGiverUtility.HaulStuffOffBillGiverJob(pawn, bill.billStack.billGiver, uft); @@ -189,19 +183,18 @@ private static Job FinishUftJob(Pawn pawn, UnfinishedThing uft, Bill_ProductionW { return job; } - return new Job(JobDefOf.DoBill, (Thing)bill.billStack.billGiver) + Job job2 = new Job(JobDefOf.DoBill, (Thing)bill.billStack.billGiver); + job2.bill = bill; + job2.targetQueueB = new List { - bill = bill, - targetQueueB = new List - { - uft - }, - countQueue = new List - { - 1 - }, - haulMode = HaulMode.ToCellNonStorage + (Thing)uft }; + job2.countQueue = new List + { + 1 + }; + job2.haulMode = HaulMode.ToCellNonStorage; + return job2; } private Job StartOrResumeBillJob(Pawn pawn, IBillGiver giver) @@ -209,59 +202,47 @@ private Job StartOrResumeBillJob(Pawn pawn, IBillGiver giver) for (int i = 0; i < giver.BillStack.Count; i++) { Bill bill = giver.BillStack[i]; - if (bill.recipe.requiredGiverWorkType == null || bill.recipe.requiredGiverWorkType == this.def.workType) + if ((bill.recipe.requiredGiverWorkType == null || bill.recipe.requiredGiverWorkType == base.def.workType) && (Find.TickManager.TicksGame >= bill.lastIngredientSearchFailTicks + WorkGiver_DoBill.ReCheckFailedBillTicksRange.RandomInRange || FloatMenuMakerMap.making)) { - if (Find.TickManager.TicksGame >= bill.lastIngredientSearchFailTicks + WorkGiver_DoBill.ReCheckFailedBillTicksRange.RandomInRange || FloatMenuMakerMap.making) + bill.lastIngredientSearchFailTicks = 0; + if (bill.ShouldDoNow() && bill.PawnAllowedToStartAnew(pawn)) { - bill.lastIngredientSearchFailTicks = 0; - if (bill.ShouldDoNow()) + if (bill.recipe.PawnSatisfiesSkillRequirements(pawn)) { - if (bill.PawnAllowedToStartAnew(pawn)) + Bill_ProductionWithUft bill_ProductionWithUft = bill as Bill_ProductionWithUft; + if (bill_ProductionWithUft != null) + { + if (bill_ProductionWithUft.BoundUft != null) + { + if (bill_ProductionWithUft.BoundWorker == pawn && pawn.CanReserveAndReach((Thing)bill_ProductionWithUft.BoundUft, PathEndMode.Touch, Danger.Deadly, 1, -1, null, false) && !bill_ProductionWithUft.BoundUft.IsForbidden(pawn)) + { + return WorkGiver_DoBill.FinishUftJob(pawn, bill_ProductionWithUft.BoundUft, bill_ProductionWithUft); + } + continue; + } + UnfinishedThing unfinishedThing = WorkGiver_DoBill.ClosestUnfinishedThingForBill(pawn, bill_ProductionWithUft); + if (unfinishedThing != null) + { + return WorkGiver_DoBill.FinishUftJob(pawn, unfinishedThing, bill_ProductionWithUft); + } + } + if (!WorkGiver_DoBill.TryFindBestBillIngredients(bill, pawn, (Thing)giver, this.chosenIngThings)) { - if (!bill.recipe.PawnSatisfiesSkillRequirements(pawn)) + if (!FloatMenuMakerMap.making) { - JobFailReason.Is(WorkGiver_DoBill.MissingSkillTranslated); + bill.lastIngredientSearchFailTicks = Find.TickManager.TicksGame; } else { - Bill_ProductionWithUft bill_ProductionWithUft = bill as Bill_ProductionWithUft; - if (bill_ProductionWithUft != null) - { - if (bill_ProductionWithUft.BoundUft != null) - { - if (bill_ProductionWithUft.BoundWorker != pawn || !pawn.CanReserveAndReach(bill_ProductionWithUft.BoundUft, PathEndMode.Touch, Danger.Deadly, 1, -1, null, false) || bill_ProductionWithUft.BoundUft.IsForbidden(pawn)) - { - goto IL_18A; - } - return WorkGiver_DoBill.FinishUftJob(pawn, bill_ProductionWithUft.BoundUft, bill_ProductionWithUft); - } - else - { - UnfinishedThing unfinishedThing = WorkGiver_DoBill.ClosestUnfinishedThingForBill(pawn, bill_ProductionWithUft); - if (unfinishedThing != null) - { - return WorkGiver_DoBill.FinishUftJob(pawn, unfinishedThing, bill_ProductionWithUft); - } - } - } - if (WorkGiver_DoBill.TryFindBestBillIngredients(bill, pawn, (Thing)giver, this.chosenIngThings)) - { - return this.TryStartNewDoBillJob(pawn, bill, giver); - } - if (!FloatMenuMakerMap.making) - { - bill.lastIngredientSearchFailTicks = Find.TickManager.TicksGame; - } - else - { - JobFailReason.Is(WorkGiver_DoBill.MissingMaterialsTranslated); - } + JobFailReason.Is(WorkGiver_DoBill.MissingMaterialsTranslated); } + continue; } + return this.TryStartNewDoBillJob(pawn, bill, giver); } + JobFailReason.Is(WorkGiver_DoBill.MissingSkillTranslated); } } - IL_18A:; } return null; } @@ -278,8 +259,12 @@ private Job TryStartNewDoBillJob(Pawn pawn, Bill bill, IBillGiver giver) job2.countQueue = new List(this.chosenIngThings.Count); for (int i = 0; i < this.chosenIngThings.Count; i++) { - job2.targetQueueB.Add(this.chosenIngThings[i].thing); - job2.countQueue.Add(this.chosenIngThings[i].count); + List targetQueueB = job2.targetQueueB; + ThingAmount thingAmount = this.chosenIngThings[i]; + targetQueueB.Add(thingAmount.thing); + List countQueue = job2.countQueue; + ThingAmount thingAmount2 = this.chosenIngThings[i]; + countQueue.Add(thingAmount2.count); } job2.haulMode = HaulMode.ToCellNonStorage; job2.bill = bill; @@ -295,36 +280,36 @@ private bool ThingIsUsableBillGiver(Thing thing) { pawn2 = corpse.InnerPawn; } - if (this.def.fixedBillGiverDefs != null && this.def.fixedBillGiverDefs.Contains(thing.def)) + if (base.def.fixedBillGiverDefs != null && base.def.fixedBillGiverDefs.Contains(thing.def)) { return true; } if (pawn != null) { - if (this.def.billGiversAllHumanlikes && pawn.RaceProps.Humanlike) + if (base.def.billGiversAllHumanlikes && pawn.RaceProps.Humanlike) { return true; } - if (this.def.billGiversAllMechanoids && pawn.RaceProps.IsMechanoid) + if (base.def.billGiversAllMechanoids && pawn.RaceProps.IsMechanoid) { return true; } - if (this.def.billGiversAllAnimals && pawn.RaceProps.Animal) + if (base.def.billGiversAllAnimals && pawn.RaceProps.Animal) { return true; } } if (corpse != null && pawn2 != null) { - if (this.def.billGiversAllHumanlikesCorpses && pawn2.RaceProps.Humanlike) + if (base.def.billGiversAllHumanlikesCorpses && pawn2.RaceProps.Humanlike) { return true; } - if (this.def.billGiversAllMechanoidsCorpses && pawn2.RaceProps.IsMechanoid) + if (base.def.billGiversAllMechanoidsCorpses && pawn2.RaceProps.IsMechanoid) { return true; } - if (this.def.billGiversAllAnimalsCorpses && pawn2.RaceProps.Animal) + if (base.def.billGiversAllAnimalsCorpses && pawn2.RaceProps.Animal) { return true; } @@ -350,7 +335,7 @@ private static bool TryFindBestBillIngredients(Bill bill, Pawn pawn, Thing billG WorkGiver_DoBill.relevantThings.Clear(); WorkGiver_DoBill.processedThings.Clear(); bool foundAll = false; - Predicate baseValidator = (Thing t) => t.Spawned && !t.IsForbidden(pawn) && (float)(t.Position - billGiver.Position).LengthHorizontalSquared < bill.ingredientSearchRadius * bill.ingredientSearchRadius && bill.IsFixedOrAllowedIngredient(t) && bill.recipe.ingredients.Any((IngredientCount ingNeed) => ingNeed.filter.Allows(t)) && pawn.CanReserve(t, 1, -1, null, false); + Predicate baseValidator = (Predicate)((Thing t) => t.Spawned && !t.IsForbidden(pawn) && (float)(t.Position - billGiver.Position).LengthHorizontalSquared < bill.ingredientSearchRadius * bill.ingredientSearchRadius && bill.IsFixedOrAllowedIngredient(t) && bill.recipe.ingredients.Any((Predicate)((IngredientCount ingNeed) => ingNeed.filter.Allows(t))) && pawn.CanReserve(t, 1, -1, null, false)); bool billGiverIsPawn = billGiver is Pawn; if (billGiverIsPawn) { @@ -361,32 +346,26 @@ private static bool TryFindBestBillIngredients(Bill bill, Pawn pawn, Thing billG } } TraverseParms traverseParams = TraverseParms.For(pawn, Danger.Deadly, TraverseMode.ByPawn, false); - RegionEntryPredicate entryCondition = (Region from, Region r) => r.Allows(traverseParams, false); - int adjacentRegionsAvailable = rootReg.Neighbors.Count((Region region) => entryCondition(rootReg, region)); + RegionEntryPredicate entryCondition = (RegionEntryPredicate)((Region from, Region r) => r.Allows(traverseParams, false)); + int adjacentRegionsAvailable = rootReg.Neighbors.Count((Func)((Region region) => entryCondition(rootReg, region))); int regionsProcessed = 0; WorkGiver_DoBill.processedThings.AddRange(WorkGiver_DoBill.relevantThings); - RegionProcessor regionProcessor = delegate(Region r) + RegionProcessor regionProcessor = (RegionProcessor)delegate(Region r) { List list = r.ListerThings.ThingsMatching(ThingRequest.ForGroup(ThingRequestGroup.HaulableEver)); for (int i = 0; i < list.Count; i++) { Thing thing = list[i]; - if (!WorkGiver_DoBill.processedThings.Contains(thing)) + if (!WorkGiver_DoBill.processedThings.Contains(thing) && ReachabilityWithinRegion.ThingFromRegionListerReachable(thing, r, PathEndMode.ClosestTouch, pawn) && baseValidator(thing) && (!thing.def.IsMedicine || !billGiverIsPawn)) { - if (ReachabilityWithinRegion.ThingFromRegionListerReachable(thing, r, PathEndMode.ClosestTouch, pawn)) - { - if (baseValidator(thing) && (!thing.def.IsMedicine || !billGiverIsPawn)) - { - WorkGiver_DoBill.newRelevantThings.Add(thing); - WorkGiver_DoBill.processedThings.Add(thing); - } - } + WorkGiver_DoBill.newRelevantThings.Add(thing); + WorkGiver_DoBill.processedThings.Add(thing); } } regionsProcessed++; if (WorkGiver_DoBill.newRelevantThings.Count > 0 && regionsProcessed > adjacentRegionsAvailable) { - Comparison comparison = delegate(Thing t1, Thing t2) + Comparison comparison = (Comparison)delegate(Thing t1, Thing t2) { float num = (float)(t1.Position - rootCell).LengthHorizontalSquared; float value = (float)(t2.Position - rootCell).LengthHorizontalSquared; @@ -397,7 +376,7 @@ private static bool TryFindBestBillIngredients(Bill bill, Pawn pawn, Thing billG WorkGiver_DoBill.newRelevantThings.Clear(); if (WorkGiver_DoBill.TryFindBestBillIngredientsInSet(WorkGiver_DoBill.relevantThings, bill, chosen)) { - foundAll = true; + bool foundAll2 = true; return true; } } @@ -412,16 +391,16 @@ private static bool TryFindBestBillIngredients(Bill bill, Pawn pawn, Thing billG private static IntVec3 GetBillGiverRootCell(Thing billGiver, Pawn forPawn) { Building building = billGiver as Building; - if (building == null) - { - return billGiver.Position; - } - if (building.def.hasInteractionCell) + if (building != null) { - return building.InteractionCell; + if (building.def.hasInteractionCell) + { + return building.InteractionCell; + } + Log.Error("Tried to find bill ingredients for " + billGiver + " which has no interaction cell."); + return forPawn.Position; } - Log.Error("Tried to find bill ingredients for " + billGiver + " which has no interaction cell."); - return forPawn.Position; + return billGiver.Position; } private static void AddEveryMedicineToRelevantThings(Pawn pawn, Thing billGiver, List relevantThings, Predicate baseValidator, Map map) @@ -437,7 +416,7 @@ private static void AddEveryMedicineToRelevantThings(Pawn pawn, Thing billGiver, WorkGiver_DoBill.tmpMedicine.Add(thing); } } - WorkGiver_DoBill.tmpMedicine.SortBy((Thing x) => -x.GetStatValue(StatDefOf.MedicalPotency, true), (Thing x) => x.Position.DistanceToSquared(billGiver.Position)); + WorkGiver_DoBill.tmpMedicine.SortBy((Func)((Thing x) => (float)(0.0 - x.GetStatValue(StatDefOf.MedicalPotency, true))), (Func)((Thing x) => x.Position.DistanceToSquared(billGiver.Position))); relevantThings.AddRange(WorkGiver_DoBill.tmpMedicine); WorkGiver_DoBill.tmpMedicine.Clear(); } @@ -461,7 +440,7 @@ private static void MakeIngredientsListInProcessingOrder(List i } for (int i = 0; i < bill.recipe.ingredients.Count; i++) { - if (!bill.recipe.productHasIngredientStuff || i != 0) + if (((!bill.recipe.productHasIngredientStuff) ? 1 : i) != 0) { IngredientCount ingredientCount = bill.recipe.ingredients[i]; if (ingredientCount.IsFixedIngredient) @@ -502,39 +481,31 @@ private static bool TryFindBestBillIngredientsInSet_NoMix(List availableT for (int j = 0; j < WorkGiver_DoBill.availableCounts.Count; j++) { float num = (float)ingredientCount.CountRequiredOfFor(WorkGiver_DoBill.availableCounts.GetDef(j), bill.recipe); - if (num <= WorkGiver_DoBill.availableCounts.GetCount(j)) + if (!(num > WorkGiver_DoBill.availableCounts.GetCount(j)) && ingredientCount.filter.Allows(WorkGiver_DoBill.availableCounts.GetDef(j)) && (ingredientCount.IsFixedIngredient || bill.ingredientFilter.Allows(WorkGiver_DoBill.availableCounts.GetDef(j)))) { - if (ingredientCount.filter.Allows(WorkGiver_DoBill.availableCounts.GetDef(j))) + for (int k = 0; k < availableThings.Count; k++) { - if (ingredientCount.IsFixedIngredient || bill.ingredientFilter.Allows(WorkGiver_DoBill.availableCounts.GetDef(j))) + if (availableThings[k].def == WorkGiver_DoBill.availableCounts.GetDef(j)) { - for (int k = 0; k < availableThings.Count; k++) + int num2 = availableThings[k].stackCount - ThingAmount.CountUsed(chosen, availableThings[k]); + if (num2 > 0) { - if (availableThings[k].def == WorkGiver_DoBill.availableCounts.GetDef(j)) + int num3 = Mathf.Min(Mathf.FloorToInt(num), num2); + ThingAmount.AddToList(chosen, availableThings[k], num3); + num -= (float)num3; + if (num < 0.0010000000474974513) { - int num2 = availableThings[k].stackCount - ThingAmount.CountUsed(chosen, availableThings[k]); - if (num2 > 0) - { - int num3 = Mathf.Min(Mathf.FloorToInt(num), num2); - ThingAmount.AddToList(chosen, availableThings[k], num3); - num -= (float)num3; - if (num < 0.001f) - { - flag = true; - float num4 = WorkGiver_DoBill.availableCounts.GetCount(j); - num4 -= (float)ingredientCount.CountRequiredOfFor(WorkGiver_DoBill.availableCounts.GetDef(j), bill.recipe); - WorkGiver_DoBill.availableCounts.SetCount(j, num4); - break; - } - } + flag = true; + float count = WorkGiver_DoBill.availableCounts.GetCount(j); + count -= (float)ingredientCount.CountRequiredOfFor(WorkGiver_DoBill.availableCounts.GetDef(j), bill.recipe); + WorkGiver_DoBill.availableCounts.SetCount(j, count); + break; } } - if (flag) - { - break; - } } } + if (flag) + break; } } if (!flag) @@ -555,22 +526,17 @@ private static bool TryFindBestBillIngredientsInSet_AllowMix(List availab for (int j = 0; j < availableThings.Count; j++) { Thing thing = availableThings[j]; - if (ingredientCount.filter.Allows(thing)) + if (ingredientCount.filter.Allows(thing) && (ingredientCount.IsFixedIngredient || bill.ingredientFilter.Allows(thing))) { - if (ingredientCount.IsFixedIngredient || bill.ingredientFilter.Allows(thing)) - { - float num2 = bill.recipe.IngredientValueGetter.ValuePerUnitOf(thing.def); - int num3 = Mathf.Min(Mathf.CeilToInt(num / num2), thing.stackCount); - ThingAmount.AddToList(chosen, thing, num3); - num -= (float)num3 * num2; - if (num <= 0.0001f) - { - break; - } - } + float num2 = bill.recipe.IngredientValueGetter.ValuePerUnitOf(thing.def); + int num3 = Mathf.Min(Mathf.CeilToInt(num / num2), thing.stackCount); + ThingAmount.AddToList(chosen, thing, num3); + num -= (float)num3 * num2; + if (num <= 9.9999997473787516E-05) + break; } } - if (num > 0.0001f) + if (num > 9.9999997473787516E-05) { return false; } diff --git a/Assembly-CSharp/RimWorld/WorkGiver_FeedPatient.cs b/Assembly-CSharp/RimWorld/WorkGiver_FeedPatient.cs index 10307ecc3..2db56ba59 100644 --- a/Assembly-CSharp/RimWorld/WorkGiver_FeedPatient.cs +++ b/Assembly-CSharp/RimWorld/WorkGiver_FeedPatient.cs @@ -1,4 +1,3 @@ -using System; using Verse; using Verse.AI; @@ -25,53 +24,52 @@ public override PathEndMode PathEndMode public override bool HasJobOnThing(Pawn pawn, Thing t, bool forced = false) { Pawn pawn2 = t as Pawn; - if (pawn2 == null || pawn2 == pawn) + if (pawn2 != null && pawn2 != pawn) { + if (base.def.feedHumanlikesOnly && !pawn2.RaceProps.Humanlike) + { + return false; + } + if (base.def.feedAnimalsOnly && !pawn2.RaceProps.Animal) + { + return false; + } + if (pawn2.needs.food != null && !(pawn2.needs.food.CurLevelPercentage > pawn2.needs.food.PercentageThreshHungry + 0.019999999552965164)) + { + if (!FeedPatientUtility.ShouldBeFed(pawn2)) + { + return false; + } + if (!pawn.CanReserveAndReach(t, PathEndMode.ClosestTouch, Danger.Deadly, 1, -1, null, forced)) + { + return false; + } + Thing thing = default(Thing); + ThingDef thingDef = default(ThingDef); + if (!FoodUtility.TryFindBestFoodSourceFor(pawn, pawn2, pawn2.needs.food.CurCategory == HungerCategory.Starving, out thing, out thingDef, false, true, false, true, false)) + { + JobFailReason.Is("NoFood".Translate()); + return false; + } + return true; + } return false; } - if (this.def.feedHumanlikesOnly && !pawn2.RaceProps.Humanlike) - { - return false; - } - if (this.def.feedAnimalsOnly && !pawn2.RaceProps.Animal) - { - return false; - } - if (pawn2.needs.food == null || pawn2.needs.food.CurLevelPercentage > pawn2.needs.food.PercentageThreshHungry + 0.02f) - { - return false; - } - if (!FeedPatientUtility.ShouldBeFed(pawn2)) - { - return false; - } - if (!pawn.CanReserveAndReach(t, PathEndMode.ClosestTouch, Danger.Deadly, 1, -1, null, forced)) - { - return false; - } - Thing thing; - ThingDef thingDef; - if (!FoodUtility.TryFindBestFoodSourceFor(pawn, pawn2, pawn2.needs.food.CurCategory == HungerCategory.Starving, out thing, out thingDef, false, true, false, true, false)) - { - JobFailReason.Is("NoFood".Translate()); - return false; - } - return true; + return false; } public override Job JobOnThing(Pawn pawn, Thing t, bool forced = false) { Pawn pawn2 = (Pawn)t; - Thing t2; - ThingDef def; + Thing t2 = default(Thing); + ThingDef def = default(ThingDef); if (FoodUtility.TryFindBestFoodSourceFor(pawn, pawn2, pawn2.needs.food.CurCategory == HungerCategory.Starving, out t2, out def, false, true, false, true, false)) { - return new Job(JobDefOf.FeedPatient) - { - targetA = t2, - targetB = pawn2, - count = FoodUtility.WillIngestStackCountOf(pawn2, def) - }; + Job job = new Job(JobDefOf.FeedPatient); + job.targetA = t2; + job.targetB = (Thing)pawn2; + job.count = FoodUtility.WillIngestStackCountOf(pawn2, def); + return job; } return null; } diff --git a/Assembly-CSharp/RimWorld/WorkGiver_FightFires.cs b/Assembly-CSharp/RimWorld/WorkGiver_FightFires.cs index f55bab3a4..41800d51f 100644 --- a/Assembly-CSharp/RimWorld/WorkGiver_FightFires.cs +++ b/Assembly-CSharp/RimWorld/WorkGiver_FightFires.cs @@ -1,4 +1,3 @@ -using System; using Verse; using Verse.AI; @@ -42,11 +41,11 @@ public override bool HasJobOnThing(Pawn pawn, Thing t, bool forced = false) { return false; } - if ((pawn2.Faction == pawn.Faction || pawn2.HostFaction == pawn.Faction || pawn2.HostFaction == pawn.HostFaction) && !pawn.Map.areaManager.Home[fire.Position] && IntVec3Utility.ManhattanDistanceFlat(pawn.Position, pawn2.Position) > 15) + if ((pawn2.Faction == pawn.Faction || pawn2.HostFaction == pawn.Faction || pawn2.HostFaction == pawn.HostFaction) && !((Area)pawn.Map.areaManager.Home)[fire.Position] && IntVec3Utility.ManhattanDistanceFlat(pawn.Position, pawn2.Position) > 15) { return false; } - if (!pawn.CanReach(pawn2, PathEndMode.Touch, Danger.Deadly, false, TraverseMode.ByPawn)) + if (!pawn.CanReach((Thing)pawn2, PathEndMode.Touch, Danger.Deadly, false, TraverseMode.ByPawn)) { return false; } @@ -57,7 +56,7 @@ public override bool HasJobOnThing(Pawn pawn, Thing t, bool forced = false) { return false; } - if (!pawn.Map.areaManager.Home[fire.Position]) + if (!((Area)pawn.Map.areaManager.Home)[fire.Position]) { JobFailReason.Is(WorkGiver_FixBrokenDownBuilding.NotInHomeAreaTrans); return false; @@ -67,7 +66,15 @@ public override bool HasJobOnThing(Pawn pawn, Thing t, bool forced = false) return false; } } - return ((pawn.Position - fire.Position).LengthHorizontalSquared <= 225 || pawn.CanReserve(fire, 1, -1, null, forced)) && !WorkGiver_FightFires.FireIsBeingHandled(fire, pawn); + if ((pawn.Position - fire.Position).LengthHorizontalSquared > 225 && !pawn.CanReserve((Thing)fire, 1, -1, null, forced)) + { + return false; + } + if (WorkGiver_FightFires.FireIsBeingHandled(fire, pawn)) + { + return false; + } + return true; } public override Job JobOnThing(Pawn pawn, Thing t, bool forced = false) @@ -81,7 +88,7 @@ public static bool FireIsBeingHandled(Fire f, Pawn potentialHandler) { return false; } - Pawn pawn = f.Map.reservationManager.FirstReserverWhoseReservationsRespects(f, potentialHandler); + Pawn pawn = f.Map.reservationManager.FirstReserverWhoseReservationsRespects((Thing)f, potentialHandler); return pawn != null && pawn.Position.InHorDistOf(f.Position, 5f); } } diff --git a/Assembly-CSharp/RimWorld/WorkGiver_FillFermentingBarrel.cs b/Assembly-CSharp/RimWorld/WorkGiver_FillFermentingBarrel.cs index ce868da86..39eec384c 100644 --- a/Assembly-CSharp/RimWorld/WorkGiver_FillFermentingBarrel.cs +++ b/Assembly-CSharp/RimWorld/WorkGiver_FillFermentingBarrel.cs @@ -35,47 +35,58 @@ public static void Reset() public override bool HasJobOnThing(Pawn pawn, Thing t, bool forced = false) { Building_FermentingBarrel building_FermentingBarrel = t as Building_FermentingBarrel; - if (building_FermentingBarrel == null || building_FermentingBarrel.Fermented || building_FermentingBarrel.SpaceLeftForWort <= 0) - { - return false; - } - float ambientTemperature = building_FermentingBarrel.AmbientTemperature; - CompProperties_TemperatureRuinable compProperties = building_FermentingBarrel.def.GetCompProperties(); - if (ambientTemperature < compProperties.minSafeTemperature + 2f || ambientTemperature > compProperties.maxSafeTemperature - 2f) + if (building_FermentingBarrel != null && !building_FermentingBarrel.Fermented && building_FermentingBarrel.SpaceLeftForWort > 0) { + float ambientTemperature = building_FermentingBarrel.AmbientTemperature; + CompProperties_TemperatureRuinable compProperties = building_FermentingBarrel.def.GetCompProperties(); + if (!(ambientTemperature < compProperties.minSafeTemperature + 2.0) && !(ambientTemperature > compProperties.maxSafeTemperature - 2.0)) + { + if (!t.IsForbidden(pawn) && pawn.CanReserveAndReach(t, PathEndMode.Touch, pawn.NormalMaxDanger(), 1, -1, null, forced)) + { + if (pawn.Map.designationManager.DesignationOn(t, DesignationDefOf.Deconstruct) != null) + { + return false; + } + Thing thing = this.FindWort(pawn, building_FermentingBarrel); + if (thing == null) + { + JobFailReason.Is(WorkGiver_FillFermentingBarrel.NoWortTrans); + return false; + } + if (t.IsBurning()) + { + return false; + } + return true; + } + return false; + } JobFailReason.Is(WorkGiver_FillFermentingBarrel.TemperatureTrans); return false; } - if (t.IsForbidden(pawn) || !pawn.CanReserveAndReach(t, PathEndMode.Touch, pawn.NormalMaxDanger(), 1, -1, null, forced)) - { - return false; - } - if (pawn.Map.designationManager.DesignationOn(t, DesignationDefOf.Deconstruct) != null) - { - return false; - } - if (this.FindWort(pawn, building_FermentingBarrel) == null) - { - JobFailReason.Is(WorkGiver_FillFermentingBarrel.NoWortTrans); - return false; - } - return !t.IsBurning(); + return false; } public override Job JobOnThing(Pawn pawn, Thing t, bool forced = false) { Building_FermentingBarrel building_FermentingBarrel = (Building_FermentingBarrel)t; Thing t2 = this.FindWort(pawn, building_FermentingBarrel); - return new Job(JobDefOf.FillFermentingBarrel, t, t2) - { - count = building_FermentingBarrel.SpaceLeftForWort - }; + Job job = new Job(JobDefOf.FillFermentingBarrel, t, t2); + job.count = building_FermentingBarrel.SpaceLeftForWort; + return job; } private Thing FindWort(Pawn pawn, Building_FermentingBarrel barrel) { - Predicate predicate = (Thing x) => !x.IsForbidden(pawn) && pawn.CanReserve(x, 1, -1, null, false); - Predicate validator = predicate; + Predicate validator; + Predicate predicate = validator = (Predicate)delegate(Thing x) + { + if (!x.IsForbidden(pawn) && pawn.CanReserve(x, 1, -1, null, false)) + { + return true; + } + return false; + }; return GenClosest.ClosestThingReachable(pawn.Position, pawn.Map, ThingRequest.ForDef(ThingDefOf.Wort), PathEndMode.ClosestTouch, TraverseParms.For(pawn, Danger.Deadly, TraverseMode.ByPawn, false), 9999f, validator, null, 0, -1, false, RegionType.Set_Passable, false); } } diff --git a/Assembly-CSharp/RimWorld/WorkGiver_FixBrokenDownBuilding.cs b/Assembly-CSharp/RimWorld/WorkGiver_FixBrokenDownBuilding.cs index 467a38fc0..d80144169 100644 --- a/Assembly-CSharp/RimWorld/WorkGiver_FixBrokenDownBuilding.cs +++ b/Assembly-CSharp/RimWorld/WorkGiver_FixBrokenDownBuilding.cs @@ -66,12 +66,12 @@ public override bool HasJobOnThing(Pawn pawn, Thing t, bool forced = false) { return false; } - if (pawn.Faction == Faction.OfPlayer && !pawn.Map.areaManager.Home[t.Position]) + if (pawn.Faction == Faction.OfPlayer && !((Area)pawn.Map.areaManager.Home)[t.Position]) { JobFailReason.Is(WorkGiver_FixBrokenDownBuilding.NotInHomeAreaTrans); return false; } - if (!pawn.CanReserve(building, 1, -1, null, forced)) + if (!pawn.CanReserve((Thing)building, 1, -1, null, forced)) { return false; } @@ -83,7 +83,8 @@ public override bool HasJobOnThing(Pawn pawn, Thing t, bool forced = false) { return false; } - if (this.FindClosestComponent(pawn) == null) + Thing thing = this.FindClosestComponent(pawn); + if (thing == null) { JobFailReason.Is(WorkGiver_FixBrokenDownBuilding.NoComponentsToRepairTrans); return false; @@ -94,15 +95,14 @@ public override bool HasJobOnThing(Pawn pawn, Thing t, bool forced = false) public override Job JobOnThing(Pawn pawn, Thing t, bool forced = false) { Thing t2 = this.FindClosestComponent(pawn); - return new Job(JobDefOf.FixBrokenDownBuilding, t, t2) - { - count = 1 - }; + Job job = new Job(JobDefOf.FixBrokenDownBuilding, t, t2); + job.count = 1; + return job; } private Thing FindClosestComponent(Pawn pawn) { - Predicate validator = (Thing x) => !x.IsForbidden(pawn) && pawn.CanReserve(x, 1, -1, null, false); + Predicate validator = (Predicate)((Thing x) => !x.IsForbidden(pawn) && pawn.CanReserve(x, 1, -1, null, false)); return GenClosest.ClosestThingReachable(pawn.Position, pawn.Map, ThingRequest.ForDef(ThingDefOf.Component), PathEndMode.InteractionCell, TraverseParms.For(pawn, pawn.NormalMaxDanger(), TraverseMode.ByPawn, false), 9999f, validator, null, 0, -1, false, RegionType.Set_Passable, false); } } diff --git a/Assembly-CSharp/RimWorld/WorkGiver_Flick.cs b/Assembly-CSharp/RimWorld/WorkGiver_Flick.cs index f0c763372..b37e5a082 100644 --- a/Assembly-CSharp/RimWorld/WorkGiver_Flick.cs +++ b/Assembly-CSharp/RimWorld/WorkGiver_Flick.cs @@ -1,6 +1,4 @@ -using System; using System.Collections.Generic; -using System.Diagnostics; using Verse; using Verse.AI; @@ -8,20 +6,29 @@ namespace RimWorld { public class WorkGiver_Flick : WorkGiver_Scanner { - [DebuggerHidden] public override IEnumerable PotentialWorkThingsGlobal(Pawn pawn) { - WorkGiver_Flick.c__Iterator67 c__Iterator = new WorkGiver_Flick.c__Iterator67(); - c__Iterator.pawn = pawn; - c__Iterator.<$>pawn = pawn; - WorkGiver_Flick.c__Iterator67 expr_15 = c__Iterator; - expr_15.$PC = -2; - return expr_15; + List desList = pawn.Map.designationManager.allDesignations; + for (int i = 0; i < desList.Count; i++) + { + if (desList[i].def == DesignationDefOf.Flick) + { + yield return desList[i].target.Thing; + } + } } public override bool HasJobOnThing(Pawn pawn, Thing t, bool forced = false) { - return pawn.Map.designationManager.DesignationOn(t, DesignationDefOf.Flick) != null && pawn.CanReserveAndReach(t, PathEndMode.Touch, pawn.NormalMaxDanger(), 1, -1, null, forced); + if (pawn.Map.designationManager.DesignationOn(t, DesignationDefOf.Flick) == null) + { + return false; + } + if (!pawn.CanReserveAndReach(t, PathEndMode.Touch, pawn.NormalMaxDanger(), 1, -1, null, forced)) + { + return false; + } + return true; } public override Job JobOnThing(Pawn pawn, Thing t, bool forced = false) diff --git a/Assembly-CSharp/RimWorld/WorkGiver_GatherAnimalBodyResources.cs b/Assembly-CSharp/RimWorld/WorkGiver_GatherAnimalBodyResources.cs index fe2e81f7b..f889a7ff7 100644 --- a/Assembly-CSharp/RimWorld/WorkGiver_GatherAnimalBodyResources.cs +++ b/Assembly-CSharp/RimWorld/WorkGiver_GatherAnimalBodyResources.cs @@ -1,6 +1,4 @@ -using System; using System.Collections.Generic; -using System.Diagnostics; using Verse; using Verse.AI; @@ -23,21 +21,23 @@ public override PathEndMode PathEndMode protected abstract CompHasGatherableBodyResource GetComp(Pawn animal); - [DebuggerHidden] public override IEnumerable PotentialWorkThingsGlobal(Pawn pawn) { - WorkGiver_GatherAnimalBodyResources.c__Iterator59 c__Iterator = new WorkGiver_GatherAnimalBodyResources.c__Iterator59(); - c__Iterator.pawn = pawn; - c__Iterator.<$>pawn = pawn; - WorkGiver_GatherAnimalBodyResources.c__Iterator59 expr_15 = c__Iterator; - expr_15.$PC = -2; - return expr_15; + List pawns = pawn.Map.mapPawns.SpawnedPawnsInFaction(pawn.Faction); + for (int i = 0; i < pawns.Count; i++) + { + yield return (Thing)pawns[i]; + } } public override bool HasJobOnThing(Pawn pawn, Thing t, bool forced = false) { Pawn pawn2 = t as Pawn; - return pawn2 != null && pawn2.RaceProps.Animal && !pawn2.Downed && pawn2.CanCasuallyInteractNow(false) && this.GetComp(pawn2) != null && this.GetComp(pawn2).ActiveAndFull && pawn.CanReserve(pawn2, 1, -1, null, forced); + if (pawn2 != null && pawn2.RaceProps.Animal && !pawn2.Downed && pawn2.CanCasuallyInteractNow(false) && this.GetComp(pawn2) != null && this.GetComp(pawn2).ActiveAndFull && pawn.CanReserve((Thing)pawn2, 1, -1, null, forced)) + { + return true; + } + return false; } public override Job JobOnThing(Pawn pawn, Thing t, bool forced = false) diff --git a/Assembly-CSharp/RimWorld/WorkGiver_Grower.cs b/Assembly-CSharp/RimWorld/WorkGiver_Grower.cs index ad1cdac39..02d93b531 100644 --- a/Assembly-CSharp/RimWorld/WorkGiver_Grower.cs +++ b/Assembly-CSharp/RimWorld/WorkGiver_Grower.cs @@ -1,7 +1,6 @@ -using System; using System.Collections.Generic; -using System.Diagnostics; using Verse; +using Verse.AI; namespace RimWorld { @@ -14,16 +13,46 @@ protected virtual bool ExtraRequirements(IPlantToGrowSettable settable, Pawn paw return true; } - [DebuggerHidden] public override IEnumerable PotentialWorkCellsGlobal(Pawn pawn) { - WorkGiver_Grower.c__Iterator5F c__Iterator5F = new WorkGiver_Grower.c__Iterator5F(); - c__Iterator5F.pawn = pawn; - c__Iterator5F.<$>pawn = pawn; - c__Iterator5F.<>f__this = this; - WorkGiver_Grower.c__Iterator5F expr_1C = c__Iterator5F; - expr_1C.$PC = -2; - return expr_1C; + Danger maxDanger = pawn.NormalMaxDanger(); + List bList = pawn.Map.listerBuildings.allBuildingsColonist; + for (int k = 0; k < bList.Count; k++) + { + Building_PlantGrower b = bList[k] as Building_PlantGrower; + if (b != null && this.ExtraRequirements(b, pawn) && !b.IsForbidden(pawn) && pawn.CanReach((Thing)b, PathEndMode.OnCell, maxDanger, false, TraverseMode.ByPawn) && !b.IsBurning()) + { + CellRect.CellRectIterator cri = b.OccupiedRect().GetIterator(); + while (!cri.Done()) + { + yield return cri.Current; + cri.MoveNext(); + } + WorkGiver_Grower.wantedPlantDef = null; + } + } + WorkGiver_Grower.wantedPlantDef = null; + List zonesList = pawn.Map.zoneManager.AllZones; + for (int j = 0; j < zonesList.Count; j++) + { + Zone_Growing growZone = zonesList[j] as Zone_Growing; + if (growZone != null) + { + if (growZone.cells.Count == 0) + { + Log.ErrorOnce("Grow zone has 0 cells: " + growZone, -563487); + } + else if (this.ExtraRequirements(growZone, pawn) && !growZone.ContainsStaticFire && pawn.CanReach(growZone.Cells[0], PathEndMode.OnCell, maxDanger, false, TraverseMode.ByPawn)) + { + for (int i = 0; i < growZone.cells.Count; i++) + { + yield return growZone.cells[i]; + } + WorkGiver_Grower.wantedPlantDef = null; + } + } + } + WorkGiver_Grower.wantedPlantDef = null; } public static ThingDef CalculateWantedPlantDef(IntVec3 c, Map map) diff --git a/Assembly-CSharp/RimWorld/WorkGiver_GrowerHarvest.cs b/Assembly-CSharp/RimWorld/WorkGiver_GrowerHarvest.cs index ab50708a1..f3c741bd1 100644 --- a/Assembly-CSharp/RimWorld/WorkGiver_GrowerHarvest.cs +++ b/Assembly-CSharp/RimWorld/WorkGiver_GrowerHarvest.cs @@ -17,7 +17,23 @@ public override PathEndMode PathEndMode public override bool HasJobOnCell(Pawn pawn, IntVec3 c) { Plant plant = c.GetPlant(pawn.Map); - return plant != null && !plant.IsForbidden(pawn) && plant.def.plant.Harvestable && plant.LifeStage == PlantLifeStage.Mature && pawn.CanReserve(plant, 1, -1, null, false); + if (plant == null) + { + return false; + } + if (plant.IsForbidden(pawn)) + { + return false; + } + if (plant.def.plant.Harvestable && plant.LifeStage == PlantLifeStage.Mature) + { + if (!pawn.CanReserve((Thing)plant, 1, -1, null, false)) + { + return false; + } + return true; + } + return false; } public override Job JobOnCell(Pawn pawn, IntVec3 c) @@ -29,23 +45,21 @@ public override Job JobOnCell(Pawn pawn, IntVec3 c) for (int i = 0; i < 40; i++) { IntVec3 c2 = c + GenRadial.RadialPattern[i]; - if (c.GetRoom(map, RegionType.Set_Passable) == room) + if (c.GetRoom(map, RegionType.Set_Passable) == room && this.HasJobOnCell(pawn, c2)) { - if (this.HasJobOnCell(pawn, c2)) + Plant plant = c2.GetPlant(map); + num += plant.def.plant.harvestWork; + if (!(num > 2400.0)) { - Plant plant = c2.GetPlant(map); - num += plant.def.plant.harvestWork; - if (num > 2400f) - { - break; - } - job.AddQueuedTarget(TargetIndex.A, plant); + job.AddQueuedTarget(TargetIndex.A, (Thing)plant); + continue; } + break; } } if (job.targetQueueA != null && job.targetQueueA.Count >= 3) { - job.targetQueueA.SortBy((LocalTargetInfo targ) => targ.Cell.DistanceToSquared(pawn.Position)); + job.targetQueueA.SortBy((Func)((LocalTargetInfo targ) => targ.Cell.DistanceToSquared(pawn.Position))); } return job; } diff --git a/Assembly-CSharp/RimWorld/WorkGiver_GrowerSow.cs b/Assembly-CSharp/RimWorld/WorkGiver_GrowerSow.cs index 278138a48..b40701f35 100644 --- a/Assembly-CSharp/RimWorld/WorkGiver_GrowerSow.cs +++ b/Assembly-CSharp/RimWorld/WorkGiver_GrowerSow.cs @@ -1,4 +1,3 @@ -using System; using System.Collections.Generic; using Verse; using Verse.AI; @@ -36,7 +35,11 @@ protected override bool ExtraRequirements(IPlantToGrowSettable settable, Pawn pa c = ((Thing)settable).Position; } WorkGiver_Grower.wantedPlantDef = WorkGiver_Grower.CalculateWantedPlantDef(c, pawn.Map); - return WorkGiver_Grower.wantedPlantDef != null; + if (WorkGiver_Grower.wantedPlantDef == null) + { + return false; + } + return true; } public override Job JobOnCell(Pawn pawn, IntVec3 c) @@ -73,73 +76,64 @@ public override Job JobOnCell(Pawn pawn, IntVec3 c) Plant plant = c.GetPlant(pawn.Map); if (plant != null && plant.def.plant.blockAdjacentSow) { - if (!pawn.CanReserve(plant, 1, -1, null, false) || plant.IsForbidden(pawn)) + if (pawn.CanReserve((Thing)plant, 1, -1, null, false) && !plant.IsForbidden(pawn)) { - return null; + return new Job(JobDefOf.CutPlant, (Thing)plant); } - return new Job(JobDefOf.CutPlant, plant); + return null; } - else + Thing thing2 = GenPlant.AdjacentSowBlocker(WorkGiver_Grower.wantedPlantDef, c, pawn.Map); + if (thing2 != null) { - Thing thing2 = GenPlant.AdjacentSowBlocker(WorkGiver_Grower.wantedPlantDef, c, pawn.Map); - if (thing2 != null) + Plant plant2 = thing2 as Plant; + if (plant2 != null && pawn.CanReserve((Thing)plant2, 1, -1, null, false) && !plant2.IsForbidden(pawn)) { - Plant plant2 = thing2 as Plant; - if (plant2 != null && pawn.CanReserve(plant2, 1, -1, null, false) && !plant2.IsForbidden(pawn)) + IPlantToGrowSettable plantToGrowSettable = plant2.Position.GetPlantToGrowSettable(plant2.Map); + if (plantToGrowSettable != null && plantToGrowSettable.GetPlantDefToGrow() == plant2.def) { - IPlantToGrowSettable plantToGrowSettable = plant2.Position.GetPlantToGrowSettable(plant2.Map); - if (plantToGrowSettable == null || plantToGrowSettable.GetPlantDefToGrow() != plant2.def) - { - return new Job(JobDefOf.CutPlant, plant2); - } + goto IL_0199; } - return null; + return new Job(JobDefOf.CutPlant, (Thing)plant2); } - if (WorkGiver_Grower.wantedPlantDef.plant.sowMinSkill > 0 && pawn.skills != null && pawn.skills.GetSkill(SkillDefOf.Growing).Level < WorkGiver_Grower.wantedPlantDef.plant.sowMinSkill) - { - return null; - } - int j = 0; - while (j < thingList.Count) + goto IL_0199; + } + if (WorkGiver_Grower.wantedPlantDef.plant.sowMinSkill > 0 && pawn.skills != null && pawn.skills.GetSkill(SkillDefOf.Growing).Level < WorkGiver_Grower.wantedPlantDef.plant.sowMinSkill) + { + return null; + } + for (int j = 0; j < thingList.Count; j++) + { + Thing thing3 = thingList[j]; + if (thing3.def.BlockPlanting) { - Thing thing3 = thingList[j]; - if (thing3.def.BlockPlanting) + if (!pawn.CanReserve(thing3, 1, -1, null, false)) { - if (!pawn.CanReserve(thing3, 1, -1, null, false)) - { - return null; - } - if (thing3.def.category == ThingCategory.Plant) - { - if (!thing3.IsForbidden(pawn)) - { - return new Job(JobDefOf.CutPlant, thing3); - } - return null; - } - else + return null; + } + if (thing3.def.category == ThingCategory.Plant) + { + if (!thing3.IsForbidden(pawn)) { - if (thing3.def.EverHaulable) - { - return HaulAIUtility.HaulAsideJobFor(pawn, thing3); - } - return null; + return new Job(JobDefOf.CutPlant, thing3); } + return null; } - else + if (thing3.def.EverHaulable) { - j++; + return HaulAIUtility.HaulAsideJobFor(pawn, thing3); } - } - if (!WorkGiver_Grower.wantedPlantDef.CanEverPlantAt(c, pawn.Map) || !GenPlant.GrowthSeasonNow(c, pawn.Map) || !pawn.CanReserve(c, 1, -1, null, false)) - { return null; } - return new Job(JobDefOf.Sow, c) - { - plantDefToSow = WorkGiver_Grower.wantedPlantDef - }; } + if (WorkGiver_Grower.wantedPlantDef.CanEverPlantAt(c, pawn.Map) && GenPlant.GrowthSeasonNow(c, pawn.Map) && pawn.CanReserve(c, 1, -1, null, false)) + { + Job job = new Job(JobDefOf.Sow, c); + job.plantDefToSow = WorkGiver_Grower.wantedPlantDef; + return job; + } + return null; + IL_0199: + return null; } } } diff --git a/Assembly-CSharp/RimWorld/WorkGiver_Haul.cs b/Assembly-CSharp/RimWorld/WorkGiver_Haul.cs index 09bbfc880..0ca43cd9e 100644 --- a/Assembly-CSharp/RimWorld/WorkGiver_Haul.cs +++ b/Assembly-CSharp/RimWorld/WorkGiver_Haul.cs @@ -1,4 +1,3 @@ -using System; using Verse; using Verse.AI; diff --git a/Assembly-CSharp/RimWorld/WorkGiver_HaulCorpses.cs b/Assembly-CSharp/RimWorld/WorkGiver_HaulCorpses.cs index edaca105d..30ef86436 100644 --- a/Assembly-CSharp/RimWorld/WorkGiver_HaulCorpses.cs +++ b/Assembly-CSharp/RimWorld/WorkGiver_HaulCorpses.cs @@ -1,4 +1,3 @@ -using System; using System.Collections.Generic; using Verse; using Verse.AI; diff --git a/Assembly-CSharp/RimWorld/WorkGiver_HaulGeneral.cs b/Assembly-CSharp/RimWorld/WorkGiver_HaulGeneral.cs index f8249e87e..d64160ca4 100644 --- a/Assembly-CSharp/RimWorld/WorkGiver_HaulGeneral.cs +++ b/Assembly-CSharp/RimWorld/WorkGiver_HaulGeneral.cs @@ -1,4 +1,3 @@ -using System; using System.Collections.Generic; using Verse; using Verse.AI; diff --git a/Assembly-CSharp/RimWorld/WorkGiver_HelpGatheringItemsForCaravan.cs b/Assembly-CSharp/RimWorld/WorkGiver_HelpGatheringItemsForCaravan.cs index 3b682702e..29b832772 100644 --- a/Assembly-CSharp/RimWorld/WorkGiver_HelpGatheringItemsForCaravan.cs +++ b/Assembly-CSharp/RimWorld/WorkGiver_HelpGatheringItemsForCaravan.cs @@ -1,4 +1,3 @@ -using System; using System.Collections.Generic; using Verse; using Verse.AI; @@ -17,15 +16,11 @@ public override Job NonScanJob(Pawn pawn) if (lordJob_FormAndSendCaravan != null && lordJob_FormAndSendCaravan.GatheringItemsNow) { Thing thing = GatherItemsForCaravanUtility.FindThingToHaul(pawn, lords[i]); - if (thing != null) + if (thing != null && this.AnyReachableCarrierOrColonist(pawn, lords[i])) { - if (this.AnyReachableCarrierOrColonist(pawn, lords[i])) - { - return new Job(JobDefOf.PrepareCaravan_GatherItems, thing) - { - lord = lords[i] - }; - } + Job job = new Job(JobDefOf.PrepareCaravan_GatherItems, thing); + job.lord = lords[i]; + return job; } } } @@ -36,15 +31,9 @@ private bool AnyReachableCarrierOrColonist(Pawn forPawn, Lord lord) { for (int i = 0; i < lord.ownedPawns.Count; i++) { - if (JobDriver_PrepareCaravan_GatherItems.IsUsableCarrier(lord.ownedPawns[i], forPawn, false)) + if (JobDriver_PrepareCaravan_GatherItems.IsUsableCarrier(lord.ownedPawns[i], forPawn, false) && !lord.ownedPawns[i].IsForbidden(forPawn) && forPawn.CanReach((Thing)lord.ownedPawns[i], PathEndMode.Touch, Danger.Deadly, false, TraverseMode.ByPawn)) { - if (!lord.ownedPawns[i].IsForbidden(forPawn)) - { - if (forPawn.CanReach(lord.ownedPawns[i], PathEndMode.Touch, Danger.Deadly, false, TraverseMode.ByPawn)) - { - return true; - } - } + return true; } } return false; diff --git a/Assembly-CSharp/RimWorld/WorkGiver_HunterHunt.cs b/Assembly-CSharp/RimWorld/WorkGiver_HunterHunt.cs index 8ce8e3341..74c399200 100644 --- a/Assembly-CSharp/RimWorld/WorkGiver_HunterHunt.cs +++ b/Assembly-CSharp/RimWorld/WorkGiver_HunterHunt.cs @@ -1,6 +1,4 @@ -using System; using System.Collections.Generic; -using System.Diagnostics; using Verse; using Verse.AI; @@ -16,26 +14,43 @@ public override PathEndMode PathEndMode } } - [DebuggerHidden] public override IEnumerable PotentialWorkThingsGlobal(Pawn pawn) { - WorkGiver_HunterHunt.c__Iterator60 c__Iterator = new WorkGiver_HunterHunt.c__Iterator60(); - c__Iterator.pawn = pawn; - c__Iterator.<$>pawn = pawn; - WorkGiver_HunterHunt.c__Iterator60 expr_15 = c__Iterator; - expr_15.$PC = -2; - return expr_15; + foreach (Designation item in pawn.Map.designationManager.SpawnedDesignationsOfDef(DesignationDefOf.Hunt)) + { + yield return item.target.Thing; + } } public override bool ShouldSkip(Pawn pawn) { - return !WorkGiver_HunterHunt.HasHuntingWeapon(pawn) || WorkGiver_HunterHunt.HasShieldAndRangedWeapon(pawn); + if (!WorkGiver_HunterHunt.HasHuntingWeapon(pawn)) + { + return true; + } + if (WorkGiver_HunterHunt.HasShieldAndRangedWeapon(pawn)) + { + return true; + } + return false; } public override bool HasJobOnThing(Pawn pawn, Thing t, bool forced = false) { Pawn pawn2 = t as Pawn; - return pawn2 != null && pawn2.RaceProps.Animal && pawn.CanReserve(t, 1, -1, null, forced) && pawn.Map.designationManager.DesignationOn(t, DesignationDefOf.Hunt) != null; + if (pawn2 != null && pawn2.RaceProps.Animal) + { + if (!pawn.CanReserve(t, 1, -1, null, forced)) + { + return false; + } + if (pawn.Map.designationManager.DesignationOn(t, DesignationDefOf.Hunt) == null) + { + return false; + } + return true; + } + return false; } public override Job JobOnThing(Pawn pawn, Thing t, bool forced = false) @@ -45,7 +60,11 @@ public override Job JobOnThing(Pawn pawn, Thing t, bool forced = false) public static bool HasHuntingWeapon(Pawn p) { - return p.equipment.Primary != null && p.equipment.Primary.def.IsRangedWeapon; + if (p.equipment.Primary != null && p.equipment.Primary.def.IsRangedWeapon) + { + return true; + } + return false; } public static bool HasShieldAndRangedWeapon(Pawn p) diff --git a/Assembly-CSharp/RimWorld/WorkGiver_InteractAnimal.cs b/Assembly-CSharp/RimWorld/WorkGiver_InteractAnimal.cs index f93805e1f..012ca6d0e 100644 --- a/Assembly-CSharp/RimWorld/WorkGiver_InteractAnimal.cs +++ b/Assembly-CSharp/RimWorld/WorkGiver_InteractAnimal.cs @@ -1,4 +1,3 @@ -using System; using UnityEngine; using Verse; using Verse.AI; @@ -30,7 +29,7 @@ public static void Reset() protected virtual bool CanInteractWithAnimal(Pawn pawn, Pawn animal) { - if (!pawn.CanReserve(animal, 1, -1, null, false)) + if (!pawn.CanReserve((Thing)animal, 1, -1, null, false)) { return false; } @@ -59,7 +58,7 @@ protected bool HasFoodToInteractAnimal(Pawn pawn, Pawn tamee) for (int i = 0; i < innerContainer.Count; i++) { Thing thing = innerContainer[i]; - if (tamee.RaceProps.CanEverEat(thing) && thing.def.ingestible.preferability <= FoodPreferability.RawTasty && !thing.def.IsDrug) + if (tamee.RaceProps.CanEverEat(thing) && (int)thing.def.ingestible.preferability <= 4 && !thing.def.IsDrug) { for (int j = 0; j < thing.stackCount; j++) { @@ -81,16 +80,15 @@ protected bool HasFoodToInteractAnimal(Pawn pawn, Pawn tamee) protected Job TakeFoodForAnimalInteractJob(Pawn pawn, Pawn tamee) { - float num = JobDriver_InteractAnimal.RequiredNutritionPerFeed(tamee) * 2f * 4f; + float num = (float)(JobDriver_InteractAnimal.RequiredNutritionPerFeed(tamee) * 2.0 * 4.0); Thing thing = FoodUtility.BestFoodSourceOnMap(pawn, tamee, false, FoodPreferability.RawTasty, false, false, false, false, false, false, false); if (thing == null) { return null; } - return new Job(JobDefOf.TakeInventory, thing) - { - count = Mathf.CeilToInt(num / thing.def.ingestible.nutrition) - }; + Job job = new Job(JobDefOf.TakeInventory, thing); + job.count = Mathf.CeilToInt(num / thing.def.ingestible.nutrition); + return job; } } } diff --git a/Assembly-CSharp/RimWorld/WorkGiver_LoadTransporters.cs b/Assembly-CSharp/RimWorld/WorkGiver_LoadTransporters.cs index ee3735df1..35e21f6bf 100644 --- a/Assembly-CSharp/RimWorld/WorkGiver_LoadTransporters.cs +++ b/Assembly-CSharp/RimWorld/WorkGiver_LoadTransporters.cs @@ -1,4 +1,3 @@ -using System; using Verse; using Verse.AI; diff --git a/Assembly-CSharp/RimWorld/WorkGiver_Milk.cs b/Assembly-CSharp/RimWorld/WorkGiver_Milk.cs index de7674103..c6863f93e 100644 --- a/Assembly-CSharp/RimWorld/WorkGiver_Milk.cs +++ b/Assembly-CSharp/RimWorld/WorkGiver_Milk.cs @@ -1,4 +1,3 @@ -using System; using Verse; namespace RimWorld diff --git a/Assembly-CSharp/RimWorld/WorkGiver_Miner.cs b/Assembly-CSharp/RimWorld/WorkGiver_Miner.cs index 671ea5823..b9b9909e2 100644 --- a/Assembly-CSharp/RimWorld/WorkGiver_Miner.cs +++ b/Assembly-CSharp/RimWorld/WorkGiver_Miner.cs @@ -1,6 +1,4 @@ -using System; using System.Collections.Generic; -using System.Diagnostics; using Verse; using Verse.AI; @@ -16,15 +14,29 @@ public override PathEndMode PathEndMode } } - [DebuggerHidden] public override IEnumerable PotentialWorkThingsGlobal(Pawn pawn) { - WorkGiver_Miner.c__Iterator61 c__Iterator = new WorkGiver_Miner.c__Iterator61(); - c__Iterator.pawn = pawn; - c__Iterator.<$>pawn = pawn; - WorkGiver_Miner.c__Iterator61 expr_15 = c__Iterator; - expr_15.$PC = -2; - return expr_15; + foreach (Designation item in pawn.Map.designationManager.SpawnedDesignationsOfDef(DesignationDefOf.Mine)) + { + bool mayBeAccessible = false; + for (int j = 0; j < 8; j++) + { + IntVec3 c = item.target.Cell + GenAdj.AdjacentCells[j]; + if (c.InBounds(pawn.Map) && c.Walkable(pawn.Map)) + { + mayBeAccessible = true; + break; + } + } + if (mayBeAccessible) + { + Thing i = MineUtility.MineableInCell(item.target.Cell, pawn.Map); + if (i != null) + { + yield return i; + } + } + } } public override Job JobOnThing(Pawn pawn, Thing t, bool forced = false) @@ -56,18 +68,12 @@ public override Job JobOnThing(Pawn pawn, Thing t, bool forced = false) for (int j = 0; j < 8; j++) { IntVec3 intVec2 = t.Position + GenAdj.AdjacentCells[j]; - if (intVec2.InBounds(t.Map)) + if (intVec2.InBounds(t.Map) && ReachabilityImmediate.CanReachImmediate(intVec2, t, pawn.Map, PathEndMode.Touch, pawn) && intVec2.Walkable(t.Map) && !intVec2.Standable(t.Map)) { - if (ReachabilityImmediate.CanReachImmediate(intVec2, t, pawn.Map, PathEndMode.Touch, pawn)) + Thing firstHaulable = intVec2.GetFirstHaulable(t.Map); + if (firstHaulable != null && firstHaulable.def.passability == Traversability.PassThroughOnly) { - if (intVec2.Walkable(t.Map) && !intVec2.Standable(t.Map)) - { - Thing firstHaulable = intVec2.GetFirstHaulable(t.Map); - if (firstHaulable != null && firstHaulable.def.passability == Traversability.PassThroughOnly) - { - return HaulAIUtility.HaulAsideJobFor(pawn, firstHaulable); - } - } + return HaulAIUtility.HaulAsideJobFor(pawn, firstHaulable); } } } diff --git a/Assembly-CSharp/RimWorld/WorkGiver_Open.cs b/Assembly-CSharp/RimWorld/WorkGiver_Open.cs index bca09af4a..efbad5404 100644 --- a/Assembly-CSharp/RimWorld/WorkGiver_Open.cs +++ b/Assembly-CSharp/RimWorld/WorkGiver_Open.cs @@ -1,6 +1,4 @@ -using System; using System.Collections.Generic; -using System.Diagnostics; using Verse; using Verse.AI; @@ -16,20 +14,25 @@ public override PathEndMode PathEndMode } } - [DebuggerHidden] public override IEnumerable PotentialWorkThingsGlobal(Pawn pawn) { - WorkGiver_Open.c__Iterator62 c__Iterator = new WorkGiver_Open.c__Iterator62(); - c__Iterator.pawn = pawn; - c__Iterator.<$>pawn = pawn; - WorkGiver_Open.c__Iterator62 expr_15 = c__Iterator; - expr_15.$PC = -2; - return expr_15; + foreach (Designation item in pawn.Map.designationManager.SpawnedDesignationsOfDef(DesignationDefOf.Open)) + { + yield return item.target.Thing; + } } public override bool HasJobOnThing(Pawn pawn, Thing t, bool forced = false) { - return pawn.Map.designationManager.DesignationOn(t, DesignationDefOf.Open) != null && pawn.CanReserve(t, 1, -1, null, forced); + if (pawn.Map.designationManager.DesignationOn(t, DesignationDefOf.Open) == null) + { + return false; + } + if (!pawn.CanReserve(t, 1, -1, null, forced)) + { + return false; + } + return true; } public override Job JobOnThing(Pawn pawn, Thing t, bool forced = false) diff --git a/Assembly-CSharp/RimWorld/WorkGiver_PatientGoToBedEmergency.cs b/Assembly-CSharp/RimWorld/WorkGiver_PatientGoToBedEmergency.cs index 8594014e7..21c4ec714 100644 --- a/Assembly-CSharp/RimWorld/WorkGiver_PatientGoToBedEmergency.cs +++ b/Assembly-CSharp/RimWorld/WorkGiver_PatientGoToBedEmergency.cs @@ -1,4 +1,3 @@ -using System; using Verse; using Verse.AI; diff --git a/Assembly-CSharp/RimWorld/WorkGiver_PatientGoToBedRecuperate.cs b/Assembly-CSharp/RimWorld/WorkGiver_PatientGoToBedRecuperate.cs index 31a0a9e39..a24b886ea 100644 --- a/Assembly-CSharp/RimWorld/WorkGiver_PatientGoToBedRecuperate.cs +++ b/Assembly-CSharp/RimWorld/WorkGiver_PatientGoToBedRecuperate.cs @@ -1,4 +1,3 @@ -using System; using Verse; using Verse.AI; diff --git a/Assembly-CSharp/RimWorld/WorkGiver_PlantsCut.cs b/Assembly-CSharp/RimWorld/WorkGiver_PlantsCut.cs index f0e544004..741f56b9e 100644 --- a/Assembly-CSharp/RimWorld/WorkGiver_PlantsCut.cs +++ b/Assembly-CSharp/RimWorld/WorkGiver_PlantsCut.cs @@ -1,6 +1,4 @@ -using System; using System.Collections.Generic; -using System.Diagnostics; using Verse; using Verse.AI; @@ -16,15 +14,17 @@ public override PathEndMode PathEndMode } } - [DebuggerHidden] public override IEnumerable PotentialWorkThingsGlobal(Pawn pawn) { - WorkGiver_PlantsCut.c__Iterator63 c__Iterator = new WorkGiver_PlantsCut.c__Iterator63(); - c__Iterator.pawn = pawn; - c__Iterator.<$>pawn = pawn; - WorkGiver_PlantsCut.c__Iterator63 expr_15 = c__Iterator; - expr_15.$PC = -2; - return expr_15; + List desList = pawn.Map.designationManager.allDesignations; + for (int i = 0; i < desList.Count; i++) + { + Designation des = desList[i]; + if (des.def == DesignationDefOf.CutPlant || des.def == DesignationDefOf.HarvestPlant) + { + yield return des.target.Thing; + } + } } public override Job JobOnThing(Pawn pawn, Thing t, bool forced = false) @@ -45,24 +45,26 @@ public override Job JobOnThing(Pawn pawn, Thing t, bool forced = false) { return null; } - foreach (Designation current in pawn.Map.designationManager.AllDesignationsOn(t)) + using (IEnumerator enumerator = pawn.Map.designationManager.AllDesignationsOn(t).GetEnumerator()) { - if (current.def == DesignationDefOf.HarvestPlant) + while (enumerator.MoveNext()) { - Job result; - if (!((Plant)t).HarvestableNow) + Designation current = enumerator.Current; + if (current.def == DesignationDefOf.HarvestPlant) + goto IL_0078; + if (current.def == DesignationDefOf.CutPlant) { - result = null; - return result; + return new Job(JobDefOf.CutPlant, t); } - result = new Job(JobDefOf.Harvest, t); - return result; } - else if (current.def == DesignationDefOf.CutPlant) + goto end_IL_005c; + IL_0078: + if (!((Plant)t).HarvestableNow) { - Job result = new Job(JobDefOf.CutPlant, t); - return result; + return null; } + return new Job(JobDefOf.Harvest, t); + end_IL_005c:; } return null; } diff --git a/Assembly-CSharp/RimWorld/WorkGiver_RearmTraps.cs b/Assembly-CSharp/RimWorld/WorkGiver_RearmTraps.cs index 715b95d00..c31ac26a2 100644 --- a/Assembly-CSharp/RimWorld/WorkGiver_RearmTraps.cs +++ b/Assembly-CSharp/RimWorld/WorkGiver_RearmTraps.cs @@ -1,6 +1,4 @@ -using System; using System.Collections.Generic; -using System.Diagnostics; using Verse; using Verse.AI; @@ -16,15 +14,12 @@ public override PathEndMode PathEndMode } } - [DebuggerHidden] public override IEnumerable PotentialWorkThingsGlobal(Pawn pawn) { - WorkGiver_RearmTraps.c__Iterator64 c__Iterator = new WorkGiver_RearmTraps.c__Iterator64(); - c__Iterator.pawn = pawn; - c__Iterator.<$>pawn = pawn; - WorkGiver_RearmTraps.c__Iterator64 expr_15 = c__Iterator; - expr_15.$PC = -2; - return expr_15; + foreach (Designation item in pawn.Map.designationManager.SpawnedDesignationsOfDef(DesignationDefOf.RearmTrap)) + { + yield return item.target.Thing; + } } public override bool HasJobOnThing(Pawn pawn, Thing t, bool forced = false) @@ -40,7 +35,7 @@ public override bool HasJobOnThing(Pawn pawn, Thing t, bool forced = false) List thingList = t.Position.GetThingList(t.Map); for (int i = 0; i < thingList.Count; i++) { - IntVec3 intVec; + IntVec3 intVec = default(IntVec3); if (thingList[i] != t && thingList[i].def.category == ThingCategory.Item && (thingList[i].IsForbidden(pawn) || thingList[i].IsInValidStorage() || !HaulAIUtility.CanHaulAside(pawn, thingList[i], out intVec))) { return false; diff --git a/Assembly-CSharp/RimWorld/WorkGiver_Refuel.cs b/Assembly-CSharp/RimWorld/WorkGiver_Refuel.cs index 5e851fc77..edb11fe61 100644 --- a/Assembly-CSharp/RimWorld/WorkGiver_Refuel.cs +++ b/Assembly-CSharp/RimWorld/WorkGiver_Refuel.cs @@ -30,57 +30,65 @@ public override bool HasJobOnThing(Pawn pawn, Thing t, bool forced = false) public override Job JobOnThing(Pawn pawn, Thing t, bool forced = false) { Thing t2 = this.FindBestFuel(pawn, t); - return new Job(JobDefOf.Refuel, t, t2) - { - count = t.TryGetComp().GetFuelCountToFullyRefuel() - }; + Job job = new Job(JobDefOf.Refuel, t, t2); + job.count = t.TryGetComp().GetFuelCountToFullyRefuel(); + return job; } private bool ShouldRefuel(Pawn pawn, Thing t, bool mustBeAutoRefuelable, bool forced) { CompRefuelable compRefuelable = t.TryGetComp(); - if (compRefuelable == null || compRefuelable.IsFull) - { - return false; - } - if (mustBeAutoRefuelable && !compRefuelable.ShouldAutoRefuelNow) - { - return false; - } - if (t.IsForbidden(pawn) || !pawn.CanReserveAndReach(t, PathEndMode.Touch, pawn.NormalMaxDanger(), 1, -1, null, forced)) - { - return false; - } - if (t.Faction != pawn.Faction) + if (compRefuelable != null && !compRefuelable.IsFull) { - return false; - } - ThingWithComps thingWithComps = t as ThingWithComps; - if (thingWithComps != null) - { - CompFlickable comp = thingWithComps.GetComp(); - if (comp != null && !comp.SwitchIsOn) + if (mustBeAutoRefuelable && !compRefuelable.ShouldAutoRefuelNow) { return false; } - } - if (this.FindBestFuel(pawn, t) == null) - { - ThingFilter fuelFilter = t.TryGetComp().Props.fuelFilter; - JobFailReason.Is("NoFuelToRefuel".Translate(new object[] + if (!t.IsForbidden(pawn) && pawn.CanReserveAndReach(t, PathEndMode.Touch, pawn.NormalMaxDanger(), 1, -1, null, forced)) { - fuelFilter.Summary - })); + if (t.Faction != pawn.Faction) + { + return false; + } + ThingWithComps thingWithComps = t as ThingWithComps; + if (thingWithComps != null) + { + CompFlickable comp = thingWithComps.GetComp(); + if (comp != null && !comp.SwitchIsOn) + { + return false; + } + } + Thing thing = this.FindBestFuel(pawn, t); + if (thing == null) + { + ThingFilter fuelFilter = t.TryGetComp().Props.fuelFilter; + JobFailReason.Is("NoFuelToRefuel".Translate(fuelFilter.Summary)); + return false; + } + return true; + } return false; } - return true; + return false; } private Thing FindBestFuel(Pawn pawn, Thing refuelable) { ThingFilter filter = refuelable.TryGetComp().Props.fuelFilter; - Predicate predicate = (Thing x) => !x.IsForbidden(pawn) && pawn.CanReserve(x, 1, -1, null, false) && filter.Allows(x); - Predicate validator = predicate; + Predicate validator; + Predicate predicate = validator = (Predicate)delegate(Thing x) + { + if (!x.IsForbidden(pawn) && pawn.CanReserve(x, 1, -1, null, false)) + { + if (!filter.Allows(x)) + { + return false; + } + return true; + } + return false; + }; return GenClosest.ClosestThingReachable(pawn.Position, pawn.Map, filter.BestThingRequest, PathEndMode.ClosestTouch, TraverseParms.For(pawn, Danger.Deadly, TraverseMode.ByPawn, false), 9999f, validator, null, 0, -1, false, RegionType.Set_Passable, false); } } diff --git a/Assembly-CSharp/RimWorld/WorkGiver_RemoveBuilding.cs b/Assembly-CSharp/RimWorld/WorkGiver_RemoveBuilding.cs index 3dc001efc..ea13f69db 100644 --- a/Assembly-CSharp/RimWorld/WorkGiver_RemoveBuilding.cs +++ b/Assembly-CSharp/RimWorld/WorkGiver_RemoveBuilding.cs @@ -1,6 +1,4 @@ -using System; using System.Collections.Generic; -using System.Diagnostics; using Verse; using Verse.AI; @@ -26,16 +24,12 @@ public override PathEndMode PathEndMode } } - [DebuggerHidden] public override IEnumerable PotentialWorkThingsGlobal(Pawn pawn) { - WorkGiver_RemoveBuilding.c__Iterator5E c__Iterator5E = new WorkGiver_RemoveBuilding.c__Iterator5E(); - c__Iterator5E.pawn = pawn; - c__Iterator5E.<$>pawn = pawn; - c__Iterator5E.<>f__this = this; - WorkGiver_RemoveBuilding.c__Iterator5E expr_1C = c__Iterator5E; - expr_1C.$PC = -2; - return expr_1C; + foreach (Designation item in pawn.Map.designationManager.SpawnedDesignationsOfDef(this.Designation)) + { + yield return item.target.Thing; + } } public override bool HasJobOnThing(Pawn pawn, Thing t, bool forced = false) @@ -51,7 +45,15 @@ public override bool HasJobOnThing(Pawn pawn, Thing t, bool forced = false) { return false; } - return pawn.CanReserve(t, 1, -1, null, forced) && pawn.Map.designationManager.DesignationOn(t, this.Designation) != null; + if (!pawn.CanReserve(t, 1, -1, null, forced)) + { + return false; + } + if (pawn.Map.designationManager.DesignationOn(t, this.Designation) == null) + { + return false; + } + return true; } public override Job JobOnThing(Pawn pawn, Thing t, bool forced = false) diff --git a/Assembly-CSharp/RimWorld/WorkGiver_RemoveRoof.cs b/Assembly-CSharp/RimWorld/WorkGiver_RemoveRoof.cs index da91c475e..87198b23b 100644 --- a/Assembly-CSharp/RimWorld/WorkGiver_RemoveRoof.cs +++ b/Assembly-CSharp/RimWorld/WorkGiver_RemoveRoof.cs @@ -1,4 +1,3 @@ -using System; using System.Collections.Generic; using UnityEngine; using Verse; @@ -31,7 +30,7 @@ public override IEnumerable PotentialWorkCellsGlobal(Pawn pawn) public override bool HasJobOnCell(Pawn pawn, IntVec3 c) { - if (!pawn.Map.areaManager.NoRoof[c]) + if (!((Area)pawn.Map.areaManager.NoRoof)[c]) { return false; } @@ -40,7 +39,11 @@ public override bool HasJobOnCell(Pawn pawn, IntVec3 c) return false; } ReservationLayerDef ceiling = ReservationLayerDefOf.Ceiling; - return pawn.CanReserveAndReach(c, PathEndMode.ClosestTouch, pawn.NormalMaxDanger(), 1, -1, ceiling, false); + if (!pawn.CanReserveAndReach(c, PathEndMode.ClosestTouch, pawn.NormalMaxDanger(), 1, -1, ceiling, false)) + { + return false; + } + return true; } public override Job JobOnCell(Pawn pawn, IntVec3 c) @@ -68,7 +71,7 @@ public override float GetPriority(Pawn pawn, TargetInfo t) } } } - return (float)(-(float)Mathf.Min(num, 3)); + return (float)(-Mathf.Min(num, 3)); } } } diff --git a/Assembly-CSharp/RimWorld/WorkGiver_Repair.cs b/Assembly-CSharp/RimWorld/WorkGiver_Repair.cs index aacac26f6..e397bbdd6 100644 --- a/Assembly-CSharp/RimWorld/WorkGiver_Repair.cs +++ b/Assembly-CSharp/RimWorld/WorkGiver_Repair.cs @@ -1,4 +1,3 @@ -using System; using System.Collections.Generic; using Verse; using Verse.AI; @@ -52,12 +51,28 @@ public override bool HasJobOnThing(Pawn pawn, Thing t, bool forced = false) { return false; } - if (pawn.Faction == Faction.OfPlayer && !pawn.Map.areaManager.Home[t.Position]) + if (pawn.Faction == Faction.OfPlayer && !((Area)pawn.Map.areaManager.Home)[t.Position]) { JobFailReason.Is(WorkGiver_FixBrokenDownBuilding.NotInHomeAreaTrans); return false; } - return t.def.useHitPoints && t.HitPoints != t.MaxHitPoints && pawn.CanReserve(building, 1, -1, null, forced) && building.Map.designationManager.DesignationOn(building, DesignationDefOf.Deconstruct) == null && !building.IsBurning(); + if (t.def.useHitPoints && t.HitPoints != t.MaxHitPoints) + { + if (!pawn.CanReserve((Thing)building, 1, -1, null, forced)) + { + return false; + } + if (building.Map.designationManager.DesignationOn(building, DesignationDefOf.Deconstruct) != null) + { + return false; + } + if (building.IsBurning()) + { + return false; + } + return true; + } + return false; } public override Job JobOnThing(Pawn pawn, Thing t, bool forced = false) diff --git a/Assembly-CSharp/RimWorld/WorkGiver_RescueDowned.cs b/Assembly-CSharp/RimWorld/WorkGiver_RescueDowned.cs index e2495054c..69de22f54 100644 --- a/Assembly-CSharp/RimWorld/WorkGiver_RescueDowned.cs +++ b/Assembly-CSharp/RimWorld/WorkGiver_RescueDowned.cs @@ -1,4 +1,3 @@ -using System; using Verse; using Verse.AI; @@ -27,22 +26,25 @@ public override ThingRequest PotentialWorkThingRequest public override bool HasJobOnThing(Pawn pawn, Thing t, bool forced = false) { Pawn pawn2 = t as Pawn; - if (pawn2 == null || !pawn2.Downed || pawn2.Faction != pawn.Faction || pawn2.InBed() || !pawn.CanReserve(pawn2, 1, -1, null, forced) || GenAI.EnemyIsNear(pawn2, 40f)) + if (pawn2 != null && pawn2.Downed && pawn2.Faction == pawn.Faction && !pawn2.InBed() && pawn.CanReserve((Thing)pawn2, 1, -1, null, forced) && !GenAI.EnemyIsNear(pawn2, 40f)) { + Thing thing = base.FindBed(pawn, pawn2); + if (thing != null && pawn2.CanReserve(thing, 1, -1, null, false)) + { + return true; + } return false; } - Thing thing = base.FindBed(pawn, pawn2); - return thing != null && pawn2.CanReserve(thing, 1, -1, null, false); + return false; } public override Job JobOnThing(Pawn pawn, Thing t, bool forced = false) { Pawn pawn2 = t as Pawn; Thing t2 = base.FindBed(pawn, pawn2); - return new Job(JobDefOf.Rescue, pawn2, t2) - { - count = 1 - }; + Job job = new Job(JobDefOf.Rescue, (Thing)pawn2, t2); + job.count = 1; + return job; } } } diff --git a/Assembly-CSharp/RimWorld/WorkGiver_Researcher.cs b/Assembly-CSharp/RimWorld/WorkGiver_Researcher.cs index 1d562715b..4dbd827f4 100644 --- a/Assembly-CSharp/RimWorld/WorkGiver_Researcher.cs +++ b/Assembly-CSharp/RimWorld/WorkGiver_Researcher.cs @@ -1,4 +1,3 @@ -using System; using Verse; using Verse.AI; @@ -28,7 +27,11 @@ public override bool Prioritized public override bool ShouldSkip(Pawn pawn) { - return Find.ResearchManager.currentProj == null; + if (Find.ResearchManager.currentProj == null) + { + return true; + } + return false; } public override bool HasJobOnThing(Pawn pawn, Thing t, bool forced = false) @@ -39,7 +42,19 @@ public override bool HasJobOnThing(Pawn pawn, Thing t, bool forced = false) return false; } Building_ResearchBench building_ResearchBench = t as Building_ResearchBench; - return building_ResearchBench != null && currentProj.CanBeResearchedAt(building_ResearchBench, false) && pawn.CanReserve(t, 1, -1, null, forced); + if (building_ResearchBench == null) + { + return false; + } + if (!currentProj.CanBeResearchedAt(building_ResearchBench, false)) + { + return false; + } + if (!pawn.CanReserve(t, 1, -1, null, forced)) + { + return false; + } + return true; } public override Job JobOnThing(Pawn pawn, Thing t, bool forced = false) diff --git a/Assembly-CSharp/RimWorld/WorkGiver_Scanner.cs b/Assembly-CSharp/RimWorld/WorkGiver_Scanner.cs index 94c5b1c34..97e659848 100644 --- a/Assembly-CSharp/RimWorld/WorkGiver_Scanner.cs +++ b/Assembly-CSharp/RimWorld/WorkGiver_Scanner.cs @@ -1,6 +1,4 @@ -using System; using System.Collections.Generic; -using System.Diagnostics; using Verse; using Verse.AI; @@ -40,13 +38,9 @@ public virtual PathEndMode PathEndMode } } - [DebuggerHidden] public virtual IEnumerable PotentialWorkCellsGlobal(Pawn pawn) { - WorkGiver_Scanner.c__Iterator58 c__Iterator = new WorkGiver_Scanner.c__Iterator58(); - WorkGiver_Scanner.c__Iterator58 expr_07 = c__Iterator; - expr_07.$PC = -2; - return expr_07; + yield break; } public virtual IEnumerable PotentialWorkThingsGlobal(Pawn pawn) diff --git a/Assembly-CSharp/RimWorld/WorkGiver_Shear.cs b/Assembly-CSharp/RimWorld/WorkGiver_Shear.cs index ae802ca9c..d7a866954 100644 --- a/Assembly-CSharp/RimWorld/WorkGiver_Shear.cs +++ b/Assembly-CSharp/RimWorld/WorkGiver_Shear.cs @@ -1,4 +1,3 @@ -using System; using Verse; namespace RimWorld diff --git a/Assembly-CSharp/RimWorld/WorkGiver_Slaughter.cs b/Assembly-CSharp/RimWorld/WorkGiver_Slaughter.cs index 436cfbb5d..9789659e5 100644 --- a/Assembly-CSharp/RimWorld/WorkGiver_Slaughter.cs +++ b/Assembly-CSharp/RimWorld/WorkGiver_Slaughter.cs @@ -1,6 +1,4 @@ -using System; using System.Collections.Generic; -using System.Diagnostics; using Verse; using Verse.AI; @@ -16,46 +14,43 @@ public override PathEndMode PathEndMode } } - [DebuggerHidden] public override IEnumerable PotentialWorkThingsGlobal(Pawn pawn) { - WorkGiver_Slaughter.c__Iterator5A c__Iterator5A = new WorkGiver_Slaughter.c__Iterator5A(); - c__Iterator5A.pawn = pawn; - c__Iterator5A.<$>pawn = pawn; - WorkGiver_Slaughter.c__Iterator5A expr_15 = c__Iterator5A; - expr_15.$PC = -2; - return expr_15; + foreach (Designation item in pawn.Map.designationManager.SpawnedDesignationsOfDef(DesignationDefOf.Slaughter)) + { + yield return item.target.Thing; + } } public override bool HasJobOnThing(Pawn pawn, Thing t, bool forced = false) { Pawn pawn2 = t as Pawn; - if (pawn2 == null || !pawn2.RaceProps.Animal) - { - return false; - } - if (pawn.Map.designationManager.DesignationOn(t, DesignationDefOf.Slaughter) == null) - { - return false; - } - if (pawn.Faction != t.Faction) - { - return false; - } - if (pawn2.InAggroMentalState) - { - return false; - } - if (!pawn.CanReserve(t, 1, -1, null, forced)) - { - return false; - } - if (pawn.story != null && pawn.story.WorkTagIsDisabled(WorkTags.Violent)) + if (pawn2 != null && pawn2.RaceProps.Animal) { - JobFailReason.Is("IsIncapableOfViolenceShort".Translate()); - return false; + if (pawn.Map.designationManager.DesignationOn(t, DesignationDefOf.Slaughter) == null) + { + return false; + } + if (pawn.Faction != t.Faction) + { + return false; + } + if (pawn2.InAggroMentalState) + { + return false; + } + if (!pawn.CanReserve(t, 1, -1, null, forced)) + { + return false; + } + if (pawn.story != null && pawn.story.WorkTagIsDisabled(WorkTags.Violent)) + { + JobFailReason.Is("IsIncapableOfViolenceShort".Translate()); + return false; + } + return true; } - return true; + return false; } public override Job JobOnThing(Pawn pawn, Thing t, bool forced = false) diff --git a/Assembly-CSharp/RimWorld/WorkGiver_Strip.cs b/Assembly-CSharp/RimWorld/WorkGiver_Strip.cs index ac8a35a3d..add6c4f18 100644 --- a/Assembly-CSharp/RimWorld/WorkGiver_Strip.cs +++ b/Assembly-CSharp/RimWorld/WorkGiver_Strip.cs @@ -1,6 +1,4 @@ -using System; using System.Collections.Generic; -using System.Diagnostics; using Verse; using Verse.AI; @@ -16,20 +14,36 @@ public override PathEndMode PathEndMode } } - [DebuggerHidden] public override IEnumerable PotentialWorkThingsGlobal(Pawn pawn) { - WorkGiver_Strip.c__Iterator65 c__Iterator = new WorkGiver_Strip.c__Iterator65(); - c__Iterator.pawn = pawn; - c__Iterator.<$>pawn = pawn; - WorkGiver_Strip.c__Iterator65 expr_15 = c__Iterator; - expr_15.$PC = -2; - return expr_15; + foreach (Designation item in pawn.Map.designationManager.SpawnedDesignationsOfDef(DesignationDefOf.Strip)) + { + if (!item.target.HasThing) + { + Log.ErrorOnce("Strip designation has no target.", 63126); + } + else + { + yield return item.target.Thing; + } + } } public override bool HasJobOnThing(Pawn pawn, Thing t, bool forced = false) { - return t.Map.designationManager.DesignationOn(t, DesignationDefOf.Strip) != null && pawn.CanReserve(t, 1, -1, null, forced) && StrippableUtility.CanBeStrippedByColony(t); + if (t.Map.designationManager.DesignationOn(t, DesignationDefOf.Strip) == null) + { + return false; + } + if (!pawn.CanReserve(t, 1, -1, null, forced)) + { + return false; + } + if (!StrippableUtility.CanBeStrippedByColony(t)) + { + return false; + } + return true; } public override Job JobOnThing(Pawn pawn, Thing t, bool forced = false) diff --git a/Assembly-CSharp/RimWorld/WorkGiver_TakeBeerOutOfFermentingBarrel.cs b/Assembly-CSharp/RimWorld/WorkGiver_TakeBeerOutOfFermentingBarrel.cs index 6729ec17c..2898ac400 100644 --- a/Assembly-CSharp/RimWorld/WorkGiver_TakeBeerOutOfFermentingBarrel.cs +++ b/Assembly-CSharp/RimWorld/WorkGiver_TakeBeerOutOfFermentingBarrel.cs @@ -1,4 +1,3 @@ -using System; using Verse; using Verse.AI; @@ -25,7 +24,19 @@ public override PathEndMode PathEndMode public override bool HasJobOnThing(Pawn pawn, Thing t, bool forced = false) { Building_FermentingBarrel building_FermentingBarrel = t as Building_FermentingBarrel; - return building_FermentingBarrel != null && building_FermentingBarrel.Fermented && !t.IsBurning() && !t.IsForbidden(pawn) && pawn.CanReserveAndReach(t, PathEndMode.Touch, pawn.NormalMaxDanger(), 1, -1, null, forced); + if (building_FermentingBarrel != null && building_FermentingBarrel.Fermented) + { + if (t.IsBurning()) + { + return false; + } + if (!t.IsForbidden(pawn) && pawn.CanReserveAndReach(t, PathEndMode.Touch, pawn.NormalMaxDanger(), 1, -1, null, forced)) + { + return true; + } + return false; + } + return false; } public override Job JobOnThing(Pawn pawn, Thing t, bool forced = false) diff --git a/Assembly-CSharp/RimWorld/WorkGiver_TakeToBed.cs b/Assembly-CSharp/RimWorld/WorkGiver_TakeToBed.cs index 49c5ccc2d..81fa5a3dc 100644 --- a/Assembly-CSharp/RimWorld/WorkGiver_TakeToBed.cs +++ b/Assembly-CSharp/RimWorld/WorkGiver_TakeToBed.cs @@ -1,4 +1,3 @@ -using System; using Verse; namespace RimWorld diff --git a/Assembly-CSharp/RimWorld/WorkGiver_TakeToBedToOperate.cs b/Assembly-CSharp/RimWorld/WorkGiver_TakeToBedToOperate.cs index 3d8331900..0304dca88 100644 --- a/Assembly-CSharp/RimWorld/WorkGiver_TakeToBedToOperate.cs +++ b/Assembly-CSharp/RimWorld/WorkGiver_TakeToBedToOperate.cs @@ -1,4 +1,3 @@ -using System; using Verse; using Verse.AI; @@ -25,33 +24,36 @@ public override PathEndMode PathEndMode public override bool HasJobOnThing(Pawn pawn, Thing t, bool forced = false) { Pawn pawn2 = t as Pawn; - if (pawn2 == null || pawn2 == pawn || pawn2.InBed() || !pawn2.RaceProps.IsFlesh || !HealthAIUtility.ShouldHaveSurgeryDoneNow(pawn2) || !pawn.CanReserve(pawn2, 1, -1, null, forced) || (pawn2.InMentalState && pawn2.MentalStateDef.IsAggro)) + if (pawn2 != null && pawn2 != pawn && !pawn2.InBed() && pawn2.RaceProps.IsFlesh && HealthAIUtility.ShouldHaveSurgeryDoneNow(pawn2) && pawn.CanReserve((Thing)pawn2, 1, -1, null, forced) && (!pawn2.InMentalState || !pawn2.MentalStateDef.IsAggro)) { - return false; - } - if (!pawn2.Downed) - { - if (pawn2.IsColonist) + if (!pawn2.Downed) { - return false; + if (pawn2.IsColonist) + { + return false; + } + if (!pawn2.IsPrisonerOfColony && pawn2.Faction != Faction.OfPlayer) + { + return false; + } } - if (!pawn2.IsPrisonerOfColony && pawn2.Faction != Faction.OfPlayer) + Building_Bed building_Bed = base.FindBed(pawn, pawn2); + if (building_Bed != null && pawn2.CanReserve((Thing)building_Bed, building_Bed.SleepingSlotsCount, -1, null, false)) { - return false; + return true; } + return false; } - Building_Bed building_Bed = base.FindBed(pawn, pawn2); - return building_Bed != null && pawn2.CanReserve(building_Bed, building_Bed.SleepingSlotsCount, -1, null, false); + return false; } public override Job JobOnThing(Pawn pawn, Thing t, bool forced = false) { Pawn pawn2 = t as Pawn; Thing t2 = base.FindBed(pawn, pawn2); - return new Job(JobDefOf.TakeToBedToOperate, pawn2, t2) - { - count = 1 - }; + Job job = new Job(JobDefOf.TakeToBedToOperate, (Thing)pawn2, t2); + job.count = 1; + return job; } } } diff --git a/Assembly-CSharp/RimWorld/WorkGiver_Tame.cs b/Assembly-CSharp/RimWorld/WorkGiver_Tame.cs index 63f114310..9d8c886ab 100644 --- a/Assembly-CSharp/RimWorld/WorkGiver_Tame.cs +++ b/Assembly-CSharp/RimWorld/WorkGiver_Tame.cs @@ -1,6 +1,4 @@ -using System; using System.Collections.Generic; -using System.Diagnostics; using Verse; using Verse.AI; @@ -10,47 +8,44 @@ public class WorkGiver_Tame : WorkGiver_InteractAnimal { public const int MinTameInterval = 30000; - [DebuggerHidden] public override IEnumerable PotentialWorkThingsGlobal(Pawn pawn) { - WorkGiver_Tame.c__Iterator5B c__Iterator5B = new WorkGiver_Tame.c__Iterator5B(); - c__Iterator5B.pawn = pawn; - c__Iterator5B.<$>pawn = pawn; - WorkGiver_Tame.c__Iterator5B expr_15 = c__Iterator5B; - expr_15.$PC = -2; - return expr_15; + foreach (Designation item in pawn.Map.designationManager.SpawnedDesignationsOfDef(DesignationDefOf.Tame)) + { + yield return item.target.Thing; + } } public override Job JobOnThing(Pawn pawn, Thing t, bool forced = false) { Pawn pawn2 = t as Pawn; - if (pawn2 == null || pawn2.RaceProps.Humanlike) - { - return null; - } - if (pawn.Map.designationManager.DesignationOn(t, DesignationDefOf.Tame) == null) - { - return null; - } - if (Find.TickManager.TicksGame < pawn2.mindState.lastAssignedInteractTime + 30000) - { - JobFailReason.Is(WorkGiver_InteractAnimal.AnimalInteractedTooRecentlyTrans); - return null; - } - if (!this.CanInteractWithAnimal(pawn, pawn2)) + if (pawn2 != null && !pawn2.RaceProps.Humanlike) { - return null; - } - if (pawn2.RaceProps.EatsFood && !base.HasFoodToInteractAnimal(pawn, pawn2)) - { - Job job = base.TakeFoodForAnimalInteractJob(pawn, pawn2); - if (job == null) + if (pawn.Map.designationManager.DesignationOn(t, DesignationDefOf.Tame) == null) + { + return null; + } + if (Find.TickManager.TicksGame < pawn2.mindState.lastAssignedInteractTime + 30000) + { + JobFailReason.Is(WorkGiver_InteractAnimal.AnimalInteractedTooRecentlyTrans); + return null; + } + if (!this.CanInteractWithAnimal(pawn, pawn2)) + { + return null; + } + if (pawn2.RaceProps.EatsFood && !base.HasFoodToInteractAnimal(pawn, pawn2)) { - JobFailReason.Is(WorkGiver_InteractAnimal.NoUsableFoodTrans); + Job job = base.TakeFoodForAnimalInteractJob(pawn, pawn2); + if (job == null) + { + JobFailReason.Is(WorkGiver_InteractAnimal.NoUsableFoodTrans); + } + return job; } - return job; + return new Job(JobDefOf.Tame, t); } - return new Job(JobDefOf.Tame, t); + return null; } } } diff --git a/Assembly-CSharp/RimWorld/WorkGiver_Tend.cs b/Assembly-CSharp/RimWorld/WorkGiver_Tend.cs index e4a045560..bfeaa0b50 100644 --- a/Assembly-CSharp/RimWorld/WorkGiver_Tend.cs +++ b/Assembly-CSharp/RimWorld/WorkGiver_Tend.cs @@ -1,4 +1,3 @@ -using System; using Verse; using Verse.AI; @@ -25,7 +24,11 @@ public override ThingRequest PotentialWorkThingRequest public override bool HasJobOnThing(Pawn pawn, Thing t, bool forced = false) { Pawn pawn2 = t as Pawn; - return pawn2 != null && (!this.def.tendToHumanlikesOnly || pawn2.RaceProps.Humanlike) && (!this.def.tendToAnimalsOnly || pawn2.RaceProps.Animal) && WorkGiver_Tend.GoodLayingStatusForTend(pawn2, pawn) && HealthAIUtility.ShouldBeTendedNow(pawn2) && pawn.CanReserve(pawn2, 1, -1, null, forced); + if (pawn2 != null && (!base.def.tendToHumanlikesOnly || pawn2.RaceProps.Humanlike) && (!base.def.tendToAnimalsOnly || pawn2.RaceProps.Animal) && WorkGiver_Tend.GoodLayingStatusForTend(pawn2, pawn) && HealthAIUtility.ShouldBeTendedNow(pawn2) && pawn.CanReserve((Thing)pawn2, 1, -1, null, forced)) + { + return true; + } + return false; } public static bool GoodLayingStatusForTend(Pawn patient, Pawn doctor) @@ -51,9 +54,9 @@ public override Job JobOnThing(Pawn pawn, Thing t, bool forced = false) } if (thing != null) { - return new Job(JobDefOf.TendPatient, pawn2, thing); + return new Job(JobDefOf.TendPatient, (Thing)pawn2, thing); } - return new Job(JobDefOf.TendPatient, pawn2); + return new Job(JobDefOf.TendPatient, (Thing)pawn2); } } } diff --git a/Assembly-CSharp/RimWorld/WorkGiver_TendEmergency.cs b/Assembly-CSharp/RimWorld/WorkGiver_TendEmergency.cs index 42ad1f961..9c99d05d9 100644 --- a/Assembly-CSharp/RimWorld/WorkGiver_TendEmergency.cs +++ b/Assembly-CSharp/RimWorld/WorkGiver_TendEmergency.cs @@ -1,4 +1,3 @@ -using System; using Verse; namespace RimWorld diff --git a/Assembly-CSharp/RimWorld/WorkGiver_TendOther.cs b/Assembly-CSharp/RimWorld/WorkGiver_TendOther.cs index 55c9086bf..40bd61fb7 100644 --- a/Assembly-CSharp/RimWorld/WorkGiver_TendOther.cs +++ b/Assembly-CSharp/RimWorld/WorkGiver_TendOther.cs @@ -1,4 +1,3 @@ -using System; using Verse; namespace RimWorld diff --git a/Assembly-CSharp/RimWorld/WorkGiver_TendSelf.cs b/Assembly-CSharp/RimWorld/WorkGiver_TendSelf.cs index 4737c7565..c4c7afdf1 100644 --- a/Assembly-CSharp/RimWorld/WorkGiver_TendSelf.cs +++ b/Assembly-CSharp/RimWorld/WorkGiver_TendSelf.cs @@ -1,6 +1,4 @@ -using System; using System.Collections.Generic; -using System.Diagnostics; using Verse; using Verse.AI; @@ -16,15 +14,9 @@ public override ThingRequest PotentialWorkThingRequest } } - [DebuggerHidden] public override IEnumerable PotentialWorkThingsGlobal(Pawn pawn) { - WorkGiver_TendSelf.c__Iterator66 c__Iterator = new WorkGiver_TendSelf.c__Iterator66(); - c__Iterator.pawn = pawn; - c__Iterator.<$>pawn = pawn; - WorkGiver_TendSelf.c__Iterator66 expr_15 = c__Iterator; - expr_15.$PC = -2; - return expr_15; + yield return (Thing)pawn; } public override bool HasJobOnThing(Pawn pawn, Thing t, bool forced = false) diff --git a/Assembly-CSharp/RimWorld/WorkGiver_Train.cs b/Assembly-CSharp/RimWorld/WorkGiver_Train.cs index 6c06244fe..9f55907bc 100644 --- a/Assembly-CSharp/RimWorld/WorkGiver_Train.cs +++ b/Assembly-CSharp/RimWorld/WorkGiver_Train.cs @@ -1,6 +1,4 @@ -using System; using System.Collections.Generic; -using System.Diagnostics; using Verse; using Verse.AI; @@ -10,55 +8,54 @@ public class WorkGiver_Train : WorkGiver_InteractAnimal { public const int MinTrainInterval = 15000; - [DebuggerHidden] public override IEnumerable PotentialWorkThingsGlobal(Pawn pawn) { - WorkGiver_Train.c__Iterator5C c__Iterator5C = new WorkGiver_Train.c__Iterator5C(); - c__Iterator5C.pawn = pawn; - c__Iterator5C.<$>pawn = pawn; - WorkGiver_Train.c__Iterator5C expr_15 = c__Iterator5C; - expr_15.$PC = -2; - return expr_15; + List pawnList = pawn.Map.mapPawns.SpawnedPawnsInFaction(pawn.Faction); + for (int i = 0; i < pawnList.Count; i++) + { + yield return (Thing)pawnList[i]; + } } public override Job JobOnThing(Pawn pawn, Thing t, bool forced = false) { Pawn pawn2 = t as Pawn; - if (pawn2 == null || !pawn2.RaceProps.Animal) - { - return null; - } - if (pawn2.Faction != pawn.Faction) - { - return null; - } - if (Find.TickManager.TicksGame < pawn2.mindState.lastAssignedInteractTime + 15000) - { - JobFailReason.Is(WorkGiver_InteractAnimal.AnimalInteractedTooRecentlyTrans); - return null; - } - if (pawn2.training == null) - { - return null; - } - if (pawn2.training.NextTrainableToTrain() == null) - { - return null; - } - if (!this.CanInteractWithAnimal(pawn, pawn2)) + if (pawn2 != null && pawn2.RaceProps.Animal) { - return null; - } - if (pawn2.RaceProps.EatsFood && !base.HasFoodToInteractAnimal(pawn, pawn2)) - { - Job job = base.TakeFoodForAnimalInteractJob(pawn, pawn2); - if (job == null) + if (pawn2.Faction != pawn.Faction) + { + return null; + } + if (Find.TickManager.TicksGame < pawn2.mindState.lastAssignedInteractTime + 15000) + { + JobFailReason.Is(WorkGiver_InteractAnimal.AnimalInteractedTooRecentlyTrans); + return null; + } + if (pawn2.training == null) + { + return null; + } + TrainableDef trainableDef = pawn2.training.NextTrainableToTrain(); + if (trainableDef == null) + { + return null; + } + if (!this.CanInteractWithAnimal(pawn, pawn2)) + { + return null; + } + if (pawn2.RaceProps.EatsFood && !base.HasFoodToInteractAnimal(pawn, pawn2)) { - JobFailReason.Is(WorkGiver_InteractAnimal.NoUsableFoodTrans); + Job job = base.TakeFoodForAnimalInteractJob(pawn, pawn2); + if (job == null) + { + JobFailReason.Is(WorkGiver_InteractAnimal.NoUsableFoodTrans); + } + return job; } - return job; + return new Job(JobDefOf.Train, t); } - return new Job(JobDefOf.Train, t); + return null; } } } diff --git a/Assembly-CSharp/RimWorld/WorkGiver_Uninstall.cs b/Assembly-CSharp/RimWorld/WorkGiver_Uninstall.cs index a4c11a5e8..5edf5f7f7 100644 --- a/Assembly-CSharp/RimWorld/WorkGiver_Uninstall.cs +++ b/Assembly-CSharp/RimWorld/WorkGiver_Uninstall.cs @@ -1,4 +1,3 @@ -using System; using Verse; namespace RimWorld diff --git a/Assembly-CSharp/RimWorld/WorkGiver_UnloadCarriers.cs b/Assembly-CSharp/RimWorld/WorkGiver_UnloadCarriers.cs index ee14bcc70..62edd0bc8 100644 --- a/Assembly-CSharp/RimWorld/WorkGiver_UnloadCarriers.cs +++ b/Assembly-CSharp/RimWorld/WorkGiver_UnloadCarriers.cs @@ -1,4 +1,3 @@ -using System; using Verse; using Verse.AI; @@ -25,7 +24,11 @@ public override PathEndMode PathEndMode public override bool HasJobOnThing(Pawn pawn, Thing t, bool forced = false) { Pawn pawn2 = t as Pawn; - return pawn2 != null && pawn2 != pawn && (!pawn2.IsColonist || pawn2.HostFaction != null) && (pawn2.inventory.UnloadEverything && (pawn2.Faction == pawn.Faction || pawn2.HostFaction == pawn.HostFaction)) && !t.IsForbidden(pawn) && !t.IsBurning() && pawn.CanReserve(t, 1, -1, null, forced); + if (pawn2 != null && pawn2 != pawn && (!pawn2.IsColonist || pawn2.HostFaction != null) && pawn2.inventory.UnloadEverything && (pawn2.Faction == pawn.Faction || pawn2.HostFaction == pawn.HostFaction) && !t.IsForbidden(pawn) && !t.IsBurning() && pawn.CanReserve(t, 1, -1, null, forced)) + { + return true; + } + return false; } public override Job JobOnThing(Pawn pawn, Thing t, bool forced = false) diff --git a/Assembly-CSharp/RimWorld/WorkGiver_VisitSickPawn.cs b/Assembly-CSharp/RimWorld/WorkGiver_VisitSickPawn.cs index 8f35b26d2..33bdc699a 100644 --- a/Assembly-CSharp/RimWorld/WorkGiver_VisitSickPawn.cs +++ b/Assembly-CSharp/RimWorld/WorkGiver_VisitSickPawn.cs @@ -1,4 +1,3 @@ -using System; using Verse; using Verse.AI; @@ -38,10 +37,9 @@ public override Job JobOnThing(Pawn pawn, Thing t, bool forced = false) { return null; } - return new Job(JobDefOf.VisitSickPawn, pawn2, SickPawnVisitUtility.FindChair(pawn, pawn2)) - { - ignoreJoyTimeAssignment = true - }; + Job job = new Job(JobDefOf.VisitSickPawn, (Thing)pawn2, SickPawnVisitUtility.FindChair(pawn, pawn2)); + job.ignoreJoyTimeAssignment = true; + return job; } } } diff --git a/Assembly-CSharp/RimWorld/WorkGiver_Warden.cs b/Assembly-CSharp/RimWorld/WorkGiver_Warden.cs index 39b85745a..510e300cc 100644 --- a/Assembly-CSharp/RimWorld/WorkGiver_Warden.cs +++ b/Assembly-CSharp/RimWorld/WorkGiver_Warden.cs @@ -1,4 +1,3 @@ -using System; using Verse; using Verse.AI; using Verse.AI.Group; @@ -26,7 +25,11 @@ public override PathEndMode PathEndMode protected bool ShouldTakeCareOfPrisoner(Pawn warden, Thing prisoner) { Pawn pawn = prisoner as Pawn; - return pawn != null && pawn.IsPrisonerOfColony && pawn.guest.PrisonerIsSecure && pawn.Spawned && !pawn.InAggroMentalState && !prisoner.IsForbidden(warden) && (pawn.GetLord() == null || !(pawn.GetLord().LordJob is LordJob_FormAndSendCaravan)) && warden.CanReserveAndReach(pawn, PathEndMode.OnCell, warden.NormalMaxDanger(), 1, -1, null, false); + if (pawn != null && pawn.IsPrisonerOfColony && pawn.guest.PrisonerIsSecure && pawn.Spawned && !pawn.InAggroMentalState && !prisoner.IsForbidden(warden) && (pawn.GetLord() == null || !(pawn.GetLord().LordJob is LordJob_FormAndSendCaravan)) && warden.CanReserveAndReach((Thing)pawn, PathEndMode.OnCell, warden.NormalMaxDanger(), 1, -1, null, false)) + { + return true; + } + return false; } } } diff --git a/Assembly-CSharp/RimWorld/WorkGiver_Warden_Chat.cs b/Assembly-CSharp/RimWorld/WorkGiver_Warden_Chat.cs index 500cf01db..eec6f04d8 100644 --- a/Assembly-CSharp/RimWorld/WorkGiver_Warden_Chat.cs +++ b/Assembly-CSharp/RimWorld/WorkGiver_Warden_Chat.cs @@ -1,4 +1,3 @@ -using System; using Verse; using Verse.AI; diff --git a/Assembly-CSharp/RimWorld/WorkGiver_Warden_DeliverFood.cs b/Assembly-CSharp/RimWorld/WorkGiver_Warden_DeliverFood.cs index 1ced79892..9d346aec6 100644 --- a/Assembly-CSharp/RimWorld/WorkGiver_Warden_DeliverFood.cs +++ b/Assembly-CSharp/RimWorld/WorkGiver_Warden_DeliverFood.cs @@ -1,4 +1,3 @@ -using System; using System.Collections.Generic; using Verse; using Verse.AI; @@ -22,7 +21,7 @@ public override Job JobOnThing(Pawn pawn, Thing t, bool forced = false) { return null; } - if (pawn2.needs.food.CurLevelPercentage >= pawn2.needs.food.PercentageThreshHungry + 0.02f) + if (pawn2.needs.food.CurLevelPercentage >= pawn2.needs.food.PercentageThreshHungry + 0.019999999552965164) { return null; } @@ -30,8 +29,8 @@ public override Job JobOnThing(Pawn pawn, Thing t, bool forced = false) { return null; } - Thing thing; - ThingDef def; + Thing thing = default(Thing); + ThingDef def = default(ThingDef); if (!FoodUtility.TryFindBestFoodSourceFor(pawn, pawn2, pawn2.needs.food.CurCategory == HungerCategory.Starving, out thing, out def, false, true, false, false, false)) { return null; @@ -44,16 +43,15 @@ public override Job JobOnThing(Pawn pawn, Thing t, bool forced = false) { return null; } - return new Job(JobDefOf.DeliverFood, thing, pawn2) - { - count = FoodUtility.WillIngestStackCountOf(pawn2, def), - targetC = RCellFinder.SpotToChewStandingNear(pawn2, thing) - }; + Job job = new Job(JobDefOf.DeliverFood, thing, (Thing)pawn2); + job.count = FoodUtility.WillIngestStackCountOf(pawn2, def); + job.targetC = RCellFinder.SpotToChewStandingNear(pawn2, thing); + return job; } private static bool FoodAvailableInRoomTo(Pawn prisoner) { - if (prisoner.carryTracker.CarriedThing != null && WorkGiver_Warden_DeliverFood.NutritionAvailableForFrom(prisoner, prisoner.carryTracker.CarriedThing) > 0f) + if (prisoner.carryTracker.CarriedThing != null && WorkGiver_Warden_DeliverFood.NutritionAvailableForFrom(prisoner, prisoner.carryTracker.CarriedThing) > 0.0) { return true; } @@ -71,7 +69,7 @@ private static bool FoodAvailableInRoomTo(Pawn prisoner) for (int j = 0; j < list.Count; j++) { Thing thing = list[j]; - if (!thing.def.IsIngestible || thing.def.ingestible.preferability > FoodPreferability.DesperateOnly) + if (!thing.def.IsIngestible || (int)thing.def.ingestible.preferability > 2) { num2 += WorkGiver_Warden_DeliverFood.NutritionAvailableForFrom(prisoner, thing); } @@ -80,13 +78,17 @@ private static bool FoodAvailableInRoomTo(Pawn prisoner) for (int k = 0; k < list2.Count; k++) { Pawn pawn = list2[k] as Pawn; - if (pawn.IsPrisonerOfColony && pawn.needs.food.CurLevelPercentage < pawn.needs.food.PercentageThreshHungry + 0.02f && (pawn.carryTracker.CarriedThing == null || !pawn.RaceProps.WillAutomaticallyEat(pawn.carryTracker.CarriedThing))) + if (pawn.IsPrisonerOfColony && pawn.needs.food.CurLevelPercentage < pawn.needs.food.PercentageThreshHungry + 0.019999999552965164 && (pawn.carryTracker.CarriedThing == null || !pawn.RaceProps.WillAutomaticallyEat(pawn.carryTracker.CarriedThing))) { num += pawn.needs.food.NutritionWanted; } } } - return num2 + 0.5f >= num; + if (num2 + 0.5 >= num) + { + return true; + } + return false; } private static float NutritionAvailableForFrom(Pawn p, Thing foodSource) diff --git a/Assembly-CSharp/RimWorld/WorkGiver_Warden_DoExecution.cs b/Assembly-CSharp/RimWorld/WorkGiver_Warden_DoExecution.cs index 6be9450b6..54d587f4c 100644 --- a/Assembly-CSharp/RimWorld/WorkGiver_Warden_DoExecution.cs +++ b/Assembly-CSharp/RimWorld/WorkGiver_Warden_DoExecution.cs @@ -1,4 +1,3 @@ -using System; using Verse; using Verse.AI; @@ -28,16 +27,16 @@ public override Job JobOnThing(Pawn pawn, Thing t, bool forced = false) return null; } Pawn pawn2 = (Pawn)t; - if (pawn2.guest.interactionMode != PrisonerInteractionModeDefOf.Execution || !pawn.CanReserve(t, 1, -1, null, false)) + if (pawn2.guest.interactionMode == PrisonerInteractionModeDefOf.Execution && pawn.CanReserve(t, 1, -1, null, false)) { - return null; - } - if (pawn.story != null && pawn.story.WorkTagIsDisabled(WorkTags.Violent)) - { - JobFailReason.Is(WorkGiver_Warden_DoExecution.IncapableOfViolenceLowerTrans); - return null; + if (pawn.story != null && pawn.story.WorkTagIsDisabled(WorkTags.Violent)) + { + JobFailReason.Is(WorkGiver_Warden_DoExecution.IncapableOfViolenceLowerTrans); + return null; + } + return new Job(JobDefOf.PrisonerExecution, t); } - return new Job(JobDefOf.PrisonerExecution, t); + return null; } } } diff --git a/Assembly-CSharp/RimWorld/WorkGiver_Warden_Feed.cs b/Assembly-CSharp/RimWorld/WorkGiver_Warden_Feed.cs index 813ca6d66..ae21a9786 100644 --- a/Assembly-CSharp/RimWorld/WorkGiver_Warden_Feed.cs +++ b/Assembly-CSharp/RimWorld/WorkGiver_Warden_Feed.cs @@ -1,4 +1,3 @@ -using System; using Verse; using Verse.AI; @@ -17,21 +16,20 @@ public override Job JobOnThing(Pawn pawn, Thing t, bool forced = false) { return null; } - if (pawn2.needs.food.CurLevelPercentage >= pawn2.needs.food.PercentageThreshHungry + 0.02f) + if (pawn2.needs.food.CurLevelPercentage >= pawn2.needs.food.PercentageThreshHungry + 0.019999999552965164) { return null; } - Thing t2; - ThingDef def; + Thing t2 = default(Thing); + ThingDef def = default(ThingDef); if (!FoodUtility.TryFindBestFoodSourceFor(pawn, pawn2, pawn2.needs.food.CurCategory == HungerCategory.Starving, out t2, out def, false, true, false, false, false)) { JobFailReason.Is("NoFood".Translate()); return null; } - return new Job(JobDefOf.FeedPatient, t2, pawn2) - { - count = FoodUtility.WillIngestStackCountOf(pawn2, def) - }; + Job job = new Job(JobDefOf.FeedPatient, t2, (Thing)pawn2); + job.count = FoodUtility.WillIngestStackCountOf(pawn2, def); + return job; } } } diff --git a/Assembly-CSharp/RimWorld/WorkGiver_Warden_ReleasePrisoner.cs b/Assembly-CSharp/RimWorld/WorkGiver_Warden_ReleasePrisoner.cs index e7b7ff49d..7e08cd5d0 100644 --- a/Assembly-CSharp/RimWorld/WorkGiver_Warden_ReleasePrisoner.cs +++ b/Assembly-CSharp/RimWorld/WorkGiver_Warden_ReleasePrisoner.cs @@ -1,4 +1,3 @@ -using System; using Verse; using Verse.AI; @@ -13,19 +12,18 @@ public override Job JobOnThing(Pawn pawn, Thing t, bool forced = false) return null; } Pawn pawn2 = (Pawn)t; - if (pawn2.guest.interactionMode != PrisonerInteractionModeDefOf.Release || pawn2.Downed || !pawn2.Awake()) + if (pawn2.guest.interactionMode == PrisonerInteractionModeDefOf.Release && !pawn2.Downed && pawn2.Awake()) { - return null; + IntVec3 c = default(IntVec3); + if (!RCellFinder.TryFindPrisonerReleaseCell(pawn2, pawn, out c)) + { + return null; + } + Job job = new Job(JobDefOf.ReleasePrisoner, (Thing)pawn2, c); + job.count = 1; + return job; } - IntVec3 c; - if (!RCellFinder.TryFindPrisonerReleaseCell(pawn2, pawn, out c)) - { - return null; - } - return new Job(JobDefOf.ReleasePrisoner, pawn2, c) - { - count = 1 - }; + return null; } } } diff --git a/Assembly-CSharp/RimWorld/WorkGiver_Warden_TakeToBed.cs b/Assembly-CSharp/RimWorld/WorkGiver_Warden_TakeToBed.cs index 167ff37cb..2318d35fa 100644 --- a/Assembly-CSharp/RimWorld/WorkGiver_Warden_TakeToBed.cs +++ b/Assembly-CSharp/RimWorld/WorkGiver_Warden_TakeToBed.cs @@ -1,4 +1,3 @@ -using System; using Verse; using Verse.AI; @@ -28,39 +27,37 @@ public override Job JobOnThing(Pawn pawn, Thing t, bool forced = false) private Job TakeToPreferredBedJob(Pawn prisoner, Pawn warden) { - if (prisoner.Downed || !warden.CanReserve(prisoner, 1, -1, null, false)) + if (!prisoner.Downed && warden.CanReserve((Thing)prisoner, 1, -1, null, false)) { - return null; - } - if (RestUtility.FindBedFor(prisoner, prisoner, true, true, false) != null) - { - return null; - } - Room room = prisoner.GetRoom(RegionType.Set_Passable); - Building_Bed building_Bed = RestUtility.FindBedFor(prisoner, warden, true, false, false); - if (building_Bed != null && building_Bed.GetRoom(RegionType.Set_Passable) != room) - { - return new Job(JobDefOf.EscortPrisonerToBed, prisoner, building_Bed) + if (RestUtility.FindBedFor(prisoner, prisoner, true, true, false) != null) { - count = 1 - }; + return null; + } + Room room = prisoner.GetRoom(RegionType.Set_Passable); + Building_Bed building_Bed = RestUtility.FindBedFor(prisoner, warden, true, false, false); + if (building_Bed != null && building_Bed.GetRoom(RegionType.Set_Passable) != room) + { + Job job = new Job(JobDefOf.EscortPrisonerToBed, (Thing)prisoner, (Thing)building_Bed); + job.count = 1; + return job; + } + return null; } return null; } private Job TakeDownedToBedJob(Pawn prisoner, Pawn warden) { - if (!prisoner.Downed || !HealthAIUtility.ShouldSeekMedicalRestUrgent(prisoner) || prisoner.InBed() || !warden.CanReserve(prisoner, 1, -1, null, false)) - { - return null; - } - Building_Bed building_Bed = RestUtility.FindBedFor(prisoner, warden, true, true, false); - if (building_Bed != null) + if (prisoner.Downed && HealthAIUtility.ShouldSeekMedicalRestUrgent(prisoner) && !prisoner.InBed() && warden.CanReserve((Thing)prisoner, 1, -1, null, false)) { - return new Job(JobDefOf.TakeWoundedPrisonerToBed, prisoner, building_Bed) + Building_Bed building_Bed = RestUtility.FindBedFor(prisoner, warden, true, true, false); + if (building_Bed != null) { - count = 1 - }; + Job job = new Job(JobDefOf.TakeWoundedPrisonerToBed, (Thing)prisoner, (Thing)building_Bed); + job.count = 1; + return job; + } + return null; } return null; } diff --git a/Assembly-CSharp/RimWorld/WorkTypeDefOf.cs b/Assembly-CSharp/RimWorld/WorkTypeDefOf.cs index e7c1343e6..dd6a4f97e 100644 --- a/Assembly-CSharp/RimWorld/WorkTypeDefOf.cs +++ b/Assembly-CSharp/RimWorld/WorkTypeDefOf.cs @@ -1,4 +1,3 @@ -using System; using Verse; namespace RimWorld diff --git a/Assembly-CSharp/RimWorld/WorldInterface.cs b/Assembly-CSharp/RimWorld/WorldInterface.cs index ddcbf2e67..9784b9dae 100644 --- a/Assembly-CSharp/RimWorld/WorldInterface.cs +++ b/Assembly-CSharp/RimWorld/WorldInterface.cs @@ -1,5 +1,4 @@ using RimWorld.Planet; -using System; using Verse; namespace RimWorld @@ -72,8 +71,7 @@ public void Reset() public void WorldInterfaceUpdate() { - bool worldRenderedNow = WorldRendererUtility.WorldRenderedNow; - if (worldRenderedNow) + if (WorldRendererUtility.WorldRenderedNow) { this.targeter.TargeterUpdate(); WorldSelectionDrawer.DrawSelectionOverlays(); @@ -112,8 +110,7 @@ public void WorldInterfaceOnGUI() public void HandleLowPriorityInput() { - bool worldRenderedNow = WorldRendererUtility.WorldRenderedNow; - if (worldRenderedNow) + if (WorldRendererUtility.WorldRenderedNow) { this.targeter.ProcessInputEvents(); this.selector.WorldSelectorOnGUI(); diff --git a/Assembly-CSharp/RimWorld/WorldObjectCompProperties.cs b/Assembly-CSharp/RimWorld/WorldObjectCompProperties.cs index 4fb9c7684..3d8f893c7 100644 --- a/Assembly-CSharp/RimWorld/WorldObjectCompProperties.cs +++ b/Assembly-CSharp/RimWorld/WorldObjectCompProperties.cs @@ -1,7 +1,6 @@ using RimWorld.Planet; using System; using System.Collections.Generic; -using System.Diagnostics; namespace RimWorld { @@ -9,16 +8,12 @@ public class WorldObjectCompProperties { public Type compClass = typeof(WorldObjectComp); - [DebuggerHidden] public virtual IEnumerable ConfigErrors(WorldObjectDef parentDef) { - WorldObjectCompProperties.c__Iterator87 c__Iterator = new WorldObjectCompProperties.c__Iterator87(); - c__Iterator.parentDef = parentDef; - c__Iterator.<$>parentDef = parentDef; - c__Iterator.<>f__this = this; - WorldObjectCompProperties.c__Iterator87 expr_1C = c__Iterator; - expr_1C.$PC = -2; - return expr_1C; + if (this.compClass == null) + { + yield return parentDef.defName + " has WorldObjectCompProperties with null compClass."; + } } public virtual void ResolveReferences(WorldObjectDef parentDef) diff --git a/Assembly-CSharp/RimWorld/WorldObjectCompProperties_CaravanRequest.cs b/Assembly-CSharp/RimWorld/WorldObjectCompProperties_CaravanRequest.cs index 4084076cd..9dce4ea41 100644 --- a/Assembly-CSharp/RimWorld/WorldObjectCompProperties_CaravanRequest.cs +++ b/Assembly-CSharp/RimWorld/WorldObjectCompProperties_CaravanRequest.cs @@ -1,5 +1,4 @@ using RimWorld.Planet; -using System; namespace RimWorld { @@ -7,7 +6,7 @@ public class WorldObjectCompProperties_CaravanRequest : WorldObjectCompPropertie { public WorldObjectCompProperties_CaravanRequest() { - this.compClass = typeof(CaravanRequestComp); + base.compClass = typeof(CaravanRequestComp); } } } diff --git a/Assembly-CSharp/RimWorld/WorldObjectCompProperties_DefeatAllEnemiesQuest.cs b/Assembly-CSharp/RimWorld/WorldObjectCompProperties_DefeatAllEnemiesQuest.cs index d1916e5eb..2ab873e21 100644 --- a/Assembly-CSharp/RimWorld/WorldObjectCompProperties_DefeatAllEnemiesQuest.cs +++ b/Assembly-CSharp/RimWorld/WorldObjectCompProperties_DefeatAllEnemiesQuest.cs @@ -1,7 +1,5 @@ using RimWorld.Planet; -using System; using System.Collections.Generic; -using System.Diagnostics; namespace RimWorld { @@ -9,19 +7,19 @@ public class WorldObjectCompProperties_DefeatAllEnemiesQuest : WorldObjectCompPr { public WorldObjectCompProperties_DefeatAllEnemiesQuest() { - this.compClass = typeof(DefeatAllEnemiesQuestComp); + base.compClass = typeof(DefeatAllEnemiesQuestComp); } - [DebuggerHidden] public override IEnumerable ConfigErrors(WorldObjectDef parentDef) { - WorldObjectCompProperties_DefeatAllEnemiesQuest.c__Iterator88 c__Iterator = new WorldObjectCompProperties_DefeatAllEnemiesQuest.c__Iterator88(); - c__Iterator.parentDef = parentDef; - c__Iterator.<$>parentDef = parentDef; - c__Iterator.<>f__this = this; - WorldObjectCompProperties_DefeatAllEnemiesQuest.c__Iterator88 expr_1C = c__Iterator; - expr_1C.$PC = -2; - return expr_1C; + foreach (string item in base.ConfigErrors(parentDef)) + { + yield return item; + } + if (!typeof(MapParent).IsAssignableFrom(parentDef.worldObjectClass)) + { + yield return parentDef.defName + " has WorldObjectCompProperties_DefeatAllEnemiesQuest but it's not MapParent."; + } } } } diff --git a/Assembly-CSharp/RimWorld/WorldObjectCompProperties_ItemStashContents.cs b/Assembly-CSharp/RimWorld/WorldObjectCompProperties_ItemStashContents.cs index dd2a128cf..152e87bb7 100644 --- a/Assembly-CSharp/RimWorld/WorldObjectCompProperties_ItemStashContents.cs +++ b/Assembly-CSharp/RimWorld/WorldObjectCompProperties_ItemStashContents.cs @@ -1,5 +1,4 @@ using RimWorld.Planet; -using System; namespace RimWorld { @@ -7,7 +6,7 @@ public class WorldObjectCompProperties_ItemStashContents : WorldObjectCompProper { public WorldObjectCompProperties_ItemStashContents() { - this.compClass = typeof(ItemStashContentsComp); + base.compClass = typeof(ItemStashContentsComp); } } } diff --git a/Assembly-CSharp/RimWorld/WorldObjectCompProperties_Timeout.cs b/Assembly-CSharp/RimWorld/WorldObjectCompProperties_Timeout.cs index eeb8fbabb..913c45f4c 100644 --- a/Assembly-CSharp/RimWorld/WorldObjectCompProperties_Timeout.cs +++ b/Assembly-CSharp/RimWorld/WorldObjectCompProperties_Timeout.cs @@ -1,5 +1,4 @@ using RimWorld.Planet; -using System; namespace RimWorld { @@ -7,7 +6,7 @@ public class WorldObjectCompProperties_Timeout : WorldObjectCompProperties { public WorldObjectCompProperties_Timeout() { - this.compClass = typeof(TimeoutComp); + base.compClass = typeof(TimeoutComp); } } } diff --git a/Assembly-CSharp/RimWorld/WorldObjectDef.cs b/Assembly-CSharp/RimWorld/WorldObjectDef.cs index 96c66a5b4..d2ade3f5b 100644 --- a/Assembly-CSharp/RimWorld/WorldObjectDef.cs +++ b/Assembly-CSharp/RimWorld/WorldObjectDef.cs @@ -1,7 +1,6 @@ using RimWorld.Planet; using System; using System.Collections.Generic; -using System.Diagnostics; using UnityEngine; using Verse; @@ -58,7 +57,7 @@ public Material Material { return null; } - if (this.material == null) + if ((UnityEngine.Object)this.material == (UnityEngine.Object)null) { this.material = MaterialPool.MatFrom(this.texture, ShaderDatabase.WorldOverlayTransparentLit, WorldMaterials.WorldObjectRenderQueue); } @@ -70,7 +69,7 @@ public Texture2D ExpandingIconTexture { get { - if (this.expandingIconTextureInt == null) + if ((UnityEngine.Object)this.expandingIconTextureInt == (UnityEngine.Object)null) { if (this.expandingIconTexture.NullOrEmpty()) { @@ -99,13 +98,7 @@ public override void PostLoad() } catch (Exception ex) { - Log.Error(string.Concat(new object[] - { - "Could not instantiate inspector tab of type ", - this.inspectorTabs[i], - ": ", - ex - })); + Log.Error("Could not instantiate inspector tab of type " + this.inspectorTabs[i] + ": " + ex); } } } @@ -120,14 +113,19 @@ public override void ResolveReferences() } } - [DebuggerHidden] public override IEnumerable ConfigErrors() { - WorldObjectDef.c__IteratorA0 c__IteratorA = new WorldObjectDef.c__IteratorA0(); - c__IteratorA.<>f__this = this; - WorldObjectDef.c__IteratorA0 expr_0E = c__IteratorA; - expr_0E.$PC = -2; - return expr_0E; + foreach (string item in base.ConfigErrors()) + { + yield return item; + } + for (int i = 0; i < this.comps.Count; i++) + { + foreach (string item2 in this.comps[i].ConfigErrors(this)) + { + yield return item2; + } + } } } } diff --git a/Assembly-CSharp/RimWorld/WorldObjectDefOf.cs b/Assembly-CSharp/RimWorld/WorldObjectDefOf.cs index 95b243b8f..6e0c3cce8 100644 --- a/Assembly-CSharp/RimWorld/WorldObjectDefOf.cs +++ b/Assembly-CSharp/RimWorld/WorldObjectDefOf.cs @@ -1,5 +1,3 @@ -using System; - namespace RimWorld { [DefOf] diff --git a/Assembly-CSharp/RimWorld/WorldTargeter.cs b/Assembly-CSharp/RimWorld/WorldTargeter.cs index 21c05423f..ab08363d2 100644 --- a/Assembly-CSharp/RimWorld/WorldTargeter.cs +++ b/Assembly-CSharp/RimWorld/WorldTargeter.cs @@ -28,7 +28,7 @@ public bool IsTargeting { get { - return this.action != null; + return (object)this.action != null; } } @@ -91,9 +91,9 @@ public void TargeterOnGUI() { Vector2 mousePosition = Event.current.mousePosition; Texture2D image = this.mouseAttachment ?? TexCommand.Attack; - Rect position = new Rect(mousePosition.x + 8f, mousePosition.y + 8f, 32f, 32f); + Rect position = new Rect((float)(mousePosition.x + 8.0), (float)(mousePosition.y + 8.0), 32f, 32f); GUI.DrawTexture(position, image); - if (this.extraLabelGetter != null) + if ((object)this.extraLabelGetter != null) { string text = this.extraLabelGetter(this.CurrentTargetUnderMouse()); if (!text.NullOrEmpty()) @@ -122,9 +122,9 @@ public void TargeterUpdate() } if (globalTargetInfo.IsValid) { - WorldRendererUtility.DrawQuadTangentialToPlanet(pos, 0.8f * Find.WorldGrid.averageTileSize, 0.018f, WorldMaterials.CurTargetingMat, false, false, null); + WorldRendererUtility.DrawQuadTangentialToPlanet(pos, (float)(0.800000011920929 * Find.WorldGrid.averageTileSize), 0.018f, WorldMaterials.CurTargetingMat, false, false, null); } - if (this.onUpdate != null) + if ((object)this.onUpdate != null) { this.onUpdate(); } @@ -141,7 +141,11 @@ public bool IsTargetedNow(WorldObject o, List worldObjectsUnderMous { worldObjectsUnderMouse = GenWorldUI.WorldObjectsUnderMouse(UI.MousePositionOnUI); } - return worldObjectsUnderMouse.Any() && o == worldObjectsUnderMouse[0]; + if (worldObjectsUnderMouse.Any()) + { + return o == worldObjectsUnderMouse[0]; + } + return false; } private GlobalTargetInfo CurrentTargetUnderMouse() @@ -151,19 +155,19 @@ private GlobalTargetInfo CurrentTargetUnderMouse() return GlobalTargetInfo.Invalid; } List list = GenWorldUI.WorldObjectsUnderMouse(UI.MousePositionOnUI); - if (list.Any()) + if (list.Any()) { return list[0]; } - if (!this.canTargetTiles) + if (this.canTargetTiles) { + int num = GenWorld.MouseTile(false); + if (num >= 0) + { + return new GlobalTargetInfo(num); + } return GlobalTargetInfo.Invalid; } - int num = GenWorld.MouseTile(false); - if (num >= 0) - { - return new GlobalTargetInfo(num); - } return GlobalTargetInfo.Invalid; } } diff --git a/Assembly-CSharp/RimWorld/ZonePresetNames.cs b/Assembly-CSharp/RimWorld/ZonePresetNames.cs index 06a7e804e..e7658bfb0 100644 --- a/Assembly-CSharp/RimWorld/ZonePresetNames.cs +++ b/Assembly-CSharp/RimWorld/ZonePresetNames.cs @@ -1,4 +1,3 @@ -using System; using Verse; namespace RimWorld @@ -7,15 +6,21 @@ public static class ZonePresetNames { public static string PresetName(this StorageSettingsPreset preset) { - if (preset == StorageSettingsPreset.DumpingStockpile) + switch (preset) + { + case StorageSettingsPreset.DumpingStockpile: { return "DumpingStockpile".Translate(); } - if (preset == StorageSettingsPreset.DefaultStockpile) + case StorageSettingsPreset.DefaultStockpile: { return "Stockpile".Translate(); } - return "Zone".Translate(); + default: + { + return "Zone".Translate(); + } + } } } } diff --git a/Assembly-CSharp/RimWorld/Zone_Growing.cs b/Assembly-CSharp/RimWorld/Zone_Growing.cs index e1b4b41e7..2b94e9346 100644 --- a/Assembly-CSharp/RimWorld/Zone_Growing.cs +++ b/Assembly-CSharp/RimWorld/Zone_Growing.cs @@ -1,6 +1,5 @@ using System; using System.Collections.Generic; -using System.Diagnostics; using System.Linq; using UnityEngine; using Verse; @@ -47,29 +46,15 @@ public override void ExposeData() public override string GetInspectString() { string text = string.Empty; - if (!base.Cells.NullOrEmpty()) + if (!base.Cells.NullOrEmpty()) { - IntVec3 c = base.Cells.First(); + IntVec3 c = base.Cells.First(); if (c.UsesOutdoorTemperature(base.Map)) { string text2 = text; - text = string.Concat(new string[] - { - text2, - "OutdoorGrowingPeriod".Translate(), - ": ", - Zone_Growing.GrowingQuadrumsDescription(base.Map.Tile), - "\n" - }); - } - if (GenPlant.GrowthSeasonNow(c, base.Map)) - { - text += "GrowSeasonHereNow".Translate(); - } - else - { - text += "CannotGrowBadSeasonTemperature".Translate(); + text = text2 + "OutdoorGrowingPeriod".Translate() + ": " + Zone_Growing.GrowingQuadrumsDescription(base.Map.Tile) + "\n"; } + text = ((!GenPlant.GrowthSeasonNow(c, base.Map)) ? (text + "CannotGrowBadSeasonTemperature".Translate()) : (text + "GrowSeasonHereNow".Translate())); } return text; } @@ -77,7 +62,7 @@ public override string GetInspectString() public static string GrowingQuadrumsDescription(int tile) { List list = GenTemperature.TwelfthsInAverageTemperatureRange(tile, 10f, 42f); - if (list.NullOrEmpty()) + if (list.NullOrEmpty()) { return "NoGrowingPeriod".Translate(); } @@ -85,20 +70,28 @@ public static string GrowingQuadrumsDescription(int tile) { return "GrowYearRound".Translate(); } - return "PeriodDays".Translate(new object[] - { - list.Count * 5 - }) + " (" + QuadrumUtility.QuadrumsRangeLabel(list) + ")"; + return "PeriodDays".Translate(list.Count * 5) + " (" + QuadrumUtility.QuadrumsRangeLabel(list) + ")"; } - [DebuggerHidden] public override IEnumerable GetGizmos() { - Zone_Growing.c__IteratorBB c__IteratorBB = new Zone_Growing.c__IteratorBB(); - c__IteratorBB.<>f__this = this; - Zone_Growing.c__IteratorBB expr_0E = c__IteratorBB; - expr_0E.$PC = -2; - return expr_0E; + foreach (Gizmo gizmo in base.GetGizmos()) + { + yield return gizmo; + } + yield return (Gizmo)PlantToGrowSettableUtility.SetPlantToGrowCommand(this); + yield return (Gizmo)new Command_Toggle + { + defaultLabel = "CommandAllowSow".Translate(), + defaultDesc = "CommandAllowSowDesc".Translate(), + hotKey = KeyBindingDefOf.CommandItemForbid, + icon = TexCommand.Forbidden, + isActive = (Func)(() => ((_003CGetGizmos_003Ec__IteratorBB)/*Error near IL_0126: stateMachine*/)._003C_003Ef__this.allowSow), + toggleAction = (Action)delegate + { + ((_003CGetGizmos_003Ec__IteratorBB)/*Error near IL_013d: stateMachine*/)._003C_003Ef__this.allowSow = !((_003CGetGizmos_003Ec__IteratorBB)/*Error near IL_013d: stateMachine*/)._003C_003Ef__this.allowSow; + } + }; } public ThingDef GetPlantDefToGrow() @@ -120,5 +113,11 @@ virtual Map get_Map() { return base.Map; } + + Map IPlantToGrowSettable.get_Map() + { + //ILSpy generated this explicit interface implementation from .override directive in get_Map + return this.get_Map(); + } } } diff --git a/Assembly-CSharp/RimWorld/Zone_Stockpile.cs b/Assembly-CSharp/RimWorld/Zone_Stockpile.cs index 6f530b365..f9a1a3272 100644 --- a/Assembly-CSharp/RimWorld/Zone_Stockpile.cs +++ b/Assembly-CSharp/RimWorld/Zone_Stockpile.cs @@ -1,6 +1,4 @@ -using System; using System.Collections.Generic; -using System.Diagnostics; using UnityEngine; using Verse; @@ -52,7 +50,7 @@ public Zone_Stockpile(StorageSettingsPreset preset, ZoneManager zoneManager) : b public override void ExposeData() { base.ExposeData(); - Scribe_Deep.Look(ref this.settings, "settings", new object[] + Scribe_Deep.Look(ref this.settings, "settings", new object[1] { this }); @@ -83,23 +81,21 @@ public override void Deregister() this.slotGroup.Notify_ParentDestroying(); } - [DebuggerHidden] public override IEnumerable GetInspectTabs() { - Zone_Stockpile.c__IteratorBC c__IteratorBC = new Zone_Stockpile.c__IteratorBC(); - Zone_Stockpile.c__IteratorBC expr_07 = c__IteratorBC; - expr_07.$PC = -2; - return expr_07; + yield return (InspectTabBase)Zone_Stockpile.StorageTab; } - [DebuggerHidden] public override IEnumerable GetGizmos() { - Zone_Stockpile.c__IteratorBD c__IteratorBD = new Zone_Stockpile.c__IteratorBD(); - c__IteratorBD.<>f__this = this; - Zone_Stockpile.c__IteratorBD expr_0E = c__IteratorBD; - expr_0E.$PC = -2; - return expr_0E; + foreach (Gizmo gizmo in base.GetGizmos()) + { + yield return gizmo; + } + foreach (Gizmo item in StorageSettingsClipboard.CopyPasteGizmosFor(this.settings)) + { + yield return item; + } } public SlotGroup GetSlotGroup() @@ -107,19 +103,17 @@ public SlotGroup GetSlotGroup() return this.slotGroup; } - [DebuggerHidden] public IEnumerable AllSlotCells() { - Zone_Stockpile.c__IteratorBE c__IteratorBE = new Zone_Stockpile.c__IteratorBE(); - c__IteratorBE.<>f__this = this; - Zone_Stockpile.c__IteratorBE expr_0E = c__IteratorBE; - expr_0E.$PC = -2; - return expr_0E; + for (int i = 0; i < base.cells.Count; i++) + { + yield return base.cells[i]; + } } public List AllSlotCellsList() { - return this.cells; + return base.cells; } public StorageSettings GetParentStoreSettings() @@ -134,7 +128,7 @@ public StorageSettings GetStoreSettings() public string SlotYielderLabel() { - return this.label; + return base.label; } public void Notify_ReceivedThing(Thing newItem) @@ -153,5 +147,11 @@ virtual Map get_Map() { return base.Map; } + + Map ISlotGroupParent.get_Map() + { + //ILSpy generated this explicit interface implementation from .override directive in get_Map + return this.get_Map(); + } } } diff --git a/Assembly-CSharp/RuntimeAudioClipLoader/AudioFormat.cs b/Assembly-CSharp/RuntimeAudioClipLoader/AudioFormat.cs index 96e16e3da..a6604ca78 100644 --- a/Assembly-CSharp/RuntimeAudioClipLoader/AudioFormat.cs +++ b/Assembly-CSharp/RuntimeAudioClipLoader/AudioFormat.cs @@ -1,13 +1,11 @@ -using System; - namespace RuntimeAudioClipLoader { public enum AudioFormat { - wav, - mp3, - aiff, - ogg, + wav = 0, + mp3 = 1, + aiff = 2, + ogg = 3, unknown = -1 } } diff --git a/Assembly-CSharp/RuntimeAudioClipLoader/CustomAudioFileReader.cs b/Assembly-CSharp/RuntimeAudioClipLoader/CustomAudioFileReader.cs index fa2fd4cb9..6ca946055 100644 --- a/Assembly-CSharp/RuntimeAudioClipLoader/CustomAudioFileReader.cs +++ b/Assembly-CSharp/RuntimeAudioClipLoader/CustomAudioFileReader.cs @@ -1,8 +1,8 @@ using NAudio.Wave; using NAudio.Wave.SampleProviders; using NVorbis.NAudioSupport; -using System; using System.IO; +using System.Threading; using UnityEngine; namespace RuntimeAudioClipLoader @@ -46,10 +46,15 @@ public override long Position set { object obj = this.lockObject; - lock (obj) + Monitor.Enter(obj); + try { this.readerStream.Position = this.DestToSource(value); } + finally + { + Monitor.Exit(obj); + } } } @@ -77,7 +82,9 @@ public CustomAudioFileReader(Stream stream, AudioFormat format) private void CreateReaderStream(Stream stream, AudioFormat format) { - if (format == AudioFormat.wav) + switch (format) + { + case AudioFormat.wav: { this.readerStream = new WaveFileReader(stream); if (this.readerStream.WaveFormat.Encoding != WaveFormatEncoding.Pcm && this.readerStream.WaveFormat.Encoding != WaveFormatEncoding.IeeeFloat) @@ -85,22 +92,28 @@ private void CreateReaderStream(Stream stream, AudioFormat format) this.readerStream = WaveFormatConversionStream.CreatePcmStream(this.readerStream); this.readerStream = new BlockAlignReductionStream(this.readerStream); } + break; } - else if (format == AudioFormat.mp3) + case AudioFormat.mp3: { this.readerStream = new Mp3FileReader(stream); + break; } - else if (format == AudioFormat.aiff) + case AudioFormat.aiff: { this.readerStream = new AiffFileReader(stream); + break; } - else if (format == AudioFormat.ogg) + case AudioFormat.ogg: { this.readerStream = new VorbisWaveReader(stream); + break; } - else + default: { Debug.LogWarning("Audio format " + format + " is not supported"); + break; + } } } @@ -115,22 +128,28 @@ public override int Read(byte[] buffer, int offset, int count) public int Read(float[] buffer, int offset, int count) { object obj = this.lockObject; - int result; - lock (obj) + Monitor.Enter(obj); + try + { + return this.sampleChannel.Read(buffer, offset, count); + IL_0021: + int result; + return result; + } + finally { - result = this.sampleChannel.Read(buffer, offset, count); + Monitor.Exit(obj); } - return result; } private long SourceToDest(long sourceBytes) { - return (long)this.destBytesPerSample * (sourceBytes / (long)this.sourceBytesPerSample); + return this.destBytesPerSample * (sourceBytes / this.sourceBytesPerSample); } private long DestToSource(long destBytes) { - return (long)this.sourceBytesPerSample * (destBytes / (long)this.destBytesPerSample); + return this.sourceBytesPerSample * (destBytes / this.destBytesPerSample); } protected override void Dispose(bool disposing) diff --git a/Assembly-CSharp/RuntimeAudioClipLoader/Manager.cs b/Assembly-CSharp/RuntimeAudioClipLoader/Manager.cs index dfea3ac2b..12a8dfb1d 100644 --- a/Assembly-CSharp/RuntimeAudioClipLoader/Manager.cs +++ b/Assembly-CSharp/RuntimeAudioClipLoader/Manager.cs @@ -39,7 +39,7 @@ public int sampleRate } } - public static implicit operator AudioClip(Manager.AudioInstance ai) + public static implicit operator AudioClip(AudioInstance ai) { return ai.audioClip; } @@ -49,11 +49,11 @@ public static implicit operator AudioClip(Manager.AudioInstance ai) private static Dictionary cache; - private static Queue deferredLoadQueue; + private static Queue deferredLoadQueue; - private static Queue deferredSetDataQueue; + private static Queue deferredSetDataQueue; - private static Queue deferredSetFail; + private static Queue deferredSetFail; private static Thread deferredLoaderThread; @@ -66,9 +66,9 @@ public static implicit operator AudioClip(Manager.AudioInstance ai) static Manager() { Manager.cache = new Dictionary(); - Manager.deferredLoadQueue = new Queue(); - Manager.deferredSetDataQueue = new Queue(); - Manager.deferredSetFail = new Queue(); + Manager.deferredLoadQueue = new Queue(); + Manager.deferredSetDataQueue = new Queue(); + Manager.deferredSetFail = new Queue(); Manager.audioClipLoadType = new Dictionary(); Manager.audioLoadState = new Dictionary(); Manager.supportedFormats = Enum.GetNames(typeof(AudioFormat)); @@ -82,7 +82,7 @@ public static AudioClip Load(string filePath, bool doStream = false, bool loadIn return null; } AudioClip audioClip = null; - if (useCache && Manager.cache.TryGetValue(filePath, out audioClip) && audioClip) + if (useCache && Manager.cache.TryGetValue(filePath, out audioClip) && (UnityEngine.Object)audioClip) { return audioClip; } @@ -102,95 +102,96 @@ public static AudioClip Load(Stream dataStream, AudioFormat audioFormat, string try { reader = new CustomAudioFileReader(dataStream, audioFormat); - Manager.AudioInstance audioInstance = new Manager.AudioInstance - { - reader = reader, - samplesCount = (int)(reader.Length / (long)(reader.WaveFormat.BitsPerSample / 8)) - }; + AudioInstance audioInstance = new AudioInstance(); + audioInstance.reader = reader; + audioInstance.samplesCount = (int)(reader.Length / (reader.WaveFormat.BitsPerSample / 8)); + AudioInstance audioInstance2 = audioInstance; if (doStream) { - audioClip = AudioClip.Create(unityAudioClipName, audioInstance.samplesCount / audioInstance.channels, audioInstance.channels, audioInstance.sampleRate, doStream, delegate(float[] target) + audioClip = (audioInstance2.audioClip = AudioClip.Create(unityAudioClipName, audioInstance2.samplesCount / audioInstance2.channels, audioInstance2.channels, audioInstance2.sampleRate, doStream, (AudioClip.PCMReaderCallback)delegate(float[] target) { reader.Read(target, 0, target.Length); - }, delegate(int target) + }, (AudioClip.PCMSetPositionCallback)delegate(int target) { - reader.Seek((long)target, SeekOrigin.Begin); - }); - audioInstance.audioClip = audioClip; - Manager.SetAudioClipLoadType(audioInstance, AudioClipLoadType.Streaming); - Manager.SetAudioClipLoadState(audioInstance, AudioDataLoadState.Loaded); + reader.Seek(target, SeekOrigin.Begin); + })); + Manager.SetAudioClipLoadType(audioInstance2, AudioClipLoadType.Streaming); + Manager.SetAudioClipLoadState(audioInstance2, AudioDataLoadState.Loaded); + return audioClip; } - else + audioClip = (audioInstance2.audioClip = AudioClip.Create(unityAudioClipName, audioInstance2.samplesCount / audioInstance2.channels, audioInstance2.channels, audioInstance2.sampleRate, doStream)); + if (diposeDataStreamIfNotNeeded) { - audioClip = AudioClip.Create(unityAudioClipName, audioInstance.samplesCount / audioInstance.channels, audioInstance.channels, audioInstance.sampleRate, doStream); - audioInstance.audioClip = audioClip; - if (diposeDataStreamIfNotNeeded) - { - audioInstance.streamToDisposeOnceDone = dataStream; - } - Manager.SetAudioClipLoadType(audioInstance, AudioClipLoadType.DecompressOnLoad); - Manager.SetAudioClipLoadState(audioInstance, AudioDataLoadState.Loading); - if (loadInBackground) + audioInstance2.streamToDisposeOnceDone = dataStream; + } + Manager.SetAudioClipLoadType(audioInstance2, AudioClipLoadType.DecompressOnLoad); + Manager.SetAudioClipLoadState(audioInstance2, AudioDataLoadState.Loading); + if (loadInBackground) + { + Queue obj = Manager.deferredLoadQueue; + Monitor.Enter(obj); + try { - Queue obj = Manager.deferredLoadQueue; - lock (obj) - { - Manager.deferredLoadQueue.Enqueue(audioInstance); - } - Manager.RunDeferredLoaderThread(); - Manager.EnsureInstanceExists(); + Manager.deferredLoadQueue.Enqueue(audioInstance2); } - else + finally { - audioInstance.dataToSet = new float[audioInstance.samplesCount]; - audioInstance.reader.Read(audioInstance.dataToSet, 0, audioInstance.dataToSet.Length); - audioInstance.audioClip.SetData(audioInstance.dataToSet, 0); - Manager.SetAudioClipLoadState(audioInstance, AudioDataLoadState.Loaded); + Monitor.Exit(obj); } + Manager.RunDeferredLoaderThread(); + Manager.EnsureInstanceExists(); + return audioClip; } + audioInstance2.dataToSet = new float[audioInstance2.samplesCount]; + audioInstance2.reader.Read(audioInstance2.dataToSet, 0, audioInstance2.dataToSet.Length); + audioInstance2.audioClip.SetData(audioInstance2.dataToSet, 0); + Manager.SetAudioClipLoadState(audioInstance2, AudioDataLoadState.Loaded); + return audioClip; } catch (Exception ex) { Manager.SetAudioClipLoadState(audioClip, AudioDataLoadState.Failed); - Debug.LogError(string.Concat(new object[] - { - "Could not load AudioClip named '", - unityAudioClipName, - "', exception:", - ex - })); + Debug.LogError("Could not load AudioClip named '" + unityAudioClipName + "', exception:" + ex); + return audioClip; } - return audioClip; } private static void RunDeferredLoaderThread() { - if (Manager.deferredLoaderThread == null || !Manager.deferredLoaderThread.IsAlive) - { - Manager.deferredLoaderThread = new Thread(new ThreadStart(Manager.DeferredLoaderMain)); - Manager.deferredLoaderThread.IsBackground = true; - Manager.deferredLoaderThread.Start(); - } + if (Manager.deferredLoaderThread != null && Manager.deferredLoaderThread.IsAlive) + return; + Manager.deferredLoaderThread = new Thread(new ThreadStart(Manager.DeferredLoaderMain)); + Manager.deferredLoaderThread.IsBackground = true; + Manager.deferredLoaderThread.Start(); } private static void DeferredLoaderMain() { - Manager.AudioInstance audioInstance = null; + AudioInstance audioInstance = null; bool flag = true; long num = 100000L; - while (flag || num > 0L) + while (true) { - num -= 1L; - Queue obj = Manager.deferredLoadQueue; - lock (obj) + if (!flag && num <= 0) + break; + num--; + Queue obj = Manager.deferredLoadQueue; + Monitor.Enter(obj); + try { flag = (Manager.deferredLoadQueue.Count > 0); - if (!flag) + if (flag) { - continue; + audioInstance = Manager.deferredLoadQueue.Dequeue(); + goto IL_0051; } - audioInstance = Manager.deferredLoadQueue.Dequeue(); } + finally + { + Monitor.Exit(obj); + } + continue; + IL_0051: num = 100000L; try { @@ -204,47 +205,60 @@ private static void DeferredLoaderMain() audioInstance.streamToDisposeOnceDone.Dispose(); audioInstance.streamToDisposeOnceDone = null; } - Queue obj2 = Manager.deferredSetDataQueue; - lock (obj2) + Queue obj2 = Manager.deferredSetDataQueue; + Monitor.Enter(obj2); + try { Manager.deferredSetDataQueue.Enqueue(audioInstance); } + finally + { + Monitor.Exit(obj2); + } } catch (Exception exception) { Debug.LogException(exception); - Queue obj3 = Manager.deferredSetFail; - lock (obj3) + Queue obj3 = Manager.deferredSetFail; + Monitor.Enter(obj3); + try { Manager.deferredSetFail.Enqueue(audioInstance); } + finally + { + Monitor.Exit(obj3); + } } } } private void Update() { - Manager.AudioInstance audioInstance = null; + AudioInstance audioInstance = null; bool flag = true; - while (flag) + for (; flag; audioInstance.audioClip.SetData(audioInstance.dataToSet, 0), Manager.SetAudioClipLoadState(audioInstance, AudioDataLoadState.Loaded), audioInstance.audioClip = null, audioInstance.dataToSet = null) { - Queue obj = Manager.deferredSetDataQueue; - lock (obj) + Queue obj = Manager.deferredSetDataQueue; + Monitor.Enter(obj); + try { flag = (Manager.deferredSetDataQueue.Count > 0); - if (!flag) + if (flag) { - break; + audioInstance = Manager.deferredSetDataQueue.Dequeue(); + continue; } - audioInstance = Manager.deferredSetDataQueue.Dequeue(); } - audioInstance.audioClip.SetData(audioInstance.dataToSet, 0); - Manager.SetAudioClipLoadState(audioInstance, AudioDataLoadState.Loaded); - audioInstance.audioClip = null; - audioInstance.dataToSet = null; + finally + { + Monitor.Exit(obj); + } + break; } - Queue obj2 = Manager.deferredSetFail; - lock (obj2) + Queue obj2 = Manager.deferredSetFail; + Monitor.Enter(obj2); + try { while (Manager.deferredSetFail.Count > 0) { @@ -252,11 +266,15 @@ private void Update() Manager.SetAudioClipLoadState(audioInstance, AudioDataLoadState.Failed); } } + finally + { + Monitor.Exit(obj2); + } } private static void EnsureInstanceExists() { - if (!Manager.managerInstance) + if (!(UnityEngine.Object)Manager.managerInstance) { Manager.managerInstance = new GameObject("Runtime AudioClip Loader Manger singleton instance"); Manager.managerInstance.hideFlags = HideFlags.HideAndDontSave; @@ -272,7 +290,7 @@ public static void SetAudioClipLoadState(AudioClip audioClip, AudioDataLoadState public static AudioDataLoadState GetAudioClipLoadState(AudioClip audioClip) { AudioDataLoadState result = AudioDataLoadState.Failed; - if (audioClip != null) + if ((UnityEngine.Object)audioClip != (UnityEngine.Object)null) { result = audioClip.loadState; Manager.audioLoadState.TryGetValue(audioClip, out result); @@ -288,7 +306,7 @@ public static void SetAudioClipLoadType(AudioClip audioClip, AudioClipLoadType n public static AudioClipLoadType GetAudioClipLoadType(AudioClip audioClip) { AudioClipLoadType result = (AudioClipLoadType)(-1); - if (audioClip != null) + if ((UnityEngine.Object)audioClip != (UnityEngine.Object)null) { result = audioClip.loadType; Manager.audioClipLoadType.TryGetValue(audioClip, out result); @@ -311,12 +329,13 @@ public static AudioFormat GetAudioFormat(string filePath) AudioFormat result = AudioFormat.unknown; try { - result = (AudioFormat)((int)Enum.Parse(typeof(AudioFormat), Manager.GetExtension(filePath), true)); + result = (AudioFormat)(int)Enum.Parse(typeof(AudioFormat), Manager.GetExtension(filePath), true); + return result; } catch { + return result; } - return result; } public static void ClearCache() diff --git a/Assembly-CSharp/Verse.AI.Group/AvoidGridMode.cs b/Assembly-CSharp/Verse.AI.Group/AvoidGridMode.cs index 48952900e..18870ea91 100644 --- a/Assembly-CSharp/Verse.AI.Group/AvoidGridMode.cs +++ b/Assembly-CSharp/Verse.AI.Group/AvoidGridMode.cs @@ -1,11 +1,9 @@ -using System; - namespace Verse.AI.Group { public enum AvoidGridMode { - Ignore, - Basic, - Smart + Ignore = 0, + Basic = 1, + Smart = 2 } } diff --git a/Assembly-CSharp/Verse.AI.Group/Lord.cs b/Assembly-CSharp/Verse.AI.Group/Lord.cs index 3b6c740ca..91af8ae93 100644 --- a/Assembly-CSharp/Verse.AI.Group/Lord.cs +++ b/Assembly-CSharp/Verse.AI.Group/Lord.cs @@ -114,7 +114,7 @@ public void ExposeData() Scribe_Values.Look(ref this.lastPawnHarmTick, "lastPawnHarmTick", -99999, false); if (Scribe.mode == LoadSaveMode.PostLoadInit) { - this.extraForbiddenThings.RemoveAll((Thing x) => x == null); + this.extraForbiddenThings.RemoveAll((Predicate)((Thing x) => x == null)); } this.ExposeData_StateGraph(); } @@ -160,56 +160,52 @@ private void ExposeData_StateGraph() LordJob job = this.curJob; this.curJob = null; this.SetJob(job); - foreach (KeyValuePair current in this.tmpLordToilData) + Dictionary.Enumerator enumerator = this.tmpLordToilData.GetEnumerator(); + try { - if (current.Key < 0 || current.Key >= this.graph.lordToils.Count) + while (enumerator.MoveNext()) { - Log.Error(string.Concat(new object[] + KeyValuePair current = enumerator.Current; + if (current.Key < 0 || current.Key >= this.graph.lordToils.Count) { - "Could not find lord toil for lord toil data of type \"", - current.Value.GetType(), - "\" (lord job: \"", - this.curJob.GetType(), - "\"), because lord toil index is out of bounds: ", - current.Key - })); - } - else - { - this.graph.lordToils[current.Key].data = current.Value; + Log.Error("Could not find lord toil for lord toil data of type \"" + current.Value.GetType() + "\" (lord job: \"" + this.curJob.GetType() + "\"), because lord toil index is out of bounds: " + current.Key); + } + else + { + this.graph.lordToils[current.Key].data = current.Value; + } } } + finally + { + ((IDisposable)(object)enumerator).Dispose(); + } this.tmpLordToilData.Clear(); - foreach (KeyValuePair current2 in this.tmpTriggerData) + Dictionary.Enumerator enumerator2 = this.tmpTriggerData.GetEnumerator(); + try { - Trigger triggerByIndex = this.GetTriggerByIndex(current2.Key); - if (triggerByIndex == null) + while (enumerator2.MoveNext()) { - Log.Error(string.Concat(new object[] + KeyValuePair current2 = enumerator2.Current; + Trigger triggerByIndex = this.GetTriggerByIndex(current2.Key); + if (triggerByIndex == null) { - "Could not find trigger for trigger data of type \"", - current2.Value.GetType(), - "\" (lord job: \"", - this.curJob.GetType(), - "\"), because trigger index is out of bounds: ", - current2.Key - })); - } - else - { - triggerByIndex.data = current2.Value; + Log.Error("Could not find trigger for trigger data of type \"" + current2.Value.GetType() + "\" (lord job: \"" + this.curJob.GetType() + "\"), because trigger index is out of bounds: " + current2.Key); + } + else + { + triggerByIndex.data = current2.Value; + } } } + finally + { + ((IDisposable)(object)enumerator2).Dispose(); + } this.tmpTriggerData.Clear(); if (this.tmpCurLordToilIdx < 0 || this.tmpCurLordToilIdx >= this.graph.lordToils.Count) { - Log.Error(string.Concat(new object[] - { - "Current lord toil index out of bounds (lord job: \"", - this.curJob.GetType(), - "\"): ", - this.tmpCurLordToilIdx - })); + Log.Error("Current lord toil index out of bounds (lord job: \"" + this.curJob.GetType() + "\"): " + this.tmpCurLordToilIdx); } else { @@ -240,11 +236,7 @@ public void SetJob(LordJob lordJob) for (int i = 0; i < this.graph.lordToils.Count; i++) { Transition transition = new Transition(this.graph.lordToils[i], lordToil_PanicFlee); - transition.AddPreAction(new TransitionAction_Message("MessageFightersFleeing".Translate(new object[] - { - this.faction.def.pawnsPlural.CapitalizeFirst(), - this.faction.Name - }))); + transition.AddPreAction(new TransitionAction_Message("MessageFightersFleeing".Translate(this.faction.def.pawnsPlural.CapitalizeFirst(), this.faction.Name))); transition.AddTrigger(new Trigger_FractionPawnsLost(0.5f)); this.graph.AddTransition(transition); } @@ -285,35 +277,20 @@ public void AddPawn(Pawn p) { if (this.ownedPawns.Contains(p)) { - Log.Error(string.Concat(new object[] - { - "Lord for ", - this.faction, - " tried to add ", - p, - " whom it already controls." - })); - return; + Log.Error("Lord for " + this.faction + " tried to add " + p + " whom it already controls."); } - if (p.GetLord() != null) + else if (p.GetLord() != null) { - Log.Error(string.Concat(new object[] - { - "Tried to add pawn ", - p, - " to lord ", - this, - " but this pawn is already a member of lord ", - p.GetLord(), - ". Pawns can't be members of more than one lord at the same time." - })); - return; - } - this.ownedPawns.Add(p); - this.numPawnsEverGained++; - this.Map.attackTargetsCache.UpdateTarget(p); - this.curLordToil.UpdateAllDuties(); - this.curJob.Notify_PawnAdded(p); + Log.Error("Tried to add pawn " + p + " to lord " + this + " but this pawn is already a member of lord " + p.GetLord() + ". Pawns can't be members of more than one lord at the same time."); + } + else + { + this.ownedPawns.Add(p); + this.numPawnsEverGained++; + this.Map.attackTargetsCache.UpdateTarget(p); + this.curLordToil.UpdateAllDuties(); + this.curJob.Notify_PawnAdded(p); + } } private void RemovePawn(Pawn p) @@ -417,15 +394,11 @@ public void Notify_PawnLost(Pawn pawn, PawnLostCondition cond) condition = cond }); } - return; } - Log.Error(string.Concat(new object[] + else { - "Lord lost pawn ", - pawn, - " it didn't have. Condition=", - cond - })); + Log.Error("Lord lost pawn " + pawn + " it didn't have. Condition=" + cond); + } } public void Notify_BuildingDamaged(Building building, DamageInfo dinfo) @@ -492,14 +465,22 @@ private Vector3 DebugCenter() Vector3 result = this.Map.Center.ToVector3ShiftedWithAltitude(AltitudeLayer.MetaOverlays); if ((from p in this.ownedPawns where p.Spawned - select p).Any()) + select p).Any()) { result.x = (from p in this.ownedPawns where p.Spawned - select p).Average((Pawn p) => p.DrawPos.x); + select p).Average((Func)delegate(Pawn p) + { + Vector3 drawPos2 = p.DrawPos; + return drawPos2.x; + }); result.z = (from p in this.ownedPawns where p.Spawned - select p).Average((Pawn p) => p.DrawPos.z); + select p).Average((Func)delegate(Pawn p) + { + Vector3 drawPos = p.DrawPos; + return drawPos.z; + }); } return result; } @@ -513,10 +494,19 @@ public void DebugDraw() Graphics.DrawMesh(MeshPool.plane14, flagLoc.ToVector3ShiftedWithAltitude(AltitudeLayer.Building), Quaternion.identity, Lord.FlagTex, 0); } GenDraw.DrawLineBetween(a, flagLoc.ToVector3Shifted(), SimpleColor.Red); - foreach (Pawn current in this.ownedPawns) + List.Enumerator enumerator = this.ownedPawns.GetEnumerator(); + try + { + while (enumerator.MoveNext()) + { + Pawn current = enumerator.Current; + SimpleColor color = (SimpleColor)(current.InMentalState ? 5 : 0); + GenDraw.DrawLineBetween(a, current.DrawPos, color); + } + } + finally { - SimpleColor color = current.InMentalState ? SimpleColor.Yellow : SimpleColor.White; - GenDraw.DrawLineBetween(a, current.DrawPos, color); + ((IDisposable)(object)enumerator).Dispose(); } } @@ -524,23 +514,9 @@ public void DebugOnGUI() { Text.Anchor = TextAnchor.MiddleCenter; Text.Font = GameFont.Tiny; - string label; - if (this.CurLordToil != null) - { - label = string.Concat(new object[] - { - "toil ", - this.graph.lordToils.IndexOf(this.CurLordToil), - "\n", - this.CurLordToil.ToString() - }); - } - else - { - label = "toil=NULL"; - } + string label = (this.CurLordToil == null) ? "toil=NULL" : ("toil " + this.graph.lordToils.IndexOf(this.CurLordToil) + "\n" + this.CurLordToil.ToString()); Vector2 vector = this.DebugCenter().MapToUIPosition(); - Widgets.Label(new Rect(vector.x - 100f, vector.y - 100f, 200f, 200f), label); + Widgets.Label(new Rect((float)(vector.x - 100.0), (float)(vector.y - 100.0), 200f, 200f), label); Text.Anchor = TextAnchor.UpperLeft; } @@ -549,15 +525,18 @@ public string DebugString() StringBuilder stringBuilder = new StringBuilder(); stringBuilder.AppendLine("Start steal threshold: " + StealAIUtility.StartStealingMarketValueThreshold(this).ToString("F0")); stringBuilder.AppendLine("Duties:"); - foreach (Pawn current in this.ownedPawns) + List.Enumerator enumerator = this.ownedPawns.GetEnumerator(); + try { - stringBuilder.AppendLine(string.Concat(new object[] + while (enumerator.MoveNext()) { - " ", - current.LabelCap, - " - ", - current.mindState.duty - })); + Pawn current = enumerator.Current; + stringBuilder.AppendLine(" " + current.LabelCap + " - " + current.mindState.duty); + } + } + finally + { + ((IDisposable)(object)enumerator).Dispose(); } stringBuilder.AppendLine("Faction data:"); stringBuilder.AppendLine(this.faction.DebugString()); diff --git a/Assembly-CSharp/Verse.AI.Group/LordJob.cs b/Assembly-CSharp/Verse.AI.Group/LordJob.cs index c4584459e..7da5a037d 100644 --- a/Assembly-CSharp/Verse.AI.Group/LordJob.cs +++ b/Assembly-CSharp/Verse.AI.Group/LordJob.cs @@ -1,5 +1,3 @@ -using System; - namespace Verse.AI.Group { public abstract class LordJob : IExposable @@ -58,7 +56,7 @@ public virtual void Notify_PawnLost(Pawn p, PawnLostCondition condition) public virtual string GetReport() { - return null; + return (string)null; } public virtual bool CanOpenAnyDoor(Pawn p) diff --git a/Assembly-CSharp/Verse.AI.Group/LordJob_DefendPoint.cs b/Assembly-CSharp/Verse.AI.Group/LordJob_DefendPoint.cs index 776138cc2..2d49e062d 100644 --- a/Assembly-CSharp/Verse.AI.Group/LordJob_DefendPoint.cs +++ b/Assembly-CSharp/Verse.AI.Group/LordJob_DefendPoint.cs @@ -1,5 +1,3 @@ -using System; - namespace Verse.AI.Group { public class LordJob_DefendPoint : LordJob diff --git a/Assembly-CSharp/Verse.AI.Group/LordJob_ExitMapBest.cs b/Assembly-CSharp/Verse.AI.Group/LordJob_ExitMapBest.cs index cec0a1c52..a73a412d7 100644 --- a/Assembly-CSharp/Verse.AI.Group/LordJob_ExitMapBest.cs +++ b/Assembly-CSharp/Verse.AI.Group/LordJob_ExitMapBest.cs @@ -1,5 +1,3 @@ -using System; - namespace Verse.AI.Group { public class LordJob_ExitMapBest : LordJob @@ -21,10 +19,9 @@ public LordJob_ExitMapBest(LocomotionUrgency locomotion, bool canDig = false) public override StateGraph CreateGraph() { StateGraph stateGraph = new StateGraph(); - stateGraph.AddToil(new LordToil_ExitMap(this.locomotion, this.canDig) - { - avoidGridMode = AvoidGridMode.Smart - }); + LordToil_ExitMap lordToil_ExitMap = new LordToil_ExitMap(this.locomotion, this.canDig); + lordToil_ExitMap.avoidGridMode = AvoidGridMode.Smart; + stateGraph.AddToil(lordToil_ExitMap); return stateGraph; } diff --git a/Assembly-CSharp/Verse.AI.Group/LordJob_Travel.cs b/Assembly-CSharp/Verse.AI.Group/LordJob_Travel.cs index 9f9503784..1c7541748 100644 --- a/Assembly-CSharp/Verse.AI.Group/LordJob_Travel.cs +++ b/Assembly-CSharp/Verse.AI.Group/LordJob_Travel.cs @@ -1,5 +1,3 @@ -using System; - namespace Verse.AI.Group { public class LordJob_Travel : LordJob diff --git a/Assembly-CSharp/Verse.AI.Group/LordJob_TravelAndExit.cs b/Assembly-CSharp/Verse.AI.Group/LordJob_TravelAndExit.cs index 6dfc48f62..d148f0dfb 100644 --- a/Assembly-CSharp/Verse.AI.Group/LordJob_TravelAndExit.cs +++ b/Assembly-CSharp/Verse.AI.Group/LordJob_TravelAndExit.cs @@ -1,5 +1,3 @@ -using System; - namespace Verse.AI.Group { public class LordJob_TravelAndExit : LordJob @@ -22,13 +20,9 @@ public override StateGraph CreateGraph() stateGraph.StartingToil = startingToil; LordToil_ExitMap lordToil_ExitMap = new LordToil_ExitMap(LocomotionUrgency.None, false); stateGraph.AddToil(lordToil_ExitMap); - stateGraph.AddTransition(new Transition(startingToil, lordToil_ExitMap) - { - triggers = - { - new Trigger_Memo("TravelArrived") - } - }); + Transition transition = new Transition(startingToil, lordToil_ExitMap); + transition.triggers.Add(new Trigger_Memo("TravelArrived")); + stateGraph.AddTransition(transition); return stateGraph; } diff --git a/Assembly-CSharp/Verse.AI.Group/LordMaker.cs b/Assembly-CSharp/Verse.AI.Group/LordMaker.cs index 1066c1596..baf6191a1 100644 --- a/Assembly-CSharp/Verse.AI.Group/LordMaker.cs +++ b/Assembly-CSharp/Verse.AI.Group/LordMaker.cs @@ -1,5 +1,4 @@ using RimWorld; -using System; using System.Collections.Generic; namespace Verse.AI.Group @@ -26,9 +25,12 @@ public static Lord MakeNewLord(Faction faction, LordJob lordJob, Map map, IEnume lord.GotoToil(lord.Graph.StartingToil); if (startingPawns != null) { - foreach (Pawn current in startingPawns) { - lord.AddPawn(current); + foreach (Pawn item in startingPawns) + { + lord.AddPawn(item); + } + return lord; } } return lord; diff --git a/Assembly-CSharp/Verse.AI.Group/LordManager.cs b/Assembly-CSharp/Verse.AI.Group/LordManager.cs index f9eeea4d1..1ce076296 100644 --- a/Assembly-CSharp/Verse.AI.Group/LordManager.cs +++ b/Assembly-CSharp/Verse.AI.Group/LordManager.cs @@ -1,4 +1,3 @@ -using System; using System.Collections.Generic; using System.Text; using UnityEngine; @@ -34,12 +33,12 @@ public void LordManagerTick() { this.lords[i].LordTick(); } - for (int j = this.lords.Count - 1; j >= 0; j--) + for (int num = this.lords.Count - 1; num >= 0; num--) { - LordToil curLordToil = this.lords[j].CurLordToil; + LordToil curLordToil = this.lords[num].CurLordToil; if (curLordToil.ShouldFail) { - this.RemoveLord(this.lords[j]); + this.RemoveLord(this.lords[num]); } } } @@ -68,21 +67,21 @@ public void LordManagerOnGUI() { Text.Anchor = TextAnchor.MiddleCenter; Text.Font = GameFont.Tiny; - foreach (Pawn current in this.map.mapPawns.AllPawns) + foreach (Pawn allPawn in this.map.mapPawns.AllPawns) { - if (current.Spawned) + if (allPawn.Spawned) { string text = string.Empty; - if (!current.Dead && current.mindState.duty != null) + if (!allPawn.Dead && allPawn.mindState.duty != null) { - text = current.mindState.duty.ToString(); + text = allPawn.mindState.duty.ToString(); } - if (current.InMentalState) + if (allPawn.InMentalState) { - text = text + "\nMentalState=" + current.MentalState.ToString(); + text = text + "\nMentalState=" + allPawn.MentalState.ToString(); } - Vector2 vector = current.DrawPos.MapToUIPosition(); - Widgets.Label(new Rect(vector.x - 100f, vector.y - 100f, 200f, 200f), text); + Vector2 vector = allPawn.DrawPos.MapToUIPosition(); + Widgets.Label(new Rect((float)(vector.x - 100.0), (float)(vector.y - 100.0), 200f, 200f), text); } } Text.Anchor = TextAnchor.UpperLeft; @@ -147,14 +146,7 @@ public void LogLords() stringBuilder.AppendLine("Members (count: " + lord.ownedPawns.Count + "):"); for (int j = 0; j < lord.ownedPawns.Count; j++) { - stringBuilder.AppendLine(string.Concat(new object[] - { - " ", - lord.ownedPawns[j].LabelShort, - " (", - lord.ownedPawns[j].Faction, - ")" - })); + stringBuilder.AppendLine(" " + lord.ownedPawns[j].LabelShort + " (" + lord.ownedPawns[j].Faction + ")"); } } Log.Message(stringBuilder.ToString()); diff --git a/Assembly-CSharp/Verse.AI.Group/LordToil.cs b/Assembly-CSharp/Verse.AI.Group/LordToil.cs index 0f93f31b5..424f5faea 100644 --- a/Assembly-CSharp/Verse.AI.Group/LordToil.cs +++ b/Assembly-CSharp/Verse.AI.Group/LordToil.cs @@ -43,7 +43,7 @@ public virtual float? CustomWakeThreshold { get { - return null; + return default(float?); } } diff --git a/Assembly-CSharp/Verse.AI.Group/LordToilData.cs b/Assembly-CSharp/Verse.AI.Group/LordToilData.cs index 10a687523..d9c0bb08a 100644 --- a/Assembly-CSharp/Verse.AI.Group/LordToilData.cs +++ b/Assembly-CSharp/Verse.AI.Group/LordToilData.cs @@ -1,5 +1,3 @@ -using System; - namespace Verse.AI.Group { public abstract class LordToilData : IExposable diff --git a/Assembly-CSharp/Verse.AI.Group/LordToilData_DefendPoint.cs b/Assembly-CSharp/Verse.AI.Group/LordToilData_DefendPoint.cs index e933462a8..8d9e794e3 100644 --- a/Assembly-CSharp/Verse.AI.Group/LordToilData_DefendPoint.cs +++ b/Assembly-CSharp/Verse.AI.Group/LordToilData_DefendPoint.cs @@ -1,5 +1,3 @@ -using System; - namespace Verse.AI.Group { public class LordToilData_DefendPoint : LordToilData diff --git a/Assembly-CSharp/Verse.AI.Group/LordToilData_ExitMap.cs b/Assembly-CSharp/Verse.AI.Group/LordToilData_ExitMap.cs index c888d9113..b6248b2db 100644 --- a/Assembly-CSharp/Verse.AI.Group/LordToilData_ExitMap.cs +++ b/Assembly-CSharp/Verse.AI.Group/LordToilData_ExitMap.cs @@ -1,5 +1,3 @@ -using System; - namespace Verse.AI.Group { public class LordToilData_ExitMap : LordToilData diff --git a/Assembly-CSharp/Verse.AI.Group/LordToilData_Travel.cs b/Assembly-CSharp/Verse.AI.Group/LordToilData_Travel.cs index 80132ca3b..b401e2504 100644 --- a/Assembly-CSharp/Verse.AI.Group/LordToilData_Travel.cs +++ b/Assembly-CSharp/Verse.AI.Group/LordToilData_Travel.cs @@ -1,5 +1,3 @@ -using System; - namespace Verse.AI.Group { public class LordToilData_Travel : LordToilData diff --git a/Assembly-CSharp/Verse.AI.Group/LordToil_DefendPoint.cs b/Assembly-CSharp/Verse.AI.Group/LordToil_DefendPoint.cs index 5c0cf2b3c..29b49b18f 100644 --- a/Assembly-CSharp/Verse.AI.Group/LordToil_DefendPoint.cs +++ b/Assembly-CSharp/Verse.AI.Group/LordToil_DefendPoint.cs @@ -1,5 +1,4 @@ using RimWorld; -using System; namespace Verse.AI.Group { @@ -11,7 +10,7 @@ protected LordToilData_DefendPoint Data { get { - return (LordToilData_DefendPoint)this.data; + return (LordToilData_DefendPoint)base.data; } } @@ -34,7 +33,7 @@ public override bool AllowSatisfyLongNeeds public LordToil_DefendPoint(bool canSatisfyLongNeeds = true) { this.allowSatisfyLongNeeds = canSatisfyLongNeeds; - this.data = new LordToilData_DefendPoint(); + base.data = new LordToilData_DefendPoint(); } public LordToil_DefendPoint(IntVec3 defendPoint, float defendRadius = 28f) : this(true) @@ -46,11 +45,11 @@ public LordToil_DefendPoint(IntVec3 defendPoint, float defendRadius = 28f) : thi public override void UpdateAllDuties() { LordToilData_DefendPoint data = this.Data; - for (int i = 0; i < this.lord.ownedPawns.Count; i++) + for (int i = 0; i < base.lord.ownedPawns.Count; i++) { - this.lord.ownedPawns[i].mindState.duty = new PawnDuty(DutyDefOf.Defend, data.defendPoint, -1f); - this.lord.ownedPawns[i].mindState.duty.focusSecond = data.defendPoint; - this.lord.ownedPawns[i].mindState.duty.radius = data.defendRadius; + base.lord.ownedPawns[i].mindState.duty = new PawnDuty(DutyDefOf.Defend, data.defendPoint, -1f); + base.lord.ownedPawns[i].mindState.duty.focusSecond = data.defendPoint; + base.lord.ownedPawns[i].mindState.duty.radius = data.defendRadius; } } diff --git a/Assembly-CSharp/Verse.AI.Group/LordToil_DefendSelf.cs b/Assembly-CSharp/Verse.AI.Group/LordToil_DefendSelf.cs index 63e99b2aa..e2ec0d9c8 100644 --- a/Assembly-CSharp/Verse.AI.Group/LordToil_DefendSelf.cs +++ b/Assembly-CSharp/Verse.AI.Group/LordToil_DefendSelf.cs @@ -1,5 +1,4 @@ using RimWorld; -using System; namespace Verse.AI.Group { @@ -7,10 +6,10 @@ public class LordToil_DefendSelf : LordToil { public override void UpdateAllDuties() { - for (int i = 0; i < this.lord.ownedPawns.Count; i++) + for (int i = 0; i < base.lord.ownedPawns.Count; i++) { - this.lord.ownedPawns[i].mindState.duty = new PawnDuty(DutyDefOf.Defend, this.lord.ownedPawns[i].Position, -1f); - this.lord.ownedPawns[i].mindState.duty.radius = 28f; + base.lord.ownedPawns[i].mindState.duty = new PawnDuty(DutyDefOf.Defend, base.lord.ownedPawns[i].Position, -1f); + base.lord.ownedPawns[i].mindState.duty.radius = 28f; } } } diff --git a/Assembly-CSharp/Verse.AI.Group/LordToil_End.cs b/Assembly-CSharp/Verse.AI.Group/LordToil_End.cs index 7f3831cb0..2aa493e22 100644 --- a/Assembly-CSharp/Verse.AI.Group/LordToil_End.cs +++ b/Assembly-CSharp/Verse.AI.Group/LordToil_End.cs @@ -1,5 +1,3 @@ -using System; - namespace Verse.AI.Group { public class LordToil_End : LordToil diff --git a/Assembly-CSharp/Verse.AI.Group/LordToil_ExitMap.cs b/Assembly-CSharp/Verse.AI.Group/LordToil_ExitMap.cs index 9579bab80..0320695d1 100644 --- a/Assembly-CSharp/Verse.AI.Group/LordToil_ExitMap.cs +++ b/Assembly-CSharp/Verse.AI.Group/LordToil_ExitMap.cs @@ -1,5 +1,4 @@ using RimWorld; -using System; namespace Verse.AI.Group { @@ -17,13 +16,13 @@ protected LordToilData_ExitMap Data { get { - return (LordToilData_ExitMap)this.data; + return (LordToilData_ExitMap)base.data; } } public LordToil_ExitMap(LocomotionUrgency locomotion = LocomotionUrgency.None, bool canDig = false) { - this.data = new LordToilData_ExitMap(); + base.data = new LordToilData_ExitMap(); this.Data.locomotion = locomotion; this.Data.canDig = canDig; } @@ -31,12 +30,12 @@ public LordToil_ExitMap(LocomotionUrgency locomotion = LocomotionUrgency.None, b public override void UpdateAllDuties() { LordToilData_ExitMap data = this.Data; - for (int i = 0; i < this.lord.ownedPawns.Count; i++) + for (int i = 0; i < base.lord.ownedPawns.Count; i++) { PawnDuty pawnDuty = new PawnDuty(DutyDefOf.ExitMapBest); pawnDuty.locomotion = data.locomotion; pawnDuty.canDig = data.canDig; - this.lord.ownedPawns[i].mindState.duty = pawnDuty; + base.lord.ownedPawns[i].mindState.duty = pawnDuty; } } } diff --git a/Assembly-CSharp/Verse.AI.Group/LordToil_ExitMapTraderFighting.cs b/Assembly-CSharp/Verse.AI.Group/LordToil_ExitMapTraderFighting.cs index ab854c7f0..7813e7a2b 100644 --- a/Assembly-CSharp/Verse.AI.Group/LordToil_ExitMapTraderFighting.cs +++ b/Assembly-CSharp/Verse.AI.Group/LordToil_ExitMapTraderFighting.cs @@ -1,5 +1,4 @@ using RimWorld; -using System; namespace Verse.AI.Group { @@ -15,9 +14,9 @@ public override bool AllowSatisfyLongNeeds public override void UpdateAllDuties() { - for (int i = 0; i < this.lord.ownedPawns.Count; i++) + for (int i = 0; i < base.lord.ownedPawns.Count; i++) { - Pawn pawn = this.lord.ownedPawns[i]; + Pawn pawn = base.lord.ownedPawns[i]; TraderCaravanRole traderCaravanRole = pawn.GetTraderCaravanRole(); if (traderCaravanRole == TraderCaravanRole.Carrier || traderCaravanRole == TraderCaravanRole.Chattel) { diff --git a/Assembly-CSharp/Verse.AI.Group/LordToil_Travel.cs b/Assembly-CSharp/Verse.AI.Group/LordToil_Travel.cs index 03da0d53d..5dabbb6fe 100644 --- a/Assembly-CSharp/Verse.AI.Group/LordToil_Travel.cs +++ b/Assembly-CSharp/Verse.AI.Group/LordToil_Travel.cs @@ -1,5 +1,4 @@ using RimWorld; -using System; namespace Verse.AI.Group { @@ -19,7 +18,7 @@ private LordToilData_Travel Data { get { - return (LordToilData_Travel)this.data; + return (LordToilData_Travel)base.data; } } @@ -41,18 +40,18 @@ protected virtual float AllArrivedCheckRadius public LordToil_Travel(IntVec3 dest) { - this.data = new LordToilData_Travel(); + base.data = new LordToilData_Travel(); this.Data.dest = dest; } public override void UpdateAllDuties() { LordToilData_Travel data = this.Data; - for (int i = 0; i < this.lord.ownedPawns.Count; i++) + for (int i = 0; i < base.lord.ownedPawns.Count; i++) { PawnDuty pawnDuty = new PawnDuty(DutyDefOf.Travel, data.dest, -1f); pawnDuty.maxDanger = this.maxDanger; - this.lord.ownedPawns[i].mindState.duty = pawnDuty; + base.lord.ownedPawns[i].mindState.duty = pawnDuty; } } @@ -62,18 +61,21 @@ public override void LordToilTick() { LordToilData_Travel data = this.Data; bool flag = true; - for (int i = 0; i < this.lord.ownedPawns.Count; i++) + int num = 0; + while (num < base.lord.ownedPawns.Count) { - Pawn pawn = this.lord.ownedPawns[i]; - if (!pawn.Position.InHorDistOf(data.dest, this.AllArrivedCheckRadius) || !pawn.CanReach(data.dest, PathEndMode.ClosestTouch, Danger.Deadly, false, TraverseMode.ByPawn)) + Pawn pawn = base.lord.ownedPawns[num]; + if (pawn.Position.InHorDistOf(data.dest, this.AllArrivedCheckRadius) && pawn.CanReach(data.dest, PathEndMode.ClosestTouch, Danger.Deadly, false, TraverseMode.ByPawn)) { - flag = false; - break; + num++; + continue; } + flag = false; + break; } if (flag) { - this.lord.ReceiveMemo("TravelArrived"); + base.lord.ReceiveMemo("TravelArrived"); } } } diff --git a/Assembly-CSharp/Verse.AI.Group/LordUtility.cs b/Assembly-CSharp/Verse.AI.Group/LordUtility.cs index a0cf805c4..8cb9ab71a 100644 --- a/Assembly-CSharp/Verse.AI.Group/LordUtility.cs +++ b/Assembly-CSharp/Verse.AI.Group/LordUtility.cs @@ -1,4 +1,3 @@ -using System; using System.Collections.Generic; namespace Verse.AI.Group diff --git a/Assembly-CSharp/Verse.AI.Group/PawnLostCondition.cs b/Assembly-CSharp/Verse.AI.Group/PawnLostCondition.cs index 551389b0c..22c9b5fe1 100644 --- a/Assembly-CSharp/Verse.AI.Group/PawnLostCondition.cs +++ b/Assembly-CSharp/Verse.AI.Group/PawnLostCondition.cs @@ -1,17 +1,15 @@ -using System; - namespace Verse.AI.Group { public enum PawnLostCondition : byte { - Undefined, - Vanished, - IncappedOrKilled, - MadePrisoner, - ChangedFaction, - ExitedMap, - LeftVoluntarily, - Drafted, - ForcedToJoinOtherLord + Undefined = 0, + Vanished = 1, + IncappedOrKilled = 2, + MadePrisoner = 3, + ChangedFaction = 4, + ExitedMap = 5, + LeftVoluntarily = 6, + Drafted = 7, + ForcedToJoinOtherLord = 8 } } diff --git a/Assembly-CSharp/Verse.AI.Group/StateGraph.cs b/Assembly-CSharp/Verse.AI.Group/StateGraph.cs index 181cb1304..8f1c4d9f4 100644 --- a/Assembly-CSharp/Verse.AI.Group/StateGraph.cs +++ b/Assembly-CSharp/Verse.AI.Group/StateGraph.cs @@ -57,40 +57,41 @@ public void ErrorCheck() { Log.Error("Graph has 0 lord toils."); } - foreach (LordToil toil in this.lordToils.Distinct()) + using (IEnumerator enumerator = this.lordToils.Distinct().GetEnumerator()) { - int num = (from s in this.lordToils - where s == toil - select s).Count(); - if (num != 1) + LordToil toil; + while (enumerator.MoveNext()) { - Log.Error(string.Concat(new object[] + toil = enumerator.Current; + int num = (from s in this.lordToils + where s == toil + select s).Count(); + if (num != 1) { - "Graph has lord toil ", - toil, - " registered ", - num, - " times." - })); + Log.Error("Graph has lord toil " + toil + " registered " + num + " times."); + } } } - foreach (Transition trans in this.transitions) + List.Enumerator enumerator2 = this.transitions.GetEnumerator(); + try { - int num2 = (from t in this.transitions - where t == trans - select t).Count(); - if (num2 != 1) + Transition trans; + while (enumerator2.MoveNext()) { - Log.Error(string.Concat(new object[] + trans = enumerator2.Current; + int num2 = (from t in this.transitions + where t == trans + select t).Count(); + if (num2 != 1) { - "Graph has transition ", - trans, - " registered ", - num2, - " times." - })); + Log.Error("Graph has transition " + trans + " registered " + num2 + " times."); + } } } + finally + { + ((IDisposable)(object)enumerator2).Dispose(); + } StateGraph.checkedToils = new HashSet(); this.CheckForUnregisteredLinkedToilsRecursive(this.StartingToil); StateGraph.checkedToils = null; diff --git a/Assembly-CSharp/Verse.AI.Group/Transition.cs b/Assembly-CSharp/Verse.AI.Group/Transition.cs index 0137881e6..286cf1921 100644 --- a/Assembly-CSharp/Verse.AI.Group/Transition.cs +++ b/Assembly-CSharp/Verse.AI.Group/Transition.cs @@ -1,4 +1,3 @@ -using System; using System.Collections.Generic; namespace Verse.AI.Group @@ -37,20 +36,22 @@ public void AddSource(LordToil source) if (this.sources.Contains(source)) { Log.Error("Double-added source to Transition: " + source); - return; } - if (!this.canMoveToSameState && this.target == source) + else { - Log.Error("Transition canMoveToSameState and target is source: " + source); + if (!this.canMoveToSameState && this.target == source) + { + Log.Error("Transition canMoveToSameState and target is source: " + source); + } + this.sources.Add(source); } - this.sources.Add(source); } public void AddSources(IEnumerable sources) { - foreach (LordToil current in sources) + foreach (LordToil item in sources) { - this.AddSource(current); + this.AddSource(item); } } @@ -91,40 +92,33 @@ public bool CheckSignal(Lord lord, TriggerSignal signal) { if (this.triggers[i].ActivateOn(lord, signal)) { - if (this.triggers[i].filters != null) + if (this.triggers[i].filters == null) { - bool flag = true; - for (int j = 0; j < this.triggers[i].filters.Count; j++) - { - if (!this.triggers[i].filters[j].AllowActivation(lord, signal)) - { - flag = false; - break; - } - } - if (!flag) - { - goto IL_100; - } + goto IL_0093; } - if (DebugViewSettings.logLordToilTransitions) + bool flag = true; + int num = 0; + while (num < this.triggers[i].filters.Count) { - Log.Message(string.Concat(new object[] + if (this.triggers[i].filters[num].AllowActivation(lord, signal)) { - "Transitioning ", - this.sources, - " to ", - this.target, - " by trigger ", - this.triggers[i], - " on signal ", - signal - })); + num++; + continue; + } + flag = false; + break; } - this.Execute(lord); - return true; + if (flag) + goto IL_0093; + } + continue; + IL_0093: + if (DebugViewSettings.logLordToilTransitions) + { + Log.Message("Transitioning " + this.sources + " to " + this.target + " by trigger " + this.triggers[i] + " on signal " + signal); } - IL_100:; + this.Execute(lord); + return true; } return false; } @@ -132,9 +126,7 @@ public bool CheckSignal(Lord lord, TriggerSignal signal) public void Execute(Lord lord) { if (!this.canMoveToSameState && this.target == lord.CurLordToil) - { return; - } for (int i = 0; i < this.preActions.Count; i++) { this.preActions[i].DoAction(this); @@ -148,17 +140,10 @@ public void Execute(Lord lord) public override string ToString() { - string text = (!this.sources.NullOrEmpty()) ? this.sources[0].ToString() : "null"; + string text = (!this.sources.NullOrEmpty()) ? this.sources[0].ToString() : "null"; int num = (this.sources != null) ? this.sources.Count : 0; string text2 = (this.target != null) ? this.target.ToString() : "null"; - return string.Concat(new object[] - { - text, - "(", - num, - ")->", - text2 - }); + return text + "(" + num + ")->" + text2; } } } diff --git a/Assembly-CSharp/Verse.AI.Group/TransitionAction.cs b/Assembly-CSharp/Verse.AI.Group/TransitionAction.cs index 32bc18893..0903a53dc 100644 --- a/Assembly-CSharp/Verse.AI.Group/TransitionAction.cs +++ b/Assembly-CSharp/Verse.AI.Group/TransitionAction.cs @@ -1,5 +1,3 @@ -using System; - namespace Verse.AI.Group { public abstract class TransitionAction diff --git a/Assembly-CSharp/Verse.AI.Group/TransitionAction_Custom.cs b/Assembly-CSharp/Verse.AI.Group/TransitionAction_Custom.cs index ee0067fd1..2c8119630 100644 --- a/Assembly-CSharp/Verse.AI.Group/TransitionAction_Custom.cs +++ b/Assembly-CSharp/Verse.AI.Group/TransitionAction_Custom.cs @@ -20,11 +20,11 @@ public TransitionAction_Custom(Action actionWithArg) public override void DoAction(Transition trans) { - if (this.actionWithArg != null) + if ((object)this.actionWithArg != null) { this.actionWithArg(trans); } - if (this.action != null) + if ((object)this.action != null) { this.action(); } diff --git a/Assembly-CSharp/Verse.AI.Group/TransitionAction_EndAllJobs.cs b/Assembly-CSharp/Verse.AI.Group/TransitionAction_EndAllJobs.cs index a9f422671..ecf751502 100644 --- a/Assembly-CSharp/Verse.AI.Group/TransitionAction_EndAllJobs.cs +++ b/Assembly-CSharp/Verse.AI.Group/TransitionAction_EndAllJobs.cs @@ -1,4 +1,3 @@ -using System; using System.Collections.Generic; namespace Verse.AI.Group diff --git a/Assembly-CSharp/Verse.AI.Group/TransitionAction_EndAttackBuildingJobs.cs b/Assembly-CSharp/Verse.AI.Group/TransitionAction_EndAttackBuildingJobs.cs index dd4b9cf82..6fa9b5d68 100644 --- a/Assembly-CSharp/Verse.AI.Group/TransitionAction_EndAttackBuildingJobs.cs +++ b/Assembly-CSharp/Verse.AI.Group/TransitionAction_EndAttackBuildingJobs.cs @@ -1,5 +1,4 @@ using RimWorld; -using System; using System.Collections.Generic; namespace Verse.AI.Group diff --git a/Assembly-CSharp/Verse.AI.Group/TransitionAction_EnsureHaveExitDestination.cs b/Assembly-CSharp/Verse.AI.Group/TransitionAction_EnsureHaveExitDestination.cs index 366861c1c..5147d88d9 100644 --- a/Assembly-CSharp/Verse.AI.Group/TransitionAction_EnsureHaveExitDestination.cs +++ b/Assembly-CSharp/Verse.AI.Group/TransitionAction_EnsureHaveExitDestination.cs @@ -8,17 +8,16 @@ public class TransitionAction_EnsureHaveExitDestination : TransitionAction public override void DoAction(Transition trans) { LordToil_Travel lordToil_Travel = (LordToil_Travel)trans.target; - if (lordToil_Travel.HasDestination()) + if (!lordToil_Travel.HasDestination()) { - return; + Pawn pawn = lordToil_Travel.lord.ownedPawns.RandomElement(); + IntVec3 destination = default(IntVec3); + if (!CellFinder.TryFindRandomPawnExitCell(pawn, out destination)) + { + RCellFinder.TryFindRandomPawnEntryCell(out destination, pawn.Map, 0f, (Predicate)null); + } + lordToil_Travel.SetDestination(destination); } - Pawn pawn = lordToil_Travel.lord.ownedPawns.RandomElement(); - IntVec3 destination; - if (!CellFinder.TryFindRandomPawnExitCell(pawn, out destination)) - { - RCellFinder.TryFindRandomPawnEntryCell(out destination, pawn.Map, 0f, null); - } - lordToil_Travel.SetDestination(destination); } } } diff --git a/Assembly-CSharp/Verse.AI.Group/TransitionAction_Message.cs b/Assembly-CSharp/Verse.AI.Group/TransitionAction_Message.cs index ae6cc4bc7..88b300a05 100644 --- a/Assembly-CSharp/Verse.AI.Group/TransitionAction_Message.cs +++ b/Assembly-CSharp/Verse.AI.Group/TransitionAction_Message.cs @@ -1,4 +1,3 @@ -using System; using System.Linq; namespace Verse.AI.Group @@ -9,7 +8,7 @@ public class TransitionAction_Message : TransitionAction public MessageSound sound; - public TargetInfo lookTarget; + public TargetInfo lookTarget = TargetInfo.Invalid; public TransitionAction_Message(string message) : this(message, MessageSound.Standard) { @@ -18,16 +17,12 @@ public TransitionAction_Message(string message) : this(message, MessageSound.Sta public TransitionAction_Message(string message, MessageSound messageSound) { - this.lookTarget = TargetInfo.Invalid; - base..ctor(); this.message = message; this.sound = messageSound; } public TransitionAction_Message(string message, MessageSound messageSound, TargetInfo lookTarget) { - this.lookTarget = TargetInfo.Invalid; - base..ctor(); this.message = message; this.sound = messageSound; this.lookTarget = lookTarget; @@ -35,15 +30,7 @@ public TransitionAction_Message(string message, MessageSound messageSound, Targe public override void DoAction(Transition trans) { - TargetInfo target; - if (this.lookTarget.IsValid) - { - target = this.lookTarget; - } - else - { - target = trans.target.lord.ownedPawns.FirstOrDefault(); - } + TargetInfo target = (!this.lookTarget.IsValid) ? ((Thing)trans.target.lord.ownedPawns.FirstOrDefault()) : this.lookTarget; Messages.Message(this.message, target, this.sound); } } diff --git a/Assembly-CSharp/Verse.AI.Group/TransitionAction_SetDefendLocalGroup.cs b/Assembly-CSharp/Verse.AI.Group/TransitionAction_SetDefendLocalGroup.cs index 713a8ee99..7220f0881 100644 --- a/Assembly-CSharp/Verse.AI.Group/TransitionAction_SetDefendLocalGroup.cs +++ b/Assembly-CSharp/Verse.AI.Group/TransitionAction_SetDefendLocalGroup.cs @@ -1,5 +1,3 @@ -using System; - namespace Verse.AI.Group { public class TransitionAction_SetDefendLocalGroup : TransitionAction @@ -7,7 +5,7 @@ public class TransitionAction_SetDefendLocalGroup : TransitionAction public override void DoAction(Transition trans) { LordToil_DefendPoint lordToil_DefendPoint = (LordToil_DefendPoint)trans.target; - lordToil_DefendPoint.SetDefendPoint(lordToil_DefendPoint.lord.ownedPawns.RandomElement().Position); + lordToil_DefendPoint.SetDefendPoint(lordToil_DefendPoint.lord.ownedPawns.RandomElement().Position); } } } diff --git a/Assembly-CSharp/Verse.AI.Group/TransitionAction_SetDefendTrader.cs b/Assembly-CSharp/Verse.AI.Group/TransitionAction_SetDefendTrader.cs index 0c7e25d7a..ecb79b8f8 100644 --- a/Assembly-CSharp/Verse.AI.Group/TransitionAction_SetDefendTrader.cs +++ b/Assembly-CSharp/Verse.AI.Group/TransitionAction_SetDefendTrader.cs @@ -20,13 +20,13 @@ public override void DoAction(Transition trans) IEnumerable source = from x in lordToil_DefendPoint.lord.ownedPawns where x.GetTraderCaravanRole() == TraderCaravanRole.Carrier select x; - if (source.Any()) + if (source.Any()) { - lordToil_DefendPoint.SetDefendPoint(source.RandomElement().Position); + lordToil_DefendPoint.SetDefendPoint(source.RandomElement().Position); } else { - lordToil_DefendPoint.SetDefendPoint(lordToil_DefendPoint.lord.ownedPawns.RandomElement().Position); + lordToil_DefendPoint.SetDefendPoint(lordToil_DefendPoint.lord.ownedPawns.RandomElement().Position); } } } diff --git a/Assembly-CSharp/Verse.AI.Group/TransitionAction_WakeAll.cs b/Assembly-CSharp/Verse.AI.Group/TransitionAction_WakeAll.cs index 044119d6d..20c29a9d0 100644 --- a/Assembly-CSharp/Verse.AI.Group/TransitionAction_WakeAll.cs +++ b/Assembly-CSharp/Verse.AI.Group/TransitionAction_WakeAll.cs @@ -1,5 +1,4 @@ using RimWorld; -using System; using System.Collections.Generic; namespace Verse.AI.Group diff --git a/Assembly-CSharp/Verse.AI.Group/Trigger.cs b/Assembly-CSharp/Verse.AI.Group/Trigger.cs index 69a76c4f8..d8e7c2cf5 100644 --- a/Assembly-CSharp/Verse.AI.Group/Trigger.cs +++ b/Assembly-CSharp/Verse.AI.Group/Trigger.cs @@ -1,4 +1,3 @@ -using System; using System.Collections.Generic; namespace Verse.AI.Group diff --git a/Assembly-CSharp/Verse.AI.Group/TriggerData.cs b/Assembly-CSharp/Verse.AI.Group/TriggerData.cs index 2444765ac..2b7760b0f 100644 --- a/Assembly-CSharp/Verse.AI.Group/TriggerData.cs +++ b/Assembly-CSharp/Verse.AI.Group/TriggerData.cs @@ -1,5 +1,3 @@ -using System; - namespace Verse.AI.Group { public abstract class TriggerData : IExposable diff --git a/Assembly-CSharp/Verse.AI.Group/TriggerData_TicksPassed.cs b/Assembly-CSharp/Verse.AI.Group/TriggerData_TicksPassed.cs index f7e6f163f..a18361f1a 100644 --- a/Assembly-CSharp/Verse.AI.Group/TriggerData_TicksPassed.cs +++ b/Assembly-CSharp/Verse.AI.Group/TriggerData_TicksPassed.cs @@ -1,5 +1,3 @@ -using System; - namespace Verse.AI.Group { public class TriggerData_TicksPassed : TriggerData diff --git a/Assembly-CSharp/Verse.AI.Group/TriggerFilter.cs b/Assembly-CSharp/Verse.AI.Group/TriggerFilter.cs index 752084211..d48c6df49 100644 --- a/Assembly-CSharp/Verse.AI.Group/TriggerFilter.cs +++ b/Assembly-CSharp/Verse.AI.Group/TriggerFilter.cs @@ -1,5 +1,3 @@ -using System; - namespace Verse.AI.Group { public abstract class TriggerFilter diff --git a/Assembly-CSharp/Verse.AI.Group/TriggerFilterExtension.cs b/Assembly-CSharp/Verse.AI.Group/TriggerFilterExtension.cs index 0dad3a213..656e1bd26 100644 --- a/Assembly-CSharp/Verse.AI.Group/TriggerFilterExtension.cs +++ b/Assembly-CSharp/Verse.AI.Group/TriggerFilterExtension.cs @@ -1,4 +1,3 @@ -using System; using System.Collections.Generic; namespace Verse.AI.Group diff --git a/Assembly-CSharp/Verse.AI.Group/TriggerFilter_NoSapperSapping.cs b/Assembly-CSharp/Verse.AI.Group/TriggerFilter_NoSapperSapping.cs index 44ac91748..2a3363222 100644 --- a/Assembly-CSharp/Verse.AI.Group/TriggerFilter_NoSapperSapping.cs +++ b/Assembly-CSharp/Verse.AI.Group/TriggerFilter_NoSapperSapping.cs @@ -1,5 +1,4 @@ using RimWorld; -using System; namespace Verse.AI.Group { @@ -10,10 +9,15 @@ public override bool AllowActivation(Lord lord, TriggerSignal signal) for (int i = 0; i < lord.ownedPawns.Count; i++) { Pawn pawn = lord.ownedPawns[i]; - if ((pawn.mindState.duty != null && pawn.mindState.duty.def == DutyDefOf.Sapper && pawn.CurJob != null && pawn.CurJob.def == JobDefOf.Mine && pawn.CurJob.targetA.Cell.InHorDistOf(pawn.Position, 5f)) || (pawn.CurJob.def == JobDefOf.UseVerbOnThing && pawn.CurJob.targetA.Cell.InHorDistOf(pawn.Position, 20f))) + if (pawn.mindState.duty != null && pawn.mindState.duty.def == DutyDefOf.Sapper && pawn.CurJob != null && pawn.CurJob.def == JobDefOf.Mine && pawn.CurJob.targetA.Cell.InHorDistOf(pawn.Position, 5f)) { - return false; + goto IL_00c3; } + if (pawn.CurJob.def == JobDefOf.UseVerbOnThing && pawn.CurJob.targetA.Cell.InHorDistOf(pawn.Position, 20f)) + goto IL_00c3; + continue; + IL_00c3: + return false; } return true; } diff --git a/Assembly-CSharp/Verse.AI.Group/TriggerSignal.cs b/Assembly-CSharp/Verse.AI.Group/TriggerSignal.cs index 7259f80b7..e8da5942d 100644 --- a/Assembly-CSharp/Verse.AI.Group/TriggerSignal.cs +++ b/Assembly-CSharp/Verse.AI.Group/TriggerSignal.cs @@ -37,7 +37,7 @@ public static TriggerSignal ForTick public TriggerSignal(TriggerSignalType type) { this.type = type; - this.memo = null; + this.memo = (string)null; this.thing = null; this.dinfo = default(DamageInfo); this.condition = PawnLostCondition.Undefined; @@ -56,7 +56,7 @@ public override string ToString() { StringBuilder stringBuilder = new StringBuilder(); stringBuilder.Append("("); - stringBuilder.Append(this.type.ToString()); + stringBuilder.Append(((Enum)(object)this.type).ToString()); if (this.memo != null) { stringBuilder.Append(", memo=" + this.memo); @@ -69,7 +69,7 @@ public override string ToString() { stringBuilder.Append(", dinfo=" + this.dinfo); } - if (this.condition != PawnLostCondition.Undefined) + if (this.condition != 0) { stringBuilder.Append(", condition=" + this.condition); } diff --git a/Assembly-CSharp/Verse.AI.Group/TriggerSignalType.cs b/Assembly-CSharp/Verse.AI.Group/TriggerSignalType.cs index bfb1cbede..c440b0f30 100644 --- a/Assembly-CSharp/Verse.AI.Group/TriggerSignalType.cs +++ b/Assembly-CSharp/Verse.AI.Group/TriggerSignalType.cs @@ -1,16 +1,14 @@ -using System; - namespace Verse.AI.Group { public enum TriggerSignalType : byte { - Undefined, - Tick, - Memo, - PawnDamaged, - PawnArrestAttempted, - PawnLost, - BuildingDamaged, - FactionRelationsChanged + Undefined = 0, + Tick = 1, + Memo = 2, + PawnDamaged = 3, + PawnArrestAttempted = 4, + PawnLost = 5, + BuildingDamaged = 6, + FactionRelationsChanged = 7 } } diff --git a/Assembly-CSharp/Verse.AI.Group/Trigger_BecameColonyAlly.cs b/Assembly-CSharp/Verse.AI.Group/Trigger_BecameColonyAlly.cs index f8addf088..1902531f8 100644 --- a/Assembly-CSharp/Verse.AI.Group/Trigger_BecameColonyAlly.cs +++ b/Assembly-CSharp/Verse.AI.Group/Trigger_BecameColonyAlly.cs @@ -1,5 +1,4 @@ using RimWorld; -using System; namespace Verse.AI.Group { @@ -7,7 +6,11 @@ public class Trigger_BecameColonyAlly : Trigger { public override bool ActivateOn(Lord lord, TriggerSignal signal) { - return signal.type == TriggerSignalType.FactionRelationsChanged && !lord.faction.HostileTo(Faction.OfPlayer); + if (signal.type == TriggerSignalType.FactionRelationsChanged) + { + return !lord.faction.HostileTo(Faction.OfPlayer); + } + return false; } } } diff --git a/Assembly-CSharp/Verse.AI.Group/Trigger_BecameColonyEnemy.cs b/Assembly-CSharp/Verse.AI.Group/Trigger_BecameColonyEnemy.cs index 093357641..a9e4fb956 100644 --- a/Assembly-CSharp/Verse.AI.Group/Trigger_BecameColonyEnemy.cs +++ b/Assembly-CSharp/Verse.AI.Group/Trigger_BecameColonyEnemy.cs @@ -1,5 +1,4 @@ using RimWorld; -using System; namespace Verse.AI.Group { @@ -7,7 +6,11 @@ public class Trigger_BecameColonyEnemy : Trigger { public override bool ActivateOn(Lord lord, TriggerSignal signal) { - return signal.type == TriggerSignalType.FactionRelationsChanged && lord.faction.HostileTo(Faction.OfPlayer); + if (signal.type == TriggerSignalType.FactionRelationsChanged) + { + return lord.faction.HostileTo(Faction.OfPlayer); + } + return false; } } } diff --git a/Assembly-CSharp/Verse.AI.Group/Trigger_ChanceOnPlayerHarmNPCBuilding.cs b/Assembly-CSharp/Verse.AI.Group/Trigger_ChanceOnPlayerHarmNPCBuilding.cs index 089330aa3..b05bdddec 100644 --- a/Assembly-CSharp/Verse.AI.Group/Trigger_ChanceOnPlayerHarmNPCBuilding.cs +++ b/Assembly-CSharp/Verse.AI.Group/Trigger_ChanceOnPlayerHarmNPCBuilding.cs @@ -1,5 +1,4 @@ using RimWorld; -using System; namespace Verse.AI.Group { @@ -14,7 +13,11 @@ public Trigger_ChanceOnPlayerHarmNPCBuilding(float chance) public override bool ActivateOn(Lord lord, TriggerSignal signal) { - return signal.type == TriggerSignalType.BuildingDamaged && signal.dinfo.Def.externalViolence && signal.thing.def.category == ThingCategory.Building && signal.dinfo.Instigator != null && signal.dinfo.Instigator.Faction == Faction.OfPlayer && signal.thing.Faction != Faction.OfPlayer && Rand.Value < this.chance; + if (signal.type == TriggerSignalType.BuildingDamaged && signal.dinfo.Def.externalViolence && signal.thing.def.category == ThingCategory.Building && signal.dinfo.Instigator != null && signal.dinfo.Instigator.Faction == Faction.OfPlayer && signal.thing.Faction != Faction.OfPlayer && Rand.Value < this.chance) + { + return true; + } + return false; } } } diff --git a/Assembly-CSharp/Verse.AI.Group/Trigger_ChanceOnSignal.cs b/Assembly-CSharp/Verse.AI.Group/Trigger_ChanceOnSignal.cs index 06def1572..210fe12d0 100644 --- a/Assembly-CSharp/Verse.AI.Group/Trigger_ChanceOnSignal.cs +++ b/Assembly-CSharp/Verse.AI.Group/Trigger_ChanceOnSignal.cs @@ -1,5 +1,3 @@ -using System; - namespace Verse.AI.Group { public class Trigger_ChanceOnSignal : Trigger @@ -16,7 +14,11 @@ public Trigger_ChanceOnSignal(TriggerSignalType signalType, float chance) public override bool ActivateOn(Lord lord, TriggerSignal signal) { - return signal.type == this.signalType && Rand.Value < this.chance; + if (signal.type == this.signalType) + { + return Rand.Value < this.chance; + } + return false; } } } diff --git a/Assembly-CSharp/Verse.AI.Group/Trigger_ChanceOnTickInteval.cs b/Assembly-CSharp/Verse.AI.Group/Trigger_ChanceOnTickInteval.cs index 94f82b327..279076282 100644 --- a/Assembly-CSharp/Verse.AI.Group/Trigger_ChanceOnTickInteval.cs +++ b/Assembly-CSharp/Verse.AI.Group/Trigger_ChanceOnTickInteval.cs @@ -1,5 +1,3 @@ -using System; - namespace Verse.AI.Group { public class Trigger_ChanceOnTickInteval : Trigger @@ -16,7 +14,11 @@ public Trigger_ChanceOnTickInteval(int interval, float chancePerInterval) public override bool ActivateOn(Lord lord, TriggerSignal signal) { - return signal.type == TriggerSignalType.Tick && Find.TickManager.TicksGame % this.interval == 0 && Rand.Value < this.chancePerInterval; + if (signal.type == TriggerSignalType.Tick && Find.TickManager.TicksGame % this.interval == 0) + { + return Rand.Value < this.chancePerInterval; + } + return false; } } } diff --git a/Assembly-CSharp/Verse.AI.Group/Trigger_FractionPawnsLost.cs b/Assembly-CSharp/Verse.AI.Group/Trigger_FractionPawnsLost.cs index cb0f13aaf..9c910e1eb 100644 --- a/Assembly-CSharp/Verse.AI.Group/Trigger_FractionPawnsLost.cs +++ b/Assembly-CSharp/Verse.AI.Group/Trigger_FractionPawnsLost.cs @@ -1,5 +1,3 @@ -using System; - namespace Verse.AI.Group { public class Trigger_FractionPawnsLost : Trigger @@ -13,7 +11,11 @@ public Trigger_FractionPawnsLost(float fraction) public override bool ActivateOn(Lord lord, TriggerSignal signal) { - return signal.type == TriggerSignalType.PawnLost && (float)lord.numPawnsLostViolently >= (float)lord.numPawnsEverGained * this.fraction; + if (signal.type == TriggerSignalType.PawnLost) + { + return (float)lord.numPawnsLostViolently >= (float)lord.numPawnsEverGained * this.fraction; + } + return false; } } } diff --git a/Assembly-CSharp/Verse.AI.Group/Trigger_ImportantTraderCaravanPeopleLost.cs b/Assembly-CSharp/Verse.AI.Group/Trigger_ImportantTraderCaravanPeopleLost.cs index f49138d89..139416ade 100644 --- a/Assembly-CSharp/Verse.AI.Group/Trigger_ImportantTraderCaravanPeopleLost.cs +++ b/Assembly-CSharp/Verse.AI.Group/Trigger_ImportantTraderCaravanPeopleLost.cs @@ -1,5 +1,4 @@ using RimWorld; -using System; namespace Verse.AI.Group { @@ -10,15 +9,18 @@ public override bool ActivateOn(Lord lord, TriggerSignal signal) if (signal.type == TriggerSignalType.PawnLost && (signal.condition == PawnLostCondition.IncappedOrKilled || signal.condition == PawnLostCondition.MadePrisoner)) { TraderCaravanRole traderCaravanRole = signal.Pawn.GetTraderCaravanRole(); - if (traderCaravanRole == TraderCaravanRole.Trader || traderCaravanRole == TraderCaravanRole.Carrier) + if (traderCaravanRole != TraderCaravanRole.Trader && traderCaravanRole != TraderCaravanRole.Carrier) { - return true; - } - if (lord.numPawnsLostViolently > 0 && (float)lord.numPawnsLostViolently / (float)lord.numPawnsEverGained >= 0.5f) - { - return true; + if (lord.numPawnsLostViolently > 0 && (float)lord.numPawnsLostViolently / (float)lord.numPawnsEverGained >= 0.5) + { + return true; + } + goto IL_006b; } + return true; } + goto IL_006b; + IL_006b: return false; } } diff --git a/Assembly-CSharp/Verse.AI.Group/Trigger_Memo.cs b/Assembly-CSharp/Verse.AI.Group/Trigger_Memo.cs index b1a44773c..fec688c17 100644 --- a/Assembly-CSharp/Verse.AI.Group/Trigger_Memo.cs +++ b/Assembly-CSharp/Verse.AI.Group/Trigger_Memo.cs @@ -1,5 +1,3 @@ -using System; - namespace Verse.AI.Group { public class Trigger_Memo : Trigger @@ -13,7 +11,11 @@ public Trigger_Memo(string memo) public override bool ActivateOn(Lord lord, TriggerSignal signal) { - return signal.type == TriggerSignalType.Memo && signal.memo == this.memo; + if (signal.type == TriggerSignalType.Memo) + { + return signal.memo == this.memo; + } + return false; } } } diff --git a/Assembly-CSharp/Verse.AI.Group/Trigger_MentalState.cs b/Assembly-CSharp/Verse.AI.Group/Trigger_MentalState.cs index c9886a390..2c1b0580e 100644 --- a/Assembly-CSharp/Verse.AI.Group/Trigger_MentalState.cs +++ b/Assembly-CSharp/Verse.AI.Group/Trigger_MentalState.cs @@ -1,5 +1,3 @@ -using System; - namespace Verse.AI.Group { public class Trigger_MentalState : Trigger diff --git a/Assembly-CSharp/Verse.AI.Group/Trigger_NoFightingSappers.cs b/Assembly-CSharp/Verse.AI.Group/Trigger_NoFightingSappers.cs index 616a63243..505daff34 100644 --- a/Assembly-CSharp/Verse.AI.Group/Trigger_NoFightingSappers.cs +++ b/Assembly-CSharp/Verse.AI.Group/Trigger_NoFightingSappers.cs @@ -1,5 +1,4 @@ using RimWorld; -using System; namespace Verse.AI.Group { @@ -24,7 +23,15 @@ public override bool ActivateOn(Lord lord, TriggerSignal signal) private bool IsFightingSapper(Pawn p) { - return !p.Downed && !p.InMentalState && RaidStrategyWorker_ImmediateAttackSappers.CanBeSapper(p.kindDef); + if (!p.Downed && !p.InMentalState) + { + if (RaidStrategyWorker_ImmediateAttackSappers.CanBeSapper(p.kindDef)) + { + return true; + } + return false; + } + return false; } } } diff --git a/Assembly-CSharp/Verse.AI.Group/Trigger_NoMentalState.cs b/Assembly-CSharp/Verse.AI.Group/Trigger_NoMentalState.cs index 87a8c1038..d2236ec7c 100644 --- a/Assembly-CSharp/Verse.AI.Group/Trigger_NoMentalState.cs +++ b/Assembly-CSharp/Verse.AI.Group/Trigger_NoMentalState.cs @@ -1,5 +1,3 @@ -using System; - namespace Verse.AI.Group { public class Trigger_NoMentalState : Trigger diff --git a/Assembly-CSharp/Verse.AI.Group/Trigger_NoPawnsVeryTiredAndSleeping.cs b/Assembly-CSharp/Verse.AI.Group/Trigger_NoPawnsVeryTiredAndSleeping.cs index ba5e4c763..611c7bea4 100644 --- a/Assembly-CSharp/Verse.AI.Group/Trigger_NoPawnsVeryTiredAndSleeping.cs +++ b/Assembly-CSharp/Verse.AI.Group/Trigger_NoPawnsVeryTiredAndSleeping.cs @@ -1,5 +1,4 @@ using RimWorld; -using System; namespace Verse.AI.Group { @@ -19,12 +18,9 @@ public override bool ActivateOn(Lord lord, TriggerSignal signal) for (int i = 0; i < lord.ownedPawns.Count; i++) { Need_Rest rest = lord.ownedPawns[i].needs.rest; - if (rest != null) + if (rest != null && rest.CurLevelPercentage < 0.14000000059604645 + this.extraRestThreshOffset && !lord.ownedPawns[i].Awake()) { - if (rest.CurLevelPercentage < 0.14f + this.extraRestThreshOffset && !lord.ownedPawns[i].Awake()) - { - return false; - } + return false; } } return true; diff --git a/Assembly-CSharp/Verse.AI.Group/Trigger_PawnCanReachMapEdge.cs b/Assembly-CSharp/Verse.AI.Group/Trigger_PawnCanReachMapEdge.cs index e9931d980..b069ecc40 100644 --- a/Assembly-CSharp/Verse.AI.Group/Trigger_PawnCanReachMapEdge.cs +++ b/Assembly-CSharp/Verse.AI.Group/Trigger_PawnCanReachMapEdge.cs @@ -1,5 +1,3 @@ -using System; - namespace Verse.AI.Group { public class Trigger_PawnCanReachMapEdge : Trigger @@ -11,12 +9,9 @@ public override bool ActivateOn(Lord lord, TriggerSignal signal) for (int i = 0; i < lord.ownedPawns.Count; i++) { Pawn pawn = lord.ownedPawns[i]; - if (pawn.Spawned && !pawn.Dead && !pawn.Downed) + if (pawn.Spawned && !pawn.Dead && !pawn.Downed && !pawn.CanReachMapEdge()) { - if (!pawn.CanReachMapEdge()) - { - return false; - } + return false; } } return true; diff --git a/Assembly-CSharp/Verse.AI.Group/Trigger_PawnCannotReachMapEdge.cs b/Assembly-CSharp/Verse.AI.Group/Trigger_PawnCannotReachMapEdge.cs index 4929c46f2..8cd5aa80a 100644 --- a/Assembly-CSharp/Verse.AI.Group/Trigger_PawnCannotReachMapEdge.cs +++ b/Assembly-CSharp/Verse.AI.Group/Trigger_PawnCannotReachMapEdge.cs @@ -1,5 +1,3 @@ -using System; - namespace Verse.AI.Group { public class Trigger_PawnCannotReachMapEdge : Trigger @@ -11,12 +9,9 @@ public override bool ActivateOn(Lord lord, TriggerSignal signal) for (int i = 0; i < lord.ownedPawns.Count; i++) { Pawn pawn = lord.ownedPawns[i]; - if (pawn.Spawned && !pawn.Dead && !pawn.Downed) + if (pawn.Spawned && !pawn.Dead && !pawn.Downed && !pawn.CanReachMapEdge()) { - if (!pawn.CanReachMapEdge()) - { - return true; - } + return true; } } } diff --git a/Assembly-CSharp/Verse.AI.Group/Trigger_PawnExperiencingDangerousTemperatures.cs b/Assembly-CSharp/Verse.AI.Group/Trigger_PawnExperiencingDangerousTemperatures.cs index b8ecec61f..2c17cab28 100644 --- a/Assembly-CSharp/Verse.AI.Group/Trigger_PawnExperiencingDangerousTemperatures.cs +++ b/Assembly-CSharp/Verse.AI.Group/Trigger_PawnExperiencingDangerousTemperatures.cs @@ -1,5 +1,4 @@ using RimWorld; -using System; namespace Verse.AI.Group { diff --git a/Assembly-CSharp/Verse.AI.Group/Trigger_PawnHarmed.cs b/Assembly-CSharp/Verse.AI.Group/Trigger_PawnHarmed.cs index ee1ca8808..f4159f146 100644 --- a/Assembly-CSharp/Verse.AI.Group/Trigger_PawnHarmed.cs +++ b/Assembly-CSharp/Verse.AI.Group/Trigger_PawnHarmed.cs @@ -1,5 +1,3 @@ -using System; - namespace Verse.AI.Group { public class Trigger_PawnHarmed : Trigger @@ -16,7 +14,15 @@ public Trigger_PawnHarmed(float chance = 1f, bool requireInstigatorWithFaction = public override bool ActivateOn(Lord lord, TriggerSignal signal) { - return Trigger_PawnHarmed.SignalIsHarm(signal) && (!this.requireInstigatorWithFaction || (signal.dinfo.Instigator != null && signal.dinfo.Instigator.Faction != null)) && Rand.Value < this.chance; + if (!Trigger_PawnHarmed.SignalIsHarm(signal)) + { + return false; + } + if (this.requireInstigatorWithFaction && (signal.dinfo.Instigator == null || signal.dinfo.Instigator.Faction == null)) + { + return false; + } + return Rand.Value < this.chance; } public static bool SignalIsHarm(TriggerSignal signal) @@ -29,7 +35,11 @@ public static bool SignalIsHarm(TriggerSignal signal) { return signal.condition == PawnLostCondition.MadePrisoner || signal.condition == PawnLostCondition.IncappedOrKilled; } - return signal.type == TriggerSignalType.PawnArrestAttempted; + if (signal.type == TriggerSignalType.PawnArrestAttempted) + { + return true; + } + return false; } } } diff --git a/Assembly-CSharp/Verse.AI.Group/Trigger_PawnLost.cs b/Assembly-CSharp/Verse.AI.Group/Trigger_PawnLost.cs index 6a9f85d91..f70b28eb4 100644 --- a/Assembly-CSharp/Verse.AI.Group/Trigger_PawnLost.cs +++ b/Assembly-CSharp/Verse.AI.Group/Trigger_PawnLost.cs @@ -1,5 +1,3 @@ -using System; - namespace Verse.AI.Group { public class Trigger_PawnLost : Trigger diff --git a/Assembly-CSharp/Verse.AI.Group/Trigger_PawnLostViolently.cs b/Assembly-CSharp/Verse.AI.Group/Trigger_PawnLostViolently.cs index 69e2fda28..cf380c834 100644 --- a/Assembly-CSharp/Verse.AI.Group/Trigger_PawnLostViolently.cs +++ b/Assembly-CSharp/Verse.AI.Group/Trigger_PawnLostViolently.cs @@ -1,12 +1,14 @@ -using System; - namespace Verse.AI.Group { public class Trigger_PawnLostViolently : Trigger { public override bool ActivateOn(Lord lord, TriggerSignal signal) { - return signal.type == TriggerSignalType.PawnLost && (signal.condition == PawnLostCondition.MadePrisoner || signal.condition == PawnLostCondition.IncappedOrKilled); + if (signal.type == TriggerSignalType.PawnLost) + { + return signal.condition == PawnLostCondition.MadePrisoner || signal.condition == PawnLostCondition.IncappedOrKilled; + } + return false; } } } diff --git a/Assembly-CSharp/Verse.AI.Group/Trigger_PawnsLost.cs b/Assembly-CSharp/Verse.AI.Group/Trigger_PawnsLost.cs index b0f5d8932..9458e0889 100644 --- a/Assembly-CSharp/Verse.AI.Group/Trigger_PawnsLost.cs +++ b/Assembly-CSharp/Verse.AI.Group/Trigger_PawnsLost.cs @@ -1,5 +1,3 @@ -using System; - namespace Verse.AI.Group { public class Trigger_PawnsLost : Trigger @@ -13,7 +11,11 @@ public Trigger_PawnsLost(int count) public override bool ActivateOn(Lord lord, TriggerSignal signal) { - return signal.type == TriggerSignalType.PawnLost && lord.numPawnsLostViolently >= this.count; + if (signal.type == TriggerSignalType.PawnLost) + { + return lord.numPawnsLostViolently >= this.count; + } + return false; } } } diff --git a/Assembly-CSharp/Verse.AI.Group/Trigger_ThingDamageTaken.cs b/Assembly-CSharp/Verse.AI.Group/Trigger_ThingDamageTaken.cs index ad864dc72..95c8b8f61 100644 --- a/Assembly-CSharp/Verse.AI.Group/Trigger_ThingDamageTaken.cs +++ b/Assembly-CSharp/Verse.AI.Group/Trigger_ThingDamageTaken.cs @@ -1,5 +1,3 @@ -using System; - namespace Verse.AI.Group { public class Trigger_ThingDamageTaken : Trigger @@ -16,7 +14,11 @@ public Trigger_ThingDamageTaken(Thing thing, float damageFraction) public override bool ActivateOn(Lord lord, TriggerSignal signal) { - return signal.type == TriggerSignalType.Tick && (this.thing.DestroyedOrNull() || (float)this.thing.HitPoints < (1f - this.damageFraction) * (float)this.thing.MaxHitPoints); + if (signal.type == TriggerSignalType.Tick) + { + return this.thing.DestroyedOrNull() || (float)this.thing.HitPoints < (1.0 - this.damageFraction) * (float)this.thing.MaxHitPoints; + } + return false; } } } diff --git a/Assembly-CSharp/Verse.AI.Group/Trigger_TickCondition.cs b/Assembly-CSharp/Verse.AI.Group/Trigger_TickCondition.cs index e12de21c6..c19a2e6d3 100644 --- a/Assembly-CSharp/Verse.AI.Group/Trigger_TickCondition.cs +++ b/Assembly-CSharp/Verse.AI.Group/Trigger_TickCondition.cs @@ -13,7 +13,11 @@ public Trigger_TickCondition(Func condition) public override bool ActivateOn(Lord lord, TriggerSignal signal) { - return signal.type == TriggerSignalType.Tick && this.condition(); + if (signal.type == TriggerSignalType.Tick) + { + return this.condition(); + } + return false; } } } diff --git a/Assembly-CSharp/Verse.AI.Group/Trigger_TicksPassed.cs b/Assembly-CSharp/Verse.AI.Group/Trigger_TicksPassed.cs index 4c8ec030b..7a16454bd 100644 --- a/Assembly-CSharp/Verse.AI.Group/Trigger_TicksPassed.cs +++ b/Assembly-CSharp/Verse.AI.Group/Trigger_TicksPassed.cs @@ -1,4 +1,3 @@ -using System; using UnityEngine; namespace Verse.AI.Group @@ -11,7 +10,7 @@ protected TriggerData_TicksPassed Data { get { - return (TriggerData_TicksPassed)this.data; + return (TriggerData_TicksPassed)base.data; } } @@ -25,7 +24,7 @@ public int TicksLeft public Trigger_TicksPassed(int tickLimit) { - this.data = new TriggerData_TicksPassed(); + base.data = new TriggerData_TicksPassed(); this.duration = tickLimit; } diff --git a/Assembly-CSharp/Verse.AI.Group/Trigger_TicksPassedAndNoRecentHarm.cs b/Assembly-CSharp/Verse.AI.Group/Trigger_TicksPassedAndNoRecentHarm.cs index ce0203828..fd4ce1c6b 100644 --- a/Assembly-CSharp/Verse.AI.Group/Trigger_TicksPassedAndNoRecentHarm.cs +++ b/Assembly-CSharp/Verse.AI.Group/Trigger_TicksPassedAndNoRecentHarm.cs @@ -1,5 +1,3 @@ -using System; - namespace Verse.AI.Group { public class Trigger_TicksPassedAndNoRecentHarm : Trigger_TicksPassed @@ -12,7 +10,11 @@ public Trigger_TicksPassedAndNoRecentHarm(int tickLimit) : base(tickLimit) public override bool ActivateOn(Lord lord, TriggerSignal signal) { - return base.ActivateOn(lord, signal) && Find.TickManager.TicksGame - lord.lastPawnHarmTick >= 300; + if (base.ActivateOn(lord, signal) && Find.TickManager.TicksGame - lord.lastPawnHarmTick >= 300) + { + return true; + } + return false; } } } diff --git a/Assembly-CSharp/Verse.AI.Group/Trigger_TicksPassedWithoutHarm.cs b/Assembly-CSharp/Verse.AI.Group/Trigger_TicksPassedWithoutHarm.cs index c81c9c7d0..cae7b3a27 100644 --- a/Assembly-CSharp/Verse.AI.Group/Trigger_TicksPassedWithoutHarm.cs +++ b/Assembly-CSharp/Verse.AI.Group/Trigger_TicksPassedWithoutHarm.cs @@ -1,5 +1,3 @@ -using System; - namespace Verse.AI.Group { public class Trigger_TicksPassedWithoutHarm : Trigger_TicksPassed diff --git a/Assembly-CSharp/Verse.AI.Group/Trigger_TicksPassedWithoutHarmOrMemos.cs b/Assembly-CSharp/Verse.AI.Group/Trigger_TicksPassedWithoutHarmOrMemos.cs index 9268cb6e4..780a89a17 100644 --- a/Assembly-CSharp/Verse.AI.Group/Trigger_TicksPassedWithoutHarmOrMemos.cs +++ b/Assembly-CSharp/Verse.AI.Group/Trigger_TicksPassedWithoutHarmOrMemos.cs @@ -1,4 +1,3 @@ -using System; using System.Collections.Generic; using System.Linq; @@ -10,7 +9,7 @@ public class Trigger_TicksPassedWithoutHarmOrMemos : Trigger_TicksPassed public Trigger_TicksPassedWithoutHarmOrMemos(int tickLimit, params string[] memos) : base(tickLimit) { - this.memos = memos.ToList(); + this.memos = memos.ToList(); } public override bool ActivateOn(Lord lord, TriggerSignal signal) diff --git a/Assembly-CSharp/Verse.AI.Group/Trigger_TraderAndAllTraderCaravanGuardsLost.cs b/Assembly-CSharp/Verse.AI.Group/Trigger_TraderAndAllTraderCaravanGuardsLost.cs index 88f25386d..5b2638c73 100644 --- a/Assembly-CSharp/Verse.AI.Group/Trigger_TraderAndAllTraderCaravanGuardsLost.cs +++ b/Assembly-CSharp/Verse.AI.Group/Trigger_TraderAndAllTraderCaravanGuardsLost.cs @@ -1,5 +1,4 @@ using RimWorld; -using System; namespace Verse.AI.Group { @@ -9,13 +8,16 @@ public override bool ActivateOn(Lord lord, TriggerSignal signal) { if (signal.type == TriggerSignalType.PawnLost) { - for (int i = 0; i < lord.ownedPawns.Count; i++) + int num = 0; + while (num < lord.ownedPawns.Count) { - TraderCaravanRole traderCaravanRole = lord.ownedPawns[i].GetTraderCaravanRole(); - if (traderCaravanRole == TraderCaravanRole.Trader || traderCaravanRole == TraderCaravanRole.Guard) + TraderCaravanRole traderCaravanRole = lord.ownedPawns[num].GetTraderCaravanRole(); + if (traderCaravanRole != TraderCaravanRole.Trader && traderCaravanRole != TraderCaravanRole.Guard) { - return false; + num++; + continue; } + return false; } return true; } diff --git a/Assembly-CSharp/Verse.AI.Group/Trigger_UrgentlyHungry.cs b/Assembly-CSharp/Verse.AI.Group/Trigger_UrgentlyHungry.cs index 1a2be7ace..cd8faca33 100644 --- a/Assembly-CSharp/Verse.AI.Group/Trigger_UrgentlyHungry.cs +++ b/Assembly-CSharp/Verse.AI.Group/Trigger_UrgentlyHungry.cs @@ -1,6 +1,3 @@ -using RimWorld; -using System; - namespace Verse.AI.Group { public class Trigger_UrgentlyHungry : Trigger @@ -11,7 +8,7 @@ public override bool ActivateOn(Lord lord, TriggerSignal signal) { for (int i = 0; i < lord.ownedPawns.Count; i++) { - if (lord.ownedPawns[i].needs.food.CurCategory >= HungerCategory.UrgentlyHungry) + if ((int)lord.ownedPawns[i].needs.food.CurCategory >= 2) { return true; } diff --git a/Assembly-CSharp/Verse.AI/AttackTargetFinder.cs b/Assembly-CSharp/Verse.AI/AttackTargetFinder.cs index a5c50ecca..54117c5cc 100644 --- a/Assembly-CSharp/Verse.AI/AttackTargetFinder.cs +++ b/Assembly-CSharp/Verse.AI/AttackTargetFinder.cs @@ -19,7 +19,7 @@ public static class AttackTargetFinder private static List tempSourceList = new List(); - public static IAttackTarget BestAttackTarget(IAttackTargetSearcher searcher, TargetScanFlags flags, Predicate validator = null, float minDist = 0f, float maxDist = 9999f, IntVec3 locus = default(IntVec3), float maxTravelRadiusFromLocus = 3.40282347E+38f, bool canBash = false) + public static IAttackTarget BestAttackTarget(IAttackTargetSearcher searcher, TargetScanFlags flags, Predicate validator = null, float minDist = 0, float maxDist = 9999, IntVec3 locus = default(IntVec3), float maxTravelRadiusFromLocus = 3.40282347E+38f, bool canBash = false) { Thing searcherThing = searcher.Thing; Pawn searcherPawn = searcher as Pawn; @@ -34,26 +34,30 @@ public static class AttackTargetFinder float num = maxTravelRadiusFromLocus + verb.verbProps.range; float maxLocusDistSquared = num * num; Func losValidator = null; - if ((byte)(flags & TargetScanFlags.LOSBlockableByGas) != 0) + if ((byte)((int)flags & 64) != 0) { - losValidator = delegate(IntVec3 vec3) + losValidator = (Func)delegate(IntVec3 vec3) { Thing gas = vec3.GetGas(searcherThing.Map); - return gas == null || !gas.def.gas.blockTurretTracking; + if (gas != null && gas.def.gas.blockTurretTracking) + { + return false; + } + return true; }; } - Predicate innerValidator = delegate(IAttackTarget t) + Predicate innerValidator = (Predicate)delegate(IAttackTarget t) { Thing thing = t.Thing; if (t == searcher) { return false; } - if (minDistanceSquared > 0f && (float)(searcherThing.Position - thing.Position).LengthHorizontalSquared < minDistanceSquared) + if (minDistanceSquared > 0.0 && (float)(searcherThing.Position - thing.Position).LengthHorizontalSquared < minDistanceSquared) { return false; } - if (maxTravelRadiusFromLocus < 9999f && (float)(thing.Position - locus).LengthHorizontalSquared > maxLocusDistSquared) + if (maxTravelRadiusFromLocus < 9999.0 && (float)(thing.Position - locus).LengthHorizontalSquared > maxLocusDistSquared) { return false; } @@ -61,25 +65,25 @@ public static class AttackTargetFinder { return false; } - if (validator != null && !validator(thing)) + if ((object)validator != null && !validator(thing)) { return false; } - if ((byte)(flags & TargetScanFlags.NeedLOSToAll) != 0 && !searcherThing.CanSee(thing, losValidator)) + if ((byte)((int)flags & 3) != 0 && !searcherThing.CanSee(thing, losValidator)) { if (t is Pawn) { - if ((byte)(flags & TargetScanFlags.NeedLOSToPawns) != 0) + if ((byte)((int)flags & 1) != 0) { return false; } } - else if ((byte)(flags & TargetScanFlags.NeedLOSToNonPawns) != 0) + else if ((byte)((int)flags & 2) != 0) { return false; } } - if ((byte)(flags & TargetScanFlags.NeedThreat) != 0 && t.ThreatDisabled()) + if ((byte)((int)flags & 32) != 0 && t.ThreatDisabled()) { return false; } @@ -88,11 +92,11 @@ public static class AttackTargetFinder { return false; } - if ((byte)(flags & TargetScanFlags.NeedNonBurning) != 0 && thing.IsBurning()) + if ((byte)((int)flags & 16) != 0 && thing.IsBurning()) { return false; } - if (searcherThing.def.race != null && searcherThing.def.race.intelligence >= Intelligence.Humanlike) + if (searcherThing.def.race != null && (int)searcherThing.def.race.intelligence >= 2) { CompExplosive compExplosive = thing.TryGetComp(); if (compExplosive != null && compExplosive.wickStarted) @@ -106,10 +110,11 @@ public static class AttackTargetFinder { AttackTargetFinder.tmpTargets.Clear(); AttackTargetFinder.tmpTargets.AddRange(searcherThing.Map.attackTargetsCache.GetPotentialTargetsFor(searcher)); - if ((byte)(flags & TargetScanFlags.NeedReachable) != 0) + if ((byte)((int)flags & 4) != 0) { Predicate oldValidator = innerValidator; - innerValidator = ((IAttackTarget t) => oldValidator(t) && AttackTargetFinder.CanReach(searcherThing, t.Thing, canBash)); + _003CBestAttackTarget_003Ec__AnonStorey502 _003CBestAttackTarget_003Ec__AnonStorey; + innerValidator = (Predicate)((IAttackTarget t) => oldValidator(t) && AttackTargetFinder.CanReach(_003CBestAttackTarget_003Ec__AnonStorey.searcherThing, t.Thing, canBash)); } bool flag = false; if (searcherThing.Faction != Faction.OfPlayer) @@ -127,37 +132,40 @@ public static class AttackTargetFinder IAttackTarget result; if (flag) { - AttackTargetFinder.tmpTargets.RemoveAll((IAttackTarget x) => !x.Thing.Position.InHorDistOf(searcherThing.Position, maxDist) || !innerValidator(x)); + AttackTargetFinder.tmpTargets.RemoveAll((Predicate)((IAttackTarget x) => !x.Thing.Position.InHorDistOf(searcherThing.Position, maxDist) || !innerValidator(x))); result = AttackTargetFinder.GetRandomShootingTargetByScore(AttackTargetFinder.tmpTargets, searcher, verb); } else { - Predicate validator2; - if ((byte)(flags & TargetScanFlags.NeedReachableIfCantHitFromMyPos) != 0 && (byte)(flags & TargetScanFlags.NeedReachable) == 0) - { - validator2 = ((Thing t) => innerValidator((IAttackTarget)t) && (AttackTargetFinder.CanReach(searcherThing, t, canBash) || AttackTargetFinder.CanShootAtFromCurrentPosition((IAttackTarget)t, searcher, verb))); - } - else - { - validator2 = ((Thing t) => innerValidator((IAttackTarget)t)); - } + Predicate validator2 = ((((byte)((int)flags & 8) == 0) ? 1 : ((byte)((int)flags & 4))) != 0) ? ((Predicate)((Thing t) => innerValidator((IAttackTarget)t))) : ((Predicate)((Thing t) => innerValidator((IAttackTarget)t) && (AttackTargetFinder.CanReach(searcherThing, t, canBash) || AttackTargetFinder.CanShootAtFromCurrentPosition((IAttackTarget)t, searcher, verb)))); result = (IAttackTarget)GenClosest.ClosestThing_Global(searcherThing.Position, AttackTargetFinder.tmpTargets, maxDist, validator2); } AttackTargetFinder.tmpTargets.Clear(); return result; } - if (searcherPawn != null && searcherPawn.mindState.duty != null && searcherPawn.mindState.duty.radius > 0f) + if (searcherPawn != null && searcherPawn.mindState.duty != null && searcherPawn.mindState.duty.radius > 0.0) { - Predicate oldValidator = innerValidator; - innerValidator = ((IAttackTarget t) => oldValidator(t) && t.Thing.Position.InHorDistOf(searcherPawn.mindState.duty.focus.Cell, searcherPawn.mindState.duty.radius)); + Predicate oldValidator2 = innerValidator; + innerValidator = (Predicate)delegate(IAttackTarget t) + { + if (!oldValidator2(t)) + { + return false; + } + _003CBestAttackTarget_003Ec__AnonStorey502 _003CBestAttackTarget_003Ec__AnonStorey2; + if (!t.Thing.Position.InHorDistOf(_003CBestAttackTarget_003Ec__AnonStorey2.searcherPawn.mindState.duty.focus.Cell, _003CBestAttackTarget_003Ec__AnonStorey2.searcherPawn.mindState.duty.radius)) + { + return false; + } + return true; + }; } - int searchRegionsMax = (maxDist <= 800f) ? 40 : -1; - IntVec3 arg_415_0 = searcherThing.Position; - Map arg_415_1 = searcherThing.Map; - ThingRequest arg_415_2 = ThingRequest.ForGroup(ThingRequestGroup.AttackTarget); - PathEndMode arg_415_3 = PathEndMode.Touch; + int searchRegionsMax = (!(maxDist > 800.0)) ? 40 : (-1); + IntVec3 position = searcherThing.Position; + Map map = searcherThing.Map; + ThingRequest thingReq = ThingRequest.ForGroup(ThingRequestGroup.AttackTarget); bool canBash2 = canBash; - IAttackTarget attackTarget2 = (IAttackTarget)GenClosest.ClosestThingReachable(arg_415_0, arg_415_1, arg_415_2, arg_415_3, TraverseParms.For(searcherPawn, Danger.Deadly, TraverseMode.ByPawn, canBash2), maxDist, (Thing x) => innerValidator((IAttackTarget)x), null, 0, searchRegionsMax, false, RegionType.Set_Passable, false); + IAttackTarget attackTarget2 = (IAttackTarget)GenClosest.ClosestThingReachable(position, map, thingReq, PathEndMode.Touch, TraverseParms.For(searcherPawn, Danger.Deadly, TraverseMode.ByPawn, canBash2), maxDist, (Predicate)((Thing x) => innerValidator((IAttackTarget)x)), null, 0, searchRegionsMax, false, RegionType.Set_Passable, false); if (attackTarget2 != null && PawnUtility.ShouldCollideWithPawns(searcherPawn)) { IAttackTarget attackTarget3 = AttackTargetFinder.FindBestReachableMeleeTarget(innerValidator, searcherPawn, maxDist, canBash); @@ -165,7 +173,7 @@ public static class AttackTargetFinder { float lengthHorizontal = (searcherPawn.Position - attackTarget2.Thing.Position).LengthHorizontal; float lengthHorizontal2 = (searcherPawn.Position - attackTarget3.Thing.Position).LengthHorizontal; - if (Mathf.Abs(lengthHorizontal - lengthHorizontal2) < 50f) + if (Mathf.Abs(lengthHorizontal - lengthHorizontal2) < 50.0) { attackTarget2 = attackTarget3; } @@ -186,7 +194,7 @@ private static bool CanReach(Thing searcher, Thing target, bool canBash) } else { - TraverseMode mode = (!canBash) ? TraverseMode.NoPassClosedDoors : TraverseMode.PassDoors; + TraverseMode mode = (TraverseMode)(canBash ? 1 : 2); if (!searcher.Map.reachability.CanReach(searcher.Position, target, PathEndMode.Touch, TraverseParms.For(mode, Danger.Deadly, false))) { return false; @@ -199,30 +207,21 @@ private static IAttackTarget FindBestReachableMeleeTarget(Predicate bestTargetOnCell = delegate(IntVec3 x) + Func bestTargetOnCell = (Func)delegate(IntVec3 x) { List thingList = x.GetThingList(searcherPawn.Map); - for (int i = 0; i < thingList.Count; i++) + for (int j = 0; j < thingList.Count; j++) { - Thing thing = thingList[i]; - IAttackTarget attackTarget = thing as IAttackTarget; - if (attackTarget != null) + Thing thing = thingList[j]; + IAttackTarget attackTarget2 = thing as IAttackTarget; + if (attackTarget2 != null && validator(attackTarget2) && ReachabilityImmediate.CanReachImmediate(x, thing, searcherPawn.Map, PathEndMode.Touch, searcherPawn) && (searcherPawn.CanReachImmediate(thing, PathEndMode.Touch) || searcherPawn.Map.attackTargetReservationManager.CanReserve(searcherPawn, attackTarget2))) { - if (validator(attackTarget)) - { - if (ReachabilityImmediate.CanReachImmediate(x, thing, searcherPawn.Map, PathEndMode.Touch, searcherPawn)) - { - if (searcherPawn.CanReachImmediate(thing, PathEndMode.Touch) || searcherPawn.Map.attackTargetReservationManager.CanReserve(searcherPawn, attackTarget)) - { - return attackTarget; - } - } - } + return attackTarget2; } } return null; }; - searcherPawn.Map.floodFiller.FloodFill(searcherPawn.Position, delegate(IntVec3 x) + searcherPawn.Map.floodFiller.FloodFill(searcherPawn.Position, (Predicate)delegate(IntVec3 x) { if (!x.Walkable(searcherPawn.Map)) { @@ -240,8 +239,12 @@ private static IAttackTarget FindBestReachableMeleeTarget(Predicate)delegate(IntVec3 x) { for (int i = 0; i < 8; i++) { @@ -269,13 +272,17 @@ private static bool HasRangedAttack(IAttackTargetSearcher t) private static bool CanShootAtFromCurrentPosition(IAttackTarget target, IAttackTargetSearcher searcher, Verb verb) { - return verb != null && verb.CanHitTargetFrom(searcher.Thing.Position, target.Thing); + if (verb == null) + { + return false; + } + return verb.CanHitTargetFrom(searcher.Thing.Position, target.Thing); } private static IAttackTarget GetRandomShootingTargetByScore(List targets, IAttackTargetSearcher searcher, Verb verb) { - Pair pair; - if (AttackTargetFinder.GetAvailableShootingTargetsByScore(targets, searcher, verb).TryRandomElementByWeight((Pair x) => x.Second, out pair)) + Pair pair = default(Pair); + if (((IEnumerable>)AttackTargetFinder.GetAvailableShootingTargetsByScore(targets, searcher, verb)).TryRandomElementByWeight>((Func, float>)((Pair x) => x.Second), out pair)) { return pair.First; } @@ -313,7 +320,7 @@ private static List> GetAvailableShootingTargetsBySco } } } - if (num < 1f) + if (num < 1.0) { if (attackTarget != null) { @@ -322,19 +329,16 @@ private static List> GetAvailableShootingTargetsBySco } else { - float num2 = num - 30f; + float num2 = (float)(num - 30.0); for (int j = 0; j < rawTargets.Count; j++) { - if (rawTargets[j] != searcher) + if (rawTargets[j] != searcher && AttackTargetFinder.tmpCanShootAtTarget[j]) { - if (AttackTargetFinder.tmpCanShootAtTarget[j]) + float num3 = AttackTargetFinder.tmpTargetScores[j]; + if (num3 >= num2) { - float num3 = AttackTargetFinder.tmpTargetScores[j]; - if (num3 >= num2) - { - float second = Mathf.InverseLerp(num - 30f, num, num3); - AttackTargetFinder.availableShootingTargets.Add(new Pair(rawTargets[j], second)); - } + float second = Mathf.InverseLerp((float)(num - 30.0), num, num3); + AttackTargetFinder.availableShootingTargets.Add(new Pair(rawTargets[j], second)); } } } @@ -348,24 +352,24 @@ private static float GetShootingTargetScore(IAttackTarget target, IAttackTargetS num -= Mathf.Min((target.Thing.Position - searcher.Thing.Position).LengthHorizontal, 40f); if (target.TargetCurrentlyAimingAt == searcher.Thing) { - num += 10f; + num = (float)(num + 10.0); } if (searcher.LastAttackedTarget == target.Thing && Find.TickManager.TicksGame - searcher.LastAttackTargetTick <= 300) { - num += 40f; + num = (float)(num + 40.0); } - num -= CoverUtility.CalculateOverallBlockChance(target.Thing.Position, searcher.Thing.Position, searcher.Thing.Map) * 10f; + num = (float)(num - CoverUtility.CalculateOverallBlockChance(target.Thing.Position, searcher.Thing.Position, searcher.Thing.Map) * 10.0); Pawn pawn = target as Pawn; if (pawn != null && pawn.RaceProps.Animal && pawn.Faction != null && !pawn.IsFighting()) { - num -= 50f; + num = (float)(num - 50.0); } return num + AttackTargetFinder.FriendlyFireShootingTargetScoreOffset(target, searcher, verb); } private static float FriendlyFireShootingTargetScoreOffset(IAttackTarget target, IAttackTargetSearcher searcher, Verb verb) { - if (verb.verbProps.ai_AvoidFriendlyFireRadius <= 0f) + if (verb.verbProps.ai_AvoidFriendlyFireRadius <= 0.0) { return 0f; } @@ -373,16 +377,16 @@ private static float FriendlyFireShootingTargetScoreOffset(IAttackTarget target, IntVec3 position = target.Thing.Position; int num = GenRadial.NumCellsInRadius(verb.verbProps.ai_AvoidFriendlyFireRadius); float num2 = 0f; - for (int i = 0; i < num; i++) + for (int num3 = 0; num3 < num; num3++) { - IntVec3 intVec = position + GenRadial.RadialPattern[i]; + IntVec3 intVec = position + GenRadial.RadialPattern[num3]; if (intVec.InBounds(map)) { bool flag = true; List thingList = intVec.GetThingList(map); - for (int j = 0; j < thingList.Count; j++) + for (int i = 0; i < thingList.Count; i++) { - if (thingList[j] is IAttackTarget && thingList[j] != target) + if (thingList[i] is IAttackTarget && thingList[i] != target) { if (flag) { @@ -392,27 +396,8 @@ private static float FriendlyFireShootingTargetScoreOffset(IAttackTarget target, } flag = false; } - float num3; - if (thingList[j] == searcher) - { - num3 = 40f; - } - else if (thingList[j] is Pawn) - { - num3 = ((!thingList[j].def.race.Animal) ? 18f : 7f); - } - else - { - num3 = 10f; - } - if (searcher.Thing.HostileTo(thingList[j])) - { - num2 += num3 * 0.6f; - } - else - { - num2 -= num3; - } + float num4 = (float)((thingList[i] != searcher) ? ((!(thingList[i] is Pawn)) ? 10.0 : ((!thingList[i].def.race.Animal) ? 18.0 : 7.0)) : 40.0); + num2 = (float)((!searcher.Thing.HostileTo(thingList[i])) ? (num2 - num4) : (num2 + num4 * 0.60000002384185791)); } } } @@ -452,74 +437,62 @@ public static bool CanSee(this Thing seer, Thing target, Func val public static void DebugDrawAttackTargetScores_Update() { IAttackTargetSearcher attackTargetSearcher = Find.Selector.SingleSelectedThing as IAttackTargetSearcher; - if (attackTargetSearcher == null) - { - return; - } - if (attackTargetSearcher.Thing.Map != Find.VisibleMap) + if (attackTargetSearcher != null && attackTargetSearcher.Thing.Map == Find.VisibleMap) { - return; - } - Verb currentEffectiveVerb = attackTargetSearcher.CurrentEffectiveVerb; - if (currentEffectiveVerb == null) - { - return; - } - AttackTargetFinder.tmpTargets.Clear(); - List list = attackTargetSearcher.Thing.Map.listerThings.ThingsInGroup(ThingRequestGroup.AttackTarget); - for (int i = 0; i < list.Count; i++) - { - AttackTargetFinder.tmpTargets.Add((IAttackTarget)list[i]); - } - List> availableShootingTargetsByScore = AttackTargetFinder.GetAvailableShootingTargetsByScore(AttackTargetFinder.tmpTargets, attackTargetSearcher, currentEffectiveVerb); - for (int j = 0; j < availableShootingTargetsByScore.Count; j++) - { - GenDraw.DrawLineBetween(attackTargetSearcher.Thing.DrawPos, availableShootingTargetsByScore[j].First.Thing.DrawPos); + Verb currentEffectiveVerb = attackTargetSearcher.CurrentEffectiveVerb; + if (currentEffectiveVerb != null) + { + AttackTargetFinder.tmpTargets.Clear(); + List list = attackTargetSearcher.Thing.Map.listerThings.ThingsInGroup(ThingRequestGroup.AttackTarget); + for (int i = 0; i < list.Count; i++) + { + AttackTargetFinder.tmpTargets.Add((IAttackTarget)list[i]); + } + List> availableShootingTargetsByScore = AttackTargetFinder.GetAvailableShootingTargetsByScore(AttackTargetFinder.tmpTargets, attackTargetSearcher, currentEffectiveVerb); + for (int j = 0; j < availableShootingTargetsByScore.Count; j++) + { + GenDraw.DrawLineBetween(attackTargetSearcher.Thing.DrawPos, availableShootingTargetsByScore[j].First.Thing.DrawPos); + } + } } } public static void DebugDrawAttackTargetScores_OnGUI() { IAttackTargetSearcher attackTargetSearcher = Find.Selector.SingleSelectedThing as IAttackTargetSearcher; - if (attackTargetSearcher == null) - { - return; - } - if (attackTargetSearcher.Thing.Map != Find.VisibleMap) - { - return; - } - Verb currentEffectiveVerb = attackTargetSearcher.CurrentEffectiveVerb; - if (currentEffectiveVerb == null) - { - return; - } - List list = attackTargetSearcher.Thing.Map.listerThings.ThingsInGroup(ThingRequestGroup.AttackTarget); - Text.Anchor = TextAnchor.MiddleCenter; - Text.Font = GameFont.Tiny; - for (int i = 0; i < list.Count; i++) + if (attackTargetSearcher != null && attackTargetSearcher.Thing.Map == Find.VisibleMap) { - Thing thing = list[i]; - if (thing != attackTargetSearcher) + Verb currentEffectiveVerb = attackTargetSearcher.CurrentEffectiveVerb; + if (currentEffectiveVerb != null) { - string text; - Color red; - if (!AttackTargetFinder.CanShootAtFromCurrentPosition((IAttackTarget)thing, attackTargetSearcher, currentEffectiveVerb)) + List list = attackTargetSearcher.Thing.Map.listerThings.ThingsInGroup(ThingRequestGroup.AttackTarget); + Text.Anchor = TextAnchor.MiddleCenter; + Text.Font = GameFont.Tiny; + for (int i = 0; i < list.Count; i++) { - text = "out of range"; - red = Color.red; - } - else - { - text = AttackTargetFinder.GetShootingTargetScore((IAttackTarget)thing, attackTargetSearcher, currentEffectiveVerb).ToString("F0"); - red = new Color(0.25f, 1f, 0.25f); + Thing thing = list[i]; + if (thing != attackTargetSearcher) + { + string text; + Color textColor; + if (!AttackTargetFinder.CanShootAtFromCurrentPosition((IAttackTarget)thing, attackTargetSearcher, currentEffectiveVerb)) + { + text = "out of range"; + textColor = Color.red; + } + else + { + text = AttackTargetFinder.GetShootingTargetScore((IAttackTarget)thing, attackTargetSearcher, currentEffectiveVerb).ToString("F0"); + textColor = new Color(0.25f, 1f, 0.25f); + } + Vector2 screenPos = thing.DrawPos.MapToUIPosition(); + GenMapUI.DrawThingLabel(screenPos, text, textColor); + } } - Vector2 screenPos = thing.DrawPos.MapToUIPosition(); - GenMapUI.DrawThingLabel(screenPos, text, red); + Text.Anchor = TextAnchor.UpperLeft; + Text.Font = GameFont.Small; } } - Text.Anchor = TextAnchor.UpperLeft; - Text.Font = GameFont.Small; } } } diff --git a/Assembly-CSharp/Verse.AI/AttackTargetReservationManager.cs b/Assembly-CSharp/Verse.AI/AttackTargetReservationManager.cs index 698985d95..483e22e42 100644 --- a/Assembly-CSharp/Verse.AI/AttackTargetReservationManager.cs +++ b/Assembly-CSharp/Verse.AI/AttackTargetReservationManager.cs @@ -21,7 +21,7 @@ public void ExposeData() private Map map; - private List reservations = new List(); + private List reservations = new List(); public AttackTargetReservationManager(Map map) { @@ -33,16 +33,14 @@ public void Reserve(Pawn claimant, IAttackTarget target) if (target == null) { Log.Warning(claimant + " tried to reserve null attack target."); - return; } - if (this.IsReservedBy(claimant, target)) + else if (!this.IsReservedBy(claimant, target)) { - return; + AttackTargetReservation attackTargetReservation = new AttackTargetReservation(); + attackTargetReservation.target = target; + attackTargetReservation.claimant = claimant; + this.reservations.Add(attackTargetReservation); } - AttackTargetReservationManager.AttackTargetReservation attackTargetReservation = new AttackTargetReservationManager.AttackTargetReservation(); - attackTargetReservation.target = target; - attackTargetReservation.claimant = claimant; - this.reservations.Add(attackTargetReservation); } public void Release(Pawn claimant, IAttackTarget target) @@ -50,24 +48,20 @@ public void Release(Pawn claimant, IAttackTarget target) if (target == null) { Log.Warning(claimant + " tried to release reservation on null attack target."); - return; } - for (int i = 0; i < this.reservations.Count; i++) + else { - AttackTargetReservationManager.AttackTargetReservation attackTargetReservation = this.reservations[i]; - if (attackTargetReservation.target == target && attackTargetReservation.claimant == claimant) + for (int i = 0; i < this.reservations.Count; i++) { - this.reservations.RemoveAt(i); - return; + AttackTargetReservation attackTargetReservation = this.reservations[i]; + if (attackTargetReservation.target == target && attackTargetReservation.claimant == claimant) + { + this.reservations.RemoveAt(i); + return; + } } + Log.Warning(claimant + " tried to release reservation on target " + target + ", but it's not reserved by him."); } - Log.Warning(string.Concat(new object[] - { - claimant, - " tried to release reservation on target ", - target, - ", but it's not reserved by him." - })); } public bool CanReserve(Pawn claimant, IAttackTarget target) @@ -85,7 +79,7 @@ public bool IsReservedBy(Pawn claimant, IAttackTarget target) { for (int i = 0; i < this.reservations.Count; i++) { - AttackTargetReservationManager.AttackTargetReservation attackTargetReservation = this.reservations[i]; + AttackTargetReservation attackTargetReservation = this.reservations[i]; if (attackTargetReservation.target == target && attackTargetReservation.claimant == claimant) { return true; @@ -96,26 +90,26 @@ public bool IsReservedBy(Pawn claimant, IAttackTarget target) public void ReleaseAllForTarget(IAttackTarget target) { - this.reservations.RemoveAll((AttackTargetReservationManager.AttackTargetReservation x) => x.target == target); + this.reservations.RemoveAll((Predicate)((AttackTargetReservation x) => x.target == target)); } public void ReleaseAllClaimedBy(Pawn claimant) { - for (int i = this.reservations.Count - 1; i >= 0; i--) + for (int num = this.reservations.Count - 1; num >= 0; num--) { - if (this.reservations[i].claimant == claimant) + if (this.reservations[num].claimant == claimant) { - this.reservations.RemoveAt(i); + this.reservations.RemoveAt(num); } } } public void ExposeData() { - Scribe_Collections.Look(ref this.reservations, "reservations", LookMode.Deep, new object[0]); + Scribe_Collections.Look(ref this.reservations, "reservations", LookMode.Deep, new object[0]); if (Scribe.mode == LoadSaveMode.PostLoadInit) { - this.reservations.RemoveAll((AttackTargetReservationManager.AttackTargetReservation x) => x.target == null); + this.reservations.RemoveAll((Predicate)((AttackTargetReservation x) => x.target == null)); } } @@ -124,7 +118,7 @@ private int GetReservationsCount(IAttackTarget target, Faction faction) int num = 0; for (int i = 0; i < this.reservations.Count; i++) { - AttackTargetReservationManager.AttackTargetReservation attackTargetReservation = this.reservations[i]; + AttackTargetReservation attackTargetReservation = this.reservations[i]; if (attackTargetReservation.target == target && attackTargetReservation.claimant.Faction == faction) { num++; @@ -138,17 +132,11 @@ private int GetMaxPreferredReservationsCount(IAttackTarget target) int num = 0; Thing thing = target.Thing; CellRect cellRect = thing.OccupiedRect(); - foreach (IntVec3 current in cellRect.ExpandedBy(1)) + foreach (IntVec3 item in cellRect.ExpandedBy(1)) { - if (!cellRect.Contains(current)) + if (!cellRect.Contains(item) && item.InBounds(this.map) && item.Standable(this.map)) { - if (current.InBounds(this.map)) - { - if (current.Standable(this.map)) - { - num++; - } - } + num++; } } return num; diff --git a/Assembly-CSharp/Verse.AI/AttackTargetsCache.cs b/Assembly-CSharp/Verse.AI/AttackTargetsCache.cs index d5f450b72..7799e5314 100644 --- a/Assembly-CSharp/Verse.AI/AttackTargetsCache.cs +++ b/Assembly-CSharp/Verse.AI/AttackTargetsCache.cs @@ -37,15 +37,14 @@ public AttackTargetsCache(Map map) public void UpdateTarget(IAttackTarget t) { - if (!this.allTargets.Contains(t)) + if (this.allTargets.Contains(t)) { - return; - } - this.DeregisterTarget(t); - Thing thing = t.Thing; - if (thing.Spawned && thing.Map == this.map) - { - this.RegisterTarget(t); + this.DeregisterTarget(t); + Thing thing = t.Thing; + if (thing.Spawned && thing.Map == this.map) + { + this.RegisterTarget(t); + } } } @@ -60,21 +59,39 @@ public List GetPotentialTargetsFor(IAttackTargetSearcher th) { this.Debug_AssertHostile(faction, this.TargetsHostileToFaction(faction)); } - foreach (IAttackTarget current in this.TargetsHostileToFaction(faction)) + HashSet.Enumerator enumerator = this.TargetsHostileToFaction(faction).GetEnumerator(); + try { - if (thing.HostileTo(current.Thing)) + while (enumerator.MoveNext()) { - AttackTargetsCache.targets.Add(current); + IAttackTarget current = enumerator.Current; + if (thing.HostileTo(current.Thing)) + { + AttackTargetsCache.targets.Add(current); + } } } + finally + { + ((IDisposable)(object)enumerator).Dispose(); + } } - foreach (Pawn current2 in this.pawnsInAggroMentalState) + HashSet.Enumerator enumerator2 = this.pawnsInAggroMentalState.GetEnumerator(); + try { - if (thing.HostileTo(current2)) + while (enumerator2.MoveNext()) { - AttackTargetsCache.targets.Add(current2); + Pawn current2 = enumerator2.Current; + if (thing.HostileTo(current2)) + { + AttackTargetsCache.targets.Add(current2); + } } } + finally + { + ((IDisposable)(object)enumerator2).Dispose(); + } Pawn pawn = th as Pawn; if (pawn != null && PrisonBreakUtility.IsPrisonBreaking(pawn)) { @@ -126,14 +143,23 @@ public void Notify_ThingDespawned(Thing th) public void Notify_FactionHostilityChanged(Faction f1, Faction f2) { AttackTargetsCache.tmpTargets.Clear(); - foreach (IAttackTarget current in this.allTargets) + HashSet.Enumerator enumerator = this.allTargets.GetEnumerator(); + try { - Thing thing = current.Thing; - if (thing.Faction == f1 || thing.Faction == f2) + while (enumerator.MoveNext()) { - AttackTargetsCache.tmpTargets.Add(current); + IAttackTarget current = enumerator.Current; + Thing thing = current.Thing; + if (thing.Faction == f1 || thing.Faction == f2) + { + AttackTargetsCache.tmpTargets.Add(current); + } } } + finally + { + ((IDisposable)(object)enumerator).Dispose(); + } for (int i = 0; i < AttackTargetsCache.tmpTargets.Count; i++) { this.UpdateTarget(AttackTargetsCache.tmpTargets[i]); @@ -145,98 +171,93 @@ private void RegisterTarget(IAttackTarget target) { if (this.allTargets.Contains(target)) { - Log.Warning(string.Concat(new object[] - { - "Tried to register the same target twice ", - target, - " in ", - base.GetType() - })); - return; + Log.Warning("Tried to register the same target twice " + target + " in " + base.GetType()); } - Thing thing = target.Thing; - if (!thing.Spawned) + else { - Log.Warning(string.Concat(new object[] + Thing thing = target.Thing; + if (!thing.Spawned) { - "Tried to register unspawned thing ", - thing, - " in ", - base.GetType() - })); - return; - } - if (thing.Map != this.map) - { - Log.Warning("Tried to register attack target " + thing + " but its Map is not this one."); - return; - } - this.allTargets.Add(target); - List allFactionsListForReading = Find.FactionManager.AllFactionsListForReading; - for (int i = 0; i < allFactionsListForReading.Count; i++) - { - if (thing.HostileTo(allFactionsListForReading[i])) + Log.Warning("Tried to register unspawned thing " + thing + " in " + base.GetType()); + } + else if (thing.Map != this.map) { - if (!this.targetsHostileToFaction.ContainsKey(allFactionsListForReading[i])) + Log.Warning("Tried to register attack target " + thing + " but its Map is not this one."); + } + else + { + this.allTargets.Add(target); + List allFactionsListForReading = Find.FactionManager.AllFactionsListForReading; + for (int i = 0; i < allFactionsListForReading.Count; i++) { - this.targetsHostileToFaction.Add(allFactionsListForReading[i], new HashSet()); + if (thing.HostileTo(allFactionsListForReading[i])) + { + if (!this.targetsHostileToFaction.ContainsKey(allFactionsListForReading[i])) + { + this.targetsHostileToFaction.Add(allFactionsListForReading[i], new HashSet()); + } + this.targetsHostileToFaction[allFactionsListForReading[i]].Add(target); + } + } + Pawn pawn = target as Pawn; + if (pawn != null && pawn.InAggroMentalState) + { + this.pawnsInAggroMentalState.Add(pawn); } - this.targetsHostileToFaction[allFactionsListForReading[i]].Add(target); } } - Pawn pawn = target as Pawn; - if (pawn != null && pawn.InAggroMentalState) - { - this.pawnsInAggroMentalState.Add(pawn); - } } private void DeregisterTarget(IAttackTarget target) { if (!this.allTargets.Contains(target)) { - Log.Warning(string.Concat(new object[] - { - "Tried to deregister ", - target, - " but it's not in ", - base.GetType() - })); - return; + Log.Warning("Tried to deregister " + target + " but it's not in " + base.GetType()); } - this.allTargets.Remove(target); - foreach (KeyValuePair> current in this.targetsHostileToFaction) + else { - HashSet value = current.Value; - value.Remove(target); - } - Pawn pawn = target as Pawn; - if (pawn != null) - { - this.pawnsInAggroMentalState.Remove(pawn); + this.allTargets.Remove(target); + Dictionary>.Enumerator enumerator = this.targetsHostileToFaction.GetEnumerator(); + try + { + while (enumerator.MoveNext()) + { + HashSet value = enumerator.Current.Value; + value.Remove(target); + } + } + finally + { + ((IDisposable)(object)enumerator).Dispose(); + } + Pawn pawn = target as Pawn; + if (pawn != null) + { + this.pawnsInAggroMentalState.Remove(pawn); + } } } private void Debug_AssertHostile(Faction f, HashSet targets) { AttackTargetsCache.tmpToUpdate.Clear(); - foreach (IAttackTarget current in targets) + HashSet.Enumerator enumerator = targets.GetEnumerator(); + try { - if (!current.Thing.HostileTo(f)) + while (enumerator.MoveNext()) { - AttackTargetsCache.tmpToUpdate.Add(current); - Log.Error(string.Concat(new string[] + IAttackTarget current = enumerator.Current; + if (!current.Thing.HostileTo(f)) { - "Target ", - (current == null) ? "null" : current.ToString(), - " is not hostile to ", - (f == null) ? "null" : f.ToString(), - " (in ", - base.GetType().Name, - ") but it's in the list (forgot to update the target somewhere?). Trying to update the target..." - })); + AttackTargetsCache.tmpToUpdate.Add(current); + Log.Error("Target " + ((current == null) ? "null" : current.ToString()) + " is not hostile to " + ((f == null) ? "null" : f.ToString()) + " (in " + base.GetType().Name + ") but it's in the list (forgot to update the target somewhere?). Trying to update the target..."); + } } } + finally + { + ((IDisposable)(object)enumerator).Dispose(); + } for (int i = 0; i < AttackTargetsCache.tmpToUpdate.Count; i++) { this.UpdateTarget(AttackTargetsCache.tmpToUpdate[i]); diff --git a/Assembly-CSharp/Verse.AI/AvoidGridMaker.cs b/Assembly-CSharp/Verse.AI/AvoidGridMaker.cs index fe5e3857d..c6491b6f0 100644 --- a/Assembly-CSharp/Verse.AI/AvoidGridMaker.cs +++ b/Assembly-CSharp/Verse.AI/AvoidGridMaker.cs @@ -1,5 +1,4 @@ using RimWorld; -using System; using System.Collections.Generic; using UnityEngine; using Verse.AI.Group; @@ -12,54 +11,52 @@ public static class AvoidGridMaker public static void RegenerateAllAvoidGridsFor(Faction faction) { - if (!faction.def.canUseAvoidGrid) + if (faction.def.canUseAvoidGrid) { - return; - } - List maps = Find.Maps; - for (int i = 0; i < maps.Count; i++) - { - AvoidGridMaker.RegenerateAvoidGridsFor(faction, maps[i]); + List maps = Find.Maps; + for (int i = 0; i < maps.Count; i++) + { + AvoidGridMaker.RegenerateAvoidGridsFor(faction, maps[i]); + } } } public static void RegenerateAvoidGridsFor(Faction faction, Map map) { - if (!faction.def.canUseAvoidGrid) - { - return; - } - ByteGrid byteGrid; - if (faction.avoidGridsSmart.TryGetValue(map, out byteGrid)) - { - byteGrid.Clear(0); - } - else - { - byteGrid = new ByteGrid(map); - faction.avoidGridsSmart.Add(map, byteGrid); - } - ByteGrid byteGrid2; - if (faction.avoidGridsBasic.TryGetValue(map, out byteGrid2)) + if (faction.def.canUseAvoidGrid) { - byteGrid2.Clear(0); - } - else - { - byteGrid2 = new ByteGrid(map); - faction.avoidGridsBasic.Add(map, byteGrid2); + ByteGrid byteGrid = default(ByteGrid); + if (faction.avoidGridsSmart.TryGetValue(map, out byteGrid)) + { + byteGrid.Clear((byte)0); + } + else + { + byteGrid = new ByteGrid(map); + faction.avoidGridsSmart.Add(map, byteGrid); + } + ByteGrid byteGrid2 = default(ByteGrid); + if (faction.avoidGridsBasic.TryGetValue(map, out byteGrid2)) + { + byteGrid2.Clear((byte)0); + } + else + { + byteGrid2 = new ByteGrid(map); + faction.avoidGridsBasic.Add(map, byteGrid2); + } + AvoidGridMaker.GenerateAvoidGridInternal(byteGrid, faction, map, AvoidGridMode.Smart); + AvoidGridMaker.GenerateAvoidGridInternal(byteGrid2, faction, map, AvoidGridMode.Basic); } - AvoidGridMaker.GenerateAvoidGridInternal(byteGrid, faction, map, AvoidGridMode.Smart); - AvoidGridMaker.GenerateAvoidGridInternal(byteGrid2, faction, map, AvoidGridMode.Basic); } internal static void Notify_CombatDangerousBuildingDespawned(Building building, Map map) { - foreach (Faction current in Find.FactionManager.AllFactions) + foreach (Faction allFaction in Find.FactionManager.AllFactions) { - if (current.HostileTo(Faction.OfPlayer) && map.mapPawns.SpawnedPawnsInFaction(current).Count > 0) + if (allFaction.HostileTo(Faction.OfPlayer) && map.mapPawns.SpawnedPawnsInFaction(allFaction).Count > 0) { - AvoidGridMaker.RegenerateAvoidGridsFor(current, map); + AvoidGridMaker.RegenerateAvoidGridsFor(allFaction, map); } } } @@ -101,7 +98,7 @@ private static void PrintAvoidGridAroundTrapLoc(TrapMemory mem, ByteGrid avoidGr if (intVec.InBounds(mem.map) && intVec.Walkable(mem.map) && intVec.GetRoom(mem.map, RegionType.Set_Passable) == room) { float num = (float)Mathf.Max(1, intVec.DistanceToSquared(mem.Cell)); - int num2 = Mathf.Max(1, Mathf.RoundToInt(32f * mem.PowerPercent / num)); + int num2 = Mathf.Max(1, Mathf.RoundToInt((float)(32.0 * mem.PowerPercent / num))); AvoidGridMaker.IncrementAvoidGrid(avoidGrid, intVec, num2); } } @@ -109,10 +106,10 @@ private static void PrintAvoidGridAroundTrapLoc(TrapMemory mem, ByteGrid avoidGr private static void PrintAvoidGridAroundTurret(Building_TurretGun tur, ByteGrid avoidGrid) { - int num = GenRadial.NumCellsInRadius(tur.GunCompEq.PrimaryVerb.verbProps.range + 4f); - for (int i = 0; i < num; i++) + int num = GenRadial.NumCellsInRadius((float)(tur.GunCompEq.PrimaryVerb.verbProps.range + 4.0)); + for (int num2 = 0; num2 < num; num2++) { - IntVec3 intVec = tur.Position + GenRadial.RadialPattern[i]; + IntVec3 intVec = tur.Position + GenRadial.RadialPattern[num2]; if (intVec.InBounds(tur.Map) && intVec.Walkable(tur.Map) && GenSight.LineOfSight(intVec, tur.Position, tur.Map, true, null, 0, 0)) { AvoidGridMaker.IncrementAvoidGrid(avoidGrid, intVec, 12); @@ -123,28 +120,26 @@ private static void PrintAvoidGridAroundTurret(Building_TurretGun tur, ByteGrid private static void IncrementAvoidGrid(ByteGrid avoidGrid, IntVec3 c, int num) { byte b = avoidGrid[c]; - b = (byte)Mathf.Min(255, (int)b + num); + b = (byte)Mathf.Min(255, b + num); avoidGrid[c] = b; } private static void ExpandAvoidGridIntoEdifices(ByteGrid avoidGrid, Map map) { int numGridCells = map.cellIndices.NumGridCells; - for (int i = 0; i < numGridCells; i++) + for (int num = 0; num < numGridCells; num++) { - if (avoidGrid[i] != 0) + if (avoidGrid[num] != 0 && map.edificeGrid[num] == null) { - if (map.edificeGrid[i] == null) + for (int i = 0; i < 8; i++) { - for (int j = 0; j < 8; j++) + IntVec3 c = map.cellIndices.IndexToCell(num) + GenAdj.AdjacentCells[i]; + if (c.InBounds(map)) { - IntVec3 c = map.cellIndices.IndexToCell(i) + GenAdj.AdjacentCells[j]; - if (c.InBounds(map)) + Building edifice = c.GetEdifice(map); + if (edifice != null) { - if (c.GetEdifice(map) != null) - { - avoidGrid[c] = (byte)Mathf.Min(255, Mathf.Max((int)avoidGrid[c], (int)avoidGrid[i])); - } + avoidGrid[c] = (byte)Mathf.Min(255, Mathf.Max(avoidGrid[c], avoidGrid[num])); } } } diff --git a/Assembly-CSharp/Verse.AI/AvoidGridTunings.cs b/Assembly-CSharp/Verse.AI/AvoidGridTunings.cs index 0e9ab833d..6ba2b32e1 100644 --- a/Assembly-CSharp/Verse.AI/AvoidGridTunings.cs +++ b/Assembly-CSharp/Verse.AI/AvoidGridTunings.cs @@ -1,5 +1,3 @@ -using System; - namespace Verse.AI { public static class AvoidGridTunings diff --git a/Assembly-CSharp/Verse.AI/CastPositionFinder.cs b/Assembly-CSharp/Verse.AI/CastPositionFinder.cs index 5810a11b9..e5a535427 100644 --- a/Assembly-CSharp/Verse.AI/CastPositionFinder.cs +++ b/Assembly-CSharp/Verse.AI/CastPositionFinder.cs @@ -1,5 +1,4 @@ using RimWorld; -using System; using System.Collections.Generic; using UnityEngine; @@ -71,7 +70,7 @@ public static bool TryFindCastPosition(CastPositionRequest newReq, out IntVec3 d } CastPositionFinder.inRadiusMark = Rand.Int; RegionTraverser.MarkRegionsBFS(region, null, newReq.maxRegionsRadius, CastPositionFinder.inRadiusMark, RegionType.Set_Passable); - if (CastPositionFinder.req.maxRangeFromLocus > 0.01f) + if (CastPositionFinder.req.maxRangeFromLocus > 0.0099999997764825821) { Region region2 = CastPositionFinder.req.locus.GetRegion(CastPositionFinder.req.caster.Map, RegionType.Set_Passable); if (region2 == null) @@ -82,21 +81,13 @@ public static bool TryFindCastPosition(CastPositionRequest newReq, out IntVec3 d } if (region2.mark != CastPositionFinder.inRadiusMark) { - Log.Error(string.Concat(new object[] - { - CastPositionFinder.req.caster, - " can't possibly get to locus ", - CastPositionFinder.req.locus, - " as it's not in a maxRegionsRadius of ", - CastPositionFinder.req.maxRegionsRadius, - ". Overriding maxRegionsRadius." - })); + Log.Error(CastPositionFinder.req.caster + " can't possibly get to locus " + CastPositionFinder.req.locus + " as it's not in a maxRegionsRadius of " + CastPositionFinder.req.maxRegionsRadius + ". Overriding maxRegionsRadius."); CastPositionFinder.req.maxRegionsRadius = 0; } } } CellRect cellRect = CellRect.WholeMap(CastPositionFinder.req.caster.Map); - if (CastPositionFinder.req.maxRangeFromCaster > 0.01f) + if (CastPositionFinder.req.maxRangeFromCaster > 0.0099999997764825821) { int num = Mathf.CeilToInt(CastPositionFinder.req.maxRangeFromCaster); CellRect otherRect = new CellRect(CastPositionFinder.casterLoc.x - num, CastPositionFinder.casterLoc.z - num, num * 2 + 1, num * 2 + 1); @@ -105,7 +96,7 @@ public static bool TryFindCastPosition(CastPositionRequest newReq, out IntVec3 d int num2 = Mathf.CeilToInt(CastPositionFinder.req.maxRangeFromTarget); CellRect otherRect2 = new CellRect(CastPositionFinder.targetLoc.x - num2, CastPositionFinder.targetLoc.z - num2, num2 * 2 + 1, num2 * 2 + 1); cellRect.ClipInsideRect(otherRect2); - if (CastPositionFinder.req.maxRangeFromLocus > 0.01f) + if (CastPositionFinder.req.maxRangeFromLocus > 0.0099999997764825821) { int num3 = Mathf.CeilToInt(CastPositionFinder.req.maxRangeFromLocus); CellRect otherRect3 = new CellRect(CastPositionFinder.targetLoc.x - num3, CastPositionFinder.targetLoc.z - num3, num3 * 2 + 1, num3 * 2 + 1); @@ -118,14 +109,14 @@ public static bool TryFindCastPosition(CastPositionRequest newReq, out IntVec3 d CastPositionFinder.maxRangeFromLocusSquared = CastPositionFinder.req.maxRangeFromLocus * CastPositionFinder.req.maxRangeFromLocus; CastPositionFinder.rangeFromTarget = (CastPositionFinder.req.caster.Position - CastPositionFinder.req.target.Position).LengthHorizontal; CastPositionFinder.rangeFromTargetSquared = (float)(CastPositionFinder.req.caster.Position - CastPositionFinder.req.target.Position).LengthHorizontalSquared; - CastPositionFinder.optimalRangeSquared = CastPositionFinder.verb.verbProps.range * 0.8f * (CastPositionFinder.verb.verbProps.range * 0.8f); + CastPositionFinder.optimalRangeSquared = (float)(CastPositionFinder.verb.verbProps.range * 0.800000011920929 * (CastPositionFinder.verb.verbProps.range * 0.800000011920929)); CastPositionFinder.EvaluateCell(CastPositionFinder.req.caster.Position); if ((double)CastPositionFinder.bestSpotPref >= 1.0) { dest = CastPositionFinder.req.caster.Position; return true; } - float slope = -1f / CellLine.Between(CastPositionFinder.req.target.Position, CastPositionFinder.req.caster.Position).Slope; + float slope = (float)(-1.0 / CellLine.Between(CastPositionFinder.req.target.Position, CastPositionFinder.req.caster.Position).Slope); CellLine cellLine = new CellLine(CastPositionFinder.req.target.Position, slope); bool flag = cellLine.CellIsAbove(CastPositionFinder.req.caster.Position); CellRect.CellRectIterator iterator = cellRect.GetIterator(); @@ -138,7 +129,7 @@ public static bool TryFindCastPosition(CastPositionRequest newReq, out IntVec3 d } iterator.MoveNext(); } - if (CastPositionFinder.bestSpot.IsValid && CastPositionFinder.bestSpotPref > 0.33f) + if (CastPositionFinder.bestSpot.IsValid && CastPositionFinder.bestSpotPref > 0.33000001311302185) { dest = CastPositionFinder.bestSpot; return true; @@ -164,94 +155,94 @@ public static bool TryFindCastPosition(CastPositionRequest newReq, out IntVec3 d private static void EvaluateCell(IntVec3 c) { - if (CastPositionFinder.maxRangeFromTargetSquared > 0.01f && CastPositionFinder.maxRangeFromTargetSquared < 250000f && (float)(c - CastPositionFinder.req.target.Position).LengthHorizontalSquared > CastPositionFinder.maxRangeFromTargetSquared) + if (CastPositionFinder.maxRangeFromTargetSquared > 0.0099999997764825821 && CastPositionFinder.maxRangeFromTargetSquared < 250000.0 && (float)(c - CastPositionFinder.req.target.Position).LengthHorizontalSquared > CastPositionFinder.maxRangeFromTargetSquared) { if (DebugViewSettings.drawCastPositionSearch) { CastPositionFinder.req.caster.Map.debugDrawer.FlashCell(c, 0f, "range target"); } - return; } - if ((double)CastPositionFinder.maxRangeFromLocusSquared > 0.01 && (float)(c - CastPositionFinder.req.locus).LengthHorizontalSquared > CastPositionFinder.maxRangeFromLocusSquared) + else if ((double)CastPositionFinder.maxRangeFromLocusSquared > 0.01 && (float)(c - CastPositionFinder.req.locus).LengthHorizontalSquared > CastPositionFinder.maxRangeFromLocusSquared) { if (DebugViewSettings.drawCastPositionSearch) { CastPositionFinder.req.caster.Map.debugDrawer.FlashCell(c, 0.1f, "range home"); } - return; } - if (CastPositionFinder.maxRangeFromCasterSquared > 0.01f) + else { - CastPositionFinder.rangeFromCasterToCellSquared = (float)(c - CastPositionFinder.req.caster.Position).LengthHorizontalSquared; - if (CastPositionFinder.rangeFromCasterToCellSquared > CastPositionFinder.maxRangeFromCasterSquared) + if (CastPositionFinder.maxRangeFromCasterSquared > 0.0099999997764825821) { - if (DebugViewSettings.drawCastPositionSearch) + CastPositionFinder.rangeFromCasterToCellSquared = (float)(c - CastPositionFinder.req.caster.Position).LengthHorizontalSquared; + if (CastPositionFinder.rangeFromCasterToCellSquared > CastPositionFinder.maxRangeFromCasterSquared) { - CastPositionFinder.req.caster.Map.debugDrawer.FlashCell(c, 0.2f, "range caster"); + if (DebugViewSettings.drawCastPositionSearch) + { + CastPositionFinder.req.caster.Map.debugDrawer.FlashCell(c, 0.2f, "range caster"); + } + return; } - return; - } - } - if (!c.Walkable(CastPositionFinder.req.caster.Map)) - { - return; - } - if (CastPositionFinder.req.maxRegionsRadius > 0 && c.GetRegion(CastPositionFinder.req.caster.Map, RegionType.Set_Passable).mark != CastPositionFinder.inRadiusMark) - { - if (DebugViewSettings.drawCastPositionSearch) - { - CastPositionFinder.req.caster.Map.debugDrawer.FlashCell(c, 0.64f, "reg radius"); - } - return; - } - if (!CastPositionFinder.req.caster.Map.reachability.CanReach(CastPositionFinder.req.caster.Position, c, PathEndMode.OnCell, TraverseParms.For(CastPositionFinder.req.caster, Danger.Some, TraverseMode.ByPawn, false))) - { - if (DebugViewSettings.drawCastPositionSearch) - { - CastPositionFinder.req.caster.Map.debugDrawer.FlashCell(c, 0.4f, "can't reach"); - } - return; - } - float num = CastPositionFinder.CastPositionPreference(c); - if (CastPositionFinder.avoidGrid != null) - { - byte b = CastPositionFinder.avoidGrid[c]; - num *= Mathf.Max(0.1f, (37.5f - (float)b) / 37.5f); - } - if (DebugViewSettings.drawCastPositionSearch) - { - CastPositionFinder.req.caster.Map.debugDrawer.FlashCell(c, num / 4f, num.ToString("F3")); - } - if (num < CastPositionFinder.bestSpotPref) - { - return; - } - if (!CastPositionFinder.verb.CanHitTargetFrom(c, CastPositionFinder.req.target)) - { - if (DebugViewSettings.drawCastPositionSearch) - { - CastPositionFinder.req.caster.Map.debugDrawer.FlashCell(c, 0.6f, "can't hit"); } - return; - } - if (CastPositionFinder.req.caster.Map.pawnDestinationManager.DestinationIsReserved(c, CastPositionFinder.req.caster)) - { - if (DebugViewSettings.drawCastPositionSearch) - { - CastPositionFinder.req.caster.Map.debugDrawer.FlashCell(c, num * 0.9f, "resvd"); - } - return; - } - if (PawnUtility.KnownDangerAt(c, CastPositionFinder.req.caster)) - { - if (DebugViewSettings.drawCastPositionSearch) + if (c.Walkable(CastPositionFinder.req.caster.Map)) { - CastPositionFinder.req.caster.Map.debugDrawer.FlashCell(c, 0.9f, "danger"); + if (CastPositionFinder.req.maxRegionsRadius > 0 && c.GetRegion(CastPositionFinder.req.caster.Map, RegionType.Set_Passable).mark != CastPositionFinder.inRadiusMark) + { + if (DebugViewSettings.drawCastPositionSearch) + { + CastPositionFinder.req.caster.Map.debugDrawer.FlashCell(c, 0.64f, "reg radius"); + } + } + else if (!CastPositionFinder.req.caster.Map.reachability.CanReach(CastPositionFinder.req.caster.Position, c, PathEndMode.OnCell, TraverseParms.For(CastPositionFinder.req.caster, Danger.Some, TraverseMode.ByPawn, false))) + { + if (DebugViewSettings.drawCastPositionSearch) + { + CastPositionFinder.req.caster.Map.debugDrawer.FlashCell(c, 0.4f, "can't reach"); + } + } + else + { + float num = CastPositionFinder.CastPositionPreference(c); + if (CastPositionFinder.avoidGrid != null) + { + byte b = CastPositionFinder.avoidGrid[c]; + num *= Mathf.Max(0.1f, (float)((37.5 - (float)(int)b) / 37.5)); + } + if (DebugViewSettings.drawCastPositionSearch) + { + CastPositionFinder.req.caster.Map.debugDrawer.FlashCell(c, (float)(num / 4.0), num.ToString("F3")); + } + if (!(num < CastPositionFinder.bestSpotPref)) + { + if (!CastPositionFinder.verb.CanHitTargetFrom(c, CastPositionFinder.req.target)) + { + if (DebugViewSettings.drawCastPositionSearch) + { + CastPositionFinder.req.caster.Map.debugDrawer.FlashCell(c, 0.6f, "can't hit"); + } + } + else if (CastPositionFinder.req.caster.Map.pawnDestinationManager.DestinationIsReserved(c, CastPositionFinder.req.caster)) + { + if (DebugViewSettings.drawCastPositionSearch) + { + CastPositionFinder.req.caster.Map.debugDrawer.FlashCell(c, (float)(num * 0.89999997615814209), "resvd"); + } + } + else if (PawnUtility.KnownDangerAt(c, CastPositionFinder.req.caster)) + { + if (DebugViewSettings.drawCastPositionSearch) + { + CastPositionFinder.req.caster.Map.debugDrawer.FlashCell(c, 0.9f, "danger"); + } + } + else + { + CastPositionFinder.bestSpot = c; + CastPositionFinder.bestSpotPref = num; + } + } + } } - return; } - CastPositionFinder.bestSpot = c; - CastPositionFinder.bestSpotPref = num; } private static float CastPositionPreference(IntVec3 c) @@ -274,17 +265,17 @@ private static float CastPositionPreference(IntVec3 c) float num = 0.3f; if (CastPositionFinder.req.caster.kindDef.aiAvoidCover) { - num += 8f - CoverUtility.TotalSurroundingCoverScore(c, CastPositionFinder.req.caster.Map); + num = (float)(num + (8.0 - CoverUtility.TotalSurroundingCoverScore(c, CastPositionFinder.req.caster.Map))); } if (CastPositionFinder.req.wantCoverFromTarget) { num += CoverUtility.CalculateOverallBlockChance(c, CastPositionFinder.req.target.Position, CastPositionFinder.req.caster.Map); } float num2 = (CastPositionFinder.req.caster.Position - c).LengthHorizontal; - if (CastPositionFinder.rangeFromTarget > 100f) + if (CastPositionFinder.rangeFromTarget > 100.0) { - num2 -= CastPositionFinder.rangeFromTarget - 100f; - if (num2 < 0f) + num2 = (float)(num2 - (CastPositionFinder.rangeFromTarget - 100.0)); + if (num2 < 0.0) { num2 = 0f; } @@ -293,21 +284,21 @@ private static float CastPositionPreference(IntVec3 c) float num3 = 1f; CastPositionFinder.rangeFromTargetToCellSquared = (float)(c - CastPositionFinder.req.target.Position).LengthHorizontalSquared; float num4 = Mathf.Abs(CastPositionFinder.rangeFromTargetToCellSquared - CastPositionFinder.optimalRangeSquared) / CastPositionFinder.optimalRangeSquared; - num4 = 1f - num4; - num4 = 0.7f + 0.3f * num4; + num4 = (float)(1.0 - num4); + num4 = (float)(0.699999988079071 + 0.30000001192092896 * num4); num3 *= num4; - if (CastPositionFinder.rangeFromTargetToCellSquared < 25f) + if (CastPositionFinder.rangeFromTargetToCellSquared < 25.0) { - num3 *= 0.5f; + num3 = (float)(num3 * 0.5); } num *= num3; if (CastPositionFinder.rangeFromCasterToCellSquared > CastPositionFinder.rangeFromTargetSquared) { - num *= 0.4f; + num = (float)(num * 0.40000000596046448); } if (!flag) { - num *= 0.2f; + num = (float)(num * 0.20000000298023224); } return num; } diff --git a/Assembly-CSharp/Verse.AI/CastPositionRequest.cs b/Assembly-CSharp/Verse.AI/CastPositionRequest.cs index eb8a5cf80..b3e257a48 100644 --- a/Assembly-CSharp/Verse.AI/CastPositionRequest.cs +++ b/Assembly-CSharp/Verse.AI/CastPositionRequest.cs @@ -1,5 +1,3 @@ -using System; - namespace Verse.AI { public struct CastPositionRequest diff --git a/Assembly-CSharp/Verse.AI/DutyDef.cs b/Assembly-CSharp/Verse.AI/DutyDef.cs index 1c981e4df..b2817c3b6 100644 --- a/Assembly-CSharp/Verse.AI/DutyDef.cs +++ b/Assembly-CSharp/Verse.AI/DutyDef.cs @@ -1,5 +1,4 @@ using RimWorld; -using System; namespace Verse.AI { diff --git a/Assembly-CSharp/Verse.AI/GenAI.cs b/Assembly-CSharp/Verse.AI/GenAI.cs index f49d049e6..07e4d228e 100644 --- a/Assembly-CSharp/Verse.AI/GenAI.cs +++ b/Assembly-CSharp/Verse.AI/GenAI.cs @@ -9,38 +9,74 @@ public static class GenAI { public static bool CanInteractPawn(Pawn assister, Pawn assistee) { - return assistee.Spawned && assister.CanReach(assistee, PathEndMode.OnCell, Danger.Deadly, false, TraverseMode.ByPawn); + if (assistee.Spawned && assister.CanReach((Thing)assistee, PathEndMode.OnCell, Danger.Deadly, false, TraverseMode.ByPawn)) + { + return true; + } + return false; } public static bool MachinesLike(Faction machineFaction, Pawn p) { - return p.Faction != null && (!p.IsPrisoner || p.HostFaction != machineFaction) && !p.Faction.HostileTo(machineFaction); + if (p.Faction == null) + { + return false; + } + if (p.IsPrisoner && p.HostFaction == machineFaction) + { + return false; + } + if (p.Faction.HostileTo(machineFaction)) + { + return false; + } + return true; } public static bool CanUseItemForWork(Pawn p, Thing item) { - return !item.IsForbidden(p) && p.CanReserveAndReach(item, PathEndMode.ClosestTouch, p.NormalMaxDanger(), 1, -1, null, false); + if (item.IsForbidden(p)) + { + return false; + } + if (!p.CanReserveAndReach(item, PathEndMode.ClosestTouch, p.NormalMaxDanger(), 1, -1, null, false)) + { + return false; + } + return true; } public static bool CanBeArrested(this Pawn pawn) { - return pawn.RaceProps.Humanlike && !pawn.InAggroMentalState && !pawn.HostileTo(Faction.OfPlayer) && (!pawn.IsPrisonerOfColony || !pawn.Position.IsInPrisonCell(pawn.Map)); + if (!pawn.RaceProps.Humanlike) + { + return false; + } + if (!pawn.InAggroMentalState && !pawn.HostileTo(Faction.OfPlayer)) + { + if (pawn.IsPrisonerOfColony && pawn.Position.IsInPrisonCell(pawn.Map)) + { + return false; + } + return true; + } + return false; } public static bool InDangerousCombat(Pawn pawn) { Region root = pawn.GetRegion(RegionType.Set_Passable); bool found = false; - RegionTraverser.BreadthFirstTraverse(root, (Region r1, Region r2) => r2.Room == root.Room, (Region r) => r.ListerThings.ThingsInGroup(ThingRequestGroup.Pawn).Any(delegate(Thing t) + RegionTraverser.BreadthFirstTraverse(root, (RegionEntryPredicate)((Region r1, Region r2) => r2.Room == root.Room), (RegionProcessor)((Region r) => r.ListerThings.ThingsInGroup(ThingRequestGroup.Pawn).Any((Predicate)delegate(Thing t) { Pawn pawn2 = t as Pawn; - if (pawn2 != null && !pawn2.Downed && (float)(pawn.Position - pawn2.Position).LengthHorizontalSquared < 144f && pawn2.HostileTo(pawn.Faction)) + if (pawn2 != null && !pawn2.Downed && (float)(pawn.Position - pawn2.Position).LengthHorizontalSquared < 144.0 && pawn2.HostileTo(pawn.Faction)) { - found = true; + bool found2 = true; return true; } return false; - }), 9, RegionType.Set_Passable); + })), 9, RegionType.Set_Passable); return found; } @@ -50,27 +86,27 @@ public static IntVec3 RandomRaidDest(IntVec3 raidSpawnLoc, Map map) List list = new List(map.mapPawns.FreeColonistsAndPrisonersSpawnedCount); for (int i = 0; i < allBedDefBestToWorst.Count; i++) { - foreach (Building current in map.listerBuildings.AllBuildingsColonistOfDef(allBedDefBestToWorst[i])) + foreach (Building item in map.listerBuildings.AllBuildingsColonistOfDef(allBedDefBestToWorst[i])) { - if (((Building_Bed)current).owners.Any() && map.reachability.CanReach(raidSpawnLoc, current, PathEndMode.OnCell, TraverseMode.PassAllDestroyableThings, Danger.Deadly)) + if (((Building_Bed)item).owners.Any() && map.reachability.CanReach(raidSpawnLoc, (Thing)item, PathEndMode.OnCell, TraverseMode.PassAllDestroyableThings, Danger.Deadly)) { - list.Add(current); + list.Add(item); } } } - Building building; - if (list.TryRandomElement(out building)) + Building building = default(Building); + if (((IEnumerable)list).TryRandomElement(out building)) { return building.Position; } IEnumerable source = from b in map.listerBuildings.allBuildingsColonist where !b.def.building.ai_combatDangerous && !b.def.building.isInert select b; - if (source.Any()) + if (source.Any()) { for (int j = 0; j < 500; j++) { - Building t = source.RandomElement(); + Building t = source.RandomElement(); IntVec3 intVec = t.RandomAdjacentCell8Way(); if (intVec.Walkable(map) && map.reachability.CanReach(raidSpawnLoc, intVec, PathEndMode.OnCell, TraverseMode.PassAllDestroyableThings, Danger.Deadly)) { @@ -78,15 +114,15 @@ public static IntVec3 RandomRaidDest(IntVec3 raidSpawnLoc, Map map) } } } - Pawn pawn; + Pawn pawn = default(Pawn); if ((from x in map.mapPawns.FreeColonistsSpawned - where map.reachability.CanReach(raidSpawnLoc, x, PathEndMode.OnCell, TraverseMode.PassAllDestroyableThings, Danger.Deadly) - select x).TryRandomElement(out pawn)) + where map.reachability.CanReach(raidSpawnLoc, (Thing)x, PathEndMode.OnCell, TraverseMode.PassAllDestroyableThings, Danger.Deadly) + select x).TryRandomElement(out pawn)) { return pawn.Position; } - IntVec3 result; - if (CellFinderLoose.TryGetRandomCellWith((IntVec3 x) => map.reachability.CanReach(raidSpawnLoc, x, PathEndMode.OnCell, TraverseMode.PassAllDestroyableThings, Danger.Deadly), map, 1000, out result)) + IntVec3 result = default(IntVec3); + if (CellFinderLoose.TryGetRandomCellWith((Predicate)((IntVec3 x) => map.reachability.CanReach(raidSpawnLoc, x, PathEndMode.OnCell, TraverseMode.PassAllDestroyableThings, Danger.Deadly)), map, 1000, out result)) { return result; } @@ -103,12 +139,9 @@ public static bool EnemyIsNear(Pawn p, float radius) for (int i = 0; i < potentialTargetsFor.Count; i++) { IAttackTarget attackTarget = potentialTargetsFor[i]; - if (!attackTarget.ThreatDisabled()) + if (!attackTarget.ThreatDisabled() && p.Position.InHorDistOf(((Thing)attackTarget).Position, radius)) { - if (p.Position.InHorDistOf(((Thing)attackTarget).Position, radius)) - { - return true; - } + return true; } } return false; diff --git a/Assembly-CSharp/Verse.AI/GenPath.cs b/Assembly-CSharp/Verse.AI/GenPath.cs index dfd6036c8..e0a3bc0fe 100644 --- a/Assembly-CSharp/Verse.AI/GenPath.cs +++ b/Assembly-CSharp/Verse.AI/GenPath.cs @@ -1,5 +1,4 @@ using RimWorld; -using System; namespace Verse.AI { diff --git a/Assembly-CSharp/Verse.AI/HaulAIUtility.cs b/Assembly-CSharp/Verse.AI/HaulAIUtility.cs index d72b9d31b..b47a2e6e1 100644 --- a/Assembly-CSharp/Verse.AI/HaulAIUtility.cs +++ b/Assembly-CSharp/Verse.AI/HaulAIUtility.cs @@ -46,7 +46,15 @@ public static bool PawnCanAutomaticallyHaul(Pawn p, Thing t, bool forced) } return false; } - return (t.def.alwaysHaulable || t.Map.designationManager.DesignationOn(t, DesignationDefOf.Haul) != null || t.IsInValidStorage()) && HaulAIUtility.PawnCanAutomaticallyHaulBasicChecks(p, t, forced); + if (!t.def.alwaysHaulable && t.Map.designationManager.DesignationOn(t, DesignationDefOf.Haul) == null && !t.IsInValidStorage()) + { + return false; + } + if (!HaulAIUtility.PawnCanAutomaticallyHaulBasicChecks(p, t, forced)) + { + return false; + } + return true; } public static bool PawnCanAutomaticallyHaulFast(Pawn p, Thing t, bool forced) @@ -85,7 +93,7 @@ private static bool PawnCanAutomaticallyHaulBasicChecks(Pawn p, Thing t, bool fo public static Job HaulToStorageJob(Pawn p, Thing t) { StoragePriority currentPriority = HaulAIUtility.StoragePriorityAtFor(t.Position, t); - IntVec3 storeCell; + IntVec3 storeCell = default(IntVec3); if (!StoreUtility.TryFindBestBetterStoreCellFor(t, p, p.Map, currentPriority, p.Faction, out storeCell, true)) { JobFailReason.Is(HaulAIUtility.NoEmptyPlaceLowerTrans); @@ -121,18 +129,11 @@ public static Job HaulMaxNumToCellJob(Pawn p, Thing t, IntVec3 storeCell, bool f if (StoreUtility.IsGoodStoreCell(cellsList[i], p.Map, t, p, p.Faction)) { Thing thing2 = p.Map.thingGrid.ThingAt(cellsList[i], t.def); - if (thing2 != null && thing2 != t) - { - num += Mathf.Max(t.def.stackLimit - thing2.stackCount, 0); - } - else - { - num += t.def.stackLimit; - } - if (num >= job.count || (float)num >= statValue) - { + num = ((thing2 == null || thing2 == t) ? (num + t.def.stackLimit) : (num + Mathf.Max(t.def.stackLimit - thing2.stackCount, 0))); + if (num >= job.count) + break; + if ((float)num >= statValue) break; - } } } job.count = Mathf.Min(job.count, num); @@ -153,33 +154,48 @@ public static StoragePriority StoragePriorityAtFor(IntVec3 c, Thing t) return StoragePriority.Unstored; } SlotGroup slotGroup = t.Map.slotGroupManager.SlotGroupAt(c); - if (slotGroup == null || !slotGroup.Settings.AllowedToAccept(t)) + if (slotGroup != null && slotGroup.Settings.AllowedToAccept(t)) { - return StoragePriority.Unstored; + return slotGroup.Settings.Priority; } - return slotGroup.Settings.Priority; + return StoragePriority.Unstored; } public static bool CanHaulAside(Pawn p, Thing t, out IntVec3 storeCell) { storeCell = IntVec3.Invalid; - return t.def.EverHaulable && !t.IsBurning() && p.CanReserveAndReach(t, PathEndMode.ClosestTouch, p.NormalMaxDanger(), 1, -1, null, false) && HaulAIUtility.TryFindSpotToPlaceHaulableCloseTo(t, p, t.PositionHeld, out storeCell); + if (!t.def.EverHaulable) + { + return false; + } + if (t.IsBurning()) + { + return false; + } + if (!p.CanReserveAndReach(t, PathEndMode.ClosestTouch, p.NormalMaxDanger(), 1, -1, null, false)) + { + return false; + } + if (!HaulAIUtility.TryFindSpotToPlaceHaulableCloseTo(t, p, t.PositionHeld, out storeCell)) + { + return false; + } + return true; } public static Job HaulAsideJobFor(Pawn p, Thing t) { - IntVec3 c; + IntVec3 c = default(IntVec3); if (!HaulAIUtility.CanHaulAside(p, t, out c)) { return null; } - return new Job(JobDefOf.HaulToCell, t, c) - { - count = 99999, - haulOpportunisticDuplicates = false, - haulMode = HaulMode.ToCellNonStorage, - ignoreDesignations = true - }; + Job job = new Job(JobDefOf.HaulToCell, t, c); + job.count = 99999; + job.haulOpportunisticDuplicates = false; + job.haulMode = HaulMode.ToCellNonStorage; + job.ignoreDesignations = true; + return job; } private static bool TryFindSpotToPlaceHaulableCloseTo(Thing haulable, Pawn worker, IntVec3 center, out IntVec3 spot) @@ -192,17 +208,17 @@ private static bool TryFindSpotToPlaceHaulableCloseTo(Thing haulable, Pawn worke } TraverseParms traverseParms = TraverseParms.For(worker, Danger.Deadly, TraverseMode.ByPawn, false); IntVec3 foundCell = IntVec3.Invalid; - RegionTraverser.BreadthFirstTraverse(region, (Region from, Region r) => r.Allows(traverseParms, false), delegate(Region r) + RegionTraverser.BreadthFirstTraverse(region, (RegionEntryPredicate)((Region from, Region r) => r.Allows(traverseParms, false)), (RegionProcessor)delegate(Region r) { HaulAIUtility.candidates.Clear(); HaulAIUtility.candidates.AddRange(r.Cells); - HaulAIUtility.candidates.Sort((IntVec3 a, IntVec3 b) => a.DistanceToSquared(center).CompareTo(b.DistanceToSquared(center))); + HaulAIUtility.candidates.Sort((Comparison)((IntVec3 a, IntVec3 b) => a.DistanceToSquared(center).CompareTo(b.DistanceToSquared(center)))); for (int i = 0; i < HaulAIUtility.candidates.Count; i++) { IntVec3 intVec = HaulAIUtility.candidates[i]; if (HaulAIUtility.HaulablePlaceValidator(haulable, worker, intVec)) { - foundCell = intVec; + IntVec3 foundCell2 = intVec; return true; } } @@ -247,7 +263,7 @@ private static bool HaulablePlaceValidator(Thing haulable, Pawn worker, IntVec3 return false; } } - if (haulable.def.passability != Traversability.Standable) + if (haulable.def.passability != 0) { for (int i = 0; i < 8; i++) { diff --git a/Assembly-CSharp/Verse.AI/HaulMode.cs b/Assembly-CSharp/Verse.AI/HaulMode.cs index ca0ef6e5c..3b3416c4c 100644 --- a/Assembly-CSharp/Verse.AI/HaulMode.cs +++ b/Assembly-CSharp/Verse.AI/HaulMode.cs @@ -1,12 +1,10 @@ -using System; - namespace Verse.AI { public enum HaulMode : byte { - Undefined, - ToCellStorage, - ToCellNonStorage, - ToContainer + Undefined = 0, + ToCellStorage = 1, + ToCellNonStorage = 2, + ToContainer = 3 } } diff --git a/Assembly-CSharp/Verse.AI/IAttackTarget.cs b/Assembly-CSharp/Verse.AI/IAttackTarget.cs index 52c898b68..a3671ae4d 100644 --- a/Assembly-CSharp/Verse.AI/IAttackTarget.cs +++ b/Assembly-CSharp/Verse.AI/IAttackTarget.cs @@ -1,5 +1,3 @@ -using System; - namespace Verse.AI { public interface IAttackTarget : ILoadReferenceable diff --git a/Assembly-CSharp/Verse.AI/IAttackTargetSearcher.cs b/Assembly-CSharp/Verse.AI/IAttackTargetSearcher.cs index eb0b1c9fc..e6f9e336d 100644 --- a/Assembly-CSharp/Verse.AI/IAttackTargetSearcher.cs +++ b/Assembly-CSharp/Verse.AI/IAttackTargetSearcher.cs @@ -1,5 +1,3 @@ -using System; - namespace Verse.AI { public interface IAttackTargetSearcher diff --git a/Assembly-CSharp/Verse.AI/Job.cs b/Assembly-CSharp/Verse.AI/Job.cs index 845dc9157..92525df49 100644 --- a/Assembly-CSharp/Verse.AI/Job.cs +++ b/Assembly-CSharp/Verse.AI/Job.cs @@ -93,11 +93,11 @@ public Job() { } - public Job(JobDef def) : this(def, null) + public Job(JobDef def) : this(def, (Thing)null) { } - public Job(JobDef def, LocalTargetInfo targetA) : this(def, targetA, null) + public Job(JobDef def, LocalTargetInfo targetA) : this(def, targetA, (Thing)null) { } @@ -136,19 +136,29 @@ public LocalTargetInfo GetTarget(TargetIndex ind) switch (ind) { case TargetIndex.A: + { return this.targetA; + } case TargetIndex.B: + { return this.targetB; + } case TargetIndex.C: + { return this.targetC; + } default: + { throw new ArgumentException(); } + } } public List GetTargetQueue(TargetIndex ind) { - if (ind == TargetIndex.A) + switch (ind) + { + case TargetIndex.A: { if (this.targetQueueA == null) { @@ -156,15 +166,19 @@ public List GetTargetQueue(TargetIndex ind) } return this.targetQueueA; } - if (ind != TargetIndex.B) + case TargetIndex.B: { - throw new ArgumentException(); + if (this.targetQueueB == null) + { + this.targetQueueB = new List(); + } + return this.targetQueueB; } - if (this.targetQueueB == null) + default: { - this.targetQueueB = new List(); + throw new ArgumentException(); + } } - return this.targetQueueB; } public void SetTarget(TargetIndex ind, LocalTargetInfo pack) @@ -172,17 +186,25 @@ public void SetTarget(TargetIndex ind, LocalTargetInfo pack) switch (ind) { case TargetIndex.A: + { this.targetA = pack; - return; + break; + } case TargetIndex.B: + { this.targetB = pack; - return; + break; + } case TargetIndex.C: + { this.targetC = pack; - return; + break; + } default: + { throw new ArgumentException(); } + } } public void AddQueuedTarget(TargetIndex ind, LocalTargetInfo target) @@ -193,7 +215,7 @@ public void AddQueuedTarget(TargetIndex ind, LocalTargetInfo target) public void ExposeData() { ILoadReferenceable loadReferenceable = (ILoadReferenceable)this.commTarget; - Scribe_References.Look(ref loadReferenceable, "commTarget", false); + Scribe_References.Look(ref loadReferenceable, "commTarget", false); this.commTarget = (ICommunicable)loadReferenceable; Scribe_References.Look(ref this.verbToUse, "verbToUse", false); Scribe_References.Look(ref this.bill, "bill", false); @@ -241,29 +263,41 @@ public JobDriver MakeDriver(Pawn driverPawn) public bool CanBeginNow(Pawn pawn) { - if (!pawn.Downed) + if (pawn.Downed) { - return true; + if (this.def != JobDefOf.LayDown) + { + return false; + } + if (this.targetA.HasThing) + { + return RestUtility.GetBedSleepingSlotPosFor(pawn, (Building_Bed)this.targetA.Thing) == pawn.Position; + } + return this.targetA.Cell == pawn.Position; } - if (this.def != JobDefOf.LayDown) + return true; + } + + public bool JobIsSameAs(Job other) + { + if (other == null) { return false; } - if (this.targetA.HasThing) + if (this.def == other.def && !(this.targetA != other.targetA) && !(this.targetB != other.targetB) && this.verbToUse == other.verbToUse && !(this.targetC != other.targetC) && this.commTarget == other.commTarget && this.bill == other.bill) { - return RestUtility.GetBedSleepingSlotPosFor(pawn, (Building_Bed)this.targetA.Thing) == pawn.Position; + return true; } - return this.targetA.Cell == pawn.Position; - } - - public bool JobIsSameAs(Job other) - { - return other != null && this.def == other.def && !(this.targetA != other.targetA) && !(this.targetB != other.targetB) && this.verbToUse == other.verbToUse && !(this.targetC != other.targetC) && this.commTarget == other.commTarget && this.bill == other.bill; + return false; } public bool AnyTargetIs(LocalTargetInfo target) { - return target.IsValid && (this.targetA == target || this.targetB == target || this.targetC == target || (this.targetQueueA != null && this.targetQueueA.Contains(target)) || (this.targetQueueB != null && this.targetQueueB.Contains(target))); + if (!target.IsValid) + { + return false; + } + return this.targetA == target || this.targetB == target || this.targetC == target || (this.targetQueueA != null && this.targetQueueA.Contains(target)) || (this.targetQueueB != null && this.targetQueueB.Contains(target)); } public override string ToString() diff --git a/Assembly-CSharp/Verse.AI/JobCondition.cs b/Assembly-CSharp/Verse.AI/JobCondition.cs index f437c7194..cc3c689b8 100644 --- a/Assembly-CSharp/Verse.AI/JobCondition.cs +++ b/Assembly-CSharp/Verse.AI/JobCondition.cs @@ -1,16 +1,14 @@ -using System; - namespace Verse.AI { public enum JobCondition : byte { - None, - Ongoing, - Succeeded, - Incompletable, - InterruptOptional, - InterruptForced, - Errored, - ErroredPather + None = 0, + Ongoing = 1, + Succeeded = 2, + Incompletable = 3, + InterruptOptional = 4, + InterruptForced = 5, + Errored = 6, + ErroredPather = 7 } } diff --git a/Assembly-CSharp/Verse.AI/JobDriver.cs b/Assembly-CSharp/Verse.AI/JobDriver.cs index 31957fd57..f847ae5b2 100644 --- a/Assembly-CSharp/Verse.AI/JobDriver.cs +++ b/Assembly-CSharp/Verse.AI/JobDriver.cs @@ -47,17 +47,7 @@ protected Toil CurToil } if (this.curToilIndex >= this.toils.Count) { - Log.Error(string.Concat(new object[] - { - this.pawn, - " with job ", - this.pawn.CurJob, - " tried to get CurToil with curToilIndex=", - this.curToilIndex, - " but only has ", - this.toils.Count, - " toils." - })); + Log.Error(this.pawn + " with job " + this.pawn.CurJob + " tried to get CurToil with curToilIndex=" + this.curToilIndex + " but only has " + this.toils.Count + " toils."); return null; } return this.toils[this.curToilIndex]; @@ -77,7 +67,11 @@ private bool CanStartNextToilInBusyStance get { int num = this.curToilIndex + 1; - return num < this.toils.Count && this.toils[num].atomicWithPrevious; + if (num >= this.toils.Count) + { + return false; + } + return this.toils[num].atomicWithPrevious; } } @@ -85,7 +79,7 @@ public virtual PawnPosture Posture { get { - return (this.layingDown == LayingDownState.NotLaying) ? PawnPosture.Standing : PawnPosture.LayingAny; + return (PawnPosture)((this.layingDown != 0) ? 2 : 0); } } @@ -185,30 +179,9 @@ public virtual string GetReport() protected string ReportStringProcessed(string str) { Job curJob = this.CurJob; - if (curJob.targetA.HasThing) - { - str = str.Replace("TargetA", curJob.targetA.Thing.LabelShort); - } - else - { - str = str.Replace("TargetA", "AreaLower".Translate()); - } - if (curJob.targetB.HasThing) - { - str = str.Replace("TargetB", curJob.targetB.Thing.LabelShort); - } - else - { - str = str.Replace("TargetB", "AreaLower".Translate()); - } - if (curJob.targetC.HasThing) - { - str = str.Replace("TargetC", curJob.targetC.Thing.LabelShort); - } - else - { - str = str.Replace("TargetC", "AreaLower".Translate()); - } + str = ((!curJob.targetA.HasThing) ? str.Replace("TargetA", "AreaLower".Translate()) : str.Replace("TargetA", curJob.targetA.Thing.LabelShort)); + str = ((!curJob.targetB.HasThing) ? str.Replace("TargetB", "AreaLower".Translate()) : str.Replace("TargetB", curJob.targetB.Thing.LabelShort)); + str = ((!curJob.targetC.HasThing) ? str.Replace("TargetC", "AreaLower".Translate()) : str.Replace("TargetC", curJob.targetC.Thing.LabelShort)); return str; } @@ -242,17 +215,7 @@ public void Cleanup(JobCondition condition) } catch (Exception ex) { - Log.Error(string.Concat(new object[] - { - "Pawn ", - this.pawn, - " threw exception while executing a global finish action (", - i, - "), jobDriver=", - base.GetType(), - ": ", - ex - })); + Log.Error("Pawn " + this.pawn + " threw exception while executing a global finish action (" + i + "), jobDriver=" + base.GetType() + ": " + ex); } } if (this.HaveCurToil) @@ -266,28 +229,20 @@ internal void SetupToils() try { this.toils.Clear(); - foreach (Toil current in this.MakeNewToils()) + foreach (Toil item in this.MakeNewToils()) { - if (current.defaultCompleteMode == ToilCompleteMode.Undefined) + if (item.defaultCompleteMode == ToilCompleteMode.Undefined) { Log.Error("Toil has undefined complete mode."); - current.defaultCompleteMode = ToilCompleteMode.Instant; + item.defaultCompleteMode = ToilCompleteMode.Instant; } - current.actor = this.pawn; - this.toils.Add(current); + item.actor = this.pawn; + this.toils.Add(item); } } catch (Exception ex) { - this.pawn.jobs.StartErrorRecoverJob(string.Concat(new object[] - { - "Exception in SetupToils (pawn=", - this.pawn, - ", job=", - this.CurJob, - "): ", - ex - })); + this.pawn.jobs.StartErrorRecoverJob("Exception in SetupToils (pawn=" + this.pawn + ", job=" + this.CurJob + "): " + ex); } } @@ -311,13 +266,13 @@ public void DriverTick() if (this.ticksLeftThisToil <= 0) { this.ReadyForNextToil(); - return; + goto end_IL_0000; } } else if (this.curToilCompleteMode == ToilCompleteMode.FinishedBusy && !this.pawn.stances.FullBodyBusy) { this.ReadyForNextToil(); - return; + goto end_IL_0000; } if (this.wantBeginNextToil) { @@ -325,14 +280,7 @@ public void DriverTick() } else if (this.curToilCompleteMode == ToilCompleteMode.Instant && this.debugTicksSpentThisToil > 300) { - Log.Error(string.Concat(new object[] - { - this.pawn, - " had to be broken from frozen state. He was doing job ", - this.CurJob, - ", toilindex=", - this.curToilIndex - })); + Log.Error(this.pawn + " had to be broken from frozen state. He was doing job " + this.CurJob + ", toilindex=" + this.curToilIndex); this.ReadyForNextToil(); } else @@ -341,39 +289,29 @@ public void DriverTick() if (this.CurToil.preTickActions != null) { Toil curToil = this.CurToil; - for (int i = 0; i < curToil.preTickActions.Count; i++) + int num = 0; + while (num < curToil.preTickActions.Count) { - curToil.preTickActions[i](); - if (this.CurJob != curJob) + curToil.preTickActions[num](); + if (this.CurJob == curJob && this.CurToil == curToil && !this.wantBeginNextToil) { - return; - } - if (this.CurToil != curToil || this.wantBeginNextToil) - { - return; + num++; + continue; } + return; } } - if (this.CurToil.tickAction != null) + if ((object)this.CurToil.tickAction != null) { this.CurToil.tickAction(); } } } + end_IL_0000:; } catch (Exception ex) { - this.pawn.jobs.StartErrorRecoverJob(string.Concat(new object[] - { - "Exception in Tick (pawn=", - this.pawn, - ", job=", - this.CurJob, - ", CurToil=", - this.curToilIndex, - "): ", - ex - })); + this.pawn.jobs.StartErrorRecoverJob("Exception in Tick (pawn=" + this.pawn + ", job=" + this.CurJob + ", CurToil=" + this.curToilIndex + "): " + ex); } } @@ -385,78 +323,65 @@ public void ReadyForNextToil() private void TryActuallyStartNextToil() { - if (!this.pawn.Spawned) + if (this.pawn.Spawned && (!this.pawn.stances.FullBodyBusy || this.CanStartNextToilInBusyStance)) { - return; - } - if (this.pawn.stances.FullBodyBusy && !this.CanStartNextToilInBusyStance) - { - return; - } - if (this.HaveCurToil) - { - this.CurToil.Cleanup(); - } - this.curToilIndex++; - this.wantBeginNextToil = false; - if (!this.HaveCurToil) - { - if (this.pawn.stances != null && this.pawn.stances.curStance.StanceBusy) + if (this.HaveCurToil) { - Log.ErrorOnce(string.Concat(new object[] - { - this.pawn, - " ended job ", - this.CurJob, - " due to running out of toils during a busy stance." - }), 6453432); + this.CurToil.Cleanup(); } - this.EndJobWith(JobCondition.Succeeded); - return; - } - this.debugTicksSpentThisToil = 0; - this.ticksLeftThisToil = this.CurToil.defaultDuration; - this.curToilCompleteMode = this.CurToil.defaultCompleteMode; - if (!this.CheckCurrentToilEndOrFail()) - { - int num = this.CurToilIndex; - if (this.CurToil.preInitActions != null) + this.curToilIndex++; + this.wantBeginNextToil = false; + if (!this.HaveCurToil) { - for (int i = 0; i < this.CurToil.preInitActions.Count; i++) + if (this.pawn.stances != null && this.pawn.stances.curStance.StanceBusy) { - this.CurToil.preInitActions[i](); - if (this.CurToilIndex != num) - { - break; - } + Log.ErrorOnce(this.pawn + " ended job " + this.CurJob + " due to running out of toils during a busy stance.", 6453432); } + this.EndJobWith(JobCondition.Succeeded); } - if (this.CurToilIndex == num) + else { - if (this.CurToil.initAction != null) + this.debugTicksSpentThisToil = 0; + this.ticksLeftThisToil = this.CurToil.defaultDuration; + this.curToilCompleteMode = this.CurToil.defaultCompleteMode; + if (!this.CheckCurrentToilEndOrFail()) { - try + int num = this.CurToilIndex; + if (this.CurToil.preInitActions != null) { - this.CurToil.initAction(); + int num2 = 0; + while (num2 < this.CurToil.preInitActions.Count) + { + this.CurToil.preInitActions[num2](); + if (this.CurToilIndex == num) + { + num2++; + continue; + } + break; + } } - catch (Exception ex) + if (this.CurToilIndex == num) { - this.pawn.jobs.StartErrorRecoverJob(string.Concat(new object[] + if ((object)this.CurToil.initAction != null) + { + try + { + this.CurToil.initAction(); + } + catch (Exception ex) + { + this.pawn.jobs.StartErrorRecoverJob("JobDriver threw exception in initAction. Pawn=" + this.pawn + ", Job=" + this.CurJob + ", Exception: " + ex); + return; + IL_01e4:; + } + } + if (this.CurToilIndex == num && !this.ended && this.curToilCompleteMode == ToilCompleteMode.Instant) { - "JobDriver threw exception in initAction. Pawn=", - this.pawn, - ", Job=", - this.CurJob, - ", Exception: ", - ex - })); - return; + this.ReadyForNextToil(); + } } } - if (this.CurToilIndex == num && !this.ended && this.curToilCompleteMode == ToilCompleteMode.Instant) - { - this.ReadyForNextToil(); - } } } } @@ -552,7 +477,7 @@ public void AddEndCondition(Func newEndCondition) public void AddFailCondition(Func newFailCondition) { - this.globalFailConditions.Add(delegate + this.globalFailConditions.Add((Func)delegate() { if (newFailCondition()) { diff --git a/Assembly-CSharp/Verse.AI/JobDriver_AttackMelee.cs b/Assembly-CSharp/Verse.AI/JobDriver_AttackMelee.cs index 0eeaa8c6f..cc35c88a8 100644 --- a/Assembly-CSharp/Verse.AI/JobDriver_AttackMelee.cs +++ b/Assembly-CSharp/Verse.AI/JobDriver_AttackMelee.cs @@ -1,6 +1,6 @@ +using RimWorld; using System; using System.Collections.Generic; -using System.Diagnostics; namespace Verse.AI { @@ -14,29 +14,39 @@ public override void ExposeData() Scribe_Values.Look(ref this.numMeleeAttacksMade, "numMeleeAttacksMade", 0, false); } - [DebuggerHidden] protected override IEnumerable MakeNewToils() { - JobDriver_AttackMelee.c__Iterator1B5 c__Iterator1B = new JobDriver_AttackMelee.c__Iterator1B5(); - c__Iterator1B.<>f__this = this; - JobDriver_AttackMelee.c__Iterator1B5 expr_0E = c__Iterator1B; - expr_0E.$PC = -2; - return expr_0E; + yield return Toils_ReserveAttackTarget.TryReserve(TargetIndex.A); + yield return Toils_Misc.ThrowColonistAttackingMote(TargetIndex.A); + yield return Toils_Combat.FollowAndMeleeAttack(TargetIndex.A, (Action)delegate + { + Thing thing = ((_003CMakeNewToils_003Ec__Iterator1B5)/*Error near IL_005b: stateMachine*/)._003C_003Ef__this.CurJob.GetTarget(TargetIndex.A).Thing; + if (((_003CMakeNewToils_003Ec__Iterator1B5)/*Error near IL_005b: stateMachine*/)._003C_003Ef__this.pawn.meleeVerbs.TryMeleeAttack(thing, ((_003CMakeNewToils_003Ec__Iterator1B5)/*Error near IL_005b: stateMachine*/)._003C_003Ef__this.CurJob.verbToUse, false) && ((_003CMakeNewToils_003Ec__Iterator1B5)/*Error near IL_005b: stateMachine*/)._003C_003Ef__this.pawn.CurJob != null && ((_003CMakeNewToils_003Ec__Iterator1B5)/*Error near IL_005b: stateMachine*/)._003C_003Ef__this.pawn.jobs.curDriver == ((_003CMakeNewToils_003Ec__Iterator1B5)/*Error near IL_005b: stateMachine*/)._003C_003Ef__this) + { + ((_003CMakeNewToils_003Ec__Iterator1B5)/*Error near IL_005b: stateMachine*/)._003C_003Ef__this.numMeleeAttacksMade++; + if (((_003CMakeNewToils_003Ec__Iterator1B5)/*Error near IL_005b: stateMachine*/)._003C_003Ef__this.numMeleeAttacksMade >= ((_003CMakeNewToils_003Ec__Iterator1B5)/*Error near IL_005b: stateMachine*/)._003C_003Ef__this.pawn.CurJob.maxNumMeleeAttacks) + { + ((_003CMakeNewToils_003Ec__Iterator1B5)/*Error near IL_005b: stateMachine*/)._003C_003Ef__this.EndJobWith(JobCondition.Succeeded); + } + } + }).FailOnDespawnedOrNull(TargetIndex.A); } public override void Notify_PatherFailed() { if (base.CurJob.attackDoorIfTargetLost) { - Thing thing; - using (PawnPath pawnPath = base.Map.pathFinder.FindPath(this.pawn.Position, base.TargetA.Cell, TraverseParms.For(this.pawn, Danger.Deadly, TraverseMode.PassDoors, false), PathEndMode.OnCell)) + Thing thing = default(Thing); + using (PawnPath pawnPath = base.Map.pathFinder.FindPath(base.pawn.Position, base.TargetA.Cell, TraverseParms.For(base.pawn, Danger.Deadly, TraverseMode.PassDoors, false), PathEndMode.OnCell)) { - if (!pawnPath.Found) + if (pawnPath.Found) { - return; + IntVec3 intVec = default(IntVec3); + thing = pawnPath.FirstBlockingBuilding(out intVec, base.pawn); + goto end_IL_004e; } - IntVec3 intVec; - thing = pawnPath.FirstBlockingBuilding(out intVec, this.pawn); + return; + end_IL_004e:; } if (thing != null) { diff --git a/Assembly-CSharp/Verse.AI/JobDriver_AttackStatic.cs b/Assembly-CSharp/Verse.AI/JobDriver_AttackStatic.cs index 43289b4ab..8fc642dcd 100644 --- a/Assembly-CSharp/Verse.AI/JobDriver_AttackStatic.cs +++ b/Assembly-CSharp/Verse.AI/JobDriver_AttackStatic.cs @@ -1,6 +1,6 @@ +using RimWorld; using System; using System.Collections.Generic; -using System.Diagnostics; namespace Verse.AI { @@ -17,14 +17,45 @@ public override void ExposeData() Scribe_Values.Look(ref this.numAttacksMade, "numAttacksMade", 0, false); } - [DebuggerHidden] protected override IEnumerable MakeNewToils() { - JobDriver_AttackStatic.c__Iterator1B6 c__Iterator1B = new JobDriver_AttackStatic.c__Iterator1B6(); - c__Iterator1B.<>f__this = this; - JobDriver_AttackStatic.c__Iterator1B6 expr_0E = c__Iterator1B; - expr_0E.$PC = -2; - return expr_0E; + yield return Toils_Misc.ThrowColonistAttackingMote(TargetIndex.A); + yield return new Toil + { + initAction = (Action)delegate + { + Pawn pawn2 = ((_003CMakeNewToils_003Ec__Iterator1B6)/*Error near IL_004e: stateMachine*/)._003C_003Ef__this.TargetThingA as Pawn; + if (pawn2 != null) + { + ((_003CMakeNewToils_003Ec__Iterator1B6)/*Error near IL_004e: stateMachine*/)._003C_003Ef__this.startedIncapacitated = pawn2.Downed; + } + ((_003CMakeNewToils_003Ec__Iterator1B6)/*Error near IL_004e: stateMachine*/)._003C_003Ef__this.pawn.pather.StopDead(); + }, + tickAction = (Action)delegate + { + if (((_003CMakeNewToils_003Ec__Iterator1B6)/*Error near IL_0065: stateMachine*/)._003C_003Ef__this.TargetA.HasThing) + { + Pawn pawn = ((_003CMakeNewToils_003Ec__Iterator1B6)/*Error near IL_0065: stateMachine*/)._003C_003Ef__this.TargetA.Thing as Pawn; + if (!((_003CMakeNewToils_003Ec__Iterator1B6)/*Error near IL_0065: stateMachine*/)._003C_003Ef__this.TargetA.Thing.Destroyed && (pawn == null || ((_003CMakeNewToils_003Ec__Iterator1B6)/*Error near IL_0065: stateMachine*/)._003C_003Ef__this.startedIncapacitated || !pawn.Downed)) + { + goto IL_007c; + } + ((_003CMakeNewToils_003Ec__Iterator1B6)/*Error near IL_0065: stateMachine*/)._003C_003Ef__this.EndJobWith(JobCondition.Succeeded); + return; + } + goto IL_007c; + IL_007c: + if (((_003CMakeNewToils_003Ec__Iterator1B6)/*Error near IL_0065: stateMachine*/)._003C_003Ef__this.numAttacksMade >= ((_003CMakeNewToils_003Ec__Iterator1B6)/*Error near IL_0065: stateMachine*/)._003C_003Ef__this.pawn.CurJob.maxNumStaticAttacks && !((_003CMakeNewToils_003Ec__Iterator1B6)/*Error near IL_0065: stateMachine*/)._003C_003Ef__this.pawn.stances.FullBodyBusy) + { + ((_003CMakeNewToils_003Ec__Iterator1B6)/*Error near IL_0065: stateMachine*/)._003C_003Ef__this.EndJobWith(JobCondition.Succeeded); + } + else if (((_003CMakeNewToils_003Ec__Iterator1B6)/*Error near IL_0065: stateMachine*/)._003C_003Ef__this.pawn.equipment.TryStartAttack(((_003CMakeNewToils_003Ec__Iterator1B6)/*Error near IL_0065: stateMachine*/)._003C_003Ef__this.TargetA)) + { + ((_003CMakeNewToils_003Ec__Iterator1B6)/*Error near IL_0065: stateMachine*/)._003C_003Ef__this.numAttacksMade++; + } + }, + defaultCompleteMode = ToilCompleteMode.Never + }; } } } diff --git a/Assembly-CSharp/Verse.AI/JobDriver_CastVerbOnce.cs b/Assembly-CSharp/Verse.AI/JobDriver_CastVerbOnce.cs index 7876a2562..1500c4058 100644 --- a/Assembly-CSharp/Verse.AI/JobDriver_CastVerbOnce.cs +++ b/Assembly-CSharp/Verse.AI/JobDriver_CastVerbOnce.cs @@ -1,6 +1,4 @@ -using System; using System.Collections.Generic; -using System.Diagnostics; namespace Verse.AI { @@ -8,29 +6,14 @@ public class JobDriver_CastVerbOnce : JobDriver { public override string GetReport() { - string text; - if (base.TargetA.HasThing) - { - text = base.TargetThingA.LabelCap; - } - else - { - text = "AreaLower".Translate(); - } - return "UsingVerb".Translate(new object[] - { - base.CurJob.verbToUse.verbProps.label, - text - }); + string text = (!base.TargetA.HasThing) ? "AreaLower".Translate() : base.TargetThingA.LabelCap; + return "UsingVerb".Translate(base.CurJob.verbToUse.verbProps.label, text); } - [DebuggerHidden] protected override IEnumerable MakeNewToils() { - JobDriver_CastVerbOnce.c__Iterator1B8 c__Iterator1B = new JobDriver_CastVerbOnce.c__Iterator1B8(); - JobDriver_CastVerbOnce.c__Iterator1B8 expr_07 = c__Iterator1B; - expr_07.$PC = -2; - return expr_07; + yield return Toils_Combat.GotoCastPosition(TargetIndex.A, false); + yield return Toils_Combat.CastVerb(TargetIndex.A, true); } } } diff --git a/Assembly-CSharp/Verse.AI/JobDriver_DoBill.cs b/Assembly-CSharp/Verse.AI/JobDriver_DoBill.cs index 656d0b2b8..eb1213aae 100644 --- a/Assembly-CSharp/Verse.AI/JobDriver_DoBill.cs +++ b/Assembly-CSharp/Verse.AI/JobDriver_DoBill.cs @@ -1,7 +1,6 @@ using RimWorld; using System; using System.Collections.Generic; -using System.Diagnostics; using UnityEngine; namespace Verse.AI @@ -26,7 +25,7 @@ public IBillGiver BillGiver { get { - IBillGiver billGiver = this.pawn.jobs.curJob.GetTarget(TargetIndex.A).Thing as IBillGiver; + IBillGiver billGiver = base.pawn.jobs.curJob.GetTarget(TargetIndex.A).Thing as IBillGiver; if (billGiver == null) { throw new InvalidOperationException("DoBill on non-Billgiver."); @@ -37,9 +36,9 @@ public IBillGiver BillGiver public override string GetReport() { - if (this.pawn.jobs.curJob.RecipeDef != null) + if (base.pawn.jobs.curJob.RecipeDef != null) { - return base.ReportStringProcessed(this.pawn.jobs.curJob.RecipeDef.jobString); + return base.ReportStringProcessed(base.pawn.jobs.curJob.RecipeDef.jobString); } return base.GetReport(); } @@ -52,69 +51,136 @@ public override void ExposeData() Scribe_Values.Look(ref this.ticksSpentDoingRecipeWork, "ticksSpentDoingRecipeWork", 0, false); } - [DebuggerHidden] protected override IEnumerable MakeNewToils() { - JobDriver_DoBill.c__Iterator1B9 c__Iterator1B = new JobDriver_DoBill.c__Iterator1B9(); - c__Iterator1B.<>f__this = this; - JobDriver_DoBill.c__Iterator1B9 expr_0E = c__Iterator1B; - expr_0E.$PC = -2; - return expr_0E; + this.AddEndCondition((Func)delegate + { + Thing thing = ((_003CMakeNewToils_003Ec__Iterator1B9)/*Error near IL_0073: stateMachine*/)._003C_003Ef__this.GetActor().jobs.curJob.GetTarget(TargetIndex.A).Thing; + if (thing is Building && !thing.Spawned) + { + return JobCondition.Incompletable; + } + return JobCondition.Ongoing; + }); + this.FailOnBurningImmobile(TargetIndex.A); + this.FailOn((Func)delegate + { + IBillGiver billGiver = ((_003CMakeNewToils_003Ec__Iterator1B9)/*Error near IL_0097: stateMachine*/)._003C_003Ef__this.pawn.jobs.curJob.GetTarget(TargetIndex.A).Thing as IBillGiver; + if (billGiver != null) + { + if (((_003CMakeNewToils_003Ec__Iterator1B9)/*Error near IL_0097: stateMachine*/)._003C_003Ef__this.pawn.jobs.curJob.bill.DeletedOrDereferenced) + { + return true; + } + if (!billGiver.CurrentlyUsable()) + { + return true; + } + } + return false; + }); + Toil gotoBillGiver = Toils_Goto.GotoThing(TargetIndex.A, PathEndMode.InteractionCell); + yield return Toils_Reserve.Reserve(TargetIndex.A, 1, -1, null); + yield return Toils_Reserve.ReserveQueue(TargetIndex.B, 1, -1, null); + yield return new Toil + { + initAction = (Action)delegate + { + if (((_003CMakeNewToils_003Ec__Iterator1B9)/*Error near IL_00fd: stateMachine*/)._003C_003Ef__this.CurJob.targetQueueB != null && ((_003CMakeNewToils_003Ec__Iterator1B9)/*Error near IL_00fd: stateMachine*/)._003C_003Ef__this.CurJob.targetQueueB.Count == 1) + { + UnfinishedThing unfinishedThing = ((_003CMakeNewToils_003Ec__Iterator1B9)/*Error near IL_00fd: stateMachine*/)._003C_003Ef__this.CurJob.targetQueueB[0].Thing as UnfinishedThing; + if (unfinishedThing != null) + { + unfinishedThing.BoundBill = (Bill_ProductionWithUft)((_003CMakeNewToils_003Ec__Iterator1B9)/*Error near IL_00fd: stateMachine*/)._003C_003Ef__this.CurJob.bill; + } + } + } + }; + yield return Toils_Jump.JumpIf(gotoBillGiver, (Func)(() => ((_003CMakeNewToils_003Ec__Iterator1B9)/*Error near IL_012d: stateMachine*/)._003C_003Ef__this.CurJob.GetTargetQueue(TargetIndex.B).NullOrEmpty())); + Toil extract = Toils_JobTransforms.ExtractNextTargetFromQueue(TargetIndex.B); + yield return extract; + Toil getToHaulTarget = Toils_Goto.GotoThing(TargetIndex.B, PathEndMode.ClosestTouch).FailOnDespawnedNullOrForbidden(TargetIndex.B).FailOnSomeonePhysicallyInteracting(TargetIndex.B); + yield return getToHaulTarget; + yield return Toils_Haul.StartCarryThing(TargetIndex.B, true, false); + yield return JobDriver_DoBill.JumpToCollectNextIntoHandsForBill(getToHaulTarget, TargetIndex.B); + yield return Toils_Goto.GotoThing(TargetIndex.A, PathEndMode.InteractionCell).FailOnDestroyedOrNull(TargetIndex.B); + Toil findPlaceTarget = Toils_JobTransforms.SetTargetToIngredientPlaceCell(TargetIndex.A, TargetIndex.B, TargetIndex.C); + yield return findPlaceTarget; + yield return Toils_Haul.PlaceHauledThingInCell(TargetIndex.C, findPlaceTarget, false); + yield return Toils_Jump.JumpIfHaveTargetInQueue(TargetIndex.B, extract); + yield return gotoBillGiver; + yield return Toils_Recipe.MakeUnfinishedThingIfNeeded(); + yield return Toils_Recipe.DoRecipeWork().FailOnDespawnedOrForbiddenPlacedThings().FailOnCannotTouch(TargetIndex.A, PathEndMode.InteractionCell); + yield return Toils_Recipe.FinishRecipeAndStartStoringProduct(); + if (base.CurJob.RecipeDef.products.NullOrEmpty() && base.CurJob.RecipeDef.specialProducts.NullOrEmpty()) + yield break; + yield return Toils_Reserve.Reserve(TargetIndex.B, 1, -1, null); + Toil carryToCell = Toils_Haul.CarryHauledThingToCell(TargetIndex.B); + yield return carryToCell; + yield return Toils_Haul.PlaceHauledThingInCell(TargetIndex.B, carryToCell, true); + yield return new Toil + { + initAction = (Action)delegate + { + Bill_Production bill_Production = ((_003CMakeNewToils_003Ec__Iterator1B9)/*Error near IL_037f: stateMachine*/)._003Crecount_003E__6.actor.jobs.curJob.bill as Bill_Production; + if (bill_Production != null && bill_Production.repeatMode == BillRepeatModeDefOf.TargetCount) + { + ((_003CMakeNewToils_003Ec__Iterator1B9)/*Error near IL_037f: stateMachine*/)._003C_003Ef__this.Map.resourceCounter.UpdateResourceCounts(); + } + } + }; } private static Toil JumpToCollectNextIntoHandsForBill(Toil gotoGetTargetToil, TargetIndex ind) { Toil toil = new Toil(); - toil.initAction = delegate + toil.initAction = (Action)delegate() { Pawn actor = toil.actor; if (actor.carryTracker.CarriedThing == null) { Log.Error("JumpToAlsoCollectTargetInQueue run on " + actor + " who is not carrying something."); - return; - } - if (actor.carryTracker.Full) - { - return; } - Job curJob = actor.jobs.curJob; - List targetQueue = curJob.GetTargetQueue(ind); - if (targetQueue.NullOrEmpty()) + else if (!actor.carryTracker.Full) { - return; - } - for (int i = 0; i < targetQueue.Count; i++) - { - if (GenAI.CanUseItemForWork(actor, targetQueue[i].Thing)) + Job curJob = actor.jobs.curJob; + List targetQueue = curJob.GetTargetQueue(ind); + if (!targetQueue.NullOrEmpty()) { - if (targetQueue[i].Thing.CanStackWith(actor.carryTracker.CarriedThing)) + int num = 0; + int a; + while (true) { - if ((float)(actor.Position - targetQueue[i].Thing.Position).LengthHorizontalSquared <= 64f) + if (num < targetQueue.Count) { - int num = (actor.carryTracker.CarriedThing != null) ? actor.carryTracker.CarriedThing.stackCount : 0; - int num2 = curJob.countQueue[i]; - num2 = Mathf.Min(num2, targetQueue[i].Thing.def.stackLimit - num); - num2 = Mathf.Min(num2, actor.carryTracker.AvailableStackSpace(targetQueue[i].Thing.def)); - if (num2 > 0) + if (GenAI.CanUseItemForWork(actor, targetQueue[num].Thing) && targetQueue[num].Thing.CanStackWith(actor.carryTracker.CarriedThing) && !((float)(actor.Position - targetQueue[num].Thing.Position).LengthHorizontalSquared > 64.0)) { - curJob.count = num2; - curJob.SetTarget(ind, targetQueue[i].Thing); - List countQueue; - List expr_1B3 = countQueue = curJob.countQueue; - int num3; - int expr_1B7 = num3 = i; - num3 = countQueue[num3]; - expr_1B3[expr_1B7] = num3 - num2; - if (curJob.countQueue[i] == 0) - { - curJob.countQueue.RemoveAt(i); - targetQueue.RemoveAt(i); - } - actor.jobs.curDriver.JumpToToil(gotoGetTargetToil); - return; + int num2 = (actor.carryTracker.CarriedThing != null) ? actor.carryTracker.CarriedThing.stackCount : 0; + a = curJob.countQueue[num]; + a = Mathf.Min(a, targetQueue[num].Thing.def.stackLimit - num2); + a = Mathf.Min(a, actor.carryTracker.AvailableStackSpace(targetQueue[num].Thing.def)); + if (a > 0) + break; } + num++; + continue; } + return; + } + curJob.count = a; + curJob.SetTarget(ind, targetQueue[num].Thing); + List countQueue; + List obj = countQueue = curJob.countQueue; + int index; + int index2 = index = num; + index = countQueue[index]; + obj[index2] = index - a; + if (curJob.countQueue[num] == 0) + { + curJob.countQueue.RemoveAt(num); + targetQueue.RemoveAt(num); } + actor.jobs.curDriver.JumpToToil(gotoGetTargetToil); } } }; diff --git a/Assembly-CSharp/Verse.AI/JobDriver_Equip.cs b/Assembly-CSharp/Verse.AI/JobDriver_Equip.cs index e8ce926f9..e3ddacd30 100644 --- a/Assembly-CSharp/Verse.AI/JobDriver_Equip.cs +++ b/Assembly-CSharp/Verse.AI/JobDriver_Equip.cs @@ -1,19 +1,39 @@ using System; using System.Collections.Generic; -using System.Diagnostics; +using Verse.Sound; namespace Verse.AI { public class JobDriver_Equip : JobDriver { - [DebuggerHidden] protected override IEnumerable MakeNewToils() { - JobDriver_Equip.c__Iterator1B1 c__Iterator1B = new JobDriver_Equip.c__Iterator1B1(); - c__Iterator1B.<>f__this = this; - JobDriver_Equip.c__Iterator1B1 expr_0E = c__Iterator1B; - expr_0E.$PC = -2; - return expr_0E; + yield return Toils_Reserve.Reserve(TargetIndex.A, 1, -1, null); + yield return Toils_Goto.GotoThing(TargetIndex.A, PathEndMode.ClosestTouch).FailOnDespawnedNullOrForbidden(TargetIndex.A); + yield return new Toil + { + initAction = (Action)delegate + { + ThingWithComps thingWithComps = (ThingWithComps)((_003CMakeNewToils_003Ec__Iterator1B1)/*Error near IL_0074: stateMachine*/)._003C_003Ef__this.CurJob.targetA.Thing; + ThingWithComps thingWithComps2 = null; + if (thingWithComps.def.stackLimit > 1 && thingWithComps.stackCount > 1) + { + thingWithComps2 = (ThingWithComps)thingWithComps.SplitOff(1); + } + else + { + thingWithComps2 = thingWithComps; + thingWithComps2.DeSpawn(); + } + ((_003CMakeNewToils_003Ec__Iterator1B1)/*Error near IL_0074: stateMachine*/)._003C_003Ef__this.pawn.equipment.MakeRoomFor(thingWithComps2); + ((_003CMakeNewToils_003Ec__Iterator1B1)/*Error near IL_0074: stateMachine*/)._003C_003Ef__this.pawn.equipment.AddEquipment(thingWithComps2); + if (thingWithComps.def.soundInteract != null) + { + thingWithComps.def.soundInteract.PlayOneShot(new TargetInfo(((_003CMakeNewToils_003Ec__Iterator1B1)/*Error near IL_0074: stateMachine*/)._003C_003Ef__this.pawn.Position, ((_003CMakeNewToils_003Ec__Iterator1B1)/*Error near IL_0074: stateMachine*/)._003C_003Ef__this.pawn.Map, false)); + } + }, + defaultCompleteMode = ToilCompleteMode.Instant + }; } } } diff --git a/Assembly-CSharp/Verse.AI/JobDriver_Goto.cs b/Assembly-CSharp/Verse.AI/JobDriver_Goto.cs index 063fcbb80..3496606d5 100644 --- a/Assembly-CSharp/Verse.AI/JobDriver_Goto.cs +++ b/Assembly-CSharp/Verse.AI/JobDriver_Goto.cs @@ -1,29 +1,47 @@ using RimWorld.Planet; using System; using System.Collections.Generic; -using System.Diagnostics; namespace Verse.AI { public class JobDriver_Goto : JobDriver { - [DebuggerHidden] protected override IEnumerable MakeNewToils() { - JobDriver_Goto.c__Iterator1B2 c__Iterator1B = new JobDriver_Goto.c__Iterator1B2(); - c__Iterator1B.<>f__this = this; - JobDriver_Goto.c__Iterator1B2 expr_0E = c__Iterator1B; - expr_0E.$PC = -2; - return expr_0E; + Toil gotoCell = Toils_Goto.GotoCell(TargetIndex.A, PathEndMode.OnCell); + gotoCell.AddPreTickAction((Action)delegate + { + if (((_003CMakeNewToils_003Ec__Iterator1B2)/*Error near IL_0038: stateMachine*/)._003C_003Ef__this.CurJob.exitMapOnArrival && ((_003CMakeNewToils_003Ec__Iterator1B2)/*Error near IL_0038: stateMachine*/)._003C_003Ef__this.pawn.Map.exitMapGrid.IsExitCell(((_003CMakeNewToils_003Ec__Iterator1B2)/*Error near IL_0038: stateMachine*/)._003C_003Ef__this.pawn.Position)) + { + ((_003CMakeNewToils_003Ec__Iterator1B2)/*Error near IL_0038: stateMachine*/)._003C_003Ef__this.TryExitMap(); + } + }); + gotoCell.FailOn((Func)(() => ((_003CMakeNewToils_003Ec__Iterator1B2)/*Error near IL_004f: stateMachine*/)._003C_003Ef__this.CurJob.failIfCantJoinOrCreateCaravan && !CaravanExitMapUtility.CanExitMapAndJoinOrCreateCaravanNow(((_003CMakeNewToils_003Ec__Iterator1B2)/*Error near IL_004f: stateMachine*/)._003C_003Ef__this.pawn))); + yield return gotoCell; + yield return new Toil + { + initAction = (Action)delegate + { + if (((_003CMakeNewToils_003Ec__Iterator1B2)/*Error near IL_008a: stateMachine*/)._003C_003Ef__this.pawn.mindState != null && ((_003CMakeNewToils_003Ec__Iterator1B2)/*Error near IL_008a: stateMachine*/)._003C_003Ef__this.pawn.mindState.forcedGotoPosition == ((_003CMakeNewToils_003Ec__Iterator1B2)/*Error near IL_008a: stateMachine*/)._003C_003Ef__this.TargetA.Cell) + { + ((_003CMakeNewToils_003Ec__Iterator1B2)/*Error near IL_008a: stateMachine*/)._003C_003Ef__this.pawn.mindState.forcedGotoPosition = IntVec3.Invalid; + } + if (((_003CMakeNewToils_003Ec__Iterator1B2)/*Error near IL_008a: stateMachine*/)._003C_003Ef__this.CurJob.exitMapOnArrival) + { + if (!((_003CMakeNewToils_003Ec__Iterator1B2)/*Error near IL_008a: stateMachine*/)._003C_003Ef__this.pawn.Position.OnEdge(((_003CMakeNewToils_003Ec__Iterator1B2)/*Error near IL_008a: stateMachine*/)._003C_003Ef__this.pawn.Map) && !((_003CMakeNewToils_003Ec__Iterator1B2)/*Error near IL_008a: stateMachine*/)._003C_003Ef__this.pawn.Map.exitMapGrid.IsExitCell(((_003CMakeNewToils_003Ec__Iterator1B2)/*Error near IL_008a: stateMachine*/)._003C_003Ef__this.pawn.Position)) + return; + ((_003CMakeNewToils_003Ec__Iterator1B2)/*Error near IL_008a: stateMachine*/)._003C_003Ef__this.TryExitMap(); + } + }, + defaultCompleteMode = ToilCompleteMode.Instant + }; } private void TryExitMap() { - if (base.CurJob.failIfCantJoinOrCreateCaravan && !CaravanExitMapUtility.CanExitMapAndJoinOrCreateCaravanNow(this.pawn)) - { + if (base.CurJob.failIfCantJoinOrCreateCaravan && !CaravanExitMapUtility.CanExitMapAndJoinOrCreateCaravanNow(base.pawn)) return; - } - this.pawn.ExitMap(true); + base.pawn.ExitMap(true); } } } diff --git a/Assembly-CSharp/Verse.AI/JobDriver_HaulToCell.cs b/Assembly-CSharp/Verse.AI/JobDriver_HaulToCell.cs index 178167a3a..f4ef056d3 100644 --- a/Assembly-CSharp/Verse.AI/JobDriver_HaulToCell.cs +++ b/Assembly-CSharp/Verse.AI/JobDriver_HaulToCell.cs @@ -1,7 +1,6 @@ using RimWorld; using System; using System.Collections.Generic; -using System.Diagnostics; namespace Verse.AI { @@ -13,49 +12,53 @@ public class JobDriver_HaulToCell : JobDriver public override string GetReport() { - IntVec3 cell = this.pawn.jobs.curJob.targetB.Cell; - Thing thing; - if (this.pawn.carryTracker.CarriedThing != null) - { - thing = this.pawn.carryTracker.CarriedThing; - } - else - { - thing = base.TargetThingA; - } - string text = null; + IntVec3 cell = base.pawn.jobs.curJob.targetB.Cell; + Thing thing = null; + thing = ((base.pawn.carryTracker.CarriedThing == null) ? base.TargetThingA : base.pawn.carryTracker.CarriedThing); + string text = (string)null; SlotGroup slotGroup = cell.GetSlotGroup(base.Map); if (slotGroup != null) { text = slotGroup.parent.SlotYielderLabel(); } - string result; - if (text != null) + return (text == null) ? "ReportHauling".Translate(thing.LabelCap) : "ReportHaulingTo".Translate(thing.LabelCap, text); + } + + protected override IEnumerable MakeNewToils() + { + this.FailOnDestroyedOrNull(TargetIndex.A); + this.FailOnBurningImmobile(TargetIndex.B); + if (!base.TargetThingA.IsForbidden(base.pawn)) { - result = "ReportHaulingTo".Translate(new object[] - { - thing.LabelCap, - text - }); + this.FailOnForbidden(TargetIndex.A); } - else + yield return Toils_Reserve.Reserve(TargetIndex.B, 1, -1, null); + Toil reserveTargetA = Toils_Reserve.Reserve(TargetIndex.A, 1, -1, null); + yield return reserveTargetA; + Toil toilGoto = Toils_Goto.GotoThing(TargetIndex.A, PathEndMode.ClosestTouch).FailOnSomeonePhysicallyInteracting(TargetIndex.A).FailOn((Func)delegate { - result = "ReportHauling".Translate(new object[] + Pawn actor = ((_003CMakeNewToils_003Ec__Iterator1BA)/*Error near IL_00d7: stateMachine*/)._003CtoilGoto_003E__1.actor; + Job curJob = actor.jobs.curJob; + if (curJob.haulMode == HaulMode.ToCellStorage) { - thing.LabelCap - }); + Thing thing = curJob.GetTarget(TargetIndex.A).Thing; + IntVec3 cell = actor.jobs.curJob.GetTarget(TargetIndex.B).Cell; + if (!cell.IsValidStorageFor(((_003CMakeNewToils_003Ec__Iterator1BA)/*Error near IL_00d7: stateMachine*/)._003C_003Ef__this.Map, thing)) + { + return true; + } + } + return false; + }); + yield return toilGoto; + yield return Toils_Haul.StartCarryThing(TargetIndex.A, false, true); + if (base.CurJob.haulOpportunisticDuplicates) + { + yield return Toils_Haul.CheckForGetOpportunityDuplicate(reserveTargetA, TargetIndex.A, TargetIndex.B, false, null); } - return result; - } - - [DebuggerHidden] - protected override IEnumerable MakeNewToils() - { - JobDriver_HaulToCell.c__Iterator1BA c__Iterator1BA = new JobDriver_HaulToCell.c__Iterator1BA(); - c__Iterator1BA.<>f__this = this; - JobDriver_HaulToCell.c__Iterator1BA expr_0E = c__Iterator1BA; - expr_0E.$PC = -2; - return expr_0E; + Toil carryToCell = Toils_Haul.CarryHauledThingToCell(TargetIndex.B); + yield return carryToCell; + yield return Toils_Haul.PlaceHauledThingInCell(TargetIndex.B, carryToCell, true); } } } diff --git a/Assembly-CSharp/Verse.AI/JobDriver_HaulToContainer.cs b/Assembly-CSharp/Verse.AI/JobDriver_HaulToContainer.cs index 2e860f8b2..407efcea7 100644 --- a/Assembly-CSharp/Verse.AI/JobDriver_HaulToContainer.cs +++ b/Assembly-CSharp/Verse.AI/JobDriver_HaulToContainer.cs @@ -1,6 +1,6 @@ +using RimWorld; using System; using System.Collections.Generic; -using System.Diagnostics; namespace Verse.AI { @@ -22,30 +22,31 @@ private Thing Container public override string GetReport() { - Thing thing; - if (this.pawn.carryTracker.CarriedThing != null) - { - thing = this.pawn.carryTracker.CarriedThing; - } - else - { - thing = base.TargetThingA; - } - return "ReportHaulingTo".Translate(new object[] - { - thing.LabelCap, - base.CurJob.targetB.Thing.LabelShort - }); + Thing thing = null; + thing = ((base.pawn.carryTracker.CarriedThing == null) ? base.TargetThingA : base.pawn.carryTracker.CarriedThing); + return "ReportHaulingTo".Translate(thing.LabelCap, base.CurJob.targetB.Thing.LabelShort); } - [DebuggerHidden] protected override IEnumerable MakeNewToils() { - JobDriver_HaulToContainer.c__Iterator1BB c__Iterator1BB = new JobDriver_HaulToContainer.c__Iterator1BB(); - c__Iterator1BB.<>f__this = this; - JobDriver_HaulToContainer.c__Iterator1BB expr_0E = c__Iterator1BB; - expr_0E.$PC = -2; - return expr_0E; + this.FailOnDestroyedOrNull(TargetIndex.A); + this.FailOnDestroyedNullOrForbidden(TargetIndex.B); + this.FailOn((Func)(() => TransporterUtility.WasLoadingCanceled(((_003CMakeNewToils_003Ec__Iterator1BB)/*Error near IL_0071: stateMachine*/)._003C_003Ef__this.Container))); + yield return Toils_Reserve.Reserve(TargetIndex.A, 1, -1, null); + yield return Toils_Reserve.ReserveQueue(TargetIndex.A, 1, -1, null); + yield return Toils_Reserve.Reserve(TargetIndex.B, 1, -1, null); + yield return Toils_Reserve.ReserveQueue(TargetIndex.B, 1, -1, null); + Toil getToHaulTarget = Toils_Goto.GotoThing(TargetIndex.A, PathEndMode.ClosestTouch).FailOnSomeonePhysicallyInteracting(TargetIndex.A); + yield return getToHaulTarget; + yield return Toils_Construct.UninstallIfMinifiable(TargetIndex.A).FailOnSomeonePhysicallyInteracting(TargetIndex.A); + yield return Toils_Haul.StartCarryThing(TargetIndex.A, false, true); + yield return Toils_Haul.JumpIfAlsoCollectingNextTargetInQueue(getToHaulTarget, TargetIndex.A); + Toil carryToContainer = Toils_Haul.CarryHauledThingToContainer(); + yield return carryToContainer; + yield return Toils_Goto.MoveOffTargetBlueprint(TargetIndex.B); + yield return Toils_Construct.MakeSolidThingFromBlueprintIfNecessary(TargetIndex.B, TargetIndex.C); + yield return Toils_Haul.DepositHauledThingInContainer(TargetIndex.B, TargetIndex.C); + yield return Toils_Haul.JumpToCarryToNextContainerIfPossible(carryToContainer, TargetIndex.C); } } } diff --git a/Assembly-CSharp/Verse.AI/JobDriver_Kill.cs b/Assembly-CSharp/Verse.AI/JobDriver_Kill.cs index a1ab47734..78f711d61 100644 --- a/Assembly-CSharp/Verse.AI/JobDriver_Kill.cs +++ b/Assembly-CSharp/Verse.AI/JobDriver_Kill.cs @@ -1,6 +1,4 @@ -using System; using System.Collections.Generic; -using System.Diagnostics; namespace Verse.AI { @@ -8,14 +6,17 @@ public class JobDriver_Kill : JobDriver { private const TargetIndex VictimInd = TargetIndex.A; - [DebuggerHidden] protected override IEnumerable MakeNewToils() { - JobDriver_Kill.c__Iterator1B7 c__Iterator1B = new JobDriver_Kill.c__Iterator1B7(); - c__Iterator1B.<>f__this = this; - JobDriver_Kill.c__Iterator1B7 expr_0E = c__Iterator1B; - expr_0E.$PC = -2; - return expr_0E; + this.EndOnDespawnedOrNull(TargetIndex.A, JobCondition.Succeeded); + yield return Toils_Reserve.Reserve(TargetIndex.A, 1, -1, null); + yield return Toils_Combat.TrySetJobToUseAttackVerb(); + Toil gotoCastPos = Toils_Combat.GotoCastPosition(TargetIndex.A, false); + yield return gotoCastPos; + Toil jumpIfCannotHit = Toils_Jump.JumpIfTargetNotHittable(TargetIndex.A, gotoCastPos); + yield return jumpIfCannotHit; + yield return Toils_Combat.CastVerb(TargetIndex.A, true); + yield return Toils_Jump.Jump(jumpIfCannotHit); } } } diff --git a/Assembly-CSharp/Verse.AI/JobDriver_ReleasePrisoner.cs b/Assembly-CSharp/Verse.AI/JobDriver_ReleasePrisoner.cs index 46b1c53d1..c2919fd99 100644 --- a/Assembly-CSharp/Verse.AI/JobDriver_ReleasePrisoner.cs +++ b/Assembly-CSharp/Verse.AI/JobDriver_ReleasePrisoner.cs @@ -1,6 +1,6 @@ +using RimWorld; using System; using System.Collections.Generic; -using System.Diagnostics; namespace Verse.AI { @@ -18,14 +18,30 @@ private Pawn Prisoner } } - [DebuggerHidden] protected override IEnumerable MakeNewToils() { - JobDriver_ReleasePrisoner.c__Iterator3A c__Iterator3A = new JobDriver_ReleasePrisoner.c__Iterator3A(); - c__Iterator3A.<>f__this = this; - JobDriver_ReleasePrisoner.c__Iterator3A expr_0E = c__Iterator3A; - expr_0E.$PC = -2; - return expr_0E; + this.FailOnDestroyedOrNull(TargetIndex.A); + this.FailOnBurningImmobile(TargetIndex.B); + this.FailOn((Func)(() => ((Pawn)(Thing)((_003CMakeNewToils_003Ec__Iterator3A)/*Error near IL_0055: stateMachine*/)._003C_003Ef__this.GetActor().CurJob.GetTarget(TargetIndex.A)).guest.interactionMode != PrisonerInteractionModeDefOf.Release)); + this.FailOnDowned(TargetIndex.A); + this.FailOnAggroMentalState(TargetIndex.A); + Toil reserveTargetA = Toils_Reserve.Reserve(TargetIndex.A, 1, -1, null); + yield return reserveTargetA; + yield return Toils_Goto.GotoThing(TargetIndex.A, PathEndMode.ClosestTouch).FailOn((Func)(() => !((_003CMakeNewToils_003Ec__Iterator3A)/*Error near IL_00b0: stateMachine*/)._003C_003Ef__this.Prisoner.IsPrisonerOfColony || !((_003CMakeNewToils_003Ec__Iterator3A)/*Error near IL_00b0: stateMachine*/)._003C_003Ef__this.Prisoner.guest.PrisonerIsSecure)).FailOnSomeonePhysicallyInteracting(TargetIndex.A); + yield return Toils_Haul.StartCarryThing(TargetIndex.A, false, false); + Toil carryToCell = Toils_Haul.CarryHauledThingToCell(TargetIndex.B); + yield return carryToCell; + yield return Toils_Haul.PlaceHauledThingInCell(TargetIndex.B, carryToCell, false); + yield return new Toil + { + initAction = (Action)delegate + { + Pawn actor = ((_003CMakeNewToils_003Ec__Iterator3A)/*Error near IL_0146: stateMachine*/)._003CsetReleased_003E__2.actor; + Job curJob = actor.jobs.curJob; + Pawn p = curJob.targetA.Thing as Pawn; + GenGuest.PrisonerRelease(p); + } + }; } } } diff --git a/Assembly-CSharp/Verse.AI/JobDriver_TakeInventory.cs b/Assembly-CSharp/Verse.AI/JobDriver_TakeInventory.cs index a9eba5ce7..2dc9eafc0 100644 --- a/Assembly-CSharp/Verse.AI/JobDriver_TakeInventory.cs +++ b/Assembly-CSharp/Verse.AI/JobDriver_TakeInventory.cs @@ -1,19 +1,24 @@ using System; using System.Collections.Generic; -using System.Diagnostics; namespace Verse.AI { public class JobDriver_TakeInventory : JobDriver { - [DebuggerHidden] protected override IEnumerable MakeNewToils() { - JobDriver_TakeInventory.c__Iterator1B3 c__Iterator1B = new JobDriver_TakeInventory.c__Iterator1B3(); - c__Iterator1B.<>f__this = this; - JobDriver_TakeInventory.c__Iterator1B3 expr_0E = c__Iterator1B; - expr_0E.$PC = -2; - return expr_0E; + yield return Toils_Reserve.Reserve(TargetIndex.A, 1, -1, null); + Toil gotoThing = new Toil + { + initAction = (Action)delegate + { + ((_003CMakeNewToils_003Ec__Iterator1B3)/*Error near IL_0055: stateMachine*/)._003C_003Ef__this.pawn.pather.StartPath(((_003CMakeNewToils_003Ec__Iterator1B3)/*Error near IL_0055: stateMachine*/)._003C_003Ef__this.TargetThingA, PathEndMode.ClosestTouch); + }, + defaultCompleteMode = ToilCompleteMode.PatherArrival + }; + gotoThing.FailOnDespawnedNullOrForbidden(TargetIndex.A); + yield return gotoThing; + yield return Toils_Haul.TakeToInventory(TargetIndex.A, base.CurJob.count); } } } diff --git a/Assembly-CSharp/Verse.AI/JobDriver_Wait.cs b/Assembly-CSharp/Verse.AI/JobDriver_Wait.cs index 03401f1b7..97188adc9 100644 --- a/Assembly-CSharp/Verse.AI/JobDriver_Wait.cs +++ b/Assembly-CSharp/Verse.AI/JobDriver_Wait.cs @@ -1,7 +1,6 @@ using RimWorld; using System; using System.Collections.Generic; -using System.Diagnostics; namespace Verse.AI { @@ -11,25 +10,43 @@ public class JobDriver_Wait : JobDriver public override string GetReport() { - if (base.CurJob.def != JobDefOf.WaitCombat) + if (base.CurJob.def == JobDefOf.WaitCombat) { + if (base.pawn.RaceProps.Humanlike && base.pawn.story.WorkTagIsDisabled(WorkTags.Violent)) + { + return "ReportStanding".Translate(); + } return base.GetReport(); } - if (this.pawn.RaceProps.Humanlike && this.pawn.story.WorkTagIsDisabled(WorkTags.Violent)) - { - return "ReportStanding".Translate(); - } return base.GetReport(); } - [DebuggerHidden] protected override IEnumerable MakeNewToils() { - JobDriver_Wait.c__Iterator1B4 c__Iterator1B = new JobDriver_Wait.c__Iterator1B4(); - c__Iterator1B.<>f__this = this; - JobDriver_Wait.c__Iterator1B4 expr_0E = c__Iterator1B; - expr_0E.$PC = -2; - return expr_0E; + Toil wait = new Toil + { + initAction = (Action)delegate + { + ((_003CMakeNewToils_003Ec__Iterator1B4)/*Error near IL_0032: stateMachine*/)._003C_003Ef__this.Map.pawnDestinationManager.ReserveDestinationFor(((_003CMakeNewToils_003Ec__Iterator1B4)/*Error near IL_0032: stateMachine*/)._003C_003Ef__this.pawn, ((_003CMakeNewToils_003Ec__Iterator1B4)/*Error near IL_0032: stateMachine*/)._003C_003Ef__this.pawn.Position); + ((_003CMakeNewToils_003Ec__Iterator1B4)/*Error near IL_0032: stateMachine*/)._003C_003Ef__this.pawn.pather.StopDead(); + ((_003CMakeNewToils_003Ec__Iterator1B4)/*Error near IL_0032: stateMachine*/)._003C_003Ef__this.CheckForAutoAttack(); + }, + tickAction = (Action)delegate + { + if (((_003CMakeNewToils_003Ec__Iterator1B4)/*Error near IL_0049: stateMachine*/)._003C_003Ef__this.CurJob.expiryInterval == -1 && ((_003CMakeNewToils_003Ec__Iterator1B4)/*Error near IL_0049: stateMachine*/)._003C_003Ef__this.CurJob.def == JobDefOf.WaitCombat && !((_003CMakeNewToils_003Ec__Iterator1B4)/*Error near IL_0049: stateMachine*/)._003C_003Ef__this.pawn.Drafted) + { + Log.Error(((_003CMakeNewToils_003Ec__Iterator1B4)/*Error near IL_0049: stateMachine*/)._003C_003Ef__this.pawn + " in eternal WaitCombat without being drafted."); + ((_003CMakeNewToils_003Ec__Iterator1B4)/*Error near IL_0049: stateMachine*/)._003C_003Ef__this.ReadyForNextToil(); + } + else if ((Find.TickManager.TicksGame + ((_003CMakeNewToils_003Ec__Iterator1B4)/*Error near IL_0049: stateMachine*/)._003C_003Ef__this.pawn.thingIDNumber) % 4 == 0) + { + ((_003CMakeNewToils_003Ec__Iterator1B4)/*Error near IL_0049: stateMachine*/)._003C_003Ef__this.CheckForAutoAttack(); + } + } + }; + this.DecorateWaitToil(wait); + wait.defaultCompleteMode = ToilCompleteMode.Never; + yield return wait; } public virtual void DecorateWaitToil(Toil wait) @@ -38,7 +55,7 @@ public virtual void DecorateWaitToil(Toil wait) public override void Notify_StanceChanged() { - if (this.pawn.stances.curStance is Stance_Mobile) + if (base.pawn.stances.curStance is Stance_Mobile) { this.CheckForAutoAttack(); } @@ -46,23 +63,17 @@ public override void Notify_StanceChanged() private void CheckForAutoAttack() { - if (this.pawn.Downed) - { - return; - } - if (this.pawn.stances.FullBodyBusy) - { - return; - } - bool flag = this.pawn.story == null || !this.pawn.story.WorkTagIsDisabled(WorkTags.Violent); - bool flag2 = this.pawn.RaceProps.ToolUser && this.pawn.Faction == Faction.OfPlayer && !this.pawn.story.WorkTagIsDisabled(WorkTags.Firefighting); - if (flag || flag2) + if (!base.pawn.Downed && !base.pawn.stances.FullBodyBusy) { + bool flag = base.pawn.story == null || !base.pawn.story.WorkTagIsDisabled(WorkTags.Violent); + bool flag2 = base.pawn.RaceProps.ToolUser && base.pawn.Faction == Faction.OfPlayer && !base.pawn.story.WorkTagIsDisabled(WorkTags.Firefighting); + if (!flag && !flag2) + return; Fire fire = null; for (int i = 0; i < 9; i++) { - IntVec3 c = this.pawn.Position + GenAdj.AdjacentCellsAndInside[i]; - if (c.InBounds(this.pawn.Map)) + IntVec3 c = base.pawn.Position + GenAdj.AdjacentCellsAndInside[i]; + if (c.InBounds(base.pawn.Map)) { List thingList = c.GetThingList(base.Map); for (int j = 0; j < thingList.Count; j++) @@ -70,16 +81,16 @@ private void CheckForAutoAttack() if (flag) { Pawn pawn = thingList[j] as Pawn; - if (pawn != null && !pawn.Downed && this.pawn.HostileTo(pawn)) + if (pawn != null && !pawn.Downed && base.pawn.HostileTo(pawn)) { - this.pawn.meleeVerbs.TryMeleeAttack(pawn, null, false); + base.pawn.meleeVerbs.TryMeleeAttack(pawn, null, false); return; } } if (flag2) { Fire fire2 = thingList[j] as Fire; - if (fire2 != null && (fire == null || fire2.fireSize < fire.fireSize || i == 8) && (fire2.parent == null || fire2.parent != this.pawn)) + if (fire2 != null && (fire == null || fire2.fireSize < fire.fireSize || i == 8) && (fire2.parent == null || fire2.parent != base.pawn)) { fire = fire2; } @@ -87,27 +98,27 @@ private void CheckForAutoAttack() } } } - if (fire != null && (!this.pawn.InMentalState || this.pawn.MentalState.def.allowBeatfire)) + if (fire != null && (!base.pawn.InMentalState || base.pawn.MentalState.def.allowBeatfire)) { - this.pawn.natives.TryBeatFire(fire); - return; + base.pawn.natives.TryBeatFire(fire); } - if (flag && this.pawn.Faction != null && this.pawn.jobs.curJob.def == JobDefOf.WaitCombat && (this.pawn.drafter == null || this.pawn.drafter.FireAtWill)) + else if (flag && base.pawn.Faction != null && base.pawn.jobs.curJob.def == JobDefOf.WaitCombat) { - bool allowManualCastWeapons = !this.pawn.IsColonist; - Verb verb = this.pawn.TryGetAttackVerb(allowManualCastWeapons); + if (base.pawn.drafter != null && !base.pawn.drafter.FireAtWill) + return; + bool allowManualCastWeapons = !base.pawn.IsColonist; + Verb verb = base.pawn.TryGetAttackVerb(allowManualCastWeapons); if (verb != null && !verb.verbProps.MeleeRange) { TargetScanFlags targetScanFlags = TargetScanFlags.NeedLOSToPawns | TargetScanFlags.NeedLOSToNonPawns | TargetScanFlags.NeedThreat; if (verb.verbProps.ai_IsIncendiary) { - targetScanFlags |= TargetScanFlags.NeedNonBurning; + targetScanFlags = (TargetScanFlags)(byte)((int)targetScanFlags | 16); } - Thing thing = (Thing)AttackTargetFinder.BestShootTargetFromCurrentPosition(this.pawn, null, verb.verbProps.range, verb.verbProps.minRange, targetScanFlags); + Thing thing = (Thing)AttackTargetFinder.BestShootTargetFromCurrentPosition(base.pawn, null, verb.verbProps.range, verb.verbProps.minRange, targetScanFlags); if (thing != null) { - this.pawn.equipment.TryStartAttack(thing); - return; + base.pawn.equipment.TryStartAttack(thing); } } } diff --git a/Assembly-CSharp/Verse.AI/JobDriver_WaitDowned.cs b/Assembly-CSharp/Verse.AI/JobDriver_WaitDowned.cs index 391ab4c34..0c886afd5 100644 --- a/Assembly-CSharp/Verse.AI/JobDriver_WaitDowned.cs +++ b/Assembly-CSharp/Verse.AI/JobDriver_WaitDowned.cs @@ -7,7 +7,7 @@ public class JobDriver_WaitDowned : JobDriver_Wait public override void DecorateWaitToil(Toil wait) { base.DecorateWaitToil(wait); - wait.AddFailCondition(() => !this.pawn.Downed); + wait.AddFailCondition((Func)(() => !base.pawn.Downed)); } } } diff --git a/Assembly-CSharp/Verse.AI/JobDriver_WaitMaintainPosture.cs b/Assembly-CSharp/Verse.AI/JobDriver_WaitMaintainPosture.cs index 2f525b1e4..1429fe858 100644 --- a/Assembly-CSharp/Verse.AI/JobDriver_WaitMaintainPosture.cs +++ b/Assembly-CSharp/Verse.AI/JobDriver_WaitMaintainPosture.cs @@ -1,5 +1,4 @@ using RimWorld; -using System; namespace Verse.AI { @@ -18,7 +17,7 @@ public override PawnPosture Posture public override void Notify_LastPosture(PawnPosture posture, LayingDownState layingDown) { this.lastPosture = posture; - this.layingDown = layingDown; + base.layingDown = layingDown; } public override void ExposeData() diff --git a/Assembly-CSharp/Verse.AI/JobFailReason.cs b/Assembly-CSharp/Verse.AI/JobFailReason.cs index deb6135fb..4eb191600 100644 --- a/Assembly-CSharp/Verse.AI/JobFailReason.cs +++ b/Assembly-CSharp/Verse.AI/JobFailReason.cs @@ -1,5 +1,3 @@ -using System; - namespace Verse.AI { public static class JobFailReason @@ -29,7 +27,7 @@ public static void Is(string reason) public static void Clear() { - JobFailReason.lastReason = null; + JobFailReason.lastReason = (string)null; } } } diff --git a/Assembly-CSharp/Verse.AI/JobGiver_ExitMap.cs b/Assembly-CSharp/Verse.AI/JobGiver_ExitMap.cs index 9722bd58b..6dbe61dad 100644 --- a/Assembly-CSharp/Verse.AI/JobGiver_ExitMap.cs +++ b/Assembly-CSharp/Verse.AI/JobGiver_ExitMap.cs @@ -1,5 +1,4 @@ using RimWorld; -using System; namespace Verse.AI { @@ -33,17 +32,17 @@ protected override Job TryGiveJob(Pawn pawn) { flag = true; } - IntVec3 c; + IntVec3 c = default(IntVec3); if (!this.TryFindGoodExitDest(pawn, flag, out c)) { return null; } if (flag) { - using (PawnPath pawnPath = pawn.Map.pathFinder.FindPath(pawn.Position, c, TraverseParms.For(pawn, Danger.Deadly, TraverseMode.PassAllDestroyableThings, false), PathEndMode.OnCell)) + using (PawnPath path = pawn.Map.pathFinder.FindPath(pawn.Position, c, TraverseParms.For(pawn, Danger.Deadly, TraverseMode.PassAllDestroyableThings, false), PathEndMode.OnCell)) { - IntVec3 cellBeforeBlocker; - Thing thing = pawnPath.FirstBlockingBuilding(out cellBeforeBlocker, pawn); + IntVec3 cellBeforeBlocker = default(IntVec3); + Thing thing = path.FirstBlockingBuilding(out cellBeforeBlocker, pawn); if (thing != null) { Job job = DigUtility.PassBlockerJob(pawn, thing, cellBeforeBlocker, true); @@ -54,14 +53,13 @@ protected override Job TryGiveJob(Pawn pawn) } } } - return new Job(JobDefOf.Goto, c) - { - exitMapOnArrival = true, - failIfCantJoinOrCreateCaravan = this.failIfCantJoinOrCreateCaravan, - locomotionUrgency = PawnUtility.ResolveLocomotion(pawn, this.defaultLocomotion, LocomotionUrgency.Jog), - expiryInterval = this.jobMaxDuration, - canBash = this.canBash - }; + Job job2 = new Job(JobDefOf.Goto, c); + job2.exitMapOnArrival = true; + job2.failIfCantJoinOrCreateCaravan = this.failIfCantJoinOrCreateCaravan; + job2.locomotionUrgency = PawnUtility.ResolveLocomotion(pawn, this.defaultLocomotion, LocomotionUrgency.Jog); + job2.expiryInterval = this.jobMaxDuration; + job2.canBash = this.canBash; + return job2; } protected abstract bool TryFindGoodExitDest(Pawn pawn, bool canDig, out IntVec3 dest); diff --git a/Assembly-CSharp/Verse.AI/JobGiver_ExitMapBest.cs b/Assembly-CSharp/Verse.AI/JobGiver_ExitMapBest.cs index 463d9c8ee..58cde6249 100644 --- a/Assembly-CSharp/Verse.AI/JobGiver_ExitMapBest.cs +++ b/Assembly-CSharp/Verse.AI/JobGiver_ExitMapBest.cs @@ -1,5 +1,4 @@ using RimWorld; -using System; namespace Verse.AI { @@ -7,7 +6,7 @@ public class JobGiver_ExitMapBest : JobGiver_ExitMap { protected override bool TryFindGoodExitDest(Pawn pawn, bool canDig, out IntVec3 spot) { - TraverseMode mode = (!canDig) ? TraverseMode.ByPawn : TraverseMode.PassAllDestroyableThings; + TraverseMode mode = (TraverseMode)(canDig ? 3 : 0); return RCellFinder.TryFindBestExitSpot(pawn, out spot, mode); } } diff --git a/Assembly-CSharp/Verse.AI/JobGiver_ExitMapPanic.cs b/Assembly-CSharp/Verse.AI/JobGiver_ExitMapPanic.cs index 1e100e2de..09e486259 100644 --- a/Assembly-CSharp/Verse.AI/JobGiver_ExitMapPanic.cs +++ b/Assembly-CSharp/Verse.AI/JobGiver_ExitMapPanic.cs @@ -1,12 +1,10 @@ -using System; - namespace Verse.AI { public class JobGiver_ExitMapPanic : JobGiver_ExitMapBest { public JobGiver_ExitMapPanic() { - this.canBash = true; + base.canBash = true; } } } diff --git a/Assembly-CSharp/Verse.AI/JobGiver_ExitMapRandom.cs b/Assembly-CSharp/Verse.AI/JobGiver_ExitMapRandom.cs index bac2ea4dc..861d419de 100644 --- a/Assembly-CSharp/Verse.AI/JobGiver_ExitMapRandom.cs +++ b/Assembly-CSharp/Verse.AI/JobGiver_ExitMapRandom.cs @@ -1,5 +1,4 @@ using RimWorld; -using System; namespace Verse.AI { @@ -7,7 +6,7 @@ public class JobGiver_ExitMapRandom : JobGiver_ExitMap { protected override bool TryFindGoodExitDest(Pawn pawn, bool canDig, out IntVec3 spot) { - TraverseMode mode = (!canDig) ? TraverseMode.ByPawn : TraverseMode.PassAllDestroyableThings; + TraverseMode mode = (TraverseMode)(canDig ? 3 : 0); return RCellFinder.TryFindRandomExitSpot(pawn, out spot, mode); } } diff --git a/Assembly-CSharp/Verse.AI/JobGiver_ForcedGoto.cs b/Assembly-CSharp/Verse.AI/JobGiver_ForcedGoto.cs index e1e205287..c2e39cf42 100644 --- a/Assembly-CSharp/Verse.AI/JobGiver_ForcedGoto.cs +++ b/Assembly-CSharp/Verse.AI/JobGiver_ForcedGoto.cs @@ -1,5 +1,4 @@ using RimWorld; -using System; namespace Verse.AI { @@ -17,10 +16,9 @@ protected override Job TryGiveJob(Pawn pawn) pawn.mindState.forcedGotoPosition = IntVec3.Invalid; return null; } - return new Job(JobDefOf.Goto, forcedGotoPosition) - { - locomotionUrgency = LocomotionUrgency.Walk - }; + Job job = new Job(JobDefOf.Goto, forcedGotoPosition); + job.locomotionUrgency = LocomotionUrgency.Walk; + return job; } } } diff --git a/Assembly-CSharp/Verse.AI/JobGiver_Idle.cs b/Assembly-CSharp/Verse.AI/JobGiver_Idle.cs index 8c628a50b..9975e84ed 100644 --- a/Assembly-CSharp/Verse.AI/JobGiver_Idle.cs +++ b/Assembly-CSharp/Verse.AI/JobGiver_Idle.cs @@ -1,5 +1,4 @@ using RimWorld; -using System; namespace Verse.AI { @@ -16,10 +15,9 @@ public override ThinkNode DeepCopy(bool resolve = true) protected override Job TryGiveJob(Pawn pawn) { - return new Job(JobDefOf.Wait) - { - expiryInterval = this.ticks - }; + Job job = new Job(JobDefOf.Wait); + job.expiryInterval = this.ticks; + return job; } } } diff --git a/Assembly-CSharp/Verse.AI/JobGiver_IdleError.cs b/Assembly-CSharp/Verse.AI/JobGiver_IdleError.cs index 55fc95d5a..f817a5862 100644 --- a/Assembly-CSharp/Verse.AI/JobGiver_IdleError.cs +++ b/Assembly-CSharp/Verse.AI/JobGiver_IdleError.cs @@ -1,5 +1,4 @@ using RimWorld; -using System; namespace Verse.AI { @@ -10,10 +9,9 @@ public class JobGiver_IdleError : ThinkNode_JobGiver protected override Job TryGiveJob(Pawn pawn) { Log.ErrorOnce(pawn + " issued IdleError wait job. The behavior tree should never get here.", 532983); - return new Job(JobDefOf.Wait) - { - expiryInterval = 100 - }; + Job job = new Job(JobDefOf.Wait); + job.expiryInterval = 100; + return job; } } } diff --git a/Assembly-CSharp/Verse.AI/JobGiver_IdleForever.cs b/Assembly-CSharp/Verse.AI/JobGiver_IdleForever.cs index e4b726ee2..cecd2c432 100644 --- a/Assembly-CSharp/Verse.AI/JobGiver_IdleForever.cs +++ b/Assembly-CSharp/Verse.AI/JobGiver_IdleForever.cs @@ -1,5 +1,4 @@ using RimWorld; -using System; namespace Verse.AI { diff --git a/Assembly-CSharp/Verse.AI/JobGiver_Orders.cs b/Assembly-CSharp/Verse.AI/JobGiver_Orders.cs index 20dbcf9aa..4d31837f2 100644 --- a/Assembly-CSharp/Verse.AI/JobGiver_Orders.cs +++ b/Assembly-CSharp/Verse.AI/JobGiver_Orders.cs @@ -1,5 +1,4 @@ using RimWorld; -using System; namespace Verse.AI { diff --git a/Assembly-CSharp/Verse.AI/JobGiver_RunRandom.cs b/Assembly-CSharp/Verse.AI/JobGiver_RunRandom.cs index fef78ecbb..b840cc617 100644 --- a/Assembly-CSharp/Verse.AI/JobGiver_RunRandom.cs +++ b/Assembly-CSharp/Verse.AI/JobGiver_RunRandom.cs @@ -1,14 +1,12 @@ -using System; - namespace Verse.AI { public class JobGiver_RunRandom : JobGiver_Wander { public JobGiver_RunRandom() { - this.wanderRadius = 7f; - this.ticksBetweenWandersRange = new IntRange(5, 10); - this.locomotionUrgency = LocomotionUrgency.Sprint; + base.wanderRadius = 7f; + base.ticksBetweenWandersRange = new IntRange(5, 10); + base.locomotionUrgency = LocomotionUrgency.Sprint; } protected override IntVec3 GetWanderRoot(Pawn pawn) diff --git a/Assembly-CSharp/Verse.AI/JobGiver_Wander.cs b/Assembly-CSharp/Verse.AI/JobGiver_Wander.cs index 6880c2568..98e8cbd22 100644 --- a/Assembly-CSharp/Verse.AI/JobGiver_Wander.cs +++ b/Assembly-CSharp/Verse.AI/JobGiver_Wander.cs @@ -32,10 +32,9 @@ protected override Job TryGiveJob(Pawn pawn) pawn.mindState.nextMoveOrderIsWait = !pawn.mindState.nextMoveOrderIsWait; if (nextMoveOrderIsWait) { - return new Job(JobDefOf.WaitWander) - { - expiryInterval = this.ticksBetweenWandersRange.RandomInRange - }; + Job job = new Job(JobDefOf.WaitWander); + job.expiryInterval = this.ticksBetweenWandersRange.RandomInRange; + return job; } IntVec3 exactWanderDest = this.GetExactWanderDest(pawn); if (!exactWanderDest.IsValid) @@ -44,10 +43,9 @@ protected override Job TryGiveJob(Pawn pawn) return null; } pawn.Map.pawnDestinationManager.ReserveDestinationFor(pawn, exactWanderDest); - return new Job(JobDefOf.GotoWander, exactWanderDest) - { - locomotionUrgency = this.locomotionUrgency - }; + Job job2 = new Job(JobDefOf.GotoWander, exactWanderDest); + job2.locomotionUrgency = this.locomotionUrgency; + return job2; } protected virtual IntVec3 GetExactWanderDest(Pawn pawn) diff --git a/Assembly-CSharp/Verse.AI/JobGiver_WanderAnywhere.cs b/Assembly-CSharp/Verse.AI/JobGiver_WanderAnywhere.cs index 71687e852..698ec3efa 100644 --- a/Assembly-CSharp/Verse.AI/JobGiver_WanderAnywhere.cs +++ b/Assembly-CSharp/Verse.AI/JobGiver_WanderAnywhere.cs @@ -1,14 +1,12 @@ -using System; - namespace Verse.AI { public class JobGiver_WanderAnywhere : JobGiver_Wander { public JobGiver_WanderAnywhere() { - this.wanderRadius = 7f; - this.locomotionUrgency = LocomotionUrgency.Walk; - this.ticksBetweenWandersRange = new IntRange(125, 200); + base.wanderRadius = 7f; + base.locomotionUrgency = LocomotionUrgency.Walk; + base.ticksBetweenWandersRange = new IntRange(125, 200); } protected override IntVec3 GetWanderRoot(Pawn pawn) diff --git a/Assembly-CSharp/Verse.AI/JobGiver_WanderCurrentRoom.cs b/Assembly-CSharp/Verse.AI/JobGiver_WanderCurrentRoom.cs index 37e91ba60..9e4773649 100644 --- a/Assembly-CSharp/Verse.AI/JobGiver_WanderCurrentRoom.cs +++ b/Assembly-CSharp/Verse.AI/JobGiver_WanderCurrentRoom.cs @@ -6,10 +6,10 @@ public class JobGiver_WanderCurrentRoom : JobGiver_Wander { public JobGiver_WanderCurrentRoom() { - this.wanderRadius = 7f; - this.ticksBetweenWandersRange = new IntRange(125, 200); - this.locomotionUrgency = LocomotionUrgency.Amble; - this.wanderDestValidator = ((Pawn pawn, IntVec3 loc) => WanderRoomUtility.IsValidWanderDest(pawn, loc, this.GetWanderRoot(pawn))); + base.wanderRadius = 7f; + base.ticksBetweenWandersRange = new IntRange(125, 200); + base.locomotionUrgency = LocomotionUrgency.Amble; + base.wanderDestValidator = (Func)((Pawn pawn, IntVec3 loc) => WanderRoomUtility.IsValidWanderDest(pawn, loc, this.GetWanderRoot(pawn))); } protected override IntVec3 GetWanderRoot(Pawn pawn) diff --git a/Assembly-CSharp/Verse.AI/JobGiver_WanderHerd.cs b/Assembly-CSharp/Verse.AI/JobGiver_WanderHerd.cs index ac31e6d2c..3e9f4b3ff 100644 --- a/Assembly-CSharp/Verse.AI/JobGiver_WanderHerd.cs +++ b/Assembly-CSharp/Verse.AI/JobGiver_WanderHerd.cs @@ -10,44 +10,44 @@ public class JobGiver_WanderHerd : JobGiver_Wander public JobGiver_WanderHerd() { - this.wanderRadius = 5f; - this.ticksBetweenWandersRange = new IntRange(125, 200); + base.wanderRadius = 5f; + base.ticksBetweenWandersRange = new IntRange(125, 200); } protected override IntVec3 GetWanderRoot(Pawn pawn) { - Predicate validator = delegate(Thing t) + Predicate validator = (Predicate)delegate(Thing t) { - if (((Pawn)t).RaceProps != pawn.RaceProps || t == pawn) + if (((Pawn)t).RaceProps == pawn.RaceProps && t != pawn) { - return false; - } - if (t.Faction != pawn.Faction) - { - return false; - } - if (t.Position.IsForbidden(pawn)) - { - return false; - } - if (!pawn.CanReach(t, PathEndMode.OnCell, Danger.Deadly, false, TraverseMode.ByPawn)) - { - return false; - } - if (Rand.Value < 0.5f) - { - return false; - } - List allPawnsSpawned = pawn.Map.mapPawns.AllPawnsSpawned; - for (int i = 0; i < allPawnsSpawned.Count; i++) - { - Pawn pawn2 = allPawnsSpawned[i]; - if (pawn2.RaceProps.Humanlike && (pawn2.Position - t.Position).LengthHorizontalSquared < 225) + if (t.Faction != pawn.Faction) { return false; } + if (t.Position.IsForbidden(pawn)) + { + return false; + } + if (!pawn.CanReach(t, PathEndMode.OnCell, Danger.Deadly, false, TraverseMode.ByPawn)) + { + return false; + } + if (Rand.Value < 0.5) + { + return false; + } + List allPawnsSpawned = pawn.Map.mapPawns.AllPawnsSpawned; + for (int i = 0; i < allPawnsSpawned.Count; i++) + { + Pawn pawn2 = allPawnsSpawned[i]; + if (pawn2.RaceProps.Humanlike && (pawn2.Position - t.Position).LengthHorizontalSquared < 225) + { + return false; + } + } + return true; } - return true; + return false; }; Thing thing = GenClosest.ClosestThingReachable(pawn.Position, pawn.Map, ThingRequest.ForGroup(ThingRequestGroup.Pawn), PathEndMode.OnCell, TraverseParms.For(pawn, Danger.Deadly, TraverseMode.ByPawn, false), 35f, validator, null, 13, -1, false, RegionType.Set_Passable, false); if (thing != null) diff --git a/Assembly-CSharp/Verse.AI/JobGiver_WanderMapEdge.cs b/Assembly-CSharp/Verse.AI/JobGiver_WanderMapEdge.cs index 5ee779e75..330c1b6a4 100644 --- a/Assembly-CSharp/Verse.AI/JobGiver_WanderMapEdge.cs +++ b/Assembly-CSharp/Verse.AI/JobGiver_WanderMapEdge.cs @@ -1,5 +1,4 @@ using RimWorld; -using System; namespace Verse.AI { @@ -7,13 +6,13 @@ public class JobGiver_WanderMapEdge : JobGiver_Wander { public JobGiver_WanderMapEdge() { - this.wanderRadius = 7f; - this.ticksBetweenWandersRange = new IntRange(50, 125); + base.wanderRadius = 7f; + base.ticksBetweenWandersRange = new IntRange(50, 125); } protected override IntVec3 GetWanderRoot(Pawn pawn) { - IntVec3 result; + IntVec3 result = default(IntVec3); if (RCellFinder.TryFindBestExitSpot(pawn, out result, TraverseMode.ByPawn)) { return result; diff --git a/Assembly-CSharp/Verse.AI/JobGiver_WanderNearDutyLocation.cs b/Assembly-CSharp/Verse.AI/JobGiver_WanderNearDutyLocation.cs index 464635821..d7728ccdd 100644 --- a/Assembly-CSharp/Verse.AI/JobGiver_WanderNearDutyLocation.cs +++ b/Assembly-CSharp/Verse.AI/JobGiver_WanderNearDutyLocation.cs @@ -1,13 +1,11 @@ -using System; - namespace Verse.AI { public class JobGiver_WanderNearDutyLocation : JobGiver_Wander { public JobGiver_WanderNearDutyLocation() { - this.wanderRadius = 7f; - this.ticksBetweenWandersRange = new IntRange(125, 200); + base.wanderRadius = 7f; + base.ticksBetweenWandersRange = new IntRange(125, 200); } protected override IntVec3 GetWanderRoot(Pawn pawn) diff --git a/Assembly-CSharp/Verse.AI/JobGiver_WanderNearFallbackLocation.cs b/Assembly-CSharp/Verse.AI/JobGiver_WanderNearFallbackLocation.cs index 0d095b932..d77d82123 100644 --- a/Assembly-CSharp/Verse.AI/JobGiver_WanderNearFallbackLocation.cs +++ b/Assembly-CSharp/Verse.AI/JobGiver_WanderNearFallbackLocation.cs @@ -1,13 +1,11 @@ -using System; - namespace Verse.AI { public class JobGiver_WanderNearFallbackLocation : JobGiver_Wander { public JobGiver_WanderNearFallbackLocation() { - this.wanderRadius = 7f; - this.ticksBetweenWandersRange = new IntRange(125, 200); + base.wanderRadius = 7f; + base.ticksBetweenWandersRange = new IntRange(125, 200); } protected override IntVec3 GetWanderRoot(Pawn pawn) diff --git a/Assembly-CSharp/Verse.AI/JobGiver_WanderNearMaster.cs b/Assembly-CSharp/Verse.AI/JobGiver_WanderNearMaster.cs index 2000e1e23..ce936ad35 100644 --- a/Assembly-CSharp/Verse.AI/JobGiver_WanderNearMaster.cs +++ b/Assembly-CSharp/Verse.AI/JobGiver_WanderNearMaster.cs @@ -1,13 +1,11 @@ -using System; - namespace Verse.AI { public class JobGiver_WanderNearMaster : JobGiver_Wander { public JobGiver_WanderNearMaster() { - this.wanderRadius = 3f; - this.ticksBetweenWandersRange = new IntRange(125, 200); + base.wanderRadius = 3f; + base.ticksBetweenWandersRange = new IntRange(125, 200); } protected override IntVec3 GetWanderRoot(Pawn pawn) diff --git a/Assembly-CSharp/Verse.AI/JobGiver_WanderOwnRoom.cs b/Assembly-CSharp/Verse.AI/JobGiver_WanderOwnRoom.cs index 9aaffd4ea..4109d5bff 100644 --- a/Assembly-CSharp/Verse.AI/JobGiver_WanderOwnRoom.cs +++ b/Assembly-CSharp/Verse.AI/JobGiver_WanderOwnRoom.cs @@ -6,10 +6,10 @@ public class JobGiver_WanderOwnRoom : JobGiver_Wander { public JobGiver_WanderOwnRoom() { - this.wanderRadius = 7f; - this.ticksBetweenWandersRange = new IntRange(300, 600); - this.locomotionUrgency = LocomotionUrgency.Amble; - this.wanderDestValidator = ((Pawn pawn, IntVec3 loc) => WanderRoomUtility.IsValidWanderDest(pawn, loc, this.GetWanderRoot(pawn))); + base.wanderRadius = 7f; + base.ticksBetweenWandersRange = new IntRange(300, 600); + base.locomotionUrgency = LocomotionUrgency.Amble; + base.wanderDestValidator = (Func)((Pawn pawn, IntVec3 loc) => WanderRoomUtility.IsValidWanderDest(pawn, loc, this.GetWanderRoot(pawn))); } protected override IntVec3 GetWanderRoot(Pawn pawn) diff --git a/Assembly-CSharp/Verse.AI/JobIssueParams.cs b/Assembly-CSharp/Verse.AI/JobIssueParams.cs index d5325584b..b472cce3c 100644 --- a/Assembly-CSharp/Verse.AI/JobIssueParams.cs +++ b/Assembly-CSharp/Verse.AI/JobIssueParams.cs @@ -1,5 +1,3 @@ -using System; - namespace Verse.AI { public struct JobIssueParams diff --git a/Assembly-CSharp/Verse.AI/JobQueue.cs b/Assembly-CSharp/Verse.AI/JobQueue.cs index a45f27efa..617657bea 100644 --- a/Assembly-CSharp/Verse.AI/JobQueue.cs +++ b/Assembly-CSharp/Verse.AI/JobQueue.cs @@ -1,4 +1,3 @@ -using System; using System.Collections.Generic; namespace Verse.AI @@ -43,19 +42,19 @@ public void ExposeData() Scribe_Collections.Look(ref this.jobs, "jobs", LookMode.Deep, new object[0]); } - public void EnqueueFirst(Job j, JobTag? tag = null) + public void EnqueueFirst(Job j, JobTag? tag = default(JobTag?)) { this.jobs.Insert(0, new QueuedJob(j, tag)); } - public void EnqueueLast(Job j, JobTag? tag = null) + public void EnqueueLast(Job j, JobTag? tag = default(JobTag?)) { this.jobs.Add(new QueuedJob(j, tag)); } public QueuedJob Dequeue() { - if (this.jobs.NullOrEmpty()) + if (this.jobs.NullOrEmpty()) { return null; } diff --git a/Assembly-CSharp/Verse.AI/JobTag.cs b/Assembly-CSharp/Verse.AI/JobTag.cs index ff399a04f..2f8fbf126 100644 --- a/Assembly-CSharp/Verse.AI/JobTag.cs +++ b/Assembly-CSharp/Verse.AI/JobTag.cs @@ -1,24 +1,22 @@ -using System; - namespace Verse.AI { public enum JobTag : byte { - Misc, - MiscWork, - Fieldwork, - Idle, - InMentalState, - SatisfyingNeeds, - DraftedOrder, - UnspecifiedLordDuty, - WaitingForOthersToFinishGatheringItems, - TuckedIntoBed, - RestingForMedicalReasons, - ChangingApparel, - Escaping, - JoiningCaravan, - TrainedAnimalBehavior, - UnloadingOwnInventory + Misc = 0, + MiscWork = 1, + Fieldwork = 2, + Idle = 3, + InMentalState = 4, + SatisfyingNeeds = 5, + DraftedOrder = 6, + UnspecifiedLordDuty = 7, + WaitingForOthersToFinishGatheringItems = 8, + TuckedIntoBed = 9, + RestingForMedicalReasons = 10, + ChangingApparel = 11, + Escaping = 12, + JoiningCaravan = 13, + TrainedAnimalBehavior = 14, + UnloadingOwnInventory = 15 } } diff --git a/Assembly-CSharp/Verse.AI/LayingDownState.cs b/Assembly-CSharp/Verse.AI/LayingDownState.cs index c5c53747f..d20a08219 100644 --- a/Assembly-CSharp/Verse.AI/LayingDownState.cs +++ b/Assembly-CSharp/Verse.AI/LayingDownState.cs @@ -1,11 +1,9 @@ -using System; - namespace Verse.AI { public enum LayingDownState { - NotLaying, - LayingSurface, - LayingInBed + NotLaying = 0, + LayingSurface = 1, + LayingInBed = 2 } } diff --git a/Assembly-CSharp/Verse.AI/LocomotionUrgency.cs b/Assembly-CSharp/Verse.AI/LocomotionUrgency.cs index d3425dfcd..28e7a798e 100644 --- a/Assembly-CSharp/Verse.AI/LocomotionUrgency.cs +++ b/Assembly-CSharp/Verse.AI/LocomotionUrgency.cs @@ -1,13 +1,11 @@ -using System; - namespace Verse.AI { public enum LocomotionUrgency : byte { - None, - Amble, - Walk, - Jog, - Sprint + None = 0, + Amble = 1, + Walk = 2, + Jog = 3, + Sprint = 4 } } diff --git a/Assembly-CSharp/Verse.AI/MentalState.cs b/Assembly-CSharp/Verse.AI/MentalState.cs index eb7d02672..2afddb08f 100644 --- a/Assembly-CSharp/Verse.AI/MentalState.cs +++ b/Assembly-CSharp/Verse.AI/MentalState.cs @@ -46,7 +46,7 @@ public virtual void PostEnd() { if (!this.def.recoveryMessage.NullOrEmpty() && PawnUtility.ShouldSendNotificationAbout(this.pawn)) { - string text = null; + string text = (string)null; try { text = string.Format(this.def.recoveryMessage, this.pawn.NameStringShort); @@ -57,7 +57,7 @@ public virtual void PostEnd() } if (!text.NullOrEmpty()) { - Messages.Message(text.AdjustedFor(this.pawn), this.pawn, MessageSound.Silent); + Messages.Message(text.AdjustedFor(this.pawn), (Thing)this.pawn, MessageSound.Silent); } } } @@ -70,17 +70,14 @@ public virtual void MentalStateTick() if (this.age >= this.def.maxTicksBeforeRecovery || (this.age >= this.def.minTicksBeforeRecovery && Rand.MTBEventOccurs(this.def.recoveryMtbDays, 60000f, 150f))) { this.RecoverFromState(); - return; } - if (this.def.recoverFromSleep && !this.pawn.Awake()) + else if (this.def.recoverFromSleep && !this.pawn.Awake()) { this.RecoverFromState(); - return; } - if (this.def.recoverFromDowned && this.pawn.Downed) + else if (this.def.recoverFromDowned && this.pawn.Downed) { this.RecoverFromState(); - return; } } } @@ -89,13 +86,7 @@ public void RecoverFromState() { if (this.pawn.MentalState != this) { - Log.Error(string.Concat(new object[] - { - "Recovered from ", - this.def, - " but pawn's mental state is not this, it is ", - this.pawn.MentalState - })); + Log.Error("Recovered from " + this.def + " but pawn's mental state is not this, it is " + this.pawn.MentalState); } this.pawn.mindState.mentalStateHandler.ClearMentalStateDirect(); if (this.causedByMood && this.def.moodRecoveryThought != null && this.pawn.needs.mood != null) diff --git a/Assembly-CSharp/Verse.AI/MentalStateHandler.cs b/Assembly-CSharp/Verse.AI/MentalStateHandler.cs index 1dccdbc22..f8ff37a8e 100644 --- a/Assembly-CSharp/Verse.AI/MentalStateHandler.cs +++ b/Assembly-CSharp/Verse.AI/MentalStateHandler.cs @@ -59,7 +59,7 @@ public void ExposeData() { this.curStateInt.pawn = this.pawn; } - if (Current.ProgramState != ProgramState.Entry && this.pawn.Spawned) + if (Current.ProgramState != 0 && this.pawn.Spawned) { this.pawn.Map.attackTargetsCache.UpdateTarget(this.pawn); } @@ -79,109 +79,104 @@ public void MentalStateHandlerTick() { Log.Error("In mental state while downed: " + this.pawn); this.CurState.RecoverFromState(); - return; } - this.curStateInt.MentalStateTick(); + else + { + this.curStateInt.MentalStateTick(); + } } } public bool TryStartMentalState(MentalStateDef stateDef, string reason = null, bool forceWake = false, bool causedByMood = false, Pawn otherPawn = null) { - if ((!this.pawn.Spawned && !this.pawn.IsCaravanMember()) || this.CurStateDef == stateDef || this.pawn.Downed || (!forceWake && !this.pawn.Awake())) - { - return false; - } - if (TutorSystem.TutorialMode && this.pawn.Faction == Faction.OfPlayer) + if ((this.pawn.Spawned || this.pawn.IsCaravanMember()) && this.CurStateDef != stateDef && !this.pawn.Downed && (forceWake || this.pawn.Awake())) { - return false; - } - if ((this.pawn.IsColonist || this.pawn.HostFaction == Faction.OfPlayer) && stateDef.tale != null) - { - TaleRecorder.RecordTale(stateDef.tale, new object[] + if (TutorSystem.TutorialMode && this.pawn.Faction == Faction.OfPlayer) { - this.pawn - }); - } - if (!stateDef.beginLetter.NullOrEmpty() && PawnUtility.ShouldSendNotificationAbout(this.pawn)) - { - string label = "MentalBreakLetterLabel".Translate() + ": " + stateDef.beginLetterLabel; - string text = string.Format(stateDef.beginLetter, this.pawn.Label).AdjustedFor(this.pawn).CapitalizeFirst(); - if (reason != null) + return false; + } + if ((this.pawn.IsColonist || this.pawn.HostFaction == Faction.OfPlayer) && stateDef.tale != null) + { + TaleRecorder.RecordTale(stateDef.tale, this.pawn); + } + if (!stateDef.beginLetter.NullOrEmpty() && PawnUtility.ShouldSendNotificationAbout(this.pawn)) { - text = text + "\n\n" + "FinalStraw".Translate(new object[] + string label = "MentalBreakLetterLabel".Translate() + ": " + stateDef.beginLetterLabel; + string text = string.Format(stateDef.beginLetter, this.pawn.Label).AdjustedFor(this.pawn).CapitalizeFirst(); + if (reason != null) { - reason - }); + text = text + "\n\n" + "FinalStraw".Translate(reason); + } + Find.LetterStack.ReceiveLetter(label, text, stateDef.beginLetterDef, (Thing)this.pawn, (string)null); } - Find.LetterStack.ReceiveLetter(label, text, stateDef.beginLetterDef, this.pawn, null); - } - if (stateDef.IsExtreme && this.pawn.IsPlayerControlledCaravanMember()) - { - Messages.Message("MessageCaravanMemberHasExtremeMentalBreak".Translate(), this.pawn.GetCaravan(), MessageSound.Negative); - } - this.pawn.records.Increment(RecordDefOf.TimesInMentalState); - if (this.pawn.Drafted) - { - this.pawn.drafter.Drafted = false; - } - this.curStateInt = (MentalState)Activator.CreateInstance(stateDef.stateClass); - this.curStateInt.pawn = this.pawn; - this.curStateInt.def = stateDef; - this.curStateInt.causedByMood = causedByMood; - if (otherPawn != null) - { - ((MentalState_SocialFighting)this.curStateInt).otherPawn = otherPawn; - } - if (this.pawn.needs.mood != null) - { - this.pawn.needs.mood.thoughts.situational.Notify_SituationalThoughtsDirty(); - } - if (stateDef != null && stateDef.IsAggro && this.pawn.caller != null) - { - this.pawn.caller.Notify_InAggroMentalState(); - } - if (this.CurState != null) - { - this.CurState.PostStart(reason); - } - if (this.pawn.CurJob != null) - { - this.pawn.jobs.EndCurrentJob(JobCondition.InterruptForced, true); - } - if (this.pawn.Spawned) - { - this.pawn.Map.attackTargetsCache.UpdateTarget(this.pawn); - } - if (this.pawn.Spawned && forceWake && !this.pawn.Awake()) - { - this.pawn.jobs.EndCurrentJob(JobCondition.InterruptForced, true); + if (stateDef.IsExtreme && this.pawn.IsPlayerControlledCaravanMember()) + { + Messages.Message("MessageCaravanMemberHasExtremeMentalBreak".Translate(), (WorldObject)this.pawn.GetCaravan(), MessageSound.Negative); + } + this.pawn.records.Increment(RecordDefOf.TimesInMentalState); + if (this.pawn.Drafted) + { + this.pawn.drafter.Drafted = false; + } + this.curStateInt = (MentalState)Activator.CreateInstance(stateDef.stateClass); + this.curStateInt.pawn = this.pawn; + this.curStateInt.def = stateDef; + this.curStateInt.causedByMood = causedByMood; + if (otherPawn != null) + { + ((MentalState_SocialFighting)this.curStateInt).otherPawn = otherPawn; + } + if (this.pawn.needs.mood != null) + { + this.pawn.needs.mood.thoughts.situational.Notify_SituationalThoughtsDirty(); + } + if (stateDef != null && stateDef.IsAggro && this.pawn.caller != null) + { + this.pawn.caller.Notify_InAggroMentalState(); + } + if (this.CurState != null) + { + this.CurState.PostStart(reason); + } + if (this.pawn.CurJob != null) + { + this.pawn.jobs.EndCurrentJob(JobCondition.InterruptForced, true); + } + if (this.pawn.Spawned) + { + this.pawn.Map.attackTargetsCache.UpdateTarget(this.pawn); + } + if (this.pawn.Spawned && forceWake && !this.pawn.Awake()) + { + this.pawn.jobs.EndCurrentJob(JobCondition.InterruptForced, true); + } + return true; } - return true; + return false; } public void Notify_DamageTaken(DamageInfo dinfo) { if (!this.neverFleeIndividual && this.pawn.Spawned && this.pawn.MentalStateDef == null && !this.pawn.Downed && dinfo.Def.externalViolence && this.pawn.RaceProps.Humanlike && this.pawn.mindState.canFleeIndividual) { - float lerpPct = (float)(this.pawn.HashOffset() % 100) / 100f; + float lerpPct = (float)((float)(this.pawn.HashOffset() % 100) / 100.0); float num = this.pawn.kindDef.fleeHealthThresholdRange.LerpThroughRange(lerpPct); if (this.pawn.health.summaryHealth.SummaryHealthPercent < num && this.pawn.Faction != Faction.OfPlayer && this.pawn.HostFaction == null) { - this.TryStartMentalState(MentalStateDefOf.PanicFlee, null, false, false, null); + this.TryStartMentalState(MentalStateDefOf.PanicFlee, (string)null, false, false, null); } } } internal void ClearMentalStateDirect() { - if (this.curStateInt == null) - { - return; - } - this.curStateInt = null; - if (this.pawn.Spawned) + if (this.curStateInt != null) { - this.pawn.Map.attackTargetsCache.UpdateTarget(this.pawn); + this.curStateInt = null; + if (this.pawn.Spawned) + { + this.pawn.Map.attackTargetsCache.UpdateTarget(this.pawn); + } } } } diff --git a/Assembly-CSharp/Verse.AI/MentalState_Berserk.cs b/Assembly-CSharp/Verse.AI/MentalState_Berserk.cs index 5759a96f1..4d6907f23 100644 --- a/Assembly-CSharp/Verse.AI/MentalState_Berserk.cs +++ b/Assembly-CSharp/Verse.AI/MentalState_Berserk.cs @@ -1,5 +1,4 @@ using RimWorld; -using System; namespace Verse.AI { diff --git a/Assembly-CSharp/Verse.AI/MentalState_Binging.cs b/Assembly-CSharp/Verse.AI/MentalState_Binging.cs index ea8add045..45b9d4c11 100644 --- a/Assembly-CSharp/Verse.AI/MentalState_Binging.cs +++ b/Assembly-CSharp/Verse.AI/MentalState_Binging.cs @@ -1,5 +1,4 @@ using RimWorld; -using System; namespace Verse.AI { diff --git a/Assembly-CSharp/Verse.AI/MentalState_BingingDrug.cs b/Assembly-CSharp/Verse.AI/MentalState_BingingDrug.cs index 6b09136c0..0e9e0aaf7 100644 --- a/Assembly-CSharp/Verse.AI/MentalState_BingingDrug.cs +++ b/Assembly-CSharp/Verse.AI/MentalState_BingingDrug.cs @@ -29,73 +29,51 @@ public override void PostStart(string reason) { base.PostStart(reason); this.ChooseRandomChemical(); - if (PawnUtility.ShouldSendNotificationAbout(this.pawn)) + if (PawnUtility.ShouldSendNotificationAbout(base.pawn)) { - string label = "MentalBreakLetterLabel".Translate() + ": " + "LetterLabelDrugBinge".Translate(new object[] - { - this.chemical.label - }); - string text = "LetterDrugBinge".Translate(new object[] - { - this.pawn.Label, - this.chemical.label - }).CapitalizeFirst(); + string label = "MentalBreakLetterLabel".Translate() + ": " + "LetterLabelDrugBinge".Translate(this.chemical.label); + string text = "LetterDrugBinge".Translate(base.pawn.Label, this.chemical.label).CapitalizeFirst(); if (reason != null) { - text = text + "\n\n" + "FinalStraw".Translate(new object[] - { - reason - }); + text = text + "\n\n" + "FinalStraw".Translate(reason); } - Find.LetterStack.ReceiveLetter(label, text, LetterDefOf.BadNonUrgent, this.pawn, null); + Find.LetterStack.ReceiveLetter(label, text, LetterDefOf.BadNonUrgent, (Thing)base.pawn, (string)null); } } public override void PostEnd() { base.PostEnd(); - if (PawnUtility.ShouldSendNotificationAbout(this.pawn)) + if (PawnUtility.ShouldSendNotificationAbout(base.pawn)) { - Messages.Message("MessageNoLongerBingingOnDrug".Translate(new object[] - { - this.pawn.NameStringShort, - this.chemical.label - }), this.pawn, MessageSound.Silent); + Messages.Message("MessageNoLongerBingingOnDrug".Translate(base.pawn.NameStringShort, this.chemical.label), (Thing)base.pawn, MessageSound.Silent); } } private void ChooseRandomChemical() { MentalState_BingingDrug.addictions.Clear(); - List hediffs = this.pawn.health.hediffSet.hediffs; + List hediffs = base.pawn.health.hediffSet.hediffs; for (int i = 0; i < hediffs.Count; i++) { Hediff_Addiction hediff_Addiction = hediffs[i] as Hediff_Addiction; - if (hediff_Addiction != null && AddictionUtility.CanBingeOnNow(this.pawn, hediff_Addiction.Chemical, DrugCategory.Any)) + if (hediff_Addiction != null && AddictionUtility.CanBingeOnNow(base.pawn, hediff_Addiction.Chemical, DrugCategory.Any)) { MentalState_BingingDrug.addictions.Add(hediff_Addiction.Chemical); } } if (MentalState_BingingDrug.addictions.Count > 0) { - this.chemical = MentalState_BingingDrug.addictions.RandomElement(); + this.chemical = MentalState_BingingDrug.addictions.RandomElement(); MentalState_BingingDrug.addictions.Clear(); } - else + else if (!(from x in DefDatabase.AllDefsListForReading + where AddictionUtility.CanBingeOnNow(base.pawn, x, base.def.drugCategory) + select x).TryRandomElement(out this.chemical) && !(from x in DefDatabase.AllDefsListForReading + where AddictionUtility.CanBingeOnNow(base.pawn, x, DrugCategory.Any) + select x).TryRandomElement(out this.chemical)) { - if ((from x in DefDatabase.AllDefsListForReading - where AddictionUtility.CanBingeOnNow(this.pawn, x, this.def.drugCategory) - select x).TryRandomElement(out this.chemical)) - { - return; - } - if ((from x in DefDatabase.AllDefsListForReading - where AddictionUtility.CanBingeOnNow(this.pawn, x, DrugCategory.Any) - select x).TryRandomElement(out this.chemical)) - { - return; - } - this.chemical = DefDatabase.AllDefsListForReading.RandomElement(); + this.chemical = DefDatabase.AllDefsListForReading.RandomElement(); } } } diff --git a/Assembly-CSharp/Verse.AI/MentalState_FireStartingSpree.cs b/Assembly-CSharp/Verse.AI/MentalState_FireStartingSpree.cs index 803acc2c4..337d2f532 100644 --- a/Assembly-CSharp/Verse.AI/MentalState_FireStartingSpree.cs +++ b/Assembly-CSharp/Verse.AI/MentalState_FireStartingSpree.cs @@ -1,5 +1,4 @@ using RimWorld; -using System; namespace Verse.AI { diff --git a/Assembly-CSharp/Verse.AI/MentalState_GiveUpExit.cs b/Assembly-CSharp/Verse.AI/MentalState_GiveUpExit.cs index e3d791e30..1ca4931ad 100644 --- a/Assembly-CSharp/Verse.AI/MentalState_GiveUpExit.cs +++ b/Assembly-CSharp/Verse.AI/MentalState_GiveUpExit.cs @@ -1,5 +1,4 @@ using RimWorld; -using System; namespace Verse.AI { diff --git a/Assembly-CSharp/Verse.AI/MentalState_Manhunter.cs b/Assembly-CSharp/Verse.AI/MentalState_Manhunter.cs index 54291f309..9f23e20ce 100644 --- a/Assembly-CSharp/Verse.AI/MentalState_Manhunter.cs +++ b/Assembly-CSharp/Verse.AI/MentalState_Manhunter.cs @@ -1,5 +1,4 @@ using RimWorld; -using System; namespace Verse.AI { diff --git a/Assembly-CSharp/Verse.AI/MentalState_PanicFlee.cs b/Assembly-CSharp/Verse.AI/MentalState_PanicFlee.cs index 84b51e63b..a1d447a03 100644 --- a/Assembly-CSharp/Verse.AI/MentalState_PanicFlee.cs +++ b/Assembly-CSharp/Verse.AI/MentalState_PanicFlee.cs @@ -1,5 +1,4 @@ using RimWorld; -using System; namespace Verse.AI { diff --git a/Assembly-CSharp/Verse.AI/MentalState_SocialFighting.cs b/Assembly-CSharp/Verse.AI/MentalState_SocialFighting.cs index 069a5b5bd..308704d89 100644 --- a/Assembly-CSharp/Verse.AI/MentalState_SocialFighting.cs +++ b/Assembly-CSharp/Verse.AI/MentalState_SocialFighting.cs @@ -1,5 +1,4 @@ using RimWorld; -using System; namespace Verse.AI { @@ -11,7 +10,15 @@ private bool ShouldStop { get { - return !this.otherPawn.Spawned || this.otherPawn.Dead || this.otherPawn.Downed || !this.IsOtherPawnSocialFightingWithMe; + if (this.otherPawn.Spawned && !this.otherPawn.Dead && !this.otherPawn.Downed) + { + if (!this.IsOtherPawnSocialFightingWithMe) + { + return true; + } + return false; + } + return true; } } @@ -24,7 +31,15 @@ private bool IsOtherPawnSocialFightingWithMe return false; } MentalState_SocialFighting mentalState_SocialFighting = this.otherPawn.MentalState as MentalState_SocialFighting; - return mentalState_SocialFighting != null && mentalState_SocialFighting.otherPawn == this.pawn; + if (mentalState_SocialFighting == null) + { + return false; + } + if (mentalState_SocialFighting.otherPawn != base.pawn) + { + return false; + } + return true; } } @@ -43,32 +58,20 @@ public override void MentalStateTick() public override void PostEnd() { base.PostEnd(); - this.pawn.jobs.StopAll(false); - this.pawn.mindState.meleeThreat = null; + base.pawn.jobs.StopAll(false); + base.pawn.mindState.meleeThreat = null; if (this.IsOtherPawnSocialFightingWithMe) { this.otherPawn.MentalState.RecoverFromState(); } - if ((PawnUtility.ShouldSendNotificationAbout(this.pawn) || PawnUtility.ShouldSendNotificationAbout(this.otherPawn)) && this.pawn.thingIDNumber < this.otherPawn.thingIDNumber) + if ((PawnUtility.ShouldSendNotificationAbout(base.pawn) || PawnUtility.ShouldSendNotificationAbout(this.otherPawn)) && base.pawn.thingIDNumber < this.otherPawn.thingIDNumber) { - Messages.Message("MessageNoLongerSocialFighting".Translate(new object[] - { - this.pawn.NameStringShort, - this.otherPawn.LabelShort - }), this.pawn, MessageSound.Silent); + Messages.Message("MessageNoLongerSocialFighting".Translate(base.pawn.NameStringShort, this.otherPawn.LabelShort), (Thing)base.pawn, MessageSound.Silent); } - if (!this.pawn.Dead && this.pawn.needs.mood != null && !this.otherPawn.Dead) + if (!base.pawn.Dead && base.pawn.needs.mood != null && !this.otherPawn.Dead) { - ThoughtDef def; - if (Rand.Value < 0.5f) - { - def = ThoughtDefOf.HadAngeringFight; - } - else - { - def = ThoughtDefOf.HadCatharticFight; - } - this.pawn.needs.mood.thoughts.memories.TryGainMemory(def, this.otherPawn); + ThoughtDef def = (!(Rand.Value < 0.5)) ? ThoughtDefOf.HadCatharticFight : ThoughtDefOf.HadAngeringFight; + base.pawn.needs.mood.thoughts.memories.TryGainMemory(def, this.otherPawn); } } diff --git a/Assembly-CSharp/Verse.AI/MentalState_WanderConfused.cs b/Assembly-CSharp/Verse.AI/MentalState_WanderConfused.cs index 3cb66bb8d..acf80752b 100644 --- a/Assembly-CSharp/Verse.AI/MentalState_WanderConfused.cs +++ b/Assembly-CSharp/Verse.AI/MentalState_WanderConfused.cs @@ -1,5 +1,4 @@ using RimWorld; -using System; namespace Verse.AI { diff --git a/Assembly-CSharp/Verse.AI/MentalState_WanderOwnRoom.cs b/Assembly-CSharp/Verse.AI/MentalState_WanderOwnRoom.cs index 0a4f8cbd7..5eb9f04c9 100644 --- a/Assembly-CSharp/Verse.AI/MentalState_WanderOwnRoom.cs +++ b/Assembly-CSharp/Verse.AI/MentalState_WanderOwnRoom.cs @@ -1,5 +1,4 @@ using RimWorld; -using System; namespace Verse.AI { @@ -10,13 +9,13 @@ public class MentalState_WanderOwnRoom : MentalState public override void PostStart(string reason) { base.PostStart(reason); - if (this.pawn.ownership.OwnedBed != null) + if (base.pawn.ownership.OwnedBed != null) { - this.target = this.pawn.ownership.OwnedBed.Position; + this.target = base.pawn.ownership.OwnedBed.Position; } else { - this.target = this.pawn.Position; + this.target = base.pawn.Position; } } diff --git a/Assembly-CSharp/Verse.AI/MentalState_WanderPsychotic.cs b/Assembly-CSharp/Verse.AI/MentalState_WanderPsychotic.cs index 7b6613055..8c071c471 100644 --- a/Assembly-CSharp/Verse.AI/MentalState_WanderPsychotic.cs +++ b/Assembly-CSharp/Verse.AI/MentalState_WanderPsychotic.cs @@ -1,5 +1,4 @@ using RimWorld; -using System; namespace Verse.AI { diff --git a/Assembly-CSharp/Verse.AI/MentalState_WanderSad.cs b/Assembly-CSharp/Verse.AI/MentalState_WanderSad.cs index 07bdfdc35..b3111826c 100644 --- a/Assembly-CSharp/Verse.AI/MentalState_WanderSad.cs +++ b/Assembly-CSharp/Verse.AI/MentalState_WanderSad.cs @@ -1,5 +1,4 @@ using RimWorld; -using System; namespace Verse.AI { diff --git a/Assembly-CSharp/Verse.AI/PathEndMode.cs b/Assembly-CSharp/Verse.AI/PathEndMode.cs index 4d1c168b9..ffa931bb5 100644 --- a/Assembly-CSharp/Verse.AI/PathEndMode.cs +++ b/Assembly-CSharp/Verse.AI/PathEndMode.cs @@ -1,13 +1,11 @@ -using System; - namespace Verse.AI { public enum PathEndMode : byte { - None, - OnCell, - Touch, - ClosestTouch, - InteractionCell + None = 0, + OnCell = 1, + Touch = 2, + ClosestTouch = 3, + InteractionCell = 4 } } diff --git a/Assembly-CSharp/Verse.AI/PathFinder.cs b/Assembly-CSharp/Verse.AI/PathFinder.cs index 1dbc42bb5..1e8ad55f3 100644 --- a/Assembly-CSharp/Verse.AI/PathFinder.cs +++ b/Assembly-CSharp/Verse.AI/PathFinder.cs @@ -1,3 +1,4 @@ +#define PFPROFILE using RimWorld; using System; using System.Collections.Generic; @@ -34,9 +35,9 @@ private struct PathFinderNodeFast public ushort status; } - internal class CostNodeComparer : IComparer + internal class CostNodeComparer : IComparer { - public int Compare(PathFinder.CostNode a, PathFinder.CostNode b) + public int Compare(CostNode a, CostNode b) { return a.cost.CompareTo(b.cost); } @@ -66,15 +67,15 @@ public int Compare(PathFinder.CostNode a, PathFinder.CostNode b) private Map map; - private FastPriorityQueue openList; + private FastPriorityQueue openList; - private PathFinder.PathFinderNodeFast[] calcGrid; + private PathFinderNodeFast[] calcGrid; private List disallowedCornerIndices = new List(4); - private ushort statusOpenValue = 1; + private ushort statusOpenValue = (ushort)1; - private ushort statusClosedValue = 2; + private ushort statusClosedValue = (ushort)2; private RegionCostCalculatorWrapper regionCostCalculator; @@ -88,7 +89,7 @@ public int Compare(PathFinder.CostNode a, PathFinder.CostNode b) private CellIndices cellIndices; - private static readonly int[] Directions = new int[] + private static readonly int[] Directions = new int[16] { 0, 1, @@ -123,10 +124,12 @@ public int Compare(PathFinder.CostNode a, PathFinder.CostNode b) public PathFinder(Map map) { this.map = map; - this.mapSizeX = map.Size.x; - this.mapSizeZ = map.Size.z; - this.calcGrid = new PathFinder.PathFinderNodeFast[this.mapSizeX * this.mapSizeZ]; - this.openList = new FastPriorityQueue(new PathFinder.CostNodeComparer()); + IntVec3 size = map.Size; + this.mapSizeX = size.x; + IntVec3 size2 = map.Size; + this.mapSizeZ = size2.z; + this.calcGrid = new PathFinderNodeFast[this.mapSizeX * this.mapSizeZ]; + this.openList = new FastPriorityQueue(new CostNodeComparer()); this.regionCostCalculator = new RegionCostCalculatorWrapper(map); } @@ -150,37 +153,17 @@ public PawnPath FindPath(IntVec3 start, LocalTargetInfo dest, TraverseParms trav Pawn pawn = traverseParms.pawn; if (pawn != null && pawn.Map != this.map) { - Log.Error(string.Concat(new object[] - { - "Tried to FindPath for pawn which is spawned in another map. His map PathFinder should have been used, not this one. pawn=", - pawn, - " pawn.Map=", - pawn.Map, - " map=", - this.map - })); + Log.Error("Tried to FindPath for pawn which is spawned in another map. His map PathFinder should have been used, not this one. pawn=" + pawn + " pawn.Map=" + pawn.Map + " map=" + this.map); return PawnPath.NotFound; } if (!start.IsValid) { - Log.Error(string.Concat(new object[] - { - "Tried to FindPath with invalid start ", - start, - ", pawn= ", - pawn - })); + Log.Error("Tried to FindPath with invalid start " + start + ", pawn= " + pawn); return PawnPath.NotFound; } if (!dest.IsValid) { - Log.Error(string.Concat(new object[] - { - "Tried to FindPath with invalid dest ", - dest, - ", pawn= ", - pawn - })); + Log.Error("Tried to FindPath with invalid dest " + dest + ", pawn= " + pawn); return PawnPath.NotFound; } if (traverseParms.mode == TraverseMode.ByPawn) @@ -194,21 +177,14 @@ public PawnPath FindPath(IntVec3 start, LocalTargetInfo dest, TraverseParms trav { return PawnPath.NotFound; } - this.PfProfilerBeginSample(string.Concat(new object[] - { - "FindPath for ", - pawn, - " from ", - start, - " to ", - dest, - (!dest.HasThing) ? string.Empty : (" at " + dest.Cell) - })); + this.PfProfilerBeginSample("FindPath for " + pawn + " from " + start + " to " + dest + ((!dest.HasThing) ? string.Empty : (" at " + dest.Cell))); this.cellIndices = this.map.cellIndices; this.pathGrid = this.map.pathGrid; this.edificeGrid = this.map.edificeGrid.InnerArray; - int x = dest.Cell.x; - int z = dest.Cell.z; + IntVec3 cell = dest.Cell; + int x = cell.x; + IntVec3 cell2 = dest.Cell; + int z = cell2.z; int num = this.cellIndices.CellToIndex(start); int num2 = this.cellIndices.CellToIndex(dest.Cell); ByteGrid byteGrid = (pawn == null) ? null : pawn.GetAvoidGrid(); @@ -248,261 +224,279 @@ public PawnPath FindPath(IntVec3 start, LocalTargetInfo dest, TraverseParms trav this.PfProfilerBeginSample("Open cell"); if (this.openList.Count <= 0) { - break; + string text = (pawn == null || pawn.CurJob == null) ? "null" : pawn.CurJob.ToString(); + string text2 = (pawn == null || pawn.Faction == null) ? "null" : pawn.Faction.ToString(); + Log.Warning(pawn + " pathing from " + start + " to " + dest + " ran out of cells to process.\nJob:" + text + "\nFaction: " + text2); + this.DebugDrawRichData(); + this.PfProfilerEndSample(); + return PawnPath.NotFound; } num5 += this.openList.Count; num6++; - PathFinder.CostNode costNode = this.openList.Pop(); + CostNode costNode = this.openList.Pop(); num = costNode.index; if (costNode.cost != this.calcGrid[num].costNodeCost) { this.PfProfilerEndSample(); + continue; } - else if (this.calcGrid[num].status == this.statusClosedValue) + if (this.calcGrid[num].status == this.statusClosedValue) { this.PfProfilerEndSample(); + continue; } - else + IntVec3 c = this.cellIndices.IndexToCell(num); + int x2 = c.x; + int z2 = c.z; + if (flag5) { - IntVec3 c = this.cellIndices.IndexToCell(num); - int x2 = c.x; - int z2 = c.z; - if (flag5) - { - this.DebugFlash(c, (float)this.calcGrid[num].knownCost / 1500f, this.calcGrid[num].knownCost.ToString()); - } - if (flag3) - { - if (num == num2) - { - goto Block_26; - } - } - else if (cellRect.Contains(c) && !this.disallowedCornerIndices.Contains(num)) - { - goto Block_28; - } - if (num3 > 160000) + this.DebugFlash(c, (float)((float)this.calcGrid[num].knownCost / 1500.0), this.calcGrid[num].knownCost.ToString()); + } + if (flag3) + { + if (num == num2) { - goto Block_29; + this.PfProfilerEndSample(); + return this.FinalizedPath(num); } + } + else if (cellRect.Contains(c) && !this.disallowedCornerIndices.Contains(num)) + { + this.PfProfilerEndSample(); + return this.FinalizedPath(num); + } + if (num3 <= 160000) + { this.PfProfilerEndSample(); this.PfProfilerBeginSample("Neighbor consideration"); for (int i = 0; i < 8; i++) { uint num10 = (uint)(x2 + PathFinder.Directions[i]); uint num11 = (uint)(z2 + PathFinder.Directions[i + 8]); - if ((ulong)num10 < (ulong)((long)this.mapSizeX) && (ulong)num11 < (ulong)((long)this.mapSizeZ)) + int num12; + int num13; + int num14; + bool flag9; + int num15; + if (num10 < this.mapSizeX && num11 < this.mapSizeZ) { - int num12 = (int)num10; - int num13 = (int)num11; - int num14 = this.cellIndices.CellToIndex(num12, num13); - if (this.calcGrid[num14].status != this.statusClosedValue || flag8) + num12 = (int)num10; + num13 = (int)num11; + num14 = this.cellIndices.CellToIndex(num12, num13); + if (this.calcGrid[num14].status == this.statusClosedValue && !flag8) + { + continue; + } + num15 = 0; + flag9 = false; + if (!this.pathGrid.WalkableFast(num14)) { - int num15 = 0; - bool flag9 = false; - if (!this.pathGrid.WalkableFast(num14)) + if (!flag) { - if (!flag) + if (flag5) { - if (flag5) - { - this.DebugFlash(new IntVec3(num12, 0, num13), 0.22f, "walk"); - } - goto IL_BAD; + this.DebugFlash(new IntVec3(num12, 0, num13), 0.22f, "walk"); } + } + else + { flag9 = true; num15 += 60; Building building = edificeGrid[num14]; - if (building == null) - { - goto IL_BAD; - } - if (!PathFinder.IsDestroyable(building)) + if (building != null && PathFinder.IsDestroyable(building)) { - goto IL_BAD; + num15 += (int)((float)building.HitPoints * 0.10000000149011612); + goto IL_06d6; } - num15 += (int)((float)building.HitPoints * 0.1f); } - if (i > 3) + continue; + } + goto IL_06d6; + } + continue; + IL_06d6: + switch (i) + { + case 4: + { + if (this.BlocksDiagonalMovement(num - this.mapSizeX)) + { + if (flag7) { - switch (i) + if (flag5) { - case 4: - if (this.BlocksDiagonalMovement(num - this.mapSizeX)) - { - if (flag7) - { - if (flag5) - { - this.DebugFlash(new IntVec3(x2, 0, z2 - 1), 0.9f, "corn"); - } - goto IL_BAD; - } - num15 += 60; - } - if (this.BlocksDiagonalMovement(num + 1)) - { - if (flag7) - { - if (flag5) - { - this.DebugFlash(new IntVec3(x2 + 1, 0, z2), 0.9f, "corn"); - } - goto IL_BAD; - } - num15 += 60; - } - break; - case 5: - if (this.BlocksDiagonalMovement(num + this.mapSizeX)) - { - if (flag7) - { - if (flag5) - { - this.DebugFlash(new IntVec3(x2, 0, z2 + 1), 0.9f, "corn"); - } - goto IL_BAD; - } - num15 += 60; - } - if (this.BlocksDiagonalMovement(num + 1)) - { - if (flag7) - { - if (flag5) - { - this.DebugFlash(new IntVec3(x2 + 1, 0, z2), 0.9f, "corn"); - } - goto IL_BAD; - } - num15 += 60; - } - break; - case 6: - if (this.BlocksDiagonalMovement(num + this.mapSizeX)) - { - if (flag7) - { - if (flag5) - { - this.DebugFlash(new IntVec3(x2, 0, z2 + 1), 0.9f, "corn"); - } - goto IL_BAD; - } - num15 += 60; - } - if (this.BlocksDiagonalMovement(num - 1)) - { - if (flag7) - { - if (flag5) - { - this.DebugFlash(new IntVec3(x2 - 1, 0, z2), 0.9f, "corn"); - } - goto IL_BAD; - } - num15 += 60; - } - break; - case 7: - if (this.BlocksDiagonalMovement(num - this.mapSizeX)) - { - if (flag7) - { - if (flag5) - { - this.DebugFlash(new IntVec3(x2, 0, z2 - 1), 0.9f, "corn"); - } - goto IL_BAD; - } - num15 += 60; - } - if (this.BlocksDiagonalMovement(num - 1)) - { - if (flag7) - { - if (flag5) - { - this.DebugFlash(new IntVec3(x2 - 1, 0, z2), 0.9f, "corn"); - } - goto IL_BAD; - } - num15 += 60; - } - break; + this.DebugFlash(new IntVec3(x2, 0, z2 - 1), 0.9f, "corn"); } + continue; } - int num16 = (i <= 3) ? num8 : num9; - num16 += num15; - if (!flag9) - { - num16 += array[num14]; - } - if (byteGrid != null) - { - num16 += (int)(byteGrid[num14] * 8); - } - if (allowedArea != null && !allowedArea[num14]) + num15 += 60; + } + if (this.BlocksDiagonalMovement(num + 1)) + { + if (flag7) { - num16 += 600; + if (flag5) + { + this.DebugFlash(new IntVec3(x2 + 1, 0, z2), 0.9f, "corn"); + } + continue; } - if (flag4 && PawnUtility.AnyPawnBlockingPathAt(new IntVec3(num12, 0, num13), pawn, false, false)) + num15 += 60; + } + break; + } + case 5: + { + if (this.BlocksDiagonalMovement(num + this.mapSizeX)) + { + if (flag7) { - num16 += 175; + if (flag5) + { + this.DebugFlash(new IntVec3(x2, 0, z2 + 1), 0.9f, "corn"); + } + continue; } - Building building2 = this.edificeGrid[num14]; - if (building2 != null) + num15 += 60; + } + if (this.BlocksDiagonalMovement(num + 1)) + { + if (flag7) { - this.PfProfilerBeginSample("Edifices"); - int buildingCost = PathFinder.GetBuildingCost(building2, traverseParms, pawn); - if (buildingCost == 2147483647) + if (flag5) { - this.PfProfilerEndSample(); - goto IL_BAD; + this.DebugFlash(new IntVec3(x2 + 1, 0, z2), 0.9f, "corn"); } - num16 += buildingCost; - this.PfProfilerEndSample(); + continue; } - int num17 = num16 + this.calcGrid[num].knownCost; - ushort status = this.calcGrid[num14].status; - if (status == this.statusClosedValue || status == this.statusOpenValue) + num15 += 60; + } + break; + } + case 6: + { + if (this.BlocksDiagonalMovement(num + this.mapSizeX)) + { + if (flag7) { - int num18 = 0; - if (status == this.statusClosedValue) + if (flag5) { - num18 = num8; + this.DebugFlash(new IntVec3(x2, 0, z2 + 1), 0.9f, "corn"); } - if (this.calcGrid[num14].knownCost <= num17 + num18) + continue; + } + num15 += 60; + } + if (this.BlocksDiagonalMovement(num - 1)) + { + if (flag7) + { + if (flag5) { - goto IL_BAD; + this.DebugFlash(new IntVec3(x2 - 1, 0, z2), 0.9f, "corn"); } + continue; } - if (status != this.statusClosedValue && status != this.statusOpenValue) + num15 += 60; + } + break; + } + case 7: + { + if (this.BlocksDiagonalMovement(num - this.mapSizeX)) + { + if (flag7) { - if (flag8) + if (flag5) { - this.calcGrid[num14].heuristicCost = Mathf.RoundToInt((float)this.regionCostCalculator.GetPathCostFromDestToRegion(num14) * 5f); + this.DebugFlash(new IntVec3(x2, 0, z2 - 1), 0.9f, "corn"); } - else + continue; + } + num15 += 60; + } + if (this.BlocksDiagonalMovement(num - 1)) + { + if (flag7) + { + if (flag5) { - int dx = Math.Abs(num12 - x); - int dz = Math.Abs(num13 - z); - int num19 = GenMath.OctileDistance(dx, dz, num8, num9); - this.calcGrid[num14].heuristicCost = Mathf.RoundToInt((float)num19 * num7); + this.DebugFlash(new IntVec3(x2 - 1, 0, z2), 0.9f, "corn"); } + continue; } - int num20 = num17 + this.calcGrid[num14].heuristicCost; - this.calcGrid[num14].parentIndex = num; - this.calcGrid[num14].knownCost = num17; - this.calcGrid[num14].status = this.statusOpenValue; - this.calcGrid[num14].costNodeCost = num20; - num4++; - this.openList.Push(new PathFinder.CostNode(num14, num20)); + num15 += 60; + } + break; + } + } + int num16 = (i <= 3) ? num8 : num9; + num16 += num15; + if (!flag9) + { + num16 += array[num14]; + } + if (byteGrid != null) + { + num16 += byteGrid[num14] * 8; + } + if (allowedArea != null && !allowedArea[num14]) + { + num16 += 600; + } + if (flag4 && PawnUtility.AnyPawnBlockingPathAt(new IntVec3(num12, 0, num13), pawn, false, false)) + { + num16 += 175; + } + Building building2 = this.edificeGrid[num14]; + if (building2 != null) + { + this.PfProfilerBeginSample("Edifices"); + int buildingCost = PathFinder.GetBuildingCost(building2, traverseParms, pawn); + if (buildingCost == 2147483647) + { + this.PfProfilerEndSample(); + continue; } + num16 += buildingCost; + this.PfProfilerEndSample(); + } + int num17 = num16 + this.calcGrid[num].knownCost; + ushort status = this.calcGrid[num14].status; + if (status != this.statusClosedValue && status != this.statusOpenValue) + { + goto IL_0a96; } - IL_BAD:; + int num18 = 0; + if (status == this.statusClosedValue) + { + num18 = num8; + } + if (this.calcGrid[num14].knownCost > num17 + num18) + goto IL_0a96; + continue; + IL_0a96: + if (status != this.statusClosedValue && status != this.statusOpenValue) + { + if (flag8) + { + this.calcGrid[num14].heuristicCost = Mathf.RoundToInt((float)((float)this.regionCostCalculator.GetPathCostFromDestToRegion(num14) * 5.0)); + } + else + { + int dx = Math.Abs(num12 - x); + int dz = Math.Abs(num13 - z); + int num19 = GenMath.OctileDistance(dx, dz, num8, num9); + this.calcGrid[num14].heuristicCost = Mathf.RoundToInt((float)num19 * num7); + } + } + int num20 = num17 + this.calcGrid[num14].heuristicCost; + this.calcGrid[num14].parentIndex = num; + this.calcGrid[num14].knownCost = num17; + this.calcGrid[num14].status = this.statusOpenValue; + this.calcGrid[num14].costNodeCost = num20; + num4++; + this.openList.Push(new CostNode(num14, num20)); } this.PfProfilerEndSample(); num3++; @@ -513,43 +507,11 @@ public PawnPath FindPath(IntVec3 start, LocalTargetInfo dest, TraverseParms trav this.regionCostCalculator.Init(cellRect, traverseParms, num8, num9, byteGrid, allowedArea, this.disallowedCornerIndices); this.InitStatusesAndPushStartNode(ref num, start); } + continue; } + break; } - string text = (pawn == null || pawn.CurJob == null) ? "null" : pawn.CurJob.ToString(); - string text2 = (pawn == null || pawn.Faction == null) ? "null" : pawn.Faction.ToString(); - Log.Warning(string.Concat(new object[] - { - pawn, - " pathing from ", - start, - " to ", - dest, - " ran out of cells to process.\nJob:", - text, - "\nFaction: ", - text2 - })); - this.DebugDrawRichData(); - this.PfProfilerEndSample(); - return PawnPath.NotFound; - Block_26: - this.PfProfilerEndSample(); - return this.FinalizedPath(num); - Block_28: - this.PfProfilerEndSample(); - return this.FinalizedPath(num); - Block_29: - Log.Warning(string.Concat(new object[] - { - pawn, - " pathing from ", - start, - " to ", - dest, - " hit search limit of ", - 160000, - " cells." - })); + Log.Warning(pawn + " pathing from " + start + " to " + dest + " hit search limit of " + 160000 + " cells."); this.DebugDrawRichData(); this.PfProfilerEndSample(); return PawnPath.NotFound; @@ -562,7 +524,16 @@ public static int GetBuildingCost(Building b, TraverseParms traverseParms, Pawn { switch (traverseParms.mode) { + case TraverseMode.NoPassClosedDoors: + { + if (!building_Door.FreePassage) + { + return 2147483647; + } + break; + } case TraverseMode.ByPawn: + { if (!traverseParms.canBash && building_Door.IsForbiddenToPass(pawn)) { if (DebugViewSettings.drawPaths) @@ -588,17 +559,12 @@ public static int GetBuildingCost(Building b, TraverseParms traverseParms, Pawn return 2147483647; } break; - case TraverseMode.NoPassClosedDoors: - if (!building_Door.FreePassage) - { - return 2147483647; - } - break; + } } } else if (pawn != null) { - return (int)b.PathFindCostFor(pawn); + return b.PathFindCostFor(pawn); } return 0; } @@ -625,7 +591,15 @@ public static bool BlocksDiagonalMovement(int x, int z, Map map) public static bool BlocksDiagonalMovement(int index, Map map) { - return !map.pathGrid.WalkableFast(index) || map.edificeGrid[index] is Building_Door; + if (!map.pathGrid.WalkableFast(index)) + { + return true; + } + if (map.edificeGrid[index] is Building_Door) + { + return true; + } + return false; } private void DebugFlash(IntVec3 c, float colorPct, string str) @@ -647,14 +621,15 @@ private PawnPath FinalizedPath(int finalIndex) int num = finalIndex; while (true) { - PathFinder.PathFinderNodeFast pathFinderNodeFast = this.calcGrid[num]; + PathFinderNodeFast pathFinderNodeFast = this.calcGrid[num]; int parentIndex = pathFinderNodeFast.parentIndex; emptyPawnPath.AddNode(this.map.cellIndices.IndexToCell(num)); - if (num == parentIndex) + if (num != parentIndex) { - break; + num = parentIndex; + continue; } - num = parentIndex; + break; } emptyPawnPath.SetupFound((float)this.calcGrid[finalIndex].knownCost); this.PfProfilerEndSample(); @@ -663,8 +638,8 @@ private PawnPath FinalizedPath(int finalIndex) private void InitStatusesAndPushStartNode(ref int curIndex, IntVec3 start) { - this.statusOpenValue += 2; - this.statusClosedValue += 2; + this.statusOpenValue = (ushort)(this.statusOpenValue + 2); + this.statusClosedValue = (ushort)(this.statusClosedValue + 2); if (this.statusClosedValue >= 65435) { this.ResetStatuses(); @@ -676,18 +651,18 @@ private void InitStatusesAndPushStartNode(ref int curIndex, IntVec3 start) this.calcGrid[curIndex].parentIndex = curIndex; this.calcGrid[curIndex].status = this.statusOpenValue; this.openList.Clear(); - this.openList.Push(new PathFinder.CostNode(curIndex, 0)); + this.openList.Push(new CostNode(curIndex, 0)); } private void ResetStatuses() { int num = this.calcGrid.Length; - for (int i = 0; i < num; i++) + for (int num2 = 0; num2 < num; num2++) { - this.calcGrid[i].status = 0; + this.calcGrid[num2].status = (ushort)0; } - this.statusOpenValue = 1; - this.statusClosedValue = 2; + this.statusOpenValue = (ushort)1; + this.statusClosedValue = (ushort)2; } [Conditional("PFPROFILE")] @@ -708,7 +683,8 @@ private void DebugDrawRichData() { while (this.openList.Count > 0) { - int index = this.openList.Pop().index; + CostNode costNode = this.openList.Pop(); + int index = costNode.index; IntVec3 c = new IntVec3(index % this.mapSizeX, 0, index / this.mapSizeX); this.map.debugDrawer.FlashCell(c, 0f, "open"); } @@ -727,15 +703,7 @@ private float DetermineHeuristicStrength(Pawn pawn, IntVec3 start, LocalTargetIn private CellRect CalculateDestinationRect(LocalTargetInfo dest, PathEndMode peMode) { - CellRect result; - if (!dest.HasThing || peMode == PathEndMode.OnCell) - { - result = CellRect.SingleCell(dest.Cell); - } - else - { - result = dest.Thing.OccupiedRect(); - } + CellRect result = (dest.HasThing && peMode != PathEndMode.OnCell) ? dest.Thing.OccupiedRect() : CellRect.SingleCell(dest.Cell); if (peMode == PathEndMode.Touch) { result = result.ExpandedBy(1); diff --git a/Assembly-CSharp/Verse.AI/PathGrid.cs b/Assembly-CSharp/Verse.AI/PathGrid.cs index 59d30732a..7a144fdf7 100644 --- a/Assembly-CSharp/Verse.AI/PathGrid.cs +++ b/Assembly-CSharp/Verse.AI/PathGrid.cs @@ -1,5 +1,4 @@ using RimWorld; -using System; using System.Collections.Generic; using System.Text; @@ -26,7 +25,11 @@ public void ResetPathGrid() public bool Walkable(IntVec3 loc) { - return loc.InBounds(this.map) && this.pathGrid[this.map.cellIndices.CellToIndex(loc)] < 10000; + if (!loc.InBounds(this.map)) + { + return false; + } + return this.pathGrid[this.map.cellIndices.CellToIndex(loc)] < 10000; } public bool WalkableFast(IntVec3 loc) @@ -71,24 +74,23 @@ public void RecalculatePerceivedPathCostUnderThing(Thing t) public void RecalculatePerceivedPathCostAt(IntVec3 c) { - if (!c.InBounds(this.map)) - { - return; - } - bool flag = this.WalkableFast(c); - this.pathGrid[this.map.cellIndices.CellToIndex(c)] = this.CalculatedCostAt(c, true, IntVec3.Invalid); - if (this.WalkableFast(c) != flag) + if (c.InBounds(this.map)) { - this.map.reachability.ClearCache(); - this.map.regionDirtyer.Notify_WalkabilityChanged(c); + bool flag = this.WalkableFast(c); + this.pathGrid[this.map.cellIndices.CellToIndex(c)] = this.CalculatedCostAt(c, true, IntVec3.Invalid); + if (this.WalkableFast(c) != flag) + { + this.map.reachability.ClearCache(); + this.map.regionDirtyer.Notify_WalkabilityChanged(c); + } } } public void RecalculateAllPerceivedPathCosts() { - foreach (IntVec3 current in this.map.AllCells) + foreach (IntVec3 allCell in this.map.AllCells) { - this.RecalculatePerceivedPathCostAt(current); + this.RecalculatePerceivedPathCostAt(allCell); } } @@ -96,14 +98,7 @@ public int CalculatedCostAt(IntVec3 c, bool perceivedStatic, IntVec3 prevCell) { int num = 0; TerrainDef terrainDef = this.map.terrainGrid.TerrainAt(c); - if (terrainDef == null || terrainDef.passability == Traversability.Impassable) - { - num = 10000; - } - else - { - num += terrainDef.pathCost; - } + num = ((terrainDef != null && terrainDef.passability != Traversability.Impassable) ? (num + terrainDef.pathCost) : 10000); int num2 = SnowUtility.MovementTicksAddOn(this.map.snowGrid.GetCategory(c)); num += num2; List list = this.map.thingGrid.ThingsListAt(c); @@ -137,24 +132,20 @@ public int CalculatedCostAt(IntVec3 c, bool perceivedStatic, IntVec3 prevCell) { Fire fire = null; list = this.map.thingGrid.ThingsListAtFast(c2); - for (int k = 0; k < list.Count; k++) + int num3 = 0; + while (num3 < list.Count) { - fire = (list[k] as Fire); - if (fire != null) + fire = (list[num3] as Fire); + if (fire == null) { - break; + num3++; + continue; } + break; } if (fire != null && fire.parent == null) { - if (b.x == 0 && b.z == 0) - { - num += 1000; - } - else - { - num += 150; - } + num = ((((b.x != 0) ? 1 : b.z) != 0) ? (num + 150) : (num + 1000)); } } } @@ -184,19 +175,19 @@ public static void LogPathCostIgnoreRepeaters() { StringBuilder stringBuilder = new StringBuilder(); stringBuilder.AppendLine("===============PATH COST IGNORE REPEATERS=============="); - foreach (ThingDef current in DefDatabase.AllDefs) + foreach (ThingDef allDef in DefDatabase.AllDefs) { - if (PathGrid.IsPathCostIgnoreRepeater(current) && current.passability != Traversability.Impassable) + if (PathGrid.IsPathCostIgnoreRepeater(allDef) && allDef.passability != Traversability.Impassable) { - stringBuilder.AppendLine(current.defName + " " + current.pathCost); + stringBuilder.AppendLine(allDef.defName + " " + allDef.pathCost); } } stringBuilder.AppendLine("===============NON-PATH COST IGNORE REPEATERS that are buildings with >0 pathCost =============="); - foreach (ThingDef current2 in DefDatabase.AllDefs) + foreach (ThingDef allDef2 in DefDatabase.AllDefs) { - if (!PathGrid.IsPathCostIgnoreRepeater(current2) && current2.passability != Traversability.Impassable && current2.category == ThingCategory.Building && current2.pathCost > 0) + if (!PathGrid.IsPathCostIgnoreRepeater(allDef2) && allDef2.passability != Traversability.Impassable && allDef2.category == ThingCategory.Building && allDef2.pathCost > 0) { - stringBuilder.AppendLine(current2.defName + " " + current2.pathCost); + stringBuilder.AppendLine(allDef2.defName + " " + allDef2.pathCost); } } Log.Message(stringBuilder.ToString()); diff --git a/Assembly-CSharp/Verse.AI/PawnDuty.cs b/Assembly-CSharp/Verse.AI/PawnDuty.cs index d3f79fb93..d82fde7a2 100644 --- a/Assembly-CSharp/Verse.AI/PawnDuty.cs +++ b/Assembly-CSharp/Verse.AI/PawnDuty.cs @@ -1,5 +1,4 @@ using RimWorld; -using System; namespace Verse.AI { @@ -36,13 +35,13 @@ public PawnDuty(DutyDef def) this.def = def; } - public PawnDuty(DutyDef def, LocalTargetInfo focus, float radius = -1f) : this(def) + public PawnDuty(DutyDef def, LocalTargetInfo focus, float radius = -1) : this(def) { this.focus = focus; this.radius = radius; } - public PawnDuty(DutyDef def, LocalTargetInfo focus, LocalTargetInfo focusSecond, float radius = -1f) : this(def, focus, radius) + public PawnDuty(DutyDef def, LocalTargetInfo focus, LocalTargetInfo focusSecond, float radius = -1) : this(def, focus, radius) { this.focusSecond = focusSecond; } @@ -66,17 +65,8 @@ public override string ToString() { string text = (!this.focus.IsValid) ? string.Empty : this.focus.ToString(); string text2 = (!this.focusSecond.IsValid) ? string.Empty : (", second=" + this.focusSecond.ToString()); - string text3 = (this.radius <= 0f) ? string.Empty : (", rad=" + this.radius.ToString("F2")); - return string.Concat(new object[] - { - "(", - this.def, - " ", - text, - text2, - text3, - ")" - }); + string text3 = (!(this.radius > 0.0)) ? string.Empty : (", rad=" + this.radius.ToString("F2")); + return "(" + this.def + " " + text + text2 + text3 + ")"; } internal void DrawDebug(Pawn pawn) @@ -84,7 +74,7 @@ internal void DrawDebug(Pawn pawn) if (this.focus.IsValid) { GenDraw.DrawLineBetween(pawn.DrawPos, this.focus.Cell.ToVector3Shifted()); - if (this.radius > 0f) + if (this.radius > 0.0) { GenDraw.DrawRadiusRing(this.focus.Cell, this.radius); } diff --git a/Assembly-CSharp/Verse.AI/PawnLocalAwareness.cs b/Assembly-CSharp/Verse.AI/PawnLocalAwareness.cs index eae9d33a7..f99af332a 100644 --- a/Assembly-CSharp/Verse.AI/PawnLocalAwareness.cs +++ b/Assembly-CSharp/Verse.AI/PawnLocalAwareness.cs @@ -1,5 +1,3 @@ -using System; - namespace Verse.AI { public static class PawnLocalAwareness @@ -8,7 +6,23 @@ public static class PawnLocalAwareness public static bool AnimalAwareOf(this Pawn p, Thing t) { - return p.RaceProps.ToolUser || p.Faction != null || ((float)(p.Position - t.Position).LengthHorizontalSquared <= 900f && p.GetRoom(RegionType.Set_Passable) == t.GetRoom(RegionType.Set_Passable) && GenSight.LineOfSight(p.Position, t.Position, p.Map, false, null, 0, 0)); + if (!p.RaceProps.ToolUser && p.Faction == null) + { + if ((float)(p.Position - t.Position).LengthHorizontalSquared > 900.0) + { + return false; + } + if (p.GetRoom(RegionType.Set_Passable) != t.GetRoom(RegionType.Set_Passable)) + { + return false; + } + if (!GenSight.LineOfSight(p.Position, t.Position, p.Map, false, null, 0, 0)) + { + return false; + } + return true; + } + return true; } } } diff --git a/Assembly-CSharp/Verse.AI/PawnPath.cs b/Assembly-CSharp/Verse.AI/PawnPath.cs index f6c400146..312057d40 100644 --- a/Assembly-CSharp/Verse.AI/PawnPath.cs +++ b/Assembly-CSharp/Verse.AI/PawnPath.cs @@ -18,7 +18,7 @@ public bool Found { get { - return this.totalCostInt >= 0f; + return this.totalCostInt >= 0.0; } } @@ -80,10 +80,12 @@ public void SetupFound(float totalCost) if (this == PawnPath.NotFound) { Log.Warning("Calling SetupFound with totalCost=" + totalCost + " on PawnPath.NotFound"); - return; } - this.totalCostInt = totalCost; - this.curNodeIndex = this.nodes.Count - 1; + else + { + this.totalCostInt = totalCost; + this.curNodeIndex = this.nodes.Count - 1; + } } public void Dispose() @@ -103,10 +105,9 @@ public void ReleaseToPool() public static PawnPath NewNotFound() { - return new PawnPath - { - totalCostInt = -1f - }; + PawnPath pawnPath = new PawnPath(); + pawnPath.totalCostInt = -1f; + return pawnPath; } public IntVec3 ConsumeNextNode() @@ -131,49 +132,34 @@ public override string ToString() { return "PawnPath(not in use)"; } - return string.Concat(new object[] - { - "PawnPath(nodeCount= ", - this.nodes.Count, - (this.nodes.Count <= 0) ? string.Empty : string.Concat(new object[] - { - " first=", - this.FirstNode, - " last=", - this.LastNode - }), - " cost=", - this.totalCostInt, - " )" - }); + return "PawnPath(nodeCount= " + this.nodes.Count + ((this.nodes.Count <= 0) ? string.Empty : (" first=" + this.FirstNode + " last=" + this.LastNode)) + " cost=" + this.totalCostInt + " )"; } public void DrawPath(Pawn pathingPawn) { - if (!this.Found) + if (this.Found) { - return; - } - float y = Altitudes.AltitudeFor(AltitudeLayer.Item); - if (this.NodesLeftCount > 0) - { - for (int i = 0; i < this.NodesLeftCount - 1; i++) - { - Vector3 a = this.Peek(i).ToVector3Shifted(); - a.y = y; - Vector3 b = this.Peek(i + 1).ToVector3Shifted(); - b.y = y; - GenDraw.DrawLineBetween(a, b); - } - if (pathingPawn != null) + float y = Altitudes.AltitudeFor(AltitudeLayer.Item); + if (this.NodesLeftCount > 0) { - Vector3 drawPos = pathingPawn.DrawPos; - drawPos.y = y; - Vector3 b2 = this.Peek(0).ToVector3Shifted(); - b2.y = y; - if ((drawPos - b2).sqrMagnitude > 0.01f) + for (int i = 0; i < this.NodesLeftCount - 1; i++) + { + Vector3 a = this.Peek(i).ToVector3Shifted(); + a.y = y; + Vector3 b = this.Peek(i + 1).ToVector3Shifted(); + b.y = y; + GenDraw.DrawLineBetween(a, b); + } + if (pathingPawn != null) { - GenDraw.DrawLineBetween(drawPos, b2); + Vector3 drawPos = pathingPawn.DrawPos; + drawPos.y = y; + Vector3 b2 = this.Peek(0).ToVector3Shifted(); + b2.y = y; + if ((drawPos - b2).sqrMagnitude > 0.0099999997764825821) + { + GenDraw.DrawLineBetween(drawPos, b2); + } } } } diff --git a/Assembly-CSharp/Verse.AI/PawnPathPool.cs b/Assembly-CSharp/Verse.AI/PawnPathPool.cs index 6cf486810..ca8692b19 100644 --- a/Assembly-CSharp/Verse.AI/PawnPathPool.cs +++ b/Assembly-CSharp/Verse.AI/PawnPathPool.cs @@ -1,4 +1,3 @@ -using System; using System.Collections.Generic; namespace Verse.AI diff --git a/Assembly-CSharp/Verse.AI/PawnPathUtility.cs b/Assembly-CSharp/Verse.AI/PawnPathUtility.cs index 4baf9c3aa..0a45e812a 100644 --- a/Assembly-CSharp/Verse.AI/PawnPathUtility.cs +++ b/Assembly-CSharp/Verse.AI/PawnPathUtility.cs @@ -1,5 +1,4 @@ using RimWorld; -using System; using System.Collections.Generic; namespace Verse.AI @@ -21,29 +20,32 @@ public static Thing FirstBlockingBuilding(this PawnPath path, out IntVec3 cellBe } Building building = null; IntVec3 intVec = IntVec3.Invalid; - for (int i = nodesReversed.Count - 2; i >= 1; i--) + for (int num = nodesReversed.Count - 2; num >= 1; num--) { - Building edifice = nodesReversed[i].GetEdifice(pawn.Map); + Building edifice = nodesReversed[num].GetEdifice(pawn.Map); if (edifice != null) { Building_Door building_Door = edifice as Building_Door; - if ((building_Door != null && !building_Door.FreePassage && (pawn == null || !building_Door.PawnCanOpen(pawn))) || edifice.def.passability == Traversability.Impassable) + if ((building_Door == null || building_Door.FreePassage || (pawn != null && building_Door.PawnCanOpen(pawn))) && edifice.def.passability != Traversability.Impassable) { - if (building != null) - { - cellBefore = intVec; - return building; - } - cellBefore = nodesReversed[i + 1]; - return edifice; + goto IL_00da; } + if (building != null) + { + cellBefore = intVec; + return building; + } + cellBefore = nodesReversed[num + 1]; + return edifice; } + goto IL_00da; + IL_00da: if (edifice != null && edifice.def.passability == Traversability.PassThroughOnly && edifice.def.Fillage == FillCategory.Full) { if (building == null) { building = edifice; - intVec = nodesReversed[i + 1]; + intVec = nodesReversed[num + 1]; } } else if (edifice == null || edifice.def.passability != Traversability.PassThroughOnly) @@ -65,14 +67,16 @@ public static IntVec3 FinalWalkableNonDoorCell(this PawnPath path, Map map) for (int i = 0; i < nodesReversed.Count; i++) { Building edifice = nodesReversed[i].GetEdifice(map); - if (edifice == null || edifice.def.passability != Traversability.Impassable) + if (edifice != null && edifice.def.passability == Traversability.Impassable) { - Building_Door building_Door = edifice as Building_Door; - if (building_Door == null || building_Door.FreePassage) - { - return nodesReversed[i]; - } + continue; } + Building_Door building_Door = edifice as Building_Door; + if (building_Door != null && !building_Door.FreePassage) + { + continue; + } + return nodesReversed[i]; } return nodesReversed[0]; } @@ -84,19 +88,19 @@ public static IntVec3 LastCellBeforeBlockerOrFinalCell(this PawnPath path, Map m return path.NodesReversed[0]; } List nodesReversed = path.NodesReversed; - for (int i = nodesReversed.Count - 2; i >= 1; i--) + for (int num = nodesReversed.Count - 2; num >= 1; num--) { - Building edifice = nodesReversed[i].GetEdifice(map); + Building edifice = nodesReversed[num].GetEdifice(map); if (edifice != null) { if (edifice.def.passability == Traversability.Impassable) { - return nodesReversed[i + 1]; + return nodesReversed[num + 1]; } Building_Door building_Door = edifice as Building_Door; if (building_Door != null && !building_Door.FreePassage) { - return nodesReversed[i + 1]; + return nodesReversed[num + 1]; } } } @@ -111,12 +115,12 @@ public static bool TryFindLastCellBeforeBlockingDoor(this PawnPath path, Pawn pa return false; } List nodesReversed = path.NodesReversed; - for (int i = nodesReversed.Count - 2; i >= 1; i--) + for (int num = nodesReversed.Count - 2; num >= 1; num--) { - Building_Door building_Door = nodesReversed[i].GetEdifice(pawn.Map) as Building_Door; + Building_Door building_Door = nodesReversed[num].GetEdifice(pawn.Map) as Building_Door; if (building_Door != null && !building_Door.CanPhysicallyPass(pawn)) { - result = nodesReversed[i + 1]; + result = nodesReversed[num + 1]; return true; } } @@ -126,13 +130,13 @@ public static bool TryFindLastCellBeforeBlockingDoor(this PawnPath path, Pawn pa public static bool TryFindCellAtIndex(PawnPath path, int index, out IntVec3 result) { - if (path.NodesReversed.Count <= index || index < 0) + if (path.NodesReversed.Count > index && index >= 0) { - result = IntVec3.Invalid; - return false; + result = path.NodesReversed[path.NodesReversed.Count - 1 - index]; + return true; } - result = path.NodesReversed[path.NodesReversed.Count - 1 - index]; - return true; + result = IntVec3.Invalid; + return false; } } } diff --git a/Assembly-CSharp/Verse.AI/Pawn_JobTracker.cs b/Assembly-CSharp/Verse.AI/Pawn_JobTracker.cs index a154d0e27..6d0ccb26e 100644 --- a/Assembly-CSharp/Verse.AI/Pawn_JobTracker.cs +++ b/Assembly-CSharp/Verse.AI/Pawn_JobTracker.cs @@ -140,21 +140,12 @@ private void FinalizeTick() string text = GenText.ToCommaList(this.jobsGivenRecentTicksTextual, true); this.jobsGivenRecentTicks.Clear(); this.jobsGivenRecentTicksTextual.Clear(); - this.StartErrorRecoverJob(string.Concat(new object[] - { - this.pawn, - " started ", - 10, - " jobs in ", - 10, - " ticks. List: ", - text - })); + this.StartErrorRecoverJob(this.pawn + " started " + 10 + " jobs in " + 10 + " ticks. List: " + text); } } } - public void StartJob(Job newJob, JobCondition lastJobEndCondition = JobCondition.None, ThinkNode jobGiver = null, bool resumeCurJobAfterwards = false, bool cancelBusyStances = true, ThinkTreeDef thinkTree = null, JobTag? tag = null) + public void StartJob(Job newJob, JobCondition lastJobEndCondition = JobCondition.None, ThinkNode jobGiver = null, bool resumeCurJobAfterwards = false, bool cancelBusyStances = true, ThinkTreeDef thinkTree = null, JobTag? tag = default(JobTag?)) { if (!Find.TickManager.Paused || this.lastJobGivenAtFrame == RealTime.frameCount) { @@ -167,121 +158,94 @@ public void StartJob(Job newJob, JobCondition lastJobEndCondition = JobCondition string text = this.jobsGivenThisTickTextual; this.jobsGivenThisTick = 0; this.jobsGivenThisTickTextual = string.Empty; - this.StartErrorRecoverJob(string.Concat(new object[] - { - this.pawn, - " started 10 jobs in one tick. newJob=", - newJob, - " jobGiver=", - jobGiver, - " jobList=", - text - })); - return; + this.StartErrorRecoverJob(this.pawn + " started 10 jobs in one tick. newJob=" + newJob + " jobGiver=" + jobGiver + " jobList=" + text); } - PawnPosture posture = this.pawn.GetPosture(); - LayingDownState layingDown = (this.pawn.jobs == null || this.pawn.jobs.curDriver == null) ? LayingDownState.NotLaying : this.pawn.jobs.curDriver.layingDown; - if (this.debugLog) + else { - this.DebugLogEvent(string.Concat(new object[] + PawnPosture posture = this.pawn.GetPosture(); + LayingDownState layingDown = (this.pawn.jobs != null && this.pawn.jobs.curDriver != null) ? this.pawn.jobs.curDriver.layingDown : LayingDownState.NotLaying; + if (this.debugLog) { - "StartJob [", - newJob, - "] lastJobEndCondition=", - lastJobEndCondition, - ", jobGiver=", - jobGiver, - ", cancelBusyStances=", - cancelBusyStances - })); - } - if (cancelBusyStances && this.pawn.stances.FullBodyBusy) - { - this.pawn.stances.CancelBusyStanceHard(); - } - if (this.curJob != null) - { - if (lastJobEndCondition == JobCondition.None) + this.DebugLogEvent("StartJob [" + newJob + "] lastJobEndCondition=" + lastJobEndCondition + ", jobGiver=" + jobGiver + ", cancelBusyStances=" + cancelBusyStances); + } + if (cancelBusyStances && this.pawn.stances.FullBodyBusy) + { + this.pawn.stances.CancelBusyStanceHard(); + } + if (this.curJob != null) { - Log.Warning(string.Concat(new object[] + if (lastJobEndCondition == JobCondition.None) { - this.pawn, - " starting job ", - newJob, - " from JobGiver ", - this.pawn.mindState.lastJobGiver, - " while already having job ", - this.curJob, - " without a specific job end condition." - })); - lastJobEndCondition = JobCondition.InterruptForced; + Log.Warning(this.pawn + " starting job " + newJob + " from JobGiver " + this.pawn.mindState.lastJobGiver + " while already having job " + this.curJob + " without a specific job end condition."); + lastJobEndCondition = JobCondition.InterruptForced; + } + if (resumeCurJobAfterwards && this.curJob.def.suspendable) + { + this.jobQueue.EnqueueFirst(this.curJob, default(JobTag?)); + if (this.debugLog) + { + this.DebugLogEvent(" JobQueue EnqueueFirst curJob: " + this.curJob); + } + } + this.CleanupCurrentJob(lastJobEndCondition, !resumeCurJobAfterwards, cancelBusyStances); } - if (resumeCurJobAfterwards && this.curJob.def.suspendable) + if (newJob == null) { - this.jobQueue.EnqueueFirst(this.curJob, null); - if (this.debugLog) + Log.Warning(this.pawn + " tried to start doing a null job."); + } + else + { + newJob.startTick = Find.TickManager.TicksGame; + if (this.pawn.Drafted || newJob.playerForced) + { + newJob.ignoreForbidden = true; + newJob.ignoreDesignations = true; + } + this.curJob = newJob; + this.pawn.mindState.lastJobGiver = jobGiver; + this.pawn.mindState.lastJobGiverThinkTree = thinkTree; + if (tag.HasValue) { - this.DebugLogEvent(" JobQueue EnqueueFirst curJob: " + this.curJob); + this.pawn.mindState.lastJobTag = tag.Value; } + this.curDriver = this.curJob.MakeDriver(this.pawn); + this.curDriver.Notify_Starting(); + this.curDriver.Notify_LastPosture(posture, layingDown); + this.curDriver.SetupToils(); + this.curDriver.ReadyForNextToil(); } - this.CleanupCurrentJob(lastJobEndCondition, !resumeCurJobAfterwards, cancelBusyStances); - } - if (newJob == null) - { - Log.Warning(this.pawn + " tried to start doing a null job."); - return; } - newJob.startTick = Find.TickManager.TicksGame; - if (this.pawn.Drafted || newJob.playerForced) - { - newJob.ignoreForbidden = true; - newJob.ignoreDesignations = true; - } - this.curJob = newJob; - this.pawn.mindState.lastJobGiver = jobGiver; - this.pawn.mindState.lastJobGiverThinkTree = thinkTree; - if (tag.HasValue) - { - this.pawn.mindState.lastJobTag = tag.Value; - } - this.curDriver = this.curJob.MakeDriver(this.pawn); - this.curDriver.Notify_Starting(); - this.curDriver.Notify_LastPosture(posture, layingDown); - this.curDriver.SetupToils(); - this.curDriver.ReadyForNextToil(); } public void EndCurrentJob(JobCondition condition, bool startNewJob = true) { if (this.debugLog) { - this.DebugLogEvent(string.Concat(new object[] - { - "EndCurrentJob ", - (this.curJob == null) ? "null" : this.curJob.ToString(), - " condition=", - condition, - " curToil=", - (this.curDriver == null) ? "null_driver" : this.curDriver.CurToilIndex.ToString() - })); + this.DebugLogEvent("EndCurrentJob " + ((this.curJob == null) ? "null" : this.curJob.ToString()) + " condition=" + condition + " curToil=" + ((this.curDriver == null) ? "null_driver" : this.curDriver.CurToilIndex.ToString())); } Job job = this.curJob; this.CleanupCurrentJob(condition, true, true); if (startNewJob) { - if (condition == JobCondition.ErroredPather || condition == JobCondition.Errored) + switch (condition) + { + case JobCondition.Errored: + case JobCondition.ErroredPather: { - this.StartJob(new Job(JobDefOf.Wait, 250, false), JobCondition.None, null, false, true, null, null); + this.StartJob(new Job(JobDefOf.Wait, 250, false), JobCondition.None, null, false, true, null, default(JobTag?)); return; } - if (condition == JobCondition.Succeeded && job != null && job.def != JobDefOf.WaitMaintainPosture && !this.pawn.pather.Moving) + case JobCondition.Succeeded: { - this.StartJob(new Job(JobDefOf.WaitMaintainPosture, 1, false), JobCondition.None, null, false, false, null, null); + if (job != null && job.def != JobDefOf.WaitMaintainPosture && !this.pawn.pather.Moving) + { + this.StartJob(new Job(JobDefOf.WaitMaintainPosture, 1, false), JobCondition.None, null, false, false, null, default(JobTag?)); + return; + } + break; } - else - { - this.TryFindAndStartJob(); } + this.TryFindAndStartJob(); } } @@ -289,34 +253,27 @@ private void CleanupCurrentJob(JobCondition condition, bool releaseReservations, { if (this.debugLog) { - this.DebugLogEvent(string.Concat(new object[] - { - "CleanupCurrentJob ", - (this.curJob == null) ? "null" : this.curJob.def.ToString(), - " condition ", - condition - })); + this.DebugLogEvent("CleanupCurrentJob " + ((this.curJob == null) ? "null" : this.curJob.def.ToString()) + " condition " + condition); } - if (this.curJob == null) - { - return; - } - this.curDriver.ended = true; - this.curDriver.Cleanup(condition); - this.curDriver = null; - this.curJob = null; - if (releaseReservations) - { - this.pawn.ClearReservations(false); - } - if (cancelBusyStancesSoft) - { - this.pawn.stances.CancelBusyStanceSoft(); - } - if (!this.pawn.Destroyed && this.pawn.carryTracker != null && this.pawn.carryTracker.CarriedThing != null) + if (this.curJob != null) { - Thing thing; - this.pawn.carryTracker.TryDropCarriedThing(this.pawn.Position, ThingPlaceMode.Near, out thing, null); + this.curDriver.ended = true; + this.curDriver.Cleanup(condition); + this.curDriver = null; + this.curJob = null; + if (releaseReservations) + { + this.pawn.ClearReservations(false); + } + if (cancelBusyStancesSoft) + { + this.pawn.stances.CancelBusyStanceSoft(); + } + if (!this.pawn.Destroyed && this.pawn.carryTracker != null && this.pawn.carryTracker.CarriedThing != null) + { + Thing thing = default(Thing); + this.pawn.carryTracker.TryDropCarriedThing(this.pawn.Position, ThingPlaceMode.Near, out thing, (Action)null); + } } } @@ -326,7 +283,7 @@ public void CheckForJobOverride() { this.DebugLogEvent("CheckForJobOverride"); } - ThinkTreeDef thinkTree; + ThinkTreeDef thinkTree = default(ThinkTreeDef); ThinkResult thinkResult = this.DetermineNextJob(out thinkTree); if (this.ShouldStartJobFromThinkTree(thinkResult)) { @@ -337,10 +294,8 @@ public void CheckForJobOverride() public void StopAll(bool ifLayingKeepLaying = false) { - if (ifLayingKeepLaying && this.curJob != null && this.curDriver.layingDown != LayingDownState.NotLaying) - { + if ((ifLayingKeepLaying ? ((this.curJob != null) ? this.curDriver.layingDown : LayingDownState.NotLaying) : LayingDownState.NotLaying) != 0) return; - } this.CleanupCurrentJob(JobCondition.InterruptForced, true, true); this.jobQueue.Clear(); } @@ -350,36 +305,40 @@ private void TryFindAndStartJob() if (this.pawn.thinker == null) { Log.ErrorOnce(this.pawn + " did TryFindAndStartJob but had no thinker.", 8573261); - return; - } - if (this.curJob != null) - { - Log.Warning(this.pawn + " doing TryFindAndStartJob while still having job " + this.curJob); - } - if (this.debugLog) - { - this.DebugLogEvent("TryFindAndStartJob"); } - if (!this.CanDoAnyJob()) + else { + if (this.curJob != null) + { + Log.Warning(this.pawn + " doing TryFindAndStartJob while still having job " + this.curJob); + } if (this.debugLog) { - this.DebugLogEvent(" CanDoAnyJob is false. Clearing queue and returning"); + this.DebugLogEvent("TryFindAndStartJob"); + } + if (!this.CanDoAnyJob()) + { + if (this.debugLog) + { + this.DebugLogEvent(" CanDoAnyJob is false. Clearing queue and returning"); + } + if (this.jobQueue != null) + { + this.jobQueue.Clear(); + } } - if (this.jobQueue != null) + else { - this.jobQueue.Clear(); + ThinkTreeDef thinkTreeDef = default(ThinkTreeDef); + ThinkResult result = this.DetermineNextJob(out thinkTreeDef); + if (result.IsValid) + { + this.CheckLeaveJoinableLordBecauseJobIssued(result); + ThinkNode sourceNode = result.SourceNode; + ThinkTreeDef thinkTree = thinkTreeDef; + this.StartJob(result.Job, JobCondition.None, sourceNode, false, false, thinkTree, result.Tag); + } } - return; - } - ThinkTreeDef thinkTreeDef; - ThinkResult result = this.DetermineNextJob(out thinkTreeDef); - if (result.IsValid) - { - this.CheckLeaveJoinableLordBecauseJobIssued(result); - ThinkNode sourceNode = result.SourceNode; - ThinkTreeDef thinkTree = thinkTreeDef; - this.StartJob(result.Job, JobCondition.None, sourceNode, false, false, thinkTree, result.Tag); } } @@ -422,6 +381,7 @@ private ThinkResult DetermineNextJob(out ThinkTreeDef thinkTree) this.StartErrorRecoverJob(this.pawn + " threw exception while determining job (main): " + ex.ToString()); thinkTree = null; return ThinkResult.NoJob; + IL_0148:; } finally { @@ -439,6 +399,7 @@ private ThinkResult DetermineNextConstantThinkTreeJob() try { return this.pawn.thinker.ConstantThinkNodeRoot.TryIssueJobPackage(this.pawn, default(JobIssueParams)); + IL_0045:; } catch (Exception ex) { @@ -468,14 +429,14 @@ public void StartErrorRecoverJob(string message) } if (this.startingErrorRecoverJob) { - Log.Error("An error occurred while starting an error recover job. We have to stop now to avoid infinite loops. This means that the pawn is now jobless which can cause further bugs. pawn=" + this.pawn.ToStringSafe()); + Log.Error("An error occurred while starting an error recover job. We have to stop now to avoid infinite loops. This means that the pawn is now jobless which can cause further bugs. pawn=" + this.pawn.ToStringSafe()); } else { this.startingErrorRecoverJob = true; try { - this.StartJob(new Job(JobDefOf.Wait, 150, false), JobCondition.None, null, false, true, null, null); + this.StartJob(new Job(JobDefOf.Wait, 150, false), JobCondition.None, null, false, true, null, default(JobTag?)); } finally { @@ -486,32 +447,30 @@ public void StartErrorRecoverJob(string message) private void CheckLeaveJoinableLordBecauseJobIssued(ThinkResult result) { - if (!result.IsValid || result.SourceNode == null) + if (result.IsValid && result.SourceNode != null) { - return; - } - Lord lord = this.pawn.GetLord(); - if (lord == null || !(lord.LordJob is LordJob_VoluntarilyJoinable)) - { - return; - } - bool flag = false; - ThinkNode thinkNode = result.SourceNode; - while (!thinkNode.leaveJoinableLordIfIssuesJob) - { - thinkNode = thinkNode.parent; - if (thinkNode == null) + Lord lord = this.pawn.GetLord(); + if (lord != null && lord.LordJob is LordJob_VoluntarilyJoinable) { - IL_6F: + bool flag = false; + ThinkNode thinkNode = result.SourceNode; + while (true) + { + if (thinkNode.leaveJoinableLordIfIssuesJob) + { + flag = true; + break; + } + thinkNode = thinkNode.parent; + if (thinkNode == null) + break; + } if (flag) { lord.Notify_PawnLost(this.pawn, PawnLostCondition.LeftVoluntarily); } - return; } } - flag = true; - goto IL_6F; } private bool CanDoAnyJob() @@ -521,12 +480,28 @@ private bool CanDoAnyJob() private bool ShouldStartJobFromThinkTree(ThinkResult thinkResult) { - return this.curJob == null || (thinkResult.Job.def != this.curJob.def || thinkResult.SourceNode != this.pawn.mindState.lastJobGiver || !this.curDriver.IsContinuation(thinkResult.Job)); + if (this.curJob == null) + { + return true; + } + if (thinkResult.Job.def == this.curJob.def && thinkResult.SourceNode == this.pawn.mindState.lastJobGiver && this.curDriver.IsContinuation(thinkResult.Job)) + { + return false; + } + return true; } public bool IsCurrentJobPlayerInterruptible() { - return (this.curJob == null || this.curJob.def.playerInterruptible) && !this.pawn.HasAttachment(ThingDefOf.Fire); + if (this.curJob != null && !this.curJob.def.playerInterruptible) + { + return false; + } + if (this.pawn.HasAttachment(ThingDefOf.Fire)) + { + return false; + } + return true; } public bool TryTakeOrderedJobPrioritizedWork(Job job, WorkGiver giver, IntVec3 cell) @@ -585,27 +560,23 @@ public void Notify_TuckedIntoBed(Building_Bed bed) this.pawn.Position = RestUtility.GetBedSleepingSlotPosFor(this.pawn, bed); this.pawn.Notify_Teleported(false); this.pawn.stances.CancelBusyStanceHard(); - this.StartJob(new Job(JobDefOf.LayDown, bed), JobCondition.InterruptForced, null, false, true, null, new JobTag?(JobTag.TuckedIntoBed)); + this.StartJob(new Job(JobDefOf.LayDown, (Thing)bed), JobCondition.InterruptForced, null, false, true, null, new JobTag?(JobTag.TuckedIntoBed)); } public void Notify_DamageTaken(DamageInfo dinfo) { - if (this.curJob == null) - { - return; - } - if (Find.TickManager.TicksGame < this.lastDamageCheckTick + 180) - { - return; - } - if (dinfo.Def.externalViolence && dinfo.Def.canInterruptJobs && !this.curJob.playerForced) + if (this.curJob != null && Find.TickManager.TicksGame >= this.lastDamageCheckTick + 180 && dinfo.Def.externalViolence && dinfo.Def.canInterruptJobs && !this.curJob.playerForced) { Thing instigator = dinfo.Instigator; - if (this.curJob.def.checkOverrideOnDamage == CheckJobOverrideOnDamageMode.Always || (this.curJob.def.checkOverrideOnDamage == CheckJobOverrideOnDamageMode.OnlyIfInstigatorNotJobTarget && !this.curJob.AnyTargetIs(instigator))) + if (this.curJob.def.checkOverrideOnDamage != CheckJobOverrideOnDamageMode.Always) { - this.lastDamageCheckTick = Find.TickManager.TicksGame; - this.CheckForJobOverride(); + if (this.curJob.def.checkOverrideOnDamage != CheckJobOverrideOnDamageMode.OnlyIfInstigatorNotJobTarget) + return; + if (this.curJob.AnyTargetIs(instigator)) + return; } + this.lastDamageCheckTick = Find.TickManager.TicksGame; + this.CheckForJobOverride(); } } @@ -618,14 +589,7 @@ public void DebugLogEvent(string s) { if (this.debugLog) { - Log.Message(string.Concat(new object[] - { - Find.TickManager.TicksGame, - " ", - this.pawn, - ": ", - s - })); + Log.Message(Find.TickManager.TicksGame + " " + this.pawn + ": " + s); } } } diff --git a/Assembly-CSharp/Verse.AI/Pawn_MindState.cs b/Assembly-CSharp/Verse.AI/Pawn_MindState.cs index c01692828..fdd1e4136 100644 --- a/Assembly-CSharp/Verse.AI/Pawn_MindState.cs +++ b/Assembly-CSharp/Verse.AI/Pawn_MindState.cs @@ -2,7 +2,7 @@ using RimWorld.Planet; using System; using System.Collections.Generic; -using System.Diagnostics; +using Verse.AI.Group; namespace Verse.AI { @@ -119,7 +119,15 @@ public bool IsIdle { get { - return !this.pawn.Downed && this.pawn.Spawned && this.lastJobTag == JobTag.Idle; + if (this.pawn.Downed) + { + return false; + } + if (!this.pawn.Spawned) + { + return false; + } + return this.lastJobTag == JobTag.Idle; } } @@ -127,7 +135,7 @@ public bool MeleeThreatStillThreat { get { - return this.meleeThreat != null && this.meleeThreat.Spawned && !this.meleeThreat.Downed && this.pawn.Spawned && Find.TickManager.TicksGame <= this.lastMeleeThreatHarmTick + 400 && (float)(this.pawn.Position - this.meleeThreat.Position).LengthHorizontalSquared <= 9f && GenSight.LineOfSight(this.pawn.Position, this.meleeThreat.Position, this.pawn.Map, false, null, 0, 0); + return this.meleeThreat != null && this.meleeThreat.Spawned && !this.meleeThreat.Downed && this.pawn.Spawned && Find.TickManager.TicksGame <= this.lastMeleeThreatHarmTick + 400 && (float)(this.pawn.Position - this.meleeThreat.Position).LengthHorizontalSquared <= 9.0 && GenSight.LineOfSight(this.pawn.Position, this.meleeThreat.Position, this.pawn.Map, false, null, 0, 0); } } @@ -184,7 +192,7 @@ public void ExposeData() { if (Scribe.mode == LoadSaveMode.Saving) { - this.lastJobGiverKey = ((this.lastJobGiver == null) ? -1 : this.lastJobGiver.UniqueSaveKey); + this.lastJobGiverKey = ((this.lastJobGiver == null) ? (-1) : this.lastJobGiver.UniqueSaveKey); } Scribe_Values.Look(ref this.lastJobGiverKey, "lastJobGiverKey", -1, false); if (Scribe.mode == LoadSaveMode.PostLoadInit && this.lastJobGiverKey != -1 && !this.lastJobGiverThinkTree.TryGetThinkNodeWithSaveKey(this.lastJobGiverKey, out this.lastJobGiver)) @@ -219,15 +227,15 @@ public void ExposeData() Scribe_Values.Look(ref this.lastHarmTick, "lastHarmTick", -99999, false); Scribe_Values.Look(ref this.anyCloseHostilesRecently, "anyCloseHostilesRecently", false, false); Scribe_Deep.Look(ref this.duty, "duty", new object[0]); - Scribe_Deep.Look(ref this.mentalStateHandler, "mentalStateHandler", new object[] + Scribe_Deep.Look(ref this.mentalStateHandler, "mentalStateHandler", new object[1] { this.pawn }); - Scribe_Deep.Look(ref this.mentalBreaker, "mentalBreaker", new object[] + Scribe_Deep.Look(ref this.mentalBreaker, "mentalBreaker", new object[1] { this.pawn }); - Scribe_Deep.Look(ref this.priorityWork, "priorityWork", new object[] + Scribe_Deep.Look(ref this.priorityWork, "priorityWork", new object[1] { this.pawn }); @@ -269,14 +277,28 @@ public void ResetLastDisturbanceTick() this.lastDisturbanceTick = -9999999; } - [DebuggerHidden] public IEnumerable GetGizmos() { - Pawn_MindState.c__Iterator1BE c__Iterator1BE = new Pawn_MindState.c__Iterator1BE(); - c__Iterator1BE.<>f__this = this; - Pawn_MindState.c__Iterator1BE expr_0E = c__Iterator1BE; - expr_0E.$PC = -2; - return expr_0E; + foreach (Gizmo gizmo in this.priorityWork.GetGizmos()) + { + yield return gizmo; + } + Lord lord = this.pawn.GetLord(); + if (lord != null && lord.LordJob is LordJob_FormAndSendCaravan) + { + yield return (Gizmo)new Command_Action + { + defaultLabel = "CommandCancelFormingCaravan".Translate(), + defaultDesc = "CommandCancelFormingCaravanDesc".Translate(), + icon = TexCommand.ClearPrioritizedWork, + activateSound = SoundDefOf.TickLow, + action = (Action)delegate + { + CaravanFormingUtility.StopFormingCaravan(((_003CGetGizmos_003Ec__Iterator1BE)/*Error near IL_0140: stateMachine*/)._003Clord_003E__2); + }, + hotKey = KeyBindingDefOf.DesignatorCancel + }; + } } public void Notify_OutfitChanged() @@ -299,7 +321,7 @@ public void Notify_DamageTaken(DamageInfo dinfo) { this.lastHarmTick = Find.TickManager.TicksGame; Pawn pawn = dinfo.Instigator as Pawn; - if (!this.mentalStateHandler.InMentalState && dinfo.Instigator != null && (pawn != null || dinfo.Instigator is Building_Turret) && dinfo.Instigator.Faction != null && (dinfo.Instigator.Faction.def.humanlikeFaction || (pawn != null && pawn.def.race.intelligence >= Intelligence.ToolUser)) && this.pawn.Faction == null && (this.pawn.CurJob == null || this.pawn.CurJob.def != JobDefOf.PredatorHunt) && Rand.Value < this.pawn.RaceProps.manhunterOnDamageChance) + if (!this.mentalStateHandler.InMentalState && dinfo.Instigator != null && (pawn != null || dinfo.Instigator is Building_Turret) && dinfo.Instigator.Faction != null && (dinfo.Instigator.Faction.def.humanlikeFaction || (pawn != null && (int)pawn.def.race.intelligence >= 1)) && this.pawn.Faction == null && (this.pawn.CurJob == null || this.pawn.CurJob.def != JobDefOf.PredatorHunt) && Rand.Value < this.pawn.RaceProps.manhunterOnDamageChance) { this.StartManhunterBecauseOfPawnAction("AnimalManhunterFromDamage"); } @@ -307,7 +329,7 @@ public void Notify_DamageTaken(DamageInfo dinfo) { this.StartFleeingBecauseOfPawnAction(dinfo.Instigator); } - if (this.pawn.GetPosture() != PawnPosture.Standing) + if (this.pawn.GetPosture() != 0) { this.lastDisturbanceTick = Find.TickManager.TicksGame; } @@ -341,68 +363,52 @@ internal bool CheckStartMentalStateBecauseRecruitAttempted(Pawn tamer) internal void Notify_DangerousExploderAboutToExplode(Thing exploder) { - if (this.pawn.RaceProps.intelligence >= Intelligence.Humanlike) + if ((int)this.pawn.RaceProps.intelligence >= 2) { this.knownExploder = exploder; this.pawn.jobs.CheckForJobOverride(); } } - [DebuggerHidden] private IEnumerable GetPackmates(Pawn pawn, float radius) { - Pawn_MindState.c__Iterator1BF c__Iterator1BF = new Pawn_MindState.c__Iterator1BF(); - c__Iterator1BF.pawn = pawn; - c__Iterator1BF.radius = radius; - c__Iterator1BF.<$>pawn = pawn; - c__Iterator1BF.<$>radius = radius; - Pawn_MindState.c__Iterator1BF expr_23 = c__Iterator1BF; - expr_23.$PC = -2; - return expr_23; + Room pawnRoom = pawn.GetRoom(RegionType.Set_Passable); + List raceMates = pawn.Map.mapPawns.AllPawnsSpawned; + for (int i = 0; i < raceMates.Count; i++) + { + if (pawn != raceMates[i] && raceMates[i].def == pawn.def && raceMates[i].Faction == pawn.Faction && raceMates[i].Position.InHorDistOf(pawn.Position, radius) && raceMates[i].GetRoom(RegionType.Set_Passable) == pawnRoom) + { + yield return raceMates[i]; + } + } } private void StartManhunterBecauseOfPawnAction(string letterTextKey) { - if (!this.mentalStateHandler.TryStartMentalState(MentalStateDefOf.Manhunter, null, false, false, null)) + if (this.mentalStateHandler.TryStartMentalState(MentalStateDefOf.Manhunter, (string)null, false, false, null)) { - return; - } - string text = letterTextKey.Translate(new object[] - { - this.pawn.Label - }); - GlobalTargetInfo lookTarget = this.pawn; - if (Rand.Value < 0.5f) - { - int num = 1; - foreach (Pawn current in this.GetPackmates(this.pawn, 24f)) + string text = letterTextKey.Translate(this.pawn.Label); + GlobalTargetInfo lookTarget = (Thing)this.pawn; + if (Rand.Value < 0.5) { - if (current.mindState.mentalStateHandler.TryStartMentalState(MentalStateDefOf.Manhunter, null, false, false, null)) + int num = 1; + foreach (Pawn packmate in this.GetPackmates(this.pawn, 24f)) { - num++; + if (packmate.mindState.mentalStateHandler.TryStartMentalState(MentalStateDefOf.Manhunter, (string)null, false, false, null)) + { + num++; + } } - } - if (num > 1) - { - lookTarget = new TargetInfo(this.pawn.Position, this.pawn.Map, false); - text += "\n\n"; - text += ((!"AnimalManhunterOthers".CanTranslate()) ? "AnimalManhunterFromDamageOthers".Translate(new object[] - { - this.pawn.def.label - }) : "AnimalManhunterOthers".Translate(new object[] + if (num > 1) { - this.pawn.def.label - })); + lookTarget = new TargetInfo(this.pawn.Position, this.pawn.Map, false); + text += "\n\n"; + text += ((!"AnimalManhunterOthers".CanTranslate()) ? "AnimalManhunterFromDamageOthers".Translate(this.pawn.def.label) : "AnimalManhunterOthers".Translate(this.pawn.def.label)); + } } + string label = (!"LetterLabelAnimalManhunterRevenge".CanTranslate()) ? "LetterLabelAnimalManhunterFromDamage".Translate(this.pawn.Label).CapitalizeFirst() : "LetterLabelAnimalManhunterRevenge".Translate(this.pawn.Label).CapitalizeFirst(); + Find.LetterStack.ReceiveLetter(label, text, LetterDefOf.BadNonUrgent, lookTarget, (string)null); } - string label = (!"LetterLabelAnimalManhunterRevenge".CanTranslate()) ? "LetterLabelAnimalManhunterFromDamage".Translate(new object[] - { - this.pawn.Label - }).CapitalizeFirst() : "LetterLabelAnimalManhunterRevenge".Translate(new object[] - { - this.pawn.Label - }).CapitalizeFirst(); - Find.LetterStack.ReceiveLetter(label, text, LetterDefOf.BadNonUrgent, lookTarget, null); } private static bool CanStartFleeingBecauseOfPawnAction(Pawn p) @@ -412,25 +418,24 @@ private static bool CanStartFleeingBecauseOfPawnAction(Pawn p) private void StartFleeingBecauseOfPawnAction(Thing instigator) { - List threats = new List - { - instigator - }; - IntVec3 fleeDest = CellFinderLoose.GetFleeDest(this.pawn, threats, this.pawn.Position.DistanceTo(instigator.Position) + 14f); + List list = new List(); + list.Add(instigator); + List threats = list; + IntVec3 fleeDest = CellFinderLoose.GetFleeDest(this.pawn, threats, (float)(this.pawn.Position.DistanceTo(instigator.Position) + 14.0)); if (fleeDest.IsValid) { - this.pawn.jobs.StartJob(new Job(JobDefOf.Flee, fleeDest, instigator), JobCondition.InterruptOptional, null, false, true, null, null); + this.pawn.jobs.StartJob(new Job(JobDefOf.Flee, fleeDest, instigator), JobCondition.InterruptOptional, null, false, true, null, default(JobTag?)); } if (this.pawn.RaceProps.herdAnimal && Rand.Chance(0.1f)) { - foreach (Pawn current in this.GetPackmates(this.pawn, 24f)) + foreach (Pawn packmate in this.GetPackmates(this.pawn, 24f)) { - if (Pawn_MindState.CanStartFleeingBecauseOfPawnAction(current)) + if (Pawn_MindState.CanStartFleeingBecauseOfPawnAction(packmate)) { - IntVec3 fleeDest2 = CellFinderLoose.GetFleeDest(this.pawn, threats, this.pawn.Position.DistanceTo(instigator.Position) + 14f); + IntVec3 fleeDest2 = CellFinderLoose.GetFleeDest(this.pawn, threats, (float)(this.pawn.Position.DistanceTo(instigator.Position) + 14.0)); if (fleeDest2.IsValid) { - current.jobs.StartJob(new Job(JobDefOf.Flee, fleeDest2, instigator), JobCondition.InterruptOptional, null, false, true, null, null); + packmate.jobs.StartJob(new Job(JobDefOf.Flee, fleeDest2, instigator), JobCondition.InterruptOptional, null, false, true, null, default(JobTag?)); } } } diff --git a/Assembly-CSharp/Verse.AI/Pawn_PathFollower.cs b/Assembly-CSharp/Verse.AI/Pawn_PathFollower.cs index 4a61fe74c..a596d826d 100644 --- a/Assembly-CSharp/Verse.AI/Pawn_PathFollower.cs +++ b/Assembly-CSharp/Verse.AI/Pawn_PathFollower.cs @@ -1,5 +1,4 @@ using RimWorld; -using System; using UnityEngine; namespace Verse.AI @@ -105,48 +104,49 @@ public void StartPath(LocalTargetInfo dest, PathEndMode peMode) { Log.Error(this.pawn + " pathing to destroyed thing " + dest.Thing); this.PatherFailed(); - return; - } - if (!this.PawnCanOccupy(this.pawn.Position) && !this.TryRecoverFromUnwalkablePosition(dest)) - { - return; - } - if (this.moving && this.curPath != null && this.destination == dest && this.peMode == peMode) - { - return; - } - if (!this.pawn.Map.reachability.CanReach(this.pawn.Position, dest, peMode, TraverseParms.For(TraverseMode.PassDoors, Danger.Deadly, false))) - { - this.PatherFailed(); - return; - } - this.peMode = peMode; - this.destination = dest; - if (!this.IsNextCellWalkable()) - { - this.nextCell = this.pawn.Position; } - if (!this.destination.HasThing && this.pawn.Map.pawnDestinationManager.DestinationReservedFor(this.pawn) != this.destination.Cell) - { - this.pawn.Map.pawnDestinationManager.UnreserveAllFor(this.pawn); - } - if (this.AtDestinationPosition()) - { - this.PatherArrived(); - return; - } - if (this.pawn.Downed) - { - Log.Error(this.pawn.LabelCap + " tried to path while incapacitated. This should never happen."); - this.PatherFailed(); - return; - } - if (this.curPath != null) + else { - this.curPath.ReleaseToPool(); + if (!this.PawnCanOccupy(this.pawn.Position) && !this.TryRecoverFromUnwalkablePosition(dest)) + return; + if (this.moving && this.curPath != null && this.destination == dest && this.peMode == peMode) + return; + if (!this.pawn.Map.reachability.CanReach(this.pawn.Position, dest, peMode, TraverseParms.For(TraverseMode.PassDoors, Danger.Deadly, false))) + { + this.PatherFailed(); + } + else + { + this.peMode = peMode; + this.destination = dest; + if (!this.IsNextCellWalkable()) + { + this.nextCell = this.pawn.Position; + } + if (!this.destination.HasThing && this.pawn.Map.pawnDestinationManager.DestinationReservedFor(this.pawn) != this.destination.Cell) + { + this.pawn.Map.pawnDestinationManager.UnreserveAllFor(this.pawn); + } + if (this.AtDestinationPosition()) + { + this.PatherArrived(); + } + else if (this.pawn.Downed) + { + Log.Error(this.pawn.LabelCap + " tried to path while incapacitated. This should never happen."); + this.PatherFailed(); + } + else + { + if (this.curPath != null) + { + this.curPath.ReleaseToPool(); + } + this.curPath = null; + this.moving = true; + } + } } - this.curPath = null; - this.moving = true; } public void StopDead() @@ -162,61 +162,60 @@ public void StopDead() public void PatherTick() { - if (this.pawn.stances.FullBodyBusy) - { - return; - } - if (this.WillCollideWithPawnAt(this.pawn.Position)) + if (!this.pawn.stances.FullBodyBusy) { - if (!this.FailedToFindCloseUnoccupiedCellRecently()) + if (this.WillCollideWithPawnAt(this.pawn.Position)) { - IntVec3 position; - if (CellFinder.TryFindBestPawnStandCell(this.pawn, out position)) + if (!this.FailedToFindCloseUnoccupiedCellRecently()) { - this.pawn.Position = position; - this.ResetToCurrentPosition(); - if (this.moving && this.TrySetNewPath()) + IntVec3 position = default(IntVec3); + if (CellFinder.TryFindBestPawnStandCell(this.pawn, out position)) { - this.TryEnterNextPathCell(); + this.pawn.Position = position; + this.ResetToCurrentPosition(); + if (this.moving && this.TrySetNewPath()) + { + this.TryEnterNextPathCell(); + } + } + else + { + this.failedToFindCloseUnoccupiedCellTicks = Find.TickManager.TicksGame; } - } - else - { - this.failedToFindCloseUnoccupiedCellTicks = Find.TickManager.TicksGame; } } - return; - } - if (!this.moving || !this.WillCollideWithPawnOnNextPathCell()) - { - this.lastMovedTick = Find.TickManager.TicksGame; - if (this.nextCellCostLeft > 0f) - { - this.nextCellCostLeft -= this.CostToPayThisTick(); - } - else if (this.moving) + else if (this.moving && this.WillCollideWithPawnOnNextPathCell()) { - this.TryEnterNextPathCell(); + this.nextCellCostLeft = this.nextCellCostTotal; + if (((this.curPath != null && this.curPath.NodesLeftCount < 30) || PawnUtility.AnyPawnBlockingPathAt(this.nextCell, this.pawn, false, true)) && !this.BestPathHadPawnsInTheWayRecently() && this.TrySetNewPath()) + { + this.ResetToCurrentPosition(); + this.TryEnterNextPathCell(); + return; + } + if (Find.TickManager.TicksGame - this.lastMovedTick >= 180) + { + Pawn pawn = PawnUtility.PawnBlockingPathAt(this.nextCell, this.pawn, false, false); + if (pawn != null && this.pawn.HostileTo(pawn) && this.pawn.TryGetAttackVerb(false) != null) + { + Job job = new Job(JobDefOf.AttackMelee, (Thing)pawn); + job.maxNumMeleeAttacks = 1; + job.expiryInterval = 300; + this.pawn.jobs.StartJob(job, JobCondition.Incompletable, null, false, true, null, default(JobTag?)); + } + } } - return; - } - this.nextCellCostLeft = this.nextCellCostTotal; - if (((this.curPath != null && this.curPath.NodesLeftCount < 30) || PawnUtility.AnyPawnBlockingPathAt(this.nextCell, this.pawn, false, true)) && !this.BestPathHadPawnsInTheWayRecently() && this.TrySetNewPath()) - { - this.ResetToCurrentPosition(); - this.TryEnterNextPathCell(); - return; - } - if (Find.TickManager.TicksGame - this.lastMovedTick >= 180) - { - Pawn pawn = PawnUtility.PawnBlockingPathAt(this.nextCell, this.pawn, false, false); - if (pawn != null && this.pawn.HostileTo(pawn) && this.pawn.TryGetAttackVerb(false) != null) + else { - Job job = new Job(JobDefOf.AttackMelee, pawn); - job.maxNumMeleeAttacks = 1; - job.expiryInterval = 300; - this.pawn.jobs.StartJob(job, JobCondition.Incompletable, null, false, true, null, null); - return; + this.lastMovedTick = Find.TickManager.TicksGame; + if (this.nextCellCostLeft > 0.0) + { + this.nextCellCostLeft -= this.CostToPayThisTick(); + } + else if (this.moving) + { + this.TryEnterNextPathCell(); + } } } } @@ -276,12 +275,24 @@ public bool WillCollideWithPawnOnNextPathCell() private bool IsNextCellWalkable() { - return this.nextCell.Walkable(this.pawn.Map) && !this.WillCollideWithPawnAt(this.nextCell); + if (!this.nextCell.Walkable(this.pawn.Map)) + { + return false; + } + if (this.WillCollideWithPawnAt(this.nextCell)) + { + return false; + } + return true; } private bool WillCollideWithPawnAt(IntVec3 c) { - return PawnUtility.ShouldCollideWithPawns(this.pawn) && PawnUtility.AnyPawnBlockingPathAt(c, this.pawn, false, false); + if (!PawnUtility.ShouldCollideWithPawns(this.pawn)) + { + return false; + } + return PawnUtility.AnyPawnBlockingPathAt(c, this.pawn, false, false); } public Building_Door NextCellDoorToManuallyOpen() @@ -315,14 +326,7 @@ private bool TryRecoverFromUnwalkablePosition(LocalTargetInfo originalDest) IntVec3 intVec = this.pawn.Position + GenRadial.RadialPattern[i]; if (this.PawnCanOccupy(intVec)) { - Log.Warning(string.Concat(new object[] - { - this.pawn, - " on unwalkable cell ", - this.pawn.Position, - ". Teleporting to ", - intVec - })); + Log.Warning(this.pawn + " on unwalkable cell " + this.pawn.Position + ". Teleporting to " + intVec); this.pawn.Position = intVec; this.moving = false; this.nextCell = this.pawn.Position; @@ -334,13 +338,7 @@ private bool TryRecoverFromUnwalkablePosition(LocalTargetInfo originalDest) if (!flag) { this.pawn.Destroy(DestroyMode.Vanish); - Log.Error(string.Concat(new object[] - { - this.pawn, - " on unwalkable cell ", - this.pawn.Position, - ". Could not find walkable position nearby. Destroyed." - })); + Log.Error(this.pawn + " on unwalkable cell " + this.pawn.Position + ". Could not find walkable position nearby. Destroyed."); } return flag; } @@ -366,127 +364,129 @@ private void TryEnterNextPathCell() if (building != null) { Building_Door building_Door = building as Building_Door; - if (building_Door == null || !building_Door.FreePassage) + if (building_Door != null && building_Door.FreePassage) { - if ((this.pawn.CurJob != null && this.pawn.CurJob.canBash) || this.pawn.HostileTo(building)) - { - Job job = new Job(JobDefOf.AttackMelee, building); - job.expiryInterval = 300; - this.pawn.jobs.StartJob(job, JobCondition.Incompletable, null, false, true, null, null); - return; - } - this.PatherFailed(); - return; + goto IL_009f; + } + if (this.pawn.CurJob != null && this.pawn.CurJob.canBash) + { + goto IL_005b; } + if (this.pawn.HostileTo(building)) + goto IL_005b; + this.PatherFailed(); + return; } + goto IL_009f; + IL_009f: Building_Door building_Door2 = this.NextCellDoorToManuallyOpen(); if (building_Door2 != null) { - Stance_Cooldown stance_Cooldown = new Stance_Cooldown(building_Door2.TicksToOpenNow, building_Door2, null); + Stance_Cooldown stance_Cooldown = new Stance_Cooldown(building_Door2.TicksToOpenNow, (Thing)building_Door2, null); stance_Cooldown.neverAimWeapon = true; this.pawn.stances.SetStance(stance_Cooldown); building_Door2.StartManualOpenBy(this.pawn); - return; } - this.lastCell = this.pawn.Position; - this.pawn.Position = this.nextCell; - if (this.pawn.RaceProps.Humanlike) + else { - this.cellsUntilClamor--; - if (this.cellsUntilClamor <= 0) + this.lastCell = this.pawn.Position; + this.pawn.Position = this.nextCell; + if (this.pawn.RaceProps.Humanlike) { - GenClamor.DoClamor(this.pawn, 7f, ClamorType.Movement); - this.cellsUntilClamor = 12; + this.cellsUntilClamor--; + if (this.cellsUntilClamor <= 0) + { + GenClamor.DoClamor(this.pawn, 7f, ClamorType.Movement); + this.cellsUntilClamor = 12; + } } - } - this.pawn.filth.Notify_EnteredNewCell(); - if (this.pawn.BodySize > 0.9f) - { - this.pawn.Map.snowGrid.AddDepth(this.pawn.Position, -0.001f); - } - Building_Door building_Door3 = this.pawn.Map.thingGrid.ThingAt(this.lastCell); - if (building_Door3 != null && !building_Door3.BlockedOpenMomentary && !this.pawn.HostileTo(building_Door3)) - { - building_Door3.FriendlyTouched(); - if (!building_Door3.HoldOpen && building_Door3.SlowsPawns) + this.pawn.filth.Notify_EnteredNewCell(); + if (this.pawn.BodySize > 0.89999997615814209) + { + this.pawn.Map.snowGrid.AddDepth(this.pawn.Position, -0.001f); + } + Building_Door building_Door3 = this.pawn.Map.thingGrid.ThingAt(this.lastCell); + if (building_Door3 != null && !building_Door3.BlockedOpenMomentary && !this.pawn.HostileTo(building_Door3)) { - building_Door3.StartManualCloseBy(this.pawn); + building_Door3.FriendlyTouched(); + if (!building_Door3.HoldOpen && building_Door3.SlowsPawns) + { + building_Door3.StartManualCloseBy(this.pawn); + return; + } + } + if (this.NeedNewPath() && !this.TrySetNewPath()) return; + if (this.AtDestinationPosition()) + { + this.PatherArrived(); } - } - if (this.NeedNewPath() && !this.TrySetNewPath()) - { - return; - } - if (this.AtDestinationPosition()) - { - this.PatherArrived(); - } - else - { - if (this.curPath.NodesLeftCount == 0) + else if (this.curPath.NodesLeftCount == 0) { Log.Error(this.pawn + " ran out of path nodes. Force-arriving."); this.PatherArrived(); - return; } - this.SetupMoveIntoNextCell(); + else + { + this.SetupMoveIntoNextCell(); + } } + return; + IL_005b: + Job job = new Job(JobDefOf.AttackMelee, (Thing)building); + job.expiryInterval = 300; + this.pawn.jobs.StartJob(job, JobCondition.Incompletable, null, false, true, null, default(JobTag?)); } private void SetupMoveIntoNextCell() { if (this.curPath.NodesLeftCount <= 1) { - Log.Error(string.Concat(new object[] - { - this.pawn, - " at ", - this.pawn.Position, - " ran out of path nodes while pathing to ", - this.destination, - "." - })); + Log.Error(this.pawn + " at " + this.pawn.Position + " ran out of path nodes while pathing to " + this.destination + "."); this.PatherFailed(); - return; } - this.nextCell = this.curPath.ConsumeNextNode(); - if (!this.nextCell.Walkable(this.pawn.Map)) + else { - Log.Error(string.Concat(new object[] + this.nextCell = this.curPath.ConsumeNextNode(); + if (!this.nextCell.Walkable(this.pawn.Map)) { - this.pawn, - " entering ", - this.nextCell, - " which is unwalkable." - })); - } - Building_Door building_Door = this.pawn.Map.thingGrid.ThingAt(this.nextCell); - if (building_Door != null) - { - building_Door.Notify_PawnApproaching(this.pawn); + Log.Error(this.pawn + " entering " + this.nextCell + " which is unwalkable."); + } + Building_Door building_Door = this.pawn.Map.thingGrid.ThingAt(this.nextCell); + if (building_Door != null) + { + building_Door.Notify_PawnApproaching(this.pawn); + } + int num = this.CostToMoveIntoCell(this.nextCell); + this.nextCellCostTotal = (float)num; + this.nextCellCostLeft = (float)num; } - int num = this.CostToMoveIntoCell(this.nextCell); - this.nextCellCostTotal = (float)num; - this.nextCellCostLeft = (float)num; } private int CostToMoveIntoCell(IntVec3 c) { + int x = c.x; + IntVec3 position = this.pawn.Position; int num; - if (c.x == this.pawn.Position.x || c.z == this.pawn.Position.z) - { - num = this.pawn.TicksPerMoveCardinal; - } - else + if (x != position.x) { + int z = c.z; + IntVec3 position2 = this.pawn.Position; + if (z == position2.z) + goto IL_003e; num = this.pawn.TicksPerMoveDiagonal; + goto IL_005b; } + goto IL_003e; + IL_003e: + num = this.pawn.TicksPerMoveCardinal; + goto IL_005b; + IL_005b: num += this.pawn.Map.pathGrid.CalculatedCostAt(c, false, this.pawn.Position); Building edifice = c.GetEdifice(this.pawn.Map); if (edifice != null) { - num += (int)edifice.PathWalkCostFor(this.pawn); + num += edifice.PathWalkCostFor(this.pawn); } if (num > 450) { @@ -497,26 +497,34 @@ private int CostToMoveIntoCell(IntVec3 c) switch (this.pawn.jobs.curJob.locomotionUrgency) { case LocomotionUrgency.Amble: + { num *= 3; if (num < 60) { num = 60; } break; + } case LocomotionUrgency.Walk: + { num *= 2; if (num < 50) { num = 50; } break; + } case LocomotionUrgency.Jog: + { num *= 1; break; + } case LocomotionUrgency.Sprint: - num = Mathf.RoundToInt((float)num * 0.75f); + { + num = Mathf.RoundToInt((float)((float)num * 0.75)); break; } + } } return Mathf.Max(num, 1); } @@ -526,11 +534,11 @@ private float CostToPayThisTick() float num = 1f; if (this.pawn.stances.Staggered) { - num *= 0.17f; + num = (float)(num * 0.17000000178813934); } - if (num < this.nextCellCostTotal / 450f) + if (num < this.nextCellCostTotal / 450.0) { - num = this.nextCellCostTotal / 450f; + num = (float)(this.nextCellCostTotal / 450.0); } return num; } @@ -561,9 +569,7 @@ private bool TrySetNewPath() this.foundPathWithDanger = Find.TickManager.TicksGame; } if (this.foundPathWhichCollidesWithPawns == Find.TickManager.TicksGame && this.foundPathWithDanger == Find.TickManager.TicksGame) - { break; - } num++; } return true; @@ -582,82 +588,62 @@ private bool AtDestinationPosition() private bool NeedNewPath() { - if (this.curPath == null || !this.curPath.Found || this.curPath.NodesLeftCount == 0) - { - return true; - } - if (this.destination.HasThing && this.destination.Thing.Map != this.pawn.Map) - { - return true; - } - if (this.lastPathedTargetPosition != this.destination.Cell) - { - float num = (float)(this.pawn.Position - this.destination.Cell).LengthHorizontalSquared; - float num2; - if (num > 900f) - { - num2 = 10f; - } - else if (num > 289f) - { - num2 = 5f; - } - else if (num > 100f) - { - num2 = 3f; - } - else if (num > 49f) - { - num2 = 2f; - } - else - { - num2 = 0.5f; - } - if ((float)(this.lastPathedTargetPosition - this.destination.Cell).LengthHorizontalSquared > num2 * num2) - { - return true; - } - } - bool flag = PawnUtility.ShouldCollideWithPawns(this.pawn); - bool flag2 = this.curPath.NodesLeftCount < 30; - IntVec3 other = IntVec3.Invalid; - int num3 = 0; - while (num3 < 20 && num3 < this.curPath.NodesLeftCount) + if (((this.curPath != null) ? (this.curPath.Found ? this.curPath.NodesLeftCount : 0) : 0) != 0) { - IntVec3 intVec = this.curPath.Peek(num3); - if (!intVec.Walkable(this.pawn.Map)) + if (this.destination.HasThing && this.destination.Thing.Map != this.pawn.Map) { return true; } - if (flag && !this.BestPathHadPawnsInTheWayRecently() && (PawnUtility.AnyPawnBlockingPathAt(intVec, this.pawn, false, true) || (flag2 && PawnUtility.AnyPawnBlockingPathAt(intVec, this.pawn, false, false)))) + if (this.lastPathedTargetPosition != this.destination.Cell) { - return true; + float num = (float)(this.pawn.Position - this.destination.Cell).LengthHorizontalSquared; + float num2 = (float)((!(num > 900.0)) ? ((!(num > 289.0)) ? ((!(num > 100.0)) ? ((!(num > 49.0)) ? 0.5 : 2.0) : 3.0) : 5.0) : 10.0); + if ((float)(this.lastPathedTargetPosition - this.destination.Cell).LengthHorizontalSquared > num2 * num2) + { + return true; + } } - if (!this.BestPathHadDangerRecently() && PawnUtility.KnownDangerAt(intVec, this.pawn)) + bool flag = PawnUtility.ShouldCollideWithPawns(this.pawn); + bool flag2 = this.curPath.NodesLeftCount < 30; + IntVec3 other = IntVec3.Invalid; + int num3 = 0; + while (num3 < 20 && num3 < this.curPath.NodesLeftCount) { - return true; - } - Building_Door building_Door = intVec.GetEdifice(this.pawn.Map) as Building_Door; - if (building_Door != null) - { - if (!building_Door.CanPhysicallyPass(this.pawn) && !this.pawn.HostileTo(building_Door)) + IntVec3 intVec = this.curPath.Peek(num3); + if (!intVec.Walkable(this.pawn.Map)) { return true; } - if (building_Door.IsForbiddenToPass(this.pawn)) + if (flag && !this.BestPathHadPawnsInTheWayRecently() && (PawnUtility.AnyPawnBlockingPathAt(intVec, this.pawn, false, true) || (flag2 && PawnUtility.AnyPawnBlockingPathAt(intVec, this.pawn, false, false)))) { return true; } + if (!this.BestPathHadDangerRecently() && PawnUtility.KnownDangerAt(intVec, this.pawn)) + { + return true; + } + Building_Door building_Door = intVec.GetEdifice(this.pawn.Map) as Building_Door; + if (building_Door != null) + { + if (!building_Door.CanPhysicallyPass(this.pawn) && !this.pawn.HostileTo(building_Door)) + { + return true; + } + if (building_Door.IsForbiddenToPass(this.pawn)) + { + return true; + } + } + if (num3 != 0 && intVec.AdjacentToDiagonal(other) && (PathFinder.BlocksDiagonalMovement(intVec.x, other.z, this.pawn.Map) || PathFinder.BlocksDiagonalMovement(other.x, intVec.z, this.pawn.Map))) + { + return true; + } + other = intVec; + num3++; } - if (num3 != 0 && intVec.AdjacentToDiagonal(other) && (PathFinder.BlocksDiagonalMovement(intVec.x, other.z, this.pawn.Map) || PathFinder.BlocksDiagonalMovement(other.x, intVec.z, this.pawn.Map))) - { - return true; - } - other = intVec; - num3++; + return false; } - return false; + return true; } private bool BestPathHadPawnsInTheWayRecently() diff --git a/Assembly-CSharp/Verse.AI/Pawn_Thinker.cs b/Assembly-CSharp/Verse.AI/Pawn_Thinker.cs index 13293fb11..5b438018f 100644 --- a/Assembly-CSharp/Verse.AI/Pawn_Thinker.cs +++ b/Assembly-CSharp/Verse.AI/Pawn_Thinker.cs @@ -1,5 +1,3 @@ -using System; - namespace Verse.AI { public class Pawn_Thinker @@ -45,31 +43,25 @@ public Pawn_Thinker(Pawn pawn) public T TryGetMainTreeThinkNode() where T : ThinkNode { - foreach (ThinkNode current in this.MainThinkNodeRoot.ChildrenRecursive) + foreach (ThinkNode item in this.MainThinkNodeRoot.ChildrenRecursive) { - T t = current as T; - if (t != null) + T val = (T)(item as T); + if (val != null) { - return t; + return val; } } - return (T)((object)null); + return (T)null; } public T GetMainTreeThinkNode() where T : ThinkNode { - T t = this.TryGetMainTreeThinkNode(); - if (t == null) + T val = this.TryGetMainTreeThinkNode(); + if (val == null) { - Log.Warning(string.Concat(new object[] - { - this.pawn, - " looked for ThinkNode of type ", - typeof(T), - " and didn't find it." - })); + Log.Warning(this.pawn + " looked for ThinkNode of type " + typeof(T) + " and didn't find it."); } - return t; + return val; } } } diff --git a/Assembly-CSharp/Verse.AI/QueuedJob.cs b/Assembly-CSharp/Verse.AI/QueuedJob.cs index 50adb88a3..b113f9927 100644 --- a/Assembly-CSharp/Verse.AI/QueuedJob.cs +++ b/Assembly-CSharp/Verse.AI/QueuedJob.cs @@ -1,5 +1,3 @@ -using System; - namespace Verse.AI { public class QueuedJob : IExposable @@ -21,7 +19,7 @@ public QueuedJob(Job job, JobTag? tag) public void ExposeData() { Scribe_Deep.Look(ref this.job, "job", new object[0]); - Scribe_Values.Look(ref this.tag, "tag", null, false); + Scribe_Values.Look(ref this.tag, "tag", default(JobTag?), false); } } } diff --git a/Assembly-CSharp/Verse.AI/RegionCostCalculator.cs b/Assembly-CSharp/Verse.AI/RegionCostCalculator.cs index 39bab1478..a45e5bf6b 100644 --- a/Assembly-CSharp/Verse.AI/RegionCostCalculator.cs +++ b/Assembly-CSharp/Verse.AI/RegionCostCalculator.cs @@ -57,9 +57,9 @@ public RegionLinkQueueEntry(Region from, RegionLink link, int cost, int estimate } } - private class DistanceComparer : IComparer + private class DistanceComparer : IComparer { - public int Compare(RegionCostCalculator.RegionLinkQueueEntry a, RegionCostCalculator.RegionLinkQueueEntry b) + public int Compare(RegionLinkQueueEntry a, RegionLinkQueueEntry b) { return a.EstimatedPathCost.CompareTo(b.EstimatedPathCost); } @@ -89,7 +89,7 @@ public int Compare(RegionCostCalculator.RegionLinkQueueEntry a, RegionCostCalcul private Dictionary distances = new Dictionary(); - private FastPriorityQueue queue = new FastPriorityQueue(new RegionCostCalculator.DistanceComparer()); + private FastPriorityQueue queue = new FastPriorityQueue(new DistanceComparer()); private Dictionary minPathCosts = new Dictionary(); @@ -125,49 +125,58 @@ public void Init(CellRect destination, HashSet destRegions, TraverseParm this.linkTargetCells.Clear(); this.queue.Clear(); this.minPathCosts.Clear(); - foreach (Region current in destRegions) + HashSet.Enumerator enumerator = destRegions.GetEnumerator(); + try { - int minPathCost = this.RegionMedianPathCost(current); - for (int i = 0; i < current.links.Count; i++) + while (enumerator.MoveNext()) { - RegionLink regionLink = current.links[i]; - if (regionLink.GetOtherRegion(current).type.Passable()) + Region current = enumerator.Current; + int minPathCost = this.RegionMedianPathCost(current); + for (int i = 0; i < current.links.Count; i++) { - int num = this.RegionLinkDistance(this.destinationCell, regionLink, minPathCost); - int num2; - if (this.distances.TryGetValue(regionLink, out num2)) + RegionLink regionLink = current.links[i]; + if (regionLink.GetOtherRegion(current).type.Passable()) { - if (num < num2) + int num = this.RegionLinkDistance(this.destinationCell, regionLink, minPathCost); + int num2 = default(int); + if (this.distances.TryGetValue(regionLink, out num2)) + { + if (num < num2) + { + this.linkTargetCells[regionLink] = this.GetLinkTargetCell(this.destinationCell, regionLink); + } + num = Math.Min(num2, num); + } + else { this.linkTargetCells[regionLink] = this.GetLinkTargetCell(this.destinationCell, regionLink); } - num = Math.Min(num2, num); + this.distances[regionLink] = num; + } + } + this.GetPreciseRegionLinkDistances(current, destination, this.preciseRegionLinkDistances); + for (int j = 0; j < this.preciseRegionLinkDistances.Count; j++) + { + Pair pair = this.preciseRegionLinkDistances[j]; + RegionLink first = pair.First; + int num3 = this.distances[first]; + int num4; + if (pair.Second > num3) + { + this.distances[first] = pair.Second; + num4 = pair.Second; } else { - this.linkTargetCells[regionLink] = this.GetLinkTargetCell(this.destinationCell, regionLink); + num4 = num3; } - this.distances[regionLink] = num; + this.queue.Push(new RegionLinkQueueEntry(current, first, num4, num4)); } } - this.GetPreciseRegionLinkDistances(current, destination, this.preciseRegionLinkDistances); - for (int j = 0; j < this.preciseRegionLinkDistances.Count; j++) - { - Pair pair = this.preciseRegionLinkDistances[j]; - RegionLink first = pair.First; - int num3 = this.distances[first]; - int num4; - if (pair.Second > num3) - { - this.distances[first] = pair.Second; - num4 = pair.Second; - } - else - { - num4 = num3; - } - this.queue.Push(new RegionCostCalculator.RegionLinkQueueEntry(current, first, num4, num4)); - } + } + finally + { + ((IDisposable)(object)enumerator).Dispose(); } } @@ -179,60 +188,66 @@ public int GetRegionDistance(Region region, out RegionLink minLink) } while (this.queue.Count != 0) { - RegionCostCalculator.RegionLinkQueueEntry regionLinkQueueEntry = this.queue.Pop(); + RegionLinkQueueEntry regionLinkQueueEntry = this.queue.Pop(); int num = this.distances[regionLinkQueueEntry.Link]; + Region otherRegion; + int num2; if (regionLinkQueueEntry.Cost == num) { - Region otherRegion = regionLinkQueueEntry.Link.GetOtherRegion(regionLinkQueueEntry.From); + otherRegion = regionLinkQueueEntry.Link.GetOtherRegion(regionLinkQueueEntry.From); if (otherRegion != null && otherRegion.valid) { - int num2 = 0; + num2 = 0; if (otherRegion.portal != null) { num2 = PathFinder.GetBuildingCost(otherRegion.portal, this.traverseParms, this.traverseParms.pawn); - if (num2 == 2147483647) + if (num2 != 2147483647) { - continue; + num2 += this.OctileDistance(1, 0); + goto IL_00ca; } - num2 += this.OctileDistance(1, 0); + continue; } - int minPathCost = this.RegionMedianPathCost(otherRegion); - for (int i = 0; i < otherRegion.links.Count; i++) + goto IL_00ca; + } + } + continue; + IL_00ca: + int minPathCost = this.RegionMedianPathCost(otherRegion); + for (int i = 0; i < otherRegion.links.Count; i++) + { + RegionLink regionLink = otherRegion.links[i]; + if (regionLink != regionLinkQueueEntry.Link && regionLink.GetOtherRegion(otherRegion).type.Passable()) + { + int val = (otherRegion.portal == null) ? this.RegionLinkDistance(regionLinkQueueEntry.Link, regionLink, minPathCost) : num2; + val = Math.Max(val, 1); + int num3 = num + val; + int estimatedPathCost = this.MinimumRegionLinkDistance(this.destinationCell, regionLink) + num3; + int num4 = default(int); + if (this.distances.TryGetValue(regionLink, out num4)) { - RegionLink regionLink = otherRegion.links[i]; - if (regionLink != regionLinkQueueEntry.Link && regionLink.GetOtherRegion(otherRegion).type.Passable()) + if (num3 < num4) { - int num3 = (otherRegion.portal == null) ? this.RegionLinkDistance(regionLinkQueueEntry.Link, regionLink, minPathCost) : num2; - num3 = Math.Max(num3, 1); - int num4 = num + num3; - int estimatedPathCost = this.MinimumRegionLinkDistance(this.destinationCell, regionLink) + num4; - int num5; - if (this.distances.TryGetValue(regionLink, out num5)) - { - if (num4 < num5) - { - this.distances[regionLink] = num4; - this.queue.Push(new RegionCostCalculator.RegionLinkQueueEntry(otherRegion, regionLink, num4, estimatedPathCost)); - } - } - else - { - this.distances.Add(regionLink, num4); - this.queue.Push(new RegionCostCalculator.RegionLinkQueueEntry(otherRegion, regionLink, num4, estimatedPathCost)); - } + this.distances[regionLink] = num3; + this.queue.Push(new RegionLinkQueueEntry(otherRegion, regionLink, num3, estimatedPathCost)); } } - if (!this.regionMinLink.ContainsKey(otherRegion.id)) + else { - this.regionMinLink.Add(otherRegion.id, regionLinkQueueEntry.Link); - if (otherRegion == region) - { - minLink = regionLinkQueueEntry.Link; - return regionLinkQueueEntry.Cost; - } + this.distances.Add(regionLink, num3); + this.queue.Push(new RegionLinkQueueEntry(otherRegion, regionLink, num3, estimatedPathCost)); } } } + if (!this.regionMinLink.ContainsKey(otherRegion.id)) + { + this.regionMinLink.Add(otherRegion.id, regionLinkQueueEntry.Link); + if (otherRegion == region) + { + minLink = regionLinkQueueEntry.Link; + return regionLinkQueueEntry.Cost; + } + } } return 10000; } @@ -245,14 +260,11 @@ public int GetRegionBestDistances(Region region, out RegionLink bestLink, out Re for (int i = 0; i < region.links.Count; i++) { RegionLink regionLink = region.links[i]; - if (regionLink != bestLink && regionLink.GetOtherRegion(region).type.Passable()) + int num = default(int); + if (regionLink != bestLink && regionLink.GetOtherRegion(region).type.Passable() && this.distances.TryGetValue(regionLink, out num) && num < secondBestCost) { - int num; - if (this.distances.TryGetValue(regionLink, out num) && num < secondBestCost) - { - secondBestCost = num; - secondBestLink = regionLink; - } + secondBestCost = num; + secondBestLink = regionLink; } } return regionDistance; @@ -260,7 +272,7 @@ public int GetRegionBestDistances(Region region, out RegionLink bestLink, out Re public int RegionMedianPathCost(Region region) { - int result; + int result = default(int); if (this.minPathCosts.TryGetValue(region, out result)) { return result; @@ -274,7 +286,7 @@ public int RegionMedianPathCost(Region region) RegionCostCalculator.pathCostSamples[i] = this.GetCellCostFast(cellIndices.CellToIndex(region.RandomCell), ignoreAllowedAreaCost); } Rand.PopState(); - Array.Sort(RegionCostCalculator.pathCostSamples); + Array.Sort(RegionCostCalculator.pathCostSamples); int num = RegionCostCalculator.pathCostSamples[4]; this.minPathCosts[region] = num; return num; @@ -285,7 +297,7 @@ private int GetCellCostFast(int index, bool ignoreAllowedAreaCost = false) int num = this.map.pathGrid.pathGrid[index]; if (this.avoidGrid != null) { - num += (int)(this.avoidGrid[index] * 8); + num += this.avoidGrid[index] * 8; } if (this.allowedArea != null && !ignoreAllowedAreaCost && !this.allowedArea[index]) { @@ -315,12 +327,12 @@ public int RegionLinkDistance(IntVec3 cell, RegionLink link, int minPathCost) private static int SpanCenterX(EdgeSpan e) { - return e.root.x + ((e.dir != SpanDirection.East) ? 0 : (e.length / 2)); + return e.root.x + ((e.dir == SpanDirection.East) ? (e.length / 2) : 0); } private static int SpanCenterZ(EdgeSpan e) { - return e.root.z + ((e.dir != SpanDirection.North) ? 0 : (e.length / 2)); + return e.root.z + ((e.dir == SpanDirection.North) ? (e.length / 2) : 0); } private static IntVec3 RegionLinkCenter(RegionLink link) @@ -358,8 +370,7 @@ private static IntVec3 LinkClosestCell(IntVec3 cell, RegionLink link) num = span.length - 1; } IntVec3 root = span.root; - IntVec3 result = new IntVec3(Mathf.Clamp(cell.x, root.x, root.x + num), 0, Mathf.Clamp(cell.z, root.z, root.z + num2)); - return result; + return new IntVec3(Mathf.Clamp(cell.x, root.x, root.x + num), 0, Mathf.Clamp(cell.z, root.z, root.z + num2)); } private void GetPreciseRegionLinkDistances(Region region, CellRect destination, List> outDistances) @@ -383,13 +394,13 @@ private void GetPreciseRegionLinkDistances(Region region, CellRect destination, iterator.MoveNext(); } } - Dijkstra.Run(RegionCostCalculator.tmpCellIndices, (int x) => this.PreciseRegionLinkDistancesNeighborsGetter(x, region), this.preciseRegionLinkDistancesDistanceGetter, ref RegionCostCalculator.tmpDistances); + Dijkstra.Run((IEnumerable)RegionCostCalculator.tmpCellIndices, (Func>)((int x) => this.PreciseRegionLinkDistancesNeighborsGetter(x, region)), this.preciseRegionLinkDistancesDistanceGetter, ref RegionCostCalculator.tmpDistances); for (int i = 0; i < region.links.Count; i++) { RegionLink regionLink = region.links[i]; if (regionLink.GetOtherRegion(region).type.Passable()) { - float num; + float num = default(float); if (!RegionCostCalculator.tmpDistances.TryGetValue(this.map.cellIndices.CellToIndex(this.linkTargetCells[regionLink]), out num)) { Log.ErrorOnce("Dijkstra couldn't reach one of the cells even though they are in the same region. There is most likely something wrong with the neighbor nodes getter.", 1938471531); @@ -402,11 +413,11 @@ private void GetPreciseRegionLinkDistances(Region region, CellRect destination, private IEnumerable PreciseRegionLinkDistancesNeighborsGetter(int node, Region region) { - if (this.regionGrid[node] == null || this.regionGrid[node] != region) + if (this.regionGrid[node] != null && this.regionGrid[node] == region) { - return null; + return this.PathableNeighborIndices(node); } - return this.PathableNeighborIndices(node); + return null; } private float PreciseRegionLinkDistancesDistanceGetter(int a, int b) @@ -416,7 +427,8 @@ private float PreciseRegionLinkDistancesDistanceGetter(int a, int b) private bool AreCellsDiagonal(int a, int b) { - int x = this.map.Size.x; + IntVec3 size = this.map.Size; + int x = size.x; return a % x != b % x && a / x != b / x; } @@ -424,11 +436,14 @@ private List PathableNeighborIndices(int index) { RegionCostCalculator.tmpPathableNeighborIndices.Clear(); PathGrid pathGrid = this.map.pathGrid; - int x = this.map.Size.x; + IntVec3 size = this.map.Size; + int x = size.x; bool flag = index % x > 0; bool flag2 = index % x < x - 1; bool flag3 = index >= x; - bool flag4 = index / x < this.map.Size.z - 1; + int num = index / x; + IntVec3 size2 = this.map.Size; + bool flag4 = num < size2.z - 1; if (flag3 && pathGrid.WalkableFast(index - x)) { RegionCostCalculator.tmpPathableNeighborIndices.Add(index - x); diff --git a/Assembly-CSharp/Verse.AI/RegionCostCalculatorWrapper.cs b/Assembly-CSharp/Verse.AI/RegionCostCalculatorWrapper.cs index 2ae6d7050..cbd50f0fd 100644 --- a/Assembly-CSharp/Verse.AI/RegionCostCalculatorWrapper.cs +++ b/Assembly-CSharp/Verse.AI/RegionCostCalculatorWrapper.cs @@ -1,4 +1,3 @@ -using System; using System.Collections.Generic; using UnityEngine; @@ -105,17 +104,17 @@ public int GetPathCostFromDestToRegion(int cellIndex) { return this.OctileDistanceToEnd(cell); } - if (this.cachedBestLink == null) + if (this.cachedBestLink != null) { - return 10000; - } - int num = this.regionCostCalculator.RegionLinkDistance(cell, this.cachedBestLink, this.cachedRegionCellPathCost); - if (this.cachedSecondBestLink != null) - { - int num2 = this.regionCostCalculator.RegionLinkDistance(cell, this.cachedSecondBestLink, this.cachedRegionCellPathCost); - return Mathf.Min(this.cachedSecondBestLinkCost + num2, this.cachedBestLinkCost + num); + int num = this.regionCostCalculator.RegionLinkDistance(cell, this.cachedBestLink, this.cachedRegionCellPathCost); + if (this.cachedSecondBestLink != null) + { + int num2 = this.regionCostCalculator.RegionLinkDistance(cell, this.cachedSecondBestLink, this.cachedRegionCellPathCost); + return Mathf.Min(this.cachedSecondBestLinkCost + num2, this.cachedBestLinkCost + num); + } + return this.cachedBestLinkCost + num; } - return this.cachedBestLinkCost + num; + return 10000; } private int OctileDistanceToEnd(IntVec3 cell) diff --git a/Assembly-CSharp/Verse.AI/Reservation.cs b/Assembly-CSharp/Verse.AI/Reservation.cs index 99bf9b2dd..59ca2f407 100644 --- a/Assembly-CSharp/Verse.AI/Reservation.cs +++ b/Assembly-CSharp/Verse.AI/Reservation.cs @@ -1,5 +1,4 @@ using RimWorld; -using System; namespace Verse.AI { @@ -87,18 +86,7 @@ public void ExposeData() public override string ToString() { - return string.Concat(new object[] - { - (this.claimant == null) ? "null" : this.claimant.LabelShort, - ", ", - this.target.ToString(), - ", ", - this.layer.ToString(), - ", ", - this.maxPawns, - ", ", - this.stackCount - }); + return ((this.claimant == null) ? "null" : this.claimant.LabelShort) + ", " + this.target.ToString() + ", " + this.layer.ToString() + ", " + this.maxPawns + ", " + this.stackCount; } } } diff --git a/Assembly-CSharp/Verse.AI/ReservationManager.cs b/Assembly-CSharp/Verse.AI/ReservationManager.cs index 396e832af..bac7b4c34 100644 --- a/Assembly-CSharp/Verse.AI/ReservationManager.cs +++ b/Assembly-CSharp/Verse.AI/ReservationManager.cs @@ -28,9 +28,9 @@ public void ExposeData() Scribe_Collections.Look(ref this.reservations, "reservations", LookMode.Deep, new object[0]); if (Scribe.mode == LoadSaveMode.PostLoadInit) { - for (int i = this.reservations.Count - 1; i >= 0; i--) + for (int num = this.reservations.Count - 1; num >= 0; num--) { - Reservation reservation = this.reservations[i]; + Reservation reservation = this.reservations[num]; if (reservation.Target.Thing != null && reservation.Target.Thing.Destroyed) { Log.Error("Loaded reservation with destroyed target: " + reservation + ". Deleting it..."); @@ -57,73 +57,61 @@ public bool CanReserve(Pawn claimant, LocalTargetInfo target, int maxPawns = 1, Log.Error("CanReserve with claimant==null"); return false; } - if (!claimant.Spawned || claimant.Map != this.map) - { - return false; - } - if (target.HasThing && target.Thing.Spawned && target.Thing.Map != this.map) - { - return false; - } - int num = 1; - if (target.HasThing) + if (claimant.Spawned && claimant.Map == this.map) { - num = target.Thing.stackCount; - } - if (stackCount == -1) - { - stackCount = num; - } - if (stackCount > num) - { - return false; - } - if (ignoreOtherReservations) - { - return true; - } - if (this.map.physicalInteractionReservationManager.IsReserved(target) && !this.map.physicalInteractionReservationManager.IsReservedBy(claimant, target)) - { - return false; - } - int num2 = 0; - int count = this.reservations.Count; - int num3 = 0; - for (int i = 0; i < count; i++) - { - Reservation reservation = this.reservations[i]; - if (!(reservation.Target != target)) + if (target.HasThing && target.Thing.Spawned && target.Thing.Map != this.map) + { + return false; + } + int num = 1; + if (target.HasThing) + { + num = target.Thing.stackCount; + } + if (stackCount == -1) + { + stackCount = num; + } + if (stackCount > num) { - if (reservation.Layer == layer) + return false; + } + if (ignoreOtherReservations) + { + return true; + } + if (this.map.physicalInteractionReservationManager.IsReserved(target) && !this.map.physicalInteractionReservationManager.IsReservedBy(claimant, target)) + { + return false; + } + int num2 = 0; + int count = this.reservations.Count; + int num3 = 0; + for (int i = 0; i < count; i++) + { + Reservation reservation = this.reservations[i]; + if (!(reservation.Target != target) && reservation.Layer == layer && ReservationManager.RespectsReservationsOf(claimant, reservation.Claimant)) { - if (ReservationManager.RespectsReservationsOf(claimant, reservation.Claimant)) + if (reservation.Claimant == claimant) { - if (reservation.Claimant == claimant) - { - return true; - } - if (reservation.MaxPawns != maxPawns) - { - return false; - } - num2++; - if (reservation.StackCount == -1) - { - num3 = num; - } - else - { - num3 += reservation.StackCount; - } - if (num2 >= maxPawns || num3 + stackCount > num) - { - return false; - } + return true; + } + if (reservation.MaxPawns != maxPawns) + { + return false; + } + num2++; + num3 = ((reservation.StackCount != -1) ? (num3 + reservation.StackCount) : num); + if (num2 < maxPawns && num3 + stackCount <= num) + { + continue; } + return false; } } + return true; } - return true; + return false; } public bool Reserve(Pawn claimant, LocalTargetInfo target, int maxPawns = 1, int stackCount = -1, ReservationLayerDef layer = null) @@ -138,50 +126,44 @@ public bool Reserve(Pawn claimant, LocalTargetInfo target, int maxPawns = 1, int } if (target.ThingDestroyed) { - Log.Warning(string.Concat(new object[] - { - claimant, - " tried to reserve destroyed thing ", - target, - " for maxPawns ", - maxPawns, - " doing job ", - (claimant.CurJob == null) ? "null" : claimant.CurJob.ToString() - })); + Log.Warning(claimant + " tried to reserve destroyed thing " + target + " for maxPawns " + maxPawns + " doing job " + ((claimant.CurJob == null) ? "null" : claimant.CurJob.ToString())); return false; } - if (this.CanReserve(claimant, target, maxPawns, stackCount, layer, false)) - { - this.reservations.Add(new Reservation(claimant, maxPawns, stackCount, target, layer)); - return true; - } - if (claimant.CurJob != null && claimant.CurJob.playerForced && this.CanReserve(claimant, target, maxPawns, stackCount, layer, true)) + if (!this.CanReserve(claimant, target, maxPawns, stackCount, layer, false)) { - this.reservations.Add(new Reservation(claimant, maxPawns, stackCount, target, layer)); - foreach (Reservation current in new List(this.reservations)) + if (claimant.CurJob != null && claimant.CurJob.playerForced && this.CanReserve(claimant, target, maxPawns, stackCount, layer, true)) { - if (current.Target == target && current.Claimant != claimant && current.Layer == layer && ReservationManager.RespectsReservationsOf(claimant, current.Claimant)) + this.reservations.Add(new Reservation(claimant, maxPawns, stackCount, target, layer)); + List.Enumerator enumerator = new List(this.reservations).GetEnumerator(); + try + { + while (enumerator.MoveNext()) + { + Reservation current = enumerator.Current; + if (current.Target == target && current.Claimant != claimant && current.Layer == layer && ReservationManager.RespectsReservationsOf(claimant, current.Claimant)) + { + current.Claimant.jobs.EndCurrentJob(JobCondition.InterruptForced, true); + } + } + } + finally { - current.Claimant.jobs.EndCurrentJob(JobCondition.InterruptForced, true); + ((IDisposable)(object)enumerator).Dispose(); } + return true; } - return true; + this.LogCouldNotReserveError(claimant, target, maxPawns, stackCount, layer); + return false; } - this.LogCouldNotReserveError(claimant, target, maxPawns, stackCount, layer); - return false; + this.reservations.Add(new Reservation(claimant, maxPawns, stackCount, target, layer)); + return true; } public void Release(LocalTargetInfo target, Pawn claimant) { if (target.ThingDestroyed) { - Log.Warning(string.Concat(new object[] - { - "Releasing destroyed thing ", - target, - " for ", - claimant - })); + Log.Warning("Releasing destroyed thing " + target + " for " + claimant); } Reservation reservation = null; for (int i = 0; i < this.reservations.Count; i++) @@ -195,35 +177,29 @@ public void Release(LocalTargetInfo target, Pawn claimant) } if (reservation == null && !target.ThingDestroyed) { - Log.Error(string.Concat(new object[] - { - "Tried to release ", - target, - " that wasn't reserved by ", - claimant, - "." - })); - return; + Log.Error("Tried to release " + target + " that wasn't reserved by " + claimant + "."); + } + else + { + this.reservations.Remove(reservation); } - this.reservations.Remove(reservation); } public void ReleaseAllForTarget(Thing t) { - if (t == null) + if (t != null) { - return; + this.reservations.RemoveAll((Predicate)((Reservation r) => r.Target.Thing == t)); } - this.reservations.RemoveAll((Reservation r) => r.Target.Thing == t); } public void ReleaseAllClaimedBy(Pawn claimant) { - for (int i = this.reservations.Count - 1; i >= 0; i--) + for (int num = this.reservations.Count - 1; num >= 0; num--) { - if (this.reservations[i].Claimant == claimant) + if (this.reservations[num].Claimant == claimant) { - this.reservations.RemoveAt(i); + this.reservations.RemoveAt(num); } } } @@ -231,9 +207,9 @@ public void ReleaseAllClaimedBy(Pawn claimant) public bool IsReserved(LocalTargetInfo target, Faction faction) { int count = this.reservations.Count; - for (int i = 0; i < count; i++) + for (int num = 0; num < count; num++) { - Reservation reservation = this.reservations[i]; + Reservation reservation = this.reservations[num]; if (reservation.Target == target && reservation.Claimant.Faction == faction) { return true; @@ -250,9 +226,9 @@ public bool IsReservedByAnyoneWhoseReservationsRespects(LocalTargetInfo target, public Pawn FirstReserverWhoseReservationsRespects(LocalTargetInfo target, Pawn claimant) { int count = this.reservations.Count; - for (int i = 0; i < count; i++) + for (int num = 0; num < count; num++) { - Reservation reservation = this.reservations[i]; + Reservation reservation = this.reservations[num]; if (reservation.Target == target && ReservationManager.RespectsReservationsOf(claimant, reservation.Claimant)) { return reservation.Claimant; @@ -264,9 +240,9 @@ public Pawn FirstReserverWhoseReservationsRespects(LocalTargetInfo target, Pawn public bool ReservedBy(LocalTargetInfo target, Pawn claimant) { int count = this.reservations.Count; - for (int i = 0; i < count; i++) + for (int num = 0; num < count; num++) { - Reservation reservation = this.reservations[i]; + Reservation reservation = this.reservations[num]; if (reservation.Target == target && reservation.Claimant == claimant) { return true; @@ -287,32 +263,32 @@ private static bool RespectsReservationsOf(Pawn newClaimant, Pawn oldClaimant) { return true; } - if (newClaimant.Faction == null || oldClaimant.Faction == null) + if (newClaimant.Faction != null && oldClaimant.Faction != null) { - return false; - } - if (newClaimant.Faction == oldClaimant.Faction) - { - return true; - } - if (!newClaimant.Faction.HostileTo(oldClaimant.Faction)) - { - return true; - } - if (oldClaimant.HostFaction != null && oldClaimant.HostFaction == newClaimant.HostFaction) - { - return true; - } - if (newClaimant.HostFaction != null) - { - if (oldClaimant.HostFaction != null) + if (newClaimant.Faction == oldClaimant.Faction) { return true; } - if (newClaimant.HostFaction == oldClaimant.Faction) + if (!newClaimant.Faction.HostileTo(oldClaimant.Faction)) { return true; } + if (oldClaimant.HostFaction != null && oldClaimant.HostFaction == newClaimant.HostFaction) + { + return true; + } + if (newClaimant.HostFaction != null) + { + if (oldClaimant.HostFaction != null) + { + return true; + } + if (newClaimant.HostFaction == oldClaimant.Faction) + { + return true; + } + } + return false; } return false; } @@ -323,13 +299,7 @@ internal string DebugString() stringBuilder.AppendLine("All reservation in ReservationManager:"); for (int i = 0; i < this.reservations.Count; i++) { - stringBuilder.AppendLine(string.Concat(new object[] - { - "[", - i, - "] ", - this.reservations[i].ToString() - })); + stringBuilder.AppendLine("[" + i + "] " + this.reservations[i].ToString()); } return stringBuilder.ToString(); } @@ -344,7 +314,10 @@ internal void DebugDrawReservations() if (reservation.Target.Thing.Spawned) { Thing thing = reservation.Target.Thing; - Vector3 s = new Vector3((float)thing.RotatedSize.x, 1f, (float)thing.RotatedSize.z); + IntVec2 rotatedSize = thing.RotatedSize; + float x = (float)rotatedSize.x; + IntVec2 rotatedSize2 = thing.RotatedSize; + Vector3 s = new Vector3(x, 1f, (float)rotatedSize2.z); Matrix4x4 matrix = default(Matrix4x4); matrix.SetTRS(thing.DrawPos + Vector3.up * 0.1f, Quaternion.identity, s); Graphics.DrawMesh(MeshPool.plane10, matrix, ReservationManager.DebugReservedThingIcon, 0); @@ -391,30 +364,7 @@ private void LogCouldNotReserveError(Pawn claimant, LocalTargetInfo target, int } } } - Log.Error(string.Concat(new object[] - { - "Could not reserve ", - target, - "/", - layer, - " for ", - claimant, - " doing job ", - text, - "(curToil=", - num, - ") for maxPawns ", - maxPawns, - " and stackCount ", - stackCount, - ". Existing reserver: ", - pawn, - " doing job ", - text2, - "(curToil=", - num2, - ")" - })); + Log.Error("Could not reserve " + target + "/" + layer + " for " + claimant + " doing job " + text + "(curToil=" + num + ") for maxPawns " + maxPawns + " and stackCount " + stackCount + ". Existing reserver: " + pawn + " doing job " + text2 + "(curToil=" + num2 + ")"); } } } diff --git a/Assembly-CSharp/Verse.AI/ReservationUtility.cs b/Assembly-CSharp/Verse.AI/ReservationUtility.cs index 88ded6b19..e25b1f464 100644 --- a/Assembly-CSharp/Verse.AI/ReservationUtility.cs +++ b/Assembly-CSharp/Verse.AI/ReservationUtility.cs @@ -1,27 +1,41 @@ -using System; - namespace Verse.AI { public static class ReservationUtility { public static bool CanReserve(this Pawn p, LocalTargetInfo target, int maxPawns = 1, int stackCount = -1, ReservationLayerDef layer = null, bool ignoreOtherReservations = false) { - return p.Spawned && p.Map.reservationManager.CanReserve(p, target, maxPawns, stackCount, layer, ignoreOtherReservations); + if (!p.Spawned) + { + return false; + } + return p.Map.reservationManager.CanReserve(p, target, maxPawns, stackCount, layer, ignoreOtherReservations); } public static bool CanReserveAndReach(this Pawn p, LocalTargetInfo target, PathEndMode peMode, Danger maxDanger, int maxPawns = 1, int stackCount = -1, ReservationLayerDef layer = null, bool ignoreOtherReservations = false) { - return p.Spawned && p.CanReach(target, peMode, maxDanger, false, TraverseMode.ByPawn) && p.Map.reservationManager.CanReserve(p, target, maxPawns, stackCount, layer, ignoreOtherReservations); + if (!p.Spawned) + { + return false; + } + return p.CanReach(target, peMode, maxDanger, false, TraverseMode.ByPawn) && p.Map.reservationManager.CanReserve(p, target, maxPawns, stackCount, layer, ignoreOtherReservations); } public static bool Reserve(this Pawn p, LocalTargetInfo target, int maxPawns = 1, int stackCount = -1, ReservationLayerDef layer = null) { - return p.Spawned && p.Map.reservationManager.Reserve(p, target, maxPawns, stackCount, layer); + if (!p.Spawned) + { + return false; + } + return p.Map.reservationManager.Reserve(p, target, maxPawns, stackCount, layer); } public static bool HasReserved(this Pawn p, LocalTargetInfo target) { - return p.Spawned && p.Map.reservationManager.ReservedBy(target, p); + if (!p.Spawned) + { + return false; + } + return p.Map.reservationManager.ReservedBy(target, p); } } } diff --git a/Assembly-CSharp/Verse.AI/TargetIndex.cs b/Assembly-CSharp/Verse.AI/TargetIndex.cs index 3b82e3298..01bd62e66 100644 --- a/Assembly-CSharp/Verse.AI/TargetIndex.cs +++ b/Assembly-CSharp/Verse.AI/TargetIndex.cs @@ -1,12 +1,10 @@ -using System; - namespace Verse.AI { public enum TargetIndex : byte { - None, - A, - B, - C + None = 0, + A = 1, + B = 2, + C = 3 } } diff --git a/Assembly-CSharp/Verse.AI/ThinkNode.cs b/Assembly-CSharp/Verse.AI/ThinkNode.cs index fb0564841..b1a026820 100644 --- a/Assembly-CSharp/Verse.AI/ThinkNode.cs +++ b/Assembly-CSharp/Verse.AI/ThinkNode.cs @@ -33,11 +33,11 @@ public IEnumerable ThisAndChildrenRecursive { get { - ThinkNode.<>c__Iterator55 <>c__Iterator = new ThinkNode.<>c__Iterator55(); - <>c__Iterator.<>f__this = this; - ThinkNode.<>c__Iterator55 expr_0E = <>c__Iterator; - expr_0E.$PC = -2; - return expr_0E; + yield return this; + foreach (ThinkNode item in this.ChildrenRecursive) + { + yield return item; + } } } @@ -45,17 +45,19 @@ public IEnumerable ChildrenRecursive { get { - ThinkNode.<>c__Iterator56 <>c__Iterator = new ThinkNode.<>c__Iterator56(); - <>c__Iterator.<>f__this = this; - ThinkNode.<>c__Iterator56 expr_0E = <>c__Iterator; - expr_0E.$PC = -2; - return expr_0E; + for (int i = 0; i < this.subNodes.Count; i++) + { + foreach (ThinkNode item in this.subNodes[i].ThisAndChildrenRecursive) + { + yield return item; + } + } } } public virtual float GetPriority(Pawn pawn) { - if (this.priority < 0f) + if (this.priority < 0.0) { Log.ErrorOnce("ThinkNode_PrioritySorter has child node which didn't give a priority: " + this, this.GetHashCode()); return 0f; @@ -71,14 +73,13 @@ protected virtual void ResolveSubnodes() public void ResolveSubnodesAndRecur() { - if (this.uniqueSaveKeyInt != -2) + if (this.uniqueSaveKeyInt == -2) { - return; - } - this.ResolveSubnodes(); - for (int i = 0; i < this.subNodes.Count; i++) - { - this.subNodes[i].ResolveSubnodesAndRecur(); + this.ResolveSubnodes(); + for (int i = 0; i < this.subNodes.Count; i++) + { + this.subNodes[i].ResolveSubnodesAndRecur(); + } } } diff --git a/Assembly-CSharp/Verse.AI/ThinkNodePriority.cs b/Assembly-CSharp/Verse.AI/ThinkNodePriority.cs index 86f2eb907..1446304a6 100644 --- a/Assembly-CSharp/Verse.AI/ThinkNodePriority.cs +++ b/Assembly-CSharp/Verse.AI/ThinkNodePriority.cs @@ -1,5 +1,3 @@ -using System; - namespace Verse.AI { public static class ThinkNodePriority diff --git a/Assembly-CSharp/Verse.AI/ThinkNode_ChancePerHour.cs b/Assembly-CSharp/Verse.AI/ThinkNode_ChancePerHour.cs index 08eb6c52d..67ba5ac92 100644 --- a/Assembly-CSharp/Verse.AI/ThinkNode_ChancePerHour.cs +++ b/Assembly-CSharp/Verse.AI/ThinkNode_ChancePerHour.cs @@ -1,5 +1,3 @@ -using System; - namespace Verse.AI { public abstract class ThinkNode_ChancePerHour : ThinkNode_Priority @@ -12,7 +10,7 @@ public override ThinkResult TryIssueJobPackage(Pawn pawn, JobIssueParams jobPara } this.SetLastTryTick(pawn, Find.TickManager.TicksGame); float num = this.MtbHours(pawn); - if (num <= 0f) + if (num <= 0.0) { return ThinkResult.NoJob; } @@ -32,7 +30,7 @@ public override ThinkResult TryIssueJobPackage(Pawn pawn, JobIssueParams jobPara private int GetLastTryTick(Pawn pawn) { - int result; + int result = default(int); if (pawn.mindState.thinkData.TryGetValue(base.UniqueSaveKey, out result)) { return result; diff --git a/Assembly-CSharp/Verse.AI/ThinkNode_ChancePerHour_Constant.cs b/Assembly-CSharp/Verse.AI/ThinkNode_ChancePerHour_Constant.cs index 658a017ff..9ebe98d2f 100644 --- a/Assembly-CSharp/Verse.AI/ThinkNode_ChancePerHour_Constant.cs +++ b/Assembly-CSharp/Verse.AI/ThinkNode_ChancePerHour_Constant.cs @@ -1,5 +1,3 @@ -using System; - namespace Verse.AI { public class ThinkNode_ChancePerHour_Constant : ThinkNode_ChancePerHour diff --git a/Assembly-CSharp/Verse.AI/ThinkNode_ChancePerHour_Lovin.cs b/Assembly-CSharp/Verse.AI/ThinkNode_ChancePerHour_Lovin.cs index 1c3b4d804..834402028 100644 --- a/Assembly-CSharp/Verse.AI/ThinkNode_ChancePerHour_Lovin.cs +++ b/Assembly-CSharp/Verse.AI/ThinkNode_ChancePerHour_Lovin.cs @@ -1,5 +1,4 @@ using RimWorld; -using System; namespace Verse.AI { diff --git a/Assembly-CSharp/Verse.AI/ThinkNode_ChancePerHour_Mate.cs b/Assembly-CSharp/Verse.AI/ThinkNode_ChancePerHour_Mate.cs index 940682fdd..f4758492f 100644 --- a/Assembly-CSharp/Verse.AI/ThinkNode_ChancePerHour_Mate.cs +++ b/Assembly-CSharp/Verse.AI/ThinkNode_ChancePerHour_Mate.cs @@ -1,5 +1,3 @@ -using System; - namespace Verse.AI { public class ThinkNode_ChancePerHour_Mate : ThinkNode_ChancePerHour diff --git a/Assembly-CSharp/Verse.AI/ThinkNode_ChancePerHour_Nuzzle.cs b/Assembly-CSharp/Verse.AI/ThinkNode_ChancePerHour_Nuzzle.cs index 7a1bf9790..f203757ee 100644 --- a/Assembly-CSharp/Verse.AI/ThinkNode_ChancePerHour_Nuzzle.cs +++ b/Assembly-CSharp/Verse.AI/ThinkNode_ChancePerHour_Nuzzle.cs @@ -1,5 +1,3 @@ -using System; - namespace Verse.AI { public class ThinkNode_ChancePerHour_Nuzzle : ThinkNode_ChancePerHour diff --git a/Assembly-CSharp/Verse.AI/ThinkNode_ConditionalHasFallbackLocation.cs b/Assembly-CSharp/Verse.AI/ThinkNode_ConditionalHasFallbackLocation.cs index b3619d0fc..dce3bfccb 100644 --- a/Assembly-CSharp/Verse.AI/ThinkNode_ConditionalHasFallbackLocation.cs +++ b/Assembly-CSharp/Verse.AI/ThinkNode_ConditionalHasFallbackLocation.cs @@ -1,16 +1,14 @@ -using System; - namespace Verse.AI { public class ThinkNode_ConditionalHasFallbackLocation : ThinkNode_Priority { public override ThinkResult TryIssueJobPackage(Pawn pawn, JobIssueParams jobParams) { - if (pawn.mindState.duty == null || !pawn.mindState.duty.focusSecond.IsValid) + if (pawn.mindState.duty != null && pawn.mindState.duty.focusSecond.IsValid) { - return ThinkResult.NoJob; + return base.TryIssueJobPackage(pawn, jobParams); } - return base.TryIssueJobPackage(pawn, jobParams); + return ThinkResult.NoJob; } } } diff --git a/Assembly-CSharp/Verse.AI/ThinkNode_ConditionalMentalState.cs b/Assembly-CSharp/Verse.AI/ThinkNode_ConditionalMentalState.cs index 02b878b35..a3ec7c832 100644 --- a/Assembly-CSharp/Verse.AI/ThinkNode_ConditionalMentalState.cs +++ b/Assembly-CSharp/Verse.AI/ThinkNode_ConditionalMentalState.cs @@ -1,5 +1,3 @@ -using System; - namespace Verse.AI { public class ThinkNode_ConditionalMentalState : ThinkNode_Priority diff --git a/Assembly-CSharp/Verse.AI/ThinkNode_ConditionalMentalStates.cs b/Assembly-CSharp/Verse.AI/ThinkNode_ConditionalMentalStates.cs index 54154c057..abf17d764 100644 --- a/Assembly-CSharp/Verse.AI/ThinkNode_ConditionalMentalStates.cs +++ b/Assembly-CSharp/Verse.AI/ThinkNode_ConditionalMentalStates.cs @@ -1,4 +1,3 @@ -using System; using System.Collections.Generic; namespace Verse.AI @@ -10,7 +9,7 @@ public class ThinkNode_ConditionalMentalStates : ThinkNode_Priority public override ThinkNode DeepCopy(bool resolve = true) { ThinkNode_ConditionalMentalStates thinkNode_ConditionalMentalStates = (ThinkNode_ConditionalMentalStates)base.DeepCopy(resolve); - thinkNode_ConditionalMentalStates.states = this.states.ListFullCopyOrNull(); + thinkNode_ConditionalMentalStates.states = this.states.ListFullCopyOrNull(); return thinkNode_ConditionalMentalStates; } diff --git a/Assembly-CSharp/Verse.AI/ThinkNode_ConditionalNoTarget.cs b/Assembly-CSharp/Verse.AI/ThinkNode_ConditionalNoTarget.cs index 0e057f6fa..8b7b6398f 100644 --- a/Assembly-CSharp/Verse.AI/ThinkNode_ConditionalNoTarget.cs +++ b/Assembly-CSharp/Verse.AI/ThinkNode_ConditionalNoTarget.cs @@ -1,5 +1,3 @@ -using System; - namespace Verse.AI { public class ThinkNode_ConditionalNoTarget : ThinkNode_Priority diff --git a/Assembly-CSharp/Verse.AI/ThinkNode_FilterPriority.cs b/Assembly-CSharp/Verse.AI/ThinkNode_FilterPriority.cs index 41fb0d389..5eeb3f605 100644 --- a/Assembly-CSharp/Verse.AI/ThinkNode_FilterPriority.cs +++ b/Assembly-CSharp/Verse.AI/ThinkNode_FilterPriority.cs @@ -1,5 +1,3 @@ -using System; - namespace Verse.AI { public class ThinkNode_FilterPriority : ThinkNode @@ -15,12 +13,12 @@ public override ThinkNode DeepCopy(bool resolve = true) public override ThinkResult TryIssueJobPackage(Pawn pawn, JobIssueParams jobParams) { - int count = this.subNodes.Count; - for (int i = 0; i < count; i++) + int count = base.subNodes.Count; + for (int num = 0; num < count; num++) { - if (this.subNodes[i].GetPriority(pawn) > this.minPriority) + if (base.subNodes[num].GetPriority(pawn) > this.minPriority) { - ThinkResult result = this.subNodes[i].TryIssueJobPackage(pawn, jobParams); + ThinkResult result = base.subNodes[num].TryIssueJobPackage(pawn, jobParams); if (result.IsValid) { return result; diff --git a/Assembly-CSharp/Verse.AI/ThinkNode_ForbidOutsideFlagRadius.cs b/Assembly-CSharp/Verse.AI/ThinkNode_ForbidOutsideFlagRadius.cs index 4544f6034..2f72b3399 100644 --- a/Assembly-CSharp/Verse.AI/ThinkNode_ForbidOutsideFlagRadius.cs +++ b/Assembly-CSharp/Verse.AI/ThinkNode_ForbidOutsideFlagRadius.cs @@ -1,4 +1,3 @@ -using System; using UnityEngine; namespace Verse.AI @@ -16,9 +15,9 @@ public override ThinkNode DeepCopy(bool resolve = true) public override ThinkResult TryIssueJobPackage(Pawn pawn, JobIssueParams jobParams) { - if (this.maxDistToSquadFlag > 0f) + if (this.maxDistToSquadFlag > 0.0) { - if (jobParams.maxDistToSquadFlag > 0f) + if (jobParams.maxDistToSquadFlag > 0.0) { jobParams.maxDistToSquadFlag = Mathf.Min(jobParams.maxDistToSquadFlag, this.maxDistToSquadFlag); } diff --git a/Assembly-CSharp/Verse.AI/ThinkNode_JobGiver.cs b/Assembly-CSharp/Verse.AI/ThinkNode_JobGiver.cs index 6ac64ca0b..dd426d5e4 100644 --- a/Assembly-CSharp/Verse.AI/ThinkNode_JobGiver.cs +++ b/Assembly-CSharp/Verse.AI/ThinkNode_JobGiver.cs @@ -1,5 +1,3 @@ -using System; - namespace Verse.AI { public abstract class ThinkNode_JobGiver : ThinkNode @@ -8,12 +6,11 @@ public abstract class ThinkNode_JobGiver : ThinkNode public override ThinkResult TryIssueJobPackage(Pawn pawn, JobIssueParams jobParams) { - ThinkResult result; try { - if (jobParams.maxDistToSquadFlag > 0f) + if (jobParams.maxDistToSquadFlag > 0.0) { - if (pawn.mindState.maxDistToSquadFlag > 0f) + if (pawn.mindState.maxDistToSquadFlag > 0.0) { Log.Error("Squad flag was not reset properly; raiders may behave strangely"); } @@ -22,18 +19,17 @@ public override ThinkResult TryIssueJobPackage(Pawn pawn, JobIssueParams jobPara Job job = this.TryGiveJob(pawn); if (job == null) { - result = ThinkResult.NoJob; - } - else - { - result = new ThinkResult(job, this, null); + return ThinkResult.NoJob; } + return new ThinkResult(job, this, default(JobTag?)); + IL_0071: + ThinkResult result; + return result; } finally { pawn.mindState.maxDistToSquadFlag = -1f; } - return result; } } } diff --git a/Assembly-CSharp/Verse.AI/ThinkNode_Priority.cs b/Assembly-CSharp/Verse.AI/ThinkNode_Priority.cs index 6d92b9c8f..3ce088cc6 100644 --- a/Assembly-CSharp/Verse.AI/ThinkNode_Priority.cs +++ b/Assembly-CSharp/Verse.AI/ThinkNode_Priority.cs @@ -6,23 +6,17 @@ public class ThinkNode_Priority : ThinkNode { public override ThinkResult TryIssueJobPackage(Pawn pawn, JobIssueParams jobParams) { - int count = this.subNodes.Count; - for (int i = 0; i < count; i++) + int count = base.subNodes.Count; + for (int num = 0; num < count; num++) { ThinkResult result = ThinkResult.NoJob; try { - result = this.subNodes[i].TryIssueJobPackage(pawn, jobParams); + result = base.subNodes[num].TryIssueJobPackage(pawn, jobParams); } catch (Exception ex) { - Log.Error(string.Concat(new object[] - { - "Exception in ", - base.GetType(), - " TryIssueJobPackage: ", - ex.ToString() - })); + Log.Error("Exception in " + base.GetType() + " TryIssueJobPackage: " + ex.ToString()); } if (result.IsValid) { diff --git a/Assembly-CSharp/Verse.AI/ThinkNode_PrioritySorter.cs b/Assembly-CSharp/Verse.AI/ThinkNode_PrioritySorter.cs index 9c1053f2c..a2691ae05 100644 --- a/Assembly-CSharp/Verse.AI/ThinkNode_PrioritySorter.cs +++ b/Assembly-CSharp/Verse.AI/ThinkNode_PrioritySorter.cs @@ -19,65 +19,51 @@ public override ThinkNode DeepCopy(bool resolve = true) public override ThinkResult TryIssueJobPackage(Pawn pawn, JobIssueParams jobParams) { ThinkNode_PrioritySorter.workingNodes.Clear(); - int count = this.subNodes.Count; - for (int i = 0; i < count; i++) + int count = base.subNodes.Count; + for (int num = 0; num < count; num++) { - ThinkNode_PrioritySorter.workingNodes.Insert(Rand.Range(0, ThinkNode_PrioritySorter.workingNodes.Count - 1), this.subNodes[i]); + ThinkNode_PrioritySorter.workingNodes.Insert(Rand.Range(0, ThinkNode_PrioritySorter.workingNodes.Count - 1), base.subNodes[num]); } while (ThinkNode_PrioritySorter.workingNodes.Count > 0) { - float num = 0f; - int num2 = -1; - for (int j = 0; j < ThinkNode_PrioritySorter.workingNodes.Count; j++) + float num2 = 0f; + int num3 = -1; + for (int i = 0; i < ThinkNode_PrioritySorter.workingNodes.Count; i++) { - float num3 = 0f; + float num4 = 0f; try { - num3 = ThinkNode_PrioritySorter.workingNodes[j].GetPriority(pawn); + num4 = ThinkNode_PrioritySorter.workingNodes[i].GetPriority(pawn); } catch (Exception ex) { - Log.Error(string.Concat(new object[] - { - "Exception in ", - base.GetType(), - " GetPriority: ", - ex.ToString() - })); + Log.Error("Exception in " + base.GetType() + " GetPriority: " + ex.ToString()); } - if (num3 > 0f && num3 >= this.minPriority) + if (!(num4 <= 0.0) && !(num4 < this.minPriority) && num4 > num2) { - if (num3 > num) - { - num = num3; - num2 = j; - } + num2 = num4; + num3 = i; } } - if (num2 == -1) + if (num3 != -1) { - break; - } - ThinkResult result = ThinkResult.NoJob; - try - { - result = ThinkNode_PrioritySorter.workingNodes[num2].TryIssueJobPackage(pawn, jobParams); - } - catch (Exception ex2) - { - Log.Error(string.Concat(new object[] + ThinkResult result = ThinkResult.NoJob; + try { - "Exception in ", - base.GetType(), - " TryIssueJobPackage: ", - ex2.ToString() - })); - } - if (result.IsValid) - { - return result; + result = ThinkNode_PrioritySorter.workingNodes[num3].TryIssueJobPackage(pawn, jobParams); + } + catch (Exception ex2) + { + Log.Error("Exception in " + base.GetType() + " TryIssueJobPackage: " + ex2.ToString()); + } + if (result.IsValid) + { + return result; + } + ThinkNode_PrioritySorter.workingNodes.RemoveAt(num3); + continue; } - ThinkNode_PrioritySorter.workingNodes.RemoveAt(num2); + break; } return ThinkResult.NoJob; } diff --git a/Assembly-CSharp/Verse.AI/ThinkNode_Random.cs b/Assembly-CSharp/Verse.AI/ThinkNode_Random.cs index b5a0e97e5..614fd93ee 100644 --- a/Assembly-CSharp/Verse.AI/ThinkNode_Random.cs +++ b/Assembly-CSharp/Verse.AI/ThinkNode_Random.cs @@ -1,4 +1,3 @@ -using System; using System.Collections.Generic; namespace Verse.AI @@ -10,11 +9,11 @@ public class ThinkNode_Random : ThinkNode public override ThinkResult TryIssueJobPackage(Pawn pawn, JobIssueParams jobParams) { ThinkNode_Random.tempList.Clear(); - for (int i = 0; i < this.subNodes.Count; i++) + for (int i = 0; i < base.subNodes.Count; i++) { - ThinkNode_Random.tempList.Add(this.subNodes[i]); + ThinkNode_Random.tempList.Add(base.subNodes[i]); } - ThinkNode_Random.tempList.Shuffle(); + ThinkNode_Random.tempList.Shuffle(); for (int j = 0; j < ThinkNode_Random.tempList.Count; j++) { ThinkResult result = ThinkNode_Random.tempList[j].TryIssueJobPackage(pawn, jobParams); diff --git a/Assembly-CSharp/Verse.AI/ThinkNode_Subtree.cs b/Assembly-CSharp/Verse.AI/ThinkNode_Subtree.cs index b0a36b996..f00d3de97 100644 --- a/Assembly-CSharp/Verse.AI/ThinkNode_Subtree.cs +++ b/Assembly-CSharp/Verse.AI/ThinkNode_Subtree.cs @@ -1,5 +1,3 @@ -using System; - namespace Verse.AI { public class ThinkNode_Subtree : ThinkNode @@ -16,7 +14,7 @@ public override ThinkNode DeepCopy(bool resolve = true) if (resolve) { thinkNode_Subtree.ResolveSubnodesAndRecur(); - thinkNode_Subtree.subtreeNode = thinkNode_Subtree.subNodes[this.subNodes.IndexOf(this.subtreeNode)]; + thinkNode_Subtree.subtreeNode = thinkNode_Subtree.subNodes[base.subNodes.IndexOf(this.subtreeNode)]; } return thinkNode_Subtree; } @@ -24,7 +22,7 @@ public override ThinkNode DeepCopy(bool resolve = true) protected override void ResolveSubnodes() { this.subtreeNode = this.treeDef.thinkRoot.DeepCopy(true); - this.subNodes.Add(this.subtreeNode); + base.subNodes.Add(this.subtreeNode); } public override ThinkResult TryIssueJobPackage(Pawn pawn, JobIssueParams jobParams) diff --git a/Assembly-CSharp/Verse.AI/ThinkNode_SubtreesByTag.cs b/Assembly-CSharp/Verse.AI/ThinkNode_SubtreesByTag.cs index bafa4ec2b..a4f9e0029 100644 --- a/Assembly-CSharp/Verse.AI/ThinkNode_SubtreesByTag.cs +++ b/Assembly-CSharp/Verse.AI/ThinkNode_SubtreesByTag.cs @@ -27,16 +27,16 @@ public override ThinkResult TryIssueJobPackage(Pawn pawn, JobIssueParams jobPara if (this.matchedTrees == null) { this.matchedTrees = new List(); - foreach (ThinkTreeDef current in DefDatabase.AllDefs) + foreach (ThinkTreeDef allDef in DefDatabase.AllDefs) { - if (current.insertTag == this.insertTag) + if (allDef.insertTag == this.insertTag) { - this.matchedTrees.Add(current); + this.matchedTrees.Add(allDef); } } this.matchedTrees = (from tDef in this.matchedTrees orderby tDef.insertPriority descending - select tDef).ToList(); + select tDef).ToList(); } for (int i = 0; i < this.matchedTrees.Count; i++) { diff --git a/Assembly-CSharp/Verse.AI/ThinkNode_Tagger.cs b/Assembly-CSharp/Verse.AI/ThinkNode_Tagger.cs index 63e322f2c..aa4cbe7c3 100644 --- a/Assembly-CSharp/Verse.AI/ThinkNode_Tagger.cs +++ b/Assembly-CSharp/Verse.AI/ThinkNode_Tagger.cs @@ -1,5 +1,3 @@ -using System; - namespace Verse.AI { public class ThinkNode_Tagger : ThinkNode_Priority @@ -15,13 +13,13 @@ public override ThinkNode DeepCopy(bool resolve = true) public override float GetPriority(Pawn pawn) { - if (this.priority >= 0f) + if (base.priority >= 0.0) { - return this.priority; + return base.priority; } - if (this.subNodes.Any()) + if (base.subNodes.Any()) { - return this.subNodes[0].GetPriority(pawn); + return base.subNodes[0].GetPriority(pawn); } Log.ErrorOnce("ThinkNode_PrioritySorter has child node which didn't give a priority: " + this, this.GetHashCode()); return 0f; diff --git a/Assembly-CSharp/Verse.AI/ThinkResult.cs b/Assembly-CSharp/Verse.AI/ThinkResult.cs index 4010d4dd7..3a7fcc8cc 100644 --- a/Assembly-CSharp/Verse.AI/ThinkResult.cs +++ b/Assembly-CSharp/Verse.AI/ThinkResult.cs @@ -46,11 +46,11 @@ public static ThinkResult NoJob { get { - return new ThinkResult(null, null, null); + return new ThinkResult(null, null, default(JobTag?)); } } - public ThinkResult(Job job, ThinkNode sourceNode, JobTag? tag = null) + public ThinkResult(Job job, ThinkNode sourceNode, JobTag? tag = default(JobTag?)) { this.jobInt = job; this.sourceNodeInt = sourceNode; @@ -61,44 +61,41 @@ public override string ToString() { string text = (this.Job == null) ? "null" : this.Job.ToString(); string text2 = (this.SourceNode == null) ? "null" : this.SourceNode.ToString(); - return string.Concat(new string[] - { - "(job=", - text, - " sourceNode=", - text2, - ")" - }); + return "(job=" + text + " sourceNode=" + text2 + ")"; } public override int GetHashCode() { int seed = 0; - seed = Gen.HashCombine(seed, this.jobInt); - seed = Gen.HashCombine(seed, this.sourceNodeInt); - return Gen.HashCombine(seed, this.tag); + seed = Gen.HashCombine(seed, this.jobInt); + seed = Gen.HashCombine(seed, this.sourceNodeInt); + return Gen.HashCombine(seed, this.tag); } public override bool Equals(object obj) { - return obj is ThinkResult && this.Equals((ThinkResult)obj); + if (!(obj is ThinkResult)) + { + return false; + } + return this.Equals((ThinkResult)obj); } public bool Equals(ThinkResult other) { - bool arg_59_0; + int result; if (this.jobInt == other.jobInt && this.sourceNodeInt == other.sourceNodeInt) { - JobTag? jobTag = this.tag; - JobTag arg_41_0 = jobTag.GetValueOrDefault(); - JobTag? jobTag2 = other.tag; - arg_59_0 = (arg_41_0 == jobTag2.GetValueOrDefault() && jobTag.HasValue == jobTag2.HasValue); + JobTag? nullable = this.tag; + JobTag valueOrDefault = nullable.GetValueOrDefault(); + JobTag? nullable2 = other.tag; + result = ((valueOrDefault == nullable2.GetValueOrDefault() && nullable.HasValue == nullable2.HasValue) ? 1 : 0); } else { - arg_59_0 = false; + result = 0; } - return arg_59_0; + return (byte)result != 0; } public static bool operator ==(ThinkResult lhs, ThinkResult rhs) diff --git a/Assembly-CSharp/Verse.AI/ThinkTreeDutyHook.cs b/Assembly-CSharp/Verse.AI/ThinkTreeDutyHook.cs index 2e610f8c5..e5e70098f 100644 --- a/Assembly-CSharp/Verse.AI/ThinkTreeDutyHook.cs +++ b/Assembly-CSharp/Verse.AI/ThinkTreeDutyHook.cs @@ -1,11 +1,9 @@ -using System; - namespace Verse.AI { public enum ThinkTreeDutyHook { - None, - HighPriority, - MediumPriority + None = 0, + HighPriority = 1, + MediumPriority = 2 } } diff --git a/Assembly-CSharp/Verse.AI/Toil.cs b/Assembly-CSharp/Verse.AI/Toil.cs index ef2ca08a0..05251b71d 100644 --- a/Assembly-CSharp/Verse.AI/Toil.cs +++ b/Assembly-CSharp/Verse.AI/Toil.cs @@ -42,17 +42,7 @@ public void Cleanup() } catch (Exception ex) { - Log.Error(string.Concat(new object[] - { - "Pawn ", - this.actor, - " threw exception while executing toil's finish action (", - i, - "), curJob=", - this.actor.CurJob, - ": ", - ex - })); + Log.Error("Pawn " + this.actor + " threw exception while executing toil's finish action (" + i + "), curJob=" + this.actor.CurJob + ": " + ex); } } } @@ -65,7 +55,7 @@ public Pawn GetActor() public void AddFailCondition(Func newFailCondition) { - this.endConditions.Add(delegate + this.endConditions.Add((Func)delegate() { if (newFailCondition()) { diff --git a/Assembly-CSharp/Verse.AI/ToilCompleteMode.cs b/Assembly-CSharp/Verse.AI/ToilCompleteMode.cs index b1271cddc..13ca037d2 100644 --- a/Assembly-CSharp/Verse.AI/ToilCompleteMode.cs +++ b/Assembly-CSharp/Verse.AI/ToilCompleteMode.cs @@ -1,14 +1,12 @@ -using System; - namespace Verse.AI { public enum ToilCompleteMode : byte { - Undefined, - Instant, - PatherArrival, - Delay, - FinishedBusy, - Never + Undefined = 0, + Instant = 1, + PatherArrival = 2, + Delay = 3, + FinishedBusy = 4, + Never = 5 } } diff --git a/Assembly-CSharp/Verse.AI/ToilEffects.cs b/Assembly-CSharp/Verse.AI/ToilEffects.cs index 45d8ba6da..fcec64fa3 100644 --- a/Assembly-CSharp/Verse.AI/ToilEffects.cs +++ b/Assembly-CSharp/Verse.AI/ToilEffects.cs @@ -9,7 +9,7 @@ public static class ToilEffects { public static Toil PlaySoundAtStart(this Toil toil, SoundDef sound) { - toil.AddPreInitAction(delegate + toil.AddPreInitAction((Action)delegate() { sound.PlayOneShot(new TargetInfo(toil.GetActor().Position, toil.GetActor().Map, false)); }); @@ -18,7 +18,7 @@ public static Toil PlaySoundAtStart(this Toil toil, SoundDef sound) public static Toil PlaySoundAtEnd(this Toil toil, SoundDef sound) { - toil.AddFinishAction(delegate + toil.AddFinishAction((Action)delegate() { sound.PlayOneShot(new TargetInfo(toil.GetActor().Position, toil.GetActor().Map, false)); }); @@ -27,28 +27,28 @@ public static Toil PlaySoundAtEnd(this Toil toil, SoundDef sound) public static Toil PlaySustainerOrSound(this Toil toil, SoundDef soundDef) { - return toil.PlaySustainerOrSound(() => soundDef); + return toil.PlaySustainerOrSound((Func)(() => soundDef)); } public static Toil PlaySustainerOrSound(this Toil toil, Func soundDefGetter) { Sustainer sustainer = null; - toil.AddPreInitAction(delegate + toil.AddPreInitAction((Action)delegate() { - SoundDef soundDef = soundDefGetter(); - if (soundDef != null && !soundDef.sustain) + SoundDef soundDef2 = soundDefGetter(); + if (soundDef2 != null && !soundDef2.sustain) { - soundDef.PlayOneShot(new TargetInfo(toil.GetActor().Position, toil.GetActor().Map, false)); + soundDef2.PlayOneShot(new TargetInfo(toil.GetActor().Position, toil.GetActor().Map, false)); } }); - toil.AddPreTickAction(delegate + toil.AddPreTickAction((Action)delegate() { if (sustainer == null || sustainer.Ended) { SoundDef soundDef = soundDefGetter(); if (soundDef != null && soundDef.sustain) { - SoundInfo info = SoundInfo.InMap(toil.actor, MaintenanceType.PerTick); + SoundInfo info = SoundInfo.InMap((Thing)toil.actor, MaintenanceType.PerTick); sustainer = soundDef.TrySpawnSustainer(info); } } @@ -62,39 +62,38 @@ public static Toil PlaySustainerOrSound(this Toil toil, Func soundDefG public static Toil WithEffect(this Toil toil, EffecterDef effectDef, TargetIndex ind) { - return toil.WithEffect(() => effectDef, ind); + return toil.WithEffect((Func)(() => effectDef), ind); } public static Toil WithEffect(this Toil toil, Func effecterDefGetter, TargetIndex ind) { - return toil.WithEffect(effecterDefGetter, () => toil.actor.CurJob.GetTarget(ind)); + return toil.WithEffect(effecterDefGetter, (Func)(() => toil.actor.CurJob.GetTarget(ind))); } public static Toil WithEffect(this Toil toil, Func effecterDefGetter, Thing thing) { - return toil.WithEffect(effecterDefGetter, () => thing); + return toil.WithEffect(effecterDefGetter, (Func)(() => thing)); } public static Toil WithEffect(this Toil toil, Func effecterDefGetter, Func effectTargetGetter) { Effecter effecter = null; - toil.AddPreTickAction(delegate + toil.AddPreTickAction((Action)delegate() { if (effecter == null) { EffecterDef effecterDef = effecterDefGetter(); - if (effecterDef == null) + if (effecterDef != null) { - return; + effecter = effecterDef.Spawn(); } - effecter = effecterDef.Spawn(); } else { - effecter.EffectTick(toil.actor, effectTargetGetter().ToTargetInfo(toil.actor.Map)); + effecter.EffectTick((Thing)toil.actor, effectTargetGetter().ToTargetInfo(toil.actor.Map)); } }); - toil.AddFinishAction(delegate + toil.AddFinishAction((Action)delegate { if (effecter != null) { @@ -108,41 +107,40 @@ public static Toil WithEffect(this Toil toil, Func effecterDefGette public static Toil WithProgressBar(this Toil toil, TargetIndex ind, Func progressGetter, bool interpolateBetweenActorAndTarget = false, float offsetZ = -0.5f) { Effecter effecter = null; - toil.AddPreTickAction(delegate + toil.AddPreTickAction((Action)delegate() { - if (toil.actor.Faction != Faction.OfPlayer) + if (toil.actor.Faction == Faction.OfPlayer) { - return; - } - if (effecter == null) - { - EffecterDef progressBar = EffecterDefOf.ProgressBar; - effecter = progressBar.Spawn(); - } - else - { - LocalTargetInfo target = toil.actor.CurJob.GetTarget(ind); - if (!target.IsValid || (target.HasThing && !target.Thing.Spawned)) - { - effecter.EffectTick(toil.actor, TargetInfo.Invalid); - } - else if (interpolateBetweenActorAndTarget) + if (effecter == null) { - effecter.EffectTick(toil.actor.CurJob.GetTarget(ind).ToTargetInfo(toil.actor.Map), toil.actor); + EffecterDef progressBar = EffecterDefOf.ProgressBar; + effecter = progressBar.Spawn(); } else { - effecter.EffectTick(toil.actor.CurJob.GetTarget(ind).ToTargetInfo(toil.actor.Map), TargetInfo.Invalid); - } - MoteProgressBar mote = ((SubEffecter_ProgressBar)effecter.children[0]).mote; - if (mote != null) - { - mote.progress = Mathf.Clamp01(progressGetter()); - mote.offsetZ = offsetZ; + LocalTargetInfo target = toil.actor.CurJob.GetTarget(ind); + if (!target.IsValid || (target.HasThing && !target.Thing.Spawned)) + { + effecter.EffectTick((Thing)toil.actor, TargetInfo.Invalid); + } + else if (interpolateBetweenActorAndTarget) + { + effecter.EffectTick(toil.actor.CurJob.GetTarget(ind).ToTargetInfo(toil.actor.Map), (Thing)toil.actor); + } + else + { + effecter.EffectTick(toil.actor.CurJob.GetTarget(ind).ToTargetInfo(toil.actor.Map), TargetInfo.Invalid); + } + MoteProgressBar mote = ((SubEffecter_ProgressBar)effecter.children[0]).mote; + if (mote != null) + { + mote.progress = Mathf.Clamp01(progressGetter()); + mote.offsetZ = offsetZ; + } } } }); - toil.AddFinishAction(delegate + toil.AddFinishAction((Action)delegate { if (effecter != null) { @@ -155,12 +153,12 @@ public static Toil WithProgressBar(this Toil toil, TargetIndex ind, Func public static Toil WithProgressBarToilDelay(this Toil toil, TargetIndex ind, bool interpolateBetweenActorAndTarget = false, float offsetZ = -0.5f) { - return toil.WithProgressBar(ind, () => 1f - (float)toil.actor.jobs.curDriver.ticksLeftThisToil / (float)toil.defaultDuration, interpolateBetweenActorAndTarget, offsetZ); + return toil.WithProgressBar(ind, (Func)(() => (float)(1.0 - (float)toil.actor.jobs.curDriver.ticksLeftThisToil / (float)toil.defaultDuration)), interpolateBetweenActorAndTarget, offsetZ); } public static Toil WithProgressBarToilDelay(this Toil toil, TargetIndex ind, int toilDuration, bool interpolateBetweenActorAndTarget = false, float offsetZ = -0.5f) { - return toil.WithProgressBar(ind, () => 1f - (float)toil.actor.jobs.curDriver.ticksLeftThisToil / (float)toilDuration, interpolateBetweenActorAndTarget, offsetZ); + return toil.WithProgressBar(ind, (Func)(() => (float)(1.0 - (float)toil.actor.jobs.curDriver.ticksLeftThisToil / (float)toilDuration)), interpolateBetweenActorAndTarget, offsetZ); } } } diff --git a/Assembly-CSharp/Verse.AI/ToilFailConditions.cs b/Assembly-CSharp/Verse.AI/ToilFailConditions.cs index b423e724a..01256986b 100644 --- a/Assembly-CSharp/Verse.AI/ToilFailConditions.cs +++ b/Assembly-CSharp/Verse.AI/ToilFailConditions.cs @@ -1,5 +1,6 @@ using RimWorld; using System; +using System.Collections.Generic; namespace Verse.AI { @@ -7,7 +8,7 @@ public static class ToilFailConditions { public static Toil FailOn(this Toil toil, Func condition) { - toil.AddEndCondition(delegate + toil.AddEndCondition((Func)delegate() { if (condition(toil)) { @@ -20,7 +21,7 @@ public static Toil FailOn(this Toil toil, Func condition) public static T FailOn(this T f, Func condition) where T : IJobEndable { - f.AddEndCondition(delegate + f.AddEndCondition((Func)delegate() { if (condition()) { @@ -33,7 +34,7 @@ public static T FailOn(this T f, Func condition) where T : IJobEndable public static T FailOnDestroyedOrNull(this T f, TargetIndex ind) where T : IJobEndable { - f.AddEndCondition(delegate + f.AddEndCondition((Func)delegate() { if (f.GetActor().jobs.curJob.GetTarget(ind).Thing.DestroyedOrNull()) { @@ -46,7 +47,7 @@ public static T FailOnDestroyedOrNull(this T f, TargetIndex ind) where T : IJ public static T FailOnDespawnedOrNull(this T f, TargetIndex ind) where T : IJobEndable { - f.AddEndCondition(delegate + f.AddEndCondition((Func)delegate() { LocalTargetInfo target = f.GetActor().jobs.curJob.GetTarget(ind); Thing thing = target.Thing; @@ -54,18 +55,18 @@ public static T FailOnDespawnedOrNull(this T f, TargetIndex ind) where T : IJ { return JobCondition.Ongoing; } - if (thing == null || !thing.Spawned || thing.Map != f.GetActor().Map) + if (thing != null && thing.Spawned && thing.Map == f.GetActor().Map) { - return JobCondition.Incompletable; + return JobCondition.Ongoing; } - return JobCondition.Ongoing; + return JobCondition.Incompletable; }); return f; } public static T EndOnDespawnedOrNull(this T f, TargetIndex ind, JobCondition endCondition = JobCondition.Incompletable) where T : IJobEndable { - f.AddEndCondition(delegate + f.AddEndCondition((Func)delegate() { LocalTargetInfo target = f.GetActor().jobs.curJob.GetTarget(ind); Thing thing = target.Thing; @@ -73,18 +74,18 @@ public static T EndOnDespawnedOrNull(this T f, TargetIndex ind, JobCondition { return JobCondition.Ongoing; } - if (thing == null || !thing.Spawned || thing.Map != f.GetActor().Map) + if (thing != null && thing.Spawned && thing.Map == f.GetActor().Map) { - return endCondition; + return JobCondition.Ongoing; } - return JobCondition.Ongoing; + return endCondition; }); return f; } public static T FailOnDowned(this T f, TargetIndex ind) where T : IJobEndable { - f.AddEndCondition(delegate + f.AddEndCondition((Func)delegate() { Thing thing = f.GetActor().jobs.curJob.GetTarget(ind).Thing; if (((Pawn)thing).Downed) @@ -98,7 +99,7 @@ public static T FailOnDowned(this T f, TargetIndex ind) where T : IJobEndable public static T FailOnNotDowned(this T f, TargetIndex ind) where T : IJobEndable { - f.AddEndCondition(delegate + f.AddEndCondition((Func)delegate() { Thing thing = f.GetActor().jobs.curJob.GetTarget(ind).Thing; if (!((Pawn)thing).Downed) @@ -112,7 +113,7 @@ public static T FailOnNotDowned(this T f, TargetIndex ind) where T : IJobEnda public static T FailOnNotAwake(this T f, TargetIndex ind) where T : IJobEndable { - f.AddEndCondition(delegate + f.AddEndCondition((Func)delegate() { Thing thing = f.GetActor().jobs.curJob.GetTarget(ind).Thing; if (!((Pawn)thing).Awake()) @@ -126,7 +127,7 @@ public static T FailOnNotAwake(this T f, TargetIndex ind) where T : IJobEndab public static T FailOnNotCasualInterruptible(this T f, TargetIndex ind) where T : IJobEndable { - f.AddEndCondition(delegate + f.AddEndCondition((Func)delegate() { Thing thing = f.GetActor().jobs.curJob.GetTarget(ind).Thing; if (!((Pawn)thing).CanCasuallyInteractNow(false)) @@ -140,7 +141,7 @@ public static T FailOnNotCasualInterruptible(this T f, TargetIndex ind) where public static T FailOnMentalState(this T f, TargetIndex ind) where T : IJobEndable { - f.AddEndCondition(delegate + f.AddEndCondition((Func)delegate() { Pawn pawn = f.GetActor().jobs.curJob.GetTarget(ind).Thing as Pawn; if (pawn != null && pawn.InMentalState) @@ -154,7 +155,7 @@ public static T FailOnMentalState(this T f, TargetIndex ind) where T : IJobEn public static T FailOnAggroMentalState(this T f, TargetIndex ind) where T : IJobEndable { - f.AddEndCondition(delegate + f.AddEndCondition((Func)delegate() { Pawn pawn = f.GetActor().jobs.curJob.GetTarget(ind).Thing as Pawn; if (pawn != null && pawn.InAggroMentalState) @@ -168,7 +169,7 @@ public static T FailOnAggroMentalState(this T f, TargetIndex ind) where T : I public static T FailOnSomeonePhysicallyInteracting(this T f, TargetIndex ind) where T : IJobEndable { - f.AddEndCondition(delegate + f.AddEndCondition((Func)delegate() { Pawn actor = f.GetActor(); Thing thing = actor.jobs.curJob.GetTarget(ind).Thing; @@ -183,7 +184,7 @@ public static T FailOnSomeonePhysicallyInteracting(this T f, TargetIndex ind) public static T FailOnForbidden(this T f, TargetIndex ind) where T : IJobEndable { - f.AddEndCondition(delegate + f.AddEndCondition((Func)delegate() { Pawn actor = f.GetActor(); if (actor.Faction != Faction.OfPlayer) @@ -210,21 +211,21 @@ public static T FailOnForbidden(this T f, TargetIndex ind) where T : IJobEnda public static T FailOnDespawnedNullOrForbidden(this T f, TargetIndex ind) where T : IJobEndable { - f.FailOnDespawnedOrNull(ind); - f.FailOnForbidden(ind); + f.FailOnDespawnedOrNull(ind); + f.FailOnForbidden(ind); return f; } public static T FailOnDestroyedNullOrForbidden(this T f, TargetIndex ind) where T : IJobEndable { - f.FailOnDestroyedOrNull(ind); - f.FailOnForbidden(ind); + f.FailOnDestroyedOrNull(ind); + f.FailOnForbidden(ind); return f; } public static T FailOnThingMissingDesignation(this T f, TargetIndex ind, DesignationDef desDef) where T : IJobEndable { - f.AddEndCondition(delegate + f.AddEndCondition((Func)delegate() { Pawn actor = f.GetActor(); Job curJob = actor.jobs.curJob; @@ -243,7 +244,7 @@ public static T FailOnThingMissingDesignation(this T f, TargetIndex ind, Desi public static T FailOnCellMissingDesignation(this T f, TargetIndex ind, DesignationDef desDef) where T : IJobEndable { - f.AddEndCondition(delegate + f.AddEndCondition((Func)delegate() { Pawn actor = f.GetActor(); Job curJob = actor.jobs.curJob; @@ -262,7 +263,7 @@ public static T FailOnCellMissingDesignation(this T f, TargetIndex ind, Desig public static T FailOnBurningImmobile(this T f, TargetIndex ind) where T : IJobEndable { - f.AddEndCondition(delegate + f.AddEndCondition((Func)delegate() { if (f.GetActor().jobs.curJob.GetTarget(ind).ToTargetInfo(f.GetActor().Map).IsBurning()) { @@ -275,7 +276,7 @@ public static T FailOnBurningImmobile(this T f, TargetIndex ind) where T : IJ public static T FailOnCannotTouch(this T f, TargetIndex ind, PathEndMode peMode) where T : IJobEndable { - f.AddEndCondition(delegate + f.AddEndCondition((Func)delegate() { if (!f.GetActor().CanReachImmediate(f.GetActor().jobs.curJob.GetTarget(ind), peMode)) { @@ -288,19 +289,29 @@ public static T FailOnCannotTouch(this T f, TargetIndex ind, PathEndMode peMo public static Toil FailOnDespawnedOrForbiddenPlacedThings(this Toil toil) { - toil.AddFailCondition(delegate + toil.AddFailCondition((Func)delegate() { if (toil.actor.jobs.curJob.placedThings == null) { return false; } - foreach (ThingStackPartClass current in toil.actor.jobs.curJob.placedThings) + List.Enumerator enumerator = toil.actor.jobs.curJob.placedThings.GetEnumerator(); + try { - if (!current.thing.Spawned || current.thing.Map != toil.actor.Map || (!toil.actor.CurJob.ignoreForbidden && current.thing.IsForbidden(toil.actor))) + while (enumerator.MoveNext()) { + ThingStackPartClass current = enumerator.Current; + if (current.thing.Spawned && current.thing.Map == toil.actor.Map && (toil.actor.CurJob.ignoreForbidden || !current.thing.IsForbidden(toil.actor))) + { + continue; + } return true; } } + finally + { + ((IDisposable)(object)enumerator).Dispose(); + } return false; }); return toil; diff --git a/Assembly-CSharp/Verse.AI/ToilJumpConditions.cs b/Assembly-CSharp/Verse.AI/ToilJumpConditions.cs index 150b16491..b05ac5fd3 100644 --- a/Assembly-CSharp/Verse.AI/ToilJumpConditions.cs +++ b/Assembly-CSharp/Verse.AI/ToilJumpConditions.cs @@ -7,12 +7,11 @@ public static class ToilJumpConditions { public static Toil JumpIf(this Toil toil, Func jumpCondition, Toil jumpToil) { - toil.AddPreTickAction(delegate + toil.AddPreTickAction((Action)delegate() { if (jumpCondition()) { toil.actor.jobs.curDriver.JumpToToil(jumpToil); - return; } }); return toil; @@ -20,7 +19,7 @@ public static Toil JumpIf(this Toil toil, Func jumpCondition, Toil jumpToi public static Toil JumpIfDespawnedOrNull(this Toil toil, TargetIndex ind, Toil jumpToil) { - return toil.JumpIf(delegate + return toil.JumpIf((Func)delegate() { Thing thing = toil.actor.jobs.curJob.GetTarget(ind).Thing; return thing == null || !thing.Spawned; @@ -29,7 +28,7 @@ public static Toil JumpIfDespawnedOrNull(this Toil toil, TargetIndex ind, Toil j public static Toil JumpIfDespawnedOrNullOrForbidden(this Toil toil, TargetIndex ind, Toil jumpToil) { - return toil.JumpIf(delegate + return toil.JumpIf((Func)delegate() { Thing thing = toil.actor.jobs.curJob.GetTarget(ind).Thing; return thing == null || !thing.Spawned || thing.IsForbidden(toil.actor); @@ -38,10 +37,14 @@ public static Toil JumpIfDespawnedOrNullOrForbidden(this Toil toil, TargetIndex public static Toil JumpIfOutsideHomeArea(this Toil toil, TargetIndex ind, Toil jumpToil) { - return toil.JumpIf(delegate + return toil.JumpIf((Func)delegate() { Thing thing = toil.actor.jobs.curJob.GetTarget(ind).Thing; - return !toil.actor.Map.areaManager.Home[thing.Position]; + if (!((Area)toil.actor.Map.areaManager.Home)[thing.Position]) + { + return true; + } + return false; }, jumpToil); } } diff --git a/Assembly-CSharp/Verse.AI/Toils_Combat.cs b/Assembly-CSharp/Verse.AI/Toils_Combat.cs index a5f4d8488..249203eea 100644 --- a/Assembly-CSharp/Verse.AI/Toils_Combat.cs +++ b/Assembly-CSharp/Verse.AI/Toils_Combat.cs @@ -8,7 +8,7 @@ public static class Toils_Combat public static Toil TrySetJobToUseAttackVerb() { Toil toil = new Toil(); - toil.initAction = delegate + toil.initAction = (Action)delegate { Pawn actor = toil.actor; Job curJob = actor.jobs.curJob; @@ -17,9 +17,11 @@ public static Toil TrySetJobToUseAttackVerb() if (verb == null) { actor.jobs.EndCurrentJob(JobCondition.Incompletable, true); - return; } - curJob.verbToUse = verb; + else + { + curJob.verbToUse = verb; + } }; return toil; } @@ -27,13 +29,13 @@ public static Toil TrySetJobToUseAttackVerb() public static Toil GotoCastPosition(TargetIndex targetInd, bool closeIfDowned = false) { Toil toil = new Toil(); - toil.initAction = delegate + toil.initAction = (Action)delegate() { Pawn actor = toil.actor; Job curJob = actor.jobs.curJob; Thing thing = curJob.GetTarget(targetInd).Thing; Pawn pawn = thing as Pawn; - IntVec3 intVec; + IntVec3 intVec = default(IntVec3); if (!CastPositionFinder.TryFindCastPosition(new CastPositionRequest { caster = toil.actor, @@ -44,10 +46,12 @@ public static Toil GotoCastPosition(TargetIndex targetInd, bool closeIfDowned = }, out intVec)) { toil.actor.jobs.EndCurrentJob(JobCondition.Incompletable, true); - return; } - toil.actor.pather.StartPath(intVec, PathEndMode.OnCell); - actor.Map.pawnDestinationManager.ReserveDestinationFor(actor, intVec); + else + { + toil.actor.pather.StartPath(intVec, PathEndMode.OnCell); + actor.Map.pawnDestinationManager.ReserveDestinationFor(actor, intVec); + } }; toil.FailOnDespawnedOrNull(targetInd); toil.defaultCompleteMode = ToilCompleteMode.PatherArrival; @@ -57,11 +61,11 @@ public static Toil GotoCastPosition(TargetIndex targetInd, bool closeIfDowned = public static Toil CastVerb(TargetIndex targetInd, bool canFreeIntercept = true) { Toil toil = new Toil(); - toil.initAction = delegate + toil.initAction = (Action)delegate() { - Verb arg_43_0 = toil.actor.jobs.curJob.verbToUse; + Verb verbToUse = toil.actor.jobs.curJob.verbToUse; bool canFreeIntercept2 = canFreeIntercept; - arg_43_0.TryStartCastOn(toil.actor.jobs.curJob.GetTarget(targetInd), false, canFreeIntercept2); + verbToUse.TryStartCastOn(toil.actor.jobs.curJob.GetTarget(targetInd), false, canFreeIntercept2); }; toil.defaultCompleteMode = ToilCompleteMode.FinishedBusy; return toil; @@ -70,7 +74,7 @@ public static Toil CastVerb(TargetIndex targetInd, bool canFreeIntercept = true) public static Toil FollowAndMeleeAttack(TargetIndex targetInd, Action hitAction) { Toil followAndAttack = new Toil(); - followAndAttack.tickAction = delegate + followAndAttack.tickAction = (Action)delegate() { Pawn actor = followAndAttack.actor; Job curJob = actor.jobs.curJob; @@ -80,9 +84,8 @@ public static Toil FollowAndMeleeAttack(TargetIndex targetInd, Action hitAction) if (!thing.Spawned) { curDriver.ReadyForNextToil(); - return; } - if (thing != actor.pather.Destination.Thing || (!actor.pather.Moving && !actor.CanReachImmediate(thing, PathEndMode.Touch))) + else if (thing != actor.pather.Destination.Thing || (!actor.pather.Moving && !actor.CanReachImmediate(thing, PathEndMode.Touch))) { actor.pather.StartPath(thing, PathEndMode.Touch); } @@ -91,9 +94,11 @@ public static Toil FollowAndMeleeAttack(TargetIndex targetInd, Action hitAction) if (pawn != null && pawn.Downed && !curJob.killIncappedTarget) { curDriver.ReadyForNextToil(); - return; } - hitAction(); + else + { + hitAction(); + } } }; followAndAttack.defaultCompleteMode = ToilCompleteMode.Never; diff --git a/Assembly-CSharp/Verse.AI/Toils_Effects.cs b/Assembly-CSharp/Verse.AI/Toils_Effects.cs index 3d237fbe6..2f2b20628 100644 --- a/Assembly-CSharp/Verse.AI/Toils_Effects.cs +++ b/Assembly-CSharp/Verse.AI/Toils_Effects.cs @@ -8,7 +8,7 @@ public static class Toils_Effects public static Toil MakeSound(string soundDefName) { Toil toil = new Toil(); - toil.initAction = delegate + toil.initAction = (Action)delegate() { Pawn actor = toil.actor; SoundDef.Named(soundDefName).PlayOneShot(new TargetInfo(actor.Position, actor.Map, false)); diff --git a/Assembly-CSharp/Verse.AI/Toils_General.cs b/Assembly-CSharp/Verse.AI/Toils_General.cs index e0873d4c3..0d9cabfba 100644 --- a/Assembly-CSharp/Verse.AI/Toils_General.cs +++ b/Assembly-CSharp/Verse.AI/Toils_General.cs @@ -8,7 +8,7 @@ public static class Toils_General public static Toil Wait(int ticks) { Toil toil = new Toil(); - toil.initAction = delegate + toil.initAction = (Action)delegate { toil.actor.pather.StopDead(); }; @@ -20,7 +20,7 @@ public static Toil Wait(int ticks) public static Toil WaitWith(TargetIndex targetInd, int ticks, bool useProgressBar = false, bool maintainPosture = false) { Toil toil = new Toil(); - toil.initAction = delegate + toil.initAction = (Action)delegate() { toil.actor.pather.StopDead(); Pawn pawn = toil.actor.CurJob.GetTarget(targetInd).Thing as Pawn; @@ -44,7 +44,7 @@ public static Toil WaitWith(TargetIndex targetInd, int ticks, bool useProgressBa public static Toil RemoveDesignationsOnThing(TargetIndex ind, DesignationDef def) { Toil toil = new Toil(); - toil.initAction = delegate + toil.initAction = (Action)delegate() { toil.actor.Map.designationManager.RemoveAllDesignationsOn(toil.actor.jobs.curJob.GetTarget(ind).Thing, false); }; @@ -54,9 +54,9 @@ public static Toil RemoveDesignationsOnThing(TargetIndex ind, DesignationDef def public static Toil ClearTarget(TargetIndex ind) { Toil toil = new Toil(); - toil.initAction = delegate + toil.initAction = (Action)delegate() { - toil.GetActor().CurJob.SetTarget(ind, null); + toil.GetActor().CurJob.SetTarget(ind, (Thing)null); }; return toil; } @@ -64,13 +64,13 @@ public static Toil ClearTarget(TargetIndex ind) public static Toil PutCarriedThingInInventory() { Toil toil = new Toil(); - toil.initAction = delegate + toil.initAction = (Action)delegate { Pawn actor = toil.GetActor(); if (actor.carryTracker.CarriedThing != null && !actor.carryTracker.innerContainer.TryTransferToContainer(actor.carryTracker.CarriedThing, actor.inventory.innerContainer, true)) { - Thing thing; - actor.carryTracker.TryDropCarriedThing(actor.Position, actor.carryTracker.CarriedThing.stackCount, ThingPlaceMode.Near, out thing, null); + Thing thing = default(Thing); + actor.carryTracker.TryDropCarriedThing(actor.Position, actor.carryTracker.CarriedThing.stackCount, ThingPlaceMode.Near, out thing, (Action)null); } }; return toil; diff --git a/Assembly-CSharp/Verse.AI/Toils_Goto.cs b/Assembly-CSharp/Verse.AI/Toils_Goto.cs index 382b4e355..066bf07a6 100644 --- a/Assembly-CSharp/Verse.AI/Toils_Goto.cs +++ b/Assembly-CSharp/Verse.AI/Toils_Goto.cs @@ -13,7 +13,7 @@ public static Toil Goto(TargetIndex ind, PathEndMode peMode) public static Toil GotoThing(TargetIndex ind, PathEndMode peMode) { Toil toil = new Toil(); - toil.initAction = delegate + toil.initAction = (Action)delegate() { Pawn actor = toil.actor; actor.pather.StartPath(actor.jobs.curJob.GetTarget(ind), peMode); @@ -26,7 +26,7 @@ public static Toil GotoThing(TargetIndex ind, PathEndMode peMode) public static Toil GotoThing(TargetIndex ind, IntVec3 exactCell) { Toil toil = new Toil(); - toil.initAction = delegate + toil.initAction = (Action)delegate() { Pawn actor = toil.actor; actor.pather.StartPath(exactCell, PathEndMode.OnCell); @@ -39,7 +39,7 @@ public static Toil GotoThing(TargetIndex ind, IntVec3 exactCell) public static Toil GotoCell(TargetIndex ind, PathEndMode peMode) { Toil toil = new Toil(); - toil.initAction = delegate + toil.initAction = (Action)delegate() { Pawn actor = toil.actor; actor.pather.StartPath(actor.jobs.curJob.GetTarget(ind), peMode); @@ -51,7 +51,7 @@ public static Toil GotoCell(TargetIndex ind, PathEndMode peMode) public static Toil GotoCell(IntVec3 cell, PathEndMode peMode) { Toil toil = new Toil(); - toil.initAction = delegate + toil.initAction = (Action)delegate() { Pawn actor = toil.actor; actor.pather.StartPath(cell, peMode); @@ -63,22 +63,23 @@ public static Toil GotoCell(IntVec3 cell, PathEndMode peMode) public static Toil MoveOffTargetBlueprint(TargetIndex targetInd) { Toil toil = new Toil(); - toil.initAction = delegate + toil.initAction = (Action)delegate() { Pawn actor = toil.actor; Thing thing = actor.jobs.curJob.GetTarget(targetInd).Thing as Blueprint; + IntVec3 c = default(IntVec3); if (thing == null || !actor.Position.IsInside(thing)) { actor.jobs.curDriver.ReadyForNextToil(); - return; } - IntVec3 c; - if (RCellFinder.TryFindGoodAdjacentSpotToTouch(actor, thing, out c)) + else if (RCellFinder.TryFindGoodAdjacentSpotToTouch(actor, thing, out c)) { actor.pather.StartPath(c, PathEndMode.OnCell); - return; } - actor.jobs.EndCurrentJob(JobCondition.Incompletable, true); + else + { + actor.jobs.EndCurrentJob(JobCondition.Incompletable, true); + } }; toil.defaultCompleteMode = ToilCompleteMode.PatherArrival; return toil; diff --git a/Assembly-CSharp/Verse.AI/Toils_Haul.cs b/Assembly-CSharp/Verse.AI/Toils_Haul.cs index b5e9959c4..d100cb115 100644 --- a/Assembly-CSharp/Verse.AI/Toils_Haul.cs +++ b/Assembly-CSharp/Verse.AI/Toils_Haul.cs @@ -13,35 +13,17 @@ public static void ErrorCheckForCarry(Pawn pawn, Thing haulThing) { if (!haulThing.Spawned) { - Log.Message(string.Concat(new object[] - { - pawn, - " tried to start carry ", - haulThing, - " which isn't spawned." - })); + Log.Message(pawn + " tried to start carry " + haulThing + " which isn't spawned."); pawn.jobs.EndCurrentJob(JobCondition.Incompletable, true); } if (haulThing.stackCount == 0) { - Log.Message(string.Concat(new object[] - { - pawn, - " tried to start carry ", - haulThing, - " which had stackcount 0." - })); + Log.Message(pawn + " tried to start carry " + haulThing + " which had stackcount 0."); pawn.jobs.EndCurrentJob(JobCondition.Incompletable, true); } if (pawn.jobs.curJob.count <= 0) { - Log.Error(string.Concat(new object[] - { - "Invalid count: ", - pawn.jobs.curJob.count, - ", setting to 1. Job was ", - pawn.jobs.curJob - })); + Log.Error("Invalid count: " + pawn.jobs.curJob.count + ", setting to 1. Job was " + pawn.jobs.curJob); pawn.jobs.curJob.count = 1; } } @@ -49,7 +31,7 @@ public static void ErrorCheckForCarry(Pawn pawn, Thing haulThing) public static Toil StartCarryThing(TargetIndex haulableInd, bool putRemainderInQueue = false, bool subtractNumTakenFromJobCount = false) { Toil toil = new Toil(); - toil.initAction = delegate + toil.initAction = (Action)delegate() { Pawn actor = toil.actor; Job curJob = actor.jobs.curJob; @@ -57,33 +39,14 @@ public static Toil StartCarryThing(TargetIndex haulableInd, bool putRemainderInQ Toils_Haul.ErrorCheckForCarry(actor, thing); if (curJob.count == 0) { - throw new Exception(string.Concat(new object[] - { - "StartCarryThing job had count = ", - curJob.count, - ". Job: ", - curJob - })); + throw new Exception("StartCarryThing job had count = " + curJob.count + ". Job: " + curJob); } int num = actor.carryTracker.AvailableStackSpace(thing.def); if (num == 0) { - throw new Exception(string.Concat(new object[] - { - "StartCarryThing got availableStackSpace ", - num, - " for haulTarg ", - thing, - ". Job: ", - curJob - })); + throw new Exception("StartCarryThing got availableStackSpace " + num + " for haulTarg " + thing + ". Job: " + curJob); } - int num2 = Mathf.Min(new int[] - { - curJob.count, - num, - thing.stackCount - }); + int num2 = Mathf.Min(curJob.count, num, thing.stackCount); if (num2 <= 0) { throw new Exception("StartCarryThing desiredNumToTake = " + num2); @@ -125,37 +88,40 @@ public static Toil StartCarryThing(TargetIndex haulableInd, bool putRemainderInQ public static Toil JumpIfAlsoCollectingNextTargetInQueue(Toil gotoGetTargetToil, TargetIndex ind) { Toil toil = new Toil(); - toil.initAction = delegate + toil.initAction = (Action)delegate() { Pawn actor = toil.actor; Job curJob = actor.jobs.curJob; List targetQueue = curJob.GetTargetQueue(ind); - if (targetQueue.NullOrEmpty()) - { - return; - } - if (curJob.count <= 0) - { - return; - } - if (actor.carryTracker.CarriedThing == null) + if (!targetQueue.NullOrEmpty() && curJob.count > 0) { - Log.Error("JumpToAlsoCollectTargetInQueue run on " + actor + " who is not carrying something."); - return; - } - for (int i = 0; i < targetQueue.Count; i++) - { - if (!GenAI.CanUseItemForWork(actor, targetQueue[i].Thing)) + if (actor.carryTracker.CarriedThing == null) { - actor.jobs.EndCurrentJob(JobCondition.Incompletable, true); - return; + Log.Error("JumpToAlsoCollectTargetInQueue run on " + actor + " who is not carrying something."); } - if (targetQueue[i].Thing.def == actor.carryTracker.CarriedThing.def) + else { - curJob.SetTarget(ind, targetQueue[i].Thing); - targetQueue.RemoveAt(i); + int num = 0; + while (true) + { + if (num < targetQueue.Count) + { + if (GenAI.CanUseItemForWork(actor, targetQueue[num].Thing)) + { + if (targetQueue[num].Thing.def != actor.carryTracker.CarriedThing.def) + { + num++; + continue; + } + break; + } + actor.jobs.EndCurrentJob(JobCondition.Incompletable, true); + } + return; + } + curJob.SetTarget(ind, targetQueue[num].Thing); + targetQueue.RemoveAt(num); actor.jobs.curDriver.JumpToToil(gotoGetTargetToil); - break; } } }; @@ -165,28 +131,55 @@ public static Toil JumpIfAlsoCollectingNextTargetInQueue(Toil gotoGetTargetToil, public static Toil CheckForGetOpportunityDuplicate(Toil getHaulTargetToil, TargetIndex haulableInd, TargetIndex storeCellInd, bool takeFromValidStorage = false, Predicate extraValidator = null) { Toil toil = new Toil(); - toil.initAction = delegate + toil.initAction = (Action)delegate() { Pawn actor = toil.actor; Job curJob = actor.jobs.curJob; - if (actor.carryTracker.CarriedThing.def.stackLimit == 1) - { - return; - } - if (actor.carryTracker.Full) - { - return; - } - if (curJob.count <= 0) - { - return; - } - Predicate validator = (Thing t) => t.Spawned && t.def == actor.carryTracker.CarriedThing.def && t.CanStackWith(actor.carryTracker.CarriedThing) && !t.IsForbidden(actor) && (takeFromValidStorage || !t.IsInValidStorage()) && (storeCellInd == TargetIndex.None || curJob.GetTarget(storeCellInd).Cell.IsValidStorageFor(actor.Map, t)) && actor.CanReserve(t, 1, -1, null, false) && (extraValidator == null || extraValidator(t)); - Thing thing = GenClosest.ClosestThingReachable(actor.Position, actor.Map, ThingRequest.ForGroup(ThingRequestGroup.HaulableAlways), PathEndMode.ClosestTouch, TraverseParms.For(actor, Danger.Deadly, TraverseMode.ByPawn, false), 8f, validator, null, 0, -1, false, RegionType.Set_Passable, false); - if (thing != null) + if (actor.carryTracker.CarriedThing.def.stackLimit != 1 && !actor.carryTracker.Full && curJob.count > 0) { - curJob.SetTarget(haulableInd, thing); - actor.jobs.curDriver.JumpToToil(getHaulTargetToil); + Thing thing = null; + Predicate validator = (Predicate)delegate(Thing t) + { + if (!t.Spawned) + { + return false; + } + if (t.def != actor.carryTracker.CarriedThing.def) + { + return false; + } + if (!t.CanStackWith(actor.carryTracker.CarriedThing)) + { + return false; + } + if (t.IsForbidden(actor)) + { + return false; + } + if (!takeFromValidStorage && t.IsInValidStorage()) + { + return false; + } + if (storeCellInd != 0 && !curJob.GetTarget(storeCellInd).Cell.IsValidStorageFor(actor.Map, t)) + { + return false; + } + if (!actor.CanReserve(t, 1, -1, null, false)) + { + return false; + } + if ((object)extraValidator != null && !extraValidator(t)) + { + return false; + } + return true; + }; + thing = GenClosest.ClosestThingReachable(actor.Position, actor.Map, ThingRequest.ForGroup(ThingRequestGroup.HaulableAlways), PathEndMode.ClosestTouch, TraverseParms.For(actor, Danger.Deadly, TraverseMode.ByPawn, false), 8f, validator, null, 0, -1, false, RegionType.Set_Passable, false); + if (thing != null) + { + curJob.SetTarget(haulableInd, thing); + actor.jobs.curDriver.JumpToToil(getHaulTargetToil); + } } }; return toil; @@ -195,17 +188,21 @@ public static Toil CheckForGetOpportunityDuplicate(Toil getHaulTargetToil, Targe public static Toil CarryHauledThingToCell(TargetIndex squareIndex) { Toil toil = new Toil(); - toil.initAction = delegate + toil.initAction = (Action)delegate() { - IntVec3 cell = toil.actor.jobs.curJob.GetTarget(squareIndex).Cell; - toil.actor.pather.StartPath(cell, PathEndMode.ClosestTouch); + IntVec3 cell2 = toil.actor.jobs.curJob.GetTarget(squareIndex).Cell; + toil.actor.pather.StartPath(cell2, PathEndMode.ClosestTouch); }; toil.defaultCompleteMode = ToilCompleteMode.PatherArrival; - toil.AddFailCondition(delegate + toil.AddFailCondition((Func)delegate() { Pawn actor = toil.actor; IntVec3 cell = actor.jobs.curJob.GetTarget(squareIndex).Cell; - return actor.jobs.curJob.haulMode == HaulMode.ToCellStorage && !cell.IsValidStorageFor(actor.Map, actor.carryTracker.CarriedThing); + if (actor.jobs.curJob.haulMode == HaulMode.ToCellStorage && !cell.IsValidStorageFor(actor.Map, actor.carryTracker.CarriedThing)) + { + return true; + } + return false; }); return toil; } @@ -213,22 +210,14 @@ public static Toil CarryHauledThingToCell(TargetIndex squareIndex) public static Toil PlaceCarriedThingInCellFacing(TargetIndex facingTargetInd) { Toil toil = new Toil(); - toil.initAction = delegate + toil.initAction = (Action)delegate() { Pawn actor = toil.actor; LocalTargetInfo target = actor.CurJob.GetTarget(facingTargetInd); - IntVec3 b; - if (target.HasThing) - { - b = target.Thing.OccupiedRect().ClosestCellTo(actor.Position); - } - else - { - b = target.Cell; - } + IntVec3 b = (!target.HasThing) ? target.Cell : target.Thing.OccupiedRect().ClosestCellTo(actor.Position); IntVec3 dropLoc = actor.Position + PawnRotator.RotFromAngleBiased((actor.Position - b).AngleFlat).FacingCell; - Thing thing; - if (!actor.carryTracker.TryDropCarriedThing(dropLoc, ThingPlaceMode.Direct, out thing, null)) + Thing thing = default(Thing); + if (!actor.carryTracker.TryDropCarriedThing(dropLoc, ThingPlaceMode.Direct, out thing, (Action)null)) { actor.jobs.EndCurrentJob(JobCondition.Incompletable, true); } @@ -239,7 +228,7 @@ public static Toil PlaceCarriedThingInCellFacing(TargetIndex facingTargetInd) public static Toil PlaceHauledThingInCell(TargetIndex cellInd, Toil nextToilOnPlaceFailOrIncomplete, bool storageMode) { Toil toil = new Toil(); - toil.initAction = delegate + toil.initAction = (Action)delegate() { Pawn actor = toil.actor; Job curJob = actor.jobs.curJob; @@ -252,13 +241,13 @@ public static Toil PlaceHauledThingInCell(TargetIndex cellInd, Toil nextToilOnPl Action placedAction = null; if (curJob.def == JobDefOf.DoBill) { - placedAction = delegate(Thing th, int added) + placedAction = (Action)delegate(Thing th, int added) { if (curJob.placedThings == null) { curJob.placedThings = new List(); } - ThingStackPartClass thingStackPartClass = curJob.placedThings.Find((ThingStackPartClass x) => x.thing == th); + ThingStackPartClass thingStackPartClass = curJob.placedThings.Find((Predicate)((ThingStackPartClass x) => x.thing == th)); if (thingStackPartClass != null) { thingStackPartClass.Count += added; @@ -269,12 +258,12 @@ public static Toil PlaceHauledThingInCell(TargetIndex cellInd, Toil nextToilOnPl } }; } - Thing thing; + Thing thing = default(Thing); if (!actor.carryTracker.TryDropCarriedThing(cell, ThingPlaceMode.Direct, out thing, placedAction)) { if (storageMode) { - IntVec3 c; + IntVec3 c = default(IntVec3); if (nextToilOnPlaceFailOrIncomplete != null && StoreUtility.TryFindBestBetterStoreCellFor(actor.carryTracker.CarriedThing, actor, actor.Map, StoragePriority.Unstored, actor.Faction, out c, true)) { if (actor.CanReserve(c, 1, -1, null, false)) @@ -283,38 +272,30 @@ public static Toil PlaceHauledThingInCell(TargetIndex cellInd, Toil nextToilOnPl } actor.CurJob.SetTarget(cellInd, c); actor.jobs.curDriver.JumpToToil(nextToilOnPlaceFailOrIncomplete); - return; - } - Job job = HaulAIUtility.HaulAsideJobFor(actor, actor.carryTracker.CarriedThing); - if (job != null) - { - curJob.targetA = job.targetA; - curJob.targetB = job.targetB; - curJob.targetC = job.targetC; - curJob.count = job.count; - curJob.haulOpportunisticDuplicates = job.haulOpportunisticDuplicates; - curJob.haulMode = job.haulMode; - actor.jobs.curDriver.JumpToToil(nextToilOnPlaceFailOrIncomplete); } else { - Log.Error(string.Concat(new object[] + Job job = HaulAIUtility.HaulAsideJobFor(actor, actor.carryTracker.CarriedThing); + if (job != null) + { + curJob.targetA = job.targetA; + curJob.targetB = job.targetB; + curJob.targetC = job.targetC; + curJob.count = job.count; + curJob.haulOpportunisticDuplicates = job.haulOpportunisticDuplicates; + curJob.haulMode = job.haulMode; + actor.jobs.curDriver.JumpToToil(nextToilOnPlaceFailOrIncomplete); + } + else { - "Incomplete haul for ", - actor, - ": Could not find anywhere to put ", - actor.carryTracker.CarriedThing, - " near ", - actor.Position, - ". Destroying. This should never happen!" - })); - actor.carryTracker.CarriedThing.Destroy(DestroyMode.Vanish); + Log.Error("Incomplete haul for " + actor + ": Could not find anywhere to put " + actor.carryTracker.CarriedThing + " near " + actor.Position + ". Destroying. This should never happen!"); + actor.carryTracker.CarriedThing.Destroy(DestroyMode.Vanish); + } } } else if (nextToilOnPlaceFailOrIncomplete != null) { actor.jobs.curDriver.JumpToToil(nextToilOnPlaceFailOrIncomplete); - return; } } }; @@ -324,19 +305,23 @@ public static Toil PlaceHauledThingInCell(TargetIndex cellInd, Toil nextToilOnPl public static Toil CarryHauledThingToContainer() { Toil gotoDest = new Toil(); - gotoDest.initAction = delegate + gotoDest.initAction = (Action)delegate { gotoDest.actor.pather.StartPath(gotoDest.actor.jobs.curJob.targetB.Thing, PathEndMode.Touch); }; - gotoDest.AddFailCondition(delegate + gotoDest.AddFailCondition((Func)delegate { Thing thing = gotoDest.actor.jobs.curJob.targetB.Thing; - if (thing.Destroyed || thing.IsForbidden(gotoDest.actor)) + if (!thing.Destroyed && !thing.IsForbidden(gotoDest.actor)) { - return true; + ThingOwner thingOwner = thing.TryGetInnerInteractableThingOwner(); + if (thingOwner != null && !thingOwner.CanAcceptAnyOf(gotoDest.actor.carryTracker.CarriedThing, true)) + { + return true; + } + return false; } - ThingOwner thingOwner = thing.TryGetInnerInteractableThingOwner(); - return thingOwner != null && !thingOwner.CanAcceptAnyOf(gotoDest.actor.carryTracker.CarriedThing, true); + return true; }); gotoDest.defaultCompleteMode = ToilCompleteMode.PatherArrival; return gotoDest; @@ -345,43 +330,45 @@ public static Toil CarryHauledThingToContainer() public static Toil DepositHauledThingInContainer(TargetIndex containerInd, TargetIndex reserveForContainerInd) { Toil toil = new Toil(); - toil.initAction = delegate + toil.initAction = (Action)delegate() { Pawn actor = toil.actor; Job curJob = actor.jobs.curJob; if (actor.carryTracker.CarriedThing == null) { Log.Error(actor + " tried to place hauled thing in container but is not hauling anything."); - return; } - Thing thing = curJob.GetTarget(containerInd).Thing; - ThingOwner thingOwner = thing.TryGetInnerInteractableThingOwner(); - if (thingOwner != null) + else { - int num = actor.carryTracker.CarriedThing.stackCount; - if (thing is IConstructible) + Thing thing = curJob.GetTarget(containerInd).Thing; + ThingOwner thingOwner = thing.TryGetInnerInteractableThingOwner(); + if (thingOwner != null) { - int a = GenConstruct.AmountNeededByOf((IConstructible)thing, actor.carryTracker.CarriedThing.def); - num = Mathf.Min(a, num); - if (reserveForContainerInd != TargetIndex.None) + int num = actor.carryTracker.CarriedThing.stackCount; + if (thing is IConstructible) { - Thing thing2 = curJob.GetTarget(reserveForContainerInd).Thing; - if (thing2 != null && thing2 != thing) + int a = GenConstruct.AmountNeededByOf((IConstructible)thing, actor.carryTracker.CarriedThing.def); + num = Mathf.Min(a, num); + if (reserveForContainerInd != 0) { - int num2 = GenConstruct.AmountNeededByOf((IConstructible)thing2, actor.carryTracker.CarriedThing.def); - num = Mathf.Min(num, actor.carryTracker.CarriedThing.stackCount - num2); + Thing thing2 = curJob.GetTarget(reserveForContainerInd).Thing; + if (thing2 != null && thing2 != thing) + { + int num2 = GenConstruct.AmountNeededByOf((IConstructible)thing2, actor.carryTracker.CarriedThing.def); + num = Mathf.Min(num, actor.carryTracker.CarriedThing.stackCount - num2); + } } } + actor.carryTracker.innerContainer.TryTransferToContainer(actor.carryTracker.CarriedThing, thingOwner, num, true); + } + else if (curJob.GetTarget(containerInd).Thing.def.Minifiable) + { + actor.carryTracker.innerContainer.Clear(); + } + else + { + Log.Error("Could not deposit hauled thing in container: " + curJob.GetTarget(containerInd).Thing); } - actor.carryTracker.innerContainer.TryTransferToContainer(actor.carryTracker.CarriedThing, thingOwner, num, true); - } - else if (curJob.GetTarget(containerInd).Thing.def.Minifiable) - { - actor.carryTracker.innerContainer.Clear(); - } - else - { - Log.Error("Could not deposit hauled thing in container: " + curJob.GetTarget(containerInd).Thing); } }; return toil; @@ -390,24 +377,35 @@ public static Toil DepositHauledThingInContainer(TargetIndex containerInd, Targe public static Toil JumpToCarryToNextContainerIfPossible(Toil carryToContainerToil, TargetIndex primaryTargetInd) { Toil toil = new Toil(); - toil.initAction = delegate + toil.initAction = (Action)delegate() { Pawn actor = toil.actor; Job curJob = actor.jobs.curJob; - if (actor.carryTracker.CarriedThing == null) - { - return; - } - if (curJob.targetQueueB != null && curJob.targetQueueB.Count > 0) + if (actor.carryTracker.CarriedThing != null && curJob.targetQueueB != null && curJob.targetQueueB.Count > 0) { Thing primaryTarget = curJob.GetTarget(primaryTargetInd).Thing; bool hasSpareItems = actor.carryTracker.CarriedThing.stackCount > GenConstruct.AmountNeededByOf((IConstructible)primaryTarget, actor.carryTracker.CarriedThing.def); - Predicate validator = (Thing th) => GenConstruct.CanConstruct(th, actor, false) && ((IConstructible)th).MaterialsNeeded().Any((ThingCountClass need) => need.thingDef == actor.carryTracker.CarriedThing.def) && (th == primaryTarget || hasSpareItems); + Predicate validator = (Predicate)delegate(Thing th) + { + if (!GenConstruct.CanConstruct(th, actor, false)) + { + return false; + } + if (!((IConstructible)th).MaterialsNeeded().Any((Predicate)((ThingCountClass need) => need.thingDef == actor.carryTracker.CarriedThing.def))) + { + return false; + } + if (th != primaryTarget && !hasSpareItems) + { + return false; + } + return true; + }; Thing nextTarget = GenClosest.ClosestThing_Global_Reachable(actor.Position, actor.Map, from targ in curJob.targetQueueB select targ.Thing, PathEndMode.Touch, TraverseParms.For(actor, Danger.Deadly, TraverseMode.ByPawn, false), 99999f, validator, null); if (nextTarget != null) { - curJob.targetQueueB.RemoveAll((LocalTargetInfo targ) => targ.Thing == nextTarget); + curJob.targetQueueB.RemoveAll((Predicate)((LocalTargetInfo targ) => targ.Thing == nextTarget)); curJob.targetB = nextTarget; actor.jobs.curDriver.JumpToToil(carryToContainerToil); } @@ -418,13 +416,13 @@ public static Toil JumpToCarryToNextContainerIfPossible(Toil carryToContainerToi public static Toil TakeToInventory(TargetIndex ind, int count) { - return Toils_Haul.TakeToInventory(ind, () => count); + return Toils_Haul.TakeToInventory(ind, (Func)(() => count)); } public static Toil TakeToInventory(TargetIndex ind, Func countGetter) { Toil takeThing = new Toil(); - takeThing.initAction = delegate + takeThing.initAction = (Action)delegate() { Pawn actor = takeThing.actor; Thing thing = actor.CurJob.GetTarget(ind).Thing; @@ -437,7 +435,7 @@ public static Toil TakeToInventory(TargetIndex ind, Func countGetter) else { actor.inventory.GetDirectlyHeldThings().TryAdd(thing, num, true); - if (thing.def.ingestible != null && thing.def.ingestible.preferability <= FoodPreferability.RawTasty) + if (thing.def.ingestible != null && (int)thing.def.ingestible.preferability <= 4) { actor.mindState.lastInventoryRawFoodUseTick = Find.TickManager.TicksGame; } diff --git a/Assembly-CSharp/Verse.AI/Toils_Interact.cs b/Assembly-CSharp/Verse.AI/Toils_Interact.cs index 5a542aa86..ba2abf8d6 100644 --- a/Assembly-CSharp/Verse.AI/Toils_Interact.cs +++ b/Assembly-CSharp/Verse.AI/Toils_Interact.cs @@ -7,7 +7,7 @@ internal class Toils_Interact public static Toil DestroyThing(TargetIndex ind) { Toil toil = new Toil(); - toil.initAction = delegate + toil.initAction = (Action)delegate() { Pawn actor = toil.actor; Thing thing = actor.jobs.curJob.GetTarget(ind).Thing; diff --git a/Assembly-CSharp/Verse.AI/Toils_JobTransforms.cs b/Assembly-CSharp/Verse.AI/Toils_JobTransforms.cs index c33ca672d..d5f1963f2 100644 --- a/Assembly-CSharp/Verse.AI/Toils_JobTransforms.cs +++ b/Assembly-CSharp/Verse.AI/Toils_JobTransforms.cs @@ -1,7 +1,7 @@ using RimWorld; using System; using System.Collections.Generic; -using System.Diagnostics; +using System.Linq; namespace Verse.AI { @@ -12,21 +12,20 @@ public static class Toils_JobTransforms public static Toil ExtractNextTargetFromQueue(TargetIndex ind) { Toil toil = new Toil(); - toil.initAction = delegate + toil.initAction = (Action)delegate() { Pawn actor = toil.actor; Job curJob = actor.jobs.curJob; List targetQueue = curJob.GetTargetQueue(ind); - if (targetQueue.NullOrEmpty()) + if (!targetQueue.NullOrEmpty()) { - return; - } - curJob.SetTarget(ind, targetQueue[0]); - targetQueue.RemoveAt(0); - if (!curJob.countQueue.NullOrEmpty()) - { - curJob.count = curJob.countQueue[0]; - curJob.countQueue.RemoveAt(0); + curJob.SetTarget(ind, targetQueue[0]); + targetQueue.RemoveAt(0); + if (!curJob.countQueue.NullOrEmpty()) + { + curJob.count = curJob.countQueue[0]; + curJob.countQueue.RemoveAt(0); + } } }; return toil; @@ -35,56 +34,73 @@ public static Toil ExtractNextTargetFromQueue(TargetIndex ind) public static Toil ClearDespawnedNullOrForbiddenQueuedTargets(TargetIndex ind) { Toil toil = new Toil(); - toil.initAction = delegate + toil.initAction = (Action)delegate() { Pawn actor = toil.actor; Job curJob = actor.jobs.curJob; List targetQueue = curJob.GetTargetQueue(ind); - targetQueue.RemoveAll((LocalTargetInfo ta) => !ta.HasThing || !ta.Thing.Spawned || ta.Thing.IsForbidden(actor)); + targetQueue.RemoveAll((Predicate)((LocalTargetInfo ta) => !ta.HasThing || !ta.Thing.Spawned || ta.Thing.IsForbidden(actor))); }; return toil; } - [DebuggerHidden] private static IEnumerable IngredientPlaceCellsInOrder(IBillGiver billGiver) { - Toils_JobTransforms.c__Iterator1BC c__Iterator1BC = new Toils_JobTransforms.c__Iterator1BC(); - c__Iterator1BC.billGiver = billGiver; - c__Iterator1BC.<$>billGiver = billGiver; - Toils_JobTransforms.c__Iterator1BC expr_15 = c__Iterator1BC; - expr_15.$PC = -2; - return expr_15; + Toils_JobTransforms.yieldedIngPlaceCells.Clear(); + IntVec3 interactCell = ((Thing)billGiver).InteractionCell; + foreach (IntVec3 item in from c in billGiver.IngredientStackCells + orderby (c - ((_003CIngredientPlaceCellsInOrder_003Ec__Iterator1BC)/*Error near IL_0053: stateMachine*/)._003CinteractCell_003E__0).LengthHorizontalSquared + select c) + { + Toils_JobTransforms.yieldedIngPlaceCells.Add(item); + yield return item; + } + for (int i = 0; i < 200; i++) + { + IntVec3 c2 = interactCell + GenRadial.RadialPattern[i]; + if (!Toils_JobTransforms.yieldedIngPlaceCells.Contains(c2)) + { + Building ed = c2.GetEdifice(billGiver.Map); + if (((ed == null) ? SurfaceType.Item : ((ed.def.passability != Traversability.Impassable) ? SurfaceType.Item : ed.def.surfaceType)) != 0) + { + yield return c2; + } + } + } } public static Toil SetTargetToIngredientPlaceCell(TargetIndex billGiverInd, TargetIndex carryItemInd, TargetIndex cellTargetInd) { Toil toil = new Toil(); - toil.initAction = delegate + toil.initAction = (Action)delegate() { Pawn actor = toil.actor; Job curJob = actor.jobs.curJob; Thing thing = curJob.GetTarget(carryItemInd).Thing; IBillGiver billGiver = curJob.GetTarget(billGiverInd).Thing as IBillGiver; IntVec3 c = IntVec3.Invalid; - foreach (IntVec3 current in Toils_JobTransforms.IngredientPlaceCellsInOrder(billGiver)) + foreach (IntVec3 item in Toils_JobTransforms.IngredientPlaceCellsInOrder(billGiver)) { if (!c.IsValid) { - c = current; + c = item; } bool flag = false; - List list = actor.Map.thingGrid.ThingsListAt(current); - for (int i = 0; i < list.Count; i++) + List list = actor.Map.thingGrid.ThingsListAt(item); + int num = 0; + while (num < list.Count) { - if (list[i].def.category == ThingCategory.Item && (list[i].def != thing.def || list[i].stackCount == list[i].def.stackLimit)) + if (list[num].def.category != ThingCategory.Item || (list[num].def == thing.def && list[num].stackCount != list[num].def.stackLimit)) { - flag = true; - break; + num++; + continue; } + flag = true; + break; } if (!flag) { - curJob.SetTarget(cellTargetInd, current); + curJob.SetTarget(cellTargetInd, item); return; } } @@ -96,7 +112,7 @@ public static Toil SetTargetToIngredientPlaceCell(TargetIndex billGiverInd, Targ public static Toil MoveCurrentTargetIntoQueue(TargetIndex ind) { Toil toil = new Toil(); - toil.initAction = delegate + toil.initAction = (Action)delegate() { Job curJob = toil.actor.CurJob; LocalTargetInfo target = curJob.GetTarget(ind); @@ -111,7 +127,7 @@ public static Toil MoveCurrentTargetIntoQueue(TargetIndex ind) { targetQueue.Insert(0, target); } - curJob.SetTarget(ind, null); + curJob.SetTarget(ind, (Thing)null); } }; return toil; diff --git a/Assembly-CSharp/Verse.AI/Toils_Jump.cs b/Assembly-CSharp/Verse.AI/Toils_Jump.cs index 092c8f9e3..a0637f3c3 100644 --- a/Assembly-CSharp/Verse.AI/Toils_Jump.cs +++ b/Assembly-CSharp/Verse.AI/Toils_Jump.cs @@ -8,7 +8,7 @@ public static class Toils_Jump public static Toil Jump(Toil jumpTarget) { Toil toil = new Toil(); - toil.initAction = delegate + toil.initAction = (Action)delegate() { toil.actor.jobs.curDriver.JumpToToil(jumpTarget); }; @@ -18,7 +18,7 @@ public static Toil Jump(Toil jumpTarget) public static Toil JumpIf(Toil jumpTarget, Func condition) { Toil toil = new Toil(); - toil.initAction = delegate + toil.initAction = (Action)delegate() { if (condition()) { @@ -31,13 +31,12 @@ public static Toil JumpIf(Toil jumpTarget, Func condition) public static Toil JumpIfTargetDespawnedOrNull(TargetIndex ind, Toil jumpToil) { Toil toil = new Toil(); - toil.initAction = delegate + toil.initAction = (Action)delegate() { Thing thing = toil.actor.jobs.curJob.GetTarget(ind).Thing; - if (thing == null || !thing.Spawned) - { - toil.actor.jobs.curDriver.JumpToToil(jumpToil); - } + if (thing != null && thing.Spawned) + return; + toil.actor.jobs.curDriver.JumpToToil(jumpToil); }; return toil; } @@ -45,7 +44,7 @@ public static Toil JumpIfTargetDespawnedOrNull(TargetIndex ind, Toil jumpToil) public static Toil JumpIfTargetNotHittable(TargetIndex ind, Toil jumpToil) { Toil toil = new Toil(); - toil.initAction = delegate + toil.initAction = (Action)delegate() { Pawn actor = toil.actor; Job curJob = actor.jobs.curJob; @@ -61,7 +60,7 @@ public static Toil JumpIfTargetNotHittable(TargetIndex ind, Toil jumpToil) public static Toil JumpIfTargetDownedDistant(TargetIndex ind, Toil jumpToil) { Toil toil = new Toil(); - toil.initAction = delegate + toil.initAction = (Action)delegate() { Pawn actor = toil.actor; Job curJob = actor.jobs.curJob; @@ -78,12 +77,12 @@ public static Toil JumpIfTargetDownedDistant(TargetIndex ind, Toil jumpToil) public static Toil JumpIfHaveTargetInQueue(TargetIndex ind, Toil jumpToil) { Toil toil = new Toil(); - toil.initAction = delegate + toil.initAction = (Action)delegate() { Pawn actor = toil.actor; Job curJob = actor.jobs.curJob; List targetQueue = curJob.GetTargetQueue(ind); - if (!targetQueue.NullOrEmpty()) + if (!targetQueue.NullOrEmpty()) { actor.jobs.curDriver.JumpToToil(jumpToil); } @@ -94,7 +93,7 @@ public static Toil JumpIfHaveTargetInQueue(TargetIndex ind, Toil jumpToil) public static Toil JumpIfCannotTouch(TargetIndex ind, PathEndMode peMode, Toil jumpToil) { Toil toil = new Toil(); - toil.initAction = delegate + toil.initAction = (Action)delegate() { Pawn actor = toil.actor; Job curJob = actor.jobs.curJob; diff --git a/Assembly-CSharp/Verse.AI/Toils_Recipe.cs b/Assembly-CSharp/Verse.AI/Toils_Recipe.cs index c85fb39d6..22c1b9f35 100644 --- a/Assembly-CSharp/Verse.AI/Toils_Recipe.cs +++ b/Assembly-CSharp/Verse.AI/Toils_Recipe.cs @@ -10,42 +10,37 @@ public static class Toils_Recipe public static Toil MakeUnfinishedThingIfNeeded() { Toil toil = new Toil(); - toil.initAction = delegate + toil.initAction = (Action)delegate { Pawn actor = toil.actor; Job curJob = actor.jobs.curJob; - if (!curJob.RecipeDef.UsesUnfinishedThing) + if (curJob.RecipeDef.UsesUnfinishedThing && !(curJob.GetTarget(TargetIndex.B).Thing is UnfinishedThing)) { - return; - } - if (curJob.GetTarget(TargetIndex.B).Thing is UnfinishedThing) - { - return; - } - List list = Toils_Recipe.CalculateIngredients(curJob, actor); - Thing thing = Toils_Recipe.CalculateDominantIngredient(curJob, list); - for (int i = 0; i < list.Count; i++) - { - Thing thing2 = list[i]; - actor.Map.designationManager.RemoveAllDesignationsOn(thing2, false); - if (thing2.Spawned) + List list = Toils_Recipe.CalculateIngredients(curJob, actor); + Thing thing = Toils_Recipe.CalculateDominantIngredient(curJob, list); + for (int i = 0; i < list.Count; i++) { - thing2.DeSpawn(); + Thing thing2 = list[i]; + actor.Map.designationManager.RemoveAllDesignationsOn(thing2, false); + if (thing2.Spawned) + { + thing2.DeSpawn(); + } } + ThingDef stuff = (!curJob.RecipeDef.unfinishedThingDef.MadeFromStuff) ? null : thing.def; + UnfinishedThing unfinishedThing = (UnfinishedThing)ThingMaker.MakeThing(curJob.RecipeDef.unfinishedThingDef, stuff); + unfinishedThing.Creator = actor; + unfinishedThing.BoundBill = (Bill_ProductionWithUft)curJob.bill; + unfinishedThing.ingredients = list; + CompColorable compColorable = unfinishedThing.TryGetComp(); + if (compColorable != null) + { + compColorable.Color = thing.DrawColor; + } + GenSpawn.Spawn(unfinishedThing, curJob.GetTarget(TargetIndex.A).Cell, actor.Map); + curJob.SetTarget(TargetIndex.B, (Thing)unfinishedThing); + actor.Reserve((Thing)unfinishedThing, 1, -1, null); } - ThingDef stuff = (!curJob.RecipeDef.unfinishedThingDef.MadeFromStuff) ? null : thing.def; - UnfinishedThing unfinishedThing = (UnfinishedThing)ThingMaker.MakeThing(curJob.RecipeDef.unfinishedThingDef, stuff); - unfinishedThing.Creator = actor; - unfinishedThing.BoundBill = (Bill_ProductionWithUft)curJob.bill; - unfinishedThing.ingredients = list; - CompColorable compColorable = unfinishedThing.TryGetComp(); - if (compColorable != null) - { - compColorable.Color = thing.DrawColor; - } - GenSpawn.Spawn(unfinishedThing, curJob.GetTarget(TargetIndex.A).Cell, actor.Map); - curJob.SetTarget(TargetIndex.B, unfinishedThing); - actor.Reserve(unfinishedThing, 1, -1, null); }; return toil; } @@ -53,174 +48,159 @@ public static Toil MakeUnfinishedThingIfNeeded() public static Toil DoRecipeWork() { Toil toil = new Toil(); - toil.initAction = delegate + toil.initAction = (Action)delegate { - Pawn actor = toil.actor; - Job curJob = actor.jobs.curJob; - JobDriver_DoBill jobDriver_DoBill = (JobDriver_DoBill)actor.jobs.curDriver; - UnfinishedThing unfinishedThing = curJob.GetTarget(TargetIndex.B).Thing as UnfinishedThing; - if (unfinishedThing != null && unfinishedThing.Initialized) + Pawn actor3 = toil.actor; + Job curJob3 = actor3.jobs.curJob; + JobDriver_DoBill jobDriver_DoBill2 = (JobDriver_DoBill)actor3.jobs.curDriver; + UnfinishedThing unfinishedThing3 = curJob3.GetTarget(TargetIndex.B).Thing as UnfinishedThing; + if (unfinishedThing3 != null && unfinishedThing3.Initialized) { - jobDriver_DoBill.workLeft = unfinishedThing.workLeft; + jobDriver_DoBill2.workLeft = unfinishedThing3.workLeft; } else { - jobDriver_DoBill.workLeft = curJob.bill.recipe.WorkAmountTotal((unfinishedThing == null) ? null : unfinishedThing.Stuff); - if (unfinishedThing != null) + jobDriver_DoBill2.workLeft = curJob3.bill.recipe.WorkAmountTotal((unfinishedThing3 == null) ? null : unfinishedThing3.Stuff); + if (unfinishedThing3 != null) { - unfinishedThing.workLeft = jobDriver_DoBill.workLeft; + unfinishedThing3.workLeft = jobDriver_DoBill2.workLeft; } } - jobDriver_DoBill.billStartTick = Find.TickManager.TicksGame; - jobDriver_DoBill.ticksSpentDoingRecipeWork = 0; - curJob.bill.Notify_DoBillStarted(actor); + jobDriver_DoBill2.billStartTick = Find.TickManager.TicksGame; + jobDriver_DoBill2.ticksSpentDoingRecipeWork = 0; + curJob3.bill.Notify_DoBillStarted(actor3); }; - toil.tickAction = delegate + toil.tickAction = (Action)delegate { - Pawn actor = toil.actor; - Job curJob = actor.jobs.curJob; - JobDriver_DoBill jobDriver_DoBill = (JobDriver_DoBill)actor.jobs.curDriver; - UnfinishedThing unfinishedThing = curJob.GetTarget(TargetIndex.B).Thing as UnfinishedThing; - if (unfinishedThing != null && unfinishedThing.Destroyed) + Pawn actor2 = toil.actor; + Job curJob2 = actor2.jobs.curJob; + JobDriver_DoBill jobDriver_DoBill = (JobDriver_DoBill)actor2.jobs.curDriver; + UnfinishedThing unfinishedThing2 = curJob2.GetTarget(TargetIndex.B).Thing as UnfinishedThing; + if (unfinishedThing2 != null && unfinishedThing2.Destroyed) { - actor.jobs.EndCurrentJob(JobCondition.Incompletable, true); - return; + actor2.jobs.EndCurrentJob(JobCondition.Incompletable, true); } - jobDriver_DoBill.ticksSpentDoingRecipeWork++; - curJob.bill.Notify_PawnDidWork(actor); - IBillGiverWithTickAction billGiverWithTickAction = toil.actor.CurJob.GetTarget(TargetIndex.A).Thing as IBillGiverWithTickAction; - if (billGiverWithTickAction != null) - { - billGiverWithTickAction.UsedThisTick(); - } - if (curJob.RecipeDef.workSkill != null && curJob.RecipeDef.UsesUnfinishedThing) - { - actor.skills.GetSkill(curJob.RecipeDef.workSkill).Learn(0.11f * curJob.RecipeDef.workSkillLearnFactor, false); - } - float num = (curJob.RecipeDef.workSpeedStat != null) ? actor.GetStatValue(curJob.RecipeDef.workSpeedStat, true) : 1f; - Building_WorkTable building_WorkTable = jobDriver_DoBill.BillGiver as Building_WorkTable; - if (building_WorkTable != null) - { - num *= building_WorkTable.GetStatValue(StatDefOf.WorkTableWorkSpeedFactor, true); - } - if (DebugSettings.fastCrafting) - { - num *= 30f; - } - jobDriver_DoBill.workLeft -= num; - if (unfinishedThing != null) - { - unfinishedThing.workLeft = jobDriver_DoBill.workLeft; - } - actor.GainComfortFromCellIfPossible(); - if (jobDriver_DoBill.workLeft <= 0f) - { - jobDriver_DoBill.ReadyForNextToil(); - } - if (curJob.bill.recipe.UsesUnfinishedThing) + else { - int num2 = Find.TickManager.TicksGame - jobDriver_DoBill.billStartTick; - if (num2 >= 3000 && num2 % 1000 == 0) + jobDriver_DoBill.ticksSpentDoingRecipeWork++; + curJob2.bill.Notify_PawnDidWork(actor2); + IBillGiverWithTickAction billGiverWithTickAction = toil.actor.CurJob.GetTarget(TargetIndex.A).Thing as IBillGiverWithTickAction; + if (billGiverWithTickAction != null) { - actor.jobs.CheckForJobOverride(); + billGiverWithTickAction.UsedThisTick(); + } + if (curJob2.RecipeDef.workSkill != null && curJob2.RecipeDef.UsesUnfinishedThing) + { + actor2.skills.GetSkill(curJob2.RecipeDef.workSkill).Learn((float)(0.10999999940395355 * curJob2.RecipeDef.workSkillLearnFactor), false); + } + float num = (float)((curJob2.RecipeDef.workSpeedStat != null) ? actor2.GetStatValue(curJob2.RecipeDef.workSpeedStat, true) : 1.0); + Building_WorkTable building_WorkTable = jobDriver_DoBill.BillGiver as Building_WorkTable; + if (building_WorkTable != null) + { + num *= building_WorkTable.GetStatValue(StatDefOf.WorkTableWorkSpeedFactor, true); + } + if (DebugSettings.fastCrafting) + { + num = (float)(num * 30.0); + } + jobDriver_DoBill.workLeft -= num; + if (unfinishedThing2 != null) + { + unfinishedThing2.workLeft = jobDriver_DoBill.workLeft; + } + actor2.GainComfortFromCellIfPossible(); + if (jobDriver_DoBill.workLeft <= 0.0) + { + jobDriver_DoBill.ReadyForNextToil(); + } + if (curJob2.bill.recipe.UsesUnfinishedThing) + { + int num2 = Find.TickManager.TicksGame - jobDriver_DoBill.billStartTick; + if (num2 >= 3000 && num2 % 1000 == 0) + { + actor2.jobs.CheckForJobOverride(); + } } } }; toil.defaultCompleteMode = ToilCompleteMode.Never; - toil.WithEffect(() => toil.actor.CurJob.bill.recipe.effectWorking, TargetIndex.A); - toil.PlaySustainerOrSound(() => toil.actor.CurJob.bill.recipe.soundWorking); - toil.WithProgressBar(TargetIndex.A, delegate + toil.WithEffect((Func)(() => toil.actor.CurJob.bill.recipe.effectWorking), TargetIndex.A); + toil.PlaySustainerOrSound((Func)(() => toil.actor.CurJob.bill.recipe.soundWorking)); + toil.WithProgressBar(TargetIndex.A, (Func)delegate { Pawn actor = toil.actor; Job curJob = actor.CurJob; UnfinishedThing unfinishedThing = curJob.GetTarget(TargetIndex.B).Thing as UnfinishedThing; - return 1f - ((JobDriver_DoBill)actor.jobs.curDriver).workLeft / curJob.bill.recipe.WorkAmountTotal((unfinishedThing == null) ? null : unfinishedThing.Stuff); + return (float)(1.0 - ((JobDriver_DoBill)actor.jobs.curDriver).workLeft / curJob.bill.recipe.WorkAmountTotal((unfinishedThing == null) ? null : unfinishedThing.Stuff)); }, false, -0.5f); - toil.FailOn(() => toil.actor.CurJob.bill.suspended); + toil.FailOn((Func)(() => toil.actor.CurJob.bill.suspended)); return toil; } public static Toil FinishRecipeAndStartStoringProduct() { Toil toil = new Toil(); - toil.initAction = delegate + toil.initAction = (Action)delegate { Pawn actor = toil.actor; Job curJob = actor.jobs.curJob; JobDriver_DoBill jobDriver_DoBill = (JobDriver_DoBill)actor.jobs.curDriver; if (curJob.RecipeDef.workSkill != null && !curJob.RecipeDef.UsesUnfinishedThing) { - float xp = (float)jobDriver_DoBill.ticksSpentDoingRecipeWork * 0.11f * curJob.RecipeDef.workSkillLearnFactor; + float xp = (float)((float)jobDriver_DoBill.ticksSpentDoingRecipeWork * 0.10999999940395355 * curJob.RecipeDef.workSkillLearnFactor); actor.skills.GetSkill(curJob.RecipeDef.workSkill).Learn(xp, false); } List ingredients = Toils_Recipe.CalculateIngredients(curJob, actor); Thing dominantIngredient = Toils_Recipe.CalculateDominantIngredient(curJob, ingredients); - List list = GenRecipe.MakeRecipeProducts(curJob.RecipeDef, actor, ingredients, dominantIngredient).ToList(); + List list = GenRecipe.MakeRecipeProducts(curJob.RecipeDef, actor, ingredients, dominantIngredient).ToList(); Toils_Recipe.ConsumeIngredients(ingredients, curJob.RecipeDef, actor.Map); curJob.bill.Notify_IterationCompleted(actor, ingredients); RecordsUtility.Notify_BillDone(actor, list); if (list.Count == 0) { actor.jobs.EndCurrentJob(JobCondition.Succeeded, true); - return; } - if (curJob.bill.GetStoreMode() == BillStoreModeDefOf.DropOnFloor) + else if (curJob.bill.GetStoreMode() == BillStoreModeDefOf.DropOnFloor) { for (int i = 0; i < list.Count; i++) { if (!GenPlace.TryPlaceThing(list[i], actor.Position, actor.Map, ThingPlaceMode.Near, null)) { - Log.Error(string.Concat(new object[] - { - actor, - " could not drop recipe product ", - list[i], - " near ", - actor.Position - })); + Log.Error(actor + " could not drop recipe product " + list[i] + " near " + actor.Position); } } actor.jobs.EndCurrentJob(JobCondition.Succeeded, true); - return; } - if (list.Count > 1) + else { - for (int j = 1; j < list.Count; j++) + if (list.Count > 1) { - if (!GenPlace.TryPlaceThing(list[j], actor.Position, actor.Map, ThingPlaceMode.Near, null)) + for (int j = 1; j < list.Count; j++) { - Log.Error(string.Concat(new object[] + if (!GenPlace.TryPlaceThing(list[j], actor.Position, actor.Map, ThingPlaceMode.Near, null)) { - actor, - " could not drop recipe product ", - list[j], - " near ", - actor.Position - })); + Log.Error(actor + " could not drop recipe product " + list[j] + " near " + actor.Position); + } } } - } - list[0].SetPositionDirect(actor.Position); - IntVec3 c; - if (StoreUtility.TryFindBestBetterStoreCellFor(list[0], actor, actor.Map, StoragePriority.Unstored, actor.Faction, out c, true)) - { - actor.carryTracker.TryStartCarry(list[0]); - curJob.targetB = c; - curJob.targetA = list[0]; - curJob.count = 99999; - return; - } - if (!GenPlace.TryPlaceThing(list[0], actor.Position, actor.Map, ThingPlaceMode.Near, null)) - { - Log.Error(string.Concat(new object[] + list[0].SetPositionDirect(actor.Position); + IntVec3 c = default(IntVec3); + if (StoreUtility.TryFindBestBetterStoreCellFor(list[0], actor, actor.Map, StoragePriority.Unstored, actor.Faction, out c, true)) + { + actor.carryTracker.TryStartCarry(list[0]); + curJob.targetB = c; + curJob.targetA = list[0]; + curJob.count = 99999; + } + else { - "Bill doer could not drop product ", - list[0], - " near ", - actor.Position - })); + if (!GenPlace.TryPlaceThing(list[0], actor.Position, actor.Map, ThingPlaceMode.Near, null)) + { + Log.Error("Bill doer could not drop product " + list[0] + " near " + actor.Position); + } + actor.jobs.EndCurrentJob(JobCondition.Succeeded, true); + } } - actor.jobs.EndCurrentJob(JobCondition.Succeeded, true); }; return toil; } @@ -242,27 +222,11 @@ private static List CalculateIngredients(Job job, Pawn actor) { if (job.placedThings[i].Count <= 0) { - Log.Error(string.Concat(new object[] - { - "PlacedThing ", - job.placedThings[i], - " with count ", - job.placedThings[i].Count, - " for job ", - job - })); + Log.Error("PlacedThing " + job.placedThings[i] + " with count " + job.placedThings[i].Count + " for job " + job); } else { - Thing thing; - if (job.placedThings[i].Count < job.placedThings[i].thing.stackCount) - { - thing = job.placedThings[i].thing.SplitOff(job.placedThings[i].Count); - } - else - { - thing = job.placedThings[i].thing; - } + Thing thing = (job.placedThings[i].Count >= job.placedThings[i].thing.stackCount) ? job.placedThings[i].thing : job.placedThings[i].thing.SplitOff(job.placedThings[i].Count); job.placedThings[i].Count = 0; if (list.Contains(thing)) { @@ -289,23 +253,23 @@ private static Thing CalculateDominantIngredient(Job job, List ingredient UnfinishedThing uft = job.GetTarget(TargetIndex.B).Thing as UnfinishedThing; if (uft != null && uft.def.MadeFromStuff) { - return uft.ingredients.First((Thing ing) => ing.def == uft.Stuff); - } - if (ingredients.NullOrEmpty()) - { - return null; - } - if (job.RecipeDef.productHasIngredientStuff) - { - return ingredients[0]; + return uft.ingredients.First((Func)((Thing ing) => ing.def == uft.Stuff)); } - if (job.RecipeDef.products.Any((ThingCountClass x) => x.thingDef.MadeFromStuff)) + if (!ingredients.NullOrEmpty()) { - return (from x in ingredients - where x.def.IsStuff - select x).RandomElementByWeight((Thing x) => (float)x.stackCount); + if (job.RecipeDef.productHasIngredientStuff) + { + return ingredients[0]; + } + if (job.RecipeDef.products.Any((Predicate)((ThingCountClass x) => x.thingDef.MadeFromStuff))) + { + return (from x in ingredients + where x.def.IsStuff + select x).RandomElementByWeight((Func)((Thing x) => (float)x.stackCount)); + } + return ingredients.RandomElementByWeight((Func)((Thing x) => (float)x.stackCount)); } - return ingredients.RandomElementByWeight((Thing x) => (float)x.stackCount); + return null; } private static void ConsumeIngredients(List ingredients, RecipeDef recipe, Map map) diff --git a/Assembly-CSharp/Verse.AI/Toils_Reserve.cs b/Assembly-CSharp/Verse.AI/Toils_Reserve.cs index 809812123..f3c0b2a44 100644 --- a/Assembly-CSharp/Verse.AI/Toils_Reserve.cs +++ b/Assembly-CSharp/Verse.AI/Toils_Reserve.cs @@ -8,7 +8,7 @@ public static class Toils_Reserve public static Toil Reserve(TargetIndex ind, int maxPawns = 1, int stackCount = -1, ReservationLayerDef layer = null) { Toil toil = new Toil(); - toil.initAction = delegate + toil.initAction = (Action)delegate() { if (!toil.actor.Reserve(toil.actor.jobs.curJob.GetTarget(ind), maxPawns, stackCount, layer)) { @@ -23,7 +23,7 @@ public static Toil Reserve(TargetIndex ind, int maxPawns = 1, int stackCount = - public static Toil ReserveQueue(TargetIndex ind, int maxPawns = 1, int stackCount = -1, ReservationLayerDef layer = null) { Toil toil = new Toil(); - toil.initAction = delegate + toil.initAction = (Action)delegate() { List targetQueue = toil.actor.jobs.curJob.GetTargetQueue(ind); if (targetQueue != null) @@ -45,7 +45,7 @@ public static Toil ReserveQueue(TargetIndex ind, int maxPawns = 1, int stackCoun public static Toil Release(TargetIndex ind) { Toil toil = new Toil(); - toil.initAction = delegate + toil.initAction = (Action)delegate() { toil.actor.Map.reservationManager.Release(toil.actor.jobs.curJob.GetTarget(ind), toil.actor); }; diff --git a/Assembly-CSharp/Verse.AI/Toils_ReserveAttackTarget.cs b/Assembly-CSharp/Verse.AI/Toils_ReserveAttackTarget.cs index 7f8f288b5..d1ced8f72 100644 --- a/Assembly-CSharp/Verse.AI/Toils_ReserveAttackTarget.cs +++ b/Assembly-CSharp/Verse.AI/Toils_ReserveAttackTarget.cs @@ -7,7 +7,7 @@ public static class Toils_ReserveAttackTarget public static Toil TryReserve(TargetIndex ind) { Toil toil = new Toil(); - toil.initAction = delegate + toil.initAction = (Action)delegate() { Pawn actor = toil.actor; IAttackTarget attackTarget = actor.CurJob.GetTarget(ind).Thing as IAttackTarget; diff --git a/Assembly-CSharp/Verse.AI/TouchPathEndModeUtility.cs b/Assembly-CSharp/Verse.AI/TouchPathEndModeUtility.cs index 99f3b5958..69a9194c4 100644 --- a/Assembly-CSharp/Verse.AI/TouchPathEndModeUtility.cs +++ b/Assembly-CSharp/Verse.AI/TouchPathEndModeUtility.cs @@ -1,4 +1,3 @@ -using System; using System.Collections.Generic; namespace Verse.AI @@ -14,26 +13,54 @@ public static bool IsCornerTouchAllowed(int cornerX, int cornerZ, int adjCardina } IntVec3 intVec = new IntVec3(adjCardinal1X, 0, adjCardinal1Z); IntVec3 intVec2 = new IntVec3(adjCardinal2X, 0, adjCardinal2Z); - return (map.pathGrid.Walkable(intVec) && intVec.GetDoor(map) == null) || (map.pathGrid.Walkable(intVec2) && intVec2.GetDoor(map) == null); + if (map.pathGrid.Walkable(intVec) && intVec.GetDoor(map) == null) + { + goto IL_0081; + } + if (map.pathGrid.Walkable(intVec2) && intVec2.GetDoor(map) == null) + goto IL_0081; + return false; + IL_0081: + return true; } public static bool MakesOccupiedCellsAlwaysReachableDiagonally(ThingDef def) { ThingDef thingDef = (!def.IsFrame) ? def : (def.entityDefToBuild as ThingDef); - return thingDef != null && thingDef.category == ThingCategory.Building && thingDef.holdsRoof && !thingDef.building.isNaturalRock; + if (thingDef != null && thingDef.category == ThingCategory.Building && thingDef.holdsRoof && !thingDef.building.isNaturalRock) + { + return true; + } + return false; } public static bool IsAdjacentCornerAndNotAllowed(IntVec3 cell, IntVec3 BL, IntVec3 TL, IntVec3 TR, IntVec3 BR, Map map) { - return (cell == BL && !TouchPathEndModeUtility.IsCornerTouchAllowed(BL.x + 1, BL.z + 1, BL.x + 1, BL.z, BL.x, BL.z + 1, map)) || (cell == TL && !TouchPathEndModeUtility.IsCornerTouchAllowed(TL.x + 1, TL.z - 1, TL.x + 1, TL.z, TL.x, TL.z - 1, map)) || (cell == TR && !TouchPathEndModeUtility.IsCornerTouchAllowed(TR.x - 1, TR.z - 1, TR.x - 1, TR.z, TR.x, TR.z - 1, map)) || (cell == BR && !TouchPathEndModeUtility.IsCornerTouchAllowed(BR.x - 1, BR.z + 1, BR.x - 1, BR.z, BR.x, BR.z + 1, map)); + if (cell == BL && !TouchPathEndModeUtility.IsCornerTouchAllowed(BL.x + 1, BL.z + 1, BL.x + 1, BL.z, BL.x, BL.z + 1, map)) + { + return true; + } + if (cell == TL && !TouchPathEndModeUtility.IsCornerTouchAllowed(TL.x + 1, TL.z - 1, TL.x + 1, TL.z, TL.x, TL.z - 1, map)) + { + return true; + } + if (cell == TR && !TouchPathEndModeUtility.IsCornerTouchAllowed(TR.x - 1, TR.z - 1, TR.x - 1, TR.z, TR.x, TR.z - 1, map)) + { + return true; + } + if (cell == BR && !TouchPathEndModeUtility.IsCornerTouchAllowed(BR.x - 1, BR.z + 1, BR.x - 1, BR.z, BR.x, BR.z + 1, map)) + { + return true; + } + return false; } public static void AddAllowedAdjacentRegions(LocalTargetInfo dest, TraverseParms traverseParams, Map map, List regions) { - IntVec3 bL; - IntVec3 tL; - IntVec3 tR; - IntVec3 bR; + IntVec3 bL = default(IntVec3); + IntVec3 tL = default(IntVec3); + IntVec3 tR = default(IntVec3); + IntVec3 bR = default(IntVec3); GenAdj.GetAdjacentCorners(dest, out bL, out tL, out tR, out bR); if (!dest.HasThing || (dest.Thing.def.size.x == 1 && dest.Thing.def.size.z == 1)) { @@ -70,10 +97,10 @@ public static void AddAllowedAdjacentRegions(LocalTargetInfo dest, TraverseParms public static bool IsAdjacentOrInsideAndAllowedToTouch(IntVec3 root, LocalTargetInfo target, Map map) { - IntVec3 bL; - IntVec3 tL; - IntVec3 tR; - IntVec3 bR; + IntVec3 bL = default(IntVec3); + IntVec3 tL = default(IntVec3); + IntVec3 tR = default(IntVec3); + IntVec3 bR = default(IntVec3); GenAdj.GetAdjacentCorners(target, out bL, out tL, out tR, out bR); return root.AdjacentTo8WayOrInside(target) && !TouchPathEndModeUtility.IsAdjacentCornerAndNotAllowed(root, bL, tL, tR, bR, map); } diff --git a/Assembly-CSharp/Verse.AI/WanderRoomUtility.cs b/Assembly-CSharp/Verse.AI/WanderRoomUtility.cs index 41bb702f6..e89d2a983 100644 --- a/Assembly-CSharp/Verse.AI/WanderRoomUtility.cs +++ b/Assembly-CSharp/Verse.AI/WanderRoomUtility.cs @@ -1,5 +1,3 @@ -using System; - namespace Verse.AI { public static class WanderRoomUtility @@ -7,7 +5,11 @@ public static class WanderRoomUtility public static bool IsValidWanderDest(Pawn pawn, IntVec3 loc, IntVec3 root) { Room room = root.GetRoom(pawn.Map, RegionType.Set_Passable); - return room == null || room.RegionType == RegionType.Portal || WanderUtility.InSameRoom(root, loc, pawn.Map); + if (room != null && room.RegionType != RegionType.Portal) + { + return WanderUtility.InSameRoom(root, loc, pawn.Map); + } + return true; } } } diff --git a/Assembly-CSharp/Verse.AI/WanderUtility.cs b/Assembly-CSharp/Verse.AI/WanderUtility.cs index 26a25a5ad..1290949cf 100644 --- a/Assembly-CSharp/Verse.AI/WanderUtility.cs +++ b/Assembly-CSharp/Verse.AI/WanderUtility.cs @@ -1,5 +1,3 @@ -using System; - namespace Verse.AI { public static class WanderUtility @@ -8,15 +6,7 @@ public static IntVec3 BestCloseWanderRoot(IntVec3 trueWanderRoot, Pawn pawn) { for (int i = 0; i < 50; i++) { - IntVec3 intVec; - if (i < 8) - { - intVec = trueWanderRoot + GenRadial.RadialPattern[i]; - } - else - { - intVec = trueWanderRoot + GenRadial.RadialPattern[i - 8 + 1] * 7; - } + IntVec3 intVec = (i >= 8) ? (trueWanderRoot + GenRadial.RadialPattern[i - 8 + 1] * 7) : (trueWanderRoot + GenRadial.RadialPattern[i]); if (intVec.InBounds(pawn.Map) && intVec.Walkable(pawn.Map) && pawn.CanReach(intVec, PathEndMode.OnCell, Danger.Some, false, TraverseMode.ByPawn)) { return intVec; @@ -28,7 +18,11 @@ public static IntVec3 BestCloseWanderRoot(IntVec3 trueWanderRoot, Pawn pawn) public static bool InSameRoom(IntVec3 locA, IntVec3 locB, Map map) { Room room = locA.GetRoom(map, RegionType.Set_All); - return room == null || room == locB.GetRoom(map, RegionType.Set_All); + if (room == null) + { + return true; + } + return room == locB.GetRoom(map, RegionType.Set_All); } } } diff --git a/Assembly-CSharp/Verse.Grammar/GrammarResolver.cs b/Assembly-CSharp/Verse.Grammar/GrammarResolver.cs index 3ff0cbbaf..08a64b398 100644 --- a/Assembly-CSharp/Verse.Grammar/GrammarResolver.cs +++ b/Assembly-CSharp/Verse.Grammar/GrammarResolver.cs @@ -20,7 +20,7 @@ public float SelectionWeight { get { - return this.rule.BaseSelectionWeight * 100000f / (float)((this.uses + 1) * 1000); + return (float)(this.rule.BaseSelectionWeight * 100000.0 / (float)((this.uses + 1) * 1000)); } } @@ -45,13 +45,13 @@ public override string ToString() private const int LoopsLimit = 100; - private static List rules = new List(); + private static List rules = new List(); private static int loopCount; private static StringBuilder logSb; - private static List matchingRules = new List(); + private static List matchingRules = new List(); private static bool LogOn { @@ -66,11 +66,11 @@ public static string Resolve(string rootKeyword, List rawRules, string deb GrammarResolver.rules.Clear(); for (int i = 0; i < rawRules.Count; i++) { - GrammarResolver.rules.Add(new GrammarResolver.RuleEntry(rawRules[i])); + GrammarResolver.rules.Add(new RuleEntry(rawRules[i])); } for (int j = 0; j < RulePackDefOf.GlobalUtility.Rules.Count; j++) { - GrammarResolver.rules.Add(new GrammarResolver.RuleEntry(RulePackDefOf.GlobalUtility.Rules[j])); + GrammarResolver.rules.Add(new RuleEntry(RulePackDefOf.GlobalUtility.Rules[j])); } GrammarResolver.loopCount = 0; if (GrammarResolver.LogOn) @@ -79,11 +79,11 @@ public static string Resolve(string rootKeyword, List rawRules, string deb } string text = "err"; bool flag = false; - foreach (GrammarResolver.RuleEntry current in (from r in GrammarResolver.rules + foreach (RuleEntry item in (from r in GrammarResolver.rules where r.rule.keyword == rootKeyword select r).InRandomOrder(null)) { - if (GrammarResolver.TryResolveRecursive(current, 0, out text)) + if (GrammarResolver.TryResolveRecursive(item, 0, out text)) { flag = true; break; @@ -109,13 +109,13 @@ public static string Resolve(string rootKeyword, List rawRules, string deb return text; } - private static bool TryResolveRecursive(GrammarResolver.RuleEntry entry, int depth, out string output) + private static bool TryResolveRecursive(RuleEntry entry, int depth, out string output) { if (GrammarResolver.LogOn) { GrammarResolver.logSb.AppendLine(); GrammarResolver.logSb.Append(depth.ToStringCached() + " "); - for (int i = 0; i < depth; i++) + for (int num = 0; num < depth; num++) { GrammarResolver.logSb.Append(" "); } @@ -144,17 +144,18 @@ private static bool TryResolveRecursive(GrammarResolver.RuleEntry entry, int dep } string text = entry.rule.Generate(); bool flag = false; - int num = -1; - for (int j = 0; j < text.Length; j++) + int num2 = -1; + for (int i = 0; i < text.Length; i++) { - char c = text[j]; + char c = text[i]; if (c == '[') { - num = j; + num2 = i; } + string str = default(string); if (c == ']') { - if (num == -1) + if (num2 == -1) { Log.Error("Could not resolve rule " + text + ": mismatched brackets."); output = "MISMATCHED_BRACKETS"; @@ -166,21 +167,19 @@ private static bool TryResolveRecursive(GrammarResolver.RuleEntry entry, int dep } else { - string text2 = text.Substring(num + 1, j - num - 1); - string str; + string text2 = text.Substring(num2 + 1, i - num2 - 1); while (true) { - GrammarResolver.RuleEntry ruleEntry = GrammarResolver.RandomPossiblyResolvableEntry(text2); - if (ruleEntry == null) + RuleEntry ruleEntry = GrammarResolver.RandomPossiblyResolvableEntry(text2); + if (ruleEntry != null) { - break; + ruleEntry.uses++; + if (GrammarResolver.TryResolveRecursive(ruleEntry, depth + 1, out str)) + goto IL_01f0; + ruleEntry.MarkKnownUnresolvable(); + continue; } - ruleEntry.uses++; - if (GrammarResolver.TryResolveRecursive(ruleEntry, depth + 1, out str)) - { - goto Block_13; - } - ruleEntry.MarkKnownUnresolvable(); + break; } entry.MarkKnownUnresolvable(); output = "CANNOT_RESOLVE_SUBKEYWORD:" + text2; @@ -189,19 +188,18 @@ private static bool TryResolveRecursive(GrammarResolver.RuleEntry entry, int dep GrammarResolver.logSb.Append("UNRESOLVABLE: Cannot resolve sub-keyword '" + text2 + "'"); } flag = true; - goto IL_21E; - Block_13: - text = text.Substring(0, num) + str + text.Substring(j + 1); - j = num; } } - IL_21E:; + continue; + IL_01f0: + text = text.Substring(0, num2) + str + text.Substring(i + 1); + i = num2; } output = text; return !flag; } - private static GrammarResolver.RuleEntry RandomPossiblyResolvableEntry(string keyword) + private static RuleEntry RandomPossiblyResolvableEntry(string keyword) { GrammarResolver.matchingRules.Clear(); for (int i = 0; i < GrammarResolver.rules.Count; i++) @@ -215,7 +213,7 @@ private static GrammarResolver.RuleEntry RandomPossiblyResolvableEntry(string ke { return null; } - return GrammarResolver.matchingRules.RandomElementByWeight((GrammarResolver.RuleEntry r) => r.SelectionWeight); + return GrammarResolver.matchingRules.RandomElementByWeight((Func)((RuleEntry r) => r.SelectionWeight)); } } } diff --git a/Assembly-CSharp/Verse.Grammar/GrammarUtility.cs b/Assembly-CSharp/Verse.Grammar/GrammarUtility.cs index 47a8ed877..7c812615c 100644 --- a/Assembly-CSharp/Verse.Grammar/GrammarUtility.cs +++ b/Assembly-CSharp/Verse.Grammar/GrammarUtility.cs @@ -1,29 +1,29 @@ using RimWorld; -using System; using System.Collections.Generic; -using System.Diagnostics; namespace Verse.Grammar { public static class GrammarUtility { - [DebuggerHidden] public static IEnumerable RulesForPawn(string prefix, Name name, PawnKindDef kind, Gender gender, Faction faction = null) { - GrammarUtility.c__Iterator1EC c__Iterator1EC = new GrammarUtility.c__Iterator1EC(); - c__Iterator1EC.name = name; - c__Iterator1EC.kind = kind; - c__Iterator1EC.prefix = prefix; - c__Iterator1EC.faction = faction; - c__Iterator1EC.gender = gender; - c__Iterator1EC.<$>name = name; - c__Iterator1EC.<$>kind = kind; - c__Iterator1EC.<$>prefix = prefix; - c__Iterator1EC.<$>faction = faction; - c__Iterator1EC.<$>gender = gender; - GrammarUtility.c__Iterator1EC expr_4F = c__Iterator1EC; - expr_4F.$PC = -2; - return expr_4F; + string nameFull = (name == null) ? Find.ActiveLanguageWorker.WithIndefiniteArticle(kind.label) : name.ToStringFull; + yield return (Rule)new Rule_String(prefix + "_nameFull", nameFull); + string nameShort = (name == null) ? kind.label : name.ToStringShort; + yield return (Rule)new Rule_String(prefix + "_nameShort", nameShort); + string nameShortIndef = (name == null) ? Find.ActiveLanguageWorker.WithIndefiniteArticle(kind.label) : name.ToStringShort; + yield return (Rule)new Rule_String(prefix + "_nameShortIndef", nameShortIndef); + yield return (Rule)new Rule_String(prefix + "_nameShortIndefinite", nameShortIndef); + string nameShortDef = (name == null) ? Find.ActiveLanguageWorker.WithDefiniteArticle(kind.label) : name.ToStringShort; + yield return (Rule)new Rule_String(prefix + "_nameShortDef", nameShortDef); + yield return (Rule)new Rule_String(prefix + "_nameShortDefinite", nameShortDef); + if (faction != null) + { + yield return (Rule)new Rule_String(prefix + "_factionName", faction.Name); + } + yield return (Rule)new Rule_String(prefix + "_pronoun", gender.GetPronoun()); + yield return (Rule)new Rule_String(prefix + "_possessive", gender.GetPossessive()); + yield return (Rule)new Rule_String(prefix + "_objective", gender.GetObjective()); } } } diff --git a/Assembly-CSharp/Verse.Grammar/Rule.cs b/Assembly-CSharp/Verse.Grammar/Rule.cs index dfb2f361b..71da4546b 100644 --- a/Assembly-CSharp/Verse.Grammar/Rule.cs +++ b/Assembly-CSharp/Verse.Grammar/Rule.cs @@ -1,5 +1,3 @@ -using System; - namespace Verse.Grammar { public abstract class Rule diff --git a/Assembly-CSharp/Verse.Grammar/Rule_File.cs b/Assembly-CSharp/Verse.Grammar/Rule_File.cs index 341a8f6ea..09d390e92 100644 --- a/Assembly-CSharp/Verse.Grammar/Rule_File.cs +++ b/Assembly-CSharp/Verse.Grammar/Rule_File.cs @@ -21,7 +21,7 @@ public override float BaseSelectionWeight public override string Generate() { - return this.cachedStrings.RandomElement(); + return this.cachedStrings.RandomElement(); } public override void Init() @@ -30,20 +30,38 @@ public override void Init() { this.LoadStringsFromFile(this.path); } - foreach (string current in this.pathList) + List.Enumerator enumerator = this.pathList.GetEnumerator(); + try { - this.LoadStringsFromFile(current); + while (enumerator.MoveNext()) + { + string current = enumerator.Current; + this.LoadStringsFromFile(current); + } + } + finally + { + ((IDisposable)(object)enumerator).Dispose(); } } private void LoadStringsFromFile(string filePath) { - List list; + List list = default(List); if (Translator.TryGetTranslatedStringsForFile(filePath, out list)) { - foreach (string current in list) + List.Enumerator enumerator = list.GetEnumerator(); + try { - this.cachedStrings.Add(current); + while (enumerator.MoveNext()) + { + string current = enumerator.Current; + this.cachedStrings.Add(current); + } + } + finally + { + ((IDisposable)(object)enumerator).Dispose(); } } } @@ -52,29 +70,13 @@ public override string ToString() { if (!this.path.NullOrEmpty()) { - return string.Concat(new object[] - { - this.keyword, - "->(", - this.cachedStrings.Count, - " strings from file: ", - this.path, - ")" - }); + return base.keyword + "->(" + this.cachedStrings.Count + " strings from file: " + this.path + ")"; } if (this.pathList.Count > 0) { - return string.Concat(new object[] - { - this.keyword, - "->(", - this.cachedStrings.Count, - " strings from ", - this.pathList.Count, - " files)" - }); + return base.keyword + "->(" + this.cachedStrings.Count + " strings from " + this.pathList.Count + " files)"; } - return this.keyword + "->(Rule_File with no configuration)"; + return base.keyword + "->(Rule_File with no configuration)"; } } } diff --git a/Assembly-CSharp/Verse.Grammar/Rule_List.cs b/Assembly-CSharp/Verse.Grammar/Rule_List.cs index 201b05767..0c590a4f4 100644 --- a/Assembly-CSharp/Verse.Grammar/Rule_List.cs +++ b/Assembly-CSharp/Verse.Grammar/Rule_List.cs @@ -1,4 +1,3 @@ -using System; using System.Collections.Generic; namespace Verse.Grammar @@ -17,12 +16,12 @@ public override float BaseSelectionWeight public override string Generate() { - return this.strings.RandomElement(); + return this.strings.RandomElement(); } public override string ToString() { - return this.keyword + "->(list: " + this.strings[0] + " etc)"; + return base.keyword + "->(list: " + this.strings[0] + " etc)"; } } } diff --git a/Assembly-CSharp/Verse.Grammar/Rule_Number.cs b/Assembly-CSharp/Verse.Grammar/Rule_Number.cs index 3e918ed5c..b897194dc 100644 --- a/Assembly-CSharp/Verse.Grammar/Rule_Number.cs +++ b/Assembly-CSharp/Verse.Grammar/Rule_Number.cs @@ -1,5 +1,3 @@ -using System; - namespace Verse.Grammar { public class Rule_Number : Rule @@ -23,7 +21,7 @@ public override string Generate() public override string ToString() { - return this.keyword + "->(number: " + this.range.ToString() + ")"; + return base.keyword + "->(number: " + this.range.ToString() + ")"; } } } diff --git a/Assembly-CSharp/Verse.Grammar/Rule_PersonName.cs b/Assembly-CSharp/Verse.Grammar/Rule_PersonName.cs index 1a41e04df..fa7b7e441 100644 --- a/Assembly-CSharp/Verse.Grammar/Rule_PersonName.cs +++ b/Assembly-CSharp/Verse.Grammar/Rule_PersonName.cs @@ -1,5 +1,4 @@ using RimWorld; -using System; namespace Verse.Grammar { @@ -23,14 +22,14 @@ public override string Generate() Gender gender = this.gender; if (gender == Gender.None) { - gender = ((Rand.Value >= 0.5f) ? Gender.Female : Gender.Male); + gender = (Gender)((Rand.Value < 0.5) ? 1 : 2); } return nameBank.GetName(PawnNameSlot.First, gender); } public override string ToString() { - return this.keyword + "->(personname)"; + return base.keyword + "->(personname)"; } } } diff --git a/Assembly-CSharp/Verse.Grammar/Rule_String.cs b/Assembly-CSharp/Verse.Grammar/Rule_String.cs index 0d8449187..8b36dcfa9 100644 --- a/Assembly-CSharp/Verse.Grammar/Rule_String.cs +++ b/Assembly-CSharp/Verse.Grammar/Rule_String.cs @@ -16,17 +16,17 @@ public override float BaseSelectionWeight public Rule_String(string keyword, string output) { - this.keyword = keyword; + base.keyword = keyword; this.output = output; } public Rule_String(string rawString) { - string[] array = rawString.Split(new string[] + string[] array = rawString.Split(new string[1] { "->" }, StringSplitOptions.None); - this.keyword = array[0].Trim(); + base.keyword = array[0].Trim(); this.output = array[1].Trim(); } @@ -37,7 +37,7 @@ public override string Generate() public override string ToString() { - return this.keyword + "->" + this.output; + return base.keyword + "->" + this.output; } } } diff --git a/Assembly-CSharp/Verse.Noise/Abs.cs b/Assembly-CSharp/Verse.Noise/Abs.cs index 1711c0c7b..c7ef531ee 100644 --- a/Assembly-CSharp/Verse.Noise/Abs.cs +++ b/Assembly-CSharp/Verse.Noise/Abs.cs @@ -10,12 +10,12 @@ public Abs() : base(1) public Abs(ModuleBase input) : base(1) { - this.modules[0] = input; + base.modules[0] = input; } public override double GetValue(double x, double y, double z) { - return Math.Abs(this.modules[0].GetValue(x, y, z)); + return Math.Abs(base.modules[0].GetValue(x, y, z)); } } } diff --git a/Assembly-CSharp/Verse.Noise/AbsLatitudeCurve.cs b/Assembly-CSharp/Verse.Noise/AbsLatitudeCurve.cs index 2b979c7be..e503dd9e5 100644 --- a/Assembly-CSharp/Verse.Noise/AbsLatitudeCurve.cs +++ b/Assembly-CSharp/Verse.Noise/AbsLatitudeCurve.cs @@ -1,4 +1,3 @@ -using System; using UnityEngine; namespace Verse.Noise @@ -21,7 +20,7 @@ public AbsLatitudeCurve(SimpleCurve curve, float planetRadius) : base(0) public override double GetValue(double x, double y, double z) { - float f = Mathf.Asin((float)(y / (double)this.planetRadius)) * 57.29578f; + float f = (float)(Mathf.Asin((float)(y / (double)this.planetRadius)) * 57.295780181884766); return (double)this.curve.Evaluate(Mathf.Abs(f)); } } diff --git a/Assembly-CSharp/Verse.Noise/Add.cs b/Assembly-CSharp/Verse.Noise/Add.cs index 1ae4f8ec1..454e2c7d8 100644 --- a/Assembly-CSharp/Verse.Noise/Add.cs +++ b/Assembly-CSharp/Verse.Noise/Add.cs @@ -1,5 +1,3 @@ -using System; - namespace Verse.Noise { public class Add : ModuleBase @@ -10,13 +8,13 @@ public Add() : base(2) public Add(ModuleBase lhs, ModuleBase rhs) : base(2) { - this.modules[0] = lhs; - this.modules[1] = rhs; + base.modules[0] = lhs; + base.modules[1] = rhs; } public override double GetValue(double x, double y, double z) { - return this.modules[0].GetValue(x, y, z) + this.modules[1].GetValue(x, y, z); + return base.modules[0].GetValue(x, y, z) + base.modules[1].GetValue(x, y, z); } } } diff --git a/Assembly-CSharp/Verse.Noise/Arbitrary.cs b/Assembly-CSharp/Verse.Noise/Arbitrary.cs index 90f7ecd9c..bc946c49a 100644 --- a/Assembly-CSharp/Verse.Noise/Arbitrary.cs +++ b/Assembly-CSharp/Verse.Noise/Arbitrary.cs @@ -12,13 +12,13 @@ public Arbitrary() : base(1) public Arbitrary(ModuleBase source, Func processor) : base(1) { - this.modules[0] = source; + base.modules[0] = source; this.processor = processor; } public override double GetValue(double x, double y, double z) { - return this.processor(this.modules[0].GetValue(x, y, z)); + return this.processor(base.modules[0].GetValue(x, y, z)); } } } diff --git a/Assembly-CSharp/Verse.Noise/Bend.cs b/Assembly-CSharp/Verse.Noise/Bend.cs index bad5c28ae..407860ce1 100644 --- a/Assembly-CSharp/Verse.Noise/Bend.cs +++ b/Assembly-CSharp/Verse.Noise/Bend.cs @@ -1,5 +1,3 @@ -using System; - namespace Verse.Noise { public class Bend : ModuleBase @@ -10,12 +8,12 @@ public Bend() : base(1) public Bend(float angle, float radius, ModuleBase input) : base(1) { - this.modules[0] = input; + base.modules[0] = input; } public override double GetValue(double x, double y, double z) { - return this.modules[0].GetValue(x, y, z); + return base.modules[0].GetValue(x, y, z); } } } diff --git a/Assembly-CSharp/Verse.Noise/Billow.cs b/Assembly-CSharp/Verse.Noise/Billow.cs index ab999843c..ecf15614c 100644 --- a/Assembly-CSharp/Verse.Noise/Billow.cs +++ b/Assembly-CSharp/Verse.Noise/Billow.cs @@ -106,7 +106,8 @@ public Billow(double frequency, double lacunarity, double persistence, int octav public override double GetValue(double x, double y, double z) { double num = 0.0; - double num2 = 1.0; + double num2 = 0.0; + double num3 = 1.0; x *= this.m_frequency; y *= this.m_frequency; z *= this.m_frequency; @@ -115,14 +116,14 @@ public override double GetValue(double x, double y, double z) double x2 = Utils.MakeInt32Range(x); double y2 = Utils.MakeInt32Range(y); double z2 = Utils.MakeInt32Range(z); - long seed = (long)(this.m_seed + i) & (long)((ulong)-1); - double num3 = Utils.GradientCoherentNoise3D(x2, y2, z2, seed, this.m_quality); - num3 = 2.0 * Math.Abs(num3) - 1.0; - num += num3 * num2; + long seed = this.m_seed + i & 4294967295u; + num2 = Utils.GradientCoherentNoise3D(x2, y2, z2, seed, this.m_quality); + num2 = 2.0 * Math.Abs(num2) - 1.0; + num += num2 * num3; x *= this.m_lacunarity; y *= this.m_lacunarity; z *= this.m_lacunarity; - num2 *= this.m_persistence; + num3 *= this.m_persistence; } return num + 0.5; } diff --git a/Assembly-CSharp/Verse.Noise/Blend.cs b/Assembly-CSharp/Verse.Noise/Blend.cs index f05569749..8c3406767 100644 --- a/Assembly-CSharp/Verse.Noise/Blend.cs +++ b/Assembly-CSharp/Verse.Noise/Blend.cs @@ -1,5 +1,3 @@ -using System; - namespace Verse.Noise { public class Blend : ModuleBase @@ -8,11 +6,11 @@ public ModuleBase Controller { get { - return this.modules[2]; + return base.modules[2]; } set { - this.modules[2] = value; + base.modules[2] = value; } } @@ -22,16 +20,16 @@ public Blend() : base(3) public Blend(ModuleBase lhs, ModuleBase rhs, ModuleBase controller) : base(3) { - this.modules[0] = lhs; - this.modules[1] = rhs; - this.modules[2] = controller; + base.modules[0] = lhs; + base.modules[1] = rhs; + base.modules[2] = controller; } public override double GetValue(double x, double y, double z) { - double value = this.modules[0].GetValue(x, y, z); - double value2 = this.modules[1].GetValue(x, y, z); - double position = (this.modules[2].GetValue(x, y, z) + 1.0) / 2.0; + double value = base.modules[0].GetValue(x, y, z); + double value2 = base.modules[1].GetValue(x, y, z); + double position = (base.modules[2].GetValue(x, y, z) + 1.0) / 2.0; return Utils.InterpolateLinear(value, value2, position); } } diff --git a/Assembly-CSharp/Verse.Noise/Cache.cs b/Assembly-CSharp/Verse.Noise/Cache.cs index 978fd7445..1e07c05b5 100644 --- a/Assembly-CSharp/Verse.Noise/Cache.cs +++ b/Assembly-CSharp/Verse.Noise/Cache.cs @@ -1,5 +1,3 @@ -using System; - namespace Verse.Noise { public class Cache : ModuleBase @@ -33,14 +31,14 @@ public Cache() : base(1) public Cache(ModuleBase input) : base(1) { - this.modules[0] = input; + base.modules[0] = input; } public override double GetValue(double x, double y, double z) { if (!this.m_cached || this.m_x != x || this.m_y != y || this.m_z != z) { - this.m_value = this.modules[0].GetValue(x, y, z); + this.m_value = base.modules[0].GetValue(x, y, z); this.m_x = x; this.m_y = y; this.m_z = z; diff --git a/Assembly-CSharp/Verse.Noise/Clamp.cs b/Assembly-CSharp/Verse.Noise/Clamp.cs index 72be408cb..93b76e43b 100644 --- a/Assembly-CSharp/Verse.Noise/Clamp.cs +++ b/Assembly-CSharp/Verse.Noise/Clamp.cs @@ -1,5 +1,3 @@ -using System; - namespace Verse.Noise { public class Clamp : ModuleBase @@ -38,14 +36,14 @@ public Clamp() : base(1) public Clamp(ModuleBase input) : base(1) { - this.modules[0] = input; + base.modules[0] = input; } public Clamp(double min, double max, ModuleBase input) : base(1) { this.Minimum = min; this.Maximum = max; - this.modules[0] = input; + base.modules[0] = input; } public void SetBounds(double min, double max) @@ -62,7 +60,7 @@ public override double GetValue(double x, double y, double z) this.m_min = this.m_max; this.m_max = min; } - double value = this.modules[0].GetValue(x, y, z); + double value = base.modules[0].GetValue(x, y, z); if (value < this.m_min) { return this.m_min; diff --git a/Assembly-CSharp/Verse.Noise/Const.cs b/Assembly-CSharp/Verse.Noise/Const.cs index 53c6c8535..6c45a186c 100644 --- a/Assembly-CSharp/Verse.Noise/Const.cs +++ b/Assembly-CSharp/Verse.Noise/Const.cs @@ -1,5 +1,3 @@ -using System; - namespace Verse.Noise { public class Const : ModuleBase diff --git a/Assembly-CSharp/Verse.Noise/ConvertToIsland.cs b/Assembly-CSharp/Verse.Noise/ConvertToIsland.cs index ed3da2eac..0ce4ea549 100644 --- a/Assembly-CSharp/Verse.Noise/ConvertToIsland.cs +++ b/Assembly-CSharp/Verse.Noise/ConvertToIsland.cs @@ -1,4 +1,3 @@ -using System; using UnityEngine; namespace Verse.Noise @@ -19,15 +18,15 @@ public ConvertToIsland(Vector3 viewCenter, float viewAngle, ModuleBase input) : { this.viewCenter = viewCenter; this.viewAngle = viewAngle; - this.modules[0] = input; + base.modules[0] = input; } public override double GetValue(double x, double y, double z) { float num = Vector3.Angle(this.viewCenter, new Vector3((float)x, (float)y, (float)z)); - double value = this.modules[0].GetValue(x, y, z); - float num2 = Mathf.Max(2.5f, this.viewAngle * 0.25f); - float num3 = Mathf.Max(0.8f, this.viewAngle * 0.1f); + double value = base.modules[0].GetValue(x, y, z); + float num2 = Mathf.Max(2.5f, (float)(this.viewAngle * 0.25)); + float num3 = Mathf.Max(0.8f, (float)(this.viewAngle * 0.10000000149011612)); if (num < this.viewAngle - num2) { return value; @@ -35,9 +34,9 @@ public override double GetValue(double x, double y, double z) float num4 = GenMath.LerpDouble(this.viewAngle - num2, this.viewAngle - num3, 0f, 0.62f, num); if (value > -0.11999999731779099) { - return (value - -0.11999999731779099) * (double)(1f - num4 * 0.7f) - (double)(num4 * 0.3f) + -0.11999999731779099; + return (value - -0.11999999731779099) * (1.0 - num4 * 0.699999988079071) - num4 * 0.30000001192092896 + -0.11999999731779099; } - return value - (double)(num4 * 0.3f); + return value - num4 * 0.30000001192092896; } } } diff --git a/Assembly-CSharp/Verse.Noise/Curve.cs b/Assembly-CSharp/Verse.Noise/Curve.cs index 85989a7f8..f3f7449b5 100644 --- a/Assembly-CSharp/Verse.Noise/Curve.cs +++ b/Assembly-CSharp/Verse.Noise/Curve.cs @@ -30,7 +30,7 @@ public Curve() : base(1) public Curve(ModuleBase input) : base(1) { - this.modules[0] = input; + base.modules[0] = input; } public void Add(double input, double output) @@ -40,7 +40,7 @@ public void Add(double input, double output) { this.m_data.Add(item); } - this.m_data.Sort((KeyValuePair lhs, KeyValuePair rhs) => lhs.Key.CompareTo(rhs.Key)); + this.m_data.Sort((Comparison>)((KeyValuePair lhs, KeyValuePair rhs) => lhs.Key.CompareTo(rhs.Key))); } public void Clear() @@ -50,27 +50,24 @@ public void Clear() public override double GetValue(double x, double y, double z) { - double value = this.modules[0].GetValue(x, y, z); - int i; - for (i = 0; i < this.m_data.Count; i++) + double value = base.modules[0].GetValue(x, y, z); + int num = 0; + while (num < this.m_data.Count && !(value < this.m_data[num].Key)) { - if (value < this.m_data[i].Key) - { - break; - } + num++; } - int index = Mathf.Clamp(i - 2, 0, this.m_data.Count - 1); - int num = Mathf.Clamp(i - 1, 0, this.m_data.Count - 1); - int num2 = Mathf.Clamp(i, 0, this.m_data.Count - 1); - int index2 = Mathf.Clamp(i + 1, 0, this.m_data.Count - 1); - if (num == num2) + int index = Mathf.Clamp(num - 2, 0, this.m_data.Count - 1); + int num2 = Mathf.Clamp(num - 1, 0, this.m_data.Count - 1); + int num3 = Mathf.Clamp(num, 0, this.m_data.Count - 1); + int index2 = Mathf.Clamp(num + 1, 0, this.m_data.Count - 1); + if (num2 == num3) { - return this.m_data[num].Value; + return this.m_data[num2].Value; } - double key = this.m_data[num].Key; - double key2 = this.m_data[num2].Key; + double key = this.m_data[num2].Key; + double key2 = this.m_data[num3].Key; double position = (value - key) / (key2 - key); - return Utils.InterpolateCubic(this.m_data[index].Value, this.m_data[num].Value, this.m_data[num2].Value, this.m_data[index2].Value, position); + return Utils.InterpolateCubic(this.m_data[index].Value, this.m_data[num2].Value, this.m_data[num3].Value, this.m_data[index2].Value, position); } } } diff --git a/Assembly-CSharp/Verse.Noise/CurveFromAxis.cs b/Assembly-CSharp/Verse.Noise/CurveFromAxis.cs index ccb1045d9..8b495fca6 100644 --- a/Assembly-CSharp/Verse.Noise/CurveFromAxis.cs +++ b/Assembly-CSharp/Verse.Noise/CurveFromAxis.cs @@ -1,4 +1,3 @@ -using System; using UnityEngine; namespace Verse.Noise diff --git a/Assembly-CSharp/Verse.Noise/CurveSimple.cs b/Assembly-CSharp/Verse.Noise/CurveSimple.cs index 127dae452..ca6a0aa3d 100644 --- a/Assembly-CSharp/Verse.Noise/CurveSimple.cs +++ b/Assembly-CSharp/Verse.Noise/CurveSimple.cs @@ -1,5 +1,3 @@ -using System; - namespace Verse.Noise { public class CurveSimple : ModuleBase @@ -8,13 +6,13 @@ public class CurveSimple : ModuleBase public CurveSimple(ModuleBase input, SimpleCurve curve) : base(1) { - this.modules[0] = input; + base.modules[0] = input; this.curve = curve; } public override double GetValue(double x, double y, double z) { - return (double)this.curve.Evaluate((float)this.modules[0].GetValue(x, y, z)); + return (double)this.curve.Evaluate((float)base.modules[0].GetValue(x, y, z)); } } } diff --git a/Assembly-CSharp/Verse.Noise/Displace.cs b/Assembly-CSharp/Verse.Noise/Displace.cs index 5f5c8bc26..c925960d1 100644 --- a/Assembly-CSharp/Verse.Noise/Displace.cs +++ b/Assembly-CSharp/Verse.Noise/Displace.cs @@ -1,5 +1,3 @@ -using System; - namespace Verse.Noise { public class Displace : ModuleBase @@ -8,11 +6,11 @@ public ModuleBase X { get { - return this.modules[1]; + return base.modules[1]; } set { - this.modules[1] = value; + base.modules[1] = value; } } @@ -20,11 +18,11 @@ public ModuleBase Y { get { - return this.modules[2]; + return base.modules[2]; } set { - this.modules[2] = value; + base.modules[2] = value; } } @@ -32,11 +30,11 @@ public ModuleBase Z { get { - return this.modules[3]; + return base.modules[3]; } set { - this.modules[3] = value; + base.modules[3] = value; } } @@ -46,18 +44,18 @@ public Displace() : base(4) public Displace(ModuleBase input, ModuleBase x, ModuleBase y, ModuleBase z) : base(4) { - this.modules[0] = input; - this.modules[1] = x; - this.modules[2] = y; - this.modules[3] = z; + base.modules[0] = input; + base.modules[1] = x; + base.modules[2] = y; + base.modules[3] = z; } public override double GetValue(double x, double y, double z) { - double x2 = x + this.modules[1].GetValue(x, y, z); - double y2 = y + this.modules[2].GetValue(x, y, z); - double z2 = z + this.modules[3].GetValue(x, y, z); - return this.modules[0].GetValue(x2, y2, z2); + double x2 = x + base.modules[1].GetValue(x, y, z); + double y2 = y + base.modules[2].GetValue(x, y, z); + double z2 = z + base.modules[3].GetValue(x, y, z); + return base.modules[0].GetValue(x2, y2, z2); } } } diff --git a/Assembly-CSharp/Verse.Noise/DistanceFromPlanetViewCenter.cs b/Assembly-CSharp/Verse.Noise/DistanceFromPlanetViewCenter.cs index 47f6ab79f..a6de4e1df 100644 --- a/Assembly-CSharp/Verse.Noise/DistanceFromPlanetViewCenter.cs +++ b/Assembly-CSharp/Verse.Noise/DistanceFromPlanetViewCenter.cs @@ -1,4 +1,3 @@ -using System; using UnityEngine; namespace Verse.Noise @@ -27,14 +26,14 @@ public override double GetValue(double x, double y, double z) float valueInt = this.GetValueInt(x, y, z); if (this.invert) { - return (double)(1f - valueInt); + return 1.0 - valueInt; } return (double)valueInt; } private float GetValueInt(double x, double y, double z) { - if (this.viewAngle >= 180f) + if (this.viewAngle >= 180.0) { return 0f; } diff --git a/Assembly-CSharp/Verse.Noise/Exponent.cs b/Assembly-CSharp/Verse.Noise/Exponent.cs index 5bb517f0b..b063055a7 100644 --- a/Assembly-CSharp/Verse.Noise/Exponent.cs +++ b/Assembly-CSharp/Verse.Noise/Exponent.cs @@ -24,18 +24,18 @@ public Exponent() : base(1) public Exponent(ModuleBase input) : base(1) { - this.modules[0] = input; + base.modules[0] = input; } public Exponent(double exponent, ModuleBase input) : base(1) { - this.modules[0] = input; + base.modules[0] = input; this.Value = exponent; } public override double GetValue(double x, double y, double z) { - double value = this.modules[0].GetValue(x, y, z); + double value = base.modules[0].GetValue(x, y, z); return Math.Pow(Math.Abs((value + 1.0) / 2.0), this.m_exponent) * 2.0 - 1.0; } } diff --git a/Assembly-CSharp/Verse.Noise/Filter.cs b/Assembly-CSharp/Verse.Noise/Filter.cs index 33181cc4c..21988c282 100644 --- a/Assembly-CSharp/Verse.Noise/Filter.cs +++ b/Assembly-CSharp/Verse.Noise/Filter.cs @@ -1,5 +1,3 @@ -using System; - namespace Verse.Noise { public class Filter : ModuleBase @@ -14,14 +12,14 @@ public Filter() : base(1) public Filter(ModuleBase module, float from, float to) : base(1) { - this.modules[0] = module; + base.modules[0] = module; this.from = from; this.to = to; } public override double GetValue(double x, double y, double z) { - double value = this.modules[0].GetValue(x, y, z); + double value = base.modules[0].GetValue(x, y, z); if (value >= (double)this.from && value <= (double)this.to) { return 1.0; diff --git a/Assembly-CSharp/Verse.Noise/GradientPresets.cs b/Assembly-CSharp/Verse.Noise/GradientPresets.cs index d74aa243a..1ec48d97c 100644 --- a/Assembly-CSharp/Verse.Noise/GradientPresets.cs +++ b/Assembly-CSharp/Verse.Noise/GradientPresets.cs @@ -1,4 +1,3 @@ -using System; using System.Collections.Generic; using UnityEngine; @@ -58,33 +57,45 @@ public static Gradient Terrain static GradientPresets() { - List list = new List(); - list.Add(new GradientColorKey(Color.black, 0f)); - list.Add(new GradientColorKey(Color.white, 1f)); - List list2 = new List(); - list2.Add(new GradientColorKey(Color.red, 0f)); - list2.Add(new GradientColorKey(Color.green, 0.5f)); - list2.Add(new GradientColorKey(Color.blue, 1f)); - List list3 = new List(); - list3.Add(new GradientColorKey(Color.red, 0f)); - list3.Add(new GradientColorKey(Color.green, 0.333333343f)); - list3.Add(new GradientColorKey(Color.blue, 0.6666667f)); - list3.Add(new GradientColorKey(Color.black, 1f)); - List list4 = new List(); - list4.Add(new GradientAlphaKey(0f, 0.6666667f)); - list4.Add(new GradientAlphaKey(1f, 1f)); - List list5 = new List(); - list5.Add(new GradientColorKey(new Color(0f, 0f, 0.5f), 0f)); - list5.Add(new GradientColorKey(new Color(0.125f, 0.25f, 0.5f), 0.4f)); - list5.Add(new GradientColorKey(new Color(0.25f, 0.375f, 0.75f), 0.48f)); - list5.Add(new GradientColorKey(new Color(0f, 0.75f, 0f), 0.5f)); - list5.Add(new GradientColorKey(new Color(0.75f, 0.75f, 0f), 0.625f)); - list5.Add(new GradientColorKey(new Color(0.625f, 0.375f, 0.25f), 0.75f)); - list5.Add(new GradientColorKey(new Color(0.5f, 1f, 1f), 0.875f)); - list5.Add(new GradientColorKey(Color.white, 1f)); - List list6 = new List(); - list6.Add(new GradientAlphaKey(1f, 0f)); - list6.Add(new GradientAlphaKey(1f, 1f)); + List list = new List + { + new GradientColorKey(Color.black, 0f), + new GradientColorKey(Color.white, 1f) + }; + List list2 = new List + { + new GradientColorKey(Color.red, 0f), + new GradientColorKey(Color.green, 0.5f), + new GradientColorKey(Color.blue, 1f) + }; + List list3 = new List + { + new GradientColorKey(Color.red, 0f), + new GradientColorKey(Color.green, 0.333333343f), + new GradientColorKey(Color.blue, 0.6666667f), + new GradientColorKey(Color.black, 1f) + }; + List list4 = new List + { + new GradientAlphaKey(0f, 0.6666667f), + new GradientAlphaKey(1f, 1f) + }; + List list5 = new List + { + new GradientColorKey(new Color(0f, 0f, 0.5f), 0f), + new GradientColorKey(new Color(0.125f, 0.25f, 0.5f), 0.4f), + new GradientColorKey(new Color(0.25f, 0.375f, 0.75f), 0.48f), + new GradientColorKey(new Color(0f, 0.75f, 0f), 0.5f), + new GradientColorKey(new Color(0.75f, 0.75f, 0f), 0.625f), + new GradientColorKey(new Color(0.625f, 0.375f, 0.25f), 0.75f), + new GradientColorKey(new Color(0.5f, 1f, 1f), 0.875f), + new GradientColorKey(Color.white, 1f) + }; + List list6 = new List + { + new GradientAlphaKey(1f, 0f), + new GradientAlphaKey(1f, 1f) + }; GradientPresets._empty = new Gradient(); GradientPresets._rgb = new Gradient(); GradientPresets._rgb.SetKeys(list2.ToArray(), list6.ToArray()); diff --git a/Assembly-CSharp/Verse.Noise/Invert.cs b/Assembly-CSharp/Verse.Noise/Invert.cs index 656ea0ef6..1940fd1ef 100644 --- a/Assembly-CSharp/Verse.Noise/Invert.cs +++ b/Assembly-CSharp/Verse.Noise/Invert.cs @@ -1,5 +1,3 @@ -using System; - namespace Verse.Noise { public class Invert : ModuleBase @@ -10,12 +8,12 @@ public Invert() : base(1) public Invert(ModuleBase input) : base(1) { - this.modules[0] = input; + base.modules[0] = input; } public override double GetValue(double x, double y, double z) { - return -this.modules[0].GetValue(x, y, z); + return 0.0 - base.modules[0].GetValue(x, y, z); } } } diff --git a/Assembly-CSharp/Verse.Noise/Max.cs b/Assembly-CSharp/Verse.Noise/Max.cs index 50f830055..20173a9b6 100644 --- a/Assembly-CSharp/Verse.Noise/Max.cs +++ b/Assembly-CSharp/Verse.Noise/Max.cs @@ -10,14 +10,14 @@ public Max() : base(2) public Max(ModuleBase lhs, ModuleBase rhs) : base(2) { - this.modules[0] = lhs; - this.modules[1] = rhs; + base.modules[0] = lhs; + base.modules[1] = rhs; } public override double GetValue(double x, double y, double z) { - double value = this.modules[0].GetValue(x, y, z); - double value2 = this.modules[1].GetValue(x, y, z); + double value = base.modules[0].GetValue(x, y, z); + double value2 = base.modules[1].GetValue(x, y, z); return Math.Max(value, value2); } } diff --git a/Assembly-CSharp/Verse.Noise/Min.cs b/Assembly-CSharp/Verse.Noise/Min.cs index 76ff99393..1386e54e3 100644 --- a/Assembly-CSharp/Verse.Noise/Min.cs +++ b/Assembly-CSharp/Verse.Noise/Min.cs @@ -10,14 +10,14 @@ public Min() : base(2) public Min(ModuleBase lhs, ModuleBase rhs) : base(2) { - this.modules[0] = lhs; - this.modules[1] = rhs; + base.modules[0] = lhs; + base.modules[1] = rhs; } public override double GetValue(double x, double y, double z) { - double value = this.modules[0].GetValue(x, y, z); - double value2 = this.modules[1].GetValue(x, y, z); + double value = base.modules[0].GetValue(x, y, z); + double value2 = base.modules[1].GetValue(x, y, z); return Math.Min(value, value2); } } diff --git a/Assembly-CSharp/Verse.Noise/ModuleBase.cs b/Assembly-CSharp/Verse.Noise/ModuleBase.cs index ef0f00dcf..b17d0cde6 100644 --- a/Assembly-CSharp/Verse.Noise/ModuleBase.cs +++ b/Assembly-CSharp/Verse.Noise/ModuleBase.cs @@ -8,8 +8,8 @@ public abstract class ModuleBase : IDisposable { protected ModuleBase[] modules; - [XmlIgnore] [NonSerialized] + [XmlIgnore] private bool m_disposed; public int SourceModuleCount @@ -24,27 +24,28 @@ public virtual ModuleBase this[int index] { get { - if (index < 0 || index >= this.modules.Length) - { - throw new ArgumentOutOfRangeException("Index out of valid module range"); - } - if (this.modules[index] == null) + if (index >= 0 && index < this.modules.Length) { - throw new ArgumentNullException("Desired element is null"); + if (this.modules[index] == null) + { + throw new ArgumentNullException("Desired element is null"); + } + return this.modules[index]; } - return this.modules[index]; + throw new ArgumentOutOfRangeException("Index out of valid module range"); } set { - if (index < 0 || index >= this.modules.Length) - { - throw new ArgumentOutOfRangeException("Index out of valid module range"); - } - if (value == null) + if (index >= 0 && index < this.modules.Length) { - throw new ArgumentNullException("Value should not be null"); + if (value == null) + { + throw new ArgumentNullException("Value should not be null"); + } + this.modules[index] = value; + return; } - this.modules[index] = value; + throw new ArgumentOutOfRangeException("Index out of valid module range"); } } diff --git a/Assembly-CSharp/Verse.Noise/Multiply.cs b/Assembly-CSharp/Verse.Noise/Multiply.cs index 8e6f61a53..e2294ec0c 100644 --- a/Assembly-CSharp/Verse.Noise/Multiply.cs +++ b/Assembly-CSharp/Verse.Noise/Multiply.cs @@ -1,5 +1,3 @@ -using System; - namespace Verse.Noise { public class Multiply : ModuleBase @@ -10,13 +8,13 @@ public Multiply() : base(2) public Multiply(ModuleBase lhs, ModuleBase rhs) : base(2) { - this.modules[0] = lhs; - this.modules[1] = rhs; + base.modules[0] = lhs; + base.modules[1] = rhs; } public override double GetValue(double x, double y, double z) { - return this.modules[0].GetValue(x, y, z) * this.modules[1].GetValue(x, y, z); + return base.modules[0].GetValue(x, y, z) * base.modules[1].GetValue(x, y, z); } } } diff --git a/Assembly-CSharp/Verse.Noise/Noise2D.cs b/Assembly-CSharp/Verse.Noise/Noise2D.cs index c6093dc97..8f79ab1c0 100644 --- a/Assembly-CSharp/Verse.Noise/Noise2D.cs +++ b/Assembly-CSharp/Verse.Noise/Noise2D.cs @@ -44,8 +44,8 @@ public class Noise2D : IDisposable private ModuleBase m_generator; - [XmlIgnore] [NonSerialized] + [XmlIgnore] private bool m_disposed; public float this[int x, int y, bool isCropped = true] @@ -64,18 +64,15 @@ public class Noise2D : IDisposable } return this.m_data[x, y]; } - else + if (x < 0 && x >= this.m_ucWidth) { - if (x < 0 && x >= this.m_ucWidth) - { - throw new ArgumentOutOfRangeException("Invalid x position"); - } - if (y < 0 && y >= this.m_ucHeight) - { - throw new ArgumentOutOfRangeException("Inavlid y position"); - } - return this.m_ucData[x, y]; + throw new ArgumentOutOfRangeException("Invalid x position"); } + if (y < 0 && y >= this.m_ucHeight) + { + throw new ArgumentOutOfRangeException("Inavlid y position"); + } + return this.m_ucData[x, y]; } set { @@ -188,9 +185,9 @@ public Noise2D(int width, int height, ModuleBase generator) public float[,] GetData(bool isCropped = true, int xCrop = 0, int yCrop = 0, bool isNormalized = false) { + float[,] array; int num; int num2; - float[,] array; if (isCropped) { num = this.m_width; @@ -206,20 +203,12 @@ public Noise2D(int width, int height, ModuleBase generator) num -= xCrop; num2 -= yCrop; float[,] array2 = new float[num, num2]; - for (int i = 0; i < num; i++) + for (int num3 = 0; num3 < num; num3++) { - for (int j = 0; j < num2; j++) + for (int num4 = 0; num4 < num2; num4++) { - float num3; - if (isNormalized) - { - num3 = (array[i, j] + 1f) / 2f; - } - else - { - num3 = array[i, j]; - } - array2[i, j] = num3; + float num5 = (float)((!isNormalized) ? array[num3, num4] : ((array[num3, num4] + 1.0) / 2.0)); + array2[num3, num4] = num5; } } return array2; @@ -253,50 +242,51 @@ public void GeneratePlanar(double left, double right, double top, double bottom) public void GeneratePlanar(double left, double right, double top, double bottom, bool isSeamless) { - if (right <= left || bottom <= top) - { - throw new ArgumentException("Invalid right/left or bottom/top combination"); - } - if (this.m_generator == null) + if (!(right <= left) && !(bottom <= top)) { - throw new ArgumentNullException("Generator is null"); - } - double num = right - left; - double num2 = bottom - top; - double num3 = num / ((double)this.m_width - (double)this.m_ucBorder); - double num4 = num2 / ((double)this.m_height - (double)this.m_ucBorder); - double num5 = left; - for (int i = 0; i < this.m_ucWidth; i++) - { - double num6 = top; - for (int j = 0; j < this.m_ucHeight; j++) + if (this.m_generator == null) { - float num7; - if (isSeamless) - { - num7 = (float)this.GeneratePlanar(num5, num6); - } - else - { - double a = this.GeneratePlanar(num5, num6); - double b = this.GeneratePlanar(num5 + num, num6); - double a2 = this.GeneratePlanar(num5, num6 + num2); - double b2 = this.GeneratePlanar(num5 + num, num6 + num2); - double position = 1.0 - (num5 - left) / num; - double position2 = 1.0 - (num6 - top) / num2; - double a3 = Utils.InterpolateLinear(a, b, position); - double b3 = Utils.InterpolateLinear(a2, b2, position); - num7 = (float)Utils.InterpolateLinear(a3, b3, position2); - } - this.m_ucData[i, j] = num7; - if (i >= this.m_ucBorder && j >= this.m_ucBorder && i < this.m_width + this.m_ucBorder && j < this.m_height + this.m_ucBorder) + throw new ArgumentNullException("Generator is null"); + } + double num = right - left; + double num2 = bottom - top; + double num3 = num / ((double)this.m_width - (double)this.m_ucBorder); + double num4 = num2 / ((double)this.m_height - (double)this.m_ucBorder); + double num5 = left; + float num6 = 0f; + for (int i = 0; i < this.m_ucWidth; i++) + { + double num7 = top; + for (int j = 0; j < this.m_ucHeight; j++) { - this.m_data[i - this.m_ucBorder, j - this.m_ucBorder] = num7; + if (isSeamless) + { + num6 = (float)this.GeneratePlanar(num5, num7); + } + else + { + double a = this.GeneratePlanar(num5, num7); + double b = this.GeneratePlanar(num5 + num, num7); + double a2 = this.GeneratePlanar(num5, num7 + num2); + double b2 = this.GeneratePlanar(num5 + num, num7 + num2); + double position = 1.0 - (num5 - left) / num; + double position2 = 1.0 - (num7 - top) / num2; + double a3 = Utils.InterpolateLinear(a, b, position); + double b3 = Utils.InterpolateLinear(a2, b2, position); + num6 = (float)Utils.InterpolateLinear(a3, b3, position2); + } + this.m_ucData[i, j] = num6; + if (i >= this.m_ucBorder && j >= this.m_ucBorder && i < this.m_width + this.m_ucBorder && j < this.m_height + this.m_ucBorder) + { + this.m_data[i - this.m_ucBorder, j - this.m_ucBorder] = num6; + } + num7 += num4; } - num6 += num4; + num5 += num3; } - num5 += num3; + return; } + throw new ArgumentException("Invalid right/left or bottom/top combination"); } private double GenerateCylindrical(double angle, double height) @@ -308,33 +298,34 @@ private double GenerateCylindrical(double angle, double height) public void GenerateCylindrical(double angleMin, double angleMax, double heightMin, double heightMax) { - if (angleMax <= angleMin || heightMax <= heightMin) - { - throw new ArgumentException("Invalid angle or height parameters"); - } - if (this.m_generator == null) + if (!(angleMax <= angleMin) && !(heightMax <= heightMin)) { - throw new ArgumentNullException("Generator is null"); - } - double num = angleMax - angleMin; - double num2 = heightMax - heightMin; - double num3 = num / ((double)this.m_width - (double)this.m_ucBorder); - double num4 = num2 / ((double)this.m_height - (double)this.m_ucBorder); - double num5 = angleMin; - for (int i = 0; i < this.m_ucWidth; i++) - { - double num6 = heightMin; - for (int j = 0; j < this.m_ucHeight; j++) + if (this.m_generator == null) { - this.m_ucData[i, j] = (float)this.GenerateCylindrical(num5, num6); - if (i >= this.m_ucBorder && j >= this.m_ucBorder && i < this.m_width + this.m_ucBorder && j < this.m_height + this.m_ucBorder) + throw new ArgumentNullException("Generator is null"); + } + double num = angleMax - angleMin; + double num2 = heightMax - heightMin; + double num3 = num / ((double)this.m_width - (double)this.m_ucBorder); + double num4 = num2 / ((double)this.m_height - (double)this.m_ucBorder); + double num5 = angleMin; + for (int i = 0; i < this.m_ucWidth; i++) + { + double num6 = heightMin; + for (int j = 0; j < this.m_ucHeight; j++) { - this.m_data[i - this.m_ucBorder, j - this.m_ucBorder] = (float)this.GenerateCylindrical(num5, num6); + this.m_ucData[i, j] = (float)this.GenerateCylindrical(num5, num6); + if (i >= this.m_ucBorder && j >= this.m_ucBorder && i < this.m_width + this.m_ucBorder && j < this.m_height + this.m_ucBorder) + { + this.m_data[i - this.m_ucBorder, j - this.m_ucBorder] = (float)this.GenerateCylindrical(num5, num6); + } + num6 += num4; } - num6 += num4; + num5 += num3; } - num5 += num3; + return; } + throw new ArgumentException("Invalid angle or height parameters"); } private double GenerateSpherical(double lat, double lon) @@ -345,33 +336,34 @@ private double GenerateSpherical(double lat, double lon) public void GenerateSpherical(double south, double north, double west, double east) { - if (east <= west || north <= south) + if (!(east <= west) && !(north <= south)) { - throw new ArgumentException("Invalid east/west or north/south combination"); - } - if (this.m_generator == null) - { - throw new ArgumentNullException("Generator is null"); - } - double num = east - west; - double num2 = north - south; - double num3 = num / ((double)this.m_width - (double)this.m_ucBorder); - double num4 = num2 / ((double)this.m_height - (double)this.m_ucBorder); - double num5 = west; - for (int i = 0; i < this.m_ucWidth; i++) - { - double num6 = south; - for (int j = 0; j < this.m_ucHeight; j++) + if (this.m_generator == null) { - this.m_ucData[i, j] = (float)this.GenerateSpherical(num6, num5); - if (i >= this.m_ucBorder && j >= this.m_ucBorder && i < this.m_width + this.m_ucBorder && j < this.m_height + this.m_ucBorder) + throw new ArgumentNullException("Generator is null"); + } + double num = east - west; + double num2 = north - south; + double num3 = num / ((double)this.m_width - (double)this.m_ucBorder); + double num4 = num2 / ((double)this.m_height - (double)this.m_ucBorder); + double num5 = west; + for (int i = 0; i < this.m_ucWidth; i++) + { + double num6 = south; + for (int j = 0; j < this.m_ucHeight; j++) { - this.m_data[i - this.m_ucBorder, j - this.m_ucBorder] = (float)this.GenerateSpherical(num6, num5); + this.m_ucData[i, j] = (float)this.GenerateSpherical(num6, num5); + if (i >= this.m_ucBorder && j >= this.m_ucBorder && i < this.m_width + this.m_ucBorder && j < this.m_height + this.m_ucBorder) + { + this.m_data[i - this.m_ucBorder, j - this.m_ucBorder] = (float)this.GenerateSpherical(num6, num5); + } + num6 += num4; } - num6 += num4; + num5 += num3; } - num5 += num3; + return; } + throw new ArgumentException("Invalid east/west or north/south combination"); } public Texture2D GetTexture() @@ -388,16 +380,9 @@ public Texture2D GetTexture(Gradient gradient) { for (int j = 0; j < this.m_height; j++) { - float num; - if (!float.IsNaN(this.m_borderValue) && (i == 0 || i == this.m_width - this.m_ucBorder || j == 0 || j == this.m_height - this.m_ucBorder)) - { - num = this.m_borderValue; - } - else - { - num = this.m_data[i, j]; - } - array[i + j * this.m_width] = gradient.Evaluate((num + 1f) / 2f); + float num = 0f; + num = ((float.IsNaN(this.m_borderValue) || (i != 0 && i != this.m_width - this.m_ucBorder && j != 0 && j != this.m_height - this.m_ucBorder)) ? this.m_data[i, j] : this.m_borderValue); + array[i + j * this.m_width] = gradient.Evaluate((float)((num + 1.0) / 2.0)); } } texture2D.SetPixels(array); @@ -415,16 +400,16 @@ public Texture2D GetNormalMap(float intensity) { for (int j = 0; j < this.m_ucHeight; j++) { - float num = (this.m_ucData[Mathf.Max(0, i - this.m_ucBorder), j] - this.m_ucData[Mathf.Min(i + this.m_ucBorder, this.m_height + this.m_ucBorder), j]) / 2f; - float num2 = (this.m_ucData[i, Mathf.Max(0, j - this.m_ucBorder)] - this.m_ucData[i, Mathf.Min(j + this.m_ucBorder, this.m_width + this.m_ucBorder)]) / 2f; + float num = (float)((this.m_ucData[Mathf.Max(0, i - this.m_ucBorder), j] - this.m_ucData[Mathf.Min(i + this.m_ucBorder, this.m_height + this.m_ucBorder), j]) / 2.0); + float num2 = (float)((this.m_ucData[i, Mathf.Max(0, j - this.m_ucBorder)] - this.m_ucData[i, Mathf.Min(j + this.m_ucBorder, this.m_width + this.m_ucBorder)]) / 2.0); Vector3 a = new Vector3(num * intensity, 0f, 1f); Vector3 b = new Vector3(0f, num2 * intensity, 1f); Vector3 vector = a + b; vector.Normalize(); Vector3 zero = Vector3.zero; - zero.x = (vector.x + 1f) / 2f; - zero.y = (vector.y + 1f) / 2f; - zero.z = (vector.z + 1f) / 2f; + zero.x = (float)((vector.x + 1.0) / 2.0); + zero.y = (float)((vector.y + 1.0) / 2.0); + zero.z = (float)((vector.z + 1.0) / 2.0); if (i >= this.m_ucBorder && j >= this.m_ucBorder && i < this.m_width + this.m_ucBorder && j < this.m_height + this.m_ucBorder) { array[i - this.m_ucBorder + (j - this.m_ucBorder) * this.m_width] = new Color(zero.x, zero.y, zero.z); diff --git a/Assembly-CSharp/Verse.Noise/NoiseDebugUI.cs b/Assembly-CSharp/Verse.Noise/NoiseDebugUI.cs index 598013a83..65afd5e4e 100644 --- a/Assembly-CSharp/Verse.Noise/NoiseDebugUI.cs +++ b/Assembly-CSharp/Verse.Noise/NoiseDebugUI.cs @@ -19,7 +19,7 @@ public Texture2D Texture { get { - if (this.tex == null) + if ((UnityEngine.Object)this.tex == (UnityEngine.Object)null) { this.tex = NoiseRenderer.NoiseRendered(this.noise); } @@ -47,15 +47,15 @@ public NoisePlanet(ModuleBase noise, string name) } } - private static List noises2D = new List(); + private static List noises2D = new List(); - private static List planetNoises = new List(); + private static List planetNoises = new List(); private static Mesh planetNoiseMesh; - private static NoiseDebugUI.NoisePlanet currentPlanetNoise; + private static NoisePlanet currentPlanetNoise; - private static NoiseDebugUI.NoisePlanet lastDrawnPlanetNoise; + private static NoisePlanet lastDrawnPlanetNoise; private static List planetNoiseMeshColors = new List(); @@ -77,112 +77,113 @@ public static void StoreNoiseRender(ModuleBase noise, string name, IntVec2 rende public static void StoreNoiseRender(ModuleBase noise, string name) { - if (!Prefs.DevMode || !DebugViewSettings.drawRecordedNoise) + if (Prefs.DevMode && DebugViewSettings.drawRecordedNoise) { - return; + Noise2D item = new Noise2D(noise, name); + NoiseDebugUI.noises2D.Add(item); } - NoiseDebugUI.Noise2D item = new NoiseDebugUI.Noise2D(noise, name); - NoiseDebugUI.noises2D.Add(item); } public static void StorePlanetNoise(ModuleBase noise, string name) { - if (!Prefs.DevMode || !DebugViewSettings.drawRecordedNoise) + if (Prefs.DevMode && DebugViewSettings.drawRecordedNoise) { - return; + NoisePlanet item = new NoisePlanet(noise, name); + NoiseDebugUI.planetNoises.Add(item); } - NoiseDebugUI.NoisePlanet item = new NoiseDebugUI.NoisePlanet(noise, name); - NoiseDebugUI.planetNoises.Add(item); } public static void NoiseDebugOnGUI() { - if (!Prefs.DevMode || !DebugViewSettings.drawRecordedNoise) + if (Prefs.DevMode && DebugViewSettings.drawRecordedNoise) { - return; - } - if (Widgets.ButtonText(new Rect(0f, 40f, 200f, 30f), "Clear noise renders", true, false, true)) - { - NoiseDebugUI.Clear(); - } - if (Widgets.ButtonText(new Rect(200f, 40f, 200f, 30f), "Hide noise renders", true, false, true)) - { - DebugViewSettings.drawRecordedNoise = false; - } - if (WorldRendererUtility.WorldRenderedNow) - { - if (NoiseDebugUI.planetNoises.Any() && Widgets.ButtonText(new Rect(400f, 40f, 200f, 30f), "Next planet noise", true, false, true)) + if (Widgets.ButtonText(new Rect(0f, 40f, 200f, 30f), "Clear noise renders", true, false, true)) { - if (NoiseDebugUI.currentPlanetNoise == null || NoiseDebugUI.planetNoises.IndexOf(NoiseDebugUI.currentPlanetNoise) == -1) - { - NoiseDebugUI.currentPlanetNoise = NoiseDebugUI.planetNoises[0]; - } - else if (NoiseDebugUI.planetNoises.IndexOf(NoiseDebugUI.currentPlanetNoise) == NoiseDebugUI.planetNoises.Count - 1) + NoiseDebugUI.Clear(); + } + if (Widgets.ButtonText(new Rect(200f, 40f, 200f, 30f), "Hide noise renders", true, false, true)) + { + DebugViewSettings.drawRecordedNoise = false; + } + if (WorldRendererUtility.WorldRenderedNow) + { + if (NoiseDebugUI.planetNoises.Any() && Widgets.ButtonText(new Rect(400f, 40f, 200f, 30f), "Next planet noise", true, false, true)) { - NoiseDebugUI.currentPlanetNoise = null; + if (NoiseDebugUI.currentPlanetNoise == null || NoiseDebugUI.planetNoises.IndexOf(NoiseDebugUI.currentPlanetNoise) == -1) + { + NoiseDebugUI.currentPlanetNoise = NoiseDebugUI.planetNoises[0]; + } + else if (NoiseDebugUI.planetNoises.IndexOf(NoiseDebugUI.currentPlanetNoise) == NoiseDebugUI.planetNoises.Count - 1) + { + NoiseDebugUI.currentPlanetNoise = null; + } + else + { + NoiseDebugUI.currentPlanetNoise = NoiseDebugUI.planetNoises[NoiseDebugUI.planetNoises.IndexOf(NoiseDebugUI.currentPlanetNoise) + 1]; + } } - else + if (NoiseDebugUI.currentPlanetNoise != null) { - NoiseDebugUI.currentPlanetNoise = NoiseDebugUI.planetNoises[NoiseDebugUI.planetNoises.IndexOf(NoiseDebugUI.currentPlanetNoise) + 1]; + Rect rect = new Rect(605f, 40f, 300f, 30f); + Text.Font = GameFont.Medium; + Widgets.Label(rect, NoiseDebugUI.currentPlanetNoise.name); + Text.Font = GameFont.Small; } } - if (NoiseDebugUI.currentPlanetNoise != null) + float num = 0f; + float num2 = 90f; + Text.Font = GameFont.Tiny; + List.Enumerator enumerator = NoiseDebugUI.noises2D.GetEnumerator(); + try { - Rect rect = new Rect(605f, 40f, 300f, 30f); - Text.Font = GameFont.Medium; - Widgets.Label(rect, NoiseDebugUI.currentPlanetNoise.name); - Text.Font = GameFont.Small; + while (enumerator.MoveNext()) + { + Noise2D current = enumerator.Current; + Texture2D texture = current.Texture; + if (num + (float)texture.width + 5.0 > (float)UI.screenWidth) + { + num = 0f; + num2 += (float)(texture.height + 5 + 25); + } + Rect position = new Rect(num, num2, (float)texture.width, (float)texture.height); + GUI.DrawTexture(position, texture); + Rect rect2 = new Rect(num, (float)(num2 - 15.0), (float)texture.width, (float)texture.height); + GUI.color = Color.black; + Widgets.Label(rect2, current.name); + GUI.color = Color.white; + Widgets.Label(new Rect((float)(rect2.x + 1.0), (float)(rect2.y + 1.0), rect2.width, rect2.height), current.name); + num += (float)(texture.width + 5); + } } - } - float num = 0f; - float num2 = 90f; - Text.Font = GameFont.Tiny; - foreach (NoiseDebugUI.Noise2D current in NoiseDebugUI.noises2D) - { - Texture2D texture = current.Texture; - if (num + (float)texture.width + 5f > (float)UI.screenWidth) + finally { - num = 0f; - num2 += (float)(texture.height + 5 + 25); + ((IDisposable)(object)enumerator).Dispose(); } - Rect position = new Rect(num, num2, (float)texture.width, (float)texture.height); - GUI.DrawTexture(position, texture); - Rect rect2 = new Rect(num, num2 - 15f, (float)texture.width, (float)texture.height); - GUI.color = Color.black; - Widgets.Label(rect2, current.name); - GUI.color = Color.white; - Widgets.Label(new Rect(rect2.x + 1f, rect2.y + 1f, rect2.width, rect2.height), current.name); - num += (float)(texture.width + 5); } } public static void RenderPlanetNoise() { - if (!Prefs.DevMode || !DebugViewSettings.drawRecordedNoise) - { - return; - } - if (NoiseDebugUI.currentPlanetNoise == null) - { - return; - } - if (NoiseDebugUI.planetNoiseMesh == null) + if (Prefs.DevMode && DebugViewSettings.drawRecordedNoise && NoiseDebugUI.currentPlanetNoise != null) { - List triangles; - SphereGenerator.Generate(5, 100.3f, Vector3.forward, 360f, out NoiseDebugUI.planetNoiseMeshVerts, out triangles); - NoiseDebugUI.planetNoiseMesh = new Mesh(); - NoiseDebugUI.planetNoiseMesh.name = "NoiseDebugUI"; - NoiseDebugUI.planetNoiseMesh.SetVertices(NoiseDebugUI.planetNoiseMeshVerts); - NoiseDebugUI.planetNoiseMesh.SetTriangles(triangles, 0); - NoiseDebugUI.planetNoiseMesh.Optimize(); - NoiseDebugUI.lastDrawnPlanetNoise = null; - } - if (NoiseDebugUI.lastDrawnPlanetNoise != NoiseDebugUI.currentPlanetNoise) - { - NoiseDebugUI.UpdatePlanetNoiseVertexColors(); - NoiseDebugUI.lastDrawnPlanetNoise = NoiseDebugUI.currentPlanetNoise; + if ((UnityEngine.Object)NoiseDebugUI.planetNoiseMesh == (UnityEngine.Object)null) + { + List triangles = default(List); + SphereGenerator.Generate(5, 100.3f, Vector3.forward, 360f, out NoiseDebugUI.planetNoiseMeshVerts, out triangles); + NoiseDebugUI.planetNoiseMesh = new Mesh(); + NoiseDebugUI.planetNoiseMesh.name = "NoiseDebugUI"; + NoiseDebugUI.planetNoiseMesh.SetVertices(NoiseDebugUI.planetNoiseMeshVerts); + NoiseDebugUI.planetNoiseMesh.SetTriangles(triangles, 0); + NoiseDebugUI.planetNoiseMesh.Optimize(); + NoiseDebugUI.lastDrawnPlanetNoise = null; + } + if (NoiseDebugUI.lastDrawnPlanetNoise != NoiseDebugUI.currentPlanetNoise) + { + NoiseDebugUI.UpdatePlanetNoiseVertexColors(); + NoiseDebugUI.lastDrawnPlanetNoise = NoiseDebugUI.currentPlanetNoise; + } + Graphics.DrawMesh(NoiseDebugUI.planetNoiseMesh, Vector3.zero, Quaternion.identity, WorldMaterials.VertexColor, WorldCameraManager.WorldLayer); } - Graphics.DrawMesh(NoiseDebugUI.planetNoiseMesh, Vector3.zero, Quaternion.identity, WorldMaterials.VertexColor, WorldCameraManager.WorldLayer); } public static void Clear() @@ -200,10 +201,10 @@ public static void ClearPlanetNoises() NoiseDebugUI.planetNoises.Clear(); NoiseDebugUI.currentPlanetNoise = null; NoiseDebugUI.lastDrawnPlanetNoise = null; - if (NoiseDebugUI.planetNoiseMesh != null) + if ((UnityEngine.Object)NoiseDebugUI.planetNoiseMesh != (UnityEngine.Object)null) { Mesh localPlanetNoiseMesh = NoiseDebugUI.planetNoiseMesh; - LongEventHandler.ExecuteWhenFinished(delegate + LongEventHandler.ExecuteWhenFinished((Action)delegate { UnityEngine.Object.Destroy(localPlanetNoiseMesh); }); @@ -217,8 +218,8 @@ private static void UpdatePlanetNoiseVertexColors() for (int i = 0; i < NoiseDebugUI.planetNoiseMeshVerts.Count; i++) { float value = NoiseDebugUI.currentPlanetNoise.noise.GetValue(NoiseDebugUI.planetNoiseMeshVerts[i]); - byte b = (byte)Mathf.Clamp((value * 0.5f + 0.5f) * 255f, 0f, 255f); - NoiseDebugUI.planetNoiseMeshColors.Add(new Color32(b, b, b, 255)); + byte b = (byte)Mathf.Clamp((float)((value * 0.5 + 0.5) * 255.0), 0f, 255f); + NoiseDebugUI.planetNoiseMeshColors.Add(new Color32(b, b, b, (byte)255)); } NoiseDebugUI.planetNoiseMesh.SetColors(NoiseDebugUI.planetNoiseMeshColors); } diff --git a/Assembly-CSharp/Verse.Noise/NoiseRenderer.cs b/Assembly-CSharp/Verse.Noise/NoiseRenderer.cs index 3ef1f755f..63c20b95a 100644 --- a/Assembly-CSharp/Verse.Noise/NoiseRenderer.cs +++ b/Assembly-CSharp/Verse.Noise/NoiseRenderer.cs @@ -1,4 +1,3 @@ -using System; using UnityEngine; namespace Verse.Noise @@ -7,7 +6,7 @@ public static class NoiseRenderer { public static IntVec2 renderSize = new IntVec2(200, 200); - private static Color[] spectrum = new Color[] + private static Color[] spectrum = new Color[4] { Color.black, Color.blue, @@ -24,8 +23,9 @@ public static Texture2D NoiseRendered(CellRect rect, ModuleBase noise) { Texture2D texture2D = new Texture2D(rect.Width, rect.Height); texture2D.name = "NoiseRender"; - foreach (IntVec2 current in rect.Cells2D) + foreach (IntVec2 item in rect.Cells2D) { + IntVec2 current = item; texture2D.SetPixel(current.x, current.z, NoiseRenderer.ColorForValue(noise.GetValue(current))); } texture2D.Apply(); @@ -34,7 +34,7 @@ public static Texture2D NoiseRendered(CellRect rect, ModuleBase noise) private static Color ColorForValue(float val) { - val = val * 0.5f + 0.5f; + val = (float)(val * 0.5 + 0.5); return ColorsFromSpectrum.Get(NoiseRenderer.spectrum, val); } } diff --git a/Assembly-CSharp/Verse.Noise/OneMinus.cs b/Assembly-CSharp/Verse.Noise/OneMinus.cs index e2107d073..180ab0692 100644 --- a/Assembly-CSharp/Verse.Noise/OneMinus.cs +++ b/Assembly-CSharp/Verse.Noise/OneMinus.cs @@ -1,5 +1,3 @@ -using System; - namespace Verse.Noise { public class OneMinus : ModuleBase @@ -10,12 +8,12 @@ public OneMinus() : base(1) public OneMinus(ModuleBase module) : base(1) { - this.modules[0] = module; + base.modules[0] = module; } public override double GetValue(double x, double y, double z) { - return 1.0 - this.modules[0].GetValue(x, y, z); + return 1.0 - base.modules[0].GetValue(x, y, z); } } } diff --git a/Assembly-CSharp/Verse.Noise/Perlin.cs b/Assembly-CSharp/Verse.Noise/Perlin.cs index 01073efef..f33ff5ba7 100644 --- a/Assembly-CSharp/Verse.Noise/Perlin.cs +++ b/Assembly-CSharp/Verse.Noise/Perlin.cs @@ -1,4 +1,3 @@ -using System; using UnityEngine; namespace Verse.Noise @@ -106,7 +105,8 @@ public Perlin(double frequency, double lacunarity, double persistence, int octav public override double GetValue(double x, double y, double z) { double num = 0.0; - double num2 = 1.0; + double num2 = 0.0; + double num3 = 1.0; x *= this.m_frequency; y *= this.m_frequency; z *= this.m_frequency; @@ -115,13 +115,13 @@ public override double GetValue(double x, double y, double z) double x2 = Utils.MakeInt32Range(x); double y2 = Utils.MakeInt32Range(y); double z2 = Utils.MakeInt32Range(z); - long seed = (long)(this.m_seed + i) & (long)((ulong)-1); - double num3 = Utils.GradientCoherentNoise3D(x2, y2, z2, seed, this.m_quality); - num += num3 * num2; + long seed = this.m_seed + i & 4294967295u; + num2 = Utils.GradientCoherentNoise3D(x2, y2, z2, seed, this.m_quality); + num += num2 * num3; x *= this.m_lacunarity; y *= this.m_lacunarity; z *= this.m_lacunarity; - num2 *= this.m_persistence; + num3 *= this.m_persistence; } return num; } diff --git a/Assembly-CSharp/Verse.Noise/Power.cs b/Assembly-CSharp/Verse.Noise/Power.cs index 33489fb5a..6de5ff205 100644 --- a/Assembly-CSharp/Verse.Noise/Power.cs +++ b/Assembly-CSharp/Verse.Noise/Power.cs @@ -10,13 +10,13 @@ public Power() : base(2) public Power(ModuleBase lhs, ModuleBase rhs) : base(2) { - this.modules[0] = lhs; - this.modules[1] = rhs; + base.modules[0] = lhs; + base.modules[1] = rhs; } public override double GetValue(double x, double y, double z) { - return Math.Pow(this.modules[0].GetValue(x, y, z), this.modules[1].GetValue(x, y, z)); + return Math.Pow(base.modules[0].GetValue(x, y, z), base.modules[1].GetValue(x, y, z)); } } } diff --git a/Assembly-CSharp/Verse.Noise/PowerKeepSign.cs b/Assembly-CSharp/Verse.Noise/PowerKeepSign.cs index 814cf8c96..651d712c9 100644 --- a/Assembly-CSharp/Verse.Noise/PowerKeepSign.cs +++ b/Assembly-CSharp/Verse.Noise/PowerKeepSign.cs @@ -10,14 +10,14 @@ public PowerKeepSign() : base(2) public PowerKeepSign(ModuleBase lhs, ModuleBase rhs) : base(2) { - this.modules[0] = lhs; - this.modules[1] = rhs; + base.modules[0] = lhs; + base.modules[1] = rhs; } public override double GetValue(double x, double y, double z) { - double value = this.modules[0].GetValue(x, y, z); - return (double)Math.Sign(value) * Math.Pow(Math.Abs(value), this.modules[1].GetValue(x, y, z)); + double value = base.modules[0].GetValue(x, y, z); + return (double)Math.Sign(value) * Math.Pow(Math.Abs(value), base.modules[1].GetValue(x, y, z)); } } } diff --git a/Assembly-CSharp/Verse.Noise/QualityMode.cs b/Assembly-CSharp/Verse.Noise/QualityMode.cs index 58368ce37..3930ccb36 100644 --- a/Assembly-CSharp/Verse.Noise/QualityMode.cs +++ b/Assembly-CSharp/Verse.Noise/QualityMode.cs @@ -1,11 +1,9 @@ -using System; - namespace Verse.Noise { public enum QualityMode : byte { - Low, - Medium, - High + Low = 0, + Medium = 1, + High = 2 } } diff --git a/Assembly-CSharp/Verse.Noise/RidgedMultifractal.cs b/Assembly-CSharp/Verse.Noise/RidgedMultifractal.cs index 1e29433f1..11993be91 100644 --- a/Assembly-CSharp/Verse.Noise/RidgedMultifractal.cs +++ b/Assembly-CSharp/Verse.Noise/RidgedMultifractal.cs @@ -108,35 +108,36 @@ public override double GetValue(double x, double y, double z) y *= this.m_frequency; z *= this.m_frequency; double num = 0.0; - double num2 = 1.0; + double num2 = 0.0; double num3 = 1.0; - double num4 = 2.0; + double num4 = 1.0; + double num5 = 2.0; for (int i = 0; i < this.m_octaveCount; i++) { double x2 = Utils.MakeInt32Range(x); double y2 = Utils.MakeInt32Range(y); double z2 = Utils.MakeInt32Range(z); - long seed = (long)(this.m_seed + i & 2147483647); - double num5 = Utils.GradientCoherentNoise3D(x2, y2, z2, seed, this.m_quality); - num5 = Math.Abs(num5); - num5 = num3 - num5; - num5 *= num5; - num5 *= num2; - num2 = num5 * num4; - if (num2 > 1.0) + long seed = this.m_seed + i & 2147483647; + num = Utils.GradientCoherentNoise3D(x2, y2, z2, seed, this.m_quality); + num = Math.Abs(num); + num = num4 - num; + num *= num; + num *= num3; + num3 = num * num5; + if (num3 > 1.0) { - num2 = 1.0; + num3 = 1.0; } - if (num2 < 0.0) + if (num3 < 0.0) { - num2 = 0.0; + num3 = 0.0; } - num += num5 * this.m_weights[i]; + num2 += num * this.m_weights[i]; x *= this.m_lacunarity; y *= this.m_lacunarity; z *= this.m_lacunarity; } - return num * 1.25 - 1.0; + return num2 * 1.25 - 1.0; } } } diff --git a/Assembly-CSharp/Verse.Noise/Rotate.cs b/Assembly-CSharp/Verse.Noise/Rotate.cs index 7b7670bc7..5cd754705 100644 --- a/Assembly-CSharp/Verse.Noise/Rotate.cs +++ b/Assembly-CSharp/Verse.Noise/Rotate.cs @@ -71,12 +71,12 @@ public Rotate() : base(1) public Rotate(ModuleBase input) : base(1) { - this.modules[0] = input; + base.modules[0] = input; } public Rotate(double x, double y, double z, ModuleBase input) : base(1) { - this.modules[0] = input; + base.modules[0] = input; this.SetAngles(x, y, z); } @@ -93,8 +93,8 @@ private void SetAngles(double x, double y, double z) this.m_z1Matrix = num5 * num3 - num2 * num4 * num6; this.m_x2Matrix = num5 * num4 * num3 - num2 * num6; this.m_y2Matrix = num * num3; - this.m_z2Matrix = -num2 * num4 * num3 - num5 * num6; - this.m_x3Matrix = -num5 * num; + this.m_z2Matrix = (0.0 - num2) * num4 * num3 - num5 * num6; + this.m_x3Matrix = (0.0 - num5) * num; this.m_y3Matrix = num4; this.m_z3Matrix = num2 * num; this.m_x = x; @@ -107,7 +107,7 @@ public override double GetValue(double x, double y, double z) double x2 = this.m_x1Matrix * x + this.m_y1Matrix * y + this.m_z1Matrix * z; double y2 = this.m_x2Matrix * x + this.m_y2Matrix * y + this.m_z2Matrix * z; double z2 = this.m_x3Matrix * x + this.m_y3Matrix * y + this.m_z3Matrix * z; - return this.modules[0].GetValue(x2, y2, z2); + return base.modules[0].GetValue(x2, y2, z2); } } } diff --git a/Assembly-CSharp/Verse.Noise/Scale.cs b/Assembly-CSharp/Verse.Noise/Scale.cs index 35f108fad..97cc75ec2 100644 --- a/Assembly-CSharp/Verse.Noise/Scale.cs +++ b/Assembly-CSharp/Verse.Noise/Scale.cs @@ -1,5 +1,3 @@ -using System; - namespace Verse.Noise { public class Scale : ModuleBase @@ -52,12 +50,12 @@ public Scale() : base(1) public Scale(ModuleBase input) : base(1) { - this.modules[0] = input; + base.modules[0] = input; } public Scale(double x, double y, double z, ModuleBase input) : base(1) { - this.modules[0] = input; + base.modules[0] = input; this.X = x; this.Y = y; this.Z = z; @@ -65,7 +63,7 @@ public Scale(double x, double y, double z, ModuleBase input) : base(1) public override double GetValue(double x, double y, double z) { - return this.modules[0].GetValue(x * this.m_x, y * this.m_y, z * this.m_z); + return base.modules[0].GetValue(x * this.m_x, y * this.m_y, z * this.m_z); } } } diff --git a/Assembly-CSharp/Verse.Noise/ScaleBias.cs b/Assembly-CSharp/Verse.Noise/ScaleBias.cs index d85919592..b9eb722bc 100644 --- a/Assembly-CSharp/Verse.Noise/ScaleBias.cs +++ b/Assembly-CSharp/Verse.Noise/ScaleBias.cs @@ -1,5 +1,3 @@ -using System; - namespace Verse.Noise { public class ScaleBias : ModuleBase @@ -38,19 +36,19 @@ public ScaleBias() : base(1) public ScaleBias(ModuleBase input) : base(1) { - this.modules[0] = input; + base.modules[0] = input; } public ScaleBias(double scale, double bias, ModuleBase input) : base(1) { - this.modules[0] = input; + base.modules[0] = input; this.Bias = bias; this.Scale = scale; } public override double GetValue(double x, double y, double z) { - return this.modules[0].GetValue(x, y, z) * this.scale + this.bias; + return base.modules[0].GetValue(x, y, z) * this.scale + this.bias; } } } diff --git a/Assembly-CSharp/Verse.Noise/Select.cs b/Assembly-CSharp/Verse.Noise/Select.cs index 0f113450b..3c664bb3a 100644 --- a/Assembly-CSharp/Verse.Noise/Select.cs +++ b/Assembly-CSharp/Verse.Noise/Select.cs @@ -1,5 +1,3 @@ -using System; - namespace Verse.Noise { public class Select : ModuleBase @@ -16,11 +14,11 @@ public ModuleBase Controller { get { - return this.modules[2]; + return base.modules[2]; } set { - this.modules[2] = value; + base.modules[2] = value; } } @@ -34,7 +32,7 @@ public double FallOff { double num = this.m_max - this.m_min; this.m_raw = value; - this.m_fallOff = ((value <= num / 2.0) ? value : (num / 2.0)); + this.m_fallOff = ((!(value > num / 2.0)) ? value : (num / 2.0)); } } @@ -70,9 +68,9 @@ public Select() : base(3) public Select(ModuleBase inputA, ModuleBase inputB, ModuleBase controller) : base(3) { - this.modules[0] = inputA; - this.modules[1] = inputB; - this.modules[2] = controller; + base.modules[0] = inputA; + base.modules[1] = inputB; + base.modules[2] = controller; } public Select(double min, double max, double fallOff, ModuleBase inputA, ModuleBase inputB) : this(inputA, inputB, null) @@ -91,41 +89,38 @@ public void SetBounds(double min, double max) public override double GetValue(double x, double y, double z) { - double value = this.modules[2].GetValue(x, y, z); + double value = base.modules[2].GetValue(x, y, z); if (this.m_fallOff > 0.0) { if (value < this.m_min - this.m_fallOff) { - return this.modules[0].GetValue(x, y, z); + return base.modules[0].GetValue(x, y, z); } if (value < this.m_min + this.m_fallOff) { double num = this.m_min - this.m_fallOff; double num2 = this.m_min + this.m_fallOff; double position = Utils.MapCubicSCurve((value - num) / (num2 - num)); - return Utils.InterpolateLinear(this.modules[0].GetValue(x, y, z), this.modules[1].GetValue(x, y, z), position); + return Utils.InterpolateLinear(base.modules[0].GetValue(x, y, z), base.modules[1].GetValue(x, y, z), position); } if (value < this.m_max - this.m_fallOff) { - return this.modules[1].GetValue(x, y, z); + return base.modules[1].GetValue(x, y, z); } if (value < this.m_max + this.m_fallOff) { double num3 = this.m_max - this.m_fallOff; double num4 = this.m_max + this.m_fallOff; double position = Utils.MapCubicSCurve((value - num3) / (num4 - num3)); - return Utils.InterpolateLinear(this.modules[1].GetValue(x, y, z), this.modules[0].GetValue(x, y, z), position); + return Utils.InterpolateLinear(base.modules[1].GetValue(x, y, z), base.modules[0].GetValue(x, y, z), position); } - return this.modules[0].GetValue(x, y, z); + return base.modules[0].GetValue(x, y, z); } - else + if (!(value < this.m_min) && !(value > this.m_max)) { - if (value < this.m_min || value > this.m_max) - { - return this.modules[0].GetValue(x, y, z); - } - return this.modules[1].GetValue(x, y, z); + return base.modules[1].GetValue(x, y, z); } + return base.modules[0].GetValue(x, y, z); } } } diff --git a/Assembly-CSharp/Verse.Noise/SqueezeHorizontally.cs b/Assembly-CSharp/Verse.Noise/SqueezeHorizontally.cs index cd5c5e738..23fd2d98e 100644 --- a/Assembly-CSharp/Verse.Noise/SqueezeHorizontally.cs +++ b/Assembly-CSharp/Verse.Noise/SqueezeHorizontally.cs @@ -1,5 +1,3 @@ -using System; - namespace Verse.Noise { public class SqueezeHorizontally : ModuleBase @@ -8,13 +6,13 @@ public class SqueezeHorizontally : ModuleBase public SqueezeHorizontally(ModuleBase input, float factor) : base(1) { - this.modules[0] = input; + base.modules[0] = input; this.factor = factor; } public override double GetValue(double x, double y, double z) { - return this.modules[0].GetValue(x * (double)this.factor, y, z * (double)this.factor); + return base.modules[0].GetValue(x * (double)this.factor, y, z * (double)this.factor); } } } diff --git a/Assembly-CSharp/Verse.Noise/SqueezeVertically.cs b/Assembly-CSharp/Verse.Noise/SqueezeVertically.cs index cb8bc5923..f039290ff 100644 --- a/Assembly-CSharp/Verse.Noise/SqueezeVertically.cs +++ b/Assembly-CSharp/Verse.Noise/SqueezeVertically.cs @@ -1,5 +1,3 @@ -using System; - namespace Verse.Noise { public class SqueezeVertically : ModuleBase @@ -8,13 +6,13 @@ public class SqueezeVertically : ModuleBase public SqueezeVertically(ModuleBase input, float factor) : base(1) { - this.modules[0] = input; + base.modules[0] = input; this.factor = factor; } public override double GetValue(double x, double y, double z) { - return this.modules[0].GetValue(x, y * (double)this.factor, z); + return base.modules[0].GetValue(x, y * (double)this.factor, z); } } } diff --git a/Assembly-CSharp/Verse.Noise/Subtract.cs b/Assembly-CSharp/Verse.Noise/Subtract.cs index 7181ce0f0..6b73462aa 100644 --- a/Assembly-CSharp/Verse.Noise/Subtract.cs +++ b/Assembly-CSharp/Verse.Noise/Subtract.cs @@ -1,5 +1,3 @@ -using System; - namespace Verse.Noise { public class Subtract : ModuleBase @@ -10,13 +8,13 @@ public Subtract() : base(2) public Subtract(ModuleBase lhs, ModuleBase rhs) : base(2) { - this.modules[0] = lhs; - this.modules[1] = rhs; + base.modules[0] = lhs; + base.modules[1] = rhs; } public override double GetValue(double x, double y, double z) { - return this.modules[0].GetValue(x, y, z) - this.modules[1].GetValue(x, y, z); + return base.modules[0].GetValue(x, y, z) - base.modules[1].GetValue(x, y, z); } } } diff --git a/Assembly-CSharp/Verse.Noise/Terrace.cs b/Assembly-CSharp/Verse.Noise/Terrace.cs index 39eb5b657..bbf91d5f2 100644 --- a/Assembly-CSharp/Verse.Noise/Terrace.cs +++ b/Assembly-CSharp/Verse.Noise/Terrace.cs @@ -44,12 +44,12 @@ public Terrace() : base(1) public Terrace(ModuleBase input) : base(1) { - this.modules[0] = input; + base.modules[0] = input; } public Terrace(bool inverted, ModuleBase input) : base(1) { - this.modules[0] = input; + base.modules[0] = input; this.IsInverted = inverted; } @@ -59,7 +59,7 @@ public void Add(double input) { this.m_data.Add(input); } - this.m_data.Sort((double lhs, double rhs) => lhs.CompareTo(rhs)); + this.m_data.Sort((Comparison)((double lhs, double rhs) => lhs.CompareTo(rhs))); } public void Clear() @@ -76,7 +76,7 @@ public void Generate(int steps) this.Clear(); double num = 2.0 / ((double)steps - 1.0); double num2 = -1.0; - for (int i = 0; i < steps; i++) + for (int num3 = 0; num3 < steps; num3++) { this.Add(num2); num2 += num; @@ -85,33 +85,30 @@ public void Generate(int steps) public override double GetValue(double x, double y, double z) { - double value = this.modules[0].GetValue(x, y, z); - int i; - for (i = 0; i < this.m_data.Count; i++) + double value = base.modules[0].GetValue(x, y, z); + int num = 0; + while (num < this.m_data.Count && !(value < this.m_data[num])) { - if (value < this.m_data[i]) - { - break; - } + num++; } - int num = Mathf.Clamp(i - 1, 0, this.m_data.Count - 1); - int num2 = Mathf.Clamp(i, 0, this.m_data.Count - 1); - if (num == num2) + int num2 = Mathf.Clamp(num - 1, 0, this.m_data.Count - 1); + int num3 = Mathf.Clamp(num, 0, this.m_data.Count - 1); + if (num2 == num3) { - return this.m_data[num2]; + return this.m_data[num3]; } - double num3 = this.m_data[num]; double num4 = this.m_data[num2]; - double num5 = (value - num3) / (num4 - num3); + double num5 = this.m_data[num3]; + double num6 = (value - num4) / (num5 - num4); if (this.m_inverted) { - num5 = 1.0 - num5; - double num6 = num3; - num3 = num4; - num4 = num6; + num6 = 1.0 - num6; + double num7 = num4; + num4 = num5; + num5 = num7; } - num5 *= num5; - return Utils.InterpolateLinear(num3, num4, num5); + num6 *= num6; + return Utils.InterpolateLinear(num4, num5, num6); } } } diff --git a/Assembly-CSharp/Verse.Noise/Translate.cs b/Assembly-CSharp/Verse.Noise/Translate.cs index a072ba5f5..63c8e858d 100644 --- a/Assembly-CSharp/Verse.Noise/Translate.cs +++ b/Assembly-CSharp/Verse.Noise/Translate.cs @@ -1,5 +1,3 @@ -using System; - namespace Verse.Noise { public class Translate : ModuleBase @@ -52,12 +50,12 @@ public Translate() : base(1) public Translate(ModuleBase input) : base(1) { - this.modules[0] = input; + base.modules[0] = input; } public Translate(double x, double y, double z, ModuleBase input) : base(1) { - this.modules[0] = input; + base.modules[0] = input; this.X = x; this.Y = y; this.Z = z; @@ -65,7 +63,7 @@ public Translate(double x, double y, double z, ModuleBase input) : base(1) public override double GetValue(double x, double y, double z) { - return this.modules[0].GetValue(x + this.m_x, y + this.m_y, z + this.m_z); + return base.modules[0].GetValue(x + this.m_x, y + this.m_y, z + this.m_z); } } } diff --git a/Assembly-CSharp/Verse.Noise/Turbulence.cs b/Assembly-CSharp/Verse.Noise/Turbulence.cs index fa6dff6de..6c191682b 100644 --- a/Assembly-CSharp/Verse.Noise/Turbulence.cs +++ b/Assembly-CSharp/Verse.Noise/Turbulence.cs @@ -1,5 +1,3 @@ -using System; - namespace Verse.Noise { public class Turbulence : ModuleBase @@ -96,7 +94,7 @@ public Turbulence(ModuleBase input) : base(1) this.m_xDistort = new Perlin(); this.m_yDistort = new Perlin(); this.m_zDistort = new Perlin(); - this.modules[0] = input; + base.modules[0] = input; } public Turbulence(double power, ModuleBase input) : this(new Perlin(), new Perlin(), new Perlin(), power, input) @@ -108,7 +106,7 @@ public Turbulence(Perlin x, Perlin y, Perlin z, double power, ModuleBase input) this.m_xDistort = x; this.m_yDistort = y; this.m_zDistort = z; - this.modules[0] = input; + base.modules[0] = input; this.Power = power; } @@ -117,7 +115,7 @@ public override double GetValue(double x, double y, double z) double x2 = x + this.m_xDistort.GetValue(x + 0.189422607421875, y + 0.99371337890625, z + 0.4781646728515625) * this.m_power; double y2 = y + this.m_yDistort.GetValue(x + 0.4046478271484375, y + 0.276611328125, z + 0.9230499267578125) * this.m_power; double z2 = z + this.m_zDistort.GetValue(x + 0.82122802734375, y + 0.1710968017578125, z + 0.6842803955078125) * this.m_power; - return this.modules[0].GetValue(x2, y2, z2); + return base.modules[0].GetValue(x2, y2, z2); } } } diff --git a/Assembly-CSharp/Verse.Noise/Utils.cs b/Assembly-CSharp/Verse.Noise/Utils.cs index bde05716c..61fb4baac 100644 --- a/Assembly-CSharp/Verse.Noise/Utils.cs +++ b/Assembly-CSharp/Verse.Noise/Utils.cs @@ -20,7 +20,7 @@ internal static class Utils private const int GeneratorShift = 8; - internal static double[] _randoms = new double[] + internal static double[] _randoms = new double[1024] { -0.763874, -0.596439, @@ -1050,11 +1050,11 @@ internal static class Utils internal static double GradientCoherentNoise3D(double x, double y, double z, long seed, QualityMode quality) { - int num = (x <= 0.0) ? ((int)x - 1) : ((int)x); + int num = (!(x > 0.0)) ? ((int)x - 1) : ((int)x); int ix = num + 1; - int num2 = (y <= 0.0) ? ((int)y - 1) : ((int)y); + int num2 = (!(y > 0.0)) ? ((int)y - 1) : ((int)y); int iy = num2 + 1; - int num3 = (z <= 0.0) ? ((int)z - 1) : ((int)z); + int num3 = (!(z > 0.0)) ? ((int)z - 1) : ((int)z); int iz = num3 + 1; double position = 0.0; double position2 = 0.0; @@ -1062,21 +1062,27 @@ internal static double GradientCoherentNoise3D(double x, double y, double z, lon switch (quality) { case QualityMode.Low: + { position = x - (double)num; position2 = y - (double)num2; position3 = z - (double)num3; break; + } case QualityMode.Medium: + { position = Utils.MapCubicSCurve(x - (double)num); position2 = Utils.MapCubicSCurve(y - (double)num2); position3 = Utils.MapCubicSCurve(z - (double)num3); break; + } case QualityMode.High: + { position = Utils.MapQuinticSCurve(x - (double)num); position2 = Utils.MapQuinticSCurve(y - (double)num2); position3 = Utils.MapQuinticSCurve(z - (double)num3); break; } + } double a = Utils.GradientNoise3D(x, y, z, num, num2, num3, seed); double b = Utils.GradientNoise3D(x, y, z, ix, num2, num3, seed); double a2 = Utils.InterpolateLinear(a, b, position); @@ -1096,18 +1102,12 @@ internal static double GradientCoherentNoise3D(double x, double y, double z, lon internal static double GradientNoise3D(double fx, double fy, double fz, int ix, int iy, int iz, long seed) { - long num = (long)(1619 * ix + 31337 * iy + 6971 * iz) + 1013L * seed & (long)((ulong)-1); + long num = 1619 * ix + 31337 * iy + 6971 * iz + 1013 * seed & 4294967295u; num ^= num >> 8; - num &= 255L; - double num2; - double num3; - double num4; - checked - { - num2 = Utils._randoms[(int)((IntPtr)(num << 2))]; - num3 = Utils._randoms[(int)((IntPtr)(unchecked((num << 2) + 1L)))]; - num4 = Utils._randoms[(int)((IntPtr)(unchecked((num << 2) + 2L)))]; - } + num &= 255; + double num2 = Utils._randoms[num << 2]; + double num3 = Utils._randoms[(num << 2) + 1]; + double num4 = Utils._randoms[(num << 2) + 2]; double num5 = fx - (double)ix; double num6 = fy - (double)iy; double num7 = fz - (double)iz; @@ -1160,9 +1160,9 @@ internal static double ValueNoise3D(int x, int y, int z, int seed) internal static long ValueNoise3DInt(int x, int y, int z, int seed) { - long num = (long)(1619 * x + 31337 * y + 6971 * z + 1013 * seed & 2147483647); + long num = 1619 * x + 31337 * y + 6971 * z + 1013 * seed & 2147483647; num = (num >> 13 ^ num); - return num * (num * num * 60493L + 19990303L) + 1376312589L & 2147483647L; + return num * (num * num * 60493 + 19990303) + 1376312589 & 2147483647; } } } diff --git a/Assembly-CSharp/Verse.Noise/Voronoi.cs b/Assembly-CSharp/Verse.Noise/Voronoi.cs index aa02324c5..ef0e8b2f3 100644 --- a/Assembly-CSharp/Verse.Noise/Voronoi.cs +++ b/Assembly-CSharp/Verse.Noise/Voronoi.cs @@ -78,9 +78,9 @@ public override double GetValue(double x, double y, double z) x *= this.m_frequency; y *= this.m_frequency; z *= this.m_frequency; - int num = (x <= 0.0) ? ((int)x - 1) : ((int)x); - int num2 = (y <= 0.0) ? ((int)y - 1) : ((int)y); - int num3 = (z <= 0.0) ? ((int)z - 1) : ((int)z); + int num = (!(x > 0.0)) ? ((int)x - 1) : ((int)x); + int num2 = (!(y > 0.0)) ? ((int)y - 1) : ((int)y); + int num3 = (!(z > 0.0)) ? ((int)z - 1) : ((int)z); double num4 = 2147483647.0; double num5 = 0.0; double num6 = 0.0; diff --git a/Assembly-CSharp/Verse.Profile/MemoryTracker.cs b/Assembly-CSharp/Verse.Profile/MemoryTracker.cs index caf90eea7..4543ae205 100644 --- a/Assembly-CSharp/Verse.Profile/MemoryTracker.cs +++ b/Assembly-CSharp/Verse.Profile/MemoryTracker.cs @@ -1,6 +1,6 @@ using System; +using System.Collections; using System.Collections.Generic; -using System.Diagnostics; using System.Linq; using System.Reflection; using System.Text; @@ -16,14 +16,14 @@ public struct Link { public object target; - public MemoryTracker.ReferenceData targetRef; + public ReferenceData targetRef; public string path; } - public List refers = new List(); + public List refers = new List(); - public List referredBy = new List(); + public List referredBy = new List(); public string path; @@ -60,16 +60,18 @@ public static void RegisterObject(object obj) if (MemoryTracker.trackedLocked) { MemoryTracker.trackedQueue.Add(obj); - return; } - Type type = obj.GetType(); - HashSet hashSet = null; - if (!MemoryTracker.tracked.TryGetValue(type, out hashSet)) + else { - hashSet = new HashSet(); - MemoryTracker.tracked[type] = hashSet; + Type type = obj.GetType(); + HashSet hashSet = null; + if (!MemoryTracker.tracked.TryGetValue(type, out hashSet)) + { + hashSet = new HashSet(); + MemoryTracker.tracked[type] = hashSet; + } + hashSet.Add(new WeakReference(obj)); } - hashSet.Add(new WeakReference(obj)); } public static void RegisterType(RuntimeTypeHandle typeHandle) @@ -77,12 +79,14 @@ public static void RegisterType(RuntimeTypeHandle typeHandle) if (MemoryTracker.trackedLocked) { MemoryTracker.trackedTypeQueue.Add(typeHandle); - return; } - Type typeFromHandle = Type.GetTypeFromHandle(typeHandle); - if (!MemoryTracker.tracked.ContainsKey(typeFromHandle)) + else { - MemoryTracker.tracked[typeFromHandle] = new HashSet(); + Type typeFromHandle = Type.GetTypeFromHandle(typeHandle); + if (!MemoryTracker.tracked.ContainsKey(typeFromHandle)) + { + MemoryTracker.tracked[typeFromHandle] = new HashSet(); + } } } @@ -102,14 +106,32 @@ private static void UnlockTracking() throw new NotImplementedException(); } MemoryTracker.trackedLocked = false; - foreach (object current in MemoryTracker.trackedQueue) + List.Enumerator enumerator = MemoryTracker.trackedQueue.GetEnumerator(); + try + { + while (enumerator.MoveNext()) + { + object current = enumerator.Current; + MemoryTracker.RegisterObject(current); + } + } + finally { - MemoryTracker.RegisterObject(current); + ((IDisposable)(object)enumerator).Dispose(); } MemoryTracker.trackedQueue.Clear(); - foreach (RuntimeTypeHandle current2 in MemoryTracker.trackedTypeQueue) + List.Enumerator enumerator2 = MemoryTracker.trackedTypeQueue.GetEnumerator(); + try + { + while (enumerator2.MoveNext()) + { + RuntimeTypeHandle current2 = enumerator2.Current; + MemoryTracker.RegisterType(current2); + } + } + finally { - MemoryTracker.RegisterType(current2); + ((IDisposable)(object)enumerator2).Dispose(); } MemoryTracker.trackedTypeQueue.Clear(); } @@ -119,28 +141,39 @@ public static void LogObjectsLoaded() if (MemoryTracker.tracked.Count == 0) { Log.Message("No objects tracked, memory tracker markup may not be applied."); - return; } - GC.Collect(); - MemoryTracker.LockTracking(); - try + else { - foreach (HashSet current in MemoryTracker.tracked.Values) + GC.Collect(); + MemoryTracker.LockTracking(); + try { - MemoryTracker.CullNulls(current); + Dictionary>.ValueCollection.Enumerator enumerator = MemoryTracker.tracked.Values.GetEnumerator(); + try + { + while (enumerator.MoveNext()) + { + HashSet current = enumerator.Current; + MemoryTracker.CullNulls(current); + } + } + finally + { + ((IDisposable)(object)enumerator).Dispose(); + } + StringBuilder stringBuilder = new StringBuilder(); + foreach (KeyValuePair> item in from kvp in MemoryTracker.tracked + orderby -kvp.Value.Count + select kvp) + { + stringBuilder.AppendLine(string.Format("{0,6} {1}", item.Value.Count, item.Key)); + } + Log.Message(stringBuilder.ToString()); } - StringBuilder stringBuilder = new StringBuilder(); - foreach (KeyValuePair> current2 in from kvp in MemoryTracker.tracked - orderby -kvp.Value.Count - select kvp) + finally { - stringBuilder.AppendLine(string.Format("{0,6} {1}", current2.Value.Count, current2.Key)); + MemoryTracker.UnlockTracking(); } - Log.Message(stringBuilder.ToString()); - } - finally - { - MemoryTracker.UnlockTracking(); } } @@ -149,36 +182,45 @@ public static void LogObjectHoldPaths() if (MemoryTracker.tracked.Count == 0) { Log.Message("No objects tracked, memory tracker markup may not be applied."); - return; } - GC.Collect(); - MemoryTracker.LockTracking(); - try + else { - foreach (HashSet current in MemoryTracker.tracked.Values) - { - MemoryTracker.CullNulls(current); - } - List list = new List(); - foreach (KeyValuePair> current2 in from kvp in MemoryTracker.tracked - orderby -kvp.Value.Count - select kvp) + GC.Collect(); + MemoryTracker.LockTracking(); + try { - KeyValuePair> elementLocal = current2; - list.Add(new FloatMenuOption(string.Format("{0} ({1})", current2.Key, current2.Value.Count), delegate + Dictionary>.ValueCollection.Enumerator enumerator = MemoryTracker.tracked.Values.GetEnumerator(); + try + { + while (enumerator.MoveNext()) + { + HashSet current = enumerator.Current; + MemoryTracker.CullNulls(current); + } + } + finally { - MemoryTracker.LogObjectHoldPathsFor(elementLocal.Key, elementLocal.Value); - }, MenuOptionPriority.Default, null, null, 0f, null, null)); - if (list.Count == 30) + ((IDisposable)(object)enumerator).Dispose(); + } + List list = new List(); + foreach (KeyValuePair> item in from kvp in MemoryTracker.tracked + orderby -kvp.Value.Count + select kvp) { - break; + KeyValuePair> elementLocal = item; + list.Add(new FloatMenuOption(string.Format("{0} ({1})", item.Key, item.Value.Count), (Action)delegate + { + MemoryTracker.LogObjectHoldPathsFor(elementLocal.Key, elementLocal.Value); + }, MenuOptionPriority.Default, null, null, 0f, null, null)); + if (list.Count == 30) + break; } + Find.WindowStack.Add(new FloatMenu(list)); + } + finally + { + MemoryTracker.UnlockTracking(); } - Find.WindowStack.Add(new FloatMenu(list)); - } - finally - { - MemoryTracker.UnlockTracking(); } } @@ -188,27 +230,24 @@ public static void LogObjectHoldPathsFor(Type type, HashSet eleme MemoryTracker.LockTracking(); try { - Dictionary dictionary = new Dictionary(); + Dictionary dictionary = new Dictionary(); HashSet hashSet = new HashSet(); Queue queue = new Queue(); - foreach (object current in from weakref in MemoryTracker.tracked.SelectMany((KeyValuePair> kvp) => kvp.Value) + foreach (object item in from weakref in MemoryTracker.tracked.SelectMany((Func>, IEnumerable>)((KeyValuePair> kvp) => kvp.Value)) where weakref.IsAlive select weakref.Target) { - if (!hashSet.Contains(current)) + if (!hashSet.Contains(item)) { - hashSet.Add(current); - queue.Enqueue(current); + hashSet.Add(item); + queue.Enqueue(item); } } - foreach (Type current2 in GenTypes.AllTypes.Union(MemoryTracker.tracked.Keys)) + foreach (Type item2 in GenTypes.AllTypes.Union(MemoryTracker.tracked.Keys)) { - if (!current2.FullName.Contains("MemoryTracker")) + if (!item2.FullName.Contains("MemoryTracker") && !item2.ContainsGenericParameters) { - if (!current2.ContainsGenericParameters) - { - MemoryTracker.AccumulateStaticMembers(current2, dictionary, hashSet, queue); - } + MemoryTracker.AccumulateStaticMembers(item2, dictionary, hashSet, queue); } } int num = 0; @@ -216,12 +255,7 @@ where weakref.IsAlive { if (num % 10000 == 0) { - UnityEngine.Debug.LogFormat("{0} / {1} (to process: {2})", new object[] - { - num, - num + queue.Count, - queue.Count - }); + Debug.LogFormat("{0} / {1} (to process: {2})", num, num + queue.Count, queue.Count); } num++; MemoryTracker.AccumulateReferences(queue.Dequeue(), dictionary, hashSet, queue); @@ -234,43 +268,52 @@ where weakref.IsAlive MemoryTracker.CalculateReferencePaths(dictionary, from kvp in dictionary where kvp.Value.path.NullOrEmpty() && kvp.Value.referredBy.Count == 0 select kvp.Key, num2); - foreach (object current3 in from kvp in dictionary + foreach (object item3 in from kvp in dictionary where kvp.Value.path.NullOrEmpty() select kvp.Key) { num2 += 1000; - MemoryTracker.CalculateReferencePaths(dictionary, new object[] + MemoryTracker.CalculateReferencePaths(dictionary, new object[1] { - current3 + item3 }, num2); } Dictionary dictionary2 = new Dictionary(); - foreach (WeakReference current4 in elements) + HashSet.Enumerator enumerator4 = elements.GetEnumerator(); + try { - if (current4.IsAlive) + while (enumerator4.MoveNext()) { - string path = dictionary[current4.Target].path; - if (dictionary2.ContainsKey(path)) - { - Dictionary dictionary3; - Dictionary expr_34D = dictionary3 = dictionary2; - string key; - string expr_352 = key = path; - int num3 = dictionary3[key]; - expr_34D[expr_352] = num3 + 1; - } - else + WeakReference current4 = enumerator4.Current; + if (current4.IsAlive) { - dictionary2[path] = 1; + string path = dictionary[current4.Target].path; + if (dictionary2.ContainsKey(path)) + { + Dictionary dictionary3; + Dictionary obj = dictionary3 = dictionary2; + string key; + string key2 = key = path; + int num3 = dictionary3[key]; + obj[key2] = num3 + 1; + } + else + { + dictionary2[path] = 1; + } } } } + finally + { + ((IDisposable)(object)enumerator4).Dispose(); + } StringBuilder stringBuilder = new StringBuilder(); - foreach (KeyValuePair current5 in from kvp in dictionary2 + foreach (KeyValuePair item4 in from kvp in dictionary2 orderby -kvp.Value select kvp) { - stringBuilder.AppendLine(string.Format("{0}: {1}", current5.Value, current5.Key)); + stringBuilder.AppendLine(string.Format("{0}: {1}", item4.Value, item4.Key)); } Log.Message(stringBuilder.ToString()); } @@ -280,129 +323,169 @@ where kvp.Value.path.NullOrEmpty() } } - private static void AccumulateReferences(object obj, Dictionary references, HashSet seen, Queue toProcess) + private static void AccumulateReferences(object obj, Dictionary references, HashSet seen, Queue toProcess) { - MemoryTracker.ReferenceData referenceData = null; + ReferenceData referenceData = null; if (!references.TryGetValue(obj, out referenceData)) { - referenceData = new MemoryTracker.ReferenceData(); + referenceData = new ReferenceData(); references[obj] = referenceData; } - foreach (MemoryTracker.ChildReference current in MemoryTracker.GetAllReferencedClassesFromClassOrStruct(obj, MemoryTracker.GetFieldsFromHierarchy(obj.GetType(), BindingFlags.Instance), obj, string.Empty)) + using (IEnumerator enumerator = MemoryTracker.GetAllReferencedClassesFromClassOrStruct(obj, MemoryTracker.GetFieldsFromHierarchy(obj.GetType(), BindingFlags.Instance), obj, string.Empty).GetEnumerator()) { - if (!current.child.GetType().IsClass) + while (true) { - throw new ApplicationException(); + if (enumerator.MoveNext()) + { + ChildReference current = enumerator.Current; + if (current.child.GetType().IsClass) + { + ReferenceData referenceData2 = null; + if (!references.TryGetValue(current.child, out referenceData2)) + { + referenceData2 = new ReferenceData(); + references[current.child] = referenceData2; + } + referenceData2.referredBy.Add(new ReferenceData.Link + { + target = obj, + targetRef = referenceData, + path = current.path + }); + referenceData.refers.Add(new ReferenceData.Link + { + target = current.child, + targetRef = referenceData2, + path = current.path + }); + if (!seen.Contains(current.child)) + { + seen.Add(current.child); + toProcess.Enqueue(current.child); + } + continue; + } + break; + } + return; } - MemoryTracker.ReferenceData referenceData2 = null; - if (!references.TryGetValue(current.child, out referenceData2)) + throw new ApplicationException(); + } + } + + private static void AccumulateStaticMembers(Type type, Dictionary references, HashSet seen, Queue toProcess) + { + using (IEnumerator enumerator = MemoryTracker.GetAllReferencedClassesFromClassOrStruct(null, MemoryTracker.GetFields(type, BindingFlags.Static), null, type.ToString() + ".").GetEnumerator()) + { + while (true) { - referenceData2 = new MemoryTracker.ReferenceData(); - references[current.child] = referenceData2; + if (enumerator.MoveNext()) + { + ChildReference current = enumerator.Current; + if (current.child.GetType().IsClass) + { + ReferenceData referenceData = null; + if (!references.TryGetValue(current.child, out referenceData)) + { + referenceData = new ReferenceData(); + referenceData.path = current.path; + referenceData.pathCost = 0; + references[current.child] = referenceData; + } + if (!seen.Contains(current.child)) + { + seen.Add(current.child); + toProcess.Enqueue(current.child); + } + continue; + } + break; + } + return; } - referenceData2.referredBy.Add(new MemoryTracker.ReferenceData.Link - { - target = obj, - targetRef = referenceData, - path = current.path - }); - referenceData.refers.Add(new MemoryTracker.ReferenceData.Link + throw new ApplicationException(); + } + } + + private static IEnumerable GetAllReferencedClassesFromClassOrStruct(object current, IEnumerable fields, object parent, string currentPath) + { + foreach (FieldInfo item in fields) + { + if (!item.FieldType.IsPrimitive) { - target = current.child, - targetRef = referenceData2, - path = current.path - }); - if (!seen.Contains(current.child)) + object referenced = item.GetValue(current); + if (referenced != null) + { + foreach (ChildReference item2 in MemoryTracker.DistillChildReferencesFromObject(referenced, parent, currentPath + item.Name)) + { + yield return item2; + } + } + } + } + if (current != null && current is ICollection) + { + foreach (object item3 in current as IEnumerable) { - seen.Add(current.child); - toProcess.Enqueue(current.child); + if (item3 != null && !item3.GetType().IsPrimitive) + { + foreach (ChildReference item4 in MemoryTracker.DistillChildReferencesFromObject(item3, parent, currentPath + "[]")) + { + yield return item4; + } + } } } } - private static void AccumulateStaticMembers(Type type, Dictionary references, HashSet seen, Queue toProcess) + private static IEnumerable DistillChildReferencesFromObject(object current, object parent, string currentPath) { - foreach (MemoryTracker.ChildReference current in MemoryTracker.GetAllReferencedClassesFromClassOrStruct(null, MemoryTracker.GetFields(type, BindingFlags.Static), null, type.ToString() + ".")) + Type type = current.GetType(); + if (type.IsClass) { - if (!current.child.GetType().IsClass) + yield return new ChildReference { - throw new ApplicationException(); - } - MemoryTracker.ReferenceData referenceData = null; - if (!references.TryGetValue(current.child, out referenceData)) + child = current, + path = currentPath + }; + } + else if (!type.IsPrimitive) + { + if (!type.IsValueType) { - referenceData = new MemoryTracker.ReferenceData(); - referenceData.path = current.path; - referenceData.pathCost = 0; - references[current.child] = referenceData; + throw new NotImplementedException(); } - if (!seen.Contains(current.child)) + string structPath = currentPath + "."; + foreach (ChildReference item in MemoryTracker.GetAllReferencedClassesFromClassOrStruct(current, MemoryTracker.GetFieldsFromHierarchy(type, BindingFlags.Instance), parent, structPath)) { - seen.Add(current.child); - toProcess.Enqueue(current.child); + yield return item; } } } - [DebuggerHidden] - private static IEnumerable GetAllReferencedClassesFromClassOrStruct(object current, IEnumerable fields, object parent, string currentPath) - { - MemoryTracker.c__Iterator220 c__Iterator = new MemoryTracker.c__Iterator220(); - c__Iterator.fields = fields; - c__Iterator.current = current; - c__Iterator.parent = parent; - c__Iterator.currentPath = currentPath; - c__Iterator.<$>fields = fields; - c__Iterator.<$>current = current; - c__Iterator.<$>parent = parent; - c__Iterator.<$>currentPath = currentPath; - MemoryTracker.c__Iterator220 expr_3F = c__Iterator; - expr_3F.$PC = -2; - return expr_3F; - } - - [DebuggerHidden] - private static IEnumerable DistillChildReferencesFromObject(object current, object parent, string currentPath) - { - MemoryTracker.c__Iterator221 c__Iterator = new MemoryTracker.c__Iterator221(); - c__Iterator.current = current; - c__Iterator.currentPath = currentPath; - c__Iterator.parent = parent; - c__Iterator.<$>current = current; - c__Iterator.<$>currentPath = currentPath; - c__Iterator.<$>parent = parent; - MemoryTracker.c__Iterator221 expr_31 = c__Iterator; - expr_31.$PC = -2; - return expr_31; - } - - [DebuggerHidden] private static IEnumerable GetFieldsFromHierarchy(Type type, BindingFlags bindingFlags) { - MemoryTracker.c__Iterator222 c__Iterator = new MemoryTracker.c__Iterator222(); - c__Iterator.type = type; - c__Iterator.bindingFlags = bindingFlags; - c__Iterator.<$>type = type; - c__Iterator.<$>bindingFlags = bindingFlags; - MemoryTracker.c__Iterator222 expr_23 = c__Iterator; - expr_23.$PC = -2; - return expr_23; + while (type != null) + { + foreach (FieldInfo field in MemoryTracker.GetFields(type, bindingFlags)) + { + yield return field; + } + type = type.BaseType; + } } - [DebuggerHidden] private static IEnumerable GetFields(Type type, BindingFlags bindingFlags) { - MemoryTracker.c__Iterator223 c__Iterator = new MemoryTracker.c__Iterator223(); - c__Iterator.type = type; - c__Iterator.bindingFlags = bindingFlags; - c__Iterator.<$>type = type; - c__Iterator.<$>bindingFlags = bindingFlags; - MemoryTracker.c__Iterator223 expr_23 = c__Iterator; - expr_23.$PC = -2; - return expr_23; + FieldInfo[] fields = type.GetFields((BindingFlags)((int)bindingFlags | 16 | 32)); + for (int i = 0; i < fields.Length; i++) + { + FieldInfo field = fields[i]; + yield return field; + } } - private static void CalculateReferencePaths(Dictionary references, IEnumerable objects, int pathCost) + private static void CalculateReferencePaths(Dictionary references, IEnumerable objects, int pathCost) { Queue queue = new Queue(objects); while (queue.Count > 0) @@ -417,38 +500,47 @@ private static void CalculateReferencePaths(Dictionary references, Queue queue) + private static void CalculateObjectReferencePath(object obj, Dictionary references, Queue queue) { - MemoryTracker.ReferenceData referenceData = references[obj]; - foreach (MemoryTracker.ReferenceData.Link current in referenceData.refers) + ReferenceData referenceData = references[obj]; + List.Enumerator enumerator = referenceData.refers.GetEnumerator(); + try { - MemoryTracker.ReferenceData referenceData2 = references[current.target]; - string text = referenceData.path + "." + current.path; - int num = referenceData.pathCost + 1; - if (referenceData2.path.NullOrEmpty()) + while (true) { - queue.Enqueue(current.target); - referenceData2.path = text; - referenceData2.pathCost = num; - } - else if (referenceData2.pathCost == num && referenceData2.path.CompareTo(text) < 0) - { - referenceData2.path = text; - } - else if (referenceData2.pathCost > num) - { - throw new ApplicationException(); + if (enumerator.MoveNext()) + { + ReferenceData.Link current = enumerator.Current; + ReferenceData referenceData2 = references[current.target]; + string text = referenceData.path + "." + current.path; + int num = referenceData.pathCost + 1; + if (referenceData2.path.NullOrEmpty()) + { + queue.Enqueue(current.target); + referenceData2.path = text; + referenceData2.pathCost = num; + } + else if (referenceData2.pathCost == num && referenceData2.path.CompareTo(text) < 0) + { + referenceData2.path = text; + } + else if (referenceData2.pathCost > num) + break; + continue; + } + return; } + throw new ApplicationException(); + } + finally + { + ((IDisposable)(object)enumerator).Dispose(); } } public static void Update() { - if (MemoryTracker.tracked.Count == 0) - { - return; - } - if (MemoryTracker.updatesSinceLastCull++ >= 10) + if (MemoryTracker.tracked.Count != 0 && MemoryTracker.updatesSinceLastCull++ >= 10) { MemoryTracker.updatesSinceLastCull = 0; KeyValuePair> keyValuePair = MemoryTracker.tracked.ElementAtOrDefault(MemoryTracker.cullTargetIndex++); @@ -465,7 +557,7 @@ public static void Update() private static void CullNulls(HashSet table) { - table.RemoveWhere((WeakReference element) => !element.IsAlive); + table.RemoveWhere((Predicate)((WeakReference element) => !element.IsAlive)); } } } diff --git a/Assembly-CSharp/Verse.Profile/MemoryUtility.cs b/Assembly-CSharp/Verse.Profile/MemoryUtility.cs index b8816cf58..0c55107f2 100644 --- a/Assembly-CSharp/Verse.Profile/MemoryUtility.cs +++ b/Assembly-CSharp/Verse.Profile/MemoryUtility.cs @@ -10,7 +10,7 @@ public static class MemoryUtility { public static void UnloadUnusedUnityAssets() { - LongEventHandler.ExecuteWhenFinished(delegate + LongEventHandler.ExecuteWhenFinished((Action)delegate { Resources.UnloadUnusedAssets(); }); @@ -33,7 +33,7 @@ public static void ClearAllMapsAndWorld() } } maps.Clear(); - Current.Game.visibleMapIndex = -1; + Current.Game.visibleMapIndex = (sbyte)(-1); } if (Find.World != null) { diff --git a/Assembly-CSharp/Verse.Sound/AudioGrain.cs b/Assembly-CSharp/Verse.Sound/AudioGrain.cs index fd6078afb..5ff3a75c9 100644 --- a/Assembly-CSharp/Verse.Sound/AudioGrain.cs +++ b/Assembly-CSharp/Verse.Sound/AudioGrain.cs @@ -1,4 +1,3 @@ -using System; using System.Collections.Generic; namespace Verse.Sound diff --git a/Assembly-CSharp/Verse.Sound/AudioGrain_Clip.cs b/Assembly-CSharp/Verse.Sound/AudioGrain_Clip.cs index ca1b5f97c..309fde27b 100644 --- a/Assembly-CSharp/Verse.Sound/AudioGrain_Clip.cs +++ b/Assembly-CSharp/Verse.Sound/AudioGrain_Clip.cs @@ -1,6 +1,5 @@ -using System; using System.Collections.Generic; -using System.Diagnostics; +using UnityEngine; namespace Verse.Sound { @@ -8,14 +7,17 @@ public class AudioGrain_Clip : AudioGrain { public string clipPath = string.Empty; - [DebuggerHidden] public override IEnumerable GetResolvedGrains() { - AudioGrain_Clip.c__Iterator1DB c__Iterator1DB = new AudioGrain_Clip.c__Iterator1DB(); - c__Iterator1DB.<>f__this = this; - AudioGrain_Clip.c__Iterator1DB expr_0E = c__Iterator1DB; - expr_0E.$PC = -2; - return expr_0E; + AudioClip clip = ContentFinder.Get(this.clipPath, true); + if ((Object)clip != (Object)null) + { + yield return (ResolvedGrain)new ResolvedGrain_Clip(clip); + } + else + { + Log.Error("Grain couldn't resolve: Clip not found at " + this.clipPath); + } } } } diff --git a/Assembly-CSharp/Verse.Sound/AudioGrain_Folder.cs b/Assembly-CSharp/Verse.Sound/AudioGrain_Folder.cs index 0c701c348..ffef324d0 100644 --- a/Assembly-CSharp/Verse.Sound/AudioGrain_Folder.cs +++ b/Assembly-CSharp/Verse.Sound/AudioGrain_Folder.cs @@ -1,6 +1,5 @@ -using System; using System.Collections.Generic; -using System.Diagnostics; +using UnityEngine; namespace Verse.Sound { @@ -9,14 +8,12 @@ public class AudioGrain_Folder : AudioGrain [LoadAlias("clipPath")] public string clipFolderPath = string.Empty; - [DebuggerHidden] public override IEnumerable GetResolvedGrains() { - AudioGrain_Folder.c__Iterator1DC c__Iterator1DC = new AudioGrain_Folder.c__Iterator1DC(); - c__Iterator1DC.<>f__this = this; - AudioGrain_Folder.c__Iterator1DC expr_0E = c__Iterator1DC; - expr_0E.$PC = -2; - return expr_0E; + foreach (AudioClip item in ContentFinder.GetAllInFolder(this.clipFolderPath)) + { + yield return (ResolvedGrain)new ResolvedGrain_Clip(item); + } } } } diff --git a/Assembly-CSharp/Verse.Sound/AudioGrain_Silence.cs b/Assembly-CSharp/Verse.Sound/AudioGrain_Silence.cs index 07bbad7df..da32e891c 100644 --- a/Assembly-CSharp/Verse.Sound/AudioGrain_Silence.cs +++ b/Assembly-CSharp/Verse.Sound/AudioGrain_Silence.cs @@ -1,6 +1,4 @@ -using System; using System.Collections.Generic; -using System.Diagnostics; namespace Verse.Sound { @@ -9,14 +7,9 @@ public class AudioGrain_Silence : AudioGrain [EditSliderRange(0f, 5f)] public FloatRange durationRange = new FloatRange(1f, 2f); - [DebuggerHidden] public override IEnumerable GetResolvedGrains() { - AudioGrain_Silence.c__Iterator1DD c__Iterator1DD = new AudioGrain_Silence.c__Iterator1DD(); - c__Iterator1DD.<>f__this = this; - AudioGrain_Silence.c__Iterator1DD expr_0E = c__Iterator1DD; - expr_0E.$PC = -2; - return expr_0E; + yield return (ResolvedGrain)new ResolvedGrain_Silence(this); } public override int GetHashCode() diff --git a/Assembly-CSharp/Verse.Sound/AudioSourceMaker.cs b/Assembly-CSharp/Verse.Sound/AudioSourceMaker.cs index 3c8a75b7f..d8b5aa3ee 100644 --- a/Assembly-CSharp/Verse.Sound/AudioSourceMaker.cs +++ b/Assembly-CSharp/Verse.Sound/AudioSourceMaker.cs @@ -1,4 +1,3 @@ -using System; using UnityEngine; namespace Verse.Sound @@ -9,7 +8,7 @@ public static class AudioSourceMaker public static AudioSource NewAudioSourceOn(GameObject go) { - if (go.GetComponent() != null) + if ((Object)go.GetComponent() != (Object)null) { Log.Warning("Adding audio source on " + go + " that already has one."); return go.GetComponent(); diff --git a/Assembly-CSharp/Verse.Sound/AudioSourcePool.cs b/Assembly-CSharp/Verse.Sound/AudioSourcePool.cs index c4784cbcb..44b889418 100644 --- a/Assembly-CSharp/Verse.Sound/AudioSourcePool.cs +++ b/Assembly-CSharp/Verse.Sound/AudioSourcePool.cs @@ -1,4 +1,3 @@ -using System; using UnityEngine; namespace Verse.Sound diff --git a/Assembly-CSharp/Verse.Sound/AudioSourcePoolCamera.cs b/Assembly-CSharp/Verse.Sound/AudioSourcePoolCamera.cs index 7d91d5cdb..2e7b168ad 100644 --- a/Assembly-CSharp/Verse.Sound/AudioSourcePoolCamera.cs +++ b/Assembly-CSharp/Verse.Sound/AudioSourcePoolCamera.cs @@ -1,4 +1,3 @@ -using System; using System.Collections.Generic; using UnityEngine; diff --git a/Assembly-CSharp/Verse.Sound/AudioSourcePoolWorld.cs b/Assembly-CSharp/Verse.Sound/AudioSourcePoolWorld.cs index 27125e347..b7f3a5df0 100644 --- a/Assembly-CSharp/Verse.Sound/AudioSourcePoolWorld.cs +++ b/Assembly-CSharp/Verse.Sound/AudioSourcePoolWorld.cs @@ -12,27 +12,46 @@ public class AudioSourcePoolWorld public AudioSourcePoolWorld() { - GameObject gameObject = new GameObject("OneShotSourcesWorldContainer"); - gameObject.transform.position = Vector3.zero; + GameObject gameObject = new GameObject("OneShotSourcesWorldContainer") + { + transform = + { + position = Vector3.zero + } + }; for (int i = 0; i < 32; i++) { - GameObject gameObject2 = new GameObject("OneShotSource_" + i.ToString()); - gameObject2.transform.parent = gameObject.transform; - gameObject2.transform.localPosition = Vector3.zero; - this.sourcesWorld.Add(AudioSourceMaker.NewAudioSourceOn(gameObject2)); + GameObject go = new GameObject("OneShotSource_" + i.ToString()) + { + transform = + { + parent = gameObject.transform, + localPosition = Vector3.zero + } + }; + this.sourcesWorld.Add(AudioSourceMaker.NewAudioSourceOn(go)); } } public AudioSource GetSourceWorld() { - foreach (AudioSource current in this.sourcesWorld) + List.Enumerator enumerator = this.sourcesWorld.GetEnumerator(); + try { - if (!current.isPlaying) + while (enumerator.MoveNext()) { - SoundFilterUtility.DisableAllFiltersOn(current); - return current; + AudioSource current = enumerator.Current; + if (!current.isPlaying) + { + SoundFilterUtility.DisableAllFiltersOn(current); + return current; + } } } + finally + { + ((IDisposable)(object)enumerator).Dispose(); + } return null; } } diff --git a/Assembly-CSharp/Verse.Sound/DebugSoundEventsLog.cs b/Assembly-CSharp/Verse.Sound/DebugSoundEventsLog.cs index a608a9711..cbcc13d21 100644 --- a/Assembly-CSharp/Verse.Sound/DebugSoundEventsLog.cs +++ b/Assembly-CSharp/Verse.Sound/DebugSoundEventsLog.cs @@ -1,4 +1,3 @@ -using System; using System.Linq; using System.Text; @@ -13,9 +12,9 @@ public static string EventsListingDebugString get { StringBuilder stringBuilder = new StringBuilder(); - foreach (LogMessage current in DebugSoundEventsLog.queue.Messages.Reverse()) + foreach (LogMessage item in DebugSoundEventsLog.queue.Messages.Reverse()) { - stringBuilder.AppendLine(current.ToString()); + stringBuilder.AppendLine(item.ToString()); } return stringBuilder.ToString(); } @@ -23,26 +22,13 @@ public static string EventsListingDebugString public static void Notify_SoundEvent(SoundDef def, SoundInfo info) { - if (!DebugViewSettings.writeSoundEventsRecord) + if (DebugViewSettings.writeSoundEventsRecord) { - return; + string str = (def != null) ? ((!def.isUndefined) ? ((!def.sustain) ? "OneShot: " : "SustainerSpawn: ") : "Undefined: ") : "null: "; + string str2 = (def == null) ? "null" : def.defName; + string str3 = str + str2 + " - " + info.ToString(); + DebugSoundEventsLog.CreateRecord(str3); } - string str; - if (def == null) - { - str = "null: "; - } - else if (def.isUndefined) - { - str = "Undefined: "; - } - else - { - str = ((!def.sustain) ? "OneShot: " : "SustainerSpawn: "); - } - string str2 = (def == null) ? "null" : def.defName; - string str3 = str + str2 + " - " + info.ToString(); - DebugSoundEventsLog.CreateRecord(str3); } public static void Notify_SustainerEnded(Sustainer sustainer, SoundInfo info) diff --git a/Assembly-CSharp/Verse.Sound/EchoFilterProperty.cs b/Assembly-CSharp/Verse.Sound/EchoFilterProperty.cs index 07e4575a9..fde08ad1b 100644 --- a/Assembly-CSharp/Verse.Sound/EchoFilterProperty.cs +++ b/Assembly-CSharp/Verse.Sound/EchoFilterProperty.cs @@ -1,12 +1,10 @@ -using System; - namespace Verse.Sound { public enum EchoFilterProperty : byte { - Delay, - DecayRatio, - WetMix, - DryMix + Delay = 0, + DecayRatio = 1, + WetMix = 2, + DryMix = 3 } } diff --git a/Assembly-CSharp/Verse.Sound/HighPassFilterProperty.cs b/Assembly-CSharp/Verse.Sound/HighPassFilterProperty.cs index 8c262ea10..b937de73b 100644 --- a/Assembly-CSharp/Verse.Sound/HighPassFilterProperty.cs +++ b/Assembly-CSharp/Verse.Sound/HighPassFilterProperty.cs @@ -1,10 +1,8 @@ -using System; - namespace Verse.Sound { public enum HighPassFilterProperty : byte { - Cutoff, - Resonance + Cutoff = 0, + Resonance = 1 } } diff --git a/Assembly-CSharp/Verse.Sound/ISizeReporter.cs b/Assembly-CSharp/Verse.Sound/ISizeReporter.cs index dff8f97b5..a7f7ca388 100644 --- a/Assembly-CSharp/Verse.Sound/ISizeReporter.cs +++ b/Assembly-CSharp/Verse.Sound/ISizeReporter.cs @@ -1,5 +1,3 @@ -using System; - namespace Verse.Sound { public interface ISizeReporter diff --git a/Assembly-CSharp/Verse.Sound/ImpactSoundTypeDef.cs b/Assembly-CSharp/Verse.Sound/ImpactSoundTypeDef.cs index 650d2eb8e..d39ea3be1 100644 --- a/Assembly-CSharp/Verse.Sound/ImpactSoundTypeDef.cs +++ b/Assembly-CSharp/Verse.Sound/ImpactSoundTypeDef.cs @@ -1,5 +1,3 @@ -using System; - namespace Verse.Sound { public class ImpactSoundTypeDef : Def diff --git a/Assembly-CSharp/Verse.Sound/LowPassFilterProperty.cs b/Assembly-CSharp/Verse.Sound/LowPassFilterProperty.cs index ff1a6d31d..3f0e3f8e3 100644 --- a/Assembly-CSharp/Verse.Sound/LowPassFilterProperty.cs +++ b/Assembly-CSharp/Verse.Sound/LowPassFilterProperty.cs @@ -1,10 +1,8 @@ -using System; - namespace Verse.Sound { public enum LowPassFilterProperty : byte { - Cutoff, - Resonance + Cutoff = 0, + Resonance = 1 } } diff --git a/Assembly-CSharp/Verse.Sound/MaintenanceType.cs b/Assembly-CSharp/Verse.Sound/MaintenanceType.cs index da9fb8fe0..9b8d5b8df 100644 --- a/Assembly-CSharp/Verse.Sound/MaintenanceType.cs +++ b/Assembly-CSharp/Verse.Sound/MaintenanceType.cs @@ -1,11 +1,9 @@ -using System; - namespace Verse.Sound { public enum MaintenanceType : byte { - None, - PerTick, - PerFrame + None = 0, + PerTick = 1, + PerFrame = 2 } } diff --git a/Assembly-CSharp/Verse.Sound/MouseoverSounds.cs b/Assembly-CSharp/Verse.Sound/MouseoverSounds.cs index 2e3ea854f..653c05bb2 100644 --- a/Assembly-CSharp/Verse.Sound/MouseoverSounds.cs +++ b/Assembly-CSharp/Verse.Sound/MouseoverSounds.cs @@ -1,5 +1,4 @@ using RimWorld; -using System; using System.Collections.Generic; using UnityEngine; @@ -19,22 +18,22 @@ public bool IsValid { get { - return this.rect.x >= 0f; + return this.rect.x >= 0.0; } } - public static MouseoverSounds.MouseoverRegionCall Invalid + public static MouseoverRegionCall Invalid { get { - return new MouseoverSounds.MouseoverRegionCall + return new MouseoverRegionCall { rect = new Rect(-1000f, -1000f, 0f, 0f) }; } } - public bool Matches(MouseoverSounds.MouseoverRegionCall other) + public bool Matches(MouseoverRegionCall other) { return this.rect.Equals(other.rect); } @@ -45,21 +44,15 @@ public override string ToString() { return "(Invalid)"; } - return string.Concat(new object[] - { - "(rect=", - this.rect, - (!this.mouseIsOver) ? string.Empty : "mouseIsOver", - ")" - }); + return "(rect=" + this.rect + ((!this.mouseIsOver) ? string.Empty : "mouseIsOver") + ")"; } } - private static List frameCalls = new List(); + private static List frameCalls = new List(); private static int lastUsedCallInd = -1; - private static MouseoverSounds.MouseoverRegionCall lastUsedCall; + private static MouseoverRegionCall lastUsedCall; private static int forceSilenceUntilFrame = -1; @@ -75,30 +68,29 @@ public static void DoRegion(Rect rect) public static void DoRegion(Rect rect, SoundDef sound) { - if (sound == null) - { - return; - } - if (Event.current.type != EventType.Repaint) + if (sound != null && Event.current.type == EventType.Repaint) { - return; + MouseoverRegionCall item = new MouseoverRegionCall + { + rect = rect, + sound = sound, + mouseIsOver = Mouse.IsOver(rect) + }; + MouseoverSounds.frameCalls.Add(item); } - MouseoverSounds.MouseoverRegionCall item = default(MouseoverSounds.MouseoverRegionCall); - item.rect = rect; - item.sound = sound; - item.mouseIsOver = Mouse.IsOver(rect); - MouseoverSounds.frameCalls.Add(item); } public static void ResolveFrame() { for (int i = 0; i < MouseoverSounds.frameCalls.Count; i++) { - if (MouseoverSounds.frameCalls[i].mouseIsOver) + MouseoverRegionCall mouseoverRegionCall = MouseoverSounds.frameCalls[i]; + if (mouseoverRegionCall.mouseIsOver) { if (MouseoverSounds.lastUsedCallInd != i && !MouseoverSounds.frameCalls[i].Matches(MouseoverSounds.lastUsedCall) && MouseoverSounds.forceSilenceUntilFrame < Time.frameCount) { - MouseoverSounds.frameCalls[i].sound.PlayOneShotOnCamera(null); + MouseoverRegionCall mouseoverRegionCall2 = MouseoverSounds.frameCalls[i]; + mouseoverRegionCall2.sound.PlayOneShotOnCamera(null); } MouseoverSounds.lastUsedCallInd = i; MouseoverSounds.lastUsedCall = MouseoverSounds.frameCalls[i]; @@ -106,7 +98,7 @@ public static void ResolveFrame() return; } } - MouseoverSounds.lastUsedCall = MouseoverSounds.MouseoverRegionCall.Invalid; + MouseoverSounds.lastUsedCall = MouseoverRegionCall.Invalid; MouseoverSounds.lastUsedCallInd = -1; MouseoverSounds.frameCalls.Clear(); } diff --git a/Assembly-CSharp/Verse.Sound/PerlinMappingSyncType.cs b/Assembly-CSharp/Verse.Sound/PerlinMappingSyncType.cs index 2ea420a79..76fd324f8 100644 --- a/Assembly-CSharp/Verse.Sound/PerlinMappingSyncType.cs +++ b/Assembly-CSharp/Verse.Sound/PerlinMappingSyncType.cs @@ -1,10 +1,8 @@ -using System; - namespace Verse.Sound { public enum PerlinMappingSyncType : byte { - Sync, - Desync + Sync = 0, + Desync = 1 } } diff --git a/Assembly-CSharp/Verse.Sound/PitchParamType.cs b/Assembly-CSharp/Verse.Sound/PitchParamType.cs index 26d531de6..051948866 100644 --- a/Assembly-CSharp/Verse.Sound/PitchParamType.cs +++ b/Assembly-CSharp/Verse.Sound/PitchParamType.cs @@ -1,10 +1,8 @@ -using System; - namespace Verse.Sound { public enum PitchParamType : byte { - Multiply, - Semitones + Multiply = 0, + Semitones = 1 } } diff --git a/Assembly-CSharp/Verse.Sound/RepeatSelectMode.cs b/Assembly-CSharp/Verse.Sound/RepeatSelectMode.cs index 84c2a160a..076b81b95 100644 --- a/Assembly-CSharp/Verse.Sound/RepeatSelectMode.cs +++ b/Assembly-CSharp/Verse.Sound/RepeatSelectMode.cs @@ -1,11 +1,9 @@ -using System; - namespace Verse.Sound { public enum RepeatSelectMode : byte { - Any, - NeverTwice, - NeverLastHalf + Any = 0, + NeverTwice = 1, + NeverLastHalf = 2 } } diff --git a/Assembly-CSharp/Verse.Sound/ResolvedGrain.cs b/Assembly-CSharp/Verse.Sound/ResolvedGrain.cs index c21a74ba9..0dd0e56e6 100644 --- a/Assembly-CSharp/Verse.Sound/ResolvedGrain.cs +++ b/Assembly-CSharp/Verse.Sound/ResolvedGrain.cs @@ -1,5 +1,3 @@ -using System; - namespace Verse.Sound { public class ResolvedGrain diff --git a/Assembly-CSharp/Verse.Sound/ResolvedGrain_Clip.cs b/Assembly-CSharp/Verse.Sound/ResolvedGrain_Clip.cs index b0fe3a9db..2aff1c5df 100644 --- a/Assembly-CSharp/Verse.Sound/ResolvedGrain_Clip.cs +++ b/Assembly-CSharp/Verse.Sound/ResolvedGrain_Clip.cs @@ -1,4 +1,3 @@ -using System; using UnityEngine; namespace Verse.Sound @@ -10,7 +9,7 @@ public class ResolvedGrain_Clip : ResolvedGrain public ResolvedGrain_Clip(AudioClip clip) { this.clip = clip; - this.duration = clip.length; + base.duration = clip.length; } public override string ToString() @@ -25,12 +24,16 @@ public override bool Equals(object obj) return false; } ResolvedGrain_Clip resolvedGrain_Clip = obj as ResolvedGrain_Clip; - return resolvedGrain_Clip != null && resolvedGrain_Clip.clip == this.clip; + if (resolvedGrain_Clip == null) + { + return false; + } + return (Object)resolvedGrain_Clip.clip == (Object)this.clip; } public override int GetHashCode() { - if (this.clip == null) + if ((Object)this.clip == (Object)null) { return 0; } diff --git a/Assembly-CSharp/Verse.Sound/ResolvedGrain_Silence.cs b/Assembly-CSharp/Verse.Sound/ResolvedGrain_Silence.cs index 5366569ed..e086dc02e 100644 --- a/Assembly-CSharp/Verse.Sound/ResolvedGrain_Silence.cs +++ b/Assembly-CSharp/Verse.Sound/ResolvedGrain_Silence.cs @@ -1,5 +1,3 @@ -using System; - namespace Verse.Sound { public class ResolvedGrain_Silence : ResolvedGrain @@ -9,7 +7,7 @@ public class ResolvedGrain_Silence : ResolvedGrain public ResolvedGrain_Silence(AudioGrain_Silence sourceGrain) { this.sourceGrain = sourceGrain; - this.duration = sourceGrain.durationRange.RandomInRange; + base.duration = sourceGrain.durationRange.RandomInRange; } public override string ToString() @@ -24,7 +22,11 @@ public override bool Equals(object obj) return false; } ResolvedGrain_Silence resolvedGrain_Silence = obj as ResolvedGrain_Silence; - return resolvedGrain_Silence != null && resolvedGrain_Silence.sourceGrain == this.sourceGrain; + if (resolvedGrain_Silence == null) + { + return false; + } + return resolvedGrain_Silence.sourceGrain == this.sourceGrain; } public override int GetHashCode() diff --git a/Assembly-CSharp/Verse.Sound/ReverbCustomPresets.cs b/Assembly-CSharp/Verse.Sound/ReverbCustomPresets.cs index 58024344c..8019c61f5 100644 --- a/Assembly-CSharp/Verse.Sound/ReverbCustomPresets.cs +++ b/Assembly-CSharp/Verse.Sound/ReverbCustomPresets.cs @@ -1,4 +1,3 @@ -using System; using UnityEngine; namespace Verse.Sound @@ -25,7 +24,7 @@ public static void SetupAs(this ReverbSetup setup, AudioReverbPreset preset) setup.lfReference = audioReverbFilter.lfReference; setup.diffusion = audioReverbFilter.diffusion; setup.density = audioReverbFilter.density; - UnityEngine.Object.Destroy(audioReverbFilter); + Object.Destroy(audioReverbFilter); } } } diff --git a/Assembly-CSharp/Verse.Sound/ReverbSetup.cs b/Assembly-CSharp/Verse.Sound/ReverbSetup.cs index bb2bdea5e..cd1c1795a 100644 --- a/Assembly-CSharp/Verse.Sound/ReverbSetup.cs +++ b/Assembly-CSharp/Verse.Sound/ReverbSetup.cs @@ -1,5 +1,4 @@ using System; -using System.Collections; using System.Collections.Generic; using UnityEngine; @@ -40,19 +39,15 @@ public void DoEditWidgets(WidgetRow widgetRow) if (widgetRow.ButtonText("Setup from preset...", "Set up the reverb filter from a preset.", true, false)) { List list = new List(); - using (IEnumerator enumerator = Enum.GetValues(typeof(AudioReverbPreset)).GetEnumerator()) + foreach (int value in Enum.GetValues(typeof(AudioReverbPreset))) { - while (enumerator.MoveNext()) + if (value != 27) { - AudioReverbPreset audioReverbPreset = (AudioReverbPreset)((int)enumerator.Current); - if (audioReverbPreset != AudioReverbPreset.User) + AudioReverbPreset localPreset = (AudioReverbPreset)value; + list.Add(new FloatMenuOption(((Enum)(object)(AudioReverbPreset)value).ToString(), (Action)delegate { - AudioReverbPreset localPreset = audioReverbPreset; - list.Add(new FloatMenuOption(audioReverbPreset.ToString(), delegate - { - this.SetupAs(localPreset); - }, MenuOptionPriority.Default, null, null, 0f, null, null)); - } + this.SetupAs(localPreset); + }, MenuOptionPriority.Default, null, null, 0f, null, null)); } } Find.WindowStack.Add(new FloatMenu(list)); @@ -79,23 +74,22 @@ public void ApplyTo(AudioReverbFilter filter) public static ReverbSetup Lerp(ReverbSetup A, ReverbSetup B, float t) { - return new ReverbSetup - { - dryLevel = Mathf.Lerp(A.dryLevel, B.dryLevel, t), - room = Mathf.Lerp(A.room, B.room, t), - roomHF = Mathf.Lerp(A.roomHF, B.roomHF, t), - roomLF = Mathf.Lerp(A.roomLF, B.roomLF, t), - decayTime = Mathf.Lerp(A.decayTime, B.decayTime, t), - decayHFRatio = Mathf.Lerp(A.decayHFRatio, B.decayHFRatio, t), - reflectionsLevel = Mathf.Lerp(A.reflectionsLevel, B.reflectionsLevel, t), - reflectionsDelay = Mathf.Lerp(A.reflectionsDelay, B.reflectionsDelay, t), - reverbLevel = Mathf.Lerp(A.reverbLevel, B.reverbLevel, t), - reverbDelay = Mathf.Lerp(A.reverbDelay, B.reverbDelay, t), - hfReference = Mathf.Lerp(A.hfReference, B.hfReference, t), - lfReference = Mathf.Lerp(A.lfReference, B.lfReference, t), - diffusion = Mathf.Lerp(A.diffusion, B.diffusion, t), - density = Mathf.Lerp(A.density, B.density, t) - }; + ReverbSetup reverbSetup = new ReverbSetup(); + reverbSetup.dryLevel = Mathf.Lerp(A.dryLevel, B.dryLevel, t); + reverbSetup.room = Mathf.Lerp(A.room, B.room, t); + reverbSetup.roomHF = Mathf.Lerp(A.roomHF, B.roomHF, t); + reverbSetup.roomLF = Mathf.Lerp(A.roomLF, B.roomLF, t); + reverbSetup.decayTime = Mathf.Lerp(A.decayTime, B.decayTime, t); + reverbSetup.decayHFRatio = Mathf.Lerp(A.decayHFRatio, B.decayHFRatio, t); + reverbSetup.reflectionsLevel = Mathf.Lerp(A.reflectionsLevel, B.reflectionsLevel, t); + reverbSetup.reflectionsDelay = Mathf.Lerp(A.reflectionsDelay, B.reflectionsDelay, t); + reverbSetup.reverbLevel = Mathf.Lerp(A.reverbLevel, B.reverbLevel, t); + reverbSetup.reverbDelay = Mathf.Lerp(A.reverbDelay, B.reverbDelay, t); + reverbSetup.hfReference = Mathf.Lerp(A.hfReference, B.hfReference, t); + reverbSetup.lfReference = Mathf.Lerp(A.lfReference, B.lfReference, t); + reverbSetup.diffusion = Mathf.Lerp(A.diffusion, B.diffusion, t); + reverbSetup.density = Mathf.Lerp(A.density, B.density, t); + return reverbSetup; } } } diff --git a/Assembly-CSharp/Verse.Sound/Sample.cs b/Assembly-CSharp/Verse.Sound/Sample.cs index 75a4e6cc8..42ef26f7d 100644 --- a/Assembly-CSharp/Verse.Sound/Sample.cs +++ b/Assembly-CSharp/Verse.Sound/Sample.cs @@ -44,7 +44,7 @@ public int AgeTicks { return Find.TickManager.TicksGame - this.startTick; } - return (int)(this.AgeRealTime * 60f); + return (int)(this.AgeRealTime * 60.0); } } @@ -77,11 +77,20 @@ protected float MappedVolumeMultiplier return 0f; } float num = 1f; - foreach (float num2 in this.volumeInMappings.Values) + Dictionary.ValueCollection.Enumerator enumerator = this.volumeInMappings.Values.GetEnumerator(); + try { - num *= num2; + while (enumerator.MoveNext()) + { + float num2 = enumerator.Current; + num *= num2; + } + return num; + } + finally + { + ((IDisposable)(object)enumerator).Dispose(); } - return num; } } @@ -116,10 +125,10 @@ public Sample(SubSoundDef def) { this.startTick = 0; } - foreach (SoundParamTarget_Volume current in (from m in this.subDef.paramMappings + foreach (SoundParamTarget_Volume item in (from m in this.subDef.paramMappings select m.outParam).OfType()) { - this.volumeInMappings.Add(current, 0f); + this.volumeInMappings.Add(item, 0f); } } @@ -155,20 +164,12 @@ public virtual void SampleCleanup() public override string ToString() { - return string.Concat(new object[] - { - "Sample_", - this.subDef.name, - " volume=", - this.source.volume, - " at ", - this.source.transform.position.ToIntVec3() - }); + return "Sample_" + this.subDef.name + " volume=" + this.source.volume + " at " + this.source.transform.position.ToIntVec3(); } public override int GetHashCode() { - return Gen.HashCombine(this.startRealTime.GetHashCode(), this.subDef); + return Gen.HashCombine(this.startRealTime.GetHashCode(), this.subDef); } } } diff --git a/Assembly-CSharp/Verse.Sound/SampleOneShot.cs b/Assembly-CSharp/Verse.Sound/SampleOneShot.cs index 0e0f08562..4fd6a9d6f 100644 --- a/Assembly-CSharp/Verse.Sound/SampleOneShot.cs +++ b/Assembly-CSharp/Verse.Sound/SampleOneShot.cs @@ -1,4 +1,3 @@ -using System; using System.Collections.Generic; using UnityEngine; @@ -22,7 +21,7 @@ public override float ParentStartRealTime { get { - return this.startRealTime; + return base.startRealTime; } } @@ -30,7 +29,7 @@ public override float ParentStartTick { get { - return (float)this.startTick; + return (float)base.startTick; } } @@ -66,21 +65,13 @@ public static SampleOneShot TryMakeAndPlay(SubSoundDef def, AudioClip clip, Soun { if ((double)info.pitchFactor <= 0.0001) { - Log.ErrorOnce(string.Concat(new object[] - { - "Played sound with pitchFactor ", - info.pitchFactor, - ": ", - def, - ", ", - info - }), 632321); + Log.ErrorOnce("Played sound with pitchFactor " + info.pitchFactor + ": " + def + ", " + info, 632321); return null; } SampleOneShot sampleOneShot = new SampleOneShot(def); sampleOneShot.info = info; sampleOneShot.source = Find.SoundRoot.sourcePool.GetSource(def.onCamera); - if (sampleOneShot.source == null) + if ((Object)sampleOneShot.source == (Object)null) { return null; } @@ -104,9 +95,9 @@ public static SampleOneShot TryMakeAndPlay(SubSoundDef def, AudioClip clip, Soun { def.filters[i].SetupOn(sampleOneShot.source); } - foreach (KeyValuePair current in info.DefinedParameters) + foreach (KeyValuePair definedParameter in info.DefinedParameters) { - sampleOneShot.externalParams[current.Key] = current.Value; + sampleOneShot.externalParams[definedParameter.Key] = definedParameter.Value; } sampleOneShot.ApplyMappedParameters(); sampleOneShot.source.Play(); diff --git a/Assembly-CSharp/Verse.Sound/SampleOneShotManager.cs b/Assembly-CSharp/Verse.Sound/SampleOneShotManager.cs index 076db2df7..0fe2e0600 100644 --- a/Assembly-CSharp/Verse.Sound/SampleOneShotManager.cs +++ b/Assembly-CSharp/Verse.Sound/SampleOneShotManager.cs @@ -1,6 +1,7 @@ using System; using System.Collections.Generic; using System.Linq; +using UnityEngine; namespace Verse.Sound { @@ -32,11 +33,11 @@ private float ImportanceOf(SoundDef def, SoundInfo info, float ageRealTime) { if (def.priorityMode == VoicePriorityMode.PrioritizeNearest) { - return 1f / (this.CameraDistanceSquaredOf(info) + 1f); + return (float)(1.0 / (this.CameraDistanceSquaredOf(info) + 1.0)); } if (def.priorityMode == VoicePriorityMode.PrioritizeNewest) { - return 1f / (ageRealTime + 1f); + return (float)(1.0 / (ageRealTime + 1.0)); } throw new NotImplementedException(); } @@ -48,20 +49,24 @@ public bool CanAddPlayingOneShot(SoundDef def, SoundInfo info) return false; } if ((from s in this.samples - where s.subDef.parentDef == def && s.AgeRealTime < 0.05f - select s).Count() >= def.MaxSimultaneousSamples) + where s.subDef.parentDef == def && s.AgeRealTime < 0.05000000074505806 + select s).Count() >= def.MaxSimultaneousSamples) { return false; } SampleOneShot sampleOneShot = this.LeastImportantOf(def); - return sampleOneShot == null || this.ImportanceOf(def, info, 0f) >= this.ImportanceOf(sampleOneShot); + if (sampleOneShot != null && this.ImportanceOf(def, info, 0f) < this.ImportanceOf(sampleOneShot)) + { + return false; + } + return true; } public void TryAddPlayingOneShot(SampleOneShot newSample) { int num = (from s in this.samples where s.subDef == newSample.subDef - select s).Count(); + select s).Count(); if (num >= newSample.subDef.parentDef.maxVoices) { SampleOneShot sampleOneShot = this.LeastImportantOf(newSample.subDef.parentDef); @@ -95,9 +100,9 @@ public void SampleOneShotManagerUpdate() for (int j = 0; j < this.samples.Count; j++) { SampleOneShot sampleOneShot = this.samples[j]; - if (sampleOneShot.source == null || !sampleOneShot.source.isPlaying || !SoundDefHelper.CorrectContextNow(sampleOneShot.subDef.parentDef, sampleOneShot.Map)) + if ((UnityEngine.Object)sampleOneShot.source == (UnityEngine.Object)null || !sampleOneShot.source.isPlaying || !SoundDefHelper.CorrectContextNow(sampleOneShot.subDef.parentDef, sampleOneShot.Map)) { - if (sampleOneShot.source != null && sampleOneShot.source.isPlaying) + if ((UnityEngine.Object)sampleOneShot.source != (UnityEngine.Object)null && sampleOneShot.source.isPlaying) { sampleOneShot.source.Stop(); } @@ -107,7 +112,7 @@ public void SampleOneShotManagerUpdate() } if (this.cleanupList.Count > 0) { - this.samples.RemoveAll((SampleOneShot s) => this.cleanupList.Contains(s)); + this.samples.RemoveAll((Predicate)((SampleOneShot s) => this.cleanupList.Contains(s))); } } } diff --git a/Assembly-CSharp/Verse.Sound/SampleSustainer.cs b/Assembly-CSharp/Verse.Sound/SampleSustainer.cs index f57781968..d90034624 100644 --- a/Assembly-CSharp/Verse.Sound/SampleSustainer.cs +++ b/Assembly-CSharp/Verse.Sound/SampleSustainer.cs @@ -1,4 +1,3 @@ -using System; using System.Collections.Generic; using UnityEngine; @@ -56,7 +55,8 @@ protected override bool TestPlaying { get { - return this.subSustainer.Info.testPlay; + SoundInfo info = this.subSustainer.Info; + return info.testPlay; } } @@ -69,22 +69,16 @@ public static SampleSustainer TryMakeAndPlay(SubSustainer subSus, AudioClip clip SampleSustainer sampleSustainer = new SampleSustainer(subSus.subDef); sampleSustainer.subSustainer = subSus; sampleSustainer.scheduledEndTime = scheduledEndTime; - GameObject gameObject = new GameObject(string.Concat(new object[] - { - "SampleSource_", - sampleSustainer.subDef.name, - "_", - sampleSustainer.startRealTime - })); + GameObject gameObject = new GameObject("SampleSource_" + sampleSustainer.subDef.name + "_" + sampleSustainer.startRealTime); GameObject gameObject2 = (!subSus.subDef.onCamera) ? subSus.parent.worldRootObject : Find.Camera.gameObject; gameObject.transform.parent = gameObject2.transform; gameObject.transform.localPosition = Vector3.zero; sampleSustainer.source = AudioSourceMaker.NewAudioSourceOn(gameObject); - if (sampleSustainer.source == null) + if ((Object)sampleSustainer.source == (Object)null) { - if (gameObject != null) + if ((Object)gameObject != (Object)null) { - UnityEngine.Object.Destroy(gameObject); + Object.Destroy(gameObject); } return null; } @@ -112,53 +106,53 @@ public static SampleSustainer TryMakeAndPlay(SubSustainer subSus, AudioClip clip public void UpdateSourceVolume() { - float num = this.resolvedVolume * this.subSustainer.parent.scopeFader.inScopePercent * base.MappedVolumeMultiplier * base.ContextVolumeMultiplier; - if (base.AgeRealTime < this.subDef.sustainAttack) + float num = base.resolvedVolume * this.subSustainer.parent.scopeFader.inScopePercent * base.MappedVolumeMultiplier * base.ContextVolumeMultiplier; + if (base.AgeRealTime < base.subDef.sustainAttack) { - if (this.resolvedSkipAttack || this.subDef.sustainAttack < 0.01f) + if (this.resolvedSkipAttack || base.subDef.sustainAttack < 0.0099999997764825821) { - this.source.volume = num; + base.source.volume = num; } else { - float num2 = base.AgeRealTime / this.subDef.sustainAttack; - num2 = Mathf.Sqrt(num2); - this.source.volume = Mathf.Lerp(0f, num, num2); + float f = base.AgeRealTime / base.subDef.sustainAttack; + f = Mathf.Sqrt(f); + base.source.volume = Mathf.Lerp(0f, num, f); } } - else if (Time.realtimeSinceStartup > this.scheduledEndTime - this.subDef.sustainRelease) + else if (Time.realtimeSinceStartup > this.scheduledEndTime - base.subDef.sustainRelease) { - float num3 = (Time.realtimeSinceStartup - (this.scheduledEndTime - this.subDef.sustainRelease)) / this.subDef.sustainRelease; - num3 = 1f - num3; - num3 = Mathf.Sqrt(num3); - num3 = 1f - num3; - this.source.volume = Mathf.Lerp(num, 0f, num3); + float num2 = (Time.realtimeSinceStartup - (this.scheduledEndTime - base.subDef.sustainRelease)) / base.subDef.sustainRelease; + num2 = (float)(1.0 - num2); + num2 = Mathf.Sqrt(num2); + num2 = (float)(1.0 - num2); + base.source.volume = Mathf.Lerp(num, 0f, num2); } else { - this.source.volume = num; + base.source.volume = num; } if (this.subSustainer.parent.Ended) { - float num4 = 1f - this.subSustainer.parent.TimeSinceEnd / this.subDef.parentDef.sustainFadeoutTime; - this.source.volume *= num4; + float num3 = (float)(1.0 - this.subSustainer.parent.TimeSinceEnd / base.subDef.parentDef.sustainFadeoutTime); + base.source.volume *= num3; } - if (this.source.volume < 0.001f) + if (base.source.volume < 0.0010000000474974513) { - this.source.mute = true; + base.source.mute = true; } else { - this.source.mute = false; + base.source.mute = false; } } public override void SampleCleanup() { base.SampleCleanup(); - if (this.source != null && this.source.gameObject != null) + if ((Object)base.source != (Object)null && (Object)base.source.gameObject != (Object)null) { - UnityEngine.Object.Destroy(this.source.gameObject); + Object.Destroy(base.source.gameObject); } } } diff --git a/Assembly-CSharp/Verse.Sound/SoundContext.cs b/Assembly-CSharp/Verse.Sound/SoundContext.cs index fa0cf2dc7..78f2cc1b8 100644 --- a/Assembly-CSharp/Verse.Sound/SoundContext.cs +++ b/Assembly-CSharp/Verse.Sound/SoundContext.cs @@ -1,11 +1,9 @@ -using System; - namespace Verse.Sound { public enum SoundContext { - Any, - MapOnly, - WorldOnly + Any = 0, + MapOnly = 1, + WorldOnly = 2 } } diff --git a/Assembly-CSharp/Verse.Sound/SoundFilter.cs b/Assembly-CSharp/Verse.Sound/SoundFilter.cs index 843d2a536..33903ac51 100644 --- a/Assembly-CSharp/Verse.Sound/SoundFilter.cs +++ b/Assembly-CSharp/Verse.Sound/SoundFilter.cs @@ -1,4 +1,3 @@ -using System; using UnityEngine; namespace Verse.Sound @@ -9,16 +8,16 @@ public abstract class SoundFilter protected static T GetOrMakeFilterOn(AudioSource source) where T : Behaviour { - T t = source.gameObject.GetComponent(); - if (t != null) + T val = source.gameObject.GetComponent(); + if ((Object)(object)val != (Object)null) { - t.enabled = true; + val.enabled = true; } else { - t = source.gameObject.AddComponent(); + val = source.gameObject.AddComponent(); } - return t; + return val; } } } diff --git a/Assembly-CSharp/Verse.Sound/SoundFilterEcho.cs b/Assembly-CSharp/Verse.Sound/SoundFilterEcho.cs index 19c7a7b34..8f351bc5a 100644 --- a/Assembly-CSharp/Verse.Sound/SoundFilterEcho.cs +++ b/Assembly-CSharp/Verse.Sound/SoundFilterEcho.cs @@ -1,20 +1,23 @@ -using System; using UnityEngine; namespace Verse.Sound { public class SoundFilterEcho : SoundFilter { - [Description("Echo delay in ms. 10 to 5000. Default = 500."), EditSliderRange(10f, 5000f)] + [EditSliderRange(10f, 5000f)] + [Description("Echo delay in ms. 10 to 5000. Default = 500.")] private float delay = 500f; - [Description("Echo decay per delay. 0 to 1. 1.0 = No decay, 0.0 = total decay (ie simple 1 line delay)."), EditSliderRange(0f, 1f)] + [EditSliderRange(0f, 1f)] + [Description("Echo decay per delay. 0 to 1. 1.0 = No decay, 0.0 = total decay (ie simple 1 line delay).")] private float decayRatio = 0.5f; - [Description("The volume of the echo signal to pass to output."), EditSliderRange(0f, 1f)] + [EditSliderRange(0f, 1f)] + [Description("The volume of the echo signal to pass to output.")] private float wetMix = 1f; - [Description("The volume of the original signal to pass to output."), EditSliderRange(0f, 1f)] + [Description("The volume of the original signal to pass to output.")] + [EditSliderRange(0f, 1f)] private float dryMix = 1f; public override void SetupOn(AudioSource source) diff --git a/Assembly-CSharp/Verse.Sound/SoundFilterHighPass.cs b/Assembly-CSharp/Verse.Sound/SoundFilterHighPass.cs index 9b0222e88..a52da6a3d 100644 --- a/Assembly-CSharp/Verse.Sound/SoundFilterHighPass.cs +++ b/Assembly-CSharp/Verse.Sound/SoundFilterHighPass.cs @@ -1,14 +1,15 @@ -using System; using UnityEngine; namespace Verse.Sound { public class SoundFilterHighPass : SoundFilter { - [Description("This filter will attenuate frequencies below this cutoff frequency."), EditSliderRange(50f, 20000f)] + [Description("This filter will attenuate frequencies below this cutoff frequency.")] + [EditSliderRange(50f, 20000f)] private float cutoffFrequency = 10000f; - [Description("The resonance Q value."), EditSliderRange(1f, 10f)] + [Description("The resonance Q value.")] + [EditSliderRange(1f, 10f)] private float highpassResonanceQ = 1f; public override void SetupOn(AudioSource source) diff --git a/Assembly-CSharp/Verse.Sound/SoundFilterLowPass.cs b/Assembly-CSharp/Verse.Sound/SoundFilterLowPass.cs index bf3ab5c9d..531f34365 100644 --- a/Assembly-CSharp/Verse.Sound/SoundFilterLowPass.cs +++ b/Assembly-CSharp/Verse.Sound/SoundFilterLowPass.cs @@ -1,14 +1,15 @@ -using System; using UnityEngine; namespace Verse.Sound { public class SoundFilterLowPass : SoundFilter { - [Description("This filter will attenuate frequencies above this cutoff frequency."), EditSliderRange(50f, 20000f)] + [Description("This filter will attenuate frequencies above this cutoff frequency.")] + [EditSliderRange(50f, 20000f)] private float cutoffFrequency = 10000f; - [Description("The resonance Q value."), EditSliderRange(1f, 10f)] + [EditSliderRange(1f, 10f)] + [Description("The resonance Q value.")] private float lowpassResonaceQ = 1f; public override void SetupOn(AudioSource source) diff --git a/Assembly-CSharp/Verse.Sound/SoundFilterReverb.cs b/Assembly-CSharp/Verse.Sound/SoundFilterReverb.cs index c630bba0b..d0994bcc6 100644 --- a/Assembly-CSharp/Verse.Sound/SoundFilterReverb.cs +++ b/Assembly-CSharp/Verse.Sound/SoundFilterReverb.cs @@ -1,4 +1,3 @@ -using System; using UnityEngine; namespace Verse.Sound diff --git a/Assembly-CSharp/Verse.Sound/SoundFilterUtility.cs b/Assembly-CSharp/Verse.Sound/SoundFilterUtility.cs index 8744e515f..bf7f175db 100644 --- a/Assembly-CSharp/Verse.Sound/SoundFilterUtility.cs +++ b/Assembly-CSharp/Verse.Sound/SoundFilterUtility.cs @@ -1,4 +1,3 @@ -using System; using UnityEngine; namespace Verse.Sound @@ -17,8 +16,8 @@ public static void DisableAllFiltersOn(AudioSource source) private static void DisableFilterOn(AudioSource source) where T : Behaviour { - T component = source.GetComponent(); - if (component != null) + T component = ((Component)source).GetComponent(); + if ((Object)(object)component != (Object)null) { component.enabled = false; } diff --git a/Assembly-CSharp/Verse.Sound/SoundInfo.cs b/Assembly-CSharp/Verse.Sound/SoundInfo.cs index 8a2e3d263..917d7e4cb 100644 --- a/Assembly-CSharp/Verse.Sound/SoundInfo.cs +++ b/Assembly-CSharp/Verse.Sound/SoundInfo.cs @@ -35,32 +35,47 @@ public IEnumerable> DefinedParameters { get { - SoundInfo.<>c__Iterator229 <>c__Iterator = new SoundInfo.<>c__Iterator229(); - <>c__Iterator.<>f__this = this; - SoundInfo.<>c__Iterator229 expr_13 = <>c__Iterator; - expr_13.$PC = -2; - return expr_13; + if (this.parameters != null) + { + Dictionary.Enumerator enumerator = this.parameters.GetEnumerator(); + try + { + while (enumerator.MoveNext()) + { + KeyValuePair kvp = enumerator.Current; + yield return kvp; + } + } + finally + { + ((IDisposable)(object)enumerator).Dispose(); + } + } } } public static SoundInfo OnCamera(MaintenanceType maint = MaintenanceType.None) { - SoundInfo result = default(SoundInfo); - result.IsOnCamera = true; - result.Maintenance = maint; - result.Maker = TargetInfo.Invalid; - result.testPlay = false; + SoundInfo result = new SoundInfo + { + IsOnCamera = true, + Maintenance = maint, + Maker = TargetInfo.Invalid, + testPlay = false + }; result.volumeFactor = (result.pitchFactor = 1f); return result; } public static SoundInfo InMap(TargetInfo maker, MaintenanceType maint = MaintenanceType.None) { - SoundInfo result = default(SoundInfo); - result.IsOnCamera = false; - result.Maintenance = maint; - result.Maker = maker; - result.testPlay = false; + SoundInfo result = new SoundInfo + { + IsOnCamera = false, + Maintenance = maint, + Maker = maker, + testPlay = false + }; result.volumeFactor = (result.pitchFactor = 1f); return result; } @@ -76,42 +91,36 @@ public void SetParameter(string key, float value) public override string ToString() { - string text = null; + string text = (string)null; if (this.parameters != null && this.parameters.Count > 0) { text = "parameters="; - foreach (KeyValuePair current in this.parameters) + Dictionary.Enumerator enumerator = this.parameters.GetEnumerator(); + try { - string text2 = text; - text = string.Concat(new string[] + while (enumerator.MoveNext()) { - text2, - current.Key.ToString(), - "-", - current.Value.ToString(), - " " - }); + KeyValuePair current = enumerator.Current; + string text2 = text; + text = text2 + current.Key.ToString() + "-" + current.Value.ToString() + " "; + } + } + finally + { + ((IDisposable)(object)enumerator).Dispose(); } } - string text3 = null; + string text3 = (string)null; if (this.Maker.HasThing || this.Maker.Cell.IsValid) { text3 = this.Maker.ToString(); } - string text4 = null; - if (this.Maintenance != MaintenanceType.None) + string text4 = (string)null; + if (this.Maintenance != 0) { text4 = ", Maint=" + this.Maintenance; } - return string.Concat(new string[] - { - "(", - (!this.IsOnCamera) ? "World from " : "Camera", - text3, - text, - text4, - ")" - }); + return "(" + ((!this.IsOnCamera) ? "World from " : "Camera") + text3 + text + text4 + ")"; } public static implicit operator SoundInfo(TargetInfo source) diff --git a/Assembly-CSharp/Verse.Sound/SoundParamSource.cs b/Assembly-CSharp/Verse.Sound/SoundParamSource.cs index 2b1db58ab..a82991404 100644 --- a/Assembly-CSharp/Verse.Sound/SoundParamSource.cs +++ b/Assembly-CSharp/Verse.Sound/SoundParamSource.cs @@ -1,8 +1,7 @@ -using System; - namespace Verse.Sound { - [EditorReplaceable, EditorShowClassName] + [EditorShowClassName] + [EditorReplaceable] public abstract class SoundParamSource { public abstract string Label diff --git a/Assembly-CSharp/Verse.Sound/SoundParamSource_AggregateSize.cs b/Assembly-CSharp/Verse.Sound/SoundParamSource_AggregateSize.cs index ef8f5b8da..19b8b9754 100644 --- a/Assembly-CSharp/Verse.Sound/SoundParamSource_AggregateSize.cs +++ b/Assembly-CSharp/Verse.Sound/SoundParamSource_AggregateSize.cs @@ -1,5 +1,3 @@ -using System; - namespace Verse.Sound { public class SoundParamSource_AggregateSize : SoundParamSource diff --git a/Assembly-CSharp/Verse.Sound/SoundParamSource_CameraAltitude.cs b/Assembly-CSharp/Verse.Sound/SoundParamSource_CameraAltitude.cs index df1059d7c..5c1b23626 100644 --- a/Assembly-CSharp/Verse.Sound/SoundParamSource_CameraAltitude.cs +++ b/Assembly-CSharp/Verse.Sound/SoundParamSource_CameraAltitude.cs @@ -1,4 +1,4 @@ -using System; +using UnityEngine; namespace Verse.Sound { @@ -14,7 +14,8 @@ public override string Label public override float ValueFor(Sample samp) { - return Find.Camera.transform.position.y; + Vector3 position = Find.Camera.transform.position; + return position.y; } } } diff --git a/Assembly-CSharp/Verse.Sound/SoundParamSource_External.cs b/Assembly-CSharp/Verse.Sound/SoundParamSource_External.cs index dd96c99ae..2d206dfd4 100644 --- a/Assembly-CSharp/Verse.Sound/SoundParamSource_External.cs +++ b/Assembly-CSharp/Verse.Sound/SoundParamSource_External.cs @@ -1,5 +1,3 @@ -using System; - namespace Verse.Sound { public class SoundParamSource_External : SoundParamSource @@ -24,7 +22,7 @@ public override string Label public override float ValueFor(Sample samp) { - float result; + float result = default(float); if (samp.ExternalParams.TryGetValue(this.inParamName, out result)) { return result; diff --git a/Assembly-CSharp/Verse.Sound/SoundParamSource_MusicPlayingFadeOut.cs b/Assembly-CSharp/Verse.Sound/SoundParamSource_MusicPlayingFadeOut.cs index 703833b7c..a76c96ac1 100644 --- a/Assembly-CSharp/Verse.Sound/SoundParamSource_MusicPlayingFadeOut.cs +++ b/Assembly-CSharp/Verse.Sound/SoundParamSource_MusicPlayingFadeOut.cs @@ -1,5 +1,3 @@ -using System; - namespace Verse.Sound { public class SoundParamSource_MusicPlayingFadeOut : SoundParamSource @@ -14,11 +12,11 @@ public override string Label public override float ValueFor(Sample samp) { - if (Current.ProgramState != ProgramState.Playing || Find.MusicManagerPlay == null) + if (Current.ProgramState == ProgramState.Playing && Find.MusicManagerPlay != null) { - return 1f; + return Find.MusicManagerPlay.subtleAmbienceSoundVolumeMultiplier; } - return Find.MusicManagerPlay.subtleAmbienceSoundVolumeMultiplier; + return 1f; } } } diff --git a/Assembly-CSharp/Verse.Sound/SoundParamSource_OutdoorTemperature.cs b/Assembly-CSharp/Verse.Sound/SoundParamSource_OutdoorTemperature.cs index 6bf2993e0..77b1aabde 100644 --- a/Assembly-CSharp/Verse.Sound/SoundParamSource_OutdoorTemperature.cs +++ b/Assembly-CSharp/Verse.Sound/SoundParamSource_OutdoorTemperature.cs @@ -1,5 +1,3 @@ -using System; - namespace Verse.Sound { public class SoundParamSource_OutdoorTemperature : SoundParamSource diff --git a/Assembly-CSharp/Verse.Sound/SoundParamSource_Perlin.cs b/Assembly-CSharp/Verse.Sound/SoundParamSource_Perlin.cs index 1395c8358..b35c7073d 100644 --- a/Assembly-CSharp/Verse.Sound/SoundParamSource_Perlin.cs +++ b/Assembly-CSharp/Verse.Sound/SoundParamSource_Perlin.cs @@ -1,4 +1,3 @@ -using System; using UnityEngine; using Verse.Noise; @@ -27,47 +26,23 @@ public override string Label public override float ValueFor(Sample samp) { - float num; - if (this.syncType == PerlinMappingSyncType.Sync) - { - num = samp.ParentHashCode % 100f; - } - else - { - num = (float)(samp.GetHashCode() % 100); - } + float num = (float)((this.syncType != 0) ? ((float)(samp.GetHashCode() % 100)) : (samp.ParentHashCode % 100.0)); if (this.timeType == TimeType.Ticks && Current.ProgramState == ProgramState.Playing) { - float num2; - if (this.syncType == PerlinMappingSyncType.Sync) - { - num2 = (float)Find.TickManager.TicksGame - samp.ParentStartTick; - } - else - { - num2 = (float)(Find.TickManager.TicksGame - samp.startTick); - } - num2 /= 60f; + float num2 = (this.syncType != 0) ? ((float)(Find.TickManager.TicksGame - samp.startTick)) : ((float)Find.TickManager.TicksGame - samp.ParentStartTick); + num2 = (float)(num2 / 60.0); num += num2; } else { - float num3; - if (this.syncType == PerlinMappingSyncType.Sync) - { - num3 = Time.realtimeSinceStartup - samp.ParentStartRealTime; - } - else - { - num3 = Time.realtimeSinceStartup - samp.startRealTime; - } + float num3 = (this.syncType != 0) ? (Time.realtimeSinceStartup - samp.startRealTime) : (Time.realtimeSinceStartup - samp.ParentStartRealTime); num += num3; } num *= this.perlinFrequency; float num4 = (float)SoundParamSource_Perlin.perlin.GetValue((double)num, 0.0, 0.0); - num4 *= 2f; - num4 += 1f; - return num4 / 2f; + num4 = (float)(num4 * 2.0); + num4 = (float)(num4 + 1.0); + return (float)(num4 / 2.0); } } } diff --git a/Assembly-CSharp/Verse.Sound/SoundParamSource_Random.cs b/Assembly-CSharp/Verse.Sound/SoundParamSource_Random.cs index 184c30b05..f482e0bbe 100644 --- a/Assembly-CSharp/Verse.Sound/SoundParamSource_Random.cs +++ b/Assembly-CSharp/Verse.Sound/SoundParamSource_Random.cs @@ -1,5 +1,3 @@ -using System; - namespace Verse.Sound { public class SoundParamSource_Random : SoundParamSource diff --git a/Assembly-CSharp/Verse.Sound/SoundParamSource_SourceAge.cs b/Assembly-CSharp/Verse.Sound/SoundParamSource_SourceAge.cs index 5ea681ec8..b7c3f49a3 100644 --- a/Assembly-CSharp/Verse.Sound/SoundParamSource_SourceAge.cs +++ b/Assembly-CSharp/Verse.Sound/SoundParamSource_SourceAge.cs @@ -1,4 +1,3 @@ -using System; using UnityEngine; namespace Verse.Sound diff --git a/Assembly-CSharp/Verse.Sound/SoundParamTarget_Pitch.cs b/Assembly-CSharp/Verse.Sound/SoundParamTarget_Pitch.cs index a82a38c7f..01c96f2ec 100644 --- a/Assembly-CSharp/Verse.Sound/SoundParamTarget_Pitch.cs +++ b/Assembly-CSharp/Verse.Sound/SoundParamTarget_Pitch.cs @@ -17,15 +17,7 @@ public override string Label public override void SetOn(Sample sample, float value) { - float num; - if (this.pitchType == PitchParamType.Multiply) - { - num = value; - } - else - { - num = (float)Math.Pow(1.05946, (double)value); - } + float num = (this.pitchType != 0) ? ((float)Math.Pow(1.05946, (double)value)) : value; sample.source.pitch = sample.resolvedPitch * num; } } diff --git a/Assembly-CSharp/Verse.Sound/SoundParamTarget_PropertyEcho.cs b/Assembly-CSharp/Verse.Sound/SoundParamTarget_PropertyEcho.cs index 6f9192b3a..383cda442 100644 --- a/Assembly-CSharp/Verse.Sound/SoundParamTarget_PropertyEcho.cs +++ b/Assembly-CSharp/Verse.Sound/SoundParamTarget_PropertyEcho.cs @@ -25,8 +25,8 @@ public override Type NeededFilterType public override void SetOn(Sample sample, float value) { - AudioEchoFilter audioEchoFilter = sample.source.GetComponent(); - if (audioEchoFilter == null) + AudioEchoFilter audioEchoFilter = ((Component)sample.source).GetComponent(); + if ((UnityEngine.Object)audioEchoFilter == (UnityEngine.Object)null) { audioEchoFilter = sample.source.gameObject.AddComponent(); } diff --git a/Assembly-CSharp/Verse.Sound/SoundParamTarget_PropertyHighPass.cs b/Assembly-CSharp/Verse.Sound/SoundParamTarget_PropertyHighPass.cs index 5928a77cd..004ec2895 100644 --- a/Assembly-CSharp/Verse.Sound/SoundParamTarget_PropertyHighPass.cs +++ b/Assembly-CSharp/Verse.Sound/SoundParamTarget_PropertyHighPass.cs @@ -25,8 +25,8 @@ public override Type NeededFilterType public override void SetOn(Sample sample, float value) { - AudioHighPassFilter audioHighPassFilter = sample.source.GetComponent(); - if (audioHighPassFilter == null) + AudioHighPassFilter audioHighPassFilter = ((Component)sample.source).GetComponent(); + if ((UnityEngine.Object)audioHighPassFilter == (UnityEngine.Object)null) { audioHighPassFilter = sample.source.gameObject.AddComponent(); } diff --git a/Assembly-CSharp/Verse.Sound/SoundParamTarget_PropertyLowPass.cs b/Assembly-CSharp/Verse.Sound/SoundParamTarget_PropertyLowPass.cs index 887f0a05e..818df5d96 100644 --- a/Assembly-CSharp/Verse.Sound/SoundParamTarget_PropertyLowPass.cs +++ b/Assembly-CSharp/Verse.Sound/SoundParamTarget_PropertyLowPass.cs @@ -25,8 +25,8 @@ public override Type NeededFilterType public override void SetOn(Sample sample, float value) { - AudioLowPassFilter audioLowPassFilter = sample.source.GetComponent(); - if (audioLowPassFilter == null) + AudioLowPassFilter audioLowPassFilter = ((Component)sample.source).GetComponent(); + if ((UnityEngine.Object)audioLowPassFilter == (UnityEngine.Object)null) { audioLowPassFilter = sample.source.gameObject.AddComponent(); } diff --git a/Assembly-CSharp/Verse.Sound/SoundParamTarget_PropertyReverb.cs b/Assembly-CSharp/Verse.Sound/SoundParamTarget_PropertyReverb.cs index b536bbcde..b85fa00be 100644 --- a/Assembly-CSharp/Verse.Sound/SoundParamTarget_PropertyReverb.cs +++ b/Assembly-CSharp/Verse.Sound/SoundParamTarget_PropertyReverb.cs @@ -29,24 +29,17 @@ public override Type NeededFilterType public override void SetOn(Sample sample, float value) { - AudioReverbFilter audioReverbFilter = sample.source.GetComponent(); - if (audioReverbFilter == null) + AudioReverbFilter audioReverbFilter = ((Component)sample.source).GetComponent(); + if ((UnityEngine.Object)audioReverbFilter == (UnityEngine.Object)null) { audioReverbFilter = sample.source.gameObject.AddComponent(); } ReverbSetup reverbSetup; - if (value < 0.001f) + if (value < 0.0010000000474974513) { reverbSetup = this.baseSetup; } - if (value > 0.999f) - { - reverbSetup = this.targetSetup; - } - else - { - reverbSetup = ReverbSetup.Lerp(this.baseSetup, this.targetSetup, value); - } + reverbSetup = ((!(value > 0.99900001287460327)) ? ReverbSetup.Lerp(this.baseSetup, this.targetSetup, value) : this.targetSetup); reverbSetup.ApplyTo(audioReverbFilter); } } diff --git a/Assembly-CSharp/Verse.Sound/SoundParamTarget_Volume.cs b/Assembly-CSharp/Verse.Sound/SoundParamTarget_Volume.cs index 351b03db2..c2000fa2c 100644 --- a/Assembly-CSharp/Verse.Sound/SoundParamTarget_Volume.cs +++ b/Assembly-CSharp/Verse.Sound/SoundParamTarget_Volume.cs @@ -1,5 +1,3 @@ -using System; - namespace Verse.Sound { public class SoundParamTarget_Volume : SoundParamTarget diff --git a/Assembly-CSharp/Verse.Sound/SoundParamUpdateMode.cs b/Assembly-CSharp/Verse.Sound/SoundParamUpdateMode.cs index 0c348ae2d..e4f315eda 100644 --- a/Assembly-CSharp/Verse.Sound/SoundParamUpdateMode.cs +++ b/Assembly-CSharp/Verse.Sound/SoundParamUpdateMode.cs @@ -1,10 +1,8 @@ -using System; - namespace Verse.Sound { public enum SoundParamUpdateMode : byte { - Constant, - OncePerSample + Constant = 0, + OncePerSample = 1 } } diff --git a/Assembly-CSharp/Verse.Sound/SoundParameterMapping.cs b/Assembly-CSharp/Verse.Sound/SoundParameterMapping.cs index adde1ebb4..e5dc9e0a1 100644 --- a/Assembly-CSharp/Verse.Sound/SoundParameterMapping.cs +++ b/Assembly-CSharp/Verse.Sound/SoundParameterMapping.cs @@ -1,5 +1,3 @@ -using System; - namespace Verse.Sound { public class SoundParameterMapping @@ -34,16 +32,15 @@ public void DoEditWidgets(WidgetRow widgetRow) public void Apply(Sample samp) { - if (this.inParam == null || this.outParam == null) - { - return; - } - float num = this.inParam.ValueFor(samp); - float value = this.curve.Evaluate(num); - this.outParam.SetOn(samp, value); - if (UnityData.isDebugBuild && this.curve.HasView) + if (this.inParam != null && this.outParam != null) { - this.curve.View.SetDebugInput(samp, num); + float num = this.inParam.ValueFor(samp); + float value = this.curve.Evaluate(num); + this.outParam.SetOn(samp, value); + if (UnityData.isDebugBuild && this.curve.HasView) + { + this.curve.View.SetDebugInput(samp, num); + } } } } diff --git a/Assembly-CSharp/Verse.Sound/SoundParams.cs b/Assembly-CSharp/Verse.Sound/SoundParams.cs index 4d7eb6246..a83e295c8 100644 --- a/Assembly-CSharp/Verse.Sound/SoundParams.cs +++ b/Assembly-CSharp/Verse.Sound/SoundParams.cs @@ -1,4 +1,3 @@ -using System; using System.Collections.Generic; namespace Verse.Sound diff --git a/Assembly-CSharp/Verse.Sound/SoundRoot.cs b/Assembly-CSharp/Verse.Sound/SoundRoot.cs index aa7b69b4d..6870e7068 100644 --- a/Assembly-CSharp/Verse.Sound/SoundRoot.cs +++ b/Assembly-CSharp/Verse.Sound/SoundRoot.cs @@ -1,5 +1,3 @@ -using System; - namespace Verse.Sound { public class SoundRoot diff --git a/Assembly-CSharp/Verse.Sound/SoundSizeAggregator.cs b/Assembly-CSharp/Verse.Sound/SoundSizeAggregator.cs index e2df9870e..5bf03cc1e 100644 --- a/Assembly-CSharp/Verse.Sound/SoundSizeAggregator.cs +++ b/Assembly-CSharp/Verse.Sound/SoundSizeAggregator.cs @@ -18,17 +18,26 @@ public float AggregateSize return this.testSize; } float num = 0f; - foreach (ISizeReporter current in this.reporters) + List.Enumerator enumerator = this.reporters.GetEnumerator(); + try { - num += current.CurrentSize(); + while (enumerator.MoveNext()) + { + ISizeReporter current = enumerator.Current; + num += current.CurrentSize(); + } + return num; + } + finally + { + ((IDisposable)(object)enumerator).Dispose(); } - return num; } } public SoundSizeAggregator() { - this.testSize = Rand.Value * 3f; + this.testSize = (float)(Rand.Value * 3.0); this.testSize *= this.testSize; } diff --git a/Assembly-CSharp/Verse.Sound/SoundSlotManager.cs b/Assembly-CSharp/Verse.Sound/SoundSlotManager.cs index 79b540531..16406657f 100644 --- a/Assembly-CSharp/Verse.Sound/SoundSlotManager.cs +++ b/Assembly-CSharp/Verse.Sound/SoundSlotManager.cs @@ -1,4 +1,3 @@ -using System; using System.Collections.Generic; using UnityEngine; @@ -15,23 +14,26 @@ public static bool CanPlayNow(string slotName) return true; } float num = 0f; - return !SoundSlotManager.allowedPlayTimes.TryGetValue(slotName, out num) || Time.realtimeSinceStartup >= SoundSlotManager.allowedPlayTimes[slotName]; + if (SoundSlotManager.allowedPlayTimes.TryGetValue(slotName, out num) && Time.realtimeSinceStartup < SoundSlotManager.allowedPlayTimes[slotName]) + { + return false; + } + return true; } public static void Notify_Played(string slot, float duration) { - if (slot == string.Empty) - { - return; - } - float a; - if (SoundSlotManager.allowedPlayTimes.TryGetValue(slot, out a)) - { - SoundSlotManager.allowedPlayTimes[slot] = Mathf.Max(a, Time.realtimeSinceStartup + duration); - } - else + if (!(slot == string.Empty)) { - SoundSlotManager.allowedPlayTimes[slot] = Time.realtimeSinceStartup + duration; + float a = default(float); + if (SoundSlotManager.allowedPlayTimes.TryGetValue(slot, out a)) + { + SoundSlotManager.allowedPlayTimes[slot] = Mathf.Max(a, Time.realtimeSinceStartup + duration); + } + else + { + SoundSlotManager.allowedPlayTimes[slot] = Time.realtimeSinceStartup + duration; + } } } } diff --git a/Assembly-CSharp/Verse.Sound/SoundStarter.cs b/Assembly-CSharp/Verse.Sound/SoundStarter.cs index 8a7dd9aa2..8fed883ec 100644 --- a/Assembly-CSharp/Verse.Sound/SoundStarter.cs +++ b/Assembly-CSharp/Verse.Sound/SoundStarter.cs @@ -1,5 +1,4 @@ using RimWorld.Planet; -using System; namespace Verse.Sound { @@ -7,79 +6,80 @@ public static class SoundStarter { public static void PlayOneShotOnCamera(this SoundDef soundDef, Map onlyThisMap = null) { - if (!UnityData.IsInMainThread) + if (UnityData.IsInMainThread) { - return; - } - if (onlyThisMap != null && (Find.VisibleMap != onlyThisMap || WorldRendererUtility.WorldRenderedNow)) - { - return; - } - if (soundDef == null) - { - return; - } - if (soundDef.subSounds.Count > 0) - { - bool flag = false; - for (int i = 0; i < soundDef.subSounds.Count; i++) + if (onlyThisMap != null) { - if (soundDef.subSounds[i].onCamera) - { - flag = true; - break; - } + if (Find.VisibleMap != onlyThisMap) + return; + if (WorldRendererUtility.WorldRenderedNow) + return; } - if (!flag) + if (soundDef != null) { - Log.Error("Tried to play " + soundDef + " on camera but it has no on-camera subSounds."); + if (soundDef.subSounds.Count > 0) + { + bool flag = false; + int num = 0; + while (num < soundDef.subSounds.Count) + { + if (!soundDef.subSounds[num].onCamera) + { + num++; + continue; + } + flag = true; + break; + } + if (!flag) + { + Log.Error("Tried to play " + soundDef + " on camera but it has no on-camera subSounds."); + } + } + soundDef.PlayOneShot(SoundInfo.OnCamera(MaintenanceType.None)); } } - soundDef.PlayOneShot(SoundInfo.OnCamera(MaintenanceType.None)); } public static void PlayOneShot(this SoundDef soundDef, SoundInfo info) { - if (!UnityData.IsInMainThread) - { - return; - } - if (soundDef == null) - { - Log.Error("Tried to PlayOneShot with null SoundDef. Info=" + info); - return; - } - DebugSoundEventsLog.Notify_SoundEvent(soundDef, info); - if (soundDef == null) + if (UnityData.IsInMainThread) { - return; - } - if (soundDef.isUndefined) - { - if (Prefs.DevMode && Find.WindowStack.IsOpen(typeof(EditWindow_DefEditor))) + if (soundDef == null) { - DefDatabase.Clear(); - DefDatabase.AddAllInMods(); - SoundDef soundDef2 = SoundDef.Named(soundDef.defName); - if (!soundDef2.isUndefined) + Log.Error("Tried to PlayOneShot with null SoundDef. Info=" + info); + } + else + { + DebugSoundEventsLog.Notify_SoundEvent(soundDef, info); + if (soundDef != null) { - soundDef2.PlayOneShot(info); + if (soundDef.isUndefined) + { + if (Prefs.DevMode && Find.WindowStack.IsOpen(typeof(EditWindow_DefEditor))) + { + DefDatabase.Clear(); + DefDatabase.AddAllInMods(); + SoundDef soundDef2 = SoundDef.Named(soundDef.defName); + if (!soundDef2.isUndefined) + { + soundDef2.PlayOneShot(info); + } + } + } + else if (soundDef.sustain) + { + Log.Error("Tried to play sustainer SoundDef " + soundDef + " as a one-shot sound."); + } + else if (SoundSlotManager.CanPlayNow(soundDef.slot)) + { + for (int i = 0; i < soundDef.subSounds.Count; i++) + { + soundDef.subSounds[i].TryPlay(info); + } + } } } - return; - } - if (soundDef.sustain) - { - Log.Error("Tried to play sustainer SoundDef " + soundDef + " as a one-shot sound."); - return; - } - if (!SoundSlotManager.CanPlayNow(soundDef.slot)) - { - return; - } - for (int i = 0; i < soundDef.subSounds.Count; i++) - { - soundDef.subSounds[i].TryPlay(info); } } diff --git a/Assembly-CSharp/Verse.Sound/SubSoundDef.cs b/Assembly-CSharp/Verse.Sound/SubSoundDef.cs index ea7519557..60bcdc0fa 100644 --- a/Assembly-CSharp/Verse.Sound/SubSoundDef.cs +++ b/Assembly-CSharp/Verse.Sound/SubSoundDef.cs @@ -1,6 +1,5 @@ using System; using System.Collections.Generic; -using System.Diagnostics; using System.Linq; using UnityEngine; @@ -8,55 +7,79 @@ namespace Verse.Sound { public class SubSoundDef : Editable { - [DefaultValue("UnnamedSubSoundDef"), Description("A name to help you identify the sound.")] + [Description("A name to help you identify the sound.")] + [DefaultValue("UnnamedSubSoundDef")] public string name = "UnnamedSubSoundDef"; - [DefaultValue(false), Description("Whether this sound plays on the camera or in the world.\n\nThis must match what the game expects from the sound Def with this name.")] + [DefaultValue(false)] + [Description("Whether this sound plays on the camera or in the world.\n\nThis must match what the game expects from the sound Def with this name.")] public bool onCamera; - [DefaultValue(false), Description("Whether to mute this subSound while the game is paused (either by the pausing in play or by opening a menu)")] + [DefaultValue(false)] + [Description("Whether to mute this subSound while the game is paused (either by the pausing in play or by opening a menu)")] public bool muteWhenPaused; [Description("The sound grains used for this sample. The game will choose one of these randomly when the sound plays. Sustainers choose one for each sample as it begins.")] public List grains = new List(); - [DefaultFloatRange(50f, 50f), Description("This sound will play at a random volume inside this range.\n\nSustainers will choose a different random volume for each sample."), EditSliderRange(0f, 100f)] + [DefaultFloatRange(50f, 50f)] + [EditSliderRange(0f, 100f)] + [Description("This sound will play at a random volume inside this range.\n\nSustainers will choose a different random volume for each sample.")] public FloatRange volumeRange = new FloatRange(50f, 50f); - [DefaultFloatRange(1f, 1f), Description("This sound will play at a random pitch inside this range.\n\nSustainers will choose a different random pitch for each sample."), EditSliderRange(0.05f, 2f)] + [Description("This sound will play at a random pitch inside this range.\n\nSustainers will choose a different random pitch for each sample.")] + [EditSliderRange(0.05f, 2f)] + [DefaultFloatRange(1f, 1f)] public FloatRange pitchRange = FloatRange.One; - [DefaultFloatRange(25f, 70f), Description("This sound will play max volume when it is under minDistance from the camera.\n\nIt will fade out linearly until the camera distance reaches its max."), EditSliderRange(0f, 200f)] + [EditSliderRange(0f, 200f)] + [Description("This sound will play max volume when it is under minDistance from the camera.\n\nIt will fade out linearly until the camera distance reaches its max.")] + [DefaultFloatRange(25f, 70f)] public FloatRange distRange = new FloatRange(25f, 70f); - [DefaultValue(RepeatSelectMode.NeverLastHalf), Description("When the sound chooses the next grain, you may use this setting to have it avoid repeating the last grain, or avoid repeating any of the grains in the last X played, X being half the total number of grains defined.")] + [Description("When the sound chooses the next grain, you may use this setting to have it avoid repeating the last grain, or avoid repeating any of the grains in the last X played, X being half the total number of grains defined.")] + [DefaultValue(RepeatSelectMode.NeverLastHalf)] public RepeatSelectMode repeatMode = RepeatSelectMode.NeverLastHalf; - [DefaultEmptyList(typeof(SoundParameterMapping)), Description("Mappings between game parameters (like fire size or wind speed) and properties of the sound.")] + [Description("Mappings between game parameters (like fire size or wind speed) and properties of the sound.")] + [DefaultEmptyList(typeof(SoundParameterMapping))] public List paramMappings = new List(); - [DefaultEmptyList(typeof(SoundFilter)), Description("The filters to be applied to this sound.")] + [Description("The filters to be applied to this sound.")] + [DefaultEmptyList(typeof(SoundFilter))] public List filters = new List(); - [DefaultFloatRange(0f, 0f), Description("A range of possible times between when this sound is triggered and when it will actually start playing.")] + [DefaultFloatRange(0f, 0f)] + [Description("A range of possible times between when this sound is triggered and when it will actually start playing.")] public FloatRange startDelayRange = FloatRange.Zero; - [DefaultValue(true), Description("If true, each sample in the sustainer will be looped and ended only after sustainerLoopDurationRange. If not, the sounds will just play once and end after their own length.")] + [Description("If true, each sample in the sustainer will be looped and ended only after sustainerLoopDurationRange. If not, the sounds will just play once and end after their own length.")] + [DefaultValue(true)] public bool sustainLoop = true; - [DefaultFloatRange(9999f, 9999f), Description("The range of durations that individual looped samples in the sustainer will have. Each sample ends after a time randomly chosen in this range.\n\nOnly used if the sustainer is looped."), EditSliderRange(0f, 10f)] + [DefaultFloatRange(9999f, 9999f)] + [EditSliderRange(0f, 10f)] + [Description("The range of durations that individual looped samples in the sustainer will have. Each sample ends after a time randomly chosen in this range.\n\nOnly used if the sustainer is looped.")] public FloatRange sustainLoopDurationRange = new FloatRange(9999f, 9999f); - [DefaultFloatRange(0f, 0f), Description("The time between when one sample ends and the next starts.\n\nSet to negative if you wish samples to overlap."), EditSliderRange(-2f, 2f), LoadAlias("sustainInterval")] + [DefaultFloatRange(0f, 0f)] + [EditSliderRange(-2f, 2f)] + [Description("The time between when one sample ends and the next starts.\n\nSet to negative if you wish samples to overlap.")] + [LoadAlias("sustainInterval")] public FloatRange sustainIntervalRange = FloatRange.Zero; - [DefaultValue(0f), Description("The fade-in time of each sample. The sample will start at 0 volume and fade in over this number of seconds."), EditSliderRange(0f, 2f)] + [Description("The fade-in time of each sample. The sample will start at 0 volume and fade in over this number of seconds.")] + [DefaultValue(0f)] + [EditSliderRange(0f, 2f)] public float sustainAttack; - [DefaultValue(true), Description("Skip the attack on the first sustainer sample.")] + [DefaultValue(true)] + [Description("Skip the attack on the first sustainer sample.")] public bool sustainSkipFirstAttack = true; - [DefaultValue(0f), Description("The fade-out time of each sample. At this number of seconds before the sample ends, it will start fading out. Its volume will be zero at the moment it finishes fading out."), EditSliderRange(0f, 2f)] + [DefaultValue(0f)] + [Description("The fade-out time of each sample. At this number of seconds before the sample ends, it will start fading out. Its volume will be zero at the moment it finishes fading out.")] + [EditSliderRange(0f, 2f)] public float sustainRelease; [Unsaved] @@ -79,32 +102,29 @@ public class SubSoundDef : Editable public virtual void TryPlay(SoundInfo info) { + ResolvedGrain resolvedGrain; if (this.resolvedGrains.Count == 0) { - Log.Error(string.Concat(new object[] - { - "Cannot play ", - this.parentDef, - " (subSound ", - this, - "_: No resolved grains." - })); - return; - } - if (!Find.SoundRoot.oneShotManager.CanAddPlayingOneShot(this.parentDef, info)) - { - return; + Log.Error("Cannot play " + this.parentDef + " (subSound " + this + "_: No resolved grains."); } - ResolvedGrain resolvedGrain = this.RandomizedResolvedGrain(); - ResolvedGrain_Clip resolvedGrain_Clip = resolvedGrain as ResolvedGrain_Clip; - if (resolvedGrain_Clip != null) + else if (Find.SoundRoot.oneShotManager.CanAddPlayingOneShot(this.parentDef, info)) { - if (SampleOneShot.TryMakeAndPlay(this, resolvedGrain_Clip.clip, info) == null) + resolvedGrain = this.RandomizedResolvedGrain(); + ResolvedGrain_Clip resolvedGrain_Clip = resolvedGrain as ResolvedGrain_Clip; + if (resolvedGrain_Clip != null) { + SampleOneShot sampleOneShot = SampleOneShot.TryMakeAndPlay(this, resolvedGrain_Clip.clip, info); + if (sampleOneShot != null) + { + SoundSlotManager.Notify_Played(this.parentDef.slot, resolvedGrain_Clip.clip.length); + goto IL_00a6; + } return; } - SoundSlotManager.Notify_Played(this.parentDef.slot, resolvedGrain_Clip.clip.length); + goto IL_00a6; } + return; + IL_00a6: if (this.distinctResolvedGrainsCount > 1) { if (this.repeatMode == RepeatSelectMode.NeverLastHalf) @@ -128,50 +148,62 @@ public virtual void TryPlay(SoundInfo info) public ResolvedGrain RandomizedResolvedGrain() { ResolvedGrain chosenGrain = null; + goto IL_000d; + IL_000d: while (true) { - chosenGrain = this.resolvedGrains.RandomElement(); + chosenGrain = this.resolvedGrains.RandomElement(); if (this.distinctResolvedGrainsCount <= 1) - { break; - } if (this.repeatMode == RepeatSelectMode.NeverLastHalf) { if (!(from g in this.recentlyPlayedResolvedGrains where g.Equals(chosenGrain) - select g).Any()) - { + select g).Any()) break; - } } - else if (this.repeatMode != RepeatSelectMode.NeverTwice || !chosenGrain.Equals(this.lastPlayedResolvedGrain)) + else { - break; + if (this.repeatMode != RepeatSelectMode.NeverTwice) + break; + if (!chosenGrain.Equals(this.lastPlayedResolvedGrain)) + break; } } return chosenGrain; + IL_008f: + goto IL_000d; } public float RandomizedVolume() { float randomInRange = this.volumeRange.RandomInRange; - return randomInRange / 100f; + return (float)(randomInRange / 100.0); } public override void ResolveReferences() { - LongEventHandler.ExecuteWhenFinished(delegate + LongEventHandler.ExecuteWhenFinished((Action)delegate { this.resolvedGrains.Clear(); - foreach (AudioGrain current in this.grains) + List.Enumerator enumerator = this.grains.GetEnumerator(); + try { - foreach (ResolvedGrain current2 in current.GetResolvedGrains()) + while (enumerator.MoveNext()) { - this.resolvedGrains.Add(current2); + AudioGrain current = enumerator.Current; + foreach (ResolvedGrain resolvedGrain in current.GetResolvedGrains()) + { + this.resolvedGrains.Add(resolvedGrain); + } } } - this.distinctResolvedGrainsCount = this.resolvedGrains.Distinct().Count(); - this.numToAvoid = Mathf.FloorToInt((float)this.distinctResolvedGrainsCount / 2f); + finally + { + ((IDisposable)(object)enumerator).Dispose(); + } + this.distinctResolvedGrainsCount = this.resolvedGrains.Distinct().Count(); + this.numToAvoid = Mathf.FloorToInt((float)((float)this.distinctResolvedGrainsCount / 2.0)); if (this.distinctResolvedGrainsCount >= 6) { this.numToAvoid++; @@ -179,14 +211,52 @@ public override void ResolveReferences() }); } - [DebuggerHidden] public override IEnumerable ConfigErrors() { - SubSoundDef.c__Iterator1DF c__Iterator1DF = new SubSoundDef.c__Iterator1DF(); - c__Iterator1DF.<>f__this = this; - SubSoundDef.c__Iterator1DF expr_0E = c__Iterator1DF; - expr_0E.$PC = -2; - return expr_0E; + if (this.resolvedGrains.Count == 0) + { + yield return "No grains resolved."; + } + if (this.sustainAttack + this.sustainRelease > this.sustainLoopDurationRange.TrueMin) + { + yield return "Attack + release < min loop duration. Sustain samples will cut off."; + } + if (this.distRange.min > this.distRange.max) + { + yield return "Dist range min/max are reversed."; + } + List.Enumerator enumerator = this.paramMappings.GetEnumerator(); + try + { + while (true) + { + if (enumerator.MoveNext()) + { + SoundParameterMapping mapping = enumerator.Current; + if (mapping.inParam != null && mapping.outParam != null) + { + if (mapping.outParam != null) + { + Type neededFilter = mapping.outParam.NeededFilterType; + if (neededFilter != null && !(from fil in this.filters + where fil.GetType() == ((_003CConfigErrors_003Ec__Iterator1DF)/*Error near IL_0197: stateMachine*/)._003CneededFilter_003E__2 + select fil).Any()) + { + yield return "A parameter wants to modify the " + neededFilter.ToString() + " filter, but this sound doesn't have it."; + } + } + continue; + } + break; + } + yield break; + } + yield return "At least one parameter mapping is missing an in or out parameter."; + } + finally + { + ((IDisposable)(object)enumerator).Dispose(); + } } public override string ToString() diff --git a/Assembly-CSharp/Verse.Sound/SubSustainer.cs b/Assembly-CSharp/Verse.Sound/SubSustainer.cs index e9e28653e..0cd90946a 100644 --- a/Assembly-CSharp/Verse.Sound/SubSustainer.cs +++ b/Assembly-CSharp/Verse.Sound/SubSustainer.cs @@ -43,7 +43,7 @@ public SubSustainer(Sustainer parent, SubSoundDef subSoundDef) { this.parent = parent; this.subDef = subSoundDef; - LongEventHandler.ExecuteWhenFinished(delegate + LongEventHandler.ExecuteWhenFinished((Action)delegate { this.creationFrame = Time.frameCount; this.creationRealTime = Time.realtimeSinceStartup; @@ -51,7 +51,7 @@ public SubSustainer(Sustainer parent, SubSoundDef subSoundDef) { this.creationTick = Find.TickManager.TicksGame; } - if (this.subDef.startDelayRange.TrueMax < 0.001f) + if (this.subDef.startDelayRange.TrueMax < 0.0010000000474974513) { this.StartSample(); } @@ -67,68 +67,53 @@ private void StartSample() ResolvedGrain resolvedGrain = this.subDef.RandomizedResolvedGrain(); if (resolvedGrain == null) { - Log.Error(string.Concat(new object[] - { - "SubSustainer for ", - this.subDef, - " of ", - this.parent.def, - " could not resolve any grains." - })); + Log.Error("SubSustainer for " + this.subDef + " of " + this.parent.def + " could not resolve any grains."); this.parent.End(); - return; - } - float num; - if (this.subDef.sustainLoop) - { - num = this.subDef.sustainLoopDurationRange.RandomInRange; } else { - num = resolvedGrain.duration; - } - float num2 = Time.realtimeSinceStartup + num; - this.nextSampleStartTime = num2 + this.subDef.sustainIntervalRange.RandomInRange; - if (this.nextSampleStartTime < Time.realtimeSinceStartup + 0.01f) - { - this.nextSampleStartTime = Time.realtimeSinceStartup + 0.01f; - } - if (resolvedGrain is ResolvedGrain_Silence) - { - return; - } - SampleSustainer sampleSustainer = SampleSustainer.TryMakeAndPlay(this, ((ResolvedGrain_Clip)resolvedGrain).clip, num2); - if (sampleSustainer == null) - { - return; - } - if (this.subDef.sustainSkipFirstAttack && Time.frameCount == this.creationFrame) - { - sampleSustainer.resolvedSkipAttack = true; + float num = (!this.subDef.sustainLoop) ? resolvedGrain.duration : this.subDef.sustainLoopDurationRange.RandomInRange; + float num2 = Time.realtimeSinceStartup + num; + this.nextSampleStartTime = num2 + this.subDef.sustainIntervalRange.RandomInRange; + if (this.nextSampleStartTime < Time.realtimeSinceStartup + 0.0099999997764825821) + { + this.nextSampleStartTime = (float)(Time.realtimeSinceStartup + 0.0099999997764825821); + } + if (!(resolvedGrain is ResolvedGrain_Silence)) + { + SampleSustainer sampleSustainer = SampleSustainer.TryMakeAndPlay(this, ((ResolvedGrain_Clip)resolvedGrain).clip, num2); + if (sampleSustainer != null) + { + if (this.subDef.sustainSkipFirstAttack && Time.frameCount == this.creationFrame) + { + sampleSustainer.resolvedSkipAttack = true; + } + this.samples.Add(sampleSustainer); + } + } } - this.samples.Add(sampleSustainer); } public void SubSustainerUpdate() { - for (int i = this.samples.Count - 1; i >= 0; i--) + for (int num = this.samples.Count - 1; num >= 0; num--) { - if (Time.realtimeSinceStartup > this.samples[i].scheduledEndTime) + if (Time.realtimeSinceStartup > this.samples[num].scheduledEndTime) { - this.EndSample(this.samples[i]); + this.EndSample(this.samples[num]); } } if (Time.realtimeSinceStartup > this.nextSampleStartTime) { this.StartSample(); } - for (int j = 0; j < this.samples.Count; j++) + for (int i = 0; i < this.samples.Count; i++) { - this.samples[j].ApplyMappedParameters(); + this.samples[i].ApplyMappedParameters(); } - for (int k = 0; k < this.samples.Count; k++) + for (int j = 0; j < this.samples.Count; j++) { - this.samples[k].UpdateSourceVolume(); + this.samples[j].UpdateSourceVolume(); } } @@ -153,15 +138,24 @@ public override string ToString() public override int GetHashCode() { - return Gen.HashCombine(this.creationRealTime.GetHashCode(), this.subDef); + return Gen.HashCombine(this.creationRealTime.GetHashCode(), this.subDef); } public string SamplesDebugString() { StringBuilder stringBuilder = new StringBuilder(); - foreach (SampleSustainer current in this.samples) + List.Enumerator enumerator = this.samples.GetEnumerator(); + try + { + while (enumerator.MoveNext()) + { + SampleSustainer current = enumerator.Current; + stringBuilder.AppendLine(current.ToString()); + } + } + finally { - stringBuilder.AppendLine(current.ToString()); + ((IDisposable)(object)enumerator).Dispose(); } return stringBuilder.ToString(); } diff --git a/Assembly-CSharp/Verse.Sound/Sustainer.cs b/Assembly-CSharp/Verse.Sound/Sustainer.cs index 89abb494d..98c645ed3 100644 --- a/Assembly-CSharp/Verse.Sound/Sustainer.cs +++ b/Assembly-CSharp/Verse.Sound/Sustainer.cs @@ -28,7 +28,7 @@ public bool Ended { get { - return this.endRealTime >= 0f; + return this.endRealTime >= 0.0; } } @@ -48,18 +48,11 @@ public float CameraDistanceSquared { return 0f; } - if (this.worldRootObject == null) + if ((UnityEngine.Object)this.worldRootObject == (UnityEngine.Object)null) { if (Prefs.DevMode) { - Log.Error(string.Concat(new object[] - { - "Sustainer ", - this.def, - " info is ", - this.info, - " but its worldRootObject is null" - })); + Log.Error("Sustainer " + this.def + " info is " + this.info + " but its worldRootObject is null"); } return 0f; } @@ -73,9 +66,9 @@ public Sustainer(SoundDef def, SoundInfo info) this.info = info; if (def.subSounds.Count > 0) { - foreach (KeyValuePair current in info.DefinedParameters) + foreach (KeyValuePair definedParameter in info.DefinedParameters) { - this.externalParams[current.Key] = current.Value; + this.externalParams[definedParameter.Key] = definedParameter.Value; } if (def.HasSubSoundsInWorld) { @@ -100,7 +93,7 @@ public Sustainer(SoundDef def, SoundInfo info) this.subSustainers.Add(new SubSustainer(this, def.subSounds[i])); } } - LongEventHandler.ExecuteWhenFinished(delegate + LongEventHandler.ExecuteWhenFinished((Action)delegate { this.lastMaintainTick = Find.TickManager.TicksGame; this.lastMaintainFrame = Time.frameCount; @@ -145,7 +138,7 @@ public void SustainerUpdate() private void UpdateRootObjectPosition() { - if (this.worldRootObject != null) + if ((UnityEngine.Object)this.worldRootObject != (UnityEngine.Object)null) { this.worldRootObject.transform.position = this.info.Maker.Cell.ToVector3ShiftedWithAltitude(0f); } @@ -156,9 +149,8 @@ public void Maintain() if (this.Ended) { Log.Error("Tried to maintain ended sustainer: " + this.def); - return; } - if (this.info.Maintenance == MaintenanceType.PerTick) + else if (this.info.Maintenance == MaintenanceType.PerTick) { this.lastMaintainTick = Find.TickManager.TicksGame; } @@ -171,7 +163,7 @@ public void Maintain() public void End() { this.endRealTime = Time.realtimeSinceStartup; - if (this.def.sustainFadeoutTime < 0.001f) + if (this.def.sustainFadeoutTime < 0.0010000000474974513) { this.Cleanup(); } @@ -189,7 +181,7 @@ private void Cleanup() } if (this.def.sustainStopSound != string.Empty) { - if (this.worldRootObject != null) + if ((UnityEngine.Object)this.worldRootObject != (UnityEngine.Object)null) { Map map = this.info.Maker.Map; if (map != null) @@ -203,7 +195,7 @@ private void Cleanup() SoundDef.Named(this.def.sustainStopSound).PlayOneShot(SoundInfo.OnCamera(MaintenanceType.None)); } } - if (this.worldRootObject != null) + if ((UnityEngine.Object)this.worldRootObject != (UnityEngine.Object)null) { UnityEngine.Object.Destroy(this.worldRootObject); } @@ -212,14 +204,23 @@ private void Cleanup() public string DebugString() { - string text = this.def.defName; - text = text + "\n inScopePercent=" + this.scopeFader.inScopePercent; - text = text + "\n CameraDistanceSquared=" + this.CameraDistanceSquared; - foreach (SubSustainer current in this.subSustainers) + string defName = this.def.defName; + defName = defName + "\n inScopePercent=" + this.scopeFader.inScopePercent; + defName = defName + "\n CameraDistanceSquared=" + this.CameraDistanceSquared; + List.Enumerator enumerator = this.subSustainers.GetEnumerator(); + try { - text = text + "\n sub: " + current; + while (enumerator.MoveNext()) + { + SubSustainer current = enumerator.Current; + defName = defName + "\n sub: " + current; + } + return defName; + } + finally + { + ((IDisposable)(object)enumerator).Dispose(); } - return text; } } } diff --git a/Assembly-CSharp/Verse.Sound/SustainerAggregatorUtility.cs b/Assembly-CSharp/Verse.Sound/SustainerAggregatorUtility.cs index d76e02718..c9056e57d 100644 --- a/Assembly-CSharp/Verse.Sound/SustainerAggregatorUtility.cs +++ b/Assembly-CSharp/Verse.Sound/SustainerAggregatorUtility.cs @@ -1,4 +1,5 @@ using System; +using System.Collections.Generic; namespace Verse.Sound { @@ -9,14 +10,23 @@ public static class SustainerAggregatorUtility public static Sustainer AggregateOrSpawnSustainerFor(ISizeReporter reporter, SoundDef def, SoundInfo info) { Sustainer sustainer = null; - foreach (Sustainer current in Find.SoundRoot.sustainerManager.AllSustainers) + List.Enumerator enumerator = Find.SoundRoot.sustainerManager.AllSustainers.GetEnumerator(); + try { - if (current.def == def && current.info.Maker.Map == info.Maker.Map && current.info.Maker.Cell.InHorDistOf(info.Maker.Cell, SustainerAggregatorUtility.AggregateRadius)) + while (enumerator.MoveNext()) { - sustainer = current; - break; + Sustainer current = enumerator.Current; + if (current.def == def && current.info.Maker.Map == info.Maker.Map && current.info.Maker.Cell.InHorDistOf(info.Maker.Cell, SustainerAggregatorUtility.AggregateRadius)) + { + sustainer = current; + break; + } } } + finally + { + ((IDisposable)(object)enumerator).Dispose(); + } if (sustainer == null) { sustainer = def.TrySpawnSustainer(info); diff --git a/Assembly-CSharp/Verse.Sound/SustainerManager.cs b/Assembly-CSharp/Verse.Sound/SustainerManager.cs index 277ff80f1..239a29b9a 100644 --- a/Assembly-CSharp/Verse.Sound/SustainerManager.cs +++ b/Assembly-CSharp/Verse.Sound/SustainerManager.cs @@ -42,9 +42,9 @@ public bool SustainerExists(SoundDef def) public void SustainerManagerUpdate() { - for (int i = this.allSustainers.Count - 1; i >= 0; i--) + for (int num = this.allSustainers.Count - 1; num >= 0; num--) { - this.allSustainers[i].SustainerUpdate(); + this.allSustainers[num].SustainerUpdate(); } this.UpdateAllSustainerScopes(); } @@ -66,49 +66,65 @@ public void UpdateAllSustainerScopes() SustainerManager.playingPerDef[sustainer.def].Add(sustainer); } } - foreach (KeyValuePair> current in SustainerManager.playingPerDef) + Dictionary>.Enumerator enumerator = SustainerManager.playingPerDef.GetEnumerator(); + try { - SoundDef key = current.Key; - List value = current.Value; - int num = value.Count - key.maxVoices; - if (num < 0) + while (enumerator.MoveNext()) { - for (int j = 0; j < value.Count; j++) + KeyValuePair> current = enumerator.Current; + SoundDef key = current.Key; + List value = current.Value; + int num = value.Count - key.maxVoices; + if (num < 0) { - value[j].scopeFader.inScope = true; - } - } - else - { - for (int k = 0; k < value.Count; k++) - { - value[k].scopeFader.inScope = false; - } - int num2 = 0; - foreach (Sustainer current2 in from lo in value - orderby lo.CameraDistanceSquared - select lo) - { - current2.scopeFader.inScope = true; - num2++; - if (num2 >= key.maxVoices) + for (int j = 0; j < value.Count; j++) { - break; + value[j].scopeFader.inScope = true; } } - for (int l = 0; l < value.Count; l++) + else { - if (!value[l].scopeFader.inScope) + for (int k = 0; k < value.Count; k++) + { + value[k].scopeFader.inScope = false; + } + int num2 = 0; + foreach (Sustainer item in from lo in value + orderby lo.CameraDistanceSquared + select lo) { - value[l].scopeFader.inScopePercent = 0f; + item.scopeFader.inScope = true; + num2++; + if (num2 >= key.maxVoices) + break; + } + for (int l = 0; l < value.Count; l++) + { + if (!value[l].scopeFader.inScope) + { + value[l].scopeFader.inScopePercent = 0f; + } } } } } - foreach (KeyValuePair> current3 in SustainerManager.playingPerDef) + finally + { + ((IDisposable)(object)enumerator).Dispose(); + } + Dictionary>.Enumerator enumerator3 = SustainerManager.playingPerDef.GetEnumerator(); + try + { + while (enumerator3.MoveNext()) + { + KeyValuePair> current3 = enumerator3.Current; + current3.Value.Clear(); + SimplePool>.Return(current3.Value); + } + } + finally { - current3.Value.Clear(); - SimplePool>.Return(current3.Value); + ((IDisposable)(object)enumerator3).Dispose(); } SustainerManager.playingPerDef.Clear(); ProfilerThreadCheck.EndSample(); @@ -116,7 +132,7 @@ orderby lo.CameraDistanceSquared public void RemoveAllFromMap(Map map) { - this.allSustainers.RemoveAll((Sustainer sustainer) => sustainer.info.Maker.Map == map); + this.allSustainers.RemoveAll((Predicate)((Sustainer sustainer) => sustainer.info.Maker.Map == map)); } } } diff --git a/Assembly-CSharp/Verse.Sound/SustainerScopeFader.cs b/Assembly-CSharp/Verse.Sound/SustainerScopeFader.cs index 33990cd13..1872a2d28 100644 --- a/Assembly-CSharp/Verse.Sound/SustainerScopeFader.cs +++ b/Assembly-CSharp/Verse.Sound/SustainerScopeFader.cs @@ -1,5 +1,3 @@ -using System; - namespace Verse.Sound { public class SustainerScopeFader @@ -16,9 +14,8 @@ public void SustainerScopeUpdate() { if (this.inScope) { - float num = this.inScopePercent + 0.05f; - this.inScopePercent = num; - if (this.inScopePercent > 1f) + float num = this.inScopePercent += 0.05f; + if (this.inScopePercent > 1.0) { this.inScopePercent = 1f; } @@ -26,7 +23,7 @@ public void SustainerScopeUpdate() else { this.inScopePercent -= 0.03f; - if (this.inScopePercent <= 0.001f) + if (this.inScopePercent <= 0.0010000000474974513) { this.inScopePercent = 0f; } diff --git a/Assembly-CSharp/Verse.Sound/TimeType.cs b/Assembly-CSharp/Verse.Sound/TimeType.cs index d77424ce9..28b37a5d1 100644 --- a/Assembly-CSharp/Verse.Sound/TimeType.cs +++ b/Assembly-CSharp/Verse.Sound/TimeType.cs @@ -1,10 +1,8 @@ -using System; - namespace Verse.Sound { public enum TimeType : byte { - Ticks, - RealtimeSeconds + Ticks = 0, + RealtimeSeconds = 1 } } diff --git a/Assembly-CSharp/Verse.Sound/VoicePriorityMode.cs b/Assembly-CSharp/Verse.Sound/VoicePriorityMode.cs index 327e398ae..08ce2cbb8 100644 --- a/Assembly-CSharp/Verse.Sound/VoicePriorityMode.cs +++ b/Assembly-CSharp/Verse.Sound/VoicePriorityMode.cs @@ -1,10 +1,8 @@ -using System; - namespace Verse.Sound { public enum VoicePriorityMode : byte { - PrioritizeNewest, - PrioritizeNearest + PrioritizeNewest = 0, + PrioritizeNearest = 1 } } diff --git a/Assembly-CSharp/Verse.Steam/Dialog_WorkshopOperationInProgress.cs b/Assembly-CSharp/Verse.Steam/Dialog_WorkshopOperationInProgress.cs index be53efa85..4a9714789 100644 --- a/Assembly-CSharp/Verse.Steam/Dialog_WorkshopOperationInProgress.cs +++ b/Assembly-CSharp/Verse.Steam/Dialog_WorkshopOperationInProgress.cs @@ -1,5 +1,4 @@ using Steamworks; -using System; using UnityEngine; namespace Verse.Steam @@ -16,39 +15,41 @@ public override Vector2 InitialSize public Dialog_WorkshopOperationInProgress() { - this.forcePause = true; - this.closeOnEscapeKey = false; - this.absorbInputAroundWindow = true; - this.preventDrawTutor = true; + base.forcePause = true; + base.closeOnEscapeKey = false; + base.absorbInputAroundWindow = true; + base.preventDrawTutor = true; } public override void DoWindowContents(Rect inRect) { - EItemUpdateStatus eItemUpdateStatus; - float num; + EItemUpdateStatus eItemUpdateStatus = default(EItemUpdateStatus); + float num = default(float); Workshop.GetUpdateStatus(out eItemUpdateStatus, out num); WorkshopInteractStage curStage = Workshop.CurStage; if (curStage == WorkshopInteractStage.None && eItemUpdateStatus == EItemUpdateStatus.k_EItemUpdateStatusInvalid) { this.Close(true); - return; } - string text = string.Empty; - if (curStage != WorkshopInteractStage.None) + else { - text += curStage.GetLabel(); - text += "\n\n"; - } - if (eItemUpdateStatus != EItemUpdateStatus.k_EItemUpdateStatusInvalid) - { - text += eItemUpdateStatus.GetLabel(); - if (num > 0f) + string text = string.Empty; + if (curStage != 0) + { + text += curStage.GetLabel(); + text += "\n\n"; + } + if (eItemUpdateStatus != 0) { - text = text + " (" + num.ToStringPercent() + ")"; + text += eItemUpdateStatus.GetLabel(); + if (num > 0.0) + { + text = text + " (" + num.ToStringPercent() + ")"; + } + text += GenText.MarchingEllipsis(0f); } - text += GenText.MarchingEllipsis(0f); + Widgets.Label(inRect, text); } - Widgets.Label(inRect, text); } public static void CloseAll() diff --git a/Assembly-CSharp/Verse.Steam/SteamManager.cs b/Assembly-CSharp/Verse.Steam/SteamManager.cs index fda301ba1..4cfb214a8 100644 --- a/Assembly-CSharp/Verse.Steam/SteamManager.cs +++ b/Assembly-CSharp/Verse.Steam/SteamManager.cs @@ -29,64 +29,62 @@ public static bool Active public static void InitIfNeeded() { - if (SteamManager.initializedInt) - { - return; - } - if (!Packsize.Test()) - { - Log.Error("[Steamworks.NET] Packsize Test returned false, the wrong version of Steamworks.NET is being run in this platform."); - } - if (!DllCheck.Test()) - { - Log.Error("[Steamworks.NET] DllCheck Test returned false, One or more of the Steamworks binaries seems to be the wrong version."); - } - try + if (!SteamManager.initializedInt) { - if (SteamAPI.RestartAppIfNecessary(AppId_t.Invalid)) + if (!Packsize.Test()) + { + Log.Error("[Steamworks.NET] Packsize Test returned false, the wrong version of Steamworks.NET is being run in this platform."); + } + if (!DllCheck.Test()) + { + Log.Error("[Steamworks.NET] DllCheck Test returned false, One or more of the Steamworks binaries seems to be the wrong version."); + } + try + { + if (SteamAPI.RestartAppIfNecessary(AppId_t.Invalid)) + { + Application.Quit(); + return; + } + } + catch (DllNotFoundException arg) { + Log.Error("[Steamworks.NET] Could not load [lib]steam_api.dll/so/dylib. It's likely not in the correct location. Refer to the README for more details.\n" + arg); Application.Quit(); return; + IL_006c:; } - } - catch (DllNotFoundException arg) - { - Log.Error("[Steamworks.NET] Could not load [lib]steam_api.dll/so/dylib. It's likely not in the correct location. Refer to the README for more details.\n" + arg); - Application.Quit(); - return; - } - SteamManager.initializedInt = SteamAPI.Init(); - if (!SteamManager.initializedInt) - { - Log.Warning("[Steamworks.NET] SteamAPI.Init() failed. Possible causes: Steam client not running, launched from outside Steam without steam_appid.txt in place, running with different privileges than Steam client (e.g. \"as administrator\")"); - } - else - { - if (SteamManager.steamAPIWarningMessageHook == null) + SteamManager.initializedInt = SteamAPI.Init(); + if (!SteamManager.initializedInt) { - SteamManager.steamAPIWarningMessageHook = new SteamAPIWarningMessageHook_t(SteamManager.SteamAPIDebugTextHook); - SteamClient.SetWarningMessageHook(SteamManager.steamAPIWarningMessageHook); + Log.Warning("[Steamworks.NET] SteamAPI.Init() failed. Possible causes: Steam client not running, launched from outside Steam without steam_appid.txt in place, running with different privileges than Steam client (e.g. \"as administrator\")"); + } + else + { + if ((object)SteamManager.steamAPIWarningMessageHook == null) + { + SteamManager.steamAPIWarningMessageHook = new SteamAPIWarningMessageHook_t(SteamManager.SteamAPIDebugTextHook); + SteamClient.SetWarningMessageHook(SteamManager.steamAPIWarningMessageHook); + } + Workshop.Init(); } - Workshop.Init(); } } public static void Update() { - if (!SteamManager.initializedInt) + if (SteamManager.initializedInt) { - return; + SteamAPI.RunCallbacks(); } - SteamAPI.RunCallbacks(); } public static void ShutdownSteam() { - if (!SteamManager.initializedInt) + if (SteamManager.initializedInt) { - return; + SteamAPI.Shutdown(); } - SteamAPI.Shutdown(); } private static void SteamAPIDebugTextHook(int nSeverity, StringBuilder pchDebugText) diff --git a/Assembly-CSharp/Verse.Steam/Workshop.cs b/Assembly-CSharp/Verse.Steam/Workshop.cs index 6110e3960..5e729a38d 100644 --- a/Assembly-CSharp/Verse.Steam/Workshop.cs +++ b/Assembly-CSharp/Verse.Steam/Workshop.cs @@ -2,7 +2,6 @@ using Steamworks; using System; using System.Collections.Generic; -using System.Diagnostics; using System.IO; using System.Linq; using System.Text; @@ -52,43 +51,39 @@ internal static void Init() internal static void Upload(WorkshopUploadable item) { - if (Workshop.curStage != WorkshopInteractStage.None) + if (Workshop.curStage != 0) { Messages.Message("UploadAlreadyInProgress".Translate(), MessageSound.RejectInput); - return; } - Workshop.uploadingHook = item.GetWorkshopItemHook(); - if (Workshop.uploadingHook.PublishedFileId != PublishedFileId_t.Invalid) + else { - if (Prefs.LogVerbose) + Workshop.uploadingHook = item.GetWorkshopItemHook(); + if (Workshop.uploadingHook.PublishedFileId != PublishedFileId_t.Invalid) { - Log.Message(string.Concat(new object[] + if (Prefs.LogVerbose) { - "Workshop: Starting item update for mod '", - Workshop.uploadingHook.Name, - "' with PublishedFileId ", - Workshop.uploadingHook.PublishedFileId - })); + Log.Message("Workshop: Starting item update for mod '" + Workshop.uploadingHook.Name + "' with PublishedFileId " + Workshop.uploadingHook.PublishedFileId); + } + Workshop.curStage = WorkshopInteractStage.SubmittingItem; + Workshop.curUpdateHandle = SteamUGC.StartItemUpdate(SteamUtils.GetAppID(), Workshop.uploadingHook.PublishedFileId); + Workshop.SetWorkshopItemDataFrom(Workshop.curUpdateHandle, Workshop.uploadingHook, false); + SteamAPICall_t hAPICall = SteamUGC.SubmitItemUpdate(Workshop.curUpdateHandle, "[Auto-generated text]: Update on " + DateTime.Now.ToString() + "."); + Workshop.submitResult = CallResult.Create(new CallResult.APIDispatchDelegate(Workshop.OnItemSubmitted)); + Workshop.submitResult.Set(hAPICall, null); } - Workshop.curStage = WorkshopInteractStage.SubmittingItem; - Workshop.curUpdateHandle = SteamUGC.StartItemUpdate(SteamUtils.GetAppID(), Workshop.uploadingHook.PublishedFileId); - Workshop.SetWorkshopItemDataFrom(Workshop.curUpdateHandle, Workshop.uploadingHook, false); - SteamAPICall_t hAPICall = SteamUGC.SubmitItemUpdate(Workshop.curUpdateHandle, "[Auto-generated text]: Update on " + DateTime.Now.ToString() + "."); - Workshop.submitResult = CallResult.Create(new CallResult.APIDispatchDelegate(Workshop.OnItemSubmitted)); - Workshop.submitResult.Set(hAPICall, null); - } - else - { - if (Prefs.LogVerbose) + else { - Log.Message("Workshop: Starting item creation for mod '" + Workshop.uploadingHook.Name + "'."); + if (Prefs.LogVerbose) + { + Log.Message("Workshop: Starting item creation for mod '" + Workshop.uploadingHook.Name + "'."); + } + Workshop.curStage = WorkshopInteractStage.CreatingItem; + SteamAPICall_t hAPICall2 = SteamUGC.CreateItem(SteamUtils.GetAppID(), EWorkshopFileType.k_EWorkshopFileTypeFirst); + Workshop.createResult = CallResult.Create(new CallResult.APIDispatchDelegate(Workshop.OnItemCreated)); + Workshop.createResult.Set(hAPICall2, null); } - Workshop.curStage = WorkshopInteractStage.CreatingItem; - SteamAPICall_t hAPICall2 = SteamUGC.CreateItem(SteamUtils.GetAppID(), EWorkshopFileType.k_EWorkshopFileTypeFirst); - Workshop.createResult = CallResult.Create(new CallResult.APIDispatchDelegate(Workshop.OnItemCreated)); - Workshop.createResult.Set(hAPICall2, null); + Find.WindowStack.Add(new Dialog_WorkshopOperationInProgress()); } - Find.WindowStack.Add(new Dialog_WorkshopOperationInProgress()); } internal static void Unsubscribe(WorkshopUploadable item) @@ -101,62 +96,61 @@ internal static void RequestItemsDetails(PublishedFileId_t[] publishedFileIds) if (Workshop.detailsQueryCount >= 0) { Log.Error("Requested Workshop item details while a details request was already pending."); - return; } - Workshop.detailsQueryCount = publishedFileIds.Length; - Workshop.detailsQueryHandle = SteamUGC.CreateQueryUGCDetailsRequest(publishedFileIds, (uint)Workshop.detailsQueryCount); - SteamAPICall_t hAPICall = SteamUGC.SendQueryUGCRequest(Workshop.detailsQueryHandle); - Workshop.requestDetailsResult = CallResult.Create(new CallResult.APIDispatchDelegate(Workshop.OnGotItemDetails)); - Workshop.requestDetailsResult.Set(hAPICall, null); + else + { + Workshop.detailsQueryCount = publishedFileIds.Length; + Workshop.detailsQueryHandle = SteamUGC.CreateQueryUGCDetailsRequest(publishedFileIds, (uint)Workshop.detailsQueryCount); + SteamAPICall_t hAPICall = SteamUGC.SendQueryUGCRequest(Workshop.detailsQueryHandle); + Workshop.requestDetailsResult = CallResult.Create(new CallResult.APIDispatchDelegate(Workshop.OnGotItemDetails)); + Workshop.requestDetailsResult.Set(hAPICall, null); + } } internal static void OnItemSubscribed(RemoteStoragePublishedFileSubscribed_t result) { - if (!Workshop.IsOurAppId(result.m_nAppID)) - { - return; - } - if (Prefs.LogVerbose) + if (Workshop.IsOurAppId(result.m_nAppID)) { - Log.Message("Workshop: Item subscribed: " + result.m_nPublishedFileId); + if (Prefs.LogVerbose) + { + Log.Message("Workshop: Item subscribed: " + result.m_nPublishedFileId); + } + WorkshopItems.Notify_Subscribed(result.m_nPublishedFileId); } - WorkshopItems.Notify_Subscribed(result.m_nPublishedFileId); } internal static void OnItemInstalled(ItemInstalled_t result) { - if (!Workshop.IsOurAppId(result.m_unAppID)) - { - return; - } - if (Prefs.LogVerbose) + if (Workshop.IsOurAppId(result.m_unAppID)) { - Log.Message("Workshop: Item installed: " + result.m_nPublishedFileId); + if (Prefs.LogVerbose) + { + Log.Message("Workshop: Item installed: " + result.m_nPublishedFileId); + } + WorkshopItems.Notify_Installed(result.m_nPublishedFileId); } - WorkshopItems.Notify_Installed(result.m_nPublishedFileId); } internal static void OnItemUnsubscribed(RemoteStoragePublishedFileUnsubscribed_t result) { - if (!Workshop.IsOurAppId(result.m_nAppID)) + if (Workshop.IsOurAppId(result.m_nAppID)) { - return; - } - if (Prefs.LogVerbose) - { - Log.Message("Workshop: Item unsubscribed: " + result.m_nPublishedFileId); - } - Page_ModsConfig page_ModsConfig = Find.WindowStack.WindowOfType(); - if (page_ModsConfig != null) - { - page_ModsConfig.Notify_SteamItemUnsubscribed(result.m_nPublishedFileId); - } - Page_SelectScenario page_SelectScenario = Find.WindowStack.WindowOfType(); - if (page_SelectScenario != null) - { - page_SelectScenario.Notify_SteamItemUnsubscribed(result.m_nPublishedFileId); + if (Prefs.LogVerbose) + { + Log.Message("Workshop: Item unsubscribed: " + result.m_nPublishedFileId); + } + Page_ModsConfig page_ModsConfig = Find.WindowStack.WindowOfType(); + if (page_ModsConfig != null) + { + page_ModsConfig.Notify_SteamItemUnsubscribed(result.m_nPublishedFileId); + } + Page_SelectScenario page_SelectScenario = Find.WindowStack.WindowOfType(); + if (page_SelectScenario != null) + { + page_SelectScenario.Notify_SteamItemUnsubscribed(result.m_nPublishedFileId); + } + WorkshopItems.Notify_Unsubscribed(result.m_nPublishedFileId); } - WorkshopItems.Notify_Unsubscribed(result.m_nPublishedFileId); } private static void OnItemCreated(CreateItemResult_t result, bool IOFailure) @@ -166,28 +160,27 @@ private static void OnItemCreated(CreateItemResult_t result, bool IOFailure) Workshop.uploadingHook = null; Dialog_WorkshopOperationInProgress.CloseAll(); Log.Error("Workshop: OnItemCreated failure. Result: " + result.m_eResult.GetLabel()); - Find.WindowStack.Add(new Dialog_MessageBox("WorkshopSubmissionFailed".Translate(new object[] - { - GenText.SplitCamelCase(result.m_eResult.GetLabel()) - }), null, null, null, null, null, false)); - return; - } - Workshop.uploadingHook.PublishedFileId = result.m_nPublishedFileId; - if (Prefs.LogVerbose) - { - Log.Message("Workshop: Item created. PublishedFileId: " + Workshop.uploadingHook.PublishedFileId); + Find.WindowStack.Add(new Dialog_MessageBox("WorkshopSubmissionFailed".Translate(GenText.SplitCamelCase(result.m_eResult.GetLabel())), (string)null, null, (string)null, null, (string)null, false)); } - Workshop.curUpdateHandle = SteamUGC.StartItemUpdate(SteamUtils.GetAppID(), Workshop.uploadingHook.PublishedFileId); - Workshop.SetWorkshopItemDataFrom(Workshop.curUpdateHandle, Workshop.uploadingHook, true); - Workshop.curStage = WorkshopInteractStage.SubmittingItem; - if (Prefs.LogVerbose) + else { - Log.Message("Workshop: Submitting item."); + Workshop.uploadingHook.PublishedFileId = result.m_nPublishedFileId; + if (Prefs.LogVerbose) + { + Log.Message("Workshop: Item created. PublishedFileId: " + Workshop.uploadingHook.PublishedFileId); + } + Workshop.curUpdateHandle = SteamUGC.StartItemUpdate(SteamUtils.GetAppID(), Workshop.uploadingHook.PublishedFileId); + Workshop.SetWorkshopItemDataFrom(Workshop.curUpdateHandle, Workshop.uploadingHook, true); + Workshop.curStage = WorkshopInteractStage.SubmittingItem; + if (Prefs.LogVerbose) + { + Log.Message("Workshop: Submitting item."); + } + SteamAPICall_t hAPICall = SteamUGC.SubmitItemUpdate(Workshop.curUpdateHandle, "[Auto-generated text]: Initial upload."); + Workshop.submitResult = CallResult.Create(new CallResult.APIDispatchDelegate(Workshop.OnItemSubmitted)); + Workshop.submitResult.Set(hAPICall, null); + Workshop.createResult = null; } - SteamAPICall_t hAPICall = SteamUGC.SubmitItemUpdate(Workshop.curUpdateHandle, "[Auto-generated text]: Initial upload."); - Workshop.submitResult = CallResult.Create(new CallResult.APIDispatchDelegate(Workshop.OnItemSubmitted)); - Workshop.submitResult.Set(hAPICall, null); - Workshop.createResult = null; } private static void OnItemSubmitted(SubmitItemUpdateResult_t result, bool IOFailure) @@ -197,18 +190,12 @@ private static void OnItemSubmitted(SubmitItemUpdateResult_t result, bool IOFail Workshop.uploadingHook = null; Dialog_WorkshopOperationInProgress.CloseAll(); Log.Error("Workshop: OnItemSubmitted failure. Result: " + result.m_eResult.GetLabel()); - Find.WindowStack.Add(new Dialog_MessageBox("WorkshopSubmissionFailed".Translate(new object[] - { - GenText.SplitCamelCase(result.m_eResult.GetLabel()) - }), null, null, null, null, null, false)); + Find.WindowStack.Add(new Dialog_MessageBox("WorkshopSubmissionFailed".Translate(GenText.SplitCamelCase(result.m_eResult.GetLabel())), (string)null, null, (string)null, null, (string)null, false)); } else { SteamUtility.OpenWorkshopPage(Workshop.uploadingHook.PublishedFileId); - Messages.Message("WorkshopUploadSucceeded".Translate(new object[] - { - Workshop.uploadingHook.Name - }), MessageSound.Benefit); + Messages.Message("WorkshopUploadSucceeded".Translate(Workshop.uploadingHook.Name), MessageSound.Benefit); if (Prefs.LogVerbose) { Log.Message("Workshop: Item submit result: " + result.m_eResult); @@ -224,49 +211,51 @@ private static void OnGotItemDetails(SteamUGCRequestUGCDetailsResult_t result, b { Log.Error("Workshop: OnGotItemDetails IOFailure."); Workshop.detailsQueryCount = -1; - return; - } - if (Workshop.detailsQueryCount < 0) - { - Log.Warning("Got unexpected Steam Workshop item details response."); } - string text = "Steam Workshop Item details received:"; - for (int i = 0; i < Workshop.detailsQueryCount; i++) + else { - SteamUGCDetails_t steamUGCDetails_t; - SteamUGC.GetQueryUGCResult(Workshop.detailsQueryHandle, (uint)i, out steamUGCDetails_t); - if (steamUGCDetails_t.m_eResult != EResult.k_EResultOK) + if (Workshop.detailsQueryCount < 0) { - text = text + "\n Query result: " + steamUGCDetails_t.m_eResult; + Log.Warning("Got unexpected Steam Workshop item details response."); } - else + string text = "Steam Workshop Item details received:"; + for (int i = 0; i < Workshop.detailsQueryCount; i++) { - text = text + "\n Title: " + steamUGCDetails_t.m_rgchTitle; - text = text + "\n PublishedFileId: " + steamUGCDetails_t.m_nPublishedFileId; - text = text + "\n Created: " + DateTime.FromFileTimeUtc((long)((ulong)steamUGCDetails_t.m_rtimeCreated)).ToString(); - text = text + "\n Updated: " + DateTime.FromFileTimeUtc((long)((ulong)steamUGCDetails_t.m_rtimeUpdated)).ToString(); - text = text + "\n Added to list: " + DateTime.FromFileTimeUtc((long)((ulong)steamUGCDetails_t.m_rtimeAddedToUserList)).ToString(); - text = text + "\n File size: " + steamUGCDetails_t.m_nFileSize.ToStringKilobytes("F2"); - text = text + "\n Preview size: " + steamUGCDetails_t.m_nPreviewFileSize.ToStringKilobytes("F2"); - text = text + "\n File name: " + steamUGCDetails_t.m_pchFileName; - text = text + "\n CreatorAppID: " + steamUGCDetails_t.m_nCreatorAppID; - text = text + "\n ConsumerAppID: " + steamUGCDetails_t.m_nConsumerAppID; - text = text + "\n Visibiliy: " + steamUGCDetails_t.m_eVisibility; - text = text + "\n FileType: " + steamUGCDetails_t.m_eFileType; - text = text + "\n Owner: " + steamUGCDetails_t.m_ulSteamIDOwner; + SteamUGCDetails_t steamUGCDetails_t = default(SteamUGCDetails_t); + SteamUGC.GetQueryUGCResult(Workshop.detailsQueryHandle, (uint)i, out steamUGCDetails_t); + if (steamUGCDetails_t.m_eResult != EResult.k_EResultOK) + { + text = text + "\n Query result: " + steamUGCDetails_t.m_eResult; + } + else + { + text = text + "\n Title: " + steamUGCDetails_t.m_rgchTitle; + text = text + "\n PublishedFileId: " + steamUGCDetails_t.m_nPublishedFileId; + text = text + "\n Created: " + DateTime.FromFileTimeUtc(steamUGCDetails_t.m_rtimeCreated).ToString(); + text = text + "\n Updated: " + DateTime.FromFileTimeUtc(steamUGCDetails_t.m_rtimeUpdated).ToString(); + text = text + "\n Added to list: " + DateTime.FromFileTimeUtc(steamUGCDetails_t.m_rtimeAddedToUserList).ToString(); + text = text + "\n File size: " + steamUGCDetails_t.m_nFileSize.ToStringKilobytes("F2"); + text = text + "\n Preview size: " + steamUGCDetails_t.m_nPreviewFileSize.ToStringKilobytes("F2"); + text = text + "\n File name: " + steamUGCDetails_t.m_pchFileName; + text = text + "\n CreatorAppID: " + steamUGCDetails_t.m_nCreatorAppID; + text = text + "\n ConsumerAppID: " + steamUGCDetails_t.m_nConsumerAppID; + text = text + "\n Visibiliy: " + steamUGCDetails_t.m_eVisibility; + text = text + "\n FileType: " + steamUGCDetails_t.m_eFileType; + text = text + "\n Owner: " + steamUGCDetails_t.m_ulSteamIDOwner; + } + text += "\n"; } - text += "\n"; + Log.Message(text.TrimEndNewlines()); + Workshop.detailsQueryCount = -1; } - Log.Message(text.TrimEndNewlines()); - Workshop.detailsQueryCount = -1; } public static void GetUpdateStatus(out EItemUpdateStatus updateStatus, out float progPercent) { - ulong num; - ulong num2; + ulong num = default(ulong); + ulong num2 = default(ulong); updateStatus = SteamUGC.GetItemUpdateProgress(Workshop.curUpdateHandle, out num, out num2); - progPercent = num / num2; + progPercent = (float)(double)num / (float)(double)num2; } public static string UploadButtonLabel(PublishedFileId_t pfid) @@ -296,35 +285,40 @@ private static void SetWorkshopItemDataFrom(UGCUpdateHandle_t updateHandle, Work SteamUGC.SetItemContent(updateHandle, hook.Directory.FullName); } - [DebuggerHidden] internal static IEnumerable AllSubscribedItems() { - Workshop.c__Iterator256 c__Iterator = new Workshop.c__Iterator256(); - Workshop.c__Iterator256 expr_07 = c__Iterator; - expr_07.$PC = -2; - return expr_07; + uint numSub = SteamUGC.GetNumSubscribedItems(); + PublishedFileId_t[] subbedItems = new PublishedFileId_t[numSub]; + uint count = SteamUGC.GetSubscribedItems(subbedItems, numSub); + for (int i = 0; i < count; i++) + { + PublishedFileId_t pfid = subbedItems[i]; + yield return pfid; + } } internal static void LogStatus() { StringBuilder stringBuilder = new StringBuilder(); stringBuilder.AppendLine("All subscribed items (" + SteamUGC.GetNumSubscribedItems() + " total):"); - List list = Workshop.AllSubscribedItems().ToList(); + List list = Workshop.AllSubscribedItems().ToList(); for (int i = 0; i < list.Count; i++) { stringBuilder.AppendLine(" " + Workshop.ItemStatusString(list[i])); } stringBuilder.AppendLine("All installed mods:"); - foreach (ModMetaData current in ModLister.AllInstalledMods) + foreach (ModMetaData allInstalledMod in ModLister.AllInstalledMods) { - stringBuilder.AppendLine(" " + current.Identifier + ": " + Workshop.ItemStatusString(current.GetPublishedFileId())); + stringBuilder.AppendLine(" " + allInstalledMod.Identifier + ": " + Workshop.ItemStatusString(allInstalledMod.GetPublishedFileId())); } Log.Message(stringBuilder.ToString()); - List list2 = Workshop.AllSubscribedItems().ToList(); + List list2 = Workshop.AllSubscribedItems().ToList(); PublishedFileId_t[] array = new PublishedFileId_t[list2.Count]; for (int j = 0; j < list2.Count; j++) { - array[j] = (PublishedFileId_t)list2[j].m_PublishedFileId; + ref PublishedFileId_t val = ref array[j]; + PublishedFileId_t publishedFileId_t = list2[j]; + val = (PublishedFileId_t)publishedFileId_t.m_PublishedFileId; } Workshop.RequestItemsDetails(array); } @@ -335,26 +329,30 @@ private static string ItemStatusString(PublishedFileId_t pfid) { return "[unpublished]"; } - string text = "[" + pfid + "] "; - ulong num; - string str; - uint num2; - if (SteamUGC.GetItemInstallInfo(pfid, out num, out str, 257u, out num2)) + string str = "[" + pfid + "] "; + ulong num = default(ulong); + string str2 = default(string); + uint num2 = default(uint); + if (SteamUGC.GetItemInstallInfo(pfid, out num, out str2, 257u, out num2)) { - text += "\n installed"; - text = text + "\n folder=" + str; - text = text + "\n sizeOnDisk=" + (num / 1024f).ToString("F2") + "Kb"; + str += "\n installed"; + str = str + "\n folder=" + str2; + str = str + "\n sizeOnDisk=" + ((float)((float)(double)num / 1024.0)).ToString("F2") + "Kb"; } else { - text += "\n not installed"; + str += "\n not installed"; } - return text; + return str; } private static bool IsOurAppId(AppId_t appId) { - return !(appId != SteamUtils.GetAppID()); + if (appId != SteamUtils.GetAppID()) + { + return false; + } + return true; } } } diff --git a/Assembly-CSharp/Verse.Steam/WorkshopInteractStage.cs b/Assembly-CSharp/Verse.Steam/WorkshopInteractStage.cs index adb53ac5b..0a041af8c 100644 --- a/Assembly-CSharp/Verse.Steam/WorkshopInteractStage.cs +++ b/Assembly-CSharp/Verse.Steam/WorkshopInteractStage.cs @@ -1,11 +1,9 @@ -using System; - namespace Verse.Steam { public enum WorkshopInteractStage { - None, - CreatingItem, - SubmittingItem + None = 0, + CreatingItem = 1, + SubmittingItem = 2 } } diff --git a/Assembly-CSharp/Verse.Steam/WorkshopItem.cs b/Assembly-CSharp/Verse.Steam/WorkshopItem.cs index 07071ec7d..e8c6fd1cd 100644 --- a/Assembly-CSharp/Verse.Steam/WorkshopItem.cs +++ b/Assembly-CSharp/Verse.Steam/WorkshopItem.cs @@ -1,5 +1,4 @@ using Steamworks; -using System; using System.IO; namespace Verse.Steam @@ -32,9 +31,9 @@ public virtual PublishedFileId_t PublishedFileId public static WorkshopItem MakeFrom(PublishedFileId_t pfid) { - ulong num; - string path; - uint num2; + ulong num = default(ulong); + string path = default(string); + uint num2 = default(uint); bool itemInstallInfo = SteamUGC.GetItemInstallInfo(pfid, out num, out path, 257u, out num2); WorkshopItem workshopItem = null; if (!itemInstallInfo) diff --git a/Assembly-CSharp/Verse.Steam/WorkshopItemHook.cs b/Assembly-CSharp/Verse.Steam/WorkshopItemHook.cs index 34a74708a..57fce8dda 100644 --- a/Assembly-CSharp/Verse.Steam/WorkshopItemHook.cs +++ b/Assembly-CSharp/Verse.Steam/WorkshopItemHook.cs @@ -1,5 +1,4 @@ using Steamworks; -using System; using System.Collections.Generic; using System.IO; @@ -69,7 +68,15 @@ public bool MayHaveAuthorNotCurrentUser { get { - return !(this.PublishedFileId == PublishedFileId_t.Invalid) && (this.steamAuthor == CSteamID.Nil || this.steamAuthor != SteamUser.GetSteamID()); + if (this.PublishedFileId == PublishedFileId_t.Invalid) + { + return false; + } + if (this.steamAuthor == CSteamID.Nil) + { + return true; + } + return this.steamAuthor != SteamUser.GetSteamID(); } } diff --git a/Assembly-CSharp/Verse.Steam/WorkshopItem_Mod.cs b/Assembly-CSharp/Verse.Steam/WorkshopItem_Mod.cs index 7860e3609..ec8b87447 100644 --- a/Assembly-CSharp/Verse.Steam/WorkshopItem_Mod.cs +++ b/Assembly-CSharp/Verse.Steam/WorkshopItem_Mod.cs @@ -1,5 +1,3 @@ -using System; - namespace Verse.Steam { public class WorkshopItem_Mod : WorkshopItem diff --git a/Assembly-CSharp/Verse.Steam/WorkshopItem_NotInstalled.cs b/Assembly-CSharp/Verse.Steam/WorkshopItem_NotInstalled.cs index de03582ac..1d1f6ec4b 100644 --- a/Assembly-CSharp/Verse.Steam/WorkshopItem_NotInstalled.cs +++ b/Assembly-CSharp/Verse.Steam/WorkshopItem_NotInstalled.cs @@ -1,5 +1,3 @@ -using System; - namespace Verse.Steam { public class WorkshopItem_NotInstalled : WorkshopItem diff --git a/Assembly-CSharp/Verse.Steam/WorkshopItem_Scenario.cs b/Assembly-CSharp/Verse.Steam/WorkshopItem_Scenario.cs index 5337c71e0..304085b5e 100644 --- a/Assembly-CSharp/Verse.Steam/WorkshopItem_Scenario.cs +++ b/Assembly-CSharp/Verse.Steam/WorkshopItem_Scenario.cs @@ -39,7 +39,7 @@ private void LoadScenario() { FileInfo fileInfo = (from fi in base.Directory.GetFiles("*.rsc") where fi.Extension == ".rsc" - select fi).First(); + select fi).First(); if (GameDataSaveLoader.TryLoadScenario(fileInfo.FullName, ScenarioCategory.SteamWorkshop, out this.cachedScenario)) { this.cachedScenario.SetPublishedFileId(this.PublishedFileId); diff --git a/Assembly-CSharp/Verse.Steam/WorkshopItems.cs b/Assembly-CSharp/Verse.Steam/WorkshopItems.cs index 40254ffd1..30c71d8aa 100644 --- a/Assembly-CSharp/Verse.Steam/WorkshopItems.cs +++ b/Assembly-CSharp/Verse.Steam/WorkshopItems.cs @@ -59,17 +59,16 @@ public static bool HasItem(PublishedFileId_t pfid) private static void RebuildItemsList() { - if (!SteamManager.Initialized) + if (SteamManager.Initialized) { - return; - } - WorkshopItems.subbedItems.Clear(); - foreach (PublishedFileId_t current in Workshop.AllSubscribedItems()) - { - WorkshopItems.subbedItems.Add(WorkshopItem.MakeFrom(current)); + WorkshopItems.subbedItems.Clear(); + foreach (PublishedFileId_t item in Workshop.AllSubscribedItems()) + { + WorkshopItems.subbedItems.Add(WorkshopItem.MakeFrom(item)); + } + ModLister.RebuildModList(); + ScenarioLister.MarkDirty(); } - ModLister.RebuildModList(); - ScenarioLister.MarkDirty(); } internal static void Notify_Subscribed(PublishedFileId_t pfid) @@ -91,9 +90,18 @@ public static string DebugOutput() { StringBuilder stringBuilder = new StringBuilder(); stringBuilder.AppendLine("Subscribed items:"); - foreach (WorkshopItem current in WorkshopItems.subbedItems) + List.Enumerator enumerator = WorkshopItems.subbedItems.GetEnumerator(); + try + { + while (enumerator.MoveNext()) + { + WorkshopItem current = enumerator.Current; + stringBuilder.AppendLine(" " + current.ToString()); + } + } + finally { - stringBuilder.AppendLine(" " + current.ToString()); + ((IDisposable)(object)enumerator).Dispose(); } return stringBuilder.ToString(); } diff --git a/Assembly-CSharp/Verse.Steam/WorkshopUploadable.cs b/Assembly-CSharp/Verse.Steam/WorkshopUploadable.cs index ca1141329..48d535984 100644 --- a/Assembly-CSharp/Verse.Steam/WorkshopUploadable.cs +++ b/Assembly-CSharp/Verse.Steam/WorkshopUploadable.cs @@ -1,5 +1,4 @@ using Steamworks; -using System; using System.Collections.Generic; using System.IO; diff --git a/Assembly-CSharp/Verse.Steam/WorkshopUtility.cs b/Assembly-CSharp/Verse.Steam/WorkshopUtility.cs index 5c91ccf2c..e332e1016 100644 --- a/Assembly-CSharp/Verse.Steam/WorkshopUtility.cs +++ b/Assembly-CSharp/Verse.Steam/WorkshopUtility.cs @@ -11,17 +11,17 @@ public static string GetLabel(this WorkshopInteractStage stage) { return "None".Translate(); } - return ("WorkshopInteractStage_" + stage.ToString()).Translate(); + return ("WorkshopInteractStage_" + ((Enum)(object)stage).ToString()).Translate(); } public static string GetLabel(this EItemUpdateStatus status) { - return ("EItemUpdateStatus_" + status.ToString()).Translate(); + return ("EItemUpdateStatus_" + ((Enum)(object)status).ToString()).Translate(); } public static string GetLabel(this EResult result) { - return result.ToString().Substring(9); + return ((Enum)(object)result).ToString().Substring(9); } } } diff --git a/Assembly-CSharp/Verse/AcceptanceReport.cs b/Assembly-CSharp/Verse/AcceptanceReport.cs index 8b8ae3d55..649453383 100644 --- a/Assembly-CSharp/Verse/AcceptanceReport.cs +++ b/Assembly-CSharp/Verse/AcceptanceReport.cs @@ -1,5 +1,3 @@ -using System; - namespace Verse { public struct AcceptanceReport diff --git a/Assembly-CSharp/Verse/ActiveTip.cs b/Assembly-CSharp/Verse/ActiveTip.cs index f8b83bfa0..f707f3db9 100644 --- a/Assembly-CSharp/Verse/ActiveTip.cs +++ b/Assembly-CSharp/Verse/ActiveTip.cs @@ -21,7 +21,7 @@ private string FinalText get { string text; - if (this.signal.textGetter != null) + if ((object)this.signal.textGetter != null) { try { @@ -37,7 +37,7 @@ private string FinalText { text = this.signal.text; } - return text.TrimEnd(new char[0]); + return text.TrimEnd(); } } @@ -54,8 +54,7 @@ public Rect TipRect vector.y = Text.CalcHeight(finalText, vector.x); } Rect rect = new Rect(0f, 0f, vector.x, vector.y); - rect = rect.ContractedBy(-4f); - return rect; + return rect.ContractedBy(-4f); } } @@ -77,7 +76,7 @@ public float DrawTooltip(Vector2 pos) string finalText = this.FinalText; Rect bgRect = this.TipRect; bgRect.position = pos; - Find.WindowStack.ImmediateWindow(153 * this.signal.uniqueId + 62346, bgRect, WindowLayer.Super, delegate + Find.WindowStack.ImmediateWindow(153 * this.signal.uniqueId + 62346, bgRect, WindowLayer.Super, (Action)delegate { Rect rect = bgRect.AtZero(); Widgets.DrawAtlas(rect, ActiveTip.TooltipBGAtlas); diff --git a/Assembly-CSharp/Verse/AddedBodyPartProps.cs b/Assembly-CSharp/Verse/AddedBodyPartProps.cs index 24ae75b46..0181c0a02 100644 --- a/Assembly-CSharp/Verse/AddedBodyPartProps.cs +++ b/Assembly-CSharp/Verse/AddedBodyPartProps.cs @@ -1,5 +1,3 @@ -using System; - namespace Verse { public class AddedBodyPartProps diff --git a/Assembly-CSharp/Verse/AltitudeLayer.cs b/Assembly-CSharp/Verse/AltitudeLayer.cs index 79a1dbaa5..001fabd87 100644 --- a/Assembly-CSharp/Verse/AltitudeLayer.cs +++ b/Assembly-CSharp/Verse/AltitudeLayer.cs @@ -1,40 +1,38 @@ -using System; - namespace Verse { public enum AltitudeLayer : byte { - Terrain, - TerrainScatter, - Floor, - FloorEmplacement, - Filth, - Zone, - SmallWire, - LowPlant, - MoteLow, - Shadows, - DoorMoveable, - Building, - BuildingOnTop, - Item, - ItemImportant, - LayingPawn, - Projectile, - Pawn, - PawnUnused, - PawnState, - Blueprint, - MoteOverhead, - FlyingItem, - Gas, - Weather, - LightingOverlay, - VisEffects, - FogOfWar, - WorldClipper, - WorldDataOverlay, - MetaOverlays, - _Count + Terrain = 0, + TerrainScatter = 1, + Floor = 2, + FloorEmplacement = 3, + Filth = 4, + Zone = 5, + SmallWire = 6, + LowPlant = 7, + MoteLow = 8, + Shadows = 9, + DoorMoveable = 10, + Building = 11, + BuildingOnTop = 12, + Item = 13, + ItemImportant = 14, + LayingPawn = 15, + Projectile = 16, + Pawn = 17, + PawnUnused = 18, + PawnState = 19, + Blueprint = 20, + MoteOverhead = 21, + FlyingItem = 22, + Gas = 23, + Weather = 24, + LightingOverlay = 25, + VisEffects = 26, + FogOfWar = 27, + WorldClipper = 28, + WorldDataOverlay = 29, + MetaOverlays = 30, + _Count = 31 } } diff --git a/Assembly-CSharp/Verse/Altitudes.cs b/Assembly-CSharp/Verse/Altitudes.cs index bb339ffb6..d265336ec 100644 --- a/Assembly-CSharp/Verse/Altitudes.cs +++ b/Assembly-CSharp/Verse/Altitudes.cs @@ -1,4 +1,3 @@ -using System; using UnityEngine; namespace Verse @@ -21,13 +20,13 @@ static Altitudes() Altitudes.AltIncVect = new Vector3(0f, 0.046875f, 0f); for (int i = 0; i < 31; i++) { - Altitudes.Alts[i] = (float)i * 0.46875f; + Altitudes.Alts[i] = (float)((float)i * 0.46875); } } public static float AltitudeFor(AltitudeLayer alt) { - return Altitudes.Alts[(int)alt]; + return Altitudes.Alts[(uint)alt]; } } } diff --git a/Assembly-CSharp/Verse/AnimalNameDisplayMode.cs b/Assembly-CSharp/Verse/AnimalNameDisplayMode.cs index c5e3d3e8f..8da5ff766 100644 --- a/Assembly-CSharp/Verse/AnimalNameDisplayMode.cs +++ b/Assembly-CSharp/Verse/AnimalNameDisplayMode.cs @@ -1,11 +1,9 @@ -using System; - namespace Verse { public enum AnimalNameDisplayMode : byte { - None, - TameNamed, - TameAll + None = 0, + TameNamed = 1, + TameAll = 2 } } diff --git a/Assembly-CSharp/Verse/AnimalNameDisplayModeExtension.cs b/Assembly-CSharp/Verse/AnimalNameDisplayModeExtension.cs index b51893c88..93a7d8d05 100644 --- a/Assembly-CSharp/Verse/AnimalNameDisplayModeExtension.cs +++ b/Assembly-CSharp/Verse/AnimalNameDisplayModeExtension.cs @@ -9,14 +9,22 @@ public static string ToStringHuman(this AnimalNameDisplayMode mode) switch (mode) { case AnimalNameDisplayMode.None: + { return "None".Translate(); + } case AnimalNameDisplayMode.TameNamed: + { return "AnimalNameDisplayMode_TameNamed".Translate(); + } case AnimalNameDisplayMode.TameAll: + { return "AnimalNameDisplayMode_TameAll".Translate(); + } default: + { throw new NotImplementedException(); } + } } } } diff --git a/Assembly-CSharp/Verse/Area.cs b/Assembly-CSharp/Verse/Area.cs index d61180c6a..170ee0b5a 100644 --- a/Assembly-CSharp/Verse/Area.cs +++ b/Assembly-CSharp/Verse/Area.cs @@ -52,7 +52,7 @@ public Texture2D ColorTexture { get { - if (this.colorTextureInt == null) + if ((UnityEngine.Object)this.colorTextureInt == (UnityEngine.Object)null) { this.colorTextureInt = SolidColorMaterials.NewSolidColorTexture(this.Color); } @@ -90,7 +90,10 @@ private CellBoolDrawer Drawer { if (this.drawer == null) { - this.drawer = new CellBoolDrawer(this, this.Map.Size.x, this.Map.Size.z, 0.33f); + IntVec3 size = this.Map.Size; + int x = size.x; + IntVec3 size2 = this.Map.Size; + this.drawer = new CellBoolDrawer(this, x, size2.z, 0.33f); } return this.drawer; } @@ -152,12 +155,11 @@ public virtual void SetLabel(string label) protected virtual void Set(IntVec3 c, bool val) { int index = this.Map.cellIndices.CellToIndex(c); - if (this.innerGrid[index] == val) + if (this.innerGrid[index] != val) { - return; + this.innerGrid[index] = val; + this.MarkDirty(c); } - this.innerGrid[index] = val; - this.MarkDirty(c); } private void MarkDirty(IntVec3 c) diff --git a/Assembly-CSharp/Verse/AreaManager.cs b/Assembly-CSharp/Verse/AreaManager.cs index 32033e56f..212c4f774 100644 --- a/Assembly-CSharp/Verse/AreaManager.cs +++ b/Assembly-CSharp/Verse/AreaManager.cs @@ -64,7 +64,7 @@ public void AddStartingAreas() this.areas.Add(new Area_BuildRoof(this)); this.areas.Add(new Area_NoRoof(this)); this.areas.Add(new Area_SnowClear(this)); - Area_Allowed area_Allowed; + Area_Allowed area_Allowed = default(Area_Allowed); this.TryMakeNewAllowed(AllowedAreaMode.Humanlike, out area_Allowed); this.TryMakeNewAllowed(AllowedAreaMode.Animal, out area_Allowed); } @@ -91,19 +91,21 @@ internal void Remove(Area area) if (!area.Mutable) { Log.Error("Tried to delete non-Deletable area " + area); - return; } - this.areas.Remove(area); - foreach (Pawn current in PawnsFinder.AllMapsAndWorld_Alive) + else { - if (current.playerSettings != null) + this.areas.Remove(area); + foreach (Pawn item in PawnsFinder.AllMapsAndWorld_Alive) { - current.playerSettings.Notify_AreaRemoved(area); + if (item.playerSettings != null) + { + item.playerSettings.Notify_AreaRemoved(area); + } + } + if (Designator_AreaAllowed.SelectedArea == area) + { + Designator_AreaAllowed.ClearSelectedArea(); } - } - if (Designator_AreaAllowed.SelectedArea == area) - { - Designator_AreaAllowed.ClearSelectedArea(); } } @@ -123,18 +125,18 @@ public T Get() where T : Area { for (int i = 0; i < this.areas.Count; i++) { - T t = this.areas[i] as T; - if (t != null) + T val = (T)(this.areas[i] as T); + if (val != null) { - return t; + return val; } } - return (T)((object)null); + return (T)null; } private void SortAreas() { - this.areas.InsertionSort((Area a, Area b) => b.ListPriority.CompareTo(a.ListPriority)); + this.areas.InsertionSort((Comparison)((Area a, Area b) => b.ListPriority.CompareTo(a.ListPriority))); } private void UpdateAllAreasLinks() @@ -149,7 +151,7 @@ public bool CanMakeNewAllowed(AllowedAreaMode mode) { return (from a in this.areas where a is Area_Allowed && ((Area_Allowed)a).mode == mode - select a).Count() < 5; + select a).Count() < 5; } public bool TryMakeNewAllowed(AllowedAreaMode mode, out Area_Allowed area) @@ -159,7 +161,7 @@ public bool TryMakeNewAllowed(AllowedAreaMode mode, out Area_Allowed area) area = null; return false; } - area = new Area_Allowed(this, mode, null); + area = new Area_Allowed(this, mode, (string)null); this.areas.Add(area); this.SortAreas(); return true; diff --git a/Assembly-CSharp/Verse/AreaOverlap.cs b/Assembly-CSharp/Verse/AreaOverlap.cs index 5c54e1d46..4499dd411 100644 --- a/Assembly-CSharp/Verse/AreaOverlap.cs +++ b/Assembly-CSharp/Verse/AreaOverlap.cs @@ -1,11 +1,9 @@ -using System; - namespace Verse { public enum AreaOverlap { - None, - Entire, - Partial + None = 0, + Entire = 1, + Partial = 2 } } diff --git a/Assembly-CSharp/Verse/AreaUtility.cs b/Assembly-CSharp/Verse/AreaUtility.cs index 58081f1bd..c351d852c 100644 --- a/Assembly-CSharp/Verse/AreaUtility.cs +++ b/Assembly-CSharp/Verse/AreaUtility.cs @@ -12,21 +12,21 @@ public static void MakeAllowedAreaListFloatMenu(Action selAction, AllowedA List list = new List(); if (addNullAreaOption) { - list.Add(new FloatMenuOption("NoAreaAllowed".Translate(), delegate + list.Add(new FloatMenuOption("NoAreaAllowed".Translate(), (Action)delegate() { selAction(null); }, MenuOptionPriority.High, null, null, 0f, null, null)); } - foreach (Area current in from a in map.areaManager.AllAreas + foreach (Area item2 in from a in map.areaManager.AllAreas where a.AssignableAsAllowed(mode) select a) { - Area localArea = current; - Action mouseoverGuiAction = delegate + Area localArea = item2; + Action mouseoverGuiAction = (Action)delegate { localArea.MarkForDraw(); }; - FloatMenuOption item = new FloatMenuOption(localArea.Label, delegate + FloatMenuOption item = new FloatMenuOption(localArea.Label, (Action)delegate() { selAction(localArea); }, MenuOptionPriority.Default, mouseoverGuiAction, null, 0f, null, null); @@ -34,7 +34,7 @@ where a.AssignableAsAllowed(mode) } if (addManageOption) { - list.Add(new FloatMenuOption("ManageAreas".Translate(), delegate + list.Add(new FloatMenuOption("ManageAreas".Translate(), (Action)delegate() { Find.WindowStack.Add(new Dialog_ManageAreas(map)); }, MenuOptionPriority.Low, null, null, 0f, null, null)); diff --git a/Assembly-CSharp/Verse/ArmorUtility.cs b/Assembly-CSharp/Verse/ArmorUtility.cs index 6e4e7c661..862cbd423 100644 --- a/Assembly-CSharp/Verse/ArmorUtility.cs +++ b/Assembly-CSharp/Verse/ArmorUtility.cs @@ -1,5 +1,4 @@ using RimWorld; -using System; using System.Collections.Generic; namespace Verse @@ -23,7 +22,7 @@ public static int GetPostArmorDamage(Pawn pawn, int amountInt, BodyPartRecord pa if (apparel.def.apparel.CoversBodyPart(part)) { ArmorUtility.ApplyArmor(ref num, apparel.GetStatValue(deflectionStat, true), apparel, damageDef); - if (num < 0.001f) + if (num < 0.0010000000474974513) { return 0; } @@ -43,36 +42,28 @@ private static void ApplyArmor(ref float damAmount, float armorRating, Thing arm num = armorRating; num2 = 0f; } - else if (armorRating < 1f) + else if (armorRating < 1.0) { num = 0.5f; - num2 = armorRating - 0.5f; + num2 = (float)(armorRating - 0.5); } else { - num = 0.5f + (armorRating - 1f) * 0.25f; - num2 = 0.5f + (armorRating - 1f) * 0.25f; + num = (float)(0.5 + (armorRating - 1.0) * 0.25); + num2 = (float)(0.5 + (armorRating - 1.0) * 0.25); } - if (num > 0.9f) + if (num > 0.89999997615814209) { num = 0.9f; } - if (num2 > 0.9f) + if (num2 > 0.89999997615814209) { num2 = 0.9f; } - float num3; - if (Rand.Value < num2) - { - num3 = damAmount; - } - else - { - num3 = damAmount * num; - } + float num3 = (!(Rand.Value < num2)) ? (damAmount * num) : damAmount; if (armorThing != null) { - float f = damAmount * 0.25f; + float f = (float)(damAmount * 0.25); armorThing.TakeDamage(new DamageInfo(damageDef, GenMath.RoundRandom(f), -1f, null, null, null, DamageInfo.SourceCategory.ThingOrUnknown)); } damAmount -= num3; diff --git a/Assembly-CSharp/Verse/ArrayExposeUtility.cs b/Assembly-CSharp/Verse/ArrayExposeUtility.cs index 5e519879e..b18b43d78 100644 --- a/Assembly-CSharp/Verse/ArrayExposeUtility.cs +++ b/Assembly-CSharp/Verse/ArrayExposeUtility.cs @@ -9,13 +9,13 @@ public static class ArrayExposeUtility public static void ExposeByteArray(ref byte[] arr, string label) { - string text = null; + string text = (string)null; if (Scribe.mode == LoadSaveMode.Saving) { text = Convert.ToBase64String(arr); text = ArrayExposeUtility.AddLineBreaksToLongString(text); } - Scribe_Values.Look(ref text, label, null, false); + Scribe_Values.Look(ref text, label, (string)null, false); if (Scribe.mode == LoadSaveMode.LoadingVars) { text = ArrayExposeUtility.RemoveLineBreaks(text); @@ -26,24 +26,23 @@ public static void ExposeByteArray(ref byte[] arr, string label) public static void ExposeBoolArray(ref bool[] arr, int mapSizeX, int mapSizeZ, string label) { int num = mapSizeX * mapSizeZ; - int num2 = (int)Math.Ceiling((double)((float)num / 6f)); + int num2 = (int)Math.Ceiling((float)num / 6.0); byte[] array = new byte[num2]; if (Scribe.mode == LoadSaveMode.Saving) { int num3 = 0; - byte b = 1; - for (int i = 0; i < num; i++) + byte b = (byte)1; + for (int num4 = 0; num4 < num; num4++) { - if (arr[i]) + if (arr[num4]) { - byte[] expr_44_cp_0 = array; - int expr_44_cp_1 = num3; - expr_44_cp_0[expr_44_cp_1] |= b; + ref byte val = ref array[num3]; + val = (byte)(val | b); } - b *= 2; + b = (byte)(b * 2); if (b > 32) { - b = 1; + b = (byte)1; num3++; } } @@ -51,20 +50,20 @@ public static void ExposeBoolArray(ref bool[] arr, int mapSizeX, int mapSizeZ, s ArrayExposeUtility.ExposeByteArray(ref array, label); if (Scribe.mode == LoadSaveMode.LoadingVars) { - int num4 = 0; - byte b2 = 1; - for (int j = 0; j < num; j++) + int num5 = 0; + byte b2 = (byte)1; + for (int num6 = 0; num6 < num; num6++) { if (arr == null) { arr = new bool[num]; } - arr[j] = ((array[num4] & b2) != 0); - b2 *= 2; + arr[num6] = ((array[num5] & b2) != 0); + b2 = (byte)(b2 * 2); if (b2 > 32) { - b2 = 1; - num4++; + b2 = (byte)1; + num5++; } } } diff --git a/Assembly-CSharp/Verse/AttachableThing.cs b/Assembly-CSharp/Verse/AttachableThing.cs index 63b7ae129..1b3db1fed 100644 --- a/Assembly-CSharp/Verse/AttachableThing.cs +++ b/Assembly-CSharp/Verse/AttachableThing.cs @@ -1,4 +1,3 @@ -using System; using UnityEngine; namespace Verse @@ -40,17 +39,12 @@ public virtual void AttachTo(Thing parent) CompAttachBase compAttachBase = parent.TryGetComp(); if (compAttachBase == null) { - Log.Error(string.Concat(new object[] - { - "Cannot attach ", - this, - " to ", - parent, - ": parent has no CompAttachBase." - })); - return; + Log.Error("Cannot attach " + this + " to " + parent + ": parent has no CompAttachBase."); + } + else + { + compAttachBase.AddAttachment(this); } - compAttachBase.AddAttachment(this); } public override void Destroy(DestroyMode mode = DestroyMode.Vanish) diff --git a/Assembly-CSharp/Verse/AttachmentUtility.cs b/Assembly-CSharp/Verse/AttachmentUtility.cs index 77b97484e..268590c73 100644 --- a/Assembly-CSharp/Verse/AttachmentUtility.cs +++ b/Assembly-CSharp/Verse/AttachmentUtility.cs @@ -1,5 +1,3 @@ -using System; - namespace Verse { public static class AttachmentUtility diff --git a/Assembly-CSharp/Verse/AutoBuildRoofAreaSetter.cs b/Assembly-CSharp/Verse/AutoBuildRoofAreaSetter.cs index b1d18d92b..fd88f3874 100644 --- a/Assembly-CSharp/Verse/AutoBuildRoofAreaSetter.cs +++ b/Assembly-CSharp/Verse/AutoBuildRoofAreaSetter.cs @@ -38,7 +38,7 @@ public void TryGenerateAreaOnImpassable(IntVec3 c) } if (flag) { - this.map.areaManager.BuildRoof[c] = true; + ((Area)this.map.areaManager.BuildRoof)[c] = true; MoteMaker.PlaceTempRoof(c, this.map); } } @@ -65,84 +65,91 @@ public void ResolveQueuedGenerateRoofs() private void TryGenerateAreaNow(Room room) { - if (room.Dereferenced || room.TouchesMapEdge) + if (!room.Dereferenced && !room.TouchesMapEdge && room.RegionCount <= 26 && room.CellCount <= 320) { - return; - } - if (room.RegionCount > 26 || room.CellCount > 320) - { - return; - } - foreach (IntVec3 current in room.BorderCells) - { - Thing roofHolderOrImpassable = current.GetRoofHolderOrImpassable(this.map); - if (roofHolderOrImpassable != null) + foreach (IntVec3 borderCell in room.BorderCells) { - if (roofHolderOrImpassable.Faction != null && roofHolderOrImpassable.Faction != Faction.OfPlayer) + Thing roofHolderOrImpassable = borderCell.GetRoofHolderOrImpassable(this.map); + if (roofHolderOrImpassable != null) { - return; - } - if (roofHolderOrImpassable.def.building != null && !roofHolderOrImpassable.def.building.allowAutoroof) - { - return; + if (roofHolderOrImpassable.Faction != null && roofHolderOrImpassable.Faction != Faction.OfPlayer) + return; + if (roofHolderOrImpassable.def.building != null && !roofHolderOrImpassable.def.building.allowAutoroof) + return; } } - } - this.innerCells.Clear(); - foreach (IntVec3 current2 in room.Cells) - { - if (!this.innerCells.Contains(current2)) - { - this.innerCells.Add(current2); - } - for (int i = 0; i < 8; i++) + this.innerCells.Clear(); + foreach (IntVec3 cell in room.Cells) { - IntVec3 c = current2 + GenAdj.AdjacentCells[i]; - if (c.InBounds(this.map)) + if (!this.innerCells.Contains(cell)) { - Thing roofHolderOrImpassable2 = c.GetRoofHolderOrImpassable(this.map); - if (roofHolderOrImpassable2 != null && (roofHolderOrImpassable2.def.size.x > 1 || roofHolderOrImpassable2.def.size.z > 1)) + this.innerCells.Add(cell); + } + for (int i = 0; i < 8; i++) + { + IntVec3 c = cell + GenAdj.AdjacentCells[i]; + if (c.InBounds(this.map)) { - CellRect cellRect = roofHolderOrImpassable2.OccupiedRect(); - cellRect.ClipInsideMap(this.map); - for (int j = cellRect.minZ; j <= cellRect.maxZ; j++) + Thing roofHolderOrImpassable2 = c.GetRoofHolderOrImpassable(this.map); + if (roofHolderOrImpassable2 != null && (roofHolderOrImpassable2.def.size.x > 1 || roofHolderOrImpassable2.def.size.z > 1)) { - for (int k = cellRect.minX; k <= cellRect.maxX; k++) + CellRect cellRect = roofHolderOrImpassable2.OccupiedRect(); + cellRect.ClipInsideMap(this.map); + for (int j = cellRect.minZ; j <= cellRect.maxZ; j++) { - IntVec3 item = new IntVec3(k, 0, j); - if (!this.innerCells.Contains(item)) + for (int k = cellRect.minX; k <= cellRect.maxX; k++) { - this.innerCells.Add(item); + IntVec3 item = new IntVec3(k, 0, j); + if (!this.innerCells.Contains(item)) + { + this.innerCells.Add(item); + } } } } } } } - } - this.cellsToRoof.Clear(); - foreach (IntVec3 current3 in this.innerCells) - { - for (int l = 0; l < 9; l++) + this.cellsToRoof.Clear(); + HashSet.Enumerator enumerator3 = this.innerCells.GetEnumerator(); + try { - IntVec3 intVec = current3 + GenAdj.AdjacentCellsAndInside[l]; - if (intVec.InBounds(this.map) && (l == 8 || intVec.GetRoofHolderOrImpassable(this.map) != null) && !this.cellsToRoof.Contains(intVec)) + while (enumerator3.MoveNext()) { - this.cellsToRoof.Add(intVec); + IntVec3 current3 = enumerator3.Current; + for (int l = 0; l < 9; l++) + { + IntVec3 intVec = current3 + GenAdj.AdjacentCellsAndInside[l]; + if (intVec.InBounds(this.map) && (l == 8 || intVec.GetRoofHolderOrImpassable(this.map) != null) && !this.cellsToRoof.Contains(intVec)) + { + this.cellsToRoof.Add(intVec); + } + } } } - } - this.justRoofedCells.Clear(); - foreach (IntVec3 current4 in this.cellsToRoof) - { - if (this.map.roofGrid.RoofAt(current4) == null && !this.justRoofedCells.Contains(current4)) + finally { - if (!this.map.areaManager.NoRoof[current4] && RoofCollapseUtility.WithinRangeOfRoofHolder(current4, this.map)) + ((IDisposable)(object)enumerator3).Dispose(); + } + this.justRoofedCells.Clear(); + HashSet.Enumerator enumerator4 = this.cellsToRoof.GetEnumerator(); + try + { + while (enumerator4.MoveNext()) { - this.map.areaManager.BuildRoof[current4] = true; - this.justRoofedCells.Add(current4); + IntVec3 current4 = enumerator4.Current; + RoofDef roofDef = this.map.roofGrid.RoofAt(current4); + if (roofDef == null && !this.justRoofedCells.Contains(current4) && !((Area)this.map.areaManager.NoRoof)[current4] && RoofCollapseUtility.WithinRangeOfRoofHolder(current4, this.map)) + { + ((Area)this.map.areaManager.BuildRoof)[current4] = true; + this.justRoofedCells.Add(current4); + } } } + finally + { + ((IDisposable)(object)enumerator4).Dispose(); + } } } } diff --git a/Assembly-CSharp/Verse/Autotests_RegionListers.cs b/Assembly-CSharp/Verse/Autotests_RegionListers.cs index 65f666ce8..bf5b28410 100644 --- a/Assembly-CSharp/Verse/Autotests_RegionListers.cs +++ b/Assembly-CSharp/Verse/Autotests_RegionListers.cs @@ -19,13 +19,22 @@ public static void CheckBugs(Map map) private static void CheckThingRegisteredTwice(Map map) { - foreach (KeyValuePair> current in Autotests_RegionListers.expectedListers) + Dictionary>.Enumerator enumerator = Autotests_RegionListers.expectedListers.GetEnumerator(); + try { - Autotests_RegionListers.CheckDuplicates(current.Value, current.Key, true); + while (enumerator.MoveNext()) + { + KeyValuePair> current = enumerator.Current; + Autotests_RegionListers.CheckDuplicates(current.Value, current.Key, true); + } + } + finally + { + ((IDisposable)(object)enumerator).Dispose(); } - foreach (Region current2 in map.regionGrid.AllRegions) + foreach (Region allRegion in map.regionGrid.AllRegions) { - Autotests_RegionListers.CheckDuplicates(current2.ListerThings.AllThings, current2, false); + Autotests_RegionListers.CheckDuplicates(allRegion.ListerThings.AllThings, allRegion, false); } } @@ -33,30 +42,17 @@ private static void CheckDuplicates(List lister, Region region, bool expe { for (int i = 1; i < lister.Count; i++) { - for (int j = 0; j < i; j++) + for (int num = 0; num < i; num++) { - if (lister[i] == lister[j]) + if (lister[i] == lister[num]) { if (expected) { - Log.Error(string.Concat(new object[] - { - "Region error: thing ", - lister[i], - " is expected to be registered twice in ", - region, - "? This should never happen." - })); + Log.Error("Region error: thing " + lister[i] + " is expected to be registered twice in " + region + "? This should never happen."); } else { - Log.Error(string.Concat(new object[] - { - "Region error: thing ", - lister[i], - " is registered twice in ", - region - })); + Log.Error("Region error: thing " + lister[i] + " is registered twice in " + region); } } } @@ -65,53 +61,44 @@ private static void CheckDuplicates(List lister, Region region, bool expe private static void CheckThingNotRegisteredButShould() { - foreach (KeyValuePair> current in Autotests_RegionListers.expectedListers) + Dictionary>.Enumerator enumerator = Autotests_RegionListers.expectedListers.GetEnumerator(); + try { - List value = current.Value; - List allThings = current.Key.ListerThings.AllThings; - for (int i = 0; i < value.Count; i++) + while (enumerator.MoveNext()) { - if (!allThings.Contains(value[i])) + KeyValuePair> current = enumerator.Current; + List value = current.Value; + List allThings = current.Key.ListerThings.AllThings; + for (int i = 0; i < value.Count; i++) { - Log.Error(string.Concat(new object[] + if (!allThings.Contains(value[i])) { - "Region error: thing ", - value[i], - " at ", - value[i].Position, - " should be registered in ", - current.Key, - " but it's not." - })); + Log.Error("Region error: thing " + value[i] + " at " + value[i].Position + " should be registered in " + current.Key + " but it's not."); + } } } } + finally + { + ((IDisposable)(object)enumerator).Dispose(); + } } private static void CheckThingRegisteredButShouldnt(Map map) { - foreach (Region current in map.regionGrid.AllRegions) + foreach (Region allRegion in map.regionGrid.AllRegions) { - List list; - if (!Autotests_RegionListers.expectedListers.TryGetValue(current, out list)) + List list = default(List); + if (!Autotests_RegionListers.expectedListers.TryGetValue(allRegion, out list)) { list = null; } - List allThings = current.ListerThings.AllThings; + List allThings = allRegion.ListerThings.AllThings; for (int i = 0; i < allThings.Count; i++) { if (list == null || !list.Contains(allThings[i])) { - Log.Error(string.Concat(new object[] - { - "Region error: thing ", - allThings[i], - " at ", - allThings[i].Position, - " is registered in ", - current, - " but it shouldn't be." - })); + Log.Error("Region error: thing " + allThings[i] + " at " + allThings[i].Position + " is registered in " + allRegion + " but it shouldn't be."); } } } @@ -130,7 +117,7 @@ private static void CalculateExpectedListers(Map map) for (int j = 0; j < Autotests_RegionListers.tmpTouchableRegions.Count; j++) { Region key = Autotests_RegionListers.tmpTouchableRegions[j]; - List list; + List list = default(List); if (!Autotests_RegionListers.expectedListers.TryGetValue(key, out list)) { list = new List(); diff --git a/Assembly-CSharp/Verse/BackCompatibility.cs b/Assembly-CSharp/Verse/BackCompatibility.cs index 3f11e8260..625667e28 100644 --- a/Assembly-CSharp/Verse/BackCompatibility.cs +++ b/Assembly-CSharp/Verse/BackCompatibility.cs @@ -16,18 +16,18 @@ public static bool IsSaveCompatibleWith(string version) { return true; } - if (VersionControl.MajorFromVersionString(version) != 0 || VersionControl.CurrentMajor != 0) + if (VersionControl.MajorFromVersionString(version) == 0 && VersionControl.CurrentMajor == 0) { - return false; - } - int num = VersionControl.MinorFromVersionString(version); - int currentMinor = VersionControl.CurrentMinor; - for (int i = 0; i < BackCompatibility.SaveCompatibleMinorVersions.Length; i++) - { - if (BackCompatibility.SaveCompatibleMinorVersions[i].First == num && BackCompatibility.SaveCompatibleMinorVersions[i].Second == currentMinor) + int num = VersionControl.MinorFromVersionString(version); + int currentMinor = VersionControl.CurrentMinor; + for (int i = 0; i < BackCompatibility.SaveCompatibleMinorVersions.Length; i++) { - return true; + if (BackCompatibility.SaveCompatibleMinorVersions[i].First == num && BackCompatibility.SaveCompatibleMinorVersions[i].Second == currentMinor) + { + return true; + } } + return false; } return false; } @@ -322,13 +322,16 @@ public static void JobTrackerPostLoadInit(Pawn_JobTracker jobTracker) if (jobTracker.jobQueue != null) { bool flag = false; - for (int i = 0; i < jobTracker.jobQueue.Count; i++) + int num = 0; + while (num < jobTracker.jobQueue.Count) { - if (jobTracker.jobQueue[i].job == null) + if (jobTracker.jobQueue[num].job != null) { - flag = true; - break; + num++; + continue; } + flag = true; + break; } if (flag) { diff --git a/Assembly-CSharp/Verse/BackstoryTranslationUtility.cs b/Assembly-CSharp/Verse/BackstoryTranslationUtility.cs index cfbd26ec0..d19d887e1 100644 --- a/Assembly-CSharp/Verse/BackstoryTranslationUtility.cs +++ b/Assembly-CSharp/Verse/BackstoryTranslationUtility.cs @@ -1,36 +1,56 @@ using RimWorld; using System; using System.Collections.Generic; -using System.Diagnostics; +using System.IO; +using System.Linq; using System.Xml.Linq; namespace Verse { public static class BackstoryTranslationUtility { - [DebuggerHidden] private static IEnumerable BackstoryTranslationElements(LoadedLanguage lang) { - BackstoryTranslationUtility.c__Iterator1ED c__Iterator1ED = new BackstoryTranslationUtility.c__Iterator1ED(); - c__Iterator1ED.lang = lang; - c__Iterator1ED.<$>lang = lang; - BackstoryTranslationUtility.c__Iterator1ED expr_15 = c__Iterator1ED; - expr_15.$PC = -2; - return expr_15; + foreach (string folderPath2 in lang.FolderPaths) + { + string _ = folderPath2; + FileInfo fi = new FileInfo(Path.Combine(folderPath2.ToString(), "Backstories/Backstories.xml")); + if (fi.Exists) + { + XDocument doc; + try + { + doc = XDocument.Load(fi.FullName); + } + catch (Exception ex) + { + Exception e; + Exception ex2 = e = ex; + Log.Warning("Exception loading backstory translation data from file " + fi + ": " + e); + yield break; + } + foreach (XElement item in doc.Root.Elements()) + { + yield return item; + } + continue; + } + break; + } } public static void LoadAndInjectBackstoryData(LoadedLanguage lang) { - foreach (XElement current in BackstoryTranslationUtility.BackstoryTranslationElements(lang)) + foreach (XElement item in BackstoryTranslationUtility.BackstoryTranslationElements(lang)) { string text = "[unknown]"; try { - text = current.Name.ToString(); - string value = current.Element("title").Value; - string value2 = current.Element("titleShort").Value; - string value3 = current.Element("desc").Value; - Backstory backstory; + text = item.Name.ToString(); + string value = item.Element("title").Value; + string value2 = item.Element("titleShort").Value; + string value3 = item.Element("desc").Value; + Backstory backstory = default(Backstory); if (!BackstoryDatabase.TryGetWithIdentifier(text, out backstory)) { throw new Exception("Backstory not found matching identifier " + text); @@ -57,28 +77,55 @@ public static void LoadAndInjectBackstoryData(LoadedLanguage lang) } catch (Exception ex) { - Log.Warning(string.Concat(new object[] - { - "Couldn't load backstory ", - text, - ": ", - ex, - "\nFull XML text:\n\n", - current.ToString() - })); + Log.Warning("Couldn't load backstory " + text + ": " + ex + "\nFull XML text:\n\n" + item.ToString()); } } } - [DebuggerHidden] public static IEnumerable MissingBackstoryTranslations(LoadedLanguage lang) { - BackstoryTranslationUtility.c__Iterator1EE c__Iterator1EE = new BackstoryTranslationUtility.c__Iterator1EE(); - c__Iterator1EE.lang = lang; - c__Iterator1EE.<$>lang = lang; - BackstoryTranslationUtility.c__Iterator1EE expr_15 = c__Iterator1EE; - expr_15.$PC = -2; - return expr_15; + List neededTranslations = (from kvp in BackstoryDatabase.allBackstories + select kvp.Key).ToList(); + foreach (XElement item in BackstoryTranslationUtility.BackstoryTranslationElements(lang)) + { + string identifier = item.Name.ToString(); + if (neededTranslations.Contains(identifier)) + { + neededTranslations.Remove(identifier); + string title = item.Element("title").Value; + string titleShort = item.Element("titleShort").Value; + string desc = item.Element("desc").Value; + if (title.NullOrEmpty()) + { + yield return identifier + ".title missing"; + } + if (titleShort.NullOrEmpty()) + { + yield return identifier + ".titleShort missing"; + } + if (desc.NullOrEmpty()) + { + yield return identifier + ".desc missing"; + } + } + else + { + yield return "Translation doesn't correspond to any backstory: " + identifier; + } + } + List.Enumerator enumerator2 = neededTranslations.GetEnumerator(); + try + { + while (enumerator2.MoveNext()) + { + string tra = enumerator2.Current; + yield return "Missing backstory: " + tra; + } + } + finally + { + ((IDisposable)(object)enumerator2).Dispose(); + } } } } diff --git a/Assembly-CSharp/Verse/BaseContent.cs b/Assembly-CSharp/Verse/BaseContent.cs index 7a13c41a5..3ddafcf70 100644 --- a/Assembly-CSharp/Verse/BaseContent.cs +++ b/Assembly-CSharp/Verse/BaseContent.cs @@ -1,4 +1,3 @@ -using System; using UnityEngine; namespace Verse @@ -32,12 +31,12 @@ public static class BaseContent public static bool NullOrBad(this Material mat) { - return mat == null || mat == BaseContent.BadMat; + return (Object)mat == (Object)null || (Object)mat == (Object)BaseContent.BadMat; } public static bool NullOrBad(this Texture2D tex) { - return tex == null || tex == BaseContent.BadTex; + return (Object)tex == (Object)null || (Object)tex == (Object)BaseContent.BadTex; } } } diff --git a/Assembly-CSharp/Verse/BeautyDrawer.cs b/Assembly-CSharp/Verse/BeautyDrawer.cs index 76f696b7e..cc97f351b 100644 --- a/Assembly-CSharp/Verse/BeautyDrawer.cs +++ b/Assembly-CSharp/Verse/BeautyDrawer.cs @@ -1,5 +1,4 @@ using RimWorld; -using System; using System.Collections.Generic; using UnityEngine; @@ -20,7 +19,7 @@ public static void DrawBeautyAroundMouse() { IntVec3 intVec = BeautyUtility.beautyRelevantCells[i]; float num = BeautyUtility.CellBeauty(intVec, Find.VisibleMap, BeautyDrawer.beautyCountedThings); - if (num != 0f) + if (num != 0.0) { Vector3 v = GenMapUI.LabelDrawPosFor(intVec); GenMapUI.DrawThingLabel(v, Mathf.RoundToInt(num).ToStringCached(), BeautyDrawer.BeautyColor(num, 8f)); @@ -31,9 +30,9 @@ public static void DrawBeautyAroundMouse() public static Color BeautyColor(float beauty, float scale) { - float num = Mathf.InverseLerp(-scale, scale, beauty); - num = Mathf.Clamp01(num); - Color a = Color.Lerp(BeautyDrawer.ColorUgly, BeautyDrawer.ColorBeautiful, num); + float value = Mathf.InverseLerp((float)(0.0 - scale), scale, beauty); + value = Mathf.Clamp01(value); + Color a = Color.Lerp(BeautyDrawer.ColorUgly, BeautyDrawer.ColorBeautiful, value); return Color.Lerp(a, Color.white, 0.5f); } } diff --git a/Assembly-CSharp/Verse/BlackScreenFixer.cs b/Assembly-CSharp/Verse/BlackScreenFixer.cs index dc77970ed..2305daeae 100644 --- a/Assembly-CSharp/Verse/BlackScreenFixer.cs +++ b/Assembly-CSharp/Verse/BlackScreenFixer.cs @@ -1,4 +1,3 @@ -using System; using UnityEngine; namespace Verse diff --git a/Assembly-CSharp/Verse/BodyDef.cs b/Assembly-CSharp/Verse/BodyDef.cs index 7f5d0036e..111a7798b 100644 --- a/Assembly-CSharp/Verse/BodyDef.cs +++ b/Assembly-CSharp/Verse/BodyDef.cs @@ -1,6 +1,5 @@ using System; using System.Collections.Generic; -using System.Diagnostics; namespace Verse { @@ -30,16 +29,16 @@ public List AllPartsVulnerableToFrostbite } } - [DebuggerHidden] public IEnumerable GetPartsWithTag(string tag) { - BodyDef.c__Iterator1C4 c__Iterator1C = new BodyDef.c__Iterator1C4(); - c__Iterator1C.tag = tag; - c__Iterator1C.<$>tag = tag; - c__Iterator1C.<>f__this = this; - BodyDef.c__Iterator1C4 expr_1C = c__Iterator1C; - expr_1C.$PC = -2; - return expr_1C; + for (int i = 0; i < this.AllParts.Count; i++) + { + BodyPartRecord part = this.AllParts[i]; + if (part.def.tags.Contains(tag)) + { + yield return part; + } + } } public bool HasPartWithTag(string tag) @@ -72,14 +71,32 @@ public int GetIndexOfPart(BodyPartRecord rec) throw new ArgumentException("Cannot get index of BodyPartRecord that is not in this BodyDef."); } - [DebuggerHidden] public override IEnumerable ConfigErrors() { - BodyDef.c__Iterator1C5 c__Iterator1C = new BodyDef.c__Iterator1C5(); - c__Iterator1C.<>f__this = this; - BodyDef.c__Iterator1C5 expr_0E = c__Iterator1C; - expr_0E.$PC = -2; - return expr_0E; + foreach (string item in base.ConfigErrors()) + { + yield return item; + } + if (this.cachedPartsVulnerableToFrostbite.NullOrEmpty()) + { + yield return "no parts vulnerable to frostbite"; + } + List.Enumerator enumerator2 = this.AllParts.GetEnumerator(); + try + { + while (enumerator2.MoveNext()) + { + BodyPartRecord part = enumerator2.Current; + if (part.def.isConceptual && part.coverageAbs != 0.0) + { + yield return string.Format("part {0} is tagged conceptual, but has nonzero coverage", part); + } + } + } + finally + { + ((IDisposable)(object)enumerator2).Dispose(); + } } public override void ResolveReferences() @@ -92,7 +109,7 @@ public override void ResolveReferences() List allParts = this.AllParts; for (int i = 0; i < allParts.Count; i++) { - if (allParts[i].def.frostbiteVulnerability > 0f) + if (allParts[i].def.frostbiteVulnerability > 0.0) { this.cachedPartsVulnerableToFrostbite.Add(allParts[i]); } @@ -118,17 +135,10 @@ private void CacheDataRecursive(BodyPartRecord node) { num -= node.parts[j].coverage; } - if (num <= 0f) + if (num <= 0.0) { num = 0f; - Log.Warning(string.Concat(new string[] - { - "BodyDef ", - this.defName, - " has BodyPartRecord of ", - node.def.defName, - " whose children have more or equal total coverage than 1. This means parent can't be hit independently at all." - })); + Log.Warning("BodyDef " + base.defName + " has BodyPartRecord of " + node.def.defName + " whose children have more or equal total coverage than 1. This means parent can't be hit independently at all."); } node.coverageAbs = node.coverageAbsWithChildren * num; if (node.height == BodyPartHeight.Undefined) diff --git a/Assembly-CSharp/Verse/BodyPartDef.cs b/Assembly-CSharp/Verse/BodyPartDef.cs index d80d8ff27..5491173b3 100644 --- a/Assembly-CSharp/Verse/BodyPartDef.cs +++ b/Assembly-CSharp/Verse/BodyPartDef.cs @@ -1,6 +1,4 @@ -using System; using System.Collections.Generic; -using System.Diagnostics; using UnityEngine; namespace Verse @@ -41,18 +39,20 @@ public bool IsDelicate { get { - return this.oldInjuryBaseChance >= 0.8f; + return this.oldInjuryBaseChance >= 0.800000011920929; } } - [DebuggerHidden] public override IEnumerable ConfigErrors() { - BodyPartDef.c__Iterator1C6 c__Iterator1C = new BodyPartDef.c__Iterator1C6(); - c__Iterator1C.<>f__this = this; - BodyPartDef.c__Iterator1C6 expr_0E = c__Iterator1C; - expr_0E.$PC = -2; - return expr_0E; + foreach (string item in base.ConfigErrors()) + { + yield return item; + } + if (this.frostbiteVulnerability > 10.0) + { + yield return "frostbitePriority > max 10: " + this.frostbiteVulnerability; + } } public bool IsSolid(BodyPartRecord part, List hediffs) @@ -72,7 +72,11 @@ public bool IsSolid(BodyPartRecord part, List hediffs) public bool IsSkinCovered(BodyPartRecord part, HediffSet body) { - return !body.PartOrAnyAncestorHasDirectlyAddedParts(part) && this.skinCovered; + if (body.PartOrAnyAncestorHasDirectlyAddedParts(part)) + { + return false; + } + return this.skinCovered; } public float GetMaxHealth(Pawn pawn) @@ -90,7 +94,7 @@ public float GetHitChanceFactorFor(DamageDef damage) { return 1f; } - float result; + float result = default(float); if (this.hitChanceFactors.TryGetValue(damage, out result)) { return result; diff --git a/Assembly-CSharp/Verse/BodyPartDepth.cs b/Assembly-CSharp/Verse/BodyPartDepth.cs index 5d415c958..9e1bc810a 100644 --- a/Assembly-CSharp/Verse/BodyPartDepth.cs +++ b/Assembly-CSharp/Verse/BodyPartDepth.cs @@ -1,11 +1,9 @@ -using System; - namespace Verse { public enum BodyPartDepth : byte { - Undefined, - Inside, - Outside + Undefined = 0, + Inside = 1, + Outside = 2 } } diff --git a/Assembly-CSharp/Verse/BodyPartGroupDef.cs b/Assembly-CSharp/Verse/BodyPartGroupDef.cs index 98106a0f9..8a4532195 100644 --- a/Assembly-CSharp/Verse/BodyPartGroupDef.cs +++ b/Assembly-CSharp/Verse/BodyPartGroupDef.cs @@ -1,5 +1,3 @@ -using System; - namespace Verse { public class BodyPartGroupDef : Def diff --git a/Assembly-CSharp/Verse/BodyPartHeight.cs b/Assembly-CSharp/Verse/BodyPartHeight.cs index 225489858..34ff0d835 100644 --- a/Assembly-CSharp/Verse/BodyPartHeight.cs +++ b/Assembly-CSharp/Verse/BodyPartHeight.cs @@ -1,12 +1,10 @@ -using System; - namespace Verse { public enum BodyPartHeight : byte { - Undefined, - Bottom, - Middle, - Top + Undefined = 0, + Bottom = 1, + Middle = 2, + Top = 3 } } diff --git a/Assembly-CSharp/Verse/BodyPartRecord.cs b/Assembly-CSharp/Verse/BodyPartRecord.cs index 65603e103..c388922ea 100644 --- a/Assembly-CSharp/Verse/BodyPartRecord.cs +++ b/Assembly-CSharp/Verse/BodyPartRecord.cs @@ -1,6 +1,4 @@ -using System; using System.Collections.Generic; -using System.Diagnostics; using System.Linq; namespace Verse @@ -30,14 +28,7 @@ public class BodyPartRecord public override string ToString() { - return string.Concat(new object[] - { - "BodyPartRecord(", - (this.def == null) ? "NULL_DEF" : this.def.defName, - " parts.Count=", - this.parts.Count, - ")" - }); + return "BodyPartRecord(" + ((this.def == null) ? "NULL_DEF" : this.def.defName) + " parts.Count=" + this.parts.Count + ")"; } public bool IsInGroup(BodyPartGroupDef group) @@ -52,33 +43,37 @@ public bool IsInGroup(BodyPartGroupDef group) return false; } - [DebuggerHidden] public IEnumerable GetChildParts(string tag) { - BodyPartRecord.c__Iterator1C2 c__Iterator1C = new BodyPartRecord.c__Iterator1C2(); - c__Iterator1C.tag = tag; - c__Iterator1C.<$>tag = tag; - c__Iterator1C.<>f__this = this; - BodyPartRecord.c__Iterator1C2 expr_1C = c__Iterator1C; - expr_1C.$PC = -2; - return expr_1C; + if (this.def.tags.Contains(tag)) + { + yield return this; + } + for (int i = 0; i < this.parts.Count; i++) + { + foreach (BodyPartRecord childPart in this.parts[i].GetChildParts(tag)) + { + yield return childPart; + } + } } public bool HasChildParts(string tag) { - return this.GetChildParts(tag).Any(); + return this.GetChildParts(tag).Any(); } - [DebuggerHidden] public IEnumerable GetConnectedParts(string tag) { - BodyPartRecord.c__Iterator1C3 c__Iterator1C = new BodyPartRecord.c__Iterator1C3(); - c__Iterator1C.tag = tag; - c__Iterator1C.<$>tag = tag; - c__Iterator1C.<>f__this = this; - BodyPartRecord.c__Iterator1C3 expr_1C = c__Iterator1C; - expr_1C.$PC = -2; - return expr_1C; + BodyPartRecord ancestor = this; + while (ancestor.parent != null && ancestor.parent.def.tags.Contains(tag)) + { + ancestor = ancestor.parent; + } + foreach (BodyPartRecord childPart in ancestor.GetChildParts(tag)) + { + yield return childPart; + } } } } diff --git a/Assembly-CSharp/Verse/BodyPartRemovalIntent.cs b/Assembly-CSharp/Verse/BodyPartRemovalIntent.cs index 3fdace170..2bfd51d0a 100644 --- a/Assembly-CSharp/Verse/BodyPartRemovalIntent.cs +++ b/Assembly-CSharp/Verse/BodyPartRemovalIntent.cs @@ -1,10 +1,8 @@ -using System; - namespace Verse { public enum BodyPartRemovalIntent { - Harvest, - Amputate + Harvest = 0, + Amputate = 1 } } diff --git a/Assembly-CSharp/Verse/BodyPartToDrop.cs b/Assembly-CSharp/Verse/BodyPartToDrop.cs index 311458cb4..a5a8d1988 100644 --- a/Assembly-CSharp/Verse/BodyPartToDrop.cs +++ b/Assembly-CSharp/Verse/BodyPartToDrop.cs @@ -1,5 +1,3 @@ -using System; - namespace Verse { public class BodyPartToDrop diff --git a/Assembly-CSharp/Verse/BoolGrid.cs b/Assembly-CSharp/Verse/BoolGrid.cs index ee6195138..a28fc136d 100644 --- a/Assembly-CSharp/Verse/BoolGrid.cs +++ b/Assembly-CSharp/Verse/BoolGrid.cs @@ -25,11 +25,20 @@ public IEnumerable ActiveCells { get { - BoolGrid.<>c__Iterator1F6 <>c__Iterator1F = new BoolGrid.<>c__Iterator1F6(); - <>c__Iterator1F.<>f__this = this; - BoolGrid.<>c__Iterator1F6 expr_0E = <>c__Iterator1F; - expr_0E.$PC = -2; - return expr_0E; + if (this.trueCountInt != 0) + { + int yieldedCount = 0; + for (int i = 0; i < this.arr.Length; i++) + { + if (this.arr[i]) + { + yield return CellIndicesUtility.IndexToCell(i, this.mapSizeX); + yieldedCount++; + if (yieldedCount >= this.trueCountInt) + break; + } + } + } } } @@ -80,7 +89,20 @@ public BoolGrid(Map map) public bool MapSizeMatches(Map map) { - return this.mapSizeX == map.Size.x && this.mapSizeZ == map.Size.z; + int num = this.mapSizeX; + IntVec3 size = map.Size; + int result; + if (num == size.x) + { + int num2 = this.mapSizeZ; + IntVec3 size2 = map.Size; + result = ((num2 == size2.z) ? 1 : 0); + } + else + { + result = 0; + } + return (byte)result != 0; } public void ClearAndResizeTo(Map map) @@ -88,11 +110,15 @@ public void ClearAndResizeTo(Map map) if (this.MapSizeMatches(map) && this.arr != null) { this.Clear(); - return; } - this.mapSizeX = map.Size.x; - this.mapSizeZ = map.Size.z; - this.arr = new bool[this.mapSizeX * this.mapSizeZ]; + else + { + IntVec3 size = map.Size; + this.mapSizeX = size.x; + IntVec3 size2 = map.Size; + this.mapSizeZ = size2.z; + this.arr = new bool[this.mapSizeX * this.mapSizeZ]; + } } public void ExposeData() @@ -116,18 +142,17 @@ public virtual void Set(IntVec3 c, bool value) public virtual void Set(int index, bool value) { - if (this.arr[index] == value) - { - return; - } - this.arr[index] = value; - if (value) - { - this.trueCountInt++; - } - else + if (this.arr[index] != value) { - this.trueCountInt--; + this.arr[index] = value; + if (value) + { + this.trueCountInt++; + } + else + { + this.trueCountInt--; + } } } diff --git a/Assembly-CSharp/Verse/BoolUnknown.cs b/Assembly-CSharp/Verse/BoolUnknown.cs index 3bb83032a..64a8b9d31 100644 --- a/Assembly-CSharp/Verse/BoolUnknown.cs +++ b/Assembly-CSharp/Verse/BoolUnknown.cs @@ -1,11 +1,9 @@ -using System; - namespace Verse { public enum BoolUnknown : byte { - True, - False, - Unknown + True = 0, + False = 1, + Unknown = 2 } } diff --git a/Assembly-CSharp/Verse/BuildableDef.cs b/Assembly-CSharp/Verse/BuildableDef.cs index 1247b654c..49935aee1 100644 --- a/Assembly-CSharp/Verse/BuildableDef.cs +++ b/Assembly-CSharp/Verse/BuildableDef.cs @@ -1,7 +1,6 @@ using RimWorld; using System; using System.Collections.Generic; -using System.Diagnostics; using UnityEngine; namespace Verse @@ -85,7 +84,7 @@ public bool MadeFromStuff { get { - return !this.stuffCategories.NullOrEmpty(); + return !this.stuffCategories.NullOrEmpty(); } } @@ -123,9 +122,18 @@ public List PlaceWorkers return null; } this.placeWorkersInstantiatedInt = new List(); - foreach (Type current in this.placeWorkers) + List.Enumerator enumerator = this.placeWorkers.GetEnumerator(); + try { - this.placeWorkersInstantiatedInt.Add((PlaceWorker)Activator.CreateInstance(current)); + while (enumerator.MoveNext()) + { + Type current = enumerator.Current; + this.placeWorkersInstantiatedInt.Add((PlaceWorker)Activator.CreateInstance(current)); + } + } + finally + { + ((IDisposable)(object)enumerator).Dispose(); } return this.placeWorkersInstantiatedInt; } @@ -150,13 +158,13 @@ public bool ForceAllowPlaceOver(BuildableDef other) public override void PostLoad() { base.PostLoad(); - LongEventHandler.ExecuteWhenFinished(delegate + LongEventHandler.ExecuteWhenFinished((Action)delegate { if (!this.uiIconPath.NullOrEmpty()) { this.uiIcon = ContentFinder.Get(this.uiIconPath, true); } - else if (this.DrawMatSingle != null && this.DrawMatSingle != BaseContent.BadMat) + else if ((UnityEngine.Object)this.DrawMatSingle != (UnityEngine.Object)null && (UnityEngine.Object)this.DrawMatSingle != (UnityEngine.Object)BaseContent.BadMat) { this.uiIcon = (Texture2D)this.DrawMatSingle.mainTexture; } @@ -168,24 +176,22 @@ public override void ResolveReferences() base.ResolveReferences(); } - [DebuggerHidden] public override IEnumerable ConfigErrors() { - BuildableDef.c__Iterator1C7 c__Iterator1C = new BuildableDef.c__Iterator1C7(); - c__Iterator1C.<>f__this = this; - BuildableDef.c__Iterator1C7 expr_0E = c__Iterator1C; - expr_0E.$PC = -2; - return expr_0E; + foreach (string item in base.ConfigErrors()) + { + yield return item; + } } public override string ToString() { - return this.defName; + return base.defName; } public override int GetHashCode() { - return this.defName.GetHashCode(); + return base.defName.GetHashCode(); } } } diff --git a/Assembly-CSharp/Verse/Building.cs b/Assembly-CSharp/Verse/Building.cs index 445a47ffb..329d69592 100644 --- a/Assembly-CSharp/Verse/Building.cs +++ b/Assembly-CSharp/Verse/Building.cs @@ -1,7 +1,6 @@ using RimWorld; using System; using System.Collections.Generic; -using System.Diagnostics; using Verse.AI; using Verse.AI.Group; using Verse.Sound; @@ -41,13 +40,13 @@ public override int HitPoints public override void SpawnSetup(Map map, bool respawningAfterLoad) { - if (this.def.IsEdifice()) + if (base.def.IsEdifice()) { map.edificeGrid.Register(this); } base.SpawnSetup(map, respawningAfterLoad); base.Map.listerBuildings.Add(this); - if (this.def.coversFloor) + if (base.def.coversFloor) { base.Map.mapDrawer.MapMeshDirty(base.Position, MapMeshFlag.Terrain, true, false); } @@ -59,23 +58,23 @@ public override void SpawnSetup(Map map, bool respawningAfterLoad) IntVec3 intVec = new IntVec3(j, 0, i); base.Map.mapDrawer.MapMeshDirty(intVec, MapMeshFlag.Buildings); base.Map.glowGrid.MarkGlowGridDirty(intVec); - if (!SnowGrid.CanCoexistWithSnow(this.def)) + if (!SnowGrid.CanCoexistWithSnow(base.def)) { base.Map.snowGrid.SetDepth(intVec, 0f); } } } - if (base.Faction == Faction.OfPlayer && this.def.building != null && this.def.building.spawnedConceptLearnOpportunity != null) + if (base.Faction == Faction.OfPlayer && base.def.building != null && base.def.building.spawnedConceptLearnOpportunity != null) { - LessonAutoActivator.TeachOpportunity(this.def.building.spawnedConceptLearnOpportunity, OpportunityType.GoodToKnow); + LessonAutoActivator.TeachOpportunity(base.def.building.spawnedConceptLearnOpportunity, OpportunityType.GoodToKnow); } AutoHomeAreaMaker.Notify_BuildingSpawned(this); - if (this.def.building != null && !this.def.building.soundAmbient.NullOrUndefined()) + if (base.def.building != null && !base.def.building.soundAmbient.NullOrUndefined()) { - LongEventHandler.ExecuteWhenFinished(delegate + LongEventHandler.ExecuteWhenFinished((Action)delegate { - SoundInfo info = SoundInfo.InMap(this, MaintenanceType.None); - this.sustainerAmbient = this.def.building.soundAmbient.TrySpawnSustainer(info); + SoundInfo info = SoundInfo.InMap((Thing)this, MaintenanceType.None); + this.sustainerAmbient = base.def.building.soundAmbient.TrySpawnSustainer(info); }); } base.Map.listerBuildingsRepairable.Notify_BuildingSpawned(this); @@ -90,15 +89,15 @@ public override void DeSpawn() { Map map = base.Map; base.DeSpawn(); - if (this.def.IsEdifice()) + if (base.def.IsEdifice()) { map.edificeGrid.DeRegister(this); } - if (this.def.MakeFog) + if (base.def.MakeFog) { map.fogGrid.Notify_FogBlockerRemoved(base.Position); } - if (this.def.holdsRoof) + if (base.def.holdsRoof) { RoofCollapseCellsFinder.Notify_RoofHolderDespawned(this, map); } @@ -113,14 +112,14 @@ public override void DeSpawn() { IntVec3 loc = new IntVec3(j, 0, i); MapMeshFlag mapMeshFlag = MapMeshFlag.Buildings; - if (this.def.coversFloor) + if (base.def.coversFloor) { - mapMeshFlag |= MapMeshFlag.Terrain; + mapMeshFlag = (MapMeshFlag)((int)mapMeshFlag | 16); } - if (this.def.Fillage == FillCategory.Full) + if (base.def.Fillage == FillCategory.Full) { - mapMeshFlag |= MapMeshFlag.Roofs; - mapMeshFlag |= MapMeshFlag.Snow; + mapMeshFlag = (MapMeshFlag)((int)mapMeshFlag | 32); + mapMeshFlag = (MapMeshFlag)((int)mapMeshFlag | 64); } map.mapDrawer.MapMeshDirty(loc, mapMeshFlag); map.glowGrid.MarkGlowGridDirty(loc); @@ -128,12 +127,12 @@ public override void DeSpawn() } map.listerBuildings.Remove(this); map.listerBuildingsRepairable.Notify_BuildingDeSpawned(this); - if (this.def.leaveTerrain != null && Current.ProgramState == ProgramState.Playing) + if (base.def.leaveTerrain != null && Current.ProgramState == ProgramState.Playing) { CellRect.CellRectIterator iterator = this.OccupiedRect().GetIterator(); while (!iterator.Done()) { - map.terrainGrid.SetTerrain(iterator.Current, this.def.leaveTerrain); + map.terrainGrid.SetTerrain(iterator.Current, base.def.leaveTerrain); iterator.MoveNext(); } } @@ -142,7 +141,7 @@ public override void DeSpawn() { map.exitMapGrid.Notify_LOSBlockerDespawned(); } - if (this.def.building.hasFuelingPort) + if (base.def.building.hasFuelingPort) { IntVec3 fuelingPortCell = FuelingPortUtility.GetFuelingPortCell(base.Position, base.Rotation); CompLaunchable compLaunchable = FuelingPortUtility.LaunchableAt(fuelingPortCell, map); @@ -151,7 +150,7 @@ public override void DeSpawn() compLaunchable.Notify_FuelingPortSourceDeSpawned(); } } - if (this.def.building.ai_combatDangerous) + if (base.def.building.ai_combatDangerous) { AvoidGridMaker.Notify_CombatDangerousBuildingDespawned(this, map); } @@ -170,7 +169,7 @@ public override void Destroy(DestroyMode mode = DestroyMode.Vanish) public override void Draw() { - if (this.def.drawerType == DrawerType.RealtimeOnly) + if (base.def.drawerType == DrawerType.RealtimeOnly) { base.Draw(); } @@ -227,48 +226,55 @@ public override void DrawExtraSelectionOverlays() } } - [DebuggerHidden] public override IEnumerable GetGizmos() { - Building.c__Iterator141 c__Iterator = new Building.c__Iterator141(); - c__Iterator.<>f__this = this; - Building.c__Iterator141 expr_0E = c__Iterator; - expr_0E.$PC = -2; - return expr_0E; + foreach (Gizmo gizmo in base.GetGizmos()) + { + yield return gizmo; + } + if (base.def.Minifiable && base.Faction == Faction.OfPlayer) + { + yield return (Gizmo)InstallationDesignatorDatabase.DesignatorFor(base.def); + } + Command buildCopy = BuildCopyCommandUtility.BuildCopyCommand(base.def, base.Stuff); + if (buildCopy != null) + { + yield return (Gizmo)buildCopy; + } } public virtual bool ClaimableBy(Faction by) { - if (this.def.building.isNaturalRock || !this.def.Claimable) + if (!base.def.building.isNaturalRock && base.def.Claimable) { - return false; - } - if (base.Faction != null) - { - if (base.Faction == by) - { - return false; - } - List list = base.Map.mapPawns.SpawnedPawnsInFaction(base.Faction); - for (int i = 0; i < list.Count; i++) + if (base.Faction != null) { - if (list[i].RaceProps.Humanlike && GenHostility.IsActiveThreat(list[i])) + if (base.Faction == by) { return false; } + List list = base.Map.mapPawns.SpawnedPawnsInFaction(base.Faction); + for (int i = 0; i < list.Count; i++) + { + if (list[i].RaceProps.Humanlike && GenHostility.IsActiveThreat(list[i])) + { + return false; + } + } } + return true; } - return true; + return false; } public virtual ushort PathFindCostFor(Pawn p) { - return 0; + return (ushort)0; } public virtual ushort PathWalkCostFor(Pawn p) { - return 0; + return (ushort)0; } public virtual bool IsDangerousFor(Pawn p) diff --git a/Assembly-CSharp/Verse/BuildingsDamageSectionLayerUtility.cs b/Assembly-CSharp/Verse/BuildingsDamageSectionLayerUtility.cs index ac3fa9473..54c0e208e 100644 --- a/Assembly-CSharp/Verse/BuildingsDamageSectionLayerUtility.cs +++ b/Assembly-CSharp/Verse/BuildingsDamageSectionLayerUtility.cs @@ -1,4 +1,3 @@ -using System; using System.Collections.Generic; using System.Linq; using UnityEngine; @@ -8,7 +7,7 @@ namespace Verse [StaticConstructorOnStartup] public static class BuildingsDamageSectionLayerUtility { - private static readonly Material[] DefaultScratchMats = new Material[] + private static readonly Material[] DefaultScratchMats = new Material[3] { MaterialPool.MatFrom("Damage/Scratch1"), MaterialPool.MatFrom("Damage/Scratch2"), @@ -23,11 +22,10 @@ public static class BuildingsDamageSectionLayerUtility public static void Notify_BuildingHitPointsChanged(Building b, int oldHitPoints) { - if (!b.Spawned || !b.def.useHitPoints || b.HitPoints == oldHitPoints || !b.def.drawDamagedOverlay || BuildingsDamageSectionLayerUtility.GetDamageOverlaysCount(b, b.HitPoints) == BuildingsDamageSectionLayerUtility.GetDamageOverlaysCount(b, oldHitPoints)) + if (b.Spawned && b.def.useHitPoints && b.HitPoints != oldHitPoints && b.def.drawDamagedOverlay && BuildingsDamageSectionLayerUtility.GetDamageOverlaysCount(b, b.HitPoints) != BuildingsDamageSectionLayerUtility.GetDamageOverlaysCount(b, oldHitPoints)) { - return; + b.Map.mapDrawer.MapMeshDirty(b.Position, MapMeshFlag.BuildingsDamage); } - b.Map.mapDrawer.MapMeshDirty(b.Position, MapMeshFlag.BuildingsDamage); } public static bool UsesLinkableCornersAndEdges(Building b) @@ -48,16 +46,16 @@ public static IList GetScratchMats(Building b) public static List GetAvailableOverlays(Building b) { BuildingsDamageSectionLayerUtility.availableOverlays.Clear(); - if (BuildingsDamageSectionLayerUtility.GetScratchMats(b).Any()) + if (BuildingsDamageSectionLayerUtility.GetScratchMats(b).Any()) { int num = 3; Rect damageRect = BuildingsDamageSectionLayerUtility.GetDamageRect(b); float num2 = damageRect.width * damageRect.height; - if (num2 > 4f) + if (num2 > 4.0) { - num += Mathf.RoundToInt((num2 - 4f) * 0.54f); + num += Mathf.RoundToInt((float)((num2 - 4.0) * 0.54000002145767212)); } - for (int i = 0; i < num; i++) + for (int num3 = 0; num3 < num; num3++) { BuildingsDamageSectionLayerUtility.availableOverlays.Add(DamageOverlay.Scratch); } @@ -68,35 +66,35 @@ public static List GetAvailableOverlays(Building b) { IntVec3 position = b.Position; DamageGraphicData damageData = b.def.graphicData.damageData; - if (damageData.edgeTopMat != null && BuildingsDamageSectionLayerUtility.DifferentAt(b, position.x, position.z + 1) && BuildingsDamageSectionLayerUtility.SameAndDamagedAt(b, position.x + 1, position.z) && BuildingsDamageSectionLayerUtility.DifferentAt(b, position.x + 1, position.z + 1)) + if ((Object)damageData.edgeTopMat != (Object)null && BuildingsDamageSectionLayerUtility.DifferentAt(b, position.x, position.z + 1) && BuildingsDamageSectionLayerUtility.SameAndDamagedAt(b, position.x + 1, position.z) && BuildingsDamageSectionLayerUtility.DifferentAt(b, position.x + 1, position.z + 1)) { BuildingsDamageSectionLayerUtility.availableOverlays.Add(DamageOverlay.TopEdge); } - if (damageData.edgeRightMat != null && BuildingsDamageSectionLayerUtility.DifferentAt(b, position.x + 1, position.z) && BuildingsDamageSectionLayerUtility.SameAndDamagedAt(b, position.x, position.z + 1) && BuildingsDamageSectionLayerUtility.DifferentAt(b, position.x + 1, position.z + 1)) + if ((Object)damageData.edgeRightMat != (Object)null && BuildingsDamageSectionLayerUtility.DifferentAt(b, position.x + 1, position.z) && BuildingsDamageSectionLayerUtility.SameAndDamagedAt(b, position.x, position.z + 1) && BuildingsDamageSectionLayerUtility.DifferentAt(b, position.x + 1, position.z + 1)) { BuildingsDamageSectionLayerUtility.availableOverlays.Add(DamageOverlay.RightEdge); } - if (damageData.edgeBotMat != null && BuildingsDamageSectionLayerUtility.DifferentAt(b, position.x, position.z - 1) && BuildingsDamageSectionLayerUtility.SameAndDamagedAt(b, position.x + 1, position.z) && BuildingsDamageSectionLayerUtility.DifferentAt(b, position.x + 1, position.z - 1)) + if ((Object)damageData.edgeBotMat != (Object)null && BuildingsDamageSectionLayerUtility.DifferentAt(b, position.x, position.z - 1) && BuildingsDamageSectionLayerUtility.SameAndDamagedAt(b, position.x + 1, position.z) && BuildingsDamageSectionLayerUtility.DifferentAt(b, position.x + 1, position.z - 1)) { BuildingsDamageSectionLayerUtility.availableOverlays.Add(DamageOverlay.BotEdge); } - if (damageData.edgeLeftMat != null && BuildingsDamageSectionLayerUtility.DifferentAt(b, position.x - 1, position.z) && BuildingsDamageSectionLayerUtility.SameAndDamagedAt(b, position.x, position.z + 1) && BuildingsDamageSectionLayerUtility.DifferentAt(b, position.x - 1, position.z + 1)) + if ((Object)damageData.edgeLeftMat != (Object)null && BuildingsDamageSectionLayerUtility.DifferentAt(b, position.x - 1, position.z) && BuildingsDamageSectionLayerUtility.SameAndDamagedAt(b, position.x, position.z + 1) && BuildingsDamageSectionLayerUtility.DifferentAt(b, position.x - 1, position.z + 1)) { BuildingsDamageSectionLayerUtility.availableOverlays.Add(DamageOverlay.LeftEdge); } - if (damageData.cornerTLMat != null && BuildingsDamageSectionLayerUtility.DifferentAt(b, position.x - 1, position.z) && BuildingsDamageSectionLayerUtility.DifferentAt(b, position.x, position.z + 1)) + if ((Object)damageData.cornerTLMat != (Object)null && BuildingsDamageSectionLayerUtility.DifferentAt(b, position.x - 1, position.z) && BuildingsDamageSectionLayerUtility.DifferentAt(b, position.x, position.z + 1)) { BuildingsDamageSectionLayerUtility.availableOverlays.Add(DamageOverlay.TopLeftCorner); } - if (damageData.cornerTRMat != null && BuildingsDamageSectionLayerUtility.DifferentAt(b, position.x + 1, position.z) && BuildingsDamageSectionLayerUtility.DifferentAt(b, position.x, position.z + 1)) + if ((Object)damageData.cornerTRMat != (Object)null && BuildingsDamageSectionLayerUtility.DifferentAt(b, position.x + 1, position.z) && BuildingsDamageSectionLayerUtility.DifferentAt(b, position.x, position.z + 1)) { BuildingsDamageSectionLayerUtility.availableOverlays.Add(DamageOverlay.TopRightCorner); } - if (damageData.cornerBRMat != null && BuildingsDamageSectionLayerUtility.DifferentAt(b, position.x + 1, position.z) && BuildingsDamageSectionLayerUtility.DifferentAt(b, position.x, position.z - 1)) + if ((Object)damageData.cornerBRMat != (Object)null && BuildingsDamageSectionLayerUtility.DifferentAt(b, position.x + 1, position.z) && BuildingsDamageSectionLayerUtility.DifferentAt(b, position.x, position.z - 1)) { BuildingsDamageSectionLayerUtility.availableOverlays.Add(DamageOverlay.BotRightCorner); } - if (damageData.cornerBLMat != null && BuildingsDamageSectionLayerUtility.DifferentAt(b, position.x - 1, position.z) && BuildingsDamageSectionLayerUtility.DifferentAt(b, position.x, position.z - 1)) + if ((Object)damageData.cornerBLMat != (Object)null && BuildingsDamageSectionLayerUtility.DifferentAt(b, position.x - 1, position.z) && BuildingsDamageSectionLayerUtility.DifferentAt(b, position.x, position.z - 1)) { BuildingsDamageSectionLayerUtility.availableOverlays.Add(DamageOverlay.BotLeftCorner); } @@ -104,24 +102,24 @@ public static List GetAvailableOverlays(Building b) } else { - Material x; - Material x2; - Material x3; - Material x4; + Material x = default(Material); + Material x2 = default(Material); + Material x3 = default(Material); + Material x4 = default(Material); BuildingsDamageSectionLayerUtility.GetCornerMats(out x, out x2, out x3, out x4, b); - if (x != null) + if ((Object)x != (Object)null) { BuildingsDamageSectionLayerUtility.availableOverlays.Add(DamageOverlay.TopLeftCorner); } - if (x2 != null) + if ((Object)x2 != (Object)null) { BuildingsDamageSectionLayerUtility.availableOverlays.Add(DamageOverlay.TopRightCorner); } - if (x4 != null) + if ((Object)x4 != (Object)null) { BuildingsDamageSectionLayerUtility.availableOverlays.Add(DamageOverlay.BotLeftCorner); } - if (x3 != null) + if ((Object)x3 != (Object)null) { BuildingsDamageSectionLayerUtility.availableOverlays.Add(DamageOverlay.BotRightCorner); } @@ -137,36 +135,38 @@ public static void GetCornerMats(out Material topLeft, out Material topRight, ou topRight = null; botRight = null; botLeft = null; - return; - } - DamageGraphicData damageData = b.def.graphicData.damageData; - if (b.Rotation == Rot4.North) - { - topLeft = damageData.cornerTLMat; - topRight = damageData.cornerTRMat; - botRight = damageData.cornerBRMat; - botLeft = damageData.cornerBLMat; - } - else if (b.Rotation == Rot4.East) - { - topLeft = damageData.cornerBLMat; - topRight = damageData.cornerTLMat; - botRight = damageData.cornerTRMat; - botLeft = damageData.cornerBRMat; - } - else if (b.Rotation == Rot4.South) - { - topLeft = damageData.cornerBRMat; - topRight = damageData.cornerBLMat; - botRight = damageData.cornerTLMat; - botLeft = damageData.cornerTRMat; } else { - topLeft = damageData.cornerTRMat; - topRight = damageData.cornerBRMat; - botRight = damageData.cornerBLMat; - botLeft = damageData.cornerTLMat; + DamageGraphicData damageData = b.def.graphicData.damageData; + if (b.Rotation == Rot4.North) + { + topLeft = damageData.cornerTLMat; + topRight = damageData.cornerTRMat; + botRight = damageData.cornerBRMat; + botLeft = damageData.cornerBLMat; + } + else if (b.Rotation == Rot4.East) + { + topLeft = damageData.cornerBLMat; + topRight = damageData.cornerTLMat; + botRight = damageData.cornerTRMat; + botLeft = damageData.cornerBRMat; + } + else if (b.Rotation == Rot4.South) + { + topLeft = damageData.cornerBRMat; + topRight = damageData.cornerBLMat; + botRight = damageData.cornerTLMat; + botLeft = damageData.cornerTRMat; + } + else + { + topLeft = damageData.cornerTRMat; + topRight = damageData.cornerBRMat; + botRight = damageData.cornerBLMat; + botLeft = damageData.cornerTLMat; + } } } @@ -175,22 +175,20 @@ public static List GetOverlays(Building b) BuildingsDamageSectionLayerUtility.overlays.Clear(); BuildingsDamageSectionLayerUtility.overlaysWorkingList.Clear(); BuildingsDamageSectionLayerUtility.overlaysWorkingList.AddRange(BuildingsDamageSectionLayerUtility.GetAvailableOverlays(b)); - if (!BuildingsDamageSectionLayerUtility.overlaysWorkingList.Any()) + if (!BuildingsDamageSectionLayerUtility.overlaysWorkingList.Any()) { return BuildingsDamageSectionLayerUtility.overlays; } Rand.PushState(); Rand.Seed = Gen.HashCombineInt(b.thingIDNumber, 1958376471); int damageOverlaysCount = BuildingsDamageSectionLayerUtility.GetDamageOverlaysCount(b, b.HitPoints); - for (int i = 0; i < damageOverlaysCount; i++) + int num = 0; + while (num < damageOverlaysCount && BuildingsDamageSectionLayerUtility.overlaysWorkingList.Any()) { - if (!BuildingsDamageSectionLayerUtility.overlaysWorkingList.Any()) - { - break; - } - DamageOverlay item = BuildingsDamageSectionLayerUtility.overlaysWorkingList.RandomElement(); + DamageOverlay item = BuildingsDamageSectionLayerUtility.overlaysWorkingList.RandomElement(); BuildingsDamageSectionLayerUtility.overlaysWorkingList.Remove(item); BuildingsDamageSectionLayerUtility.overlays.Add(item); + num++; } Rand.PopState(); return BuildingsDamageSectionLayerUtility.overlays; diff --git a/Assembly-CSharp/Verse/ByteGrid.cs b/Assembly-CSharp/Verse/ByteGrid.cs index ceaae818f..9776f8bd2 100644 --- a/Assembly-CSharp/Verse/ByteGrid.cs +++ b/Assembly-CSharp/Verse/ByteGrid.cs @@ -66,19 +66,36 @@ public ByteGrid(Map map) public bool MapSizeMatches(Map map) { - return this.mapSizeX == map.Size.x && this.mapSizeZ == map.Size.z; + int num = this.mapSizeX; + IntVec3 size = map.Size; + int result; + if (num == size.x) + { + int num2 = this.mapSizeZ; + IntVec3 size2 = map.Size; + result = ((num2 == size2.z) ? 1 : 0); + } + else + { + result = 0; + } + return (byte)result != 0; } public void ClearAndResizeTo(Map map) { if (this.MapSizeMatches(map) && this.grid != null) { - this.Clear(0); - return; + this.Clear((byte)0); + } + else + { + IntVec3 size = map.Size; + this.mapSizeX = size.x; + IntVec3 size2 = map.Size; + this.mapSizeZ = size2.z; + this.grid = new byte[this.mapSizeX * this.mapSizeZ]; } - this.mapSizeX = map.Size.x; - this.mapSizeZ = map.Size.z; - this.grid = new byte[this.mapSizeX * this.mapSizeZ]; } public void ExposeData() @@ -111,7 +128,7 @@ public void DebugDraw() if (b > 0) { IntVec3 c = CellIndicesUtility.IndexToCell(i, this.mapSizeX); - CellRenderer.RenderCell(c, (float)b / 255f * 0.5f); + CellRenderer.RenderCell(c, (float)((float)(int)b / 255.0 * 0.5)); } } } diff --git a/Assembly-CSharp/Verse/CachedTempInfo.cs b/Assembly-CSharp/Verse/CachedTempInfo.cs index 279f5ac40..963c92c5c 100644 --- a/Assembly-CSharp/Verse/CachedTempInfo.cs +++ b/Assembly-CSharp/Verse/CachedTempInfo.cs @@ -1,5 +1,3 @@ -using System; - namespace Verse { public struct CachedTempInfo diff --git a/Assembly-CSharp/Verse/CameraDriver.cs b/Assembly-CSharp/Verse/CameraDriver.cs index b8a7c0c71..f1c88019a 100644 --- a/Assembly-CSharp/Verse/CameraDriver.cs +++ b/Assembly-CSharp/Verse/CameraDriver.cs @@ -71,7 +71,7 @@ private Camera MyCamera { get { - if (this.cachedCamera == null) + if ((UnityEngine.Object)this.cachedCamera == (UnityEngine.Object)null) { this.cachedCamera = base.GetComponent(); } @@ -95,19 +95,19 @@ public CameraZoomRange CurrentZoom { get { - if (this.rootSize < 12f) + if (this.rootSize < 12.0) { return CameraZoomRange.Closest; } - if (this.rootSize < 13.8f) + if (this.rootSize < 13.800000190734863) { return CameraZoomRange.Close; } - if (this.rootSize < 42f) + if (this.rootSize < 42.0) { return CameraZoomRange.Middle; } - if (this.rootSize < 57f) + if (this.rootSize < 57.0) { return CameraZoomRange.Far; } @@ -149,10 +149,14 @@ public CellRect CurrentViewRect { CameraDriver.lastViewRect = default(CellRect); float num = (float)UI.screenWidth / (float)UI.screenHeight; - CameraDriver.lastViewRect.minX = Mathf.FloorToInt(this.CurrentRealPosition.x - this.rootSize * num - 1f); - CameraDriver.lastViewRect.maxX = Mathf.CeilToInt(this.CurrentRealPosition.x + this.rootSize * num); - CameraDriver.lastViewRect.minZ = Mathf.FloorToInt(this.CurrentRealPosition.z - this.rootSize - 1f); - CameraDriver.lastViewRect.maxZ = Mathf.CeilToInt(this.CurrentRealPosition.z + this.rootSize); + Vector3 currentRealPosition = this.CurrentRealPosition; + CameraDriver.lastViewRect.minX = Mathf.FloorToInt((float)(currentRealPosition.x - this.rootSize * num - 1.0)); + Vector3 currentRealPosition2 = this.CurrentRealPosition; + CameraDriver.lastViewRect.maxX = Mathf.CeilToInt(currentRealPosition2.x + this.rootSize * num); + Vector3 currentRealPosition3 = this.CurrentRealPosition; + CameraDriver.lastViewRect.minZ = Mathf.FloorToInt((float)(currentRealPosition3.z - this.rootSize - 1.0)); + Vector3 currentRealPosition4 = this.CurrentRealPosition; + CameraDriver.lastViewRect.maxZ = Mathf.CeilToInt(currentRealPosition4.z + this.rootSize); CameraDriver.lastViewRectGetFrame = Time.frameCount; } return CameraDriver.lastViewRect; @@ -164,9 +168,9 @@ public static float HitchReduceFactor get { float result = 1f; - if (Time.deltaTime > 0.025f) + if (Time.deltaTime > 0.02500000037252903) { - result = 0.025f / Time.deltaTime; + result = (float)(0.02500000037252903 / Time.deltaTime); } return result; } @@ -176,7 +180,7 @@ public float CellSizePixels { get { - return (float)UI.screenHeight / (this.rootSize * 2f); + return (float)((float)UI.screenHeight / (this.rootSize * 2.0)); } } @@ -190,15 +194,7 @@ public void Awake() public void OnPreRender() { - if (LongEventHandler.ShouldWaitForEvent) - { - return; - } - if (Find.VisibleMap == null) - { - return; - } - if (!WorldRendererUtility.WorldRenderedNow) + if (!LongEventHandler.ShouldWaitForEvent && Find.VisibleMap != null && !WorldRendererUtility.WorldRenderedNow) { Find.VisibleMap.GenerateWaterMap(); } @@ -206,15 +202,7 @@ public void OnPreRender() public void OnPreCull() { - if (LongEventHandler.ShouldWaitForEvent) - { - return; - } - if (Find.VisibleMap == null) - { - return; - } - if (!WorldRendererUtility.WorldRenderedNow) + if (!LongEventHandler.ShouldWaitForEvent && Find.VisibleMap != null && !WorldRendererUtility.WorldRenderedNow) { Find.VisibleMap.weatherManager.DrawAllWeather(); } @@ -223,139 +211,139 @@ public void OnPreCull() public void OnGUI() { GUI.depth = 100; - if (LongEventHandler.ShouldWaitForEvent) - { - return; - } - if (Find.VisibleMap == null) + if (!LongEventHandler.ShouldWaitForEvent && Find.VisibleMap != null) { - return; - } - this.mouseCoveredByUI = false; - if (Find.WindowStack.GetWindowAt(UI.MousePositionOnUIInverted) != null) - { - this.mouseCoveredByUI = true; - } - if (!this.AnythingPreventsCameraMotion) - { - if (Event.current.type == EventType.MouseDrag && Event.current.button == 2) - { - this.mouseDragVect = Event.current.delta; - Event.current.Use(); - } - float num = 0f; - if (Event.current.type == EventType.ScrollWheel) - { - num -= Event.current.delta.y * 0.35f; - PlayerKnowledgeDatabase.KnowledgeDemonstrated(ConceptDefOf.CameraZoom, KnowledgeAmount.TinyInteraction); - } - if (KeyBindingDefOf.MapZoomIn.KeyDownEvent) - { - num += 4f; - PlayerKnowledgeDatabase.KnowledgeDemonstrated(ConceptDefOf.CameraZoom, KnowledgeAmount.SmallInteraction); - } - if (KeyBindingDefOf.MapZoomOut.KeyDownEvent) + this.mouseCoveredByUI = false; + if (Find.WindowStack.GetWindowAt(UI.MousePositionOnUIInverted) != null) { - num -= 4f; - PlayerKnowledgeDatabase.KnowledgeDemonstrated(ConceptDefOf.CameraZoom, KnowledgeAmount.SmallInteraction); + this.mouseCoveredByUI = true; } - this.desiredSize -= num * 2.6f * this.rootSize / 35f; - if (this.desiredSize < 11f) + if (!this.AnythingPreventsCameraMotion) { - this.desiredSize = 11f; - } - if (this.desiredSize > 60f) - { - this.desiredSize = 60f; - } - this.desiredDolly = Vector3.zero; - if (KeyBindingDefOf.MapDollyLeft.IsDown) - { - this.desiredDolly.x = -this.config.dollyRateKeys; - } - if (KeyBindingDefOf.MapDollyRight.IsDown) - { - this.desiredDolly.x = this.config.dollyRateKeys; - } - if (KeyBindingDefOf.MapDollyUp.IsDown) - { - this.desiredDolly.y = this.config.dollyRateKeys; - } - if (KeyBindingDefOf.MapDollyDown.IsDown) - { - this.desiredDolly.y = -this.config.dollyRateKeys; - } - if (this.mouseDragVect != Vector2.zero) - { - this.mouseDragVect *= CameraDriver.HitchReduceFactor; - this.mouseDragVect.x = this.mouseDragVect.x * -1f; - this.desiredDolly += this.mouseDragVect * this.config.dollyRateMouseDrag; - this.mouseDragVect = Vector2.zero; + if (Event.current.type == EventType.MouseDrag && Event.current.button == 2) + { + this.mouseDragVect = Event.current.delta; + Event.current.Use(); + } + float num = 0f; + if (Event.current.type == EventType.ScrollWheel) + { + float num2 = num; + Vector2 delta = Event.current.delta; + num = (float)(num2 - delta.y * 0.34999999403953552); + PlayerKnowledgeDatabase.KnowledgeDemonstrated(ConceptDefOf.CameraZoom, KnowledgeAmount.TinyInteraction); + } + if (KeyBindingDefOf.MapZoomIn.KeyDownEvent) + { + num = (float)(num + 4.0); + PlayerKnowledgeDatabase.KnowledgeDemonstrated(ConceptDefOf.CameraZoom, KnowledgeAmount.SmallInteraction); + } + if (KeyBindingDefOf.MapZoomOut.KeyDownEvent) + { + num = (float)(num - 4.0); + PlayerKnowledgeDatabase.KnowledgeDemonstrated(ConceptDefOf.CameraZoom, KnowledgeAmount.SmallInteraction); + } + this.desiredSize -= (float)(num * 2.5999999046325684 * this.rootSize / 35.0); + if (this.desiredSize < 11.0) + { + this.desiredSize = 11f; + } + if (this.desiredSize > 60.0) + { + this.desiredSize = 60f; + } + this.desiredDolly = Vector3.zero; + if (KeyBindingDefOf.MapDollyLeft.IsDown) + { + this.desiredDolly.x = (float)(0.0 - this.config.dollyRateKeys); + } + if (KeyBindingDefOf.MapDollyRight.IsDown) + { + this.desiredDolly.x = this.config.dollyRateKeys; + } + if (KeyBindingDefOf.MapDollyUp.IsDown) + { + this.desiredDolly.y = this.config.dollyRateKeys; + } + if (KeyBindingDefOf.MapDollyDown.IsDown) + { + this.desiredDolly.y = (float)(0.0 - this.config.dollyRateKeys); + } + if (this.mouseDragVect != Vector2.zero) + { + this.mouseDragVect *= CameraDriver.HitchReduceFactor; + this.mouseDragVect.x *= -1f; + this.desiredDolly += this.mouseDragVect * this.config.dollyRateMouseDrag; + this.mouseDragVect = Vector2.zero; + } } } } public void Update() { - if (LongEventHandler.ShouldWaitForEvent) - { - return; - } - if (Find.VisibleMap == null) - { - return; - } - Vector2 lhs = this.CalculateCurInputDollyVect(); - if (lhs != Vector2.zero) + if (!LongEventHandler.ShouldWaitForEvent && Find.VisibleMap != null) { - float d = (this.rootSize - 11f) / 49f * 0.7f + 0.3f; - this.velocity = new Vector3(lhs.x, 0f, lhs.y) * d; - PlayerKnowledgeDatabase.KnowledgeDemonstrated(ConceptDefOf.CameraDolly, KnowledgeAmount.FrameInteraction); - } - if (!this.AnythingPreventsCameraMotion) - { - float d2 = Time.deltaTime * CameraDriver.HitchReduceFactor; - this.rootPos += this.velocity * d2 * this.config.moveSpeedScale; - if (this.rootPos.x > (float)Find.VisibleMap.Size.x + -2f) + Vector2 lhs = this.CalculateCurInputDollyVect(); + if (lhs != Vector2.zero) { - this.rootPos.x = (float)Find.VisibleMap.Size.x + -2f; + float d = (float)((this.rootSize - 11.0) / 49.0 * 0.699999988079071 + 0.30000001192092896); + this.velocity = new Vector3(lhs.x, 0f, lhs.y) * d; + PlayerKnowledgeDatabase.KnowledgeDemonstrated(ConceptDefOf.CameraDolly, KnowledgeAmount.FrameInteraction); } - if (this.rootPos.z > (float)Find.VisibleMap.Size.z + -2f) + if (!this.AnythingPreventsCameraMotion) { - this.rootPos.z = (float)Find.VisibleMap.Size.z + -2f; - } - if (this.rootPos.x < 2f) - { - this.rootPos.x = 2f; + float d2 = Time.deltaTime * CameraDriver.HitchReduceFactor; + this.rootPos += this.velocity * d2 * this.config.moveSpeedScale; + float x = this.rootPos.x; + IntVec3 size = Find.VisibleMap.Size; + if (x > (float)size.x + -2.0) + { + ref Vector3 val = ref this.rootPos; + IntVec3 size2 = Find.VisibleMap.Size; + val.x = (float)((float)size2.x + -2.0); + } + float z = this.rootPos.z; + IntVec3 size3 = Find.VisibleMap.Size; + if (z > (float)size3.z + -2.0) + { + ref Vector3 val2 = ref this.rootPos; + IntVec3 size4 = Find.VisibleMap.Size; + val2.z = (float)((float)size4.z + -2.0); + } + if (this.rootPos.x < 2.0) + { + this.rootPos.x = 2f; + } + if (this.rootPos.z < 2.0) + { + this.rootPos.z = 2f; + } } - if (this.rootPos.z < 2f) + if (this.velocity != Vector3.zero) { - this.rootPos.z = 2f; + this.velocity *= this.config.camSpeedDecayFactor; + if (this.velocity.magnitude < 0.10000000149011612) + { + this.velocity = Vector3.zero; + } } - } - if (this.velocity != Vector3.zero) - { - this.velocity *= this.config.camSpeedDecayFactor; - if (this.velocity.magnitude < 0.1f) + float num = this.desiredSize - this.rootSize; + this.rootSize += (float)(num * 0.40000000596046448); + this.shaker.Update(); + this.ApplyPositionToGameObject(); + if (Find.VisibleMap != null) { - this.velocity = Vector3.zero; + RememberedCameraPos rememberedCameraPos = Find.VisibleMap.rememberedCameraPos; + rememberedCameraPos.rootPos = this.rootPos; + rememberedCameraPos.rootSize = this.rootSize; } } - float num = this.desiredSize - this.rootSize; - this.rootSize += num * 0.4f; - this.shaker.Update(); - this.ApplyPositionToGameObject(); - if (Find.VisibleMap != null) - { - RememberedCameraPos rememberedCameraPos = Find.VisibleMap.rememberedCameraPos; - rememberedCameraPos.rootPos = this.rootPos; - rememberedCameraPos.rootSize = this.rootSize; - } } private void ApplyPositionToGameObject() { - this.rootPos.y = 15f + (this.rootSize - 11f) / 49f * 50f; + this.rootPos.y = (float)(15.0 + (this.rootSize - 11.0) / 49.0 * 50.0); this.MyCamera.orthographicSize = this.rootSize; this.MyCamera.transform.position = this.rootPos + this.shaker.ShakeOffset; Vector3 position = base.transform.position; @@ -384,25 +372,25 @@ private Vector2 CalculateCurInputDollyVect() if (!rect.Contains(point) && !rect3.Contains(point) && !rect2.Contains(point) && !rect4.Contains(point)) { Vector2 b = new Vector2(0f, 0f); - if (mousePositionOnUI.x >= 0f && mousePositionOnUI.x < 20f) + if (mousePositionOnUI.x >= 0.0 && mousePositionOnUI.x < 20.0) { b.x -= this.config.dollyRateScreenEdge; } - if (mousePositionOnUI.x <= (float)UI.screenWidth && mousePositionOnUI.x > (float)UI.screenWidth - 20f) + if (mousePositionOnUI.x <= (float)UI.screenWidth && mousePositionOnUI.x > (float)UI.screenWidth - 20.0) { b.x += this.config.dollyRateScreenEdge; } - if (mousePositionOnUI.y <= (float)UI.screenHeight && mousePositionOnUI.y > (float)UI.screenHeight - 20f) + if (mousePositionOnUI.y <= (float)UI.screenHeight && mousePositionOnUI.y > (float)UI.screenHeight - 20.0) { b.y += this.config.dollyRateScreenEdge; } - if (mousePositionOnUI.y >= 0f && mousePositionOnUI.y < this.ScreenDollyEdgeWidthBottom) + if (mousePositionOnUI.y >= 0.0 && mousePositionOnUI.y < this.ScreenDollyEdgeWidthBottom) { - if (this.mouseTouchingScreenBottomEdgeStartTime < 0f) + if (this.mouseTouchingScreenBottomEdgeStartTime < 0.0) { this.mouseTouchingScreenBottomEdgeStartTime = Time.realtimeSinceStartup; } - if (Time.realtimeSinceStartup - this.mouseTouchingScreenBottomEdgeStartTime >= 0.28f) + if (Time.realtimeSinceStartup - this.mouseTouchingScreenBottomEdgeStartTime >= 0.2800000011920929) { b.y -= this.config.dollyRateScreenEdge; } diff --git a/Assembly-CSharp/Verse/CameraJumper.cs b/Assembly-CSharp/Verse/CameraJumper.cs index 81f22f43d..7c5e82a17 100644 --- a/Assembly-CSharp/Verse/CameraJumper.cs +++ b/Assembly-CSharp/Verse/CameraJumper.cs @@ -1,6 +1,5 @@ using RimWorld; using RimWorld.Planet; -using System; using Verse.Sound; namespace Verse @@ -9,38 +8,32 @@ public static class CameraJumper { public static void TryJumpAndSelect(GlobalTargetInfo target) { - if (!target.IsValid) + if (target.IsValid) { - return; + CameraJumper.TryJump(target); + CameraJumper.TrySelect(target); } - CameraJumper.TryJump(target); - CameraJumper.TrySelect(target); } public static void TrySelect(GlobalTargetInfo target) { - if (!target.IsValid) + if (target.IsValid) { - return; - } - target = CameraJumper.GetAdjustedTarget(target); - if (target.HasThing) - { - CameraJumper.TrySelectInternal(target.Thing); - } - else if (target.HasWorldObject) - { - CameraJumper.TrySelectInternal(target.WorldObject); + target = CameraJumper.GetAdjustedTarget(target); + if (target.HasThing) + { + CameraJumper.TrySelectInternal(target.Thing); + } + else if (target.HasWorldObject) + { + CameraJumper.TrySelectInternal(target.WorldObject); + } } } private static void TrySelectInternal(Thing thing) { - if (Current.ProgramState != ProgramState.Playing) - { - return; - } - if (thing.Spawned) + if (Current.ProgramState == ProgramState.Playing && thing.Spawned) { bool flag = CameraJumper.TryHideWorld(); bool flag2 = false; @@ -64,11 +57,7 @@ private static void TrySelectInternal(Thing thing) private static void TrySelectInternal(WorldObject worldObject) { - if (Find.World == null) - { - return; - } - if (worldObject.Spawned) + if (Find.World != null && worldObject.Spawned) { CameraJumper.TryShowWorld(); Find.WorldSelector.ClearSelection(); @@ -78,26 +67,25 @@ private static void TrySelectInternal(WorldObject worldObject) public static void TryJump(GlobalTargetInfo target) { - if (!target.IsValid) - { - return; - } - target = CameraJumper.GetAdjustedTarget(target); - if (target.HasThing) - { - CameraJumper.TryJumpInternal(target.Thing); - } - else if (target.HasWorldObject) - { - CameraJumper.TryJumpInternal(target.WorldObject); - } - else if (target.Cell.IsValid) + if (target.IsValid) { - CameraJumper.TryJumpInternal(target.Cell, target.Map); - } - else - { - CameraJumper.TryJumpInternal(target.Tile); + target = CameraJumper.GetAdjustedTarget(target); + if (target.HasThing) + { + CameraJumper.TryJumpInternal(target.Thing); + } + else if (target.HasWorldObject) + { + CameraJumper.TryJumpInternal(target.WorldObject); + } + else if (target.Cell.IsValid) + { + CameraJumper.TryJumpInternal(target.Cell, target.Map); + } + else + { + CameraJumper.TryJumpInternal(target.Tile); + } } } @@ -113,78 +101,58 @@ public static void TryJump(int tile) private static void TryJumpInternal(Thing thing) { - if (Current.ProgramState != ProgramState.Playing) - { - return; - } - Map mapHeld = thing.MapHeld; - if (mapHeld != null && thing.PositionHeld.IsValid && thing.PositionHeld.InBounds(mapHeld)) + if (Current.ProgramState == ProgramState.Playing) { - bool flag = CameraJumper.TryHideWorld(); - if (Current.Game.VisibleMap != mapHeld) + Map mapHeld = thing.MapHeld; + if (mapHeld != null && thing.PositionHeld.IsValid && thing.PositionHeld.InBounds(mapHeld)) { - Current.Game.VisibleMap = mapHeld; - if (!flag) + bool flag = CameraJumper.TryHideWorld(); + if (Current.Game.VisibleMap != mapHeld) { - SoundDefOf.MapSelected.PlayOneShotOnCamera(null); + Current.Game.VisibleMap = mapHeld; + if (!flag) + { + SoundDefOf.MapSelected.PlayOneShotOnCamera(null); + } } + Find.CameraDriver.JumpToVisibleMapLoc(thing.PositionHeld); } - Find.CameraDriver.JumpToVisibleMapLoc(thing.PositionHeld); } } private static void TryJumpInternal(IntVec3 cell, Map map) { - if (Current.ProgramState != ProgramState.Playing) - { - return; - } - if (!cell.IsValid) - { - return; - } - if (map == null || !Find.Maps.Contains(map)) + if (Current.ProgramState == ProgramState.Playing && cell.IsValid && map != null && Find.Maps.Contains(map)) { - return; - } - bool flag = CameraJumper.TryHideWorld(); - if (Current.Game.VisibleMap != map) - { - Current.Game.VisibleMap = map; - if (!flag) + bool flag = CameraJumper.TryHideWorld(); + if (Current.Game.VisibleMap != map) { - SoundDefOf.MapSelected.PlayOneShotOnCamera(null); + Current.Game.VisibleMap = map; + if (!flag) + { + SoundDefOf.MapSelected.PlayOneShotOnCamera(null); + } } + Find.CameraDriver.JumpToVisibleMapLoc(cell); } - Find.CameraDriver.JumpToVisibleMapLoc(cell); } private static void TryJumpInternal(WorldObject worldObject) { - if (Find.World == null) - { - return; - } - if (worldObject.Tile < 0) + if (Find.World != null && worldObject.Tile >= 0) { - return; + CameraJumper.TryShowWorld(); + Find.WorldCameraDriver.JumpTo(worldObject.Tile); } - CameraJumper.TryShowWorld(); - Find.WorldCameraDriver.JumpTo(worldObject.Tile); } private static void TryJumpInternal(int tile) { - if (Find.World == null) - { - return; - } - if (tile < 0) + if (Find.World != null && tile >= 0) { - return; + CameraJumper.TryShowWorld(); + Find.WorldCameraDriver.JumpTo(tile); } - CameraJumper.TryShowWorld(); - Find.WorldCameraDriver.JumpTo(tile); } public static GlobalTargetInfo GetAdjustedTarget(GlobalTargetInfo target) @@ -222,22 +190,25 @@ public static GlobalTargetInfo GetAdjustedTarget(GlobalTargetInfo target) return new GlobalTargetInfo(thing.Tile); } } - else if (target.Cell.IsValid && target.Tile >= 0 && target.Map != null && !Find.Maps.Contains(target.Map)) + else { - MapParent parent = target.Map.info.parent; - if (parent != null && parent.Spawned) + if (target.Cell.IsValid && target.Tile >= 0 && target.Map != null && !Find.Maps.Contains(target.Map)) { - return parent; + MapParent parent = target.Map.info.parent; + if (parent != null && parent.Spawned) + { + return (WorldObject)parent; + } + if (parent != null && parent.Tile >= 0) + { + return new GlobalTargetInfo(target.Map.Tile); + } + return GlobalTargetInfo.Invalid; } - if (parent != null && parent.Tile >= 0) + if (target.HasWorldObject && !target.WorldObject.Spawned && target.WorldObject.Tile >= 0) { - return new GlobalTargetInfo(target.Map.Tile); + return new GlobalTargetInfo(target.WorldObject.Tile); } - return GlobalTargetInfo.Invalid; - } - else if (target.HasWorldObject && !target.WorldObject.Spawned && target.WorldObject.Tile >= 0) - { - return new GlobalTargetInfo(target.WorldObject.Tile); } return target; } @@ -245,15 +216,15 @@ public static GlobalTargetInfo GetAdjustedTarget(GlobalTargetInfo target) public static GlobalTargetInfo GetWorldTarget(GlobalTargetInfo target) { GlobalTargetInfo adjustedTarget = CameraJumper.GetAdjustedTarget(target); - if (!adjustedTarget.IsValid) + if (adjustedTarget.IsValid) { - return GlobalTargetInfo.Invalid; - } - if (adjustedTarget.IsWorldTarget) - { - return adjustedTarget; + if (adjustedTarget.IsWorldTarget) + { + return adjustedTarget; + } + return CameraJumper.GetWorldTargetOfMap(adjustedTarget.Map); } - return CameraJumper.GetWorldTargetOfMap(adjustedTarget.Map); + return GlobalTargetInfo.Invalid; } public static GlobalTargetInfo GetWorldTargetOfMap(Map map) @@ -264,7 +235,7 @@ public static GlobalTargetInfo GetWorldTargetOfMap(Map map) } if (map.info.parent != null && map.info.parent.Spawned) { - return map.info.parent; + return (WorldObject)map.info.parent; } if (map.info.parent != null && map.info.parent.Tile >= 0) { @@ -283,7 +254,7 @@ public static bool TryHideWorld() { return false; } - if (Find.World.renderer.wantedMode != WorldRenderMode.None) + if (Find.World.renderer.wantedMode != 0) { Find.World.renderer.wantedMode = WorldRenderMode.None; SoundDefOf.TabClose.PlayOneShotOnCamera(null); diff --git a/Assembly-CSharp/Verse/CameraMapConfig.cs b/Assembly-CSharp/Verse/CameraMapConfig.cs index b4a3aa330..c8be523e5 100644 --- a/Assembly-CSharp/Verse/CameraMapConfig.cs +++ b/Assembly-CSharp/Verse/CameraMapConfig.cs @@ -1,5 +1,3 @@ -using System; - namespace Verse { public abstract class CameraMapConfig diff --git a/Assembly-CSharp/Verse/CameraMapConfig_ContinuousPan.cs b/Assembly-CSharp/Verse/CameraMapConfig_ContinuousPan.cs index 0474e90e2..02788b71e 100644 --- a/Assembly-CSharp/Verse/CameraMapConfig_ContinuousPan.cs +++ b/Assembly-CSharp/Verse/CameraMapConfig_ContinuousPan.cs @@ -1,16 +1,14 @@ -using System; - namespace Verse { public class CameraMapConfig_ContinuousPan : CameraMapConfig { public CameraMapConfig_ContinuousPan() { - this.dollyRateKeys = 10f; - this.dollyRateMouseDrag = 4f; - this.dollyRateScreenEdge = 5f; - this.camSpeedDecayFactor = 1f; - this.moveSpeedScale = 1f; + base.dollyRateKeys = 10f; + base.dollyRateMouseDrag = 4f; + base.dollyRateScreenEdge = 5f; + base.camSpeedDecayFactor = 1f; + base.moveSpeedScale = 1f; } } } diff --git a/Assembly-CSharp/Verse/CameraMapConfig_Normal.cs b/Assembly-CSharp/Verse/CameraMapConfig_Normal.cs index 9ca5fdd68..a9072c544 100644 --- a/Assembly-CSharp/Verse/CameraMapConfig_Normal.cs +++ b/Assembly-CSharp/Verse/CameraMapConfig_Normal.cs @@ -1,16 +1,14 @@ -using System; - namespace Verse { public class CameraMapConfig_Normal : CameraMapConfig { public CameraMapConfig_Normal() { - this.dollyRateKeys = 50f; - this.dollyRateMouseDrag = 6.5f; - this.dollyRateScreenEdge = 35f; - this.camSpeedDecayFactor = 0.85f; - this.moveSpeedScale = 2f; + base.dollyRateKeys = 50f; + base.dollyRateMouseDrag = 6.5f; + base.dollyRateScreenEdge = 35f; + base.camSpeedDecayFactor = 0.85f; + base.moveSpeedScale = 2f; } } } diff --git a/Assembly-CSharp/Verse/CameraShaker.cs b/Assembly-CSharp/Verse/CameraShaker.cs index 305434495..031b46078 100644 --- a/Assembly-CSharp/Verse/CameraShaker.cs +++ b/Assembly-CSharp/Verse/CameraShaker.cs @@ -1,4 +1,3 @@ -using System; using UnityEngine; namespace Verse @@ -17,9 +16,9 @@ public Vector3 ShakeOffset { get { - float x = Mathf.Sin(Time.realtimeSinceStartup * 24f) * this.curShakeMag; - float y = Mathf.Sin(Time.realtimeSinceStartup * 24f * 1.05f) * this.curShakeMag; - float z = Mathf.Sin(Time.realtimeSinceStartup * 24f * 1.1f) * this.curShakeMag; + float x = Mathf.Sin((float)(Time.realtimeSinceStartup * 24.0)) * this.curShakeMag; + float y = Mathf.Sin((float)(Time.realtimeSinceStartup * 24.0 * 1.0499999523162842)) * this.curShakeMag; + float z = Mathf.Sin((float)(Time.realtimeSinceStartup * 24.0 * 1.1000000238418579)) * this.curShakeMag; return new Vector3(x, y, z); } } @@ -27,7 +26,7 @@ public Vector3 ShakeOffset public void DoShake(float mag) { this.curShakeMag += mag; - if (this.curShakeMag > 0.1f) + if (this.curShakeMag > 0.10000000149011612) { this.curShakeMag = 0.1f; } @@ -35,8 +34,8 @@ public void DoShake(float mag) public void Update() { - this.curShakeMag -= 0.5f * RealTime.realDeltaTime; - if (this.curShakeMag < 0f) + this.curShakeMag -= (float)(0.5 * RealTime.realDeltaTime); + if (this.curShakeMag < 0.0) { this.curShakeMag = 0f; } diff --git a/Assembly-CSharp/Verse/CameraSwooper.cs b/Assembly-CSharp/Verse/CameraSwooper.cs index 01e951e2b..345edabc9 100644 --- a/Assembly-CSharp/Verse/CameraSwooper.cs +++ b/Assembly-CSharp/Verse/CameraSwooper.cs @@ -44,7 +44,7 @@ public void Update() if (this.TimeSinceSwoopStart >= this.TotalSwoopTime) { this.Swooping = false; - if (this.SwoopFinishedCallback != null) + if ((object)this.SwoopFinishedCallback != null) { this.SwoopFinishedCallback(); } @@ -64,7 +64,7 @@ public void OffsetCameraFrom(GameObject camObj, Vector3 basePos, float baseSize) num = this.TimeSinceSwoopStart / this.TotalSwoopTime; if (this.SwoopingTo) { - num = 1f - num; + num = (float)(1.0 - num); } num = (float)Math.Pow((double)num, 1.7000000476837158); } diff --git a/Assembly-CSharp/Verse/CameraZoomRange.cs b/Assembly-CSharp/Verse/CameraZoomRange.cs index 0eaf8f58d..236dbce93 100644 --- a/Assembly-CSharp/Verse/CameraZoomRange.cs +++ b/Assembly-CSharp/Verse/CameraZoomRange.cs @@ -1,13 +1,11 @@ -using System; - namespace Verse { public enum CameraZoomRange : byte { - Closest, - Close, - Middle, - Far, - Furthest + Closest = 0, + Close = 1, + Middle = 2, + Far = 3, + Furthest = 4 } } diff --git a/Assembly-CSharp/Verse/CellBoolDrawer.cs b/Assembly-CSharp/Verse/CellBoolDrawer.cs index 60a56cdc6..f849a8cff 100644 --- a/Assembly-CSharp/Verse/CellBoolDrawer.cs +++ b/Assembly-CSharp/Verse/CellBoolDrawer.cs @@ -1,4 +1,3 @@ -using System; using System.Collections.Generic; using UnityEngine; @@ -155,12 +154,19 @@ private void FinalizeWorkingDataIntoMesh(Mesh mesh) private void CreateMaterialIfNeeded(bool careAboutVertexColors) { - if (this.material == null || this.materialCaresAboutVertexColors != careAboutVertexColors) - { - this.material = SolidColorMaterials.SimpleSolidColorMaterial(new Color(this.giver.Color.r, this.giver.Color.g, this.giver.Color.b, this.opacity * this.giver.Color.a), careAboutVertexColors); - this.materialCaresAboutVertexColors = careAboutVertexColors; - this.material.renderQueue = 3600; - } + if (!((Object)this.material == (Object)null) && this.materialCaresAboutVertexColors == careAboutVertexColors) + return; + Color color = this.giver.Color; + float r = color.r; + Color color2 = this.giver.Color; + float g = color2.g; + Color color3 = this.giver.Color; + float b = color3.b; + float num = this.opacity; + Color color4 = this.giver.Color; + this.material = SolidColorMaterials.SimpleSolidColorMaterial(new Color(r, g, b, num * color4.a), careAboutVertexColors); + this.materialCaresAboutVertexColors = careAboutVertexColors; + this.material.renderQueue = 3600; } } } diff --git a/Assembly-CSharp/Verse/CellFinder.cs b/Assembly-CSharp/Verse/CellFinder.cs index 3247cb002..407a66371 100644 --- a/Assembly-CSharp/Verse/CellFinder.cs +++ b/Assembly-CSharp/Verse/CellFinder.cs @@ -1,7 +1,6 @@ using RimWorld; using System; using System.Collections.Generic; -using System.Diagnostics; using System.Linq; using UnityEngine; using Verse.AI; @@ -44,35 +43,42 @@ public static class CellFinder public static IntVec3 RandomCell(Map map) { - return new IntVec3(Rand.Range(0, map.Size.x), 0, Rand.Range(0, map.Size.z)); + IntVec3 size = map.Size; + int newX = Rand.Range(0, size.x); + IntVec3 size2 = map.Size; + return new IntVec3(newX, 0, Rand.Range(0, size2.z)); } public static IntVec3 RandomEdgeCell(Map map) { IntVec3 result = default(IntVec3); - if (Rand.Value < 0.5f) + if (Rand.Value < 0.5) { - if (Rand.Value < 0.5f) + if (Rand.Value < 0.5) { result.x = 0; } else { - result.x = map.Size.x - 1; + IntVec3 size = map.Size; + result.x = size.x - 1; } - result.z = Rand.Range(0, map.Size.z); + IntVec3 size2 = map.Size; + result.z = Rand.Range(0, size2.z); } else { - if (Rand.Value < 0.5f) + if (Rand.Value < 0.5) { result.z = 0; } else { - result.z = map.Size.z - 1; + IntVec3 size3 = map.Size; + result.z = size3.z - 1; } - result.x = Rand.Range(0, map.Size.x); + IntVec3 size4 = map.Size; + result.x = Rand.Range(0, size4.x); } return result; } @@ -81,32 +87,48 @@ public static IntVec3 RandomEdgeCell(Rot4 dir, Map map) { if (dir == Rot4.North) { - return new IntVec3(Rand.Range(0, map.Size.x), 0, map.Size.z - 1); + IntVec3 size = map.Size; + int newX = Rand.Range(0, size.x); + IntVec3 size2 = map.Size; + return new IntVec3(newX, 0, size2.z - 1); } if (dir == Rot4.South) { - return new IntVec3(Rand.Range(0, map.Size.x), 0, 0); + IntVec3 size3 = map.Size; + return new IntVec3(Rand.Range(0, size3.x), 0, 0); } if (dir == Rot4.West) { - return new IntVec3(0, 0, Rand.Range(0, map.Size.z)); + IntVec3 size4 = map.Size; + return new IntVec3(0, 0, Rand.Range(0, size4.z)); } if (dir == Rot4.East) { - return new IntVec3(map.Size.x - 1, 0, Rand.Range(0, map.Size.z)); + IntVec3 size5 = map.Size; + int newX2 = size5.x - 1; + IntVec3 size6 = map.Size; + return new IntVec3(newX2, 0, Rand.Range(0, size6.z)); } return IntVec3.Invalid; } public static IntVec3 RandomNotEdgeCell(int minEdgeDistance, Map map) { - if (minEdgeDistance > map.Size.x / 2 || minEdgeDistance > map.Size.z / 2) - { - return IntVec3.Invalid; - } - int newX = Rand.Range(minEdgeDistance, map.Size.x - minEdgeDistance); - int newZ = Rand.Range(minEdgeDistance, map.Size.z - minEdgeDistance); - return new IntVec3(newX, 0, newZ); + IntVec3 size = map.Size; + if (minEdgeDistance <= size.x / 2) + { + IntVec3 size2 = map.Size; + if (minEdgeDistance > size2.z / 2) + goto IL_002c; + IntVec3 size3 = map.Size; + int newX = Rand.Range(minEdgeDistance, size3.x - minEdgeDistance); + IntVec3 size4 = map.Size; + int newZ = Rand.Range(minEdgeDistance, size4.z - minEdgeDistance); + return new IntVec3(newX, 0, newZ); + } + goto IL_002c; + IL_002c: + return IntVec3.Invalid; } public static bool TryFindClosestRegionWith(Region rootReg, TraverseParms traverseParms, Predicate validator, int maxRegions, out Region result, RegionType traversableRegionTypes = RegionType.Set_Passable) @@ -117,7 +139,7 @@ public static bool TryFindClosestRegionWith(Region rootReg, TraverseParms traver return false; } Region localResult = null; - RegionTraverser.BreadthFirstTraverse(rootReg, (Region from, Region r) => r.Allows(traverseParms, true), delegate(Region r) + RegionTraverser.BreadthFirstTraverse(rootReg, (RegionEntryPredicate)((Region from, Region r) => r.Allows(traverseParms, true)), (RegionProcessor)delegate(Region r) { if (validator(r)) { @@ -141,12 +163,24 @@ public static Region RandomRegionNear(Region root, int maxRegions, TraverseParms return root; } CellFinder.workingRegions.Clear(); - RegionTraverser.BreadthFirstTraverse(root, (Region from, Region r) => (validator == null || validator(r)) && r.Allows(traverseParms, true) && (pawnToAllow == null || !r.IsForbiddenEntirely(pawnToAllow)), delegate(Region r) + RegionTraverser.BreadthFirstTraverse(root, (RegionEntryPredicate)delegate(Region from, Region r) + { + int result2; + if (((object)validator == null || validator(r)) && r.Allows(traverseParms, true)) + { + result2 = ((pawnToAllow == null || !r.IsForbiddenEntirely(pawnToAllow)) ? 1 : 0); + goto IL_004e; + } + result2 = 0; + goto IL_004e; + IL_004e: + return (byte)result2 != 0; + }, (RegionProcessor)delegate(Region r) { CellFinder.workingRegions.Add(r); return false; }, maxRegions, traversableRegionTypes); - Region result = CellFinder.workingRegions.RandomElementByWeight((Region r) => (float)r.CellCount); + Region result = CellFinder.workingRegions.RandomElementByWeight((Func)((Region r) => (float)r.CellCount)); CellFinder.workingRegions.Clear(); return result; } @@ -156,19 +190,35 @@ public static void AllRegionsNear(List results, Region root, int maxRegi if (results == null) { Log.ErrorOnce("Attempted to call AllRegionsNear with an invalid results list", 60733193); - return; } - results.Clear(); - if (root == null) + else { - Log.ErrorOnce("Attempted to call AllRegionsNear with an invalid root", 9107839); - return; + results.Clear(); + if (root == null) + { + Log.ErrorOnce("Attempted to call AllRegionsNear with an invalid root", 9107839); + } + else + { + RegionTraverser.BreadthFirstTraverse(root, (RegionEntryPredicate)delegate(Region from, Region r) + { + int result; + if (((object)validator == null || validator(r)) && r.Allows(traverseParms, true)) + { + result = ((pawnToAllow == null || !r.IsForbiddenEntirely(pawnToAllow)) ? 1 : 0); + goto IL_004e; + } + result = 0; + goto IL_004e; + IL_004e: + return (byte)result != 0; + }, (RegionProcessor)delegate(Region r) + { + results.Add(r); + return false; + }, maxRegions, traversableRegionTypes); + } } - RegionTraverser.BreadthFirstTraverse(root, (Region from, Region r) => (validator == null || validator(r)) && r.Allows(traverseParms, true) && (pawnToAllow == null || !r.IsForbiddenEntirely(pawnToAllow)), delegate(Region r) - { - results.Add(r); - return false; - }, maxRegions, traversableRegionTypes); } public static bool TryFindRandomReachableCellNear(IntVec3 root, Map map, float radius, TraverseParms traverseParms, Predicate cellValidator, Predicate regionValidator, out IntVec3 result, int maxRegions = 999999) @@ -187,15 +237,15 @@ public static bool TryFindRandomReachableCellNear(IntVec3 root, Map map, float r } CellFinder.workingRegions.Clear(); float radSquared = radius * radius; - RegionTraverser.BreadthFirstTraverse(region, (Region from, Region r) => r.Allows(traverseParms, true) && (radius > 1000f || r.extentsClose.ClosestDistSquaredTo(root) <= radSquared) && (regionValidator == null || regionValidator(r)), delegate(Region r) + RegionTraverser.BreadthFirstTraverse(region, (RegionEntryPredicate)((Region from, Region r) => r.Allows(traverseParms, true) && (radius > 1000.0 || r.extentsClose.ClosestDistSquaredTo(root) <= radSquared) && ((object)regionValidator == null || regionValidator(r))), (RegionProcessor)delegate(Region r) { CellFinder.workingRegions.Add(r); return false; }, maxRegions, RegionType.Set_Passable); while (CellFinder.workingRegions.Count > 0) { - Region region2 = CellFinder.workingRegions.RandomElementByWeight((Region r) => (float)r.CellCount); - if (region2.TryFindRandomCellInRegion((IntVec3 c) => (float)(c - root).LengthHorizontalSquared <= radSquared && cellValidator(c), out result)) + Region region2 = CellFinder.workingRegions.RandomElementByWeight((Func)((Region r) => (float)r.CellCount)); + if (region2.TryFindRandomCellInRegion((Predicate)((IntVec3 c) => (float)(c - root).LengthHorizontalSquared <= radSquared && cellValidator(c)), out result)) { CellFinder.workingRegions.Clear(); return true; @@ -209,7 +259,7 @@ public static bool TryFindRandomReachableCellNear(IntVec3 root, Map map, float r public static IntVec3 RandomClosewalkCellNear(IntVec3 root, Map map, int radius, Predicate extraValidator = null) { - IntVec3 result; + IntVec3 result = default(IntVec3); if (CellFinder.TryRandomClosewalkCellNear(root, map, radius, out result, extraValidator)) { return result; @@ -219,13 +269,13 @@ public static IntVec3 RandomClosewalkCellNear(IntVec3 root, Map map, int radius, public static bool TryRandomClosewalkCellNear(IntVec3 root, Map map, int radius, out IntVec3 result, Predicate extraValidator = null) { - return CellFinder.TryFindRandomReachableCellNear(root, map, (float)radius, TraverseParms.For(TraverseMode.NoPassClosedDoors, Danger.Deadly, false), (IntVec3 c) => c.Standable(map) && (extraValidator == null || extraValidator(c)), null, out result, 999999); + return CellFinder.TryFindRandomReachableCellNear(root, map, (float)radius, TraverseParms.For(TraverseMode.NoPassClosedDoors, Danger.Deadly, false), (Predicate)((IntVec3 c) => c.Standable(map) && ((object)extraValidator == null || extraValidator(c))), (Predicate)null, out result, 999999); } public static IntVec3 RandomClosewalkCellNearNotForbidden(IntVec3 root, Map map, int radius, Pawn pawn) { - IntVec3 result; - if (!CellFinder.TryFindRandomReachableCellNear(root, map, (float)radius, TraverseParms.For(TraverseMode.NoPassClosedDoors, Danger.Deadly, false), (IntVec3 c) => !c.IsForbidden(pawn) && c.Standable(map), null, out result, 999999)) + IntVec3 result = default(IntVec3); + if (!CellFinder.TryFindRandomReachableCellNear(root, map, (float)radius, TraverseParms.For(TraverseMode.NoPassClosedDoors, Danger.Deadly, false), (Predicate)((IntVec3 c) => !c.IsForbidden(pawn) && c.Standable(map)), (Predicate)null, out result, 999999)) { return CellFinder.RandomClosewalkCellNear(root, map, radius, null); } @@ -234,24 +284,30 @@ public static IntVec3 RandomClosewalkCellNearNotForbidden(IntVec3 root, Map map, public static bool TryFindRandomCellInRegion(this Region reg, Predicate validator, out IntVec3 result) { - for (int i = 0; i < 10; i++) + int num = 0; + while (num < 10) { result = reg.RandomCell; - if (validator == null || validator(result)) + if ((object)validator != null && !validator(result)) { - return true; + num++; + continue; } + return true; } CellFinder.workingCells.Clear(); CellFinder.workingCells.AddRange(reg.Cells); - CellFinder.workingCells.Shuffle(); - for (int j = 0; j < CellFinder.workingCells.Count; j++) + CellFinder.workingCells.Shuffle(); + int num2 = 0; + while (num2 < CellFinder.workingCells.Count) { - result = CellFinder.workingCells[j]; - if (validator == null || validator(result)) + result = CellFinder.workingCells[num2]; + if ((object)validator != null && !validator(result)) { - return true; + num2++; + continue; } + return true; } result = reg.RandomCell; return false; @@ -271,57 +327,59 @@ public static bool TryFindRandomCellNear(IntVec3 root, Map map, int squareRadius { num3 = 0; } - if (num2 > map.Size.x) + int num5 = num2; + IntVec3 size = map.Size; + if (num5 > size.x) { - num2 = map.Size.x; + IntVec3 size2 = map.Size; + num2 = size2.x; } - if (num4 > map.Size.z) + int num6 = num4; + IntVec3 size3 = map.Size; + if (num6 > size3.z) { - num4 = map.Size.z; + IntVec3 size4 = map.Size; + num4 = size4.z; } - int num5 = 0; - IntVec3 intVec; + int num7 = 0; while (true) { - intVec = new IntVec3(Rand.RangeInclusive(num, num2), 0, Rand.RangeInclusive(num3, num4)); - if (validator == null || validator(intVec)) + IntVec3 intVec = new IntVec3(Rand.RangeInclusive(num, num2), 0, Rand.RangeInclusive(num3, num4)); + if ((object)validator != null && !validator(intVec)) { - break; + if (DebugViewSettings.drawDestSearch) + { + map.debugDrawer.FlashCell(intVec, 0f, "inv"); + } + num7++; + if (num7 > 20) + break; + continue; } if (DebugViewSettings.drawDestSearch) { - map.debugDrawer.FlashCell(intVec, 0f, "inv"); - } - num5++; - if (num5 > 20) - { - goto Block_8; + map.debugDrawer.FlashCell(intVec, 0.5f, "found"); } + result = intVec; + return true; } - if (DebugViewSettings.drawDestSearch) - { - map.debugDrawer.FlashCell(intVec, 0.5f, "found"); - } - result = intVec; - return true; - Block_8: CellFinder.workingListX.Clear(); CellFinder.workingListZ.Clear(); - for (int i = num; i <= num2; i++) + for (int num8 = num; num8 <= num2; num8++) { - CellFinder.workingListX.Add(i); + CellFinder.workingListX.Add(num8); } - for (int j = num3; j <= num4; j++) + for (int num9 = num3; num9 <= num4; num9++) { - CellFinder.workingListZ.Add(j); + CellFinder.workingListZ.Add(num9); } - CellFinder.workingListX.Shuffle(); - CellFinder.workingListZ.Shuffle(); - for (int k = 0; k < CellFinder.workingListX.Count; k++) + CellFinder.workingListX.Shuffle(); + CellFinder.workingListZ.Shuffle(); + for (int i = 0; i < CellFinder.workingListX.Count; i++) { - for (int l = 0; l < CellFinder.workingListZ.Count; l++) + for (int j = 0; j < CellFinder.workingListZ.Count; j++) { - intVec = new IntVec3(CellFinder.workingListX[k], 0, CellFinder.workingListZ[l]); + IntVec3 intVec = new IntVec3(CellFinder.workingListX[i], 0, CellFinder.workingListZ[j]); if (validator(intVec)) { if (DebugViewSettings.drawDestSearch) @@ -343,7 +401,7 @@ public static bool TryFindRandomCellNear(IntVec3 root, Map map, int squareRadius public static bool TryFindRandomPawnExitCell(Pawn searcher, out IntVec3 result) { - return CellFinder.TryFindRandomEdgeCellWith((IntVec3 c) => !searcher.Map.roofGrid.Roofed(c) && c.Walkable(searcher.Map) && searcher.CanReach(c, PathEndMode.OnCell, Danger.Some, false, TraverseMode.ByPawn), searcher.Map, 0f, out result); + return CellFinder.TryFindRandomEdgeCellWith((Predicate)((IntVec3 c) => !searcher.Map.roofGrid.Roofed(c) && c.Walkable(searcher.Map) && searcher.CanReach(c, PathEndMode.OnCell, Danger.Some, false, TraverseMode.ByPawn)), searcher.Map, 0f, out result); } public static bool TryFindRandomEdgeCellWith(Predicate validator, Map map, float roadChance, out IntVec3 result) @@ -352,7 +410,7 @@ public static bool TryFindRandomEdgeCellWith(Predicate validator, Map m { bool flag = (from c in map.roadInfo.roadEdgeTiles where validator(c) - select c).TryRandomElement(out result); + select c).TryRandomElement(out result); if (flag) { return flag; @@ -370,12 +428,12 @@ where validator(c) { CellFinder.mapEdgeCellsSize = map.Size; CellFinder.mapEdgeCells = new List(); - foreach (IntVec3 current in CellRect.WholeMap(map).EdgeCells) + foreach (IntVec3 edgeCell in CellRect.WholeMap(map).EdgeCells) { - CellFinder.mapEdgeCells.Add(current); + CellFinder.mapEdgeCells.Add(edgeCell); } } - CellFinder.mapEdgeCells.Shuffle(); + CellFinder.mapEdgeCells.Shuffle(); for (int j = 0; j < CellFinder.mapEdgeCells.Count; j++) { try @@ -388,13 +446,7 @@ where validator(c) } catch (Exception ex) { - Log.Error(string.Concat(new object[] - { - "TryFindRandomEdgeCellWith exception validating ", - CellFinder.mapEdgeCells[j], - ": ", - ex.ToString() - })); + Log.Error("TryFindRandomEdgeCellWith exception validating " + CellFinder.mapEdgeCells[j] + ": " + ex.ToString()); } } result = IntVec3.Invalid; @@ -407,7 +459,7 @@ public static bool TryFindRandomEdgeCellWith(Predicate validator, Map m { bool flag = (from c in map.roadInfo.roadEdgeTiles where validator(c) && c.OnEdge(map, dir) - select c).TryRandomElement(out result); + select c).TryRandomElement(out result); if (flag) { return flag; @@ -426,36 +478,30 @@ where validator(c) && c.OnEdge(map, dir) { CellFinder.mapSingleEdgeCellsSize = map.Size; CellFinder.mapSingleEdgeCells[asInt] = new List(); - foreach (IntVec3 current in CellRect.WholeMap(map).GetEdgeCells(dir)) + foreach (IntVec3 edgeCell in CellRect.WholeMap(map).GetEdgeCells(dir)) { - CellFinder.mapSingleEdgeCells[asInt].Add(current); + CellFinder.mapSingleEdgeCells[asInt].Add(edgeCell); } } List list = CellFinder.mapSingleEdgeCells[asInt]; - list.Shuffle(); - int j = 0; + list.Shuffle(); + int num = 0; int count = list.Count; - while (j < count) + while (num < count) { try { - if (validator(list[j])) + if (validator(list[num])) { - result = list[j]; + result = list[num]; return true; } } catch (Exception ex) { - Log.Error(string.Concat(new object[] - { - "TryFindRandomEdgeCellWith exception validating ", - list[j], - ": ", - ex.ToString() - })); + Log.Error("TryFindRandomEdgeCellWith exception validating " + list[num] + ": " + ex.ToString()); } - j++; + num++; } result = IntVec3.Invalid; return false; @@ -469,66 +515,66 @@ public static bool TryFindBestPawnStandCell(Pawn forPawn, out IntVec3 cell) while (true) { CellFinder.tmpDistances.Clear(); - Dijkstra.Run(forPawn.Position, (IntVec3 x) => CellFinder.GetAdjacentCells(x, radius, forPawn), delegate(IntVec3 from, IntVec3 to) + Dijkstra.Run(forPawn.Position, (Func>)((IntVec3 x) => CellFinder.GetAdjacentCells(x, radius, forPawn)), (Func)delegate(IntVec3 from, IntVec3 to) { - float num3 = 1f; + float num5 = 1f; if (from.x != to.x && from.z != to.z) { - num3 = 1.41421354f; + num5 = 1.41421354f; } if (!to.Standable(forPawn.Map)) { - num3 += 3f; + num5 = (float)(num5 + 3.0); } if (PawnUtility.AnyPawnBlockingPathAt(to, forPawn, false, false)) { - bool flag = to.GetThingList(forPawn.Map).Find((Thing x) => x is Pawn && x.HostileTo(forPawn)) != null; - if (flag) - { - num3 += 40f; - } - else - { - num3 += 15f; - } + num5 = (float)((to.GetThingList(forPawn.Map).Find((Predicate)((Thing x) => x is Pawn && x.HostileTo(forPawn))) == null) ? (num5 + 15.0) : (num5 + 40.0)); } Building_Door building_Door2 = to.GetEdifice(forPawn.Map) as Building_Door; if (building_Door2 != null && !building_Door2.FreePassage) { - num3 += 6f; + num5 = (float)(num5 + 6.0); } - return num3; + return num5; }, ref CellFinder.tmpDistances); if (CellFinder.tmpDistances.Count == num) { - break; + return false; } float num2 = 0f; - foreach (KeyValuePair current in CellFinder.tmpDistances) + List>.Enumerator enumerator = CellFinder.tmpDistances.GetEnumerator(); + try { - if (!cell.IsValid || current.Value < num2) + while (enumerator.MoveNext()) { - if (current.Key.Walkable(forPawn.Map)) + KeyValuePair current = enumerator.Current; + if ((!cell.IsValid || !(current.Value >= num2)) && current.Key.Walkable(forPawn.Map) && !PawnUtility.AnyPawnBlockingPathAt(current.Key, forPawn, false, false)) { - if (!PawnUtility.AnyPawnBlockingPathAt(current.Key, forPawn, false, false)) + Building_Door building_Door = current.Key.GetEdifice(forPawn.Map) as Building_Door; + if (building_Door == null || building_Door.FreePassage) { - Building_Door building_Door = current.Key.GetEdifice(forPawn.Map) as Building_Door; - if (building_Door == null || building_Door.FreePassage) - { - cell = current.Key; - num2 = current.Value; - } + cell = current.Key; + num2 = current.Value; } } } } + finally + { + ((IDisposable)(object)enumerator).Dispose(); + } if (cell.IsValid) { return true; } - if (radius > (float)forPawn.Map.Size.x && radius > (float)forPawn.Map.Size.z) + float num3 = radius; + IntVec3 size = forPawn.Map.Size; + if (num3 > (float)size.x) { - return false; + float num4 = radius; + IntVec3 size2 = forPawn.Map.Size; + if (num4 > (float)size2.z) + break; } radius *= 2f; num = CellFinder.tmpDistances.Count; @@ -540,7 +586,7 @@ public static bool TryFindRandomCellInsideWith(CellRect cellRect, Predicate(); - int j = 0; + CellFinder.tmpCells.Shuffle(); + int num3 = 0; int count = CellFinder.tmpCells.Count; - while (j < count) + while (num3 < count) { - if (predicate(CellFinder.tmpCells[j])) + if (predicate(CellFinder.tmpCells[num3])) { - result = CellFinder.tmpCells[j]; + result = CellFinder.tmpCells[num3]; return true; } - j++; + num3++; } result = IntVec3.Invalid; return false; @@ -574,7 +620,7 @@ public static bool TryFindRandomCellInsideWith(CellRect cellRect, Predicate c.Standable(map) && (rootFogged || !c.Fogged(map)) && c.GetFirstPawn(map) == null, null, out result, 999999)) + if (CellFinder.TryFindRandomReachableCellNear(root, map, (float)num, TraverseParms.For(TraverseMode.NoPassClosedDoors, Danger.Deadly, false), (Predicate)((IntVec3 c) => c.Standable(map) && (rootFogged || !c.Fogged(map)) && c.GetFirstPawn(map) == null), (Predicate)null, out result, 999999)) { return true; } num *= 2; } num = firstTryWithRadius + 1; - while (!CellFinder.TryRandomClosewalkCellNear(root, map, num, out result, null)) + while (true) { - if (num > map.Size.x / 2 && num > map.Size.z / 2) + if (CellFinder.TryRandomClosewalkCellNear(root, map, num, out result, (Predicate)null)) { - result = root; - return false; + return true; + } + int num2 = num; + IntVec3 size = map.Size; + if (num2 > size.x / 2) + { + int num3 = num; + IntVec3 size2 = map.Size; + if (num3 > size2.z / 2) + break; } num *= 2; } - return true; + result = root; + return false; } - [DebuggerHidden] private static IEnumerable GetAdjacentCells(IntVec3 x, float radius, Pawn pawn) { - CellFinder.c__Iterator23E c__Iterator23E = new CellFinder.c__Iterator23E(); - c__Iterator23E.x = x; - c__Iterator23E.pawn = pawn; - c__Iterator23E.radius = radius; - c__Iterator23E.<$>x = x; - c__Iterator23E.<$>pawn = pawn; - c__Iterator23E.<$>radius = radius; - CellFinder.c__Iterator23E expr_31 = c__Iterator23E; - expr_31.$PC = -2; - return expr_31; + if (!((float)(x - pawn.Position).LengthManhattan > radius)) + { + for (int i = 0; i < 8; i++) + { + IntVec3 c = x + GenAdj.AdjacentCells[i]; + if (c.InBounds(pawn.Map) && c.Walkable(pawn.Map)) + { + Building_Door door = c.GetEdifice(pawn.Map) as Building_Door; + if (door == null || door.CanPhysicallyPass(pawn)) + { + yield return c; + } + } + } + } } } } diff --git a/Assembly-CSharp/Verse/CellFinderLoose.cs b/Assembly-CSharp/Verse/CellFinderLoose.cs index 0b582c313..14ddb2efb 100644 --- a/Assembly-CSharp/Verse/CellFinderLoose.cs +++ b/Assembly-CSharp/Verse/CellFinderLoose.cs @@ -9,14 +9,14 @@ public static class CellFinderLoose { public static IntVec3 RandomCellWith(Predicate validator, Map map, int maxTries = 1000) { - IntVec3 result; + IntVec3 result = default(IntVec3); CellFinderLoose.TryGetRandomCellWith(validator, map, maxTries, out result); return result; } public static bool TryGetRandomCellWith(Predicate validator, Map map, int maxTries, out IntVec3 result) { - for (int i = 0; i < maxTries; i++) + for (int num = 0; num < maxTries; num++) { result = CellFinder.RandomCell(map); if (validator(result)) @@ -55,23 +55,23 @@ public static IntVec3 GetFleeDestAnimal(Pawn pawn, List threats, float di { Vector3 normalized = (pawn.Position - threats[0].Position).ToVector3().normalized; float num = distance - pawn.Position.DistanceTo(threats[0].Position); - for (float num2 = 200f; num2 <= 360f; num2 += 10f) + for (float num2 = 200f; num2 <= 360.0; num2 = (float)(num2 + 10.0)) { - IntVec3 intVec = pawn.Position + (normalized.RotatedBy(Rand.Range(-num2 / 2f, num2 / 2f)) * num).ToIntVec3(); + IntVec3 intVec = pawn.Position + (normalized.RotatedBy(Rand.Range((float)((0.0 - num2) / 2.0), (float)(num2 / 2.0))) * num).ToIntVec3(); if (CellFinderLoose.CanFleeToLocation(pawn, intVec)) { return intVec; } } float num3 = num; - while (num3 * 3f > num) + while (num3 * 3.0 > num) { IntVec3 intVec2 = pawn.Position + IntVec3Utility.RandomHorizontalOffset(num3); if (CellFinderLoose.CanFleeToLocation(pawn, intVec2)) { return intVec2; } - num3 -= distance / 10f; + num3 = (float)(num3 - distance / 10.0); } return IntVec3.Invalid; } @@ -87,7 +87,15 @@ public static bool CanFleeToLocation(Pawn pawn, IntVec3 location) return false; } Region region = location.GetRegion(pawn.Map, RegionType.Set_Passable); - return region.type != RegionType.Portal && pawn.CanReach(location, PathEndMode.OnCell, Danger.Deadly, false, TraverseMode.ByPawn); + if (region.type == RegionType.Portal) + { + return false; + } + if (!pawn.CanReach(location, PathEndMode.OnCell, Danger.Deadly, false, TraverseMode.ByPawn)) + { + return false; + } + return true; } public static IntVec3 GetFleeDestToolUser(Pawn pawn, List threats, float distance = 23f) @@ -95,53 +103,50 @@ public static IntVec3 GetFleeDestToolUser(Pawn pawn, List threats, float IntVec3 bestPos = pawn.Position; float bestScore = -1f; TraverseParms traverseParms = TraverseParms.For(pawn, Danger.Deadly, TraverseMode.ByPawn, false); - RegionTraverser.BreadthFirstTraverse(pawn.GetRegion(RegionType.Set_Passable), (Region from, Region reg) => reg.Allows(traverseParms, false), delegate(Region reg) + RegionTraverser.BreadthFirstTraverse(pawn.GetRegion(RegionType.Set_Passable), (RegionEntryPredicate)((Region from, Region reg) => reg.Allows(traverseParms, false)), (RegionProcessor)delegate(Region reg) { Danger danger = reg.DangerFor(pawn); Map map = pawn.Map; - foreach (IntVec3 current in reg.Cells) + foreach (IntVec3 cell in reg.Cells) { - if (current.Standable(map)) + if (cell.Standable(map) && reg.portal == null) { - if (reg.portal == null) + Thing thing = null; + float num = 0f; + for (int i = 0; i < threats.Count; i++) { - Thing thing = null; - float num = 0f; - for (int i = 0; i < threats.Count; i++) - { - float num2 = (float)current.DistanceToSquared(threats[i].Position); - if (thing == null || num2 < num) - { - thing = threats[i]; - num = num2; - } - } - float num3 = Mathf.Sqrt(num); - float f = Mathf.Min(num3, distance); - float num4 = Mathf.Pow(f, 1.2f); - num4 *= Mathf.InverseLerp(50f, 0f, (current - pawn.Position).LengthHorizontal); - if (current.GetRoom(map, RegionType.Set_Passable) != thing.GetRoom(RegionType.Set_Passable)) - { - num4 *= 4.2f; - } - else if (num3 < 8f) - { - num4 *= 0.05f; - } - if (map.pawnDestinationManager.DestinationIsReserved(current, pawn)) - { - num4 *= 0.5f; - } - if (danger == Danger.Deadly) + float num2 = (float)cell.DistanceToSquared(threats[i].Position); + if (thing == null || num2 < num) { - num4 *= 0.8f; - } - if (num4 > bestScore) - { - bestPos = current; - bestScore = num4; + thing = threats[i]; + num = num2; } } + float num3 = Mathf.Sqrt(num); + float f = Mathf.Min(num3, distance); + float num4 = Mathf.Pow(f, 1.2f); + num4 *= Mathf.InverseLerp(50f, 0f, (cell - pawn.Position).LengthHorizontal); + if (cell.GetRoom(map, RegionType.Set_Passable) != thing.GetRoom(RegionType.Set_Passable)) + { + num4 = (float)(num4 * 4.1999998092651367); + } + else if (num3 < 8.0) + { + num4 = (float)(num4 * 0.05000000074505806); + } + if (map.pawnDestinationManager.DestinationIsReserved(cell, pawn)) + { + num4 = (float)(num4 * 0.5); + } + if (danger == Danger.Deadly) + { + num4 = (float)(num4 * 0.800000011920929); + } + if (num4 > bestScore) + { + bestPos = cell; + bestScore = num4; + } } } return false; @@ -156,7 +161,7 @@ public static IntVec3 TryFindCentralCell(Map map, int tightness, int minCellCoun int debug_numTouch = 0; int debug_numRoomCellCount = 0; int debug_numExtraValidator = 0; - Predicate validator = delegate(IntVec3 c) + Predicate validator = (Predicate)delegate(IntVec3 c) { if (!c.Standable(map)) { @@ -179,37 +184,27 @@ public static IntVec3 TryFindCentralCell(Map map, int tightness, int minCellCoun debug_numRoomCellCount++; return false; } - if (extraValidator != null && !extraValidator(c)) + if ((object)extraValidator != null && !extraValidator(c)) { debug_numExtraValidator++; return false; } return true; }; - for (int i = tightness; i >= 1; i--) + for (int num = tightness; num >= 1; num--) { - int num = map.Size.x / i; - int minEdgeDistance = (map.Size.x - num) / 2; - IntVec3 result; + IntVec3 size = map.Size; + int num2 = size.x / num; + IntVec3 size2 = map.Size; + int minEdgeDistance = (size2.x - num2) / 2; + IntVec3 result = default(IntVec3); if (CellFinderLoose.TryFindRandomNotEdgeCellWith(minEdgeDistance, validator, map, out result)) { return result; } } - Log.Error(string.Concat(new object[] - { - "Found no good central spot. Choosing randomly. numStand=", - debug_numStand, - ", numRoom=", - debug_numRoom, - ", numTouch=", - debug_numTouch, - ", numRoomCellCount=", - debug_numRoomCellCount, - ", numExtraValidator=", - debug_numExtraValidator - })); - return CellFinderLoose.RandomCellWith((IntVec3 x) => x.Standable(map), map, 1000); + Log.Error("Found no good central spot. Choosing randomly. numStand=" + debug_numStand + ", numRoom=" + debug_numRoom + ", numTouch=" + debug_numTouch + ", numRoomCellCount=" + debug_numRoomCellCount + ", numExtraValidator=" + debug_numExtraValidator); + return CellFinderLoose.RandomCellWith((Predicate)((IntVec3 x) => x.Standable(map)), map, 1000); } } } diff --git a/Assembly-CSharp/Verse/CellGrid.cs b/Assembly-CSharp/Verse/CellGrid.cs index 31d37891e..4d71fe064 100644 --- a/Assembly-CSharp/Verse/CellGrid.cs +++ b/Assembly-CSharp/Verse/CellGrid.cs @@ -1,5 +1,3 @@ -using System; - namespace Verse { public class CellGrid @@ -69,7 +67,20 @@ public CellGrid(Map map) public bool MapSizeMatches(Map map) { - return this.mapSizeX == map.Size.x && this.mapSizeZ == map.Size.z; + int num = this.mapSizeX; + IntVec3 size = map.Size; + int result; + if (num == size.x) + { + int num2 = this.mapSizeZ; + IntVec3 size2 = map.Size; + result = ((num2 == size2.z) ? 1 : 0); + } + else + { + result = 0; + } + return (byte)result != 0; } public void ClearAndResizeTo(Map map) @@ -77,12 +88,16 @@ public void ClearAndResizeTo(Map map) if (this.MapSizeMatches(map) && this.grid != null) { this.Clear(); - return; } - this.mapSizeX = map.Size.x; - this.mapSizeZ = map.Size.z; - this.grid = new int[this.mapSizeX * this.mapSizeZ]; - this.Clear(); + else + { + IntVec3 size = map.Size; + this.mapSizeX = size.x; + IntVec3 size2 = map.Size; + this.mapSizeZ = size2.z; + this.grid = new int[this.mapSizeX * this.mapSizeZ]; + this.Clear(); + } } public void Clear() diff --git a/Assembly-CSharp/Verse/CellIndices.cs b/Assembly-CSharp/Verse/CellIndices.cs index f7dcda94d..f429b31df 100644 --- a/Assembly-CSharp/Verse/CellIndices.cs +++ b/Assembly-CSharp/Verse/CellIndices.cs @@ -1,5 +1,3 @@ -using System; - namespace Verse { public class CellIndices @@ -18,8 +16,10 @@ public int NumGridCells public CellIndices(Map map) { - this.mapSizeX = map.Size.x; - this.mapSizeZ = map.Size.z; + IntVec3 size = map.Size; + this.mapSizeX = size.x; + IntVec3 size2 = map.Size; + this.mapSizeZ = size2.z; } public int CellToIndex(IntVec3 c) diff --git a/Assembly-CSharp/Verse/CellIndicesUtility.cs b/Assembly-CSharp/Verse/CellIndicesUtility.cs index 585637e97..b2a73e9fd 100644 --- a/Assembly-CSharp/Verse/CellIndicesUtility.cs +++ b/Assembly-CSharp/Verse/CellIndicesUtility.cs @@ -1,5 +1,3 @@ -using System; - namespace Verse { public static class CellIndicesUtility diff --git a/Assembly-CSharp/Verse/CellLine.cs b/Assembly-CSharp/Verse/CellLine.cs index 9821d39cd..f24b6c154 100644 --- a/Assembly-CSharp/Verse/CellLine.cs +++ b/Assembly-CSharp/Verse/CellLine.cs @@ -1,5 +1,3 @@ -using System; - namespace Verse { public struct CellLine @@ -38,15 +36,7 @@ public CellLine(IntVec3 cell, float slope) public static CellLine Between(IntVec3 a, IntVec3 b) { - float num; - if (a.x == b.x) - { - num = 1E+08f; - } - else - { - num = (float)(b.z - a.z) / (float)(b.x - a.x); - } + float num = (float)((a.x != b.x) ? ((float)(b.z - a.z) / (float)(b.x - a.x)) : 100000000.0); float num2 = (float)a.z - (float)a.x * num; return new CellLine(num2, num); } diff --git a/Assembly-CSharp/Verse/CellRect.cs b/Assembly-CSharp/Verse/CellRect.cs index de74b60f3..9dd0707ec 100644 --- a/Assembly-CSharp/Verse/CellRect.cs +++ b/Assembly-CSharp/Verse/CellRect.cs @@ -1,7 +1,6 @@ using System; using System.Collections; using System.Collections.Generic; -using System.Diagnostics; using System.Linq; using UnityEngine; @@ -52,7 +51,11 @@ public bool MoveNext() this.x = this.ir.minX; this.z++; } - return this.z <= this.ir.maxZ; + if (this.z > this.ir.maxZ) + { + return false; + } + return true; } public void Reset() @@ -191,7 +194,7 @@ public Vector3 CenterVector3 { get { - return new Vector3((float)this.minX + (float)this.Width / 2f, 0f, (float)this.minZ + (float)this.Height / 2f); + return new Vector3((float)((float)this.minX + (float)this.Width / 2.0), 0f, (float)((float)this.minZ + (float)this.Height / 2.0)); } } @@ -207,11 +210,13 @@ public IEnumerable Cells { get { - CellRect.<>c__Iterator237 <>c__Iterator = new CellRect.<>c__Iterator237(); - <>c__Iterator.<>f__this = this; - CellRect.<>c__Iterator237 expr_13 = <>c__Iterator; - expr_13.$PC = -2; - return expr_13; + for (int z = this.minZ; z <= this.maxZ; z++) + { + for (int x = this.minX; x <= this.maxX; x++) + { + yield return new IntVec3(x, 0, z); + } + } } } @@ -219,11 +224,13 @@ public IEnumerable Cells2D { get { - CellRect.<>c__Iterator238 <>c__Iterator = new CellRect.<>c__Iterator238(); - <>c__Iterator.<>f__this = this; - CellRect.<>c__Iterator238 expr_13 = <>c__Iterator; - expr_13.$PC = -2; - return expr_13; + for (int z = this.minZ; z <= this.maxZ; z++) + { + for (int x = this.minX; x <= this.maxX; x++) + { + yield return new IntVec2(x, z); + } + } } } @@ -231,11 +238,27 @@ public IEnumerable EdgeCells { get { - CellRect.<>c__Iterator239 <>c__Iterator = new CellRect.<>c__Iterator239(); - <>c__Iterator.<>f__this = this; - CellRect.<>c__Iterator239 expr_13 = <>c__Iterator; - expr_13.$PC = -2; - return expr_13; + int x4 = this.minX; + int z4 = this.minZ; + for (; x4 <= this.maxX; x4++) + { + yield return new IntVec3(x4, 0, z4); + } + x4--; + for (z4++; z4 <= this.maxZ; z4++) + { + yield return new IntVec3(x4, 0, z4); + } + z4--; + for (x4--; x4 >= this.minX; x4--) + { + yield return new IntVec3(x4, 0, z4); + } + x4++; + for (z4--; z4 > this.minZ; z4--) + { + yield return new IntVec3(x4, 0, z4); + } } } @@ -263,14 +286,17 @@ public CellRect(int minX, int minZ, int width, int height) this.maxZ = minZ + height - 1; } - public CellRect.CellRectIterator GetIterator() + public CellRectIterator GetIterator() { - return new CellRect.CellRectIterator(this); + return new CellRectIterator(this); } public static CellRect WholeMap(Map map) { - return new CellRect(0, 0, map.Size.x, map.Size.z); + IntVec3 size = map.Size; + int x = size.x; + IntVec3 size2 = map.Size; + return new CellRect(0, 0, x, size2.z); } public static CellRect FromLimits(int minX, int minZ, int maxX, int maxZ) @@ -313,7 +339,23 @@ public static CellRect SingleCell(IntVec3 c) public bool InBounds(Map map) { - return this.minX >= 0 && this.minZ >= 0 && this.maxX < map.Size.x && this.maxZ < map.Size.z; + int result; + if (this.minX >= 0 && this.minZ >= 0) + { + int num = this.maxX; + IntVec3 size = map.Size; + if (num < size.x) + { + int num2 = this.maxZ; + IntVec3 size2 = map.Size; + result = ((num2 < size2.z) ? 1 : 0); + goto IL_004a; + } + } + result = 0; + goto IL_004a; + IL_004a: + return (byte)result != 0; } public bool FullyContainedWithin(CellRect within) @@ -325,12 +367,48 @@ public bool FullyContainedWithin(CellRect within) public bool IsOnEdge(IntVec3 c) { - return (c.x == this.minX && c.z >= this.minZ && c.z <= this.maxZ) || (c.x == this.maxX && c.z >= this.minZ && c.z <= this.maxZ) || (c.z == this.minZ && c.x >= this.minX && c.x <= this.maxX) || (c.z == this.maxZ && c.x >= this.minX && c.x <= this.maxX); + if (c.x == this.minX && c.z >= this.minZ && c.z <= this.maxZ) + { + goto IL_00dd; + } + if (c.x == this.maxX && c.z >= this.minZ && c.z <= this.maxZ) + { + goto IL_00dd; + } + if (c.z == this.minZ && c.x >= this.minX && c.x <= this.maxX) + { + goto IL_00dd; + } + int result = (c.z == this.maxZ && c.x >= this.minX && c.x <= this.maxX) ? 1 : 0; + goto IL_00de; + IL_00dd: + result = 1; + goto IL_00de; + IL_00de: + return (byte)result != 0; } public bool IsCorner(IntVec3 c) { - return (c.x == this.minX && c.z == this.minZ) || (c.x == this.maxX && c.z == this.minZ) || (c.x == this.minX && c.z == this.maxZ) || (c.x == this.maxX && c.z == this.maxZ); + if (c.x == this.minX && c.z == this.minZ) + { + goto IL_0092; + } + if (c.x == this.maxX && c.z == this.minZ) + { + goto IL_0092; + } + if (c.x == this.minX && c.z == this.maxZ) + { + goto IL_0092; + } + int result = (c.x == this.maxX && c.z == this.maxZ) ? 1 : 0; + goto IL_0093; + IL_0093: + return (byte)result != 0; + IL_0092: + result = 1; + goto IL_0093; } public CellRect ClipInsideMap(Map map) @@ -343,13 +421,19 @@ public CellRect ClipInsideMap(Map map) { this.minZ = 0; } - if (this.maxX > map.Size.x - 1) + int num = this.maxX; + IntVec3 size = map.Size; + if (num > size.x - 1) { - this.maxX = map.Size.x - 1; + IntVec3 size2 = map.Size; + this.maxX = size2.x - 1; } - if (this.maxZ > map.Size.z - 1) + int num2 = this.maxZ; + IntVec3 size3 = map.Size; + if (num2 > size3.z - 1) { - this.maxZ = map.Size.z - 1; + IntVec3 size4 = map.Size; + this.maxZ = size4.z - 1; } return this; } @@ -398,7 +482,7 @@ public float ClosestDistSquaredTo(IntVec3 c) } return (float)((this.minX - c.x) * (this.minX - c.x)); } - else if (c.x > this.maxX) + if (c.x > this.maxX) { if (c.z < this.minZ) { @@ -410,14 +494,11 @@ public float ClosestDistSquaredTo(IntVec3 c) } return (float)((c.x - this.maxX) * (c.x - this.maxX)); } - else + if (c.z < this.minZ) { - if (c.z < this.minZ) - { - return (float)((this.minZ - c.z) * (this.minZ - c.z)); - } - return (float)((c.z - this.maxZ) * (c.z - this.maxZ)); + return (float)((this.minZ - c.z) * (this.minZ - c.z)); } + return (float)((c.z - this.maxZ) * (c.z - this.maxZ)); } public IntVec3 ClosestCellTo(IntVec3 c) @@ -438,7 +519,7 @@ public IntVec3 ClosestCellTo(IntVec3 c) } return new IntVec3(this.minX, 0, c.z); } - else if (c.x > this.maxX) + if (c.x > this.maxX) { if (c.z < this.minZ) { @@ -450,51 +531,68 @@ public IntVec3 ClosestCellTo(IntVec3 c) } return new IntVec3(this.maxX, 0, c.z); } - else + if (c.z < this.minZ) { - if (c.z < this.minZ) - { - return new IntVec3(c.x, 0, this.minZ); - } - return new IntVec3(c.x, 0, this.maxZ); + return new IntVec3(c.x, 0, this.minZ); } + return new IntVec3(c.x, 0, this.maxZ); } - [DebuggerHidden] public IEnumerable GetEdgeCells(Rot4 dir) { - CellRect.c__Iterator23A c__Iterator23A = new CellRect.c__Iterator23A(); - c__Iterator23A.dir = dir; - c__Iterator23A.<$>dir = dir; - c__Iterator23A.<>f__this = this; - CellRect.c__Iterator23A expr_21 = c__Iterator23A; - expr_21.$PC = -2; - return expr_21; + if (dir == Rot4.North) + { + for (int x2 = this.minX; x2 <= this.maxX; x2++) + { + yield return new IntVec3(x2, 0, this.maxZ); + } + } + else if (dir == Rot4.South) + { + for (int x = this.minX; x <= this.maxX; x++) + { + yield return new IntVec3(x, 0, this.minZ); + } + } + else if (dir == Rot4.West) + { + for (int z2 = this.minZ; z2 <= this.maxZ; z2++) + { + yield return new IntVec3(this.minX, 0, z2); + } + } + else if (dir == Rot4.East) + { + for (int z = this.minZ; z <= this.maxZ; z++) + { + yield return new IntVec3(this.maxX, 0, z); + } + } } public bool TryFindRandomInnerRectTouchingEdge(IntVec2 size, out CellRect rect, Predicate predicate = null) { - if (this.Width < size.x || this.Height < size.z) - { - rect = CellRect.Empty; - return false; - } - CellRect cellRect = this; - cellRect.maxX -= size.x - 1; - cellRect.maxZ -= size.z - 1; - IntVec3 intVec; - if (cellRect.EdgeCells.Where(delegate(IntVec3 x) + if (this.Width >= size.x && this.Height >= size.z) { - if (predicate == null) + CellRect cellRect = this; + cellRect.maxX -= size.x - 1; + cellRect.maxZ -= size.z - 1; + IntVec3 intVec = default(IntVec3); + if (cellRect.EdgeCells.Where((Func)delegate(IntVec3 x) { + if ((object)predicate == null) + { + return true; + } + CellRect obj = new CellRect(x.x, x.z, size.x, size.z); + return predicate(obj); + }).TryRandomElement(out intVec)) + { + rect = new CellRect(intVec.x, intVec.z, size.x, size.z); return true; } - CellRect obj = new CellRect(x.x, x.z, size.x, size.z); - return predicate(obj); - }).TryRandomElement(out intVec)) - { - rect = new CellRect(intVec.x, intVec.z, size.x, size.z); - return true; + rect = CellRect.Empty; + return false; } rect = CellRect.Empty; return false; @@ -530,39 +628,19 @@ public void DebugDraw() public IEnumerator GetEnumerator() { - return new CellRect.Enumerator(this); + return (IEnumerator)(object)new Enumerator(this); } public override string ToString() { - return string.Concat(new object[] - { - "(", - this.minX, - ",", - this.minZ, - ",", - this.maxX, - ",", - this.maxZ, - ")" - }); + return "(" + this.minX + "," + this.minZ + "," + this.maxX + "," + this.maxZ + ")"; } public static CellRect FromString(string str) { - str = str.TrimStart(new char[] - { - '(' - }); - str = str.TrimEnd(new char[] - { - ')' - }); - string[] array = str.Split(new char[] - { - ',' - }); + str = str.TrimStart('('); + str = str.TrimEnd(')'); + string[] array = str.Split(','); int num = Convert.ToInt32(array[0]); int num2 = Convert.ToInt32(array[1]); int num3 = Convert.ToInt32(array[2]); @@ -581,7 +659,11 @@ public override int GetHashCode() public override bool Equals(object obj) { - return obj is CellRect && this.Equals((CellRect)obj); + if (!(obj is CellRect)) + { + return false; + } + return this.Equals((CellRect)obj); } public bool Equals(CellRect other) diff --git a/Assembly-CSharp/Verse/CellRenderer.cs b/Assembly-CSharp/Verse/CellRenderer.cs index d0c666128..56b08ae29 100644 --- a/Assembly-CSharp/Verse/CellRenderer.cs +++ b/Assembly-CSharp/Verse/CellRenderer.cs @@ -1,4 +1,3 @@ -using System; using UnityEngine; namespace Verse @@ -20,9 +19,9 @@ private static void InitFrame() private static Material MatFromColorPct(float colorPct, bool transparent) { - int num = Mathf.RoundToInt(colorPct * 100f); - num = GenMath.PositiveMod(num, 100); - return DebugMatsSpectrum.Mat(num, transparent); + int x = Mathf.RoundToInt((float)(colorPct * 100.0)); + x = GenMath.PositiveMod(x, 100); + return DebugMatsSpectrum.Mat(x, transparent); } public static void RenderCell(IntVec3 c, float colorPct = 0.5f) @@ -33,12 +32,11 @@ public static void RenderCell(IntVec3 c, float colorPct = 0.5f) public static void RenderCell(IntVec3 c, Material mat) { CellRenderer.InitFrame(); - if (!CellRenderer.viewRect.Contains(c)) + if (CellRenderer.viewRect.Contains(c)) { - return; + Vector3 position = c.ToVector3ShiftedWithAltitude(AltitudeLayer.MetaOverlays); + Graphics.DrawMesh(MeshPool.plane10, position, Quaternion.identity, mat, 0); } - Vector3 position = c.ToVector3ShiftedWithAltitude(AltitudeLayer.MetaOverlays); - Graphics.DrawMesh(MeshPool.plane10, position, Quaternion.identity, mat, 0); } public static void RenderSpot(Vector3 loc, float colorPct = 0.5f) @@ -49,15 +47,14 @@ public static void RenderSpot(Vector3 loc, float colorPct = 0.5f) public static void RenderSpot(Vector3 loc, Material mat, float scale = 0.15f) { CellRenderer.InitFrame(); - if (!CellRenderer.viewRect.Contains(loc.ToIntVec3())) + if (CellRenderer.viewRect.Contains(loc.ToIntVec3())) { - return; + loc.y = Altitudes.AltitudeFor(AltitudeLayer.MetaOverlays); + Vector3 s = new Vector3(scale, 1f, scale); + Matrix4x4 matrix = default(Matrix4x4); + matrix.SetTRS(loc, Quaternion.identity, s); + Graphics.DrawMesh(MeshPool.circle, matrix, mat, 0); } - loc.y = Altitudes.AltitudeFor(AltitudeLayer.MetaOverlays); - Vector3 s = new Vector3(scale, 1f, scale); - Matrix4x4 matrix = default(Matrix4x4); - matrix.SetTRS(loc, Quaternion.identity, s); - Graphics.DrawMesh(MeshPool.circle, matrix, mat, 0); } } } diff --git a/Assembly-CSharp/Verse/CheckJobOverrideOnDamageMode.cs b/Assembly-CSharp/Verse/CheckJobOverrideOnDamageMode.cs index 585ec4d32..05556c6e0 100644 --- a/Assembly-CSharp/Verse/CheckJobOverrideOnDamageMode.cs +++ b/Assembly-CSharp/Verse/CheckJobOverrideOnDamageMode.cs @@ -1,11 +1,9 @@ -using System; - namespace Verse { public enum CheckJobOverrideOnDamageMode { - Never, - OnlyIfInstigatorNotJobTarget, - Always + Never = 0, + OnlyIfInstigatorNotJobTarget = 1, + Always = 2 } } diff --git a/Assembly-CSharp/Verse/ChoiceLetter.cs b/Assembly-CSharp/Verse/ChoiceLetter.cs index 11a1800a4..e15a725bf 100644 --- a/Assembly-CSharp/Verse/ChoiceLetter.cs +++ b/Assembly-CSharp/Verse/ChoiceLetter.cs @@ -20,14 +20,13 @@ protected DiaOption Reject { get { - return new DiaOption("RejectLetter".Translate()) + DiaOption diaOption = new DiaOption("RejectLetter".Translate()); + diaOption.action = (Action)delegate { - action = delegate - { - Find.LetterStack.RemoveLetter(this); - }, - resolveTree = true + Find.LetterStack.RemoveLetter(this); }; + diaOption.resolveTree = true; + return diaOption; } } @@ -37,9 +36,9 @@ protected DiaOption Postpone { DiaOption diaOption = new DiaOption("PostponeLetter".Translate()); diaOption.resolveTree = true; - if (base.TimeoutActive && this.disappearAtTick <= Find.TickManager.TicksGame + 1) + if (base.TimeoutActive && base.disappearAtTick <= Find.TickManager.TicksGame + 1) { - diaOption.Disable(null); + diaOption.Disable((string)null); } return diaOption; } @@ -49,14 +48,13 @@ protected DiaOption OK { get { - return new DiaOption("OK".Translate()) + DiaOption diaOption = new DiaOption("OK".Translate()); + diaOption.action = (Action)delegate { - action = delegate - { - Find.LetterStack.RemoveLetter(this); - }, - resolveTree = true + Find.LetterStack.RemoveLetter(this); }; + diaOption.resolveTree = true; + return diaOption; } } @@ -65,15 +63,15 @@ protected DiaOption JumpToLocation get { DiaOption diaOption = new DiaOption("JumpToLocation".Translate()); - diaOption.action = delegate + diaOption.action = (Action)delegate { - CameraJumper.TryJumpAndSelect(this.lookTarget); + CameraJumper.TryJumpAndSelect(base.lookTarget); Find.LetterStack.RemoveLetter(this); }; diaOption.resolveTree = true; - if (!this.lookTarget.IsValid) + if (!base.lookTarget.IsValid) { - diaOption.Disable(null); + diaOption.Disable((string)null); } return diaOption; } @@ -82,8 +80,8 @@ protected DiaOption JumpToLocation public override void ExposeData() { base.ExposeData(); - Scribe_Values.Look(ref this.title, "title", null, false); - Scribe_Values.Look(ref this.text, "text", null, false); + Scribe_Values.Look(ref this.title, "title", (string)null, false); + Scribe_Values.Look(ref this.text, "text", (string)null, false); Scribe_Values.Look(ref this.radioMode, "radioMode", false, false); } @@ -96,9 +94,9 @@ public override void OpenLetter() { DiaNode diaNode = new DiaNode(this.text); diaNode.options.AddRange(this.Choices); - WindowStack arg_37_0 = Find.WindowStack; + WindowStack windowStack = Find.WindowStack; bool flag = this.radioMode; - arg_37_0.Add(new Dialog_NodeTree(diaNode, false, flag, this.title)); + windowStack.Add(new Dialog_NodeTree(diaNode, false, flag, this.title)); } } } diff --git a/Assembly-CSharp/Verse/ClamorType.cs b/Assembly-CSharp/Verse/ClamorType.cs index b1bdad412..621803b74 100644 --- a/Assembly-CSharp/Verse/ClamorType.cs +++ b/Assembly-CSharp/Verse/ClamorType.cs @@ -1,11 +1,9 @@ -using System; - namespace Verse { public enum ClamorType { - Movement, - Harm, - Construction + Movement = 0, + Harm = 1, + Construction = 2 } } diff --git a/Assembly-CSharp/Verse/ColorGenerator.cs b/Assembly-CSharp/Verse/ColorGenerator.cs index 29a2a3332..c333b439f 100644 --- a/Assembly-CSharp/Verse/ColorGenerator.cs +++ b/Assembly-CSharp/Verse/ColorGenerator.cs @@ -1,4 +1,3 @@ -using System; using UnityEngine; namespace Verse diff --git a/Assembly-CSharp/Verse/ColorGenerator_Options.cs b/Assembly-CSharp/Verse/ColorGenerator_Options.cs index dee51d8bd..4259860ba 100644 --- a/Assembly-CSharp/Verse/ColorGenerator_Options.cs +++ b/Assembly-CSharp/Verse/ColorGenerator_Options.cs @@ -10,7 +10,7 @@ public class ColorGenerator_Options : ColorGenerator public override Color NewRandomizedColor() { - ColorOption colorOption = this.options.RandomElementByWeight((ColorOption pi) => pi.weight); + ColorOption colorOption = this.options.RandomElementByWeight((Func)((ColorOption pi) => pi.weight)); return colorOption.RandomizedColor(); } } diff --git a/Assembly-CSharp/Verse/ColorGenerator_Single.cs b/Assembly-CSharp/Verse/ColorGenerator_Single.cs index 7dcba185d..aac6154cb 100644 --- a/Assembly-CSharp/Verse/ColorGenerator_Single.cs +++ b/Assembly-CSharp/Verse/ColorGenerator_Single.cs @@ -1,4 +1,3 @@ -using System; using UnityEngine; namespace Verse diff --git a/Assembly-CSharp/Verse/ColorGenerator_StandardApparel.cs b/Assembly-CSharp/Verse/ColorGenerator_StandardApparel.cs index 6cc6adf35..5bfde4f99 100644 --- a/Assembly-CSharp/Verse/ColorGenerator_StandardApparel.cs +++ b/Assembly-CSharp/Verse/ColorGenerator_StandardApparel.cs @@ -1,4 +1,3 @@ -using System; using UnityEngine; namespace Verse @@ -9,11 +8,11 @@ public class ColorGenerator_StandardApparel : ColorGenerator public override Color NewRandomizedColor() { - if (Rand.Value < 0.1f) + if (Rand.Value < 0.10000000149011612) { return Color.white; } - if (Rand.Value < 0.1f) + if (Rand.Value < 0.10000000149011612) { return new Color(0.4f, 0.4f, 0.4f); } @@ -22,7 +21,7 @@ public override Color NewRandomizedColor() white.r -= num * Rand.Value; white.g -= num * Rand.Value; white.b -= num * Rand.Value; - if (Rand.Value < 0.2f) + if (Rand.Value < 0.20000000298023224) { white.r *= 0.4f; white.g *= 0.4f; diff --git a/Assembly-CSharp/Verse/ColorGenerator_White.cs b/Assembly-CSharp/Verse/ColorGenerator_White.cs index fc626504e..b94c8fbb6 100644 --- a/Assembly-CSharp/Verse/ColorGenerator_White.cs +++ b/Assembly-CSharp/Verse/ColorGenerator_White.cs @@ -1,4 +1,3 @@ -using System; using UnityEngine; namespace Verse diff --git a/Assembly-CSharp/Verse/ColorInt.cs b/Assembly-CSharp/Verse/ColorInt.cs index d6822d5b5..fc25dcc1e 100644 --- a/Assembly-CSharp/Verse/ColorInt.cs +++ b/Assembly-CSharp/Verse/ColorInt.cs @@ -19,10 +19,10 @@ public Color ToColor { return new Color { - r = (float)this.r / 255f, - g = (float)this.g / 255f, - b = (float)this.b / 255f, - a = (float)this.a / 255f + r = (float)((float)this.r / 255.0), + g = (float)((float)this.g / 255.0), + b = (float)((float)this.b / 255.0), + a = (float)((float)this.a / 255.0) }; } } @@ -34,7 +34,7 @@ public Color32 ToColor32 Color32 result = default(Color32); if (this.a > 255) { - result.a = 255; + result.a = (byte)255; } else { @@ -42,7 +42,7 @@ public Color32 ToColor32 } if (this.r > 255) { - result.r = 255; + result.r = (byte)255; } else { @@ -50,7 +50,7 @@ public Color32 ToColor32 } if (this.g > 255) { - result.g = 255; + result.g = (byte)255; } else { @@ -58,7 +58,7 @@ public Color32 ToColor32 } if (this.b > 255) { - result.b = 255; + result.b = (byte)255; } else { @@ -86,15 +86,19 @@ public ColorInt(int r, int g, int b, int a) public ColorInt(Color32 col) { - this.r = (int)col.r; - this.g = (int)col.g; - this.b = (int)col.b; - this.a = (int)col.a; + this.r = col.r; + this.g = col.g; + this.b = col.b; + this.a = col.a; } public override bool Equals(object o) { - return o is ColorInt && this.Equals((ColorInt)o); + if (!(o is ColorInt)) + { + return false; + } + return this.Equals((ColorInt)o); } public bool Equals(ColorInt other) @@ -134,7 +138,7 @@ public void ClampToNonNegative() public static ColorInt operator +(ColorInt colA, Color32 colB) { - return new ColorInt(colA.r + (int)colB.r, colA.g + (int)colB.g, colA.b + (int)colB.b, colA.a + (int)colB.a); + return new ColorInt(colA.r + colB.r, colA.g + colB.g, colA.b + colB.b, colA.a + colB.a); } public static ColorInt operator -(ColorInt a, ColorInt b) diff --git a/Assembly-CSharp/Verse/ColorIntUtility.cs b/Assembly-CSharp/Verse/ColorIntUtility.cs index 3c100026d..59d46c3ed 100644 --- a/Assembly-CSharp/Verse/ColorIntUtility.cs +++ b/Assembly-CSharp/Verse/ColorIntUtility.cs @@ -1,4 +1,3 @@ -using System; using UnityEngine; namespace Verse diff --git a/Assembly-CSharp/Verse/ColorLibrary.cs b/Assembly-CSharp/Verse/ColorLibrary.cs index a9fdc1e65..bb1f64ef4 100644 --- a/Assembly-CSharp/Verse/ColorLibrary.cs +++ b/Assembly-CSharp/Verse/ColorLibrary.cs @@ -1,4 +1,3 @@ -using System; using UnityEngine; namespace Verse diff --git a/Assembly-CSharp/Verse/ColorOption.cs b/Assembly-CSharp/Verse/ColorOption.cs index beaba99a4..24fb6f38f 100644 --- a/Assembly-CSharp/Verse/ColorOption.cs +++ b/Assembly-CSharp/Verse/ColorOption.cs @@ -1,4 +1,3 @@ -using System; using UnityEngine; namespace Verse @@ -15,7 +14,7 @@ public class ColorOption public Color RandomizedColor() { - if (this.only.a >= 0f) + if (this.only.a >= 0.0) { return this.only; } diff --git a/Assembly-CSharp/Verse/ColorsFromSpectrum.cs b/Assembly-CSharp/Verse/ColorsFromSpectrum.cs index 0ae340c8f..5700c25f9 100644 --- a/Assembly-CSharp/Verse/ColorsFromSpectrum.cs +++ b/Assembly-CSharp/Verse/ColorsFromSpectrum.cs @@ -1,4 +1,3 @@ -using System; using System.Collections.Generic; using UnityEngine; @@ -18,7 +17,7 @@ public static Color Get(IList spectrum, float val) return spectrum[0]; } val = Mathf.Clamp01(val); - float num = 1f / (float)(spectrum.Count - 1); + float num = (float)(1.0 / (float)(spectrum.Count - 1)); int num2 = (int)(val / num); if (num2 == spectrum.Count - 1) { diff --git a/Assembly-CSharp/Verse/Command.cs b/Assembly-CSharp/Verse/Command.cs index 53c1bf2f1..7bea8eb1d 100644 --- a/Assembly-CSharp/Verse/Command.cs +++ b/Assembly-CSharp/Verse/Command.cs @@ -1,5 +1,4 @@ using RimWorld; -using System; using UnityEngine; using Verse.Sound; @@ -114,20 +113,20 @@ public override GizmoResult GizmoOnGUI(Vector2 topLeft) GUI.color = GenUI.MouseoverColor; } Texture2D badTex = this.icon; - if (badTex == null) + if ((Object)badTex == (Object)null) { badTex = BaseContent.BadTex; } GUI.DrawTexture(rect, Command.BGTex); MouseoverSounds.DoRegion(rect, SoundDefOf.MouseoverCommand); GUI.color = this.IconDrawColor; - Widgets.DrawTextureFitted(new Rect(rect), badTex, this.iconDrawScale * 0.85f, this.iconProportions, this.iconTexCoords); + Widgets.DrawTextureFitted(new Rect(rect), badTex, (float)(this.iconDrawScale * 0.85000002384185791), this.iconProportions, this.iconTexCoords); GUI.color = Color.white; bool flag2 = false; KeyCode keyCode = (this.hotKey != null) ? this.hotKey.MainKey : KeyCode.None; - if (keyCode != KeyCode.None && !GizmoGridDrawer.drawnHotKeys.Contains(keyCode)) + if (keyCode != 0 && !GizmoGridDrawer.drawnHotKeys.Contains(keyCode)) { - Rect rect2 = new Rect(rect.x + 5f, rect.y + 5f, rect.width - 10f, 18f); + Rect rect2 = new Rect((float)(rect.x + 5.0), (float)(rect.y + 5.0), (float)(rect.width - 10.0), 18f); Widgets.Label(rect2, keyCode.ToStringReadable()); GizmoGridDrawer.drawnHotKeys.Add(keyCode); if (this.hotKey.KeyDownEvent) @@ -144,7 +143,7 @@ public override GizmoResult GizmoOnGUI(Vector2 topLeft) if (!labelCap.NullOrEmpty()) { float num = Text.CalcHeight(labelCap, rect.width); - Rect rect3 = new Rect(rect.x, rect.yMax - num + 12f, rect.width, num); + Rect rect3 = new Rect(rect.x, (float)(rect.yMax - num + 12.0), rect.width, num); GUI.DrawTexture(rect3, TexUI.GrayTextBG); GUI.color = Color.white; Text.Anchor = TextAnchor.UpperCenter; @@ -156,17 +155,10 @@ public override GizmoResult GizmoOnGUI(Vector2 topLeft) if (this.DoTooltip) { TipSignal tip = this.Desc; - if (this.disabled && !this.disabledReason.NullOrEmpty()) + if (base.disabled && !base.disabledReason.NullOrEmpty()) { string text = tip.text; - tip.text = string.Concat(new string[] - { - text, - "\n\n", - "DisabledCommand".Translate(), - ": ", - this.disabledReason - }); + tip.text = text + "\n\n" + "DisabledCommand".Translate() + ": " + base.disabledReason; } TooltipHandler.TipRegion(rect, tip); } @@ -176,11 +168,11 @@ public override GizmoResult GizmoOnGUI(Vector2 topLeft) } if (flag2) { - if (this.disabled) + if (base.disabled) { - if (!this.disabledReason.NullOrEmpty()) + if (!base.disabledReason.NullOrEmpty()) { - Messages.Message(this.disabledReason, MessageSound.RejectInput); + Messages.Message(base.disabledReason, MessageSound.RejectInput); } return new GizmoResult(GizmoState.Mouseover, null); } @@ -192,20 +184,33 @@ public override GizmoResult GizmoOnGUI(Vector2 topLeft) TutorSystem.Notify_Event(this.TutorTagSelect); return result; } - else + if (flag) { - if (flag) - { - return new GizmoResult(GizmoState.Mouseover, null); - } - return new GizmoResult(GizmoState.Clear, null); + return new GizmoResult(GizmoState.Mouseover, null); } + return new GizmoResult(GizmoState.Clear, null); } public override bool GroupsWith(Gizmo other) { Command command = other as Command; - return command != null && ((this.hotKey == command.hotKey && this.Label == command.Label && this.icon == command.icon) || (this.groupKey != 0 && command.groupKey != 0 && this.groupKey == command.groupKey)); + if (command == null) + { + return false; + } + if (this.hotKey == command.hotKey && this.Label == command.Label && (Object)this.icon == (Object)command.icon) + { + return true; + } + if (((this.groupKey != 0) ? command.groupKey : 0) != 0) + { + if (this.groupKey == command.groupKey) + { + return true; + } + return false; + } + return false; } public override void ProcessInput(Event ev) @@ -219,21 +224,14 @@ public override void ProcessInput(Event ev) public override int GetHashCode() { int seed = 0; - seed = Gen.HashCombine(seed, this.hotKey); - seed = Gen.HashCombine(seed, this.icon); - return Gen.HashCombine(seed, this.defaultDesc); + seed = Gen.HashCombine(seed, this.hotKey); + seed = Gen.HashCombine(seed, this.icon); + return Gen.HashCombine(seed, this.defaultDesc); } public override string ToString() { - return string.Concat(new string[] - { - "Command(label=", - this.defaultLabel, - ", defaultDesc=", - this.defaultDesc, - ")" - }); + return "Command(label=" + this.defaultLabel + ", defaultDesc=" + this.defaultDesc + ")"; } } } diff --git a/Assembly-CSharp/Verse/Command_SetPlantToGrow.cs b/Assembly-CSharp/Verse/Command_SetPlantToGrow.cs index 61b777d31..c9767f92f 100644 --- a/Assembly-CSharp/Verse/Command_SetPlantToGrow.cs +++ b/Assembly-CSharp/Verse/Command_SetPlantToGrow.cs @@ -16,34 +16,40 @@ public class Command_SetPlantToGrow : Command public Command_SetPlantToGrow() { - this.tutorTag = "GrowingZoneSetPlant"; + base.tutorTag = "GrowingZoneSetPlant"; ThingDef thingDef = null; bool flag = false; - foreach (object current in Find.Selector.SelectedObjects) + List.Enumerator enumerator = Find.Selector.SelectedObjects.GetEnumerator(); + try { - IPlantToGrowSettable plantToGrowSettable = current as IPlantToGrowSettable; - if (plantToGrowSettable != null) + while (enumerator.MoveNext()) { - if (thingDef != null && thingDef != plantToGrowSettable.GetPlantDefToGrow()) + object current = enumerator.Current; + IPlantToGrowSettable plantToGrowSettable = current as IPlantToGrowSettable; + if (plantToGrowSettable != null) { - flag = true; - break; + if (thingDef != null && thingDef != plantToGrowSettable.GetPlantDefToGrow()) + { + flag = true; + break; + } + thingDef = plantToGrowSettable.GetPlantDefToGrow(); } - thingDef = plantToGrowSettable.GetPlantDefToGrow(); } } + finally + { + ((IDisposable)(object)enumerator).Dispose(); + } if (flag) { - this.icon = Command_SetPlantToGrow.SetPlantToGrowTex; - this.defaultLabel = "CommandSelectPlantToGrowMulti".Translate(); + base.icon = Command_SetPlantToGrow.SetPlantToGrowTex; + base.defaultLabel = "CommandSelectPlantToGrowMulti".Translate(); } else { - this.icon = thingDef.uiIcon; - this.defaultLabel = "CommandSelectPlantToGrow".Translate(new object[] - { - thingDef.label - }); + base.icon = thingDef.uiIcon; + base.defaultLabel = "CommandSelectPlantToGrow".Translate(thingDef.label); } } @@ -59,41 +65,32 @@ public override void ProcessInput(Event ev) { this.settables.Add(this.settable); } - foreach (ThingDef current in GenPlant.ValidPlantTypesForGrowers(this.settables)) + foreach (ThingDef item in GenPlant.ValidPlantTypesForGrowers(this.settables)) { - if (this.IsPlantAvailable(current)) + if (this.IsPlantAvailable(item)) { - ThingDef localPlantDef = current; - string text = current.LabelCap; - if (current.plant.sowMinSkill > 0) + ThingDef localPlantDef = item; + string text = item.LabelCap; + if (item.plant.sowMinSkill > 0) { string text2 = text; - text = string.Concat(new object[] - { - text2, - " (", - "MinSkill".Translate(), - ": ", - current.plant.sowMinSkill, - ")" - }); + text = text2 + " (" + "MinSkill".Translate() + ": " + item.plant.sowMinSkill + ")"; } - List arg_121_0 = list; - Func extraPartOnGUI = (Rect rect) => Widgets.InfoCardButton(rect.x + 5f, rect.y + (rect.height - 24f) / 2f, localPlantDef); - arg_121_0.Add(new FloatMenuOption(text, delegate + List obj = list; + Func extraPartOnGUI = (Func)((Rect rect) => Widgets.InfoCardButton((float)(rect.x + 5.0), (float)(rect.y + (rect.height - 24.0) / 2.0), localPlantDef)); + obj.Add(new FloatMenuOption(text, (Action)delegate { - string s = this.tutorTag + "-" + localPlantDef.defName; - if (!TutorSystem.AllowAction(s)) + string s = base.tutorTag + "-" + localPlantDef.defName; + if (TutorSystem.AllowAction(s)) { - return; + for (int i = 0; i < this.settables.Count; i++) + { + this.settables[i].SetPlantDefToGrow(localPlantDef); + } + PlayerKnowledgeDatabase.KnowledgeDemonstrated(ConceptDefOf.SetGrowingZonePlant, KnowledgeAmount.Total); + this.WarnAsAppropriate(localPlantDef); + TutorSystem.Notify_Event(s); } - for (int i = 0; i < this.settables.Count; i++) - { - this.settables[i].SetPlantDefToGrow(localPlantDef); - } - PlayerKnowledgeDatabase.KnowledgeDemonstrated(ConceptDefOf.SetGrowingZonePlant, KnowledgeAmount.Total); - this.WarnAsAppropriate(localPlantDef); - TutorSystem.Notify_Event(s); }, MenuOptionPriority.Default, null, null, 29f, extraPartOnGUI, null)); } } @@ -114,18 +111,12 @@ private void WarnAsAppropriate(ThingDef plantDef) { if (plantDef.plant.sowMinSkill > 0) { - foreach (Pawn current in this.settable.Map.mapPawns.FreeColonistsSpawned) + foreach (Pawn item in this.settable.Map.mapPawns.FreeColonistsSpawned) { - if (current.skills.GetSkill(SkillDefOf.Growing).Level >= plantDef.plant.sowMinSkill && !current.Downed && current.workSettings.WorkIsActive(WorkTypeDefOf.Growing)) - { + if (item.skills.GetSkill(SkillDefOf.Growing).Level >= plantDef.plant.sowMinSkill && !item.Downed && item.workSettings.WorkIsActive(WorkTypeDefOf.Growing)) return; - } } - Find.WindowStack.Add(new Dialog_MessageBox("NoGrowerCanPlant".Translate(new object[] - { - plantDef.label, - plantDef.plant.sowMinSkill - }).CapitalizeFirst(), null, null, null, null, null, false)); + Find.WindowStack.Add(new Dialog_MessageBox("NoGrowerCanPlant".Translate(plantDef.label, plantDef.plant.sowMinSkill).CapitalizeFirst(), (string)null, null, (string)null, null, (string)null, false)); } } diff --git a/Assembly-CSharp/Verse/Command_Settle.cs b/Assembly-CSharp/Verse/Command_Settle.cs index cdf30a1c7..9428a305c 100644 --- a/Assembly-CSharp/Verse/Command_Settle.cs +++ b/Assembly-CSharp/Verse/Command_Settle.cs @@ -1,5 +1,3 @@ -using System; - namespace Verse { public class Command_Settle : Command_Action diff --git a/Assembly-CSharp/Verse/Command_Target.cs b/Assembly-CSharp/Verse/Command_Target.cs index b44cf117f..d46d23b98 100644 --- a/Assembly-CSharp/Verse/Command_Target.cs +++ b/Assembly-CSharp/Verse/Command_Target.cs @@ -15,7 +15,7 @@ public override void ProcessInput(Event ev) { base.ProcessInput(ev); SoundDefOf.TickTiny.PlayOneShotOnCamera(null); - Find.Targeter.BeginTargeting(this.targetingParams, delegate(LocalTargetInfo target) + Find.Targeter.BeginTargeting(this.targetingParams, (Action)delegate(LocalTargetInfo target) { this.action(target.Thing); }, null, null, null); diff --git a/Assembly-CSharp/Verse/Command_Toggle.cs b/Assembly-CSharp/Verse/Command_Toggle.cs index ff37d217b..5b365e6e3 100644 --- a/Assembly-CSharp/Verse/Command_Toggle.cs +++ b/Assembly-CSharp/Verse/Command_Toggle.cs @@ -36,7 +36,7 @@ public override GizmoResult GizmoOnGUI(Vector2 loc) { GizmoResult result = base.GizmoOnGUI(loc); Rect rect = new Rect(loc.x, loc.y, this.Width, 75f); - Rect position = new Rect(rect.x + rect.width - 24f, rect.y, 24f, 24f); + Rect position = new Rect((float)(rect.x + rect.width - 24.0), rect.y, 24f, 24f); Texture2D image = (!this.isActive()) ? Widgets.CheckboxOffTex : Widgets.CheckboxOnTex; GUI.DrawTexture(position, image); return result; @@ -45,7 +45,11 @@ public override GizmoResult GizmoOnGUI(Vector2 loc) public override bool InheritInteractionsFrom(Gizmo other) { Command_Toggle command_Toggle = other as Command_Toggle; - return command_Toggle != null && command_Toggle.isActive() == this.isActive(); + if (command_Toggle != null) + { + return command_Toggle.isActive() == this.isActive(); + } + return false; } } } diff --git a/Assembly-CSharp/Verse/Command_VerbTarget.cs b/Assembly-CSharp/Verse/Command_VerbTarget.cs index 3d724f14c..49be84c58 100644 --- a/Assembly-CSharp/Verse/Command_VerbTarget.cs +++ b/Assembly-CSharp/Verse/Command_VerbTarget.cs @@ -1,5 +1,4 @@ using RimWorld; -using System; using UnityEngine; using Verse.Sound; diff --git a/Assembly-CSharp/Verse/CompAttachBase.cs b/Assembly-CSharp/Verse/CompAttachBase.cs index 57fdec78f..3ee5b07dc 100644 --- a/Assembly-CSharp/Verse/CompAttachBase.cs +++ b/Assembly-CSharp/Verse/CompAttachBase.cs @@ -1,4 +1,3 @@ -using System; using System.Collections.Generic; using System.Text; @@ -14,7 +13,7 @@ public override void CompTick() { for (int i = 0; i < this.attachments.Count; i++) { - this.attachments[i].Position = this.parent.Position; + this.attachments[i].Position = base.parent.Position; } } } @@ -24,9 +23,9 @@ public override void PostDestroy(DestroyMode mode, Map previousMap) base.PostDestroy(mode, previousMap); if (this.attachments != null) { - for (int i = this.attachments.Count - 1; i >= 0; i--) + for (int num = this.attachments.Count - 1; num >= 0; num--) { - this.attachments[i].Destroy(DestroyMode.Vanish); + this.attachments[num].Destroy(DestroyMode.Vanish); } } } @@ -42,7 +41,7 @@ public override string CompInspectStringExtra() } return stringBuilder.ToString().TrimEndNewlines(); } - return null; + return (string)null; } public Thing GetAttachment(ThingDef def) diff --git a/Assembly-CSharp/Verse/CompColorable.cs b/Assembly-CSharp/Verse/CompColorable.cs index 598fbdc80..831198f5f 100644 --- a/Assembly-CSharp/Verse/CompColorable.cs +++ b/Assembly-CSharp/Verse/CompColorable.cs @@ -1,4 +1,3 @@ -using System; using UnityEngine; namespace Verse @@ -15,19 +14,18 @@ public Color Color { if (!this.active) { - return this.parent.def.graphicData.color; + return base.parent.def.graphicData.color; } return this.color; } set { - if (value == this.color) + if (!(value == this.color)) { - return; + this.active = true; + this.color = value; + base.parent.Notify_ColorChanged(); } - this.active = true; - this.color = value; - this.parent.Notify_ColorChanged(); } } @@ -42,9 +40,11 @@ public bool Active public override void Initialize(CompProperties props) { base.Initialize(props); - if (this.parent.def.colorGenerator != null && (this.parent.Stuff == null || this.parent.Stuff.stuffProps.allowColorGenerators)) + if (base.parent.def.colorGenerator != null) { - this.Color = this.parent.def.colorGenerator.NewRandomizedColor(); + if (base.parent.Stuff != null && !base.parent.Stuff.stuffProps.allowColorGenerators) + return; + this.Color = base.parent.def.colorGenerator.NewRandomizedColor(); } } @@ -52,9 +52,7 @@ public override void PostExposeData() { base.PostExposeData(); if (Scribe.mode == LoadSaveMode.Saving && !this.active) - { return; - } Scribe_Values.Look(ref this.color, "color", default(Color), false); Scribe_Values.Look(ref this.active, "colorActive", false, false); } diff --git a/Assembly-CSharp/Verse/CompColorableUtility.cs b/Assembly-CSharp/Verse/CompColorableUtility.cs index 4bdc93de0..b03df0c3c 100644 --- a/Assembly-CSharp/Verse/CompColorableUtility.cs +++ b/Assembly-CSharp/Verse/CompColorableUtility.cs @@ -1,4 +1,3 @@ -using System; using UnityEngine; namespace Verse @@ -14,20 +13,21 @@ public static void SetColor(this Thing t, Color newColor, bool reportFailure = t { Log.Error("SetColor on non-ThingWithComps " + t); } - return; } - CompColorable comp = thingWithComps.GetComp(); - if (comp == null) + else { - if (reportFailure) + CompColorable comp = thingWithComps.GetComp(); + if (comp == null) { - Log.Error("SetColor on Thing without CompColorable " + t); + if (reportFailure) + { + Log.Error("SetColor on Thing without CompColorable " + t); + } + } + else if (comp.Color != newColor) + { + comp.Color = newColor; } - return; - } - if (comp.Color != newColor) - { - comp.Color = newColor; } } } diff --git a/Assembly-CSharp/Verse/CompEquippable.cs b/Assembly-CSharp/Verse/CompEquippable.cs index 222a6b44c..f6823462e 100644 --- a/Assembly-CSharp/Verse/CompEquippable.cs +++ b/Assembly-CSharp/Verse/CompEquippable.cs @@ -1,4 +1,3 @@ -using System; using System.Collections.Generic; using UnityEngine; @@ -44,7 +43,7 @@ public List VerbProperties { get { - return this.parent.def.Verbs; + return base.parent.def.Verbs; } } @@ -61,7 +60,7 @@ public IEnumerable GetVerbsCommands() public override void PostDestroy(DestroyMode mode, Map previousMap) { base.PostDestroy(mode, previousMap); - if (this.Holder != null && this.Holder.equipment != null && this.Holder.equipment.Primary == this.parent) + if (this.Holder != null && this.Holder.equipment != null && this.Holder.equipment.Primary == base.parent) { this.Holder.equipment.Notify_PrimaryDestroyed(); } @@ -70,7 +69,7 @@ public override void PostDestroy(DestroyMode mode, Map previousMap) public override void PostExposeData() { base.PostExposeData(); - Scribe_Deep.Look(ref this.verbTracker, "verbTracker", new object[] + Scribe_Deep.Look(ref this.verbTracker, "verbTracker", new object[1] { this }); diff --git a/Assembly-CSharp/Verse/CompGlower.cs b/Assembly-CSharp/Verse/CompGlower.cs index 67ffe9b0b..252bb5eed 100644 --- a/Assembly-CSharp/Verse/CompGlower.cs +++ b/Assembly-CSharp/Verse/CompGlower.cs @@ -1,5 +1,4 @@ using RimWorld; -using System; namespace Verse { @@ -11,7 +10,7 @@ public CompProperties_Glower Props { get { - return (CompProperties_Glower)this.props; + return (CompProperties_Glower)base.props; } } @@ -19,41 +18,44 @@ private bool ShouldBeLitNow { get { - if (!this.parent.Spawned) + if (!base.parent.Spawned) { return false; } - if (!FlickUtility.WantsToBeOn(this.parent)) + if (!FlickUtility.WantsToBeOn(base.parent)) { return false; } - CompPowerTrader compPowerTrader = this.parent.TryGetComp(); + CompPowerTrader compPowerTrader = base.parent.TryGetComp(); if (compPowerTrader != null && !compPowerTrader.PowerOn) { return false; } - CompRefuelable compRefuelable = this.parent.TryGetComp(); - return compRefuelable == null || compRefuelable.HasFuel; + CompRefuelable compRefuelable = base.parent.TryGetComp(); + if (compRefuelable != null && !compRefuelable.HasFuel) + { + return false; + } + return true; } } public void UpdateLit(Map map) { bool shouldBeLitNow = this.ShouldBeLitNow; - if (this.glowOnInt == shouldBeLitNow) - { - return; - } - this.glowOnInt = shouldBeLitNow; - if (!this.glowOnInt) - { - map.mapDrawer.MapMeshDirty(this.parent.Position, MapMeshFlag.Things); - map.glowGrid.DeRegisterGlower(this); - } - else + if (this.glowOnInt != shouldBeLitNow) { - map.mapDrawer.MapMeshDirty(this.parent.Position, MapMeshFlag.Things); - map.glowGrid.RegisterGlower(this); + this.glowOnInt = shouldBeLitNow; + if (!this.glowOnInt) + { + map.mapDrawer.MapMeshDirty(base.parent.Position, MapMeshFlag.Things); + map.glowGrid.DeRegisterGlower(this); + } + else + { + map.mapDrawer.MapMeshDirty(base.parent.Position, MapMeshFlag.Things); + map.glowGrid.RegisterGlower(this); + } } } @@ -61,21 +63,20 @@ public override void PostSpawnSetup(bool respawningAfterLoad) { if (this.ShouldBeLitNow) { - this.UpdateLit(this.parent.Map); - this.parent.Map.glowGrid.RegisterGlower(this); + this.UpdateLit(base.parent.Map); + base.parent.Map.glowGrid.RegisterGlower(this); } else { - this.UpdateLit(this.parent.Map); + this.UpdateLit(base.parent.Map); } } public override void ReceiveCompSignal(string signal) { - if (signal == "PowerTurnedOn" || signal == "PowerTurnedOff" || signal == "FlickedOn" || signal == "FlickedOff" || signal == "Refueled" || signal == "RanOutOfFuel" || signal == "ScheduledOn" || signal == "ScheduledOff") - { - this.UpdateLit(this.parent.Map); - } + if (!(signal == "PowerTurnedOn") && !(signal == "PowerTurnedOff") && !(signal == "FlickedOn") && !(signal == "FlickedOff") && !(signal == "Refueled") && !(signal == "RanOutOfFuel") && !(signal == "ScheduledOn") && !(signal == "ScheduledOff")) + return; + this.UpdateLit(base.parent.Map); } public override void PostExposeData() diff --git a/Assembly-CSharp/Verse/CompHeatPusher.cs b/Assembly-CSharp/Verse/CompHeatPusher.cs index eb74202aa..ca3b846ba 100644 --- a/Assembly-CSharp/Verse/CompHeatPusher.cs +++ b/Assembly-CSharp/Verse/CompHeatPusher.cs @@ -1,5 +1,3 @@ -using System; - namespace Verse { public class CompHeatPusher : ThingComp @@ -10,7 +8,7 @@ public CompProperties_HeatPusher Props { get { - return (CompProperties_HeatPusher)this.props; + return (CompProperties_HeatPusher)base.props; } } @@ -25,13 +23,13 @@ protected virtual bool ShouldPushHeatNow public override void CompTick() { base.CompTick(); - if (this.parent.IsHashIntervalTick(60) && this.ShouldPushHeatNow) + if (base.parent.IsHashIntervalTick(60) && this.ShouldPushHeatNow) { CompProperties_HeatPusher props = this.Props; - float ambientTemperature = this.parent.AmbientTemperature; + float ambientTemperature = base.parent.AmbientTemperature; if (ambientTemperature < props.heatPushMaxTemperature && ambientTemperature > props.heatPushMinTemperature) { - GenTemperature.PushHeat(this.parent.Position, this.parent.Map, props.heatPerSecond); + GenTemperature.PushHeat(base.parent.Position, base.parent.Map, props.heatPerSecond); } } } diff --git a/Assembly-CSharp/Verse/CompHeatPusherPowered.cs b/Assembly-CSharp/Verse/CompHeatPusherPowered.cs index 24b408961..c095e0be1 100644 --- a/Assembly-CSharp/Verse/CompHeatPusherPowered.cs +++ b/Assembly-CSharp/Verse/CompHeatPusherPowered.cs @@ -1,5 +1,4 @@ using RimWorld; -using System; namespace Verse { @@ -15,16 +14,20 @@ protected override bool ShouldPushHeatNow { get { - return FlickUtility.WantsToBeOn(this.parent) && (this.powerComp == null || this.powerComp.PowerOn) && (this.refuelableComp == null || this.refuelableComp.HasFuel) && (this.breakdownableComp == null || !this.breakdownableComp.BrokenDown); + if (FlickUtility.WantsToBeOn(base.parent) && (this.powerComp == null || this.powerComp.PowerOn) && (this.refuelableComp == null || this.refuelableComp.HasFuel) && (this.breakdownableComp == null || !this.breakdownableComp.BrokenDown)) + { + return true; + } + return false; } } public override void PostSpawnSetup(bool respawningAfterLoad) { base.PostSpawnSetup(respawningAfterLoad); - this.powerComp = this.parent.GetComp(); - this.refuelableComp = this.parent.GetComp(); - this.breakdownableComp = this.parent.GetComp(); + this.powerComp = base.parent.GetComp(); + this.refuelableComp = base.parent.GetComp(); + this.breakdownableComp = base.parent.GetComp(); } } } diff --git a/Assembly-CSharp/Verse/CompLifespan.cs b/Assembly-CSharp/Verse/CompLifespan.cs index cea1ef070..7cb1fa1cd 100644 --- a/Assembly-CSharp/Verse/CompLifespan.cs +++ b/Assembly-CSharp/Verse/CompLifespan.cs @@ -1,5 +1,4 @@ using RimWorld; -using System; namespace Verse { @@ -11,7 +10,7 @@ public CompProperties_Lifespan Props { get { - return (CompProperties_Lifespan)this.props; + return (CompProperties_Lifespan)base.props; } } @@ -26,7 +25,7 @@ public override void CompTick() this.age++; if (this.age >= this.Props.lifespanTicks) { - this.parent.Destroy(DestroyMode.Vanish); + base.parent.Destroy(DestroyMode.Vanish); } } @@ -35,7 +34,7 @@ public override void CompTickRare() this.age += 250; if (this.age >= this.Props.lifespanTicks) { - this.parent.Destroy(DestroyMode.Vanish); + base.parent.Destroy(DestroyMode.Vanish); } } diff --git a/Assembly-CSharp/Verse/CompProperties.cs b/Assembly-CSharp/Verse/CompProperties.cs index 644cbef7c..595e22c18 100644 --- a/Assembly-CSharp/Verse/CompProperties.cs +++ b/Assembly-CSharp/Verse/CompProperties.cs @@ -1,7 +1,6 @@ using RimWorld; using System; using System.Collections.Generic; -using System.Diagnostics; namespace Verse { @@ -18,29 +17,21 @@ public CompProperties(Type compClass) this.compClass = compClass; } - [DebuggerHidden] public virtual IEnumerable ConfigErrors(ThingDef parentDef) { - CompProperties.c__Iterator78 c__Iterator = new CompProperties.c__Iterator78(); - c__Iterator.parentDef = parentDef; - c__Iterator.<$>parentDef = parentDef; - c__Iterator.<>f__this = this; - CompProperties.c__Iterator78 expr_1C = c__Iterator; - expr_1C.$PC = -2; - return expr_1C; + if (this.compClass == null) + { + yield return parentDef.defName + " has CompProperties with null compClass."; + } } public virtual void ResolveReferences(ThingDef parentDef) { } - [DebuggerHidden] public virtual IEnumerable SpecialDisplayStats() { - CompProperties.c__Iterator79 c__Iterator = new CompProperties.c__Iterator79(); - CompProperties.c__Iterator79 expr_07 = c__Iterator; - expr_07.$PC = -2; - return expr_07; + yield break; } } } diff --git a/Assembly-CSharp/Verse/CompProperties_HeatPusher.cs b/Assembly-CSharp/Verse/CompProperties_HeatPusher.cs index f28d56991..5da454dba 100644 --- a/Assembly-CSharp/Verse/CompProperties_HeatPusher.cs +++ b/Assembly-CSharp/Verse/CompProperties_HeatPusher.cs @@ -1,5 +1,3 @@ -using System; - namespace Verse { public class CompProperties_HeatPusher : CompProperties @@ -12,7 +10,7 @@ public class CompProperties_HeatPusher : CompProperties public CompProperties_HeatPusher() { - this.compClass = typeof(CompHeatPusher); + base.compClass = typeof(CompHeatPusher); } } } diff --git a/Assembly-CSharp/Verse/CompProperties_Lifespan.cs b/Assembly-CSharp/Verse/CompProperties_Lifespan.cs index ca146054e..5c5a77cde 100644 --- a/Assembly-CSharp/Verse/CompProperties_Lifespan.cs +++ b/Assembly-CSharp/Verse/CompProperties_Lifespan.cs @@ -1,5 +1,3 @@ -using System; - namespace Verse { public class CompProperties_Lifespan : CompProperties @@ -8,7 +6,7 @@ public class CompProperties_Lifespan : CompProperties public CompProperties_Lifespan() { - this.compClass = typeof(CompLifespan); + base.compClass = typeof(CompLifespan); } } } diff --git a/Assembly-CSharp/Verse/CompProperties_TemperatureDamaged.cs b/Assembly-CSharp/Verse/CompProperties_TemperatureDamaged.cs index 770da7c4c..1325082bc 100644 --- a/Assembly-CSharp/Verse/CompProperties_TemperatureDamaged.cs +++ b/Assembly-CSharp/Verse/CompProperties_TemperatureDamaged.cs @@ -1,5 +1,3 @@ -using System; - namespace Verse { public class CompProperties_TemperatureDamaged : CompProperties @@ -10,7 +8,7 @@ public class CompProperties_TemperatureDamaged : CompProperties public CompProperties_TemperatureDamaged() { - this.compClass = typeof(CompTemperatureDamaged); + base.compClass = typeof(CompTemperatureDamaged); } } } diff --git a/Assembly-CSharp/Verse/CompTemperatureDamaged.cs b/Assembly-CSharp/Verse/CompTemperatureDamaged.cs index e1255e129..8be3a947f 100644 --- a/Assembly-CSharp/Verse/CompTemperatureDamaged.cs +++ b/Assembly-CSharp/Verse/CompTemperatureDamaged.cs @@ -1,5 +1,4 @@ using RimWorld; -using System; namespace Verse { @@ -9,7 +8,7 @@ public CompProperties_TemperatureDamaged Props { get { - return (CompProperties_TemperatureDamaged)this.props; + return (CompProperties_TemperatureDamaged)base.props; } } @@ -20,9 +19,9 @@ public override void CompTick() public override void CompTickRare() { - if (!this.Props.safeTemperatureRange.Includes(this.parent.AmbientTemperature)) + if (!this.Props.safeTemperatureRange.Includes(base.parent.AmbientTemperature)) { - this.parent.TakeDamage(new DamageInfo(DamageDefOf.Deterioration, this.Props.damagePerTickRare, -1f, null, null, null, DamageInfo.SourceCategory.ThingOrUnknown)); + base.parent.TakeDamage(new DamageInfo(DamageDefOf.Deterioration, this.Props.damagePerTickRare, -1f, null, null, null, DamageInfo.SourceCategory.ThingOrUnknown)); } } } diff --git a/Assembly-CSharp/Verse/CompressibilityDecider.cs b/Assembly-CSharp/Verse/CompressibilityDecider.cs index d8706c63d..485e4016e 100644 --- a/Assembly-CSharp/Verse/CompressibilityDecider.cs +++ b/Assembly-CSharp/Verse/CompressibilityDecider.cs @@ -21,14 +21,14 @@ public CompressibilityDecider(Map map) public void DetermineReferences() { this.referencedThings.Clear(); - foreach (Thing current in from des in this.map.designationManager.allDesignations + foreach (Thing item in from des in this.map.designationManager.allDesignations select des.target.Thing) { - this.referencedThings.Add(current); + this.referencedThings.Add(item); } - foreach (Thing current2 in this.map.reservationManager.AllReservedThings()) + foreach (Thing item2 in this.map.reservationManager.AllReservedThings()) { - this.referencedThings.Add(current2); + this.referencedThings.Add(item2); } List allPawnsSpawned = this.map.mapPawns.AllPawnsSpawned; for (int i = 0; i < allPawnsSpawned.Count; i++) diff --git a/Assembly-CSharp/Verse/CompressibilityDeciderUtility.cs b/Assembly-CSharp/Verse/CompressibilityDeciderUtility.cs index aac4810b0..66b5a4ac2 100644 --- a/Assembly-CSharp/Verse/CompressibilityDeciderUtility.cs +++ b/Assembly-CSharp/Verse/CompressibilityDeciderUtility.cs @@ -1,4 +1,3 @@ -using System; using System.Collections.Generic; namespace Verse diff --git a/Assembly-CSharp/Verse/ContentFinder.cs b/Assembly-CSharp/Verse/ContentFinder.cs index 7d96a85f5..eb09803a9 100644 --- a/Assembly-CSharp/Verse/ContentFinder.cs +++ b/Assembly-CSharp/Verse/ContentFinder.cs @@ -1,6 +1,4 @@ -using System; using System.Collections.Generic; -using System.Diagnostics; using UnityEngine; namespace Verse @@ -12,53 +10,70 @@ public static T Get(string itemPath, bool reportFailure = true) if (!UnityData.IsInMainThread) { Log.Error("Tried to get a resource \"" + itemPath + "\" from a different thread. All resources must be loaded in the main thread."); - return (T)((object)null); + return (T)null; } - T t = (T)((object)null); - foreach (ModContentPack current in LoadedModManager.RunningMods) + T val = (T)null; + foreach (ModContentPack runningMod in LoadedModManager.RunningMods) { - t = current.GetContentHolder().Get(itemPath); - if (t != null) + val = runningMod.GetContentHolder().Get(itemPath); + if (val != null) { - T result = t; - return result; + return val; } } if (typeof(T) == typeof(Texture2D)) { - t = (T)((object)Resources.Load(GenFilePaths.ContentPath() + itemPath)); + val = (T)(object)Resources.Load(GenFilePaths.ContentPath() + itemPath); } if (typeof(T) == typeof(AudioClip)) { - t = (T)((object)Resources.Load(GenFilePaths.ContentPath() + itemPath)); + val = (T)(object)Resources.Load(GenFilePaths.ContentPath() + itemPath); } - if (t != null) + if (val != null) { - return t; + return val; } if (reportFailure) { - Log.Error(string.Concat(new object[] - { - "Could not load ", - typeof(T), - " at ", - itemPath, - " in any active mod or in base resources." - })); + Log.Error("Could not load " + typeof(T) + " at " + itemPath + " in any active mod or in base resources."); } - return (T)((object)null); + return (T)null; } - [DebuggerHidden] public static IEnumerable GetAllInFolder(string folderPath) { - ContentFinder.c__Iterator20E c__Iterator20E = new ContentFinder.c__Iterator20E(); - c__Iterator20E.folderPath = folderPath; - c__Iterator20E.<$>folderPath = folderPath; - ContentFinder.c__Iterator20E expr_15 = c__Iterator20E; - expr_15.$PC = -2; - return expr_15; + if (!UnityData.IsInMainThread) + { + Log.Error("Tried to get all resources in a folder \"" + folderPath + "\" from a different thread. All resources must be loaded in the main thread."); + } + else + { + foreach (ModContentPack runningMod in LoadedModManager.RunningMods) + { + foreach (T item2 in runningMod.GetContentHolder().GetAllUnderPath(folderPath)) + { + yield return item2; + } + } + T[] items = null; + if (typeof(T) == typeof(Texture2D)) + { + items = (T[])Resources.LoadAll(GenFilePaths.ContentPath() + folderPath); + } + if (typeof(T) == typeof(AudioClip)) + { + items = (T[])Resources.LoadAll(GenFilePaths.ContentPath() + folderPath); + } + if (items != null) + { + T[] array = items; + for (int i = 0; i < array.Length; i++) + { + T item = array[i]; + yield return item; + } + } + } } } } diff --git a/Assembly-CSharp/Verse/ContentSource.cs b/Assembly-CSharp/Verse/ContentSource.cs index cf5b6a0a3..cb0fd27d9 100644 --- a/Assembly-CSharp/Verse/ContentSource.cs +++ b/Assembly-CSharp/Verse/ContentSource.cs @@ -1,11 +1,9 @@ -using System; - namespace Verse { public enum ContentSource { - Undefined, - LocalFolder, - SteamWorkshop + Undefined = 0, + LocalFolder = 1, + SteamWorkshop = 2 } } diff --git a/Assembly-CSharp/Verse/ContentSourceUtility.cs b/Assembly-CSharp/Verse/ContentSourceUtility.cs index adff3ed7c..87490135e 100644 --- a/Assembly-CSharp/Verse/ContentSourceUtility.cs +++ b/Assembly-CSharp/Verse/ContentSourceUtility.cs @@ -17,23 +17,31 @@ public static Texture2D GetIcon(this ContentSource s) switch (s) { case ContentSource.Undefined: + { return BaseContent.BadTex; + } case ContentSource.LocalFolder: + { return ContentSourceUtility.ContentSourceIcon_LocalFolder; + } case ContentSource.SteamWorkshop: + { return ContentSourceUtility.ContentSourceIcon_SteamWorkshop; + } default: + { throw new NotImplementedException(); } + } } public static void DrawContentSource(Rect r, ContentSource source, Action clickAction = null) { - Rect rect = new Rect(r.x, r.y + r.height / 2f - 12f, 24f, 24f); + Rect rect = new Rect(r.x, (float)(r.y + r.height / 2.0 - 12.0), 24f, 24f); GUI.DrawTexture(rect, source.GetIcon()); Widgets.DrawHighlightIfMouseover(rect); - TooltipHandler.TipRegion(rect, () => "Source".Translate() + ": " + source.HumanLabel(), (int)(r.x + r.y * 56161f)); - if (clickAction != null && Widgets.ButtonInvisible(rect, false)) + TooltipHandler.TipRegion(rect, (Func)(() => "Source".Translate() + ": " + source.HumanLabel()), (int)(r.x + r.y * 56161.0)); + if ((object)clickAction != null && Widgets.ButtonInvisible(rect, false)) { clickAction(); } @@ -41,7 +49,7 @@ public static void DrawContentSource(Rect r, ContentSource source, Action clickA public static string HumanLabel(this ContentSource s) { - return ("ContentSource_" + s.ToString()).Translate(); + return ("ContentSource_" + ((Enum)(object)s).ToString()).Translate(); } } } diff --git a/Assembly-CSharp/Verse/Corpse.cs b/Assembly-CSharp/Verse/Corpse.cs index d0a4f67bd..415261c91 100644 --- a/Assembly-CSharp/Verse/Corpse.cs +++ b/Assembly-CSharp/Verse/Corpse.cs @@ -2,7 +2,6 @@ using RimWorld.Planet; using System; using System.Collections.Generic; -using System.Diagnostics; using System.Linq; using System.Text; using UnityEngine; @@ -60,10 +59,7 @@ public override string Label { get { - return "DeadLabel".Translate(new object[] - { - this.InnerPawn.LabelCap - }); + return "DeadLabel".Translate(this.InnerPawn.LabelCap); } } @@ -76,7 +72,19 @@ public override bool IngestibleNow Log.Error("IngestibleNow on Corpse while Bugged."); return false; } - return base.IngestibleNow && this.InnerPawn.RaceProps.IsFlesh && this.GetRotStage() == RotStage.Fresh; + if (!base.IngestibleNow) + { + return false; + } + if (!this.InnerPawn.RaceProps.IsFlesh) + { + return false; + } + if (this.GetRotStage() != 0) + { + return false; + } + return true; } } @@ -112,11 +120,18 @@ public override IEnumerable SpecialDisplayStats { get { - Corpse.<>c__Iterator22A <>c__Iterator22A = new Corpse.<>c__Iterator22A(); - <>c__Iterator22A.<>f__this = this; - Corpse.<>c__Iterator22A expr_0E = <>c__Iterator22A; - expr_0E.$PC = -2; - return expr_0E; + foreach (StatDrawEntry specialDisplayStat in base.SpecialDisplayStats) + { + yield return specialDisplayStat; + } + if (this.GetRotStage() == RotStage.Fresh) + { + yield return new StatDrawEntry(StatCategoryDefOf.Basics, "Nutrition".Translate(), FoodUtility.GetBodyPartNutrition(this.InnerPawn, this.InnerPawn.RaceProps.body.corePart).ToString("0.##"), 0); + StatDef meatAmount = StatDefOf.MeatAmount; + yield return new StatDrawEntry(meatAmount.category, meatAmount, this.InnerPawn.GetStatValue(meatAmount, true), StatRequest.For(this.InnerPawn), ToStringNumberSense.Undefined); + StatDef leatherAmount = StatDefOf.LeatherAmount; + yield return new StatDrawEntry(leatherAmount.category, leatherAmount, this.InnerPawn.GetStatValue(leatherAmount, true), StatRequest.For(this.InnerPawn), ToStringNumberSense.Undefined); + } } } @@ -132,11 +147,7 @@ public IEnumerable IngredientStackCells { get { - Corpse.<>c__Iterator22B <>c__Iterator22B = new Corpse.<>c__Iterator22B(); - <>c__Iterator22B.<>f__this = this; - Corpse.<>c__Iterator22B expr_0E = <>c__Iterator22B; - expr_0E.$PC = -2; - return expr_0E; + yield return this.InteractionCell; } } @@ -179,15 +190,17 @@ public override void SpawnSetup(Map map, bool respawningAfterLoad) if (this.Bugged) { Log.Error(this + " spawned in bugged state."); - return; } - base.SpawnSetup(map, respawningAfterLoad); - if (this.timeOfDeath < 0) + else { - this.timeOfDeath = Find.TickManager.TicksGame; + base.SpawnSetup(map, respawningAfterLoad); + if (this.timeOfDeath < 0) + { + this.timeOfDeath = Find.TickManager.TicksGame; + } + this.InnerPawn.Rotation = Rot4.South; + this.NotifyColonistBar(); } - this.InnerPawn.Rotation = Rot4.South; - this.NotifyColonistBar(); } public override void DeSpawn() @@ -239,24 +252,25 @@ public static void PostCorpseDestroy(Pawn pawn) public override void TickRare() { base.TickRare(); - if (base.Destroyed) + if (!base.Destroyed) { - return; - } - if (this.Bugged) - { - Log.Error(this + " has null innerPawn. Destroying."); - this.Destroy(DestroyMode.Vanish); - return; - } - this.InnerPawn.TickRare(); - if (this.vanishAfterTimestamp < 0 || this.GetRotStage() != RotStage.Dessicated) - { - this.vanishAfterTimestamp = this.Age + 6000000; - } - if (this.ShouldVanish) - { - this.Destroy(DestroyMode.Vanish); + if (this.Bugged) + { + Log.Error(this + " has null innerPawn. Destroying."); + this.Destroy(DestroyMode.Vanish); + } + else + { + this.InnerPawn.TickRare(); + if (this.vanishAfterTimestamp < 0 || this.GetRotStage() != RotStage.Dessicated) + { + this.vanishAfterTimestamp = this.Age + 6000000; + } + if (this.ShouldVanish) + { + this.Destroy(DestroyMode.Vanish); + } + } } } @@ -265,13 +279,7 @@ protected override void IngestedCalculateAmounts(Pawn ingester, float nutritionW BodyPartRecord bodyPartRecord = this.GetBestBodyPartToEat(ingester, nutritionWanted); if (bodyPartRecord == null) { - Log.Error(string.Concat(new object[] - { - ingester, - " ate ", - this, - " but no body part was found. Replacing with core part." - })); + Log.Error(ingester + " ate " + this + " but no body part was found. Replacing with core part."); bodyPartRecord = this.InnerPawn.RaceProps.body.corePart; } float bodyPartNutrition = FoodUtility.GetBodyPartNutrition(this.InnerPawn, bodyPartRecord); @@ -279,11 +287,7 @@ protected override void IngestedCalculateAmounts(Pawn ingester, float nutritionW { if (PawnUtility.ShouldSendNotificationAbout(this.InnerPawn) && this.InnerPawn.RaceProps.Humanlike) { - Messages.Message("MessageEatenByPredator".Translate(new object[] - { - this.InnerPawn.LabelShort, - ingester.LabelIndefinite() - }).CapitalizeFirst(), ingester, MessageSound.Negative); + Messages.Message("MessageEatenByPredator".Translate(this.InnerPawn.LabelShort, ingester.LabelIndefinite()).CapitalizeFirst(), (Thing)ingester, MessageSound.Negative); } numTaken = 1; } @@ -292,28 +296,47 @@ protected override void IngestedCalculateAmounts(Pawn ingester, float nutritionW Hediff_MissingPart hediff_MissingPart = (Hediff_MissingPart)HediffMaker.MakeHediff(HediffDefOf.MissingBodyPart, this.InnerPawn, bodyPartRecord); hediff_MissingPart.lastInjury = HediffDefOf.Bite; hediff_MissingPart.IsFresh = true; - this.InnerPawn.health.AddHediff(hediff_MissingPart, null, null); + this.InnerPawn.health.AddHediff(hediff_MissingPart, null, default(DamageInfo?)); numTaken = 0; } - if (ingester.RaceProps.Humanlike && Rand.Value < 0.05f) + if (ingester.RaceProps.Humanlike && Rand.Value < 0.05000000074505806) { FoodUtility.AddFoodPoisoningHediff(ingester, this); } nutritionIngested = bodyPartNutrition; } - [DebuggerHidden] public override IEnumerable ButcherProducts(Pawn butcher, float efficiency) { - Corpse.c__Iterator22C c__Iterator22C = new Corpse.c__Iterator22C(); - c__Iterator22C.butcher = butcher; - c__Iterator22C.efficiency = efficiency; - c__Iterator22C.<$>butcher = butcher; - c__Iterator22C.<$>efficiency = efficiency; - c__Iterator22C.<>f__this = this; - Corpse.c__Iterator22C expr_2A = c__Iterator22C; - expr_2A.$PC = -2; - return expr_2A; + foreach (Thing item in this.InnerPawn.ButcherProducts(butcher, efficiency)) + { + yield return item; + } + if (this.InnerPawn.RaceProps.BloodDef != null) + { + FilthMaker.MakeFilth(butcher.Position, butcher.Map, this.InnerPawn.RaceProps.BloodDef, this.InnerPawn.LabelIndefinite(), 1); + } + if (this.InnerPawn.RaceProps.Humanlike) + { + butcher.needs.mood.thoughts.memories.TryGainMemory(ThoughtDefOf.ButcheredHumanlikeCorpse, null); + List.Enumerator enumerator2 = butcher.Map.mapPawns.SpawnedPawnsInFaction(butcher.Faction).GetEnumerator(); + try + { + while (enumerator2.MoveNext()) + { + Pawn p = enumerator2.Current; + if (p != butcher && p.needs != null && p.needs.mood != null && p.needs.mood.thoughts != null) + { + p.needs.mood.thoughts.memories.TryGainMemory(ThoughtDefOf.KnowButcheredHumanlikeCorpse, null); + } + } + } + finally + { + ((IDisposable)(object)enumerator2).Dispose(); + } + TaleRecorder.RecordTale(TaleDefOf.ButcheredHumanlikeCorpse, butcher); + } } public override void ExposeData() @@ -322,11 +345,11 @@ public override void ExposeData() Scribe_Values.Look(ref this.timeOfDeath, "timeOfDeath", 0, false); Scribe_Values.Look(ref this.vanishAfterTimestamp, "vanishAfterTimestamp", 0, false); Scribe_Values.Look(ref this.everBuriedInSarcophagus, "everBuriedInSarcophagus", false, false); - Scribe_Deep.Look(ref this.operationsBillStack, "operationsBillStack", new object[] + Scribe_Deep.Look(ref this.operationsBillStack, "operationsBillStack", new object[1] { this }); - Scribe_Deep.Look>(ref this.innerContainer, "innerContainer", new object[] + Scribe_Deep.Look>(ref this.innerContainer, "innerContainer", new object[1] { this }); @@ -341,9 +364,7 @@ public override void DrawAt(Vector3 drawLoc, bool flip = false) { Building building = this.StoringBuilding(); if (building != null && building.def == ThingDefOf.Grave) - { return; - } this.InnerPawn.Drawer.renderer.RenderPawnAt(drawLoc); } @@ -353,17 +374,10 @@ public Thought_Memory GiveObservedThought() { return null; } - if (this.StoringBuilding() == null) + Thing thing = this.StoringBuilding(); + if (thing == null) { - Thought_MemoryObservation thought_MemoryObservation; - if (this.IsNotFresh()) - { - thought_MemoryObservation = (Thought_MemoryObservation)ThoughtMaker.MakeThought(ThoughtDefOf.ObservedLayingRottingCorpse); - } - else - { - thought_MemoryObservation = (Thought_MemoryObservation)ThoughtMaker.MakeThought(ThoughtDefOf.ObservedLayingCorpse); - } + Thought_MemoryObservation thought_MemoryObservation = (!this.IsNotFresh()) ? ((Thought_MemoryObservation)ThoughtMaker.MakeThought(ThoughtDefOf.ObservedLayingCorpse)) : ((Thought_MemoryObservation)ThoughtMaker.MakeThought(ThoughtDefOf.ObservedLayingRottingCorpse)); thought_MemoryObservation.Target = this; return thought_MemoryObservation; } @@ -377,12 +391,9 @@ public override string GetInspectString() { stringBuilder.AppendLine("Faction".Translate() + ": " + this.InnerPawn.Faction.Name); } - stringBuilder.AppendLine("DeadTime".Translate(new object[] - { - this.Age.ToStringTicksToPeriod(false, false, true) - })); - float num = 1f - this.InnerPawn.health.hediffSet.GetCoverageOfNotMissingNaturalParts(this.InnerPawn.RaceProps.body.corePart); - if (num != 0f) + stringBuilder.AppendLine("DeadTime".Translate(this.Age.ToStringTicksToPeriod(false, false, true))); + float num = (float)(1.0 - this.InnerPawn.health.hediffSet.GetCoverageOfNotMissingNaturalParts(this.InnerPawn.RaceProps.body.corePart)); + if (num != 0.0) { stringBuilder.AppendLine("CorpsePercentMissing".Translate() + ": " + num.ToStringPercent()); } @@ -399,13 +410,13 @@ public void RotStageChanged() private BodyPartRecord GetBestBodyPartToEat(Pawn ingester, float nutritionWanted) { IEnumerable source = from x in this.InnerPawn.health.hediffSet.GetNotMissingParts(BodyPartHeight.Undefined, BodyPartDepth.Undefined) - where x.depth == BodyPartDepth.Outside && FoodUtility.GetBodyPartNutrition(this.InnerPawn, x) > 0.001f + where x.depth == BodyPartDepth.Outside && FoodUtility.GetBodyPartNutrition(this.InnerPawn, x) > 0.0010000000474974513 select x; - if (!source.Any()) + if (!source.Any()) { return null; } - return source.MinBy((BodyPartRecord x) => Mathf.Abs(FoodUtility.GetBodyPartNutrition(this.InnerPawn, x) - nutritionWanted)); + return source.MinBy((Func)((BodyPartRecord x) => Mathf.Abs(FoodUtility.GetBodyPartNutrition(this.InnerPawn, x) - nutritionWanted))); } private void NotifyColonistBar() @@ -421,9 +432,21 @@ virtual IThingHolder get_ParentHolder() return base.ParentHolder; } + IThingHolder IThingHolder.get_ParentHolder() + { + //ILSpy generated this explicit interface implementation from .override directive in get_ParentHolder + return this.get_ParentHolder(); + } + virtual Map get_Map() { return base.Map; } + + Map IBillGiver.get_Map() + { + //ILSpy generated this explicit interface implementation from .override directive in get_Map + return this.get_Map(); + } } } diff --git a/Assembly-CSharp/Verse/CoverGrid.cs b/Assembly-CSharp/Verse/CoverGrid.cs index 892e8b162..36e426da7 100644 --- a/Assembly-CSharp/Verse/CoverGrid.cs +++ b/Assembly-CSharp/Verse/CoverGrid.cs @@ -1,4 +1,3 @@ -using System; using System.Collections.Generic; namespace Verse @@ -33,34 +32,32 @@ public CoverGrid(Map map) public void Register(Thing t) { - if (t.def.Fillage == FillCategory.None) + if (t.def.Fillage != 0) { - return; - } - CellRect cellRect = t.OccupiedRect(); - for (int i = cellRect.minZ; i <= cellRect.maxZ; i++) - { - for (int j = cellRect.minX; j <= cellRect.maxX; j++) + CellRect cellRect = t.OccupiedRect(); + for (int i = cellRect.minZ; i <= cellRect.maxZ; i++) { - IntVec3 c = new IntVec3(j, 0, i); - this.RecalculateCell(c, null); + for (int j = cellRect.minX; j <= cellRect.maxX; j++) + { + IntVec3 c = new IntVec3(j, 0, i); + this.RecalculateCell(c, null); + } } } } public void DeRegister(Thing t) { - if (t.def.Fillage == FillCategory.None) - { - return; - } - CellRect cellRect = t.OccupiedRect(); - for (int i = cellRect.minZ; i <= cellRect.maxZ; i++) + if (t.def.Fillage != 0) { - for (int j = cellRect.minX; j <= cellRect.maxX; j++) + CellRect cellRect = t.OccupiedRect(); + for (int i = cellRect.minZ; i <= cellRect.maxZ; i++) { - IntVec3 c = new IntVec3(j, 0, i); - this.RecalculateCell(c, t); + for (int j = cellRect.minX; j <= cellRect.maxX; j++) + { + IntVec3 c = new IntVec3(j, 0, i); + this.RecalculateCell(c, t); + } } } } @@ -73,13 +70,10 @@ private void RecalculateCell(IntVec3 c, Thing ignoreThing = null) for (int i = 0; i < list.Count; i++) { Thing thing2 = list[i]; - if (thing2 != ignoreThing && !thing2.Destroyed && thing2.Spawned) + if (thing2 != ignoreThing && !thing2.Destroyed && thing2.Spawned && thing2.def.fillPercent > num) { - if (thing2.def.fillPercent > num) - { - thing = thing2; - num = thing2.def.fillPercent; - } + thing = thing2; + num = thing2.def.fillPercent; } } this.innerArray[this.map.cellIndices.CellToIndex(c)] = thing; diff --git a/Assembly-CSharp/Verse/CoverInfo.cs b/Assembly-CSharp/Verse/CoverInfo.cs index 065df0cc6..427bce446 100644 --- a/Assembly-CSharp/Verse/CoverInfo.cs +++ b/Assembly-CSharp/Verse/CoverInfo.cs @@ -1,5 +1,3 @@ -using System; - namespace Verse { public struct CoverInfo diff --git a/Assembly-CSharp/Verse/CoverUtility.cs b/Assembly-CSharp/Verse/CoverUtility.cs index f811817f2..9b62a3f72 100644 --- a/Assembly-CSharp/Verse/CoverUtility.cs +++ b/Assembly-CSharp/Verse/CoverUtility.cs @@ -1,4 +1,3 @@ -using System; using System.Collections.Generic; namespace Verse @@ -13,13 +12,10 @@ public static List CalculateCoverGiverSet(IntVec3 targetLoc, IntVec3 for (int i = 0; i < 8; i++) { IntVec3 intVec = targetLoc + GenAdj.AdjacentCells[i]; - if (intVec.InBounds(map)) + CoverInfo item = default(CoverInfo); + if (intVec.InBounds(map) && CoverUtility.TryFindAdjustedCoverInCell(shooterLoc, targetLoc, intVec, map, out item)) { - CoverInfo item; - if (CoverUtility.TryFindAdjustedCoverInCell(shooterLoc, targetLoc, intVec, map, out item)) - { - list.Add(item); - } + list.Add(item); } } return list; @@ -31,13 +27,10 @@ public static float CalculateOverallBlockChance(IntVec3 targetLoc, IntVec3 shoot for (int i = 0; i < 8; i++) { IntVec3 intVec = targetLoc + GenAdj.AdjacentCells[i]; - if (intVec.InBounds(map)) + CoverInfo coverInfo = default(CoverInfo); + if (intVec.InBounds(map) && CoverUtility.TryFindAdjustedCoverInCell(shooterLoc, targetLoc, intVec, map, out coverInfo)) { - CoverInfo coverInfo; - if (CoverUtility.TryFindAdjustedCoverInCell(shooterLoc, targetLoc, intVec, map, out coverInfo)) - { - num += (1f - num) * coverInfo.BlockChance; - } + num = (float)(num + (1.0 - num) * coverInfo.BlockChance); } } return num; @@ -46,52 +39,56 @@ public static float CalculateOverallBlockChance(IntVec3 targetLoc, IntVec3 shoot private static bool TryFindAdjustedCoverInCell(IntVec3 shooterLoc, IntVec3 targetLoc, IntVec3 adjCell, Map map, out CoverInfo result) { Thing cover = adjCell.GetCover(map); - if (cover == null || shooterLoc == targetLoc) - { - result = CoverInfo.Invalid; - return false; - } - float angleFlat = (shooterLoc - targetLoc).AngleFlat; - float angleFlat2 = (adjCell - targetLoc).AngleFlat; - float num = GenGeo.AngleDifferenceBetween(angleFlat2, angleFlat); - if (!targetLoc.AdjacentToCardinal(adjCell)) - { - num *= 1.75f; - } - float num2 = cover.def.BaseBlockChance(); - if (num < 15f) - { - num2 *= 1f; - } - else if (num < 27f) - { - num2 *= 0.8f; - } - else if (num < 40f) - { - num2 *= 0.6f; - } - else if (num < 52f) - { - num2 *= 0.4f; - } - else + float num2; + if (cover != null && !(shooterLoc == targetLoc)) { - if (num >= 65f) + float angleFlat = (shooterLoc - targetLoc).AngleFlat; + float angleFlat2 = (adjCell - targetLoc).AngleFlat; + float num = GenGeo.AngleDifferenceBetween(angleFlat2, angleFlat); + if (!targetLoc.AdjacentToCardinal(adjCell)) + { + num = (float)(num * 1.75); + } + num2 = cover.def.BaseBlockChance(); + if (num < 15.0) + { + num2 = (float)(num2 * 1.0); + goto IL_0104; + } + if (num < 27.0) { - result = CoverInfo.Invalid; - return false; + num2 = (float)(num2 * 0.800000011920929); + goto IL_0104; } - num2 *= 0.2f; + if (num < 40.0) + { + num2 = (float)(num2 * 0.60000002384185791); + goto IL_0104; + } + if (num < 52.0) + { + num2 = (float)(num2 * 0.40000000596046448); + goto IL_0104; + } + if (num < 65.0) + { + num2 = (float)(num2 * 0.20000000298023224); + goto IL_0104; + } + result = CoverInfo.Invalid; + return false; } + result = CoverInfo.Invalid; + return false; + IL_0104: float lengthHorizontal = (shooterLoc - adjCell).LengthHorizontal; - if (lengthHorizontal < 1.9f) + if (lengthHorizontal < 1.8999999761581421) { - num2 *= 0.3333f; + num2 = (float)(num2 * 0.33329999446868896); } - else if (lengthHorizontal < 2.9f) + else if (lengthHorizontal < 2.9000000953674316) { - num2 *= 0.66666f; + num2 = (float)(num2 * 0.66666001081466675); } result = new CoverInfo(cover, num2); return true; diff --git a/Assembly-CSharp/Verse/CreditRecord_Role.cs b/Assembly-CSharp/Verse/CreditRecord_Role.cs index c09404a6f..19d9e2e67 100644 --- a/Assembly-CSharp/Verse/CreditRecord_Role.cs +++ b/Assembly-CSharp/Verse/CreditRecord_Role.cs @@ -1,4 +1,3 @@ -using System; using UnityEngine; namespace Verse diff --git a/Assembly-CSharp/Verse/CreditRecord_Space.cs b/Assembly-CSharp/Verse/CreditRecord_Space.cs index 7ea8ab114..64f00b71b 100644 --- a/Assembly-CSharp/Verse/CreditRecord_Space.cs +++ b/Assembly-CSharp/Verse/CreditRecord_Space.cs @@ -1,4 +1,3 @@ -using System; using UnityEngine; namespace Verse diff --git a/Assembly-CSharp/Verse/CreditRecord_Text.cs b/Assembly-CSharp/Verse/CreditRecord_Text.cs index 2a8480d06..5fa5b2baa 100644 --- a/Assembly-CSharp/Verse/CreditRecord_Text.cs +++ b/Assembly-CSharp/Verse/CreditRecord_Text.cs @@ -1,4 +1,3 @@ -using System; using UnityEngine; namespace Verse diff --git a/Assembly-CSharp/Verse/CreditRecord_Title.cs b/Assembly-CSharp/Verse/CreditRecord_Title.cs index 0269abac9..bf7fc3533 100644 --- a/Assembly-CSharp/Verse/CreditRecord_Title.cs +++ b/Assembly-CSharp/Verse/CreditRecord_Title.cs @@ -1,4 +1,3 @@ -using System; using UnityEngine; namespace Verse @@ -29,7 +28,7 @@ public override void Draw(Rect rect) Widgets.Label(rect, this.title); Text.Anchor = TextAnchor.UpperLeft; GUI.color = new Color(1f, 1f, 1f, 0.5f); - Widgets.DrawLineHorizontal(rect.x + 10f, Mathf.Round(rect.yMax) - 14f, rect.width - 20f); + Widgets.DrawLineHorizontal((float)(rect.x + 10.0), (float)(Mathf.Round(rect.yMax) - 14.0), (float)(rect.width - 20.0)); GUI.color = Color.white; } } diff --git a/Assembly-CSharp/Verse/CreditsEntry.cs b/Assembly-CSharp/Verse/CreditsEntry.cs index 25cb75a6f..b6a53817c 100644 --- a/Assembly-CSharp/Verse/CreditsEntry.cs +++ b/Assembly-CSharp/Verse/CreditsEntry.cs @@ -1,4 +1,3 @@ -using System; using UnityEngine; namespace Verse diff --git a/Assembly-CSharp/Verse/CrossRefHandler.cs b/Assembly-CSharp/Verse/CrossRefHandler.cs index d97150dba..0714de971 100644 --- a/Assembly-CSharp/Verse/CrossRefHandler.cs +++ b/Assembly-CSharp/Verse/CrossRefHandler.cs @@ -15,24 +15,16 @@ public void RegisterForCrossRefResolve(IExposable s) { if (Scribe.mode != LoadSaveMode.LoadingVars) { - Log.Error(string.Concat(new object[] - { - "Registered ", - s, - " for cross ref resolve, but current mode is ", - Scribe.mode - })); - return; - } - if (s == null) - { - return; + Log.Error("Registered " + s + " for cross ref resolve, but current mode is " + Scribe.mode); } - if (DebugViewSettings.logMapLoad) + else if (s != null) { - LogSimple.Message("RegisterForCrossRefResolve " + ((s == null) ? "null" : s.GetType().ToString())); + if (DebugViewSettings.logMapLoad) + { + LogSimple.Message("RegisterForCrossRefResolve " + ((s == null) ? "null" : s.GetType().ToString())); + } + this.crossReferencingExposables.Add(s); } - this.crossReferencingExposables.Add(s); } public void ResolveAllCrossReferences() @@ -42,41 +34,59 @@ public void ResolveAllCrossReferences() { LogSimple.Message("==================Register the saveables all so we can find them later"); } - foreach (IExposable current in this.crossReferencingExposables) + List.Enumerator enumerator = this.crossReferencingExposables.GetEnumerator(); + try { - ILoadReferenceable loadReferenceable = current as ILoadReferenceable; - if (loadReferenceable != null) + while (enumerator.MoveNext()) { - if (DebugViewSettings.logMapLoad) + IExposable current = enumerator.Current; + ILoadReferenceable loadReferenceable = current as ILoadReferenceable; + if (loadReferenceable != null) { - LogSimple.Message("RegisterLoaded " + loadReferenceable.GetType()); + if (DebugViewSettings.logMapLoad) + { + LogSimple.Message("RegisterLoaded " + loadReferenceable.GetType()); + } + this.loadedObjectDirectory.RegisterLoaded(loadReferenceable); } - this.loadedObjectDirectory.RegisterLoaded(loadReferenceable); } } + finally + { + ((IDisposable)(object)enumerator).Dispose(); + } if (DebugViewSettings.logMapLoad) { LogSimple.Message("==================Fill all cross-references to the saveables"); } - foreach (IExposable current2 in this.crossReferencingExposables) + List.Enumerator enumerator2 = this.crossReferencingExposables.GetEnumerator(); + try { - if (DebugViewSettings.logMapLoad) - { - LogSimple.Message("ResolvingCrossRefs ExposeData " + current2.GetType()); - } - try - { - Scribe.loader.curParent = current2; - Scribe.loader.curPathRelToParent = null; - current2.ExposeData(); - } - catch (Exception arg) + while (enumerator2.MoveNext()) { - Log.Error("Could not resolve cross refs: " + arg); + IExposable current2 = enumerator2.Current; + if (DebugViewSettings.logMapLoad) + { + LogSimple.Message("ResolvingCrossRefs ExposeData " + current2.GetType()); + } + try + { + Scribe.loader.curParent = current2; + Scribe.loader.curPathRelToParent = (string)null; + current2.ExposeData(); + } + catch (Exception arg) + { + Log.Error("Could not resolve cross refs: " + arg); + } } } + finally + { + ((IDisposable)(object)enumerator2).Dispose(); + } Scribe.loader.curParent = null; - Scribe.loader.curPathRelToParent = null; + Scribe.loader.curPathRelToParent = (string)null; Scribe.mode = LoadSaveMode.Inactive; this.Clear(true); } diff --git a/Assembly-CSharp/Verse/CrownType.cs b/Assembly-CSharp/Verse/CrownType.cs index 5680d7ad0..e7f3fd099 100644 --- a/Assembly-CSharp/Verse/CrownType.cs +++ b/Assembly-CSharp/Verse/CrownType.cs @@ -1,11 +1,9 @@ -using System; - namespace Verse { public enum CrownType : byte { - Undefined, - Average, - Narrow + Undefined = 0, + Average = 1, + Narrow = 2 } } diff --git a/Assembly-CSharp/Verse/Current.cs b/Assembly-CSharp/Verse/Current.cs index 1ace0f8bc..260a69189 100644 --- a/Assembly-CSharp/Verse/Current.cs +++ b/Assembly-CSharp/Verse/Current.cs @@ -1,5 +1,4 @@ using RimWorld.Planet; -using System; using UnityEngine; using UnityStandardAssets.ImageEffects; @@ -127,8 +126,8 @@ public static void Notify_LoadedSceneChanged() Current.rootEntryInt = null; Current.rootPlayInt = GameObject.Find("GameRoot").GetComponent(); Current.rootInt = Current.rootPlayInt; - Current.cameraDriverInt = Current.cameraInt.GetComponent(); - Current.colorCorrectionCurvesInt = Current.cameraInt.GetComponent(); + Current.cameraDriverInt = ((Component)Current.cameraInt).GetComponent(); + Current.colorCorrectionCurvesInt = ((Component)Current.cameraInt).GetComponent(); } } } diff --git a/Assembly-CSharp/Verse/CurveMark.cs b/Assembly-CSharp/Verse/CurveMark.cs index 9f749c190..24169b438 100644 --- a/Assembly-CSharp/Verse/CurveMark.cs +++ b/Assembly-CSharp/Verse/CurveMark.cs @@ -1,4 +1,3 @@ -using System; using UnityEngine; namespace Verse diff --git a/Assembly-CSharp/Verse/CurvePoint.cs b/Assembly-CSharp/Verse/CurvePoint.cs index f39de0b8d..0410c3c07 100644 --- a/Assembly-CSharp/Verse/CurvePoint.cs +++ b/Assembly-CSharp/Verse/CurvePoint.cs @@ -1,4 +1,3 @@ -using System; using UnityEngine; namespace Verse diff --git a/Assembly-CSharp/Verse/CustomCursor.cs b/Assembly-CSharp/Verse/CustomCursor.cs index 7ee00082e..1b4a3ddaa 100644 --- a/Assembly-CSharp/Verse/CustomCursor.cs +++ b/Assembly-CSharp/Verse/CustomCursor.cs @@ -1,4 +1,3 @@ -using System; using UnityEngine; namespace Verse diff --git a/Assembly-CSharp/Verse/DamageArmorCategoryDef.cs b/Assembly-CSharp/Verse/DamageArmorCategoryDef.cs index e1741c7a7..889878c20 100644 --- a/Assembly-CSharp/Verse/DamageArmorCategoryDef.cs +++ b/Assembly-CSharp/Verse/DamageArmorCategoryDef.cs @@ -1,5 +1,4 @@ using RimWorld; -using System; namespace Verse { diff --git a/Assembly-CSharp/Verse/DamageDefAdditionalHediff.cs b/Assembly-CSharp/Verse/DamageDefAdditionalHediff.cs index 8c401b9b3..85bc8ec59 100644 --- a/Assembly-CSharp/Verse/DamageDefAdditionalHediff.cs +++ b/Assembly-CSharp/Verse/DamageDefAdditionalHediff.cs @@ -1,5 +1,3 @@ -using System; - namespace Verse { public class DamageDefAdditionalHediff diff --git a/Assembly-CSharp/Verse/DamageFlasher.cs b/Assembly-CSharp/Verse/DamageFlasher.cs index c5990dede..2b2204151 100644 --- a/Assembly-CSharp/Verse/DamageFlasher.cs +++ b/Assembly-CSharp/Verse/DamageFlasher.cs @@ -1,4 +1,3 @@ -using System; using UnityEngine; namespace Verse @@ -31,7 +30,7 @@ public DamageFlasher(Pawn pawn) public Material GetDamagedMat(Material baseMat) { - return DamagedMatPool.GetDamageFlashMat(baseMat, (float)this.DamageFlashTicksLeft / 16f); + return DamagedMatPool.GetDamageFlashMat(baseMat, (float)((float)this.DamageFlashTicksLeft / 16.0)); } public void Notify_DamageApplied(DamageInfo dinfo) diff --git a/Assembly-CSharp/Verse/DamageGraphicData.cs b/Assembly-CSharp/Verse/DamageGraphicData.cs index 3c0ef5bff..4f343f9be 100644 --- a/Assembly-CSharp/Verse/DamageGraphicData.cs +++ b/Assembly-CSharp/Verse/DamageGraphicData.cs @@ -65,7 +65,7 @@ public class DamageGraphicData public void ResolveReferencesSpecial() { - LongEventHandler.ExecuteWhenFinished(delegate + LongEventHandler.ExecuteWhenFinished((Action)delegate { if (this.scratches != null) { diff --git a/Assembly-CSharp/Verse/DamageInfo.cs b/Assembly-CSharp/Verse/DamageInfo.cs index c7c01de0a..d7b70e73b 100644 --- a/Assembly-CSharp/Verse/DamageInfo.cs +++ b/Assembly-CSharp/Verse/DamageInfo.cs @@ -7,8 +7,8 @@ public struct DamageInfo { public enum SourceCategory { - ThingOrUnknown, - Collapse + ThingOrUnknown = 0, + Collapse = 1 } private DamageDef defInt; @@ -19,7 +19,7 @@ public enum SourceCategory private Thing instigatorInt; - private DamageInfo.SourceCategory categoryInt; + private SourceCategory categoryInt; private BodyPartRecord forceHitPartInt; @@ -65,7 +65,7 @@ public Thing Instigator } } - public DamageInfo.SourceCategory Category + public SourceCategory Category { get { @@ -141,15 +141,19 @@ public bool AllowDamagePropagation { get { - return !this.InstantOldInjury && this.allowDamagePropagationInt; + if (this.InstantOldInjury) + { + return false; + } + return this.allowDamagePropagationInt; } } - public DamageInfo(DamageDef def, int amount, float angle = -1f, Thing instigator = null, BodyPartRecord forceHitPart = null, ThingDef weaponGear = null, DamageInfo.SourceCategory category = DamageInfo.SourceCategory.ThingOrUnknown) + public DamageInfo(DamageDef def, int amount, float angle = -1, Thing instigator = null, BodyPartRecord forceHitPart = null, ThingDef weaponGear = null, SourceCategory category = SourceCategory.ThingOrUnknown) { this.defInt = def; this.amountInt = amount; - if (angle < 0f) + if (angle < 0.0) { this.angleInt = (float)Rand.RangeInclusive(0, 359); } @@ -224,9 +228,10 @@ public void SetAllowDamagePropagation(bool val) public void SetAngle(Vector3 vec) { - if (vec.x != 0f || vec.z != 0f) + if (vec.x != 0.0 || vec.z != 0.0) { - this.angleInt = Quaternion.LookRotation(vec).eulerAngles.y; + Vector3 eulerAngles = Quaternion.LookRotation(vec).eulerAngles; + this.angleInt = eulerAngles.y; } else { @@ -236,18 +241,7 @@ public void SetAngle(Vector3 vec) public override string ToString() { - return string.Concat(new object[] - { - "(def=", - this.defInt, - ", amount= ", - this.amountInt, - ", instigator=", - (this.instigatorInt == null) ? this.categoryInt.ToString() : this.instigatorInt.ToString(), - ", angle=", - this.angleInt.ToString("F1"), - ")" - }); + return "(def=" + this.defInt + ", amount= " + this.amountInt + ", instigator=" + ((this.instigatorInt == null) ? ((Enum)(object)this.categoryInt).ToString() : this.instigatorInt.ToString()) + ", angle=" + this.angleInt.ToString("F1") + ")"; } } } diff --git a/Assembly-CSharp/Verse/DamageMultiplier.cs b/Assembly-CSharp/Verse/DamageMultiplier.cs index 5fd236bf9..b0a17e862 100644 --- a/Assembly-CSharp/Verse/DamageMultiplier.cs +++ b/Assembly-CSharp/Verse/DamageMultiplier.cs @@ -1,5 +1,3 @@ -using System; - namespace Verse { public class DamageMultiplier diff --git a/Assembly-CSharp/Verse/DamageOverlay.cs b/Assembly-CSharp/Verse/DamageOverlay.cs index 109cbe33a..5b84d53c0 100644 --- a/Assembly-CSharp/Verse/DamageOverlay.cs +++ b/Assembly-CSharp/Verse/DamageOverlay.cs @@ -1,17 +1,15 @@ -using System; - namespace Verse { public enum DamageOverlay { - Scratch, - TopLeftCorner, - TopRightCorner, - BotLeftCorner, - BotRightCorner, - LeftEdge, - RightEdge, - TopEdge, - BotEdge + Scratch = 0, + TopLeftCorner = 1, + TopRightCorner = 2, + BotLeftCorner = 3, + BotRightCorner = 4, + LeftEdge = 5, + RightEdge = 6, + TopEdge = 7, + BotEdge = 8 } } diff --git a/Assembly-CSharp/Verse/DamageWorker.cs b/Assembly-CSharp/Verse/DamageWorker.cs index c26cffa2c..9dce851f8 100644 --- a/Assembly-CSharp/Verse/DamageWorker.cs +++ b/Assembly-CSharp/Verse/DamageWorker.cs @@ -1,5 +1,4 @@ using RimWorld; -using System; using System.Collections.Generic; using System.Linq; using UnityEngine; @@ -32,7 +31,7 @@ public virtual float Apply(DamageInfo dinfo, Thing victim) if (victim.HitPoints <= 0) { victim.HitPoints = 0; - victim.Kill(null); + victim.Kill(default(DamageInfo?)); } } return result; @@ -40,15 +39,15 @@ public virtual float Apply(DamageInfo dinfo, Thing victim) public virtual void ExplosionStart(Explosion explosion, List cellsToAffect) { - if (this.def.explosionHeatEnergyPerCell > 1.401298E-45f) + if (this.def.explosionHeatEnergyPerCell > 1.4012984643248171E-45) { GenTemperature.PushHeat(explosion.position, explosion.Map, this.def.explosionHeatEnergyPerCell * (float)cellsToAffect.Count); } - MoteMaker.MakeStaticMote(explosion.position, explosion.Map, ThingDefOf.Mote_ExplosionFlash, explosion.radius * 6f); + MoteMaker.MakeStaticMote(explosion.position, explosion.Map, ThingDefOf.Mote_ExplosionFlash, (float)(explosion.radius * 6.0)); if (explosion.Map == Find.VisibleMap) { float magnitude = (explosion.position.ToVector3() - Find.Camera.transform.position).magnitude; - Find.CameraDriver.shaker.DoShake(4f * explosion.radius / magnitude); + Find.CameraDriver.shaker.DoShake((float)(4.0 * explosion.radius / magnitude)); } this.ExplosionVisualEffectCenter(explosion); } @@ -57,97 +56,85 @@ protected virtual void ExplosionVisualEffectCenter(Explosion explosion) { for (int i = 0; i < 4; i++) { - MoteMaker.ThrowSmoke(explosion.position.ToVector3Shifted() + Gen.RandomHorizontalVector(explosion.radius * 0.7f), explosion.Map, explosion.radius * 0.6f); + MoteMaker.ThrowSmoke(explosion.position.ToVector3Shifted() + Gen.RandomHorizontalVector((float)(explosion.radius * 0.699999988079071)), explosion.Map, (float)(explosion.radius * 0.60000002384185791)); } if (this.def.explosionInteriorMote != null) { - int num = Mathf.RoundToInt(3.14159274f * explosion.radius * explosion.radius / 6f); - for (int j = 0; j < num; j++) + int num = Mathf.RoundToInt((float)(3.1415927410125732 * explosion.radius * explosion.radius / 6.0)); + for (int num2 = 0; num2 < num; num2++) { - MoteMaker.ThrowExplosionInteriorMote(explosion.position.ToVector3Shifted() + Gen.RandomHorizontalVector(explosion.radius * 0.7f), explosion.Map, this.def.explosionInteriorMote); + MoteMaker.ThrowExplosionInteriorMote(explosion.position.ToVector3Shifted() + Gen.RandomHorizontalVector((float)(explosion.radius * 0.699999988079071)), explosion.Map, this.def.explosionInteriorMote); } } } public virtual void ExplosionAffectCell(Explosion explosion, IntVec3 c, List damagedThings, bool canThrowMotes) { - if (!c.InBounds(explosion.Map)) + if (c.InBounds(explosion.Map)) { - return; - } - if (this.def.explosionCellMote != null && canThrowMotes) - { - float t = Mathf.Clamp01((explosion.position - c).LengthHorizontal / explosion.radius); - Color color = Color.Lerp(this.def.explosionColorCenter, this.def.explosionColorEdge, t); - MoteMaker.ThrowExplosionCell(c, explosion.Map, this.def.explosionCellMote, color); - } - List list = explosion.Map.thingGrid.ThingsListAt(c); - DamageWorker.thingsToAffect.Clear(); - float num = -3.40282347E+38f; - for (int i = 0; i < list.Count; i++) - { - Thing thing = list[i]; - DamageWorker.thingsToAffect.Add(thing); - if (thing.def.Fillage == FillCategory.Full && thing.def.Altitude > num) + if (this.def.explosionCellMote != null && canThrowMotes) { - num = thing.def.Altitude; + float t = Mathf.Clamp01((explosion.position - c).LengthHorizontal / explosion.radius); + Color color = Color.Lerp(this.def.explosionColorCenter, this.def.explosionColorEdge, t); + MoteMaker.ThrowExplosionCell(c, explosion.Map, this.def.explosionCellMote, color); } - } - for (int j = 0; j < DamageWorker.thingsToAffect.Count; j++) - { - if (DamageWorker.thingsToAffect[j].def.Altitude >= num) + List list = explosion.Map.thingGrid.ThingsListAt(c); + DamageWorker.thingsToAffect.Clear(); + float num = -3.40282347E+38f; + for (int i = 0; i < list.Count; i++) { - this.ExplosionDamageThing(explosion, DamageWorker.thingsToAffect[j], damagedThings); + Thing thing = list[i]; + DamageWorker.thingsToAffect.Add(thing); + if (thing.def.Fillage == FillCategory.Full && thing.def.Altitude > num) + { + num = thing.def.Altitude; + } } - } - if (this.def.explosionSnowMeltAmount > 0.0001f) - { - float lengthHorizontal = (c - explosion.position).LengthHorizontal; - float num2 = 1f - lengthHorizontal / explosion.radius; - if (num2 > 0f) + for (int j = 0; j < DamageWorker.thingsToAffect.Count; j++) { - explosion.Map.snowGrid.AddDepth(c, -num2 * this.def.explosionSnowMeltAmount); + if (DamageWorker.thingsToAffect[j].def.Altitude >= num) + { + this.ExplosionDamageThing(explosion, DamageWorker.thingsToAffect[j], damagedThings); + } + } + if (this.def.explosionSnowMeltAmount > 9.9999997473787516E-05) + { + float lengthHorizontal = (c - explosion.position).LengthHorizontal; + float num2 = (float)(1.0 - lengthHorizontal / explosion.radius); + if (num2 > 0.0) + { + explosion.Map.snowGrid.AddDepth(c, (float)((0.0 - num2) * this.def.explosionSnowMeltAmount)); + } } } } protected virtual void ExplosionDamageThing(Explosion explosion, Thing t, List damagedThings) { - if (t.def.category == ThingCategory.Mote) - { - return; - } - if (damagedThings.Contains(t)) - { - return; - } - damagedThings.Add(t); - if (this.def == DamageDefOf.Bomb && t.def == ThingDefOf.Fire && !t.Destroyed) - { - t.Destroy(DestroyMode.Vanish); - return; - } - float angle; - if (t.Position == explosion.position) - { - angle = (float)Rand.RangeInclusive(0, 359); - } - else + if (t.def.category != ThingCategory.Mote && !damagedThings.Contains(t)) { - angle = (t.Position - explosion.position).AngleFlat; - } - ThingDef weaponGear = explosion.weaponGear; - DamageInfo dinfo = new DamageInfo(this.def, explosion.damAmount, angle, explosion.instigator, null, weaponGear, DamageInfo.SourceCategory.ThingOrUnknown); - if (this.def.explosionAffectOutsidePartsOnly) - { - dinfo.SetBodyRegion(BodyPartHeight.Undefined, BodyPartDepth.Outside); - } - if (t.def.category == ThingCategory.Building) - { - int amount = Mathf.RoundToInt((float)dinfo.Amount * this.def.explosionBuildingDamageFactor); - dinfo = new DamageInfo(this.def, amount, dinfo.Angle, explosion.instigator, null, null, DamageInfo.SourceCategory.ThingOrUnknown); + damagedThings.Add(t); + if (this.def == DamageDefOf.Bomb && t.def == ThingDefOf.Fire && !t.Destroyed) + { + t.Destroy(DestroyMode.Vanish); + } + else + { + float angle = (!(t.Position == explosion.position)) ? (t.Position - explosion.position).AngleFlat : ((float)Rand.RangeInclusive(0, 359)); + ThingDef weaponGear = explosion.weaponGear; + DamageInfo dinfo = new DamageInfo(this.def, explosion.damAmount, angle, explosion.instigator, null, weaponGear, DamageInfo.SourceCategory.ThingOrUnknown); + if (this.def.explosionAffectOutsidePartsOnly) + { + dinfo.SetBodyRegion(BodyPartHeight.Undefined, BodyPartDepth.Outside); + } + if (t.def.category == ThingCategory.Building) + { + int amount = Mathf.RoundToInt((float)dinfo.Amount * this.def.explosionBuildingDamageFactor); + dinfo = new DamageInfo(this.def, amount, dinfo.Angle, explosion.instigator, null, null, DamageInfo.SourceCategory.ThingOrUnknown); + } + t.TakeDamage(dinfo); + } } - t.TakeDamage(dinfo); } public IEnumerable ExplosionCellsToHit(Explosion explosion) @@ -160,40 +147,25 @@ public virtual IEnumerable ExplosionCellsToHit(IntVec3 center, Map map, DamageWorker.openCells.Clear(); DamageWorker.adjWallCells.Clear(); int num = GenRadial.NumCellsInRadius(radius); - for (int i = 0; i < num; i++) + for (int num2 = 0; num2 < num; num2++) { - IntVec3 intVec = center + GenRadial.RadialPattern[i]; - if (intVec.InBounds(map)) + IntVec3 intVec = center + GenRadial.RadialPattern[num2]; + if (intVec.InBounds(map) && GenSight.LineOfSight(center, intVec, map, true, null, 0, 0)) { - if (GenSight.LineOfSight(center, intVec, map, true, null, 0, 0)) - { - DamageWorker.openCells.Add(intVec); - } + DamageWorker.openCells.Add(intVec); } } - for (int j = 0; j < DamageWorker.openCells.Count; j++) + for (int i = 0; i < DamageWorker.openCells.Count; i++) { - IntVec3 intVec2 = DamageWorker.openCells[j]; + IntVec3 intVec2 = DamageWorker.openCells[i]; if (intVec2.Walkable(map)) { - for (int k = 0; k < 4; k++) + for (int j = 0; j < 4; j++) { - IntVec3 intVec3 = intVec2 + GenAdj.CardinalDirections[k]; - if (intVec3.InHorDistOf(center, radius)) + IntVec3 intVec3 = intVec2 + GenAdj.CardinalDirections[j]; + if (intVec3.InHorDistOf(center, radius) && intVec3.InBounds(map) && !intVec3.Standable(map) && intVec3.GetEdifice(map) != null && !DamageWorker.openCells.Contains(intVec3) && DamageWorker.adjWallCells.Contains(intVec3)) { - if (intVec3.InBounds(map)) - { - if (!intVec3.Standable(map)) - { - if (intVec3.GetEdifice(map) != null) - { - if (!DamageWorker.openCells.Contains(intVec3) && DamageWorker.adjWallCells.Contains(intVec3)) - { - DamageWorker.adjWallCells.Add(intVec3); - } - } - } - } + DamageWorker.adjWallCells.Add(intVec3); } } } diff --git a/Assembly-CSharp/Verse/DamageWorker_AddGlobal.cs b/Assembly-CSharp/Verse/DamageWorker_AddGlobal.cs index d35a1dc42..465c09672 100644 --- a/Assembly-CSharp/Verse/DamageWorker_AddGlobal.cs +++ b/Assembly-CSharp/Verse/DamageWorker_AddGlobal.cs @@ -1,5 +1,3 @@ -using System; - namespace Verse { public class DamageWorker_AddGlobal : DamageWorker diff --git a/Assembly-CSharp/Verse/DamageWorker_AddInjury.cs b/Assembly-CSharp/Verse/DamageWorker_AddInjury.cs index f8f8123e0..4a421c3aa 100644 --- a/Assembly-CSharp/Verse/DamageWorker_AddInjury.cs +++ b/Assembly-CSharp/Verse/DamageWorker_AddInjury.cs @@ -20,9 +20,9 @@ private struct LocalInjuryResult public float totalDamageDealt; - public static DamageWorker_AddInjury.LocalInjuryResult MakeNew() + public static LocalInjuryResult MakeNew() { - return new DamageWorker_AddInjury.LocalInjuryResult + return new LocalInjuryResult { wounded = false, headshot = false, @@ -55,7 +55,7 @@ private float ApplyToPawn(DamageInfo dinfo, Pawn pawn) { return 0f; } - DamageWorker_AddInjury.LocalInjuryResult localInjuryResult = DamageWorker_AddInjury.LocalInjuryResult.MakeNew(); + LocalInjuryResult localInjuryResult = LocalInjuryResult.MakeNew(); Map mapHeld = pawn.MapHeld; bool spawnedOrAnyParentSpawned = pawn.SpawnedOrAnyParentSpawned; if (dinfo.Def.spreadOut) @@ -63,9 +63,9 @@ private float ApplyToPawn(DamageInfo dinfo, Pawn pawn) if (pawn.apparel != null) { List wornApparel = pawn.apparel.WornApparel; - for (int i = wornApparel.Count - 1; i >= 0; i--) + for (int num = wornApparel.Count - 1; num >= 0; num--) { - this.CheckApplySpreadDamage(dinfo, wornApparel[i]); + this.CheckApplySpreadDamage(dinfo, wornApparel[num]); } } if (pawn.equipment != null && pawn.equipment.Primary != null) @@ -75,19 +75,19 @@ private float ApplyToPawn(DamageInfo dinfo, Pawn pawn) if (pawn.inventory != null) { ThingOwner innerContainer = pawn.inventory.innerContainer; - for (int j = innerContainer.Count - 1; j >= 0; j--) + for (int num2 = innerContainer.Count - 1; num2 >= 0; num2--) { - this.CheckApplySpreadDamage(dinfo, innerContainer[j]); + this.CheckApplySpreadDamage(dinfo, innerContainer[num2]); } } } if (this.ShouldFragmentDamageForDamageType(dinfo)) { - int num = Rand.RangeInclusive(3, 4); - for (int k = 0; k < num; k++) + int num3 = Rand.RangeInclusive(3, 4); + for (int num4 = 0; num4 < num3; num4++) { DamageInfo dinfo2 = dinfo; - dinfo2.SetAmount(dinfo.Amount / num); + dinfo2.SetAmount(dinfo.Amount / num3); this.ApplyDamageToPart(dinfo2, pawn, ref localInjuryResult); } } @@ -104,7 +104,12 @@ private float ApplyToPawn(DamageInfo dinfo, Pawn pawn) } if (localInjuryResult.headshot && pawn.Spawned) { - MoteMaker.ThrowText(new Vector3((float)pawn.Position.x + 1f, (float)pawn.Position.y, (float)pawn.Position.z + 1f), pawn.Map, "Headshot".Translate(), Color.white, -1f); + IntVec3 position = pawn.Position; + double x = (float)position.x + 1.0; + IntVec3 position2 = pawn.Position; + float y = (float)position2.y; + IntVec3 position3 = pawn.Position; + MoteMaker.ThrowText(new Vector3((float)x, y, (float)((float)position3.z + 1.0)), pawn.Map, "Headshot".Translate(), Color.white, -1f); if (dinfo.Instigator != null) { Pawn pawn2 = dinfo.Instigator as Pawn; @@ -120,7 +125,7 @@ private float ApplyToPawn(DamageInfo dinfo, Pawn pawn) { pawn.health.deflectionEffecter = EffecterDefOf.ArmorDeflect.Spawn(); } - pawn.health.deflectionEffecter.Trigger(pawn, pawn); + pawn.health.deflectionEffecter.Trigger((Thing)pawn, (Thing)pawn); } else if (spawnedOrAnyParentSpawned) { @@ -132,10 +137,8 @@ private float ApplyToPawn(DamageInfo dinfo, Pawn pawn) private void CheckApplySpreadDamage(DamageInfo dinfo, Thing t) { if (dinfo.Def == DamageDefOf.Flame && !t.FlammableNow) - { return; - } - if (UnityEngine.Random.value < 0.5f) + if (UnityEngine.Random.value < 0.5) { dinfo.SetAmount(Mathf.CeilToInt((float)dinfo.Amount * Rand.Range(0.35f, 0.7f))); t.TakeDamage(dinfo); @@ -143,17 +146,25 @@ private void CheckApplySpreadDamage(DamageInfo dinfo, Thing t) } private bool ShouldFragmentDamageForDamageType(DamageInfo dinfo) - { - return dinfo.AllowDamagePropagation && dinfo.Amount >= 9 && dinfo.Def.spreadOut; - } - - private void CheckDuplicateSmallPawnDamageToPartParent(DamageInfo dinfo, Pawn pawn, ref DamageWorker_AddInjury.LocalInjuryResult result) { if (!dinfo.AllowDamagePropagation) { - return; + return false; + } + if (dinfo.Amount < 9) + { + return false; } - if (result.lastHitPart != null && dinfo.Def.harmsHealth && result.lastHitPart != pawn.RaceProps.body.corePart && result.lastHitPart.parent != null && pawn.health.hediffSet.GetPartHealth(result.lastHitPart.parent) > 0f && dinfo.Amount >= 10 && pawn.HealthScale <= 0.5001f) + if (!dinfo.Def.spreadOut) + { + return false; + } + return true; + } + + private void CheckDuplicateSmallPawnDamageToPartParent(DamageInfo dinfo, Pawn pawn, ref LocalInjuryResult result) + { + if (dinfo.AllowDamagePropagation && result.lastHitPart != null && dinfo.Def.harmsHealth && result.lastHitPart != pawn.RaceProps.body.corePart && result.lastHitPart.parent != null && pawn.health.hediffSet.GetPartHealth(result.lastHitPart.parent) > 0.0 && dinfo.Amount >= 10 && pawn.HealthScale <= 0.50010001659393311) { DamageInfo dinfo2 = dinfo; dinfo2.SetForcedHitPart(result.lastHitPart.parent); @@ -161,65 +172,67 @@ private void CheckDuplicateSmallPawnDamageToPartParent(DamageInfo dinfo, Pawn pa } } - private void ApplyDamageToPart(DamageInfo dinfo, Pawn pawn, ref DamageWorker_AddInjury.LocalInjuryResult result) + private void ApplyDamageToPart(DamageInfo dinfo, Pawn pawn, ref LocalInjuryResult result) { BodyPartRecord exactPartFromDamageInfo = DamageWorker_AddInjury.GetExactPartFromDamageInfo(dinfo, pawn); - if (exactPartFromDamageInfo == null) - { - return; - } - int num = dinfo.Amount; - bool flag = !dinfo.InstantOldInjury; - if (flag) - { - num = ArmorUtility.GetPostArmorDamage(pawn, dinfo.Amount, exactPartFromDamageInfo, dinfo.Def); - } - if (num <= 0) - { - result.deflected = true; - return; - } - HediffDef hediffDefFromDamage = HealthUtility.GetHediffDefFromDamage(dinfo.Def, pawn, exactPartFromDamageInfo); - Hediff_Injury hediff_Injury = (Hediff_Injury)HediffMaker.MakeHediff(hediffDefFromDamage, pawn, null); - hediff_Injury.Part = exactPartFromDamageInfo; - hediff_Injury.source = dinfo.WeaponGear; - hediff_Injury.sourceBodyPartGroup = dinfo.WeaponBodyPartGroup; - hediff_Injury.sourceHediffDef = dinfo.WeaponLinkedHediff; - hediff_Injury.Severity = (float)num; - if (dinfo.InstantOldInjury) + if (exactPartFromDamageInfo != null) { - HediffComp_GetsOld hediffComp_GetsOld = hediff_Injury.TryGetComp(); - if (hediffComp_GetsOld != null) + int num = dinfo.Amount; + bool flag = !dinfo.InstantOldInjury; + if (flag) { - hediffComp_GetsOld.IsOld = true; + num = ArmorUtility.GetPostArmorDamage(pawn, dinfo.Amount, exactPartFromDamageInfo, dinfo.Def); + } + if (num <= 0) + { + result.deflected = true; } else { - Log.Error(string.Concat(new object[] + HediffDef hediffDefFromDamage = HealthUtility.GetHediffDefFromDamage(dinfo.Def, pawn, exactPartFromDamageInfo); + Hediff_Injury hediff_Injury = (Hediff_Injury)HediffMaker.MakeHediff(hediffDefFromDamage, pawn, null); + hediff_Injury.Part = exactPartFromDamageInfo; + hediff_Injury.source = dinfo.WeaponGear; + hediff_Injury.sourceBodyPartGroup = dinfo.WeaponBodyPartGroup; + hediff_Injury.sourceHediffDef = dinfo.WeaponLinkedHediff; + hediff_Injury.Severity = (float)num; + if (dinfo.InstantOldInjury) { - "Tried to create instant old injury on Hediff without a GetsOld comp: ", - hediffDefFromDamage, - " on ", - pawn - })); + HediffComp_GetsOld hediffComp_GetsOld = hediff_Injury.TryGetComp(); + if (hediffComp_GetsOld != null) + { + hediffComp_GetsOld.IsOld = true; + } + else + { + Log.Error("Tried to create instant old injury on Hediff without a GetsOld comp: " + hediffDefFromDamage + " on " + pawn); + } + } + result.wounded = true; + result.lastHitPart = hediff_Injury.Part; + if (DamageWorker_AddInjury.IsHeadshot(dinfo, hediff_Injury, pawn)) + { + result.headshot = true; + } + if (dinfo.InstantOldInjury) + { + if (hediff_Injury.def.CompPropsFor(typeof(HediffComp_GetsOld)) == null) + return; + if (hediff_Injury.Part.def.oldInjuryBaseChance == 0.0) + return; + if (hediff_Injury.Part.def.IsSolid(hediff_Injury.Part, pawn.health.hediffSet.hediffs)) + return; + if (pawn.health.hediffSet.PartOrAnyAncestorHasDirectlyAddedParts(hediff_Injury.Part)) + return; + } + this.FinalizeAndAddInjury(pawn, hediff_Injury, dinfo, ref result); + this.CheckPropagateDamageToInnerSolidParts(dinfo, pawn, hediff_Injury, flag, ref result); + this.CheckDuplicateDamageToOuterParts(dinfo, pawn, hediff_Injury, flag, ref result); } } - result.wounded = true; - result.lastHitPart = hediff_Injury.Part; - if (DamageWorker_AddInjury.IsHeadshot(dinfo, hediff_Injury, pawn)) - { - result.headshot = true; - } - if (dinfo.InstantOldInjury && (hediff_Injury.def.CompPropsFor(typeof(HediffComp_GetsOld)) == null || hediff_Injury.Part.def.oldInjuryBaseChance == 0f || hediff_Injury.Part.def.IsSolid(hediff_Injury.Part, pawn.health.hediffSet.hediffs) || pawn.health.hediffSet.PartOrAnyAncestorHasDirectlyAddedParts(hediff_Injury.Part))) - { - return; - } - this.FinalizeAndAddInjury(pawn, hediff_Injury, dinfo, ref result); - this.CheckPropagateDamageToInnerSolidParts(dinfo, pawn, hediff_Injury, flag, ref result); - this.CheckDuplicateDamageToOuterParts(dinfo, pawn, hediff_Injury, flag, ref result); } - private void FinalizeAndAddInjury(Pawn pawn, Hediff_Injury injury, DamageInfo dinfo, ref DamageWorker_AddInjury.LocalInjuryResult result) + private void FinalizeAndAddInjury(Pawn pawn, Hediff_Injury injury, DamageInfo dinfo, ref LocalInjuryResult result) { this.CalculateOldInjuryDamageThreshold(pawn, injury); result.totalDamageDealt += Mathf.Min(injury.Severity, pawn.health.hediffSet.GetPartHealth(injury.Part)); @@ -229,20 +242,14 @@ private void FinalizeAndAddInjury(Pawn pawn, Hediff_Injury injury, DamageInfo di private void CalculateOldInjuryDamageThreshold(Pawn pawn, Hediff_Injury injury) { HediffCompProperties_GetsOld hediffCompProperties_GetsOld = injury.def.CompProps(); - if (hediffCompProperties_GetsOld == null) - { - return; - } - if (injury.Part.def.IsSolid(injury.Part, pawn.health.hediffSet.hediffs) || pawn.health.hediffSet.PartOrAnyAncestorHasDirectlyAddedParts(injury.Part) || injury.IsOld() || injury.Part.def.oldInjuryBaseChance < 1E-05f) - { - return; - } - bool isDelicate = injury.Part.def.IsDelicate; - if ((Rand.Value <= injury.Part.def.oldInjuryBaseChance * hediffCompProperties_GetsOld.becomeOldChance && injury.Severity >= injury.Part.def.GetMaxHealth(pawn) * 0.25f && injury.Severity >= 7f) || isDelicate) + if (hediffCompProperties_GetsOld != null && !injury.Part.def.IsSolid(injury.Part, pawn.health.hediffSet.hediffs) && !pawn.health.hediffSet.PartOrAnyAncestorHasDirectlyAddedParts(injury.Part) && !injury.IsOld() && !(injury.Part.def.oldInjuryBaseChance < 9.9999997473787516E-06)) { + bool isDelicate = injury.Part.def.IsDelicate; + if ((!(Rand.Value <= injury.Part.def.oldInjuryBaseChance * hediffCompProperties_GetsOld.becomeOldChance) || !(injury.Severity >= injury.Part.def.GetMaxHealth(pawn) * 0.25) || !(injury.Severity >= 7.0)) && !isDelicate) + return; HediffComp_GetsOld hediffComp_GetsOld = injury.TryGetComp(); float num = 1f; - float num2 = injury.Severity / 2f; + float num2 = (float)(injury.Severity / 2.0); if (num <= num2) { hediffComp_GetsOld.oldDamageThreshold = Rand.Range(num, num2); @@ -255,23 +262,15 @@ private void CalculateOldInjuryDamageThreshold(Pawn pawn, Hediff_Injury injury) } } - private void CheckPropagateDamageToInnerSolidParts(DamageInfo dinfo, Pawn pawn, Hediff_Injury injury, bool involveArmor, ref DamageWorker_AddInjury.LocalInjuryResult result) + private void CheckPropagateDamageToInnerSolidParts(DamageInfo dinfo, Pawn pawn, Hediff_Injury injury, bool involveArmor, ref LocalInjuryResult result) { - if (!dinfo.AllowDamagePropagation) - { - return; - } - if (Rand.Value >= HealthTunings.ChanceToAdditionallyDamageInnerSolidPart) - { - return; - } - if (dinfo.Def.hasChanceToAdditionallyDamageInnerSolidParts && !injury.Part.def.IsSolid(injury.Part, pawn.health.hediffSet.hediffs) && injury.Part.depth == BodyPartDepth.Outside) + if (dinfo.AllowDamagePropagation && Rand.Value < HealthTunings.ChanceToAdditionallyDamageInnerSolidPart && dinfo.Def.hasChanceToAdditionallyDamageInnerSolidParts && !injury.Part.def.IsSolid(injury.Part, pawn.health.hediffSet.hediffs) && injury.Part.depth == BodyPartDepth.Outside) { IEnumerable source = from x in pawn.health.hediffSet.GetNotMissingParts(BodyPartHeight.Undefined, BodyPartDepth.Undefined) where x.parent == injury.Part && x.def.IsSolid(x, pawn.health.hediffSet.hediffs) && x.depth == BodyPartDepth.Inside select x; - BodyPartRecord part; - if (source.TryRandomElementByWeight((BodyPartRecord x) => x.coverageAbs, out part)) + BodyPartRecord part = default(BodyPartRecord); + if (source.TryRandomElementByWeight((Func)((BodyPartRecord x) => x.coverageAbs), out part)) { HediffDef hediffDefFromDamage = HealthUtility.GetHediffDefFromDamage(dinfo.Def, pawn, part); Hediff_Injury hediff_Injury = (Hediff_Injury)HediffMaker.MakeHediff(hediffDefFromDamage, pawn, null); @@ -283,28 +282,23 @@ private void CheckPropagateDamageToInnerSolidParts(DamageInfo dinfo, Pawn pawn, { hediff_Injury.Severity = (float)ArmorUtility.GetPostArmorDamage(pawn, dinfo.Amount / 2, part, dinfo.Def); } - if (hediff_Injury.Severity <= 0f) + if (!(hediff_Injury.Severity <= 0.0)) { - return; + result.lastHitPart = hediff_Injury.Part; + this.FinalizeAndAddInjury(pawn, hediff_Injury, dinfo, ref result); } - result.lastHitPart = hediff_Injury.Part; - this.FinalizeAndAddInjury(pawn, hediff_Injury, dinfo, ref result); } } } - private void CheckDuplicateDamageToOuterParts(DamageInfo dinfo, Pawn pawn, Hediff_Injury injury, bool involveArmor, ref DamageWorker_AddInjury.LocalInjuryResult result) + private void CheckDuplicateDamageToOuterParts(DamageInfo dinfo, Pawn pawn, Hediff_Injury injury, bool involveArmor, ref LocalInjuryResult result) { - if (!dinfo.AllowDamagePropagation) - { - return; - } - if (dinfo.Def.harmAllLayersUntilOutside && injury.Part.depth == BodyPartDepth.Inside) + if (dinfo.AllowDamagePropagation && dinfo.Def.harmAllLayersUntilOutside && injury.Part.depth == BodyPartDepth.Inside) { BodyPartRecord parent = injury.Part.parent; - do + while (true) { - if (pawn.health.hediffSet.GetPartHealth(parent) != 0f) + if (pawn.health.hediffSet.GetPartHealth(parent) != 0.0) { HediffDef hediffDefFromDamage = HealthUtility.GetHediffDefFromDamage(dinfo.Def, pawn, parent); Hediff_Injury hediff_Injury = (Hediff_Injury)HediffMaker.MakeHediff(hediffDefFromDamage, pawn, null); @@ -316,20 +310,22 @@ private void CheckDuplicateDamageToOuterParts(DamageInfo dinfo, Pawn pawn, Hedif { hediff_Injury.Severity = (float)ArmorUtility.GetPostArmorDamage(pawn, dinfo.Amount, parent, dinfo.Def); } - if (hediff_Injury.Severity <= 0f) + if (hediff_Injury.Severity <= 0.0) { hediff_Injury.Severity = 1f; } result.lastHitPart = hediff_Injury.Part; this.FinalizeAndAddInjury(pawn, hediff_Injury, dinfo, ref result); } - if (parent.depth == BodyPartDepth.Outside) + if (parent.depth != BodyPartDepth.Outside) { - break; + parent = parent.parent; + if (parent == null) + break; + continue; } - parent = parent.parent; + break; } - while (parent != null); } } @@ -339,7 +335,11 @@ private static void InformPsychology(DamageInfo dinfo, Pawn pawn) private static bool IsHeadshot(DamageInfo dinfo, Hediff_Injury injury, Pawn pawn) { - return !dinfo.InstantOldInjury && injury.Part.groups.Contains(BodyPartGroupDefOf.FullHead) && dinfo.Def == DamageDefOf.Bullet; + if (dinfo.InstantOldInjury) + { + return false; + } + return injury.Part.groups.Contains(BodyPartGroupDefOf.FullHead) && dinfo.Def == DamageDefOf.Bullet; } private static BodyPartRecord GetExactPartFromDamageInfo(DamageInfo dinfo, Pawn pawn) @@ -348,7 +348,7 @@ private static BodyPartRecord GetExactPartFromDamageInfo(DamageInfo dinfo, Pawn { return (from x in pawn.health.hediffSet.GetNotMissingParts(BodyPartHeight.Undefined, BodyPartDepth.Undefined) where x == dinfo.ForceHitPart - select x).FirstOrDefault(); + select x).FirstOrDefault(); } BodyPartRecord randomNotMissingPart = pawn.health.hediffSet.GetRandomNotMissingPart(dinfo.Def, dinfo.Height, dinfo.Depth); if (randomNotMissingPart == null) @@ -360,21 +360,9 @@ private static BodyPartRecord GetExactPartFromDamageInfo(DamageInfo dinfo, Pawn private static void PlayWoundedVoiceSound(DamageInfo dinfo, Pawn pawn) { - if (pawn.Dead) - { - return; - } - if (dinfo.InstantOldInjury) - { - return; - } - if (!pawn.SpawnedOrAnyParentSpawned) - { - return; - } - if (dinfo.Def.externalViolence) + if (!pawn.Dead && !dinfo.InstantOldInjury && pawn.SpawnedOrAnyParentSpawned && dinfo.Def.externalViolence) { - LifeStageUtility.PlayNearestLifestageSound(pawn, (LifeStageAge ls) => ls.soundWounded, 1f); + LifeStageUtility.PlayNearestLifestageSound(pawn, (Func)((LifeStageAge ls) => ls.soundWounded), 1f); } } } diff --git a/Assembly-CSharp/Verse/DamageWorker_Extinguish.cs b/Assembly-CSharp/Verse/DamageWorker_Extinguish.cs index 7e128316c..772e4894d 100644 --- a/Assembly-CSharp/Verse/DamageWorker_Extinguish.cs +++ b/Assembly-CSharp/Verse/DamageWorker_Extinguish.cs @@ -1,5 +1,4 @@ using RimWorld; -using System; namespace Verse { diff --git a/Assembly-CSharp/Verse/DamageWorker_Flame.cs b/Assembly-CSharp/Verse/DamageWorker_Flame.cs index 526ece056..2fd22a931 100644 --- a/Assembly-CSharp/Verse/DamageWorker_Flame.cs +++ b/Assembly-CSharp/Verse/DamageWorker_Flame.cs @@ -1,5 +1,4 @@ using RimWorld; -using System; using System.Collections.Generic; namespace Verse @@ -21,12 +20,12 @@ public override float Apply(DamageInfo dinfo, Thing victim) float result = base.Apply(dinfo, victim); if (victim.Destroyed && map != null && pawn == null) { - foreach (IntVec3 current in victim.OccupiedRect()) + foreach (IntVec3 item in victim.OccupiedRect()) { - FilthMaker.MakeFilth(current, map, ThingDefOf.FilthAsh, 1); + FilthMaker.MakeFilth(item, map, ThingDefOf.FilthAsh, 1); } Plant plant = victim as Plant; - if (plant != null && victim.def.plant.IsTree && plant.LifeStage != PlantLifeStage.Sowing && victim.def != ThingDefOf.BurnedTree) + if (plant != null && victim.def.plant.IsTree && plant.LifeStage != 0 && victim.def != ThingDefOf.BurnedTree) { DeadPlant deadPlant = (DeadPlant)GenSpawn.Spawn(ThingDefOf.BurnedTree, victim.Position, map); deadPlant.Growth = plant.Growth; @@ -38,7 +37,7 @@ public override float Apply(DamageInfo dinfo, Thing victim) public override void ExplosionAffectCell(Explosion explosion, IntVec3 c, List damagedThings, bool canThrowMotes) { base.ExplosionAffectCell(explosion, c, damagedThings, canThrowMotes); - if (this.def == DamageDefOf.Flame && Rand.Chance(FireUtility.ChanceToStartFireIn(c, explosion.Map))) + if (base.def == DamageDefOf.Flame && Rand.Chance(FireUtility.ChanceToStartFireIn(c, explosion.Map))) { FireUtility.TryStartFireIn(c, explosion.Map, Rand.Range(0.2f, 0.6f)); } diff --git a/Assembly-CSharp/Verse/DamagedMatPool.cs b/Assembly-CSharp/Verse/DamagedMatPool.cs index b78c9e862..3d7bf2f44 100644 --- a/Assembly-CSharp/Verse/DamagedMatPool.cs +++ b/Assembly-CSharp/Verse/DamagedMatPool.cs @@ -1,4 +1,3 @@ -using System; using System.Collections.Generic; using UnityEngine; @@ -20,11 +19,11 @@ public static int MatCount public static Material GetDamageFlashMat(Material baseMat, float damPct) { - if (damPct < 0.01f) + if (damPct < 0.0099999997764825821) { return baseMat; } - Material material; + Material material = default(Material); if (!DamagedMatPool.damagedMats.TryGetValue(baseMat, out material)) { material = new Material(baseMat); diff --git a/Assembly-CSharp/Verse/Danger.cs b/Assembly-CSharp/Verse/Danger.cs index a6707e4c6..14a25a9b3 100644 --- a/Assembly-CSharp/Verse/Danger.cs +++ b/Assembly-CSharp/Verse/Danger.cs @@ -1,12 +1,10 @@ -using System; - namespace Verse { public enum Danger : byte { - Unspecified, - None, - Some, - Deadly + Unspecified = 0, + None = 1, + Some = 2, + Deadly = 3 } } diff --git a/Assembly-CSharp/Verse/DangerUtility.cs b/Assembly-CSharp/Verse/DangerUtility.cs index c08089d8a..cb2fac632 100644 --- a/Assembly-CSharp/Verse/DangerUtility.cs +++ b/Assembly-CSharp/Verse/DangerUtility.cs @@ -1,5 +1,4 @@ using RimWorld; -using System; using UnityEngine; namespace Verse @@ -35,30 +34,30 @@ public static Danger NormalMaxDanger(this Pawn p) { return Danger.Deadly; } - if (p.Faction != Faction.OfPlayer) + if (p.Faction == Faction.OfPlayer) { + if (p.health.hediffSet.HasTemperatureInjury(TemperatureInjuryStage.Minor) && GenTemperature.FactionOwnsPassableRoomInTemperatureRange(p.Faction, p.SafeTemperatureRange(), p.MapHeld)) + { + return Danger.None; + } return Danger.Some; } - if (p.health.hediffSet.HasTemperatureInjury(TemperatureInjuryStage.Minor) && GenTemperature.FactionOwnsPassableRoomInTemperatureRange(p.Faction, p.SafeTemperatureRange(), p.MapHeld)) - { - return Danger.None; - } return Danger.Some; } public static Danger GetDangerFor(this IntVec3 c, Pawn p, Map map) { Map mapHeld = p.MapHeld; - if (mapHeld == null || mapHeld != map) - { - return Danger.None; - } - Region region = c.GetRegion(mapHeld, RegionType.Set_All); - if (region == null) + if (mapHeld != null && mapHeld == map) { - return Danger.None; + Region region = c.GetRegion(mapHeld, RegionType.Set_All); + if (region == null) + { + return Danger.None; + } + return region.DangerFor(p); } - return region.DangerFor(p); + return Danger.None; } } } diff --git a/Assembly-CSharp/Verse/DataAnalysisLogger.cs b/Assembly-CSharp/Verse/DataAnalysisLogger.cs index 1280544b3..0e9a60413 100644 --- a/Assembly-CSharp/Verse/DataAnalysisLogger.cs +++ b/Assembly-CSharp/Verse/DataAnalysisLogger.cs @@ -1,7 +1,6 @@ using RimWorld; using RimWorld.Planet; using System; -using System.Collections; using System.Collections.Generic; using System.Linq; using System.Text; @@ -101,28 +100,21 @@ public static void DoLog_ObjectHoldPaths() public static void DoLog_ListSolidBackstories() { - IEnumerable enumerable = SolidBioDatabase.allBios.SelectMany((PawnBio bio) => bio.adulthood.spawnCategories).Distinct(); + IEnumerable enumerable = SolidBioDatabase.allBios.SelectMany((Func>)((PawnBio bio) => bio.adulthood.spawnCategories)).Distinct(); List list = new List(); - foreach (string current in enumerable) + foreach (string item2 in enumerable) { - string catInner = current; - FloatMenuOption item = new FloatMenuOption(catInner, delegate + string catInner = item2; + FloatMenuOption item = new FloatMenuOption(catInner, (Action)delegate() { IEnumerable enumerable2 = from b in SolidBioDatabase.allBios where b.adulthood.spawnCategories.Contains(catInner) select b; StringBuilder stringBuilder = new StringBuilder(); - stringBuilder.AppendLine(string.Concat(new object[] + stringBuilder.AppendLine("Backstories with category: " + catInner + " (" + enumerable2.Count() + ")"); + foreach (PawnBio item in enumerable2) { - "Backstories with category: ", - catInner, - " (", - enumerable2.Count(), - ")" - })); - foreach (PawnBio current2 in enumerable2) - { - stringBuilder.AppendLine(current2.ToString()); + stringBuilder.AppendLine(item.ToString()); } Log.Message(stringBuilder.ToString()); }, MenuOptionPriority.Default, null, null, 0f, null, null); @@ -134,13 +126,9 @@ where b.adulthood.spawnCategories.Contains(catInner) public static void DoLog_KeyStrings() { StringBuilder stringBuilder = new StringBuilder(); - using (IEnumerator enumerator = Enum.GetValues(typeof(KeyCode)).GetEnumerator()) + foreach (int value in Enum.GetValues(typeof(KeyCode))) { - while (enumerator.MoveNext()) - { - KeyCode keyCode = (KeyCode)((int)enumerator.Current); - stringBuilder.AppendLine(keyCode.ToString() + " - " + keyCode.ToStringReadable()); - } + stringBuilder.AppendLine(((Enum)(object)(KeyCode)value).ToString() + " - " + ((KeyCode)value).ToStringReadable()); } Log.Message(stringBuilder.ToString()); } @@ -152,19 +140,11 @@ where k.RaceProps.Humanlike orderby k.combatPower select k; List list = new List(); - foreach (PawnKindDef current in orderedEnumerable) + foreach (PawnKindDef item2 in orderedEnumerable) { - Faction fac = FactionUtility.DefaultFactionFrom(current.defaultFactionType); - PawnKindDef kind = current; - FloatMenuOption item = new FloatMenuOption(string.Concat(new object[] - { - kind.defName, - "(", - kind.combatPower, - ", $", - kind.weaponMoney, - ")" - }), delegate + Faction fac = FactionUtility.DefaultFactionFrom(item2.defaultFactionType); + PawnKindDef kind = item2; + FloatMenuOption item = new FloatMenuOption(kind.defName + "(" + kind.combatPower + ", $" + kind.weaponMoney + ")", (Action)delegate() { DefMap weapons = new DefMap(); for (int i = 0; i < 500; i++) @@ -172,31 +152,25 @@ orderby k.combatPower Pawn pawn = PawnGenerator.GeneratePawn(kind, fac); if (pawn.equipment.Primary != null) { - DefMap weapons2; - DefMap expr_4B = weapons2 = weapons; + DefMap defMap; + DefMap obj = defMap = weapons; ThingDef def; - ThingDef expr_5E = def = pawn.equipment.Primary.def; - int num = weapons2[def]; - expr_4B[expr_5E] = num + 1; + ThingDef def2 = def = pawn.equipment.Primary.def; + int num = defMap[def]; + obj[def2] = num + 1; } pawn.Destroy(DestroyMode.Vanish); } StringBuilder stringBuilder = new StringBuilder(); - stringBuilder.AppendLine(string.Concat(new object[] - { - "Weapons spawned from ", - 500, - "x ", - kind.defName - })); - foreach (ThingDef current2 in from t in DefDatabase.AllDefs + stringBuilder.AppendLine("Weapons spawned from " + 500 + "x " + kind.defName); + foreach (ThingDef item in from t in DefDatabase.AllDefs orderby weapons[t] descending select t) { - int num2 = weapons[current2]; + int num2 = weapons[item]; if (num2 > 0) { - stringBuilder.AppendLine(" " + current2.defName + " " + ((float)num2 / 500f).ToStringPercent()); + stringBuilder.AppendLine(" " + item.defName + " " + ((float)((float)num2 / 500.0)).ToStringPercent()); } } Log.Message(stringBuilder.ToString().TrimEndNewlines()); @@ -211,33 +185,33 @@ public static void DoLog_RecipeSkills() StringBuilder stringBuilder = new StringBuilder(); stringBuilder.AppendLine("Recipes per skill, with work speed stats:"); stringBuilder.AppendLine("(No skill)"); - foreach (RecipeDef current in DefDatabase.AllDefs) + foreach (RecipeDef allDef in DefDatabase.AllDefs) { - if (current.workSkill == null) + if (allDef.workSkill == null) { - stringBuilder.Append(" " + current.defName); - if (current.workSpeedStat != null) + stringBuilder.Append(" " + allDef.defName); + if (allDef.workSpeedStat != null) { - stringBuilder.Append(" (" + current.workSpeedStat + ")"); + stringBuilder.Append(" (" + allDef.workSpeedStat + ")"); } stringBuilder.AppendLine(); } } stringBuilder.AppendLine(); - foreach (SkillDef current2 in DefDatabase.AllDefs) + foreach (SkillDef allDef2 in DefDatabase.AllDefs) { - stringBuilder.AppendLine(current2.label); - foreach (RecipeDef current3 in DefDatabase.AllDefs) + stringBuilder.AppendLine(allDef2.label); + foreach (RecipeDef allDef3 in DefDatabase.AllDefs) { - if (current3.workSkill == current2) + if (allDef3.workSkill == allDef2) { - stringBuilder.Append(" " + current3.defName); - if (current3.workSpeedStat != null) + stringBuilder.Append(" " + allDef3.defName); + if (allDef3.workSpeedStat != null) { - stringBuilder.Append(" (" + current3.workSpeedStat); - if (!current3.workSpeedStat.skillNeedFactors.NullOrEmpty()) + stringBuilder.Append(" (" + allDef3.workSpeedStat); + if (!allDef3.workSpeedStat.skillNeedFactors.NullOrEmpty()) { - stringBuilder.Append(" - " + GenText.ToCommaList(from fac in current3.workSpeedStat.skillNeedFactors + stringBuilder.Append(" - " + GenText.ToCommaList(from fac in allDef3.workSpeedStat.skillNeedFactors select fac.skill.defName, false)); } stringBuilder.Append(")"); @@ -256,18 +230,10 @@ public static void DoLog_RaidStrategies() stringBuilder.AppendLine("Raid strategy chances:"); float num = (from d in DefDatabase.AllDefs select d.Worker.SelectionChance(Find.VisibleMap)).Sum(); - foreach (RaidStrategyDef current in DefDatabase.AllDefs) + foreach (RaidStrategyDef allDef in DefDatabase.AllDefs) { - float num2 = current.Worker.SelectionChance(Find.VisibleMap); - stringBuilder.AppendLine(string.Concat(new string[] - { - current.defName, - ": ", - num2.ToString("F2"), - " (", - (num2 / num).ToStringPercent(), - ")" - })); + float num2 = allDef.Worker.SelectionChance(Find.VisibleMap); + stringBuilder.AppendLine(allDef.defName + ": " + num2.ToString("F2") + " (" + (num2 / num).ToStringPercent() + ")"); } Log.Message(stringBuilder.ToString()); } @@ -277,56 +243,46 @@ public static void DoLog_StockGeneratorsDefs() if (Find.VisibleMap == null) { Log.Error("Requires visible map."); - return; } - StringBuilder sb = new StringBuilder(); - Action action = delegate(StockGenerator gen) + else { - sb.AppendLine(gen.GetType().ToString()); - sb.AppendLine("ALLOWED DEFS:"); - foreach (ThingDef current in from d in DefDatabase.AllDefs - where gen.HandlesThingDef(d) - select d) + StringBuilder sb = new StringBuilder(); + Action action = (Action)delegate(StockGenerator gen) { - sb.AppendLine(string.Concat(new object[] + sb.AppendLine(gen.GetType().ToString()); + sb.AppendLine("ALLOWED DEFS:"); + foreach (ThingDef item in from d in DefDatabase.AllDefs + where gen.HandlesThingDef(d) + select d) { - current.defName, - " [", - current.BaseMarketValue, - "]" - })); - } - sb.AppendLine(); - sb.AppendLine("GENERATION TEST:"); - gen.countRange = IntRange.one; - for (int i = 0; i < 30; i++) - { - foreach (Thing current2 in gen.GenerateThings(Find.VisibleMap.Tile)) + sb.AppendLine(item.defName + " [" + item.BaseMarketValue + "]"); + } + sb.AppendLine(); + sb.AppendLine("GENERATION TEST:"); + gen.countRange = IntRange.one; + for (int i = 0; i < 30; i++) { - sb.AppendLine(string.Concat(new object[] + foreach (Thing item2 in gen.GenerateThings(Find.VisibleMap.Tile)) { - current2.Label, - " [", - current2.MarketValue, - "]" - })); + sb.AppendLine(item2.Label + " [" + item2.MarketValue + "]"); + } } - } - sb.AppendLine("---------------------------------------------------------"); - }; - action(new StockGenerator_Armor()); - action(new StockGenerator_WeaponsRanged()); - action(new StockGenerator_Clothes()); - action(new StockGenerator_Art()); - Log.Message(sb.ToString()); + sb.AppendLine("---------------------------------------------------------"); + }; + action(new StockGenerator_Armor()); + action(new StockGenerator_WeaponsRanged()); + action(new StockGenerator_Clothes()); + action(new StockGenerator_Art()); + Log.Message(sb.ToString()); + } } public static void DoLog_TraderStockMarketValues() { StringBuilder stringBuilder = new StringBuilder(); - foreach (TraderKindDef current in DefDatabase.AllDefs) + foreach (TraderKindDef allDef in DefDatabase.AllDefs) { - stringBuilder.AppendLine(current.defName + " : " + ((ItemCollectionGenerator_TraderStock)ItemCollectionGeneratorDefOf.TraderStock.Worker).AverageTotalStockValue(current).ToString("F0")); + stringBuilder.AppendLine(allDef.defName + " : " + ((ItemCollectionGenerator_TraderStock)ItemCollectionGeneratorDefOf.TraderStock.Worker).AverageTotalStockValue(allDef).ToString("F0")); } Log.Message(stringBuilder.ToString()); } @@ -334,10 +290,10 @@ public static void DoLog_TraderStockMarketValues() public static void DoLog_TraderStockGeneration() { List list = new List(); - foreach (TraderKindDef current in DefDatabase.AllDefs) + foreach (TraderKindDef allDef in DefDatabase.AllDefs) { - TraderKindDef localDef = current; - FloatMenuOption item = new FloatMenuOption(localDef.defName, delegate + TraderKindDef localDef = allDef; + FloatMenuOption item = new FloatMenuOption(localDef.defName, (Action)delegate { Log.Message(((ItemCollectionGenerator_TraderStock)ItemCollectionGeneratorDefOf.TraderStock.Worker).GenerationDataFor(localDef)); }, MenuOptionPriority.Default, null, null, 0f, null, null); @@ -349,24 +305,29 @@ public static void DoLog_TraderStockGeneration() public static void DoLog_BodyPartTagGroups() { List list = new List(); - foreach (BodyDef current in DefDatabase.AllDefs) + foreach (BodyDef allDef in DefDatabase.AllDefs) { - BodyDef localBd = current; - FloatMenuOption item = new FloatMenuOption(localBd.defName, delegate + BodyDef localBd = allDef; + FloatMenuOption item = new FloatMenuOption(localBd.defName, (Action)delegate() { StringBuilder stringBuilder = new StringBuilder(); stringBuilder.AppendLine(localBd.defName + "\n----------------"); - foreach (string tag in (from elem in localBd.AllParts.SelectMany((BodyPartRecord part) => part.def.tags) + using (IEnumerator enumerator2 = (from elem in localBd.AllParts.SelectMany((Func>)((BodyPartRecord part) => part.def.tags)) orderby elem - select elem).Distinct()) + select elem).Distinct().GetEnumerator()) { - stringBuilder.AppendLine(tag); - foreach (BodyPartRecord current2 in from part in localBd.AllParts - where part.def.tags.Contains(tag) - orderby part.def.defName - select part) + string tag; + while (enumerator2.MoveNext()) { - stringBuilder.AppendLine(" " + current2.def.defName); + tag = enumerator2.Current; + stringBuilder.AppendLine(tag); + foreach (BodyPartRecord item in from part in localBd.AllParts + where part.def.tags.Contains(tag) + orderby part.def.defName + select part) + { + stringBuilder.AppendLine(" " + item.def.defName); + } } } Log.Message(stringBuilder.ToString()); @@ -380,42 +341,14 @@ public static void DoLog_LoadedAssets() { StringBuilder stringBuilder = new StringBuilder(); UnityEngine.Object[] array = Resources.FindObjectsOfTypeAll(typeof(Mesh)); - stringBuilder.AppendLine(string.Concat(new object[] - { - "Meshes: ", - array.Length, - " (", - DataAnalysisLogger.TotalBytes(array).ToStringBytes("F2"), - ")" - })); + stringBuilder.AppendLine("Meshes: " + array.Length + " (" + DataAnalysisLogger.TotalBytes(array).ToStringBytes("F2") + ")"); UnityEngine.Object[] array2 = Resources.FindObjectsOfTypeAll(typeof(Material)); - stringBuilder.AppendLine(string.Concat(new object[] - { - "Materials: ", - array2.Length, - " (", - DataAnalysisLogger.TotalBytes(array2).ToStringBytes("F2"), - ")" - })); + stringBuilder.AppendLine("Materials: " + array2.Length + " (" + DataAnalysisLogger.TotalBytes(array2).ToStringBytes("F2") + ")"); stringBuilder.AppendLine(" Damaged: " + DamagedMatPool.MatCount); - stringBuilder.AppendLine(string.Concat(new object[] - { - " Faded: ", - FadedMaterialPool.TotalMaterialCount, - " (", - FadedMaterialPool.TotalMaterialBytes.ToStringBytes("F2"), - ")" - })); + stringBuilder.AppendLine(" Faded: " + FadedMaterialPool.TotalMaterialCount + " (" + FadedMaterialPool.TotalMaterialBytes.ToStringBytes("F2") + ")"); stringBuilder.AppendLine(" SolidColorsSimple: " + SolidColorMaterials.SimpleColorMatCount); UnityEngine.Object[] array3 = Resources.FindObjectsOfTypeAll(typeof(Texture)); - stringBuilder.AppendLine(string.Concat(new object[] - { - "Textures: ", - array3.Length, - " (", - DataAnalysisLogger.TotalBytes(array3).ToStringBytes("F2"), - ")" - })); + stringBuilder.AppendLine("Textures: " + array3.Length + " (" + DataAnalysisLogger.TotalBytes(array3).ToStringBytes("F2") + ")"); stringBuilder.AppendLine(); stringBuilder.AppendLine("Texture list:"); UnityEngine.Object[] array4 = array3; @@ -446,15 +379,15 @@ private static int TotalBytes(UnityEngine.Object[] arr) public static void DoLog_MinifiableTags() { StringBuilder stringBuilder = new StringBuilder(); - foreach (ThingDef current in DefDatabase.AllDefs) + foreach (ThingDef allDef in DefDatabase.AllDefs) { - if (current.Minifiable) + if (allDef.Minifiable) { - stringBuilder.Append(current.defName); - if (!current.tradeTags.NullOrEmpty()) + stringBuilder.Append(allDef.defName); + if (!allDef.tradeTags.NullOrEmpty()) { stringBuilder.Append(" - "); - stringBuilder.Append(GenText.ToCommaList(current.tradeTags, true)); + stringBuilder.Append(GenText.ToCommaList(allDef.tradeTags, true)); } stringBuilder.AppendLine(); } @@ -465,12 +398,12 @@ public static void DoLog_MinifiableTags() public static void DoLog_ItemBeauties() { StringBuilder stringBuilder = new StringBuilder(); - foreach (ThingDef current in from d in DefDatabase.AllDefs + foreach (ThingDef item in from d in DefDatabase.AllDefs where d.category == ThingCategory.Item && !d.destroyOnDrop orderby d.GetStatValueAbstract(StatDefOf.Beauty, null) descending select d) { - stringBuilder.AppendLine(current.defName + " " + current.GetStatValueAbstract(StatDefOf.Beauty, null).ToString("F1")); + stringBuilder.AppendLine(item.defName + " " + item.GetStatValueAbstract(StatDefOf.Beauty, null).ToString("F1")); } Log.Message(stringBuilder.ToString()); } @@ -478,15 +411,15 @@ orderby d.GetStatValueAbstract(StatDefOf.Beauty, null) descending public static void DoLog_TestRulepack() { List list = new List(); - foreach (RulePackDef current in DefDatabase.AllDefs) + foreach (RulePackDef allDef in DefDatabase.AllDefs) { - RulePackDef localNamer = current; - FloatMenuOption item = new FloatMenuOption(localNamer.defName, delegate + RulePackDef localNamer = allDef; + FloatMenuOption item = new FloatMenuOption(localNamer.defName, (Action)delegate { StringBuilder stringBuilder = new StringBuilder(); for (int i = 0; i < 200; i++) { - stringBuilder.AppendLine(NameGenerator.GenerateName(localNamer, null, false)); + stringBuilder.AppendLine(NameGenerator.GenerateName(localNamer, (Predicate)null, false)); } Log.Message(stringBuilder.ToString()); }, MenuOptionPriority.Default, null, null, 0f, null, null); @@ -498,16 +431,16 @@ public static void DoLog_TestRulepack() public static void DoLog_GeneratedNames() { List list = new List(); - foreach (RulePackDef current in DefDatabase.AllDefs) + foreach (RulePackDef allDef in DefDatabase.AllDefs) { - RulePackDef localRp = current; - FloatMenuOption item = new FloatMenuOption(localRp.defName, delegate + RulePackDef localRp = allDef; + FloatMenuOption item = new FloatMenuOption(localRp.defName, (Action)delegate { StringBuilder stringBuilder = new StringBuilder(); stringBuilder.AppendLine("Test names for " + localRp.defName + ":"); for (int i = 0; i < 200; i++) { - stringBuilder.AppendLine(NameGenerator.GenerateName(localRp, null, false)); + stringBuilder.AppendLine(NameGenerator.GenerateName(localRp, (Predicate)null, false)); } Log.Message(stringBuilder.ToString()); }, MenuOptionPriority.Default, null, null, 0f, null, null); @@ -519,28 +452,17 @@ public static void DoLog_GeneratedNames() public static void DoLog_ThingList() { List list = new List(); - using (IEnumerator enumerator = Enum.GetValues(typeof(ThingRequestGroup)).GetEnumerator()) + foreach (byte value in Enum.GetValues(typeof(ThingRequestGroup))) { - while (enumerator.MoveNext()) + ThingRequestGroup localRg = (ThingRequestGroup)value; + FloatMenuOption item = new FloatMenuOption(((Enum)(object)localRg).ToString(), (Action)delegate { - ThingRequestGroup localRg2 = (ThingRequestGroup)((byte)enumerator.Current); - ThingRequestGroup localRg = localRg2; - FloatMenuOption item = new FloatMenuOption(localRg.ToString(), delegate - { - StringBuilder stringBuilder = new StringBuilder(); - List list2 = Find.VisibleMap.listerThings.ThingsInGroup(localRg); - stringBuilder.AppendLine(string.Concat(new object[] - { - "Global things in group ", - localRg, - " (count ", - list2.Count, - ")" - })); - Log.Message(DebugLogsUtility.ThingListToUniqueCountString(list2)); - }, MenuOptionPriority.Default, null, null, 0f, null, null); - list.Add(item); - } + StringBuilder stringBuilder = new StringBuilder(); + List list2 = Find.VisibleMap.listerThings.ThingsInGroup(localRg); + stringBuilder.AppendLine("Global things in group " + localRg + " (count " + list2.Count + ")"); + Log.Message(DebugLogsUtility.ThingListToUniqueCountString(list2)); + }, MenuOptionPriority.Default, null, null, 0f, null, null); + list.Add(item); } Find.WindowStack.Add(new FloatMenu(list)); } @@ -548,28 +470,15 @@ public static void DoLog_ThingList() public static void DoLog_SimpleCurveTest() { StringBuilder stringBuilder = new StringBuilder(); - SimpleCurve simpleCurve = new SimpleCurve - { - { - new CurvePoint(5f, 0f), - true - }, - { - new CurvePoint(10f, 1f), - true - }, - { - new CurvePoint(20f, 3f), - true - }, - { - new CurvePoint(40f, 2f), - true - } - }; + SimpleCurve simpleCurve = new SimpleCurve(); + simpleCurve.Add(new CurvePoint(5f, 0f), true); + simpleCurve.Add(new CurvePoint(10f, 1f), true); + simpleCurve.Add(new CurvePoint(20f, 3f), true); + simpleCurve.Add(new CurvePoint(40f, 2f), true); + SimpleCurve simpleCurve2 = simpleCurve; for (int i = 0; i < 50; i++) { - stringBuilder.AppendLine(i + " -> " + simpleCurve.Evaluate((float)i)); + stringBuilder.AppendLine(i + " -> " + simpleCurve2.Evaluate((float)i)); } Log.Message(stringBuilder.ToString()); } @@ -599,19 +508,9 @@ public static void DoLog_TestPawnNames() stringBuilder.AppendLine("------Testing ResolveMissingPieces consistency"); for (int i = 0; i < 20; i++) { - NameTriple nameTriple = new NameTriple("John", null, "Last"); - nameTriple.ResolveMissingPieces(null); - stringBuilder.AppendLine(string.Concat(new string[] - { - nameTriple.ToString(), - " [", - nameTriple.First, - "] [", - nameTriple.Nick, - "] [", - nameTriple.Last, - "]" - })); + NameTriple nameTriple = new NameTriple("John", (string)null, "Last"); + nameTriple.ResolveMissingPieces((string)null); + stringBuilder.AppendLine(nameTriple.ToString() + " [" + nameTriple.First + "] [" + nameTriple.Nick + "] [" + nameTriple.Last + "]"); } Log.Message(stringBuilder.ToString()); } @@ -619,42 +518,23 @@ public static void DoLog_TestPawnNames() private static string PawnNameTestResult(string rawName) { NameTriple nameTriple = NameTriple.FromString(rawName); - nameTriple.ResolveMissingPieces(null); - return string.Concat(new string[] - { - rawName, - " -> ", - nameTriple.ToString(), - " [", - nameTriple.First, - "] [", - nameTriple.Nick, - "] [", - nameTriple.Last, - "]" - }); + nameTriple.ResolveMissingPieces((string)null); + return rawName + " -> " + nameTriple.ToString() + " [" + nameTriple.First + "] [" + nameTriple.Nick + "] [" + nameTriple.Last + "]"; } public static void DoLog_PassabilityFill() { StringBuilder stringBuilder = new StringBuilder(); - foreach (ThingDef current in DefDatabase.AllDefs) + foreach (ThingDef allDef in DefDatabase.AllDefs) { - if (current.passability != Traversability.Standable || current.fillPercent > 0f) + if (allDef.passability != 0 || allDef.fillPercent > 0.0) { - stringBuilder.Append(string.Concat(new string[] - { - current.defName, - " - pass=", - current.passability.ToString(), - ", fill=", - current.fillPercent.ToStringPercent() - })); - if (current.passability == Traversability.Impassable && current.fillPercent < 0.1f) + stringBuilder.Append(allDef.defName + " - pass=" + ((Enum)(object)allDef.passability).ToString() + ", fill=" + allDef.fillPercent.ToStringPercent()); + if (allDef.passability == Traversability.Impassable && allDef.fillPercent < 0.10000000149011612) { stringBuilder.Append(" ALERT, impassable with low fill"); } - if (current.passability != Traversability.Impassable && current.fillPercent > 0.8f) + if (allDef.passability != Traversability.Impassable && allDef.fillPercent > 0.800000011920929) { stringBuilder.Append(" ALERT, passabile with very high fill"); } @@ -667,75 +547,59 @@ public static void DoLog_PassabilityFill() public static void DoLog_AnimalsPerBiome() { IEnumerable enumerable = from d in DefDatabase.AllDefs - where d.animalDensity > 0f + where d.animalDensity > 0.0 select d; IOrderedEnumerable source = from d in DefDatabase.AllDefs where d.race.race.Animal - orderby (!d.race.race.predator) ? 0 : 1 + orderby d.race.race.predator ? 1 : 0 select d; - string text = string.Empty; - text += "name commonality commonalityShare size\n\n"; - foreach (BiomeDef b in enumerable) + string empty = string.Empty; + empty += "name commonality commonalityShare size\n\n"; + using (IEnumerator enumerator = enumerable.GetEnumerator()) { - float num = source.Sum((PawnKindDef a) => b.CommonalityOfAnimal(a)); - float f = (from a in source - where a.race.race.predator - select a).Sum((PawnKindDef a) => b.CommonalityOfAnimal(a)) / num; - float num2 = source.Sum((PawnKindDef a) => b.CommonalityOfAnimal(a) * a.race.race.baseBodySize); - float f2 = (from a in source - where a.race.race.predator - select a).Sum((PawnKindDef a) => b.CommonalityOfAnimal(a) * a.race.race.baseBodySize) / num2; - string text2 = text; - text = string.Concat(new string[] - { - text2, - b.label, - " (predators: ", - f.ToStringPercent("F2"), - ", predators by size: ", - f2.ToStringPercent("F2"), - ")" - }); - foreach (PawnKindDef current in from a in source - orderby b.CommonalityOfAnimal(a) descending - select a) + BiomeDef b; + while (enumerator.MoveNext()) { - float num3 = b.CommonalityOfAnimal(current); - if (num3 > 0f) + b = enumerator.Current; + float num = source.Sum((Func)((PawnKindDef a) => b.CommonalityOfAnimal(a))); + float f = (from a in source + where a.race.race.predator + select a).Sum((Func)((PawnKindDef a) => b.CommonalityOfAnimal(a))) / num; + float num2 = source.Sum((Func)((PawnKindDef a) => b.CommonalityOfAnimal(a) * a.race.race.baseBodySize)); + float f2 = (from a in source + where a.race.race.predator + select a).Sum((Func)((PawnKindDef a) => b.CommonalityOfAnimal(a) * a.race.race.baseBodySize)) / num2; + string text = empty; + empty = text + b.label + " (predators: " + f.ToStringPercent("F2") + ", predators by size: " + f2.ToStringPercent("F2") + ")"; + foreach (PawnKindDef item in from a in source + orderby b.CommonalityOfAnimal(a) descending + select a) { - text2 = text; - text = string.Concat(new string[] + float num3 = b.CommonalityOfAnimal(item); + if (num3 > 0.0) { - text2, - "\n ", - current.label, - (!current.RaceProps.predator) ? string.Empty : "*", - " ", - num3.ToString("F3"), - " ", - (num3 / num).ToStringPercent("F2"), - " ", - current.race.race.baseBodySize.ToString("F2") - }); + text = empty; + empty = text + "\n " + item.label + ((!item.RaceProps.predator) ? string.Empty : "*") + " " + num3.ToString("F3") + " " + (num3 / num).ToStringPercent("F2") + " " + item.race.race.baseBodySize.ToString("F2"); + } } + empty += "\n\n"; } - text += "\n\n"; } - Log.Message(text); + Log.Message(empty); } public static void DoLog_SmeltProducts() { StringBuilder stringBuilder = new StringBuilder(); - foreach (ThingDef current in DefDatabase.AllDefs) + foreach (ThingDef allDef in DefDatabase.AllDefs) { - Thing thing = ThingMaker.MakeThing(current, GenStuff.DefaultStuffFor(current)); - if (thing.SmeltProducts(1f).Any()) + Thing thing = ThingMaker.MakeThing(allDef, GenStuff.DefaultStuffFor(allDef)); + if (thing.SmeltProducts(1f).Any()) { stringBuilder.Append(thing.LabelCap + ": "); - foreach (Thing current2 in thing.SmeltProducts(1f)) + foreach (Thing item in thing.SmeltProducts(1f)) { - stringBuilder.Append(" " + current2.Label); + stringBuilder.Append(" " + item.Label); } stringBuilder.AppendLine(); } @@ -762,10 +626,10 @@ public static void DoLog_PawnArrivalCandidates() public static void DoLog_SpecificTaleDescs() { List list = new List(); - foreach (TaleDef current in DefDatabase.AllDefs) + foreach (TaleDef allDef in DefDatabase.AllDefs) { - TaleDef localDef = current; - FloatMenuOption item = new FloatMenuOption(localDef.defName, delegate + TaleDef localDef = allDef; + FloatMenuOption item = new FloatMenuOption(localDef.defName, (Action)delegate { TaleTester.LogSpecificTale(localDef, 40); }, MenuOptionPriority.Default, null, null, 0f, null, null); @@ -778,11 +642,11 @@ public static void DoLog_SocialPropernessMatters() { StringBuilder stringBuilder = new StringBuilder(); stringBuilder.AppendLine("Social-properness-matters things:"); - foreach (ThingDef current in DefDatabase.AllDefs) + foreach (ThingDef allDef in DefDatabase.AllDefs) { - if (current.socialPropernessMatters) + if (allDef.socialPropernessMatters) { - stringBuilder.AppendLine(string.Format(" {0}", current.defName)); + stringBuilder.AppendLine(string.Format(" {0}", allDef.defName)); } } Log.Message(stringBuilder.ToString()); @@ -792,12 +656,12 @@ public static void DoLog_FoodPreferability() { StringBuilder stringBuilder = new StringBuilder(); stringBuilder.AppendLine("Food, ordered by preferability:"); - foreach (ThingDef current in from td in DefDatabase.AllDefs + foreach (ThingDef item in from td in DefDatabase.AllDefs where td.ingestible != null orderby td.ingestible.preferability select td) { - stringBuilder.AppendLine(string.Format(" {0}: {1}", current.ingestible.preferability, current.defName)); + stringBuilder.AppendLine(string.Format(" {0}: {1}", item.ingestible.preferability, item.defName)); } Log.Message(stringBuilder.ToString()); } @@ -808,17 +672,20 @@ public static void DoLog_CaravanRequests() stringBuilder.AppendLine("Caravan request sample:"); Map visibleMap = Find.VisibleMap; IncidentWorker_CaravanRequest incidentWorker_CaravanRequest = (IncidentWorker_CaravanRequest)IncidentDefOf.CaravanRequest.Worker; - for (int i = 0; i < 100; i++) + int num = 0; + while (num < 100) { Settlement settlement = IncidentWorker_CaravanRequest.RandomNearbyTradeableSettlement(visibleMap.Tile); - if (settlement == null) + if (settlement != null) { - break; + CaravanRequestComp component = ((WorldObject)settlement).GetComponent(); + incidentWorker_CaravanRequest.GenerateCaravanRequest(component, visibleMap); + stringBuilder.AppendLine(string.Format(" {0} -> {1}", GenLabel.ThingLabel(component.requestThingDef, null, component.requestCount), component.rewards[0].Label, ThingDefOf.Silver.label)); + ((WorldObject)settlement).GetComponent().Disable(); + num++; + continue; } - CaravanRequestComp component = settlement.GetComponent(); - incidentWorker_CaravanRequest.GenerateCaravanRequest(component, visibleMap); - stringBuilder.AppendLine(string.Format(" {0} -> {1}", GenLabel.ThingLabel(component.requestThingDef, null, component.requestCount), component.rewards[0].Label, ThingDefOf.Silver.label)); - settlement.GetComponent().Disable(); + break; } Log.Message(stringBuilder.ToString()); } diff --git a/Assembly-CSharp/Verse/DataAnalysisTableMaker.cs b/Assembly-CSharp/Verse/DataAnalysisTableMaker.cs index 314099179..5e098d1f2 100644 --- a/Assembly-CSharp/Verse/DataAnalysisTableMaker.cs +++ b/Assembly-CSharp/Verse/DataAnalysisTableMaker.cs @@ -26,31 +26,34 @@ public static void DoTable_ManhunterResults() public static void DoTable_DrugEconomy() { - Func ingredients = delegate(ThingDef d) + Func ingredients = (Func)delegate(ThingDef d) { if (d.costList == null) { return "-"; } StringBuilder stringBuilder = new StringBuilder(); - foreach (ThingCountClass current in d.costList) + List.Enumerator enumerator = d.costList.GetEnumerator(); + try { - if (stringBuilder.Length > 0) + while (enumerator.MoveNext()) { - stringBuilder.Append(", "); + ThingCountClass current = enumerator.Current; + if (stringBuilder.Length > 0) + { + stringBuilder.Append(", "); + } + string text = (!DataAnalysisTableMaker.RequiresBuying(current.thingDef)) ? string.Empty : "*"; + stringBuilder.Append(current.thingDef.defName + text + " x" + current.count); } - string text = (!DataAnalysisTableMaker.RequiresBuying(current.thingDef)) ? string.Empty : "*"; - stringBuilder.Append(string.Concat(new object[] - { - current.thingDef.defName, - text, - " x", - current.count - })); + } + finally + { + ((IDisposable)(object)enumerator).Dispose(); } return stringBuilder.ToString().TrimEndNewlines(); }; - Func workAmount = delegate(ThingDef d) + Func workAmount = (Func)delegate(ThingDef d) { if (d.recipeMaker == null) { @@ -62,67 +65,49 @@ public static void DoTable_DrugEconomy() } return Mathf.Max(d.GetStatValueAbstract(StatDefOf.WorkToMake, null), d.GetStatValueAbstract(StatDefOf.WorkToBuild, null)); }; - Func realIngredientCost = (ThingDef d) => DataAnalysisTableMaker.CostToMake(d, true); - Func realSellPrice = (ThingDef d) => d.BaseMarketValue * 0.5f; - Func realBuyPrice = (ThingDef d) => d.BaseMarketValue * 1.5f; - IEnumerable arg_1BB_0 = from d in DefDatabase.AllDefs + Func realIngredientCost = (Func)((ThingDef d) => DataAnalysisTableMaker.CostToMake(d, true)); + Func realSellPrice = (Func)((ThingDef d) => (float)(d.BaseMarketValue * 0.5)); + Func realBuyPrice = (Func)((ThingDef d) => (float)(d.BaseMarketValue * 1.5)); + DebugTables.MakeTablesDialog(from d in DefDatabase.AllDefs where d.IsWithinCategory(ThingCategoryDefOf.Medicine) || d.IsWithinCategory(ThingCategoryDefOf.Drugs) - select d; - TableDataGetter[] expr_E2 = new TableDataGetter[8]; - expr_E2[0] = new TableDataGetter("name", (ThingDef d) => d.defName); - expr_E2[1] = new TableDataGetter("ingredients", (ThingDef d) => ingredients(d)); - expr_E2[2] = new TableDataGetter("work amount", (ThingDef d) => workAmount(d).ToString("F0")); - expr_E2[3] = new TableDataGetter("real ingredient cost", (ThingDef d) => realIngredientCost(d).ToString("F1")); - expr_E2[4] = new TableDataGetter("real sell price", (ThingDef d) => realSellPrice(d).ToString("F1")); - expr_E2[5] = new TableDataGetter("real profit per item", (ThingDef d) => (realSellPrice(d) - realIngredientCost(d)).ToString("F1")); - expr_E2[6] = new TableDataGetter("real profit per day's work", (ThingDef d) => ((realSellPrice(d) - realIngredientCost(d)) / workAmount(d) * 30000f).ToString("F1")); - expr_E2[7] = new TableDataGetter("real buy price", (ThingDef d) => realBuyPrice(d).ToString("F1")); - DebugTables.MakeTablesDialog(arg_1BB_0, expr_E2); + select d, new TableDataGetter("name", (Func)((ThingDef d) => d.defName)), new TableDataGetter("ingredients", (Func)((ThingDef d) => ingredients(d))), new TableDataGetter("work amount", (Func)((ThingDef d) => workAmount(d).ToString("F0"))), new TableDataGetter("real ingredient cost", (Func)((ThingDef d) => realIngredientCost(d).ToString("F1"))), new TableDataGetter("real sell price", (Func)((ThingDef d) => realSellPrice(d).ToString("F1"))), new TableDataGetter("real profit per item", (Func)((ThingDef d) => (realSellPrice(d) - realIngredientCost(d)).ToString("F1"))), new TableDataGetter("real profit per day's work", (Func)((ThingDef d) => ((float)((realSellPrice(d) - realIngredientCost(d)) / workAmount(d) * 30000.0)).ToString("F1"))), new TableDataGetter("real buy price", (Func)((ThingDef d) => realBuyPrice(d).ToString("F1")))); } public static void DoTable_WoolEconomy() { - IEnumerable arg_129_0 = from d in DefDatabase.AllDefs + DebugTables.MakeTablesDialog(from d in DefDatabase.AllDefs where d.category == ThingCategory.Pawn && d.race.IsFlesh && d.GetCompProperties() != null - select d; - TableDataGetter[] expr_2D = new TableDataGetter[6]; - expr_2D[0] = new TableDataGetter("animal", (ThingDef d) => d.defName); - expr_2D[1] = new TableDataGetter("woolDef", (ThingDef d) => d.GetCompProperties().woolDef.defName); - expr_2D[2] = new TableDataGetter("woolAmount", (ThingDef d) => d.GetCompProperties().woolAmount.ToString()); - expr_2D[3] = new TableDataGetter("woolValue", (ThingDef d) => d.GetCompProperties().woolDef.BaseMarketValue.ToString("F2")); - expr_2D[4] = new TableDataGetter("shear interval", (ThingDef d) => d.GetCompProperties().shearIntervalDays.ToString("F1")); - expr_2D[5] = new TableDataGetter("value per year", delegate(ThingDef d) + select d, new TableDataGetter("animal", (Func)((ThingDef d) => d.defName)), new TableDataGetter("woolDef", (Func)((ThingDef d) => d.GetCompProperties().woolDef.defName)), new TableDataGetter("woolAmount", (Func)((ThingDef d) => d.GetCompProperties().woolAmount.ToString())), new TableDataGetter("woolValue", (Func)((ThingDef d) => d.GetCompProperties().woolDef.BaseMarketValue.ToString("F2"))), new TableDataGetter("shear interval", (Func)((ThingDef d) => d.GetCompProperties().shearIntervalDays.ToString("F1"))), new TableDataGetter("value per year", (Func)delegate(ThingDef d) { CompProperties_Shearable compProperties = d.GetCompProperties(); - return (compProperties.woolDef.BaseMarketValue * (float)compProperties.woolAmount * (60f / (float)compProperties.shearIntervalDays)).ToString("F0"); - }); - DebugTables.MakeTablesDialog(arg_129_0, expr_2D); + return ((float)(compProperties.woolDef.BaseMarketValue * (float)compProperties.woolAmount * (60.0 / (float)compProperties.shearIntervalDays))).ToString("F0"); + })); } public static void DoTable_AnimalGrowthEconomy() { - Func gestDays = delegate(ThingDef d) + Func gestDays = (Func)delegate(ThingDef d) { if (d.HasComp(typeof(CompEggLayer))) { - CompProperties_EggLayer compProperties = d.GetCompProperties(); - return compProperties.eggLayIntervalDays / compProperties.eggCountRange.Average; + CompProperties_EggLayer compProperties2 = d.GetCompProperties(); + return compProperties2.eggLayIntervalDays / compProperties2.eggCountRange.Average; } return d.race.gestationPeriodDays; }; - Func nutritionToGestate = delegate(ThingDef d) + Func nutritionToGestate = (Func)delegate(ThingDef d) { - float num = 0f; - LifeStageAge lifeStageAge = d.race.lifeStageAges[d.race.lifeStageAges.Count - 1]; - return num + gestDays(d) * lifeStageAge.def.hungerRateFactor * d.race.baseHungerRate; + float num4 = 0f; + LifeStageAge lifeStageAge3 = d.race.lifeStageAges[d.race.lifeStageAges.Count - 1]; + return num4 + gestDays(d) * lifeStageAge3.def.hungerRateFactor * d.race.baseHungerRate; }; - Func babyMeatNut = delegate(ThingDef d) + Func babyMeatNut = (Func)delegate(ThingDef d) { - LifeStageAge lifeStageAge = d.race.lifeStageAges[0]; - return d.GetStatValueAbstract(StatDefOf.MeatAmount, null) * 0.05f * lifeStageAge.def.bodySizeFactor; + LifeStageAge lifeStageAge2 = d.race.lifeStageAges[0]; + return (float)(d.GetStatValueAbstract(StatDefOf.MeatAmount, null) * 0.05000000074505806 * lifeStageAge2.def.bodySizeFactor); }; - Func babyMeatNutPerInput = (ThingDef d) => babyMeatNut(d) / nutritionToGestate(d); - Func nutritionToAdulthood = delegate(ThingDef d) + Func babyMeatNutPerInput = (Func)((ThingDef d) => babyMeatNut(d) / nutritionToGestate(d)); + Func nutritionToAdulthood = (Func)delegate(ThingDef d) { float num = 0f; num += nutritionToGestate(d); @@ -130,19 +115,19 @@ public static void DoTable_AnimalGrowthEconomy() { LifeStageAge lifeStageAge = d.race.lifeStageAges[i]; float num2 = lifeStageAge.minAge - d.race.lifeStageAges[i - 1].minAge; - float num3 = num2 * 60f; + float num3 = (float)(num2 * 60.0); num += num3 * lifeStageAge.def.hungerRateFactor * d.race.baseHungerRate; } return num; }; - Func adultMeatNutPerInput = (ThingDef d) => d.GetStatValueAbstract(StatDefOf.MeatAmount, null) * 0.05f / nutritionToAdulthood(d); - Func bestMeatPerInput = delegate(ThingDef d) + Func adultMeatNutPerInput = (Func)((ThingDef d) => (float)(d.GetStatValueAbstract(StatDefOf.MeatAmount, null) * 0.05000000074505806 / nutritionToAdulthood(d))); + Func bestMeatPerInput = (Func)delegate(ThingDef d) { float a = babyMeatNutPerInput(d); float b = adultMeatNutPerInput(d); return Mathf.Max(a, b); }; - Func eggNut = delegate(ThingDef d) + Func eggNut = (Func)delegate(ThingDef d) { CompProperties_EggLayer compProperties = d.GetCompProperties(); if (compProperties == null) @@ -151,81 +136,38 @@ public static void DoTable_AnimalGrowthEconomy() } return compProperties.eggFertilizedDef.ingestible.nutrition.ToString("F2"); }; - IEnumerable arg_37D_0 = from d in DefDatabase.AllDefs + DebugTables.MakeTablesDialog(from d in DefDatabase.AllDefs where d.category == ThingCategory.Pawn && d.race.IsFlesh orderby bestMeatPerInput(d) descending - select d; - TableDataGetter[] expr_108 = new TableDataGetter[18]; - expr_108[0] = new TableDataGetter("animal", (ThingDef d) => d.defName); - expr_108[1] = new TableDataGetter("hungerRate", (ThingDef d) => d.race.baseHungerRate.ToString("F2")); - expr_108[2] = new TableDataGetter("gestDays", (ThingDef d) => gestDays(d).ToString("F2")); - expr_108[3] = new TableDataGetter("herbiv", (ThingDef d) => ((d.race.foodType & FoodTypeFlags.Plant) == FoodTypeFlags.None) ? string.Empty : "Y"); - expr_108[4] = new TableDataGetter("eggs", (ThingDef d) => (!d.HasComp(typeof(CompEggLayer))) ? string.Empty : d.GetCompProperties().eggCountRange.ToString()); - expr_108[5] = new TableDataGetter("|", (ThingDef d) => "|"); - expr_108[6] = new TableDataGetter("bodySize", (ThingDef d) => d.race.baseBodySize.ToString("F2")); - expr_108[7] = new TableDataGetter("age Adult", (ThingDef d) => d.race.lifeStageAges[d.race.lifeStageAges.Count - 1].minAge.ToString("F2")); - expr_108[8] = new TableDataGetter("nutrition to adulthood", (ThingDef d) => nutritionToAdulthood(d).ToString("F2")); - expr_108[9] = new TableDataGetter("adult meat-nut", (ThingDef d) => (d.GetStatValueAbstract(StatDefOf.MeatAmount, null) * 0.05f).ToString("F2")); - expr_108[10] = new TableDataGetter("adult meat-nut / input-nut", (ThingDef d) => adultMeatNutPerInput(d).ToString("F3")); - expr_108[11] = new TableDataGetter("|", (ThingDef d) => "|"); - expr_108[12] = new TableDataGetter("baby size", (ThingDef d) => (d.race.lifeStageAges[0].def.bodySizeFactor * d.race.baseBodySize).ToString("F2")); - expr_108[13] = new TableDataGetter("nutrition to gestate", (ThingDef d) => nutritionToGestate(d).ToString("F2")); - expr_108[14] = new TableDataGetter("egg nut", (ThingDef d) => eggNut(d)); - expr_108[15] = new TableDataGetter("baby meat-nut", (ThingDef d) => babyMeatNut(d).ToString("F2")); - expr_108[16] = new TableDataGetter("baby meat-nut / input-nut", (ThingDef d) => babyMeatNutPerInput(d).ToString("F2")); - expr_108[17] = new TableDataGetter("baby wins", (ThingDef d) => (babyMeatNutPerInput(d) <= adultMeatNutPerInput(d)) ? string.Empty : "B"); - DebugTables.MakeTablesDialog(arg_37D_0, expr_108); + select d, new TableDataGetter("animal", (Func)((ThingDef d) => d.defName)), new TableDataGetter("hungerRate", (Func)((ThingDef d) => d.race.baseHungerRate.ToString("F2"))), new TableDataGetter("gestDays", (Func)((ThingDef d) => gestDays(d).ToString("F2"))), new TableDataGetter("herbiv", (Func)((ThingDef d) => (((int)d.race.foodType & 64) == 0) ? string.Empty : "Y")), new TableDataGetter("eggs", (Func)((ThingDef d) => (!d.HasComp(typeof(CompEggLayer))) ? string.Empty : d.GetCompProperties().eggCountRange.ToString())), new TableDataGetter("|", (Func)((ThingDef d) => "|")), new TableDataGetter("bodySize", (Func)((ThingDef d) => d.race.baseBodySize.ToString("F2"))), new TableDataGetter("age Adult", (Func)((ThingDef d) => d.race.lifeStageAges[d.race.lifeStageAges.Count - 1].minAge.ToString("F2"))), new TableDataGetter("nutrition to adulthood", (Func)((ThingDef d) => nutritionToAdulthood(d).ToString("F2"))), new TableDataGetter("adult meat-nut", (Func)((ThingDef d) => ((float)(d.GetStatValueAbstract(StatDefOf.MeatAmount, null) * 0.05000000074505806)).ToString("F2"))), new TableDataGetter("adult meat-nut / input-nut", (Func)((ThingDef d) => adultMeatNutPerInput(d).ToString("F3"))), new TableDataGetter("|", (Func)((ThingDef d) => "|")), new TableDataGetter("baby size", (Func)((ThingDef d) => (d.race.lifeStageAges[0].def.bodySizeFactor * d.race.baseBodySize).ToString("F2"))), new TableDataGetter("nutrition to gestate", (Func)((ThingDef d) => nutritionToGestate(d).ToString("F2"))), new TableDataGetter("egg nut", (Func)((ThingDef d) => eggNut(d))), new TableDataGetter("baby meat-nut", (Func)((ThingDef d) => babyMeatNut(d).ToString("F2"))), new TableDataGetter("baby meat-nut / input-nut", (Func)((ThingDef d) => babyMeatNutPerInput(d).ToString("F2"))), new TableDataGetter("baby wins", (Func)((ThingDef d) => (!(babyMeatNutPerInput(d) > adultMeatNutPerInput(d))) ? string.Empty : "B"))); } public static void DoTable_CropEconomy() { - Func calculatedProductionCost = delegate(ThingDef d) + Func calculatedProductionCost = (Func)delegate(ThingDef d) { float num = 1.1f; - num += d.plant.growDays * 2.8f; - return num + (d.plant.sowWork + d.plant.harvestWork) * 0.006f; + num = (float)(num + d.plant.growDays * 2.7999999523162842); + return (float)(num + (d.plant.sowWork + d.plant.harvestWork) * 0.0060000000521540642); }; - IEnumerable arg_1DA_0 = from d in DefDatabase.AllDefs + DebugTables.MakeTablesDialog(from d in DefDatabase.AllDefs where d.category == ThingCategory.Plant && d.plant.Harvestable && d.plant.Sowable && !d.plant.IsTree - select d; - TableDataGetter[] expr_57 = new TableDataGetter[10]; - expr_57[0] = new TableDataGetter("plant", (ThingDef d) => d.defName); - expr_57[1] = new TableDataGetter("product", (ThingDef d) => d.plant.harvestedThingDef.defName); - expr_57[2] = new TableDataGetter("grow time", (ThingDef d) => d.plant.growDays.ToString("F1")); - expr_57[3] = new TableDataGetter("work", (ThingDef d) => (d.plant.sowWork + d.plant.harvestWork).ToString("F0")); - expr_57[4] = new TableDataGetter("yield", (ThingDef d) => d.plant.harvestYield.ToString("F1")); - expr_57[5] = new TableDataGetter("yield value", (ThingDef d) => (d.plant.harvestYield * d.plant.harvestedThingDef.BaseMarketValue).ToString("F1")); - expr_57[6] = new TableDataGetter("calculated production cost total", (ThingDef d) => calculatedProductionCost(d).ToString("F2")); - expr_57[7] = new TableDataGetter("calculated production cost", (ThingDef d) => (calculatedProductionCost(d) / d.plant.harvestYield).ToString("F2")); - expr_57[8] = new TableDataGetter("value", (ThingDef d) => d.plant.harvestedThingDef.BaseMarketValue.ToString("F1")); - expr_57[9] = new TableDataGetter("nutrition", (ThingDef d) => (d.plant.harvestedThingDef.ingestible == null) ? string.Empty : d.plant.harvestedThingDef.ingestible.nutrition.ToString("F2")); - DebugTables.MakeTablesDialog(arg_1DA_0, expr_57); + select d, new TableDataGetter("plant", (Func)((ThingDef d) => d.defName)), new TableDataGetter("product", (Func)((ThingDef d) => d.plant.harvestedThingDef.defName)), new TableDataGetter("grow time", (Func)((ThingDef d) => d.plant.growDays.ToString("F1"))), new TableDataGetter("work", (Func)((ThingDef d) => (d.plant.sowWork + d.plant.harvestWork).ToString("F0"))), new TableDataGetter("yield", (Func)((ThingDef d) => d.plant.harvestYield.ToString("F1"))), new TableDataGetter("yield value", (Func)((ThingDef d) => (d.plant.harvestYield * d.plant.harvestedThingDef.BaseMarketValue).ToString("F1"))), new TableDataGetter("calculated production cost total", (Func)((ThingDef d) => calculatedProductionCost(d).ToString("F2"))), new TableDataGetter("calculated production cost", (Func)((ThingDef d) => (calculatedProductionCost(d) / d.plant.harvestYield).ToString("F2"))), new TableDataGetter("value", (Func)((ThingDef d) => d.plant.harvestedThingDef.BaseMarketValue.ToString("F1"))), new TableDataGetter("nutrition", (Func)((ThingDef d) => (d.plant.harvestedThingDef.ingestible == null) ? string.Empty : d.plant.harvestedThingDef.ingestible.nutrition.ToString("F2")))); } public static void DoTable_ItemNutritions() { - IEnumerable arg_121_0 = from d in DefDatabase.AllDefs + DebugTables.MakeTablesDialog(from d in DefDatabase.AllDefs where d.category == ThingCategory.Item && d.IsNutritionGivingIngestible orderby d.ingestible.nutrition - select d; - TableDataGetter[] expr_4F = new TableDataGetter[5]; - expr_4F[0] = new TableDataGetter("defName", (ThingDef d) => d.defName); - expr_4F[1] = new TableDataGetter("market value", (ThingDef d) => d.BaseMarketValue.ToString("F1")); - expr_4F[2] = new TableDataGetter("nutrition", (ThingDef d) => d.ingestible.nutrition.ToString("F2")); - expr_4F[3] = new TableDataGetter("nutrition per value", (ThingDef d) => (d.ingestible.nutrition / d.BaseMarketValue).ToString("F3")); - expr_4F[4] = new TableDataGetter("work", (ThingDef d) => d.GetStatValueAbstract(StatDefOf.WorkToMake, null).ToString("F0")); - DebugTables.MakeTablesDialog(arg_121_0, expr_4F); + select d, new TableDataGetter("defName", (Func)((ThingDef d) => d.defName)), new TableDataGetter("market value", (Func)((ThingDef d) => d.BaseMarketValue.ToString("F1"))), new TableDataGetter("nutrition", (Func)((ThingDef d) => d.ingestible.nutrition.ToString("F2"))), new TableDataGetter("nutrition per value", (Func)((ThingDef d) => (d.ingestible.nutrition / d.BaseMarketValue).ToString("F3"))), new TableDataGetter("work", (Func)((ThingDef d) => d.GetStatValueAbstract(StatDefOf.WorkToMake, null).ToString("F0")))); } public static void DoTable_AllNutritions() { - IEnumerable arg_81_0 = from d in DefDatabase.AllDefs + DebugTables.MakeTablesDialog(from d in DefDatabase.AllDefs where d.ingestible != null - select d; - TableDataGetter[] expr_2D = new TableDataGetter[2]; - expr_2D[0] = new TableDataGetter("defName", (ThingDef d) => d.defName); - expr_2D[1] = new TableDataGetter("nutrition", (ThingDef d) => d.ingestible.nutrition.ToStringPercentEmptyZero("F0")); - DebugTables.MakeTablesDialog(arg_81_0, expr_2D); + select d, new TableDataGetter("defName", (Func)((ThingDef d) => d.defName)), new TableDataGetter("nutrition", (Func)((ThingDef d) => d.ingestible.nutrition.ToStringPercentEmptyZero("F0")))); } public static void DoTable_ItemMarketValuesStackable() @@ -240,7 +182,7 @@ public static void DoTable_ItemMarketValuesUnstackable() private static void DoItemMarketValues(bool stackable) { - Func workAmountGetter = delegate(ThingDef d) + Func workAmountGetter = (Func)delegate(ThingDef d) { if (d.recipeMaker == null) { @@ -252,83 +194,77 @@ private static void DoItemMarketValues(bool stackable) } return Mathf.Max(d.GetStatValueAbstract(StatDefOf.WorkToMake, null), d.GetStatValueAbstract(StatDefOf.WorkToBuild, null)); }; - IEnumerable arg_148_0 = from d in DefDatabase.AllDefs - where d.category == ThingCategory.Item && d.BaseMarketValue > 0.01f && d.stackLimit > 1 == stackable + DebugTables.MakeTablesDialog(from d in DefDatabase.AllDefs + where d.category == ThingCategory.Item && d.BaseMarketValue > 0.0099999997764825821 && d.stackLimit > 1 == stackable orderby d.BaseMarketValue - select d; - TableDataGetter[] expr_6E = new TableDataGetter[6]; - expr_6E[0] = new TableDataGetter("defName", (ThingDef d) => d.defName); - expr_6E[1] = new TableDataGetter("base market value", (ThingDef d) => d.BaseMarketValue.ToString("F1")); - expr_6E[2] = new TableDataGetter("cost to make", (ThingDef d) => DataAnalysisTableMaker.CostToMakeString(d, false)); - expr_6E[3] = new TableDataGetter("work to make", (ThingDef d) => (d.recipeMaker == null) ? "-" : workAmountGetter(d).ToString("F1")); - expr_6E[4] = new TableDataGetter("profit", (ThingDef d) => (d.BaseMarketValue - DataAnalysisTableMaker.CostToMake(d, false)).ToString("F1")); - expr_6E[5] = new TableDataGetter("profit rate", (ThingDef d) => (d.recipeMaker == null) ? "-" : ((d.BaseMarketValue - DataAnalysisTableMaker.CostToMake(d, false)) / workAmountGetter(d) * 10000f).ToString("F0")); - DebugTables.MakeTablesDialog(arg_148_0, expr_6E); + select d, new TableDataGetter("defName", (Func)((ThingDef d) => d.defName)), new TableDataGetter("base market value", (Func)((ThingDef d) => d.BaseMarketValue.ToString("F1"))), new TableDataGetter("cost to make", (Func)((ThingDef d) => DataAnalysisTableMaker.CostToMakeString(d, false))), new TableDataGetter("work to make", (Func)((ThingDef d) => (d.recipeMaker == null) ? "-" : workAmountGetter(d).ToString("F1"))), new TableDataGetter("profit", (Func)((ThingDef d) => (d.BaseMarketValue - DataAnalysisTableMaker.CostToMake(d, false)).ToString("F1"))), new TableDataGetter("profit rate", (Func)((ThingDef d) => (d.recipeMaker == null) ? "-" : ((float)((d.BaseMarketValue - DataAnalysisTableMaker.CostToMake(d, false)) / workAmountGetter(d) * 10000.0)).ToString("F0")))); } public static void DoTable_Stuffs() { - Func workGetter = delegate(ThingDef d, StatDef stat) + Func workGetter = (Func)delegate(ThingDef d, StatDef stat) { if (d.stuffProps.statFactors == null) { return string.Empty; } - StatModifier statModifier = d.stuffProps.statFactors.FirstOrDefault((StatModifier fa) => fa.stat == stat); + StatModifier statModifier = d.stuffProps.statFactors.FirstOrDefault((Func)((StatModifier fa) => fa.stat == stat)); if (statModifier == null) { return string.Empty; } return statModifier.value.ToString(); }; - IEnumerable arg_FE_0 = from d in DefDatabase.AllDefs + DebugTables.MakeTablesDialog(from d in DefDatabase.AllDefs where d.IsStuff orderby d.BaseMarketValue - select d; - TableDataGetter[] expr_78 = new TableDataGetter[4]; - expr_78[0] = new TableDataGetter("defName", (ThingDef d) => d.defName); - expr_78[1] = new TableDataGetter("base market value", (ThingDef d) => d.BaseMarketValue.ToString("F1")); - expr_78[2] = new TableDataGetter("fac-WorkToMake", (ThingDef d) => workGetter(d, StatDefOf.WorkToMake)); - expr_78[3] = new TableDataGetter("fac-WorkToBuild", (ThingDef d) => workGetter(d, StatDefOf.WorkToBuild)); - DebugTables.MakeTablesDialog(arg_FE_0, expr_78); + select d, new TableDataGetter("defName", (Func)((ThingDef d) => d.defName)), new TableDataGetter("base market value", (Func)((ThingDef d) => d.BaseMarketValue.ToString("F1"))), new TableDataGetter("fac-WorkToMake", (Func)((ThingDef d) => workGetter(d, StatDefOf.WorkToMake))), new TableDataGetter("fac-WorkToBuild", (Func)((ThingDef d) => workGetter(d, StatDefOf.WorkToBuild)))); } public static void DoTable_Recipes() { - Func trueWork = (RecipeDef d) => d.WorkAmountTotal(null); - Func cheapestIngredientVal = delegate(RecipeDef d) + Func trueWork = (Func)((RecipeDef d) => d.WorkAmountTotal(null)); + Func cheapestIngredientVal = (Func)delegate(RecipeDef d) { - float num = 0f; - foreach (IngredientCount current in d.ingredients) + float num2 = 0f; + List.Enumerator enumerator2 = d.ingredients.GetEnumerator(); + try { - num += current.filter.AllowedThingDefs.Min((ThingDef td) => td.BaseMarketValue) * current.GetBaseCount(); + while (enumerator2.MoveNext()) + { + IngredientCount current2 = enumerator2.Current; + num2 += current2.filter.AllowedThingDefs.Min((Func)((ThingDef td) => td.BaseMarketValue)) * current2.GetBaseCount(); + } + return num2; + } + finally + { + ((IDisposable)(object)enumerator2).Dispose(); } - return num; }; - Func workVal = (RecipeDef d) => trueWork(d) * 0.01f; - Func cheapestProductsVal = delegate(RecipeDef d) + Func workVal = (Func)((RecipeDef d) => (float)(trueWork(d) * 0.0099999997764825821)); + Func cheapestProductsVal = (Func)delegate(RecipeDef d) { - ThingDef thingDef = d.ingredients.First().filter.AllowedThingDefs.MinBy((ThingDef td) => td.BaseMarketValue); + ThingDef thingDef = d.ingredients.First().filter.AllowedThingDefs.MinBy((Func)((ThingDef td) => td.BaseMarketValue)); float num = 0f; - foreach (ThingCountClass current in d.products) + List.Enumerator enumerator = d.products.GetEnumerator(); + try { - num += current.thingDef.GetStatValueAbstract(StatDefOf.MarketValue, (!current.thingDef.MadeFromStuff) ? null : thingDef) * (float)current.count; + while (enumerator.MoveNext()) + { + ThingCountClass current = enumerator.Current; + num += current.thingDef.GetStatValueAbstract(StatDefOf.MarketValue, (!current.thingDef.MadeFromStuff) ? null : thingDef) * (float)current.count; + } + return num; + } + finally + { + ((IDisposable)(object)enumerator).Dispose(); } - return num; }; - IEnumerable arg_187_0 = from d in DefDatabase.AllDefs - where !d.products.NullOrEmpty() - select d; - TableDataGetter[] expr_AE = new TableDataGetter[8]; - expr_AE[0] = new TableDataGetter("defName", (RecipeDef d) => d.defName); - expr_AE[1] = new TableDataGetter("work", (RecipeDef d) => trueWork(d).ToString("F0")); - expr_AE[2] = new TableDataGetter("cheapest ingredients value", (RecipeDef d) => cheapestIngredientVal(d).ToString("F1")); - expr_AE[3] = new TableDataGetter("work value", (RecipeDef d) => workVal(d).ToString("F1")); - expr_AE[4] = new TableDataGetter("cheapest products value", (RecipeDef d) => cheapestProductsVal(d).ToString("F1")); - expr_AE[5] = new TableDataGetter("profit raw", (RecipeDef d) => (cheapestProductsVal(d) - cheapestIngredientVal(d)).ToString("F1")); - expr_AE[6] = new TableDataGetter("profit with work", (RecipeDef d) => (cheapestProductsVal(d) - workVal(d) - cheapestIngredientVal(d)).ToString("F1")); - expr_AE[7] = new TableDataGetter("profit per work day", (RecipeDef d) => ((cheapestProductsVal(d) - cheapestIngredientVal(d)) * 60000f / trueWork(d)).ToString("F0")); - DebugTables.MakeTablesDialog(arg_187_0, expr_AE); + DebugTables.MakeTablesDialog(from d in DefDatabase.AllDefs + where !d.products.NullOrEmpty() + select d, new TableDataGetter("defName", (Func)((RecipeDef d) => d.defName)), new TableDataGetter("work", (Func)((RecipeDef d) => trueWork(d).ToString("F0"))), new TableDataGetter("cheapest ingredients value", (Func)((RecipeDef d) => cheapestIngredientVal(d).ToString("F1"))), new TableDataGetter("work value", (Func)((RecipeDef d) => workVal(d).ToString("F1"))), new TableDataGetter("cheapest products value", (Func)((RecipeDef d) => cheapestProductsVal(d).ToString("F1"))), new TableDataGetter("profit raw", (Func)((RecipeDef d) => (cheapestProductsVal(d) - cheapestIngredientVal(d)).ToString("F1"))), new TableDataGetter("profit with work", (Func)((RecipeDef d) => (cheapestProductsVal(d) - workVal(d) - cheapestIngredientVal(d)).ToString("F1"))), new TableDataGetter("profit per work day", (Func)((RecipeDef d) => ((float)((cheapestProductsVal(d) - cheapestIngredientVal(d)) * 60000.0 / trueWork(d))).ToString("F0")))); } private static string CostToMakeString(ThingDef d, bool real = false) @@ -349,14 +285,23 @@ private static float CostToMake(ThingDef d, bool real = false) float num = 0f; if (d.costList != null) { - foreach (ThingCountClass current in d.costList) + List.Enumerator enumerator = d.costList.GetEnumerator(); + try { - float num2 = 1f; - if (real) + while (enumerator.MoveNext()) { - num2 = ((!DataAnalysisTableMaker.RequiresBuying(current.thingDef)) ? 0.5f : 1.5f); + ThingCountClass current = enumerator.Current; + float num2 = 1f; + if (real) + { + num2 = (float)((!DataAnalysisTableMaker.RequiresBuying(current.thingDef)) ? 0.5 : 1.5); + } + num += (float)current.count * DataAnalysisTableMaker.CostToMake(current.thingDef, true) * num2; } - num += (float)current.count * DataAnalysisTableMaker.CostToMake(current.thingDef, true) * num2; + } + finally + { + ((IDisposable)(object)enumerator).Dispose(); } } if (d.costStuffCount > 0) @@ -371,128 +316,119 @@ private static bool RequiresBuying(ThingDef def) { if (def.costList != null) { - foreach (ThingCountClass current in def.costList) + List.Enumerator enumerator = def.costList.GetEnumerator(); + try { - if (DataAnalysisTableMaker.RequiresBuying(current.thingDef)) + while (enumerator.MoveNext()) { - return true; + ThingCountClass current = enumerator.Current; + if (DataAnalysisTableMaker.RequiresBuying(current.thingDef)) + { + return true; + } } } + finally + { + ((IDisposable)(object)enumerator).Dispose(); + } return false; } - return !DefDatabase.AllDefs.Any((ThingDef d) => d.plant != null && d.plant.harvestedThingDef == def && d.plant.Sowable); + return !DefDatabase.AllDefs.Any((Func)((ThingDef d) => d.plant != null && d.plant.harvestedThingDef == def && d.plant.Sowable)); } public static void DoTable_RacesBasics() { - Func dps = (PawnKindDef d) => DataAnalysisTableMaker.RaceMeleeDpsEstimate(d.race); - Func pointsGuess = delegate(PawnKindDef d) + Func dps = (Func)((PawnKindDef d) => DataAnalysisTableMaker.RaceMeleeDpsEstimate(d.race)); + Func pointsGuess = (Func)delegate(PawnKindDef d) { - float num = 15f; - num += dps(d) * 10f; - num *= Mathf.Lerp(1f, d.race.GetStatValueAbstract(StatDefOf.MoveSpeed, null) / 3f, 0.25f); - num *= d.RaceProps.baseHealthScale; - num *= GenMath.LerpDouble(0.25f, 1f, 1.65f, 1f, Mathf.Clamp(d.RaceProps.baseBodySize, 0.25f, 1f)); - return num * 0.76f; + float num2 = 15f; + num2 = (float)(num2 + dps(d) * 10.0); + num2 *= Mathf.Lerp(1f, (float)(d.race.GetStatValueAbstract(StatDefOf.MoveSpeed, null) / 3.0), 0.25f); + num2 *= d.RaceProps.baseHealthScale; + num2 *= GenMath.LerpDouble(0.25f, 1f, 1.65f, 1f, Mathf.Clamp(d.RaceProps.baseBodySize, 0.25f, 1f)); + return (float)(num2 * 0.75999999046325684); }; - Func mktValGuess = delegate(PawnKindDef d) + Func mktValGuess = (Func)delegate(PawnKindDef d) { float num = 18f; - num += pointsGuess(d) * 2.7f; + num = (float)(num + pointsGuess(d) * 2.7000000476837158); if (d.RaceProps.TrainableIntelligence == TrainableIntelligenceDefOf.None) { - num *= 0.5f; + num = (float)(num * 0.5); + goto IL_00a3; } - else if (d.RaceProps.TrainableIntelligence == TrainableIntelligenceDefOf.Simple) + if (d.RaceProps.TrainableIntelligence == TrainableIntelligenceDefOf.Simple) { - num *= 0.8f; + num = (float)(num * 0.800000011920929); + goto IL_00a3; } - else if (d.RaceProps.TrainableIntelligence == TrainableIntelligenceDefOf.Intermediate) + if (d.RaceProps.TrainableIntelligence == TrainableIntelligenceDefOf.Intermediate) { num = num; + goto IL_00a3; } - else + if (d.RaceProps.TrainableIntelligence == TrainableIntelligenceDefOf.Advanced) { - if (d.RaceProps.TrainableIntelligence != TrainableIntelligenceDefOf.Advanced) - { - throw new InvalidOperationException(); - } - num += 250f; + num = (float)(num + 250.0); + goto IL_00a3; } - num += d.RaceProps.baseBodySize * 80f; + throw new InvalidOperationException(); + IL_00a3: + num = (float)(num + d.RaceProps.baseBodySize * 80.0); if (d.race.HasComp(typeof(CompMilkable))) { - num += 125f; + num = (float)(num + 125.0); } if (d.race.HasComp(typeof(CompShearable))) { - num += 90f; + num = (float)(num + 90.0); } if (d.race.HasComp(typeof(CompEggLayer))) { - num += 90f; + num = (float)(num + 90.0); } num *= Mathf.Lerp(0.8f, 1.2f, d.RaceProps.wildness); - return num * 0.75f; + return (float)(num * 0.75); }; - IEnumerable arg_345_0 = from d in DefDatabase.AllDefs + DebugTables.MakeTablesDialog(from d in DefDatabase.AllDefs where d.race != null && !d.RaceProps.Humanlike - select d; - TableDataGetter[] expr_7B = new TableDataGetter[18]; - expr_7B[0] = new TableDataGetter("defName", (PawnKindDef d) => d.defName); - expr_7B[1] = new TableDataGetter("points", (PawnKindDef d) => d.combatPower.ToString("F0")); - expr_7B[2] = new TableDataGetter("points guess", (PawnKindDef d) => pointsGuess(d).ToString("F0")); - expr_7B[3] = new TableDataGetter("mktval", (PawnKindDef d) => d.race.GetStatValueAbstract(StatDefOf.MarketValue, null).ToString("F0")); - expr_7B[4] = new TableDataGetter("mktval guess", (PawnKindDef d) => mktValGuess(d).ToString("F0")); - expr_7B[5] = new TableDataGetter("healthScale", (PawnKindDef d) => d.RaceProps.baseHealthScale.ToString("F2")); - expr_7B[6] = new TableDataGetter("bodySize", (PawnKindDef d) => d.RaceProps.baseBodySize.ToString("F2")); - expr_7B[7] = new TableDataGetter("hunger rate", (PawnKindDef d) => d.RaceProps.baseHungerRate.ToString("F2")); - expr_7B[8] = new TableDataGetter("speed", (PawnKindDef d) => d.race.GetStatValueAbstract(StatDefOf.MoveSpeed, null).ToString("F2")); - expr_7B[9] = new TableDataGetter("melee dps", (PawnKindDef d) => dps(d).ToString("F2")); - expr_7B[10] = new TableDataGetter("wildness", (PawnKindDef d) => d.RaceProps.wildness.ToStringPercent()); - expr_7B[11] = new TableDataGetter("life expec.", (PawnKindDef d) => d.RaceProps.lifeExpectancy.ToString("F1")); - expr_7B[12] = new TableDataGetter("train-int", (PawnKindDef d) => d.RaceProps.TrainableIntelligence.GetLabel()); - expr_7B[13] = new TableDataGetter("temps", (PawnKindDef d) => d.race.GetStatValueAbstract(StatDefOf.ComfyTemperatureMin, null).ToString("F0") + ".." + d.race.GetStatValueAbstract(StatDefOf.ComfyTemperatureMax, null).ToString("F0")); - expr_7B[14] = new TableDataGetter("mateMtb", (PawnKindDef d) => d.RaceProps.mateMtbHours.ToStringEmptyZero("F0")); - expr_7B[15] = new TableDataGetter("nuzzMtb", (PawnKindDef d) => d.RaceProps.nuzzleMtbHours.ToStringEmptyZero("F0")); - expr_7B[16] = new TableDataGetter("mhChDam", (PawnKindDef d) => d.RaceProps.manhunterOnDamageChance.ToStringPercentEmptyZero("F2")); - expr_7B[17] = new TableDataGetter("mhChTam", (PawnKindDef d) => d.RaceProps.manhunterOnTameFailChance.ToStringPercentEmptyZero("F2")); - DebugTables.MakeTablesDialog(arg_345_0, expr_7B); + select d, new TableDataGetter("defName", (Func)((PawnKindDef d) => d.defName)), new TableDataGetter("points", (Func)((PawnKindDef d) => d.combatPower.ToString("F0"))), new TableDataGetter("points guess", (Func)((PawnKindDef d) => pointsGuess(d).ToString("F0"))), new TableDataGetter("mktval", (Func)((PawnKindDef d) => d.race.GetStatValueAbstract(StatDefOf.MarketValue, null).ToString("F0"))), new TableDataGetter("mktval guess", (Func)((PawnKindDef d) => mktValGuess(d).ToString("F0"))), new TableDataGetter("healthScale", (Func)((PawnKindDef d) => d.RaceProps.baseHealthScale.ToString("F2"))), new TableDataGetter("bodySize", (Func)((PawnKindDef d) => d.RaceProps.baseBodySize.ToString("F2"))), new TableDataGetter("hunger rate", (Func)((PawnKindDef d) => d.RaceProps.baseHungerRate.ToString("F2"))), new TableDataGetter("speed", (Func)((PawnKindDef d) => d.race.GetStatValueAbstract(StatDefOf.MoveSpeed, null).ToString("F2"))), new TableDataGetter("melee dps", (Func)((PawnKindDef d) => dps(d).ToString("F2"))), new TableDataGetter("wildness", (Func)((PawnKindDef d) => d.RaceProps.wildness.ToStringPercent())), new TableDataGetter("life expec.", (Func)((PawnKindDef d) => d.RaceProps.lifeExpectancy.ToString("F1"))), new TableDataGetter("train-int", (Func)((PawnKindDef d) => d.RaceProps.TrainableIntelligence.GetLabel())), new TableDataGetter("temps", (Func)((PawnKindDef d) => d.race.GetStatValueAbstract(StatDefOf.ComfyTemperatureMin, null).ToString("F0") + ".." + d.race.GetStatValueAbstract(StatDefOf.ComfyTemperatureMax, null).ToString("F0"))), new TableDataGetter("mateMtb", (Func)((PawnKindDef d) => d.RaceProps.mateMtbHours.ToStringEmptyZero("F0"))), new TableDataGetter("nuzzMtb", (Func)((PawnKindDef d) => d.RaceProps.nuzzleMtbHours.ToStringEmptyZero("F0"))), new TableDataGetter("mhChDam", (Func)((PawnKindDef d) => d.RaceProps.manhunterOnDamageChance.ToStringPercentEmptyZero("F2"))), new TableDataGetter("mhChTam", (Func)((PawnKindDef d) => d.RaceProps.manhunterOnTameFailChance.ToStringPercentEmptyZero("F2")))); } private static float RaceMeleeDpsEstimate(ThingDef race) { - if (race.Verbs.NullOrEmpty()) + if (race.Verbs.NullOrEmpty()) { return 0f; } IEnumerable list = from v in race.Verbs - where (float)v.meleeDamageBaseAmount > 0.001f + where (float)v.meleeDamageBaseAmount > 0.0010000000474974513 select v; - return list.AverageWeighted((VerbProperties v) => v.BaseSelectionWeight, (VerbProperties v) => (float)v.meleeDamageBaseAmount / (v.defaultCooldownTime + v.warmupTime)); + return list.AverageWeighted((Func)((VerbProperties v) => v.BaseSelectionWeight), (Func)((VerbProperties v) => (float)v.meleeDamageBaseAmount / (v.defaultCooldownTime + v.warmupTime))); } public static void DoTable_RacesFoodConsumption() { - Func lsName = delegate(ThingDef d, int lsIndex) + Func lsName = (Func)delegate(ThingDef d, int lsIndex) { if (d.race.lifeStageAges.Count <= lsIndex) { return string.Empty; } - LifeStageDef def = d.race.lifeStageAges[lsIndex].def; - return def.defName; + LifeStageDef def3 = d.race.lifeStageAges[lsIndex].def; + return def3.defName; }; - Func maxFood = delegate(ThingDef d, int lsIndex) + Func maxFood = (Func)delegate(ThingDef d, int lsIndex) { if (d.race.lifeStageAges.Count <= lsIndex) { return string.Empty; } - LifeStageDef def = d.race.lifeStageAges[lsIndex].def; - return (d.race.baseBodySize * def.bodySizeFactor * def.foodMaxFactor).ToString("F2"); + LifeStageDef def2 = d.race.lifeStageAges[lsIndex].def; + return (d.race.baseBodySize * def2.bodySizeFactor * def2.foodMaxFactor).ToString("F2"); }; - Func hungerRate = delegate(ThingDef d, int lsIndex) + Func hungerRate = (Func)delegate(ThingDef d, int lsIndex) { if (d.race.lifeStageAges.Count <= lsIndex) { @@ -501,42 +437,18 @@ public static void DoTable_RacesFoodConsumption() LifeStageDef def = d.race.lifeStageAges[lsIndex].def; return (d.race.baseHungerRate * def.hungerRateFactor).ToString("F2"); }; - IEnumerable arg_219_0 = from d in DefDatabase.AllDefs + DebugTables.MakeTablesDialog(from d in DefDatabase.AllDefs where d.race != null && d.race.EatsFood orderby d.race.baseHungerRate descending - select d; - TableDataGetter[] expr_BF = new TableDataGetter[13]; - expr_BF[0] = new TableDataGetter("defName", (ThingDef d) => d.defName); - expr_BF[1] = new TableDataGetter("Lifestage 0", (ThingDef d) => lsName(d, 0)); - expr_BF[2] = new TableDataGetter("maxFood", (ThingDef d) => maxFood(d, 0)); - expr_BF[3] = new TableDataGetter("hungerRate", (ThingDef d) => hungerRate(d, 0)); - expr_BF[4] = new TableDataGetter("Lifestage 1", (ThingDef d) => lsName(d, 1)); - expr_BF[5] = new TableDataGetter("maxFood", (ThingDef d) => maxFood(d, 1)); - expr_BF[6] = new TableDataGetter("hungerRate", (ThingDef d) => hungerRate(d, 1)); - expr_BF[7] = new TableDataGetter("Lifestage 2", (ThingDef d) => lsName(d, 2)); - expr_BF[8] = new TableDataGetter("maxFood", (ThingDef d) => maxFood(d, 2)); - expr_BF[9] = new TableDataGetter("hungerRate", (ThingDef d) => hungerRate(d, 2)); - expr_BF[10] = new TableDataGetter("Lifestage 3", (ThingDef d) => lsName(d, 3)); - expr_BF[11] = new TableDataGetter("maxFood", (ThingDef d) => maxFood(d, 3)); - expr_BF[12] = new TableDataGetter("hungerRate", (ThingDef d) => hungerRate(d, 3)); - DebugTables.MakeTablesDialog(arg_219_0, expr_BF); + select d, new TableDataGetter("defName", (Func)((ThingDef d) => d.defName)), new TableDataGetter("Lifestage 0", (Func)((ThingDef d) => lsName(d, 0))), new TableDataGetter("maxFood", (Func)((ThingDef d) => maxFood(d, 0))), new TableDataGetter("hungerRate", (Func)((ThingDef d) => hungerRate(d, 0))), new TableDataGetter("Lifestage 1", (Func)((ThingDef d) => lsName(d, 1))), new TableDataGetter("maxFood", (Func)((ThingDef d) => maxFood(d, 1))), new TableDataGetter("hungerRate", (Func)((ThingDef d) => hungerRate(d, 1))), new TableDataGetter("Lifestage 2", (Func)((ThingDef d) => lsName(d, 2))), new TableDataGetter("maxFood", (Func)((ThingDef d) => maxFood(d, 2))), new TableDataGetter("hungerRate", (Func)((ThingDef d) => hungerRate(d, 2))), new TableDataGetter("Lifestage 3", (Func)((ThingDef d) => lsName(d, 3))), new TableDataGetter("maxFood", (Func)((ThingDef d) => maxFood(d, 3))), new TableDataGetter("hungerRate", (Func)((ThingDef d) => hungerRate(d, 3)))); } public static void DoTable_PlantsBasics() { - IEnumerable arg_175_0 = from d in DefDatabase.AllDefs + DebugTables.MakeTablesDialog(from d in DefDatabase.AllDefs where d.category == ThingCategory.Plant orderby d.plant.fertilitySensitivity - select d; - TableDataGetter[] expr_4F = new TableDataGetter[7]; - expr_4F[0] = new TableDataGetter("defName", (ThingDef d) => d.defName); - expr_4F[1] = new TableDataGetter("growDays", (ThingDef d) => d.plant.growDays.ToString("F2")); - expr_4F[2] = new TableDataGetter("reproduceMtb", (ThingDef d) => d.plant.reproduceMtbDays.ToString("F2")); - expr_4F[3] = new TableDataGetter("nutrition", (ThingDef d) => (d.ingestible == null) ? "-" : d.ingestible.nutrition.ToString("F2")); - expr_4F[4] = new TableDataGetter("nut/day", (ThingDef d) => (d.ingestible == null) ? "-" : (d.ingestible.nutrition / d.plant.growDays).ToString("F4")); - expr_4F[5] = new TableDataGetter("fertilityMin", (ThingDef d) => d.plant.fertilityMin.ToString("F2")); - expr_4F[6] = new TableDataGetter("fertilitySensitivity", (ThingDef d) => d.plant.fertilitySensitivity.ToString("F2")); - DebugTables.MakeTablesDialog(arg_175_0, expr_4F); + select d, new TableDataGetter("defName", (Func)((ThingDef d) => d.defName)), new TableDataGetter("growDays", (Func)((ThingDef d) => d.plant.growDays.ToString("F2"))), new TableDataGetter("reproduceMtb", (Func)((ThingDef d) => d.plant.reproduceMtbDays.ToString("F2"))), new TableDataGetter("nutrition", (Func)((ThingDef d) => (d.ingestible == null) ? "-" : d.ingestible.nutrition.ToString("F2"))), new TableDataGetter("nut/day", (Func)((ThingDef d) => (d.ingestible == null) ? "-" : (d.ingestible.nutrition / d.plant.growDays).ToString("F4"))), new TableDataGetter("fertilityMin", (Func)((ThingDef d) => d.plant.fertilityMin.ToString("F2"))), new TableDataGetter("fertilitySensitivity", (Func)((ThingDef d) => d.plant.fertilitySensitivity.ToString("F2")))); } public static void DoTable_WeaponPairs() @@ -551,52 +463,33 @@ public static void DoTable_WeaponPairsByThing() public static void DoTable_WeaponsRanged() { - Func damageGetter = (ThingDef d) => (d.Verbs[0].projectileDef == null) ? 0 : d.Verbs[0].projectileDef.projectile.damageAmountBase; - Func warmupGetter = (ThingDef d) => d.Verbs[0].warmupTime; - Func cooldownGetter = (ThingDef d) => d.GetStatValueAbstract(StatDefOf.RangedWeapon_Cooldown, null); - Func burstShotsGetter = (ThingDef d) => d.Verbs[0].burstShotCount; - Func dpsRawGetter = delegate(ThingDef d) + Func damageGetter = (Func)((ThingDef d) => (d.Verbs[0].projectileDef != null) ? d.Verbs[0].projectileDef.projectile.damageAmountBase : 0); + Func warmupGetter = (Func)((ThingDef d) => d.Verbs[0].warmupTime); + Func cooldownGetter = (Func)((ThingDef d) => d.GetStatValueAbstract(StatDefOf.RangedWeapon_Cooldown, null)); + Func burstShotsGetter = (Func)((ThingDef d) => d.Verbs[0].burstShotCount); + Func dpsRawGetter = (Func)delegate(ThingDef d) { - int num = burstShotsGetter(d); - float num2 = warmupGetter(d) + cooldownGetter(d); - num2 += (float)(num - 1) * ((float)d.Verbs[0].ticksBetweenBurstShots / 60f); - return (float)(damageGetter(d) * num) / num2; + int num2 = burstShotsGetter(d); + float num3 = warmupGetter(d) + cooldownGetter(d); + num3 = (float)(num3 + (float)(num2 - 1) * ((float)d.Verbs[0].ticksBetweenBurstShots / 60.0)); + return (float)(damageGetter(d) * num2) / num3; }; - Func accTouchGetter = (ThingDef d) => d.GetStatValueAbstract(StatDefOf.AccuracyTouch, null); - Func accShortGetter = (ThingDef d) => d.GetStatValueAbstract(StatDefOf.AccuracyShort, null); - Func accMedGetter = (ThingDef d) => d.GetStatValueAbstract(StatDefOf.AccuracyMedium, null); - Func accLongGetter = (ThingDef d) => d.GetStatValueAbstract(StatDefOf.AccuracyLong, null); - Func dpsAvgGetter = delegate(ThingDef d) + Func accTouchGetter = (Func)((ThingDef d) => d.GetStatValueAbstract(StatDefOf.AccuracyTouch, null)); + Func accShortGetter = (Func)((ThingDef d) => d.GetStatValueAbstract(StatDefOf.AccuracyShort, null)); + Func accMedGetter = (Func)((ThingDef d) => d.GetStatValueAbstract(StatDefOf.AccuracyMedium, null)); + Func accLongGetter = (Func)((ThingDef d) => d.GetStatValueAbstract(StatDefOf.AccuracyLong, null)); + Func dpsAvgGetter = (Func)delegate(ThingDef d) { float num = 0f; num += dpsRawGetter(d) * accShortGetter(d); num += dpsRawGetter(d) * accMedGetter(d); num += dpsRawGetter(d) * accLongGetter(d); - return num / 3f; + return (float)(num / 3.0); }; - IEnumerable arg_376_0 = from d in DefDatabase.AllDefs + DebugTables.MakeTablesDialog(from d in DefDatabase.AllDefs where d.IsRangedWeapon orderby d.GetStatValueAbstract(StatDefOf.MarketValue, null) - select d; - TableDataGetter[] expr_192 = new TableDataGetter[17]; - expr_192[0] = new TableDataGetter("defName", (ThingDef d) => d.defName); - expr_192[1] = new TableDataGetter("damage", (ThingDef d) => damageGetter(d).ToString()); - expr_192[2] = new TableDataGetter("warmup", (ThingDef d) => warmupGetter(d).ToString("F2")); - expr_192[3] = new TableDataGetter("burst", (ThingDef d) => burstShotsGetter(d).ToString()); - expr_192[4] = new TableDataGetter("cooldown", (ThingDef d) => cooldownGetter(d).ToString("F2")); - expr_192[5] = new TableDataGetter("dpsRaw", (ThingDef d) => dpsRawGetter(d).ToString("F3")); - expr_192[6] = new TableDataGetter("accTouch", (ThingDef d) => accTouchGetter(d).ToStringPercent()); - expr_192[7] = new TableDataGetter("accShort", (ThingDef d) => accShortGetter(d).ToStringPercent()); - expr_192[8] = new TableDataGetter("accMed", (ThingDef d) => accMedGetter(d).ToStringPercent()); - expr_192[9] = new TableDataGetter("accLong", (ThingDef d) => accLongGetter(d).ToStringPercent()); - expr_192[10] = new TableDataGetter("dpsTouch", (ThingDef d) => (dpsRawGetter(d) * accTouchGetter(d)).ToString("F2")); - expr_192[11] = new TableDataGetter("dpsShort", (ThingDef d) => (dpsRawGetter(d) * accShortGetter(d)).ToString("F2")); - expr_192[12] = new TableDataGetter("dpsMed", (ThingDef d) => (dpsRawGetter(d) * accMedGetter(d)).ToString("F2")); - expr_192[13] = new TableDataGetter("dpsLong", (ThingDef d) => (dpsRawGetter(d) * accLongGetter(d)).ToString("F2")); - expr_192[14] = new TableDataGetter("dpsAvg", (ThingDef d) => dpsAvgGetter(d).ToString("F2")); - expr_192[15] = new TableDataGetter("mktval", (ThingDef d) => d.GetStatValueAbstract(StatDefOf.MarketValue, null).ToString("F0")); - expr_192[16] = new TableDataGetter("work", (ThingDef d) => d.GetStatValueAbstract(StatDefOf.WorkToMake, null).ToString("F0")); - DebugTables.MakeTablesDialog(arg_376_0, expr_192); + select d, new TableDataGetter("defName", (Func)((ThingDef d) => d.defName)), new TableDataGetter("damage", (Func)((ThingDef d) => damageGetter(d).ToString())), new TableDataGetter("warmup", (Func)((ThingDef d) => warmupGetter(d).ToString("F2"))), new TableDataGetter("burst", (Func)((ThingDef d) => burstShotsGetter(d).ToString())), new TableDataGetter("cooldown", (Func)((ThingDef d) => cooldownGetter(d).ToString("F2"))), new TableDataGetter("dpsRaw", (Func)((ThingDef d) => dpsRawGetter(d).ToString("F3"))), new TableDataGetter("accTouch", (Func)((ThingDef d) => accTouchGetter(d).ToStringPercent())), new TableDataGetter("accShort", (Func)((ThingDef d) => accShortGetter(d).ToStringPercent())), new TableDataGetter("accMed", (Func)((ThingDef d) => accMedGetter(d).ToStringPercent())), new TableDataGetter("accLong", (Func)((ThingDef d) => accLongGetter(d).ToStringPercent())), new TableDataGetter("dpsTouch", (Func)((ThingDef d) => (dpsRawGetter(d) * accTouchGetter(d)).ToString("F2"))), new TableDataGetter("dpsShort", (Func)((ThingDef d) => (dpsRawGetter(d) * accShortGetter(d)).ToString("F2"))), new TableDataGetter("dpsMed", (Func)((ThingDef d) => (dpsRawGetter(d) * accMedGetter(d)).ToString("F2"))), new TableDataGetter("dpsLong", (Func)((ThingDef d) => (dpsRawGetter(d) * accLongGetter(d)).ToString("F2"))), new TableDataGetter("dpsAvg", (Func)((ThingDef d) => dpsAvgGetter(d).ToString("F2"))), new TableDataGetter("mktval", (Func)((ThingDef d) => d.GetStatValueAbstract(StatDefOf.MarketValue, null).ToString("F0"))), new TableDataGetter("work", (Func)((ThingDef d) => d.GetStatValueAbstract(StatDefOf.WorkToMake, null).ToString("F0")))); } public static void DoTable_WeaponsMeleeStuffless() @@ -626,80 +519,74 @@ public static void DoTable_MeleeSteelAndRaces() private static void DoTablesInternal_Melee(ThingDef stuff, bool doRaces = false) { - Func damageGetter = delegate(Def d) + Func damageGetter = (Func)delegate(Def d) { - ThingDef thingDef = d as ThingDef; - if (thingDef != null) + ThingDef thingDef5 = d as ThingDef; + if (thingDef5 != null) { - if (thingDef.race != null) + if (thingDef5.race != null) { - return thingDef.Verbs.AverageWeighted((VerbProperties v) => v.BaseSelectionWeight, (VerbProperties v) => (float)v.meleeDamageBaseAmount); + return thingDef5.Verbs.AverageWeighted((Func)((VerbProperties v) => v.BaseSelectionWeight), (Func)((VerbProperties v) => (float)v.meleeDamageBaseAmount)); } - return thingDef.GetStatValueAbstract(StatDefOf.MeleeWeapon_DamageAmount, stuff); + return thingDef5.GetStatValueAbstract(StatDefOf.MeleeWeapon_DamageAmount, stuff); } - else + HediffDef hediffDef4 = d as HediffDef; + if (hediffDef4 != null) { - HediffDef hediffDef = d as HediffDef; - if (hediffDef != null) - { - return (float)hediffDef.CompProps().verbs[0].meleeDamageBaseAmount; - } - return -1f; + return (float)hediffDef4.CompProps().verbs[0].meleeDamageBaseAmount; } + return -1f; }; - Func warmupGetter = delegate(Def d) + Func warmupGetter = (Func)delegate(Def d) { - ThingDef thingDef = d as ThingDef; - if (thingDef != null) + ThingDef thingDef4 = d as ThingDef; + if (thingDef4 != null) { - return thingDef.Verbs.AverageWeighted((VerbProperties v) => v.BaseSelectionWeight, (VerbProperties v) => v.warmupTime); + return thingDef4.Verbs.AverageWeighted((Func)((VerbProperties v) => v.BaseSelectionWeight), (Func)((VerbProperties v) => v.warmupTime)); } - HediffDef hediffDef = d as HediffDef; - if (hediffDef != null) + HediffDef hediffDef3 = d as HediffDef; + if (hediffDef3 != null) { - return hediffDef.CompProps().verbs[0].warmupTime; + return hediffDef3.CompProps().verbs[0].warmupTime; } return -1f; }; - Func cooldownGetter = delegate(Def d) + Func cooldownGetter = (Func)delegate(Def d) { - ThingDef thingDef = d as ThingDef; - if (thingDef != null) + ThingDef thingDef3 = d as ThingDef; + if (thingDef3 != null) { - if (thingDef.race != null) + if (thingDef3.race != null) { - return thingDef.Verbs.AverageWeighted((VerbProperties v) => v.BaseSelectionWeight, (VerbProperties v) => v.defaultCooldownTime); + return thingDef3.Verbs.AverageWeighted((Func)((VerbProperties v) => v.BaseSelectionWeight), (Func)((VerbProperties v) => v.defaultCooldownTime)); } - return thingDef.GetStatValueAbstract(StatDefOf.MeleeWeapon_Cooldown, stuff); + return thingDef3.GetStatValueAbstract(StatDefOf.MeleeWeapon_Cooldown, stuff); } - else + HediffDef hediffDef2 = d as HediffDef; + if (hediffDef2 != null) { - HediffDef hediffDef = d as HediffDef; - if (hediffDef != null) - { - return hediffDef.CompProps().verbs[0].defaultCooldownTime; - } - return -1f; + return hediffDef2.CompProps().verbs[0].defaultCooldownTime; } + return -1f; }; - Func dpsGetter = (Def d) => damageGetter(d) / (warmupGetter(d) + cooldownGetter(d)); - Func marketValueGetter = delegate(Def d) + Func dpsGetter = (Func)((Def d) => damageGetter(d) / (warmupGetter(d) + cooldownGetter(d))); + Func marketValueGetter = (Func)delegate(Def d) { - ThingDef thingDef = d as ThingDef; - if (thingDef != null) + ThingDef thingDef2 = d as ThingDef; + if (thingDef2 != null) { - return thingDef.GetStatValueAbstract(StatDefOf.MarketValue, stuff); + return thingDef2.GetStatValueAbstract(StatDefOf.MarketValue, stuff); } HediffDef hediffDef = d as HediffDef; - if (hediffDef == null) - { - return -1f; - } - if (hediffDef.spawnThingOnRemoved == null) + if (hediffDef != null) { - return 0f; + if (hediffDef.spawnThingOnRemoved == null) + { + return 0f; + } + return hediffDef.spawnThingOnRemoved.GetStatValueAbstract(StatDefOf.MarketValue, null); } - return hediffDef.spawnThingOnRemoved.GetStatValueAbstract(StatDefOf.MarketValue, null); + return -1f; }; IEnumerable enumerable = (from d in DefDatabase.AllDefs where d.IsMeleeWeapon @@ -715,15 +602,7 @@ where h.CompProps() != null enumerable = from h in enumerable orderby dpsGetter(h) descending select h; - IEnumerable arg_1E9_0 = enumerable; - TableDataGetter[] expr_129 = new TableDataGetter[7]; - expr_129[0] = new TableDataGetter("defName", (Def d) => d.defName); - expr_129[1] = new TableDataGetter("damage", (Def d) => damageGetter(d).ToString()); - expr_129[2] = new TableDataGetter("warmup", (Def d) => warmupGetter(d).ToString("F2")); - expr_129[3] = new TableDataGetter("cooldown", (Def d) => cooldownGetter(d).ToString("F2")); - expr_129[4] = new TableDataGetter("dps", (Def d) => dpsGetter(d).ToString("F2")); - expr_129[5] = new TableDataGetter("mktval", (Def d) => marketValueGetter(d).ToString("F0")); - expr_129[6] = new TableDataGetter("work", delegate(Def d) + DebugTables.MakeTablesDialog(enumerable, new TableDataGetter("defName", (Func)((Def d) => d.defName)), new TableDataGetter("damage", (Func)((Def d) => damageGetter(d).ToString())), new TableDataGetter("warmup", (Func)((Def d) => warmupGetter(d).ToString("F2"))), new TableDataGetter("cooldown", (Func)((Def d) => cooldownGetter(d).ToString("F2"))), new TableDataGetter("dps", (Func)((Def d) => dpsGetter(d).ToString("F2"))), new TableDataGetter("mktval", (Func)((Def d) => marketValueGetter(d).ToString("F0"))), new TableDataGetter("work", (Func)delegate(Def d) { ThingDef thingDef = d as ThingDef; if (thingDef == null) @@ -731,8 +610,7 @@ orderby dpsGetter(h) descending return "-"; } return thingDef.GetStatValueAbstract(StatDefOf.WorkToMake, stuff).ToString("F0"); - }); - DebugTables.MakeTablesDialog(arg_1E9_0, expr_129); + })); } public static void DoTable_ApparelPairs() @@ -753,34 +631,38 @@ public static void DoTable_ApparelPairsHeadwearLog() public static void DoTable_ApparelSpawnStats() { List list = new List(); - foreach (PawnKindDef current in from pk in DefDatabase.AllDefs + foreach (PawnKindDef item in from pk in DefDatabase.AllDefs where pk.race.race.Humanlike select pk) { - PawnKindDef kind = current; - list.Add(new FloatMenuOption(kind.defName, delegate + PawnKindDef kind = item; + list.Add(new FloatMenuOption(kind.defName, (Action)delegate() { Faction faction = FactionUtility.DefaultFactionFrom(kind.defaultFactionType); DefMap appCounts = new DefMap(); for (int i = 0; i < 200; i++) { Pawn pawn = PawnGenerator.GeneratePawn(kind, faction); - foreach (Apparel current2 in pawn.apparel.WornApparel) + List.Enumerator enumerator2 = pawn.apparel.WornApparel.GetEnumerator(); + try + { + while (enumerator2.MoveNext()) + { + Apparel current2 = enumerator2.Current; + DefMap defMap; + DefMap obj = defMap = appCounts; + ThingDef def; + ThingDef def2 = def = current2.def; + int num = defMap[def]; + obj[def2] = num + 1; + } + } + finally { - DefMap appCounts2; - DefMap expr_67 = appCounts2 = appCounts; - ThingDef def; - ThingDef expr_71 = def = current2.def; - int num = appCounts2[def]; - expr_67[expr_71] = num + 1; + ((IDisposable)(object)enumerator2).Dispose(); } } - IEnumerable arg_151_0 = DefDatabase.AllDefs.Where((ThingDef d) => d.IsApparel && appCounts[d] > 0).OrderByDescending((ThingDef d) => appCounts[d]); - TableDataGetter[] expr_E4 = new TableDataGetter[3]; - expr_E4[0] = new TableDataGetter("defName", (ThingDef d) => d.defName); - expr_E4[1] = new TableDataGetter("count of " + 200, (ThingDef d) => appCounts[d].ToString()); - expr_E4[2] = new TableDataGetter("percent of pawns", (ThingDef d) => ((float)appCounts[d] / 200f).ToStringPercent("F2")); - DebugTables.MakeTablesDialog(arg_151_0, expr_E4); + DebugTables.MakeTablesDialog(DefDatabase.AllDefs.Where((Func)((ThingDef d) => d.IsApparel && appCounts[d] > 0)).OrderByDescending((Func)((ThingDef d) => appCounts[d])), new TableDataGetter("defName", (Func)((ThingDef d) => d.defName)), new TableDataGetter("count of " + 200, (Func)((ThingDef d) => appCounts[d].ToString())), new TableDataGetter("percent of pawns", (Func)((ThingDef d) => ((float)((float)appCounts[d] / 200.0)).ToStringPercent("F2")))); }, MenuOptionPriority.Default, null, null, 0f, null, null)); } Find.WindowStack.Add(new FloatMenu(list)); @@ -808,79 +690,59 @@ public static void DoTable_ApparelHumanleather() private static void DoTablesInternal_Apparel(ThingDef stuff) { - IEnumerable arg_146_0 = from d in DefDatabase.AllDefs + DebugTables.MakeTablesDialog(from d in DefDatabase.AllDefs where d.IsApparel - select d; - TableDataGetter[] expr_3A = new TableDataGetter[8]; - expr_3A[0] = new TableDataGetter("defName", (ThingDef d) => d.defName); - expr_3A[1] = new TableDataGetter("bodyParts", (ThingDef d) => GenText.ToSpaceList(from bp in d.apparel.bodyPartGroups - select bp.defName)); - expr_3A[2] = new TableDataGetter("layers", (ThingDef d) => GenText.ToSpaceList(from l in d.apparel.layers - select l.ToString())); - expr_3A[3] = new TableDataGetter("tags", (ThingDef d) => GenText.ToSpaceList(from t in d.apparel.tags - select t.ToString())); - expr_3A[4] = new TableDataGetter("insCold", (ThingDef d) => d.GetStatValueAbstract(StatDefOf.Insulation_Cold, stuff).ToString("F0")); - expr_3A[5] = new TableDataGetter("insHeat", (ThingDef d) => d.GetStatValueAbstract(StatDefOf.Insulation_Heat, stuff).ToString("F0")); - expr_3A[6] = new TableDataGetter("mktval", (ThingDef d) => d.GetStatValueAbstract(StatDefOf.MarketValue, stuff).ToString("F0")); - expr_3A[7] = new TableDataGetter("work", (ThingDef d) => d.GetStatValueAbstract(StatDefOf.WorkToMake, stuff).ToString("F0")); - DebugTables.MakeTablesDialog(arg_146_0, expr_3A); + select d, new TableDataGetter("defName", (Func)((ThingDef d) => d.defName)), new TableDataGetter("bodyParts", (Func)((ThingDef d) => GenText.ToSpaceList(d.apparel.bodyPartGroups.Select((Func)((BodyPartGroupDef bp) => bp.defName))))), new TableDataGetter("layers", (Func)((ThingDef d) => GenText.ToSpaceList(d.apparel.layers.Select((Func)((ApparelLayer l) => ((Enum)(object)l).ToString()))))), new TableDataGetter("tags", (Func)((ThingDef d) => GenText.ToSpaceList(d.apparel.tags.Select((Func)((string t) => t.ToString()))))), new TableDataGetter("insCold", (Func)((ThingDef d) => d.GetStatValueAbstract(StatDefOf.Insulation_Cold, stuff).ToString("F0"))), new TableDataGetter("insHeat", (Func)((ThingDef d) => d.GetStatValueAbstract(StatDefOf.Insulation_Heat, stuff).ToString("F0"))), new TableDataGetter("mktval", (Func)((ThingDef d) => d.GetStatValueAbstract(StatDefOf.MarketValue, stuff).ToString("F0"))), new TableDataGetter("work", (Func)((ThingDef d) => d.GetStatValueAbstract(StatDefOf.WorkToMake, stuff).ToString("F0")))); } public static void DoTable_HitPoints() { - IEnumerable arg_CD_0 = from d in DefDatabase.AllDefs + DebugTables.MakeTablesDialog(from d in DefDatabase.AllDefs where d.useHitPoints orderby d.GetStatValueAbstract(StatDefOf.MaxHitPoints, null) descending - select d; - TableDataGetter[] expr_4F = new TableDataGetter[3]; - expr_4F[0] = new TableDataGetter("defName", (ThingDef d) => d.defName); - expr_4F[1] = new TableDataGetter("hp", (ThingDef d) => d.BaseMaxHitPoints.ToString()); - expr_4F[2] = new TableDataGetter("category", (ThingDef d) => d.category.ToString()); - DebugTables.MakeTablesDialog(arg_CD_0, expr_4F); + select d, new TableDataGetter("defName", (Func)((ThingDef d) => d.defName)), new TableDataGetter("hp", (Func)((ThingDef d) => d.BaseMaxHitPoints.ToString())), new TableDataGetter("category", (Func)((ThingDef d) => ((Enum)(object)d.category).ToString()))); } public static void DoTable_FillPercent() { - IEnumerable arg_CD_0 = from d in DefDatabase.AllDefs - where d.fillPercent > 0f + DebugTables.MakeTablesDialog(from d in DefDatabase.AllDefs + where d.fillPercent > 0.0 orderby d.fillPercent descending - select d; - TableDataGetter[] expr_4F = new TableDataGetter[3]; - expr_4F[0] = new TableDataGetter("defName", (ThingDef d) => d.defName); - expr_4F[1] = new TableDataGetter("fillPercent", (ThingDef d) => d.fillPercent.ToStringPercent()); - expr_4F[2] = new TableDataGetter("category", (ThingDef d) => d.category.ToString()); - DebugTables.MakeTablesDialog(arg_CD_0, expr_4F); + select d, new TableDataGetter("defName", (Func)((ThingDef d) => d.defName)), new TableDataGetter("fillPercent", (Func)((ThingDef d) => d.fillPercent.ToStringPercent())), new TableDataGetter("category", (Func)((ThingDef d) => ((Enum)(object)d.category).ToString()))); } public static void DoTable_DeteriorationRates() { - IEnumerable arg_F7_0 = from d in DefDatabase.AllDefs - where d.GetStatValueAbstract(StatDefOf.DeteriorationRate, null) > 0f + DebugTables.MakeTablesDialog(from d in DefDatabase.AllDefs + where d.GetStatValueAbstract(StatDefOf.DeteriorationRate, null) > 0.0 orderby d.GetStatValueAbstract(StatDefOf.DeteriorationRate, null) descending - select d; - TableDataGetter[] expr_4F = new TableDataGetter[4]; - expr_4F[0] = new TableDataGetter("defName", (ThingDef d) => d.defName); - expr_4F[1] = new TableDataGetter("deterioration rate", (ThingDef d) => d.GetStatValueAbstract(StatDefOf.DeteriorationRate, null).ToString("F1")); - expr_4F[2] = new TableDataGetter("hp", (ThingDef d) => d.BaseMaxHitPoints.ToString()); - expr_4F[3] = new TableDataGetter("days to vanish", (ThingDef d) => ((float)d.BaseMaxHitPoints / d.GetStatValueAbstract(StatDefOf.DeteriorationRate, null)).ToString("0.#")); - DebugTables.MakeTablesDialog(arg_F7_0, expr_4F); + select d, new TableDataGetter("defName", (Func)((ThingDef d) => d.defName)), new TableDataGetter("deterioration rate", (Func)((ThingDef d) => d.GetStatValueAbstract(StatDefOf.DeteriorationRate, null).ToString("F1"))), new TableDataGetter("hp", (Func)((ThingDef d) => d.BaseMaxHitPoints.ToString())), new TableDataGetter("days to vanish", (Func)((ThingDef d) => ((float)d.BaseMaxHitPoints / d.GetStatValueAbstract(StatDefOf.DeteriorationRate, null)).ToString("0.#")))); } public static void DoTable_ShootingAccuracy() { StatDef stat = StatDefOf.ShootingAccuracy; - Func accAtDistance = delegate(int level, float dist, int traitDegree) + Func accAtDistance = (Func)delegate(int level, float dist, int traitDegree) { float num = 1f; if (traitDegree != 0) { - float value = TraitDef.Named("ShootingAccuracy").DataAtDegree(traitDegree).statOffsets.First((StatModifier so) => so.stat == stat).value; + float value = TraitDef.Named("ShootingAccuracy").DataAtDegree(traitDegree).statOffsets.First((Func)((StatModifier so) => so.stat == stat)).value; num += value; } - foreach (SkillNeed current in stat.skillNeedFactors) + List.Enumerator enumerator = stat.skillNeedFactors.GetEnumerator(); + try { - SkillNeed_Direct skillNeed_Direct = current as SkillNeed_Direct; - num *= skillNeed_Direct.factorsPerLevel[level]; + while (enumerator.MoveNext()) + { + SkillNeed current = enumerator.Current; + SkillNeed_Direct skillNeed_Direct = current as SkillNeed_Direct; + num *= skillNeed_Direct.factorsPerLevel[level]; + } + } + finally + { + ((IDisposable)(object)enumerator).Dispose(); } num = stat.postProcessCurve.Evaluate(num); return Mathf.Pow(num, dist); @@ -890,27 +752,7 @@ public static void DoTable_ShootingAccuracy() { list.Add(i); } - IEnumerable arg_249_0 = list; - TableDataGetter[] expr_4B = new TableDataGetter[18]; - expr_4B[0] = new TableDataGetter("No trait skill", (int lev) => lev.ToString()); - expr_4B[1] = new TableDataGetter("acc at 1", (int lev) => accAtDistance(lev, 1f, 0).ToStringPercent("F2")); - expr_4B[2] = new TableDataGetter("acc at 10", (int lev) => accAtDistance(lev, 10f, 0).ToStringPercent("F2")); - expr_4B[3] = new TableDataGetter("acc at 20", (int lev) => accAtDistance(lev, 20f, 0).ToStringPercent("F2")); - expr_4B[4] = new TableDataGetter("acc at 30", (int lev) => accAtDistance(lev, 30f, 0).ToStringPercent("F2")); - expr_4B[5] = new TableDataGetter("acc at 50", (int lev) => accAtDistance(lev, 50f, 0).ToStringPercent("F2")); - expr_4B[6] = new TableDataGetter("Careful shooter skill", (int lev) => lev.ToString()); - expr_4B[7] = new TableDataGetter("acc at 1", (int lev) => accAtDistance(lev, 1f, 1).ToStringPercent("F2")); - expr_4B[8] = new TableDataGetter("acc at 10", (int lev) => accAtDistance(lev, 10f, 1).ToStringPercent("F2")); - expr_4B[9] = new TableDataGetter("acc at 20", (int lev) => accAtDistance(lev, 20f, 1).ToStringPercent("F2")); - expr_4B[10] = new TableDataGetter("acc at 30", (int lev) => accAtDistance(lev, 30f, 1).ToStringPercent("F2")); - expr_4B[11] = new TableDataGetter("acc at 50", (int lev) => accAtDistance(lev, 50f, 1).ToStringPercent("F2")); - expr_4B[12] = new TableDataGetter("Trigger-happy skill", (int lev) => lev.ToString()); - expr_4B[13] = new TableDataGetter("acc at 1", (int lev) => accAtDistance(lev, 1f, -1).ToStringPercent("F2")); - expr_4B[14] = new TableDataGetter("acc at 10", (int lev) => accAtDistance(lev, 10f, -1).ToStringPercent("F2")); - expr_4B[15] = new TableDataGetter("acc at 20", (int lev) => accAtDistance(lev, 20f, -1).ToStringPercent("F2")); - expr_4B[16] = new TableDataGetter("acc at 30", (int lev) => accAtDistance(lev, 30f, -1).ToStringPercent("F2")); - expr_4B[17] = new TableDataGetter("acc at 50", (int lev) => accAtDistance(lev, 50f, -1).ToStringPercent("F2")); - DebugTables.MakeTablesDialog(arg_249_0, expr_4B); + DebugTables.MakeTablesDialog(list, new TableDataGetter("No trait skill", (Func)((int lev) => lev.ToString())), new TableDataGetter("acc at 1", (Func)((int lev) => accAtDistance(lev, 1f, 0).ToStringPercent("F2"))), new TableDataGetter("acc at 10", (Func)((int lev) => accAtDistance(lev, 10f, 0).ToStringPercent("F2"))), new TableDataGetter("acc at 20", (Func)((int lev) => accAtDistance(lev, 20f, 0).ToStringPercent("F2"))), new TableDataGetter("acc at 30", (Func)((int lev) => accAtDistance(lev, 30f, 0).ToStringPercent("F2"))), new TableDataGetter("acc at 50", (Func)((int lev) => accAtDistance(lev, 50f, 0).ToStringPercent("F2"))), new TableDataGetter("Careful shooter skill", (Func)((int lev) => lev.ToString())), new TableDataGetter("acc at 1", (Func)((int lev) => accAtDistance(lev, 1f, 1).ToStringPercent("F2"))), new TableDataGetter("acc at 10", (Func)((int lev) => accAtDistance(lev, 10f, 1).ToStringPercent("F2"))), new TableDataGetter("acc at 20", (Func)((int lev) => accAtDistance(lev, 20f, 1).ToStringPercent("F2"))), new TableDataGetter("acc at 30", (Func)((int lev) => accAtDistance(lev, 30f, 1).ToStringPercent("F2"))), new TableDataGetter("acc at 50", (Func)((int lev) => accAtDistance(lev, 50f, 1).ToStringPercent("F2"))), new TableDataGetter("Trigger-happy skill", (Func)((int lev) => lev.ToString())), new TableDataGetter("acc at 1", (Func)((int lev) => accAtDistance(lev, 1f, -1).ToStringPercent("F2"))), new TableDataGetter("acc at 10", (Func)((int lev) => accAtDistance(lev, 10f, -1).ToStringPercent("F2"))), new TableDataGetter("acc at 20", (Func)((int lev) => accAtDistance(lev, 20f, -1).ToStringPercent("F2"))), new TableDataGetter("acc at 30", (Func)((int lev) => accAtDistance(lev, 30f, -1).ToStringPercent("F2"))), new TableDataGetter("acc at 50", (Func)((int lev) => accAtDistance(lev, 50f, -1).ToStringPercent("F2")))); } public static void DoTable_MiscIncidentChances() @@ -929,22 +771,14 @@ public static void DoTable_MiscIncidentChances() public static void DoTable_BodyParts() { List list = new List(); - foreach (BodyDef current in DefDatabase.AllDefs) + foreach (BodyDef allDef in DefDatabase.AllDefs) { - BodyDef localBd = current; - list.Add(new FloatMenuOption(localBd.defName, delegate + BodyDef localBd = allDef; + list.Add(new FloatMenuOption(localBd.defName, (Action)delegate() { - IEnumerable arg_12F_0 = from d in localBd.AllParts + DebugTables.MakeTablesDialog(from d in localBd.AllParts orderby d.height descending - select d; - TableDataGetter[] expr_33 = new TableDataGetter[6]; - expr_33[0] = new TableDataGetter("defName", (BodyPartRecord d) => d.def.defName); - expr_33[1] = new TableDataGetter("coverage", (BodyPartRecord d) => d.coverage.ToStringPercent()); - expr_33[2] = new TableDataGetter("coverageAbsWithChildren", (BodyPartRecord d) => d.coverageAbsWithChildren.ToStringPercent()); - expr_33[3] = new TableDataGetter("coverageAbs", (BodyPartRecord d) => d.coverageAbs.ToStringPercent()); - expr_33[4] = new TableDataGetter("depth", (BodyPartRecord d) => d.depth.ToString()); - expr_33[5] = new TableDataGetter("height", (BodyPartRecord d) => d.height.ToString()); - DebugTables.MakeTablesDialog(arg_12F_0, expr_33); + select d, new TableDataGetter("defName", (Func)((BodyPartRecord d) => d.def.defName)), new TableDataGetter("coverage", (Func)((BodyPartRecord d) => d.coverage.ToStringPercent())), new TableDataGetter("coverageAbsWithChildren", (Func)((BodyPartRecord d) => d.coverageAbsWithChildren.ToStringPercent())), new TableDataGetter("coverageAbs", (Func)((BodyPartRecord d) => d.coverageAbs.ToStringPercent())), new TableDataGetter("depth", (Func)((BodyPartRecord d) => ((Enum)(object)d.depth).ToString())), new TableDataGetter("height", (Func)((BodyPartRecord d) => ((Enum)(object)d.height).ToString()))); }, MenuOptionPriority.Default, null, null, 0f, null, null)); } Find.WindowStack.Add(new FloatMenu(list)); @@ -952,13 +786,9 @@ orderby d.height descending private static void DoTable_FillPercents(ThingCategory cat) { - IEnumerable arg_7D_0 = from d in DefDatabase.AllDefs + DebugTables.MakeTablesDialog(from d in DefDatabase.AllDefs where d.category == cat && !d.IsFrame && d.passability != Traversability.Impassable - select d; - TableDataGetter[] expr_29 = new TableDataGetter[2]; - expr_29[0] = new TableDataGetter("defName", (ThingDef d) => d.defName); - expr_29[1] = new TableDataGetter("fillPercent", (ThingDef d) => d.fillPercent.ToStringPercent()); - DebugTables.MakeTablesDialog(arg_7D_0, expr_29); + select d, new TableDataGetter("defName", (Func)((ThingDef d) => d.defName)), new TableDataGetter("fillPercent", (Func)((ThingDef d) => d.fillPercent.ToStringPercent()))); } public static void DoTable_AnimalBiomeCommonalities() @@ -966,19 +796,19 @@ public static void DoTable_AnimalBiomeCommonalities() List> list = (from b in DefDatabase.AllDefs where b.implemented && b.canBuildBase orderby b.animalDensity - select new TableDataGetter(b.defName, delegate(PawnKindDef k) + select new TableDataGetter(b.defName, (Func)delegate(PawnKindDef k) { - float num = DefDatabase.AllDefs.Sum((PawnKindDef ki) => b.CommonalityOfAnimal(ki)); + float num = DefDatabase.AllDefs.Sum((Func)((PawnKindDef ki) => b.CommonalityOfAnimal(ki))); float num2 = b.CommonalityOfAnimal(k); float num3 = num2 / num; - if (num3 == 0f) + if (num3 == 0.0) { return string.Empty; } return num3.ToStringPercent("F1"); - })).ToList>(); - list.Insert(0, new TableDataGetter("animal", (PawnKindDef k) => k.defName + ((!k.race.race.predator) ? string.Empty : "*"))); - DebugTables.MakeTablesDialog(from d in DefDatabase.AllDefs + })).ToList(); + list.Insert(0, new TableDataGetter("animal", (Func)((PawnKindDef k) => k.defName + ((!k.race.race.predator) ? string.Empty : "*")))); + DebugTables.MakeTablesDialog(from d in DefDatabase.AllDefs where d.race != null && d.RaceProps.Animal orderby d.defName select d, list.ToArray()); @@ -986,23 +816,21 @@ orderby d.defName public static void DoTable_ThingMasses() { - IOrderedEnumerable orderedEnumerable = from x in DefDatabase.AllDefsListForReading + IOrderedEnumerable dataSources = from x in DefDatabase.AllDefsListForReading where x.category == ThingCategory.Item || x.Minifiable where x.thingClass != typeof(MinifiedThing) && x.thingClass != typeof(UnfinishedThing) orderby x.GetStatValueAbstract(StatDefOf.Mass, null), x.GetStatValueAbstract(StatDefOf.MarketValue, null) select x; - Func perPawn = (ThingDef d, float bodySize) => (bodySize * 35f / d.GetStatValueAbstract(StatDefOf.Mass, null)).ToString("F0"); - Func perNutrition = delegate(ThingDef d) + Func perPawn = (Func)((ThingDef d, float bodySize) => ((float)(bodySize * 35.0 / d.GetStatValueAbstract(StatDefOf.Mass, null))).ToString("F0")); + Func perNutrition = (Func)delegate(ThingDef d) { - if (d.ingestible == null || d.ingestible.nutrition == 0f) + if (d.ingestible != null && d.ingestible.nutrition != 0.0) { - return string.Empty; + return (d.GetStatValueAbstract(StatDefOf.Mass, null) / d.ingestible.nutrition).ToString("F2"); } - return (d.GetStatValueAbstract(StatDefOf.Mass, null) / d.ingestible.nutrition).ToString("F2"); + return string.Empty; }; - IEnumerable arg_1C3_0 = orderedEnumerable; - TableDataGetter[] expr_E1 = new TableDataGetter[7]; - expr_E1[0] = new TableDataGetter("defName", delegate(ThingDef d) + DebugTables.MakeTablesDialog(dataSources, new TableDataGetter("defName", (Func)delegate(ThingDef d) { if (d.Minifiable) { @@ -1014,14 +842,7 @@ orderby x.GetStatValueAbstract(StatDefOf.Mass, null), x.GetStatValueAbstract(Sta text += " (not haulable)"; } return text; - }); - expr_E1[1] = new TableDataGetter("mass", (ThingDef d) => d.GetStatValueAbstract(StatDefOf.Mass, null).ToString()); - expr_E1[2] = new TableDataGetter("per human", (ThingDef d) => perPawn(d, ThingDefOf.Human.race.baseBodySize)); - expr_E1[3] = new TableDataGetter("per muffalo", (ThingDef d) => perPawn(d, ThingDefOf.Muffalo.race.baseBodySize)); - expr_E1[4] = new TableDataGetter("per dromedary", (ThingDef d) => perPawn(d, ThingDefOf.Dromedary.race.baseBodySize)); - expr_E1[5] = new TableDataGetter("per nutrition", (ThingDef d) => perNutrition(d)); - expr_E1[6] = new TableDataGetter("small volume", (ThingDef d) => (!d.smallVolume) ? string.Empty : "small"); - DebugTables.MakeTablesDialog(arg_1C3_0, expr_E1); + }), new TableDataGetter("mass", (Func)((ThingDef d) => d.GetStatValueAbstract(StatDefOf.Mass, null).ToString())), new TableDataGetter("per human", (Func)((ThingDef d) => perPawn(d, ThingDefOf.Human.race.baseBodySize))), new TableDataGetter("per muffalo", (Func)((ThingDef d) => perPawn(d, ThingDefOf.Muffalo.race.baseBodySize))), new TableDataGetter("per dromedary", (Func)((ThingDef d) => perPawn(d, ThingDefOf.Dromedary.race.baseBodySize))), new TableDataGetter("per nutrition", (Func)((ThingDef d) => perNutrition(d))), new TableDataGetter("small volume", (Func)((ThingDef d) => (!d.smallVolume) ? string.Empty : "small"))); } public static void DoTable_MedicalPotencyPerMedicine() @@ -1032,14 +853,36 @@ public static void DoTable_MedicalPotencyPerMedicine() where typeof(Medicine).IsAssignableFrom(d.thingClass) select d.GetStatValueAbstract(StatDefOf.MedicalPotency, null)); SkillNeed_Direct skillNeed_Direct = (SkillNeed_Direct)StatDefOf.MedicalTendQuality.skillNeedFactors[0]; - TableDataGetter[] array = new TableDataGetter[21]; - array[0] = new TableDataGetter("potency", (float p) => p.ToStringPercent()); + TableDataGetter[] array = new TableDataGetter[21] + { + new TableDataGetter("potency", (Func)((float p) => p.ToStringPercent())), + null, + null, + null, + null, + null, + null, + null, + null, + null, + null, + null, + null, + null, + null, + null, + null, + null, + null, + null, + null + }; for (int i = 0; i < 20; i++) { float factor = skillNeed_Direct.factorsPerLevel[i]; - array[i + 1] = new TableDataGetter((i + 1).ToString(), (float p) => (p * factor).ToStringPercent()); + array[i + 1] = new TableDataGetter((i + 1).ToString(), (Func)((float p) => (p * factor).ToStringPercent())); } - DebugTables.MakeTablesDialog(list, array); + DebugTables.MakeTablesDialog(list, array); } public static void DoTable_BuildingFillpercents() @@ -1055,28 +898,28 @@ public static void DoTable_ItemFillpercents() public static void DoTable_TraderKinds() { List> list = new List>(); - list.Add(new TableDataGetter("defName", (ThingDef d) => d.defName)); - foreach (TraderKindDef current in DefDatabase.AllDefs) - { - TraderKindDef localTk = current; - string text = localTk.defName; - text = text.Replace("Caravan", "C"); - text = text.Replace("Visitor", "V"); - text = text.Replace("Orbital", "R"); - text = text.Replace("Neolithic", "N"); - text = text.Replace("Outlander", "O"); - text = GenText.WithoutVowels(text); - list.Add(new TableDataGetter(text, (ThingDef td) => (!localTk.WillTrade(td)) ? string.Empty : "✓")); + list.Add(new TableDataGetter("defName", (Func)((ThingDef d) => d.defName))); + foreach (TraderKindDef allDef in DefDatabase.AllDefs) + { + TraderKindDef localTk = allDef; + string defName = localTk.defName; + defName = defName.Replace("Caravan", "C"); + defName = defName.Replace("Visitor", "V"); + defName = defName.Replace("Orbital", "R"); + defName = defName.Replace("Neolithic", "N"); + defName = defName.Replace("Outlander", "O"); + defName = GenText.WithoutVowels(defName); + list.Add(new TableDataGetter(defName, (Func)((ThingDef td) => (!localTk.WillTrade(td)) ? string.Empty : "✓"))); } - DebugTables.MakeTablesDialog(from d in DefDatabase.AllDefs - where (d.category == ThingCategory.Item && d.BaseMarketValue > 0.001f && !d.isUnfinishedThing && !d.IsCorpse && !d.destroyOnDrop && d != ThingDefOf.Silver && !d.thingCategories.NullOrEmpty()) || (d.category == ThingCategory.Building && d.Minifiable) - orderby d.thingCategories.NullOrEmpty() ? "zzzzzzz" : d.thingCategories[0].defName, d.BaseMarketValue + DebugTables.MakeTablesDialog(from d in DefDatabase.AllDefs + where (d.category == ThingCategory.Item && d.BaseMarketValue > 0.0010000000474974513 && !d.isUnfinishedThing && !d.IsCorpse && !d.destroyOnDrop && d != ThingDefOf.Silver && !d.thingCategories.NullOrEmpty()) || (d.category == ThingCategory.Building && d.Minifiable) + orderby d.thingCategories.NullOrEmpty() ? "zzzzzzz" : d.thingCategories[0].defName, d.BaseMarketValue select d, list.ToArray()); } private static string ToStringEmptyZero(this float f, string format) { - if (f <= 0f) + if (f <= 0.0) { return string.Empty; } @@ -1085,7 +928,7 @@ private static string ToStringEmptyZero(this float f, string format) private static string ToStringPercentEmptyZero(this float f, string format = "F0") { - if (f <= 0f) + if (f <= 0.0) { return string.Empty; } diff --git a/Assembly-CSharp/Verse/DeathActionWorker.cs b/Assembly-CSharp/Verse/DeathActionWorker.cs index 3e03f0822..4ba0a840d 100644 --- a/Assembly-CSharp/Verse/DeathActionWorker.cs +++ b/Assembly-CSharp/Verse/DeathActionWorker.cs @@ -1,5 +1,3 @@ -using System; - namespace Verse { public abstract class DeathActionWorker diff --git a/Assembly-CSharp/Verse/DebugCell.cs b/Assembly-CSharp/Verse/DebugCell.cs index 8880e7ba7..deb6fc5a3 100644 --- a/Assembly-CSharp/Verse/DebugCell.cs +++ b/Assembly-CSharp/Verse/DebugCell.cs @@ -1,4 +1,3 @@ -using System; using UnityEngine; namespace Verse @@ -17,7 +16,7 @@ internal sealed class DebugCell public void Draw() { - if (this.customMat != null) + if ((Object)this.customMat != (Object)null) { CellRenderer.RenderCell(this.c, this.customMat); } @@ -32,9 +31,8 @@ public void OnGUI() if (this.displayString != null) { Vector2 vector = this.c.ToUIPosition(); - Rect rect = new Rect(vector.x - 20f, vector.y - 20f, 40f, 40f); - Rect rect2 = new Rect(0f, 0f, (float)UI.screenWidth, (float)UI.screenHeight); - if (rect2.Overlaps(rect)) + Rect rect = new Rect((float)(vector.x - 20.0), (float)(vector.y - 20.0), 40f, 40f); + if (new Rect(0f, 0f, (float)UI.screenWidth, (float)UI.screenHeight).Overlaps(rect)) { Widgets.Label(rect, this.displayString); } diff --git a/Assembly-CSharp/Verse/DebugCellDrawer.cs b/Assembly-CSharp/Verse/DebugCellDrawer.cs index e682139ba..3b88b8eff 100644 --- a/Assembly-CSharp/Verse/DebugCellDrawer.cs +++ b/Assembly-CSharp/Verse/DebugCellDrawer.cs @@ -1,4 +1,3 @@ -using System; using System.Collections.Generic; using UnityEngine; @@ -12,7 +11,7 @@ public sealed class DebugCellDrawer private List debugLines = new List(); - public void FlashCell(IntVec3 c, float colorPct = 0f, string text = null) + public void FlashCell(IntVec3 c, float colorPct = 0, string text = null) { DebugCell debugCell = new DebugCell(); debugCell.c = c; @@ -34,8 +33,10 @@ public void FlashCell(IntVec3 c, Material mat, string text = null) public void FlashLine(IntVec3 a, IntVec3 b) { - DebugLine item = new DebugLine(a.ToVector3Shifted(), b.ToVector3Shifted()); - item.TicksLeft = 50; + DebugLine item = new DebugLine(a.ToVector3Shifted(), b.ToVector3Shifted()) + { + TicksLeft = 50 + }; this.debugLines.Add(item); } @@ -53,21 +54,26 @@ public void DebugDrawerUpdate() public void DebugDrawerTick() { - for (int i = this.debugCells.Count - 1; i >= 0; i--) + for (int num = this.debugCells.Count - 1; num >= 0; num--) { - DebugCell debugCell = this.debugCells[i]; + DebugCell debugCell = this.debugCells[num]; debugCell.ticksLeft--; if (debugCell.ticksLeft <= 0) { - this.debugCells.RemoveAt(i); + this.debugCells.RemoveAt(num); } } - for (int j = this.debugLines.Count - 1; j >= 0; j--) + for (int num2 = this.debugLines.Count - 1; num2 >= 0; num2--) { - this.debugLines[j] = new DebugLine(this.debugLines[j].a, this.debugLines[j].b, this.debugLines[j].TicksLeft - 1); - if (this.debugLines[j].TicksLeft <= 0) + List obj = this.debugLines; + int index = num2; + DebugLine debugLine = this.debugLines[num2]; + Vector3 a = debugLine.a; + DebugLine debugLine2 = this.debugLines[num2]; + obj[index] = new DebugLine(a, debugLine2.b, this.debugLines[num2].TicksLeft - 1); + if (this.debugLines[num2].TicksLeft <= 0) { - this.debugLines.RemoveAt(j); + this.debugLines.RemoveAt(num2); } } } diff --git a/Assembly-CSharp/Verse/DebugInputLogger.cs b/Assembly-CSharp/Verse/DebugInputLogger.cs index 2e468ac83..cb5d18f0f 100644 --- a/Assembly-CSharp/Verse/DebugInputLogger.cs +++ b/Assembly-CSharp/Verse/DebugInputLogger.cs @@ -1,4 +1,3 @@ -using System; using UnityEngine; namespace Verse @@ -7,68 +6,15 @@ internal static class DebugInputLogger { public static void InputLogOnGUI() { - if (!DebugViewSettings.logInput) + if (DebugViewSettings.logInput && (Event.current.type == EventType.MouseDown || Event.current.type == EventType.MouseUp || Event.current.type == EventType.KeyDown || Event.current.type == EventType.KeyUp || Event.current.type == EventType.ScrollWheel)) { - return; - } - if (Event.current.type == EventType.MouseDown || Event.current.type == EventType.MouseUp || Event.current.type == EventType.KeyDown || Event.current.type == EventType.KeyUp || Event.current.type == EventType.ScrollWheel) - { - Log.Message(string.Concat(new object[] - { - "Frame ", - Time.frameCount, - ": ", - Event.current.ToStringFull() - })); + Log.Message("Frame " + Time.frameCount + ": " + Event.current.ToStringFull()); } } public static string ToStringFull(this Event ev) { - return string.Concat(new object[] - { - "(EVENT\ntype=", - ev.type, - "\nbutton=", - ev.button, - "\nkeyCode=", - ev.keyCode, - "\ndelta=", - ev.delta, - "\nalt=", - ev.alt, - "\ncapsLock=", - ev.capsLock, - "\ncharacter=", - (ev.character == '\0') ? ' ' : ev.character, - "\nclickCount=", - ev.clickCount, - "\ncommand=", - ev.command, - "\ncommandName=", - ev.commandName, - "\ncontrol=", - ev.control, - "\nfunctionKey=", - ev.functionKey, - "\nisKey=", - ev.isKey, - "\nisMouse=", - ev.isMouse, - "\nmodifiers=", - ev.modifiers, - "\nmousePosition=", - ev.mousePosition, - "\nnumeric=", - ev.numeric, - "\npressure=", - ev.pressure, - "\nrawType=", - ev.rawType, - "\nshift=", - ev.shift, - "\n)" - }); + return "(EVENT\ntype=" + ev.type + "\nbutton=" + ev.button + "\nkeyCode=" + ev.keyCode + "\ndelta=" + ev.delta + "\nalt=" + ev.alt + "\ncapsLock=" + ev.capsLock + "\ncharacter=" + ((ev.character == '\0') ? ' ' : ev.character) + "\nclickCount=" + ev.clickCount + "\ncommand=" + ev.command + "\ncommandName=" + ev.commandName + "\ncontrol=" + ev.control + "\nfunctionKey=" + ev.functionKey + "\nisKey=" + ev.isKey + "\nisMouse=" + ev.isMouse + "\nmodifiers=" + ev.modifiers + "\nmousePosition=" + ev.mousePosition + "\nnumeric=" + ev.numeric + "\npressure=" + ev.pressure + "\nrawType=" + ev.rawType + "\nshift=" + ev.shift + "\n)"; } } } diff --git a/Assembly-CSharp/Verse/DebugLine.cs b/Assembly-CSharp/Verse/DebugLine.cs index 389664c18..93dec90c0 100644 --- a/Assembly-CSharp/Verse/DebugLine.cs +++ b/Assembly-CSharp/Verse/DebugLine.cs @@ -1,4 +1,3 @@ -using System; using UnityEngine; namespace Verse diff --git a/Assembly-CSharp/Verse/DebugLoadIDsSavingErrorsChecker.cs b/Assembly-CSharp/Verse/DebugLoadIDsSavingErrorsChecker.cs index a23889843..beb6ec67e 100644 --- a/Assembly-CSharp/Verse/DebugLoadIDsSavingErrorsChecker.cs +++ b/Assembly-CSharp/Verse/DebugLoadIDsSavingErrorsChecker.cs @@ -5,7 +5,7 @@ namespace Verse { public class DebugLoadIDsSavingErrorsChecker { - private struct ReferencedObject : IEquatable + private struct ReferencedObject : IEquatable { public string loadID; @@ -19,10 +19,14 @@ public ReferencedObject(string loadID, string label) public override bool Equals(object obj) { - return obj is DebugLoadIDsSavingErrorsChecker.ReferencedObject && this.Equals((DebugLoadIDsSavingErrorsChecker.ReferencedObject)obj); + if (!(obj is ReferencedObject)) + { + return false; + } + return this.Equals((ReferencedObject)obj); } - public bool Equals(DebugLoadIDsSavingErrorsChecker.ReferencedObject other) + public bool Equals(ReferencedObject other) { return this.loadID == other.loadID && this.label == other.label; } @@ -30,16 +34,16 @@ public bool Equals(DebugLoadIDsSavingErrorsChecker.ReferencedObject other) public override int GetHashCode() { int seed = 0; - seed = Gen.HashCombine(seed, this.loadID); - return Gen.HashCombine(seed, this.label); + seed = Gen.HashCombine(seed, this.loadID); + return Gen.HashCombine(seed, this.label); } - public static bool operator ==(DebugLoadIDsSavingErrorsChecker.ReferencedObject lhs, DebugLoadIDsSavingErrorsChecker.ReferencedObject rhs) + public static bool operator ==(ReferencedObject lhs, ReferencedObject rhs) { return lhs.Equals(rhs); } - public static bool operator !=(DebugLoadIDsSavingErrorsChecker.ReferencedObject lhs, DebugLoadIDsSavingErrorsChecker.ReferencedObject rhs) + public static bool operator !=(ReferencedObject lhs, ReferencedObject rhs) { return !(lhs == rhs); } @@ -47,101 +51,76 @@ public override int GetHashCode() private HashSet deepSaved = new HashSet(); - private HashSet referenced = new HashSet(); + private HashSet referenced = new HashSet(); public void Clear() { - if (!Prefs.DevMode) + if (Prefs.DevMode) { - return; + this.deepSaved.Clear(); + this.referenced.Clear(); } - this.deepSaved.Clear(); - this.referenced.Clear(); } public void CheckForErrorsAndClear() { - if (!Prefs.DevMode) - { - return; - } - if (!Scribe.saver.savingForDebug) + if (Prefs.DevMode) { - foreach (DebugLoadIDsSavingErrorsChecker.ReferencedObject current in this.referenced) + if (!Scribe.saver.savingForDebug) { - if (!this.deepSaved.Contains(current.loadID)) + HashSet.Enumerator enumerator = this.referenced.GetEnumerator(); + try { - Log.Warning(string.Concat(new string[] + while (enumerator.MoveNext()) { - "Object with load ID ", - current.loadID, - " is referenced (xml node name: ", - current.label, - ") but is not deep-saved. This will cause errors during loading." - })); + ReferencedObject current = enumerator.Current; + if (!this.deepSaved.Contains(current.loadID)) + { + Log.Warning("Object with load ID " + current.loadID + " is referenced (xml node name: " + current.label + ") but is not deep-saved. This will cause errors during loading."); + } + } + } + finally + { + ((IDisposable)(object)enumerator).Dispose(); } } + this.Clear(); } - this.Clear(); } public void RegisterDeepSaved(object obj, string label) { - if (!Prefs.DevMode) + if (Prefs.DevMode) { - return; - } - if (Scribe.mode != LoadSaveMode.Saving) - { - Log.Error(string.Concat(new object[] + if (Scribe.mode != LoadSaveMode.Saving) { - "Registered ", - obj, - ", but current mode is ", - Scribe.mode - })); - return; - } - if (obj == null) - { - return; - } - ILoadReferenceable loadReferenceable = obj as ILoadReferenceable; - if (loadReferenceable != null && !this.deepSaved.Add(loadReferenceable.GetUniqueLoadID())) - { - Log.Warning(string.Concat(new string[] + Log.Error("Registered " + obj + ", but current mode is " + Scribe.mode); + } + else if (obj != null) { - "DebugLoadIDsSavingErrorsChecker error: tried to register deep-saved object with loadID ", - loadReferenceable.GetUniqueLoadID(), - ", but it's already here. label=", - label, - " (not cleared after the previous save? different objects have the same load ID? the same object is deep-saved twice?)" - })); + ILoadReferenceable loadReferenceable = obj as ILoadReferenceable; + if (loadReferenceable != null && !this.deepSaved.Add(loadReferenceable.GetUniqueLoadID())) + { + Log.Warning("DebugLoadIDsSavingErrorsChecker error: tried to register deep-saved object with loadID " + loadReferenceable.GetUniqueLoadID() + ", but it's already here. label=" + label + " (not cleared after the previous save? different objects have the same load ID? the same object is deep-saved twice?)"); + } + } } } public void RegisterReferenced(ILoadReferenceable obj, string label) { - if (!Prefs.DevMode) - { - return; - } - if (Scribe.mode != LoadSaveMode.Saving) + if (Prefs.DevMode) { - Log.Error(string.Concat(new object[] + if (Scribe.mode != LoadSaveMode.Saving) { - "Registered ", - obj, - ", but current mode is ", - Scribe.mode - })); - return; - } - if (obj == null) - { - return; + Log.Error("Registered " + obj + ", but current mode is " + Scribe.mode); + } + else if (obj != null) + { + this.referenced.Add(new ReferencedObject(obj.GetUniqueLoadID(), label)); + } } - this.referenced.Add(new DebugLoadIDsSavingErrorsChecker.ReferencedObject(obj.GetUniqueLoadID(), label)); } } } diff --git a/Assembly-CSharp/Verse/DebugLogsUtility.cs b/Assembly-CSharp/Verse/DebugLogsUtility.cs index 2ad8ce3b7..442e34f56 100644 --- a/Assembly-CSharp/Verse/DebugLogsUtility.cs +++ b/Assembly-CSharp/Verse/DebugLogsUtility.cs @@ -14,26 +14,26 @@ public static string ThingListToUniqueCountString(IEnumerable things) return "null"; } Dictionary dictionary = new Dictionary(); - foreach (Thing current in things) + foreach (Thing item in things) { - if (!dictionary.ContainsKey(current.def)) + if (!dictionary.ContainsKey(item.def)) { - dictionary.Add(current.def, 0); + dictionary.Add(item.def, 0); } Dictionary dictionary2; - Dictionary expr_44 = dictionary2 = dictionary; + Dictionary obj = dictionary2 = dictionary; ThingDef def; - ThingDef expr_4D = def = current.def; + ThingDef key = def = item.def; int num = dictionary2[def]; - expr_44[expr_4D] = num + 1; + obj[key] = num + 1; } StringBuilder stringBuilder = new StringBuilder(); stringBuilder.AppendLine("Registered things in dynamic draw list:"); - foreach (KeyValuePair current2 in from k in dictionary + foreach (KeyValuePair item2 in from k in dictionary orderby k.Value descending select k) { - stringBuilder.AppendLine(current2.Key + " - " + current2.Value); + stringBuilder.AppendLine(item2.Key + " - " + item2.Value); } return stringBuilder.ToString(); } diff --git a/Assembly-CSharp/Verse/DebugMatsRandom.cs b/Assembly-CSharp/Verse/DebugMatsRandom.cs index e4b389580..ff5790560 100644 --- a/Assembly-CSharp/Verse/DebugMatsRandom.cs +++ b/Assembly-CSharp/Verse/DebugMatsRandom.cs @@ -1,4 +1,3 @@ -using System; using UnityEngine; namespace Verse diff --git a/Assembly-CSharp/Verse/DebugMatsSpectrum.cs b/Assembly-CSharp/Verse/DebugMatsSpectrum.cs index d40e8fbe4..0ead7e5bb 100644 --- a/Assembly-CSharp/Verse/DebugMatsSpectrum.cs +++ b/Assembly-CSharp/Verse/DebugMatsSpectrum.cs @@ -1,4 +1,3 @@ -using System; using UnityEngine; namespace Verse @@ -18,7 +17,7 @@ static DebugMatsSpectrum() { DebugMatsSpectrum.spectrumMatsTranparent = new Material[100]; DebugMatsSpectrum.spectrumMatsOpaque = new Material[100]; - DebugMatsSpectrum.DebugSpectrum = new Color[] + DebugMatsSpectrum.DebugSpectrum = new Color[5] { new Color(0.75f, 0f, 0f), new Color(0.5f, 0.3f, 0f), @@ -28,8 +27,8 @@ static DebugMatsSpectrum() }; for (int i = 0; i < 100; i++) { - DebugMatsSpectrum.spectrumMatsTranparent[i] = MatsFromSpectrum.Get(DebugMatsSpectrum.DebugSpectrumWithOpacity(0.25f), (float)i / 100f); - DebugMatsSpectrum.spectrumMatsOpaque[i] = MatsFromSpectrum.Get(DebugMatsSpectrum.DebugSpectrumWithOpacity(1f), (float)i / 100f); + DebugMatsSpectrum.spectrumMatsTranparent[i] = MatsFromSpectrum.Get(DebugMatsSpectrum.DebugSpectrumWithOpacity(0.25f), (float)((float)i / 100.0)); + DebugMatsSpectrum.spectrumMatsOpaque[i] = MatsFromSpectrum.Get(DebugMatsSpectrum.DebugSpectrumWithOpacity(1f), (float)((float)i / 100.0)); } } diff --git a/Assembly-CSharp/Verse/DebugMenuOptionMode.cs b/Assembly-CSharp/Verse/DebugMenuOptionMode.cs index 4a3c674e8..5e94f52f3 100644 --- a/Assembly-CSharp/Verse/DebugMenuOptionMode.cs +++ b/Assembly-CSharp/Verse/DebugMenuOptionMode.cs @@ -1,10 +1,8 @@ -using System; - namespace Verse { public enum DebugMenuOptionMode : byte { - Action, - Tool + Action = 0, + Tool = 1 } } diff --git a/Assembly-CSharp/Verse/DebugSettings.cs b/Assembly-CSharp/Verse/DebugSettings.cs index 9b713e53f..92ce643e7 100644 --- a/Assembly-CSharp/Verse/DebugSettings.cs +++ b/Assembly-CSharp/Verse/DebugSettings.cs @@ -1,5 +1,3 @@ -using System; - namespace Verse { public static class DebugSettings diff --git a/Assembly-CSharp/Verse/DebugSolidColorMats.cs b/Assembly-CSharp/Verse/DebugSolidColorMats.cs index 9fdee6db5..9f3fb73e8 100644 --- a/Assembly-CSharp/Verse/DebugSolidColorMats.cs +++ b/Assembly-CSharp/Verse/DebugSolidColorMats.cs @@ -1,4 +1,3 @@ -using System; using System.Collections.Generic; using UnityEngine; @@ -10,7 +9,7 @@ public static class DebugSolidColorMats public static Material MaterialOf(Color col) { - Material material; + Material material = default(Material); if (DebugSolidColorMats.colorMatDict.TryGetValue(col, out material)) { return material; diff --git a/Assembly-CSharp/Verse/DebugTables.cs b/Assembly-CSharp/Verse/DebugTables.cs index e3b3865e2..c53f43a18 100644 --- a/Assembly-CSharp/Verse/DebugTables.cs +++ b/Assembly-CSharp/Verse/DebugTables.cs @@ -8,7 +8,7 @@ public static class DebugTables { public static void MakeTablesDialog(IEnumerable dataSources, params TableDataGetter[] getters) { - List> list = getters.ToList>(); + List> list = ((IEnumerable>)getters).ToList>(); int num = dataSources.Count() + 1; int count = list.Count; string[,] array = new string[count, num]; @@ -20,11 +20,11 @@ public static void MakeTablesDialog(IEnumerable dataSources, params TableD num2++; } int num3 = 1; - foreach (T current in dataSources) + foreach (T item in dataSources) { - for (int j = 0; j < count; j++) + for (int num4 = 0; num4 < count; num4++) { - array[j, num3] = list[j].getter(current); + array[num4, num3] = list[num4].getter(item); } num3++; } @@ -38,24 +38,24 @@ public static void MakeTablesDialog(IEnumerable colValue string[,] array = new string[num, num2]; array[0, 0] = tlLabel; int num3 = 1; - foreach (TColumn current in colValues) + foreach (TColumn item in colValues) { - array[num3, 0] = colLabelFormatter(current); + array[num3, 0] = colLabelFormatter(item); num3++; } int num4 = 1; - foreach (TRow current2 in rowValues) + foreach (TRow item2 in rowValues) { - array[0, num4] = rowLabelFormatter(current2); + array[0, num4] = rowLabelFormatter(item2); num4++; } int num5 = 1; - foreach (TRow current3 in rowValues) + foreach (TRow item3 in rowValues) { int num6 = 1; - foreach (TColumn current4 in colValues) + foreach (TColumn item4 in colValues) { - array[num6, num5] = func(current4, current3); + array[num6, num5] = func(item4, item3); num6++; } num5++; diff --git a/Assembly-CSharp/Verse/DebugThingPlaceHelper.cs b/Assembly-CSharp/Verse/DebugThingPlaceHelper.cs index 662d101f6..42f6c7e6b 100644 --- a/Assembly-CSharp/Verse/DebugThingPlaceHelper.cs +++ b/Assembly-CSharp/Verse/DebugThingPlaceHelper.cs @@ -9,7 +9,27 @@ public static class DebugThingPlaceHelper { public static bool IsDebugSpawnable(ThingDef def) { - return def.forceDebugSpawnable || (def.thingClass != typeof(Corpse) && !def.IsBlueprint && !def.IsFrame && def != ThingDefOf.ActiveDropPod && def.thingClass != typeof(MinifiedThing) && def.thingClass != typeof(UnfinishedThing) && !def.destroyOnDrop && (def.category == ThingCategory.Filth || def.category == ThingCategory.Item || def.category == ThingCategory.Plant || def.category == ThingCategory.Ethereal || (def.category == ThingCategory.Building && def.building.isNaturalRock) || (def.category == ThingCategory.Building && def.designationCategory == null))); + if (def.forceDebugSpawnable) + { + return true; + } + if (def.thingClass != typeof(Corpse) && !def.IsBlueprint && !def.IsFrame && def != ThingDefOf.ActiveDropPod && def.thingClass != typeof(MinifiedThing) && def.thingClass != typeof(UnfinishedThing) && !def.destroyOnDrop) + { + if (def.category != ThingCategory.Filth && def.category != ThingCategory.Item && def.category != ThingCategory.Plant && def.category != ThingCategory.Ethereal) + { + if (def.category == ThingCategory.Building && def.building.isNaturalRock) + { + return true; + } + if (def.category == ThingCategory.Building && def.designationCategory == null) + { + return true; + } + return false; + } + return true; + } + return false; } public static void DebugSpawn(ThingDef def, IntVec3 c, int stackCount = -1, bool direct = false) @@ -46,25 +66,28 @@ public static List TryPlaceOptionsForStackCount(int stackCount, IEnumerable enumerable = from def in DefDatabase.AllDefs where DebugThingPlaceHelper.IsDebugSpawnable(def) && def.stackLimit >= stackCount select def; - foreach (ThingDef current in enumerable) + foreach (ThingDef item in enumerable) { - ThingDef localDef = current; - list.Add(new DebugMenuOption(localDef.LabelCap, DebugMenuOptionMode.Tool, delegate + ThingDef localDef = item; + list.Add(new DebugMenuOption(localDef.LabelCap, DebugMenuOptionMode.Tool, (Action)delegate() { DebugThingPlaceHelper.DebugSpawn(localDef, UI.MouseCell(), stackCount, direct); })); } if (stackCount == 1) { - foreach (ThingDef current2 in from def in DefDatabase.AllDefs - where def.Minifiable - select def) { - ThingDef localDef = current2; - list.Add(new DebugMenuOption(localDef.LabelCap + " (minified)", DebugMenuOptionMode.Tool, delegate + foreach (ThingDef item2 in from def in DefDatabase.AllDefs + where def.Minifiable + select def) { - DebugThingPlaceHelper.DebugSpawn(localDef, UI.MouseCell(), stackCount, direct); - })); + ThingDef localDef2 = item2; + list.Add(new DebugMenuOption(localDef2.LabelCap + " (minified)", DebugMenuOptionMode.Tool, (Action)delegate() + { + DebugThingPlaceHelper.DebugSpawn(localDef2, UI.MouseCell(), stackCount, direct); + })); + } + return list; } } return list; diff --git a/Assembly-CSharp/Verse/DebugTool.cs b/Assembly-CSharp/Verse/DebugTool.cs index 49813d039..3c0fff1a1 100644 --- a/Assembly-CSharp/Verse/DebugTool.cs +++ b/Assembly-CSharp/Verse/DebugTool.cs @@ -22,7 +22,7 @@ public DebugTool(string label, Action clickAction, IntVec3 firstRectCorner) { this.label = label; this.clickAction = clickAction; - this.onGUIAction = delegate + this.onGUIAction = (Action)delegate() { IntVec3 intVec = UI.MouseCell(); Vector3 v = firstRectCorner.ToVector3Shifted(); @@ -71,7 +71,7 @@ public void DebugToolOnGUI() Rect rect = new Rect(vector.x, vector.y, 999f, 999f); Text.Font = GameFont.Small; Widgets.Label(rect, this.label); - if (this.onGUIAction != null) + if ((object)this.onGUIAction != null) { this.onGUIAction(); } diff --git a/Assembly-CSharp/Verse/DebugTools.cs b/Assembly-CSharp/Verse/DebugTools.cs index 26e823330..96f331a88 100644 --- a/Assembly-CSharp/Verse/DebugTools.cs +++ b/Assembly-CSharp/Verse/DebugTools.cs @@ -1,5 +1,3 @@ -using System; - namespace Verse { public static class DebugTools diff --git a/Assembly-CSharp/Verse/DebugTools_Health.cs b/Assembly-CSharp/Verse/DebugTools_Health.cs index 36801d359..2a65db04a 100644 --- a/Assembly-CSharp/Verse/DebugTools_Health.cs +++ b/Assembly-CSharp/Verse/DebugTools_Health.cs @@ -13,10 +13,10 @@ public static List Options_RestorePart(Pawn p) throw new ArgumentNullException("p"); } List list = new List(); - foreach (BodyPartRecord current in p.health.hediffSet.GetNotMissingParts(BodyPartHeight.Undefined, BodyPartDepth.Undefined)) + foreach (BodyPartRecord notMissingPart in p.health.hediffSet.GetNotMissingParts(BodyPartHeight.Undefined, BodyPartDepth.Undefined)) { - BodyPartRecord localPart = current; - list.Add(new DebugMenuOption(localPart.def.LabelCap, DebugMenuOptionMode.Action, delegate + BodyPartRecord localPart = notMissingPart; + list.Add(new DebugMenuOption(localPart.def.LabelCap, DebugMenuOptionMode.Action, (Action)delegate() { p.health.RestorePart(localPart, null, true); })); @@ -27,14 +27,14 @@ public static List Options_RestorePart(Pawn p) public static List Options_ApplyDamage() { List list = new List(); - foreach (DamageDef current in DefDatabase.AllDefs) + foreach (DamageDef allDef in DefDatabase.AllDefs) { - DamageDef localDef = current; - list.Add(new DebugMenuOption(localDef.LabelCap, DebugMenuOptionMode.Tool, delegate + DamageDef localDef = allDef; + list.Add(new DebugMenuOption(localDef.LabelCap, DebugMenuOptionMode.Tool, (Action)delegate() { Pawn pawn = (from t in Find.VisibleMap.thingGrid.ThingsAt(UI.MouseCell()) where t is Pawn - select t).Cast().FirstOrDefault(); + select t).Cast().FirstOrDefault(); if (pawn != null) { Find.WindowStack.Add(new Dialog_DebugOptionListLister(DebugTools_Health.Options_Damage_BodyParts(pawn, localDef))); @@ -51,34 +51,43 @@ private static List Options_Damage_BodyParts(Pawn p, DamageDef throw new ArgumentNullException("p"); } List list = new List(); - list.Add(new DebugMenuOption("(no body part)", DebugMenuOptionMode.Action, delegate + list.Add(new DebugMenuOption("(no body part)", DebugMenuOptionMode.Action, (Action)delegate() { p.TakeDamage(new DamageInfo(def, 5, -1f, null, null, null, DamageInfo.SourceCategory.ThingOrUnknown)); })); - foreach (BodyPartRecord current in p.RaceProps.body.AllParts) + List.Enumerator enumerator = p.RaceProps.body.AllParts.GetEnumerator(); + try { - BodyPartRecord localPart = current; - list.Add(new DebugMenuOption(localPart.def.LabelCap, DebugMenuOptionMode.Action, delegate + while (enumerator.MoveNext()) { - Thing arg_2C_0 = p; - BodyPartRecord localPart = localPart; - arg_2C_0.TakeDamage(new DamageInfo(def, 5, -1f, null, localPart, null, DamageInfo.SourceCategory.ThingOrUnknown)); - })); + BodyPartRecord current = enumerator.Current; + BodyPartRecord localPart = current; + list.Add(new DebugMenuOption(localPart.def.LabelCap, DebugMenuOptionMode.Action, (Action)delegate() + { + Pawn obj = p; + BodyPartRecord forceHitPart = localPart; + obj.TakeDamage(new DamageInfo(def, 5, -1f, null, forceHitPart, null, DamageInfo.SourceCategory.ThingOrUnknown)); + })); + } + return list; + } + finally + { + ((IDisposable)(object)enumerator).Dispose(); } - return list; } public static List Options_AddHediff() { List list = new List(); - foreach (Type current in (from t in typeof(Hediff).AllSubclasses() + foreach (Type item in (from t in typeof(Hediff).AllSubclasses() where !t.IsAbstract - select t).Concat(Gen.YieldSingle(typeof(Hediff)))) + select t).Concat(Gen.YieldSingle(typeof(Hediff)))) { - Type localDiffType = current; + Type localDiffType = item; if (localDiffType != typeof(Hediff_Injury)) { - list.Add(new DebugMenuOption(localDiffType.ToString(), DebugMenuOptionMode.Action, delegate + list.Add(new DebugMenuOption(localDiffType.ToString(), DebugMenuOptionMode.Action, (Action)delegate { Find.WindowStack.Add(new Dialog_DebugOptionListLister(DebugTools_Health.Options_HediffsDefs(localDiffType))); })); @@ -90,14 +99,14 @@ public static List Options_AddHediff() private static List Options_HediffsDefs(Type diffType) { List list = new List(); - foreach (HediffDef current in from d in DefDatabase.AllDefs + foreach (HediffDef item in from d in DefDatabase.AllDefs where d.hediffClass == diffType select d) { - HediffDef localDef = current; - list.Add(new DebugMenuOption(localDef.LabelCap, DebugMenuOptionMode.Tool, delegate + HediffDef localDef = item; + list.Add(new DebugMenuOption(localDef.LabelCap, DebugMenuOptionMode.Tool, (Action)delegate() { - Pawn pawn = Find.VisibleMap.thingGrid.ThingsAt(UI.MouseCell()).Where((Thing t) => t is Pawn).Cast().FirstOrDefault(); + Pawn pawn = Find.VisibleMap.thingGrid.ThingsAt(UI.MouseCell()).Where((Func)((Thing t) => t is Pawn)).Cast().FirstOrDefault(); if (pawn != null) { Find.WindowStack.Add(new Dialog_DebugOptionListLister(DebugTools_Health.Options_Hediff_BodyParts(pawn, localDef))); @@ -115,19 +124,28 @@ private static List Options_Hediff_BodyParts(Pawn p, HediffDef throw new ArgumentNullException("p"); } List list = new List(); - list.Add(new DebugMenuOption("(no body part)", DebugMenuOptionMode.Action, delegate + list.Add(new DebugMenuOption("(no body part)", DebugMenuOptionMode.Action, (Action)delegate() { - p.health.AddHediff(def, null, null); + p.health.AddHediff(def, null, default(DamageInfo?)); })); - foreach (BodyPartRecord current in p.RaceProps.body.AllParts) + List.Enumerator enumerator = p.RaceProps.body.AllParts.GetEnumerator(); + try { - BodyPartRecord localPart = current; - list.Add(new DebugMenuOption(localPart.def.LabelCap, DebugMenuOptionMode.Action, delegate + while (enumerator.MoveNext()) { - p.health.AddHediff(def, localPart, null); - })); + BodyPartRecord current = enumerator.Current; + BodyPartRecord localPart = current; + list.Add(new DebugMenuOption(localPart.def.LabelCap, DebugMenuOptionMode.Action, (Action)delegate() + { + p.health.AddHediff(def, localPart, default(DamageInfo?)); + })); + } + return list; + } + finally + { + ((IDisposable)(object)enumerator).Dispose(); } - return list; } } } diff --git a/Assembly-CSharp/Verse/DebugTools_MapGen.cs b/Assembly-CSharp/Verse/DebugTools_MapGen.cs index 7856ae9e0..b0618d530 100644 --- a/Assembly-CSharp/Verse/DebugTools_MapGen.cs +++ b/Assembly-CSharp/Verse/DebugTools_MapGen.cs @@ -8,10 +8,10 @@ public static class DebugTools_MapGen public static List Options_Scatterers() { List list = new List(); - foreach (Type current in typeof(GenStep_Scatterer).AllLeafSubclasses()) + foreach (Type item in typeof(GenStep_Scatterer).AllLeafSubclasses()) { - Type localSt = current; - list.Add(new DebugMenuOption(localSt.ToString(), DebugMenuOptionMode.Tool, delegate + Type localSt = item; + list.Add(new DebugMenuOption(localSt.ToString(), DebugMenuOptionMode.Tool, (Action)delegate { GenStep_Scatterer genStep_Scatterer = (GenStep_Scatterer)Activator.CreateInstance(localSt); genStep_Scatterer.ForceScatterAt(UI.MouseCell(), Find.VisibleMap); diff --git a/Assembly-CSharp/Verse/DebugViewSettings.cs b/Assembly-CSharp/Verse/DebugViewSettings.cs index e988efd99..ceed30eb3 100644 --- a/Assembly-CSharp/Verse/DebugViewSettings.cs +++ b/Assembly-CSharp/Verse/DebugViewSettings.cs @@ -1,5 +1,3 @@ -using System; - namespace Verse { public static class DebugViewSettings diff --git a/Assembly-CSharp/Verse/DebugWindowsOpener.cs b/Assembly-CSharp/Verse/DebugWindowsOpener.cs index 076e2fc1f..b70cd692a 100644 --- a/Assembly-CSharp/Verse/DebugWindowsOpener.cs +++ b/Assembly-CSharp/Verse/DebugWindowsOpener.cs @@ -9,54 +9,53 @@ public class DebugWindowsOpener { public void DevToolStarterOnGUI() { - if (!Prefs.DevMode) + if (Prefs.DevMode) { - return; - } - Vector2 vector = new Vector2((float)UI.screenWidth * 0.5f, 3f); - int num = 6; - if (Current.ProgramState == ProgramState.Playing) - { - num += 2; - } - float num2 = 25f; - if (Current.ProgramState == ProgramState.Playing && DebugSettings.godMode) - { - num2 += 15f; - } - Find.WindowStack.ImmediateWindow(1593759361, new Rect(vector.x, vector.y, (float)num * 28f - 4f + 1f, num2).Rounded(), WindowLayer.GameUI, delegate - { - this.DrawButtons(); - }, false, false, 0f); - if (KeyBindingDefOf.ToggleDebugLog.KeyDownEvent) - { - this.ToggleLogWindow(); - Event.current.Use(); - } - if (KeyBindingDefOf.ToggleDebugActionsMenu.KeyDownEvent) - { - this.ToggleDebugActionsMenu(); - Event.current.Use(); - } - if (KeyBindingDefOf.ToggleDebugLogMenu.KeyDownEvent) - { - this.ToggleDebugLogMenu(); - Event.current.Use(); - } - if (KeyBindingDefOf.ToggleDebugSettingsMenu.KeyDownEvent) - { - this.ToggleDebugSettingsMenu(); - Event.current.Use(); - } - if (KeyBindingDefOf.ToggleDebugInspector.KeyDownEvent) - { - this.ToggleDebugInspector(); - Event.current.Use(); - } - if (Current.ProgramState == ProgramState.Playing && KeyBindingDefOf.ToggleGodMode.KeyDownEvent) - { - this.ToggleGodMode(); - Event.current.Use(); + Vector2 vector = new Vector2((float)((float)UI.screenWidth * 0.5), 3f); + int num = 6; + if (Current.ProgramState == ProgramState.Playing) + { + num += 2; + } + float num2 = 25f; + if (Current.ProgramState == ProgramState.Playing && DebugSettings.godMode) + { + num2 = (float)(num2 + 15.0); + } + Find.WindowStack.ImmediateWindow(1593759361, new Rect(vector.x, vector.y, (float)((float)num * 28.0 - 4.0 + 1.0), num2).Rounded(), WindowLayer.GameUI, (Action)delegate + { + this.DrawButtons(); + }, false, false, 0f); + if (KeyBindingDefOf.ToggleDebugLog.KeyDownEvent) + { + this.ToggleLogWindow(); + Event.current.Use(); + } + if (KeyBindingDefOf.ToggleDebugActionsMenu.KeyDownEvent) + { + this.ToggleDebugActionsMenu(); + Event.current.Use(); + } + if (KeyBindingDefOf.ToggleDebugLogMenu.KeyDownEvent) + { + this.ToggleDebugLogMenu(); + Event.current.Use(); + } + if (KeyBindingDefOf.ToggleDebugSettingsMenu.KeyDownEvent) + { + this.ToggleDebugSettingsMenu(); + Event.current.Use(); + } + if (KeyBindingDefOf.ToggleDebugInspector.KeyDownEvent) + { + this.ToggleDebugInspector(); + Event.current.Use(); + } + if (Current.ProgramState == ProgramState.Playing && KeyBindingDefOf.ToggleGodMode.KeyDownEvent) + { + this.ToggleGodMode(); + Event.current.Use(); + } } } @@ -99,7 +98,7 @@ private void DrawButtons() Widgets.Label(new Rect(0f, 25f, 200f, 100f), "God mode"); } bool pauseOnError = Prefs.PauseOnError; - widgetRow.ToggleableIcon(ref pauseOnError, TexButton.TogglePauseOnError, "Pause the game when an error is logged.", null, null); + widgetRow.ToggleableIcon(ref pauseOnError, TexButton.TogglePauseOnError, "Pause the game when an error is logged.", null, (string)null); Prefs.PauseOnError = pauseOnError; } } @@ -115,12 +114,12 @@ private void ToggleLogWindow() private void OpenPackageEditor() { List list = new List(); - FloatMenuOption item = new FloatMenuOption("SoundDefs", delegate + FloatMenuOption item = new FloatMenuOption("SoundDefs", (Action)delegate { Find.WindowStack.Add(new EditWindow_PackageEditor("SoundDefs")); }, MenuOptionPriority.Default, null, null, 0f, null, null); list.Add(item); - item = new FloatMenuOption("HairDefs", delegate + item = new FloatMenuOption("HairDefs", (Action)delegate { Find.WindowStack.Add(new EditWindow_PackageEditor("HairDefs")); }, MenuOptionPriority.Default, null, null, 0f, null, null); diff --git a/Assembly-CSharp/Verse/DeepProfiler.cs b/Assembly-CSharp/Verse/DeepProfiler.cs index 20d6d188d..1ee16e6f6 100644 --- a/Assembly-CSharp/Verse/DeepProfiler.cs +++ b/Assembly-CSharp/Verse/DeepProfiler.cs @@ -1,4 +1,3 @@ -using System; using System.Collections.Generic; using System.Threading; @@ -13,41 +12,42 @@ public static class DeepProfiler public static ThreadLocalDeepProfiler Get() { object deepProfilersLock = DeepProfiler.DeepProfilersLock; - ThreadLocalDeepProfiler result; - lock (deepProfilersLock) + Monitor.Enter(deepProfilersLock); + try { int managedThreadId = Thread.CurrentThread.ManagedThreadId; - ThreadLocalDeepProfiler threadLocalDeepProfiler; + ThreadLocalDeepProfiler threadLocalDeepProfiler = default(ThreadLocalDeepProfiler); if (!DeepProfiler.deepProfilers.TryGetValue(managedThreadId, out threadLocalDeepProfiler)) { threadLocalDeepProfiler = new ThreadLocalDeepProfiler(); DeepProfiler.deepProfilers.Add(managedThreadId, threadLocalDeepProfiler); - result = threadLocalDeepProfiler; - } - else - { - result = threadLocalDeepProfiler; + return threadLocalDeepProfiler; } + return threadLocalDeepProfiler; + IL_0049: + ThreadLocalDeepProfiler result; + return result; + } + finally + { + Monitor.Exit(deepProfilersLock); } - return result; } public static void Start(string label = null) { - if (!Prefs.LogVerbose) + if (Prefs.LogVerbose) { - return; + DeepProfiler.Get().Start(label); } - DeepProfiler.Get().Start(label); } public static void End() { - if (!Prefs.LogVerbose) + if (Prefs.LogVerbose) { - return; + DeepProfiler.Get().End(); } - DeepProfiler.Get().End(); } } } diff --git a/Assembly-CSharp/Verse/DeepResourceGrid.cs b/Assembly-CSharp/Verse/DeepResourceGrid.cs index 41b9fa56f..4729842a8 100644 --- a/Assembly-CSharp/Verse/DeepResourceGrid.cs +++ b/Assembly-CSharp/Verse/DeepResourceGrid.cs @@ -26,7 +26,10 @@ public DeepResourceGrid(Map map) this.map = map; this.defGrid = new ushort[map.cellIndices.NumGridCells]; this.countGrid = new ushort[map.cellIndices.NumGridCells]; - this.drawer = new CellBoolDrawer(this, map.Size.x, map.Size.z, 1f); + IntVec3 size = map.Size; + int x = size.x; + IntVec3 size2 = map.Size; + this.drawer = new CellBoolDrawer(this, x, size2.z, 1f); } public void ExposeData() @@ -35,19 +38,21 @@ public void ExposeData() string compressedString2 = string.Empty; if (Scribe.mode == LoadSaveMode.Saving) { - compressedString = GridSaveUtility.CompressedStringForShortGrid((IntVec3 c) => this.defGrid[this.map.cellIndices.CellToIndex(c)], this.map); - compressedString2 = GridSaveUtility.CompressedStringForShortGrid((IntVec3 c) => this.countGrid[this.map.cellIndices.CellToIndex(c)], this.map); + compressedString = GridSaveUtility.CompressedStringForShortGrid((Func)((IntVec3 c) => this.defGrid[this.map.cellIndices.CellToIndex(c)]), this.map); + compressedString2 = GridSaveUtility.CompressedStringForShortGrid((Func)((IntVec3 c) => this.countGrid[this.map.cellIndices.CellToIndex(c)]), this.map); } - Scribe_Values.Look(ref compressedString, "defGrid", null, false); - Scribe_Values.Look(ref compressedString2, "countGrid", null, false); + Scribe_Values.Look(ref compressedString, "defGrid", (string)null, false); + Scribe_Values.Look(ref compressedString2, "countGrid", (string)null, false); if (Scribe.mode == LoadSaveMode.LoadingVars) { - foreach (GridSaveUtility.LoadedGridShort current in GridSaveUtility.LoadedUShortGrid(compressedString, this.map)) + foreach (GridSaveUtility.LoadedGridShort item in GridSaveUtility.LoadedUShortGrid(compressedString, this.map)) { + GridSaveUtility.LoadedGridShort current = item; this.defGrid[this.map.cellIndices.CellToIndex(current.cell)] = current.val; } - foreach (GridSaveUtility.LoadedGridShort current2 in GridSaveUtility.LoadedUShortGrid(compressedString2, this.map)) + foreach (GridSaveUtility.LoadedGridShort item2 in GridSaveUtility.LoadedUShortGrid(compressedString2, this.map)) { + GridSaveUtility.LoadedGridShort current2 = item2; this.countGrid[this.map.cellIndices.CellToIndex(current2.cell)] = current2.val; } } @@ -60,7 +65,7 @@ public ThingDef ThingDefAt(IntVec3 c) public int CountAt(IntVec3 c) { - return (int)this.countGrid[this.map.cellIndices.CellToIndex(c)]; + return this.countGrid[this.map.cellIndices.CellToIndex(c)]; } public void SetAt(IntVec3 c, ThingDef def, int count) @@ -69,31 +74,21 @@ public void SetAt(IntVec3 c, ThingDef def, int count) { def = null; } - ushort num; - if (def == null) - { - num = 0; - } - else - { - num = def.shortHash; - } + ushort num = (ushort)((def != null) ? def.shortHash : 0); ushort num2 = (ushort)count; if (count > 65535) { Log.Error("Cannot store count " + count + " in DeepResourceGrid: out of ushort range."); - num2 = 65535; + num2 = (ushort)65535; } if (count < 0) { Log.Error("Cannot store count " + count + " in DeepResourceGrid: out of ushort range."); - num2 = 0; + num2 = (ushort)0; } int num3 = this.map.cellIndices.CellToIndex(c); if (this.defGrid[num3] == num && this.countGrid[num3] == num2) - { return; - } this.defGrid[num3] = num; this.countGrid[num3] = num2; this.drawer.SetDirty(); @@ -126,8 +121,8 @@ public Color GetCellExtraColor(int index) IntVec3 c = this.map.cellIndices.IndexToCell(index); int num = this.CountAt(c); ThingDef thingDef = this.ThingDefAt(c); - float num2 = (float)num / (float)thingDef.deepCountPerCell / 2f; - int num3 = Mathf.RoundToInt(num2 * 100f); + float num2 = (float)((float)num / (float)thingDef.deepCountPerCell / 2.0); + int num3 = Mathf.RoundToInt((float)(num2 * 100.0)); num3 %= 100; return DebugMatsSpectrum.Mat(num3, true).color; } diff --git a/Assembly-CSharp/Verse/Def.cs b/Assembly-CSharp/Verse/Def.cs index 6e63c170c..ae532f8d9 100644 --- a/Assembly-CSharp/Verse/Def.cs +++ b/Assembly-CSharp/Verse/Def.cs @@ -1,7 +1,5 @@ using RimWorld; -using System; using System.Collections.Generic; -using System.Diagnostics; using System.Text.RegularExpressions; namespace Verse @@ -10,23 +8,27 @@ public class Def : Editable { public const string DefaultDefName = "UnnamedDef"; - [Description("The name of this Def. It is used as an identifier by the game code."), NoTranslate] + [Description("The name of this Def. It is used as an identifier by the game code.")] + [NoTranslate] public string defName = "UnnamedDef"; - [DefaultValue(null), Description("A human-readable label used to identify this in game.")] + [DefaultValue(null)] + [Description("A human-readable label used to identify this in game.")] public string label; - [DefaultValue(null), Description("A human-readable description given when the Def is inspected by players.")] + [Description("A human-readable description given when the Def is inspected by players.")] + [DefaultValue(null)] public string description; - [DefaultValue(null), Description("Mod-specific data. Not used by core game code.")] + [Description("Mod-specific data. Not used by core game code.")] + [DefaultValue(null)] public List modExtensions; [Unsaved] public ushort shortHash; [Unsaved] - public ushort index = 65535; + public ushort index = (ushort)65535; [Unsaved] private string cachedLabelCap; @@ -42,7 +44,7 @@ public string LabelCap { if (this.label.NullOrEmpty()) { - return null; + return (string)null; } if (this.cachedLabelCap.NullOrEmpty()) { @@ -52,28 +54,30 @@ public string LabelCap } } - [DebuggerHidden] public virtual IEnumerable SpecialDisplayStats() { - Def.c__Iterator8A c__Iterator8A = new Def.c__Iterator8A(); - Def.c__Iterator8A expr_07 = c__Iterator8A; - expr_07.$PC = -2; - return expr_07; + yield break; } - [DebuggerHidden] public override IEnumerable ConfigErrors() { - Def.c__Iterator8B c__Iterator8B = new Def.c__Iterator8B(); - c__Iterator8B.<>f__this = this; - Def.c__Iterator8B expr_0E = c__Iterator8B; - expr_0E.$PC = -2; - return expr_0E; + if (this.defName == "UnnamedDef") + { + yield return base.GetType() + " lacks defName. Label=" + this.label; + } + if (this.defName == "null") + { + yield return "defName cannot be the string 'null'."; + } + if (!Def.AllowedDefnamesRegex.IsMatch(this.defName)) + { + yield return "defName " + this.defName + " should only contain letters, numbers, underscores, or dashes."; + } } public virtual void ClearCachedData() { - this.cachedLabelCap = null; + this.cachedLabelCap = (string)null; } public override string ToString() @@ -90,16 +94,16 @@ public T GetModExtension() where T : DefModExtension { if (this.modExtensions == null) { - return (T)((object)null); + return (T)null; } for (int i = 0; i < this.modExtensions.Count; i++) { if (this.modExtensions[i] is T) { - return this.modExtensions[i] as T; + return (T)(this.modExtensions[i] as T); } } - return (T)((object)null); + return (T)null; } public bool HasModExtension() where T : DefModExtension diff --git a/Assembly-CSharp/Verse/DefDatabase.cs b/Assembly-CSharp/Verse/DefDatabase.cs index 55c4048e2..0cdc32620 100644 --- a/Assembly-CSharp/Verse/DefDatabase.cs +++ b/Assembly-CSharp/Verse/DefDatabase.cs @@ -38,49 +38,31 @@ public static int DefCount public static void AddAllInMods() { HashSet hashSet = new HashSet(); - foreach (ModContentPack current in from m in LoadedModManager.RunningMods + foreach (ModContentPack item in (IEnumerable)(from m in LoadedModManager.RunningMods orderby m.OverwritePriority - select m) + select m)) { hashSet.Clear(); - foreach (T current2 in GenDefDatabase.DefsToGoInDatabase(current)) + foreach (T item2 in GenDefDatabase.DefsToGoInDatabase(item)) { - if (hashSet.Contains(current2.defName)) + if (hashSet.Contains(((Def)(object)item2).defName)) { - Log.Error(string.Concat(new object[] - { - "Mod ", - current, - " has multiple ", - typeof(T), - "s named ", - current2.defName, - ". Skipping." - })); + Log.Error("Mod " + item + " has multiple " + typeof(T) + "s named " + ((Def)(object)item2).defName + ". Skipping."); } else { - if (current2.defName == "UnnamedDef") + if (((Def)(object)item2).defName == "UnnamedDef") { string text = "Unnamed" + typeof(T).Name + Rand.Range(1, 100000).ToString() + "A"; - Log.Error(string.Concat(new string[] - { - typeof(T).Name, - " in ", - current.ToString(), - " with label ", - current2.label, - " lacks a defName. Giving name ", - text - })); - current2.defName = text; + Log.Error(typeof(T).Name + " in " + item.ToString() + " with label " + ((Def)(object)item2).label + " lacks a defName. Giving name " + text); + ((Def)(object)item2).defName = text; } - T def; - if (DefDatabase.defsByName.TryGetValue(current2.defName, out def)) + T def = default(T); + if (DefDatabase.defsByName.TryGetValue(((Def)(object)item2).defName, out def)) { DefDatabase.Remove(def); } - DefDatabase.Add(current2); + DefDatabase.Add(item2); } } } @@ -88,44 +70,32 @@ orderby m.OverwritePriority public static void Add(IEnumerable defs) { - foreach (T current in defs) + foreach (T item in defs) { - DefDatabase.Add(current); + DefDatabase.Add(item); } } public static void Add(T def) { - while (DefDatabase.defsByName.ContainsKey(def.defName)) + while (DefDatabase.defsByName.ContainsKey(((Def)(object)def).defName)) { - Log.Error(string.Concat(new object[] - { - "Adding duplicate ", - typeof(T), - " name: ", - def.defName - })); - T expr_46 = def; - expr_46.defName += Mathf.RoundToInt(Rand.Value * 1000f); + Log.Error("Adding duplicate " + typeof(T) + " name: " + ((Def)(object)def).defName); + object obj = def; + ((Def)obj).defName = ((Def)obj).defName + Mathf.RoundToInt((float)(Rand.Value * 1000.0)); } DefDatabase.defsList.Add(def); - DefDatabase.defsByName.Add(def.defName, def); + DefDatabase.defsByName.Add(((Def)(object)def).defName, def); if (DefDatabase.defsList.Count > 65535) { - Log.Error(string.Concat(new object[] - { - "Too many ", - typeof(T), - "; over ", - 65535 - })); + Log.Error("Too many " + typeof(T) + "; over " + (ushort)65535); } - def.index = (ushort)(DefDatabase.defsList.Count - 1); + ((Def)(object)def).index = (ushort)(DefDatabase.defsList.Count - 1); } private static void Remove(T def) { - DefDatabase.defsByName.Remove(def.defName); + DefDatabase.defsByName.Remove(((Def)(object)def).defName); DefDatabase.defsList.Remove(def); DefDatabase.SetIndices(); } @@ -140,8 +110,8 @@ public static void ClearCachedData() { for (int i = 0; i < DefDatabase.defsList.Count; i++) { - T t = DefDatabase.defsList[i]; - t.ClearCachedData(); + T val = DefDatabase.defsList[i]; + val.ClearCachedData(); } } @@ -152,18 +122,12 @@ public static void ResolveAllReferences() { try { - T t = DefDatabase.defsList[i]; - t.ResolveReferences(); + T val = DefDatabase.defsList[i]; + val.ResolveReferences(); } catch (Exception ex) { - Log.Error(string.Concat(new object[] - { - "Error while resolving references for def ", - DefDatabase.defsList[i], - ": ", - ex - })); + Log.Error("Error while resolving references for def " + DefDatabase.defsList[i] + ": " + ex); } } DefDatabase.SetIndices(); @@ -173,23 +137,18 @@ private static void SetIndices() { for (int i = 0; i < DefDatabase.defsList.Count; i++) { - DefDatabase.defsList[i].index = (ushort)i; + ((Def)(object)DefDatabase.defsList[i]).index = (ushort)i; } } public static void ErrorCheckAllDefs() { - foreach (T current in DefDatabase.AllDefs) + foreach (T allDef in DefDatabase.AllDefs) { - foreach (string current2 in current.ConfigErrors()) + T current = allDef; + foreach (string item in current.ConfigErrors()) { - Log.Warning(string.Concat(new object[] - { - "Config error in ", - current, - ": ", - current2 - })); + Log.Warning("Config error in " + current + ": " + item); } } } @@ -198,32 +157,20 @@ public static T GetNamed(string defName, bool errorOnFail = true) { if (errorOnFail) { - T result; + T result = default(T); if (DefDatabase.defsByName.TryGetValue(defName, out result)) { return result; } - Log.Error(string.Concat(new object[] - { - "Failed to find ", - typeof(T), - " named ", - defName, - ". There are ", - DefDatabase.defsList.Count, - " defs of this type loaded." - })); - return (T)((object)null); + Log.Error("Failed to find " + typeof(T) + " named " + defName + ". There are " + DefDatabase.defsList.Count + " defs of this type loaded."); + return (T)null; } - else + T result2 = default(T); + if (DefDatabase.defsByName.TryGetValue(defName, out result2)) { - T result2; - if (DefDatabase.defsByName.TryGetValue(defName, out result2)) - { - return result2; - } - return (T)((object)null); + return result2; } + return (T)null; } public static T GetNamedSilentFail(string defName) @@ -235,17 +182,17 @@ public static T GetByShortHash(ushort shortHash) { for (int i = 0; i < DefDatabase.defsList.Count; i++) { - if (DefDatabase.defsList[i].shortHash == shortHash) + if (((Def)(object)DefDatabase.defsList[i]).shortHash == shortHash) { return DefDatabase.defsList[i]; } } - return (T)((object)null); + return (T)null; } public static T GetRandom() { - return DefDatabase.defsList.RandomElement(); + return ((IEnumerable)DefDatabase.defsList).RandomElement(); } } } diff --git a/Assembly-CSharp/Verse/DefInjectionPackage.cs b/Assembly-CSharp/Verse/DefInjectionPackage.cs index e368a5b36..b4663c875 100644 --- a/Assembly-CSharp/Verse/DefInjectionPackage.cs +++ b/Assembly-CSharp/Verse/DefInjectionPackage.cs @@ -1,6 +1,6 @@ using System; +using System.Collections; using System.Collections.Generic; -using System.Diagnostics; using System.IO; using System.Linq; using System.Reflection; @@ -40,60 +40,44 @@ public void AddDataFromFile(FileInfo file) try { XDocument xDocument = XDocument.Load(file.FullName); - foreach (XElement current in xDocument.Root.Elements()) + foreach (XElement item in xDocument.Root.Elements()) { - if (current.Name == "rep") + if (item.Name == "rep") { - string key = this.ProcessedPath(current.Elements("path").First().Value); - string translation = this.ProcessedTranslation(current.Elements("trans").First().Value); + string key = this.ProcessedPath(item.Elements("path").First().Value); + string translation = this.ProcessedTranslation(item.Elements("trans").First().Value); this.TryAddInjection(file, key, translation); } else { - string key2 = this.ProcessedPath(current.Name.ToString()); - string translation2 = this.ProcessedTranslation(current.Value); + string key2 = this.ProcessedPath(item.Name.ToString()); + string translation2 = this.ProcessedTranslation(item.Value); this.TryAddInjection(file, key2, translation2); } } } catch (Exception ex) { - Log.Warning(string.Concat(new object[] - { - "Exception loading translation data from file ", - file, - ": ", - ex - })); + Log.Warning("Exception loading translation data from file " + file + ": " + ex); } } private void TryAddInjection(FileInfo file, string key, string translation) { - string[] array = key.Split(new char[] - { - '.' - }); + string[] array = key.Split('.'); array[0] = BackCompatibility.BackCompatibleDefName(this.defType, array[0]); key = string.Join(".", array); - if (this.HasError(file, key)) + if (!this.HasError(file, key)) { - return; + this.injections.Add(key, translation); } - this.injections.Add(key, translation); } private bool HasError(FileInfo file, string key) { if (!key.Contains('.')) { - Log.Warning(string.Concat(new object[] - { - "Error loading DefInjection from file ", - file, - ": Key lacks a dot: ", - key - })); + Log.Warning("Error loading DefInjection from file " + file + ": Key lacks a dot: " + key); return true; } if (this.injections.ContainsKey(key)) @@ -106,34 +90,30 @@ private bool HasError(FileInfo file, string key) public void InjectIntoDefs() { - foreach (KeyValuePair current in this.injections) + Dictionary.Enumerator enumerator = this.injections.GetEnumerator(); + try { - string[] array = current.Key.Split(new char[] - { - '.' - }); - string text = array[0]; - text = BackCompatibility.BackCompatibleDefName(this.defType, text); - if (GenGeneric.InvokeStaticMethodOnGenericType(typeof(DefDatabase<>), this.defType, "GetNamedSilentFail", new object[] - { - text - }) == null) + while (enumerator.MoveNext()) { - Log.Warning(string.Concat(new object[] + KeyValuePair current = enumerator.Current; + string[] array = current.Key.Split('.'); + string defName = array[0]; + defName = BackCompatibility.BackCompatibleDefName(this.defType, defName); + object obj = GenGeneric.InvokeStaticMethodOnGenericType(typeof(DefDatabase<>), this.defType, "GetNamedSilentFail", defName); + if (obj == null) { - "Def-linked translation error: Found no ", - this.defType, - " named ", - text, - " to match ", - current.Key - })); - } - else - { - this.SetDefFieldAtPath(this.defType, current.Key, current.Value); + Log.Warning("Def-linked translation error: Found no " + this.defType + " named " + defName + " to match " + current.Key); + } + else + { + this.SetDefFieldAtPath(this.defType, current.Key, current.Value); + } } } + finally + { + ((IDisposable)(object)enumerator).Dispose(); + } GenGeneric.InvokeStaticMethodOnGenericType(typeof(DefDatabase<>), this.defType, "ClearCachedData"); } @@ -142,34 +122,22 @@ private void SetDefFieldAtPath(Type defType, string path, string value) path = BackCompatibility.BackCompatibleModifiedTranslationPath(defType, path); try { - List list = path.Split(new char[] - { - '.' - }).ToList(); - object obj = GenGeneric.InvokeStaticMethodOnGenericType(typeof(DefDatabase<>), defType, "GetNamedSilentFail", new object[] - { - list[0] - }); + List list = path.Split('.').ToList(); + object obj = GenGeneric.InvokeStaticMethodOnGenericType(typeof(DefDatabase<>), defType, "GetNamedSilentFail", list[0]); if (obj == null) { throw new InvalidOperationException("Def named " + list[0] + " not found."); } list.RemoveAt(0); - DefInjectionPathPartKind defInjectionPathPartKind; - string text; - int num; while (true) { - defInjectionPathPartKind = DefInjectionPathPartKind.Field; - text = list[0]; - num = -1; + DefInjectionPathPartKind defInjectionPathPartKind = DefInjectionPathPartKind.Field; + string text = list[0]; + int num = -1; if (text.Contains('[')) { defInjectionPathPartKind = DefInjectionPathPartKind.FieldWithListIndex; - string[] array = text.Split(new char[] - { - '[' - }); + string[] array = text.Split('['); string text2 = array[1]; text2 = text2.Substring(0, text2.Length - 1); num = (int)ParseHelper.FromString(text2, typeof(int)); @@ -181,161 +149,111 @@ private void SetDefFieldAtPath(Type defType, string path, string value) } if (list.Count == 1) { - break; - } - if (defInjectionPathPartKind == DefInjectionPathPartKind.ListIndex) - { - PropertyInfo property = obj.GetType().GetProperty("Item"); - if (property == null) + object obj2; + switch (defInjectionPathPartKind) { - goto Block_17; - } - obj = property.GetValue(obj, new object[] + case DefInjectionPathPartKind.Field: { - num - }); - } - else - { - FieldInfo field = obj.GetType().GetField(text, BindingFlags.IgnoreCase | BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic); - if (field == null) + FieldInfo fieldNamed = this.GetFieldNamed(obj.GetType(), text); + if (fieldNamed == null) + { + throw new InvalidOperationException("Field " + text + " does not exist in type " + obj.GetType() + "."); + } + if (fieldNamed.HasAttribute()) + { + Log.Error("Translated untranslateable field " + fieldNamed.Name + " of type " + fieldNamed.FieldType + " at path " + path + ". Translating this field will break the game."); + } + else if (fieldNamed.FieldType != typeof(string)) + { + Log.Error("Translated non-string field " + fieldNamed.Name + " of type " + fieldNamed.FieldType + " at path " + path + ". Only string fields should be translated."); + } + else + { + fieldNamed.SetValue(obj, value); + } + return; + } + case DefInjectionPathPartKind.FieldWithListIndex: { - goto Block_18; + FieldInfo field = obj.GetType().GetField(text, BindingFlags.IgnoreCase | BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic); + if (field == null) + { + throw new InvalidOperationException("Field " + text + " does not exist."); + } + obj2 = field.GetValue(obj); + break; } - if (defInjectionPathPartKind == DefInjectionPathPartKind.Field) + default: { - obj = field.GetValue(obj); + obj2 = obj; + break; } - else + } + Type type = obj2.GetType(); + PropertyInfo property = type.GetProperty("Count"); + if (property == null) { - object value2 = field.GetValue(obj); - PropertyInfo property2 = value2.GetType().GetProperty("Item"); - if (property2 == null) - { - goto Block_20; - } - obj = property2.GetValue(value2, new object[] - { - num - }); + throw new InvalidOperationException("Tried to use index on non-list (missing 'Count' property)."); } - } - list.RemoveAt(0); - } - if (defInjectionPathPartKind == DefInjectionPathPartKind.Field) - { - FieldInfo fieldNamed = this.GetFieldNamed(obj.GetType(), text); - if (fieldNamed == null) - { - throw new InvalidOperationException(string.Concat(new object[] + int num2 = (int)property.GetValue(obj2, null); + if (num >= num2) { - "Field ", - text, - " does not exist in type ", - obj.GetType(), - "." - })); - } - if (fieldNamed.HasAttribute()) - { - Log.Error(string.Concat(new object[] + throw new InvalidOperationException("Trying to translate " + defType + "." + path + " at index " + num + " but the original list only has " + num2 + " entries (so the max index is " + (num2 - 1).ToString() + ")."); + } + PropertyInfo property2 = type.GetProperty("Item"); + if (property2 == null) { - "Translated untranslateable field ", - fieldNamed.Name, - " of type ", - fieldNamed.FieldType, - " at path ", - path, - ". Translating this field will break the game." - })); - } - else if (fieldNamed.FieldType != typeof(string)) - { - Log.Error(string.Concat(new object[] + throw new InvalidOperationException("Tried to use index on non-list (missing 'Item' property)."); + } + property2.SetValue(obj2, value, new object[1] { - "Translated non-string field ", - fieldNamed.Name, - " of type ", - fieldNamed.FieldType, - " at path ", - path, - ". Only string fields should be translated." - })); - } - else - { - fieldNamed.SetValue(obj, value); + num + }); + return; } - } - else - { - object obj2; - if (defInjectionPathPartKind == DefInjectionPathPartKind.FieldWithListIndex) + if (defInjectionPathPartKind == DefInjectionPathPartKind.ListIndex) { - FieldInfo field2 = obj.GetType().GetField(text, BindingFlags.IgnoreCase | BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic); - if (field2 == null) + PropertyInfo property3 = obj.GetType().GetProperty("Item"); + if (property3 == null) { - throw new InvalidOperationException("Field " + text + " does not exist."); + throw new InvalidOperationException("Tried to use index on non-list (missing 'Item' property)."); } - obj2 = field2.GetValue(obj); + obj = property3.GetValue(obj, new object[1] + { + num + }); + goto IL_041b; } - else + FieldInfo field2 = obj.GetType().GetField(text, BindingFlags.IgnoreCase | BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic); + if (field2 == null) { - obj2 = obj; + throw new InvalidOperationException("Field " + text + " does not exist."); } - Type type = obj2.GetType(); - PropertyInfo property3 = type.GetProperty("Count"); - if (property3 == null) + if (defInjectionPathPartKind == DefInjectionPathPartKind.Field) { - throw new InvalidOperationException("Tried to use index on non-list (missing 'Count' property)."); + obj = field2.GetValue(obj); + goto IL_041b; } - int num2 = (int)property3.GetValue(obj2, null); - if (num >= num2) + object value2 = field2.GetValue(obj); + PropertyInfo property4 = value2.GetType().GetProperty("Item"); + if (property4 != null) { - throw new InvalidOperationException(string.Concat(new object[] + obj = property4.GetValue(value2, new object[1] { - "Trying to translate ", - defType, - ".", - path, - " at index ", - num, - " but the original list only has ", - num2, - " entries (so the max index is ", - (num2 - 1).ToString(), - ")." - })); - } - PropertyInfo property4 = type.GetProperty("Item"); - if (property4 == null) - { - throw new InvalidOperationException("Tried to use index on non-list (missing 'Item' property)."); + num + }); + goto IL_041b; } - property4.SetValue(obj2, value, new object[] - { - num - }); + break; + IL_041b: + list.RemoveAt(0); } - return; - Block_17: - throw new InvalidOperationException("Tried to use index on non-list (missing 'Item' property)."); - Block_18: - throw new InvalidOperationException("Field " + text + " does not exist."); - Block_20: throw new InvalidOperationException("Tried to use index on non-list (missing 'Item' property)."); + IL_0427:; } catch (Exception ex) { - Log.Warning(string.Concat(new object[] - { - "Def-linked translation error: Exception getting field at path ", - path, - " in ", - defType, - ": ", - ex.ToString() - })); + Log.Warning("Def-linked translation error: Exception getting field at path " + path + " in " + defType + ": " + ex.ToString()); } } @@ -364,26 +282,56 @@ private FieldInfo GetFieldNamed(Type type, string name) return field; } - [DebuggerHidden] public IEnumerable MissingInjections() { - DefInjectionPackage.c__Iterator1EF c__Iterator1EF = new DefInjectionPackage.c__Iterator1EF(); - c__Iterator1EF.<>f__this = this; - DefInjectionPackage.c__Iterator1EF expr_0E = c__Iterator1EF; - expr_0E.$PC = -2; - return expr_0E; + Type databaseType = typeof(DefDatabase<>).MakeGenericType(this.defType); + PropertyInfo allDefsProperty = databaseType.GetProperty("AllDefs"); + MethodInfo allDefsMethod = allDefsProperty.GetGetMethod(); + IEnumerable allDefsEnum = (IEnumerable)allDefsMethod.Invoke(null, null); + foreach (Def item in allDefsEnum) + { + foreach (string item2 in this.MissingInjectionsFromDef(item)) + { + yield return item2; + } + } } - [DebuggerHidden] private IEnumerable MissingInjectionsFromDef(Def def) { - DefInjectionPackage.c__Iterator1F0 c__Iterator1F = new DefInjectionPackage.c__Iterator1F0(); - c__Iterator1F.def = def; - c__Iterator1F.<$>def = def; - c__Iterator1F.<>f__this = this; - DefInjectionPackage.c__Iterator1F0 expr_1C = c__Iterator1F; - expr_1C.$PC = -2; - return expr_1C; + if (!def.label.NullOrEmpty()) + { + string path3 = def.defName + ".label"; + if (!this.injections.ContainsKey(path3)) + { + yield return path3 + " '" + def.label + "'"; + } + } + if (!def.description.NullOrEmpty()) + { + string path2 = def.defName + ".description"; + if (!this.injections.ContainsKey(path2)) + { + yield return path2 + " '" + def.description + "'"; + } + } + FieldInfo[] fields = def.GetType().GetFields(); + for (int i = 0; i < fields.Length; i++) + { + FieldInfo fi = fields[i]; + if (fi.FieldType == typeof(string)) + { + string val = (string)fi.GetValue(def); + if (!val.NullOrEmpty() && !(fi.Name == "defName") && !(fi.Name == "label") && !(fi.Name == "description") && !fi.HasAttribute() && !fi.HasAttribute() && (fi.HasAttribute() || (val != null && val.Contains(' ')))) + { + string path = def.defName + "." + fi.Name; + if (!this.injections.ContainsKey(path)) + { + yield return path + " '" + val + "'"; + } + } + } + } } } } diff --git a/Assembly-CSharp/Verse/DefInjectionPathPartKind.cs b/Assembly-CSharp/Verse/DefInjectionPathPartKind.cs index c5c4554cd..3867c1179 100644 --- a/Assembly-CSharp/Verse/DefInjectionPathPartKind.cs +++ b/Assembly-CSharp/Verse/DefInjectionPathPartKind.cs @@ -1,11 +1,9 @@ -using System; - namespace Verse { internal enum DefInjectionPathPartKind { - Field, - FieldWithListIndex, - ListIndex + Field = 0, + FieldWithListIndex = 1, + ListIndex = 2 } } diff --git a/Assembly-CSharp/Verse/DefMap.cs b/Assembly-CSharp/Verse/DefMap.cs index 11cb5f9fe..eaba6aab0 100644 --- a/Assembly-CSharp/Verse/DefMap.cs +++ b/Assembly-CSharp/Verse/DefMap.cs @@ -19,11 +19,11 @@ public V this[D def] { get { - return this.values[(int)def.index]; + return this.values[((Def)(object)def).index]; } set { - this.values[(int)def.index] = value; + this.values[((Def)(object)def).index] = value; } } @@ -44,19 +44,12 @@ public DefMap() int defCount = DefDatabase.DefCount; if (defCount == 0) { - throw new Exception(string.Concat(new object[] - { - "Constructed DefMap<", - typeof(D), - ", ", - typeof(V), - "> without defs being initialized. Try constructing it in ResolveReferences instead of the constructor." - })); + throw new Exception("Constructed DefMap<" + typeof(D) + ", " + typeof(V) + "> without defs being initialized. Try constructing it in ResolveReferences instead of the constructor."); } this.values = new List(defCount); - for (int i = 0; i < defCount; i++) + for (int num = 0; num < defCount; num++) { - this.values.Add((default(V) == null) ? Activator.CreateInstance() : default(V)); + this.values.Add(new V()); } } diff --git a/Assembly-CSharp/Verse/DefModExtension.cs b/Assembly-CSharp/Verse/DefModExtension.cs index f117a8c75..202736bb7 100644 --- a/Assembly-CSharp/Verse/DefModExtension.cs +++ b/Assembly-CSharp/Verse/DefModExtension.cs @@ -1,5 +1,3 @@ -using System; - namespace Verse { public abstract class DefModExtension diff --git a/Assembly-CSharp/Verse/DefPackage.cs b/Assembly-CSharp/Verse/DefPackage.cs index bbe3e88d5..aab805605 100644 --- a/Assembly-CSharp/Verse/DefPackage.cs +++ b/Assembly-CSharp/Verse/DefPackage.cs @@ -37,14 +37,7 @@ public void RemoveDef(Def def) } if (!this.defs.Contains(def)) { - throw new InvalidOperationException(string.Concat(new object[] - { - "Package ", - this, - " cannot remove ", - def, - " because it doesn't contain it." - })); + throw new InvalidOperationException("Package " + this + " cannot remove " + def + " because it doesn't contain it."); } this.defs.Remove(def); } @@ -58,10 +51,19 @@ public void SaveIn(ModContentPack mod) xDocument.Add(xElement); try { - foreach (Def current in this.defs) + List.Enumerator enumerator = this.defs.GetEnumerator(); + try + { + while (enumerator.MoveNext()) + { + Def current = enumerator.Current; + XElement content = DirectXmlSaver.XElementFromObject(current, current.GetType()); + xElement.Add(content); + } + } + finally { - XElement content = DirectXmlSaver.XElementFromObject(current, current.GetType()); - xElement.Add(content); + ((IDisposable)(object)enumerator).Dispose(); } DirectXmlSaveFormatter.AddWhitespaceFromRoot(xElement); SaveOptions options = SaveOptions.DisableFormatting; @@ -72,6 +74,7 @@ public void SaveIn(ModContentPack mod) { Messages.Message("Exception saving XML: " + ex.ToString(), MessageSound.Negative); throw; + IL_00c6:; } } @@ -90,12 +93,13 @@ public static string UnusedPackageName(string relFolder, ModContentPack mod) string fullPath = Path.GetFullPath(Path.Combine(Path.Combine(mod.RootDir, "Defs/"), relFolder)); int num = 1; string text; - do + while (true) { text = "NewPackage" + num.ToString() + ".xml"; num++; + if (!File.Exists(Path.Combine(fullPath, text))) + break; } - while (File.Exists(Path.Combine(fullPath, text))); return text; } } diff --git a/Assembly-CSharp/Verse/DefaultEmptyListAttribute.cs b/Assembly-CSharp/Verse/DefaultEmptyListAttribute.cs index 0455450ef..54e565286 100644 --- a/Assembly-CSharp/Verse/DefaultEmptyListAttribute.cs +++ b/Assembly-CSharp/Verse/DefaultEmptyListAttribute.cs @@ -21,12 +21,15 @@ public override bool ObjIsDefault(object obj) return false; } Type[] genericArguments = obj.GetType().GetGenericArguments(); - if (genericArguments.Length != 1 || genericArguments[0] != (Type)this.value) + if (genericArguments.Length == 1 && genericArguments[0] == (Type)base.value) { - return false; + if ((int)obj.GetType().GetProperty("Count").GetValue(obj, null) != 0) + { + return false; + } + return true; } - int num = (int)obj.GetType().GetProperty("Count").GetValue(obj, null); - return num == 0; + return false; } } } diff --git a/Assembly-CSharp/Verse/DefaultValueAttribute.cs b/Assembly-CSharp/Verse/DefaultValueAttribute.cs index 31c162521..311cc3066 100644 --- a/Assembly-CSharp/Verse/DefaultValueAttribute.cs +++ b/Assembly-CSharp/Verse/DefaultValueAttribute.cs @@ -18,7 +18,11 @@ public virtual bool ObjIsDefault(object obj) { return this.value == null; } - return this.value != null && this.value.Equals(obj); + if (this.value == null) + { + return false; + } + return this.value.Equals(obj); } } } diff --git a/Assembly-CSharp/Verse/DelayedErrorWindowRequest.cs b/Assembly-CSharp/Verse/DelayedErrorWindowRequest.cs index a747c775a..915d9c2fa 100644 --- a/Assembly-CSharp/Verse/DelayedErrorWindowRequest.cs +++ b/Assembly-CSharp/Verse/DelayedErrorWindowRequest.cs @@ -1,4 +1,3 @@ -using System; using System.Collections.Generic; namespace Verse @@ -12,7 +11,7 @@ private struct Request public string title; } - private static List requests = new List(); + private static List requests = new List(); public static void DelayedErrorWindowRequestOnGUI() { @@ -20,9 +19,11 @@ public static void DelayedErrorWindowRequestOnGUI() { for (int i = 0; i < DelayedErrorWindowRequest.requests.Count; i++) { - WindowStack arg_47_0 = Find.WindowStack; - string title = DelayedErrorWindowRequest.requests[i].title; - arg_47_0.Add(new Dialog_MessageBox(DelayedErrorWindowRequest.requests[i].text, "OK".Translate(), null, null, null, title, false)); + WindowStack windowStack = Find.WindowStack; + Request request = DelayedErrorWindowRequest.requests[i]; + string title = request.title; + Request request2 = DelayedErrorWindowRequest.requests[i]; + windowStack.Add(new Dialog_MessageBox(request2.text, "OK".Translate(), null, (string)null, null, title, false)); } } finally @@ -33,9 +34,11 @@ public static void DelayedErrorWindowRequestOnGUI() public static void Add(string text, string title = null) { - DelayedErrorWindowRequest.Request item = default(DelayedErrorWindowRequest.Request); - item.text = text; - item.title = title; + Request item = new Request + { + text = text, + title = title + }; DelayedErrorWindowRequest.requests.Add(item); } } diff --git a/Assembly-CSharp/Verse/Designation.cs b/Assembly-CSharp/Verse/Designation.cs index 84821395e..14997d14e 100644 --- a/Assembly-CSharp/Verse/Designation.cs +++ b/Assembly-CSharp/Verse/Designation.cs @@ -1,5 +1,4 @@ using RimWorld; -using System; using UnityEngine; namespace Verse @@ -70,9 +69,7 @@ internal void Notify_Removing() public virtual void DesignationDraw() { if (this.target.HasThing && !this.target.Thing.Spawned) - { return; - } Vector3 position = default(Vector3); if (this.target.HasThing) { @@ -93,14 +90,7 @@ public void Delete() public override string ToString() { - return string.Format(string.Concat(new object[] - { - "(", - this.def.defName, - " target=", - this.target, - ")" - }), new object[0]); + return string.Format("(" + this.def.defName + " target=" + this.target + ")"); } } } diff --git a/Assembly-CSharp/Verse/DesignationCategoryDef.cs b/Assembly-CSharp/Verse/DesignationCategoryDef.cs index 60048aa68..55a09bd09 100644 --- a/Assembly-CSharp/Verse/DesignationCategoryDef.cs +++ b/Assembly-CSharp/Verse/DesignationCategoryDef.cs @@ -26,11 +26,15 @@ public IEnumerable ResolvedAllowedDesignators { get { - DesignationCategoryDef.<>c__Iterator1CD <>c__Iterator1CD = new DesignationCategoryDef.<>c__Iterator1CD(); - <>c__Iterator1CD.<>f__this = this; - DesignationCategoryDef.<>c__Iterator1CD expr_0E = <>c__Iterator1CD; - expr_0E.$PC = -2; - return expr_0E; + GameRules rules = Current.Game.Rules; + for (int i = 0; i < this.resolvedDesignators.Count; i++) + { + Designator des = this.resolvedDesignators[i]; + if (rules.DesignatorAllowed(des)) + { + yield return des; + } + } } } @@ -45,46 +49,47 @@ public List AllResolvedDesignators public override void ResolveReferences() { base.ResolveReferences(); - LongEventHandler.ExecuteWhenFinished(delegate + LongEventHandler.ExecuteWhenFinished((Action)delegate { this.ResolveDesignators(); }); - this.cachedHighlightClosedTag = "DesignationCategoryButton-" + this.defName + "-Closed"; + this.cachedHighlightClosedTag = "DesignationCategoryButton-" + base.defName + "-Closed"; } private void ResolveDesignators() { this.resolvedDesignators.Clear(); - foreach (Type current in this.specialDesignatorClasses) + List.Enumerator enumerator = this.specialDesignatorClasses.GetEnumerator(); + try { - Designator designator = null; - try + while (enumerator.MoveNext()) { - designator = (Designator)Activator.CreateInstance(current); - } - catch (Exception ex) - { - Log.Error(string.Concat(new object[] + Type current = enumerator.Current; + Designator designator = null; + try { - "DesignationCategoryDef", - this.defName, - " could not instantiate special designator from class ", - current, - ".\n Exception: \n", - ex.ToString() - })); - } - if (designator != null) - { - this.resolvedDesignators.Add(designator); + designator = (Designator)Activator.CreateInstance(current); + } + catch (Exception ex) + { + Log.Error("DesignationCategoryDef" + base.defName + " could not instantiate special designator from class " + current + ".\n Exception: \n" + ex.ToString()); + } + if (designator != null) + { + this.resolvedDesignators.Add(designator); + } } } + finally + { + ((IDisposable)(object)enumerator).Dispose(); + } IEnumerable enumerable = from tDef in DefDatabase.AllDefs.Cast().Concat(DefDatabase.AllDefs.Cast()) where tDef.designationCategory == this select tDef; - foreach (BuildableDef current2 in enumerable) + foreach (BuildableDef item in enumerable) { - this.resolvedDesignators.Add(new Designator_Build(current2)); + this.resolvedDesignators.Add(new Designator_Build(item)); } } } diff --git a/Assembly-CSharp/Verse/DesignationDef.cs b/Assembly-CSharp/Verse/DesignationDef.cs index 8b27a53d0..292b7bd50 100644 --- a/Assembly-CSharp/Verse/DesignationDef.cs +++ b/Assembly-CSharp/Verse/DesignationDef.cs @@ -20,7 +20,7 @@ public class DesignationDef : Def public override void ResolveReferences() { base.ResolveReferences(); - LongEventHandler.ExecuteWhenFinished(delegate + LongEventHandler.ExecuteWhenFinished((Action)delegate { this.iconMat = MaterialPool.MatFrom(this.texturePath, ShaderDatabase.MetaOverlay); }); diff --git a/Assembly-CSharp/Verse/DesignationDragger.cs b/Assembly-CSharp/Verse/DesignationDragger.cs index a354634a3..0be857ee3 100644 --- a/Assembly-CSharp/Verse/DesignationDragger.cs +++ b/Assembly-CSharp/Verse/DesignationDragger.cs @@ -1,4 +1,3 @@ -using System; using System.Collections.Generic; using UnityEngine; using Verse.Sound; @@ -123,13 +122,15 @@ public void DraggerOnGUI() if (intVec.x >= 3) { Vector2 screenPos = (this.startDragCell.ToUIPosition() + UI.MouseCell().ToUIPosition()) / 2f; - screenPos.y = this.startDragCell.ToUIPosition().y; + Vector2 vector = this.startDragCell.ToUIPosition(); + screenPos.y = vector.y; this.DrawNumber(screenPos, intVec.x); } if (intVec.z >= 3) { Vector2 screenPos2 = (this.startDragCell.ToUIPosition() + UI.MouseCell().ToUIPosition()) / 2f; - screenPos2.x = this.startDragCell.ToUIPosition().x; + Vector2 vector2 = this.startDragCell.ToUIPosition(); + screenPos2.x = vector2.x; this.DrawNumber(screenPos2, intVec.z); } Text.Font = GameFont.Small; @@ -141,7 +142,7 @@ private void DrawNumber(Vector2 screenPos, int number) { Text.Anchor = TextAnchor.MiddleCenter; Text.Font = GameFont.Medium; - Rect rect = new Rect(screenPos.x - 20f, screenPos.y - 15f, 40f, 30f); + Rect rect = new Rect((float)(screenPos.x - 20.0), (float)(screenPos.y - 15.0), 40f, 30f); GUI.DrawTexture(rect, TexUI.GrayBg); rect.y += 3f; Widgets.Label(rect, number.ToStringCached()); @@ -149,88 +150,87 @@ private void DrawNumber(Vector2 screenPos, int number) private void UpdateDragCellsIfNeeded() { - if (Time.frameCount == this.lastUpdateFrame) + if (Time.frameCount != this.lastUpdateFrame) { - return; - } - this.lastUpdateFrame = Time.frameCount; - this.dragCells.Clear(); - this.failureReasonInt = null; - IntVec3 intVec = this.startDragCell; - IntVec3 intVec2 = UI.MouseCell(); - if (this.SelDes.DraggableDimensions == 1) - { - bool flag = true; - if (Mathf.Abs(intVec.x - intVec2.x) < Mathf.Abs(intVec.z - intVec2.z)) + this.lastUpdateFrame = Time.frameCount; + this.dragCells.Clear(); + this.failureReasonInt = (string)null; + IntVec3 intVec = this.startDragCell; + IntVec3 intVec2 = UI.MouseCell(); + if (this.SelDes.DraggableDimensions == 1) { - flag = false; - } - if (flag) - { - int z = intVec.z; - if (intVec.x > intVec2.x) + bool flag = true; + if (Mathf.Abs(intVec.x - intVec2.x) < Mathf.Abs(intVec.z - intVec2.z)) + { + flag = false; + } + if (flag) { - IntVec3 intVec3 = intVec; - intVec = intVec2; - intVec2 = intVec3; + int z = intVec.z; + if (intVec.x > intVec2.x) + { + IntVec3 intVec3 = intVec; + intVec = intVec2; + intVec2 = intVec3; + } + for (int i = intVec.x; i <= intVec2.x; i++) + { + this.TryAddDragCell(new IntVec3(i, intVec.y, z)); + } } - for (int i = intVec.x; i <= intVec2.x; i++) + else { - this.TryAddDragCell(new IntVec3(i, intVec.y, z)); + int x = intVec.x; + if (intVec.z > intVec2.z) + { + IntVec3 intVec4 = intVec; + intVec = intVec2; + intVec2 = intVec4; + } + for (int j = intVec.z; j <= intVec2.z; j++) + { + this.TryAddDragCell(new IntVec3(x, intVec.y, j)); + } } } - else + if (this.SelDes.DraggableDimensions == 2) { - int x = intVec.x; - if (intVec.z > intVec2.z) + IntVec3 intVec5 = intVec; + IntVec3 intVec6 = intVec2; + if (intVec6.x > intVec5.x + 50) { - IntVec3 intVec4 = intVec; - intVec = intVec2; - intVec2 = intVec4; + intVec6.x = intVec5.x + 50; } - for (int j = intVec.z; j <= intVec2.z; j++) + if (intVec6.z > intVec5.z + 50) { - this.TryAddDragCell(new IntVec3(x, intVec.y, j)); + intVec6.z = intVec5.z + 50; } - } - } - if (this.SelDes.DraggableDimensions == 2) - { - IntVec3 intVec5 = intVec; - IntVec3 intVec6 = intVec2; - if (intVec6.x > intVec5.x + 50) - { - intVec6.x = intVec5.x + 50; - } - if (intVec6.z > intVec5.z + 50) - { - intVec6.z = intVec5.z + 50; - } - if (intVec6.x < intVec5.x) - { - if (intVec6.x < intVec5.x - 50) + if (intVec6.x < intVec5.x) { - intVec6.x = intVec5.x - 50; + if (intVec6.x < intVec5.x - 50) + { + intVec6.x = intVec5.x - 50; + } + int x2 = intVec5.x; + intVec5 = new IntVec3(intVec6.x, intVec5.y, intVec5.z); + intVec6 = new IntVec3(x2, intVec6.y, intVec6.z); } - int x2 = intVec5.x; - intVec5 = new IntVec3(intVec6.x, intVec5.y, intVec5.z); - intVec6 = new IntVec3(x2, intVec6.y, intVec6.z); - } - if (intVec6.z < intVec5.z) - { - if (intVec6.z < intVec5.z - 50) + if (intVec6.z < intVec5.z) { - intVec6.z = intVec5.z - 50; + if (intVec6.z < intVec5.z - 50) + { + intVec6.z = intVec5.z - 50; + } + int z2 = intVec5.z; + intVec5 = new IntVec3(intVec5.x, intVec5.y, intVec6.z); + intVec6 = new IntVec3(intVec6.x, intVec6.y, z2); } - int z2 = intVec5.z; - intVec5 = new IntVec3(intVec5.x, intVec5.y, intVec6.z); - intVec6 = new IntVec3(intVec6.x, intVec6.y, z2); - } - for (int k = intVec5.x; k <= intVec6.x; k++) - { - for (int l = intVec5.z; l <= intVec6.z; l++) + for (int k = intVec5.x; k <= intVec6.x; k++) { - this.TryAddDragCell(new IntVec3(k, intVec5.y, l)); + for (int l = intVec5.z; l <= intVec6.z; l++) + { + this.TryAddDragCell(new IntVec3(k, intVec5.y, l)); + } } } } diff --git a/Assembly-CSharp/Verse/DesignationManager.cs b/Assembly-CSharp/Verse/DesignationManager.cs index f96e45ad2..b23b97be6 100644 --- a/Assembly-CSharp/Verse/DesignationManager.cs +++ b/Assembly-CSharp/Verse/DesignationManager.cs @@ -1,7 +1,6 @@ using RimWorld; using System; using System.Collections.Generic; -using System.Diagnostics; namespace Verse { @@ -28,24 +27,28 @@ public void ExposeData() } if (Scribe.mode == LoadSaveMode.PostLoadInit) { - for (int j = this.allDesignations.Count - 1; j >= 0; j--) + for (int num = this.allDesignations.Count - 1; num >= 0; num--) { - TargetType targetType = this.allDesignations[j].def.targetType; - if (targetType != TargetType.Thing) + switch (this.allDesignations[num].def.targetType) { - if (targetType == TargetType.Cell) + case TargetType.Thing: + { + if (!this.allDesignations[num].target.HasThing) { - if (!this.allDesignations[j].target.Cell.IsValid) - { - Log.Error("Cell-needing designation " + this.allDesignations[j] + " had no cell target. Removing..."); - this.allDesignations.RemoveAt(j); - } + Log.Error("Thing-needing designation " + this.allDesignations[num] + " had no thing target. Removing..."); + this.allDesignations.RemoveAt(num); } + break; } - else if (!this.allDesignations[j].target.HasThing) + case TargetType.Cell: { - Log.Error("Thing-needing designation " + this.allDesignations[j] + " had no thing target. Removing..."); - this.allDesignations.RemoveAt(j); + if (!this.allDesignations[num].target.Cell.IsValid) + { + Log.Error("Cell-needing designation " + this.allDesignations[num] + " had no cell target. Removing..."); + this.allDesignations.RemoveAt(num); + } + break; + } } } } @@ -67,24 +70,25 @@ public void AddDesignation(Designation newDes) if (newDes.def.targetType == TargetType.Cell && this.DesignationAt(newDes.target.Cell, newDes.def) != null) { Log.Error("Tried to double-add designation at location " + newDes.target); - return; } - if (newDes.def.targetType == TargetType.Thing && this.DesignationOn(newDes.target.Thing, newDes.def) != null) + else if (newDes.def.targetType == TargetType.Thing && this.DesignationOn(newDes.target.Thing, newDes.def) != null) { Log.Error("Tried to double-add designation on Thing " + newDes.target); - return; } - if (newDes.def.targetType == TargetType.Thing) + else { - newDes.target.Thing.SetForbidden(false, false); - } - this.allDesignations.Add(newDes); - newDes.designationManager = this; - newDes.Notify_Added(); - Map map = (!newDes.target.HasThing) ? this.map : newDes.target.Thing.Map; - if (map != null) - { - MoteMaker.ThrowMetaPuffs(newDes.target.ToTargetInfo(map)); + if (newDes.def.targetType == TargetType.Thing) + { + newDes.target.Thing.SetForbidden(false, false); + } + this.allDesignations.Add(newDes); + newDes.designationManager = this; + newDes.Notify_Added(); + Map map = (!newDes.target.HasThing) ? this.map : newDes.target.Thing.Map; + if (map != null) + { + MoteMaker.ThrowMetaPuffs(newDes.target.ToTargetInfo(map)); + } } } @@ -137,40 +141,42 @@ public Designation DesignationAt(IntVec3 c, DesignationDef def) return null; } - [DebuggerHidden] public IEnumerable AllDesignationsOn(Thing t) { - DesignationManager.c__Iterator1F3 c__Iterator1F = new DesignationManager.c__Iterator1F3(); - c__Iterator1F.t = t; - c__Iterator1F.<$>t = t; - c__Iterator1F.<>f__this = this; - DesignationManager.c__Iterator1F3 expr_1C = c__Iterator1F; - expr_1C.$PC = -2; - return expr_1C; + int count = this.allDesignations.Count; + for (int i = 0; i < count; i++) + { + if (this.allDesignations[i].target.Thing == t) + { + yield return this.allDesignations[i]; + } + } } - [DebuggerHidden] public IEnumerable AllDesignationsAt(IntVec3 c) { - DesignationManager.c__Iterator1F4 c__Iterator1F = new DesignationManager.c__Iterator1F4(); - c__Iterator1F.c = c; - c__Iterator1F.<$>c = c; - c__Iterator1F.<>f__this = this; - DesignationManager.c__Iterator1F4 expr_1C = c__Iterator1F; - expr_1C.$PC = -2; - return expr_1C; + int count = this.allDesignations.Count; + for (int i = 0; i < count; i++) + { + Designation des = this.allDesignations[i]; + if ((!des.target.HasThing || des.target.Thing.Map == this.map) && des.target.Cell == c) + { + yield return des; + } + } } - [DebuggerHidden] public IEnumerable SpawnedDesignationsOfDef(DesignationDef def) { - DesignationManager.c__Iterator1F5 c__Iterator1F = new DesignationManager.c__Iterator1F5(); - c__Iterator1F.def = def; - c__Iterator1F.<$>def = def; - c__Iterator1F.<>f__this = this; - DesignationManager.c__Iterator1F5 expr_1C = c__Iterator1F; - expr_1C.$PC = -2; - return expr_1C; + int count = this.allDesignations.Count; + for (int i = 0; i < count; i++) + { + Designation des = this.allDesignations[i]; + if (des.def == def && (!des.target.HasThing || des.target.Thing.Map == this.map)) + { + yield return des; + } + } } public void RemoveDesignation(Designation des) @@ -184,23 +190,20 @@ public void RemoveAllDesignationsOn(Thing t, bool standardCanceling = false) for (int i = 0; i < this.allDesignations.Count; i++) { Designation designation = this.allDesignations[i]; - if (!standardCanceling || designation.def.designateCancelable) + if ((!standardCanceling || designation.def.designateCancelable) && designation.target.Thing == t) { - if (designation.target.Thing == t) - { - designation.Notify_Removing(); - } + designation.Notify_Removing(); } } - this.allDesignations.RemoveAll((Designation d) => (!standardCanceling || d.def.designateCancelable) && d.target.Thing == t); + this.allDesignations.RemoveAll((Predicate)((Designation d) => (!standardCanceling || d.def.designateCancelable) && d.target.Thing == t)); } public void Notify_BuildingDespawned(Thing b) { CellRect cellRect = b.OccupiedRect(); - for (int i = this.allDesignations.Count - 1; i >= 0; i--) + for (int num = this.allDesignations.Count - 1; num >= 0; num--) { - Designation designation = this.allDesignations[i]; + Designation designation = this.allDesignations[num]; if (cellRect.Contains(designation.target.Cell) && designation.def.removeIfBuildingDespawned) { this.RemoveDesignation(designation); diff --git a/Assembly-CSharp/Verse/Designator.cs b/Assembly-CSharp/Verse/Designator.cs index 4557eae41..9857c8c3b 100644 --- a/Assembly-CSharp/Verse/Designator.cs +++ b/Assembly-CSharp/Verse/Designator.cs @@ -60,13 +60,13 @@ public override string TutorTagSelect { get { - if (this.tutorTag == null) + if (base.tutorTag == null) { - return null; + return (string)null; } if (this.cachedTutorTagSelect == null) { - this.cachedTutorTagSelect = "SelectDesignator-" + this.tutorTag; + this.cachedTutorTagSelect = "SelectDesignator-" + base.tutorTag; } return this.cachedTutorTagSelect; } @@ -76,13 +76,13 @@ public string TutorTagDesignate { get { - if (this.tutorTag == null) + if (base.tutorTag == null) { - return null; + return (string)null; } if (this.cachedTutorTagDesignate == null) { - this.cachedTutorTagDesignate = "Designate-" + this.tutorTag; + this.cachedTutorTagDesignate = "Designate-" + base.tutorTag; } return this.cachedTutorTagDesignate; } @@ -92,9 +92,9 @@ public override string HighlightTag { get { - if (this.cachedHighlightTag == null && this.tutorTag != null) + if (this.cachedHighlightTag == null && base.tutorTag != null) { - this.cachedHighlightTag = "Designator-" + this.tutorTag; + this.cachedHighlightTag = "Designator-" + base.tutorTag; } return this.cachedHighlightTag; } @@ -102,22 +102,25 @@ public override string HighlightTag public Designator() { - this.activateSound = SoundDefOf.SelectDesignator; + base.activateSound = SoundDefOf.SelectDesignator; } protected bool CheckCanInteract() { - return !TutorSystem.TutorialMode || TutorSystem.AllowAction(this.TutorTagSelect); + if (TutorSystem.TutorialMode && !TutorSystem.AllowAction(this.TutorTagSelect)) + { + return false; + } + return true; } public override void ProcessInput(Event ev) { - if (!this.CheckCanInteract()) + if (this.CheckCanInteract()) { - return; + base.ProcessInput(ev); + Find.DesignatorManager.Select(this); } - base.ProcessInput(ev); - Find.DesignatorManager.Select(this); } public virtual AcceptanceReport CanDesignateThing(Thing t) @@ -135,17 +138,15 @@ public virtual void DesignateThing(Thing t) public virtual void DesignateMultiCell(IEnumerable cells) { if (TutorSystem.TutorialMode && !TutorSystem.AllowAction(new EventPack(this.TutorTagDesignate, cells))) - { return; - } bool flag = false; bool somethingSucceeded = false; - foreach (IntVec3 current in cells) + foreach (IntVec3 item in cells) { - AcceptanceReport acceptanceReport = this.CanDesignateCell(current); + AcceptanceReport acceptanceReport = this.CanDesignateCell(item); if (acceptanceReport.Accepted) { - this.DesignateSingleCell(current); + this.DesignateSingleCell(item); somethingSucceeded = true; } else if (!flag) @@ -210,14 +211,14 @@ public virtual string DescReverseDesignating(Thing t) public virtual Texture2D IconReverseDesignating(Thing t) { - return this.icon; + return base.icon; } public virtual void DrawMouseAttachments() { if (this.useMouseIcon) { - GenUI.DrawMouseAttachment(this.icon, string.Empty); + GenUI.DrawMouseAttachment(base.icon, string.Empty); } } diff --git a/Assembly-CSharp/Verse/DesignatorManager.cs b/Assembly-CSharp/Verse/DesignatorManager.cs index b137da57a..71647dd48 100644 --- a/Assembly-CSharp/Verse/DesignatorManager.cs +++ b/Assembly-CSharp/Verse/DesignatorManager.cs @@ -1,5 +1,4 @@ using RimWorld; -using System; using UnityEngine; using Verse.Sound; @@ -59,41 +58,48 @@ private bool CheckSelectedDesignatorValid() public void ProcessInputEvents() { - if (!this.CheckSelectedDesignatorValid()) - { - return; - } - if (Event.current.type == EventType.MouseDown && Event.current.button == 0) + if (this.CheckSelectedDesignatorValid()) { - if (this.selectedDesignator.DraggableDimensions == 0) + if (Event.current.type == EventType.MouseDown && Event.current.button == 0) { - Designator designator = this.selectedDesignator; - AcceptanceReport acceptanceReport = this.selectedDesignator.CanDesignateCell(UI.MouseCell()); - if (acceptanceReport.Accepted) + if (this.selectedDesignator.DraggableDimensions == 0) { - designator.DesignateSingleCell(UI.MouseCell()); - designator.Finalize(true); + Designator designator = this.selectedDesignator; + AcceptanceReport acceptanceReport = this.selectedDesignator.CanDesignateCell(UI.MouseCell()); + if (acceptanceReport.Accepted) + { + designator.DesignateSingleCell(UI.MouseCell()); + designator.Finalize(true); + } + else + { + Messages.Message(acceptanceReport.Reason, MessageSound.Silent); + this.selectedDesignator.Finalize(false); + } } else { - Messages.Message(acceptanceReport.Reason, MessageSound.Silent); - this.selectedDesignator.Finalize(false); + this.dragger.StartDrag(); } + Event.current.Use(); } - else + if (Event.current.type == EventType.MouseDown && Event.current.button == 1) { - this.dragger.StartDrag(); + goto IL_00e8; } - Event.current.Use(); - } - if ((Event.current.type == EventType.MouseDown && Event.current.button == 1) || (Event.current.type == EventType.KeyDown && Event.current.keyCode == KeyCode.Escape)) - { - SoundDefOf.CancelMode.PlayOneShotOnCamera(null); - this.Deselect(); - this.dragger.EndDrag(); - Event.current.Use(); - TutorSystem.Notify_Event("ClearDesignatorSelection"); + if (Event.current.type == EventType.KeyDown && Event.current.keyCode == KeyCode.Escape) + goto IL_00e8; + goto IL_011d; } + return; + IL_00e8: + SoundDefOf.CancelMode.PlayOneShotOnCamera(null); + this.Deselect(); + this.dragger.EndDrag(); + Event.current.Use(); + TutorSystem.Notify_Event("ClearDesignatorSelection"); + goto IL_011d; + IL_011d: if (Event.current.type == EventType.MouseUp && Event.current.button == 0 && this.dragger.Dragging) { this.selectedDesignator.DesignateMultiCell(this.dragger.DragCells); diff --git a/Assembly-CSharp/Verse/DesignatorUtility.cs b/Assembly-CSharp/Verse/DesignatorUtility.cs index db698cc60..e68400feb 100644 --- a/Assembly-CSharp/Verse/DesignatorUtility.cs +++ b/Assembly-CSharp/Verse/DesignatorUtility.cs @@ -1,5 +1,4 @@ using RimWorld; -using System; using System.Collections.Generic; namespace Verse @@ -17,10 +16,10 @@ public static Designator FindAllowedDesignator() where T : Designator { if (rules.DesignatorAllowed(allResolvedDesignators[j])) { - T t = allResolvedDesignators[j] as T; - if (t != null) + T val = (T)(allResolvedDesignators[j] as T); + if (val != null) { - return t; + return (Designator)(object)val; } } } diff --git a/Assembly-CSharp/Verse/DestroyMode.cs b/Assembly-CSharp/Verse/DestroyMode.cs index 3eb5f1d5f..5c1d7bd31 100644 --- a/Assembly-CSharp/Verse/DestroyMode.cs +++ b/Assembly-CSharp/Verse/DestroyMode.cs @@ -1,13 +1,11 @@ -using System; - namespace Verse { public enum DestroyMode : byte { - Vanish, - KillFinalize, - Deconstruct, - FailConstruction, - Cancel + Vanish = 0, + KillFinalize = 1, + Deconstruct = 2, + FailConstruction = 3, + Cancel = 4 } } diff --git a/Assembly-CSharp/Verse/DiaNode.cs b/Assembly-CSharp/Verse/DiaNode.cs index ae21d5b52..d658eba09 100644 --- a/Assembly-CSharp/Verse/DiaNode.cs +++ b/Assembly-CSharp/Verse/DiaNode.cs @@ -28,12 +28,21 @@ public DiaNode(DiaNodeMold newDef) { this.def = newDef; this.def.used = true; - this.text = this.def.texts.RandomElement(); + this.text = this.def.texts.RandomElement(); if (this.def.optionList.Count > 0) { - foreach (DiaOptionMold current in this.def.optionList) + List.Enumerator enumerator = this.def.optionList.GetEnumerator(); + try { - this.options.Add(new DiaOption(current)); + while (enumerator.MoveNext()) + { + DiaOptionMold current = enumerator.Current; + this.options.Add(new DiaOption(current)); + } + } + finally + { + ((IDisposable)(object)enumerator).Dispose(); } } else diff --git a/Assembly-CSharp/Verse/DiaNodeList.cs b/Assembly-CSharp/Verse/DiaNodeList.cs index 79f68091a..3df1d89f5 100644 --- a/Assembly-CSharp/Verse/DiaNodeList.cs +++ b/Assembly-CSharp/Verse/DiaNodeList.cs @@ -13,19 +13,37 @@ public class DiaNodeList public DiaNodeMold RandomNodeFromList() { - List list = this.Nodes.ListFullCopy(); - foreach (string current in this.NodeNames) + List list = this.Nodes.ListFullCopy(); + List.Enumerator enumerator = this.NodeNames.GetEnumerator(); + try { - list.Add(DialogDatabase.GetNodeNamed(current)); + while (enumerator.MoveNext()) + { + string current = enumerator.Current; + list.Add(DialogDatabase.GetNodeNamed(current)); + } + } + finally + { + ((IDisposable)(object)enumerator).Dispose(); } - foreach (DiaNodeMold current2 in list) + List.Enumerator enumerator2 = list.GetEnumerator(); + try { - if (current2.unique && current2.used) + while (enumerator2.MoveNext()) { - list.Remove(current2); + DiaNodeMold current2 = enumerator2.Current; + if (current2.unique && current2.used) + { + list.Remove(current2); + } } } - return list.RandomElement(); + finally + { + ((IDisposable)(object)enumerator2).Dispose(); + } + return list.RandomElement(); } } } diff --git a/Assembly-CSharp/Verse/DiaNodeMold.cs b/Assembly-CSharp/Verse/DiaNodeMold.cs index 0d1458b48..ef03db446 100644 --- a/Assembly-CSharp/Verse/DiaNodeMold.cs +++ b/Assembly-CSharp/Verse/DiaNodeMold.cs @@ -25,18 +25,45 @@ public class DiaNodeMold public void PostLoad() { int num = 0; - foreach (string current in this.texts.ListFullCopy()) + List.Enumerator enumerator = this.texts.ListFullCopy().GetEnumerator(); + try { - this.texts[num] = current.Replace("\\n", Environment.NewLine); - num++; + while (enumerator.MoveNext()) + { + string current = enumerator.Current; + this.texts[num] = current.Replace("\\n", Environment.NewLine); + num++; + } + } + finally + { + ((IDisposable)(object)enumerator).Dispose(); } - foreach (DiaOptionMold current2 in this.optionList) + List.Enumerator enumerator2 = this.optionList.GetEnumerator(); + try { - foreach (DiaNodeMold current3 in current2.ChildNodes) + while (enumerator2.MoveNext()) { - current3.PostLoad(); + DiaOptionMold current2 = enumerator2.Current; + List.Enumerator enumerator3 = current2.ChildNodes.GetEnumerator(); + try + { + while (enumerator3.MoveNext()) + { + DiaNodeMold current3 = enumerator3.Current; + current3.PostLoad(); + } + } + finally + { + ((IDisposable)(object)enumerator3).Dispose(); + } } } + finally + { + ((IDisposable)(object)enumerator2).Dispose(); + } } } } diff --git a/Assembly-CSharp/Verse/DiaNodeType.cs b/Assembly-CSharp/Verse/DiaNodeType.cs index 3097c98af..eabffaa04 100644 --- a/Assembly-CSharp/Verse/DiaNodeType.cs +++ b/Assembly-CSharp/Verse/DiaNodeType.cs @@ -1,12 +1,10 @@ -using System; - namespace Verse { public enum DiaNodeType : byte { - Undefined, - Special, - BaseEncounters, - InsanityBattles + Undefined = 0, + Special = 1, + BaseEncounters = 2, + InsanityBattles = 3 } } diff --git a/Assembly-CSharp/Verse/DiaOption.cs b/Assembly-CSharp/Verse/DiaOption.cs index ed5e449bc..7558eaa6f 100644 --- a/Assembly-CSharp/Verse/DiaOption.cs +++ b/Assembly-CSharp/Verse/DiaOption.cs @@ -31,10 +31,9 @@ public static DiaOption DefaultOK { get { - return new DiaOption("OK".Translate()) - { - resolveTree = true - }; + DiaOption diaOption = new DiaOption("OK".Translate()); + diaOption.resolveTree = true; + return diaOption; } } @@ -102,11 +101,11 @@ protected void Activate() { this.OwningDialog.Close(true); } - if (this.action != null) + if ((object)this.action != null) { this.action(); } - if (this.linkLateBind != null) + if ((object)this.linkLateBind != null) { this.OwningDialog.GotoNode(this.linkLateBind()); } diff --git a/Assembly-CSharp/Verse/DiaOptionMold.cs b/Assembly-CSharp/Verse/DiaOptionMold.cs index 83d46bbe5..4b7144284 100644 --- a/Assembly-CSharp/Verse/DiaOptionMold.cs +++ b/Assembly-CSharp/Verse/DiaOptionMold.cs @@ -11,28 +11,47 @@ public class DiaOptionMold [XmlElement("Node")] public List ChildNodes = new List(); - [XmlElement("NodeName"), DefaultValue("")] + [XmlElement("NodeName")] + [DefaultValue("")] public List ChildNodeNames = new List(); public DiaNodeMold RandomLinkNode() { - List list = this.ChildNodes.ListFullCopy(); - foreach (string current in this.ChildNodeNames) + List list = this.ChildNodes.ListFullCopy(); + List.Enumerator enumerator = this.ChildNodeNames.GetEnumerator(); + try { - list.Add(DialogDatabase.GetNodeNamed(current)); + while (enumerator.MoveNext()) + { + string current = enumerator.Current; + list.Add(DialogDatabase.GetNodeNamed(current)); + } + } + finally + { + ((IDisposable)(object)enumerator).Dispose(); } - foreach (DiaNodeMold current2 in list) + List.Enumerator enumerator2 = list.GetEnumerator(); + try { - if (current2.unique && current2.used) + while (enumerator2.MoveNext()) { - list.Remove(current2); + DiaNodeMold current2 = enumerator2.Current; + if (current2.unique && current2.used) + { + list.Remove(current2); + } } } + finally + { + ((IDisposable)(object)enumerator2).Dispose(); + } if (list.Count == 0) { return null; } - return list.RandomElement(); + return list.RandomElement(); } } } diff --git a/Assembly-CSharp/Verse/DialogDatabase.cs b/Assembly-CSharp/Verse/DialogDatabase.cs index 1f36a702a..770d29465 100644 --- a/Assembly-CSharp/Verse/DialogDatabase.cs +++ b/Assembly-CSharp/Verse/DialogDatabase.cs @@ -20,11 +20,11 @@ static DialogDatabase() private static void LoadAllDialog() { DialogDatabase.Nodes.Clear(); - UnityEngine.Object[] array = Resources.LoadAll("Dialog", typeof(TextAsset)); - UnityEngine.Object[] array2 = array; - for (int i = 0; i < array2.Length; i++) + UnityEngine.Object[] array; + UnityEngine.Object[] array2 = array = Resources.LoadAll("Dialog", typeof(TextAsset)); + for (int i = 0; i < array.Length; i++) { - UnityEngine.Object @object = array2[i]; + UnityEngine.Object @object = array[i]; TextAsset ass = @object as TextAsset; if (@object.name == "BaseEncounters" || @object.name == "GeneratedDialogs") { @@ -39,9 +39,18 @@ private static void LoadAllDialog() LayerLoader.LoadFileIntoList(ass, DialogDatabase.Nodes, DialogDatabase.NodeLists, DiaNodeType.Special); } } - foreach (DiaNodeMold current in DialogDatabase.Nodes) + List.Enumerator enumerator = DialogDatabase.Nodes.GetEnumerator(); + try { - current.PostLoad(); + while (enumerator.MoveNext()) + { + DiaNodeMold current = enumerator.Current; + current.PostLoad(); + } + } + finally + { + ((IDisposable)(object)enumerator).Dispose(); } LayerLoader.MarkNonRootNodes(DialogDatabase.Nodes); } @@ -49,34 +58,59 @@ private static void LoadAllDialog() public static DiaNodeMold GetRandomEncounterRootNode(DiaNodeType NType) { List list = new List(); - foreach (DiaNodeMold current in DialogDatabase.Nodes) + List.Enumerator enumerator = DialogDatabase.Nodes.GetEnumerator(); + try { - if (current.isRoot && (!current.unique || !current.used) && current.nodeType == NType) + while (enumerator.MoveNext()) { - list.Add(current); + DiaNodeMold current = enumerator.Current; + if (current.isRoot && (!current.unique || !current.used) && current.nodeType == NType) + { + list.Add(current); + } } } - return list.RandomElement(); + finally + { + ((IDisposable)(object)enumerator).Dispose(); + } + return list.RandomElement(); } public static DiaNodeMold GetNodeNamed(string NodeName) { - foreach (DiaNodeMold current in DialogDatabase.Nodes) + List.Enumerator enumerator = DialogDatabase.Nodes.GetEnumerator(); + try { - if (current.name == NodeName) + while (enumerator.MoveNext()) { - DiaNodeMold result = current; - return result; + DiaNodeMold current = enumerator.Current; + if (current.name == NodeName) + { + return current; + } } } - foreach (DiaNodeList current2 in DialogDatabase.NodeLists) + finally + { + ((IDisposable)(object)enumerator).Dispose(); + } + List.Enumerator enumerator2 = DialogDatabase.NodeLists.GetEnumerator(); + try { - if (current2.Name == NodeName) + while (enumerator2.MoveNext()) { - DiaNodeMold result = current2.RandomNodeFromList(); - return result; + DiaNodeList current2 = enumerator2.Current; + if (current2.Name == NodeName) + { + return current2.RandomNodeFromList(); + } } } + finally + { + ((IDisposable)(object)enumerator2).Dispose(); + } Log.Error("Did not find node named '" + NodeName + "'."); return null; } diff --git a/Assembly-CSharp/Verse/Dialog_ChangeNameTriple.cs b/Assembly-CSharp/Verse/Dialog_ChangeNameTriple.cs index fdcb86f99..be484d68b 100644 --- a/Assembly-CSharp/Verse/Dialog_ChangeNameTriple.cs +++ b/Assembly-CSharp/Verse/Dialog_ChangeNameTriple.cs @@ -36,9 +36,9 @@ public Dialog_ChangeNameTriple(Pawn pawn) { this.pawn = pawn; this.curName = ((NameTriple)pawn.Name).Nick; - this.forcePause = true; - this.absorbInputAroundWindow = true; - this.closeOnClickedOutside = true; + base.forcePause = true; + base.absorbInputAroundWindow = true; + base.closeOnClickedOutside = true; } public override void DoWindowContents(Rect inRect) @@ -46,24 +46,25 @@ public override void DoWindowContents(Rect inRect) Text.Font = GameFont.Medium; Widgets.Label(new Rect(15f, 15f, 500f, 50f), this.CurPawnName.ToString().Replace(" '' ", " ")); Text.Font = GameFont.Small; - string text = Widgets.TextField(new Rect(15f, 50f, inRect.width / 2f - 20f, 35f), this.curName); + string text = Widgets.TextField(new Rect(15f, 50f, (float)(inRect.width / 2.0 - 20.0), 35f), this.curName); if (text.Length < 16) { this.curName = text; } - if (Widgets.ButtonText(new Rect(inRect.width / 2f + 20f, inRect.height - 35f, inRect.width / 2f - 20f, 35f), "OK", true, false, true) || (Event.current.type == EventType.KeyDown && Event.current.keyCode == KeyCode.Return)) + if (!Widgets.ButtonText(new Rect((float)(inRect.width / 2.0 + 20.0), (float)(inRect.height - 35.0), (float)(inRect.width / 2.0 - 20.0), 35f), "OK", true, false, true)) { - if (this.curName.Length < 1) - { - this.curName = ((NameTriple)this.pawn.Name).First; - } - this.pawn.Name = this.CurPawnName; - Find.WindowStack.TryRemove(this, true); - Messages.Message("PawnGainsName".Translate(new object[] - { - this.curName - }), this.pawn, MessageSound.Benefit); + if (Event.current.type != EventType.KeyDown) + return; + if (Event.current.keyCode != KeyCode.Return) + return; + } + if (this.curName.Length < 1) + { + this.curName = ((NameTriple)this.pawn.Name).First; } + this.pawn.Name = this.CurPawnName; + Find.WindowStack.TryRemove(this, true); + Messages.Message("PawnGainsName".Translate(this.curName), (Thing)this.pawn, MessageSound.Benefit); } } } diff --git a/Assembly-CSharp/Verse/Dialog_DebugActionsMenu.cs b/Assembly-CSharp/Verse/Dialog_DebugActionsMenu.cs index d314c5c48..4e636a3cb 100644 --- a/Assembly-CSharp/Verse/Dialog_DebugActionsMenu.cs +++ b/Assembly-CSharp/Verse/Dialog_DebugActionsMenu.cs @@ -3,7 +3,6 @@ using RimWorld.Planet; using System; using System.Collections.Generic; -using System.Diagnostics; using System.Linq; using System.Text; using UnityEngine; @@ -27,7 +26,7 @@ public override bool IsDebug public Dialog_DebugActionsMenu() { - this.forcePause = true; + base.forcePause = true; } protected override void DoListingItems() @@ -59,11 +58,11 @@ protected override void DoListingItems() private void DoListingItems_Entry() { this.DoLabel("Translation tools"); - base.DebugAction("Write backstory translation file", delegate + base.DebugAction("Write backstory translation file", (Action)delegate { LanguageDataWriter.WriteBackstoryFile(); }); - base.DebugAction("Output translation report", delegate + base.DebugAction("Output translation report", (Action)delegate { LanguageReportGenerator.OutputTranslationReport(); }); @@ -73,7 +72,7 @@ private void DoListingItems_AllModePlayActions() { this.DoGap(); this.DoLabel("Actions - Map management"); - base.DebugAction("Generate map", delegate + base.DebugAction("Generate map", (Action)delegate { MapParent mapParent = (MapParent)WorldObjectMaker.MakeWorldObject(WorldObjectDefOf.FactionBase); mapParent.Tile = TileFinder.RandomStartingTile(); @@ -81,55 +80,59 @@ private void DoListingItems_AllModePlayActions() Find.WorldObjects.Add(mapParent); GetOrGenerateMapUtility.GetOrGenerateMap(mapParent.Tile, new IntVec3(50, 1, 50), null); }); - base.DebugAction("Destroy map", delegate + base.DebugAction("Destroy map", (Action)delegate { - List list = new List(); - List maps = Find.Maps; - for (int i = 0; i < maps.Count; i++) + List list3 = new List(); + List maps3 = Find.Maps; + for (int l = 0; l < maps3.Count; l++) { - Map map = maps[i]; - list.Add(new DebugMenuOption(map.ToString(), DebugMenuOptionMode.Action, delegate + Map map4 = maps3[l]; + list3.Add(new DebugMenuOption(map4.ToString(), DebugMenuOptionMode.Action, (Action)delegate { - Current.Game.DeinitAndRemoveMap(map); + Current.Game.DeinitAndRemoveMap(map4); })); } - Find.WindowStack.Add(new Dialog_DebugOptionListLister(list)); + Find.WindowStack.Add(new Dialog_DebugOptionListLister(list3)); }); - base.DebugToolMap("Transfer", delegate + base.DebugToolMap("Transfer", (Action)delegate() { - List toTransfer = Find.VisibleMap.thingGrid.ThingsAt(UI.MouseCell()).ToList(); - if (!toTransfer.Any()) - { - return; - } - List list = new List(); - List maps = Find.Maps; - for (int i = 0; i < maps.Count; i++) + List toTransfer = Find.VisibleMap.thingGrid.ThingsAt(UI.MouseCell()).ToList(); + if (toTransfer.Any()) { - Map map = maps[i]; - if (map != Find.VisibleMap) + List list2 = new List(); + List maps2 = Find.Maps; + for (int j = 0; j < maps2.Count; j++) { - list.Add(new DebugMenuOption(map.ToString(), DebugMenuOptionMode.Action, delegate + Map map2 = maps2[j]; + if (map2 != Find.VisibleMap) { - for (int j = 0; j < toTransfer.Count; j++) + list2.Add(new DebugMenuOption(map2.ToString(), DebugMenuOptionMode.Action, (Action)delegate() { - IntVec3 center; - if (CellFinder.TryFindRandomCellNear(map.Center, map, Mathf.Max(map.Size.x, map.Size.z), (IntVec3 x) => !x.Fogged(map) && x.Standable(map), out center)) - { - toTransfer[j].DeSpawn(); - GenPlace.TryPlaceThing(toTransfer[j], center, map, ThingPlaceMode.Near, null); - } - else + for (int k = 0; k < toTransfer.Count; k++) { - Log.Error("Could not find spawn cell."); + IntVec3 center = map2.Center; + Map map3 = map2; + IntVec3 size = map2.Size; + int x2 = size.x; + IntVec3 size2 = map2.Size; + IntVec3 center2 = default(IntVec3); + if (CellFinder.TryFindRandomCellNear(center, map3, Mathf.Max(x2, size2.z), (Predicate)((IntVec3 x) => !x.Fogged(map2) && x.Standable(map2)), out center2)) + { + toTransfer[k].DeSpawn(); + GenPlace.TryPlaceThing(toTransfer[k], center2, map2, ThingPlaceMode.Near, null); + } + else + { + Log.Error("Could not find spawn cell."); + } } - } - })); + })); + } } + Find.WindowStack.Add(new Dialog_DebugOptionListLister(list2)); } - Find.WindowStack.Add(new Dialog_DebugOptionListLister(list)); }); - base.DebugAction("Change map", delegate + base.DebugAction("Change map", (Action)delegate { List list = new List(); List maps = Find.Maps; @@ -138,7 +141,7 @@ private void DoListingItems_AllModePlayActions() Map map = maps[i]; if (map != Find.VisibleMap) { - list.Add(new DebugMenuOption(map.ToString(), DebugMenuOptionMode.Action, delegate + list.Add(new DebugMenuOption(map.ToString(), DebugMenuOptionMode.Action, (Action)delegate { Current.Game.VisibleMap = map; })); @@ -154,220 +157,275 @@ private void DoListingItems_MapActions() this.DoLabel("Incidents"); this.DoExecuteIncidentDebugAction(Find.VisibleMap, null); this.DoExecuteIncidentWithDebugAction(Find.VisibleMap, null); - base.DebugAction("Execute raid with...", delegate + base.DebugAction("Execute raid with...", (Action)delegate() { - StorytellerComp storytellerComp = Find.Storyteller.storytellerComps.First((StorytellerComp x) => x is StorytellerComp_ThreatCycle || x is StorytellerComp_RandomMain); + StorytellerComp storytellerComp = Find.Storyteller.storytellerComps.First((Func)((StorytellerComp x) => x is StorytellerComp_ThreatCycle || x is StorytellerComp_RandomMain)); IncidentParms parms = storytellerComp.GenerateParms(IncidentCategory.ThreatBig, Find.VisibleMap); - List list = new List(); - foreach (Faction current in Find.FactionManager.AllFactions) + List list8 = new List(); + foreach (Faction allFaction in Find.FactionManager.AllFactions) { - Faction localFac = current; - list.Add(new DebugMenuOption(localFac.Name + " (" + localFac.def.defName + ")", DebugMenuOptionMode.Action, delegate + Faction localFac = allFaction; + list8.Add(new DebugMenuOption(localFac.Name + " (" + localFac.def.defName + ")", DebugMenuOptionMode.Action, (Action)delegate { parms.faction = localFac; - List list2 = new List(); - foreach (float num in Dialog_DebugActionsMenu.PointsOptions()) + List list9 = new List(); + foreach (float item in Dialog_DebugActionsMenu.PointsOptions()) { - float localPoints = num; - list2.Add(new DebugMenuOption(num + " points", DebugMenuOptionMode.Action, delegate + float num2 = item; + float localPoints = num2; + list9.Add(new DebugMenuOption(num2 + " points", DebugMenuOptionMode.Action, (Action)delegate { parms.points = localPoints; - List list3 = new List(); - foreach (RaidStrategyDef current2 in DefDatabase.AllDefs) + List list10 = new List(); + foreach (RaidStrategyDef allDef in DefDatabase.AllDefs) { - RaidStrategyDef localStrat = current2; + RaidStrategyDef localStrat = allDef; string text = localStrat.defName; if (!localStrat.Worker.CanUseWith(parms)) { text += " [NO]"; } - list3.Add(new DebugMenuOption(text, DebugMenuOptionMode.Action, delegate + list10.Add(new DebugMenuOption(text, DebugMenuOptionMode.Action, (Action)delegate { parms.raidStrategy = localStrat; this.DoRaid(parms); })); } - Find.WindowStack.Add(new Dialog_DebugOptionListLister(list3)); + Find.WindowStack.Add(new Dialog_DebugOptionListLister(list10)); })); } - Find.WindowStack.Add(new Dialog_DebugOptionListLister(list2)); + Find.WindowStack.Add(new Dialog_DebugOptionListLister(list9)); })); } - Find.WindowStack.Add(new Dialog_DebugOptionListLister(list)); + Find.WindowStack.Add(new Dialog_DebugOptionListLister(list8)); }); - Action DoRandomEnemyRaid = delegate(int pts) + Action DoRandomEnemyRaid = (Action)delegate(int pts) { this.Close(true); - IncidentParms incidentParms = new IncidentParms(); - incidentParms.target = Find.VisibleMap; - incidentParms.points = (float)pts; - IncidentDefOf.RaidEnemy.Worker.TryExecute(incidentParms); + IncidentParms incidentParms2 = new IncidentParms(); + incidentParms2.target = Find.VisibleMap; + incidentParms2.points = (float)pts; + IncidentDefOf.RaidEnemy.Worker.TryExecute(incidentParms2); }; - base.DebugAction("Raid (35 pts)", delegate + base.DebugAction("Raid (35 pts)", (Action)delegate { DoRandomEnemyRaid(35); }); - base.DebugAction("Raid (75 pts)", delegate + base.DebugAction("Raid (75 pts)", (Action)delegate { DoRandomEnemyRaid(75); }); - base.DebugAction("Raid (300 pts)", delegate + base.DebugAction("Raid (300 pts)", (Action)delegate { DoRandomEnemyRaid(300); }); - base.DebugAction("Raid (400 pts)", delegate + base.DebugAction("Raid (400 pts)", (Action)delegate { DoRandomEnemyRaid(400); }); - base.DebugAction("Raid (1000 pts)", delegate + base.DebugAction("Raid (1000 pts)", (Action)delegate { DoRandomEnemyRaid(1000); }); - base.DebugAction("Raid (3000 pts)", delegate + base.DebugAction("Raid (3000 pts)", (Action)delegate { DoRandomEnemyRaid(3000); }); this.DoGap(); this.DoLabel("Actions - Misc"); - base.DebugAction("Change weather...", delegate + base.DebugAction("Change weather...", (Action)delegate { - List list = new List(); - foreach (WeatherDef current in DefDatabase.AllDefs) + List list7 = new List(); + foreach (WeatherDef allDef in DefDatabase.AllDefs) { - WeatherDef localWeather = current; - list.Add(new DebugMenuOption(localWeather.LabelCap, DebugMenuOptionMode.Action, delegate + WeatherDef localWeather = allDef; + list7.Add(new DebugMenuOption(localWeather.LabelCap, DebugMenuOptionMode.Action, (Action)delegate { Find.VisibleMap.weatherManager.TransitionTo(localWeather); })); } - Find.WindowStack.Add(new Dialog_DebugOptionListLister(list)); + Find.WindowStack.Add(new Dialog_DebugOptionListLister(list7)); }); - base.DebugAction("Start song...", delegate + base.DebugAction("Start song...", (Action)delegate { - List list = new List(); - foreach (SongDef current in DefDatabase.AllDefs) + List list6 = new List(); + foreach (SongDef allDef in DefDatabase.AllDefs) { - SongDef localSong = current; - list.Add(new DebugMenuOption(localSong.defName, DebugMenuOptionMode.Action, delegate + SongDef localSong = allDef; + list6.Add(new DebugMenuOption(localSong.defName, DebugMenuOptionMode.Action, (Action)delegate { Find.MusicManagerPlay.ForceStartSong(localSong, false); })); } - Find.WindowStack.Add(new Dialog_DebugOptionListLister(list)); + Find.WindowStack.Add(new Dialog_DebugOptionListLister(list6)); }); if (Find.VisibleMap.gameConditionManager.ActiveConditions.Count > 0) { - base.DebugAction("End game condition ...", delegate + base.DebugAction("End game condition ...", (Action)delegate { - List list = new List(); - foreach (GameCondition current in Find.VisibleMap.gameConditionManager.ActiveConditions) + List list5 = new List(); + List.Enumerator enumerator8 = Find.VisibleMap.gameConditionManager.ActiveConditions.GetEnumerator(); + try { - GameCondition localMc = current; - list.Add(new DebugMenuOption(localMc.LabelCap, DebugMenuOptionMode.Action, delegate + while (enumerator8.MoveNext()) { - localMc.End(); - })); + GameCondition current8 = enumerator8.Current; + GameCondition localMc = current8; + list5.Add(new DebugMenuOption(localMc.LabelCap, DebugMenuOptionMode.Action, (Action)delegate + { + localMc.End(); + })); + } } - Find.WindowStack.Add(new Dialog_DebugOptionListLister(list)); + finally + { + ((IDisposable)(object)enumerator8).Dispose(); + } + Find.WindowStack.Add(new Dialog_DebugOptionListLister(list5)); }); } - base.DebugAction("Add prisoner", delegate + base.DebugAction("Add prisoner", (Action)delegate { this.AddGuest(true); }); - base.DebugAction("Add guest", delegate + base.DebugAction("Add guest", (Action)delegate { this.AddGuest(false); }); - base.DebugAction("Force enemy assault", delegate + base.DebugAction("Force enemy assault", (Action)delegate { - foreach (Lord current in Find.VisibleMap.lordManager.lords) + List.Enumerator enumerator6 = Find.VisibleMap.lordManager.lords.GetEnumerator(); + try { - LordToil_Stage lordToil_Stage = current.CurLordToil as LordToil_Stage; - if (lordToil_Stage != null) + while (enumerator6.MoveNext()) { - foreach (Transition current2 in current.Graph.transitions) + Lord current6 = enumerator6.Current; + LordToil_Stage lordToil_Stage = current6.CurLordToil as LordToil_Stage; + if (lordToil_Stage != null) { - if (current2.sources.Contains(lordToil_Stage) && current2.target is LordToil_AssaultColony) + List.Enumerator enumerator7 = current6.Graph.transitions.GetEnumerator(); + try + { + while (enumerator7.MoveNext()) + { + Transition current7 = enumerator7.Current; + if (current7.sources.Contains(lordToil_Stage) && current7.target is LordToil_AssaultColony) + { + Messages.Message("Debug forcing to assault toil: " + current6.faction, MessageSound.SeriousAlert); + current6.GotoToil(current7.target); + return; + } + } + } + finally { - Messages.Message("Debug forcing to assault toil: " + current.faction, MessageSound.SeriousAlert); - current.GotoToil(current2.target); - return; + ((IDisposable)(object)enumerator7).Dispose(); } } } } + finally + { + ((IDisposable)(object)enumerator6).Dispose(); + } }); - base.DebugAction("Force enemy flee", delegate + base.DebugAction("Force enemy flee", (Action)delegate() { - foreach (Lord current in Find.VisibleMap.lordManager.lords) + List.Enumerator enumerator5 = Find.VisibleMap.lordManager.lords.GetEnumerator(); + try { - if (current.faction.HostileTo(Faction.OfPlayer) && current.faction.def.autoFlee) + while (enumerator5.MoveNext()) { - LordToil lordToil = current.Graph.lordToils.FirstOrDefault((LordToil st) => st is LordToil_PanicFlee); - if (lordToil != null) + Lord current5 = enumerator5.Current; + if (current5.faction.HostileTo(Faction.OfPlayer) && current5.faction.def.autoFlee) { - current.GotoToil(lordToil); + LordToil lordToil = current5.Graph.lordToils.FirstOrDefault((Func)((LordToil st) => st is LordToil_PanicFlee)); + if (lordToil != null) + { + current5.GotoToil(lordToil); + } } } } + finally + { + ((IDisposable)(object)enumerator5).Dispose(); + } }); - base.DebugAction("Destroy all things", delegate + base.DebugAction("Destroy all things", (Action)delegate { - foreach (Thing current in Find.VisibleMap.listerThings.AllThings.ToList()) + List.Enumerator enumerator4 = Find.VisibleMap.listerThings.AllThings.ToList().GetEnumerator(); + try { - current.Destroy(DestroyMode.Vanish); + while (enumerator4.MoveNext()) + { + Thing current4 = enumerator4.Current; + current4.Destroy(DestroyMode.Vanish); + } + } + finally + { + ((IDisposable)(object)enumerator4).Dispose(); } }); - base.DebugAction("Destroy all plants", delegate + base.DebugAction("Destroy all plants", (Action)delegate { - foreach (Thing current in Find.VisibleMap.listerThings.AllThings.ToList()) + List.Enumerator enumerator3 = Find.VisibleMap.listerThings.AllThings.ToList().GetEnumerator(); + try { - if (current is Plant) + while (enumerator3.MoveNext()) { - current.Destroy(DestroyMode.Vanish); + Thing current3 = enumerator3.Current; + if (current3 is Plant) + { + current3.Destroy(DestroyMode.Vanish); + } } } + finally + { + ((IDisposable)(object)enumerator3).Dispose(); + } }); - base.DebugAction("Unload unused assets", delegate + base.DebugAction("Unload unused assets", (Action)delegate { MemoryUtility.UnloadUnusedUnityAssets(); }); - base.DebugAction("Name colony...", delegate + base.DebugAction("Name colony...", (Action)delegate { - List list = new List(); - list.Add(new DebugMenuOption("Faction", DebugMenuOptionMode.Action, delegate + List list4 = new List(); + list4.Add(new DebugMenuOption("Faction", DebugMenuOptionMode.Action, (Action)delegate { Find.WindowStack.Add(new Dialog_NamePlayerFaction()); })); if (Find.VisibleMap != null && Find.VisibleMap.IsPlayerHome) { FactionBase factionBase = (FactionBase)Find.VisibleMap.info.parent; - list.Add(new DebugMenuOption("Faction base", DebugMenuOptionMode.Action, delegate + list4.Add(new DebugMenuOption("Faction base", DebugMenuOptionMode.Action, (Action)delegate { Find.WindowStack.Add(new Dialog_NamePlayerFactionBase(factionBase)); })); - list.Add(new DebugMenuOption("Faction and faction base", DebugMenuOptionMode.Action, delegate + list4.Add(new DebugMenuOption("Faction and faction base", DebugMenuOptionMode.Action, (Action)delegate { Find.WindowStack.Add(new Dialog_NamePlayerFactionAndBase(factionBase)); })); } - Find.WindowStack.Add(new Dialog_DebugOptionListLister(list)); + Find.WindowStack.Add(new Dialog_DebugOptionListLister(list4)); }); - base.DebugAction("Next lesson", delegate + base.DebugAction("Next lesson", (Action)delegate { LessonAutoActivator.DebugForceInitiateBestLessonNow(); }); - base.DebugAction("Regen all map mesh sections", delegate + base.DebugAction("Regen all map mesh sections", (Action)delegate { Find.VisibleMap.mapDrawer.RegenerateEverythingNow(); }); - base.DebugAction("Finish all research", delegate + base.DebugAction("Finish all research", (Action)delegate { Find.ResearchManager.DebugSetAllProjectsFinished(); Messages.Message("All research finished.", MessageSound.Benefit); }); - base.DebugAction("Replace all trade ships", delegate + base.DebugAction("Replace all trade ships", (Action)delegate { Find.VisibleMap.passingShipManager.DebugSendAllShipsAway(); for (int i = 0; i < 5; i++) @@ -377,65 +435,70 @@ private void DoListingItems_MapActions() IncidentDefOf.OrbitalTraderArrival.Worker.TryExecute(incidentParms); } }); - base.DebugAction("Change camera config...", delegate + base.DebugAction("Change camera config...", (Action)delegate { - List list = new List(); - foreach (Type current in typeof(CameraMapConfig).AllSubclasses()) + List list3 = new List(); + foreach (Type item in typeof(CameraMapConfig).AllSubclasses()) { - Type localType = current; - list.Add(new DebugMenuOption(localType.Name, DebugMenuOptionMode.Action, delegate + Type localType = item; + list3.Add(new DebugMenuOption(localType.Name, DebugMenuOptionMode.Action, (Action)delegate { Find.CameraDriver.config = (CameraMapConfig)Activator.CreateInstance(localType); })); } - Find.WindowStack.Add(new Dialog_DebugOptionListLister(list)); + Find.WindowStack.Add(new Dialog_DebugOptionListLister(list3)); }); - base.DebugAction("Force ship countdown...", delegate + base.DebugAction("Force ship countdown...", (Action)delegate { - List list = new List(); - list.Add(new DebugMenuOption("Player ship", DebugMenuOptionMode.Action, delegate + List list2 = new List(); + list2.Add(new DebugMenuOption("Player ship", DebugMenuOptionMode.Action, (Action)delegate { ShipCountdown.InitiateCountdown(null, -1); })); - list.Add(new DebugMenuOption("Journey destination", DebugMenuOptionMode.Action, delegate + list2.Add(new DebugMenuOption("Journey destination", DebugMenuOptionMode.Action, (Action)delegate { ShipCountdown.InitiateCountdown(null, 0); })); - Find.WindowStack.Add(new Dialog_DebugOptionListLister(list)); + Find.WindowStack.Add(new Dialog_DebugOptionListLister(list2)); }); - base.DebugAction("Flash trade drop spot", delegate + base.DebugAction("Flash trade drop spot", (Action)delegate { IntVec3 intVec = DropCellFinder.TradeDropSpot(Find.VisibleMap); - Find.VisibleMap.debugDrawer.FlashCell(intVec, 0f, null); + Find.VisibleMap.debugDrawer.FlashCell(intVec, 0f, (string)null); Log.Message("trade drop spot: " + intVec); }); - base.DebugAction("Kill faction leader", delegate + base.DebugAction("Kill faction leader", (Action)delegate() { Pawn leader = (from x in Find.FactionManager.AllFactions where x.leader != null - select x).RandomElement().leader; + select x).RandomElement().leader; int num = 0; - while (!leader.Dead) + while (true) { - if (++num > 1000) + if (!leader.Dead) { - Log.Warning("Could not kill faction leader."); + if (++num <= 1000) + { + leader.TakeDamage(new DamageInfo(DamageDefOf.Bullet, 30, -1f, null, null, null, DamageInfo.SourceCategory.ThingOrUnknown)); + continue; + } break; } - leader.TakeDamage(new DamageInfo(DamageDefOf.Bullet, 30, -1f, null, null, null, DamageInfo.SourceCategory.ThingOrUnknown)); + return; } + Log.Warning("Could not kill faction leader."); }); - base.DebugAction("Refog map", delegate + base.DebugAction("Refog map", (Action)delegate { FloodFillerFog.DebugRefogMap(Find.VisibleMap); }); - base.DebugAction("Use GenStep", delegate + base.DebugAction("Use GenStep", (Action)delegate { List list = new List(); - foreach (Type current in typeof(GenStep).AllSubclassesNonAbstract()) + foreach (Type item in typeof(GenStep).AllSubclassesNonAbstract()) { - Type localGenStep = current; - list.Add(new DebugMenuOption(localGenStep.Name, DebugMenuOptionMode.Action, delegate + Type localGenStep = item; + list.Add(new DebugMenuOption(localGenStep.Name, DebugMenuOptionMode.Action, (Action)delegate { GenStep genStep = (GenStep)Activator.CreateInstance(localGenStep); genStep.Generate(Find.VisibleMap); @@ -443,11 +506,11 @@ private void DoListingItems_MapActions() } Find.WindowStack.Add(new Dialog_DebugOptionListLister(list)); }); - base.DebugAction("Increment time 1 day", delegate + base.DebugAction("Increment time 1 day", (Action)delegate { Find.TickManager.DebugSetTicksGame(Find.TickManager.TicksGame + 60000); }); - base.DebugAction("Increment time 1 season", delegate + base.DebugAction("Increment time 1 season", (Action)delegate { Find.TickManager.DebugSetTicksGame(Find.TickManager.TicksGame + 900000); }); @@ -457,296 +520,340 @@ private void DoListingItems_MapTools() { this.DoGap(); this.DoLabel("Tools - General"); - base.DebugToolMap("Tool: Destroy", delegate + base.DebugToolMap("Tool: Destroy", (Action)delegate { - foreach (Thing current in Find.VisibleMap.thingGrid.ThingsAt(UI.MouseCell()).ToList()) + List.Enumerator enumerator43 = Find.VisibleMap.thingGrid.ThingsAt(UI.MouseCell()).ToList().GetEnumerator(); + try { - current.Destroy(DestroyMode.Vanish); + while (enumerator43.MoveNext()) + { + Thing current43 = enumerator43.Current; + current43.Destroy(DestroyMode.Vanish); + } + } + finally + { + ((IDisposable)(object)enumerator43).Dispose(); } }); - base.DebugToolMap("Tool: Kill", delegate + base.DebugToolMap("Tool: Kill", (Action)delegate { - foreach (Thing current in Find.VisibleMap.thingGrid.ThingsAt(UI.MouseCell()).ToList()) + List.Enumerator enumerator42 = Find.VisibleMap.thingGrid.ThingsAt(UI.MouseCell()).ToList().GetEnumerator(); + try { - current.Kill(null); + while (enumerator42.MoveNext()) + { + Thing current42 = enumerator42.Current; + current42.Kill(default(DamageInfo?)); + } + } + finally + { + ((IDisposable)(object)enumerator42).Dispose(); } }); - base.DebugToolMap("Tool: 10 damage", delegate + base.DebugToolMap("Tool: 10 damage", (Action)delegate { - foreach (Thing current in Find.VisibleMap.thingGrid.ThingsAt(UI.MouseCell()).ToList()) + List.Enumerator enumerator41 = Find.VisibleMap.thingGrid.ThingsAt(UI.MouseCell()).ToList().GetEnumerator(); + try + { + while (enumerator41.MoveNext()) + { + Thing current41 = enumerator41.Current; + current41.TakeDamage(new DamageInfo(DamageDefOf.Crush, 10, -1f, null, null, null, DamageInfo.SourceCategory.ThingOrUnknown)); + } + } + finally { - current.TakeDamage(new DamageInfo(DamageDefOf.Crush, 10, -1f, null, null, null, DamageInfo.SourceCategory.ThingOrUnknown)); + ((IDisposable)(object)enumerator41).Dispose(); } }); - base.DebugToolMap("Tool: 5000 damage", delegate + base.DebugToolMap("Tool: 5000 damage", (Action)delegate { - foreach (Thing current in Find.VisibleMap.thingGrid.ThingsAt(UI.MouseCell()).ToList()) + List.Enumerator enumerator40 = Find.VisibleMap.thingGrid.ThingsAt(UI.MouseCell()).ToList().GetEnumerator(); + try + { + while (enumerator40.MoveNext()) + { + Thing current40 = enumerator40.Current; + current40.TakeDamage(new DamageInfo(DamageDefOf.Crush, 5000, -1f, null, null, null, DamageInfo.SourceCategory.ThingOrUnknown)); + } + } + finally { - current.TakeDamage(new DamageInfo(DamageDefOf.Crush, 5000, -1f, null, null, null, DamageInfo.SourceCategory.ThingOrUnknown)); + ((IDisposable)(object)enumerator40).Dispose(); } }); - base.DebugToolMap("Tool: 5000 flame damage", delegate + base.DebugToolMap("Tool: 5000 flame damage", (Action)delegate { - foreach (Thing current in Find.VisibleMap.thingGrid.ThingsAt(UI.MouseCell()).ToList()) + List.Enumerator enumerator39 = Find.VisibleMap.thingGrid.ThingsAt(UI.MouseCell()).ToList().GetEnumerator(); + try + { + while (enumerator39.MoveNext()) + { + Thing current39 = enumerator39.Current; + current39.TakeDamage(new DamageInfo(DamageDefOf.Flame, 5000, -1f, null, null, null, DamageInfo.SourceCategory.ThingOrUnknown)); + } + } + finally { - current.TakeDamage(new DamageInfo(DamageDefOf.Flame, 5000, -1f, null, null, null, DamageInfo.SourceCategory.ThingOrUnknown)); + ((IDisposable)(object)enumerator39).Dispose(); } }); - base.DebugToolMap("Tool: Clear area 21x21", delegate + base.DebugToolMap("Tool: Clear area 21x21", (Action)delegate { CellRect r = CellRect.CenteredOn(UI.MouseCell(), 10); GenDebug.ClearArea(r, Find.VisibleMap); }); - base.DebugToolMap("Tool: Rock 21x21", delegate + base.DebugToolMap("Tool: Rock 21x21", (Action)delegate { CellRect cellRect = CellRect.CenteredOn(UI.MouseCell(), 10); cellRect.ClipInsideMap(Find.VisibleMap); ThingDef granite = ThingDefOf.Granite; - foreach (IntVec3 current in cellRect) + foreach (IntVec3 item in cellRect) { - GenSpawn.Spawn(granite, current, Find.VisibleMap); + GenSpawn.Spawn(granite, item, Find.VisibleMap); } }); this.DoGap(); - base.DebugToolMap("Tool: Explosion (bomb)", delegate + base.DebugToolMap("Tool: Explosion (bomb)", (Action)delegate { GenExplosion.DoExplosion(UI.MouseCell(), Find.VisibleMap, 3.9f, DamageDefOf.Bomb, null, null, null, null, null, 0f, 1, false, null, 0f, 1); }); - base.DebugToolMap("Tool: Explosion (flame)", delegate + base.DebugToolMap("Tool: Explosion (flame)", (Action)delegate { GenExplosion.DoExplosion(UI.MouseCell(), Find.VisibleMap, 3.9f, DamageDefOf.Flame, null, null, null, null, null, 0f, 1, false, null, 0f, 1); }); - base.DebugToolMap("Tool: Explosion (stun)", delegate + base.DebugToolMap("Tool: Explosion (stun)", (Action)delegate { GenExplosion.DoExplosion(UI.MouseCell(), Find.VisibleMap, 3.9f, DamageDefOf.Stun, null, null, null, null, null, 0f, 1, false, null, 0f, 1); }); - base.DebugToolMap("Tool: Explosion (EMP)", delegate + base.DebugToolMap("Tool: Explosion (EMP)", (Action)delegate { GenExplosion.DoExplosion(UI.MouseCell(), Find.VisibleMap, 3.9f, DamageDefOf.EMP, null, null, null, null, null, 0f, 1, false, null, 0f, 1); }); - base.DebugToolMap("Tool: Explosion (extinguisher)", delegate + base.DebugToolMap("Tool: Explosion (extinguisher)", (Action)delegate { ThingDef filthFireFoam = ThingDefOf.FilthFireFoam; GenExplosion.DoExplosion(UI.MouseCell(), Find.VisibleMap, 10f, DamageDefOf.Extinguish, null, null, null, null, filthFireFoam, 1f, 3, true, null, 0f, 1); }); - base.DebugToolMap("Tool: Explosion (smoke)", delegate + base.DebugToolMap("Tool: Explosion (smoke)", (Action)delegate { ThingDef gas_Smoke = ThingDefOf.Gas_Smoke; GenExplosion.DoExplosion(UI.MouseCell(), Find.VisibleMap, 10f, DamageDefOf.Smoke, null, null, null, null, gas_Smoke, 1f, 1, false, null, 0f, 1); }); - base.DebugToolMap("Tool: Lightning strike", delegate + base.DebugToolMap("Tool: Lightning strike", (Action)delegate { Find.VisibleMap.weatherManager.eventHandler.AddEvent(new WeatherEvent_LightningStrike(Find.VisibleMap, UI.MouseCell())); }); this.DoGap(); - base.DebugToolMap("Tool: Add snow", delegate + base.DebugToolMap("Tool: Add snow", (Action)delegate { SnowUtility.AddSnowRadial(UI.MouseCell(), Find.VisibleMap, 5f, 1f); }); - base.DebugToolMap("Tool: Remove snow", delegate + base.DebugToolMap("Tool: Remove snow", (Action)delegate { SnowUtility.AddSnowRadial(UI.MouseCell(), Find.VisibleMap, 5f, -1f); }); - base.DebugAction("Clear all snow", delegate + base.DebugAction("Clear all snow", (Action)delegate { - foreach (IntVec3 current in Find.VisibleMap.AllCells) + foreach (IntVec3 allCell in Find.VisibleMap.AllCells) { - Find.VisibleMap.snowGrid.SetDepth(current, 0f); + Find.VisibleMap.snowGrid.SetDepth(allCell, 0f); } }); - base.DebugToolMap("Tool: Push heat (10)", delegate + base.DebugToolMap("Tool: Push heat (10)", (Action)delegate { GenTemperature.PushHeat(UI.MouseCell(), Find.VisibleMap, 10f); }); - base.DebugToolMap("Tool: Push heat (10000)", delegate + base.DebugToolMap("Tool: Push heat (10000)", (Action)delegate { GenTemperature.PushHeat(UI.MouseCell(), Find.VisibleMap, 10000f); }); - base.DebugToolMap("Tool: Push heat (-1000)", delegate + base.DebugToolMap("Tool: Push heat (-1000)", (Action)delegate { GenTemperature.PushHeat(UI.MouseCell(), Find.VisibleMap, -1000f); }); this.DoGap(); - base.DebugToolMap("Tool: Finish plant growth", delegate + base.DebugToolMap("Tool: Finish plant growth", (Action)delegate { - foreach (Thing current in Find.VisibleMap.thingGrid.ThingsAt(UI.MouseCell())) + foreach (Thing item in Find.VisibleMap.thingGrid.ThingsAt(UI.MouseCell())) { - Plant plant = current as Plant; - if (plant != null) + Plant plant6 = item as Plant; + if (plant6 != null) { - plant.Growth = 1f; + plant6.Growth = 1f; } } }); - base.DebugToolMap("Tool: Grow 1 day", delegate + base.DebugToolMap("Tool: Grow 1 day", (Action)delegate { - IntVec3 intVec = UI.MouseCell(); - Plant plant = intVec.GetPlant(Find.VisibleMap); - if (plant != null && plant.def.plant != null) + IntVec3 intVec5 = UI.MouseCell(); + Plant plant5 = intVec5.GetPlant(Find.VisibleMap); + if (plant5 != null && plant5.def.plant != null) { - int num = (int)((1f - plant.Growth) * plant.def.plant.growDays); - if (num >= 60000) + int num13 = (int)((1.0 - plant5.Growth) * plant5.def.plant.growDays); + if (num13 >= 60000) { - plant.Age += 60000; + plant5.Age += 60000; } - else if (num > 0) + else if (num13 > 0) { - plant.Age += num; + plant5.Age += num13; } - plant.Growth += 1f / plant.def.plant.growDays; - if ((double)plant.Growth > 1.0) + plant5.Growth += (float)(1.0 / plant5.def.plant.growDays); + if ((double)plant5.Growth > 1.0) { - plant.Growth = 1f; + plant5.Growth = 1f; } - Find.VisibleMap.mapDrawer.SectionAt(intVec).RegenerateAllLayers(); + Find.VisibleMap.mapDrawer.SectionAt(intVec5).RegenerateAllLayers(); } }); - base.DebugToolMap("Tool: Grow to maturity", delegate + base.DebugToolMap("Tool: Grow to maturity", (Action)delegate { - IntVec3 intVec = UI.MouseCell(); - Plant plant = intVec.GetPlant(Find.VisibleMap); - if (plant != null && plant.def.plant != null) + IntVec3 intVec4 = UI.MouseCell(); + Plant plant4 = intVec4.GetPlant(Find.VisibleMap); + if (plant4 != null && plant4.def.plant != null) { - int num = (int)((1f - plant.Growth) * plant.def.plant.growDays); - plant.Age += num; - plant.Growth = 1f; - Find.VisibleMap.mapDrawer.SectionAt(intVec).RegenerateAllLayers(); + int num12 = (int)((1.0 - plant4.Growth) * plant4.def.plant.growDays); + plant4.Age += num12; + plant4.Growth = 1f; + Find.VisibleMap.mapDrawer.SectionAt(intVec4).RegenerateAllLayers(); } }); - base.DebugToolMap("Tool: Reproduce present plant", delegate + base.DebugToolMap("Tool: Reproduce present plant", (Action)delegate { - IntVec3 c = UI.MouseCell(); - Plant plant = c.GetPlant(Find.VisibleMap); - if (plant != null && plant.def.plant != null) + IntVec3 c7 = UI.MouseCell(); + Plant plant2 = c7.GetPlant(Find.VisibleMap); + if (plant2 != null && plant2.def.plant != null) { - Plant plant2 = GenPlantReproduction.TryReproduceFrom(plant.Position, plant.def, SeedTargFindMode.Reproduce, plant.Map); - if (plant2 != null) + Plant plant3 = GenPlantReproduction.TryReproduceFrom(plant2.Position, plant2.def, SeedTargFindMode.Reproduce, plant2.Map); + if (plant3 != null) { - Find.VisibleMap.debugDrawer.FlashCell(plant2.Position, 0f, null); - Find.VisibleMap.debugDrawer.FlashLine(plant.Position, plant2.Position); + Find.VisibleMap.debugDrawer.FlashCell(plant3.Position, 0f, (string)null); + Find.VisibleMap.debugDrawer.FlashLine(plant2.Position, plant3.Position); } else { - Find.VisibleMap.debugDrawer.FlashCell(plant.Position, 0f, null); + Find.VisibleMap.debugDrawer.FlashCell(plant2.Position, 0f, (string)null); } } }); - base.DebugToolMap("Tool: Reproduce plant...", delegate + base.DebugToolMap("Tool: Reproduce plant...", (Action)delegate() { - List list = new List(); - foreach (ThingDef current in from d in DefDatabase.AllDefs + List list26 = new List(); + foreach (ThingDef item in from d in DefDatabase.AllDefs where d.category == ThingCategory.Plant && d.plant.reproduces select d) { - ThingDef localDef = current; - list.Add(new FloatMenuOption(localDef.LabelCap, delegate + ThingDef localDef4 = item; + list26.Add(new FloatMenuOption(localDef4.LabelCap, (Action)delegate { - Plant plant = GenPlantReproduction.TryReproduceFrom(UI.MouseCell(), localDef, SeedTargFindMode.Reproduce, Find.VisibleMap); + Plant plant = GenPlantReproduction.TryReproduceFrom(UI.MouseCell(), localDef4, SeedTargFindMode.Reproduce, Find.VisibleMap); if (plant != null) { - Find.VisibleMap.debugDrawer.FlashCell(plant.Position, 0f, null); + Find.VisibleMap.debugDrawer.FlashCell(plant.Position, 0f, (string)null); Find.VisibleMap.debugDrawer.FlashLine(UI.MouseCell(), plant.Position); } else { - Find.VisibleMap.debugDrawer.FlashCell(UI.MouseCell(), 0f, null); + Find.VisibleMap.debugDrawer.FlashCell(UI.MouseCell(), 0f, (string)null); } }, MenuOptionPriority.Default, null, null, 0f, null, null)); } - Find.WindowStack.Add(new FloatMenu(list)); + Find.WindowStack.Add(new FloatMenu(list26)); }); this.DoGap(); - base.DebugToolMap("Tool: Regen section", delegate + base.DebugToolMap("Tool: Regen section", (Action)delegate { Find.VisibleMap.mapDrawer.SectionAt(UI.MouseCell()).RegenerateAllLayers(); }); - base.DebugToolMap("Tool: Randomize color", delegate + base.DebugToolMap("Tool: Randomize color", (Action)delegate { - foreach (Thing current in Find.VisibleMap.thingGrid.ThingsAt(UI.MouseCell())) + foreach (Thing item in Find.VisibleMap.thingGrid.ThingsAt(UI.MouseCell())) { - CompColorable compColorable = current.TryGetComp(); + CompColorable compColorable = item.TryGetComp(); if (compColorable != null) { - current.SetColor(GenColor.RandomColorOpaque(), true); + item.SetColor(GenColor.RandomColorOpaque(), true); } } }); - base.DebugToolMap("Tool: Rot 1 day", delegate + base.DebugToolMap("Tool: Rot 1 day", (Action)delegate { - foreach (Thing current in Find.VisibleMap.thingGrid.ThingsAt(UI.MouseCell())) + foreach (Thing item in Find.VisibleMap.thingGrid.ThingsAt(UI.MouseCell())) { - CompRottable compRottable = current.TryGetComp(); + CompRottable compRottable = item.TryGetComp(); if (compRottable != null) { compRottable.RotProgress += 60000f; } } }); - base.DebugToolMap("Tool: Fuel -20%", delegate + base.DebugToolMap("Tool: Fuel -20%", (Action)delegate { - foreach (Thing current in Find.VisibleMap.thingGrid.ThingsAt(UI.MouseCell())) + foreach (Thing item in Find.VisibleMap.thingGrid.ThingsAt(UI.MouseCell())) { - CompRefuelable compRefuelable = current.TryGetComp(); + CompRefuelable compRefuelable = item.TryGetComp(); if (compRefuelable != null) { - compRefuelable.ConsumeFuel(compRefuelable.Props.fuelCapacity * 0.2f); + compRefuelable.ConsumeFuel((float)(compRefuelable.Props.fuelCapacity * 0.20000000298023224)); } } }); - base.DebugToolMap("Tool: Break down...", delegate + base.DebugToolMap("Tool: Break down...", (Action)delegate { - foreach (Thing current in Find.VisibleMap.thingGrid.ThingsAt(UI.MouseCell())) + foreach (Thing item in Find.VisibleMap.thingGrid.ThingsAt(UI.MouseCell())) { - CompBreakdownable compBreakdownable = current.TryGetComp(); + CompBreakdownable compBreakdownable = item.TryGetComp(); if (compBreakdownable != null && !compBreakdownable.BrokenDown) { compBreakdownable.DoBreakdown(); } } }); - base.DebugAction("Tool: Use scatterer", delegate + base.DebugAction("Tool: Use scatterer", (Action)delegate { Find.WindowStack.Add(new Dialog_DebugOptionListLister(DebugTools_MapGen.Options_Scatterers())); }); - base.DebugAction("Tool: BaseGen", delegate + base.DebugAction("Tool: BaseGen", (Action)delegate() { - List list = new List(); - foreach (string current in (from x in DefDatabase.AllDefs - select x.symbol).Distinct()) + List list25 = new List(); + foreach (string item in (from x in DefDatabase.AllDefs + select x.symbol).Distinct()) { - string localSymbol = current; - list.Add(new DebugMenuOption(current, DebugMenuOptionMode.Action, delegate + string localSymbol = item; + list25.Add(new DebugMenuOption(item, DebugMenuOptionMode.Action, (Action)delegate { - DebugTool tool = null; - IntVec3 firstCorner; - tool = new DebugTool("first corner...", delegate + DebugTool tool3 = null; + tool3 = new DebugTool("first corner...", (Action)delegate { - firstCorner = UI.MouseCell(); - DebugTools.curTool = new DebugTool("second corner...", delegate + IntVec3 firstCorner2 = UI.MouseCell(); + DebugTools.curTool = new DebugTool("second corner...", (Action)delegate { - IntVec3 second = UI.MouseCell(); - CellRect rect = CellRect.FromLimits(firstCorner, second).ClipInsideMap(Find.VisibleMap); + IntVec3 second2 = UI.MouseCell(); + CellRect rect = CellRect.FromLimits(firstCorner2, second2).ClipInsideMap(Find.VisibleMap); BaseGen.globalSettings.map = Find.VisibleMap; BaseGen.symbolStack.Push(localSymbol, rect); BaseGen.Generate(); - DebugTools.curTool = tool; - }, firstCorner); + DebugTools.curTool = tool3; + }, firstCorner2); }, null); - DebugTools.curTool = tool; + DebugTools.curTool = tool3; })); } - Find.WindowStack.Add(new Dialog_DebugOptionListLister(list)); + Find.WindowStack.Add(new Dialog_DebugOptionListLister(list25)); }); - base.DebugToolMap("Tool: Make roof", delegate + base.DebugToolMap("Tool: Make roof", (Action)delegate { - CellRect.CellRectIterator iterator = CellRect.CenteredOn(UI.MouseCell(), 1).GetIterator(); - while (!iterator.Done()) + CellRect.CellRectIterator iterator2 = CellRect.CenteredOn(UI.MouseCell(), 1).GetIterator(); + while (!iterator2.Done()) { - Find.VisibleMap.roofGrid.SetRoof(iterator.Current, RoofDefOf.RoofConstructed); - iterator.MoveNext(); + Find.VisibleMap.roofGrid.SetRoof(iterator2.Current, RoofDefOf.RoofConstructed); + iterator2.MoveNext(); } }); - base.DebugToolMap("Tool: Delete roof", delegate + base.DebugToolMap("Tool: Delete roof", (Action)delegate { CellRect.CellRectIterator iterator = CellRect.CenteredOn(UI.MouseCell(), 1).GetIterator(); while (!iterator.Done()) @@ -755,84 +862,92 @@ private void DoListingItems_MapTools() iterator.MoveNext(); } }); - base.DebugToolMap("Tool: Toggle trap status", delegate + base.DebugToolMap("Tool: Toggle trap status", (Action)delegate { - foreach (Thing current in Find.VisibleMap.thingGrid.ThingsAt(UI.MouseCell()).ToList()) + List.Enumerator enumerator29 = Find.VisibleMap.thingGrid.ThingsAt(UI.MouseCell()).ToList().GetEnumerator(); + try { - Building_Trap building_Trap = current as Building_Trap; - if (building_Trap != null) + while (enumerator29.MoveNext()) { - if (building_Trap.Armed) - { - building_Trap.Spring(null); - } - else + Thing current29 = enumerator29.Current; + Building_Trap building_Trap = current29 as Building_Trap; + if (building_Trap != null) { - Building_TrapRearmable building_TrapRearmable = building_Trap as Building_TrapRearmable; - if (building_TrapRearmable != null) + if (building_Trap.Armed) { - building_TrapRearmable.Rearm(); + building_Trap.Spring(null); + } + else + { + Building_TrapRearmable building_TrapRearmable = building_Trap as Building_TrapRearmable; + if (building_TrapRearmable != null) + { + building_TrapRearmable.Rearm(); + } } } } } + finally + { + ((IDisposable)(object)enumerator29).Dispose(); + } }); - base.DebugToolMap("Tool: Add trap memory", delegate + base.DebugToolMap("Tool: Add trap memory", (Action)delegate { - foreach (Faction current in Find.World.factionManager.AllFactions) + foreach (Faction allFaction in Find.World.factionManager.AllFactions) { - current.TacticalMemory.TrapRevealed(UI.MouseCell(), Find.VisibleMap); + allFaction.TacticalMemory.TrapRevealed(UI.MouseCell(), Find.VisibleMap); } Find.VisibleMap.debugDrawer.FlashCell(UI.MouseCell(), 0f, "added"); }); - base.DebugToolMap("Tool: Test flood unfog", delegate + base.DebugToolMap("Tool: Test flood unfog", (Action)delegate { FloodFillerFog.DebugFloodUnfog(UI.MouseCell(), Find.VisibleMap); }); - base.DebugToolMap("Tool: Flash closewalk cell 30", delegate + base.DebugToolMap("Tool: Flash closewalk cell 30", (Action)delegate { - IntVec3 c = CellFinder.RandomClosewalkCellNear(UI.MouseCell(), Find.VisibleMap, 30, null); - Find.VisibleMap.debugDrawer.FlashCell(c, 0f, null); + IntVec3 c6 = CellFinder.RandomClosewalkCellNear(UI.MouseCell(), Find.VisibleMap, 30, null); + Find.VisibleMap.debugDrawer.FlashCell(c6, 0f, (string)null); }); - base.DebugToolMap("Tool: Flash walk path", delegate + base.DebugToolMap("Tool: Flash walk path", (Action)delegate { WalkPathFinder.DebugFlashWalkPath(UI.MouseCell(), 8); }); - base.DebugToolMap("Tool: Flash skygaze cell", delegate + base.DebugToolMap("Tool: Flash skygaze cell", (Action)delegate { - Pawn pawn = Find.VisibleMap.mapPawns.FreeColonists.First(); - IntVec3 c; - RCellFinder.TryFindSkygazeCell(UI.MouseCell(), pawn, out c); - Find.VisibleMap.debugDrawer.FlashCell(c, 0f, null); - MoteMaker.ThrowText(c.ToVector3Shifted(), Find.VisibleMap, "for " + pawn.Label, Color.white, -1f); + Pawn pawn9 = Find.VisibleMap.mapPawns.FreeColonists.First(); + IntVec3 c5 = default(IntVec3); + RCellFinder.TryFindSkygazeCell(UI.MouseCell(), pawn9, out c5); + Find.VisibleMap.debugDrawer.FlashCell(c5, 0f, (string)null); + MoteMaker.ThrowText(c5.ToVector3Shifted(), Find.VisibleMap, "for " + pawn9.Label, Color.white, -1f); }); - base.DebugToolMap("Tool: Flash direct flee dest", delegate + base.DebugToolMap("Tool: Flash direct flee dest", (Action)delegate { - Pawn pawn = Find.Selector.SingleSelectedThing as Pawn; - IntVec3 c; - if (pawn == null) + Pawn pawn8 = Find.Selector.SingleSelectedThing as Pawn; + IntVec3 c4 = default(IntVec3); + if (pawn8 == null) { Find.VisibleMap.debugDrawer.FlashCell(UI.MouseCell(), 0f, "select a pawn"); } - else if (RCellFinder.TryFindDirectFleeDestination(UI.MouseCell(), 9f, pawn, out c)) + else if (RCellFinder.TryFindDirectFleeDestination(UI.MouseCell(), 9f, pawn8, out c4)) { - Find.VisibleMap.debugDrawer.FlashCell(c, 0.5f, null); + Find.VisibleMap.debugDrawer.FlashCell(c4, 0.5f, (string)null); } else { Find.VisibleMap.debugDrawer.FlashCell(UI.MouseCell(), 0.8f, "not found"); } }); - base.DebugAction("Tool: Flash spectators cells", delegate + base.DebugAction("Tool: Flash spectators cells", (Action)delegate() { - Action act = delegate(bool bestSideOnly) + Action act4 = (Action)delegate(bool bestSideOnly) { - DebugTool tool = null; - IntVec3 firstCorner; - tool = new DebugTool("first watch rect corner...", delegate + DebugTool tool2 = null; + tool2 = new DebugTool("first watch rect corner...", (Action)delegate() { - firstCorner = UI.MouseCell(); - DebugTools.curTool = new DebugTool("second watch rect corner...", delegate + IntVec3 firstCorner = UI.MouseCell(); + DebugTools.curTool = new DebugTool("second watch rect corner...", (Action)delegate() { IntVec3 second = UI.MouseCell(); CellRect spectateRect = CellRect.FromLimits(firstCorner, second).ClipInsideMap(Find.VisibleMap); @@ -842,91 +957,90 @@ private void DoListingItems_MapTools() allowedSides = SpectatorCellFinder.FindSingleBestSide(spectateRect, Find.VisibleMap, SpectateRectSide.All, 1); } SpectatorCellFinder.DebugFlashPotentialSpectatorCells(spectateRect, Find.VisibleMap, allowedSides, 1); - DebugTools.curTool = tool; + DebugTools.curTool = tool2; }, firstCorner); }, null); - DebugTools.curTool = tool; + DebugTools.curTool = tool2; }; - List list = new List(); - list.Add(new DebugMenuOption("All sides", DebugMenuOptionMode.Action, delegate + List list24 = new List(); + list24.Add(new DebugMenuOption("All sides", DebugMenuOptionMode.Action, (Action)delegate { - act(false); + act4(false); })); - list.Add(new DebugMenuOption("Best side only", DebugMenuOptionMode.Action, delegate + list24.Add(new DebugMenuOption("Best side only", DebugMenuOptionMode.Action, (Action)delegate { - act(true); + act4(true); })); - Find.WindowStack.Add(new Dialog_DebugOptionListLister(list)); + Find.WindowStack.Add(new Dialog_DebugOptionListLister(list24)); }); - base.DebugAction("Tool: Check reachability", delegate + base.DebugAction("Tool: Check reachability", (Action)delegate { - List list = new List(); - TraverseMode[] array = (TraverseMode[])Enum.GetValues(typeof(TraverseMode)); - for (int i = 0; i < array.Length; i++) + List list23 = new List(); + TraverseMode[] array3 = (TraverseMode[])Enum.GetValues(typeof(TraverseMode)); + DebugTool tool; + for (int num11 = 0; num11 < array3.Length; num11++) { - TraverseMode traverseMode3 = array[i]; - TraverseMode traverseMode = traverseMode3; - list.Add(new DebugMenuOption(traverseMode3.ToString(), DebugMenuOptionMode.Action, delegate + TraverseMode traverseMode2 = array3[num11]; + TraverseMode traverseMode = traverseMode2; + list23.Add(new DebugMenuOption(((Enum)(object)traverseMode2).ToString(), DebugMenuOptionMode.Action, (Action)delegate { - DebugTool tool = null; - IntVec3 from; - Pawn fromPawn; - tool = new DebugTool("from...", delegate + tool = null; + tool = new DebugTool("from...", (Action)delegate { - from = UI.MouseCell(); - fromPawn = from.GetFirstPawn(Find.VisibleMap); - string text = "to..."; + IntVec3 from = UI.MouseCell(); + Pawn fromPawn = from.GetFirstPawn(Find.VisibleMap); + string text2 = "to..."; if (fromPawn != null) { - text = text + " (pawn=" + fromPawn.LabelShort + ")"; + text2 = text2 + " (pawn=" + fromPawn.LabelShort + ")"; } - DebugTools.curTool = new DebugTool(text, delegate + DebugTools.curTool = new DebugTool(text2, (Action)delegate { DebugTools.curTool = tool; - }, delegate + }, (Action)delegate { - IntVec3 c = UI.MouseCell(); - bool flag; - IntVec3 intVec; + IntVec3 c3 = UI.MouseCell(); + bool flag2; + IntVec3 intVec3; if (fromPawn != null) { - TraverseMode traverseMode2 = traverseMode; - flag = fromPawn.CanReach(c, PathEndMode.OnCell, Danger.Deadly, false, traverseMode2); - intVec = fromPawn.Position; + TraverseMode mode = traverseMode; + flag2 = fromPawn.CanReach(c3, PathEndMode.OnCell, Danger.Deadly, false, mode); + intVec3 = fromPawn.Position; } else { - flag = Find.VisibleMap.reachability.CanReach(from, c, PathEndMode.OnCell, traverseMode, Danger.Deadly); - intVec = from; + flag2 = Find.VisibleMap.reachability.CanReach(from, c3, PathEndMode.OnCell, traverseMode, Danger.Deadly); + intVec3 = from; } - Color color = (!flag) ? Color.red : Color.green; - Widgets.DrawLine(intVec.ToUIPosition(), c.ToUIPosition(), color, 2f); + Color color = (!flag2) ? Color.red : Color.green; + Widgets.DrawLine(intVec3.ToUIPosition(), c3.ToUIPosition(), color, 2f); }); }, null); DebugTools.curTool = tool; })); } - Find.WindowStack.Add(new Dialog_DebugOptionListLister(list)); + Find.WindowStack.Add(new Dialog_DebugOptionListLister(list23)); }); - base.DebugToolMapForPawns("Tool: Flash TryFindRandomPawnExitCell", delegate(Pawn p) + base.DebugToolMapForPawns("Tool: Flash TryFindRandomPawnExitCell", (Action)delegate(Pawn p) { - IntVec3 intVec; - if (CellFinder.TryFindRandomPawnExitCell(p, out intVec)) + IntVec3 intVec2 = default(IntVec3); + if (CellFinder.TryFindRandomPawnExitCell(p, out intVec2)) { - p.Map.debugDrawer.FlashCell(intVec, 0.5f, null); - p.Map.debugDrawer.FlashLine(p.Position, intVec); + p.Map.debugDrawer.FlashCell(intVec2, 0.5f, (string)null); + p.Map.debugDrawer.FlashLine(p.Position, intVec2); } else { p.Map.debugDrawer.FlashCell(p.Position, 0.2f, "no exit cell"); } }); - base.DebugToolMapForPawns("Tool: RandomSpotJustOutsideColony", delegate(Pawn p) + base.DebugToolMapForPawns("Tool: RandomSpotJustOutsideColony", (Action)delegate(Pawn p) { - IntVec3 intVec; + IntVec3 intVec = default(IntVec3); if (RCellFinder.TryFindRandomSpotJustOutsideColony(p, out intVec)) { - p.Map.debugDrawer.FlashCell(intVec, 0.5f, null); + p.Map.debugDrawer.FlashCell(intVec, 0.5f, (string)null); p.Map.debugDrawer.FlashLine(p.Position, intVec); } else @@ -936,334 +1050,335 @@ private void DoListingItems_MapTools() }); this.DoGap(); this.DoLabel("Tools - Pawns"); - base.DebugToolMapForPawns("Tool: Damage to down", delegate(Pawn p) + base.DebugToolMapForPawns("Tool: Damage to down", (Action)delegate(Pawn p) { HealthUtility.DamageUntilDowned(p); }); - base.DebugToolMapForPawns("Tool: Damage to death", delegate(Pawn p) + base.DebugToolMapForPawns("Tool: Damage to death", (Action)delegate(Pawn p) { HealthUtility.DamageUntilDead(p); }); - base.DebugToolMap("Tool: Damage held pawn to death", delegate + base.DebugToolMap("Tool: Damage held pawn to death", (Action)delegate { - foreach (Thing current in Find.VisibleMap.thingGrid.ThingsAt(UI.MouseCell()).ToList()) + List.Enumerator enumerator27 = Find.VisibleMap.thingGrid.ThingsAt(UI.MouseCell()).ToList().GetEnumerator(); + try { - Pawn pawn = current as Pawn; - if (pawn != null && pawn.carryTracker.CarriedThing != null && pawn.carryTracker.CarriedThing is Pawn) + while (enumerator27.MoveNext()) { - HealthUtility.DamageUntilDead((Pawn)pawn.carryTracker.CarriedThing); + Thing current27 = enumerator27.Current; + Pawn pawn7 = current27 as Pawn; + if (pawn7 != null && pawn7.carryTracker.CarriedThing != null && pawn7.carryTracker.CarriedThing is Pawn) + { + HealthUtility.DamageUntilDead((Pawn)pawn7.carryTracker.CarriedThing); + } } } + finally + { + ((IDisposable)(object)enumerator27).Dispose(); + } }); - base.DebugToolMapForPawns("Tool: Surgery fail minor", delegate(Pawn p) + base.DebugToolMapForPawns("Tool: Surgery fail minor", (Action)delegate(Pawn p) { - BodyPartRecord bodyPartRecord = p.health.hediffSet.GetNotMissingParts(BodyPartHeight.Undefined, BodyPartDepth.Undefined).RandomElement(); - Log.Message("part is " + bodyPartRecord); - HealthUtility.GiveInjuriesOperationFailureMinor(p, bodyPartRecord); + BodyPartRecord bodyPartRecord2 = p.health.hediffSet.GetNotMissingParts(BodyPartHeight.Undefined, BodyPartDepth.Undefined).RandomElement(); + Log.Message("part is " + bodyPartRecord2); + HealthUtility.GiveInjuriesOperationFailureMinor(p, bodyPartRecord2); }); - base.DebugToolMapForPawns("Tool: Surgery fail catastrophic", delegate(Pawn p) + base.DebugToolMapForPawns("Tool: Surgery fail catastrophic", (Action)delegate(Pawn p) { - BodyPartRecord bodyPartRecord = p.health.hediffSet.GetNotMissingParts(BodyPartHeight.Undefined, BodyPartDepth.Undefined).RandomElement(); + BodyPartRecord bodyPartRecord = p.health.hediffSet.GetNotMissingParts(BodyPartHeight.Undefined, BodyPartDepth.Undefined).RandomElement(); Log.Message("part is " + bodyPartRecord); HealthUtility.GiveInjuriesOperationFailureCatastrophic(p, bodyPartRecord); }); - base.DebugToolMapForPawns("Tool: Surgery fail ridiculous", delegate(Pawn p) + base.DebugToolMapForPawns("Tool: Surgery fail ridiculous", (Action)delegate(Pawn p) { HealthUtility.GiveInjuriesOperationFailureRidiculous(p); }); - base.DebugToolMapForPawns("Tool: Restore body part...", delegate(Pawn p) + base.DebugToolMapForPawns("Tool: Restore body part...", (Action)delegate(Pawn p) { Find.WindowStack.Add(new Dialog_DebugOptionListLister(DebugTools_Health.Options_RestorePart(p))); }); - base.DebugAction("Tool: Apply damage...", delegate + base.DebugAction("Tool: Apply damage...", (Action)delegate { Find.WindowStack.Add(new Dialog_DebugOptionListLister(DebugTools_Health.Options_ApplyDamage())); }); - base.DebugAction("Tool: Add Hediff...", delegate + base.DebugAction("Tool: Add Hediff...", (Action)delegate { Find.WindowStack.Add(new Dialog_DebugOptionListLister(DebugTools_Health.Options_AddHediff())); }); - base.DebugToolMapForPawns("Tool: Heal random injury (10)", delegate(Pawn p) + base.DebugToolMapForPawns("Tool: Heal random injury (10)", (Action)delegate(Pawn p) { - Hediff_Injury hediff_Injury; + Hediff_Injury hediff_Injury = default(Hediff_Injury); if ((from x in p.health.hediffSet.GetHediffs() where x.CanHealNaturally() || x.CanHealFromTending() - select x).TryRandomElement(out hediff_Injury)) + select x).TryRandomElement(out hediff_Injury)) { hediff_Injury.Heal(10f); } }); - base.DebugToolMapForPawns("Tool: Activate HediffGiver", delegate(Pawn p) + base.DebugToolMapForPawns("Tool: Activate HediffGiver", (Action)delegate(Pawn p) { - List list = new List(); + List list22 = new List(); if (p.RaceProps.hediffGiverSets != null) { - foreach (HediffGiver current in p.RaceProps.hediffGiverSets.SelectMany((HediffGiverSetDef set) => set.hediffGivers)) + foreach (HediffGiver item in p.RaceProps.hediffGiverSets.SelectMany((Func>)((HediffGiverSetDef set) => set.hediffGivers))) { - HediffGiver localHdg = current; - list.Add(new FloatMenuOption(localHdg.hediff.defName, delegate + HediffGiver localHdg = item; + list22.Add(new FloatMenuOption(localHdg.hediff.defName, (Action)delegate() { localHdg.TryApply(p, null); }, MenuOptionPriority.Default, null, null, 0f, null, null)); } } - if (list.Any()) + if (list22.Any()) { - Find.WindowStack.Add(new FloatMenu(list)); + Find.WindowStack.Add(new FloatMenu(list22)); this.DustPuffFrom(p); } }); - base.DebugToolMapForPawns("Tool: Give birth", delegate(Pawn p) + base.DebugToolMapForPawns("Tool: Give birth", (Action)delegate(Pawn p) { Hediff_Pregnant.DoBirthSpawn(p, null); this.DustPuffFrom(p); }); - base.DebugToolMapForPawns("Tool: Add/remove pawn relation", delegate(Pawn p) + base.DebugToolMapForPawns("Tool: Add/remove pawn relation", (Action)delegate(Pawn p) { - if (!p.RaceProps.IsFlesh) - { - return; - } - Action act = delegate(bool add) + if (p.RaceProps.IsFlesh) { - if (add) + Action act3 = (Action)delegate(bool add) { - List list2 = new List(); - foreach (PawnRelationDef current in DefDatabase.AllDefs) + if (add) { - if (!current.implied) + List list19 = new List(); + foreach (PawnRelationDef allDef in DefDatabase.AllDefs) { - PawnRelationDef defLocal = current; - list2.Add(new DebugMenuOption(defLocal.defName, DebugMenuOptionMode.Action, delegate + if (!allDef.implied) { - List list4 = new List(); - IOrderedEnumerable orderedEnumerable = from x in PawnsFinder.AllMapsAndWorld_Alive - where x.RaceProps.IsFlesh - orderby x.def == p.def descending, x.IsWorldPawn() - select x; - foreach (Pawn current2 in orderedEnumerable) + PawnRelationDef defLocal = allDef; + list19.Add(new DebugMenuOption(defLocal.defName, DebugMenuOptionMode.Action, (Action)delegate() { - if (p != current2) + List list21 = new List(); + IOrderedEnumerable orderedEnumerable = from x in PawnsFinder.AllMapsAndWorld_Alive + where x.RaceProps.IsFlesh + orderby x.def == p.def descending, x.IsWorldPawn() + select x; + foreach (Pawn item in orderedEnumerable) { - if (!defLocal.familyByBloodRelation || current2.def == p.def) + if (p != item && (!defLocal.familyByBloodRelation || item.def == p.def) && !p.relations.DirectRelationExists(defLocal, item)) { - if (!p.relations.DirectRelationExists(defLocal, current2)) + Pawn otherLocal3 = item; + list21.Add(new DebugMenuOption(otherLocal3.LabelShort + " (" + otherLocal3.KindLabel + ")", DebugMenuOptionMode.Action, (Action)delegate() { - Pawn otherLocal = current2; - list4.Add(new DebugMenuOption(otherLocal.LabelShort + " (" + otherLocal.KindLabel + ")", DebugMenuOptionMode.Action, delegate - { - p.relations.AddDirectRelation(defLocal, otherLocal); - })); - } + _003CDoListingItems_MapTools_003Ec__AnonStorey5A6._003CDoListingItems_MapTools_003Ec__AnonStorey5A7 _003CDoListingItems_MapTools_003Ec__AnonStorey5A; + p.relations.AddDirectRelation(_003CDoListingItems_MapTools_003Ec__AnonStorey5A.defLocal, otherLocal3); + })); } } - } - Find.WindowStack.Add(new Dialog_DebugOptionListLister(list4)); - })); + Find.WindowStack.Add(new Dialog_DebugOptionListLister(list21)); + })); + } } + Find.WindowStack.Add(new Dialog_DebugOptionListLister(list19)); } - Find.WindowStack.Add(new Dialog_DebugOptionListLister(list2)); - } - else - { - List list3 = new List(); - List directRelations = p.relations.DirectRelations; - for (int i = 0; i < directRelations.Count; i++) + else { - DirectPawnRelation rel = directRelations[i]; - list3.Add(new DebugMenuOption(rel.def.defName + " - " + rel.otherPawn.LabelShort, DebugMenuOptionMode.Action, delegate + List list20 = new List(); + List directRelations = p.relations.DirectRelations; + for (int num10 = 0; num10 < directRelations.Count; num10++) { - p.relations.RemoveDirectRelation(rel); - })); + DirectPawnRelation rel = directRelations[num10]; + list20.Add(new DebugMenuOption(rel.def.defName + " - " + rel.otherPawn.LabelShort, DebugMenuOptionMode.Action, (Action)delegate() + { + p.relations.RemoveDirectRelation(rel); + })); + } + Find.WindowStack.Add(new Dialog_DebugOptionListLister(list20)); } - Find.WindowStack.Add(new Dialog_DebugOptionListLister(list3)); - } - }; - List list = new List(); - list.Add(new DebugMenuOption("Add", DebugMenuOptionMode.Action, delegate - { - act(true); - })); - list.Add(new DebugMenuOption("Remove", DebugMenuOptionMode.Action, delegate - { - act(false); - })); - Find.WindowStack.Add(new Dialog_DebugOptionListLister(list)); + }; + List list18 = new List(); + list18.Add(new DebugMenuOption("Add", DebugMenuOptionMode.Action, (Action)delegate + { + act3(true); + })); + list18.Add(new DebugMenuOption("Remove", DebugMenuOptionMode.Action, (Action)delegate + { + act3(false); + })); + Find.WindowStack.Add(new Dialog_DebugOptionListLister(list18)); + } }); - base.DebugToolMapForPawns("Tool: Add opinion thoughts about", delegate(Pawn p) + base.DebugToolMapForPawns("Tool: Add opinion thoughts about", (Action)delegate(Pawn p) { - if (!p.RaceProps.Humanlike) - { - return; - } - Action act = delegate(bool good) + if (p.RaceProps.Humanlike) { - foreach (Pawn current in from x in p.Map.mapPawns.AllPawnsSpawned - where x.RaceProps.Humanlike - select x) + Action act2 = (Action)delegate(bool good) { - if (p != current) + foreach (Pawn item in from x in p.Map.mapPawns.AllPawnsSpawned + where x.RaceProps.Humanlike + select x) { - IEnumerable source = DefDatabase.AllDefs.Where((ThoughtDef x) => typeof(Thought_MemorySocial).IsAssignableFrom(x.thoughtClass) && ((good && x.stages[0].baseOpinionOffset > 0f) || (!good && x.stages[0].baseOpinionOffset < 0f))); - if (source.Any()) + if (p != item) { - int num = Rand.Range(2, 5); - for (int i = 0; i < num; i++) + IEnumerable source3 = DefDatabase.AllDefs.Where((Func)((ThoughtDef x) => typeof(Thought_MemorySocial).IsAssignableFrom(x.thoughtClass) && ((good && x.stages[0].baseOpinionOffset > 0.0) || (!good && x.stages[0].baseOpinionOffset < 0.0)))); + if (source3.Any()) { - ThoughtDef def = source.RandomElement(); - current.needs.mood.thoughts.memories.TryGainMemory(def, p); + int num8 = Rand.Range(2, 5); + for (int num9 = 0; num9 < num8; num9++) + { + ThoughtDef def2 = source3.RandomElement(); + item.needs.mood.thoughts.memories.TryGainMemory(def2, p); + } } } } - } - }; - List list = new List(); - list.Add(new DebugMenuOption("Good", DebugMenuOptionMode.Action, delegate - { - act(true); - })); - list.Add(new DebugMenuOption("Bad", DebugMenuOptionMode.Action, delegate - { - act(false); - })); - Find.WindowStack.Add(new Dialog_DebugOptionListLister(list)); + }; + List list17 = new List(); + list17.Add(new DebugMenuOption("Good", DebugMenuOptionMode.Action, (Action)delegate + { + act2(true); + })); + list17.Add(new DebugMenuOption("Bad", DebugMenuOptionMode.Action, (Action)delegate + { + act2(false); + })); + Find.WindowStack.Add(new Dialog_DebugOptionListLister(list17)); + } }); - base.DebugToolMapForPawns("Tool: Force vomit...", delegate(Pawn p) + base.DebugToolMapForPawns("Tool: Force vomit...", (Action)delegate(Pawn p) { - p.jobs.StartJob(new Job(JobDefOf.Vomit), JobCondition.InterruptForced, null, true, true, null, null); + p.jobs.StartJob(new Job(JobDefOf.Vomit), JobCondition.InterruptForced, null, true, true, null, default(JobTag?)); }); - base.DebugToolMap("Tool: Food -20%", delegate + base.DebugToolMap("Tool: Food -20%", (Action)delegate { this.OffsetNeed(NeedDefOf.Food, -0.2f); }); - base.DebugToolMap("Tool: Rest -20%", delegate + base.DebugToolMap("Tool: Rest -20%", (Action)delegate { this.OffsetNeed(NeedDefOf.Rest, -0.2f); }); - base.DebugToolMap("Tool: Joy -20%", delegate + base.DebugToolMap("Tool: Joy -20%", (Action)delegate { this.OffsetNeed(NeedDefOf.Joy, -0.2f); }); - base.DebugToolMap("Tool: Chemical -20%", delegate + base.DebugToolMap("Tool: Chemical -20%", (Action)delegate { - List allDefsListForReading = DefDatabase.AllDefsListForReading; - for (int i = 0; i < allDefsListForReading.Count; i++) + List allDefsListForReading2 = DefDatabase.AllDefsListForReading; + for (int num7 = 0; num7 < allDefsListForReading2.Count; num7++) { - if (typeof(Need_Chemical).IsAssignableFrom(allDefsListForReading[i].needClass)) + if (typeof(Need_Chemical).IsAssignableFrom(allDefsListForReading2[num7].needClass)) { - this.OffsetNeed(allDefsListForReading[i], -0.2f); + this.OffsetNeed(allDefsListForReading2[num7], -0.2f); } } }); - base.DebugToolMapForPawns("Tool: Set skill", delegate(Pawn p) + base.DebugToolMapForPawns("Tool: Set skill", (Action)delegate(Pawn p) { - if (p.skills == null) - { - return; - } - List list = new List(); - foreach (SkillDef current in DefDatabase.AllDefs) + if (p.skills != null) { - SkillDef localDef = current; - list.Add(new DebugMenuOption(localDef.defName, DebugMenuOptionMode.Action, delegate + List list15 = new List(); + foreach (SkillDef allDef in DefDatabase.AllDefs) { - List list2 = new List(); - for (int i = 0; i <= 20; i++) + SkillDef localDef3 = allDef; + list15.Add(new DebugMenuOption(localDef3.defName, DebugMenuOptionMode.Action, (Action)delegate() { - int level = i; - list2.Add(new DebugMenuOption(level.ToString(), DebugMenuOptionMode.Action, delegate + List list16 = new List(); + for (int num6 = 0; num6 <= 20; num6++) { - SkillRecord skill = p.skills.GetSkill(localDef); - skill.Level = level; - skill.xpSinceLastLevel = skill.XpRequiredForLevelUp / 2f; - })); - } - Find.WindowStack.Add(new Dialog_DebugOptionListLister(list2)); - })); + int level = num6; + list16.Add(new DebugMenuOption(level.ToString(), DebugMenuOptionMode.Action, (Action)delegate() + { + SkillRecord skill = p.skills.GetSkill(localDef3); + skill.Level = level; + skill.xpSinceLastLevel = (float)(skill.XpRequiredForLevelUp / 2.0); + })); + } + Find.WindowStack.Add(new Dialog_DebugOptionListLister(list16)); + })); + } + Find.WindowStack.Add(new Dialog_DebugOptionListLister(list15)); } - Find.WindowStack.Add(new Dialog_DebugOptionListLister(list)); }); - base.DebugToolMapForPawns("Tool: Max skills", delegate(Pawn p) + base.DebugToolMapForPawns("Tool: Max skills", (Action)delegate(Pawn p) { if (p.skills != null) { - foreach (SkillDef current in DefDatabase.AllDefs) + foreach (SkillDef allDef in DefDatabase.AllDefs) { - p.skills.Learn(current, 1E+08f, false); + p.skills.Learn(allDef, 1E+08f, false); } this.DustPuffFrom(p); } if (p.training != null) { - foreach (TrainableDef current2 in DefDatabase.AllDefs) + foreach (TrainableDef allDef2 in DefDatabase.AllDefs) { - Pawn trainer = p.Map.mapPawns.FreeColonistsSpawned.RandomElement(); - bool flag; - if (p.training.CanAssignToTrain(current2, out flag).Accepted) + Pawn trainer = p.Map.mapPawns.FreeColonistsSpawned.RandomElement(); + bool flag = default(bool); + if (p.training.CanAssignToTrain(allDef2, out flag).Accepted) { - p.training.Train(current2, trainer); + p.training.Train(allDef2, trainer); } } } }); - base.DebugAction("Tool: Mental break...", delegate + base.DebugAction("Tool: Mental break...", (Action)delegate() { - List list = new List(); - list.Add(new DebugMenuOption("(log possibles)", DebugMenuOptionMode.Tool, delegate + List list14 = new List(); + list14.Add(new DebugMenuOption("(log possibles)", DebugMenuOptionMode.Tool, (Action)delegate() { - foreach (Pawn current2 in (from t in Find.VisibleMap.thingGrid.ThingsAt(UI.MouseCell()) + foreach (Pawn item in (from t in Find.VisibleMap.thingGrid.ThingsAt(UI.MouseCell()) where t is Pawn select t).Cast()) { - current2.mindState.mentalBreaker.LogPossibleMentalBreaks(); - this.DustPuffFrom(current2); + item.mindState.mentalBreaker.LogPossibleMentalBreaks(); + this.DustPuffFrom(item); } })); - list.Add(new DebugMenuOption("(natural mood break)", DebugMenuOptionMode.Tool, delegate + list14.Add(new DebugMenuOption("(natural mood break)", DebugMenuOptionMode.Tool, (Action)delegate() { - foreach (Pawn current2 in (from t in Find.VisibleMap.thingGrid.ThingsAt(UI.MouseCell()) + foreach (Pawn item in (from t in Find.VisibleMap.thingGrid.ThingsAt(UI.MouseCell()) where t is Pawn select t).Cast()) { - current2.mindState.mentalBreaker.TryDoRandomMoodCausedMentalBreak(); - this.DustPuffFrom(current2); + item.mindState.mentalBreaker.TryDoRandomMoodCausedMentalBreak(); + this.DustPuffFrom(item); } })); - foreach (MentalStateDef current in DefDatabase.AllDefs) + foreach (MentalStateDef allDef in DefDatabase.AllDefs) { - MentalStateDef locBrDef = current; + MentalStateDef locBrDef = allDef; string text = locBrDef.defName; - if (!Find.VisibleMap.mapPawns.FreeColonists.Any((Pawn x) => locBrDef.Worker.StateCanOccur(x))) + if (!Find.VisibleMap.mapPawns.FreeColonists.Any((Func)((Pawn x) => locBrDef.Worker.StateCanOccur(x)))) { text += " [NO]"; } - list.Add(new DebugMenuOption(text, DebugMenuOptionMode.Tool, delegate + list14.Add(new DebugMenuOption(text, DebugMenuOptionMode.Tool, (Action)delegate() { - foreach (Pawn current2 in (from t in Find.VisibleMap.thingGrid.ThingsAt(UI.MouseCell()) + foreach (Pawn item in (from t in Find.VisibleMap.thingGrid.ThingsAt(UI.MouseCell()) where t is Pawn select t).Cast()) { - Pawn locP = current2; + Pawn locP = item; if (locBrDef != MentalStateDefOf.SocialFighting) { - locP.mindState.mentalStateHandler.TryStartMentalState(locBrDef, null, true, false, null); + locP.mindState.mentalStateHandler.TryStartMentalState(locBrDef, (string)null, true, false, null); this.DustPuffFrom(locP); } else { - DebugTools.curTool = new DebugTool("...with", delegate + DebugTools.curTool = new DebugTool("...with", (Action)delegate() { - Pawn pawn = (Pawn)(from t in Find.VisibleMap.thingGrid.ThingsAt(UI.MouseCell()) + Pawn pawn6 = (Pawn)(from t in Find.VisibleMap.thingGrid.ThingsAt(UI.MouseCell()) where t is Pawn - select t).FirstOrDefault(); - if (pawn != null) + select t).FirstOrDefault(); + if (pawn6 != null) { - if (!InteractionUtility.HasAnySocialFightProvokingThought(locP, pawn)) + if (!InteractionUtility.HasAnySocialFightProvokingThought(locP, pawn6)) { - locP.needs.mood.thoughts.memories.TryGainMemory(ThoughtDefOf.Insulted, pawn); - Messages.Message("Dev: auto added negative thought.", locP, MessageSound.Standard); + locP.needs.mood.thoughts.memories.TryGainMemory(ThoughtDefOf.Insulted, pawn6); + Messages.Message("Dev: auto added negative thought.", (Thing)locP, MessageSound.Standard); } - locP.interactions.StartSocialFight(pawn); + locP.interactions.StartSocialFight(pawn6); DebugTools.curTool = null; } }, null); @@ -1271,56 +1386,50 @@ where t is Pawn } })); } - Find.WindowStack.Add(new Dialog_DebugOptionListLister(list)); + Find.WindowStack.Add(new Dialog_DebugOptionListLister(list14)); }); - base.DebugAction("Tool: Give trait...", delegate + base.DebugAction("Tool: Give trait...", (Action)delegate() { - List list = new List(); - foreach (TraitDef current in DefDatabase.AllDefs) + List list13 = new List(); + foreach (TraitDef allDef in DefDatabase.AllDefs) { - TraitDef trDef = current; - for (int j = 0; j < current.degreeDatas.Count; j++) + TraitDef trDef = allDef; + for (int num5 = 0; num5 < allDef.degreeDatas.Count; num5++) { - int i = j; - list.Add(new DebugMenuOption(string.Concat(new object[] + int i2 = num5; + list13.Add(new DebugMenuOption(trDef.degreeDatas[i2].label + " (" + trDef.degreeDatas[num5].degree + ")", DebugMenuOptionMode.Tool, (Action)delegate() { - trDef.degreeDatas[i].label, - " (", - trDef.degreeDatas[j].degree, - ")" - }), DebugMenuOptionMode.Tool, delegate - { - foreach (Pawn current2 in (from t in Find.VisibleMap.thingGrid.ThingsAt(UI.MouseCell()) + foreach (Pawn item2 in (from t in Find.VisibleMap.thingGrid.ThingsAt(UI.MouseCell()) where t is Pawn select t).Cast()) { - if (current2.story != null) + if (item2.story != null) { - Trait item = new Trait(trDef, trDef.degreeDatas[i].degree, false); - current2.story.traits.allTraits.Add(item); - this.DustPuffFrom(current2); + Trait item = new Trait(trDef, trDef.degreeDatas[i2].degree, false); + item2.story.traits.allTraits.Add(item); + this.DustPuffFrom(item2); } } })); } } - Find.WindowStack.Add(new Dialog_DebugOptionListLister(list)); + Find.WindowStack.Add(new Dialog_DebugOptionListLister(list13)); }); - base.DebugToolMapForPawns("Tool: Give good thought", delegate(Pawn p) + base.DebugToolMapForPawns("Tool: Give good thought", (Action)delegate(Pawn p) { if (p.needs.mood != null) { p.needs.mood.thoughts.memories.TryGainMemory(ThoughtDefOf.DebugGood, null); } }); - base.DebugToolMapForPawns("Tool: Give bad thought", delegate(Pawn p) + base.DebugToolMapForPawns("Tool: Give bad thought", (Action)delegate(Pawn p) { if (p.needs.mood != null) { p.needs.mood.thoughts.memories.TryGainMemory(ThoughtDefOf.DebugBad, null); } }); - base.DebugToolMapForPawns("Tool: Make faction hostile", delegate(Pawn p) + base.DebugToolMapForPawns("Tool: Make faction hostile", (Action)delegate(Pawn p) { if (p.Faction != null && !p.Faction.HostileTo(Faction.OfPlayer)) { @@ -1328,7 +1437,7 @@ where t is Pawn this.DustPuffFrom(p); } }); - base.DebugToolMapForPawns("Tool: Make faction neutral", delegate(Pawn p) + base.DebugToolMapForPawns("Tool: Make faction neutral", (Action)delegate(Pawn p) { if (p.Faction != null && p.Faction.HostileTo(Faction.OfPlayer)) { @@ -1336,15 +1445,15 @@ where t is Pawn this.DustPuffFrom(p); } }); - base.DebugToolMap("Tool: Clear bound unfinished things", delegate + base.DebugToolMap("Tool: Clear bound unfinished things", (Action)delegate() { - foreach (Building_WorkTable current in (from t in Find.VisibleMap.thingGrid.ThingsAt(UI.MouseCell()) + foreach (Building_WorkTable item in (from t in Find.VisibleMap.thingGrid.ThingsAt(UI.MouseCell()) where t is Building_WorkTable select t).Cast()) { - foreach (Bill current2 in current.BillStack) + foreach (Bill item2 in item.BillStack) { - Bill_ProductionWithUft bill_ProductionWithUft = current2 as Bill_ProductionWithUft; + Bill_ProductionWithUft bill_ProductionWithUft = item2 as Bill_ProductionWithUft; if (bill_ProductionWithUft != null) { bill_ProductionWithUft.ClearBoundUft(); @@ -1352,183 +1461,199 @@ where t is Building_WorkTable } } }); - base.DebugToolMapForPawns("Tool: Force birthday", delegate(Pawn p) + base.DebugToolMapForPawns("Tool: Force birthday", (Action)delegate(Pawn p) { - p.ageTracker.AgeBiologicalTicks = (long)((p.ageTracker.AgeBiologicalYears + 1) * 3600000 + 1); + p.ageTracker.AgeBiologicalTicks = (p.ageTracker.AgeBiologicalYears + 1) * 3600000 + 1; p.ageTracker.DebugForceBirthdayBiological(); }); - base.DebugToolMapForPawns("Tool: Recruit", delegate(Pawn p) + base.DebugToolMapForPawns("Tool: Recruit", (Action)delegate(Pawn p) { if (p.Faction != Faction.OfPlayer && p.RaceProps.Humanlike) { - InteractionWorker_RecruitAttempt.DoRecruit(p.Map.mapPawns.FreeColonists.RandomElement(), p, 1f, true); + InteractionWorker_RecruitAttempt.DoRecruit(p.Map.mapPawns.FreeColonists.RandomElement(), p, 1f, true); this.DustPuffFrom(p); } }); - base.DebugToolMapForPawns("Tool: Damage apparel", delegate(Pawn p) + base.DebugToolMapForPawns("Tool: Damage apparel", (Action)delegate(Pawn p) { if (p.apparel != null && p.apparel.WornApparelCount > 0) { - p.apparel.WornApparel.RandomElement().TakeDamage(new DamageInfo(DamageDefOf.Deterioration, 30, -1f, null, null, null, DamageInfo.SourceCategory.ThingOrUnknown)); + p.apparel.WornApparel.RandomElement().TakeDamage(new DamageInfo(DamageDefOf.Deterioration, 30, -1f, null, null, null, DamageInfo.SourceCategory.ThingOrUnknown)); this.DustPuffFrom(p); } }); - base.DebugToolMapForPawns("Tool: Tame animal", delegate(Pawn p) + base.DebugToolMapForPawns("Tool: Tame animal", (Action)delegate(Pawn p) { if (p.RaceProps.Animal && p.Faction != Faction.OfPlayer) { - InteractionWorker_RecruitAttempt.DoRecruit(p.Map.mapPawns.FreeColonists.FirstOrDefault(), p, 1f, true); + InteractionWorker_RecruitAttempt.DoRecruit(p.Map.mapPawns.FreeColonists.FirstOrDefault(), p, 1f, true); this.DustPuffFrom(p); } }); - base.DebugToolMapForPawns("Tool: Train animal", delegate(Pawn p) + base.DebugToolMapForPawns("Tool: Train animal", (Action)delegate(Pawn p) { if (p.RaceProps.Animal && p.Faction == Faction.OfPlayer && p.training != null) { - foreach (TrainableDef current in DefDatabase.AllDefs) + foreach (TrainableDef allDef in DefDatabase.AllDefs) { - while (!p.training.IsCompleted(current)) + while (!p.training.IsCompleted(allDef)) { - p.training.Train(current, null); + p.training.Train(allDef, null); } } this.DustPuffFrom(p); } }); - base.DebugToolMapForPawns("Tool: Name animal by nuzzling", delegate(Pawn p) + base.DebugToolMapForPawns("Tool: Name animal by nuzzling", (Action)delegate(Pawn p) { - if ((p.Name == null || p.Name.Numerical) && p.RaceProps.Animal) + if (p.Name != null && !p.Name.Numerical) + return; + if (p.RaceProps.Animal) { - PawnUtility.GiveNameBecauseOfNuzzle(p.Map.mapPawns.FreeColonists.First(), p); + PawnUtility.GiveNameBecauseOfNuzzle(p.Map.mapPawns.FreeColonists.First(), p); this.DustPuffFrom(p); } }); - base.DebugToolMapForPawns("Tool: Try develop bond relation", delegate(Pawn p) + base.DebugToolMapForPawns("Tool: Try develop bond relation", (Action)delegate(Pawn p) { - if (p.Faction == null) + if (p.Faction != null) { - return; - } - if (p.RaceProps.Humanlike) - { - IEnumerable source = from x in p.Map.mapPawns.AllPawnsSpawned - where x.RaceProps.Animal && x.Faction == p.Faction - select x; - if (source.Any()) + if (p.RaceProps.Humanlike) { - RelationsUtility.TryDevelopBondRelation(p, source.RandomElement(), 999999f); + IEnumerable source = from x in p.Map.mapPawns.AllPawnsSpawned + where x.RaceProps.Animal && x.Faction == p.Faction + select x; + if (source.Any()) + { + RelationsUtility.TryDevelopBondRelation(p, source.RandomElement(), 999999f); + } } - } - else if (p.RaceProps.Animal) - { - IEnumerable source2 = from x in p.Map.mapPawns.AllPawnsSpawned - where x.RaceProps.Humanlike && x.Faction == p.Faction - select x; - if (source2.Any()) + else if (p.RaceProps.Animal) { - RelationsUtility.TryDevelopBondRelation(source2.RandomElement(), p, 999999f); + IEnumerable source2 = from x in p.Map.mapPawns.AllPawnsSpawned + where x.RaceProps.Humanlike && x.Faction == p.Faction + select x; + if (source2.Any()) + { + RelationsUtility.TryDevelopBondRelation(source2.RandomElement(), p, 999999f); + } } } }); - base.DebugToolMapForPawns("Tool: Start marriage ceremony", delegate(Pawn p) + base.DebugToolMapForPawns("Tool: Start marriage ceremony", (Action)delegate(Pawn p) { - if (!p.RaceProps.Humanlike) - { - return; - } - List list = new List(); - foreach (Pawn current in from x in p.Map.mapPawns.AllPawnsSpawned - where x.RaceProps.Humanlike - select x) + if (p.RaceProps.Humanlike) { - if (p != current) + List list12 = new List(); + foreach (Pawn item in from x in p.Map.mapPawns.AllPawnsSpawned + where x.RaceProps.Humanlike + select x) { - Pawn otherLocal = current; - list.Add(new DebugMenuOption(otherLocal.LabelShort + " (" + otherLocal.KindLabel + ")", DebugMenuOptionMode.Action, delegate + if (p != item) { - if (!p.relations.DirectRelationExists(PawnRelationDefOf.Fiance, otherLocal)) - { - p.relations.TryRemoveDirectRelation(PawnRelationDefOf.Lover, otherLocal); - p.relations.TryRemoveDirectRelation(PawnRelationDefOf.Spouse, otherLocal); - p.relations.AddDirectRelation(PawnRelationDefOf.Fiance, otherLocal); - Messages.Message("Dev: auto added fiance relation.", p, MessageSound.Standard); - } - if (!p.Map.lordsStarter.TryStartMarriageCeremony(p, otherLocal)) + Pawn otherLocal2 = item; + list12.Add(new DebugMenuOption(otherLocal2.LabelShort + " (" + otherLocal2.KindLabel + ")", DebugMenuOptionMode.Action, (Action)delegate() { - Messages.Message("Could not find any valid marriage site.", MessageSound.Negative); - } - })); + if (!p.relations.DirectRelationExists(PawnRelationDefOf.Fiance, otherLocal2)) + { + p.relations.TryRemoveDirectRelation(PawnRelationDefOf.Lover, otherLocal2); + p.relations.TryRemoveDirectRelation(PawnRelationDefOf.Spouse, otherLocal2); + p.relations.AddDirectRelation(PawnRelationDefOf.Fiance, otherLocal2); + Messages.Message("Dev: auto added fiance relation.", (Thing)p, MessageSound.Standard); + } + if (!p.Map.lordsStarter.TryStartMarriageCeremony(p, otherLocal2)) + { + Messages.Message("Could not find any valid marriage site.", MessageSound.Negative); + } + })); + } } + Find.WindowStack.Add(new Dialog_DebugOptionListLister(list12)); } - Find.WindowStack.Add(new Dialog_DebugOptionListLister(list)); }); - base.DebugToolMapForPawns("Tool: Force interaction", delegate(Pawn p) + base.DebugToolMapForPawns("Tool: Force interaction", (Action)delegate(Pawn p) { - if (p.Faction == null) + if (p.Faction != null) { - return; - } - List list = new List(); - foreach (Pawn current in p.Map.mapPawns.SpawnedPawnsInFaction(p.Faction)) - { - if (current != p) + List list10 = new List(); + List.Enumerator enumerator8 = p.Map.mapPawns.SpawnedPawnsInFaction(p.Faction).GetEnumerator(); + try { - Pawn otherLocal = current; - list.Add(new DebugMenuOption(otherLocal.LabelShort + " (" + otherLocal.KindLabel + ")", DebugMenuOptionMode.Action, delegate + while (enumerator8.MoveNext()) { - List list2 = new List(); - foreach (InteractionDef current2 in DefDatabase.AllDefsListForReading) + Pawn current8 = enumerator8.Current; + if (current8 != p) { - InteractionDef interactionLocal = current2; - list2.Add(new DebugMenuOption(interactionLocal.label, DebugMenuOptionMode.Action, delegate + Pawn otherLocal = current8; + list10.Add(new DebugMenuOption(otherLocal.LabelShort + " (" + otherLocal.KindLabel + ")", DebugMenuOptionMode.Action, (Action)delegate() { - p.interactions.TryInteractWith(otherLocal, interactionLocal); + List list11 = new List(); + List.Enumerator enumerator9 = DefDatabase.AllDefsListForReading.GetEnumerator(); + try + { + while (enumerator9.MoveNext()) + { + InteractionDef current9 = enumerator9.Current; + InteractionDef interactionLocal = current9; + list11.Add(new DebugMenuOption(interactionLocal.label, DebugMenuOptionMode.Action, (Action)delegate() + { + p.interactions.TryInteractWith(otherLocal, interactionLocal); + })); + } + } + finally + { + ((IDisposable)(object)enumerator9).Dispose(); + } + Find.WindowStack.Add(new Dialog_DebugOptionListLister(list11)); })); } - Find.WindowStack.Add(new Dialog_DebugOptionListLister(list2)); - })); + } + } + finally + { + ((IDisposable)(object)enumerator8).Dispose(); } + Find.WindowStack.Add(new Dialog_DebugOptionListLister(list10)); } - Find.WindowStack.Add(new Dialog_DebugOptionListLister(list)); }); - base.DebugAction("Tool: Start party", delegate + base.DebugAction("Tool: Start party", (Action)delegate { if (!Find.VisibleMap.lordsStarter.TryStartParty()) { Messages.Message("Could not find any valid party spot or organizer.", MessageSound.Negative); } }); - base.DebugToolMapForPawns("Tool: Start prison break", delegate(Pawn p) + base.DebugToolMapForPawns("Tool: Start prison break", (Action)delegate(Pawn p) { - if (!p.IsPrisoner) + if (p.IsPrisoner) { - return; + PrisonBreakUtility.StartPrisonBreak(p); } - PrisonBreakUtility.StartPrisonBreak(p); }); - base.DebugToolMapForPawns("Tool: Pass to world", delegate(Pawn p) + base.DebugToolMapForPawns("Tool: Pass to world", (Action)delegate(Pawn p) { p.DeSpawn(); Find.WorldPawns.PassToWorld(p, PawnDiscardDecideMode.KeepForever); }); - base.DebugToolMapForPawns("Tool: Make 1 year older", delegate(Pawn p) + base.DebugToolMapForPawns("Tool: Make 1 year older", (Action)delegate(Pawn p) { p.ageTracker.DebugMake1YearOlder(); }); this.DoGap(); - base.DebugToolMapForPawns("Tool: Try job giver", delegate(Pawn p) + base.DebugToolMapForPawns("Tool: Try job giver", (Action)delegate(Pawn p) { - List list = new List(); - foreach (Type current in typeof(ThinkNode_JobGiver).AllSubclasses()) + List list9 = new List(); + foreach (Type item in typeof(ThinkNode_JobGiver).AllSubclasses()) { - Type localType = current; - list.Add(new DebugMenuOption(localType.Name, DebugMenuOptionMode.Action, delegate + Type localType = item; + list9.Add(new DebugMenuOption(localType.Name, DebugMenuOptionMode.Action, (Action)delegate() { ThinkNode_JobGiver thinkNode_JobGiver = (ThinkNode_JobGiver)Activator.CreateInstance(localType); ThinkResult thinkResult = thinkNode_JobGiver.TryIssueJobPackage(p, default(JobIssueParams)); if (thinkResult.Job != null) { - p.jobs.StartJob(thinkResult.Job, JobCondition.None, null, false, true, null, null); + p.jobs.StartJob(thinkResult.Job, JobCondition.None, null, false, true, null, default(JobTag?)); } else { @@ -1536,40 +1661,40 @@ where x.RaceProps.Humanlike } })); } - Find.WindowStack.Add(new Dialog_DebugOptionListLister(list)); + Find.WindowStack.Add(new Dialog_DebugOptionListLister(list9)); }); - base.DebugToolMapForPawns("Tool: EndCurrentJob(" + JobCondition.InterruptForced.ToString() + ")", delegate(Pawn p) + base.DebugToolMapForPawns("Tool: EndCurrentJob(" + ((Enum)(object)JobCondition.InterruptForced).ToString() + ")", (Action)delegate(Pawn p) { p.jobs.EndCurrentJob(JobCondition.InterruptForced, true); this.DustPuffFrom(p); }); - base.DebugToolMapForPawns("Tool: CheckForJobOverride", delegate(Pawn p) + base.DebugToolMapForPawns("Tool: CheckForJobOverride", (Action)delegate(Pawn p) { p.jobs.CheckForJobOverride(); this.DustPuffFrom(p); }); - base.DebugToolMapForPawns("Tool: Toggle job logging", delegate(Pawn p) + base.DebugToolMapForPawns("Tool: Toggle job logging", (Action)delegate(Pawn p) { p.jobs.debugLog = !p.jobs.debugLog; this.DustPuffFrom(p); MoteMaker.ThrowText(p.DrawPos, p.Map, p.LabelShort + "\n" + ((!p.jobs.debugLog) ? "OFF" : "ON"), -1f); }); - base.DebugToolMapForPawns("Tool: Toggle stance logging", delegate(Pawn p) + base.DebugToolMapForPawns("Tool: Toggle stance logging", (Action)delegate(Pawn p) { p.stances.debugLog = !p.stances.debugLog; this.DustPuffFrom(p); }); this.DoGap(); this.DoLabel("Tools - Spawning"); - base.DebugAction("Tool: Spawn pawn", delegate + base.DebugAction("Tool: Spawn pawn", (Action)delegate() { - List list = new List(); - foreach (PawnKindDef current in from kd in DefDatabase.AllDefs + List list8 = new List(); + foreach (PawnKindDef item in from kd in DefDatabase.AllDefs orderby kd.defName select kd) { - PawnKindDef localKindDef = current; - list.Add(new DebugMenuOption(localKindDef.defName, DebugMenuOptionMode.Tool, delegate + PawnKindDef localKindDef = item; + list8.Add(new DebugMenuOption(localKindDef.defName, DebugMenuOptionMode.Tool, (Action)delegate() { Faction faction = FactionUtility.DefaultFactionFrom(localKindDef.defaultFactionType); Pawn newPawn = PawnGenerator.GeneratePawn(localKindDef, faction); @@ -1577,9 +1702,9 @@ orderby kd.defName if (faction != null && faction != Faction.OfPlayer) { Lord lord = null; - if (newPawn.Map.mapPawns.SpawnedPawnsInFaction(faction).Any((Pawn p) => p != newPawn)) + if (newPawn.Map.mapPawns.SpawnedPawnsInFaction(faction).Any((Predicate)((Pawn p) => p != newPawn))) { - Predicate validator = (Thing p) => p != newPawn && ((Pawn)p).GetLord() != null; + Predicate validator = (Predicate)((Thing p) => p != newPawn && ((Pawn)p).GetLord() != null); Pawn p2 = (Pawn)GenClosest.ClosestThing_Global(newPawn.Position, newPawn.Map.mapPawns.SpawnedPawnsInFaction(faction), 99999f, validator); lord = p2.GetLord(); } @@ -1592,50 +1717,50 @@ orderby kd.defName } })); } - Find.WindowStack.Add(new Dialog_DebugOptionListLister(list)); + Find.WindowStack.Add(new Dialog_DebugOptionListLister(list8)); }); - base.DebugAction("Tool: Spawn weapon...", delegate + base.DebugAction("Tool: Spawn weapon...", (Action)delegate() { - List list = new List(); - foreach (ThingDef current in from def in DefDatabase.AllDefs + List list7 = new List(); + foreach (ThingDef item in from def in DefDatabase.AllDefs where def.equipmentType == EquipmentType.Primary select def) { - ThingDef localDef = current; - list.Add(new DebugMenuOption(localDef.LabelCap, DebugMenuOptionMode.Tool, delegate + ThingDef localDef2 = item; + list7.Add(new DebugMenuOption(localDef2.LabelCap, DebugMenuOptionMode.Tool, (Action)delegate { - DebugThingPlaceHelper.DebugSpawn(localDef, UI.MouseCell(), -1, false); + DebugThingPlaceHelper.DebugSpawn(localDef2, UI.MouseCell(), -1, false); })); } - Find.WindowStack.Add(new Dialog_DebugOptionListLister(list)); + Find.WindowStack.Add(new Dialog_DebugOptionListLister(list7)); }); - base.DebugAction("Tool: Try place near thing...", delegate + base.DebugAction("Tool: Try place near thing...", (Action)delegate { Find.WindowStack.Add(new Dialog_DebugOptionListLister(DebugThingPlaceHelper.TryPlaceOptionsForStackCount(1, false))); }); - base.DebugAction("Tool: Try place near stacks of 25...", delegate + base.DebugAction("Tool: Try place near stacks of 25...", (Action)delegate { Find.WindowStack.Add(new Dialog_DebugOptionListLister(DebugThingPlaceHelper.TryPlaceOptionsForStackCount(25, false))); }); - base.DebugAction("Tool: Try place near stacks of 75...", delegate + base.DebugAction("Tool: Try place near stacks of 75...", (Action)delegate { Find.WindowStack.Add(new Dialog_DebugOptionListLister(DebugThingPlaceHelper.TryPlaceOptionsForStackCount(75, false))); }); - base.DebugAction("Tool: Try place direct thing...", delegate + base.DebugAction("Tool: Try place direct thing...", (Action)delegate { Find.WindowStack.Add(new Dialog_DebugOptionListLister(DebugThingPlaceHelper.TryPlaceOptionsForStackCount(1, true))); }); - base.DebugAction("Tool: Try place direct stacks of 25...", delegate + base.DebugAction("Tool: Try place direct stacks of 25...", (Action)delegate { Find.WindowStack.Add(new Dialog_DebugOptionListLister(DebugThingPlaceHelper.TryPlaceOptionsForStackCount(25, true))); }); - base.DebugAction("Tool: Set terrain...", delegate + base.DebugAction("Tool: Set terrain...", (Action)delegate { - List list = new List(); - foreach (TerrainDef current in DefDatabase.AllDefs) + List list6 = new List(); + foreach (TerrainDef allDef in DefDatabase.AllDefs) { - TerrainDef localDef = current; - list.Add(new DebugMenuOption(localDef.LabelCap, DebugMenuOptionMode.Tool, delegate + TerrainDef localDef = allDef; + list6.Add(new DebugMenuOption(localDef.LabelCap, DebugMenuOptionMode.Tool, (Action)delegate { if (UI.MouseCell().InBounds(Find.VisibleMap)) { @@ -1643,205 +1768,190 @@ orderby kd.defName } })); } - Find.WindowStack.Add(new Dialog_DebugOptionListLister(list)); + Find.WindowStack.Add(new Dialog_DebugOptionListLister(list6)); }); - base.DebugToolMap("Tool: Make filth x100", delegate + base.DebugToolMap("Tool: Make filth x100", (Action)delegate { - for (int i = 0; i < 100; i++) + for (int num4 = 0; num4 < 100; num4++) { - IntVec3 c = UI.MouseCell() + GenRadial.RadialPattern[i]; - if (c.InBounds(Find.VisibleMap) && c.Walkable(Find.VisibleMap)) + IntVec3 c2 = UI.MouseCell() + GenRadial.RadialPattern[num4]; + if (c2.InBounds(Find.VisibleMap) && c2.Walkable(Find.VisibleMap)) { - FilthMaker.MakeFilth(c, Find.VisibleMap, ThingDefOf.FilthDirt, 2); - MoteMaker.ThrowMetaPuff(c.ToVector3Shifted(), Find.VisibleMap); + FilthMaker.MakeFilth(c2, Find.VisibleMap, ThingDefOf.FilthDirt, 2); + MoteMaker.ThrowMetaPuff(c2.ToVector3Shifted(), Find.VisibleMap); } } }); - base.DebugToolMap("Tool: Spawn faction leader", delegate + base.DebugToolMap("Tool: Spawn faction leader", (Action)delegate { - List list = new List(); - foreach (Faction current in Find.FactionManager.AllFactions) + List list5 = new List(); + foreach (Faction allFaction in Find.FactionManager.AllFactions) { - Faction localFac = current; + Faction localFac = allFaction; if (localFac.leader != null) { - list.Add(new FloatMenuOption(localFac.Name + " - " + localFac.leader.Name.ToStringFull, delegate + list5.Add(new FloatMenuOption(localFac.Name + " - " + localFac.leader.Name.ToStringFull, (Action)delegate { GenSpawn.Spawn(localFac.leader, UI.MouseCell(), Find.VisibleMap); }, MenuOptionPriority.Default, null, null, 0f, null, null)); } } - Find.WindowStack.Add(new FloatMenu(list)); + Find.WindowStack.Add(new FloatMenu(list5)); }); - base.DebugAction("Spawn world pawn...", delegate + base.DebugAction("Spawn world pawn...", (Action)delegate() { - List list = new List(); - Action act = delegate(Pawn p) + List list3 = new List(); + Action act = (Action)delegate(Pawn p) { - List list2 = new List(); - foreach (PawnKindDef current2 in from x in DefDatabase.AllDefs + List list4 = new List(); + foreach (PawnKindDef item in from x in DefDatabase.AllDefs where x.race == p.def select x) { - PawnKindDef kLocal = current2; - list2.Add(new DebugMenuOption(kLocal.defName, DebugMenuOptionMode.Tool, delegate + PawnKindDef kLocal = item; + list4.Add(new DebugMenuOption(kLocal.defName, DebugMenuOptionMode.Tool, (Action)delegate() { - PawnGenerationRequest request = new PawnGenerationRequest(kLocal, p.Faction, PawnGenerationContext.NonPlayer, -1, false, false, false, false, true, false, 1f, false, true, true, false, false, null, null, null, null, null, null); + PawnGenerationRequest request = new PawnGenerationRequest(kLocal, p.Faction, PawnGenerationContext.NonPlayer, -1, false, false, false, false, true, false, 1f, false, true, true, false, false, null, default(float?), default(float?), default(Gender?), default(float?), (string)null); PawnGenerator.RedressPawn(p, request); GenSpawn.Spawn(p, UI.MouseCell(), Find.VisibleMap); DebugTools.curTool = null; })); } - Find.WindowStack.Add(new Dialog_DebugOptionListLister(list2)); + Find.WindowStack.Add(new Dialog_DebugOptionListLister(list4)); }; - foreach (Pawn current in Find.WorldPawns.AllPawnsAlive) + foreach (Pawn item2 in Find.WorldPawns.AllPawnsAlive) { - Pawn pLocal = current; - list.Add(new DebugMenuOption(current.LabelShort, DebugMenuOptionMode.Action, delegate + Pawn pLocal = item2; + list3.Add(new DebugMenuOption(item2.LabelShort, DebugMenuOptionMode.Action, (Action)delegate { act(pLocal); })); } - Find.WindowStack.Add(new Dialog_DebugOptionListLister(list)); + Find.WindowStack.Add(new Dialog_DebugOptionListLister(list3)); }); - base.DebugAction("Spawn item collection...", delegate + base.DebugAction("Spawn item collection...", (Action)delegate { List list = new List(); List allDefsListForReading = DefDatabase.AllDefsListForReading; - for (int i = 0; i < allDefsListForReading.Count; i++) + for (int m = 0; m < allDefsListForReading.Count; m++) { - ItemCollectionGeneratorDef localGenerator = allDefsListForReading[i]; - list.Add(new DebugMenuOption(localGenerator.defName, DebugMenuOptionMode.Tool, delegate + ItemCollectionGeneratorDef localGenerator = allDefsListForReading[m]; + list.Add(new DebugMenuOption(localGenerator.defName, DebugMenuOptionMode.Tool, (Action)delegate { - if (!UI.MouseCell().InBounds(Find.VisibleMap)) - { - return; - } - StringBuilder stringBuilder = new StringBuilder(); - List list2 = localGenerator.Worker.GenerateRandomTestItems(); - stringBuilder.AppendLine(string.Concat(new object[] - { - localGenerator.Worker.GetType().Name, - " generated ", - list2.Count, - " things:" - })); - float num = 0f; - for (int j = 0; j < list2.Count; j++) + if (UI.MouseCell().InBounds(Find.VisibleMap)) { - stringBuilder.AppendLine(" - " + list2[j].LabelCap); - num += list2[j].MarketValue * (float)list2[j].stackCount; - if (!GenPlace.TryPlaceThing(list2[j], UI.MouseCell(), Find.VisibleMap, ThingPlaceMode.Near, null)) + StringBuilder stringBuilder2 = new StringBuilder(); + List list2 = localGenerator.Worker.GenerateRandomTestItems(); + stringBuilder2.AppendLine(localGenerator.Worker.GetType().Name + " generated " + list2.Count + " things:"); + float num3 = 0f; + for (int n = 0; n < list2.Count; n++) { - list2[j].Destroy(DestroyMode.Vanish); + stringBuilder2.AppendLine(" - " + list2[n].LabelCap); + num3 += list2[n].MarketValue * (float)list2[n].stackCount; + if (!GenPlace.TryPlaceThing(list2[n], UI.MouseCell(), Find.VisibleMap, ThingPlaceMode.Near, null)) + { + list2[n].Destroy(DestroyMode.Vanish); + } } + stringBuilder2.AppendLine("Total market value: " + num3.ToString("0.##")); + Log.Message(stringBuilder2.ToString()); } - stringBuilder.AppendLine("Total market value: " + num.ToString("0.##")); - Log.Message(stringBuilder.ToString()); })); } Find.WindowStack.Add(new Dialog_DebugOptionListLister(list)); }); this.DoGap(); this.DoLabel("Autotests"); - base.DebugAction("Make colony (full)", delegate + base.DebugAction("Make colony (full)", (Action)delegate { Autotests_ColonyMaker.MakeColony_Full(); }); - base.DebugAction("Make colony (animals)", delegate + base.DebugAction("Make colony (animals)", (Action)delegate { Autotests_ColonyMaker.MakeColony_Animals(); }); - base.DebugAction("Test force downed x100", delegate + base.DebugAction("Test force downed x100", (Action)delegate() { - for (int i = 0; i < 100; i++) + int num2 = 0; + Pawn pawn5; + while (true) { - PawnKindDef random = DefDatabase.GetRandom(); - Pawn pawn = PawnGenerator.GeneratePawn(random, FactionUtility.DefaultFactionFrom(random.defaultFactionType)); - GenSpawn.Spawn(pawn, CellFinderLoose.RandomCellWith((IntVec3 c) => c.Standable(Find.VisibleMap), Find.VisibleMap, 1000), Find.VisibleMap); - HealthUtility.DamageUntilDowned(pawn); - if (pawn.Dead) + if (num2 < 100) { - Log.Error(string.Concat(new object[] + PawnKindDef random5 = DefDatabase.GetRandom(); + pawn5 = PawnGenerator.GeneratePawn(random5, FactionUtility.DefaultFactionFrom(random5.defaultFactionType)); + GenSpawn.Spawn(pawn5, CellFinderLoose.RandomCellWith((Predicate)((IntVec3 c) => c.Standable(Find.VisibleMap)), Find.VisibleMap, 1000), Find.VisibleMap); + HealthUtility.DamageUntilDowned(pawn5); + if (!pawn5.Dead) { - "Pawn died while force downing: ", - pawn, - " at ", - pawn.Position - })); - return; + num2++; + continue; + } + break; } + return; } + Log.Error("Pawn died while force downing: " + pawn5 + " at " + pawn5.Position); }); - base.DebugAction("Test force kill x100", delegate + base.DebugAction("Test force kill x100", (Action)delegate() { - for (int i = 0; i < 100; i++) + int num = 0; + Pawn pawn4; + while (true) { - PawnKindDef random = DefDatabase.GetRandom(); - Pawn pawn = PawnGenerator.GeneratePawn(random, FactionUtility.DefaultFactionFrom(random.defaultFactionType)); - GenSpawn.Spawn(pawn, CellFinderLoose.RandomCellWith((IntVec3 c) => c.Standable(Find.VisibleMap), Find.VisibleMap, 1000), Find.VisibleMap); - HealthUtility.DamageUntilDead(pawn); - if (!pawn.Dead) + if (num < 100) { - Log.Error(string.Concat(new object[] + PawnKindDef random4 = DefDatabase.GetRandom(); + pawn4 = PawnGenerator.GeneratePawn(random4, FactionUtility.DefaultFactionFrom(random4.defaultFactionType)); + GenSpawn.Spawn(pawn4, CellFinderLoose.RandomCellWith((Predicate)((IntVec3 c) => c.Standable(Find.VisibleMap)), Find.VisibleMap, 1000), Find.VisibleMap); + HealthUtility.DamageUntilDead(pawn4); + if (pawn4.Dead) { - "Pawn died not die: ", - pawn, - " at ", - pawn.Position - })); - return; + num++; + continue; + } + break; } + return; } + Log.Error("Pawn died not die: " + pawn4 + " at " + pawn4.Position); }); - base.DebugAction("Test Surgery fail catastrophic x100", delegate + base.DebugAction("Test Surgery fail catastrophic x100", (Action)delegate() { - for (int i = 0; i < 100; i++) + for (int l = 0; l < 100; l++) { - PawnKindDef random = DefDatabase.GetRandom(); - Pawn pawn = PawnGenerator.GeneratePawn(random, FactionUtility.DefaultFactionFrom(random.defaultFactionType)); - GenSpawn.Spawn(pawn, CellFinderLoose.RandomCellWith((IntVec3 c) => c.Standable(Find.VisibleMap), Find.VisibleMap, 1000), Find.VisibleMap); - pawn.health.forceIncap = true; - BodyPartRecord part = pawn.health.hediffSet.GetNotMissingParts(BodyPartHeight.Undefined, BodyPartDepth.Undefined).RandomElement(); - HealthUtility.GiveInjuriesOperationFailureCatastrophic(pawn, part); - pawn.health.forceIncap = false; - if (pawn.Dead) + PawnKindDef random3 = DefDatabase.GetRandom(); + Pawn pawn3 = PawnGenerator.GeneratePawn(random3, FactionUtility.DefaultFactionFrom(random3.defaultFactionType)); + GenSpawn.Spawn(pawn3, CellFinderLoose.RandomCellWith((Predicate)((IntVec3 c) => c.Standable(Find.VisibleMap)), Find.VisibleMap, 1000), Find.VisibleMap); + pawn3.health.forceIncap = true; + BodyPartRecord part = pawn3.health.hediffSet.GetNotMissingParts(BodyPartHeight.Undefined, BodyPartDepth.Undefined).RandomElement(); + HealthUtility.GiveInjuriesOperationFailureCatastrophic(pawn3, part); + pawn3.health.forceIncap = false; + if (pawn3.Dead) { - Log.Error(string.Concat(new object[] - { - "Pawn died: ", - pawn, - " at ", - pawn.Position - })); + Log.Error("Pawn died: " + pawn3 + " at " + pawn3.Position); } } }); - base.DebugAction("Test Surgery fail ridiculous x100", delegate + base.DebugAction("Test Surgery fail ridiculous x100", (Action)delegate() { - for (int i = 0; i < 100; i++) + for (int k = 0; k < 100; k++) { - PawnKindDef random = DefDatabase.GetRandom(); - Pawn pawn = PawnGenerator.GeneratePawn(random, FactionUtility.DefaultFactionFrom(random.defaultFactionType)); - GenSpawn.Spawn(pawn, CellFinderLoose.RandomCellWith((IntVec3 c) => c.Standable(Find.VisibleMap), Find.VisibleMap, 1000), Find.VisibleMap); - pawn.health.forceIncap = true; - HealthUtility.GiveInjuriesOperationFailureRidiculous(pawn); - pawn.health.forceIncap = false; - if (pawn.Dead) + PawnKindDef random2 = DefDatabase.GetRandom(); + Pawn pawn2 = PawnGenerator.GeneratePawn(random2, FactionUtility.DefaultFactionFrom(random2.defaultFactionType)); + GenSpawn.Spawn(pawn2, CellFinderLoose.RandomCellWith((Predicate)((IntVec3 c) => c.Standable(Find.VisibleMap)), Find.VisibleMap, 1000), Find.VisibleMap); + pawn2.health.forceIncap = true; + HealthUtility.GiveInjuriesOperationFailureRidiculous(pawn2); + pawn2.health.forceIncap = false; + if (pawn2.Dead) { - Log.Error(string.Concat(new object[] - { - "Pawn died: ", - pawn, - " at ", - pawn.Position - })); + Log.Error("Pawn died: " + pawn2 + " at " + pawn2.Position); } } }); - base.DebugAction("Test generate pawn x1000", delegate + base.DebugAction("Test generate pawn x1000", (Action)delegate() { - float[] array = new float[] + float[] array = new float[10] { 10f, 20f, @@ -1860,8 +1970,8 @@ orderby kd.defName PawnKindDef random = DefDatabase.GetRandom(); PerfLogger.Reset(); Pawn pawn = PawnGenerator.GeneratePawn(random, FactionUtility.DefaultFactionFrom(random.defaultFactionType)); - float ms = PerfLogger.Duration() * 1000f; - array2[array.FirstIndexOf((float time) => ms <= time)]++; + float ms = (float)(PerfLogger.Duration() * 1000.0); + array2[array.FirstIndexOf((Func)((float time) => ms <= time))]++; if (pawn.Dead) { Log.Error("Pawn is dead"); @@ -1876,7 +1986,7 @@ orderby kd.defName } Log.Message(stringBuilder.ToString()); }); - base.DebugAction("Check region listers", delegate + base.DebugAction("Check region listers", (Action)delegate { Autotests_RegionListers.CheckBugs(Find.VisibleMap); }); @@ -1891,59 +2001,57 @@ private void DoListingItems_World() this.DoExecuteIncidentDebugAction(Find.World, altTarget); this.DoExecuteIncidentWithDebugAction(Find.World, altTarget); this.DoLabel("Tools - Spawning"); - base.DebugToolWorld("Spawn random caravan", delegate - { - int num = GenWorld.MouseTile(false); - Tile tile = Find.WorldGrid[num]; - if (tile.biome.impassable) - { - return; - } - Caravan caravan = (Caravan)WorldObjectMaker.MakeWorldObject(WorldObjectDefOf.Caravan); - caravan.Tile = num; - caravan.SetFaction(Faction.OfPlayer); - Find.WorldObjects.Add(caravan); - int num2 = Rand.RangeInclusive(1, 10); - for (int i = 0; i < num2; i++) - { - Pawn pawn = PawnGenerator.GeneratePawn(Faction.OfPlayer.def.basicMemberKind, Faction.OfPlayer); - caravan.AddPawn(pawn, true); - Find.WorldPawns.PassToWorld(pawn, PawnDiscardDecideMode.Decide); - if (Rand.Value < 0.5f) + base.DebugToolWorld("Spawn random caravan", (Action)delegate() + { + int num2 = GenWorld.MouseTile(false); + Tile tile3 = Find.WorldGrid[num2]; + if (!tile3.biome.impassable) + { + Caravan caravan = (Caravan)WorldObjectMaker.MakeWorldObject(WorldObjectDefOf.Caravan); + caravan.Tile = num2; + caravan.SetFaction(Faction.OfPlayer); + Find.WorldObjects.Add(caravan); + int num3 = Rand.RangeInclusive(1, 10); + for (int num4 = 0; num4 < num3; num4++) + { + Pawn pawn = PawnGenerator.GeneratePawn(Faction.OfPlayer.def.basicMemberKind, Faction.OfPlayer); + caravan.AddPawn(pawn, true); + Find.WorldPawns.PassToWorld(pawn, PawnDiscardDecideMode.Decide); + if (Rand.Value < 0.5) + { + ThingDef thingDef = (from def in DefDatabase.AllDefs + where def.IsWeapon && def.PlayerAcquirable + select def).RandomElementWithFallback(null); + pawn.equipment.AddEquipment((ThingWithComps)ThingMaker.MakeThing(thingDef, GenStuff.RandomStuffFor(thingDef))); + } + } + List list3 = ItemCollectionGeneratorDefOf.DebugCaravanInventory.Worker.Generate(default(ItemCollectionGeneratorParams)); + for (int i = 0; i < list3.Count; i++) { - ThingDef thingDef = (from def in DefDatabase.AllDefs - where def.IsWeapon && def.PlayerAcquirable - select def).RandomElementWithFallback(null); - pawn.equipment.AddEquipment((ThingWithComps)ThingMaker.MakeThing(thingDef, GenStuff.RandomStuffFor(thingDef))); + CaravanInventoryUtility.GiveThing(caravan, list3[i]); } } - List list = ItemCollectionGeneratorDefOf.DebugCaravanInventory.Worker.Generate(default(ItemCollectionGeneratorParams)); - for (int j = 0; j < list.Count; j++) - { - CaravanInventoryUtility.GiveThing(caravan, list[j]); - } }); - base.DebugToolWorld("Spawn random faction base", delegate + base.DebugToolWorld("Spawn random faction base", (Action)delegate() { - Faction faction; + Faction faction = default(Faction); if ((from x in Find.FactionManager.AllFactions where !x.IsPlayer && !x.def.hidden - select x).TryRandomElement(out faction)) + select x).TryRandomElement(out faction)) { int num = GenWorld.MouseTile(false); - Tile tile = Find.WorldGrid[num]; - if (tile.biome.impassable) - { - return; + Tile tile2 = Find.WorldGrid[num]; + if (!tile2.biome.impassable) + { + FactionBase factionBase = (FactionBase)WorldObjectMaker.MakeWorldObject(WorldObjectDefOf.FactionBase); + factionBase.SetFaction(faction); + factionBase.Tile = num; + factionBase.Name = FactionBaseNameGenerator.GenerateFactionBaseName(factionBase); + Find.WorldObjects.Add(factionBase); } - FactionBase factionBase = (FactionBase)WorldObjectMaker.MakeWorldObject(WorldObjectDefOf.FactionBase); - factionBase.SetFaction(faction); - factionBase.Tile = num; - factionBase.Name = FactionBaseNameGenerator.GenerateFactionBaseName(factionBase); - Find.WorldObjects.Add(factionBase); } }); - base.DebugToolWorld("Spawn site", delegate + base.DebugToolWorld("Spawn site", (Action)delegate { int tile = GenWorld.MouseTile(false); if (tile < 0 || Find.World.Impassable(tile)) @@ -1954,14 +2062,14 @@ where def.IsWeapon && def.PlayerAcquirable { List list = new List(); List parts = new List(); - foreach (SiteCoreDef current in DefDatabase.AllDefs) + foreach (SiteCoreDef allDef in DefDatabase.AllDefs) { - SiteCoreDef localDef = current; + SiteCoreDef localDef = allDef; Action addPart = null; - addPart = delegate + addPart = (Action)delegate { List list2 = new List(); - list2.Add(new DebugMenuOption("-Done (" + parts.Count + " parts)-", DebugMenuOptionMode.Action, delegate + list2.Add(new DebugMenuOption("-Done (" + parts.Count + " parts)-", DebugMenuOptionMode.Action, (Action)delegate { Site site = SiteMaker.TryMakeSite(localDef, parts, true, null); if (site == null) @@ -1974,10 +2082,10 @@ where def.IsWeapon && def.PlayerAcquirable Find.WorldObjects.Add(site); } })); - foreach (SitePartDef current2 in DefDatabase.AllDefs) + foreach (SitePartDef allDef in DefDatabase.AllDefs) { - SitePartDef localPart = current2; - list2.Add(new DebugMenuOption(current2.defName, DebugMenuOptionMode.Action, delegate + SitePartDef localPart = allDef; + list2.Add(new DebugMenuOption(allDef.defName, DebugMenuOptionMode.Action, (Action)delegate { parts.Add(localPart); addPart(); @@ -1994,76 +2102,62 @@ where def.IsWeapon && def.PlayerAcquirable private void DoLabel(string label) { - this.listing.Label(label, -1f); - this.totalOptionsHeight += Text.CalcHeight(label, 300f) + 2f; + base.listing.Label(label, -1f); + base.totalOptionsHeight += (float)(Text.CalcHeight(label, 300f) + 2.0); } private void DoGap() { - this.listing.Gap(7f); - this.totalOptionsHeight += 7f; + base.listing.Gap(7f); + base.totalOptionsHeight += 7f; } private void DoRaid(IncidentParms parms) { - IncidentDef incidentDef; - if (parms.faction.HostileTo(Faction.OfPlayer)) - { - incidentDef = IncidentDefOf.RaidEnemy; - } - else - { - incidentDef = IncidentDefOf.RaidFriendly; - } + IncidentDef incidentDef = (!parms.faction.HostileTo(Faction.OfPlayer)) ? IncidentDefOf.RaidFriendly : IncidentDefOf.RaidEnemy; incidentDef.Worker.TryExecute(parms); } private void DoExecuteIncidentDebugAction(IIncidentTarget target, IIncidentTarget altTarget) { - Dialog_DebugActionsMenu.c__AnonStorey5CA c__AnonStorey5CA = new Dialog_DebugActionsMenu.c__AnonStorey5CA(); - c__AnonStorey5CA.target = target; - c__AnonStorey5CA.altTarget = altTarget; - base.DebugAction("Execute incident...", delegate + base.DebugAction("Execute incident...", (Action)delegate() { List list = new List(); - foreach (IncidentDef current in from d in DefDatabase.AllDefs - where d.TargetAllowed(c__AnonStorey5CA.target) || (c__AnonStorey5CA.altTarget != null && d.TargetAllowed(c__AnonStorey5CA.altTarget)) - orderby !d.TargetAllowed(c__AnonStorey5CA.target), d.defName + foreach (IncidentDef item in from d in DefDatabase.AllDefs + where d.TargetAllowed(target) || (altTarget != null && d.TargetAllowed(altTarget)) + orderby !d.TargetAllowed(target), d.defName select d) { - Dialog_DebugActionsMenu.c__AnonStorey5CA.c__AnonStorey5CB c__AnonStorey5CB = new Dialog_DebugActionsMenu.c__AnonStorey5CA.c__AnonStorey5CB(); - c__AnonStorey5CB.<>f__ref$1482 = c__AnonStorey5CA; - Dialog_DebugActionsMenu.c__AnonStorey5CA.c__AnonStorey5CB arg_98_0 = c__AnonStorey5CB; - IIncidentTarget arg_98_1; - if (current.TargetAllowed(c__AnonStorey5CA.target)) + object obj; + if (item.TargetAllowed(target)) { - IIncidentTarget target2 = c__AnonStorey5CA.target; - arg_98_1 = target2; + IIncidentTarget incidentTarget = target; + obj = incidentTarget; } else { - arg_98_1 = c__AnonStorey5CA.altTarget; + obj = altTarget; } - arg_98_0.thisIncidentTarget = arg_98_1; - c__AnonStorey5CB.localDef = current; - string text = c__AnonStorey5CB.localDef.defName; - if (!c__AnonStorey5CB.localDef.Worker.CanFireNow(c__AnonStorey5CB.thisIncidentTarget)) + IIncidentTarget thisIncidentTarget = (IIncidentTarget)obj; + IncidentDef localDef = item; + string text = localDef.defName; + if (!localDef.Worker.CanFireNow(thisIncidentTarget)) { text += " [NO]"; } - if (c__AnonStorey5CB.thisIncidentTarget == c__AnonStorey5CA.altTarget) + if (thisIncidentTarget == altTarget) { - text = text + " (" + c__AnonStorey5CA.altTarget.GetType().Name.Truncate(52f, null) + ")"; + text = text + " (" + altTarget.GetType().Name.Truncate(52f, null) + ")"; } - list.Add(new DebugMenuOption(text, DebugMenuOptionMode.Action, delegate + list.Add(new DebugMenuOption(text, DebugMenuOptionMode.Action, (Action)delegate() { - IncidentParms incidentParms = StorytellerUtility.DefaultParmsNow(Find.Storyteller.def, c__AnonStorey5CB.localDef.category, c__AnonStorey5CB.thisIncidentTarget); - if (c__AnonStorey5CB.localDef.pointsScaleable) + IncidentParms incidentParms = StorytellerUtility.DefaultParmsNow(Find.Storyteller.def, localDef.category, thisIncidentTarget); + if (localDef.pointsScaleable) { - StorytellerComp storytellerComp = Find.Storyteller.storytellerComps.First((StorytellerComp x) => x is StorytellerComp_ThreatCycle || x is StorytellerComp_RandomMain); - incidentParms = storytellerComp.GenerateParms(c__AnonStorey5CB.localDef.category, incidentParms.target); + StorytellerComp storytellerComp = Find.Storyteller.storytellerComps.First((Func)((StorytellerComp x) => x is StorytellerComp_ThreatCycle || x is StorytellerComp_RandomMain)); + incidentParms = storytellerComp.GenerateParms(localDef.category, incidentParms.target); } - c__AnonStorey5CB.localDef.Worker.TryExecute(incidentParms); + localDef.Worker.TryExecute(incidentParms); })); } Find.WindowStack.Add(new Dialog_DebugOptionListLister(list)); @@ -2072,52 +2166,47 @@ where d.TargetAllowed(c__AnonStorey5CA.target) || private void DoExecuteIncidentWithDebugAction(IIncidentTarget target, IIncidentTarget altTarget) { - Dialog_DebugActionsMenu.c__AnonStorey5CC c__AnonStorey5CC = new Dialog_DebugActionsMenu.c__AnonStorey5CC(); - c__AnonStorey5CC.target = target; - c__AnonStorey5CC.altTarget = altTarget; - base.DebugAction("Execute incident with...", delegate + base.DebugAction("Execute incident with...", (Action)delegate() { List list = new List(); - foreach (IncidentDef current in from d in DefDatabase.AllDefs - where (d.TargetAllowed(c__AnonStorey5CC.target) || (c__AnonStorey5CC.altTarget != null && d.TargetAllowed(c__AnonStorey5CC.altTarget))) && d.pointsScaleable - orderby !d.TargetAllowed(c__AnonStorey5CC.target), d.defName + foreach (IncidentDef item in from d in DefDatabase.AllDefs + where (d.TargetAllowed(target) || (altTarget != null && d.TargetAllowed(altTarget))) && d.pointsScaleable + orderby !d.TargetAllowed(target), d.defName select d) { - Dialog_DebugActionsMenu.c__AnonStorey5CC.c__AnonStorey5CD c__AnonStorey5CD = new Dialog_DebugActionsMenu.c__AnonStorey5CC.c__AnonStorey5CD(); - c__AnonStorey5CD.<>f__ref$1484 = c__AnonStorey5CC; - Dialog_DebugActionsMenu.c__AnonStorey5CC.c__AnonStorey5CD arg_98_0 = c__AnonStorey5CD; - IIncidentTarget arg_98_1; - if (current.TargetAllowed(c__AnonStorey5CC.target)) + object obj; + if (item.TargetAllowed(target)) { - IIncidentTarget target2 = c__AnonStorey5CC.target; - arg_98_1 = target2; + IIncidentTarget incidentTarget = target; + obj = incidentTarget; } else { - arg_98_1 = c__AnonStorey5CC.altTarget; + obj = altTarget; } - arg_98_0.thisIncidentTarget = arg_98_1; - c__AnonStorey5CD.localDef = current; - string text = c__AnonStorey5CD.localDef.defName; - if (!c__AnonStorey5CD.localDef.Worker.CanFireNow(c__AnonStorey5CD.thisIncidentTarget)) + IIncidentTarget thisIncidentTarget = (IIncidentTarget)obj; + IncidentDef localDef = item; + string text = localDef.defName; + if (!localDef.Worker.CanFireNow(thisIncidentTarget)) { text += " [NO]"; } - if (c__AnonStorey5CD.thisIncidentTarget == c__AnonStorey5CC.altTarget) + if (thisIncidentTarget == altTarget) { - text = text + " (" + c__AnonStorey5CC.altTarget.GetType().Name.Truncate(52f, null) + ")"; + text = text + " (" + altTarget.GetType().Name.Truncate(52f, null) + ")"; } - list.Add(new DebugMenuOption(text, DebugMenuOptionMode.Action, delegate + list.Add(new DebugMenuOption(text, DebugMenuOptionMode.Action, (Action)delegate { - IncidentParms parms = StorytellerUtility.DefaultParmsNow(Find.Storyteller.def, c__AnonStorey5CD.localDef.category, c__AnonStorey5CD.thisIncidentTarget); + IncidentParms parms = StorytellerUtility.DefaultParmsNow(Find.Storyteller.def, localDef.category, thisIncidentTarget); List list2 = new List(); - foreach (float num in Dialog_DebugActionsMenu.PointsOptions()) + foreach (float item in Dialog_DebugActionsMenu.PointsOptions()) { + float num = item; float localPoints = num; - list2.Add(new DebugMenuOption(num + " points", DebugMenuOptionMode.Action, delegate + list2.Add(new DebugMenuOption(num + " points", DebugMenuOptionMode.Action, (Action)delegate { parms.points = localPoints; - c__AnonStorey5CD.localDef.Worker.TryExecute(parms); + localDef.Worker.TryExecute(parms); })); } Find.WindowStack.Add(new Dialog_DebugOptionListLister(list2)); @@ -2129,44 +2218,36 @@ private void DoExecuteIncidentWithDebugAction(IIncidentTarget target, IIncidentT private void DebugGiveResource(ThingDef resDef, int count) { - Pawn pawn = Find.VisibleMap.mapPawns.FreeColonistsSpawned.RandomElement(); - int i = count; - int num = 0; - while (i > 0) + Pawn pawn = Find.VisibleMap.mapPawns.FreeColonistsSpawned.RandomElement(); + int num = count; + int num2 = 0; + while (num > 0) { - int num2 = Math.Min(resDef.stackLimit, i); - i -= num2; + int num3 = Math.Min(resDef.stackLimit, num); + num -= num3; Thing thing = ThingMaker.MakeThing(resDef, null); - thing.stackCount = num2; - if (!GenPlace.TryPlaceThing(thing, pawn.Position, pawn.Map, ThingPlaceMode.Near, null)) + thing.stackCount = num3; + if (GenPlace.TryPlaceThing(thing, pawn.Position, pawn.Map, ThingPlaceMode.Near, null)) { - break; + num2 += num3; + continue; } - num += num2; + break; } - Messages.Message(string.Concat(new object[] - { - "Made ", - num, - " ", - resDef, - " near ", - pawn, - "." - }), MessageSound.Benefit); + Messages.Message("Made " + num2 + " " + resDef + " near " + pawn + ".", MessageSound.Benefit); } private void OffsetNeed(NeedDef nd, float offsetPct) { - foreach (Pawn current in (from t in Find.VisibleMap.thingGrid.ThingsAt(UI.MouseCell()) + foreach (Pawn item in (from t in Find.VisibleMap.thingGrid.ThingsAt(UI.MouseCell()) where t is Pawn select t).Cast()) { - Need need = current.needs.TryGetNeed(nd); + Need need = item.needs.TryGetNeed(nd); if (need != null) { need.CurLevel += offsetPct * need.MaxLevel; - this.DustPuffFrom(current); + this.DustPuffFrom(item); } } } @@ -2182,47 +2263,67 @@ private void DustPuffFrom(Thing t) private void AddGuest(bool prisoner) { - foreach (Building_Bed current in Find.VisibleMap.listerBuildings.AllBuildingsColonistOfClass()) + using (IEnumerator enumerator = Find.VisibleMap.listerBuildings.AllBuildingsColonistOfClass().GetEnumerator()) { - if (current.ForPrisoners == prisoner && (!current.owners.Any() || (prisoner && current.AnyUnownedSleepingSlot))) + Building_Bed current; + while (true) { - PawnKindDef pawnKindDef; - if (!prisoner) + if (enumerator.MoveNext()) { - pawnKindDef = PawnKindDefOf.SpaceRefugee; - } - else - { - pawnKindDef = (from pk in DefDatabase.AllDefs - where pk.defaultFactionType != null && !pk.defaultFactionType.isPlayer && pk.RaceProps.Humanlike - select pk).RandomElement(); + current = enumerator.Current; + if (current.ForPrisoners == prisoner) + { + if (!current.owners.Any()) + break; + if (prisoner && current.AnyUnownedSleepingSlot) + break; + } + continue; } - Faction faction = FactionUtility.DefaultFactionFrom(pawnKindDef.defaultFactionType); - Pawn pawn = PawnGenerator.GeneratePawn(pawnKindDef, faction); - GenSpawn.Spawn(pawn, current.Position, Find.VisibleMap); - foreach (ThingWithComps current2 in pawn.equipment.AllEquipmentListForReading.ToList()) + return; + } + PawnKindDef pawnKindDef = prisoner ? (from pk in DefDatabase.AllDefs + where pk.defaultFactionType != null && !pk.defaultFactionType.isPlayer && pk.RaceProps.Humanlike + select pk).RandomElement() : PawnKindDefOf.SpaceRefugee; + Faction faction = FactionUtility.DefaultFactionFrom(pawnKindDef.defaultFactionType); + Pawn pawn = PawnGenerator.GeneratePawn(pawnKindDef, faction); + GenSpawn.Spawn(pawn, current.Position, Find.VisibleMap); + List.Enumerator enumerator2 = pawn.equipment.AllEquipmentListForReading.ToList().GetEnumerator(); + try + { + while (enumerator2.MoveNext()) { - ThingWithComps thingWithComps; + ThingWithComps current2 = enumerator2.Current; + ThingWithComps thingWithComps = default(ThingWithComps); if (pawn.equipment.TryDropEquipment(current2, out thingWithComps, pawn.Position, true)) { thingWithComps.Destroy(DestroyMode.Vanish); } } - pawn.inventory.innerContainer.Clear(); - pawn.ownership.ClaimBedIfNonMedical(current); - pawn.guest.SetGuestStatus(Faction.OfPlayer, prisoner); - break; } + finally + { + ((IDisposable)(object)enumerator2).Dispose(); + } + pawn.inventory.innerContainer.Clear(); + pawn.ownership.ClaimBedIfNonMedical(current); + pawn.guest.SetGuestStatus(Faction.OfPlayer, prisoner); } } - [DebuggerHidden] public static IEnumerable PointsOptions() { - Dialog_DebugActionsMenu.c__Iterator231 c__Iterator = new Dialog_DebugActionsMenu.c__Iterator231(); - Dialog_DebugActionsMenu.c__Iterator231 expr_07 = c__Iterator; - expr_07.$PC = -2; - return expr_07; + yield return 35f; + yield return 70f; + yield return 135f; + yield return 200f; + yield return 300f; + yield return 500f; + yield return 800f; + yield return 1200f; + yield return 2000f; + yield return 3000f; + yield return 4000f; } } } diff --git a/Assembly-CSharp/Verse/Dialog_DebugLogMenu.cs b/Assembly-CSharp/Verse/Dialog_DebugLogMenu.cs index 72db0b135..065594b50 100644 --- a/Assembly-CSharp/Verse/Dialog_DebugLogMenu.cs +++ b/Assembly-CSharp/Verse/Dialog_DebugLogMenu.cs @@ -17,124 +17,124 @@ public override bool IsDebug public Dialog_DebugLogMenu() { - this.forcePause = true; + base.forcePause = true; } protected override void DoListingItems() { - this.listing.Label("Logs", -1f); + base.listing.Label("Logs", -1f); MethodInfo[] methods = typeof(DataAnalysisLogger).GetMethods(BindingFlags.Static | BindingFlags.Public); - MethodInfo mi2; + MethodInfo mi; for (int i = 0; i < methods.Length; i++) { - mi2 = methods[i]; - string name = mi2.Name; + mi = methods[i]; + string name = mi.Name; if (name.StartsWith("DoLog_")) { - base.DebugAction(GenText.SplitCamelCase(name.Substring(6)), delegate + base.DebugAction(GenText.SplitCamelCase(name.Substring(6)), (Action)delegate { - mi2.Invoke(null, null); + mi.Invoke(null, null); }); } } if (Current.ProgramState == ProgramState.Playing) { - base.DebugAction("Plant proportions", delegate + base.DebugAction("Plant proportions", (Action)delegate { GenPlant.LogPlantProportions(); }); - base.DebugAction("Database tales list", delegate + base.DebugAction("Database tales list", (Action)delegate { Find.TaleManager.LogTales(); }); - base.DebugAction("Database tales interest", delegate + base.DebugAction("Database tales interest", (Action)delegate { Find.TaleManager.LogTaleInterestSummary(); }); - base.DebugAction("Database tales descs", delegate + base.DebugAction("Database tales descs", (Action)delegate { TaleTester.LogTalesInDatabase(); }); - base.DebugAction("Random tales descs", delegate + base.DebugAction("Random tales descs", (Action)delegate { TaleTester.LogGeneratedTales(40); }); - base.DebugAction("Taleless descs", delegate + base.DebugAction("Taleless descs", (Action)delegate { TaleTester.LogDescriptionsTaleless(); }); - base.DebugAction("Temperature data", delegate + base.DebugAction("Temperature data", (Action)delegate { Find.VisibleMap.mapTemperature.DebugLogTemps(); }); - base.DebugAction("Weather chances", delegate + base.DebugAction("Weather chances", (Action)delegate { Find.VisibleMap.weatherDecider.LogWeatherChances(); }); - base.DebugAction("Celestial glow", delegate + base.DebugAction("Celestial glow", (Action)delegate { GenCelestial.LogSunGlowForYear(); }); - base.DebugAction("ListerPawns", delegate + base.DebugAction("ListerPawns", (Action)delegate { Find.VisibleMap.mapPawns.LogListedPawns(); }); - base.DebugAction("Wind speeds", delegate + base.DebugAction("Wind speeds", (Action)delegate { Find.VisibleMap.windManager.LogWindSpeeds(); }); - base.DebugAction("Kidnapped pawns", delegate + base.DebugAction("Kidnapped pawns", (Action)delegate { Find.FactionManager.LogKidnappedPawns(); }); - base.DebugAction("World pawns", delegate + base.DebugAction("World pawns", (Action)delegate { Find.WorldPawns.LogWorldPawns(); }); - base.DebugAction("Draw list", delegate + base.DebugAction("Draw list", (Action)delegate { Find.VisibleMap.dynamicDrawManager.LogDynamicDrawThings(); }); - base.DebugAction("Future incidents", delegate + base.DebugAction("Future incidents", (Action)delegate { StorytellerUtility.DebugLogTestFutureIncidents(false); }); - base.DebugAction("Future incidents (visible map)", delegate + base.DebugAction("Future incidents (visible map)", (Action)delegate { StorytellerUtility.DebugLogTestFutureIncidents(true); }); - base.DebugAction("Map pawns", delegate + base.DebugAction("Map pawns", (Action)delegate { Find.VisibleMap.mapPawns.LogListedPawns(); }); } - this.listing.Gap(12f); + base.listing.Gap(12f); Text.Font = GameFont.Small; - this.listing.Label("Tables", -1f); + base.listing.Label("Tables", -1f); MethodInfo[] methods2 = typeof(DataAnalysisTableMaker).GetMethods(BindingFlags.Static | BindingFlags.Public); - MethodInfo mi; + MethodInfo mi2; for (int j = 0; j < methods2.Length; j++) { - mi = methods2[j]; - string name2 = mi.Name; + mi2 = methods2[j]; + string name2 = mi2.Name; if (name2.StartsWith("DoTable_")) { - base.DebugAction(GenText.SplitCamelCase(name2.Substring(8)), delegate + base.DebugAction(GenText.SplitCamelCase(name2.Substring(8)), (Action)delegate { - mi.Invoke(null, null); + mi2.Invoke(null, null); }); } } - this.listing.Gap(12f); - this.listing.Label("UI", -1f); - base.DebugAction("Pawn column", delegate + base.listing.Gap(12f); + base.listing.Label("UI", -1f); + base.DebugAction("Pawn column", (Action)delegate { List list = new List(); List allDefsListForReading = DefDatabase.AllDefsListForReading; for (int k = 0; k < allDefsListForReading.Count; k++) { PawnColumnDef localDef = allDefsListForReading[k]; - list.Add(new DebugMenuOption(localDef.defName, DebugMenuOptionMode.Action, delegate + list.Add(new DebugMenuOption(localDef.defName, DebugMenuOptionMode.Action, (Action)delegate { Find.WindowStack.Add(new Dialog_PawnTableTest(localDef)); })); diff --git a/Assembly-CSharp/Verse/Dialog_DebugOptionListLister.cs b/Assembly-CSharp/Verse/Dialog_DebugOptionListLister.cs index b3419b99b..034ddcfbf 100644 --- a/Assembly-CSharp/Verse/Dialog_DebugOptionListLister.cs +++ b/Assembly-CSharp/Verse/Dialog_DebugOptionListLister.cs @@ -10,22 +10,31 @@ public class Dialog_DebugOptionListLister : Dialog_DebugOptionLister public Dialog_DebugOptionListLister(IEnumerable options) { - this.options = options.ToList(); + this.options = options.ToList(); } protected override void DoListingItems() { - foreach (DebugMenuOption current in this.options) + List.Enumerator enumerator = this.options.GetEnumerator(); + try { - if (current.mode == DebugMenuOptionMode.Action) + while (enumerator.MoveNext()) { - base.DebugAction(current.label, current.method); - } - if (current.mode == DebugMenuOptionMode.Tool) - { - base.DebugToolMap(current.label, current.method); + DebugMenuOption current = enumerator.Current; + if (current.mode == DebugMenuOptionMode.Action) + { + base.DebugAction(current.label, current.method); + } + if (current.mode == DebugMenuOptionMode.Tool) + { + base.DebugToolMap(current.label, current.method); + } } } + finally + { + ((IDisposable)(object)enumerator).Dispose(); + } } } } diff --git a/Assembly-CSharp/Verse/Dialog_DebugOptionLister.cs b/Assembly-CSharp/Verse/Dialog_DebugOptionLister.cs index e07a259ab..b009fcb2f 100644 --- a/Assembly-CSharp/Verse/Dialog_DebugOptionLister.cs +++ b/Assembly-CSharp/Verse/Dialog_DebugOptionLister.cs @@ -1,5 +1,6 @@ using RimWorld.Planet; using System; +using System.Collections.Generic; using System.Linq; using UnityEngine; @@ -13,7 +14,7 @@ protected void DebugAction(string label, Action action) { GUI.color = new Color(1f, 1f, 1f, 0.3f); } - if (this.listing.ButtonDebug(label)) + if (base.listing.ButtonDebug(label)) { this.Close(true); action(); @@ -21,43 +22,51 @@ protected void DebugAction(string label, Action action) GUI.color = Color.white; if (Event.current.type == EventType.Layout) { - this.totalOptionsHeight += 24f; + base.totalOptionsHeight += 24f; } } protected void DebugToolMap(string label, Action toolAction) { - if (WorldRendererUtility.WorldRenderedNow) - { - return; - } - if (!base.FilterAllows(label)) - { - GUI.color = new Color(1f, 1f, 1f, 0.3f); - } - if (this.listing.ButtonDebug(label)) - { - this.Close(true); - DebugTools.curTool = new DebugTool(label, toolAction, null); - } - GUI.color = Color.white; - if (Event.current.type == EventType.Layout) + if (!WorldRendererUtility.WorldRenderedNow) { - this.totalOptionsHeight += 24f; + if (!base.FilterAllows(label)) + { + GUI.color = new Color(1f, 1f, 1f, 0.3f); + } + if (base.listing.ButtonDebug(label)) + { + this.Close(true); + DebugTools.curTool = new DebugTool(label, toolAction, null); + } + GUI.color = Color.white; + if (Event.current.type == EventType.Layout) + { + base.totalOptionsHeight += 24f; + } } } protected void DebugToolMapForPawns(string label, Action pawnAction) { - this.DebugToolMap(label, delegate + this.DebugToolMap(label, (Action)delegate() { if (UI.MouseCell().InBounds(Find.VisibleMap)) { - foreach (Pawn current in (from t in Find.VisibleMap.thingGrid.ThingsAt(UI.MouseCell()) + List.Enumerator enumerator = (from t in Find.VisibleMap.thingGrid.ThingsAt(UI.MouseCell()) where t is Pawn - select t).Cast().ToList()) + select t).Cast().ToList().GetEnumerator(); + try + { + while (enumerator.MoveNext()) + { + Pawn current = enumerator.Current; + pawnAction(current); + } + } + finally { - pawnAction(current); + ((IDisposable)(object)enumerator).Dispose(); } } }); @@ -65,23 +74,22 @@ where t is Pawn protected void DebugToolWorld(string label, Action toolAction) { - if (!WorldRendererUtility.WorldRenderedNow) - { - return; - } - if (!base.FilterAllows(label)) - { - GUI.color = new Color(1f, 1f, 1f, 0.3f); - } - if (this.listing.ButtonDebug(label)) - { - this.Close(true); - DebugTools.curTool = new DebugTool(label, toolAction, null); - } - GUI.color = Color.white; - if (Event.current.type == EventType.Layout) + if (WorldRendererUtility.WorldRenderedNow) { - this.totalOptionsHeight += 24f; + if (!base.FilterAllows(label)) + { + GUI.color = new Color(1f, 1f, 1f, 0.3f); + } + if (base.listing.ButtonDebug(label)) + { + this.Close(true); + DebugTools.curTool = new DebugTool(label, toolAction, null); + } + GUI.color = Color.white; + if (Event.current.type == EventType.Layout) + { + base.totalOptionsHeight += 24f; + } } } @@ -91,11 +99,11 @@ protected void CheckboxLabeledDebug(string label, ref bool checkOn) { GUI.color = new Color(1f, 1f, 1f, 0.3f); } - this.listing.LabelCheckboxDebug(label, ref checkOn); + base.listing.LabelCheckboxDebug(label, ref checkOn); GUI.color = Color.white; if (Event.current.type == EventType.Layout) { - this.totalOptionsHeight += 24f; + base.totalOptionsHeight += 24f; } } } diff --git a/Assembly-CSharp/Verse/Dialog_DebugSettingsMenu.cs b/Assembly-CSharp/Verse/Dialog_DebugSettingsMenu.cs index c55148bd5..36f16b7cd 100644 --- a/Assembly-CSharp/Verse/Dialog_DebugSettingsMenu.cs +++ b/Assembly-CSharp/Verse/Dialog_DebugSettingsMenu.cs @@ -1,5 +1,4 @@ using RimWorld; -using System; using System.Reflection; using UnityEngine; @@ -17,7 +16,7 @@ public override bool IsDebug public Dialog_DebugSettingsMenu() { - this.forcePause = true; + base.forcePause = true; } protected override void DoListingItems() @@ -28,16 +27,16 @@ protected override void DoListingItems() this.Close(true); } Text.Font = GameFont.Small; - this.listing.Label("Gameplay", -1f); + base.listing.Label("Gameplay", -1f); FieldInfo[] fields = typeof(DebugSettings).GetFields(); for (int i = 0; i < fields.Length; i++) { FieldInfo fi = fields[i]; this.DoField(fi); } - this.listing.Gap(36f); + base.listing.Gap(36f); Text.Font = GameFont.Small; - this.listing.Label("View", -1f); + base.listing.Label("View", -1f); FieldInfo[] fields2 = typeof(DebugViewSettings).GetFields(); for (int j = 0; j < fields2.Length; j++) { @@ -48,17 +47,16 @@ protected override void DoListingItems() private void DoField(FieldInfo fi) { - if (fi.IsLiteral) + if (!fi.IsLiteral) { - return; - } - string label = GenText.SplitCamelCase(fi.Name).CapitalizeFirst(); - bool flag = (bool)fi.GetValue(null); - bool flag2 = flag; - base.CheckboxLabeledDebug(label, ref flag); - if (flag != flag2) - { - fi.SetValue(null, flag); + string label = GenText.SplitCamelCase(fi.Name).CapitalizeFirst(); + bool flag; + bool flag2 = flag = (bool)fi.GetValue(null); + base.CheckboxLabeledDebug(label, ref flag2); + if (flag2 != flag) + { + fi.SetValue(null, flag2); + } } } } diff --git a/Assembly-CSharp/Verse/Dialog_DebugTables.cs b/Assembly-CSharp/Verse/Dialog_DebugTables.cs index b6066f8aa..f4e2c32d3 100644 --- a/Assembly-CSharp/Verse/Dialog_DebugTables.cs +++ b/Assembly-CSharp/Verse/Dialog_DebugTables.cs @@ -1,4 +1,3 @@ -using System; using System.Collections.Generic; using UnityEngine; @@ -25,15 +24,15 @@ public override Vector2 InitialSize public Dialog_DebugTables(string[,] tables) { this.table = tables; - this.doCloseButton = true; - this.doCloseX = true; + base.doCloseButton = true; + base.doCloseX = true; } public override void DoWindowContents(Rect inRect) { Text.Font = GameFont.Tiny; inRect.yMax -= 40f; - Rect viewRect = new Rect(0f, 0f, inRect.width - 16f, (float)this.table.GetLength(1) * 23f); + Rect viewRect = new Rect(0f, 0f, (float)(inRect.width - 16.0), (float)((float)this.table.GetLength(1) * 23.0)); Widgets.BeginScrollView(inRect, ref this.scrollPosition, viewRect, true); List list = new List(); for (int i = 0; i < this.table.GetLength(0); i++) @@ -42,28 +41,29 @@ public override void DoWindowContents(Rect inRect) for (int j = 0; j < this.table.GetLength(1); j++) { string text = this.table[i, j]; - float x = Text.CalcSize(text).x; + Vector2 vector = Text.CalcSize(text); + float x = vector.x; if (x > num) { num = x; } } - list.Add(num + 8f); + list.Add((float)(num + 8.0)); } float num2 = 0f; for (int k = 0; k < this.table.GetLength(0); k++) { for (int l = 0; l < this.table.GetLength(1); l++) { - Rect rect = new Rect(num2, (float)l * 23f, list[k], 23f); - Rect rect2 = rect; - rect2.xMin -= 999f; - rect2.xMax += 999f; - if (Mouse.IsOver(rect2) || k % 2 == 0) + Rect rect; + Rect rect2 = rect = new Rect(num2, (float)((float)l * 23.0), list[k], 23f); + rect.xMin -= 999f; + rect.xMax += 999f; + if (Mouse.IsOver(rect) || k % 2 == 0) { - Widgets.DrawHighlight(rect); + Widgets.DrawHighlight(rect2); } - Widgets.Label(rect, this.table[k, l]); + Widgets.Label(rect2, this.table[k, l]); } num2 += list[k]; } diff --git a/Assembly-CSharp/Verse/Dialog_InfoCard.cs b/Assembly-CSharp/Verse/Dialog_InfoCard.cs index a8e0658ad..6235c916f 100644 --- a/Assembly-CSharp/Verse/Dialog_InfoCard.cs +++ b/Assembly-CSharp/Verse/Dialog_InfoCard.cs @@ -10,10 +10,10 @@ public class Dialog_InfoCard : Window { private enum InfoCardTab : byte { - Stats, - Character, - Health, - Records + Stats = 0, + Character = 1, + Health = 2, + Records = 3 } private Thing thing; @@ -24,7 +24,7 @@ private enum InfoCardTab : byte private WorldObject worldObject; - private Dialog_InfoCard.InfoCardTab tab; + private InfoCardTab tab; private Def Def { @@ -69,7 +69,7 @@ protected override float Margin public Dialog_InfoCard(Thing thing) { this.thing = thing; - this.tab = Dialog_InfoCard.InfoCardTab.Stats; + this.tab = InfoCardTab.Stats; this.Setup(); } @@ -94,13 +94,13 @@ public Dialog_InfoCard(WorldObject worldObject) private void Setup() { - this.forcePause = true; - this.closeOnEscapeKey = true; - this.doCloseButton = true; - this.doCloseX = true; - this.absorbInputAroundWindow = true; - this.soundAppear = SoundDef.Named("InfoCard_Open"); - this.soundClose = SoundDef.Named("InfoCard_Close"); + base.forcePause = true; + base.closeOnEscapeKey = true; + base.doCloseButton = true; + base.doCloseX = true; + base.absorbInputAroundWindow = true; + base.soundAppear = SoundDef.Named("InfoCard_Open"); + base.soundClose = SoundDef.Named("InfoCard_Close"); StatsReportUtility.Reset(); PlayerKnowledgeDatabase.KnowledgeDemonstrated(ConceptDefOf.InfoCard, KnowledgeAmount.Total); } @@ -117,36 +117,38 @@ public override void DoWindowContents(Rect inRect) rect.height = 34f; Text.Font = GameFont.Medium; Widgets.Label(rect, this.GetTitle()); - Rect rect2 = new Rect(inRect); - rect2.yMin = rect.yMax; + Rect rect2 = new Rect(inRect) + { + yMin = rect.yMax + }; rect2.yMax -= 38f; Rect rect3 = rect2; rect3.yMin += 45f; List list = new List(); - TabRecord item = new TabRecord("TabStats".Translate(), delegate + TabRecord item = new TabRecord("TabStats".Translate(), (Action)delegate { - this.tab = Dialog_InfoCard.InfoCardTab.Stats; - }, this.tab == Dialog_InfoCard.InfoCardTab.Stats); + this.tab = InfoCardTab.Stats; + }, this.tab == InfoCardTab.Stats); list.Add(item); if (this.ThingPawn != null) { if (this.ThingPawn.RaceProps.Humanlike) { - TabRecord item2 = new TabRecord("TabCharacter".Translate(), delegate + TabRecord item2 = new TabRecord("TabCharacter".Translate(), (Action)delegate { - this.tab = Dialog_InfoCard.InfoCardTab.Character; - }, this.tab == Dialog_InfoCard.InfoCardTab.Character); + this.tab = InfoCardTab.Character; + }, this.tab == InfoCardTab.Character); list.Add(item2); } - TabRecord item3 = new TabRecord("TabHealth".Translate(), delegate + TabRecord item3 = new TabRecord("TabHealth".Translate(), (Action)delegate { - this.tab = Dialog_InfoCard.InfoCardTab.Health; - }, this.tab == Dialog_InfoCard.InfoCardTab.Health); + this.tab = InfoCardTab.Health; + }, this.tab == InfoCardTab.Health); list.Add(item3); - TabRecord item4 = new TabRecord("TabRecords".Translate(), delegate + TabRecord item4 = new TabRecord("TabRecords".Translate(), (Action)delegate { - this.tab = Dialog_InfoCard.InfoCardTab.Records; - }, this.tab == Dialog_InfoCard.InfoCardTab.Records); + this.tab = InfoCardTab.Records; + }, this.tab == InfoCardTab.Records); list.Add(item4); } TabDrawer.DrawTabs(rect3, list); @@ -155,7 +157,7 @@ public override void DoWindowContents(Rect inRect) protected void FillCard(Rect cardRect) { - if (this.tab == Dialog_InfoCard.InfoCardTab.Stats) + if (this.tab == InfoCardTab.Stats) { if (this.thing != null) { @@ -176,16 +178,16 @@ protected void FillCard(Rect cardRect) StatsReportUtility.DrawStatsReport(cardRect, this.def, this.stuff); } } - else if (this.tab == Dialog_InfoCard.InfoCardTab.Character) + else if (this.tab == InfoCardTab.Character) { CharacterCardUtility.DrawCharacterCard(cardRect, (Pawn)this.thing); } - else if (this.tab == Dialog_InfoCard.InfoCardTab.Health) + else if (this.tab == InfoCardTab.Health) { cardRect.yMin += 8f; HealthCardUtility.DrawPawnHealthCard(cardRect, (Pawn)this.thing, false, false, null); } - else if (this.tab == Dialog_InfoCard.InfoCardTab.Records) + else if (this.tab == InfoCardTab.Records) { RecordsCardUtility.DrawRecordsCard(cardRect, (Pawn)this.thing); } diff --git a/Assembly-CSharp/Verse/Dialog_MessageBox.cs b/Assembly-CSharp/Verse/Dialog_MessageBox.cs index 76db4820a..6a6d79804 100644 --- a/Assembly-CSharp/Verse/Dialog_MessageBox.cs +++ b/Assembly-CSharp/Verse/Dialog_MessageBox.cs @@ -49,7 +49,7 @@ private bool InteractionDelayExpired { get { - return this.TimeUntilInteractive <= 0f; + return this.TimeUntilInteractive <= 0.0; } } @@ -66,15 +66,15 @@ public Dialog_MessageBox(string text, string buttonAText = null, Action buttonAA { this.buttonAText = "OK".Translate(); } - if (buttonAAction == null) + if ((object)buttonAAction == null) { - this.closeOnEscapeKey = true; + base.closeOnEscapeKey = true; } - this.forcePause = true; - this.absorbInputAroundWindow = true; - this.closeOnEscapeKey = false; + base.forcePause = true; + base.absorbInputAroundWindow = true; + base.closeOnEscapeKey = false; this.creationRealTime = RealTime.LastRealTime; - this.onlyOneOfTypeAllowed = false; + base.onlyOneOfTypeAllowed = false; } public static Dialog_MessageBox CreateConfirmation(string text, Action confirmedAct, bool destructive = false, string title = null) @@ -89,11 +89,11 @@ public override void DoWindowContents(Rect inRect) { Text.Font = GameFont.Medium; Widgets.Label(new Rect(0f, num, inRect.width, 42f), this.title); - num += 42f; + num = (float)(num + 42.0); } Text.Font = GameFont.Small; - Rect outRect = new Rect(inRect.x, num, inRect.width, inRect.height - 35f - 5f - num); - float width = outRect.width - 16f; + Rect outRect = new Rect(inRect.x, num, inRect.width, (float)(inRect.height - 35.0 - 5.0 - num)); + float width = (float)(outRect.width - 16.0); Rect viewRect = new Rect(0f, 0f, width, Text.CalcHeight(this.text, width)); Widgets.BeginScrollView(outRect, ref this.scrollPosition, viewRect, true); Widgets.Label(new Rect(0f, 0f, viewRect.width, viewRect.height), this.text); @@ -103,19 +103,19 @@ public override void DoWindowContents(Rect inRect) GUI.color = new Color(1f, 0.3f, 0.35f); } string label = (!this.InteractionDelayExpired) ? (this.buttonAText + "(" + Mathf.Ceil(this.TimeUntilInteractive).ToString("F0") + ")") : this.buttonAText; - float width2 = inRect.width / 2f - 20f; - if (Widgets.ButtonText(new Rect(inRect.width / 2f + 20f, inRect.height - 35f, width2, 35f), label, true, false, true) && this.InteractionDelayExpired) + float width2 = (float)(inRect.width / 2.0 - 20.0); + if (Widgets.ButtonText(new Rect((float)(inRect.width / 2.0 + 20.0), (float)(inRect.height - 35.0), width2, 35f), label, true, false, true) && this.InteractionDelayExpired) { - if (this.buttonAAction != null) + if ((object)this.buttonAAction != null) { this.buttonAAction(); } this.Close(true); } GUI.color = Color.white; - if (this.buttonBText != null && Widgets.ButtonText(new Rect(0f, inRect.height - 35f, width2, 35f), this.buttonBText, true, false, true)) + if (this.buttonBText != null && Widgets.ButtonText(new Rect(0f, (float)(inRect.height - 35.0), width2, 35f), this.buttonBText, true, false, true)) { - if (this.buttonBAction != null) + if ((object)this.buttonBAction != null) { this.buttonBAction(); } diff --git a/Assembly-CSharp/Verse/Dialog_NodeTree.cs b/Assembly-CSharp/Verse/Dialog_NodeTree.cs index 2652282d7..4d2257786 100644 --- a/Assembly-CSharp/Verse/Dialog_NodeTree.cs +++ b/Assembly-CSharp/Verse/Dialog_NodeTree.cs @@ -1,5 +1,6 @@ using RimWorld; using System; +using System.Collections.Generic; using UnityEngine; namespace Verse @@ -44,19 +45,19 @@ public Dialog_NodeTree(DiaNode nodeRoot, bool delayInteractivity = false, bool r { this.title = title; this.GotoNode(nodeRoot); - this.forcePause = true; - this.absorbInputAroundWindow = true; - this.closeOnEscapeKey = false; + base.forcePause = true; + base.absorbInputAroundWindow = true; + base.closeOnEscapeKey = false; if (delayInteractivity) { - this.makeInteractiveAtTime = Time.realtimeSinceStartup + 0.5f; - this.closeOnEscapeKey = false; + this.makeInteractiveAtTime = (float)(Time.realtimeSinceStartup + 0.5); + base.closeOnEscapeKey = false; } - this.soundAppear = SoundDefOf.CommsWindow_Open; - this.soundClose = SoundDefOf.CommsWindow_Close; + base.soundAppear = SoundDefOf.CommsWindow_Open; + base.soundClose = SoundDefOf.CommsWindow_Close; if (radioMode) { - this.soundAmbient = SoundDefOf.RadioComms_Ambience; + base.soundAmbient = SoundDefOf.RadioComms_Ambience; } } @@ -69,7 +70,7 @@ public override void PreClose() public override void PostClose() { base.PostClose(); - if (this.closeAction != null) + if ((object)this.closeAction != null) { this.closeAction(); } @@ -106,12 +107,12 @@ protected void DrawNode(Rect rect) { if (this.InteractiveNow) { - this.closeOnEscapeKey = true; + base.closeOnEscapeKey = true; } GUI.BeginGroup(rect); Text.Font = GameFont.Small; Rect outRect = new Rect(0f, 0f, rect.width, rect.height - this.optTotalHeight); - float width = rect.width - 16f; + float width = (float)(rect.width - 16.0); Rect rect2 = new Rect(0f, 0f, width, Text.CalcHeight(this.curNode.text, width)); Widgets.BeginScrollView(outRect, ref this.scrollPosition, rect2, true); Widgets.Label(rect2, this.curNode.text); @@ -120,10 +121,10 @@ protected void DrawNode(Rect rect) float num2 = 0f; for (int i = 0; i < this.curNode.options.Count; i++) { - Rect rect3 = new Rect(15f, num, rect.width - 30f, 999f); + Rect rect3 = new Rect(15f, num, (float)(rect.width - 30.0), 999f); float num3 = this.curNode.options[i].OptOnGUI(rect3, this.InteractiveNow); - num += num3 + 7f; - num2 += num3 + 7f; + num = (float)(num + (num3 + 7.0)); + num2 = (float)(num2 + (num3 + 7.0)); } if (Event.current.type == EventType.Layout) { @@ -134,9 +135,18 @@ protected void DrawNode(Rect rect) public void GotoNode(DiaNode node) { - foreach (DiaOption current in node.options) + List.Enumerator enumerator = node.options.GetEnumerator(); + try { - current.dialog = this; + while (enumerator.MoveNext()) + { + DiaOption current = enumerator.Current; + current.dialog = this; + } + } + finally + { + ((IDisposable)(object)enumerator).Dispose(); } this.curNode = node; } diff --git a/Assembly-CSharp/Verse/Dialog_OptionLister.cs b/Assembly-CSharp/Verse/Dialog_OptionLister.cs index c6eb4b53b..a36a0c4fd 100644 --- a/Assembly-CSharp/Verse/Dialog_OptionLister.cs +++ b/Assembly-CSharp/Verse/Dialog_OptionLister.cs @@ -39,10 +39,10 @@ public override bool IsDebug public Dialog_OptionLister() { - this.closeOnEscapeKey = true; - this.doCloseX = true; - this.onlyOneOfTypeAllowed = true; - this.absorbInputAroundWindow = true; + base.closeOnEscapeKey = true; + base.doCloseX = true; + base.onlyOneOfTypeAllowed = true; + base.absorbInputAroundWindow = true; } public override void DoWindowContents(Rect inRect) @@ -54,15 +54,15 @@ public override void DoWindowContents(Rect inRect) } Rect outRect = new Rect(inRect); outRect.yMin += 35f; - float num = (this.totalOptionsHeight + 72f) / 4f; + float num = (float)((this.totalOptionsHeight + 72.0) / 4.0); if (num < outRect.height) { num = outRect.height; } - Rect rect = new Rect(0f, 0f, outRect.width - 16f, num); + Rect rect = new Rect(0f, 0f, (float)(outRect.width - 16.0), num); Widgets.BeginScrollView(outRect, ref this.scrollPosition, rect, true); this.listing = new Listing_Standard(); - this.listing.ColumnWidth = (rect.width - 51f) / 4f; + this.listing.ColumnWidth = (float)((rect.width - 51.0) / 4.0); this.listing.Begin(rect); this.DoListingItems(); this.listing.End(); @@ -79,7 +79,15 @@ public override void PostClose() protected bool FilterAllows(string label) { - return this.filter.NullOrEmpty() || label.NullOrEmpty() || label.IndexOf(this.filter, StringComparison.OrdinalIgnoreCase) >= 0; + if (this.filter.NullOrEmpty()) + { + return true; + } + if (label.NullOrEmpty()) + { + return true; + } + return label.IndexOf(this.filter, StringComparison.OrdinalIgnoreCase) >= 0; } } } diff --git a/Assembly-CSharp/Verse/Dialog_PackageSelector.cs b/Assembly-CSharp/Verse/Dialog_PackageSelector.cs index 63e67d0b0..f3a34c051 100644 --- a/Assembly-CSharp/Verse/Dialog_PackageSelector.cs +++ b/Assembly-CSharp/Verse/Dialog_PackageSelector.cs @@ -33,10 +33,10 @@ public Dialog_PackageSelector(Action setPackageCallback, ModContentP this.setPackageCallback = setPackageCallback; this.mod = mod; this.relFolder = relFolder; - this.doCloseX = true; - this.closeOnEscapeKey = true; - this.onlyOneOfTypeAllowed = true; - this.draggable = true; + base.doCloseX = true; + base.closeOnEscapeKey = true; + base.onlyOneOfTypeAllowed = true; + base.draggable = true; } public override void DoWindowContents(Rect inRect) @@ -44,12 +44,12 @@ public override void DoWindowContents(Rect inRect) Listing_Standard listing_Standard = new Listing_Standard(); listing_Standard.Begin(inRect.AtZero()); listing_Standard.ColumnWidth = 240f; - foreach (DefPackage current in this.mod.GetDefPackagesInFolder(this.relFolder)) + foreach (DefPackage item in this.mod.GetDefPackagesInFolder(this.relFolder)) { - string fileNameWithoutExtension = Path.GetFileNameWithoutExtension(current.fileName); - if (listing_Standard.ButtonText(fileNameWithoutExtension, null)) + string fileNameWithoutExtension = Path.GetFileNameWithoutExtension(item.fileName); + if (listing_Standard.ButtonText(fileNameWithoutExtension, (string)null)) { - this.setPackageCallback(current); + this.setPackageCallback(item); this.Close(true); } } diff --git a/Assembly-CSharp/Verse/Dialog_PawnTableTest.cs b/Assembly-CSharp/Verse/Dialog_PawnTableTest.cs index 8d68d552d..b0d639541 100644 --- a/Assembly-CSharp/Verse/Dialog_PawnTableTest.cs +++ b/Assembly-CSharp/Verse/Dialog_PawnTableTest.cs @@ -30,7 +30,7 @@ private List Pawns { get { - return Find.VisibleMap.mapPawns.PawnsInFaction(Faction.OfPlayer).ToList(); + return Find.VisibleMap.mapPawns.PawnsInFaction(Faction.OfPlayer).ToList(); } } @@ -44,17 +44,17 @@ public override void DoWindowContents(Rect inRect) int num = ((int)inRect.height - 90) / 3; if (this.pawnTableMin == null) { - this.pawnTableMin = new PawnTable(Gen.YieldSingle(this.singleColumn), () => this.Pawns, 0, 0, 0, 0); + this.pawnTableMin = new PawnTable(Gen.YieldSingle(this.singleColumn), (Func>)(() => this.Pawns), 0, 0, 0, 0); this.pawnTableMin.SetMinMaxSize(Mathf.Min(this.singleColumn.Worker.GetMinWidth(this.pawnTableMin) + 16, (int)inRect.width), Mathf.Min(this.singleColumn.Worker.GetMinWidth(this.pawnTableMin) + 16, (int)inRect.width), 0, num); } if (this.pawnTableOptimal == null) { - this.pawnTableOptimal = new PawnTable(Gen.YieldSingle(this.singleColumn), () => this.Pawns, 0, 0, 0, 0); + this.pawnTableOptimal = new PawnTable(Gen.YieldSingle(this.singleColumn), (Func>)(() => this.Pawns), 0, 0, 0, 0); this.pawnTableOptimal.SetMinMaxSize(Mathf.Min(this.singleColumn.Worker.GetOptimalWidth(this.pawnTableOptimal) + 16, (int)inRect.width), Mathf.Min(this.singleColumn.Worker.GetOptimalWidth(this.pawnTableOptimal) + 16, (int)inRect.width), 0, num); } if (this.pawnTableMax == null) { - this.pawnTableMax = new PawnTable(Gen.YieldSingle(this.singleColumn), () => this.Pawns, 0, 0, 0, 0); + this.pawnTableMax = new PawnTable(Gen.YieldSingle(this.singleColumn), (Func>)(() => this.Pawns), 0, 0, 0, 0); this.pawnTableMax.SetMinMaxSize(Mathf.Min(this.singleColumn.Worker.GetMaxWidth(this.pawnTableMax) + 16, (int)inRect.width), Mathf.Min(this.singleColumn.Worker.GetMaxWidth(this.pawnTableMax) + 16, (int)inRect.width), 0, num); } int num2 = 0; diff --git a/Assembly-CSharp/Verse/Dialog_Rename.cs b/Assembly-CSharp/Verse/Dialog_Rename.cs index 88a866a5c..1e5e32fe3 100644 --- a/Assembly-CSharp/Verse/Dialog_Rename.cs +++ b/Assembly-CSharp/Verse/Dialog_Rename.cs @@ -1,4 +1,3 @@ -using System; using UnityEngine; namespace Verse @@ -25,11 +24,11 @@ public override Vector2 InitialSize public Dialog_Rename() { - this.forcePause = true; - this.doCloseX = true; - this.closeOnEscapeKey = true; - this.absorbInputAroundWindow = true; - this.closeOnClickedOutside = true; + base.forcePause = true; + base.doCloseX = true; + base.closeOnEscapeKey = true; + base.absorbInputAroundWindow = true; + base.closeOnClickedOutside = true; } protected virtual AcceptanceReport NameIsValid(string name) @@ -55,26 +54,25 @@ public override void DoWindowContents(Rect inRect) { this.curName = text; } - if (Widgets.ButtonText(new Rect(15f, inRect.height - 35f - 15f, inRect.width - 15f - 15f, 35f), "OK", true, false, true) || flag) + if (!Widgets.ButtonText(new Rect(15f, (float)(inRect.height - 35.0 - 15.0), (float)(inRect.width - 15.0 - 15.0), 35f), "OK", true, false, true) && !flag) + return; + AcceptanceReport acceptanceReport = this.NameIsValid(this.curName); + if (!acceptanceReport.Accepted) { - AcceptanceReport acceptanceReport = this.NameIsValid(this.curName); - if (!acceptanceReport.Accepted) + if (acceptanceReport.Reason == null) { - if (acceptanceReport.Reason == null) - { - Messages.Message("NameIsInvalid".Translate(), MessageSound.RejectInput); - } - else - { - Messages.Message(acceptanceReport.Reason, MessageSound.RejectInput); - } + Messages.Message("NameIsInvalid".Translate(), MessageSound.RejectInput); } else { - this.SetName(this.curName); - Find.WindowStack.TryRemove(this, true); + Messages.Message(acceptanceReport.Reason, MessageSound.RejectInput); } } + else + { + this.SetName(this.curName); + Find.WindowStack.TryRemove(this, true); + } } protected abstract void SetName(string name); diff --git a/Assembly-CSharp/Verse/Dialog_RenameArea.cs b/Assembly-CSharp/Verse/Dialog_RenameArea.cs index 8263d3c29..b0793f7fb 100644 --- a/Assembly-CSharp/Verse/Dialog_RenameArea.cs +++ b/Assembly-CSharp/Verse/Dialog_RenameArea.cs @@ -9,7 +9,7 @@ public class Dialog_RenameArea : Dialog_Rename public Dialog_RenameArea(Area area) { this.area = area; - this.curName = area.Label; + base.curName = area.Label; } protected override AcceptanceReport NameIsValid(string name) @@ -19,7 +19,7 @@ protected override AcceptanceReport NameIsValid(string name) { return result; } - if (this.area.Map.areaManager.AllAreas.Any((Area a) => a.Label == name)) + if (this.area.Map.areaManager.AllAreas.Any((Predicate)((Area a) => a.Label == name))) { return "NameIsInUse".Translate(); } @@ -28,7 +28,7 @@ protected override AcceptanceReport NameIsValid(string name) protected override void SetName(string name) { - this.area.SetLabel(this.curName); + this.area.SetLabel(base.curName); } } } diff --git a/Assembly-CSharp/Verse/Dialog_RenamePackage.cs b/Assembly-CSharp/Verse/Dialog_RenamePackage.cs index ab8707ab8..7e2816a8c 100644 --- a/Assembly-CSharp/Verse/Dialog_RenamePackage.cs +++ b/Assembly-CSharp/Verse/Dialog_RenamePackage.cs @@ -1,4 +1,3 @@ -using System; using System.IO; using UnityEngine; @@ -30,9 +29,9 @@ public Dialog_RenamePackage(DefPackage renamingPackage) { this.renamingPackage = renamingPackage; this.proposedName = renamingPackage.fileName; - this.closeOnEscapeKey = true; - this.doCloseX = true; - this.forcePause = true; + base.closeOnEscapeKey = true; + base.doCloseX = true; + base.forcePause = true; } public override void DoWindowContents(Rect inRect) diff --git a/Assembly-CSharp/Verse/Dialog_RenameZone.cs b/Assembly-CSharp/Verse/Dialog_RenameZone.cs index f479778f3..0ea079098 100644 --- a/Assembly-CSharp/Verse/Dialog_RenameZone.cs +++ b/Assembly-CSharp/Verse/Dialog_RenameZone.cs @@ -9,7 +9,7 @@ public class Dialog_RenameZone : Dialog_Rename public Dialog_RenameZone(Zone zone) { this.zone = zone; - this.curName = zone.label; + base.curName = zone.label; } protected override AcceptanceReport NameIsValid(string name) @@ -19,7 +19,7 @@ protected override AcceptanceReport NameIsValid(string name) { return result; } - if (this.zone.Map.zoneManager.AllZones.Any((Zone z) => z.label == name)) + if (this.zone.Map.zoneManager.AllZones.Any((Predicate)((Zone z) => z.label == name))) { return "NameIsInUse".Translate(); } @@ -28,11 +28,8 @@ protected override AcceptanceReport NameIsValid(string name) protected override void SetName(string name) { - this.zone.label = this.curName; - Messages.Message("ZoneGainsName".Translate(new object[] - { - this.curName - }), MessageSound.Benefit); + this.zone.label = base.curName; + Messages.Message("ZoneGainsName".Translate(base.curName), MessageSound.Benefit); } } } diff --git a/Assembly-CSharp/Verse/Dialog_ResolutionConfirm.cs b/Assembly-CSharp/Verse/Dialog_ResolutionConfirm.cs index 0e5d12c71..4cfd7c8e5 100644 --- a/Assembly-CSharp/Verse/Dialog_ResolutionConfirm.cs +++ b/Assembly-CSharp/Verse/Dialog_ResolutionConfirm.cs @@ -1,4 +1,3 @@ -using System; using UnityEngine; namespace Verse @@ -19,7 +18,7 @@ private float TimeUntilRevert { get { - return this.startTime + 10f - Time.realtimeSinceStartup; + return (float)(this.startTime + 10.0 - Time.realtimeSinceStartup); } } @@ -34,8 +33,8 @@ public override Vector2 InitialSize private Dialog_ResolutionConfirm() { this.startTime = Time.realtimeSinceStartup; - this.closeOnEscapeKey = false; - this.absorbInputAroundWindow = true; + base.closeOnEscapeKey = false; + base.absorbInputAroundWindow = true; } public Dialog_ResolutionConfirm(bool oldFullscreen) : this() @@ -62,16 +61,13 @@ public Dialog_ResolutionConfirm(float oldUIScale) : this() public override void DoWindowContents(Rect inRect) { Text.Font = GameFont.Small; - string label = "ConfirmResolutionChange".Translate(new object[] - { - Mathf.CeilToInt(this.TimeUntilRevert) - }); + string label = "ConfirmResolutionChange".Translate(Mathf.CeilToInt(this.TimeUntilRevert)); Widgets.Label(new Rect(0f, 0f, inRect.width, inRect.height), label); - if (Widgets.ButtonText(new Rect(0f, inRect.height - 35f, inRect.width / 2f - 20f, 35f), "ResolutionKeep".Translate(), true, false, true)) + if (Widgets.ButtonText(new Rect(0f, (float)(inRect.height - 35.0), (float)(inRect.width / 2.0 - 20.0), 35f), "ResolutionKeep".Translate(), true, false, true)) { this.Close(true); } - if (Widgets.ButtonText(new Rect(inRect.width / 2f + 20f, inRect.height - 35f, inRect.width / 2f - 20f, 35f), "ResolutionRevert".Translate(), true, false, true)) + if (Widgets.ButtonText(new Rect((float)(inRect.width / 2.0 + 20.0), (float)(inRect.height - 35.0), (float)(inRect.width / 2.0 - 20.0), 35f), "ResolutionRevert".Translate(), true, false, true)) { this.Revert(); this.Close(true); @@ -82,15 +78,7 @@ private void Revert() { if (Prefs.LogVerbose) { - Log.Message(string.Concat(new object[] - { - "Reverting screen settings to ", - this.oldRes.x, - "x", - this.oldRes.z, - ", fs=", - this.oldFullscreen - })); + Log.Message("Reverting screen settings to " + this.oldRes.x + "x" + this.oldRes.z + ", fs=" + this.oldFullscreen); } Screen.SetResolution(this.oldRes.x, this.oldRes.z, this.oldFullscreen); Prefs.UIScale = this.oldUIScale; @@ -98,7 +86,7 @@ private void Revert() public override void WindowUpdate() { - if (this.TimeUntilRevert <= 0f) + if (this.TimeUntilRevert <= 0.0) { this.Revert(); this.Close(true); diff --git a/Assembly-CSharp/Verse/Dialog_Slider.cs b/Assembly-CSharp/Verse/Dialog_Slider.cs index 7b856b412..e5a4cf1e8 100644 --- a/Assembly-CSharp/Verse/Dialog_Slider.cs +++ b/Assembly-CSharp/Verse/Dialog_Slider.cs @@ -33,9 +33,9 @@ public Dialog_Slider(Func textGetter, int from, int to, Action this.from = from; this.to = to; this.confirmAction = confirmAction; - this.forcePause = true; - this.closeOnEscapeKey = true; - this.closeOnClickedOutside = true; + base.forcePause = true; + base.closeOnEscapeKey = true; + base.closeOnClickedOutside = true; if (startingValue == -2147483648) { this.curValue = from; @@ -46,21 +46,21 @@ public Dialog_Slider(Func textGetter, int from, int to, Action } } - public Dialog_Slider(string text, int from, int to, Action confirmAction, int startingValue = -2147483648) : this((int val) => string.Format(text, val), from, to, confirmAction, startingValue) + public Dialog_Slider(string text, int from, int to, Action confirmAction, int startingValue = -2147483648) : this((Func)((int val) => string.Format(text, val)), from, to, confirmAction, startingValue) { } public override void DoWindowContents(Rect inRect) { - Rect rect = new Rect(inRect.x, inRect.y + 15f, inRect.width, 30f); - this.curValue = (int)Widgets.HorizontalSlider(rect, (float)this.curValue, (float)this.from, (float)this.to, true, this.textGetter(this.curValue), null, null, 1f); + Rect rect = new Rect(inRect.x, (float)(inRect.y + 15.0), inRect.width, 30f); + this.curValue = (int)Widgets.HorizontalSlider(rect, (float)this.curValue, (float)this.from, (float)this.to, true, this.textGetter(this.curValue), (string)null, (string)null, 1f); Text.Font = GameFont.Small; - Rect rect2 = new Rect(inRect.x, inRect.yMax - 30f, inRect.width / 2f, 30f); + Rect rect2 = new Rect(inRect.x, (float)(inRect.yMax - 30.0), (float)(inRect.width / 2.0), 30f); if (Widgets.ButtonText(rect2, "CancelButton".Translate(), true, false, true)) { this.Close(true); } - Rect rect3 = new Rect(inRect.x + inRect.width / 2f, inRect.yMax - 30f, inRect.width / 2f, 30f); + Rect rect3 = new Rect((float)(inRect.x + inRect.width / 2.0), (float)(inRect.yMax - 30.0), (float)(inRect.width / 2.0), 30f); if (Widgets.ButtonText(rect3, "OK".Translate(), true, false, true)) { this.Close(true); diff --git a/Assembly-CSharp/Verse/DietCategory.cs b/Assembly-CSharp/Verse/DietCategory.cs index aebbbaad5..bbdea825a 100644 --- a/Assembly-CSharp/Verse/DietCategory.cs +++ b/Assembly-CSharp/Verse/DietCategory.cs @@ -1,14 +1,12 @@ -using System; - namespace Verse { public enum DietCategory : byte { - NeverEats, - Herbivorous, - Dendrovorous, - Ovivorous, - Omnivorous, - Carnivorous + NeverEats = 0, + Herbivorous = 1, + Dendrovorous = 2, + Ovivorous = 3, + Omnivorous = 4, + Carnivorous = 5 } } diff --git a/Assembly-CSharp/Verse/Dijkstra.cs b/Assembly-CSharp/Verse/Dijkstra.cs index 86c36cba6..4bcde5af0 100644 --- a/Assembly-CSharp/Verse/Dijkstra.cs +++ b/Assembly-CSharp/Verse/Dijkstra.cs @@ -16,7 +16,7 @@ public int Compare(KeyValuePair a, KeyValuePair b) private static Dictionary distances = new Dictionary(); - private static FastPriorityQueue> queue = new FastPriorityQueue>(new Dijkstra.DistanceComparer()); + private static FastPriorityQueue> queue = new FastPriorityQueue>((IComparer>)new DistanceComparer()); private static List singleNodeList = new List(); @@ -26,7 +26,7 @@ public static void Run(T startingNode, Func> neighborsGetter, { Dijkstra.singleNodeList.Clear(); Dijkstra.singleNodeList.Add(startingNode); - Dijkstra.Run(Dijkstra.singleNodeList, neighborsGetter, distanceGetter, ref outDistances); + Dijkstra.Run((IEnumerable)Dijkstra.singleNodeList, neighborsGetter, distanceGetter, ref outDistances); } public static void Run(IEnumerable startingNodes, Func> neighborsGetter, Func distanceGetter, ref List> outDistances) @@ -37,7 +37,7 @@ public static void Run(IEnumerable startingNodes, Func> nei IList list = startingNodes as IList; if (list != null) { - for (int i = 0; i < list.Count; i++) + for (int i = 0; i < ((ICollection)list).Count; i++) { T key = list[i]; if (!Dijkstra.distances.ContainsKey(key)) @@ -49,12 +49,12 @@ public static void Run(IEnumerable startingNodes, Func> nei } else { - foreach (T current in startingNodes) + foreach (T item in startingNodes) { - if (!Dijkstra.distances.ContainsKey(current)) + if (!Dijkstra.distances.ContainsKey(item)) { - Dijkstra.distances.Add(current, 0f); - Dijkstra.queue.Push(new KeyValuePair(current, 0f)); + Dijkstra.distances.Add(item, 0f); + Dijkstra.queue.Push(new KeyValuePair(item, 0f)); } } } @@ -70,24 +70,33 @@ public static void Run(IEnumerable startingNodes, Func> nei IList list2 = enumerable as IList; if (list2 != null) { - for (int j = 0; j < list2.Count; j++) + for (int j = 0; j < ((ICollection)list2).Count; j++) { Dijkstra.HandleNeighbor(list2[j], num, node, distanceGetter); } } else { - foreach (T current2 in enumerable) + foreach (T item2 in enumerable) { - Dijkstra.HandleNeighbor(current2, num, node, distanceGetter); + Dijkstra.HandleNeighbor(item2, num, node, distanceGetter); } } } } } - foreach (KeyValuePair current3 in Dijkstra.distances) + Dictionary.Enumerator enumerator3 = Dijkstra.distances.GetEnumerator(); + try { - outDistances.Add(current3); + while (enumerator3.MoveNext()) + { + KeyValuePair current3 = enumerator3.Current; + outDistances.Add(current3); + } + } + finally + { + ((IDisposable)(object)enumerator3).Dispose(); } Dijkstra.distances.Clear(); } @@ -106,7 +115,7 @@ public static void Run(IEnumerable startingNodes, Func> nei private static void HandleNeighbor(T n, float nodeDist, KeyValuePair node, Func distanceGetter) { float num = nodeDist + Mathf.Max(distanceGetter(node.Key, n), 0f); - float num2; + float num2 = default(float); if (Dijkstra.distances.TryGetValue(n, out num2)) { if (num < num2) diff --git a/Assembly-CSharp/Verse/DijkstraUtility.cs b/Assembly-CSharp/Verse/DijkstraUtility.cs index e58982e96..e43ef8d62 100644 --- a/Assembly-CSharp/Verse/DijkstraUtility.cs +++ b/Assembly-CSharp/Verse/DijkstraUtility.cs @@ -1,4 +1,3 @@ -using System; using System.Collections.Generic; namespace Verse diff --git a/Assembly-CSharp/Verse/DirectXmlCrossRefLoader.cs b/Assembly-CSharp/Verse/DirectXmlCrossRefLoader.cs index 9735a7bfd..5692a2038 100644 --- a/Assembly-CSharp/Verse/DirectXmlCrossRefLoader.cs +++ b/Assembly-CSharp/Verse/DirectXmlCrossRefLoader.cs @@ -14,7 +14,7 @@ private abstract class WantedRef public abstract bool TryResolve(FailMode failReportMode); } - private class WantedRefForObject : DirectXmlCrossRefLoader.WantedRef + private class WantedRefForObject : WantedRef { public FieldInfo fi; @@ -22,7 +22,7 @@ private class WantedRefForObject : DirectXmlCrossRefLoader.WantedRef public WantedRefForObject(object wanter, FieldInfo fi, string targetDefName) { - this.wanter = wanter; + base.wanter = wanter; this.fi = fi; this.defName = targetDefName; } @@ -39,48 +39,27 @@ public override bool TryResolve(FailMode failReportMode) { if (failReportMode == FailMode.LogErrors) { - Log.Error(string.Concat(new object[] - { - "Could not resolve cross-reference: No ", - this.fi.FieldType, - " named ", - this.defName, - " found to give to ", - this.wanter.GetType(), - " ", - this.wanter - })); + Log.Error("Could not resolve cross-reference: No " + this.fi.FieldType + " named " + this.defName + " found to give to " + base.wanter.GetType() + " " + base.wanter); } return false; } SoundDef soundDef = defSilentFail as SoundDef; if (soundDef != null && soundDef.isUndefined) { - Log.Warning(string.Concat(new object[] - { - "Could not resolve cross-reference: No ", - this.fi.FieldType, - " named ", - this.defName, - " found to give to ", - this.wanter.GetType(), - " ", - this.wanter, - " (using undefined sound instead)" - })); + Log.Warning("Could not resolve cross-reference: No " + this.fi.FieldType + " named " + this.defName + " found to give to " + base.wanter.GetType() + " " + base.wanter + " (using undefined sound instead)"); } - this.fi.SetValue(this.wanter, defSilentFail); + this.fi.SetValue(base.wanter, defSilentFail); return true; } } - private class WantedRefForList : DirectXmlCrossRefLoader.WantedRef where T : new() + private class WantedRefForList : WantedRef where T : new() { private List defNames = new List(); public WantedRefForList(object wanter) { - this.wanter = wanter; + base.wanter = wanter; } public void AddWantedListEntry(string newTargetDefName) @@ -93,10 +72,10 @@ public override bool TryResolve(FailMode failReportMode) bool flag = false; for (int i = 0; i < this.defNames.Count; i++) { - T t = DirectXmlCrossRefLoader.TryResolveDef(this.defNames[i], failReportMode); - if (t != null) + T val = DirectXmlCrossRefLoader.TryResolveDef(this.defNames[i], failReportMode); + if (val != null) { - ((List)this.wanter).Add(t); + ((List)base.wanter).Add(val); this.defNames.RemoveAt(i); i--; } @@ -109,13 +88,13 @@ public override bool TryResolve(FailMode failReportMode) } } - private class WantedRefForDictionary : DirectXmlCrossRefLoader.WantedRef where K : new() where V : new() + private class WantedRefForDictionary : WantedRef where K : new() where V : new() { private List wantedDictRefs = new List(); public WantedRefForDictionary(object wanter) { - this.wanter = wanter; + base.wanter = wanter; } public void AddWantedDictEntry(XmlNode entryNode) @@ -129,54 +108,50 @@ public override bool TryResolve(FailMode failReportMode) bool flag = typeof(Def).IsAssignableFrom(typeof(K)); bool flag2 = typeof(Def).IsAssignableFrom(typeof(V)); List> list = new List>(); - foreach (XmlNode current in this.wantedDictRefs) + List.Enumerator enumerator = this.wantedDictRefs.GetEnumerator(); + try { - XmlNode xmlNode = current["key"]; - XmlNode xmlNode2 = current["value"]; - K first; - if (flag) - { - first = DirectXmlCrossRefLoader.TryResolveDef(xmlNode.InnerText, failReportMode); - } - else - { - first = DirectXmlToObject.ObjectFromXml(xmlNode, true); - } - V second; - if (flag2) + while (enumerator.MoveNext()) { - second = DirectXmlCrossRefLoader.TryResolveDef(xmlNode2.InnerText, failReportMode); + XmlNode current = enumerator.Current; + XmlNode xmlNode = current["key"]; + XmlNode xmlNode2 = current["value"]; + K first = (!flag) ? DirectXmlToObject.ObjectFromXml(xmlNode, true) : DirectXmlCrossRefLoader.TryResolveDef(xmlNode.InnerText, failReportMode); + V second = (!flag2) ? DirectXmlToObject.ObjectFromXml(xmlNode2, true) : DirectXmlCrossRefLoader.TryResolveDef(xmlNode2.InnerText, failReportMode); + list.Add(new Pair(first, second)); } - else - { - second = DirectXmlToObject.ObjectFromXml(xmlNode2, true); - } - list.Add(new Pair(first, second)); } - Dictionary dictionary = (Dictionary)this.wanter; + finally + { + ((IDisposable)(object)enumerator).Dispose(); + } + Dictionary dictionary = (Dictionary)base.wanter; dictionary.Clear(); - foreach (Pair current2 in list) + List>.Enumerator enumerator2 = list.GetEnumerator(); + try { - try + while (enumerator2.MoveNext()) { - dictionary.Add(current2.First, current2.Second); - } - catch - { - Log.Error(string.Concat(new object[] + Pair current2 = enumerator2.Current; + try + { + dictionary.Add(current2.First, current2.Second); + } + catch { - "Failed to load key/value pair: ", - current2.First, - ", ", - current2.Second - })); + Log.Error("Failed to load key/value pair: " + current2.First + ", " + current2.Second); + } } } + finally + { + ((IDisposable)(object)enumerator2).Dispose(); + } return true; } } - private static List wantedRefs = new List(); + private static List wantedRefs = new List(); public static bool LoadingInProgress { @@ -188,70 +163,82 @@ public static bool LoadingInProgress public static void RegisterObjectWantsCrossRef(object wanter, FieldInfo fi, string targetDefName) { - DirectXmlCrossRefLoader.WantedRefForObject item = new DirectXmlCrossRefLoader.WantedRefForObject(wanter, fi, targetDefName); + WantedRefForObject item = new WantedRefForObject(wanter, fi, targetDefName); DirectXmlCrossRefLoader.wantedRefs.Add(item); } public static void RegisterObjectWantsCrossRef(object wanter, string fieldName, string targetDefName) { - DirectXmlCrossRefLoader.WantedRefForObject item = new DirectXmlCrossRefLoader.WantedRefForObject(wanter, wanter.GetType().GetField(fieldName), targetDefName); + WantedRefForObject item = new WantedRefForObject(wanter, wanter.GetType().GetField(fieldName), targetDefName); DirectXmlCrossRefLoader.wantedRefs.Add(item); } public static void RegisterListWantsCrossRef(List wanterList, string targetDefName) where T : new() { - DirectXmlCrossRefLoader.WantedRefForList wantedRefForList = null; - foreach (DirectXmlCrossRefLoader.WantedRef current in DirectXmlCrossRefLoader.wantedRefs) + WantedRefForList wantedRefForList = null; + List.Enumerator enumerator = DirectXmlCrossRefLoader.wantedRefs.GetEnumerator(); + try { - if (current.wanter == wanterList) + while (enumerator.MoveNext()) { - wantedRefForList = (DirectXmlCrossRefLoader.WantedRefForList)current; - break; + WantedRef current = enumerator.Current; + if (current.wanter == wanterList) + { + wantedRefForList = (WantedRefForList)current; + break; + } } } + finally + { + ((IDisposable)(object)enumerator).Dispose(); + } if (wantedRefForList == null) { - wantedRefForList = new DirectXmlCrossRefLoader.WantedRefForList(wanterList); - DirectXmlCrossRefLoader.wantedRefs.Add(wantedRefForList); + wantedRefForList = new WantedRefForList((object)wanterList); + DirectXmlCrossRefLoader.wantedRefs.Add((WantedRef)wantedRefForList); } wantedRefForList.AddWantedListEntry(targetDefName); } public static void RegisterDictionaryWantsCrossRef(Dictionary wanterDict, XmlNode entryNode) where K : new() where V : new() { - DirectXmlCrossRefLoader.WantedRefForDictionary wantedRefForDictionary = null; - foreach (DirectXmlCrossRefLoader.WantedRef current in DirectXmlCrossRefLoader.wantedRefs) + WantedRefForDictionary wantedRefForDictionary = null; + List.Enumerator enumerator = DirectXmlCrossRefLoader.wantedRefs.GetEnumerator(); + try { - if (current.wanter == wanterDict) + while (enumerator.MoveNext()) { - wantedRefForDictionary = (DirectXmlCrossRefLoader.WantedRefForDictionary)current; - break; + WantedRef current = enumerator.Current; + if (current.wanter == wanterDict) + { + wantedRefForDictionary = (WantedRefForDictionary)current; + break; + } } } + finally + { + ((IDisposable)(object)enumerator).Dispose(); + } if (wantedRefForDictionary == null) { - wantedRefForDictionary = new DirectXmlCrossRefLoader.WantedRefForDictionary(wanterDict); - DirectXmlCrossRefLoader.wantedRefs.Add(wantedRefForDictionary); + wantedRefForDictionary = new WantedRefForDictionary((object)wanterDict); + DirectXmlCrossRefLoader.wantedRefs.Add((WantedRef)wantedRefForDictionary); } wantedRefForDictionary.AddWantedDictEntry(entryNode); } public static T TryResolveDef(string defName, FailMode failReportMode) { - T t = (T)((object)GenDefDatabase.GetDefSilentFail(typeof(T), defName)); - if (t != null) + T val = (T)(object)GenDefDatabase.GetDefSilentFail(typeof(T), defName); + if (val != null) { - return t; + return val; } if (failReportMode == FailMode.LogErrors) { - Log.Error(string.Concat(new object[] - { - "Could not resolve cross-reference to ", - typeof(T), - " named ", - defName - })); + Log.Error("Could not resolve cross-reference to " + typeof(T) + " named " + defName); } return default(T); } @@ -263,13 +250,22 @@ public static void Clear() public static void ResolveAllWantedCrossReferences(FailMode failReportMode) { - foreach (DirectXmlCrossRefLoader.WantedRef current in DirectXmlCrossRefLoader.wantedRefs.ListFullCopy()) + List.Enumerator enumerator = DirectXmlCrossRefLoader.wantedRefs.ListFullCopy().GetEnumerator(); + try { - if (current.TryResolve(failReportMode)) + while (enumerator.MoveNext()) { - DirectXmlCrossRefLoader.wantedRefs.Remove(current); + WantedRef current = enumerator.Current; + if (current.TryResolve(failReportMode)) + { + DirectXmlCrossRefLoader.wantedRefs.Remove(current); + } } } + finally + { + ((IDisposable)(object)enumerator).Dispose(); + } } } } diff --git a/Assembly-CSharp/Verse/DirectXmlLoader.cs b/Assembly-CSharp/Verse/DirectXmlLoader.cs index b5cefd7c2..0c1564916 100644 --- a/Assembly-CSharp/Verse/DirectXmlLoader.cs +++ b/Assembly-CSharp/Verse/DirectXmlLoader.cs @@ -1,8 +1,9 @@ using System; using System.Collections.Generic; -using System.Diagnostics; using System.IO; +using System.Reflection; using System.Xml; +using UnityEngine; namespace Verse { @@ -10,28 +11,44 @@ public static class DirectXmlLoader { private static LoadableXmlAsset loadingAsset; - [DebuggerHidden] public static IEnumerable XmlAssetsInModFolder(ModContentPack mod, string folderPath) { - DirectXmlLoader.c__Iterator224 c__Iterator = new DirectXmlLoader.c__Iterator224(); - c__Iterator.mod = mod; - c__Iterator.folderPath = folderPath; - c__Iterator.<$>mod = mod; - c__Iterator.<$>folderPath = folderPath; - DirectXmlLoader.c__Iterator224 expr_23 = c__Iterator; - expr_23.$PC = -2; - return expr_23; + DirectoryInfo di = new DirectoryInfo(Path.Combine(mod.RootDir, folderPath)); + if (di.Exists) + { + FileInfo[] files2; + FileInfo[] files = files2 = di.GetFiles("*.xml", SearchOption.AllDirectories); + for (int i = 0; i < files2.Length; i++) + { + FileInfo file = files2[i]; + LoadableXmlAsset asset = new LoadableXmlAsset(file.Name, file.Directory.FullName, File.ReadAllText(file.FullName)); + yield return asset; + } + } } - [DebuggerHidden] public static IEnumerable LoadXmlDataInResourcesFolder(string folderPath) where T : new() { - DirectXmlLoader.c__Iterator225 c__Iterator = new DirectXmlLoader.c__Iterator225(); - c__Iterator.folderPath = folderPath; - c__Iterator.<$>folderPath = folderPath; - DirectXmlLoader.c__Iterator225 expr_15 = c__Iterator; - expr_15.$PC = -2; - return expr_15; + XmlInheritance.Clear(); + List assets = new List(); + object[] array; + object[] textObjects = array = Resources.LoadAll(folderPath); + for (int j = 0; j < array.Length; j++) + { + TextAsset text = (TextAsset)array[j]; + LoadableXmlAsset asset = new LoadableXmlAsset(text.name, string.Empty, text.text); + XmlInheritance.TryRegisterAllFrom(asset, null); + assets.Add(asset); + } + XmlInheritance.Resolve(); + for (int i = 0; i < assets.Count; i++) + { + foreach (T item in DirectXmlLoader.AllGameItemsFromAsset(assets[i])) + { + yield return item; + } + } + XmlInheritance.Clear(); } public static T ItemFromXmlFile(string filePath, bool resolveCrossRefs = true) where T : new() @@ -43,48 +60,129 @@ public static IEnumerable XmlAssetsInModFolder(ModContentPack FileInfo fileInfo = new FileInfo(filePath); if (!fileInfo.Exists) { - return (default(T) == null) ? Activator.CreateInstance() : default(T); + return new T(); } - T result; try { XmlDocument xmlDocument = new XmlDocument(); xmlDocument.LoadXml(File.ReadAllText(fileInfo.FullName)); - T t = DirectXmlToObject.ObjectFromXml(xmlDocument.DocumentElement, false); + T result = DirectXmlToObject.ObjectFromXml((XmlNode)xmlDocument.DocumentElement, false); if (resolveCrossRefs) { DirectXmlCrossRefLoader.ResolveAllWantedCrossReferences(FailMode.LogErrors); } - result = t; + return result; + IL_008a: + T result2; + return result2; } catch (Exception ex) { Log.Error("Exception loading file at " + filePath + ". Loading defaults instead. Exception was: " + ex.ToString()); - result = ((default(T) == null) ? Activator.CreateInstance() : default(T)); + return new T(); + IL_00d7: + T result2; + return result2; } - return result; } - [DebuggerHidden] public static IEnumerable AllDefsFromAsset(LoadableXmlAsset asset) { - DirectXmlLoader.c__Iterator226 c__Iterator = new DirectXmlLoader.c__Iterator226(); - c__Iterator.asset = asset; - c__Iterator.<$>asset = asset; - DirectXmlLoader.c__Iterator226 expr_15 = c__Iterator; - expr_15.$PC = -2; - return expr_15; + if (DirectXmlLoader.loadingAsset != null) + { + Log.Error("Tried to load " + asset + " while loading " + DirectXmlLoader.loadingAsset + ". This will corrupt the internal state of DataLoader."); + } + if (asset.xmlDoc != null) + { + DirectXmlLoader.loadingAsset = asset; + XmlNodeList assetNodes = asset.xmlDoc.DocumentElement.ChildNodes; + bool gotData = false; + foreach (XmlNode item in assetNodes) + { + if (item.NodeType == XmlNodeType.Element) + { + XmlAttribute abstractAtt = item.Attributes["Abstract"]; + if (abstractAtt != null && abstractAtt.Value.ToLower() == "true") + { + gotData = true; + } + else + { + Type defType = GenTypes.GetTypeInAnyAssembly(item.Name); + if (defType != null && typeof(Def).IsAssignableFrom(defType)) + { + MethodInfo method = typeof(DirectXmlToObject).GetMethod("ObjectFromXml"); + MethodInfo gen = method.MakeGenericMethod(defType); + Def def = null; + try + { + def = (Def)gen.Invoke(null, new object[2] + { + item, + true + }); + gotData = true; + } + catch (Exception ex) + { + Exception e; + Exception ex2 = e = ex; + Log.Error("Exception loading def from file " + asset.name + ": " + e); + } + if (def != null) + { + yield return def; + } + } + } + } + } + if (!gotData) + { + Log.Error("Found no usable data when trying to get defs from file " + asset.name); + } + DirectXmlLoader.loadingAsset = null; + } } - [DebuggerHidden] public static IEnumerable AllGameItemsFromAsset(LoadableXmlAsset asset) where T : new() { - DirectXmlLoader.c__Iterator227 c__Iterator = new DirectXmlLoader.c__Iterator227(); - c__Iterator.asset = asset; - c__Iterator.<$>asset = asset; - DirectXmlLoader.c__Iterator227 expr_15 = c__Iterator; - expr_15.$PC = -2; - return expr_15; + if (DirectXmlLoader.loadingAsset != null) + { + Log.Error("Tried to load " + asset + " while loading " + DirectXmlLoader.loadingAsset + ". This will corrupt the internal state of DataLoader."); + } + if (asset.xmlDoc != null) + { + DirectXmlLoader.loadingAsset = asset; + XmlNodeList assetNodes = asset.xmlDoc.DocumentElement.SelectNodes(typeof(T).Name); + bool gotData = false; + foreach (XmlNode item2 in assetNodes) + { + XmlAttribute abstractAtt = item2.Attributes["Abstract"]; + if (abstractAtt == null || !(abstractAtt.Value.ToLower() == "true")) + { + T item; + try + { + item = DirectXmlToObject.ObjectFromXml(item2, true); + gotData = true; + } + catch (Exception ex) + { + Exception e; + Exception ex2 = e = ex; + Log.Error("Exception loading data from file " + asset.name + ": " + e); + continue; + } + yield return item; + } + } + if (!gotData) + { + Log.Error("Found no usable data when trying to get " + typeof(T) + "s from file " + asset.name); + } + DirectXmlLoader.loadingAsset = null; + } } } } diff --git a/Assembly-CSharp/Verse/DirectXmlLoaderSimple.cs b/Assembly-CSharp/Verse/DirectXmlLoaderSimple.cs index 6b4e61b3d..cb9817684 100644 --- a/Assembly-CSharp/Verse/DirectXmlLoaderSimple.cs +++ b/Assembly-CSharp/Verse/DirectXmlLoaderSimple.cs @@ -1,21 +1,21 @@ -using System; using System.Collections.Generic; -using System.Diagnostics; using System.IO; +using System.Xml.Linq; namespace Verse { public static class DirectXmlLoaderSimple { - [DebuggerHidden] public static IEnumerable> ValuesFromXmlFile(FileInfo file) { - DirectXmlLoaderSimple.c__Iterator228 c__Iterator = new DirectXmlLoaderSimple.c__Iterator228(); - c__Iterator.file = file; - c__Iterator.<$>file = file; - DirectXmlLoaderSimple.c__Iterator228 expr_15 = c__Iterator; - expr_15.$PC = -2; - return expr_15; + XDocument doc = XDocument.Load(file.FullName); + foreach (XElement item in doc.Root.Elements()) + { + string key = item.Name.ToString(); + string value2 = item.Value; + value2 = value2.Replace("\\n", "\n"); + yield return new KeyValuePair(key, value2); + } } } } diff --git a/Assembly-CSharp/Verse/DirectXmlSaveFormatter.cs b/Assembly-CSharp/Verse/DirectXmlSaveFormatter.cs index e4a6e7fa1..892e20ef9 100644 --- a/Assembly-CSharp/Verse/DirectXmlSaveFormatter.cs +++ b/Assembly-CSharp/Verse/DirectXmlSaveFormatter.cs @@ -1,4 +1,5 @@ using System; +using System.Collections.Generic; using System.Linq; using System.Text; using System.Xml.Linq; @@ -9,20 +10,37 @@ internal static class DirectXmlSaveFormatter { public static void AddWhitespaceFromRoot(XElement root) { - if (!root.Elements().Any()) + if (root.Elements().Any()) { - return; - } - foreach (XElement current in root.Elements().ToList()) - { - XText content = new XText("\n"); - current.AddAfterSelf(content); - } - root.Elements().First().AddBeforeSelf(new XText("\n")); - root.Elements().Last().AddAfterSelf(new XText("\n")); - foreach (XElement current2 in root.Elements().ToList()) - { - DirectXmlSaveFormatter.IndentXml(current2, 1); + List.Enumerator enumerator = root.Elements().ToList().GetEnumerator(); + try + { + while (enumerator.MoveNext()) + { + XElement current = enumerator.Current; + XText content = new XText("\n"); + current.AddAfterSelf(content); + } + } + finally + { + ((IDisposable)(object)enumerator).Dispose(); + } + root.Elements().First().AddBeforeSelf(new XText("\n")); + root.Elements().Last().AddAfterSelf(new XText("\n")); + List.Enumerator enumerator2 = root.Elements().ToList().GetEnumerator(); + try + { + while (enumerator2.MoveNext()) + { + XElement current2 = enumerator2.Current; + DirectXmlSaveFormatter.IndentXml(current2, 1); + } + } + finally + { + ((IDisposable)(object)enumerator2).Dispose(); + } } } @@ -31,9 +49,18 @@ private static void IndentXml(XElement element, int depth) element.AddBeforeSelf(new XText(DirectXmlSaveFormatter.IndentString(depth, true))); bool startWithNewline = element.NextNode == null; element.AddAfterSelf(new XText(DirectXmlSaveFormatter.IndentString(depth - 1, startWithNewline))); - foreach (XElement current in element.Elements().ToList()) + List.Enumerator enumerator = element.Elements().ToList().GetEnumerator(); + try + { + while (enumerator.MoveNext()) + { + XElement current = enumerator.Current; + DirectXmlSaveFormatter.IndentXml(current, depth + 1); + } + } + finally { - DirectXmlSaveFormatter.IndentXml(current, depth + 1); + ((IDisposable)(object)enumerator).Dispose(); } } @@ -44,7 +71,7 @@ private static string IndentString(int depth, bool startWithNewline) { stringBuilder.Append("\n"); } - for (int i = 0; i < depth; i++) + for (int num = 0; num < depth; num++) { stringBuilder.Append(" "); } diff --git a/Assembly-CSharp/Verse/DirectXmlSaveLoadUtility.cs b/Assembly-CSharp/Verse/DirectXmlSaveLoadUtility.cs index 413bd3937..822eb02fe 100644 --- a/Assembly-CSharp/Verse/DirectXmlSaveLoadUtility.cs +++ b/Assembly-CSharp/Verse/DirectXmlSaveLoadUtility.cs @@ -1,4 +1,3 @@ -using System; using System.Reflection; namespace Verse diff --git a/Assembly-CSharp/Verse/DirectXmlSaver.cs b/Assembly-CSharp/Verse/DirectXmlSaver.cs index d04aae45e..b552d769b 100644 --- a/Assembly-CSharp/Verse/DirectXmlSaver.cs +++ b/Assembly-CSharp/Verse/DirectXmlSaver.cs @@ -25,18 +25,8 @@ public static void SaveDataObject(object obj, string filePath) } catch (Exception ex) { - GenUI.ErrorDialog("ProblemSavingFile".Translate(new object[] - { - filePath, - ex.ToString() - })); - Log.Error(string.Concat(new object[] - { - "Exception saving data object ", - obj, - ": ", - ex - })); + GenUI.ErrorDialog("ProblemSavingFile".Translate(filePath, ex.ToString())); + Log.Error("Exception saving data object " + obj + ": " + ex); } } @@ -47,8 +37,8 @@ public static XElement XElementFromObject(object obj, Type expectedClass) public static XElement XElementFromObject(object obj, Type expectedType, string nodeName, FieldInfo owningField = null, bool saveDefsAsRefs = false) { - DefaultValueAttribute defaultValueAttribute; - if (owningField != null && owningField.TryGetAttribute(out defaultValueAttribute) && defaultValueAttribute.ObjIsDefault(obj)) + DefaultValueAttribute defaultValueAttribute = default(DefaultValueAttribute); + if (owningField != null && ((MemberInfo)owningField).TryGetAttribute(out defaultValueAttribute) && defaultValueAttribute.ObjIsDefault(obj)) { return null; } @@ -63,67 +53,73 @@ public static XElement XElementFromObject(object obj, Type expectedType, string if (DirectXmlSaver.IsSimpleTextType(type)) { xElement2.Add(new XText(obj.ToString())); + goto IL_02ff; } - else if (saveDefsAsRefs && typeof(Def).IsAssignableFrom(type)) + if (saveDefsAsRefs && typeof(Def).IsAssignableFrom(type)) { string defName = ((Def)obj).defName; xElement2.Add(new XText(defName)); + goto IL_02ff; } - else if (type.IsGenericType && type.GetGenericTypeDefinition() == typeof(List<>)) + if (type.IsGenericType && type.GetGenericTypeDefinition() == typeof(List<>)) { Type expectedType2 = type.GetGenericArguments()[0]; int num = (int)type.GetProperty("Count").GetValue(obj, null); - for (int i = 0; i < num; i++) + for (int num2 = 0; num2 < num; num2++) { - object[] index = new object[] + object[] index = new object[1] { - i + num2 }; object value = type.GetProperty("Item").GetValue(obj, index); XNode content = DirectXmlSaver.XElementFromObject(value, expectedType2, "li", null, true); xElement2.Add(content); } + goto IL_02ff; } - else if (type.IsGenericType && type.GetGenericTypeDefinition() == typeof(Dictionary<, >)) + if (type.IsGenericType && type.GetGenericTypeDefinition() == typeof(Dictionary<, >)) { Type expectedType3 = type.GetGenericArguments()[0]; Type expectedType4 = type.GetGenericArguments()[1]; - foreach (object current in (obj as IEnumerable)) { - object value2 = current.GetType().GetProperty("Key").GetValue(current, null); - object value3 = current.GetType().GetProperty("Value").GetValue(current, null); - XElement xElement3 = new XElement("li"); - xElement3.Add(DirectXmlSaver.XElementFromObject(value2, expectedType3, "key", null, true)); - xElement3.Add(DirectXmlSaver.XElementFromObject(value3, expectedType4, "value", null, true)); - xElement2.Add(xElement3); + foreach (object item in obj as IEnumerable) + { + object value2 = item.GetType().GetProperty("Key").GetValue(item, null); + object value3 = item.GetType().GetProperty("Value").GetValue(item, null); + XElement xElement3 = new XElement("li"); + xElement3.Add(DirectXmlSaver.XElementFromObject(value2, expectedType3, "key", null, true)); + xElement3.Add(DirectXmlSaver.XElementFromObject(value3, expectedType4, "value", null, true)); + xElement2.Add(xElement3); + } + return xElement2; } } - else + if (type != expectedType) { - if (type != expectedType) - { - XAttribute content2 = new XAttribute("Class", GenTypes.GetTypeNameWithoutIgnoredNamespaces(obj.GetType())); - xElement2.Add(content2); - } - foreach (FieldInfo current2 in from f in type.GetFields(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic) - orderby f.MetadataToken - select f) + XAttribute content2 = new XAttribute("Class", GenTypes.GetTypeNameWithoutIgnoredNamespaces(obj.GetType())); + xElement2.Add(content2); + } + foreach (FieldInfo item2 in from f in type.GetFields(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic) + orderby f.MetadataToken + select f) + { + try { - try - { - XElement xElement4 = DirectXmlSaver.XElementFromField(current2, obj); - if (xElement4 != null) - { - xElement2.Add(xElement4); - } - } - catch + XElement xElement4 = DirectXmlSaver.XElementFromField(item2, obj); + if (xElement4 != null) { - throw; + xElement2.Add(xElement4); } } + catch + { + throw; + IL_02dc:; + } } return xElement2; + IL_02ff: + return xElement2; } private static XElement XElementFromField(FieldInfo fi, object owningObj) diff --git a/Assembly-CSharp/Verse/DirectXmlToObject.cs b/Assembly-CSharp/Verse/DirectXmlToObject.cs index 6f7975d0d..abe70dafa 100644 --- a/Assembly-CSharp/Verse/DirectXmlToObject.cs +++ b/Assembly-CSharp/Verse/DirectXmlToObject.cs @@ -28,32 +28,24 @@ public static class DirectXmlToObject { xmlRoot = XmlInheritance.GetResolvedNodeFor(xmlRoot); Type type = DirectXmlToObject.ClassTypeOf(xmlRoot); - T t = (T)((object)Activator.CreateInstance(type)); + T val = (T)Activator.CreateInstance(type); try { - methodInfo.Invoke(t, new object[] + methodInfo.Invoke(val, new object[1] { xmlRoot }); } catch (Exception ex) { - Log.Error(string.Concat(new object[] - { - "Exception in custom XML loader for ", - typeof(T), - ". Node is:\n ", - xmlRoot.OuterXml, - "\n\nException is:\n ", - ex.ToString() - })); - t = default(T); + Log.Error("Exception in custom XML loader for " + typeof(T) + ". Node is:\n " + xmlRoot.OuterXml + "\n\nException is:\n " + ex.ToString()); + val = default(T); } if (doPostLoad) { - DirectXmlToObject.TryDoPostLoad(t); + DirectXmlToObject.TryDoPostLoad(val); } - return t; + return val; } if (xmlRoot.ChildNodes.Count == 1 && xmlRoot.FirstChild.NodeType == XmlNodeType.CDATA) { @@ -62,247 +54,232 @@ public static class DirectXmlToObject Log.Error("CDATA can only be used for strings. Bad xml: " + xmlRoot.OuterXml); return default(T); } - return (T)((object)xmlRoot.FirstChild.Value); + return (T)(object)xmlRoot.FirstChild.Value; } - else + if (xmlRoot.ChildNodes.Count == 1 && xmlRoot.FirstChild.NodeType == XmlNodeType.Text) { - if (xmlRoot.ChildNodes.Count == 1 && xmlRoot.FirstChild.NodeType == XmlNodeType.Text) + try { - try - { - return (T)((object)ParseHelper.FromString(xmlRoot.InnerText, typeof(T))); - } - catch (Exception ex2) - { - Log.Error(string.Concat(new object[] - { - "Exception parsing ", - xmlRoot.OuterXml, - " to type ", - typeof(T), - ": ", - ex2 - })); - } - return default(T); + return (T)ParseHelper.FromString(xmlRoot.InnerText, typeof(T)); + IL_0167:; } - if (Attribute.IsDefined(typeof(T), typeof(FlagsAttribute))) + catch (Exception ex2) { - List list = DirectXmlToObject.ListFromXml(xmlRoot); - int num = 0; - foreach (T current in list) + Log.Error("Exception parsing " + xmlRoot.OuterXml + " to type " + typeof(T) + ": " + ex2); + } + return default(T); + } + if (Attribute.IsDefined(typeof(T), typeof(FlagsAttribute))) + { + List list = DirectXmlToObject.ListFromXml(xmlRoot); + int num = 0; + List.Enumerator enumerator = list.GetEnumerator(); + try + { + while (enumerator.MoveNext()) { - int num2 = (int)((object)current); + T current = enumerator.Current; + int num2 = (int)(object)current; num |= num2; } - return (T)((object)num); } - if (typeof(T).HasGenericDefinition(typeof(List<>))) + finally { - MethodInfo method = typeof(DirectXmlToObject).GetMethod("ListFromXml", BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic); - Type[] genericArguments = typeof(T).GetGenericArguments(); - MethodInfo methodInfo2 = method.MakeGenericMethod(genericArguments); - object[] parameters = new object[] - { - xmlRoot - }; - object obj = methodInfo2.Invoke(null, parameters); - return (T)((object)obj); + ((IDisposable)(object)enumerator).Dispose(); } - if (typeof(T).HasGenericDefinition(typeof(Dictionary<, >))) + return (T)(object)num; + } + if (typeof(T).HasGenericDefinition(typeof(List<>))) + { + MethodInfo method = typeof(DirectXmlToObject).GetMethod("ListFromXml", BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic); + Type[] genericArguments = typeof(T).GetGenericArguments(); + MethodInfo methodInfo2 = method.MakeGenericMethod(genericArguments); + object[] parameters = new object[1] { - MethodInfo method2 = typeof(DirectXmlToObject).GetMethod("DictionaryFromXml", BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic); - Type[] genericArguments2 = typeof(T).GetGenericArguments(); - MethodInfo methodInfo3 = method2.MakeGenericMethod(genericArguments2); - object[] parameters2 = new object[] - { - xmlRoot - }; - object obj2 = methodInfo3.Invoke(null, parameters2); - return (T)((object)obj2); + xmlRoot + }; + object obj = methodInfo2.Invoke(null, parameters); + return (T)obj; + } + if (typeof(T).HasGenericDefinition(typeof(Dictionary<, >))) + { + MethodInfo method2 = typeof(DirectXmlToObject).GetMethod("DictionaryFromXml", BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic); + Type[] genericArguments2 = typeof(T).GetGenericArguments(); + MethodInfo methodInfo3 = method2.MakeGenericMethod(genericArguments2); + object[] parameters2 = new object[1] + { + xmlRoot + }; + object obj2 = methodInfo3.Invoke(null, parameters2); + return (T)obj2; + } + if (!xmlRoot.HasChildNodes) + { + if (typeof(T) == typeof(string)) + { + return (T)(object)string.Empty; } - if (!xmlRoot.HasChildNodes) + XmlAttribute xmlAttribute = xmlRoot.Attributes["IsNull"]; + if (xmlAttribute != null && xmlAttribute.Value.ToUpperInvariant() == "TRUE") { - if (typeof(T) == typeof(string)) - { - return (T)((object)string.Empty); - } - XmlAttribute xmlAttribute = xmlRoot.Attributes["IsNull"]; - if (xmlAttribute != null && xmlAttribute.Value.ToUpperInvariant() == "TRUE") + return default(T); + } + if (typeof(T).IsGenericType) + { + Type genericTypeDefinition = typeof(T).GetGenericTypeDefinition(); + if (genericTypeDefinition != typeof(List<>) && genericTypeDefinition != typeof(HashSet<>) && genericTypeDefinition != typeof(Dictionary<, >)) { - return default(T); + goto IL_0411; } - if (typeof(T).IsGenericType) + return new T(); + } + } + goto IL_0411; + IL_0411: + xmlRoot = XmlInheritance.GetResolvedNodeFor(xmlRoot); + Type type2 = DirectXmlToObject.ClassTypeOf(xmlRoot); + T val2 = (T)Activator.CreateInstance(type2); + List list2 = null; + if (xmlRoot.ChildNodes.Count > 1) + { + list2 = new List(); + } + for (int i = 0; i < xmlRoot.ChildNodes.Count; i++) + { + XmlNode xmlNode = xmlRoot.ChildNodes[i]; + if (!(xmlNode is XmlComment)) + { + if (xmlRoot.ChildNodes.Count > 1) { - Type genericTypeDefinition = typeof(T).GetGenericTypeDefinition(); - if (genericTypeDefinition == typeof(List<>) || genericTypeDefinition == typeof(HashSet<>) || genericTypeDefinition == typeof(Dictionary<, >)) + if (list2.Contains(xmlNode.Name)) + { + Log.Error("XML " + typeof(T) + " defines the same field twice: " + xmlNode.Name + ".\n\nField contents: " + xmlNode.InnerText + ".\n\nWhole XML:\n\n" + xmlRoot.OuterXml); + } + else { - return (default(T) == null) ? Activator.CreateInstance() : default(T); + list2.Add(xmlNode.Name); } } - } - xmlRoot = XmlInheritance.GetResolvedNodeFor(xmlRoot); - Type type2 = DirectXmlToObject.ClassTypeOf(xmlRoot); - T t2 = (T)((object)Activator.CreateInstance(type2)); - List list2 = null; - if (xmlRoot.ChildNodes.Count > 1) - { - list2 = new List(); - } - for (int i = 0; i < xmlRoot.ChildNodes.Count; i++) - { - XmlNode xmlNode = xmlRoot.ChildNodes[i]; - if (!(xmlNode is XmlComment)) + FieldInfo fieldInfo = null; + Type type3 = val2.GetType(); + while (true) { - if (xmlRoot.ChildNodes.Count > 1) + fieldInfo = type3.GetField(xmlNode.Name, BindingFlags.IgnoreCase | BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic); + if (fieldInfo != null) + break; + if (type3.BaseType == typeof(object)) + break; + type3 = type3.BaseType; + } + if (fieldInfo == null) + { + FieldInfo[] fields = val2.GetType().GetFields(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic); + int num3 = 0; + while (num3 < fields.Length) { - if (list2.Contains(xmlNode.Name)) + FieldInfo fieldInfo2 = fields[num3]; + object[] customAttributes = fieldInfo2.GetCustomAttributes(typeof(LoadAliasAttribute), true); + for (int j = 0; j < customAttributes.Length; j++) { - Log.Error(string.Concat(new object[] + object obj3 = customAttributes[j]; + string alias = ((LoadAliasAttribute)obj3).alias; + if (alias.EqualsIgnoreCase(xmlNode.Name)) { - "XML ", - typeof(T), - " defines the same field twice: ", - xmlNode.Name, - ".\n\nField contents: ", - xmlNode.InnerText, - ".\n\nWhole XML:\n\n", - xmlRoot.OuterXml - })); + fieldInfo = fieldInfo2; + break; + } } - else + if (fieldInfo == null) { - list2.Add(xmlNode.Name); + num3++; + continue; } + break; } - FieldInfo fieldInfo = null; - Type type3 = t2.GetType(); - while (true) + } + if (fieldInfo == null) + { + bool flag = false; + object[] customAttributes2 = val2.GetType().GetCustomAttributes(typeof(IgnoreSavedElementAttribute), true); + for (int k = 0; k < customAttributes2.Length; k++) { - fieldInfo = type3.GetField(xmlNode.Name, BindingFlags.IgnoreCase | BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic); - if (fieldInfo != null || type3.BaseType == typeof(object)) + object obj4 = customAttributes2[k]; + string elementToIgnore = ((IgnoreSavedElementAttribute)obj4).elementToIgnore; + if (string.Equals(elementToIgnore, xmlNode.Name, StringComparison.OrdinalIgnoreCase)) { + flag = true; break; } - type3 = type3.BaseType; } - if (fieldInfo == null) + if (!flag) { - FieldInfo[] fields = t2.GetType().GetFields(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic); - for (int j = 0; j < fields.Length; j++) - { - FieldInfo fieldInfo2 = fields[j]; - object[] customAttributes = fieldInfo2.GetCustomAttributes(typeof(LoadAliasAttribute), true); - for (int k = 0; k < customAttributes.Length; k++) - { - object obj3 = customAttributes[k]; - string alias = ((LoadAliasAttribute)obj3).alias; - if (alias.EqualsIgnoreCase(xmlNode.Name)) - { - fieldInfo = fieldInfo2; - break; - } - } - if (fieldInfo != null) - { - break; - } - } + Log.Error("XML error: " + xmlNode.OuterXml + " doesn't correspond to any field in type " + val2.GetType().Name + "."); } - if (fieldInfo == null) + } + else if (typeof(Def).IsAssignableFrom(fieldInfo.FieldType)) + { + if (xmlNode.InnerText.NullOrEmpty()) { - bool flag = false; - object[] customAttributes2 = t2.GetType().GetCustomAttributes(typeof(IgnoreSavedElementAttribute), true); - for (int l = 0; l < customAttributes2.Length; l++) - { - object obj4 = customAttributes2[l]; - string elementToIgnore = ((IgnoreSavedElementAttribute)obj4).elementToIgnore; - if (string.Equals(elementToIgnore, xmlNode.Name, StringComparison.OrdinalIgnoreCase)) - { - flag = true; - break; - } - } - if (!flag) - { - Log.Error(string.Concat(new string[] - { - "XML error: ", - xmlNode.OuterXml, - " doesn't correspond to any field in type ", - t2.GetType().Name, - "." - })); - } + fieldInfo.SetValue(val2, null); } - else if (typeof(Def).IsAssignableFrom(fieldInfo.FieldType)) + else { - if (xmlNode.InnerText.NullOrEmpty()) - { - fieldInfo.SetValue(t2, null); - } - else + DirectXmlCrossRefLoader.RegisterObjectWantsCrossRef(val2, fieldInfo, xmlNode.InnerText); + } + } + else + { + object obj5 = null; + try + { + MethodInfo method3 = typeof(DirectXmlToObject).GetMethod("ObjectFromXml", BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic); + MethodInfo methodInfo4 = method3.MakeGenericMethod(fieldInfo.FieldType); + obj5 = methodInfo4.Invoke(null, new object[2] { - DirectXmlCrossRefLoader.RegisterObjectWantsCrossRef(t2, fieldInfo, xmlNode.InnerText); - } + xmlNode, + doPostLoad + }); + } + catch (Exception ex3) + { + Log.Error("Exception loading from " + xmlNode.ToString() + ": " + ex3.ToString()); + continue; + IL_07a8:; + } + if (!typeof(T).IsValueType) + { + fieldInfo.SetValue(val2, obj5); } else { - object value = null; - try - { - MethodInfo method3 = typeof(DirectXmlToObject).GetMethod("ObjectFromXml", BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic); - MethodInfo methodInfo4 = method3.MakeGenericMethod(new Type[] - { - fieldInfo.FieldType - }); - value = methodInfo4.Invoke(null, new object[] - { - xmlNode, - doPostLoad - }); - } - catch (Exception ex3) - { - Log.Error("Exception loading from " + xmlNode.ToString() + ": " + ex3.ToString()); - goto IL_7F3; - } - if (!typeof(T).IsValueType) - { - fieldInfo.SetValue(t2, value); - } - else - { - object obj5 = t2; - fieldInfo.SetValue(obj5, value); - t2 = (T)((object)obj5); - } + object obj6 = val2; + fieldInfo.SetValue(obj6, obj5); + val2 = (T)obj6; } } - IL_7F3:; - } - if (doPostLoad) - { - DirectXmlToObject.TryDoPostLoad(t2); } - return t2; } + if (doPostLoad) + { + DirectXmlToObject.TryDoPostLoad(val2); + } + return val2; } private static Type ClassTypeOf(XmlNode xmlRoot) { XmlAttribute xmlAttribute = xmlRoot.Attributes["Class"]; - if (xmlAttribute == null) - { - return typeof(T); - } - Type typeInAnyAssembly = GenTypes.GetTypeInAnyAssembly(xmlAttribute.Value); - if (typeInAnyAssembly == null) + if (xmlAttribute != null) { - Log.Error("Could not find type named " + xmlAttribute.Value + " from node " + xmlRoot.OuterXml); - return typeof(T); + Type typeInAnyAssembly = GenTypes.GetTypeInAnyAssembly(xmlAttribute.Value); + if (typeInAnyAssembly == null) + { + Log.Error("Could not find type named " + xmlAttribute.Value + " from node " + xmlRoot.OuterXml); + return typeof(T); + } + return typeInAnyAssembly; } - return typeInAnyAssembly; + return typeof(T); } private static void TryDoPostLoad(object obj) @@ -317,13 +294,7 @@ private static void TryDoPostLoad(object obj) } catch (Exception ex) { - Log.Error(string.Concat(new object[] - { - "Exception while executing PostLoad on ", - obj.ToStringSafe(), - ": ", - ex - })); + Log.Error("Exception while executing PostLoad on " + obj.ToStringSafe() + ": " + ex); } } @@ -333,32 +304,27 @@ private static void TryDoPostLoad(object obj) try { bool flag = typeof(Def).IsAssignableFrom(typeof(T)); - foreach (XmlNode xmlNode in listRootNode.ChildNodes) + foreach (XmlNode childNode in listRootNode.ChildNodes) { - if (DirectXmlToObject.ValidateListNode(xmlNode, listRootNode, typeof(T))) + if (DirectXmlToObject.ValidateListNode(childNode, listRootNode, typeof(T))) { if (flag) { - DirectXmlCrossRefLoader.RegisterListWantsCrossRef(list, xmlNode.InnerText); + DirectXmlCrossRefLoader.RegisterListWantsCrossRef(list, childNode.InnerText); } else { - list.Add(DirectXmlToObject.ObjectFromXml(xmlNode, true)); + list.Add(DirectXmlToObject.ObjectFromXml(childNode, true)); } } } + return list; } catch (Exception ex) { - Log.Error(string.Concat(new object[] - { - "Exception loading list from XML: ", - ex, - "\nXML:\n", - listRootNode.OuterXml - })); + Log.Error("Exception loading list from XML: " + ex + "\nXML:\n" + listRootNode.OuterXml); + return list; } - return list; } private static Dictionary DictionaryFromXml(XmlNode dictRootNode) where K : new() where V : new() @@ -370,38 +336,33 @@ private static void TryDoPostLoad(object obj) bool flag2 = typeof(Def).IsAssignableFrom(typeof(V)); if (!flag && !flag2) { - foreach (XmlNode xmlNode in dictRootNode.ChildNodes) { - if (DirectXmlToObject.ValidateListNode(xmlNode, dictRootNode, typeof(KeyValuePair))) + foreach (XmlNode childNode in dictRootNode.ChildNodes) { - K key = DirectXmlToObject.ObjectFromXml(xmlNode["key"], true); - V value = DirectXmlToObject.ObjectFromXml(xmlNode["value"], true); - dictionary.Add(key, value); + if (DirectXmlToObject.ValidateListNode(childNode, dictRootNode, typeof(KeyValuePair))) + { + K key = DirectXmlToObject.ObjectFromXml((XmlNode)childNode["key"], true); + V value = DirectXmlToObject.ObjectFromXml((XmlNode)childNode["value"], true); + dictionary.Add(key, value); + } } + return dictionary; } } - else + foreach (XmlNode childNode2 in dictRootNode.ChildNodes) { - foreach (XmlNode xmlNode2 in dictRootNode.ChildNodes) + if (DirectXmlToObject.ValidateListNode(childNode2, dictRootNode, typeof(KeyValuePair))) { - if (DirectXmlToObject.ValidateListNode(xmlNode2, dictRootNode, typeof(KeyValuePair))) - { - DirectXmlCrossRefLoader.RegisterDictionaryWantsCrossRef(dictionary, xmlNode2); - } + DirectXmlCrossRefLoader.RegisterDictionaryWantsCrossRef(dictionary, childNode2); } } + return dictionary; } catch (Exception ex) { - Log.Error(string.Concat(new object[] - { - "Malformed dictionary XML. Node: ", - dictRootNode.OuterXml, - ".\n\nException: ", - ex - })); + Log.Error("Malformed dictionary XML. Node: " + dictRootNode.OuterXml + ".\n\nException: " + ex); + return dictionary; } - return dictionary; } private static MethodInfo CustomDataLoadMethodOf(Type type) diff --git a/Assembly-CSharp/Verse/DragSliderCallback.cs b/Assembly-CSharp/Verse/DragSliderCallback.cs index 912c6fcfc..3a717b2d6 100644 --- a/Assembly-CSharp/Verse/DragSliderCallback.cs +++ b/Assembly-CSharp/Verse/DragSliderCallback.cs @@ -1,5 +1,3 @@ -using System; - namespace Verse { public delegate void DragSliderCallback(float mouseOffset, float rateFactor); diff --git a/Assembly-CSharp/Verse/DragSliderManager.cs b/Assembly-CSharp/Verse/DragSliderManager.cs index 95b4583e8..ec97acf17 100644 --- a/Assembly-CSharp/Verse/DragSliderManager.cs +++ b/Assembly-CSharp/Verse/DragSliderManager.cs @@ -1,4 +1,3 @@ -using System; using UnityEngine; namespace Verse @@ -37,12 +36,14 @@ private static void StartDragSliding(DragSliderCallback newDraggingUpdateMethod, DragSliderManager.dragging = true; DragSliderManager.draggingUpdateMethod = newDraggingUpdateMethod; DragSliderManager.completedMethod = newCompletedMethod; - DragSliderManager.rootX = UI.MousePositionOnUI.x; + Vector2 mousePositionOnUI = UI.MousePositionOnUI; + DragSliderManager.rootX = mousePositionOnUI.x; } private static float CurMouseOffset() { - return UI.MousePositionOnUI.x - DragSliderManager.rootX; + Vector2 mousePositionOnUI = UI.MousePositionOnUI; + return mousePositionOnUI.x - DragSliderManager.rootX; } public static void DragSlidersOnGUI() @@ -50,7 +51,7 @@ public static void DragSlidersOnGUI() if (DragSliderManager.dragging && Event.current.type == EventType.MouseUp && Event.current.button == 0) { DragSliderManager.dragging = false; - if (DragSliderManager.completedMethod != null) + if ((object)DragSliderManager.completedMethod != null) { DragSliderManager.completedMethod(DragSliderManager.CurMouseOffset(), DragSliderManager.lastRateFactor); } @@ -59,7 +60,7 @@ public static void DragSlidersOnGUI() public static void DragSlidersUpdate() { - if (DragSliderManager.dragging && DragSliderManager.draggingUpdateMethod != null) + if (DragSliderManager.dragging && (object)DragSliderManager.draggingUpdateMethod != null) { DragSliderManager.draggingUpdateMethod(DragSliderManager.CurMouseOffset(), DragSliderManager.lastRateFactor); } diff --git a/Assembly-CSharp/Verse/DrawTargetDef.cs b/Assembly-CSharp/Verse/DrawTargetDef.cs index 1b814c5fd..92ee59147 100644 --- a/Assembly-CSharp/Verse/DrawTargetDef.cs +++ b/Assembly-CSharp/Verse/DrawTargetDef.cs @@ -1,5 +1,3 @@ -using System; - namespace Verse { public class DrawTargetDef : Def diff --git a/Assembly-CSharp/Verse/DrawerType.cs b/Assembly-CSharp/Verse/DrawerType.cs index 9cfef6c65..b0eb0158e 100644 --- a/Assembly-CSharp/Verse/DrawerType.cs +++ b/Assembly-CSharp/Verse/DrawerType.cs @@ -1,12 +1,10 @@ -using System; - namespace Verse { public enum DrawerType : byte { - None, - RealtimeOnly, - MapMeshOnly, - MapMeshAndRealTime + None = 0, + RealtimeOnly = 1, + MapMeshOnly = 2, + MapMeshAndRealTime = 3 } } diff --git a/Assembly-CSharp/Verse/DynamicDrawManager.cs b/Assembly-CSharp/Verse/DynamicDrawManager.cs index d7486160b..c81766181 100644 --- a/Assembly-CSharp/Verse/DynamicDrawManager.cs +++ b/Assembly-CSharp/Verse/DynamicDrawManager.cs @@ -22,7 +22,7 @@ public DynamicDrawManager(Map map) public void RegisterDrawable(Thing t) { - if (t.def.drawerType != DrawerType.None) + if (t.def.drawerType != 0) { if (this.drawingNow) { @@ -41,7 +41,7 @@ public void RegisterDrawable(Thing t) public void DeRegisterDrawable(Thing t) { - if (t.def.drawerType != DrawerType.None) + if (t.def.drawerType != 0) { if (this.drawingNow) { @@ -54,27 +54,25 @@ public void DeRegisterDrawable(Thing t) public void DrawDynamicThings(DrawTargetDef drawTarget) { - if (!DebugViewSettings.drawThingsDynamic) + if (DebugViewSettings.drawThingsDynamic) { - return; - } - this.drawingNow = true; - HashSet hashSet = (drawTarget != DrawTargetDefOf.WaterHeight) ? this.drawThings : this.drawThingsWater; - try - { - bool[] fogGrid = this.map.fogGrid.fogGrid; - CellRect cellRect = Find.CameraDriver.CurrentViewRect; - cellRect.ClipInsideMap(this.map); - cellRect = cellRect.ExpandedBy(1); - CellIndices cellIndices = this.map.cellIndices; - foreach (Thing current in hashSet) + this.drawingNow = true; + HashSet hashSet = (drawTarget != DrawTargetDefOf.WaterHeight) ? this.drawThings : this.drawThingsWater; + try { - IntVec3 position = current.Position; - if (cellRect.Contains(position) || current.def.drawOffscreen) + bool[] fogGrid = this.map.fogGrid.fogGrid; + CellRect cellRect = Find.CameraDriver.CurrentViewRect; + cellRect.ClipInsideMap(this.map); + cellRect = cellRect.ExpandedBy(1); + CellIndices cellIndices = this.map.cellIndices; + HashSet.Enumerator enumerator = hashSet.GetEnumerator(); + try { - if (!fogGrid[cellIndices.CellToIndex(position)] || current.def.seeThroughFog) + while (enumerator.MoveNext()) { - if (current.def.hideAtSnowDepth >= 1f || this.map.snowGrid.GetDepth(current.Position) <= current.def.hideAtSnowDepth) + Thing current = enumerator.Current; + IntVec3 position = current.Position; + if ((cellRect.Contains(position) || current.def.drawOffscreen) && (!fogGrid[cellIndices.CellToIndex(position)] || current.def.seeThroughFog) && (!(current.def.hideAtSnowDepth < 1.0) || !(this.map.snowGrid.GetDepth(current.Position) > current.def.hideAtSnowDepth))) { try { @@ -82,24 +80,22 @@ public void DrawDynamicThings(DrawTargetDef drawTarget) } catch (Exception ex) { - Log.Error(string.Concat(new object[] - { - "Exception drawing ", - current, - ": ", - ex.ToString() - })); + Log.Error("Exception drawing " + current + ": " + ex.ToString()); } } } } + finally + { + ((IDisposable)(object)enumerator).Dispose(); + } } + catch (Exception arg) + { + Log.Error("Exception drawing dynamic things: " + arg); + } + this.drawingNow = false; } - catch (Exception arg) - { - Log.Error("Exception drawing dynamic things: " + arg); - } - this.drawingNow = false; } public void LogDynamicDrawThings() diff --git a/Assembly-CSharp/Verse/EdgeSpan.cs b/Assembly-CSharp/Verse/EdgeSpan.cs index 2efe5908f..8235bf469 100644 --- a/Assembly-CSharp/Verse/EdgeSpan.cs +++ b/Assembly-CSharp/Verse/EdgeSpan.cs @@ -23,11 +23,17 @@ public IEnumerable Cells { get { - EdgeSpan.<>c__Iterator204 <>c__Iterator = new EdgeSpan.<>c__Iterator204(); - <>c__Iterator.<>f__this = this; - EdgeSpan.<>c__Iterator204 expr_13 = <>c__Iterator; - expr_13.$PC = -2; - return expr_13; + for (int i = 0; i < this.length; i++) + { + if (this.dir == SpanDirection.North) + { + yield return new IntVec3(this.root.x, 0, this.root.z + i); + } + else if (this.dir == SpanDirection.East) + { + yield return new IntVec3(this.root.x + i, 0, this.root.z); + } + } } } @@ -40,16 +46,7 @@ public EdgeSpan(IntVec3 root, SpanDirection dir, int length) public override string ToString() { - return string.Concat(new object[] - { - "(root=", - this.root, - ", dir=", - this.dir.ToString(), - " + length=", - this.length, - ")" - }); + return "(root=" + this.root + ", dir=" + ((Enum)(object)this.dir).ToString() + " + length=" + this.length + ")"; } public ulong UniqueHashCode() @@ -57,9 +54,9 @@ public ulong UniqueHashCode() ulong num = this.root.UniqueHashCode(); if (this.dir == SpanDirection.East) { - num += 17592186044416uL; + num += 17592186044416L; } - return num + (ulong)(281474976710656L * (long)this.length); + return (ulong)((long)num + 281474976710656L * this.length); } } } diff --git a/Assembly-CSharp/Verse/EdificeGrid.cs b/Assembly-CSharp/Verse/EdificeGrid.cs index 6b9ba923d..0a6ca3788 100644 --- a/Assembly-CSharp/Verse/EdificeGrid.cs +++ b/Assembly-CSharp/Verse/EdificeGrid.cs @@ -1,5 +1,3 @@ -using System; - namespace Verse { public sealed class EdificeGrid @@ -49,16 +47,7 @@ public void Register(Building ed) IntVec3 intVec = new IntVec3(j, 0, i); if (UnityData.isDebugBuild && this[intVec] != null && !this[intVec].Destroyed) { - Log.Error(string.Concat(new object[] - { - "Added edifice ", - ed.LabelCap, - " over edifice ", - this[intVec].LabelCap, - " at ", - intVec, - ". Destroying old edifice." - })); + Log.Error("Added edifice " + ed.LabelCap + " over edifice " + this[intVec].LabelCap + " at " + intVec + ". Destroying old edifice."); this[intVec].Destroy(DestroyMode.Vanish); return; } diff --git a/Assembly-CSharp/Verse/EdificeUtility.cs b/Assembly-CSharp/Verse/EdificeUtility.cs index c9ea33ac4..12e412156 100644 --- a/Assembly-CSharp/Verse/EdificeUtility.cs +++ b/Assembly-CSharp/Verse/EdificeUtility.cs @@ -1,5 +1,3 @@ -using System; - namespace Verse { public static class EdificeUtility diff --git a/Assembly-CSharp/Verse/EditTreeNodeDatabase.cs b/Assembly-CSharp/Verse/EditTreeNodeDatabase.cs index b323e38f1..6895ae5bb 100644 --- a/Assembly-CSharp/Verse/EditTreeNodeDatabase.cs +++ b/Assembly-CSharp/Verse/EditTreeNodeDatabase.cs @@ -1,4 +1,3 @@ -using System; using System.Collections.Generic; namespace Verse diff --git a/Assembly-CSharp/Verse/EditTreeNodeType.cs b/Assembly-CSharp/Verse/EditTreeNodeType.cs index e57fc9b73..29bedf2a7 100644 --- a/Assembly-CSharp/Verse/EditTreeNodeType.cs +++ b/Assembly-CSharp/Verse/EditTreeNodeType.cs @@ -1,11 +1,9 @@ -using System; - namespace Verse { public enum EditTreeNodeType : byte { - ComplexObject, - ListRoot, - TerminalValue + ComplexObject = 0, + ListRoot = 1, + TerminalValue = 2 } } diff --git a/Assembly-CSharp/Verse/EditWindow.cs b/Assembly-CSharp/Verse/EditWindow.cs index 062759096..76e58a472 100644 --- a/Assembly-CSharp/Verse/EditWindow.cs +++ b/Assembly-CSharp/Verse/EditWindow.cs @@ -30,38 +30,36 @@ protected override float Margin public EditWindow() { - this.resizeable = true; - this.draggable = true; - this.preventCameraMotion = false; - this.doCloseX = true; - this.windowRect.x = 5f; - this.windowRect.y = 5f; + base.resizeable = true; + base.draggable = true; + base.preventCameraMotion = false; + base.doCloseX = true; + base.windowRect.x = 5f; + base.windowRect.y = 5f; } public override void PostOpen() { - while (this.windowRect.x <= (float)UI.screenWidth - 200f && this.windowRect.y <= (float)UI.screenHeight - 200f) + while (!(base.windowRect.x > (float)UI.screenWidth - 200.0) && !(base.windowRect.y > (float)UI.screenHeight - 200.0)) { bool flag = false; - foreach (EditWindow current in (from di in Find.WindowStack.Windows + foreach (EditWindow item in (from di in Find.WindowStack.Windows where di is EditWindow select di).Cast()) { - if (current != this) + if (item != this && Mathf.Abs(item.windowRect.x - base.windowRect.x) < 8.0 && Mathf.Abs(item.windowRect.y - base.windowRect.y) < 8.0) { - if (Mathf.Abs(current.windowRect.x - this.windowRect.x) < 8f && Mathf.Abs(current.windowRect.y - this.windowRect.y) < 8f) - { - flag = true; - break; - } + flag = true; + break; } } - if (!flag) + if (flag) { - return; + base.windowRect.x += 16f; + base.windowRect.y += 16f; + continue; } - this.windowRect.x = this.windowRect.x + 16f; - this.windowRect.y = this.windowRect.y + 16f; + break; } } } diff --git a/Assembly-CSharp/Verse/EditWindow_CurveEditor.cs b/Assembly-CSharp/Verse/EditWindow_CurveEditor.cs index a608b1dd7..ead4bce26 100644 --- a/Assembly-CSharp/Verse/EditWindow_CurveEditor.cs +++ b/Assembly-CSharp/Verse/EditWindow_CurveEditor.cs @@ -1,6 +1,5 @@ using System; using System.Collections.Generic; -using System.Diagnostics; using System.Linq; using UnityEngine; @@ -49,7 +48,7 @@ public override bool IsDebug public EditWindow_CurveEditor(SimpleCurve curve, string title) { this.curve = curve; - this.optionalTitle = title; + base.optionalTitle = title; } public override void DoWindowContents(Rect inRect) @@ -110,34 +109,36 @@ private void DoCurveEditor(Rect screenRect) Vector2 mousePosition = Event.current.mousePosition; if (Mouse.IsOver(screenRect)) { - Rect rect = new Rect(mousePosition.x + 8f, mousePosition.y + 18f, 100f, 100f); + Rect rect = new Rect((float)(mousePosition.x + 8.0), (float)(mousePosition.y + 18.0), 100f, 100f); Vector2 v = SimpleCurveDrawer.ScreenToCurveCoords(screenRect, this.curve.View.rect, mousePosition); Widgets.Label(rect, v.ToStringTwoDigits()); } - Rect rect2 = new Rect(0f, 0f, 50f, 24f); - rect2.x = screenRect.x; - rect2.y = screenRect.y + screenRect.height / 2f - 12f; + Rect rect2 = new Rect(0f, 0f, 50f, 24f) + { + x = screenRect.x, + y = (float)(screenRect.y + screenRect.height / 2.0 - 12.0) + }; string s = Widgets.TextField(rect2, this.curve.View.rect.x.ToString()); - float num; + float num = default(float); if (float.TryParse(s, out num)) { this.curve.View.rect.x = num; } rect2.x = screenRect.xMax - rect2.width; - rect2.y = screenRect.y + screenRect.height / 2f - 12f; + rect2.y = (float)(screenRect.y + screenRect.height / 2.0 - 12.0); s = Widgets.TextField(rect2, this.curve.View.rect.xMax.ToString()); if (float.TryParse(s, out num)) { this.curve.View.rect.xMax = num; } - rect2.x = screenRect.x + screenRect.width / 2f - rect2.width / 2f; + rect2.x = (float)(screenRect.x + screenRect.width / 2.0 - rect2.width / 2.0); rect2.y = screenRect.yMax - rect2.height; s = Widgets.TextField(rect2, this.curve.View.rect.y.ToString()); if (float.TryParse(s, out num)) { this.curve.View.rect.y = num; } - rect2.x = screenRect.x + screenRect.width / 2f - rect2.width / 2f; + rect2.x = (float)(screenRect.x + screenRect.width / 2.0 - rect2.width / 2.0); rect2.y = screenRect.y; s = Widgets.TextField(rect2, this.curve.View.rect.yMax.ToString()); if (float.TryParse(s, out num)) @@ -148,23 +149,22 @@ private void DoCurveEditor(Rect screenRect) { if (Event.current.type == EventType.ScrollWheel) { - float num2 = -1f * Event.current.delta.y * 0.025f; - float num3 = this.curve.View.rect.center.x - this.curve.View.rect.x; - float num4 = this.curve.View.rect.center.y - this.curve.View.rect.y; - SimpleCurveView expr_363_cp_0 = this.curve.View; - expr_363_cp_0.rect.xMin = expr_363_cp_0.rect.xMin + num3 * num2; - SimpleCurveView expr_384_cp_0 = this.curve.View; - expr_384_cp_0.rect.xMax = expr_384_cp_0.rect.xMax - num3 * num2; - SimpleCurveView expr_3A5_cp_0 = this.curve.View; - expr_3A5_cp_0.rect.yMin = expr_3A5_cp_0.rect.yMin + num4 * num2; - SimpleCurveView expr_3C6_cp_0 = this.curve.View; - expr_3C6_cp_0.rect.yMax = expr_3C6_cp_0.rect.yMax - num4 * num2; + Vector2 delta = Event.current.delta; + float num2 = (float)(-1.0 * delta.y * 0.02500000037252903); + Vector2 center = this.curve.View.rect.center; + float num3 = center.x - this.curve.View.rect.x; + Vector2 center2 = this.curve.View.rect.center; + float num4 = center2.y - this.curve.View.rect.y; + this.curve.View.rect.xMin += num3 * num2; + this.curve.View.rect.xMax -= num3 * num2; + this.curve.View.rect.yMin += num4 * num2; + this.curve.View.rect.yMax -= num4 * num2; Event.current.Use(); } if (Event.current.type == EventType.MouseDown && (Event.current.button == 0 || Event.current.button == 2)) { - List list = this.PointsNearMouse(screenRect).ToList(); - if (list.Any()) + List list = this.PointsNearMouse(screenRect).ToList(); + if (list.Any()) { this.draggingPointIndex = list[0]; } @@ -182,14 +182,14 @@ private void DoCurveEditor(Rect screenRect) { Vector2 mouseCurveCoords = SimpleCurveDrawer.ScreenToCurveCoords(screenRect, this.curve.View.rect, Event.current.mousePosition); List list2 = new List(); - list2.Add(new FloatMenuOption("Add point at " + mouseCurveCoords.ToString(), delegate + list2.Add(new FloatMenuOption("Add point at " + mouseCurveCoords.ToString(), (Action)delegate { this.curve.Add(new CurvePoint(mouseCurveCoords), true); }, MenuOptionPriority.Default, null, null, 0f, null, null)); - foreach (int current in this.PointsNearMouse(screenRect)) + foreach (int item in this.PointsNearMouse(screenRect)) { - CurvePoint point = this.curve[current]; - list2.Add(new FloatMenuOption("Remove point at " + point.ToString(), delegate + CurvePoint point = this.curve[item]; + list2.Add(new FloatMenuOption("Remove point at " + point.ToString(), (Action)delegate { this.curve.RemovePointNear(point); }, MenuOptionPriority.Default, null, null, 0f, null, null)); @@ -212,11 +212,9 @@ private void DoCurveEditor(Rect screenRect) { if (Event.current.type == EventType.MouseDrag) { - Vector2 delta = Event.current.delta; - SimpleCurveView expr_668_cp_0 = this.curve.View; - expr_668_cp_0.rect.x = expr_668_cp_0.rect.x - delta.x * this.curve.View.rect.width * 0.002f; - SimpleCurveView expr_6A7_cp_0 = this.curve.View; - expr_6A7_cp_0.rect.y = expr_6A7_cp_0.rect.y + delta.y * this.curve.View.rect.height * 0.002f; + Vector2 delta2 = Event.current.delta; + this.curve.View.rect.x -= (float)(delta2.x * this.curve.View.rect.width * 0.0020000000949949026); + this.curve.View.rect.y += (float)(delta2.y * this.curve.View.rect.height * 0.0020000000949949026); Event.current.Use(); } if (Event.current.type == EventType.MouseUp && Event.current.button == this.draggingButton) @@ -226,16 +224,24 @@ private void DoCurveEditor(Rect screenRect) } } - [DebuggerHidden] private IEnumerable PointsNearMouse(Rect screenRect) { - EditWindow_CurveEditor.c__Iterator232 c__Iterator = new EditWindow_CurveEditor.c__Iterator232(); - c__Iterator.screenRect = screenRect; - c__Iterator.<$>screenRect = screenRect; - c__Iterator.<>f__this = this; - EditWindow_CurveEditor.c__Iterator232 expr_1C = c__Iterator; - expr_1C.$PC = -2; - return expr_1C; + GUI.BeginGroup(screenRect); + try + { + for (int i = 0; i < this.curve.PointsCount; i++) + { + Vector2 screenPoint = SimpleCurveDrawer.CurveToScreenCoordsInsideScreenRect(screenRect, this.curve.View.rect, this.curve[i].Loc); + if ((screenPoint - Event.current.mousePosition).sqrMagnitude < 49.0) + { + yield return i; + } + } + } + finally + { + ((_003CPointsNearMouse_003Ec__Iterator232)/*Error near IL_0100: stateMachine*/)._003C_003E__Finally0(); + } } } } diff --git a/Assembly-CSharp/Verse/EditWindow_DebugInspector.cs b/Assembly-CSharp/Verse/EditWindow_DebugInspector.cs index b3af49a22..33e56ae45 100644 --- a/Assembly-CSharp/Verse/EditWindow_DebugInspector.cs +++ b/Assembly-CSharp/Verse/EditWindow_DebugInspector.cs @@ -38,7 +38,7 @@ public override bool IsDebug public EditWindow_DebugInspector() { - this.optionalTitle = "Debug inspector"; + base.optionalTitle = "Debug inspector"; } public override void WindowUpdate() @@ -59,8 +59,8 @@ public override void DoWindowContents(Rect inRect) } Text.Font = GameFont.Tiny; WidgetRow widgetRow = new WidgetRow(0f, 0f, UIDirection.RightThenUp, 99999f, 4f); - widgetRow.ToggleableIcon(ref this.fullMode, TexButton.InspectModeToggle, "Toggle deep inspection mode for things on the map.", null, null); - widgetRow.ToggleableIcon(ref DebugViewSettings.writeCellContents, TexButton.InspectModeToggle, "Toggle shallow inspection for things on the map.", null, null); + widgetRow.ToggleableIcon(ref this.fullMode, TexButton.InspectModeToggle, "Toggle deep inspection mode for things on the map.", (SoundDef)null, (string)null); + widgetRow.ToggleableIcon(ref DebugViewSettings.writeCellContents, TexButton.InspectModeToggle, "Toggle shallow inspection for things on the map.", (SoundDef)null, (string)null); if (widgetRow.ButtonText("Visibility", "Toggle what information should be reported by the inspector.", true, false)) { Find.WindowStack.Add(new Dialog_DebugSettingsMenu()); @@ -79,14 +79,11 @@ public override void DoWindowContents(Rect inRect) Listing_Standard listing_Standard = new Listing_Standard(GameFont.Tiny); listing_Standard.ColumnWidth = Mathf.Min(this.columnWidth, inRect.width); listing_Standard.Begin(inRect); - string[] array = this.debugStringBuilder.ToString().Split(new char[] + string[] array; + string[] array2 = array = this.debugStringBuilder.ToString().Split('\n'); + for (int i = 0; i < array.Length; i++) { - '\n' - }); - string[] array2 = array; - for (int i = 0; i < array2.Length; i++) - { - string label = array2[i]; + string label = array[i]; listing_Standard.Label(label, -1f); listing_Standard.Gap(-10f); } @@ -106,386 +103,411 @@ public void AppendDebugString(string str) private string CurrentDebugString() { StringBuilder stringBuilder = new StringBuilder(); - if (WorldRendererUtility.WorldRenderedNow || Find.VisibleMap == null) - { - stringBuilder.AppendLine("World view"); - return stringBuilder.ToString(); - } - if (DebugViewSettings.writeGameConditions) + Pawn pawn2; + Pawn pawn3; + if (!WorldRendererUtility.WorldRenderedNow && Find.VisibleMap != null) { - stringBuilder.AppendLine("---"); - stringBuilder.AppendLine(Find.VisibleMap.gameConditionManager.DebugString()); - } - if (DebugViewSettings.writePlayingSounds) - { - stringBuilder.AppendLine("---"); - stringBuilder.AppendLine("Sustainers:"); - foreach (Sustainer current in Find.SoundRoot.sustainerManager.AllSustainers) + if (DebugViewSettings.writeGameConditions) { - stringBuilder.AppendLine(current.DebugString()); + stringBuilder.AppendLine("---"); + stringBuilder.AppendLine(Find.VisibleMap.gameConditionManager.DebugString()); } - stringBuilder.AppendLine(); - stringBuilder.AppendLine("OneShots:"); - foreach (SampleOneShot current2 in Find.SoundRoot.oneShotManager.PlayingOneShots) - { - stringBuilder.AppendLine(current2.ToString()); - } - } - if (DebugViewSettings.writeSoundEventsRecord) - { - stringBuilder.AppendLine("---"); - stringBuilder.AppendLine("Recent sound events:\n ..."); - stringBuilder.AppendLine(DebugSoundEventsLog.EventsListingDebugString); - } - if (DebugViewSettings.writeGame) - { - stringBuilder.AppendLine("---"); - stringBuilder.AppendLine((Current.Game != null) ? Current.Game.DebugString() : "Current.Game = null"); - } - if (DebugViewSettings.writeSteamItems) - { - stringBuilder.AppendLine("---"); - stringBuilder.AppendLine(WorkshopItems.DebugOutput()); - } - if (DebugViewSettings.writeConcepts) - { - stringBuilder.AppendLine("---"); - stringBuilder.AppendLine(LessonAutoActivator.DebugString()); - } - if (DebugViewSettings.writeMemoryUsage) - { - stringBuilder.AppendLine("---"); - stringBuilder.AppendLine("Total allocated: " + Profiler.GetTotalAllocatedMemory().ToStringBytes("F2")); - stringBuilder.AppendLine("Total reserved: " + Profiler.GetTotalReservedMemory().ToStringBytes("F2")); - stringBuilder.AppendLine("Total reserved unused: " + Profiler.GetTotalUnusedReservedMemory().ToStringBytes("F2")); - stringBuilder.AppendLine("Mono heap size: " + Profiler.GetMonoHeapSize().ToStringBytes("F2")); - stringBuilder.AppendLine("Mono used size: " + Profiler.GetMonoUsedSize().ToStringBytes("F2")); - } - if (Current.ProgramState == ProgramState.Playing) - { - IntVec3 intVec = UI.MouseCell(); - stringBuilder.AppendLine("Tick " + Find.TickManager.TicksGame); - stringBuilder.AppendLine("Inspecting " + intVec.ToString()); - if (DebugViewSettings.writeCellContents || this.fullMode) + if (DebugViewSettings.writePlayingSounds) { stringBuilder.AppendLine("---"); - if (intVec.InBounds(Find.VisibleMap)) + stringBuilder.AppendLine("Sustainers:"); + List.Enumerator enumerator = Find.SoundRoot.sustainerManager.AllSustainers.GetEnumerator(); + try { - foreach (Designation current3 in Find.VisibleMap.designationManager.AllDesignationsAt(intVec)) + while (enumerator.MoveNext()) { - stringBuilder.AppendLine(current3.ToString()); - } - foreach (Thing current4 in Find.VisibleMap.thingGrid.ThingsAt(intVec)) - { - if (!this.fullMode) - { - stringBuilder.AppendLine(current4.LabelCap + " - " + current4.ToString()); - } - else - { - stringBuilder.AppendLine(Scribe.saver.DebugOutputFor(current4)); - stringBuilder.AppendLine(); - } + Sustainer current = enumerator.Current; + stringBuilder.AppendLine(current.DebugString()); } } - } - if (DebugViewSettings.debugApparelOptimize) - { - stringBuilder.AppendLine("---"); - foreach (Thing current5 in Find.VisibleMap.thingGrid.ThingsAt(intVec)) + finally { - Apparel apparel = current5 as Apparel; - if (apparel != null) - { - stringBuilder.AppendLine(apparel.LabelCap); - stringBuilder.AppendLine(" raw: " + JobGiver_OptimizeApparel.ApparelScoreRaw(null, apparel).ToString("F2")); - Pawn pawn = Find.Selector.SingleSelectedThing as Pawn; - if (pawn != null) - { - stringBuilder.AppendLine(" Pawn: " + pawn); - stringBuilder.AppendLine(" gain: " + JobGiver_OptimizeApparel.ApparelScoreGain(pawn, apparel).ToString("F2")); - } - } + ((IDisposable)(object)enumerator).Dispose(); + } + stringBuilder.AppendLine(); + stringBuilder.AppendLine("OneShots:"); + foreach (SampleOneShot playingOneShot in Find.SoundRoot.oneShotManager.PlayingOneShots) + { + stringBuilder.AppendLine(playingOneShot.ToString()); } } - if (DebugViewSettings.drawPawnDebug) - { - stringBuilder.AppendLine("---"); - stringBuilder.AppendLine(Find.VisibleMap.reservationManager.DebugString()); - } - if (DebugViewSettings.writeMoteSaturation) - { - stringBuilder.AppendLine("---"); - stringBuilder.AppendLine("Mote count: " + Find.VisibleMap.moteCounter.MoteCount); - stringBuilder.AppendLine("Mote saturation: " + Find.VisibleMap.moteCounter.Saturation); - } - if (DebugViewSettings.writeSnowDepth) - { - stringBuilder.AppendLine("---"); - stringBuilder.AppendLine("Snow depth: " + Find.VisibleMap.snowGrid.GetDepth(intVec)); - } - if (DebugViewSettings.drawDeepResources) - { - stringBuilder.AppendLine("---"); - stringBuilder.AppendLine("Deep resource def: " + Find.VisibleMap.deepResourceGrid.ThingDefAt(intVec)); - stringBuilder.AppendLine("Deep resource count: " + Find.VisibleMap.deepResourceGrid.CountAt(intVec)); - } - if (DebugViewSettings.writeEcosystem) + if (DebugViewSettings.writeSoundEventsRecord) { stringBuilder.AppendLine("---"); - stringBuilder.AppendLine(Find.VisibleMap.wildSpawner.DebugString()); + stringBuilder.AppendLine("Recent sound events:\n ..."); + stringBuilder.AppendLine(DebugSoundEventsLog.EventsListingDebugString); } - if (DebugViewSettings.writeTotalSnowDepth) + if (DebugViewSettings.writeGame) { stringBuilder.AppendLine("---"); - stringBuilder.AppendLine("Total snow depth: " + Find.VisibleMap.snowGrid.TotalDepth); + stringBuilder.AppendLine((Current.Game != null) ? Current.Game.DebugString() : "Current.Game = null"); } - if (DebugViewSettings.writeCanReachColony) + if (DebugViewSettings.writeSteamItems) { stringBuilder.AppendLine("---"); - stringBuilder.AppendLine("CanReachColony: " + Find.VisibleMap.reachability.CanReachColony(UI.MouseCell())); + stringBuilder.AppendLine(WorkshopItems.DebugOutput()); } - if (DebugViewSettings.writeMentalStateCalcs) + if (DebugViewSettings.writeConcepts) { stringBuilder.AppendLine("---"); - foreach (Pawn current6 in (from t in Find.VisibleMap.thingGrid.ThingsAt(UI.MouseCell()) - where t is Pawn - select t).Cast()) - { - stringBuilder.AppendLine(current6.mindState.mentalBreaker.DebugString()); - } + stringBuilder.AppendLine(LessonAutoActivator.DebugString()); } - if (DebugViewSettings.writeWind) + if (DebugViewSettings.writeMemoryUsage) { stringBuilder.AppendLine("---"); - stringBuilder.AppendLine(Find.VisibleMap.windManager.DebugString()); + stringBuilder.AppendLine("Total allocated: " + Profiler.GetTotalAllocatedMemory().ToStringBytes("F2")); + stringBuilder.AppendLine("Total reserved: " + Profiler.GetTotalReservedMemory().ToStringBytes("F2")); + stringBuilder.AppendLine("Total reserved unused: " + Profiler.GetTotalUnusedReservedMemory().ToStringBytes("F2")); + stringBuilder.AppendLine("Mono heap size: " + Profiler.GetMonoHeapSize().ToStringBytes("F2")); + stringBuilder.AppendLine("Mono used size: " + Profiler.GetMonoUsedSize().ToStringBytes("F2")); } - if (DebugViewSettings.writeWorkSettings) + if (Current.ProgramState == ProgramState.Playing) { - foreach (Pawn current7 in (from t in Find.VisibleMap.thingGrid.ThingsAt(UI.MouseCell()) - where t is Pawn - select t).Cast()) + IntVec3 intVec = UI.MouseCell(); + stringBuilder.AppendLine("Tick " + Find.TickManager.TicksGame); + stringBuilder.AppendLine("Inspecting " + intVec.ToString()); + if (DebugViewSettings.writeCellContents || this.fullMode) { - if (current7.workSettings != null) + stringBuilder.AppendLine("---"); + if (intVec.InBounds(Find.VisibleMap)) { - stringBuilder.AppendLine("---"); - stringBuilder.AppendLine(current7.workSettings.DebugString()); + foreach (Designation item in Find.VisibleMap.designationManager.AllDesignationsAt(intVec)) + { + stringBuilder.AppendLine(item.ToString()); + } + foreach (Thing item2 in Find.VisibleMap.thingGrid.ThingsAt(intVec)) + { + if (!this.fullMode) + { + stringBuilder.AppendLine(item2.LabelCap + " - " + item2.ToString()); + } + else + { + stringBuilder.AppendLine(Scribe.saver.DebugOutputFor(item2)); + stringBuilder.AppendLine(); + } + } } } - } - if (DebugViewSettings.writeApparelScore) - { - stringBuilder.AppendLine("---"); - if (intVec.InBounds(Find.VisibleMap)) + if (DebugViewSettings.debugApparelOptimize) { - foreach (Thing current8 in intVec.GetThingList(Find.VisibleMap)) + stringBuilder.AppendLine("---"); + foreach (Thing item3 in Find.VisibleMap.thingGrid.ThingsAt(intVec)) { - Apparel apparel2 = current8 as Apparel; - if (apparel2 != null) + Apparel apparel = item3 as Apparel; + if (apparel != null) { - stringBuilder.AppendLine(apparel2.Label + ": " + JobGiver_OptimizeApparel.ApparelScoreRaw(null, apparel2).ToString("F2")); + stringBuilder.AppendLine(apparel.LabelCap); + stringBuilder.AppendLine(" raw: " + JobGiver_OptimizeApparel.ApparelScoreRaw(null, apparel).ToString("F2")); + Pawn pawn = Find.Selector.SingleSelectedThing as Pawn; + if (pawn != null) + { + stringBuilder.AppendLine(" Pawn: " + pawn); + stringBuilder.AppendLine(" gain: " + JobGiver_OptimizeApparel.ApparelScoreGain(pawn, apparel).ToString("F2")); + } } } } - } - if (DebugViewSettings.writeRecentStrikes) - { - stringBuilder.AppendLine("---"); - stringBuilder.AppendLine(Find.VisibleMap.mineStrikeManager.DebugStrikeRecords()); - } - if (DebugViewSettings.writeStoryteller) - { - stringBuilder.AppendLine("---"); - stringBuilder.AppendLine(Find.Storyteller.DebugString()); - stringBuilder.AppendLine("---"); - stringBuilder.AppendLine(Find.StoryWatcher.DebugString()); - } - if (DebugViewSettings.writeListRepairableBldgs) - { - stringBuilder.AppendLine("---"); - stringBuilder.AppendLine(Find.VisibleMap.listerBuildingsRepairable.DebugString()); - } - if (DebugViewSettings.writeListFilthInHomeArea) - { - stringBuilder.AppendLine("---"); - stringBuilder.AppendLine(Find.VisibleMap.listerFilthInHomeArea.DebugString()); - } - if (DebugViewSettings.writeTerrain) - { - stringBuilder.AppendLine("---"); - stringBuilder.AppendLine(Find.VisibleMap.terrainGrid.DebugStringAt(intVec)); - } - if (DebugViewSettings.writeListHaulables) - { - stringBuilder.AppendLine("---"); - stringBuilder.AppendLine(Find.VisibleMap.listerHaulables.DebugString()); - } - if (DebugViewSettings.drawLords) - { - foreach (Lord current9 in Find.VisibleMap.lordManager.lords) + if (DebugViewSettings.drawPawnDebug) { stringBuilder.AppendLine("---"); - stringBuilder.AppendLine(current9.DebugString()); + stringBuilder.AppendLine(Find.VisibleMap.reservationManager.DebugString()); } - } - if (DebugViewSettings.writeMusicManagerPlay) - { - stringBuilder.AppendLine("---"); - stringBuilder.AppendLine(Find.MusicManagerPlay.DebugString()); - } - if (DebugViewSettings.writeAttackTargets) - { - foreach (Pawn current10 in Find.VisibleMap.thingGrid.ThingsAt(UI.MouseCell()).OfType()) + if (DebugViewSettings.writeMoteSaturation) { stringBuilder.AppendLine("---"); - stringBuilder.AppendLine("Potential attack targets for " + current10.LabelShort + ":"); - List potentialTargetsFor = Find.VisibleMap.attackTargetsCache.GetPotentialTargetsFor(current10); - for (int i = 0; i < potentialTargetsFor.Count; i++) - { - Thing thing = (Thing)potentialTargetsFor[i]; - stringBuilder.AppendLine(string.Concat(new object[] - { - thing.LabelShort, - ", ", - thing.Faction, - (!potentialTargetsFor[i].ThreatDisabled()) ? string.Empty : " (threat disabled)" - })); - } + stringBuilder.AppendLine("Mote count: " + Find.VisibleMap.moteCounter.MoteCount); + stringBuilder.AppendLine("Mote saturation: " + Find.VisibleMap.moteCounter.Saturation); } - } - if (intVec.InBounds(Find.VisibleMap)) - { - if (DebugViewSettings.drawRegions) + if (DebugViewSettings.writeSnowDepth) { stringBuilder.AppendLine("---"); - Region regionAt_NoRebuild_InvalidAllowed = Find.VisibleMap.regionGrid.GetRegionAt_NoRebuild_InvalidAllowed(intVec); - stringBuilder.AppendLine("Region:\n" + ((regionAt_NoRebuild_InvalidAllowed == null) ? "null" : regionAt_NoRebuild_InvalidAllowed.DebugString)); + stringBuilder.AppendLine("Snow depth: " + Find.VisibleMap.snowGrid.GetDepth(intVec)); } - if (DebugViewSettings.drawRooms) + if (DebugViewSettings.drawDeepResources) { stringBuilder.AppendLine("---"); - Room room = intVec.GetRoom(Find.VisibleMap, RegionType.Set_All); - if (room != null) - { - stringBuilder.AppendLine(room.DebugString()); - } - else + stringBuilder.AppendLine("Deep resource def: " + Find.VisibleMap.deepResourceGrid.ThingDefAt(intVec)); + stringBuilder.AppendLine("Deep resource count: " + Find.VisibleMap.deepResourceGrid.CountAt(intVec)); + } + if (DebugViewSettings.writeEcosystem) + { + stringBuilder.AppendLine("---"); + stringBuilder.AppendLine(Find.VisibleMap.wildSpawner.DebugString()); + } + if (DebugViewSettings.writeTotalSnowDepth) + { + stringBuilder.AppendLine("---"); + stringBuilder.AppendLine("Total snow depth: " + Find.VisibleMap.snowGrid.TotalDepth); + } + if (DebugViewSettings.writeCanReachColony) + { + stringBuilder.AppendLine("---"); + stringBuilder.AppendLine("CanReachColony: " + Find.VisibleMap.reachability.CanReachColony(UI.MouseCell())); + } + if (DebugViewSettings.writeMentalStateCalcs) + { + stringBuilder.AppendLine("---"); + foreach (Pawn item4 in (from t in Find.VisibleMap.thingGrid.ThingsAt(UI.MouseCell()) + where t is Pawn + select t).Cast()) { - stringBuilder.AppendLine("(no room)"); + stringBuilder.AppendLine(item4.mindState.mentalBreaker.DebugString()); } } - if (DebugViewSettings.drawRoomGroups) + if (DebugViewSettings.writeWind) { stringBuilder.AppendLine("---"); - RoomGroup roomGroup = intVec.GetRoomGroup(Find.VisibleMap); - if (roomGroup != null) + stringBuilder.AppendLine(Find.VisibleMap.windManager.DebugString()); + } + if (DebugViewSettings.writeWorkSettings) + { + foreach (Pawn item5 in (from t in Find.VisibleMap.thingGrid.ThingsAt(UI.MouseCell()) + where t is Pawn + select t).Cast()) { - stringBuilder.AppendLine(roomGroup.DebugString()); + if (item5.workSettings != null) + { + stringBuilder.AppendLine("---"); + stringBuilder.AppendLine(item5.workSettings.DebugString()); + } } - else + } + if (DebugViewSettings.writeApparelScore) + { + stringBuilder.AppendLine("---"); + if (intVec.InBounds(Find.VisibleMap)) { - stringBuilder.AppendLine("(no room group)"); + List.Enumerator enumerator8 = intVec.GetThingList(Find.VisibleMap).GetEnumerator(); + try + { + while (enumerator8.MoveNext()) + { + Thing current8 = enumerator8.Current; + Apparel apparel2 = current8 as Apparel; + if (apparel2 != null) + { + stringBuilder.AppendLine(apparel2.Label + ": " + JobGiver_OptimizeApparel.ApparelScoreRaw(null, apparel2).ToString("F2")); + } + } + } + finally + { + ((IDisposable)(object)enumerator8).Dispose(); + } } } - if (DebugViewSettings.drawGlow) + if (DebugViewSettings.writeRecentStrikes) { stringBuilder.AppendLine("---"); - stringBuilder.AppendLine("Game glow: " + Find.VisibleMap.glowGrid.GameGlowAt(intVec)); - stringBuilder.AppendLine("Psych glow: " + Find.VisibleMap.glowGrid.PsychGlowAt(intVec)); - stringBuilder.AppendLine("Visual Glow: " + Find.VisibleMap.glowGrid.VisualGlowAt(intVec)); - stringBuilder.AppendLine("GlowReport:\n" + ((SectionLayer_LightingOverlay)Find.VisibleMap.mapDrawer.SectionAt(intVec).GetLayer(typeof(SectionLayer_LightingOverlay))).GlowReportAt(intVec)); - stringBuilder.AppendLine("SkyManager.CurSkyGlow: " + Find.VisibleMap.skyManager.CurSkyGlow); + stringBuilder.AppendLine(Find.VisibleMap.mineStrikeManager.DebugStrikeRecords()); } - if (DebugViewSettings.writePathCosts) + if (DebugViewSettings.writeStoryteller) { stringBuilder.AppendLine("---"); - stringBuilder.AppendLine("Perceived path cost: " + Find.VisibleMap.pathGrid.PerceivedPathCostAt(intVec)); - stringBuilder.AppendLine("Real path cost: " + Find.VisibleMap.pathGrid.CalculatedCostAt(intVec, false, IntVec3.Invalid)); + stringBuilder.AppendLine(Find.Storyteller.DebugString()); + stringBuilder.AppendLine("---"); + stringBuilder.AppendLine(Find.StoryWatcher.DebugString()); } - if (DebugViewSettings.writeFertility) + if (DebugViewSettings.writeListRepairableBldgs) { stringBuilder.AppendLine("---"); - stringBuilder.AppendLine("\nFertility: " + Find.VisibleMap.fertilityGrid.FertilityAt(intVec).ToString("##0.00")); + stringBuilder.AppendLine(Find.VisibleMap.listerBuildingsRepairable.DebugString()); } - if (DebugViewSettings.writeLinkFlags) + if (DebugViewSettings.writeListFilthInHomeArea) { stringBuilder.AppendLine("---"); - stringBuilder.AppendLine("\nLinkFlags: "); - foreach (object current11 in Enum.GetValues(typeof(LinkFlags))) - { - if ((Find.VisibleMap.linkGrid.LinkFlagsAt(intVec) & (LinkFlags)((int)current11)) != LinkFlags.None) - { - stringBuilder.Append(" " + current11); - } - } + stringBuilder.AppendLine(Find.VisibleMap.listerFilthInHomeArea.DebugString()); } - if (DebugViewSettings.writeSkyManager) + if (DebugViewSettings.writeTerrain) { stringBuilder.AppendLine("---"); - stringBuilder.AppendLine(Find.VisibleMap.skyManager.DebugString()); + stringBuilder.AppendLine(Find.VisibleMap.terrainGrid.DebugStringAt(intVec)); } - if (DebugViewSettings.writeCover) + if (DebugViewSettings.writeListHaulables) { stringBuilder.AppendLine("---"); - stringBuilder.Append("Cover: "); - Thing thing2 = Find.VisibleMap.coverGrid[intVec]; - if (thing2 == null) + stringBuilder.AppendLine(Find.VisibleMap.listerHaulables.DebugString()); + } + if (DebugViewSettings.drawLords) + { + List.Enumerator enumerator9 = Find.VisibleMap.lordManager.lords.GetEnumerator(); + try { - stringBuilder.AppendLine("null"); + while (enumerator9.MoveNext()) + { + Lord current9 = enumerator9.Current; + stringBuilder.AppendLine("---"); + stringBuilder.AppendLine(current9.DebugString()); + } } - else + finally { - stringBuilder.AppendLine(thing2.ToString()); + ((IDisposable)(object)enumerator9).Dispose(); } } - if (DebugViewSettings.drawPower) + if (DebugViewSettings.writeMusicManagerPlay) { stringBuilder.AppendLine("---"); - foreach (Thing current12 in Find.VisibleMap.thingGrid.ThingsAt(intVec)) + stringBuilder.AppendLine(Find.MusicManagerPlay.DebugString()); + } + if (DebugViewSettings.writeAttackTargets) + { + foreach (Pawn item6 in Find.VisibleMap.thingGrid.ThingsAt(UI.MouseCell()).OfType()) { - ThingWithComps thingWithComps = current12 as ThingWithComps; - if (thingWithComps != null && thingWithComps.GetComp() != null) + stringBuilder.AppendLine("---"); + stringBuilder.AppendLine("Potential attack targets for " + item6.LabelShort + ":"); + List potentialTargetsFor = Find.VisibleMap.attackTargetsCache.GetPotentialTargetsFor(item6); + for (int i = 0; i < potentialTargetsFor.Count; i++) { - stringBuilder.AppendLine(" " + thingWithComps.GetComp().DebugString); + Thing thing = (Thing)potentialTargetsFor[i]; + stringBuilder.AppendLine(thing.LabelShort + ", " + thing.Faction + ((!potentialTargetsFor[i].ThreatDisabled()) ? string.Empty : " (threat disabled)")); } } - PowerNet powerNet = Find.VisibleMap.powerNetGrid.TransmittedPowerNetAt(intVec); - if (powerNet != null) + } + if (intVec.InBounds(Find.VisibleMap)) + { + if (DebugViewSettings.drawRegions) { - stringBuilder.AppendLine(string.Empty + powerNet.DebugString()); + stringBuilder.AppendLine("---"); + Region regionAt_NoRebuild_InvalidAllowed = Find.VisibleMap.regionGrid.GetRegionAt_NoRebuild_InvalidAllowed(intVec); + stringBuilder.AppendLine("Region:\n" + ((regionAt_NoRebuild_InvalidAllowed == null) ? "null" : regionAt_NoRebuild_InvalidAllowed.DebugString)); } - else + if (DebugViewSettings.drawRooms) { - stringBuilder.AppendLine("(no PowerNet here)"); + stringBuilder.AppendLine("---"); + Room room = intVec.GetRoom(Find.VisibleMap, RegionType.Set_All); + if (room != null) + { + stringBuilder.AppendLine(room.DebugString()); + } + else + { + stringBuilder.AppendLine("(no room)"); + } } - } - if (DebugViewSettings.drawPreyInfo) - { - Pawn pawn2 = Find.Selector.SingleSelectedThing as Pawn; - if (pawn2 != null) + if (DebugViewSettings.drawRoomGroups) + { + stringBuilder.AppendLine("---"); + RoomGroup roomGroup = intVec.GetRoomGroup(Find.VisibleMap); + if (roomGroup != null) + { + stringBuilder.AppendLine(roomGroup.DebugString()); + } + else + { + stringBuilder.AppendLine("(no room group)"); + } + } + if (DebugViewSettings.drawGlow) + { + stringBuilder.AppendLine("---"); + stringBuilder.AppendLine("Game glow: " + Find.VisibleMap.glowGrid.GameGlowAt(intVec)); + stringBuilder.AppendLine("Psych glow: " + Find.VisibleMap.glowGrid.PsychGlowAt(intVec)); + stringBuilder.AppendLine("Visual Glow: " + Find.VisibleMap.glowGrid.VisualGlowAt(intVec)); + stringBuilder.AppendLine("GlowReport:\n" + ((SectionLayer_LightingOverlay)Find.VisibleMap.mapDrawer.SectionAt(intVec).GetLayer(typeof(SectionLayer_LightingOverlay))).GlowReportAt(intVec)); + stringBuilder.AppendLine("SkyManager.CurSkyGlow: " + Find.VisibleMap.skyManager.CurSkyGlow); + } + if (DebugViewSettings.writePathCosts) + { + stringBuilder.AppendLine("---"); + stringBuilder.AppendLine("Perceived path cost: " + Find.VisibleMap.pathGrid.PerceivedPathCostAt(intVec)); + stringBuilder.AppendLine("Real path cost: " + Find.VisibleMap.pathGrid.CalculatedCostAt(intVec, false, IntVec3.Invalid)); + } + if (DebugViewSettings.writeFertility) + { + stringBuilder.AppendLine("---"); + stringBuilder.AppendLine("\nFertility: " + Find.VisibleMap.fertilityGrid.FertilityAt(intVec).ToString("##0.00")); + } + if (DebugViewSettings.writeLinkFlags) { - List thingList = intVec.GetThingList(Find.VisibleMap); - for (int j = 0; j < thingList.Count; j++) + stringBuilder.AppendLine("---"); + stringBuilder.AppendLine("\nLinkFlags: "); + foreach (object value in Enum.GetValues(typeof(LinkFlags))) { - Pawn pawn3 = thingList[j] as Pawn; - if (pawn3 != null) + if (((int)Find.VisibleMap.linkGrid.LinkFlagsAt(intVec) & (int)value) != 0) { - stringBuilder.AppendLine("---"); - if (FoodUtility.IsAcceptablePreyFor(pawn2, pawn3)) - { - stringBuilder.AppendLine("Prey score: " + FoodUtility.GetPreyScoreFor(pawn2, pawn3)); - } - else - { - stringBuilder.AppendLine("Prey score: None"); - } - break; + stringBuilder.Append(" " + value); + } + } + } + if (DebugViewSettings.writeSkyManager) + { + stringBuilder.AppendLine("---"); + stringBuilder.AppendLine(Find.VisibleMap.skyManager.DebugString()); + } + if (DebugViewSettings.writeCover) + { + stringBuilder.AppendLine("---"); + stringBuilder.Append("Cover: "); + Thing thing2 = Find.VisibleMap.coverGrid[intVec]; + if (thing2 == null) + { + stringBuilder.AppendLine("null"); + } + else + { + stringBuilder.AppendLine(thing2.ToString()); + } + } + if (DebugViewSettings.drawPower) + { + stringBuilder.AppendLine("---"); + foreach (Thing item7 in Find.VisibleMap.thingGrid.ThingsAt(intVec)) + { + ThingWithComps thingWithComps = item7 as ThingWithComps; + if (thingWithComps != null && thingWithComps.GetComp() != null) + { + stringBuilder.AppendLine(" " + thingWithComps.GetComp().DebugString); + } + } + PowerNet powerNet = Find.VisibleMap.powerNetGrid.TransmittedPowerNetAt(intVec); + if (powerNet != null) + { + stringBuilder.AppendLine(string.Empty + powerNet.DebugString()); + } + else + { + stringBuilder.AppendLine("(no PowerNet here)"); + } + } + if (DebugViewSettings.drawPreyInfo) + { + pawn2 = (Find.Selector.SingleSelectedThing as Pawn); + if (pawn2 != null) + { + List thingList = intVec.GetThingList(Find.VisibleMap); + for (int j = 0; j < thingList.Count; j++) + { + pawn3 = (thingList[j] as Pawn); + if (pawn3 != null) + goto IL_105f; } } } } } + goto IL_10c2; + } + stringBuilder.AppendLine("World view"); + return stringBuilder.ToString(); + IL_105f: + stringBuilder.AppendLine("---"); + if (FoodUtility.IsAcceptablePreyFor(pawn2, pawn3)) + { + stringBuilder.AppendLine("Prey score: " + FoodUtility.GetPreyScoreFor(pawn2, pawn3)); + } + else + { + stringBuilder.AppendLine("Prey score: None"); } + goto IL_10c2; + IL_10c2: return stringBuilder.ToString(); } } diff --git a/Assembly-CSharp/Verse/EditWindow_DefEditor.cs b/Assembly-CSharp/Verse/EditWindow_DefEditor.cs index ec4f45ca7..8d3f84b72 100644 --- a/Assembly-CSharp/Verse/EditWindow_DefEditor.cs +++ b/Assembly-CSharp/Verse/EditWindow_DefEditor.cs @@ -1,4 +1,3 @@ -using System; using UnityEngine; namespace Verse @@ -36,7 +35,7 @@ public override bool IsDebug public EditWindow_DefEditor(Def def) { this.def = def; - this.optionalTitle = def.ToString(); + base.optionalTitle = def.ToString(); } public override void DoWindowContents(Rect inRect) @@ -46,10 +45,10 @@ public override void DoWindowContents(Rect inRect) UI.UnfocusCurrentControl(); } Rect rect = new Rect(0f, 0f, inRect.width, 16f); - this.labelColumnWidth = Widgets.HorizontalSlider(rect, this.labelColumnWidth, 0f, inRect.width, false, null, null, null, -1f); + this.labelColumnWidth = Widgets.HorizontalSlider(rect, this.labelColumnWidth, 0f, inRect.width, false, (string)null, (string)null, (string)null, -1f); Rect outRect = inRect.AtZero(); outRect.yMin += 16f; - Rect rect2 = new Rect(0f, 0f, outRect.width - 16f, this.viewHeight); + Rect rect2 = new Rect(0f, 0f, (float)(outRect.width - 16.0), this.viewHeight); Widgets.BeginScrollView(outRect, ref this.scrollPosition, rect2, true); Listing_TreeDefs listing_TreeDefs = new Listing_TreeDefs(this.labelColumnWidth); listing_TreeDefs.Begin(rect2); @@ -58,7 +57,7 @@ public override void DoWindowContents(Rect inRect) listing_TreeDefs.End(); if (Event.current.type == EventType.Layout) { - this.viewHeight = listing_TreeDefs.CurHeight + 200f; + this.viewHeight = (float)(listing_TreeDefs.CurHeight + 200.0); } Widgets.EndScrollView(); } diff --git a/Assembly-CSharp/Verse/EditWindow_Log.cs b/Assembly-CSharp/Verse/EditWindow_Log.cs index bcebff824..8a09afd45 100644 --- a/Assembly-CSharp/Verse/EditWindow_Log.cs +++ b/Assembly-CSharp/Verse/EditWindow_Log.cs @@ -1,4 +1,3 @@ -using System; using System.Text; using UnityEngine; @@ -51,7 +50,7 @@ public override Vector2 InitialSize { get { - return new Vector2((float)UI.screenWidth / 2f, (float)UI.screenHeight / 2f); + return new Vector2((float)((float)UI.screenWidth / 2.0), (float)((float)UI.screenHeight / 2.0)); } } @@ -71,21 +70,20 @@ private static LogMessage SelectedMessage } set { - if (EditWindow_Log.selectedMessage == value) + if (EditWindow_Log.selectedMessage != value) { - return; - } - EditWindow_Log.selectedMessage = value; - if (UnityData.IsInMainThread && GUI.GetNameOfFocusedControl() == EditWindow_Log.MessageDetailsControlName) - { - UI.UnfocusCurrentControl(); + EditWindow_Log.selectedMessage = value; + if (UnityData.IsInMainThread && GUI.GetNameOfFocusedControl() == EditWindow_Log.MessageDetailsControlName) + { + UI.UnfocusCurrentControl(); + } } } } public EditWindow_Log() { - this.optionalTitle = "Debug log"; + base.optionalTitle = "Debug log"; } public static void TryAutoOpen() @@ -158,8 +156,10 @@ public override void DoWindowContents(Rect inRect) { rect.yMax -= EditWindow_Log.detailsPaneHeight; } - Rect detailsRect = new Rect(inRect); - detailsRect.yMin = rect.yMax; + Rect detailsRect = new Rect(inRect) + { + yMin = rect.yMax + }; this.DoMessagesListing(rect); this.DoMessageDetails(detailsRect, inRect); if (Event.current.type == EventType.MouseDown && Event.current.button == 0 && Mouse.IsOver(rect)) @@ -167,7 +167,7 @@ public override void DoWindowContents(Rect inRect) EditWindow_Log.ClearSelectedMessage(); } EditWindow_Log.detailsPaneHeight = Mathf.Max(EditWindow_Log.detailsPaneHeight, 20f); - EditWindow_Log.detailsPaneHeight = Mathf.Min(EditWindow_Log.detailsPaneHeight, inRect.height - 80f); + EditWindow_Log.detailsPaneHeight = Mathf.Min(EditWindow_Log.detailsPaneHeight, (float)(inRect.height - 80.0)); } public static void Notify_MessageDequeued(LogMessage oldMessage) @@ -180,24 +180,24 @@ public static void Notify_MessageDequeued(LogMessage oldMessage) private void DoMessagesListing(Rect listingRect) { - Rect viewRect = new Rect(0f, 0f, listingRect.width - 16f, this.listingViewHeight + 100f); + Rect viewRect = new Rect(0f, 0f, (float)(listingRect.width - 16.0), (float)(this.listingViewHeight + 100.0)); Widgets.BeginScrollView(listingRect, ref EditWindow_Log.messagesScrollPosition, viewRect, true); - float width = viewRect.width - 28f; + float width = (float)(viewRect.width - 28.0); Text.Font = GameFont.Tiny; float num = 0f; bool flag = false; - foreach (LogMessage current in Log.Messages) + foreach (LogMessage message in Log.Messages) { - float num2 = Text.CalcHeight(current.text, width); - if (num2 > 30f) + float num2 = Text.CalcHeight(message.text, width); + if (num2 > 30.0) { num2 = 30f; } GUI.color = new Color(1f, 1f, 1f, 0.7f); Rect rect = new Rect(4f, num, 28f, num2); - Widgets.Label(rect, current.repeats.ToStringCached()); + Widgets.Label(rect, message.repeats.ToStringCached()); Rect rect2 = new Rect(28f, num, width, num2); - if (EditWindow_Log.selectedMessage == current) + if (EditWindow_Log.selectedMessage == message) { GUI.DrawTexture(rect2, EditWindow_Log.SelectedMessageTex); } @@ -208,10 +208,10 @@ private void DoMessagesListing(Rect listingRect) if (Widgets.ButtonInvisible(rect2, false)) { EditWindow_Log.ClearSelectedMessage(); - EditWindow_Log.SelectedMessage = current; + EditWindow_Log.SelectedMessage = message; } - GUI.color = current.Color; - Widgets.Label(rect2, current.text); + GUI.color = message.Color; + Widgets.Label(rect2, message.text); num += num2; flag = !flag; } @@ -225,49 +225,50 @@ private void DoMessagesListing(Rect listingRect) private void DoMessageDetails(Rect detailsRect, Rect outRect) { - if (EditWindow_Log.selectedMessage == null) - { - return; - } - Rect rect = detailsRect; - rect.height = 7f; - Rect rect2 = detailsRect; - rect2.yMin = rect.yMax; - GUI.DrawTexture(rect, EditWindow_Log.StackTraceBorderTex); - if (Mouse.IsOver(rect)) - { - Widgets.DrawHighlight(rect); - } - if (Event.current.type == EventType.MouseDown && Mouse.IsOver(rect)) - { - this.borderDragging = true; - Event.current.Use(); - } - if (this.borderDragging) - { - EditWindow_Log.detailsPaneHeight = outRect.height + Mathf.Round(3.5f) - Event.current.mousePosition.y; - } - if (Event.current.rawType == EventType.MouseUp) + if (EditWindow_Log.selectedMessage != null) { - this.borderDragging = false; + Rect rect = detailsRect; + rect.height = 7f; + Rect rect2 = detailsRect; + rect2.yMin = rect.yMax; + GUI.DrawTexture(rect, EditWindow_Log.StackTraceBorderTex); + if (Mouse.IsOver(rect)) + { + Widgets.DrawHighlight(rect); + } + if (Event.current.type == EventType.MouseDown && Mouse.IsOver(rect)) + { + this.borderDragging = true; + Event.current.Use(); + } + if (this.borderDragging) + { + float num = outRect.height + Mathf.Round(3.5f); + Vector2 mousePosition = Event.current.mousePosition; + EditWindow_Log.detailsPaneHeight = num - mousePosition.y; + } + if (Event.current.rawType == EventType.MouseUp) + { + this.borderDragging = false; + } + GUI.DrawTexture(rect2, EditWindow_Log.StackTraceAreaTex); + string text = EditWindow_Log.selectedMessage.text + "\n" + EditWindow_Log.selectedMessage.StackTrace; + GUI.SetNextControlName(EditWindow_Log.MessageDetailsControlName); + Widgets.TextAreaScrollable(rect2, text, ref EditWindow_Log.detailsScrollPosition, true); } - GUI.DrawTexture(rect2, EditWindow_Log.StackTraceAreaTex); - string text = EditWindow_Log.selectedMessage.text + "\n" + EditWindow_Log.selectedMessage.StackTrace; - GUI.SetNextControlName(EditWindow_Log.MessageDetailsControlName); - Widgets.TextAreaScrollable(rect2, text, ref EditWindow_Log.detailsScrollPosition, true); } private void CopyAllMessagesToClipboard() { StringBuilder stringBuilder = new StringBuilder(); - foreach (LogMessage current in Log.Messages) + foreach (LogMessage message in Log.Messages) { if (stringBuilder.Length != 0) { stringBuilder.AppendLine(); } - stringBuilder.AppendLine(current.text); - stringBuilder.Append(current.StackTrace); + stringBuilder.AppendLine(message.text); + stringBuilder.Append(message.StackTrace); if (stringBuilder[stringBuilder.Length - 1] != '\n') { stringBuilder.AppendLine(); diff --git a/Assembly-CSharp/Verse/EditWindow_PackageEditor.cs b/Assembly-CSharp/Verse/EditWindow_PackageEditor.cs index abdde0dab..781feaa0e 100644 --- a/Assembly-CSharp/Verse/EditWindow_PackageEditor.cs +++ b/Assembly-CSharp/Verse/EditWindow_PackageEditor.cs @@ -1,4 +1,5 @@ using System; +using System.Collections.Generic; using System.Linq; using UnityEngine; @@ -37,14 +38,14 @@ public override bool IsDebug public EditWindow_PackageEditor(string relFolder) { this.relFolder = relFolder; - this.onlyOneOfTypeAllowed = true; - this.optionalTitle = "Package Editor: " + relFolder; + base.onlyOneOfTypeAllowed = true; + base.optionalTitle = "Package Editor: " + relFolder; } public override void DoWindowContents(Rect selectorInner) { Text.Font = GameFont.Tiny; - float width = (selectorInner.width - 4f) / 2f; + float width = (float)((selectorInner.width - 4.0) / 2.0); Rect rect = new Rect(0f, 0f, width, 24f); string str = this.curMod.ToString(); if (Widgets.ButtonText(rect, "Editing: " + str, true, false, true)) @@ -52,7 +53,7 @@ public override void DoWindowContents(Rect selectorInner) Messages.Message("Mod changing not implemented - it's always Core for now.", MessageSound.RejectInput); } TooltipHandler.TipRegion(rect, "Change the mod being edited."); - Rect rect2 = new Rect(rect.xMax + 4f, 0f, width, 24f); + Rect rect2 = new Rect((float)(rect.xMax + 4.0), 0f, width, 24f); string label = "No package loaded"; if (this.curPackage != null) { @@ -60,7 +61,7 @@ public override void DoWindowContents(Rect selectorInner) } if (Widgets.ButtonText(rect2, label, true, false, true)) { - Find.WindowStack.Add(new Dialog_PackageSelector(delegate(DefPackage pack) + Find.WindowStack.Add(new Dialog_PackageSelector((Action)delegate(DefPackage pack) { if (pack != this.curPackage) { @@ -90,7 +91,7 @@ public override void DoWindowContents(Rect selectorInner) } float num = 56f; Rect rect3 = new Rect(0f, num, selectorInner.width, selectorInner.height - num); - Rect rect4 = new Rect(0f, 0f, rect3.width - 16f, this.viewHeight); + Rect rect4 = new Rect(0f, 0f, (float)(rect3.width - 16.0), this.viewHeight); Widgets.DrawMenuSection(rect3, true); Widgets.BeginScrollView(rect3, ref this.scrollPosition, rect4, true); Rect rect5 = rect4.ContractedBy(4f); @@ -110,43 +111,52 @@ public override void DoWindowContents(Rect selectorInner) } else { - EditWindow_PackageEditor.c__AnonStorey5D6 c__AnonStorey5D = new EditWindow_PackageEditor.c__AnonStorey5D6(); - c__AnonStorey5D.<>f__this = this; - c__AnonStorey5D.deletingDef = null; - foreach (Def def in this.curPackage) + Def deletingDef = null; + List.Enumerator enumerator = this.curPackage.GetEnumerator(); + try { - if (listing_Standard.SelectableDef(def.defName, false, delegate + Def def; + Def deletingDef2; + while (enumerator.MoveNext()) { - c__AnonStorey5D.deletingDef = def; - })) - { - bool flag = false; - WindowStack windowStack = Find.WindowStack; - for (int i = 0; i < windowStack.Count; i++) + def = enumerator.Current; + if (listing_Standard.SelectableDef(def.defName, false, (Action)delegate + { + deletingDef2 = def; + })) { - EditWindow_DefEditor editWindow_DefEditor = windowStack[i] as EditWindow_DefEditor; - if (editWindow_DefEditor != null && editWindow_DefEditor.def == def) + bool flag = false; + WindowStack windowStack = Find.WindowStack; + for (int i = 0; i < windowStack.Count; i++) { - flag = true; + EditWindow_DefEditor editWindow_DefEditor = windowStack[i] as EditWindow_DefEditor; + if (editWindow_DefEditor != null && editWindow_DefEditor.def == def) + { + flag = true; + } + } + if (!flag) + { + Find.WindowStack.Add(new EditWindow_DefEditor(def)); } - } - if (!flag) - { - Find.WindowStack.Add(new EditWindow_DefEditor(def)); } } } - if (c__AnonStorey5D.deletingDef != null) + finally + { + ((IDisposable)(object)enumerator).Dispose(); + } + if (deletingDef != null) { - Find.WindowStack.Add(Dialog_MessageBox.CreateConfirmation("Really delete Def " + c__AnonStorey5D.deletingDef.defName + "?", delegate + Find.WindowStack.Add(Dialog_MessageBox.CreateConfirmation("Really delete Def " + deletingDef.defName + "?", (Action)delegate { - c__AnonStorey5D.<>f__this.curPackage.RemoveDef(c__AnonStorey5D.deletingDef); - }, true, null)); + this.curPackage.RemoveDef(deletingDef); + }, true, (string)null)); } } if (listing_Standard.ButtonImage(TexButton.Add, 24f, 24f)) { - Def def2 = Activator.CreateInstance(); + Def def2 = (Def)(object)new TNewDef(); def2.defName = "New" + typeof(TNewDef).Name; this.curPackage.AddDef(def2); } diff --git a/Assembly-CSharp/Verse/Editable.cs b/Assembly-CSharp/Verse/Editable.cs index 657e936bc..36afca39a 100644 --- a/Assembly-CSharp/Verse/Editable.cs +++ b/Assembly-CSharp/Verse/Editable.cs @@ -1,6 +1,4 @@ -using System; using System.Collections.Generic; -using System.Diagnostics; namespace Verse { @@ -14,13 +12,9 @@ public virtual void PostLoad() { } - [DebuggerHidden] public virtual IEnumerable ConfigErrors() { - Editable.c__Iterator89 c__Iterator = new Editable.c__Iterator89(); - Editable.c__Iterator89 expr_07 = c__Iterator; - expr_07.$PC = -2; - return expr_07; + yield break; } } } diff --git a/Assembly-CSharp/Verse/Effecter.cs b/Assembly-CSharp/Verse/Effecter.cs index 791a3c3c3..a718dff7e 100644 --- a/Assembly-CSharp/Verse/Effecter.cs +++ b/Assembly-CSharp/Verse/Effecter.cs @@ -1,4 +1,3 @@ -using System; using System.Collections.Generic; namespace Verse diff --git a/Assembly-CSharp/Verse/EffecterDef.cs b/Assembly-CSharp/Verse/EffecterDef.cs index 4f49d8c35..9f1d65c38 100644 --- a/Assembly-CSharp/Verse/EffecterDef.cs +++ b/Assembly-CSharp/Verse/EffecterDef.cs @@ -1,4 +1,3 @@ -using System; using System.Collections.Generic; namespace Verse diff --git a/Assembly-CSharp/Verse/EnvironmentInspectDrawer.cs b/Assembly-CSharp/Verse/EnvironmentInspectDrawer.cs index 4a6eaaae4..2c2010fb6 100644 --- a/Assembly-CSharp/Verse/EnvironmentInspectDrawer.cs +++ b/Assembly-CSharp/Verse/EnvironmentInspectDrawer.cs @@ -44,81 +44,86 @@ private static int DisplayedRoomStatsCount private static bool ShouldShow() { - return Find.PlaySettings.showEnvironment && !Mouse.IsInputBlockedNow && UI.MouseCell().InBounds(Find.VisibleMap) && !UI.MouseCell().Fogged(Find.VisibleMap); + if (!Find.PlaySettings.showEnvironment) + { + return false; + } + if (Mouse.IsInputBlockedNow) + { + return false; + } + if (UI.MouseCell().InBounds(Find.VisibleMap) && !UI.MouseCell().Fogged(Find.VisibleMap)) + { + return true; + } + return false; } public static void EnvironmentInspectOnGUI() { - if (Event.current.type != EventType.Repaint || !EnvironmentInspectDrawer.ShouldShow()) + if (Event.current.type == EventType.Repaint && EnvironmentInspectDrawer.ShouldShow()) { - return; + BeautyDrawer.DrawBeautyAroundMouse(); + EnvironmentInspectDrawer.DrawInfoWindow(); } - BeautyDrawer.DrawBeautyAroundMouse(); - EnvironmentInspectDrawer.DrawInfoWindow(); } private static void DrawInfoWindow() { - EnvironmentInspectDrawer.c__AnonStorey5D8 c__AnonStorey5D = new EnvironmentInspectDrawer.c__AnonStorey5D8(); - c__AnonStorey5D.room = UI.MouseCell().GetRoom(Find.VisibleMap, RegionType.Set_All); - c__AnonStorey5D.roomValid = (c__AnonStorey5D.room != null && c__AnonStorey5D.room.Role != RoomRoleDefOf.None); + Room room = UI.MouseCell().GetRoom(Find.VisibleMap, RegionType.Set_All); + bool roomValid = room != null && room.Role != RoomRoleDefOf.None; Text.Font = GameFont.Small; - c__AnonStorey5D.windowRect = new Rect(Event.current.mousePosition.x, Event.current.mousePosition.y, 416f, 36f); - EnvironmentInspectDrawer.c__AnonStorey5D8 expr_8A_cp_0 = c__AnonStorey5D; - expr_8A_cp_0.windowRect.height = expr_8A_cp_0.windowRect.height + 25f; - if (c__AnonStorey5D.roomValid) + Vector2 mousePosition = Event.current.mousePosition; + float x = mousePosition.x; + Vector2 mousePosition2 = Event.current.mousePosition; + Rect windowRect = new Rect(x, mousePosition2.y, 416f, 36f); + windowRect.height += 25f; + if (roomValid) { - EnvironmentInspectDrawer.c__AnonStorey5D8 expr_AC_cp_0 = c__AnonStorey5D; - expr_AC_cp_0.windowRect.height = expr_AC_cp_0.windowRect.height + 13f; - EnvironmentInspectDrawer.c__AnonStorey5D8 expr_C3_cp_0 = c__AnonStorey5D; - expr_C3_cp_0.windowRect.height = expr_C3_cp_0.windowRect.height + 23f; - EnvironmentInspectDrawer.c__AnonStorey5D8 expr_DA_cp_0 = c__AnonStorey5D; - expr_DA_cp_0.windowRect.height = expr_DA_cp_0.windowRect.height + (float)EnvironmentInspectDrawer.DisplayedRoomStatsCount * 25f; + windowRect.height += 13f; + windowRect.height += 23f; + windowRect.height += (float)((float)EnvironmentInspectDrawer.DisplayedRoomStatsCount * 25.0); } - EnvironmentInspectDrawer.c__AnonStorey5D8 expr_F8_cp_0 = c__AnonStorey5D; - expr_F8_cp_0.windowRect.x = expr_F8_cp_0.windowRect.x + 26f; - EnvironmentInspectDrawer.c__AnonStorey5D8 expr_10F_cp_0 = c__AnonStorey5D; - expr_10F_cp_0.windowRect.y = expr_10F_cp_0.windowRect.y + 26f; - if (c__AnonStorey5D.windowRect.xMax > (float)UI.screenWidth) + windowRect.x += 26f; + windowRect.y += 26f; + if (windowRect.xMax > (float)UI.screenWidth) { - EnvironmentInspectDrawer.c__AnonStorey5D8 expr_13C_cp_0 = c__AnonStorey5D; - expr_13C_cp_0.windowRect.x = expr_13C_cp_0.windowRect.x - (c__AnonStorey5D.windowRect.width + 52f); + windowRect.x -= (float)(windowRect.width + 52.0); } - if (c__AnonStorey5D.windowRect.yMax > (float)UI.screenHeight) + if (windowRect.yMax > (float)UI.screenHeight) { - EnvironmentInspectDrawer.c__AnonStorey5D8 expr_175_cp_0 = c__AnonStorey5D; - expr_175_cp_0.windowRect.y = expr_175_cp_0.windowRect.y - (c__AnonStorey5D.windowRect.height + 52f); + windowRect.y -= (float)(windowRect.height + 52.0); } - Find.WindowStack.ImmediateWindow(74975, c__AnonStorey5D.windowRect, WindowLayer.Super, delegate + Find.WindowStack.ImmediateWindow(74975, windowRect, WindowLayer.Super, (Action)delegate { PlayerKnowledgeDatabase.KnowledgeDemonstrated(ConceptDefOf.InspectRoomStats, KnowledgeAmount.FrameDisplayed); Text.Font = GameFont.Small; float num = 18f; float beauty = BeautyUtility.AverageBeautyPerceptible(UI.MouseCell(), Find.VisibleMap); - Rect rect = new Rect(18f, num, c__AnonStorey5D.windowRect.width - 36f, 100f); + Rect rect = new Rect(18f, num, (float)(windowRect.width - 36.0), 100f); GUI.color = BeautyDrawer.BeautyColor(beauty, 40f); Widgets.Label(rect, "BeautyHere".Translate() + ": " + beauty.ToString("F1")); - num += 25f; - if (c__AnonStorey5D.roomValid) + num = (float)(num + 25.0); + if (roomValid) { - num += 5f; + num = (float)(num + 5.0); GUI.color = new Color(1f, 1f, 1f, 0.4f); - Widgets.DrawLineHorizontal(18f, num, c__AnonStorey5D.windowRect.width - 36f); + Widgets.DrawLineHorizontal(18f, num, (float)(windowRect.width - 36.0)); GUI.color = Color.white; - num += 8f; - Rect rect2 = new Rect(18f, num, c__AnonStorey5D.windowRect.width - 36f, 100f); + num = (float)(num + 8.0); + Rect rect2 = new Rect(18f, num, (float)(windowRect.width - 36.0), 100f); GUI.color = Color.white; - Widgets.Label(rect2, EnvironmentInspectDrawer.GetRoomRoleLabel(c__AnonStorey5D.room)); - num += 25f; + Widgets.Label(rect2, EnvironmentInspectDrawer.GetRoomRoleLabel(room)); + num = (float)(num + 25.0); Text.WordWrap = false; for (int i = 0; i < DefDatabase.AllDefsListForReading.Count; i++) { RoomStatDef roomStatDef = DefDatabase.AllDefsListForReading[i]; if (!roomStatDef.isHidden || DebugViewSettings.showAllRoomStats) { - float stat = c__AnonStorey5D.room.GetStat(roomStatDef); + float stat = room.GetStat(roomStatDef); RoomStatScoreStage scoreStage = roomStatDef.GetScoreStage(stat); - if (c__AnonStorey5D.room.Role.IsStatRelated(roomStatDef)) + if (room.Role.IsStatRelated(roomStatDef)) { GUI.color = EnvironmentInspectDrawer.RelatedStatColor; } @@ -128,12 +133,12 @@ private static void DrawInfoWindow() } Rect rect3 = new Rect(rect2.x, num, 100f, 23f); Widgets.Label(rect3, roomStatDef.LabelCap); - Rect rect4 = new Rect(rect3.xMax + 35f, num, 50f, 23f); + Rect rect4 = new Rect((float)(rect3.xMax + 35.0), num, 50f, 23f); string label = roomStatDef.ScoreToString(stat); Widgets.Label(rect4, label); - Rect rect5 = new Rect(rect4.xMax + 35f, num, 160f, 23f); + Rect rect5 = new Rect((float)(rect4.xMax + 35.0), num, 160f, 23f); Widgets.Label(rect5, (scoreStage != null) ? scoreStage.label : string.Empty); - num += 25f; + num = (float)(num + 25.0); } } Text.WordWrap = true; @@ -144,15 +149,14 @@ private static void DrawInfoWindow() public static void DrawRoomOverlays() { - if (!EnvironmentInspectDrawer.ShouldShow()) - { - return; - } - GenUI.RenderMouseoverBracket(); - Room room = UI.MouseCell().GetRoom(Find.VisibleMap, RegionType.Set_All); - if (room != null && room.Role != RoomRoleDefOf.None) + if (EnvironmentInspectDrawer.ShouldShow()) { - room.DrawFieldEdges(); + GenUI.RenderMouseoverBracket(); + Room room = UI.MouseCell().GetRoom(Find.VisibleMap, RegionType.Set_All); + if (room != null && room.Role != RoomRoleDefOf.None) + { + room.DrawFieldEdges(); + } } } @@ -160,40 +164,18 @@ private static string GetRoomRoleLabel(Room room) { Pawn pawn = null; Pawn pawn2 = null; - foreach (Pawn current in room.Owners) + foreach (Pawn owner in room.Owners) { if (pawn == null) { - pawn = current; + pawn = owner; } else { - pawn2 = current; + pawn2 = owner; } } - string result; - if (pawn == null) - { - result = room.Role.LabelCap; - } - else if (pawn2 == null) - { - result = "SomeonesRoom".Translate(new object[] - { - pawn.NameStringShort, - room.Role.label - }); - } - else - { - result = "CouplesRoom".Translate(new object[] - { - pawn.NameStringShort, - pawn2.NameStringShort, - room.Role.label - }); - } - return result; + return (pawn != null) ? ((pawn2 != null) ? "CouplesRoom".Translate(pawn.NameStringShort, pawn2.NameStringShort, room.Role.label) : "SomeonesRoom".Translate(pawn.NameStringShort, room.Role.label)) : room.Role.LabelCap; } } } diff --git a/Assembly-CSharp/Verse/EquipmentType.cs b/Assembly-CSharp/Verse/EquipmentType.cs index c9944f059..c71a6c420 100644 --- a/Assembly-CSharp/Verse/EquipmentType.cs +++ b/Assembly-CSharp/Verse/EquipmentType.cs @@ -1,10 +1,8 @@ -using System; - namespace Verse { public enum EquipmentType : byte { - None, - Primary + None = 0, + Primary = 1 } } diff --git a/Assembly-CSharp/Verse/ExitMapGrid.cs b/Assembly-CSharp/Verse/ExitMapGrid.cs index 27821c75b..06daf2cf1 100644 --- a/Assembly-CSharp/Verse/ExitMapGrid.cs +++ b/Assembly-CSharp/Verse/ExitMapGrid.cs @@ -1,5 +1,4 @@ using RimWorld.Planet; -using System; using UnityEngine; namespace Verse @@ -25,7 +24,11 @@ public bool MapUsesExitGrid return false; } CaravansBattlefield caravansBattlefield = this.map.info.parent as CaravansBattlefield; - return caravansBattlefield == null || !caravansBattlefield.def.blockExitGridUntilBattleIsWon || caravansBattlefield.WonBattle; + if (caravansBattlefield != null && caravansBattlefield.def.blockExitGridUntilBattleIsWon && !caravansBattlefield.WonBattle) + { + return false; + } + return true; } } @@ -43,7 +46,10 @@ public CellBoolDrawer Drawer } if (this.drawerInt == null) { - this.drawerInt = new CellBoolDrawer(this, this.map.Size.x, this.map.Size.z, 0.33f); + IntVec3 size = this.map.Size; + int x = size.x; + IntVec3 size2 = this.map.Size; + this.drawerInt = new CellBoolDrawer(this, x, size2.z, 0.33f); } return this.drawerInt; } @@ -90,17 +96,20 @@ public Color GetCellExtraColor(int index) public bool IsExitCell(IntVec3 c) { - return this.MapUsesExitGrid && this.Grid[c]; + if (!this.MapUsesExitGrid) + { + return false; + } + return this.Grid[c]; } public void ExitMapGridUpdate() { - if (!this.MapUsesExitGrid) + if (this.MapUsesExitGrid) { - return; + this.Drawer.MarkForDraw(); + this.Drawer.CellBoolDrawerUpdate(); } - this.Drawer.MarkForDraw(); - this.Drawer.CellBoolDrawerUpdate(); } public void Notify_LOSBlockerSpawned() @@ -153,9 +162,9 @@ private bool IsGoodExitCell(IntVec3 cell) return false; } int num = GenRadial.NumCellsInRadius(4f); - for (int i = 0; i < num; i++) + for (int num2 = 0; num2 < num; num2++) { - IntVec3 intVec = cell + GenRadial.RadialPattern[i]; + IntVec3 intVec = cell + GenRadial.RadialPattern[num2]; if (intVec.InBounds(this.map) && intVec.OnEdge(this.map) && intVec.CanBeSeenOverFast(this.map) && GenSight.LineOfSight(cell, intVec, this.map, false, null, 0, 0)) { return true; diff --git a/Assembly-CSharp/Verse/Explosion.cs b/Assembly-CSharp/Verse/Explosion.cs index 0d603ef74..6cee2ff99 100644 --- a/Assembly-CSharp/Verse/Explosion.cs +++ b/Assembly-CSharp/Verse/Explosion.cs @@ -71,37 +71,29 @@ public void StartExplosion(SoundDef explosionSound) } this.damType.Worker.ExplosionStart(this, this.cellsToAffect); this.PlayExplosionSound(explosionSound); - MoteMaker.MakeWaterSplash(this.position.ToVector3Shifted(), this.Map, this.radius * 6f, 20f); - this.cellsToAffect.Sort((IntVec3 a, IntVec3 b) => this.GetCellAffectTick(b).CompareTo(this.GetCellAffectTick(a))); + MoteMaker.MakeWaterSplash(this.position.ToVector3Shifted(), this.Map, (float)(this.radius * 6.0), 20f); + this.cellsToAffect.Sort((Comparison)((IntVec3 a, IntVec3 b) => this.GetCellAffectTick(b).CompareTo(this.GetCellAffectTick(a)))); } public void Tick() { int ticksGame = Find.TickManager.TicksGame; int count = this.cellsToAffect.Count; - for (int i = count - 1; i >= 0; i--) + int num = count - 1; + while (num >= 0 && ticksGame >= this.GetCellAffectTick(this.cellsToAffect[num])) { - if (ticksGame < this.GetCellAffectTick(this.cellsToAffect[i])) - { - break; - } try { - this.AffectCell(this.cellsToAffect[i]); + this.AffectCell(this.cellsToAffect[num]); } catch (Exception ex) { - Log.Error(string.Concat(new object[] - { - "Explosion could not affect cell ", - this.cellsToAffect[i], - ": ", - ex - })); + Log.Error("Explosion could not affect cell " + this.cellsToAffect[num] + ": " + ex); } - this.cellsToAffect.RemoveAt(i); + this.cellsToAffect.RemoveAt(num); + num--; } - if (!this.cellsToAffect.Any()) + if (!this.cellsToAffect.Any()) { this.Finished(); } @@ -109,20 +101,19 @@ public void Tick() public void Finished() { - if (this.finished) - { - return; + if (!this.finished) + { + this.cellsToAffect.Clear(); + SimplePool>.Return(this.cellsToAffect); + this.cellsToAffect = null; + this.damagedThings.Clear(); + SimplePool>.Return(this.damagedThings); + this.damagedThings = null; + this.addedCellsAffectedOnlyByDamage.Clear(); + SimplePool>.Return(this.addedCellsAffectedOnlyByDamage); + this.addedCellsAffectedOnlyByDamage = null; + this.finished = true; } - this.cellsToAffect.Clear(); - SimplePool>.Return(this.cellsToAffect); - this.cellsToAffect = null; - this.damagedThings.Clear(); - SimplePool>.Return(this.damagedThings); - this.damagedThings = null; - this.addedCellsAffectedOnlyByDamage.Clear(); - SimplePool>.Return(this.addedCellsAffectedOnlyByDamage); - this.addedCellsAffectedOnlyByDamage = null; - this.finished = true; } public void ExposeData() @@ -147,13 +138,13 @@ public void ExposeData() Scribe_Collections.Look(ref this.addedCellsAffectedOnlyByDamage, "addedCellsAffectedOnlyByDamage", LookMode.Value); if (Scribe.mode == LoadSaveMode.PostLoadInit) { - this.damagedThings.RemoveAll((Thing x) => x == null); + this.damagedThings.RemoveAll((Predicate)((Thing x) => x == null)); } } private int GetCellAffectTick(IntVec3 cell) { - return this.startTick + (int)((cell - this.position).LengthHorizontal * 1.5f); + return this.startTick + (int)((cell - this.position).LengthHorizontal * 1.5); } private void AffectCell(IntVec3 c) @@ -172,34 +163,24 @@ private void AffectCell(IntVec3 c) private void TrySpawnExplosionThing(ThingDef thingDef, IntVec3 c, int count) { - if (thingDef == null) + if (thingDef != null) { - return; - } - if (thingDef.IsFilth) - { - FilthMaker.MakeFilth(c, this.Map, thingDef, count); - } - else - { - Thing thing = ThingMaker.MakeThing(thingDef, null); - thing.stackCount = count; - GenSpawn.Spawn(thing, c, this.Map); + if (thingDef.IsFilth) + { + FilthMaker.MakeFilth(c, this.Map, thingDef, count); + } + else + { + Thing thing = ThingMaker.MakeThing(thingDef, null); + thing.stackCount = count; + GenSpawn.Spawn(thing, c, this.Map); + } } } private void PlayExplosionSound(SoundDef explosionSound) { - bool flag; - if (Prefs.DevMode) - { - flag = (explosionSound != null); - } - else - { - flag = !explosionSound.NullOrUndefined(); - } - if (flag) + if ((!Prefs.DevMode) ? (!explosionSound.NullOrUndefined()) : (explosionSound != null)) { explosionSound.PlayOneShot(new TargetInfo(this.position, this.Map, false)); } @@ -224,28 +205,37 @@ private void AddCellsNeighbors(List cells) for (int k = 0; k < GenAdj.AdjacentCells.Length; k++) { IntVec3 intVec = cells[j] + GenAdj.AdjacentCells[k]; - if (intVec.InBounds(this.Map)) + if (intVec.InBounds(this.Map) && Explosion.tmpCells.Add(intVec)) { - bool flag = Explosion.tmpCells.Add(intVec); - if (flag) - { - this.addedCellsAffectedOnlyByDamage.Add(intVec); - } + this.addedCellsAffectedOnlyByDamage.Add(intVec); } } } } cells.Clear(); - foreach (IntVec3 current in Explosion.tmpCells) + HashSet.Enumerator enumerator = Explosion.tmpCells.GetEnumerator(); + try { - cells.Add(current); + while (enumerator.MoveNext()) + { + IntVec3 current = enumerator.Current; + cells.Add(current); + } + } + finally + { + ((IDisposable)(object)enumerator).Dispose(); } Explosion.tmpCells.Clear(); } private bool ShouldCellBeAffectedOnlyByDamage(IntVec3 c) { - return this.applyDamageToExplosionCellsNeighbors && this.addedCellsAffectedOnlyByDamage.Contains(c); + if (!this.applyDamageToExplosionCellsNeighbors) + { + return false; + } + return this.addedCellsAffectedOnlyByDamage.Contains(c); } } } diff --git a/Assembly-CSharp/Verse/ExplosionManager.cs b/Assembly-CSharp/Verse/ExplosionManager.cs index fc3ae3a9c..60da2fa4c 100644 --- a/Assembly-CSharp/Verse/ExplosionManager.cs +++ b/Assembly-CSharp/Verse/ExplosionManager.cs @@ -43,7 +43,7 @@ public override void MapComponentTick() this.explosions.Remove(this.tmpToTick[i]); } } - this.explosions.RemoveAll((Explosion x) => x.finished); + this.explosions.RemoveAll((Predicate)((Explosion x) => x.finished)); } public void StartExplosion(Explosion explosion, SoundDef explosionSound) diff --git a/Assembly-CSharp/Verse/ExtraMeleeDamage.cs b/Assembly-CSharp/Verse/ExtraMeleeDamage.cs index 8398716ae..27d408840 100644 --- a/Assembly-CSharp/Verse/ExtraMeleeDamage.cs +++ b/Assembly-CSharp/Verse/ExtraMeleeDamage.cs @@ -1,5 +1,3 @@ -using System; - namespace Verse { public class ExtraMeleeDamage diff --git a/Assembly-CSharp/Verse/FadedMaterialPool.cs b/Assembly-CSharp/Verse/FadedMaterialPool.cs index dc69f1911..9535b5886 100644 --- a/Assembly-CSharp/Verse/FadedMaterialPool.cs +++ b/Assembly-CSharp/Verse/FadedMaterialPool.cs @@ -6,7 +6,7 @@ namespace Verse { public static class FadedMaterialPool { - private struct FadedMatRequest : IEquatable + private struct FadedMatRequest : IEquatable { private Material mat; @@ -20,12 +20,16 @@ public FadedMatRequest(Material mat, int alphaIndex) public override bool Equals(object obj) { - return obj != null && obj is FadedMaterialPool.FadedMatRequest && this.Equals((FadedMaterialPool.FadedMatRequest)obj); + if (obj != null && obj is FadedMatRequest) + { + return this.Equals((FadedMatRequest)obj); + } + return false; } - public bool Equals(FadedMaterialPool.FadedMatRequest other) + public bool Equals(FadedMatRequest other) { - return this.mat == other.mat && this.alphaIndex == other.alphaIndex; + return (UnityEngine.Object)this.mat == (UnityEngine.Object)other.mat && this.alphaIndex == other.alphaIndex; } public override int GetHashCode() @@ -33,27 +37,27 @@ public override int GetHashCode() return Gen.HashCombineInt(this.mat.GetHashCode(), this.alphaIndex); } - public static bool operator ==(FadedMaterialPool.FadedMatRequest lhs, FadedMaterialPool.FadedMatRequest rhs) + public static bool operator ==(FadedMatRequest lhs, FadedMatRequest rhs) { return lhs.Equals(rhs); } - public static bool operator !=(FadedMaterialPool.FadedMatRequest lhs, FadedMaterialPool.FadedMatRequest rhs) + public static bool operator !=(FadedMatRequest lhs, FadedMatRequest rhs) { return !(lhs == rhs); } } - private class FadedMatRequestComparer : IEqualityComparer + private class FadedMatRequestComparer : IEqualityComparer { - public static readonly FadedMaterialPool.FadedMatRequestComparer Instance = new FadedMaterialPool.FadedMatRequestComparer(); + public static readonly FadedMatRequestComparer Instance = new FadedMatRequestComparer(); - public bool Equals(FadedMaterialPool.FadedMatRequest x, FadedMaterialPool.FadedMatRequest y) + public bool Equals(FadedMatRequest x, FadedMatRequest y) { return x.Equals(y); } - public int GetHashCode(FadedMaterialPool.FadedMatRequest obj) + public int GetHashCode(FadedMatRequest obj) { return obj.GetHashCode(); } @@ -61,7 +65,7 @@ public int GetHashCode(FadedMaterialPool.FadedMatRequest obj) private const int NumFadeSteps = 30; - private static Dictionary cachedMats = new Dictionary(FadedMaterialPool.FadedMatRequestComparer.Instance); + private static Dictionary cachedMats = new Dictionary(FadedMatRequestComparer.Instance); public static int TotalMaterialCount { @@ -76,39 +80,53 @@ public static int TotalMaterialBytes get { int num = 0; - foreach (KeyValuePair current in FadedMaterialPool.cachedMats) + Dictionary.Enumerator enumerator = FadedMaterialPool.cachedMats.GetEnumerator(); + try + { + while (enumerator.MoveNext()) + { + num += Profiler.GetRuntimeMemorySize(enumerator.Current.Value); + } + return num; + } + finally { - num += Profiler.GetRuntimeMemorySize(current.Value); + ((IDisposable)(object)enumerator).Dispose(); } - return num; } } public static Material FadedVersionOf(Material sourceMat, float alpha) { int num = FadedMaterialPool.IndexFromAlpha(alpha); - if (num == 0) + switch (num) + { + case 0: { return BaseContent.ClearMat; } - if (num == 29) + case 29: { return sourceMat; } - FadedMaterialPool.FadedMatRequest key = new FadedMaterialPool.FadedMatRequest(sourceMat, num); - Material material; - if (!FadedMaterialPool.cachedMats.TryGetValue(key, out material)) + default: { - material = new Material(sourceMat); - material.color = new Color(1f, 1f, 1f, (float)FadedMaterialPool.IndexFromAlpha(alpha) / 30f); - FadedMaterialPool.cachedMats.Add(key, material); + FadedMatRequest key = new FadedMatRequest(sourceMat, num); + Material material = default(Material); + if (!FadedMaterialPool.cachedMats.TryGetValue(key, out material)) + { + material = new Material(sourceMat); + material.color = new Color(1f, 1f, 1f, (float)((float)FadedMaterialPool.IndexFromAlpha(alpha) / 30.0)); + FadedMaterialPool.cachedMats.Add(key, material); + } + return material; + } } - return material; } private static int IndexFromAlpha(float alpha) { - int num = Mathf.FloorToInt(alpha * 30f); + int num = Mathf.FloorToInt((float)(alpha * 30.0)); if (num == 30) { num = 29; diff --git a/Assembly-CSharp/Verse/FailMode.cs b/Assembly-CSharp/Verse/FailMode.cs index 9e61b7e6b..ecd7b0c33 100644 --- a/Assembly-CSharp/Verse/FailMode.cs +++ b/Assembly-CSharp/Verse/FailMode.cs @@ -1,10 +1,8 @@ -using System; - namespace Verse { public enum FailMode : byte { - Silent, - LogErrors + Silent = 0, + LogErrors = 1 } } diff --git a/Assembly-CSharp/Verse/FastEntityTypeComparer.cs b/Assembly-CSharp/Verse/FastEntityTypeComparer.cs index 4e78fd6ae..4ad8e68fd 100644 --- a/Assembly-CSharp/Verse/FastEntityTypeComparer.cs +++ b/Assembly-CSharp/Verse/FastEntityTypeComparer.cs @@ -1,4 +1,3 @@ -using System; using System.Collections.Generic; namespace Verse diff --git a/Assembly-CSharp/Verse/FastPawnCapacityDefComparer.cs b/Assembly-CSharp/Verse/FastPawnCapacityDefComparer.cs index 24ffb2b83..931b2a809 100644 --- a/Assembly-CSharp/Verse/FastPawnCapacityDefComparer.cs +++ b/Assembly-CSharp/Verse/FastPawnCapacityDefComparer.cs @@ -1,4 +1,3 @@ -using System; using System.Collections.Generic; namespace Verse diff --git a/Assembly-CSharp/Verse/FastPriorityQueue.cs b/Assembly-CSharp/Verse/FastPriorityQueue.cs index bd2a24081..727dccb85 100644 --- a/Assembly-CSharp/Verse/FastPriorityQueue.cs +++ b/Assembly-CSharp/Verse/FastPriorityQueue.cs @@ -1,4 +1,3 @@ -using System; using System.Collections.Generic; namespace Verse @@ -35,9 +34,7 @@ public void Push(T item) { int num2 = (num - 1) / 2; if (this.CompareElements(num, num2) >= 0) - { break; - } this.SwapElements(num, num2); num = num2; } @@ -64,11 +61,12 @@ public T Pop() { num = num4; } - if (num == num2) + if (num != num2) { - break; + this.SwapElements(num, num2); + continue; } - this.SwapElements(num, num2); + break; } return result; } diff --git a/Assembly-CSharp/Verse/FastVector2Comparer.cs b/Assembly-CSharp/Verse/FastVector2Comparer.cs index 163faf58c..622e5913a 100644 --- a/Assembly-CSharp/Verse/FastVector2Comparer.cs +++ b/Assembly-CSharp/Verse/FastVector2Comparer.cs @@ -1,4 +1,3 @@ -using System; using System.Collections.Generic; using UnityEngine; diff --git a/Assembly-CSharp/Verse/Favorability.cs b/Assembly-CSharp/Verse/Favorability.cs index 5ac8a1916..9af37d7cc 100644 --- a/Assembly-CSharp/Verse/Favorability.cs +++ b/Assembly-CSharp/Verse/Favorability.cs @@ -1,13 +1,11 @@ -using System; - namespace Verse { public enum Favorability : byte { - VeryBad, - Bad, - Neutral, - Good, - VeryGood + VeryBad = 0, + Bad = 1, + Neutral = 2, + Good = 3, + VeryGood = 4 } } diff --git a/Assembly-CSharp/Verse/FeedbackFloaters.cs b/Assembly-CSharp/Verse/FeedbackFloaters.cs index 01f09ed7d..2f2e56eea 100644 --- a/Assembly-CSharp/Verse/FeedbackFloaters.cs +++ b/Assembly-CSharp/Verse/FeedbackFloaters.cs @@ -14,21 +14,30 @@ public void AddFeedback(FeedbackItem newFeedback) public void FeedbackUpdate() { - for (int i = this.feeders.Count - 1; i >= 0; i--) + for (int num = this.feeders.Count - 1; num >= 0; num--) { - this.feeders[i].Update(); - if (this.feeders[i].TimeLeft <= 0f) + this.feeders[num].Update(); + if (this.feeders[num].TimeLeft <= 0.0) { - this.feeders.Remove(this.feeders[i]); + this.feeders.Remove(this.feeders[num]); } } } public void FeedbackOnGUI() { - foreach (FeedbackItem current in this.feeders) + List.Enumerator enumerator = this.feeders.GetEnumerator(); + try { - current.FeedbackOnGUI(); + while (enumerator.MoveNext()) + { + FeedbackItem current = enumerator.Current; + current.FeedbackOnGUI(); + } + } + finally + { + ((IDisposable)(object)enumerator).Dispose(); } } } diff --git a/Assembly-CSharp/Verse/FeedbackItem.cs b/Assembly-CSharp/Verse/FeedbackItem.cs index 888f59038..d6cd0dea3 100644 --- a/Assembly-CSharp/Verse/FeedbackItem.cs +++ b/Assembly-CSharp/Verse/FeedbackItem.cs @@ -19,7 +19,7 @@ public FeedbackItem(Vector2 ScreenPos) { this.uniqueID = FeedbackItem.freeUniqueID++; this.CurScreenPos = ScreenPos; - this.CurScreenPos.y = this.CurScreenPos.y - 15f; + this.CurScreenPos.y -= 15f; } public void Update() @@ -32,9 +32,10 @@ public void Update() protected void DrawFloatingText(string str, Color TextColor) { - float x = Text.CalcSize(str).x; - Rect wordRect = new Rect(this.CurScreenPos.x - x / 2f, this.CurScreenPos.y, x, 20f); - Find.WindowStack.ImmediateWindow(5983 * this.uniqueID + 495, wordRect, WindowLayer.Super, delegate + Vector2 vector = Text.CalcSize(str); + float x = vector.x; + Rect wordRect = new Rect((float)(this.CurScreenPos.x - x / 2.0), this.CurScreenPos.y, x, 20f); + Find.WindowStack.ImmediateWindow(5983 * this.uniqueID + 495, wordRect, WindowLayer.Super, (Action)delegate() { Rect rect = wordRect.AtZero(); Text.Anchor = TextAnchor.UpperCenter; diff --git a/Assembly-CSharp/Verse/FeedbackItem_FoodGain.cs b/Assembly-CSharp/Verse/FeedbackItem_FoodGain.cs index d18b0594a..600bb3472 100644 --- a/Assembly-CSharp/Verse/FeedbackItem_FoodGain.cs +++ b/Assembly-CSharp/Verse/FeedbackItem_FoodGain.cs @@ -1,4 +1,3 @@ -using System; using UnityEngine; namespace Verse diff --git a/Assembly-CSharp/Verse/FeedbackItem_HealthGain.cs b/Assembly-CSharp/Verse/FeedbackItem_HealthGain.cs index 105602665..e66ed907b 100644 --- a/Assembly-CSharp/Verse/FeedbackItem_HealthGain.cs +++ b/Assembly-CSharp/Verse/FeedbackItem_HealthGain.cs @@ -1,4 +1,3 @@ -using System; using UnityEngine; namespace Verse @@ -17,17 +16,10 @@ public FeedbackItem_HealthGain(Vector2 ScreenPos, int Amount, Pawn Healer) : bas public override void FeedbackOnGUI() { - string text = string.Empty; - if (this.Amount >= 0) - { - text = "+"; - } - else - { - text = "-"; - } - text += this.Amount; - base.DrawFloatingText(text, Color.red); + string empty = string.Empty; + empty = ((this.Amount < 0) ? "-" : "+"); + empty += this.Amount; + base.DrawFloatingText(empty, Color.red); } } } diff --git a/Assembly-CSharp/Verse/FillCategory.cs b/Assembly-CSharp/Verse/FillCategory.cs index 4fc70568a..675af97ec 100644 --- a/Assembly-CSharp/Verse/FillCategory.cs +++ b/Assembly-CSharp/Verse/FillCategory.cs @@ -1,11 +1,9 @@ -using System; - namespace Verse { public enum FillCategory : byte { - None, - Partial, - Full + None = 0, + Partial = 1, + Full = 2 } } diff --git a/Assembly-CSharp/Verse/Find.cs b/Assembly-CSharp/Verse/Find.cs index 773532933..615a19728 100644 --- a/Assembly-CSharp/Verse/Find.cs +++ b/Assembly-CSharp/Verse/Find.cs @@ -1,6 +1,5 @@ using RimWorld; using RimWorld.Planet; -using System; using System.Collections.Generic; using UnityEngine; using UnityStandardAssets.ImageEffects; diff --git a/Assembly-CSharp/Verse/FloatMenu.cs b/Assembly-CSharp/Verse/FloatMenu.cs index e5f8a59e9..a1b8ce947 100644 --- a/Assembly-CSharp/Verse/FloatMenu.cs +++ b/Assembly-CSharp/Verse/FloatMenu.cs @@ -57,7 +57,7 @@ private float MaxWindowHeight { get { - return (float)UI.screenHeight * 0.9f; + return (float)((float)UI.screenHeight * 0.89999997615814209); } } @@ -65,7 +65,7 @@ private float TotalWindowHeight { get { - return Mathf.Min(this.TotalViewHeight, this.MaxWindowHeight) + 1f; + return (float)(Mathf.Min(this.TotalViewHeight, this.MaxWindowHeight) + 1.0); } } @@ -84,7 +84,7 @@ private float MaxViewHeight { num = requiredHeight; } - num2 += requiredHeight + -1f; + num2 = (float)(num2 + (requiredHeight + -1.0)); } int columnCount = this.ColumnCount; num2 += (float)columnCount * num; @@ -104,7 +104,7 @@ private float TotalViewHeight for (int i = 0; i < this.options.Count; i++) { float requiredHeight = this.options[i].RequiredHeight; - if (num2 + requiredHeight + -1f > maxViewHeight) + if (num2 + requiredHeight + -1.0 > maxViewHeight) { if (num2 > num) { @@ -114,7 +114,7 @@ private float TotalViewHeight } else { - num2 += requiredHeight + -1f; + num2 = (float)(num2 + (requiredHeight + -1.0)); } } return Mathf.Max(num, num2); @@ -128,7 +128,7 @@ private float TotalWidth float num = (float)this.ColumnCount * this.ColumnWidth; if (this.UsingScrollbar) { - num += 16f; + num = (float)(num + 16.0); } return num; } @@ -142,7 +142,7 @@ private float ColumnWidth for (int i = 0; i < this.options.Count; i++) { float requiredWidth = this.options[i].RequiredWidth; - if (requiredWidth >= 300f) + if (requiredWidth >= 300.0) { return 300f; } @@ -159,7 +159,7 @@ private int MaxColumns { get { - return Mathf.FloorToInt(((float)UI.screenWidth - 16f) / this.ColumnWidth); + return Mathf.FloorToInt((float)(((float)UI.screenWidth - 16.0) / this.ColumnWidth)); } } @@ -194,14 +194,14 @@ private int ColumnCountIfNoScrollbar for (int i = 0; i < this.options.Count; i++) { float requiredHeight = this.options[i].RequiredHeight; - if (num2 + requiredHeight + -1f > maxWindowHeight) + if (num2 + requiredHeight + -1.0 > maxWindowHeight) { num2 = requiredHeight; num++; } else { - num2 += requiredHeight + -1f; + num2 = (float)(num2 + (requiredHeight + -1.0)); } } return num; @@ -222,7 +222,7 @@ public FloatMenuSizeMode SizeMode public FloatMenu(List options) { - if (options.NullOrEmpty()) + if (options.NullOrEmpty()) { Log.Error("Created FloatMenu with no options. Closing."); this.Close(true); @@ -232,10 +232,10 @@ public FloatMenu(List options) { options[i].SetSizeMode(this.SizeMode); } - this.layer = WindowLayer.Super; - this.closeOnClickedOutside = true; - this.doWindowBackground = false; - this.drawShadow = false; + base.layer = WindowLayer.Super; + base.closeOnClickedOutside = true; + base.doWindowBackground = false; + base.drawShadow = false; SoundDefOf.FloatMenuOpen.PlayOneShotOnCamera(null); } @@ -248,15 +248,28 @@ public FloatMenu(List options, string title, bool needSelection protected override void SetInitialSizeAndPosition() { Vector2 vector = UI.MousePositionOnUIInverted + FloatMenu.InitialPositionShift; - if (vector.x + this.InitialSize.x > (float)UI.screenWidth) + float x = vector.x; + Vector2 initialSize = this.InitialSize; + if (x + initialSize.x > (float)UI.screenWidth) { - vector.x = (float)UI.screenWidth - this.InitialSize.x; + float num = (float)UI.screenWidth; + Vector2 initialSize2 = this.InitialSize; + vector.x = num - initialSize2.x; } - if (vector.y + this.InitialSize.y > (float)UI.screenHeight) + float y = vector.y; + Vector2 initialSize3 = this.InitialSize; + if (y + initialSize3.y > (float)UI.screenHeight) { - vector.y = (float)UI.screenHeight - this.InitialSize.y; + float num2 = (float)UI.screenHeight; + Vector2 initialSize4 = this.InitialSize; + vector.y = num2 - initialSize4.y; } - this.windowRect = new Rect(vector.x, vector.y, this.InitialSize.x, this.InitialSize.y); + float x2 = vector.x; + float y2 = vector.y; + Vector2 initialSize5 = this.InitialSize; + float x3 = initialSize5.x; + Vector2 initialSize6 = this.InitialSize; + base.windowRect = new Rect(x2, y2, x3, initialSize6.y); } public override void ExtraOnGUI() @@ -264,11 +277,17 @@ public override void ExtraOnGUI() base.ExtraOnGUI(); if (!this.title.NullOrEmpty()) { - Vector2 vector = new Vector2(this.windowRect.x, this.windowRect.y); + Vector2 vector = new Vector2(base.windowRect.x, base.windowRect.y); Text.Font = GameFont.Small; - float width = Mathf.Max(150f, 15f + Text.CalcSize(this.title).x); - Rect titleRect = new Rect(vector.x + FloatMenu.TitleOffset.x, vector.y + FloatMenu.TitleOffset.y, width, 23f); - Find.WindowStack.ImmediateWindow(6830963, titleRect, WindowLayer.Super, delegate + Vector2 vector2 = Text.CalcSize(this.title); + float width = Mathf.Max(150f, (float)(15.0 + vector2.x)); + float x = vector.x; + Vector2 titleOffset = FloatMenu.TitleOffset; + float x2 = x + titleOffset.x; + float y = vector.y; + Vector2 titleOffset2 = FloatMenu.TitleOffset; + Rect titleRect = new Rect(x2, y + titleOffset2.y, width, 23f); + Find.WindowStack.ImmediateWindow(6830963, titleRect, WindowLayer.Super, (Action)delegate { GUI.color = this.baseColor; Text.Font = GameFont.Small; @@ -289,49 +308,50 @@ public override void DoWindowContents(Rect rect) if (this.needSelection && Find.Selector.SingleSelectedThing == null) { Find.WindowStack.TryRemove(this, true); - return; } - this.UpdateBaseColor(); - bool usingScrollbar = this.UsingScrollbar; - GUI.color = this.baseColor; - Text.Font = GameFont.Small; - Vector2 zero = Vector2.zero; - float maxViewHeight = this.MaxViewHeight; - float columnWidth = this.ColumnWidth; - if (usingScrollbar) + else { - rect.width -= 10f; - Widgets.BeginScrollView(rect, ref this.scrollPosition, new Rect(0f, 0f, this.TotalWidth - 16f, this.TotalViewHeight), true); - } - foreach (FloatMenuOption current in from op in this.options - orderby op.Priority descending - select op) - { - float requiredHeight = current.RequiredHeight; - if (zero.y + requiredHeight + -1f > maxViewHeight) + this.UpdateBaseColor(); + bool usingScrollbar = this.UsingScrollbar; + GUI.color = this.baseColor; + Text.Font = GameFont.Small; + Vector2 zero = Vector2.zero; + float maxViewHeight = this.MaxViewHeight; + float columnWidth = this.ColumnWidth; + if (usingScrollbar) { - zero.y = 0f; - zero.x += columnWidth + -1f; + rect.width -= 10f; + Widgets.BeginScrollView(rect, ref this.scrollPosition, new Rect(0f, 0f, (float)(this.TotalWidth - 16.0), this.TotalViewHeight), true); } - Rect rect2 = new Rect(zero.x, zero.y, columnWidth, requiredHeight); - zero.y += requiredHeight + -1f; - bool flag = current.DoGUI(rect2, this.givesColonistOrders); - if (flag) + foreach (FloatMenuOption item in from op in this.options + orderby op.Priority descending + select op) { - Find.WindowStack.TryRemove(this, true); - break; + float requiredHeight = item.RequiredHeight; + if (zero.y + requiredHeight + -1.0 > maxViewHeight) + { + zero.y = 0f; + zero.x += (float)(columnWidth + -1.0); + } + Rect rect2 = new Rect(zero.x, zero.y, columnWidth, requiredHeight); + zero.y += (float)(requiredHeight + -1.0); + if (item.DoGUI(rect2, this.givesColonistOrders)) + { + Find.WindowStack.TryRemove(this, true); + break; + } } + if (usingScrollbar) + { + Widgets.EndScrollView(); + } + if (Event.current.type == EventType.MouseDown) + { + Event.current.Use(); + this.Close(true); + } + GUI.color = Color.white; } - if (usingScrollbar) - { - Widgets.EndScrollView(); - } - if (Event.current.type == EventType.MouseDown) - { - Event.current.Use(); - this.Close(true); - } - GUI.color = Color.white; } public void Cancel() @@ -349,12 +369,11 @@ private void UpdateBaseColor() if (!r.Contains(Event.current.mousePosition)) { float num = GenUI.DistFromRect(r, Event.current.mousePosition); - this.baseColor = new Color(1f, 1f, 1f, 1f - num / 95f); - if (num > 95f) + this.baseColor = new Color(1f, 1f, 1f, (float)(1.0 - num / 95.0)); + if (num > 95.0) { this.Close(false); this.Cancel(); - return; } } } diff --git a/Assembly-CSharp/Verse/FloatMenuMap.cs b/Assembly-CSharp/Verse/FloatMenuMap.cs index a03b63693..1b74e3c8f 100644 --- a/Assembly-CSharp/Verse/FloatMenuMap.cs +++ b/Assembly-CSharp/Verse/FloatMenuMap.cs @@ -1,5 +1,4 @@ using RimWorld; -using System; using System.Collections.Generic; using UnityEngine; @@ -20,17 +19,19 @@ public override void DoWindowContents(Rect inRect) if (pawn == null) { Find.WindowStack.TryRemove(this, true); - return; } - List curOpts = FloatMenuMakerMap.ChoicesAtFor(this.clickPos, pawn); - for (int i = 0; i < this.options.Count; i++) + else { - if (!this.options[i].Disabled && !FloatMenuMap.StillValid(this.options[i], curOpts)) + List curOpts = FloatMenuMakerMap.ChoicesAtFor(this.clickPos, pawn); + for (int i = 0; i < base.options.Count; i++) { - this.options[i].Disabled = true; + if (!base.options[i].Disabled && !FloatMenuMap.StillValid(base.options[i], curOpts)) + { + base.options[i].Disabled = true; + } } + base.DoWindowContents(inRect); } - base.DoWindowContents(inRect); } private static bool StillValid(FloatMenuOption opt, List curOpts) @@ -65,7 +66,11 @@ private static bool StillValid(FloatMenuOption opt, List curOpt private static bool OptionsMatch(FloatMenuOption a, FloatMenuOption b) { - return a.Label == b.Label; + if (a.Label == b.Label) + { + return true; + } + return false; } } } diff --git a/Assembly-CSharp/Verse/FloatMenuOption.cs b/Assembly-CSharp/Verse/FloatMenuOption.cs index d997320d7..1a28f4048 100644 --- a/Assembly-CSharp/Verse/FloatMenuOption.cs +++ b/Assembly-CSharp/Verse/FloatMenuOption.cs @@ -48,15 +48,15 @@ public class FloatMenuOption private float cachedRequiredWidth; - private static readonly Color ColorBGActive; + private static readonly Color ColorBGActive = new ColorInt(21, 25, 29).ToColor; - private static readonly Color ColorBGActiveMouseover; + private static readonly Color ColorBGActiveMouseover = new ColorInt(29, 45, 50).ToColor; - private static readonly Color ColorBGDisabled; + private static readonly Color ColorBGDisabled = new ColorInt(40, 40, 40).ToColor; - private static readonly Color ColorTextActive; + private static readonly Color ColorTextActive = Color.white; - private static readonly Color ColorTextDisabled; + private static readonly Color ColorTextDisabled = new Color(0.9f, 0.9f, 0.9f); public string Label { @@ -70,7 +70,7 @@ public string Label { value = "(missing label)"; } - this.labelInt = value.TrimEnd(new char[0]); + this.labelInt = value.TrimEnd(); this.SetSizeMode(this.sizeMode); } } @@ -79,7 +79,7 @@ private float VerticalMargin { get { - return (this.sizeMode != FloatMenuSizeMode.Normal) ? 1f : 4f; + return (float)((this.sizeMode != FloatMenuSizeMode.Normal) ? 1.0 : 4.0); } } @@ -87,7 +87,7 @@ private float HorizontalMargin { get { - return (this.sizeMode != FloatMenuSizeMode.Normal) ? 3f : 6f; + return (float)((this.sizeMode != FloatMenuSizeMode.Normal) ? 3.0 : 6.0); } } @@ -95,7 +95,7 @@ private GameFont CurrentFont { get { - return (this.sizeMode != FloatMenuSizeMode.Normal) ? GameFont.Tiny : GameFont.Small; + return (GameFont)((this.sizeMode == FloatMenuSizeMode.Normal) ? 1 : 0); } } @@ -103,7 +103,7 @@ public bool Disabled { get { - return this.action == null; + return (object)this.action == null; } set { @@ -167,33 +167,22 @@ public FloatMenuOption(string label, Action action, MenuOptionPriority priority this.revalidateWorldClickTarget = revalidateWorldClickTarget; } - static FloatMenuOption() - { - // Note: this type is marked as 'beforefieldinit'. - ColorInt colorInt = new ColorInt(21, 25, 29); - FloatMenuOption.ColorBGActive = colorInt.ToColor; - ColorInt colorInt2 = new ColorInt(29, 45, 50); - FloatMenuOption.ColorBGActiveMouseover = colorInt2.ToColor; - ColorInt colorInt3 = new ColorInt(40, 40, 40); - FloatMenuOption.ColorBGDisabled = colorInt3.ToColor; - FloatMenuOption.ColorTextActive = Color.white; - FloatMenuOption.ColorTextDisabled = new Color(0.9f, 0.9f, 0.9f); - } - public void SetSizeMode(FloatMenuSizeMode newSizeMode) { this.sizeMode = newSizeMode; Text.Font = this.CurrentFont; - float width = 300f - (2f * this.HorizontalMargin + 4f + this.extraPartWidth); - this.cachedRequiredHeight = 2f * this.VerticalMargin + Text.CalcHeight(this.Label, width); - this.cachedRequiredWidth = this.HorizontalMargin + 4f + Text.CalcSize(this.Label).x + this.extraPartWidth + this.HorizontalMargin; + float width = (float)(300.0 - (2.0 * this.HorizontalMargin + 4.0 + this.extraPartWidth)); + this.cachedRequiredHeight = (float)(2.0 * this.VerticalMargin + Text.CalcHeight(this.Label, width)); + double num = this.HorizontalMargin + 4.0; + Vector2 vector = Text.CalcSize(this.Label); + this.cachedRequiredWidth = (float)(num + vector.x + this.extraPartWidth + this.HorizontalMargin); } public void Chosen(bool colonistOrdering) { if (!this.Disabled) { - if (this.action != null) + if ((object)this.action != null) { if (colonistOrdering) { @@ -223,9 +212,10 @@ public virtual bool DoGUI(Rect rect, bool colonistOrdering) rect2.x += 4f; } Rect rect3 = default(Rect); - if (this.extraPartWidth != 0f) + if (this.extraPartWidth != 0.0) { - float num = Mathf.Min(Text.CalcSize(this.Label).x, rect2.width - 4f); + Vector2 vector = Text.CalcSize(this.Label); + float num = Mathf.Min(vector.x, (float)(rect2.width - 4.0)); rect3 = new Rect(rect2.xMin + num, rect2.yMin, this.extraPartWidth, 30f); flag2 = Mouse.IsOver(rect3); } @@ -257,7 +247,7 @@ public virtual bool DoGUI(Rect rect, bool colonistOrdering) Widgets.Label(rect2, this.Label); Text.Anchor = TextAnchor.UpperLeft; GUI.color = color; - if (this.extraPartOnGUI != null) + if ((object)this.extraPartOnGUI != null) { bool flag3 = this.extraPartOnGUI(rect3); GUI.color = color; @@ -266,7 +256,7 @@ public virtual bool DoGUI(Rect rect, bool colonistOrdering) return true; } } - if (flag && this.mouseoverGuiAction != null) + if (flag && (object)this.mouseoverGuiAction != null) { this.mouseoverGuiAction(); } @@ -274,20 +264,20 @@ public virtual bool DoGUI(Rect rect, bool colonistOrdering) { UIHighlighter.HighlightOpportunity(rect, this.tutorTag); } - if (!Widgets.ButtonInvisible(rect, false)) - { - return false; - } - if (this.tutorTag != null && !TutorSystem.AllowAction(this.tutorTag)) - { - return false; - } - this.Chosen(colonistOrdering); - if (this.tutorTag != null) + if (Widgets.ButtonInvisible(rect, false)) { - TutorSystem.Notify_Event(this.tutorTag); + if (this.tutorTag != null && !TutorSystem.AllowAction(this.tutorTag)) + { + return false; + } + this.Chosen(colonistOrdering); + if (this.tutorTag != null) + { + TutorSystem.Notify_Event(this.tutorTag); + } + return true; } - return true; + return false; } public override string ToString() diff --git a/Assembly-CSharp/Verse/FloatMenuSizeMode.cs b/Assembly-CSharp/Verse/FloatMenuSizeMode.cs index 51147f2b5..16f9edce2 100644 --- a/Assembly-CSharp/Verse/FloatMenuSizeMode.cs +++ b/Assembly-CSharp/Verse/FloatMenuSizeMode.cs @@ -1,11 +1,9 @@ -using System; - namespace Verse { public enum FloatMenuSizeMode { - Undefined, - Normal, - Tiny + Undefined = 0, + Normal = 1, + Tiny = 2 } } diff --git a/Assembly-CSharp/Verse/FloatMenuWorld.cs b/Assembly-CSharp/Verse/FloatMenuWorld.cs index a466a127c..46e65799b 100644 --- a/Assembly-CSharp/Verse/FloatMenuWorld.cs +++ b/Assembly-CSharp/Verse/FloatMenuWorld.cs @@ -1,5 +1,4 @@ using RimWorld.Planet; -using System; using System.Collections.Generic; using UnityEngine; @@ -20,17 +19,19 @@ public override void DoWindowContents(Rect inRect) if (caravan == null) { Find.WindowStack.TryRemove(this, true); - return; } - List curOpts = FloatMenuMakerWorld.ChoicesAtFor(this.clickPos, caravan); - for (int i = 0; i < this.options.Count; i++) + else { - if (!this.options[i].Disabled && !FloatMenuWorld.StillValid(this.options[i], curOpts)) + List curOpts = FloatMenuMakerWorld.ChoicesAtFor(this.clickPos, caravan); + for (int i = 0; i < base.options.Count; i++) { - this.options[i].Disabled = true; + if (!base.options[i].Disabled && !FloatMenuWorld.StillValid(base.options[i], curOpts)) + { + base.options[i].Disabled = true; + } } + base.DoWindowContents(inRect); } - base.DoWindowContents(inRect); } private static bool StillValid(FloatMenuOption opt, List curOpts) @@ -67,7 +68,11 @@ private static bool StillValid(FloatMenuOption opt, List curOpt private static bool OptionsMatch(FloatMenuOption a, FloatMenuOption b) { - return a.Label == b.Label; + if (a.Label == b.Label) + { + return true; + } + return false; } } } diff --git a/Assembly-CSharp/Verse/FloatRange.cs b/Assembly-CSharp/Verse/FloatRange.cs index 4cc355d4e..254154ee6 100644 --- a/Assembly-CSharp/Verse/FloatRange.cs +++ b/Assembly-CSharp/Verse/FloatRange.cs @@ -37,7 +37,7 @@ public float Average { get { - return (this.min + this.max) / 2f; + return (float)((this.min + this.max) / 2.0); } } @@ -81,7 +81,7 @@ public FloatRange(float min, float max) public float LerpThroughRange(float lerpPct) { - return (1f - lerpPct) * this.min + lerpPct * this.max; + return (float)((1.0 - lerpPct) * this.min + lerpPct * this.max); } public float InverseLerpThroughRange(float f) @@ -96,7 +96,7 @@ public bool Includes(float f) public bool IncludesEpsilon(float f) { - return f >= this.min - 1E-05f && f <= this.max + 1E-05f; + return f >= this.min - 9.9999997473787516E-06 && f <= this.max + 9.9999997473787516E-06; } public FloatRange ExpandedBy(float f) @@ -106,10 +106,7 @@ public FloatRange ExpandedBy(float f) public static FloatRange FromString(string s) { - string[] array = s.Split(new char[] - { - '~' - }); + string[] array = s.Split('~'); if (array.Length == 1) { float num = Convert.ToSingle(array[0]); @@ -125,12 +122,16 @@ public override string ToString() public override int GetHashCode() { - return Gen.HashCombineStruct(this.min.GetHashCode(), this.max); + return Gen.HashCombineStruct(this.min.GetHashCode(), this.max); } public override bool Equals(object obj) { - return obj is FloatRange && this.Equals((FloatRange)obj); + if (!(obj is FloatRange)) + { + return false; + } + return this.Equals((FloatRange)obj); } public bool Equals(FloatRange other) diff --git a/Assembly-CSharp/Verse/FloodFillRange.cs b/Assembly-CSharp/Verse/FloodFillRange.cs index d6a189404..b12e1cc95 100644 --- a/Assembly-CSharp/Verse/FloodFillRange.cs +++ b/Assembly-CSharp/Verse/FloodFillRange.cs @@ -1,5 +1,3 @@ -using System; - namespace Verse { public struct FloodFillRange diff --git a/Assembly-CSharp/Verse/FloodFillRangeQueue.cs b/Assembly-CSharp/Verse/FloodFillRangeQueue.cs index 57aabb0d5..773008c9c 100644 --- a/Assembly-CSharp/Verse/FloodFillRangeQueue.cs +++ b/Assembly-CSharp/Verse/FloodFillRangeQueue.cs @@ -34,17 +34,7 @@ public string PerfDebugString { get { - return string.Concat(new object[] - { - "NumTimesExpanded: ", - this.debugNumTimesExpanded, - ", MaxUsedSize= ", - this.debugMaxUsedSpace, - ", ClaimedSize=", - this.array.Length, - ", UnusedSpace=", - this.array.Length - this.debugMaxUsedSpace - }); + return "NumTimesExpanded: " + this.debugNumTimesExpanded + ", MaxUsedSize= " + this.debugMaxUsedSpace + ", ClaimedSize=" + this.array.Length + ", UnusedSpace=" + (this.array.Length - this.debugMaxUsedSpace); } } @@ -65,7 +55,12 @@ public void Enqueue(FloodFillRange r) this.head = 0; this.debugNumTimesExpanded++; } - this.array[this.head + this.count++] = r; + FloodFillRange[] obj = this.array; + int num = this.head; + int num2 = this.count; + int num3 = num2; + this.count = num2 + 1; + obj[num + num3] = r; this.debugMaxUsedSpace = this.count + this.head; } diff --git a/Assembly-CSharp/Verse/FloodFiller.cs b/Assembly-CSharp/Verse/FloodFiller.cs index 9f759cb97..f28a16ece 100644 --- a/Assembly-CSharp/Verse/FloodFiller.cs +++ b/Assembly-CSharp/Verse/FloodFiller.cs @@ -23,7 +23,7 @@ public FloodFiller(Map map) public void FloodFill(IntVec3 root, Predicate passCheck, Action processor, bool rememberParents = false) { - this.FloodFill(root, passCheck, delegate(IntVec3 x) + this.FloodFill(root, passCheck, (Func)delegate(IntVec3 x) { processor(x); return false; @@ -45,100 +45,99 @@ public void FloodFill(IntVec3 root, Predicate passCheck, Func 0) - { - IntVec3 intVec = this.openSet.Dequeue(); - if (processor(intVec)) + int area = this.map.Area; + IntVec3[] cardinalDirectionsAround = GenAdj.CardinalDirectionsAround; + int num = cardinalDirectionsAround.Length; + CellIndices cellIndices = this.map.cellIndices; + int num2 = cellIndices.CellToIndex(root); + this.visited.Add(num2); + this.queuedGrid.Set(num2, true); + if (rememberParents) { - break; + this.parentGrid[num2] = root; } - for (int i = 0; i < num; i++) + this.openSet.Clear(); + this.openSet.Enqueue(root); + while (this.openSet.Count > 0) { - IntVec3 intVec2 = intVec + cardinalDirectionsAround[i]; - int num3 = cellIndices.CellToIndex(intVec2); - if (intVec2.InBounds(this.map) && !this.queuedGrid[num3] && passCheck(intVec2)) + IntVec3 intVec = this.openSet.Dequeue(); + if (!processor(intVec)) { - this.visited.Add(num3); - this.openSet.Enqueue(intVec2); - this.queuedGrid.Set(num3, true); - if (rememberParents) + for (int num3 = 0; num3 < num; num3++) + { + IntVec3 intVec2 = intVec + cardinalDirectionsAround[num3]; + int num4 = cellIndices.CellToIndex(intVec2); + if (intVec2.InBounds(this.map) && !this.queuedGrid[num4] && passCheck(intVec2)) + { + this.visited.Add(num4); + this.openSet.Enqueue(intVec2); + this.queuedGrid.Set(num4, true); + if (rememberParents) + { + this.parentGrid[num4] = intVec; + } + } + } + if (this.openSet.Count > area) { - this.parentGrid[num3] = intVec; + Log.Error("Overflow on flood fill (>" + area + " cells). Make sure we're not flooding over the same area after we check it."); + ProfilerThreadCheck.EndSample(); + return; } + continue; } + break; } - if (this.openSet.Count > area) - { - Log.Error("Overflow on flood fill (>" + area + " cells). Make sure we're not flooding over the same area after we check it."); - ProfilerThreadCheck.EndSample(); - return; - } + ProfilerThreadCheck.EndSample(); } - ProfilerThreadCheck.EndSample(); } public void ReconstructLastFloodFillPath(IntVec3 dest, List outPath) { outPath.Clear(); - if (this.parentGrid == null || !dest.InBounds(this.map) || !this.parentGrid[dest].IsValid) - { - return; - } - int num = 0; - int num2 = this.map.Area + 1; - IntVec3 intVec = dest; - while (true) + if (this.parentGrid != null && dest.InBounds(this.map) && this.parentGrid[dest].IsValid) { - num++; - if (num > num2) + int num = 0; + int num2 = this.map.Area + 1; + IntVec3 intVec = dest; + while (true) { + num++; + if (num > num2) + { + Log.Error("Too many iterations."); + } + else if (intVec.IsValid) + { + outPath.Add(intVec); + if (!(this.parentGrid[intVec] == intVec)) + { + intVec = this.parentGrid[intVec]; + continue; + } + } break; } - if (!intVec.IsValid) - { - goto Block_4; - } - outPath.Add(intVec); - if (this.parentGrid[intVec] == intVec) - { - goto Block_5; - } - intVec = this.parentGrid[intVec]; + outPath.Reverse(); } - Log.Error("Too many iterations."); - Block_4: - Block_5: - outPath.Reverse(); } private void ClearVisited() { - int i = 0; + int num = 0; int count = this.visited.Count; - while (i < count) + while (num < count) { - int index = this.visited[i]; + int index = this.visited[num]; this.queuedGrid[index] = false; if (this.parentGrid != null) { this.parentGrid[index] = IntVec3.Invalid; } - i++; + num++; } this.visited.Clear(); this.openSet.Clear(); diff --git a/Assembly-CSharp/Verse/FloodFillerFog.cs b/Assembly-CSharp/Verse/FloodFillerFog.cs index 78dfede37..bbab21641 100644 --- a/Assembly-CSharp/Verse/FloodFillerFog.cs +++ b/Assembly-CSharp/Verse/FloodFillerFog.cs @@ -21,16 +21,24 @@ public static FloodUnfogResult FloodUnfog(IntVec3 root, Map map) List newlyUnfoggedCells = new List(); int numUnfogged = 0; bool expanding = false; - Predicate predicate = delegate(IntVec3 c) + Predicate predicate = (Predicate)delegate(IntVec3 c) { if (!fogGridDirect[map.cellIndices.CellToIndex(c)]) { return false; } Thing edifice = c.GetEdifice(map); - return (edifice == null || !edifice.def.MakeFog) && (!FloodFillerFog.testMode || expanding || numUnfogged <= 500); + if (edifice != null && edifice.def.MakeFog) + { + return false; + } + if (FloodFillerFog.testMode && !expanding && numUnfogged > 500) + { + return false; + } + return true; }; - Action processor = delegate(IntVec3 c) + Action processor = (Action)delegate(IntVec3 c) { fogGrid.Unfog(c); newlyUnfoggedCells.Add(c); @@ -50,7 +58,7 @@ public static FloodUnfogResult FloodUnfog(IntVec3 root, Map map) if (FloodFillerFog.testMode) { numUnfogged++; - map.debugDrawer.FlashCell(c, (float)numUnfogged / 200f, numUnfogged.ToStringCached()); + map.debugDrawer.FlashCell(c, (float)((float)numUnfogged / 200.0), numUnfogged.ToStringCached()); } }; map.floodFiller.FloodFill(root, predicate, processor, false); @@ -61,12 +69,9 @@ public static FloodUnfogResult FloodUnfog(IntVec3 root, Map map) for (int j = 0; j < 8; j++) { IntVec3 intVec = a + GenAdj.AdjacentCells[j]; - if (intVec.InBounds(map) && fogGrid.IsFogged(intVec)) + if (intVec.InBounds(map) && fogGrid.IsFogged(intVec) && !predicate(intVec)) { - if (!predicate(intVec)) - { - FloodFillerFog.cellsToUnfog.Add(intVec); - } + FloodFillerFog.cellsToUnfog.Add(intVec); } } } @@ -86,9 +91,9 @@ public static FloodUnfogResult FloodUnfog(IntVec3 root, Map map) internal static void DebugFloodUnfog(IntVec3 root, Map map) { map.fogGrid.SetAllFogged(); - foreach (IntVec3 current in map.AllCells) + foreach (IntVec3 allCell in map.AllCells) { - map.mapDrawer.MapMeshDirty(current, MapMeshFlag.FogOfWar); + map.mapDrawer.MapMeshDirty(allCell, MapMeshFlag.FogOfWar); } FloodFillerFog.testMode = true; FloodFillerFog.FloodUnfog(root, map); @@ -98,11 +103,11 @@ internal static void DebugFloodUnfog(IntVec3 root, Map map) internal static void DebugRefogMap(Map map) { map.fogGrid.SetAllFogged(); - foreach (IntVec3 current in map.AllCells) + foreach (IntVec3 allCell in map.AllCells) { - map.mapDrawer.MapMeshDirty(current, MapMeshFlag.FogOfWar); + map.mapDrawer.MapMeshDirty(allCell, MapMeshFlag.FogOfWar); } - FloodFillerFog.FloodUnfog(map.mapPawns.FreeColonistsSpawned.RandomElement().Position, map); + FloodFillerFog.FloodUnfog(map.mapPawns.FreeColonistsSpawned.RandomElement().Position, map); } } } diff --git a/Assembly-CSharp/Verse/FloodUnfogResult.cs b/Assembly-CSharp/Verse/FloodUnfogResult.cs index 736b89179..d01addefe 100644 --- a/Assembly-CSharp/Verse/FloodUnfogResult.cs +++ b/Assembly-CSharp/Verse/FloodUnfogResult.cs @@ -1,5 +1,3 @@ -using System; - namespace Verse { public struct FloodUnfogResult diff --git a/Assembly-CSharp/Verse/FogGrid.cs b/Assembly-CSharp/Verse/FogGrid.cs index 91719d917..2330d8beb 100644 --- a/Assembly-CSharp/Verse/FogGrid.cs +++ b/Assembly-CSharp/Verse/FogGrid.cs @@ -1,5 +1,4 @@ using RimWorld; -using System; namespace Verse { @@ -16,35 +15,42 @@ public FogGrid(Map map) public void ExposeData() { - ArrayExposeUtility.ExposeBoolArray(ref this.fogGrid, this.map.Size.x, this.map.Size.z, "fogGrid"); + ref bool[] arr = ref this.fogGrid; + IntVec3 size = this.map.Size; + int x = size.x; + IntVec3 size2 = this.map.Size; + ArrayExposeUtility.ExposeBoolArray(ref arr, x, size2.z, "fogGrid"); } public void Unfog(IntVec3 c) { int num = this.map.cellIndices.CellToIndex(c); - if (!this.fogGrid[num]) + if (this.fogGrid[num]) { - return; - } - this.fogGrid[num] = false; - if (Current.ProgramState == ProgramState.Playing) - { - this.map.mapDrawer.MapMeshDirty(c, MapMeshFlag.FogOfWar); - } - Designation designation = this.map.designationManager.DesignationAt(c, DesignationDefOf.Mine); - if (designation != null && MineUtility.MineableInCell(c, this.map) == null) - { - designation.Delete(); - } - if (Current.ProgramState == ProgramState.Playing) - { - this.map.roofGrid.Drawer.SetDirty(); + this.fogGrid[num] = false; + if (Current.ProgramState == ProgramState.Playing) + { + this.map.mapDrawer.MapMeshDirty(c, MapMeshFlag.FogOfWar); + } + Designation designation = this.map.designationManager.DesignationAt(c, DesignationDefOf.Mine); + if (designation != null && MineUtility.MineableInCell(c, this.map) == null) + { + designation.Delete(); + } + if (Current.ProgramState == ProgramState.Playing) + { + this.map.roofGrid.Drawer.SetDirty(); + } } } public bool IsFogged(IntVec3 c) { - return c.InBounds(this.map) && this.fogGrid != null && this.fogGrid[this.map.cellIndices.CellToIndex(c)]; + if (c.InBounds(this.map) && this.fogGrid != null) + { + return this.fogGrid[this.map.cellIndices.CellToIndex(c)]; + } + return false; } public bool IsFogged(int index) @@ -54,44 +60,58 @@ public bool IsFogged(int index) public void ClearAllFog() { - for (int i = 0; i < this.map.Size.x; i++) + int num = 0; + while (true) { - for (int j = 0; j < this.map.Size.z; j++) + int num2 = num; + IntVec3 size = this.map.Size; + if (num2 < size.x) { - this.Unfog(new IntVec3(i, 0, j)); + int num3 = 0; + while (true) + { + int num4 = num3; + IntVec3 size2 = this.map.Size; + if (num4 < size2.z) + { + this.Unfog(new IntVec3(num, 0, num3)); + num3++; + continue; + } + break; + } + num++; + continue; } + break; } } public void Notify_FogBlockerRemoved(IntVec3 c) { - if (Current.ProgramState != ProgramState.Playing) - { - return; - } - bool flag = false; - for (int i = 0; i < 8; i++) + if (Current.ProgramState == ProgramState.Playing) { - IntVec3 c2 = c + GenAdj.AdjacentCells[i]; - if (c2.InBounds(this.map) && !this.IsFogged(c2)) + bool flag = false; + for (int i = 0; i < 8; i++) { - flag = true; - break; + IntVec3 c2 = c + GenAdj.AdjacentCells[i]; + if (c2.InBounds(this.map) && !this.IsFogged(c2)) + { + flag = true; + break; + } + } + if (flag) + { + this.FloodUnfogAdjacent(c); } } - if (!flag) - { - return; - } - this.FloodUnfogAdjacent(c); } public void Notify_PawnEnteringDoor(Building_Door door, Pawn pawn) { if (pawn.Faction != Faction.OfPlayer && pawn.HostFaction != Faction.OfPlayer) - { return; - } this.FloodUnfogAdjacent(door.Position); } @@ -102,9 +122,9 @@ internal void SetAllFogged() { this.fogGrid = new bool[cellIndices.NumGridCells]; } - foreach (IntVec3 current in this.map.AllCells) + foreach (IntVec3 allCell in this.map.AllCells) { - this.fogGrid[cellIndices.CellToIndex(current)] = true; + this.fogGrid[cellIndices.CellToIndex(allCell)] = true; } if (Current.ProgramState == ProgramState.Playing) { @@ -120,20 +140,17 @@ private void FloodUnfogAdjacent(IntVec3 c) for (int i = 0; i < 4; i++) { IntVec3 intVec = c + GenAdj.CardinalDirections[i]; - if (intVec.InBounds(this.map)) + if (intVec.InBounds(this.map) && intVec.Fogged(this.map)) { - if (intVec.Fogged(this.map)) + Building edifice = intVec.GetEdifice(this.map); + if (edifice == null || !edifice.def.MakeFog) { - Building edifice = intVec.GetEdifice(this.map); - if (edifice == null || !edifice.def.MakeFog) - { - flag = true; - floodUnfogResult = FloodFillerFog.FloodUnfog(intVec, this.map); - } - else - { - this.Unfog(intVec); - } + flag = true; + floodUnfogResult = FloodFillerFog.FloodUnfog(intVec, this.map); + } + else + { + this.Unfog(intVec); } } } @@ -153,11 +170,11 @@ private void FloodUnfogAdjacent(IntVec3 c) { if (floodUnfogResult.mechanoidFound) { - Find.LetterStack.ReceiveLetter("LetterLabelAreaRevealed".Translate(), "AreaRevealedWithMechanoids".Translate(), LetterDefOf.BadUrgent, new TargetInfo(c, this.map, false), null); + Find.LetterStack.ReceiveLetter("LetterLabelAreaRevealed".Translate(), "AreaRevealedWithMechanoids".Translate(), LetterDefOf.BadUrgent, new TargetInfo(c, this.map, false), (string)null); } else { - Find.LetterStack.ReceiveLetter("LetterLabelAreaRevealed".Translate(), "AreaRevealed".Translate(), LetterDefOf.Good, new TargetInfo(c, this.map, false), null); + Find.LetterStack.ReceiveLetter("LetterLabelAreaRevealed".Translate(), "AreaRevealed".Translate(), LetterDefOf.Good, new TargetInfo(c, this.map, false), (string)null); } } } diff --git a/Assembly-CSharp/Verse/FullPool.cs b/Assembly-CSharp/Verse/FullPool.cs index 71523864f..71444f8fe 100644 --- a/Assembly-CSharp/Verse/FullPool.cs +++ b/Assembly-CSharp/Verse/FullPool.cs @@ -1,4 +1,3 @@ -using System; using System.Collections.Generic; namespace Verse @@ -11,7 +10,7 @@ public static T Get() { if (FullPool.freeItems.Count == 0) { - return (default(T) == null) ? Activator.CreateInstance() : default(T); + return new T(); } T result = FullPool.freeItems[FullPool.freeItems.Count - 1]; FullPool.freeItems.RemoveAt(FullPool.freeItems.Count - 1); diff --git a/Assembly-CSharp/Verse/GUIEventFilterForOSX.cs b/Assembly-CSharp/Verse/GUIEventFilterForOSX.cs index d7f99836a..068e8a3ce 100644 --- a/Assembly-CSharp/Verse/GUIEventFilterForOSX.cs +++ b/Assembly-CSharp/Verse/GUIEventFilterForOSX.cs @@ -1,4 +1,3 @@ -using System; using System.Collections.Generic; using UnityEngine; @@ -12,27 +11,22 @@ internal static class GUIEventFilterForOSX public static void CheckRejectGUIEvent() { - if (UnityData.platform != RuntimePlatform.OSXPlayer) + if (UnityData.platform == RuntimePlatform.OSXPlayer && (Event.current.type == EventType.MouseDown || Event.current.type == EventType.MouseUp)) { - return; - } - if (Event.current.type != EventType.MouseDown && Event.current.type != EventType.MouseUp) - { - return; - } - if (Time.frameCount != GUIEventFilterForOSX.lastRecordedFrame) - { - GUIEventFilterForOSX.eventsThisFrame.Clear(); - GUIEventFilterForOSX.lastRecordedFrame = Time.frameCount; - } - for (int i = 0; i < GUIEventFilterForOSX.eventsThisFrame.Count; i++) - { - if (GUIEventFilterForOSX.EventsAreEquivalent(GUIEventFilterForOSX.eventsThisFrame[i], Event.current)) + if (Time.frameCount != GUIEventFilterForOSX.lastRecordedFrame) + { + GUIEventFilterForOSX.eventsThisFrame.Clear(); + GUIEventFilterForOSX.lastRecordedFrame = Time.frameCount; + } + for (int i = 0; i < GUIEventFilterForOSX.eventsThisFrame.Count; i++) { - GUIEventFilterForOSX.RejectEvent(); + if (GUIEventFilterForOSX.EventsAreEquivalent(GUIEventFilterForOSX.eventsThisFrame[i], Event.current)) + { + GUIEventFilterForOSX.RejectEvent(); + } } + GUIEventFilterForOSX.eventsThisFrame.Add(Event.current); } - GUIEventFilterForOSX.eventsThisFrame.Add(Event.current); } private static bool EventsAreEquivalent(Event A, Event B) @@ -44,13 +38,7 @@ private static void RejectEvent() { if (DebugViewSettings.logInput) { - Log.Message(string.Concat(new object[] - { - "Frame ", - Time.frameCount, - ": REJECTED ", - Event.current.ToStringFull() - })); + Log.Message("Frame " + Time.frameCount + ": REJECTED " + Event.current.ToStringFull()); } Event.current.Use(); } diff --git a/Assembly-CSharp/Verse/Game.cs b/Assembly-CSharp/Verse/Game.cs index b399695f5..8b4d893c9 100644 --- a/Assembly-CSharp/Verse/Game.cs +++ b/Assembly-CSharp/Verse/Game.cs @@ -12,7 +12,7 @@ public class Game : IExposable { private GameInitData initData; - public sbyte visibleMapIndex = -1; + public sbyte visibleMapIndex = (sbyte)(-1); private GameInfo info = new GameInfo(); @@ -76,11 +76,10 @@ public World World } set { - if (this.worldInt == value) + if (this.worldInt != value) { - return; + this.worldInt = value; } - this.worldInt = value; } } @@ -88,11 +87,11 @@ public Map VisibleMap { get { - if ((int)this.visibleMapIndex < 0) + if (this.visibleMapIndex < 0) { return null; } - return this.maps[(int)this.visibleMapIndex]; + return this.maps[this.visibleMapIndex]; } set { @@ -110,7 +109,7 @@ public Map VisibleMap return; } } - if ((int)this.visibleMapIndex != num) + if (this.visibleMapIndex != num) { this.visibleMapIndex = (sbyte)num; Find.MapUI.Notify_SwitchedMap(); @@ -185,20 +184,20 @@ public void AddMap(Map map) if (map == null) { Log.Error("Tried to add null map."); - return; } - if (this.maps.Contains(map)) + else if (this.maps.Contains(map)) { Log.Error("Tried to add map but it's already here."); - return; } - if (this.maps.Count > 127) + else if (this.maps.Count > 127) { - Log.Error("Can't add map. Reached maps count limit (" + 127 + ")."); - return; + Log.Error("Can't add map. Reached maps count limit (" + (sbyte)127 + ")."); + } + else + { + this.maps.Add(map); + Find.ColonistBar.MarkColonistsDirty(); } - this.maps.Add(map); - Find.ColonistBar.MarkColonistsDirty(); } public Map FindMap(MapParent mapParent) @@ -230,13 +229,15 @@ public void ExposeData() if (Scribe.mode == LoadSaveMode.LoadingVars) { Log.Error("You must use special LoadData method to load Game."); - return; } - Scribe_Values.Look(ref this.visibleMapIndex, "visibleMapIndex", -1, false); - this.ExposeSmallComponents(); - Scribe_Deep.Look(ref this.worldInt, "world", new object[0]); - Scribe_Collections.Look(ref this.maps, "maps", LookMode.Deep, new object[0]); - Find.CameraDriver.Expose(); + else + { + Scribe_Values.Look(ref this.visibleMapIndex, "visibleMapIndex", (sbyte)(-1), false); + this.ExposeSmallComponents(); + Scribe_Deep.Look(ref this.worldInt, "world", new object[0]); + Scribe_Collections.Look(ref this.maps, "maps", LookMode.Deep, new object[0]); + Find.CameraDriver.Expose(); + } } private void ExposeSmallComponents() @@ -264,15 +265,12 @@ private void ExposeSmallComponents() private void FillComponents() { - this.components.RemoveAll((GameComponent component) => component == null); - foreach (Type current in typeof(GameComponent).AllSubclassesNonAbstract()) + this.components.RemoveAll((Predicate)((GameComponent component) => component == null)); + foreach (Type item2 in typeof(GameComponent).AllSubclassesNonAbstract()) { - if (this.GetComponent(current) == null) + if (this.GetComponent(item2) == null) { - GameComponent item = (GameComponent)Activator.CreateInstance(current, new object[] - { - this - }); + GameComponent item = (GameComponent)Activator.CreateInstance(item2, this); this.components.Add(item); } } @@ -283,150 +281,160 @@ public void InitNewGame() string str = GenText.ToCommaList(from mod in LoadedModManager.RunningMods select mod.ToString(), true); Log.Message("Initializing new game with mods " + str); - if (this.maps.Any()) + if (this.maps.Any()) { Log.Error("Called InitNewGame() but there already is a map. There should be 0 maps..."); - return; } - if (this.initData == null) + else if (this.initData == null) { Log.Error("Called InitNewGame() but init data is null. Create it first."); - return; } - MemoryUtility.UnloadUnusedUnityAssets(); - DeepProfiler.Start("InitNewGame"); - try + else { - Current.ProgramState = ProgramState.MapInitializing; - IntVec3 intVec = new IntVec3(this.initData.mapSize, 1, this.initData.mapSize); - FactionBase factionBase = null; - List factionBases = Find.WorldObjects.FactionBases; - for (int i = 0; i < factionBases.Count; i++) + MemoryUtility.UnloadUnusedUnityAssets(); + DeepProfiler.Start("InitNewGame"); + try { - if (factionBases[i].Faction == Faction.OfPlayer) + Current.ProgramState = ProgramState.MapInitializing; + IntVec3 intVec = new IntVec3(this.initData.mapSize, 1, this.initData.mapSize); + FactionBase factionBase = null; + List factionBases = Find.WorldObjects.FactionBases; + int num = 0; + while (num < factionBases.Count) { - factionBase = factionBases[i]; + if (factionBases[num].Faction != Faction.OfPlayer) + { + num++; + continue; + } + factionBase = factionBases[num]; break; } - } - if (factionBase == null) - { - Log.Error("Could not generate starting map because there is no any player faction base."); - } - this.tickManager.gameStartAbsTick = GenTicks.ConfiguredTicksAbsAtGameStart; - Map visibleMap = MapGenerator.GenerateMap(intVec, factionBase, factionBase.MapGeneratorDef, factionBase.ExtraGenStepDefs, null); - this.worldInt.info.initialMapSize = intVec; - if (this.initData.permadeath) - { - this.info.permadeathMode = true; - this.info.permadeathModeUniqueName = PermadeathModeUtility.GeneratePermadeathSaveName(); - } - PawnUtility.GiveAllStartingPlayerPawnsThought(ThoughtDefOf.NewColonyOptimism); - this.FinalizeInit(); - Current.Game.VisibleMap = visibleMap; - Find.CameraDriver.JumpToVisibleMapLoc(MapGenerator.PlayerStartSpot); - Find.CameraDriver.ResetSize(); - if (Prefs.PauseOnLoad && this.initData.startedFromEntry) - { - LongEventHandler.ExecuteWhenFinished(delegate + if (factionBase == null) { - this.tickManager.DoSingleTick(); - this.tickManager.CurTimeSpeed = TimeSpeed.Paused; - }); - } - Find.Scenario.PostGameStart(); - if (Faction.OfPlayer.def.startingResearchTags != null) - { - foreach (string current in Faction.OfPlayer.def.startingResearchTags) + Log.Error("Could not generate starting map because there is no any player faction base."); + } + this.tickManager.gameStartAbsTick = GenTicks.ConfiguredTicksAbsAtGameStart; + Map visibleMap = MapGenerator.GenerateMap(intVec, factionBase, factionBase.MapGeneratorDef, factionBase.ExtraGenStepDefs, null); + this.worldInt.info.initialMapSize = intVec; + if (this.initData.permadeath) + { + this.info.permadeathMode = true; + this.info.permadeathModeUniqueName = PermadeathModeUtility.GeneratePermadeathSaveName(); + } + PawnUtility.GiveAllStartingPlayerPawnsThought(ThoughtDefOf.NewColonyOptimism); + this.FinalizeInit(); + Current.Game.VisibleMap = visibleMap; + Find.CameraDriver.JumpToVisibleMapLoc(MapGenerator.PlayerStartSpot); + Find.CameraDriver.ResetSize(); + if (Prefs.PauseOnLoad && this.initData.startedFromEntry) + { + LongEventHandler.ExecuteWhenFinished((Action)delegate + { + this.tickManager.DoSingleTick(); + this.tickManager.CurTimeSpeed = TimeSpeed.Paused; + }); + } + Find.Scenario.PostGameStart(); + if (Faction.OfPlayer.def.startingResearchTags != null) { - foreach (ResearchProjectDef current2 in DefDatabase.AllDefs) + List.Enumerator enumerator = Faction.OfPlayer.def.startingResearchTags.GetEnumerator(); + try { - if (current2.HasTag(current)) + while (enumerator.MoveNext()) { - this.researchManager.InstantFinish(current2, false); + string current = enumerator.Current; + foreach (ResearchProjectDef allDef in DefDatabase.AllDefs) + { + if (allDef.HasTag(current)) + { + this.researchManager.InstantFinish(allDef, false); + } + } } } + finally + { + ((IDisposable)(object)enumerator).Dispose(); + } } + GameComponentUtility.StartedNewGame(); + this.initData = null; + } + finally + { + DeepProfiler.End(); } - GameComponentUtility.StartedNewGame(); - this.initData = null; - } - finally - { - DeepProfiler.End(); } } public void LoadGame() { - if (this.maps.Any()) + if (this.maps.Any()) { Log.Error("Called LoadGame() but there already is a map. There should be 0 maps..."); - return; } - MemoryUtility.UnloadUnusedUnityAssets(); - Current.ProgramState = ProgramState.MapInitializing; - this.ExposeSmallComponents(); - BackCompatibility.AfterLoadingSmallGameClassComponents(this); - LongEventHandler.SetCurrentEventText("LoadingWorld".Translate()); - if (Scribe.EnterNode("world")) + else { - try - { - this.World = new World(); - this.World.ExposeData(); - } - finally - { - Scribe.ExitNode(); - } - this.World.FinalizeInit(); - LongEventHandler.SetCurrentEventText("LoadingMap".Translate()); - Scribe_Collections.Look(ref this.maps, "maps", LookMode.Deep, new object[0]); - int num = -1; - Scribe_Values.Look(ref num, "visibleMapIndex", -1, false); - if (num < 0 && this.maps.Any()) - { - Log.Error("Visible map is null after loading but there are maps available. Setting visible map to [0]."); - num = 0; - } - if (num >= this.maps.Count) + MemoryUtility.UnloadUnusedUnityAssets(); + Current.ProgramState = ProgramState.MapInitializing; + this.ExposeSmallComponents(); + BackCompatibility.AfterLoadingSmallGameClassComponents(this); + LongEventHandler.SetCurrentEventText("LoadingWorld".Translate()); + if (Scribe.EnterNode("world")) { - Log.Error("Visible map index out of bounds after loading."); - if (this.maps.Any()) + try { + this.World = new World(); + this.World.ExposeData(); + } + finally + { + Scribe.ExitNode(); + } + this.World.FinalizeInit(); + LongEventHandler.SetCurrentEventText("LoadingMap".Translate()); + Scribe_Collections.Look(ref this.maps, "maps", LookMode.Deep, new object[0]); + int num = -1; + Scribe_Values.Look(ref num, "visibleMapIndex", -1, false); + if (num < 0 && this.maps.Any()) + { + Log.Error("Visible map is null after loading but there are maps available. Setting visible map to [0]."); num = 0; } - else + if (num >= this.maps.Count) { - num = -1; + Log.Error("Visible map index out of bounds after loading."); + num = ((!this.maps.Any()) ? (-1) : 0); } + this.visibleMapIndex = (sbyte)(-128); + this.VisibleMap = ((num < 0) ? null : this.maps[num]); + LongEventHandler.SetCurrentEventText("InitializingGame".Translate()); + Find.CameraDriver.Expose(); + DeepProfiler.Start("FinalizeLoading"); + Scribe.loader.FinalizeLoading(); + DeepProfiler.End(); + LongEventHandler.SetCurrentEventText("SpawningAllThings".Translate()); + for (int i = 0; i < this.maps.Count; i++) + { + this.maps[i].FinalizeLoading(); + } + this.FinalizeInit(); + if (Prefs.PauseOnLoad) + { + LongEventHandler.ExecuteWhenFinished((Action)delegate + { + Find.TickManager.DoSingleTick(); + Find.TickManager.CurTimeSpeed = TimeSpeed.Paused; + }); + } + GameComponentUtility.LoadedGame(); } - this.visibleMapIndex = -128; - this.VisibleMap = ((num < 0) ? null : this.maps[num]); - LongEventHandler.SetCurrentEventText("InitializingGame".Translate()); - Find.CameraDriver.Expose(); - DeepProfiler.Start("FinalizeLoading"); - Scribe.loader.FinalizeLoading(); - DeepProfiler.End(); - LongEventHandler.SetCurrentEventText("SpawningAllThings".Translate()); - for (int i = 0; i < this.maps.Count; i++) - { - this.maps[i].FinalizeLoading(); - } - this.FinalizeInit(); - if (Prefs.PauseOnLoad) + else { - LongEventHandler.ExecuteWhenFinished(delegate - { - Find.TickManager.DoSingleTick(); - Find.TickManager.CurTimeSpeed = TimeSpeed.Paused; - }); + Log.Error("Could not find world XML node."); } - GameComponentUtility.LoadedGame(); - return; } - Log.Error("Could not find world XML node."); } public void UpdateEntry() @@ -451,13 +459,13 @@ public T GetComponent() where T : GameComponent { for (int i = 0; i < this.components.Count; i++) { - T t = this.components[i] as T; - if (t != null) + T val = (T)(this.components[i] as T); + if (val != null) { - return t; + return val; } } - return (T)((object)null); + return (T)null; } public GameComponent GetComponent(Type type) @@ -486,43 +494,44 @@ public void DeinitAndRemoveMap(Map map) if (map == null) { Log.Error("Tried to remove null map."); - return; } - if (!this.maps.Contains(map)) + else if (!this.maps.Contains(map)) { Log.Error("Tried to remove map " + map + " but it's not here."); - return; } - Map visibleMap = this.VisibleMap; - MapDeiniter.Deinit(map); - this.maps.Remove(map); - if (visibleMap != null) + else { - sbyte b = (sbyte)this.maps.IndexOf(visibleMap); - if ((int)b < 0) + Map visibleMap = this.VisibleMap; + MapDeiniter.Deinit(map); + this.maps.Remove(map); + if (visibleMap != null) { - if (this.maps.Any()) + sbyte b = (sbyte)this.maps.IndexOf(visibleMap); + if (b < 0) { - this.VisibleMap = this.maps[0]; + if (this.maps.Any()) + { + this.VisibleMap = this.maps[0]; + } + else + { + this.VisibleMap = null; + } } else { - this.VisibleMap = null; + this.visibleMapIndex = b; } } - else + if (Current.ProgramState == ProgramState.Playing) { - this.visibleMapIndex = b; + Find.ColonistBar.MarkColonistsDirty(); + } + MapComponentUtility.MapRemoved(map); + if (map.info.parent != null) + { + map.info.parent.Notify_MyMapRemoved(map); } - } - if (Current.ProgramState == ProgramState.Playing) - { - Find.ColonistBar.MarkColonistsDirty(); - } - MapComponentUtility.MapRemoved(map); - if (map.info.parent != null) - { - map.info.parent.Notify_MyMapRemoved(map); } } diff --git a/Assembly-CSharp/Verse/GameAndMapInitExceptionHandlers.cs b/Assembly-CSharp/Verse/GameAndMapInitExceptionHandlers.cs index b881632e3..c49a2ceda 100644 --- a/Assembly-CSharp/Verse/GameAndMapInitExceptionHandlers.cs +++ b/Assembly-CSharp/Verse/GameAndMapInitExceptionHandlers.cs @@ -8,7 +8,7 @@ public static class GameAndMapInitExceptionHandlers public static void ErrorWhileLoadingAssets(Exception e) { string text = "ErrorWhileLoadingAssets".Translate(); - if (ModsConfig.ActiveModsInLoadOrder.Count() != 1 || !ModsConfig.ActiveModsInLoadOrder.First().IsCoreMod) + if (ModsConfig.ActiveModsInLoadOrder.Count() != 1 || !ModsConfig.ActiveModsInLoadOrder.First().IsCoreMod) { text = text + "\n\n" + "ErrorWhileLoadingAssets_ModsInfo".Translate(); } @@ -26,15 +26,11 @@ public static void ErrorWhileGeneratingMap(Exception e) public static void ErrorWhileLoadingGame(Exception e) { string text = "ErrorWhileLoadingMap".Translate(); - string text2; - string text3; + string text2 = default(string); + string text3 = default(string); if (!ScribeMetaHeaderUtility.LoadedModsMatchesActiveMods(out text2, out text3)) { - text = text + "\n\n" + "ModsMismatchWarningText".Translate(new object[] - { - text2, - text3 - }); + text = text + "\n\n" + "ModsMismatchWarningText".Translate(text2, text3); } DelayedErrorWindowRequest.Add(text, "ErrorWhileLoadingMapTitle".Translate()); Scribe.ForceStop(); diff --git a/Assembly-CSharp/Verse/GameComponent.cs b/Assembly-CSharp/Verse/GameComponent.cs index 230827ac8..2e00c32a9 100644 --- a/Assembly-CSharp/Verse/GameComponent.cs +++ b/Assembly-CSharp/Verse/GameComponent.cs @@ -1,5 +1,3 @@ -using System; - namespace Verse { public abstract class GameComponent : IExposable diff --git a/Assembly-CSharp/Verse/GameConditionDef.cs b/Assembly-CSharp/Verse/GameConditionDef.cs index a2a403040..1a4092b9f 100644 --- a/Assembly-CSharp/Verse/GameConditionDef.cs +++ b/Assembly-CSharp/Verse/GameConditionDef.cs @@ -1,7 +1,6 @@ using RimWorld; using System; using System.Collections.Generic; -using System.Diagnostics; namespace Verse { @@ -22,7 +21,11 @@ public class GameConditionDef : Def public bool CanCoexistWith(GameConditionDef other) { - return this != other && (this.exclusiveConditions == null || !this.exclusiveConditions.Contains(other)); + if (this == other) + { + return false; + } + return this.exclusiveConditions == null || !this.exclusiveConditions.Contains(other); } public static GameConditionDef Named(string defName) @@ -30,14 +33,16 @@ public static GameConditionDef Named(string defName) return DefDatabase.GetNamed(defName, true); } - [DebuggerHidden] public override IEnumerable ConfigErrors() { - GameConditionDef.c__Iterator1CE c__Iterator1CE = new GameConditionDef.c__Iterator1CE(); - c__Iterator1CE.<>f__this = this; - GameConditionDef.c__Iterator1CE expr_0E = c__Iterator1CE; - expr_0E.$PC = -2; - return expr_0E; + foreach (string item in base.ConfigErrors()) + { + yield return item; + } + if (this.conditionClass == null) + { + yield return "conditionClass is null"; + } } } } diff --git a/Assembly-CSharp/Verse/GameDataSaveLoader.cs b/Assembly-CSharp/Verse/GameDataSaveLoader.cs index fa259e5c3..396343b56 100644 --- a/Assembly-CSharp/Verse/GameDataSaveLoader.cs +++ b/Assembly-CSharp/Verse/GameDataSaveLoader.cs @@ -33,10 +33,10 @@ public static void SaveScenario(Scenario scen, string absFilePath) try { scen.fileName = Path.GetFileNameWithoutExtension(absFilePath); - SafeSaver.Save(absFilePath, "savedscenario", delegate + SafeSaver.Save(absFilePath, "savedscenario", (Action)delegate() { ScribeMetaHeaderUtility.WriteMetaHeader(); - Scribe_Deep.Look(ref scen, "scenario", new object[0]); + Scribe_Deep.Look(ref scen, "scenario"); }); } catch (Exception ex) @@ -61,6 +61,7 @@ public static bool TryLoadScenario(string absPath, ScenarioCategory category, ou { Scribe.ForceStop(); throw; + IL_003d:; } scen.fileName = Path.GetFileNameWithoutExtension(new FileInfo(absPath).Name); scen.Category = category; @@ -79,11 +80,11 @@ public static void SaveGame(string fileName) try { string path = GenFilePaths.FilePathForSavedGame(fileName); - SafeSaver.Save(path, "savegame", delegate + SafeSaver.Save(path, "savegame", (Action)delegate { ScribeMetaHeaderUtility.WriteMetaHeader(); Game game = Current.Game; - Scribe_Deep.Look(ref game, "game", new object[0]); + Scribe_Deep.Look(ref game, "game"); }); GameDataSaveLoader.lastSaveTick = Find.TickManager.TicksGame; } diff --git a/Assembly-CSharp/Verse/GameFont.cs b/Assembly-CSharp/Verse/GameFont.cs index f1bee96ed..8ab362b07 100644 --- a/Assembly-CSharp/Verse/GameFont.cs +++ b/Assembly-CSharp/Verse/GameFont.cs @@ -1,11 +1,9 @@ -using System; - namespace Verse { public enum GameFont : byte { - Tiny, - Small, - Medium + Tiny = 0, + Small = 1, + Medium = 2 } } diff --git a/Assembly-CSharp/Verse/GameInfo.cs b/Assembly-CSharp/Verse/GameInfo.cs index 152395493..50e6dd938 100644 --- a/Assembly-CSharp/Verse/GameInfo.cs +++ b/Assembly-CSharp/Verse/GameInfo.cs @@ -1,5 +1,4 @@ using RimWorld; -using System; using UnityEngine; namespace Verse @@ -24,15 +23,14 @@ public float RealPlayTimeInteracting public void GameInfoOnGUI() { - if (Event.current.type == EventType.MouseDown || Event.current.type == EventType.MouseMove || Event.current.type == EventType.KeyDown) - { - this.lastInputRealTime = Time.realtimeSinceStartup; - } + if (Event.current.type != 0 && Event.current.type != EventType.MouseMove && Event.current.type != EventType.KeyDown) + return; + this.lastInputRealTime = Time.realtimeSinceStartup; } public void GameInfoUpdate() { - if (Time.realtimeSinceStartup < this.lastInputRealTime + 90f && Find.MainTabsRoot.OpenTab != MainButtonDefOf.Menu && Current.ProgramState == ProgramState.Playing && !Find.WindowStack.IsOpen()) + if (Time.realtimeSinceStartup < this.lastInputRealTime + 90.0 && Find.MainTabsRoot.OpenTab != MainButtonDefOf.Menu && Current.ProgramState == ProgramState.Playing && !Find.WindowStack.IsOpen()) { this.realPlayTimeInteracting += RealTime.realDeltaTime; } @@ -42,7 +40,7 @@ public void ExposeData() { Scribe_Values.Look(ref this.realPlayTimeInteracting, "realPlayTimeInteracting", 0f, false); Scribe_Values.Look(ref this.permadeathMode, "permadeathMode", false, false); - Scribe_Values.Look(ref this.permadeathModeUniqueName, "permadeathModeUniqueName", null, false); + Scribe_Values.Look(ref this.permadeathModeUniqueName, "permadeathModeUniqueName", (string)null, false); } } } diff --git a/Assembly-CSharp/Verse/GameInitData.cs b/Assembly-CSharp/Verse/GameInitData.cs index 3a75ae395..dd67ef245 100644 --- a/Assembly-CSharp/Verse/GameInitData.cs +++ b/Assembly-CSharp/Verse/GameInitData.cs @@ -49,61 +49,87 @@ public void ResetWorldRelatedMapInitData() public override string ToString() { - return string.Concat(new object[] - { - "startedFromEntry: ", - this.startedFromEntry, - "\nstartingPawns: ", - this.startingPawns.Count - }); + return "startedFromEntry: " + this.startedFromEntry + "\nstartingPawns: " + this.startingPawns.Count; } public void PrepForMapGen() { - foreach (Pawn current in this.startingPawns) + List.Enumerator enumerator = this.startingPawns.GetEnumerator(); + try { - current.SetFactionDirect(Faction.OfPlayer); - PawnComponentsUtility.AddAndRemoveDynamicComponents(current, false); + while (enumerator.MoveNext()) + { + Pawn current = enumerator.Current; + current.SetFactionDirect(Faction.OfPlayer); + PawnComponentsUtility.AddAndRemoveDynamicComponents(current, false); + } } - foreach (Pawn current2 in this.startingPawns) + finally { - current2.workSettings.DisableAll(); + ((IDisposable)(object)enumerator).Dispose(); } - foreach (WorkTypeDef w in DefDatabase.AllDefs) + List.Enumerator enumerator2 = this.startingPawns.GetEnumerator(); + try { - if (w.alwaysStartActive) + while (enumerator2.MoveNext()) { - foreach (Pawn current3 in from col in this.startingPawns - where !col.story.WorkTypeIsDisabled(w) - select col) - { - current3.workSettings.SetPriority(w, 3); - } + Pawn current2 = enumerator2.Current; + current2.workSettings.DisableAll(); } - else + } + finally + { + ((IDisposable)(object)enumerator2).Dispose(); + } + using (IEnumerator enumerator3 = DefDatabase.AllDefs.GetEnumerator()) + { + WorkTypeDef w; + while (enumerator3.MoveNext()) { - bool flag = false; - foreach (Pawn current4 in this.startingPawns) + w = enumerator3.Current; + if (w.alwaysStartActive) { - if (!current4.story.WorkTypeIsDisabled(w) && current4.skills.AverageOfRelevantSkillsFor(w) >= 6f) + foreach (Pawn item in from col in this.startingPawns + where !col.story.WorkTypeIsDisabled(w) + select col) { - current4.workSettings.SetPriority(w, 3); - flag = true; + item.workSettings.SetPriority(w, 3); } } - if (!flag) + else { - IEnumerable source = from col in this.startingPawns - where !col.story.WorkTypeIsDisabled(w) - select col; - if (source.Any()) + bool flag = false; + List.Enumerator enumerator5 = this.startingPawns.GetEnumerator(); + try + { + while (enumerator5.MoveNext()) + { + Pawn current4 = enumerator5.Current; + if (!current4.story.WorkTypeIsDisabled(w) && current4.skills.AverageOfRelevantSkillsFor(w) >= 6.0) + { + current4.workSettings.SetPriority(w, 3); + flag = true; + } + } + } + finally { - Pawn pawn = source.InRandomOrder(null).MaxBy((Pawn c) => c.skills.AverageOfRelevantSkillsFor(w)); - pawn.workSettings.SetPriority(w, 3); + ((IDisposable)(object)enumerator5).Dispose(); } - else if (w.requireCapableColonist) + if (!flag) { - Log.Error("No colonist could do requireCapableColonist work type " + w); + IEnumerable source = from col in this.startingPawns + where !col.story.WorkTypeIsDisabled(w) + select col; + if (source.Any()) + { + Pawn pawn = source.InRandomOrder(null).MaxBy((Func)((Pawn c) => c.skills.AverageOfRelevantSkillsFor(w))); + pawn.workSettings.SetPriority(w, 3); + } + else if (w.requireCapableColonist) + { + Log.Error("No colonist could do requireCapableColonist work type " + w); + } } } } diff --git a/Assembly-CSharp/Verse/Gen.cs b/Assembly-CSharp/Verse/Gen.cs index 3438e0573..f25cae4e2 100644 --- a/Assembly-CSharp/Verse/Gen.cs +++ b/Assembly-CSharp/Verse/Gen.cs @@ -1,7 +1,6 @@ using RimWorld.Planet; using System; using System.Collections.Generic; -using System.Diagnostics; using System.Linq; using UnityEngine; @@ -33,6 +32,7 @@ public static Vector3 TrueCenter(IntVec3 loc, Rot4 rotation, IntVec2 thingSize, switch (rotation.AsInt) { case 0: + { if (thingSize.x % 2 == 0) { result.x += 0.5f; @@ -42,7 +42,9 @@ public static Vector3 TrueCenter(IntVec3 loc, Rot4 rotation, IntVec2 thingSize, result.z += 0.5f; } break; + } case 1: + { if (thingSize.x % 2 == 0) { result.x += 0.5f; @@ -52,7 +54,9 @@ public static Vector3 TrueCenter(IntVec3 loc, Rot4 rotation, IntVec2 thingSize, result.z -= 0.5f; } break; + } case 2: + { if (thingSize.x % 2 == 0) { result.x -= 0.5f; @@ -62,7 +66,9 @@ public static Vector3 TrueCenter(IntVec3 loc, Rot4 rotation, IntVec2 thingSize, result.z -= 0.5f; } break; + } case 3: + { if (thingSize.x % 2 == 0) { result.x -= 0.5f; @@ -73,25 +79,26 @@ public static Vector3 TrueCenter(IntVec3 loc, Rot4 rotation, IntVec2 thingSize, } break; } + } } return result; } public static Vector3 AveragePosition(List cells) { - return new Vector3((float)cells.Average((IntVec3 c) => c.x) + 0.5f, 0f, (float)cells.Average((IntVec3 c) => c.z) + 0.5f); + return new Vector3((float)((float)cells.Average((Func)((IntVec3 c) => c.x)) + 0.5), 0f, (float)((float)cells.Average((Func)((IntVec3 c) => c.z)) + 0.5)); } public static T RandomEnumValue(bool disallowFirstValue) { - int min = (!disallowFirstValue) ? 0 : 1; + int min = disallowFirstValue ? 1 : 0; int num = Rand.Range(min, Enum.GetValues(typeof(T)).Length); - return (T)((object)num); + return (T)(object)num; } public static Vector3 RandomHorizontalVector(float max) { - return new Vector3(Rand.Range(-max, max), 0f, Rand.Range(-max, max)); + return new Vector3(Rand.Range((float)(0.0 - max), max), 0f, Rand.Range((float)(0.0 - max), max)); } public static int GetBitCountOf(long lValue) @@ -99,32 +106,28 @@ public static int GetBitCountOf(long lValue) int num = 0; while (lValue != 0L) { - lValue &= lValue - 1L; + lValue &= lValue - 1; num++; } return num; } - [DebuggerHidden] public static IEnumerable GetAllSelectedItems(this Enum value) { - Gen.c__Iterator23F c__Iterator23F = new Gen.c__Iterator23F(); - c__Iterator23F.value = value; - c__Iterator23F.<$>value = value; - Gen.c__Iterator23F expr_15 = c__Iterator23F; - expr_15.$PC = -2; - return expr_15; + int valueAsInt = Convert.ToInt32(value); + foreach (object value2 in Enum.GetValues(typeof(T))) + { + int itemAsInt = Convert.ToInt32(value2); + if (itemAsInt == (valueAsInt & itemAsInt)) + { + yield return (T)value2; + } + } } - [DebuggerHidden] public static IEnumerable YieldSingle(T val) { - Gen.c__Iterator240 c__Iterator = new Gen.c__Iterator240(); - c__Iterator.val = val; - c__Iterator.<$>val = val; - Gen.c__Iterator240 expr_15 = c__Iterator; - expr_15.$PC = -2; - return expr_15; + yield return val; } public static string ToStringSafe(this T obj) @@ -133,33 +136,37 @@ public static string ToStringSafe(this T obj) { return "null"; } - string result; try { - result = obj.ToString(); + return obj.ToString(); + IL_0024: + string result; + return result; } catch (Exception arg) { Log.Warning("Exception in ToString(): " + arg); - result = "error"; + return "error"; + IL_0045: + string result; + return result; } - return result; } public static int HashCombine(int seed, T obj) { int num = (obj != null) ? obj.GetHashCode() : 0; - return (int)((long)seed ^ (long)num + (long)((ulong)-1640531527) + (long)((long)seed << 6) + (long)(seed >> 2)); + return (int)(seed ^ num + 2654435769u + (seed << 6) + (seed >> 2)); } public static int HashCombineStruct(int seed, T obj) where T : struct { - return (int)((long)seed ^ (long)obj.GetHashCode() + (long)((ulong)-1640531527) + (long)((long)seed << 6) + (long)(seed >> 2)); + return (int)(seed ^ obj.GetHashCode() + 2654435769u + (seed << 6) + (seed >> 2)); } public static int HashCombineInt(int seed, int value) { - return (int)((long)seed ^ (long)value + (long)((ulong)-1640531527) + (long)((long)seed << 6) + (long)(seed >> 2)); + return (int)(seed ^ value + 2654435769u + (seed << 6) + (seed >> 2)); } public static int HashOffset(this int baseInt) diff --git a/Assembly-CSharp/Verse/GenAdj.cs b/Assembly-CSharp/Verse/GenAdj.cs index f725dc5a8..711324472 100644 --- a/Assembly-CSharp/Verse/GenAdj.cs +++ b/Assembly-CSharp/Verse/GenAdj.cs @@ -1,6 +1,4 @@ -using System; using System.Collections.Generic; -using System.Diagnostics; namespace Verse { @@ -115,45 +113,57 @@ public static List AdjacentCells8WayRandomized() GenAdj.adjRandomOrderList.Add(GenAdj.AdjacentCells[i]); } } - GenAdj.adjRandomOrderList.Shuffle(); + GenAdj.adjRandomOrderList.Shuffle(); return GenAdj.adjRandomOrderList; } - [DebuggerHidden] public static IEnumerable CellsOccupiedBy(Thing t) { - GenAdj.c__Iterator241 c__Iterator = new GenAdj.c__Iterator241(); - c__Iterator.t = t; - c__Iterator.<$>t = t; - GenAdj.c__Iterator241 expr_15 = c__Iterator; - expr_15.$PC = -2; - return expr_15; + if (t.def.size.x == 1 && t.def.size.z == 1) + { + yield return t.Position; + } + else + { + foreach (IntVec3 item in GenAdj.CellsOccupiedBy(t.Position, t.Rotation, t.def.size)) + { + yield return item; + } + } } - [DebuggerHidden] public static IEnumerable CellsOccupiedBy(IntVec3 center, Rot4 rotation, IntVec2 size) { - GenAdj.c__Iterator242 c__Iterator = new GenAdj.c__Iterator242(); - c__Iterator.center = center; - c__Iterator.size = size; - c__Iterator.rotation = rotation; - c__Iterator.<$>center = center; - c__Iterator.<$>size = size; - c__Iterator.<$>rotation = rotation; - GenAdj.c__Iterator242 expr_31 = c__Iterator; - expr_31.$PC = -2; - return expr_31; + GenAdj.AdjustForRotation(ref center, ref size, rotation); + int minX = center.x - (size.x - 1) / 2; + int minZ = center.z - (size.z - 1) / 2; + int maxX = minX + size.x - 1; + int maxZ = minZ + size.z - 1; + for (int j = minX; j <= maxX; j++) + { + for (int i = minZ; i <= maxZ; i++) + { + yield return new IntVec3(j, 0, i); + } + } } - [DebuggerHidden] public static IEnumerable CellsAdjacent8Way(TargetInfo pack) { - GenAdj.c__Iterator243 c__Iterator = new GenAdj.c__Iterator243(); - c__Iterator.pack = pack; - c__Iterator.<$>pack = pack; - GenAdj.c__Iterator243 expr_15 = c__Iterator; - expr_15.$PC = -2; - return expr_15; + if (pack.HasThing) + { + foreach (IntVec3 item in GenAdj.CellsAdjacent8Way(pack.Thing)) + { + yield return item; + } + } + else + { + for (int i = 0; i < 8; i++) + { + yield return pack.Cell + GenAdj.AdjacentCells[i]; + } + } } public static IEnumerable CellsAdjacent8Way(Thing t) @@ -161,19 +171,42 @@ public static IEnumerable CellsAdjacent8Way(Thing t) return GenAdj.CellsAdjacent8Way(t.Position, t.Rotation, t.def.size); } - [DebuggerHidden] public static IEnumerable CellsAdjacent8Way(IntVec3 thingCenter, Rot4 thingRot, IntVec2 thingSize) { - GenAdj.c__Iterator244 c__Iterator = new GenAdj.c__Iterator244(); - c__Iterator.thingCenter = thingCenter; - c__Iterator.thingSize = thingSize; - c__Iterator.thingRot = thingRot; - c__Iterator.<$>thingCenter = thingCenter; - c__Iterator.<$>thingSize = thingSize; - c__Iterator.<$>thingRot = thingRot; - GenAdj.c__Iterator244 expr_31 = c__Iterator; - expr_31.$PC = -2; - return expr_31; + GenAdj.AdjustForRotation(ref thingCenter, ref thingSize, thingRot); + int minX = thingCenter.x - (thingSize.x - 1) / 2 - 1; + int maxX = minX + thingSize.x + 1; + int minZ = thingCenter.z - (thingSize.z - 1) / 2 - 1; + int maxZ = minZ + thingSize.z + 1; + IntVec3 cur = new IntVec3(minX - 1, 0, minZ); + while (true) + { + cur.x++; + yield return cur; + if (cur.x >= maxX) + break; + } + while (true) + { + cur.z++; + yield return cur; + if (cur.z >= maxZ) + break; + } + while (true) + { + cur.x--; + yield return cur; + if (cur.x <= minX) + break; + } + while (true) + { + cur.z--; + yield return cur; + if (cur.z <= minZ + 1) + break; + } } public static IEnumerable CellsAdjacentCardinal(Thing t) @@ -181,47 +214,79 @@ public static IEnumerable CellsAdjacentCardinal(Thing t) return GenAdj.CellsAdjacentCardinal(t.Position, t.Rotation, t.def.size); } - [DebuggerHidden] public static IEnumerable CellsAdjacentCardinal(IntVec3 center, Rot4 rot, IntVec2 size) { - GenAdj.c__Iterator245 c__Iterator = new GenAdj.c__Iterator245(); - c__Iterator.center = center; - c__Iterator.size = size; - c__Iterator.rot = rot; - c__Iterator.<$>center = center; - c__Iterator.<$>size = size; - c__Iterator.<$>rot = rot; - GenAdj.c__Iterator245 expr_31 = c__Iterator; - expr_31.$PC = -2; - return expr_31; + GenAdj.AdjustForRotation(ref center, ref size, rot); + int minX = center.x - (size.x - 1) / 2 - 1; + int minZ = center.z - (size.z - 1) / 2 - 1; + int maxX = minX + size.x + 1; + int maxZ = minZ + size.z + 1; + for (int j = minX; j <= maxX; j++) + { + for (int i = minZ; i <= maxZ; i++) + { + if ((j == minX || j == maxX || i == minZ || i == maxZ) && (j != minX || i != minZ) && (j != minX || i != maxZ) && (j != maxX || i != maxZ) && (j != maxX || i != minZ)) + { + yield return new IntVec3(j, 0, i); + } + } + } } - [DebuggerHidden] public static IEnumerable CellsAdjacentAlongEdge(IntVec3 thingCent, Rot4 thingRot, IntVec2 thingSize, LinkDirections dir) { - GenAdj.c__Iterator246 c__Iterator = new GenAdj.c__Iterator246(); - c__Iterator.thingCent = thingCent; - c__Iterator.thingSize = thingSize; - c__Iterator.thingRot = thingRot; - c__Iterator.dir = dir; - c__Iterator.<$>thingCent = thingCent; - c__Iterator.<$>thingSize = thingSize; - c__Iterator.<$>thingRot = thingRot; - c__Iterator.<$>dir = dir; - GenAdj.c__Iterator246 expr_3F = c__Iterator; - expr_3F.$PC = -2; - return expr_3F; + GenAdj.AdjustForRotation(ref thingCent, ref thingSize, thingRot); + int minX = thingCent.x - (thingSize.x - 1) / 2 - 1; + int minZ = thingCent.z - (thingSize.z - 1) / 2 - 1; + int maxX = minX + thingSize.x + 1; + int maxZ = minZ + thingSize.z + 1; + if (dir == LinkDirections.Down) + { + for (int x2 = minX; x2 <= maxX; x2++) + { + yield return new IntVec3(x2, thingCent.y, minZ - 1); + } + } + if (dir == LinkDirections.Up) + { + for (int x = minX; x <= maxX; x++) + { + yield return new IntVec3(x, thingCent.y, maxZ + 1); + } + } + if (dir == LinkDirections.Left) + { + for (int z2 = minZ; z2 <= maxZ; z2++) + { + yield return new IntVec3(minX - 1, thingCent.y, z2); + } + } + if (dir == LinkDirections.Right) + { + for (int z = minZ; z <= maxZ; z++) + { + yield return new IntVec3(maxX + 1, thingCent.y, z); + } + } } - [DebuggerHidden] public static IEnumerable CellsAdjacent8WayAndInside(this Thing thing) { - GenAdj.c__Iterator247 c__Iterator = new GenAdj.c__Iterator247(); - c__Iterator.thing = thing; - c__Iterator.<$>thing = thing; - GenAdj.c__Iterator247 expr_15 = c__Iterator; - expr_15.$PC = -2; - return expr_15; + IntVec3 center = thing.Position; + IntVec2 size = thing.def.size; + Rot4 rotation = thing.Rotation; + GenAdj.AdjustForRotation(ref center, ref size, rotation); + int minX = center.x - (size.x - 1) / 2 - 1; + int minZ = center.z - (size.z - 1) / 2 - 1; + int maxX = minX + size.x + 1; + int maxZ = minZ + size.z + 1; + for (int j = minX; j <= maxX; j++) + { + for (int i = minZ; i <= maxZ; i++) + { + yield return new IntVec3(j, 0, i); + } + } } public static void GetAdjacentCorners(LocalTargetInfo target, out IntVec3 BL, out IntVec3 TL, out IntVec3 TR, out IntVec3 BR) @@ -259,11 +324,12 @@ public static IntVec3 RandomAdjacentCell8Way(this Thing t) CellRect cellRect = t.OccupiedRect(); CellRect cellRect2 = cellRect.ExpandedBy(1); IntVec3 randomCell; - do + while (true) { randomCell = cellRect2.RandomCell; + if (!cellRect.Contains(randomCell)) + break; } - while (cellRect.Contains(randomCell)); return randomCell; } @@ -271,9 +337,9 @@ public static IntVec3 RandomAdjacentCellCardinal(this Thing t) { CellRect cellRect = t.OccupiedRect(); IntVec3 randomCell = cellRect.RandomCell; - if (Rand.Value < 0.5f) + if (Rand.Value < 0.5) { - if (Rand.Value < 0.5f) + if (Rand.Value < 0.5) { randomCell.x = cellRect.minX - 1; } @@ -282,7 +348,7 @@ public static IntVec3 RandomAdjacentCellCardinal(this Thing t) randomCell.x = cellRect.maxX + 1; } } - else if (Rand.Value < 0.5f) + else if (Rand.Value < 0.5) { randomCell.z = cellRect.minZ - 1; } @@ -302,14 +368,14 @@ public static bool TryFindRandomAdjacentCell8WayWithRoomGroup(IntVec3 center, Ro { GenAdj.AdjustForRotation(ref center, ref size, rot); GenAdj.validCells.Clear(); - foreach (IntVec3 current in GenAdj.CellsAdjacent8Way(center, rot, size)) + foreach (IntVec3 item in GenAdj.CellsAdjacent8Way(center, rot, size)) { - if (current.InBounds(map) && current.GetRoomGroup(map) != null) + if (item.InBounds(map) && item.GetRoomGroup(map) != null) { - GenAdj.validCells.Add(current); + GenAdj.validCells.Add(item); } } - return GenAdj.validCells.TryRandomElement(out result); + return ((IEnumerable)GenAdj.validCells).TryRandomElement(out result); } public static bool AdjacentTo8WayOrInside(this IntVec3 me, LocalTargetInfo other) @@ -363,36 +429,36 @@ public static bool IsAdjacentToCardinalOrInside(this Thing t1, Thing t2) int maxX = cellRect.maxX; int minZ = cellRect.minZ; int maxZ = cellRect.maxZ; - int i = minX; - int j = minZ; - while (i <= maxX) + int num = minX; + int num2 = minZ; + while (num <= maxX) { - if (cellRect2.Contains(new IntVec3(i, 0, j)) && (i != minX || j != minZ) && (i != minX || j != maxZ) && (i != maxX || j != minZ) && (i != maxX || j != maxZ)) + if (cellRect2.Contains(new IntVec3(num, 0, num2)) && (num != minX || num2 != minZ) && (num != minX || num2 != maxZ) && (num != maxX || num2 != minZ) && (num != maxX || num2 != maxZ)) { return true; } - i++; + num++; } - i--; - for (j++; j <= maxZ; j++) + num--; + for (num2++; num2 <= maxZ; num2++) { - if (cellRect2.Contains(new IntVec3(i, 0, j)) && (i != minX || j != minZ) && (i != minX || j != maxZ) && (i != maxX || j != minZ) && (i != maxX || j != maxZ)) + if (cellRect2.Contains(new IntVec3(num, 0, num2)) && (num != minX || num2 != minZ) && (num != minX || num2 != maxZ) && (num != maxX || num2 != minZ) && (num != maxX || num2 != maxZ)) { return true; } } - j--; - for (i--; i >= minX; i--) + num2--; + for (num--; num >= minX; num--) { - if (cellRect2.Contains(new IntVec3(i, 0, j)) && (i != minX || j != minZ) && (i != minX || j != maxZ) && (i != maxX || j != minZ) && (i != maxX || j != maxZ)) + if (cellRect2.Contains(new IntVec3(num, 0, num2)) && (num != minX || num2 != minZ) && (num != minX || num2 != maxZ) && (num != maxX || num2 != minZ) && (num != maxX || num2 != maxZ)) { return true; } } - i++; - for (j--; j > minZ; j--) + num++; + for (num2--; num2 > minZ; num2--) { - if (cellRect2.Contains(new IntVec3(i, 0, j)) && (i != minX || j != minZ) && (i != minX || j != maxZ) && (i != maxX || j != minZ) && (i != maxX || j != maxZ)) + if (cellRect2.Contains(new IntVec3(num, 0, num2)) && (num != minX || num2 != minZ) && (num != minX || num2 != maxZ) && (num != maxX || num2 != minZ) && (num != maxX || num2 != maxZ)) { return true; } @@ -412,7 +478,11 @@ public static bool AdjacentTo8WayOrInside(this IntVec3 root, IntVec3 center, Rot int num2 = center.z - (size.z - 1) / 2 - 1; int num3 = num + size.x + 1; int num4 = num2 + size.z + 1; - return root.x >= num && root.x <= num3 && root.z >= num2 && root.z <= num4; + if (root.x >= num && root.x <= num3 && root.z >= num2 && root.z <= num4) + { + return true; + } + return false; } public static bool IsInside(this IntVec3 root, Thing t) @@ -427,7 +497,11 @@ public static bool IsInside(IntVec3 root, IntVec3 center, Rot4 rot, IntVec2 size int num2 = center.z - (size.z - 1) / 2; int num3 = num + size.x - 1; int num4 = num2 + size.z - 1; - return root.x >= num && root.x <= num3 && root.z >= num2 && root.z <= num4; + if (root.x >= num && root.x <= num3 && root.z >= num2 && root.z <= num4) + { + return true; + } + return false; } public static CellRect OccupiedRect(this Thing t) @@ -444,9 +518,7 @@ public static CellRect OccupiedRect(IntVec3 center, Rot4 rot, IntVec2 size) public static void AdjustForRotation(ref IntVec3 center, ref IntVec2 size, Rot4 rot) { if (size.x == 1 && size.z == 1) - { return; - } if (rot.IsHorizontal) { int x = size.x; @@ -456,12 +528,15 @@ public static void AdjustForRotation(ref IntVec3 center, ref IntVec2 size, Rot4 switch (rot.AsInt) { case 1: + { if (size.z % 2 == 0) { center.z--; } break; + } case 2: + { if (size.x % 2 == 0) { center.x--; @@ -471,13 +546,18 @@ public static void AdjustForRotation(ref IntVec3 center, ref IntVec2 size, Rot4 center.z--; } break; + } case 3: + { if (size.x % 2 == 0) { center.x--; } break; } + case 0: + return; + } } } } diff --git a/Assembly-CSharp/Verse/GenAdjFast.cs b/Assembly-CSharp/Verse/GenAdjFast.cs index b364517b4..6f63c6480 100644 --- a/Assembly-CSharp/Verse/GenAdjFast.cs +++ b/Assembly-CSharp/Verse/GenAdjFast.cs @@ -57,30 +57,34 @@ public static List AdjacentCells8Way(IntVec3 thingCenter, Rot4 thingRot int num3 = thingCenter.z - (thingSize.z - 1) / 2 - 1; int num4 = num3 + thingSize.z + 1; IntVec3 item = new IntVec3(num - 1, 0, num3); - do + while (true) { item.x++; GenAdjFast.resultList.Add(item); + if (item.x >= num2) + break; } - while (item.x < num2); - do + while (true) { item.z++; GenAdjFast.resultList.Add(item); + if (item.z >= num4) + break; } - while (item.z < num4); - do + while (true) { item.x--; GenAdjFast.resultList.Add(item); + if (item.x <= num) + break; } - while (item.x > num); - do + while (true) { item.z--; GenAdjFast.resultList.Add(item); + if (item.z <= num3 + 1) + break; } - while (item.z > num3 + 1); GenAdjFast.working = false; return GenAdjFast.resultList; } @@ -88,20 +92,19 @@ public static List AdjacentCells8Way(IntVec3 thingCenter, Rot4 thingRot public static void AdjacentThings8Way(Thing thing, List outThings) { outThings.Clear(); - if (!thing.Spawned) + if (thing.Spawned) { - return; - } - Map map = thing.Map; - List list = GenAdjFast.AdjacentCells8Way(thing); - for (int i = 0; i < list.Count; i++) - { - List thingList = list[i].GetThingList(map); - for (int j = 0; j < thingList.Count; j++) + Map map = thing.Map; + List list = GenAdjFast.AdjacentCells8Way(thing); + for (int i = 0; i < list.Count; i++) { - if (!outThings.Contains(thingList[j])) + List thingList = list[i].GetThingList(map); + for (int j = 0; j < thingList.Count; j++) { - outThings.Add(thingList[j]); + if (!outThings.Contains(thingList[j])) + { + outThings.Add(thingList[j]); + } } } } diff --git a/Assembly-CSharp/Verse/GenAttribute.cs b/Assembly-CSharp/Verse/GenAttribute.cs index ad7760adf..e1dc5d5ae 100644 --- a/Assembly-CSharp/Verse/GenAttribute.cs +++ b/Assembly-CSharp/Verse/GenAttribute.cs @@ -1,4 +1,5 @@ using System; +using System.Collections.Generic; using System.Linq; using System.Reflection; @@ -8,19 +9,19 @@ public static class GenAttribute { public static bool HasAttribute(this MemberInfo memberInfo) where T : Attribute { - T t; - return memberInfo.TryGetAttribute(out t); + T val = default(T); + return memberInfo.TryGetAttribute(out val); } public static bool TryGetAttribute(this MemberInfo memberInfo, out T customAttribute) where T : Attribute { - object obj = memberInfo.GetCustomAttributes(typeof(T), true).FirstOrDefault(); + object obj = ((IEnumerable)memberInfo.GetCustomAttributes(typeof(T), true)).FirstOrDefault(); if (obj == null) { - customAttribute = (T)((object)null); + customAttribute = (T)null; return false; } - customAttribute = (T)((object)obj); + customAttribute = (T)obj; return true; } } diff --git a/Assembly-CSharp/Verse/GenClamor.cs b/Assembly-CSharp/Verse/GenClamor.cs index b5171556d..49570aee0 100644 --- a/Assembly-CSharp/Verse/GenClamor.cs +++ b/Assembly-CSharp/Verse/GenClamor.cs @@ -1,4 +1,3 @@ -using System; using System.Collections.Generic; namespace Verse @@ -9,23 +8,22 @@ public static void DoClamor(Pawn source, float radius, ClamorType type) { IntVec3 root = source.Position; Region region = source.GetRegion(RegionType.Set_Passable); - if (region == null) + if (region != null) { - return; - } - RegionTraverser.BreadthFirstTraverse(region, (Region from, Region r) => r.portal == null || r.portal.Open, delegate(Region r) - { - List list = r.ListerThings.ThingsInGroup(ThingRequestGroup.Pawn); - for (int i = 0; i < list.Count; i++) + RegionTraverser.BreadthFirstTraverse(region, (RegionEntryPredicate)((Region from, Region r) => r.portal == null || r.portal.Open), (RegionProcessor)delegate(Region r) { - Pawn pawn = list[i] as Pawn; - if (pawn.Position.InHorDistOf(root, radius)) + List list = r.ListerThings.ThingsInGroup(ThingRequestGroup.Pawn); + for (int i = 0; i < list.Count; i++) { - pawn.HearClamor(source, type); + Pawn pawn = list[i] as Pawn; + if (pawn.Position.InHorDistOf(root, radius)) + { + pawn.HearClamor(source, type); + } } - } - return false; - }, 15, RegionType.Set_Passable); + return false; + }, 15, RegionType.Set_Passable); + } } } } diff --git a/Assembly-CSharp/Verse/GenClosest.cs b/Assembly-CSharp/Verse/GenClosest.cs index 7fda79205..855c7e264 100644 --- a/Assembly-CSharp/Verse/GenClosest.cs +++ b/Assembly-CSharp/Verse/GenClosest.cs @@ -19,19 +19,21 @@ private static bool EarlyOutSearch(IntVec3 start, Map map, ThingRequest thingReq } if (!start.InBounds(map)) { - Log.Error(string.Concat(new object[] - { - "Did FindClosestThing with start out of bounds (", - start, - "), thingReq=", - thingReq - })); + Log.Error("Did FindClosestThing with start out of bounds (" + start + "), thingReq=" + thingReq); + return true; + } + if (thingReq.group == ThingRequestGroup.Nothing) + { return true; } - return thingReq.group == ThingRequestGroup.Nothing || (customGlobalSearchSet == null && !thingReq.IsUndefined && map.listerThings.ThingsMatching(thingReq).Count == 0); + if (customGlobalSearchSet == null && !thingReq.IsUndefined && map.listerThings.ThingsMatching(thingReq).Count == 0) + { + return true; + } + return false; } - public static Thing ClosestThingReachable(IntVec3 root, Map map, ThingRequest thingReq, PathEndMode peMode, TraverseParms traverseParams, float maxDistance = 9999f, Predicate validator = null, IEnumerable customGlobalSearchSet = null, int searchRegionsMin = 0, int searchRegionsMax = -1, bool forceGlobalSearch = false, RegionType traversableRegionTypes = RegionType.Set_Passable, bool ignoreEntirelyForbiddenRegions = false) + public static Thing ClosestThingReachable(IntVec3 root, Map map, ThingRequest thingReq, PathEndMode peMode, TraverseParms traverseParams, float maxDistance = 9999, Predicate validator = null, IEnumerable customGlobalSearchSet = null, int searchRegionsMin = 0, int searchRegionsMax = -1, bool forceGlobalSearch = false, RegionType traversableRegionTypes = RegionType.Set_Passable, bool ignoreEntirelyForbiddenRegions = false) { ProfilerThreadCheck.BeginSample("ClosestThingReachable"); if (searchRegionsMax > 0 && customGlobalSearchSet != null && !forceGlobalSearch) @@ -55,7 +57,18 @@ public static Thing ClosestThingReachable(IntVec3 root, Map map, ThingRequest th { Log.ErrorOnce("ClosestThingReachable had to do a global search, but traversableRegionTypes is not set to passable only. It's not supported, because Reachability is based on passable regions only.", 14384767); } - Predicate validator2 = (Thing t) => map.reachability.CanReach(root, t, peMode, traverseParams) && (validator == null || validator(t)); + Predicate validator2 = (Predicate)delegate(Thing t) + { + if (!map.reachability.CanReach(root, t, peMode, traverseParams)) + { + return false; + } + if ((object)validator != null && !validator(t)) + { + return false; + } + return true; + }; IEnumerable searchSet = customGlobalSearchSet ?? map.listerThings.ThingsMatching(thingReq); thing = GenClosest.ClosestThing_Global(root, searchSet, maxDistance, validator2); } @@ -63,7 +76,7 @@ public static Thing ClosestThingReachable(IntVec3 root, Map map, ThingRequest th return thing; } - public static Thing ClosestThing_Regionwise_ReachablePrioritized(IntVec3 root, Map map, ThingRequest thingReq, PathEndMode peMode, TraverseParms traverseParams, float maxDistance = 9999f, Predicate validator = null, Func priorityGetter = null, int minRegions = 24, int maxRegions = 30) + public static Thing ClosestThing_Regionwise_ReachablePrioritized(IntVec3 root, Map map, ThingRequest thingReq, PathEndMode peMode, TraverseParms traverseParams, float maxDistance = 9999, Predicate validator = null, Func priorityGetter = null, int minRegions = 24, int maxRegions = 30) { if (GenClosest.EarlyOutSearch(root, map, thingReq, null)) { @@ -98,12 +111,19 @@ public static Thing RegionwiseBFSWorker(IntVec3 root, Map map, ThingRequest req, return null; } float maxDistSquared = maxDistance * maxDistance; - RegionEntryPredicate entryCondition = (Region from, Region to) => to.Allows(traverseParams, false) && (maxDistance > 5000f || to.extentsClose.ClosestDistSquaredTo(root) < maxDistSquared); + RegionEntryPredicate entryCondition = (RegionEntryPredicate)delegate(Region from, Region to) + { + if (!to.Allows(traverseParams, false)) + { + return false; + } + return maxDistance > 5000.0 || to.extentsClose.ClosestDistSquaredTo(root) < maxDistSquared; + }; Thing closestThing = null; float closestDistSquared = 9999999f; float bestPrio = -3.40282347E+38f; int regionsSeen = 0; - RegionProcessor regionProcessor = delegate(Region r) + RegionProcessor regionProcessor = (RegionProcessor)delegate(Region r) { if (r.portal == null && !r.Allows(traverseParams, true)) { @@ -117,11 +137,11 @@ public static Thing RegionwiseBFSWorker(IntVec3 root, Map map, ThingRequest req, Thing thing = list[i]; if (ReachabilityWithinRegion.ThingFromRegionListerReachable(thing, r, peMode, traverseParams.pawn)) { - float num = (priorityGetter == null) ? 0f : priorityGetter(thing); - if (num >= bestPrio) + float num = (float)(((object)priorityGetter == null) ? 0.0 : priorityGetter(thing)); + if (!(num < bestPrio)) { float num2 = (float)(thing.Position - root).LengthHorizontalSquared; - if ((num > bestPrio || num2 < closestDistSquared) && num2 < maxDistSquared && (validator == null || validator(thing))) + if ((num > bestPrio || num2 < closestDistSquared) && num2 < maxDistSquared && ((object)validator == null || validator(thing))) { closestThing = thing; closestDistSquared = num2; @@ -139,7 +159,7 @@ public static Thing RegionwiseBFSWorker(IntVec3 root, Map map, ThingRequest req, return closestThing; } - public static Thing ClosestThing_Global(IntVec3 center, IEnumerable searchSet, float maxDistance = 99999f, Predicate validator = null) + public static Thing ClosestThing_Global(IntVec3 center, IEnumerable searchSet, float maxDistance = 99999, Predicate validator = null) { ProfilerThreadCheck.BeginSample("ClosestThing_Global"); if (searchSet == null) @@ -149,22 +169,22 @@ public static Thing ClosestThing_Global(IntVec3 center, IEnumerable searchSet, f float num = 2.14748365E+09f; Thing result = null; float num2 = maxDistance * maxDistance; - foreach (Thing thing in searchSet) + foreach (Thing item in searchSet) { - float num3 = (float)(center - thing.Position).LengthHorizontalSquared; + float num3 = (float)(center - item.Position).LengthHorizontalSquared; if (num3 < num && num3 <= num2) { ProfilerThreadCheck.BeginSample("validator"); - if (validator != null && !validator(thing)) + if ((object)validator != null && !validator(item)) { ProfilerThreadCheck.EndSample(); } else { ProfilerThreadCheck.EndSample(); - if (thing.Spawned) + if (item.Spawned) { - result = thing; + result = item; num = num3; } } @@ -174,7 +194,7 @@ public static Thing ClosestThing_Global(IntVec3 center, IEnumerable searchSet, f return result; } - public static Thing ClosestThing_Global_Reachable(IntVec3 center, Map map, IEnumerable searchSet, PathEndMode peMode, TraverseParms traverseParams, float maxDistance = 9999f, Predicate validator = null, Func priorityGetter = null) + public static Thing ClosestThing_Global_Reachable(IntVec3 center, Map map, IEnumerable searchSet, PathEndMode peMode, TraverseParms traverseParams, float maxDistance = 9999, Predicate validator = null, Func priorityGetter = null) { ProfilerThreadCheck.BeginSample("ClosestThing_Global_Reachable"); if (searchSet == null) @@ -188,45 +208,31 @@ public static Thing ClosestThing_Global_Reachable(IntVec3 center, Map map, IEnum float num4 = 0f; float num5 = maxDistance * maxDistance; float num6 = 2.14748365E+09f; - foreach (Thing current in searchSet) + foreach (Thing item in searchSet) { num2++; - float num7 = (float)(center - current.Position).LengthHorizontalSquared; - if (num7 <= num5) + float num7 = (float)(center - item.Position).LengthHorizontalSquared; + if (!(num7 > num5)) { - if (priorityGetter != null) + if ((object)priorityGetter == null) { - num4 = priorityGetter(current); - if (num4 < num3) - { - continue; - } - } - if (num4 > num3 || num7 < num6) - { - if (map.reachability.CanReach(center, current, peMode, traverseParams)) - { - if (current.Spawned) - { - if (validator == null || validator(current)) - { - result = current; - num6 = num7; - num3 = num4; - num++; - } - } - } + goto IL_0093; } + num4 = priorityGetter(item); + if (!(num4 < num3)) + goto IL_0093; + } + continue; + IL_0093: + if ((num4 > num3 || num7 < num6) && map.reachability.CanReach(center, item, peMode, traverseParams) && item.Spawned && ((object)validator == null || validator(item))) + { + result = item; + num6 = num7; + num3 = num4; + num++; } } - ProfilerThreadCheck.BeginSample(string.Concat(new object[] - { - "changedCount: ", - num, - " scanCount: ", - num2 - })); + ProfilerThreadCheck.BeginSample("changedCount: " + num + " scanCount: " + num2); ProfilerThreadCheck.EndSample(); ProfilerThreadCheck.EndSample(); return result; diff --git a/Assembly-CSharp/Verse/GenCollection.cs b/Assembly-CSharp/Verse/GenCollection.cs index 5a8189f9e..bd7b1670a 100644 --- a/Assembly-CSharp/Verse/GenCollection.cs +++ b/Assembly-CSharp/Verse/GenCollection.cs @@ -1,7 +1,6 @@ using System; using System.Collections; using System.Collections.Generic; -using System.Diagnostics; using System.Linq; namespace Verse @@ -10,20 +9,38 @@ public static class GenCollection { public static bool SharesElementWith(this IEnumerable source, IEnumerable other) { - return source.Any((T item) => other.Contains(item)); + return source.Any((Func)((T item) => ((IEnumerable)other).Contains(item))); } - [DebuggerHidden] public static IEnumerable InRandomOrder(this IEnumerable source, IList workingList = null) { - GenCollection.c__Iterator248 c__Iterator = new GenCollection.c__Iterator248(); - c__Iterator.source = source; - c__Iterator.workingList = workingList; - c__Iterator.<$>source = source; - c__Iterator.<$>workingList = workingList; - GenCollection.c__Iterator248 expr_23 = c__Iterator; - expr_23.$PC = -2; - return expr_23; + if (source == null) + { + throw new ArgumentNullException("source"); + } + if (workingList == null) + { + workingList = source.ToList(); + } + else + { + ((ICollection)workingList).Clear(); + foreach (T item in source) + { + ((ICollection)workingList).Add(item); + } + } + int countUnChosen = ((ICollection)workingList).Count; + int rand2 = 0; + while (countUnChosen > 0) + { + rand2 = Rand.Range(0, countUnChosen); + yield return workingList[rand2]; + T temp = workingList[rand2]; + workingList[rand2] = workingList[countUnChosen - 1]; + workingList[countUnChosen - 1] = temp; + countUnChosen--; + } } public static T RandomElement(this IEnumerable source) @@ -37,18 +54,18 @@ public static T RandomElement(this IEnumerable source) { list = source.ToList(); } - if (list.Count == 0) + if (((ICollection)list).Count == 0) { Log.Warning("Getting random element from empty collection."); return default(T); } - return list[Rand.Range(0, list.Count)]; + return list[Rand.Range(0, ((ICollection)list).Count)]; } - public static T RandomElementWithFallback(this IEnumerable source, T fallback = null) + public static T RandomElementWithFallback(this IEnumerable source, T fallback = default(T)) { - T result; - if (source.TryRandomElement(out result)) + T result = default(T); + if (source.TryRandomElement(out result)) { return result; } @@ -64,7 +81,7 @@ public static bool TryRandomElement(this IEnumerable source, out T result) IList list = source as IList; if (list != null) { - if (list.Count == 0) + if (((ICollection)list).Count == 0) { result = default(T); return false; @@ -85,23 +102,17 @@ public static T RandomElementByWeight(this IEnumerable source, Func list = source as IList; if (list != null) { - for (int i = 0; i < list.Count; i++) + for (int i = 0; i < ((ICollection)list).Count; i++) { float num2 = weightSelector(list[i]); - if (num2 < 0f) + if (num2 < 0.0) { - Log.Error(string.Concat(new object[] - { - "Negative weight in selector: ", - num2, - " from ", - list[i] - })); + Log.Error("Negative weight in selector: " + num2 + " from " + list[i]); num2 = 0f; } num += num2; } - if (list.Count == 1 && num > 0f) + if (((ICollection)list).Count == 1 && num > 0.0) { return list[0]; } @@ -109,29 +120,23 @@ public static T RandomElementByWeight(this IEnumerable source, Func 0f) + if (num3 == 1 && num > 0.0) { return source.First(); } } - if (num <= 0f) + if (num <= 0.0) { Log.Error("RandomElementByWeight with totalWeight=" + num + " - use TryRandomElementByWeight."); return default(T); @@ -140,10 +145,10 @@ public static T RandomElementByWeight(this IEnumerable source, Func)list).Count; j++) { float num7 = weightSelector(list[j]); - if (num7 > 0f) + if (!(num7 <= 0.0)) { num6 += num7; if (num6 >= num5) @@ -155,15 +160,15 @@ public static T RandomElementByWeight(this IEnumerable source, Func 0f) + float num8 = weightSelector(item2); + if (!(num8 <= 0.0)) { num6 += num8; if (num6 >= num5) { - return current2; + return item2; } } } @@ -171,10 +176,10 @@ public static T RandomElementByWeight(this IEnumerable source, Func(this IEnumerable source, Func weightSelector, T fallback = null) + public static T RandomElementByWeightWithFallback(this IEnumerable source, Func weightSelector, T fallback = default(T)) { - T result; - if (source.TryRandomElementByWeight(weightSelector, out result)) + T result = default(T); + if (source.TryRandomElementByWeight(weightSelector, out result)) { return result; } @@ -187,23 +192,17 @@ public static bool TryRandomElementByWeight(this IEnumerable source, Func< IList list = source as IList; if (list != null) { - for (int i = 0; i < list.Count; i++) + for (int i = 0; i < ((ICollection)list).Count; i++) { float num2 = weightSelector(list[i]); - if (num2 < 0f) + if (num2 < 0.0) { - Log.Error(string.Concat(new object[] - { - "Negative weight in selector: ", - num2, - " from ", - list[i] - })); + Log.Error("Negative weight in selector: " + num2 + " from " + list[i]); num2 = 0f; } num += num2; } - if (list.Count == 1 && num > 0f) + if (((ICollection)list).Count == 1 && num > 0.0) { result = list[0]; return true; @@ -212,30 +211,24 @@ public static bool TryRandomElementByWeight(this IEnumerable source, Func< else { int num3 = 0; - foreach (T current in source) + foreach (T item in source) { num3++; - float num4 = weightSelector(current); - if (num4 < 0f) + float num4 = weightSelector(item); + if (num4 < 0.0) { - Log.Error(string.Concat(new object[] - { - "Negative weight in selector: ", - num4, - " from ", - current - })); + Log.Error("Negative weight in selector: " + num4 + " from " + item); num4 = 0f; } num += num4; } - if (num3 == 1 && num > 0f) + if (num3 == 1 && num > 0.0) { result = source.First(); return true; } } - if (num <= 0f) + if (num <= 0.0) { result = default(T); return false; @@ -244,10 +237,10 @@ public static bool TryRandomElementByWeight(this IEnumerable source, Func< float num6 = 0f; if (list != null) { - for (int j = 0; j < list.Count; j++) + for (int j = 0; j < ((ICollection)list).Count; j++) { float num7 = weightSelector(list[j]); - if (num7 > 0f) + if (!(num7 <= 0.0)) { num6 += num7; if (num6 >= num5) @@ -260,15 +253,15 @@ public static bool TryRandomElementByWeight(this IEnumerable source, Func< } else { - foreach (T current2 in source) + foreach (T item2 in source) { - float num8 = weightSelector(current2); - if (num8 > 0f) + float num8 = weightSelector(item2); + if (!(num8 <= 0.0)) { num6 += num8; if (num6 >= num5) { - result = current2; + result = item2; return true; } } @@ -280,49 +273,43 @@ public static bool TryRandomElementByWeight(this IEnumerable source, Func< public static T RandomElementByWeightWithDefault(this IEnumerable source, Func weightSelector, float defaultValueWeight) { - if (defaultValueWeight < 0f) + if (defaultValueWeight < 0.0) { Log.Error("Negative default value weight."); defaultValueWeight = 0f; } float num = 0f; - foreach (T current in source) + foreach (T item in source) { - float num2 = weightSelector(current); - if (num2 < 0f) + float num2 = weightSelector(item); + if (num2 < 0.0) { - Log.Error(string.Concat(new object[] - { - "Negative weight in selector: ", - num2, - " from ", - current - })); + Log.Error("Negative weight in selector: " + num2 + " from " + item); num2 = 0f; } num += num2; } float num3 = defaultValueWeight + num; - if (num3 <= 0f) + if (num3 <= 0.0) { Log.Error("RandomElementByWeightWithDefault with totalWeight=" + num3); return default(T); } - if (Rand.Value < defaultValueWeight / num3 || num == 0f) + if (!(Rand.Value < defaultValueWeight / num3) && num != 0.0) { - return default(T); + return source.RandomElementByWeight(weightSelector); } - return source.RandomElementByWeight(weightSelector); + return default(T); } public static T RandomEnumValue() { - return Enum.GetValues(typeof(T)).Cast().RandomElement(); + return ((IEnumerable)Enum.GetValues(typeof(T))).Cast().RandomElement(); } public static TSource MaxBy(this IEnumerable source, Func selector) { - return source.MaxBy(selector, Comparer.Default); + return source.MaxBy(selector, (IComparer)Comparer.Default); } public static TSource MaxBy(this IEnumerable source, Func selector, IComparer comparer) @@ -331,7 +318,7 @@ public static TSource MaxBy(this IEnumerable source, Fun { throw new ArgumentNullException("source"); } - if (selector == null) + if ((object)selector == null) { throw new ArgumentNullException("selector"); } @@ -339,42 +326,43 @@ public static TSource MaxBy(this IEnumerable source, Fun { throw new ArgumentNullException("comparer"); } - TSource result; using (IEnumerator enumerator = source.GetEnumerator()) { if (!enumerator.MoveNext()) { throw new InvalidOperationException("Sequence contains no elements"); } - TSource tSource = enumerator.Current; - TKey y = selector(tSource); + TSource val = enumerator.Current; + TKey y = selector(val); while (enumerator.MoveNext()) { TSource current = enumerator.Current; - TKey tKey = selector(current); - if (comparer.Compare(tKey, y) > 0) + TKey val2 = selector(current); + if (comparer.Compare(val2, y) > 0) { - tSource = current; - y = tKey; + val = current; + y = val2; } } - result = tSource; + return val; + IL_009b: + TSource result; + return result; } - return result; } - public static TSource MaxByWithFallback(this IEnumerable source, Func selector, TSource fallback = null) + public static TSource MaxByWithFallback(this IEnumerable source, Func selector, TSource fallback = default(TSource)) { - return source.MaxByWithFallback(selector, Comparer.Default, fallback); + return source.MaxByWithFallback(selector, (IComparer)Comparer.Default, fallback); } - public static TSource MaxByWithFallback(this IEnumerable source, Func selector, IComparer comparer, TSource fallback = null) + public static TSource MaxByWithFallback(this IEnumerable source, Func selector, IComparer comparer, TSource fallback = default(TSource)) { if (source == null) { throw new ArgumentNullException("source"); } - if (selector == null) + if ((object)selector == null) { throw new ArgumentNullException("selector"); } @@ -382,36 +370,34 @@ public static TSource MaxByWithFallback(this IEnumerable { throw new ArgumentNullException("comparer"); } - TSource result; using (IEnumerator enumerator = source.GetEnumerator()) { if (!enumerator.MoveNext()) { - result = fallback; + return fallback; } - else + TSource val = enumerator.Current; + TKey y = selector(val); + while (enumerator.MoveNext()) { - TSource tSource = enumerator.Current; - TKey y = selector(tSource); - while (enumerator.MoveNext()) + TSource current = enumerator.Current; + TKey val2 = selector(current); + if (comparer.Compare(val2, y) > 0) { - TSource current = enumerator.Current; - TKey tKey = selector(current); - if (comparer.Compare(tKey, y) > 0) - { - tSource = current; - y = tKey; - } + val = current; + y = val2; } - result = tSource; } + return val; + IL_0098: + TSource result; + return result; } - return result; } public static TSource MinBy(this IEnumerable source, Func selector) { - return source.MinBy(selector, Comparer.Default); + return source.MinBy(selector, (IComparer)Comparer.Default); } public static TSource MinBy(this IEnumerable source, Func selector, IComparer comparer) @@ -420,7 +406,7 @@ public static TSource MinBy(this IEnumerable source, Fun { throw new ArgumentNullException("source"); } - if (selector == null) + if ((object)selector == null) { throw new ArgumentNullException("selector"); } @@ -428,126 +414,121 @@ public static TSource MinBy(this IEnumerable source, Fun { throw new ArgumentNullException("comparer"); } - TSource result; using (IEnumerator enumerator = source.GetEnumerator()) { if (!enumerator.MoveNext()) { throw new InvalidOperationException("Sequence contains no elements"); } - TSource tSource = enumerator.Current; - TKey y = selector(tSource); + TSource val = enumerator.Current; + TKey y = selector(val); while (enumerator.MoveNext()) { TSource current = enumerator.Current; - TKey tKey = selector(current); - if (comparer.Compare(tKey, y) < 0) + TKey val2 = selector(current); + if (comparer.Compare(val2, y) < 0) { - tSource = current; - y = tKey; + val = current; + y = val2; } } - result = tSource; + return val; + IL_009b: + TSource result; + return result; } - return result; } public static void SortBy(this List list, Func selector) where TSortBy : IComparable { - if (list.Count <= 1) + if (list.Count > 1) { - return; + list.Sort((Comparison)((T a, T b) => ((IComparable)selector(a)).CompareTo(selector(b)))); } - list.Sort(delegate(T a, T b) - { - TSortBy tSortBy = selector(a); - return tSortBy.CompareTo(selector(b)); - }); } public static void SortBy(this List list, Func selector, Func thenBySelector) where TSortBy : IComparable, IEquatable where TThenBy : IComparable { - if (list.Count <= 1) - { - return; - } - list.Sort(delegate(T a, T b) + if (list.Count > 1) { - TSortBy tSortBy = selector(a); - TSortBy other = selector(b); - if (!tSortBy.Equals(other)) + list.Sort((Comparison)delegate(T a, T b) { - return tSortBy.CompareTo(other); - } - TThenBy tThenBy = thenBySelector(a); - return tThenBy.CompareTo(thenBySelector(b)); - }); + TSortBy val = selector(a); + TSortBy other = selector(b); + if (!((IEquatable)val).Equals(other)) + { + return ((IComparable)val).CompareTo(other); + } + return ((IComparable)thenBySelector(a)).CompareTo(thenBySelector(b)); + }); + } } public static void SortByDescending(this List list, Func selector) where TSortByDescending : IComparable { - if (list.Count <= 1) + if (list.Count > 1) { - return; + list.Sort((Comparison)((T a, T b) => ((IComparable)selector(b)).CompareTo(selector(a)))); } - list.Sort(delegate(T a, T b) - { - TSortByDescending tSortByDescending = selector(b); - return tSortByDescending.CompareTo(selector(a)); - }); } public static void SortByDescending(this List list, Func selector, Func thenByDescendingSelector) where TSortByDescending : IComparable, IEquatable where TThenByDescending : IComparable { - if (list.Count <= 1) - { - return; - } - list.Sort(delegate(T a, T b) + if (list.Count > 1) { - TSortByDescending other = selector(a); - TSortByDescending other2 = selector(b); - if (!other.Equals(other2)) + list.Sort((Comparison)delegate(T a, T b) { - return other2.CompareTo(other); - } - TThenByDescending tThenByDescending = thenByDescendingSelector(b); - return tThenByDescending.CompareTo(thenByDescendingSelector(a)); - }); + TSortByDescending other = selector(a); + TSortByDescending other2 = selector(b); + if (!((IEquatable)other).Equals(other2)) + { + return ((IComparable)other2).CompareTo(other); + } + return ((IComparable)thenByDescendingSelector(b)).CompareTo(thenByDescendingSelector(a)); + }); + } } public static int RemoveAll(this Dictionary dictionary, Predicate> predicate) { List list = null; - int result; try { - foreach (KeyValuePair current in dictionary) + Dictionary.Enumerator enumerator = dictionary.GetEnumerator(); + try { - if (predicate(current)) + while (enumerator.MoveNext()) { - if (list == null) + KeyValuePair current = enumerator.Current; + if (predicate(current)) { - list = SimplePool>.Get(); + if (list == null) + { + list = SimplePool>.Get(); + } + list.Add(current.Key); } - list.Add(current.Key); } } + finally + { + ((IDisposable)(object)enumerator).Dispose(); + } if (list != null) { - int i = 0; + int num = 0; int count = list.Count; - while (i < count) + while (num < count) { - dictionary.Remove(list[i]); - i++; + dictionary.Remove(list[num]); + num++; } - result = list.Count; - } - else - { - result = 0; + return list.Count; } + return 0; + IL_009c: + int result; + return result; } finally { @@ -557,7 +538,6 @@ public static int RemoveAll(this Dictionary dictiona SimplePool>.Return(list); } } - return result; } public static void RemoveAll(this List list, Func predicate) @@ -568,20 +548,19 @@ public static void RemoveAll(this List list, Func predicate) { num++; } - if (num >= count) - { - return; - } - int i = num + 1; - while (i < count) + if (num < count) { - while (i < count && predicate(list[i], i)) + int num2 = num + 1; + while (num2 < count) { - i++; - } - if (i < count) - { - list[num++] = list[i++]; + while (num2 < count && predicate(list[num2], num2)) + { + num2++; + } + if (num2 < count) + { + list[num++] = list[num2++]; + } } } } @@ -613,18 +592,18 @@ public static float AverageWeighted(this IEnumerable list, Func { float num = 0f; float num2 = 0f; - foreach (T current in list) + foreach (T item in list) { - float num3 = weight(current); + float num3 = weight(item); num += num3; - num2 += value(current) * num3; + num2 += value(item) * num3; } return num2 / num; } public static void ExecuteEnumerable(this IEnumerable enumerable) { - foreach (object current in enumerable) + foreach (object item in enumerable) { } } @@ -632,15 +611,24 @@ public static void ExecuteEnumerable(this IEnumerable enumerable) public static int FirstIndexOf(this IEnumerable enumerable, Func predicate) { int num = 0; - foreach (T current in enumerable) + using (IEnumerator enumerator = enumerable.GetEnumerator()) { - if (predicate(current)) + while (true) { - break; + if (enumerator.MoveNext()) + { + T current = enumerator.Current; + if (!predicate(current)) + { + num++; + continue; + } + break; + } + return num; } - num++; + return num; } - return num; } } } diff --git a/Assembly-CSharp/Verse/GenColor.cs b/Assembly-CSharp/Verse/GenColor.cs index c846bfff3..b9d8ea055 100644 --- a/Assembly-CSharp/Verse/GenColor.cs +++ b/Assembly-CSharp/Verse/GenColor.cs @@ -1,4 +1,3 @@ -using System; using System.Globalization; using UnityEngine; @@ -8,20 +7,20 @@ public static class GenColor { public static Color SaturationChanged(this Color col, float change) { - float num = col.r; - float num2 = col.g; - float num3 = col.b; - float num4 = Mathf.Sqrt(num * num * 0.299f + num2 * num2 * 0.587f + num3 * num3 * 0.114f); - num = num4 + (num - num4) * change; - num2 = num4 + (num2 - num4) * change; - num3 = num4 + (num3 - num4) * change; - return new Color(num, num2, num3); + float r = col.r; + float g = col.g; + float b = col.b; + float num = Mathf.Sqrt((float)(r * r * 0.29899999499320984 + g * g * 0.58700001239776611 + b * b * 0.11400000005960464)); + r = num + (r - num) * change; + g = num + (g - num) * change; + b = num + (b - num) * change; + return new Color(r, g, b); } public static bool IndistinguishableFrom(this Color colA, Color colB) { Color color = colA - colB; - return Mathf.Abs(color.r) + Mathf.Abs(color.g) + Mathf.Abs(color.b) + Mathf.Abs(color.a) < 0.001f; + return Mathf.Abs(color.r) + Mathf.Abs(color.g) + Mathf.Abs(color.b) + Mathf.Abs(color.a) < 0.0010000000474974513; } public static Color RandomColorOpaque() @@ -33,10 +32,10 @@ public static Color FromBytes(int r, int g, int b, int a = 255) { return new Color { - r = (float)r / 255f, - g = (float)g / 255f, - b = (float)b / 255f, - a = (float)a / 255f + r = (float)((float)r / 255.0), + g = (float)((float)g / 255.0), + b = (float)((float)b / 255.0), + a = (float)((float)a / 255.0) }; } diff --git a/Assembly-CSharp/Verse/GenCommandLine.cs b/Assembly-CSharp/Verse/GenCommandLine.cs index 3651605ea..914eeb950 100644 --- a/Assembly-CSharp/Verse/GenCommandLine.cs +++ b/Assembly-CSharp/Verse/GenCommandLine.cs @@ -10,12 +10,15 @@ public static class GenCommandLine public static bool CommandLineArgPassed(string key) { string[] commandLineArgs = Environment.GetCommandLineArgs(); - for (int i = 0; i < commandLineArgs.Length; i++) + int num = 0; + while (num < commandLineArgs.Length) { - if (string.Compare(commandLineArgs[i], key, true) == 0 || string.Compare(commandLineArgs[i], "-" + key, true) == 0) + if (((string.Compare(commandLineArgs[num], key, true) != 0) ? string.Compare(commandLineArgs[num], "-" + key, true) : 0) != 0) { - return true; + num++; + continue; } + return true; } return false; } @@ -27,21 +30,15 @@ public static bool TryGetCommandLineArg(string key, out string value) { if (commandLineArgs[i].Contains('=')) { - string[] array = commandLineArgs[i].Split(new char[] - { - '=' - }); - if (array.Length == 2) + string[] array = commandLineArgs[i].Split('='); + if (array.Length == 2 && (string.Compare(array[0], key, true) == 0 || string.Compare(array[0], "-" + key, true) == 0)) { - if (string.Compare(array[0], key, true) == 0 || string.Compare(array[0], "-" + key, true) == 0) - { - value = array[1]; - return true; - } + value = array[1]; + return true; } } } - value = null; + value = (string)null; return false; } @@ -60,12 +57,11 @@ public static void Restart() } text2 = text2 + "\"" + commandLineArgs[i].Replace("\"", "\\\"") + "\""; } - new Process - { - StartInfo = new ProcessStartInfo(commandLineArgs[0], text2) - }.Start(); + Process process = new Process(); + process.StartInfo = new ProcessStartInfo(commandLineArgs[0], text2); + process.Start(); Root.Shutdown(); - LongEventHandler.QueueLongEvent(delegate + LongEventHandler.QueueLongEvent((Action)delegate { Thread.Sleep(10000); }, "Restarting", true, null); @@ -73,7 +69,7 @@ public static void Restart() catch (Exception arg) { Log.Error("Error restarting: " + arg); - Find.WindowStack.Add(new Dialog_MessageBox("FailedToRestart".Translate(), null, null, null, null, null, false)); + Find.WindowStack.Add(new Dialog_MessageBox("FailedToRestart".Translate(), (string)null, null, (string)null, null, (string)null, false)); } } } diff --git a/Assembly-CSharp/Verse/GenDebug.cs b/Assembly-CSharp/Verse/GenDebug.cs index 63b774e9b..48fa4f4fd 100644 --- a/Assembly-CSharp/Verse/GenDebug.cs +++ b/Assembly-CSharp/Verse/GenDebug.cs @@ -16,28 +16,37 @@ public static void DebugPlaceSphere(Vector3 Loc, float Scale) public static void LogList(IEnumerable list) { - foreach (T current in list) + foreach (T item in list) { - Log.Message(" " + current.ToString()); + Log.Message(" " + item.ToString()); } } public static void ClearArea(CellRect r, Map map) { r.ClipInsideMap(map); - foreach (IntVec3 current in r) + foreach (IntVec3 item in r) { - map.roofGrid.SetRoof(current, null); + map.roofGrid.SetRoof(item, null); } - foreach (IntVec3 current2 in r) + foreach (IntVec3 item2 in r) { - foreach (Thing current3 in current2.GetThingList(map).ToList()) + List.Enumerator enumerator3 = item2.GetThingList(map).ToList().GetEnumerator(); + try { - if (current3.def.destroyable) + while (enumerator3.MoveNext()) { - current3.Destroy(DestroyMode.Vanish); + Thing current3 = enumerator3.Current; + if (current3.def.destroyable) + { + current3.Destroy(DestroyMode.Vanish); + } } } + finally + { + ((IDisposable)(object)enumerator3).Dispose(); + } } } } diff --git a/Assembly-CSharp/Verse/GenDefDatabase.cs b/Assembly-CSharp/Verse/GenDefDatabase.cs index 02b6d5182..1003214e2 100644 --- a/Assembly-CSharp/Verse/GenDefDatabase.cs +++ b/Assembly-CSharp/Verse/GenDefDatabase.cs @@ -1,6 +1,6 @@ using System; +using System.Collections; using System.Collections.Generic; -using System.Diagnostics; using System.Linq; namespace Verse @@ -9,11 +9,7 @@ public static class GenDefDatabase { public static Def GetDef(Type defType, string defName, bool errorOnFail = true) { - return (Def)GenGeneric.InvokeStaticMethodOnGenericType(typeof(DefDatabase<>), defType, "GetNamed", new object[] - { - defName, - errorOnFail - }); + return (Def)GenGeneric.InvokeStaticMethodOnGenericType(typeof(DefDatabase<>), defType, "GetNamed", defName, errorOnFail); } public static Def GetDefSilentFail(Type type, string targetDefName) @@ -22,24 +18,38 @@ public static Def GetDefSilentFail(Type type, string targetDefName) { return SoundDef.Named(targetDefName); } - return (Def)GenGeneric.InvokeStaticMethodOnGenericType(typeof(DefDatabase<>), type, "GetNamedSilentFail", new object[] - { - targetDefName - }); + return (Def)GenGeneric.InvokeStaticMethodOnGenericType(typeof(DefDatabase<>), type, "GetNamedSilentFail", targetDefName); } - [DebuggerHidden] public static IEnumerable AllDefTypesWithDatabases() { - GenDefDatabase.c__Iterator1C1 c__Iterator1C = new GenDefDatabase.c__Iterator1C1(); - GenDefDatabase.c__Iterator1C1 expr_07 = c__Iterator1C; - expr_07.$PC = -2; - return expr_07; + foreach (Type item in typeof(Def).AllSubclasses()) + { + if (!item.IsAbstract && item != typeof(Def)) + { + bool foundNonAbstractAncestor = false; + Type parent = item.BaseType; + while (parent != null && parent != typeof(Def)) + { + if (parent.IsAbstract) + { + parent = parent.BaseType; + continue; + } + foundNonAbstractAncestor = true; + break; + } + if (!foundNonAbstractAncestor) + { + yield return item; + } + } + } } public static IEnumerable DefsToGoInDatabase(ModContentPack mod) { - return mod.AllDefs.OfType(); + return ((IEnumerable)mod.AllDefs).OfType(); } } } diff --git a/Assembly-CSharp/Verse/GenDictionary.cs b/Assembly-CSharp/Verse/GenDictionary.cs index 754d0e597..1c508fe74 100644 --- a/Assembly-CSharp/Verse/GenDictionary.cs +++ b/Assembly-CSharp/Verse/GenDictionary.cs @@ -9,14 +9,18 @@ public static class GenDictionary public static string ToStringFullContents(this Dictionary dict) { StringBuilder stringBuilder = new StringBuilder(); - foreach (KeyValuePair current in dict) + Dictionary.Enumerator enumerator = dict.GetEnumerator(); + try { - StringBuilder arg_50_0 = stringBuilder; - K key = current.Key; - string arg_4B_0 = key.ToString(); - string arg_4B_1 = ": "; - V value = current.Value; - arg_50_0.AppendLine(arg_4B_0 + arg_4B_1 + value.ToString()); + while (enumerator.MoveNext()) + { + KeyValuePair current = enumerator.Current; + stringBuilder.AppendLine(current.Key.ToString() + ": " + current.Value.ToString()); + } + } + finally + { + ((IDisposable)(object)enumerator).Dispose(); } return stringBuilder.ToString(); } diff --git a/Assembly-CSharp/Verse/GenDraw.cs b/Assembly-CSharp/Verse/GenDraw.cs index fe8f9064a..0b16d0188 100644 --- a/Assembly-CSharp/Verse/GenDraw.cs +++ b/Assembly-CSharp/Verse/GenDraw.cs @@ -94,9 +94,9 @@ public static Color CurTargetingColor { get { - float num = (float)Math.Sin((double)(Time.time * 8f)); - num *= 0.2f; - num += 0.8f; + float num = (float)Math.Sin(Time.time * 8.0); + num = (float)(num * 0.20000000298023224); + num = (float)(num + 0.800000011920929); return new Color(1f, num, num); } } @@ -136,51 +136,64 @@ public static void DrawLineBetween(Vector3 A, Vector3 B, SimpleColor color) switch (color) { case SimpleColor.White: + { mat = GenDraw.LineMatWhite; break; + } case SimpleColor.Red: + { mat = GenDraw.LineMatRed; break; + } case SimpleColor.Green: + { mat = GenDraw.LineMatGreen; break; + } case SimpleColor.Blue: + { mat = GenDraw.LineMatBlue; break; + } case SimpleColor.Magenta: + { mat = GenDraw.LineMatMagenta; break; + } case SimpleColor.Yellow: + { mat = GenDraw.LineMatYellow; break; + } case SimpleColor.Cyan: + { mat = GenDraw.LineMatCyan; break; + } default: + { mat = GenDraw.LineMatWhite; break; } + } GenDraw.DrawLineBetween(A, B, mat); } public static void DrawLineBetween(Vector3 A, Vector3 B, Material mat) { - if (Mathf.Abs(A.x - B.x) < 0.01f && Mathf.Abs(A.z - B.z) < 0.01f) - { + if (Mathf.Abs(A.x - B.x) < 0.0099999997764825821 && Mathf.Abs(A.z - B.z) < 0.0099999997764825821) return; - } Vector3 pos = (A + B) / 2f; - if (A == B) + if (!(A == B)) { - return; + A.y = B.y; + float z = (A - B).MagnitudeHorizontal(); + Quaternion q = Quaternion.LookRotation(A - B); + Vector3 s = new Vector3(0.2f, 1f, z); + Matrix4x4 matrix = default(Matrix4x4); + matrix.SetTRS(pos, q, s); + Graphics.DrawMesh(MeshPool.plane10, matrix, mat, 0); } - A.y = B.y; - float z = (A - B).MagnitudeHorizontal(); - Quaternion q = Quaternion.LookRotation(A - B); - Vector3 s = new Vector3(0.2f, 1f, z); - Matrix4x4 matrix = default(Matrix4x4); - matrix.SetTRS(pos, q, s); - Graphics.DrawMesh(MeshPool.plane10, matrix, mat, 0); } public static void DrawWorldLineBetween(Vector3 A, Vector3 B) @@ -195,14 +208,12 @@ public static void DrawWorldLineBetween(Vector3 A, Vector3 B, Material material) public static void DrawWorldLineBetween(Vector3 A, Vector3 B, Material material, float widthFactor) { - if (Mathf.Abs(A.x - B.x) < 0.005f && Mathf.Abs(A.y - B.y) < 0.005f && Mathf.Abs(A.z - B.z) < 0.005f) - { + if (Mathf.Abs(A.x - B.x) < 0.004999999888241291 && Mathf.Abs(A.y - B.y) < 0.004999999888241291 && Mathf.Abs(A.z - B.z) < 0.004999999888241291) return; - } Vector3 pos = (A + B) / 2f; float magnitude = (A - B).magnitude; Quaternion q = Quaternion.LookRotation(A - B, pos.normalized); - Vector3 s = new Vector3(0.2f * Find.WorldGrid.averageTileSize * widthFactor, 1f, magnitude); + Vector3 s = new Vector3((float)(0.20000000298023224 * Find.WorldGrid.averageTileSize * widthFactor), 1f, magnitude); Matrix4x4 matrix = default(Matrix4x4); matrix.SetTRS(pos, q, s); Graphics.DrawMesh(MeshPool.plane10, matrix, material, WorldCameraManager.WorldLayer); @@ -210,68 +221,66 @@ public static void DrawWorldLineBetween(Vector3 A, Vector3 B, Material material, public static void DrawWorldRadiusRing(int center, int radius) { - if (radius < 0) - { - return; - } - if (GenDraw.cachedEdgeTilesForCenter != center || GenDraw.cachedEdgeTilesForRadius != radius || GenDraw.cachedEdgeTilesForWorldSeed != Find.World.info.Seed) + if (radius >= 0) { - GenDraw.cachedEdgeTilesForCenter = center; - GenDraw.cachedEdgeTilesForRadius = radius; - GenDraw.cachedEdgeTilesForWorldSeed = Find.World.info.Seed; - GenDraw.cachedEdgeTiles.Clear(); - Find.WorldFloodFiller.FloodFill(center, (int tile) => true, delegate(int tile, int dist) - { - if (dist > radius + 1) - { - return true; - } - if (dist == radius + 1) - { - GenDraw.cachedEdgeTiles.Add(tile); - } - return false; - }, 2147483647); - WorldGrid worldGrid = Find.WorldGrid; - Vector3 c = worldGrid.GetTileCenter(center); - Vector3 n = c.normalized; - GenDraw.cachedEdgeTiles.Sort(delegate(int a, int b) + if (GenDraw.cachedEdgeTilesForCenter != center || GenDraw.cachedEdgeTilesForRadius != radius || GenDraw.cachedEdgeTilesForWorldSeed != Find.World.info.Seed) { - float num = Vector3.Dot(n, Vector3.Cross(worldGrid.GetTileCenter(a) - c, worldGrid.GetTileCenter(b) - c)); - if (Mathf.Abs(num) < 0.0001f) + GenDraw.cachedEdgeTilesForCenter = center; + GenDraw.cachedEdgeTilesForRadius = radius; + GenDraw.cachedEdgeTilesForWorldSeed = Find.World.info.Seed; + GenDraw.cachedEdgeTiles.Clear(); + Find.WorldFloodFiller.FloodFill(center, (Predicate)((int tile) => true), (Func)delegate(int tile, int dist) { - return 0; - } - if (num < 0f) + if (dist > radius + 1) + { + return true; + } + if (dist == radius + 1) + { + GenDraw.cachedEdgeTiles.Add(tile); + } + return false; + }, 2147483647); + WorldGrid worldGrid = Find.WorldGrid; + Vector3 c = worldGrid.GetTileCenter(center); + Vector3 i = c.normalized; + GenDraw.cachedEdgeTiles.Sort((Comparison)delegate(int a, int b) { - return -1; - } - return 1; - }); + float num = Vector3.Dot(i, Vector3.Cross(worldGrid.GetTileCenter(a) - c, worldGrid.GetTileCenter(b) - c)); + if (Mathf.Abs(num) < 9.9999997473787516E-05) + { + return 0; + } + if (num < 0.0) + { + return -1; + } + return 1; + }); + } + GenDraw.DrawWorldLineStrip(GenDraw.cachedEdgeTiles, GenDraw.OneSidedWorldLineMatWhite, 5f); } - GenDraw.DrawWorldLineStrip(GenDraw.cachedEdgeTiles, GenDraw.OneSidedWorldLineMatWhite, 5f); } public static void DrawWorldLineStrip(List edgeTiles, Material material, float widthFactor) { - if (edgeTiles.Count < 3) - { - return; - } - WorldGrid worldGrid = Find.WorldGrid; - float d = 0.05f; - for (int i = 0; i < edgeTiles.Count; i++) + if (edgeTiles.Count >= 3) { - int index = (i != 0) ? (i - 1) : (edgeTiles.Count - 1); - int num = edgeTiles[index]; - int num2 = edgeTiles[i]; - if (worldGrid.IsNeighbor(num, num2)) + WorldGrid worldGrid = Find.WorldGrid; + float d = 0.05f; + for (int i = 0; i < edgeTiles.Count; i++) { - Vector3 a = worldGrid.GetTileCenter(num); - Vector3 vector = worldGrid.GetTileCenter(num2); - a += a.normalized * d; - vector += vector.normalized * d; - GenDraw.DrawWorldLineBetween(a, vector, material, widthFactor); + int index = (i != 0) ? (i - 1) : (edgeTiles.Count - 1); + int num = edgeTiles[index]; + int num2 = edgeTiles[i]; + if (worldGrid.IsNeighbor(num, num2)) + { + Vector3 a = worldGrid.GetTileCenter(num); + Vector3 vector = worldGrid.GetTileCenter(num2); + a += a.normalized * d; + vector += vector.normalized * d; + GenDraw.DrawWorldLineBetween(a, vector, material, widthFactor); + } } } } @@ -322,15 +331,17 @@ public static void DrawRadiusRing(IntVec3 center, float radius) Log.Error("Cannot draw radius ring of radius " + radius + ": not enough squares in the precalculated list."); GenDraw.maxRadiusMessaged = true; } - return; } - GenDraw.ringDrawCells.Clear(); - int num = GenRadial.NumCellsInRadius(radius); - for (int i = 0; i < num; i++) + else { - GenDraw.ringDrawCells.Add(center + GenRadial.RadialPattern[i]); + GenDraw.ringDrawCells.Clear(); + int num = GenRadial.NumCellsInRadius(radius); + for (int num2 = 0; num2 < num; num2++) + { + GenDraw.ringDrawCells.Add(center + GenRadial.RadialPattern[num2]); + } + GenDraw.DrawFieldEdges(GenDraw.ringDrawCells); } - GenDraw.DrawFieldEdges(GenDraw.ringDrawCells); } public static void DrawFieldEdges(List cells) @@ -356,33 +367,36 @@ public static void DrawFieldEdges(List cells, Color color) { GenDraw.fieldGrid.ClearAndResizeTo(visibleMap); } - int x = visibleMap.Size.x; - int z = visibleMap.Size.z; + IntVec3 size = visibleMap.Size; + int x = size.x; + IntVec3 size2 = visibleMap.Size; + int z = size2.z; int count = cells.Count; - for (int i = 0; i < count; i++) + for (int num = 0; num < count; num++) { - if (cells[i].InBounds(visibleMap)) + if (cells[num].InBounds(visibleMap)) { - GenDraw.fieldGrid[cells[i].x, cells[i].z] = true; + BoolGrid obj = GenDraw.fieldGrid; + IntVec3 intVec = cells[num]; + int x2 = intVec.x; + IntVec3 intVec2 = cells[num]; + obj[x2, intVec2.z] = true; } } - for (int j = 0; j < count; j++) + for (int num2 = 0; num2 < count; num2++) { - IntVec3 c = cells[j]; + IntVec3 c = cells[num2]; if (c.InBounds(visibleMap)) { GenDraw.rotNeeded[0] = (c.z < z - 1 && !GenDraw.fieldGrid[c.x, c.z + 1]); GenDraw.rotNeeded[1] = (c.x < x - 1 && !GenDraw.fieldGrid[c.x + 1, c.z]); GenDraw.rotNeeded[2] = (c.z > 0 && !GenDraw.fieldGrid[c.x, c.z - 1]); GenDraw.rotNeeded[3] = (c.x > 0 && !GenDraw.fieldGrid[c.x - 1, c.z]); - for (int k = 0; k < 4; k++) + for (int i = 0; i < 4; i++) { - if (GenDraw.rotNeeded[k]) + if (GenDraw.rotNeeded[i]) { - Mesh arg_219_0 = MeshPool.plane10; - Vector3 arg_219_1 = c.ToVector3ShiftedWithAltitude(AltitudeLayer.MetaOverlays); - Rot4 rot = new Rot4(k); - Graphics.DrawMesh(arg_219_0, arg_219_1, rot.AsQuat, material, 0); + Graphics.DrawMesh(MeshPool.plane10, c.ToVector3ShiftedWithAltitude(AltitudeLayer.MetaOverlays), new Rot4(i).AsQuat, material, 0); } } } @@ -394,30 +408,22 @@ public static void DrawAimPie(Thing shooter, LocalTargetInfo target, int degrees float facing = 0f; if (target.Cell != shooter.Position) { - if (target.Thing != null) - { - facing = (target.Thing.DrawPos - shooter.Position.ToVector3Shifted()).AngleFlat(); - } - else - { - facing = (target.Cell - shooter.Position).AngleFlat; - } + facing = ((target.Thing == null) ? (target.Cell - shooter.Position).AngleFlat : (target.Thing.DrawPos - shooter.Position.ToVector3Shifted()).AngleFlat()); } GenDraw.DrawAimPieRaw(shooter.DrawPos + new Vector3(0f, offsetDist, 0f), facing, degreesWide); } public static void DrawAimPieRaw(Vector3 center, float facing, int degreesWide) { - if (degreesWide <= 0) + if (degreesWide > 0) { - return; - } - if (degreesWide > 360) - { - degreesWide = 360; + if (degreesWide > 360) + { + degreesWide = 360; + } + center += Quaternion.AngleAxis(facing, Vector3.up) * Vector3.forward * 0.8f; + Graphics.DrawMesh(MeshPool.pies[degreesWide], center, Quaternion.AngleAxis((float)(facing + (float)(degreesWide / 2) - 90.0), Vector3.up), GenDraw.AimPieMaterial, 0); } - center += Quaternion.AngleAxis(facing, Vector3.up) * Vector3.forward * 0.8f; - Graphics.DrawMesh(MeshPool.pies[degreesWide], center, Quaternion.AngleAxis(facing + (float)(degreesWide / 2) - 90f, Vector3.up), GenDraw.AimPieMaterial, 0); } public static void DrawCooldownCircle(Vector3 center, float radius) @@ -428,7 +434,7 @@ public static void DrawCooldownCircle(Vector3 center, float radius) Graphics.DrawMesh(MeshPool.circle, matrix, GenDraw.AimPieMaterial, 0); } - public static void DrawFillableBar(GenDraw.FillableBarRequest r) + public static void DrawFillableBar(FillableBarRequest r) { Vector2 vector = r.preRotationOffset.RotatedBy(r.rotation.AsAngle); r.center += new Vector3(vector.x, 0f, vector.y); @@ -444,20 +450,20 @@ public static void DrawFillableBar(GenDraw.FillableBarRequest r) Matrix4x4 matrix = default(Matrix4x4); matrix.SetTRS(r.center, r.rotation.AsQuat, s); Graphics.DrawMesh(MeshPool.plane10, matrix, r.unfilledMat, 0); - if (r.fillPercent > 0.001f) + if (r.fillPercent > 0.0010000000474974513) { s = new Vector3(r.size.x * r.fillPercent, 1f, r.size.y); matrix = default(Matrix4x4); Vector3 pos = r.center + Vector3.up * 0.01f; if (!r.rotation.IsHorizontal) { - pos.x -= r.size.x * 0.5f; - pos.x += 0.5f * r.size.x * r.fillPercent; + pos.x -= (float)(r.size.x * 0.5); + pos.x += (float)(0.5 * r.size.x * r.fillPercent); } else { - pos.z -= r.size.x * 0.5f; - pos.z += 0.5f * r.size.x * r.fillPercent; + pos.z -= (float)(r.size.x * 0.5); + pos.z += (float)(0.5 * r.size.x * r.fillPercent); } matrix.SetTRS(pos, r.rotation.AsQuat, s); Graphics.DrawMesh(MeshPool.plane10, matrix, r.filledMat, 0); @@ -480,7 +486,7 @@ public static void DrawMeshNowOrLater(Mesh mesh, Vector3 loc, Quaternion quat, M public static void DrawArrowPointingAt(Vector3 mapTarget, bool offscreenOnly = false) { Vector3 vector = UI.UIToMapPosition((float)(UI.screenWidth / 2), (float)(UI.screenHeight / 2)); - if ((vector - mapTarget).MagnitudeHorizontalSquared() < 81f) + if ((vector - mapTarget).MagnitudeHorizontalSquared() < 81.0) { if (!offscreenOnly) { diff --git a/Assembly-CSharp/Verse/GenDrop.cs b/Assembly-CSharp/Verse/GenDrop.cs index 4253440b6..3225b9146 100644 --- a/Assembly-CSharp/Verse/GenDrop.cs +++ b/Assembly-CSharp/Verse/GenDrop.cs @@ -15,13 +15,7 @@ public static bool TryDropSpawn(Thing thing, IntVec3 dropCell, Map map, ThingPla } if (!dropCell.InBounds(map)) { - Log.Error(string.Concat(new object[] - { - "Dropped ", - thing, - " out of bounds at ", - dropCell - })); + Log.Error("Dropped " + thing + " out of bounds at " + dropCell); resultingThing = null; return false; } diff --git a/Assembly-CSharp/Verse/GenExplosion.cs b/Assembly-CSharp/Verse/GenExplosion.cs index 0cf407119..bbad19afe 100644 --- a/Assembly-CSharp/Verse/GenExplosion.cs +++ b/Assembly-CSharp/Verse/GenExplosion.cs @@ -1,5 +1,4 @@ using RimWorld; -using System; using System.Collections.Generic; using System.Linq; @@ -14,52 +13,53 @@ public static void DoExplosion(IntVec3 center, Map map, float radius, DamageDef if (map == null) { Log.Warning("Tried to do explosion in a null map."); - return; } - Explosion explosion = new Explosion(); - explosion.position = center; - explosion.radius = radius; - explosion.damType = damType; - explosion.instigator = instigator; - explosion.damAmount = ((projectile == null) ? GenMath.RoundRandom((float)damType.explosionDamage) : projectile.projectile.damageAmountBase); - explosion.weaponGear = source; - explosion.preExplosionSpawnThingDef = preExplosionSpawnThingDef; - explosion.preExplosionSpawnChance = preExplosionSpawnChance; - explosion.preExplosionSpawnThingCount = preExplosionSpawnThingCount; - explosion.postExplosionSpawnThingDef = postExplosionSpawnThingDef; - explosion.postExplosionSpawnChance = postExplosionSpawnChance; - explosion.postExplosionSpawnThingCount = postExplosionSpawnThingCount; - explosion.applyDamageToExplosionCellsNeighbors = applyDamageToExplosionCellsNeighbors; - map.GetComponent().StartExplosion(explosion, explosionSound); + else + { + Explosion explosion = new Explosion(); + explosion.position = center; + explosion.radius = radius; + explosion.damType = damType; + explosion.instigator = instigator; + explosion.damAmount = ((projectile == null) ? GenMath.RoundRandom((float)damType.explosionDamage) : projectile.projectile.damageAmountBase); + explosion.weaponGear = source; + explosion.preExplosionSpawnThingDef = preExplosionSpawnThingDef; + explosion.preExplosionSpawnChance = preExplosionSpawnChance; + explosion.preExplosionSpawnThingCount = preExplosionSpawnThingCount; + explosion.postExplosionSpawnThingDef = postExplosionSpawnThingDef; + explosion.postExplosionSpawnChance = postExplosionSpawnChance; + explosion.postExplosionSpawnThingCount = postExplosionSpawnThingCount; + explosion.applyDamageToExplosionCellsNeighbors = applyDamageToExplosionCellsNeighbors; + map.GetComponent().StartExplosion(explosion, explosionSound); + } } public static void RenderPredictedAreaOfEffect(IntVec3 loc, float radius) { - GenDraw.DrawFieldEdges(DamageDefOf.Bomb.Worker.ExplosionCellsToHit(loc, Find.VisibleMap, radius).ToList()); + GenDraw.DrawFieldEdges(DamageDefOf.Bomb.Worker.ExplosionCellsToHit(loc, Find.VisibleMap, radius).ToList()); } public static void NotifyNearbyPawnsOfDangerousExplosive(Thing exploder, DamageDef damage, Faction onlyFaction = null) { - if (!damage.externalViolence) - { - return; - } - Room room = exploder.GetRoom(RegionType.Set_Passable); - for (int i = 0; i < GenExplosion.PawnNotifyCellCount; i++) + if (damage.externalViolence) { - IntVec3 c = exploder.Position + GenRadial.RadialPattern[i]; - if (c.InBounds(exploder.Map)) + Room room = exploder.GetRoom(RegionType.Set_Passable); + for (int i = 0; i < GenExplosion.PawnNotifyCellCount; i++) { - List thingList = c.GetThingList(exploder.Map); - for (int j = 0; j < thingList.Count; j++) + IntVec3 c = exploder.Position + GenRadial.RadialPattern[i]; + if (c.InBounds(exploder.Map)) { - Pawn pawn = thingList[j] as Pawn; - if (pawn != null && pawn.RaceProps.intelligence >= Intelligence.Humanlike && (onlyFaction == null || pawn.Faction == onlyFaction)) + List thingList = c.GetThingList(exploder.Map); + for (int j = 0; j < thingList.Count; j++) { - Room room2 = pawn.GetRoom(RegionType.Set_Passable); - if (room2 == null || room2.CellCount == 1 || (room2 == room && GenSight.LineOfSight(exploder.Position, pawn.Position, exploder.Map, true, null, 0, 0))) + Pawn pawn = thingList[j] as Pawn; + if (pawn != null && (int)pawn.RaceProps.intelligence >= 2 && (onlyFaction == null || pawn.Faction == onlyFaction)) { - pawn.mindState.Notify_DangerousExploderAboutToExplode(exploder); + Room room2 = pawn.GetRoom(RegionType.Set_Passable); + if (room2 == null || room2.CellCount == 1 || (room2 == room && GenSight.LineOfSight(exploder.Position, pawn.Position, exploder.Map, true, null, 0, 0))) + { + pawn.mindState.Notify_DangerousExploderAboutToExplode(exploder); + } } } } diff --git a/Assembly-CSharp/Verse/GenFile.cs b/Assembly-CSharp/Verse/GenFile.cs index 8bd4f3079..4eb46b887 100644 --- a/Assembly-CSharp/Verse/GenFile.cs +++ b/Assembly-CSharp/Verse/GenFile.cs @@ -1,6 +1,4 @@ -using System; using System.Collections.Generic; -using System.Diagnostics; using System.IO; using UnityEngine; @@ -16,36 +14,33 @@ public static string TextFromRawFile(string filePath) public static string TextFromResourceFile(string filePath) { TextAsset textAsset = Resources.Load("Text/" + filePath) as TextAsset; - if (textAsset == null) + if ((Object)textAsset == (Object)null) { Log.Message("Found no text asset in resources at " + filePath); - return null; + return (string)null; } return GenFile.GetTextWithoutBOM(textAsset); } public static string GetTextWithoutBOM(TextAsset textAsset) { - string result = null; - using (MemoryStream memoryStream = new MemoryStream(textAsset.bytes)) + string text = (string)null; + using (MemoryStream stream = new MemoryStream(textAsset.bytes)) { - using (StreamReader streamReader = new StreamReader(memoryStream, true)) + using (StreamReader streamReader = new StreamReader(stream, true)) { - result = streamReader.ReadToEnd(); + return streamReader.ReadToEnd(); } } - return result; } - [DebuggerHidden] public static IEnumerable LinesFromFile(string filePath) { - GenFile.c__Iterator249 c__Iterator = new GenFile.c__Iterator249(); - c__Iterator.filePath = filePath; - c__Iterator.<$>filePath = filePath; - GenFile.c__Iterator249 expr_15 = c__Iterator; - expr_15.$PC = -2; - return expr_15; + string rawText = GenFile.TextFromResourceFile(filePath); + foreach (string item in GenText.LinesFromString(rawText)) + { + yield return item; + } } public static void DirectoryCopy(string sourceDirName, string destDirName, bool copySubDirs) @@ -60,11 +55,11 @@ public static void DirectoryCopy(string sourceDirName, string destDirName, bool { Directory.CreateDirectory(destDirName); } - FileInfo[] files = directoryInfo.GetFiles(); - FileInfo[] array = files; - for (int i = 0; i < array.Length; i++) + FileInfo[] files; + FileInfo[] array = files = directoryInfo.GetFiles(); + for (int i = 0; i < files.Length; i++) { - FileInfo fileInfo = array[i]; + FileInfo fileInfo = files[i]; string destFileName = Path.Combine(destDirName, fileInfo.Name); fileInfo.CopyTo(destFileName, false); } diff --git a/Assembly-CSharp/Verse/GenFilePaths.cs b/Assembly-CSharp/Verse/GenFilePaths.cs index 32d2ec254..d6685970c 100644 --- a/Assembly-CSharp/Verse/GenFilePaths.cs +++ b/Assembly-CSharp/Verse/GenFilePaths.cs @@ -28,11 +28,11 @@ public static class GenFilePaths private const string SaveDataFolderCommand = "savedatafolder"; - private static string saveDataPath = null; + private static string saveDataPath = (string)null; - private static string coreModsFolderPath = null; + private static string coreModsFolderPath = (string)null; - private static readonly string[] FilePathRaw = new string[] + private static readonly string[] FilePathRaw = new string[73] { "Ž", "ž", @@ -44,7 +44,7 @@ public static class GenFilePaths "¥", "¦", "§", - "¨", + "\u00a8", "©", "ª", "À", @@ -109,7 +109,7 @@ public static class GenFilePaths "ÿ" }; - private static readonly string[] FilePathSafe = new string[] + private static readonly string[] FilePathSafe = new string[73] { "%8E", "%9E", @@ -192,14 +192,10 @@ public static string SaveDataFolderPath { if (GenFilePaths.saveDataPath == null) { - string text; + string text = default(string); if (GenCommandLine.TryGetCommandLineArg("savedatafolder", out text)) { - text.TrimEnd(new char[] - { - '\\', - '/' - }); + text.TrimEnd('\\', '/'); if (text == string.Empty) { text = string.Empty + Path.DirectorySeparatorChar; @@ -266,15 +262,7 @@ public static string CoreModsFolderPath if (GenFilePaths.coreModsFolderPath == null) { DirectoryInfo directoryInfo = new DirectoryInfo(UnityData.dataPath); - DirectoryInfo directoryInfo2; - if (UnityData.isEditor) - { - directoryInfo2 = directoryInfo; - } - else - { - directoryInfo2 = directoryInfo.Parent; - } + DirectoryInfo directoryInfo2 = (!UnityData.isEditor) ? directoryInfo.Parent : directoryInfo; GenFilePaths.coreModsFolderPath = Path.Combine(directoryInfo2.ToString(), "Mods"); if (UnityData.isDebugBuild) { @@ -498,23 +486,18 @@ public static string FolderPathRelativeToDefsFolder(string fullFolderPath, ModCo } if (!fullFolderPath.StartsWith(text)) { - Log.Error(string.Concat(new string[] - { - "Can't get relative path. Path \"", - fullFolderPath, - "\" does not start with \"", - text, - "\"." - })); - return null; + Log.Error("Can't get relative path. Path \"" + fullFolderPath + "\" does not start with \"" + text + "\"."); + return (string)null; } if (fullFolderPath == text) { return string.Empty; } string text2 = fullFolderPath.Substring(text.Length); - while (text2.StartsWith("/") || text2.StartsWith("\\")) + while (true) { + if (!text2.StartsWith("/") && !text2.StartsWith("\\")) + break; if (text2.Length == 1) { return string.Empty; diff --git a/Assembly-CSharp/Verse/GenGeneric.cs b/Assembly-CSharp/Verse/GenGeneric.cs index 77ea6262f..7d58a1c85 100644 --- a/Assembly-CSharp/Verse/GenGeneric.cs +++ b/Assembly-CSharp/Verse/GenGeneric.cs @@ -9,19 +9,13 @@ public static class GenGeneric private static MethodInfo MethodOnGenericType(Type genericBase, Type genericParam, string methodName) { - Type type = genericBase.MakeGenericType(new Type[] - { - genericParam - }); + Type type = genericBase.MakeGenericType(genericParam); return type.GetMethod(methodName, BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic); } public static void InvokeGenericMethod(object objectToInvoke, Type genericParam, string methodName, params object[] args) { - objectToInvoke.GetType().GetMethod(methodName, BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic).MakeGenericMethod(new Type[] - { - genericParam - }).Invoke(objectToInvoke, args); + objectToInvoke.GetType().GetMethod(methodName, BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic).MakeGenericMethod(genericParam).Invoke(objectToInvoke, args); } public static object InvokeStaticMethodOnGenericType(Type genericBase, Type genericParam, string methodName, params object[] args) @@ -36,19 +30,13 @@ public static object InvokeStaticMethodOnGenericType(Type genericBase, Type gene public static object InvokeStaticGenericMethod(Type baseClass, Type genericParam, string methodName) { - return baseClass.GetMethod(methodName, BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic).MakeGenericMethod(new Type[] - { - genericParam - }).Invoke(null, null); + return baseClass.GetMethod(methodName, BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic).MakeGenericMethod(genericParam).Invoke(null, null); } public static object InvokeStaticGenericMethod(Type baseClass, Type genericParam, string methodName, params object[] args) { MethodInfo method = baseClass.GetMethod(methodName, BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic); - MethodInfo methodInfo = method.MakeGenericMethod(new Type[] - { - genericParam - }); + MethodInfo methodInfo = method.MakeGenericMethod(genericParam); return methodInfo.Invoke(null, args); } diff --git a/Assembly-CSharp/Verse/GenGeo.cs b/Assembly-CSharp/Verse/GenGeo.cs index e7979c1e4..77fd4c548 100644 --- a/Assembly-CSharp/Verse/GenGeo.cs +++ b/Assembly-CSharp/Verse/GenGeo.cs @@ -7,31 +7,32 @@ public static class GenGeo { public static float AngleDifferenceBetween(float A, float B) { - float num = A + 360f; - float num2 = B + 360f; + float num = (float)(A + 360.0); + float num2 = (float)(B + 360.0); float num3 = 9999f; - float num4 = A - B; - if (num4 < 0f) + float num4 = 0f; + num4 = A - B; + if (num4 < 0.0) { - num4 *= -1f; + num4 = (float)(num4 * -1.0); } if (num4 < num3) { num3 = num4; } num4 = num - B; - if (num4 < 0f) + if (num4 < 0.0) { - num4 *= -1f; + num4 = (float)(num4 * -1.0); } if (num4 < num3) { num3 = num4; } num4 = A - num2; - if (num4 < 0f) + if (num4 < 0.0) { - num4 *= -1f; + num4 = (float)(num4 * -1.0); } if (num4 < num3) { @@ -59,13 +60,45 @@ public static bool LinesIntersect(Vector3 line1V1, Vector3 line1V2, Vector3 line float num5 = line2V1.x - line2V2.x; float num6 = num4 * line2V1.x + num5 * line2V1.z; float num7 = num * num5 - num4 * num2; - if (num7 == 0f) + if (num7 == 0.0) { return false; } float num8 = (num5 * num3 - num2 * num6) / num7; float num9 = (num * num6 - num4 * num3) / num7; - return (num8 <= line1V1.x || num8 <= line1V2.x) && (num8 <= line2V1.x || num8 <= line2V2.x) && (num8 >= line1V1.x || num8 >= line1V2.x) && (num8 >= line2V1.x || num8 >= line2V2.x) && (num9 <= line1V1.z || num9 <= line1V2.z) && (num9 <= line2V1.z || num9 <= line2V2.z) && (num9 >= line1V1.z || num9 >= line1V2.z) && (num9 >= line2V1.z || num9 >= line2V2.z); + if (num8 > line1V1.x && num8 > line1V2.x) + { + goto IL_017e; + } + if (num8 > line2V1.x && num8 > line2V2.x) + { + goto IL_017e; + } + if (num8 < line1V1.x && num8 < line1V2.x) + { + goto IL_017e; + } + if (num8 < line2V1.x && num8 < line2V2.x) + { + goto IL_017e; + } + if (num9 > line1V1.z && num9 > line1V2.z) + { + goto IL_017e; + } + if (num9 > line2V1.z && num9 > line2V2.z) + { + goto IL_017e; + } + if (num9 < line1V1.z && num9 < line1V2.z) + { + goto IL_017e; + } + if (num9 < line2V1.z && num9 < line2V2.z) + goto IL_017e; + return true; + IL_017e: + return false; } public static bool IntersectLineCircle(Vector2 center, float radius, Vector2 lineA, Vector2 lineB) @@ -75,11 +108,11 @@ public static bool IntersectLineCircle(Vector2 center, float radius, Vector2 lin float num = Vector2.Dot(vector, vector); float num2 = Vector2.Dot(lhs, vector); float num3 = num2 / num; - if (num3 < 0f) + if (num3 < 0.0) { num3 = 0f; } - else if (num3 > 1f) + else if (num3 > 1.0) { num3 = 1f; } @@ -96,29 +129,23 @@ public static Vector3 RegularPolygonVertexPositionVec3(int polygonVertices, int public static Vector2 RegularPolygonVertexPosition(int polygonVertices, int vertexIndex) { - if (vertexIndex < 0 || vertexIndex >= polygonVertices) + if (vertexIndex >= 0 && vertexIndex < polygonVertices) { - Log.Warning(string.Concat(new object[] + if (polygonVertices == 1) { - "Vertex index out of bounds. polygonVertices=", - polygonVertices, - " vertexIndex=", - vertexIndex - })); - return Vector2.zero; - } - if (polygonVertices == 1) - { - return Vector2.zero; + return Vector2.zero; + } + return GenGeo.CalculatePolygonVertexPosition(polygonVertices, vertexIndex); } - return GenGeo.CalculatePolygonVertexPosition(polygonVertices, vertexIndex); + Log.Warning("Vertex index out of bounds. polygonVertices=" + polygonVertices + " vertexIndex=" + vertexIndex); + return Vector2.zero; } private static Vector2 CalculatePolygonVertexPosition(int polygonVertices, int vertexIndex) { - float num = 6.28318548f / (float)polygonVertices; + float num = (float)(6.2831854820251465 / (float)polygonVertices); float num2 = num * (float)vertexIndex; - num2 += 3.14159274f; + num2 = (float)(num2 + 3.1415927410125732); return new Vector3(Mathf.Cos(num2), Mathf.Sin(num2)); } } diff --git a/Assembly-CSharp/Verse/GenGrid.cs b/Assembly-CSharp/Verse/GenGrid.cs index 9bed39761..5349206a1 100644 --- a/Assembly-CSharp/Verse/GenGrid.cs +++ b/Assembly-CSharp/Verse/GenGrid.cs @@ -1,5 +1,4 @@ using RimWorld; -using System; using System.Collections.Generic; using UnityEngine; @@ -23,12 +22,44 @@ public static bool InNoZoneEdgeArea(this IntVec3 c, Map map) public static bool CloseToEdge(this IntVec3 c, Map map, int edgeDist) { - return c.x < edgeDist || c.z < edgeDist || c.x >= map.Size.x - edgeDist || c.z >= map.Size.z - edgeDist; + int result; + if (c.x >= edgeDist && c.z >= edgeDist) + { + int x = c.x; + IntVec3 size = map.Size; + if (x < size.x - edgeDist) + { + int z = c.z; + IntVec3 size2 = map.Size; + result = ((z >= size2.z - edgeDist) ? 1 : 0); + goto IL_0055; + } + } + result = 1; + goto IL_0055; + IL_0055: + return (byte)result != 0; } public static bool OnEdge(this IntVec3 c, Map map) { - return c.x == 0 || c.x == map.Size.x - 1 || c.z == 0 || c.z == map.Size.z - 1; + int result; + if (c.x != 0) + { + int x = c.x; + IntVec3 size = map.Size; + if (((x != size.x - 1) ? c.z : 0) != 0) + { + int z = c.z; + IntVec3 size2 = map.Size; + result = ((z == size2.z - 1) ? 1 : 0); + goto IL_0050; + } + } + result = 1; + goto IL_0050; + IL_0050: + return (byte)result != 0; } public static bool OnEdge(this IntVec3 c, Map map, Rot4 dir) @@ -39,7 +70,9 @@ public static bool OnEdge(this IntVec3 c, Map map, Rot4 dir) } if (dir == Rot4.South) { - return c.z == map.Size.z - 1; + int z = c.z; + IntVec3 size = map.Size; + return z == size.z - 1; } if (dir == Rot4.West) { @@ -47,7 +80,9 @@ public static bool OnEdge(this IntVec3 c, Map map, Rot4 dir) } if (dir == Rot4.East) { - return c.x == map.Size.x - 1; + int x = c.x; + IntVec3 size2 = map.Size; + return x == size2.x - 1; } Log.ErrorOnce("Invalid edge direction", 55370769); return false; @@ -56,13 +91,13 @@ public static bool OnEdge(this IntVec3 c, Map map, Rot4 dir) public static bool InBounds(this IntVec3 c, Map map) { IntVec3 size = map.Size; - return (ulong)c.x < (ulong)((long)size.x) && (ulong)c.z < (ulong)((long)size.z); + return (uint)c.x < size.x && (uint)c.z < size.z; } public static bool InBounds(this Vector3 v, Map map) { IntVec3 size = map.Size; - return v.x >= 0f && v.z >= 0f && v.x < (float)size.x && v.z < (float)size.z; + return v.x >= 0.0 && v.z >= 0.0 && v.x < (float)size.x && v.z < (float)size.z; } public static bool Walkable(this IntVec3 c, Map map) @@ -79,7 +114,7 @@ public static bool Standable(this IntVec3 c, Map map) List list = map.thingGrid.ThingsListAt(c); for (int i = 0; i < list.Count; i++) { - if (list[i].def.passability != Traversability.Standable) + if (list[i].def.passability != 0) { return false; } @@ -112,13 +147,21 @@ public static bool CanBeSeenOver(this IntVec3 c, Map map) return false; } Building edifice = c.GetEdifice(map); - return edifice == null || edifice.CanBeSeenOver(); + if (edifice != null && !edifice.CanBeSeenOver()) + { + return false; + } + return true; } public static bool CanBeSeenOverFast(this IntVec3 c, Map map) { Building edifice = c.GetEdifice(map); - return edifice == null || edifice.CanBeSeenOver(); + if (edifice != null && !edifice.CanBeSeenOver()) + { + return false; + } + return true; } public static bool CanBeSeenOver(this Building b) @@ -126,7 +169,11 @@ public static bool CanBeSeenOver(this Building b) if (b.def.Fillage == FillCategory.Full) { Building_Door building_Door = b as Building_Door; - return building_Door != null && building_Door.Open; + if (building_Door != null && building_Door.Open) + { + return true; + } + return false; } return true; } @@ -140,7 +187,7 @@ public static SurfaceType GetSurfaceType(this IntVec3 c, Map map) List thingList = c.GetThingList(map); for (int i = 0; i < thingList.Count; i++) { - if (thingList[i].def.surfaceType != SurfaceType.None) + if (thingList[i].def.surfaceType != 0) { return thingList[i].def.surfaceType; } diff --git a/Assembly-CSharp/Verse/GenList.cs b/Assembly-CSharp/Verse/GenList.cs index 1936cbd90..38b6cccb8 100644 --- a/Assembly-CSharp/Verse/GenList.cs +++ b/Assembly-CSharp/Verse/GenList.cs @@ -7,12 +7,12 @@ public static class GenList { public static int CountAllowNull(this IList list) { - return (list == null) ? 0 : list.Count; + return (list != null) ? ((ICollection)list).Count : 0; } public static bool NullOrEmpty(this IList list) { - return list == null || list.Count == 0; + return list == null || ((ICollection)list).Count == 0; } public static List ListFullCopy(this List source) @@ -36,17 +36,19 @@ public static List ListFullCopyOrNull(this List source) public static void RemoveDuplicates(this List list) where T : class { - if (list.Count <= 1) + if (list.Count > 1) { - return; - } - for (int i = list.Count - 1; i >= 0; i--) - { - for (int j = 0; j < i; j++) + for (int num = list.Count - 1; num >= 0; num--) { - if (list[i] == list[j]) + int num2 = 0; + while (num2 < num) { - list.RemoveAt(i); + if ((object)list[num] != (object)list[num2]) + { + num2++; + continue; + } + list.RemoveAt(num); break; } } @@ -55,30 +57,30 @@ public static void RemoveDuplicates(this List list) where T : class public static void Shuffle(this IList list) { - int i = list.Count; - while (i > 1) + int num = ((ICollection)list).Count; + while (num > 1) { - i--; - int index = Rand.RangeInclusive(0, i); + num--; + int index = Rand.RangeInclusive(0, num); T value = list[index]; - list[index] = list[i]; - list[i] = value; + list[index] = list[num]; + list[num] = value; } } public static void InsertionSort(this IList list, Comparison comparison) { - int count = list.Count; - for (int i = 1; i < count; i++) + int count = ((ICollection)list).Count; + for (int num = 1; num < count; num++) { - T t = list[i]; - int num = i - 1; - while (num >= 0 && comparison(list[num], t) > 0) + T val = list[num]; + int num2 = num - 1; + while (num2 >= 0 && comparison(list[num2], val) > 0) { - list[num + 1] = list[num]; - num--; + list[num2 + 1] = list[num2]; + num2--; } - list[num + 1] = t; + list[num2 + 1] = val; } } } diff --git a/Assembly-CSharp/Verse/GenMapUI.cs b/Assembly-CSharp/Verse/GenMapUI.cs index 6bb1acfe1..fe39562ec 100644 --- a/Assembly-CSharp/Verse/GenMapUI.cs +++ b/Assembly-CSharp/Verse/GenMapUI.cs @@ -1,4 +1,3 @@ -using System; using System.Collections.Generic; using UnityEngine; @@ -48,12 +47,13 @@ public static void DrawThingLabel(Thing thing, string text, Color textColor) public static void DrawThingLabel(Vector2 screenPos, string text, Color textColor) { Text.Font = GameFont.Tiny; - float x = Text.CalcSize(text).x; - Rect position = new Rect(screenPos.x - x / 2f - 4f, screenPos.y, x + 8f, 12f); + Vector2 vector = Text.CalcSize(text); + float x = vector.x; + Rect position = new Rect((float)(screenPos.x - x / 2.0 - 4.0), screenPos.y, (float)(x + 8.0), 12f); GUI.DrawTexture(position, TexUI.GrayTextBG); GUI.color = textColor; Text.Anchor = TextAnchor.UpperCenter; - Rect rect = new Rect(screenPos.x - x / 2f, screenPos.y - 3f, x, 999f); + Rect rect = new Rect((float)(screenPos.x - x / 2.0), (float)(screenPos.y - 3.0), x, 999f); Widgets.Label(rect, text); GUI.color = Color.white; Text.Anchor = TextAnchor.UpperLeft; @@ -62,7 +62,7 @@ public static void DrawThingLabel(Vector2 screenPos, string text, Color textColo public static void DrawPawnLabel(Pawn pawn, Vector2 pos, float alpha = 1f, float truncateToWidth = 9999f, Dictionary truncatedLabelsCache = null, GameFont font = GameFont.Tiny, bool alwaysDrawBg = true, bool alignCenter = true) { float pawnLabelNameWidth = GenMapUI.GetPawnLabelNameWidth(pawn, truncateToWidth, truncatedLabelsCache, font); - Rect bgRect = new Rect(pos.x - pawnLabelNameWidth / 2f - 4f, pos.y, pawnLabelNameWidth + 8f, 12f); + Rect bgRect = new Rect((float)(pos.x - pawnLabelNameWidth / 2.0 - 4.0), pos.y, (float)(pawnLabelNameWidth + 8.0), 12f); if (!pawn.RaceProps.Humanlike) { bgRect.y -= 4f; @@ -77,11 +77,11 @@ public static void DrawPawnLabel(Pawn pawn, Rect bgRect, float alpha = 1f, float string pawnLabel = GenMapUI.GetPawnLabel(pawn, truncateToWidth, truncatedLabelsCache, font); float pawnLabelNameWidth = GenMapUI.GetPawnLabelNameWidth(pawn, truncateToWidth, truncatedLabelsCache, font); float summaryHealthPercent = pawn.health.summaryHealth.SummaryHealthPercent; - if (alwaysDrawBg || summaryHealthPercent < 0.999f) + if (alwaysDrawBg || summaryHealthPercent < 0.99900001287460327) { GUI.DrawTexture(bgRect, TexUI.GrayTextBG); } - if (summaryHealthPercent < 0.999f) + if (summaryHealthPercent < 0.99900001287460327) { Rect rect = bgRect.ContractedBy(1f); Widgets.FillableBar(rect, summaryHealthPercent, GenMapUI.OverlayHealthTex, BaseContent.ClearTex, false); @@ -89,21 +89,27 @@ public static void DrawPawnLabel(Pawn pawn, Rect bgRect, float alpha = 1f, float Color color = PawnNameColorUtility.PawnNameColorOf(pawn); color.a = alpha; GUI.color = color; - Rect rect2; + Rect rect2 = default(Rect); if (alignCenter) { Text.Anchor = TextAnchor.UpperCenter; - rect2 = new Rect(bgRect.center.x - pawnLabelNameWidth / 2f, bgRect.y - 2f, pawnLabelNameWidth, 100f); + Vector2 center = bgRect.center; + rect2 = new Rect((float)(center.x - pawnLabelNameWidth / 2.0), (float)(bgRect.y - 2.0), pawnLabelNameWidth, 100f); } else { Text.Anchor = TextAnchor.UpperLeft; - rect2 = new Rect(bgRect.x + 2f, bgRect.center.y - Text.CalcSize(pawnLabel).y / 2f, pawnLabelNameWidth, 100f); + double x = bgRect.x + 2.0; + Vector2 center2 = bgRect.center; + float y = center2.y; + Vector2 vector = Text.CalcSize(pawnLabel); + rect2 = new Rect((float)x, (float)(y - vector.y / 2.0), pawnLabelNameWidth, 100f); } Widgets.Label(rect2, pawnLabel); if (pawn.Drafted) { - Widgets.DrawLineHorizontal(bgRect.center.x - pawnLabelNameWidth / 2f, bgRect.y + 11f, pawnLabelNameWidth); + Vector2 center3 = bgRect.center; + Widgets.DrawLineHorizontal((float)(center3.x - pawnLabelNameWidth / 2.0), (float)(bgRect.y + 11.0), pawnLabelNameWidth); } GUI.color = Color.white; Text.Anchor = TextAnchor.UpperLeft; @@ -117,8 +123,9 @@ public static void DrawText(Vector2 worldPos, string text, Color textColor) Text.Font = GameFont.Tiny; GUI.color = textColor; Text.Anchor = TextAnchor.UpperCenter; - float x = Text.CalcSize(text).x; - Widgets.Label(new Rect(vector.x - x / 2f, vector.y - 2f, x, 999f), text); + Vector2 vector2 = Text.CalcSize(text); + float x = vector2.x; + Widgets.Label(new Rect((float)(vector.x - x / 2.0), (float)(vector.y - 2.0), x, 999f), text); GUI.color = Color.white; Text.Anchor = TextAnchor.UpperLeft; } @@ -135,9 +142,10 @@ private static float GetPawnLabelNameWidth(Pawn pawn, float truncateToWidth, Dic } else { - num = Text.CalcSize(pawnLabel).x; + Vector2 vector = Text.CalcSize(pawnLabel); + num = vector.x; } - if (num < 20f) + if (num < 20.0) { num = 20f; } diff --git a/Assembly-CSharp/Verse/GenMath.cs b/Assembly-CSharp/Verse/GenMath.cs index a48e3fd34..e8d7427f4 100644 --- a/Assembly-CSharp/Verse/GenMath.cs +++ b/Assembly-CSharp/Verse/GenMath.cs @@ -30,23 +30,23 @@ public struct BezierCubicControls public static float RoundedHundredth(float f) { - return Mathf.Round(f * 100f) / 100f; + return (float)(Mathf.Round((float)(f * 100.0)) / 100.0); } public static float ChanceEitherHappens(float chanceA, float chanceB) { - return chanceA + (1f - chanceA) * chanceB; + return (float)(chanceA + (1.0 - chanceA) * chanceB); } public static float SmootherStep(float edge0, float edge1, float x) { x = Mathf.Clamp01((x - edge0) / (edge1 - edge0)); - return x * x * x * (x * (x * 6f - 15f) + 10f); + return (float)(x * x * x * (x * (x * 6.0 - 15.0) + 10.0)); } public static int RoundRandom(float f) { - return (int)f + ((Rand.Value >= f % 1f) ? 0 : 1); + return (int)f + ((Rand.Value < f % 1.0) ? 1 : 0); } public static float WeightedAverage(float A, float weightA, float B, float weightB) @@ -81,24 +81,17 @@ public static float GetFactorInInterval(float min, float mid, float max, float p { return 0f; } - if (x <= min || x >= max) + if (!(x <= min) && !(x >= max)) { - return 0f; - } - if (x == mid) - { - return 1f; - } - float f; - if (x < mid) - { - f = 1f - (mid - x) / (mid - min); - } - else - { - f = 1f - (x - mid) / (max - mid); + if (x == mid) + { + return 1f; + } + float num = 0f; + num = (float)((!(x < mid)) ? (1.0 - (x - mid) / (max - mid)) : (1.0 - (mid - x) / (mid - min))); + return Mathf.Pow(num, power); } - return Mathf.Pow(f, power); + return 0f; } public static float FlatHill(float min, float lower, float upper, float max, float x) @@ -150,11 +143,11 @@ public static int OctileDistance(int dx, int dz, int cardinal, int diagonal) public static float UnboundedValueToFactor(float val) { - if (val > 0f) + if (val > 0.0) { - return 1f + val; + return (float)(1.0 + val); } - return 1f / (1f - val); + return (float)(1.0 / (1.0 - val)); } public static void LogTestMathPerf() @@ -165,49 +158,31 @@ public static void LogTestMathPerf() float num = 0f; Stopwatch stopwatch = Stopwatch.StartNew(); int num2 = 0; - while ((float)num2 < 1E+07f) + while ((float)num2 < 10000000.0) { num += (float)Math.Sqrt(101.20999908447266); num2++; } - stringBuilder.AppendLine(string.Concat(new object[] - { - "(float)System.Math.Sqrt(", - 101.21f, - "): ", - stopwatch.ElapsedTicks - })); + stringBuilder.AppendLine("(float)System.Math.Sqrt(" + 101.21f + "): " + stopwatch.ElapsedTicks); Stopwatch stopwatch2 = Stopwatch.StartNew(); int num3 = 0; - while ((float)num3 < 1E+07f) + while ((float)num3 < 10000000.0) { num += Mathf.Sqrt(101.21f); num3++; } - stringBuilder.AppendLine(string.Concat(new object[] - { - "UnityEngine.Mathf.Sqrt(", - 101.21f, - "): ", - stopwatch2.ElapsedTicks - })); + stringBuilder.AppendLine("UnityEngine.Mathf.Sqrt(" + 101.21f + "): " + stopwatch2.ElapsedTicks); Stopwatch stopwatch3 = Stopwatch.StartNew(); int num4 = 0; - while ((float)num4 < 1E+07f) + while ((float)num4 < 10000000.0) { num += GenMath.Sqrt(101.21f); num4++; } - stringBuilder.AppendLine(string.Concat(new object[] - { - "Verse.GenMath.Sqrt(", - 101.21f, - "): ", - stopwatch3.ElapsedTicks - })); + stringBuilder.AppendLine("Verse.GenMath.Sqrt(" + 101.21f + "): " + stopwatch3.ElapsedTicks); Stopwatch stopwatch4 = Stopwatch.StartNew(); int num5 = 0; - while ((float)num5 < 1E+07f) + while ((float)num5 < 10000000.0) { num += (float)intVec.LengthManhattan; num5++; @@ -215,7 +190,7 @@ public static void LogTestMathPerf() stringBuilder.AppendLine("Verse.IntVec3.LengthManhattan: " + stopwatch4.ElapsedTicks); Stopwatch stopwatch5 = Stopwatch.StartNew(); int num6 = 0; - while ((float)num6 < 1E+07f) + while ((float)num6 < 10000000.0) { num += intVec.LengthHorizontal; num6++; @@ -223,7 +198,7 @@ public static void LogTestMathPerf() stringBuilder.AppendLine("Verse.IntVec3.LengthHorizontal: " + stopwatch5.ElapsedTicks); Stopwatch stopwatch6 = Stopwatch.StartNew(); int num7 = 0; - while ((float)num7 < 1E+07f) + while ((float)num7 < 10000000.0) { num += (float)intVec.LengthHorizontalSquared; num7++; @@ -243,14 +218,11 @@ public static float Min(float a, float b, float c) } return c; } - else + if (b < c) { - if (b < c) - { - return b; - } - return c; + return b; } + return c; } public static int Max(int a, int b, int c) @@ -263,14 +235,11 @@ public static int Max(int a, int b, int c) } return c; } - else + if (b > c) { - if (b > c) - { - return b; - } - return c; + return b; } + return c; } public static float SphericalDistance(Vector3 normalizedA, Vector3 normalizedB) @@ -293,14 +262,16 @@ public static void DHondtDistribution(List candidates, Func sco GenMath.tmpScores.Add(item); GenMath.tmpCalcList.Add(item); } - for (int j = 0; j < numToDistribute; j++) - { - int num = GenMath.tmpCalcList.IndexOf(GenMath.tmpCalcList.Max()); - int num2; - int expr_72 = num2 = num; - num2 = candidates[num2]; - candidates[expr_72] = num2 + 1; - GenMath.tmpCalcList[num] = GenMath.tmpScores[num] / ((float)candidates[num] + 1f); + for (int num = 0; num < numToDistribute; num++) + { + int num2 = GenMath.tmpCalcList.IndexOf(GenMath.tmpCalcList.Max()); + List list; + List obj = list = candidates; + int index; + int index2 = index = num2; + index = list[index]; + obj[index2] = index + 1; + GenMath.tmpCalcList[num2] = (float)(GenMath.tmpScores[num2] / ((float)candidates[num2] + 1.0)); } } @@ -309,7 +280,7 @@ public static int PositiveMod(int x, int m) return (x % m + m) % m; } - public static Vector3 BezierCubicEvaluate(float t, GenMath.BezierCubicControls bcc) + public static Vector3 BezierCubicEvaluate(float t, BezierCubicControls bcc) { return GenMath.BezierCubicEvaluate(t, bcc.w0, bcc.w1, bcc.w2, bcc.w3); } @@ -317,7 +288,7 @@ public static Vector3 BezierCubicEvaluate(float t, GenMath.BezierCubicControls b public static Vector3 BezierCubicEvaluate(float t, Vector3 w0, Vector3 w1, Vector3 w2, Vector3 w3) { float d = t * t; - float num = 1f - t; + float num = (float)(1.0 - t); float d2 = num * num; return w0 * d2 * num + 3f * w1 * d2 * t + 3f * w2 * num * d + w3 * d * t; } @@ -335,16 +306,16 @@ public static float CirclesOverlapArea(float x1, float y1, float r1, float x2, f } if (num2 <= num5 && r1 >= r2) { - return 3.14159274f * num4; + return (float)(3.1415927410125732 * num4); } if (num2 <= num5 && r2 >= r1) { - return 3.14159274f * num3; + return (float)(3.1415927410125732 * num3); } - float num6 = Mathf.Acos((num3 - num4 + num) / (2f * r1 * num2)) * 2f; - float num7 = Mathf.Acos((num4 - num3 + num) / (2f * r2 * num2)) * 2f; - float num8 = (num7 * num4 - num4 * Mathf.Sin(num7)) * 0.5f; - float num9 = (num6 * num3 - num3 * Mathf.Sin(num6)) * 0.5f; + float num6 = (float)(Mathf.Acos((float)((num3 - num4 + num) / (2.0 * r1 * num2))) * 2.0); + float num7 = (float)(Mathf.Acos((float)((num4 - num3 + num) / (2.0 * r2 * num2))) * 2.0); + float num8 = (float)((num7 * num4 - num4 * Mathf.Sin(num7)) * 0.5); + float num9 = (float)((num6 * num3 - num3 * Mathf.Sin(num6)) * 0.5); return num8 + num9; } } diff --git a/Assembly-CSharp/Verse/GenPlace.cs b/Assembly-CSharp/Verse/GenPlace.cs index 4f47e4e14..07d327750 100644 --- a/Assembly-CSharp/Verse/GenPlace.cs +++ b/Assembly-CSharp/Verse/GenPlace.cs @@ -9,11 +9,11 @@ public static class GenPlace { private enum PlaceSpotQuality : byte { - Unusable, - Awful, - Bad, - Okay, - Perfect + Unusable = 0, + Awful = 1, + Bad = 2, + Okay = 3, + Perfect = 4 } private static readonly int PlaceNearMaxRadialCells = GenRadial.NumCellsInRadius(12.9f); @@ -22,7 +22,7 @@ private enum PlaceSpotQuality : byte public static bool TryPlaceThing(Thing thing, IntVec3 center, Map map, ThingPlaceMode mode, Action placedAction = null) { - Thing thing2; + Thing thing2 = default(Thing); return GenPlace.TryPlaceThing(thing, center, map, mode, out thing2, placedAction); } @@ -38,51 +38,45 @@ public static bool TryPlaceThing(Thing thing, IntVec3 center, Map map, ThingPlac { mode = ThingPlaceMode.Direct; } - if (mode == ThingPlaceMode.Direct) + switch (mode) + { + case ThingPlaceMode.Direct: { return GenPlace.TryPlaceDirect(thing, center, map, out lastResultingThing, placedAction); } - if (mode == ThingPlaceMode.Near) + case ThingPlaceMode.Near: { lastResultingThing = null; + int num = -1; while (true) { - int stackCount = thing.stackCount; - IntVec3 loc; + num = thing.stackCount; + IntVec3 loc = default(IntVec3); if (!GenPlace.TryFindPlaceSpotNear(center, map, thing, true, out loc)) { - break; + return false; } if (GenPlace.TryPlaceDirect(thing, loc, map, out lastResultingThing, placedAction)) { return true; } - if (thing.stackCount == stackCount) - { - goto Block_7; - } + if (thing.stackCount == num) + break; } - return false; - Block_7: - Log.Error(string.Concat(new object[] - { - "Failed to place ", - thing, - " at ", - center, - " in mode ", - mode, - "." - })); + Log.Error("Failed to place " + thing + " at " + center + " in mode " + mode + "."); lastResultingThing = null; return false; } - throw new InvalidOperationException(); + default: + { + throw new InvalidOperationException(); + } + } } public static bool TryMoveThing(Thing thing, IntVec3 loc, Map map) { - IntVec3 position; + IntVec3 position = default(IntVec3); if (!GenPlace.TryFindPlaceSpotNear(loc, map, thing, false, out position)) { return false; @@ -93,59 +87,68 @@ public static bool TryMoveThing(Thing thing, IntVec3 loc, Map map) private static bool TryFindPlaceSpotNear(IntVec3 center, Map map, Thing thing, bool allowStacking, out IntVec3 bestSpot) { - GenPlace.PlaceSpotQuality placeSpotQuality = GenPlace.PlaceSpotQuality.Unusable; + PlaceSpotQuality placeSpotQuality = PlaceSpotQuality.Unusable; bestSpot = center; - for (int i = 0; i < 9; i++) + int num = 0; + while (num < 9) { - IntVec3 intVec = center + GenRadial.RadialPattern[i]; - GenPlace.PlaceSpotQuality placeSpotQuality2 = GenPlace.PlaceSpotQualityAt(intVec, map, thing, center, allowStacking); - if (placeSpotQuality2 > placeSpotQuality) + IntVec3 intVec = center + GenRadial.RadialPattern[num]; + PlaceSpotQuality placeSpotQuality2 = GenPlace.PlaceSpotQualityAt(intVec, map, thing, center, allowStacking); + if ((int)placeSpotQuality2 > (int)placeSpotQuality) { bestSpot = intVec; placeSpotQuality = placeSpotQuality2; } - if (placeSpotQuality == GenPlace.PlaceSpotQuality.Perfect) + if (placeSpotQuality != PlaceSpotQuality.Perfect) { - break; + num++; + continue; } + break; } - if (placeSpotQuality >= GenPlace.PlaceSpotQuality.Okay) + if ((int)placeSpotQuality >= 3) { return true; } - for (int j = 0; j < GenPlace.PlaceNearMiddleRadialCells; j++) + int num2 = 0; + while (num2 < GenPlace.PlaceNearMiddleRadialCells) { - IntVec3 intVec = center + GenRadial.RadialPattern[j]; - GenPlace.PlaceSpotQuality placeSpotQuality2 = GenPlace.PlaceSpotQualityAt(intVec, map, thing, center, allowStacking); - if (placeSpotQuality2 > placeSpotQuality) + IntVec3 intVec = center + GenRadial.RadialPattern[num2]; + PlaceSpotQuality placeSpotQuality2 = GenPlace.PlaceSpotQualityAt(intVec, map, thing, center, allowStacking); + if ((int)placeSpotQuality2 > (int)placeSpotQuality) { bestSpot = intVec; placeSpotQuality = placeSpotQuality2; } - if (placeSpotQuality == GenPlace.PlaceSpotQuality.Perfect) + if (placeSpotQuality != PlaceSpotQuality.Perfect) { - break; + num2++; + continue; } + break; } - if (placeSpotQuality >= GenPlace.PlaceSpotQuality.Okay) + if ((int)placeSpotQuality >= 3) { return true; } - for (int k = 0; k < GenPlace.PlaceNearMaxRadialCells; k++) + int num3 = 0; + while (num3 < GenPlace.PlaceNearMaxRadialCells) { - IntVec3 intVec = center + GenRadial.RadialPattern[k]; - GenPlace.PlaceSpotQuality placeSpotQuality2 = GenPlace.PlaceSpotQualityAt(intVec, map, thing, center, allowStacking); - if (placeSpotQuality2 > placeSpotQuality) + IntVec3 intVec = center + GenRadial.RadialPattern[num3]; + PlaceSpotQuality placeSpotQuality2 = GenPlace.PlaceSpotQualityAt(intVec, map, thing, center, allowStacking); + if ((int)placeSpotQuality2 > (int)placeSpotQuality) { bestSpot = intVec; placeSpotQuality = placeSpotQuality2; } - if (placeSpotQuality == GenPlace.PlaceSpotQuality.Perfect) + if (placeSpotQuality != PlaceSpotQuality.Perfect) { - break; + num3++; + continue; } + break; } - if (placeSpotQuality > GenPlace.PlaceSpotQuality.Unusable) + if ((int)placeSpotQuality > 0) { return true; } @@ -153,27 +156,31 @@ private static bool TryFindPlaceSpotNear(IntVec3 center, Map map, Thing thing, b return false; } - private static GenPlace.PlaceSpotQuality PlaceSpotQualityAt(IntVec3 c, Map map, Thing thing, IntVec3 center, bool allowStacking) + private static PlaceSpotQuality PlaceSpotQualityAt(IntVec3 c, Map map, Thing thing, IntVec3 center, bool allowStacking) { - if (!c.InBounds(map) || !c.Walkable(map)) - { - return GenPlace.PlaceSpotQuality.Unusable; - } - List list = map.thingGrid.ThingsListAt(c); - for (int i = 0; i < list.Count; i++) + if (c.InBounds(map) && c.Walkable(map)) { - Thing thing2 = list[i]; - if (thing.def.saveCompressible && thing2.def.saveCompressible) + List list = map.thingGrid.ThingsListAt(c); + for (int i = 0; i < list.Count; i++) { - return GenPlace.PlaceSpotQuality.Unusable; + Thing thing2 = list[i]; + if (thing.def.saveCompressible && thing2.def.saveCompressible) + { + return PlaceSpotQuality.Unusable; + } + if (thing.def.category == ThingCategory.Item && thing2.def.category == ThingCategory.Item && (thing2.def != thing.def || thing2.stackCount >= thing.def.stackLimit)) + { + return PlaceSpotQuality.Unusable; + } } - if (thing.def.category == ThingCategory.Item && thing2.def.category == ThingCategory.Item && (thing2.def != thing.def || thing2.stackCount >= thing.def.stackLimit)) + if (c.GetRoom(map, RegionType.Set_Passable) != center.GetRoom(map, RegionType.Set_Passable)) { - return GenPlace.PlaceSpotQuality.Unusable; + if (!map.reachability.CanReach(center, c, PathEndMode.OnCell, TraverseMode.PassDoors, Danger.Deadly)) + { + return PlaceSpotQuality.Awful; + } + return PlaceSpotQuality.Bad; } - } - if (c.GetRoom(map, RegionType.Set_Passable) == center.GetRoom(map, RegionType.Set_Passable)) - { if (allowStacking) { for (int j = 0; j < list.Count; j++) @@ -181,48 +188,44 @@ private static GenPlace.PlaceSpotQuality PlaceSpotQualityAt(IntVec3 c, Map map, Thing thing3 = list[j]; if (thing3.def.category == ThingCategory.Item && thing3.def == thing.def && thing3.stackCount < thing.def.stackLimit) { - return GenPlace.PlaceSpotQuality.Perfect; + return PlaceSpotQuality.Perfect; } } } Pawn pawn = thing as Pawn; bool flag = pawn != null && pawn.Downed; - GenPlace.PlaceSpotQuality placeSpotQuality = GenPlace.PlaceSpotQuality.Perfect; + PlaceSpotQuality placeSpotQuality = PlaceSpotQuality.Perfect; for (int k = 0; k < list.Count; k++) { Thing thing4 = list[k]; if (thing4.def.IsDoor) { - return GenPlace.PlaceSpotQuality.Bad; + return PlaceSpotQuality.Bad; } if (thing4 is Building_WorkTable) { - return GenPlace.PlaceSpotQuality.Bad; + return PlaceSpotQuality.Bad; } Pawn pawn2 = thing4 as Pawn; if (pawn2 != null) { if (pawn2.Downed || flag) { - return GenPlace.PlaceSpotQuality.Bad; + return PlaceSpotQuality.Bad; } - if (placeSpotQuality > GenPlace.PlaceSpotQuality.Okay) + if ((int)placeSpotQuality > 3) { - placeSpotQuality = GenPlace.PlaceSpotQuality.Okay; + placeSpotQuality = PlaceSpotQuality.Okay; } } - if (thing4.def.category == ThingCategory.Plant && thing4.def.selectable && placeSpotQuality > GenPlace.PlaceSpotQuality.Okay) + if (thing4.def.category == ThingCategory.Plant && thing4.def.selectable && (int)placeSpotQuality > 3) { - placeSpotQuality = GenPlace.PlaceSpotQuality.Okay; + placeSpotQuality = PlaceSpotQuality.Okay; } } return placeSpotQuality; } - if (!map.reachability.CanReach(center, c, PathEndMode.OnCell, TraverseMode.PassDoors, Danger.Deadly)) - { - return GenPlace.PlaceSpotQuality.Awful; - } - return GenPlace.PlaceSpotQuality.Bad; + return PlaceSpotQuality.Unusable; } private static bool TryPlaceDirect(Thing thing, IntVec3 loc, Map map, out Thing resultingThing, Action placedAction = null) @@ -234,48 +237,44 @@ private static bool TryPlaceDirect(Thing thing, IntVec3 loc, Map map, out Thing thing = thing.SplitOff(thing.def.stackLimit); flag = true; } + Thing thing3; if (thing.def.stackLimit > 1) { List thingList = loc.GetThingList(map); - int i = 0; - while (i < thingList.Count) + for (int i = 0; i < thingList.Count; i++) { - Thing thing3 = thingList[i]; - if (!thing3.CanStackWith(thing)) - { - i++; - } - else - { - int stackCount = thing.stackCount; - if (thing3.TryAbsorbStack(thing, true)) - { - resultingThing = thing3; - if (placedAction != null) - { - placedAction(thing3, stackCount); - } - return !flag; - } - resultingThing = null; - if (placedAction != null && stackCount != thing.stackCount) - { - placedAction(thing3, stackCount - thing.stackCount); - } - if (thing2 != thing) - { - thing2.TryAbsorbStack(thing, false); - } - return false; - } + thing3 = thingList[i]; + if (thing3.CanStackWith(thing)) + goto IL_006a; } } resultingThing = GenSpawn.Spawn(thing, loc, map); - if (placedAction != null) + if ((object)placedAction != null) { placedAction(thing, thing.stackCount); } return !flag; + IL_006a: + int stackCount = thing.stackCount; + if (thing3.TryAbsorbStack(thing, true)) + { + resultingThing = thing3; + if ((object)placedAction != null) + { + placedAction(thing3, stackCount); + } + return !flag; + } + resultingThing = null; + if ((object)placedAction != null && stackCount != thing.stackCount) + { + placedAction(thing3, stackCount - thing.stackCount); + } + if (thing2 != thing) + { + thing2.TryAbsorbStack(thing, false); + } + return false; } public static Thing HaulPlaceBlockerIn(Thing haulThing, IntVec3 c, Map map, bool checkBlueprints) @@ -288,25 +287,19 @@ public static Thing HaulPlaceBlockerIn(Thing haulThing, IntVec3 c, Map map, bool { return thing; } - if ((thing.def.category != ThingCategory.Plant || thing.def.passability != Traversability.Standable) && thing.def.category != ThingCategory.Filth) + if (((thing.def.category != ThingCategory.Plant) ? Traversability.PassThroughOnly : thing.def.passability) != 0 && thing.def.category != ThingCategory.Filth && (haulThing == null || thing.def.category != ThingCategory.Item || !thing.CanStackWith(haulThing) || thing.def.stackLimit - thing.stackCount < haulThing.stackCount)) { - if (haulThing == null || thing.def.category != ThingCategory.Item || !thing.CanStackWith(haulThing) || thing.def.stackLimit - thing.stackCount < haulThing.stackCount) + if (thing.def.EverHaulable) { - if (thing.def.EverHaulable) - { - return thing; - } - if (haulThing != null && GenSpawn.SpawningWipes(haulThing.def, thing.def)) - { - return thing; - } - if (thing.def.passability != Traversability.Standable) - { - if (thing.def.surfaceType != SurfaceType.Item) - { - return thing; - } - } + return thing; + } + if (haulThing != null && GenSpawn.SpawningWipes(haulThing.def, thing.def)) + { + return thing; + } + if (thing.def.passability != 0 && thing.def.surfaceType != SurfaceType.Item) + { + return thing; } } } diff --git a/Assembly-CSharp/Verse/GenRadial.cs b/Assembly-CSharp/Verse/GenRadial.cs index ba10d388e..c2327e1bd 100644 --- a/Assembly-CSharp/Verse/GenRadial.cs +++ b/Assembly-CSharp/Verse/GenRadial.cs @@ -1,6 +1,5 @@ using System; using System.Collections.Generic; -using System.Diagnostics; namespace Verse { @@ -94,7 +93,7 @@ private static void SetupRadialPattern() list.Add(new IntVec3(i, 0, j)); } } - list.Sort(delegate(IntVec3 A, IntVec3 B) + list.Sort((Comparison)delegate(IntVec3 A, IntVec3 B) { float num = (float)A.LengthHorizontalSquared; float num2 = (float)B.LengthHorizontalSquared; @@ -117,40 +116,40 @@ private static void SetupRadialPattern() public static int NumCellsToFillForRadius_ManualRadialPattern(int radius) { - if (radius == 0) + switch (radius) + { + case 0: { return 1; } - if (radius == 1) + case 1: { return 9; } - if (radius == 2) + case 2: { return 21; } - if (radius == 3) + case 3: { return 37; } - Log.Error("NumSquares radius error"); - return 0; + default: + { + Log.Error("NumSquares radius error"); + return 0; + } + } } public static int NumCellsInRadius(float radius) { if (radius >= GenRadial.MaxRadialPatternRadius) { - Log.Error(string.Concat(new object[] - { - "Not enough squares to get to radius ", - radius, - ". Max is ", - GenRadial.MaxRadialPatternRadius - })); + Log.Error("Not enough squares to get to radius " + radius + ". Max is " + GenRadial.MaxRadialPatternRadius); return 10000; } - float num = radius + 1.401298E-45f; + float num = (float)(radius + 1.4012984643248171E-45); for (int i = 0; i < 10000; i++) { if (GenRadial.RadialPatternRadii[i] > num) @@ -166,47 +165,56 @@ public static float RadiusOfNumCells(int numCells) return GenRadial.RadialPatternRadii[numCells]; } - [DebuggerHidden] public static IEnumerable RadialPatternInRadius(float radius) { - GenRadial.c__Iterator24A c__Iterator24A = new GenRadial.c__Iterator24A(); - c__Iterator24A.radius = radius; - c__Iterator24A.<$>radius = radius; - GenRadial.c__Iterator24A expr_15 = c__Iterator24A; - expr_15.$PC = -2; - return expr_15; + int numSquares = GenRadial.NumCellsInRadius(radius); + for (int i = 0; i < numSquares; i++) + { + yield return GenRadial.RadialPattern[i]; + } } - [DebuggerHidden] public static IEnumerable RadialCellsAround(IntVec3 center, float radius, bool useCenter) { - GenRadial.c__Iterator24B c__Iterator24B = new GenRadial.c__Iterator24B(); - c__Iterator24B.radius = radius; - c__Iterator24B.useCenter = useCenter; - c__Iterator24B.center = center; - c__Iterator24B.<$>radius = radius; - c__Iterator24B.<$>useCenter = useCenter; - c__Iterator24B.<$>center = center; - GenRadial.c__Iterator24B expr_31 = c__Iterator24B; - expr_31.$PC = -2; - return expr_31; + int numSquares = GenRadial.NumCellsInRadius(radius); + for (int i = (!useCenter) ? 1 : 0; i < numSquares; i++) + { + yield return GenRadial.RadialPattern[i] + center; + } } - [DebuggerHidden] public static IEnumerable RadialDistinctThingsAround(IntVec3 center, Map map, float radius, bool useCenter) { - GenRadial.c__Iterator24C c__Iterator24C = new GenRadial.c__Iterator24C(); - c__Iterator24C.radius = radius; - c__Iterator24C.useCenter = useCenter; - c__Iterator24C.center = center; - c__Iterator24C.map = map; - c__Iterator24C.<$>radius = radius; - c__Iterator24C.<$>useCenter = useCenter; - c__Iterator24C.<$>center = center; - c__Iterator24C.<$>map = map; - GenRadial.c__Iterator24C expr_3F = c__Iterator24C; - expr_3F.$PC = -2; - return expr_3F; + int numCells = GenRadial.NumCellsInRadius(radius); + HashSet returnedThings = null; + for (int j = (!useCenter) ? 1 : 0; j < numCells; j++) + { + IntVec3 cell = GenRadial.RadialPattern[j] + center; + if (cell.InBounds(map)) + { + List thingList = cell.GetThingList(map); + for (int i = 0; i < thingList.Count; i++) + { + Thing t = thingList[i]; + if (t.def.size.x > 1 && t.def.size.z > 1) + { + if (returnedThings == null) + { + returnedThings = new HashSet(); + } + if (!returnedThings.Contains(t)) + { + returnedThings.Add(t); + goto IL_014a; + } + continue; + } + goto IL_014a; + IL_014a: + yield return t; + } + } + } } } } diff --git a/Assembly-CSharp/Verse/GenRecipe.cs b/Assembly-CSharp/Verse/GenRecipe.cs index c0fd7b3fc..f06484027 100644 --- a/Assembly-CSharp/Verse/GenRecipe.cs +++ b/Assembly-CSharp/Verse/GenRecipe.cs @@ -1,27 +1,80 @@ using RimWorld; -using System; using System.Collections.Generic; -using System.Diagnostics; +using UnityEngine; namespace Verse { public static class GenRecipe { - [DebuggerHidden] public static IEnumerable MakeRecipeProducts(RecipeDef recipeDef, Pawn worker, List ingredients, Thing dominantIngredient) { - GenRecipe.c__Iterator24D c__Iterator24D = new GenRecipe.c__Iterator24D(); - c__Iterator24D.recipeDef = recipeDef; - c__Iterator24D.worker = worker; - c__Iterator24D.dominantIngredient = dominantIngredient; - c__Iterator24D.ingredients = ingredients; - c__Iterator24D.<$>recipeDef = recipeDef; - c__Iterator24D.<$>worker = worker; - c__Iterator24D.<$>dominantIngredient = dominantIngredient; - c__Iterator24D.<$>ingredients = ingredients; - GenRecipe.c__Iterator24D expr_3F = c__Iterator24D; - expr_3F.$PC = -2; - return expr_3F; + float efficiency = (float)((recipeDef.efficiencyStat != null) ? worker.GetStatValue(recipeDef.efficiencyStat, true) : 1.0); + if (recipeDef.products != null) + { + for (int l = 0; l < recipeDef.products.Count; l++) + { + ThingCountClass prod = recipeDef.products[l]; + ThingDef stuffDef = (!prod.thingDef.MadeFromStuff) ? null : dominantIngredient.def; + Thing product3 = ThingMaker.MakeThing(prod.thingDef, stuffDef); + product3.stackCount = Mathf.CeilToInt((float)prod.count * efficiency); + if (dominantIngredient != null) + { + product3.SetColor(dominantIngredient.DrawColor, false); + } + CompIngredients ingredientsComp = product3.TryGetComp(); + if (ingredientsComp != null) + { + for (int k = 0; k < ingredients.Count; k++) + { + ingredientsComp.RegisterIngredient(ingredients[k].def); + } + } + CompFoodPoisonable foodPoisonable = product3.TryGetComp(); + if (foodPoisonable != null) + { + float poisonChance = worker.GetStatValue(StatDefOf.FoodPoisonChance, true); + Room room = worker.GetRoom(RegionType.Set_Passable); + if (room != null) + { + poisonChance *= room.GetStat(RoomStatDefOf.FoodPoisonChanceFactor); + } + if (Rand.Value < poisonChance) + { + foodPoisonable.PoisonPercent = 1f; + } + } + yield return GenRecipe.PostProcessProduct(product3, recipeDef, worker); + } + } + if (recipeDef.specialProducts != null) + { + for (int j = 0; j < recipeDef.specialProducts.Count; j++) + { + for (int i = 0; i < ingredients.Count; i++) + { + Thing ing = ingredients[i]; + switch (recipeDef.specialProducts[j]) + { + case SpecialProductType.Butchery: + { + foreach (Thing item in ing.ButcherProducts(worker, efficiency)) + { + yield return GenRecipe.PostProcessProduct(item, recipeDef, worker); + } + break; + } + case SpecialProductType.Smelted: + { + foreach (Thing item2 in ing.SmeltProducts(efficiency)) + { + yield return GenRecipe.PostProcessProduct(item2, recipeDef, worker); + } + break; + } + } + } + } + } } private static Thing PostProcessProduct(Thing product, RecipeDef recipeDef, Pawn worker) @@ -40,13 +93,9 @@ private static Thing PostProcessProduct(Thing product, RecipeDef recipeDef, Pawn if (compArt != null) { compArt.JustCreatedBy(worker); - if (compQuality.Quality >= QualityCategory.Excellent) + if ((int)compQuality.Quality >= 6) { - TaleRecorder.RecordTale(TaleDefOf.CraftedArt, new object[] - { - worker, - product - }); + TaleRecorder.RecordTale(TaleDefOf.CraftedArt, worker, product); } } if (product.def.Minifiable) diff --git a/Assembly-CSharp/Verse/GenScene.cs b/Assembly-CSharp/Verse/GenScene.cs index acc1b2ed9..2daa4a4cb 100644 --- a/Assembly-CSharp/Verse/GenScene.cs +++ b/Assembly-CSharp/Verse/GenScene.cs @@ -29,7 +29,7 @@ public static bool InPlayScene public static void GoToMainMenu() { LongEventHandler.ClearQueuedEvents(); - LongEventHandler.QueueLongEvent(delegate + LongEventHandler.QueueLongEvent((Action)delegate { MemoryUtility.ClearAllMapsAndWorld(); Current.Game = null; diff --git a/Assembly-CSharp/Verse/GenSight.cs b/Assembly-CSharp/Verse/GenSight.cs index eab3d1e2c..8eb55bd31 100644 --- a/Assembly-CSharp/Verse/GenSight.cs +++ b/Assembly-CSharp/Verse/GenSight.cs @@ -1,6 +1,5 @@ using System; using System.Collections.Generic; -using System.Diagnostics; using UnityEngine; namespace Verse @@ -9,126 +8,130 @@ public static class GenSight { public static bool LineOfSight(IntVec3 start, IntVec3 end, Map map, bool skipFirstCell = false, Func validator = null, int halfXOffset = 0, int halfZOffset = 0) { - if (!start.InBounds(map) || !end.InBounds(map)) + if (start.InBounds(map) && end.InBounds(map)) { - return false; - } - bool flag; - if (start.x == end.x) - { - flag = (start.z < end.z); - } - else - { - flag = (start.x < end.x); - } - int num = Mathf.Abs(end.x - start.x); - int num2 = Mathf.Abs(end.z - start.z); - int num3 = start.x; - int num4 = start.z; - int i = 1 + num + num2; - int num5 = (end.x <= start.x) ? -1 : 1; - int num6 = (end.z <= start.z) ? -1 : 1; - num *= 4; - num2 *= 4; - num += halfXOffset * 2; - num2 += halfZOffset * 2; - int num7 = num / 2 - num2 / 2; - IntVec3 intVec = default(IntVec3); - while (i > 1) - { - intVec.x = num3; - intVec.z = num4; - if (!skipFirstCell || !(intVec == start)) + bool flag = (start.x != end.x) ? (start.x < end.x) : (start.z < end.z); + int num = Mathf.Abs(end.x - start.x); + int num2 = Mathf.Abs(end.z - start.z); + int num3 = start.x; + int num4 = start.z; + int num5 = 1 + num + num2; + int num6 = (end.x > start.x) ? 1 : (-1); + int num7 = (end.z > start.z) ? 1 : (-1); + num *= 4; + num2 *= 4; + num += halfXOffset * 2; + num2 += halfZOffset * 2; + int num8 = num / 2 - num2 / 2; + IntVec3 intVec = default(IntVec3); + while (num5 > 1) { - if (!intVec.CanBeSeenOverFast(map)) + intVec.x = num3; + intVec.z = num4; + if (!skipFirstCell || !(intVec == start)) { - return false; + if (!intVec.CanBeSeenOverFast(map)) + { + return false; + } + if ((object)validator != null && !validator(intVec)) + { + return false; + } } - if (validator != null && !validator(intVec)) + if (num8 > 0 || (num8 == 0 && flag)) { - return false; + num3 += num6; + num8 -= num2; } + else + { + num4 += num7; + num8 += num; + } + num5--; } - if (num7 > 0 || (num7 == 0 && flag)) - { - num3 += num5; - num7 -= num2; - } - else - { - num4 += num6; - num7 += num; - } - i--; + return true; } - return true; + return false; } public static bool LineOfSight(IntVec3 start, IntVec3 end, Map map, CellRect startRect, CellRect endRect) { - if (!start.InBounds(map) || !end.InBounds(map)) - { - return false; - } - bool flag; - if (start.x == end.x) + if (start.InBounds(map) && end.InBounds(map)) { - flag = (start.z < end.z); - } - else - { - flag = (start.x < end.x); + bool flag = (start.x != end.x) ? (start.x < end.x) : (start.z < end.z); + int num = Mathf.Abs(end.x - start.x); + int num2 = Mathf.Abs(end.z - start.z); + int num3 = start.x; + int num4 = start.z; + int num5 = 1 + num + num2; + int num6 = (end.x > start.x) ? 1 : (-1); + int num7 = (end.z > start.z) ? 1 : (-1); + int num8 = num - num2; + num *= 2; + num2 *= 2; + IntVec3 c = default(IntVec3); + while (num5 > 1) + { + c.x = num3; + c.z = num4; + if (endRect.Contains(c)) + { + return true; + } + if (!startRect.Contains(c) && !c.CanBeSeenOverFast(map)) + { + return false; + } + if (num8 > 0 || (num8 == 0 && flag)) + { + num3 += num6; + num8 -= num2; + } + else + { + num4 += num7; + num8 += num; + } + num5--; + } + return true; } - int num = Mathf.Abs(end.x - start.x); - int num2 = Mathf.Abs(end.z - start.z); - int num3 = start.x; - int num4 = start.z; - int i = 1 + num + num2; - int num5 = (end.x <= start.x) ? -1 : 1; - int num6 = (end.z <= start.z) ? -1 : 1; - int num7 = num - num2; - num *= 2; - num2 *= 2; + return false; + } + + public static IEnumerable PointsOnLineOfSight(IntVec3 start, IntVec3 end) + { + bool sideOnEqual = (start.x != end.x) ? (start.x < end.x) : (start.z < end.z); + int dx2 = Mathf.Abs(end.x - start.x); + int dz2 = Mathf.Abs(end.z - start.z); + int x = start.x; + int z = start.z; + int i = 1 + dx2 + dz2; + int x_inc = (end.x > start.x) ? 1 : (-1); + int z_inc = (end.z > start.z) ? 1 : (-1); + int error = dx2 - dz2; + dx2 *= 2; + dz2 *= 2; IntVec3 c = default(IntVec3); while (i > 1) { - c.x = num3; - c.z = num4; - if (endRect.Contains(c)) + c.x = x; + c.z = z; + yield return c; + if (error <= 0 && (error != 0 || !sideOnEqual)) { - return true; - } - if (!startRect.Contains(c) && !c.CanBeSeenOverFast(map)) - { - return false; - } - if (num7 > 0 || (num7 == 0 && flag)) - { - num3 += num5; - num7 -= num2; + z += z_inc; + error += dx2; } else { - num4 += num6; - num7 += num; + x += x_inc; + error -= dz2; } i--; } - return true; - } - - [DebuggerHidden] - public static IEnumerable PointsOnLineOfSight(IntVec3 start, IntVec3 end) - { - GenSight.c__Iterator24E c__Iterator24E = new GenSight.c__Iterator24E(); - c__Iterator24E.start = start; - c__Iterator24E.end = end; - c__Iterator24E.<$>start = start; - c__Iterator24E.<$>end = end; - GenSight.c__Iterator24E expr_23 = c__Iterator24E; - expr_23.$PC = -2; - return expr_23; } public static bool LineOfSightToEdges(IntVec3 start, IntVec3 end, Map map, bool skipFirstCell = false, Func validator = null) @@ -140,12 +143,9 @@ public static bool LineOfSightToEdges(IntVec3 start, IntVec3 end, Map map, bool int num = (start * 2).DistanceToSquared(end * 2); for (int i = 0; i < 4; i++) { - if ((start * 2).DistanceToSquared(end * 2 + GenAdj.CardinalDirections[i]) <= num) + if ((start * 2).DistanceToSquared(end * 2 + GenAdj.CardinalDirections[i]) <= num && GenSight.LineOfSight(start, end, map, skipFirstCell, validator, GenAdj.CardinalDirections[i].x, GenAdj.CardinalDirections[i].z)) { - if (GenSight.LineOfSight(start, end, map, skipFirstCell, validator, GenAdj.CardinalDirections[i].x, GenAdj.CardinalDirections[i].z)) - { - return true; - } + return true; } } return false; diff --git a/Assembly-CSharp/Verse/GenSpawn.cs b/Assembly-CSharp/Verse/GenSpawn.cs index 61c30436c..9d2fe0ee0 100644 --- a/Assembly-CSharp/Verse/GenSpawn.cs +++ b/Assembly-CSharp/Verse/GenSpawn.cs @@ -1,5 +1,6 @@ using RimWorld; using System; +using System.Collections.Generic; using System.Linq; namespace Verse @@ -25,14 +26,7 @@ public static Thing Spawn(Thing newThing, IntVec3 loc, Map map, Rot4 rot, bool r } if (!loc.InBounds(map)) { - Log.Error(string.Concat(new object[] - { - "Tried to spawn ", - newThing, - " out of bounds at ", - loc, - "." - })); + Log.Error("Tried to spawn " + newThing + " out of bounds at " + loc + "."); return null; } if (newThing.Spawned) @@ -66,15 +60,24 @@ public static Thing Spawn(Thing newThing, IntVec3 loc, Map map, Rot4 rot, bool r public static void WipeExistingThings(IntVec3 thingPos, Rot4 thingRot, BuildableDef thingDef, Map map, DestroyMode mode) { - foreach (IntVec3 current in GenAdj.CellsOccupiedBy(thingPos, thingRot, thingDef.Size)) + foreach (IntVec3 item in GenAdj.CellsOccupiedBy(thingPos, thingRot, thingDef.Size)) { - foreach (Thing current2 in map.thingGrid.ThingsAt(current).ToList()) + List.Enumerator enumerator2 = map.thingGrid.ThingsAt(item).ToList().GetEnumerator(); + try { - if (GenSpawn.SpawningWipes(thingDef, current2.def)) + while (enumerator2.MoveNext()) { - current2.Destroy(mode); + Thing current2 = enumerator2.Current; + if (GenSpawn.SpawningWipes(thingDef, current2.def)) + { + current2.Destroy(mode); + } } } + finally + { + ((IDisposable)(object)enumerator2).Dispose(); + } } } @@ -85,15 +88,24 @@ public static bool WouldWipeAnythingWith(IntVec3 thingPos, Rot4 thingRot, Builda public static bool WouldWipeAnythingWith(CellRect cellRect, BuildableDef thingDef, Map map, Predicate predicate) { - foreach (IntVec3 current in cellRect) + foreach (IntVec3 item in cellRect) { - foreach (Thing current2 in map.thingGrid.ThingsAt(current).ToList()) + List.Enumerator enumerator2 = map.thingGrid.ThingsAt(item).ToList().GetEnumerator(); + try { - if (GenSpawn.SpawningWipes(thingDef, current2.def) && predicate(current2)) + while (enumerator2.MoveNext()) { - return true; + Thing current2 = enumerator2.Current; + if (GenSpawn.SpawningWipes(thingDef, current2.def) && predicate(current2)) + { + return true; + } } } + finally + { + ((IDisposable)(object)enumerator2).Dispose(); + } } return false; } @@ -102,90 +114,102 @@ public static bool SpawningWipes(BuildableDef newEntDef, BuildableDef oldEntDef) { ThingDef thingDef = newEntDef as ThingDef; ThingDef thingDef2 = oldEntDef as ThingDef; - if (thingDef == null || thingDef2 == null) - { - return false; - } - if (thingDef.category == ThingCategory.Attachment || thingDef.category == ThingCategory.Mote || thingDef.category == ThingCategory.Filth || thingDef.category == ThingCategory.Projectile) - { - return false; - } - if (!thingDef2.destroyable) - { - return false; - } - if (thingDef.category == ThingCategory.Plant) - { - return false; - } - if (thingDef2.category == ThingCategory.Filth && thingDef.passability != Traversability.Standable) - { - return true; - } - if (thingDef.EverTransmitsPower && thingDef2 == ThingDefOf.PowerConduit) - { - return true; - } - if (thingDef.IsFrame && GenSpawn.SpawningWipes(thingDef.entityDefToBuild, oldEntDef)) - { - return true; - } - BuildableDef buildableDef = GenConstruct.BuiltDefOf(thingDef); - BuildableDef buildableDef2 = GenConstruct.BuiltDefOf(thingDef2); - if (buildableDef == null || buildableDef2 == null) - { - return false; - } - ThingDef thingDef3 = thingDef.entityDefToBuild as ThingDef; - if (thingDef2.IsBlueprint) + if (thingDef != null && thingDef2 != null) { - if (thingDef.IsBlueprint) + if (thingDef.category != ThingCategory.Attachment && thingDef.category != ThingCategory.Mote && thingDef.category != ThingCategory.Filth && thingDef.category != ThingCategory.Projectile) { - if (thingDef3 != null && thingDef3.building != null && thingDef3.building.canPlaceOverWall && thingDef2.entityDefToBuild is ThingDef && (ThingDef)thingDef2.entityDefToBuild == ThingDefOf.Wall) + if (!thingDef2.destroyable) + { + return false; + } + if (thingDef.category == ThingCategory.Plant) + { + return false; + } + if (((thingDef2.category == ThingCategory.Filth) ? thingDef.passability : Traversability.Standable) != 0) + { + return true; + } + if (thingDef.EverTransmitsPower && thingDef2 == ThingDefOf.PowerConduit) + { + return true; + } + if (thingDef.IsFrame && GenSpawn.SpawningWipes(thingDef.entityDefToBuild, oldEntDef)) { return true; } - if (thingDef2.entityDefToBuild is TerrainDef) + BuildableDef buildableDef = GenConstruct.BuiltDefOf(thingDef); + BuildableDef buildableDef2 = GenConstruct.BuiltDefOf(thingDef2); + if (buildableDef != null && buildableDef2 != null) { - if (thingDef.entityDefToBuild is ThingDef && ((ThingDef)thingDef.entityDefToBuild).coversFloor) + ThingDef thingDef3 = thingDef.entityDefToBuild as ThingDef; + if (thingDef2.IsBlueprint) { - return true; + if (thingDef.IsBlueprint) + { + if (thingDef3 != null && thingDef3.building != null && thingDef3.building.canPlaceOverWall && thingDef2.entityDefToBuild is ThingDef && (ThingDef)thingDef2.entityDefToBuild == ThingDefOf.Wall) + { + return true; + } + if (thingDef2.entityDefToBuild is TerrainDef) + { + if (thingDef.entityDefToBuild is ThingDef && ((ThingDef)thingDef.entityDefToBuild).coversFloor) + { + return true; + } + if (thingDef.entityDefToBuild is TerrainDef) + { + return true; + } + } + } + if (thingDef2.entityDefToBuild == ThingDefOf.PowerConduit && thingDef.entityDefToBuild is ThingDef && (thingDef.entityDefToBuild as ThingDef).EverTransmitsPower) + { + return true; + } + return false; } - if (thingDef.entityDefToBuild is TerrainDef) + if ((thingDef2.IsFrame || thingDef2.IsBlueprint) && thingDef2.entityDefToBuild is TerrainDef) { - return true; + ThingDef thingDef4 = buildableDef as ThingDef; + if (thingDef4 != null && !thingDef4.CoexistsWithFloors) + { + return true; + } + } + if (thingDef2 == ThingDefOf.ActiveDropPod) + { + return false; + } + if (thingDef == ThingDefOf.ActiveDropPod) + { + if (thingDef2 == ThingDefOf.ActiveDropPod) + { + return false; + } + if (thingDef2.category == ThingCategory.Building && thingDef2.passability == Traversability.Impassable) + { + return true; + } + return false; } + if (thingDef.IsEdifice()) + { + if (thingDef.BlockPlanting && thingDef2.category == ThingCategory.Plant) + { + return true; + } + if (!(buildableDef is TerrainDef) && buildableDef2.IsEdifice()) + { + return true; + } + } + return false; } + return false; } - return thingDef2.entityDefToBuild == ThingDefOf.PowerConduit && thingDef.entityDefToBuild is ThingDef && (thingDef.entityDefToBuild as ThingDef).EverTransmitsPower; - } - if ((thingDef2.IsFrame || thingDef2.IsBlueprint) && thingDef2.entityDefToBuild is TerrainDef) - { - ThingDef thingDef4 = buildableDef as ThingDef; - if (thingDef4 != null && !thingDef4.CoexistsWithFloors) - { - return true; - } - } - if (thingDef2 == ThingDefOf.ActiveDropPod) - { return false; } - if (thingDef == ThingDefOf.ActiveDropPod) - { - return thingDef2 != ThingDefOf.ActiveDropPod && (thingDef2.category == ThingCategory.Building && thingDef2.passability == Traversability.Impassable); - } - if (thingDef.IsEdifice()) - { - if (thingDef.BlockPlanting && thingDef2.category == ThingCategory.Plant) - { - return true; - } - if (!(buildableDef is TerrainDef) && buildableDef2.IsEdifice()) - { - return true; - } - } return false; } } diff --git a/Assembly-CSharp/Verse/GenStep.cs b/Assembly-CSharp/Verse/GenStep.cs index ab821ff8d..2f01de593 100644 --- a/Assembly-CSharp/Verse/GenStep.cs +++ b/Assembly-CSharp/Verse/GenStep.cs @@ -1,5 +1,3 @@ -using System; - namespace Verse { public abstract class GenStep diff --git a/Assembly-CSharp/Verse/GenStepDef.cs b/Assembly-CSharp/Verse/GenStepDef.cs index 2ced2a5af..2b69d0f02 100644 --- a/Assembly-CSharp/Verse/GenStepDef.cs +++ b/Assembly-CSharp/Verse/GenStepDef.cs @@ -1,5 +1,4 @@ using RimWorld; -using System; namespace Verse { diff --git a/Assembly-CSharp/Verse/GenStep_RandomSelector.cs b/Assembly-CSharp/Verse/GenStep_RandomSelector.cs index 5ac9dfc76..5720a3a37 100644 --- a/Assembly-CSharp/Verse/GenStep_RandomSelector.cs +++ b/Assembly-CSharp/Verse/GenStep_RandomSelector.cs @@ -9,7 +9,7 @@ public class GenStep_RandomSelector : GenStep public override void Generate(Map map) { - RandomGenStepSelectorOption randomGenStepSelectorOption = this.options.RandomElementByWeight((RandomGenStepSelectorOption opt) => opt.weight); + RandomGenStepSelectorOption randomGenStepSelectorOption = this.options.RandomElementByWeight((Func)((RandomGenStepSelectorOption opt) => opt.weight)); if (randomGenStepSelectorOption.genStep != null) { randomGenStepSelectorOption.genStep.Generate(map); diff --git a/Assembly-CSharp/Verse/GenStep_ScatterThings.cs b/Assembly-CSharp/Verse/GenStep_ScatterThings.cs index 52d4e0fa0..5d069261f 100644 --- a/Assembly-CSharp/Verse/GenStep_ScatterThings.cs +++ b/Assembly-CSharp/Verse/GenStep_ScatterThings.cs @@ -57,36 +57,25 @@ private List PossibleRotations public override void Generate(Map map) { - if (!this.allowOnWater && map.TileInfo.WaterCovered) - { + if (!base.allowOnWater && map.TileInfo.WaterCovered) return; - } int count = base.CalculateFinalCount(map); - IntRange one; - if (this.thingDef.ingestible != null && this.thingDef.ingestible.IsMeal && this.thingDef.stackLimit <= 10) - { - one = IntRange.one; - } - else if (this.thingDef.stackLimit > 5) - { - one = new IntRange(Mathf.RoundToInt((float)this.thingDef.stackLimit * 0.5f), this.thingDef.stackLimit); - } - else + IntRange stackSizeRange = (this.thingDef.ingestible == null || !this.thingDef.ingestible.IsMeal || this.thingDef.stackLimit > 10) ? ((this.thingDef.stackLimit <= 5) ? new IntRange(this.thingDef.stackLimit, this.thingDef.stackLimit) : new IntRange(Mathf.RoundToInt((float)((float)this.thingDef.stackLimit * 0.5)), this.thingDef.stackLimit)) : IntRange.one; + List list = GenStep_ScatterThings.CountDividedIntoStacks(count, stackSizeRange); + int num = 0; + while (num < list.Count) { - one = new IntRange(this.thingDef.stackLimit, this.thingDef.stackLimit); - } - List list = GenStep_ScatterThings.CountDividedIntoStacks(count, one); - for (int i = 0; i < list.Count; i++) - { - IntVec3 intVec; - if (!this.TryFindScatterCell(map, out intVec)) + IntVec3 intVec = default(IntVec3); + if (this.TryFindScatterCell(map, out intVec)) { - return; + this.ScatterAt(intVec, map, list[num]); + base.usedSpots.Add(intVec); + num++; + continue; } - this.ScatterAt(intVec, map, list[i]); - this.usedSpots.Add(intVec); + return; } - this.usedSpots.Clear(); + base.usedSpots.Clear(); this.clusterCenter = IntVec3.Invalid; this.leftInCluster = 0; } @@ -104,11 +93,8 @@ protected override bool TryFindScatterCell(Map map, out IntVec3 result) this.leftInCluster = this.clusterSize; } this.leftInCluster--; - result = CellFinder.RandomClosewalkCellNear(this.clusterCenter, map, 4, delegate(IntVec3 x) - { - Rot4 rot; - return this.TryGetRandomValidRotation(x, map, out rot); - }); + Rot4 rot = default(Rot4); + result = CellFinder.RandomClosewalkCellNear(this.clusterCenter, map, 4, (Predicate)((IntVec3 x) => this.TryGetRandomValidRotation(x, map, out rot))); return result.IsValid; } return base.TryFindScatterCell(map, out result); @@ -116,42 +102,44 @@ protected override bool TryFindScatterCell(Map map, out IntVec3 result) protected override void ScatterAt(IntVec3 loc, Map map, int stackCount = 1) { - Rot4 rot; + Rot4 rot = default(Rot4); if (!this.TryGetRandomValidRotation(loc, map, out rot)) { Log.Warning("Could not find any valid rotation for " + this.thingDef); - return; } - if (this.clearSpaceSize > 0) + else { - foreach (IntVec3 current in GridShapeMaker.IrregularLump(loc, map, this.clearSpaceSize)) + if (this.clearSpaceSize > 0) { - Building edifice = current.GetEdifice(map); - if (edifice != null) + foreach (IntVec3 item in GridShapeMaker.IrregularLump(loc, map, this.clearSpaceSize)) { - edifice.Destroy(DestroyMode.Vanish); + Building edifice = item.GetEdifice(map); + if (edifice != null) + { + edifice.Destroy(DestroyMode.Vanish); + } } } - } - Thing thing = ThingMaker.MakeThing(this.thingDef, this.stuff); - if (this.thingDef.Minifiable) - { - thing = thing.MakeMinified(); - } - if (thing.def.category == ThingCategory.Item) - { - thing.stackCount = stackCount; - thing.SetForbidden(true, false); - Thing thing2; - GenPlace.TryPlaceThing(thing, loc, map, ThingPlaceMode.Near, out thing2, null); - if (this.nearPlayerStart && thing2 != null && thing2.def.category == ThingCategory.Item && TutorSystem.TutorialMode) + Thing thing = ThingMaker.MakeThing(this.thingDef, this.stuff); + if (this.thingDef.Minifiable) { - Find.TutorialState.AddStartingItem(thing2); + thing = thing.MakeMinified(); + } + if (thing.def.category == ThingCategory.Item) + { + thing.stackCount = stackCount; + thing.SetForbidden(true, false); + Thing thing2 = default(Thing); + GenPlace.TryPlaceThing(thing, loc, map, ThingPlaceMode.Near, out thing2, (Action)null); + if (base.nearPlayerStart && thing2 != null && thing2.def.category == ThingCategory.Item && TutorSystem.TutorialMode) + { + Find.TutorialState.AddStartingItem(thing2); + } + } + else + { + GenSpawn.Spawn(thing, loc, map, rot, false); } - } - else - { - GenSpawn.Spawn(thing, loc, map, rot, false); } } @@ -161,18 +149,18 @@ protected override bool CanScatterAt(IntVec3 loc, Map map) { return false; } - Rot4 rot; + Rot4 rot = default(Rot4); if (!this.TryGetRandomValidRotation(loc, map, out rot)) { return false; } - if (this.terrainValidationRadius > 0f) + if (this.terrainValidationRadius > 0.0) { - foreach (IntVec3 current in GenRadial.RadialCellsAround(loc, this.terrainValidationRadius, true)) + foreach (IntVec3 item in GenRadial.RadialCellsAround(loc, this.terrainValidationRadius, true)) { - if (current.InBounds(map)) + if (item.InBounds(map)) { - TerrainDef terrain = current.GetTerrain(map); + TerrainDef terrain = item.GetTerrain(map); for (int i = 0; i < this.terrainValidationDisallowed.Count; i++) { if (terrain.HasTag(this.terrainValidationDisallowed[i])) @@ -182,7 +170,6 @@ protected override bool CanScatterAt(IntVec3 loc, Map map) } } } - return true; } return true; } @@ -197,7 +184,7 @@ private bool TryGetRandomValidRotation(IntVec3 loc, Map map, out Rot4 rot) GenStep_ScatterThings.tmpRotations.Add(possibleRotations[i]); } } - if (GenStep_ScatterThings.tmpRotations.TryRandomElement(out rot)) + if (((IEnumerable)GenStep_ScatterThings.tmpRotations).TryRandomElement(out rot)) { GenStep_ScatterThings.tmpRotations.Clear(); return true; @@ -208,7 +195,15 @@ private bool TryGetRandomValidRotation(IntVec3 loc, Map map, out Rot4 rot) private bool IsRotationValid(IntVec3 loc, Rot4 rot, Map map) { - return GenAdj.OccupiedRect(loc, rot, this.thingDef.size).InBounds(map) && !GenSpawn.WouldWipeAnythingWith(loc, rot, this.thingDef, map, (Thing x) => x.def == this.thingDef || (x.def.category != ThingCategory.Plant && x.def.category != ThingCategory.Filth)); + if (!GenAdj.OccupiedRect(loc, rot, this.thingDef.size).InBounds(map)) + { + return false; + } + if (GenSpawn.WouldWipeAnythingWith(loc, rot, this.thingDef, map, (Predicate)((Thing x) => x.def == this.thingDef || (x.def.category != ThingCategory.Plant && x.def.category != ThingCategory.Filth)))) + { + return false; + } + return true; } public static List CountDividedIntoStacks(int count, IntRange stackSizeRange) @@ -226,23 +221,20 @@ public static List CountDividedIntoStacks(int count, IntRange stackSizeRang { int num2 = Rand.RangeInclusive(0, list.Count - 1); int num3 = Rand.RangeInclusive(0, list.Count - 1); - if (num2 != num3) + if (num2 != num3 && list[num2] > list[num3]) { - if (list[num2] > list[num3]) - { - int num4 = (int)((float)(list[num2] - list[num3]) * Rand.Value); - List list2; - List expr_9B = list2 = list; - int num5; - int expr_9F = num5 = num2; - num5 = list2[num5]; - expr_9B[expr_9F] = num5 - num4; - List list3; - List expr_B8 = list3 = list; - int expr_BD = num5 = num3; - num5 = list3[num5]; - expr_B8[expr_BD] = num5 + num4; - } + int num4 = (int)((float)(list[num2] - list[num3]) * Rand.Value); + List list2; + List obj = list2 = list; + int index; + int index2 = index = num2; + index = list2[index]; + obj[index2] = index - num4; + List list3; + List obj2 = list3 = list; + int index3 = index = num3; + index = list3[index]; + obj2[index3] = index + num4; } } } diff --git a/Assembly-CSharp/Verse/GenStep_Scatterer.cs b/Assembly-CSharp/Verse/GenStep_Scatterer.cs index 7524ff799..0a42794bb 100644 --- a/Assembly-CSharp/Verse/GenStep_Scatterer.cs +++ b/Assembly-CSharp/Verse/GenStep_Scatterer.cs @@ -39,19 +39,20 @@ public abstract class GenStep_Scatterer : GenStep public override void Generate(Map map) { if (!this.allowOnWater && map.TileInfo.WaterCovered) - { return; - } int num = this.CalculateFinalCount(map); - for (int i = 0; i < num; i++) + int num2 = 0; + while (num2 < num) { - IntVec3 intVec; - if (!this.TryFindScatterCell(map, out intVec)) + IntVec3 intVec = default(IntVec3); + if (this.TryFindScatterCell(map, out intVec)) { - return; + this.ScatterAt(intVec, map, 1); + this.usedSpots.Add(intVec); + num2++; + continue; } - this.ScatterAt(intVec, map, 1); - this.usedSpots.Add(intVec); + return; } this.usedSpots.Clear(); } @@ -60,7 +61,7 @@ protected virtual bool TryFindScatterCell(Map map, out IntVec3 result) { if (this.nearMapCenter) { - if (RCellFinder.TryFindRandomCellNearWith(map.Center, (IntVec3 x) => this.CanScatterAt(x, map), map, out result, 3)) + if (RCellFinder.TryFindRandomCellNearWith(map.Center, (Predicate)((IntVec3 x) => this.CanScatterAt(x, map)), map, out result, 3)) { return true; } @@ -69,10 +70,10 @@ protected virtual bool TryFindScatterCell(Map map, out IntVec3 result) { if (this.nearPlayerStart) { - result = CellFinder.RandomClosewalkCellNear(MapGenerator.PlayerStartSpot, map, 20, (IntVec3 x) => this.CanScatterAt(x, map)); + result = CellFinder.RandomClosewalkCellNear(MapGenerator.PlayerStartSpot, map, 20, (Predicate)((IntVec3 x) => this.CanScatterAt(x, map))); return true; } - if (CellFinderLoose.TryFindRandomNotEdgeCellWith(5, (IntVec3 x) => this.CanScatterAt(x, map), map, out result)) + if (CellFinderLoose.TryFindRandomNotEdgeCellWith(5, (Predicate)((IntVec3 x) => this.CanScatterAt(x, map)), map, out result)) { return true; } @@ -146,9 +147,10 @@ public static int CountFromPer10kCells(float countPer10kCells, Map map, int mapS { if (mapSize < 0) { - mapSize = map.Size.x; + IntVec3 size = map.Size; + mapSize = size.x; } - int num = Mathf.RoundToInt(10000f / countPer10kCells); + int num = Mathf.RoundToInt((float)(10000.0 / countPer10kCells)); return Mathf.RoundToInt((float)(mapSize * mapSize) / (float)num); } diff --git a/Assembly-CSharp/Verse/GenStep_TerrainPatches.cs b/Assembly-CSharp/Verse/GenStep_TerrainPatches.cs index 925c258e2..f916ffc6f 100644 --- a/Assembly-CSharp/Verse/GenStep_TerrainPatches.cs +++ b/Assembly-CSharp/Verse/GenStep_TerrainPatches.cs @@ -1,4 +1,3 @@ -using System; using UnityEngine; namespace Verse @@ -13,14 +12,14 @@ public class GenStep_TerrainPatches : GenStep public override void Generate(Map map) { - int num = Mathf.RoundToInt((float)map.Area / 10000f * this.patchesPer10kCellsRange.RandomInRange); - for (int i = 0; i < num; i++) + int num = Mathf.RoundToInt((float)((float)map.Area / 10000.0 * this.patchesPer10kCellsRange.RandomInRange)); + for (int num2 = 0; num2 < num; num2++) { float randomInRange = this.patchSizeRange.RandomInRange; IntVec3 a = CellFinder.RandomCell(map); - foreach (IntVec3 current in GenRadial.RadialPatternInRadius(randomInRange / 2f)) + foreach (IntVec3 item in GenRadial.RadialPatternInRadius((float)(randomInRange / 2.0))) { - IntVec3 c = a + current; + IntVec3 c = a + item; if (c.InBounds(map)) { map.terrainGrid.SetTerrain(c, this.terrainDef); diff --git a/Assembly-CSharp/Verse/GenString.cs b/Assembly-CSharp/Verse/GenString.cs index 0c7bd032b..b6c73efd6 100644 --- a/Assembly-CSharp/Verse/GenString.cs +++ b/Assembly-CSharp/Verse/GenString.cs @@ -1,5 +1,3 @@ -using System; - namespace Verse { public static class GenString @@ -30,11 +28,11 @@ public static string ToStringCached(this int num) public static string TrimmedToLength(this string str, int length) { - if (str == null || str.Length <= length) + if (str != null && str.Length > length) { - return str; + return str.Substring(0, length); } - return str.Substring(0, length); + return str; } } } diff --git a/Assembly-CSharp/Verse/GenTemperature.cs b/Assembly-CSharp/Verse/GenTemperature.cs index a4194cd7b..a3d5bb854 100644 --- a/Assembly-CSharp/Verse/GenTemperature.cs +++ b/Assembly-CSharp/Verse/GenTemperature.cs @@ -28,10 +28,10 @@ public static float AverageTemperatureAtTileForTwelfth(int tile, Twelfth twelfth float num3 = 0f; for (int i = 0; i < 120; i++) { - int absTick = num2 + num + Mathf.RoundToInt((float)i / 120f * 300000f); + int absTick = num2 + num + Mathf.RoundToInt((float)((float)i / 120.0 * 300000.0)); num3 += GenTemperature.GetTemperatureFromSeasonAtTile(absTick, tile); } - return num3 / 120f; + return (float)(num3 / 120.0); } public static FloatRange ComfortableTemperatureRange(this Pawn p) @@ -49,7 +49,7 @@ public static FloatRange SafeTemperatureRange(this Pawn p) public static float GetTemperatureForCell(IntVec3 c, Map map) { - float result; + float result = default(float); GenTemperature.TryGetTemperatureForCell(c, map, out result); return result; } @@ -106,7 +106,7 @@ public static bool TryGetAirTemperatureAroundThing(Thing t, out float temperatur List list = GenAdjFast.AdjacentCells8Way(t); for (int i = 0; i < list.Count; i++) { - float num3; + float num3 = default(float); if (list[i].InBounds(t.Map) && GenTemperature.TryGetDirectAirTemperatureForCell(list[i], t.Map, out num3)) { num += num3; @@ -124,16 +124,18 @@ public static bool TryGetAirTemperatureAroundThing(Thing t, out float temperatur public static float OffsetFromSunCycle(int absTick, int tile) { - float num = GenDate.DayPercent((long)absTick, Find.WorldGrid.LongLatOf(tile).x); - float f = 6.28318548f * (num + 0.32f); - return Mathf.Cos(f) * 7f; + long absTicks = absTick; + Vector2 vector = Find.WorldGrid.LongLatOf(tile); + float num = GenDate.DayPercent(absTicks, vector.x); + float f = (float)(6.2831854820251465 * (num + 0.31999999284744263)); + return (float)(Mathf.Cos(f) * 7.0); } public static float OffsetFromSeasonCycle(int absTick, int tile) { - float num = (float)(absTick / 60000 % 60) / 60f; - float f = 6.28318548f * (num - Season.Winter.GetMiddleTwelfth(0f).GetBeginningYearPct()); - return Mathf.Cos(f) * -GenTemperature.SeasonalShiftAmplitudeAt(tile); + float num = (float)((float)(absTick / 60000 % 60) / 60.0); + float f = (float)(6.2831854820251465 * (num - Season.Winter.GetMiddleTwelfth(0f).GetBeginningYearPct())); + return (float)(Mathf.Cos(f) * (0.0 - GenTemperature.SeasonalShiftAmplitudeAt(tile))); } public static float GetTemperatureFromSeasonAtTile(int absTick, int tile) @@ -158,11 +160,12 @@ public static float GetTemperatureAtTile(int tile) public static float SeasonalShiftAmplitudeAt(int tile) { - if (Find.WorldGrid.LongLatOf(tile).y >= 0f) + Vector2 vector = Find.WorldGrid.LongLatOf(tile); + if (vector.y >= 0.0) { return TemperatureTuning.SeasonalTempVariationCurve.Evaluate(Find.WorldGrid.DistanceFromEquatorNormalized(tile)); } - return -TemperatureTuning.SeasonalTempVariationCurve.Evaluate(Find.WorldGrid.DistanceFromEquatorNormalized(tile)); + return (float)(0.0 - TemperatureTuning.SeasonalTempVariationCurve.Evaluate(Find.WorldGrid.DistanceFromEquatorNormalized(tile))); } public static List TwelfthsInAverageTemperatureRange(int tile, float minTemp, float maxTemp) @@ -170,67 +173,61 @@ public static List TwelfthsInAverageTemperatureRange(int tile, float mi List twelfths = new List(); for (int i = 0; i < 12; i++) { - float num = GenTemperature.AverageTemperatureAtTileForTwelfth(tile, (Twelfth)i); + float num = GenTemperature.AverageTemperatureAtTileForTwelfth(tile, (Twelfth)(byte)i); if (num >= minTemp && num <= maxTemp) { - twelfths.Add((Twelfth)i); + twelfths.Add((Twelfth)(byte)i); } } - if (twelfths.Count <= 1 || twelfths.Count == 12) + if (twelfths.Count > 1 && twelfths.Count != 12) { - return twelfths; - } - if (twelfths.Contains(Twelfth.Twelfth) && twelfths.Contains(Twelfth.First)) - { - Twelfth twelfth = twelfths.First((Twelfth m) => !twelfths.Contains((Twelfth)(m - Twelfth.Second))); - List list = new List(); - for (int j = (int)twelfth; j < 12; j++) + if (twelfths.Contains(Twelfth.Twelfth) && twelfths.Contains(Twelfth.First)) { - if (!twelfths.Contains((Twelfth)j)) + Twelfth twelfth = twelfths.First((Func)((Twelfth m) => !twelfths.Contains(m - 1))); + List list = new List(); + int num2 = (int)twelfth; + while (num2 < 12 && twelfths.Contains((Twelfth)(byte)num2)) { - break; + list.Add((Twelfth)(byte)num2); + num2++; } - list.Add((Twelfth)j); - } - for (int k = 0; k < 12; k++) - { - if (!twelfths.Contains((Twelfth)k)) + int num3 = 0; + while (num3 < 12 && twelfths.Contains((Twelfth)(byte)num3)) { - break; + list.Add((Twelfth)(byte)num3); + num3++; } - list.Add((Twelfth)k); } + return twelfths; } return twelfths; } public static Twelfth EarliestTwelfthInAverageTemperatureRange(int tile, float minTemp, float maxTemp) { - int i = 0; - while (i < 12) + for (int i = 0; i < 12; i++) { - float num = GenTemperature.AverageTemperatureAtTileForTwelfth(tile, (Twelfth)i); + float num = GenTemperature.AverageTemperatureAtTileForTwelfth(tile, (Twelfth)(byte)i); if (num >= minTemp && num <= maxTemp) { if (i != 0) { - return (Twelfth)i; + return (Twelfth)(byte)i; } - Twelfth twelfth = (Twelfth)i; - for (int j = 0; j < 12; j++) + Twelfth twelfth = (Twelfth)(byte)i; + int num2 = 0; + while (num2 < 12) { - float num2 = GenTemperature.AverageTemperatureAtTileForTwelfth(tile, twelfth.PreviousTwelfth()); - if (num2 < minTemp || num2 > maxTemp) + float num3 = GenTemperature.AverageTemperatureAtTileForTwelfth(tile, twelfth.PreviousTwelfth()); + if (!(num3 < minTemp) && !(num3 > maxTemp)) { - return twelfth; + twelfth = twelfth.PreviousTwelfth(); + num2++; + continue; } - twelfth = twelfth.PreviousTwelfth(); + return twelfth; } - return (Twelfth)i; - } - else - { - i++; + return (Twelfth)(byte)i; } } return Twelfth.Undefined; @@ -273,7 +270,7 @@ public static bool PushHeat(IntVec3 c, Map map, float energy) public static void PushHeat(Thing t, float energy) { - IntVec3 c; + IntVec3 c = default(IntVec3); if (t.GetRoomGroup() != null) { GenTemperature.PushHeat(t.Position, t.Map, energy); @@ -287,24 +284,24 @@ public static void PushHeat(Thing t, float energy) public static float ControlTemperatureTempChange(IntVec3 cell, Map map, float energyLimit, float targetTemperature) { RoomGroup roomGroup = cell.GetRoomGroup(map); - if (roomGroup == null || roomGroup.UsesOutdoorTemperature) - { - return 0f; - } - float b = energyLimit / (float)roomGroup.CellCount; - float a = targetTemperature - roomGroup.Temperature; - float num; - if (energyLimit > 0f) - { - num = Mathf.Min(a, b); - num = Mathf.Max(num, 0f); - } - else + if (roomGroup != null && !roomGroup.UsesOutdoorTemperature) { - num = Mathf.Max(a, b); - num = Mathf.Min(num, 0f); + float b = energyLimit / (float)roomGroup.CellCount; + float a = targetTemperature - roomGroup.Temperature; + float num = 0f; + if (energyLimit > 0.0) + { + num = Mathf.Min(a, b); + num = Mathf.Max(num, 0f); + } + else + { + num = Mathf.Max(a, b); + num = Mathf.Min(num, 0f); + } + return num; } - return num; + return 0f; } public static void EqualizeTemperaturesThroughBuilding(Building b, float rate, bool twoWay) @@ -345,73 +342,71 @@ public static void EqualizeTemperaturesThroughBuilding(Building b, float rate, b } } } - if (num == 0) - { - return; - } - float num3 = num2 / (float)num; - RoomGroup roomGroup3 = b.GetRoomGroup(); - if (roomGroup3 != null) + if (num != 0) { - roomGroup3.Temperature = num3; - } - if (num == 1) - { - return; - } - float num4 = 1f; - for (int k = 0; k < num; k++) - { - if (!GenTemperature.beqRoomGroups[k].UsesOutdoorTemperature) + float num3 = num2 / (float)num; + RoomGroup roomGroup3 = b.GetRoomGroup(); + if (roomGroup3 != null) { - float temperature = GenTemperature.beqRoomGroups[k].Temperature; - float num5 = num3 - temperature; - float num6 = num5 * rate; - float num7 = num6 / (float)GenTemperature.beqRoomGroups[k].CellCount; - float num8 = GenTemperature.beqRoomGroups[k].Temperature + num7; - if (num6 > 0f && num8 > num3) + roomGroup3.Temperature = num3; + } + if (num != 1) + { + float num4 = 1f; + for (int num5 = 0; num5 < num; num5++) { - num8 = num3; + if (!GenTemperature.beqRoomGroups[num5].UsesOutdoorTemperature) + { + float temperature = GenTemperature.beqRoomGroups[num5].Temperature; + float num6 = num3 - temperature; + float num7 = num6 * rate; + float num8 = num7 / (float)GenTemperature.beqRoomGroups[num5].CellCount; + float num9 = GenTemperature.beqRoomGroups[num5].Temperature + num8; + if (num7 > 0.0 && num9 > num3) + { + num9 = num3; + } + else if (num7 < 0.0 && num9 < num3) + { + num9 = num3; + } + float num10 = Mathf.Abs((num9 - temperature) * (float)GenTemperature.beqRoomGroups[num5].CellCount / num7); + if (num10 < num4) + { + num4 = num10; + } + } } - else if (num6 < 0f && num8 < num3) + for (int num11 = 0; num11 < num; num11++) { - num8 = num3; + if (!GenTemperature.beqRoomGroups[num11].UsesOutdoorTemperature) + { + float temperature2 = GenTemperature.beqRoomGroups[num11].Temperature; + float num12 = num3 - temperature2; + float num13 = num12 * rate * num4; + float num14 = num13 / (float)GenTemperature.beqRoomGroups[num11].CellCount; + GenTemperature.beqRoomGroups[num11].Temperature += num14; + } } - float num9 = Mathf.Abs((num8 - temperature) * (float)GenTemperature.beqRoomGroups[k].CellCount / num6); - if (num9 < num4) + for (int k = 0; k < GenTemperature.beqRoomGroups.Length; k++) { - num4 = num9; + GenTemperature.beqRoomGroups[k] = null; } } } - for (int l = 0; l < num; l++) - { - if (!GenTemperature.beqRoomGroups[l].UsesOutdoorTemperature) - { - float temperature2 = GenTemperature.beqRoomGroups[l].Temperature; - float num10 = num3 - temperature2; - float num11 = num10 * rate * num4; - float num12 = num11 / (float)GenTemperature.beqRoomGroups[l].CellCount; - GenTemperature.beqRoomGroups[l].Temperature += num12; - } - } - for (int m = 0; m < GenTemperature.beqRoomGroups.Length; m++) - { - GenTemperature.beqRoomGroups[m] = null; - } } public static float RotRateAtTemperature(float temperature) { - if (temperature < 0f) + if (temperature < 0.0) { return 0f; } - if (temperature >= 10f) + if (temperature >= 10.0) { return 1f; } - return temperature / 10f; + return (float)(temperature / 10.0); } public static bool FactionOwnsPassableRoomInTemperatureRange(Faction faction, FloatRange tempRange, Map map) @@ -437,14 +432,22 @@ public static float CelsiusTo(float temp, TemperatureDisplayMode oldMode) switch (oldMode) { case TemperatureDisplayMode.Celsius: + { return temp; + } case TemperatureDisplayMode.Fahrenheit: - return temp * 1.8f + 32f; + { + return (float)(temp * 1.7999999523162842 + 32.0); + } case TemperatureDisplayMode.Kelvin: - return temp + 273.15f; + { + return (float)(temp + 273.14999389648437); + } default: + { throw new InvalidOperationException(); } + } } public static float CelsiusToOffset(float temp, TemperatureDisplayMode oldMode) @@ -452,14 +455,22 @@ public static float CelsiusToOffset(float temp, TemperatureDisplayMode oldMode) switch (oldMode) { case TemperatureDisplayMode.Celsius: + { return temp; + } case TemperatureDisplayMode.Fahrenheit: - return temp * 1.8f; + { + return (float)(temp * 1.7999999523162842); + } case TemperatureDisplayMode.Kelvin: + { return temp; + } default: + { throw new InvalidOperationException(); } + } } public static float ConvertTemperatureOffset(float temp, TemperatureDisplayMode oldMode, TemperatureDisplayMode newMode) @@ -467,15 +478,19 @@ public static float ConvertTemperatureOffset(float temp, TemperatureDisplayMode switch (oldMode) { case TemperatureDisplayMode.Fahrenheit: - temp /= 1.8f; + { + temp = (float)(temp / 1.7999999523162842); break; } + } switch (newMode) { case TemperatureDisplayMode.Fahrenheit: - temp *= 1.8f; + { + temp = (float)(temp * 1.7999999523162842); break; } + } return temp; } } diff --git a/Assembly-CSharp/Verse/GenText.cs b/Assembly-CSharp/Verse/GenText.cs index 0d5294b52..2161554d3 100644 --- a/Assembly-CSharp/Verse/GenText.cs +++ b/Assembly-CSharp/Verse/GenText.cs @@ -2,7 +2,6 @@ using System; using System.Collections; using System.Collections.Generic; -using System.Diagnostics; using System.IO; using System.Linq; using System.Text; @@ -84,30 +83,29 @@ public static string AdjustedForKeys(this string text) while (true) { int num = text.IndexOf("{Key:"); - if (num < 0) + if (num >= 0) { - break; - } - int num2 = num; - while (text[num2] != '}') - { - num2++; - if (num2 == text.Length - 1) + int num2 = num; + while (text[num2] != '}') { - goto Block_1; + num2++; + if (num2 == text.Length - 1) + { + Log.Error("Cannot adjust for keys (mismatched braces): '" + text + "'"); + return text; + } } + string defName = text.Substring(num + 5, num2 - (num + 5)); + KeyBindingDef namedSilentFail = DefDatabase.GetNamedSilentFail(defName); + if (namedSilentFail != null) + { + text = text.Substring(0, num) + namedSilentFail.MainKeyLabel + text.Substring(num2 + 1); + } + continue; } - string defName = text.Substring(num + 5, num2 - (num + 5)); - KeyBindingDef namedSilentFail = DefDatabase.GetNamedSilentFail(defName); - if (namedSilentFail != null) - { - text = text.Substring(0, num) + namedSilentFail.MainKeyLabel + text.Substring(num2 + 1); - } + break; } return text; - Block_1: - Log.Error("Cannot adjust for keys (mismatched braces): '" + text + "'"); - return text; } public static string LabelIndefinite(this Pawn pawn) @@ -132,7 +130,7 @@ public static string LabelDefinite(this Pawn pawn) public static string RandomSeedString() { - return GrammarResolver.Resolve("seed", RulePackDefOf.SeedGenerator.Rules, null).ToLower(); + return GrammarResolver.Resolve("seed", RulePackDefOf.SeedGenerator.Rules, (string)null).ToLower(); } public static string WithoutVowels(string s) @@ -140,22 +138,30 @@ public static string WithoutVowels(string s) string vowels = "aeiouy"; return new string((from c in s where !vowels.Contains(c) - select c).ToArray()); + select c).ToArray()); } - public static string MarchingEllipsis(float offset = 0f) + public static string MarchingEllipsis(float offset = 0) { switch (Mathf.FloorToInt(Time.realtimeSinceStartup + offset) % 3) { case 0: + { return "."; + } case 1: + { return ".."; + } case 2: + { return "..."; + } default: + { throw new Exception(); } + } } public static void SetTextSizeToFit(string text, Rect r) @@ -170,11 +176,7 @@ public static void SetTextSizeToFit(string text, Rect r) public static string TrimEndNewlines(this string s) { - return s.TrimEnd(new char[] - { - '\r', - '\n' - }); + return s.TrimEnd('\r', '\n'); } public static string Indented(this string s) @@ -204,9 +206,9 @@ public static int StableStringHash(string str) } int num = 23; int length = str.Length; - for (int i = 0; i < length; i++) + for (int num2 = 0; num2 < length; num2++) { - num = num * 31 + (int)str[i]; + num = num * 31 + str[num2]; } return num; } @@ -214,22 +216,37 @@ public static int StableStringHash(string str) public static string StringFromEnumerable(IEnumerable source) { StringBuilder stringBuilder = new StringBuilder(); - foreach (object current in source) + foreach (object item in source) { - stringBuilder.AppendLine("� " + current.ToString()); + stringBuilder.AppendLine("� " + item.ToString()); } return stringBuilder.ToString(); } - [DebuggerHidden] public static IEnumerable LinesFromString(string text) { - GenText.c__Iterator252 c__Iterator = new GenText.c__Iterator252(); - c__Iterator.text = text; - c__Iterator.<$>text = text; - GenText.c__Iterator252 expr_15 = c__Iterator; - expr_15.$PC = -2; - return expr_15; + string[] lineSeparators = new string[2] + { + "\r\n", + "\n" + }; + string[] array = text.Split(lineSeparators, StringSplitOptions.RemoveEmptyEntries); + for (int i = 0; i < array.Length; i++) + { + string str = array[i]; + string doneStr2 = str.Trim(); + if (!doneStr2.StartsWith("//")) + { + doneStr2 = doneStr2.Split(new string[1] + { + "//" + }, StringSplitOptions.None)[0]; + if (doneStr2.Length != 0) + { + yield return doneStr2; + } + } + } } public static string GetInvalidFilenameCharacters() @@ -249,10 +266,7 @@ public static bool IsValidFilename(string str) public static string SanitizeFilename(string str) { - return string.Join("_", str.Split(GenText.GetInvalidFilenameCharacters().ToArray(), StringSplitOptions.RemoveEmptyEntries)).TrimEnd(new char[] - { - '.' - }); + return string.Join("_", str.Split(GenText.GetInvalidFilenameCharacters().ToArray(), StringSplitOptions.RemoveEmptyEntries)).TrimEnd('.'); } public static bool NullOrEmpty(this string str) @@ -267,10 +281,7 @@ public static string SplitCamelCase(string Str) public static string CapitalizedNoSpaces(string s) { - string[] array = s.Split(new char[] - { - ' ' - }); + string[] array = s.Split(' '); StringBuilder stringBuilder = new StringBuilder(); string[] array2 = array; for (int i = 0; i < array2.Length; i++) @@ -308,34 +319,22 @@ public static bool EqualsIgnoreCase(this string A, string B) public static string WithoutByteOrderMark(this string str) { - return str.Trim().Trim(new char[] - { - '' - }); + return str.Trim().Trim('\ufeff'); } public static bool NamesOverlap(string A, string B) { A = A.ToLower(); B = B.ToLower(); - string[] array = A.Split(new char[] - { - ' ' - }); - string[] source = B.Split(new char[] - { - ' ' - }); + string[] array = A.Split(' '); + string[] source = B.Split(' '); string[] array2 = array; for (int i = 0; i < array2.Length; i++) { string text = array2[i]; - if (TitleCaseHelper.IsUppercaseTitleWord(text)) + if (TitleCaseHelper.IsUppercaseTitleWord(text) && source.Contains(text)) { - if (source.Contains(text)) - { - return true; - } + return true; } } return false; @@ -360,10 +359,7 @@ public static string CapitalizeFirst(this string str) public static string ToNewsCase(string str) { - string[] array = str.Split(new char[] - { - ' ' - }); + string[] array = str.Split(' '); for (int i = 0; i < array.Length; i++) { string text = array[i]; @@ -384,10 +380,7 @@ public static string ToNewsCase(string str) public static string ToTitleCaseSmart(string str) { - string[] array = str.Split(new char[] - { - ' ' - }); + string[] array = str.Split(' '); for (int i = 0; i < array.Length; i++) { string text = array[i]; @@ -414,20 +407,20 @@ public static string CapitalizeSentences(string input) input = Regex.Replace(input, "\\s+", " "); input = input.Trim(); input = char.ToUpper(input[0]) + input.Substring(1); - string[] array = new string[] + string[] array; + string[] array2 = array = new string[3] { ". ", "! ", "? " }; - string[] array2 = array; - for (int i = 0; i < array2.Length; i++) + for (int i = 0; i < array.Length; i++) { - string text = array2[i]; + string text = array[i]; int length = text.Length; - for (int j = input.IndexOf(text, 0); j > -1; j = input.IndexOf(text, j + 1)) + for (int num = input.IndexOf(text, 0); num > -1; num = input.IndexOf(text, num + 1)) { - input = input.Substring(0, j + length) + input[j + length].ToString().ToUpper() + input.Substring(j + length + 1); + input = input.Substring(0, num + length) + input[num + length].ToString().ToUpper() + input.Substring(num + length + 1); } } return input; @@ -446,8 +439,8 @@ public static string ToCommaList(IEnumerable items, bool useAnd = true) public static string ToCommaList(IEnumerable items, bool useAnd = true) { - string text = null; - string text2 = null; + string text = (string)null; + string text2 = (string)null; int num = 0; StringBuilder stringBuilder = new StringBuilder(); IList list = items as IList; @@ -473,49 +466,48 @@ public static string ToCommaList(IEnumerable items, bool useAnd = true) } else { - foreach (string current in items) + foreach (string item in items) { - if (!current.NullOrEmpty()) + if (!item.NullOrEmpty()) { if (text2 == null) { - text2 = current; + text2 = item; } if (text != null) { stringBuilder.Append(text + ", "); } - text = current; + text = item; num++; } } } - if (num == 0) + switch (num) + { + case 0: { return "NoneLower".Translate(); } - if (num == 1) + case 1: { return text; } - if (!useAnd) + default: { + if (useAnd) + { + if (num == 2) + { + return text2 + " " + "AndLower".Translate() + " " + text; + } + stringBuilder.Append("AndLower".Translate() + " " + text); + return stringBuilder.ToString(); + } stringBuilder.Append(text); return stringBuilder.ToString(); } - if (num == 2) - { - return string.Concat(new string[] - { - text2, - " ", - "AndLower".Translate(), - " ", - text - }); - } - stringBuilder.Append("AndLower".Translate() + " " + text); - return stringBuilder.ToString(); + } } public static string ToSpaceList(IEnumerable entries) @@ -527,13 +519,13 @@ public static string ToTextList(IEnumerable entries, string spacer) { StringBuilder stringBuilder = new StringBuilder(); bool flag = true; - foreach (string current in entries) + foreach (string item in entries) { if (!flag) { stringBuilder.Append(spacer); } - stringBuilder.Append(current); + stringBuilder.Append(item); flag = false; } return stringBuilder.ToString(); @@ -542,17 +534,18 @@ public static string ToTextList(IEnumerable entries, string spacer) public static string ToCamelCase(string str) { str = GenText.ToTitleCaseSmart(str); - return str.Replace(" ", null); + return str.Replace(" ", (string)null); } public static string Truncate(this string str, float width, Dictionary cache = null) { - string text; + string text = default(string); if (cache != null && cache.TryGetValue(str, out text)) { return text; } - if (Text.CalcSize(str).x <= width) + Vector2 vector = Text.CalcSize(str); + if (vector.x <= width) { if (cache != null) { @@ -561,11 +554,15 @@ public static string Truncate(this string str, float width, Dictionary width)) + break; } - while (text.Length > 0 && Text.CalcSize(text + "...").x > width); text += "..."; if (cache != null) { @@ -576,7 +573,23 @@ public static string Truncate(this string str, float width, Dictionary= 0f) + if (f >= 0.0) { text = "+" + text; } + break; } - else if (numberSense == ToStringNumberSense.Factor) + case ToStringNumberSense.Factor: { text = "x" + text; + break; + } } return text; } public static string ToStringDecimalIfSmall(this float f) { - if (Mathf.Abs(f) < 1f) + if (Mathf.Abs(f) < 1.0) { return Math.Round((double)f, 2).ToString("0.##"); } - if (Mathf.Abs(f) < 10f) + if (Mathf.Abs(f) < 10.0) { return Math.Round((double)f, 1).ToString("0.#"); } @@ -649,12 +687,12 @@ public static string ToStringDecimalIfSmall(this float f) public static string ToStringPercent(this float f) { - return (f * 100f).ToStringDecimalIfSmall() + "%"; + return ((float)(f * 100.0)).ToStringDecimalIfSmall() + "%"; } public static string ToStringPercent(this float f, string format) { - return ((f + 1E-05f) * 100f).ToString(format) + "%"; + return ((float)((f + 9.9999997473787516E-06) * 100.0)).ToString(format) + "%"; } public static string ToStringMoney(this float f) @@ -669,54 +707,54 @@ public static string ToStringWithSign(this int i) public static string ToStringKilobytes(this int bytes, string format = "F2") { - return ((float)bytes / 1024f).ToString(format) + "Kb"; + return ((float)((float)bytes / 1024.0)).ToString(format) + "Kb"; } public static string ToStringLongitude(this float longitude) { - bool flag = longitude < 0f; + bool flag = longitude < 0.0; if (flag) { - longitude = -longitude; + longitude = (float)(0.0 - longitude); } return longitude.ToString("F2") + '°' + ((!flag) ? "E" : "W"); } public static string ToStringLatitude(this float latitude) { - bool flag = latitude < 0f; + bool flag = latitude < 0.0; if (flag) { - latitude = -latitude; + latitude = (float)(0.0 - latitude); } return latitude.ToString("F2") + '°' + ((!flag) ? "N" : "S"); } public static string ToStringMass(this float mass) { - if (mass == 0f) + if (mass == 0.0) { return "0 g"; } float num = Mathf.Abs(mass); - if (num >= 100f) + if (num >= 100.0) { return mass.ToString("F0") + " kg"; } - if (num >= 10f) + if (num >= 10.0) { return mass.ToString("0.#") + " kg"; } - if (num >= 0.1f) + if (num >= 0.10000000149011612) { return mass.ToString("0.##") + " kg"; } - float num2 = mass * 1000f; - if (num >= 0.01f) + float num2 = (float)(mass * 1000.0); + if (num >= 0.0099999997764825821) { return num2.ToString("F0") + " g"; } - if (num >= 0.001f) + if (num >= 0.0010000000474974513) { return num2.ToString("0.#") + " g"; } @@ -726,7 +764,7 @@ public static string ToStringMass(this float mass) public static string ToStringMassOffset(this float mass) { string text = mass.ToStringMass(); - if (mass > 0f) + if (mass > 0.0) { return "+" + text; } @@ -750,290 +788,397 @@ public static string ToStringTemperatureRaw(this float temp, string format = "F1 switch (Prefs.TemperatureMode) { case TemperatureDisplayMode.Celsius: + { return temp.ToString(format) + "C"; + } case TemperatureDisplayMode.Fahrenheit: + { return temp.ToString(format) + "F"; + } case TemperatureDisplayMode.Kelvin: + { return temp.ToString(format) + "K"; + } default: + { throw new InvalidOperationException(); } + } } public static string ToStringTwoDigits(this Vector2 v) { - return string.Concat(new string[] - { - "(", - v.x.ToString("F2"), - ", ", - v.y.ToString("F2"), - ")" - }); + return "(" + v.x.ToString("F2") + ", " + v.y.ToString("F2") + ")"; } public static string ToStringWorkAmount(this float workAmount) { - return Mathf.CeilToInt(workAmount / 60f).ToString(); + return Mathf.CeilToInt((float)(workAmount / 60.0)).ToString(); } public static string ToStringBytes(this int b, string format = "F2") { - return ((float)b / 8f / 1024f).ToString(format) + "kb"; + return ((float)((float)b / 8.0 / 1024.0)).ToString(format) + "kb"; } public static string ToStringBytes(this uint b, string format = "F2") { - return (b / 8f / 1024f).ToString(format) + "kb"; + return ((float)((float)(double)b / 8.0 / 1024.0)).ToString(format) + "kb"; } public static string ToStringReadable(this KeyCode k) { switch (k) { + case KeyCode.Keypad0: + { + return "Kp0"; + } + case KeyCode.Keypad1: + { + return "Kp1"; + } + case KeyCode.Keypad2: + { + return "Kp2"; + } + case KeyCode.Keypad3: + { + return "Kp3"; + } + case KeyCode.Keypad4: + { + return "Kp4"; + } + case KeyCode.Keypad5: + { + return "Kp5"; + } + case KeyCode.Keypad6: + { + return "Kp6"; + } + case KeyCode.Keypad7: + { + return "Kp7"; + } + case KeyCode.Keypad8: + { + return "Kp8"; + } + case KeyCode.Keypad9: + { + return "Kp9"; + } + case KeyCode.KeypadDivide: + { + return "Kp/"; + } + case KeyCode.KeypadEnter: + { + return "KpEnt"; + } + case KeyCode.KeypadEquals: + { + return "Kp="; + } + case KeyCode.KeypadMinus: + { + return "Kp-"; + } + case KeyCode.KeypadMultiply: + { + return "Kp*"; + } + case KeyCode.KeypadPeriod: + { + return "Kp."; + } + case KeyCode.KeypadPlus: + { + return "Kp+"; + } + case KeyCode.Alpha0: + { + return "0"; + } + case KeyCode.Alpha1: + { + return "1"; + } + case KeyCode.Alpha2: + { + return "2"; + } + case KeyCode.Alpha3: + { + return "3"; + } + case KeyCode.Alpha4: + { + return "4"; + } + case KeyCode.Alpha5: + { + return "5"; + } + case KeyCode.Alpha6: + { + return "6"; + } + case KeyCode.Alpha7: + { + return "7"; + } + case KeyCode.Alpha8: + { + return "8"; + } + case KeyCode.Alpha9: + { + return "9"; + } + case KeyCode.Clear: + { + return "Clr"; + } + case KeyCode.Backspace: + { + return "Bksp"; + } + case KeyCode.Return: + { + return "Ent"; + } case KeyCode.Escape: + { return "Esc"; - case (KeyCode)28: - case (KeyCode)29: - case (KeyCode)30: - case (KeyCode)31: - case KeyCode.Space: - case (KeyCode)37: - case KeyCode.Equals: - case (KeyCode)65: - case (KeyCode)66: - case (KeyCode)67: - case (KeyCode)68: - case (KeyCode)69: - case (KeyCode)70: - case (KeyCode)71: - case (KeyCode)72: - case (KeyCode)73: - case (KeyCode)74: - case (KeyCode)75: - case (KeyCode)76: - case (KeyCode)77: - case (KeyCode)78: - case (KeyCode)79: - case (KeyCode)80: - case (KeyCode)81: - case (KeyCode)82: - case (KeyCode)83: - case (KeyCode)84: - case (KeyCode)85: - case (KeyCode)86: - case (KeyCode)87: - case (KeyCode)88: - case (KeyCode)89: - case (KeyCode)90: - IL_123: - switch (k) - { - case KeyCode.Keypad0: - return "Kp0"; - case KeyCode.Keypad1: - return "Kp1"; - case KeyCode.Keypad2: - return "Kp2"; - case KeyCode.Keypad3: - return "Kp3"; - case KeyCode.Keypad4: - return "Kp4"; - case KeyCode.Keypad5: - return "Kp5"; - case KeyCode.Keypad6: - return "Kp6"; - case KeyCode.Keypad7: - return "Kp7"; - case KeyCode.Keypad8: - return "Kp8"; - case KeyCode.Keypad9: - return "Kp9"; - case KeyCode.KeypadPeriod: - return "Kp."; - case KeyCode.KeypadDivide: - return "Kp/"; - case KeyCode.KeypadMultiply: - return "Kp*"; - case KeyCode.KeypadMinus: - return "Kp-"; - case KeyCode.KeypadPlus: - return "Kp+"; - case KeyCode.KeypadEnter: - return "KpEnt"; - case KeyCode.KeypadEquals: - return "Kp="; - case KeyCode.UpArrow: - return "Up"; - case KeyCode.DownArrow: - return "Down"; - case KeyCode.RightArrow: - return "Right"; - case KeyCode.LeftArrow: - return "Left"; - case KeyCode.Insert: - return "Ins"; - case KeyCode.Home: - return "Home"; - case KeyCode.End: - return "End"; - case KeyCode.PageUp: - return "PgUp"; - case KeyCode.PageDown: - return "PgDn"; - case KeyCode.F1: - case KeyCode.F2: - case KeyCode.F3: - case KeyCode.F4: - case KeyCode.F5: - case KeyCode.F6: - case KeyCode.F7: - case KeyCode.F8: - case KeyCode.F9: - case KeyCode.F10: - case KeyCode.F11: - case KeyCode.F12: - case KeyCode.F13: - case KeyCode.F14: - case KeyCode.F15: - case (KeyCode)297: - case (KeyCode)298: - case (KeyCode)299: - case (KeyCode)314: - IL_22F: - switch (k) - { - case KeyCode.Backspace: - return "Bksp"; - case KeyCode.Tab: - case (KeyCode)10: - case (KeyCode)11: - IL_24F: - if (k != KeyCode.Delete) - { - return k.ToString(); - } - return "Del"; - case KeyCode.Clear: - return "Clr"; - case KeyCode.Return: - return "Ent"; - } - goto IL_24F; - case KeyCode.Numlock: - return "NumL"; - case KeyCode.CapsLock: - return "CapL"; - case KeyCode.ScrollLock: - return "ScrL"; - case KeyCode.RightShift: - return "RShf"; - case KeyCode.LeftShift: - return "LShf"; - case KeyCode.RightControl: - return "RCtrl"; - case KeyCode.LeftControl: - return "LCtrl"; - case KeyCode.RightAlt: - return "RAlt"; - case KeyCode.LeftAlt: - return "LAlt"; - case KeyCode.RightCommand: - return "Appl"; - case KeyCode.LeftCommand: - return "Cmd"; - case KeyCode.LeftWindows: - return "Win"; - case KeyCode.RightWindows: - return "Win"; - case KeyCode.AltGr: - return "AltGr"; - case KeyCode.Help: - return "Help"; - case KeyCode.Print: - return "Prnt"; - case KeyCode.SysReq: - return "SysReq"; - case KeyCode.Break: - return "Brk"; - case KeyCode.Menu: - return "Menu"; - } - goto IL_22F; - case KeyCode.Exclaim: - return "!"; + } case KeyCode.DoubleQuote: + { return "\""; + } + case KeyCode.Exclaim: + { + return "!"; + } case KeyCode.Hash: + { return "#"; + } case KeyCode.Dollar: + { return "$"; + } case KeyCode.Ampersand: + { return "&"; + } case KeyCode.Quote: + { return "'"; + } case KeyCode.LeftParen: + { return "("; + } case KeyCode.RightParen: + { return ")"; + } case KeyCode.Asterisk: + { return "*"; + } case KeyCode.Plus: + { return "+"; - case KeyCode.Comma: - return ","; + } case KeyCode.Minus: + { return "-"; + } + case KeyCode.Comma: + { + return ","; + } case KeyCode.Period: + { return "."; + } case KeyCode.Slash: + { return "/"; - case KeyCode.Alpha0: - return "0"; - case KeyCode.Alpha1: - return "1"; - case KeyCode.Alpha2: - return "2"; - case KeyCode.Alpha3: - return "3"; - case KeyCode.Alpha4: - return "4"; - case KeyCode.Alpha5: - return "5"; - case KeyCode.Alpha6: - return "6"; - case KeyCode.Alpha7: - return "7"; - case KeyCode.Alpha8: - return "8"; - case KeyCode.Alpha9: - return "9"; + } case KeyCode.Colon: + { return ":"; + } case KeyCode.Semicolon: + { return ";"; + } case KeyCode.Less: + { return "<"; + } case KeyCode.Greater: + { return ">"; + } case KeyCode.Question: + { return "?"; + } case KeyCode.At: + { return "@"; + } case KeyCode.LeftBracket: + { return "["; - case KeyCode.Backslash: - return "\\"; + } case KeyCode.RightBracket: + { return "]"; + } + case KeyCode.Backslash: + { + return "\\"; + } case KeyCode.Caret: + { return "^"; + } case KeyCode.Underscore: + { return "_"; + } case KeyCode.BackQuote: + { return "`"; } - goto IL_123; + case KeyCode.Delete: + { + return "Del"; + } + case KeyCode.UpArrow: + { + return "Up"; + } + case KeyCode.DownArrow: + { + return "Down"; + } + case KeyCode.LeftArrow: + { + return "Left"; + } + case KeyCode.RightArrow: + { + return "Right"; + } + case KeyCode.Insert: + { + return "Ins"; + } + case KeyCode.Home: + { + return "Home"; + } + case KeyCode.End: + { + return "End"; + } + case KeyCode.PageDown: + { + return "PgDn"; + } + case KeyCode.PageUp: + { + return "PgUp"; + } + case KeyCode.Numlock: + { + return "NumL"; + } + case KeyCode.CapsLock: + { + return "CapL"; + } + case KeyCode.ScrollLock: + { + return "ScrL"; + } + case KeyCode.RightShift: + { + return "RShf"; + } + case KeyCode.LeftShift: + { + return "LShf"; + } + case KeyCode.RightControl: + { + return "RCtrl"; + } + case KeyCode.LeftControl: + { + return "LCtrl"; + } + case KeyCode.RightAlt: + { + return "RAlt"; + } + case KeyCode.LeftAlt: + { + return "LAlt"; + } + case KeyCode.RightCommand: + { + return "Appl"; + } + case KeyCode.LeftCommand: + { + return "Cmd"; + } + case KeyCode.LeftWindows: + { + return "Win"; + } + case KeyCode.RightWindows: + { + return "Win"; + } + case KeyCode.AltGr: + { + return "AltGr"; + } + case KeyCode.Help: + { + return "Help"; + } + case KeyCode.Print: + { + return "Prnt"; + } + case KeyCode.SysReq: + { + return "SysReq"; + } + case KeyCode.Break: + { + return "Brk"; + } + case KeyCode.Menu: + { + return "Menu"; + } + default: + { + return ((Enum)(object)k).ToString(); + } + } } } } diff --git a/Assembly-CSharp/Verse/GenTicks.cs b/Assembly-CSharp/Verse/GenTicks.cs index 20b816509..4d60c02b6 100644 --- a/Assembly-CSharp/Verse/GenTicks.cs +++ b/Assembly-CSharp/Verse/GenTicks.cs @@ -1,5 +1,4 @@ using RimWorld; -using System; using UnityEngine; namespace Verse @@ -33,28 +32,8 @@ public static int ConfiguredTicksAbsAtGameStart get { GameInitData gameInitData = Find.GameInitData; - Vector2 vector; - if (gameInitData.startingTile >= 0) - { - vector = Find.WorldGrid.LongLatOf(gameInitData.startingTile); - } - else - { - vector = Vector2.zero; - } - Twelfth twelfth; - if (gameInitData.startingSeason != Season.Undefined) - { - twelfth = gameInitData.startingSeason.GetFirstTwelfth(vector.y); - } - else if (gameInitData.startingTile >= 0) - { - twelfth = TwelfthUtility.FindStartingWarmTwelfth(gameInitData.startingTile); - } - else - { - twelfth = Season.Summer.GetFirstTwelfth(0f); - } + Vector2 vector = (gameInitData.startingTile < 0) ? Vector2.zero : Find.WorldGrid.LongLatOf(gameInitData.startingTile); + Twelfth twelfth = (gameInitData.startingSeason == Season.Undefined) ? ((gameInitData.startingTile < 0) ? Season.Summer.GetFirstTwelfth(0f) : TwelfthUtility.FindStartingWarmTwelfth(gameInitData.startingTile)) : gameInitData.startingSeason.GetFirstTwelfth(vector.y); int num = (24 - GenDate.TimeZoneAt(vector.x)) % 24; return 300000 * (int)twelfth + 2500 * (6 + num); } @@ -62,12 +41,12 @@ public static int ConfiguredTicksAbsAtGameStart public static float TicksToSeconds(this int numTicks) { - return (float)numTicks / 60f; + return (float)((float)numTicks / 60.0); } public static int SecondsToTicks(this float numSeconds) { - return Mathf.RoundToInt(60f * numSeconds); + return Mathf.RoundToInt((float)(60.0 * numSeconds)); } public static string TicksToSecondsString(this int numTicks) diff --git a/Assembly-CSharp/Verse/GenTypes.cs b/Assembly-CSharp/Verse/GenTypes.cs index 80fb13042..4c2269f83 100644 --- a/Assembly-CSharp/Verse/GenTypes.cs +++ b/Assembly-CSharp/Verse/GenTypes.cs @@ -1,6 +1,5 @@ using System; using System.Collections.Generic; -using System.Diagnostics; using System.Linq; using System.Reflection; @@ -23,10 +22,14 @@ private static IEnumerable AllActiveAssemblies { get { - GenTypes.<>c__Iterator24F <>c__Iterator24F = new GenTypes.<>c__Iterator24F(); - GenTypes.<>c__Iterator24F expr_07 = <>c__Iterator24F; - expr_07.$PC = -2; - return expr_07; + yield return Assembly.GetExecutingAssembly(); + foreach (ModContentPack runningMod in LoadedModManager.RunningMods) + { + for (int i = 0; i < runningMod.assemblies.loadedAssemblies.Count; i++) + { + yield return runningMod.assemblies.loadedAssemblies[i]; + } + } } } @@ -34,17 +37,34 @@ public static IEnumerable AllTypes { get { - GenTypes.<>c__Iterator250 <>c__Iterator = new GenTypes.<>c__Iterator250(); - GenTypes.<>c__Iterator250 expr_07 = <>c__Iterator; - expr_07.$PC = -2; - return expr_07; + foreach (Assembly allActiveAssembly in GenTypes.AllActiveAssemblies) + { + Type[] assemblyTypes = null; + try + { + assemblyTypes = allActiveAssembly.GetTypes(); + } + catch (ReflectionTypeLoadException) + { + Log.Error("Exception getting types in assembly " + allActiveAssembly.ToString()); + } + if (assemblyTypes != null) + { + Type[] array = assemblyTypes; + for (int i = 0; i < array.Length; i++) + { + Type type = array[i]; + yield return type; + } + } + } } } public static IEnumerable AllTypesWithAttribute() where TAttr : Attribute { return from x in GenTypes.AllTypes - where x.HasAttribute() + where ((MemberInfo)x).HasAttribute() select x; } @@ -65,19 +85,23 @@ where x.IsSubclassOf(baseType) && !x.IsAbstract public static IEnumerable AllLeafSubclasses(this Type baseType) { return from type in baseType.AllSubclasses() - where !type.AllSubclasses().Any() + where !type.AllSubclasses().Any() select type; } - [DebuggerHidden] public static IEnumerable InstantiableDescendantsAndSelf(this Type baseType) { - GenTypes.c__Iterator251 c__Iterator = new GenTypes.c__Iterator251(); - c__Iterator.baseType = baseType; - c__Iterator.<$>baseType = baseType; - GenTypes.c__Iterator251 expr_15 = c__Iterator; - expr_15.$PC = -2; - return expr_15; + if (!baseType.IsAbstract) + { + yield return baseType; + } + foreach (Type item in baseType.AllSubclasses()) + { + if (!item.IsAbstract) + { + yield return item; + } + } } public static Type GetTypeInAnyAssembly(string typeName) @@ -101,9 +125,9 @@ public static Type GetTypeInAnyAssembly(string typeName) private static Type GetTypeInAnyAssemblyRaw(string typeName) { - foreach (Assembly current in GenTypes.AllActiveAssemblies) + foreach (Assembly allActiveAssembly in GenTypes.AllActiveAssemblies) { - Type type = current.GetType(typeName, false, true); + Type type = allActiveAssembly.GetType(typeName, false, true); if (type != null) { return type; diff --git a/Assembly-CSharp/Verse/GenUI.cs b/Assembly-CSharp/Verse/GenUI.cs index ac4285aec..1fe22187a 100644 --- a/Assembly-CSharp/Verse/GenUI.cs +++ b/Assembly-CSharp/Verse/GenUI.cs @@ -1,7 +1,6 @@ using RimWorld; using System; using System.Collections.Generic; -using System.Diagnostics; using UnityEngine; namespace Verse @@ -74,14 +73,14 @@ public static float BackgroundDarkAlphaForText() return 0f; } float num = GenCelestial.CurCelestialSunGlow(Find.VisibleMap); - float num2 = (Find.VisibleMap.Biome != BiomeDefOf.IceSheet) ? Mathf.Clamp01(Find.VisibleMap.snowGrid.TotalDepth / 1000f) : 1f; - return num * num2 * 0.41f; + float num2 = (float)((Find.VisibleMap.Biome != BiomeDefOf.IceSheet) ? Mathf.Clamp01((float)(Find.VisibleMap.snowGrid.TotalDepth / 1000.0)) : 1.0); + return (float)(num * num2 * 0.40999999642372131); } public static void DrawTextWinterShadow(Rect rect) { float num = GenUI.BackgroundDarkAlphaForText(); - if (num > 0.001f) + if (num > 0.0010000000474974513) { GUI.color = new Color(1f, 1f, 1f, num); GUI.DrawTexture(rect, GenUI.UnderShadowTex); @@ -95,13 +94,25 @@ public static float IconDrawScale(ThingDef tDef) { return 1f; } - if (tDef.iconDrawScale > 0f) + if (tDef.iconDrawScale > 0.0) { return tDef.iconDrawScale; } - if (tDef.graphicData.drawSize.x > (float)tDef.Size.x && tDef.graphicData.drawSize.y > (float)tDef.Size.z) + float x = tDef.graphicData.drawSize.x; + IntVec2 size = tDef.Size; + if (x > (float)size.x) { - return Mathf.Min(tDef.graphicData.drawSize.x / (float)tDef.Size.x, tDef.graphicData.drawSize.y / (float)tDef.Size.z); + float y = tDef.graphicData.drawSize.y; + IntVec2 size2 = tDef.Size; + if (y > (float)size2.z) + { + float num = tDef.graphicData.drawSize.x; + IntVec2 size3 = tDef.Size; + float a = num / (float)size3.x; + float num2 = tDef.graphicData.drawSize.y; + IntVec2 size4 = tDef.Size; + return Mathf.Min(a, num2 / (float)size4.z); + } } return 1f; } @@ -110,13 +121,13 @@ public static void ErrorDialog(string message) { if (Find.WindowStack != null) { - Find.WindowStack.Add(new Dialog_MessageBox(message, null, null, null, null, null, false)); + Find.WindowStack.Add(new Dialog_MessageBox(message, (string)null, null, (string)null, null, (string)null, false)); } } public static void DrawFlash(float centerX, float centerY, float size, float alpha, Color color) { - Rect position = new Rect(centerX - size / 2f, centerY - size / 2f, size, size); + Rect position = new Rect((float)(centerX - size / 2.0), (float)(centerY - size / 2.0), size, size); Color color2 = color; color2.a = alpha; GUI.color = color2; @@ -130,30 +141,35 @@ public static float GetWidthCached(this string s) { GenUI.labelWidthCache.Clear(); } - float x; + float x = default(float); if (GenUI.labelWidthCache.TryGetValue(s, out x)) { return x; } - x = Text.CalcSize(s).x; + Vector2 vector = Text.CalcSize(s); + x = vector.x; GenUI.labelWidthCache.Add(s, x); return x; } public static Rect Rounded(this Rect r) { - return new Rect((float)((int)r.x), (float)((int)r.y), (float)((int)r.width), (float)((int)r.height)); + return new Rect((float)(int)r.x, (float)(int)r.y, (float)(int)r.width, (float)(int)r.height); } public static float DistFromRect(Rect r, Vector2 p) { - float num = Mathf.Abs(p.x - r.center.x) - r.width / 2f; - if (num < 0f) + float x = p.x; + Vector2 center = r.center; + float num = (float)(Mathf.Abs(x - center.x) - r.width / 2.0); + if (num < 0.0) { num = 0f; } - float num2 = Mathf.Abs(p.y - r.center.y) - r.height / 2f; - if (num2 < 0f) + float y = p.y; + Vector2 center2 = r.center; + float num2 = (float)(Mathf.Abs(y - center2.y) - r.height / 2.0); + if (num2 < 0.0) { num2 = 0f; } @@ -163,16 +179,16 @@ public static float DistFromRect(Rect r, Vector2 p) public static void DrawMouseAttachment(Texture2D iconTex, string text) { Vector2 mousePosition = Event.current.mousePosition; - float num = mousePosition.y + 12f; - if (iconTex != null) + float num = (float)(mousePosition.y + 12.0); + if ((UnityEngine.Object)iconTex != (UnityEngine.Object)null) { - Rect position = new Rect(mousePosition.x + 12f, num, 32f, 32f); + Rect position = new Rect((float)(mousePosition.x + 12.0), num, 32f, 32f); GUI.DrawTexture(position, iconTex); num += position.height; } if (text != string.Empty) { - Rect rect = new Rect(mousePosition.x + 12f, num, 200f, 9999f); + Rect rect = new Rect((float)(mousePosition.x + 12.0), num, 200f, 9999f); Widgets.Label(rect, text); } } @@ -180,7 +196,7 @@ public static void DrawMouseAttachment(Texture2D iconTex, string text) public static void DrawMouseAttachment(Texture2D icon) { Vector2 mousePosition = Event.current.mousePosition; - GUI.DrawTexture(new Rect(mousePosition.x + 8f, mousePosition.y + 8f, 32f, 32f), icon); + GUI.DrawTexture(new Rect((float)(mousePosition.x + 8.0), (float)(mousePosition.y + 8.0), 32f, 32f), icon); } public static void RenderMouseoverBracket() @@ -194,7 +210,10 @@ public static void DrawStatusLevel(Need status, Rect rect) GUI.BeginGroup(rect); Rect rect2 = new Rect(0f, 2f, rect.width, 25f); Widgets.Label(rect2, status.LabelCap); - Rect rect3 = new Rect(100f, 3f, GenUI.PieceBarSize.x, GenUI.PieceBarSize.y); + Vector2 pieceBarSize = GenUI.PieceBarSize; + float x = pieceBarSize.x; + Vector2 pieceBarSize2 = GenUI.PieceBarSize; + Rect rect3 = new Rect(100f, 3f, x, pieceBarSize2.y); Widgets.FillableBar(rect3, status.CurLevelPercentage); Widgets.FillableBarChangeArrows(rect3, status.GUIChangeArrow); GUI.EndGroup(); @@ -210,19 +229,21 @@ public static IEnumerable TargetsAtMouse(TargetingParameters cl return GenUI.TargetsAt(UI.MouseMapPosition(), clickParams, thingsOnly); } - [DebuggerHidden] public static IEnumerable TargetsAt(Vector3 clickPos, TargetingParameters clickParams, bool thingsOnly = false) { - GenUI.c__Iterator233 c__Iterator = new GenUI.c__Iterator233(); - c__Iterator.clickPos = clickPos; - c__Iterator.clickParams = clickParams; - c__Iterator.thingsOnly = thingsOnly; - c__Iterator.<$>clickPos = clickPos; - c__Iterator.<$>clickParams = clickParams; - c__Iterator.<$>thingsOnly = thingsOnly; - GenUI.c__Iterator233 expr_31 = c__Iterator; - expr_31.$PC = -2; - return expr_31; + List clickableList = GenUI.ThingsUnderMouse(clickPos, 0.8f, clickParams); + for (int i = 0; i < clickableList.Count; i++) + { + yield return clickableList[i]; + } + if (!thingsOnly) + { + IntVec3 cellTarg = UI.MouseCell(); + if (cellTarg.InBounds(Find.VisibleMap) && clickParams.CanTarget(new TargetInfo(cellTarg, Find.VisibleMap, false))) + { + yield return cellTarg; + } + } } public static List ThingsUnderMouse(Vector3 clickPos, float pawnWideClickRadius, TargetingParameters clickParams) @@ -234,7 +255,7 @@ public static List ThingsUnderMouse(Vector3 clickPos, float pawnWideClick for (int i = 0; i < allPawnsSpawned.Count; i++) { Pawn pawn = allPawnsSpawned[i]; - if ((pawn.DrawPos - clickPos).MagnitudeHorizontal() < 0.4f && clickParams.CanTarget(pawn)) + if ((pawn.DrawPos - clickPos).MagnitudeHorizontal() < 0.40000000596046448 && clickParams.CanTarget((Thing)pawn)) { GenUI.clickedPawns.Add(pawn); } @@ -245,11 +266,11 @@ public static List ThingsUnderMouse(Vector3 clickPos, float pawnWideClick list.Add(GenUI.clickedPawns[j]); } List list2 = new List(); - foreach (Thing current in Find.VisibleMap.thingGrid.ThingsAt(c)) + foreach (Thing item in Find.VisibleMap.thingGrid.ThingsAt(c)) { - if (!list.Contains(current) && clickParams.CanTarget(current)) + if (!list.Contains(item) && clickParams.CanTarget(item)) { - list2.Add(current); + list2.Add(item); } } list2.Sort(new Comparison(GenUI.CompareThingsByDrawAltitude)); @@ -259,7 +280,7 @@ public static List ThingsUnderMouse(Vector3 clickPos, float pawnWideClick for (int k = 0; k < allPawnsSpawned2.Count; k++) { Pawn pawn2 = allPawnsSpawned2[k]; - if ((pawn2.DrawPos - clickPos).MagnitudeHorizontal() < pawnWideClickRadius && clickParams.CanTarget(pawn2)) + if ((pawn2.DrawPos - clickPos).MagnitudeHorizontal() < pawnWideClickRadius && clickParams.CanTarget((Thing)pawn2)) { GenUI.clickedPawns.Add(pawn2); } @@ -272,7 +293,7 @@ public static List ThingsUnderMouse(Vector3 clickPos, float pawnWideClick list.Add(GenUI.clickedPawns[l]); } } - list.RemoveAll((Thing t) => !t.Spawned); + list.RemoveAll((Predicate)((Thing t) => !t.Spawned)); GenUI.clickedPawns.Clear(); return list; } @@ -330,13 +351,13 @@ public static Rect GetInnerRect(this Rect rect) public static Rect ContractedBy(this Rect rect, float margin) { - return new Rect(rect.x + margin, rect.y + margin, rect.width - margin * 2f, rect.height - margin * 2f); + return new Rect(rect.x + margin, rect.y + margin, (float)(rect.width - margin * 2.0), (float)(rect.height - margin * 2.0)); } public static Rect ScaledBy(this Rect rect, float scale) { - rect.x -= rect.width * (scale - 1f) / 2f; - rect.y -= rect.height * (scale - 1f) / 2f; + rect.x -= (float)(rect.width * (scale - 1.0) / 2.0); + rect.y -= (float)(rect.height * (scale - 1.0) / 2.0); rect.width *= scale; rect.height *= scale; return rect; @@ -344,12 +365,12 @@ public static Rect ScaledBy(this Rect rect, float scale) public static Rect CenteredOnXIn(this Rect rect, Rect otherRect) { - return new Rect(otherRect.x + (otherRect.width - rect.width) / 2f, rect.y, rect.width, rect.height); + return new Rect((float)(otherRect.x + (otherRect.width - rect.width) / 2.0), rect.y, rect.width, rect.height); } public static Rect CenteredOnYIn(this Rect rect, Rect otherRect) { - return new Rect(rect.x, otherRect.y + (otherRect.height - rect.height) / 2f, rect.width, rect.height); + return new Rect(rect.x, (float)(otherRect.y + (otherRect.height - rect.height) / 2.0), rect.width, rect.height); } public static Rect AtZero(this Rect rect) @@ -367,7 +388,7 @@ public static void AbsorbClicksInRect(Rect r) public static Rect LeftHalf(this Rect rect) { - return new Rect(rect.x, rect.y, rect.width / 2f, rect.height); + return new Rect(rect.x, rect.y, (float)(rect.width / 2.0), rect.height); } public static Rect LeftPart(this Rect rect, float pct) @@ -382,12 +403,12 @@ public static Rect LeftPartPixels(this Rect rect, float width) public static Rect RightHalf(this Rect rect) { - return new Rect(rect.x + rect.width / 2f, rect.y, rect.width / 2f, rect.height); + return new Rect((float)(rect.x + rect.width / 2.0), rect.y, (float)(rect.width / 2.0), rect.height); } public static Rect RightPart(this Rect rect, float pct) { - return new Rect(rect.x + rect.width * (1f - pct), rect.y, rect.width * pct, rect.height); + return new Rect((float)(rect.x + rect.width * (1.0 - pct)), rect.y, rect.width * pct, rect.height); } public static Rect RightPartPixels(this Rect rect, float width) @@ -397,7 +418,7 @@ public static Rect RightPartPixels(this Rect rect, float width) public static Rect TopHalf(this Rect rect) { - return new Rect(rect.x, rect.y, rect.width, rect.height / 2f); + return new Rect(rect.x, rect.y, rect.width, (float)(rect.height / 2.0)); } public static Rect TopPart(this Rect rect, float pct) @@ -412,12 +433,12 @@ public static Rect TopPartPixels(this Rect rect, float height) public static Rect BottomHalf(this Rect rect) { - return new Rect(rect.x, rect.y + rect.height / 2f, rect.width, rect.height / 2f); + return new Rect(rect.x, (float)(rect.y + rect.height / 2.0), rect.width, (float)(rect.height / 2.0)); } public static Rect BottomPart(this Rect rect, float pct) { - return new Rect(rect.x, rect.y + rect.height * (1f - pct), rect.width, rect.height * pct); + return new Rect(rect.x, (float)(rect.y + rect.height * (1.0 - pct)), rect.width, rect.height * pct); } public static Rect BottomPartPixels(this Rect rect, float height) diff --git a/Assembly-CSharp/Verse/GenView.cs b/Assembly-CSharp/Verse/GenView.cs index c1d8a02e6..ebf51d93a 100644 --- a/Assembly-CSharp/Verse/GenView.cs +++ b/Assembly-CSharp/Verse/GenView.cs @@ -1,4 +1,3 @@ -using System; using UnityEngine; namespace Verse diff --git a/Assembly-CSharp/Verse/Gender.cs b/Assembly-CSharp/Verse/Gender.cs index 10b0b5d13..cffdbf395 100644 --- a/Assembly-CSharp/Verse/Gender.cs +++ b/Assembly-CSharp/Verse/Gender.cs @@ -1,11 +1,9 @@ -using System; - namespace Verse { public enum Gender : byte { - None, - Male, - Female + None = 0, + Male = 1, + Female = 2 } } diff --git a/Assembly-CSharp/Verse/GenderUtility.cs b/Assembly-CSharp/Verse/GenderUtility.cs index d553409b4..be1014166 100644 --- a/Assembly-CSharp/Verse/GenderUtility.cs +++ b/Assembly-CSharp/Verse/GenderUtility.cs @@ -17,14 +17,22 @@ public static string GetLabel(this Gender gender) switch (gender) { case Gender.None: + { return "NoneLower".Translate(); + } case Gender.Male: + { return "Male".Translate(); + } case Gender.Female: + { return "Female".Translate(); + } default: + { throw new ArgumentException(); } + } } public static string GetPronoun(this Gender gender) @@ -32,14 +40,22 @@ public static string GetPronoun(this Gender gender) switch (gender) { case Gender.None: + { return "Proit".Translate(); + } case Gender.Male: + { return "Prohe".Translate(); + } case Gender.Female: + { return "Proshe".Translate(); + } default: + { throw new ArgumentException(); } + } } public static string GetPossessive(this Gender gender) @@ -47,14 +63,22 @@ public static string GetPossessive(this Gender gender) switch (gender) { case Gender.None: + { return "Proits".Translate(); + } case Gender.Male: + { return "Prohis".Translate(); + } case Gender.Female: + { return "Proher".Translate(); + } default: + { throw new ArgumentException(); } + } } public static string GetObjective(this Gender gender) @@ -62,14 +86,22 @@ public static string GetObjective(this Gender gender) switch (gender) { case Gender.None: + { return "ProitObj".Translate(); + } case Gender.Male: + { return "ProhimObj".Translate(); + } case Gender.Female: + { return "ProherObj".Translate(); + } default: + { throw new ArgumentException(); } + } } public static Texture2D GetIcon(this Gender gender) @@ -77,14 +109,22 @@ public static Texture2D GetIcon(this Gender gender) switch (gender) { case Gender.None: + { return GenderUtility.GenderlessIcon; + } case Gender.Male: + { return GenderUtility.MaleIcon; + } case Gender.Female: + { return GenderUtility.FemaleIcon; + } default: + { throw new ArgumentException(); } + } } } } diff --git a/Assembly-CSharp/Verse/GetOrGenerateMapUtility.cs b/Assembly-CSharp/Verse/GetOrGenerateMapUtility.cs index 227273de8..a8a552489 100644 --- a/Assembly-CSharp/Verse/GetOrGenerateMapUtility.cs +++ b/Assembly-CSharp/Verse/GetOrGenerateMapUtility.cs @@ -1,6 +1,5 @@ using RimWorld; using RimWorld.Planet; -using System; namespace Verse { diff --git a/Assembly-CSharp/Verse/GhostDrawer.cs b/Assembly-CSharp/Verse/GhostDrawer.cs index b33ffe948..d0961d767 100644 --- a/Assembly-CSharp/Verse/GhostDrawer.cs +++ b/Assembly-CSharp/Verse/GhostDrawer.cs @@ -1,4 +1,3 @@ -using System; using System.Collections.Generic; using UnityEngine; @@ -28,12 +27,12 @@ public static void DrawGhostThing(IntVec3 center, Rot4 rot, ThingDef thingDef, G private static Graphic GhostGraphicFor(Graphic baseGraphic, ThingDef thingDef, Color ghostCol) { - int num = 0; - num = Gen.HashCombine(num, baseGraphic); - num = Gen.HashCombine(num, thingDef); - num = Gen.HashCombineStruct(num, ghostCol); - Graphic graphic; - if (!GhostDrawer.ghostGraphics.TryGetValue(num, out graphic)) + int seed = 0; + seed = Gen.HashCombine(seed, baseGraphic); + seed = Gen.HashCombine(seed, thingDef); + seed = Gen.HashCombineStruct(seed, ghostCol); + Graphic graphic = default(Graphic); + if (!GhostDrawer.ghostGraphics.TryGetValue(seed, out graphic)) { if (thingDef.graphicData.Linked || thingDef.IsDoor) { @@ -54,7 +53,7 @@ private static Graphic GhostGraphicFor(Graphic baseGraphic, ThingDef thingDef, C } graphic = GraphicDatabase.Get(baseGraphic.GetType(), baseGraphic.path, ShaderDatabase.Transparent, baseGraphic.drawSize, ghostCol, Color.white, graphicData); } - GhostDrawer.ghostGraphics.Add(num, graphic); + GhostDrawer.ghostGraphics.Add(seed, graphic); } return graphic; } diff --git a/Assembly-CSharp/Verse/Gizmo.cs b/Assembly-CSharp/Verse/Gizmo.cs index 9c94d4bfc..8f08e2591 100644 --- a/Assembly-CSharp/Verse/Gizmo.cs +++ b/Assembly-CSharp/Verse/Gizmo.cs @@ -1,4 +1,3 @@ -using System; using UnityEngine; namespace Verse diff --git a/Assembly-CSharp/Verse/GizmoGridDrawer.cs b/Assembly-CSharp/Verse/GizmoGridDrawer.cs index a27d9de10..0166c1c1c 100644 --- a/Assembly-CSharp/Verse/GizmoGridDrawer.cs +++ b/Assembly-CSharp/Verse/GizmoGridDrawer.cs @@ -34,52 +34,61 @@ public static float HeightDrawnRecently public static void DrawGizmoGrid(IEnumerable gizmos, float startX, out Gizmo mouseoverGizmo) { GizmoGridDrawer.gizmoGroups.Clear(); - foreach (Gizmo current in gizmos) + foreach (Gizmo item in gizmos) { bool flag = false; - for (int i = 0; i < GizmoGridDrawer.gizmoGroups.Count; i++) + int num = 0; + while (num < GizmoGridDrawer.gizmoGroups.Count) { - if (GizmoGridDrawer.gizmoGroups[i][0].GroupsWith(current)) + if (!GizmoGridDrawer.gizmoGroups[num][0].GroupsWith(item)) { - flag = true; - GizmoGridDrawer.gizmoGroups[i].Add(current); - break; + num++; + continue; } + flag = true; + GizmoGridDrawer.gizmoGroups[num].Add(item); + break; } if (!flag) { List list = new List(); - list.Add(current); + list.Add(item); GizmoGridDrawer.gizmoGroups.Add(list); } } GizmoGridDrawer.firstGizmos.Clear(); - for (int j = 0; j < GizmoGridDrawer.gizmoGroups.Count; j++) + for (int i = 0; i < GizmoGridDrawer.gizmoGroups.Count; i++) { - List source = GizmoGridDrawer.gizmoGroups[j]; - Gizmo gizmo = source.FirstOrDefault((Gizmo opt) => !opt.disabled); + List source = GizmoGridDrawer.gizmoGroups[i]; + Gizmo gizmo = source.FirstOrDefault((Func)((Gizmo opt) => !opt.disabled)); if (gizmo == null) { - gizmo = source.FirstOrDefault(); + gizmo = source.FirstOrDefault(); } GizmoGridDrawer.firstGizmos.Add(gizmo); } GizmoGridDrawer.drawnHotKeys.Clear(); - float num = (float)(UI.screenWidth - 140); + float num2 = (float)(UI.screenWidth - 140); Text.Font = GameFont.Tiny; - Vector2 topLeft = new Vector2(startX, (float)(UI.screenHeight - 35) - GizmoGridDrawer.GizmoSpacing.y - 75f); + float num3 = (float)(UI.screenHeight - 35); + Vector2 gizmoSpacing = GizmoGridDrawer.GizmoSpacing; + Vector2 topLeft = new Vector2(startX, (float)(num3 - gizmoSpacing.y - 75.0)); mouseoverGizmo = null; Gizmo interactedGiz = null; Event ev = null; - for (int k = 0; k < GizmoGridDrawer.firstGizmos.Count; k++) + for (int j = 0; j < GizmoGridDrawer.firstGizmos.Count; j++) { - Gizmo gizmo2 = GizmoGridDrawer.firstGizmos[k]; + Gizmo gizmo2 = GizmoGridDrawer.firstGizmos[j]; if (gizmo2.Visible) { - if (topLeft.x + gizmo2.Width + GizmoGridDrawer.GizmoSpacing.x > num) + float num4 = topLeft.x + gizmo2.Width; + Vector2 gizmoSpacing2 = GizmoGridDrawer.GizmoSpacing; + if (num4 + gizmoSpacing2.x > num2) { topLeft.x = startX; - topLeft.y -= 75f + GizmoGridDrawer.GizmoSpacing.x; + float y = topLeft.y; + Vector2 gizmoSpacing3 = GizmoGridDrawer.GizmoSpacing; + topLeft.y = (float)(y - (75.0 + gizmoSpacing3.x)); } GizmoGridDrawer.heightDrawnFrame = Time.frameCount; GizmoGridDrawer.heightDrawn = (float)UI.screenHeight - topLeft.y; @@ -89,22 +98,29 @@ public static void DrawGizmoGrid(IEnumerable gizmos, float startX, out Gi ev = gizmoResult.InteractEvent; interactedGiz = gizmo2; } - if (gizmoResult.State >= GizmoState.Mouseover) + if ((int)gizmoResult.State >= 1) { mouseoverGizmo = gizmo2; } - Rect rect = new Rect(topLeft.x, topLeft.y, gizmo2.Width, 75f + GizmoGridDrawer.GizmoSpacing.y); + float x = topLeft.x; + float y2 = topLeft.y; + float width = gizmo2.Width; + Vector2 gizmoSpacing4 = GizmoGridDrawer.GizmoSpacing; + Rect rect = new Rect(x, y2, width, (float)(75.0 + gizmoSpacing4.y)); rect = rect.ContractedBy(-12f); GenUI.AbsorbClicksInRect(rect); - topLeft.x += gizmo2.Width + GizmoGridDrawer.GizmoSpacing.x; + float x2 = topLeft.x; + float width2 = gizmo2.Width; + Vector2 gizmoSpacing5 = GizmoGridDrawer.GizmoSpacing; + topLeft.x = x2 + (width2 + gizmoSpacing5.x); } } if (interactedGiz != null) { - List list2 = GizmoGridDrawer.gizmoGroups.First((List group) => group.Contains(interactedGiz)); - for (int l = 0; l < list2.Count; l++) + List list2 = GizmoGridDrawer.gizmoGroups.First((Func, bool>)((List group) => group.Contains(interactedGiz))); + for (int k = 0; k < list2.Count; k++) { - Gizmo gizmo3 = list2[l]; + Gizmo gizmo3 = list2[k]; if (gizmo3 != interactedGiz && !gizmo3.disabled && interactedGiz.InheritInteractionsFrom(gizmo3)) { gizmo3.ProcessInput(ev); diff --git a/Assembly-CSharp/Verse/GizmoResult.cs b/Assembly-CSharp/Verse/GizmoResult.cs index 4057f2466..bde704859 100644 --- a/Assembly-CSharp/Verse/GizmoResult.cs +++ b/Assembly-CSharp/Verse/GizmoResult.cs @@ -1,4 +1,3 @@ -using System; using UnityEngine; namespace Verse diff --git a/Assembly-CSharp/Verse/GizmoState.cs b/Assembly-CSharp/Verse/GizmoState.cs index 60f039d65..0a2bdd476 100644 --- a/Assembly-CSharp/Verse/GizmoState.cs +++ b/Assembly-CSharp/Verse/GizmoState.cs @@ -1,11 +1,9 @@ -using System; - namespace Verse { public enum GizmoState : byte { - Clear, - Mouseover, - Interacted + Clear = 0, + Mouseover = 1, + Interacted = 2 } } diff --git a/Assembly-CSharp/Verse/GlobalRenderTexture.cs b/Assembly-CSharp/Verse/GlobalRenderTexture.cs index be1c53207..29321b45c 100644 --- a/Assembly-CSharp/Verse/GlobalRenderTexture.cs +++ b/Assembly-CSharp/Verse/GlobalRenderTexture.cs @@ -1,4 +1,3 @@ -using System; using UnityEngine; namespace Verse @@ -12,12 +11,12 @@ public static RenderTexture WaterLight { get { - if (GlobalRenderTexture.waterLight != null && (GlobalRenderTexture.waterLight.width != Screen.width || GlobalRenderTexture.waterLight.height != Screen.height)) + if ((Object)GlobalRenderTexture.waterLight != (Object)null && (GlobalRenderTexture.waterLight.width != Screen.width || GlobalRenderTexture.waterLight.height != Screen.height)) { - UnityEngine.Object.Destroy(GlobalRenderTexture.waterLight); + Object.Destroy(GlobalRenderTexture.waterLight); GlobalRenderTexture.waterLight = null; } - if (GlobalRenderTexture.waterLight == null) + if ((Object)GlobalRenderTexture.waterLight == (Object)null) { GlobalRenderTexture.waterLight = new RenderTexture(Screen.width, Screen.height, 0, RenderTextureFormat.RFloat); } diff --git a/Assembly-CSharp/Verse/GlowFlooder.cs b/Assembly-CSharp/Verse/GlowFlooder.cs index afc4db07b..8eaa6b142 100644 --- a/Assembly-CSharp/Verse/GlowFlooder.cs +++ b/Assembly-CSharp/Verse/GlowFlooder.cs @@ -15,9 +15,9 @@ private struct GlowFloodCell private class CompareGlowFlooderLightSquares : IComparer { - private GlowFlooder.GlowFloodCell[] grid; + private GlowFloodCell[] grid; - public CompareGlowFlooderLightSquares(GlowFlooder.GlowFloodCell[] grid) + public CompareGlowFlooderLightSquares(GlowFloodCell[] grid) { this.grid = grid; } @@ -38,7 +38,7 @@ public int Compare(int a, int b) private Map map; - private GlowFlooder.GlowFloodCell[] calcGrid; + private GlowFloodCell[] calcGrid; private FastPriorityQueue openSet; @@ -68,39 +68,39 @@ public int Compare(int a, int b) private Color32[] glowGrid; - private static readonly sbyte[,] Directions = new sbyte[,] + private static readonly sbyte[,] Directions = new sbyte[8, 2] { { - 0, - -1 + (sbyte)0, + (sbyte)(-1) }, { - 1, - 0 + (sbyte)1, + (sbyte)0 }, { - 0, - 1 + (sbyte)0, + (sbyte)1 }, { - -1, - 0 + (sbyte)(-1), + (sbyte)0 }, { - 1, - -1 + (sbyte)1, + (sbyte)(-1) }, { - 1, - 1 + (sbyte)1, + (sbyte)1 }, { - -1, - 1 + (sbyte)(-1), + (sbyte)1 }, { - -1, - -1 + (sbyte)(-1), + (sbyte)(-1) } }; @@ -114,13 +114,13 @@ private void InitializeWorkingData() this.mapSizePowTwo = this.map.info.PowerOfTwoOverMapSize; this.gridSizeX = (ushort)this.mapSizePowTwo; this.gridSizeY = (ushort)this.mapSizePowTwo; - this.gridSizeXMinus1 = this.gridSizeX - 1; - this.gridSizeZLog2 = (ushort)Math.Log((double)this.gridSizeY, 2.0); - if (this.calcGrid == null || this.calcGrid.Length != (int)(this.gridSizeX * this.gridSizeY)) + this.gridSizeXMinus1 = (ushort)(this.gridSizeX - 1); + this.gridSizeZLog2 = (ushort)Math.Log((double)(int)this.gridSizeY, 2.0); + if (this.calcGrid == null || this.calcGrid.Length != this.gridSizeX * this.gridSizeY) { - this.calcGrid = new GlowFlooder.GlowFloodCell[(int)(this.gridSizeX * this.gridSizeY)]; + this.calcGrid = new GlowFloodCell[this.gridSizeX * this.gridSizeY]; } - this.openSet = new FastPriorityQueue(new GlowFlooder.CompareGlowFlooderLightSquares(this.calcGrid)); + this.openSet = new FastPriorityQueue(new CompareGlowFlooderLightSquares(this.calcGrid)); } public void AddFloodGlowFor(CompGlower theGlower) @@ -136,8 +136,8 @@ public void AddFloodGlowFor(CompGlower theGlower) this.openVal += 3u; this.finalizedVal += 3u; IntVec3 position = this.glower.parent.Position; - this.attenLinearSlope = -1f / this.glower.Props.glowRadius; - int num = Mathf.RoundToInt(this.glower.Props.glowRadius * 100f); + this.attenLinearSlope = (float)(-1.0 / this.glower.Props.glowRadius); + int num = Mathf.RoundToInt((float)(this.glower.Props.glowRadius * 100.0)); IntVec3 intVec = default(IntVec3); IntVec3 c = default(IntVec3); int num2 = 0; @@ -149,98 +149,93 @@ public void AddFloodGlowFor(CompGlower theGlower) while (this.openSet.Count != 0) { int num4 = this.openSet.Pop(); - intVec.x = (int)((ushort)(num4 & (int)this.gridSizeXMinus1)); - intVec.z = (int)((ushort)(num4 >> (int)this.gridSizeZLog2)); + intVec.x = (ushort)(num4 & this.gridSizeXMinus1); + intVec.z = (ushort)(num4 >> (int)this.gridSizeZLog2); this.calcGrid[num4].status = this.finalizedVal; this.SetGlowGridFromDist(intVec); if (UnityData.isDebugBuild && DebugViewSettings.drawGlow) { - this.map.debugDrawer.FlashCell(intVec, (float)this.calcGrid[num4].intDist / 10f, this.calcGrid[num4].intDist.ToString("F2")); + this.map.debugDrawer.FlashCell(intVec, (float)((float)this.calcGrid[num4].intDist / 10.0), this.calcGrid[num4].intDist.ToString("F2")); num2++; } for (int i = 0; i < 8; i++) { - c.x = (int)((ushort)(intVec.x + (int)GlowFlooder.Directions[i, 0])); - c.z = (int)((ushort)(intVec.z + (int)GlowFlooder.Directions[i, 1])); + c.x = (ushort)(intVec.x + GlowFlooder.Directions[i, 0]); + c.z = (ushort)(intVec.z + GlowFlooder.Directions[i, 1]); int num5 = (c.z << (int)this.gridSizeZLog2) + c.x; - if (c.InBounds(this.map)) + int num7; + if (c.InBounds(this.map) && this.calcGrid[num5].status != this.finalizedVal) { - if (this.calcGrid[num5].status != this.finalizedVal) + this.blockers[i] = innerArray[cellIndices.CellToIndex(c)]; + if (this.blockers[i] != null) { - this.blockers[i] = innerArray[cellIndices.CellToIndex(c)]; - if (this.blockers[i] != null) + if (this.blockers[i].def.blockLight) { - if (this.blockers[i].def.blockLight) + continue; + } + this.blockers[i] = null; + } + int num6 = (i >= 4) ? 141 : 100; + num7 = this.calcGrid[num4].intDist + num6; + if (num7 <= num && this.calcGrid[num5].status != this.finalizedVal) + { + if (i < 4) + { + goto IL_03de; + } + bool flag = false; + switch (i) + { + case 4: + { + if (this.blockers[0] != null && this.blockers[1] != null) { - goto IL_47C; + flag = true; } - this.blockers[i] = null; + break; } - int num6; - if (i < 4) + case 5: { - num6 = 100; + if (this.blockers[1] != null && this.blockers[2] != null) + { + flag = true; + } + break; } - else + case 6: { - num6 = 141; + if (this.blockers[2] != null && this.blockers[3] != null) + { + flag = true; + } + break; } - int num7 = this.calcGrid[num4].intDist + num6; - if (num7 <= num) + case 7: { - if (this.calcGrid[num5].status != this.finalizedVal) + if (this.blockers[0] != null && this.blockers[3] != null) { - if (i >= 4) - { - bool flag = false; - switch (i) - { - case 4: - if (this.blockers[0] != null && this.blockers[1] != null) - { - flag = true; - } - break; - case 5: - if (this.blockers[1] != null && this.blockers[2] != null) - { - flag = true; - } - break; - case 6: - if (this.blockers[2] != null && this.blockers[3] != null) - { - flag = true; - } - break; - case 7: - if (this.blockers[0] != null && this.blockers[3] != null) - { - flag = true; - } - break; - } - if (flag) - { - goto IL_47C; - } - } - if (this.calcGrid[num5].status <= this.unseenVal) - { - this.calcGrid[num5].intDist = 999999; - this.calcGrid[num5].status = this.openVal; - } - if (num7 < this.calcGrid[num5].intDist) - { - this.calcGrid[num5].intDist = num7; - this.calcGrid[num5].status = this.openVal; - this.openSet.Push(num5); - } + flag = true; } + break; } + } + if (!flag) + goto IL_03de; } } - IL_47C:; + continue; + IL_03de: + if (this.calcGrid[num5].status <= this.unseenVal) + { + this.calcGrid[num5].intDist = 999999; + this.calcGrid[num5].status = this.openVal; + } + if (num7 < this.calcGrid[num5].intDist) + { + this.calcGrid[num5].intDist = num7; + this.calcGrid[num5].status = this.openVal; + this.openSet.Push(num5); + } } } } @@ -248,28 +243,26 @@ public void AddFloodGlowFor(CompGlower theGlower) private void SetGlowGridFromDist(IntVec3 c) { this.finalIdx = (c.z << (int)this.gridSizeZLog2) + c.x; - float num = (float)this.calcGrid[this.finalIdx].intDist / 100f; + float num = (float)((float)this.calcGrid[this.finalIdx].intDist / 100.0); ColorInt colB = default(ColorInt); if (num <= this.glower.Props.glowRadius) { - float b = 1f / (num * num); - float a = 1f + this.attenLinearSlope * num; + float b = (float)(1.0 / (num * num)); + float a = (float)(1.0 + this.attenLinearSlope * num); float b2 = Mathf.Lerp(a, b, 0.4f); colB = this.glower.Props.glowColor * b2; } - if (colB.r > 0 || colB.g > 0 || colB.b > 0) + if (colB.r <= 0 && colB.g <= 0 && colB.b <= 0) + return; + colB.ClampToNonNegative(); + int num2 = this.map.cellIndices.CellToIndex(c); + ColorInt colA = this.glowGrid[num2].AsColorInt(); + colA += colB; + if (num < this.glower.Props.overlightRadius) { - colB.ClampToNonNegative(); - int num2 = this.map.cellIndices.CellToIndex(c); - ColorInt colA = this.glowGrid[num2].AsColorInt(); - colA += colB; - if (num < this.glower.Props.overlightRadius) - { - colA.a = 1; - } - Color32 toColor = colA.ToColor32; - this.glowGrid[num2] = toColor; + colA.a = 1; } + Color32 color = this.glowGrid[num2] = colA.ToColor32; } } } diff --git a/Assembly-CSharp/Verse/GlowGrid.cs b/Assembly-CSharp/Verse/GlowGrid.cs index 5b2fb107c..dbba0ec91 100644 --- a/Assembly-CSharp/Verse/GlowGrid.cs +++ b/Assembly-CSharp/Verse/GlowGrid.cs @@ -45,7 +45,7 @@ public float GameGlowAt(IntVec3 c) if (!this.map.roofGrid.Roofed(c)) { num = this.map.skyManager.CurSkyGlow; - if (num == 1f) + if (num == 1.0) { return num; } @@ -55,7 +55,7 @@ public float GameGlowAt(IntVec3 c) { return 1f; } - float b = (float)(color.r + color.g + color.b) / 3f / 255f * 3.6f; + float b = (float)((float)(color.r + color.g + color.b) / 3.0 / 255.0 * 3.5999999046325684); b = Mathf.Min(0.5f, b); return Mathf.Max(num, b); } @@ -68,11 +68,11 @@ public PsychGlow PsychGlowAt(IntVec3 c) public static PsychGlow PsychGlowAtGlow(float glow) { - if (glow > 0.9f) + if (glow > 0.89999997615814209) { return PsychGlow.Overlit; } - if (glow > 0.3f) + if (glow > 0.30000001192092896) { return PsychGlow.Lit; } @@ -112,26 +112,43 @@ public void GlowGridUpdate_First() private void RecalculateAllGlow() { - if (Current.ProgramState != ProgramState.Playing) - { - return; - } - if (this.initialGlowerLocs != null) + if (Current.ProgramState == ProgramState.Playing) { - foreach (IntVec3 current in this.initialGlowerLocs) + if (this.initialGlowerLocs != null) { - this.MarkGlowGridDirty(current); + List.Enumerator enumerator = this.initialGlowerLocs.GetEnumerator(); + try + { + while (enumerator.MoveNext()) + { + IntVec3 current = enumerator.Current; + this.MarkGlowGridDirty(current); + } + } + finally + { + ((IDisposable)(object)enumerator).Dispose(); + } + this.initialGlowerLocs = null; + } + int numGridCells = this.map.cellIndices.NumGridCells; + for (int num = 0; num < numGridCells; num++) + { + this.glowGrid[num] = new Color32((byte)0, (byte)0, (byte)0, (byte)0); + } + HashSet.Enumerator enumerator2 = this.litGlowers.GetEnumerator(); + try + { + while (enumerator2.MoveNext()) + { + CompGlower current2 = enumerator2.Current; + this.map.glowFlooder.AddFloodGlowFor(current2); + } + } + finally + { + ((IDisposable)(object)enumerator2).Dispose(); } - this.initialGlowerLocs = null; - } - int numGridCells = this.map.cellIndices.NumGridCells; - for (int i = 0; i < numGridCells; i++) - { - this.glowGrid[i] = new Color32(0, 0, 0, 0); - } - foreach (CompGlower current2 in this.litGlowers) - { - this.map.glowFlooder.AddFloodGlowFor(current2); } } } diff --git a/Assembly-CSharp/Verse/Graphic.cs b/Assembly-CSharp/Verse/Graphic.cs index f7b85cb10..f4bd8e8c1 100644 --- a/Assembly-CSharp/Verse/Graphic.cs +++ b/Assembly-CSharp/Verse/Graphic.cs @@ -1,4 +1,3 @@ -using System; using UnityEngine; namespace Verse @@ -22,7 +21,7 @@ public Shader Shader get { Material matSingle = this.MatSingle; - if (matSingle != null) + if ((Object)matSingle != (Object)null) { return matSingle.shader; } @@ -108,16 +107,26 @@ public virtual Material MatAt(Rot4 rot, Thing thing = null) switch (rot.AsInt) { case 0: + { return this.MatBack; + } case 1: + { return this.MatSide; + } case 2: + { return this.MatFront; + } case 3: + { return this.MatSide; + } default: + { return BaseContent.BadMat; } + } } public virtual Mesh MeshAt(Rot4 rot) @@ -176,14 +185,7 @@ public virtual void Print(SectionLayer layer, Thing thing) } else { - if (!thing.Rotation.IsHorizontal) - { - size = this.drawSize; - } - else - { - size = this.drawSize.Rotated(); - } + size = (thing.Rotation.IsHorizontal ? this.drawSize.Rotated() : this.drawSize); flag = (thing.Rotation == Rot4.West); if (this.data != null && !this.data.allowFlip) { diff --git a/Assembly-CSharp/Verse/GraphicData.cs b/Assembly-CSharp/Verse/GraphicData.cs index bf0fb41e1..befb01876 100644 --- a/Assembly-CSharp/Verse/GraphicData.cs +++ b/Assembly-CSharp/Verse/GraphicData.cs @@ -1,6 +1,5 @@ using System; using System.Collections.Generic; -using System.Diagnostics; using UnityEngine; namespace Verse @@ -80,22 +79,24 @@ private void Init() if (this.graphicClass == null) { this.cachedGraphic = null; - return; } - ShaderType sType = this.shaderType; - if (this.shaderType == ShaderType.None) + else { - sType = ShaderType.Cutout; - } - Shader shader = ShaderDatabase.ShaderFromType(sType); - this.cachedGraphic = GraphicDatabase.Get(this.graphicClass, this.texPath, shader, this.drawSize, this.color, this.colorTwo, this); - if (this.onGroundRandomRotateAngle > 0.01f) - { - this.cachedGraphic = new Graphic_RandomRotated(this.cachedGraphic, this.onGroundRandomRotateAngle); - } - if (this.Linked) - { - this.cachedGraphic = GraphicUtility.WrapLinked(this.cachedGraphic, this.linkType); + ShaderType sType = this.shaderType; + if (this.shaderType == ShaderType.None) + { + sType = ShaderType.Cutout; + } + Shader shader = ShaderDatabase.ShaderFromType(sType); + this.cachedGraphic = GraphicDatabase.Get(this.graphicClass, this.texPath, shader, this.drawSize, this.color, this.colorTwo, this); + if (this.onGroundRandomRotateAngle > 0.0099999997764825821) + { + this.cachedGraphic = new Graphic_RandomRotated(this.cachedGraphic, this.onGroundRandomRotateAngle); + } + if (this.Linked) + { + this.cachedGraphic = GraphicUtility.WrapLinked(this.cachedGraphic, this.linkType); + } } } @@ -116,16 +117,28 @@ public Graphic GraphicColoredFor(Thing t) return this.Graphic.GetColoredVersion(this.Graphic.Shader, t.DrawColor, t.DrawColorTwo); } - [DebuggerHidden] internal IEnumerable ConfigErrors(ThingDef thingDef) { - GraphicData.c__Iterator1C8 c__Iterator1C = new GraphicData.c__Iterator1C8(); - c__Iterator1C.thingDef = thingDef; - c__Iterator1C.<$>thingDef = thingDef; - c__Iterator1C.<>f__this = this; - GraphicData.c__Iterator1C8 expr_1C = c__Iterator1C; - expr_1C.$PC = -2; - return expr_1C; + if (this.graphicClass == null) + { + yield return "graphicClass is null"; + } + if (this.texPath.NullOrEmpty()) + { + yield return "texPath is null or empty"; + } + if (thingDef != null && thingDef.drawerType == DrawerType.RealtimeOnly && this.Linked) + { + yield return "does not add to map mesh but has a link drawer. Link drawers can only work on the map mesh."; + } + if (this.shaderType != ShaderType.Cutout && this.shaderType != ShaderType.CutoutComplex) + yield break; + if (thingDef.mote != null) + { + if (!(thingDef.mote.fadeInTime > 0.0) && !(thingDef.mote.fadeOutTime > 0.0)) + yield break; + yield return "mote fades but uses cutout shader type. It will abruptly disappear when opacity falls under the cutout threshold."; + } } } } diff --git a/Assembly-CSharp/Verse/GraphicDatabase.cs b/Assembly-CSharp/Verse/GraphicDatabase.cs index f711f949c..aaac0c513 100644 --- a/Assembly-CSharp/Verse/GraphicDatabase.cs +++ b/Assembly-CSharp/Verse/GraphicDatabase.cs @@ -12,37 +12,37 @@ public static class GraphicDatabase public static Graphic Get(string path) where T : Graphic, new() { GraphicRequest req = new GraphicRequest(typeof(T), path, ShaderDatabase.Cutout, Vector2.one, Color.white, Color.white, null, 0); - return GraphicDatabase.GetInner(req); + return (Graphic)(object)GraphicDatabase.GetInner(req); } public static Graphic Get(string path, Shader shader) where T : Graphic, new() { GraphicRequest req = new GraphicRequest(typeof(T), path, shader, Vector2.one, Color.white, Color.white, null, 0); - return GraphicDatabase.GetInner(req); + return (Graphic)(object)GraphicDatabase.GetInner(req); } public static Graphic Get(string path, Shader shader, Vector2 drawSize, Color color) where T : Graphic, new() { GraphicRequest req = new GraphicRequest(typeof(T), path, shader, drawSize, color, Color.white, null, 0); - return GraphicDatabase.GetInner(req); + return (Graphic)(object)GraphicDatabase.GetInner(req); } public static Graphic Get(string path, Shader shader, Vector2 drawSize, Color color, int renderQueue) where T : Graphic, new() { GraphicRequest req = new GraphicRequest(typeof(T), path, shader, drawSize, color, Color.white, null, renderQueue); - return GraphicDatabase.GetInner(req); + return (Graphic)(object)GraphicDatabase.GetInner(req); } public static Graphic Get(string path, Shader shader, Vector2 drawSize, Color color, Color colorTwo) where T : Graphic, new() { GraphicRequest req = new GraphicRequest(typeof(T), path, shader, drawSize, color, colorTwo, null, 0); - return GraphicDatabase.GetInner(req); + return (Graphic)(object)GraphicDatabase.GetInner(req); } public static Graphic Get(string path, Shader shader, Vector2 drawSize, Color color, Color colorTwo, GraphicData data) where T : Graphic, new() { GraphicRequest req = new GraphicRequest(typeof(T), path, shader, drawSize, color, colorTwo, data, 0); - return GraphicDatabase.GetInner(req); + return (Graphic)(object)GraphicDatabase.GetInner(req); } public static Graphic Get(Type graphicClass, string path, Shader shader, Vector2 drawSize, Color color, Color colorTwo) @@ -87,36 +87,26 @@ public static Graphic Get(Type graphicClass, string path, Shader shader, Vector2 } try { - return (Graphic)GenGeneric.InvokeStaticGenericMethod(typeof(GraphicDatabase), graphicRequest.graphicClass, "GetInner", new object[] - { - graphicRequest - }); + return (Graphic)GenGeneric.InvokeStaticGenericMethod(typeof(GraphicDatabase), graphicRequest.graphicClass, "GetInner", graphicRequest); + IL_012f:; } catch (Exception ex) { - Log.Error(string.Concat(new object[] - { - "Exception getting ", - graphicClass, - " at ", - path, - ": ", - ex.ToString() - })); + Log.Error("Exception getting " + graphicClass + " at " + path + ": " + ex.ToString()); } return BaseContent.BadGraphic; } private static T GetInner(GraphicRequest req) where T : Graphic, new() { - Graphic graphic; + Graphic graphic = default(Graphic); if (!GraphicDatabase.allGraphics.TryGetValue(req, out graphic)) { - graphic = Activator.CreateInstance(); + graphic = (Graphic)(object)new T(); graphic.Init(req); GraphicDatabase.allGraphics.Add(req, graphic); } - return (T)((object)graphic); + return (T)graphic; } public static void Clear() @@ -129,15 +119,24 @@ public static void DebugLogAllGraphics() StringBuilder stringBuilder = new StringBuilder(); stringBuilder.AppendLine("There are " + GraphicDatabase.allGraphics.Count + " graphics loaded."); int num = 0; - foreach (Graphic current in GraphicDatabase.allGraphics.Values) + Dictionary.ValueCollection.Enumerator enumerator = GraphicDatabase.allGraphics.Values.GetEnumerator(); + try { - stringBuilder.AppendLine(num + " - " + current.ToString()); - if (num % 50 == 49) + while (enumerator.MoveNext()) { - Log.Message(stringBuilder.ToString()); - stringBuilder = new StringBuilder(); + Graphic current = enumerator.Current; + stringBuilder.AppendLine(num + " - " + current.ToString()); + if (num % 50 == 49) + { + Log.Message(stringBuilder.ToString()); + stringBuilder = new StringBuilder(); + } + num++; } - num++; + } + finally + { + ((IDisposable)(object)enumerator).Dispose(); } Log.Message(stringBuilder.ToString()); } diff --git a/Assembly-CSharp/Verse/GraphicDatabaseHeadRecords.cs b/Assembly-CSharp/Verse/GraphicDatabaseHeadRecords.cs index b6b325bed..e1b1a7020 100644 --- a/Assembly-CSharp/Verse/GraphicDatabaseHeadRecords.cs +++ b/Assembly-CSharp/Verse/GraphicDatabaseHeadRecords.cs @@ -22,14 +22,11 @@ public HeadGraphicRecord(string graphicPath) { this.graphicPath = graphicPath; string fileNameWithoutExtension = Path.GetFileNameWithoutExtension(graphicPath); - string[] array = fileNameWithoutExtension.Split(new char[] - { - '_' - }); + string[] array = fileNameWithoutExtension.Split('_'); try { - this.crownType = (CrownType)((byte)ParseHelper.FromString(array[array.Length - 2], typeof(CrownType))); - this.gender = (Gender)((byte)ParseHelper.FromString(array[array.Length - 3], typeof(Gender))); + this.crownType = (CrownType)(byte)ParseHelper.FromString(array[array.Length - 2], typeof(CrownType)); + this.gender = (Gender)(byte)ParseHelper.FromString(array[array.Length - 3], typeof(Gender)); } catch (Exception ex) { @@ -54,13 +51,13 @@ public Graphic_Multi GetGraphic(Color color) } } - private static List heads = new List(); + private static List heads = new List(); - private static GraphicDatabaseHeadRecords.HeadGraphicRecord skull; + private static HeadGraphicRecord skull; - private static GraphicDatabaseHeadRecords.HeadGraphicRecord stump; + private static HeadGraphicRecord stump; - private static readonly string[] HeadsFolderPaths = new string[] + private static readonly string[] HeadsFolderPaths = new string[2] { "Things/Pawn/Humanlike/Heads/Male", "Things/Pawn/Humanlike/Heads/Female" @@ -80,21 +77,19 @@ public static void Reset() private static void BuildDatabaseIfNecessary() { if (GraphicDatabaseHeadRecords.heads.Count > 0 && GraphicDatabaseHeadRecords.skull != null && GraphicDatabaseHeadRecords.stump != null) - { return; - } GraphicDatabaseHeadRecords.heads.Clear(); string[] headsFolderPaths = GraphicDatabaseHeadRecords.HeadsFolderPaths; for (int i = 0; i < headsFolderPaths.Length; i++) { string text = headsFolderPaths[i]; - foreach (string current in GraphicDatabaseUtility.GraphicNamesInFolder(text)) + foreach (string item in GraphicDatabaseUtility.GraphicNamesInFolder(text)) { - GraphicDatabaseHeadRecords.heads.Add(new GraphicDatabaseHeadRecords.HeadGraphicRecord(text + "/" + current)); + GraphicDatabaseHeadRecords.heads.Add(new HeadGraphicRecord(text + "/" + item)); } } - GraphicDatabaseHeadRecords.skull = new GraphicDatabaseHeadRecords.HeadGraphicRecord(GraphicDatabaseHeadRecords.SkullPath); - GraphicDatabaseHeadRecords.stump = new GraphicDatabaseHeadRecords.HeadGraphicRecord(GraphicDatabaseHeadRecords.StumpPath); + GraphicDatabaseHeadRecords.skull = new HeadGraphicRecord(GraphicDatabaseHeadRecords.SkullPath); + GraphicDatabaseHeadRecords.stump = new HeadGraphicRecord(GraphicDatabaseHeadRecords.StumpPath); } public static Graphic_Multi GetHeadNamed(string graphicPath, Color skinColor) @@ -102,14 +97,14 @@ public static Graphic_Multi GetHeadNamed(string graphicPath, Color skinColor) GraphicDatabaseHeadRecords.BuildDatabaseIfNecessary(); for (int i = 0; i < GraphicDatabaseHeadRecords.heads.Count; i++) { - GraphicDatabaseHeadRecords.HeadGraphicRecord headGraphicRecord = GraphicDatabaseHeadRecords.heads[i]; + HeadGraphicRecord headGraphicRecord = GraphicDatabaseHeadRecords.heads[i]; if (headGraphicRecord.graphicPath == graphicPath) { return headGraphicRecord.GetGraphic(skinColor); } } Log.Message("Tried to get pawn head at path " + graphicPath + " that was not found. Defaulting..."); - return GraphicDatabaseHeadRecords.heads.First().GetGraphic(skinColor); + return GraphicDatabaseHeadRecords.heads.First().GetGraphic(skinColor); } public static Graphic_Multi GetSkull() @@ -127,33 +122,39 @@ public static Graphic_Multi GetStump(Color skinColor) public static Graphic_Multi GetHeadRandom(Gender gender, Color skinColor, CrownType crownType) { GraphicDatabaseHeadRecords.BuildDatabaseIfNecessary(); - Predicate predicate = (GraphicDatabaseHeadRecords.HeadGraphicRecord head) => head.crownType == crownType && head.gender == gender; + Predicate predicate = (Predicate)delegate(HeadGraphicRecord head) + { + if (head.crownType != crownType) + { + return false; + } + if (head.gender != gender) + { + return false; + } + return true; + }; int num = 0; - GraphicDatabaseHeadRecords.HeadGraphicRecord headGraphicRecord; while (true) { - headGraphicRecord = GraphicDatabaseHeadRecords.heads.RandomElement(); + HeadGraphicRecord headGraphicRecord = GraphicDatabaseHeadRecords.heads.RandomElement(); if (predicate(headGraphicRecord)) { - break; + return headGraphicRecord.GetGraphic(skinColor); } num++; if (num > 40) - { - goto Block_2; - } + break; } - return headGraphicRecord.GetGraphic(skinColor); - Block_2: - foreach (GraphicDatabaseHeadRecords.HeadGraphicRecord current in GraphicDatabaseHeadRecords.heads.InRandomOrder(null)) + foreach (HeadGraphicRecord item in GraphicDatabaseHeadRecords.heads.InRandomOrder(null)) { - if (predicate(current)) + if (predicate(item)) { - return current.GetGraphic(skinColor); + return item.GetGraphic(skinColor); } } Log.Error("Failed to find head for gender=" + gender + ". Defaulting..."); - return GraphicDatabaseHeadRecords.heads.First().GetGraphic(skinColor); + return GraphicDatabaseHeadRecords.heads.First().GetGraphic(skinColor); } } } diff --git a/Assembly-CSharp/Verse/GraphicDatabaseUtility.cs b/Assembly-CSharp/Verse/GraphicDatabaseUtility.cs index 00dc611e0..79be2b00b 100644 --- a/Assembly-CSharp/Verse/GraphicDatabaseUtility.cs +++ b/Assembly-CSharp/Verse/GraphicDatabaseUtility.cs @@ -1,20 +1,42 @@ -using System; using System.Collections.Generic; -using System.Diagnostics; +using UnityEngine; namespace Verse { public static class GraphicDatabaseUtility { - [DebuggerHidden] public static IEnumerable GraphicNamesInFolder(string folderPath) { - GraphicDatabaseUtility.c__Iterator22D c__Iterator22D = new GraphicDatabaseUtility.c__Iterator22D(); - c__Iterator22D.folderPath = folderPath; - c__Iterator22D.<$>folderPath = folderPath; - GraphicDatabaseUtility.c__Iterator22D expr_15 = c__Iterator22D; - expr_15.$PC = -2; - return expr_15; + HashSet loadedAssetNames = new HashSet(); + Texture2D[] array = Resources.LoadAll("Textures/" + folderPath); + for (int i = 0; i < array.Length; i++) + { + Texture2D tex = array[i]; + string origAssetName = tex.name; + string[] pieces = origAssetName.Split('_'); + string assetName = string.Empty; + if (pieces.Length <= 2) + { + assetName = pieces[0]; + } + else if (pieces.Length == 3) + { + assetName = pieces[0] + "_" + pieces[1]; + } + else if (pieces.Length == 4) + { + assetName = pieces[0] + "_" + pieces[1] + "_" + pieces[2]; + } + else + { + Log.Error("Cannot load assets with >3 pieces."); + } + if (!loadedAssetNames.Contains(assetName)) + { + loadedAssetNames.Add(assetName); + yield return assetName; + } + } } } } diff --git a/Assembly-CSharp/Verse/GraphicGetter_NakedHumanlike.cs b/Assembly-CSharp/Verse/GraphicGetter_NakedHumanlike.cs index a7909d630..1e2ee7e73 100644 --- a/Assembly-CSharp/Verse/GraphicGetter_NakedHumanlike.cs +++ b/Assembly-CSharp/Verse/GraphicGetter_NakedHumanlike.cs @@ -15,7 +15,7 @@ public static Graphic GetNakedBodyGraphic(BodyType bodyType, Shader shader, Colo Log.Error("Getting naked body graphic with undefined body type."); bodyType = BodyType.Male; } - string str = "Naked_" + bodyType.ToString(); + string str = "Naked_" + ((Enum)(object)bodyType).ToString(); string path = "Things/Pawn/Humanlike/Bodies/" + str; return GraphicDatabase.Get(path, shader, Vector2.one, skinColor); } diff --git a/Assembly-CSharp/Verse/GraphicMeshSet.cs b/Assembly-CSharp/Verse/GraphicMeshSet.cs index 8b60051a1..f7b8a6d0f 100644 --- a/Assembly-CSharp/Verse/GraphicMeshSet.cs +++ b/Assembly-CSharp/Verse/GraphicMeshSet.cs @@ -1,4 +1,3 @@ -using System; using UnityEngine; namespace Verse @@ -9,12 +8,7 @@ public class GraphicMeshSet public GraphicMeshSet(Mesh normalMesh, Mesh leftMesh) { - Mesh[] arg_30_0 = this.meshes; - int arg_30_1 = 0; - Mesh[] arg_2E_0 = this.meshes; - int arg_2E_1 = 1; - this.meshes[2] = normalMesh; - arg_30_0[arg_30_1] = (arg_2E_0[arg_2E_1] = normalMesh); + this.meshes[0] = (this.meshes[1] = (this.meshes[2] = normalMesh)); this.meshes[3] = leftMesh; } diff --git a/Assembly-CSharp/Verse/GraphicRequest.cs b/Assembly-CSharp/Verse/GraphicRequest.cs index 74f3be1bc..7ad895f66 100644 --- a/Assembly-CSharp/Verse/GraphicRequest.cs +++ b/Assembly-CSharp/Verse/GraphicRequest.cs @@ -40,24 +40,28 @@ public override int GetHashCode() this.path = BaseContent.BadTexPath; } int seed = 0; - seed = Gen.HashCombine(seed, this.graphicClass); - seed = Gen.HashCombine(seed, this.path); - seed = Gen.HashCombine(seed, this.shader); - seed = Gen.HashCombineStruct(seed, this.drawSize); - seed = Gen.HashCombineStruct(seed, this.color); - seed = Gen.HashCombineStruct(seed, this.colorTwo); - seed = Gen.HashCombine(seed, this.graphicData); - return Gen.HashCombine(seed, this.renderQueue); + seed = Gen.HashCombine(seed, this.graphicClass); + seed = Gen.HashCombine(seed, this.path); + seed = Gen.HashCombine(seed, this.shader); + seed = Gen.HashCombineStruct(seed, this.drawSize); + seed = Gen.HashCombineStruct(seed, this.color); + seed = Gen.HashCombineStruct(seed, this.colorTwo); + seed = Gen.HashCombine(seed, this.graphicData); + return Gen.HashCombine(seed, this.renderQueue); } public override bool Equals(object obj) { - return obj is GraphicRequest && this.Equals((GraphicRequest)obj); + if (!(obj is GraphicRequest)) + { + return false; + } + return this.Equals((GraphicRequest)obj); } public bool Equals(GraphicRequest other) { - return this.graphicClass == other.graphicClass && this.path == other.path && this.shader == other.shader && this.drawSize == other.drawSize && this.color == other.color && this.colorTwo == other.colorTwo && this.graphicData == other.graphicData && this.renderQueue == other.renderQueue; + return this.graphicClass == other.graphicClass && this.path == other.path && (UnityEngine.Object)this.shader == (UnityEngine.Object)other.shader && this.drawSize == other.drawSize && this.color == other.color && this.colorTwo == other.colorTwo && this.graphicData == other.graphicData && this.renderQueue == other.renderQueue; } public static bool operator ==(GraphicRequest lhs, GraphicRequest rhs) diff --git a/Assembly-CSharp/Verse/GraphicUtility.cs b/Assembly-CSharp/Verse/GraphicUtility.cs index b0580a64f..0d28cb7c0 100644 --- a/Assembly-CSharp/Verse/GraphicUtility.cs +++ b/Assembly-CSharp/Verse/GraphicUtility.cs @@ -20,18 +20,30 @@ public static Graphic_Linked WrapLinked(Graphic subGraphic, LinkDrawerType linkD switch (linkDrawerType) { case LinkDrawerType.None: + { return null; + } case LinkDrawerType.Basic: + { return new Graphic_Linked(subGraphic); + } case LinkDrawerType.CornerFiller: + { return new Graphic_LinkedCornerFiller(subGraphic); + } case LinkDrawerType.Transmitter: + { return new Graphic_LinkedTransmitter(subGraphic); + } case LinkDrawerType.TransmitterOverlay: + { return new Graphic_LinkedTransmitterOverlay(subGraphic); + } default: + { throw new ArgumentException(); } + } } } } diff --git a/Assembly-CSharp/Verse/Graphic_Appearances.cs b/Assembly-CSharp/Verse/Graphic_Appearances.cs index 1723b65bf..715b8eba4 100644 --- a/Assembly-CSharp/Verse/Graphic_Appearances.cs +++ b/Assembly-CSharp/Verse/Graphic_Appearances.cs @@ -14,16 +14,16 @@ public override Material MatSingle { get { - return this.subGraphics[(int)StuffAppearanceDefOf.Smooth.index].MatSingle; + return this.subGraphics[StuffAppearanceDefOf.Smooth.index].MatSingle; } } public override void Init(GraphicRequest req) { - this.data = req.graphicData; - this.path = req.path; - this.color = req.color; - this.drawSize = req.drawSize; + base.data = req.graphicData; + base.path = req.path; + base.color = req.color; + base.drawSize = req.drawSize; List allDefsListForReading = DefDatabase.AllDefsListForReading; this.subGraphics = new Graphic[allDefsListForReading.Count]; for (int i = 0; i < this.subGraphics.Length; i++) @@ -32,24 +32,21 @@ public override void Init(GraphicRequest req) string text = req.path; if (!stuffAppearance.pathPrefix.NullOrEmpty()) { - text = stuffAppearance.pathPrefix + "/" + text.Split(new char[] - { - '/' - }).Last(); + text = stuffAppearance.pathPrefix + "/" + text.Split('/').Last(); } Texture2D texture2D = (from x in ContentFinder.GetAllInFolder(text) where x.name.EndsWith(stuffAppearance.defName) - select x).FirstOrDefault(); - if (texture2D != null) + select x).FirstOrDefault(); + if ((UnityEngine.Object)texture2D != (UnityEngine.Object)null) { - this.subGraphics[i] = GraphicDatabase.Get(text + "/" + texture2D.name, req.shader, this.drawSize, this.color); + this.subGraphics[i] = GraphicDatabase.Get(text + "/" + texture2D.name, req.shader, base.drawSize, base.color); } } for (int j = 0; j < this.subGraphics.Length; j++) { if (this.subGraphics[j] == null) { - this.subGraphics[j] = this.subGraphics[(int)StuffAppearanceDefOf.Smooth.index]; + this.subGraphics[j] = this.subGraphics[StuffAppearanceDefOf.Smooth.index]; } } } @@ -60,7 +57,7 @@ public override Graphic GetColoredVersion(Shader newShader, Color newColor, Colo { Log.ErrorOnce("Cannot use Graphic_Appearances.GetColoredVersion with a non-white colorTwo.", 9910251); } - return GraphicDatabase.Get(this.path, newShader, this.drawSize, newColor, Color.white, this.data); + return GraphicDatabase.Get(base.path, newShader, base.drawSize, newColor, Color.white, base.data); } public override Material MatSingleFor(Thing thing) @@ -70,7 +67,7 @@ public override Material MatSingleFor(Thing thing) { stuffAppearanceDef = thing.Stuff.stuffProps.appearance; } - Graphic graphic = this.subGraphics[(int)stuffAppearanceDef.index]; + Graphic graphic = this.subGraphics[stuffAppearanceDef.index]; return graphic.MatSingleFor(thing); } @@ -81,20 +78,13 @@ public override void DrawWorker(Vector3 loc, Rot4 rot, ThingDef thingDef, Thing { stuffAppearanceDef = thing.Stuff.stuffProps.appearance; } - Graphic graphic = this.subGraphics[(int)stuffAppearanceDef.index]; + Graphic graphic = this.subGraphics[stuffAppearanceDef.index]; graphic.DrawWorker(loc, rot, thingDef, thing); } public override string ToString() { - return string.Concat(new object[] - { - "Appearance(path=", - this.path, - ", color=", - this.color, - ", colorTwo=unsupported)" - }); + return "Appearance(path=" + base.path + ", color=" + base.color + ", colorTwo=unsupported)"; } } } diff --git a/Assembly-CSharp/Verse/Graphic_Cluster.cs b/Assembly-CSharp/Verse/Graphic_Cluster.cs index 65ef48bf9..c2635f739 100644 --- a/Assembly-CSharp/Verse/Graphic_Cluster.cs +++ b/Assembly-CSharp/Verse/Graphic_Cluster.cs @@ -1,5 +1,4 @@ using RimWorld; -using System; using UnityEngine; namespace Verse @@ -14,7 +13,7 @@ public override Material MatSingle { get { - return this.subGraphics[Rand.Range(0, this.subGraphics.Length)].MatSingle; + return base.subGraphics[Rand.Range(0, base.subGraphics.Length)].MatSingle; } } @@ -29,22 +28,14 @@ public override void Print(SectionLayer layer, Thing thing) Rand.PushState(); Rand.Seed = thing.Position.GetHashCode(); Filth filth = thing as Filth; - int num; - if (filth == null) - { - num = 3; - } - else - { - num = filth.thickness; - } - for (int i = 0; i < num; i++) + int num = (filth != null) ? filth.thickness : 3; + for (int num2 = 0; num2 < num; num2++) { Material matSingle = this.MatSingle; Vector3 center = a + new Vector3(Rand.Range(-0.45f, 0.45f), 0f, Rand.Range(-0.45f, 0.45f)); Vector2 size = new Vector2(Rand.Range(0.8f, 1.2f), Rand.Range(0.8f, 1.2f)); float rot = (float)Rand.RangeInclusive(0, 360); - bool flipUv = Rand.Value < 0.5f; + bool flipUv = Rand.Value < 0.5; Printer_Plane.PrintPlane(layer, center, size, matSingle, rot, flipUv, null, null, 0.01f); } Rand.PopState(); @@ -52,14 +43,7 @@ public override void Print(SectionLayer layer, Thing thing) public override string ToString() { - return string.Concat(new object[] - { - "Scatter(subGraphic[0]=", - this.subGraphics[0].ToString(), - ", count=", - this.subGraphics.Length, - ")" - }); + return "Scatter(subGraphic[0]=" + base.subGraphics[0].ToString() + ", count=" + base.subGraphics.Length + ")"; } } } diff --git a/Assembly-CSharp/Verse/Graphic_Collection.cs b/Assembly-CSharp/Verse/Graphic_Collection.cs index 1ebc242f5..1aa760987 100644 --- a/Assembly-CSharp/Verse/Graphic_Collection.cs +++ b/Assembly-CSharp/Verse/Graphic_Collection.cs @@ -11,35 +11,37 @@ public abstract class Graphic_Collection : Graphic public override void Init(GraphicRequest req) { - this.data = req.graphicData; + base.data = req.graphicData; if (req.path.NullOrEmpty()) { throw new ArgumentNullException("folderPath"); } - if (req.shader == null) + if ((UnityEngine.Object)req.shader == (UnityEngine.Object)null) { throw new ArgumentNullException("shader"); } - this.path = req.path; - this.color = req.color; - this.drawSize = req.drawSize; + base.path = req.path; + base.color = req.color; + base.drawSize = req.drawSize; List list = (from x in ContentFinder.GetAllInFolder(req.path) where !x.name.EndsWith(Graphic_Single.MaskSuffix) - select x).ToList(); - if (list.NullOrEmpty()) + select x).ToList(); + if (list.NullOrEmpty()) { Log.Error("Collection cannot init: No textures found at path " + req.path); - this.subGraphics = new Graphic[] + this.subGraphics = new Graphic[1] { BaseContent.BadGraphic }; - return; } - this.subGraphics = new Graphic[list.Count]; - for (int i = 0; i < list.Count; i++) + else { - string path = req.path + "/" + list[i].name; - this.subGraphics[i] = GraphicDatabase.Get(path, req.shader, this.drawSize, this.color); + this.subGraphics = new Graphic[list.Count]; + for (int i = 0; i < list.Count; i++) + { + string path = req.path + "/" + list[i].name; + this.subGraphics[i] = GraphicDatabase.Get(path, req.shader, base.drawSize, base.color); + } } } } diff --git a/Assembly-CSharp/Verse/Graphic_Flicker.cs b/Assembly-CSharp/Verse/Graphic_Flicker.cs index 618049636..c5a0410dc 100644 --- a/Assembly-CSharp/Verse/Graphic_Flicker.cs +++ b/Assembly-CSharp/Verse/Graphic_Flicker.cs @@ -1,5 +1,4 @@ using RimWorld; -using System; using UnityEngine; namespace Verse @@ -16,7 +15,7 @@ public override Material MatSingle { get { - return this.subGraphics[Rand.Range(0, this.subGraphics.Length)].MatSingle; + return base.subGraphics[Rand.Range(0, base.subGraphics.Length)].MatSingle; } } @@ -25,64 +24,59 @@ public override void DrawWorker(Vector3 loc, Rot4 rot, ThingDef thingDef, Thing if (thingDef == null) { Log.ErrorOnce("Fire DrawWorker with null thingDef: " + loc, 3427324); - return; } - if (this.subGraphics == null) + else if (base.subGraphics == null) { Log.ErrorOnce("Graphic_Flicker has no subgraphics " + thingDef, 358773632); - return; } - int num = Find.TickManager.TicksGame; - int num2 = 0; - int num3 = 0; - float num4 = 1f; - CompFireOverlay compFireOverlay = null; - if (thing != null) + else { - compFireOverlay = thing.TryGetComp(); - num += Mathf.Abs(thing.thingIDNumber ^ 8453458); - num2 = num / 15; - num3 = Mathf.Abs(num2 ^ thing.thingIDNumber * 391) % this.subGraphics.Length; - Fire fire = thing as Fire; - if (fire != null) + int ticksGame = Find.TickManager.TicksGame; + int num = 0; + int num2 = 0; + Fire fire = null; + float num3 = 1f; + CompFireOverlay compFireOverlay = null; + if (thing != null) { - num4 = fire.fireSize; + compFireOverlay = thing.TryGetComp(); + ticksGame += Mathf.Abs(thing.thingIDNumber ^ 8453458); + num = ticksGame / 15; + num2 = Mathf.Abs(num ^ thing.thingIDNumber * 391) % base.subGraphics.Length; + fire = (thing as Fire); + if (fire != null) + { + num3 = fire.fireSize; + } + else if (compFireOverlay != null) + { + num3 = compFireOverlay.Props.fireSize; + } } - else if (compFireOverlay != null) + if (num2 < 0 || num2 >= base.subGraphics.Length) { - num4 = compFireOverlay.Props.fireSize; + Log.ErrorOnce("Fire drawing out of range: " + num2, 7453435); + num2 = 0; } + Graphic graphic = base.subGraphics[num2]; + float num4 = Mathf.Min((float)(num3 / 1.2000000476837158), 1.2f); + Vector3 a = GenRadial.RadialPattern[num % GenRadial.RadialPattern.Length].ToVector3() / GenRadial.MaxRadialPatternRadius; + a *= 0.05f; + Vector3 vector = loc + a * num3; + if (compFireOverlay != null) + { + vector += compFireOverlay.Props.offset; + } + Vector3 s = new Vector3(num4, 1f, num4); + Matrix4x4 matrix = default(Matrix4x4); + matrix.SetTRS(vector, Quaternion.identity, s); + Graphics.DrawMesh(MeshPool.plane10, matrix, graphic.MatSingle, 0); } - if (num3 < 0 || num3 >= this.subGraphics.Length) - { - Log.ErrorOnce("Fire drawing out of range: " + num3, 7453435); - num3 = 0; - } - Graphic graphic = this.subGraphics[num3]; - float num5 = Mathf.Min(num4 / 1.2f, 1.2f); - Vector3 a = GenRadial.RadialPattern[num2 % GenRadial.RadialPattern.Length].ToVector3() / GenRadial.MaxRadialPatternRadius; - a *= 0.05f; - Vector3 vector = loc + a * num4; - if (compFireOverlay != null) - { - vector += compFireOverlay.Props.offset; - } - Vector3 s = new Vector3(num5, 1f, num5); - Matrix4x4 matrix = default(Matrix4x4); - matrix.SetTRS(vector, Quaternion.identity, s); - Graphics.DrawMesh(MeshPool.plane10, matrix, graphic.MatSingle, 0); } public override string ToString() { - return string.Concat(new object[] - { - "Flicker(subGraphic[0]=", - this.subGraphics[0].ToString(), - ", count=", - this.subGraphics.Length, - ")" - }); + return "Flicker(subGraphic[0]=" + base.subGraphics[0].ToString() + ", count=" + base.subGraphics.Length + ")"; } } } diff --git a/Assembly-CSharp/Verse/Graphic_Gas.cs b/Assembly-CSharp/Verse/Graphic_Gas.cs index bdd62ed92..fecb437b2 100644 --- a/Assembly-CSharp/Verse/Graphic_Gas.cs +++ b/Assembly-CSharp/Verse/Graphic_Gas.cs @@ -1,5 +1,4 @@ using RimWorld; -using System; using UnityEngine; namespace Verse @@ -15,9 +14,9 @@ public override void DrawWorker(Vector3 loc, Rot4 rot, ThingDef thingDef, Thing Rand.PushState(); Rand.Seed = thing.thingIDNumber.GetHashCode(); Gas gas = thing as Gas; - float angle = (float)Rand.Range(0, 360) + ((gas != null) ? gas.graphicRotation : 0f); + float angle = (float)((float)Rand.Range(0, 360) + ((gas != null) ? gas.graphicRotation : 0.0)); Vector3 pos = thing.TrueCenter() + new Vector3(Rand.Range(-0.45f, 0.45f), 0f, Rand.Range(-0.45f, 0.45f)); - Vector3 s = new Vector3(Rand.Range(0.8f, 1.2f) * this.drawSize.x, 0f, Rand.Range(0.8f, 1.2f) * this.drawSize.y); + Vector3 s = new Vector3(Rand.Range(0.8f, 1.2f) * base.drawSize.x, 0f, Rand.Range(0.8f, 1.2f) * base.drawSize.y); Matrix4x4 matrix = default(Matrix4x4); matrix.SetTRS(pos, Quaternion.AngleAxis(angle, Vector3.up), s); Graphics.DrawMesh(MeshPool.plane10, matrix, this.MatSingle, 0); diff --git a/Assembly-CSharp/Verse/Graphic_Linked.cs b/Assembly-CSharp/Verse/Graphic_Linked.cs index 7431f8c13..d8f46af6e 100644 --- a/Assembly-CSharp/Verse/Graphic_Linked.cs +++ b/Assembly-CSharp/Verse/Graphic_Linked.cs @@ -1,4 +1,3 @@ -using System; using UnityEngine; namespace Verse @@ -34,10 +33,9 @@ public Graphic_Linked(Graphic subGraphic) public override Graphic GetColoredVersion(Shader newShader, Color newColor, Color newColorTwo) { - return new Graphic_Linked(this.subGraphic.GetColoredVersion(newShader, newColor, newColorTwo)) - { - data = this.data - }; + Graphic_Linked graphic_Linked = new Graphic_Linked(this.subGraphic.GetColoredVersion(newShader, newColor, newColorTwo)); + graphic_Linked.data = base.data; + return graphic_Linked; } public override void Print(SectionLayer layer, Thing thing) @@ -59,7 +57,7 @@ protected Material LinkedDrawMatFrom(Thing parent, IntVec3 cell) } num2 *= 2; } - LinkDirections linkSet = (LinkDirections)num; + LinkDirections linkSet = (LinkDirections)(byte)num; Material mat = this.subGraphic.MatSingleFor(parent); return MaterialAtlasPool.SubMaterialFromAtlas(mat, linkSet); } @@ -68,7 +66,7 @@ public virtual bool ShouldLinkWith(IntVec3 c, Thing parent) { if (!c.InBounds(parent.Map)) { - return (parent.def.graphicData.linkFlags & LinkFlags.MapEdge) != LinkFlags.None; + return ((int)parent.def.graphicData.linkFlags & 1) != 0; } return (parent.Map.linkGrid.LinkFlagsAt(c) & parent.def.graphicData.linkFlags) != LinkFlags.None; } diff --git a/Assembly-CSharp/Verse/Graphic_LinkedCornerFiller.cs b/Assembly-CSharp/Verse/Graphic_LinkedCornerFiller.cs index 4c4d623cb..9bbbd1c66 100644 --- a/Assembly-CSharp/Verse/Graphic_LinkedCornerFiller.cs +++ b/Assembly-CSharp/Verse/Graphic_LinkedCornerFiller.cs @@ -1,4 +1,3 @@ -using System; using UnityEngine; namespace Verse @@ -9,13 +8,19 @@ public class Graphic_LinkedCornerFiller : Graphic_Linked private const float CoverSize = 0.45f; - private static readonly float CoverSizeCornerCorner; + private static readonly float CoverSizeCornerCorner = new Vector2(0.45f, 0.45f).magnitude; - private static readonly float DistCenterCorner; + private static readonly float DistCenterCorner = new Vector2(0.5f, 0.5f).magnitude; - private static readonly float CoverOffsetDist; + private static readonly float CoverOffsetDist = (float)(Graphic_LinkedCornerFiller.DistCenterCorner - Graphic_LinkedCornerFiller.CoverSizeCornerCorner * 0.5); - private static readonly Vector2[] CornerFillUVs; + private static readonly Vector2[] CornerFillUVs = new Vector2[4] + { + new Vector2(0.5f, 0.6f), + new Vector2(0.5f, 0.6f), + new Vector2(0.5f, 0.6f), + new Vector2(0.5f, 0.6f) + }; public override LinkDrawerType LinkerType { @@ -29,29 +34,11 @@ public Graphic_LinkedCornerFiller(Graphic subGraphic) : base(subGraphic) { } - static Graphic_LinkedCornerFiller() - { - // Note: this type is marked as 'beforefieldinit'. - Vector2 vector = new Vector2(0.45f, 0.45f); - Graphic_LinkedCornerFiller.CoverSizeCornerCorner = vector.magnitude; - Vector2 vector2 = new Vector2(0.5f, 0.5f); - Graphic_LinkedCornerFiller.DistCenterCorner = vector2.magnitude; - Graphic_LinkedCornerFiller.CoverOffsetDist = Graphic_LinkedCornerFiller.DistCenterCorner - Graphic_LinkedCornerFiller.CoverSizeCornerCorner * 0.5f; - Graphic_LinkedCornerFiller.CornerFillUVs = new Vector2[] - { - new Vector2(0.5f, 0.6f), - new Vector2(0.5f, 0.6f), - new Vector2(0.5f, 0.6f), - new Vector2(0.5f, 0.6f) - }; - } - public override Graphic GetColoredVersion(Shader newShader, Color newColor, Color newColorTwo) { - return new Graphic_LinkedCornerFiller(this.subGraphic.GetColoredVersion(newShader, newColor, newColorTwo)) - { - data = this.data - }; + Graphic_LinkedCornerFiller graphic_LinkedCornerFiller = new Graphic_LinkedCornerFiller(base.subGraphic.GetColoredVersion(newShader, newColor, newColorTwo)); + graphic_LinkedCornerFiller.data = base.data; + return graphic_LinkedCornerFiller; } public override void Print(SectionLayer layer, Thing thing) @@ -61,23 +48,11 @@ public override void Print(SectionLayer layer, Thing thing) for (int i = 0; i < 4; i++) { IntVec3 c = thing.Position + GenAdj.DiagonalDirectionsAround[i]; - if (this.ShouldLinkWith(c, thing)) + if (this.ShouldLinkWith(c, thing) && (i != 0 || (this.ShouldLinkWith(position + IntVec3.West, thing) && this.ShouldLinkWith(position + IntVec3.South, thing))) && (i != 1 || (this.ShouldLinkWith(position + IntVec3.West, thing) && this.ShouldLinkWith(position + IntVec3.North, thing))) && (i != 2 || (this.ShouldLinkWith(position + IntVec3.East, thing) && this.ShouldLinkWith(position + IntVec3.North, thing))) && (i != 3 || (this.ShouldLinkWith(position + IntVec3.East, thing) && this.ShouldLinkWith(position + IntVec3.South, thing)))) { - if (i != 0 || (this.ShouldLinkWith(position + IntVec3.West, thing) && this.ShouldLinkWith(position + IntVec3.South, thing))) - { - if (i != 1 || (this.ShouldLinkWith(position + IntVec3.West, thing) && this.ShouldLinkWith(position + IntVec3.North, thing))) - { - if (i != 2 || (this.ShouldLinkWith(position + IntVec3.East, thing) && this.ShouldLinkWith(position + IntVec3.North, thing))) - { - if (i != 3 || (this.ShouldLinkWith(position + IntVec3.East, thing) && this.ShouldLinkWith(position + IntVec3.South, thing))) - { - Vector3 center = thing.DrawPos + GenAdj.DiagonalDirectionsAround[i].ToVector3().normalized * Graphic_LinkedCornerFiller.CoverOffsetDist + Altitudes.AltIncVect + new Vector3(0f, 0f, 0.09f); - Vector2[] cornerFillUVs = Graphic_LinkedCornerFiller.CornerFillUVs; - Printer_Plane.PrintPlane(layer, center, new Vector2(0.45f, 0.45f), base.LinkedDrawMatFrom(thing, thing.Position), 0f, false, cornerFillUVs, null, 0.01f); - } - } - } - } + Vector3 center = thing.DrawPos + GenAdj.DiagonalDirectionsAround[i].ToVector3().normalized * Graphic_LinkedCornerFiller.CoverOffsetDist + Altitudes.AltIncVect + new Vector3(0f, 0f, 0.09f); + Vector2[] cornerFillUVs = Graphic_LinkedCornerFiller.CornerFillUVs; + Printer_Plane.PrintPlane(layer, center, new Vector2(0.45f, 0.45f), base.LinkedDrawMatFrom(thing, thing.Position), 0f, false, cornerFillUVs, null, 0.01f); } } } diff --git a/Assembly-CSharp/Verse/Graphic_Mote.cs b/Assembly-CSharp/Verse/Graphic_Mote.cs index 3c295a3bc..4fb41811c 100644 --- a/Assembly-CSharp/Verse/Graphic_Mote.cs +++ b/Assembly-CSharp/Verse/Graphic_Mote.cs @@ -1,4 +1,3 @@ -using System; using UnityEngine; namespace Verse @@ -12,26 +11,25 @@ public override void DrawWorker(Vector3 loc, Rot4 rot, ThingDef thingDef, Thing { Mote mote = (Mote)thing; float num = Graphic_Mote.CalculateMoteAlpha(mote); - if (num <= 0f) + if (!(num <= 0.0)) { - return; - } - Color color = base.Color * mote.instanceColor; - color.a *= num; - Vector3 exactScale = mote.exactScale; - exactScale.x *= this.data.drawSize.x; - exactScale.z *= this.data.drawSize.y; - Matrix4x4 matrix = default(Matrix4x4); - matrix.SetTRS(mote.DrawPos, Quaternion.AngleAxis(mote.exactRotation, Vector3.up), exactScale); - Material matSingle = this.MatSingle; - if (color.IndistinguishableFrom(matSingle.color)) - { - Graphics.DrawMesh(MeshPool.plane10, matrix, matSingle, 0); - } - else - { - Graphic_Mote.propertyBlock.SetColor(ShaderPropertyIDs.Color, color); - Graphics.DrawMesh(MeshPool.plane10, matrix, matSingle, 0, null, 0, Graphic_Mote.propertyBlock); + Color color = base.Color * mote.instanceColor; + color.a *= num; + Vector3 exactScale = mote.exactScale; + exactScale.x *= base.data.drawSize.x; + exactScale.z *= base.data.drawSize.y; + Matrix4x4 matrix = default(Matrix4x4); + matrix.SetTRS(mote.DrawPos, Quaternion.AngleAxis(mote.exactRotation, Vector3.up), exactScale); + Material matSingle = this.MatSingle; + if (color.IndistinguishableFrom(matSingle.color)) + { + Graphics.DrawMesh(MeshPool.plane10, matrix, matSingle, 0); + } + else + { + Graphic_Mote.propertyBlock.SetColor(ShaderPropertyIDs.Color, color); + Graphics.DrawMesh(MeshPool.plane10, matrix, matSingle, 0, null, 0, Graphic_Mote.propertyBlock); + } } } @@ -41,38 +39,26 @@ public static float CalculateMoteAlpha(Mote mote) float ageSecs = mote.AgeSecs; if (ageSecs <= def.mote.fadeInTime) { - if (def.mote.fadeInTime > 0f) + if (def.mote.fadeInTime > 0.0) { return ageSecs / def.mote.fadeInTime; } return 1f; } - else + if (ageSecs <= def.mote.fadeInTime + def.mote.solidTime) { - if (ageSecs <= def.mote.fadeInTime + def.mote.solidTime) - { - return 1f; - } - if (def.mote.fadeOutTime > 0f) - { - return 1f - Mathf.InverseLerp(def.mote.fadeInTime + def.mote.solidTime, def.mote.fadeInTime + def.mote.solidTime + def.mote.fadeOutTime, ageSecs); - } return 1f; } + if (def.mote.fadeOutTime > 0.0) + { + return (float)(1.0 - Mathf.InverseLerp(def.mote.fadeInTime + def.mote.solidTime, def.mote.fadeInTime + def.mote.solidTime + def.mote.fadeOutTime, ageSecs)); + } + return 1f; } public override string ToString() { - return string.Concat(new object[] - { - "Mote(path=", - this.path, - ", shader=", - base.Shader, - ", color=", - this.color, - ", colorTwo=unsupported)" - }); + return "Mote(path=" + base.path + ", shader=" + base.Shader + ", color=" + base.color + ", colorTwo=unsupported)"; } } } diff --git a/Assembly-CSharp/Verse/Graphic_MoteSplash.cs b/Assembly-CSharp/Verse/Graphic_MoteSplash.cs index fa391358e..0deb23e56 100644 --- a/Assembly-CSharp/Verse/Graphic_MoteSplash.cs +++ b/Assembly-CSharp/Verse/Graphic_MoteSplash.cs @@ -1,4 +1,3 @@ -using System; using UnityEngine; namespace Verse @@ -10,36 +9,26 @@ public override void DrawWorker(Vector3 loc, Rot4 rot, ThingDef thingDef, Thing { MoteSplash moteSplash = (MoteSplash)thing; float num = moteSplash.CalculatedAlpha(); - if (num <= 0f) + if (!(num <= 0.0)) { - return; + Color color = new Color(1f, 1f, 1f, num); + Vector3 exactScale = moteSplash.exactScale; + exactScale.x *= base.data.drawSize.x; + exactScale.z *= base.data.drawSize.y; + Matrix4x4 rhs = default(Matrix4x4); + rhs.SetTRS(moteSplash.DrawPos, Quaternion.AngleAxis(moteSplash.exactRotation, Vector3.up), exactScale); + Matrix4x4 matrix = Find.Camera.cameraToWorldMatrix * Find.Camera.projectionMatrix * Find.Camera.worldToCameraMatrix * rhs; + Material matSingle = this.MatSingle; + matSingle.SetColor(ShaderPropertyIDs.Color, color); + matSingle.SetFloat(ShaderPropertyIDs.ShockwaveSpan, moteSplash.CalculatedShockwaveSpan()); + matSingle.SetPass(0); + Graphics.DrawMeshNow(MeshPool.plane10, matrix); } - Color color = new Color(1f, 1f, 1f, num); - Vector3 exactScale = moteSplash.exactScale; - exactScale.x *= this.data.drawSize.x; - exactScale.z *= this.data.drawSize.y; - Matrix4x4 rhs = default(Matrix4x4); - rhs.SetTRS(moteSplash.DrawPos, Quaternion.AngleAxis(moteSplash.exactRotation, Vector3.up), exactScale); - Matrix4x4 matrix = Find.Camera.cameraToWorldMatrix * Find.Camera.projectionMatrix * Find.Camera.worldToCameraMatrix * rhs; - Material matSingle = this.MatSingle; - matSingle.SetColor(ShaderPropertyIDs.Color, color); - matSingle.SetFloat(ShaderPropertyIDs.ShockwaveSpan, moteSplash.CalculatedShockwaveSpan()); - matSingle.SetPass(0); - Graphics.DrawMeshNow(MeshPool.plane10, matrix); } public override string ToString() { - return string.Concat(new object[] - { - "MoteSplash(path=", - this.path, - ", shader=", - base.Shader, - ", color=", - this.color, - ", colorTwo=unsupported)" - }); + return "MoteSplash(path=" + base.path + ", shader=" + base.Shader + ", color=" + base.color + ", colorTwo=unsupported)"; } } } diff --git a/Assembly-CSharp/Verse/Graphic_Multi.cs b/Assembly-CSharp/Verse/Graphic_Multi.cs index c5a1ba49a..3056a3b8d 100644 --- a/Assembly-CSharp/Verse/Graphic_Multi.cs +++ b/Assembly-CSharp/Verse/Graphic_Multi.cs @@ -1,4 +1,3 @@ -using System; using UnityEngine; namespace Verse @@ -11,7 +10,7 @@ public string GraphicPath { get { - return this.path; + return base.path; } } @@ -51,89 +50,88 @@ public override bool ShouldDrawRotated { get { - return this.MatSide == this.MatBack; + return (Object)this.MatSide == (Object)this.MatBack; } } public override void Init(GraphicRequest req) { - this.data = req.graphicData; - this.path = req.path; - this.color = req.color; - this.colorTwo = req.colorTwo; - this.drawSize = req.drawSize; - Texture2D[] array = new Texture2D[3]; - array[0] = ContentFinder.Get(req.path + "_back", false); - if (array[0] == null) + base.data = req.graphicData; + base.path = req.path; + base.color = req.color; + base.colorTwo = req.colorTwo; + base.drawSize = req.drawSize; + Texture2D[] array = new Texture2D[3] { - Log.Error("Failed to find any texture while constructing " + this.ToString()); - return; - } - array[1] = ContentFinder.Get(req.path + "_side", false); - if (array[1] == null) - { - array[1] = array[0]; - } - array[2] = ContentFinder.Get(req.path + "_front", false); - if (array[2] == null) + ContentFinder.Get(req.path + "_back", false), + null, + null + }; + if ((Object)array[0] == (Object)null) { - array[2] = array[0]; + Log.Error("Failed to find any texture while constructing " + this.ToString()); } - Texture2D[] array2 = new Texture2D[3]; - if (req.shader.SupportsMaskTex()) + else { - array2[0] = ContentFinder.Get(req.path + "_backm", false); - if (array2[0] != null) + array[1] = ContentFinder.Get(req.path + "_side", false); + if ((Object)array[1] == (Object)null) + { + array[1] = array[0]; + } + array[2] = ContentFinder.Get(req.path + "_front", false); + if ((Object)array[2] == (Object)null) { - array2[1] = ContentFinder.Get(req.path + "_sidem", false); - if (array2[1] == null) + array[2] = array[0]; + } + Texture2D[] array2 = new Texture2D[3]; + if (req.shader.SupportsMaskTex()) + { + array2[0] = ContentFinder.Get(req.path + "_backm", false); + if ((Object)array2[0] != (Object)null) { - array2[1] = array2[0]; + array2[1] = ContentFinder.Get(req.path + "_sidem", false); + if ((Object)array2[1] == (Object)null) + { + array2[1] = array2[0]; + } + array2[2] = ContentFinder.Get(req.path + "_frontm", false); + if ((Object)array2[2] == (Object)null) + { + array2[2] = array2[0]; + } } - array2[2] = ContentFinder.Get(req.path + "_frontm", false); - if (array2[2] == null) + } + for (int i = 0; i < 3; i++) + { + MaterialRequest req2 = new MaterialRequest { - array2[2] = array2[0]; - } + mainTex = array[i], + shader = req.shader, + color = base.color, + colorTwo = base.colorTwo, + maskTex = array2[i] + }; + this.mats[i] = MaterialPool.MatFrom(req2); } } - for (int i = 0; i < 3; i++) - { - MaterialRequest req2 = default(MaterialRequest); - req2.mainTex = array[i]; - req2.shader = req.shader; - req2.color = this.color; - req2.colorTwo = this.colorTwo; - req2.maskTex = array2[i]; - this.mats[i] = MaterialPool.MatFrom(req2); - } } public override Graphic GetColoredVersion(Shader newShader, Color newColor, Color newColorTwo) { - return GraphicDatabase.Get(this.path, newShader, this.drawSize, newColor, newColorTwo, this.data); + return GraphicDatabase.Get(base.path, newShader, base.drawSize, newColor, newColorTwo, base.data); } public override string ToString() { - return string.Concat(new object[] - { - "Multi(initPath=", - this.path, - ", color=", - this.color, - ", colorTwo=", - this.colorTwo, - ")" - }); + return "Multi(initPath=" + base.path + ", color=" + base.color + ", colorTwo=" + base.colorTwo + ")"; } public override int GetHashCode() { int seed = 0; - seed = Gen.HashCombine(seed, this.path); - seed = Gen.HashCombineStruct(seed, this.color); - return Gen.HashCombineStruct(seed, this.colorTwo); + seed = Gen.HashCombine(seed, base.path); + seed = Gen.HashCombineStruct(seed, base.color); + return Gen.HashCombineStruct(seed, base.colorTwo); } } } diff --git a/Assembly-CSharp/Verse/Graphic_Random.cs b/Assembly-CSharp/Verse/Graphic_Random.cs index 5a2f9d55f..7a3a47fca 100644 --- a/Assembly-CSharp/Verse/Graphic_Random.cs +++ b/Assembly-CSharp/Verse/Graphic_Random.cs @@ -1,4 +1,3 @@ -using System; using UnityEngine; namespace Verse @@ -9,7 +8,7 @@ public override Material MatSingle { get { - return this.subGraphics[Rand.Range(0, this.subGraphics.Length)].MatSingle; + return base.subGraphics[Rand.Range(0, base.subGraphics.Length)].MatSingle; } } @@ -19,7 +18,7 @@ public override Graphic GetColoredVersion(Shader newShader, Color newColor, Colo { Log.ErrorOnce("Cannot use Graphic_Random.GetColoredVersion with a non-white colorTwo.", 9910251); } - return GraphicDatabase.Get(this.path, newShader, this.drawSize, newColor, Color.white, this.data); + return GraphicDatabase.Get(base.path, newShader, base.drawSize, newColor, Color.white, base.data); } public override Material MatAt(Rot4 rot, Thing thing = null) @@ -42,33 +41,18 @@ public override Material MatSingleFor(Thing thing) public override void DrawWorker(Vector3 loc, Rot4 rot, ThingDef thingDef, Thing thing) { - Graphic graphic; - if (thing != null) - { - graphic = this.SubGraphicFor(thing); - } - else - { - graphic = this.subGraphics[0]; - } + Graphic graphic = (thing == null) ? base.subGraphics[0] : this.SubGraphicFor(thing); graphic.DrawWorker(loc, rot, thingDef, thing); } public Graphic SubGraphicFor(Thing thing) { - return this.subGraphics[thing.thingIDNumber % this.subGraphics.Length]; + return base.subGraphics[thing.thingIDNumber % base.subGraphics.Length]; } public override string ToString() { - return string.Concat(new object[] - { - "Random(path=", - this.path, - ", count=", - this.subGraphics.Length, - ")" - }); + return "Random(path=" + base.path + ", count=" + base.subGraphics.Length + ")"; } } } diff --git a/Assembly-CSharp/Verse/Graphic_RandomRotated.cs b/Assembly-CSharp/Verse/Graphic_RandomRotated.cs index 069cb14c6..0e5010380 100644 --- a/Assembly-CSharp/Verse/Graphic_RandomRotated.cs +++ b/Assembly-CSharp/Verse/Graphic_RandomRotated.cs @@ -1,4 +1,3 @@ -using System; using UnityEngine; namespace Verse @@ -29,7 +28,7 @@ public override void DrawWorker(Vector3 loc, Rot4 rot, ThingDef thingDef, Thing float angle = 0f; if (thing != null) { - angle = -this.maxAngle + (float)(thing.thingIDNumber * 542) % (this.maxAngle * 2f); + angle = (float)(0.0 - this.maxAngle + (float)(thing.thingIDNumber * 542) % (this.maxAngle * 2.0)); } Material matSingle = this.subGraphic.MatSingle; Graphics.DrawMesh(mesh, loc, Quaternion.AngleAxis(angle, Vector3.up), matSingle, 0, null, 0); @@ -42,10 +41,9 @@ public override string ToString() public override Graphic GetColoredVersion(Shader newShader, Color newColor, Color newColorTwo) { - return new Graphic_RandomRotated(this.subGraphic.GetColoredVersion(newShader, newColor, newColorTwo), this.maxAngle) - { - data = this.data - }; + Graphic_RandomRotated graphic_RandomRotated = new Graphic_RandomRotated(this.subGraphic.GetColoredVersion(newShader, newColor, newColorTwo), this.maxAngle); + graphic_RandomRotated.data = base.data; + return graphic_RandomRotated; } } } diff --git a/Assembly-CSharp/Verse/Graphic_Shadow.cs b/Assembly-CSharp/Verse/Graphic_Shadow.cs index 87347fc40..027d98a04 100644 --- a/Assembly-CSharp/Verse/Graphic_Shadow.cs +++ b/Assembly-CSharp/Verse/Graphic_Shadow.cs @@ -21,8 +21,10 @@ public Graphic_Shadow(ShadowData shadowInfo) public override void DrawWorker(Vector3 loc, Rot4 rot, ThingDef thingDef, Thing thing) { - if (this.shadowMesh != null && thingDef != null && this.shadowInfo != null && (Find.VisibleMap == null || !loc.ToIntVec3().InBounds(Find.VisibleMap) || !Find.VisibleMap.roofGrid.Roofed(loc.ToIntVec3()))) + if ((UnityEngine.Object)this.shadowMesh != (UnityEngine.Object)null && thingDef != null && this.shadowInfo != null) { + if (Find.VisibleMap != null && loc.ToIntVec3().InBounds(Find.VisibleMap) && Find.VisibleMap.roofGrid.Roofed(loc.ToIntVec3())) + return; Vector3 position = loc + this.shadowInfo.offset; position.y = Altitudes.AltitudeFor(AltitudeLayer.Shadows); Graphics.DrawMesh(this.shadowMesh, position, rot.AsQuat, MatBases.SunShadowFade, 0); diff --git a/Assembly-CSharp/Verse/Graphic_Single.cs b/Assembly-CSharp/Verse/Graphic_Single.cs index 492fa3a52..b2d586998 100644 --- a/Assembly-CSharp/Verse/Graphic_Single.cs +++ b/Assembly-CSharp/Verse/Graphic_Single.cs @@ -1,4 +1,3 @@ -using System; using UnityEngine; namespace Verse @@ -45,23 +44,29 @@ public override bool ShouldDrawRotated { get { - return this.data == null || this.data.drawRotated; + if (base.data != null && !base.data.drawRotated) + { + return false; + } + return true; } } public override void Init(GraphicRequest req) { - this.data = req.graphicData; - this.path = req.path; - this.color = req.color; - this.colorTwo = req.colorTwo; - this.drawSize = req.drawSize; - MaterialRequest req2 = default(MaterialRequest); - req2.mainTex = ContentFinder.Get(req.path, true); - req2.shader = req.shader; - req2.color = this.color; - req2.colorTwo = this.colorTwo; - req2.renderQueue = req.renderQueue; + base.data = req.graphicData; + base.path = req.path; + base.color = req.color; + base.colorTwo = req.colorTwo; + base.drawSize = req.drawSize; + MaterialRequest req2 = new MaterialRequest + { + mainTex = ContentFinder.Get(req.path, true), + shader = req.shader, + color = base.color, + colorTwo = base.colorTwo, + renderQueue = req.renderQueue + }; if (req.shader.SupportsMaskTex()) { req2.maskTex = ContentFinder.Get(req.path + Graphic_Single.MaskSuffix, false); @@ -71,7 +76,7 @@ public override void Init(GraphicRequest req) public override Graphic GetColoredVersion(Shader newShader, Color newColor, Color newColorTwo) { - return GraphicDatabase.Get(this.path, newShader, this.drawSize, newColor, newColorTwo, this.data); + return GraphicDatabase.Get(base.path, newShader, base.drawSize, newColor, newColorTwo, base.data); } public override Material MatAt(Rot4 rot, Thing thing = null) @@ -81,16 +86,7 @@ public override Material MatAt(Rot4 rot, Thing thing = null) public override string ToString() { - return string.Concat(new object[] - { - "Single(path=", - this.path, - ", color=", - this.color, - ", colorTwo=", - this.colorTwo, - ")" - }); + return "Single(path=" + base.path + ", color=" + base.color + ", colorTwo=" + base.colorTwo + ")"; } } } diff --git a/Assembly-CSharp/Verse/Graphic_StackCount.cs b/Assembly-CSharp/Verse/Graphic_StackCount.cs index 3b3b80751..ed583436f 100644 --- a/Assembly-CSharp/Verse/Graphic_StackCount.cs +++ b/Assembly-CSharp/Verse/Graphic_StackCount.cs @@ -1,4 +1,3 @@ -using System; using UnityEngine; namespace Verse @@ -9,7 +8,7 @@ public override Material MatSingle { get { - return this.subGraphics[this.subGraphics.Length - 1].MatSingle; + return base.subGraphics[base.subGraphics.Length - 1].MatSingle; } } @@ -19,7 +18,7 @@ public override Graphic GetColoredVersion(Shader newShader, Color newColor, Colo { Log.ErrorOnce("Cannot use this GetColoredVersion with a non-white colorTwo.", 908251); } - return GraphicDatabase.Get(this.path, newShader, this.drawSize, newColor, newColorTwo, this.data); + return GraphicDatabase.Get(base.path, newShader, base.drawSize, newColor, newColorTwo, base.data); } public override Material MatAt(Rot4 rot, Thing thing = null) @@ -47,66 +46,57 @@ public Graphic SubGraphicFor(Thing thing) public override void DrawWorker(Vector3 loc, Rot4 rot, ThingDef thingDef, Thing thing) { - Graphic graphic; - if (thing != null) - { - graphic = this.SubGraphicFor(thing); - } - else - { - graphic = this.subGraphics[0]; - } + Graphic graphic = (thing == null) ? base.subGraphics[0] : this.SubGraphicFor(thing); graphic.DrawWorker(loc, rot, thingDef, thing); } public Graphic SubGraphicForStackCount(int stackCount, ThingDef def) { - switch (this.subGraphics.Length) + switch (base.subGraphics.Length) { case 1: - return this.subGraphics[0]; + { + return base.subGraphics[0]; + } case 2: + { if (stackCount == 1) { - return this.subGraphics[0]; + return base.subGraphics[0]; } - return this.subGraphics[1]; + return base.subGraphics[1]; + } case 3: + { if (stackCount == 1) { - return this.subGraphics[0]; + return base.subGraphics[0]; } if (stackCount == def.stackLimit) { - return this.subGraphics[2]; + return base.subGraphics[2]; } - return this.subGraphics[1]; + return base.subGraphics[1]; + } default: { if (stackCount == 1) { - return this.subGraphics[0]; + return base.subGraphics[0]; } if (stackCount == def.stackLimit) { - return this.subGraphics[this.subGraphics.Length - 1]; + return base.subGraphics[base.subGraphics.Length - 1]; } - int num = 1 + Mathf.RoundToInt(Mathf.InverseLerp(2f, (float)(def.stackLimit - 1), (float)(this.subGraphics.Length - 2))); - return this.subGraphics[num]; + int num = 1 + Mathf.RoundToInt(Mathf.InverseLerp(2f, (float)(def.stackLimit - 1), (float)(base.subGraphics.Length - 2))); + return base.subGraphics[num]; } } } public override string ToString() { - return string.Concat(new object[] - { - "StackCount(path=", - this.path, - ", count=", - this.subGraphics.Length, - ")" - }); + return "StackCount(path=" + base.path + ", count=" + base.subGraphics.Length + ")"; } } } diff --git a/Assembly-CSharp/Verse/Graphic_Terrain.cs b/Assembly-CSharp/Verse/Graphic_Terrain.cs index 249f190a8..f8b4838cc 100644 --- a/Assembly-CSharp/Verse/Graphic_Terrain.cs +++ b/Assembly-CSharp/Verse/Graphic_Terrain.cs @@ -1,5 +1,3 @@ -using System; - namespace Verse { public class Graphic_Terrain : Graphic_Single @@ -11,16 +9,7 @@ public override void Init(GraphicRequest req) public override string ToString() { - return string.Concat(new object[] - { - "Terrain(path=", - this.path, - ", shader=", - base.Shader, - ", color=", - this.color, - ")" - }); + return "Terrain(path=" + base.path + ", shader=" + base.Shader + ", color=" + base.color + ")"; } } } diff --git a/Assembly-CSharp/Verse/GridLayout.cs b/Assembly-CSharp/Verse/GridLayout.cs index 1f83e6376..815e9322d 100644 --- a/Assembly-CSharp/Verse/GridLayout.cs +++ b/Assembly-CSharp/Verse/GridLayout.cs @@ -1,4 +1,3 @@ -using System; using UnityEngine; namespace Verse @@ -27,8 +26,8 @@ public GridLayout(Rect container, int cols = 1, int rows = 1, float outerPadding this.cols = cols; this.innerPadding = innerPadding; this.outerPadding = outerPadding; - float num = container.width - outerPadding * 2f - (float)(cols - 1) * innerPadding; - float num2 = container.height - outerPadding * 2f - (float)(rows - 1) * innerPadding; + float num = (float)(container.width - outerPadding * 2.0 - (float)(cols - 1) * innerPadding); + float num2 = (float)(container.height - outerPadding * 2.0 - (float)(rows - 1) * innerPadding); this.colWidth = num / (float)cols; this.rowHeight = num2 / (float)rows; this.colStride = this.colWidth + innerPadding; @@ -44,7 +43,7 @@ public GridLayout(float colWidth, float rowHeight, int cols, int rows, float out this.outerPadding = outerPadding; this.colStride = colWidth + innerPadding; this.rowStride = rowHeight + innerPadding; - this.container = new Rect(0f, 0f, outerPadding * 2f + colWidth * (float)cols + innerPadding * (float)cols - 1f, outerPadding * 2f + rowHeight * (float)rows + innerPadding * (float)rows - 1f); + this.container = new Rect(0f, 0f, (float)(outerPadding * 2.0 + colWidth * (float)cols + innerPadding * (float)cols - 1.0), (float)(outerPadding * 2.0 + rowHeight * (float)rows + innerPadding * (float)rows - 1.0)); } public Rect GetCellRectByIndex(int index, int colspan = 1, int rowspan = 1) diff --git a/Assembly-CSharp/Verse/GridSaveUtility.cs b/Assembly-CSharp/Verse/GridSaveUtility.cs index 455b19c55..6bf0c542a 100644 --- a/Assembly-CSharp/Verse/GridSaveUtility.cs +++ b/Assembly-CSharp/Verse/GridSaveUtility.cs @@ -1,6 +1,5 @@ using System; using System.Collections.Generic; -using System.Diagnostics; namespace Verse { @@ -22,37 +21,56 @@ public static string CompressedStringForShortGrid(Func shortGet while (true) { ushort num2 = shortGetter(arg); - byte b = (byte)(num2 % 256); - byte b2 = (byte)(num2 / 256); + byte b = (byte)((int)num2 % 256); + byte b2 = (byte)((int)num2 / 256); array[num] = b; array[num + 1] = b2; num += 2; arg.x++; - if (arg.x >= map.Size.x) + int x = arg.x; + IntVec3 size = map.Size; + if (x >= size.x) { arg.x = 0; arg.z++; - if (arg.z >= map.Size.z) - { + int z = arg.z; + IntVec3 size2 = map.Size; + if (z >= size2.z) break; - } } } string str = Convert.ToBase64String(array); return ArrayExposeUtility.AddLineBreaksToLongString(str); } - [DebuggerHidden] - public static IEnumerable LoadedUShortGrid(string compressedString, Map map) + public static IEnumerable LoadedUShortGrid(string compressedString, Map map) { - GridSaveUtility.c__Iterator20B c__Iterator20B = new GridSaveUtility.c__Iterator20B(); - c__Iterator20B.compressedString = compressedString; - c__Iterator20B.map = map; - c__Iterator20B.<$>compressedString = compressedString; - c__Iterator20B.<$>map = map; - GridSaveUtility.c__Iterator20B expr_23 = c__Iterator20B; - expr_23.$PC = -2; - return expr_23; + compressedString = ArrayExposeUtility.RemoveLineBreaks(compressedString); + byte[] byteGrid = Convert.FromBase64String(compressedString); + IntVec3 curSq = new IntVec3(0, 0, 0); + int byteInd = 0; + while (true) + { + LoadedGridShort loadedElement = new LoadedGridShort + { + cell = curSq, + val = (ushort)(byteGrid[byteInd] + byteGrid[byteInd + 1] * 256) + }; + byteInd += 2; + yield return loadedElement; + curSq.x++; + int x = curSq.x; + IntVec3 size = map.Size; + if (x >= size.x) + { + curSq.x = 0; + curSq.z++; + int z = curSq.z; + IntVec3 size2 = map.Size; + if (z >= size2.z) + break; + } + } } } } diff --git a/Assembly-CSharp/Verse/GridsUtility.cs b/Assembly-CSharp/Verse/GridsUtility.cs index 2f62ee92e..44c47b026 100644 --- a/Assembly-CSharp/Verse/GridsUtility.cs +++ b/Assembly-CSharp/Verse/GridsUtility.cs @@ -1,5 +1,4 @@ using RimWorld; -using System; using System.Collections.Generic; using System.Linq; @@ -89,12 +88,15 @@ public static Plant GetPlant(this IntVec3 c, Map map) public static Thing GetRoofHolderOrImpassable(this IntVec3 c, Map map) { List thingList = c.GetThingList(map); - for (int i = 0; i < thingList.Count; i++) + int num = 0; + while (num < thingList.Count) { - if (thingList[i].def.holdsRoof || thingList[i].def.passability == Traversability.Impassable) + if (!thingList[num].def.holdsRoof && thingList[num].def.passability != Traversability.Impassable) { - return thingList[i]; + num++; + continue; } + return thingList[num]; } return null; } @@ -247,7 +249,7 @@ public static bool UsesOutdoorTemperature(this IntVec3 c, Map map) Building edifice = c.GetEdifice(map); if (edifice != null) { - IntVec3[] array = GenAdj.CellsAdjacent8Way(edifice).ToArray(); + IntVec3[] array = GenAdj.CellsAdjacent8Way(edifice).ToArray(); for (int i = 0; i < array.Length; i++) { if (array[i].InBounds(map)) diff --git a/Assembly-CSharp/Verse/HealthTunings.cs b/Assembly-CSharp/Verse/HealthTunings.cs index 4247fb94f..d0698f6aa 100644 --- a/Assembly-CSharp/Verse/HealthTunings.cs +++ b/Assembly-CSharp/Verse/HealthTunings.cs @@ -1,5 +1,3 @@ -using System; - namespace Verse { public class HealthTunings diff --git a/Assembly-CSharp/Verse/HealthUtility.cs b/Assembly-CSharp/Verse/HealthUtility.cs index 54019e158..cc83b522f 100644 --- a/Assembly-CSharp/Verse/HealthUtility.cs +++ b/Assembly-CSharp/Verse/HealthUtility.cs @@ -33,26 +33,22 @@ public static void Reset() public static void HealInjuryRandom(Pawn pawn, float amount) { BodyPartRecord part; - if (!pawn.health.hediffSet.GetInjuredParts().TryRandomElement(out part)) + if (pawn.health.hediffSet.GetInjuredParts().TryRandomElement(out part)) { - return; - } - Hediff_Injury hediff_Injury = null; - foreach (Hediff_Injury current in from x in pawn.health.hediffSet.GetHediffs() - where x.Part == part - select x) - { - if (!current.IsOld()) + Hediff_Injury hediff_Injury = null; + foreach (Hediff_Injury item in from x in pawn.health.hediffSet.GetHediffs() + where x.Part == part + select x) { - if (hediff_Injury == null || current.Severity > hediff_Injury.Severity) + if (!item.IsOld() && (hediff_Injury == null || item.Severity > hediff_Injury.Severity)) { - hediff_Injury = current; + hediff_Injury = item; } } - } - if (hediff_Injury != null) - { - hediff_Injury.Heal(amount); + if (hediff_Injury != null) + { + hediff_Injury.Heal(amount); + } } } @@ -78,19 +74,16 @@ public static string GetGeneralConditionLabel(Pawn pawn, bool shortVersion = fal for (int i = 0; i < pawn.health.hediffSet.hediffs.Count; i++) { Hediff_Injury hediff_Injury = pawn.health.hediffSet.hediffs[i] as Hediff_Injury; - if (hediff_Injury != null) + if (hediff_Injury != null && !hediff_Injury.IsOld()) { - if (!hediff_Injury.IsOld()) - { - flag = true; - } + flag = true; } } if (flag) { return "Injured".Translate(); } - if (pawn.health.hediffSet.PainTotal > 0.3f) + if (pawn.health.hediffSet.PainTotal > 0.30000001192092896) { return "InPain".Translate(); } @@ -102,19 +95,22 @@ public static Pair GetPartConditionLabel(Pawn pawn, BodyPartRecor float partHealth = pawn.health.hediffSet.GetPartHealth(part); float maxHealth = part.def.GetMaxHealth(pawn); float num = partHealth / maxHealth; - string first = string.Empty; - Color second = Color.white; - if (partHealth <= 0f) + string empty = string.Empty; + Color white = Color.white; + if (partHealth <= 0.0) { Hediff_MissingPart hediff_MissingPart = null; List missingPartsCommonAncestors = pawn.health.hediffSet.GetMissingPartsCommonAncestors(); - for (int i = 0; i < missingPartsCommonAncestors.Count; i++) + int num2 = 0; + while (num2 < missingPartsCommonAncestors.Count) { - if (missingPartsCommonAncestors[i].Part == part) + if (missingPartsCommonAncestors[num2].Part != part) { - hediff_MissingPart = missingPartsCommonAncestors[i]; - break; + num2++; + continue; } + hediff_MissingPart = missingPartsCommonAncestors[num2]; + break; } if (hediff_MissingPart == null) { @@ -124,36 +120,36 @@ public static Pair GetPartConditionLabel(Pawn pawn, BodyPartRecor fresh = true; } bool solid = part.def.IsSolid(part, pawn.health.hediffSet.hediffs); - first = HealthUtility.GetGeneralDestroyedPartLabel(part, fresh, solid); - second = Color.gray; + empty = HealthUtility.GetGeneralDestroyedPartLabel(part, fresh, solid); + white = Color.gray; } else { - first = hediff_MissingPart.LabelCap; - second = hediff_MissingPart.LabelColor; + empty = hediff_MissingPart.LabelCap; + white = hediff_MissingPart.LabelColor; } } - else if (num < 0.4f) + else if (num < 0.40000000596046448) { - first = "SeriouslyImpaired".Translate(); - second = HealthUtility.DarkRedColor; + empty = "SeriouslyImpaired".Translate(); + white = HealthUtility.DarkRedColor; } - else if (num < 0.7f) + else if (num < 0.699999988079071) { - first = "Impaired".Translate(); - second = HealthUtility.ImpairedColor; + empty = "Impaired".Translate(); + white = HealthUtility.ImpairedColor; } - else if (num < 0.999f) + else if (num < 0.99900001287460327) { - first = "SlightlyImpaired".Translate(); - second = HealthUtility.SlightlyImpairedColor; + empty = "SlightlyImpaired".Translate(); + white = HealthUtility.SlightlyImpairedColor; } else { - first = "GoodCondition".Translate(); - second = HealthUtility.GoodConditionColor; + empty = "GoodCondition".Translate(); + white = HealthUtility.GoodConditionColor; } - return new Pair(first, second); + return new Pair(empty, white); } public static string GetGeneralDestroyedPartLabel(BodyPartRecord part, bool fresh, bool solid) @@ -197,51 +193,44 @@ public static void GiveInjuriesOperationFailureRidiculous(Pawn p) private static void GiveRandomSurgeryInjuries(Pawn p, int totalDamage, BodyPartRecord operatedPart) { - IEnumerable source; - if (operatedPart == null) - { - source = p.health.hediffSet.GetNotMissingParts(BodyPartHeight.Undefined, BodyPartDepth.Undefined); - } - else - { - source = from pa in p.health.hediffSet.GetNotMissingParts(BodyPartHeight.Undefined, BodyPartDepth.Undefined) - where pa == operatedPart || pa.parent == operatedPart || (operatedPart != null && operatedPart.parent == pa) - select pa; - } + IEnumerable source = (operatedPart != null) ? (from pa in p.health.hediffSet.GetNotMissingParts(BodyPartHeight.Undefined, BodyPartDepth.Undefined) + where pa == operatedPart || pa.parent == operatedPart || (operatedPart != null && operatedPart.parent == pa) + select pa) : p.health.hediffSet.GetNotMissingParts(BodyPartHeight.Undefined, BodyPartDepth.Undefined); source = from x in source - where HealthUtility.GetMinHealthOfPartsWeWantToAvoidDestroying(x, p) >= 2f + where HealthUtility.GetMinHealthOfPartsWeWantToAvoidDestroying(x, p) >= 2.0 select x; BodyPartRecord brain = p.health.hediffSet.GetBrain(); if (brain != null) { float maxBrainHealth = brain.def.GetMaxHealth(p); source = from x in source - where x != brain || p.health.hediffSet.GetPartHealth(x) >= maxBrainHealth * 0.5f + 1f + where x != brain || p.health.hediffSet.GetPartHealth(x) >= maxBrainHealth * 0.5 + 1.0 select x; } - while (totalDamage > 0 && source.Any()) + while (totalDamage > 0 && source.Any()) { - BodyPartRecord bodyPartRecord = source.RandomElementByWeight((BodyPartRecord x) => x.coverageAbs); + BodyPartRecord bodyPartRecord = source.RandomElementByWeight((Func)((BodyPartRecord x) => x.coverageAbs)); float partHealth = p.health.hediffSet.GetPartHealth(bodyPartRecord); int num = Mathf.Max(3, GenMath.RoundRandom(partHealth * Rand.Range(0.5f, 1f))); float minHealthOfPartsWeWantToAvoidDestroying = HealthUtility.GetMinHealthOfPartsWeWantToAvoidDestroying(bodyPartRecord, p); - if (minHealthOfPartsWeWantToAvoidDestroying - (float)num < 1f) + if (minHealthOfPartsWeWantToAvoidDestroying - (float)num < 1.0) { - num = Mathf.RoundToInt(minHealthOfPartsWeWantToAvoidDestroying - 1f); + num = Mathf.RoundToInt((float)(minHealthOfPartsWeWantToAvoidDestroying - 1.0)); } - if (bodyPartRecord == brain && partHealth - (float)num < brain.def.GetMaxHealth(p) * 0.5f) + if (bodyPartRecord == brain && partHealth - (float)num < brain.def.GetMaxHealth(p) * 0.5) { - num = Mathf.Max(Mathf.RoundToInt(partHealth - brain.def.GetMaxHealth(p) * 0.5f), 1); + num = Mathf.Max(Mathf.RoundToInt((float)(partHealth - brain.def.GetMaxHealth(p) * 0.5)), 1); } - if (num <= 0) + if (num > 0) { - break; + DamageDef def = Rand.Element(DamageDefOf.Cut, DamageDefOf.Scratch, DamageDefOf.Stab, DamageDefOf.Crush); + Pawn obj = p; + BodyPartRecord forceHitPart = bodyPartRecord; + obj.TakeDamage(new DamageInfo(def, num, -1f, null, forceHitPart, null, DamageInfo.SourceCategory.ThingOrUnknown)); + totalDamage -= num; + continue; } - DamageDef def = Rand.Element(DamageDefOf.Cut, DamageDefOf.Scratch, DamageDefOf.Stab, DamageDefOf.Crush); - Thing arg_220_0 = p; - BodyPartRecord forceHitPart = bodyPartRecord; - arg_220_0.TakeDamage(new DamageInfo(def, num, -1f, null, forceHitPart, null, DamageInfo.SourceCategory.ThingOrUnknown)); - totalDamage -= num; + break; } } @@ -265,7 +254,7 @@ private static bool ShouldRandomSurgeryInjuriesAvoidDestroying(BodyPartRecord pa { return true; } - if (part.def.tags.Any((string x) => HealthUtility.vitalPawnCapacityTags.Contains(x))) + if (part.def.tags.Any((Predicate)((string x) => HealthUtility.vitalPawnCapacityTags.Contains(x)))) { return true; } @@ -281,70 +270,53 @@ private static bool ShouldRandomSurgeryInjuriesAvoidDestroying(BodyPartRecord pa public static void DamageUntilDowned(Pawn p) { - if (p.health.Downed) - { - return; - } - HediffSet hediffSet = p.health.hediffSet; - p.health.forceIncap = true; - IEnumerable source = from x in HealthUtility.HittablePartsViolence(hediffSet) - where !p.health.hediffSet.hediffs.Any((Hediff y) => y.Part == x && y.CurStage != null && y.CurStage.partEfficiencyOffset < 0f) - select x; - int num = 0; - while (num < 300 && !p.Downed && source.Any()) + if (!p.health.Downed) { - num++; - BodyPartRecord bodyPartRecord = source.RandomElementByWeight((BodyPartRecord x) => x.coverageAbs); - int num2 = Mathf.RoundToInt(hediffSet.GetPartHealth(bodyPartRecord)) - 3; - if (num2 >= 8) + HediffSet hediffSet = p.health.hediffSet; + p.health.forceIncap = true; + IEnumerable source = from x in HealthUtility.HittablePartsViolence(hediffSet) + where !p.health.hediffSet.hediffs.Any((Predicate)((Hediff y) => y.Part == x && y.CurStage != null && y.CurStage.partEfficiencyOffset < 0.0)) + select x; + int num = 0; + while (num < 300 && !p.Downed && source.Any()) { - DamageDef def; - if (bodyPartRecord.depth == BodyPartDepth.Outside) + num++; + BodyPartRecord bodyPartRecord = source.RandomElementByWeight((Func)((BodyPartRecord x) => x.coverageAbs)); + int num2 = Mathf.RoundToInt(hediffSet.GetPartHealth(bodyPartRecord)) - 3; + if (num2 >= 8) { - def = HealthUtility.RandomViolenceDamageType(); + DamageDef def = (bodyPartRecord.depth != BodyPartDepth.Outside) ? DamageDefOf.Blunt : HealthUtility.RandomViolenceDamageType(); + int amount = Rand.RangeInclusive(Mathf.RoundToInt((float)((float)num2 * 0.64999997615814209)), num2); + BodyPartRecord forceHitPart = bodyPartRecord; + DamageInfo dinfo = new DamageInfo(def, amount, -1f, null, forceHitPart, null, DamageInfo.SourceCategory.ThingOrUnknown); + dinfo.SetAllowDamagePropagation(false); + p.TakeDamage(dinfo); } - else - { - def = DamageDefOf.Blunt; - } - int amount = Rand.RangeInclusive(Mathf.RoundToInt((float)num2 * 0.65f), num2); - BodyPartRecord forceHitPart = bodyPartRecord; - DamageInfo dinfo = new DamageInfo(def, amount, -1f, null, forceHitPart, null, DamageInfo.SourceCategory.ThingOrUnknown); - dinfo.SetAllowDamagePropagation(false); - p.TakeDamage(dinfo); } - } - if (p.Dead) - { - StringBuilder stringBuilder = new StringBuilder(); - stringBuilder.AppendLine(p + " died during GiveInjuriesToForceDowned"); - for (int i = 0; i < p.health.hediffSet.hediffs.Count; i++) + if (p.Dead) { - stringBuilder.AppendLine(" -" + p.health.hediffSet.hediffs[i].ToString()); + StringBuilder stringBuilder = new StringBuilder(); + stringBuilder.AppendLine(p + " died during GiveInjuriesToForceDowned"); + for (int i = 0; i < p.health.hediffSet.hediffs.Count; i++) + { + stringBuilder.AppendLine(" -" + p.health.hediffSet.hediffs[i].ToString()); + } + Log.Error(stringBuilder.ToString()); } - Log.Error(stringBuilder.ToString()); + p.health.forceIncap = false; } - p.health.forceIncap = false; } public static void DamageUntilDead(Pawn p) { HediffSet hediffSet = p.health.hediffSet; int num = 0; - while (!p.Dead && num < 200 && HealthUtility.HittablePartsViolence(hediffSet).Any()) + while (!p.Dead && num < 200 && HealthUtility.HittablePartsViolence(hediffSet).Any()) { num++; - BodyPartRecord bodyPartRecord = HealthUtility.HittablePartsViolence(hediffSet).RandomElementByWeight((BodyPartRecord x) => x.coverageAbs); + BodyPartRecord bodyPartRecord = HealthUtility.HittablePartsViolence(hediffSet).RandomElementByWeight((Func)((BodyPartRecord x) => x.coverageAbs)); int amount = Rand.RangeInclusive(8, 25); - DamageDef def; - if (bodyPartRecord.depth == BodyPartDepth.Outside) - { - def = HealthUtility.RandomViolenceDamageType(); - } - else - { - def = DamageDefOf.Blunt; - } + DamageDef def = (bodyPartRecord.depth != BodyPartDepth.Outside) ? DamageDefOf.Blunt : HealthUtility.RandomViolenceDamageType(); BodyPartRecord forceHitPart = bodyPartRecord; DamageInfo dinfo = new DamageInfo(def, amount, -1f, null, forceHitPart, null, DamageInfo.SourceCategory.ThingOrUnknown); p.TakeDamage(dinfo); @@ -360,18 +332,30 @@ public static DamageDef RandomViolenceDamageType() switch (Rand.RangeInclusive(0, 4)) { case 0: + { return DamageDefOf.Bullet; + } case 1: + { return DamageDefOf.Blunt; + } case 2: + { return DamageDefOf.Stab; + } case 3: + { return DamageDefOf.Scratch; + } case 4: + { return DamageDefOf.Cut; + } default: + { return null; } + } } public static HediffDef GetHediffDefFromDamage(DamageDef dam, Pawn pawn, BodyPartRecord part) @@ -395,33 +379,32 @@ public static bool TryAnesthetize(Pawn pawn) return false; } pawn.health.forceIncap = true; - pawn.health.AddHediff(HediffDefOf.Anesthetic, null, null); + pawn.health.AddHediff(HediffDefOf.Anesthetic, null, default(DamageInfo?)); pawn.health.forceIncap = false; return true; } public static void AdjustSeverity(Pawn pawn, HediffDef hdDef, float sevOffset) { - if (sevOffset == 0f) - { - return; - } - Hediff hediff = pawn.health.hediffSet.GetFirstHediffOfDef(hdDef, false); - if (hediff != null) - { - hediff.Severity += sevOffset; - } - else if (sevOffset > 0f) + if (sevOffset != 0.0) { - hediff = HediffMaker.MakeHediff(hdDef, pawn, null); - hediff.Severity = sevOffset; - pawn.health.AddHediff(hediff, null, null); + Hediff firstHediffOfDef = pawn.health.hediffSet.GetFirstHediffOfDef(hdDef, false); + if (firstHediffOfDef != null) + { + firstHediffOfDef.Severity += sevOffset; + } + else if (sevOffset > 0.0) + { + firstHediffOfDef = HediffMaker.MakeHediff(hdDef, pawn, null); + firstHediffOfDef.Severity = sevOffset; + pawn.health.AddHediff(firstHediffOfDef, null, default(DamageInfo?)); + } } } public static BodyPartRemovalIntent PartRemovalIntent(Pawn pawn, BodyPartRecord part) { - if (pawn.health.hediffSet.hediffs.Any((Hediff d) => d.Visible && d.Part == part && d.def.isBad)) + if (pawn.health.hediffSet.hediffs.Any((Predicate)((Hediff d) => d.Visible && d.Part == part && d.def.isBad))) { return BodyPartRemovalIntent.Amputate; } @@ -435,7 +418,7 @@ public static int TicksUntilDeathDueToBloodLoss(Pawn pawn) { return 2147483647; } - return (int)((1f - firstHediffOfDef.Severity) / pawn.health.hediffSet.BleedRateTotal * 60000f); + return (int)((1.0 - firstHediffOfDef.Severity) / pawn.health.hediffSet.BleedRateTotal * 60000.0); } } } diff --git a/Assembly-CSharp/Verse/Hediff.cs b/Assembly-CSharp/Verse/Hediff.cs index da91213df..995b289c9 100644 --- a/Assembly-CSharp/Verse/Hediff.cs +++ b/Assembly-CSharp/Verse/Hediff.cs @@ -1,6 +1,5 @@ using RimWorld; using RimWorld.Planet; -using System; using System.Collections.Generic; using System.Text; using UnityEngine; @@ -79,7 +78,7 @@ public virtual string SeverityLabel { get { - return (this.def.lethalSeverity > 0f) ? (this.Severity / this.def.lethalSeverity).ToStringPercent() : null; + return (!(this.def.lethalSeverity <= 0.0)) ? (this.Severity / this.def.lethalSeverity).ToStringPercent() : null; } } @@ -96,11 +95,11 @@ public virtual string TipStringExtra get { StringBuilder stringBuilder = new StringBuilder(); - foreach (StatDrawEntry current in HediffStatsUtility.SpecialDisplayStats(this.CurStage, this)) + foreach (StatDrawEntry item in HediffStatsUtility.SpecialDisplayStats(this.CurStage, this)) { - if (current.ShouldDisplay) + if (item.ShouldDisplay) { - stringBuilder.AppendLine(current.LabelCap + ": " + current.ValueString); + stringBuilder.AppendLine(item.LabelCap + ": " + item.ValueString); } } return stringBuilder.ToString(); @@ -111,7 +110,7 @@ public virtual HediffStage CurStage { get { - return (!this.def.stages.NullOrEmpty()) ? this.def.stages[this.CurStageIndex] : null; + return (!this.def.stages.NullOrEmpty()) ? this.def.stages[this.CurStageIndex] : null; } } @@ -119,7 +118,7 @@ public virtual bool ShouldRemove { get { - return this.Severity <= 0f; + return this.Severity <= 0.0; } } @@ -143,7 +142,7 @@ public bool Bleeding { get { - return this.BleedRate > 1E-05f; + return this.BleedRate > 9.9999997473787516E-06; } } @@ -151,7 +150,7 @@ public virtual float PainOffset { get { - return (this.CurStage != null && !this.causesNoPain) ? this.CurStage.painOffset : 0f; + return (float)((this.CurStage != null && !this.causesNoPain) ? this.CurStage.painOffset : 0.0); } } @@ -159,7 +158,7 @@ public virtual float PainFactor { get { - return (this.CurStage != null) ? this.CurStage.painFactor : 1f; + return (float)((this.CurStage != null) ? this.CurStage.painFactor : 1.0); } } @@ -183,19 +182,19 @@ public virtual float TendPriority { get { - float num = 0f; + float a = 0f; HediffStage curStage = this.CurStage; if (curStage != null && curStage.lifeThreatening) { - num = Mathf.Max(num, 1f); + a = Mathf.Max(a, 1f); } - num = Mathf.Max(num, this.BleedRate * 1.5f); + a = Mathf.Max(a, (float)(this.BleedRate * 1.5)); HediffComp_TendDuration hediffComp_TendDuration = this.TryGetComp(); - if (hediffComp_TendDuration != null && hediffComp_TendDuration.TProps.severityPerDayTended < 0f) + if (hediffComp_TendDuration != null && hediffComp_TendDuration.TProps.severityPerDayTended < 0.0) { - num = Mathf.Max(num, 0.025f); + a = Mathf.Max(a, 0.025f); } - return num; + return a; } } @@ -217,11 +216,11 @@ public virtual int CurStageIndex } List stages = this.def.stages; float severity = this.Severity; - for (int i = stages.Count - 1; i >= 0; i--) + for (int num = stages.Count - 1; num >= 0; num--) { - if (severity >= stages[i].minSeverity) + if (severity >= stages[num].minSeverity) { - return i; + return num; } } return 0; @@ -237,20 +236,19 @@ public virtual float Severity set { bool flag = false; - if (this.def.lethalSeverity > 0f && value >= this.def.lethalSeverity) + if (this.def.lethalSeverity > 0.0 && value >= this.def.lethalSeverity) { value = this.def.lethalSeverity; flag = true; } int curStageIndex = this.CurStageIndex; this.severityInt = Mathf.Clamp(value, this.def.minSeverity, this.def.maxSeverity); - if (this.CurStageIndex != curStageIndex || flag) + if (this.CurStageIndex == curStageIndex && !flag) + return; + this.pawn.health.Notify_HediffChanged(this); + if (!this.pawn.Dead && this.pawn.needs.mood != null) { - this.pawn.health.Notify_HediffChanged(this); - if (!this.pawn.Dead && this.pawn.needs.mood != null) - { - this.pawn.needs.mood.thoughts.situational.Notify_SituationalThoughtsDirty(); - } + this.pawn.needs.mood.thoughts.situational.Notify_SituationalThoughtsDirty(); } } } @@ -270,17 +268,19 @@ public BodyPartRecord Part if (this.pawn == null) { Log.Error("Hediff: Cannot set Part without setting pawn first."); - return; - } - if (value != null) - { - this.partIndex = this.pawn.RaceProps.body.GetIndexOfPart(value); } else { - this.partIndex = -1; + if (value != null) + { + this.partIndex = this.pawn.RaceProps.body.GetIndexOfPart(value); + } + else + { + this.partIndex = -1; + } + this.cachedPart = value; } - this.cachedPart = value; } } @@ -288,7 +288,11 @@ public virtual bool TendableNow { get { - return this.def.tendable && this.Severity > 0f && this.Visible && !this.FullyImmune() && !this.IsTended() && !this.IsOld(); + if (this.def.tendable && !(this.Severity <= 0.0) && this.Visible && !this.FullyImmune() && !this.IsTended() && !this.IsOld()) + { + return true; + } + return false; } } @@ -336,41 +340,37 @@ public virtual void Tick() MentalStateGiver mentalStateGiver = curStage.mentalStateGivers[k]; if (Rand.MTBEventOccurs(mentalStateGiver.mtbDays, 60000f, 60f)) { - this.pawn.mindState.mentalStateHandler.TryStartMentalState(mentalStateGiver.mentalState, null, false, false, null); + this.pawn.mindState.mentalStateHandler.TryStartMentalState(mentalStateGiver.mentalState, (string)null, false, false, null); } } } - if (curStage.vomitMtbDays > 0f && this.pawn.IsHashIntervalTick(600) && Rand.MTBEventOccurs(curStage.vomitMtbDays, 60000f, 600f) && this.pawn.Spawned && this.pawn.Awake()) + if (curStage.vomitMtbDays > 0.0 && this.pawn.IsHashIntervalTick(600) && Rand.MTBEventOccurs(curStage.vomitMtbDays, 60000f, 600f) && this.pawn.Spawned && this.pawn.Awake()) { - this.pawn.jobs.StartJob(new Job(JobDefOf.Vomit), JobCondition.InterruptForced, null, true, true, null, null); + this.pawn.jobs.StartJob(new Job(JobDefOf.Vomit), JobCondition.InterruptForced, null, true, true, null, default(JobTag?)); } - Thought_Memory th; - if (curStage.forgetMemoryThoughtMtbDays > 0f && this.pawn.needs.mood != null && this.pawn.IsHashIntervalTick(400) && Rand.MTBEventOccurs(curStage.forgetMemoryThoughtMtbDays, 60000f, 400f) && this.pawn.needs.mood.thoughts.memories.Memories.TryRandomElement(out th)) + Thought_Memory th = default(Thought_Memory); + if (curStage.forgetMemoryThoughtMtbDays > 0.0 && this.pawn.needs.mood != null && this.pawn.IsHashIntervalTick(400) && Rand.MTBEventOccurs(curStage.forgetMemoryThoughtMtbDays, 60000f, 400f) && ((IEnumerable)this.pawn.needs.mood.thoughts.memories.Memories).TryRandomElement(out th)) { this.pawn.needs.mood.thoughts.memories.RemoveMemory(th); } if (!this.recordedTale && curStage.tale != null) { - TaleRecorder.RecordTale(curStage.tale, new object[] - { - this.pawn - }); + TaleRecorder.RecordTale(curStage.tale, this.pawn); this.recordedTale = true; } if (curStage.destroyPart && this.Part != null && this.Part != this.pawn.RaceProps.body.corePart) { - this.pawn.health.AddHediff(HediffDefOf.MissingBodyPart, this.Part, null); + this.pawn.health.AddHediff(HediffDefOf.MissingBodyPart, this.Part, default(DamageInfo?)); } - if (curStage.deathMtbDays > 0f && this.pawn.IsHashIntervalTick(200) && Rand.MTBEventOccurs(curStage.deathMtbDays, 60000f, 200f)) + if (curStage.deathMtbDays > 0.0 && this.pawn.IsHashIntervalTick(200) && Rand.MTBEventOccurs(curStage.deathMtbDays, 60000f, 200f)) { bool flag = PawnUtility.ShouldSendNotificationAbout(this.pawn); Caravan caravan = this.pawn.GetCaravan(); - this.pawn.Kill(null); + this.pawn.Kill(default(DamageInfo?)); if (flag) { - this.pawn.health.NotifyPlayerOfKilled(null, this, caravan); + this.pawn.health.NotifyPlayerOfKilled(default(DamageInfo?), this, caravan); } - return; } } } @@ -403,12 +403,11 @@ public virtual void Tended(float quality, int batchPosition = 0) public virtual void Heal(float amount) { - if (amount <= 0f) + if (!(amount <= 0.0)) { - return; + this.Severity -= amount; + this.pawn.health.Notify_HediffChanged(this); } - this.Severity -= amount; - this.pawn.health.Notify_HediffChanged(this); } public virtual void ModifyChemicalEffect(ChemicalDef chem, ref float effect) @@ -417,18 +416,22 @@ public virtual void ModifyChemicalEffect(ChemicalDef chem, ref float effect) public virtual bool TryMergeWith(Hediff other) { - if (other == null || other.def != this.def || other.Part != this.Part) + if (other != null && other.def == this.def && other.Part == this.Part) { - return false; + this.Severity += other.Severity; + this.ageTicks = 0; + return true; } - this.Severity += other.Severity; - this.ageTicks = 0; - return true; + return false; } public virtual bool CauseDeathNow() { - return this.def.lethalSeverity >= 0f && this.Severity >= this.def.lethalSeverity; + if (this.def.lethalSeverity >= 0.0) + { + return this.Severity >= this.def.lethalSeverity; + } + return false; } public virtual void Notify_PawnDied() @@ -437,7 +440,7 @@ public virtual void Notify_PawnDied() public virtual string DebugString() { - string text = "severity: " + this.Severity.ToString("F3") + ((this.Severity < this.def.maxSeverity) ? string.Empty : " (reached max)"); + string text = "severity: " + this.Severity.ToString("F3") + ((!(this.Severity >= this.def.maxSeverity)) ? string.Empty : " (reached max)"); if (this.TendableNow) { text = text + "\ntend priority: " + this.TendPriority; @@ -447,15 +450,7 @@ public virtual string DebugString() public override string ToString() { - return string.Concat(new object[] - { - "(", - this.def.defName, - (this.cachedPart == null) ? string.Empty : (" " + this.cachedPart.def.label), - " ticksSinceCreation=", - this.ageTicks, - ")" - }); + return "(" + this.def.defName + ((this.cachedPart == null) ? string.Empty : (" " + this.cachedPart.def.label)) + " ticksSinceCreation=" + this.ageTicks + ")"; } public override int GetHashCode() diff --git a/Assembly-CSharp/Verse/HediffComp.cs b/Assembly-CSharp/Verse/HediffComp.cs index 0719fd78e..131ab7d53 100644 --- a/Assembly-CSharp/Verse/HediffComp.cs +++ b/Assembly-CSharp/Verse/HediffComp.cs @@ -1,5 +1,4 @@ using RimWorld; -using System; namespace Verse { @@ -29,7 +28,7 @@ public virtual string CompLabelInBracketsExtra { get { - return null; + return (string)null; } } @@ -37,7 +36,7 @@ public virtual string CompTipStringExtra { get { - return null; + return (string)null; } } @@ -100,7 +99,7 @@ public virtual void Notify_PawnDied() public virtual string CompDebugString() { - return null; + return (string)null; } } } diff --git a/Assembly-CSharp/Verse/HediffCompProperties.cs b/Assembly-CSharp/Verse/HediffCompProperties.cs index 1d50e39a9..aac62cd8b 100644 --- a/Assembly-CSharp/Verse/HediffCompProperties.cs +++ b/Assembly-CSharp/Verse/HediffCompProperties.cs @@ -1,6 +1,5 @@ using System; using System.Collections.Generic; -using System.Diagnostics; namespace Verse { @@ -8,16 +7,19 @@ public class HediffCompProperties { public Type compClass; - [DebuggerHidden] public IEnumerable ConfigErrors(HediffDef parentDef) { - HediffCompProperties.c__Iterator1C9 c__Iterator1C = new HediffCompProperties.c__Iterator1C9(); - c__Iterator1C.parentDef = parentDef; - c__Iterator1C.<$>parentDef = parentDef; - c__Iterator1C.<>f__this = this; - HediffCompProperties.c__Iterator1C9 expr_1C = c__Iterator1C; - expr_1C.$PC = -2; - return expr_1C; + if (this.compClass == null) + { + yield return "compClass is null"; + } + for (int i = 0; i < parentDef.comps.Count; i++) + { + if (parentDef.comps[i] != this && parentDef.comps[i].compClass == this.compClass) + { + yield return "two comps with same compClass: " + this.compClass; + } + } } } } diff --git a/Assembly-CSharp/Verse/HediffCompProperties_Disappears.cs b/Assembly-CSharp/Verse/HediffCompProperties_Disappears.cs index 82d8db676..63df45c36 100644 --- a/Assembly-CSharp/Verse/HediffCompProperties_Disappears.cs +++ b/Assembly-CSharp/Verse/HediffCompProperties_Disappears.cs @@ -1,5 +1,3 @@ -using System; - namespace Verse { public class HediffCompProperties_Disappears : HediffCompProperties @@ -8,7 +6,7 @@ public class HediffCompProperties_Disappears : HediffCompProperties public HediffCompProperties_Disappears() { - this.compClass = typeof(HediffComp_Disappears); + base.compClass = typeof(HediffComp_Disappears); } } } diff --git a/Assembly-CSharp/Verse/HediffCompProperties_Discoverable.cs b/Assembly-CSharp/Verse/HediffCompProperties_Discoverable.cs index 891089f78..c203af683 100644 --- a/Assembly-CSharp/Verse/HediffCompProperties_Discoverable.cs +++ b/Assembly-CSharp/Verse/HediffCompProperties_Discoverable.cs @@ -1,5 +1,3 @@ -using System; - namespace Verse { public class HediffCompProperties_Discoverable : HediffCompProperties @@ -12,7 +10,7 @@ public class HediffCompProperties_Discoverable : HediffCompProperties public HediffCompProperties_Discoverable() { - this.compClass = typeof(HediffComp_Discoverable); + base.compClass = typeof(HediffComp_Discoverable); } } } diff --git a/Assembly-CSharp/Verse/HediffCompProperties_DrugEffectFactor.cs b/Assembly-CSharp/Verse/HediffCompProperties_DrugEffectFactor.cs index 16b25a6a6..5c082790c 100644 --- a/Assembly-CSharp/Verse/HediffCompProperties_DrugEffectFactor.cs +++ b/Assembly-CSharp/Verse/HediffCompProperties_DrugEffectFactor.cs @@ -1,5 +1,4 @@ using RimWorld; -using System; namespace Verse { @@ -9,7 +8,7 @@ public class HediffCompProperties_DrugEffectFactor : HediffCompProperties public HediffCompProperties_DrugEffectFactor() { - this.compClass = typeof(HediffComp_DrugEffectFactor); + base.compClass = typeof(HediffComp_DrugEffectFactor); } } } diff --git a/Assembly-CSharp/Verse/HediffCompProperties_Effecter.cs b/Assembly-CSharp/Verse/HediffCompProperties_Effecter.cs index 2bb3b8835..e215f33a2 100644 --- a/Assembly-CSharp/Verse/HediffCompProperties_Effecter.cs +++ b/Assembly-CSharp/Verse/HediffCompProperties_Effecter.cs @@ -1,5 +1,3 @@ -using System; - namespace Verse { public class HediffCompProperties_Effecter : HediffCompProperties @@ -10,7 +8,7 @@ public class HediffCompProperties_Effecter : HediffCompProperties public HediffCompProperties_Effecter() { - this.compClass = typeof(HediffComp_Effecter); + base.compClass = typeof(HediffComp_Effecter); } } } diff --git a/Assembly-CSharp/Verse/HediffCompProperties_GetsOld.cs b/Assembly-CSharp/Verse/HediffCompProperties_GetsOld.cs index 4cc6c4ebc..35d35356f 100644 --- a/Assembly-CSharp/Verse/HediffCompProperties_GetsOld.cs +++ b/Assembly-CSharp/Verse/HediffCompProperties_GetsOld.cs @@ -1,5 +1,3 @@ -using System; - namespace Verse { public class HediffCompProperties_GetsOld : HediffCompProperties @@ -12,7 +10,7 @@ public class HediffCompProperties_GetsOld : HediffCompProperties public HediffCompProperties_GetsOld() { - this.compClass = typeof(HediffComp_GetsOld); + base.compClass = typeof(HediffComp_GetsOld); } } } diff --git a/Assembly-CSharp/Verse/HediffCompProperties_GrowthMode.cs b/Assembly-CSharp/Verse/HediffCompProperties_GrowthMode.cs index ecf3240f6..eabcb60b8 100644 --- a/Assembly-CSharp/Verse/HediffCompProperties_GrowthMode.cs +++ b/Assembly-CSharp/Verse/HediffCompProperties_GrowthMode.cs @@ -1,5 +1,3 @@ -using System; - namespace Verse { public class HediffCompProperties_GrowthMode : HediffCompProperties @@ -14,7 +12,7 @@ public class HediffCompProperties_GrowthMode : HediffCompProperties public HediffCompProperties_GrowthMode() { - this.compClass = typeof(HediffComp_GrowthMode); + base.compClass = typeof(HediffComp_GrowthMode); } } } diff --git a/Assembly-CSharp/Verse/HediffCompProperties_HealOldWounds.cs b/Assembly-CSharp/Verse/HediffCompProperties_HealOldWounds.cs index fc93ed356..eb086401b 100644 --- a/Assembly-CSharp/Verse/HediffCompProperties_HealOldWounds.cs +++ b/Assembly-CSharp/Verse/HediffCompProperties_HealOldWounds.cs @@ -1,12 +1,10 @@ -using System; - namespace Verse { public class HediffCompProperties_HealOldWounds : HediffCompProperties { public HediffCompProperties_HealOldWounds() { - this.compClass = typeof(HediffComp_HealOldWounds); + base.compClass = typeof(HediffComp_HealOldWounds); } } } diff --git a/Assembly-CSharp/Verse/HediffCompProperties_Immunizable.cs b/Assembly-CSharp/Verse/HediffCompProperties_Immunizable.cs index d7b614b2e..9e51571a7 100644 --- a/Assembly-CSharp/Verse/HediffCompProperties_Immunizable.cs +++ b/Assembly-CSharp/Verse/HediffCompProperties_Immunizable.cs @@ -1,5 +1,3 @@ -using System; - namespace Verse { public class HediffCompProperties_Immunizable : HediffCompProperties @@ -16,7 +14,7 @@ public class HediffCompProperties_Immunizable : HediffCompProperties public HediffCompProperties_Immunizable() { - this.compClass = typeof(HediffComp_Immunizable); + base.compClass = typeof(HediffComp_Immunizable); } } } diff --git a/Assembly-CSharp/Verse/HediffCompProperties_Infecter.cs b/Assembly-CSharp/Verse/HediffCompProperties_Infecter.cs index 686e49cdd..21400fd54 100644 --- a/Assembly-CSharp/Verse/HediffCompProperties_Infecter.cs +++ b/Assembly-CSharp/Verse/HediffCompProperties_Infecter.cs @@ -1,5 +1,3 @@ -using System; - namespace Verse { public class HediffCompProperties_Infecter : HediffCompProperties @@ -8,7 +6,7 @@ public class HediffCompProperties_Infecter : HediffCompProperties public HediffCompProperties_Infecter() { - this.compClass = typeof(HediffComp_Infecter); + base.compClass = typeof(HediffComp_Infecter); } } } diff --git a/Assembly-CSharp/Verse/HediffCompProperties_SelfHeal.cs b/Assembly-CSharp/Verse/HediffCompProperties_SelfHeal.cs index 3b15d73d6..5d6b9d499 100644 --- a/Assembly-CSharp/Verse/HediffCompProperties_SelfHeal.cs +++ b/Assembly-CSharp/Verse/HediffCompProperties_SelfHeal.cs @@ -1,5 +1,3 @@ -using System; - namespace Verse { public class HediffCompProperties_SelfHeal : HediffCompProperties @@ -8,7 +6,7 @@ public class HediffCompProperties_SelfHeal : HediffCompProperties public HediffCompProperties_SelfHeal() { - this.compClass = typeof(HediffComp_SelfHeal); + base.compClass = typeof(HediffComp_SelfHeal); } } } diff --git a/Assembly-CSharp/Verse/HediffCompProperties_SeverityPerDay.cs b/Assembly-CSharp/Verse/HediffCompProperties_SeverityPerDay.cs index f46a5f9a9..b2f25db23 100644 --- a/Assembly-CSharp/Verse/HediffCompProperties_SeverityPerDay.cs +++ b/Assembly-CSharp/Verse/HediffCompProperties_SeverityPerDay.cs @@ -1,5 +1,3 @@ -using System; - namespace Verse { public class HediffCompProperties_SeverityPerDay : HediffCompProperties @@ -8,7 +6,7 @@ public class HediffCompProperties_SeverityPerDay : HediffCompProperties public HediffCompProperties_SeverityPerDay() { - this.compClass = typeof(HediffComp_SeverityPerDay); + base.compClass = typeof(HediffComp_SeverityPerDay); } } } diff --git a/Assembly-CSharp/Verse/HediffCompProperties_TendDuration.cs b/Assembly-CSharp/Verse/HediffCompProperties_TendDuration.cs index 3877b7a85..94d4efd6c 100644 --- a/Assembly-CSharp/Verse/HediffCompProperties_TendDuration.cs +++ b/Assembly-CSharp/Verse/HediffCompProperties_TendDuration.cs @@ -1,5 +1,3 @@ -using System; - namespace Verse { public class HediffCompProperties_TendDuration : HediffCompProperties @@ -23,7 +21,7 @@ public class HediffCompProperties_TendDuration : HediffCompProperties public HediffCompProperties_TendDuration() { - this.compClass = typeof(HediffComp_TendDuration); + base.compClass = typeof(HediffComp_TendDuration); } } } diff --git a/Assembly-CSharp/Verse/HediffCompProperties_VerbGiver.cs b/Assembly-CSharp/Verse/HediffCompProperties_VerbGiver.cs index 99c7dce78..f57c6c81e 100644 --- a/Assembly-CSharp/Verse/HediffCompProperties_VerbGiver.cs +++ b/Assembly-CSharp/Verse/HediffCompProperties_VerbGiver.cs @@ -1,4 +1,3 @@ -using System; using System.Collections.Generic; namespace Verse @@ -9,7 +8,7 @@ public class HediffCompProperties_VerbGiver : HediffCompProperties public HediffCompProperties_VerbGiver() { - this.compClass = typeof(HediffComp_VerbGiver); + base.compClass = typeof(HediffComp_VerbGiver); } } } diff --git a/Assembly-CSharp/Verse/HediffComp_Disappears.cs b/Assembly-CSharp/Verse/HediffComp_Disappears.cs index e362ed8fd..0cb6c0cd3 100644 --- a/Assembly-CSharp/Verse/HediffComp_Disappears.cs +++ b/Assembly-CSharp/Verse/HediffComp_Disappears.cs @@ -1,5 +1,3 @@ -using System; - namespace Verse { public class HediffComp_Disappears : HediffComp @@ -10,7 +8,7 @@ public HediffCompProperties_Disappears Props { get { - return (HediffCompProperties_Disappears)this.props; + return (HediffCompProperties_Disappears)base.props; } } diff --git a/Assembly-CSharp/Verse/HediffComp_Discoverable.cs b/Assembly-CSharp/Verse/HediffComp_Discoverable.cs index 03c259a58..18a2ae7f1 100644 --- a/Assembly-CSharp/Verse/HediffComp_Discoverable.cs +++ b/Assembly-CSharp/Verse/HediffComp_Discoverable.cs @@ -1,5 +1,4 @@ using RimWorld; -using System; namespace Verse { @@ -11,7 +10,7 @@ public HediffCompProperties_Discoverable Props { get { - return (HediffCompProperties_Discoverable)this.props; + return (HediffCompProperties_Discoverable)base.props; } } @@ -42,59 +41,26 @@ private void CheckDiscovered() { if (this.discovered) { - if (!this.parent.CurStage.everVisible) + if (!base.parent.CurStage.everVisible) { this.discovered = false; } - return; } - if (!this.parent.CurStage.everVisible) + else if (base.parent.CurStage.everVisible) { - return; - } - this.discovered = true; - if (this.Props.sendLetterWhenDiscovered && PawnUtility.ShouldSendNotificationAbout(base.Pawn)) - { - string label; - if (!this.Props.discoverLetterLabel.NullOrEmpty()) - { - label = string.Format(this.Props.discoverLetterLabel, base.Pawn.LabelShort).CapitalizeFirst(); - } - else - { - label = "LetterLabelNewDisease".Translate() + " (" + base.Def.label + ")"; - } - string text; - if (!this.Props.discoverLetterText.NullOrEmpty()) - { - text = string.Format(this.Props.discoverLetterText, base.Pawn.LabelIndefinite()).AdjustedFor(base.Pawn).CapitalizeFirst(); - } - else if (this.parent.Part == null) + this.discovered = true; + if (this.Props.sendLetterWhenDiscovered && PawnUtility.ShouldSendNotificationAbout(base.Pawn)) { - text = "NewDisease".Translate(new object[] + string label = this.Props.discoverLetterLabel.NullOrEmpty() ? ("LetterLabelNewDisease".Translate() + " (" + base.Def.label + ")") : string.Format(this.Props.discoverLetterLabel, base.Pawn.LabelShort).CapitalizeFirst(); + string text = this.Props.discoverLetterText.NullOrEmpty() ? ((base.parent.Part != null) ? "NewPartDisease".Translate(base.Pawn.LabelIndefinite(), base.parent.Part.def.label, base.Pawn.LabelDefinite(), base.Def.LabelCap).AdjustedFor(base.Pawn).CapitalizeFirst() : "NewDisease".Translate(base.Pawn.LabelIndefinite(), base.Def.label, base.Pawn.LabelDefinite()).AdjustedFor(base.Pawn).CapitalizeFirst()) : string.Format(this.Props.discoverLetterText, base.Pawn.LabelIndefinite()).AdjustedFor(base.Pawn).CapitalizeFirst(); + if (base.Pawn.RaceProps.Humanlike) { - base.Pawn.LabelIndefinite(), - base.Def.label, - base.Pawn.LabelDefinite() - }).AdjustedFor(base.Pawn).CapitalizeFirst(); - } - else - { - text = "NewPartDisease".Translate(new object[] + Find.LetterStack.ReceiveLetter(label, text, LetterDefOf.BadNonUrgent, (Thing)base.Pawn, (string)null); + } + else { - base.Pawn.LabelIndefinite(), - this.parent.Part.def.label, - base.Pawn.LabelDefinite(), - base.Def.LabelCap - }).AdjustedFor(base.Pawn).CapitalizeFirst(); - } - if (base.Pawn.RaceProps.Humanlike) - { - Find.LetterStack.ReceiveLetter(label, text, LetterDefOf.BadNonUrgent, base.Pawn, null); - } - else - { - Messages.Message(text, base.Pawn, MessageSound.Standard); + Messages.Message(text, (Thing)base.Pawn, MessageSound.Standard); + } } } } diff --git a/Assembly-CSharp/Verse/HediffComp_DrugEffectFactor.cs b/Assembly-CSharp/Verse/HediffComp_DrugEffectFactor.cs index 7658b035e..16453daa2 100644 --- a/Assembly-CSharp/Verse/HediffComp_DrugEffectFactor.cs +++ b/Assembly-CSharp/Verse/HediffComp_DrugEffectFactor.cs @@ -1,5 +1,4 @@ using RimWorld; -using System; namespace Verse { @@ -21,7 +20,7 @@ public HediffCompProperties_DrugEffectFactor Props { get { - return (HediffCompProperties_DrugEffectFactor)this.props; + return (HediffCompProperties_DrugEffectFactor)base.props; } } @@ -29,7 +28,7 @@ private float CurrentFactor { get { - return HediffComp_DrugEffectFactor.EffectFactorSeverityCurve.Evaluate(this.parent.Severity); + return HediffComp_DrugEffectFactor.EffectFactorSeverityCurve.Evaluate(base.parent.Severity); } } @@ -37,11 +36,7 @@ public override string CompTipStringExtra { get { - return "DrugEffectMultiplier".Translate(new object[] - { - this.Props.chemical.label, - this.CurrentFactor.ToStringPercent() - }).CapitalizeFirst(); + return "DrugEffectMultiplier".Translate(this.Props.chemical.label, this.CurrentFactor.ToStringPercent()).CapitalizeFirst(); } } diff --git a/Assembly-CSharp/Verse/HediffComp_Effecter.cs b/Assembly-CSharp/Verse/HediffComp_Effecter.cs index 3b20b949d..69d99e896 100644 --- a/Assembly-CSharp/Verse/HediffComp_Effecter.cs +++ b/Assembly-CSharp/Verse/HediffComp_Effecter.cs @@ -1,5 +1,3 @@ -using System; - namespace Verse { public class HediffComp_Effecter : HediffComp @@ -8,13 +6,13 @@ public HediffCompProperties_Effecter Props { get { - return (HediffCompProperties_Effecter)this.props; + return (HediffCompProperties_Effecter)base.props; } } public EffecterDef CurrentStateEffecter() { - if (this.parent.CurStageIndex >= this.Props.severityIndices.min && (this.Props.severityIndices.max < 0 || this.parent.CurStageIndex <= this.Props.severityIndices.max)) + if (base.parent.CurStageIndex >= this.Props.severityIndices.min && (this.Props.severityIndices.max < 0 || base.parent.CurStageIndex <= this.Props.severityIndices.max)) { return this.Props.stateEffecter; } diff --git a/Assembly-CSharp/Verse/HediffComp_GetsOld.cs b/Assembly-CSharp/Verse/HediffComp_GetsOld.cs index 20b9a346a..cf035c71d 100644 --- a/Assembly-CSharp/Verse/HediffComp_GetsOld.cs +++ b/Assembly-CSharp/Verse/HediffComp_GetsOld.cs @@ -1,4 +1,3 @@ -using System; using UnityEngine; namespace Verse @@ -15,7 +14,7 @@ public HediffCompProperties_GetsOld Props { get { - return (HediffCompProperties_GetsOld)this.props; + return (HediffCompProperties_GetsOld)base.props; } } @@ -27,14 +26,13 @@ public bool IsOld } set { - if (value == this.isOldInt) + if (value != this.isOldInt) { - return; - } - this.isOldInt = value; - if (this.isOldInt) - { - this.painFactor = OldInjuryUtility.GetRandomPainFactor(); + this.isOldInt = value; + if (this.isOldInt) + { + this.painFactor = OldInjuryUtility.GetRandomPainFactor(); + } } } } @@ -43,7 +41,7 @@ private bool Active { get { - return this.oldDamageThreshold < 9000f; + return this.oldDamageThreshold < 9000.0; } } @@ -56,23 +54,19 @@ public override void CompExposeData() public override void CompPostInjuryHeal(float amount) { - if (!this.Active || this.IsOld) - { - return; - } - if (this.parent.Severity <= this.oldDamageThreshold && this.parent.Severity >= this.oldDamageThreshold - amount) + if (this.Active && !this.IsOld && base.parent.Severity <= this.oldDamageThreshold && base.parent.Severity >= this.oldDamageThreshold - amount) { float num = 0.2f; - HediffComp_TendDuration hediffComp_TendDuration = this.parent.TryGetComp(); + HediffComp_TendDuration hediffComp_TendDuration = base.parent.TryGetComp(); if (hediffComp_TendDuration != null) { - num *= Mathf.Clamp01(1f - hediffComp_TendDuration.tendQuality); + num *= Mathf.Clamp01((float)(1.0 - hediffComp_TendDuration.tendQuality)); } if (Rand.Value < num) { - this.parent.Severity = this.oldDamageThreshold; + base.parent.Severity = this.oldDamageThreshold; this.IsOld = true; - base.Pawn.health.Notify_HediffChanged(this.parent); + base.Pawn.health.Notify_HediffChanged(base.parent); } else { @@ -83,15 +77,7 @@ public override void CompPostInjuryHeal(float amount) public override string CompDebugString() { - return string.Concat(new object[] - { - "isOld: ", - this.isOldInt, - "\noldDamageThreshold: ", - this.oldDamageThreshold, - "\npainFactor: ", - this.painFactor - }); + return "isOld: " + this.isOldInt + "\noldDamageThreshold: " + this.oldDamageThreshold + "\npainFactor: " + this.painFactor; } } } diff --git a/Assembly-CSharp/Verse/HediffComp_GrowthMode.cs b/Assembly-CSharp/Verse/HediffComp_GrowthMode.cs index 321179aff..6f8afd354 100644 --- a/Assembly-CSharp/Verse/HediffComp_GrowthMode.cs +++ b/Assembly-CSharp/Verse/HediffComp_GrowthMode.cs @@ -21,7 +21,7 @@ public HediffCompProperties_GrowthMode Props { get { - return (HediffCompProperties_GrowthMode)this.props; + return (HediffCompProperties_GrowthMode)base.props; } } @@ -44,7 +44,7 @@ public override void CompExposeData() public override void CompPostPostAdd(DamageInfo? dinfo) { base.CompPostPostAdd(dinfo); - this.growthMode = ((HediffGrowthMode[])Enum.GetValues(typeof(HediffGrowthMode))).RandomElement(); + this.growthMode = ((HediffGrowthMode[])Enum.GetValues(typeof(HediffGrowthMode))).RandomElement(); this.severityPerDayGrowingRandomFactor = this.Props.severityPerDayGrowingRandomFactor.RandomInRange; this.severityPerDayRemissionRandomFactor = this.Props.severityPerDayRemissionRandomFactor.RandomInRange; } @@ -63,47 +63,49 @@ protected override float SeverityChangePerDay() switch (this.growthMode) { case HediffGrowthMode.Growing: + { return this.Props.severityPerDayGrowing * this.severityPerDayGrowingRandomFactor; + } case HediffGrowthMode.Stable: + { return 0f; + } case HediffGrowthMode.Remission: + { return this.Props.severityPerDayRemission * this.severityPerDayRemissionRandomFactor; + } default: + { throw new NotImplementedException("GrowthMode"); } + } } private void ChangeGrowthMode() { this.growthMode = (from x in (HediffGrowthMode[])Enum.GetValues(typeof(HediffGrowthMode)) where x != this.growthMode - select x).RandomElement(); + select x).RandomElement(); if (PawnUtility.ShouldSendNotificationAbout(base.Pawn)) { switch (this.growthMode) { case HediffGrowthMode.Growing: - Messages.Message("DiseaseGrowthModeChanged_Growing".Translate(new object[] - { - base.Pawn.LabelShort, - base.Def.label - }), base.Pawn, MessageSound.SeriousAlert); + { + Messages.Message("DiseaseGrowthModeChanged_Growing".Translate(base.Pawn.LabelShort, base.Def.label), (Thing)base.Pawn, MessageSound.SeriousAlert); break; + } case HediffGrowthMode.Stable: - Messages.Message("DiseaseGrowthModeChanged_Stable".Translate(new object[] - { - base.Pawn.LabelShort, - base.Def.label - }), base.Pawn, MessageSound.Standard); + { + Messages.Message("DiseaseGrowthModeChanged_Stable".Translate(base.Pawn.LabelShort, base.Def.label), (Thing)base.Pawn, MessageSound.Standard); break; + } case HediffGrowthMode.Remission: - Messages.Message("DiseaseGrowthModeChanged_Remission".Translate(new object[] - { - base.Pawn.LabelShort, - base.Def.label - }), base.Pawn, MessageSound.Benefit); + { + Messages.Message("DiseaseGrowthModeChanged_Remission".Translate(base.Pawn.LabelShort, base.Def.label), (Thing)base.Pawn, MessageSound.Benefit); break; } + } } } @@ -111,7 +113,7 @@ public override string CompDebugString() { StringBuilder stringBuilder = new StringBuilder(); stringBuilder.Append(base.CompDebugString()); - stringBuilder.AppendLine("severity: " + this.parent.Severity.ToString("F3") + ((this.parent.Severity < base.Def.maxSeverity) ? string.Empty : " (reached max)")); + stringBuilder.AppendLine("severity: " + base.parent.Severity.ToString("F3") + ((!(base.parent.Severity >= base.Def.maxSeverity)) ? string.Empty : " (reached max)")); stringBuilder.AppendLine("severityPerDayGrowingRandomFactor: " + this.severityPerDayGrowingRandomFactor.ToString("0.##")); stringBuilder.AppendLine("severityPerDayRemissionRandomFactor: " + this.severityPerDayRemissionRandomFactor.ToString("0.##")); return stringBuilder.ToString(); diff --git a/Assembly-CSharp/Verse/HediffComp_HealOldWounds.cs b/Assembly-CSharp/Verse/HediffComp_HealOldWounds.cs index f6505fe42..eb71f3f1b 100644 --- a/Assembly-CSharp/Verse/HediffComp_HealOldWounds.cs +++ b/Assembly-CSharp/Verse/HediffComp_HealOldWounds.cs @@ -12,7 +12,7 @@ public HediffCompProperties_HealOldWounds Props { get { - return (HediffCompProperties_HealOldWounds)this.props; + return (HediffCompProperties_HealOldWounds)base.props; } } @@ -39,22 +39,16 @@ public override void CompPostTick(ref float severityAdjustment) private void TryHealRandomOldWound() { - Hediff hediff; - if (!(from hd in base.Pawn.health.hediffSet.hediffs + Hediff hediff = default(Hediff); + if ((from hd in base.Pawn.health.hediffSet.hediffs where hd.IsOld() - select hd).TryRandomElement(out hediff)) + select hd).TryRandomElement(out hediff)) { - return; - } - hediff.Severity = 0f; - if (PawnUtility.ShouldSendNotificationAbout(base.Pawn)) - { - Messages.Message("MessageOldWoundHealed".Translate(new object[] + hediff.Severity = 0f; + if (PawnUtility.ShouldSendNotificationAbout(base.Pawn)) { - this.parent.Label, - base.Pawn.LabelShort, - hediff.Label - }), MessageSound.Benefit); + Messages.Message("MessageOldWoundHealed".Translate(base.parent.Label, base.Pawn.LabelShort, hediff.Label), MessageSound.Benefit); + } } } diff --git a/Assembly-CSharp/Verse/HediffComp_Immunizable.cs b/Assembly-CSharp/Verse/HediffComp_Immunizable.cs index 3d61d5415..ffe0e1de1 100644 --- a/Assembly-CSharp/Verse/HediffComp_Immunizable.cs +++ b/Assembly-CSharp/Verse/HediffComp_Immunizable.cs @@ -1,4 +1,3 @@ -using System; using System.Text; using UnityEngine; @@ -15,7 +14,7 @@ public HediffCompProperties_Immunizable Props { get { - return (HediffCompProperties_Immunizable)this.props; + return (HediffCompProperties_Immunizable)base.props; } } @@ -27,7 +26,7 @@ public override string CompLabelInBracketsExtra { return "DevelopedImmunityLower".Translate(); } - return null; + return (string)null; } } @@ -37,9 +36,9 @@ public override string CompTipStringExtra { if (base.Def.PossibleToDevelopImmunityNaturally() && !this.FullyImmune) { - return "Immunity".Translate() + ": " + (Mathf.Floor(this.Immunity * 100f) / 100f).ToStringPercent(); + return "Immunity".Translate() + ": " + ((float)(Mathf.Floor((float)(this.Immunity * 100.0)) / 100.0)).ToStringPercent(); } - return null; + return (string)null; } } @@ -55,7 +54,7 @@ public bool FullyImmune { get { - return this.Immunity >= 1f; + return this.Immunity >= 1.0; } } @@ -92,7 +91,7 @@ public override string CompDebugString() { StringBuilder stringBuilder = new StringBuilder(); stringBuilder.AppendLine(base.CompDebugString()); - if (this.severityPerDayNotImmuneRandomFactor != 1f) + if (this.severityPerDayNotImmuneRandomFactor != 1.0) { stringBuilder.AppendLine("severityPerDayNotImmuneRandomFactor: " + this.severityPerDayNotImmuneRandomFactor.ToString("0.##")); } @@ -101,7 +100,7 @@ public override string CompDebugString() ImmunityRecord immunityRecord = base.Pawn.health.immunity.GetImmunityRecord(base.Def); if (immunityRecord != null) { - stringBuilder.AppendLine("immunity change per day: " + (immunityRecord.ImmunityChangePerTick(base.Pawn, true, this.parent) * 60000f).ToString("F3")); + stringBuilder.AppendLine("immunity change per day: " + ((float)(immunityRecord.ImmunityChangePerTick(base.Pawn, true, base.parent) * 60000.0)).ToString("F3")); } } return stringBuilder.ToString(); diff --git a/Assembly-CSharp/Verse/HediffComp_Infecter.cs b/Assembly-CSharp/Verse/HediffComp_Infecter.cs index 70d311f7e..1c6e5e896 100644 --- a/Assembly-CSharp/Verse/HediffComp_Infecter.cs +++ b/Assembly-CSharp/Verse/HediffComp_Infecter.cs @@ -1,5 +1,4 @@ using RimWorld; -using System; namespace Verse { @@ -33,39 +32,39 @@ public HediffCompProperties_Infecter Props { get { - return (HediffCompProperties_Infecter)this.props; + return (HediffCompProperties_Infecter)base.props; } } public override void CompPostPostAdd(DamageInfo? dinfo) { - if (this.parent.IsOld()) + if (base.parent.IsOld()) { this.ticksUntilInfect = -2; - return; } - if (this.parent.Part.def.IsSolid(this.parent.Part, base.Pawn.health.hediffSet.hediffs)) + else if (base.parent.Part.def.IsSolid(base.parent.Part, base.Pawn.health.hediffSet.hediffs)) { this.ticksUntilInfect = -2; - return; } - if (base.Pawn.health.hediffSet.PartOrAnyAncestorHasDirectlyAddedParts(this.parent.Part)) + else if (base.Pawn.health.hediffSet.PartOrAnyAncestorHasDirectlyAddedParts(base.parent.Part)) { this.ticksUntilInfect = -2; - return; - } - float num = this.Props.infectionChance; - if (base.Pawn.RaceProps.Animal) - { - num *= 0.2f; - } - if (Rand.Value <= num) - { - this.ticksUntilInfect = HealthTunings.InfectionDelayRange.RandomInRange; } else { - this.ticksUntilInfect = -2; + float num = this.Props.infectionChance; + if (base.Pawn.RaceProps.Animal) + { + num = (float)(num * 0.20000000298023224); + } + if (Rand.Value <= num) + { + this.ticksUntilInfect = HealthTunings.InfectionDelayRange.RandomInRange; + } + else + { + this.ticksUntilInfect = -2; + } } } @@ -101,62 +100,58 @@ public override void CompTended(float quality, int batchPosition = 0) private void CheckMakeInfection() { - if (base.Pawn.health.immunity.DiseaseContractChanceFactor(HediffDefOf.WoundInfection, this.parent.Part) <= 0.001f) + if (base.Pawn.health.immunity.DiseaseContractChanceFactor(HediffDefOf.WoundInfection, base.parent.Part) <= 0.0010000000474974513) { this.ticksUntilInfect = -3; - return; - } - float num = 1f; - HediffComp_TendDuration hediffComp_TendDuration = this.parent.TryGetComp(); - if (hediffComp_TendDuration != null && hediffComp_TendDuration.IsTended) - { - num *= this.infectionChanceFactorFromTendRoom; - num *= HediffComp_Infecter.InfectionChanceFactorFromTendQualityCurve.Evaluate(hediffComp_TendDuration.tendQuality); - } - if (base.Pawn.Faction == Faction.OfPlayer) - { - num *= Find.Storyteller.difficulty.playerPawnInfectionChanceFactor; - } - if (Rand.Value < num) - { - this.ticksUntilInfect = -4; - base.Pawn.health.AddHediff(HediffDefOf.WoundInfection, this.parent.Part, null); } else { - this.ticksUntilInfect = -3; + float num = 1f; + HediffComp_TendDuration hediffComp_TendDuration = base.parent.TryGetComp(); + if (hediffComp_TendDuration != null && hediffComp_TendDuration.IsTended) + { + num *= this.infectionChanceFactorFromTendRoom; + num *= HediffComp_Infecter.InfectionChanceFactorFromTendQualityCurve.Evaluate(hediffComp_TendDuration.tendQuality); + } + if (base.Pawn.Faction == Faction.OfPlayer) + { + num *= Find.Storyteller.difficulty.playerPawnInfectionChanceFactor; + } + if (Rand.Value < num) + { + this.ticksUntilInfect = -4; + base.Pawn.health.AddHediff(HediffDefOf.WoundInfection, base.parent.Part, default(DamageInfo?)); + } + else + { + this.ticksUntilInfect = -3; + } } } public override string CompDebugString() { - if (this.ticksUntilInfect > 0) + if (this.ticksUntilInfect <= 0) { - return string.Concat(new object[] + if (this.ticksUntilInfect == -4) { - "infection may appear in: ", - this.ticksUntilInfect, - " ticks\ninfectChnceFactorFromTendRoom: ", - this.infectionChanceFactorFromTendRoom.ToStringPercent() - }); - } - if (this.ticksUntilInfect == -4) - { - return "already created infection"; - } - if (this.ticksUntilInfect == -3) - { - return "failed to make infection"; - } - if (this.ticksUntilInfect == -2) - { - return "will not make infection"; - } - if (this.ticksUntilInfect == -1) - { - return "uninitialized data!"; + return "already created infection"; + } + if (this.ticksUntilInfect == -3) + { + return "failed to make infection"; + } + if (this.ticksUntilInfect == -2) + { + return "will not make infection"; + } + if (this.ticksUntilInfect == -1) + { + return "uninitialized data!"; + } + return "unexpected ticksUntilInfect = " + this.ticksUntilInfect; } - return "unexpected ticksUntilInfect = " + this.ticksUntilInfect; + return "infection may appear in: " + this.ticksUntilInfect + " ticks\ninfectChnceFactorFromTendRoom: " + this.infectionChanceFactorFromTendRoom.ToStringPercent(); } } } diff --git a/Assembly-CSharp/Verse/HediffComp_SelfHeal.cs b/Assembly-CSharp/Verse/HediffComp_SelfHeal.cs index 119db1005..ffe3cdd31 100644 --- a/Assembly-CSharp/Verse/HediffComp_SelfHeal.cs +++ b/Assembly-CSharp/Verse/HediffComp_SelfHeal.cs @@ -1,5 +1,3 @@ -using System; - namespace Verse { public class HediffComp_SelfHeal : HediffComp @@ -10,7 +8,7 @@ public HediffCompProperties_SelfHeal Props { get { - return (HediffCompProperties_SelfHeal)this.props; + return (HediffCompProperties_SelfHeal)base.props; } } diff --git a/Assembly-CSharp/Verse/HediffComp_SeverityPerDay.cs b/Assembly-CSharp/Verse/HediffComp_SeverityPerDay.cs index 11fa55b06..1dcb863b4 100644 --- a/Assembly-CSharp/Verse/HediffComp_SeverityPerDay.cs +++ b/Assembly-CSharp/Verse/HediffComp_SeverityPerDay.cs @@ -1,4 +1,3 @@ -using System; using System.Text; namespace Verse @@ -11,7 +10,7 @@ private HediffCompProperties_SeverityPerDay Props { get { - return (HediffCompProperties_SeverityPerDay)this.props; + return (HediffCompProperties_SeverityPerDay)base.props; } } @@ -21,7 +20,7 @@ public override void CompPostTick(ref float severityAdjustment) if (base.Pawn.IsHashIntervalTick(200)) { float num = this.SeverityChangePerDay(); - num *= 0.00333333341f; + num = (float)(num * 0.0033333334140479565); severityAdjustment += num; } } diff --git a/Assembly-CSharp/Verse/HediffComp_TendDuration.cs b/Assembly-CSharp/Verse/HediffComp_TendDuration.cs index bc07dad95..b5093cd4c 100644 --- a/Assembly-CSharp/Verse/HediffComp_TendDuration.cs +++ b/Assembly-CSharp/Verse/HediffComp_TendDuration.cs @@ -1,5 +1,4 @@ using RimWorld; -using System; using System.Text; using UnityEngine; @@ -16,19 +15,19 @@ public class HediffComp_TendDuration : HediffComp_SeverityPerDay private int tendedCount; - private static readonly Color UntendedColor; + private static readonly Color UntendedColor = new ColorInt(116, 101, 72).ToColor; - private static readonly Texture2D TendedIcon_Need_General; + private static readonly Texture2D TendedIcon_Need_General = ContentFinder.Get("UI/Icons/Medical/TendedNeed", true); - private static readonly Texture2D TendedIcon_Well_General; + private static readonly Texture2D TendedIcon_Well_General = ContentFinder.Get("UI/Icons/Medical/TendedWell", true); - private static readonly Texture2D TendedIcon_Well_Injury; + private static readonly Texture2D TendedIcon_Well_Injury = ContentFinder.Get("UI/Icons/Medical/BandageWell", true); public HediffCompProperties_TendDuration TProps { get { - return (HediffCompProperties_TendDuration)this.props; + return (HediffCompProperties_TendDuration)base.props; } } @@ -36,7 +35,11 @@ public override bool CompShouldRemove { get { - return base.CompShouldRemove || (this.TProps.disappearsAtTendedCount >= 0 && this.tendedCount >= this.TProps.disappearsAtTendedCount); + if (base.CompShouldRemove) + { + return true; + } + return this.TProps.disappearsAtTendedCount >= 0 && this.tendedCount >= this.TProps.disappearsAtTendedCount; } } @@ -60,63 +63,31 @@ public override string CompTipStringExtra { get { - if (this.parent.IsOld()) + if (base.parent.IsOld()) { - return null; + return (string)null; } StringBuilder stringBuilder = new StringBuilder(); if (!this.IsTended) { - if (!base.Pawn.Dead && this.parent.TendableNow) + if (!base.Pawn.Dead && base.parent.TendableNow) { stringBuilder.AppendLine("NeedsTendingNow".Translate()); } } else { - string text; - if (this.parent.Part != null && this.parent.Part.def.IsSolid(this.parent.Part, base.Pawn.health.hediffSet.hediffs)) - { - text = this.TProps.labelSolidTendedWell; - } - else if (this.parent.Part != null && this.parent.Part.depth == BodyPartDepth.Inside) - { - text = this.TProps.labelTendedWellInner; - } - else - { - text = this.TProps.labelTendedWell; - } + string text = (string)null; + text = ((base.parent.Part == null || !base.parent.Part.def.IsSolid(base.parent.Part, base.Pawn.health.hediffSet.hediffs)) ? ((base.parent.Part == null || base.parent.Part.depth != BodyPartDepth.Inside) ? this.TProps.labelTendedWell : this.TProps.labelTendedWellInner) : this.TProps.labelSolidTendedWell); if (text != null) { - stringBuilder.AppendLine(string.Concat(new string[] - { - text.CapitalizeFirst(), - " (", - "Quality".Translate().ToLower(), - " ", - this.tendQuality.ToStringPercent("F0"), - ")" - })); + stringBuilder.AppendLine(text.CapitalizeFirst() + " (" + "Quality".Translate().ToLower() + " " + this.tendQuality.ToStringPercent("F0") + ")"); } if (!base.Pawn.Dead && this.TProps.tendDuration > 0) { int numTicks = this.tendTick + this.TProps.tendDuration - Find.TickManager.TicksGame; string text2 = numTicks.ToStringTicksToPeriod(true, false, true); - if ("NextTendIn".CanTranslate()) - { - text2 = "NextTendIn".Translate(new object[] - { - text2 - }); - } - else - { - text2 = "NextTreatmentIn".Translate(new object[] - { - text2 - }); - } + text2 = ((!"NextTendIn".CanTranslate()) ? "NextTreatmentIn".Translate(text2) : "NextTendIn".Translate(text2)); stringBuilder.AppendLine(text2); } } @@ -128,40 +99,27 @@ public override TextureAndColor CompStateIcon { get { - if (this.parent is Hediff_Injury) + if (base.parent is Hediff_Injury) { - if (this.IsTended && !this.parent.IsOld()) + if (this.IsTended && !base.parent.IsOld()) { Color color = Color.Lerp(HediffComp_TendDuration.UntendedColor, Color.white, Mathf.Clamp01(this.tendQuality)); return new TextureAndColor(HediffComp_TendDuration.TendedIcon_Well_Injury, color); } } - else if (!(this.parent is Hediff_MissingPart)) + else if (!(base.parent is Hediff_MissingPart) && !base.parent.FullyImmune()) { - if (!this.parent.FullyImmune()) + if (this.IsTended) { - if (this.IsTended) - { - Color color2 = Color.Lerp(HediffComp_TendDuration.UntendedColor, Color.white, Mathf.Clamp01(this.tendQuality)); - return new TextureAndColor(HediffComp_TendDuration.TendedIcon_Well_General, color2); - } - return HediffComp_TendDuration.TendedIcon_Need_General; + Color color2 = Color.Lerp(HediffComp_TendDuration.UntendedColor, Color.white, Mathf.Clamp01(this.tendQuality)); + return new TextureAndColor(HediffComp_TendDuration.TendedIcon_Well_General, color2); } + return HediffComp_TendDuration.TendedIcon_Need_General; } return TextureAndColor.None; } } - static HediffComp_TendDuration() - { - // Note: this type is marked as 'beforefieldinit'. - ColorInt colorInt = new ColorInt(116, 101, 72); - HediffComp_TendDuration.UntendedColor = colorInt.ToColor; - HediffComp_TendDuration.TendedIcon_Need_General = ContentFinder.Get("UI/Icons/Medical/TendedNeed", true); - HediffComp_TendDuration.TendedIcon_Well_General = ContentFinder.Get("UI/Icons/Medical/TendedWell", true); - HediffComp_TendDuration.TendedIcon_Well_Injury = ContentFinder.Get("UI/Icons/Medical/BandageWell", true); - } - public override void CompExposeData() { Scribe_Values.Look(ref this.tendTick, "tendTick", -999999, false); @@ -185,20 +143,10 @@ public override void CompTended(float quality, int batchPosition = 0) this.tendedCount++; if (batchPosition == 0 && base.Pawn.Spawned) { - string text = string.Concat(new string[] - { - "TextMote_Tended".Translate(new object[] - { - this.parent.Label - }).CapitalizeFirst(), - "\n", - "Quality".Translate(), - " ", - this.tendQuality.ToStringPercent() - }); + string text = "TextMote_Tended".Translate(base.parent.Label).CapitalizeFirst() + "\n" + "Quality".Translate() + " " + this.tendQuality.ToStringPercent(); MoteMaker.ThrowText(base.Pawn.DrawPos, base.Pawn.Map, text, Color.white, 3.65f); } - base.Pawn.health.Notify_HediffChanged(this.parent); + base.Pawn.health.Notify_HediffChanged(base.parent); } public override string CompDebugString() @@ -221,13 +169,7 @@ public override string CompDebugString() } if (this.TProps.disappearsAtTendedCount >= 0) { - stringBuilder.AppendLine(string.Concat(new object[] - { - "tended count: ", - this.tendedCount, - " / ", - this.TProps.disappearsAtTendedCount - })); + stringBuilder.AppendLine("tended count: " + this.tendedCount + " / " + this.TProps.disappearsAtTendedCount); } return stringBuilder.ToString().Trim(); } diff --git a/Assembly-CSharp/Verse/HediffComp_VerbGiver.cs b/Assembly-CSharp/Verse/HediffComp_VerbGiver.cs index 0f3a58a76..d379d65a5 100644 --- a/Assembly-CSharp/Verse/HediffComp_VerbGiver.cs +++ b/Assembly-CSharp/Verse/HediffComp_VerbGiver.cs @@ -1,4 +1,3 @@ -using System; using System.Collections.Generic; namespace Verse @@ -11,7 +10,7 @@ public HediffCompProperties_VerbGiver Props { get { - return (HediffCompProperties_VerbGiver)this.props; + return (HediffCompProperties_VerbGiver)base.props; } } @@ -39,7 +38,7 @@ public HediffComp_VerbGiver() public override void CompExposeData() { base.CompExposeData(); - Scribe_Deep.Look(ref this.verbTracker, "verbTracker", new object[] + Scribe_Deep.Look(ref this.verbTracker, "verbTracker", new object[1] { this }); diff --git a/Assembly-CSharp/Verse/HediffDef.cs b/Assembly-CSharp/Verse/HediffDef.cs index bf9c68d30..441816fa7 100644 --- a/Assembly-CSharp/Verse/HediffDef.cs +++ b/Assembly-CSharp/Verse/HediffDef.cs @@ -1,7 +1,6 @@ using RimWorld; using System; using System.Collections.Generic; -using System.Diagnostics; using UnityEngine; namespace Verse @@ -92,40 +91,93 @@ public T CompProps() where T : class { for (int i = 0; i < this.comps.Count; i++) { - T t = this.comps[i] as T; - if (t != null) + T val = (T)(((object)this.comps[i]) as T); + if (val != null) { - return t; + return val; } } } - return (T)((object)null); + return (T)null; } public bool PossibleToDevelopImmunityNaturally() { HediffCompProperties_Immunizable hediffCompProperties_Immunizable = this.CompProps(); - return hediffCompProperties_Immunizable != null && (hediffCompProperties_Immunizable.immunityPerDayNotSick > 0f || hediffCompProperties_Immunizable.immunityPerDaySick > 0f); + if (hediffCompProperties_Immunizable != null && (hediffCompProperties_Immunizable.immunityPerDayNotSick > 0.0 || hediffCompProperties_Immunizable.immunityPerDaySick > 0.0)) + { + return true; + } + return false; } - [DebuggerHidden] public override IEnumerable ConfigErrors() { - HediffDef.c__Iterator1CF c__Iterator1CF = new HediffDef.c__Iterator1CF(); - c__Iterator1CF.<>f__this = this; - HediffDef.c__Iterator1CF expr_0E = c__Iterator1CF; - expr_0E.$PC = -2; - return expr_0E; + foreach (string item in base.ConfigErrors()) + { + yield return item; + } + if (this.hediffClass == null) + { + yield return "hediffClass is null"; + } + if (!this.comps.NullOrEmpty() && !typeof(HediffWithComps).IsAssignableFrom(this.hediffClass)) + { + yield return "has comps but hediffClass is not HediffWithComps or subclass thereof"; + } + if (this.minSeverity > this.initialSeverity) + { + yield return "minSeverity is greater than initialSeverity"; + } + if (this.maxSeverity < this.initialSeverity) + { + yield return "maxSeverity is lower than initialSeverity"; + } + if (!this.tendable && this.HasComp(typeof(HediffComp_TendDuration))) + { + yield return "has HediffComp_TendDuration but tendable = false"; + } + if (this.comps != null) + { + for (int k = 0; k < this.comps.Count; k++) + { + foreach (string item2 in this.comps[k].ConfigErrors(this)) + { + yield return this.comps[k] + ": " + item2; + } + } + } + if (this.stages != null) + { + if (!typeof(Hediff_Addiction).IsAssignableFrom(this.hediffClass)) + { + for (int j = 0; j < this.stages.Count; j++) + { + if (j >= 1 && this.stages[j].minSeverity <= this.stages[j - 1].minSeverity) + { + yield return "stages are not in order of minSeverity"; + } + } + } + for (int i = 0; i < this.stages.Count; i++) + { + if (this.stages[i].makeImmuneTo != null && !this.stages[i].makeImmuneTo.Any((Predicate)((HediffDef im) => im.HasComp(typeof(HediffComp_Immunizable))))) + { + yield return "makes immune to hediff which doesn't have comp immunizable"; + } + } + } } - [DebuggerHidden] public override IEnumerable SpecialDisplayStats() { - HediffDef.c__Iterator1D0 c__Iterator1D = new HediffDef.c__Iterator1D0(); - c__Iterator1D.<>f__this = this; - HediffDef.c__Iterator1D0 expr_0E = c__Iterator1D; - expr_0E.$PC = -2; - return expr_0E; + if (this.stages != null && this.stages.Count == 1) + { + foreach (StatDrawEntry item in this.stages[0].SpecialDisplayStats()) + { + yield return item; + } + } } public static HediffDef Named(string defName) diff --git a/Assembly-CSharp/Verse/HediffGiveUtility.cs b/Assembly-CSharp/Verse/HediffGiveUtility.cs index 7c78b298e..08cd29723 100644 --- a/Assembly-CSharp/Verse/HediffGiveUtility.cs +++ b/Assembly-CSharp/Verse/HediffGiveUtility.cs @@ -8,53 +8,56 @@ public static class HediffGiveUtility { public static bool TryApply(Pawn pawn, HediffDef hediff, List partsToAffect, bool canAffectAnyLivePart = false, int countToAffect = 1, List outAddedHediffs = null) { - if (canAffectAnyLivePart || partsToAffect != null) + if (!canAffectAnyLivePart && partsToAffect == null) { - bool result = false; - for (int i = 0; i < countToAffect; i++) + if (!pawn.health.hediffSet.HasHediff(hediff)) { - IEnumerable source = pawn.health.hediffSet.GetNotMissingParts(BodyPartHeight.Undefined, BodyPartDepth.Undefined); - if (partsToAffect != null) - { - source = from p in source - where partsToAffect.Contains(p.def) - select p; - } - if (canAffectAnyLivePart) - { - source = from p in source - where p.def.isAlive - select p; - } - source = from p in source - where !pawn.health.hediffSet.HasHediff(hediff, p) && !pawn.health.hediffSet.PartOrAnyAncestorHasDirectlyAddedParts(p) - select p; - if (!source.Any()) - { - break; - } - BodyPartRecord partRecord = source.RandomElementByWeight((BodyPartRecord x) => x.coverageAbs); - Hediff hediff2 = HediffMaker.MakeHediff(hediff, pawn, partRecord); - pawn.health.AddHediff(hediff2, null, null); + Hediff hediff2 = HediffMaker.MakeHediff(hediff, pawn, null); + pawn.health.AddHediff(hediff2, null, default(DamageInfo?)); if (outAddedHediffs != null) { outAddedHediffs.Add(hediff2); } - result = true; + return true; } - return result; + return false; } - if (!pawn.health.hediffSet.HasHediff(hediff)) + bool result = false; + int num = 0; + while (num < countToAffect) { - Hediff hediff3 = HediffMaker.MakeHediff(hediff, pawn, null); - pawn.health.AddHediff(hediff3, null, null); - if (outAddedHediffs != null) + IEnumerable source = pawn.health.hediffSet.GetNotMissingParts(BodyPartHeight.Undefined, BodyPartDepth.Undefined); + if (partsToAffect != null) { - outAddedHediffs.Add(hediff3); + source = from p in source + where partsToAffect.Contains(p.def) + select p; + } + if (canAffectAnyLivePart) + { + source = from p in source + where p.def.isAlive + select p; + } + source = from p in source + where !pawn.health.hediffSet.HasHediff(hediff, p) && !pawn.health.hediffSet.PartOrAnyAncestorHasDirectlyAddedParts(p) + select p; + if (source.Any()) + { + BodyPartRecord partRecord = source.RandomElementByWeight((Func)((BodyPartRecord x) => x.coverageAbs)); + Hediff hediff3 = HediffMaker.MakeHediff(hediff, pawn, partRecord); + pawn.health.AddHediff(hediff3, null, default(DamageInfo?)); + if (outAddedHediffs != null) + { + outAddedHediffs.Add(hediff3); + } + result = true; + num++; + continue; } - return true; + break; } - return false; + return result; } } } diff --git a/Assembly-CSharp/Verse/HediffGiver.cs b/Assembly-CSharp/Verse/HediffGiver.cs index 665dc4f8c..4787d639f 100644 --- a/Assembly-CSharp/Verse/HediffGiver.cs +++ b/Assembly-CSharp/Verse/HediffGiver.cs @@ -1,5 +1,4 @@ using RimWorld; -using System; using System.Collections.Generic; namespace Verse @@ -34,28 +33,11 @@ protected void SendLetter(Pawn pawn, Hediff cause) { if (cause == null) { - Find.LetterStack.ReceiveLetter("LetterHediffFromRandomHediffGiverLabel".Translate(new object[] - { - pawn.LabelShort, - this.hediff.LabelCap - }), "LetterHediffFromRandomHediffGiver".Translate(new object[] - { - pawn.LabelShort, - this.hediff.LabelCap - }), LetterDefOf.BadNonUrgent, pawn, null); + Find.LetterStack.ReceiveLetter("LetterHediffFromRandomHediffGiverLabel".Translate(pawn.LabelShort, this.hediff.LabelCap), "LetterHediffFromRandomHediffGiver".Translate(pawn.LabelShort, this.hediff.LabelCap), LetterDefOf.BadNonUrgent, (Thing)pawn, (string)null); } else { - Find.LetterStack.ReceiveLetter("LetterHealthComplicationsLabel".Translate(new object[] - { - pawn.LabelShort, - this.hediff.LabelCap - }), "LetterHealthComplications".Translate(new object[] - { - pawn.LabelShort, - this.hediff.LabelCap, - cause.LabelCap - }), LetterDefOf.BadNonUrgent, pawn, null); + Find.LetterStack.ReceiveLetter("LetterHealthComplicationsLabel".Translate(pawn.LabelShort, this.hediff.LabelCap), "LetterHealthComplications".Translate(pawn.LabelShort, this.hediff.LabelCap, cause.LabelCap), LetterDefOf.BadNonUrgent, (Thing)pawn, (string)null); } } } diff --git a/Assembly-CSharp/Verse/HediffGiver_Birthday.cs b/Assembly-CSharp/Verse/HediffGiver_Birthday.cs index 89965452f..e7f9404d6 100644 --- a/Assembly-CSharp/Verse/HediffGiver_Birthday.cs +++ b/Assembly-CSharp/Verse/HediffGiver_Birthday.cs @@ -1,4 +1,3 @@ -using System; using System.Collections.Generic; using UnityEngine; @@ -15,30 +14,23 @@ public class HediffGiver_Birthday : HediffGiver public void TryApplyAndSimulateSeverityChange(Pawn pawn, float gotAtAge, bool tryNotToKillPawn) { HediffGiver_Birthday.addedHediffs.Clear(); - if (!base.TryApply(pawn, HediffGiver_Birthday.addedHediffs)) + if (base.TryApply(pawn, HediffGiver_Birthday.addedHediffs)) { - return; - } - if (this.averageSeverityPerDayBeforeGeneration != 0f) - { - float num = (pawn.ageTracker.AgeBiologicalYearsFloat - gotAtAge) * 60f; - if (num < 0f) + if (this.averageSeverityPerDayBeforeGeneration != 0.0) { - Log.Error(string.Concat(new object[] + float num = (float)((pawn.ageTracker.AgeBiologicalYearsFloat - gotAtAge) * 60.0); + if (num < 0.0) { - "daysPassed < 0, pawn=", - pawn, - ", gotAtAge=", - gotAtAge - })); - return; - } - for (int i = 0; i < HediffGiver_Birthday.addedHediffs.Count; i++) - { - this.SimulateSeverityChange(pawn, HediffGiver_Birthday.addedHediffs[i], num, tryNotToKillPawn); + Log.Error("daysPassed < 0, pawn=" + pawn + ", gotAtAge=" + gotAtAge); + return; + } + for (int i = 0; i < HediffGiver_Birthday.addedHediffs.Count; i++) + { + this.SimulateSeverityChange(pawn, HediffGiver_Birthday.addedHediffs[i], num, tryNotToKillPawn); + } } + HediffGiver_Birthday.addedHediffs.Clear(); } - HediffGiver_Birthday.addedHediffs.Clear(); } private void SimulateSeverityChange(Pawn pawn, Hediff hediff, float daysPassed, bool tryNotToKillPawn) @@ -56,28 +48,30 @@ private void SimulateSeverityChange(Pawn pawn, Hediff hediff, float daysPassed, private void AvoidLifeThreateningStages(ref float severity, List stages) { - if (stages.NullOrEmpty()) - { - return; - } - int num = -1; - for (int i = 0; i < stages.Count; i++) + if (!stages.NullOrEmpty()) { - if (stages[i].lifeThreatening) + int num = -1; + int num2 = 0; + while (num2 < stages.Count) { - num = i; + if (!stages[num2].lifeThreatening) + { + num2++; + continue; + } + num = num2; break; } - } - if (num >= 0) - { - if (num == 0) + if (num >= 0) { - severity = Mathf.Min(severity, stages[num].minSeverity); - } - else - { - severity = Mathf.Min(severity, (stages[num].minSeverity + stages[num - 1].minSeverity) / 2f); + if (num == 0) + { + severity = Mathf.Min(severity, stages[num].minSeverity); + } + else + { + severity = Mathf.Min(severity, (float)((stages[num].minSeverity + stages[num - 1].minSeverity) / 2.0)); + } } } } @@ -85,12 +79,12 @@ private void AvoidLifeThreateningStages(ref float severity, List st public float DebugChanceToHaveAtAge(Pawn pawn, int age) { float num = 1f; - for (int i = 1; i <= age; i++) + for (int num2 = 1; num2 <= age; num2++) { - float x = (float)i / pawn.RaceProps.lifeExpectancy; - num *= 1f - this.ageFractionChanceCurve.Evaluate(x); + float x = (float)num2 / pawn.RaceProps.lifeExpectancy; + num = (float)(num * (1.0 - this.ageFractionChanceCurve.Evaluate(x))); } - return 1f - num; + return (float)(1.0 - num); } } } diff --git a/Assembly-CSharp/Verse/HediffGiver_Bleeding.cs b/Assembly-CSharp/Verse/HediffGiver_Bleeding.cs index 6705ffb8c..b93932132 100644 --- a/Assembly-CSharp/Verse/HediffGiver_Bleeding.cs +++ b/Assembly-CSharp/Verse/HediffGiver_Bleeding.cs @@ -1,5 +1,3 @@ -using System; - namespace Verse { public class HediffGiver_Bleeding : HediffGiver @@ -7,14 +5,13 @@ public class HediffGiver_Bleeding : HediffGiver public override void OnIntervalPassed(Pawn pawn, Hediff cause) { HediffSet hediffSet = pawn.health.hediffSet; - bool flag = hediffSet.BleedRateTotal >= 0.1f; - if (flag) + if (hediffSet.BleedRateTotal >= 0.10000000149011612) { - HealthUtility.AdjustSeverity(pawn, this.hediff, hediffSet.BleedRateTotal * 0.001f); + HealthUtility.AdjustSeverity(pawn, base.hediff, (float)(hediffSet.BleedRateTotal * 0.0010000000474974513)); } else { - HealthUtility.AdjustSeverity(pawn, this.hediff, -0.00033333333f); + HealthUtility.AdjustSeverity(pawn, base.hediff, -0.00033333333f); } } } diff --git a/Assembly-CSharp/Verse/HediffGiver_BrainInjury.cs b/Assembly-CSharp/Verse/HediffGiver_BrainInjury.cs index b69a4047c..4697ffc02 100644 --- a/Assembly-CSharp/Verse/HediffGiver_BrainInjury.cs +++ b/Assembly-CSharp/Verse/HediffGiver_BrainInjury.cs @@ -1,5 +1,4 @@ using RimWorld; -using System; namespace Verse { @@ -22,17 +21,13 @@ public override bool OnHediffAdded(Pawn pawn, Hediff hediff) return false; } float num = hediff.Severity / hediff.Part.def.GetMaxHealth(pawn); - if (Rand.Value < num * this.chancePerDamagePct) + if (Rand.Value < num * this.chancePerDamagePct && base.TryApply(pawn, null)) { - bool flag = base.TryApply(pawn, null); - if (flag) + if ((pawn.Faction == Faction.OfPlayer || pawn.IsPrisonerOfColony) && !this.letter.NullOrEmpty()) { - if ((pawn.Faction == Faction.OfPlayer || pawn.IsPrisonerOfColony) && !this.letter.NullOrEmpty()) - { - Find.LetterStack.ReceiveLetter(this.letterLabel, this.letter.AdjustedFor(pawn), LetterDefOf.BadNonUrgent, pawn, null); - } - return true; + Find.LetterStack.ReceiveLetter(this.letterLabel, this.letter.AdjustedFor(pawn), LetterDefOf.BadNonUrgent, (Thing)pawn, (string)null); } + return true; } return false; } diff --git a/Assembly-CSharp/Verse/HediffGiver_Event.cs b/Assembly-CSharp/Verse/HediffGiver_Event.cs index 07a8e0998..90827bb3e 100644 --- a/Assembly-CSharp/Verse/HediffGiver_Event.cs +++ b/Assembly-CSharp/Verse/HediffGiver_Event.cs @@ -1,5 +1,3 @@ -using System; - namespace Verse { public class HediffGiver_Event : HediffGiver @@ -8,7 +6,11 @@ public class HediffGiver_Event : HediffGiver public bool EventOccurred(Pawn pawn) { - return Rand.Value < this.chance && base.TryApply(pawn, null); + if (Rand.Value < this.chance) + { + return base.TryApply(pawn, null); + } + return false; } } } diff --git a/Assembly-CSharp/Verse/HediffGiver_Heat.cs b/Assembly-CSharp/Verse/HediffGiver_Heat.cs index b6788fdfc..1662c469b 100644 --- a/Assembly-CSharp/Verse/HediffGiver_Heat.cs +++ b/Assembly-CSharp/Verse/HediffGiver_Heat.cs @@ -1,5 +1,4 @@ using RimWorld; -using System; using UnityEngine; using Verse.AI.Group; @@ -49,33 +48,29 @@ public override void OnIntervalPassed(Pawn pawn, Hediff cause) FloatRange floatRange = pawn.ComfortableTemperatureRange(); FloatRange floatRange2 = pawn.SafeTemperatureRange(); HediffSet hediffSet = pawn.health.hediffSet; - Hediff firstHediffOfDef = hediffSet.GetFirstHediffOfDef(this.hediff, false); + Hediff firstHediffOfDef = hediffSet.GetFirstHediffOfDef(base.hediff, false); if (ambientTemperature > floatRange2.max) { - float num = ambientTemperature - floatRange2.max; - num = HediffGiver_Heat.TemperatureOverageAdjustmentCurve.Evaluate(num); - float num2 = num * 6.45E-05f; - num2 = Mathf.Max(num2, 0.000375f); - HealthUtility.AdjustSeverity(pawn, this.hediff, num2); + float x = ambientTemperature - floatRange2.max; + x = HediffGiver_Heat.TemperatureOverageAdjustmentCurve.Evaluate(x); + float a = (float)(x * 6.44999963697046E-05); + a = Mathf.Max(a, 0.000375f); + HealthUtility.AdjustSeverity(pawn, base.hediff, a); } else if (firstHediffOfDef != null && ambientTemperature < floatRange.max) { - float num3 = firstHediffOfDef.Severity * 0.027f; - num3 = Mathf.Clamp(num3, 0.0015f, 0.015f); - firstHediffOfDef.Severity -= num3; + float value = (float)(firstHediffOfDef.Severity * 0.027000000700354576); + value = Mathf.Clamp(value, 0.0015f, 0.015f); + firstHediffOfDef.Severity -= value; } - if (pawn.Dead) + if (!pawn.Dead && pawn.IsNestedHashIntervalTick(60, 420)) { - return; - } - if (pawn.IsNestedHashIntervalTick(60, 420)) - { - float num4 = floatRange.max + 150f; - if (ambientTemperature > num4) + float num = (float)(floatRange.max + 150.0); + if (ambientTemperature > num) { - float num5 = ambientTemperature - num4; - num5 = HediffGiver_Heat.TemperatureOverageAdjustmentCurve.Evaluate(num5); - int amount = Mathf.Max(GenMath.RoundRandom(num5 * 0.06f), 3); + float x2 = ambientTemperature - num; + x2 = HediffGiver_Heat.TemperatureOverageAdjustmentCurve.Evaluate(x2); + int amount = Mathf.Max(GenMath.RoundRandom((float)(x2 * 0.059999998658895493)), 3); DamageInfo dinfo = new DamageInfo(DamageDefOf.Burn, amount, -1f, null, null, null, DamageInfo.SourceCategory.ThingOrUnknown); dinfo.SetBodyRegion(BodyPartHeight.Undefined, BodyPartDepth.Outside); pawn.TakeDamage(dinfo); @@ -84,10 +79,7 @@ public override void OnIntervalPassed(Pawn pawn, Hediff cause) Find.TickManager.slower.SignalForceNormalSpeed(); if (MessagesRepeatAvoider.MessageShowAllowed("PawnBeingBurned", 60f)) { - Messages.Message("MessagePawnBeingBurned".Translate(new object[] - { - pawn.LabelShort - }).CapitalizeFirst(), pawn, MessageSound.SeriousAlert); + Messages.Message("MessagePawnBeingBurned".Translate(pawn.LabelShort).CapitalizeFirst(), (Thing)pawn, MessageSound.SeriousAlert); } } Lord lord = pawn.GetLord(); diff --git a/Assembly-CSharp/Verse/HediffGiver_Hypothermia.cs b/Assembly-CSharp/Verse/HediffGiver_Hypothermia.cs index a77b350f2..eca63dccc 100644 --- a/Assembly-CSharp/Verse/HediffGiver_Hypothermia.cs +++ b/Assembly-CSharp/Verse/HediffGiver_Hypothermia.cs @@ -13,41 +13,36 @@ public override void OnIntervalPassed(Pawn pawn, Hediff cause) FloatRange floatRange = pawn.ComfortableTemperatureRange(); FloatRange floatRange2 = pawn.SafeTemperatureRange(); HediffSet hediffSet = pawn.health.hediffSet; - Hediff firstHediffOfDef = hediffSet.GetFirstHediffOfDef(this.hediff, false); + Hediff firstHediffOfDef = hediffSet.GetFirstHediffOfDef(base.hediff, false); if (ambientTemperature < floatRange2.min) { float num = Mathf.Abs(ambientTemperature - floatRange2.min); - float num2 = num * 6.45E-05f; - num2 = Mathf.Max(num2, 0.00075f); - HealthUtility.AdjustSeverity(pawn, this.hediff, num2); + float a = (float)(num * 6.44999963697046E-05); + a = Mathf.Max(a, 0.00075f); + HealthUtility.AdjustSeverity(pawn, base.hediff, a); if (pawn.Dead) - { return; - } } if (firstHediffOfDef != null) { if (ambientTemperature > floatRange.min) { - float num3 = firstHediffOfDef.Severity * 0.027f; - num3 = Mathf.Clamp(num3, 0.0015f, 0.015f); - firstHediffOfDef.Severity -= num3; + float value = (float)(firstHediffOfDef.Severity * 0.027000000700354576); + value = Mathf.Clamp(value, 0.0015f, 0.015f); + firstHediffOfDef.Severity -= value; } - else if (ambientTemperature < 0f && firstHediffOfDef.Severity > 0.37f) + else if (ambientTemperature < 0.0 && firstHediffOfDef.Severity > 0.37000000476837158) { - float num4 = 0.025f * firstHediffOfDef.Severity; - if (Rand.Value < num4) + float num2 = (float)(0.02500000037252903 * firstHediffOfDef.Severity); + BodyPartRecord bodyPartRecord = default(BodyPartRecord); + if (Rand.Value < num2 && (from x in pawn.RaceProps.body.AllPartsVulnerableToFrostbite + where !hediffSet.PartIsMissing(x) + select x).TryRandomElementByWeight((Func)((BodyPartRecord x) => x.def.frostbiteVulnerability), out bodyPartRecord)) { - BodyPartRecord bodyPartRecord; - if ((from x in pawn.RaceProps.body.AllPartsVulnerableToFrostbite - where !hediffSet.PartIsMissing(x) - select x).TryRandomElementByWeight((BodyPartRecord x) => x.def.frostbiteVulnerability, out bodyPartRecord)) - { - int amount = Mathf.CeilToInt((float)bodyPartRecord.def.hitPoints * 0.5f); - BodyPartRecord forceHitPart = bodyPartRecord; - DamageInfo dinfo = new DamageInfo(DamageDefOf.Frostbite, amount, -1f, null, forceHitPart, null, DamageInfo.SourceCategory.ThingOrUnknown); - pawn.TakeDamage(dinfo); - } + int amount = Mathf.CeilToInt((float)((float)bodyPartRecord.def.hitPoints * 0.5)); + BodyPartRecord forceHitPart = bodyPartRecord; + DamageInfo dinfo = new DamageInfo(DamageDefOf.Frostbite, amount, -1f, null, forceHitPart, null, DamageInfo.SourceCategory.ThingOrUnknown); + pawn.TakeDamage(dinfo); } } } diff --git a/Assembly-CSharp/Verse/HediffGiver_Random.cs b/Assembly-CSharp/Verse/HediffGiver_Random.cs index 4f00d4203..640ffb009 100644 --- a/Assembly-CSharp/Verse/HediffGiver_Random.cs +++ b/Assembly-CSharp/Verse/HediffGiver_Random.cs @@ -1,5 +1,3 @@ -using System; - namespace Verse { public class HediffGiver_Random : HediffGiver diff --git a/Assembly-CSharp/Verse/HediffGiver_RandomAgeCurved.cs b/Assembly-CSharp/Verse/HediffGiver_RandomAgeCurved.cs index c455dc21c..14b50c618 100644 --- a/Assembly-CSharp/Verse/HediffGiver_RandomAgeCurved.cs +++ b/Assembly-CSharp/Verse/HediffGiver_RandomAgeCurved.cs @@ -1,5 +1,3 @@ -using System; - namespace Verse { public class HediffGiver_RandomAgeCurved : HediffGiver diff --git a/Assembly-CSharp/Verse/HediffGiver_RandomDrugEffect.cs b/Assembly-CSharp/Verse/HediffGiver_RandomDrugEffect.cs index 0d685cae1..357942ae0 100644 --- a/Assembly-CSharp/Verse/HediffGiver_RandomDrugEffect.cs +++ b/Assembly-CSharp/Verse/HediffGiver_RandomDrugEffect.cs @@ -1,5 +1,3 @@ -using System; - namespace Verse { public class HediffGiver_RandomDrugEffect : HediffGiver @@ -10,11 +8,7 @@ public class HediffGiver_RandomDrugEffect : HediffGiver public override void OnIntervalPassed(Pawn pawn, Hediff cause) { - if (cause.Severity < this.minSeverity) - { - return; - } - if (Rand.MTBEventOccurs(this.baseMtbDays, 60000f, 60f) && base.TryApply(pawn, null)) + if (!(cause.Severity < this.minSeverity) && Rand.MTBEventOccurs(this.baseMtbDays, 60000f, 60f) && base.TryApply(pawn, null)) { base.SendLetter(pawn, cause); } diff --git a/Assembly-CSharp/Verse/HediffGrowthMode.cs b/Assembly-CSharp/Verse/HediffGrowthMode.cs index 2ff222804..f4aecd5e0 100644 --- a/Assembly-CSharp/Verse/HediffGrowthMode.cs +++ b/Assembly-CSharp/Verse/HediffGrowthMode.cs @@ -1,11 +1,9 @@ -using System; - namespace Verse { public enum HediffGrowthMode { - Growing, - Stable, - Remission + Growing = 0, + Stable = 1, + Remission = 2 } } diff --git a/Assembly-CSharp/Verse/HediffGrowthModeUtility.cs b/Assembly-CSharp/Verse/HediffGrowthModeUtility.cs index 4a34507be..3d4d532ec 100644 --- a/Assembly-CSharp/Verse/HediffGrowthModeUtility.cs +++ b/Assembly-CSharp/Verse/HediffGrowthModeUtility.cs @@ -9,14 +9,22 @@ public static string GetLabel(this HediffGrowthMode m) switch (m) { case HediffGrowthMode.Growing: + { return "HediffGrowthMode_Growing".Translate(); + } case HediffGrowthMode.Stable: + { return "HediffGrowthMode_Stable".Translate(); + } case HediffGrowthMode.Remission: + { return "HediffGrowthMode_Remission".Translate(); + } default: + { throw new ArgumentException(); } + } } } } diff --git a/Assembly-CSharp/Verse/HediffSet.cs b/Assembly-CSharp/Verse/HediffSet.cs index bdf6cc743..5df1456d6 100644 --- a/Assembly-CSharp/Verse/HediffSet.cs +++ b/Assembly-CSharp/Verse/HediffSet.cs @@ -1,7 +1,6 @@ using RimWorld; using System; using System.Collections.Generic; -using System.Diagnostics; using System.Linq; using UnityEngine; @@ -31,7 +30,7 @@ public float PainTotal { get { - if (this.cachedPain < 0f) + if (this.cachedPain < 0.0) { this.cachedPain = this.CalculatePain(); } @@ -43,7 +42,7 @@ public float BleedRateTotal { get { - if (this.cachedBleedRate < 0f) + if (this.cachedBleedRate < 0.0) { this.cachedBleedRate = this.CalculateBleedRate(); } @@ -55,10 +54,10 @@ public bool HasHead { get { - bool? flag = this.cachedHasHead; - if (!flag.HasValue) + bool? nullable = this.cachedHasHead; + if (!nullable.HasValue) { - this.cachedHasHead = new bool?(this.GetNotMissingParts(BodyPartHeight.Undefined, BodyPartDepth.Undefined).Any((BodyPartRecord x) => x.def == BodyPartDefOf.Head)); + this.cachedHasHead = new bool?(this.GetNotMissingParts(BodyPartHeight.Undefined, BodyPartDepth.Undefined).Any((Func)((BodyPartRecord x) => x.def == BodyPartDefOf.Head))); } return this.cachedHasHead.Value; } @@ -70,12 +69,9 @@ public bool AnyHediffMakesSickThought { for (int i = 0; i < this.hediffs.Count; i++) { - if (this.hediffs[i].def.makesSickThought) + if (this.hediffs[i].def.makesSickThought && this.hediffs[i].Visible) { - if (this.hediffs[i].Visible) - { - return true; - } + return true; } } return false; @@ -100,78 +96,79 @@ public void ExposeData() } } - public void AddDirect(Hediff hediff, DamageInfo? dinfo = null) + public void AddDirect(Hediff hediff, DamageInfo? dinfo = default(DamageInfo?)) { if (hediff.def == null) { Log.Error("Tried to add health diff with null def. Canceling."); - return; } - if (hediff.Part != null && !this.GetNotMissingParts(BodyPartHeight.Undefined, BodyPartDepth.Undefined).Contains(hediff.Part)) + else if (hediff.Part != null && !this.GetNotMissingParts(BodyPartHeight.Undefined, BodyPartDepth.Undefined).Contains(hediff.Part)) { Log.Error("Tried to add health diff to missing part " + hediff.Part); - return; } - ProfilerThreadCheck.BeginSample("HediffSet.AddHediff()"); - hediff.ageTicks = 0; - hediff.pawn = this.pawn; - ProfilerThreadCheck.BeginSample("Attempt merge or add new hediff"); - bool flag = false; - for (int i = 0; i < this.hediffs.Count; i++) + else { - if (this.hediffs[i].TryMergeWith(hediff)) + ProfilerThreadCheck.BeginSample("HediffSet.AddHediff()"); + hediff.ageTicks = 0; + hediff.pawn = this.pawn; + ProfilerThreadCheck.BeginSample("Attempt merge or add new hediff"); + bool flag = false; + for (int i = 0; i < this.hediffs.Count; i++) { - flag = true; + if (this.hediffs[i].TryMergeWith(hediff)) + { + flag = true; + } } - } - if (!flag) - { - this.hediffs.Add(hediff); - hediff.PostAdd(dinfo); - if (this.pawn.needs != null && this.pawn.needs.mood != null) + if (!flag) { - this.pawn.needs.mood.thoughts.situational.Notify_SituationalThoughtsDirty(); + this.hediffs.Add(hediff); + hediff.PostAdd(dinfo); + if (this.pawn.needs != null && this.pawn.needs.mood != null) + { + this.pawn.needs.mood.thoughts.situational.Notify_SituationalThoughtsDirty(); + } } - } - ProfilerThreadCheck.EndSample(); - bool flag2 = hediff is Hediff_MissingPart; - if (!(hediff is Hediff_MissingPart) && hediff.Part != null && hediff.Part != this.pawn.RaceProps.body.corePart && this.GetPartHealth(hediff.Part) == 0f) - { - ProfilerThreadCheck.BeginSample("Handle missing body part"); - if (hediff.Part != this.pawn.RaceProps.body.corePart) + ProfilerThreadCheck.EndSample(); + bool flag2 = hediff is Hediff_MissingPart; + if (!(hediff is Hediff_MissingPart) && hediff.Part != null && hediff.Part != this.pawn.RaceProps.body.corePart && this.GetPartHealth(hediff.Part) == 0.0) { - bool flag3 = this.HasDirectlyAddedPartFor(hediff.Part); - Hediff_MissingPart hediff_MissingPart = (Hediff_MissingPart)HediffMaker.MakeHediff(HediffDefOf.MissingBodyPart, this.pawn, null); - hediff_MissingPart.IsFresh = !flag3; - hediff_MissingPart.lastInjury = hediff.def; - this.pawn.health.AddHediff(hediff_MissingPart, hediff.Part, dinfo); - if (flag3) + ProfilerThreadCheck.BeginSample("Handle missing body part"); + if (hediff.Part != this.pawn.RaceProps.body.corePart) { - if (dinfo.HasValue) + bool flag3 = this.HasDirectlyAddedPartFor(hediff.Part); + Hediff_MissingPart hediff_MissingPart = (Hediff_MissingPart)HediffMaker.MakeHediff(HediffDefOf.MissingBodyPart, this.pawn, null); + hediff_MissingPart.IsFresh = !flag3; + hediff_MissingPart.lastInjury = hediff.def; + this.pawn.health.AddHediff(hediff_MissingPart, hediff.Part, dinfo); + if (flag3) { - hediff_MissingPart.lastInjury = HealthUtility.GetHediffDefFromDamage(dinfo.Value.Def, this.pawn, hediff.Part); - } - else - { - hediff_MissingPart.lastInjury = null; + if (dinfo.HasValue) + { + hediff_MissingPart.lastInjury = HealthUtility.GetHediffDefFromDamage(dinfo.Value.Def, this.pawn, hediff.Part); + } + else + { + hediff_MissingPart.lastInjury = null; + } } + flag2 = true; } - flag2 = true; + ProfilerThreadCheck.EndSample(); + } + ProfilerThreadCheck.BeginSample("Dirty cache"); + this.DirtyCache(); + ProfilerThreadCheck.EndSample(); + if (flag2 && this.pawn.apparel != null) + { + this.pawn.apparel.Notify_LostBodyPart(); + } + if (hediff.def.causesNeed != null && !this.pawn.Dead) + { + this.pawn.needs.AddOrRemoveNeedsAsAppropriate(); } ProfilerThreadCheck.EndSample(); } - ProfilerThreadCheck.BeginSample("Dirty cache"); - this.DirtyCache(); - ProfilerThreadCheck.EndSample(); - if (flag2 && this.pawn.apparel != null) - { - this.pawn.apparel.Notify_LostBodyPart(); - } - if (hediff.def.causesNeed != null && !this.pawn.Dead) - { - this.pawn.needs.AddOrRemoveNeedsAsAppropriate(); - } - ProfilerThreadCheck.EndSample(); } public void DirtyCache() @@ -179,19 +176,21 @@ public void DirtyCache() this.CacheMissingPartsCommonAncestors(); this.cachedPain = -1f; this.cachedBleedRate = -1f; - this.cachedHasHead = null; + this.cachedHasHead = default(bool?); this.pawn.health.capacities.Notify_CapacityLevelsDirty(); this.pawn.health.summaryHealth.Notify_HealthChanged(); } - [DebuggerHidden] public IEnumerable GetHediffs() where T : Hediff { - HediffSet.c__Iterator212 c__Iterator = new HediffSet.c__Iterator212(); - c__Iterator.<>f__this = this; - HediffSet.c__Iterator212 expr_0E = c__Iterator; - expr_0E.$PC = -2; - return expr_0E; + for (int i = 0; i < this.hediffs.Count; i++) + { + T t = (T)(this.hediffs[i] as T); + if (t != null) + { + yield return t; + } + } } public Hediff GetFirstHediffOfDef(HediffDef def, bool mustBeVisible = false) @@ -240,7 +239,7 @@ public float GetPartHealth(BodyPartRecord part) } } } - if (num < 0f) + if (num < 0.0) { num = 0f; } @@ -249,11 +248,11 @@ public float GetPartHealth(BodyPartRecord part) public BodyPartRecord GetBrain() { - foreach (BodyPartRecord current in this.GetNotMissingParts(BodyPartHeight.Undefined, BodyPartDepth.Undefined)) + foreach (BodyPartRecord notMissingPart in this.GetNotMissingParts(BodyPartHeight.Undefined, BodyPartDepth.Undefined)) { - if (current.def.tags.Contains("ConsciousnessSource")) + if (notMissingPart.def.tags.Contains("ConsciousnessSource")) { - return current; + return notMissingPart; } } return null; @@ -283,49 +282,55 @@ public bool HasHediff(HediffDef def, BodyPartRecord bodyPart) return false; } - [DebuggerHidden] public IEnumerable GetHediffsVerbs() { - HediffSet.c__Iterator213 c__Iterator = new HediffSet.c__Iterator213(); - c__Iterator.<>f__this = this; - HediffSet.c__Iterator213 expr_0E = c__Iterator; - expr_0E.$PC = -2; - return expr_0E; + for (int j = 0; j < this.hediffs.Count; j++) + { + HediffComp_VerbGiver vg = this.hediffs[j].TryGetComp(); + if (vg != null && !vg.VerbProperties.NullOrEmpty()) + { + List verbList = vg.VerbTracker.AllVerbs; + for (int i = 0; i < verbList.Count; i++) + { + yield return verbList[i]; + } + } + } } - [DebuggerHidden] public IEnumerable GetHediffsTendable() { - HediffSet.c__Iterator214 c__Iterator = new HediffSet.c__Iterator214(); - c__Iterator.<>f__this = this; - HediffSet.c__Iterator214 expr_0E = c__Iterator; - expr_0E.$PC = -2; - return expr_0E; + for (int i = 0; i < this.hediffs.Count; i++) + { + if (this.hediffs[i].TendableNow) + { + yield return this.hediffs[i]; + } + } } public bool HasTendableHediff(bool forAlert = false) { for (int i = 0; i < this.hediffs.Count; i++) { - if (!forAlert || this.hediffs[i].def.makesAlert) + if ((!forAlert || this.hediffs[i].def.makesAlert) && this.hediffs[i].TendableNow) { - if (this.hediffs[i].TendableNow) - { - return true; - } + return true; } } return false; } - [DebuggerHidden] public IEnumerable GetInjuriesTendable() { - HediffSet.c__Iterator215 c__Iterator = new HediffSet.c__Iterator215(); - c__Iterator.<>f__this = this; - HediffSet.c__Iterator215 expr_0E = c__Iterator; - expr_0E.$PC = -2; - return expr_0E; + for (int i = 0; i < this.hediffs.Count; i++) + { + Hediff_Injury inj = this.hediffs[i] as Hediff_Injury; + if (inj != null && inj.TendableNow) + { + yield return inj; + } + } } public bool HasTendableInjury() @@ -359,7 +364,7 @@ public bool HasTendedAndHealingInjury() for (int i = 0; i < this.hediffs.Count; i++) { Hediff_Injury hediff_Injury = this.hediffs[i] as Hediff_Injury; - if (hediff_Injury != null && hediff_Injury.CanHealFromTending() && hediff_Injury.Severity > 0f) + if (hediff_Injury != null && hediff_Injury.CanHealFromTending() && hediff_Injury.Severity > 0.0) { return true; } @@ -383,17 +388,23 @@ public IEnumerable GetInjuredParts() { return (from x in this.hediffs where x is Hediff_Injury - select x.Part).Distinct(); + select x.Part).Distinct(); } - [DebuggerHidden] public IEnumerable GetNaturallyHealingInjuredParts() { - HediffSet.c__Iterator216 c__Iterator = new HediffSet.c__Iterator216(); - c__Iterator.<>f__this = this; - HediffSet.c__Iterator216 expr_0E = c__Iterator; - expr_0E.$PC = -2; - return expr_0E; + foreach (BodyPartRecord injuredPart in this.GetInjuredParts()) + { + for (int i = 0; i < this.hediffs.Count; i++) + { + Hediff_Injury injury = this.hediffs[i] as Hediff_Injury; + if (injury != null && this.hediffs[i].Part == injuredPart && injury.CanHealNaturally()) + { + yield return injuredPart; + break; + } + } + } } public List GetMissingPartsCommonAncestors() @@ -405,41 +416,40 @@ public List GetMissingPartsCommonAncestors() return this.cachedMissingPartsCommonAncestors; } - [DebuggerHidden] public IEnumerable GetNotMissingParts(BodyPartHeight height = BodyPartHeight.Undefined, BodyPartDepth depth = BodyPartDepth.Undefined) { - HediffSet.c__Iterator217 c__Iterator = new HediffSet.c__Iterator217(); - c__Iterator.height = height; - c__Iterator.depth = depth; - c__Iterator.<$>height = height; - c__Iterator.<$>depth = depth; - c__Iterator.<>f__this = this; - HediffSet.c__Iterator217 expr_2A = c__Iterator; - expr_2A.$PC = -2; - return expr_2A; + List allPartsList = this.pawn.def.race.body.AllParts; + for (int i = 0; i < allPartsList.Count; i++) + { + BodyPartRecord part = allPartsList[i]; + if (!this.GetHediffs().Any((Func)((Hediff_MissingPart x) => x.Part == ((_003CGetNotMissingParts_003Ec__Iterator217)/*Error near IL_0074: stateMachine*/)._003Cpart_003E__2)) && (height == BodyPartHeight.Undefined || part.height == height) && (depth == BodyPartDepth.Undefined || part.depth == depth)) + { + yield return part; + } + } } public BodyPartRecord GetRandomNotMissingPart(DamageDef damDef, BodyPartHeight height = BodyPartHeight.Undefined, BodyPartDepth depth = BodyPartDepth.Undefined) { - IEnumerable notMissingParts; - if (this.GetNotMissingParts(height, depth).Any()) + IEnumerable enumerable = null; + if (this.GetNotMissingParts(height, depth).Any()) { - notMissingParts = this.GetNotMissingParts(height, depth); + enumerable = this.GetNotMissingParts(height, depth); + goto IL_0053; } - else + if (this.GetNotMissingParts(BodyPartHeight.Undefined, depth).Any()) { - if (!this.GetNotMissingParts(BodyPartHeight.Undefined, depth).Any()) - { - return null; - } - notMissingParts = this.GetNotMissingParts(BodyPartHeight.Undefined, depth); + enumerable = this.GetNotMissingParts(BodyPartHeight.Undefined, depth); + goto IL_0053; } - BodyPartRecord result; - if (notMissingParts.TryRandomElementByWeight((BodyPartRecord x) => x.coverageAbs * x.def.GetHitChanceFactorFor(damDef), out result)) + return null; + IL_0053: + BodyPartRecord result = default(BodyPartRecord); + if (enumerable.TryRandomElementByWeight((Func)((BodyPartRecord x) => x.coverageAbs * x.def.GetHitChanceFactorFor(damDef)), out result)) { return result; } - if (notMissingParts.TryRandomElementByWeight((BodyPartRecord x) => x.coverageAbs, out result)) + if (enumerable.TryRandomElementByWeight((Func)((BodyPartRecord x) => x.coverageAbs), out result)) { return result; } @@ -472,7 +482,7 @@ public float GetCoverageOfNotMissingNaturalParts(BodyPartRecord part) float num = 0f; this.coveragePartsStack.Clear(); this.coveragePartsStack.Push(part); - while (this.coveragePartsStack.Any()) + while (this.coveragePartsStack.Any()) { BodyPartRecord bodyPartRecord = this.coveragePartsStack.Pop(); num += bodyPartRecord.coverageAbs; @@ -508,7 +518,7 @@ private void CacheMissingPartsCommonAncestors() { Hediff_MissingPart hediff_MissingPart = (from x in this.GetHediffs() where x.Part == node - select x).FirstOrDefault(); + select x).FirstOrDefault(); if (hediff_MissingPart != null) { this.cachedMissingPartsCommonAncestors.Add(hediff_MissingPart); @@ -538,40 +548,44 @@ public bool HasDirectlyAddedPartFor(BodyPartRecord part) public bool PartOrAnyAncestorHasDirectlyAddedParts(BodyPartRecord part) { - return this.HasDirectlyAddedPartFor(part) || (part.parent != null && this.PartOrAnyAncestorHasDirectlyAddedParts(part.parent)); + if (this.HasDirectlyAddedPartFor(part)) + { + return true; + } + if (part.parent != null && this.PartOrAnyAncestorHasDirectlyAddedParts(part.parent)) + { + return true; + } + return false; } public bool AncestorHasDirectlyAddedParts(BodyPartRecord part) { - return part.parent != null && this.PartOrAnyAncestorHasDirectlyAddedParts(part.parent); + if (part.parent != null && this.PartOrAnyAncestorHasDirectlyAddedParts(part.parent)) + { + return true; + } + return false; } - [DebuggerHidden] public IEnumerable GetTendableNonInjuryNonMissingPartHediffs() { - HediffSet.c__Iterator218 c__Iterator = new HediffSet.c__Iterator218(); - c__Iterator.<>f__this = this; - HediffSet.c__Iterator218 expr_0E = c__Iterator; - expr_0E.$PC = -2; - return expr_0E; + for (int i = 0; i < this.hediffs.Count; i++) + { + if (!(this.hediffs[i] is Hediff_Injury) && !(this.hediffs[i] is Hediff_MissingPart) && this.hediffs[i].TendableNow) + { + yield return this.hediffs[i]; + } + } } public bool HasTendableNonInjuryNonMissingPartHediff(bool forAlert = false) { for (int i = 0; i < this.hediffs.Count; i++) { - if (!forAlert || this.hediffs[i].def.makesAlert) + if ((!forAlert || this.hediffs[i].def.makesAlert) && !(this.hediffs[i] is Hediff_Injury) && !(this.hediffs[i] is Hediff_MissingPart) && this.hediffs[i].TendableNow) { - if (!(this.hediffs[i] is Hediff_Injury)) - { - if (!(this.hediffs[i] is Hediff_MissingPart)) - { - if (this.hediffs[i].TendableNow) - { - return true; - } - } - } + return true; } } return false; @@ -579,35 +593,35 @@ public bool HasTendableNonInjuryNonMissingPartHediff(bool forAlert = false) private float CalculateBleedRate() { - if (!this.pawn.RaceProps.IsFlesh || this.pawn.health.Dead) + if (this.pawn.RaceProps.IsFlesh && !this.pawn.health.Dead) { - return 0f; - } - float num = 0f; - for (int i = 0; i < this.hediffs.Count; i++) - { - num += this.hediffs[i].BleedRate; + float num = 0f; + for (int i = 0; i < this.hediffs.Count; i++) + { + num += this.hediffs[i].BleedRate; + } + return num / this.pawn.HealthScale; } - return num / this.pawn.HealthScale; + return 0f; } private float CalculatePain() { - if (!this.pawn.RaceProps.IsFlesh || this.pawn.Dead) - { - return 0f; - } - float num = 0f; - for (int i = 0; i < this.hediffs.Count; i++) - { - num += this.hediffs[i].PainOffset; - } - float num2 = num / this.pawn.HealthScale; - for (int j = 0; j < this.hediffs.Count; j++) + if (this.pawn.RaceProps.IsFlesh && !this.pawn.Dead) { - num2 *= this.hediffs[j].PainFactor; + float num = 0f; + for (int i = 0; i < this.hediffs.Count; i++) + { + num += this.hediffs[i].PainOffset; + } + float num2 = num / this.pawn.HealthScale; + for (int j = 0; j < this.hediffs.Count; j++) + { + num2 *= this.hediffs[j].PainFactor; + } + return Mathf.Clamp(num2, 0f, 1f); } - return Mathf.Clamp(num2, 0f, 1f); + return 0f; } public void Clear() diff --git a/Assembly-CSharp/Verse/HediffStage.cs b/Assembly-CSharp/Verse/HediffStage.cs index 2704ad68f..c2c574319 100644 --- a/Assembly-CSharp/Verse/HediffStage.cs +++ b/Assembly-CSharp/Verse/HediffStage.cs @@ -1,5 +1,4 @@ using RimWorld; -using System; using System.Collections.Generic; namespace Verse @@ -56,7 +55,7 @@ public bool AffectsMemory { get { - return this.forgetMemoryThoughtMtbDays > 0f || this.pctConditionalThoughtsNullified > 0f; + return this.forgetMemoryThoughtMtbDays > 0.0 || this.pctConditionalThoughtsNullified > 0.0; } } @@ -64,7 +63,7 @@ public bool AffectsSocialInteractions { get { - return this.opinionOfOthersFactor != 1f; + return this.opinionOfOthersFactor != 1.0; } } diff --git a/Assembly-CSharp/Verse/HediffStatsUtility.cs b/Assembly-CSharp/Verse/HediffStatsUtility.cs index 18f07a7dc..74471a2b8 100644 --- a/Assembly-CSharp/Verse/HediffStatsUtility.cs +++ b/Assembly-CSharp/Verse/HediffStatsUtility.cs @@ -1,23 +1,129 @@ using RimWorld; using System; using System.Collections.Generic; -using System.Diagnostics; +using System.Linq; +using System.Text; namespace Verse { public static class HediffStatsUtility { - [DebuggerHidden] public static IEnumerable SpecialDisplayStats(HediffStage stage, Hediff instance) { - HediffStatsUtility.c__Iterator1D1 c__Iterator1D = new HediffStatsUtility.c__Iterator1D1(); - c__Iterator1D.instance = instance; - c__Iterator1D.stage = stage; - c__Iterator1D.<$>instance = instance; - c__Iterator1D.<$>stage = stage; - HediffStatsUtility.c__Iterator1D1 expr_23 = c__Iterator1D; - expr_23.$PC = -2; - return expr_23; + if (instance != null && instance.Bleeding) + { + yield return new StatDrawEntry(StatCategoryDefOf.Basics, "BleedingRate".Translate(), instance.BleedRate.ToStringPercent() + "/" + "LetterDay".Translate(), 0); + } + float painOffsetToDisplay = 0f; + if (instance != null) + { + painOffsetToDisplay = instance.PainOffset; + } + else if (stage != null) + { + painOffsetToDisplay = stage.painOffset; + } + if (painOffsetToDisplay != 0.0) + { + if (painOffsetToDisplay > 0.0 && painOffsetToDisplay < 0.0099999997764825821) + { + painOffsetToDisplay = 0.01f; + } + if (painOffsetToDisplay < 0.0 && painOffsetToDisplay > -0.0099999997764825821) + { + painOffsetToDisplay = -0.01f; + } + yield return new StatDrawEntry(StatCategoryDefOf.Basics, "Pain".Translate(), ((float)(painOffsetToDisplay * 100.0)).ToString("+###0;-###0") + "%", 0); + } + float painFactorToDisplay = 1f; + if (instance != null) + { + painFactorToDisplay = instance.PainFactor; + } + else if (stage != null) + { + painFactorToDisplay = stage.painFactor; + } + if (painFactorToDisplay != 1.0) + { + yield return new StatDrawEntry(StatCategoryDefOf.Basics, "Pain".Translate(), "x" + painFactorToDisplay.ToStringPercent(), 0); + } + if (stage != null && stage.partEfficiencyOffset != 0.0) + { + yield return new StatDrawEntry(StatCategoryDefOf.Basics, "PartEfficiency".Translate(), stage.partEfficiencyOffset.ToStringByStyle(ToStringStyle.PercentZero, ToStringNumberSense.Offset), 0); + } + List capModsToDisplay = null; + if (instance != null) + { + capModsToDisplay = instance.CapMods; + } + else if (stage != null) + { + capModsToDisplay = stage.capMods; + } + if (capModsToDisplay != null) + { + for (int j = 0; j < capModsToDisplay.Count; j++) + { + if (capModsToDisplay[j].offset != 0.0) + { + yield return new StatDrawEntry(StatCategoryDefOf.Basics, capModsToDisplay[j].capacity.GetLabelFor(true, true).CapitalizeFirst(), ((float)(capModsToDisplay[j].offset * 100.0)).ToString("+#;-#") + "%", 0); + } + if (capModsToDisplay[j].postFactor != 1.0) + { + yield return new StatDrawEntry(StatCategoryDefOf.Basics, capModsToDisplay[j].capacity.GetLabelFor(true, true).CapitalizeFirst(), "x" + capModsToDisplay[j].postFactor.ToStringPercent(), 0); + } + if (capModsToDisplay[j].SetMaxDefined) + { + yield return new StatDrawEntry(StatCategoryDefOf.Basics, capModsToDisplay[j].capacity.GetLabelFor(true, true).CapitalizeFirst(), "max".Translate() + " " + capModsToDisplay[j].setMax.ToStringPercent(), 0); + } + } + } + if (stage != null) + { + if (stage.AffectsMemory || stage.AffectsSocialInteractions) + { + StringBuilder affectsSb = new StringBuilder(); + if (stage.AffectsMemory) + { + if (affectsSb.Length != 0) + { + affectsSb.Append(", "); + } + affectsSb.Append("MemoryLower".Translate()); + } + if (stage.AffectsSocialInteractions) + { + if (affectsSb.Length != 0) + { + affectsSb.Append(", "); + } + affectsSb.Append("SocialInteractionsLower".Translate()); + } + yield return new StatDrawEntry(StatCategoryDefOf.Basics, "Affects".Translate(), affectsSb.ToString(), 0); + } + if (stage.hungerRateFactor != 1.0) + { + yield return new StatDrawEntry(StatCategoryDefOf.Basics, "HungerRate".Translate(), "x" + stage.hungerRateFactor.ToStringPercent(), 0); + } + if (stage.restFallFactor != 1.0) + { + yield return new StatDrawEntry(StatCategoryDefOf.Basics, "Tiredness".Translate(), "x" + stage.restFallFactor.ToStringPercent(), 0); + } + if (stage.makeImmuneTo != null) + { + yield return new StatDrawEntry(StatCategoryDefOf.Basics, "PreventsInfection".Translate(), GenText.ToCommaList(from im in stage.makeImmuneTo + select im.label, false).CapitalizeFirst(), 0); + } + if (stage.statOffsets != null) + { + for (int i = 0; i < stage.statOffsets.Count; i++) + { + StatModifier sm = stage.statOffsets[i]; + yield return new StatDrawEntry(StatCategoryDefOf.Basics, sm.stat.LabelCap, sm.ToStringAsOffset, 0); + } + } + } } } } diff --git a/Assembly-CSharp/Verse/HediffUtility.cs b/Assembly-CSharp/Verse/HediffUtility.cs index f3ed63bbf..c0e72d45b 100644 --- a/Assembly-CSharp/Verse/HediffUtility.cs +++ b/Assembly-CSharp/Verse/HediffUtility.cs @@ -1,5 +1,3 @@ -using System; - namespace Verse { public static class HediffUtility @@ -9,20 +7,20 @@ public static T TryGetComp(this Hediff hd) where T : HediffComp HediffWithComps hediffWithComps = hd as HediffWithComps; if (hediffWithComps == null) { - return (T)((object)null); + return (T)null; } if (hediffWithComps.comps != null) { for (int i = 0; i < hediffWithComps.comps.Count; i++) { - T t = hediffWithComps.comps[i] as T; - if (t != null) + T val = (T)(hediffWithComps.comps[i] as T); + if (val != null) { - return t; + return val; } } } - return (T)((object)null); + return (T)null; } public static bool IsTended(this Hediff hd) @@ -33,7 +31,11 @@ public static bool IsTended(this Hediff hd) return false; } HediffComp_TendDuration hediffComp_TendDuration = hediffWithComps.TryGetComp(); - return hediffComp_TendDuration != null && hediffComp_TendDuration.IsTended; + if (hediffComp_TendDuration == null) + { + return false; + } + return hediffComp_TendDuration.IsTended; } public static bool IsOld(this Hediff hd) @@ -44,7 +46,11 @@ public static bool IsOld(this Hediff hd) return false; } HediffComp_GetsOld hediffComp_GetsOld = hediffWithComps.TryGetComp(); - return hediffComp_GetsOld != null && hediffComp_GetsOld.IsOld; + if (hediffComp_GetsOld == null) + { + return false; + } + return hediffComp_GetsOld.IsOld; } public static bool FullyImmune(this Hediff hd) @@ -55,7 +61,11 @@ public static bool FullyImmune(this Hediff hd) return false; } HediffComp_Immunizable hediffComp_Immunizable = hediffWithComps.TryGetComp(); - return hediffComp_Immunizable != null && hediffComp_Immunizable.FullyImmune; + if (hediffComp_Immunizable == null) + { + return false; + } + return hediffComp_Immunizable.FullyImmune; } public static bool CanHealFromTending(this Hediff_Injury hd) diff --git a/Assembly-CSharp/Verse/HediffWithComps.cs b/Assembly-CSharp/Verse/HediffWithComps.cs index 85d59d3c8..c17423b75 100644 --- a/Assembly-CSharp/Verse/HediffWithComps.cs +++ b/Assembly-CSharp/Verse/HediffWithComps.cs @@ -129,7 +129,7 @@ public override void PostTick() { this.comps[i].CompPostTick(ref num); } - if (num != 0f) + if (num != 0.0) { this.Severity += num; } @@ -202,13 +202,13 @@ public override void PostMake() private void InitializeComps() { - if (this.def.comps != null) + if (base.def.comps != null) { this.comps = new List(); - for (int i = 0; i < this.def.comps.Count; i++) + for (int i = 0; i < base.def.comps.Count; i++) { - HediffComp hediffComp = (HediffComp)Activator.CreateInstance(this.def.comps[i].compClass); - hediffComp.props = this.def.comps[i]; + HediffComp hediffComp = (HediffComp)Activator.CreateInstance(base.def.comps[i].compClass); + hediffComp.props = base.def.comps[i]; hediffComp.parent = this; this.comps.Add(hediffComp); } @@ -223,23 +223,12 @@ public override string DebugString() { for (int i = 0; i < this.comps.Count; i++) { - string str; - if (this.comps[i].ToString().Contains('_')) - { - str = this.comps[i].ToString().Split(new char[] - { - '_' - })[1]; - } - else - { - str = this.comps[i].ToString(); - } + string str = (!this.comps[i].ToString().Contains('_')) ? this.comps[i].ToString() : this.comps[i].ToString().Split('_')[1]; stringBuilder.AppendLine("--" + str); string text = this.comps[i].CompDebugString(); if (!text.NullOrEmpty()) { - stringBuilder.AppendLine(text.TrimEnd(new char[0]).Indented()); + stringBuilder.AppendLine(text.TrimEnd().Indented()); } } } diff --git a/Assembly-CSharp/Verse/Hediff_AddedPart.cs b/Assembly-CSharp/Verse/Hediff_AddedPart.cs index 9c9a0be6c..3e2b15dfd 100644 --- a/Assembly-CSharp/Verse/Hediff_AddedPart.cs +++ b/Assembly-CSharp/Verse/Hediff_AddedPart.cs @@ -1,5 +1,4 @@ using RimWorld; -using System; using System.Text; namespace Verse @@ -20,7 +19,7 @@ public override string TipStringExtra { StringBuilder stringBuilder = new StringBuilder(); stringBuilder.Append(base.TipStringExtra); - stringBuilder.AppendLine("Efficiency".Translate() + ": " + this.def.addedPartProps.partEfficiency.ToStringPercent()); + stringBuilder.AppendLine("Efficiency".Translate() + ": " + base.def.addedPartProps.partEfficiency.ToStringPercent()); return stringBuilder.ToString(); } } @@ -29,17 +28,19 @@ public override void PostAdd(DamageInfo? dinfo) { if (base.Part == null) { - Log.Error("Part is null. It should be set before PostAdd for " + this.def + "."); - return; + Log.Error("Part is null. It should be set before PostAdd for " + base.def + "."); } - this.pawn.health.RestorePart(base.Part, this, false); - for (int i = 0; i < base.Part.parts.Count; i++) + else { - Hediff_MissingPart hediff_MissingPart = (Hediff_MissingPart)HediffMaker.MakeHediff(HediffDefOf.MissingBodyPart, this.pawn, null); - hediff_MissingPart.IsFresh = true; - hediff_MissingPart.lastInjury = HediffDefOf.SurgicalCut; - hediff_MissingPart.Part = base.Part.parts[i]; - this.pawn.health.hediffSet.AddDirect(hediff_MissingPart, null); + base.pawn.health.RestorePart(base.Part, this, false); + for (int i = 0; i < base.Part.parts.Count; i++) + { + Hediff_MissingPart hediff_MissingPart = (Hediff_MissingPart)HediffMaker.MakeHediff(HediffDefOf.MissingBodyPart, base.pawn, null); + hediff_MissingPart.IsFresh = true; + hediff_MissingPart.lastInjury = HediffDefOf.SurgicalCut; + hediff_MissingPart.Part = base.Part.parts[i]; + base.pawn.health.hediffSet.AddDirect(hediff_MissingPart, default(DamageInfo?)); + } } } } diff --git a/Assembly-CSharp/Verse/Hediff_Alcohol.cs b/Assembly-CSharp/Verse/Hediff_Alcohol.cs index 8737330e8..26da2db50 100644 --- a/Assembly-CSharp/Verse/Hediff_Alcohol.cs +++ b/Assembly-CSharp/Verse/Hediff_Alcohol.cs @@ -1,5 +1,4 @@ using RimWorld; -using System; namespace Verse { @@ -10,18 +9,18 @@ public class Hediff_Alcohol : HediffWithComps public override void Tick() { base.Tick(); - if (this.CurStageIndex >= 3 && this.pawn.IsHashIntervalTick(300) && this.HangoverSusceptible(this.pawn)) + if (this.CurStageIndex >= 3 && base.pawn.IsHashIntervalTick(300) && this.HangoverSusceptible(base.pawn)) { - Hediff hediff = this.pawn.health.hediffSet.GetFirstHediffOfDef(HediffDefOf.Hangover, false); - if (hediff != null) + Hediff firstHediffOfDef = base.pawn.health.hediffSet.GetFirstHediffOfDef(HediffDefOf.Hangover, false); + if (firstHediffOfDef != null) { - hediff.Severity = 1f; + firstHediffOfDef.Severity = 1f; } else { - hediff = HediffMaker.MakeHediff(HediffDefOf.Hangover, this.pawn, null); - hediff.Severity = 1f; - this.pawn.health.AddHediff(hediff, null, null); + firstHediffOfDef = HediffMaker.MakeHediff(HediffDefOf.Hangover, base.pawn, null); + firstHediffOfDef.Severity = 1f; + base.pawn.health.AddHediff(firstHediffOfDef, null, default(DamageInfo?)); } } } diff --git a/Assembly-CSharp/Verse/Hediff_Hangover.cs b/Assembly-CSharp/Verse/Hediff_Hangover.cs index d1c3ba028..18ed37769 100644 --- a/Assembly-CSharp/Verse/Hediff_Hangover.cs +++ b/Assembly-CSharp/Verse/Hediff_Hangover.cs @@ -1,5 +1,4 @@ using RimWorld; -using System; namespace Verse { @@ -9,7 +8,11 @@ public override bool Visible { get { - return !this.pawn.health.hediffSet.HasHediff(HediffDefOf.AlcoholHigh) && base.Visible; + if (base.pawn.health.hediffSet.HasHediff(HediffDefOf.AlcoholHigh)) + { + return false; + } + return base.Visible; } } } diff --git a/Assembly-CSharp/Verse/Hediff_Implant.cs b/Assembly-CSharp/Verse/Hediff_Implant.cs index 905b76cca..b9929a742 100644 --- a/Assembly-CSharp/Verse/Hediff_Implant.cs +++ b/Assembly-CSharp/Verse/Hediff_Implant.cs @@ -1,5 +1,3 @@ -using System; - namespace Verse { public class Hediff_Implant : HediffWithComps @@ -16,8 +14,7 @@ public override void PostAdd(DamageInfo? dinfo) { if (base.Part == null) { - Log.Error("Part is null. It should be set before PostAdd for " + this.def + "."); - return; + Log.Error("Part is null. It should be set before PostAdd for " + base.def + "."); } } } diff --git a/Assembly-CSharp/Verse/Hediff_Injury.cs b/Assembly-CSharp/Verse/Hediff_Injury.cs index e1c603372..118229d23 100644 --- a/Assembly-CSharp/Verse/Hediff_Injury.cs +++ b/Assembly-CSharp/Verse/Hediff_Injury.cs @@ -1,4 +1,3 @@ -using System; using System.Text; using UnityEngine; @@ -47,25 +46,25 @@ public override string LabelInBrackets { StringBuilder stringBuilder = new StringBuilder(); stringBuilder.Append(base.LabelInBrackets); - if (this.sourceHediffDef != null) + if (base.sourceHediffDef != null) { if (stringBuilder.Length != 0) { stringBuilder.Append(", "); } - stringBuilder.Append(this.sourceHediffDef.label); + stringBuilder.Append(base.sourceHediffDef.label); } - else if (this.source != null) + else if (base.source != null) { if (stringBuilder.Length != 0) { stringBuilder.Append(", "); } - stringBuilder.Append(this.source.label); - if (this.sourceBodyPartGroup != null) + stringBuilder.Append(base.source.label); + if (base.sourceBodyPartGroup != null) { stringBuilder.Append(" - "); - stringBuilder.Append(this.sourceBodyPartGroup.label); + stringBuilder.Append(base.sourceBodyPartGroup.label); } } return stringBuilder.ToString(); @@ -88,9 +87,9 @@ public override string SeverityLabel { get { - if (this.Severity == 0f) + if (this.Severity == 0.0) { - return null; + return (string)null; } return this.Severity.ToString("0.##"); } @@ -100,11 +99,11 @@ public override float SummaryHealthPercentImpact { get { - if (this.IsOld() || !this.Visible) + if (!this.IsOld() && this.Visible) { - return 0f; + return (float)(this.Severity / (75.0 * base.pawn.HealthScale)); } - return this.Severity / (75f * this.pawn.HealthScale); + return 0f; } } @@ -112,16 +111,16 @@ public override float PainOffset { get { - if (this.pawn.Dead || this.pawn.health.hediffSet.PartOrAnyAncestorHasDirectlyAddedParts(base.Part) || this.causesNoPain) - { - return 0f; - } - HediffComp_GetsOld hediffComp_GetsOld = this.TryGetComp(); - if (hediffComp_GetsOld != null && hediffComp_GetsOld.IsOld) + if (!base.pawn.Dead && !base.pawn.health.hediffSet.PartOrAnyAncestorHasDirectlyAddedParts(base.Part) && !base.causesNoPain) { - return this.Severity * this.def.injuryProps.averagePainPerSeverityOld * hediffComp_GetsOld.painFactor; + HediffComp_GetsOld hediffComp_GetsOld = this.TryGetComp(); + if (hediffComp_GetsOld != null && hediffComp_GetsOld.IsOld) + { + return this.Severity * base.def.injuryProps.averagePainPerSeverityOld * hediffComp_GetsOld.painFactor; + } + return this.Severity * base.def.injuryProps.painPerSeverity; } - return this.Severity * this.def.injuryProps.painPerSeverity; + return 0f; } } @@ -129,7 +128,7 @@ public override float BleedRate { get { - if (this.pawn.Dead) + if (base.pawn.Dead) { return 0f; } @@ -137,20 +136,20 @@ public override float BleedRate { return 0f; } - if (base.Part.def.IsSolid(base.Part, this.pawn.health.hediffSet.hediffs) || this.IsTended() || this.IsOld()) - { - return 0f; - } - if (this.pawn.health.hediffSet.PartOrAnyAncestorHasDirectlyAddedParts(base.Part)) + if (!base.Part.def.IsSolid(base.Part, base.pawn.health.hediffSet.hediffs) && !this.IsTended() && !this.IsOld()) { - return 0f; - } - float num = this.Severity * this.def.injuryProps.bleedRate; - if (base.Part != null) - { - num *= base.Part.def.bleedingRateMultiplier; + if (base.pawn.health.hediffSet.PartOrAnyAncestorHasDirectlyAddedParts(base.Part)) + { + return 0f; + } + float num = this.Severity * base.def.injuryProps.bleedRate; + if (base.Part != null) + { + num *= base.Part.def.bleedingRateMultiplier; + } + return num; } - return num; + return 0f; } } @@ -168,7 +167,7 @@ private bool BleedingStoppedDueToAge { get { - return this.ageTicks >= this.AgeTicksToStopBleeding; + return base.ageTicks >= this.AgeTicksToStopBleeding; } } @@ -179,27 +178,31 @@ public override void Tick() bool bleedingStoppedDueToAge2 = this.BleedingStoppedDueToAge; if (bleedingStoppedDueToAge != bleedingStoppedDueToAge2) { - this.pawn.health.Notify_HediffChanged(this); + base.pawn.health.Notify_HediffChanged(this); } } public override void Heal(float amount) { this.Severity -= amount; - if (this.comps != null) + if (base.comps != null) { - for (int i = 0; i < this.comps.Count; i++) + for (int i = 0; i < base.comps.Count; i++) { - this.comps[i].CompPostInjuryHeal(amount); + base.comps[i].CompPostInjuryHeal(amount); } } - this.pawn.health.Notify_HediffChanged(this); + base.pawn.health.Notify_HediffChanged(this); } public override bool TryMergeWith(Hediff other) { Hediff_Injury hediff_Injury = other as Hediff_Injury; - return hediff_Injury != null && hediff_Injury.def == this.def && hediff_Injury.Part == base.Part && !hediff_Injury.IsTended() && !hediff_Injury.IsOld() && !this.IsTended() && !this.IsOld() && this.def.injuryProps.canMerge && base.TryMergeWith(other); + if (hediff_Injury != null && hediff_Injury.def == base.def && hediff_Injury.Part == base.Part && !hediff_Injury.IsTended() && !hediff_Injury.IsOld() && !this.IsTended() && !this.IsOld() && base.def.injuryProps.canMerge) + { + return base.TryMergeWith(other); + } + return false; } } } diff --git a/Assembly-CSharp/Verse/Hediff_MissingPart.cs b/Assembly-CSharp/Verse/Hediff_MissingPart.cs index b6a1e24ce..6e64d97b5 100644 --- a/Assembly-CSharp/Verse/Hediff_MissingPart.cs +++ b/Assembly-CSharp/Verse/Hediff_MissingPart.cs @@ -1,4 +1,3 @@ -using System; using System.Text; namespace Verse @@ -17,11 +16,11 @@ public override float SummaryHealthPercentImpact { return 0f; } - if (base.Part.def.tags.NullOrEmpty() && base.Part.parts.NullOrEmpty() && !base.Bleeding) + if (base.Part.def.tags.NullOrEmpty() && base.Part.parts.NullOrEmpty() && !base.Bleeding) { return 0f; } - return (float)base.Part.def.hitPoints / (75f * this.pawn.HealthScale); + return (float)((float)base.Part.def.hitPoints / (75.0 * base.pawn.HealthScale)); } } @@ -49,16 +48,16 @@ public override string LabelBase { return "RemovedBodyPart".Translate(); } - if (this.lastInjury == null || base.Part.depth == BodyPartDepth.Inside) + if (this.lastInjury != null && base.Part.depth != BodyPartDepth.Inside) { - bool solid = base.Part.def.IsSolid(base.Part, this.pawn.health.hediffSet.hediffs); - return HealthUtility.GetGeneralDestroyedPartLabel(base.Part, this.IsFreshNonSolidExtremity, solid); - } - if (base.Part.def.useDestroyedOutLabel && !this.lastInjury.injuryProps.destroyedOutLabel.NullOrEmpty()) - { - return this.lastInjury.injuryProps.destroyedOutLabel; + if (base.Part.def.useDestroyedOutLabel && !this.lastInjury.injuryProps.destroyedOutLabel.NullOrEmpty()) + { + return this.lastInjury.injuryProps.destroyedOutLabel; + } + return this.lastInjury.injuryProps.destroyedLabel; } - return this.lastInjury.injuryProps.destroyedLabel; + bool solid = base.Part.def.IsSolid(base.Part, base.pawn.health.hediffSet.hediffs); + return HealthUtility.GetGeneralDestroyedPartLabel(base.Part, this.IsFreshNonSolidExtremity, solid); } } @@ -84,11 +83,11 @@ public override float BleedRate { get { - if (this.pawn.Dead || !this.IsFreshNonSolidExtremity || this.ParentIsMissing) + if (!base.pawn.Dead && this.IsFreshNonSolidExtremity && !this.ParentIsMissing) { - return 0f; + return base.Part.def.GetMaxHealth(base.pawn) * base.def.injuryProps.bleedRate * base.Part.def.bleedingRateMultiplier; } - return base.Part.def.GetMaxHealth(this.pawn) * this.def.injuryProps.bleedRate * base.Part.def.bleedingRateMultiplier; + return 0f; } } @@ -96,11 +95,11 @@ public override float PainOffset { get { - if (this.pawn.Dead || this.causesNoPain || !this.IsFreshNonSolidExtremity || this.ParentIsMissing) + if (!base.pawn.Dead && !base.causesNoPain && this.IsFreshNonSolidExtremity && !this.ParentIsMissing) { - return 0f; + return base.Part.def.GetMaxHealth(base.pawn) * base.def.injuryProps.painPerSeverity; } - return base.Part.def.GetMaxHealth(this.pawn) * this.def.injuryProps.painPerSeverity; + return 0f; } } @@ -108,9 +107,9 @@ private bool ParentIsMissing { get { - for (int i = 0; i < this.pawn.health.hediffSet.hediffs.Count; i++) + for (int i = 0; i < base.pawn.health.hediffSet.hediffs.Count; i++) { - Hediff_MissingPart hediff_MissingPart = this.pawn.health.hediffSet.hediffs[i] as Hediff_MissingPart; + Hediff_MissingPart hediff_MissingPart = base.pawn.health.hediffSet.hediffs[i] as Hediff_MissingPart; if (hediff_MissingPart != null && hediff_MissingPart.Part == base.Part.parent) { return true; @@ -136,7 +135,15 @@ public bool IsFreshNonSolidExtremity { get { - return Current.ProgramState != ProgramState.Entry && this.IsFresh && base.Part.depth != BodyPartDepth.Inside && !base.Part.def.IsSolid(base.Part, this.pawn.health.hediffSet.hediffs) && !this.ParentIsMissing; + if (Current.ProgramState == ProgramState.Entry) + { + return false; + } + if (this.IsFresh && base.Part.depth != BodyPartDepth.Inside && !base.Part.def.IsSolid(base.Part, base.pawn.health.hediffSet.hediffs) && !this.ParentIsMissing) + { + return true; + } + return false; } } @@ -144,7 +151,7 @@ private bool TicksAfterNoLongerFreshPassed { get { - return this.ageTicks >= 90000; + return base.ageTicks >= 90000; } } @@ -155,7 +162,7 @@ public override void Tick() bool ticksAfterNoLongerFreshPassed2 = this.TicksAfterNoLongerFreshPassed; if (ticksAfterNoLongerFreshPassed != ticksAfterNoLongerFreshPassed2) { - this.pawn.health.Notify_HediffChanged(this); + base.pawn.health.Notify_HediffChanged(this); } } @@ -163,19 +170,19 @@ public override void Tended(float quality, int batchPosition = 0) { base.Tended(quality, batchPosition); this.IsFresh = false; - this.pawn.health.Notify_HediffChanged(this); + base.pawn.health.Notify_HediffChanged(this); } public override void PostAdd(DamageInfo? dinfo) { - this.pawn.health.RestorePart(base.Part, this, false); + base.pawn.health.RestorePart(base.Part, this, false); for (int i = 0; i < base.Part.parts.Count; i++) { - Hediff_MissingPart hediff_MissingPart = (Hediff_MissingPart)HediffMaker.MakeHediff(this.def, this.pawn, null); + Hediff_MissingPart hediff_MissingPart = (Hediff_MissingPart)HediffMaker.MakeHediff(base.def, base.pawn, null); hediff_MissingPart.IsFresh = false; hediff_MissingPart.lastInjury = this.lastInjury; hediff_MissingPart.Part = base.Part.parts[i]; - this.pawn.health.hediffSet.AddDirect(hediff_MissingPart, null); + base.pawn.health.hediffSet.AddDirect(hediff_MissingPart, default(DamageInfo?)); } } diff --git a/Assembly-CSharp/Verse/Hediff_Pregnant.cs b/Assembly-CSharp/Verse/Hediff_Pregnant.cs index 2b7ce9bd3..6a69086a8 100644 --- a/Assembly-CSharp/Verse/Hediff_Pregnant.cs +++ b/Assembly-CSharp/Verse/Hediff_Pregnant.cs @@ -1,6 +1,5 @@ using RimWorld; using RimWorld.Planet; -using System; using System.Collections.Generic; using System.Text; using UnityEngine; @@ -34,7 +33,7 @@ private bool IsSeverelyWounded get { float num = 0f; - List hediffs = this.pawn.health.hediffSet.hediffs; + List hediffs = base.pawn.health.hediffSet.hediffs; for (int i = 0; i < hediffs.Count; i++) { if (hediffs[i] is Hediff_Injury && !hediffs[i].IsOld()) @@ -42,66 +41,57 @@ private bool IsSeverelyWounded num += hediffs[i].Severity; } } - List missingPartsCommonAncestors = this.pawn.health.hediffSet.GetMissingPartsCommonAncestors(); + List missingPartsCommonAncestors = base.pawn.health.hediffSet.GetMissingPartsCommonAncestors(); for (int j = 0; j < missingPartsCommonAncestors.Count; j++) { if (missingPartsCommonAncestors[j].IsFreshNonSolidExtremity) { - num += missingPartsCommonAncestors[j].Part.def.GetMaxHealth(this.pawn); + num += missingPartsCommonAncestors[j].Part.def.GetMaxHealth(base.pawn); } } - return num > 38f * this.pawn.RaceProps.baseHealthScale; + return num > 38.0 * base.pawn.RaceProps.baseHealthScale; } } public override void Tick() { - this.ageTicks++; - if (this.pawn.IsHashIntervalTick(1000)) + base.ageTicks++; + if (base.pawn.IsHashIntervalTick(1000)) { - if (this.pawn.needs.food != null && this.pawn.needs.food.CurCategory == HungerCategory.Starving && Rand.MTBEventOccurs(0.5f, 60000f, 1000f)) + if (base.pawn.needs.food != null && base.pawn.needs.food.CurCategory == HungerCategory.Starving && Rand.MTBEventOccurs(0.5f, 60000f, 1000f)) { - if (this.Visible && PawnUtility.ShouldSendNotificationAbout(this.pawn)) + if (this.Visible && PawnUtility.ShouldSendNotificationAbout(base.pawn)) { - Messages.Message("MessageMiscarriedStarvation".Translate(new object[] - { - this.pawn.LabelIndefinite() - }).CapitalizeFirst(), this.pawn, MessageSound.Negative); + Messages.Message("MessageMiscarriedStarvation".Translate(base.pawn.LabelIndefinite()).CapitalizeFirst(), (Thing)base.pawn, MessageSound.Negative); } this.Miscarry(); return; } if (this.IsSeverelyWounded && Rand.MTBEventOccurs(0.5f, 60000f, 1000f)) { - if (this.Visible && PawnUtility.ShouldSendNotificationAbout(this.pawn)) + if (this.Visible && PawnUtility.ShouldSendNotificationAbout(base.pawn)) { - Messages.Message("MessageMiscarriedPoorHealth".Translate(new object[] - { - this.pawn.LabelIndefinite() - }).CapitalizeFirst(), this.pawn, MessageSound.Negative); + Messages.Message("MessageMiscarriedPoorHealth".Translate(base.pawn.LabelIndefinite()).CapitalizeFirst(), (Thing)base.pawn, MessageSound.Negative); } this.Miscarry(); return; } } - this.GestationProgress += 1f / (this.pawn.RaceProps.gestationPeriodDays * 60000f); - if (this.GestationProgress >= 1f) + this.GestationProgress += (float)(1.0 / (base.pawn.RaceProps.gestationPeriodDays * 60000.0)); + if (this.GestationProgress >= 1.0) { - if (this.Visible && PawnUtility.ShouldSendNotificationAbout(this.pawn)) + if (this.Visible && PawnUtility.ShouldSendNotificationAbout(base.pawn)) { - Messages.Message("MessageGaveBirth".Translate(new object[] - { - this.pawn.LabelIndefinite() - }).CapitalizeFirst(), this.pawn, MessageSound.Benefit); + Messages.Message("MessageGaveBirth".Translate(base.pawn.LabelIndefinite()).CapitalizeFirst(), (Thing)base.pawn, MessageSound.Benefit); } - Hediff_Pregnant.DoBirthSpawn(this.pawn, this.father); - this.pawn.health.RemoveHediff(this); + Hediff_Pregnant.DoBirthSpawn(base.pawn, this.father); + base.pawn.health.RemoveHediff(this); } } private void Miscarry() { - this.pawn.health.RemoveHediff(this); + base.pawn.health.RemoveHediff(this); } public static void DoBirthSpawn(Pawn mother, Pawn father) @@ -111,9 +101,9 @@ public static void DoBirthSpawn(Pawn mother, Pawn father) { num = 1; } - PawnGenerationRequest request = new PawnGenerationRequest(mother.kindDef, mother.Faction, PawnGenerationContext.NonPlayer, -1, false, true, false, false, true, false, 1f, false, true, true, false, false, null, null, null, null, null, null); + PawnGenerationRequest request = new PawnGenerationRequest(mother.kindDef, mother.Faction, PawnGenerationContext.NonPlayer, -1, false, true, false, false, true, false, 1f, false, true, true, false, false, null, default(float?), default(float?), default(Gender?), default(float?), (string)null); Pawn pawn = null; - for (int i = 0; i < num; i++) + for (int num2 = 0; num2 < num; num2++) { pawn = PawnGenerator.GeneratePawn(request); if (PawnUtility.TrySpawnHatchedOrBornPawn(pawn, mother)) @@ -161,7 +151,7 @@ public override string DebugString() StringBuilder stringBuilder = new StringBuilder(); stringBuilder.Append(base.DebugString()); stringBuilder.AppendLine("Gestation progress: " + this.GestationProgress.ToStringPercent()); - stringBuilder.AppendLine("Time left: " + ((int)((1f - this.GestationProgress) * this.pawn.RaceProps.gestationPeriodDays * 60000f)).ToStringTicksToPeriod(true, false, true)); + stringBuilder.AppendLine("Time left: " + ((int)((1.0 - this.GestationProgress) * base.pawn.RaceProps.gestationPeriodDays * 60000.0)).ToStringTicksToPeriod(true, false, true)); return stringBuilder.ToString(); } } diff --git a/Assembly-CSharp/Verse/ICellBoolGiver.cs b/Assembly-CSharp/Verse/ICellBoolGiver.cs index 1244dafa2..ed6b07d90 100644 --- a/Assembly-CSharp/Verse/ICellBoolGiver.cs +++ b/Assembly-CSharp/Verse/ICellBoolGiver.cs @@ -1,4 +1,3 @@ -using System; using UnityEngine; namespace Verse diff --git a/Assembly-CSharp/Verse/IExposable.cs b/Assembly-CSharp/Verse/IExposable.cs index 0aa7365af..7af69ff7e 100644 --- a/Assembly-CSharp/Verse/IExposable.cs +++ b/Assembly-CSharp/Verse/IExposable.cs @@ -1,5 +1,3 @@ -using System; - namespace Verse { public interface IExposable diff --git a/Assembly-CSharp/Verse/IFullPoolable.cs b/Assembly-CSharp/Verse/IFullPoolable.cs index e14e5e86f..8443536af 100644 --- a/Assembly-CSharp/Verse/IFullPoolable.cs +++ b/Assembly-CSharp/Verse/IFullPoolable.cs @@ -1,5 +1,3 @@ -using System; - namespace Verse { public interface IFullPoolable diff --git a/Assembly-CSharp/Verse/ILoadReferenceable.cs b/Assembly-CSharp/Verse/ILoadReferenceable.cs index 995e42ecc..968346ec0 100644 --- a/Assembly-CSharp/Verse/ILoadReferenceable.cs +++ b/Assembly-CSharp/Verse/ILoadReferenceable.cs @@ -1,5 +1,3 @@ -using System; - namespace Verse { public interface ILoadReferenceable diff --git a/Assembly-CSharp/Verse/ISelectable.cs b/Assembly-CSharp/Verse/ISelectable.cs index 63c0d94bf..2c531e44f 100644 --- a/Assembly-CSharp/Verse/ISelectable.cs +++ b/Assembly-CSharp/Verse/ISelectable.cs @@ -1,4 +1,3 @@ -using System; using System.Collections.Generic; namespace Verse diff --git a/Assembly-CSharp/Verse/IStrippable.cs b/Assembly-CSharp/Verse/IStrippable.cs index 5a2a4ef6d..ad7651113 100644 --- a/Assembly-CSharp/Verse/IStrippable.cs +++ b/Assembly-CSharp/Verse/IStrippable.cs @@ -1,5 +1,3 @@ -using System; - namespace Verse { public interface IStrippable diff --git a/Assembly-CSharp/Verse/IThingHolder.cs b/Assembly-CSharp/Verse/IThingHolder.cs index 47fde5c54..ad30431a7 100644 --- a/Assembly-CSharp/Verse/IThingHolder.cs +++ b/Assembly-CSharp/Verse/IThingHolder.cs @@ -1,4 +1,3 @@ -using System; using System.Collections.Generic; namespace Verse diff --git a/Assembly-CSharp/Verse/IVerbOwner.cs b/Assembly-CSharp/Verse/IVerbOwner.cs index 5e7386993..25fc3323a 100644 --- a/Assembly-CSharp/Verse/IVerbOwner.cs +++ b/Assembly-CSharp/Verse/IVerbOwner.cs @@ -1,4 +1,3 @@ -using System; using System.Collections.Generic; namespace Verse diff --git a/Assembly-CSharp/Verse/ImmediateWindow.cs b/Assembly-CSharp/Verse/ImmediateWindow.cs index e26d368b2..358e0814f 100644 --- a/Assembly-CSharp/Verse/ImmediateWindow.cs +++ b/Assembly-CSharp/Verse/ImmediateWindow.cs @@ -11,7 +11,7 @@ public override Vector2 InitialSize { get { - return this.windowRect.size; + return base.windowRect.size; } } @@ -25,14 +25,14 @@ protected override float Margin public ImmediateWindow() { - this.doCloseButton = false; - this.doCloseX = false; - this.soundAppear = null; - this.soundClose = null; - this.closeOnClickedOutside = false; - this.closeOnEscapeKey = false; - this.focusWhenOpened = false; - this.preventCameraMotion = false; + base.doCloseButton = false; + base.doCloseX = false; + base.soundAppear = null; + base.soundClose = null; + base.closeOnClickedOutside = false; + base.closeOnEscapeKey = false; + base.focusWhenOpened = false; + base.preventCameraMotion = false; } public override void DoWindowContents(Rect inRect) diff --git a/Assembly-CSharp/Verse/ImmunityHandler.cs b/Assembly-CSharp/Verse/ImmunityHandler.cs index d85416d4a..60c4217ec 100644 --- a/Assembly-CSharp/Verse/ImmunityHandler.cs +++ b/Assembly-CSharp/Verse/ImmunityHandler.cs @@ -1,4 +1,3 @@ -using System; using System.Collections.Generic; using UnityEngine; @@ -40,7 +39,7 @@ public float DiseaseContractChanceFactor(HediffDef diseaseDef, BodyPartRecord pa { if (this.immunityList[j].hediffDef == diseaseDef) { - return Mathf.Lerp(1f, 0f, this.immunityList[j].immunity / 0.6f); + return Mathf.Lerp(1f, 0f, (float)(this.immunityList[j].immunity / 0.60000002384185791)); } } return 1f; @@ -76,11 +75,11 @@ internal void ImmunityHandlerTick() immunityRecord.immunity = Mathf.Clamp(0.650000036f, immunityRecord.immunity, 1f); } } - for (int k = this.immunityList.Count - 1; k >= 0; k--) + for (int num = this.immunityList.Count - 1; num >= 0; num--) { - if (this.immunityList[k].immunity <= 0f && !list.Contains(this.immunityList[k].hediffDef)) + if (this.immunityList[num].immunity <= 0.0 && !list.Contains(this.immunityList[num].hediffDef)) { - this.immunityList.RemoveAt(k); + this.immunityList.RemoveAt(num); } } } @@ -129,17 +128,12 @@ private bool AnyHediffMakesFullyImmuneTo(HediffDef def) private void TryAddImmunityRecord(HediffDef def) { - if (def.CompProps() == null) + if (def.CompProps() != null && !this.ImmunityRecordExists(def)) { - return; + ImmunityRecord immunityRecord = new ImmunityRecord(); + immunityRecord.hediffDef = def; + this.immunityList.Add(immunityRecord); } - if (this.ImmunityRecordExists(def)) - { - return; - } - ImmunityRecord immunityRecord = new ImmunityRecord(); - immunityRecord.hediffDef = def; - this.immunityList.Add(immunityRecord); } public ImmunityRecord GetImmunityRecord(HediffDef def) diff --git a/Assembly-CSharp/Verse/ImmunityRecord.cs b/Assembly-CSharp/Verse/ImmunityRecord.cs index 23aab9e17..6a1fc8477 100644 --- a/Assembly-CSharp/Verse/ImmunityRecord.cs +++ b/Assembly-CSharp/Verse/ImmunityRecord.cs @@ -1,5 +1,4 @@ using RimWorld; -using System; using UnityEngine; namespace Verse @@ -18,14 +17,14 @@ public float ImmunityChangePerTick(Pawn pawn, bool sick, Hediff diseaseInstance) } HediffCompProperties_Immunizable hediffCompProperties_Immunizable = this.hediffDef.CompProps(); float num = (!sick) ? hediffCompProperties_Immunizable.immunityPerDayNotSick : hediffCompProperties_Immunizable.immunityPerDaySick; - num /= 60000f; + num = (float)(num / 60000.0); float num2 = pawn.GetStatValue(StatDefOf.ImmunityGainSpeed, true); if (diseaseInstance != null) { int value = Gen.HashCombineInt(diseaseInstance.GetHashCode(), 156482735); - num2 *= Mathf.Lerp(0.8f, 1.2f, (float)Mathf.Abs(value) / 2.14748365E+09f); + num2 *= Mathf.Lerp(0.8f, 1.2f, (float)((float)Mathf.Abs(value) / 2147483648.0)); } - if (num > 0f) + if (num > 0.0) { return num * num2; } diff --git a/Assembly-CSharp/Verse/IngredientCount.cs b/Assembly-CSharp/Verse/IngredientCount.cs index 138fcaf54..1a76f99b1 100644 --- a/Assembly-CSharp/Verse/IngredientCount.cs +++ b/Assembly-CSharp/Verse/IngredientCount.cs @@ -1,4 +1,3 @@ -using System; using UnityEngine; namespace Verse @@ -40,14 +39,7 @@ public void ResolveReferences() public override string ToString() { - return string.Concat(new object[] - { - "(", - this.count, - "x ", - this.filter.ToString(), - ")" - }); + return "(" + this.count + "x " + this.filter.ToString() + ")"; } } } diff --git a/Assembly-CSharp/Verse/IngredientValueGetter.cs b/Assembly-CSharp/Verse/IngredientValueGetter.cs index 8f05b21ca..911fcdac0 100644 --- a/Assembly-CSharp/Verse/IngredientValueGetter.cs +++ b/Assembly-CSharp/Verse/IngredientValueGetter.cs @@ -1,5 +1,3 @@ -using System; - namespace Verse { public abstract class IngredientValueGetter @@ -10,7 +8,7 @@ public abstract class IngredientValueGetter public virtual string ExtraDescriptionLine(RecipeDef r) { - return null; + return (string)null; } } } diff --git a/Assembly-CSharp/Verse/IngredientValueGetter_Nutrition.cs b/Assembly-CSharp/Verse/IngredientValueGetter_Nutrition.cs index b5d6121e7..2aee145bc 100644 --- a/Assembly-CSharp/Verse/IngredientValueGetter_Nutrition.cs +++ b/Assembly-CSharp/Verse/IngredientValueGetter_Nutrition.cs @@ -1,5 +1,3 @@ -using System; - namespace Verse { public class IngredientValueGetter_Nutrition : IngredientValueGetter @@ -15,10 +13,7 @@ public override float ValuePerUnitOf(ThingDef t) public override string BillRequirementsDescription(RecipeDef r, IngredientCount ing) { - return "BillRequiresNutrition".Translate(new object[] - { - ing.GetBaseCount() - }) + " (" + ing.filter.Summary + ")"; + return "BillRequiresNutrition".Translate(ing.GetBaseCount()) + " (" + ing.filter.Summary + ")"; } } } diff --git a/Assembly-CSharp/Verse/IngredientValueGetter_Volume.cs b/Assembly-CSharp/Verse/IngredientValueGetter_Volume.cs index 17a2e3bcd..75513347c 100644 --- a/Assembly-CSharp/Verse/IngredientValueGetter_Volume.cs +++ b/Assembly-CSharp/Verse/IngredientValueGetter_Volume.cs @@ -16,31 +16,20 @@ public override float ValuePerUnitOf(ThingDef t) public override string BillRequirementsDescription(RecipeDef r, IngredientCount ing) { - if (!ing.filter.AllowedThingDefs.Any((ThingDef td) => td.smallVolume) || ing.filter.AllowedThingDefs.Any((ThingDef td) => td.smallVolume && !r.GetPremultipliedSmallIngredients().Contains(td))) + if (ing.filter.AllowedThingDefs.Any((Func)((ThingDef td) => td.smallVolume)) && !ing.filter.AllowedThingDefs.Any((Func)((ThingDef td) => td.smallVolume && !r.GetPremultipliedSmallIngredients().Contains(td)))) { - return "BillRequires".Translate(new object[] - { - ing.GetBaseCount(), - ing.filter.Summary - }); + return "BillRequires".Translate((float)(ing.GetBaseCount() * 10.0), ing.filter.Summary); } - return "BillRequires".Translate(new object[] - { - ing.GetBaseCount() * 10f, - ing.filter.Summary - }); + return "BillRequires".Translate(ing.GetBaseCount(), ing.filter.Summary); } public override string ExtraDescriptionLine(RecipeDef r) { - if (r.ingredients.Any((IngredientCount ing) => ing.filter.AllowedThingDefs.Any((ThingDef td) => td.smallVolume && !r.GetPremultipliedSmallIngredients().Contains(td)))) + if (r.ingredients.Any((Predicate)((IngredientCount ing) => ing.filter.AllowedThingDefs.Any((Func)((ThingDef td) => td.smallVolume && !r.GetPremultipliedSmallIngredients().Contains(td)))))) { - return "BillRequiresMayVary".Translate(new object[] - { - 10.ToStringCached() - }); + return "BillRequiresMayVary".Translate(10.ToStringCached()); } - return null; + return (string)null; } } } diff --git a/Assembly-CSharp/Verse/InjuryProps.cs b/Assembly-CSharp/Verse/InjuryProps.cs index bef1ad00f..abf6cd4e6 100644 --- a/Assembly-CSharp/Verse/InjuryProps.cs +++ b/Assembly-CSharp/Verse/InjuryProps.cs @@ -1,5 +1,3 @@ -using System; - namespace Verse { public class InjuryProps diff --git a/Assembly-CSharp/Verse/InspectTabBase.cs b/Assembly-CSharp/Verse/InspectTabBase.cs index 88ca86fc3..83b1a4d49 100644 --- a/Assembly-CSharp/Verse/InspectTabBase.cs +++ b/Assembly-CSharp/Verse/InspectTabBase.cs @@ -37,7 +37,7 @@ public string TutorHighlightTagClosed { if (this.tutorTag == null) { - return null; + return (string)null; } if (this.cachedTutorHighlightTagClosed == null) { @@ -52,7 +52,7 @@ protected Rect TabRect get { this.UpdateSize(); - float y = this.PaneTopY - 30f - this.size.y; + float y = (float)(this.PaneTopY - 30.0 - this.size.y); return new Rect(0f, y, this.size.x, this.size.y); } } @@ -60,29 +60,22 @@ protected Rect TabRect public void DoTabGUI() { Rect rect = this.TabRect; - Find.WindowStack.ImmediateWindow(235086, rect, WindowLayer.GameUI, delegate + Find.WindowStack.ImmediateWindow(235086, rect, WindowLayer.GameUI, (Action)delegate { - if (!this.StillValid || !this.IsVisible) + if (this.StillValid && this.IsVisible) { - return; - } - if (Widgets.CloseButtonFor(rect.AtZero())) - { - this.CloseTab(); - } - try - { - this.FillTab(); - } - catch (Exception ex) - { - Log.ErrorOnce(string.Concat(new object[] + if (Widgets.CloseButtonFor(rect.AtZero())) + { + this.CloseTab(); + } + try + { + this.FillTab(); + } + catch (Exception ex) { - "Exception filling tab ", - this.GetType(), - ": ", - ex - }), 49827); + Log.ErrorOnce("Exception filling tab " + base.GetType() + ": " + ex, 49827); + } } }, true, false, 1f); this.ExtraOnGUI(); diff --git a/Assembly-CSharp/Verse/InspectTabManager.cs b/Assembly-CSharp/Verse/InspectTabManager.cs index 7565f538e..938701c57 100644 --- a/Assembly-CSharp/Verse/InspectTabManager.cs +++ b/Assembly-CSharp/Verse/InspectTabManager.cs @@ -9,7 +9,7 @@ public static class InspectTabManager public static InspectTabBase GetSharedInstance(Type tabType) { - InspectTabBase inspectTabBase; + InspectTabBase inspectTabBase = default(InspectTabBase); if (InspectTabManager.sharedInstances.TryGetValue(tabType, out inspectTabBase)) { return inspectTabBase; diff --git a/Assembly-CSharp/Verse/IntRange.cs b/Assembly-CSharp/Verse/IntRange.cs index f92ad0920..3e1f6ccfa 100644 --- a/Assembly-CSharp/Verse/IntRange.cs +++ b/Assembly-CSharp/Verse/IntRange.cs @@ -29,7 +29,7 @@ public float Average { get { - return ((float)this.min + (float)this.max) / 2f; + return (float)(((float)this.min + (float)this.max) / 2.0); } } @@ -54,10 +54,7 @@ public int Lerped(float lerpFactor) public static IntRange FromString(string s) { - string[] array = s.Split(new char[] - { - '~' - }); + string[] array = s.Split('~'); if (array.Length == 1) { int num = Convert.ToInt32(array[0]); @@ -78,7 +75,11 @@ public override int GetHashCode() public override bool Equals(object obj) { - return obj is IntRange && this.Equals((IntRange)obj); + if (!(obj is IntRange)) + { + return false; + } + return this.Equals((IntRange)obj); } public bool Equals(IntRange other) diff --git a/Assembly-CSharp/Verse/IntVec2.cs b/Assembly-CSharp/Verse/IntVec2.cs index 3575db8c8..97a366a90 100644 --- a/Assembly-CSharp/Verse/IntVec2.cs +++ b/Assembly-CSharp/Verse/IntVec2.cs @@ -134,14 +134,7 @@ public IntVec2 Rotated() public override string ToString() { - return string.Concat(new string[] - { - "(", - this.x.ToString(), - ", ", - this.z.ToString(), - ")" - }); + return "(" + this.x.ToString() + ", " + this.z.ToString() + ")"; } public string ToStringCross() @@ -151,18 +144,9 @@ public string ToStringCross() public static IntVec2 FromString(string str) { - str = str.TrimStart(new char[] - { - '(' - }); - str = str.TrimEnd(new char[] - { - ')' - }); - string[] array = str.Split(new char[] - { - ',' - }); + str = str.TrimStart('('); + str = str.TrimEnd(')'); + string[] array = str.Split(','); int newX = Convert.ToInt32(array[0]); int newZ = Convert.ToInt32(array[1]); return new IntVec2(newX, newZ); @@ -170,12 +154,16 @@ public static IntVec2 FromString(string str) public Vector2 ToVector2Shifted() { - return new Vector2((float)this.x + 0.5f, (float)this.z + 0.5f); + return new Vector2((float)((float)this.x + 0.5), (float)((float)this.z + 0.5)); } public override bool Equals(object obj) { - return obj is IntVec2 && this.Equals((IntVec2)obj); + if (!(obj is IntVec2)) + { + return false; + } + return this.Equals((IntVec2)obj); } public bool Equals(IntVec2 other) @@ -210,12 +198,20 @@ public override int GetHashCode() public static bool operator ==(IntVec2 a, IntVec2 b) { - return a.x == b.x && a.z == b.z; + if (a.x == b.x && a.z == b.z) + { + return true; + } + return false; } public static bool operator !=(IntVec2 a, IntVec2 b) { - return a.x != b.x || a.z != b.z; + if (a.x == b.x && a.z == b.z) + { + return false; + } + return true; } } } diff --git a/Assembly-CSharp/Verse/IntVec3.cs b/Assembly-CSharp/Verse/IntVec3.cs index fb925981a..91c6b81ea 100644 --- a/Assembly-CSharp/Verse/IntVec3.cs +++ b/Assembly-CSharp/Verse/IntVec3.cs @@ -59,7 +59,8 @@ public float AngleFlat { return 0f; } - return Quaternion.LookRotation(this.ToVector3()).eulerAngles.y; + Vector3 eulerAngles = Quaternion.LookRotation(this.ToVector3()).eulerAngles; + return eulerAngles.y; } } @@ -134,32 +135,27 @@ public IntVec3(Vector2 v) public static IntVec3 FromString(string str) { - str = str.TrimStart(new char[] - { - '(' - }); - str = str.TrimEnd(new char[] - { - ')' - }); - string[] array = str.Split(new char[] - { - ',' - }); - IntVec3 result; + str = str.TrimStart('('); + str = str.TrimEnd(')'); + string[] array = str.Split(','); try { int newX = Convert.ToInt32(array[0]); int newY = Convert.ToInt32(array[1]); int newZ = Convert.ToInt32(array[2]); - result = new IntVec3(newX, newY, newZ); + return new IntVec3(newX, newY, newZ); + IL_0062: + IntVec3 result; + return result; } catch (Exception arg) { Log.Warning(str + " is not a valid IntVec3 format. Exception: " + arg); - result = IntVec3.Invalid; + return IntVec3.Invalid; + IL_0087: + IntVec3 result; + return result; } - return result; } public Vector3 ToVector3() @@ -169,7 +165,7 @@ public Vector3 ToVector3() public Vector3 ToVector3Shifted() { - return new Vector3((float)this.x + 0.5f, (float)this.y, (float)this.z + 0.5f); + return new Vector3((float)((float)this.x + 0.5), (float)this.y, (float)((float)this.z + 0.5)); } public Vector3 ToVector3ShiftedWithAltitude(AltitudeLayer AltLayer) @@ -179,7 +175,7 @@ public Vector3 ToVector3ShiftedWithAltitude(AltitudeLayer AltLayer) public Vector3 ToVector3ShiftedWithAltitude(float AddedAltitude) { - return new Vector3((float)this.x + 0.5f, (float)this.y + AddedAltitude, (float)this.z + 0.5f); + return new Vector3((float)((float)this.x + 0.5), (float)this.y + AddedAltitude, (float)((float)this.z + 0.5)); } public bool InHorDistOf(IntVec3 otherLoc, float maxDist) @@ -206,12 +202,28 @@ public Vector2 ToUIPosition() public bool AdjacentToCardinal(IntVec3 other) { - return this.IsValid && ((other.z == this.z && (other.x == this.x + 1 || other.x == this.x - 1)) || (other.x == this.x && (other.z == this.z + 1 || other.z == this.z - 1))); + if (!this.IsValid) + { + return false; + } + if (other.z == this.z && (other.x == this.x + 1 || other.x == this.x - 1)) + { + return true; + } + if (other.x == this.x && (other.z == this.z + 1 || other.z == this.z - 1)) + { + return true; + } + return false; } public bool AdjacentToDiagonal(IntVec3 other) { - return this.IsValid && Mathf.Abs(this.x - other.x) == 1 && Mathf.Abs(this.z - other.z) == 1; + if (!this.IsValid) + { + return false; + } + return Mathf.Abs(this.x - other.x) == 1 && Mathf.Abs(this.z - other.z) == 1; } public bool AdjacentToCardinal(Room room) @@ -258,23 +270,14 @@ public override int GetHashCode() public ulong UniqueHashCode() { ulong num = 0uL; - num += (ulong)(1L * (long)this.x); - num += (ulong)(4096L * (long)this.z); - return num + (ulong)(16777216L * (long)this.y); + num = (ulong)((long)num + 1L * (long)this.x); + num = (ulong)((long)num + 4096L * (long)this.z); + return (ulong)((long)num + 16777216L * (long)this.y); } public override string ToString() { - return string.Concat(new string[] - { - "(", - this.x.ToString(), - ", ", - this.y.ToString(), - ", ", - this.z.ToString(), - ")" - }); + return "(" + this.x.ToString() + ", " + this.y.ToString() + ", " + this.z.ToString() + ")"; } public static IntVec3 operator +(IntVec3 a, IntVec3 b) @@ -294,12 +297,20 @@ public override string ToString() public static bool operator ==(IntVec3 a, IntVec3 b) { - return a.x == b.x && a.z == b.z && a.y == b.y; + if (a.x == b.x && a.z == b.z && a.y == b.y) + { + return true; + } + return false; } public static bool operator !=(IntVec3 a, IntVec3 b) { - return a.x != b.x || a.z != b.z || a.y != b.y; + if (a.x == b.x && a.z == b.z && a.y == b.y) + { + return false; + } + return true; } } } diff --git a/Assembly-CSharp/Verse/IntVec3Utility.cs b/Assembly-CSharp/Verse/IntVec3Utility.cs index 5b3c26601..822d95ea5 100644 --- a/Assembly-CSharp/Verse/IntVec3Utility.cs +++ b/Assembly-CSharp/Verse/IntVec3Utility.cs @@ -25,16 +25,26 @@ public static IntVec3 RotatedBy(this IntVec3 orig, Rot4 rot) switch (rot.AsInt) { case 0: + { return orig; + } case 1: + { return new IntVec3(orig.z, orig.y, -orig.x); + } case 2: + { return new IntVec3(-orig.x, orig.y, -orig.z); + } case 3: + { return new IntVec3(-orig.z, orig.y, orig.x); + } default: + { return orig; } + } } public static int ManhattanDistanceFlat(IntVec3 a, IntVec3 b) diff --git a/Assembly-CSharp/Verse/Intelligence.cs b/Assembly-CSharp/Verse/Intelligence.cs index a4b04a46f..1b6256377 100644 --- a/Assembly-CSharp/Verse/Intelligence.cs +++ b/Assembly-CSharp/Verse/Intelligence.cs @@ -1,11 +1,9 @@ -using System; - namespace Verse { public enum Intelligence : byte { - Animal, - ToolUser, - Humanlike + Animal = 0, + ToolUser = 1, + Humanlike = 2 } } diff --git a/Assembly-CSharp/Verse/JitterHandler.cs b/Assembly-CSharp/Verse/JitterHandler.cs index 9ffc98da5..513f5d372 100644 --- a/Assembly-CSharp/Verse/JitterHandler.cs +++ b/Assembly-CSharp/Verse/JitterHandler.cs @@ -1,4 +1,3 @@ -using System; using UnityEngine; namespace Verse diff --git a/Assembly-CSharp/Verse/JobDef.cs b/Assembly-CSharp/Verse/JobDef.cs index 55f06d616..df3a816da 100644 --- a/Assembly-CSharp/Verse/JobDef.cs +++ b/Assembly-CSharp/Verse/JobDef.cs @@ -1,7 +1,6 @@ using RimWorld; using System; using System.Collections.Generic; -using System.Diagnostics; namespace Verse { @@ -42,14 +41,16 @@ public class JobDef : Def public Rot4 faceDir = Rot4.Invalid; - [DebuggerHidden] public override IEnumerable ConfigErrors() { - JobDef.c__Iterator1D2 c__Iterator1D = new JobDef.c__Iterator1D2(); - c__Iterator1D.<>f__this = this; - JobDef.c__Iterator1D2 expr_0E = c__Iterator1D; - expr_0E.$PC = -2; - return expr_0E; + foreach (string item in base.ConfigErrors()) + { + yield return item; + } + if (this.joySkill != null && this.joyXpPerTick == 0.0) + { + yield return "funSkill is not null but funXpPerTick is zero"; + } } } } diff --git a/Assembly-CSharp/Verse/KeyBindingCategoryDef.cs b/Assembly-CSharp/Verse/KeyBindingCategoryDef.cs index 25342f16f..a89d3dc95 100644 --- a/Assembly-CSharp/Verse/KeyBindingCategoryDef.cs +++ b/Assembly-CSharp/Verse/KeyBindingCategoryDef.cs @@ -1,4 +1,3 @@ -using System; using System.Collections.Generic; namespace Verse diff --git a/Assembly-CSharp/Verse/KeyBindingData.cs b/Assembly-CSharp/Verse/KeyBindingData.cs index ebd1668d0..bfb0ad037 100644 --- a/Assembly-CSharp/Verse/KeyBindingData.cs +++ b/Assembly-CSharp/Verse/KeyBindingData.cs @@ -22,13 +22,13 @@ public KeyBindingData(KeyCode keyBindingA, KeyCode keyBindingB) public override string ToString() { string str = "["; - if (this.keyBindingA != KeyCode.None) + if (this.keyBindingA != 0) { - str += this.keyBindingA.ToString(); + str += ((Enum)(object)this.keyBindingA).ToString(); } - if (this.keyBindingB != KeyCode.None) + if (this.keyBindingB != 0) { - str = str + ", " + this.keyBindingB.ToString(); + str = str + ", " + ((Enum)(object)this.keyBindingB).ToString(); } return str + "]"; } diff --git a/Assembly-CSharp/Verse/KeyBindingDef.cs b/Assembly-CSharp/Verse/KeyBindingDef.cs index 288ee67b1..4be1b4d50 100644 --- a/Assembly-CSharp/Verse/KeyBindingDef.cs +++ b/Assembly-CSharp/Verse/KeyBindingDef.cs @@ -1,4 +1,3 @@ -using System; using UnityEngine; namespace Verse @@ -17,14 +16,14 @@ public KeyCode MainKey { get { - KeyBindingData keyBindingData; + KeyBindingData keyBindingData = default(KeyBindingData); if (KeyPrefs.KeyPrefsData.keyPrefs.TryGetValue(this, out keyBindingData)) { - if (keyBindingData.keyBindingA != KeyCode.None) + if (keyBindingData.keyBindingA != 0) { return keyBindingData.keyBindingA; } - if (keyBindingData.keyBindingB != KeyCode.None) + if (keyBindingData.keyBindingB != 0) { return keyBindingData.keyBindingB; } @@ -45,8 +44,12 @@ public bool KeyDownEvent { get { - KeyBindingData keyBindingData; - return Event.current.type == EventType.KeyDown && Event.current.keyCode != KeyCode.None && KeyPrefs.KeyPrefsData.keyPrefs.TryGetValue(this, out keyBindingData) && (Event.current.keyCode == keyBindingData.keyBindingA || Event.current.keyCode == keyBindingData.keyBindingB); + KeyBindingData keyBindingData = default(KeyBindingData); + if (Event.current.type == EventType.KeyDown && Event.current.keyCode != 0 && KeyPrefs.KeyPrefsData.keyPrefs.TryGetValue(this, out keyBindingData)) + { + return Event.current.keyCode == keyBindingData.keyBindingA || Event.current.keyCode == keyBindingData.keyBindingB; + } + return false; } } @@ -54,8 +57,32 @@ public bool IsDownEvent { get { - KeyBindingData keyBindingData; - return KeyPrefs.KeyPrefsData.keyPrefs.TryGetValue(this, out keyBindingData) && (this.KeyDownEvent || (Event.current.shift && (keyBindingData.keyBindingA == KeyCode.LeftShift || keyBindingData.keyBindingA == KeyCode.RightShift || keyBindingData.keyBindingB == KeyCode.LeftShift || keyBindingData.keyBindingB == KeyCode.RightShift)) || (Event.current.control && (keyBindingData.keyBindingA == KeyCode.LeftControl || keyBindingData.keyBindingA == KeyCode.RightControl || keyBindingData.keyBindingB == KeyCode.LeftControl || keyBindingData.keyBindingB == KeyCode.RightControl)) || (Event.current.alt && (keyBindingData.keyBindingA == KeyCode.LeftAlt || keyBindingData.keyBindingA == KeyCode.RightAlt || keyBindingData.keyBindingB == KeyCode.LeftAlt || keyBindingData.keyBindingB == KeyCode.RightAlt)) || (Event.current.command && (keyBindingData.keyBindingA == KeyCode.LeftCommand || keyBindingData.keyBindingA == KeyCode.RightCommand || keyBindingData.keyBindingB == KeyCode.LeftCommand || keyBindingData.keyBindingB == KeyCode.RightCommand)) || this.IsDown); + KeyBindingData keyBindingData = default(KeyBindingData); + if (!KeyPrefs.KeyPrefsData.keyPrefs.TryGetValue(this, out keyBindingData)) + { + return false; + } + if (this.KeyDownEvent) + { + return true; + } + if (Event.current.shift && (keyBindingData.keyBindingA == KeyCode.LeftShift || keyBindingData.keyBindingA == KeyCode.RightShift || keyBindingData.keyBindingB == KeyCode.LeftShift || keyBindingData.keyBindingB == KeyCode.RightShift)) + { + return true; + } + if (Event.current.control && (keyBindingData.keyBindingA == KeyCode.LeftControl || keyBindingData.keyBindingA == KeyCode.RightControl || keyBindingData.keyBindingB == KeyCode.LeftControl || keyBindingData.keyBindingB == KeyCode.RightControl)) + { + return true; + } + if (Event.current.alt && (keyBindingData.keyBindingA == KeyCode.LeftAlt || keyBindingData.keyBindingA == KeyCode.RightAlt || keyBindingData.keyBindingB == KeyCode.LeftAlt || keyBindingData.keyBindingB == KeyCode.RightAlt)) + { + return true; + } + if (Event.current.command && (keyBindingData.keyBindingA == KeyCode.LeftCommand || keyBindingData.keyBindingA == KeyCode.RightCommand || keyBindingData.keyBindingB == KeyCode.LeftCommand || keyBindingData.keyBindingB == KeyCode.RightCommand)) + { + return true; + } + return this.IsDown; } } @@ -63,8 +90,12 @@ public bool JustPressed { get { - KeyBindingData keyBindingData; - return KeyPrefs.KeyPrefsData.keyPrefs.TryGetValue(this, out keyBindingData) && (Input.GetKeyDown(keyBindingData.keyBindingA) || Input.GetKeyDown(keyBindingData.keyBindingB)); + KeyBindingData keyBindingData = default(KeyBindingData); + if (KeyPrefs.KeyPrefsData.keyPrefs.TryGetValue(this, out keyBindingData)) + { + return Input.GetKeyDown(keyBindingData.keyBindingA) || Input.GetKeyDown(keyBindingData.keyBindingB); + } + return false; } } @@ -72,8 +103,12 @@ public bool IsDown { get { - KeyBindingData keyBindingData; - return KeyPrefs.KeyPrefsData.keyPrefs.TryGetValue(this, out keyBindingData) && (Input.GetKey(keyBindingData.keyBindingA) || Input.GetKey(keyBindingData.keyBindingB)); + KeyBindingData keyBindingData = default(KeyBindingData); + if (KeyPrefs.KeyPrefsData.keyPrefs.TryGetValue(this, out keyBindingData)) + { + return Input.GetKey(keyBindingData.keyBindingA) || Input.GetKey(keyBindingData.keyBindingB); + } + return false; } } diff --git a/Assembly-CSharp/Verse/KeyBindingDefGenerator.cs b/Assembly-CSharp/Verse/KeyBindingDefGenerator.cs index ac2f66b57..664210e0b 100644 --- a/Assembly-CSharp/Verse/KeyBindingDefGenerator.cs +++ b/Assembly-CSharp/Verse/KeyBindingDefGenerator.cs @@ -1,27 +1,54 @@ +using RimWorld; using System; using System.Collections.Generic; -using System.Diagnostics; +using System.Linq; namespace Verse { public static class KeyBindingDefGenerator { - [DebuggerHidden] public static IEnumerable ImpliedKeyBindingCategoryDefs() { - KeyBindingDefGenerator.c__Iterator253 c__Iterator = new KeyBindingDefGenerator.c__Iterator253(); - KeyBindingDefGenerator.c__Iterator253 expr_07 = c__Iterator; - expr_07.$PC = -2; - return expr_07; + List gameUniversalCats = (from d in DefDatabase.AllDefs + where d.isGameUniversal + select d).ToList(); + foreach (DesignationCategoryDef allDef in DefDatabase.AllDefs) + { + KeyBindingCategoryDef catDef = new KeyBindingCategoryDef + { + defName = "Architect_" + allDef.defName, + label = allDef.label + " tab", + description = "Key bindings for the \"" + allDef.LabelCap + "\" section of the Architect menu" + }; + catDef.checkForConflicts.AddRange(gameUniversalCats); + for (int i = 0; i < gameUniversalCats.Count; i++) + { + gameUniversalCats[i].checkForConflicts.Add(catDef); + } + allDef.bindingCatDef = catDef; + yield return catDef; + } } - [DebuggerHidden] public static IEnumerable ImpliedKeyBindingDefs() { - KeyBindingDefGenerator.c__Iterator254 c__Iterator = new KeyBindingDefGenerator.c__Iterator254(); - KeyBindingDefGenerator.c__Iterator254 expr_07 = c__Iterator; - expr_07.$PC = -2; - return expr_07; + foreach (MainButtonDef item in from td in DefDatabase.AllDefs + orderby td.order + select td) + { + if (item.defaultHotKey != 0) + { + KeyBindingDef keyDef = new KeyBindingDef + { + label = "Toggle " + item.label + " tab", + defName = "MainTab_" + item.defName, + category = KeyBindingCategoryDefOf.MainTabs, + defaultKeyCodeA = item.defaultHotKey + }; + item.hotKey = keyDef; + yield return keyDef; + } + } } } } diff --git a/Assembly-CSharp/Verse/KeyPrefs.cs b/Assembly-CSharp/Verse/KeyPrefs.cs index a0678b235..2e6477e9f 100644 --- a/Assembly-CSharp/Verse/KeyPrefs.cs +++ b/Assembly-CSharp/Verse/KeyPrefs.cs @@ -9,8 +9,8 @@ public class KeyPrefs { public enum BindingSlot : byte { - A, - B + A = 0, + B = 1 } private static KeyPrefsData data; @@ -35,18 +35,27 @@ public static void Init() Dictionary dictionary = DirectXmlLoader.ItemFromXmlFile>(GenFilePaths.KeyPrefsFilePath, true); KeyPrefs.data = new KeyPrefsData(); KeyPrefs.unresolvedBindings = new Dictionary(); - foreach (KeyValuePair current in dictionary) + Dictionary.Enumerator enumerator = dictionary.GetEnumerator(); + try { - KeyBindingDef namedSilentFail = DefDatabase.GetNamedSilentFail(current.Key); - if (namedSilentFail != null) - { - KeyPrefs.data.keyPrefs[namedSilentFail] = current.Value; - } - else + while (enumerator.MoveNext()) { - KeyPrefs.unresolvedBindings[current.Key] = current.Value; + KeyValuePair current = enumerator.Current; + KeyBindingDef namedSilentFail = DefDatabase.GetNamedSilentFail(current.Key); + if (namedSilentFail != null) + { + KeyPrefs.data.keyPrefs[namedSilentFail] = current.Value; + } + else + { + KeyPrefs.unresolvedBindings[current.Key] = current.Value; + } } } + finally + { + ((IDisposable)(object)enumerator).Dispose(); + } if (flag) { KeyPrefs.data.ResetToDefaults(); @@ -64,33 +73,47 @@ public static void Save() try { Dictionary dictionary = new Dictionary(); - foreach (KeyValuePair current in KeyPrefs.data.keyPrefs) + Dictionary.Enumerator enumerator = KeyPrefs.data.keyPrefs.GetEnumerator(); + try { - dictionary[current.Key.defName] = current.Value; - } - foreach (KeyValuePair current2 in KeyPrefs.unresolvedBindings) - { - try + while (enumerator.MoveNext()) { - dictionary.Add(current2.Key, current2.Value); + KeyValuePair current = enumerator.Current; + dictionary[current.Key.defName] = current.Value; } - catch (ArgumentException) + } + finally + { + ((IDisposable)(object)enumerator).Dispose(); + } + Dictionary.Enumerator enumerator2 = KeyPrefs.unresolvedBindings.GetEnumerator(); + try + { + while (enumerator2.MoveNext()) { + KeyValuePair current2 = enumerator2.Current; + try + { + dictionary.Add(current2.Key, current2.Value); + } + catch (ArgumentException) + { + } } } + finally + { + ((IDisposable)(object)enumerator2).Dispose(); + } XDocument xDocument = new XDocument(); XElement content = DirectXmlSaver.XElementFromObject(dictionary, typeof(KeyPrefsData)); xDocument.Add(content); xDocument.Save(GenFilePaths.KeyPrefsFilePath); } - catch (Exception ex) + catch (Exception ex2) { - GenUI.ErrorDialog("ProblemSavingFile".Translate(new object[] - { - GenFilePaths.KeyPrefsFilePath, - ex.ToString() - })); - Log.Error("Exception saving keyprefs: " + ex); + GenUI.ErrorDialog("ProblemSavingFile".Translate(GenFilePaths.KeyPrefsFilePath, ex2.ToString())); + Log.Error("Exception saving keyprefs: " + ex2); } } } diff --git a/Assembly-CSharp/Verse/KeyPrefsData.cs b/Assembly-CSharp/Verse/KeyPrefsData.cs index 98cbe4b51..fb7e15c00 100644 --- a/Assembly-CSharp/Verse/KeyPrefsData.cs +++ b/Assembly-CSharp/Verse/KeyPrefsData.cs @@ -1,6 +1,5 @@ using System; using System.Collections.Generic; -using System.Diagnostics; using UnityEngine; namespace Verse @@ -17,32 +16,37 @@ public void ResetToDefaults() public void AddMissingDefaultBindings() { - foreach (KeyBindingDef current in DefDatabase.AllDefs) + foreach (KeyBindingDef allDef in DefDatabase.AllDefs) { - if (!this.keyPrefs.ContainsKey(current)) + if (!this.keyPrefs.ContainsKey(allDef)) { - this.keyPrefs.Add(current, new KeyBindingData(current.defaultKeyCodeA, current.defaultKeyCodeB)); + this.keyPrefs.Add(allDef, new KeyBindingData(allDef.defaultKeyCodeA, allDef.defaultKeyCodeB)); } } } public bool SetBinding(KeyBindingDef keyDef, KeyPrefs.BindingSlot slot, KeyCode keyCode) { - KeyBindingData keyBindingData; + KeyBindingData keyBindingData = default(KeyBindingData); if (this.keyPrefs.TryGetValue(keyDef, out keyBindingData)) { - if (slot != KeyPrefs.BindingSlot.A) + switch (slot) + { + case KeyPrefs.BindingSlot.A: + { + keyBindingData.keyBindingA = keyCode; + break; + } + case KeyPrefs.BindingSlot.B: { - if (slot != KeyPrefs.BindingSlot.B) - { - Log.Error("Tried to set a key binding for \"" + keyDef.LabelCap + "\" on a nonexistent slot: " + slot.ToString()); - return false; - } keyBindingData.keyBindingB = keyCode; + break; } - else + default: { - keyBindingData.keyBindingA = keyCode; + Log.Error("Tried to set a key binding for \"" + keyDef.LabelCap + "\" on a nonexistent slot: " + ((Enum)(object)slot).ToString()); + return false; + } } return true; } @@ -52,42 +56,46 @@ public bool SetBinding(KeyBindingDef keyDef, KeyPrefs.BindingSlot slot, KeyCode public KeyCode GetBoundKeyCode(KeyBindingDef keyDef, KeyPrefs.BindingSlot slot) { - KeyBindingData keyBindingData; + KeyBindingData keyBindingData = default(KeyBindingData); if (!this.keyPrefs.TryGetValue(keyDef, out keyBindingData)) { Log.Error("Key not found in keyprefs: \"" + keyDef.LabelCap + "\""); return KeyCode.None; } - if (slot == KeyPrefs.BindingSlot.A) + switch (slot) + { + case KeyPrefs.BindingSlot.A: { return keyBindingData.keyBindingA; } - if (slot != KeyPrefs.BindingSlot.B) + case KeyPrefs.BindingSlot.B: + { + return keyBindingData.keyBindingB; + } + default: { throw new InvalidOperationException(); } - return keyBindingData.keyBindingB; + } } - [DebuggerHidden] private IEnumerable ConflictingBindings(KeyBindingDef keyDef, KeyCode code) { - KeyPrefsData.c__Iterator255 c__Iterator = new KeyPrefsData.c__Iterator255(); - c__Iterator.keyDef = keyDef; - c__Iterator.code = code; - c__Iterator.<$>keyDef = keyDef; - c__Iterator.<$>code = code; - c__Iterator.<>f__this = this; - KeyPrefsData.c__Iterator255 expr_2A = c__Iterator; - expr_2A.$PC = -2; - return expr_2A; + foreach (KeyBindingDef allDef in DefDatabase.AllDefs) + { + KeyBindingData prefData; + if (allDef != keyDef && (allDef.category == keyDef.category || keyDef.category.checkForConflicts.Contains(allDef.category)) && this.keyPrefs.TryGetValue(allDef, out prefData) && (prefData.keyBindingA == code || prefData.keyBindingB == code)) + { + yield return allDef; + } + } } public void EraseConflictingBindingsForKeyCode(KeyBindingDef keyDef, KeyCode keyCode, Action callBackOnErase = null) { - foreach (KeyBindingDef current in this.ConflictingBindings(keyDef, keyCode)) + foreach (KeyBindingDef item in this.ConflictingBindings(keyDef, keyCode)) { - KeyBindingData keyBindingData = this.keyPrefs[current]; + KeyBindingData keyBindingData = this.keyPrefs[item]; if (keyBindingData.keyBindingA == keyCode) { keyBindingData.keyBindingA = KeyCode.None; @@ -96,9 +104,9 @@ public void EraseConflictingBindingsForKeyCode(KeyBindingDef keyDef, KeyCode key { keyBindingData.keyBindingB = KeyCode.None; } - if (callBackOnErase != null) + if ((object)callBackOnErase != null) { - callBackOnErase(current); + callBackOnErase(item); } } } @@ -106,7 +114,7 @@ public void EraseConflictingBindingsForKeyCode(KeyBindingDef keyDef, KeyCode key public void CheckConflictsFor(KeyBindingDef keyDef, KeyPrefs.BindingSlot slot) { KeyCode boundKeyCode = this.GetBoundKeyCode(keyDef, slot); - if (boundKeyCode != KeyCode.None) + if (boundKeyCode != 0) { this.EraseConflictingBindingsForKeyCode(keyDef, boundKeyCode, null); this.SetBinding(keyDef, slot, boundKeyCode); @@ -116,38 +124,39 @@ public void CheckConflictsFor(KeyBindingDef keyDef, KeyPrefs.BindingSlot slot) public KeyPrefsData Clone() { KeyPrefsData keyPrefsData = new KeyPrefsData(); - foreach (KeyValuePair current in this.keyPrefs) + Dictionary.Enumerator enumerator = this.keyPrefs.GetEnumerator(); + try + { + while (enumerator.MoveNext()) + { + KeyValuePair current = enumerator.Current; + keyPrefsData.keyPrefs[current.Key] = new KeyBindingData(current.Value.keyBindingA, current.Value.keyBindingB); + } + return keyPrefsData; + } + finally { - keyPrefsData.keyPrefs[current.Key] = new KeyBindingData(current.Value.keyBindingA, current.Value.keyBindingB); + ((IDisposable)(object)enumerator).Dispose(); } - return keyPrefsData; } public void ErrorCheck() { - foreach (KeyBindingDef current in DefDatabase.AllDefs) + foreach (KeyBindingDef allDef in DefDatabase.AllDefs) { - this.ErrorCheckOn(current, KeyPrefs.BindingSlot.A); - this.ErrorCheckOn(current, KeyPrefs.BindingSlot.B); + this.ErrorCheckOn(allDef, KeyPrefs.BindingSlot.A); + this.ErrorCheckOn(allDef, KeyPrefs.BindingSlot.B); } } private void ErrorCheckOn(KeyBindingDef keyDef, KeyPrefs.BindingSlot slot) { KeyCode boundKeyCode = this.GetBoundKeyCode(keyDef, KeyPrefs.BindingSlot.A); - if (boundKeyCode != KeyCode.None) + if (boundKeyCode != 0) { - foreach (KeyBindingDef current in this.ConflictingBindings(keyDef, boundKeyCode)) + foreach (KeyBindingDef item in this.ConflictingBindings(keyDef, boundKeyCode)) { - Log.Error(string.Concat(new object[] - { - "Key binding conflict: ", - current, - " and ", - keyDef, - " are both bound to ", - boundKeyCode - })); + Log.Error("Key binding conflict: " + item + " and " + keyDef + " are both bound to " + boundKeyCode); } } } diff --git a/Assembly-CSharp/Verse/LabelValue.cs b/Assembly-CSharp/Verse/LabelValue.cs index 4892c0a16..d38399426 100644 --- a/Assembly-CSharp/Verse/LabelValue.cs +++ b/Assembly-CSharp/Verse/LabelValue.cs @@ -1,5 +1,3 @@ -using System; - namespace Verse { public struct LabelValue diff --git a/Assembly-CSharp/Verse/LanguageDataWriter.cs b/Assembly-CSharp/Verse/LanguageDataWriter.cs index 5d7d6bff3..69bc1ef94 100644 --- a/Assembly-CSharp/Verse/LanguageDataWriter.cs +++ b/Assembly-CSharp/Verse/LanguageDataWriter.cs @@ -18,29 +18,39 @@ public static void WriteBackstoryFile() FileInfo fileInfo = new FileInfo(GenFilePaths.BackstoryOutputFilePath); if (fileInfo.Exists) { - Find.WindowStack.Add(new Dialog_MessageBox("Cannot write: File already exists at " + GenFilePaths.BackstoryOutputFilePath, null, null, null, null, null, false)); - return; + Find.WindowStack.Add(new Dialog_MessageBox("Cannot write: File already exists at " + GenFilePaths.BackstoryOutputFilePath, (string)null, null, (string)null, null, (string)null, false)); } - XmlWriterSettings xmlWriterSettings = new XmlWriterSettings(); - xmlWriterSettings.Indent = true; - xmlWriterSettings.IndentChars = "\t"; - using (XmlWriter xmlWriter = XmlWriter.Create(GenFilePaths.BackstoryOutputFilePath, xmlWriterSettings)) + else { - xmlWriter.WriteStartDocument(); - xmlWriter.WriteStartElement("BackstoryTranslations"); - foreach (KeyValuePair current in BackstoryDatabase.allBackstories) + XmlWriterSettings xmlWriterSettings = new XmlWriterSettings(); + xmlWriterSettings.Indent = true; + xmlWriterSettings.IndentChars = "\t"; + using (XmlWriter xmlWriter = XmlWriter.Create(GenFilePaths.BackstoryOutputFilePath, xmlWriterSettings)) { - Backstory value = current.Value; - xmlWriter.WriteStartElement(value.identifier); - xmlWriter.WriteElementString("title", value.Title); - xmlWriter.WriteElementString("titleShort", value.TitleShort); - xmlWriter.WriteElementString("desc", value.baseDesc); + xmlWriter.WriteStartDocument(); + xmlWriter.WriteStartElement("BackstoryTranslations"); + Dictionary.Enumerator enumerator = BackstoryDatabase.allBackstories.GetEnumerator(); + try + { + while (enumerator.MoveNext()) + { + Backstory value = enumerator.Current.Value; + xmlWriter.WriteStartElement(value.identifier); + xmlWriter.WriteElementString("title", value.Title); + xmlWriter.WriteElementString("titleShort", value.TitleShort); + xmlWriter.WriteElementString("desc", value.baseDesc); + xmlWriter.WriteEndElement(); + } + } + finally + { + ((IDisposable)(object)enumerator).Dispose(); + } xmlWriter.WriteEndElement(); + xmlWriter.WriteEndDocument(); } - xmlWriter.WriteEndElement(); - xmlWriter.WriteEndDocument(); + Messages.Message("Fresh backstory translation file saved to " + GenFilePaths.BackstoryOutputFilePath, MessageSound.Standard); } - Messages.Message("Fresh backstory translation file saved to " + GenFilePaths.BackstoryOutputFilePath, MessageSound.Standard); } } } diff --git a/Assembly-CSharp/Verse/LanguageDatabase.cs b/Assembly-CSharp/Verse/LanguageDatabase.cs index 93178d544..d670899df 100644 --- a/Assembly-CSharp/Verse/LanguageDatabase.cs +++ b/Assembly-CSharp/Verse/LanguageDatabase.cs @@ -60,7 +60,7 @@ public static IEnumerable AllLoadedLanguages public static void SelectLanguage(LoadedLanguage lang) { Prefs.LangFolderName = lang.folderName; - LongEventHandler.QueueLongEvent(delegate + LongEventHandler.QueueLongEvent((Action)delegate { PlayDataLoader.ClearAllPlayData(); PlayDataLoader.LoadAllPlayData(false); @@ -75,9 +75,9 @@ public static void Clear() public static void LoadAllMetadata() { - foreach (ModContentPack current in LoadedModManager.RunningMods) + foreach (ModContentPack runningMod in LoadedModManager.RunningMods) { - string path = Path.Combine(current.RootDir, "Languages"); + string path = Path.Combine(runningMod.RootDir, "Languages"); DirectoryInfo directoryInfo = new DirectoryInfo(path); if (directoryInfo.Exists) { @@ -89,24 +89,23 @@ public static void LoadAllMetadata() } } } - LanguageDatabase.defaultLanguage = LanguageDatabase.languages.FirstOrDefault((LoadedLanguage la) => la.folderName == LanguageDatabase.DefaultLangFolderName); - LanguageDatabase.activeLanguage = LanguageDatabase.languages.FirstOrDefault((LoadedLanguage la) => la.folderName == Prefs.LangFolderName); + LanguageDatabase.defaultLanguage = LanguageDatabase.languages.FirstOrDefault((Func)((LoadedLanguage la) => la.folderName == LanguageDatabase.DefaultLangFolderName)); + LanguageDatabase.activeLanguage = LanguageDatabase.languages.FirstOrDefault((Func)((LoadedLanguage la) => la.folderName == Prefs.LangFolderName)); if (LanguageDatabase.activeLanguage == null) { Prefs.LangFolderName = LanguageDatabase.DefaultLangFolderName; - LanguageDatabase.activeLanguage = LanguageDatabase.languages.FirstOrDefault((LoadedLanguage la) => la.folderName == Prefs.LangFolderName); - } - if (LanguageDatabase.activeLanguage == null || LanguageDatabase.defaultLanguage == null) - { - Log.Error("No default language found!"); - LanguageDatabase.defaultLanguage = LanguageDatabase.languages[0]; - LanguageDatabase.activeLanguage = LanguageDatabase.languages[0]; + LanguageDatabase.activeLanguage = LanguageDatabase.languages.FirstOrDefault((Func)((LoadedLanguage la) => la.folderName == Prefs.LangFolderName)); } + if (LanguageDatabase.activeLanguage != null && LanguageDatabase.defaultLanguage != null) + return; + Log.Error("No default language found!"); + LanguageDatabase.defaultLanguage = LanguageDatabase.languages[0]; + LanguageDatabase.activeLanguage = LanguageDatabase.languages[0]; } private static LoadedLanguage LoadLanguageMetadataFrom(DirectoryInfo langDir) { - LoadedLanguage loadedLanguage = LanguageDatabase.languages.FirstOrDefault((LoadedLanguage lib) => lib.folderName == langDir.Name); + LoadedLanguage loadedLanguage = LanguageDatabase.languages.FirstOrDefault((Func)((LoadedLanguage lib) => lib.folderName == langDir.Name)); if (loadedLanguage == null) { loadedLanguage = new LoadedLanguage(langDir.ToString()); @@ -129,7 +128,7 @@ public static string SystemLanguageFolderName() return text; } } - string text2 = Application.systemLanguage.ToString(); + string text2 = ((Enum)(object)Application.systemLanguage).ToString(); if (LanguageDatabase.SupportedAutoSelectLanguages.Contains(text2)) { return text2; diff --git a/Assembly-CSharp/Verse/LanguageReportGenerator.cs b/Assembly-CSharp/Verse/LanguageReportGenerator.cs index cb0aa779b..cb71da899 100644 --- a/Assembly-CSharp/Verse/LanguageReportGenerator.cs +++ b/Assembly-CSharp/Verse/LanguageReportGenerator.cs @@ -15,59 +15,88 @@ public static void OutputTranslationReport() if (activeLanguage == defaultLanguage) { Messages.Message("Please activate a non-English language to scan.", MessageSound.RejectInput); - return; } - activeLanguage.LoadData(); - defaultLanguage.LoadData(); - StringBuilder stringBuilder = new StringBuilder(); - stringBuilder.AppendLine("Translation report for " + activeLanguage); - stringBuilder.AppendLine(); - stringBuilder.AppendLine("========== Argument count mismatches ========="); - foreach (string current in defaultLanguage.keyedReplacements.Keys.Intersect(activeLanguage.keyedReplacements.Keys)) + else { - int num = LanguageReportGenerator.CountParametersInString(defaultLanguage.keyedReplacements[current]); - int num2 = LanguageReportGenerator.CountParametersInString(activeLanguage.keyedReplacements[current]); - if (num != num2) + activeLanguage.LoadData(); + defaultLanguage.LoadData(); + StringBuilder stringBuilder = new StringBuilder(); + stringBuilder.AppendLine("Translation report for " + activeLanguage); + stringBuilder.AppendLine(); + stringBuilder.AppendLine("========== Argument count mismatches ========="); + foreach (string item in defaultLanguage.keyedReplacements.Keys.Intersect(activeLanguage.keyedReplacements.Keys)) { - stringBuilder.AppendLine(string.Format("{0} - '{1}' compared to '{2}'", current, defaultLanguage.keyedReplacements[current], activeLanguage.keyedReplacements[current])); + int num = LanguageReportGenerator.CountParametersInString(defaultLanguage.keyedReplacements[item]); + int num2 = LanguageReportGenerator.CountParametersInString(activeLanguage.keyedReplacements[item]); + if (num != num2) + { + stringBuilder.AppendLine(string.Format("{0} - '{1}' compared to '{2}'", item, defaultLanguage.keyedReplacements[item], activeLanguage.keyedReplacements[item])); + } } - } - stringBuilder.AppendLine(); - stringBuilder.AppendLine("========== Missing keyed translations ========="); - foreach (KeyValuePair current2 in defaultLanguage.keyedReplacements) - { - if (!activeLanguage.HaveTextForKey(current2.Key)) + stringBuilder.AppendLine(); + stringBuilder.AppendLine("========== Missing keyed translations ========="); + Dictionary.Enumerator enumerator2 = defaultLanguage.keyedReplacements.GetEnumerator(); + try { - stringBuilder.AppendLine(current2.Key + " - '" + current2.Value + "'"); + while (enumerator2.MoveNext()) + { + KeyValuePair current2 = enumerator2.Current; + if (!activeLanguage.HaveTextForKey(current2.Key)) + { + stringBuilder.AppendLine(current2.Key + " - '" + current2.Value + "'"); + } + } } - } - stringBuilder.AppendLine(); - stringBuilder.AppendLine("========== Unnecessary keyed translations (will never be used) ========="); - foreach (KeyValuePair current3 in activeLanguage.keyedReplacements) - { - if (!defaultLanguage.HaveTextForKey(current3.Key)) + finally { - stringBuilder.AppendLine(current3.Key + " - '" + current3.Value + "'"); + ((IDisposable)(object)enumerator2).Dispose(); } - } - stringBuilder.AppendLine(); - stringBuilder.AppendLine("========== Def-injected translations missing ========="); - stringBuilder.AppendLine("Note: This does NOT return any kind of sub-fields. So if there's a list of strings, or a sub-member of the def with a string in it or something, they won't be reported here."); - foreach (DefInjectionPackage current4 in activeLanguage.defInjections) - { - foreach (string current5 in current4.MissingInjections()) + stringBuilder.AppendLine(); + stringBuilder.AppendLine("========== Unnecessary keyed translations (will never be used) ========="); + Dictionary.Enumerator enumerator3 = activeLanguage.keyedReplacements.GetEnumerator(); + try { - stringBuilder.AppendLine(current4.defType.Name + ": " + current5); + while (enumerator3.MoveNext()) + { + KeyValuePair current3 = enumerator3.Current; + if (!defaultLanguage.HaveTextForKey(current3.Key)) + { + stringBuilder.AppendLine(current3.Key + " - '" + current3.Value + "'"); + } + } } + finally + { + ((IDisposable)(object)enumerator3).Dispose(); + } + stringBuilder.AppendLine(); + stringBuilder.AppendLine("========== Def-injected translations missing ========="); + stringBuilder.AppendLine("Note: This does NOT return any kind of sub-fields. So if there's a list of strings, or a sub-member of the def with a string in it or something, they won't be reported here."); + List.Enumerator enumerator4 = activeLanguage.defInjections.GetEnumerator(); + try + { + while (enumerator4.MoveNext()) + { + DefInjectionPackage current4 = enumerator4.Current; + foreach (string item2 in current4.MissingInjections()) + { + stringBuilder.AppendLine(current4.defType.Name + ": " + item2); + } + } + } + finally + { + ((IDisposable)(object)enumerator4).Dispose(); + } + stringBuilder.AppendLine(); + stringBuilder.AppendLine("========== Backstory translations missing ========="); + foreach (string item3 in BackstoryTranslationUtility.MissingBackstoryTranslations(activeLanguage)) + { + stringBuilder.AppendLine(item3); + } + Log.Message(stringBuilder.ToString()); + Messages.Message("Translation report about " + activeLanguage.ToString() + " written to console. Hit ` to see it.", MessageSound.Standard); } - stringBuilder.AppendLine(); - stringBuilder.AppendLine("========== Backstory translations missing ========="); - foreach (string current6 in BackstoryTranslationUtility.MissingBackstoryTranslations(activeLanguage)) - { - stringBuilder.AppendLine(current6); - } - Log.Message(stringBuilder.ToString()); - Messages.Message("Translation report about " + activeLanguage.ToString() + " written to console. Hit ` to see it.", MessageSound.Standard); } public static int CountParametersInString(string input) @@ -77,7 +106,7 @@ public static int CountParametersInString(string input) { return 0; } - return matchCollection.Cast().Max((Match m) => int.Parse(m.Groups[1].Value)) + 1; + return matchCollection.Cast().Max((Func)((Match m) => int.Parse(m.Groups[1].Value))) + 1; } } } diff --git a/Assembly-CSharp/Verse/LanguageWorker.cs b/Assembly-CSharp/Verse/LanguageWorker.cs index 7f2c5fd23..893ba9df7 100644 --- a/Assembly-CSharp/Verse/LanguageWorker.cs +++ b/Assembly-CSharp/Verse/LanguageWorker.cs @@ -13,10 +13,7 @@ public virtual string WithIndefiniteArticle(string str) } if ("IndefiniteForm".CanTranslate()) { - return "IndefiniteForm".Translate(new object[] - { - str - }); + return "IndefiniteForm".Translate(str); } return "IndefiniteArticle".Translate() + " " + str; } @@ -29,10 +26,7 @@ public virtual string WithDefiniteArticle(string str) } if ("DefiniteForm".CanTranslate()) { - return "DefiniteForm".Translate(new object[] - { - str - }); + return "DefiniteForm".Translate(str); } return "DefiniteArticle".Translate() + " " + str; } diff --git a/Assembly-CSharp/Verse/LanguageWorker_Default.cs b/Assembly-CSharp/Verse/LanguageWorker_Default.cs index f7a1edf25..310063ae4 100644 --- a/Assembly-CSharp/Verse/LanguageWorker_Default.cs +++ b/Assembly-CSharp/Verse/LanguageWorker_Default.cs @@ -1,5 +1,3 @@ -using System; - namespace Verse { public class LanguageWorker_Default : LanguageWorker diff --git a/Assembly-CSharp/Verse/LanguageWorker_English.cs b/Assembly-CSharp/Verse/LanguageWorker_English.cs index 24efdae37..7118c8f8f 100644 --- a/Assembly-CSharp/Verse/LanguageWorker_English.cs +++ b/Assembly-CSharp/Verse/LanguageWorker_English.cs @@ -62,18 +62,21 @@ public override string OrdinalNumber(int number) int num2 = number / 10 % 10; if (num2 != 1) { - if (num == 1) + switch (num) + { + case 1: { return number + "st"; } - if (num == 2) + case 2: { return number + "nd"; } - if (num == 3) + case 3: { return number + "rd"; } + } } return number + "th"; } diff --git a/Assembly-CSharp/Verse/LayerLoader.cs b/Assembly-CSharp/Verse/LayerLoader.cs index 21fbd01f5..ae0e2bb4c 100644 --- a/Assembly-CSharp/Verse/LayerLoader.cs +++ b/Assembly-CSharp/Verse/LayerLoader.cs @@ -16,11 +16,11 @@ public static void LoadFileIntoList(TextAsset ass, List NodeListToF XPathNavigator xPathNavigator = xPathDocument.CreateNavigator(); xPathNavigator.MoveToFirst(); xPathNavigator.MoveToFirstChild(); - foreach (XPathNavigator xPathNavigator2 in xPathNavigator.Select("Node")) + foreach (XPathNavigator item2 in xPathNavigator.Select("Node")) { try { - TextReader textReader2 = new StringReader(xPathNavigator2.OuterXml); + TextReader textReader2 = new StringReader(item2.OuterXml); XmlSerializer xmlSerializer = new XmlSerializer(typeof(DiaNodeMold)); DiaNodeMold diaNodeMold = (DiaNodeMold)xmlSerializer.Deserialize(textReader2); diaNodeMold.nodeType = NodesType; @@ -29,76 +29,133 @@ public static void LoadFileIntoList(TextAsset ass, List NodeListToF } catch (Exception ex) { - Log.Message(string.Concat(new object[] - { - "Exception deserializing ", - xPathNavigator2.OuterXml, - ":\n", - ex.InnerException - })); + Log.Message("Exception deserializing " + item2.OuterXml + ":\n" + ex.InnerException); + goto end_IL_0096; + IL_00d0: + end_IL_0096:; } } - foreach (XPathNavigator xPathNavigator3 in xPathNavigator.Select("NodeList")) + foreach (XPathNavigator item3 in xPathNavigator.Select("NodeList")) { try { - TextReader textReader3 = new StringReader(xPathNavigator3.OuterXml); + TextReader textReader3 = new StringReader(item3.OuterXml); XmlSerializer xmlSerializer2 = new XmlSerializer(typeof(DiaNodeList)); DiaNodeList item = (DiaNodeList)xmlSerializer2.Deserialize(textReader3); ListListToFill.Add(item); } catch (Exception ex2) { - Log.Message(string.Concat(new object[] - { - "Exception deserializing ", - xPathNavigator3.OuterXml, - ":\n", - ex2.InnerException - })); + Log.Message("Exception deserializing " + item3.OuterXml + ":\n" + ex2.InnerException); + goto end_IL_015d; + IL_0198: + end_IL_015d:; } } } public static void MarkNonRootNodes(List NodeList) { - foreach (DiaNodeMold current in NodeList) + List.Enumerator enumerator = NodeList.GetEnumerator(); + try + { + while (enumerator.MoveNext()) + { + DiaNodeMold current = enumerator.Current; + LayerLoader.RecursiveSetIsRootFalse(current); + } + } + finally { - LayerLoader.RecursiveSetIsRootFalse(current); + ((IDisposable)(object)enumerator).Dispose(); } - foreach (DiaNodeMold current2 in NodeList) + List.Enumerator enumerator2 = NodeList.GetEnumerator(); + try { - foreach (DiaNodeMold current3 in NodeList) + while (enumerator2.MoveNext()) { - foreach (DiaOptionMold current4 in current3.optionList) + DiaNodeMold current2 = enumerator2.Current; + List.Enumerator enumerator3 = NodeList.GetEnumerator(); + try { - bool flag = false; - foreach (string current5 in current4.ChildNodeNames) + while (enumerator3.MoveNext()) { - if (current5 == current2.name) + DiaNodeMold current3 = enumerator3.Current; + List.Enumerator enumerator4 = current3.optionList.GetEnumerator(); + try { - flag = true; + while (enumerator4.MoveNext()) + { + DiaOptionMold current4 = enumerator4.Current; + bool flag = false; + List.Enumerator enumerator5 = current4.ChildNodeNames.GetEnumerator(); + try + { + while (enumerator5.MoveNext()) + { + string current5 = enumerator5.Current; + if (current5 == current2.name) + { + flag = true; + } + } + } + finally + { + ((IDisposable)(object)enumerator5).Dispose(); + } + if (flag) + { + current2.isRoot = false; + } + } + } + finally + { + ((IDisposable)(object)enumerator4).Dispose(); } } - if (flag) - { - current2.isRoot = false; - } + } + finally + { + ((IDisposable)(object)enumerator3).Dispose(); } } } + finally + { + ((IDisposable)(object)enumerator2).Dispose(); + } } private static void RecursiveSetIsRootFalse(DiaNodeMold d) { - foreach (DiaOptionMold current in d.optionList) + List.Enumerator enumerator = d.optionList.GetEnumerator(); + try { - foreach (DiaNodeMold current2 in current.ChildNodes) + while (enumerator.MoveNext()) { - current2.isRoot = false; - LayerLoader.RecursiveSetIsRootFalse(current2); + DiaOptionMold current = enumerator.Current; + List.Enumerator enumerator2 = current.ChildNodes.GetEnumerator(); + try + { + while (enumerator2.MoveNext()) + { + DiaNodeMold current2 = enumerator2.Current; + current2.isRoot = false; + LayerLoader.RecursiveSetIsRootFalse(current2); + } + } + finally + { + ((IDisposable)(object)enumerator2).Dispose(); + } } } + finally + { + ((IDisposable)(object)enumerator).Dispose(); + } } } } diff --git a/Assembly-CSharp/Verse/LayerSubMesh.cs b/Assembly-CSharp/Verse/LayerSubMesh.cs index 49bbca3dc..d8d516985 100644 --- a/Assembly-CSharp/Verse/LayerSubMesh.cs +++ b/Assembly-CSharp/Verse/LayerSubMesh.cs @@ -1,4 +1,3 @@ -using System; using System.Collections.Generic; using UnityEngine; @@ -30,19 +29,19 @@ public LayerSubMesh(Mesh mesh, Material material) public void Clear(MeshParts parts) { - if ((byte)(parts & MeshParts.Verts) != 0) + if ((byte)((int)parts & 1) != 0) { this.verts.Clear(); } - if ((byte)(parts & MeshParts.Tris) != 0) + if ((byte)((int)parts & 2) != 0) { this.tris.Clear(); } - if ((byte)(parts & MeshParts.Colors) != 0) + if ((byte)((int)parts & 4) != 0) { this.colors.Clear(); } - if ((byte)(parts & MeshParts.UVs) != 0) + if ((byte)((int)parts & 8) != 0) { this.uvs.Clear(); } @@ -51,11 +50,11 @@ public void Clear(MeshParts parts) public void FinalizeMesh(MeshParts parts, bool optimize = false) { - if ((byte)(parts & MeshParts.Verts) != 0 || (byte)(parts & MeshParts.Tris) != 0) + if ((((byte)((int)parts & 1) != 0) ? 1 : ((byte)((int)parts & 2))) != 0) { this.mesh.Clear(); } - if ((byte)(parts & MeshParts.Verts) != 0) + if ((byte)((int)parts & 1) != 0) { if (this.verts.Count > 0) { @@ -66,7 +65,7 @@ public void FinalizeMesh(MeshParts parts, bool optimize = false) Log.Error("Cannot cook Verts for " + this.material.ToString() + ": no ingredients data. If you want to not render this submesh, disable it."); } } - if ((byte)(parts & MeshParts.Tris) != 0) + if ((byte)((int)parts & 2) != 0) { if (this.tris.Count > 0) { @@ -77,11 +76,11 @@ public void FinalizeMesh(MeshParts parts, bool optimize = false) Log.Error("Cannot cook Tris for " + this.material.ToString() + ": no ingredients data."); } } - if ((byte)(parts & MeshParts.Colors) != 0 && this.colors.Count > 0) + if ((byte)((int)parts & 4) != 0 && this.colors.Count > 0) { this.mesh.SetColors(this.colors); } - if ((byte)(parts & MeshParts.UVs) != 0 && this.uvs.Count > 0) + if ((byte)((int)parts & 8) != 0 && this.uvs.Count > 0) { this.mesh.SetUVs(0, this.uvs); } diff --git a/Assembly-CSharp/Verse/Letter.cs b/Assembly-CSharp/Verse/Letter.cs index 97d233303..322f50c44 100644 --- a/Assembly-CSharp/Verse/Letter.cs +++ b/Assembly-CSharp/Verse/Letter.cs @@ -30,7 +30,15 @@ public virtual bool StillValid { get { - return (this.lookTarget.Thing == null || !this.lookTarget.Thing.Destroyed) && (this.lookTarget.WorldObject == null || this.lookTarget.WorldObject.Spawned); + if (this.lookTarget.Thing != null && this.lookTarget.Thing.Destroyed) + { + return false; + } + if (this.lookTarget.WorldObject != null && !this.lookTarget.WorldObject.Spawned) + { + return false; + } + return true; } } @@ -45,7 +53,7 @@ public IThingHolder ParentHolder public virtual void ExposeData() { Scribe_Defs.Look(ref this.def, "def"); - Scribe_Values.Look(ref this.label, "label", null, false); + Scribe_Values.Look(ref this.label, "label", (string)null, false); if (Scribe.mode == LoadSaveMode.Saving && this.lookTarget.HasThing && this.lookTarget.Thing.Destroyed) { this.lookTarget = GlobalTargetInfo.Invalid; @@ -55,29 +63,29 @@ public virtual void ExposeData() public virtual void DrawButtonAt(float topY) { - float num = (float)UI.screenWidth - 38f - 12f; + float num = (float)((float)UI.screenWidth - 38.0 - 12.0); Rect rect = new Rect(num, topY, 38f, 30f); Rect rect2 = new Rect(rect); float num2 = Time.time - this.arrivalTime; Color color = this.def.color; - if (num2 < 1f) + if (num2 < 1.0) { - rect2.y -= (1f - num2) * 200f; - color.a = num2 / 1f; + rect2.y -= (float)((1.0 - num2) * 200.0); + color.a = (float)(num2 / 1.0); } - if (!Mouse.IsOver(rect) && this.def.bounce && num2 > 15f && num2 % 5f < 1f) + if (!Mouse.IsOver(rect) && this.def.bounce && num2 > 15.0 && num2 % 5.0 < 1.0) { - float num3 = (float)UI.screenWidth * 0.06f; - float num4 = 2f * (num2 % 1f) - 1f; - float num5 = num3 * (1f - num4 * num4); + float num3 = (float)((float)UI.screenWidth * 0.059999998658895493); + float num4 = (float)(2.0 * (num2 % 1.0) - 1.0); + float num5 = (float)(num3 * (1.0 - num4 * num4)); rect2.x -= num5; } - if (this.def.flashInterval > 0f) + if (this.def.flashInterval > 0.0) { - float num6 = Time.time - (this.arrivalTime + 1f); - if (num6 > 0f && num6 % this.def.flashInterval < 1f) + float num6 = (float)(Time.time - (this.arrivalTime + 1.0)); + if (num6 > 0.0 && num6 % this.def.flashInterval < 1.0) { - GenUI.DrawFlash(num, topY, (float)UI.screenWidth * 0.6f, Pulser.PulseBrightness(1f, 1f, num6) * 0.55f, this.def.flashColor); + GenUI.DrawFlash(num, topY, (float)((float)UI.screenWidth * 0.60000002384185791), (float)(Pulser.PulseBrightness(1f, 1f, num6) * 0.550000011920929), this.def.flashColor); } } GUI.color = color; @@ -90,16 +98,18 @@ public virtual void DrawButtonAt(float topY) Vector2 vector = Text.CalcSize(text); float x = vector.x; float y = vector.y; - Vector2 vector2 = new Vector2(rect2.x + rect2.width / 2f, rect2.center.y - y / 4f); - float num7 = vector2.x + x / 2f - (float)(UI.screenWidth - 2); - if (num7 > 0f) + double x2 = rect2.x + rect2.width / 2.0; + Vector2 center = rect2.center; + Vector2 vector2 = new Vector2((float)x2, (float)(center.y - y / 4.0)); + float num7 = (float)(vector2.x + x / 2.0 - (float)(UI.screenWidth - 2)); + if (num7 > 0.0) { vector2.x -= num7; } - Rect position = new Rect(vector2.x - x / 2f - 4f - 1f, vector2.y, x + 8f, 12f); + Rect position = new Rect((float)(vector2.x - x / 2.0 - 4.0 - 1.0), vector2.y, (float)(x + 8.0), 12f); GUI.DrawTexture(position, TexUI.GrayTextBG); GUI.color = new Color(1f, 1f, 1f, 0.75f); - Rect rect3 = new Rect(vector2.x - x / 2f, vector2.y - 3f, x, 999f); + Rect rect3 = new Rect((float)(vector2.x - x / 2.0), (float)(vector2.y - 3.0), x, 999f); Widgets.Label(rect3, text); GUI.color = Color.white; Text.Anchor = TextAnchor.UpperLeft; @@ -119,7 +129,7 @@ public virtual void DrawButtonAt(float topY) public virtual void CheckForMouseOverTextAt(float topY) { - float num = (float)UI.screenWidth - 38f - 12f; + float num = (float)((float)UI.screenWidth - 38.0 - 12.0); Rect rect = new Rect(num, topY, 38f, 30f); if (Mouse.IsOver(rect)) { @@ -130,10 +140,10 @@ public virtual void CheckForMouseOverTextAt(float topY) Text.Font = GameFont.Small; Text.Anchor = TextAnchor.UpperLeft; float num2 = Text.CalcHeight(mouseoverText, 310f); - num2 += 20f; - float x = num - 330f - 10f; - Rect infoRect = new Rect(x, topY - num2 / 2f, 330f, num2); - Find.WindowStack.ImmediateWindow(2768333, infoRect, WindowLayer.Super, delegate + num2 = (float)(num2 + 20.0); + float x = (float)(num - 330.0 - 10.0); + Rect infoRect = new Rect(x, (float)(topY - num2 / 2.0), 330f, num2); + Find.WindowStack.ImmediateWindow(2768333, infoRect, WindowLayer.Super, (Action)delegate { Text.Font = GameFont.Small; Rect position = infoRect.AtZero().ContractedBy(10f); diff --git a/Assembly-CSharp/Verse/LetterDef.cs b/Assembly-CSharp/Verse/LetterDef.cs index 0f07fcb81..c7fc1a770 100644 --- a/Assembly-CSharp/Verse/LetterDef.cs +++ b/Assembly-CSharp/Verse/LetterDef.cs @@ -27,7 +27,7 @@ public Texture2D Icon { get { - if (this.iconTex == null && !this.icon.NullOrEmpty()) + if ((UnityEngine.Object)this.iconTex == (UnityEngine.Object)null && !this.icon.NullOrEmpty()) { this.iconTex = ContentFinder.Get(this.icon, true); } diff --git a/Assembly-CSharp/Verse/LetterStack.cs b/Assembly-CSharp/Verse/LetterStack.cs index 4a372ecf7..ee94b3c51 100644 --- a/Assembly-CSharp/Verse/LetterStack.cs +++ b/Assembly-CSharp/Verse/LetterStack.cs @@ -68,33 +68,39 @@ public void RemoveLetter(Letter let) public void LettersOnGUI(float baseY) { - float num = baseY - 30f; - for (int i = this.letters.Count - 1; i >= 0; i--) + float num = (float)(baseY - 30.0); + for (int num2 = this.letters.Count - 1; num2 >= 0; num2--) { - this.letters[i].DrawButtonAt(num); - num -= 42f; + this.letters[num2].DrawButtonAt(num); + num = (float)(num - 42.0); } this.lastTopYInt = num; - num = baseY - 30f; - for (int j = this.letters.Count - 1; j >= 0; j--) + num = (float)(baseY - 30.0); + for (int num3 = this.letters.Count - 1; num3 >= 0; num3--) { - this.letters[j].CheckForMouseOverTextAt(num); - num -= 42f; + this.letters[num3].CheckForMouseOverTextAt(num); + num = (float)(num - 42.0); } } public void LetterStackTick() { int num = Find.TickManager.TicksGame + 1; - for (int i = 0; i < this.letters.Count; i++) + int num2 = 0; + LetterWithTimeout letterWithTimeout; + while (true) { - LetterWithTimeout letterWithTimeout = this.letters[i] as LetterWithTimeout; - if (letterWithTimeout != null && letterWithTimeout.TimeoutActive && letterWithTimeout.disappearAtTick == num) + if (num2 < this.letters.Count) { - letterWithTimeout.OpenLetter(); - break; + letterWithTimeout = (this.letters[num2] as LetterWithTimeout); + if (letterWithTimeout != null && letterWithTimeout.TimeoutActive && letterWithTimeout.disappearAtTick == num) + break; + num2++; + continue; } + return; } + letterWithTimeout.OpenLetter(); } public void LetterStackUpdate() @@ -108,11 +114,11 @@ public void LetterStackUpdate() } } this.mouseoverLetterIndex = -1; - for (int i = this.letters.Count - 1; i >= 0; i--) + for (int num = this.letters.Count - 1; num >= 0; num--) { - if (!this.letters[i].StillValid) + if (!this.letters[num].StillValid) { - this.RemoveLetter(this.letters[i]); + this.RemoveLetter(this.letters[num]); } } } @@ -125,12 +131,9 @@ public void Notify_LetterMouseover(Letter let) public void ExposeData() { Scribe_Collections.Look(ref this.letters, "letters", LookMode.Deep, new object[0]); - if (Scribe.mode == LoadSaveMode.PostLoadInit) + if (((Scribe.mode == LoadSaveMode.PostLoadInit) ? this.letters.RemoveAll((Predicate)((Letter x) => x == null)) : 0) != 0) { - if (this.letters.RemoveAll((Letter x) => x == null) != 0) - { - Log.Error("Some letters were null."); - } + Log.Error("Some letters were null."); } } } diff --git a/Assembly-CSharp/Verse/LetterWithTimeout.cs b/Assembly-CSharp/Verse/LetterWithTimeout.cs index 29f9fea53..08a055b0f 100644 --- a/Assembly-CSharp/Verse/LetterWithTimeout.cs +++ b/Assembly-CSharp/Verse/LetterWithTimeout.cs @@ -1,4 +1,3 @@ -using System; using UnityEngine; namespace Verse @@ -19,7 +18,15 @@ public override bool StillValid { get { - return base.StillValid && (!this.TimeoutActive || Find.TickManager.TicksGame < this.disappearAtTick); + if (!base.StillValid) + { + return false; + } + if (this.TimeoutActive && Find.TickManager.TicksGame >= this.disappearAtTick) + { + return false; + } + return true; } } @@ -39,16 +46,9 @@ protected override string PostProcessedLabel() string text = base.PostProcessedLabel(); if (this.TimeoutActive) { - int num = Mathf.RoundToInt((float)(this.disappearAtTick - Find.TickManager.TicksGame) / 2500f); + int num = Mathf.RoundToInt((float)((float)(this.disappearAtTick - Find.TickManager.TicksGame) / 2500.0)); string text2 = text; - text = string.Concat(new object[] - { - text2, - " (", - num, - "LetterHour".Translate(), - ")" - }); + text = text2 + " (" + num + "LetterHour".Translate() + ")"; } return text; } diff --git a/Assembly-CSharp/Verse/LifeStageAge.cs b/Assembly-CSharp/Verse/LifeStageAge.cs index 9ddf1f36a..4e4a2d6ee 100644 --- a/Assembly-CSharp/Verse/LifeStageAge.cs +++ b/Assembly-CSharp/Verse/LifeStageAge.cs @@ -1,5 +1,4 @@ using RimWorld; -using System; using UnityEngine; namespace Verse @@ -27,7 +26,7 @@ public class LifeStageAge public Texture2D GetIcon(Pawn forPawn) { - if (this.def.iconTex != null) + if ((Object)this.def.iconTex != (Object)null) { return this.def.iconTex; } diff --git a/Assembly-CSharp/Verse/LifeStageUtility.cs b/Assembly-CSharp/Verse/LifeStageUtility.cs index 9b0e36a3f..43b51482c 100644 --- a/Assembly-CSharp/Verse/LifeStageUtility.cs +++ b/Assembly-CSharp/Verse/LifeStageUtility.cs @@ -7,46 +7,38 @@ public static class LifeStageUtility { public static void PlayNearestLifestageSound(Pawn pawn, Func getter, float volumeFactor = 1f) { - SoundDef soundDef; - float pitchFactor; - float num; + SoundDef soundDef = default(SoundDef); + float pitchFactor = default(float); + float num = default(float); LifeStageUtility.GetNearestLifestageSound(pawn, getter, out soundDef, out pitchFactor, out num); - if (soundDef == null) + if (soundDef != null && pawn.SpawnedOrAnyParentSpawned) { - return; + SoundInfo info = SoundInfo.InMap(new TargetInfo(pawn.PositionHeld, pawn.MapHeld, false), MaintenanceType.None); + info.pitchFactor = pitchFactor; + info.volumeFactor = num * volumeFactor; + soundDef.PlayOneShot(info); } - if (!pawn.SpawnedOrAnyParentSpawned) - { - return; - } - SoundInfo info = SoundInfo.InMap(new TargetInfo(pawn.PositionHeld, pawn.MapHeld, false), MaintenanceType.None); - info.pitchFactor = pitchFactor; - info.volumeFactor = num * volumeFactor; - soundDef.PlayOneShot(info); } private static void GetNearestLifestageSound(Pawn pawn, Func getter, out SoundDef def, out float pitch, out float volume) { int num = pawn.ageTracker.CurLifeStageIndex; - LifeStageAge lifeStageAge; while (true) { - lifeStageAge = pawn.RaceProps.lifeStageAges[num]; + LifeStageAge lifeStageAge = pawn.RaceProps.lifeStageAges[num]; def = getter(lifeStageAge); if (def != null) { - break; + pitch = pawn.ageTracker.CurLifeStage.voxPitch / lifeStageAge.def.voxPitch; + volume = pawn.ageTracker.CurLifeStage.voxVolume / lifeStageAge.def.voxVolume; + return; } num++; - if (num < 0 || num >= pawn.RaceProps.lifeStageAges.Count) - { - goto IL_8D; - } + if (num < 0) + break; + if (num >= pawn.RaceProps.lifeStageAges.Count) + break; } - pitch = pawn.ageTracker.CurLifeStage.voxPitch / lifeStageAge.def.voxPitch; - volume = pawn.ageTracker.CurLifeStage.voxVolume / lifeStageAge.def.voxVolume; - return; - IL_8D: def = null; pitch = (volume = 1f); } diff --git a/Assembly-CSharp/Verse/LinkDrawerType.cs b/Assembly-CSharp/Verse/LinkDrawerType.cs index 2ab9b132f..2140573d0 100644 --- a/Assembly-CSharp/Verse/LinkDrawerType.cs +++ b/Assembly-CSharp/Verse/LinkDrawerType.cs @@ -1,13 +1,11 @@ -using System; - namespace Verse { public enum LinkDrawerType : byte { - None, - Basic, - CornerFiller, - Transmitter, - TransmitterOverlay + None = 0, + Basic = 1, + CornerFiller = 2, + Transmitter = 3, + TransmitterOverlay = 4 } } diff --git a/Assembly-CSharp/Verse/LinkGrid.cs b/Assembly-CSharp/Verse/LinkGrid.cs index 11a65f84e..165300049 100644 --- a/Assembly-CSharp/Verse/LinkGrid.cs +++ b/Assembly-CSharp/Verse/LinkGrid.cs @@ -1,4 +1,3 @@ -using System; using System.Collections.Generic; namespace Verse diff --git a/Assembly-CSharp/Verse/ListableOption_WebLink.cs b/Assembly-CSharp/Verse/ListableOption_WebLink.cs index 3d8101e68..f9a2c64c0 100644 --- a/Assembly-CSharp/Verse/ListableOption_WebLink.cs +++ b/Assembly-CSharp/Verse/ListableOption_WebLink.cs @@ -11,9 +11,9 @@ public class ListableOption_WebLink : ListableOption private static readonly Vector2 Imagesize = new Vector2(24f, 18f); - public ListableOption_WebLink(string label, Texture2D image) : base(label, null, null) + public ListableOption_WebLink(string label, Texture2D image) : base(label, null, (string)null) { - this.minHeight = 24f; + base.minHeight = 24f; this.image = image; } @@ -24,19 +24,27 @@ public ListableOption_WebLink(string label, string url, Texture2D image) : this( public ListableOption_WebLink(string label, Action action, Texture2D image) : this(label, image) { - this.action = action; + base.action = action; } public override float DrawOption(Vector2 pos, float width) { - float num = width - ListableOption_WebLink.Imagesize.x - 3f; - float num2 = Text.CalcHeight(this.label, num); - float num3 = Mathf.Max(this.minHeight, num2); + Vector2 imagesize = ListableOption_WebLink.Imagesize; + float num = (float)(width - imagesize.x - 3.0); + float num2 = Text.CalcHeight(base.label, num); + float num3 = Mathf.Max(base.minHeight, num2); Rect rect = new Rect(pos.x, pos.y, width, num3); GUI.color = Color.white; - if (this.image != null) + if ((UnityEngine.Object)this.image != (UnityEngine.Object)null) { - Rect position = new Rect(pos.x, pos.y + num3 / 2f - ListableOption_WebLink.Imagesize.y / 2f, ListableOption_WebLink.Imagesize.x, ListableOption_WebLink.Imagesize.y); + float x = pos.x; + double num4 = pos.y + num3 / 2.0; + Vector2 imagesize2 = ListableOption_WebLink.Imagesize; + double y = num4 - imagesize2.y / 2.0; + Vector2 imagesize3 = ListableOption_WebLink.Imagesize; + float x2 = imagesize3.x; + Vector2 imagesize4 = ListableOption_WebLink.Imagesize; + Rect position = new Rect(x, (float)y, x2, imagesize4.y); if (Mouse.IsOver(rect)) { GUI.color = Widgets.MouseoverOptionColor; @@ -44,13 +52,13 @@ public override float DrawOption(Vector2 pos, float width) GUI.DrawTexture(position, this.image); } Rect rect2 = new Rect(rect.xMax - num, pos.y, num, num2); - Widgets.Label(rect2, this.label); + Widgets.Label(rect2, base.label); GUI.color = Color.white; if (Widgets.ButtonInvisible(rect, true)) { - if (this.action != null) + if ((object)base.action != null) { - this.action(); + base.action(); } else { diff --git a/Assembly-CSharp/Verse/ListerBuildings.cs b/Assembly-CSharp/Verse/ListerBuildings.cs index 1e870603e..30eb90a1c 100644 --- a/Assembly-CSharp/Verse/ListerBuildings.cs +++ b/Assembly-CSharp/Verse/ListerBuildings.cs @@ -1,7 +1,6 @@ using RimWorld; using System; using System.Collections.Generic; -using System.Diagnostics; using Verse.AI; namespace Verse @@ -17,9 +16,7 @@ public sealed class ListerBuildings public void Add(Building b) { if (b.def.building != null && b.def.building.isNaturalRock) - { return; - } if (b.Faction == Faction.OfPlayer) { this.allBuildingsColonist.Add(b); @@ -92,35 +89,37 @@ public bool ColonistsHaveBuildingWithPowerOn(ThingDef def) if (this.allBuildingsColonist[i].def == def) { CompPowerTrader compPowerTrader = this.allBuildingsColonist[i].TryGetComp(); - if (compPowerTrader == null || compPowerTrader.PowerOn) + if (compPowerTrader != null && !compPowerTrader.PowerOn) { - return true; + continue; } + return true; } } return false; } - [DebuggerHidden] public IEnumerable AllBuildingsColonistOfDef(ThingDef def) { - ListerBuildings.c__Iterator1F8 c__Iterator1F = new ListerBuildings.c__Iterator1F8(); - c__Iterator1F.def = def; - c__Iterator1F.<$>def = def; - c__Iterator1F.<>f__this = this; - ListerBuildings.c__Iterator1F8 expr_1C = c__Iterator1F; - expr_1C.$PC = -2; - return expr_1C; + for (int i = 0; i < this.allBuildingsColonist.Count; i++) + { + if (this.allBuildingsColonist[i].def == def) + { + yield return this.allBuildingsColonist[i]; + } + } } - [DebuggerHidden] public IEnumerable AllBuildingsColonistOfClass() where T : Building { - ListerBuildings.c__Iterator1F9 c__Iterator1F = new ListerBuildings.c__Iterator1F9(); - c__Iterator1F.<>f__this = this; - ListerBuildings.c__Iterator1F9 expr_0E = c__Iterator1F; - expr_0E.$PC = -2; - return expr_0E; + for (int i = 0; i < this.allBuildingsColonist.Count; i++) + { + T casted = (T)(this.allBuildingsColonist[i] as T); + if (casted != null) + { + yield return casted; + } + } } } } diff --git a/Assembly-CSharp/Verse/ListerThings.cs b/Assembly-CSharp/Verse/ListerThings.cs index da1859946..f30bbbbcc 100644 --- a/Assembly-CSharp/Verse/ListerThings.cs +++ b/Assembly-CSharp/Verse/ListerThings.cs @@ -42,22 +42,19 @@ public List ThingsMatching(ThingRequest req) { if (req.singleDef != null) { - List result; + List result = default(List); if (!this.listsByDef.TryGetValue(req.singleDef, out result)) { return ListerThings.EmptyList; } return result; } - else + if (req.group != 0) { - if (req.group != ThingRequestGroup.Undefined) - { - List list = this.listsByGroup[(int)req.group]; - return list ?? ListerThings.EmptyList; - } - throw new InvalidOperationException("Invalid ThingRequest " + req); + List list = this.listsByGroup[(uint)req.group]; + return list ?? ListerThings.EmptyList; } + throw new InvalidOperationException("Invalid ThingRequest " + req); } public bool Contains(Thing t) @@ -67,30 +64,25 @@ public bool Contains(Thing t) public void Add(Thing t) { - if (!ListerThings.EverListable(t.def, this.use)) - { - return; - } - List list; - if (!this.listsByDef.TryGetValue(t.def, out list)) + if (ListerThings.EverListable(t.def, this.use)) { - list = new List(); - this.listsByDef.Add(t.def, list); - } - list.Add(t); - ThingRequestGroup[] allGroups = ThingListGroupHelper.AllGroups; - for (int i = 0; i < allGroups.Length; i++) - { - ThingRequestGroup thingRequestGroup = allGroups[i]; - if (this.use != ListerThingsUse.Region || thingRequestGroup.StoreInRegion()) + List list = default(List); + if (!this.listsByDef.TryGetValue(t.def, out list)) + { + list = new List(); + this.listsByDef.Add(t.def, list); + } + list.Add(t); + ThingRequestGroup[] allGroups = ThingListGroupHelper.AllGroups; + for (int i = 0; i < allGroups.Length; i++) { - if (thingRequestGroup.Includes(t.def)) + ThingRequestGroup thingRequestGroup = allGroups[i]; + if ((this.use != ListerThingsUse.Region || thingRequestGroup.StoreInRegion()) && thingRequestGroup.Includes(t.def)) { - List list2 = this.listsByGroup[(int)thingRequestGroup]; + List list2 = this.listsByGroup[(uint)thingRequestGroup]; if (list2 == null) { - list2 = new List(); - this.listsByGroup[(int)thingRequestGroup] = list2; + list2 = (this.listsByGroup[(uint)thingRequestGroup] = new List()); } list2.Add(t); } @@ -100,18 +92,14 @@ public void Add(Thing t) public void Remove(Thing t) { - if (!ListerThings.EverListable(t.def, this.use)) + if (ListerThings.EverListable(t.def, this.use)) { - return; - } - this.listsByDef[t.def].Remove(t); - ThingRequestGroup[] allGroups = ThingListGroupHelper.AllGroups; - for (int i = 0; i < allGroups.Length; i++) - { - ThingRequestGroup group = allGroups[i]; - if (this.use != ListerThingsUse.Region || group.StoreInRegion()) + this.listsByDef[t.def].Remove(t); + ThingRequestGroup[] allGroups = ThingListGroupHelper.AllGroups; + for (int i = 0; i < allGroups.Length; i++) { - if (group.Includes(t.def)) + ThingRequestGroup group = allGroups[i]; + if ((this.use != ListerThingsUse.Region || group.StoreInRegion()) && group.Includes(t.def)) { this.listsByGroup[i].Remove(t); } @@ -121,7 +109,19 @@ public void Remove(Thing t) public static bool EverListable(ThingDef def, ListerThingsUse use) { - return (def.category != ThingCategory.Mote || (def.drawGUIOverlay && use != ListerThingsUse.Region)) && (def.category != ThingCategory.Projectile || use != ListerThingsUse.Region) && def.category != ThingCategory.Gas; + if (def.category == ThingCategory.Mote && (!def.drawGUIOverlay || use == ListerThingsUse.Region)) + { + return false; + } + if (def.category == ThingCategory.Projectile && use == ListerThingsUse.Region) + { + return false; + } + if (def.category == ThingCategory.Gas) + { + return false; + } + return true; } } } diff --git a/Assembly-CSharp/Verse/ListerThingsUse.cs b/Assembly-CSharp/Verse/ListerThingsUse.cs index 07946d792..5819e9324 100644 --- a/Assembly-CSharp/Verse/ListerThingsUse.cs +++ b/Assembly-CSharp/Verse/ListerThingsUse.cs @@ -1,11 +1,9 @@ -using System; - namespace Verse { public enum ListerThingsUse : byte { - Undefined, - Global, - Region + Undefined = 0, + Global = 1, + Region = 2 } } diff --git a/Assembly-CSharp/Verse/Listing.cs b/Assembly-CSharp/Verse/Listing.cs index 6c13de3e1..afe9a6ee5 100644 --- a/Assembly-CSharp/Verse/Listing.cs +++ b/Assembly-CSharp/Verse/Listing.cs @@ -1,4 +1,3 @@ -using System; using UnityEngine; namespace Verse @@ -45,7 +44,7 @@ public float ColumnWidth public void NewColumn() { this.curY = 0f; - this.curX += this.ColumnWidth + 17f; + this.curX += (float)(this.ColumnWidth + 17.0); } protected void NewColumnIfNeeded(float neededHeight) @@ -71,7 +70,7 @@ public void Gap(float gapHeight = 12f) public void GapLine(float gapHeight = 12f) { - float y = this.curY + gapHeight / 2f; + float y = (float)(this.curY + gapHeight / 2.0); Color color = GUI.color; GUI.color = color * new Color(1f, 1f, 1f, 0.4f); Widgets.DrawLineHorizontal(this.curX, y, this.ColumnWidth); @@ -86,14 +85,7 @@ public virtual void Begin(Rect rect) { if (this.columnWidthInt > this.listingRect.width) { - Log.Error(string.Concat(new object[] - { - "Listing set ColumnWith to ", - this.columnWidthInt, - " which is more than the whole listing rect width of ", - this.listingRect.width, - ". Clamping." - })); + Log.Error("Listing set ColumnWith to " + this.columnWidthInt + " which is more than the whole listing rect width of " + this.listingRect.width + ". Clamping."); this.columnWidthInt = this.listingRect.width; } } diff --git a/Assembly-CSharp/Verse/Listing_Lines.cs b/Assembly-CSharp/Verse/Listing_Lines.cs index 0ddc9911d..76450a27f 100644 --- a/Assembly-CSharp/Verse/Listing_Lines.cs +++ b/Assembly-CSharp/Verse/Listing_Lines.cs @@ -1,5 +1,3 @@ -using System; - namespace Verse { public abstract class Listing_Lines : Listing @@ -8,7 +6,7 @@ public abstract class Listing_Lines : Listing protected void EndLine() { - this.curY += this.lineHeight + this.verticalSpacing; + base.curY += this.lineHeight + base.verticalSpacing; } } } diff --git a/Assembly-CSharp/Verse/Listing_ScenEdit.cs b/Assembly-CSharp/Verse/Listing_ScenEdit.cs index 4c5597834..821a91f23 100644 --- a/Assembly-CSharp/Verse/Listing_ScenEdit.cs +++ b/Assembly-CSharp/Verse/Listing_ScenEdit.cs @@ -1,5 +1,4 @@ using RimWorld; -using System; using UnityEngine; using Verse.Sound; @@ -20,17 +19,17 @@ public Rect GetScenPartRect(ScenPart part, float height) Rect rect = base.GetRect(height); Widgets.DrawBoxSolid(rect, new Color(1f, 1f, 1f, 0.08f)); WidgetRow widgetRow = new WidgetRow(rect.x, rect.y, UIDirection.RightThenDown, 72f, 0f); - if (part.def.PlayerAddRemovable && widgetRow.ButtonIcon(TexButton.DeleteX, null)) + if (part.def.PlayerAddRemovable && widgetRow.ButtonIcon(TexButton.DeleteX, (string)null)) { this.scen.RemovePart(part); SoundDefOf.Click.PlayOneShotOnCamera(null); } - if (this.scen.CanReorder(part, ReorderDirection.Up) && widgetRow.ButtonIcon(TexButton.ReorderUp, null)) + if (this.scen.CanReorder(part, ReorderDirection.Up) && widgetRow.ButtonIcon(TexButton.ReorderUp, (string)null)) { this.scen.Reorder(part, ReorderDirection.Up); SoundDefOf.TickHigh.PlayOneShotOnCamera(null); } - if (this.scen.CanReorder(part, ReorderDirection.Down) && widgetRow.ButtonIcon(TexButton.ReorderDown, null)) + if (this.scen.CanReorder(part, ReorderDirection.Down) && widgetRow.ButtonIcon(TexButton.ReorderDown, (string)null)) { this.scen.Reorder(part, ReorderDirection.Down); SoundDefOf.TickLow.PlayOneShotOnCamera(null); diff --git a/Assembly-CSharp/Verse/Listing_Standard.cs b/Assembly-CSharp/Verse/Listing_Standard.cs index 5929278fc..bafe40bc5 100644 --- a/Assembly-CSharp/Verse/Listing_Standard.cs +++ b/Assembly-CSharp/Verse/Listing_Standard.cs @@ -37,11 +37,11 @@ public override void End() base.End(); if (this.labelScrollbarPositions != null) { - for (int i = this.labelScrollbarPositions.Count - 1; i >= 0; i--) + for (int num = this.labelScrollbarPositions.Count - 1; num >= 0; num--) { - if (!this.labelScrollbarPositionsSetThisFrame.Contains(this.labelScrollbarPositions[i].First)) + if (!this.labelScrollbarPositionsSetThisFrame.Contains(this.labelScrollbarPositions[num].First)) { - this.labelScrollbarPositions.RemoveAt(i); + this.labelScrollbarPositions.RemoveAt(num); } } this.labelScrollbarPositionsSetThisFrame.Clear(); @@ -52,7 +52,7 @@ public void Label(string label, float maxHeight = -1f) { float num = Text.CalcHeight(label, base.ColumnWidth); bool flag = false; - if (maxHeight >= 0f && num > maxHeight) + if (maxHeight >= 0.0 && num > maxHeight) { num = maxHeight; flag = true; @@ -60,20 +60,20 @@ public void Label(string label, float maxHeight = -1f) Rect rect = base.GetRect(num); if (flag) { - Vector2 labelScrollbarPosition = this.GetLabelScrollbarPosition(this.curX, this.curY); + Vector2 labelScrollbarPosition = this.GetLabelScrollbarPosition(base.curX, base.curY); Widgets.LabelScrollable(rect, label, ref labelScrollbarPosition); - this.SetLabelScrollbarPosition(this.curX, this.curY, labelScrollbarPosition); + this.SetLabelScrollbarPosition(base.curX, base.curY, labelScrollbarPosition); } else { Widgets.Label(rect, label); } - base.Gap(this.verticalSpacing); + base.Gap(base.verticalSpacing); } public void LabelDouble(string leftLabel, string rightLabel) { - float num = base.ColumnWidth / 2f; + float num = (float)(base.ColumnWidth / 2.0); float width = base.ColumnWidth - num; float a = Text.CalcHeight(leftLabel, num); float b = Text.CalcHeight(rightLabel, width); @@ -81,15 +81,15 @@ public void LabelDouble(string leftLabel, string rightLabel) Rect rect = base.GetRect(height); Widgets.Label(rect.LeftHalf(), leftLabel); Widgets.Label(rect.RightHalf(), rightLabel); - base.Gap(this.verticalSpacing); + base.Gap(base.verticalSpacing); } - public bool RadioButton(string label, bool active, float tabIn = 0f) + public bool RadioButton(string label, bool active, float tabIn = 0) { float lineHeight = Text.LineHeight; base.NewColumnIfNeeded(lineHeight); - bool result = Widgets.RadioButtonLabeled(new Rect(this.curX + tabIn, this.curY, base.ColumnWidth - tabIn, lineHeight), label, active); - this.curY += lineHeight + this.verticalSpacing; + bool result = Widgets.RadioButtonLabeled(new Rect(base.curX + tabIn, base.curY, base.ColumnWidth - tabIn, lineHeight), label, active); + base.curY += lineHeight + base.verticalSpacing; return result; } @@ -106,7 +106,7 @@ public void CheckboxLabeled(string label, ref bool checkOn, string tooltip = nul TooltipHandler.TipRegion(rect, tooltip); } Widgets.CheckboxLabeled(rect, label, ref checkOn, false); - base.Gap(this.verticalSpacing); + base.Gap(base.verticalSpacing); } public bool CheckboxLabeledSelectable(string label, ref bool selected, ref bool checkOn) @@ -114,7 +114,7 @@ public bool CheckboxLabeledSelectable(string label, ref bool selected, ref bool float lineHeight = Text.LineHeight; Rect rect = base.GetRect(lineHeight); bool result = Widgets.CheckboxLabeledSelectable(rect, label, ref selected, ref checkOn); - base.Gap(this.verticalSpacing); + base.Gap(base.verticalSpacing); return result; } @@ -126,7 +126,7 @@ public bool ButtonText(string label, string highlightTag = null) { UIHighlighter.HighlightOpportunity(rect, highlightTag); } - base.Gap(this.verticalSpacing); + base.Gap(base.verticalSpacing); return result; } @@ -135,31 +135,23 @@ public bool ButtonTextLabeled(string label, string buttonLabel) Rect rect = base.GetRect(30f); Widgets.Label(rect.LeftHalf(), label); bool result = Widgets.ButtonText(rect.RightHalf(), buttonLabel, true, false, true); - base.Gap(this.verticalSpacing); + base.Gap(base.verticalSpacing); return result; } public bool ButtonImage(Texture2D tex, float width, float height) { base.NewColumnIfNeeded(height); - bool result = Widgets.ButtonImage(new Rect(this.curX, this.curY, width, height), tex); - base.Gap(height + this.verticalSpacing); + bool result = Widgets.ButtonImage(new Rect(base.curX, base.curY, width, height), tex); + base.Gap(height + base.verticalSpacing); return result; } public string TextEntry(string text, int lineCount = 1) { Rect rect = base.GetRect(Text.LineHeight * (float)lineCount); - string result; - if (lineCount == 1) - { - result = Widgets.TextField(rect, text); - } - else - { - result = Widgets.TextArea(rect, text, false); - } - base.Gap(this.verticalSpacing); + string result = (lineCount != 1) ? Widgets.TextArea(rect, text, false) : Widgets.TextField(rect, text); + base.Gap(base.verticalSpacing); return result; } @@ -167,36 +159,36 @@ public string TextEntryLabeled(string label, string text, int lineCount = 1) { Rect rect = base.GetRect(Text.LineHeight * (float)lineCount); string result = Widgets.TextEntryLabeled(rect, label, text); - base.Gap(this.verticalSpacing); + base.Gap(base.verticalSpacing); return result; } - public void TextFieldNumeric(ref T val, ref string buffer, float min = 0f, float max = 1E+09f) where T : struct + public void TextFieldNumeric(ref T val, ref string buffer, float min = 0, float max = 1000000000) where T : struct { Rect rect = base.GetRect(Text.LineHeight); Widgets.TextFieldNumeric(rect, ref val, ref buffer, min, max); - base.Gap(this.verticalSpacing); + base.Gap(base.verticalSpacing); } - public void TextFieldNumericLabeled(string label, ref int val, ref string buffer, float min = 0f, float max = 1E+09f) + public void TextFieldNumericLabeled(string label, ref int val, ref string buffer, float min = 0, float max = 1000000000) { Rect rect = base.GetRect(Text.LineHeight); Widgets.TextFieldNumericLabeled(rect, label, ref val, ref buffer, min, max); - base.Gap(this.verticalSpacing); + base.Gap(base.verticalSpacing); } public void IntRange(ref IntRange range, int min, int max) { Rect rect = base.GetRect(Text.LineHeight); - Widgets.IntRange(rect, (int)base.CurHeight, ref range, min, max, null, 0); - base.Gap(this.verticalSpacing); + Widgets.IntRange(rect, (int)base.CurHeight, ref range, min, max, (string)null, 0); + base.Gap(base.verticalSpacing); } public float Slider(float val, float min, float max) { Rect rect = base.GetRect(30f); - float result = Widgets.HorizontalSlider(rect, val, min, max, false, null, null, null, -1f); - base.Gap(this.verticalSpacing); + float result = Widgets.HorizontalSlider(rect, val, min, max, false, (string)null, (string)null, (string)null, -1f); + base.Gap(base.verticalSpacing); return result; } @@ -213,7 +205,7 @@ public void IntAdjuster(ref int val, int countChange, int min = 0) val = min; } } - rect.x += rect.width + 2f; + rect.x += (float)(rect.width + 2.0); if (Widgets.ButtonText(rect, "+" + countChange, true, false, true)) { SoundDefOf.AmountIncrement.PlayOneShotOnCamera(null); @@ -223,10 +215,10 @@ public void IntAdjuster(ref int val, int countChange, int min = 0) val = min; } } - base.Gap(this.verticalSpacing); + base.Gap(base.verticalSpacing); } - public void IntSetter(ref int val, int target, string label, float width = 42f) + public void IntSetter(ref int val, int target, string label, float width = 42) { Rect rect = base.GetRect(24f); if (Widgets.ButtonText(rect, label, true, false, true)) @@ -234,7 +226,7 @@ public void IntSetter(ref int val, int target, string label, float width = 42f) SoundDefOf.TickLow.PlayOneShotOnCamera(null); val = target; } - base.Gap(this.verticalSpacing); + base.Gap(base.verticalSpacing); } private Vector2 GetLabelScrollbarPosition(float x, float y) @@ -277,9 +269,9 @@ private void SetLabelScrollbarPosition(float x, float y, Vector2 scrollbarPositi public bool SelectableDef(string name, bool selected, Action deleteCallback) { Text.Font = GameFont.Tiny; - float width = this.listingRect.width - 21f; + float width = (float)(base.listingRect.width - 21.0); Text.Anchor = TextAnchor.MiddleLeft; - Rect rect = new Rect(this.curX, this.curY, width, 21f); + Rect rect = new Rect(base.curX, base.curY, width, 21f); if (selected) { Widgets.DrawHighlight(rect); @@ -291,7 +283,7 @@ public bool SelectableDef(string name, bool selected, Action deleteCallback) Text.WordWrap = false; Widgets.Label(rect, name); Text.WordWrap = true; - if (deleteCallback != null) + if ((object)deleteCallback != null) { Rect butRect = new Rect(rect.xMax, rect.y, 21f, 21f); if (Widgets.ButtonImage(butRect, TexButton.DeleteX)) @@ -300,7 +292,7 @@ public bool SelectableDef(string name, bool selected, Action deleteCallback) } } Text.Anchor = TextAnchor.UpperLeft; - this.curY += 21f; + base.curY += 21f; return Widgets.ButtonInvisible(rect, false); } @@ -308,8 +300,8 @@ public void LabelCheckboxDebug(string label, ref bool checkOn) { Text.Font = GameFont.Tiny; base.NewColumnIfNeeded(22f); - Widgets.CheckboxLabeled(new Rect(this.curX, this.curY, base.ColumnWidth, 22f), label, ref checkOn, false); - base.Gap(22f + this.verticalSpacing); + Widgets.CheckboxLabeled(new Rect(base.curX, base.curY, base.ColumnWidth, 22f), label, ref checkOn, false); + base.Gap((float)(22.0 + base.verticalSpacing)); } public bool ButtonDebug(string label) @@ -318,9 +310,9 @@ public bool ButtonDebug(string label) base.NewColumnIfNeeded(22f); bool wordWrap = Text.WordWrap; Text.WordWrap = false; - bool result = Widgets.ButtonText(new Rect(this.curX, this.curY, base.ColumnWidth, 22f), label, true, false, true); + bool result = Widgets.ButtonText(new Rect(base.curX, base.curY, base.ColumnWidth, 22f), label, true, false, true); Text.WordWrap = wordWrap; - base.Gap(22f + this.verticalSpacing); + base.Gap((float)(22.0 + base.verticalSpacing)); return result; } } diff --git a/Assembly-CSharp/Verse/Listing_Tree.cs b/Assembly-CSharp/Verse/Listing_Tree.cs index ba06dd538..ccb8d4fab 100644 --- a/Assembly-CSharp/Verse/Listing_Tree.cs +++ b/Assembly-CSharp/Verse/Listing_Tree.cs @@ -1,4 +1,3 @@ -using System; using UnityEngine; namespace Verse @@ -13,7 +12,7 @@ protected virtual float LabelWidth { get { - return base.ColumnWidth - 26f; + return (float)(base.ColumnWidth - 26.0); } } @@ -46,8 +45,10 @@ protected float XAtIndentLevel(int indentLevel) protected void LabelLeft(string label, string tipText, int indentLevel) { - Rect rect = new Rect(0f, this.curY, base.ColumnWidth, this.lineHeight); - rect.xMin = this.XAtIndentLevel(indentLevel) + 18f; + Rect rect = new Rect(0f, base.curY, base.ColumnWidth, base.lineHeight) + { + xMin = (float)(this.XAtIndentLevel(indentLevel) + 18.0) + }; Widgets.DrawHighlightIfMouseover(rect); if (!tipText.NullOrEmpty()) { @@ -72,7 +73,7 @@ protected bool OpenCloseWidget(TreeNode node, int indentLevel, int openMask) return false; } float x = this.XAtIndentLevel(indentLevel); - float y = this.curY + this.lineHeight / 2f - 9f; + float y = (float)(base.curY + base.lineHeight / 2.0 - 9.0); Rect butRect = new Rect(x, y, 18f, 18f); Texture2D tex = (!node.IsOpen(openMask)) ? TexButton.Reveal : TexButton.Collapse; if (Widgets.ButtonImage(butRect, tex)) @@ -86,11 +87,13 @@ protected bool OpenCloseWidget(TreeNode node, int indentLevel, int openMask) public void InfoText(string text, int indentLevel) { Text.WordWrap = true; - Rect rect = new Rect(0f, this.curY, base.ColumnWidth, 50f); - rect.xMin = this.LabelWidth; + Rect rect = new Rect(0f, base.curY, base.ColumnWidth, 50f) + { + xMin = this.LabelWidth + }; rect.height = Text.CalcHeight(text, rect.width); Widgets.Label(rect, text); - this.curY += rect.height; + base.curY += rect.height; Text.WordWrap = false; } @@ -98,17 +101,17 @@ public bool ButtonText(string label) { Text.WordWrap = true; float num = Text.CalcHeight(label, base.ColumnWidth); - Rect rect = new Rect(0f, this.curY, base.ColumnWidth, num); + Rect rect = new Rect(0f, base.curY, base.ColumnWidth, num); bool result = Widgets.ButtonText(rect, label, true, false, true); - this.curY += num; + base.curY += num; Text.WordWrap = false; return result; } public WidgetRow StartWidgetsRow(int indentLevel) { - WidgetRow result = new WidgetRow(this.LabelWidth, this.curY, UIDirection.RightThenUp, 99999f, 4f); - this.curY += 24f; + WidgetRow result = new WidgetRow(this.LabelWidth, base.curY, UIDirection.RightThenUp, 99999f, 4f); + base.curY += 24f; return result; } } diff --git a/Assembly-CSharp/Verse/Listing_TreeDefs.cs b/Assembly-CSharp/Verse/Listing_TreeDefs.cs index 55db3f0f3..878c1ab98 100644 --- a/Assembly-CSharp/Verse/Listing_TreeDefs.cs +++ b/Assembly-CSharp/Verse/Listing_TreeDefs.cs @@ -29,11 +29,13 @@ public void ContentLines(TreeNode_Editor node, int indentLevel) if (node.children == null) { Log.Error(node + " children is null."); - return; } - for (int i = 0; i < node.children.Count; i++) + else { - this.Node((TreeNode_Editor)node.children[i], indentLevel, 64); + for (int i = 0; i < node.children.Count; i++) + { + this.Node((TreeNode_Editor)node.children[i], indentLevel, 64); + } } } @@ -44,7 +46,7 @@ private void Node(TreeNode_Editor node, int indentLevel, int openMask) node.DoSpecialPreElements(this); base.OpenCloseWidget(node, indentLevel, openMask); this.NodeLabelLeft(node, indentLevel); - WidgetRow widgetRow = new WidgetRow(this.LabelWidth, this.curY, UIDirection.RightThenUp, 99999f, 4f); + WidgetRow widgetRow = new WidgetRow(this.LabelWidth, base.curY, UIDirection.RightThenUp, 99999f, 4f); this.ControlButtonsRight(node, widgetRow); this.ValueEditWidgetRight(node, widgetRow.FinalX); base.EndLine(); @@ -53,7 +55,7 @@ private void Node(TreeNode_Editor node, int indentLevel, int openMask) { base.OpenCloseWidget(node, indentLevel, openMask); this.NodeLabelLeft(node, indentLevel); - WidgetRow widgetRow2 = new WidgetRow(this.LabelWidth, this.curY, UIDirection.RightThenUp, 99999f, 4f); + WidgetRow widgetRow2 = new WidgetRow(this.LabelWidth, base.curY, UIDirection.RightThenUp, 99999f, 4f); this.ControlButtonsRight(node, widgetRow2); this.ExtraInfoText(node, widgetRow2); base.EndLine(); @@ -70,28 +72,28 @@ private void Node(TreeNode_Editor node, int indentLevel, int openMask) private void ControlButtonsRight(TreeNode_Editor node, WidgetRow widgetRow) { - if (node.HasNewButton && widgetRow.ButtonIcon(TexButton.NewItem, null)) + if (node.HasNewButton && widgetRow.ButtonIcon(TexButton.NewItem, (string)null)) { - Action addAction = delegate(object o) + Action addAction = (Action)delegate(object o) { node.owningField.SetValue(node.ParentObj, o); ((TreeNode_Editor)node.parentNode).RebuildChildNodes(); }; this.MakeCreateNewObjectMenu(node, node.owningField, node.owningField.FieldType, addAction); } - if (node.nodeType == EditTreeNodeType.ListRoot && widgetRow.ButtonIcon(TexButton.Add, null)) + if (node.nodeType == EditTreeNodeType.ListRoot && widgetRow.ButtonIcon(TexButton.Add, (string)null)) { Type baseType = node.obj.GetType().GetGenericArguments()[0]; - Action addAction2 = delegate(object o) + Action addAction2 = (Action)delegate(object o) { - node.obj.GetType().GetMethod("Add").Invoke(node.obj, new object[] + node.obj.GetType().GetMethod("Add").Invoke(node.obj, new object[1] { o }); }; this.MakeCreateNewObjectMenu(node, node.owningField, baseType, addAction2); } - if (node.HasDeleteButton && widgetRow.ButtonIcon(TexButton.DeleteX, null)) + if (node.HasDeleteButton && widgetRow.ButtonIcon(TexButton.DeleteX, (string)null)) { node.Delete(); } @@ -131,30 +133,31 @@ protected void NodeLabelLeft(TreeNode_Editor node, int indentLevel) protected void MakeCreateNewObjectMenu(TreeNode_Editor owningNode, FieldInfo owningField, Type baseType, Action addAction) { - List list = baseType.InstantiableDescendantsAndSelf().ToList(); + List list = baseType.InstantiableDescendantsAndSelf().ToList(); List list2 = new List(); - foreach (Type current in list) + List.Enumerator enumerator = list.GetEnumerator(); + try { - Type creatingType = current; - Action action = delegate + while (enumerator.MoveNext()) { - owningNode.SetOpen(-1, true); - object obj; - if (creatingType == typeof(string)) - { - obj = string.Empty; - } - else - { - obj = Activator.CreateInstance(creatingType); - } - addAction(obj); - if (owningNode != null) + Type current = enumerator.Current; + Type creatingType = current; + Action action = (Action)delegate() { - owningNode.RebuildChildNodes(); - } - }; - list2.Add(new FloatMenuOption(current.ToString(), action, MenuOptionPriority.Default, null, null, 0f, null, null)); + owningNode.SetOpen(-1, true); + object obj = (creatingType != typeof(string)) ? Activator.CreateInstance(creatingType) : string.Empty; + addAction(obj); + if (owningNode != null) + { + owningNode.RebuildChildNodes(); + } + }; + list2.Add(new FloatMenuOption(current.ToString(), action, MenuOptionPriority.Default, null, null, 0f, null, null)); + } + } + finally + { + ((IDisposable)(object)enumerator).Dispose(); } Find.WindowStack.Add(new FloatMenu(list2)); } @@ -165,36 +168,36 @@ protected void ValueEditWidgetRight(TreeNode_Editor node, float leftX) { throw new ArgumentException(); } - Rect rect = new Rect(leftX, this.curY, base.ColumnWidth - leftX, this.lineHeight); + Rect rect = new Rect(leftX, base.curY, base.ColumnWidth - leftX, base.lineHeight); object obj = node.Value; Type objectType = node.ObjectType; if (objectType == typeof(string)) { - string text = (string)obj; - string text2 = text; - if (text2 == null) + string text; + string text2 = text = (string)obj; + if (text == null) { - text2 = string.Empty; + text = string.Empty; } - string b = text2; - text2 = Widgets.TextField(rect, text2); - if (text2 != b) + string b = text; + text = Widgets.TextField(rect, text); + if (text != b) { - text = text2; + text2 = text; } - obj = text; + obj = text2; } else if (objectType == typeof(bool)) { bool flag = (bool)obj; - Widgets.Checkbox(new Vector2(rect.x, rect.y), ref flag, this.lineHeight, false); + Widgets.Checkbox(new Vector2(rect.x, rect.y), ref flag, base.lineHeight, false); obj = flag; } else if (objectType == typeof(int)) { rect.width = 100f; string s = Widgets.TextField(rect, obj.ToString()); - int num; + int num = default(int); if (int.TryParse(s, out num)) { obj = num; @@ -205,18 +208,18 @@ protected void ValueEditWidgetRight(TreeNode_Editor node, float leftX) EditSliderRangeAttribute[] array = (EditSliderRangeAttribute[])node.owningField.GetCustomAttributes(typeof(EditSliderRangeAttribute), true); if (array.Length > 0) { - float num2 = (float)obj; - Rect rect2 = new Rect(this.LabelWidth + 60f + 4f, this.curY, base.EditAreaWidth - 60f - 8f, this.lineHeight); - num2 = Widgets.HorizontalSlider(rect2, num2, array[0].min, array[0].max, false, null, null, null, -1f); - obj = num2; + float value = (float)obj; + Rect rect2 = new Rect((float)(this.LabelWidth + 60.0 + 4.0), base.curY, (float)(base.EditAreaWidth - 60.0 - 8.0), base.lineHeight); + value = Widgets.HorizontalSlider(rect2, value, array[0].min, array[0].max, false, (string)null, (string)null, (string)null, -1f); + obj = value; } rect.width = 60f; string text3 = obj.ToString(); text3 = Widgets.TextField(rect, text3); - float num3; - if (float.TryParse(text3, out num3)) + float num2 = default(float); + if (float.TryParse(text3, out num2)) { - obj = num3; + obj = num2; } } else if (objectType.IsEnum) @@ -224,10 +227,10 @@ protected void ValueEditWidgetRight(TreeNode_Editor node, float leftX) if (Widgets.ButtonText(rect, obj.ToString(), true, false, true)) { List list = new List(); - foreach (object current in Enum.GetValues(objectType)) + foreach (object value2 in Enum.GetValues(objectType)) { - object localVal = current; - list.Add(new FloatMenuOption(current.ToString(), delegate + object localVal = value2; + list.Add(new FloatMenuOption(value2.ToString(), (Action)delegate() { node.Value = localVal; }, MenuOptionPriority.Default, null, null, 0f, null, null)); @@ -246,7 +249,7 @@ protected void ValueEditWidgetRight(TreeNode_Editor node, float leftX) sliderMax = array2[0].max; } FloatRange floatRange = (FloatRange)obj; - Widgets.FloatRangeWithTypeIn(rect, node.owningIndex, ref floatRange, sliderMin, sliderMax, ToStringStyle.FloatTwo, null); + Widgets.FloatRangeWithTypeIn(rect, node.owningIndex, ref floatRange, sliderMin, sliderMax, ToStringStyle.FloatTwo, (string)null); obj = floatRange; } else diff --git a/Assembly-CSharp/Verse/Listing_TreeThingFilter.cs b/Assembly-CSharp/Verse/Listing_TreeThingFilter.cs index 542b231c2..0735b65d5 100644 --- a/Assembly-CSharp/Verse/Listing_TreeThingFilter.cs +++ b/Assembly-CSharp/Verse/Listing_TreeThingFilter.cs @@ -25,11 +25,11 @@ public Listing_TreeThingFilter(ThingFilter filter, ThingFilter parentFilter, IEn this.parentFilter = parentFilter; if (forceHiddenDefs != null) { - this.forceHiddenDefs = forceHiddenDefs.ToList(); + this.forceHiddenDefs = forceHiddenDefs.ToList(); } if (forceHiddenFilters != null) { - this.tempForceHiddenSpecialFilters = forceHiddenFilters.ToList(); + this.tempForceHiddenSpecialFilters = forceHiddenFilters.ToList(); } this.suppressSmallVolumeTags = suppressSmallVolumeTags; } @@ -38,11 +38,11 @@ public void DoCategoryChildren(TreeNode_ThingCategory node, int indentLevel, int { if (isRoot) { - foreach (SpecialThingFilterDef current in node.catDef.ParentsSpecialThingFilterDefs) + foreach (SpecialThingFilterDef parentsSpecialThingFilterDef in node.catDef.ParentsSpecialThingFilterDefs) { - if (this.Visible(current)) + if (this.Visible(parentsSpecialThingFilterDef)) { - this.DoSpecialFilter(current, indentLevel); + this.DoSpecialFilter(parentsSpecialThingFilterDef, indentLevel); } } } @@ -54,39 +54,38 @@ public void DoCategoryChildren(TreeNode_ThingCategory node, int indentLevel, int this.DoSpecialFilter(childSpecialFilters[i], indentLevel); } } - foreach (TreeNode_ThingCategory current2 in node.ChildCategoryNodes) + foreach (TreeNode_ThingCategory childCategoryNode in node.ChildCategoryNodes) { - if (this.Visible(current2)) + if (this.Visible(childCategoryNode)) { - this.DoCategory(current2, indentLevel, openMask); + this.DoCategory(childCategoryNode, indentLevel, openMask); } } - foreach (ThingDef current3 in from n in node.catDef.childThingDefs + foreach (ThingDef item in from n in node.catDef.childThingDefs orderby n.label select n) { - if (this.Visible(current3)) + if (this.Visible(item)) { - this.DoThingDef(current3, indentLevel); + this.DoThingDef(item, indentLevel); } } } private void DoSpecialFilter(SpecialThingFilterDef sfDef, int nestLevel) { - if (!sfDef.configurable) + if (sfDef.configurable) { - return; - } - base.LabelLeft("*" + sfDef.LabelCap, sfDef.description, nestLevel); - bool flag = this.filter.Allows(sfDef); - bool flag2 = flag; - Widgets.Checkbox(new Vector2(this.LabelWidth, this.curY), ref flag, this.lineHeight, false); - if (flag != flag2) - { - this.filter.SetAllow(sfDef, flag); + base.LabelLeft("*" + sfDef.LabelCap, sfDef.description, nestLevel); + bool flag; + bool flag2 = flag = this.filter.Allows(sfDef); + Widgets.Checkbox(new Vector2(this.LabelWidth, base.curY), ref flag2, base.lineHeight, false); + if (flag2 != flag) + { + this.filter.SetAllow(sfDef, flag2); + } + base.EndLine(); } - base.EndLine(); } public void DoCategory(TreeNode_ThingCategory node, int indentLevel, int openMask) @@ -94,9 +93,9 @@ public void DoCategory(TreeNode_ThingCategory node, int indentLevel, int openMas base.OpenCloseWidget(node, indentLevel, openMask); base.LabelLeft(node.LabelCap, node.catDef.description, indentLevel); MultiCheckboxState multiCheckboxState = this.AllowanceStateOf(node); - if (Widgets.CheckboxMulti(new Vector2(this.LabelWidth, this.curY), multiCheckboxState, this.lineHeight)) + if (Widgets.CheckboxMulti(new Vector2(this.LabelWidth, base.curY), multiCheckboxState, base.lineHeight)) { - bool allow = multiCheckboxState == MultiCheckboxState.Off; + bool allow = (byte)((multiCheckboxState == MultiCheckboxState.Off) ? 1 : 0) != 0; this.filter.SetAllow(node.catDef, allow, this.forceHiddenDefs, this.hiddenSpecialFilters); } base.EndLine(); @@ -108,31 +107,37 @@ public void DoCategory(TreeNode_ThingCategory node, int indentLevel, int openMas private void DoThingDef(ThingDef tDef, int nestLevel) { - bool flag = (this.suppressSmallVolumeTags == null || !this.suppressSmallVolumeTags.Contains(tDef)) && tDef.IsStuff && tDef.smallVolume; + int num; + if ((this.suppressSmallVolumeTags == null || !this.suppressSmallVolumeTags.Contains(tDef)) && tDef.IsStuff) + { + num = (tDef.smallVolume ? 1 : 0); + goto IL_0030; + } + num = 0; + goto IL_0030; + IL_0030: + bool flag = (byte)num != 0; string text = tDef.description; if (flag) { - text = text + "\n\n" + "ThisIsSmallVolume".Translate(new object[] - { - 10.ToStringCached() - }); + text = text + "\n\n" + "ThisIsSmallVolume".Translate(10.ToStringCached()); } base.LabelLeft(tDef.LabelCap, text, nestLevel); if (flag) { - Rect rect = new Rect(this.LabelWidth - 30f, this.curY, 30f, 30f); + Rect rect = new Rect((float)(this.LabelWidth - 30.0), base.curY, 30f, 30f); Text.Font = GameFont.Tiny; GUI.color = Color.gray; Widgets.Label(rect, "x" + 10.ToStringCached()); Text.Font = GameFont.Small; GUI.color = Color.white; } - bool flag2 = this.filter.Allows(tDef); - bool flag3 = flag2; - Widgets.Checkbox(new Vector2(this.LabelWidth, this.curY), ref flag2, this.lineHeight, false); - if (flag2 != flag3) + bool flag2; + bool flag3 = flag2 = this.filter.Allows(tDef); + Widgets.Checkbox(new Vector2(this.LabelWidth, base.curY), ref flag3, base.lineHeight, false); + if (flag3 != flag2) { - this.filter.SetAllow(tDef, flag2); + this.filter.SetAllow(tDef, flag3); } base.EndLine(); } @@ -141,23 +146,23 @@ public MultiCheckboxState AllowanceStateOf(TreeNode_ThingCategory cat) { int num = 0; int num2 = 0; - foreach (ThingDef current in cat.catDef.DescendantThingDefs) + foreach (ThingDef descendantThingDef in cat.catDef.DescendantThingDefs) { - if (this.Visible(current)) + if (this.Visible(descendantThingDef)) { num++; - if (this.filter.Allows(current)) + if (this.filter.Allows(descendantThingDef)) { num2++; } } } - foreach (SpecialThingFilterDef current2 in cat.catDef.DescendantSpecialThingFilterDefs) + foreach (SpecialThingFilterDef descendantSpecialThingFilterDef in cat.catDef.DescendantSpecialThingFilterDefs) { - if (this.Visible(current2)) + if (this.Visible(descendantSpecialThingFilterDef)) { num++; - if (this.filter.Allows(current2)) + if (this.filter.Allows(descendantSpecialThingFilterDef)) { num2++; } @@ -238,12 +243,12 @@ private void CalculateHiddenSpecialFilters() where this.parentFilter.Allows(x) select x; } - foreach (SpecialThingFilterDef current in enumerable) + foreach (SpecialThingFilterDef item in enumerable) { bool flag = false; - foreach (ThingDef current2 in enumerable2) + foreach (ThingDef item2 in enumerable2) { - if (current.Worker.CanEverMatch(current2)) + if (item.Worker.CanEverMatch(item2)) { flag = true; break; @@ -251,7 +256,7 @@ where this.parentFilter.Allows(x) } if (!flag) { - this.hiddenSpecialFilters.Add(current); + this.hiddenSpecialFilters.Add(item); } } } diff --git a/Assembly-CSharp/Verse/LoadIDsWantedBank.cs b/Assembly-CSharp/Verse/LoadIDsWantedBank.cs index 658919fae..0fa2704aa 100644 --- a/Assembly-CSharp/Verse/LoadIDsWantedBank.cs +++ b/Assembly-CSharp/Verse/LoadIDsWantedBank.cs @@ -41,9 +41,9 @@ public IdListRecord(List targetLoadIDs, string pathRelToParent, IExposab } } - private List idsRead = new List(); + private List idsRead = new List(); - private List idListsRead = new List(); + private List idListsRead = new List(); public void ConfirmClear() { @@ -56,17 +56,30 @@ public void ConfirmClear() stringBuilder.AppendLine("Singles:"); for (int i = 0; i < this.idsRead.Count; i++) { - stringBuilder.AppendLine(string.Concat(new object[] + StringBuilder obj = stringBuilder; + object[] obj2 = new object[8] { " ", - this.idsRead[i].targetLoadID.ToStringSafe(), - " of type ", - this.idsRead[i].targetType, - ". pathRelToParent=", - this.idsRead[i].pathRelToParent, - ", parent=", - this.idsRead[i].parent.ToStringSafe() - })); + null, + null, + null, + null, + null, + null, + null + }; + IdRecord idRecord = this.idsRead[i]; + obj2[1] = idRecord.targetLoadID.ToStringSafe(); + obj2[2] = " of type "; + IdRecord idRecord2 = this.idsRead[i]; + obj2[3] = idRecord2.targetType; + obj2[4] = ". pathRelToParent="; + IdRecord idRecord3 = this.idsRead[i]; + obj2[5] = idRecord3.pathRelToParent; + obj2[6] = ", parent="; + IdRecord idRecord4 = this.idsRead[i]; + obj2[7] = idRecord4.parent.ToStringSafe(); + obj.AppendLine(string.Concat(obj2)); } } if (this.idListsRead.Count > 0) @@ -74,15 +87,35 @@ public void ConfirmClear() stringBuilder.AppendLine("Lists:"); for (int j = 0; j < this.idListsRead.Count; j++) { - stringBuilder.AppendLine(string.Concat(new object[] + StringBuilder obj3 = stringBuilder; + object[] obj4 = new object[6] { " List with ", - (this.idListsRead[j].targetLoadIDs == null) ? 0 : this.idListsRead[j].targetLoadIDs.Count, - " elements. pathRelToParent=", - this.idListsRead[j].pathRelToParent, - ", parent=", - this.idListsRead[j].parent.ToStringSafe() - })); + null, + null, + null, + null, + null + }; + IdListRecord idListRecord = this.idListsRead[j]; + int num; + if (idListRecord.targetLoadIDs != null) + { + IdListRecord idListRecord2 = this.idListsRead[j]; + num = idListRecord2.targetLoadIDs.Count; + } + else + { + num = 0; + } + obj4[1] = num; + obj4[2] = " elements. pathRelToParent="; + IdListRecord idListRecord3 = this.idListsRead[j]; + obj4[3] = idListRecord3.pathRelToParent; + obj4[4] = ", parent="; + IdListRecord idListRecord4 = this.idListsRead[j]; + obj4[5] = idListRecord4.parent.ToStringSafe(); + obj3.AppendLine(string.Concat(obj4)); } } Log.Warning(stringBuilder.ToString().TrimEndNewlines()); @@ -100,21 +133,18 @@ public void RegisterLoadIDReadFromXml(string targetLoadID, Type targetType, stri { for (int i = 0; i < this.idsRead.Count; i++) { - if (this.idsRead[i].parent == parent && this.idsRead[i].pathRelToParent == pathRelToParent) + IdRecord idRecord = this.idsRead[i]; + if (idRecord.parent == parent) { - Log.Error(string.Concat(new string[] + IdRecord idRecord2 = this.idsRead[i]; + if (idRecord2.pathRelToParent == pathRelToParent) { - "Tried to register the same load ID twice: ", - targetLoadID, - ", pathRelToParent=", - pathRelToParent, - ", parent=", - parent.ToStringSafe() - })); - return; + Log.Error("Tried to register the same load ID twice: " + targetLoadID + ", pathRelToParent=" + pathRelToParent + ", parent=" + parent.ToStringSafe()); + return; + } } } - this.idsRead.Add(new LoadIDsWantedBank.IdRecord(targetLoadID, targetType, pathRelToParent, parent)); + this.idsRead.Add(new IdRecord(targetLoadID, targetType, pathRelToParent, parent)); } public void RegisterLoadIDReadFromXml(string targetLoadID, Type targetType, string toAppendToPathRelToParent) @@ -131,13 +161,18 @@ public void RegisterLoadIDListReadFromXml(List targetLoadIDList, string { for (int i = 0; i < this.idListsRead.Count; i++) { - if (this.idListsRead[i].parent == parent && this.idListsRead[i].pathRelToParent == pathRelToParent) + IdListRecord idListRecord = this.idListsRead[i]; + if (idListRecord.parent == parent) { - Log.Error("Tried to register the same list of load IDs twice. pathRelToParent=" + pathRelToParent + ", parent=" + parent.ToStringSafe()); - return; + IdListRecord idListRecord2 = this.idListsRead[i]; + if (idListRecord2.pathRelToParent == pathRelToParent) + { + Log.Error("Tried to register the same list of load IDs twice. pathRelToParent=" + pathRelToParent + ", parent=" + parent.ToStringSafe()); + return; + } } } - this.idListsRead.Add(new LoadIDsWantedBank.IdListRecord(targetLoadIDList, pathRelToParent, parent)); + this.idListsRead.Add(new IdListRecord(targetLoadIDList, pathRelToParent, parent)); } public void RegisterLoadIDListReadFromXml(List targetLoadIDList, string toAppendToPathRelToParent) @@ -154,43 +189,64 @@ public string Take(string pathRelToParent, IExposable parent) { for (int i = 0; i < this.idsRead.Count; i++) { - if (this.idsRead[i].parent == parent && this.idsRead[i].pathRelToParent == pathRelToParent) + IdRecord idRecord = this.idsRead[i]; + if (idRecord.parent == parent) { - string targetLoadID = this.idsRead[i].targetLoadID; - if (typeof(T) != this.idsRead[i].targetType) + IdRecord idRecord2 = this.idsRead[i]; + if (idRecord2.pathRelToParent == pathRelToParent) { - Log.Error(string.Concat(new object[] + IdRecord idRecord3 = this.idsRead[i]; + string targetLoadID = idRecord3.targetLoadID; + Type typeFromHandle = typeof(T); + IdRecord idRecord4 = this.idsRead[i]; + if (typeFromHandle != idRecord4.targetType) { - "Trying to get load ID of object of type ", - typeof(T), - ", but it was registered as ", - this.idsRead[i].targetType, - ". pathRelToParent=", - pathRelToParent, - ", parent=", - parent.ToStringSafe() - })); + object[] obj = new object[8] + { + "Trying to get load ID of object of type ", + typeof(T), + ", but it was registered as ", + null, + null, + null, + null, + null + }; + IdRecord idRecord5 = this.idsRead[i]; + obj[3] = idRecord5.targetType; + obj[4] = ". pathRelToParent="; + obj[5] = pathRelToParent; + obj[6] = ", parent="; + obj[7] = parent.ToStringSafe(); + Log.Error(string.Concat(obj)); + } + this.idsRead.RemoveAt(i); + return targetLoadID; } - this.idsRead.RemoveAt(i); - return targetLoadID; } } Log.Error("Could not get load ID. We're asking for something which was never added during LoadingVars. pathRelToParent=" + pathRelToParent + ", parent=" + parent.ToStringSafe()); - return null; + return (string)null; } public List TakeList(string pathRelToParent, IExposable parent) { for (int i = 0; i < this.idListsRead.Count; i++) { - if (this.idListsRead[i].parent == parent && this.idListsRead[i].pathRelToParent == pathRelToParent) + IdListRecord idListRecord = this.idListsRead[i]; + if (idListRecord.parent == parent) { - List targetLoadIDs = this.idListsRead[i].targetLoadIDs; - this.idListsRead.RemoveAt(i); - return targetLoadIDs; + IdListRecord idListRecord2 = this.idListsRead[i]; + if (idListRecord2.pathRelToParent == pathRelToParent) + { + IdListRecord idListRecord3 = this.idListsRead[i]; + List targetLoadIDs = idListRecord3.targetLoadIDs; + this.idListsRead.RemoveAt(i); + return targetLoadIDs; + } } } - Log.Error("Could not get load IDs list. We're asking for something which was never added during LoadingVars. pathRelToParent=" + pathRelToParent + ", parent=" + parent.ToStringSafe()); + Log.Error("Could not get load IDs list. We're asking for something which was never added during LoadingVars. pathRelToParent=" + pathRelToParent + ", parent=" + parent.ToStringSafe()); return new List(); } } diff --git a/Assembly-CSharp/Verse/LoadSaveMode.cs b/Assembly-CSharp/Verse/LoadSaveMode.cs index da3d83ae5..9a5d9dadc 100644 --- a/Assembly-CSharp/Verse/LoadSaveMode.cs +++ b/Assembly-CSharp/Verse/LoadSaveMode.cs @@ -1,13 +1,11 @@ -using System; - namespace Verse { public enum LoadSaveMode : byte { - Inactive, - Saving, - LoadingVars, - ResolvingCrossRefs, - PostLoadInit + Inactive = 0, + Saving = 1, + LoadingVars = 2, + ResolvingCrossRefs = 3, + PostLoadInit = 4 } } diff --git a/Assembly-CSharp/Verse/LoadableXmlAsset.cs b/Assembly-CSharp/Verse/LoadableXmlAsset.cs index 2f3533f22..6ff190de7 100644 --- a/Assembly-CSharp/Verse/LoadableXmlAsset.cs +++ b/Assembly-CSharp/Verse/LoadableXmlAsset.cs @@ -22,13 +22,7 @@ public LoadableXmlAsset(string name, string fullFolderPath, string contents) } catch (Exception ex) { - Log.Warning(string.Concat(new object[] - { - "Exception reading ", - name, - " as XML: ", - ex - })); + Log.Warning("Exception reading " + name + " as XML: " + ex); this.xmlDoc = null; } } diff --git a/Assembly-CSharp/Verse/LoadedContentItem.cs b/Assembly-CSharp/Verse/LoadedContentItem.cs index 90029fae9..8a55cb997 100644 --- a/Assembly-CSharp/Verse/LoadedContentItem.cs +++ b/Assembly-CSharp/Verse/LoadedContentItem.cs @@ -1,5 +1,3 @@ -using System; - namespace Verse { public class LoadedContentItem where T : class diff --git a/Assembly-CSharp/Verse/LoadedLanguage.cs b/Assembly-CSharp/Verse/LoadedLanguage.cs index e8774f20e..0049220cc 100644 --- a/Assembly-CSharp/Verse/LoadedLanguage.cs +++ b/Assembly-CSharp/Verse/LoadedLanguage.cs @@ -28,11 +28,11 @@ public string FriendlyNameNative { get { - if (this.info == null || this.info.friendlyNameNative.NullOrEmpty()) + if (this.info != null && !this.info.friendlyNameNative.NullOrEmpty()) { - return this.folderName; + return this.info.friendlyNameNative; } - return this.info.friendlyNameNative; + return this.folderName; } } @@ -40,11 +40,11 @@ public string FriendlyNameEnglish { get { - if (this.info == null || this.info.friendlyNameEnglish.NullOrEmpty()) + if (this.info != null && !this.info.friendlyNameEnglish.NullOrEmpty()) { - return this.folderName; + return this.info.friendlyNameEnglish; } - return this.info.friendlyNameEnglish; + return this.folderName; } } @@ -52,11 +52,16 @@ public IEnumerable FolderPaths { get { - LoadedLanguage.<>c__Iterator1F1 <>c__Iterator1F = new LoadedLanguage.<>c__Iterator1F1(); - <>c__Iterator1F.<>f__this = this; - LoadedLanguage.<>c__Iterator1F1 expr_0E = <>c__Iterator1F; - expr_0E.$PC = -2; - return expr_0E; + foreach (ModContentPack runningMod in LoadedModManager.RunningMods) + { + string langDirPath = Path.Combine(runningMod.RootDir, "Languages"); + string myDirPath = Path.Combine(langDirPath, this.folderName); + DirectoryInfo myDir = new DirectoryInfo(myDirPath); + if (myDir.Exists) + { + yield return myDirPath; + } + } } } @@ -105,104 +110,96 @@ public void TryLoadMetadataFrom(string folderPath) public void LoadData() { - if (this.dataIsLoaded) - { - return; - } - this.dataIsLoaded = true; - DeepProfiler.Start("Loading language data: " + this.folderName); - foreach (string current in this.FolderPaths) + if (!this.dataIsLoaded) { - string localFolderPath = current; - LongEventHandler.ExecuteWhenFinished(delegate + this.dataIsLoaded = true; + DeepProfiler.Start("Loading language data: " + this.folderName); + foreach (string folderPath in this.FolderPaths) { - if (this.icon == BaseContent.BadTex) + string localFolderPath = folderPath; + LongEventHandler.ExecuteWhenFinished((Action)delegate { - FileInfo fileInfo = new FileInfo(Path.Combine(localFolderPath.ToString(), "LangIcon.png")); - if (fileInfo.Exists) + if ((UnityEngine.Object)this.icon == (UnityEngine.Object)BaseContent.BadTex) { - this.icon = ModContentLoader.LoadItem(fileInfo.FullName, null).contentItem; + FileInfo fileInfo = new FileInfo(Path.Combine(localFolderPath.ToString(), "LangIcon.png")); + if (fileInfo.Exists) + { + this.icon = ModContentLoader.LoadItem(fileInfo.FullName, (string)null).contentItem; + } } + }); + DirectoryInfo directoryInfo = new DirectoryInfo(Path.Combine(folderPath.ToString(), "CodeLinked")); + if (directoryInfo.Exists) + { + Log.Warning("Translations aren't called CodeLinked any more. Please rename to Keyed: " + directoryInfo); } - }); - DirectoryInfo directoryInfo = new DirectoryInfo(Path.Combine(current.ToString(), "CodeLinked")); - if (directoryInfo.Exists) - { - Log.Warning("Translations aren't called CodeLinked any more. Please rename to Keyed: " + directoryInfo); - } - else - { - directoryInfo = new DirectoryInfo(Path.Combine(current.ToString(), "Keyed")); - } - if (directoryInfo.Exists) - { - FileInfo[] files = directoryInfo.GetFiles("*.xml", SearchOption.AllDirectories); - for (int i = 0; i < files.Length; i++) + else { - FileInfo file = files[i]; - this.LoadFromFile_Keyed(file); + directoryInfo = new DirectoryInfo(Path.Combine(folderPath.ToString(), "Keyed")); } - } - DirectoryInfo directoryInfo2 = new DirectoryInfo(Path.Combine(current.ToString(), "DefLinked")); - if (directoryInfo2.Exists) - { - Log.Warning("Translations aren't called DefLinked any more. Please rename to DefInjected: " + directoryInfo2); - } - else - { - directoryInfo2 = new DirectoryInfo(Path.Combine(current.ToString(), "DefInjected")); - } - if (directoryInfo2.Exists) - { - DirectoryInfo[] directories = directoryInfo2.GetDirectories("*", SearchOption.TopDirectoryOnly); - for (int j = 0; j < directories.Length; j++) + if (directoryInfo.Exists) { - DirectoryInfo directoryInfo3 = directories[j]; - string name = directoryInfo3.Name; - Type typeInAnyAssembly = GenTypes.GetTypeInAnyAssembly(name); - if (typeInAnyAssembly == null && name.Length > 3) + FileInfo[] files = directoryInfo.GetFiles("*.xml", SearchOption.AllDirectories); + for (int i = 0; i < files.Length; i++) { - typeInAnyAssembly = GenTypes.GetTypeInAnyAssembly(name.Substring(0, name.Length - 1)); + FileInfo file = files[i]; + this.LoadFromFile_Keyed(file); } - if (typeInAnyAssembly == null) + } + DirectoryInfo directoryInfo2 = new DirectoryInfo(Path.Combine(folderPath.ToString(), "DefLinked")); + if (directoryInfo2.Exists) + { + Log.Warning("Translations aren't called DefLinked any more. Please rename to DefInjected: " + directoryInfo2); + } + else + { + directoryInfo2 = new DirectoryInfo(Path.Combine(folderPath.ToString(), "DefInjected")); + } + if (directoryInfo2.Exists) + { + DirectoryInfo[] directories = directoryInfo2.GetDirectories("*", SearchOption.TopDirectoryOnly); + for (int j = 0; j < directories.Length; j++) { - Log.Warning(string.Concat(new string[] + DirectoryInfo directoryInfo3 = directories[j]; + string name = directoryInfo3.Name; + Type typeInAnyAssembly = GenTypes.GetTypeInAnyAssembly(name); + if (typeInAnyAssembly == null && name.Length > 3) { - "Error loading language from ", - current, - ": dir ", - directoryInfo3.Name, - " doesn't correspond to any def type. Skipping..." - })); - } - else - { - FileInfo[] files2 = directoryInfo3.GetFiles("*.xml", SearchOption.AllDirectories); - for (int k = 0; k < files2.Length; k++) + typeInAnyAssembly = GenTypes.GetTypeInAnyAssembly(name.Substring(0, name.Length - 1)); + } + if (typeInAnyAssembly == null) + { + Log.Warning("Error loading language from " + folderPath + ": dir " + directoryInfo3.Name + " doesn't correspond to any def type. Skipping..."); + } + else { - FileInfo file2 = files2[k]; - this.LoadFromFile_DefInject(file2, typeInAnyAssembly); + FileInfo[] files2 = directoryInfo3.GetFiles("*.xml", SearchOption.AllDirectories); + for (int k = 0; k < files2.Length; k++) + { + FileInfo file2 = files2[k]; + this.LoadFromFile_DefInject(file2, typeInAnyAssembly); + } } } } - } - DirectoryInfo directoryInfo4 = new DirectoryInfo(Path.Combine(current.ToString(), "Strings")); - if (directoryInfo4.Exists) - { - DirectoryInfo[] directories2 = directoryInfo4.GetDirectories("*", SearchOption.TopDirectoryOnly); - for (int l = 0; l < directories2.Length; l++) + DirectoryInfo directoryInfo4 = new DirectoryInfo(Path.Combine(folderPath.ToString(), "Strings")); + if (directoryInfo4.Exists) { - DirectoryInfo directoryInfo5 = directories2[l]; - FileInfo[] files3 = directoryInfo5.GetFiles("*.txt", SearchOption.AllDirectories); - for (int m = 0; m < files3.Length; m++) + DirectoryInfo[] directories2 = directoryInfo4.GetDirectories("*", SearchOption.TopDirectoryOnly); + for (int l = 0; l < directories2.Length; l++) { - FileInfo file3 = files3[m]; - this.LoadFromFile_Strings(file3, directoryInfo4); + DirectoryInfo directoryInfo5 = directories2[l]; + FileInfo[] files3 = directoryInfo5.GetFiles("*.txt", SearchOption.AllDirectories); + for (int m = 0; m < files3.Length; m++) + { + FileInfo file3 = files3[m]; + this.LoadFromFile_Strings(file3, directoryInfo4); + } } } } + DeepProfiler.End(); } - DeepProfiler.End(); } private void LoadFromFile_Strings(FileInfo file, DirectoryInfo stringsTopDir) @@ -214,14 +211,9 @@ private void LoadFromFile_Strings(FileInfo file, DirectoryInfo stringsTopDir) } catch (Exception ex) { - Log.Warning(string.Concat(new object[] - { - "Exception loading from strings file ", - file, - ": ", - ex - })); + Log.Warning("Exception loading from strings file " + file + ": " + ex); return; + IL_003f:; } string text2 = file.FullName; if (stringsTopDir != null) @@ -231,16 +223,25 @@ private void LoadFromFile_Strings(FileInfo file, DirectoryInfo stringsTopDir) text2 = text2.Substring(0, text2.Length - Path.GetExtension(text2).Length); text2 = text2.Replace('\\', '/'); List list = new List(); - foreach (string current in GenText.LinesFromString(text)) + foreach (string item in GenText.LinesFromString(text)) { - list.Add(current); + list.Add(item); } - List list2; + List list2 = default(List); if (this.stringFiles.TryGetValue(text2, out list2)) { - foreach (string current2 in list) + List.Enumerator enumerator2 = list.GetEnumerator(); + try { - list2.Add(current2); + while (enumerator2.MoveNext()) + { + string current2 = enumerator2.Current; + list2.Add(current2); + } + } + finally + { + ((IDisposable)(object)enumerator2).Dispose(); } } else @@ -254,32 +255,35 @@ private void LoadFromFile_Keyed(FileInfo file) Dictionary dictionary = new Dictionary(); try { - foreach (KeyValuePair current in DirectXmlLoaderSimple.ValuesFromXmlFile(file)) + foreach (KeyValuePair item in DirectXmlLoaderSimple.ValuesFromXmlFile(file)) { - if (this.keyedReplacements.ContainsKey(current.Key) || dictionary.ContainsKey(current.Key)) + if (this.keyedReplacements.ContainsKey(item.Key) || dictionary.ContainsKey(item.Key)) { - Log.Warning("Duplicate code-linked translation key: " + current.Key + " in language " + this.folderName); + Log.Warning("Duplicate code-linked translation key: " + item.Key + " in language " + this.folderName); } else { - dictionary.Add(current.Key, current.Value); + dictionary.Add(item.Key, item.Value); } } } catch (Exception ex) { - Log.Warning(string.Concat(new object[] - { - "Exception loading from translation file ", - file, - ": ", - ex - })); + Log.Warning("Exception loading from translation file " + file + ": " + ex); dictionary.Clear(); } - foreach (KeyValuePair current2 in dictionary) + Dictionary.Enumerator enumerator2 = dictionary.GetEnumerator(); + try { - this.keyedReplacements.Add(current2.Key, current2.Value); + while (enumerator2.MoveNext()) + { + KeyValuePair current2 = enumerator2.Current; + this.keyedReplacements.Add(current2.Key, current2.Value); + } + } + finally + { + ((IDisposable)(object)enumerator2).Dispose(); } } @@ -287,7 +291,7 @@ public void LoadFromFile_DefInject(FileInfo file, Type defType) { DefInjectionPackage defInjectionPackage = (from di in this.defInjections where di.defType == defType - select di).FirstOrDefault(); + select di).FirstOrDefault(); if (defInjectionPackage == null) { defInjectionPackage = new DefInjectionPackage(defType); @@ -339,9 +343,18 @@ public void InjectIntoData() { this.LoadData(); } - foreach (DefInjectionPackage current in this.defInjections) + List.Enumerator enumerator = this.defInjections.GetEnumerator(); + try + { + while (enumerator.MoveNext()) + { + DefInjectionPackage current = enumerator.Current; + current.InjectIntoDefs(); + } + } + finally { - current.InjectIntoDefs(); + ((IDisposable)(object)enumerator).Dispose(); } BackstoryTranslationUtility.LoadAndInjectBackstoryData(this); } diff --git a/Assembly-CSharp/Verse/LoadedModManager.cs b/Assembly-CSharp/Verse/LoadedModManager.cs index 9385ff256..1708a178a 100644 --- a/Assembly-CSharp/Verse/LoadedModManager.cs +++ b/Assembly-CSharp/Verse/LoadedModManager.cs @@ -31,31 +31,32 @@ public static void LoadAllActiveMods() { XmlInheritance.Clear(); int num = 0; - foreach (ModMetaData current in ModsConfig.ActiveModsInLoadOrder.ToList()) + List.Enumerator enumerator = ModsConfig.ActiveModsInLoadOrder.ToList().GetEnumerator(); + try { - DeepProfiler.Start("Initializing " + current); - if (!current.RootDir.Exists) + while (enumerator.MoveNext()) { - ModsConfig.SetActive(current.Identifier, false); - Log.Warning(string.Concat(new object[] + ModMetaData current = enumerator.Current; + DeepProfiler.Start("Initializing " + current); + if (!current.RootDir.Exists) { - "Failed to find active mod ", - current.Name, - "(", - current.Identifier, - ") at ", - current.RootDir - })); - DeepProfiler.End(); - } - else - { - ModContentPack item = new ModContentPack(current.RootDir, num, current.Name); - num++; - LoadedModManager.runningMods.Add(item); - DeepProfiler.End(); + ModsConfig.SetActive(current.Identifier, false); + Log.Warning("Failed to find active mod " + current.Name + "(" + current.Identifier + ") at " + current.RootDir); + DeepProfiler.End(); + } + else + { + ModContentPack item = new ModContentPack(current.RootDir, num, current.Name); + num++; + LoadedModManager.runningMods.Add(item); + DeepProfiler.End(); + } } } + finally + { + ((IDisposable)(object)enumerator).Dispose(); + } for (int i = 0; i < LoadedModManager.runningMods.Count; i++) { ModContentPack modContentPack = LoadedModManager.runningMods[i]; @@ -67,28 +68,39 @@ public static void LoadAllActiveMods() { ModContentPack modContentPack2 = LoadedModManager.runningMods[j]; DeepProfiler.Start("Loading " + modContentPack2); - modContentPack2.LoadDefs(LoadedModManager.runningMods.SelectMany((ModContentPack rm) => rm.Patches)); + modContentPack2.LoadDefs(LoadedModManager.runningMods.SelectMany((Func>)((ModContentPack rm) => rm.Patches))); DeepProfiler.End(); } - foreach (ModContentPack current2 in LoadedModManager.runningMods) + List.Enumerator enumerator2 = LoadedModManager.runningMods.GetEnumerator(); + try { - foreach (PatchOperation current3 in current2.Patches) + while (enumerator2.MoveNext()) { - current3.Complete(current2.Name); + ModContentPack current2 = enumerator2.Current; + foreach (PatchOperation patch in current2.Patches) + { + patch.Complete(current2.Name); + } + current2.ClearPatchesCache(); } - current2.ClearPatchesCache(); } - foreach (Type type in typeof(Mod).InstantiableDescendantsAndSelf()) + finally { - if (!LoadedModManager.runningModClasses.ContainsKey(type)) + ((IDisposable)(object)enumerator2).Dispose(); + } + using (IEnumerator enumerator4 = typeof(Mod).InstantiableDescendantsAndSelf().GetEnumerator()) + { + Type type; + while (enumerator4.MoveNext()) { - ModContentPack modContentPack3 = (from modpack in LoadedModManager.runningMods - where modpack.assemblies.loadedAssemblies.Contains(type.Assembly) - select modpack).FirstOrDefault(); - LoadedModManager.runningModClasses[type] = (Mod)Activator.CreateInstance(type, new object[] + type = enumerator4.Current; + if (!LoadedModManager.runningModClasses.ContainsKey(type)) { - modContentPack3 - }); + ModContentPack modContentPack3 = (from modpack in LoadedModManager.runningMods + where modpack.assemblies.loadedAssemblies.Contains(type.Assembly) + select modpack).FirstOrDefault(); + LoadedModManager.runningModClasses[type] = (Mod)Activator.CreateInstance(type, modContentPack3); + } } } XmlInheritance.Clear(); @@ -96,16 +108,25 @@ where modpack.assemblies.loadedAssemblies.Contains(type.Assembly) public static void ClearDestroy() { - foreach (ModContentPack current in LoadedModManager.runningMods) + List.Enumerator enumerator = LoadedModManager.runningMods.GetEnumerator(); + try + { + while (enumerator.MoveNext()) + { + ModContentPack current = enumerator.Current; + current.ClearDestroy(); + } + } + finally { - current.ClearDestroy(); + ((IDisposable)(object)enumerator).Dispose(); } LoadedModManager.runningMods.Clear(); } public static T GetMod() where T : Mod { - return LoadedModManager.GetMod(typeof(T)) as T; + return (T)(LoadedModManager.GetMod(typeof(T)) as T); } public static Mod GetMod(Type type) @@ -116,7 +137,7 @@ public static Mod GetMod(Type type) } return (from kvp in LoadedModManager.runningModClasses where type.IsAssignableFrom(kvp.Key) - select kvp).FirstOrDefault>().Value; + select kvp).FirstOrDefault().Value; } private static string GetSettingsFilename(string modIdentifier, string modHandleName) @@ -127,32 +148,32 @@ private static string GetSettingsFilename(string modIdentifier, string modHandle public static T ReadModSettings(string modIdentifier, string modHandleName) where T : ModSettings, new() { string settingsFilename = LoadedModManager.GetSettingsFilename(modIdentifier, modHandleName); - T t = (T)((object)null); + T val = (T)null; try { if (File.Exists(settingsFilename)) { Scribe.loader.InitLoading(settingsFilename); - Scribe_Deep.Look(ref t, "ModSettings", new object[0]); + Scribe_Deep.Look(ref val, "ModSettings", new object[0]); Scribe.loader.FinalizeLoading(); } } catch (Exception ex) { Log.Warning(string.Format("Caught exception while loading mod settings data for {0}. Generating fresh settings. The exception was: {1}", modIdentifier, ex.ToString())); - t = (T)((object)null); + val = (T)null; } - if (t == null) + if (val == null) { - t = Activator.CreateInstance(); + val = new T(); } - return t; + return val; } public static void WriteModSettings(string modIdentifier, string modHandleName, ModSettings settings) { Scribe.saver.InitSaving(LoadedModManager.GetSettingsFilename(modIdentifier, modHandleName), "SettingsBlock"); - Scribe_Deep.Look(ref settings, "ModSettings", new object[0]); + Scribe_Deep.Look(ref settings, "ModSettings"); Scribe.saver.FinalizeSaving(); } } diff --git a/Assembly-CSharp/Verse/LoadedObjectDirectory.cs b/Assembly-CSharp/Verse/LoadedObjectDirectory.cs index f25127fe0..4849c45ae 100644 --- a/Assembly-CSharp/Verse/LoadedObjectDirectory.cs +++ b/Assembly-CSharp/Verse/LoadedObjectDirectory.cs @@ -32,23 +32,10 @@ public void RegisterLoaded(ILoadReferenceable reffable) catch (Exception) { } - ILoadReferenceable loadReferenceable; + ILoadReferenceable loadReferenceable = default(ILoadReferenceable); if (this.allObjectsByLoadID.TryGetValue(reffable.GetUniqueLoadID(), out loadReferenceable)) { - Log.Error(string.Concat(new object[] - { - "Cannot register ", - reffable.GetType(), - " ", - text2, - ", (id=", - text, - " in loaded object directory. Id already used by ", - loadReferenceable.GetType(), - " ", - loadReferenceable.ToString(), - "." - })); + Log.Error("Cannot register " + reffable.GetType() + " " + text2 + ", (id=" + text + " in loaded object directory. Id already used by " + loadReferenceable.GetType() + " " + loadReferenceable.ToString() + "."); return; } } @@ -56,7 +43,7 @@ public void RegisterLoaded(ILoadReferenceable reffable) { this.allObjectsByLoadID.Add(reffable.GetUniqueLoadID(), reffable); } - catch (Exception ex) + catch (Exception ex5) { string text3 = "[excepted]"; try @@ -74,66 +61,36 @@ public void RegisterLoaded(ILoadReferenceable reffable) catch (Exception) { } - Log.Error(string.Concat(new object[] - { - "Exception registering ", - reffable.GetType(), - " ", - text4, - " in loaded object directory with unique load ID ", - text3, - ": ", - ex - })); + Log.Error("Exception registering " + reffable.GetType() + " " + text4 + " in loaded object directory with unique load ID " + text3 + ": " + ex5); } } public T ObjectWithLoadID(string loadID) { - if (loadID.NullOrEmpty() || loadID == "null") + if (!loadID.NullOrEmpty() && !(loadID == "null")) { - return default(T); - } - ILoadReferenceable loadReferenceable; - if (this.allObjectsByLoadID.TryGetValue(loadID, out loadReferenceable)) - { - if (loadReferenceable == null) - { - return default(T); - } - try - { - T result = (T)((object)loadReferenceable); - return result; - } - catch (Exception ex) + ILoadReferenceable loadReferenceable = default(ILoadReferenceable); + if (this.allObjectsByLoadID.TryGetValue(loadID, out loadReferenceable)) { - Log.Error(string.Concat(new object[] + if (loadReferenceable == null) + { + return default(T); + } + try { - "Exception getting object with load id ", - loadID, - " of type ", - typeof(T), - ". What we loaded was ", - loadReferenceable.ToStringSafe(), - ". Exception:\n", - ex - })); - T result = default(T); - return result; + return (T)loadReferenceable; + IL_0055:; + } + catch (Exception ex) + { + Log.Error("Exception getting object with load id " + loadID + " of type " + typeof(T) + ". What we loaded was " + loadReferenceable.ToStringSafe() + ". Exception:\n" + ex); + return default(T); + IL_00ba:; + } } + Log.Warning("Could not resolve reference to object with loadID " + loadID + " of type " + typeof(T) + ". Was it compressed away, destroyed, had no ID number, or not saved/loaded right? curParent=" + Scribe.loader.curParent.ToStringSafe() + " curPathRelToParent=" + Scribe.loader.curPathRelToParent); + return default(T); } - Log.Warning(string.Concat(new object[] - { - "Could not resolve reference to object with loadID ", - loadID, - " of type ", - typeof(T), - ". Was it compressed away, destroyed, had no ID number, or not saved/loaded right? curParent=", - Scribe.loader.curParent.ToStringSafe(), - " curPathRelToParent=", - Scribe.loader.curPathRelToParent - })); return default(T); } } diff --git a/Assembly-CSharp/Verse/LocalTargetInfo.cs b/Assembly-CSharp/Verse/LocalTargetInfo.cs index 1ebc58493..e803ee6b6 100644 --- a/Assembly-CSharp/Verse/LocalTargetInfo.cs +++ b/Assembly-CSharp/Verse/LocalTargetInfo.cs @@ -114,7 +114,11 @@ public GlobalTargetInfo ToGlobalTargetInfo(Map map) public override bool Equals(object obj) { - return obj is LocalTargetInfo && this.Equals((LocalTargetInfo)obj); + if (!(obj is LocalTargetInfo)) + { + return false; + } + return this.Equals((LocalTargetInfo)obj); } public bool Equals(LocalTargetInfo other) @@ -174,11 +178,15 @@ public static explicit operator Thing(LocalTargetInfo targ) public static bool operator ==(LocalTargetInfo a, LocalTargetInfo b) { - if (a.Thing != null || b.Thing != null) + if (a.Thing == null && b.Thing == null) { - return a.Thing == b.Thing; + if (!a.cellInt.IsValid && !b.cellInt.IsValid) + { + return true; + } + return a.cellInt == b.cellInt; } - return (!a.cellInt.IsValid && !b.cellInt.IsValid) || a.cellInt == b.cellInt; + return a.Thing == b.Thing; } public static bool operator !=(LocalTargetInfo a, LocalTargetInfo b) diff --git a/Assembly-CSharp/Verse/Log.cs b/Assembly-CSharp/Verse/Log.cs index 0ef8c4c85..5ef35a62b 100644 --- a/Assembly-CSharp/Verse/Log.cs +++ b/Assembly-CSharp/Verse/Log.cs @@ -38,29 +38,26 @@ public static void Error(string text) } Debug.LogError(text); Log.messageQueue.Enqueue(new LogMessage(LogMessageType.Error, text, StackTraceUtility.ExtractStackTrace())); - if (!PlayDataLoader.Loaded || Prefs.DevMode) - { - Log.TryOpenLogWindow(); - } + if (PlayDataLoader.Loaded && !Prefs.DevMode) + return; + Log.TryOpenLogWindow(); } public static void ErrorOnce(string text, int key) { - if (Log.usedKeys.Contains(key)) + if (!Log.usedKeys.Contains(key)) { - return; + Log.usedKeys.Add(key); + Log.Error(text); } - Log.usedKeys.Add(key); - Log.Error(text); } public static void Notify_Exception(Exception e) { Log.messageQueue.Enqueue(new LogMessage(LogMessageType.Error, e.Message, e.StackTrace)); - if (!PlayDataLoader.Loaded || Prefs.DevMode) - { - Log.TryOpenLogWindow(); - } + if (PlayDataLoader.Loaded && !Prefs.DevMode) + return; + Log.TryOpenLogWindow(); } internal static void Clear() @@ -71,10 +68,9 @@ internal static void Clear() public static void TryOpenLogWindow() { - if (StaticConstructorOnStartupUtility.coreStaticAssetsLoaded || UnityData.IsInMainThread) - { - EditWindow_Log.TryAutoOpen(); - } + if (!StaticConstructorOnStartupUtility.coreStaticAssetsLoaded && !UnityData.IsInMainThread) + return; + EditWindow_Log.TryAutoOpen(); } } } diff --git a/Assembly-CSharp/Verse/LogMessage.cs b/Assembly-CSharp/Verse/LogMessage.cs index 53b51ac65..90d8fdff2 100644 --- a/Assembly-CSharp/Verse/LogMessage.cs +++ b/Assembly-CSharp/Verse/LogMessage.cs @@ -1,4 +1,3 @@ -using System; using UnityEngine; namespace Verse @@ -20,14 +19,22 @@ public Color Color switch (this.type) { case LogMessageType.Message: + { return Color.white; + } case LogMessageType.Warning: + { return Color.yellow; + } case LogMessageType.Error: + { return Color.red; + } default: + { return Color.white; } + } } } @@ -47,7 +54,7 @@ public LogMessage(string text) { this.text = text; this.type = LogMessageType.Message; - this.stackTrace = null; + this.stackTrace = (string)null; } public LogMessage(LogMessageType type, string text, string stackTrace) diff --git a/Assembly-CSharp/Verse/LogMessageQueue.cs b/Assembly-CSharp/Verse/LogMessageQueue.cs index d3a60a818..099bdfdd7 100644 --- a/Assembly-CSharp/Verse/LogMessageQueue.cs +++ b/Assembly-CSharp/Verse/LogMessageQueue.cs @@ -1,4 +1,3 @@ -using System; using System.Collections.Generic; namespace Verse @@ -24,14 +23,16 @@ public void Enqueue(LogMessage msg) if (this.lastMessage != null && msg.CanCombineWith(this.lastMessage)) { this.lastMessage.repeats++; - return; } - this.lastMessage = msg; - this.messages.Enqueue(msg); - if (this.messages.Count > this.maxMessages) + else { - LogMessage oldMessage = this.messages.Dequeue(); - EditWindow_Log.Notify_MessageDequeued(oldMessage); + this.lastMessage = msg; + this.messages.Enqueue(msg); + if (this.messages.Count > this.maxMessages) + { + LogMessage oldMessage = this.messages.Dequeue(); + EditWindow_Log.Notify_MessageDequeued(oldMessage); + } } } diff --git a/Assembly-CSharp/Verse/LogMessageType.cs b/Assembly-CSharp/Verse/LogMessageType.cs index 401004885..54c02e01a 100644 --- a/Assembly-CSharp/Verse/LogMessageType.cs +++ b/Assembly-CSharp/Verse/LogMessageType.cs @@ -1,11 +1,9 @@ -using System; - namespace Verse { public enum LogMessageType : byte { - Message, - Warning, - Error + Message = 0, + Warning = 1, + Error = 2 } } diff --git a/Assembly-CSharp/Verse/LogSimple.cs b/Assembly-CSharp/Verse/LogSimple.cs index e629c362c..8c5fbb739 100644 --- a/Assembly-CSharp/Verse/LogSimple.cs +++ b/Assembly-CSharp/Verse/LogSimple.cs @@ -34,42 +34,49 @@ public static void EndTab() public static void FlushToFileAndOpen() { - if (LogSimple.messages.Count == 0) + if (LogSimple.messages.Count != 0) { - return; + string value = LogSimple.CompiledLog(); + string path = GenFilePaths.SaveDataFolderPath + Path.DirectorySeparatorChar + "LogSimple.txt"; + using (StreamWriter streamWriter = new StreamWriter(path, false)) + { + streamWriter.Write(value); + } + LongEventHandler.ExecuteWhenFinished((Action)delegate + { + Application.OpenURL(path); + }); + LogSimple.messages.Clear(); } - string value = LogSimple.CompiledLog(); - string path = GenFilePaths.SaveDataFolderPath + Path.DirectorySeparatorChar + "LogSimple.txt"; - using (StreamWriter streamWriter = new StreamWriter(path, false)) - { - streamWriter.Write(value); - } - LongEventHandler.ExecuteWhenFinished(delegate - { - Application.OpenURL(path); - }); - LogSimple.messages.Clear(); } public static void FlushToStandardLog() { - if (LogSimple.messages.Count == 0) + if (LogSimple.messages.Count != 0) { - return; + string text = LogSimple.CompiledLog(); + Log.Message(text); + LogSimple.messages.Clear(); } - string text = LogSimple.CompiledLog(); - Log.Message(text); - LogSimple.messages.Clear(); } private static string CompiledLog() { StringBuilder stringBuilder = new StringBuilder(); - foreach (string current in LogSimple.messages) + List.Enumerator enumerator = LogSimple.messages.GetEnumerator(); + try + { + while (enumerator.MoveNext()) + { + string current = enumerator.Current; + stringBuilder.AppendLine(current); + } + } + finally { - stringBuilder.AppendLine(current); + ((IDisposable)(object)enumerator).Dispose(); } - return stringBuilder.ToString().TrimEnd(new char[0]); + return stringBuilder.ToString().TrimEnd(); } } } diff --git a/Assembly-CSharp/Verse/LongEventHandler.cs b/Assembly-CSharp/Verse/LongEventHandler.cs index 5fdda4226..8d85dfa99 100644 --- a/Assembly-CSharp/Verse/LongEventHandler.cs +++ b/Assembly-CSharp/Verse/LongEventHandler.cs @@ -54,9 +54,9 @@ public bool UseStandardWindow } } - private static Queue eventQueue = new Queue(); + private static Queue eventQueue = new Queue(); - private static LongEventHandler.QueuedLongEvent currentEvent = null; + private static QueuedLongEvent currentEvent = null; private static Thread eventThread = null; @@ -82,9 +82,9 @@ public static bool ShouldWaitForEvent { return true; } - if (LongEventHandler.currentEvent == null && LongEventHandler.eventQueue.Any()) + if (LongEventHandler.currentEvent == null && LongEventHandler.eventQueue.Any()) { - LongEventHandler.QueuedLongEvent queuedLongEvent = LongEventHandler.eventQueue.Peek(); + QueuedLongEvent queuedLongEvent = LongEventHandler.eventQueue.Peek(); if (queuedLongEvent.doAsynchronously) { return true; @@ -94,7 +94,11 @@ public static bool ShouldWaitForEvent return true; } } - return Find.UIRoot == null || Find.WindowStack == null; + if (Find.UIRoot != null && Find.WindowStack != null) + { + return false; + } + return true; } } @@ -116,7 +120,7 @@ public static bool ForcePause public static void QueueLongEvent(Action action, string textKey, bool doAsynchronously, Action exceptionHandler) { - LongEventHandler.QueuedLongEvent queuedLongEvent = new LongEventHandler.QueuedLongEvent(); + QueuedLongEvent queuedLongEvent = new QueuedLongEvent(); queuedLongEvent.eventAction = action; queuedLongEvent.eventTextKey = textKey; queuedLongEvent.doAsynchronously = doAsynchronously; @@ -126,7 +130,7 @@ public static void QueueLongEvent(Action action, string textKey, bool doAsynchro public static void QueueLongEvent(IEnumerable action, string textKey, Action exceptionHandler = null) { - LongEventHandler.QueuedLongEvent queuedLongEvent = new LongEventHandler.QueuedLongEvent(); + QueuedLongEvent queuedLongEvent = new QueuedLongEvent(); queuedLongEvent.eventActionEnumerator = action.GetEnumerator(); queuedLongEvent.eventTextKey = textKey; queuedLongEvent.doAsynchronously = false; @@ -136,7 +140,7 @@ public static void QueueLongEvent(IEnumerable action, string textKey, Action exceptionHandler) { - LongEventHandler.QueuedLongEvent queuedLongEvent = new LongEventHandler.QueuedLongEvent(); + QueuedLongEvent queuedLongEvent = new QueuedLongEvent(); queuedLongEvent.eventAction = preLoadLevelAction; queuedLongEvent.levelToLoad = levelToLoad; queuedLongEvent.eventTextKey = textKey; @@ -152,36 +156,49 @@ public static void ClearQueuedEvents() public static void LongEventsOnGUI() { - if (LongEventHandler.currentEvent == null) - { - return; - } - float num = LongEventHandler.GUIRectSize.x; - object currentEventTextLock = LongEventHandler.CurrentEventTextLock; - lock (currentEventTextLock) - { - Text.Font = GameFont.Small; - num = Mathf.Max(num, Text.CalcSize(LongEventHandler.currentEvent.eventText + "...").x + 40f); - } - Rect rect = new Rect(((float)UI.screenWidth - num) / 2f, ((float)UI.screenHeight - LongEventHandler.GUIRectSize.y) / 2f, num, LongEventHandler.GUIRectSize.y); - rect = rect.Rounded(); - if (!LongEventHandler.currentEvent.UseStandardWindow || Find.UIRoot == null || Find.WindowStack == null) + if (LongEventHandler.currentEvent != null) { - if (UIMenuBackgroundManager.background == null) + Vector2 gUIRectSize = LongEventHandler.GUIRectSize; + float num = gUIRectSize.x; + object currentEventTextLock = LongEventHandler.CurrentEventTextLock; + Monitor.Enter(currentEventTextLock); + try { - UIMenuBackgroundManager.background = new UI_BackgroundMain(); + Text.Font = GameFont.Small; + float a = num; + Vector2 vector = Text.CalcSize(LongEventHandler.currentEvent.eventText + "..."); + num = Mathf.Max(a, (float)(vector.x + 40.0)); } - UIMenuBackgroundManager.background.BackgroundOnGUI(); - Widgets.DrawShadowAround(rect); - Widgets.DrawWindowBackground(rect); - LongEventHandler.DrawLongEventWindowContents(rect); - } - else - { - Find.WindowStack.ImmediateWindow(62893994, rect, WindowLayer.Super, delegate + finally + { + Monitor.Exit(currentEventTextLock); + } + double x = ((float)UI.screenWidth - num) / 2.0; + float num2 = (float)UI.screenHeight; + Vector2 gUIRectSize2 = LongEventHandler.GUIRectSize; + double y = (num2 - gUIRectSize2.y) / 2.0; + float width = num; + Vector2 gUIRectSize3 = LongEventHandler.GUIRectSize; + Rect rect = new Rect((float)x, (float)y, width, gUIRectSize3.y); + rect = rect.Rounded(); + if (!LongEventHandler.currentEvent.UseStandardWindow || Find.UIRoot == null || Find.WindowStack == null) { - LongEventHandler.DrawLongEventWindowContents(rect.AtZero()); - }, true, false, 1f); + if (UIMenuBackgroundManager.background == null) + { + UIMenuBackgroundManager.background = new UI_BackgroundMain(); + } + UIMenuBackgroundManager.background.BackgroundOnGUI(); + Widgets.DrawShadowAround(rect); + Widgets.DrawWindowBackground(rect); + LongEventHandler.DrawLongEventWindowContents(rect); + } + else + { + Find.WindowStack.ImmediateWindow(62893994, rect, WindowLayer.Super, (Action)delegate + { + LongEventHandler.DrawLongEventWindowContents(rect.AtZero()); + }, true, false, 1f); + } } } @@ -220,7 +237,9 @@ public static void LongEventsUpdate(out bool sceneChanged) public static void ExecuteWhenFinished(Action action) { LongEventHandler.toExecuteWhenFinished.Add(action); - if ((LongEventHandler.currentEvent == null || LongEventHandler.currentEvent.ShouldWaitUntilDisplayed) && !LongEventHandler.executingToExecuteWhenFinished) + if (LongEventHandler.currentEvent != null && !LongEventHandler.currentEvent.ShouldWaitUntilDisplayed) + return; + if (!LongEventHandler.executingToExecuteWhenFinished) { LongEventHandler.ExecuteToExecuteWhenFinished(); } @@ -229,26 +248,29 @@ public static void ExecuteWhenFinished(Action action) public static void SetCurrentEventText(string newText) { object currentEventTextLock = LongEventHandler.CurrentEventTextLock; - lock (currentEventTextLock) + Monitor.Enter(currentEventTextLock); + try { if (LongEventHandler.currentEvent != null) { LongEventHandler.currentEvent.eventText = newText; } } + finally + { + Monitor.Exit(currentEventTextLock); + } } private static void UpdateCurrentEnumeratorEvent() { try { - float num = Time.realtimeSinceStartup + 0.1f; + float num = (float)(Time.realtimeSinceStartup + 0.10000000149011612); while (LongEventHandler.currentEvent.eventActionEnumerator.MoveNext()) { if (num <= Time.realtimeSinceStartup) - { return; - } } IDisposable disposable = LongEventHandler.currentEvent.eventActionEnumerator as IDisposable; if (disposable != null) @@ -270,7 +292,7 @@ private static void UpdateCurrentEnumeratorEvent() { disposable2.Dispose(); } - if (LongEventHandler.currentEvent.exceptionHandler != null) + if ((object)LongEventHandler.currentEvent.exceptionHandler != null) { LongEventHandler.currentEvent.exceptionHandler(ex); } @@ -285,7 +307,7 @@ private static void UpdateCurrentAsynchronousEvent() { if (LongEventHandler.eventThread == null) { - LongEventHandler.eventThread = new Thread(delegate + LongEventHandler.eventThread = new Thread((ThreadStart)delegate { LongEventHandler.RunEventFromAnotherThread(LongEventHandler.currentEvent.eventAction); }); @@ -322,36 +344,35 @@ private static void UpdateCurrentAsynchronousEvent() private static void UpdateCurrentSynchronousEvent(out bool sceneChanged) { sceneChanged = false; - if (LongEventHandler.currentEvent.ShouldWaitUntilDisplayed) - { - return; - } - try + if (!LongEventHandler.currentEvent.ShouldWaitUntilDisplayed) { - if (LongEventHandler.currentEvent.eventAction != null) - { - LongEventHandler.currentEvent.eventAction(); - } - if (!LongEventHandler.currentEvent.levelToLoad.NullOrEmpty()) + try { - SceneManager.LoadScene(LongEventHandler.currentEvent.levelToLoad); - sceneChanged = true; + if ((object)LongEventHandler.currentEvent.eventAction != null) + { + LongEventHandler.currentEvent.eventAction(); + } + if (!LongEventHandler.currentEvent.levelToLoad.NullOrEmpty()) + { + SceneManager.LoadScene(LongEventHandler.currentEvent.levelToLoad); + sceneChanged = true; + } + LongEventHandler.currentEvent = null; + LongEventHandler.eventThread = null; + LongEventHandler.levelLoadOp = null; + LongEventHandler.ExecuteToExecuteWhenFinished(); } - LongEventHandler.currentEvent = null; - LongEventHandler.eventThread = null; - LongEventHandler.levelLoadOp = null; - LongEventHandler.ExecuteToExecuteWhenFinished(); - } - catch (Exception ex) - { - Log.Error("Exception from long event: " + ex); - if (LongEventHandler.currentEvent != null && LongEventHandler.currentEvent.exceptionHandler != null) + catch (Exception ex) { - LongEventHandler.currentEvent.exceptionHandler(ex); + Log.Error("Exception from long event: " + ex); + if (LongEventHandler.currentEvent != null && (object)LongEventHandler.currentEvent.exceptionHandler != null) + { + LongEventHandler.currentEvent.exceptionHandler(ex); + } + LongEventHandler.currentEvent = null; + LongEventHandler.eventThread = null; + LongEventHandler.levelLoadOp = null; } - LongEventHandler.currentEvent = null; - LongEventHandler.eventThread = null; - LongEventHandler.levelLoadOp = null; } } @@ -359,7 +380,7 @@ private static void RunEventFromAnotherThread(Action action) { try { - if (action != null) + if ((object)action != null) { action(); } @@ -369,7 +390,7 @@ private static void RunEventFromAnotherThread(Action action) Log.Error("Exception from asynchronous event: " + ex); try { - if (LongEventHandler.currentEvent != null && LongEventHandler.currentEvent.exceptionHandler != null) + if (LongEventHandler.currentEvent != null && (object)LongEventHandler.currentEvent.exceptionHandler != null) { LongEventHandler.currentEvent.exceptionHandler(ex); } @@ -386,61 +407,70 @@ private static void ExecuteToExecuteWhenFinished() if (LongEventHandler.executingToExecuteWhenFinished) { Log.Warning("Already executing."); - return; } - LongEventHandler.executingToExecuteWhenFinished = true; - for (int i = 0; i < LongEventHandler.toExecuteWhenFinished.Count; i++) + else { - try - { - LongEventHandler.toExecuteWhenFinished[i](); - } - catch (Exception arg) + LongEventHandler.executingToExecuteWhenFinished = true; + for (int i = 0; i < LongEventHandler.toExecuteWhenFinished.Count; i++) { - Log.Error("Could not execute post-long-event action. Exception: " + arg); + try + { + LongEventHandler.toExecuteWhenFinished[i](); + } + catch (Exception arg) + { + Log.Error("Could not execute post-long-event action. Exception: " + arg); + } } + LongEventHandler.toExecuteWhenFinished.Clear(); + LongEventHandler.executingToExecuteWhenFinished = false; } - LongEventHandler.toExecuteWhenFinished.Clear(); - LongEventHandler.executingToExecuteWhenFinished = false; } private static void DrawLongEventWindowContents(Rect rect) { - if (LongEventHandler.currentEvent == null) - { - return; - } - if (Event.current.type == EventType.Repaint) - { - LongEventHandler.currentEvent.alreadyDisplayed = true; - } - Text.Font = GameFont.Small; - Text.Anchor = TextAnchor.MiddleCenter; - float num = 0f; - if (LongEventHandler.levelLoadOp != null) + if (LongEventHandler.currentEvent != null) { - float f = 1f; - if (!LongEventHandler.levelLoadOp.isDone) + if (Event.current.type == EventType.Repaint) { - f = LongEventHandler.levelLoadOp.progress; + LongEventHandler.currentEvent.alreadyDisplayed = true; } - string text = "LoadingAssets".Translate() + " " + f.ToStringPercent(); - num = Text.CalcSize(text).x; - Widgets.Label(rect, text); - } - else - { - object currentEventTextLock = LongEventHandler.CurrentEventTextLock; - lock (currentEventTextLock) + Text.Font = GameFont.Small; + Text.Anchor = TextAnchor.MiddleCenter; + float num = 0f; + if (LongEventHandler.levelLoadOp != null) { - num = Text.CalcSize(LongEventHandler.currentEvent.eventText).x; - Widgets.Label(rect, LongEventHandler.currentEvent.eventText); + float f = 1f; + if (!LongEventHandler.levelLoadOp.isDone) + { + f = LongEventHandler.levelLoadOp.progress; + } + string text = "LoadingAssets".Translate() + " " + f.ToStringPercent(); + Vector2 vector = Text.CalcSize(text); + num = vector.x; + Widgets.Label(rect, text); + } + else + { + object currentEventTextLock = LongEventHandler.CurrentEventTextLock; + Monitor.Enter(currentEventTextLock); + try + { + Vector2 vector2 = Text.CalcSize(LongEventHandler.currentEvent.eventText); + num = vector2.x; + Widgets.Label(rect, LongEventHandler.currentEvent.eventText); + } + finally + { + Monitor.Exit(currentEventTextLock); + } } + Text.Anchor = TextAnchor.MiddleLeft; + Vector2 center = rect.center; + rect.xMin = (float)(center.x + num / 2.0); + Widgets.Label(rect, LongEventHandler.currentEvent.UseAnimatedDots ? GenText.MarchingEllipsis(0f) : "..."); + Text.Anchor = TextAnchor.UpperLeft; } - Text.Anchor = TextAnchor.MiddleLeft; - rect.xMin = rect.center.x + num / 2f; - Widgets.Label(rect, LongEventHandler.currentEvent.UseAnimatedDots ? GenText.MarchingEllipsis(0f) : "..."); - Text.Anchor = TextAnchor.UpperLeft; } } } diff --git a/Assembly-CSharp/Verse/LookMode.cs b/Assembly-CSharp/Verse/LookMode.cs index 215a3c484..c46728b84 100644 --- a/Assembly-CSharp/Verse/LookMode.cs +++ b/Assembly-CSharp/Verse/LookMode.cs @@ -1,16 +1,14 @@ -using System; - namespace Verse { public enum LookMode : byte { - Undefined, - Value, - Deep, - Reference, - Def, - LocalTargetInfo, - TargetInfo, - GlobalTargetInfo + Undefined = 0, + Value = 1, + Deep = 2, + Reference = 3, + Def = 4, + LocalTargetInfo = 5, + TargetInfo = 6, + GlobalTargetInfo = 7 } } diff --git a/Assembly-CSharp/Verse/Map.cs b/Assembly-CSharp/Verse/Map.cs index d6a8ccdbd..6640aa174 100644 --- a/Assembly-CSharp/Verse/Map.cs +++ b/Assembly-CSharp/Verse/Map.cs @@ -2,7 +2,6 @@ using RimWorld.Planet; using System; using System.Collections.Generic; -using System.Diagnostics; using System.Linq; using UnityEngine; using Verse.AI; @@ -194,7 +193,10 @@ public IntVec3 Center { get { - return new IntVec3(this.Size.x / 2, 0, this.Size.z / 2); + IntVec3 size = this.Size; + int newX = size.x / 2; + IntVec3 size2 = this.Size; + return new IntVec3(newX, 0, size2.z / 2); } } @@ -210,7 +212,10 @@ public int Area { get { - return this.Size.x * this.Size.z; + IntVec3 size = this.Size; + int x = size.x; + IntVec3 size2 = this.Size; + return x * size2.z; } } @@ -226,11 +231,43 @@ public IEnumerable AllCells { get { - Map.<>c__Iterator1FD <>c__Iterator1FD = new Map.<>c__Iterator1FD(); - <>c__Iterator1FD.<>f__this = this; - Map.<>c__Iterator1FD expr_0E = <>c__Iterator1FD; - expr_0E.$PC = -2; - return expr_0E; + int z = 0; + while (true) + { + int num = z; + IntVec3 size = this.Size; + if (num < size.z) + { + int y = 0; + while (true) + { + int num2 = y; + IntVec3 size2 = this.Size; + if (num2 < size2.y) + { + int x = 0; + while (true) + { + int num3 = x; + IntVec3 size3 = this.Size; + if (num3 < size3.x) + { + yield return new IntVec3(x, y, z); + x++; + continue; + } + break; + } + y++; + continue; + } + break; + } + z++; + continue; + } + break; + } } } @@ -306,12 +343,12 @@ public IncidentTargetType Type } } - [DebuggerHidden] public IEnumerator GetEnumerator() { - Map.c__Iterator1FE c__Iterator1FE = new Map.c__Iterator1FE(); - c__Iterator1FE.<>f__this = this; - return c__Iterator1FE; + foreach (IntVec3 allCell in this.AllCells) + { + yield return allCell; + } } public void ConstructComponents() @@ -410,35 +447,38 @@ public void ExposeData() { try { - foreach (Thing current in this.listerThings.AllThings) + List.Enumerator enumerator = this.listerThings.AllThings.GetEnumerator(); + try { - try + while (enumerator.MoveNext()) { - if (current.def.isSaveable && !current.IsSaveCompressible()) + Thing current = enumerator.Current; + try { - if (hashSet.Contains(current.ThingID)) - { - Log.Error("Saving Thing with already-used ID " + current.ThingID); - } - else + if (current.def.isSaveable && !current.IsSaveCompressible()) { - hashSet.Add(current.ThingID); + if (hashSet.Contains(current.ThingID)) + { + Log.Error("Saving Thing with already-used ID " + current.ThingID); + } + else + { + hashSet.Add(current.ThingID); + } + Thing thing = current; + Scribe_Deep.Look(ref thing, "thing"); } - Thing thing = current; - Scribe_Deep.Look(ref thing, "thing", new object[0]); } - } - catch (Exception ex) - { - Log.Error(string.Concat(new object[] + catch (Exception ex) { - "Exception saving ", - current, - ": ", - ex - })); + Log.Error("Exception saving " + current + ": " + ex); + } } } + finally + { + ((IDisposable)(object)enumerator).Dispose(); + } } finally { @@ -471,15 +511,12 @@ public void ExposeData() private void FillComponents() { - this.components.RemoveAll((MapComponent component) => component == null); - foreach (Type current in typeof(MapComponent).AllSubclassesNonAbstract()) + this.components.RemoveAll((Predicate)((MapComponent component) => component == null)); + foreach (Type item2 in typeof(MapComponent).AllSubclassesNonAbstract()) { - if (this.GetComponent(current) == null) + if (this.GetComponent(item2) == null) { - MapComponent item = (MapComponent)Activator.CreateInstance(current, new object[] - { - this - }); + MapComponent item = (MapComponent)Activator.CreateInstance(item2, this); this.components.Add(item); } } @@ -488,34 +525,37 @@ private void FillComponents() public void FinalizeLoading() { - List list = this.compressor.ThingsToSpawnAfterLoad().ToList(); + List list = this.compressor.ThingsToSpawnAfterLoad().ToList(); this.compressor = null; DeepProfiler.Start("Merge compressed and non-compressed thing lists"); List list2 = new List(this.loadedFullThings.Count + list.Count); - foreach (Thing current in this.loadedFullThings.Concat(list)) + foreach (Thing item in this.loadedFullThings.Concat(list)) { - list2.Add(current); + list2.Add(item); } this.loadedFullThings.Clear(); DeepProfiler.End(); DeepProfiler.Start("Spawn everything into the map"); - foreach (Thing current2 in list2) + List.Enumerator enumerator2 = list2.GetEnumerator(); + try { - try - { - GenSpawn.Spawn(current2, current2.Position, this, current2.Rotation, true); - } - catch (Exception ex) + while (enumerator2.MoveNext()) { - Log.Error(string.Concat(new object[] + Thing current2 = enumerator2.Current; + try { - "Exception spawning loaded thing ", - current2, - ": ", - ex - })); + GenSpawn.Spawn(current2, current2.Position, this, current2.Rotation, true); + } + catch (Exception ex) + { + Log.Error("Exception spawning loaded thing " + current2 + ": " + ex); + } } } + finally + { + ((IDisposable)(object)enumerator2).Dispose(); + } DeepProfiler.End(); this.FinalizeInit(); } @@ -527,25 +567,28 @@ public void FinalizeInit() this.regionAndRoomUpdater.RebuildAllRegionsAndRooms(); this.powerNetManager.UpdatePowerNetsAndConnections_First(); this.temperatureCache.temperatureSaveLoad.ApplyLoadedDataToRegions(); - foreach (Thing current in this.listerThings.AllThings.ToList()) + List.Enumerator enumerator = this.listerThings.AllThings.ToList().GetEnumerator(); + try { - try - { - current.PostMapInit(); - } - catch (Exception ex) + while (enumerator.MoveNext()) { - Log.Error(string.Concat(new object[] + Thing current = enumerator.Current; + try + { + current.PostMapInit(); + } + catch (Exception ex) { - "Exception PostMapInit in ", - current, - ": ", - ex - })); + Log.Error("Exception PostMapInit in " + current + ": " + ex); + } } } + finally + { + ((IDisposable)(object)enumerator).Dispose(); + } this.listerFilthInHomeArea.RebuildAll(); - LongEventHandler.ExecuteWhenFinished(delegate + LongEventHandler.ExecuteWhenFinished((Action)delegate { this.mapDrawer.RegenerateEverythingNow(); }); @@ -556,86 +599,86 @@ public void FinalizeInit() private void ExposeComponents() { - Scribe_Deep.Look(ref this.weatherManager, "weatherManager", new object[] + Scribe_Deep.Look(ref this.weatherManager, "weatherManager", new object[1] { this }); - Scribe_Deep.Look(ref this.reservationManager, "reservationManager", new object[] + Scribe_Deep.Look(ref this.reservationManager, "reservationManager", new object[1] { this }); Scribe_Deep.Look(ref this.physicalInteractionReservationManager, "physicalInteractionReservationManager", new object[0]); - Scribe_Deep.Look(ref this.designationManager, "designationManager", new object[] + Scribe_Deep.Look(ref this.designationManager, "designationManager", new object[1] { this }); - Scribe_Deep.Look(ref this.lordManager, "lordManager", new object[] + Scribe_Deep.Look(ref this.lordManager, "lordManager", new object[1] { this }); - Scribe_Deep.Look(ref this.passingShipManager, "visitorManager", new object[] + Scribe_Deep.Look(ref this.passingShipManager, "visitorManager", new object[1] { this }); - Scribe_Deep.Look(ref this.gameConditionManager, "gameConditionManager", new object[] + Scribe_Deep.Look(ref this.gameConditionManager, "gameConditionManager", new object[1] { this }); - Scribe_Deep.Look(ref this.fogGrid, "fogGrid", new object[] + Scribe_Deep.Look(ref this.fogGrid, "fogGrid", new object[1] { this }); - Scribe_Deep.Look(ref this.roofGrid, "roofGrid", new object[] + Scribe_Deep.Look(ref this.roofGrid, "roofGrid", new object[1] { this }); - Scribe_Deep.Look(ref this.terrainGrid, "terrainGrid", new object[] + Scribe_Deep.Look(ref this.terrainGrid, "terrainGrid", new object[1] { this }); - Scribe_Deep.Look(ref this.zoneManager, "zoneManager", new object[] + Scribe_Deep.Look(ref this.zoneManager, "zoneManager", new object[1] { this }); - Scribe_Deep.Look(ref this.temperatureCache, "temperatureCache", new object[] + Scribe_Deep.Look(ref this.temperatureCache, "temperatureCache", new object[1] { this }); - Scribe_Deep.Look(ref this.snowGrid, "snowGrid", new object[] + Scribe_Deep.Look(ref this.snowGrid, "snowGrid", new object[1] { this }); - Scribe_Deep.Look(ref this.areaManager, "areaManager", new object[] + Scribe_Deep.Look(ref this.areaManager, "areaManager", new object[1] { this }); - Scribe_Deep.Look(ref this.lordsStarter, "lordsStarter", new object[] + Scribe_Deep.Look(ref this.lordsStarter, "lordsStarter", new object[1] { this }); - Scribe_Deep.Look(ref this.attackTargetReservationManager, "attackTargetReservationManager", new object[] + Scribe_Deep.Look(ref this.attackTargetReservationManager, "attackTargetReservationManager", new object[1] { this }); - Scribe_Deep.Look(ref this.deepResourceGrid, "deepResourceGrid", new object[] + Scribe_Deep.Look(ref this.deepResourceGrid, "deepResourceGrid", new object[1] { this }); - Scribe_Deep.Look(ref this.weatherDecider, "weatherDecider", new object[] + Scribe_Deep.Look(ref this.weatherDecider, "weatherDecider", new object[1] { this }); Scribe_Deep.Look(ref this.damageWatcher, "damageWatcher", new object[0]); - Scribe_Deep.Look(ref this.rememberedCameraPos, "rememberedCameraPos", new object[] + Scribe_Deep.Look(ref this.rememberedCameraPos, "rememberedCameraPos", new object[1] { this }); Scribe_Deep.Look(ref this.mineStrikeManager, "mineStrikeManager", new object[0]); - Scribe_Deep.Look(ref this.storyState, "storyState", new object[] + Scribe_Deep.Look(ref this.storyState, "storyState", new object[1] { this }); - Scribe_Collections.Look(ref this.components, "components", LookMode.Deep, new object[] + Scribe_Collections.Look(ref this.components, "components", LookMode.Deep, new object[1] { this }); @@ -839,13 +882,13 @@ public T GetComponent() where T : MapComponent { for (int i = 0; i < this.components.Count; i++) { - T t = this.components[i] as T; - if (t != null) + T val = (T)(this.components[i] as T); + if (val != null) { - return t; + return val; } } - return (T)((object)null); + return (T)null; } public MapComponent GetComponent(Type type) diff --git a/Assembly-CSharp/Verse/MapCellsInRandomOrder.cs b/Assembly-CSharp/Verse/MapCellsInRandomOrder.cs index 992301f18..4cb2b4694 100644 --- a/Assembly-CSharp/Verse/MapCellsInRandomOrder.cs +++ b/Assembly-CSharp/Verse/MapCellsInRandomOrder.cs @@ -1,4 +1,3 @@ -using System; using System.Collections.Generic; namespace Verse @@ -19,11 +18,11 @@ public IntVec3 Get(int index) if (this.randomizedCells == null) { this.randomizedCells = new List(this.map.Area); - foreach (IntVec3 current in this.map.AllCells) + foreach (IntVec3 allCell in this.map.AllCells) { - this.randomizedCells.Add(current); + this.randomizedCells.Add(allCell); } - this.randomizedCells.Shuffle(); + this.randomizedCells.Shuffle(); } return this.randomizedCells[index]; } diff --git a/Assembly-CSharp/Verse/MapComponent.cs b/Assembly-CSharp/Verse/MapComponent.cs index b2331c357..6a8d60adf 100644 --- a/Assembly-CSharp/Verse/MapComponent.cs +++ b/Assembly-CSharp/Verse/MapComponent.cs @@ -1,5 +1,3 @@ -using System; - namespace Verse { public abstract class MapComponent : IExposable diff --git a/Assembly-CSharp/Verse/MapDeiniter.cs b/Assembly-CSharp/Verse/MapDeiniter.cs index d23043d06..cfd9d956e 100644 --- a/Assembly-CSharp/Verse/MapDeiniter.cs +++ b/Assembly-CSharp/Verse/MapDeiniter.cs @@ -65,7 +65,7 @@ public static void Deinit(Map map) private static void PassPawnsToWorld(Map map) { bool flag = map.ParentFaction != null && map.ParentFaction.HostileTo(Faction.OfPlayer); - List list = map.mapPawns.AllPawns.ToList(); + List list = map.mapPawns.AllPawns.ToList(); for (int i = 0; i < list.Count; i++) { try @@ -86,13 +86,7 @@ private static void PassPawnsToWorld(Map map) } catch (Exception ex) { - Log.Error(string.Concat(new object[] - { - "Could not despawn and pass to world ", - list[i], - ": ", - ex - })); + Log.Error("Could not despawn and pass to world " + list[i] + ": " + ex); } } } @@ -152,15 +146,15 @@ private static void NotifyEverythingWhichUsesMapReference(Map map) allRooms[l].DecrementMapIndex(); } } - foreach (Region current in maps[j].regionGrid.AllRegions_NoRebuild_InvalidAllowed) + foreach (Region item in maps[j].regionGrid.AllRegions_NoRebuild_InvalidAllowed) { if (j == num) { - current.Notify_MyMapRemoved(); + item.Notify_MyMapRemoved(); } else { - current.DecrementMapIndex(); + item.DecrementMapIndex(); } } } diff --git a/Assembly-CSharp/Verse/MapDrawer.cs b/Assembly-CSharp/Verse/MapDrawer.cs index 973e490e4..999fa1768 100644 --- a/Assembly-CSharp/Verse/MapDrawer.cs +++ b/Assembly-CSharp/Verse/MapDrawer.cs @@ -1,5 +1,4 @@ using RimWorld; -using System; using UnityEngine; namespace Verse @@ -14,11 +13,12 @@ private IntVec2 SectionCount { get { - return new IntVec2 - { - x = Mathf.CeilToInt((float)this.map.Size.x / 17f), - z = Mathf.CeilToInt((float)this.map.Size.z / 17f) - }; + IntVec2 result = default(IntVec2); + IntVec3 size = this.map.Size; + result.x = Mathf.CeilToInt((float)((float)size.x / 17.0)); + IntVec3 size2 = this.map.Size; + result.z = Mathf.CeilToInt((float)((float)size2.z / 17.0)); + return result; } } @@ -31,11 +31,11 @@ private CellRect VisibleSections sunShadowsViewRect.ClipInsideMap(this.map); IntVec2 intVec = this.SectionCoordsAt(sunShadowsViewRect.BottomLeft); IntVec2 intVec2 = this.SectionCoordsAt(sunShadowsViewRect.TopRight); - if (intVec2.x < intVec.x || intVec2.z < intVec.z) + if (intVec2.x >= intVec.x && intVec2.z >= intVec.z) { - return CellRect.Empty; + return CellRect.FromLimits(intVec.x, intVec.z, intVec2.x, intVec2.z); } - return CellRect.FromLimits(intVec.x, intVec.z, intVec2.x, intVec2.z); + return CellRect.Empty; } } @@ -46,42 +46,41 @@ public MapDrawer(Map map) public void MapMeshDirty(IntVec3 loc, MapMeshFlag dirtyFlags) { - bool regenAdjacentCells = (dirtyFlags & (MapMeshFlag.FogOfWar | MapMeshFlag.Buildings)) != MapMeshFlag.None; - bool regenAdjacentSections = (dirtyFlags & MapMeshFlag.GroundGlow) != MapMeshFlag.None; + bool regenAdjacentCells = ((int)dirtyFlags & 6) != 0; + bool regenAdjacentSections = ((int)dirtyFlags & 8) != 0; this.MapMeshDirty(loc, dirtyFlags, regenAdjacentCells, regenAdjacentSections); } public void MapMeshDirty(IntVec3 loc, MapMeshFlag dirtyFlags, bool regenAdjacentCells, bool regenAdjacentSections) { - if (Current.ProgramState != ProgramState.Playing) - { - return; - } - Section section = this.SectionAt(loc); - section.dirtyFlags |= dirtyFlags; - if (regenAdjacentCells) + if (Current.ProgramState == ProgramState.Playing) { - for (int i = 0; i < 8; i++) + Section section = this.SectionAt(loc); + section.dirtyFlags |= dirtyFlags; + if (regenAdjacentCells) { - IntVec3 intVec = loc + GenAdj.AdjacentCells[i]; - if (intVec.InBounds(this.map)) + for (int i = 0; i < 8; i++) { - this.SectionAt(intVec).dirtyFlags |= dirtyFlags; + IntVec3 intVec = loc + GenAdj.AdjacentCells[i]; + if (intVec.InBounds(this.map)) + { + this.SectionAt(intVec).dirtyFlags |= dirtyFlags; + } } } - } - if (regenAdjacentSections) - { - IntVec2 a = this.SectionCoordsAt(loc); - for (int j = 0; j < 8; j++) + if (regenAdjacentSections) { - IntVec3 intVec2 = GenAdj.AdjacentCells[j]; - IntVec2 intVec3 = a + new IntVec2(intVec2.x, intVec2.z); - IntVec2 sectionCount = this.SectionCount; - if (intVec3.x >= 0 && intVec3.z >= 0 && intVec3.x <= sectionCount.x - 1 && intVec3.z <= sectionCount.z - 1) + IntVec2 a = this.SectionCoordsAt(loc); + for (int j = 0; j < 8; j++) { - Section section2 = this.sections[intVec3.x, intVec3.z]; - section2.dirtyFlags |= dirtyFlags; + IntVec3 intVec2 = GenAdj.AdjacentCells[j]; + IntVec2 intVec3 = a + new IntVec2(intVec2.x, intVec2.z); + IntVec2 sectionCount = this.SectionCount; + if (intVec3.x >= 0 && intVec3.z >= 0 && intVec3.x <= sectionCount.x - 1 && intVec3.z <= sectionCount.z - 1) + { + Section section2 = this.sections[intVec3.x, intVec3.z]; + section2.dirtyFlags |= dirtyFlags; + } } } } @@ -104,15 +103,33 @@ public void MapMeshDrawerUpdate_First() } if (!flag) { - for (int i = 0; i < this.SectionCount.x; i++) + int num = 0; + while (true) { - for (int j = 0; j < this.SectionCount.z; j++) + int num2 = num; + IntVec2 sectionCount = this.SectionCount; + if (num2 < sectionCount.x) { - if (this.TryUpdateSection(this.sections[i, j])) + int num3 = 0; + while (true) { - return; + int num4 = num3; + IntVec2 sectionCount2 = this.SectionCount; + if (num4 < sectionCount2.z) + { + if (!this.TryUpdateSection(this.sections[num, num3])) + { + num3++; + continue; + } + return; + } + break; } + num++; + continue; } + break; } } } @@ -126,7 +143,7 @@ private bool TryUpdateSection(Section sect) for (int i = 0; i < MapMeshFlagUtility.allFlags.Count; i++) { MapMeshFlag mapMeshFlag = MapMeshFlagUtility.allFlags[i]; - if ((sect.dirtyFlags & mapMeshFlag) != MapMeshFlag.None) + if ((sect.dirtyFlags & mapMeshFlag) != 0) { sect.RegenerateLayers(mapMeshFlag); } @@ -165,36 +182,75 @@ public void RegenerateEverythingNow() { if (this.sections == null) { - this.sections = new Section[this.SectionCount.x, this.SectionCount.z]; + IntVec2 sectionCount = this.SectionCount; + int x = sectionCount.x; + IntVec2 sectionCount2 = this.SectionCount; + this.sections = new Section[x, sectionCount2.z]; } - for (int i = 0; i < this.SectionCount.x; i++) + int num = 0; + while (true) { - for (int j = 0; j < this.SectionCount.z; j++) + int num2 = num; + IntVec2 sectionCount3 = this.SectionCount; + if (num2 < sectionCount3.x) { - if (this.sections[i, j] == null) + int num3 = 0; + while (true) { - this.sections[i, j] = new Section(new IntVec3(i, 0, j), this.map); + int num4 = num3; + IntVec2 sectionCount4 = this.SectionCount; + if (num4 < sectionCount4.z) + { + if (this.sections[num, num3] == null) + { + this.sections[num, num3] = new Section(new IntVec3(num, 0, num3), this.map); + } + this.sections[num, num3].RegenerateAllLayers(); + num3++; + continue; + } + break; } - this.sections[i, j].RegenerateAllLayers(); + num++; + continue; } + break; } } public void WholeMapChanged(MapMeshFlag change) { - for (int i = 0; i < this.SectionCount.x; i++) + int num = 0; + while (true) { - for (int j = 0; j < this.SectionCount.z; j++) + int num2 = num; + IntVec2 sectionCount = this.SectionCount; + if (num2 < sectionCount.x) { - this.sections[i, j].dirtyFlags |= change; + int num3 = 0; + while (true) + { + int num4 = num3; + IntVec2 sectionCount2 = this.SectionCount; + if (num4 < sectionCount2.z) + { + this.sections[num, num3].dirtyFlags |= change; + num3++; + continue; + } + break; + } + num++; + continue; } + break; } } private CellRect GetSunShadowsViewRect(CellRect rect) { Vector2 vector = GenCelestial.CurShadowVector(this.map); - if (vector.x < 0f) + if (vector.x < 0.0) { rect.maxX -= Mathf.FloorToInt(vector.x); } @@ -202,7 +258,7 @@ private CellRect GetSunShadowsViewRect(CellRect rect) { rect.minX -= Mathf.CeilToInt(vector.x); } - if (vector.y < 0f) + if (vector.y < 0.0) { rect.maxZ -= Mathf.FloorToInt(vector.y); } diff --git a/Assembly-CSharp/Verse/MapEdgeClipDrawer.cs b/Assembly-CSharp/Verse/MapEdgeClipDrawer.cs index b24dd7369..b47331405 100644 --- a/Assembly-CSharp/Verse/MapEdgeClipDrawer.cs +++ b/Assembly-CSharp/Verse/MapEdgeClipDrawer.cs @@ -1,4 +1,3 @@ -using System; using UnityEngine; namespace Verse @@ -17,14 +16,14 @@ public static void DrawClippers(Map map) IntVec3 size = map.Size; Vector3 s = new Vector3(500f, 1f, (float)size.z); Matrix4x4 matrix = default(Matrix4x4); - matrix.SetTRS(new Vector3(-250f, MapEdgeClipDrawer.ClipAltitude, (float)size.z / 2f), Quaternion.identity, s); + matrix.SetTRS(new Vector3(-250f, MapEdgeClipDrawer.ClipAltitude, (float)((float)size.z / 2.0)), Quaternion.identity, s); Graphics.DrawMesh(MeshPool.plane10, matrix, MapEdgeClipDrawer.ClipMat, 0); matrix = default(Matrix4x4); - matrix.SetTRS(new Vector3((float)size.x + 250f, MapEdgeClipDrawer.ClipAltitude, (float)size.z / 2f), Quaternion.identity, s); + matrix.SetTRS(new Vector3((float)((float)size.x + 250.0), MapEdgeClipDrawer.ClipAltitude, (float)((float)size.z / 2.0)), Quaternion.identity, s); Graphics.DrawMesh(MeshPool.plane10, matrix, MapEdgeClipDrawer.ClipMat, 0); s = new Vector3(1000f, 1f, 500f); matrix = default(Matrix4x4); - matrix.SetTRS(new Vector3((float)(size.x / 2), MapEdgeClipDrawer.ClipAltitude, (float)size.z + 250f), Quaternion.identity, s); + matrix.SetTRS(new Vector3((float)(size.x / 2), MapEdgeClipDrawer.ClipAltitude, (float)((float)size.z + 250.0)), Quaternion.identity, s); Graphics.DrawMesh(MeshPool.plane10, matrix, MapEdgeClipDrawer.ClipMat, 0); matrix = default(Matrix4x4); matrix.SetTRS(new Vector3((float)(size.x / 2), MapEdgeClipDrawer.ClipAltitude, -250f), Quaternion.identity, s); diff --git a/Assembly-CSharp/Verse/MapFileCompressor.cs b/Assembly-CSharp/Verse/MapFileCompressor.cs index d7a2fb56d..eef6ae276 100644 --- a/Assembly-CSharp/Verse/MapFileCompressor.cs +++ b/Assembly-CSharp/Verse/MapFileCompressor.cs @@ -1,6 +1,5 @@ using System; using System.Collections.Generic; -using System.Diagnostics; namespace Verse { @@ -19,7 +18,7 @@ public MapFileCompressor(Map map) public void ExposeData() { - Scribe_Values.Look(ref this.compressedString, "compressedThingMap", null, false); + Scribe_Values.Look(ref this.compressedString, "compressedThingMap", (string)null, false); } public void BuildCompressedString() @@ -31,35 +30,55 @@ public void BuildCompressedString() private ushort HashValueForSquare(IntVec3 curSq) { - ushort num = 0; - foreach (Thing current in this.map.thingGrid.ThingsAt(curSq)) + ushort num = (ushort)0; + foreach (Thing item in this.map.thingGrid.ThingsAt(curSq)) { - if (current.IsSaveCompressible()) + if (item.IsSaveCompressible()) { if (num != 0) { - Log.Error(string.Concat(new object[] - { - "Found two compressible things in ", - curSq, - ". The last was ", - current - })); + Log.Error("Found two compressible things in " + curSq + ". The last was " + item); } - num = current.def.shortHash; + num = item.def.shortHash; } } return num; } - [DebuggerHidden] public IEnumerable ThingsToSpawnAfterLoad() { - MapFileCompressor.c__Iterator1F2 c__Iterator1F = new MapFileCompressor.c__Iterator1F2(); - c__Iterator1F.<>f__this = this; - MapFileCompressor.c__Iterator1F2 expr_0E = c__Iterator1F; - expr_0E.$PC = -2; - return expr_0E; + Dictionary thingDefsByShortHash = new Dictionary(); + foreach (ThingDef allDef in DefDatabase.AllDefs) + { + if (thingDefsByShortHash.ContainsKey(allDef.shortHash)) + { + Log.Error("Hash collision between " + allDef + " and " + thingDefsByShortHash[allDef.shortHash] + ": both have short hash " + allDef.shortHash); + } + else + { + thingDefsByShortHash.Add(allDef.shortHash, allDef); + } + } + foreach (GridSaveUtility.LoadedGridShort item in GridSaveUtility.LoadedUShortGrid(this.compressedString, this.map)) + { + GridSaveUtility.LoadedGridShort gridThing = item; + if (gridThing.val != 0) + { + ThingDef def = null; + try + { + def = thingDefsByShortHash[gridThing.val]; + } + catch (KeyNotFoundException) + { + Log.Error("Map compressor decompression error: No thingDef with short hash " + gridThing.val + ". Adding as null to dictionary."); + thingDefsByShortHash.Add(gridThing.val, null); + } + Thing th = ThingMaker.MakeThing(def, null); + th.SetPositionDirect(gridThing.cell); + yield return th; + } + } } } } diff --git a/Assembly-CSharp/Verse/MapGenFloatGrid.cs b/Assembly-CSharp/Verse/MapGenFloatGrid.cs index b09e78a01..878705e3f 100644 --- a/Assembly-CSharp/Verse/MapGenFloatGrid.cs +++ b/Assembly-CSharp/Verse/MapGenFloatGrid.cs @@ -1,5 +1,3 @@ -using System; - namespace Verse { public class MapGenFloatGrid diff --git a/Assembly-CSharp/Verse/MapGenerator.cs b/Assembly-CSharp/Verse/MapGenerator.cs index 82cb723e0..08c45ec84 100644 --- a/Assembly-CSharp/Verse/MapGenerator.cs +++ b/Assembly-CSharp/Verse/MapGenerator.cs @@ -45,7 +45,6 @@ public static Map GenerateMap(IntVec3 mapSize, MapParent parent, MapGeneratorDef MapGenerator.playerStartSpotInt = IntVec3.Invalid; MapGenerator.rootsToUnfog.Clear(); MapGenerator.data.Clear(); - Map result; try { DeepProfiler.Start("InitNewGeneratedMap"); @@ -62,13 +61,13 @@ public static Map GenerateMap(IntVec3 mapSize, MapParent parent, MapGeneratorDef map.ConstructComponents(); DeepProfiler.End(); Current.Game.AddMap(map); - if (extraInitBeforeContentGen != null) + if ((object)extraInitBeforeContentGen != null) { extraInitBeforeContentGen(map); } if (mapGenerator == null) { - mapGenerator = DefDatabase.AllDefsListForReading.RandomElementByWeight((MapGeneratorDef x) => x.selectionWeight); + mapGenerator = DefDatabase.AllDefsListForReading.RandomElementByWeight((Func)((MapGeneratorDef x) => x.selectionWeight)); } IEnumerable enumerable = mapGenerator.GenSteps; if (extraGenStepDefs != null) @@ -90,14 +89,16 @@ public static Map GenerateMap(IntVec3 mapSize, MapParent parent, MapGeneratorDef { parent.PostMapGenerate(); } - result = map; + return map; + IL_0167: + Map result; + return result; } finally { DeepProfiler.End(); Current.ProgramState = programState; } - return result; } public static void GenerateContentsIntoMap(IEnumerable genStepDefs, Map map) @@ -105,14 +106,14 @@ public static void GenerateContentsIntoMap(IEnumerable genStepDefs, Rand.Seed = Gen.HashCombineInt(Find.World.info.Seed, map.Tile); MapGenerator.data.Clear(); RockNoises.Init(map); - foreach (GenStepDef current in from x in genStepDefs + foreach (GenStepDef item in from x in genStepDefs orderby x.order, x.index select x) { - DeepProfiler.Start("Genstep - " + current.ToString()); + DeepProfiler.Start("Genstep - " + item.ToString()); try { - current.genStep.Generate(map); + item.genStep.Generate(map); } catch (Exception ex) { @@ -130,20 +131,20 @@ public static void GenerateContentsIntoMap(IEnumerable genStepDefs, public static T GetVar(string name) { - object obj; + object obj = default(object); if (MapGenerator.data.TryGetValue(name, out obj)) { - return (T)((object)obj); + return (T)obj; } return default(T); } public static bool TryGetVar(string name, out T var) { - object obj; + object obj = default(object); if (MapGenerator.data.TryGetValue(name, out obj)) { - var = (T)((object)obj); + var = (T)obj; return true; } var = default(T); @@ -163,7 +164,7 @@ public static MapGenFloatGrid FloatGridNamed(string name, Map map) return var; } MapGenFloatGrid mapGenFloatGrid = new MapGenFloatGrid(map); - MapGenerator.SetVar(name, mapGenFloatGrid); + MapGenerator.SetVar(name, mapGenFloatGrid); return mapGenFloatGrid; } } diff --git a/Assembly-CSharp/Verse/MapGeneratorDef.cs b/Assembly-CSharp/Verse/MapGeneratorDef.cs index 64d110f70..280e57b40 100644 --- a/Assembly-CSharp/Verse/MapGeneratorDef.cs +++ b/Assembly-CSharp/Verse/MapGeneratorDef.cs @@ -1,4 +1,3 @@ -using System; using System.Collections.Generic; namespace Verse diff --git a/Assembly-CSharp/Verse/MapInfo.cs b/Assembly-CSharp/Verse/MapInfo.cs index ecd694fc3..d90feaf88 100644 --- a/Assembly-CSharp/Verse/MapInfo.cs +++ b/Assembly-CSharp/Verse/MapInfo.cs @@ -1,5 +1,4 @@ using RimWorld.Planet; -using System; using UnityEngine; namespace Verse @@ -22,7 +21,12 @@ public int NumCells { get { - return this.Size.x * this.Size.y * this.Size.z; + IntVec3 size = this.Size; + int x = size.x; + IntVec3 size2 = this.Size; + int num = x * size2.y; + IntVec3 size3 = this.Size; + return num * size3.z; } } @@ -43,11 +47,11 @@ public int PowerOfTwoOverMapSize get { int num = Mathf.Max(this.sizeInt.x, this.sizeInt.z); - int i; - for (i = 1; i <= num; i *= 2) + int num2; + for (num2 = 1; num2 <= num; num2 *= 2) { } - return i; + return num2; } } diff --git a/Assembly-CSharp/Verse/MapMeshFlagUtility.cs b/Assembly-CSharp/Verse/MapMeshFlagUtility.cs index b671b0dc8..3efad1e1e 100644 --- a/Assembly-CSharp/Verse/MapMeshFlagUtility.cs +++ b/Assembly-CSharp/Verse/MapMeshFlagUtility.cs @@ -1,5 +1,4 @@ using System; -using System.Collections; using System.Collections.Generic; namespace Verse @@ -11,15 +10,11 @@ internal static class MapMeshFlagUtility static MapMeshFlagUtility() { MapMeshFlagUtility.allFlags = new List(); - using (IEnumerator enumerator = Enum.GetValues(typeof(MapMeshFlag)).GetEnumerator()) + foreach (int value in Enum.GetValues(typeof(MapMeshFlag))) { - while (enumerator.MoveNext()) + if (value != 0) { - MapMeshFlag mapMeshFlag = (MapMeshFlag)((int)enumerator.Current); - if (mapMeshFlag != MapMeshFlag.None) - { - MapMeshFlagUtility.allFlags.Add(mapMeshFlag); - } + MapMeshFlagUtility.allFlags.Add((MapMeshFlag)value); } } } diff --git a/Assembly-CSharp/Verse/MapPawns.cs b/Assembly-CSharp/Verse/MapPawns.cs index ec25a397a..8567c2ea9 100644 --- a/Assembly-CSharp/Verse/MapPawns.cs +++ b/Assembly-CSharp/Verse/MapPawns.cs @@ -24,11 +24,14 @@ public IEnumerable AllPawns { get { - MapPawns.<>c__Iterator1FA <>c__Iterator1FA = new MapPawns.<>c__Iterator1FA(); - <>c__Iterator1FA.<>f__this = this; - MapPawns.<>c__Iterator1FA expr_0E = <>c__Iterator1FA; - expr_0E.$PC = -2; - return expr_0E; + for (int i = 0; i < this.pawnsSpawned.Count; i++) + { + yield return this.pawnsSpawned[i]; + } + foreach (Pawn item in this.AllPawnsUnspawned) + { + yield return item; + } } } @@ -36,11 +39,60 @@ public IEnumerable AllPawnsUnspawned { get { - MapPawns.<>c__Iterator1FB <>c__Iterator1FB = new MapPawns.<>c__Iterator1FB(); - <>c__Iterator1FB.<>f__this = this; - MapPawns.<>c__Iterator1FB expr_0E = <>c__Iterator1FB; - expr_0E.$PC = -2; - return expr_0E; + List holders = this.map.listerThings.ThingsInGroup(ThingRequestGroup.ThisOrAnyCompIsThingHolder); + for (int n = 0; n < holders.Count; n++) + { + IThingHolder holder = holders[n] as IThingHolder; + if (holder != null) + { + ThingOwnerUtility.GetAllThingsRecursively(holder, MapPawns.tmpThings, true); + for (int k = 0; k < MapPawns.tmpThings.Count; k++) + { + Pawn p2 = MapPawns.tmpThings[k] as Pawn; + if (p2 != null && !p2.Dead) + { + yield return p2; + } + } + } + ThingWithComps twc = holders[n] as ThingWithComps; + if (twc != null) + { + List comps = twc.AllComps; + for (int j = 0; j < comps.Count; j++) + { + IThingHolder compHolder = comps[j] as IThingHolder; + if (compHolder != null) + { + ThingOwnerUtility.GetAllThingsRecursively(compHolder, MapPawns.tmpThings, true); + for (int i = 0; i < MapPawns.tmpThings.Count; i++) + { + Pawn p = MapPawns.tmpThings[i] as Pawn; + if (p != null && !p.Dead) + { + yield return p; + } + } + } + } + } + } + MapPawns.tmpMapChildHolders.Clear(); + this.map.GetNonThingChildHolders(MapPawns.tmpMapChildHolders); + for (int m = 0; m < MapPawns.tmpMapChildHolders.Count; m++) + { + ThingOwnerUtility.GetAllThingsRecursively(MapPawns.tmpMapChildHolders[m], MapPawns.tmpThings, true); + for (int l = 0; l < MapPawns.tmpThings.Count; l++) + { + Pawn p3 = MapPawns.tmpThings[l] as Pawn; + if (p3 != null && !p3.Dead) + { + yield return p3; + } + } + } + MapPawns.tmpMapChildHolders.Clear(); + MapPawns.tmpThings.Clear(); } } @@ -81,7 +133,7 @@ public int ColonistCount } return (from x in this.AllPawns where x.RaceProps.Humanlike && x.Faction == Faction.OfPlayer - select x).Count(); + select x).Count(); } } @@ -89,7 +141,7 @@ public int AllPawnsCount { get { - return this.AllPawns.Count(); + return this.AllPawns.Count(); } } @@ -97,7 +149,7 @@ public int AllPawnsUnspawnedCount { get { - return this.AllPawnsUnspawned.Count(); + return this.AllPawnsUnspawned.Count(); } } @@ -105,7 +157,7 @@ public int FreeColonistsCount { get { - return this.FreeColonists.Count(); + return this.FreeColonists.Count(); } } @@ -113,7 +165,7 @@ public int PrisonersOfColonyCount { get { - return this.PrisonersOfColony.Count(); + return this.PrisonersOfColony.Count(); } } @@ -121,7 +173,7 @@ public int FreeColonistsAndPrisonersCount { get { - return this.PrisonersOfColony.Count(); + return this.PrisonersOfColony.Count(); } } @@ -130,23 +182,26 @@ public bool AnyPawnBlockingMapRemoval get { Faction ofPlayer = Faction.OfPlayer; - for (int i = 0; i < this.pawnsSpawned.Count; i++) + int num = 0; + while (num < this.pawnsSpawned.Count) { - if (this.pawnsSpawned[i].Faction == ofPlayer || this.pawnsSpawned[i].HostFaction == ofPlayer) + if (this.pawnsSpawned[num].Faction != ofPlayer && this.pawnsSpawned[num].HostFaction != ofPlayer) { - return true; + num++; + continue; } + return true; } List list = this.map.listerThings.ThingsInGroup(ThingRequestGroup.ThisOrAnyCompIsThingHolder); - for (int j = 0; j < list.Count; j++) + for (int i = 0; i < list.Count; i++) { - if (list[j] is IActiveDropPod || list[j].TryGetComp() != null) + if (list[i] is IActiveDropPod || list[i].TryGetComp() != null) { - IThingHolder holder = list[j].TryGetComp() ?? ((IThingHolder)list[j]); + IThingHolder holder = list[i].TryGetComp() ?? ((IThingHolder)list[i]); ThingOwnerUtility.GetAllThingsRecursively(holder, MapPawns.tmpThings, true); - for (int k = 0; k < MapPawns.tmpThings.Count; k++) + for (int j = 0; j < MapPawns.tmpThings.Count; j++) { - Pawn pawn = MapPawns.tmpThings[k] as Pawn; + Pawn pawn = MapPawns.tmpThings[j] as Pawn; if (pawn != null && (pawn.Faction == ofPlayer || pawn.HostFaction == ofPlayer)) { MapPawns.tmpThings.Clear(); @@ -204,7 +259,7 @@ public int FreeColonistsSpawnedCount { get { - return this.FreeColonistsSpawned.Count(); + return this.FreeColonistsSpawned.Count(); } } @@ -220,7 +275,7 @@ public int FreeColonistsAndPrisonersSpawnedCount { get { - return this.FreeColonistsAndPrisonersSpawned.Count(); + return this.FreeColonistsAndPrisonersSpawned.Count(); } } @@ -257,17 +312,18 @@ public int FreeColonistsSpawnedOrInPlayerEjectablePodsCount for (int j = 0; j < list.Count; j++) { Building_CryptosleepCasket building_CryptosleepCasket = list[j] as Building_CryptosleepCasket; - if ((building_CryptosleepCasket != null && building_CryptosleepCasket.def.building.isPlayerEjectable) || list[j] is IActiveDropPod || list[j].TryGetComp() != null) + if ((building_CryptosleepCasket == null || !building_CryptosleepCasket.def.building.isPlayerEjectable) && !(list[j] is IActiveDropPod) && list[j].TryGetComp() == null) { - IThingHolder holder = list[j].TryGetComp() ?? ((IThingHolder)list[j]); - ThingOwnerUtility.GetAllThingsRecursively(holder, MapPawns.tmpThings, true); - for (int k = 0; k < MapPawns.tmpThings.Count; k++) + continue; + } + IThingHolder holder = list[j].TryGetComp() ?? ((IThingHolder)list[j]); + ThingOwnerUtility.GetAllThingsRecursively(holder, MapPawns.tmpThings, true); + for (int k = 0; k < MapPawns.tmpThings.Count; k++) + { + Pawn pawn = MapPawns.tmpThings[k] as Pawn; + if (pawn != null && pawn.IsColonist && pawn.HostFaction == null) { - Pawn pawn = MapPawns.tmpThings[k] as Pawn; - if (pawn != null && pawn.IsColonist && pawn.HostFaction == null) - { - num++; - } + num++; } } } @@ -334,60 +390,42 @@ public void RegisterPawn(Pawn p) { if (p.Dead) { - Log.Warning(string.Concat(new object[] - { - "Tried to register dead pawn ", - p, - " in ", - base.GetType(), - "." - })); - return; + Log.Warning("Tried to register dead pawn " + p + " in " + base.GetType() + "."); } - if (!p.Spawned) + else if (!p.Spawned) { - Log.Warning(string.Concat(new object[] - { - "Tried to register despawned pawn ", - p, - " in ", - base.GetType(), - "." - })); - return; + Log.Warning("Tried to register despawned pawn " + p + " in " + base.GetType() + "."); } - if (p.Map != this.map) + else if (p.Map != this.map) { Log.Warning("Tried to register pawn " + p + " but his Map is not this one."); - return; - } - if (!p.mindState.Active) - { - return; - } - this.EnsureFactionsListsInit(); - if (!this.pawnsSpawned.Contains(p)) - { - this.pawnsSpawned.Add(p); } - if (p.Faction != null && !this.pawnsInFactionSpawned[p.Faction].Contains(p)) + else if (p.mindState.Active) { - this.pawnsInFactionSpawned[p.Faction].Add(p); - if (p.Faction == Faction.OfPlayer) + this.EnsureFactionsListsInit(); + if (!this.pawnsSpawned.Contains(p)) { - this.pawnsInFactionSpawned[Faction.OfPlayer].InsertionSort(delegate(Pawn a, Pawn b) + this.pawnsSpawned.Add(p); + } + if (p.Faction != null && !this.pawnsInFactionSpawned[p.Faction].Contains(p)) + { + this.pawnsInFactionSpawned[p.Faction].Add(p); + if (p.Faction == Faction.OfPlayer) { - int num = (a.playerSettings == null) ? 0 : a.playerSettings.joinTick; - int value = (b.playerSettings == null) ? 0 : b.playerSettings.joinTick; - return num.CompareTo(value); - }); + this.pawnsInFactionSpawned[Faction.OfPlayer].InsertionSort((Comparison)delegate(Pawn a, Pawn b) + { + int num = (a.playerSettings != null) ? a.playerSettings.joinTick : 0; + int value = (b.playerSettings != null) ? b.playerSettings.joinTick : 0; + return num.CompareTo(value); + }); + } } + if (p.IsPrisonerOfColony && !this.prisonersOfColonySpawned.Contains(p)) + { + this.prisonersOfColonySpawned.Add(p); + } + this.DoListChangedNotifications(); } - if (p.IsPrisonerOfColony && !this.prisonersOfColonySpawned.Contains(p)) - { - this.prisonersOfColonySpawned.Add(p); - } - this.DoListChangedNotifications(); } public void DeRegisterPawn(Pawn p) @@ -439,27 +477,63 @@ public void LogListedPawns() StringBuilder stringBuilder = new StringBuilder(); stringBuilder.AppendLine("MapPawns:"); stringBuilder.AppendLine("pawnsSpawned"); - foreach (Pawn current in this.pawnsSpawned) + List.Enumerator enumerator = this.pawnsSpawned.GetEnumerator(); + try { - stringBuilder.AppendLine(" " + current.ToString()); + while (enumerator.MoveNext()) + { + Pawn current = enumerator.Current; + stringBuilder.AppendLine(" " + current.ToString()); + } + } + finally + { + ((IDisposable)(object)enumerator).Dispose(); } stringBuilder.AppendLine("AllPawnsUnspawned"); - foreach (Pawn current2 in this.AllPawnsUnspawned) + foreach (Pawn item in this.AllPawnsUnspawned) { - stringBuilder.AppendLine(" " + current2.ToString()); + stringBuilder.AppendLine(" " + item.ToString()); } - foreach (KeyValuePair> current3 in this.pawnsInFactionSpawned) + Dictionary>.Enumerator enumerator3 = this.pawnsInFactionSpawned.GetEnumerator(); + try { - stringBuilder.AppendLine("pawnsInFactionSpawned[" + current3.Key.ToString() + "]"); - foreach (Pawn current4 in current3.Value) + while (enumerator3.MoveNext()) { - stringBuilder.AppendLine(" " + current4.ToString()); + KeyValuePair> current3 = enumerator3.Current; + stringBuilder.AppendLine("pawnsInFactionSpawned[" + current3.Key.ToString() + "]"); + List.Enumerator enumerator4 = current3.Value.GetEnumerator(); + try + { + while (enumerator4.MoveNext()) + { + Pawn current4 = enumerator4.Current; + stringBuilder.AppendLine(" " + current4.ToString()); + } + } + finally + { + ((IDisposable)(object)enumerator4).Dispose(); + } } } + finally + { + ((IDisposable)(object)enumerator3).Dispose(); + } stringBuilder.AppendLine("prisonersOfColonySpawned"); - foreach (Pawn current5 in this.prisonersOfColonySpawned) + List.Enumerator enumerator5 = this.prisonersOfColonySpawned.GetEnumerator(); + try + { + while (enumerator5.MoveNext()) + { + Pawn current5 = enumerator5.Current; + stringBuilder.AppendLine(" " + current5.ToString()); + } + } + finally { - stringBuilder.AppendLine(" " + current5.ToString()); + ((IDisposable)(object)enumerator5).Dispose(); } Log.Message(stringBuilder.ToString()); } diff --git a/Assembly-CSharp/Verse/MapTemperature.cs b/Assembly-CSharp/Verse/MapTemperature.cs index fe4808780..020dddad9 100644 --- a/Assembly-CSharp/Verse/MapTemperature.cs +++ b/Assembly-CSharp/Verse/MapTemperature.cs @@ -2,6 +2,7 @@ using System; using System.Collections.Generic; using System.Text; +using UnityEngine; namespace Verse { @@ -72,12 +73,12 @@ public bool LocalSeasonsAreMeaningful() bool flag2 = false; for (int i = 0; i < 12; i++) { - float num = Find.World.tileTemperatures.AverageTemperatureForTwelfth(this.map.Tile, (Twelfth)i); - if (num > 0f) + float num = Find.World.tileTemperatures.AverageTemperatureForTwelfth(this.map.Tile, (Twelfth)(byte)i); + if (num > 0.0) { flag2 = true; } - if (num < 0f) + if (num < 0.0) { flag = true; } @@ -88,14 +89,24 @@ public bool LocalSeasonsAreMeaningful() public void DebugLogTemps() { StringBuilder stringBuilder = new StringBuilder(); - float num = (Find.VisibleMap == null) ? 0f : Find.WorldGrid.LongLatOf(Find.VisibleMap.Tile).y; - stringBuilder.AppendLine("Latitude " + num); + double num; + if (Find.VisibleMap != null) + { + Vector2 vector = Find.WorldGrid.LongLatOf(Find.VisibleMap.Tile); + num = vector.y; + } + else + { + num = 0.0; + } + float num2 = (float)num; + stringBuilder.AppendLine("Latitude " + num2); stringBuilder.AppendLine("-----Temperature for each hour this day------"); stringBuilder.AppendLine("Hour Temp SunEffect"); - int num2 = Find.TickManager.TicksAbs - Find.TickManager.TicksAbs % 60000; + int num3 = Find.TickManager.TicksAbs - Find.TickManager.TicksAbs % 60000; for (int i = 0; i < 24; i++) { - int absTick = num2 + i * 2500; + int absTick = num3 + i * 2500; stringBuilder.Append(i.ToString().PadRight(5)); stringBuilder.Append(Find.World.tileTemperatures.OutdoorTemperatureAt(this.map.Tile, absTick).ToString("F2").PadRight(8)); stringBuilder.Append(GenTemperature.OffsetFromSunCycle(absTick, this.map.Tile).ToString("F2")); @@ -105,18 +116,9 @@ public void DebugLogTemps() stringBuilder.AppendLine("-----Temperature for each twelfth this year------"); for (int j = 0; j < 12; j++) { - Twelfth twelfth = (Twelfth)j; - float num3 = Find.World.tileTemperatures.AverageTemperatureForTwelfth(this.map.Tile, twelfth); - stringBuilder.AppendLine(string.Concat(new object[] - { - twelfth.GetQuadrum(), - "/", - twelfth.GetSeason(num), - " - ", - twelfth.ToString(), - " ", - num3.ToString("F2") - })); + Twelfth twelfth = (Twelfth)(byte)j; + float num4 = Find.World.tileTemperatures.AverageTemperatureForTwelfth(this.map.Tile, twelfth); + stringBuilder.AppendLine(twelfth.GetQuadrum() + "/" + twelfth.GetSeason(num2) + " - " + ((Enum)(object)twelfth).ToString() + " " + num4.ToString("F2")); } stringBuilder.AppendLine(); stringBuilder.AppendLine("-----Temperature for each day this year------"); @@ -127,8 +129,8 @@ public void DebugLogTemps() stringBuilder.AppendLine("Day Lo Hi OffsetFromSeason RandomDailyVariation"); for (int k = 0; k < 60; k++) { - int absTick2 = (int)((float)(k * 60000) + 15000f); - int absTick3 = (int)((float)(k * 60000) + 45000f); + int absTick2 = (int)((float)(k * 60000) + 15000.0); + int absTick3 = (int)((float)(k * 60000) + 45000.0); stringBuilder.Append(k.ToString().PadRight(8)); stringBuilder.Append(Find.World.tileTemperatures.OutdoorTemperatureAt(this.map.Tile, absTick2).ToString("F2").PadRight(11)); stringBuilder.Append(Find.World.tileTemperatures.OutdoorTemperatureAt(this.map.Tile, absTick3).ToString("F2").PadRight(11)); diff --git a/Assembly-CSharp/Verse/MatBases.cs b/Assembly-CSharp/Verse/MatBases.cs index ab07f87a7..d94d5dd58 100644 --- a/Assembly-CSharp/Verse/MatBases.cs +++ b/Assembly-CSharp/Verse/MatBases.cs @@ -1,4 +1,3 @@ -using System; using UnityEngine; namespace Verse diff --git a/Assembly-CSharp/Verse/MatLoader.cs b/Assembly-CSharp/Verse/MatLoader.cs index f53f52d98..48f271fc1 100644 --- a/Assembly-CSharp/Verse/MatLoader.cs +++ b/Assembly-CSharp/Verse/MatLoader.cs @@ -1,4 +1,3 @@ -using System; using System.Collections.Generic; using UnityEngine; @@ -15,58 +14,55 @@ private struct Request public override int GetHashCode() { int seed = 0; - seed = Gen.HashCombine(seed, this.path); - return Gen.HashCombine(seed, this.renderQueue); + seed = Gen.HashCombine(seed, this.path); + return Gen.HashCombine(seed, this.renderQueue); } public override bool Equals(object obj) { - return obj is MatLoader.Request && this.Equals((MatLoader.Request)obj); + if (!(obj is Request)) + { + return false; + } + return this.Equals((Request)obj); } - public bool Equals(MatLoader.Request other) + public bool Equals(Request other) { return other.path == this.path && other.renderQueue == this.renderQueue; } public override string ToString() { - return string.Concat(new object[] - { - "MatLoader.Request(", - this.path, - ", ", - this.renderQueue, - ")" - }); + return "MatLoader.Request(" + this.path + ", " + this.renderQueue + ")"; } - public static bool operator ==(MatLoader.Request lhs, MatLoader.Request rhs) + public static bool operator ==(Request lhs, Request rhs) { return lhs.Equals(rhs); } - public static bool operator !=(MatLoader.Request lhs, MatLoader.Request rhs) + public static bool operator !=(Request lhs, Request rhs) { return !(lhs == rhs); } } - private static Dictionary dict = new Dictionary(); + private static Dictionary dict = new Dictionary(); public static Material LoadMat(string matPath, int renderQueue = -1) { Material material = (Material)Resources.Load("Materials/" + matPath, typeof(Material)); - if (material == null) + if ((Object)material == (Object)null) { Log.Warning("Could not load material " + matPath); } - MatLoader.Request key = new MatLoader.Request + Request key = new Request { path = matPath, renderQueue = renderQueue }; - Material material2; + Material material2 = default(Material); if (!MatLoader.dict.TryGetValue(key, out material2)) { material2 = new Material(material); diff --git a/Assembly-CSharp/Verse/MaterialAtlasPool.cs b/Assembly-CSharp/Verse/MaterialAtlasPool.cs index 4466d2b2e..0e09c4cec 100644 --- a/Assembly-CSharp/Verse/MaterialAtlasPool.cs +++ b/Assembly-CSharp/Verse/MaterialAtlasPool.cs @@ -1,4 +1,3 @@ -using System; using System.Collections.Generic; using UnityEngine; @@ -17,13 +16,15 @@ public MaterialAtlas(Material newRootMat) Vector2 mainTextureScale = new Vector2(0.1875f, 0.1875f); for (int i = 0; i < 16; i++) { - float x = (float)(i % 4) * 0.25f + 0.03125f; - float y = (float)(i / 4) * 0.25f + 0.03125f; + float x = (float)((float)(i % 4) * 0.25 + 0.03125); + float y = (float)((float)(i / 4) * 0.25 + 0.03125); Vector2 mainTextureOffset = new Vector2(x, y); - Material material = new Material(newRootMat); - material.name = newRootMat.name + "_ASM" + i; - material.mainTextureScale = mainTextureScale; - material.mainTextureOffset = mainTextureOffset; + Material material = new Material(newRootMat) + { + name = newRootMat.name + "_ASM" + i, + mainTextureScale = mainTextureScale, + mainTextureOffset = mainTextureOffset + }; this.subMats[i] = material; } } @@ -35,17 +36,17 @@ public Material SubMat(LinkDirections linkSet) Log.Warning("Cannot get submat of index " + (int)linkSet + ": out of range."); return BaseContent.BadMat; } - return this.subMats[(int)linkSet]; + return this.subMats[(uint)linkSet]; } } - private static Dictionary atlasDict = new Dictionary(); + private static Dictionary atlasDict = new Dictionary(); public static Material SubMaterialFromAtlas(Material mat, LinkDirections LinkSet) { if (!MaterialAtlasPool.atlasDict.ContainsKey(mat)) { - MaterialAtlasPool.atlasDict.Add(mat, new MaterialAtlasPool.MaterialAtlas(mat)); + MaterialAtlasPool.atlasDict.Add(mat, new MaterialAtlas(mat)); } return MaterialAtlasPool.atlasDict[mat].SubMat(LinkSet); } diff --git a/Assembly-CSharp/Verse/MaterialLoader.cs b/Assembly-CSharp/Verse/MaterialLoader.cs index f28ca06dd..0c9c1a4d8 100644 --- a/Assembly-CSharp/Verse/MaterialLoader.cs +++ b/Assembly-CSharp/Verse/MaterialLoader.cs @@ -11,15 +11,15 @@ public static List MatsFromTexturesInFolder(string dirPath) { string path = "Textures/" + dirPath; return (from Texture2D tex in Resources.LoadAll(path, typeof(Texture2D)) - select MaterialPool.MatFrom(tex)).ToList(); + select MaterialPool.MatFrom(tex)).ToList(); } public static Material MatWithEnding(string dirPath, string ending) { Material material = (from mat in MaterialLoader.MatsFromTexturesInFolder(dirPath) where mat.mainTexture.name.ToLower().EndsWith(ending) - select mat).FirstOrDefault(); - if (material == null) + select mat).FirstOrDefault(); + if ((UnityEngine.Object)material == (UnityEngine.Object)null) { Log.Warning("MatWithEnding: Dir " + dirPath + " lacks texture ending in " + ending); return BaseContent.BadMat; diff --git a/Assembly-CSharp/Verse/MaterialPool.cs b/Assembly-CSharp/Verse/MaterialPool.cs index fc4db19b0..c5ad12d65 100644 --- a/Assembly-CSharp/Verse/MaterialPool.cs +++ b/Assembly-CSharp/Verse/MaterialPool.cs @@ -1,4 +1,3 @@ -using System; using System.Collections.Generic; using UnityEngine; @@ -10,22 +9,22 @@ public static class MaterialPool public static Material MatFrom(string texPath, bool reportFailure) { - if (texPath == null || texPath == "null") + if (texPath != null && !(texPath == "null")) { - return null; + MaterialRequest req = new MaterialRequest(ContentFinder.Get(texPath, reportFailure)); + return MaterialPool.MatFrom(req); } - MaterialRequest req = new MaterialRequest(ContentFinder.Get(texPath, reportFailure)); - return MaterialPool.MatFrom(req); + return null; } public static Material MatFrom(string texPath) { - if (texPath == null || texPath == "null") + if (texPath != null && !(texPath == "null")) { - return null; + MaterialRequest req = new MaterialRequest(ContentFinder.Get(texPath, true)); + return MaterialPool.MatFrom(req); } - MaterialRequest req = new MaterialRequest(ContentFinder.Get(texPath, true)); - return MaterialPool.MatFrom(req); + return null; } public static Material MatFrom(Texture2D srcTex) @@ -83,29 +82,29 @@ public static Material MatFrom(MaterialRequest req) Log.Error("Tried to get a material from a different thread."); return null; } - if (req.mainTex == null) + if ((Object)req.mainTex == (Object)null) { Log.Error("MatFrom with null sourceTex."); return BaseContent.BadMat; } - if (req.shader == null) + if ((Object)req.shader == (Object)null) { Log.Warning("Matfrom with null shader."); return BaseContent.BadMat; } - if (req.maskTex != null && !req.shader.SupportsMaskTex()) + if ((Object)req.maskTex != (Object)null && !req.shader.SupportsMaskTex()) { Log.Error("MaterialRequest has maskTex but shader does not support it. req=" + req.ToString()); req.maskTex = null; } - Material material; + Material material = default(Material); if (!MaterialPool.matDictionary.TryGetValue(req, out material)) { material = new Material(req.shader); material.name = req.shader.name + "_" + req.mainTex.name; material.mainTexture = req.mainTex; material.color = req.color; - if (req.maskTex != null) + if ((Object)req.maskTex != (Object)null) { material.SetTexture(ShaderPropertyIDs.MaskTex, req.maskTex); material.SetColor(ShaderPropertyIDs.ColorTwo, req.colorTwo); @@ -119,7 +118,7 @@ public static Material MatFrom(MaterialRequest req) { Log.Error("MaterialRequest is not present in the dictionary even though we've just added it there. The equality operators are most likely defined incorrectly."); } - if (req.shader == ShaderDatabase.CutoutPlant) + if ((Object)req.shader == (Object)ShaderDatabase.CutoutPlant) { WindManager.Notify_PlantMaterialCreated(material); } diff --git a/Assembly-CSharp/Verse/MaterialRequest.cs b/Assembly-CSharp/Verse/MaterialRequest.cs index c11b51b0e..bae14b72c 100644 --- a/Assembly-CSharp/Verse/MaterialRequest.cs +++ b/Assembly-CSharp/Verse/MaterialRequest.cs @@ -58,42 +58,31 @@ public MaterialRequest(Texture2D tex, Shader shader, Color color) public override int GetHashCode() { int seed = 0; - seed = Gen.HashCombine(seed, this.shader); - seed = Gen.HashCombineStruct(seed, this.color); - seed = Gen.HashCombineStruct(seed, this.colorTwo); - seed = Gen.HashCombine(seed, this.mainTex); - seed = Gen.HashCombine(seed, this.maskTex); + seed = Gen.HashCombine(seed, this.shader); + seed = Gen.HashCombineStruct(seed, this.color); + seed = Gen.HashCombineStruct(seed, this.colorTwo); + seed = Gen.HashCombine(seed, this.mainTex); + seed = Gen.HashCombine(seed, this.maskTex); return Gen.HashCombineInt(seed, this.renderQueue); } public override bool Equals(object obj) { - return obj is MaterialRequest && this.Equals((MaterialRequest)obj); + if (!(obj is MaterialRequest)) + { + return false; + } + return this.Equals((MaterialRequest)obj); } public bool Equals(MaterialRequest other) { - return other.shader == this.shader && other.mainTex == this.mainTex && other.color == this.color && other.colorTwo == this.colorTwo && other.maskTex == this.maskTex && other.renderQueue == this.renderQueue; + return (UnityEngine.Object)other.shader == (UnityEngine.Object)this.shader && (UnityEngine.Object)other.mainTex == (UnityEngine.Object)this.mainTex && other.color == this.color && other.colorTwo == this.colorTwo && (UnityEngine.Object)other.maskTex == (UnityEngine.Object)this.maskTex && other.renderQueue == this.renderQueue; } public override string ToString() { - return string.Concat(new string[] - { - "MaterialRequest(", - this.shader.name, - ", ", - this.mainTex.name, - ", ", - this.color.ToString(), - ", ", - this.colorTwo.ToString(), - ", ", - this.maskTex.ToString(), - ", ", - this.renderQueue.ToString(), - ")" - }); + return "MaterialRequest(" + this.shader.name + ", " + this.mainTex.name + ", " + this.color.ToString() + ", " + this.colorTwo.ToString() + ", " + this.maskTex.ToString() + ", " + this.renderQueue.ToString() + ")"; } public static bool operator ==(MaterialRequest lhs, MaterialRequest rhs) diff --git a/Assembly-CSharp/Verse/MaterialUtility.cs b/Assembly-CSharp/Verse/MaterialUtility.cs index efc95f622..6894948c7 100644 --- a/Assembly-CSharp/Verse/MaterialUtility.cs +++ b/Assembly-CSharp/Verse/MaterialUtility.cs @@ -1,4 +1,3 @@ -using System; using UnityEngine; namespace Verse diff --git a/Assembly-CSharp/Verse/MatsFromSpectrum.cs b/Assembly-CSharp/Verse/MatsFromSpectrum.cs index 381d28991..4b45a3ee1 100644 --- a/Assembly-CSharp/Verse/MatsFromSpectrum.cs +++ b/Assembly-CSharp/Verse/MatsFromSpectrum.cs @@ -1,4 +1,3 @@ -using System; using UnityEngine; namespace Verse diff --git a/Assembly-CSharp/Verse/MentalBreakIntensity.cs b/Assembly-CSharp/Verse/MentalBreakIntensity.cs index fad744510..dbe2e9063 100644 --- a/Assembly-CSharp/Verse/MentalBreakIntensity.cs +++ b/Assembly-CSharp/Verse/MentalBreakIntensity.cs @@ -1,11 +1,9 @@ -using System; - namespace Verse { public enum MentalBreakIntensity : byte { - Extreme, - Major, - Minor + Extreme = 0, + Major = 1, + Minor = 2 } } diff --git a/Assembly-CSharp/Verse/MentalBreakWorker.cs b/Assembly-CSharp/Verse/MentalBreakWorker.cs index 4546f5da2..e90abdf31 100644 --- a/Assembly-CSharp/Verse/MentalBreakWorker.cs +++ b/Assembly-CSharp/Verse/MentalBreakWorker.cs @@ -1,5 +1,3 @@ -using System; - namespace Verse { public class MentalBreakWorker diff --git a/Assembly-CSharp/Verse/MentalBreakWorker_BingingDrug.cs b/Assembly-CSharp/Verse/MentalBreakWorker_BingingDrug.cs index 1f254e57b..edb66763e 100644 --- a/Assembly-CSharp/Verse/MentalBreakWorker_BingingDrug.cs +++ b/Assembly-CSharp/Verse/MentalBreakWorker_BingingDrug.cs @@ -1,5 +1,4 @@ using RimWorld; -using System; using System.Collections.Generic; namespace Verse @@ -9,15 +8,7 @@ public class MentalBreakWorker_BingingDrug : MentalBreakWorker public override float CommonalityFor(Pawn pawn) { int num = this.BingeableAddictionsCount(pawn); - float num2; - if (num == 0) - { - num2 = this.def.baseCommonality * 1f; - } - else - { - num2 = this.def.baseCommonality * 1.4f * (float)num; - } + float num2 = (float)((num != 0) ? (base.def.baseCommonality * 1.3999999761581421 * (float)num) : (base.def.baseCommonality * 1.0)); if (pawn.story != null) { Trait trait = pawn.story.traits.GetTrait(TraitDefOf.DrugDesire); @@ -25,11 +16,11 @@ public override float CommonalityFor(Pawn pawn) { if (trait.Degree == 1) { - num2 *= 2.5f; + num2 = (float)(num2 * 2.5); } else if (trait.Degree == 2) { - num2 *= 5f; + num2 = (float)(num2 * 5.0); } } } diff --git a/Assembly-CSharp/Verse/MentalBreaker.cs b/Assembly-CSharp/Verse/MentalBreaker.cs index 576a015c5..5c5d1ed31 100644 --- a/Assembly-CSharp/Verse/MentalBreaker.cs +++ b/Assembly-CSharp/Verse/MentalBreaker.cs @@ -45,7 +45,7 @@ public float BreakThresholdMajor { get { - return this.pawn.GetStatValue(StatDefOf.MentalBreakThreshold, true) + 0.15f; + return (float)(this.pawn.GetStatValue(StatDefOf.MentalBreakThreshold, true) + 0.15000000596046448); } } @@ -53,7 +53,7 @@ public float BreakThresholdMinor { get { - return this.pawn.GetStatValue(StatDefOf.MentalBreakThreshold, true) + 0.15f + 0.15f; + return (float)(this.pawn.GetStatValue(StatDefOf.MentalBreakThreshold, true) + 0.15000000596046448 + 0.15000000596046448); } } @@ -93,7 +93,7 @@ public bool BreakExtremeIsApproaching { get { - return this.pawn.MentalStateDef == null && !this.BreakExtremeIsImminent && this.CurMood < this.BreakThresholdExtreme + 0.1f; + return this.pawn.MentalStateDef == null && !this.BreakExtremeIsImminent && this.CurMood < this.BreakThresholdExtreme + 0.10000000149011612; } } @@ -113,11 +113,30 @@ private IEnumerable CurrentPossibleMoodBreaks { get { - MentalBreaker.<>c__Iterator1BD <>c__Iterator1BD = new MentalBreaker.<>c__Iterator1BD(); - <>c__Iterator1BD.<>f__this = this; - MentalBreaker.<>c__Iterator1BD expr_0E = <>c__Iterator1BD; - expr_0E.$PC = -2; - return expr_0E; + MentalBreakIntensity intensity = this.CurrentDesiredMoodBreakIntensity; + while (true) + { + IEnumerable breaks = from d in DefDatabase.AllDefsListForReading + where ((_003C_003Ec__Iterator1BD)/*Error near IL_003a: stateMachine*/)._003C_003Ef__this.BreakCanHappenNow(d, ((_003C_003Ec__Iterator1BD)/*Error near IL_003a: stateMachine*/)._003Cintensity_003E__0) + select d; + bool yieldedOne = false; + foreach (MentalBreakDef item in breaks) + { + yield return item; + yieldedOne = true; + } + if (!yieldedOne) + { + if (intensity != MentalBreakIntensity.Minor) + { + intensity--; + continue; + } + break; + } + yield break; + } + Log.ErrorOnce("No mental breaks possible for " + this.pawn, 888112); } } @@ -166,12 +185,8 @@ public void ExposeData() public void MentalStateStarterTick() { - if (this.CanDoRandomMentalBreaks && this.pawn.MentalStateDef == null && this.pawn.IsHashIntervalTick(150)) + if (this.CanDoRandomMentalBreaks && this.pawn.MentalStateDef == null && this.pawn.IsHashIntervalTick(150) && DebugSettings.enableRandomMentalStates) { - if (!DebugSettings.enableRandomMentalStates) - { - return; - } if (this.CurMood < this.BreakThresholdExtreme) { this.ticksBelowExtreme += 150; @@ -197,9 +212,7 @@ public void MentalStateStarterTick() this.ticksBelowMinor = 0; } if (this.TestMoodMentalBreak() && this.TryDoRandomMoodCausedMentalBreak()) - { return; - } if (this.pawn.story != null) { List allTraits = this.pawn.story.traits.allTraits; @@ -209,10 +222,8 @@ public void MentalStateStarterTick() if (currentData.randomMentalState != null) { float mtb = currentData.randomMentalStateMtbDaysMoodCurve.Evaluate(this.CurMood); - if (Rand.MTBEventOccurs(mtb, 60000f, 150f) && currentData.randomMentalState.Worker.StateCanOccur(this.pawn) && this.pawn.mindState.mentalStateHandler.TryStartMentalState(currentData.randomMentalState, null, false, false, null)) - { - return; - } + if (Rand.MTBEventOccurs(mtb, 60000f, 150f) && currentData.randomMentalState.Worker.StateCanOccur(this.pawn) && this.pawn.mindState.mentalStateHandler.TryStartMentalState(currentData.randomMentalState, (string)null, false, false, null)) + break; } } } @@ -229,28 +240,32 @@ private bool TestMoodMentalBreak() { return Rand.MTBEventOccurs(3f, 60000f, 150f); } - return this.ticksBelowMinor > 1500 && Rand.MTBEventOccurs(10f, 60000f, 150f); + if (this.ticksBelowMinor > 1500) + { + return Rand.MTBEventOccurs(10f, 60000f, 150f); + } + return false; } public bool TryDoRandomMoodCausedMentalBreak() { - if (!this.CanDoRandomMentalBreaks || this.pawn.Downed || !this.pawn.Awake()) + if (this.CanDoRandomMentalBreaks && !this.pawn.Downed && this.pawn.Awake()) { - return false; - } - if (this.pawn.Faction != Faction.OfPlayer && this.CurrentDesiredMoodBreakIntensity != MentalBreakIntensity.Extreme) - { - return false; - } - MentalBreakDef mentalBreakDef; - if (!this.CurrentPossibleMoodBreaks.TryRandomElementByWeight((MentalBreakDef d) => d.Worker.CommonalityFor(this.pawn), out mentalBreakDef)) - { - return false; + if (((this.pawn.Faction != Faction.OfPlayer) ? this.CurrentDesiredMoodBreakIntensity : MentalBreakIntensity.Extreme) != 0) + { + return false; + } + MentalBreakDef mentalBreakDef = default(MentalBreakDef); + if (!this.CurrentPossibleMoodBreaks.TryRandomElementByWeight((Func)((MentalBreakDef d) => d.Worker.CommonalityFor(this.pawn)), out mentalBreakDef)) + { + return false; + } + Thought thought = this.RandomFinalStraw(); + string reason = (thought == null) ? null : thought.LabelCap; + this.pawn.mindState.mentalStateHandler.TryStartMentalState(mentalBreakDef.mentalState, reason, false, true, null); + return true; } - Thought thought = this.RandomFinalStraw(); - string reason = (thought == null) ? null : thought.LabelCap; - this.pawn.mindState.mentalStateHandler.TryStartMentalState(mentalBreakDef.mentalState, reason, false, true, null); - return true; + return false; } private Thought RandomFinalStraw() @@ -265,11 +280,11 @@ private Thought RandomFinalStraw() num = num2; } } - float maxMoodOffset = num * 0.5f; + float maxMoodOffset = (float)(num * 0.5); Thought result = null; (from x in MentalBreaker.tmpThoughts where x.MoodOffset() <= maxMoodOffset - select x).TryRandomElementByWeight((Thought x) => -x.MoodOffset(), out result); + select x).TryRandomElementByWeight((Func)((Thought x) => (float)(0.0 - x.MoodOffset())), out result); MentalBreaker.tmpThoughts.Clear(); return result; } @@ -284,7 +299,7 @@ private bool BreakCanHappenNow(MentalBreakDef def, MentalBreakIntensity intensit { return false; } - if (this.pawn.story.traits.allTraits.Any((Trait tr) => tr.CurrentData.disallowedMentalStates != null && tr.CurrentData.disallowedMentalStates.Contains(def.mentalState))) + if (this.pawn.story.traits.allTraits.Any((Predicate)((Trait tr) => tr.CurrentData.disallowedMentalStates != null && tr.CurrentData.disallowedMentalStates.Contains(def.mentalState)))) { return false; } @@ -295,7 +310,11 @@ private bool BreakCanHappenNow(MentalBreakDef def, MentalBreakIntensity intensit IEnumerable source = from bd in this.pawn.story.traits.AllowedMentalBreaks where bd.mentalState.Worker.StateCanOccur(this.pawn) select bd; - return this.pawn.story == null || !source.Any((MentalBreakDef b) => b.intensity == def.intensity) || source.Any((MentalBreakDef b) => b == def); + if (this.pawn.story != null && source.Any((Func)((MentalBreakDef b) => b.intensity == def.intensity)) && !source.Any((Func)((MentalBreakDef b) => b == def))) + { + return false; + } + return true; } public float MentalBreakThresholdFor(MentalBreakIntensity intensity) @@ -303,53 +322,37 @@ public float MentalBreakThresholdFor(MentalBreakIntensity intensity) switch (intensity) { case MentalBreakIntensity.Extreme: + { return this.BreakThresholdExtreme; + } case MentalBreakIntensity.Major: + { return this.BreakThresholdMajor; + } case MentalBreakIntensity.Minor: + { return this.BreakThresholdMinor; + } default: + { throw new NotImplementedException(); } + } } internal string DebugString() { StringBuilder stringBuilder = new StringBuilder(); stringBuilder.AppendLine(this.pawn.ToString()); - stringBuilder.AppendLine(string.Concat(new object[] - { - " ticksBelowExtreme=", - this.ticksBelowExtreme, - "/", - 1500 - })); - stringBuilder.AppendLine(string.Concat(new object[] - { - " ticksBelowSerious=", - this.ticksBelowMajor, - "/", - 1500 - })); - stringBuilder.AppendLine(string.Concat(new object[] - { - " ticksBelowMinor=", - this.ticksBelowMinor, - "/", - 1500 - })); + stringBuilder.AppendLine(" ticksBelowExtreme=" + this.ticksBelowExtreme + "/" + 1500); + stringBuilder.AppendLine(" ticksBelowSerious=" + this.ticksBelowMajor + "/" + 1500); + stringBuilder.AppendLine(" ticksBelowMinor=" + this.ticksBelowMinor + "/" + 1500); float num = (from d in this.CurrentPossibleMoodBreaks select d.Worker.CommonalityFor(this.pawn)).Sum(); - foreach (MentalBreakDef current in this.CurrentPossibleMoodBreaks) + foreach (MentalBreakDef currentPossibleMoodBreak in this.CurrentPossibleMoodBreaks) { - float num2 = current.Worker.CommonalityFor(this.pawn); - stringBuilder.AppendLine(string.Concat(new object[] - { - " ", - current, - " ", - (num2 / num).ToStringPercent("F4") - })); + float num2 = currentPossibleMoodBreak.Worker.CommonalityFor(this.pawn); + stringBuilder.AppendLine(" " + currentPossibleMoodBreak + " " + (num2 / num).ToStringPercent("F4")); } return stringBuilder.ToString(); } @@ -359,9 +362,9 @@ internal void LogPossibleMentalBreaks() StringBuilder stringBuilder = new StringBuilder(); stringBuilder.AppendLine(this.pawn + " current possible mood mental breaks:"); stringBuilder.AppendLine("CurrentDesiredMoodBreakIntensity: " + this.CurrentDesiredMoodBreakIntensity); - foreach (MentalBreakDef current in this.CurrentPossibleMoodBreaks) + foreach (MentalBreakDef currentPossibleMoodBreak in this.CurrentPossibleMoodBreaks) { - stringBuilder.AppendLine(" " + current); + stringBuilder.AppendLine(" " + currentPossibleMoodBreak); } Log.Message(stringBuilder.ToString()); } diff --git a/Assembly-CSharp/Verse/MentalStateCategory.cs b/Assembly-CSharp/Verse/MentalStateCategory.cs index af0378902..e57fbc55e 100644 --- a/Assembly-CSharp/Verse/MentalStateCategory.cs +++ b/Assembly-CSharp/Verse/MentalStateCategory.cs @@ -1,14 +1,12 @@ -using System; - namespace Verse { public enum MentalStateCategory { - Undefined, - Aggro, - Sad, - Panic, - Indulgent, - Misc + Undefined = 0, + Aggro = 1, + Sad = 2, + Panic = 3, + Indulgent = 4, + Misc = 5 } } diff --git a/Assembly-CSharp/Verse/MentalStateDef.cs b/Assembly-CSharp/Verse/MentalStateDef.cs index e9e0733de..4ddf56bad 100644 --- a/Assembly-CSharp/Verse/MentalStateDef.cs +++ b/Assembly-CSharp/Verse/MentalStateDef.cs @@ -1,7 +1,6 @@ using RimWorld; using System; using System.Collections.Generic; -using System.Diagnostics; using UnityEngine; using Verse.AI; @@ -107,14 +106,16 @@ public override void ResolveReferences() } } - [DebuggerHidden] public override IEnumerable ConfigErrors() { - MentalStateDef.c__Iterator1D3 c__Iterator1D = new MentalStateDef.c__Iterator1D3(); - c__Iterator1D.<>f__this = this; - MentalStateDef.c__Iterator1D3 expr_0E = c__Iterator1D; - expr_0E.$PC = -2; - return expr_0E; + foreach (string item in base.ConfigErrors()) + { + yield return item; + } + if (!this.beginLetter.NullOrEmpty() && this.beginLetterLabel.NullOrEmpty()) + { + yield return "no beginLetter or beginLetterLabel"; + } } } } diff --git a/Assembly-CSharp/Verse/MentalStateGiver.cs b/Assembly-CSharp/Verse/MentalStateGiver.cs index b499d4a1c..ebfd96fdc 100644 --- a/Assembly-CSharp/Verse/MentalStateGiver.cs +++ b/Assembly-CSharp/Verse/MentalStateGiver.cs @@ -1,5 +1,3 @@ -using System; - namespace Verse { public class MentalStateGiver diff --git a/Assembly-CSharp/Verse/MentalStateWorker.cs b/Assembly-CSharp/Verse/MentalStateWorker.cs index 1702205c0..5a3804ad4 100644 --- a/Assembly-CSharp/Verse/MentalStateWorker.cs +++ b/Assembly-CSharp/Verse/MentalStateWorker.cs @@ -1,5 +1,4 @@ using RimWorld; -using System; namespace Verse { @@ -9,7 +8,19 @@ public class MentalStateWorker public virtual bool StateCanOccur(Pawn pawn) { - return (this.def.unspawnedCanDo || pawn.Spawned) && (this.def.prisonersCanDo || pawn.HostFaction == null) && (!this.def.colonistsOnly || pawn.Faction == Faction.OfPlayer); + if (!this.def.unspawnedCanDo && !pawn.Spawned) + { + return false; + } + if (!this.def.prisonersCanDo && pawn.HostFaction != null) + { + return false; + } + if (this.def.colonistsOnly && pawn.Faction != Faction.OfPlayer) + { + return false; + } + return true; } } } diff --git a/Assembly-CSharp/Verse/MentalStateWorker_BingingDrug.cs b/Assembly-CSharp/Verse/MentalStateWorker_BingingDrug.cs index 1a86fbf4c..e7921cc78 100644 --- a/Assembly-CSharp/Verse/MentalStateWorker_BingingDrug.cs +++ b/Assembly-CSharp/Verse/MentalStateWorker_BingingDrug.cs @@ -1,5 +1,4 @@ using RimWorld; -using System; using System.Collections.Generic; namespace Verse @@ -19,11 +18,11 @@ public override bool StateCanOccur(Pawn pawn) List allDefsListForReading = DefDatabase.AllDefsListForReading; for (int i = 0; i < allDefsListForReading.Count; i++) { - if (AddictionUtility.CanBingeOnNow(pawn, allDefsListForReading[i], this.def.drugCategory)) + if (AddictionUtility.CanBingeOnNow(pawn, allDefsListForReading[i], base.def.drugCategory)) { return true; } - if (this.def.drugCategory == DrugCategory.Hard && AddictionUtility.CanBingeOnNow(pawn, allDefsListForReading[i], DrugCategory.Social)) + if (base.def.drugCategory == DrugCategory.Hard && AddictionUtility.CanBingeOnNow(pawn, allDefsListForReading[i], DrugCategory.Social)) { return true; } diff --git a/Assembly-CSharp/Verse/MentalStateWorker_BingingFood.cs b/Assembly-CSharp/Verse/MentalStateWorker_BingingFood.cs index 2aac6d89f..ab7f24293 100644 --- a/Assembly-CSharp/Verse/MentalStateWorker_BingingFood.cs +++ b/Assembly-CSharp/Verse/MentalStateWorker_BingingFood.cs @@ -1,12 +1,18 @@ -using System; - namespace Verse { public class MentalStateWorker_BingingFood : MentalStateWorker { public override bool StateCanOccur(Pawn pawn) { - return base.StateCanOccur(pawn) && (!pawn.Spawned || pawn.Map.resourceCounter.TotalHumanEdibleNutrition > 10f); + if (!base.StateCanOccur(pawn)) + { + return false; + } + if (!pawn.Spawned) + { + return true; + } + return pawn.Map.resourceCounter.TotalHumanEdibleNutrition > 10.0; } } } diff --git a/Assembly-CSharp/Verse/MentalStateWorker_WanderOwnRoom.cs b/Assembly-CSharp/Verse/MentalStateWorker_WanderOwnRoom.cs index 6f895a377..ae6f5574a 100644 --- a/Assembly-CSharp/Verse/MentalStateWorker_WanderOwnRoom.cs +++ b/Assembly-CSharp/Verse/MentalStateWorker_WanderOwnRoom.cs @@ -1,5 +1,4 @@ using RimWorld; -using System; namespace Verse { @@ -12,7 +11,11 @@ public override bool StateCanOccur(Pawn pawn) return false; } Building_Bed ownedBed = pawn.ownership.OwnedBed; - return ownedBed != null && ownedBed.GetRoom(RegionType.Set_Passable) != null && !ownedBed.GetRoom(RegionType.Set_Passable).PsychologicallyOutdoors; + if (ownedBed != null && ownedBed.GetRoom(RegionType.Set_Passable) != null && !ownedBed.GetRoom(RegionType.Set_Passable).PsychologicallyOutdoors) + { + return true; + } + return false; } } } diff --git a/Assembly-CSharp/Verse/MenuOptionPriority.cs b/Assembly-CSharp/Verse/MenuOptionPriority.cs index dd020e12c..1ac7bd6ee 100644 --- a/Assembly-CSharp/Verse/MenuOptionPriority.cs +++ b/Assembly-CSharp/Verse/MenuOptionPriority.cs @@ -1,17 +1,15 @@ -using System; - namespace Verse { public enum MenuOptionPriority : byte { - DisabledOption, - VeryLow, - Low, - GoHere, - Default, - High, - AttackEnemy, - InitiateSocial, - RescueOrCapture + DisabledOption = 0, + VeryLow = 1, + Low = 2, + GoHere = 3, + Default = 4, + High = 5, + AttackEnemy = 6, + InitiateSocial = 7, + RescueOrCapture = 8 } } diff --git a/Assembly-CSharp/Verse/MeshMakerCircles.cs b/Assembly-CSharp/Verse/MeshMakerCircles.cs index 4e9b13658..2ee9b652c 100644 --- a/Assembly-CSharp/Verse/MeshMakerCircles.cs +++ b/Assembly-CSharp/Verse/MeshMakerCircles.cs @@ -10,19 +10,23 @@ public static Mesh MakePieMesh(int DegreesWide) { List list = new List(); list.Add(new Vector2(0f, 0f)); - for (int i = 0; i < DegreesWide; i++) + for (int num = 0; num < DegreesWide; num++) { - float num = (float)i / 180f * 3.14159274f; + float num2 = (float)((float)num / 180.0 * 3.1415927410125732); list.Add(new Vector2(0f, 0f) { - x = (float)(0.550000011920929 * Math.Cos((double)num)), - y = (float)(0.550000011920929 * Math.Sin((double)num)) + x = (float)(0.550000011920929 * Math.Cos((double)num2)), + y = (float)(0.550000011920929 * Math.Sin((double)num2)) }); } Vector3[] array = new Vector3[list.Count]; - for (int j = 0; j < array.Length; j++) + for (int i = 0; i < array.Length; i++) { - array[j] = new Vector3(list[j].x, 0f, list[j].y); + ref Vector3 val = ref array[i]; + Vector2 vector = list[i]; + float x = vector.x; + Vector2 vector2 = list[i]; + val = new Vector3(x, 0f, vector2.y); } Triangulator triangulator = new Triangulator(list.ToArray()); int[] triangles = triangulator.Triangulate(); @@ -40,30 +44,33 @@ public static Mesh MakeCircleMesh(float radius) { List list = new List(); list.Add(new Vector2(0f, 0f)); - for (int i = 0; i <= 360; i += 4) + for (int num = 0; num <= 360; num += 4) { - float f = (float)i / 180f * 3.14159274f; + float f = (float)((float)num / 180.0 * 3.1415927410125732); list.Add(new Vector2(radius * Mathf.Cos(f), radius * Mathf.Sin(f))); } Vector3[] array = new Vector3[list.Count]; - for (int j = 0; j < array.Length; j++) + for (int i = 0; i < array.Length; i++) { - array[j] = new Vector3(list[j].x, 0f, list[j].y); + ref Vector3 val = ref array[i]; + Vector2 vector = list[i]; + float x = vector.x; + Vector2 vector2 = list[i]; + val = new Vector3(x, 0f, vector2.y); } int[] array2 = new int[(array.Length - 1) * 3]; - for (int k = 1; k < array.Length; k++) + for (int j = 1; j < array.Length; j++) { - int num = (k - 1) * 3; - array2[num] = 0; - array2[num + 1] = (k + 1) % array.Length; - array2[num + 2] = k; + int num2 = (j - 1) * 3; + array2[num2] = 0; + array2[num2 + 1] = (j + 1) % array.Length; + array2[num2 + 2] = j; } - return new Mesh - { - name = "MakeCircleMesh()", - vertices = array, - triangles = array2 - }; + Mesh mesh = new Mesh(); + mesh.name = "MakeCircleMesh()"; + mesh.vertices = array; + mesh.triangles = array2; + return mesh; } } } diff --git a/Assembly-CSharp/Verse/MeshMakerPlanes.cs b/Assembly-CSharp/Verse/MeshMakerPlanes.cs index 532ad25ba..0d10c5daf 100644 --- a/Assembly-CSharp/Verse/MeshMakerPlanes.cs +++ b/Assembly-CSharp/Verse/MeshMakerPlanes.cs @@ -1,4 +1,3 @@ -using System; using UnityEngine; namespace Verse @@ -34,10 +33,10 @@ public static Mesh NewPlaneMesh(Vector2 size, bool flipped, bool backLift, bool Vector3[] array = new Vector3[4]; Vector2[] array2 = new Vector2[4]; int[] array3 = new int[6]; - array[0] = new Vector3(-0.5f * size.x, 0f, -0.5f * size.y); - array[1] = new Vector3(-0.5f * size.x, 0f, 0.5f * size.y); - array[2] = new Vector3(0.5f * size.x, 0f, 0.5f * size.y); - array[3] = new Vector3(0.5f * size.x, 0f, -0.5f * size.y); + array[0] = new Vector3((float)(-0.5 * size.x), 0f, (float)(-0.5 * size.y)); + array[1] = new Vector3((float)(-0.5 * size.x), 0f, (float)(0.5 * size.y)); + array[2] = new Vector3((float)(0.5 * size.x), 0f, (float)(0.5 * size.y)); + array[3] = new Vector3((float)(0.5 * size.x), 0f, (float)(-0.5 * size.y)); if (backLift) { array[1].y = 0.00234375f; diff --git a/Assembly-CSharp/Verse/MeshMakerShadows.cs b/Assembly-CSharp/Verse/MeshMakerShadows.cs index b009be078..e720ef428 100644 --- a/Assembly-CSharp/Verse/MeshMakerShadows.cs +++ b/Assembly-CSharp/Verse/MeshMakerShadows.cs @@ -1,4 +1,3 @@ -using System; using System.Collections.Generic; using UnityEngine; @@ -12,20 +11,20 @@ internal static class MeshMakerShadows private static List trianglesList = new List(); - private static readonly Color32 LowVertexColor = new Color32(0, 0, 0, 0); + private static readonly Color32 LowVertexColor = new Color32((byte)0, (byte)0, (byte)0, (byte)0); public static Mesh NewShadowMesh(float baseWidth, float baseHeight, float tallness) { - Color32 item = new Color32(255, 0, 0, (byte)(255f * tallness)); - float num = baseWidth / 2f; - float num2 = baseHeight / 2f; + Color32 item = new Color32((byte)255, (byte)0, (byte)0, (byte)(255.0 * tallness)); + float num = (float)(baseWidth / 2.0); + float num2 = (float)(baseHeight / 2.0); MeshMakerShadows.vertsList.Clear(); MeshMakerShadows.colorsList.Clear(); MeshMakerShadows.trianglesList.Clear(); - MeshMakerShadows.vertsList.Add(new Vector3(-num, 0f, -num2)); - MeshMakerShadows.vertsList.Add(new Vector3(-num, 0f, num2)); + MeshMakerShadows.vertsList.Add(new Vector3((float)(0.0 - num), 0f, (float)(0.0 - num2))); + MeshMakerShadows.vertsList.Add(new Vector3((float)(0.0 - num), 0f, num2)); MeshMakerShadows.vertsList.Add(new Vector3(num, 0f, num2)); - MeshMakerShadows.vertsList.Add(new Vector3(num, 0f, -num2)); + MeshMakerShadows.vertsList.Add(new Vector3(num, 0f, (float)(0.0 - num2))); MeshMakerShadows.colorsList.Add(MeshMakerShadows.LowVertexColor); MeshMakerShadows.colorsList.Add(MeshMakerShadows.LowVertexColor); MeshMakerShadows.colorsList.Add(MeshMakerShadows.LowVertexColor); @@ -37,9 +36,9 @@ public static Mesh NewShadowMesh(float baseWidth, float baseHeight, float tallne MeshMakerShadows.trianglesList.Add(2); MeshMakerShadows.trianglesList.Add(3); int count = MeshMakerShadows.vertsList.Count; - MeshMakerShadows.vertsList.Add(new Vector3(-num, 0f, -num2)); + MeshMakerShadows.vertsList.Add(new Vector3((float)(0.0 - num), 0f, (float)(0.0 - num2))); MeshMakerShadows.colorsList.Add(item); - MeshMakerShadows.vertsList.Add(new Vector3(-num, 0f, num2)); + MeshMakerShadows.vertsList.Add(new Vector3((float)(0.0 - num), 0f, num2)); MeshMakerShadows.colorsList.Add(item); MeshMakerShadows.trianglesList.Add(0); MeshMakerShadows.trianglesList.Add(count); @@ -50,7 +49,7 @@ public static Mesh NewShadowMesh(float baseWidth, float baseHeight, float tallne int count2 = MeshMakerShadows.vertsList.Count; MeshMakerShadows.vertsList.Add(new Vector3(num, 0f, num2)); MeshMakerShadows.colorsList.Add(item); - MeshMakerShadows.vertsList.Add(new Vector3(num, 0f, -num2)); + MeshMakerShadows.vertsList.Add(new Vector3(num, 0f, (float)(0.0 - num2))); MeshMakerShadows.colorsList.Add(item); MeshMakerShadows.trianglesList.Add(2); MeshMakerShadows.trianglesList.Add(count2); @@ -59,9 +58,9 @@ public static Mesh NewShadowMesh(float baseWidth, float baseHeight, float tallne MeshMakerShadows.trianglesList.Add(3); MeshMakerShadows.trianglesList.Add(2); int count3 = MeshMakerShadows.vertsList.Count; - MeshMakerShadows.vertsList.Add(new Vector3(-num, 0f, -num2)); + MeshMakerShadows.vertsList.Add(new Vector3((float)(0.0 - num), 0f, (float)(0.0 - num2))); MeshMakerShadows.colorsList.Add(item); - MeshMakerShadows.vertsList.Add(new Vector3(num, 0f, -num2)); + MeshMakerShadows.vertsList.Add(new Vector3(num, 0f, (float)(0.0 - num2))); MeshMakerShadows.colorsList.Add(item); MeshMakerShadows.trianglesList.Add(0); MeshMakerShadows.trianglesList.Add(3); @@ -69,13 +68,12 @@ public static Mesh NewShadowMesh(float baseWidth, float baseHeight, float tallne MeshMakerShadows.trianglesList.Add(3); MeshMakerShadows.trianglesList.Add(count3 + 1); MeshMakerShadows.trianglesList.Add(count3); - return new Mesh - { - name = "NewShadowMesh()", - vertices = MeshMakerShadows.vertsList.ToArray(), - colors32 = MeshMakerShadows.colorsList.ToArray(), - triangles = MeshMakerShadows.trianglesList.ToArray() - }; + Mesh mesh = new Mesh(); + mesh.name = "NewShadowMesh()"; + mesh.vertices = MeshMakerShadows.vertsList.ToArray(); + mesh.colors32 = MeshMakerShadows.colorsList.ToArray(); + mesh.triangles = MeshMakerShadows.trianglesList.ToArray(); + return mesh; } } } diff --git a/Assembly-CSharp/Verse/MeshPool.cs b/Assembly-CSharp/Verse/MeshPool.cs index 6d4236f4a..d94a23dbc 100644 --- a/Assembly-CSharp/Verse/MeshPool.cs +++ b/Assembly-CSharp/Verse/MeshPool.cs @@ -1,4 +1,3 @@ -using System; using System.Collections.Generic; using System.Text; using UnityEngine; @@ -80,7 +79,7 @@ static MeshPool() public static Mesh GridPlane(Vector2 size) { - Mesh mesh; + Mesh mesh = default(Mesh); if (!MeshPool.planes.TryGetValue(size, out mesh)) { mesh = MeshMakerPlanes.NewPlaneMesh(size, false, false, false); @@ -91,7 +90,7 @@ public static Mesh GridPlane(Vector2 size) public static Mesh GridPlaneFlip(Vector2 size) { - Mesh mesh; + Mesh mesh = default(Mesh); if (!MeshPool.planesFlip.TryGetValue(size, out mesh)) { mesh = MeshMakerPlanes.NewPlaneMesh(size, true, false, false); @@ -102,7 +101,7 @@ public static Mesh GridPlaneFlip(Vector2 size) private static Vector2 RoundedToHundredths(this Vector2 v) { - return new Vector2((float)((int)(v.x * 100f)) / 100f, (float)((int)(v.y * 100f)) / 100f); + return new Vector2((float)((float)(int)(v.x * 100.0) / 100.0), (float)((float)(int)(v.y * 100.0) / 100.0)); } public static void LogStats() diff --git a/Assembly-CSharp/Verse/MessageSound.cs b/Assembly-CSharp/Verse/MessageSound.cs index 2b587b44a..28b932a92 100644 --- a/Assembly-CSharp/Verse/MessageSound.cs +++ b/Assembly-CSharp/Verse/MessageSound.cs @@ -1,14 +1,12 @@ -using System; - namespace Verse { public enum MessageSound : byte { - Silent, - Standard, - RejectInput, - Benefit, - Negative, - SeriousAlert + Silent = 0, + Standard = 1, + RejectInput = 2, + Benefit = 3, + Negative = 4, + SeriousAlert = 5 } } diff --git a/Assembly-CSharp/Verse/Messages.cs b/Assembly-CSharp/Verse/Messages.cs index 69f1b6249..9b50ac7da 100644 --- a/Assembly-CSharp/Verse/Messages.cs +++ b/Assembly-CSharp/Verse/Messages.cs @@ -44,7 +44,7 @@ protected float TimeLeft { get { - return 13f - this.Age; + return (float)(13.0 - this.Age); } } @@ -52,7 +52,7 @@ public bool Expired { get { - return this.TimeLeft <= 0f; + return this.TimeLeft <= 0.0; } } @@ -60,9 +60,9 @@ public float Alpha { get { - if (this.TimeLeft < 0.6f) + if (this.TimeLeft < 0.60000002384185791) { - return this.TimeLeft / 0.6f; + return (float)(this.TimeLeft / 0.60000002384185791); } return 1f; } @@ -74,7 +74,7 @@ public LiveMessage(string text) this.lookTarget = GlobalTargetInfo.Invalid; this.startingFrame = RealTime.frameCount; this.startingTime = RealTime.LastRealTime; - this.ID = Messages.LiveMessage.uniqueID++; + this.ID = LiveMessage.uniqueID++; } public LiveMessage(string text, GlobalTargetInfo lookTarget) : this(text) @@ -85,7 +85,7 @@ public LiveMessage(string text, GlobalTargetInfo lookTarget) : this(text) public Rect CalculateRect(float x, float y) { Text.Font = GameFont.Small; - if (this.cachedSize.x < 0f) + if (this.cachedSize.x < 0.0) { this.cachedSize = Text.CalcSize(this.text); } @@ -97,34 +97,34 @@ public Rect CalculateRect(float x, float y) public void Draw(int xOffset, int yOffset) { Rect rect = this.CalculateRect((float)xOffset, (float)yOffset); - Find.WindowStack.ImmediateWindow(Gen.HashCombineInt(this.ID, 45574281), rect, WindowLayer.Super, delegate + Find.WindowStack.ImmediateWindow(Gen.HashCombineInt(this.ID, 45574281), rect, WindowLayer.Super, (Action)delegate { Text.Font = GameFont.Small; Text.Anchor = TextAnchor.MiddleLeft; - Rect rect = rect.AtZero(); + Rect rect2 = rect.AtZero(); float alpha = this.Alpha; GUI.color = new Color(1f, 1f, 1f, alpha); if (Messages.ShouldDrawMessageBackground) { - GUI.color = new Color(0.15f, 0.15f, 0.15f, 0.8f * alpha); - GUI.DrawTexture(rect, BaseContent.WhiteTex); + GUI.color = new Color(0.15f, 0.15f, 0.15f, (float)(0.800000011920929 * alpha)); + GUI.DrawTexture(rect2, BaseContent.WhiteTex); GUI.color = new Color(1f, 1f, 1f, alpha); } if (this.lookTarget.IsValid) { - UIHighlighter.HighlightOpportunity(rect, "Messages"); - Widgets.DrawHighlightIfMouseover(rect); + UIHighlighter.HighlightOpportunity(rect2, "Messages"); + Widgets.DrawHighlightIfMouseover(rect2); } - Rect rect2 = new Rect(2f, 0f, rect.width - 2f, rect.height); - Widgets.Label(rect2, this.text); - if (Current.ProgramState == ProgramState.Playing && this.lookTarget.IsValid && Widgets.ButtonInvisible(rect, false)) + Rect rect3 = new Rect(2f, 0f, (float)(rect2.width - 2.0), rect2.height); + Widgets.Label(rect3, this.text); + if (Current.ProgramState == ProgramState.Playing && this.lookTarget.IsValid && Widgets.ButtonInvisible(rect2, false)) { CameraJumper.TryJumpAndSelect(this.lookTarget); PlayerKnowledgeDatabase.KnowledgeDemonstrated(ConceptDefOf.ClickingMessages, KnowledgeAmount.Total); } Text.Anchor = TextAnchor.UpperLeft; GUI.color = Color.white; - if (Mouse.IsOver(rect)) + if (Mouse.IsOver(rect2)) { Messages.mouseoverMessageIndex = Messages.liveMessages.IndexOf(this); } @@ -136,7 +136,7 @@ public void Draw(int xOffset, int yOffset) private const int MaxLiveMessages = 12; - private static List liveMessages = new List(); + private static List liveMessages = new List(); private static int mouseoverMessageIndex = -1; @@ -173,41 +173,41 @@ public static void Update() } } Messages.mouseoverMessageIndex = -1; - Messages.liveMessages.RemoveAll((Messages.LiveMessage m) => m.Expired); + Messages.liveMessages.RemoveAll((Predicate)((LiveMessage m) => m.Expired)); } public static void Message(string text, GlobalTargetInfo lookTarget, MessageSound sound) { - if (!Messages.AcceptsMessage(text, lookTarget)) + if (Messages.AcceptsMessage(text, lookTarget)) { - return; + LiveMessage msg = new LiveMessage(text, lookTarget); + Messages.Message(msg, sound); } - Messages.LiveMessage msg = new Messages.LiveMessage(text, lookTarget); - Messages.Message(msg, sound); } public static void Message(string text, MessageSound sound) { - if (!Messages.AcceptsMessage(text, TargetInfo.Invalid)) + if (Messages.AcceptsMessage(text, TargetInfo.Invalid)) { - return; + LiveMessage msg = new LiveMessage(text); + Messages.Message(msg, sound); } - Messages.LiveMessage msg = new Messages.LiveMessage(text); - Messages.Message(msg, sound); } public static void MessagesDoGUI() { Text.Font = GameFont.Small; - int xOffset = (int)Messages.MessagesTopLeftStandard.x; - int num = (int)Messages.MessagesTopLeftStandard.y; + Vector2 messagesTopLeftStandard = Messages.MessagesTopLeftStandard; + int xOffset = (int)messagesTopLeftStandard.x; + Vector2 messagesTopLeftStandard2 = Messages.MessagesTopLeftStandard; + int num = (int)messagesTopLeftStandard2.y; if (Current.Game != null && Find.ActiveLesson.ActiveLessonVisible) { num += (int)Find.ActiveLesson.Current.MessagesYOffset; } - for (int i = Messages.liveMessages.Count - 1; i >= 0; i--) + for (int num2 = Messages.liveMessages.Count - 1; num2 >= 0; num2--) { - Messages.liveMessages[i].Draw(xOffset, num); + Messages.liveMessages[num2].Draw(xOffset, num); num += 26; } } @@ -218,7 +218,7 @@ public static bool CollidesWithAnyMessage(Rect rect, out float messageAlpha) float num = 0f; for (int i = 0; i < Messages.liveMessages.Count; i++) { - Messages.LiveMessage liveMessage = Messages.liveMessages[i]; + LiveMessage liveMessage = Messages.liveMessages[i]; if (rect.Overlaps(liveMessage.lastDrawRect)) { result = true; @@ -258,34 +258,44 @@ private static bool AcceptsMessage(string text, GlobalTargetInfo lookTarget) return true; } - private static void Message(Messages.LiveMessage msg, MessageSound sound) + private static void Message(LiveMessage msg, MessageSound sound) { Messages.liveMessages.Add(msg); while (Messages.liveMessages.Count > 12) { Messages.liveMessages.RemoveAt(0); } - if (sound != MessageSound.Silent) + if (sound != 0) { SoundDef soundDef = null; switch (sound) { case MessageSound.Standard: + { soundDef = SoundDefOf.MessageAlert; break; + } case MessageSound.RejectInput: + { soundDef = SoundDefOf.ClickReject; break; + } case MessageSound.Benefit: + { soundDef = SoundDefOf.MessageBenefit; break; + } case MessageSound.Negative: + { soundDef = SoundDefOf.MessageAlertNegative; break; + } case MessageSound.SeriousAlert: + { soundDef = SoundDefOf.MessageSeriousAlert; break; } + } soundDef.PlayOneShotOnCamera(null); } } diff --git a/Assembly-CSharp/Verse/MessagesRepeatAvoider.cs b/Assembly-CSharp/Verse/MessagesRepeatAvoider.cs index b4372611f..bf10c0f56 100644 --- a/Assembly-CSharp/Verse/MessagesRepeatAvoider.cs +++ b/Assembly-CSharp/Verse/MessagesRepeatAvoider.cs @@ -1,4 +1,3 @@ -using System; using System.Collections.Generic; namespace Verse diff --git a/Assembly-CSharp/Verse/Mod.cs b/Assembly-CSharp/Verse/Mod.cs index dbf1f6436..fc8b97f26 100644 --- a/Assembly-CSharp/Verse/Mod.cs +++ b/Assembly-CSharp/Verse/Mod.cs @@ -1,4 +1,3 @@ -using System; using UnityEngine; namespace Verse @@ -27,15 +26,15 @@ public Mod(ModContentPack content) if (this.modSettings != null && this.modSettings.GetType() != typeof(T)) { Log.Error(string.Format("Mod {0} attempted to read two different settings classes (was {1}, is now {2})", this.Content.Name, this.modSettings.GetType(), typeof(T))); - return (T)((object)null); + return (T)null; } if (this.modSettings != null) { - return (T)((object)this.modSettings); + return (T)this.modSettings; } - this.modSettings = LoadedModManager.ReadModSettings(this.intContent.Identifier, base.GetType().Name); + this.modSettings = (ModSettings)(object)LoadedModManager.ReadModSettings(this.intContent.Identifier, base.GetType().Name); this.modSettings.Mod = this; - return this.modSettings as T; + return (T)(this.modSettings as T); } public virtual void WriteSettings() diff --git a/Assembly-CSharp/Verse/ModAssemblyHandler.cs b/Assembly-CSharp/Verse/ModAssemblyHandler.cs index 9753ff814..1e6afc8ee 100644 --- a/Assembly-CSharp/Verse/ModAssemblyHandler.cs +++ b/Assembly-CSharp/Verse/ModAssemblyHandler.cs @@ -23,7 +23,7 @@ public void ReloadAll() { if (!ModAssemblyHandler.globalResolverIsSet) { - ResolveEventHandler @object = (object obj, ResolveEventArgs args) => Assembly.GetExecutingAssembly(); + ResolveEventHandler @object = (ResolveEventHandler)((object obj, ResolveEventArgs args) => Assembly.GetExecutingAssembly()); AppDomain currentDomain = AppDomain.CurrentDomain; currentDomain.AssemblyResolve += new ResolveEventHandler(@object.Invoke); ModAssemblyHandler.globalResolverIsSet = true; @@ -31,40 +31,37 @@ public void ReloadAll() string path = Path.Combine(this.mod.RootDir, "Assemblies"); string path2 = Path.Combine(GenFilePaths.CoreModsFolderPath, path); DirectoryInfo directoryInfo = new DirectoryInfo(path2); - if (!directoryInfo.Exists) + if (directoryInfo.Exists) { - return; - } - FileInfo[] files = directoryInfo.GetFiles("*.*", SearchOption.AllDirectories); - for (int i = 0; i < files.Length; i++) - { - FileInfo fileInfo = files[i]; - if (!(fileInfo.Extension.ToLower() != ".dll")) + FileInfo[] files = directoryInfo.GetFiles("*.*", SearchOption.AllDirectories); + for (int i = 0; i < files.Length; i++) { - Assembly assembly = null; - try + FileInfo fileInfo = files[i]; + if (!(fileInfo.Extension.ToLower() != ".dll")) { - byte[] rawAssembly = File.ReadAllBytes(fileInfo.FullName); - string fileName = Path.Combine(fileInfo.DirectoryName, Path.GetFileNameWithoutExtension(fileInfo.FullName)) + ".pdb"; - FileInfo fileInfo2 = new FileInfo(fileName); - if (fileInfo2.Exists) + Assembly assembly = null; + try { - byte[] rawSymbolStore = File.ReadAllBytes(fileInfo2.FullName); - assembly = AppDomain.CurrentDomain.Load(rawAssembly, rawSymbolStore); + byte[] rawAssembly = File.ReadAllBytes(fileInfo.FullName); + string fileName = Path.Combine(fileInfo.DirectoryName, Path.GetFileNameWithoutExtension(fileInfo.FullName)) + ".pdb"; + FileInfo fileInfo2 = new FileInfo(fileName); + if (fileInfo2.Exists) + { + byte[] rawSymbolStore = File.ReadAllBytes(fileInfo2.FullName); + assembly = AppDomain.CurrentDomain.Load(rawAssembly, rawSymbolStore); + } + else + { + assembly = AppDomain.CurrentDomain.Load(rawAssembly); + } } - else + catch (Exception ex) { - assembly = AppDomain.CurrentDomain.Load(rawAssembly); + Log.Error("Exception loading " + fileInfo.Name + ": " + ex.ToString()); + return; + IL_0164:; } - } - catch (Exception ex) - { - Log.Error("Exception loading " + fileInfo.Name + ": " + ex.ToString()); - break; - } - if (assembly != null) - { - if (this.AssemblyIsUsable(assembly)) + if (assembly != null && this.AssemblyIsUsable(assembly)) { this.loadedAssemblies.Add(assembly); } @@ -82,13 +79,7 @@ private bool AssemblyIsUsable(Assembly asm) catch (ReflectionTypeLoadException ex) { StringBuilder stringBuilder = new StringBuilder(); - stringBuilder.AppendLine(string.Concat(new object[] - { - "ReflectionTypeLoadException getting types in assembly ", - asm.GetName().Name, - ": ", - ex - })); + stringBuilder.AppendLine("ReflectionTypeLoadException getting types in assembly " + asm.GetName().Name + ": " + ex); stringBuilder.AppendLine(); stringBuilder.AppendLine("Loader exceptions:"); if (ex.LoaderExceptions != null) @@ -101,20 +92,14 @@ private bool AssemblyIsUsable(Assembly asm) } } Log.Error(stringBuilder.ToString()); - bool result = false; - return result; + return false; + IL_00b3:; } catch (Exception ex3) { - Log.Error(string.Concat(new object[] - { - "Exception getting types in assembly ", - asm.GetName().Name, - ": ", - ex3 - })); - bool result = false; - return result; + Log.Error("Exception getting types in assembly " + asm.GetName().Name + ": " + ex3); + return false; + IL_00f5:; } return true; } diff --git a/Assembly-CSharp/Verse/ModContentHolder.cs b/Assembly-CSharp/Verse/ModContentHolder.cs index 9e32a8eb7..dde477dbd 100644 --- a/Assembly-CSharp/Verse/ModContentHolder.cs +++ b/Assembly-CSharp/Verse/ModContentHolder.cs @@ -1,6 +1,5 @@ using System; using System.Collections.Generic; -using System.Diagnostics; using UnityEngine; namespace Verse @@ -20,13 +19,22 @@ public void ClearDestroy() { if (typeof(UnityEngine.Object).IsAssignableFrom(typeof(T))) { - foreach (T current in this.contentList.Values) + Dictionary.ValueCollection.Enumerator enumerator = this.contentList.Values.GetEnumerator(); + try { - T localObj = current; - LongEventHandler.ExecuteWhenFinished(delegate + while (enumerator.MoveNext()) { - UnityEngine.Object.Destroy((UnityEngine.Object)((object)localObj)); - }); + T current = enumerator.Current; + T localObj = current; + LongEventHandler.ExecuteWhenFinished((Action)delegate + { + UnityEngine.Object.Destroy((UnityEngine.Object)(object)localObj); + }); + } + } + finally + { + ((IDisposable)(object)enumerator).Dispose(); } } this.contentList.Clear(); @@ -34,45 +42,47 @@ public void ClearDestroy() public void ReloadAll() { - foreach (LoadedContentItem current in ModContentLoader.LoadAllForMod(this.mod)) + foreach (LoadedContentItem item in ModContentLoader.LoadAllForMod(this.mod)) { - if (this.contentList.ContainsKey(current.internalPath)) + if (this.contentList.ContainsKey(item.internalPath)) { - Log.Warning(string.Concat(new object[] - { - "Tried to load duplicate ", - typeof(T), - " with path: ", - current.internalPath - })); + Log.Warning("Tried to load duplicate " + typeof(T) + " with path: " + item.internalPath); } else { - this.contentList.Add(current.internalPath, current.contentItem); + this.contentList.Add(item.internalPath, item.contentItem); } } } public T Get(string path) { - T result; + T result = default(T); if (this.contentList.TryGetValue(path, out result)) { return result; } - return (T)((object)null); + return (T)null; } - [DebuggerHidden] public IEnumerable GetAllUnderPath(string pathRoot) { - ModContentHolder.c__Iterator20F c__Iterator20F = new ModContentHolder.c__Iterator20F(); - c__Iterator20F.pathRoot = pathRoot; - c__Iterator20F.<$>pathRoot = pathRoot; - c__Iterator20F.<>f__this = this; - ModContentHolder.c__Iterator20F expr_1C = c__Iterator20F; - expr_1C.$PC = -2; - return expr_1C; + Dictionary.Enumerator enumerator = this.contentList.GetEnumerator(); + try + { + while (enumerator.MoveNext()) + { + KeyValuePair kvp = enumerator.Current; + if (kvp.Key.StartsWith(pathRoot)) + { + yield return kvp.Value; + } + } + } + finally + { + ((IDisposable)(object)enumerator).Dispose(); + } } } } diff --git a/Assembly-CSharp/Verse/ModContentLoader.cs b/Assembly-CSharp/Verse/ModContentLoader.cs index 363e3ad85..d61eb14a4 100644 --- a/Assembly-CSharp/Verse/ModContentLoader.cs +++ b/Assembly-CSharp/Verse/ModContentLoader.cs @@ -1,7 +1,6 @@ using RuntimeAudioClipLoader; using System; using System.Collections.Generic; -using System.Diagnostics; using System.IO; using UnityEngine; @@ -9,7 +8,7 @@ namespace Verse { public static class ModContentLoader where T : class { - private static string[] AcceptableExtensionsAudio = new string[] + private static string[] AcceptableExtensionsAudio = new string[7] { ".wav", ".mp3", @@ -20,13 +19,13 @@ public static class ModContentLoader where T : class ".s3m" }; - private static string[] AcceptableExtensionsTexture = new string[] + private static string[] AcceptableExtensionsTexture = new string[2] { ".png", ".jpg" }; - private static string[] AcceptableExtensionsString = new string[] + private static string[] AcceptableExtensionsString = new string[1] { ".txt" }; @@ -37,20 +36,21 @@ private static bool IsAcceptableExtension(string extension) if (typeof(T) == typeof(AudioClip)) { array = ModContentLoader.AcceptableExtensionsAudio; + goto IL_0087; } - else if (typeof(T) == typeof(Texture2D)) + if (typeof(T) == typeof(Texture2D)) { array = ModContentLoader.AcceptableExtensionsTexture; + goto IL_0087; } - else + if (typeof(T) == typeof(string)) { - if (typeof(T) != typeof(string)) - { - Log.Error("Unknown content type " + typeof(T)); - return false; - } array = ModContentLoader.AcceptableExtensionsString; + goto IL_0087; } + Log.Error("Unknown content type " + typeof(T)); + return false; + IL_0087: string[] array2 = array; for (int i = 0; i < array2.Length; i++) { @@ -63,15 +63,28 @@ private static bool IsAcceptableExtension(string extension) return false; } - [DebuggerHidden] public static IEnumerable> LoadAllForMod(ModContentPack mod) { - ModContentLoader.c__Iterator210 c__Iterator = new ModContentLoader.c__Iterator210(); - c__Iterator.mod = mod; - c__Iterator.<$>mod = mod; - ModContentLoader.c__Iterator210 expr_15 = c__Iterator; - expr_15.$PC = -2; - return expr_15; + string contentDirPath = Path.Combine(mod.RootDir, GenFilePaths.ContentPath()); + DirectoryInfo contentDir = new DirectoryInfo(contentDirPath); + if (contentDir.Exists) + { + DeepProfiler.Start("Loading assets of type " + typeof(T) + " for mod " + mod); + FileInfo[] files = contentDir.GetFiles("*.*", SearchOption.AllDirectories); + for (int i = 0; i < files.Length; i++) + { + FileInfo file = files[i]; + if (ModContentLoader.IsAcceptableExtension(file.Extension)) + { + LoadedContentItem loadedItem = ModContentLoader.LoadItem(file.FullName, contentDirPath); + if (loadedItem != null) + { + yield return loadedItem; + } + } + } + DeepProfiler.End(); + } } public static LoadedContentItem LoadItem(string absFilePath, string contentDirPath = null) @@ -87,13 +100,11 @@ public static LoadedContentItem LoadItem(string absFilePath, string contentDi { if (typeof(T) == typeof(string)) { - LoadedContentItem result = new LoadedContentItem(text, (T)((object)GenFile.TextFromRawFile(absFilePath))); - return result; + return new LoadedContentItem(text, (T)(object)GenFile.TextFromRawFile(absFilePath)); } if (typeof(T) == typeof(Texture2D)) { - LoadedContentItem result = new LoadedContentItem(text, (T)((object)ModContentLoader.LoadPNG(absFilePath))); - return result; + return new LoadedContentItem(text, (T)(object)ModContentLoader.LoadPNG(absFilePath)); } if (typeof(T) == typeof(AudioClip)) { @@ -101,11 +112,11 @@ public static LoadedContentItem LoadItem(string absFilePath, string contentDi { DeepProfiler.Start("Loading file " + text); } - T t; + T val = default(T); try { bool doStream = ModContentLoader.ShouldStreamAudioClipFromPath(absFilePath); - t = (T)((object)Manager.Load(absFilePath, doStream, true, true)); + val = (T)(object)Manager.Load(absFilePath, doStream, true, true); } finally { @@ -114,28 +125,17 @@ public static LoadedContentItem LoadItem(string absFilePath, string contentDi DeepProfiler.End(); } } - UnityEngine.Object @object = t as UnityEngine.Object; - if (@object != null) + UnityEngine.Object @object = ((object)val) as UnityEngine.Object; + if (@object != (UnityEngine.Object)null) { @object.name = Path.GetFileNameWithoutExtension(new FileInfo(absFilePath).Name); } - LoadedContentItem result = new LoadedContentItem(text, t); - return result; + return new LoadedContentItem(text, val); } } catch (Exception ex) { - Log.Error(string.Concat(new object[] - { - "Exception loading ", - typeof(T), - " from file.\nabsFilePath: ", - absFilePath, - "\ncontentDirPath: ", - contentDirPath, - "\nException: ", - ex.ToString() - })); + Log.Error("Exception loading " + typeof(T) + " from file.\nabsFilePath: " + absFilePath + "\ncontentDirPath: " + contentDirPath + "\nException: " + ex.ToString()); } if (typeof(T) == typeof(Texture2D)) { @@ -151,7 +151,7 @@ private static bool ShouldStreamAudioClipFromPath(string absPath) return false; } FileInfo fileInfo = new FileInfo(absPath); - return fileInfo.Length > 307200L; + return fileInfo.Length > 307200; } private static Texture2D LoadPNG(string filePath) diff --git a/Assembly-CSharp/Verse/ModContentPack.cs b/Assembly-CSharp/Verse/ModContentPack.cs index 136e2f876..74cda1384 100644 --- a/Assembly-CSharp/Verse/ModContentPack.cs +++ b/Assembly-CSharp/Verse/ModContentPack.cs @@ -73,7 +73,7 @@ public IEnumerable AllDefs { get { - return this.defPackages.SelectMany((DefPackage x) => x.defs); + return this.defPackages.SelectMany((Func>)((DefPackage x) => x.defs)); } } @@ -134,7 +134,7 @@ public ModContentHolder GetContentHolder() where T : class public void ReloadContent() { - LongEventHandler.ExecuteWhenFinished(delegate + LongEventHandler.ExecuteWhenFinished((Action)delegate { this.audioClips.ReloadAll(); this.textures.ReloadAll(); @@ -146,14 +146,23 @@ public void ReloadContent() public void LoadDefs(IEnumerable patches) { DeepProfiler.Start("Loading all defs"); - List list = DirectXmlLoader.XmlAssetsInModFolder(this, "Defs/").ToList(); - foreach (LoadableXmlAsset current in list) + List list = DirectXmlLoader.XmlAssetsInModFolder(this, "Defs/").ToList(); + List.Enumerator enumerator = list.GetEnumerator(); + try { - foreach (PatchOperation current2 in patches) + while (enumerator.MoveNext()) { - current2.Apply(current.xmlDoc); + LoadableXmlAsset current = enumerator.Current; + foreach (PatchOperation item in patches) + { + item.Apply(current.xmlDoc); + } } } + finally + { + ((IDisposable)(object)enumerator).Dispose(); + } for (int i = 0; i < list.Count; i++) { XmlInheritance.TryRegisterAllFrom(list[i], this); @@ -163,9 +172,9 @@ public void LoadDefs(IEnumerable patches) { string relFolder = GenFilePaths.FolderPathRelativeToDefsFolder(list[j].fullFolderPath, this); DefPackage defPackage = new DefPackage(list[j].name, relFolder); - foreach (Def current3 in DirectXmlLoader.AllDefsFromAsset(list[j])) + foreach (Def item2 in DirectXmlLoader.AllDefsFromAsset(list[j])) { - defPackage.defs.Add(current3); + defPackage.defs.Add(item2); } this.defPackages.Add(defPackage); } @@ -194,7 +203,7 @@ private void LoadPatches() { DeepProfiler.Start("Loading all patches"); this.patches = new List(); - List list = DirectXmlLoader.XmlAssetsInModFolder(this, "Patches/").ToList(); + List list = DirectXmlLoader.XmlAssetsInModFolder(this, "Patches/").ToList(); for (int i = 0; i < list.Count; i++) { XmlElement documentElement = list[i].xmlDoc.DocumentElement; diff --git a/Assembly-CSharp/Verse/ModLister.cs b/Assembly-CSharp/Verse/ModLister.cs index 132085b74..6cc2f27bc 100644 --- a/Assembly-CSharp/Verse/ModLister.cs +++ b/Assembly-CSharp/Verse/ModLister.cs @@ -43,31 +43,31 @@ internal static void RebuildModList() string s = "Rebuilding mods list"; ModLister.mods.Clear(); s += "\nAdding mods from mods folder:"; - foreach (string current in from d in new DirectoryInfo(GenFilePaths.CoreModsFolderPath).GetDirectories() + foreach (string item in from d in new DirectoryInfo(GenFilePaths.CoreModsFolderPath).GetDirectories() select d.FullName) { - ModMetaData modMetaData = new ModMetaData(current); + ModMetaData modMetaData = new ModMetaData(item); ModLister.mods.Add(modMetaData); s = s + "\n Adding " + modMetaData.ToStringLong(); } s += "\nAdding mods from Steam:"; - foreach (WorkshopItem current2 in from it in WorkshopItems.AllSubscribedItems + foreach (WorkshopItem item2 in from it in WorkshopItems.AllSubscribedItems where it is WorkshopItem_Mod select it) { - ModMetaData modMetaData2 = new ModMetaData(current2); + ModMetaData modMetaData2 = new ModMetaData(item2); ModLister.mods.Add(modMetaData2); s = s + "\n Adding " + modMetaData2.ToStringLong(); } s += "\nDeactivating not-installed mods:"; - ModsConfig.DeactivateNotInstalledMods(delegate(string log) + ModsConfig.DeactivateNotInstalledMods((Action)delegate(string log) { s = s + "\n " + log; }); - if (ModLister.mods.Count((ModMetaData m) => m.Active) == 0) + if (ModLister.mods.Count((Func)((ModMetaData m) => m.Active)) == 0) { s += "\nThere are no active mods. Activating Core mod."; - ModLister.mods.First((ModMetaData m) => m.IsCoreMod).Active = true; + ModLister.mods.First((Func)((ModMetaData m) => m.IsCoreMod)).Active = true; } if (Prefs.LogVerbose) { @@ -78,8 +78,8 @@ where it is WorkshopItem_Mod public static int InstalledModsListHash(bool activeOnly) { int num = 17; - List list = ModsConfig.ActiveModsInLoadOrder.ToList(); - for (int i = 0; i < list.Count(); i++) + List list = ModsConfig.ActiveModsInLoadOrder.ToList(); + for (int i = 0; i < list.Count(); i++) { if (!activeOnly || list[i].Active) { diff --git a/Assembly-CSharp/Verse/ModMetaData.cs b/Assembly-CSharp/Verse/ModMetaData.cs index e4a357250..f0d1f947c 100644 --- a/Assembly-CSharp/Verse/ModMetaData.cs +++ b/Assembly-CSharp/Verse/ModMetaData.cs @@ -34,7 +34,7 @@ private class ModMetaDataInternal public bool enabled = true; - private ModMetaData.ModMetaDataInternal meta = new ModMetaData.ModMetaDataInternal(); + private ModMetaDataInternal meta = new ModMetaDataInternal(); private WorkshopItemHook workshopHookInt; @@ -80,7 +80,15 @@ public bool VersionCompatible { get { - return this.IsCoreMod || (VersionControl.IsWellFormattedVersionString(this.TargetVersion) && VersionControl.MinorFromVersionString(this.TargetVersion) == VersionControl.CurrentMinor); + if (this.IsCoreMod) + { + return true; + } + if (!VersionControl.IsWellFormattedVersionString(this.TargetVersion)) + { + return false; + } + return VersionControl.MinorFromVersionString(this.TargetVersion) == VersionControl.CurrentMinor; } } @@ -132,14 +140,7 @@ public string PreviewImagePath { get { - return string.Concat(new object[] - { - this.rootDirInt.FullName, - Path.DirectorySeparatorChar, - "About", - Path.DirectorySeparatorChar, - "Preview.png" - }); + return this.rootDirInt.FullName + Path.DirectorySeparatorChar + "About" + Path.DirectorySeparatorChar + "Preview.png"; } } @@ -163,14 +164,7 @@ private string PublishedFileIdPath { get { - return string.Concat(new object[] - { - this.rootDirInt.FullName, - Path.DirectorySeparatorChar, - "About", - Path.DirectorySeparatorChar, - "PublishedFileId.txt" - }); + return this.rootDirInt.FullName + Path.DirectorySeparatorChar + "About" + Path.DirectorySeparatorChar + "PublishedFileId.txt"; } } @@ -190,14 +184,7 @@ public ModMetaData(WorkshopItem workshopItem) private void Init() { - this.meta = DirectXmlLoader.ItemFromXmlFile(string.Concat(new object[] - { - this.RootDir.FullName, - Path.DirectorySeparatorChar, - "About", - Path.DirectorySeparatorChar, - "About.xml" - }), true); + this.meta = DirectXmlLoader.ItemFromXmlFile(this.RootDir.FullName + Path.DirectorySeparatorChar + "About" + Path.DirectorySeparatorChar + "About.xml", true); if (this.meta.name.NullOrEmpty()) { if (this.OnSteamWorkshop) @@ -211,18 +198,9 @@ private void Init() } if (!this.IsCoreMod && !this.OnSteamWorkshop && !VersionControl.IsWellFormattedVersionString(this.meta.targetVersion)) { - Log.ErrorOnce(string.Concat(new string[] - { - "Mod ", - this.meta.name, - " has incorrectly formatted target version '", - this.meta.targetVersion, - "'. For the current version, write: ", - VersionControl.CurrentVersionString, - "" - }), this.Identifier.GetHashCode()); + Log.ErrorOnce("Mod " + this.meta.name + " has incorrectly formatted target version '" + this.meta.targetVersion + "'. For the current version, write: " + VersionControl.CurrentVersionString + "", this.Identifier.GetHashCode()); } - LongEventHandler.ExecuteWhenFinished(delegate + LongEventHandler.ExecuteWhenFinished((Action)delegate { string url = GenFilePaths.SafeURIForUnityWWWFromPath(this.PreviewImagePath); using (WWW wWW = new WWW(url)) @@ -258,7 +236,19 @@ public void PrepareForWorkshopUpload() public bool CanToUploadToWorkshop() { - return !this.IsCoreMod && this.Source == ContentSource.LocalFolder && !this.GetWorkshopItemHook().MayHaveAuthorNotCurrentUser; + if (this.IsCoreMod) + { + return false; + } + if (this.Source != ContentSource.LocalFolder) + { + return false; + } + if (this.GetWorkshopItemHook().MayHaveAuthorNotCurrentUser) + { + return false; + } + return true; } public PublishedFileId_t GetPublishedFileId() @@ -268,12 +258,11 @@ public PublishedFileId_t GetPublishedFileId() public void SetPublishedFileId(PublishedFileId_t newPfid) { - if (this.publishedFileIdInt == newPfid) + if (!(this.publishedFileIdInt == newPfid)) { - return; + this.publishedFileIdInt = newPfid; + File.WriteAllText(this.PublishedFileIdPath, newPfid.ToString()); } - this.publishedFileIdInt = newPfid; - File.WriteAllText(this.PublishedFileIdPath, newPfid.ToString()); } public string GetWorkshopName() @@ -293,10 +282,9 @@ public string GetWorkshopPreviewImagePath() public IList GetWorkshopTags() { - return new List - { - "Mod" - }; + List list = new List(); + list.Add("Mod"); + return list; } public DirectoryInfo GetWorkshopUploadDirectory() @@ -320,14 +308,7 @@ public override int GetHashCode() public override string ToString() { - return string.Concat(new string[] - { - "[", - this.Identifier, - "|", - this.Name, - "]" - }); + return "[" + this.Identifier + "|" + this.Name + "]"; } public string ToStringLong() diff --git a/Assembly-CSharp/Verse/ModSettings.cs b/Assembly-CSharp/Verse/ModSettings.cs index ffeb17f40..49ac7dfa0 100644 --- a/Assembly-CSharp/Verse/ModSettings.cs +++ b/Assembly-CSharp/Verse/ModSettings.cs @@ -1,5 +1,3 @@ -using System; - namespace Verse { public abstract class ModSettings : IExposable diff --git a/Assembly-CSharp/Verse/ModsConfig.cs b/Assembly-CSharp/Verse/ModsConfig.cs index e0c8ee495..b884e75a0 100644 --- a/Assembly-CSharp/Verse/ModsConfig.cs +++ b/Assembly-CSharp/Verse/ModsConfig.cs @@ -15,43 +15,35 @@ private class ModsConfigData public List activeMods = new List(); } - private static ModsConfig.ModsConfigData data; + private static ModsConfigData data; public static IEnumerable ActiveModsInLoadOrder { get { - ModsConfig.<>c__Iterator211 <>c__Iterator = new ModsConfig.<>c__Iterator211(); - ModsConfig.<>c__Iterator211 expr_07 = <>c__Iterator; - expr_07.$PC = -2; - return expr_07; + ModLister.EnsureInit(); + for (int i = 0; i < ModsConfig.data.activeMods.Count; i++) + { + yield return ModLister.GetModWithIdentifier(ModsConfig.data.activeMods[i]); + } } } static ModsConfig() { bool flag = false; - ModsConfig.data = DirectXmlLoader.ItemFromXmlFile(GenFilePaths.ModsConfigFilePath, true); + ModsConfig.data = DirectXmlLoader.ItemFromXmlFile(GenFilePaths.ModsConfigFilePath, true); if (ModsConfig.data.buildNumber < VersionControl.CurrentBuild) { - Log.Message(string.Concat(new object[] - { - "Mods config data is from build ", - ModsConfig.data.buildNumber, - " while we are at build ", - VersionControl.CurrentBuild, - ". Resetting." - })); - ModsConfig.data = new ModsConfig.ModsConfigData(); + Log.Message("Mods config data is from build " + ModsConfig.data.buildNumber + " while we are at build " + VersionControl.CurrentBuild + ". Resetting."); + ModsConfig.data = new ModsConfigData(); flag = true; } ModsConfig.data.buildNumber = VersionControl.CurrentBuild; - bool flag2 = File.Exists(GenFilePaths.ModsConfigFilePath); - if (!flag2 || flag) - { - ModsConfig.data.activeMods.Add(ModContentPack.CoreModIdentifier); - ModsConfig.Save(); - } + if (File.Exists(GenFilePaths.ModsConfigFilePath) && !flag) + return; + ModsConfig.data.activeMods.Add(ModContentPack.CoreModIdentifier); + ModsConfig.Save(); } public static void DeactivateNotInstalledMods(Action logCallback = null) @@ -59,9 +51,9 @@ public static void DeactivateNotInstalledMods(Action logCallback = null) int i; for (i = ModsConfig.data.activeMods.Count - 1; i >= 0; i--) { - if (!ModLister.AllInstalledMods.Any((ModMetaData m) => m.Identifier == ModsConfig.data.activeMods[i])) + if (!ModLister.AllInstalledMods.Any((Func)((ModMetaData m) => m.Identifier == ModsConfig.data.activeMods[i]))) { - if (logCallback != null) + if ((object)logCallback != null) { logCallback("Deactivating " + ModsConfig.data.activeMods[i]); } @@ -79,13 +71,12 @@ public static void Reset() internal static void Reorder(int modIndex, int newIndex) { - if (modIndex == newIndex) + if (modIndex != newIndex) { - return; + string item = ModsConfig.data.activeMods[modIndex]; + ModsConfig.data.activeMods.RemoveAt(modIndex); + ModsConfig.data.activeMods.Insert(newIndex, item); } - string item = ModsConfig.data.activeMods[modIndex]; - ModsConfig.data.activeMods.RemoveAt(modIndex); - ModsConfig.data.activeMods.Insert(newIndex, item); } public static bool IsActive(ModMetaData mod) diff --git a/Assembly-CSharp/Verse/Mote.cs b/Assembly-CSharp/Verse/Mote.cs index 3b57f6975..2504367e7 100644 --- a/Assembly-CSharp/Verse/Mote.cs +++ b/Assembly-CSharp/Verse/Mote.cs @@ -1,4 +1,3 @@ -using System; using UnityEngine; namespace Verse @@ -39,11 +38,11 @@ public float AgeSecs { get { - if (this.def.mote.realTime) + if (base.def.mote.realTime) { return Time.realtimeSinceStartup - this.spawnRealTime; } - return (float)(Find.TickManager.TicksGame - this.spawnTick) / 60f; + return (float)((float)(Find.TickManager.TicksGame - this.spawnTick) / 60.0); } } @@ -59,7 +58,7 @@ protected virtual float LifespanSecs { get { - return this.def.mote.fadeInTime + this.def.mote.solidTime + this.def.mote.fadeOutTime; + return base.def.mote.fadeInTime + base.def.mote.solidTime + base.def.mote.fadeOutTime; } } @@ -70,7 +69,7 @@ public override void SpawnSetup(Map map, bool respawningAfterLoad) this.spawnRealTime = Time.realtimeSinceStartup; RealTime.moteList.MoteSpawned(this); base.Map.moteCounter.Notify_MoteSpawned(); - this.exactPosition.y = Altitudes.AltitudeFor(this.def.altitudeLayer); + this.exactPosition.y = Altitudes.AltitudeFor(base.def.altitudeLayer); } public override void DeSpawn() @@ -83,7 +82,7 @@ public override void DeSpawn() public override void Tick() { - if (!this.def.mote.realTime) + if (!base.def.mote.realTime) { this.TimeInterval(0.0166666675f); } @@ -91,7 +90,7 @@ public override void Tick() public void RealtimeUpdate() { - if (this.def.mote.realTime) + if (base.def.mote.realTime) { this.TimeInterval(Time.deltaTime); } @@ -102,22 +101,20 @@ protected virtual void TimeInterval(float deltaTime) if (this.AgeSecs >= this.LifespanSecs && !base.Destroyed) { this.Destroy(DestroyMode.Vanish); - return; } - if (this.def.mote.needsMaintenance && Find.TickManager.TicksGame - 1 > this.lastMaintainTick) + else if (base.def.mote.needsMaintenance && Find.TickManager.TicksGame - 1 > this.lastMaintainTick) { this.Destroy(DestroyMode.Vanish); - return; } - if (this.def.mote.growthRate > 0f) + else if (base.def.mote.growthRate > 0.0) { - this.exactScale = new Vector3(this.exactScale.x + this.def.mote.growthRate * deltaTime, this.exactScale.y, this.exactScale.z + this.def.mote.growthRate * deltaTime); + this.exactScale = new Vector3(this.exactScale.x + base.def.mote.growthRate * deltaTime, this.exactScale.y, this.exactScale.z + base.def.mote.growthRate * deltaTime); } } public override void Draw() { - this.exactPosition.y = Altitudes.AltitudeFor(this.def.altitudeLayer); + this.exactPosition.y = Altitudes.AltitudeFor(base.def.altitudeLayer); base.Draw(); } diff --git a/Assembly-CSharp/Verse/MoteAttachLink.cs b/Assembly-CSharp/Verse/MoteAttachLink.cs index d85210f03..97ccc2270 100644 --- a/Assembly-CSharp/Verse/MoteAttachLink.cs +++ b/Assembly-CSharp/Verse/MoteAttachLink.cs @@ -1,4 +1,3 @@ -using System; using UnityEngine; namespace Verse diff --git a/Assembly-CSharp/Verse/MoteCounter.cs b/Assembly-CSharp/Verse/MoteCounter.cs index f3874ab9e..94f4d66a3 100644 --- a/Assembly-CSharp/Verse/MoteCounter.cs +++ b/Assembly-CSharp/Verse/MoteCounter.cs @@ -1,5 +1,3 @@ -using System; - namespace Verse { public class MoteCounter @@ -20,7 +18,7 @@ public float Saturation { get { - return (float)this.moteCount / 250f; + return (float)((float)this.moteCount / 250.0); } } @@ -28,7 +26,7 @@ public bool Saturated { get { - return this.Saturation > 1f; + return this.Saturation > 1.0; } } @@ -36,7 +34,7 @@ public bool SaturatedLowPriority { get { - return this.Saturation > 0.8f; + return this.Saturation > 0.800000011920929; } } diff --git a/Assembly-CSharp/Verse/MoteDualAttached.cs b/Assembly-CSharp/Verse/MoteDualAttached.cs index df53461f7..7cc915b5f 100644 --- a/Assembly-CSharp/Verse/MoteDualAttached.cs +++ b/Assembly-CSharp/Verse/MoteDualAttached.cs @@ -1,5 +1,3 @@ -using System; - namespace Verse { public class MoteDualAttached : Mote @@ -8,7 +6,7 @@ public class MoteDualAttached : Mote public void Attach(TargetInfo a, TargetInfo b) { - this.link1 = new MoteAttachLink(a); + base.link1 = new MoteAttachLink(a); this.link2 = new MoteAttachLink(b); } @@ -20,30 +18,30 @@ public override void Draw() protected void UpdatePosition() { - if (this.link1.Linked) + if (base.link1.Linked) { if (this.link2.Linked) { - if (!this.link1.Target.ThingDestroyed) + if (!base.link1.Target.ThingDestroyed) { - this.link1.UpdateDrawPos(); + base.link1.UpdateDrawPos(); } if (!this.link2.Target.ThingDestroyed) { this.link2.UpdateDrawPos(); } - this.exactPosition = (this.link1.LastDrawPos + this.link2.LastDrawPos) * 0.5f; + base.exactPosition = (base.link1.LastDrawPos + this.link2.LastDrawPos) * 0.5f; } else { - if (!this.link1.Target.ThingDestroyed) + if (!base.link1.Target.ThingDestroyed) { - this.link1.UpdateDrawPos(); + base.link1.UpdateDrawPos(); } - this.exactPosition = this.link1.LastDrawPos + this.def.mote.attachedDrawOffset; + base.exactPosition = base.link1.LastDrawPos + base.def.mote.attachedDrawOffset; } } - this.exactPosition.y = Altitudes.AltitudeFor(this.def.altitudeLayer); + base.exactPosition.y = Altitudes.AltitudeFor(base.def.altitudeLayer); } } } diff --git a/Assembly-CSharp/Verse/MoteProperties.cs b/Assembly-CSharp/Verse/MoteProperties.cs index 77dbb88b5..5be737391 100644 --- a/Assembly-CSharp/Verse/MoteProperties.cs +++ b/Assembly-CSharp/Verse/MoteProperties.cs @@ -1,4 +1,3 @@ -using System; using UnityEngine; namespace Verse diff --git a/Assembly-CSharp/Verse/MoteSpawnLocType.cs b/Assembly-CSharp/Verse/MoteSpawnLocType.cs index d280a0158..091d25c88 100644 --- a/Assembly-CSharp/Verse/MoteSpawnLocType.cs +++ b/Assembly-CSharp/Verse/MoteSpawnLocType.cs @@ -1,12 +1,10 @@ -using System; - namespace Verse { public enum MoteSpawnLocType : byte { - OnSource, - BetweenPositions, - BetweenTouchingCells, - RandomCellOnTarget + OnSource = 0, + BetweenPositions = 1, + BetweenTouchingCells = 2, + RandomCellOnTarget = 3 } } diff --git a/Assembly-CSharp/Verse/MoteSplash.cs b/Assembly-CSharp/Verse/MoteSplash.cs index 091088ce2..e3b67a4a4 100644 --- a/Assembly-CSharp/Verse/MoteSplash.cs +++ b/Assembly-CSharp/Verse/MoteSplash.cs @@ -1,5 +1,4 @@ using RimWorld; -using System; using UnityEngine; namespace Verse @@ -40,7 +39,7 @@ protected override float LifespanSecs public void Initialize(Vector3 position, float size, float velocity) { - this.exactPosition = position; + base.exactPosition = position; this.targetSize = size; this.velocity = velocity; base.Scale = 0f; @@ -49,32 +48,31 @@ public void Initialize(Vector3 position, float size, float velocity) protected override void TimeInterval(float deltaTime) { base.TimeInterval(deltaTime); - if (base.Destroyed) + if (!base.Destroyed) { - return; + float scale = base.AgeSecs * this.velocity; + base.Scale = scale; } - float scale = base.AgeSecs * this.velocity; - base.Scale = scale; } public float CalculatedIntensity() { - return Mathf.Sqrt(this.targetSize) / 10f; + return (float)(Mathf.Sqrt(this.targetSize) / 10.0); } public float CalculatedAlpha() { - float num = Mathf.Clamp01(base.AgeSecs * 10f); + float num = Mathf.Clamp01((float)(base.AgeSecs * 10.0)); num = 1f; - float num2 = Mathf.Clamp01(1f - base.AgeSecs / this.LifespanSecs); + float num2 = Mathf.Clamp01((float)(1.0 - base.AgeSecs / this.LifespanSecs)); return num * num2 * this.CalculatedIntensity(); } public float CalculatedShockwaveSpan() { - float num = Mathf.Sqrt(this.targetSize) * 0.8f; - num = Mathf.Min(num, this.exactScale.x); - return num / this.exactScale.x; + float a = (float)(Mathf.Sqrt(this.targetSize) * 0.800000011920929); + a = Mathf.Min(a, base.exactScale.x); + return a / base.exactScale.x; } } } diff --git a/Assembly-CSharp/Verse/MoteText.cs b/Assembly-CSharp/Verse/MoteText.cs index cbb738e51..972d745bc 100644 --- a/Assembly-CSharp/Verse/MoteText.cs +++ b/Assembly-CSharp/Verse/MoteText.cs @@ -1,4 +1,3 @@ -using System; using UnityEngine; namespace Verse @@ -15,7 +14,7 @@ protected float TimeBeforeStartFadeout { get { - return (this.overrideTimeBeforeStartFadeout < 0f) ? this.def.mote.solidTime : this.overrideTimeBeforeStartFadeout; + return (!(this.overrideTimeBeforeStartFadeout >= 0.0)) ? base.def.mote.solidTime : this.overrideTimeBeforeStartFadeout; } } @@ -23,7 +22,7 @@ protected override float LifespanSecs { get { - return this.TimeBeforeStartFadeout + this.def.mote.fadeOutTime; + return this.TimeBeforeStartFadeout + base.def.mote.fadeOutTime; } } @@ -33,9 +32,9 @@ public override void Draw() public override void DrawGUIOverlay() { - float a = 1f - (base.AgeSecs - this.TimeBeforeStartFadeout) / this.def.mote.fadeOutTime; + float a = (float)(1.0 - (base.AgeSecs - this.TimeBeforeStartFadeout) / base.def.mote.fadeOutTime); Color color = new Color(this.textColor.r, this.textColor.g, this.textColor.b, a); - GenMapUI.DrawText(new Vector2(this.exactPosition.x, this.exactPosition.z), this.text, color); + GenMapUI.DrawText(new Vector2(base.exactPosition.x, base.exactPosition.z), this.text, color); } } } diff --git a/Assembly-CSharp/Verse/MoteThrown.cs b/Assembly-CSharp/Verse/MoteThrown.cs index 506b219f3..ab708f68f 100644 --- a/Assembly-CSharp/Verse/MoteThrown.cs +++ b/Assembly-CSharp/Verse/MoteThrown.cs @@ -1,4 +1,3 @@ -using System; using UnityEngine; using Verse.Sound; @@ -14,7 +13,7 @@ protected bool Flying { get { - return this.airTimeLeft > 0f; + return this.airTimeLeft > 0.0; } } @@ -22,7 +21,7 @@ protected bool Skidding { get { - return !this.Flying && this.Speed > 0.01f; + return !this.Flying && this.Speed > 0.0099999997764825821; } } @@ -58,80 +57,76 @@ public float Speed } set { - if (value == 0f) + if (value == 0.0) { this.velocity = Vector3.zero; - return; } - if (this.velocity == Vector3.zero) + else if (this.velocity == Vector3.zero) { this.velocity = new Vector3(value, 0f, 0f); - return; } - this.velocity = this.velocity.normalized * value; + else + { + this.velocity = this.velocity.normalized * value; + } } } protected override void TimeInterval(float deltaTime) { base.TimeInterval(deltaTime); - if (base.Destroyed) - { - return; - } - if (!this.Flying && !this.Skidding) + if (!base.Destroyed && (this.Flying || this.Skidding)) { - return; - } - Vector3 vector = this.NextExactPosition(deltaTime); - IntVec3 intVec = new IntVec3(vector); - if (intVec != base.Position) - { - if (!intVec.InBounds(base.Map)) - { - this.Destroy(DestroyMode.Vanish); - return; - } - if (this.def.mote.collide && intVec.Filled(base.Map)) + Vector3 vector = this.NextExactPosition(deltaTime); + IntVec3 intVec = new IntVec3(vector); + if (intVec != base.Position) { - this.WallHit(); - return; + if (!intVec.InBounds(base.Map)) + { + this.Destroy(DestroyMode.Vanish); + return; + } + if (base.def.mote.collide && intVec.Filled(base.Map)) + { + this.WallHit(); + return; + } } - } - base.Position = intVec; - this.exactPosition = vector; - this.exactRotation += this.rotationRate * deltaTime; - this.velocity += this.def.mote.acceleration * deltaTime; - if (this.def.mote.speedPerTime != 0f) - { - this.Speed = Mathf.Max(this.Speed + this.def.mote.speedPerTime * deltaTime, 0f); - } - if (this.airTimeLeft > 0f) - { - this.airTimeLeft -= deltaTime; - if (this.airTimeLeft < 0f) + base.Position = intVec; + base.exactPosition = vector; + base.exactRotation += base.rotationRate * deltaTime; + this.velocity += base.def.mote.acceleration * deltaTime; + if (base.def.mote.speedPerTime != 0.0) { - this.airTimeLeft = 0f; + this.Speed = Mathf.Max(this.Speed + base.def.mote.speedPerTime * deltaTime, 0f); } - if (this.airTimeLeft <= 0f && !this.def.mote.landSound.NullOrUndefined()) + if (this.airTimeLeft > 0.0) { - this.def.mote.landSound.PlayOneShot(new TargetInfo(base.Position, base.Map, false)); + this.airTimeLeft -= deltaTime; + if (this.airTimeLeft < 0.0) + { + this.airTimeLeft = 0f; + } + if (this.airTimeLeft <= 0.0 && !base.def.mote.landSound.NullOrUndefined()) + { + base.def.mote.landSound.PlayOneShot(new TargetInfo(base.Position, base.Map, false)); + } } - } - if (this.Skidding) - { - this.Speed *= this.skidSpeedMultiplierPerTick; - this.rotationRate *= this.skidSpeedMultiplierPerTick; - if (this.Speed < 0.02f) + if (this.Skidding) { - this.Speed = 0f; + this.Speed *= base.skidSpeedMultiplierPerTick; + base.rotationRate *= base.skidSpeedMultiplierPerTick; + if (this.Speed < 0.019999999552965164) + { + this.Speed = 0f; + } } } } protected virtual Vector3 NextExactPosition(float deltaTime) { - return this.exactPosition + this.velocity * deltaTime; + return base.exactPosition + this.velocity * deltaTime; } public void SetVelocity(float angle, float speed) @@ -143,7 +138,7 @@ protected virtual void WallHit() { this.airTimeLeft = 0f; this.Speed = 0f; - this.rotationRate = 0f; + base.rotationRate = 0f; } } } diff --git a/Assembly-CSharp/Verse/MoteThrownAttached.cs b/Assembly-CSharp/Verse/MoteThrownAttached.cs index 3ed3f7c10..6c7c76af7 100644 --- a/Assembly-CSharp/Verse/MoteThrownAttached.cs +++ b/Assembly-CSharp/Verse/MoteThrownAttached.cs @@ -1,4 +1,3 @@ -using System; using UnityEngine; namespace Verse @@ -10,26 +9,26 @@ internal class MoteThrownAttached : MoteThrown public override void SpawnSetup(Map map, bool respawningAfterLoad) { base.SpawnSetup(map, respawningAfterLoad); - if (this.link1.Linked) + if (base.link1.Linked) { - this.attacheeLastPosition = this.link1.LastDrawPos; + this.attacheeLastPosition = base.link1.LastDrawPos; } - this.exactPosition += this.def.mote.attachedDrawOffset; + base.exactPosition += base.def.mote.attachedDrawOffset; } protected override Vector3 NextExactPosition(float deltaTime) { Vector3 vector = base.NextExactPosition(deltaTime); - if (this.link1.Linked) + if (base.link1.Linked) { - if (!this.link1.Target.ThingDestroyed) + if (!base.link1.Target.ThingDestroyed) { - this.link1.UpdateDrawPos(); + base.link1.UpdateDrawPos(); } - Vector3 b = this.link1.LastDrawPos - this.attacheeLastPosition; + Vector3 b = base.link1.LastDrawPos - this.attacheeLastPosition; vector += b; vector.y = Altitudes.AltitudeFor(AltitudeLayer.MoteOverhead); - this.attacheeLastPosition = this.link1.LastDrawPos; + this.attacheeLastPosition = base.link1.LastDrawPos; } return vector; } diff --git a/Assembly-CSharp/Verse/Mouse.cs b/Assembly-CSharp/Verse/Mouse.cs index 9cba362ad..c50d1cb45 100644 --- a/Assembly-CSharp/Verse/Mouse.cs +++ b/Assembly-CSharp/Verse/Mouse.cs @@ -1,4 +1,3 @@ -using System; using UnityEngine; namespace Verse @@ -10,13 +9,25 @@ public static bool IsInputBlockedNow get { WindowStack windowStack = Find.WindowStack; - return windowStack.MouseObscuredNow || !windowStack.CurrentWindowGetsInput; + if (windowStack.MouseObscuredNow) + { + return true; + } + if (!windowStack.CurrentWindowGetsInput) + { + return true; + } + return false; } } public static bool IsOver(Rect rect) { - return rect.Contains(Event.current.mousePosition) && !Mouse.IsInputBlockedNow; + if (rect.Contains(Event.current.mousePosition) && !Mouse.IsInputBlockedNow) + { + return true; + } + return false; } } } diff --git a/Assembly-CSharp/Verse/MouseoverReadout.cs b/Assembly-CSharp/Verse/MouseoverReadout.cs index 4ff535970..2216d4318 100644 --- a/Assembly-CSharp/Verse/MouseoverReadout.cs +++ b/Assembly-CSharp/Verse/MouseoverReadout.cs @@ -1,4 +1,3 @@ -using System; using System.Collections.Generic; using UnityEngine; @@ -26,99 +25,117 @@ private void MakePermaCache() this.glowStrings = new string[101]; for (int i = 0; i <= 100; i++) { - this.glowStrings[i] = GlowGrid.PsychGlowAtGlow((float)i / 100f).GetLabel() + " (" + ((float)i / 100f).ToStringPercent() + ")"; + this.glowStrings[i] = GlowGrid.PsychGlowAtGlow((float)((float)i / 100.0)).GetLabel() + " (" + ((float)((float)i / 100.0)).ToStringPercent() + ")"; } } public void MouseoverReadoutOnGUI() { - if (Event.current.type != EventType.Repaint) + if (Event.current.type == EventType.Repaint && Find.MainTabsRoot.OpenTab == null) { - return; - } - if (Find.MainTabsRoot.OpenTab != null) - { - return; - } - GenUI.DrawTextWinterShadow(new Rect(256f, (float)(UI.screenHeight - 256), -256f, 256f)); - Text.Font = GameFont.Small; - GUI.color = new Color(1f, 1f, 1f, 0.8f); - IntVec3 c = UI.MouseCell(); - if (!c.InBounds(Find.VisibleMap)) - { - return; - } - float num = 0f; - Rect rect; - if (c.Fogged(Find.VisibleMap)) - { - rect = new Rect(MouseoverReadout.BotLeft.x, (float)UI.screenHeight - MouseoverReadout.BotLeft.y - num, 999f, 999f); - Widgets.Label(rect, "Undiscovered".Translate()); - GUI.color = Color.white; - return; - } - rect = new Rect(MouseoverReadout.BotLeft.x, (float)UI.screenHeight - MouseoverReadout.BotLeft.y - num, 999f, 999f); - int num2 = Mathf.RoundToInt(Find.VisibleMap.glowGrid.GameGlowAt(c) * 100f); - Widgets.Label(rect, this.glowStrings[num2]); - num += 19f; - rect = new Rect(MouseoverReadout.BotLeft.x, (float)UI.screenHeight - MouseoverReadout.BotLeft.y - num, 999f, 999f); - TerrainDef terrain = c.GetTerrain(Find.VisibleMap); - if (terrain != this.cachedTerrain) - { - string str = ((double)terrain.fertility <= 0.0001) ? string.Empty : (" " + "FertShort".Translate() + " " + terrain.fertility.ToStringPercent()); - this.cachedTerrainString = terrain.LabelCap + ((terrain.passability == Traversability.Impassable) ? null : (" (" + "WalkSpeed".Translate(new object[] - { - this.SpeedPercentString((float)terrain.pathCost) - }) + str + ")")); - this.cachedTerrain = terrain; - } - Widgets.Label(rect, this.cachedTerrainString); - num += 19f; - Zone zone = c.GetZone(Find.VisibleMap); - if (zone != null) - { - rect = new Rect(MouseoverReadout.BotLeft.x, (float)UI.screenHeight - MouseoverReadout.BotLeft.y - num, 999f, 999f); - string label = zone.label; - Widgets.Label(rect, label); - num += 19f; - } - float depth = Find.VisibleMap.snowGrid.GetDepth(c); - if (depth > 0.03f) - { - rect = new Rect(MouseoverReadout.BotLeft.x, (float)UI.screenHeight - MouseoverReadout.BotLeft.y - num, 999f, 999f); - SnowCategory snowCategory = SnowUtility.GetSnowCategory(depth); - string label2 = SnowUtility.GetDescription(snowCategory) + " (" + "WalkSpeed".Translate(new object[] + GenUI.DrawTextWinterShadow(new Rect(256f, (float)(UI.screenHeight - 256), -256f, 256f)); + Text.Font = GameFont.Small; + GUI.color = new Color(1f, 1f, 1f, 0.8f); + IntVec3 c = UI.MouseCell(); + if (c.InBounds(Find.VisibleMap)) { - this.SpeedPercentString((float)SnowUtility.MovementTicksAddOn(snowCategory)) - }) + ")"; - Widgets.Label(rect, label2); - num += 19f; - } - List thingList = c.GetThingList(Find.VisibleMap); - for (int i = 0; i < thingList.Count; i++) - { - Thing thing = thingList[i]; - if (thing.def.category != ThingCategory.Mote) - { - rect = new Rect(MouseoverReadout.BotLeft.x, (float)UI.screenHeight - MouseoverReadout.BotLeft.y - num, 999f, 999f); - string labelMouseover = thing.LabelMouseover; - Widgets.Label(rect, labelMouseover); - num += 19f; + float num = 0f; + Rect rect = default(Rect); + if (c.Fogged(Find.VisibleMap)) + { + Vector2 botLeft = MouseoverReadout.BotLeft; + float x = botLeft.x; + float num2 = (float)UI.screenHeight; + Vector2 botLeft2 = MouseoverReadout.BotLeft; + rect = new Rect(x, num2 - botLeft2.y - num, 999f, 999f); + Widgets.Label(rect, "Undiscovered".Translate()); + GUI.color = Color.white; + } + else + { + Vector2 botLeft3 = MouseoverReadout.BotLeft; + float x2 = botLeft3.x; + float num3 = (float)UI.screenHeight; + Vector2 botLeft4 = MouseoverReadout.BotLeft; + rect = new Rect(x2, num3 - botLeft4.y - num, 999f, 999f); + int num4 = Mathf.RoundToInt((float)(Find.VisibleMap.glowGrid.GameGlowAt(c) * 100.0)); + Widgets.Label(rect, this.glowStrings[num4]); + num = (float)(num + 19.0); + Vector2 botLeft5 = MouseoverReadout.BotLeft; + float x3 = botLeft5.x; + float num5 = (float)UI.screenHeight; + Vector2 botLeft6 = MouseoverReadout.BotLeft; + rect = new Rect(x3, num5 - botLeft6.y - num, 999f, 999f); + TerrainDef terrain = c.GetTerrain(Find.VisibleMap); + if (terrain != this.cachedTerrain) + { + string str = (!((double)terrain.fertility > 0.0001)) ? string.Empty : (" " + "FertShort".Translate() + " " + terrain.fertility.ToStringPercent()); + this.cachedTerrainString = terrain.LabelCap + ((terrain.passability == Traversability.Impassable) ? null : (" (" + "WalkSpeed".Translate(this.SpeedPercentString((float)terrain.pathCost)) + str + ")")); + this.cachedTerrain = terrain; + } + Widgets.Label(rect, this.cachedTerrainString); + num = (float)(num + 19.0); + Zone zone = c.GetZone(Find.VisibleMap); + if (zone != null) + { + Vector2 botLeft7 = MouseoverReadout.BotLeft; + float x4 = botLeft7.x; + float num6 = (float)UI.screenHeight; + Vector2 botLeft8 = MouseoverReadout.BotLeft; + rect = new Rect(x4, num6 - botLeft8.y - num, 999f, 999f); + string label = zone.label; + Widgets.Label(rect, label); + num = (float)(num + 19.0); + } + float depth = Find.VisibleMap.snowGrid.GetDepth(c); + if (depth > 0.029999999329447746) + { + Vector2 botLeft9 = MouseoverReadout.BotLeft; + float x5 = botLeft9.x; + float num7 = (float)UI.screenHeight; + Vector2 botLeft10 = MouseoverReadout.BotLeft; + rect = new Rect(x5, num7 - botLeft10.y - num, 999f, 999f); + SnowCategory snowCategory = SnowUtility.GetSnowCategory(depth); + string label2 = SnowUtility.GetDescription(snowCategory) + " (" + "WalkSpeed".Translate(this.SpeedPercentString((float)SnowUtility.MovementTicksAddOn(snowCategory))) + ")"; + Widgets.Label(rect, label2); + num = (float)(num + 19.0); + } + List thingList = c.GetThingList(Find.VisibleMap); + for (int i = 0; i < thingList.Count; i++) + { + Thing thing = thingList[i]; + if (thing.def.category != ThingCategory.Mote) + { + Vector2 botLeft11 = MouseoverReadout.BotLeft; + float x6 = botLeft11.x; + float num8 = (float)UI.screenHeight; + Vector2 botLeft12 = MouseoverReadout.BotLeft; + rect = new Rect(x6, num8 - botLeft12.y - num, 999f, 999f); + string labelMouseover = thing.LabelMouseover; + Widgets.Label(rect, labelMouseover); + num = (float)(num + 19.0); + } + } + RoofDef roof = c.GetRoof(Find.VisibleMap); + if (roof != null) + { + Vector2 botLeft13 = MouseoverReadout.BotLeft; + float x7 = botLeft13.x; + float num9 = (float)UI.screenHeight; + Vector2 botLeft14 = MouseoverReadout.BotLeft; + rect = new Rect(x7, num9 - botLeft14.y - num, 999f, 999f); + Widgets.Label(rect, roof.LabelCap); + num = (float)(num + 19.0); + } + GUI.color = Color.white; + } } } - RoofDef roof = c.GetRoof(Find.VisibleMap); - if (roof != null) - { - rect = new Rect(MouseoverReadout.BotLeft.x, (float)UI.screenHeight - MouseoverReadout.BotLeft.y - num, 999f, 999f); - Widgets.Label(rect, roof.LabelCap); - num += 19f; - } - GUI.color = Color.white; } private string SpeedPercentString(float extraPathTicks) { - float f = 13f / (extraPathTicks + 13f); + float f = (float)(13.0 / (float)(extraPathTicks + 13.0)); return f.ToStringPercent(); } } diff --git a/Assembly-CSharp/Verse/MultiCheckboxState.cs b/Assembly-CSharp/Verse/MultiCheckboxState.cs index 395dd41e5..25d5b4192 100644 --- a/Assembly-CSharp/Verse/MultiCheckboxState.cs +++ b/Assembly-CSharp/Verse/MultiCheckboxState.cs @@ -1,11 +1,9 @@ -using System; - namespace Verse { public enum MultiCheckboxState : byte { - On, - Off, - Partial + On = 0, + Off = 1, + Partial = 2 } } diff --git a/Assembly-CSharp/Verse/Name.cs b/Assembly-CSharp/Verse/Name.cs index feeb30038..7df07653b 100644 --- a/Assembly-CSharp/Verse/Name.cs +++ b/Assembly-CSharp/Verse/Name.cs @@ -1,5 +1,3 @@ -using System; - namespace Verse { public abstract class Name : IExposable @@ -23,9 +21,9 @@ public bool UsedThisGame { get { - foreach (Name current in NameUseChecker.AllPawnsNamesEverUsed) + foreach (Name item in NameUseChecker.AllPawnsNamesEverUsed) { - if (current.ConfusinglySimilarTo(this)) + if (item.ConfusinglySimilarTo(this)) { return true; } diff --git a/Assembly-CSharp/Verse/NameSingle.cs b/Assembly-CSharp/Verse/NameSingle.cs index c2dd7d5f8..0a02b05a8 100644 --- a/Assembly-CSharp/Verse/NameSingle.cs +++ b/Assembly-CSharp/Verse/NameSingle.cs @@ -1,5 +1,3 @@ -using System; - namespace Verse { public class NameSingle : Name @@ -56,18 +54,18 @@ private int FirstDigitPosition { return -1; } - if (this.nameInt.NullOrEmpty() || !char.IsDigit(this.nameInt[this.nameInt.Length - 1])) - { - return -1; - } - for (int i = this.nameInt.Length - 2; i >= 0; i--) + if (!this.nameInt.NullOrEmpty() && char.IsDigit(this.nameInt[this.nameInt.Length - 1])) { - if (!char.IsDigit(this.nameInt[i])) + for (int num = this.nameInt.Length - 2; num >= 0; num--) { - return i + 1; + if (!char.IsDigit(this.nameInt[num])) + { + return num + 1; + } } + return 0; } - return 0; + return -1; } } @@ -126,7 +124,7 @@ public NameSingle(string name, bool numerical = false) public override void ExposeData() { - Scribe_Values.Look(ref this.nameInt, "name", null, false); + Scribe_Values.Look(ref this.nameInt, "name", (string)null, false); Scribe_Values.Look(ref this.numerical, "numerical", false, false); } @@ -138,7 +136,11 @@ public override bool ConfusinglySimilarTo(Name other) return true; } NameTriple nameTriple = other as NameTriple; - return nameTriple != null && nameTriple.Nick == this.nameInt; + if (nameTriple != null && nameTriple.Nick == this.nameInt) + { + return true; + } + return false; } public override string ToString() diff --git a/Assembly-CSharp/Verse/NameTriple.cs b/Assembly-CSharp/Verse/NameTriple.cs index 1334d2dd6..16591922a 100644 --- a/Assembly-CSharp/Verse/NameTriple.cs +++ b/Assembly-CSharp/Verse/NameTriple.cs @@ -1,4 +1,3 @@ -using System; using System.Linq; namespace Verse @@ -44,18 +43,11 @@ public override string ToStringFull { get { - if (this.First == this.Nick || this.Last == this.Nick) + if (!(this.First == this.Nick) && !(this.Last == this.Nick)) { - return this.First + " " + this.Last; + return this.First + " '" + this.Nick + "' " + this.Last; } - return string.Concat(new string[] - { - this.First, - " '", - this.Nick, - "' ", - this.Last - }); + return this.First + " " + this.Last; } } @@ -104,9 +96,9 @@ public NameTriple(string first, string nick, string last) public override void ExposeData() { - Scribe_Values.Look(ref this.firstInt, "first", null, false); - Scribe_Values.Look(ref this.nickInt, "nick", null, false); - Scribe_Values.Look(ref this.lastInt, "last", null, false); + Scribe_Values.Look(ref this.firstInt, "first", (string)null, false); + Scribe_Values.Look(ref this.nickInt, "nick", (string)null, false); + Scribe_Values.Look(ref this.lastInt, "last", (string)null, false); } public void ResolveMissingPieces(string overrideLastName = null) @@ -115,37 +107,39 @@ public void ResolveMissingPieces(string overrideLastName = null) { Log.Error("Cannot resolve misssing pieces in PawnName: No name data."); this.firstInt = (this.nickInt = (this.lastInt = "Empty")); - return; - } - if (this.First == null) - { - this.firstInt = string.Empty; } - if (this.Last == null) - { - this.lastInt = string.Empty; - } - if (overrideLastName != null) - { - this.lastInt = overrideLastName; - } - if (this.Nick.NullOrEmpty()) + else { - if (this.Last == string.Empty) + if (this.First == null) { - this.nickInt = this.First; + this.firstInt = string.Empty; } - else + if (this.Last == null) + { + this.lastInt = string.Empty; + } + if (overrideLastName != null) { - if (Rand.ValueSeeded(Gen.HashCombine(this.First.GetHashCode(), this.Last)) < 0.5f) + this.lastInt = overrideLastName; + } + if (this.Nick.NullOrEmpty()) + { + if (this.Last == string.Empty) { this.nickInt = this.First; } else { - this.nickInt = this.Last; + if (Rand.ValueSeeded(Gen.HashCombine(this.First.GetHashCode(), this.Last)) < 0.5) + { + this.nickInt = this.First; + } + else + { + this.nickInt = this.Last; + } + this.CapitalizeNick(); } - this.CapitalizeNick(); } } } @@ -165,7 +159,11 @@ public override bool ConfusinglySimilarTo(Name other) } } NameSingle nameSingle = other as NameSingle; - return nameSingle != null && nameSingle.Name == this.Nick; + if (nameSingle != null && nameSingle.Name == this.Nick) + { + return true; + } + return false; } public static NameTriple FromString(string rawName) @@ -197,10 +195,7 @@ public static NameTriple FromString(string rawName) } else { - string[] array = rawName.Split(new char[] - { - ' ' - }); + string[] array = rawName.Split(' '); if (array.Length == 1) { nameTriple.nickInt = array[0].Trim(); @@ -216,12 +211,12 @@ public static NameTriple FromString(string rawName) nameTriple.lastInt = string.Empty; for (int j = 1; j < array.Length; j++) { - NameTriple expr_137 = nameTriple; - expr_137.lastInt += array[j]; + NameTriple obj = nameTriple; + obj.lastInt += array[j]; if (j < array.Length - 1) { - NameTriple expr_15A = nameTriple; - expr_15A.lastInt += " "; + NameTriple obj2 = nameTriple; + obj2.lastInt += " "; } } } @@ -246,14 +241,7 @@ public void CapitalizeNick() public override string ToString() { - return string.Concat(new string[] - { - this.First, - " '", - this.Nick, - "' ", - this.Last - }); + return this.First + " '" + this.Nick + "' " + this.Last; } public override bool Equals(object obj) @@ -273,9 +261,9 @@ public override bool Equals(object obj) public override int GetHashCode() { int seed = 0; - seed = Gen.HashCombine(seed, this.First); - seed = Gen.HashCombine(seed, this.Last); - return Gen.HashCombine(seed, this.Nick); + seed = Gen.HashCombine(seed, this.First); + seed = Gen.HashCombine(seed, this.Last); + return Gen.HashCombine(seed, this.Nick); } } } diff --git a/Assembly-CSharp/Verse/NameUseChecker.cs b/Assembly-CSharp/Verse/NameUseChecker.cs index 31418e719..ec9805380 100644 --- a/Assembly-CSharp/Verse/NameUseChecker.cs +++ b/Assembly-CSharp/Verse/NameUseChecker.cs @@ -1,5 +1,4 @@ using RimWorld; -using System; using System.Collections.Generic; namespace Verse @@ -10,28 +9,29 @@ public static IEnumerable AllPawnsNamesEverUsed { get { - NameUseChecker.<>c__Iterator1FC <>c__Iterator1FC = new NameUseChecker.<>c__Iterator1FC(); - NameUseChecker.<>c__Iterator1FC expr_07 = <>c__Iterator1FC; - expr_07.$PC = -2; - return expr_07; + foreach (Pawn item in PawnsFinder.AllMapsAndWorld_AliveOrDead) + { + if (item.Name != null) + { + yield return item.Name; + } + } } } public static bool NameWordIsUsed(string singleName) { - foreach (Name current in NameUseChecker.AllPawnsNamesEverUsed) + foreach (Name item in NameUseChecker.AllPawnsNamesEverUsed) { - NameTriple nameTriple = current as NameTriple; + NameTriple nameTriple = item as NameTriple; if (nameTriple != null && (singleName == nameTriple.First || singleName == nameTriple.Nick || singleName == nameTriple.Last)) { - bool result = true; - return result; + return true; } - NameSingle nameSingle = current as NameSingle; + NameSingle nameSingle = item as NameSingle; if (nameSingle != null && nameSingle.Name == singleName) { - bool result = true; - return result; + return true; } } return false; @@ -39,9 +39,9 @@ public static bool NameWordIsUsed(string singleName) public static bool NameSingleIsUsed(string candidate) { - foreach (Pawn current in PawnsFinder.AllMapsAndWorld_AliveOrDead) + foreach (Pawn item in PawnsFinder.AllMapsAndWorld_AliveOrDead) { - NameSingle nameSingle = current.Name as NameSingle; + NameSingle nameSingle = item.Name as NameSingle; if (nameSingle != null && nameSingle.Name == candidate) { return true; diff --git a/Assembly-CSharp/Verse/OldInjuryUtility.cs b/Assembly-CSharp/Verse/OldInjuryUtility.cs index 430e0157f..942398aa9 100644 --- a/Assembly-CSharp/Verse/OldInjuryUtility.cs +++ b/Assembly-CSharp/Verse/OldInjuryUtility.cs @@ -1,4 +1,3 @@ -using System; using UnityEngine; namespace Verse diff --git a/Assembly-CSharp/Verse/OptionListingUtility.cs b/Assembly-CSharp/Verse/OptionListingUtility.cs index 7dac16d69..b2c95387d 100644 --- a/Assembly-CSharp/Verse/OptionListingUtility.cs +++ b/Assembly-CSharp/Verse/OptionListingUtility.cs @@ -13,9 +13,18 @@ public static float DrawOptionListing(Rect rect, List optList) float num = 0f; GUI.BeginGroup(rect); Text.Font = GameFont.Small; - foreach (ListableOption current in optList) + List.Enumerator enumerator = optList.GetEnumerator(); + try { - num += current.DrawOption(new Vector2(0f, num), rect.width) + 7f; + while (enumerator.MoveNext()) + { + ListableOption current = enumerator.Current; + num = (float)(num + (current.DrawOption(new Vector2(0f, num), rect.width) + 7.0)); + } + } + finally + { + ((IDisposable)(object)enumerator).Dispose(); } GUI.EndGroup(); return num; diff --git a/Assembly-CSharp/Verse/Pair.cs b/Assembly-CSharp/Verse/Pair.cs index e660e7882..8e33ed283 100644 --- a/Assembly-CSharp/Verse/Pair.cs +++ b/Assembly-CSharp/Verse/Pair.cs @@ -32,17 +32,7 @@ public Pair(T1 first, T2 second) public override string ToString() { - string[] expr_06 = new string[5]; - expr_06[0] = "("; - int arg_24_1 = 1; - T1 t = this.First; - expr_06[arg_24_1] = t.ToString(); - expr_06[2] = ", "; - int arg_43_1 = 3; - T2 t2 = this.Second; - expr_06[arg_43_1] = t2.ToString(); - expr_06[4] = ")"; - return string.Concat(expr_06); + return "(" + this.First.ToString() + ", " + this.Second.ToString() + ")"; } public override int GetHashCode() @@ -54,7 +44,11 @@ public override int GetHashCode() public override bool Equals(object other) { - return other is Pair && this.Equals((Pair)other); + if (!(other is Pair)) + { + return false; + } + return this.Equals((Pair)other); } public bool Equals(Pair other) diff --git a/Assembly-CSharp/Verse/ParseHelper.cs b/Assembly-CSharp/Verse/ParseHelper.cs index e95290cfe..7ac4d8857 100644 --- a/Assembly-CSharp/Verse/ParseHelper.cs +++ b/Assembly-CSharp/Verse/ParseHelper.cs @@ -12,258 +12,195 @@ public static class ParseHelper { public static object FromString(string str, Type itemType) { - object result; try { itemType = (Nullable.GetUnderlyingType(itemType) ?? itemType); if (itemType == typeof(string)) { str = str.Replace("\\n", "\n"); - result = str; + return str; } - else if (itemType == typeof(int)) + if (itemType == typeof(int)) { - result = int.Parse(str, CultureInfo.InvariantCulture); + return int.Parse(str, CultureInfo.InvariantCulture); } - else if (itemType == typeof(float)) + if (itemType == typeof(float)) { - result = float.Parse(str, CultureInfo.InvariantCulture); + return float.Parse(str, CultureInfo.InvariantCulture); } - else if (itemType == typeof(bool)) + if (itemType == typeof(bool)) { - result = bool.Parse(str); + return bool.Parse(str); } - else if (itemType == typeof(long)) + if (itemType == typeof(long)) { - result = long.Parse(str, CultureInfo.InvariantCulture); + return long.Parse(str, CultureInfo.InvariantCulture); } - else if (itemType == typeof(double)) + if (itemType == typeof(double)) { - result = double.Parse(str, CultureInfo.InvariantCulture); + return double.Parse(str, CultureInfo.InvariantCulture); } - else if (itemType == typeof(sbyte)) + if (itemType == typeof(sbyte)) { - result = sbyte.Parse(str, CultureInfo.InvariantCulture); + return sbyte.Parse(str, CultureInfo.InvariantCulture); } - else + if (itemType.IsEnum) { - if (itemType.IsEnum) + try { - try - { - result = Enum.Parse(itemType, str); - return result; - } - catch (ArgumentException innerException) - { - string text = string.Concat(new object[] - { - "'", - str, - "' is not a valid value for ", - itemType, - ". Valid values are: \n" - }); - text += GenText.StringFromEnumerable(Enum.GetValues(itemType)); - ArgumentException ex = new ArgumentException(text, innerException); - throw ex; - } + return Enum.Parse(itemType, str); + IL_0138:; } - if (itemType == typeof(Type)) + catch (ArgumentException innerException) { - if (str == "null" || str == "Null") - { - result = null; - } - else - { - Type typeInAnyAssembly = GenTypes.GetTypeInAnyAssembly(str); - if (typeInAnyAssembly == null) - { - Log.Error("Could not find a type named " + str); - } - result = typeInAnyAssembly; - } + string str2 = "'" + str + "' is not a valid value for " + itemType + ". Valid values are: \n"; + str2 += GenText.StringFromEnumerable(Enum.GetValues(itemType)); + ArgumentException ex = new ArgumentException(str2, innerException); + throw ex; + IL_0186:; } - else if (itemType == typeof(Action)) + } + if (itemType == typeof(Type)) + { + if (!(str == "null") && !(str == "Null")) { - string[] array = str.Split(new char[] - { - '.' - }); - string methodName = array[array.Length - 1]; - string typeName = string.Empty; - if (array.Length == 3) - { - typeName = array[0] + "." + array[1]; - } - else + Type typeInAnyAssembly = GenTypes.GetTypeInAnyAssembly(str); + if (typeInAnyAssembly == null) { - typeName = array[0]; + Log.Error("Could not find a type named " + str); } - Type typeInAnyAssembly2 = GenTypes.GetTypeInAnyAssembly(typeName); - MethodInfo method = typeInAnyAssembly2.GetMethods().First((MethodInfo m) => m.Name == methodName); - result = (Action)Delegate.CreateDelegate(typeof(Action), method); - } - else if (itemType == typeof(Vector3)) - { - result = ParseHelper.FromStringVector3(str); + return typeInAnyAssembly; } - else if (itemType == typeof(Vector2)) + return null; + } + if (itemType == typeof(Action)) + { + string[] array = str.Split('.'); + string methodName = array[array.Length - 1]; + string empty = string.Empty; + empty = ((array.Length != 3) ? array[0] : (array[0] + "." + array[1])); + Type typeInAnyAssembly2 = GenTypes.GetTypeInAnyAssembly(empty); + MethodInfo method = typeInAnyAssembly2.GetMethods().First((Func)((MethodInfo m) => m.Name == methodName)); + return (Action)Delegate.CreateDelegate(typeof(Action), method); + } + if (itemType == typeof(Vector3)) + { + return ParseHelper.FromStringVector3(str); + } + if (itemType == typeof(Vector2)) + { + return ParseHelper.FromStringVector2(str); + } + if (itemType == typeof(Rect)) + { + return ParseHelper.FromStringRect(str); + } + if (itemType == typeof(Color)) + { + str = str.TrimStart('(', 'R', 'G', 'B', 'A'); + str = str.TrimEnd(')'); + string[] array2 = str.Split(','); + float num = (float)ParseHelper.FromString(array2[0], typeof(float)); + float num2 = (float)ParseHelper.FromString(array2[1], typeof(float)); + float num3 = (float)ParseHelper.FromString(array2[2], typeof(float)); + bool flag = num > 1.0 || num3 > 1.0 || num2 > 1.0; + float num4 = (float)((!flag) ? 1 : 255); + if (array2.Length == 4) { - result = ParseHelper.FromStringVector2(str); + num4 = (float)ParseHelper.FromString(array2[3], typeof(float)); } - else if (itemType == typeof(Rect)) + Color color = default(Color); + if (!flag) { - result = ParseHelper.FromStringRect(str); + color.r = num; + color.g = num2; + color.b = num3; + color.a = num4; } - else if (itemType == typeof(Color)) - { - str = str.TrimStart(new char[] - { - '(', - 'R', - 'G', - 'B', - 'A' - }); - str = str.TrimEnd(new char[] - { - ')' - }); - string[] array2 = str.Split(new char[] - { - ',' - }); - float num = (float)ParseHelper.FromString(array2[0], typeof(float)); - float num2 = (float)ParseHelper.FromString(array2[1], typeof(float)); - float num3 = (float)ParseHelper.FromString(array2[2], typeof(float)); - bool flag = num > 1f || num3 > 1f || num2 > 1f; - float num4 = (float)((!flag) ? 1 : 255); - if (array2.Length == 4) - { - num4 = (float)ParseHelper.FromString(array2[3], typeof(float)); - } - Color color; - if (!flag) - { - color.r = num; - color.g = num2; - color.b = num3; - color.a = num4; - } - else - { - color = GenColor.FromBytes(Mathf.RoundToInt(num), Mathf.RoundToInt(num2), Mathf.RoundToInt(num3), Mathf.RoundToInt(num4)); - } - result = color; - } - else if (itemType == typeof(PublishedFileId_t)) - { - result = new PublishedFileId_t(ulong.Parse(str)); - } - else if (itemType == typeof(IntVec2)) + else { - result = IntVec2.FromString(str); + color = GenColor.FromBytes(Mathf.RoundToInt(num), Mathf.RoundToInt(num2), Mathf.RoundToInt(num3), Mathf.RoundToInt(num4)); } - else if (itemType == typeof(IntVec3)) + return color; + } + if (itemType == typeof(PublishedFileId_t)) + { + return new PublishedFileId_t(ulong.Parse(str)); + } + if (itemType == typeof(IntVec2)) + { + return IntVec2.FromString(str); + } + if (itemType == typeof(IntVec3)) + { + return IntVec3.FromString(str); + } + if (itemType == typeof(Rot4)) + { + return Rot4.FromString(str); + } + if (itemType == typeof(CellRect)) + { + return CellRect.FromString(str); + } + if (itemType == typeof(CurvePoint)) + { + return CurvePoint.FromString(str); + } + if (itemType == typeof(NameTriple)) + { + NameTriple nameTriple = NameTriple.FromString(str); + nameTriple.ResolveMissingPieces((string)null); + } + else + { + if (itemType == typeof(FloatRange)) { - result = IntVec3.FromString(str); + return FloatRange.FromString(str); } - else if (itemType == typeof(Rot4)) + if (itemType == typeof(IntRange)) { - result = Rot4.FromString(str); + return IntRange.FromString(str); } - else if (itemType == typeof(CellRect)) + if (itemType == typeof(QualityRange)) { - result = CellRect.FromString(str); + return QualityRange.FromString(str); } - else + if (itemType == typeof(ColorInt)) { - if (itemType != typeof(CurvePoint)) + str = str.TrimStart('(', 'R', 'G', 'B', 'A'); + str = str.TrimEnd(')'); + string[] array3 = str.Split(','); + ColorInt colorInt = new ColorInt(255, 255, 255, 255) + { + r = (int)ParseHelper.FromString(array3[0], typeof(int)), + g = (int)ParseHelper.FromString(array3[1], typeof(int)), + b = (int)ParseHelper.FromString(array3[2], typeof(int)) + }; + if (array3.Length == 4) + { + colorInt.a = (int)ParseHelper.FromString(array3[3], typeof(int)); + } + else { - if (itemType == typeof(NameTriple)) - { - NameTriple nameTriple = NameTriple.FromString(str); - nameTriple.ResolveMissingPieces(null); - } - else - { - if (itemType == typeof(FloatRange)) - { - result = FloatRange.FromString(str); - return result; - } - if (itemType == typeof(IntRange)) - { - result = IntRange.FromString(str); - return result; - } - if (itemType == typeof(QualityRange)) - { - result = QualityRange.FromString(str); - return result; - } - if (itemType == typeof(ColorInt)) - { - str = str.TrimStart(new char[] - { - '(', - 'R', - 'G', - 'B', - 'A' - }); - str = str.TrimEnd(new char[] - { - ')' - }); - string[] array3 = str.Split(new char[] - { - ',' - }); - ColorInt colorInt = new ColorInt(255, 255, 255, 255); - colorInt.r = (int)ParseHelper.FromString(array3[0], typeof(int)); - colorInt.g = (int)ParseHelper.FromString(array3[1], typeof(int)); - colorInt.b = (int)ParseHelper.FromString(array3[2], typeof(int)); - if (array3.Length == 4) - { - colorInt.a = (int)ParseHelper.FromString(array3[3], typeof(int)); - } - else - { - colorInt.a = 255; - } - result = colorInt; - return result; - } - } - throw new ArgumentException(string.Concat(new string[] - { - "Trying to parse to unknown data type ", - itemType.Name, - ". Content is '", - str, - "'." - })); + colorInt.a = 255; } - result = CurvePoint.FromString(str); + return colorInt; } } + throw new ArgumentException("Trying to parse to unknown data type " + itemType.Name + ". Content is '" + str + "'."); + IL_06f7: + object result; + return result; } catch (Exception innerException2) { - ArgumentException ex2 = new ArgumentException(string.Concat(new object[] - { - "Exception parsing ", - itemType, - " from \"", - str, - "\"" - }), innerException2); + ArgumentException ex2 = new ArgumentException("Exception parsing " + itemType + " from \"" + str + "\"", innerException2); throw ex2; + IL_0735: + object result; + return result; } - return result; } public static bool HandlesType(Type type) @@ -273,18 +210,9 @@ public static bool HandlesType(Type type) private static Vector3 FromStringVector3(string Str) { - Str = Str.TrimStart(new char[] - { - '(' - }); - Str = Str.TrimEnd(new char[] - { - ')' - }); - string[] array = Str.Split(new char[] - { - ',' - }); + Str = Str.TrimStart('('); + Str = Str.TrimEnd(')'); + string[] array = Str.Split(','); float x = Convert.ToSingle(array[0]); float y = Convert.ToSingle(array[1]); float z = Convert.ToSingle(array[2]); @@ -293,50 +221,32 @@ private static Vector3 FromStringVector3(string Str) private static Vector2 FromStringVector2(string Str) { - Str = Str.TrimStart(new char[] - { - '(' - }); - Str = Str.TrimEnd(new char[] - { - ')' - }); - string[] array = Str.Split(new char[] - { - ',' - }); + Str = Str.TrimStart('('); + Str = Str.TrimEnd(')'); + string[] array = Str.Split(','); float x; float y; if (array.Length == 1) { - y = (x = Convert.ToSingle(array[0])); + x = (y = Convert.ToSingle(array[0])); + goto IL_0077; } - else + if (array.Length == 2) { - if (array.Length != 2) - { - throw new InvalidOperationException(); - } x = Convert.ToSingle(array[0]); y = Convert.ToSingle(array[1]); + goto IL_0077; } + throw new InvalidOperationException(); + IL_0077: return new Vector2(x, y); } public static Rect FromStringRect(string str) { - str = str.TrimStart(new char[] - { - '(' - }); - str = str.TrimEnd(new char[] - { - ')' - }); - string[] array = str.Split(new char[] - { - ',' - }); + str = str.TrimStart('('); + str = str.TrimEnd(')'); + string[] array = str.Split(','); float x = Convert.ToSingle(array[0]); float y = Convert.ToSingle(array[1]); float width = Convert.ToSingle(array[2]); diff --git a/Assembly-CSharp/Verse/PatchOperation.cs b/Assembly-CSharp/Verse/PatchOperation.cs index 004019052..dd3df3d6d 100644 --- a/Assembly-CSharp/Verse/PatchOperation.cs +++ b/Assembly-CSharp/Verse/PatchOperation.cs @@ -1,4 +1,3 @@ -using System; using System.Xml; namespace Verse @@ -7,28 +6,28 @@ public class PatchOperation { private enum Success { - Normal, - Invert, - Always, - Never + Normal = 0, + Invert = 1, + Always = 2, + Never = 3 } private bool neverSucceeded = true; - private PatchOperation.Success success; + private Success success; public bool Apply(XmlDocument xml) { bool flag = this.ApplyWorker(xml); - if (this.success == PatchOperation.Success.Always) + if (this.success == Success.Always) { flag = true; } - else if (this.success == PatchOperation.Success.Never) + else if (this.success == Success.Never) { flag = false; } - else if (this.success == PatchOperation.Success.Invert) + else if (this.success == Success.Invert) { flag = !flag; } diff --git a/Assembly-CSharp/Verse/PatchOperationAdd.cs b/Assembly-CSharp/Verse/PatchOperationAdd.cs index d997df350..2ffae52a9 100644 --- a/Assembly-CSharp/Verse/PatchOperationAdd.cs +++ b/Assembly-CSharp/Verse/PatchOperationAdd.cs @@ -1,4 +1,3 @@ -using System; using System.Xml; namespace Verse @@ -7,34 +6,34 @@ public class PatchOperationAdd : PatchOperationPathed { private enum Order { - Append, - Prepend + Append = 0, + Prepend = 1 } private XmlContainer value; - private PatchOperationAdd.Order order; + private Order order; protected override bool ApplyWorker(XmlDocument xml) { XmlNode node = this.value.node; bool result = false; - foreach (object current in xml.SelectNodes(this.xpath)) + foreach (object item in xml.SelectNodes(base.xpath)) { result = true; - XmlNode xmlNode = current as XmlNode; - if (this.order == PatchOperationAdd.Order.Append) + XmlNode xmlNode = item as XmlNode; + if (this.order == Order.Append) { for (int i = 0; i < node.ChildNodes.Count; i++) { xmlNode.AppendChild(xmlNode.OwnerDocument.ImportNode(node.ChildNodes[i], true)); } } - else if (this.order == PatchOperationAdd.Order.Prepend) + else if (this.order == Order.Prepend) { - for (int j = node.ChildNodes.Count - 1; j >= 0; j--) + for (int num = node.ChildNodes.Count - 1; num >= 0; num--) { - xmlNode.PrependChild(xmlNode.OwnerDocument.ImportNode(node.ChildNodes[j], true)); + xmlNode.PrependChild(xmlNode.OwnerDocument.ImportNode(node.ChildNodes[num], true)); } } } diff --git a/Assembly-CSharp/Verse/PatchOperationAddModExtension.cs b/Assembly-CSharp/Verse/PatchOperationAddModExtension.cs index 1c8749c9d..759888a57 100644 --- a/Assembly-CSharp/Verse/PatchOperationAddModExtension.cs +++ b/Assembly-CSharp/Verse/PatchOperationAddModExtension.cs @@ -1,4 +1,3 @@ -using System; using System.Xml; namespace Verse @@ -11,9 +10,9 @@ protected override bool ApplyWorker(XmlDocument xml) { XmlNode node = this.value.node; bool result = false; - foreach (object current in xml.SelectNodes(this.xpath)) + foreach (object item in xml.SelectNodes(base.xpath)) { - XmlNode xmlNode = current as XmlNode; + XmlNode xmlNode = item as XmlNode; XmlNode xmlNode2 = xmlNode["modExtensions"]; if (xmlNode2 == null) { diff --git a/Assembly-CSharp/Verse/PatchOperationAttribute.cs b/Assembly-CSharp/Verse/PatchOperationAttribute.cs index a0d3f5a7a..d1fcfdda0 100644 --- a/Assembly-CSharp/Verse/PatchOperationAttribute.cs +++ b/Assembly-CSharp/Verse/PatchOperationAttribute.cs @@ -1,5 +1,3 @@ -using System; - namespace Verse { public abstract class PatchOperationAttribute : PatchOperationPathed diff --git a/Assembly-CSharp/Verse/PatchOperationAttributeAdd.cs b/Assembly-CSharp/Verse/PatchOperationAttributeAdd.cs index dbce6d2a9..5e1dc9126 100644 --- a/Assembly-CSharp/Verse/PatchOperationAttributeAdd.cs +++ b/Assembly-CSharp/Verse/PatchOperationAttributeAdd.cs @@ -1,4 +1,3 @@ -using System; using System.Xml; namespace Verse @@ -10,12 +9,12 @@ public class PatchOperationAttributeAdd : PatchOperationAttribute protected override bool ApplyWorker(XmlDocument xml) { bool result = false; - foreach (object current in xml.SelectNodes(this.xpath)) + foreach (object item in xml.SelectNodes(base.xpath)) { - XmlNode xmlNode = current as XmlNode; - if (xmlNode.Attributes[this.attribute] == null) + XmlNode xmlNode = item as XmlNode; + if (xmlNode.Attributes[base.attribute] == null) { - XmlAttribute xmlAttribute = xmlNode.OwnerDocument.CreateAttribute(this.attribute); + XmlAttribute xmlAttribute = xmlNode.OwnerDocument.CreateAttribute(base.attribute); xmlAttribute.Value = this.value; xmlNode.Attributes.Append(xmlAttribute); result = true; diff --git a/Assembly-CSharp/Verse/PatchOperationAttributeRemove.cs b/Assembly-CSharp/Verse/PatchOperationAttributeRemove.cs index b017e6cce..14ffbf990 100644 --- a/Assembly-CSharp/Verse/PatchOperationAttributeRemove.cs +++ b/Assembly-CSharp/Verse/PatchOperationAttributeRemove.cs @@ -1,4 +1,3 @@ -using System; using System.Xml; namespace Verse @@ -8,12 +7,12 @@ public class PatchOperationAttributeRemove : PatchOperationAttribute protected override bool ApplyWorker(XmlDocument xml) { bool result = false; - foreach (object current in xml.SelectNodes(this.xpath)) + foreach (object item in xml.SelectNodes(base.xpath)) { - XmlNode xmlNode = current as XmlNode; - if (xmlNode.Attributes[this.attribute] != null) + XmlNode xmlNode = item as XmlNode; + if (xmlNode.Attributes[base.attribute] != null) { - xmlNode.Attributes.Remove(xmlNode.Attributes[this.attribute]); + xmlNode.Attributes.Remove(xmlNode.Attributes[base.attribute]); result = true; } } diff --git a/Assembly-CSharp/Verse/PatchOperationAttributeSet.cs b/Assembly-CSharp/Verse/PatchOperationAttributeSet.cs index 63d15f238..6a4088fe2 100644 --- a/Assembly-CSharp/Verse/PatchOperationAttributeSet.cs +++ b/Assembly-CSharp/Verse/PatchOperationAttributeSet.cs @@ -1,4 +1,3 @@ -using System; using System.Xml; namespace Verse @@ -10,16 +9,16 @@ public class PatchOperationAttributeSet : PatchOperationAttribute protected override bool ApplyWorker(XmlDocument xml) { bool result = false; - foreach (object current in xml.SelectNodes(this.xpath)) + foreach (object item in xml.SelectNodes(base.xpath)) { - XmlNode xmlNode = current as XmlNode; - if (xmlNode.Attributes[this.attribute] != null) + XmlNode xmlNode = item as XmlNode; + if (xmlNode.Attributes[base.attribute] != null) { - xmlNode.Attributes[this.attribute].Value = this.value; + xmlNode.Attributes[base.attribute].Value = this.value; } else { - XmlAttribute xmlAttribute = xmlNode.OwnerDocument.CreateAttribute(this.attribute); + XmlAttribute xmlAttribute = xmlNode.OwnerDocument.CreateAttribute(base.attribute); xmlAttribute.Value = this.value; xmlNode.Attributes.Append(xmlAttribute); } diff --git a/Assembly-CSharp/Verse/PatchOperationInsert.cs b/Assembly-CSharp/Verse/PatchOperationInsert.cs index 8a90ab56c..6433b3910 100644 --- a/Assembly-CSharp/Verse/PatchOperationInsert.cs +++ b/Assembly-CSharp/Verse/PatchOperationInsert.cs @@ -1,4 +1,3 @@ -using System; using System.Xml; namespace Verse @@ -7,35 +6,35 @@ public class PatchOperationInsert : PatchOperationPathed { private enum Order { - Append, - Prepend + Append = 0, + Prepend = 1 } private XmlContainer value; - private PatchOperationInsert.Order order = PatchOperationInsert.Order.Prepend; + private Order order = Order.Prepend; protected override bool ApplyWorker(XmlDocument xml) { XmlNode node = this.value.node; bool result = false; - foreach (object current in xml.SelectNodes(this.xpath)) + foreach (object item in xml.SelectNodes(base.xpath)) { result = true; - XmlNode xmlNode = current as XmlNode; + XmlNode xmlNode = item as XmlNode; XmlNode parentNode = xmlNode.ParentNode; - if (this.order == PatchOperationInsert.Order.Append) + if (this.order == Order.Append) { for (int i = 0; i < node.ChildNodes.Count; i++) { parentNode.InsertAfter(parentNode.OwnerDocument.ImportNode(node.ChildNodes[i], true), xmlNode); } } - else if (this.order == PatchOperationInsert.Order.Prepend) + else if (this.order == Order.Prepend) { - for (int j = node.ChildNodes.Count - 1; j >= 0; j--) + for (int num = node.ChildNodes.Count - 1; num >= 0; num--) { - parentNode.InsertBefore(parentNode.OwnerDocument.ImportNode(node.ChildNodes[j], true), xmlNode); + parentNode.InsertBefore(parentNode.OwnerDocument.ImportNode(node.ChildNodes[num], true), xmlNode); } } } diff --git a/Assembly-CSharp/Verse/PatchOperationPathed.cs b/Assembly-CSharp/Verse/PatchOperationPathed.cs index 061943796..a0d728600 100644 --- a/Assembly-CSharp/Verse/PatchOperationPathed.cs +++ b/Assembly-CSharp/Verse/PatchOperationPathed.cs @@ -1,5 +1,3 @@ -using System; - namespace Verse { public abstract class PatchOperationPathed : PatchOperation diff --git a/Assembly-CSharp/Verse/PatchOperationRemove.cs b/Assembly-CSharp/Verse/PatchOperationRemove.cs index f912e68a8..e7e570a6f 100644 --- a/Assembly-CSharp/Verse/PatchOperationRemove.cs +++ b/Assembly-CSharp/Verse/PatchOperationRemove.cs @@ -1,4 +1,3 @@ -using System; using System.Xml; namespace Verse @@ -8,10 +7,10 @@ public class PatchOperationRemove : PatchOperationPathed protected override bool ApplyWorker(XmlDocument xml) { bool result = false; - foreach (object current in xml.SelectNodes(this.xpath)) + foreach (object item in xml.SelectNodes(base.xpath)) { result = true; - XmlNode xmlNode = current as XmlNode; + XmlNode xmlNode = item as XmlNode; xmlNode.ParentNode.RemoveChild(xmlNode); } return result; diff --git a/Assembly-CSharp/Verse/PatchOperationReplace.cs b/Assembly-CSharp/Verse/PatchOperationReplace.cs index 3bda8f972..519ef9851 100644 --- a/Assembly-CSharp/Verse/PatchOperationReplace.cs +++ b/Assembly-CSharp/Verse/PatchOperationReplace.cs @@ -1,4 +1,3 @@ -using System; using System.Xml; namespace Verse @@ -11,10 +10,10 @@ protected override bool ApplyWorker(XmlDocument xml) { XmlNode node = this.value.node; bool result = false; - foreach (object current in xml.SelectNodes(this.xpath)) + foreach (object item in xml.SelectNodes(base.xpath)) { result = true; - XmlNode xmlNode = current as XmlNode; + XmlNode xmlNode = item as XmlNode; XmlNode parentNode = xmlNode.ParentNode; for (int i = 0; i < node.ChildNodes.Count; i++) { diff --git a/Assembly-CSharp/Verse/PatchOperationSequence.cs b/Assembly-CSharp/Verse/PatchOperationSequence.cs index 2468dba5a..bb45fab33 100644 --- a/Assembly-CSharp/Verse/PatchOperationSequence.cs +++ b/Assembly-CSharp/Verse/PatchOperationSequence.cs @@ -10,13 +10,22 @@ public class PatchOperationSequence : PatchOperation protected override bool ApplyWorker(XmlDocument xml) { - foreach (PatchOperation current in this.operations) + List.Enumerator enumerator = this.operations.GetEnumerator(); + try { - if (!current.Apply(xml)) + while (enumerator.MoveNext()) { - return false; + PatchOperation current = enumerator.Current; + if (!current.Apply(xml)) + { + return false; + } } } + finally + { + ((IDisposable)(object)enumerator).Dispose(); + } return true; } } diff --git a/Assembly-CSharp/Verse/PatchOperationSetName.cs b/Assembly-CSharp/Verse/PatchOperationSetName.cs index 5270be796..f9d0a0c81 100644 --- a/Assembly-CSharp/Verse/PatchOperationSetName.cs +++ b/Assembly-CSharp/Verse/PatchOperationSetName.cs @@ -1,4 +1,3 @@ -using System; using System.Xml; namespace Verse @@ -10,9 +9,9 @@ public class PatchOperationSetName : PatchOperationPathed protected override bool ApplyWorker(XmlDocument xml) { bool result = false; - foreach (object current in xml.SelectNodes(this.xpath)) + foreach (object item in xml.SelectNodes(base.xpath)) { - XmlNode xmlNode = current as XmlNode; + XmlNode xmlNode = item as XmlNode; XmlNode xmlNode2 = xmlNode.OwnerDocument.CreateElement(this.name); xmlNode2.InnerXml = xmlNode.InnerXml; xmlNode.ParentNode.InsertBefore(xmlNode2, xmlNode); diff --git a/Assembly-CSharp/Verse/PatchOperationTest.cs b/Assembly-CSharp/Verse/PatchOperationTest.cs index 1f60d8ca4..85ce11399 100644 --- a/Assembly-CSharp/Verse/PatchOperationTest.cs +++ b/Assembly-CSharp/Verse/PatchOperationTest.cs @@ -1,4 +1,3 @@ -using System; using System.Xml; namespace Verse @@ -7,7 +6,7 @@ public class PatchOperationTest : PatchOperationPathed { protected override bool ApplyWorker(XmlDocument xml) { - return xml.SelectSingleNode(this.xpath) != null; + return xml.SelectSingleNode(base.xpath) != null; } } } diff --git a/Assembly-CSharp/Verse/Pawn.cs b/Assembly-CSharp/Verse/Pawn.cs index 19323f678..9aff0c5a2 100644 --- a/Assembly-CSharp/Verse/Pawn.cs +++ b/Assembly-CSharp/Verse/Pawn.cs @@ -2,7 +2,6 @@ using RimWorld.Planet; using System; using System.Collections.Generic; -using System.Diagnostics; using System.Linq; using System.Text; using UnityEngine; @@ -139,7 +138,7 @@ public RaceProperties RaceProps { get { - return this.def.race; + return base.def.race; } } @@ -187,7 +186,11 @@ public bool InMentalState { get { - return !this.Dead && this.mindState.mentalStateHandler.InMentalState; + if (this.Dead) + { + return false; + } + return this.mindState.mentalStateHandler.InMentalState; } } @@ -219,7 +222,11 @@ public bool InAggroMentalState { get { - return !this.Dead && this.mindState.mentalStateHandler.InMentalState && this.mindState.mentalStateHandler.CurStateDef.IsAggro; + if (this.Dead) + { + return false; + } + return this.mindState.mentalStateHandler.InMentalState && this.mindState.mentalStateHandler.CurStateDef.IsAggro; } } @@ -243,7 +250,7 @@ public List VerbProperties { get { - return this.def.Verbs; + return base.def.Verbs; } } @@ -311,11 +318,7 @@ public IEnumerable IngredientStackCells { get { - Pawn.<>c__Iterator219 <>c__Iterator = new Pawn.<>c__Iterator219(); - <>c__Iterator.<>f__this = this; - Pawn.<>c__Iterator219 expr_0E = <>c__Iterator; - expr_0E.$PC = -2; - return expr_0E; + yield return this.InteractionCell; } } @@ -356,15 +359,15 @@ public override string LabelNoCount { get { - if (this.Name == null) - { - return this.KindLabel; - } - if (this.story == null || (this.story.adulthood == null && this.story.childhood == null)) + if (this.Name != null) { + if (this.story != null && (this.story.adulthood != null || this.story.childhood != null)) + { + return this.Name.ToStringShort + ", " + this.story.TitleShort; + } return this.Name.ToStringShort; } - return this.Name.ToStringShort + ", " + this.story.TitleShort; + return this.KindLabel; } } @@ -425,61 +428,37 @@ public override IntVec3 InteractionCell position3.z++; position4.z--; } - if (position.Standable(base.Map)) + if (position.Standable(base.Map) && position.GetThingList(base.Map).Find((Predicate)((Thing x) => x.def.IsBed)) == null && position.GetDoor(base.Map) == null) { - if (position.GetThingList(base.Map).Find((Thing x) => x.def.IsBed) == null && position.GetDoor(base.Map) == null) - { - return position; - } + return position; } - if (position2.Standable(base.Map)) + if (position2.Standable(base.Map) && position2.GetThingList(base.Map).Find((Predicate)((Thing x) => x.def.IsBed)) == null && position2.GetDoor(base.Map) == null) { - if (position2.GetThingList(base.Map).Find((Thing x) => x.def.IsBed) == null && position2.GetDoor(base.Map) == null) - { - return position2; - } + return position2; } - if (position3.Standable(base.Map)) + if (position3.Standable(base.Map) && position3.GetThingList(base.Map).Find((Predicate)((Thing x) => x.def.IsBed)) == null && position3.GetDoor(base.Map) == null) { - if (position3.GetThingList(base.Map).Find((Thing x) => x.def.IsBed) == null && position3.GetDoor(base.Map) == null) - { - return position3; - } + return position3; } - if (position4.Standable(base.Map)) + if (position4.Standable(base.Map) && position4.GetThingList(base.Map).Find((Predicate)((Thing x) => x.def.IsBed)) == null && position4.GetDoor(base.Map) == null) { - if (position4.GetThingList(base.Map).Find((Thing x) => x.def.IsBed) == null && position4.GetDoor(base.Map) == null) - { - return position4; - } + return position4; } - if (position.Standable(base.Map)) + if (position.Standable(base.Map) && position.GetThingList(base.Map).Find((Predicate)((Thing x) => x.def.IsBed)) == null) { - if (position.GetThingList(base.Map).Find((Thing x) => x.def.IsBed) == null) - { - return position; - } + return position; } - if (position2.Standable(base.Map)) + if (position2.Standable(base.Map) && position2.GetThingList(base.Map).Find((Predicate)((Thing x) => x.def.IsBed)) == null) { - if (position2.GetThingList(base.Map).Find((Thing x) => x.def.IsBed) == null) - { - return position2; - } + return position2; } - if (position3.Standable(base.Map)) + if (position3.Standable(base.Map) && position3.GetThingList(base.Map).Find((Predicate)((Thing x) => x.def.IsBed)) == null) { - if (position3.GetThingList(base.Map).Find((Thing x) => x.def.IsBed) == null) - { - return position3; - } + return position3; } - if (position4.Standable(base.Map)) + if (position4.Standable(base.Map) && position4.GetThingList(base.Map).Find((Predicate)((Thing x) => x.def.IsBed)) == null) { - if (position4.GetThingList(base.Map).Find((Thing x) => x.def.IsBed) == null) - { - return position4; - } + return position4; } if (position.Standable(base.Map)) { @@ -575,11 +554,11 @@ public LocalTargetInfo TargetCurrentlyAimingAt return LocalTargetInfo.Invalid; } Stance curStance = this.stances.curStance; - if (curStance is Stance_Warmup || curStance is Stance_Cooldown) + if (!(curStance is Stance_Warmup) && !(curStance is Stance_Cooldown)) { - return ((Stance_Busy)curStance).focusTarg; + return LocalTargetInfo.Invalid; } - return LocalTargetInfo.Invalid; + return ((Stance_Busy)curStance).focusTarg; } } @@ -632,11 +611,11 @@ public override IEnumerable SpecialDisplayStats { get { - Pawn.<>c__Iterator21D <>c__Iterator21D = new Pawn.<>c__Iterator21D(); - <>c__Iterator21D.<>f__this = this; - Pawn.<>c__Iterator21D expr_0E = <>c__Iterator21D; - expr_0E.$PC = -2; - return expr_0E; + foreach (StatDrawEntry specialDisplayStat in base.SpecialDisplayStats) + { + yield return specialDisplayStat; + } + yield return new StatDrawEntry(StatCategoryDefOf.BasicsPawn, "BodySize".Translate(), this.BodySize.ToString("F2"), 0); } } @@ -677,124 +656,124 @@ public override void ExposeData() Scribe_Defs.Look(ref this.kindDef, "kindDef"); Scribe_Values.Look(ref this.gender, "gender", Gender.Male, false); Scribe_Deep.Look(ref this.nameInt, "name", new object[0]); - Scribe_Deep.Look(ref this.mindState, "mindState", new object[] + Scribe_Deep.Look(ref this.mindState, "mindState", new object[1] { this }); - Scribe_Deep.Look(ref this.jobs, "jobs", new object[] + Scribe_Deep.Look(ref this.jobs, "jobs", new object[1] { this }); - Scribe_Deep.Look(ref this.stances, "stances", new object[] + Scribe_Deep.Look(ref this.stances, "stances", new object[1] { this }); - Scribe_Deep.Look(ref this.verbTracker, "verbTracker", new object[] + Scribe_Deep.Look(ref this.verbTracker, "verbTracker", new object[1] { this }); - Scribe_Deep.Look(ref this.natives, "natives", new object[] + Scribe_Deep.Look(ref this.natives, "natives", new object[1] { this }); - Scribe_Deep.Look(ref this.meleeVerbs, "meleeVerbs", new object[] + Scribe_Deep.Look(ref this.meleeVerbs, "meleeVerbs", new object[1] { this }); - Scribe_Deep.Look(ref this.pather, "pather", new object[] + Scribe_Deep.Look(ref this.pather, "pather", new object[1] { this }); - Scribe_Deep.Look(ref this.carryTracker, "carryTracker", new object[] + Scribe_Deep.Look(ref this.carryTracker, "carryTracker", new object[1] { this }); - Scribe_Deep.Look(ref this.apparel, "apparel", new object[] + Scribe_Deep.Look(ref this.apparel, "apparel", new object[1] { this }); - Scribe_Deep.Look(ref this.story, "story", new object[] + Scribe_Deep.Look(ref this.story, "story", new object[1] { this }); - Scribe_Deep.Look(ref this.equipment, "equipment", new object[] + Scribe_Deep.Look(ref this.equipment, "equipment", new object[1] { this }); - Scribe_Deep.Look(ref this.drafter, "drafter", new object[] + Scribe_Deep.Look(ref this.drafter, "drafter", new object[1] { this }); - Scribe_Deep.Look(ref this.ageTracker, "ageTracker", new object[] + Scribe_Deep.Look(ref this.ageTracker, "ageTracker", new object[1] { this }); - Scribe_Deep.Look(ref this.health, "healthTracker", new object[] + Scribe_Deep.Look(ref this.health, "healthTracker", new object[1] { this }); - Scribe_Deep.Look(ref this.records, "records", new object[] + Scribe_Deep.Look(ref this.records, "records", new object[1] { this }); - Scribe_Deep.Look(ref this.inventory, "inventory", new object[] + Scribe_Deep.Look(ref this.inventory, "inventory", new object[1] { this }); - Scribe_Deep.Look(ref this.filth, "filth", new object[] + Scribe_Deep.Look(ref this.filth, "filth", new object[1] { this }); - Scribe_Deep.Look(ref this.needs, "needs", new object[] + Scribe_Deep.Look(ref this.needs, "needs", new object[1] { this }); - Scribe_Deep.Look(ref this.guest, "guest", new object[] + Scribe_Deep.Look(ref this.guest, "guest", new object[1] { this }); Scribe_Deep.Look(ref this.guilt, "guilt", new object[0]); - Scribe_Deep.Look(ref this.relations, "social", new object[] + Scribe_Deep.Look(ref this.relations, "social", new object[1] { this }); - Scribe_Deep.Look(ref this.ownership, "ownership", new object[] + Scribe_Deep.Look(ref this.ownership, "ownership", new object[1] { this }); - Scribe_Deep.Look(ref this.interactions, "interactions", new object[] + Scribe_Deep.Look(ref this.interactions, "interactions", new object[1] { this }); - Scribe_Deep.Look(ref this.skills, "skills", new object[] + Scribe_Deep.Look(ref this.skills, "skills", new object[1] { this }); - Scribe_Deep.Look(ref this.workSettings, "workSettings", new object[] + Scribe_Deep.Look(ref this.workSettings, "workSettings", new object[1] { this }); - Scribe_Deep.Look(ref this.trader, "trader", new object[] + Scribe_Deep.Look(ref this.trader, "trader", new object[1] { this }); - Scribe_Deep.Look(ref this.outfits, "outfits", new object[] + Scribe_Deep.Look(ref this.outfits, "outfits", new object[1] { this }); - Scribe_Deep.Look(ref this.drugs, "drugs", new object[] + Scribe_Deep.Look(ref this.drugs, "drugs", new object[1] { this }); - Scribe_Deep.Look(ref this.timetable, "timetable", new object[] + Scribe_Deep.Look(ref this.timetable, "timetable", new object[1] { this }); - Scribe_Deep.Look(ref this.playerSettings, "playerSettings", new object[] + Scribe_Deep.Look(ref this.playerSettings, "playerSettings", new object[1] { this }); - Scribe_Deep.Look(ref this.training, "training", new object[] + Scribe_Deep.Look(ref this.training, "training", new object[1] { this }); @@ -806,7 +785,7 @@ public override string ToString() { return this.NameStringShort; } - if (this.thingIDNumber > 0) + if (base.thingIDNumber > 0) { return base.ThingID; } @@ -814,7 +793,7 @@ public override string ToString() { return this.KindLabel + "_" + base.ThingID; } - if (this.def != null) + if (base.def != null) { return base.ThingID; } @@ -829,31 +808,35 @@ public override void SpawnSetup(Map map, bool respawningAfterLoad) Corpse corpse = (Corpse)ThingMaker.MakeThing(this.RaceProps.corpseDef, null); corpse.InnerPawn = this; GenSpawn.Spawn(corpse, base.Position, map); - return; - } - base.SpawnSetup(map, respawningAfterLoad); - if (Find.WorldPawns.Contains(this)) - { - Find.WorldPawns.RemovePawn(this); - } - PawnComponentsUtility.AddComponentsForSpawn(this); - if (!PawnUtility.InValidState(this)) - { - Log.Error("Pawn " + this.ToString() + " spawned in invalid state. Destroying..."); - this.Destroy(DestroyMode.Vanish); - return; - } - this.Drawer.Notify_Spawned(); - this.pather.ResetToCurrentPosition(); - base.Map.mapPawns.RegisterPawn(this); - if (this.RaceProps.IsFlesh) - { - this.relations.everSeenByPlayer = true; } - AddictionUtility.CheckDrugAddictionTeachOpportunity(this); - if (this.needs != null && this.needs.mood != null && this.needs.mood.recentMemory != null) + else { - this.needs.mood.recentMemory.Notify_Spawned(respawningAfterLoad); + base.SpawnSetup(map, respawningAfterLoad); + if (Find.WorldPawns.Contains(this)) + { + Find.WorldPawns.RemovePawn(this); + } + PawnComponentsUtility.AddComponentsForSpawn(this); + if (!PawnUtility.InValidState(this)) + { + Log.Error("Pawn " + this.ToString() + " spawned in invalid state. Destroying..."); + this.Destroy(DestroyMode.Vanish); + } + else + { + this.Drawer.Notify_Spawned(); + this.pather.ResetToCurrentPosition(); + base.Map.mapPawns.RegisterPawn(this); + if (this.RaceProps.IsFlesh) + { + this.relations.everSeenByPlayer = true; + } + AddictionUtility.CheckDrugAddictionTeachOpportunity(this); + if (this.needs != null && this.needs.mood != null && this.needs.mood.recentMemory != null) + { + this.needs.mood.recentMemory.Notify_Spawned(respawningAfterLoad); + } + } } } @@ -896,7 +879,7 @@ public override void TickRare() } if (base.Spawned && this.RaceProps.IsFlesh) { - GenTemperature.PushHeat(this, 0.3f * this.BodySize * 4.16666651f); + GenTemperature.PushHeat(this, (float)(0.30000001192092896 * this.BodySize * 4.1666665077209473)); } } @@ -905,84 +888,86 @@ public override void Tick() if (DebugSettings.noAnimals && base.Spawned && this.RaceProps.Animal) { this.Destroy(DestroyMode.Vanish); - return; } - base.Tick(); - if (Find.TickManager.TicksGame % 250 == 0) - { - this.TickRare(); - } - if (!ThingOwnerUtility.ContentsFrozen(base.ParentHolder)) + else { - if (base.Spawned) - { - this.pather.PatherTick(); - } - if (base.Spawned) - { - this.stances.StanceTrackerTick(); - this.verbTracker.VerbsTick(); - this.natives.NativeVerbsTick(); - } - if (base.Spawned) + base.Tick(); + if (Find.TickManager.TicksGame % 250 == 0) { - this.jobs.JobTrackerTick(); + this.TickRare(); } - if (base.Spawned) + if (!ThingOwnerUtility.ContentsFrozen(base.ParentHolder)) { - this.Drawer.DrawTrackerTick(); + if (base.Spawned) + { + this.pather.PatherTick(); + } + if (base.Spawned) + { + this.stances.StanceTrackerTick(); + this.verbTracker.VerbsTick(); + this.natives.NativeVerbsTick(); + } + if (base.Spawned) + { + this.jobs.JobTrackerTick(); + } + if (base.Spawned) + { + this.Drawer.DrawTrackerTick(); + } + this.health.HealthTick(); + if (!this.Dead) + { + this.mindState.MindStateTick(); + this.carryTracker.CarryHandsTick(); + } } - this.health.HealthTick(); if (!this.Dead) { - this.mindState.MindStateTick(); - this.carryTracker.CarryHandsTick(); + this.needs.NeedsTrackerTick(); } - } - if (!this.Dead) - { - this.needs.NeedsTrackerTick(); - } - if (!ThingOwnerUtility.ContentsFrozen(base.ParentHolder)) - { - if (this.equipment != null) - { - this.equipment.EquipmentTrackerTick(); - } - if (this.apparel != null) - { - this.apparel.ApparelTrackerTick(); - } - if (this.interactions != null) + if (!ThingOwnerUtility.ContentsFrozen(base.ParentHolder)) { - this.interactions.InteractionsTrackerTick(); - } - if (this.caller != null) - { - this.caller.CallTrackerTick(); - } - if (this.skills != null) - { - this.skills.SkillsTick(); - } - if (this.inventory != null) - { - this.inventory.InventoryTrackerTick(); - } - if (this.drafter != null) - { - this.drafter.DraftControllerTick(); - } - if (this.relations != null) - { - this.relations.SocialTrackerTick(); - } - if (this.RaceProps.Humanlike) - { - this.guest.GuestTrackerTick(); + if (this.equipment != null) + { + this.equipment.EquipmentTrackerTick(); + } + if (this.apparel != null) + { + this.apparel.ApparelTrackerTick(); + } + if (this.interactions != null) + { + this.interactions.InteractionsTrackerTick(); + } + if (this.caller != null) + { + this.caller.CallTrackerTick(); + } + if (this.skills != null) + { + this.skills.SkillsTick(); + } + if (this.inventory != null) + { + this.inventory.InventoryTrackerTick(); + } + if (this.drafter != null) + { + this.drafter.DraftControllerTick(); + } + if (this.relations != null) + { + this.relations.SocialTrackerTick(); + } + if (this.RaceProps.Humanlike) + { + this.guest.GuestTrackerTick(); + } + this.ageTracker.AgeTick(); + this.records.RecordsTick(); } - this.ageTracker.AgeTick(); - this.records.RecordsTick(); } } @@ -999,11 +984,10 @@ public void Notify_Teleported(bool endCurrentJob = true) public override void PreApplyDamage(DamageInfo dinfo, out bool absorbed) { base.PreApplyDamage(dinfo, out absorbed); - if (absorbed) + if (!absorbed) { - return; + this.health.PreApplyDamage(dinfo, out absorbed); } - this.health.PreApplyDamage(dinfo, out absorbed); } public override void PostApplyDamage(DamageInfo dinfo, float totalDamageDealt) @@ -1017,11 +1001,11 @@ public override void PostApplyDamage(DamageInfo dinfo, float totalDamageDealt) public override Thing SplitOff(int count) { - if (count <= 0 || count >= this.stackCount) + if (count > 0 && count < base.stackCount) { - return base.SplitOff(count); + throw new NotImplementedException("Split off on Pawns is not supported (unless we're taking a full stack)."); } - throw new NotImplementedException("Split off on Pawns is not supported (unless we're taking a full stack)."); + return base.SplitOff(count); } private int TicksPerMove(bool diagonal) @@ -1029,28 +1013,28 @@ private int TicksPerMove(bool diagonal) float num = this.GetStatValue(StatDefOf.MoveSpeed, true); if (RestraintsUtility.InRestraints(this)) { - num *= 0.35f; + num = (float)(num * 0.34999999403953552); } if (this.carryTracker != null && this.carryTracker.CarriedThing != null && this.carryTracker.CarriedThing.def.category == ThingCategory.Pawn) { - num *= 0.6f; + num = (float)(num * 0.60000002384185791); } - float num2 = num / 60f; + float num2 = (float)(num / 60.0); float num3; - if (num2 == 0f) + if (num2 == 0.0) { num3 = 450f; } else { - num3 = 1f / num2; + num3 = (float)(1.0 / num2); if (base.Spawned && !base.Map.roofGrid.Roofed(base.Position)) { num3 /= base.Map.weatherManager.CurMoveSpeedMultiplier; } if (diagonal) { - num3 *= 1.41421f; + num3 = (float)(num3 * 1.4142099618911743); } } int value = Mathf.RoundToInt(num3); @@ -1080,7 +1064,7 @@ public override void Kill(DamageInfo? dinfo) bool inContainerEnclosed = this.InContainerEnclosed; if (inContainerEnclosed) { - thingOwner = this.holdingOwner; + thingOwner = base.holdingOwner; thingOwner.Remove(this); } bool flag3 = false; @@ -1105,7 +1089,7 @@ public override void Kill(DamageInfo? dinfo) } if (flag && dinfo.HasValue && dinfo.Value.Def.externalViolence) { - LifeStageUtility.PlayNearestLifestageSound(this, (LifeStageAge ls) => ls.soundDeath, 1f); + LifeStageUtility.PlayNearestLifestageSound(this, (Func)((LifeStageAge ls) => ls.soundDeath), 1f); } if (dinfo.HasValue && dinfo.Value.Instigator != null) { @@ -1122,38 +1106,22 @@ public override void Kill(DamageInfo? dinfo) { if (pawn2 != null) { - if (base.Faction != Faction.OfPlayer && this.kindDef.combatPower >= 250f && pawn2.Faction == Faction.OfPlayer) + if (base.Faction != Faction.OfPlayer && this.kindDef.combatPower >= 250.0 && pawn2.Faction == Faction.OfPlayer) { - TaleRecorder.RecordTale(TaleDefOf.KilledMajorColonyEnemy, new object[] - { - pawn2, - this - }); + TaleRecorder.RecordTale(TaleDefOf.KilledMajorColonyEnemy, pawn2, this); } else if (this.IsColonist) { - TaleRecorder.RecordTale(TaleDefOf.KilledColonist, new object[] - { - pawn2, - this - }); + TaleRecorder.RecordTale(TaleDefOf.KilledColonist, pawn2, this); } else if (base.Faction == Faction.OfPlayer && this.RaceProps.Animal) { - TaleRecorder.RecordTale(TaleDefOf.KilledColonyAnimal, new object[] - { - pawn2, - this - }); + TaleRecorder.RecordTale(TaleDefOf.KilledColonyAnimal, pawn2, this); } } if (base.Faction == Faction.OfPlayer && (this.RaceProps.Humanlike || dinfo.Value.Instigator == null || dinfo.Value.Instigator.Faction != Faction.OfPlayer)) { - TaleRecorder.RecordTale(TaleDefOf.KilledBy, new object[] - { - this, - dinfo.Value - }); + TaleRecorder.RecordTale(TaleDefOf.KilledBy, this, dinfo.Value); } } } @@ -1168,8 +1136,8 @@ public override void Kill(DamageInfo? dinfo) } this.meleeVerbs.Notify_PawnKilled(); Pawn_CarryTracker pawn_CarryTracker = base.ParentHolder as Pawn_CarryTracker; - Thing thing; - if (pawn_CarryTracker != null && this.holdingOwner.TryDrop(this, pawn_CarryTracker.pawn.Position, pawn_CarryTracker.pawn.Map, ThingPlaceMode.Near, out thing, null)) + Thing thing = default(Thing); + if (pawn_CarryTracker != null && base.holdingOwner.TryDrop((Thing)this, pawn_CarryTracker.pawn.Position, pawn_CarryTracker.pawn.Map, ThingPlaceMode.Near, out thing, (Action)null)) { map = pawn_CarryTracker.pawn.Map; flag = true; @@ -1202,9 +1170,9 @@ public override void Kill(DamageInfo? dinfo) } else if (spawnedOrAnyParentSpawned) { - if (this.holdingOwner != null) + if (base.holdingOwner != null) { - this.holdingOwner.Remove(this); + base.holdingOwner.Remove(this); } corpse = this.MakeCorpse(assignedGrave, flag2, bedRotation); if (GenPlace.TryPlaceThing(corpse, positionHeld, mapHeld, ThingPlaceMode.Direct, null)) @@ -1212,13 +1180,13 @@ public override void Kill(DamageInfo? dinfo) corpse.Rotation = base.Rotation; if (HuntJobUtility.WasKilledByHunter(this, dinfo)) { - ((Pawn)dinfo.Value.Instigator).Reserve(corpse, 1, -1, null); + ((Pawn)dinfo.Value.Instigator).Reserve((Thing)corpse, 1, -1, null); } else if (!flag3) { corpse.SetForbiddenIfOutsideHomeArea(); } - if (num > 0f) + if (num > 0.0) { FireUtility.TryStartFireIn(corpse.Position, corpse.Map, num); } @@ -1229,7 +1197,7 @@ public override void Kill(DamageInfo? dinfo) corpse = null; } } - else if (this.holdingOwner != null || this.IsWorldPawn()) + else if (base.holdingOwner != null || this.IsWorldPawn()) { Corpse.PostCorpseDestroy(this); } @@ -1276,16 +1244,9 @@ public override void Kill(DamageInfo? dinfo) public override void Destroy(DestroyMode mode = DestroyMode.Vanish) { - if (mode != DestroyMode.Vanish && mode != DestroyMode.KillFinalize) + if (mode != 0 && mode != DestroyMode.KillFinalize) { - Log.Error(string.Concat(new object[] - { - "Destroyed pawn ", - this, - " with unsupported mode ", - mode, - "." - })); + Log.Error("Destroyed pawn " + this + " with unsupported mode " + mode + "."); } base.Destroy(mode); Find.WorldPawns.Notify_PawnDestroyed(this); @@ -1300,17 +1261,17 @@ public override void Destroy(DestroyMode mode = DestroyMode.Vanish) Lord lord = this.GetLord(); if (lord != null) { - PawnLostCondition cond = (mode != DestroyMode.KillFinalize) ? PawnLostCondition.Vanished : PawnLostCondition.IncappedOrKilled; + PawnLostCondition cond = (PawnLostCondition)((mode != DestroyMode.KillFinalize) ? 1 : 2); lord.Notify_PawnLost(this, cond); } Find.GameEnder.CheckGameOver(); Find.TaleManager.Notify_PawnDestroyed(this); } - foreach (Pawn current in from p in PawnsFinder.AllMapsAndWorld_Alive + foreach (Pawn item in from p in PawnsFinder.AllMapsAndWorld_Alive where p.playerSettings != null && p.playerSettings.master == this select p) { - current.playerSettings.master = null; + item.playerSettings.master = null; } if (mode != DestroyMode.KillFinalize) { @@ -1357,24 +1318,26 @@ public override void Discard() if (Find.WorldPawns.Contains(this)) { Log.Warning("Tried to discard a world pawn " + this + "."); - return; - } - base.Discard(); - if (this.relations != null) - { - this.relations.ClearAllRelations(); } - if (Current.ProgramState == ProgramState.Playing) + else { - Find.PlayLog.Notify_PawnDiscarded(this); - Find.TaleManager.Notify_PawnDiscarded(this); + base.Discard(); + if (this.relations != null) + { + this.relations.ClearAllRelations(); + } + if (Current.ProgramState == ProgramState.Playing) + { + Find.PlayLog.Notify_PawnDiscarded(this); + Find.TaleManager.Notify_PawnDiscarded(this); + } + Corpse.PostCorpseDestroy(this); } - Corpse.PostCorpseDestroy(this); } private Corpse MakeCorpse(Building_Grave assignedGrave, bool inBed, float bedRotation) { - if (this.holdingOwner != null) + if (base.holdingOwner != null) { Log.Warning("We can't make corpse because the pawn is in a ThingOwner. Remove him from the container first. This should have been already handled before calling this method. holder=" + base.ParentHolder); return null; @@ -1387,7 +1350,7 @@ private Corpse MakeCorpse(Building_Grave assignedGrave, bool inBed, float bedRot } if (inBed) { - corpse.InnerPawn.Drawer.renderer.wiggler.SetToCustomRotation(bedRotation + 180f); + corpse.InnerPawn.Drawer.renderer.wiggler.SetToCustomRotation((float)(bedRotation + 180.0)); } return corpse; } @@ -1397,71 +1360,67 @@ public void ExitMap(bool allowedToJoinOrCreateCaravan) if (this.IsWorldPawn()) { Log.Warning("Called ExitMap() on world pawn " + this); - return; } - if (allowedToJoinOrCreateCaravan && CaravanExitMapUtility.CanExitMapAndJoinOrCreateCaravanNow(this)) + else if (allowedToJoinOrCreateCaravan && CaravanExitMapUtility.CanExitMapAndJoinOrCreateCaravanNow(this)) { CaravanExitMapUtility.ExitMapAndJoinOrCreateCaravan(this); - return; - } - Lord lord = this.GetLord(); - if (lord != null) - { - lord.Notify_PawnLost(this, PawnLostCondition.ExitedMap); } - if (this.carryTracker != null && this.carryTracker.CarriedThing != null) + else { - Pawn pawn = this.carryTracker.CarriedThing as Pawn; - if (pawn != null) + Lord lord = this.GetLord(); + if (lord != null) { - if (base.Faction != null && base.Faction != pawn.Faction) + lord.Notify_PawnLost(this, PawnLostCondition.ExitedMap); + } + if (this.carryTracker != null && this.carryTracker.CarriedThing != null) + { + Pawn pawn = this.carryTracker.CarriedThing as Pawn; + if (pawn != null) { - base.Faction.kidnapped.KidnapPawn(pawn, this); + if (base.Faction != null && base.Faction != pawn.Faction) + { + base.Faction.kidnapped.KidnapPawn(pawn, this); + } + else + { + this.carryTracker.innerContainer.Remove(pawn); + pawn.ExitMap(false); + } } else { - this.carryTracker.innerContainer.Remove(pawn); - pawn.ExitMap(false); + this.carryTracker.CarriedThing.Destroy(DestroyMode.Vanish); } + this.carryTracker.innerContainer.Clear(); } - else + bool flag = !this.IsCaravanMember() && !PawnUtility.IsTravelingInTransportPodWorldObject(this); + if (flag && this.HostFaction != null && this.guest != null && (this.guest.released || !this.IsPrisoner) && !this.InMentalState && this.health.hediffSet.BleedRateTotal < 0.0010000000474974513 && base.Faction.def.appreciative && !base.Faction.def.hidden) { - this.carryTracker.CarriedThing.Destroy(DestroyMode.Vanish); + float num = 15f; + if (PawnUtility.IsFactionLeader(this)) + { + num = (float)(num + 50.0); + } + Messages.Message("MessagePawnExitMapRelationsGain".Translate(this.LabelShort, base.Faction.Name, num.ToString("F0")), MessageSound.Benefit); + base.Faction.AffectGoodwillWith(this.HostFaction, num); } - this.carryTracker.innerContainer.Clear(); - } - bool flag = !this.IsCaravanMember() && !PawnUtility.IsTravelingInTransportPodWorldObject(this); - if (flag && this.HostFaction != null && this.guest != null && (this.guest.released || !this.IsPrisoner) && !this.InMentalState && this.health.hediffSet.BleedRateTotal < 0.001f && base.Faction.def.appreciative && !base.Faction.def.hidden) - { - float num = 15f; - if (PawnUtility.IsFactionLeader(this)) + if (this.ownership != null) { - num += 50f; + this.ownership.UnclaimAll(); } - Messages.Message("MessagePawnExitMapRelationsGain".Translate(new object[] + if (this.guest != null && flag) { - this.LabelShort, - base.Faction.Name, - num.ToString("F0") - }), MessageSound.Benefit); - base.Faction.AffectGoodwillWith(this.HostFaction, num); - } - if (this.ownership != null) - { - this.ownership.UnclaimAll(); - } - if (this.guest != null && flag) - { - this.guest.SetGuestStatus(null, false); - } - if (base.Spawned) - { - this.DeSpawn(); + this.guest.SetGuestStatus(null, false); + } + if (base.Spawned) + { + this.DeSpawn(); + } + this.inventory.UnloadEverything = false; + this.ClearMind(false); + this.ClearReservations(true); + Find.WorldPawns.PassToWorld(this, PawnDiscardDecideMode.Decide); } - this.inventory.UnloadEverything = false; - this.ClearMind(false); - this.ClearReservations(true); - Find.WorldPawns.PassToWorld(this, PawnDiscardDecideMode.Decide); } public override void PreTraded(TradeAction action, Pawn playerNegotiator, ITrader trader) @@ -1479,20 +1438,18 @@ public override void PreTraded(TradeAction action, Pawn playerNegotiator, ITrade { this.guest.SetGuestStatus(null, false); } - if (action == TradeAction.PlayerBuys) + switch (action) + { + case TradeAction.PlayerBuys: { this.SetFaction(Faction.OfPlayer, null); + break; } - else if (action == TradeAction.PlayerSells) + case TradeAction.PlayerSells: { if (this.RaceProps.Humanlike) { - TaleRecorder.RecordTale(TaleDefOf.SoldPrisoner, new object[] - { - playerNegotiator, - this, - trader - }); + TaleRecorder.RecordTale(TaleDefOf.SoldPrisoner, playerNegotiator, this, trader); } if (base.Faction != null) { @@ -1504,13 +1461,15 @@ public override void PreTraded(TradeAction action, Pawn playerNegotiator, ITrade } if (this.RaceProps.Humanlike) { - foreach (Pawn current in from x in PawnsFinder.AllMapsCaravansAndTravelingTransportPods + foreach (Pawn item in from x in PawnsFinder.AllMapsCaravansAndTravelingTransportPods where x.IsColonist || x.IsPrisonerOfColony select x) { - current.needs.mood.thoughts.memories.TryGainMemory(ThoughtDefOf.KnowPrisonerSold, null); + item.needs.mood.thoughts.memories.TryGainMemory(ThoughtDefOf.KnowPrisonerSold, null); } } + break; + } } this.ClearMind(false); this.ClearReservations(true); @@ -1520,11 +1479,7 @@ public void PreKidnapped(Pawn kidnapper) { if (this.IsColonist && kidnapper != null) { - TaleRecorder.RecordTale(TaleDefOf.KidnappedColonist, new object[] - { - kidnapper, - this - }); + TaleRecorder.RecordTale(TaleDefOf.KidnappedColonist, kidnapper, this); } if (this.ownership != null) { @@ -1546,85 +1501,81 @@ public override void SetFaction(Faction newFaction, Pawn recruiter = null) { if (newFaction == base.Faction) { - Log.Warning(string.Concat(new object[] - { - "Used SetFaction to change ", - this, - " to same faction ", - newFaction - })); - return; + Log.Warning("Used SetFaction to change " + this + " to same faction " + newFaction); } - if (this.guest != null) - { - this.guest.SetGuestStatus(null, false); - } - if (base.Spawned) - { - base.Map.mapPawns.DeRegisterPawn(this); - base.Map.pawnDestinationManager.UnreserveAllFor(this); - base.Map.designationManager.RemoveAllDesignationsOn(this, false); - } - if (newFaction == Faction.OfPlayer || base.Faction == Faction.OfPlayer) - { - Find.ColonistBar.MarkColonistsDirty(); - } - Lord lord = this.GetLord(); - if (lord != null) - { - lord.Notify_PawnLost(this, PawnLostCondition.ChangedFaction); - } - if (base.Faction != null && base.Faction.leader == this) - { - base.Faction.Notify_LeaderLost(); - } - if (newFaction == Faction.OfPlayer && this.RaceProps.Humanlike) - { - this.kindDef = newFaction.def.basicMemberKind; - } - base.SetFaction(newFaction, null); - PawnComponentsUtility.AddAndRemoveDynamicComponents(this, false); - if (base.Faction != null && base.Faction.IsPlayer) + else { - if (this.workSettings != null) + if (this.guest != null) { - this.workSettings.EnableAndInitialize(); + this.guest.SetGuestStatus(null, false); + } + if (base.Spawned) + { + base.Map.mapPawns.DeRegisterPawn(this); + base.Map.pawnDestinationManager.UnreserveAllFor(this); + base.Map.designationManager.RemoveAllDesignationsOn(this, false); + } + if (newFaction == Faction.OfPlayer || base.Faction == Faction.OfPlayer) + { + Find.ColonistBar.MarkColonistsDirty(); + } + Lord lord = this.GetLord(); + if (lord != null) + { + lord.Notify_PawnLost(this, PawnLostCondition.ChangedFaction); + } + if (base.Faction != null && base.Faction.leader == this) + { + base.Faction.Notify_LeaderLost(); + } + if (newFaction == Faction.OfPlayer && this.RaceProps.Humanlike) + { + this.kindDef = newFaction.def.basicMemberKind; + } + base.SetFaction(newFaction, null); + PawnComponentsUtility.AddAndRemoveDynamicComponents(this, false); + if (base.Faction != null && base.Faction.IsPlayer) + { + if (this.workSettings != null) + { + this.workSettings.EnableAndInitialize(); + } + Find.Storyteller.intenderPopulation.Notify_PopulationGained(); + } + if (this.Drafted) + { + this.drafter.Drafted = false; + } + ReachabilityUtility.ClearCache(); + this.health.surgeryBills.Clear(); + if (base.Spawned) + { + base.Map.mapPawns.RegisterPawn(this); + } + this.GenerateNecessaryName(); + if (this.playerSettings != null) + { + this.playerSettings.ResetMedicalCare(); + } + this.ClearMind(true); + if (!this.Dead && this.needs.mood != null) + { + this.needs.mood.thoughts.situational.Notify_SituationalThoughtsDirty(); + } + if (base.Spawned) + { + base.Map.attackTargetsCache.UpdateTarget(this); + } + Find.GameEnder.CheckGameOver(); + AddictionUtility.CheckDrugAddictionTeachOpportunity(this); + if (this.needs != null) + { + this.needs.AddOrRemoveNeedsAsAppropriate(); + } + if (this.playerSettings != null) + { + this.playerSettings.Notify_FactionChanged(); } - Find.Storyteller.intenderPopulation.Notify_PopulationGained(); - } - if (this.Drafted) - { - this.drafter.Drafted = false; - } - ReachabilityUtility.ClearCache(); - this.health.surgeryBills.Clear(); - if (base.Spawned) - { - base.Map.mapPawns.RegisterPawn(this); - } - this.GenerateNecessaryName(); - if (this.playerSettings != null) - { - this.playerSettings.ResetMedicalCare(); - } - this.ClearMind(true); - if (!this.Dead && this.needs.mood != null) - { - this.needs.mood.thoughts.situational.Notify_SituationalThoughtsDirty(); - } - if (base.Spawned) - { - base.Map.attackTargetsCache.UpdateTarget(this); - } - Find.GameEnder.CheckGameOver(); - AddictionUtility.CheckDrugAddictionTeachOpportunity(this); - if (this.needs != null) - { - this.needs.AddOrRemoveNeedsAsAppropriate(); - } - if (this.playerSettings != null) - { - this.playerSettings.Notify_FactionChanged(); } } @@ -1665,53 +1616,48 @@ public void DropAndForbidEverything(bool keepInventoryAndEquipmentIfInBed = fals { if (this.carryTracker != null && this.carryTracker.CarriedThing != null) { - this.carryTracker.innerContainer.TryTransferToContainer(this.carryTracker.CarriedThing, this.holdingOwner, true); + this.carryTracker.innerContainer.TryTransferToContainer(this.carryTracker.CarriedThing, base.holdingOwner, true); } if (this.equipment != null && this.equipment.Primary != null) { - this.equipment.TryTransferEquipmentToContainer(this.equipment.Primary, this.holdingOwner); + this.equipment.TryTransferEquipmentToContainer(this.equipment.Primary, base.holdingOwner); } if (this.inventory != null) { - this.inventory.innerContainer.TryTransferAllToContainer(this.holdingOwner, true); + this.inventory.innerContainer.TryTransferAllToContainer(base.holdingOwner, true); } } else if (base.SpawnedOrAnyParentSpawned) { if (this.carryTracker != null && this.carryTracker.CarriedThing != null) { - Thing thing; - this.carryTracker.TryDropCarriedThing(base.PositionHeld, ThingPlaceMode.Near, out thing, null); + Thing thing = default(Thing); + this.carryTracker.TryDropCarriedThing(base.PositionHeld, ThingPlaceMode.Near, out thing, (Action)null); } - if (!keepInventoryAndEquipmentIfInBed || !this.InBed()) + if (keepInventoryAndEquipmentIfInBed && this.InBed()) + return; + if (this.equipment != null) { - if (this.equipment != null) - { - this.equipment.DropAllEquipment(base.PositionHeld, true); - } - if (this.inventory != null && this.inventory.innerContainer.TotalStackCount > 0) - { - this.inventory.DropAllNearPawn(base.PositionHeld, true, false); - } + this.equipment.DropAllEquipment(base.PositionHeld, true); + } + if (this.inventory != null && this.inventory.innerContainer.TotalStackCount > 0) + { + this.inventory.DropAllNearPawn(base.PositionHeld, true, false); } } } public void GenerateNecessaryName() { - if (base.Faction != Faction.OfPlayer || !this.RaceProps.Animal) - { - return; - } - if (this.Name == null || this.Name.Numerical) + if (base.Faction == Faction.OfPlayer && this.RaceProps.Animal && (this.Name == null || this.Name.Numerical)) { if (Rand.Value < this.RaceProps.nameOnTameChance) { - this.Name = PawnBioAndNameGenerator.GeneratePawnName(this, NameStyle.Full, null); + this.Name = PawnBioAndNameGenerator.GeneratePawnName(this, NameStyle.Full, (string)null); } else { - this.Name = PawnBioAndNameGenerator.GeneratePawnName(this, NameStyle.Numeric, null); + this.Name = PawnBioAndNameGenerator.GeneratePawnName(this, NameStyle.Numeric, (string)null); } } } @@ -1725,18 +1671,60 @@ public Verb TryGetAttackVerb(bool allowManualCastWeapons = false) return this.meleeVerbs.TryGetMeleeVerb(); } - [DebuggerHidden] public override IEnumerable ButcherProducts(Pawn butcher, float efficiency) { - Pawn.c__Iterator21A c__Iterator21A = new Pawn.c__Iterator21A(); - c__Iterator21A.butcher = butcher; - c__Iterator21A.efficiency = efficiency; - c__Iterator21A.<$>butcher = butcher; - c__Iterator21A.<$>efficiency = efficiency; - c__Iterator21A.<>f__this = this; - Pawn.c__Iterator21A expr_2A = c__Iterator21A; - expr_2A.$PC = -2; - return expr_2A; + foreach (Thing item in base.ButcherProducts(butcher, efficiency)) + { + yield return item; + } + if (this.RaceProps.meatDef != null) + { + int meatCount = GenMath.RoundRandom(this.GetStatValue(StatDefOf.MeatAmount, true) * efficiency); + if (meatCount > 0) + { + Thing meat = ThingMaker.MakeThing(this.RaceProps.meatDef, null); + meat.stackCount = meatCount; + yield return meat; + } + } + if (this.RaceProps.leatherDef != null) + { + int leatherCount = GenMath.RoundRandom(this.GetStatValue(StatDefOf.LeatherAmount, true) * efficiency); + if (leatherCount > 0) + { + Thing leather = ThingMaker.MakeThing(this.RaceProps.leatherDef, null); + leather.stackCount = leatherCount; + yield return leather; + } + } + if (!this.RaceProps.Humanlike) + { + PawnKindLifeStage lifeStage = this.ageTracker.CurKindLifeStage; + if (lifeStage.butcherBodyPart != null) + { + if (this.gender != 0 && (this.gender != Gender.Male || !lifeStage.butcherBodyPart.allowMale)) + { + if (this.gender != Gender.Female) + yield break; + if (!lifeStage.butcherBodyPart.allowFemale) + yield break; + } + while (true) + { + BodyPartRecord record = (from x in this.health.hediffSet.GetNotMissingParts(BodyPartHeight.Undefined, BodyPartDepth.Undefined) + where x.IsInGroup(((_003CButcherProducts_003Ec__Iterator21A)/*Error near IL_027f: stateMachine*/)._003ClifeStage_003E__6.butcherBodyPart.bodyPartGroup) + select x).FirstOrDefault(); + if (record != null) + { + this.health.AddHediff(HediffMaker.MakeHediff(HediffDefOf.MissingBodyPart, this, record), null, default(DamageInfo?)); + Thing thing = (lifeStage.butcherBodyPart.thing == null) ? ThingMaker.MakeThing(record.def.spawnThingOnRemoved, null) : ThingMaker.MakeThing(lifeStage.butcherBodyPart.thing, null); + yield return thing; + continue; + } + break; + } + } + } } public string MainDesc(bool writeAge) @@ -1744,18 +1732,11 @@ public string MainDesc(bool writeAge) string text = GenLabel.BestKindLabel(this, true, true, false); if (base.Faction != null && !base.Faction.def.hidden) { - text = "PawnMainDescFactionedWrap".Translate(new object[] - { - text, - base.Faction.Name - }); + text = "PawnMainDescFactionedWrap".Translate(text, base.Faction.Name); } if (writeAge && this.ageTracker != null) { - text = text + ", " + "AgeIndicator".Translate(new object[] - { - this.ageTracker.AgeNumberString - }); + text = text + ", " + "AgeIndicator".Translate(this.ageTracker.AgeNumberString); } return text.CapitalizeFirst(); } @@ -1781,7 +1762,7 @@ public override string GetInspectString() stringBuilder.Append("Carrying".Translate() + ": "); stringBuilder.AppendLine(this.carryTracker.CarriedThing.LabelCap); } - string text = null; + string text = (string)null; Lord lord = this.GetLord(); if (lord != null && lord.LordJob != null) { @@ -1792,14 +1773,7 @@ public override string GetInspectString() try { string text2 = this.jobs.curDriver.GetReport().CapitalizeFirst(); - if (!text.NullOrEmpty()) - { - text = text + ": " + text2; - } - else - { - text = text2; - } + text = (text.NullOrEmpty() ? text2 : (text + ": " + text2)); } catch (Exception arg) { @@ -1818,23 +1792,52 @@ public override string GetInspectString() return stringBuilder.ToString().TrimEndNewlines(); } - [DebuggerHidden] public override IEnumerable GetGizmos() { - Pawn.c__Iterator21B c__Iterator21B = new Pawn.c__Iterator21B(); - c__Iterator21B.<>f__this = this; - Pawn.c__Iterator21B expr_0E = c__Iterator21B; - expr_0E.$PC = -2; - return expr_0E; + if (this.IsColonistPlayerControlled) + { + foreach (Gizmo gizmo in base.GetGizmos()) + { + yield return gizmo; + } + if (this.drafter != null) + { + foreach (Gizmo gizmo2 in this.drafter.GetGizmos()) + { + yield return gizmo2; + } + } + if (this.equipment != null) + { + foreach (Gizmo gizmo3 in this.equipment.GetGizmos()) + { + yield return gizmo3; + } + } + if (this.apparel != null) + { + foreach (Gizmo gizmo4 in this.apparel.GetGizmos()) + { + yield return gizmo4; + } + } + if (this.playerSettings != null) + { + foreach (Gizmo gizmo5 in this.playerSettings.GetGizmos()) + { + yield return gizmo5; + } + } + foreach (Gizmo gizmo6 in this.mindState.GetGizmos()) + { + yield return gizmo6; + } + } } - [DebuggerHidden] public virtual IEnumerable GetExtraFloatMenuOptionsFor(IntVec3 sq) { - Pawn.c__Iterator21C c__Iterator21C = new Pawn.c__Iterator21C(); - Pawn.c__Iterator21C expr_07 = c__Iterator21C; - expr_07.$PC = -2; - return expr_07; + yield break; } public override TipSignal GetTooltip() @@ -1842,7 +1845,7 @@ public override TipSignal GetTooltip() StringBuilder stringBuilder = new StringBuilder(); stringBuilder.Append(this.LabelCap); string text = string.Empty; - if (this.gender != Gender.None) + if (this.gender != 0) { text = this.gender.GetLabel(); } @@ -1864,7 +1867,7 @@ public override TipSignal GetTooltip() stringBuilder.AppendLine(this.equipment.Primary.LabelCap); } stringBuilder.AppendLine(HealthUtility.GetGeneralConditionLabel(this, false)); - return new TipSignal(stringBuilder.ToString().TrimEndNewlines(), this.thingIDNumber * 152317, TooltipPriority.Pawn); + return new TipSignal(stringBuilder.ToString().TrimEndNewlines(), base.thingIDNumber * 152317, TooltipPriority.Pawn); } public bool CurrentlyUsable() @@ -1874,7 +1877,21 @@ public bool CurrentlyUsable() public bool AnythingToStrip() { - return (this.equipment != null && this.equipment.HasAnything()) || (this.apparel != null && this.apparel.WornApparelCount > 0) || (this.inventory != null && this.inventory.innerContainer.Count > 0); + if (this.equipment != null && this.equipment.HasAnything()) + { + goto IL_005a; + } + if (this.apparel != null && this.apparel.WornApparelCount > 0) + { + goto IL_005a; + } + int result = (this.inventory != null && this.inventory.innerContainer.Count > 0) ? 1 : 0; + goto IL_005b; + IL_005a: + result = 1; + goto IL_005b; + IL_005b: + return (byte)result != 0; } public void Strip() @@ -1927,29 +1944,28 @@ public void GiveSoldThingToPlayer(Thing toGive, int countToGive, Pawn playerNego public void HearClamor(Pawn source, ClamorType type) { - if (this.Dead) - { - return; - } - if (type == ClamorType.Movement && this.needs.mood != null && !this.Awake() && base.Faction == Faction.OfPlayer && Find.TickManager.TicksGame > this.lastSleepDisturbedTick + 300 && !LovePartnerRelationUtility.LovePartnerRelationExists(this, source)) - { - this.lastSleepDisturbedTick = Find.TickManager.TicksGame; - this.needs.mood.thoughts.memories.TryGainMemory(ThoughtDefOf.SleepDisturbed, null); - } - if (type == ClamorType.Harm && base.Faction != Faction.OfPlayer && !this.Awake() && base.Faction == source.Faction && this.HostFaction == null) + if (!this.Dead) { - this.mindState.canSleepTick = Find.TickManager.TicksGame + 1000; - if (this.CurJob != null) + if (type == ClamorType.Movement && this.needs.mood != null && !this.Awake() && base.Faction == Faction.OfPlayer && Find.TickManager.TicksGame > this.lastSleepDisturbedTick + 300 && !LovePartnerRelationUtility.LovePartnerRelationExists(this, source)) { - this.jobs.EndCurrentJob(JobCondition.InterruptForced, true); + this.lastSleepDisturbedTick = Find.TickManager.TicksGame; + this.needs.mood.thoughts.memories.TryGainMemory(ThoughtDefOf.SleepDisturbed, null); } - } - if (type == ClamorType.Construction && base.Faction != Faction.OfPlayer && !this.Awake() && base.Faction != source.Faction && this.HostFaction == null) - { - this.mindState.canSleepTick = Find.TickManager.TicksGame + 1000; - if (this.CurJob != null) + if (type == ClamorType.Harm && base.Faction != Faction.OfPlayer && !this.Awake() && base.Faction == source.Faction && this.HostFaction == null) { - this.jobs.EndCurrentJob(JobCondition.InterruptForced, true); + this.mindState.canSleepTick = Find.TickManager.TicksGame + 1000; + if (this.CurJob != null) + { + this.jobs.EndCurrentJob(JobCondition.InterruptForced, true); + } + } + if (type == ClamorType.Construction && base.Faction != Faction.OfPlayer && !this.Awake() && base.Faction != source.Faction && this.HostFaction == null) + { + this.mindState.canSleepTick = Find.TickManager.TicksGame + 1000; + if (this.CurJob != null) + { + this.jobs.EndCurrentJob(JobCondition.InterruptForced, true); + } } } } @@ -1968,35 +1984,44 @@ public bool CheckAcceptArrest(Pawn arrester) { base.Faction.Notify_MemberCaptured(this, arrester.Faction); } - if (Rand.Value < 0.5f) + if (Rand.Value < 0.5) { return true; } - Messages.Message("MessageRefusedArrest".Translate(new object[] - { - this.LabelShort - }), this, MessageSound.SeriousAlert); + Messages.Message("MessageRefusedArrest".Translate(this.LabelShort), (Thing)this, MessageSound.SeriousAlert); if (base.Faction == null || !arrester.HostileTo(this)) { - this.mindState.mentalStateHandler.TryStartMentalState(MentalStateDefOf.Berserk, null, false, false, null); + this.mindState.mentalStateHandler.TryStartMentalState(MentalStateDefOf.Berserk, (string)null, false, false, null); } return false; } public bool ThreatDisabled() { - return !base.Spawned || (!this.InMentalState && this.GetTraderCaravanRole() == TraderCaravanRole.Carrier && !(this.jobs.curDriver is JobDriver_AttackMelee)) || this.Downed; + if (!base.Spawned) + { + return true; + } + if (!this.InMentalState && this.GetTraderCaravanRole() == TraderCaravanRole.Carrier && !(this.jobs.curDriver is JobDriver_AttackMelee)) + { + return true; + } + if (this.Downed) + { + return true; + } + return false; } public override bool PreventPlayerSellingThingsNearby(out string reason) { - if (this.InAggroMentalState || (base.Faction.HostileTo(Faction.OfPlayer) && this.HostFaction == null && !this.Downed && !this.InMentalState)) + if (!this.InAggroMentalState && (!base.Faction.HostileTo(Faction.OfPlayer) || this.HostFaction != null || this.Downed || this.InMentalState)) { - reason = "Enemies".Translate(); - return true; + reason = (string)null; + return false; } - reason = null; - return false; + reason = "Enemies".Translate(); + return true; } public void ChangeKind(PawnKindDef newKindDef) @@ -2009,14 +2034,32 @@ virtual Map get_Map() return base.Map; } + Map IBillGiver.get_Map() + { + //ILSpy generated this explicit interface implementation from .override directive in get_Map + return this.get_Map(); + } + virtual Faction get_Faction() { return base.Faction; } + Faction ITrader.get_Faction() + { + //ILSpy generated this explicit interface implementation from .override directive in get_Faction + return this.get_Faction(); + } + virtual IThingHolder get_ParentHolder() { return base.ParentHolder; } + + IThingHolder IThingHolder.get_ParentHolder() + { + //ILSpy generated this explicit interface implementation from .override directive in get_ParentHolder + return this.get_ParentHolder(); + } } } diff --git a/Assembly-CSharp/Verse/PawnCapacitiesHandler.cs b/Assembly-CSharp/Verse/PawnCapacitiesHandler.cs index 47a98bb7e..0b6ad1951 100644 --- a/Assembly-CSharp/Verse/PawnCapacitiesHandler.cs +++ b/Assembly-CSharp/Verse/PawnCapacitiesHandler.cs @@ -1,5 +1,4 @@ using RimWorld; -using System; namespace Verse { @@ -7,27 +6,27 @@ public class PawnCapacitiesHandler { private enum CacheStatus { - Uncached, - Caching, - Cached + Uncached = 0, + Caching = 1, + Cached = 2 } private class CacheElement { - public PawnCapacitiesHandler.CacheStatus status; + public CacheStatus status; public float value; } private Pawn pawn; - private DefMap cachedCapacityLevels; + private DefMap cachedCapacityLevels; public bool CanBeAwake { get { - return this.GetLevel(PawnCapacityDefOf.Consciousness) >= 0.3f; + return this.GetLevel(PawnCapacityDefOf.Consciousness) >= 0.30000001192092896; } } @@ -51,17 +50,17 @@ public float GetLevel(PawnCapacityDef capacity) { this.Notify_CapacityLevelsDirty(); } - PawnCapacitiesHandler.CacheElement cacheElement = this.cachedCapacityLevels[capacity]; - if (cacheElement.status == PawnCapacitiesHandler.CacheStatus.Caching) + CacheElement cacheElement = this.cachedCapacityLevels[capacity]; + if (cacheElement.status == CacheStatus.Caching) { Log.Error(string.Format("Detected infinite stat recursion when evaluating {0}", capacity)); return 0f; } - if (cacheElement.status == PawnCapacitiesHandler.CacheStatus.Uncached) + if (cacheElement.status == CacheStatus.Uncached) { - cacheElement.status = PawnCapacitiesHandler.CacheStatus.Caching; + cacheElement.status = CacheStatus.Caching; cacheElement.value = PawnCapacityUtility.CalculateCapacityLevel(this.pawn.health.hediffSet, capacity, null); - cacheElement.status = PawnCapacitiesHandler.CacheStatus.Cached; + cacheElement.status = CacheStatus.Cached; } return cacheElement.value; } @@ -75,11 +74,11 @@ public void Notify_CapacityLevelsDirty() { if (this.cachedCapacityLevels == null) { - this.cachedCapacityLevels = new DefMap(); + this.cachedCapacityLevels = new DefMap(); } for (int i = 0; i < this.cachedCapacityLevels.Count; i++) { - this.cachedCapacityLevels[i].status = PawnCapacitiesHandler.CacheStatus.Uncached; + this.cachedCapacityLevels[i].status = CacheStatus.Uncached; } } } diff --git a/Assembly-CSharp/Verse/PawnCapacityDef.cs b/Assembly-CSharp/Verse/PawnCapacityDef.cs index 2a5ced937..5e9db818f 100644 --- a/Assembly-CSharp/Verse/PawnCapacityDef.cs +++ b/Assembly-CSharp/Verse/PawnCapacityDef.cs @@ -56,7 +56,7 @@ public string GetLabelFor(bool isFlesh, bool isHumanlike) { if (isHumanlike) { - return this.label; + return base.label; } if (isFlesh) { @@ -64,16 +64,13 @@ public string GetLabelFor(bool isFlesh, bool isHumanlike) { return this.labelAnimals; } - return this.label; + return base.label; } - else + if (!this.labelMechanoids.NullOrEmpty()) { - if (!this.labelMechanoids.NullOrEmpty()) - { - return this.labelMechanoids; - } - return this.label; + return this.labelMechanoids; } + return base.label; } } } diff --git a/Assembly-CSharp/Verse/PawnCapacityModifier.cs b/Assembly-CSharp/Verse/PawnCapacityModifier.cs index 7e0658658..ce15429c4 100644 --- a/Assembly-CSharp/Verse/PawnCapacityModifier.cs +++ b/Assembly-CSharp/Verse/PawnCapacityModifier.cs @@ -1,5 +1,3 @@ -using System; - namespace Verse { public class PawnCapacityModifier @@ -16,7 +14,7 @@ public bool SetMaxDefined { get { - return this.setMax != 999f; + return this.setMax != 999.0; } } } diff --git a/Assembly-CSharp/Verse/PawnCapacityUtility.cs b/Assembly-CSharp/Verse/PawnCapacityUtility.cs index 71a0c333b..4f5e7785a 100644 --- a/Assembly-CSharp/Verse/PawnCapacityUtility.cs +++ b/Assembly-CSharp/Verse/PawnCapacityUtility.cs @@ -13,7 +13,7 @@ public abstract class CapacityImpactor public abstract string Readable(Pawn pawn); } - public class CapacityImpactorBodyPartHealth : PawnCapacityUtility.CapacityImpactor + public class CapacityImpactorBodyPartHealth : CapacityImpactor { public BodyPartRecord bodyPart; @@ -23,17 +23,17 @@ public override string Readable(Pawn pawn) } } - public class CapacityImpactorCapacity : PawnCapacityUtility.CapacityImpactor + public class CapacityImpactorCapacity : CapacityImpactor { public PawnCapacityDef capacity; public override string Readable(Pawn pawn) { - return string.Format("{0}: {1}%", this.capacity.LabelCap, (pawn.health.capacities.GetLevel(this.capacity) * 100f).ToString("F0")); + return string.Format("{0}: {1}%", this.capacity.LabelCap, ((float)(pawn.health.capacities.GetLevel(this.capacity) * 100.0)).ToString("F0")); } } - public class CapacityImpactorHediff : PawnCapacityUtility.CapacityImpactor + public class CapacityImpactorHediff : CapacityImpactor { public Hediff hediff; @@ -43,11 +43,11 @@ public override string Readable(Pawn pawn) } } - public class CapacityImpactorPain : PawnCapacityUtility.CapacityImpactor + public class CapacityImpactorPain : CapacityImpactor { public override string Readable(Pawn pawn) { - return string.Format("{0}: {1}%", "Pain".Translate(), (pawn.health.hediffSet.PainTotal * 100f).ToString("F0")); + return string.Format("{0}: {1}%", "Pain".Translate(), ((float)(pawn.health.hediffSet.PainTotal * 100.0)).ToString("F0")); } } @@ -56,13 +56,13 @@ public static bool BodyCanEverDoCapacity(BodyDef bodyDef, PawnCapacityDef capaci return capacity.Worker.CanHaveCapacity(bodyDef); } - public static float CalculateCapacityLevel(HediffSet diffSet, PawnCapacityDef capacity, List impactors = null) + public static float CalculateCapacityLevel(HediffSet diffSet, PawnCapacityDef capacity, List impactors = null) { if (capacity.zeroIfCannotBeAwake && !diffSet.pawn.health.capacities.CanBeAwake) { if (impactors != null) { - impactors.Add(new PawnCapacityUtility.CapacityImpactorCapacity + impactors.Add(new CapacityImpactorCapacity { capacity = PawnCapacityDefOf.Consciousness }); @@ -70,7 +70,7 @@ public static float CalculateCapacityLevel(HediffSet diffSet, PawnCapacityDef ca return 0f; } float num = capacity.Worker.CalculateCapacityLevel(diffSet, impactors); - if (num > 0f && capacity.minValue <= 0f) + if (num > 0.0 && capacity.minValue <= 0.0) { float num2 = 99999f; float num3 = 1f; @@ -93,7 +93,7 @@ public static float CalculateCapacityLevel(HediffSet diffSet, PawnCapacityDef ca } if (impactors != null) { - impactors.Add(new PawnCapacityUtility.CapacityImpactorHediff + impactors.Add(new CapacityImpactorHediff { hediff = hediff }); @@ -109,7 +109,7 @@ public static float CalculateCapacityLevel(HediffSet diffSet, PawnCapacityDef ca return GenMath.RoundedHundredth(num); } - public static float CalculatePartEfficiency(HediffSet diffSet, BodyPartRecord part, bool ignoreAddedParts = false, List impactors = null) + public static float CalculatePartEfficiency(HediffSet diffSet, BodyPartRecord part, bool ignoreAddedParts = false, List impactors = null) { BodyPartRecord rec; for (rec = part.parent; rec != null; rec = rec.parent) @@ -118,10 +118,10 @@ public static float CalculatePartEfficiency(HediffSet diffSet, BodyPartRecord pa { Hediff_AddedPart hediff_AddedPart = (from x in diffSet.GetHediffs() where x.Part == rec - select x).First(); + select x).First(); if (impactors != null) { - impactors.Add(new PawnCapacityUtility.CapacityImpactorHediff + impactors.Add(new CapacityImpactorHediff { hediff = hediff_AddedPart }); @@ -142,9 +142,9 @@ public static float CalculatePartEfficiency(HediffSet diffSet, BodyPartRecord pa if (hediff_AddedPart2 != null && hediff_AddedPart2.Part == part) { num *= hediff_AddedPart2.def.addedPartProps.partEfficiency; - if (hediff_AddedPart2.def.addedPartProps.partEfficiency != 1f && impactors != null) + if (hediff_AddedPart2.def.addedPartProps.partEfficiency != 1.0 && impactors != null) { - impactors.Add(new PawnCapacityUtility.CapacityImpactorHediff + impactors.Add(new CapacityImpactorHediff { hediff = hediff_AddedPart2 }); @@ -162,9 +162,9 @@ public static float CalculatePartEfficiency(HediffSet diffSet, BodyPartRecord pa HediffStage curStage = diffSet.hediffs[j].CurStage; num2 += curStage.partEfficiencyOffset; flag |= curStage.partIgnoreMissingHP; - if (curStage.partEfficiencyOffset != 0f && curStage.everVisible && impactors != null) + if (curStage.partEfficiencyOffset != 0.0 && curStage.everVisible && impactors != null) { - impactors.Add(new PawnCapacityUtility.CapacityImpactorHediff + impactors.Add(new CapacityImpactorHediff { hediff = diffSet.hediffs[j] }); @@ -174,9 +174,9 @@ public static float CalculatePartEfficiency(HediffSet diffSet, BodyPartRecord pa if (!flag) { float num3 = diffSet.GetPartHealth(part) / part.def.GetMaxHealth(diffSet.pawn); - if (num3 != 1f && impactors != null) + if (num3 != 1.0 && impactors != null) { - impactors.Add(new PawnCapacityUtility.CapacityImpactorBodyPartHealth + impactors.Add(new CapacityImpactorBodyPartHealth { bodyPart = part }); @@ -184,14 +184,14 @@ public static float CalculatePartEfficiency(HediffSet diffSet, BodyPartRecord pa num *= num3; } num += num2; - if (num > 0.0001f) + if (num > 9.9999997473787516E-05) { num = Mathf.Max(num, b); } return Mathf.Max(num, 0f); } - public static float CalculateImmediatePartEfficiencyAndRecord(HediffSet diffSet, BodyPartRecord part, List impactors = null) + public static float CalculateImmediatePartEfficiencyAndRecord(HediffSet diffSet, BodyPartRecord part, List impactors = null) { if (diffSet.AncestorHasDirectlyAddedParts(part)) { @@ -207,36 +207,35 @@ public static float CalculateNaturalPartsAverageEfficiency(HediffSet diffSet, Bo IEnumerable enumerable = from x in diffSet.GetNotMissingParts(BodyPartHeight.Undefined, BodyPartDepth.Undefined) where x.groups.Contains(bodyPartGroup) select x; - foreach (BodyPartRecord current in enumerable) + foreach (BodyPartRecord item in enumerable) { - if (!diffSet.PartOrAnyAncestorHasDirectlyAddedParts(current)) + if (!diffSet.PartOrAnyAncestorHasDirectlyAddedParts(item)) { - num += PawnCapacityUtility.CalculatePartEfficiency(diffSet, current, false, null); + num += PawnCapacityUtility.CalculatePartEfficiency(diffSet, item, false, null); } num2++; } - if (num2 == 0 || num < 0f) + if (num2 != 0 && !(num < 0.0)) { - return 0f; + return num / (float)num2; } - return num / (float)num2; + return 0f; } - public static float CalculateTagEfficiency(HediffSet diffSet, string tag, float maximum = 3.40282347E+38f, List impactors = null) + public static float CalculateTagEfficiency(HediffSet diffSet, string tag, float maximum = 3.40282347E+38f, List impactors = null) { BodyDef body = diffSet.pawn.RaceProps.body; float num = 0f; int num2 = 0; - List list = null; - foreach (BodyPartRecord current in body.GetPartsWithTag(tag)) + List list = null; + foreach (BodyPartRecord item in body.GetPartsWithTag(tag)) { - List impactors2 = list; - float num3 = PawnCapacityUtility.CalculatePartEfficiency(diffSet, current, false, impactors2); - if (impactors != null && num3 != 1f && list == null) + List impactors2 = list; + float num3 = PawnCapacityUtility.CalculatePartEfficiency(diffSet, item, false, impactors2); + if (impactors != null && num3 != 1.0 && list == null) { - list = new List(); - impactors2 = list; - PawnCapacityUtility.CalculatePartEfficiency(diffSet, current, false, impactors2); + list = (impactors2 = new List()); + PawnCapacityUtility.CalculatePartEfficiency(diffSet, item, false, impactors2); } num += num3; num2++; @@ -247,33 +246,33 @@ public static float CalculateTagEfficiency(HediffSet diffSet, string tag, float } float num4 = num / (float)num2; float num5 = Mathf.Min(num4, maximum); - if (impactors != null && list != null && (maximum != 1f || num4 <= 1f || num5 == 1f)) + if (impactors != null && list != null && (maximum != 1.0 || num4 <= 1.0 || num5 == 1.0)) { impactors.AddRange(list); } return num5; } - public static float CalculateLimbEfficiency(HediffSet diffSet, string limbCoreTag, string limbSegmentTag, string limbDigitTag, float appendageWeight, out float functionalPercentage, List impactors) + public static float CalculateLimbEfficiency(HediffSet diffSet, string limbCoreTag, string limbSegmentTag, string limbDigitTag, float appendageWeight, out float functionalPercentage, List impactors) { BodyDef body = diffSet.pawn.RaceProps.body; float num = 0f; int num2 = 0; int num3 = 0; - foreach (BodyPartRecord current in body.GetPartsWithTag(limbCoreTag)) + foreach (BodyPartRecord item in body.GetPartsWithTag(limbCoreTag)) { - float num4 = PawnCapacityUtility.CalculateImmediatePartEfficiencyAndRecord(diffSet, current, impactors); - foreach (BodyPartRecord current2 in current.GetConnectedParts(limbSegmentTag)) + float num4 = PawnCapacityUtility.CalculateImmediatePartEfficiencyAndRecord(diffSet, item, impactors); + foreach (BodyPartRecord connectedPart in item.GetConnectedParts(limbSegmentTag)) { - num4 *= PawnCapacityUtility.CalculateImmediatePartEfficiencyAndRecord(diffSet, current2, impactors); + num4 *= PawnCapacityUtility.CalculateImmediatePartEfficiencyAndRecord(diffSet, connectedPart, impactors); } - if (current.HasChildParts(limbDigitTag)) + if (item.HasChildParts(limbDigitTag)) { - num4 = Mathf.Lerp(num4, num4 * current.GetChildParts(limbDigitTag).Average((BodyPartRecord digitPart) => PawnCapacityUtility.CalculateImmediatePartEfficiencyAndRecord(diffSet, digitPart, impactors)), appendageWeight); + num4 = Mathf.Lerp(num4, num4 * item.GetChildParts(limbDigitTag).Average((Func)((BodyPartRecord digitPart) => PawnCapacityUtility.CalculateImmediatePartEfficiencyAndRecord(diffSet, digitPart, impactors))), appendageWeight); } num += num4; num2++; - if (num4 > 0f) + if (num4 > 0.0) { num3++; } diff --git a/Assembly-CSharp/Verse/PawnCapacityWorker.cs b/Assembly-CSharp/Verse/PawnCapacityWorker.cs index d8c1c280e..37f21e2e0 100644 --- a/Assembly-CSharp/Verse/PawnCapacityWorker.cs +++ b/Assembly-CSharp/Verse/PawnCapacityWorker.cs @@ -1,4 +1,3 @@ -using System; using System.Collections.Generic; namespace Verse @@ -18,7 +17,7 @@ public virtual bool CanHaveCapacity(BodyDef body) protected float CalculateCapacityAndRecord(HediffSet diffSet, PawnCapacityDef capacity, List impactors) { float level = diffSet.pawn.health.capacities.GetLevel(capacity); - if (impactors != null && level != 1f) + if (impactors != null && level != 1.0) { impactors.Add(new PawnCapacityUtility.CapacityImpactorCapacity { diff --git a/Assembly-CSharp/Verse/PawnCollisionTweenerUtility.cs b/Assembly-CSharp/Verse/PawnCollisionTweenerUtility.cs index f81772751..080456ebb 100644 --- a/Assembly-CSharp/Verse/PawnCollisionTweenerUtility.cs +++ b/Assembly-CSharp/Verse/PawnCollisionTweenerUtility.cs @@ -1,5 +1,4 @@ using RimWorld; -using System; using System.Collections.Generic; using UnityEngine; @@ -11,60 +10,48 @@ public static class PawnCollisionTweenerUtility public static Vector3 PawnCollisionPosOffsetFor(Pawn pawn) { - if (pawn.GetPosture() != PawnPosture.Standing) + if (pawn.GetPosture() != 0) { return Vector3.zero; } bool flag = pawn.Spawned && pawn.pather.MovingNow; - if (!flag || pawn.pather.nextCell == pawn.pather.Destination.Cell) - { - if (!flag && pawn.Drawer.leaner.ShouldLean()) - { - return Vector3.zero; - } - IntVec3 at; - if (flag) - { - at = pawn.pather.nextCell; - } - else - { - at = pawn.Position; - } - int num = 0; - int vertexIndex = 0; - PawnCollisionTweenerUtility.GetPawnsStandingAtOrAboutToStandAt(at, pawn.Map, out num, out vertexIndex, pawn); - if (num == 0) - { - return Vector3.zero; - } - return GenGeo.RegularPolygonVertexPositionVec3(num, vertexIndex) * 0.32f; - } - else + if (flag && !(pawn.pather.nextCell == pawn.pather.Destination.Cell)) { IntVec3 nextCell = pawn.pather.nextCell; if (PawnCollisionTweenerUtility.CanGoDirectlyToNextCell(pawn)) { return Vector3.zero; } - int num2 = pawn.thingIDNumber % 2; - if (nextCell.x != pawn.Position.x) + int num = pawn.thingIDNumber % 2; + int x = nextCell.x; + IntVec3 position = pawn.Position; + if (x != position.x) { - if (num2 == 0) + if (num == 0) { return new Vector3(0f, 0f, 0.32f); } return new Vector3(0f, 0f, -0.32f); } - else + if (num == 0) { - if (num2 == 0) - { - return new Vector3(0.32f, 0f, 0f); - } - return new Vector3(-0.32f, 0f, 0f); + return new Vector3(0.32f, 0f, 0f); } + return new Vector3(-0.32f, 0f, 0f); + } + if (!flag && pawn.Drawer.leaner.ShouldLean()) + { + return Vector3.zero; } + IntVec3 at = (!flag) ? pawn.Position : pawn.pather.nextCell; + int num2 = 0; + int vertexIndex = 0; + PawnCollisionTweenerUtility.GetPawnsStandingAtOrAboutToStandAt(at, pawn.Map, out num2, out vertexIndex, pawn); + if (num2 == 0) + { + return Vector3.zero; + } + return GenGeo.RegularPolygonVertexPositionVec3(num2, vertexIndex) * 0.32f; } private static void GetPawnsStandingAtOrAboutToStandAt(IntVec3 at, Map map, out int pawnsCount, out int pawnsWithLowerIdCount, Pawn forPawn) @@ -81,29 +68,23 @@ private static void GetPawnsStandingAtOrAboutToStandAt(IntVec3 at, Map map, out for (int i = 0; i < thingList.Count; i++) { Pawn pawn = thingList[i] as Pawn; - if (pawn != null) + if (pawn != null && pawn.GetPosture() == PawnPosture.Standing) { - if (pawn.GetPosture() == PawnPosture.Standing) + if (current != at) { - if (current != at) - { - if (!pawn.pather.MovingNow || pawn.pather.nextCell != pawn.pather.Destination.Cell || pawn.pather.Destination.Cell != at) - { - goto IL_120; - } - } - else if (pawn.pather.MovingNow) - { - goto IL_120; - } - pawnsCount++; - if (pawn.thingIDNumber < forPawn.thingIDNumber) - { - pawnsWithLowerIdCount++; - } + if (pawn.pather.MovingNow && !(pawn.pather.nextCell != pawn.pather.Destination.Cell) && !(pawn.pather.Destination.Cell != at)) + goto IL_0101; } + else if (!pawn.pather.MovingNow) + goto IL_0101; + } + continue; + IL_0101: + pawnsCount++; + if (pawn.thingIDNumber < forPawn.thingIDNumber) + { + pawnsWithLowerIdCount++; } - IL_120:; } } iterator.MoveNext(); @@ -123,21 +104,23 @@ private static bool CanGoDirectlyToNextCell(Pawn pawn) for (int i = 0; i < thingList.Count; i++) { Pawn pawn2 = thingList[i] as Pawn; - if (pawn2 != null && pawn2 != pawn) + if (pawn2 != null && pawn2 != pawn && pawn2.GetPosture() == PawnPosture.Standing) { - if (pawn2.GetPosture() == PawnPosture.Standing) + if (!pawn2.pather.MovingNow) { - if (pawn2.pather.MovingNow) - { - if (((pawn2.Position == nextCell && PawnCollisionTweenerUtility.WillBeFasterOnNextCell(pawn, pawn2)) || pawn2.pather.nextCell == nextCell || pawn2.Position == pawn.Position || (pawn2.pather.nextCell == pawn.Position && PawnCollisionTweenerUtility.WillBeFasterOnNextCell(pawn2, pawn))) && pawn2.thingIDNumber < pawn.thingIDNumber) - { - return false; - } - } - else if (pawn2.Position == pawn.Position || pawn2.Position == nextCell) + if (!(pawn2.Position == pawn.Position) && !(pawn2.Position == nextCell)) { - return false; + continue; } + return false; + } + if ((!(pawn2.Position == nextCell) || !PawnCollisionTweenerUtility.WillBeFasterOnNextCell(pawn, pawn2)) && !(pawn2.pather.nextCell == nextCell) && !(pawn2.Position == pawn.Position) && (!(pawn2.pather.nextCell == pawn.Position) || !PawnCollisionTweenerUtility.WillBeFasterOnNextCell(pawn2, pawn))) + { + continue; + } + if (pawn2.thingIDNumber < pawn.thingIDNumber) + { + return false; } } } diff --git a/Assembly-CSharp/Verse/PawnDestinationManager.cs b/Assembly-CSharp/Verse/PawnDestinationManager.cs index 3df585fe4..0770d9606 100644 --- a/Assembly-CSharp/Verse/PawnDestinationManager.cs +++ b/Assembly-CSharp/Verse/PawnDestinationManager.cs @@ -16,9 +16,9 @@ public sealed class PawnDestinationManager public PawnDestinationManager() { - foreach (Faction current in Find.FactionManager.AllFactions) + foreach (Faction allFaction in Find.FactionManager.AllFactions) { - this.RegisterFaction(current); + this.RegisterFaction(allFaction); } } @@ -29,16 +29,13 @@ public void RegisterFaction(Faction faction) public void ReserveDestinationFor(Pawn p, IntVec3 loc) { - if (p.Faction == null) - { - return; - } - Pawn pawn = this.ReserverOfDestinationForFaction(loc, p.Faction); - if (pawn != null && pawn != p) + if (p.Faction != null) { - return; + Pawn pawn = this.ReserverOfDestinationForFaction(loc, p.Faction); + if (pawn != null && pawn != p) + return; + this.reservedDestinations[p.Faction][p] = loc; } - this.reservedDestinations[p.Faction][p] = loc; } public IntVec3 DestinationReservedFor(Pawn p) @@ -56,16 +53,32 @@ public IntVec3 DestinationReservedFor(Pawn p) public bool DestinationIsReserved(IntVec3 loc) { - foreach (KeyValuePair> current in this.reservedDestinations) + Dictionary>.Enumerator enumerator = this.reservedDestinations.GetEnumerator(); + try { - foreach (KeyValuePair current2 in current.Value) + while (enumerator.MoveNext()) { - if (current2.Value == loc) + Dictionary.Enumerator enumerator2 = enumerator.Current.Value.GetEnumerator(); + try { - return true; + while (enumerator2.MoveNext()) + { + if (enumerator2.Current.Value == loc) + { + return true; + } + } + } + finally + { + ((IDisposable)(object)enumerator2).Dispose(); } } } + finally + { + ((IDisposable)(object)enumerator).Dispose(); + } return false; } @@ -75,13 +88,22 @@ public bool DestinationIsReserved(IntVec3 c, Pawn searcher) { return false; } - foreach (KeyValuePair current in this.reservedDestinations[searcher.Faction]) + Dictionary.Enumerator enumerator = this.reservedDestinations[searcher.Faction].GetEnumerator(); + try { - if (current.Value == c && current.Key != searcher) + while (enumerator.MoveNext()) { - return true; + KeyValuePair current = enumerator.Current; + if (current.Value == c && current.Key != searcher) + { + return true; + } } } + finally + { + ((IDisposable)(object)enumerator).Dispose(); + } return false; } @@ -91,42 +113,59 @@ private Pawn ReserverOfDestinationForFaction(IntVec3 c, Faction faction) { return null; } - foreach (KeyValuePair current in this.reservedDestinations[faction]) + Dictionary.Enumerator enumerator = this.reservedDestinations[faction].GetEnumerator(); + try { - if (current.Value == c) + while (enumerator.MoveNext()) { - return current.Key; + KeyValuePair current = enumerator.Current; + if (current.Value == c) + { + return current.Key; + } } } + finally + { + ((IDisposable)(object)enumerator).Dispose(); + } return null; } public void UnreserveAllFor(Pawn p) { - if (p.Faction == null) + if (p.Faction != null) { - return; + this.reservedDestinations[p.Faction].Remove(p); } - this.reservedDestinations[p.Faction].Remove(p); } public void DebugDrawDestinations() { - foreach (KeyValuePair current in this.reservedDestinations[Faction.OfPlayer]) + Dictionary.Enumerator enumerator = this.reservedDestinations[Faction.OfPlayer].GetEnumerator(); + try { - if (!(current.Key.Position == current.Value)) + while (enumerator.MoveNext()) { - IntVec3 value = current.Value; - Vector3 s = new Vector3(1f, 1f, 1f); - Matrix4x4 matrix = default(Matrix4x4); - matrix.SetTRS(value.ToVector3ShiftedWithAltitude(AltitudeLayer.MetaOverlays), Quaternion.identity, s); - Graphics.DrawMesh(MeshPool.plane10, matrix, PawnDestinationManager.DestinationMat, 0); - if (Find.Selector.IsSelected(current.Key)) + KeyValuePair current = enumerator.Current; + if (!(current.Key.Position == current.Value)) { - Graphics.DrawMesh(MeshPool.plane10, matrix, PawnDestinationManager.DestinationSelectionMat, 0); + IntVec3 value = current.Value; + Vector3 s = new Vector3(1f, 1f, 1f); + Matrix4x4 matrix = default(Matrix4x4); + matrix.SetTRS(value.ToVector3ShiftedWithAltitude(AltitudeLayer.MetaOverlays), Quaternion.identity, s); + Graphics.DrawMesh(MeshPool.plane10, matrix, PawnDestinationManager.DestinationMat, 0); + if (Find.Selector.IsSelected(current.Key)) + { + Graphics.DrawMesh(MeshPool.plane10, matrix, PawnDestinationManager.DestinationSelectionMat, 0); + } } } } + finally + { + ((IDisposable)(object)enumerator).Dispose(); + } } } } diff --git a/Assembly-CSharp/Verse/PawnDownedWiggler.cs b/Assembly-CSharp/Verse/PawnDownedWiggler.cs index 2c0c3c3f9..8b2390571 100644 --- a/Assembly-CSharp/Verse/PawnDownedWiggler.cs +++ b/Assembly-CSharp/Verse/PawnDownedWiggler.cs @@ -1,5 +1,4 @@ using RimWorld; -using System; namespace Verse { @@ -30,9 +29,9 @@ private static float RandomDownedAngle get { float num = Rand.Range(45f, 135f); - if (Rand.Value < 0.5f) + if (Rand.Value < 0.5) { - num += 180f; + num = (float)(num + 180.0); } return num; } @@ -76,22 +75,24 @@ public void SetToCustomRotation(float rot) public void Notify_DamageApplied(DamageInfo dam) { - if ((this.pawn.Downed || this.pawn.Dead) && dam.Def.hasForcefulImpact) + if (!this.pawn.Downed && !this.pawn.Dead) + return; + if (dam.Def.hasForcefulImpact) { - this.downedAngle += 10f * Rand.Range(-1f, 1f); + this.downedAngle += (float)(10.0 * Rand.Range(-1f, 1f)); if (!this.usingCustomRotation) { - if (this.downedAngle > 315f) + if (this.downedAngle > 315.0) { this.downedAngle = 315f; } - if (this.downedAngle < 45f) + if (this.downedAngle < 45.0) { this.downedAngle = 45f; } - if (this.downedAngle > 135f && this.downedAngle < 225f) + if (this.downedAngle > 135.0 && this.downedAngle < 225.0) { - if (this.downedAngle > 180f) + if (this.downedAngle > 180.0) { this.downedAngle = 225f; } @@ -103,11 +104,11 @@ public void Notify_DamageApplied(DamageInfo dam) } else { - if (this.downedAngle >= 360f) + if (this.downedAngle >= 360.0) { this.downedAngle -= 360f; } - if (this.downedAngle < 0f) + if (this.downedAngle < 0.0) { this.downedAngle += 360f; } diff --git a/Assembly-CSharp/Verse/PawnGenerationRequest.cs b/Assembly-CSharp/Verse/PawnGenerationRequest.cs index 497dc8e9c..37318d6f2 100644 --- a/Assembly-CSharp/Verse/PawnGenerationRequest.cs +++ b/Assembly-CSharp/Verse/PawnGenerationRequest.cs @@ -137,7 +137,7 @@ public string FixedLastName private set; } - public PawnGenerationRequest(PawnKindDef kind, Faction faction = null, PawnGenerationContext context = PawnGenerationContext.NonPlayer, int tile = -1, bool forceGenerateNewPawn = false, bool newborn = false, bool allowDead = false, bool allowDowned = false, bool canGeneratePawnRelations = true, bool mustBeCapableOfViolence = false, float colonistRelationChanceFactor = 1f, bool forceAddFreeWarmLayerIfNeeded = false, bool allowGay = true, bool allowFood = true, bool inhabitant = false, bool certainlyBeenInCryptosleep = false, Predicate validator = null, float? fixedBiologicalAge = null, float? fixedChronologicalAge = null, Gender? fixedGender = null, float? fixedMelanin = null, string fixedLastName = null) + public PawnGenerationRequest(PawnKindDef kind, Faction faction = null, PawnGenerationContext context = PawnGenerationContext.NonPlayer, int tile = -1, bool forceGenerateNewPawn = false, bool newborn = false, bool allowDead = false, bool allowDowned = false, bool canGeneratePawnRelations = true, bool mustBeCapableOfViolence = false, float colonistRelationChanceFactor = 1f, bool forceAddFreeWarmLayerIfNeeded = false, bool allowGay = true, bool allowFood = true, bool inhabitant = false, bool certainlyBeenInCryptosleep = false, Predicate validator = null, float? fixedBiologicalAge = default(float?), float? fixedChronologicalAge = default(float?), Gender? fixedGender = default(Gender?), float? fixedMelanin = default(float?), string fixedLastName = null) { if (context == PawnGenerationContext.All) { @@ -178,13 +178,7 @@ public void EnsureNonNullFaction() if (this.KindDef.RaceProps.Humanlike && this.Faction == null) { this.Faction = FactionUtility.DefaultFactionFrom(this.KindDef.defaultFactionType); - Log.Error(string.Concat(new object[] - { - "Tried to generate pawn of Humanlike race ", - this.KindDef, - " with null faction. Setting to ", - this.Faction - })); + Log.Error("Tried to generate pawn of Humanlike race " + this.KindDef + " with null faction. Setting to " + this.Faction); } } @@ -193,9 +187,11 @@ public void SetFixedLastName(string fixedLastName) if (this.FixedLastName != null) { Log.Error("Last name is already a fixed value: " + this.FixedLastName + "."); - return; } - this.FixedLastName = fixedLastName; + else + { + this.FixedLastName = fixedLastName; + } } public void SetFixedMelanin(float fixedMelanin) @@ -203,60 +199,16 @@ public void SetFixedMelanin(float fixedMelanin) if (this.FixedMelanin.HasValue) { Log.Error("Melanin is already a fixed value: " + this.FixedMelanin + "."); - return; } - this.FixedMelanin = new float?(fixedMelanin); + else + { + this.FixedMelanin = new float?(fixedMelanin); + } } public override string ToString() { - return string.Concat(new object[] - { - "kindDef=", - this.KindDef, - ", context=", - this.Context, - ", faction=", - this.Faction, - ", tile=", - this.Tile, - ", forceGenerateNewPawn=", - this.ForceGenerateNewPawn, - ", newborn=", - this.Newborn, - ", allowDead=", - this.AllowDead, - ", allowDowned=", - this.AllowDowned, - ", canGeneratePawnRelations=", - this.CanGeneratePawnRelations, - ", mustBeCapableOfViolence=", - this.MustBeCapableOfViolence, - ", colonistRelationChanceFactor=", - this.ColonistRelationChanceFactor, - ", forceAddFreeWarmLayerIfNeeded=", - this.ForceAddFreeWarmLayerIfNeeded, - ", allowGay=", - this.AllowGay, - ", allowFood=", - this.AllowFood, - ", inhabitant=", - this.Inhabitant, - ", certainlyBeenInCryptosleep=", - this.CertainlyBeenInCryptosleep, - ", validator=", - this.Validator, - ", fixedBiologicalAge=", - this.FixedBiologicalAge, - ", fixedChronologicalAge=", - this.FixedChronologicalAge, - ", fixedGender=", - this.FixedGender, - ", fixedMelanin=", - this.FixedMelanin, - ", fixedLastName=", - this.FixedLastName - }); + return "kindDef=" + this.KindDef + ", context=" + this.Context + ", faction=" + this.Faction + ", tile=" + this.Tile + ", forceGenerateNewPawn=" + this.ForceGenerateNewPawn + ", newborn=" + this.Newborn + ", allowDead=" + this.AllowDead + ", allowDowned=" + this.AllowDowned + ", canGeneratePawnRelations=" + this.CanGeneratePawnRelations + ", mustBeCapableOfViolence=" + this.MustBeCapableOfViolence + ", colonistRelationChanceFactor=" + this.ColonistRelationChanceFactor + ", forceAddFreeWarmLayerIfNeeded=" + this.ForceAddFreeWarmLayerIfNeeded + ", allowGay=" + this.AllowGay + ", allowFood=" + this.AllowFood + ", inhabitant=" + this.Inhabitant + ", certainlyBeenInCryptosleep=" + this.CertainlyBeenInCryptosleep + ", validator=" + this.Validator + ", fixedBiologicalAge=" + this.FixedBiologicalAge + ", fixedChronologicalAge=" + this.FixedChronologicalAge + ", fixedGender=" + this.FixedGender + ", fixedMelanin=" + this.FixedMelanin + ", fixedLastName=" + this.FixedLastName; } } } diff --git a/Assembly-CSharp/Verse/PawnGenerator.cs b/Assembly-CSharp/Verse/PawnGenerator.cs index 0e373d565..dc0bf0c8c 100644 --- a/Assembly-CSharp/Verse/PawnGenerator.cs +++ b/Assembly-CSharp/Verse/PawnGenerator.cs @@ -34,7 +34,7 @@ public PawnGenerationStatus(Pawn pawn, List pawnsGeneratedInTheMeantime) public const int MaxStartMentalBreakThreshold = 40; - private static List pawnsBeingGenerated = new List(); + private static List pawnsBeingGenerated = new List(); private static SimpleCurve DefaultAgeGenerationCurve = new SimpleCurve { @@ -142,7 +142,7 @@ public PawnGenerationStatus(Pawn pawn, List pawnsGeneratedInTheMeantime) public static Pawn GeneratePawn(PawnKindDef kindDef, Faction faction = null) { - return PawnGenerator.GeneratePawn(new PawnGenerationRequest(kindDef, faction, PawnGenerationContext.NonPlayer, -1, false, false, false, false, true, false, 1f, false, true, true, false, false, null, null, null, null, null, null)); + return PawnGenerator.GeneratePawn(new PawnGenerationRequest(kindDef, faction, PawnGenerationContext.NonPlayer, -1, false, false, false, false, true, false, 1f, false, true, true, false, false, null, default(float?), default(float?), default(Gender?), default(float?), (string)null)); } public static Pawn GeneratePawn(PawnGenerationRequest request) @@ -154,12 +154,12 @@ public static Pawn GeneratePawn(PawnGenerationRequest request) if (request.Inhabitant && request.Tile != -1) { Settlement settlement = Find.WorldObjects.WorldObjectAt(request.Tile); - if (settlement != null && settlement.previouslyGeneratedInhabitants.Any()) + if (settlement != null && settlement.previouslyGeneratedInhabitants.Any()) { IEnumerable validCandidatesToRedress = PawnGenerator.GetValidCandidatesToRedress(request); if ((from x in validCandidatesToRedress where settlement.previouslyGeneratedInhabitants.Contains(x) - select x).TryRandomElementByWeight((Pawn x) => PawnGenerator.WorldPawnSelectionWeight(x), out pawn)) + select x).TryRandomElementByWeight((Func)((Pawn x) => PawnGenerator.WorldPawnSelectionWeight(x)), out pawn)) { PawnGenerator.RedressPawn(pawn, request); Find.WorldPawns.RemovePawn(pawn); @@ -169,7 +169,7 @@ where settlement.previouslyGeneratedInhabitants.Contains(x) if (pawn == null && Rand.Value < PawnGenerator.ChanceToRedressAnyWorldPawn()) { IEnumerable validCandidatesToRedress2 = PawnGenerator.GetValidCandidatesToRedress(request); - if (validCandidatesToRedress2.TryRandomElementByWeight((Pawn x) => PawnGenerator.WorldPawnSelectionWeight(x), out pawn)) + if (validCandidatesToRedress2.TryRandomElementByWeight((Func)((Pawn x) => PawnGenerator.WorldPawnSelectionWeight(x)), out pawn)) { PawnGenerator.RedressPawn(pawn, request); Find.WorldPawns.RemovePawn(pawn); @@ -211,7 +211,7 @@ public static void RedressPawn(Pawn pawn, PawnGenerationRequest request) public static bool IsBeingGenerated(Pawn pawn) { - return PawnGenerator.pawnsBeingGenerated.Any((PawnGenerator.PawnGenerationStatus x) => x.Pawn == pawn); + return PawnGenerator.pawnsBeingGenerated.Any((Predicate)((PawnGenerationStatus x) => x.Pawn == pawn)); } private static bool IsValidCandidateToRedress(Pawn pawn, PawnGenerationRequest request) @@ -232,7 +232,7 @@ private static bool IsValidCandidateToRedress(Pawn pawn, PawnGenerationRequest r { return false; } - if (pawn.health.hediffSet.BleedRateTotal > 0.001f) + if (pawn.health.hediffSet.BleedRateTotal > 0.0010000000474974513) { return false; } @@ -244,7 +244,7 @@ private static bool IsValidCandidateToRedress(Pawn pawn, PawnGenerationRequest r { return false; } - if (request.Validator != null && !request.Validator(pawn)) + if ((object)request.Validator != null && !request.Validator(pawn)) { return false; } @@ -285,20 +285,13 @@ private static bool IsValidCandidateToRedress(Pawn pawn, PawnGenerationRequest r private static Pawn GenerateNewNakedPawn(ref PawnGenerationRequest request) { Pawn pawn = null; - string text = null; + string text = (string)null; bool ignoreScenarioRequirements = false; for (int i = 0; i < 100; i++) { if (i == 70) { - Log.Error(string.Concat(new object[] - { - "Could not generate a pawn after ", - 70, - " tries. Last error: ", - text, - " Ignoring scenario requirements." - })); + Log.Error("Could not generate a pawn after " + 70 + " tries. Last error: " + text + " Ignoring scenario requirements."); ignoreScenarioRequirements = true; } PawnGenerationRequest pawnGenerationRequest = request; @@ -311,15 +304,7 @@ private static Pawn GenerateNewNakedPawn(ref PawnGenerationRequest request) } if (pawn == null) { - Log.Error(string.Concat(new object[] - { - "Pawn generation error: ", - text, - " Too many tries (", - 100, - "), returning null. Generation request: ", - request - })); + Log.Error("Pawn generation error: " + text + " Too many tries (" + 100 + "), returning null. Generation request: " + request); return null; } return pawn; @@ -327,10 +312,9 @@ private static Pawn GenerateNewNakedPawn(ref PawnGenerationRequest request) private static Pawn TryGenerateNewNakedPawn(ref PawnGenerationRequest request, out string error, bool ignoreScenarioRequirements) { - error = null; + error = (string)null; Pawn pawn = (Pawn)ThingMaker.MakeThing(request.KindDef.race, null); - PawnGenerator.pawnsBeingGenerated.Add(new PawnGenerator.PawnGenerationStatus(pawn, null)); - Pawn result; + PawnGenerator.pawnsBeingGenerated.Add(new PawnGenerationStatus(pawn, null)); try { pawn.kindDef = request.KindDef; @@ -342,7 +326,7 @@ private static Pawn TryGenerateNewNakedPawn(ref PawnGenerationRequest request, o } else if (pawn.RaceProps.hasGenders) { - if (Rand.Value < 0.5f) + if (Rand.Value < 0.5) { pawn.gender = Gender.Male; } @@ -364,7 +348,7 @@ private static Pawn TryGenerateNewNakedPawn(ref PawnGenerationRequest request, o if (pawn.RaceProps.Humanlike) { pawn.story.melanin = ((!request.FixedMelanin.HasValue) ? PawnSkinColors.RandomMelanin() : request.FixedMelanin.Value); - pawn.story.crownType = ((Rand.Value >= 0.5f) ? CrownType.Narrow : CrownType.Average); + pawn.story.crownType = (CrownType)((Rand.Value < 0.5) ? 1 : 2); pawn.story.hairColor = PawnHairColors.RandomHairColor(pawn.story.SkinColor, pawn.ageTracker.AgeBiologicalYears); PawnBioAndNameGenerator.GiveAppropriateBioAndNameTo(pawn, request.FixedLastName); pawn.story.hairDef = PawnHairChooser.RandomHairDefFor(pawn, request.Faction.def); @@ -385,50 +369,56 @@ private static Pawn TryGenerateNewNakedPawn(ref PawnGenerationRequest request, o { PawnGenerator.DiscardGeneratedPawn(pawn); error = "Generated dead pawn."; - result = null; + return null; } - else if (!request.AllowDowned && pawn.Downed) + if (!request.AllowDowned && pawn.Downed) { PawnGenerator.DiscardGeneratedPawn(pawn); error = "Generated downed pawn."; - result = null; + return null; } - else if (request.MustBeCapableOfViolence && ((pawn.story != null && pawn.story.WorkTagIsDisabled(WorkTags.Violent)) || !pawn.health.capacities.CapableOf(PawnCapacityDefOf.Manipulation))) + if (request.MustBeCapableOfViolence) { - PawnGenerator.DiscardGeneratedPawn(pawn); - error = "Generated pawn incapable of violence."; - result = null; + if (pawn.story != null && pawn.story.WorkTagIsDisabled(WorkTags.Violent)) + { + goto IL_02ab; + } + if (!pawn.health.capacities.CapableOf(PawnCapacityDefOf.Manipulation)) + goto IL_02ab; } - else if (!ignoreScenarioRequirements && request.Context == PawnGenerationContext.PlayerStarter && !Find.Scenario.AllowPlayerStartingPawn(pawn)) + if (!ignoreScenarioRequirements && request.Context == PawnGenerationContext.PlayerStarter && !Find.Scenario.AllowPlayerStartingPawn(pawn)) { PawnGenerator.DiscardGeneratedPawn(pawn); error = "Generated pawn doesn't meet scenario requirements."; - result = null; + return null; } - else if (request.Validator != null && !request.Validator(pawn)) + if ((object)request.Validator != null && !request.Validator(pawn)) { PawnGenerator.DiscardGeneratedPawn(pawn); error = "Generated pawn didn't pass validator check."; - result = null; + return null; } - else + for (int i = 0; i < PawnGenerator.pawnsBeingGenerated.Count - 1; i++) { - for (int i = 0; i < PawnGenerator.pawnsBeingGenerated.Count - 1; i++) + if (PawnGenerator.pawnsBeingGenerated[i].PawnsGeneratedInTheMeantime == null) { - if (PawnGenerator.pawnsBeingGenerated[i].PawnsGeneratedInTheMeantime == null) - { - PawnGenerator.pawnsBeingGenerated[i] = new PawnGenerator.PawnGenerationStatus(PawnGenerator.pawnsBeingGenerated[i].Pawn, new List()); - } - PawnGenerator.pawnsBeingGenerated[i].PawnsGeneratedInTheMeantime.Add(pawn); + PawnGenerator.pawnsBeingGenerated[i] = new PawnGenerationStatus(PawnGenerator.pawnsBeingGenerated[i].Pawn, new List()); } - result = pawn; - } + PawnGenerator.pawnsBeingGenerated[i].PawnsGeneratedInTheMeantime.Add(pawn); + } + return pawn; + IL_03a9: + Pawn result; + return result; + IL_02ab: + PawnGenerator.DiscardGeneratedPawn(pawn); + error = "Generated pawn incapable of violence."; + return null; } finally { - PawnGenerator.pawnsBeingGenerated.RemoveLast(); + PawnGenerator.pawnsBeingGenerated.RemoveLast(); } - return result; } private static void DiscardGeneratedPawn(Pawn pawn) @@ -438,7 +428,7 @@ private static void DiscardGeneratedPawn(Pawn pawn) Find.WorldPawns.RemovePawn(pawn); } Find.WorldPawns.PassToWorld(pawn, PawnDiscardDecideMode.Discard); - List pawnsGeneratedInTheMeantime = PawnGenerator.pawnsBeingGenerated.Last().PawnsGeneratedInTheMeantime; + List pawnsGeneratedInTheMeantime = PawnGenerator.pawnsBeingGenerated.Last().PawnsGeneratedInTheMeantime; if (pawnsGeneratedInTheMeantime != null) { for (int i = 0; i < pawnsGeneratedInTheMeantime.Count; i++) @@ -472,7 +462,7 @@ where PawnGenerator.IsValidCandidateToRedress(x, request) private static float ChanceToRedressAnyWorldPawn() { int pawnsBySituationCount = Find.WorldPawns.GetPawnsBySituationCount(WorldPawnSituation.Free); - return Mathf.Min(0.02f + 0.01f * ((float)pawnsBySituationCount / 10f), 0.8f); + return Mathf.Min((float)(0.019999999552965164 + 0.0099999997764825821 * ((float)pawnsBySituationCount / 10.0)), 0.8f); } private static float WorldPawnSelectionWeight(Pawn p) @@ -508,105 +498,71 @@ private static void GenerateInitialHediffs(Pawn pawn, PawnGenerationRequest requ PawnTechHediffsGenerator.GeneratePartsAndImplantsFor(pawn); PawnAddictionHediffsGenerator.GenerateAddictionsAndTolerancesFor(pawn); if (request.AllowDead && pawn.Dead) - { - break; - } - if (request.AllowDowned || !pawn.Downed) - { return; - } - pawn.health.Reset(); - num++; - if (num > 80) + if (!request.AllowDowned && pawn.Downed) { - goto Block_4; + pawn.health.Reset(); + num++; + if (num > 80) + break; + continue; } + return; } - return; - Block_4: - Log.Warning(string.Concat(new object[] - { - "Could not generate old age injuries for ", - pawn.ThingID, - " of age ", - pawn.ageTracker.AgeBiologicalYears, - " that allow pawn to move after ", - 80, - " tries. request=", - request - })); + Log.Warning("Could not generate old age injuries for " + pawn.ThingID + " of age " + pawn.ageTracker.AgeBiologicalYears + " that allow pawn to move after " + 80 + " tries. request=" + request); } private static void GenerateRandomAge(Pawn pawn, PawnGenerationRequest request) { + int num; if (request.FixedBiologicalAge.HasValue && request.FixedChronologicalAge.HasValue) { float? fixedBiologicalAge = request.FixedBiologicalAge; - bool arg_67_0; if (fixedBiologicalAge.HasValue) { float? fixedChronologicalAge = request.FixedChronologicalAge; if (fixedChronologicalAge.HasValue) { - arg_67_0 = (fixedBiologicalAge.Value > fixedChronologicalAge.Value); - goto IL_67; + num = ((fixedBiologicalAge.Value > fixedChronologicalAge.Value) ? 1 : 0); + goto IL_0067; } } - arg_67_0 = false; - IL_67: - if (arg_67_0) - { - Log.Warning(string.Concat(new object[] - { - "Tried to generate age for pawn ", - pawn, - ", but pawn generation request demands biological age (", - request.FixedBiologicalAge, - ") to be greater than chronological age (", - request.FixedChronologicalAge, - ")." - })); - } + num = 0; + goto IL_0067; + } + goto IL_00be; + IL_0067: + if (num != 0) + { + Log.Warning("Tried to generate age for pawn " + pawn + ", but pawn generation request demands biological age (" + request.FixedBiologicalAge + ") to be greater than chronological age (" + request.FixedChronologicalAge + ")."); } + goto IL_00be; + IL_00be: if (request.Newborn) { pawn.ageTracker.AgeBiologicalTicks = 0L; } else if (request.FixedBiologicalAge.HasValue) { - pawn.ageTracker.AgeBiologicalTicks = (long)(request.FixedBiologicalAge.Value * 3600000f); + pawn.ageTracker.AgeBiologicalTicks = (long)(request.FixedBiologicalAge.Value * 3600000.0); } else { - int num = 0; - float num2; + float num2 = 0f; + int num3 = 0; while (true) { - if (pawn.RaceProps.ageGenerationCurve != null) - { - num2 = (float)Mathf.RoundToInt(Rand.ByCurve(pawn.RaceProps.ageGenerationCurve, 200)); - } - else if (pawn.RaceProps.IsMechanoid) - { - num2 = (float)Rand.Range(0, 2500); - } - else - { - num2 = Rand.ByCurve(PawnGenerator.DefaultAgeGenerationCurve, 200) * pawn.RaceProps.lifeExpectancy; - } - num++; - if (num > 300) + num2 = ((pawn.RaceProps.ageGenerationCurve == null) ? ((!pawn.RaceProps.IsMechanoid) ? (Rand.ByCurve(PawnGenerator.DefaultAgeGenerationCurve, 200) * pawn.RaceProps.lifeExpectancy) : ((float)Rand.Range(0, 2500))) : ((float)Mathf.RoundToInt(Rand.ByCurve(pawn.RaceProps.ageGenerationCurve, 200)))); + num3++; + if (num3 > 300) { + Log.Error("Tried 300 times to generate age for " + pawn); break; } - if (num2 <= (float)pawn.kindDef.maxGenerationAge && num2 >= (float)pawn.kindDef.minGenerationAge) - { - goto IL_1DB; - } + if (!(num2 > (float)pawn.kindDef.maxGenerationAge) && !(num2 < (float)pawn.kindDef.minGenerationAge)) + break; } - Log.Error("Tried 300 times to generate age for " + pawn); - IL_1DB: - pawn.ageTracker.AgeBiologicalTicks = (long)(num2 * 3600000f) + (long)Rand.Range(0, 3600000); + pawn.ageTracker.AgeBiologicalTicks = (long)(num2 * 3600000.0) + Rand.Range(0, 3600000); } if (request.Newborn) { @@ -614,36 +570,36 @@ private static void GenerateRandomAge(Pawn pawn, PawnGenerationRequest request) } else if (request.FixedChronologicalAge.HasValue) { - pawn.ageTracker.AgeChronologicalTicks = (long)(request.FixedChronologicalAge.Value * 3600000f); + pawn.ageTracker.AgeChronologicalTicks = (long)(request.FixedChronologicalAge.Value * 3600000.0); } else { - int num3; + int num4; if (request.CertainlyBeenInCryptosleep || Rand.Value < pawn.kindDef.backstoryCryptosleepCommonality) { float value = Rand.Value; - if (value < 0.7f) + if (value < 0.699999988079071) { - num3 = Rand.Range(0, 100); + num4 = Rand.Range(0, 100); } - else if (value < 0.95f) + else if (value < 0.949999988079071) { - num3 = Rand.Range(100, 1000); + num4 = Rand.Range(100, 1000); } else { - int max = GenDate.Year((long)GenTicks.TicksAbs, 0f) - 2026 - pawn.ageTracker.AgeBiologicalYears; - num3 = Rand.Range(1000, max); + int max = GenDate.Year(GenTicks.TicksAbs, 0f) - 2026 - pawn.ageTracker.AgeBiologicalYears; + num4 = Rand.Range(1000, max); } } else { - num3 = 0; + num4 = 0; } int ticksAbs = GenTicks.TicksAbs; - long num4 = (long)ticksAbs - pawn.ageTracker.AgeBiologicalTicks; - num4 -= (long)num3 * 3600000L; - pawn.ageTracker.BirthAbsTicks = num4; + long num5 = ticksAbs - pawn.ageTracker.AgeBiologicalTicks; + num5 -= (long)num4 * 3600000L; + pawn.ageTracker.BirthAbsTicks = num5; } if (pawn.ageTracker.AgeBiologicalTicks > pawn.ageTracker.AgeChronologicalTicks) { @@ -657,97 +613,76 @@ public static int RandomTraitDegree(TraitDef traitDef) { return traitDef.degreeDatas[0].degree; } - return traitDef.degreeDatas.RandomElementByWeight((TraitDegreeData dd) => dd.Commonality).degree; + return traitDef.degreeDatas.RandomElementByWeight((Func)((TraitDegreeData dd) => dd.Commonality)).degree; } private static void GenerateTraits(Pawn pawn, PawnGenerationRequest request) { - if (pawn.story == null) - { - return; - } - if (pawn.story.childhood.forcedTraits != null) - { - List forcedTraits = pawn.story.childhood.forcedTraits; - for (int i = 0; i < forcedTraits.Count; i++) - { - TraitEntry traitEntry = forcedTraits[i]; - if (traitEntry.def == null) - { - Log.Error("Null forced trait def on " + pawn.story.childhood); - } - else if (!pawn.story.traits.HasTrait(traitEntry.def)) - { - pawn.story.traits.GainTrait(new Trait(traitEntry.def, traitEntry.degree, false)); - } - } - } - if (pawn.story.adulthood != null && pawn.story.adulthood.forcedTraits != null) + if (pawn.story != null) { - List forcedTraits2 = pawn.story.adulthood.forcedTraits; - for (int j = 0; j < forcedTraits2.Count; j++) + if (pawn.story.childhood.forcedTraits != null) { - TraitEntry traitEntry2 = forcedTraits2[j]; - if (traitEntry2.def == null) - { - Log.Error("Null forced trait def on " + pawn.story.adulthood); - } - else if (!pawn.story.traits.HasTrait(traitEntry2.def)) + List forcedTraits = pawn.story.childhood.forcedTraits; + for (int i = 0; i < forcedTraits.Count; i++) { - pawn.story.traits.GainTrait(new Trait(traitEntry2.def, traitEntry2.degree, false)); + TraitEntry traitEntry = forcedTraits[i]; + if (traitEntry.def == null) + { + Log.Error("Null forced trait def on " + pawn.story.childhood); + } + else if (!pawn.story.traits.HasTrait(traitEntry.def)) + { + pawn.story.traits.GainTrait(new Trait(traitEntry.def, traitEntry.degree, false)); + } } } - } - int num = Rand.RangeInclusive(2, 3); - if (request.AllowGay && (LovePartnerRelationUtility.HasAnyLovePartnerOfTheSameGender(pawn) || LovePartnerRelationUtility.HasAnyExLovePartnerOfTheSameGender(pawn))) - { - Trait trait = new Trait(TraitDefOf.Gay, PawnGenerator.RandomTraitDegree(TraitDefOf.Gay), false); - pawn.story.traits.GainTrait(trait); - } - while (pawn.story.traits.allTraits.Count < num) - { - TraitDef newTraitDef = DefDatabase.AllDefsListForReading.RandomElementByWeight((TraitDef tr) => tr.GetGenderSpecificCommonality(pawn)); - if (!pawn.story.traits.HasTrait(newTraitDef)) + if (pawn.story.adulthood != null && pawn.story.adulthood.forcedTraits != null) { - if (newTraitDef == TraitDefOf.Gay) + List forcedTraits2 = pawn.story.adulthood.forcedTraits; + for (int j = 0; j < forcedTraits2.Count; j++) { - if (!request.AllowGay) + TraitEntry traitEntry2 = forcedTraits2[j]; + if (traitEntry2.def == null) { - continue; + Log.Error("Null forced trait def on " + pawn.story.adulthood); } - if (LovePartnerRelationUtility.HasAnyLovePartnerOfTheOppositeGender(pawn) || LovePartnerRelationUtility.HasAnyExLovePartnerOfTheOppositeGender(pawn)) + else if (!pawn.story.traits.HasTrait(traitEntry2.def)) { - continue; + pawn.story.traits.GainTrait(new Trait(traitEntry2.def, traitEntry2.degree, false)); } } - if (request.Faction == null || Faction.OfPlayerSilentFail == null || !request.Faction.HostileTo(Faction.OfPlayer) || newTraitDef.allowOnHostileSpawn) + } + int num = Rand.RangeInclusive(2, 3); + if (request.AllowGay && (LovePartnerRelationUtility.HasAnyLovePartnerOfTheSameGender(pawn) || LovePartnerRelationUtility.HasAnyExLovePartnerOfTheSameGender(pawn))) + { + Trait trait = new Trait(TraitDefOf.Gay, PawnGenerator.RandomTraitDegree(TraitDefOf.Gay), false); + pawn.story.traits.GainTrait(trait); + } + while (pawn.story.traits.allTraits.Count < num) + { + TraitDef newTraitDef = DefDatabase.AllDefsListForReading.RandomElementByWeight((Func)((TraitDef tr) => tr.GetGenderSpecificCommonality(pawn))); + Trait trait2; + if (!pawn.story.traits.HasTrait(newTraitDef) && (newTraitDef != TraitDefOf.Gay || (request.AllowGay && !LovePartnerRelationUtility.HasAnyLovePartnerOfTheOppositeGender(pawn) && !LovePartnerRelationUtility.HasAnyExLovePartnerOfTheOppositeGender(pawn))) && (request.Faction == null || Faction.OfPlayerSilentFail == null || !request.Faction.HostileTo(Faction.OfPlayer) || newTraitDef.allowOnHostileSpawn) && !pawn.story.traits.allTraits.Any((Predicate)((Trait tr) => newTraitDef.ConflictsWith(tr))) && (newTraitDef.conflictingTraits == null || !newTraitDef.conflictingTraits.Any((Predicate)((TraitDef tr) => pawn.story.traits.HasTrait(tr)))) && (newTraitDef.requiredWorkTypes == null || !pawn.story.OneOfWorkTypesIsDisabled(newTraitDef.requiredWorkTypes)) && !pawn.story.WorkTagIsDisabled(newTraitDef.requiredWorkTags)) { - if (!pawn.story.traits.allTraits.Any((Trait tr) => newTraitDef.ConflictsWith(tr)) && (newTraitDef.conflictingTraits == null || !newTraitDef.conflictingTraits.Any((TraitDef tr) => pawn.story.traits.HasTrait(tr)))) + int degree = PawnGenerator.RandomTraitDegree(newTraitDef); + if (!pawn.story.childhood.DisallowsTrait(newTraitDef, degree) && (pawn.story.adulthood == null || !pawn.story.adulthood.DisallowsTrait(newTraitDef, degree))) { - if (newTraitDef.requiredWorkTypes == null || !pawn.story.OneOfWorkTypesIsDisabled(newTraitDef.requiredWorkTypes)) + trait2 = new Trait(newTraitDef, degree, false); + if (pawn.mindState != null && pawn.mindState.mentalBreaker != null) { - if (!pawn.story.WorkTagIsDisabled(newTraitDef.requiredWorkTags)) - { - int degree = PawnGenerator.RandomTraitDegree(newTraitDef); - if (!pawn.story.childhood.DisallowsTrait(newTraitDef, degree) && (pawn.story.adulthood == null || !pawn.story.adulthood.DisallowsTrait(newTraitDef, degree))) - { - Trait trait2 = new Trait(newTraitDef, degree, false); - if (pawn.mindState != null && pawn.mindState.mentalBreaker != null) - { - float num2 = pawn.mindState.mentalBreaker.BreakThresholdExtreme; - num2 += trait2.OffsetOfStat(StatDefOf.MentalBreakThreshold); - num2 *= trait2.MultiplierOfStat(StatDefOf.MentalBreakThreshold); - if (num2 > 40f) - { - continue; - } - } - pawn.story.traits.GainTrait(trait2); - } - } + float breakThresholdExtreme = pawn.mindState.mentalBreaker.BreakThresholdExtreme; + breakThresholdExtreme += trait2.OffsetOfStat(StatDefOf.MentalBreakThreshold); + breakThresholdExtreme *= trait2.MultiplierOfStat(StatDefOf.MentalBreakThreshold); + if (!(breakThresholdExtreme > 40.0)) + goto IL_04d9; + continue; } + goto IL_04d9; } } + continue; + IL_04d9: + pawn.story.traits.GainTrait(trait2); } } } @@ -758,13 +693,13 @@ private static void GenerateBodyType(Pawn pawn) { pawn.story.bodyType = pawn.story.adulthood.BodyTypeFor(pawn.gender); } - else if (Rand.Value < 0.5f) + else if (Rand.Value < 0.5) { pawn.story.bodyType = BodyType.Thin; } else { - pawn.story.bodyType = ((pawn.gender != Gender.Female) ? BodyType.Male : BodyType.Female); + pawn.story.bodyType = (BodyType)((pawn.gender != Gender.Female) ? 1 : 2); } } @@ -779,11 +714,11 @@ private static void GenerateSkills(Pawn pawn) skill.Level = num; if (!skill.TotallyDisabled) { - float num2 = (float)num * 0.11f; + float num2 = (float)((float)num * 0.10999999940395355); float value = Rand.Value; if (value < num2) { - if (value < num2 * 0.2f) + if (value < num2 * 0.20000000298023224) { skill.passion = Passion.Major; } @@ -792,33 +727,34 @@ private static void GenerateSkills(Pawn pawn) skill.passion = Passion.Minor; } } - skill.xpSinceLastLevel = Rand.Range(skill.XpRequiredForLevelUp * 0.1f, skill.XpRequiredForLevelUp * 0.9f); + skill.xpSinceLastLevel = Rand.Range((float)(skill.XpRequiredForLevelUp * 0.10000000149011612), (float)(skill.XpRequiredForLevelUp * 0.89999997615814209)); } } } private static int FinalLevelOfSkill(Pawn pawn, SkillDef sk) { - float num; - if (sk.usuallyDefinedInBackstories) - { - num = (float)Rand.RangeInclusive(0, 4); - } - else - { - num = Rand.ByCurve(PawnGenerator.LevelRandomCurve, 100); - } - foreach (Backstory current in from bs in pawn.story.AllBackstories + float num = (!sk.usuallyDefinedInBackstories) ? Rand.ByCurve(PawnGenerator.LevelRandomCurve, 100) : ((float)Rand.RangeInclusive(0, 4)); + foreach (Backstory item in from bs in pawn.story.AllBackstories where bs != null select bs) { - foreach (KeyValuePair current2 in current.skillGainsResolved) + Dictionary.Enumerator enumerator2 = item.skillGainsResolved.GetEnumerator(); + try { - if (current2.Key == sk) + while (enumerator2.MoveNext()) { - num += (float)current2.Value * Rand.Range(1f, 1.4f); + KeyValuePair current2 = enumerator2.Current; + if (current2.Key == sk) + { + num += (float)current2.Value * Rand.Range(1f, 1.4f); + } } } + finally + { + ((IDisposable)(object)enumerator2).Dispose(); + } } for (int i = 0; i < pawn.story.traits.allTraits.Count; i++) { @@ -844,74 +780,66 @@ public static void PostProcessGeneratedGear(Thing gear, Pawn pawn) if (gear.def.useHitPoints) { float randomInRange = pawn.kindDef.gearHealthRange.RandomInRange; - if (randomInRange < 1f) + if (randomInRange < 1.0) { - int num = Mathf.RoundToInt(randomInRange * (float)gear.MaxHitPoints); - num = Mathf.Max(1, num); - gear.HitPoints = num; + int b = Mathf.RoundToInt(randomInRange * (float)gear.MaxHitPoints); + b = Mathf.Max(1, b); + gear.HitPoints = b; } } } private static void GeneratePawnRelations(Pawn pawn, ref PawnGenerationRequest request) { - if (!pawn.RaceProps.Humanlike) - { - return; - } - List> list = new List>(); - List allDefsListForReading = DefDatabase.AllDefsListForReading; - IEnumerable enumerable = from x in PawnsFinder.AllMapsAndWorld_AliveOrDead - where x.def == pawn.def - select x; - foreach (Pawn current in enumerable) + if (pawn.RaceProps.Humanlike) { - if (current.Discarded) + List> list = new List>(); + List allDefsListForReading = DefDatabase.AllDefsListForReading; + IEnumerable enumerable = from x in PawnsFinder.AllMapsAndWorld_AliveOrDead + where x.def == pawn.def + select x; + foreach (Pawn item in enumerable) { - Log.Warning(string.Concat(new object[] + if (item.Discarded) { - "Warning during generating pawn relations for ", - pawn, - ": Pawn ", - current, - " is discarded, yet he was yielded by PawnUtility. Discarding a pawn means that he is no longer managed by anything." - })); - } - else - { - for (int i = 0; i < allDefsListForReading.Count; i++) + Log.Warning("Warning during generating pawn relations for " + pawn + ": Pawn " + item + " is discarded, yet he was yielded by PawnUtility. Discarding a pawn means that he is no longer managed by anything."); + } + else { - if (allDefsListForReading[i].generationChanceFactor > 0f) + for (int i = 0; i < allDefsListForReading.Count; i++) { - list.Add(new KeyValuePair(current, allDefsListForReading[i])); + if (!(allDefsListForReading[i].generationChanceFactor <= 0.0)) + { + list.Add(new KeyValuePair(item, allDefsListForReading[i])); + } } } } - } - PawnGenerationRequest localReq = request; - KeyValuePair keyValuePair = list.RandomElementByWeightWithDefault(delegate(KeyValuePair x) - { - if (!x.Value.familyByBloodRelation) + PawnGenerationRequest localReq = request; + KeyValuePair keyValuePair = list.RandomElementByWeightWithDefault((Func, float>)delegate(KeyValuePair x) + { + if (!x.Value.familyByBloodRelation) + { + return 0f; + } + return x.Value.generationChanceFactor * x.Value.Worker.GenerationChance(pawn, x.Key, localReq); + }, 82f); + if (keyValuePair.Key != null) { - return 0f; + keyValuePair.Value.Worker.CreateRelation(pawn, keyValuePair.Key, ref request); } - return x.Value.generationChanceFactor * x.Value.Worker.GenerationChance(pawn, x.Key, localReq); - }, 82f); - if (keyValuePair.Key != null) - { - keyValuePair.Value.Worker.CreateRelation(pawn, keyValuePair.Key, ref request); - } - KeyValuePair keyValuePair2 = list.RandomElementByWeightWithDefault(delegate(KeyValuePair x) - { - if (x.Value.familyByBloodRelation) + KeyValuePair keyValuePair2 = list.RandomElementByWeightWithDefault((Func, float>)delegate(KeyValuePair x) + { + if (x.Value.familyByBloodRelation) + { + return 0f; + } + return x.Value.generationChanceFactor * x.Value.Worker.GenerationChance(pawn, x.Key, localReq); + }, 82f); + if (keyValuePair2.Key != null) { - return 0f; + keyValuePair2.Value.Worker.CreateRelation(pawn, keyValuePair2.Key, ref request); } - return x.Value.generationChanceFactor * x.Value.Worker.GenerationChance(pawn, x.Key, localReq); - }, 82f); - if (keyValuePair2.Key != null) - { - keyValuePair2.Value.Worker.CreateRelation(pawn, keyValuePair2.Key, ref request); } } } diff --git a/Assembly-CSharp/Verse/PawnGraphicSet.cs b/Assembly-CSharp/Verse/PawnGraphicSet.cs index a005b9b62..2db4b1f6e 100644 --- a/Assembly-CSharp/Verse/PawnGraphicSet.cs +++ b/Assembly-CSharp/Verse/PawnGraphicSet.cs @@ -1,5 +1,4 @@ using RimWorld; -using System; using System.Collections.Generic; using UnityEngine; @@ -77,59 +76,77 @@ public List MatsBodyBaseAt(Rot4 facing, RotDrawMode bodyCondition = Ro { this.cachedMatsBodyBase.Clear(); this.cachedMatsBodyBaseHash = num; - if (bodyCondition == RotDrawMode.Fresh) + switch (bodyCondition) + { + case RotDrawMode.Rotting: + goto IL_0063; + case RotDrawMode.Fresh: { this.cachedMatsBodyBase.Add(this.nakedGraphic.MatAt(facing, null)); + break; } - else if (bodyCondition == RotDrawMode.Rotting || this.dessicatedGraphic == null) + default: { - this.cachedMatsBodyBase.Add(this.rottingGraphic.MatAt(facing, null)); + if (this.dessicatedGraphic == null) + goto IL_0063; + if (bodyCondition == RotDrawMode.Dessicated) + { + this.cachedMatsBodyBase.Add(this.dessicatedGraphic.MatAt(facing, null)); + } + break; } - else if (bodyCondition == RotDrawMode.Dessicated) - { - this.cachedMatsBodyBase.Add(this.dessicatedGraphic.MatAt(facing, null)); } - for (int i = 0; i < this.apparelGraphics.Count; i++) + goto IL_009f; + } + goto IL_0134; + IL_009f: + for (int i = 0; i < this.apparelGraphics.Count; i++) + { + ApparelGraphicRecord apparelGraphicRecord = this.apparelGraphics[i]; + if (apparelGraphicRecord.sourceApparel.def.apparel.LastLayer != ApparelLayer.Shell) { - if (this.apparelGraphics[i].sourceApparel.def.apparel.LastLayer != ApparelLayer.Shell && this.apparelGraphics[i].sourceApparel.def.apparel.LastLayer != ApparelLayer.Overhead) + ApparelGraphicRecord apparelGraphicRecord2 = this.apparelGraphics[i]; + if (apparelGraphicRecord2.sourceApparel.def.apparel.LastLayer != ApparelLayer.Overhead) { - this.cachedMatsBodyBase.Add(this.apparelGraphics[i].graphic.MatAt(facing, null)); + List obj = this.cachedMatsBodyBase; + ApparelGraphicRecord apparelGraphicRecord3 = this.apparelGraphics[i]; + obj.Add(apparelGraphicRecord3.graphic.MatAt(facing, null)); } } } + goto IL_0134; + IL_0063: + this.cachedMatsBodyBase.Add(this.rottingGraphic.MatAt(facing, null)); + goto IL_009f; + IL_0134: return this.cachedMatsBodyBase; } public Material HeadMatAt(Rot4 facing, RotDrawMode bodyCondition = RotDrawMode.Fresh, bool stump = false) { Material material = null; - if (bodyCondition == RotDrawMode.Fresh) + switch (bodyCondition) { - if (stump) - { - material = this.headStumpGraphic.MatAt(facing, null); - } - else - { - material = this.headGraphic.MatAt(facing, null); - } + case RotDrawMode.Fresh: + { + material = ((!stump) ? this.headGraphic.MatAt(facing, null) : this.headStumpGraphic.MatAt(facing, null)); + break; } - else if (bodyCondition == RotDrawMode.Rotting) + case RotDrawMode.Rotting: { - if (stump) - { - material = this.desiccatedHeadStumpGraphic.MatAt(facing, null); - } - else + material = ((!stump) ? this.desiccatedHeadGraphic.MatAt(facing, null) : this.desiccatedHeadStumpGraphic.MatAt(facing, null)); + break; + } + case RotDrawMode.Dessicated: + { + if (!stump) { - material = this.desiccatedHeadGraphic.MatAt(facing, null); + material = this.skullGraphic.MatAt(facing, null); } + break; } - else if (bodyCondition == RotDrawMode.Dessicated && !stump) - { - material = this.skullGraphic.MatAt(facing, null); } - if (material != null) + if ((Object)material != (Object)null) { material = this.flasher.GetDamagedMat(material); } @@ -190,10 +207,10 @@ public void ResolveApparelGraphics() { this.ClearCache(); this.apparelGraphics.Clear(); - foreach (Apparel current in this.pawn.apparel.WornApparelInDrawOrder) + foreach (Apparel item2 in this.pawn.apparel.WornApparelInDrawOrder) { - ApparelGraphicRecord item; - if (ApparelGraphicRecordGetter.TryGetGraphicApparel(current, this.pawn.story.bodyType, out item)) + ApparelGraphicRecord item = default(ApparelGraphicRecord); + if (ApparelGraphicRecordGetter.TryGetGraphicApparel(item2, this.pawn.story.bodyType, out item)) { this.apparelGraphics.Add(item); } diff --git a/Assembly-CSharp/Verse/PawnHeadOverlays.cs b/Assembly-CSharp/Verse/PawnHeadOverlays.cs index fb2a7d9e4..16745a0de 100644 --- a/Assembly-CSharp/Verse/PawnHeadOverlays.cs +++ b/Assembly-CSharp/Verse/PawnHeadOverlays.cs @@ -1,4 +1,3 @@ -using System; using UnityEngine; namespace Verse @@ -23,23 +22,22 @@ public PawnHeadOverlays(Pawn pawn) public void RenderStatusOverlays(Vector3 bodyLoc, Quaternion quat, Mesh headMesh) { - if (!this.pawn.IsColonistPlayerControlled) + if (this.pawn.IsColonistPlayerControlled) { - return; - } - Vector3 headLoc = bodyLoc + new Vector3(0f, 0f, 0.32f); - if (this.pawn.needs.mood != null && !this.pawn.Downed && this.pawn.HitPoints > 0) - { - if (this.pawn.mindState.mentalBreaker.BreakExtremeIsImminent) + Vector3 headLoc = bodyLoc + new Vector3(0f, 0f, 0.32f); + if (this.pawn.needs.mood != null && !this.pawn.Downed && this.pawn.HitPoints > 0) { - if (Time.time % 1.2f < 0.4f) + if (this.pawn.mindState.mentalBreaker.BreakExtremeIsImminent) { - this.DrawHeadGlow(headLoc, PawnHeadOverlays.MentalStateImminentMat); + if (Time.time % 1.2000000476837158 < 0.40000000596046448) + { + this.DrawHeadGlow(headLoc, PawnHeadOverlays.MentalStateImminentMat); + } + } + else if (this.pawn.mindState.mentalBreaker.BreakExtremeIsApproaching && Time.time % 1.2000000476837158 < 0.40000000596046448) + { + this.DrawHeadGlow(headLoc, PawnHeadOverlays.UnhappyMat); } - } - else if (this.pawn.mindState.mentalBreaker.BreakExtremeIsApproaching && Time.time % 1.2f < 0.4f) - { - this.DrawHeadGlow(headLoc, PawnHeadOverlays.UnhappyMat); } } } diff --git a/Assembly-CSharp/Verse/PawnHealthState.cs b/Assembly-CSharp/Verse/PawnHealthState.cs index 57a229a1e..a12e33363 100644 --- a/Assembly-CSharp/Verse/PawnHealthState.cs +++ b/Assembly-CSharp/Verse/PawnHealthState.cs @@ -1,11 +1,9 @@ -using System; - namespace Verse { public enum PawnHealthState : byte { - Dead, - Down, - Mobile + Dead = 0, + Down = 1, + Mobile = 2 } } diff --git a/Assembly-CSharp/Verse/PawnInventoryOption.cs b/Assembly-CSharp/Verse/PawnInventoryOption.cs index e469e0929..27630f218 100644 --- a/Assembly-CSharp/Verse/PawnInventoryOption.cs +++ b/Assembly-CSharp/Verse/PawnInventoryOption.cs @@ -1,6 +1,5 @@ using System; using System.Collections.Generic; -using System.Diagnostics; namespace Verse { @@ -18,14 +17,44 @@ public class PawnInventoryOption public List subOptionsChooseOne; - [DebuggerHidden] public IEnumerable GenerateThings() { - PawnInventoryOption.c__Iterator1D4 c__Iterator1D = new PawnInventoryOption.c__Iterator1D4(); - c__Iterator1D.<>f__this = this; - PawnInventoryOption.c__Iterator1D4 expr_0E = c__Iterator1D; - expr_0E.$PC = -2; - return expr_0E; + if (!(Rand.Value < this.skipChance)) + { + if (this.thingDef != null && this.countRange.max > 0) + { + Thing thing = ThingMaker.MakeThing(this.thingDef, null); + thing.stackCount = this.countRange.RandomInRange; + yield return thing; + } + if (this.subOptionsTakeAll != null) + { + List.Enumerator enumerator = this.subOptionsTakeAll.GetEnumerator(); + try + { + while (enumerator.MoveNext()) + { + PawnInventoryOption opt = enumerator.Current; + foreach (Thing item in opt.GenerateThings()) + { + yield return item; + } + } + } + finally + { + ((IDisposable)(object)enumerator).Dispose(); + } + } + if (this.subOptionsChooseOne != null) + { + PawnInventoryOption chosen = this.subOptionsChooseOne.RandomElementByWeight((Func)((PawnInventoryOption o) => o.choiceChance)); + foreach (Thing item2 in chosen.GenerateThings()) + { + yield return item2; + } + } + } } } } diff --git a/Assembly-CSharp/Verse/PawnKindDef.cs b/Assembly-CSharp/Verse/PawnKindDef.cs index dd06a7a0a..80ddb7266 100644 --- a/Assembly-CSharp/Verse/PawnKindDef.cs +++ b/Assembly-CSharp/Verse/PawnKindDef.cs @@ -1,7 +1,8 @@ using RimWorld; using System; using System.Collections.Generic; -using System.Diagnostics; +using System.Linq; +using UnityEngine; namespace Verse { @@ -110,14 +111,46 @@ public override void ResolveReferences() } } - [DebuggerHidden] public override IEnumerable ConfigErrors() { - PawnKindDef.c__Iterator1D5 c__Iterator1D = new PawnKindDef.c__Iterator1D5(); - c__Iterator1D.<>f__this = this; - PawnKindDef.c__Iterator1D5 expr_0E = c__Iterator1D; - expr_0E.$PC = -2; - return expr_0E; + foreach (string item in base.ConfigErrors()) + { + yield return item; + } + if (this.race == null) + { + yield return "no race"; + } + else if (this.RaceProps.Humanlike && this.backstoryCategory.NullOrEmpty()) + { + yield return "Humanlike needs backstoryCategory."; + } + if (this.baseRecruitDifficulty > 1.0001000165939331) + { + yield return base.defName + " recruitDifficulty is greater than 1. 1 means impossible to recruit."; + } + if (this.combatPower < 0.0) + { + yield return base.defName + " has no pointsCost."; + } + if (this.weaponMoney.min > 0.0) + { + float minCost = 999999f; + for (int i = 0; i < this.weaponTags.Count; i++) + { + minCost = Mathf.Min(minCost, (from d in DefDatabase.AllDefs + where d.weaponTags != null && d.weaponTags.Contains(((_003CConfigErrors_003Ec__Iterator1D5)/*Error near IL_01e0: stateMachine*/)._003C_003Ef__this.weaponTags[((_003CConfigErrors_003Ec__Iterator1D5)/*Error near IL_01e0: stateMachine*/)._003Ci_003E__3]) + select d).Min((Func)((ThingDef d) => PawnWeaponGenerator.CheapestNonDerpPriceFor(d)))); + } + if (minCost > this.weaponMoney.min) + { + yield return "Cheapest weapon with one of my weaponTags costs " + minCost + " but weaponMoney min is " + this.weaponMoney.min + ", so could end up weaponless."; + } + } + if (!this.RaceProps.Humanlike && this.lifeStages.Count != this.RaceProps.lifeStageAges.Count) + { + yield return "PawnKindDef defines " + this.lifeStages.Count + " lifeStages while race def defines " + this.RaceProps.lifeStageAges.Count; + } } public static PawnKindDef Named(string defName) diff --git a/Assembly-CSharp/Verse/PawnKindLifeStage.cs b/Assembly-CSharp/Verse/PawnKindLifeStage.cs index c6524a784..f3dd6c83a 100644 --- a/Assembly-CSharp/Verse/PawnKindLifeStage.cs +++ b/Assembly-CSharp/Verse/PawnKindLifeStage.cs @@ -1,5 +1,3 @@ -using System; - namespace Verse { public class PawnKindLifeStage diff --git a/Assembly-CSharp/Verse/PawnLeaner.cs b/Assembly-CSharp/Verse/PawnLeaner.cs index a84610279..1c5300e16 100644 --- a/Assembly-CSharp/Verse/PawnLeaner.cs +++ b/Assembly-CSharp/Verse/PawnLeaner.cs @@ -1,4 +1,3 @@ -using System; using UnityEngine; namespace Verse @@ -33,7 +32,7 @@ public void LeanerTick() if (this.ShouldLean()) { this.leanOffsetCurPct += 0.075f; - if (this.leanOffsetCurPct > 1f) + if (this.leanOffsetCurPct > 1.0) { this.leanOffsetCurPct = 1f; } @@ -41,7 +40,7 @@ public void LeanerTick() else { this.leanOffsetCurPct -= 0.075f; - if (this.leanOffsetCurPct < 0f) + if (this.leanOffsetCurPct < 0.0) { this.leanOffsetCurPct = 0f; } @@ -51,7 +50,15 @@ public void LeanerTick() public bool ShouldLean() { Stance_Busy stance_Busy = this.pawn.stances.curStance as Stance_Busy; - return stance_Busy != null && !(this.shootSourceOffset == new IntVec3(0, 0, 0)); + if (stance_Busy != null) + { + if (this.shootSourceOffset == new IntVec3(0, 0, 0)) + { + return false; + } + return true; + } + return false; } public void Notify_WarmingCastAlongLine(ShootLine newShootLine, IntVec3 ShootPosition) diff --git a/Assembly-CSharp/Verse/PawnNameColorUtility.cs b/Assembly-CSharp/Verse/PawnNameColorUtility.cs index 64b401c03..8535c2bcc 100644 --- a/Assembly-CSharp/Verse/PawnNameColorUtility.cs +++ b/Assembly-CSharp/Verse/PawnNameColorUtility.cs @@ -1,5 +1,4 @@ using RimWorld; -using System; using System.Collections.Generic; using UnityEngine; @@ -57,7 +56,15 @@ static PawnNameColorUtility() private static Color RandomShiftOf(Color color, int i) { - return new Color(Mathf.Clamp01(color.r * PawnNameColorUtility.ColorShifts[i].r), Mathf.Clamp01(color.g * PawnNameColorUtility.ColorShifts[i].g), Mathf.Clamp01(color.b * PawnNameColorUtility.ColorShifts[i].b), color.a); + float r = color.r; + Color color2 = PawnNameColorUtility.ColorShifts[i]; + float r2 = Mathf.Clamp01(r * color2.r); + float g = color.g; + Color color3 = PawnNameColorUtility.ColorShifts[i]; + float g2 = Mathf.Clamp01(g * color3.g); + float b = color.b; + Color color4 = PawnNameColorUtility.ColorShifts[i]; + return new Color(r2, g2, Mathf.Clamp01(b * color4.b), color.a); } public static Color PawnNameColorOf(Pawn pawn) @@ -66,15 +73,7 @@ public static Color PawnNameColorOf(Pawn pawn) { return pawn.MentalStateDef.nameColor; } - int index; - if (pawn.Faction == null) - { - index = 0; - } - else - { - index = pawn.Faction.randomKey % 10; - } + int index = (pawn.Faction != null) ? (pawn.Faction.randomKey % 10) : 0; if (pawn.IsPrisoner) { return PawnNameColorUtility.ColorsPrisoner[index]; diff --git a/Assembly-CSharp/Verse/PawnRenderer.cs b/Assembly-CSharp/Verse/PawnRenderer.cs index 23a42eeec..a00aba21f 100644 --- a/Assembly-CSharp/Verse/PawnRenderer.cs +++ b/Assembly-CSharp/Verse/PawnRenderer.cs @@ -1,5 +1,4 @@ using RimWorld; -using System; using System.Collections.Generic; using UnityEngine; @@ -47,7 +46,7 @@ public class PawnRenderer private Graphic_Shadow shadowGraphic; - private static readonly float[] HorHeadOffsets = new float[] + private static readonly float[] HorHeadOffsets = new float[6] { 0f, 0.04f, @@ -103,14 +102,7 @@ public void RenderPawnAt(Vector3 drawLoc, RotDrawMode bodyDrawType, bool headStu bool flip = false; if (this.pawn.CurJob == null || !this.pawn.jobs.curDriver.ModifyCarriedThingDrawPos(ref vector, ref flag, ref flip)) { - if (carriedThing is Pawn || carriedThing is Corpse) - { - vector += new Vector3(0.44f, 0f, 0f); - } - else - { - vector += new Vector3(0.18f, 0f, 0.05f); - } + vector = ((!(carriedThing is Pawn) && !(carriedThing is Corpse)) ? (vector + new Vector3(0.18f, 0f, 0.05f)) : (vector + new Vector3(0.44f, 0f, 0f))); } if (flag) { @@ -149,13 +141,14 @@ public void RenderPawnAt(Vector3 drawLoc, RotDrawMode bodyDrawType, bool headStu Rot4 rotation = building_Bed.Rotation; rotation.AsInt += 2; quat = rotation.AsQuat; - AltitudeLayer altLayer = (AltitudeLayer)Mathf.Max((int)building_Bed.def.altitudeLayer, 15); - Vector3 vector2 = this.pawn.Position.ToVector3ShiftedWithAltitude(altLayer); - Vector3 vector3 = vector2; - vector3.y += 0.0281250011f; - float d = -this.BaseHeadOffsetAt(Rot4.South).z; - Vector3 a = rotation.FacingCell.ToVector3(); - rootLoc = vector2 + a * d; + AltitudeLayer altLayer = (AltitudeLayer)(byte)Mathf.Max((int)building_Bed.def.altitudeLayer, 15); + Vector3 vector2; + Vector3 a = vector2 = this.pawn.Position.ToVector3ShiftedWithAltitude(altLayer); + vector2.y += 0.0281250011f; + Vector3 vector3 = this.BaseHeadOffsetAt(Rot4.South); + float d = (float)(0.0 - vector3.z); + Vector3 a2 = rotation.FacingCell.ToVector3(); + rootLoc = a + a2 * d; rootLoc.y += 0.0046875f; } else @@ -164,7 +157,7 @@ public void RenderPawnAt(Vector3 drawLoc, RotDrawMode bodyDrawType, bool headStu rootLoc = drawLoc; if (!this.pawn.Dead && this.pawn.CarriedBy == null) { - rootLoc.y = Altitudes.AltitudeFor(AltitudeLayer.LayingPawn) + 0.0046875f; + rootLoc.y = (float)(Altitudes.AltitudeFor(AltitudeLayer.LayingPawn) + 0.0046875001862645149); } if (this.pawn.Downed || this.pawn.Dead) { @@ -177,17 +170,18 @@ public void RenderPawnAt(Vector3 drawLoc, RotDrawMode bodyDrawType, bool headStu else { Rot4 rot2 = Rot4.West; - int num = this.pawn.thingIDNumber % 2; - if (num != 0) + switch (this.pawn.thingIDNumber % 2) { - if (num == 1) - { - rot2 = Rot4.East; - } - } - else + case 0: { rot2 = Rot4.West; + break; + } + case 1: + { + rot2 = Rot4.East; + break; + } } quat = rot2.AsQuat; } @@ -241,14 +235,7 @@ private void RenderPawnInternal(Vector3 rootLoc, Quaternion quat, bool renderBod } else { - if (this.pawn.RaceProps.Humanlike) - { - mesh = MeshPool.humanlikeBodySet.MeshAt(bodyFacing); - } - else - { - mesh = this.graphics.nakedGraphic.MeshAt(bodyFacing); - } + mesh = ((!this.pawn.RaceProps.Humanlike) ? this.graphics.nakedGraphic.MeshAt(bodyFacing) : MeshPool.humanlikeBodySet.MeshAt(bodyFacing)); List list = this.graphics.MatsBodyBaseAt(bodyFacing, bodyDrawType); for (int i = 0; i < list.Count; i++) { @@ -280,7 +267,7 @@ private void RenderPawnInternal(Vector3 rootLoc, Quaternion quat, bool renderBod { Vector3 b = quat * this.BaseHeadOffsetAt(headFacing); Material material = this.graphics.HeadMatAt(headFacing, bodyDrawType, headStump); - if (material != null) + if ((Object)material != (Object)null) { Mesh mesh2 = MeshPool.humanlikeHeadSet.MeshAt(headFacing); GenDraw.DrawMeshNowOrLater(mesh2, a + b, quat, material, portrait); @@ -294,12 +281,14 @@ private void RenderPawnInternal(Vector3 rootLoc, Quaternion quat, bool renderBod List apparelGraphics = this.graphics.apparelGraphics; for (int j = 0; j < apparelGraphics.Count; j++) { - if (apparelGraphics[j].sourceApparel.def.apparel.LastLayer == ApparelLayer.Overhead) + ApparelGraphicRecord apparelGraphicRecord = apparelGraphics[j]; + if (apparelGraphicRecord.sourceApparel.def.apparel.LastLayer == ApparelLayer.Overhead) { flag = true; - Material material2 = apparelGraphics[j].graphic.MatAt(bodyFacing, null); - material2 = this.graphics.flasher.GetDamagedMat(material2); - GenDraw.DrawMeshNowOrLater(mesh3, loc2, quat, material2, portrait); + ApparelGraphicRecord apparelGraphicRecord2 = apparelGraphics[j]; + Material baseMat = apparelGraphicRecord2.graphic.MatAt(bodyFacing, null); + baseMat = this.graphics.flasher.GetDamagedMat(baseMat); + GenDraw.DrawMeshNowOrLater(mesh3, loc2, quat, baseMat, portrait); } } } @@ -314,12 +303,12 @@ private void RenderPawnInternal(Vector3 rootLoc, Quaternion quat, bool renderBod { for (int k = 0; k < this.graphics.apparelGraphics.Count; k++) { - ApparelGraphicRecord apparelGraphicRecord = this.graphics.apparelGraphics[k]; - if (apparelGraphicRecord.sourceApparel.def.apparel.LastLayer == ApparelLayer.Shell) + ApparelGraphicRecord apparelGraphicRecord3 = this.graphics.apparelGraphics[k]; + if (apparelGraphicRecord3.sourceApparel.def.apparel.LastLayer == ApparelLayer.Shell) { - Material material3 = apparelGraphicRecord.graphic.MatAt(bodyFacing, null); - material3 = this.graphics.flasher.GetDamagedMat(material3); - GenDraw.DrawMeshNowOrLater(mesh, vector, quat, material3, portrait); + Material baseMat2 = apparelGraphicRecord3.graphic.MatAt(bodyFacing, null); + baseMat2 = this.graphics.flasher.GetDamagedMat(baseMat2); + GenDraw.DrawMeshNowOrLater(mesh, vector, quat, baseMat2, portrait); } } } @@ -346,81 +335,64 @@ private void RenderPawnInternal(Vector3 rootLoc, Quaternion quat, bool renderBod private void DrawEquipment(Vector3 rootLoc) { - if (this.pawn.Dead || !this.pawn.Spawned) - { - return; - } - if (this.pawn.equipment == null || this.pawn.equipment.Primary == null) - { - return; - } - if (this.pawn.CurJob != null && this.pawn.CurJob.def.neverShowWeapon) - { - return; - } - Stance_Busy stance_Busy = this.pawn.stances.curStance as Stance_Busy; - if (stance_Busy != null && !stance_Busy.neverAimWeapon && stance_Busy.focusTarg.IsValid) - { - Vector3 a; - if (stance_Busy.focusTarg.HasThing) - { - a = stance_Busy.focusTarg.Thing.DrawPos; - } - else - { - a = stance_Busy.focusTarg.Cell.ToVector3Shifted(); - } - float num = 0f; - if ((a - this.pawn.DrawPos).MagnitudeHorizontalSquared() > 0.001f) - { - num = (a - this.pawn.DrawPos).AngleFlat(); - } - Vector3 drawLoc = rootLoc + new Vector3(0f, 0f, 0.4f).RotatedBy(num); - drawLoc.y += 0.0375f; - this.DrawEquipmentAiming(this.pawn.equipment.Primary, drawLoc, num); - } - else if (this.CarryWeaponOpenly()) + if (!this.pawn.Dead && this.pawn.Spawned && this.pawn.equipment != null && this.pawn.equipment.Primary != null && (this.pawn.CurJob == null || !this.pawn.CurJob.def.neverShowWeapon)) { - if (this.pawn.Rotation == Rot4.South) + Stance_Busy stance_Busy = this.pawn.stances.curStance as Stance_Busy; + if (stance_Busy != null && !stance_Busy.neverAimWeapon && stance_Busy.focusTarg.IsValid) { - Vector3 drawLoc2 = rootLoc + new Vector3(0f, 0f, -0.22f); - drawLoc2.y += 0.0375f; - this.DrawEquipmentAiming(this.pawn.equipment.Primary, drawLoc2, 143f); - } - else if (this.pawn.Rotation == Rot4.North) - { - Vector3 drawLoc3 = rootLoc + new Vector3(0f, 0f, -0.11f); - drawLoc3.y = drawLoc3.y; - this.DrawEquipmentAiming(this.pawn.equipment.Primary, drawLoc3, 143f); - } - else if (this.pawn.Rotation == Rot4.East) - { - Vector3 drawLoc4 = rootLoc + new Vector3(0.2f, 0f, -0.22f); - drawLoc4.y += 0.0375f; - this.DrawEquipmentAiming(this.pawn.equipment.Primary, drawLoc4, 143f); + Vector3 a = (!stance_Busy.focusTarg.HasThing) ? stance_Busy.focusTarg.Cell.ToVector3Shifted() : stance_Busy.focusTarg.Thing.DrawPos; + float num = 0f; + if ((a - this.pawn.DrawPos).MagnitudeHorizontalSquared() > 0.0010000000474974513) + { + num = (a - this.pawn.DrawPos).AngleFlat(); + } + Vector3 drawLoc = rootLoc + new Vector3(0f, 0f, 0.4f).RotatedBy(num); + drawLoc.y += 0.0375f; + this.DrawEquipmentAiming(this.pawn.equipment.Primary, drawLoc, num); } - else if (this.pawn.Rotation == Rot4.West) + else if (this.CarryWeaponOpenly()) { - Vector3 drawLoc5 = rootLoc + new Vector3(-0.2f, 0f, -0.22f); - drawLoc5.y += 0.0375f; - this.DrawEquipmentAiming(this.pawn.equipment.Primary, drawLoc5, 217f); + if (this.pawn.Rotation == Rot4.South) + { + Vector3 drawLoc2 = rootLoc + new Vector3(0f, 0f, -0.22f); + drawLoc2.y += 0.0375f; + this.DrawEquipmentAiming(this.pawn.equipment.Primary, drawLoc2, 143f); + } + else if (this.pawn.Rotation == Rot4.North) + { + Vector3 drawLoc3 = rootLoc + new Vector3(0f, 0f, -0.11f); + drawLoc3.y = drawLoc3.y; + this.DrawEquipmentAiming(this.pawn.equipment.Primary, drawLoc3, 143f); + } + else if (this.pawn.Rotation == Rot4.East) + { + Vector3 drawLoc4 = rootLoc + new Vector3(0.2f, 0f, -0.22f); + drawLoc4.y += 0.0375f; + this.DrawEquipmentAiming(this.pawn.equipment.Primary, drawLoc4, 143f); + } + else if (this.pawn.Rotation == Rot4.West) + { + Vector3 drawLoc5 = rootLoc + new Vector3(-0.2f, 0f, -0.22f); + drawLoc5.y += 0.0375f; + this.DrawEquipmentAiming(this.pawn.equipment.Primary, drawLoc5, 217f); + } } } } public void DrawEquipmentAiming(Thing eq, Vector3 drawLoc, float aimAngle) { - float num = aimAngle - 90f; - Mesh mesh; - if (aimAngle > 20f && aimAngle < 160f) + Mesh mesh = null; + float num = (float)(aimAngle - 90.0); + if (aimAngle > 20.0 && aimAngle < 160.0) { mesh = MeshPool.plane10; num += eq.def.equippedAngleOffset; } - else if (aimAngle > 200f && aimAngle < 340f) + else if (aimAngle > 200.0 && aimAngle < 340.0) { mesh = MeshPool.plane10Flip; - num -= 180f; + num = (float)(num - 180.0); num -= eq.def.equippedAngleOffset; } else @@ -428,23 +400,32 @@ public void DrawEquipmentAiming(Thing eq, Vector3 drawLoc, float aimAngle) mesh = MeshPool.plane10; num += eq.def.equippedAngleOffset; } - num %= 360f; + num = (float)(num % 360.0); + Material material = null; Graphic_StackCount graphic_StackCount = eq.Graphic as Graphic_StackCount; - Material matSingle; - if (graphic_StackCount != null) - { - matSingle = graphic_StackCount.SubGraphicForStackCount(1, eq.def).MatSingle; - } - else - { - matSingle = eq.Graphic.MatSingle; - } - Graphics.DrawMesh(mesh, drawLoc, Quaternion.AngleAxis(num, Vector3.up), matSingle, 0); + material = ((graphic_StackCount == null) ? eq.Graphic.MatSingle : graphic_StackCount.SubGraphicForStackCount(1, eq.def).MatSingle); + Graphics.DrawMesh(mesh, drawLoc, Quaternion.AngleAxis(num, Vector3.up), material, 0); } private bool CarryWeaponOpenly() { - return (this.pawn.carryTracker == null || this.pawn.carryTracker.CarriedThing == null) && (this.pawn.Drafted || (this.pawn.CurJob != null && this.pawn.CurJob.def.alwaysShowWeapon) || (this.pawn.mindState.duty != null && this.pawn.mindState.duty.def.alwaysShowWeapon)); + if (this.pawn.carryTracker != null && this.pawn.carryTracker.CarriedThing != null) + { + return false; + } + if (this.pawn.Drafted) + { + return true; + } + if (this.pawn.CurJob != null && this.pawn.CurJob.def.alwaysShowWeapon) + { + return true; + } + if (this.pawn.mindState.duty != null && this.pawn.mindState.duty.def.alwaysShowWeapon) + { + return true; + } + return false; } private Rot4 LayingFacing() @@ -458,49 +439,75 @@ private Rot4 LayingFacing() switch (this.pawn.thingIDNumber % 4) { case 0: + { return Rot4.South; + } case 1: + { return Rot4.South; + } case 2: + { return Rot4.East; + } case 3: + { return Rot4.West; } + } } else { switch (this.pawn.thingIDNumber % 4) { case 0: + { return Rot4.South; + } case 1: + { return Rot4.East; + } case 2: + { return Rot4.West; + } case 3: + { return Rot4.West; } + } } return Rot4.Random; } public Vector3 BaseHeadOffsetAt(Rot4 rotation) { - float num = PawnRenderer.HorHeadOffsets[(int)this.pawn.story.bodyType]; + float num = PawnRenderer.HorHeadOffsets[(uint)this.pawn.story.bodyType]; switch (rotation.AsInt) { case 0: + { return new Vector3(0f, 0f, 0.34f); + } case 1: + { return new Vector3(num, 0f, 0.34f); + } case 2: + { return new Vector3(0f, 0f, 0.34f); + } case 3: - return new Vector3(-num, 0f, 0.34f); + { + return new Vector3((float)(0.0 - num), 0f, 0.34f); + } default: + { Log.Error("BaseHeadOffsetAt error in " + this.pawn); return Vector3.zero; } + } } public void Notify_DamageApplied(DamageInfo dam) diff --git a/Assembly-CSharp/Verse/PawnRotator.cs b/Assembly-CSharp/Verse/PawnRotator.cs index 4fec3ecd2..32a6e2a44 100644 --- a/Assembly-CSharp/Verse/PawnRotator.cs +++ b/Assembly-CSharp/Verse/PawnRotator.cs @@ -1,4 +1,3 @@ -using System; using UnityEngine; namespace Verse @@ -14,111 +13,104 @@ public PawnRotator(Pawn pawn) public void PawnRotatorTick() { - if (this.pawn.Destroyed) + if (!this.pawn.Destroyed && !this.pawn.jobs.HandlingFacing) { - return; - } - if (this.pawn.jobs.HandlingFacing) - { - return; - } - if (this.pawn.pather.Moving) - { - if (this.pawn.pather.curPath == null || this.pawn.pather.curPath.NodesLeftCount < 1) + if (this.pawn.pather.Moving) { - return; + if (this.pawn.pather.curPath != null && this.pawn.pather.curPath.NodesLeftCount >= 1) + { + this.FaceAdjacentCell(this.pawn.pather.nextCell); + } } - this.FaceAdjacentCell(this.pawn.pather.nextCell); - return; - } - else - { - Stance_Busy stance_Busy = this.pawn.stances.curStance as Stance_Busy; - if (stance_Busy != null && stance_Busy.focusTarg.IsValid) + else { - if (stance_Busy.focusTarg.HasThing) + Stance_Busy stance_Busy = this.pawn.stances.curStance as Stance_Busy; + if (stance_Busy != null && stance_Busy.focusTarg.IsValid) { - this.Face(stance_Busy.focusTarg.Thing.DrawPos); + if (stance_Busy.focusTarg.HasThing) + { + this.Face(stance_Busy.focusTarg.Thing.DrawPos); + } + else + { + this.FaceCell(stance_Busy.focusTarg.Cell); + } } else { - this.FaceCell(stance_Busy.focusTarg.Cell); - } - return; - } - if (this.pawn.jobs.curJob != null) - { - LocalTargetInfo target = this.pawn.CurJob.GetTarget(this.pawn.jobs.curDriver.rotateToFace); - if (target.HasThing) - { - bool flag = false; - IntVec3 c = default(IntVec3); - CellRect cellRect = target.Thing.OccupiedRect(); - for (int i = cellRect.minZ; i <= cellRect.maxZ; i++) + if (this.pawn.jobs.curJob != null) { - for (int j = cellRect.minX; j <= cellRect.maxX; j++) + LocalTargetInfo target = this.pawn.CurJob.GetTarget(this.pawn.jobs.curDriver.rotateToFace); + if (target.HasThing) { - if (this.pawn.Position == new IntVec3(j, 0, i)) + bool flag = false; + IntVec3 c = default(IntVec3); + CellRect cellRect = target.Thing.OccupiedRect(); + for (int i = cellRect.minZ; i <= cellRect.maxZ; i++) { - this.Face(target.Thing.DrawPos); - return; + for (int j = cellRect.minX; j <= cellRect.maxX; j++) + { + if (this.pawn.Position == new IntVec3(j, 0, i)) + { + this.Face(target.Thing.DrawPos); + return; + } + } } - } - } - for (int k = cellRect.minZ; k <= cellRect.maxZ; k++) - { - for (int l = cellRect.minX; l <= cellRect.maxX; l++) - { - IntVec3 intVec = new IntVec3(l, 0, k); - if (intVec.AdjacentToCardinal(this.pawn.Position)) + for (int k = cellRect.minZ; k <= cellRect.maxZ; k++) { - this.FaceAdjacentCell(intVec); - return; + for (int l = cellRect.minX; l <= cellRect.maxX; l++) + { + IntVec3 intVec = new IntVec3(l, 0, k); + if (intVec.AdjacentToCardinal(this.pawn.Position)) + { + this.FaceAdjacentCell(intVec); + return; + } + if (intVec.AdjacentTo8Way(this.pawn.Position)) + { + flag = true; + c = intVec; + } + } } - if (intVec.AdjacentTo8Way(this.pawn.Position)) + if (flag) { - flag = true; - c = intVec; + if (DebugViewSettings.drawPawnRotatorTarget) + { + this.pawn.Map.debugDrawer.FlashCell(this.pawn.Position, 0.6f, "jbthing"); + GenDraw.DrawLineBetween(this.pawn.Position.ToVector3Shifted(), c.ToVector3Shifted()); + } + this.FaceAdjacentCell(c); } + else + { + this.Face(target.Thing.DrawPos); + } + return; } - } - if (flag) - { - if (DebugViewSettings.drawPawnRotatorTarget) + if (this.pawn.Position.AdjacentTo8Way(target.Cell)) { - this.pawn.Map.debugDrawer.FlashCell(this.pawn.Position, 0.6f, "jbthing"); - GenDraw.DrawLineBetween(this.pawn.Position.ToVector3Shifted(), c.ToVector3Shifted()); + if (DebugViewSettings.drawPawnRotatorTarget) + { + this.pawn.Map.debugDrawer.FlashCell(this.pawn.Position, 0.2f, "jbloc"); + GenDraw.DrawLineBetween(this.pawn.Position.ToVector3Shifted(), target.Cell.ToVector3Shifted()); + } + this.FaceAdjacentCell(target.Cell); + return; } - this.FaceAdjacentCell(c); - return; - } - this.Face(target.Thing.DrawPos); - return; - } - else - { - if (this.pawn.Position.AdjacentTo8Way(target.Cell)) - { - if (DebugViewSettings.drawPawnRotatorTarget) + if (target.Cell.IsValid && target.Cell != this.pawn.Position) { - this.pawn.Map.debugDrawer.FlashCell(this.pawn.Position, 0.2f, "jbloc"); - GenDraw.DrawLineBetween(this.pawn.Position.ToVector3Shifted(), target.Cell.ToVector3Shifted()); + this.Face(target.Cell.ToVector3()); + return; } - this.FaceAdjacentCell(target.Cell); - return; } - if (target.Cell.IsValid && target.Cell != this.pawn.Position) + if (this.pawn.Drafted) { - this.Face(target.Cell.ToVector3()); - return; + this.pawn.Rotation = Rot4.South; } } } - if (this.pawn.Drafted) - { - this.pawn.Rotation = Rot4.South; - } - return; } } @@ -157,19 +149,19 @@ public void Face(Vector3 p) public static Rot4 RotFromAngleBiased(float angle) { - if (angle < 30f) + if (angle < 30.0) { return Rot4.North; } - if (angle < 150f) + if (angle < 150.0) { return Rot4.East; } - if (angle < 210f) + if (angle < 210.0) { return Rot4.South; } - if (angle < 330f) + if (angle < 330.0) { return Rot4.West; } diff --git a/Assembly-CSharp/Verse/PawnStatusEffecters.cs b/Assembly-CSharp/Verse/PawnStatusEffecters.cs index 8eb92395c..49f79c521 100644 --- a/Assembly-CSharp/Verse/PawnStatusEffecters.cs +++ b/Assembly-CSharp/Verse/PawnStatusEffecters.cs @@ -1,4 +1,3 @@ -using System; using System.Collections.Generic; namespace Verse @@ -27,7 +26,7 @@ public void Cleanup() { this.effecter.Cleanup(); } - FullPool.Return(this); + FullPool.Return(this); } public void Reset() @@ -48,18 +47,18 @@ public void Tick(Pawn pawn) { this.effecter = this.def.Spawn(); } - this.effecter.EffectTick(pawn, null); + this.effecter.EffectTick((Thing)pawn, (Thing)null); } } public Pawn pawn; - private List pairs; + private List pairs; public PawnStatusEffecters(Pawn pawn) { this.pawn = pawn; - this.pairs = new List(); + this.pairs = new List(); } public void EffectersTick() @@ -85,16 +84,16 @@ public void EffectersTick() this.AddOrMaintain(effecterDef2); } } - for (int j = this.pairs.Count - 1; j >= 0; j--) + for (int num = this.pairs.Count - 1; num >= 0; num--) { - if (this.pairs[j].Expired) + if (this.pairs[num].Expired) { - this.pairs[j].Cleanup(); - this.pairs.RemoveAt(j); + this.pairs[num].Cleanup(); + this.pairs.RemoveAt(num); } else { - this.pairs[j].Tick(this.pawn); + this.pairs[num].Tick(this.pawn); } } } @@ -109,7 +108,7 @@ private void AddOrMaintain(EffecterDef def) return; } } - PawnStatusEffecters.LiveEffecter liveEffecter = FullPool.Get(); + LiveEffecter liveEffecter = FullPool.Get(); liveEffecter.def = def; liveEffecter.Maintain(); this.pairs.Add(liveEffecter); diff --git a/Assembly-CSharp/Verse/PawnTweener.cs b/Assembly-CSharp/Verse/PawnTweener.cs index 8afb6e1a6..e4dd260f8 100644 --- a/Assembly-CSharp/Verse/PawnTweener.cs +++ b/Assembly-CSharp/Verse/PawnTweener.cs @@ -1,4 +1,3 @@ -using System; using UnityEngine; namespace Verse @@ -38,29 +37,28 @@ public PawnTweener(Pawn pawn) public void PreDrawPosCalculation() { - if (this.lastDrawFrame == RealTime.frameCount) + if (this.lastDrawFrame != RealTime.frameCount) { - return; - } - if (this.lastDrawFrame < RealTime.frameCount - 1) - { - this.ResetTweenedPosToRoot(); - } - else - { - this.lastTickSpringPos = this.tweenedPos; - float tickRateMultiplier = Find.TickManager.TickRateMultiplier; - if (tickRateMultiplier < 5f) + if (this.lastDrawFrame < RealTime.frameCount - 1) { - Vector3 a = this.TweenedPosRoot() - this.tweenedPos; - this.tweenedPos += a * 0.09f * (RealTime.deltaTime * 60f * tickRateMultiplier); + this.ResetTweenedPosToRoot(); } else { - this.tweenedPos = this.TweenedPosRoot(); + this.lastTickSpringPos = this.tweenedPos; + float tickRateMultiplier = Find.TickManager.TickRateMultiplier; + if (tickRateMultiplier < 5.0) + { + Vector3 a = this.TweenedPosRoot() - this.tweenedPos; + this.tweenedPos += a * 0.09f * (float)(RealTime.deltaTime * 60.0 * tickRateMultiplier); + } + else + { + this.tweenedPos = this.TweenedPosRoot(); + } } + this.lastDrawFrame = RealTime.frameCount; } - this.lastDrawFrame = RealTime.frameCount; } public void ResetTweenedPosToRoot() @@ -76,7 +74,7 @@ private Vector3 TweenedPosRoot() return this.pawn.Position.ToVector3Shifted(); } float num = this.MovedPercent(); - return this.pawn.pather.nextCell.ToVector3Shifted() * num + this.pawn.Position.ToVector3Shifted() * (1f - num) + PawnCollisionTweenerUtility.PawnCollisionPosOffsetFor(this.pawn); + return this.pawn.pather.nextCell.ToVector3Shifted() * num + this.pawn.Position.ToVector3Shifted() * (float)(1.0 - num) + PawnCollisionTweenerUtility.PawnCollisionPosOffsetFor(this.pawn); } private float MovedPercent() @@ -101,7 +99,7 @@ private float MovedPercent() { return 0f; } - return 1f - this.pawn.pather.nextCellCostLeft / this.pawn.pather.nextCellCostTotal; + return (float)(1.0 - this.pawn.pather.nextCellCostLeft / this.pawn.pather.nextCellCostTotal); } } } diff --git a/Assembly-CSharp/Verse/PawnUIOverlay.cs b/Assembly-CSharp/Verse/PawnUIOverlay.cs index 06e8fcf2f..1197a27f1 100644 --- a/Assembly-CSharp/Verse/PawnUIOverlay.cs +++ b/Assembly-CSharp/Verse/PawnUIOverlay.cs @@ -1,5 +1,4 @@ using RimWorld; -using System; using UnityEngine; namespace Verse @@ -23,35 +22,36 @@ public PawnUIOverlay(Pawn pawn) public void DrawPawnGUIOverlay() { - if (!this.pawn.Spawned || this.pawn.Map.fogGrid.IsFogged(this.pawn.Position)) + if (this.pawn.Spawned && !this.pawn.Map.fogGrid.IsFogged(this.pawn.Position)) { - return; - } - if (!this.pawn.RaceProps.Humanlike) - { - switch (Prefs.AnimalNameMode) + if (!this.pawn.RaceProps.Humanlike) { - case AnimalNameDisplayMode.None: - return; - case AnimalNameDisplayMode.TameNamed: - if (this.pawn.Name == null || this.pawn.Name.Numerical) + switch (Prefs.AnimalNameMode) { + case AnimalNameDisplayMode.None: return; + case AnimalNameDisplayMode.TameAll: + { + if (this.pawn.Name == null) + return; + break; } - break; - case AnimalNameDisplayMode.TameAll: - if (this.pawn.Name == null) + case AnimalNameDisplayMode.TameNamed: { - return; + if (this.pawn.Name == null) + return; + if (this.pawn.Name.Numerical) + return; + break; + } } - break; } - } - Vector2 pos = GenMapUI.LabelDrawPosFor(this.pawn, -0.6f); - GenMapUI.DrawPawnLabel(this.pawn, pos, 1f, 9999f, null, GameFont.Tiny, true, true); - if (this.pawn.CanTradeNow) - { - this.pawn.Map.overlayDrawer.DrawOverlay(this.pawn, OverlayTypes.QuestionMark); + Vector2 pos = GenMapUI.LabelDrawPosFor(this.pawn, -0.6f); + GenMapUI.DrawPawnLabel(this.pawn, pos, 1f, 9999f, null, GameFont.Tiny, true, true); + if (this.pawn.CanTradeNow) + { + this.pawn.Map.overlayDrawer.DrawOverlay(this.pawn, OverlayTypes.QuestionMark); + } } } } diff --git a/Assembly-CSharp/Verse/Pawn_AgeTracker.cs b/Assembly-CSharp/Verse/Pawn_AgeTracker.cs index 8cfe206e3..8541b73a5 100644 --- a/Assembly-CSharp/Verse/Pawn_AgeTracker.cs +++ b/Assembly-CSharp/Verse/Pawn_AgeTracker.cs @@ -36,7 +36,7 @@ public int AgeBiologicalYears { get { - return (int)(this.ageBiologicalTicksInt / 3600000L); + return (int)(this.ageBiologicalTicksInt / 3600000); } } @@ -44,7 +44,7 @@ public float AgeBiologicalYearsFloat { get { - return (float)this.ageBiologicalTicksInt / 3600000f; + return (float)((float)this.ageBiologicalTicksInt / 3600000.0); } } @@ -65,11 +65,11 @@ public long AgeChronologicalTicks { get { - return (long)GenTicks.TicksAbs - this.birthAbsTicksInt; + return GenTicks.TicksAbs - this.birthAbsTicksInt; } set { - this.BirthAbsTicks = (long)GenTicks.TicksAbs - value; + this.BirthAbsTicks = GenTicks.TicksAbs - value; } } @@ -77,7 +77,7 @@ public int AgeChronologicalYears { get { - return (int)(this.AgeChronologicalTicks / 3600000L); + return (int)(this.AgeChronologicalTicks / 3600000); } } @@ -85,7 +85,7 @@ public float AgeChronologicalYearsFloat { get { - return (float)this.AgeChronologicalTicks / 3600000f; + return (float)((float)this.AgeChronologicalTicks / 3600000.0); } } @@ -129,13 +129,7 @@ public string AgeNumberString if (this.AgeChronologicalYears != this.AgeBiologicalYears) { string text2 = text; - text = string.Concat(new object[] - { - text2, - " (", - this.AgeChronologicalYears, - ")" - }); + text = text2 + " (" + this.AgeChronologicalYears + ")"; } return text; } @@ -145,43 +139,18 @@ public string AgeTooltipString { get { - int num; - int num2; - int num3; - float num4; + int num = default(int); + int num2 = default(int); + int num3 = default(int); + float num4 = default(float); this.ageBiologicalTicksInt.TicksToPeriod(out num, out num2, out num3, out num4); - long numTicks = (long)GenTicks.TicksAbs - this.birthAbsTicksInt; - int num5; - int num6; - int num7; + long numTicks = GenTicks.TicksAbs - this.birthAbsTicksInt; + int num5 = default(int); + int num6 = default(int); + int num7 = default(int); numTicks.TicksToPeriod(out num5, out num6, out num7, out num4); - string text = "FullDate".Translate(new object[] - { - Find.ActiveLanguageWorker.OrdinalNumber(this.BirthDayOfSeasonZeroBased + 1), - this.BirthQuadrum.Label(), - this.BirthYear - }); - string text2 = string.Concat(new string[] - { - "Born".Translate(new object[] - { - text - }), - "\n", - "AgeChronological".Translate(new object[] - { - num5, - num6, - num7 - }), - "\n", - "AgeBiological".Translate(new object[] - { - num, - num2, - num3 - }) - }); + string text = "FullDate".Translate(Find.ActiveLanguageWorker.OrdinalNumber(this.BirthDayOfSeasonZeroBased + 1), this.BirthQuadrum.Label(), this.BirthYear); + string text2 = "Born".Translate(text) + "\n" + "AgeChronological".Translate(num5, num6, num7) + "\n" + "AgeBiological".Translate(num, num2, num3); if (Prefs.DevMode) { text2 += "\n\nDev mode info:"; @@ -262,7 +231,7 @@ public void AgeTick() { this.BirthdayChronological(); } - if (this.ageBiologicalTicksInt % 3600000L < 60000L) + if (this.ageBiologicalTicksInt % 3600000 < 60000) { this.BirthdayBiological(); } @@ -273,13 +242,16 @@ private void RecalculateLifeStageIndex() { int num = -1; List lifeStageAges = this.pawn.RaceProps.lifeStageAges; - for (int i = lifeStageAges.Count - 1; i >= 0; i--) + int num2 = lifeStageAges.Count - 1; + while (num2 >= 0) { - if (lifeStageAges[i].minAge <= this.AgeBiologicalYearsFloat + 1E-06f) + if (!(lifeStageAges[num2].minAge <= this.AgeBiologicalYearsFloat + 9.9999999747524271E-07)) { - num = i; - break; + num2--; + continue; } + num = num2; + break; } if (num == -1) { @@ -289,7 +261,7 @@ private void RecalculateLifeStageIndex() this.cachedLifeStageIndex = num; if (flag && !this.pawn.RaceProps.Humanlike) { - LongEventHandler.ExecuteWhenFinished(delegate + LongEventHandler.ExecuteWhenFinished((Action)delegate { this.pawn.Drawer.renderer.graphics.ResolveAllGraphics(); }); @@ -297,35 +269,30 @@ private void RecalculateLifeStageIndex() } if (this.cachedLifeStageIndex < lifeStageAges.Count - 1) { - float num2 = lifeStageAges[this.cachedLifeStageIndex + 1].minAge - this.AgeBiologicalYearsFloat; - int num3 = (Current.ProgramState != ProgramState.Playing) ? 0 : Find.TickManager.TicksGame; - this.nextLifeStageChangeTick = num3 + Mathf.CeilToInt(num2 * 3600000f); + float num3 = lifeStageAges[this.cachedLifeStageIndex + 1].minAge - this.AgeBiologicalYearsFloat; + int num4 = (Current.ProgramState == ProgramState.Playing) ? Find.TickManager.TicksGame : 0; + this.nextLifeStageChangeTick = num4 + Mathf.CeilToInt((float)(num3 * 3600000.0)); } } private void BirthdayBiological() { StringBuilder stringBuilder = new StringBuilder(); - foreach (HediffGiver_Birthday current in AgeInjuryUtility.RandomHediffsToGainOnBirthday(this.pawn, this.AgeBiologicalYears)) + foreach (HediffGiver_Birthday item in AgeInjuryUtility.RandomHediffsToGainOnBirthday(this.pawn, this.AgeBiologicalYears)) { - if (current.TryApply(this.pawn, null)) + if (item.TryApply(this.pawn, null)) { if (stringBuilder.Length != 0) { stringBuilder.AppendLine(); } - stringBuilder.Append(" - " + current.hediff.LabelCap); + stringBuilder.Append(" - " + item.hediff.LabelCap); } } if (this.pawn.RaceProps.Humanlike && PawnUtility.ShouldSendNotificationAbout(this.pawn) && stringBuilder.Length > 0) { - string text = "BirthdayBiologicalAgeInjuries".Translate(new object[] - { - this.pawn, - this.AgeBiologicalYears, - stringBuilder - }).AdjustedFor(this.pawn); - Find.LetterStack.ReceiveLetter("LetterLabelBirthday".Translate(), text, LetterDefOf.BadNonUrgent, this.pawn, null); + string text = "BirthdayBiologicalAgeInjuries".Translate(this.pawn, this.AgeBiologicalYears, stringBuilder).AdjustedFor(this.pawn); + Find.LetterStack.ReceiveLetter("LetterLabelBirthday".Translate(), text, LetterDefOf.BadNonUrgent, (Thing)this.pawn, (string)null); } } @@ -341,23 +308,23 @@ public void DebugForceBirthdayBiological() private void CheckChangePawnKindName() { NameSingle nameSingle = this.pawn.Name as NameSingle; - if (nameSingle == null || !nameSingle.Numerical) + if (nameSingle != null && nameSingle.Numerical) { - return; - } - string kindLabel = this.pawn.KindLabel; - if (nameSingle.NameWithoutNumber == kindLabel) - { - return; - } - int number = nameSingle.Number; - string text = this.pawn.KindLabel + " " + number; - if (!NameUseChecker.NameSingleIsUsed(text)) - { - this.pawn.Name = new NameSingle(text, true); - return; + string kindLabel = this.pawn.KindLabel; + if (!(nameSingle.NameWithoutNumber == kindLabel)) + { + int number = nameSingle.Number; + string text = this.pawn.KindLabel + " " + number; + if (!NameUseChecker.NameSingleIsUsed(text)) + { + this.pawn.Name = new NameSingle(text, true); + } + else + { + this.pawn.Name = PawnBioAndNameGenerator.GeneratePawnName(this.pawn, NameStyle.Numeric, (string)null); + } + } } - this.pawn.Name = PawnBioAndNameGenerator.GeneratePawnName(this.pawn, NameStyle.Numeric, null); } public void DebugMake1YearOlder() diff --git a/Assembly-CSharp/Verse/Pawn_CallTracker.cs b/Assembly-CSharp/Verse/Pawn_CallTracker.cs index 467663573..9c52a8760 100644 --- a/Assembly-CSharp/Verse/Pawn_CallTracker.cs +++ b/Assembly-CSharp/Verse/Pawn_CallTracker.cs @@ -21,7 +21,19 @@ private bool PawnAggressive { get { - return this.pawn.InAggroMentalState || (this.pawn.mindState.enemyTarget != null && this.pawn.mindState.enemyTarget.Spawned && Find.TickManager.TicksGame - this.pawn.mindState.lastEngageTargetTick <= 360) || (this.pawn.CurJob != null && this.pawn.CurJob.def == JobDefOf.AttackMelee); + if (this.pawn.InAggroMentalState) + { + return true; + } + if (this.pawn.mindState.enemyTarget != null && this.pawn.mindState.enemyTarget.Spawned && Find.TickManager.TicksGame - this.pawn.mindState.lastEngageTargetTick <= 360) + { + return true; + } + if (this.pawn.CurJob != null && this.pawn.CurJob.def == JobDefOf.AttackMelee) + { + return true; + } + return false; } } @@ -32,18 +44,30 @@ private float IdleCallVolumeFactor switch (Find.TickManager.CurTimeSpeed) { case TimeSpeed.Paused: + { return 1f; + } case TimeSpeed.Normal: + { return 1f; + } case TimeSpeed.Fast: + { return 1f; + } case TimeSpeed.Superfast: + { return 0.25f; + } case TimeSpeed.Ultrafast: + { return 0.25f; + } default: + { throw new NotImplementedException(); } + } } } @@ -77,34 +101,24 @@ private void ResetTicksToNextCall() private void TryDoCall() { - if (!Find.CameraDriver.CurrentViewRect.ExpandedBy(10).Contains(this.pawn.Position)) - { - return; - } - if (this.pawn.Downed || !this.pawn.Awake()) + if (Find.CameraDriver.CurrentViewRect.ExpandedBy(10).Contains(this.pawn.Position) && !this.pawn.Downed && this.pawn.Awake() && !this.pawn.Position.Fogged(this.pawn.Map)) { - return; + this.DoCall(); } - if (this.pawn.Position.Fogged(this.pawn.Map)) - { - return; - } - this.DoCall(); } public void DoCall() { - if (!this.pawn.Spawned) + if (this.pawn.Spawned) { - return; - } - if (this.PawnAggressive) - { - LifeStageUtility.PlayNearestLifestageSound(this.pawn, (LifeStageAge ls) => ls.soundAngry, 1f); - } - else - { - LifeStageUtility.PlayNearestLifestageSound(this.pawn, (LifeStageAge ls) => ls.soundCall, this.IdleCallVolumeFactor); + if (this.PawnAggressive) + { + LifeStageUtility.PlayNearestLifestageSound(this.pawn, (Func)((LifeStageAge ls) => ls.soundAngry), 1f); + } + else + { + LifeStageUtility.PlayNearestLifestageSound(this.pawn, (Func)((LifeStageAge ls) => ls.soundCall), this.IdleCallVolumeFactor); + } } } @@ -115,7 +129,7 @@ public void Notify_InAggroMentalState() public void Notify_DidMeleeAttack() { - if (Rand.Value < 0.5f) + if (Rand.Value < 0.5) { this.ticksToNextCall = Pawn_CallTracker.CallOnMeleeDelayRange.RandomInRange; } @@ -123,7 +137,7 @@ public void Notify_DidMeleeAttack() public void Notify_Released() { - if (Rand.Value < 0.75f) + if (Rand.Value < 0.75) { this.ticksToNextCall = Pawn_CallTracker.CallOnAggroDelayRange.RandomInRange; } diff --git a/Assembly-CSharp/Verse/Pawn_CarryTracker.cs b/Assembly-CSharp/Verse/Pawn_CarryTracker.cs index 3467f011d..7f7d9bc85 100644 --- a/Assembly-CSharp/Verse/Pawn_CarryTracker.cs +++ b/Assembly-CSharp/Verse/Pawn_CarryTracker.cs @@ -48,7 +48,7 @@ public Pawn_CarryTracker(Pawn pawn) public void ExposeData() { - Scribe_Deep.Look>(ref this.innerContainer, "innerContainer", new object[] + Scribe_Deep.Look>(ref this.innerContainer, "innerContainer", new object[1] { this }); @@ -83,32 +83,32 @@ public int MaxStackSpaceEver(ThingDef td) public bool TryStartCarry(Thing item) { - if (this.pawn.Dead || this.pawn.Downed) + if (!this.pawn.Dead && !this.pawn.Downed) { - Log.Error("Dead/downed pawn " + this.pawn + " tried to start carry item."); + if (this.innerContainer.TryAdd(item, true)) + { + item.def.soundPickup.PlayOneShot(new TargetInfo(item.Position, this.pawn.Map, false)); + return true; + } return false; } - if (this.innerContainer.TryAdd(item, true)) - { - item.def.soundPickup.PlayOneShot(new TargetInfo(item.Position, this.pawn.Map, false)); - return true; - } + Log.Error("Dead/downed pawn " + this.pawn + " tried to start carry item."); return false; } public int TryStartCarry(Thing item, int count) { - if (this.pawn.Dead || this.pawn.Downed) + if (!this.pawn.Dead && !this.pawn.Downed) { - Log.Error("Dead/downed pawn " + this.pawn + " tried to start carry item."); - return 0; - } - int num = this.innerContainer.TryAdd(item, count, true); - if (num > 0) - { - item.def.soundPickup.PlayOneShot(new TargetInfo(item.Position, this.pawn.Map, false)); + int num = this.innerContainer.TryAdd(item, count, true); + if (num > 0) + { + item.def.soundPickup.PlayOneShot(new TargetInfo(item.Position, this.pawn.Map, false)); + } + return num; } - return num; + Log.Error("Dead/downed pawn " + this.pawn + " tried to start carry item."); + return 0; } public bool TryDropCarriedThing(IntVec3 dropLoc, ThingPlaceMode mode, out Thing resultingThing, Action placedAction = null) diff --git a/Assembly-CSharp/Verse/Pawn_DrawTracker.cs b/Assembly-CSharp/Verse/Pawn_DrawTracker.cs index ecd62abb7..27d40e78a 100644 --- a/Assembly-CSharp/Verse/Pawn_DrawTracker.cs +++ b/Assembly-CSharp/Verse/Pawn_DrawTracker.cs @@ -1,5 +1,4 @@ using RimWorld; -using System; using UnityEngine; namespace Verse @@ -56,20 +55,15 @@ public Pawn_DrawTracker(Pawn pawn) public void DrawTrackerTick() { - if (!this.pawn.Spawned) + if (this.pawn.Spawned && (Current.ProgramState != ProgramState.Playing || Find.CameraDriver.CurrentViewRect.ExpandedBy(3).Contains(this.pawn.Position))) { - return; + this.jitterer.JitterHandlerTick(); + this.footprintMaker.FootprintMakerTick(); + this.breathMoteMaker.BreathMoteMakerTick(); + this.leaner.LeanerTick(); + this.rotator.PawnRotatorTick(); + this.renderer.RendererTick(); } - if (Current.ProgramState == ProgramState.Playing && !Find.CameraDriver.CurrentViewRect.ExpandedBy(3).Contains(this.pawn.Position)) - { - return; - } - this.jitterer.JitterHandlerTick(); - this.footprintMaker.FootprintMakerTick(); - this.breathMoteMaker.BreathMoteMakerTick(); - this.leaner.LeanerTick(); - this.rotator.PawnRotatorTick(); - this.renderer.RendererTick(); } public void DrawAt(Vector3 loc) @@ -89,12 +83,11 @@ public void Notify_WarmingCastAlongLine(ShootLine newShootLine, IntVec3 ShootPos public void Notify_DamageApplied(DamageInfo dinfo) { - if (this.pawn.Destroyed) + if (!this.pawn.Destroyed) { - return; + this.jitterer.Notify_DamageApplied(dinfo); + this.renderer.Notify_DamageApplied(dinfo); } - this.jitterer.Notify_DamageApplied(dinfo); - this.renderer.Notify_DamageApplied(dinfo); } public void Notify_MeleeAttackOn(Thing Target) diff --git a/Assembly-CSharp/Verse/Pawn_EquipmentTracker.cs b/Assembly-CSharp/Verse/Pawn_EquipmentTracker.cs index bc45d29dc..e2cbce303 100644 --- a/Assembly-CSharp/Verse/Pawn_EquipmentTracker.cs +++ b/Assembly-CSharp/Verse/Pawn_EquipmentTracker.cs @@ -1,7 +1,6 @@ using RimWorld; using System; using System.Collections.Generic; -using System.Diagnostics; using System.Linq; namespace Verse @@ -27,26 +26,27 @@ public ThingWithComps Primary } private set { - if (this.Primary == value) + if (this.Primary != value) { - return; - } - if (value != null && value.def.equipmentType != EquipmentType.Primary) - { - Log.Error("Tried to set non-primary equipment as primary."); - return; - } - if (this.Primary != null) - { - this.equipment.Remove(this.Primary); - } - if (value != null) - { - this.equipment.TryAdd(value, true); - } - if (this.pawn.drafter != null) - { - this.pawn.drafter.Notify_PrimaryWeaponChanged(); + if (value != null && value.def.equipmentType != EquipmentType.Primary) + { + Log.Error("Tried to set non-primary equipment as primary."); + } + else + { + if (this.Primary != null) + { + this.equipment.Remove(this.Primary); + } + if (value != null) + { + this.equipment.TryAdd(value, true); + } + if (this.pawn.drafter != null) + { + this.pawn.drafter.Notify_PrimaryWeaponChanged(); + } + } } } } @@ -71,11 +71,16 @@ public IEnumerable AllEquipmentVerbs { get { - Pawn_EquipmentTracker.<>c__Iterator21E <>c__Iterator21E = new Pawn_EquipmentTracker.<>c__Iterator21E(); - <>c__Iterator21E.<>f__this = this; - Pawn_EquipmentTracker.<>c__Iterator21E expr_0E = <>c__Iterator21E; - expr_0E.$PC = -2; - return expr_0E; + List list = this.AllEquipmentListForReading; + for (int j = 0; j < list.Count; j++) + { + ThingWithComps eq = list[j]; + List verbs = eq.GetComp().AllVerbs; + for (int i = 0; i < verbs.Count; i++) + { + yield return verbs[i]; + } + } } } @@ -95,7 +100,7 @@ public Pawn_EquipmentTracker(Pawn newPawn) public void ExposeData() { - Scribe_Deep.Look>(ref this.equipment, "equipment", new object[] + Scribe_Deep.Look>(ref this.equipment, "equipment", new object[1] { this }); @@ -105,10 +110,19 @@ public void ExposeData() for (int i = 0; i < allEquipmentListForReading.Count; i++) { ThingWithComps thingWithComps = allEquipmentListForReading[i]; - foreach (Verb current in thingWithComps.GetComp().AllVerbs) + List.Enumerator enumerator = thingWithComps.GetComp().AllVerbs.GetEnumerator(); + try { - current.caster = this.pawn; - current.ownerEquipment = thingWithComps; + while (enumerator.MoveNext()) + { + Verb current = enumerator.Current; + current.caster = this.pawn; + current.ownerEquipment = thingWithComps; + } + } + finally + { + ((IDisposable)(object)enumerator).Dispose(); } } } @@ -133,7 +147,7 @@ public void MakeRoomFor(ThingWithComps eq) { if (eq.def.equipmentType == EquipmentType.Primary && this.Primary != null) { - ThingWithComps thingWithComps; + ThingWithComps thingWithComps = default(ThingWithComps); if (this.TryDropEquipment(this.Primary, out thingWithComps, this.pawn.Position, true)) { if (thingWithComps != null) @@ -157,17 +171,11 @@ public bool TryDropEquipment(ThingWithComps eq, out ThingWithComps resultingEq, { if (!pos.IsValid) { - Log.Error(string.Concat(new object[] - { - this.pawn, - " tried to drop ", - eq, - " at invalid cell." - })); + Log.Error(this.pawn + " tried to drop " + eq + " at invalid cell."); resultingEq = null; return false; } - if (this.equipment.TryDrop(eq, pos, this.pawn.MapHeld, ThingPlaceMode.Near, out resultingEq, null)) + if (this.equipment.TryDrop((Thing)eq, pos, this.pawn.MapHeld, ThingPlaceMode.Near, out resultingEq, (Action)null)) { if (resultingEq != null) { @@ -180,10 +188,10 @@ public bool TryDropEquipment(ThingWithComps eq, out ThingWithComps resultingEq, public void DropAllEquipment(IntVec3 pos, bool forbid = true) { - for (int i = this.equipment.Count - 1; i >= 0; i--) + for (int num = this.equipment.Count - 1; num >= 0; num--) { - ThingWithComps thingWithComps; - this.TryDropEquipment(this.equipment[i], out thingWithComps, pos, forbid); + ThingWithComps thingWithComps = default(ThingWithComps); + this.TryDropEquipment(this.equipment[num], out thingWithComps, pos, forbid); } } @@ -197,10 +205,12 @@ public void DestroyEquipment(ThingWithComps eq) if (!this.equipment.Contains(eq)) { Log.Warning("Tried to destroy equipment " + eq + " but it's not here."); - return; } - this.Remove(eq); - eq.Destroy(DestroyMode.Vanish); + else + { + this.Remove(eq); + eq.Destroy(DestroyMode.Vanish); + } } public void DestroyAllEquipment(DestroyMode mode = DestroyMode.Vanish) @@ -229,28 +239,50 @@ public void AddEquipment(ThingWithComps newEq) { if (newEq.def.equipmentType == EquipmentType.Primary && this.Primary != null) { - Log.Error(string.Concat(new object[] - { - "Pawn ", - this.pawn.LabelCap, - " got primaryInt equipment ", - newEq, - " while already having primaryInt equipment ", - this.Primary - })); - return; + Log.Error("Pawn " + this.pawn.LabelCap + " got primaryInt equipment " + newEq + " while already having primaryInt equipment " + this.Primary); + } + else + { + this.equipment.TryAdd(newEq, true); } - this.equipment.TryAdd(newEq, true); } - [DebuggerHidden] public IEnumerable GetGizmos() { - Pawn_EquipmentTracker.c__Iterator21F c__Iterator21F = new Pawn_EquipmentTracker.c__Iterator21F(); - c__Iterator21F.<>f__this = this; - Pawn_EquipmentTracker.c__Iterator21F expr_0E = c__Iterator21F; - expr_0E.$PC = -2; - return expr_0E; + if (this.ShouldUseSquadAttackGizmo()) + { + yield return this.GetSquadAttackGizmo(); + } + else + { + List list = this.AllEquipmentListForReading; + for (int i = 0; i < list.Count; i++) + { + ThingWithComps eq = list[i]; + foreach (Command verbsCommand in eq.GetComp().GetVerbsCommands()) + { + switch (i) + { + case 0: + { + verbsCommand.hotKey = KeyBindingDefOf.Misc1; + break; + } + case 1: + { + verbsCommand.hotKey = KeyBindingDefOf.Misc2; + break; + } + case 2: + { + verbsCommand.hotKey = KeyBindingDefOf.Misc3; + break; + } + } + yield return (Gizmo)verbsCommand; + } + } + } } public bool TryStartAttack(LocalTargetInfo targ) @@ -265,7 +297,11 @@ public bool TryStartAttack(LocalTargetInfo targ) } bool allowManualCastWeapons = !this.pawn.IsColonist; Verb verb = this.pawn.TryGetAttackVerb(allowManualCastWeapons); - return verb != null && verb.TryStartCastOn(targ, false, true); + if (verb == null) + { + return false; + } + return verb.TryStartCastOn(targ, false, true); } private bool ShouldUseSquadAttackGizmo() @@ -282,15 +318,7 @@ private bool ShouldUseSquadAttackGizmo() Pawn pawn = selectedObjectsListForReading[i] as Pawn; if (pawn != null && pawn.IsColonist) { - ThingDef thingDef2; - if (pawn.equipment.Primary == null) - { - thingDef2 = null; - } - else - { - thingDef2 = pawn.equipment.Primary.def; - } + ThingDef thingDef2 = (pawn.equipment.Primary != null) ? pawn.equipment.Primary.def : null; if (!flag) { thingDef = thingDef2; @@ -313,23 +341,23 @@ private Gizmo GetSquadAttackGizmo() command_Target.targetingParams = TargetingParameters.ForAttackAny(); command_Target.hotKey = KeyBindingDefOf.Misc1; command_Target.icon = TexCommand.SquadAttack; - string str; - if (FloatMenuUtility.GetAttackAction(this.pawn, LocalTargetInfo.Invalid, out str) == null) + string str = default(string); + if ((object)FloatMenuUtility.GetAttackAction(this.pawn, LocalTargetInfo.Invalid, out str) == null) { command_Target.Disable(str.CapitalizeFirst() + "."); } - command_Target.action = delegate(Thing target) + command_Target.action = (Action)delegate(Thing target) { - IEnumerable enumerable = Find.Selector.SelectedObjects.Where(delegate(object x) + IEnumerable enumerable = Find.Selector.SelectedObjects.Where((Func)delegate(object x) { Pawn pawn = x as Pawn; return pawn != null && pawn.IsColonistPlayerControlled && pawn.Drafted; }).Cast(); - foreach (Pawn current in enumerable) + foreach (Pawn item in enumerable) { - string text; - Action attackAction = FloatMenuUtility.GetAttackAction(current, target, out text); - if (attackAction != null) + string text = default(string); + Action attackAction = FloatMenuUtility.GetAttackAction(item, target, out text); + if ((object)attackAction != null) { attackAction(); } @@ -340,10 +368,19 @@ private Gizmo GetSquadAttackGizmo() public void Notify_EquipmentAdded(ThingWithComps eq) { - foreach (Verb current in eq.GetComp().AllVerbs) + List.Enumerator enumerator = eq.GetComp().AllVerbs.GetEnumerator(); + try + { + while (enumerator.MoveNext()) + { + Verb current = enumerator.Current; + current.caster = this.pawn; + current.Notify_PickedUp(); + } + } + finally { - current.caster = this.pawn; - current.Notify_PickedUp(); + ((IDisposable)(object)enumerator).Dispose(); } } diff --git a/Assembly-CSharp/Verse/Pawn_HealthTracker.cs b/Assembly-CSharp/Verse/Pawn_HealthTracker.cs index 9167f3d51..ca053291a 100644 --- a/Assembly-CSharp/Verse/Pawn_HealthTracker.cs +++ b/Assembly-CSharp/Verse/Pawn_HealthTracker.cs @@ -64,7 +64,7 @@ public float PainShockThreshold for (int i = 0; i < allTraits.Count; i++) { float painShockThreshold = allTraits[i].CurrentData.painShockThreshold; - if (painShockThreshold > 0f) + if (painShockThreshold > 0.0) { return painShockThreshold; } @@ -106,26 +106,26 @@ public void ExposeData() { Scribe_Values.Look(ref this.healthState, "healthState", PawnHealthState.Mobile, false); Scribe_Values.Look(ref this.forceIncap, "forceIncap", false, false); - Scribe_Deep.Look(ref this.hediffSet, "hediffSet", new object[] + Scribe_Deep.Look(ref this.hediffSet, "hediffSet", new object[1] { this.pawn }); - Scribe_Deep.Look(ref this.surgeryBills, "surgeryBills", new object[] + Scribe_Deep.Look(ref this.surgeryBills, "surgeryBills", new object[1] { this.pawn }); - Scribe_Deep.Look(ref this.immunity, "immunity", new object[] + Scribe_Deep.Look(ref this.immunity, "immunity", new object[1] { this.pawn }); } - public void AddHediff(HediffDef def, BodyPartRecord part = null, DamageInfo? dinfo = null) + public void AddHediff(HediffDef def, BodyPartRecord part = null, DamageInfo? dinfo = default(DamageInfo?)) { this.AddHediff(HediffMaker.MakeHediff(def, this.pawn, null), part, dinfo); } - public void AddHediff(Hediff hediff, BodyPartRecord part = null, DamageInfo? dinfo = null) + public void AddHediff(Hediff hediff, BodyPartRecord part = null, DamageInfo? dinfo = default(DamageInfo?)) { if (part != null) { @@ -156,7 +156,7 @@ public void RemoveHediff(Hediff hediff) public void Notify_HediffChanged(Hediff hediff) { this.hediffSet.DirtyCache(); - this.CheckForStateChange(null, hediff); + this.CheckForStateChange(default(DamageInfo?), hediff); } public void PreApplyDamage(DamageInfo dinfo, out bool absorbed) @@ -254,15 +254,13 @@ public void PostApplyDamage(DamageInfo dinfo, float totalDamageDealt) if (damageDefAdditionalHediff.hediff != null) { float num = totalDamageDealt * damageDefAdditionalHediff.severityPerDamageDealt; - if (num >= 0f) + if (num >= 0.0) { Hediff hediff = HediffMaker.MakeHediff(damageDefAdditionalHediff.hediff, this.pawn, null); hediff.Severity = num; this.AddHediff(hediff, null, new DamageInfo?(dinfo)); if (this.Dead) - { return; - } } } } @@ -279,32 +277,34 @@ public void RestorePart(BodyPartRecord part, Hediff diffException = null, bool c if (part == null) { Log.Error("Tried to restore null body part."); - return; } - this.RestorePartRecursive(part, diffException); - this.hediffSet.DirtyCache(); - if (checkStateChange) + else { - this.CheckForStateChange(null, null); + this.RestorePartRecursive(part, diffException); + this.hediffSet.DirtyCache(); + if (checkStateChange) + { + this.CheckForStateChange(default(DamageInfo?), null); + } } } private void RestorePartRecursive(BodyPartRecord part, Hediff diffException = null) { List hediffs = this.hediffSet.hediffs; - for (int i = hediffs.Count - 1; i >= 0; i--) + for (int num = hediffs.Count - 1; num >= 0; num--) { - Hediff hediff = hediffs[i]; + Hediff hediff = hediffs[num]; if (hediff.Part == part && hediff != diffException) { - Hediff hediff2 = hediffs[i]; - hediffs.RemoveAt(i); + Hediff hediff2 = hediffs[num]; + hediffs.RemoveAt(num); hediff2.PostRemoved(); } } - for (int j = 0; j < part.parts.Count; j++) + for (int i = 0; i < part.parts.Count; i++) { - this.RestorePartRecursive(part.parts[j], diffException); + this.RestorePartRecursive(part.parts[i], diffException); } } @@ -324,21 +324,21 @@ private void CheckForStateChange(DamageInfo? dinfo, Hediff hediff) this.NotifyPlayerOfKilled(dinfo, hediff, caravan); } } - return; } - if (!this.Downed) + else if (!this.Downed) { if (this.ShouldBeDowned()) { - float num = (!this.pawn.RaceProps.Animal) ? 0.67f : 0.47f; + float num = (float)((!this.pawn.RaceProps.Animal) ? 0.67000001668930054 : 0.4699999988079071); if (!this.forceIncap && dinfo.HasValue && dinfo.Value.Def.externalViolence && (this.pawn.Faction == null || !this.pawn.Faction.IsPlayer) && !this.pawn.IsPrisonerOfColony && this.pawn.RaceProps.IsFlesh && Rand.Value < num) { this.pawn.Kill(dinfo); - return; } - this.forceIncap = false; - this.MakeDowned(dinfo, hediff); - return; + else + { + this.forceIncap = false; + this.MakeDowned(dinfo, hediff); + } } else if (!this.capacities.CapableOf(PawnCapacityDefOf.Manipulation)) { @@ -354,7 +354,7 @@ private void CheckForStateChange(DamageInfo? dinfo, Hediff hediff) } else if (this.pawn.SpawnedOrAnyParentSpawned) { - ThingWithComps thingWithComps; + ThingWithComps thingWithComps = default(ThingWithComps); this.pawn.equipment.TryDropEquipment(this.pawn.equipment.Primary, out thingWithComps, this.pawn.PositionHeld, true); } else @@ -367,7 +367,6 @@ private void CheckForStateChange(DamageInfo? dinfo, Hediff hediff) else if (!this.ShouldBeDowned()) { this.MakeUndowned(); - return; } } } @@ -394,14 +393,17 @@ private bool ShouldBeDead() for (int j = 0; j < allDefsListForReading.Count; j++) { PawnCapacityDef pawnCapacityDef = allDefsListForReading[j]; - bool flag = (!this.pawn.RaceProps.IsFlesh) ? pawnCapacityDef.lethalMechanoids : pawnCapacityDef.lethalFlesh; - if (flag && !this.capacities.CapableOf(pawnCapacityDef)) + if (((!this.pawn.RaceProps.IsFlesh) ? pawnCapacityDef.lethalMechanoids : pawnCapacityDef.lethalFlesh) && !this.capacities.CapableOf(pawnCapacityDef)) { return true; } } float num = PawnCapacityUtility.CalculatePartEfficiency(this.hediffSet, this.pawn.RaceProps.body.corePart, false, null); - return num <= 0.0001f; + if (num <= 9.9999997473787516E-05) + { + return true; + } + return false; } public void SetDead() @@ -418,59 +420,61 @@ private void MakeDowned(DamageInfo? dinfo, Hediff hediff) if (this.Downed) { Log.Error(this.pawn + " tried to do MakeDowned while already downed."); - return; } - this.healthState = PawnHealthState.Down; - PawnDiedOrDownedThoughtsUtility.TryGiveThoughts(this.pawn, dinfo, PawnDiedOrDownedThoughtsKind.Downed); - if (this.pawn.MentalState != null) - { - this.pawn.mindState.mentalStateHandler.CurState.RecoverFromState(); - } - if (this.pawn.Spawned) + else { - if (this.pawn.Faction == Faction.OfPlayer) + this.healthState = PawnHealthState.Down; + PawnDiedOrDownedThoughtsUtility.TryGiveThoughts(this.pawn, dinfo, PawnDiedOrDownedThoughtsKind.Downed); + if (this.pawn.MentalState != null) { - Find.StoryWatcher.watcherRampUp.Notify_PlayerPawnIncappedOrKilled(this.pawn); + this.pawn.mindState.mentalStateHandler.CurState.RecoverFromState(); } - this.pawn.DropAndForbidEverything(true); - this.pawn.stances.CancelBusyStanceSoft(); - } - this.pawn.ClearMind(true); - if (Current.ProgramState == ProgramState.Playing) - { - this.pawn.ClearReservations(true); - Lord lord = this.pawn.GetLord(); - if (lord != null) + if (this.pawn.Spawned) { - lord.Notify_PawnLost(this.pawn, PawnLostCondition.IncappedOrKilled); + if (this.pawn.Faction == Faction.OfPlayer) + { + Find.StoryWatcher.watcherRampUp.Notify_PlayerPawnIncappedOrKilled(this.pawn); + } + this.pawn.DropAndForbidEverything(true); + this.pawn.stances.CancelBusyStanceSoft(); } - } - if (this.pawn.Drafted) - { - this.pawn.drafter.Drafted = false; - } - PortraitsCache.SetDirty(this.pawn); - if (this.pawn.SpawnedOrAnyParentSpawned) - { - GenHostility.Notify_PawnLostForTutor(this.pawn, this.pawn.MapHeld); - } - if (this.pawn.RaceProps.Humanlike && Current.ProgramState == ProgramState.Playing && this.pawn.SpawnedOrAnyParentSpawned) - { - if (this.pawn.HostileTo(Faction.OfPlayer)) + this.pawn.ClearMind(true); + if (Current.ProgramState == ProgramState.Playing) { - LessonAutoActivator.TeachOpportunity(ConceptDefOf.Capturing, this.pawn, OpportunityType.Important); + this.pawn.ClearReservations(true); + Lord lord = this.pawn.GetLord(); + if (lord != null) + { + lord.Notify_PawnLost(this.pawn, PawnLostCondition.IncappedOrKilled); + } } - if (this.pawn.Faction == Faction.OfPlayer) + if (this.pawn.Drafted) { - LessonAutoActivator.TeachOpportunity(ConceptDefOf.Rescuing, this.pawn, OpportunityType.Critical); + this.pawn.drafter.Drafted = false; } - } - if (dinfo.HasValue && dinfo.Value.Instigator != null) - { - Pawn pawn = dinfo.Value.Instigator as Pawn; - if (pawn != null) + PortraitsCache.SetDirty(this.pawn); + if (this.pawn.SpawnedOrAnyParentSpawned) + { + GenHostility.Notify_PawnLostForTutor(this.pawn, this.pawn.MapHeld); + } + if (this.pawn.RaceProps.Humanlike && Current.ProgramState == ProgramState.Playing && this.pawn.SpawnedOrAnyParentSpawned) { - RecordsUtility.Notify_PawnDowned(this.pawn, pawn); + if (this.pawn.HostileTo(Faction.OfPlayer)) + { + LessonAutoActivator.TeachOpportunity(ConceptDefOf.Capturing, this.pawn, OpportunityType.Important); + } + if (this.pawn.Faction == Faction.OfPlayer) + { + LessonAutoActivator.TeachOpportunity(ConceptDefOf.Rescuing, this.pawn, OpportunityType.Critical); + } + } + if (dinfo.HasValue && dinfo.Value.Instigator != null) + { + Pawn pawn = dinfo.Value.Instigator as Pawn; + if (pawn != null) + { + RecordsUtility.Notify_PawnDowned(this.pawn, pawn); + } } } } @@ -480,157 +484,135 @@ private void MakeUndowned() if (!this.Downed) { Log.Error(this.pawn + " tried to do MakeUndowned when already undowned."); - return; } - this.healthState = PawnHealthState.Mobile; - if (PawnUtility.ShouldSendNotificationAbout(this.pawn)) + else { - Messages.Message("MessageNoLongerDowned".Translate(new object[] + this.healthState = PawnHealthState.Mobile; + if (PawnUtility.ShouldSendNotificationAbout(this.pawn)) { - this.pawn.LabelCap - }), this.pawn, MessageSound.Benefit); - } - if (this.pawn.Spawned && !this.pawn.InBed()) - { - this.pawn.jobs.EndCurrentJob(JobCondition.Incompletable, true); - } - PortraitsCache.SetDirty(this.pawn); - if (this.pawn.guest != null) - { - this.pawn.guest.Notify_PawnUndowned(); + Messages.Message("MessageNoLongerDowned".Translate(this.pawn.LabelCap), (Thing)this.pawn, MessageSound.Benefit); + } + if (this.pawn.Spawned && !this.pawn.InBed()) + { + this.pawn.jobs.EndCurrentJob(JobCondition.Incompletable, true); + } + PortraitsCache.SetDirty(this.pawn); + if (this.pawn.guest != null) + { + this.pawn.guest.Notify_PawnUndowned(); + } } } public void NotifyPlayerOfKilled(DamageInfo? dinfo, Hediff hediff, Caravan caravan) { - string text = null; + string text = (string)null; if (dinfo.HasValue) { text = string.Format(dinfo.Value.Def.deathMessage, this.pawn.NameStringShort.CapitalizeFirst()); } else if (hediff != null) { - text = "PawnDiedBecauseOf".Translate(new object[] - { - this.pawn.NameStringShort.CapitalizeFirst(), - hediff.def.label - }); + text = "PawnDiedBecauseOf".Translate(this.pawn.NameStringShort.CapitalizeFirst(), hediff.def.label); } if (!text.NullOrEmpty()) { text = text.AdjustedFor(this.pawn); - GlobalTargetInfo lookTarget; - if (caravan != null) - { - lookTarget = caravan; - } - else - { - lookTarget = this.pawn; - } + GlobalTargetInfo lookTarget = (caravan == null) ? ((Thing)this.pawn) : ((WorldObject)caravan); Messages.Message(text, lookTarget, MessageSound.Negative); } } public void HealthTick() { - if (this.Dead) - { - return; - } - for (int i = this.hediffSet.hediffs.Count - 1; i >= 0; i--) - { - Hediff hediff = this.hediffSet.hediffs[i]; - hediff.Tick(); - hediff.PostTick(); - } - bool flag = false; - for (int j = this.hediffSet.hediffs.Count - 1; j >= 0; j--) + if (!this.Dead) { - Hediff hediff2 = this.hediffSet.hediffs[j]; - if (hediff2.ShouldRemove) + for (int num = this.hediffSet.hediffs.Count - 1; num >= 0; num--) { - this.hediffSet.hediffs.RemoveAt(j); - hediff2.PostRemoved(); - flag = true; + Hediff hediff = this.hediffSet.hediffs[num]; + hediff.Tick(); + hediff.PostTick(); } - } - if (flag) - { - this.Notify_HediffChanged(null); - } - if (this.Dead) - { - return; - } - this.immunity.ImmunityHandlerTick(); - if (this.pawn.RaceProps.IsFlesh && this.pawn.IsHashIntervalTick(600) && (this.pawn.needs.food == null || !this.pawn.needs.food.Starving)) - { - bool flag2 = false; - if (this.hediffSet.HasNaturallyHealingInjury()) + bool flag = false; + for (int num2 = this.hediffSet.hediffs.Count - 1; num2 >= 0; num2--) { - float num = 8f; - if (this.pawn.GetPosture() != PawnPosture.Standing) + Hediff hediff2 = this.hediffSet.hediffs[num2]; + if (hediff2.ShouldRemove) { - num += 4f; - Building_Bed building_Bed = this.pawn.CurrentBed(); - if (building_Bed != null) - { - num += building_Bed.def.building.bed_healPerDay; - } + this.hediffSet.hediffs.RemoveAt(num2); + hediff2.PostRemoved(); + flag = true; } - Hediff_Injury hediff_Injury = (from x in this.hediffSet.GetHediffs() - where x.CanHealNaturally() - select x).RandomElement(); - hediff_Injury.Heal(num * this.pawn.HealthScale * 0.01f); - flag2 = true; } - if (this.hediffSet.HasTendedAndHealingInjury() && (this.pawn.needs.food == null || !this.pawn.needs.food.Starving)) + if (flag) { - Hediff_Injury hediff_Injury2 = (from x in this.hediffSet.GetHediffs() - where x.CanHealFromTending() - select x).RandomElement(); - float tendQuality = hediff_Injury2.TryGetComp().tendQuality; - float num2 = GenMath.LerpDouble(0f, 1f, 0.5f, 1.5f, Mathf.Clamp01(tendQuality)); - hediff_Injury2.Heal(22f * num2 * this.pawn.HealthScale * 0.01f); - flag2 = true; + this.Notify_HediffChanged(null); } - if (flag2 && !this.HasHediffsNeedingTendByColony(false) && !HealthAIUtility.ShouldSeekMedicalRest(this.pawn) && !this.hediffSet.HasTendedAndHealingInjury() && PawnUtility.ShouldSendNotificationAbout(this.pawn)) + if (!this.Dead) { - Messages.Message("MessageFullyHealed".Translate(new object[] + this.immunity.ImmunityHandlerTick(); + if (this.pawn.RaceProps.IsFlesh && this.pawn.IsHashIntervalTick(600) && (this.pawn.needs.food == null || !this.pawn.needs.food.Starving)) { - this.pawn.LabelCap - }), this.pawn, MessageSound.Benefit); - } - } - if (this.pawn.RaceProps.IsFlesh && this.hediffSet.BleedRateTotal >= 0.1f) - { - float num3 = this.hediffSet.BleedRateTotal * this.pawn.BodySize; - if (this.pawn.GetPosture() == PawnPosture.Standing) - { - num3 *= 0.008f; - } - else - { - num3 *= 0.0008f; - } - if (Rand.Value < num3) - { - this.TryDropBloodFilth(); - } - } - List hediffGiverSets = this.pawn.RaceProps.hediffGiverSets; - if (hediffGiverSets != null && this.pawn.IsHashIntervalTick(60)) - { - for (int k = 0; k < hediffGiverSets.Count; k++) - { - List hediffGivers = hediffGiverSets[k].hediffGivers; - for (int l = 0; l < hediffGivers.Count; l++) + bool flag2 = false; + if (this.hediffSet.HasNaturallyHealingInjury()) + { + float num3 = 8f; + if (this.pawn.GetPosture() != 0) + { + num3 = (float)(num3 + 4.0); + Building_Bed building_Bed = this.pawn.CurrentBed(); + if (building_Bed != null) + { + num3 += building_Bed.def.building.bed_healPerDay; + } + } + Hediff_Injury hediff_Injury = (from x in this.hediffSet.GetHediffs() + where x.CanHealNaturally() + select x).RandomElement(); + hediff_Injury.Heal((float)(num3 * this.pawn.HealthScale * 0.0099999997764825821)); + flag2 = true; + } + if (this.hediffSet.HasTendedAndHealingInjury() && (this.pawn.needs.food == null || !this.pawn.needs.food.Starving)) + { + Hediff_Injury hediff_Injury2 = (from x in this.hediffSet.GetHediffs() + where x.CanHealFromTending() + select x).RandomElement(); + float tendQuality = hediff_Injury2.TryGetComp().tendQuality; + float num4 = GenMath.LerpDouble(0f, 1f, 0.5f, 1.5f, Mathf.Clamp01(tendQuality)); + hediff_Injury2.Heal((float)(22.0 * num4 * this.pawn.HealthScale * 0.0099999997764825821)); + flag2 = true; + } + if (flag2 && !this.HasHediffsNeedingTendByColony(false) && !HealthAIUtility.ShouldSeekMedicalRest(this.pawn) && !this.hediffSet.HasTendedAndHealingInjury() && PawnUtility.ShouldSendNotificationAbout(this.pawn)) + { + Messages.Message("MessageFullyHealed".Translate(this.pawn.LabelCap), (Thing)this.pawn, MessageSound.Benefit); + } + } + if (this.pawn.RaceProps.IsFlesh && this.hediffSet.BleedRateTotal >= 0.10000000149011612) { - hediffGivers[l].OnIntervalPassed(this.pawn, null); - if (this.pawn.Dead) + float num5 = this.hediffSet.BleedRateTotal * this.pawn.BodySize; + num5 = (float)((this.pawn.GetPosture() != 0) ? (num5 * 0.00079999997979030013) : (num5 * 0.00800000037997961)); + if (Rand.Value < num5) { - return; + this.TryDropBloodFilth(); + } + } + List hediffGiverSets = this.pawn.RaceProps.hediffGiverSets; + if (hediffGiverSets != null && this.pawn.IsHashIntervalTick(60)) + { + for (int i = 0; i < hediffGiverSets.Count; i++) + { + List hediffGivers = hediffGiverSets[i].hediffGivers; + int num6 = 0; + while (num6 < hediffGivers.Count) + { + hediffGivers[num6].OnIntervalPassed(this.pawn, null); + if (!this.pawn.Dead) + { + num6++; + continue; + } + return; + } } } } @@ -658,17 +640,24 @@ public bool HasHediffsNeedingTendByColony(bool forAlert = false) return true; } } - else if ((this.pawn.Faction == Faction.OfPlayer && this.pawn.HostFaction == null) || this.pawn.HostFaction == Faction.OfPlayer) + else { - return true; + if (this.pawn.Faction == Faction.OfPlayer && this.pawn.HostFaction == null) + { + goto IL_009b; + } + if (this.pawn.HostFaction == Faction.OfPlayer) + goto IL_009b; } } return false; + IL_009b: + return true; } protected void TryDropBloodFilth() { - if (Rand.Value < 0.5f) + if (Rand.Value < 0.5) { this.DropBloodFilth(); } @@ -676,7 +665,9 @@ protected void TryDropBloodFilth() public void DropBloodFilth() { - if ((this.pawn.Spawned || this.pawn.ParentHolder is Pawn_CarryTracker) && this.pawn.SpawnedOrAnyParentSpawned && this.pawn.RaceProps.BloodDef != null) + if (!this.pawn.Spawned && !(this.pawn.ParentHolder is Pawn_CarryTracker)) + return; + if (this.pawn.SpawnedOrAnyParentSpawned && this.pawn.RaceProps.BloodDef != null) { FilthMaker.MakeFilth(this.pawn.PositionHeld, this.pawn.MapHeld, this.pawn.RaceProps.BloodDef, this.pawn.LabelIndefinite(), 1); } diff --git a/Assembly-CSharp/Verse/Pawn_InventoryTracker.cs b/Assembly-CSharp/Verse/Pawn_InventoryTracker.cs index 572127726..372394753 100644 --- a/Assembly-CSharp/Verse/Pawn_InventoryTracker.cs +++ b/Assembly-CSharp/Verse/Pawn_InventoryTracker.cs @@ -71,13 +71,16 @@ public ThingStackPart FirstUnloadableThing return new ThingStackPart(this.innerContainer[j], this.innerContainer[j].stackCount); } int num = -1; - for (int k = 0; k < Pawn_InventoryTracker.tmpDrugsToKeep.Count; k++) + int num2 = 0; + while (num2 < Pawn_InventoryTracker.tmpDrugsToKeep.Count) { - if (this.innerContainer[j].def == Pawn_InventoryTracker.tmpDrugsToKeep[k].ThingDef) + if (this.innerContainer[j].def != Pawn_InventoryTracker.tmpDrugsToKeep[num2].ThingDef) { - num = k; - break; + num2++; + continue; } + num = num2; + break; } if (num < 0) { @@ -112,7 +115,7 @@ public Pawn_InventoryTracker(Pawn pawn) public void ExposeData() { Scribe_Collections.Look(ref this.itemsNotForSale, "itemsNotForSale", LookMode.Reference, new object[0]); - Scribe_Deep.Look>(ref this.innerContainer, "innerContainer", new object[] + Scribe_Deep.Look>(ref this.innerContainer, "innerContainer", new object[1] { this }); @@ -138,28 +141,30 @@ public void DropAllNearPawn(IntVec3 pos, bool forbid = false, bool unforbid = fa if (this.pawn.MapHeld == null) { Log.Error("Tried to drop all inventory near pawn but the pawn is unspawned. pawn=" + this.pawn); - return; } - Pawn_InventoryTracker.tmpThingList.Clear(); - Pawn_InventoryTracker.tmpThingList.AddRange(this.innerContainer); - for (int i = 0; i < Pawn_InventoryTracker.tmpThingList.Count; i++) + else { - Thing thing; - this.innerContainer.TryDrop(Pawn_InventoryTracker.tmpThingList[i], pos, this.pawn.MapHeld, ThingPlaceMode.Near, out thing, delegate(Thing t, int unused) + Pawn_InventoryTracker.tmpThingList.Clear(); + Pawn_InventoryTracker.tmpThingList.AddRange(this.innerContainer); + for (int i = 0; i < Pawn_InventoryTracker.tmpThingList.Count; i++) { - if (forbid) + Thing thing = default(Thing); + this.innerContainer.TryDrop(Pawn_InventoryTracker.tmpThingList[i], pos, this.pawn.MapHeld, ThingPlaceMode.Near, out thing, (Action)delegate(Thing t, int unused) { - t.SetForbiddenIfOutsideHomeArea(); - } - if (unforbid) - { - t.SetForbidden(false, false); - } - if (t.def.IsPleasureDrug) - { - LessonAutoActivator.TeachOpportunity(ConceptDefOf.DrugBurning, OpportunityType.Important); - } - }); + if (forbid) + { + t.SetForbiddenIfOutsideHomeArea(); + } + if (unforbid) + { + t.SetForbidden(false, false); + } + if (t.def.IsPleasureDrug) + { + LessonAutoActivator.TeachOpportunity(ConceptDefOf.DrugBurning, OpportunityType.Important); + } + }); + } } } diff --git a/Assembly-CSharp/Verse/Pawn_StanceTracker.cs b/Assembly-CSharp/Verse/Pawn_StanceTracker.cs index 090d4558e..66648b3f4 100644 --- a/Assembly-CSharp/Verse/Pawn_StanceTracker.cs +++ b/Assembly-CSharp/Verse/Pawn_StanceTracker.cs @@ -1,5 +1,4 @@ using RimWorld; -using System; namespace Verse { @@ -54,7 +53,7 @@ public void StanceTrackerDraw() public void ExposeData() { Scribe_Values.Look(ref this.staggerUntilTick, "staggerUntilTick", 0, false); - Scribe_Deep.Look(ref this.stunner, "stunner", new object[] + Scribe_Deep.Look(ref this.stunner, "stunner", new object[1] { this.pawn }); @@ -87,16 +86,7 @@ public void SetStance(Stance newStance) { if (this.debugLog) { - Log.Message(string.Concat(new object[] - { - Find.TickManager.TicksGame, - " ", - this.pawn, - " SetStance ", - this.curStance, - " -> ", - newStance - })); + Log.Message(Find.TickManager.TicksGame + " " + this.pawn + " SetStance " + this.curStance + " -> " + newStance); } newStance.stanceTracker = this; this.curStance = newStance; diff --git a/Assembly-CSharp/Verse/PerfLogger.cs b/Assembly-CSharp/Verse/PerfLogger.cs index e7760ef8e..7c52e745c 100644 --- a/Assembly-CSharp/Verse/PerfLogger.cs +++ b/Assembly-CSharp/Verse/PerfLogger.cs @@ -1,4 +1,3 @@ -using System; using System.Diagnostics; using System.Text; @@ -34,13 +33,7 @@ public static void Record(string label) { PerfLogger.currentLog = new StringBuilder(); } - PerfLogger.currentLog.AppendLine(string.Format("{0}: {3}{1} ({2})", new object[] - { - (timestamp - PerfLogger.start) * 1000L / Stopwatch.Frequency, - label, - (timestamp - PerfLogger.current) * 1000L / Stopwatch.Frequency, - new string(' ', PerfLogger.indent * 2) - })); + PerfLogger.currentLog.AppendLine(string.Format("{0}: {3}{1} ({2})", (timestamp - PerfLogger.start) * 1000 / Stopwatch.Frequency, label, (timestamp - PerfLogger.current) * 1000 / Stopwatch.Frequency, new string(' ', PerfLogger.indent * 2))); PerfLogger.current = timestamp; } diff --git a/Assembly-CSharp/Verse/PermadeathModeUtility.cs b/Assembly-CSharp/Verse/PermadeathModeUtility.cs index cc074394f..f1621d818 100644 --- a/Assembly-CSharp/Verse/PermadeathModeUtility.cs +++ b/Assembly-CSharp/Verse/PermadeathModeUtility.cs @@ -7,10 +7,10 @@ public static class PermadeathModeUtility { public static string GeneratePermadeathSaveName() { - string text = NameGenerator.GenerateName(RulePackDefOf.NamerFactionPlayerRandomized, null, false); + string text = NameGenerator.GenerateName(RulePackDefOf.NamerFactionPlayerRandomized, (Predicate)null, false); int num = 0; string text2; - do + while (true) { num++; text2 = text; @@ -19,8 +19,9 @@ public static string GeneratePermadeathSaveName() text2 += num; } text2 = PermadeathModeUtility.AppendPermadeathModeSuffix(text2); + if (!SaveGameFilesUtility.SavedGameNamedExists(text2)) + break; } - while (SaveGameFilesUtility.SavedGameNamedExists(text2)); return text2; } diff --git a/Assembly-CSharp/Verse/PhysicalInteractionReservationManager.cs b/Assembly-CSharp/Verse/PhysicalInteractionReservationManager.cs index 9d3c2b534..79a066eda 100644 --- a/Assembly-CSharp/Verse/PhysicalInteractionReservationManager.cs +++ b/Assembly-CSharp/Verse/PhysicalInteractionReservationManager.cs @@ -18,45 +18,38 @@ public void ExposeData() } } - private List reservations = new List(); + private List reservations = new List(); public void Reserve(Pawn claimant, LocalTargetInfo target) { - if (this.IsReservedBy(claimant, target)) + if (!this.IsReservedBy(claimant, target)) { - return; + PhysicalInteractionReservation physicalInteractionReservation = new PhysicalInteractionReservation(); + physicalInteractionReservation.target = target; + physicalInteractionReservation.claimant = claimant; + this.reservations.Add(physicalInteractionReservation); } - PhysicalInteractionReservationManager.PhysicalInteractionReservation physicalInteractionReservation = new PhysicalInteractionReservationManager.PhysicalInteractionReservation(); - physicalInteractionReservation.target = target; - physicalInteractionReservation.claimant = claimant; - this.reservations.Add(physicalInteractionReservation); } public void Release(Pawn claimant, LocalTargetInfo target) { for (int i = 0; i < this.reservations.Count; i++) { - PhysicalInteractionReservationManager.PhysicalInteractionReservation physicalInteractionReservation = this.reservations[i]; + PhysicalInteractionReservation physicalInteractionReservation = this.reservations[i]; if (physicalInteractionReservation.target == target && physicalInteractionReservation.claimant == claimant) { this.reservations.RemoveAt(i); return; } } - Log.Warning(string.Concat(new object[] - { - claimant, - " tried to release reservation on target ", - target, - ", but it's not reserved by him." - })); + Log.Warning(claimant + " tried to release reservation on target " + target + ", but it's not reserved by him."); } public bool IsReservedBy(Pawn claimant, LocalTargetInfo target) { for (int i = 0; i < this.reservations.Count; i++) { - PhysicalInteractionReservationManager.PhysicalInteractionReservation physicalInteractionReservation = this.reservations[i]; + PhysicalInteractionReservation physicalInteractionReservation = this.reservations[i]; if (physicalInteractionReservation.target == target && physicalInteractionReservation.claimant == claimant) { return true; @@ -74,7 +67,7 @@ public Pawn FirstReserverOf(LocalTargetInfo target) { for (int i = 0; i < this.reservations.Count; i++) { - PhysicalInteractionReservationManager.PhysicalInteractionReservation physicalInteractionReservation = this.reservations[i]; + PhysicalInteractionReservation physicalInteractionReservation = this.reservations[i]; if (physicalInteractionReservation.target == target) { return physicalInteractionReservation.claimant; @@ -85,23 +78,23 @@ public Pawn FirstReserverOf(LocalTargetInfo target) public void ReleaseAllForTarget(LocalTargetInfo target) { - this.reservations.RemoveAll((PhysicalInteractionReservationManager.PhysicalInteractionReservation x) => x.target == target); + this.reservations.RemoveAll((Predicate)((PhysicalInteractionReservation x) => x.target == target)); } public void ReleaseAllClaimedBy(Pawn claimant) { - for (int i = this.reservations.Count - 1; i >= 0; i--) + for (int num = this.reservations.Count - 1; num >= 0; num--) { - if (this.reservations[i].claimant == claimant) + if (this.reservations[num].claimant == claimant) { - this.reservations.RemoveAt(i); + this.reservations.RemoveAt(num); } } } public void ExposeData() { - Scribe_Collections.Look(ref this.reservations, "reservations", LookMode.Deep, new object[0]); + Scribe_Collections.Look(ref this.reservations, "reservations", LookMode.Deep, new object[0]); } } } diff --git a/Assembly-CSharp/Verse/PlaceWorker.cs b/Assembly-CSharp/Verse/PlaceWorker.cs index 476869eb3..cd0408a74 100644 --- a/Assembly-CSharp/Verse/PlaceWorker.cs +++ b/Assembly-CSharp/Verse/PlaceWorker.cs @@ -1,5 +1,3 @@ -using System; - namespace Verse { public abstract class PlaceWorker diff --git a/Assembly-CSharp/Verse/PlayDataLoader.cs b/Assembly-CSharp/Verse/PlayDataLoader.cs index a7cb8a765..99c76cc11 100644 --- a/Assembly-CSharp/Verse/PlayDataLoader.cs +++ b/Assembly-CSharp/Verse/PlayDataLoader.cs @@ -24,52 +24,55 @@ public static void LoadAllPlayData(bool recovering = false) if (PlayDataLoader.loadedInt) { Log.Error("Loading play data when already loaded. Call ClearAllPlayData first."); - return; } - DeepProfiler.Start("LoadAllPlayData"); - try - { - PlayDataLoader.DoPlayLoad(); - } - catch (Exception arg) + else { - if (!Prefs.ResetModsConfigOnCrash) - { - throw; - } - if (recovering) + DeepProfiler.Start("LoadAllPlayData"); + try { - Log.Warning("Could not recover from errors loading play data. Giving up."); - throw; + PlayDataLoader.DoPlayLoad(); } - IEnumerable activeModsInLoadOrder = ModsConfig.ActiveModsInLoadOrder; - if (activeModsInLoadOrder.Count() == 1 && activeModsInLoadOrder.First().IsCoreMod) + catch (Exception arg) { - throw; + if (!Prefs.ResetModsConfigOnCrash) + { + throw; + } + if (recovering) + { + Log.Warning("Could not recover from errors loading play data. Giving up."); + throw; + } + IEnumerable activeModsInLoadOrder = ModsConfig.ActiveModsInLoadOrder; + if (activeModsInLoadOrder.Count() == 1 && activeModsInLoadOrder.First().IsCoreMod) + { + throw; + } + Log.Warning("Caught exception while loading play data but there are active mods other than Core. Resetting mods config and trying again.\nThe exception was: " + arg); + try + { + PlayDataLoader.ClearAllPlayData(); + } + catch + { + Log.Warning("Caught exception while recovering from errors and trying to clear all play data. Ignoring it.\nThe exception was: " + arg); + } + ModsConfig.Reset(); + DirectXmlCrossRefLoader.Clear(); + PlayDataLoader.LoadAllPlayData(true); + return; + IL_00b1:; } - Log.Warning("Caught exception while loading play data but there are active mods other than Core. Resetting mods config and trying again.\nThe exception was: " + arg); - try + finally { - PlayDataLoader.ClearAllPlayData(); + DeepProfiler.End(); } - catch + PlayDataLoader.loadedInt = true; + if (recovering) { - Log.Warning("Caught exception while recovering from errors and trying to clear all play data. Ignoring it.\nThe exception was: " + arg); + Log.Message("Successfully recovered from errors and loaded play data."); + DelayedErrorWindowRequest.Add("RecoveredFromErrorsText".Translate(), "RecoveredFromErrorsDialogTitle".Translate()); } - ModsConfig.Reset(); - DirectXmlCrossRefLoader.Clear(); - PlayDataLoader.LoadAllPlayData(true); - return; - } - finally - { - DeepProfiler.End(); - } - PlayDataLoader.loadedInt = true; - if (recovering) - { - Log.Message("Successfully recovered from errors and loaded play data."); - DelayedErrorWindowRequest.Add("RecoveredFromErrorsText".Translate(), "RecoveredFromErrorsDialogTitle".Translate()); } } @@ -98,9 +101,9 @@ private static void DoPlayLoad() DeepProfiler.Start("Copy all Defs from mods to global databases."); try { - foreach (Type current in typeof(Def).AllSubclasses()) + foreach (Type item in typeof(Def).AllSubclasses()) { - GenGeneric.InvokeStaticMethodOnGenericType(typeof(DefDatabase<>), current, "AddAllInMods"); + GenGeneric.InvokeStaticMethodOnGenericType(typeof(DefDatabase<>), item, "AddAllInMods"); } } finally @@ -187,11 +190,11 @@ private static void DoPlayLoad() DeepProfiler.Start("Resolve references."); try { - foreach (Type current2 in typeof(Def).AllSubclasses()) + foreach (Type item2 in typeof(Def).AllSubclasses()) { - if (current2 != typeof(ThingDef)) + if (item2 != typeof(ThingDef)) { - GenGeneric.InvokeStaticMethodOnGenericType(typeof(DefDatabase<>), current2, "ResolveAllReferences"); + GenGeneric.InvokeStaticMethodOnGenericType(typeof(DefDatabase<>), item2, "ResolveAllReferences"); } } DefDatabase.ResolveAllReferences(); @@ -214,9 +217,9 @@ private static void DoPlayLoad() DeepProfiler.Start("Error check all defs."); try { - foreach (Type current3 in typeof(Def).AllSubclasses()) + foreach (Type item3 in typeof(Def).AllSubclasses()) { - GenGeneric.InvokeStaticMethodOnGenericType(typeof(DefDatabase<>), current3, "ErrorCheckAllDefs"); + GenGeneric.InvokeStaticMethodOnGenericType(typeof(DefDatabase<>), item3, "ErrorCheckAllDefs"); } } finally @@ -243,7 +246,7 @@ private static void DoPlayLoad() { DeepProfiler.End(); } - LongEventHandler.ExecuteWhenFinished(delegate + LongEventHandler.ExecuteWhenFinished((Action)delegate { DeepProfiler.Start("Load backstories."); try @@ -255,7 +258,7 @@ private static void DoPlayLoad() DeepProfiler.End(); } }); - LongEventHandler.ExecuteWhenFinished(delegate + LongEventHandler.ExecuteWhenFinished((Action)delegate { DeepProfiler.Start("Inject selected language data into game data."); try @@ -268,7 +271,7 @@ private static void DoPlayLoad() DeepProfiler.End(); } }); - LongEventHandler.ExecuteWhenFinished(delegate + LongEventHandler.ExecuteWhenFinished((Action)delegate { StaticConstructorOnStartupUtility.CallAll(); if (Prefs.DevMode) @@ -282,9 +285,9 @@ public static void ClearAllPlayData() { LanguageDatabase.Clear(); LoadedModManager.ClearDestroy(); - foreach (Type current in typeof(Def).AllSubclasses()) + foreach (Type item in typeof(Def).AllSubclasses()) { - GenGeneric.InvokeStaticMethodOnGenericType(typeof(DefDatabase<>), current, "Clear"); + GenGeneric.InvokeStaticMethodOnGenericType(typeof(DefDatabase<>), item, "Clear"); } ThingCategoryNodeDatabase.Clear(); BackstoryDatabase.Clear(); diff --git a/Assembly-CSharp/Verse/PlayLog.cs b/Assembly-CSharp/Verse/PlayLog.cs index 5ad2a6c9c..186add9aa 100644 --- a/Assembly-CSharp/Verse/PlayLog.cs +++ b/Assembly-CSharp/Verse/PlayLog.cs @@ -1,4 +1,3 @@ -using System; using System.Collections.Generic; namespace Verse @@ -38,19 +37,12 @@ public void ExposeData() public void Notify_PawnDiscarded(Pawn p) { - for (int i = this.entries.Count - 1; i >= 0; i--) + for (int num = this.entries.Count - 1; num >= 0; num--) { - if (this.entries[i].Concerns(p)) + if (this.entries[num].Concerns(p)) { - Log.Warning(string.Concat(new object[] - { - "Discarding pawn ", - p, - ", but he is referenced by a play log entry ", - this.entries[i], - "." - })); - this.RemoveEntry(this.entries[i]); + Log.Warning("Discarding pawn " + p + ", but he is referenced by a play log entry " + this.entries[num] + "."); + this.RemoveEntry(this.entries[num]); } } } diff --git a/Assembly-CSharp/Verse/PlayLogEntry.cs b/Assembly-CSharp/Verse/PlayLogEntry.cs index 53b70f760..f7985f59c 100644 --- a/Assembly-CSharp/Verse/PlayLogEntry.cs +++ b/Assembly-CSharp/Verse/PlayLogEntry.cs @@ -1,5 +1,4 @@ using RimWorld; -using System; using UnityEngine; namespace Verse @@ -43,10 +42,7 @@ public virtual void PostRemove() public virtual string GetTipString() { - return "OccurredTimeAgo".Translate(new object[] - { - this.Age.ToStringTicksToPeriod(true, false, true) - }).CapitalizeFirst() + "."; + return "OccurredTimeAgo".Translate(this.Age.ToStringTicksToPeriod(true, false, true)).CapitalizeFirst() + "."; } } } diff --git a/Assembly-CSharp/Verse/PlayLogEntry_Interaction.cs b/Assembly-CSharp/Verse/PlayLogEntry_Interaction.cs index 3ce3c8b02..5d98796bd 100644 --- a/Assembly-CSharp/Verse/PlayLogEntry_Interaction.cs +++ b/Assembly-CSharp/Verse/PlayLogEntry_Interaction.cs @@ -47,7 +47,7 @@ public PlayLogEntry_Interaction() public PlayLogEntry_Interaction(InteractionDef intDef, Pawn initiator, Pawn recipient, List extraSentencePacks) { - this.ticksAbs = Find.TickManager.TicksAbs; + base.ticksAbs = Find.TickManager.TicksAbs; this.intDef = intDef; this.initiator = initiator; this.recipient = recipient; @@ -63,68 +63,67 @@ public override void ClickedFromPOV(Thing pov) { if (pov == this.initiator) { - CameraJumper.TryJumpAndSelect(this.recipient); + CameraJumper.TryJumpAndSelect((Thing)this.recipient); + return; } - else + if (pov == this.recipient) { - if (pov != this.recipient) - { - throw new NotImplementedException(); - } - CameraJumper.TryJumpAndSelect(this.initiator); + CameraJumper.TryJumpAndSelect((Thing)this.initiator); + return; } + throw new NotImplementedException(); } public override string ToGameStringFromPOV(Thing pov) { - if (this.initiator == null || this.recipient == null) - { - Log.ErrorOnce("PlayLogEntry_Interaction has a null pawn reference.", 34422); - return "[" + this.intDef.label + " error: null pawn reference]"; - } - Rand.PushState(); - Rand.Seed = this.ticksAbs * 61261; - List list = new List(); - string text; - if (pov == this.initiator) - { - list.AddRange(this.intDef.logRulesInitiator.Rules); - list.AddRange(GrammarUtility.RulesForPawn("me", this.initiator.Name, this.initiator.kindDef, this.initiator.gender, this.initiator.Faction)); - list.AddRange(GrammarUtility.RulesForPawn("other", this.recipient.Name, this.recipient.kindDef, this.recipient.gender, this.recipient.Faction)); - text = GrammarResolver.Resolve("logentry", list, "interaction from initiator"); - } - else if (pov == this.recipient) + if (this.initiator != null && this.recipient != null) { - if (this.intDef.logRulesRecipient != null) + Rand.PushState(); + Rand.Seed = base.ticksAbs * 61261; + List list = new List(); + string text; + if (pov == this.initiator) + { + list.AddRange(this.intDef.logRulesInitiator.Rules); + list.AddRange(GrammarUtility.RulesForPawn("me", this.initiator.Name, this.initiator.kindDef, this.initiator.gender, this.initiator.Faction)); + list.AddRange(GrammarUtility.RulesForPawn("other", this.recipient.Name, this.recipient.kindDef, this.recipient.gender, this.recipient.Faction)); + text = GrammarResolver.Resolve("logentry", list, "interaction from initiator"); + } + else if (pov == this.recipient) { - list.AddRange(this.intDef.logRulesRecipient.Rules); + if (this.intDef.logRulesRecipient != null) + { + list.AddRange(this.intDef.logRulesRecipient.Rules); + } + else + { + list.AddRange(this.intDef.logRulesInitiator.Rules); + } + list.AddRange(GrammarUtility.RulesForPawn("me", this.recipient.Name, this.recipient.kindDef, this.recipient.gender, this.recipient.Faction)); + list.AddRange(GrammarUtility.RulesForPawn("other", this.initiator.Name, this.initiator.kindDef, this.initiator.gender, this.initiator.Faction)); + text = GrammarResolver.Resolve("logentry", list, "interaction from recipient"); } else { - list.AddRange(this.intDef.logRulesInitiator.Rules); + Log.ErrorOnce("Cannot display PlayLogEntry_Interaction from POV who isn't initiator or recipient.", 51251); + text = this.ToString(); } - list.AddRange(GrammarUtility.RulesForPawn("me", this.recipient.Name, this.recipient.kindDef, this.recipient.gender, this.recipient.Faction)); - list.AddRange(GrammarUtility.RulesForPawn("other", this.initiator.Name, this.initiator.kindDef, this.initiator.gender, this.initiator.Faction)); - text = GrammarResolver.Resolve("logentry", list, "interaction from recipient"); - } - else - { - Log.ErrorOnce("Cannot display PlayLogEntry_Interaction from POV who isn't initiator or recipient.", 51251); - text = this.ToString(); - } - if (this.extraSentencePacks != null) - { - for (int i = 0; i < this.extraSentencePacks.Count; i++) + if (this.extraSentencePacks != null) { - list.Clear(); - list.AddRange(this.extraSentencePacks[i].Rules); - list.AddRange(GrammarUtility.RulesForPawn("initiator", this.initiator.Name, this.initiator.kindDef, this.initiator.gender, this.initiator.Faction)); - list.AddRange(GrammarUtility.RulesForPawn("recipient", this.recipient.Name, this.recipient.kindDef, this.recipient.gender, this.recipient.Faction)); - text = text + " " + GrammarResolver.Resolve(this.extraSentencePacks[i].Rules[0].keyword, list, "extraSentencePack"); + for (int i = 0; i < this.extraSentencePacks.Count; i++) + { + list.Clear(); + list.AddRange(this.extraSentencePacks[i].Rules); + list.AddRange(GrammarUtility.RulesForPawn("initiator", this.initiator.Name, this.initiator.kindDef, this.initiator.gender, this.initiator.Faction)); + list.AddRange(GrammarUtility.RulesForPawn("recipient", this.recipient.Name, this.recipient.kindDef, this.recipient.gender, this.recipient.Faction)); + text = text + " " + GrammarResolver.Resolve(this.extraSentencePacks[i].Rules[0].keyword, list, "extraSentencePack"); + } } + Rand.PopState(); + return text; } - Rand.PopState(); - return text; + Log.ErrorOnce("PlayLogEntry_Interaction has a null pawn reference.", 34422); + return "[" + this.intDef.label + " error: null pawn reference]"; } public override void PostRemove() @@ -152,14 +151,7 @@ public override void ExposeData() public override string ToString() { - return string.Concat(new string[] - { - this.intDef.label, - ": ", - this.InitiatorName, - "->", - this.RecipientName - }); + return this.intDef.label + ": " + this.InitiatorName + "->" + this.RecipientName; } } } diff --git a/Assembly-CSharp/Verse/PostLoadIniter.cs b/Assembly-CSharp/Verse/PostLoadIniter.cs index d65be3773..a58850866 100644 --- a/Assembly-CSharp/Verse/PostLoadIniter.cs +++ b/Assembly-CSharp/Verse/PostLoadIniter.cs @@ -11,47 +11,50 @@ public void RegisterForPostLoadInit(IExposable s) { if (Scribe.mode != LoadSaveMode.LoadingVars) { - Log.Error(string.Concat(new object[] - { - "Registered ", - s, - " for post load init, but current mode is ", - Scribe.mode - })); - return; + Log.Error("Registered " + s + " for post load init, but current mode is " + Scribe.mode); } - if (s == null) + else if (s == null) { Log.Warning("Trying to register null in RegisterforPostLoadInit."); - return; } - if (this.saveablesToPostLoad.Contains(s)) + else if (this.saveablesToPostLoad.Contains(s)) { Log.Warning("Tried to register in RegisterforPostLoadInit when already registered: " + s); - return; } - this.saveablesToPostLoad.Add(s); + else + { + this.saveablesToPostLoad.Add(s); + } } public void DoAllPostLoadInits() { Scribe.mode = LoadSaveMode.PostLoadInit; - foreach (IExposable current in this.saveablesToPostLoad) + HashSet.Enumerator enumerator = this.saveablesToPostLoad.GetEnumerator(); + try { - try + while (enumerator.MoveNext()) { - Scribe.loader.curParent = current; - Scribe.loader.curPathRelToParent = null; - current.ExposeData(); - } - catch (Exception arg) - { - Log.Error("Could not do PostLoadInit: " + arg); + IExposable current = enumerator.Current; + try + { + Scribe.loader.curParent = current; + Scribe.loader.curPathRelToParent = (string)null; + current.ExposeData(); + } + catch (Exception arg) + { + Log.Error("Could not do PostLoadInit: " + arg); + } } } + finally + { + ((IDisposable)(object)enumerator).Dispose(); + } this.Clear(); Scribe.loader.curParent = null; - Scribe.loader.curPathRelToParent = null; + Scribe.loader.curPathRelToParent = (string)null; Scribe.mode = LoadSaveMode.Inactive; } diff --git a/Assembly-CSharp/Verse/PreLoadUtility.cs b/Assembly-CSharp/Verse/PreLoadUtility.cs index ed94f076d..d9d901657 100644 --- a/Assembly-CSharp/Verse/PreLoadUtility.cs +++ b/Assembly-CSharp/Verse/PreLoadUtility.cs @@ -6,6 +6,7 @@ public static class PreLoadUtility { public static void CheckVersionAndLoad(string path, ScribeMetaHeaderUtility.ScribeHeaderMode mode, Action loadAct) { + bool flag = false; Scribe.loader.InitLoadingMetaHeaderOnly(path); try { @@ -14,13 +15,7 @@ public static void CheckVersionAndLoad(string path, ScribeMetaHeaderUtility.Scri } catch (Exception ex) { - Log.Warning(string.Concat(new object[] - { - "Exception loading ", - path, - ": ", - ex - })); + Log.Warning("Exception loading " + path + ": " + ex); Scribe.ForceStop(); } if (!ScribeMetaHeaderUtility.TryCreateDialogsForVersionMismatchWarnings(loadAct)) diff --git a/Assembly-CSharp/Verse/Prefs.cs b/Assembly-CSharp/Verse/Prefs.cs index 5dc02e5dd..99f579fc6 100644 --- a/Assembly-CSharp/Verse/Prefs.cs +++ b/Assembly-CSharp/Verse/Prefs.cs @@ -131,7 +131,11 @@ public static bool DevMode { get { - return Prefs.data == null || Prefs.data.devMode; + if (Prefs.data == null) + { + return true; + } + return Prefs.data.devMode; } set { @@ -277,12 +281,11 @@ public static bool ResourceReadoutCategorized } set { - if (value == Prefs.data.resourceReadoutCategorized) + if (value != Prefs.data.resourceReadoutCategorized) { - return; + Prefs.data.resourceReadoutCategorized = value; + Prefs.Save(); } - Prefs.data.resourceReadoutCategorized = value; - Prefs.Save(); } } @@ -333,11 +336,7 @@ public static void Save() } catch (Exception ex) { - GenUI.ErrorDialog("ProblemSavingFile".Translate(new object[] - { - GenFilePaths.PrefsFilePath, - ex.ToString() - })); + GenUI.ErrorDialog("ProblemSavingFile".Translate(GenFilePaths.PrefsFilePath, ex.ToString())); Log.Error("Exception saving prefs: " + ex); } } @@ -349,10 +348,10 @@ public static void Apply() public static NameTriple RandomPreferredName() { - string rawName; + string rawName = default(string); if ((from name in Prefs.PreferredNames where !name.NullOrEmpty() - select name).TryRandomElement(out rawName)) + select name).TryRandomElement(out rawName)) { return NameTriple.FromString(rawName); } diff --git a/Assembly-CSharp/Verse/PrefsData.cs b/Assembly-CSharp/Verse/PrefsData.cs index a4881e215..d1009fde1 100644 --- a/Assembly-CSharp/Verse/PrefsData.cs +++ b/Assembly-CSharp/Verse/PrefsData.cs @@ -1,4 +1,3 @@ -using System; using System.Collections.Generic; using UnityEngine; diff --git a/Assembly-CSharp/Verse/Printer_Mesh.cs b/Assembly-CSharp/Verse/Printer_Mesh.cs index c00d826c2..bffdeeb7e 100644 --- a/Assembly-CSharp/Verse/Printer_Mesh.cs +++ b/Assembly-CSharp/Verse/Printer_Mesh.cs @@ -1,4 +1,3 @@ -using System; using UnityEngine; namespace Verse @@ -13,20 +12,20 @@ public static void PrintMesh(SectionLayer layer, Vector3 center, Mesh mesh, Mate Vector3[] vertices = mesh.vertices; Color32[] colors = mesh.colors32; Vector2[] uv = mesh.uv; - for (int i = 0; i < vertexCount; i++) + for (int num = 0; num < vertexCount; num++) { - subMesh.verts.Add(vertices[i] + center); - if (colors.Length > i) + subMesh.verts.Add(vertices[num] + center); + if (colors.Length > num) { - subMesh.colors.Add(colors[i]); + subMesh.colors.Add(colors[num]); } else { - subMesh.colors.Add(new Color32(255, 255, 255, 255)); + subMesh.colors.Add(new Color32((byte)255, (byte)255, (byte)255, (byte)255)); } - if (uv.Length > i) + if (uv.Length > num) { - subMesh.uvs.Add(uv[i]); + subMesh.uvs.Add(uv[num]); } else { @@ -34,10 +33,10 @@ public static void PrintMesh(SectionLayer layer, Vector3 center, Mesh mesh, Mate } } int[] triangles = mesh.triangles; - for (int j = 0; j < triangles.Length; j++) + for (int i = 0; i < triangles.Length; i++) { - int num = triangles[j]; - subMesh.tris.Add(count + num); + int num2 = triangles[i]; + subMesh.tris.Add(count + num2); } } } diff --git a/Assembly-CSharp/Verse/Printer_Plane.cs b/Assembly-CSharp/Verse/Printer_Plane.cs index caa32db9b..e726aa653 100644 --- a/Assembly-CSharp/Verse/Printer_Plane.cs +++ b/Assembly-CSharp/Verse/Printer_Plane.cs @@ -1,4 +1,3 @@ -using System; using System.Collections.Generic; using UnityEngine; @@ -6,15 +5,15 @@ namespace Verse { public static class Printer_Plane { - private static Color32[] defaultColors = new Color32[] + private static Color32[] defaultColors = new Color32[4] { - new Color32(255, 255, 255, 255), - new Color32(255, 255, 255, 255), - new Color32(255, 255, 255, 255), - new Color32(255, 255, 255, 255) + new Color32((byte)255, (byte)255, (byte)255, (byte)255), + new Color32((byte)255, (byte)255, (byte)255, (byte)255), + new Color32((byte)255, (byte)255, (byte)255, (byte)255), + new Color32((byte)255, (byte)255, (byte)255, (byte)255) }; - private static Vector2[] defaultUvs = new Vector2[] + private static Vector2[] defaultUvs = new Vector2[4] { new Vector2(0f, 0f), new Vector2(0f, 1f), @@ -22,7 +21,7 @@ public static class Printer_Plane new Vector2(1f, 0f) }; - private static Vector2[] defaultUvsFlipped = new Vector2[] + private static Vector2[] defaultUvsFlipped = new Vector2[4] { new Vector2(1f, 0f), new Vector2(1f, 1f), @@ -30,7 +29,7 @@ public static class Printer_Plane new Vector2(0f, 0f) }; - public static void PrintPlane(SectionLayer layer, Vector3 center, Vector2 size, Material mat, float rot = 0f, bool flipUv = false, Vector2[] uvs = null, Color32[] colors = null, float topVerticesAltitudeBias = 0.01f) + public static void PrintPlane(SectionLayer layer, Vector3 center, Vector2 size, Material mat, float rot = 0, bool flipUv = false, Vector2[] uvs = null, Color32[] colors = null, float topVerticesAltitudeBias = 0.01f) { if (colors == null) { @@ -38,44 +37,43 @@ public static void PrintPlane(SectionLayer layer, Vector3 center, Vector2 size, } if (uvs == null) { - if (!flipUv) - { - uvs = Printer_Plane.defaultUvs; - } - else - { - uvs = Printer_Plane.defaultUvsFlipped; - } + uvs = (flipUv ? Printer_Plane.defaultUvsFlipped : Printer_Plane.defaultUvs); } LayerSubMesh subMesh = layer.GetSubMesh(mat); int count = subMesh.verts.Count; - subMesh.verts.Add(new Vector3(-0.5f * size.x, 0f, -0.5f * size.y)); - subMesh.verts.Add(new Vector3(-0.5f * size.x, topVerticesAltitudeBias, 0.5f * size.y)); - subMesh.verts.Add(new Vector3(0.5f * size.x, topVerticesAltitudeBias, 0.5f * size.y)); - subMesh.verts.Add(new Vector3(0.5f * size.x, 0f, -0.5f * size.y)); - if (rot != 0f) + subMesh.verts.Add(new Vector3((float)(-0.5 * size.x), 0f, (float)(-0.5 * size.y))); + subMesh.verts.Add(new Vector3((float)(-0.5 * size.x), topVerticesAltitudeBias, (float)(0.5 * size.y))); + subMesh.verts.Add(new Vector3((float)(0.5 * size.x), topVerticesAltitudeBias, (float)(0.5 * size.y))); + subMesh.verts.Add(new Vector3((float)(0.5 * size.x), 0f, (float)(-0.5 * size.y))); + if (rot != 0.0) { - float num = rot * 0.0174532924f; - num *= -1f; + float num = (float)(rot * 0.01745329238474369); + num = (float)(num * -1.0); for (int i = 0; i < 4; i++) { - float x = subMesh.verts[count + i].x; - float z = subMesh.verts[count + i].z; + Vector3 vector = subMesh.verts[count + i]; + float x = vector.x; + Vector3 vector2 = subMesh.verts[count + i]; + float z = vector2.z; float num2 = Mathf.Cos(num); float num3 = Mathf.Sin(num); - float x2 = x * num2 - z * num3; + float num4 = x * num2 - z * num3; float z2 = x * num3 + z * num2; - subMesh.verts[count + i] = new Vector3(x2, subMesh.verts[count + i].y, z2); + List verts = subMesh.verts; + int index = count + i; + float x2 = num4; + Vector3 vector3 = subMesh.verts[count + i]; + verts[index] = new Vector3(x2, vector3.y, z2); } } for (int j = 0; j < 4; j++) { - List verts; - List expr_1C0 = verts = subMesh.verts; - int index; - int expr_1C7 = index = count + j; - Vector3 a = verts[index]; - expr_1C0[expr_1C7] = a + center; + List verts2; + List obj = verts2 = subMesh.verts; + int index2; + int index3 = index2 = count + j; + Vector3 a = verts2[index2]; + obj[index3] = a + center; subMesh.uvs.Add(uvs[j]); subMesh.colors.Add(colors[j]); } diff --git a/Assembly-CSharp/Verse/Printer_Shadow.cs b/Assembly-CSharp/Verse/Printer_Shadow.cs index dca793615..562a6f2fc 100644 --- a/Assembly-CSharp/Verse/Printer_Shadow.cs +++ b/Assembly-CSharp/Verse/Printer_Shadow.cs @@ -1,16 +1,15 @@ -using System; using UnityEngine; namespace Verse { public static class Printer_Shadow { - private static readonly Color32 LowVertexColor = new Color32(0, 0, 0, 0); + private static readonly Color32 LowVertexColor = new Color32((byte)0, (byte)0, (byte)0, (byte)0); public static void PrintShadow(SectionLayer layer, Vector3 center, ShadowData shadow, Rot4 rotation) { LayerSubMesh subMesh = layer.GetSubMesh(MatBases.SunShadowFade); - Color32 item = new Color32(255, 0, 0, (byte)(255f * shadow.BaseY)); + Color32 item = new Color32((byte)255, (byte)0, (byte)0, (byte)(255.0 * shadow.BaseY)); Vector3 vector = shadow.volume.RotatedBy(rotation) / 2f; float x = center.x; float z = center.z; diff --git a/Assembly-CSharp/Verse/PriorityWork.cs b/Assembly-CSharp/Verse/PriorityWork.cs index 21a3e217a..147974310 100644 --- a/Assembly-CSharp/Verse/PriorityWork.cs +++ b/Assembly-CSharp/Verse/PriorityWork.cs @@ -1,6 +1,7 @@ +using RimWorld; using System; using System.Collections.Generic; -using System.Diagnostics; +using Verse.AI; namespace Verse { @@ -93,14 +94,30 @@ public void DrawExtraSelectionOverlays() } } - [DebuggerHidden] public IEnumerable GetGizmos() { - PriorityWork.c__Iterator1C0 c__Iterator1C = new PriorityWork.c__Iterator1C0(); - c__Iterator1C.<>f__this = this; - PriorityWork.c__Iterator1C0 expr_0E = c__Iterator1C; - expr_0E.$PC = -2; - return expr_0E; + if (!this.IsPrioritized && (this.pawn.CurJob == null || !this.pawn.CurJob.playerForced) && !this.pawn.jobs.jobQueue.AnyPlayerForced) + yield break; + if (!this.pawn.Drafted) + { + yield return (Gizmo)new Command_Action + { + defaultLabel = "CommandClearPrioritizedWork".Translate(), + defaultDesc = "CommandClearPrioritizedWorkDesc".Translate(), + icon = TexCommand.ClearPrioritizedWork, + activateSound = SoundDefOf.TickLow, + action = (Action)delegate + { + ((_003CGetGizmos_003Ec__Iterator1C0)/*Error near IL_00ef: stateMachine*/)._003C_003Ef__this.ClearPrioritizedWorkAndJobQueue(); + if (((_003CGetGizmos_003Ec__Iterator1C0)/*Error near IL_00ef: stateMachine*/)._003C_003Ef__this.pawn.CurJob.playerForced) + { + ((_003CGetGizmos_003Ec__Iterator1C0)/*Error near IL_00ef: stateMachine*/)._003C_003Ef__this.pawn.jobs.EndCurrentJob(JobCondition.InterruptForced, true); + } + }, + hotKey = KeyBindingDefOf.DesignatorCancel, + groupKey = 6165612 + }; + } } } } diff --git a/Assembly-CSharp/Verse/ProfilerThreadCheck.cs b/Assembly-CSharp/Verse/ProfilerThreadCheck.cs index 27624e8b0..5d19ae708 100644 --- a/Assembly-CSharp/Verse/ProfilerThreadCheck.cs +++ b/Assembly-CSharp/Verse/ProfilerThreadCheck.cs @@ -1,21 +1,17 @@ -using System; - namespace Verse { public static class ProfilerThreadCheck { public static void BeginSample(string name) { - if (UnityData.IsInMainThread) - { - } + if (!UnityData.IsInMainThread) + return; } public static void EndSample() { - if (UnityData.IsInMainThread) - { - } + if (!UnityData.IsInMainThread) + return; } } } diff --git a/Assembly-CSharp/Verse/ProgramState.cs b/Assembly-CSharp/Verse/ProgramState.cs index e13b1b252..25d0ea12f 100644 --- a/Assembly-CSharp/Verse/ProgramState.cs +++ b/Assembly-CSharp/Verse/ProgramState.cs @@ -1,11 +1,9 @@ -using System; - namespace Verse { public enum ProgramState : byte { - Entry, - MapInitializing, - Playing + Entry = 0, + MapInitializing = 1, + Playing = 2 } } diff --git a/Assembly-CSharp/Verse/Projectile.cs b/Assembly-CSharp/Verse/Projectile.cs index d0669034e..d97b3e130 100644 --- a/Assembly-CSharp/Verse/Projectile.cs +++ b/Assembly-CSharp/Verse/Projectile.cs @@ -1,5 +1,4 @@ using RimWorld; -using System; using System.Collections.Generic; using UnityEngine; using Verse.Sound; @@ -56,24 +55,33 @@ public bool InterceptWalls { get { - return this.def.projectile.alwaysFreeIntercept || (!this.def.projectile.flyOverhead && this.interceptWallsInt); + if (base.def.projectile.alwaysFreeIntercept) + { + return true; + } + if (base.def.projectile.flyOverhead) + { + return false; + } + return this.interceptWallsInt; } set { - if (!value && this.def.projectile.alwaysFreeIntercept) + if (!value && base.def.projectile.alwaysFreeIntercept) { Log.Error("Tried to set interceptWalls to false on projectile with alwaysFreeIntercept=true"); - return; } - if (value && this.def.projectile.flyOverhead) + else if (value && base.def.projectile.flyOverhead) { Log.Error("Tried to set interceptWalls to true on a projectile with flyOverhead=true"); - return; } - this.interceptWallsInt = value; - if (!this.interceptWallsInt && this is Projectile_Explosive) + else { - Log.Message("Non interceptWallsInt explosive."); + this.interceptWallsInt = value; + if (!this.interceptWallsInt && this is Projectile_Explosive) + { + Log.Message("Non interceptWallsInt explosive."); + } } } } @@ -82,21 +90,30 @@ public bool FreeIntercept { get { - return this.def.projectile.alwaysFreeIntercept || (!this.def.projectile.flyOverhead && this.freeInterceptInt); + if (base.def.projectile.alwaysFreeIntercept) + { + return true; + } + if (base.def.projectile.flyOverhead) + { + return false; + } + return this.freeInterceptInt; } set { - if (!value && this.def.projectile.alwaysFreeIntercept) + if (!value && base.def.projectile.alwaysFreeIntercept) { Log.Error("Tried to set FreeIntercept to false on projectile with alwaysFreeIntercept=true"); - return; } - if (value && this.def.projectile.flyOverhead) + else if (value && base.def.projectile.flyOverhead) { Log.Error("Tried to set FreeIntercept to true on a projectile with flyOverhead=true"); - return; } - this.freeInterceptInt = value; + else + { + this.freeInterceptInt = value; + } } } @@ -108,11 +125,10 @@ public Thing ThingToNeverIntercept } set { - if (value.def.Fillage == FillCategory.Full) + if (value.def.Fillage != FillCategory.Full) { - return; + this.neverInterceptTargetInt = value; } - this.neverInterceptTargetInt = value; } } @@ -120,7 +136,7 @@ protected int StartingTicksToImpact { get { - int num = Mathf.RoundToInt((this.origin - this.destination).magnitude / (this.def.projectile.speed / 100f)); + int num = Mathf.RoundToInt((float)((this.origin - this.destination).magnitude / (base.def.projectile.speed / 100.0))); if (num < 1) { num = 1; @@ -141,8 +157,8 @@ public virtual Vector3 ExactPosition { get { - Vector3 b = (this.destination - this.origin) * (1f - (float)this.ticksToImpact / (float)this.StartingTicksToImpact); - return this.origin + b + Vector3.up * this.def.Altitude; + Vector3 b = (this.destination - this.origin) * (float)(1.0 - (float)this.ticksToImpact / (float)this.StartingTicksToImpact); + return this.origin + b + Vector3.up * base.def.Altitude; } } @@ -200,51 +216,50 @@ public void Launch(Thing launcher, Vector3 origin, LocalTargetInfo targ, Thing e } this.destination = targ.Cell.ToVector3Shifted() + new Vector3(Rand.Range(-0.3f, 0.3f), 0f, Rand.Range(-0.3f, 0.3f)); this.ticksToImpact = this.StartingTicksToImpact; - if (!this.def.projectile.soundAmbient.NullOrUndefined()) + if (!base.def.projectile.soundAmbient.NullOrUndefined()) { - SoundInfo info = SoundInfo.InMap(this, MaintenanceType.PerTick); - this.ambientSustainer = this.def.projectile.soundAmbient.TrySpawnSustainer(info); + SoundInfo info = SoundInfo.InMap((Thing)this, MaintenanceType.PerTick); + this.ambientSustainer = base.def.projectile.soundAmbient.TrySpawnSustainer(info); } } public override void Tick() { base.Tick(); - if (this.landed) - { - return; - } - Vector3 exactPosition = this.ExactPosition; - this.ticksToImpact--; - if (!this.ExactPosition.InBounds(base.Map)) - { - this.ticksToImpact++; - base.Position = this.ExactPosition.ToIntVec3(); - this.Destroy(DestroyMode.Vanish); - return; - } - Vector3 exactPosition2 = this.ExactPosition; - if (this.CheckForFreeInterceptBetween(exactPosition, exactPosition2)) + if (!this.landed) { - return; - } - base.Position = this.ExactPosition.ToIntVec3(); - if (this.ticksToImpact == 60 && Find.TickManager.CurTimeSpeed == TimeSpeed.Normal && this.def.projectile.soundImpactAnticipate != null) - { - this.def.projectile.soundImpactAnticipate.PlayOneShot(this); - } - if (this.ticksToImpact <= 0) - { - if (this.DestinationCell.InBounds(base.Map)) + Vector3 exactPosition = this.ExactPosition; + this.ticksToImpact--; + if (!this.ExactPosition.InBounds(base.Map)) { - base.Position = this.DestinationCell; + this.ticksToImpact++; + base.Position = this.ExactPosition.ToIntVec3(); + this.Destroy(DestroyMode.Vanish); + } + else + { + Vector3 exactPosition2 = this.ExactPosition; + if (!this.CheckForFreeInterceptBetween(exactPosition, exactPosition2)) + { + base.Position = this.ExactPosition.ToIntVec3(); + if (this.ticksToImpact == 60 && Find.TickManager.CurTimeSpeed == TimeSpeed.Normal && base.def.projectile.soundImpactAnticipate != null) + { + base.def.projectile.soundImpactAnticipate.PlayOneShot((Thing)this); + } + if (this.ticksToImpact <= 0) + { + if (this.DestinationCell.InBounds(base.Map)) + { + base.Position = this.DestinationCell; + } + this.ImpactSomething(); + } + else if (this.ambientSustainer != null) + { + this.ambientSustainer.Maintain(); + } + } } - this.ImpactSomething(); - return; - } - if (this.ambientSustainer != null) - { - this.ambientSustainer.Maintain(); } } @@ -256,65 +271,63 @@ private bool CheckForFreeInterceptBetween(Vector3 lastExactPos, Vector3 newExact { return false; } - if (!intVec.InBounds(base.Map) || !intVec2.InBounds(base.Map)) - { - return false; - } - if (intVec2.AdjacentToCardinal(intVec)) + if (intVec.InBounds(base.Map) && intVec2.InBounds(base.Map)) { - bool flag = this.CheckForFreeIntercept(intVec2); - if (DebugViewSettings.drawInterceptChecks) + if (intVec2.AdjacentToCardinal(intVec)) { - if (flag) - { - MoteMaker.ThrowText(intVec2.ToVector3Shifted(), base.Map, "x", -1f); - } - else + bool flag = this.CheckForFreeIntercept(intVec2); + if (DebugViewSettings.drawInterceptChecks) { - MoteMaker.ThrowText(intVec2.ToVector3Shifted(), base.Map, "o", -1f); + if (flag) + { + MoteMaker.ThrowText(intVec2.ToVector3Shifted(), base.Map, "x", -1f); + } + else + { + MoteMaker.ThrowText(intVec2.ToVector3Shifted(), base.Map, "o", -1f); + } } + return flag; } - return flag; - } - if ((float)this.origin.ToIntVec3().DistanceToSquared(intVec2) > 16f) - { - Vector3 vector = lastExactPos; - Vector3 v = newExactPos - lastExactPos; - Vector3 b = v.normalized * 0.2f; - int num = (int)(v.MagnitudeHorizontal() / 0.2f); - Projectile.checkedCells.Clear(); - int num2 = 0; - while (true) + if ((float)this.origin.ToIntVec3().DistanceToSquared(intVec2) > 16.0) { - vector += b; - IntVec3 intVec3 = vector.ToIntVec3(); - if (!Projectile.checkedCells.Contains(intVec3)) + Vector3 vector = lastExactPos; + Vector3 v = newExactPos - lastExactPos; + Vector3 b = v.normalized * 0.2f; + int num = (int)(v.MagnitudeHorizontal() / 0.20000000298023224); + Projectile.checkedCells.Clear(); + int num2 = 0; + while (true) { - if (this.CheckForFreeIntercept(intVec3)) + vector += b; + IntVec3 intVec3 = vector.ToIntVec3(); + if (!Projectile.checkedCells.Contains(intVec3)) { - break; + if (this.CheckForFreeIntercept(intVec3)) + { + if (DebugViewSettings.drawInterceptChecks) + { + MoteMaker.ThrowText(vector, base.Map, "x", -1f); + } + return true; + } + Projectile.checkedCells.Add(intVec3); } - Projectile.checkedCells.Add(intVec3); - } - if (DebugViewSettings.drawInterceptChecks) - { - MoteMaker.ThrowText(vector, base.Map, "o", -1f); - } - num2++; - if (num2 > num) - { - return false; - } - if (intVec3 == intVec2) - { - return false; + if (DebugViewSettings.drawInterceptChecks) + { + MoteMaker.ThrowText(vector, base.Map, "o", -1f); + } + num2++; + if (num2 > num) + { + return false; + } + if (intVec3 == intVec2) + break; } + return false; } - if (DebugViewSettings.drawInterceptChecks) - { - MoteMaker.ThrowText(vector, base.Map, "x", -1f); - } - return true; + return false; } return false; } @@ -322,7 +335,7 @@ private bool CheckForFreeInterceptBetween(Vector3 lastExactPos, Vector3 newExact private bool CheckForFreeIntercept(IntVec3 c) { float num = (c.ToVector3Shifted() - this.origin).MagnitudeHorizontalSquared(); - if (num < 16f) + if (num < 16.0) { return false; } @@ -330,55 +343,52 @@ private bool CheckForFreeIntercept(IntVec3 c) for (int i = 0; i < list.Count; i++) { Thing thing = list[i]; - if (thing != this.ThingToNeverIntercept) + if (thing != this.ThingToNeverIntercept && thing != this.launcher) { - if (thing != this.launcher) + if (thing.def.Fillage == FillCategory.Full && this.InterceptWalls) { - if (thing.def.Fillage == FillCategory.Full && this.InterceptWalls) + this.Impact(thing); + return true; + } + if (this.FreeIntercept) + { + float num2 = 0f; + Pawn pawn = thing as Pawn; + if (pawn != null) { - this.Impact(thing); - return true; + num2 = 0.4f; + if (pawn.GetPosture() != 0) + { + num2 = (float)(num2 * 0.10000000149011612); + } + if (this.launcher != null && pawn.Faction != null && this.launcher.Faction != null && !pawn.Faction.HostileTo(this.launcher.Faction)) + { + num2 = (float)(num2 * 0.40000000596046448); + } + num2 *= Mathf.Clamp(pawn.BodySize, 0.1f, 2f); + } + else if (thing.def.fillPercent > 0.20000000298023224) + { + num2 = (float)(thing.def.fillPercent * 0.070000000298023224); } - if (this.FreeIntercept) + if (num2 > 9.9999997473787516E-06) { - float num2 = 0f; - Pawn pawn = thing as Pawn; - if (pawn != null) + if (num < 49.0) { - num2 = 0.4f; - if (pawn.GetPosture() != PawnPosture.Standing) - { - num2 *= 0.1f; - } - if (this.launcher != null && pawn.Faction != null && this.launcher.Faction != null && !pawn.Faction.HostileTo(this.launcher.Faction)) - { - num2 *= 0.4f; - } - num2 *= Mathf.Clamp(pawn.BodySize, 0.1f, 2f); + num2 = (float)(num2 * 0.5); } - else if (thing.def.fillPercent > 0.2f) + else if (num < 100.0) { - num2 = thing.def.fillPercent * 0.07f; + num2 = (float)(num2 * 0.75); } - if (num2 > 1E-05f) + if (DebugViewSettings.drawShooting) { - if (num < 49f) - { - num2 *= 0.5f; - } - else if (num < 100f) - { - num2 *= 0.75f; - } - if (DebugViewSettings.drawShooting) - { - MoteMaker.ThrowText(this.ExactPosition, base.Map, num2.ToStringPercent(), -1f); - } - if (Rand.Value < num2) - { - this.Impact(thing); - return true; - } + MoteMaker.ThrowText(this.ExactPosition, base.Map, num2.ToStringPercent(), -1f); + } + if (Rand.Value < num2) + { + this.Impact(thing); + return true; } } } @@ -389,20 +399,20 @@ private bool CheckForFreeIntercept(IntVec3 c) public override void Draw() { - Graphics.DrawMesh(MeshPool.plane10, this.DrawPos, this.ExactRotation, this.def.DrawMatSingle, 0); + Graphics.DrawMesh(MeshPool.plane10, this.DrawPos, this.ExactRotation, base.def.DrawMatSingle, 0); base.Comps_PostDraw(); } private void ImpactSomething() { - if (this.def.projectile.flyOverhead) + if (base.def.projectile.flyOverhead) { RoofDef roofDef = base.Map.roofGrid.RoofAt(base.Position); if (roofDef != null) { if (roofDef.isThickRoof) { - this.def.projectile.soundHitThickRoof.PlayOneShot(new TargetInfo(base.Position, base.Map, false)); + base.def.projectile.soundHitThickRoof.PlayOneShot(new TargetInfo(base.Position, base.Map, false)); this.Destroy(DestroyMode.Vanish); return; } @@ -412,7 +422,19 @@ private void ImpactSomething() } } } - if (this.assignedTarget == null) + if (this.assignedTarget != null) + { + Pawn pawn = this.assignedTarget as Pawn; + if (pawn != null && pawn.GetPosture() != 0 && (this.origin - this.destination).MagnitudeHorizontalSquared() >= 20.25 && Rand.Value > 0.20000000298023224) + { + this.Impact(null); + } + else + { + this.Impact(this.assignedTarget); + } + } + else { Projectile.cellThingsFiltered.Clear(); List thingList = base.Position.GetThingList(base.Map); @@ -424,26 +446,18 @@ private void ImpactSomething() Projectile.cellThingsFiltered.Add(thing); } } - Projectile.cellThingsFiltered.Shuffle(); + Projectile.cellThingsFiltered.Shuffle(); for (int j = 0; j < Projectile.cellThingsFiltered.Count; j++) { Thing t = Projectile.cellThingsFiltered[j]; if (Rand.Value < Projectile.ImpactSomethingHitThingChance(t)) { - this.Impact(Projectile.cellThingsFiltered.RandomElement()); + this.Impact(Projectile.cellThingsFiltered.RandomElement()); return; } } this.Impact(null); - return; } - Pawn pawn = this.assignedTarget as Pawn; - if (pawn != null && pawn.GetPosture() != PawnPosture.Standing && (this.origin - this.destination).MagnitudeHorizontalSquared() >= 20.25f && Rand.Value > 0.2f) - { - this.Impact(null); - return; - } - this.Impact(this.assignedTarget); } private static float ImpactSomethingHitThingChance(Thing t) @@ -451,9 +465,9 @@ private static float ImpactSomethingHitThingChance(Thing t) Pawn pawn = t as Pawn; if (pawn != null) { - return pawn.BodySize * 0.5f; + return (float)(pawn.BodySize * 0.5); } - return t.def.fillPercent * 1.5f; + return (float)(t.def.fillPercent * 1.5); } protected virtual void Impact(Thing hitThing) @@ -466,11 +480,13 @@ public void ForceInstantImpact() if (!this.DestinationCell.InBounds(base.Map)) { this.Destroy(DestroyMode.Vanish); - return; } - this.ticksToImpact = 0; - base.Position = this.DestinationCell; - this.ImpactSomething(); + else + { + this.ticksToImpact = 0; + base.Position = this.DestinationCell; + this.ImpactSomething(); + } } } } diff --git a/Assembly-CSharp/Verse/ProjectileProperties.cs b/Assembly-CSharp/Verse/ProjectileProperties.cs index e3ec4fa0a..bfb75a83b 100644 --- a/Assembly-CSharp/Verse/ProjectileProperties.cs +++ b/Assembly-CSharp/Verse/ProjectileProperties.cs @@ -1,6 +1,4 @@ -using System; using System.Collections.Generic; -using System.Diagnostics; namespace Verse { @@ -34,14 +32,12 @@ public class ProjectileProperties public float explosionSpawnChance = 1f; - [DebuggerHidden] public IEnumerable ConfigErrors(ThingDef parent) { - ProjectileProperties.c__Iterator1CA c__Iterator1CA = new ProjectileProperties.c__Iterator1CA(); - c__Iterator1CA.<>f__this = this; - ProjectileProperties.c__Iterator1CA expr_0E = c__Iterator1CA; - expr_0E.$PC = -2; - return expr_0E; + if (this.alwaysFreeIntercept && this.flyOverhead) + { + yield return "alwaysFreeIntercept and flyOverhead are both true"; + } } } } diff --git a/Assembly-CSharp/Verse/Projectile_Explosive.cs b/Assembly-CSharp/Verse/Projectile_Explosive.cs index 1a067600a..9b3d4d6cf 100644 --- a/Assembly-CSharp/Verse/Projectile_Explosive.cs +++ b/Assembly-CSharp/Verse/Projectile_Explosive.cs @@ -1,5 +1,3 @@ -using System; - namespace Verse { public class Projectile_Explosive : Projectile @@ -27,23 +25,25 @@ public override void Tick() protected override void Impact(Thing hitThing) { - if (this.def.projectile.explosionDelay == 0) + if (base.def.projectile.explosionDelay == 0) { this.Explode(); - return; } - this.landed = true; - this.ticksToDetonation = this.def.projectile.explosionDelay; - GenExplosion.NotifyNearbyPawnsOfDangerousExplosive(this, this.def.projectile.damageDef, this.launcher.Faction); + else + { + base.landed = true; + this.ticksToDetonation = base.def.projectile.explosionDelay; + GenExplosion.NotifyNearbyPawnsOfDangerousExplosive(this, base.def.projectile.damageDef, base.launcher.Faction); + } } protected virtual void Explode() { Map map = base.Map; this.Destroy(DestroyMode.Vanish); - ThingDef preExplosionSpawnThingDef = this.def.projectile.preExplosionSpawnThingDef; - float explosionSpawnChance = this.def.projectile.explosionSpawnChance; - GenExplosion.DoExplosion(base.Position, map, this.def.projectile.explosionRadius, this.def.projectile.damageDef, this.launcher, this.def.projectile.soundExplode, this.def, this.equipmentDef, this.def.projectile.postExplosionSpawnThingDef, this.def.projectile.explosionSpawnChance, 1, false, preExplosionSpawnThingDef, explosionSpawnChance, 1); + ThingDef preExplosionSpawnThingDef = base.def.projectile.preExplosionSpawnThingDef; + float explosionSpawnChance = base.def.projectile.explosionSpawnChance; + GenExplosion.DoExplosion(base.Position, map, base.def.projectile.explosionRadius, base.def.projectile.damageDef, base.launcher, base.def.projectile.soundExplode, base.def, base.equipmentDef, base.def.projectile.postExplosionSpawnThingDef, base.def.projectile.explosionSpawnChance, 1, false, preExplosionSpawnThingDef, explosionSpawnChance, 1); } } } diff --git a/Assembly-CSharp/Verse/PsychGlow.cs b/Assembly-CSharp/Verse/PsychGlow.cs index 700bb854a..fdaf8cfbb 100644 --- a/Assembly-CSharp/Verse/PsychGlow.cs +++ b/Assembly-CSharp/Verse/PsychGlow.cs @@ -1,11 +1,9 @@ -using System; - namespace Verse { public enum PsychGlow : byte { - Dark, - Lit, - Overlit + Dark = 0, + Lit = 1, + Overlit = 2 } } diff --git a/Assembly-CSharp/Verse/PsychGlowUtility.cs b/Assembly-CSharp/Verse/PsychGlowUtility.cs index 50ed44938..7bd630427 100644 --- a/Assembly-CSharp/Verse/PsychGlowUtility.cs +++ b/Assembly-CSharp/Verse/PsychGlowUtility.cs @@ -9,14 +9,22 @@ public static string GetLabel(this PsychGlow gl) switch (gl) { case PsychGlow.Dark: + { return "Dark".Translate(); + } case PsychGlow.Lit: + { return "Lit".Translate(); + } case PsychGlow.Overlit: + { return "LitBrightly".Translate(); + } default: + { throw new ArgumentException(); } + } } } } diff --git a/Assembly-CSharp/Verse/Pulser.cs b/Assembly-CSharp/Verse/Pulser.cs index d5d869046..8338af7a4 100644 --- a/Assembly-CSharp/Verse/Pulser.cs +++ b/Assembly-CSharp/Verse/Pulser.cs @@ -1,4 +1,3 @@ -using System; using UnityEngine; namespace Verse @@ -12,10 +11,10 @@ public static float PulseBrightness(float frequency, float amplitude) public static float PulseBrightness(float frequency, float amplitude, float time) { - float num = time * 6.28318548f; + float num = (float)(time * 6.2831854820251465); num *= frequency; - float t = (1f - Mathf.Cos(num)) * 0.5f; - return Mathf.Lerp(1f - amplitude, 1f, t); + float t = (float)((1.0 - Mathf.Cos(num)) * 0.5); + return Mathf.Lerp((float)(1.0 - amplitude), 1f, t); } } } diff --git a/Assembly-CSharp/Verse/QuickStarter.cs b/Assembly-CSharp/Verse/QuickStarter.cs index 587271569..8c0758658 100644 --- a/Assembly-CSharp/Verse/QuickStarter.cs +++ b/Assembly-CSharp/Verse/QuickStarter.cs @@ -1,4 +1,3 @@ -using System; using UnityEngine.SceneManagement; namespace Verse diff --git a/Assembly-CSharp/Verse/RaceProperties.cs b/Assembly-CSharp/Verse/RaceProperties.cs index d902309c8..59c39db3f 100644 --- a/Assembly-CSharp/Verse/RaceProperties.cs +++ b/Assembly-CSharp/Verse/RaceProperties.cs @@ -1,7 +1,6 @@ using RimWorld; using System; using System.Collections.Generic; -using System.Diagnostics; using UnityEngine; namespace Verse @@ -104,7 +103,7 @@ public class RaceProperties public string meatLabel; - public Color meatColor; + public Color meatColor = new ColorInt(141, 56, 52).ToColor; public ThingDef useMeatFrom; @@ -112,7 +111,7 @@ public class RaceProperties public ShadowData specialShadowData; - public IntRange soundCallIntervalRange; + public IntRange soundCallIntervalRange = new IntRange(2000, 4000); public SoundDef soundMeleeHitPawn; @@ -136,7 +135,7 @@ public bool Humanlike { get { - return this.intelligence >= Intelligence.Humanlike; + return (int)this.intelligence >= 2; } } @@ -144,7 +143,7 @@ public bool ToolUser { get { - return this.intelligence >= Intelligence.ToolUser; + return (int)this.intelligence >= 1; } } @@ -171,20 +170,34 @@ public float FoodLevelPercentageWantEat switch (this.ResolvedDietCategory) { case DietCategory.NeverEats: + { return 0.3f; - case DietCategory.Herbivorous: - return 0.45f; - case DietCategory.Dendrovorous: - return 0.45f; - case DietCategory.Ovivorous: - return 0.4f; + } case DietCategory.Omnivorous: + { return 0.3f; + } case DietCategory.Carnivorous: + { return 0.3f; + } + case DietCategory.Ovivorous: + { + return 0.4f; + } + case DietCategory.Herbivorous: + { + return 0.45f; + } + case DietCategory.Dendrovorous: + { + return 0.45f; + } default: + { throw new InvalidOperationException(); } + } } } @@ -202,20 +215,17 @@ public DietCategory ResolvedDietCategory } if (this.Eats(FoodTypeFlags.Meat)) { - if (this.Eats(FoodTypeFlags.VegetableOrFruit) || this.Eats(FoodTypeFlags.Plant)) + if (!this.Eats(FoodTypeFlags.VegetableOrFruit) && !this.Eats(FoodTypeFlags.Plant)) { - return DietCategory.Omnivorous; + return DietCategory.Carnivorous; } - return DietCategory.Carnivorous; + return DietCategory.Omnivorous; } - else + if (this.Eats(FoodTypeFlags.AnimalProduct)) { - if (this.Eats(FoodTypeFlags.AnimalProduct)) - { - return DietCategory.Ovivorous; - } - return DietCategory.Herbivorous; + return DietCategory.Ovivorous; } + return DietCategory.Herbivorous; } } @@ -287,14 +297,6 @@ public TrainableIntelligenceDef TrainableIntelligence } } - public RaceProperties() - { - ColorInt colorInt = new ColorInt(141, 56, 52); - this.meatColor = colorInt.ToColor; - this.soundCallIntervalRange = new IntRange(2000, 4000); - base..ctor(); - } - public RulePackDef GetNameGenerator(Gender gender) { if (gender == Gender.Female && this.nameGeneratorFemale != null) @@ -306,7 +308,15 @@ public RulePackDef GetNameGenerator(Gender gender) public bool WillAutomaticallyEat(Thing t) { - return t.def.ingestible != null && this.CanEverEat(t); + if (t.def.ingestible == null) + { + return false; + } + if (!this.CanEverEat(t)) + { + return false; + } + return true; } public bool CanEverEat(Thing t) @@ -316,12 +326,28 @@ public bool CanEverEat(Thing t) public bool CanEverEat(ThingDef t) { - return this.EatsFood && t.ingestible != null && t.ingestible.preferability != FoodPreferability.Undefined && this.Eats(t.ingestible.foodType); + if (!this.EatsFood) + { + return false; + } + if (t.ingestible == null) + { + return false; + } + if (t.ingestible.preferability == FoodPreferability.Undefined) + { + return false; + } + return this.Eats(t.ingestible.foodType); } public bool Eats(FoodTypeFlags food) { - return this.EatsFood && (this.foodType & food) != FoodTypeFlags.None; + if (!this.EatsFood) + { + return false; + } + return (this.foodType & food) != FoodTypeFlags.None; } public void ResolveReferencesSpecial() @@ -336,26 +362,97 @@ public void ResolveReferencesSpecial() } } - [DebuggerHidden] public IEnumerable ConfigErrors() { - RaceProperties.c__Iterator1CB c__Iterator1CB = new RaceProperties.c__Iterator1CB(); - c__Iterator1CB.<>f__this = this; - RaceProperties.c__Iterator1CB expr_0E = c__Iterator1CB; - expr_0E.$PC = -2; - return expr_0E; + if (this.soundMeleeHitPawn == null) + { + yield return "soundMeleeHitPawn is null"; + } + if (this.soundMeleeHitBuilding == null) + { + yield return "soundMeleeHitBuilding is null"; + } + if (this.soundMeleeMiss == null) + { + yield return "soundMeleeMiss is null"; + } + if (this.predator && !this.Eats(FoodTypeFlags.Meat)) + { + yield return "predator but doesn't eat meat"; + } + for (int j = 0; j < this.lifeStageAges.Count; j++) + { + for (int i = 0; i < j; i++) + { + if (this.lifeStageAges[i].minAge > this.lifeStageAges[j].minAge) + { + yield return "lifeStages minAges are not in ascending order"; + } + } + } + if (this.litterSizeCurve != null) + { + foreach (string item in this.litterSizeCurve.ConfigErrors("litterSizeCurve")) + { + yield return item; + } + } + if (this.nameOnTameChance > 0.0 && this.nameGenerator == null) + { + yield return "can be named, but has no nameGenerator"; + } + if (this.Animal && this.wildness < 0.0) + { + yield return "is animal but wildness is not defined"; + } + if (this.useMeatFrom != null && this.useMeatFrom.category != ThingCategory.Pawn) + { + yield return "tries to use meat from non-pawn " + this.useMeatFrom; + } + if (this.useMeatFrom != null && this.useMeatFrom.race.useMeatFrom != null) + { + yield return "tries to use meat from " + this.useMeatFrom + " which uses meat from " + this.useMeatFrom.race.useMeatFrom; + } + if (this.useLeatherFrom != null && this.useLeatherFrom.category != ThingCategory.Pawn) + { + yield return "tries to use leather from non-pawn " + this.useLeatherFrom; + } + if (this.useLeatherFrom != null && this.useLeatherFrom.race.useLeatherFrom != null) + { + yield return "tries to use leather from " + this.useLeatherFrom + " which uses leather from " + this.useLeatherFrom.race.useLeatherFrom; + } } - [DebuggerHidden] internal IEnumerable SpecialDisplayStats(ThingDef parentDef) { - RaceProperties.c__Iterator1CC c__Iterator1CC = new RaceProperties.c__Iterator1CC(); - c__Iterator1CC.parentDef = parentDef; - c__Iterator1CC.<$>parentDef = parentDef; - c__Iterator1CC.<>f__this = this; - RaceProperties.c__Iterator1CC expr_1C = c__Iterator1CC; - expr_1C.$PC = -2; - return expr_1C; + yield return new StatDrawEntry(StatCategoryDefOf.Basics, "Race".Translate(), parentDef.LabelCap, 2000); + yield return new StatDrawEntry(StatCategoryDefOf.Basics, "Diet".Translate(), this.foodType.ToHumanString().CapitalizeFirst(), 0); + if (this.wildness >= 0.0) + { + yield return new StatDrawEntry(StatCategoryDefOf.Basics, "Wildness".Translate(), this.wildness.ToStringPercent(), 0) + { + overrideReportText = "WildnessExplanation".Translate() + }; + } + if ((int)this.intelligence < 2) + { + yield return new StatDrawEntry(StatCategoryDefOf.Basics, "TrainableIntelligence".Translate(), this.TrainableIntelligence.GetLabel().CapitalizeFirst(), 0); + } + yield return new StatDrawEntry(StatCategoryDefOf.Basics, "StatsReport_LifeExpectancy".Translate(), this.lifeExpectancy.ToStringByStyle(ToStringStyle.Integer, ToStringNumberSense.Absolute), 0); + if ((int)this.intelligence < 2) + { + yield return new StatDrawEntry(StatCategoryDefOf.Basics, "AnimalFilthRate".Translate(), ((float)(PawnUtility.AnimalFilthChancePerCell(parentDef, parentDef.race.baseBodySize) * 1000.0)).ToString("F2"), 0) + { + overrideReportText = "AnimalFilthRateExplanation".Translate(1000.ToString()) + }; + } + if (this.packAnimal) + { + yield return new StatDrawEntry(StatCategoryDefOf.Basics, "PackAnimal".Translate(), "Yes".Translate(), 0) + { + overrideReportText = "PackAnimalExplanation".Translate() + }; + } } } } diff --git a/Assembly-CSharp/Verse/Rand.cs b/Assembly-CSharp/Verse/Rand.cs index b96b27cdd..4f92592c1 100644 --- a/Assembly-CSharp/Verse/Rand.cs +++ b/Assembly-CSharp/Verse/Rand.cs @@ -37,7 +37,7 @@ public static bool Bool { get { - return Rand.Value < 0.5f; + return Rand.Value < 0.5; } } @@ -53,8 +53,7 @@ public static Vector3 PointOnSphere { get { - Vector3 vector = new Vector3(Rand.Gaussian(0f, 1f), Rand.Gaussian(0f, 1f), Rand.Gaussian(0f, 1f)); - return vector.normalized; + return new Vector3(Rand.Gaussian(0f, 1f), Rand.Gaussian(0f, 1f), Rand.Gaussian(0f, 1f)).normalized; } } @@ -63,11 +62,12 @@ public static Vector3 PointOnDisc get { Vector3 result; - do + while (true) { - result = new Vector3(Rand.Value - 0.5f, 0f, Rand.Value - 0.5f) * 2f; + result = new Vector3((float)(Rand.Value - 0.5), 0f, (float)(Rand.Value - 0.5)) * 2f; + if (result.sqrMagnitude <= 1.0) + break; } - while (result.sqrMagnitude > 1f); return result; } } @@ -76,38 +76,38 @@ private static ulong StateCompressed { get { - return (ulong)Rand.random.seed | (ulong)Rand.iterations << 32; + return Rand.random.seed | (ulong)Rand.iterations << 32; } set { - Rand.random.seed = (uint)(value & (ulong)-1); - Rand.iterations = (uint)(value >> 32 & (ulong)-1); + Rand.random.seed = (uint)(value & 4294967295u); + Rand.iterations = (uint)(value >> 32 & 4294967295u); } } public static void EnsureStateStackEmpty() { - if (Rand.stateStack.Any()) + if (Rand.stateStack.Any()) { Log.Warning("Random state stack is not empty. There were more calls to PushState than PopState. Fixing."); Rand.stateStack.Clear(); } } - public static float Gaussian(float centerX = 0f, float widthFactor = 1f) + public static float Gaussian(float centerX = 0, float widthFactor = 1) { float value = Rand.Value; float value2 = Rand.Value; - float num = Mathf.Sqrt(-2f * Mathf.Log(value)) * Mathf.Sin(6.28318548f * value2); + float num = Mathf.Sqrt((float)(-2.0 * Mathf.Log(value))) * Mathf.Sin((float)(6.2831854820251465 * value2)); return num * widthFactor + centerX; } - public static float GaussianAsymmetric(float centerX = 0f, float lowerWidthFactor = 1f, float upperWidthFactor = 1f) + public static float GaussianAsymmetric(float centerX = 0, float lowerWidthFactor = 1, float upperWidthFactor = 1) { float value = Rand.Value; float value2 = Rand.Value; - float num = Mathf.Sqrt(-2f * Mathf.Log(value)) * Mathf.Sin(6.28318548f * value2); - if (num <= 0f) + float num = Mathf.Sqrt((float)(-2.0 * Mathf.Log(value))) * Mathf.Sin((float)(6.2831854820251465 * value2)); + if (num <= 0.0) { return num * lowerWidthFactor + centerX; } @@ -148,7 +148,11 @@ public static float Range(float min, float max) public static bool Chance(float chance) { - return chance >= 1f || Rand.Value < chance; + if (chance >= 1.0) + { + return true; + } + return Rand.Value < chance; } public static bool ChanceSeeded(float chance, int specialSeed) @@ -177,11 +181,11 @@ public static T Element(T a, T b) public static T Element(T a, T b, T c) { float value = Rand.Value; - if (value < 0.33333f) + if (value < 0.33333000540733337) { return a; } - if (value < 0.66666f) + if (value < 0.66666001081466675) { return b; } @@ -191,15 +195,15 @@ public static T Element(T a, T b, T c) public static T Element(T a, T b, T c, T d) { float value = Rand.Value; - if (value < 0.25f) + if (value < 0.25) { return a; } - if (value < 0.5f) + if (value < 0.5) { return b; } - if (value < 0.75f) + if (value < 0.75) { return c; } @@ -209,19 +213,19 @@ public static T Element(T a, T b, T c, T d) public static T Element(T a, T b, T c, T d, T e) { float value = Rand.Value; - if (value < 0.2f) + if (value < 0.20000000298023224) { return a; } - if (value < 0.4f) + if (value < 0.40000000596046448) { return b; } - if (value < 0.6f) + if (value < 0.60000002384185791) { return c; } - if (value < 0.8f) + if (value < 0.800000011920929) { return d; } @@ -231,23 +235,23 @@ public static T Element(T a, T b, T c, T d, T e) public static T Element(T a, T b, T c, T d, T e, T f) { float value = Rand.Value; - if (value < 0.16666f) + if (value < 0.16665999591350555) { return a; } - if (value < 0.33333f) + if (value < 0.33333000540733337) { return b; } - if (value < 0.5f) + if (value < 0.5) { return c; } - if (value < 0.66666f) + if (value < 0.66666001081466675) { return d; } - if (value < 0.83333f) + if (value < 0.833329975605011) { return e; } @@ -276,52 +280,52 @@ public static float ByCurve(SimpleCurve curve, int sampleCount = 100) { throw new ArgumentException("curve has < 3 points"); } - if (curve[0].y > 0f || curve[curve.PointsCount - 1].y > 0f) - { - throw new ArgumentException("curve has start/end point with y > 0"); - } - float x = curve[0].x; - float x2 = curve[curve.PointsCount - 1].x; - float num = (x2 - x) / (float)sampleCount; - float num2 = 0f; - for (int i = 0; i < sampleCount; i++) - { - float x3 = x + ((float)i + 0.5f) * num; - float num3 = curve.Evaluate(x3); - num2 += num3; - } - float num4 = Rand.Range(0f, num2); - num2 = 0f; - for (int j = 0; j < sampleCount; j++) + if (!(curve[0].y > 0.0) && !(curve[curve.PointsCount - 1].y > 0.0)) { - float num5 = x + ((float)j + 0.5f) * num; - float num6 = curve.Evaluate(num5); - num2 += num6; - if (num2 > num4) + float x = curve[0].x; + float x2 = curve[curve.PointsCount - 1].x; + float num = (x2 - x) / (float)sampleCount; + float num2 = 0f; + for (int num3 = 0; num3 < sampleCount; num3++) { - return num5 + Rand.Range(-num / 2f, num / 2f); + float x3 = (float)(x + ((float)num3 + 0.5) * num); + float num4 = curve.Evaluate(x3); + num2 += num4; } + float num5 = Rand.Range(0f, num2); + num2 = 0f; + for (int num6 = 0; num6 < sampleCount; num6++) + { + float num7 = (float)(x + ((float)num6 + 0.5) * num); + float num8 = curve.Evaluate(num7); + num2 += num8; + if (num2 > num5) + { + return num7 + Rand.Range((float)((0.0 - num) / 2.0), (float)(num / 2.0)); + } + } + throw new Exception("Reached end of Rand.ByCurve without choosing a point."); } - throw new Exception("Reached end of Rand.ByCurve without choosing a point."); + throw new ArgumentException("curve has start/end point with y > 0"); } public static bool MTBEventOccurs(float mtb, float mtbUnit, float checkDuration) { - if (mtb == float.PositiveInfinity) + if (mtb == double.PositiveInfinity) { return false; } - if (mtb <= 0f) + if (mtb <= 0.0) { Log.Error("MTBEventOccurs with mtb=" + mtb); return true; } - if (mtbUnit <= 0f) + if (mtbUnit <= 0.0) { Log.Error("MTBEventOccurs with mtbUnit=" + mtbUnit); return false; } - if (checkDuration <= 0f) + if (checkDuration <= 0.0) { Log.Error("MTBEventOccurs with checkDuration=" + checkDuration); return false; @@ -329,17 +333,7 @@ public static bool MTBEventOccurs(float mtb, float mtbUnit, float checkDuration) double num = (double)checkDuration / ((double)mtb * (double)mtbUnit); if (num <= 0.0) { - Log.Error(string.Concat(new object[] - { - "chancePerCheck is ", - num, - ". mtb=", - mtb, - ", mtbUnit=", - mtbUnit, - ", checkDuration=", - checkDuration - })); + Log.Error("chancePerCheck is " + num + ". mtb=" + mtb + ", mtbUnit=" + mtbUnit + ", checkDuration=" + checkDuration); return false; } double num2 = 1.0; @@ -379,22 +373,7 @@ internal static void LogRandTests() num++; } } - string value = string.Concat(new object[] - { - "MTB=", - 250, - " days, MTBUnit=", - 60000, - ", check duration=", - 60, - " Simulated ", - 5000, - " days (", - 5000000, - " tests). Got ", - num, - " events." - }); + string value = "MTB=" + 250 + " days, MTBUnit=" + 60000 + ", check duration=" + 60 + " Simulated " + 5000 + " days (" + 5000000 + " tests). Got " + num + " events."; stringBuilder.AppendLine(value); } stringBuilder.AppendLine(); @@ -409,20 +388,7 @@ internal static void LogRandTests() num2++; } } - string value2 = string.Concat(new object[] - { - "MTB=", - 1f, - " days, MTBUnit=", - 24000f, - ", check duration=", - 12000f, - ", ", - 10000, - " tests got ", - num2, - " events." - }); + string value2 = "MTB=" + 1f + " days, MTBUnit=" + 24000f + ", check duration=" + 12000f + ", " + 10000 + " tests got " + num2 + " events."; stringBuilder.AppendLine(value2); } for (int n = 0; n < 5; n++) @@ -435,20 +401,7 @@ internal static void LogRandTests() num3++; } } - string value3 = string.Concat(new object[] - { - "MTB=", - 2f, - " days, MTBUnit=", - 24000f, - ", check duration=", - 6000f, - ", ", - 10000, - " tests got ", - num3, - " events." - }); + string value3 = "MTB=" + 2f + " days, MTBUnit=" + 24000f + ", check duration=" + 6000f + ", " + 10000 + " tests got " + num3 + " events."; stringBuilder.AppendLine(value3); } Log.Message(stringBuilder.ToString()); @@ -465,31 +418,31 @@ public static bool TryRangeInclusiveWhere(int from, int to, Predicate predi { int num = to - from + 1; int num2 = Mathf.Max(Mathf.RoundToInt(Mathf.Sqrt((float)num)), 5); - for (int i = 0; i < num2; i++) + for (int num3 = 0; num3 < num2; num3++) { - int num3 = Rand.RangeInclusive(from, to); - if (predicate(num3)) + int num4 = Rand.RangeInclusive(from, to); + if (predicate(num4)) { - value = num3; + value = num4; return true; } } Rand.tmpRange.Clear(); - for (int j = from; j <= to; j++) + for (int num5 = from; num5 <= to; num5++) { - Rand.tmpRange.Add(j); + Rand.tmpRange.Add(num5); } - Rand.tmpRange.Shuffle(); - int k = 0; + Rand.tmpRange.Shuffle(); + int num6 = 0; int count = Rand.tmpRange.Count; - while (k < count) + while (num6 < count) { - if (predicate(Rand.tmpRange[k])) + if (predicate(Rand.tmpRange[num6])) { - value = Rand.tmpRange[k]; + value = Rand.tmpRange[num6]; return true; } - k++; + num6++; } value = 0; return false; @@ -497,17 +450,17 @@ public static bool TryRangeInclusiveWhere(int from, int to, Predicate predi public static Vector3 PointOnSphereCap(Vector3 center, float angle) { - if (angle <= 0f) + if (angle <= 0.0) { return center; } - if (angle >= 180f) + if (angle >= 180.0) { return Rand.PointOnSphere; } - float num = Rand.Range(Mathf.Cos(angle * 0.0174532924f), 1f); + float num = Rand.Range(Mathf.Cos((float)(angle * 0.01745329238474369)), 1f); float f = Rand.Range(0f, 6.28318548f); - Vector3 point = new Vector3(Mathf.Sqrt(1f - num * num) * Mathf.Cos(f), Mathf.Sqrt(1f - num * num) * Mathf.Sin(f), num); + Vector3 point = new Vector3(Mathf.Sqrt((float)(1.0 - num * num)) * Mathf.Cos(f), Mathf.Sqrt((float)(1.0 - num * num)) * Mathf.Sin(f), num); return Quaternion.FromToRotation(Vector3.forward, center) * point; } } diff --git a/Assembly-CSharp/Verse/RandomGenStepSelectorOption.cs b/Assembly-CSharp/Verse/RandomGenStepSelectorOption.cs index 88eb7f862..bf64481b6 100644 --- a/Assembly-CSharp/Verse/RandomGenStepSelectorOption.cs +++ b/Assembly-CSharp/Verse/RandomGenStepSelectorOption.cs @@ -1,5 +1,3 @@ -using System; - namespace Verse { public class RandomGenStepSelectorOption diff --git a/Assembly-CSharp/Verse/RandomNumberGenerator_BasicHash.cs b/Assembly-CSharp/Verse/RandomNumberGenerator_BasicHash.cs index aedbe5673..f19cb1803 100644 --- a/Assembly-CSharp/Verse/RandomNumberGenerator_BasicHash.cs +++ b/Assembly-CSharp/Verse/RandomNumberGenerator_BasicHash.cs @@ -1,5 +1,3 @@ -using System; - namespace Verse { public class RandomNumberGenerator_BasicHash : RandomNumberGenerator @@ -21,14 +19,14 @@ public override int GetInt(uint iterations) private uint GetHash(int buffer) { - uint num = this.seed + 374761393u; - num += 4u; - num += (uint)(buffer * -1028477379); - num = RandomNumberGenerator_BasicHash.Rotate(num, 17) * 668265263u; + uint num = base.seed + 374761393; + num += 4; + num = (uint)((int)num + buffer * -1028477379); + num = RandomNumberGenerator_BasicHash.Rotate(num, 17) * 668265263; num ^= num >> 15; - num *= 2246822519u; + num = (uint)((int)num * -2048144777); num ^= num >> 13; - num *= 3266489917u; + num = (uint)((int)num * -1028477379); return num ^ num >> 16; } diff --git a/Assembly-CSharp/Verse/Reachability.cs b/Assembly-CSharp/Verse/Reachability.cs index 748d65a8a..42a4f1705 100644 --- a/Assembly-CSharp/Verse/Reachability.cs +++ b/Assembly-CSharp/Verse/Reachability.cs @@ -45,21 +45,25 @@ private void QueueNewOpenRegion(Region region) if (region == null) { Log.ErrorOnce("Tried to queue null region.", 881121); - return; } - if (region.reachedIndex == this.reachedIndex) + else if (region.reachedIndex == this.reachedIndex) { Log.ErrorOnce("Region is already reached; you can't open it. Region: " + region.ToString(), 719991); - return; } - this.openQueue.Enqueue(region); - region.reachedIndex = this.reachedIndex; - this.numRegionsOpened++; + else + { + this.openQueue.Enqueue(region); + region.reachedIndex = this.reachedIndex; + this.numRegionsOpened++; + } } private uint NewReachedIndex() { - return this.reachedIndex++; + uint num = this.reachedIndex; + uint result = num; + this.reachedIndex = num + 1; + return result; } private void FinalizeCheck() @@ -69,12 +73,20 @@ private void FinalizeCheck() public bool CanReachNonLocal(IntVec3 start, TargetInfo dest, PathEndMode peMode, TraverseMode traverseMode, Danger maxDanger) { - return (dest.Map == null || dest.Map == this.map) && this.CanReach(start, (LocalTargetInfo)dest, peMode, traverseMode, maxDanger); + if (dest.Map != null && dest.Map != this.map) + { + return false; + } + return this.CanReach(start, (LocalTargetInfo)dest, peMode, traverseMode, maxDanger); } public bool CanReachNonLocal(IntVec3 start, TargetInfo dest, PathEndMode peMode, TraverseParms traverseParams) { - return (dest.Map == null || dest.Map == this.map) && this.CanReach(start, (LocalTargetInfo)dest, peMode, traverseParams); + if (dest.Map != null && dest.Map != this.map) + { + return false; + } + return this.CanReach(start, (LocalTargetInfo)dest, peMode, traverseParams); } public bool CanReach(IntVec3 start, LocalTargetInfo dest, PathEndMode peMode, TraverseMode traverseMode, Danger maxDanger) @@ -97,15 +109,7 @@ public bool CanReach(IntVec3 start, LocalTargetInfo dest, PathEndMode peMode, Tr } if (traverseParams.pawn.Map != this.map) { - Log.Error(string.Concat(new object[] - { - "Called CanReach() with a pawn spawned not on this map. This means that we can't check his reachability here. Pawn's current map should have been used instead of this one. pawn=", - traverseParams.pawn, - " pawn.Map=", - traverseParams.pawn.Map, - " map=", - this.map - })); + Log.Error("Called CanReach() with a pawn spawned not on this map. This means that we can't check his reachability here. Pawn's current map should have been used instead of this one. pawn=" + traverseParams.pawn + " pawn.Map=" + traverseParams.pawn.Map + " map=" + this.map); return false; } } @@ -121,100 +125,99 @@ public bool CanReach(IntVec3 start, LocalTargetInfo dest, PathEndMode peMode, Tr { return false; } - if (!start.InBounds(this.map) || !dest.Cell.InBounds(this.map)) - { - return false; - } - if (peMode == PathEndMode.OnCell || peMode == PathEndMode.Touch || peMode == PathEndMode.ClosestTouch) - { - Room room = RegionAndRoomQuery.RoomAtFast(start, this.map, RegionType.Set_Passable); - if (room != null && room == RegionAndRoomQuery.RoomAtFast(dest.Cell, this.map, RegionType.Set_Passable)) - { - return true; - } - } - if (traverseParams.mode == TraverseMode.PassAllDestroyableThings) + if (start.InBounds(this.map) && dest.Cell.InBounds(this.map)) { - TraverseParms traverseParams2 = traverseParams; - traverseParams2.mode = TraverseMode.PassDoors; - if (this.CanReach(start, dest, peMode, traverseParams2)) + if (peMode == PathEndMode.OnCell || peMode == PathEndMode.Touch || peMode == PathEndMode.ClosestTouch) { - return true; - } - } - dest = (LocalTargetInfo)GenPath.ResolvePathMode(traverseParams.pawn, dest.ToTargetInfo(this.map), ref peMode); - this.working = true; - bool result; - try - { - this.pathGrid = this.map.pathGrid; - this.regionGrid = this.map.regionGrid; - this.reachedIndex += 1u; - this.destRegions.Clear(); - if (peMode == PathEndMode.OnCell) - { - Region region = dest.Cell.GetRegion(this.map, RegionType.Set_Passable); - if (region != null && region.Allows(traverseParams, true)) + Room room = RegionAndRoomQuery.RoomAtFast(start, this.map, RegionType.Set_Passable); + if (room != null && room == RegionAndRoomQuery.RoomAtFast(dest.Cell, this.map, RegionType.Set_Passable)) { - this.destRegions.Add(region); + return true; } } - else if (peMode == PathEndMode.Touch) - { - TouchPathEndModeUtility.AddAllowedAdjacentRegions(dest, traverseParams, this.map, this.destRegions); - } - if (this.destRegions.Count == 0 && traverseParams.mode != TraverseMode.PassAllDestroyableThings) + if (traverseParams.mode == TraverseMode.PassAllDestroyableThings) { - this.FinalizeCheck(); - result = false; + TraverseParms traverseParams2 = traverseParams; + traverseParams2.mode = TraverseMode.PassDoors; + if (this.CanReach(start, dest, peMode, traverseParams2)) + { + return true; + } } - else + dest = (LocalTargetInfo)GenPath.ResolvePathMode(traverseParams.pawn, dest.ToTargetInfo(this.map), ref peMode); + this.working = true; + try { - this.destRegions.RemoveDuplicates(); + this.pathGrid = this.map.pathGrid; + this.regionGrid = this.map.regionGrid; + this.reachedIndex += 1u; + this.destRegions.Clear(); + switch (peMode) + { + case PathEndMode.OnCell: + { + Region region = dest.Cell.GetRegion(this.map, RegionType.Set_Passable); + if (region != null && region.Allows(traverseParams, true)) + { + this.destRegions.Add(region); + } + break; + } + case PathEndMode.Touch: + { + TouchPathEndModeUtility.AddAllowedAdjacentRegions(dest, traverseParams, this.map, this.destRegions); + break; + } + } + if (this.destRegions.Count == 0 && traverseParams.mode != TraverseMode.PassAllDestroyableThings) + { + this.FinalizeCheck(); + return false; + } + this.destRegions.RemoveDuplicates(); this.openQueue.Clear(); this.numRegionsOpened = 0; this.DetermineStartRegions(start); if (this.openQueue.Count == 0 && traverseParams.mode != TraverseMode.PassAllDestroyableThings) { this.FinalizeCheck(); - result = false; + return false; } - else + if (this.startingRegions.Any() && this.destRegions.Any()) { - if (this.startingRegions.Any() && this.destRegions.Any()) + switch (this.GetCachedResult(traverseParams)) { - switch (this.GetCachedResult(traverseParams)) - { - case BoolUnknown.True: - this.FinalizeCheck(); - result = true; - return result; - case BoolUnknown.False: - this.FinalizeCheck(); - result = false; - return result; - } - } - if (traverseParams.mode == TraverseMode.PassAllDestroyableThings) + case BoolUnknown.True: { - bool flag = this.CheckCellBasedReachability(start, dest, peMode, traverseParams); this.FinalizeCheck(); - result = flag; + return true; } - else + case BoolUnknown.False: { - bool flag2 = this.CheckRegionBasedReachability(traverseParams); this.FinalizeCheck(); - result = flag2; + return false; + } } } + if (traverseParams.mode == TraverseMode.PassAllDestroyableThings) + { + bool result = this.CheckCellBasedReachability(start, dest, peMode, traverseParams); + this.FinalizeCheck(); + return result; + } + bool result2 = this.CheckRegionBasedReachability(traverseParams); + this.FinalizeCheck(); + return result2; + IL_0364: + bool result3; + return result3; + } + finally + { + this.working = false; } } - finally - { - this.working = false; - } - return result; + return false; } private void DetermineStartRegions(IntVec3 start) @@ -231,16 +234,13 @@ private void DetermineStartRegions(IntVec3 start) for (int i = 0; i < 8; i++) { IntVec3 intVec = start + GenAdj.AdjacentCells[i]; - if (intVec.InBounds(this.map)) + if (intVec.InBounds(this.map) && this.pathGrid.WalkableFast(intVec)) { - if (this.pathGrid.WalkableFast(intVec)) + Region validRegionAt2 = this.regionGrid.GetValidRegionAt(intVec); + if (validRegionAt2 != null && validRegionAt2.reachedIndex != this.reachedIndex) { - Region validRegionAt2 = this.regionGrid.GetValidRegionAt(intVec); - if (validRegionAt2 != null && validRegionAt2.reachedIndex != this.reachedIndex) - { - this.QueueNewOpenRegion(validRegionAt2); - this.startingRegions.Add(validRegionAt2); - } + this.QueueNewOpenRegion(validRegionAt2); + this.startingRegions.Add(validRegionAt2); } } } @@ -258,14 +258,17 @@ private BoolUnknown GetCachedResult(TraverseParms traverseParams) { return BoolUnknown.True; } - BoolUnknown boolUnknown = this.cache.CachedResultFor(this.startingRegions[i].Room, this.destRegions[j].Room, traverseParams); - if (boolUnknown == BoolUnknown.True) + switch (this.cache.CachedResultFor(this.startingRegions[i].Room, this.destRegions[j].Room, traverseParams)) + { + case BoolUnknown.True: { return BoolUnknown.True; } - if (boolUnknown == BoolUnknown.Unknown) + case BoolUnknown.Unknown: { flag = true; + break; + } } } } @@ -287,20 +290,17 @@ private bool CheckRegionBasedReachability(TraverseParms traverseParams) for (int j = 0; j < 2; j++) { Region region2 = regionLink.regions[j]; - if (region2 != null && region2.reachedIndex != this.reachedIndex && region2.type.Passable()) + if (region2 != null && region2.reachedIndex != this.reachedIndex && region2.type.Passable() && region2.Allows(traverseParams, false)) { - if (region2.Allows(traverseParams, false)) + if (this.destRegions.Contains(region2)) { - if (this.destRegions.Contains(region2)) + for (int k = 0; k < this.startingRegions.Count; k++) { - for (int k = 0; k < this.startingRegions.Count; k++) - { - this.cache.AddCachedResult(this.startingRegions[k].Room, region2.Room, traverseParams, true); - } - return true; + this.cache.AddCachedResult(this.startingRegions[k].Room, region2.Room, traverseParams, true); } - this.QueueNewOpenRegion(region2); + return true; } + this.QueueNewOpenRegion(region2); } } } @@ -321,7 +321,7 @@ private bool CheckCellBasedReachability(IntVec3 start, LocalTargetInfo dest, Pat Region[] directRegionGrid = this.regionGrid.DirectGrid; PathGrid pathGrid = this.map.pathGrid; CellIndices cellIndices = this.map.cellIndices; - this.map.floodFiller.FloodFill(start, delegate(IntVec3 c) + this.map.floodFiller.FloodFill(start, (Predicate)delegate(IntVec3 c) { int num = cellIndices.CellToIndex(c); if (traverseParams.mode == TraverseMode.PassAllDestroyableThings) @@ -329,10 +329,11 @@ private bool CheckCellBasedReachability(IntVec3 start, LocalTargetInfo dest, Pat if (!pathGrid.WalkableFast(num)) { Building edifice = c.GetEdifice(this.map); - if (edifice == null || !PathFinder.IsDestroyable(edifice)) + if (edifice != null && PathFinder.IsDestroyable(edifice)) { - return false; + goto IL_007b; } + return false; } } else @@ -343,9 +344,15 @@ private bool CheckCellBasedReachability(IntVec3 start, LocalTargetInfo dest, Pat return false; } } + goto IL_007b; + IL_007b: Region region = directRegionGrid[num]; - return region == null || region.Allows(traverseParams, false); - }, delegate(IntVec3 c) + if (region != null && !region.Allows(traverseParams, false)) + { + return false; + } + return true; + }, (Func)delegate(IntVec3 c) { if (ReachabilityImmediate.CanReachImmediate(c, dest, this.map, peMode, traverseParams.pawn)) { @@ -406,7 +413,7 @@ public bool CanReachFactionBase(IntVec3 c, Faction factionBaseFaction) List allBuildingsColonist = this.map.listerBuildings.allBuildingsColonist; for (int j = 0; j < allBuildingsColonist.Count; j++) { - if (this.CanReach(c, allBuildingsColonist[j], PathEndMode.Touch, traverseParams)) + if (this.CanReach(c, (Thing)allBuildingsColonist[j], PathEndMode.Touch, traverseParams)) { return true; } @@ -436,15 +443,7 @@ public bool CanReachMapEdge(IntVec3 c, TraverseParms traverseParms) } if (traverseParms.pawn.Map != this.map) { - Log.Error(string.Concat(new object[] - { - "Called CanReachMapEdge() with a pawn spawned not on this map. This means that we can't check his reachability here. Pawn's current map should have been used instead of this one. pawn=", - traverseParms.pawn, - " pawn.Map=", - traverseParms.pawn.Map, - " map=", - this.map - })); + Log.Error("Called CanReachMapEdge() with a pawn spawned not on this map. This means that we can't check his reachability here. Pawn's current map should have been used instead of this one. pawn=" + traverseParms.pawn + " pawn.Map=" + traverseParms.pawn.Map + " map=" + this.map); return false; } } @@ -457,9 +456,9 @@ public bool CanReachMapEdge(IntVec3 c, TraverseParms traverseParms) { return true; } - RegionEntryPredicate entryCondition = (Region from, Region r) => r.Allows(traverseParms, false); + RegionEntryPredicate entryCondition = (RegionEntryPredicate)((Region from, Region r) => r.Allows(traverseParms, false)); bool foundReg = false; - RegionProcessor regionProcessor = delegate(Region r) + RegionProcessor regionProcessor = (RegionProcessor)delegate(Region r) { if (r.Room.TouchesMapEdge) { @@ -482,15 +481,7 @@ public bool CanReachUnfogged(IntVec3 c, TraverseParms traverseParms) } if (traverseParms.pawn.Map != this.map) { - Log.Error(string.Concat(new object[] - { - "Called CanReachUnfogged() with a pawn spawned not on this map. This means that we can't check his reachability here. Pawn's current map should have been used instead of this one. pawn=", - traverseParms.pawn, - " pawn.Map=", - traverseParms.pawn.Map, - " map=", - this.map - })); + Log.Error("Called CanReachUnfogged() with a pawn spawned not on this map. This means that we can't check his reachability here. Pawn's current map should have been used instead of this one. pawn=" + traverseParms.pawn + " pawn.Map=" + traverseParms.pawn.Map + " map=" + this.map); return false; } } @@ -507,9 +498,9 @@ public bool CanReachUnfogged(IntVec3 c, TraverseParms traverseParms) { return false; } - RegionEntryPredicate entryCondition = (Region from, Region r) => r.Allows(traverseParms, false); + RegionEntryPredicate entryCondition = (RegionEntryPredicate)((Region from, Region r) => r.Allows(traverseParms, false)); bool foundReg = false; - RegionProcessor regionProcessor = delegate(Region r) + RegionProcessor regionProcessor = (RegionProcessor)delegate(Region r) { if (!r.AnyCell.Fogged(this.map)) { diff --git a/Assembly-CSharp/Verse/ReachabilityCache.cs b/Assembly-CSharp/Verse/ReachabilityCache.cs index a7fb77435..3f4afe898 100644 --- a/Assembly-CSharp/Verse/ReachabilityCache.cs +++ b/Assembly-CSharp/Verse/ReachabilityCache.cs @@ -7,7 +7,7 @@ namespace Verse internal class ReachabilityCache { [StructLayout(LayoutKind.Sequential, Size = 1)] - private struct CachedEntry : IEquatable + private struct CachedEntry : IEquatable { public int FirstRoomID { @@ -44,10 +44,14 @@ public CachedEntry(int firstRoomID, int secondRoomID, TraverseParms traverseParm public override bool Equals(object obj) { - return obj is ReachabilityCache.CachedEntry && this.Equals((ReachabilityCache.CachedEntry)obj); + if (!(obj is CachedEntry)) + { + return false; + } + return this.Equals((CachedEntry)obj); } - public bool Equals(ReachabilityCache.CachedEntry other) + public bool Equals(CachedEntry other) { return this.FirstRoomID == other.FirstRoomID && this.SecondRoomID == other.SecondRoomID && this.TraverseParms == other.TraverseParms; } @@ -55,21 +59,21 @@ public bool Equals(ReachabilityCache.CachedEntry other) public override int GetHashCode() { int seed = Gen.HashCombineInt(this.FirstRoomID, this.SecondRoomID); - return Gen.HashCombineStruct(seed, this.TraverseParms); + return Gen.HashCombineStruct(seed, this.TraverseParms); } - public static bool operator ==(ReachabilityCache.CachedEntry lhs, ReachabilityCache.CachedEntry rhs) + public static bool operator ==(CachedEntry lhs, CachedEntry rhs) { return lhs.Equals(rhs); } - public static bool operator !=(ReachabilityCache.CachedEntry lhs, ReachabilityCache.CachedEntry rhs) + public static bool operator !=(CachedEntry lhs, CachedEntry rhs) { return !lhs.Equals(rhs); } } - private Dictionary cacheDict = new Dictionary(); + private Dictionary cacheDict = new Dictionary(); public int Count { @@ -81,17 +85,17 @@ public int Count public BoolUnknown CachedResultFor(Room A, Room B, TraverseParms traverseParams) { - bool flag; - if (this.cacheDict.TryGetValue(new ReachabilityCache.CachedEntry(A.ID, B.ID, traverseParams), out flag)) + bool flag = default(bool); + if (this.cacheDict.TryGetValue(new CachedEntry(A.ID, B.ID, traverseParams), out flag)) { - return (!flag) ? BoolUnknown.False : BoolUnknown.True; + return (BoolUnknown)((!flag) ? 1 : 0); } return BoolUnknown.Unknown; } public void AddCachedResult(Room A, Room B, TraverseParms traverseParams, bool reachable) { - ReachabilityCache.CachedEntry key = new ReachabilityCache.CachedEntry(A.ID, B.ID, traverseParams); + CachedEntry key = new CachedEntry(A.ID, B.ID, traverseParams); if (!this.cacheDict.ContainsKey(key)) { this.cacheDict.Add(key, reachable); diff --git a/Assembly-CSharp/Verse/ReachabilityImmediate.cs b/Assembly-CSharp/Verse/ReachabilityImmediate.cs index 758b35d96..9bf500233 100644 --- a/Assembly-CSharp/Verse/ReachabilityImmediate.cs +++ b/Assembly-CSharp/Verse/ReachabilityImmediate.cs @@ -1,4 +1,3 @@ -using System; using Verse.AI; namespace Verse @@ -15,34 +14,37 @@ public static bool CanReachImmediate(IntVec3 start, LocalTargetInfo target, Map if (target.HasThing) { Thing thing = target.Thing; - if (!thing.Spawned) + if (thing.Spawned) { - if (pawn != null) + if (thing.Map != map) { - if (pawn.carryTracker.innerContainer.Contains(thing)) - { - return true; - } - if (pawn.inventory.innerContainer.Contains(thing)) - { - return true; - } - if (pawn.apparel != null && pawn.apparel.Contains(thing)) - { - return true; - } - if (pawn.equipment != null && pawn.equipment.Contains(thing)) - { - return true; - } + return false; } - return false; + goto IL_00d3; } - if (thing.Map != map) + if (pawn != null) { - return false; + if (pawn.carryTracker.innerContainer.Contains(thing)) + { + return true; + } + if (pawn.inventory.innerContainer.Contains(thing)) + { + return true; + } + if (pawn.apparel != null && pawn.apparel.Contains(thing)) + { + return true; + } + if (pawn.equipment != null && pawn.equipment.Contains(thing)) + { + return true; + } } + return false; } + goto IL_00d3; + IL_00d3: if (!target.HasThing || (target.Thing.def.size.x == 1 && target.Thing.def.size.z == 1)) { if (start == target.Cell) @@ -54,17 +56,33 @@ public static bool CanReachImmediate(IntVec3 start, LocalTargetInfo target, Map { return true; } - return peMode == PathEndMode.Touch && TouchPathEndModeUtility.IsAdjacentOrInsideAndAllowedToTouch(start, target, map); + if (peMode == PathEndMode.Touch && TouchPathEndModeUtility.IsAdjacentOrInsideAndAllowedToTouch(start, target, map)) + { + return true; + } + return false; } public static bool CanReachImmediate(this Pawn pawn, LocalTargetInfo target, PathEndMode peMode) { - return pawn.Spawned && ReachabilityImmediate.CanReachImmediate(pawn.Position, target, pawn.Map, peMode, pawn); + if (!pawn.Spawned) + { + return false; + } + return ReachabilityImmediate.CanReachImmediate(pawn.Position, target, pawn.Map, peMode, pawn); } public static bool CanReachImmediateNonLocal(this Pawn pawn, TargetInfo target, PathEndMode peMode) { - return pawn.Spawned && (target.Map == null || target.Map == pawn.Map) && pawn.CanReachImmediate((LocalTargetInfo)target, peMode); + if (!pawn.Spawned) + { + return false; + } + if (target.Map != null && target.Map != pawn.Map) + { + return false; + } + return pawn.CanReachImmediate((LocalTargetInfo)target, peMode); } } } diff --git a/Assembly-CSharp/Verse/ReachabilityUtility.cs b/Assembly-CSharp/Verse/ReachabilityUtility.cs index 2c6999a60..a88aed4e7 100644 --- a/Assembly-CSharp/Verse/ReachabilityUtility.cs +++ b/Assembly-CSharp/Verse/ReachabilityUtility.cs @@ -1,4 +1,3 @@ -using System; using System.Collections.Generic; using Verse.AI; @@ -8,17 +7,29 @@ public static class ReachabilityUtility { public static bool CanReach(this Pawn pawn, LocalTargetInfo dest, PathEndMode peMode, Danger maxDanger, bool canBash = false, TraverseMode mode = TraverseMode.ByPawn) { - return pawn.Spawned && pawn.Map.reachability.CanReach(pawn.Position, dest, peMode, TraverseParms.For(pawn, maxDanger, mode, canBash)); + if (!pawn.Spawned) + { + return false; + } + return pawn.Map.reachability.CanReach(pawn.Position, dest, peMode, TraverseParms.For(pawn, maxDanger, mode, canBash)); } public static bool CanReachNonLocal(this Pawn pawn, TargetInfo dest, PathEndMode peMode, Danger maxDanger, bool canBash = false, TraverseMode mode = TraverseMode.ByPawn) { - return pawn.Spawned && pawn.Map.reachability.CanReachNonLocal(pawn.Position, dest, peMode, TraverseParms.For(pawn, maxDanger, mode, canBash)); + if (!pawn.Spawned) + { + return false; + } + return pawn.Map.reachability.CanReachNonLocal(pawn.Position, dest, peMode, TraverseParms.For(pawn, maxDanger, mode, canBash)); } public static bool CanReachMapEdge(this Pawn p) { - return p.Spawned && p.Map.reachability.CanReachMapEdge(p.Position, TraverseParms.For(p, Danger.Deadly, TraverseMode.ByPawn, false)); + if (!p.Spawned) + { + return false; + } + return p.Map.reachability.CanReachMapEdge(p.Position, TraverseParms.For(p, Danger.Deadly, TraverseMode.ByPawn, false)); } public static void ClearCache() diff --git a/Assembly-CSharp/Verse/ReachabilityWithinRegion.cs b/Assembly-CSharp/Verse/ReachabilityWithinRegion.cs index cf93757db..48c96cadf 100644 --- a/Assembly-CSharp/Verse/ReachabilityWithinRegion.cs +++ b/Assembly-CSharp/Verse/ReachabilityWithinRegion.cs @@ -1,4 +1,3 @@ -using System; using Verse.AI; namespace Verse @@ -15,8 +14,15 @@ public static bool ThingFromRegionListerReachable(Thing thing, Region region, Pa switch (peMode) { case PathEndMode.None: + { return false; + } + case PathEndMode.Touch: + { + return true; + } case PathEndMode.OnCell: + { if (thing.def.size.x == 1 && thing.def.size.z == 1) { if (thing.Position.GetRegion(map, RegionType.Set_Passable) == region) @@ -37,13 +43,21 @@ public static bool ThingFromRegionListerReachable(Thing thing, Region region, Pa } } return false; - case PathEndMode.Touch: - return true; + } case PathEndMode.InteractionCell: - return thing.InteractionCell.GetRegion(map, RegionType.Set_Passable) == region; + { + if (thing.InteractionCell.GetRegion(map, RegionType.Set_Passable) == region) + { + return true; + } + return false; + } + default: + { + Log.Error("Unsupported PathEndMode: " + peMode); + return false; + } } - Log.Error("Unsupported PathEndMode: " + peMode); - return false; } } } diff --git a/Assembly-CSharp/Verse/RealTime.cs b/Assembly-CSharp/Verse/RealTime.cs index 0a5293c10..03481f549 100644 --- a/Assembly-CSharp/Verse/RealTime.cs +++ b/Assembly-CSharp/Verse/RealTime.cs @@ -1,4 +1,3 @@ -using System; using UnityEngine; namespace Verse diff --git a/Assembly-CSharp/Verse/RealtimeMoteList.cs b/Assembly-CSharp/Verse/RealtimeMoteList.cs index ba12c4cfa..d72a60a6f 100644 --- a/Assembly-CSharp/Verse/RealtimeMoteList.cs +++ b/Assembly-CSharp/Verse/RealtimeMoteList.cs @@ -1,4 +1,3 @@ -using System; using System.Collections.Generic; namespace Verse @@ -24,9 +23,9 @@ public void MoteDespawned(Mote oldMote) public void MoteListUpdate() { - for (int i = this.allMotes.Count - 1; i >= 0; i--) + for (int num = this.allMotes.Count - 1; num >= 0; num--) { - this.allMotes[i].RealtimeUpdate(); + this.allMotes[num].RealtimeUpdate(); } } } diff --git a/Assembly-CSharp/Verse/RecipeDef.cs b/Assembly-CSharp/Verse/RecipeDef.cs index 7c3c9747e..3991218f3 100644 --- a/Assembly-CSharp/Verse/RecipeDef.cs +++ b/Assembly-CSharp/Verse/RecipeDef.cs @@ -1,7 +1,6 @@ using RimWorld; using System; using System.Collections.Generic; -using System.Diagnostics; using System.Linq; using System.Text; @@ -152,13 +151,7 @@ public string MinSkillString for (int i = 0; i < this.skillRequirements.Count; i++) { SkillRequirement skillRequirement = this.skillRequirements[i]; - stringBuilder.AppendLine(string.Concat(new object[] - { - " ", - skillRequirement.skill.skillLabel, - ": ", - skillRequirement.minLevel - })); + stringBuilder.AppendLine(" " + skillRequirement.skill.skillLabel + ": " + skillRequirement.minLevel); flag = true; } } @@ -174,11 +167,18 @@ public IEnumerable AllRecipeUsers { get { - RecipeDef.<>c__Iterator1D6 <>c__Iterator1D = new RecipeDef.<>c__Iterator1D6(); - <>c__Iterator1D.<>f__this = this; - RecipeDef.<>c__Iterator1D6 expr_0E = <>c__Iterator1D; - expr_0E.$PC = -2; - return expr_0E; + for (int j = 0; j < this.recipeUsers.Count; j++) + { + yield return this.recipeUsers[j]; + } + List thingDefs = DefDatabase.AllDefsListForReading; + for (int i = 0; i < thingDefs.Count; i++) + { + if (thingDefs[i].recipes != null && thingDefs[i].recipes.Contains(this)) + { + yield return thingDefs[i]; + } + } } } @@ -192,25 +192,47 @@ public bool UsesUnfinishedThing public float WorkAmountTotal(ThingDef stuffDef) { - if (this.workAmount >= 0f) + if (this.workAmount >= 0.0) { return this.workAmount; } return this.products[0].thingDef.GetStatValueAbstract(StatDefOf.WorkToMake, stuffDef); } - [DebuggerHidden] public IEnumerable PotentiallyMissingIngredients(Pawn billDoer, Map map) { - RecipeDef.c__Iterator1D7 c__Iterator1D = new RecipeDef.c__Iterator1D7(); - c__Iterator1D.map = map; - c__Iterator1D.billDoer = billDoer; - c__Iterator1D.<$>map = map; - c__Iterator1D.<$>billDoer = billDoer; - c__Iterator1D.<>f__this = this; - RecipeDef.c__Iterator1D7 expr_2A = c__Iterator1D; - expr_2A.$PC = -2; - return expr_2A; + for (int j = 0; j < this.ingredients.Count; j++) + { + IngredientCount ing = this.ingredients[j]; + bool foundIng = false; + List thingList = map.listerThings.ThingsInGroup(ThingRequestGroup.HaulableEver); + for (int i = 0; i < thingList.Count; i++) + { + Thing t = thingList[i]; + if ((billDoer == null || !t.IsForbidden(billDoer)) && !t.Position.Fogged(map) && (ing.IsFixedIngredient || this.fixedIngredientFilter.Allows(t)) && ing.filter.Allows(t)) + { + foundIng = true; + break; + } + } + if (!foundIng) + { + if (ing.IsFixedIngredient) + { + yield return ing.filter.AllowedThingDefs.First(); + } + else + { + ThingDef def = (from x in ing.filter.AllowedThingDefs + orderby x.BaseMarketValue + select x).FirstOrDefault((Func)((ThingDef x) => ((_003CPotentiallyMissingIngredients_003Ec__Iterator1D7)/*Error near IL_01ba: stateMachine*/)._003C_003Ef__this.fixedIngredientFilter.Allows(x))); + if (def != null) + { + yield return def; + } + } + } + } } public bool IsIngredient(ThingDef th) @@ -225,14 +247,16 @@ public bool IsIngredient(ThingDef th) return false; } - [DebuggerHidden] public override IEnumerable ConfigErrors() { - RecipeDef.c__Iterator1D8 c__Iterator1D = new RecipeDef.c__Iterator1D8(); - c__Iterator1D.<>f__this = this; - RecipeDef.c__Iterator1D8 expr_0E = c__Iterator1D; - expr_0E.$PC = -2; - return expr_0E; + foreach (string item in base.ConfigErrors()) + { + yield return item; + } + if (this.workerClass == null) + { + yield return "workerClass is null."; + } } public override void ResolveReferences() @@ -259,7 +283,7 @@ public override void ResolveReferences() public bool PawnSatisfiesSkillRequirements(Pawn pawn) { - return this.skillRequirements == null || !this.skillRequirements.Any((SkillRequirement req) => !req.PawnSatisfies(pawn)); + return this.skillRequirements == null || !this.skillRequirements.Any((Predicate)((SkillRequirement req) => !req.PawnSatisfies(pawn))); } public List GetPremultipliedSmallIngredients() @@ -268,21 +292,20 @@ public List GetPremultipliedSmallIngredients() { return this.premultipliedSmallIngredients; } - this.premultipliedSmallIngredients = (from td in this.ingredients.SelectMany((IngredientCount ingredient) => ingredient.filter.AllowedThingDefs) + this.premultipliedSmallIngredients = (from td in this.ingredients.SelectMany((Func>)((IngredientCount ingredient) => ingredient.filter.AllowedThingDefs)) where td.smallVolume - select td).Distinct().ToList(); + select td).Distinct().ToList(); bool flag = true; while (flag) { flag = false; for (int i = 0; i < this.ingredients.Count; i++) { - bool flag2 = this.ingredients[i].filter.AllowedThingDefs.Any((ThingDef td) => !this.premultipliedSmallIngredients.Contains(td)); - if (flag2) + if (this.ingredients[i].filter.AllowedThingDefs.Any((Func)((ThingDef td) => !this.premultipliedSmallIngredients.Contains(td)))) { - foreach (ThingDef current in this.ingredients[i].filter.AllowedThingDefs) + foreach (ThingDef allowedThingDef in this.ingredients[i].filter.AllowedThingDefs) { - flag |= this.premultipliedSmallIngredients.Remove(current); + flag |= this.premultipliedSmallIngredients.Remove(allowedThingDef); } } } diff --git a/Assembly-CSharp/Verse/RecipeMakerProperties.cs b/Assembly-CSharp/Verse/RecipeMakerProperties.cs index db080052a..6e5be1ad2 100644 --- a/Assembly-CSharp/Verse/RecipeMakerProperties.cs +++ b/Assembly-CSharp/Verse/RecipeMakerProperties.cs @@ -1,5 +1,4 @@ using RimWorld; -using System; using System.Collections.Generic; namespace Verse diff --git a/Assembly-CSharp/Verse/RecipeWorker.cs b/Assembly-CSharp/Verse/RecipeWorker.cs index 310a5f5a3..64494dfee 100644 --- a/Assembly-CSharp/Verse/RecipeWorker.cs +++ b/Assembly-CSharp/Verse/RecipeWorker.cs @@ -1,7 +1,5 @@ using RimWorld; -using System; using System.Collections.Generic; -using System.Diagnostics; namespace Verse { @@ -9,13 +7,9 @@ public class RecipeWorker { public RecipeDef recipe; - [DebuggerHidden] public virtual IEnumerable GetPartsToApplyOn(Pawn pawn, RecipeDef recipe) { - RecipeWorker.c__IteratorBF c__IteratorBF = new RecipeWorker.c__IteratorBF(); - RecipeWorker.c__IteratorBF expr_07 = c__IteratorBF; - expr_07.$PC = -2; - return expr_07; + yield break; } public virtual void ApplyOnPawn(Pawn pawn, BodyPartRecord part, Pawn billDoer, List ingredients) @@ -24,7 +18,11 @@ public virtual void ApplyOnPawn(Pawn pawn, BodyPartRecord part, Pawn billDoer, L public virtual bool IsViolationOnPawn(Pawn pawn, BodyPartRecord part, Faction billDoerFaction) { - return pawn.Faction != billDoerFaction && this.recipe.isViolation; + if (pawn.Faction == billDoerFaction) + { + return false; + } + return this.recipe.isViolation; } public virtual string GetLabelWhenUsedOn(Pawn pawn, BodyPartRecord part) diff --git a/Assembly-CSharp/Verse/RecipeWorkerCounter.cs b/Assembly-CSharp/Verse/RecipeWorkerCounter.cs index a91075cf5..7f46f74d7 100644 --- a/Assembly-CSharp/Verse/RecipeWorkerCounter.cs +++ b/Assembly-CSharp/Verse/RecipeWorkerCounter.cs @@ -1,5 +1,4 @@ using RimWorld; -using System; using System.Collections.Generic; namespace Verse @@ -38,7 +37,7 @@ public virtual int CountProducts(Bill_Production bill) public virtual string ProductsDescription(Bill_Production bill) { - return null; + return (string)null; } } } diff --git a/Assembly-CSharp/Verse/RecipeWorkerCounter_MakeStoneBlocks.cs b/Assembly-CSharp/Verse/RecipeWorkerCounter_MakeStoneBlocks.cs index 911f95452..9895f7965 100644 --- a/Assembly-CSharp/Verse/RecipeWorkerCounter_MakeStoneBlocks.cs +++ b/Assembly-CSharp/Verse/RecipeWorkerCounter_MakeStoneBlocks.cs @@ -19,13 +19,22 @@ public override int CountProducts(Bill_Production bill) { ThingCategoryDef stoneBlocks = ThingCategoryDefOf.StoneBlocks; this.stoneBlocksDefs = new List(16); - foreach (ThingDef current in DefDatabase.AllDefsListForReading) + List.Enumerator enumerator = DefDatabase.AllDefsListForReading.GetEnumerator(); + try { - if (current.thingCategories != null && current.thingCategories.Contains(stoneBlocks)) + while (enumerator.MoveNext()) { - this.stoneBlocksDefs.Add(current); + ThingDef current = enumerator.Current; + if (current.thingCategories != null && current.thingCategories.Contains(stoneBlocks)) + { + this.stoneBlocksDefs.Add(current); + } } } + finally + { + ((IDisposable)(object)enumerator).Dispose(); + } } int num = 0; for (int i = 0; i < this.stoneBlocksDefs.Count; i++) diff --git a/Assembly-CSharp/Verse/RectTrigger.cs b/Assembly-CSharp/Verse/RectTrigger.cs index ef7235a59..7ede1ff81 100644 --- a/Assembly-CSharp/Verse/RectTrigger.cs +++ b/Assembly-CSharp/Verse/RectTrigger.cs @@ -1,5 +1,4 @@ using RimWorld; -using System; using System.Collections.Generic; namespace Verse @@ -39,9 +38,8 @@ public override void Tick() if (this.destroyIfUnfogged && !this.rect.CenterCell.Fogged(base.Map)) { this.Destroy(DestroyMode.Vanish); - return; } - if (this.IsHashIntervalTick(60)) + else if (this.IsHashIntervalTick(60)) { Map map = base.Map; for (int i = this.rect.minZ; i <= this.rect.maxZ; i++) @@ -69,7 +67,7 @@ private void ActivatedBy(Pawn p) { ChoiceLetter choiceLetter = (ChoiceLetter)this.letter; choiceLetter.text = string.Format(choiceLetter.text, p.NameStringShort).AdjustedFor(p); - Find.LetterStack.ReceiveLetter(choiceLetter, null); + Find.LetterStack.ReceiveLetter(choiceLetter, (string)null); } if (!base.Destroyed) { diff --git a/Assembly-CSharp/Verse/Region.cs b/Assembly-CSharp/Verse/Region.cs index 3ca79ffb2..29e74e1b5 100644 --- a/Assembly-CSharp/Verse/Region.cs +++ b/Assembly-CSharp/Verse/Region.cs @@ -15,7 +15,7 @@ public sealed class Region public int id = -1; - public sbyte mapIndex = -1; + public sbyte mapIndex = (sbyte)(-1); private Room roomInt; @@ -57,7 +57,7 @@ public Map Map { get { - return ((int)this.mapIndex >= 0) ? Find.Maps[(int)this.mapIndex] : null; + return (this.mapIndex >= 0) ? Find.Maps[this.mapIndex] : null; } } @@ -65,11 +65,18 @@ public IEnumerable Cells { get { - Region.<>c__Iterator1FF <>c__Iterator1FF = new Region.<>c__Iterator1FF(); - <>c__Iterator1FF.<>f__this = this; - Region.<>c__Iterator1FF expr_0E = <>c__Iterator1FF; - expr_0E.$PC = -2; - return expr_0E; + RegionGrid regions = this.Map.regionGrid; + for (int z = this.extentsClose.minZ; z <= this.extentsClose.maxZ; z++) + { + for (int x = this.extentsClose.minX; x <= this.extentsClose.maxX; x++) + { + IntVec3 c = new IntVec3(x, 0, z); + if (regions.GetRegionAt_NoRebuild_InvalidAllowed(c) == this) + { + yield return c; + } + } + } } } @@ -79,7 +86,7 @@ public int CellCount { if (this.cachedCellCount == -1) { - this.cachedCellCount = this.Cells.Count(); + this.cachedCellCount = this.Cells.Count(); } return this.cachedCellCount; } @@ -89,11 +96,17 @@ public IEnumerable Neighbors { get { - Region.<>c__Iterator200 <>c__Iterator = new Region.<>c__Iterator200(); - <>c__Iterator.<>f__this = this; - Region.<>c__Iterator200 expr_0E = <>c__Iterator; - expr_0E.$PC = -2; - return expr_0E; + for (int li = 0; li < this.links.Count; li++) + { + RegionLink link = this.links[li]; + for (int ri = 0; ri < 2; ri++) + { + if (link.regions[ri] != null && link.regions[ri] != this && link.regions[ri].valid) + { + yield return link.regions[ri]; + } + } + } } } @@ -101,11 +114,17 @@ public IEnumerable NeighborsOfSameType { get { - Region.<>c__Iterator201 <>c__Iterator = new Region.<>c__Iterator201(); - <>c__Iterator.<>f__this = this; - Region.<>c__Iterator201 expr_0E = <>c__Iterator; - expr_0E.$PC = -2; - return expr_0E; + for (int li = 0; li < this.links.Count; li++) + { + RegionLink link = this.links[li]; + for (int ri = 0; ri < 2; ri++) + { + if (link.regions[ri] != null && link.regions[ri] != this && link.regions[ri].type == this.type && link.regions[ri].valid) + { + yield return link.regions[ri]; + } + } + } } } @@ -117,18 +136,17 @@ public Room Room } set { - if (value == this.roomInt) - { - return; - } - if (this.roomInt != null) - { - this.roomInt.RemoveRegion(this); - } - this.roomInt = value; - if (this.roomInt != null) + if (value != this.roomInt) { - this.roomInt.AddRegion(this); + if (this.roomInt != null) + { + this.roomInt.RemoveRegion(this); + } + this.roomInt = value; + if (this.roomInt != null) + { + this.roomInt.AddRegion(this); + } } } } @@ -182,9 +200,18 @@ public string DebugString stringBuilder.AppendLine("id: " + this.id); stringBuilder.AppendLine("mapIndex: " + this.mapIndex); stringBuilder.AppendLine("links count: " + this.links.Count); - foreach (RegionLink current in this.links) + List.Enumerator enumerator = this.links.GetEnumerator(); + try { - stringBuilder.AppendLine(" --" + current.ToString()); + while (enumerator.MoveNext()) + { + RegionLink current = enumerator.Current; + stringBuilder.AppendLine(" --" + current.ToString()); + } + } + finally + { + ((IDisposable)(object)enumerator).Dispose(); } stringBuilder.AppendLine("valid: " + this.valid.ToString()); stringBuilder.AppendLine("makeTick: " + this.debug_makeTick); @@ -249,13 +276,13 @@ public bool Allows(TraverseParms tp, bool isDestination) { return false; } - if (tp.maxDanger < Danger.Deadly && tp.pawn != null) + if ((int)tp.maxDanger < 3 && tp.pawn != null) { Danger danger = this.DangerFor(tp.pawn); if (isDestination || danger == Danger.Deadly) { Region region = tp.pawn.GetRegion(RegionType.Set_All); - if ((region == null || danger > region.DangerFor(tp.pawn)) && danger > tp.maxDanger) + if ((region == null || (int)danger > (int)region.DangerFor(tp.pawn)) && (int)danger > (int)tp.maxDanger) { return false; } @@ -265,30 +292,38 @@ public bool Allows(TraverseParms tp, bool isDestination) { case TraverseMode.ByPawn: { - if (this.portal == null) + if (this.portal != null) { - return true; - } - ByteGrid avoidGrid = tp.pawn.GetAvoidGrid(); - if (avoidGrid != null && avoidGrid[this.portal.Position] == 255) - { - return false; - } - if (tp.pawn.HostileTo(this.portal)) - { - return this.portal.CanPhysicallyPass(tp.pawn) || tp.canBash; + ByteGrid avoidGrid = tp.pawn.GetAvoidGrid(); + if (avoidGrid != null && avoidGrid[this.portal.Position] == 255) + { + return false; + } + if (tp.pawn.HostileTo(this.portal)) + { + return this.portal.CanPhysicallyPass(tp.pawn) || tp.canBash; + } + return this.portal.CanPhysicallyPass(tp.pawn) && !this.portal.IsForbiddenToPass(tp.pawn); } - return this.portal.CanPhysicallyPass(tp.pawn) && !this.portal.IsForbiddenToPass(tp.pawn); - } - case TraverseMode.PassDoors: return true; + } case TraverseMode.NoPassClosedDoors: + { return this.portal == null || this.portal.FreePassage; + } + case TraverseMode.PassDoors: + { + return true; + } case TraverseMode.PassAllDestroyableThings: + { return true; + } default: + { throw new NotImplementedException(); } + } } public Danger DangerFor(Pawn p) @@ -321,31 +356,20 @@ public AreaOverlap OverlapWith(Area a) { this.cachedAreaOverlaps = new Dictionary(); } - AreaOverlap areaOverlap; + AreaOverlap areaOverlap = default(AreaOverlap); if (!this.cachedAreaOverlaps.TryGetValue(a, out areaOverlap)) { int num = 0; int num2 = 0; - foreach (IntVec3 current in this.Cells) + foreach (IntVec3 cell in this.Cells) { num2++; - if (a[current]) + if (a[cell]) { num++; } } - if (num == 0) - { - areaOverlap = AreaOverlap.None; - } - else if (num == num2) - { - areaOverlap = AreaOverlap.Entire; - } - else - { - areaOverlap = AreaOverlap.Partial; - } + areaOverlap = (AreaOverlap)((num != 0) ? ((num == num2) ? 1 : 2) : 0); this.cachedAreaOverlaps.Add(a, areaOverlap); } return areaOverlap; @@ -353,11 +377,7 @@ public AreaOverlap OverlapWith(Area a) public void Notify_AreaChanged(Area a) { - if (this.cachedAreaOverlaps == null) - { - return; - } - if (this.cachedAreaOverlaps.ContainsKey(a)) + if (this.cachedAreaOverlaps != null && this.cachedAreaOverlaps.ContainsKey(a)) { this.cachedAreaOverlaps.Remove(a); } @@ -365,104 +385,84 @@ public void Notify_AreaChanged(Area a) public void DecrementMapIndex() { - if ((int)this.mapIndex <= 0) + if (this.mapIndex <= 0) { - Log.Warning(string.Concat(new object[] - { - "Tried to decrement map index for region ", - this.id, - ", but mapIndex=", - this.mapIndex - })); - return; - } - this.mapIndex -= 1; + Log.Warning("Tried to decrement map index for region " + this.id + ", but mapIndex=" + this.mapIndex); + } + else + { + this.mapIndex = (sbyte)(this.mapIndex - 1); + } } public void Notify_MyMapRemoved() { - this.mapIndex = -1; + this.mapIndex = (sbyte)(-1); } public override string ToString() { - string str; - if (this.portal != null) - { - str = this.portal.ToString(); - } - else - { - str = "null"; - } - return string.Concat(new object[] - { - "Region(id=", - this.id, - ", mapIndex=", - this.mapIndex, - ", center=", - this.extentsClose.CenterCell, - ", links=", - this.links.Count, - ", cells=", - this.CellCount, - (this.portal == null) ? null : (", portal=" + str), - ")" - }); + string str = (this.portal == null) ? "null" : this.portal.ToString(); + return "Region(id=" + this.id + ", mapIndex=" + this.mapIndex + ", center=" + this.extentsClose.CenterCell + ", links=" + this.links.Count + ", cells=" + this.CellCount + ((this.portal == null) ? null : (", portal=" + str)) + ")"; } public void DebugDraw() { if (DebugViewSettings.drawRegionTraversal && Find.TickManager.TicksGame < this.debug_lastTraverseTick + 60) { - float a = 1f - (float)(Find.TickManager.TicksGame - this.debug_lastTraverseTick) / 60f; - GenDraw.DrawFieldEdges(this.Cells.ToList(), new Color(0f, 0f, 1f, a)); + float a = (float)(1.0 - (float)(Find.TickManager.TicksGame - this.debug_lastTraverseTick) / 60.0); + GenDraw.DrawFieldEdges(this.Cells.ToList(), new Color(0f, 0f, 1f, a)); } } public void DebugDrawMouseover() { - int num = Mathf.RoundToInt(Time.realtimeSinceStartup * 2f) % 2; + int num = Mathf.RoundToInt((float)(Time.realtimeSinceStartup * 2.0)) % 2; if (DebugViewSettings.drawRegions) { - Color color; - if (!this.valid) + Color color = this.valid ? ((!this.DebugIsNew) ? Color.green : Color.yellow) : Color.red; + GenDraw.DrawFieldEdges(this.Cells.ToList(), color); + foreach (Region neighbor in this.Neighbors) { - color = Color.red; - } - else if (this.DebugIsNew) - { - color = Color.yellow; - } - else - { - color = Color.green; - } - GenDraw.DrawFieldEdges(this.Cells.ToList(), color); - foreach (Region current in this.Neighbors) - { - GenDraw.DrawFieldEdges(current.Cells.ToList(), Color.grey); + GenDraw.DrawFieldEdges(neighbor.Cells.ToList(), Color.grey); } } if (DebugViewSettings.drawRegionLinks) { - foreach (RegionLink current2 in this.links) + List.Enumerator enumerator2 = this.links.GetEnumerator(); + try { - if (num == 1) + while (enumerator2.MoveNext()) { - foreach (IntVec3 current3 in current2.span.Cells) + RegionLink current2 = enumerator2.Current; + if (num == 1) { - CellRenderer.RenderCell(current3, DebugSolidColorMats.MaterialOf(Color.magenta)); + foreach (IntVec3 cell in current2.span.Cells) + { + CellRenderer.RenderCell(cell, DebugSolidColorMats.MaterialOf(Color.magenta)); + } } } } + finally + { + ((IDisposable)(object)enumerator2).Dispose(); + } } if (DebugViewSettings.drawRegionThings) { - foreach (Thing current4 in this.listerThings.AllThings) + List.Enumerator enumerator4 = this.listerThings.AllThings.GetEnumerator(); + try + { + while (enumerator4.MoveNext()) + { + Thing current4 = enumerator4.Current; + CellRenderer.RenderSpot(current4.TrueCenter(), (float)((float)(current4.thingIDNumber % 256) / 256.0)); + } + } + finally { - CellRenderer.RenderSpot(current4.TrueCenter(), (float)(current4.thingIDNumber % 256) / 256f); + ((IDisposable)(object)enumerator4).Dispose(); } } } @@ -484,7 +484,11 @@ public override bool Equals(object obj) return false; } Region region = obj as Region; - return region != null && region.id == this.id; + if (region == null) + { + return false; + } + return region.id == this.id; } } } diff --git a/Assembly-CSharp/Verse/RegionAndRoomQuery.cs b/Assembly-CSharp/Verse/RegionAndRoomQuery.cs index b19bb1242..da2b8c659 100644 --- a/Assembly-CSharp/Verse/RegionAndRoomQuery.cs +++ b/Assembly-CSharp/Verse/RegionAndRoomQuery.cs @@ -1,5 +1,3 @@ -using System; - namespace Verse { public static class RegionAndRoomQuery @@ -11,7 +9,7 @@ public static Region RegionAt(IntVec3 c, Map map, RegionType allowedRegionTypes return null; } Region validRegionAt = map.regionGrid.GetValidRegionAt(c); - if (validRegionAt != null && (validRegionAt.type & allowedRegionTypes) != RegionType.None) + if (((validRegionAt != null) ? (validRegionAt.type & allowedRegionTypes) : RegionType.None) != 0) { return validRegionAt; } @@ -57,7 +55,7 @@ public static RoomGroup GetRoomGroup(this Thing thing) public static Room RoomAtFast(IntVec3 c, Map map, RegionType allowedRegionTypes = RegionType.Set_Passable) { Region validRegionAt = map.regionGrid.GetValidRegionAt(c); - if (validRegionAt != null && (validRegionAt.type & allowedRegionTypes) != RegionType.None) + if (((validRegionAt != null) ? (validRegionAt.type & allowedRegionTypes) : RegionType.None) != 0) { return validRegionAt.Room; } diff --git a/Assembly-CSharp/Verse/RegionAndRoomUpdater.cs b/Assembly-CSharp/Verse/RegionAndRoomUpdater.cs index b844aa57f..4df5d5e95 100644 --- a/Assembly-CSharp/Verse/RegionAndRoomUpdater.cs +++ b/Assembly-CSharp/Verse/RegionAndRoomUpdater.cs @@ -70,42 +70,43 @@ public void RebuildAllRegionsAndRooms() public void TryRebuildDirtyRegionsAndRooms() { - if (this.working || !this.Enabled) + if (!this.working && this.Enabled) { - return; - } - this.working = true; - if (!this.initialized) - { - this.RebuildAllRegionsAndRooms(); - } - if (!this.map.regionDirtyer.AnyDirty) - { - this.working = false; - return; - } - ProfilerThreadCheck.BeginSample("RebuildDirtyRegionsAndRooms"); - try - { - ProfilerThreadCheck.BeginSample("Regenerate new regions from dirty cells"); - this.RegenerateNewRegionsFromDirtyCells(); - ProfilerThreadCheck.EndSample(); - ProfilerThreadCheck.BeginSample("Create or update rooms"); - this.CreateOrUpdateRooms(); - ProfilerThreadCheck.EndSample(); - } - catch (Exception arg) - { - Log.Error("Exception while rebuilding dirty regions: " + arg); - } - this.newRegions.Clear(); - this.map.regionDirtyer.SetAllClean(); - this.initialized = true; - this.working = false; - ProfilerThreadCheck.EndSample(); - if (DebugSettings.detectRegionListersBugs) - { - Autotests_RegionListers.CheckBugs(this.map); + this.working = true; + if (!this.initialized) + { + this.RebuildAllRegionsAndRooms(); + } + if (!this.map.regionDirtyer.AnyDirty) + { + this.working = false; + } + else + { + ProfilerThreadCheck.BeginSample("RebuildDirtyRegionsAndRooms"); + try + { + ProfilerThreadCheck.BeginSample("Regenerate new regions from dirty cells"); + this.RegenerateNewRegionsFromDirtyCells(); + ProfilerThreadCheck.EndSample(); + ProfilerThreadCheck.BeginSample("Create or update rooms"); + this.CreateOrUpdateRooms(); + ProfilerThreadCheck.EndSample(); + } + catch (Exception arg) + { + Log.Error("Exception while rebuilding dirty regions: " + arg); + } + this.newRegions.Clear(); + this.map.regionDirtyer.SetAllClean(); + this.initialized = true; + this.working = false; + ProfilerThreadCheck.EndSample(); + if (DebugSettings.detectRegionListersBugs) + { + Autotests_RegionListers.CheckBugs(this.map); + } + } } } @@ -168,15 +169,15 @@ private int CombineNewRegionsIntoContiguousGroups() private void CreateOrAttachToExistingRooms(int numRegionGroups) { - for (int i = 0; i < numRegionGroups; i++) + for (int num = 0; num < numRegionGroups; num++) { ProfilerThreadCheck.BeginSample("Remake currentRegionGroup list"); this.currentRegionGroup.Clear(); - for (int j = 0; j < this.newRegions.Count; j++) + for (int i = 0; i < this.newRegions.Count; i++) { - if (this.newRegions[j].newRegionGroupIndex == i) + if (this.newRegions[i].newRegionGroupIndex == num) { - this.currentRegionGroup.Add(this.newRegions[j]); + this.currentRegionGroup.Add(this.newRegions[i]); } } ProfilerThreadCheck.EndSample(); @@ -193,7 +194,7 @@ private void CreateOrAttachToExistingRooms(int numRegionGroups) else { ProfilerThreadCheck.BeginSample("Determine neighboring old rooms"); - bool flag; + bool flag = default(bool); Room room2 = this.FindCurrentRegionGroupNeighborWithMostRegions(out flag); ProfilerThreadCheck.EndSample(); ProfilerThreadCheck.BeginSample("Apply final result"); @@ -204,9 +205,9 @@ private void CreateOrAttachToExistingRooms(int numRegionGroups) } else if (!flag) { - for (int k = 0; k < this.currentRegionGroup.Count; k++) + for (int j = 0; j < this.currentRegionGroup.Count; j++) { - this.currentRegionGroup[k].Room = room2; + this.currentRegionGroup[j].Room = room2; } this.reusedOldRooms.Add(room2); } @@ -223,28 +224,46 @@ private void CreateOrAttachToExistingRooms(int numRegionGroups) private int CombineNewAndReusedRoomsIntoContiguousGroups() { int num = 0; - foreach (Room current in this.reusedOldRooms) + HashSet.Enumerator enumerator = this.reusedOldRooms.GetEnumerator(); + try + { + while (enumerator.MoveNext()) + { + Room current = enumerator.Current; + current.newOrReusedRoomGroupIndex = -1; + } + } + finally { - current.newOrReusedRoomGroupIndex = -1; + ((IDisposable)(object)enumerator).Dispose(); } - foreach (Room current2 in this.reusedOldRooms.Concat(this.newRooms)) + foreach (Room item in this.reusedOldRooms.Concat(this.newRooms)) { - if (current2.newOrReusedRoomGroupIndex < 0) + if (item.newOrReusedRoomGroupIndex < 0) { this.tmpRoomStack.Clear(); - this.tmpRoomStack.Push(current2); - current2.newOrReusedRoomGroupIndex = num; + this.tmpRoomStack.Push(item); + item.newOrReusedRoomGroupIndex = num; while (this.tmpRoomStack.Count != 0) { Room room = this.tmpRoomStack.Pop(); - foreach (Room current3 in room.Neighbors) + List.Enumerator enumerator3 = room.Neighbors.GetEnumerator(); + try { - if (current3.newOrReusedRoomGroupIndex < 0 && this.ShouldBeInTheSameRoomGroup(room, current3)) + while (enumerator3.MoveNext()) { - current3.newOrReusedRoomGroupIndex = num; - this.tmpRoomStack.Push(current3); + Room current3 = enumerator3.Current; + if (current3.newOrReusedRoomGroupIndex < 0 && this.ShouldBeInTheSameRoomGroup(room, current3)) + { + current3.newOrReusedRoomGroupIndex = num; + this.tmpRoomStack.Push(current3); + } } } + finally + { + ((IDisposable)(object)enumerator3).Dispose(); + } } this.tmpRoomStack.Clear(); num++; @@ -255,27 +274,36 @@ private int CombineNewAndReusedRoomsIntoContiguousGroups() private void CreateOrAttachToExistingRoomGroups(int numRoomGroups) { - for (int i = 0; i < numRoomGroups; i++) + for (int num = 0; num < numRoomGroups; num++) { ProfilerThreadCheck.BeginSample("Remake currentRoomGroup list"); this.currentRoomGroup.Clear(); - foreach (Room current in this.reusedOldRooms) + HashSet.Enumerator enumerator = this.reusedOldRooms.GetEnumerator(); + try { - if (current.newOrReusedRoomGroupIndex == i) + while (enumerator.MoveNext()) { - this.currentRoomGroup.Add(current); + Room current = enumerator.Current; + if (current.newOrReusedRoomGroupIndex == num) + { + this.currentRoomGroup.Add(current); + } } } - for (int j = 0; j < this.newRooms.Count; j++) + finally { - if (this.newRooms[j].newOrReusedRoomGroupIndex == i) + ((IDisposable)(object)enumerator).Dispose(); + } + for (int i = 0; i < this.newRooms.Count; i++) + { + if (this.newRooms[i].newOrReusedRoomGroupIndex == num) { - this.currentRoomGroup.Add(this.newRooms[j]); + this.currentRoomGroup.Add(this.newRooms[i]); } } ProfilerThreadCheck.EndSample(); ProfilerThreadCheck.BeginSample("Determine neighboring old room groups"); - bool flag; + bool flag = default(bool); RoomGroup roomGroup = this.FindCurrentRoomGroupNeighborWithMostRegions(out flag); ProfilerThreadCheck.EndSample(); ProfilerThreadCheck.BeginSample("Apply final result"); @@ -287,9 +315,9 @@ private void CreateOrAttachToExistingRoomGroups(int numRoomGroups) } else if (!flag) { - for (int k = 0; k < this.currentRoomGroup.Count; k++) + for (int j = 0; j < this.currentRoomGroup.Count; j++) { - this.currentRoomGroup[k].Group = roomGroup; + this.currentRoomGroup[j].Group = roomGroup; } this.reusedOldRoomGroups.Add(roomGroup); } @@ -312,14 +340,23 @@ private void FloodAndSetRoomGroups(Room start, RoomGroup roomGroup) { Room room = this.tmpRoomStack.Pop(); room.Group = roomGroup; - foreach (Room current in room.Neighbors) + List.Enumerator enumerator = room.Neighbors.GetEnumerator(); + try { - if (!this.tmpVisitedRooms.Contains(current) && this.ShouldBeInTheSameRoomGroup(room, current)) + while (enumerator.MoveNext()) { - this.tmpRoomStack.Push(current); - this.tmpVisitedRooms.Add(current); + Room current = enumerator.Current; + if (!this.tmpVisitedRooms.Contains(current) && this.ShouldBeInTheSameRoomGroup(room, current)) + { + this.tmpRoomStack.Push(current); + this.tmpVisitedRooms.Add(current); + } } } + finally + { + ((IDisposable)(object)enumerator).Dispose(); + } } this.tmpVisitedRooms.Clear(); this.tmpRoomStack.Clear(); @@ -327,23 +364,41 @@ private void FloodAndSetRoomGroups(Room start, RoomGroup roomGroup) private void NotifyAffectedRoomsAndRoomGroupsAndUpdateTemperature() { - foreach (Room current in this.reusedOldRooms) + HashSet.Enumerator enumerator = this.reusedOldRooms.GetEnumerator(); + try + { + while (enumerator.MoveNext()) + { + Room current = enumerator.Current; + current.Notify_RoomShapeOrContainedBedsChanged(); + } + } + finally { - current.Notify_RoomShapeOrContainedBedsChanged(); + ((IDisposable)(object)enumerator).Dispose(); } for (int i = 0; i < this.newRooms.Count; i++) { this.newRooms[i].Notify_RoomShapeOrContainedBedsChanged(); } - foreach (RoomGroup current2 in this.reusedOldRoomGroups) + HashSet.Enumerator enumerator2 = this.reusedOldRoomGroups.GetEnumerator(); + try + { + while (enumerator2.MoveNext()) + { + RoomGroup current2 = enumerator2.Current; + current2.Notify_RoomGroupShapeChanged(); + } + } + finally { - current2.Notify_RoomGroupShapeChanged(); + ((IDisposable)(object)enumerator2).Dispose(); } for (int j = 0; j < this.newRoomGroups.Count; j++) { RoomGroup roomGroup = this.newRoomGroups[j]; roomGroup.Notify_RoomGroupShapeChanged(); - float temperature; + float temperature = default(float); if (this.map.temperatureCache.TryGetAverageCachedRoomGroupTemp(roomGroup, out temperature)) { roomGroup.Temperature = temperature; @@ -357,23 +412,20 @@ private Room FindCurrentRegionGroupNeighborWithMostRegions(out bool multipleOldN Room room = null; for (int i = 0; i < this.currentRegionGroup.Count; i++) { - foreach (Region current in this.currentRegionGroup[i].NeighborsOfSameType) + foreach (Region item in this.currentRegionGroup[i].NeighborsOfSameType) { - if (current.Room != null) + if (item.Room != null && !this.reusedOldRooms.Contains(item.Room)) { - if (!this.reusedOldRooms.Contains(current.Room)) + if (room == null) { - if (room == null) - { - room = current.Room; - } - else if (current.Room != room) + room = item.Room; + } + else if (item.Room != room) + { + multipleOldNeighborRooms = true; + if (item.Room.RegionCount > room.RegionCount) { - multipleOldNeighborRooms = true; - if (current.Room.RegionCount > room.RegionCount) - { - room = current.Room; - } + room = item.Room; } } } @@ -388,11 +440,13 @@ private RoomGroup FindCurrentRoomGroupNeighborWithMostRegions(out bool multipleO RoomGroup roomGroup = null; for (int i = 0; i < this.currentRoomGroup.Count; i++) { - foreach (Room current in this.currentRoomGroup[i].Neighbors) + List.Enumerator enumerator = this.currentRoomGroup[i].Neighbors.GetEnumerator(); + try { - if (current.Group != null && this.ShouldBeInTheSameRoomGroup(this.currentRoomGroup[i], current)) + while (enumerator.MoveNext()) { - if (!this.reusedOldRoomGroups.Contains(current.Group)) + Room current = enumerator.Current; + if (current.Group != null && this.ShouldBeInTheSameRoomGroup(this.currentRoomGroup[i], current) && !this.reusedOldRoomGroups.Contains(current.Group)) { if (roomGroup == null) { @@ -409,6 +463,10 @@ private RoomGroup FindCurrentRoomGroupNeighborWithMostRegions(out bool multipleO } } } + finally + { + ((IDisposable)(object)enumerator).Dispose(); + } } return roomGroup; } diff --git a/Assembly-CSharp/Verse/RegionDirtyer.cs b/Assembly-CSharp/Verse/RegionDirtyer.cs index 7aabb99f2..619b5bce9 100644 --- a/Assembly-CSharp/Verse/RegionDirtyer.cs +++ b/Assembly-CSharp/Verse/RegionDirtyer.cs @@ -1,4 +1,3 @@ -using System; using System.Collections.Generic; namespace Verse @@ -90,14 +89,14 @@ internal void Notify_ThingAffectingRegionsDespawned(Thing b) this.map.temperatureCache.TryCacheRegionTempInfo(b.Position, validRegionAt_NoRebuild); this.regionsToDirty.Add(validRegionAt_NoRebuild); } - foreach (IntVec3 current in GenAdj.CellsAdjacent8Way(b)) + foreach (IntVec3 item2 in GenAdj.CellsAdjacent8Way(b)) { - if (current.InBounds(this.map)) + if (item2.InBounds(this.map)) { - Region validRegionAt_NoRebuild2 = this.map.regionGrid.GetValidRegionAt_NoRebuild(current); + Region validRegionAt_NoRebuild2 = this.map.regionGrid.GetValidRegionAt_NoRebuild(item2); if (validRegionAt_NoRebuild2 != null) { - this.map.temperatureCache.TryCacheRegionTempInfo(current, validRegionAt_NoRebuild2); + this.map.temperatureCache.TryCacheRegionTempInfo(item2, validRegionAt_NoRebuild2); this.regionsToDirty.Add(validRegionAt_NoRebuild2); } } @@ -136,25 +135,24 @@ internal void SetAllClean() private void SetRegionDirty(Region reg, bool addCellsToDirtyCells = true) { - if (!reg.valid) + if (reg.valid) { - return; - } - reg.valid = false; - reg.Room = null; - for (int i = 0; i < reg.links.Count; i++) - { - reg.links[i].Deregister(reg); - } - reg.links.Clear(); - if (addCellsToDirtyCells) - { - foreach (IntVec3 current in reg.Cells) + reg.valid = false; + reg.Room = null; + for (int i = 0; i < reg.links.Count; i++) + { + reg.links[i].Deregister(reg); + } + reg.links.Clear(); + if (addCellsToDirtyCells) { - this.dirtyCells.Add(current); - if (DebugViewSettings.drawRegionDirties) + foreach (IntVec3 cell in reg.Cells) { - this.map.debugDrawer.FlashCell(current, 0f, null); + this.dirtyCells.Add(cell); + if (DebugViewSettings.drawRegionDirties) + { + this.map.debugDrawer.FlashCell(cell, 0f, (string)null); + } } } } @@ -163,13 +161,13 @@ private void SetRegionDirty(Region reg, bool addCellsToDirtyCells = true) internal void SetAllDirty() { this.dirtyCells.Clear(); - foreach (IntVec3 current in this.map) + foreach (IntVec3 item in this.map) { - this.dirtyCells.Add(current); + this.dirtyCells.Add(item); } - foreach (Region current2 in this.map.regionGrid.AllRegions_NoRebuild_InvalidAllowed) + foreach (Region item2 in this.map.regionGrid.AllRegions_NoRebuild_InvalidAllowed) { - this.SetRegionDirty(current2, false); + this.SetRegionDirty(item2, false); } } } diff --git a/Assembly-CSharp/Verse/RegionEntryPredicate.cs b/Assembly-CSharp/Verse/RegionEntryPredicate.cs index 1d918f959..a86fe7b37 100644 --- a/Assembly-CSharp/Verse/RegionEntryPredicate.cs +++ b/Assembly-CSharp/Verse/RegionEntryPredicate.cs @@ -1,5 +1,3 @@ -using System; - namespace Verse { public delegate bool RegionEntryPredicate(Region from, Region to); diff --git a/Assembly-CSharp/Verse/RegionGrid.cs b/Assembly-CSharp/Verse/RegionGrid.cs index 775949805..7299a4f7e 100644 --- a/Assembly-CSharp/Verse/RegionGrid.cs +++ b/Assembly-CSharp/Verse/RegionGrid.cs @@ -1,4 +1,3 @@ -using System; using System.Collections.Generic; namespace Verse @@ -36,11 +35,23 @@ public IEnumerable AllRegions_NoRebuild_InvalidAllowed { get { - RegionGrid.<>c__Iterator202 <>c__Iterator = new RegionGrid.<>c__Iterator202(); - <>c__Iterator.<>f__this = this; - RegionGrid.<>c__Iterator202 expr_0E = <>c__Iterator; - expr_0E.$PC = -2; - return expr_0E; + RegionGrid.allRegionsYielded.Clear(); + try + { + int count = this.map.cellIndices.NumGridCells; + for (int i = 0; i < count; i++) + { + if (this.regionGrid[i] != null && !RegionGrid.allRegionsYielded.Contains(this.regionGrid[i])) + { + yield return this.regionGrid[i]; + RegionGrid.allRegionsYielded.Add(this.regionGrid[i]); + } + } + } + finally + { + ((_003C_003Ec__Iterator202)/*Error near IL_0106: stateMachine*/)._003C_003E__Finally0(); + } } } @@ -48,11 +59,28 @@ public IEnumerable AllRegions { get { - RegionGrid.<>c__Iterator203 <>c__Iterator = new RegionGrid.<>c__Iterator203(); - <>c__Iterator.<>f__this = this; - RegionGrid.<>c__Iterator203 expr_0E = <>c__Iterator; - expr_0E.$PC = -2; - return expr_0E; + if (!this.map.regionAndRoomUpdater.Enabled && this.map.regionAndRoomUpdater.AnythingToRebuild) + { + Log.Warning("Trying to get all valid regions but RegionAndRoomUpdater is disabled. The result may be incorrect."); + } + this.map.regionAndRoomUpdater.TryRebuildDirtyRegionsAndRooms(); + RegionGrid.allRegionsYielded.Clear(); + try + { + int count = this.map.cellIndices.NumGridCells; + for (int i = 0; i < count; i++) + { + if (this.regionGrid[i] != null && this.regionGrid[i].valid && !RegionGrid.allRegionsYielded.Contains(this.regionGrid[i])) + { + yield return this.regionGrid[i]; + RegionGrid.allRegionsYielded.Add(this.regionGrid[i]); + } + } + } + finally + { + ((_003C_003Ec__Iterator203)/*Error near IL_0175: stateMachine*/)._003C_003E__Finally0(); + } } } @@ -126,46 +154,44 @@ public void UpdateClean() public void DebugDraw() { - if (this.map != Find.VisibleMap) - { - return; - } - if (DebugViewSettings.drawRegionTraversal) + if (this.map == Find.VisibleMap) { - CellRect currentViewRect = Find.CameraDriver.CurrentViewRect; - currentViewRect.ClipInsideMap(this.map); - foreach (IntVec3 current in currentViewRect) + if (DebugViewSettings.drawRegionTraversal) { - Region validRegionAt = this.GetValidRegionAt(current); - if (validRegionAt != null && !this.drawnRegions.Contains(validRegionAt)) + CellRect currentViewRect = Find.CameraDriver.CurrentViewRect; + currentViewRect.ClipInsideMap(this.map); + foreach (IntVec3 item in currentViewRect) { - validRegionAt.DebugDraw(); - this.drawnRegions.Add(validRegionAt); + Region validRegionAt = this.GetValidRegionAt(item); + if (validRegionAt != null && !this.drawnRegions.Contains(validRegionAt)) + { + validRegionAt.DebugDraw(); + this.drawnRegions.Add(validRegionAt); + } } + this.drawnRegions.Clear(); } - this.drawnRegions.Clear(); - } - IntVec3 intVec = UI.MouseCell(); - if (intVec.InBounds(this.map)) - { - if (DebugViewSettings.drawRooms) + IntVec3 intVec = UI.MouseCell(); + if (intVec.InBounds(this.map)) { - Room room = intVec.GetRoom(this.map, RegionType.Set_All); - if (room != null) + if (DebugViewSettings.drawRooms) { - room.DebugDraw(); + Room room = intVec.GetRoom(this.map, RegionType.Set_All); + if (room != null) + { + room.DebugDraw(); + } } - } - if (DebugViewSettings.drawRoomGroups) - { - RoomGroup roomGroup = intVec.GetRoomGroup(this.map); - if (roomGroup != null) + if (DebugViewSettings.drawRoomGroups) { - roomGroup.DebugDraw(); + RoomGroup roomGroup = intVec.GetRoomGroup(this.map); + if (roomGroup != null) + { + roomGroup.DebugDraw(); + } } - } - if (DebugViewSettings.drawRegions || DebugViewSettings.drawRegionLinks || DebugViewSettings.drawRegionThings) - { + if (!DebugViewSettings.drawRegions && !DebugViewSettings.drawRegionLinks && !DebugViewSettings.drawRegionThings) + return; Region regionAt_NoRebuild_InvalidAllowed = this.GetRegionAt_NoRebuild_InvalidAllowed(intVec); if (regionAt_NoRebuild_InvalidAllowed != null) { diff --git a/Assembly-CSharp/Verse/RegionLink.cs b/Assembly-CSharp/Verse/RegionLink.cs index 9dc405acf..a234729d1 100644 --- a/Assembly-CSharp/Verse/RegionLink.cs +++ b/Assembly-CSharp/Verse/RegionLink.cs @@ -37,16 +37,9 @@ public void Register(Region reg) { if (this.regions[0] == reg || this.regions[1] == reg) { - Log.Error(string.Concat(new object[] - { - "Tried to double-register region ", - reg.ToString(), - " in ", - this - })); - return; + Log.Error("Tried to double-register region " + reg.ToString() + " in " + this); } - if (this.RegionA == null || !this.RegionA.valid) + else if (this.RegionA == null || !this.RegionA.valid) { this.RegionA = reg; } @@ -56,17 +49,7 @@ public void Register(Region reg) } else { - Log.Error(string.Concat(new object[] - { - "Could not register region ", - reg.ToString(), - " in link ", - this, - ": > 2 regions on link!\nRegionA: ", - this.RegionA.DebugString, - "\nRegionB: ", - this.RegionB.DebugString - })); + Log.Error("Could not register region " + reg.ToString() + " in link " + this + ": > 2 regions on link!\nRegionA: " + this.RegionA.DebugString + "\nRegionB: " + this.RegionB.DebugString); } } @@ -105,21 +88,8 @@ public override string ToString() string text = GenText.ToCommaList(from r in this.regions where r != null select r.id.ToString(), true); - string text2 = string.Concat(new object[] - { - "span=", - this.span.ToString(), - " hash=", - this.UniqueHashCode() - }); - return string.Concat(new string[] - { - "(", - text2, - ", regions=", - text, - ")" - }); + string text2 = "span=" + this.span.ToString() + " hash=" + this.UniqueHashCode(); + return "(" + text2 + ", regions=" + text + ")"; } } } diff --git a/Assembly-CSharp/Verse/RegionLinkDatabase.cs b/Assembly-CSharp/Verse/RegionLinkDatabase.cs index c986b0bda..ef554ef60 100644 --- a/Assembly-CSharp/Verse/RegionLinkDatabase.cs +++ b/Assembly-CSharp/Verse/RegionLinkDatabase.cs @@ -11,7 +11,7 @@ public class RegionLinkDatabase public RegionLink LinkFrom(EdgeSpan span) { ulong key = span.UniqueHashCode(); - RegionLink regionLink; + RegionLink regionLink = default(RegionLink); if (!this.links.TryGetValue(key, out regionLink)) { regionLink = new RegionLink(); @@ -29,9 +29,17 @@ public void Notify_LinkHasNoRegions(RegionLink link) public void DebugLog() { StringBuilder stringBuilder = new StringBuilder(); - foreach (KeyValuePair current in this.links) + Dictionary.Enumerator enumerator = this.links.GetEnumerator(); + try { - stringBuilder.AppendLine(current.ToString()); + while (enumerator.MoveNext()) + { + stringBuilder.AppendLine(enumerator.Current.ToString()); + } + } + finally + { + ((IDisposable)(object)enumerator).Dispose(); } Log.Message(stringBuilder.ToString()); } diff --git a/Assembly-CSharp/Verse/RegionListersUpdater.cs b/Assembly-CSharp/Verse/RegionListersUpdater.cs index 3fdd1decc..69bd3bfe2 100644 --- a/Assembly-CSharp/Verse/RegionListersUpdater.cs +++ b/Assembly-CSharp/Verse/RegionListersUpdater.cs @@ -1,4 +1,3 @@ -using System; using System.Collections.Generic; using Verse.AI; @@ -11,36 +10,34 @@ public static class RegionListersUpdater public static void DeregisterInRegions(Thing thing, Map map) { ThingDef def = thing.def; - if (!ListerThings.EverListable(def, ListerThingsUse.Region)) + if (ListerThings.EverListable(def, ListerThingsUse.Region)) { - return; - } - RegionListersUpdater.GetTouchableRegions(thing, map, RegionListersUpdater.tmpRegions, true); - for (int i = 0; i < RegionListersUpdater.tmpRegions.Count; i++) - { - ListerThings listerThings = RegionListersUpdater.tmpRegions[i].ListerThings; - if (listerThings.Contains(thing)) + RegionListersUpdater.GetTouchableRegions(thing, map, RegionListersUpdater.tmpRegions, true); + for (int i = 0; i < RegionListersUpdater.tmpRegions.Count; i++) { - listerThings.Remove(thing); + ListerThings listerThings = RegionListersUpdater.tmpRegions[i].ListerThings; + if (listerThings.Contains(thing)) + { + listerThings.Remove(thing); + } } + RegionListersUpdater.tmpRegions.Clear(); } - RegionListersUpdater.tmpRegions.Clear(); } public static void RegisterInRegions(Thing thing, Map map) { ThingDef def = thing.def; - if (!ListerThings.EverListable(def, ListerThingsUse.Region)) + if (ListerThings.EverListable(def, ListerThingsUse.Region)) { - return; - } - RegionListersUpdater.GetTouchableRegions(thing, map, RegionListersUpdater.tmpRegions, false); - for (int i = 0; i < RegionListersUpdater.tmpRegions.Count; i++) - { - ListerThings listerThings = RegionListersUpdater.tmpRegions[i].ListerThings; - if (!listerThings.Contains(thing)) + RegionListersUpdater.GetTouchableRegions(thing, map, RegionListersUpdater.tmpRegions, false); + for (int i = 0; i < RegionListersUpdater.tmpRegions.Count; i++) { - listerThings.Add(thing); + ListerThings listerThings = RegionListersUpdater.tmpRegions[i].ListerThings; + if (!listerThings.Contains(thing)) + { + listerThings.Add(thing); + } } } } @@ -49,9 +46,9 @@ public static void RegisterAllAt(IntVec3 c, Map map, HashSet processedThi { List thingList = c.GetThingList(map); int count = thingList.Count; - for (int i = 0; i < count; i++) + for (int num = 0; num < count; num++) { - Thing thing = thingList[i]; + Thing thing = thingList[num]; if (processedThings == null || processedThings.Add(thing)) { RegionListersUpdater.RegisterInRegions(thing, map); @@ -62,13 +59,13 @@ public static void RegisterAllAt(IntVec3 c, Map map, HashSet processedThi public static void GetTouchableRegions(Thing thing, Map map, List outRegions, bool allowAdjacentEvenIfCantTouch = false) { outRegions.Clear(); - CellRect cellRect = thing.OccupiedRect(); - CellRect cellRect2 = cellRect; + CellRect cellRect; + CellRect cellRect2 = cellRect = thing.OccupiedRect(); if (RegionListersUpdater.CanRegisterInAdjacentRegions(thing)) { - cellRect2 = cellRect2.ExpandedBy(1); + cellRect = cellRect.ExpandedBy(1); } - CellRect.CellRectIterator iterator = cellRect2.GetIterator(); + CellRect.CellRectIterator iterator = cellRect.GetIterator(); while (!iterator.Done()) { IntVec3 current = iterator.Current; @@ -77,7 +74,7 @@ public static void GetTouchableRegions(Thing thing, Map map, List outReg Region validRegionAt_NoRebuild = map.regionGrid.GetValidRegionAt_NoRebuild(current); if (validRegionAt_NoRebuild != null && validRegionAt_NoRebuild.type.Passable() && !outRegions.Contains(validRegionAt_NoRebuild)) { - if (cellRect.Contains(current)) + if (cellRect2.Contains(current)) { outRegions.Add(validRegionAt_NoRebuild); } diff --git a/Assembly-CSharp/Verse/RegionMaker.cs b/Assembly-CSharp/Verse/RegionMaker.cs index b1f44c013..d659f122c 100644 --- a/Assembly-CSharp/Verse/RegionMaker.cs +++ b/Assembly-CSharp/Verse/RegionMaker.cs @@ -13,7 +13,7 @@ public class RegionMaker private bool working; - private HashSet[] linksProcessedAt = new HashSet[] + private HashSet[] linksProcessedAt = new HashSet[4] { new HashSet(), new HashSet(), @@ -43,7 +43,6 @@ public Region TryGenerateRegionFrom(IntVec3 root) return null; } this.working = true; - Region result; try { this.regionGrid = this.map.regionGrid; @@ -56,13 +55,15 @@ public Region TryGenerateRegionFrom(IntVec3 root) this.FloodFillAndAddCells(root); this.CreateLinks(); this.RegisterThingsInRegionListers(); - result = this.newReg; + return this.newReg; + IL_00a9: + Region result; + return result; } finally { this.working = false; } - return result; } private void FloodFillAndAddCells(IntVec3 root) @@ -74,7 +75,7 @@ private void FloodFillAndAddCells(IntVec3 root) } else { - this.map.floodFiller.FloodFill(root, (IntVec3 x) => this.newReg.extentsLimit.Contains(x) && x.GetExpectedRegionType(this.map) == this.newReg.type, delegate(IntVec3 x) + this.map.floodFiller.FloodFill(root, (Predicate)((IntVec3 x) => this.newReg.extentsLimit.Contains(x) && x.GetExpectedRegionType(this.map) == this.newReg.type), (Action)delegate(IntVec3 x) { this.AddCell(x); }, false); @@ -101,10 +102,19 @@ private void AddCell(IntVec3 c) { this.newReg.extentsClose.maxZ = c.z; } - if (c.x == 0 || c.x == this.map.Size.x - 1 || c.z == 0 || c.z == this.map.Size.z - 1) + if (c.x != 0) { - this.newReg.touchesMapEdge = true; + int x = c.x; + IntVec3 size = this.map.Size; + if (((x != size.x - 1) ? c.z : 0) != 0) + { + int z = c.z; + IntVec3 size2 = this.map.Size; + if (z != size2.z - 1) + return; + } } + this.newReg.touchesMapEdge = true; } private void CreateLinks() @@ -125,88 +135,85 @@ private void CreateLinks() private void SweepInTwoDirectionsAndTryToCreateLink(Rot4 potentialOtherRegionDir, IntVec3 c) { - if (!potentialOtherRegionDir.IsValid) - { - return; - } - HashSet hashSet = this.linksProcessedAt[potentialOtherRegionDir.AsInt]; - if (hashSet.Contains(c)) - { - return; - } - IntVec3 c2 = c + potentialOtherRegionDir.FacingCell; - if (c2.InBounds(this.map) && this.regionGrid.GetRegionAt_NoRebuild_InvalidAllowed(c2) == this.newReg) - { - return; - } - RegionType expectedRegionType = c2.GetExpectedRegionType(this.map); - if (expectedRegionType == RegionType.None) - { - return; - } - Rot4 rot = potentialOtherRegionDir; - rot.Rotate(RotationDirection.Clockwise); - int num = 0; - int num2 = 0; - hashSet.Add(c); - if (!expectedRegionType.IsOneCellRegion()) + if (potentialOtherRegionDir.IsValid) { - while (true) + HashSet hashSet = this.linksProcessedAt[potentialOtherRegionDir.AsInt]; + if (!hashSet.Contains(c)) { - IntVec3 intVec = c + rot.FacingCell * (num + 1); - if (!intVec.InBounds(this.map) || this.regionGrid.GetRegionAt_NoRebuild_InvalidAllowed(intVec) != this.newReg || (intVec + potentialOtherRegionDir.FacingCell).GetExpectedRegionType(this.map) != expectedRegionType) + IntVec3 c2 = c + potentialOtherRegionDir.FacingCell; + if (c2.InBounds(this.map) && this.regionGrid.GetRegionAt_NoRebuild_InvalidAllowed(c2) == this.newReg) + return; + RegionType expectedRegionType = c2.GetExpectedRegionType(this.map); + if (expectedRegionType != 0) { - break; - } - if (!hashSet.Add(intVec)) - { - Log.Error("We've processed the same cell twice."); - } - num++; - } - while (true) - { - IntVec3 intVec2 = c - rot.FacingCell * (num2 + 1); - if (!intVec2.InBounds(this.map) || this.regionGrid.GetRegionAt_NoRebuild_InvalidAllowed(intVec2) != this.newReg || (intVec2 + potentialOtherRegionDir.FacingCell).GetExpectedRegionType(this.map) != expectedRegionType) - { - break; - } - if (!hashSet.Add(intVec2)) - { - Log.Error("We've processed the same cell twice."); + Rot4 rot = potentialOtherRegionDir; + rot.Rotate(RotationDirection.Clockwise); + int num = 0; + int num2 = 0; + hashSet.Add(c); + if (!expectedRegionType.IsOneCellRegion()) + { + while (true) + { + IntVec3 intVec = c + rot.FacingCell * (num + 1); + if (intVec.InBounds(this.map) && this.regionGrid.GetRegionAt_NoRebuild_InvalidAllowed(intVec) == this.newReg && (intVec + potentialOtherRegionDir.FacingCell).GetExpectedRegionType(this.map) == expectedRegionType) + { + if (!hashSet.Add(intVec)) + { + Log.Error("We've processed the same cell twice."); + } + num++; + continue; + } + break; + } + while (true) + { + IntVec3 intVec2 = c - rot.FacingCell * (num2 + 1); + if (intVec2.InBounds(this.map) && this.regionGrid.GetRegionAt_NoRebuild_InvalidAllowed(intVec2) == this.newReg && (intVec2 + potentialOtherRegionDir.FacingCell).GetExpectedRegionType(this.map) == expectedRegionType) + { + if (!hashSet.Add(intVec2)) + { + Log.Error("We've processed the same cell twice."); + } + num2++; + continue; + } + break; + } + } + int length = num + num2 + 1; + SpanDirection dir; + IntVec3 root; + if (potentialOtherRegionDir == Rot4.North) + { + dir = SpanDirection.East; + root = c - rot.FacingCell * num2; + root.z++; + } + else if (potentialOtherRegionDir == Rot4.South) + { + dir = SpanDirection.East; + root = c + rot.FacingCell * num; + } + else if (potentialOtherRegionDir == Rot4.East) + { + dir = SpanDirection.North; + root = c + rot.FacingCell * num; + root.x++; + } + else + { + dir = SpanDirection.North; + root = c - rot.FacingCell * num2; + } + EdgeSpan span = new EdgeSpan(root, dir, length); + RegionLink regionLink = this.map.regionLinkDatabase.LinkFrom(span); + regionLink.Register(this.newReg); + this.newReg.links.Add(regionLink); } - num2++; } } - int length = num + num2 + 1; - SpanDirection dir; - IntVec3 root; - if (potentialOtherRegionDir == Rot4.North) - { - dir = SpanDirection.East; - root = c - rot.FacingCell * num2; - root.z++; - } - else if (potentialOtherRegionDir == Rot4.South) - { - dir = SpanDirection.East; - root = c + rot.FacingCell * num; - } - else if (potentialOtherRegionDir == Rot4.East) - { - dir = SpanDirection.North; - root = c + rot.FacingCell * num; - root.x++; - } - else - { - dir = SpanDirection.North; - root = c - rot.FacingCell * num2; - } - EdgeSpan span = new EdgeSpan(root, dir, length); - RegionLink regionLink = this.map.regionLinkDatabase.LinkFrom(span); - regionLink.Register(this.newReg); - this.newReg.links.Add(regionLink); } private void RegisterThingsInRegionListers() @@ -223,13 +230,10 @@ private void RegisterThingsInRegionListers() for (int i = 0; i < 9; i++) { IntVec3 c = current + GenAdj.AdjacentCellsAndInside[i]; - if (c.InBounds(this.map)) + if (c.InBounds(this.map) && this.regionGrid.GetValidRegionAt(c) == this.newReg) { - if (this.regionGrid.GetValidRegionAt(c) == this.newReg) - { - flag = true; - break; - } + flag = true; + break; } } if (flag) diff --git a/Assembly-CSharp/Verse/RegionProcessor.cs b/Assembly-CSharp/Verse/RegionProcessor.cs index 4374e0149..7edcfb7c5 100644 --- a/Assembly-CSharp/Verse/RegionProcessor.cs +++ b/Assembly-CSharp/Verse/RegionProcessor.cs @@ -1,5 +1,3 @@ -using System; - namespace Verse { public delegate bool RegionProcessor(Region reg); diff --git a/Assembly-CSharp/Verse/RegionTraverser.cs b/Assembly-CSharp/Verse/RegionTraverser.cs index daec90678..fe5cf0994 100644 --- a/Assembly-CSharp/Verse/RegionTraverser.cs +++ b/Assembly-CSharp/Verse/RegionTraverser.cs @@ -41,67 +41,66 @@ private void FinalizeSearch() public void BreadthFirstTraverseWork(Region root, RegionEntryPredicate entryCondition, RegionProcessor regionProcessor, int maxRegions, RegionType traversableRegionTypes) { - if ((root.type & traversableRegionTypes) == RegionType.None) + if ((root.type & traversableRegionTypes) != 0) { - return; - } - ProfilerThreadCheck.BeginSample("BreadthFirstTraversal"); - this.closedIndex += 1u; - this.open.Clear(); - this.numRegionsProcessed = 0; - this.QueueNewOpenRegion(root); - while (this.open.Count > 0) - { - Region region = this.open.Dequeue(); - if (DebugViewSettings.drawRegionTraversal) - { - region.Debug_Notify_Traversed(); - } - ProfilerThreadCheck.BeginSample("regionProcessor"); - if (regionProcessor != null && regionProcessor(region)) - { - this.FinalizeSearch(); - ProfilerThreadCheck.EndSample(); - ProfilerThreadCheck.EndSample(); - return; - } - ProfilerThreadCheck.EndSample(); - this.numRegionsProcessed++; - if (this.numRegionsProcessed >= maxRegions) + ProfilerThreadCheck.BeginSample("BreadthFirstTraversal"); + this.closedIndex += 1u; + this.open.Clear(); + this.numRegionsProcessed = 0; + this.QueueNewOpenRegion(root); + while (this.open.Count > 0) { - this.FinalizeSearch(); + Region region = this.open.Dequeue(); + if (DebugViewSettings.drawRegionTraversal) + { + region.Debug_Notify_Traversed(); + } + ProfilerThreadCheck.BeginSample("regionProcessor"); + if ((object)regionProcessor != null && regionProcessor(region)) + { + this.FinalizeSearch(); + ProfilerThreadCheck.EndSample(); + ProfilerThreadCheck.EndSample(); + return; + } ProfilerThreadCheck.EndSample(); - return; - } - for (int i = 0; i < region.links.Count; i++) - { - RegionLink regionLink = region.links[i]; - for (int j = 0; j < 2; j++) + this.numRegionsProcessed++; + if (this.numRegionsProcessed >= maxRegions) + { + this.FinalizeSearch(); + ProfilerThreadCheck.EndSample(); + return; + } + for (int i = 0; i < region.links.Count; i++) { - Region region2 = regionLink.regions[j]; - if (region2 != null && region2.closedIndex[this.closedArrayPos] != this.closedIndex && (region2.type & traversableRegionTypes) != RegionType.None && (entryCondition == null || entryCondition(region, region2))) + RegionLink regionLink = region.links[i]; + for (int j = 0; j < 2; j++) { - this.QueueNewOpenRegion(region2); + Region region2 = regionLink.regions[j]; + if (region2 != null && region2.closedIndex[this.closedArrayPos] != this.closedIndex && (region2.type & traversableRegionTypes) != 0 && ((object)entryCondition == null || entryCondition(region, region2))) + { + this.QueueNewOpenRegion(region2); + } } } } + this.FinalizeSearch(); + ProfilerThreadCheck.EndSample(); } - this.FinalizeSearch(); - ProfilerThreadCheck.EndSample(); } } - private static Queue freeWorkers; + private static Queue freeWorkers; public static int NumWorkers; static RegionTraverser() { - RegionTraverser.freeWorkers = new Queue(); + RegionTraverser.freeWorkers = new Queue(); RegionTraverser.NumWorkers = 8; for (int i = 0; i < RegionTraverser.NumWorkers; i++) { - RegionTraverser.freeWorkers.Enqueue(new RegionTraverser.BFSWorker(i)); + RegionTraverser.freeWorkers.Enqueue(new BFSWorker(i)); } } @@ -121,8 +120,8 @@ public static Room FloodAndSetRooms(Region root, Map map, Room existingRoom) { return floodingRoom; } - RegionEntryPredicate entryCondition = (Region from, Region r) => r.type == root.type && r.Room != floodingRoom; - RegionProcessor regionProcessor = delegate(Region r) + RegionEntryPredicate entryCondition = (RegionEntryPredicate)((Region from, Region r) => r.type == root.type && r.Room != floodingRoom); + RegionProcessor regionProcessor = (RegionProcessor)delegate(Region r) { r.Room = floodingRoom; return false; @@ -134,17 +133,16 @@ public static Room FloodAndSetRooms(Region root, Map map, Room existingRoom) public static void FloodAndSetNewRegionIndex(Region root, int newRegionGroupIndex) { root.newRegionGroupIndex = newRegionGroupIndex; - if (!root.type.AllowsMultipleRegionsPerRoom()) + if (root.type.AllowsMultipleRegionsPerRoom()) { - return; + RegionEntryPredicate entryCondition = (RegionEntryPredicate)((Region from, Region r) => r.type == root.type && r.newRegionGroupIndex < 0); + RegionProcessor regionProcessor = (RegionProcessor)delegate(Region r) + { + r.newRegionGroupIndex = newRegionGroupIndex; + return false; + }; + RegionTraverser.BreadthFirstTraverse(root, entryCondition, regionProcessor, 999999, RegionType.Set_All); } - RegionEntryPredicate entryCondition = (Region from, Region r) => r.type == root.type && r.newRegionGroupIndex < 0; - RegionProcessor regionProcessor = delegate(Region r) - { - r.newRegionGroupIndex = newRegionGroupIndex; - return false; - }; - RegionTraverser.BreadthFirstTraverse(root, entryCondition, regionProcessor, 999999, RegionType.Set_All); } public static bool WithinRegions(this IntVec3 A, IntVec3 B, Map map, int regionLookCount, TraverseParms traverseParams, RegionType traversableRegionTypes = RegionType.Set_Passable) @@ -167,9 +165,9 @@ public static bool WithinRegions(this IntVec3 A, IntVec3 B, Map map, int regionL { return true; } - RegionEntryPredicate entryCondition = (Region from, Region r) => r.Allows(traverseParams, false); + RegionEntryPredicate entryCondition = (RegionEntryPredicate)((Region from, Region r) => r.Allows(traverseParams, false)); bool found = false; - RegionProcessor regionProcessor = delegate(Region r) + RegionProcessor regionProcessor = (RegionProcessor)delegate(Region r) { if (r == regB) { @@ -184,7 +182,7 @@ public static bool WithinRegions(this IntVec3 A, IntVec3 B, Map map, int regionL public static void MarkRegionsBFS(Region root, RegionEntryPredicate entryCondition, int maxRegions, int inRadiusMark, RegionType traversableRegionTypes = RegionType.Set_Passable) { - RegionTraverser.BreadthFirstTraverse(root, entryCondition, delegate(Region r) + RegionTraverser.BreadthFirstTraverse(root, entryCondition, (RegionProcessor)delegate(Region r) { r.mark = inRadiusMark; return false; @@ -194,11 +192,10 @@ public static void MarkRegionsBFS(Region root, RegionEntryPredicate entryConditi public static void BreadthFirstTraverse(IntVec3 start, Map map, RegionEntryPredicate entryCondition, RegionProcessor regionProcessor, int maxRegions = 999999, RegionType traversableRegionTypes = RegionType.Set_Passable) { Region region = start.GetRegion(map, traversableRegionTypes); - if (region == null) + if (region != null) { - return; + RegionTraverser.BreadthFirstTraverse(region, entryCondition, regionProcessor, maxRegions, traversableRegionTypes); } - RegionTraverser.BreadthFirstTraverse(region, entryCondition, regionProcessor, maxRegions, traversableRegionTypes); } public static void BreadthFirstTraverse(Region root, RegionEntryPredicate entryCondition, RegionProcessor regionProcessor, int maxRegions = 999999, RegionType traversableRegionTypes = RegionType.Set_Passable) @@ -206,26 +203,27 @@ public static void BreadthFirstTraverse(Region root, RegionEntryPredicate entryC if (RegionTraverser.freeWorkers.Count == 0) { Log.Error("No free workers for breadth-first traversal. Either BFS recurred deeper than " + RegionTraverser.NumWorkers + ", or a bug has put this system in an inconsistent state. Resetting."); - return; } - if (root == null) + else if (root == null) { Log.Error("BreadthFirstTraverse with null root region."); - return; - } - RegionTraverser.BFSWorker bFSWorker = RegionTraverser.freeWorkers.Dequeue(); - try - { - bFSWorker.BreadthFirstTraverseWork(root, entryCondition, regionProcessor, maxRegions, traversableRegionTypes); } - catch (Exception ex) - { - Log.Error("Exception in BreadthFirstTraverse: " + ex.ToString()); - } - finally + else { - bFSWorker.Clear(); - RegionTraverser.freeWorkers.Enqueue(bFSWorker); + BFSWorker bFSWorker = RegionTraverser.freeWorkers.Dequeue(); + try + { + bFSWorker.BreadthFirstTraverseWork(root, entryCondition, regionProcessor, maxRegions, traversableRegionTypes); + } + catch (Exception ex) + { + Log.Error("Exception in BreadthFirstTraverse: " + ex.ToString()); + } + finally + { + bFSWorker.Clear(); + RegionTraverser.freeWorkers.Enqueue(bFSWorker); + } } } } diff --git a/Assembly-CSharp/Verse/RegionTypeUtility.cs b/Assembly-CSharp/Verse/RegionTypeUtility.cs index ad86cbf4a..2d6b72700 100644 --- a/Assembly-CSharp/Verse/RegionTypeUtility.cs +++ b/Assembly-CSharp/Verse/RegionTypeUtility.cs @@ -1,4 +1,3 @@ -using System; using System.Collections.Generic; namespace Verse @@ -43,12 +42,12 @@ public static RegionType GetExpectedRegionType(this IntVec3 c, Map map) public static RegionType GetRegionType(this IntVec3 c, Map map) { Region region = c.GetRegion(map, RegionType.Set_All); - return (region == null) ? RegionType.None : region.type; + return (region != null) ? region.type : RegionType.None; } public static bool Passable(this RegionType regionType) { - return (regionType & RegionType.Set_Passable) != RegionType.None; + return ((int)regionType & 6) != 0; } } } diff --git a/Assembly-CSharp/Verse/RememberedCameraPos.cs b/Assembly-CSharp/Verse/RememberedCameraPos.cs index f78b329cb..9307d7fa6 100644 --- a/Assembly-CSharp/Verse/RememberedCameraPos.cs +++ b/Assembly-CSharp/Verse/RememberedCameraPos.cs @@ -1,4 +1,3 @@ -using System; using UnityEngine; namespace Verse diff --git a/Assembly-CSharp/Verse/ReorderDirection.cs b/Assembly-CSharp/Verse/ReorderDirection.cs index 012fa2411..8b9d843a1 100644 --- a/Assembly-CSharp/Verse/ReorderDirection.cs +++ b/Assembly-CSharp/Verse/ReorderDirection.cs @@ -1,10 +1,8 @@ -using System; - namespace Verse { public enum ReorderDirection { - Up, - Down + Up = 0, + Down = 1 } } diff --git a/Assembly-CSharp/Verse/ReorderableWidget.cs b/Assembly-CSharp/Verse/ReorderableWidget.cs index 69708d5cc..d4c8a5663 100644 --- a/Assembly-CSharp/Verse/ReorderableWidget.cs +++ b/Assembly-CSharp/Verse/ReorderableWidget.cs @@ -24,9 +24,9 @@ private struct ReorderableInstance private const float LineWidth = 2f; - private static List groups = new List(); + private static List groups = new List(); - private static List reorderables = new List(); + private static List reorderables = new List(); private static int draggingReorderable = -1; @@ -57,7 +57,8 @@ public static void ReorderableWidgetOnGUI() ReorderableWidget.draggingReorderable = -1; for (int i = 0; i < ReorderableWidget.reorderables.Count; i++) { - if (ReorderableWidget.reorderables[i].rect == ReorderableWidget.clickedInRect) + ReorderableInstance reorderableInstance = ReorderableWidget.reorderables[i]; + if (reorderableInstance.rect == ReorderableWidget.clickedInRect) { ReorderableWidget.draggingReorderable = i; break; @@ -75,7 +76,10 @@ public static void ReorderableWidgetOnGUI() ReorderableWidget.released = false; if (ReorderableWidget.lastInsertAt >= 0 && ReorderableWidget.lastInsertAt != ReorderableWidget.draggingReorderable) { - ReorderableWidget.groups[ReorderableWidget.reorderables[ReorderableWidget.draggingReorderable].groupID].reorderedAction(ReorderableWidget.draggingReorderable, ReorderableWidget.lastInsertAt); + List obj = ReorderableWidget.groups; + ReorderableInstance reorderableInstance2 = ReorderableWidget.reorderables[ReorderableWidget.draggingReorderable]; + ReorderableGroup reorderableGroup = obj[reorderableInstance2.groupID]; + reorderableGroup.reorderedAction(ReorderableWidget.draggingReorderable, ReorderableWidget.lastInsertAt); } ReorderableWidget.draggingReorderable = -1; ReorderableWidget.lastInsertAt = -1; @@ -91,8 +95,10 @@ public static int NewGroup(Action reorderedAction) { return -1; } - ReorderableWidget.ReorderableGroup item = default(ReorderableWidget.ReorderableGroup); - item.reorderedAction = reorderedAction; + ReorderableGroup item = new ReorderableGroup + { + reorderedAction = reorderedAction + }; ReorderableWidget.groups.Add(item); return ReorderableWidget.groups.Count - 1; } @@ -101,13 +107,15 @@ public static void Reorderable(int groupID, Rect rect) { if (Event.current.type == EventType.Repaint) { - ReorderableWidget.ReorderableInstance item = default(ReorderableWidget.ReorderableInstance); - item.groupID = groupID; - item.rect = rect; - item.absRect = new Rect(UI.GUIToScreenPoint(rect.position), rect.size); + ReorderableInstance item = new ReorderableInstance + { + groupID = groupID, + rect = rect, + absRect = new Rect(UI.GUIToScreenPoint(rect.position), rect.size) + }; ReorderableWidget.reorderables.Add(item); int num = ReorderableWidget.reorderables.Count - 1; - if (Vector2.Distance(ReorderableWidget.clickedAt, Event.current.mousePosition) > 5f) + if (Vector2.Distance(ReorderableWidget.clickedAt, Event.current.mousePosition) > 5.0) { if (ReorderableWidget.draggingReorderable == num) { @@ -117,8 +125,12 @@ public static void Reorderable(int groupID, Rect rect) } if (ReorderableWidget.lastInsertAt == num) { - Rect rect2 = ReorderableWidget.reorderables[ReorderableWidget.lastInsertAt].rect; - bool flag = Event.current.mousePosition.y < rect2.center.y; + ReorderableInstance reorderableInstance = ReorderableWidget.reorderables[ReorderableWidget.lastInsertAt]; + Rect rect2 = reorderableInstance.rect; + Vector2 mousePosition = Event.current.mousePosition; + float y = mousePosition.y; + Vector2 center = rect2.center; + bool flag = y < center.y; GUI.color = ReorderableWidget.LineColor; if (flag) { @@ -150,56 +162,71 @@ private static int CurrentInsertAt() { return -1; } - int groupID = ReorderableWidget.reorderables[ReorderableWidget.draggingReorderable].groupID; - if (groupID < 0 || groupID >= ReorderableWidget.groups.Count) - { - Log.ErrorOnce("Reorderable used invalid group.", 1968375560); - return -1; - } - int num = -1; - int num2 = -1; - for (int i = 0; i < ReorderableWidget.reorderables.Count; i++) + ReorderableInstance reorderableInstance = ReorderableWidget.reorderables[ReorderableWidget.draggingReorderable]; + int groupID = reorderableInstance.groupID; + if (groupID >= 0 && groupID < ReorderableWidget.groups.Count) { - ReorderableWidget.ReorderableInstance reorderableInstance = ReorderableWidget.reorderables[i]; - if (reorderableInstance.groupID == groupID) + int num = -1; + int num2 = -1; + for (int i = 0; i < ReorderableWidget.reorderables.Count; i++) { - int num3 = (i > ReorderableWidget.draggingReorderable) ? num2 : i; - Rect rect = reorderableInstance.absRect.TopHalf(); - if (rect.yMin > 0f) + ReorderableInstance reorderableInstance2 = ReorderableWidget.reorderables[i]; + if (reorderableInstance2.groupID == groupID) { - rect.yMin = 0f; - } - if (rect.Contains(Event.current.mousePosition)) - { - num = num3; - break; - } - if (num2 >= 0) - { - float num4 = Mathf.Min(reorderableInstance.absRect.x, ReorderableWidget.reorderables[num2].absRect.x); - Rect rect2 = new Rect(num4, ReorderableWidget.reorderables[num2].absRect.center.y, Mathf.Max(reorderableInstance.absRect.xMax, ReorderableWidget.reorderables[num2].absRect.xMax) - num4, reorderableInstance.absRect.center.y - ReorderableWidget.reorderables[num2].absRect.center.y); - if (rect2.Contains(Event.current.mousePosition)) + int num3 = (i > ReorderableWidget.draggingReorderable) ? num2 : i; + Rect rect = reorderableInstance2.absRect.TopHalf(); + if (rect.yMin > 0.0) + { + rect.yMin = 0f; + } + if (rect.Contains(Event.current.mousePosition)) { num = num3; break; } + if (num2 >= 0) + { + float x = reorderableInstance2.absRect.x; + ReorderableInstance reorderableInstance3 = ReorderableWidget.reorderables[num2]; + float num4 = Mathf.Min(x, reorderableInstance3.absRect.x); + float x2 = num4; + ReorderableInstance reorderableInstance4 = ReorderableWidget.reorderables[num2]; + Vector2 center = reorderableInstance4.absRect.center; + float y = center.y; + float xMax = reorderableInstance2.absRect.xMax; + ReorderableInstance reorderableInstance5 = ReorderableWidget.reorderables[num2]; + float width = Mathf.Max(xMax, reorderableInstance5.absRect.xMax) - num4; + Vector2 center2 = reorderableInstance2.absRect.center; + float y2 = center2.y; + ReorderableInstance reorderableInstance6 = ReorderableWidget.reorderables[num2]; + Vector2 center3 = reorderableInstance6.absRect.center; + Rect rect2 = new Rect(x2, y, width, y2 - center3.y); + if (rect2.Contains(Event.current.mousePosition)) + { + num = num3; + break; + } + } + num2 = i; } - num2 = i; - } - } - if (num < 0 && num2 >= 0) - { - Rect rect3 = ReorderableWidget.reorderables[num2].absRect.BottomHalf(); - if (rect3.yMax < (float)UI.screenHeight) - { - rect3.yMax = (float)UI.screenHeight; } - if (rect3.Contains(Event.current.mousePosition)) + if (num < 0 && num2 >= 0) { - num = num2; + ReorderableInstance reorderableInstance7 = ReorderableWidget.reorderables[num2]; + Rect rect3 = reorderableInstance7.absRect.BottomHalf(); + if (rect3.yMax < (float)UI.screenHeight) + { + rect3.yMax = (float)UI.screenHeight; + } + if (rect3.Contains(Event.current.mousePosition)) + { + num = num2; + } } + return num; } - return num; + Log.ErrorOnce("Reorderable used invalid group.", 1968375560); + return -1; } } } diff --git a/Assembly-CSharp/Verse/ResearchMod.cs b/Assembly-CSharp/Verse/ResearchMod.cs index 6adbcffc0..fd57ab433 100644 --- a/Assembly-CSharp/Verse/ResearchMod.cs +++ b/Assembly-CSharp/Verse/ResearchMod.cs @@ -1,5 +1,3 @@ -using System; - namespace Verse { public abstract class ResearchMod diff --git a/Assembly-CSharp/Verse/ResearchProjectDef.cs b/Assembly-CSharp/Verse/ResearchProjectDef.cs index 052270761..469d1acc4 100644 --- a/Assembly-CSharp/Verse/ResearchProjectDef.cs +++ b/Assembly-CSharp/Verse/ResearchProjectDef.cs @@ -1,7 +1,6 @@ using RimWorld; using System; using System.Collections.Generic; -using System.Diagnostics; using UnityEngine; namespace Verse @@ -128,7 +127,7 @@ public string DescriptionDiscovered { return this.descriptionDiscovered; } - return this.description; + return base.description; } } @@ -161,29 +160,47 @@ public override void ResolveReferences() } } - [DebuggerHidden] public override IEnumerable ConfigErrors() { - ResearchProjectDef.c__Iterator1D9 c__Iterator1D = new ResearchProjectDef.c__Iterator1D9(); - c__Iterator1D.<>f__this = this; - ResearchProjectDef.c__Iterator1D9 expr_0E = c__Iterator1D; - expr_0E.$PC = -2; - return expr_0E; + foreach (string item in base.ConfigErrors()) + { + yield return item; + } + if (this.techLevel == TechLevel.Undefined) + { + yield return "techLevel is Undefined"; + } + if (this.ResearchViewX < 0.0 || this.ResearchViewY < 0.0) + { + yield return "researchViewX and/or researchViewY not set"; + } + List rpDefs = DefDatabase.AllDefsListForReading; + for (int i = 0; i < rpDefs.Count; i++) + { + if (rpDefs[i] != this && rpDefs[i].tab == this.tab && rpDefs[i].ResearchViewX == this.ResearchViewX && rpDefs[i].ResearchViewY == this.ResearchViewY) + { + yield return "same research view coords and tab as " + rpDefs[i] + ": " + this.ResearchViewX + ", " + this.ResearchViewY + "(" + this.tab + ")"; + } + } } public float CostFactor(TechLevel researcherTechLevel) { - if (researcherTechLevel >= this.techLevel) + if ((int)researcherTechLevel >= (int)this.techLevel) { return 1f; } - int num = (int)(this.techLevel - researcherTechLevel); - return 1f + (float)num; + int num = this.techLevel - researcherTechLevel; + return (float)(1.0 + (float)num); } public bool HasTag(string tag) { - return this.tags != null && this.tags.Contains(tag); + if (this.tags == null) + { + return false; + } + return this.tags.Contains(tag); } public bool CanBeResearchedAt(Building_ResearchBench bench, bool ignoreResearchBenchPowerStatus) @@ -200,20 +217,18 @@ public bool CanBeResearchedAt(Building_ResearchBench bench, bool ignoreResearchB return false; } } - if (!this.requiredResearchFacilities.NullOrEmpty()) + if (!this.requiredResearchFacilities.NullOrEmpty()) { - ResearchProjectDef.c__AnonStorey50C c__AnonStorey50C = new ResearchProjectDef.c__AnonStorey50C(); - c__AnonStorey50C.<>f__this = this; - c__AnonStorey50C.affectedByFacilities = bench.TryGetComp(); - if (c__AnonStorey50C.affectedByFacilities == null) + CompAffectedByFacilities affectedByFacilities = bench.TryGetComp(); + if (affectedByFacilities == null) { return false; } - List linkedFacilitiesListForReading = c__AnonStorey50C.affectedByFacilities.LinkedFacilitiesListForReading; + List linkedFacilitiesListForReading = affectedByFacilities.LinkedFacilitiesListForReading; int i; for (i = 0; i < this.requiredResearchFacilities.Count; i++) { - if (linkedFacilitiesListForReading.Find((Thing x) => x.def == this.requiredResearchFacilities[i] && c__AnonStorey50C.affectedByFacilities.IsFacilityActive(x)) == null) + if (linkedFacilitiesListForReading.Find((Predicate)((Thing x) => x.def == this.requiredResearchFacilities[i] && affectedByFacilities.IsFacilityActive(x))) == null) { return false; } @@ -234,13 +249,7 @@ public void ReapplyAllMods() } catch (Exception ex) { - Log.Error(string.Concat(new object[] - { - "Exception applying research mod for project ", - this, - ": ", - ex.ToString() - })); + Log.Error("Exception applying research mod for project " + this + ": " + ex.ToString()); } } } @@ -253,82 +262,106 @@ public static ResearchProjectDef Named(string defName) public static void GenerateNonOverlappingCoordinates() { - foreach (ResearchProjectDef current in DefDatabase.AllDefsListForReading) + List.Enumerator enumerator = DefDatabase.AllDefsListForReading.GetEnumerator(); + try { - current.x = current.researchViewX; - current.y = current.researchViewY; + while (enumerator.MoveNext()) + { + ResearchProjectDef current = enumerator.Current; + current.x = current.researchViewX; + current.y = current.researchViewY; + } + } + finally + { + ((IDisposable)(object)enumerator).Dispose(); } int num = 0; while (true) { bool flag = false; - foreach (ResearchProjectDef current2 in DefDatabase.AllDefsListForReading) + List.Enumerator enumerator2 = DefDatabase.AllDefsListForReading.GetEnumerator(); + try { - foreach (ResearchProjectDef current3 in DefDatabase.AllDefsListForReading) + while (enumerator2.MoveNext()) { - if (current2 != current3 && current2.tab == current3.tab) + ResearchProjectDef current2 = enumerator2.Current; + List.Enumerator enumerator3 = DefDatabase.AllDefsListForReading.GetEnumerator(); + try { - bool flag2 = Mathf.Abs(current2.x - current3.x) < 0.5f; - bool flag3 = Mathf.Abs(current2.y - current3.y) < 0.25f; - if (flag2 && flag3) + while (enumerator3.MoveNext()) { - flag = true; - if (current2.x <= current3.x) - { - current2.x -= 0.1f; - current3.x += 0.1f; - } - else + ResearchProjectDef current3 = enumerator3.Current; + if (current2 != current3 && current2.tab == current3.tab) { - current2.x += 0.1f; - current3.x -= 0.1f; + bool flag2 = Mathf.Abs(current2.x - current3.x) < 0.5; + bool flag3 = Mathf.Abs(current2.y - current3.y) < 0.25; + if (flag2 && flag3) + { + flag = true; + if (current2.x <= current3.x) + { + current2.x -= 0.1f; + current3.x += 0.1f; + } + else + { + current2.x += 0.1f; + current3.x -= 0.1f; + } + if (current2.y <= current3.y) + { + current2.y -= 0.1f; + current3.y += 0.1f; + } + else + { + current2.y += 0.1f; + current3.y -= 0.1f; + } + current2.x += 0.001f; + current2.y += 0.001f; + current3.x -= 0.001f; + current3.y -= 0.001f; + ResearchProjectDef.ClampInCoordinateLimits(current2); + ResearchProjectDef.ClampInCoordinateLimits(current3); + } } - if (current2.y <= current3.y) - { - current2.y -= 0.1f; - current3.y += 0.1f; - } - else - { - current2.y += 0.1f; - current3.y -= 0.1f; - } - current2.x += 0.001f; - current2.y += 0.001f; - current3.x -= 0.001f; - current3.y -= 0.001f; - ResearchProjectDef.ClampInCoordinateLimits(current2); - ResearchProjectDef.ClampInCoordinateLimits(current3); } } + finally + { + ((IDisposable)(object)enumerator3).Dispose(); + } } } - if (!flag) + finally { - break; + ((IDisposable)(object)enumerator2).Dispose(); } - num++; - if (num > 200) + if (flag) { - goto Block_4; + num++; + if (num > 200) + break; + continue; } + return; } - return; - Block_4: Log.Error("Couldn't relax research project coordinates apart after " + 200 + " passes."); } private static void ClampInCoordinateLimits(ResearchProjectDef rp) { - if (rp.x < 0f) + if (rp.x < 0.0) { rp.x = 0f; } - if (rp.y < 0f) + if (rp.y < 0.0) { rp.y = 0f; } - if (rp.y > 6.5f) + if (rp.y > 6.5) { rp.y = 6.5f; } diff --git a/Assembly-CSharp/Verse/ReservationLayerDef.cs b/Assembly-CSharp/Verse/ReservationLayerDef.cs index 28a848119..5c0aa8d0f 100644 --- a/Assembly-CSharp/Verse/ReservationLayerDef.cs +++ b/Assembly-CSharp/Verse/ReservationLayerDef.cs @@ -1,5 +1,3 @@ -using System; - namespace Verse { public class ReservationLayerDef : Def diff --git a/Assembly-CSharp/Verse/ResourceCountPriority.cs b/Assembly-CSharp/Verse/ResourceCountPriority.cs index 0ef1862ea..46ec46963 100644 --- a/Assembly-CSharp/Verse/ResourceCountPriority.cs +++ b/Assembly-CSharp/Verse/ResourceCountPriority.cs @@ -1,12 +1,10 @@ -using System; - namespace Verse { public enum ResourceCountPriority : byte { - Uncounted, - Last, - Middle, - First + Uncounted = 0, + Last = 1, + Middle = 2, + First = 3 } } diff --git a/Assembly-CSharp/Verse/ReverseDesignatorDatabase.cs b/Assembly-CSharp/Verse/ReverseDesignatorDatabase.cs index 53a5bbdf4..2df5bb8df 100644 --- a/Assembly-CSharp/Verse/ReverseDesignatorDatabase.cs +++ b/Assembly-CSharp/Verse/ReverseDesignatorDatabase.cs @@ -33,13 +33,13 @@ public T Get() where T : Designator } for (int i = 0; i < this.desList.Count; i++) { - T t = this.desList[i] as T; - if (t != null) + T val = (T)(this.desList[i] as T); + if (val != null) { - return t; + return val; } } - return (T)((object)null); + return (T)null; } private void InitDesignators() @@ -59,7 +59,7 @@ private void InitDesignators() this.desList.Add(new Designator_Strip()); this.desList.Add(new Designator_RearmTrap()); this.desList.Add(new Designator_Open()); - this.desList.RemoveAll((Designator des) => !Current.Game.Rules.DesignatorAllowed(des)); + this.desList.RemoveAll((Predicate)((Designator des) => !Current.Game.Rules.DesignatorAllowed(des))); } } } diff --git a/Assembly-CSharp/Verse/RoadInfo.cs b/Assembly-CSharp/Verse/RoadInfo.cs index 686fe6ee3..393718de9 100644 --- a/Assembly-CSharp/Verse/RoadInfo.cs +++ b/Assembly-CSharp/Verse/RoadInfo.cs @@ -1,4 +1,3 @@ -using System; using System.Collections.Generic; namespace Verse diff --git a/Assembly-CSharp/Verse/RockNoises.cs b/Assembly-CSharp/Verse/RockNoises.cs index b3b4f1828..c57b9b954 100644 --- a/Assembly-CSharp/Verse/RockNoises.cs +++ b/Assembly-CSharp/Verse/RockNoises.cs @@ -1,4 +1,3 @@ -using System; using System.Collections.Generic; using Verse.Noise; @@ -15,15 +14,15 @@ public class RockNoise private const float RockNoiseFreq = 0.005f; - public static List rockNoises; + public static List rockNoises; public static void Init(Map map) { - RockNoises.rockNoises = new List(); - foreach (ThingDef current in Find.World.NaturalRockTypesIn(map.Tile)) + RockNoises.rockNoises = new List(); + foreach (ThingDef item in Find.World.NaturalRockTypesIn(map.Tile)) { - RockNoises.RockNoise rockNoise = new RockNoises.RockNoise(); - rockNoise.rockDef = current; + RockNoise rockNoise = new RockNoise(); + rockNoise.rockDef = item; rockNoise.noise = new Perlin(0.004999999888241291, 2.0, 0.5, 6, Rand.Range(0, 2147483647), QualityMode.Medium); RockNoises.rockNoises.Add(rockNoise); NoiseDebugUI.StoreNoiseRender(rockNoise.noise, rockNoise.rockDef + " score", map.Size.ToIntVec2); diff --git a/Assembly-CSharp/Verse/RoofCollapseBuffer.cs b/Assembly-CSharp/Verse/RoofCollapseBuffer.cs index f2ff71845..83ead3dea 100644 --- a/Assembly-CSharp/Verse/RoofCollapseBuffer.cs +++ b/Assembly-CSharp/Verse/RoofCollapseBuffer.cs @@ -1,4 +1,3 @@ -using System; using System.Collections.Generic; namespace Verse @@ -54,14 +53,23 @@ private bool WorthMentioningInCrushLetter(Thing t) } switch (t.def.category) { + case ThingCategory.Building: + { + return true; + } case ThingCategory.Pawn: + { return true; + } case ThingCategory.Item: - return t.MarketValue > 0.01f; - case ThingCategory.Building: - return true; + { + return t.MarketValue > 0.0099999997764825821; + } + default: + { + return false; + } } - return false; } public void Clear() diff --git a/Assembly-CSharp/Verse/RoofCollapseBufferResolver.cs b/Assembly-CSharp/Verse/RoofCollapseBufferResolver.cs index 229c6bdd9..c9f64e48b 100644 --- a/Assembly-CSharp/Verse/RoofCollapseBufferResolver.cs +++ b/Assembly-CSharp/Verse/RoofCollapseBufferResolver.cs @@ -27,23 +27,41 @@ public void CollapseRoofsMarkedToCollapse() stringBuilder.AppendLine(); stringBuilder.AppendLine("TheseThingsCrushed".Translate()); HashSet hashSet = new HashSet(); - foreach (Thing current in roofCollapseBuffer.CrushedThingsForLetter) + List.Enumerator enumerator = roofCollapseBuffer.CrushedThingsForLetter.GetEnumerator(); + try { - string item = current.LabelShort.CapitalizeFirst(); - if (current.def.category == ThingCategory.Pawn) + while (enumerator.MoveNext()) { - item = current.LabelCap; + Thing current = enumerator.Current; + string item = current.LabelShort.CapitalizeFirst(); + if (current.def.category == ThingCategory.Pawn) + { + item = current.LabelCap; + } + if (!hashSet.Contains(item)) + { + hashSet.Add(item); + } } - if (!hashSet.Contains(item)) + } + finally + { + ((IDisposable)(object)enumerator).Dispose(); + } + HashSet.Enumerator enumerator2 = hashSet.GetEnumerator(); + try + { + while (enumerator2.MoveNext()) { - hashSet.Add(item); + string current2 = enumerator2.Current; + stringBuilder.AppendLine(" -" + current2); } } - foreach (string current2 in hashSet) + finally { - stringBuilder.AppendLine(" -" + current2); + ((IDisposable)(object)enumerator2).Dispose(); } - Find.LetterStack.ReceiveLetter("LetterLabelRoofCollapsed".Translate(), stringBuilder.ToString(), LetterDefOf.BadNonUrgent, new TargetInfo(roofCollapseBuffer.CellsMarkedToCollapse[0], this.map, false), null); + Find.LetterStack.ReceiveLetter("LetterLabelRoofCollapsed".Translate(), stringBuilder.ToString(), LetterDefOf.BadNonUrgent, new TargetInfo(roofCollapseBuffer.CellsMarkedToCollapse[0], this.map, false), (string)null); } else { diff --git a/Assembly-CSharp/Verse/RoofCollapseCellsFinder.cs b/Assembly-CSharp/Verse/RoofCollapseCellsFinder.cs index 130b3fcc7..689863d77 100644 --- a/Assembly-CSharp/Verse/RoofCollapseCellsFinder.cs +++ b/Assembly-CSharp/Verse/RoofCollapseCellsFinder.cs @@ -11,11 +11,10 @@ public static class RoofCollapseCellsFinder public static void Notify_RoofHolderDespawned(Thing t, Map map) { - if (Current.ProgramState != ProgramState.Playing) + if (Current.ProgramState == ProgramState.Playing) { - return; + RoofCollapseCellsFinder.ProcessRoofHolderDespawned(t.OccupiedRect(), t.Position, map, false); } - RoofCollapseCellsFinder.ProcessRoofHolderDespawned(t.OccupiedRect(), t.Position, map, false); } public static void ProcessRoofHolderDespawned(CellRect rect, IntVec3 position, Map map, bool removalMode = false) @@ -26,26 +25,17 @@ public static void ProcessRoofHolderDespawned(CellRect rect, IntVec3 position, M for (int i = 0; i < RoofCollapseUtility.RoofSupportRadialCellsCount; i++) { IntVec3 intVec = position + GenRadial.RadialPattern[i]; - if (intVec.InBounds(map)) + if (intVec.InBounds(map) && roofGrid.Roofed(intVec.x, intVec.z) && !map.roofCollapseBuffer.IsMarkedToCollapse(intVec) && !RoofCollapseUtility.WithinRangeOfRoofHolder(intVec, map)) { - if (roofGrid.Roofed(intVec.x, intVec.z)) + if (removalMode) { - if (!map.roofCollapseBuffer.IsMarkedToCollapse(intVec)) - { - if (!RoofCollapseUtility.WithinRangeOfRoofHolder(intVec, map)) - { - if (removalMode) - { - map.roofGrid.SetRoof(intVec, null); - } - else - { - map.roofCollapseBuffer.MarkToCollapse(intVec); - } - RoofCollapseCellsFinder.roofsCollapsingBecauseTooFar.Add(intVec); - } - } + map.roofGrid.SetRoof(intVec, null); + } + else + { + map.roofCollapseBuffer.MarkToCollapse(intVec); } + RoofCollapseCellsFinder.roofsCollapsingBecauseTooFar.Add(intVec); } } RoofCollapseCellsFinder.CheckCollapseFlyingRoofs(RoofCollapseCellsFinder.roofsCollapsingBecauseTooFar, map, removalMode); @@ -56,7 +46,10 @@ public static void RemoveBulkCollapsingRoofs(List nearCells, Map map) { for (int i = 0; i < nearCells.Count; i++) { - RoofCollapseCellsFinder.ProcessRoofHolderDespawned(new CellRect(nearCells[i].x, nearCells[i].z, 1, 1), nearCells[i], map, true); + IntVec3 intVec = nearCells[i]; + int x = intVec.x; + IntVec3 intVec2 = nearCells[i]; + RoofCollapseCellsFinder.ProcessRoofHolderDespawned(new CellRect(x, intVec2.z, 1, 1), nearCells[i], map, true); } } @@ -93,31 +86,19 @@ private static bool CheckCollapseFlyingRoofAtAndAdjInternal(IntVec3 root, Map ma for (int i = 0; i < 5; i++) { IntVec3 intVec = root + GenAdj.CardinalDirectionsAndInside[i]; - if (intVec.InBounds(map)) + if (intVec.InBounds(map) && intVec.Roofed(map) && !RoofCollapseCellsFinder.visitedCells.Contains(intVec) && !roofCollapseBuffer.IsMarkedToCollapse(intVec) && !RoofCollapseCellsFinder.ConnectsToRoofHolder(intVec, map)) { - if (intVec.Roofed(map)) + map.floodFiller.FloodFill(intVec, (Predicate)((IntVec3 x) => x.Roofed(map)), (Action)delegate(IntVec3 x) { - if (!RoofCollapseCellsFinder.visitedCells.Contains(intVec)) + roofCollapseBuffer.MarkToCollapse(x); + }, false); + if (removalMode) + { + for (int j = 0; j < roofCollapseBuffer.CellsMarkedToCollapse.Count; j++) { - if (!roofCollapseBuffer.IsMarkedToCollapse(intVec)) - { - if (!RoofCollapseCellsFinder.ConnectsToRoofHolder(intVec, map)) - { - map.floodFiller.FloodFill(intVec, (IntVec3 x) => x.Roofed(map), delegate(IntVec3 x) - { - roofCollapseBuffer.MarkToCollapse(x); - }, false); - if (removalMode) - { - for (int j = 0; j < roofCollapseBuffer.CellsMarkedToCollapse.Count; j++) - { - map.roofGrid.SetRoof(roofCollapseBuffer.CellsMarkedToCollapse[j], null); - } - roofCollapseBuffer.Clear(); - } - } - } + map.roofGrid.SetRoof(roofCollapseBuffer.CellsMarkedToCollapse[j], null); } + roofCollapseBuffer.Clear(); } } } @@ -128,26 +109,33 @@ private static bool CheckCollapseFlyingRoofAtAndAdjInternal(IntVec3 root, Map ma private static bool ConnectsToRoofHolder(IntVec3 c, Map map) { bool connected = false; - map.floodFiller.FloodFill(c, (IntVec3 x) => x.Roofed(map) && !connected, delegate(IntVec3 x) + map.floodFiller.FloodFill(c, (Predicate)((IntVec3 x) => x.Roofed(map) && !connected), (Action)delegate(IntVec3 x) { if (RoofCollapseCellsFinder.visitedCells.Contains(x)) { connected = true; - return; } - RoofCollapseCellsFinder.visitedCells.Add(x); - for (int i = 0; i < 5; i++) + else { - IntVec3 c2 = x + GenAdj.CardinalDirectionsAndInside[i]; - if (c2.InBounds(map)) + RoofCollapseCellsFinder.visitedCells.Add(x); + int num = 0; + while (true) { - Building edifice = c2.GetEdifice(map); - if (edifice != null && edifice.def.holdsRoof) + if (num < 5) { - connected = true; - break; + IntVec3 c2 = x + GenAdj.CardinalDirectionsAndInside[num]; + if (c2.InBounds(map)) + { + Building edifice = c2.GetEdifice(map); + if (edifice != null && edifice.def.holdsRoof) + break; + } + num++; + continue; } + return; } + connected = true; } }, false); return connected; diff --git a/Assembly-CSharp/Verse/RoofCollapseUtility.cs b/Assembly-CSharp/Verse/RoofCollapseUtility.cs index eb5bafd54..df9e4d2ba 100644 --- a/Assembly-CSharp/Verse/RoofCollapseUtility.cs +++ b/Assembly-CSharp/Verse/RoofCollapseUtility.cs @@ -30,21 +30,26 @@ public static bool WithinRangeOfRoofHolder(IntVec3 c, Map map) public static bool ConnectedToRoofHolder(IntVec3 c, Map map, bool assumeRoofAtRoot) { bool connected = false; - map.floodFiller.FloodFill(c, (IntVec3 x) => (x.Roofed(map) || (x == c && assumeRoofAtRoot)) && !connected, delegate(IntVec3 x) + map.floodFiller.FloodFill(c, (Predicate)((IntVec3 x) => (x.Roofed(map) || (x == c && assumeRoofAtRoot)) && !connected), (Action)delegate(IntVec3 x) { - for (int i = 0; i < 5; i++) + int num = 0; + while (true) { - IntVec3 c2 = x + GenAdj.CardinalDirectionsAndInside[i]; - if (c2.InBounds(map)) + if (num < 5) { - Building edifice = c2.GetEdifice(map); - if (edifice != null && edifice.def.holdsRoof) + IntVec3 c2 = x + GenAdj.CardinalDirectionsAndInside[num]; + if (c2.InBounds(map)) { - connected = true; - break; + Building edifice = c2.GetEdifice(map); + if (edifice != null && edifice.def.holdsRoof) + break; } + num++; + continue; } + return; } + connected = true; }, false); return connected; } diff --git a/Assembly-CSharp/Verse/RoofCollapserImmediate.cs b/Assembly-CSharp/Verse/RoofCollapserImmediate.cs index 25aacdd63..039e6214f 100644 --- a/Assembly-CSharp/Verse/RoofCollapserImmediate.cs +++ b/Assembly-CSharp/Verse/RoofCollapserImmediate.cs @@ -1,5 +1,4 @@ using RimWorld; -using System; using System.Collections.Generic; using UnityEngine; using Verse.Sound; @@ -20,14 +19,14 @@ public static void DropRoofInCells(IntVec3 c, Map map) public static void DropRoofInCells(IEnumerable cells, Map map) { IntVec3 cell = IntVec3.Invalid; - foreach (IntVec3 current in cells) + foreach (IntVec3 item in cells) { - RoofCollapserImmediate.DropRoofInCellPhaseOne(current, map); + RoofCollapserImmediate.DropRoofInCellPhaseOne(item, map); } - foreach (IntVec3 current2 in cells) + foreach (IntVec3 item2 in cells) { - RoofCollapserImmediate.DropRoofInCellPhaseTwo(current2, map); - cell = current2; + RoofCollapserImmediate.DropRoofInCellPhaseTwo(item2, map); + cell = item2; } if (cell.IsValid) { @@ -37,107 +36,104 @@ public static void DropRoofInCells(IEnumerable cells, Map map) public static void DropRoofInCells(List cells, Map map) { - if (cells.NullOrEmpty()) + if (!cells.NullOrEmpty()) { - return; - } - for (int i = 0; i < cells.Count; i++) - { - RoofCollapserImmediate.DropRoofInCellPhaseOne(cells[i], map); - } - for (int j = 0; j < cells.Count; j++) - { - RoofCollapserImmediate.DropRoofInCellPhaseTwo(cells[j], map); + for (int i = 0; i < cells.Count; i++) + { + RoofCollapserImmediate.DropRoofInCellPhaseOne(cells[i], map); + } + for (int j = 0; j < cells.Count; j++) + { + RoofCollapserImmediate.DropRoofInCellPhaseTwo(cells[j], map); + } + SoundDefOf.RoofCollapse.PlayOneShot(new TargetInfo(cells[0], map, false)); } - SoundDefOf.RoofCollapse.PlayOneShot(new TargetInfo(cells[0], map, false)); } private static void DropRoofInCellPhaseOne(IntVec3 c, Map map) { RoofDef roofDef = map.roofGrid.RoofAt(c); - if (roofDef == null) + if (roofDef != null) { - return; - } - if (roofDef.collapseLeavingThingDef != null && roofDef.collapseLeavingThingDef.passability == Traversability.Impassable) - { - for (int i = 0; i < 2; i++) + if (roofDef.collapseLeavingThingDef != null && roofDef.collapseLeavingThingDef.passability == Traversability.Impassable) { - List thingList = c.GetThingList(map); - for (int j = thingList.Count - 1; j >= 0; j--) + for (int i = 0; i < 2; i++) { - Thing thing = thingList[j]; - map.roofCollapseBuffer.Notify_Crushed(thing); - Pawn pawn = thing as Pawn; - DamageInfo dinfo; - if (pawn != null) - { - BodyPartRecord brain = pawn.health.hediffSet.GetBrain(); - dinfo = new DamageInfo(DamageDefOf.Crush, 99999, -1f, null, brain, null, DamageInfo.SourceCategory.Collapse); - } - else + List thingList = c.GetThingList(map); + for (int num = thingList.Count - 1; num >= 0; num--) { - dinfo = new DamageInfo(DamageDefOf.Crush, 99999, -1f, null, null, null, DamageInfo.SourceCategory.Collapse); - dinfo.SetBodyRegion(BodyPartHeight.Top, BodyPartDepth.Outside); - } - thing.TakeDamage(dinfo); - if (!thing.Destroyed && thing.def.destroyable) - { - thing.Destroy(DestroyMode.Vanish); + Thing thing = thingList[num]; + map.roofCollapseBuffer.Notify_Crushed(thing); + Pawn pawn = thing as Pawn; + DamageInfo dinfo = default(DamageInfo); + if (pawn != null) + { + BodyPartRecord brain = pawn.health.hediffSet.GetBrain(); + dinfo = new DamageInfo(DamageDefOf.Crush, 99999, -1f, null, brain, null, DamageInfo.SourceCategory.Collapse); + } + else + { + dinfo = new DamageInfo(DamageDefOf.Crush, 99999, -1f, null, null, null, DamageInfo.SourceCategory.Collapse); + dinfo.SetBodyRegion(BodyPartHeight.Top, BodyPartDepth.Outside); + } + thing.TakeDamage(dinfo); + if (!thing.Destroyed && thing.def.destroyable) + { + thing.Destroy(DestroyMode.Vanish); + } } } } - } - else - { - List thingList2 = c.GetThingList(map); - for (int k = thingList2.Count - 1; k >= 0; k--) + else { - Thing thing2 = thingList2[k]; - if (thing2.def.category == ThingCategory.Item || thing2.def.category == ThingCategory.Plant || thing2.def.category == ThingCategory.Building || thing2.def.category == ThingCategory.Pawn) + List thingList2 = c.GetThingList(map); + for (int num2 = thingList2.Count - 1; num2 >= 0; num2--) { - map.roofCollapseBuffer.Notify_Crushed(thing2); - float num = (float)RoofCollapserImmediate.ThinRoofCrushDamageRange.RandomInRange; - if (thing2.def.building != null) + Thing thing2 = thingList2[num2]; + if (thing2.def.category == ThingCategory.Item || thing2.def.category == ThingCategory.Plant || thing2.def.category == ThingCategory.Building || thing2.def.category == ThingCategory.Pawn) { - num *= thing2.def.building.roofCollapseDamageMultiplier; + map.roofCollapseBuffer.Notify_Crushed(thing2); + float num3 = (float)RoofCollapserImmediate.ThinRoofCrushDamageRange.RandomInRange; + if (thing2.def.building != null) + { + num3 *= thing2.def.building.roofCollapseDamageMultiplier; + } + DamageInfo dinfo2 = new DamageInfo(DamageDefOf.Crush, GenMath.RoundRandom(num3), -1f, null, null, null, DamageInfo.SourceCategory.Collapse); + dinfo2.SetBodyRegion(BodyPartHeight.Top, BodyPartDepth.Outside); + thing2.TakeDamage(dinfo2); } - DamageInfo dinfo2 = new DamageInfo(DamageDefOf.Crush, GenMath.RoundRandom(num), -1f, null, null, null, DamageInfo.SourceCategory.Collapse); - dinfo2.SetBodyRegion(BodyPartHeight.Top, BodyPartDepth.Outside); - thing2.TakeDamage(dinfo2); } } - } - if (roofDef.collapseLeavingThingDef != null) - { - Thing thing3 = GenSpawn.Spawn(roofDef.collapseLeavingThingDef, c, map); - if (thing3.def.rotatable) + if (roofDef.collapseLeavingThingDef != null) + { + Thing thing3 = GenSpawn.Spawn(roofDef.collapseLeavingThingDef, c, map); + if (thing3.def.rotatable) + { + thing3.Rotation = Rot4.Random; + } + } + for (int j = 0; j < 1; j++) { - thing3.Rotation = Rot4.Random; + Vector3 a = c.ToVector3Shifted(); + a += Gen.RandomHorizontalVector(0.6f); + MoteMaker.ThrowDustPuff(a, map, 2f); } } - for (int l = 0; l < 1; l++) - { - Vector3 vector = c.ToVector3Shifted(); - vector += Gen.RandomHorizontalVector(0.6f); - MoteMaker.ThrowDustPuff(vector, map, 2f); - } } private static void DropRoofInCellPhaseTwo(IntVec3 c, Map map) { RoofDef roofDef = map.roofGrid.RoofAt(c); - if (roofDef == null) + if (roofDef != null) { - return; - } - if (roofDef.filthLeaving != null) - { - FilthMaker.MakeFilth(c, map, roofDef.filthLeaving, 1); - } - if (!roofDef.isThickRoof) - { - map.roofGrid.SetRoof(c, null); + if (roofDef.filthLeaving != null) + { + FilthMaker.MakeFilth(c, map, roofDef.filthLeaving, 1); + } + if (!roofDef.isThickRoof) + { + map.roofGrid.SetRoof(c, null); + } } } } diff --git a/Assembly-CSharp/Verse/RoofDef.cs b/Assembly-CSharp/Verse/RoofDef.cs index 22dbb202e..5bc506f53 100644 --- a/Assembly-CSharp/Verse/RoofDef.cs +++ b/Assembly-CSharp/Verse/RoofDef.cs @@ -1,5 +1,3 @@ -using System; - namespace Verse { public class RoofDef : Def diff --git a/Assembly-CSharp/Verse/RoofGrid.cs b/Assembly-CSharp/Verse/RoofGrid.cs index 6738d3749..1203bb57d 100644 --- a/Assembly-CSharp/Verse/RoofGrid.cs +++ b/Assembly-CSharp/Verse/RoofGrid.cs @@ -18,7 +18,10 @@ public CellBoolDrawer Drawer { if (this.drawerInt == null) { - this.drawerInt = new CellBoolDrawer(this, this.map.Size.x, this.map.Size.z, 0.33f); + IntVec3 size = this.map.Size; + int x = size.x; + IntVec3 size2 = this.map.Size; + this.drawerInt = new CellBoolDrawer(this, x, size2.z, 0.33f); } return this.drawerInt; } @@ -43,13 +46,14 @@ public void ExposeData() string compressedString = string.Empty; if (Scribe.mode == LoadSaveMode.Saving) { - compressedString = GridSaveUtility.CompressedStringForShortGrid((IntVec3 c) => this.roofGrid[this.map.cellIndices.CellToIndex(c)], this.map); + compressedString = GridSaveUtility.CompressedStringForShortGrid((Func)((IntVec3 c) => this.roofGrid[this.map.cellIndices.CellToIndex(c)]), this.map); } - Scribe_Values.Look(ref compressedString, "roofs", null, false); + Scribe_Values.Look(ref compressedString, "roofs", (string)null, false); if (Scribe.mode == LoadSaveMode.LoadingVars) { - foreach (GridSaveUtility.LoadedGridShort current in GridSaveUtility.LoadedUShortGrid(compressedString, this.map)) + foreach (GridSaveUtility.LoadedGridShort item in GridSaveUtility.LoadedUShortGrid(compressedString, this.map)) { + GridSaveUtility.LoadedGridShort current = item; this.SetRoof(current.cell, DefDatabase.GetByShortHash(current.val)); } } @@ -91,31 +95,22 @@ public RoofDef RoofAt(int x, int z) public void SetRoof(IntVec3 c, RoofDef def) { - ushort num; - if (def == null) + ushort num = (ushort)((def != null) ? def.shortHash : 0); + if (this.roofGrid[this.map.cellIndices.CellToIndex(c)] != num) { - num = 0; - } - else - { - num = def.shortHash; - } - if (this.roofGrid[this.map.cellIndices.CellToIndex(c)] == num) - { - return; - } - this.roofGrid[this.map.cellIndices.CellToIndex(c)] = num; - this.map.glowGrid.MarkGlowGridDirty(c); - Region validRegionAt_NoRebuild = this.map.regionGrid.GetValidRegionAt_NoRebuild(c); - if (validRegionAt_NoRebuild != null) - { - validRegionAt_NoRebuild.Room.Notify_RoofChanged(); - } - if (this.drawerInt != null) - { - this.drawerInt.SetDirty(); + this.roofGrid[this.map.cellIndices.CellToIndex(c)] = num; + this.map.glowGrid.MarkGlowGridDirty(c); + Region validRegionAt_NoRebuild = this.map.regionGrid.GetValidRegionAt_NoRebuild(c); + if (validRegionAt_NoRebuild != null) + { + validRegionAt_NoRebuild.Room.Notify_RoofChanged(); + } + if (this.drawerInt != null) + { + this.drawerInt.SetDirty(); + } + this.map.mapDrawer.MapMeshDirty(c, MapMeshFlag.Roofs); } - this.map.mapDrawer.MapMeshDirty(c, MapMeshFlag.Roofs); } public void RoofGridUpdate() diff --git a/Assembly-CSharp/Verse/Room.cs b/Assembly-CSharp/Verse/Room.cs index 995d8f795..c098a76b2 100644 --- a/Assembly-CSharp/Verse/Room.cs +++ b/Assembly-CSharp/Verse/Room.cs @@ -12,7 +12,7 @@ public sealed class Room private const int MaxRegionsToAssignRoomRole = 36; - public sbyte mapIndex = -1; + public sbyte mapIndex = (sbyte)(-1); private RoomGroup groupInt; @@ -58,7 +58,7 @@ public Map Map { get { - return ((int)this.mapIndex >= 0) ? Find.Maps[(int)this.mapIndex] : null; + return (this.mapIndex >= 0) ? Find.Maps[this.mapIndex] : null; } } @@ -66,7 +66,7 @@ public RegionType RegionType { get { - return (!this.regions.Any()) ? RegionType.None : this.regions[0].type; + return this.regions.Any() ? this.regions[0].type : RegionType.None; } } @@ -134,18 +134,17 @@ public RoomGroup Group } set { - if (value == this.groupInt) + if (value != this.groupInt) { - return; - } - if (this.groupInt != null) - { - this.groupInt.RemoveRoom(this); - } - this.groupInt = value; - if (this.groupInt != null) - { - this.groupInt.AddRoom(this); + if (this.groupInt != null) + { + this.groupInt.RemoveRoom(this); + } + this.groupInt = value; + if (this.groupInt != null) + { + this.groupInt.AddRoom(this); + } } } } @@ -176,9 +175,9 @@ public int OpenRoofCount if (this.Map != null) { RoofGrid roofGrid = this.Map.roofGrid; - foreach (IntVec3 current in this.Cells) + foreach (IntVec3 cell in this.Cells) { - if (!roofGrid.Roofed(current)) + if (!roofGrid.Roofed(cell)) { this.cachedOpenRoofCount++; } @@ -193,7 +192,15 @@ public bool PsychologicallyOutdoors { get { - return this.TouchesMapEdge || this.OpenRoofCount > 300 || (this.Group.AnyRoomTouchesMapEdge && (float)this.OpenRoofCount / (float)this.CellCount >= 0.5f); + if (!this.TouchesMapEdge && this.OpenRoofCount <= 300) + { + if (this.Group.AnyRoomTouchesMapEdge && (float)this.OpenRoofCount / (float)this.CellCount >= 0.5) + { + return true; + } + return false; + } + return true; } } @@ -205,11 +212,11 @@ public List Neighbors this.uniqueNeighbors.Clear(); for (int i = 0; i < this.regions.Count; i++) { - foreach (Region current in this.regions[i].Neighbors) + foreach (Region neighbor in this.regions[i].Neighbors) { - if (this.uniqueNeighborsSet.Add(current.Room) && current.Room != this) + if (this.uniqueNeighborsSet.Add(neighbor.Room) && neighbor.Room != this) { - this.uniqueNeighbors.Add(current.Room); + this.uniqueNeighbors.Add(neighbor.Room); } } } @@ -222,11 +229,13 @@ public IEnumerable Cells { get { - Room.<>c__Iterator205 <>c__Iterator = new Room.<>c__Iterator205(); - <>c__Iterator.<>f__this = this; - Room.<>c__Iterator205 expr_0E = <>c__Iterator; - expr_0E.$PC = -2; - return expr_0E; + for (int i = 0; i < this.regions.Count; i++) + { + foreach (IntVec3 cell in this.regions[i].Cells) + { + yield return cell; + } + } } } @@ -234,11 +243,18 @@ public IEnumerable BorderCells { get { - Room.<>c__Iterator206 <>c__Iterator = new Room.<>c__Iterator206(); - <>c__Iterator.<>f__this = this; - Room.<>c__Iterator206 expr_0E = <>c__Iterator; - expr_0E.$PC = -2; - return expr_0E; + foreach (IntVec3 cell in this.Cells) + { + for (int i = 0; i < 8; i++) + { + IntVec3 prospective = cell + GenAdj.AdjacentCells[i]; + Region region = (cell + GenAdj.AdjacentCells[i]).GetRegion(this.Map, RegionType.Set_Passable); + if (region == null || region.Room != this) + { + yield return prospective; + } + } + } } } @@ -246,11 +262,42 @@ public IEnumerable Owners { get { - Room.<>c__Iterator207 <>c__Iterator = new Room.<>c__Iterator207(); - <>c__Iterator.<>f__this = this; - Room.<>c__Iterator207 expr_0E = <>c__Iterator; - expr_0E.$PC = -2; - return expr_0E; + if (!this.TouchesMapEdge && !this.IsHuge && (this.Role == RoomRoleDefOf.Bedroom || this.Role == RoomRoleDefOf.PrisonCell || this.Role == RoomRoleDefOf.Barracks || this.Role == RoomRoleDefOf.PrisonBarracks)) + { + Pawn firstOwner = null; + Pawn secondOwner = null; + foreach (Building_Bed containedBed in this.ContainedBeds) + { + if (containedBed.def.building.bed_humanlike) + { + for (int i = 0; i < containedBed.owners.Count; i++) + { + if (firstOwner == null) + { + firstOwner = containedBed.owners[i]; + } + else + { + if (secondOwner != null) + yield break; + secondOwner = containedBed.owners[i]; + } + } + } + } + if (firstOwner != null) + { + if (secondOwner == null) + { + yield return firstOwner; + } + else if (LovePartnerRelationUtility.LovePartnerRelationExists(firstOwner, secondOwner)) + { + yield return firstOwner; + yield return secondOwner; + } + } + } } } @@ -258,11 +305,15 @@ public IEnumerable ContainedBeds { get { - Room.<>c__Iterator208 <>c__Iterator = new Room.<>c__Iterator208(); - <>c__Iterator.<>f__this = this; - Room.<>c__Iterator208 expr_0E = <>c__Iterator; - expr_0E.$PC = -2; - return expr_0E; + List things = this.ContainedAndAdjacentThings; + for (int i = 0; i < things.Count; i++) + { + Building_Bed bed = things[i] as Building_Bed; + if (bed != null) + { + yield return bed; + } + } } } @@ -270,7 +321,11 @@ public bool Fogged { get { - return this.regions.Count != 0 && this.regions[0].AnyCell.Fogged(this.Map); + if (this.regions.Count == 0) + { + return false; + } + return this.regions[0].AnyCell.Fogged(this.Map); } } @@ -325,23 +380,19 @@ public void AddRegion(Region r) { if (this.regions.Contains(r)) { - Log.Error(string.Concat(new object[] - { - "Tried to add the same region twice to Room. region=", - r, - ", room=", - this - })); - return; - } - this.regions.Add(r); - if (r.touchesMapEdge) - { - this.numRegionsTouchingMapEdge++; + Log.Error("Tried to add the same region twice to Room. region=" + r + ", room=" + this); } - if (this.regions.Count == 1) + else { - this.Map.regionGrid.allRooms.Add(this); + this.regions.Add(r); + if (r.touchesMapEdge) + { + this.numRegionsTouchingMapEdge++; + } + if (this.regions.Count == 1) + { + this.Map.regionGrid.allRooms.Add(this); + } } } @@ -349,33 +400,29 @@ public void RemoveRegion(Region r) { if (!this.regions.Contains(r)) { - Log.Error(string.Concat(new object[] - { - "Tried to remove region from Room but this region is not here. region=", - r, - ", room=", - this - })); - return; - } - this.regions.Remove(r); - if (r.touchesMapEdge) - { - this.numRegionsTouchingMapEdge--; + Log.Error("Tried to remove region from Room but this region is not here. region=" + r + ", room=" + this); } - if (this.regions.Count == 0) + else { - this.Group = null; - this.cachedOpenRoofCount = -1; - this.cachedOpenRoofCount = -1; - this.statsAndRoleDirty = true; - this.Map.regionGrid.allRooms.Remove(this); + this.regions.Remove(r); + if (r.touchesMapEdge) + { + this.numRegionsTouchingMapEdge--; + } + if (this.regions.Count == 0) + { + this.Group = null; + this.cachedOpenRoofCount = -1; + this.cachedOpenRoofCount = -1; + this.statsAndRoleDirty = true; + this.Map.regionGrid.allRooms.Remove(this); + } } } public void Notify_MyMapRemoved() { - this.mapIndex = -1; + this.mapIndex = (sbyte)(-1); } public void Notify_ContainedThingSpawnedOrDespawned(Thing th) @@ -429,9 +476,9 @@ public void Notify_RoomShapeOrContainedBedsChanged() } if (Current.ProgramState == ProgramState.Playing && this.isPrisonCell) { - foreach (Building_Bed current in this.ContainedBeds) + foreach (Building_Bed containedBed in this.ContainedBeds) { - current.ForPrisoners = true; + containedBed.ForPrisoners = true; } } this.lastChangeTick = Find.TickManager.TicksGame; @@ -442,18 +489,14 @@ public void Notify_RoomShapeOrContainedBedsChanged() public void DecrementMapIndex() { - if ((int)this.mapIndex <= 0) + if (this.mapIndex <= 0) { - Log.Warning(string.Concat(new object[] - { - "Tried to decrement map index for room ", - this.ID, - ", but mapIndex=", - this.mapIndex - })); - return; + Log.Warning("Tried to decrement map index for room " + this.ID + ", but mapIndex=" + this.mapIndex); + } + else + { + this.mapIndex = (sbyte)(this.mapIndex - 1); } - this.mapIndex -= 1; } public float GetStat(RoomStatDef roomStat) @@ -493,13 +536,13 @@ private void UpdateRoomStatsAndRole() { this.stats = new DefMap(); } - foreach (RoomStatDef current in from x in DefDatabase.AllDefs + foreach (RoomStatDef item in from x in DefDatabase.AllDefs orderby x.updatePriority descending select x) { - this.stats[current] = current.Worker.GetScore(this); + this.stats[item] = item.Worker.GetScore(this); } - this.role = DefDatabase.AllDefs.MaxBy((RoomRoleDef x) => x.Worker.GetScore(this)); + this.role = DefDatabase.AllDefs.MaxBy((Func)((RoomRoleDef x) => x.Worker.GetScore(this))); } else { @@ -511,53 +554,20 @@ orderby x.updatePriority descending internal void DebugDraw() { int hashCode = this.GetHashCode(); - foreach (IntVec3 current in this.Cells) + foreach (IntVec3 cell in this.Cells) { - CellRenderer.RenderCell(current, (float)hashCode * 0.01f); + CellRenderer.RenderCell(cell, (float)((float)hashCode * 0.0099999997764825821)); } } internal string DebugString() { - return string.Concat(new object[] - { - "Room ID=", - this.ID, - "\n first cell=", - this.Cells.FirstOrDefault(), - "\n RegionCount=", - this.RegionCount, - "\n RegionType=", - this.RegionType, - "\n CellCount=", - this.CellCount, - "\n OpenRoofCount=", - this.OpenRoofCount, - "\n numRegionsTouchingMapEdge=", - this.numRegionsTouchingMapEdge, - "\n lastChangeTick=", - this.lastChangeTick, - "\n isPrisonCell=", - this.isPrisonCell, - "\n RoomGroup=", - (this.Group == null) ? "null" : this.Group.ID.ToString() - }); + return "Room ID=" + this.ID + "\n first cell=" + this.Cells.FirstOrDefault() + "\n RegionCount=" + this.RegionCount + "\n RegionType=" + this.RegionType + "\n CellCount=" + this.CellCount + "\n OpenRoofCount=" + this.OpenRoofCount + "\n numRegionsTouchingMapEdge=" + this.numRegionsTouchingMapEdge + "\n lastChangeTick=" + this.lastChangeTick + "\n isPrisonCell=" + this.isPrisonCell + "\n RoomGroup=" + ((this.Group == null) ? "null" : this.Group.ID.ToString()); } public override string ToString() { - return string.Concat(new object[] - { - "Room(roomID=", - this.ID, - ", first=", - this.Cells.FirstOrDefault().ToString(), - ", RegionsCount=", - this.RegionCount.ToString(), - ", lastChangeTick=", - this.lastChangeTick, - ")" - }); + return "Room(roomID=" + this.ID + ", first=" + this.Cells.FirstOrDefault().ToString() + ", RegionsCount=" + this.RegionCount.ToString() + ", lastChangeTick=" + this.lastChangeTick + ")"; } public override int GetHashCode() diff --git a/Assembly-CSharp/Verse/RoomGroup.cs b/Assembly-CSharp/Verse/RoomGroup.cs index 7e6b63f5b..75d0e3115 100644 --- a/Assembly-CSharp/Verse/RoomGroup.cs +++ b/Assembly-CSharp/Verse/RoomGroup.cs @@ -33,7 +33,7 @@ public Map Map { get { - return (!this.rooms.Any()) ? null : this.rooms[0].Map; + return (!this.rooms.Any()) ? null : this.rooms[0].Map; } } @@ -69,7 +69,7 @@ public bool UsesOutdoorTemperature { get { - return this.AnyRoomTouchesMapEdge || this.OpenRoofCount >= Mathf.CeilToInt((float)this.CellCount * 0.25f); + return this.AnyRoomTouchesMapEdge || this.OpenRoofCount >= Mathf.CeilToInt((float)((float)this.CellCount * 0.25)); } } @@ -77,11 +77,13 @@ public IEnumerable Cells { get { - RoomGroup.<>c__Iterator209 <>c__Iterator = new RoomGroup.<>c__Iterator209(); - <>c__Iterator.<>f__this = this; - RoomGroup.<>c__Iterator209 expr_0E = <>c__Iterator; - expr_0E.$PC = -2; - return expr_0E; + for (int i = 0; i < this.rooms.Count; i++) + { + foreach (IntVec3 cell in this.rooms[i].Cells) + { + yield return cell; + } + } } } @@ -105,11 +107,22 @@ public IEnumerable Regions { get { - RoomGroup.<>c__Iterator20A <>c__Iterator20A = new RoomGroup.<>c__Iterator20A(); - <>c__Iterator20A.<>f__this = this; - RoomGroup.<>c__Iterator20A expr_0E = <>c__Iterator20A; - expr_0E.$PC = -2; - return expr_0E; + for (int i = 0; i < this.rooms.Count; i++) + { + List.Enumerator enumerator = this.rooms[i].Regions.GetEnumerator(); + try + { + while (enumerator.MoveNext()) + { + Region r = enumerator.Current; + yield return r; + } + } + finally + { + ((IDisposable)(object)enumerator).Dispose(); + } + } } } @@ -170,32 +183,24 @@ public void AddRoom(Room room) { if (this.rooms.Contains(room)) { - Log.Error(string.Concat(new object[] - { - "Tried to add the same room twice to RoomGroup. room=", - room, - ", roomGroup=", - this - })); - return; + Log.Error("Tried to add the same room twice to RoomGroup. room=" + room + ", roomGroup=" + this); + } + else + { + this.rooms.Add(room); } - this.rooms.Add(room); } public void RemoveRoom(Room room) { if (!this.rooms.Contains(room)) { - Log.Error(string.Concat(new object[] - { - "Tried to remove room from RoomGroup but this room is not here. room=", - room, - ", roomGroup=", - this - })); - return; + Log.Error("Tried to remove room from RoomGroup but this room is not here. room=" + room + ", roomGroup=" + this); + } + else + { + this.rooms.Remove(room); } - this.rooms.Remove(room); } public bool PushHeat(float energy) @@ -223,31 +228,15 @@ public void Notify_RoomGroupShapeChanged() public string DebugString() { - return string.Concat(new object[] - { - "RoomGroup ID=", - this.ID, - "\n first cell=", - this.Cells.FirstOrDefault(), - "\n RoomCount=", - this.RoomCount, - "\n RegionCount=", - this.RegionCount, - "\n CellCount=", - this.CellCount, - "\n OpenRoofCount=", - this.OpenRoofCount, - "\n ", - this.tempTracker.DebugString() - }); + return "RoomGroup ID=" + this.ID + "\n first cell=" + this.Cells.FirstOrDefault() + "\n RoomCount=" + this.RoomCount + "\n RegionCount=" + this.RegionCount + "\n CellCount=" + this.CellCount + "\n OpenRoofCount=" + this.OpenRoofCount + "\n " + this.tempTracker.DebugString(); } internal void DebugDraw() { int num = Gen.HashCombineInt(this.GetHashCode(), 1948571531); - foreach (IntVec3 current in this.Cells) + foreach (IntVec3 cell in this.Cells) { - CellRenderer.RenderCell(current, (float)num * 0.01f); + CellRenderer.RenderCell(cell, (float)((float)num * 0.0099999997764825821)); } this.tempTracker.DebugDraw(); } diff --git a/Assembly-CSharp/Verse/RoomGroupTempTracker.cs b/Assembly-CSharp/Verse/RoomGroupTempTracker.cs index 91fb97888..824c7ac13 100644 --- a/Assembly-CSharp/Verse/RoomGroupTempTracker.cs +++ b/Assembly-CSharp/Verse/RoomGroupTempTracker.cs @@ -41,7 +41,7 @@ private float ThinRoofCoverage { get { - return 1f - (this.thickRoofCoverage + this.noRoofCoverage); + return (float)(1.0 - (this.thickRoofCoverage + this.noRoofCoverage)); } } @@ -82,16 +82,12 @@ private void RegenerateEqualizationData() this.thickRoofCoverage = 0f; this.noRoofCoverage = 0f; this.equalizeCells.Clear(); - if (this.roomGroup.RoomCount == 0) - { - return; - } - if (!this.roomGroup.UsesOutdoorTemperature) + if (this.roomGroup.RoomCount != 0 && !this.roomGroup.UsesOutdoorTemperature) { int num = 0; - foreach (IntVec3 current in this.roomGroup.Cells) + foreach (IntVec3 cell in this.roomGroup.Cells) { - RoofDef roof = current.GetRoof(this.Map); + RoofDef roof = cell.GetRoof(this.Map); if (roof == null) { this.noRoofCoverage += 1f; @@ -104,77 +100,67 @@ private void RegenerateEqualizationData() } this.thickRoofCoverage /= (float)num; this.noRoofCoverage /= (float)num; - foreach (IntVec3 current2 in this.roomGroup.Cells) + foreach (IntVec3 cell2 in this.roomGroup.Cells) { - int i = 0; - while (i < 4) + for (int i = 0; i < 4; i++) { - IntVec3 intVec = current2 + GenAdj.CardinalDirections[i]; - IntVec3 intVec2 = current2 + GenAdj.CardinalDirections[i] * 2; - if (!intVec.InBounds(this.Map)) - { - goto IL_237; - } - Region region = intVec.GetRegion(this.Map, RegionType.Set_Passable); - if (region == null) + IntVec3 intVec = cell2 + GenAdj.CardinalDirections[i]; + IntVec3 intVec2 = cell2 + GenAdj.CardinalDirections[i] * 2; + if (intVec.InBounds(this.Map)) { - goto IL_237; - } - if (region.type == RegionType.Portal) - { - bool flag = false; - for (int j = 0; j < region.links.Count; j++) + Region region = intVec.GetRegion(this.Map, RegionType.Set_Passable); + if (region != null) { - Region regionA = region.links[j].RegionA; - Region regionB = region.links[j].RegionB; - if (regionA.Room.Group != this.roomGroup && regionA.portal == null) - { - flag = true; - break; - } - if (regionB.Room.Group != this.roomGroup && regionB.portal == null) + if (region.type == RegionType.Portal) { - flag = true; - break; + bool flag = false; + for (int j = 0; j < region.links.Count; j++) + { + Region regionA = region.links[j].RegionA; + Region regionB = region.links[j].RegionB; + if (regionA.Room.Group != this.roomGroup && regionA.portal == null) + { + flag = true; + break; + } + if (regionB.Room.Group != this.roomGroup && regionB.portal == null) + { + flag = true; + break; + } + } + if (!flag) + goto IL_0237; } + continue; } - if (!flag) - { - goto IL_237; - } - } - IL_2CC: - i++; - continue; - IL_237: - if (!intVec2.InBounds(this.Map)) - { - goto IL_2CC; } - RoomGroup roomGroup = intVec2.GetRoomGroup(this.Map); - if (roomGroup == this.roomGroup) + goto IL_0237; + IL_0237: + if (intVec2.InBounds(this.Map)) { - goto IL_2CC; - } - bool flag2 = false; - for (int k = 0; k < 4; k++) - { - IntVec3 loc = intVec2 + GenAdj.CardinalDirections[k]; - if (loc.GetRoomGroup(this.Map) == this.roomGroup) + RoomGroup roomGroup = intVec2.GetRoomGroup(this.Map); + if (roomGroup != this.roomGroup) { - flag2 = true; - break; + bool flag2 = false; + for (int k = 0; k < 4; k++) + { + IntVec3 loc = intVec2 + GenAdj.CardinalDirections[k]; + if (loc.GetRoomGroup(this.Map) == this.roomGroup) + { + flag2 = true; + break; + } + } + if (!flag2) + { + this.equalizeCells.Add(intVec2); + } } } - if (!flag2) - { - this.equalizeCells.Add(intVec2); - goto IL_2CC; - } - goto IL_2CC; } } - this.equalizeCells.Shuffle(); + this.equalizeCells.Shuffle(); } } @@ -187,9 +173,7 @@ public void EqualizeTemperature() else { if (this.roomGroup.RoomCount != 0 && this.roomGroup.Rooms[0].RegionType == RegionType.Portal) - { return; - } float num = this.ThinRoofEqualizationTempChangePerInterval(); float num2 = this.NoRoofEqualizationTempChangePerInterval(); float num3 = this.WallEqualizationTempChangePerInterval(); @@ -205,78 +189,80 @@ private float WallEqualizationTempChangePerInterval() return 0f; } float num = 0f; - int num2 = Mathf.CeilToInt((float)this.equalizeCells.Count * 0.2f); - for (int i = 0; i < num2; i++) + int num2 = Mathf.CeilToInt((float)((float)this.equalizeCells.Count * 0.20000000298023224)); + for (int num3 = 0; num3 < num2; num3++) { this.cycleIndex++; int index = this.cycleIndex % this.equalizeCells.Count; - float num3; - if (GenTemperature.TryGetDirectAirTemperatureForCell(this.equalizeCells[index], this.Map, out num3)) - { - num += num3 - this.Temperature; - } - else - { - num += Mathf.Lerp(this.Temperature, this.Map.mapTemperature.OutdoorTemp, 0.5f) - this.Temperature; - } + float num4 = default(float); + num = ((!GenTemperature.TryGetDirectAirTemperatureForCell(this.equalizeCells[index], this.Map, out num4)) ? (num + (Mathf.Lerp(this.Temperature, this.Map.mapTemperature.OutdoorTemp, 0.5f) - this.Temperature)) : (num + (num4 - this.Temperature))); } - float num4 = num / (float)num2; - float num5 = num4 * (float)this.equalizeCells.Count; - return num5 * 120f * 0.00017f / (float)this.roomGroup.CellCount; + float num5 = num / (float)num2; + float num6 = num5 * (float)this.equalizeCells.Count; + return (float)(num6 * 120.0 * 0.00016999999934341758 / (float)this.roomGroup.CellCount); } private float TempDiffFromOutdoorsAdjusted() { float num = this.Map.mapTemperature.OutdoorTemp - this.temperatureInt; - if (Mathf.Abs(num) < 100f) + if (Mathf.Abs(num) < 100.0) { return num; } - return Mathf.Sign(num) * 100f + 5f * (num - Mathf.Sign(num) * 100f); + return (float)(Mathf.Sign(num) * 100.0 + 5.0 * (num - Mathf.Sign(num) * 100.0)); } private float ThinRoofEqualizationTempChangePerInterval() { - if (this.ThinRoofCoverage < 0.001f) + if (this.ThinRoofCoverage < 0.0010000000474974513) { return 0f; } float num = this.TempDiffFromOutdoorsAdjusted(); - float num2 = num * this.ThinRoofCoverage * 5E-05f; - return num2 * 120f; + float num2 = (float)(num * this.ThinRoofCoverage * 4.9999998736893758E-05); + return (float)(num2 * 120.0); } private float NoRoofEqualizationTempChangePerInterval() { - if (this.noRoofCoverage < 0.001f) + if (this.noRoofCoverage < 0.0010000000474974513) { return 0f; } float num = this.TempDiffFromOutdoorsAdjusted(); - float num2 = num * this.noRoofCoverage * 0.0007f; - return num2 * 120f; + float num2 = (float)(num * this.noRoofCoverage * 0.000699999975040555); + return (float)(num2 * 120.0); } private float DeepEqualizationTempChangePerInterval() { - if (this.thickRoofCoverage < 0.001f) + if (this.thickRoofCoverage < 0.0010000000474974513) { return 0f; } - float num = 15f - this.temperatureInt; - if (num > 0f) + float num = (float)(15.0 - this.temperatureInt); + if (num > 0.0) { return 0f; } - float num2 = num * this.thickRoofCoverage * 5E-05f; - return num2 * 120f; + float num2 = (float)(num * this.thickRoofCoverage * 4.9999998736893758E-05); + return (float)(num2 * 120.0); } public void DebugDraw() { - foreach (IntVec3 current in this.equalizeCells) + List.Enumerator enumerator = this.equalizeCells.GetEnumerator(); + try { - CellRenderer.RenderCell(current, 0.5f); + while (enumerator.MoveNext()) + { + IntVec3 current = enumerator.Current; + CellRenderer.RenderCell(current, 0.5f); + } + } + finally + { + ((IDisposable)(object)enumerator).Dispose(); } } @@ -296,33 +282,7 @@ internal string DebugString() RoomGroupTempTracker.debugWallEq /= 40f; RoomGroupTempTracker.debugGetFrame = Time.frameCount; } - return string.Concat(new object[] - { - " thick roof coverage: ", - this.thickRoofCoverage.ToStringPercent("F0"), - "\n thin roof coverage: ", - this.ThinRoofCoverage.ToStringPercent("F0"), - "\n no roof coverage: ", - this.noRoofCoverage.ToStringPercent("F0"), - "\n\n wall equalization: ", - RoomGroupTempTracker.debugWallEq.ToStringTemperatureOffset("F3"), - "\n thin roof equalization: ", - this.ThinRoofEqualizationTempChangePerInterval().ToStringTemperatureOffset("F3"), - "\n no roof equalization: ", - this.NoRoofEqualizationTempChangePerInterval().ToStringTemperatureOffset("F3"), - "\n deep equalization: ", - this.DeepEqualizationTempChangePerInterval().ToStringTemperatureOffset("F3"), - "\n\n temp diff from outdoors, adjusted: ", - this.TempDiffFromOutdoorsAdjusted().ToStringTemperatureOffset("F3"), - "\n tempChange e=20 targ= 200C: ", - GenTemperature.ControlTemperatureTempChange(this.roomGroup.Cells.First(), this.roomGroup.Map, 20f, 200f), - "\n tempChange e=20 targ=-200C: ", - GenTemperature.ControlTemperatureTempChange(this.roomGroup.Cells.First(), this.roomGroup.Map, 20f, -200f), - "\n equalize interval ticks: ", - 120, - "\n equalize cells count:", - this.equalizeCells.Count - }); + return " thick roof coverage: " + this.thickRoofCoverage.ToStringPercent("F0") + "\n thin roof coverage: " + this.ThinRoofCoverage.ToStringPercent("F0") + "\n no roof coverage: " + this.noRoofCoverage.ToStringPercent("F0") + "\n\n wall equalization: " + RoomGroupTempTracker.debugWallEq.ToStringTemperatureOffset("F3") + "\n thin roof equalization: " + this.ThinRoofEqualizationTempChangePerInterval().ToStringTemperatureOffset("F3") + "\n no roof equalization: " + this.NoRoofEqualizationTempChangePerInterval().ToStringTemperatureOffset("F3") + "\n deep equalization: " + this.DeepEqualizationTempChangePerInterval().ToStringTemperatureOffset("F3") + "\n\n temp diff from outdoors, adjusted: " + this.TempDiffFromOutdoorsAdjusted().ToStringTemperatureOffset("F3") + "\n tempChange e=20 targ= 200C: " + GenTemperature.ControlTemperatureTempChange(this.roomGroup.Cells.First(), this.roomGroup.Map, 20f, 200f) + "\n tempChange e=20 targ=-200C: " + GenTemperature.ControlTemperatureTempChange(this.roomGroup.Cells.First(), this.roomGroup.Map, 20f, -200f) + "\n equalize interval ticks: " + 120 + "\n equalize cells count:" + this.equalizeCells.Count; } } } diff --git a/Assembly-CSharp/Verse/RoomRoleWorker.cs b/Assembly-CSharp/Verse/RoomRoleWorker.cs index 5ceb1983a..96a419416 100644 --- a/Assembly-CSharp/Verse/RoomRoleWorker.cs +++ b/Assembly-CSharp/Verse/RoomRoleWorker.cs @@ -1,5 +1,3 @@ -using System; - namespace Verse { public abstract class RoomRoleWorker diff --git a/Assembly-CSharp/Verse/RoomStatDef.cs b/Assembly-CSharp/Verse/RoomStatDef.cs index 9cf00553f..02488a343 100644 --- a/Assembly-CSharp/Verse/RoomStatDef.cs +++ b/Assembly-CSharp/Verse/RoomStatDef.cs @@ -35,7 +35,7 @@ public RoomStatWorker Worker public RoomStatScoreStage GetScoreStage(float score) { - if (this.scoreStages.NullOrEmpty()) + if (this.scoreStages.NullOrEmpty()) { return null; } @@ -44,18 +44,16 @@ public RoomStatScoreStage GetScoreStage(float score) public int GetScoreStageIndex(float score) { - if (this.scoreStages.NullOrEmpty()) + if (this.scoreStages.NullOrEmpty()) { throw new InvalidOperationException("No score stages available."); } int result = 0; - for (int i = 0; i < this.scoreStages.Count; i++) + int num = 0; + while (num < this.scoreStages.Count && score >= this.scoreStages[num].minScore) { - if (score < this.scoreStages[i].minScore) - { - break; - } - result = i; + result = num; + num++; } return result; } diff --git a/Assembly-CSharp/Verse/RoomStatScoreStage.cs b/Assembly-CSharp/Verse/RoomStatScoreStage.cs index 0c1aa871b..7a3512046 100644 --- a/Assembly-CSharp/Verse/RoomStatScoreStage.cs +++ b/Assembly-CSharp/Verse/RoomStatScoreStage.cs @@ -1,5 +1,3 @@ -using System; - namespace Verse { public class RoomStatScoreStage diff --git a/Assembly-CSharp/Verse/RoomStatWorker.cs b/Assembly-CSharp/Verse/RoomStatWorker.cs index 11b95617c..4c1f209b4 100644 --- a/Assembly-CSharp/Verse/RoomStatWorker.cs +++ b/Assembly-CSharp/Verse/RoomStatWorker.cs @@ -1,5 +1,3 @@ -using System; - namespace Verse { public abstract class RoomStatWorker diff --git a/Assembly-CSharp/Verse/Root.cs b/Assembly-CSharp/Verse/Root.cs index 435acfeb4..e80ace3ef 100644 --- a/Assembly-CSharp/Verse/Root.cs +++ b/Assembly-CSharp/Verse/Root.cs @@ -27,7 +27,7 @@ public virtual void Start() { Current.Notify_LoadedSceneChanged(); Root.CheckGlobalInit(); - Action action = delegate + Action action = (Action)delegate { this.soundRoot = new SoundRoot(); if (GenScene.InPlayScene) @@ -43,10 +43,10 @@ public virtual void Start() }; if (!PlayDataLoader.Loaded) { - LongEventHandler.QueueLongEvent(delegate + LongEventHandler.QueueLongEvent((Action)delegate { PlayDataLoader.LoadAllPlayData(false); - }, null, true, null); + }, (string)null, true, null); LongEventHandler.QueueLongEvent(action, "InitializingInterface", false, null); } else @@ -57,32 +57,31 @@ public virtual void Start() private static void CheckGlobalInit() { - if (Root.globalInitDone) + if (!Root.globalInitDone) { - return; - } - CultureInfo currentCulture = Thread.CurrentThread.CurrentCulture; - if (currentCulture.Name != "en-US") - { - Log.Warning("Unexpected culture: " + currentCulture + ". Resetting to en-US."); - Thread.CurrentThread.CurrentCulture = new CultureInfo("en-US"); - } - SteamManager.InitIfNeeded(); - string[] commandLineArgs = Environment.GetCommandLineArgs(); - if (commandLineArgs != null && commandLineArgs.Length > 1) - { - Log.Message("Command line arguments: " + GenText.ToSpaceList(commandLineArgs.Skip(1))); - } - UnityData.CopyUnityData(); - VersionControl.LogVersionNumber(); - Application.targetFrameRate = 60; - Prefs.Init(); - if (Prefs.DevMode) - { - StaticConstructorOnStartupUtility.ReportProbablyMissingAttributes(); + CultureInfo currentCulture = Thread.CurrentThread.CurrentCulture; + if (currentCulture.Name != "en-US") + { + Log.Warning("Unexpected culture: " + currentCulture + ". Resetting to en-US."); + Thread.CurrentThread.CurrentCulture = new CultureInfo("en-US"); + } + SteamManager.InitIfNeeded(); + string[] commandLineArgs = Environment.GetCommandLineArgs(); + if (commandLineArgs != null && commandLineArgs.Length > 1) + { + Log.Message("Command line arguments: " + GenText.ToSpaceList(commandLineArgs.Skip(1))); + } + UnityData.CopyUnityData(); + VersionControl.LogVersionNumber(); + Application.targetFrameRate = 60; + Prefs.Init(); + if (Prefs.DevMode) + { + StaticConstructorOnStartupUtility.ReportProbablyMissingAttributes(); + } + LongEventHandler.QueueLongEvent(new Action(StaticConstructorOnStartupUtility.CallAll), (string)null, false, null); + Root.globalInitDone = true; } - LongEventHandler.QueueLongEvent(new Action(StaticConstructorOnStartupUtility.CallAll), null, false, null); - Root.globalInitDone = true; } public virtual void Update() @@ -90,7 +89,7 @@ public virtual void Update() try { RealTime.Update(); - bool flag; + bool flag = default(bool); LongEventHandler.LongEventsUpdate(out flag); if (flag) { @@ -115,6 +114,7 @@ public virtual void Update() { Log.Notify_Exception(e); throw; + IL_0085:; } } @@ -142,6 +142,7 @@ public void OnGUI() { Log.Notify_Exception(e); throw; + IL_0075:; } } diff --git a/Assembly-CSharp/Verse/Root_Entry.cs b/Assembly-CSharp/Verse/Root_Entry.cs index 625f91966..7af5cd7af 100644 --- a/Assembly-CSharp/Verse/Root_Entry.cs +++ b/Assembly-CSharp/Verse/Root_Entry.cs @@ -1,5 +1,4 @@ using RimWorld; -using System; namespace Verse { @@ -17,18 +16,17 @@ public override void Start() public override void Update() { base.Update(); - if (LongEventHandler.ShouldWaitForEvent || this.destroyed) + if (!LongEventHandler.ShouldWaitForEvent && !base.destroyed) { - return; - } - this.musicManagerEntry.MusicManagerEntryUpdate(); - if (Find.World != null) - { - Find.World.WorldUpdate(); - } - if (Current.Game != null) - { - Current.Game.UpdateEntry(); + this.musicManagerEntry.MusicManagerEntryUpdate(); + if (Find.World != null) + { + Find.World.WorldUpdate(); + } + if (Current.Game != null) + { + Current.Game.UpdateEntry(); + } } } } diff --git a/Assembly-CSharp/Verse/Root_Play.cs b/Assembly-CSharp/Verse/Root_Play.cs index 7c2c4c753..7e9f7d3b9 100644 --- a/Assembly-CSharp/Verse/Root_Play.cs +++ b/Assembly-CSharp/Verse/Root_Play.cs @@ -15,14 +15,14 @@ public override void Start() this.musicManagerPlay = new MusicManagerPlay(); if (Find.GameInitData != null && !Find.GameInitData.gameToLoad.NullOrEmpty()) { - LongEventHandler.QueueLongEvent(delegate + LongEventHandler.QueueLongEvent((Action)delegate { SavedGameLoader.LoadGameFromSaveFile(Find.GameInitData.gameToLoad); }, "LoadingLongEvent", true, new Action(GameAndMapInitExceptionHandlers.ErrorWhileLoadingGame)); } else { - LongEventHandler.QueueLongEvent(delegate + LongEventHandler.QueueLongEvent((Action)delegate { if (Current.Game == null) { @@ -31,30 +31,30 @@ public override void Start() Current.Game.InitNewGame(); }, "GeneratingMap", true, new Action(GameAndMapInitExceptionHandlers.ErrorWhileGeneratingMap)); } - LongEventHandler.QueueLongEvent(delegate + LongEventHandler.QueueLongEvent((Action)delegate { ScreenFader.SetColor(Color.black); ScreenFader.StartFade(Color.clear, 0.5f); - }, null, false, null); + }, (string)null, false, null); } public override void Update() { base.Update(); - if (LongEventHandler.ShouldWaitForEvent || this.destroyed) + if (!LongEventHandler.ShouldWaitForEvent && !base.destroyed) { - return; - } - try - { - ShipCountdown.ShipCountdownUpdate(); - Current.Game.UpdatePlay(); - this.musicManagerPlay.MusicUpdate(); - } - catch (Exception e) - { - Log.Notify_Exception(e); - throw; + try + { + ShipCountdown.ShipCountdownUpdate(); + Current.Game.UpdatePlay(); + this.musicManagerPlay.MusicUpdate(); + } + catch (Exception e) + { + Log.Notify_Exception(e); + throw; + IL_0044:; + } } } diff --git a/Assembly-CSharp/Verse/Rot4.cs b/Assembly-CSharp/Verse/Rot4.cs index 7595d46b6..dd97bcb24 100644 --- a/Assembly-CSharp/Verse/Rot4.cs +++ b/Assembly-CSharp/Verse/Rot4.cs @@ -1,4 +1,6 @@ using System; +using System.Collections.Generic; +using System.Runtime.CompilerServices; using UnityEngine; namespace Verse @@ -7,6 +9,9 @@ public struct Rot4 : IEquatable { private byte rotInt; + [CompilerGenerated] + private static Dictionary _003C_003Ef__switch_0024map0; + public bool IsValid { get @@ -23,7 +28,7 @@ public byte AsByte } set { - this.rotInt = value % 4; + this.rotInt = (byte)((int)value % 4); } } @@ -31,7 +36,7 @@ public int AsInt { get { - return (int)this.rotInt; + return this.rotInt; } set { @@ -50,16 +55,26 @@ public float AsAngle switch (this.AsInt) { case 0: + { return 0f; + } case 1: + { return 90f; + } case 2: + { return 180f; + } case 3: + { return 270f; + } default: + { return 0f; } + } } } @@ -69,18 +84,28 @@ public Quaternion AsQuat { switch (this.rotInt) { - case 0: + case (byte)0: + { return Quaternion.identity; - case 1: + } + case (byte)1: + { return Quaternion.LookRotation(Vector3.right); - case 2: + } + case (byte)2: + { return Quaternion.LookRotation(Vector3.back); - case 3: + } + case (byte)3: + { return Quaternion.LookRotation(Vector3.left); + } default: + { Log.Error("ToQuat with Rot = " + this.AsInt); return Quaternion.identity; } + } } } @@ -138,7 +163,7 @@ public static Rot4 Invalid { return new Rot4 { - rotInt = 200 + rotInt = (byte)200 }; } } @@ -150,16 +175,26 @@ public IntVec3 FacingCell switch (this.AsInt) { case 0: + { return new IntVec3(0, 0, 1); + } case 1: + { return new IntVec3(1, 0, 0); + } case 2: + { return new IntVec3(0, 0, -1); + } case 3: + { return new IntVec3(-1, 0, 0); + } default: + { return default(IntVec3); } + } } } @@ -170,16 +205,26 @@ public Rot4 Opposite switch (this.AsInt) { case 0: + { return new Rot4(2); + } case 1: + { return new Rot4(3); + } case 2: + { return new Rot4(0); + } case 3: + { return new Rot4(1); + } default: + { return default(Rot4); } + } } } @@ -207,19 +252,19 @@ public void Rotate(RotationDirection RotDir) public static Rot4 FromAngleFlat(float angle) { - if (angle < 45f) + if (angle < 45.0) { return Rot4.North; } - if (angle < 135f) + if (angle < 135.0) { return Rot4.East; } - if (angle < 225f) + if (angle < 225.0) { return Rot4.South; } - if (angle < 315f) + if (angle < 315.0) { return Rot4.West; } @@ -257,17 +302,27 @@ public override int GetHashCode() { switch (this.rotInt) { - case 0: + case (byte)0: + { return 235515; - case 1: + } + case (byte)1: + { return 5612938; - case 2: + } + case (byte)2: + { return 1215650; - case 3: + } + case (byte)3: + { return 9231792; + } default: + { throw new InvalidOperationException("IntRot out of range."); } + } } public override string ToString() @@ -279,22 +334,32 @@ public string ToStringHuman() { switch (this.rotInt) { - case 0: + case (byte)0: + { return "North".Translate(); - case 1: + } + case (byte)1: + { return "East".Translate(); - case 2: + } + case (byte)2: + { return "South".Translate(); - case 3: + } + case (byte)3: + { return "West".Translate(); + } default: + { return "error"; } + } } public static Rot4 FromString(string str) { - int num; + int num = default(int); byte newRot; if (int.TryParse(str, out num)) { @@ -302,31 +367,60 @@ public static Rot4 FromString(string str) } else { - switch (str) + if (str != null) { - case "North": - newRot = 0; - goto IL_C5; - case "East": - newRot = 1; - goto IL_C5; - case "South": - newRot = 2; - goto IL_C5; - case "West": - newRot = 3; - goto IL_C5; + if (Rot4._003C_003Ef__switch_0024map0 == null) + { + Dictionary dictionary = new Dictionary(4); + dictionary.Add("North", 0); + dictionary.Add("East", 1); + dictionary.Add("South", 2); + dictionary.Add("West", 3); + Rot4._003C_003Ef__switch_0024map0 = dictionary; + } + int num2 = default(int); + if (Rot4._003C_003Ef__switch_0024map0.TryGetValue(str, out num2)) + { + switch (num2) + { + case 0: + { + newRot = (byte)0; + goto IL_00c5; + } + case 1: + { + newRot = (byte)1; + goto IL_00c5; + } + case 2: + { + newRot = (byte)2; + goto IL_00c5; + } + case 3: + { + newRot = (byte)3; + goto IL_00c5; + } + } + } } - newRot = 0; + newRot = (byte)0; Log.Error("Invalid rotation: " + str); } - IL_C5: + goto IL_00c5; + IL_00c5: return new Rot4(newRot); } public override bool Equals(object obj) { - return obj is Rot4 && this.Equals((Rot4)obj); + if (!(obj is Rot4)) + { + return false; + } + return this.Equals((Rot4)obj); } public bool Equals(Rot4 other) diff --git a/Assembly-CSharp/Verse/RotDrawMode.cs b/Assembly-CSharp/Verse/RotDrawMode.cs index f8f335f0e..d1575d17a 100644 --- a/Assembly-CSharp/Verse/RotDrawMode.cs +++ b/Assembly-CSharp/Verse/RotDrawMode.cs @@ -1,11 +1,9 @@ -using System; - namespace Verse { public enum RotDrawMode : byte { - Fresh, - Rotting, - Dessicated + Fresh = 0, + Rotting = 1, + Dessicated = 2 } } diff --git a/Assembly-CSharp/Verse/RotationDirection.cs b/Assembly-CSharp/Verse/RotationDirection.cs index 2085c6a3b..7e7e8d63e 100644 --- a/Assembly-CSharp/Verse/RotationDirection.cs +++ b/Assembly-CSharp/Verse/RotationDirection.cs @@ -1,11 +1,9 @@ -using System; - namespace Verse { public enum RotationDirection : byte { - None, - Clockwise, - Counterclockwise + None = 0, + Clockwise = 1, + Counterclockwise = 2 } } diff --git a/Assembly-CSharp/Verse/RulePackDef.cs b/Assembly-CSharp/Verse/RulePackDef.cs index d9ae62023..38882bf19 100644 --- a/Assembly-CSharp/Verse/RulePackDef.cs +++ b/Assembly-CSharp/Verse/RulePackDef.cs @@ -1,6 +1,4 @@ -using System; using System.Collections.Generic; -using System.Diagnostics; using Verse.Grammar; namespace Verse @@ -36,14 +34,22 @@ public List Rules } } - [DebuggerHidden] public override IEnumerable ConfigErrors() { - RulePackDef.c__Iterator1DA c__Iterator1DA = new RulePackDef.c__Iterator1DA(); - c__Iterator1DA.<>f__this = this; - RulePackDef.c__Iterator1DA expr_0E = c__Iterator1DA; - expr_0E.$PC = -2; - return expr_0E; + foreach (string item in base.ConfigErrors()) + { + yield return item; + } + if (this.include != null) + { + for (int i = 0; i < this.include.Count; i++) + { + if (this.include[i].include != null && this.include[i].include.Contains(this)) + { + yield return "includes other RulePackDef which includes it: " + this.include[i].defName; + } + } + } } public static RulePackDef Named(string defName) diff --git a/Assembly-CSharp/Verse/SafeSaver.cs b/Assembly-CSharp/Verse/SafeSaver.cs index 4b9e7257f..2acc395db 100644 --- a/Assembly-CSharp/Verse/SafeSaver.cs +++ b/Assembly-CSharp/Verse/SafeSaver.cs @@ -43,16 +43,9 @@ public static void Save(string path, string documentElementName, Action saveActi } catch (Exception ex) { - Log.Warning(string.Concat(new object[] - { - "Could not move file from \"", - SafeSaver.GetFileFullPath(path), - "\" to \"", - SafeSaver.GetOldFileFullPath(path), - "\": ", - ex - })); + Log.Warning("Could not move file from \"" + SafeSaver.GetFileFullPath(path) + "\" to \"" + SafeSaver.GetOldFileFullPath(path) + "\": " + ex); throw; + IL_008c:; } try { @@ -60,15 +53,7 @@ public static void Save(string path, string documentElementName, Action saveActi } catch (Exception ex2) { - Log.Warning(string.Concat(new object[] - { - "Could not move file from \"", - SafeSaver.GetNewFileFullPath(path), - "\" to \"", - SafeSaver.GetFileFullPath(path), - "\": ", - ex2 - })); + Log.Warning("Could not move file from \"" + SafeSaver.GetNewFileFullPath(path) + "\" to \"" + SafeSaver.GetFileFullPath(path) + "\": " + ex2); SafeSaver.RemoveFileIfExists(SafeSaver.GetFileFullPath(path), false); SafeSaver.RemoveFileIfExists(SafeSaver.GetNewFileFullPath(path), false); try @@ -77,29 +62,19 @@ public static void Save(string path, string documentElementName, Action saveActi } catch (Exception ex3) { - Log.Warning(string.Concat(new object[] - { - "Could not move file from \"", - SafeSaver.GetOldFileFullPath(path), - "\" back to \"", - SafeSaver.GetFileFullPath(path), - "\": ", - ex3 - })); + Log.Warning("Could not move file from \"" + SafeSaver.GetOldFileFullPath(path) + "\" back to \"" + SafeSaver.GetFileFullPath(path) + "\": " + ex3); } throw; + IL_015a:; } SafeSaver.RemoveFileIfExists(SafeSaver.GetOldFileFullPath(path), true); } } catch (Exception ex4) { - GenUI.ErrorDialog("ProblemSavingFile".Translate(new object[] - { - SafeSaver.GetFileFullPath(path), - ex4.ToString() - })); + GenUI.ErrorDialog("ProblemSavingFile".Translate(SafeSaver.GetFileFullPath(path), ex4.ToString())); throw; + IL_019a:; } } @@ -119,16 +94,11 @@ private static void DoSave(string fullPath, string documentElementName, Action s } catch (Exception ex) { - Log.Warning(string.Concat(new object[] - { - "An exception was thrown during saving to \"", - fullPath, - "\": ", - ex - })); + Log.Warning("An exception was thrown during saving to \"" + fullPath + "\": " + ex); Scribe.saver.ForceStop(); SafeSaver.RemoveFileIfExists(fullPath, false); throw; + IL_005d:; } } @@ -143,17 +113,11 @@ private static void RemoveFileIfExists(string path, bool rethrow) } catch (Exception ex) { - Log.Warning(string.Concat(new object[] - { - "Could not remove file \"", - path, - "\": ", - ex - })); - if (rethrow) - { - throw; - } + Log.Warning("Could not remove file \"" + path + "\": " + ex); + if (!rethrow) + goto end_IL_0016; + throw; + end_IL_0016:; } } @@ -166,6 +130,7 @@ private static void SafeMove(string from, string to) { File.Move(from, to); return; + IL_0015:; } catch (Exception ex2) { diff --git a/Assembly-CSharp/Verse/SaveFileInfo.cs b/Assembly-CSharp/Verse/SaveFileInfo.cs index 8414a925a..bd1c2f9b7 100644 --- a/Assembly-CSharp/Verse/SaveFileInfo.cs +++ b/Assembly-CSharp/Verse/SaveFileInfo.cs @@ -1,5 +1,4 @@ using RimWorld; -using System; using System.IO; using UnityEngine; @@ -49,15 +48,7 @@ public Color VersionColor { return Color.red; } - if (VersionControl.MajorFromVersionString(this.gameVersion) != VersionControl.CurrentMajor || VersionControl.MinorFromVersionString(this.gameVersion) != VersionControl.CurrentMinor) - { - if (BackCompatibility.IsSaveCompatibleWith(this.gameVersion)) - { - return Color.yellow; - } - return Color.red; - } - else + if (VersionControl.MajorFromVersionString(this.gameVersion) == VersionControl.CurrentMajor && VersionControl.MinorFromVersionString(this.gameVersion) == VersionControl.CurrentMinor) { if (VersionControl.BuildFromVersionString(this.gameVersion) != VersionControl.CurrentBuild) { @@ -65,6 +56,11 @@ public Color VersionColor } return SaveFileInfo.UnimportantTextColor; } + if (BackCompatibility.IsSaveCompatibleWith(this.gameVersion)) + { + return Color.yellow; + } + return Color.red; } } @@ -76,23 +72,15 @@ public TipSignal CompatibilityTip { return "SaveIsUnknownFormat".Translate(); } - if (VersionControl.MajorFromVersionString(this.gameVersion) != VersionControl.CurrentMajor || VersionControl.MinorFromVersionString(this.gameVersion) != VersionControl.CurrentMinor) - { - return "SaveIsFromDifferentGameVersion".Translate(new object[] - { - VersionControl.CurrentVersionString, - this.gameVersion - }); - } - if (VersionControl.BuildFromVersionString(this.gameVersion) != VersionControl.CurrentBuild) + if (VersionControl.MajorFromVersionString(this.gameVersion) == VersionControl.CurrentMajor && VersionControl.MinorFromVersionString(this.gameVersion) == VersionControl.CurrentMinor) { - return "SaveIsFromDifferentGameBuild".Translate(new object[] + if (VersionControl.BuildFromVersionString(this.gameVersion) != VersionControl.CurrentBuild) { - VersionControl.CurrentVersionString, - this.gameVersion - }); + return "SaveIsFromDifferentGameBuild".Translate(VersionControl.CurrentVersionString, this.gameVersion); + } + return "SaveIsFromThisGameBuild".Translate(); } - return "SaveIsFromThisGameBuild".Translate(); + return "SaveIsFromDifferentGameVersion".Translate(VersionControl.CurrentVersionString, this.gameVersion); } } diff --git a/Assembly-CSharp/Verse/SaveGameFilesUtility.cs b/Assembly-CSharp/Verse/SaveGameFilesUtility.cs index 5983aa5e7..f58655c46 100644 --- a/Assembly-CSharp/Verse/SaveGameFilesUtility.cs +++ b/Assembly-CSharp/Verse/SaveGameFilesUtility.cs @@ -8,15 +8,19 @@ public static class SaveGameFilesUtility { public static bool IsAutoSave(string fileName) { - return fileName.Length >= 8 && fileName.Substring(0, 8) == "Autosave"; + if (fileName.Length < 8) + { + return false; + } + return fileName.Substring(0, 8) == "Autosave"; } public static bool SavedGameNamedExists(string fileName) { - foreach (string current in from f in GenFilePaths.AllSavedGameFiles + foreach (string item in from f in GenFilePaths.AllSavedGameFiles select Path.GetFileNameWithoutExtension(f.Name)) { - if (current == fileName) + if (item == fileName) { return true; } @@ -26,15 +30,16 @@ select Path.GetFileNameWithoutExtension(f.Name)) public static string UnusedDefaultFileName(string factionLabel) { - string text = string.Empty; + string empty = string.Empty; int num = 1; - do + while (true) { - text = factionLabel + num.ToString(); + empty = factionLabel + num.ToString(); num++; + if (!SaveGameFilesUtility.SavedGameNamedExists(empty)) + break; } - while (SaveGameFilesUtility.SavedGameNamedExists(text)); - return text; + return empty; } } } diff --git a/Assembly-CSharp/Verse/SaveLoadUtility.cs b/Assembly-CSharp/Verse/SaveLoadUtility.cs index 0abfc361c..24d9f3d4f 100644 --- a/Assembly-CSharp/Verse/SaveLoadUtility.cs +++ b/Assembly-CSharp/Verse/SaveLoadUtility.cs @@ -1,5 +1,3 @@ -using System; - namespace Verse { public static class SaveLoadUtility diff --git a/Assembly-CSharp/Verse/SavedGameLoader.cs b/Assembly-CSharp/Verse/SavedGameLoader.cs index 34b70b1c4..cd31a46f2 100644 --- a/Assembly-CSharp/Verse/SavedGameLoader.cs +++ b/Assembly-CSharp/Verse/SavedGameLoader.cs @@ -22,10 +22,12 @@ public static void LoadGameFromSaveFile(string fileName) Current.Game.LoadGame(); PermadeathModeUtility.CheckUpdatePermadeathModeUniqueNameOnGameLoad(fileName); DeepProfiler.End(); - return; } - Log.Error("Could not find game XML node."); - Scribe.ForceStop(); + else + { + Log.Error("Could not find game XML node."); + Scribe.ForceStop(); + } } } } diff --git a/Assembly-CSharp/Verse/ScatterableDef.cs b/Assembly-CSharp/Verse/ScatterableDef.cs index 6a473533a..d02f88c2c 100644 --- a/Assembly-CSharp/Verse/ScatterableDef.cs +++ b/Assembly-CSharp/Verse/ScatterableDef.cs @@ -25,11 +25,11 @@ public class ScatterableDef : Def public override void PostLoad() { base.PostLoad(); - if (this.defName == "UnnamedDef") + if (base.defName == "UnnamedDef") { - this.defName = "Scatterable_" + this.texturePath; + base.defName = "Scatterable_" + this.texturePath; } - LongEventHandler.ExecuteWhenFinished(delegate + LongEventHandler.ExecuteWhenFinished((Action)delegate { this.mat = MaterialPool.MatFrom(this.texturePath, ShaderDatabase.Transparent); }); diff --git a/Assembly-CSharp/Verse/ScattererValidator.cs b/Assembly-CSharp/Verse/ScattererValidator.cs index 834f13421..8beaca6b0 100644 --- a/Assembly-CSharp/Verse/ScattererValidator.cs +++ b/Assembly-CSharp/Verse/ScattererValidator.cs @@ -1,5 +1,3 @@ -using System; - namespace Verse { public abstract class ScattererValidator diff --git a/Assembly-CSharp/Verse/ScattererValidator_Buildable.cs b/Assembly-CSharp/Verse/ScattererValidator_Buildable.cs index 3c3b9535b..ad9ebb7fa 100644 --- a/Assembly-CSharp/Verse/ScattererValidator_Buildable.cs +++ b/Assembly-CSharp/Verse/ScattererValidator_Buildable.cs @@ -1,5 +1,3 @@ -using System; - namespace Verse { public class ScattererValidator_Buildable : ScattererValidator diff --git a/Assembly-CSharp/Verse/ScattererValidator_NoNonNaturalEdifices.cs b/Assembly-CSharp/Verse/ScattererValidator_NoNonNaturalEdifices.cs index 2e7a54115..dfa02bd03 100644 --- a/Assembly-CSharp/Verse/ScattererValidator_NoNonNaturalEdifices.cs +++ b/Assembly-CSharp/Verse/ScattererValidator_NoNonNaturalEdifices.cs @@ -1,5 +1,3 @@ -using System; - namespace Verse { public class ScattererValidator_NoNonNaturalEdifices : ScattererValidator diff --git a/Assembly-CSharp/Verse/ScreenFader.cs b/Assembly-CSharp/Verse/ScreenFader.cs index c0188b99d..1f37ca936 100644 --- a/Assembly-CSharp/Verse/ScreenFader.cs +++ b/Assembly-CSharp/Verse/ScreenFader.cs @@ -1,4 +1,3 @@ -using System; using UnityEngine; namespace Verse @@ -45,24 +44,24 @@ static ScreenFader() public static void OverlayOnGUI(Vector2 windowSize) { Color color = ScreenFader.CurrentInstantColor(); - if (color.a > 0f) + if (color.a > 0.0) { if (ScreenFader.fadeTextureDirty) { ScreenFader.fadeTexture.SetPixel(0, 0, color); ScreenFader.fadeTexture.Apply(); } - GUI.Label(new Rect(-10f, -10f, windowSize.x + 10f, windowSize.y + 10f), ScreenFader.fadeTexture, ScreenFader.backgroundStyle); + GUI.Label(new Rect(-10f, -10f, (float)(windowSize.x + 10.0), (float)(windowSize.y + 10.0)), ScreenFader.fadeTexture, ScreenFader.backgroundStyle); } } private static Color CurrentInstantColor() { - if (ScreenFader.CurTime > ScreenFader.targetTime || ScreenFader.targetTime == ScreenFader.sourceTime) + if (!(ScreenFader.CurTime > ScreenFader.targetTime) && ScreenFader.targetTime != ScreenFader.sourceTime) { - return ScreenFader.targetColor; + return Color.Lerp(ScreenFader.sourceColor, ScreenFader.targetColor, (ScreenFader.CurTime - ScreenFader.sourceTime) / (ScreenFader.targetTime - ScreenFader.sourceTime)); } - return Color.Lerp(ScreenFader.sourceColor, ScreenFader.targetColor, (ScreenFader.CurTime - ScreenFader.sourceTime) / (ScreenFader.targetTime - ScreenFader.sourceTime)); + return ScreenFader.targetColor; } public static void SetColor(Color newColor) @@ -76,15 +75,17 @@ public static void SetColor(Color newColor) public static void StartFade(Color finalColor, float duration) { - if (duration <= 0f) + if (duration <= 0.0) { ScreenFader.SetColor(finalColor); - return; } - ScreenFader.sourceColor = ScreenFader.CurrentInstantColor(); - ScreenFader.targetColor = finalColor; - ScreenFader.sourceTime = ScreenFader.CurTime; - ScreenFader.targetTime = ScreenFader.CurTime + duration; + else + { + ScreenFader.sourceColor = ScreenFader.CurrentInstantColor(); + ScreenFader.targetColor = finalColor; + ScreenFader.sourceTime = ScreenFader.CurTime; + ScreenFader.targetTime = ScreenFader.CurTime + duration; + } } } } diff --git a/Assembly-CSharp/Verse/ScreenshotModeHandler.cs b/Assembly-CSharp/Verse/ScreenshotModeHandler.cs index 73f77f1b1..a983270af 100644 --- a/Assembly-CSharp/Verse/ScreenshotModeHandler.cs +++ b/Assembly-CSharp/Verse/ScreenshotModeHandler.cs @@ -1,5 +1,4 @@ using RimWorld; -using System; using UnityEngine; namespace Verse @@ -12,7 +11,19 @@ public bool FiltersCurrentEvent { get { - return this.active && (Event.current.type == EventType.Repaint || Event.current.type == EventType.Layout || (Event.current.type == EventType.MouseDown || Event.current.type == EventType.MouseUp || Event.current.type == EventType.MouseDrag)); + if (!this.active) + { + return false; + } + if (Event.current.type != EventType.Repaint && Event.current.type != EventType.Layout) + { + if (Event.current.type != 0 && Event.current.type != EventType.MouseUp && Event.current.type != EventType.MouseDrag) + { + return false; + } + return true; + } + return true; } } diff --git a/Assembly-CSharp/Verse/ScreenshotTaker.cs b/Assembly-CSharp/Verse/ScreenshotTaker.cs index aca15fa60..34553b2fb 100644 --- a/Assembly-CSharp/Verse/ScreenshotTaker.cs +++ b/Assembly-CSharp/Verse/ScreenshotTaker.cs @@ -1,6 +1,5 @@ using RimWorld; using Steamworks; -using System; namespace Verse { @@ -8,11 +7,7 @@ public static class ScreenshotTaker { public static void Update() { - if (LongEventHandler.ShouldWaitForEvent) - { - return; - } - if (KeyBindingDefOf.TakeScreenshot.JustPressed) + if (!LongEventHandler.ShouldWaitForEvent && KeyBindingDefOf.TakeScreenshot.JustPressed) { ScreenshotTaker.TakeShot(); } diff --git a/Assembly-CSharp/Verse/Scribe.cs b/Assembly-CSharp/Verse/Scribe.cs index 02816fcda..615f861f4 100644 --- a/Assembly-CSharp/Verse/Scribe.cs +++ b/Assembly-CSharp/Verse/Scribe.cs @@ -1,5 +1,3 @@ -using System; - namespace Verse { public static class Scribe @@ -27,7 +25,11 @@ public static bool EnterNode(string nodeName) { return Scribe.saver.EnterNode(nodeName); } - return (Scribe.mode != LoadSaveMode.LoadingVars && Scribe.mode != LoadSaveMode.ResolvingCrossRefs && Scribe.mode != LoadSaveMode.PostLoadInit) || Scribe.loader.EnterNode(nodeName); + if (Scribe.mode != LoadSaveMode.LoadingVars && Scribe.mode != LoadSaveMode.ResolvingCrossRefs && Scribe.mode != LoadSaveMode.PostLoadInit) + { + return true; + } + return Scribe.loader.EnterNode(nodeName); } public static void ExitNode() @@ -36,10 +38,9 @@ public static void ExitNode() { Scribe.saver.ExitNode(); } - if (Scribe.mode == LoadSaveMode.LoadingVars || Scribe.mode == LoadSaveMode.ResolvingCrossRefs || Scribe.mode == LoadSaveMode.PostLoadInit) - { - Scribe.loader.ExitNode(); - } + if (Scribe.mode != LoadSaveMode.LoadingVars && Scribe.mode != LoadSaveMode.ResolvingCrossRefs && Scribe.mode != LoadSaveMode.PostLoadInit) + return; + Scribe.loader.ExitNode(); } } } diff --git a/Assembly-CSharp/Verse/ScribeExtractor.cs b/Assembly-CSharp/Verse/ScribeExtractor.cs index 9d1c4f164..63b9442e6 100644 --- a/Assembly-CSharp/Verse/ScribeExtractor.cs +++ b/Assembly-CSharp/Verse/ScribeExtractor.cs @@ -12,63 +12,50 @@ public static T ValueFromNode(XmlNode subNode, T defaultValue) { return defaultValue; } - T result; try { try { - result = (T)((object)ParseHelper.FromString(subNode.InnerText, typeof(T))); - return result; + return (T)ParseHelper.FromString(subNode.InnerText, typeof(T)); + IL_0028:; } catch (Exception ex) { - Log.Error(string.Concat(new object[] - { - "Exception parsing node ", - subNode.OuterXml, - " into a ", - typeof(T), - ":\n", - ex.ToString() - })); + Log.Error("Exception parsing node " + subNode.OuterXml + " into a " + typeof(T) + ":\n" + ex.ToString()); } - result = default(T); + return default(T); + IL_0089: + T result; + return result; } catch (Exception arg) { Log.Error("Exception loading XML: " + arg); - result = defaultValue; + return defaultValue; + IL_00a6: + T result; + return result; } - return result; } public static T DefFromNode(XmlNode subNode) where T : Def, new() { - if (subNode == null || subNode.InnerText == null || subNode.InnerText == "null") + if (subNode != null && subNode.InnerText != null && !(subNode.InnerText == "null")) { - return (T)((object)null); - } - string defName = BackCompatibility.BackCompatibleDefName(typeof(T), subNode.InnerText); - T namedSilentFail = DefDatabase.GetNamedSilentFail(defName); - if (namedSilentFail == null) - { - Log.Error(string.Concat(new object[] + string defName = BackCompatibility.BackCompatibleDefName(typeof(T), subNode.InnerText); + T namedSilentFail = DefDatabase.GetNamedSilentFail(defName); + if (namedSilentFail == null) { - "Could not load reference to ", - typeof(T), - " named ", - subNode.InnerText - })); + Log.Error("Could not load reference to " + typeof(T) + " named " + subNode.InnerText); + } + return namedSilentFail; } - return namedSilentFail; + return (T)null; } public static T DefFromNodeUnsafe(XmlNode subNode) { - return (T)((object)GenGeneric.InvokeStaticGenericMethod(typeof(ScribeExtractor), typeof(T), "DefFromNode", new object[] - { - subNode - })); + return (T)GenGeneric.InvokeStaticGenericMethod(typeof(ScribeExtractor), typeof(T), "DefFromNode", subNode); } public static T SaveableFromNode(XmlNode subNode, object[] ctorArgs) @@ -83,85 +70,65 @@ public static T SaveableFromNode(XmlNode subNode, object[] ctorArgs) return default(T); } XmlAttribute xmlAttribute = subNode.Attributes["IsNull"]; - T result; if (xmlAttribute != null && xmlAttribute.Value == "True") { - result = default(T); + return default(T); } - else + try { - try + Type type = null; + XmlAttribute xmlAttribute2 = subNode.Attributes["Class"]; + if (xmlAttribute2 != null) { - XmlAttribute xmlAttribute2 = subNode.Attributes["Class"]; - Type type; - if (xmlAttribute2 != null) - { - type = GenTypes.GetTypeInAnyAssembly(xmlAttribute2.Value); - if (type == null) - { - Log.Error(string.Concat(new object[] - { - "Could not find class ", - xmlAttribute2.Value, - " while resolving node ", - subNode.Name, - ". Trying to use ", - typeof(T), - " instead. Full node: ", - subNode.OuterXml - })); - type = typeof(T); - } - } - else + type = GenTypes.GetTypeInAnyAssembly(xmlAttribute2.Value); + if (type == null) { + Log.Error("Could not find class " + xmlAttribute2.Value + " while resolving node " + subNode.Name + ". Trying to use " + typeof(T) + " instead. Full node: " + subNode.OuterXml); type = typeof(T); } - if (type.IsAbstract) - { - throw new ArgumentException("Can't load abstract class " + type); - } - IExposable exposable = (IExposable)Activator.CreateInstance(type, ctorArgs); - bool flag = typeof(T).IsValueType || typeof(Name).IsAssignableFrom(typeof(T)); - if (!flag) - { - Scribe.loader.crossRefs.RegisterForCrossRefResolve(exposable); - } - XmlNode curXmlParent = Scribe.loader.curXmlParent; - IExposable curParent = Scribe.loader.curParent; - string curPathRelToParent = Scribe.loader.curPathRelToParent; - Scribe.loader.curXmlParent = subNode; - Scribe.loader.curParent = exposable; - Scribe.loader.curPathRelToParent = null; - try - { - exposable.ExposeData(); - } - finally - { - Scribe.loader.curXmlParent = curXmlParent; - Scribe.loader.curParent = curParent; - Scribe.loader.curPathRelToParent = curPathRelToParent; - } - if (!flag) - { - Scribe.loader.initer.RegisterForPostLoadInit(exposable); - } - result = (T)((object)exposable); } - catch (Exception ex) + else { - result = default(T); - Log.Error(string.Concat(new object[] - { - "SaveableFromNode exception: ", - ex, - "\nSubnode:\n", - subNode.OuterXml - })); + type = typeof(T); + } + if (type.IsAbstract) + { + throw new ArgumentException("Can't load abstract class " + type); + } + IExposable exposable = (IExposable)Activator.CreateInstance(type, ctorArgs); + bool flag = typeof(T).IsValueType || typeof(Name).IsAssignableFrom(typeof(T)); + if (!flag) + { + Scribe.loader.crossRefs.RegisterForCrossRefResolve(exposable); + } + XmlNode curXmlParent = Scribe.loader.curXmlParent; + IExposable curParent = Scribe.loader.curParent; + string curPathRelToParent = Scribe.loader.curPathRelToParent; + Scribe.loader.curXmlParent = subNode; + Scribe.loader.curParent = exposable; + Scribe.loader.curPathRelToParent = (string)null; + try + { + exposable.ExposeData(); } + finally + { + Scribe.loader.curXmlParent = curXmlParent; + Scribe.loader.curParent = curParent; + Scribe.loader.curPathRelToParent = curPathRelToParent; + } + if (!flag) + { + Scribe.loader.initer.RegisterForPostLoadInit(exposable); + } + return (T)exposable; + } + catch (Exception ex) + { + T result = default(T); + Log.Error("SaveableFromNode exception: " + ex + "\nSubnode:\n" + subNode.OuterXml); + return result; } - return result; } public static LocalTargetInfo LocalTargetInfoFromNode(XmlNode node, string label, LocalTargetInfo defaultValue) @@ -172,23 +139,21 @@ public static LocalTargetInfo LocalTargetInfoFromNode(XmlNode node, string label try { string innerText = node.InnerText; - LocalTargetInfo result; if (innerText.Length != 0 && innerText[0] == '(') { - loadIDs.RegisterLoadIDReadFromXml(null, typeof(Thing), "thing"); - result = new LocalTargetInfo(IntVec3.FromString(innerText)); - return result; + loadIDs.RegisterLoadIDReadFromXml((string)null, typeof(Thing), "thing"); + return new LocalTargetInfo(IntVec3.FromString(innerText)); } loadIDs.RegisterLoadIDReadFromXml(innerText, typeof(Thing), "thing"); - result = LocalTargetInfo.Invalid; - return result; + return LocalTargetInfo.Invalid; + IL_0089:; } finally { Scribe.ExitNode(); } } - loadIDs.RegisterLoadIDReadFromXml(null, typeof(Thing), label + "/thing"); + loadIDs.RegisterLoadIDReadFromXml((string)null, typeof(Thing), label + "/thing"); return defaultValue; } @@ -200,29 +165,27 @@ public static TargetInfo TargetInfoFromNode(XmlNode node, string label, TargetIn try { string innerText = node.InnerText; - TargetInfo result; if (innerText.Length != 0 && innerText[0] == '(') { - string str; - string targetLoadID; + string str = default(string); + string targetLoadID = default(string); ScribeExtractor.ExtractCellAndMapPairFromTargetInfo(innerText, out str, out targetLoadID); - loadIDs.RegisterLoadIDReadFromXml(null, typeof(Thing), "thing"); + loadIDs.RegisterLoadIDReadFromXml((string)null, typeof(Thing), "thing"); loadIDs.RegisterLoadIDReadFromXml(targetLoadID, typeof(Map), "map"); - result = new TargetInfo(IntVec3.FromString(str), null, true); - return result; + return new TargetInfo(IntVec3.FromString(str), null, true); } loadIDs.RegisterLoadIDReadFromXml(innerText, typeof(Thing), "thing"); - loadIDs.RegisterLoadIDReadFromXml(null, typeof(Map), "map"); - result = TargetInfo.Invalid; - return result; + loadIDs.RegisterLoadIDReadFromXml((string)null, typeof(Map), "map"); + return TargetInfo.Invalid; + IL_00c3:; } finally { Scribe.ExitNode(); } } - loadIDs.RegisterLoadIDReadFromXml(null, typeof(Thing), label + "/thing"); - loadIDs.RegisterLoadIDReadFromXml(null, typeof(Map), label + "/map"); + loadIDs.RegisterLoadIDReadFromXml((string)null, typeof(Thing), label + "/thing"); + loadIDs.RegisterLoadIDReadFromXml((string)null, typeof(Map), label + "/map"); return defaultValue; } @@ -234,49 +197,45 @@ public static GlobalTargetInfo GlobalTargetInfoFromNode(XmlNode node, string lab try { string innerText = node.InnerText; - GlobalTargetInfo result; if (innerText.Length != 0 && innerText[0] == '(') { - string str; - string targetLoadID; + string str = default(string); + string targetLoadID = default(string); ScribeExtractor.ExtractCellAndMapPairFromTargetInfo(innerText, out str, out targetLoadID); - loadIDs.RegisterLoadIDReadFromXml(null, typeof(Thing), "thing"); + loadIDs.RegisterLoadIDReadFromXml((string)null, typeof(Thing), "thing"); loadIDs.RegisterLoadIDReadFromXml(targetLoadID, typeof(Map), "map"); - loadIDs.RegisterLoadIDReadFromXml(null, typeof(WorldObject), "worldObject"); - result = new GlobalTargetInfo(IntVec3.FromString(str), null, true); - return result; + loadIDs.RegisterLoadIDReadFromXml((string)null, typeof(WorldObject), "worldObject"); + return new GlobalTargetInfo(IntVec3.FromString(str), null, true); } - int tile; + int tile = default(int); if (int.TryParse(innerText, out tile)) { - loadIDs.RegisterLoadIDReadFromXml(null, typeof(Thing), "thing"); - loadIDs.RegisterLoadIDReadFromXml(null, typeof(Map), "map"); - loadIDs.RegisterLoadIDReadFromXml(null, typeof(WorldObject), "worldObject"); - result = new GlobalTargetInfo(tile); - return result; + loadIDs.RegisterLoadIDReadFromXml((string)null, typeof(Thing), "thing"); + loadIDs.RegisterLoadIDReadFromXml((string)null, typeof(Map), "map"); + loadIDs.RegisterLoadIDReadFromXml((string)null, typeof(WorldObject), "worldObject"); + return new GlobalTargetInfo(tile); } if (innerText.Length != 0 && innerText[0] == '@') { - loadIDs.RegisterLoadIDReadFromXml(null, typeof(Thing), "thing"); - loadIDs.RegisterLoadIDReadFromXml(null, typeof(Map), "map"); + loadIDs.RegisterLoadIDReadFromXml((string)null, typeof(Thing), "thing"); + loadIDs.RegisterLoadIDReadFromXml((string)null, typeof(Map), "map"); loadIDs.RegisterLoadIDReadFromXml(innerText.Substring(1), typeof(WorldObject), "worldObject"); - result = GlobalTargetInfo.Invalid; - return result; + return GlobalTargetInfo.Invalid; } loadIDs.RegisterLoadIDReadFromXml(innerText, typeof(Thing), "thing"); - loadIDs.RegisterLoadIDReadFromXml(null, typeof(Map), "map"); - loadIDs.RegisterLoadIDReadFromXml(null, typeof(WorldObject), "worldObject"); - result = GlobalTargetInfo.Invalid; - return result; + loadIDs.RegisterLoadIDReadFromXml((string)null, typeof(Map), "map"); + loadIDs.RegisterLoadIDReadFromXml((string)null, typeof(WorldObject), "worldObject"); + return GlobalTargetInfo.Invalid; + IL_01b9:; } finally { Scribe.ExitNode(); } } - loadIDs.RegisterLoadIDReadFromXml(null, typeof(Thing), label + "/thing"); - loadIDs.RegisterLoadIDReadFromXml(null, typeof(Map), label + "/map"); - loadIDs.RegisterLoadIDReadFromXml(null, typeof(WorldObject), label + "/worldObject"); + loadIDs.RegisterLoadIDReadFromXml((string)null, typeof(Thing), label + "/thing"); + loadIDs.RegisterLoadIDReadFromXml((string)null, typeof(Map), label + "/map"); + loadIDs.RegisterLoadIDReadFromXml((string)null, typeof(WorldObject), label + "/worldObject"); return defaultValue; } @@ -288,20 +247,18 @@ public static LocalTargetInfo ResolveLocalTargetInfo(LocalTargetInfo loaded, str { Thing thing = Scribe.loader.crossRefs.TakeResolvedRef("thing"); IntVec3 cell = loaded.Cell; - LocalTargetInfo result; if (thing != null) { - result = new LocalTargetInfo(thing); - return result; + return new LocalTargetInfo(thing); } - result = new LocalTargetInfo(cell); - return result; + return new LocalTargetInfo(cell); + IL_0046: + return loaded; } finally { Scribe.ExitNode(); } - return loaded; } return loaded; } @@ -315,25 +272,22 @@ public static TargetInfo ResolveTargetInfo(TargetInfo loaded, string label) Thing thing = Scribe.loader.crossRefs.TakeResolvedRef("thing"); Map map = Scribe.loader.crossRefs.TakeResolvedRef("map"); IntVec3 cell = loaded.Cell; - TargetInfo result; if (thing != null) { - result = new TargetInfo(thing); - return result; + return new TargetInfo(thing); } if (cell.IsValid && map != null) { - result = new TargetInfo(cell, map, false); - return result; + return new TargetInfo(cell, map, false); } - result = TargetInfo.Invalid; - return result; + return TargetInfo.Invalid; + IL_007a: + return loaded; } finally { Scribe.ExitNode(); } - return loaded; } return loaded; } @@ -351,42 +305,32 @@ public static GlobalTargetInfo ResolveGlobalTargetInfo(GlobalTargetInfo loaded, int tile = loaded.Tile; if (thing != null) { - GlobalTargetInfo result = new GlobalTargetInfo(thing); - return result; + return new GlobalTargetInfo(thing); } if (worldObject != null) { - GlobalTargetInfo result = new GlobalTargetInfo(worldObject); - return result; + return new GlobalTargetInfo(worldObject); } if (cell.IsValid) { - GlobalTargetInfo result; if (map != null) { - result = new GlobalTargetInfo(cell, map, false); - return result; + return new GlobalTargetInfo(cell, map, false); } - result = GlobalTargetInfo.Invalid; - return result; + return GlobalTargetInfo.Invalid; } - else + if (tile >= 0) { - GlobalTargetInfo result; - if (tile >= 0) - { - result = new GlobalTargetInfo(tile); - return result; - } - result = GlobalTargetInfo.Invalid; - return result; + return new GlobalTargetInfo(tile); } + return GlobalTargetInfo.Invalid; + IL_00d0: + return loaded; } finally { Scribe.ExitNode(); } - return loaded; } return loaded; } @@ -397,10 +341,7 @@ private static void ExtractCellAndMapPairFromTargetInfo(string str, out string c cell = str.Substring(0, num + 1); int num2 = str.IndexOf(',', num + 1); map = str.Substring(num2 + 1); - map = map.TrimStart(new char[] - { - ' ' - }); + map = map.TrimStart(' '); } } } diff --git a/Assembly-CSharp/Verse/ScribeLoader.cs b/Assembly-CSharp/Verse/ScribeLoader.cs index d754febd5..8cd0e02ca 100644 --- a/Assembly-CSharp/Verse/ScribeLoader.cs +++ b/Assembly-CSharp/Verse/ScribeLoader.cs @@ -18,7 +18,7 @@ public class ScribeLoader public void InitLoading(string filePath) { - if (Scribe.mode != LoadSaveMode.Inactive) + if (Scribe.mode != 0) { Log.Error("Called InitLoading() but current mode is " + Scribe.mode); Scribe.ForceStop(); @@ -31,16 +31,16 @@ public void InitLoading(string filePath) if (this.curPathRelToParent != null) { Log.Error("Current path relative to parent is not null in InitLoading"); - this.curPathRelToParent = null; + this.curPathRelToParent = (string)null; } try { - using (StreamReader streamReader = new StreamReader(filePath)) + using (StreamReader input = new StreamReader(filePath)) { - using (XmlTextReader xmlTextReader = new XmlTextReader(streamReader)) + using (XmlTextReader reader = new XmlTextReader(input)) { XmlDocument xmlDocument = new XmlDocument(); - xmlDocument.Load(xmlTextReader); + xmlDocument.Load(reader); this.curXmlParent = xmlDocument.DocumentElement; } } @@ -48,39 +48,32 @@ public void InitLoading(string filePath) } catch (Exception ex) { - Log.Error(string.Concat(new object[] - { - "Exception while init loading file: ", - filePath, - "\n", - ex - })); + Log.Error("Exception while init loading file: " + filePath + "\n" + ex); this.ForceStop(); throw; + IL_00e7:; } } public void InitLoadingMetaHeaderOnly(string filePath) { - if (Scribe.mode != LoadSaveMode.Inactive) + if (Scribe.mode != 0) { Log.Error("Called InitLoadingMetaHeaderOnly() but current mode is " + Scribe.mode); Scribe.ForceStop(); } try { - using (StreamReader streamReader = new StreamReader(filePath)) + using (StreamReader input = new StreamReader(filePath)) { - using (XmlTextReader xmlTextReader = new XmlTextReader(streamReader)) + using (XmlTextReader xmlTextReader = new XmlTextReader(input)) { if (!ScribeMetaHeaderUtility.ReadToMetaElement(xmlTextReader)) - { return; - } - using (XmlReader xmlReader = xmlTextReader.ReadSubtree()) + using (XmlReader reader = xmlTextReader.ReadSubtree()) { XmlDocument xmlDocument = new XmlDocument(); - xmlDocument.Load(xmlReader); + xmlDocument.Load(reader); XmlElement xmlElement = xmlDocument.CreateElement("root"); xmlElement.AppendChild(xmlDocument.DocumentElement); this.curXmlParent = xmlElement; @@ -91,15 +84,10 @@ public void InitLoadingMetaHeaderOnly(string filePath) } catch (Exception ex) { - Log.Error(string.Concat(new object[] - { - "Exception while init loading meta header: ", - filePath, - "\n", - ex - })); + Log.Error("Exception while init loading meta header: " + filePath + "\n" + ex); this.ForceStop(); throw; + IL_00f6:; } } @@ -108,23 +96,26 @@ public void FinalizeLoading() if (Scribe.mode != LoadSaveMode.LoadingVars) { Log.Error("Called FinalizeLoading() but current mode is " + Scribe.mode); - return; - } - try - { - Scribe.ExitNode(); - this.curXmlParent = null; - this.curParent = null; - this.curPathRelToParent = null; - Scribe.mode = LoadSaveMode.Inactive; - this.crossRefs.ResolveAllCrossReferences(); - this.initer.DoAllPostLoadInits(); } - catch (Exception arg) + else { - Log.Error("Exception in FinalizeLoading(): " + arg); - this.ForceStop(); - throw; + try + { + Scribe.ExitNode(); + this.curXmlParent = null; + this.curParent = null; + this.curPathRelToParent = (string)null; + Scribe.mode = LoadSaveMode.Inactive; + this.crossRefs.ResolveAllCrossReferences(); + this.initer.DoAllPostLoadInits(); + } + catch (Exception arg) + { + Log.Error("Exception in FinalizeLoading(): " + arg); + this.ForceStop(); + throw; + IL_0079:; + } } } @@ -162,7 +153,7 @@ public void ExitNode() } else { - this.curPathRelToParent = null; + this.curPathRelToParent = (string)null; } } } @@ -173,10 +164,9 @@ public void ForceStop() this.curParent = null; this.crossRefs.Clear(false); this.initer.Clear(); - if (Scribe.mode == LoadSaveMode.LoadingVars || Scribe.mode == LoadSaveMode.ResolvingCrossRefs || Scribe.mode == LoadSaveMode.PostLoadInit) - { - Scribe.mode = LoadSaveMode.Inactive; - } + if (Scribe.mode != LoadSaveMode.LoadingVars && Scribe.mode != LoadSaveMode.ResolvingCrossRefs && Scribe.mode != LoadSaveMode.PostLoadInit) + return; + Scribe.mode = LoadSaveMode.Inactive; } } } diff --git a/Assembly-CSharp/Verse/ScribeMetaHeaderUtility.cs b/Assembly-CSharp/Verse/ScribeMetaHeaderUtility.cs index 25fb7686b..eb5864dfd 100644 --- a/Assembly-CSharp/Verse/ScribeMetaHeaderUtility.cs +++ b/Assembly-CSharp/Verse/ScribeMetaHeaderUtility.cs @@ -11,10 +11,10 @@ public class ScribeMetaHeaderUtility { public enum ScribeHeaderMode { - None, - Map, - World, - Scenario + None = 0, + Map = 1, + World = 2, + Scenario = 3 } public const string MetaNodeName = "meta"; @@ -25,7 +25,7 @@ public enum ScribeHeaderMode public const string ModNamesNodeName = "modNames"; - private static ScribeMetaHeaderUtility.ScribeHeaderMode lastMode; + private static ScribeHeaderMode lastMode; public static string loadedGameVersion; @@ -40,13 +40,13 @@ public static void WriteMetaHeader() try { string currentVersionStringWithRev = VersionControl.CurrentVersionStringWithRev; - Scribe_Values.Look(ref currentVersionStringWithRev, "gameVersion", null, false); + Scribe_Values.Look(ref currentVersionStringWithRev, "gameVersion", (string)null, false); List list = (from mod in LoadedModManager.RunningMods - select mod.Identifier).ToList(); - Scribe_Collections.Look(ref list, "modIds", LookMode.Undefined, new object[0]); + select mod.Identifier).ToList(); + Scribe_Collections.Look(ref list, "modIds", LookMode.Undefined); List list2 = (from mod in LoadedModManager.RunningMods - select mod.Name).ToList(); - Scribe_Collections.Look(ref list2, "modNames", LookMode.Undefined, new object[0]); + select mod.Name).ToList(); + Scribe_Collections.Look(ref list2, "modNames", LookMode.Undefined); } finally { @@ -55,17 +55,17 @@ public static void WriteMetaHeader() } } - public static void LoadGameDataHeader(ScribeMetaHeaderUtility.ScribeHeaderMode mode, bool logVersionConflictWarning) + public static void LoadGameDataHeader(ScribeHeaderMode mode, bool logVersionConflictWarning) { ScribeMetaHeaderUtility.loadedGameVersion = "Unknown"; ScribeMetaHeaderUtility.loadedModIdsList = null; ScribeMetaHeaderUtility.loadedModNamesList = null; ScribeMetaHeaderUtility.lastMode = mode; - if (Scribe.mode != LoadSaveMode.Inactive && Scribe.EnterNode("meta")) + if (Scribe.mode != 0 && Scribe.EnterNode("meta")) { try { - Scribe_Values.Look(ref ScribeMetaHeaderUtility.loadedGameVersion, "gameVersion", null, false); + Scribe_Values.Look(ref ScribeMetaHeaderUtility.loadedGameVersion, "gameVersion", (string)null, false); Scribe_Collections.Look(ref ScribeMetaHeaderUtility.loadedModIdsList, "modIds", LookMode.Undefined, new object[0]); Scribe_Collections.Look(ref ScribeMetaHeaderUtility.loadedModNamesList, "modNames", LookMode.Undefined, new object[0]); } @@ -74,18 +74,14 @@ public static void LoadGameDataHeader(ScribeMetaHeaderUtility.ScribeHeaderMode m Scribe.ExitNode(); } } - if (logVersionConflictWarning && (mode == ScribeMetaHeaderUtility.ScribeHeaderMode.Map || !UnityData.isEditor) && !ScribeMetaHeaderUtility.VersionsMatch()) + if (logVersionConflictWarning) { - Log.Warning(string.Concat(new object[] + if (mode != ScribeHeaderMode.Map && UnityData.isEditor) + return; + if (!ScribeMetaHeaderUtility.VersionsMatch()) { - "Loaded file (", - mode, - ") is from version ", - ScribeMetaHeaderUtility.loadedGameVersion, - ", we are running version ", - VersionControl.CurrentVersionStringWithRev, - "." - })); + Log.Warning("Loaded file (" + mode + ") is from version " + ScribeMetaHeaderUtility.loadedGameVersion + ", we are running version " + VersionControl.CurrentVersionStringWithRev + "."); + } } } @@ -96,54 +92,20 @@ private static bool VersionsMatch() public static bool TryCreateDialogsForVersionMismatchWarnings(Action confirmedAction) { - string text = null; - string text2 = null; + string text = (string)null; + string text2 = (string)null; if (!BackCompatibility.IsSaveCompatibleWith(ScribeMetaHeaderUtility.loadedGameVersion) && !ScribeMetaHeaderUtility.VersionsMatch()) { text2 = "VersionMismatch".Translate(); string text3 = (!ScribeMetaHeaderUtility.loadedGameVersion.NullOrEmpty()) ? ScribeMetaHeaderUtility.loadedGameVersion : ("(" + "UnknownLower".Translate() + ")"); - if (ScribeMetaHeaderUtility.lastMode == ScribeMetaHeaderUtility.ScribeHeaderMode.Map) - { - text = "SaveGameIncompatibleWarningText".Translate(new object[] - { - text3, - VersionControl.CurrentVersionString - }); - } - else if (ScribeMetaHeaderUtility.lastMode == ScribeMetaHeaderUtility.ScribeHeaderMode.World) - { - text = "WorldFileVersionMismatch".Translate(new object[] - { - text3, - VersionControl.CurrentVersionString - }); - } - else - { - text = "FileIncompatibleWarning".Translate(new object[] - { - text3, - VersionControl.CurrentVersionString - }); - } + text = ((ScribeMetaHeaderUtility.lastMode != ScribeHeaderMode.Map) ? ((ScribeMetaHeaderUtility.lastMode != ScribeHeaderMode.World) ? "FileIncompatibleWarning".Translate(text3, VersionControl.CurrentVersionString) : "WorldFileVersionMismatch".Translate(text3, VersionControl.CurrentVersionString)) : "SaveGameIncompatibleWarningText".Translate(text3, VersionControl.CurrentVersionString)); } - string text4; - string text5; + string text4 = default(string); + string text5 = default(string); if (!ScribeMetaHeaderUtility.LoadedModsMatchesActiveMods(out text4, out text5)) { - string text6 = "ModsMismatchWarningText".Translate(new object[] - { - text4, - text5 - }); - if (text == null) - { - text = text6; - } - else - { - text = text + "\n\n" + text6; - } + string text6 = "ModsMismatchWarningText".Translate(text4, text5); + text = ((text != null) ? (text + "\n\n" + text6) : text6); if (text2 == null) { text2 = "ModsMismatchWarningTitle".Translate(); @@ -162,10 +124,10 @@ public static bool TryCreateDialogsForVersionMismatchWarnings(Action confirmedAc public static bool LoadedModsMatchesActiveMods(out string loadedModsSummary, out string runningModsSummary) { - loadedModsSummary = null; - runningModsSummary = null; + loadedModsSummary = (string)null; + runningModsSummary = (string)null; List list = (from mod in LoadedModManager.RunningMods - select mod.Identifier).ToList(); + select mod.Identifier).ToList(); if (ScribeMetaHeaderUtility.ModListsMatch(ScribeMetaHeaderUtility.loadedModIdsList, list)) { return true; @@ -185,22 +147,22 @@ public static bool LoadedModsMatchesActiveMods(out string loadedModsSummary, out private static bool ModListsMatch(List a, List b) { - if (a == null || b == null) + if (a != null && b != null) { - return false; - } - if (a.Count != b.Count) - { - return false; - } - for (int i = 0; i < a.Count; i++) - { - if (a[i] != b[i]) + if (a.Count != b.Count) { return false; } + for (int i = 0; i < a.Count; i++) + { + if (a[i] != b[i]) + { + return false; + } + } + return true; } - return true; + return false; } public static string GameVersionOf(FileInfo file) @@ -211,9 +173,9 @@ public static string GameVersionOf(FileInfo file) } try { - using (StreamReader streamReader = new StreamReader(file.FullName)) + using (StreamReader input = new StreamReader(file.FullName)) { - using (XmlTextReader xmlTextReader = new XmlTextReader(streamReader)) + using (XmlTextReader xmlTextReader = new XmlTextReader(input)) { if (ScribeMetaHeaderUtility.ReadToMetaElement(xmlTextReader) && xmlTextReader.ReadToDescendant("gameVersion")) { @@ -226,24 +188,38 @@ public static string GameVersionOf(FileInfo file) { Log.Error("Exception getting game version of " + file.Name + ": " + ex.ToString()); } - return null; + return (string)null; } public static bool ReadToMetaElement(XmlTextReader textReader) { - return ScribeMetaHeaderUtility.ReadToNextElement(textReader) && ScribeMetaHeaderUtility.ReadToNextElement(textReader) && !(textReader.Name != "meta"); + if (!ScribeMetaHeaderUtility.ReadToNextElement(textReader)) + { + return false; + } + if (!ScribeMetaHeaderUtility.ReadToNextElement(textReader)) + { + return false; + } + if (textReader.Name != "meta") + { + return false; + } + return true; } private static bool ReadToNextElement(XmlTextReader textReader) { - while (textReader.Read()) + while (true) { - if (textReader.NodeType == XmlNodeType.Element) + if (!textReader.Read()) { - return true; + return false; } + if (textReader.NodeType == XmlNodeType.Element) + break; } - return false; + return true; } } } diff --git a/Assembly-CSharp/Verse/ScribeSaver.cs b/Assembly-CSharp/Verse/ScribeSaver.cs index 02bf98317..7847a1999 100644 --- a/Assembly-CSharp/Verse/ScribeSaver.cs +++ b/Assembly-CSharp/Verse/ScribeSaver.cs @@ -16,7 +16,7 @@ public class ScribeSaver public void InitSaving(string filePath, string documentElementName) { - if (Scribe.mode != LoadSaveMode.Inactive) + if (Scribe.mode != 0) { Log.Error("Called InitSaving() but current mode is " + Scribe.mode); Scribe.ForceStop(); @@ -34,15 +34,10 @@ public void InitSaving(string filePath, string documentElementName) } catch (Exception ex) { - Log.Error(string.Concat(new object[] - { - "Exception while init saving file: ", - filePath, - "\n", - ex - })); + Log.Error("Exception while init saving file: " + filePath + "\n" + ex); this.ForceStop(); throw; + IL_00b2:; } } @@ -51,33 +46,36 @@ public void FinalizeSaving() if (Scribe.mode != LoadSaveMode.Saving) { Log.Error("Called FinalizeSaving() but current mode is " + Scribe.mode); - return; } - try + else { - if (this.writer != null) + try { - this.ExitNode(); - this.writer.WriteEndDocument(); - this.writer.Flush(); - this.writer.Close(); - this.writer = null; + if (this.writer != null) + { + this.ExitNode(); + this.writer.WriteEndDocument(); + this.writer.Flush(); + this.writer.Close(); + this.writer = null; + } + if (this.saveStream != null) + { + this.saveStream.Flush(); + this.saveStream.Close(); + this.saveStream = null; + } + Scribe.mode = LoadSaveMode.Inactive; + this.savingForDebug = false; + this.loadIDsErrorsChecker.CheckForErrorsAndClear(); } - if (this.saveStream != null) + catch (Exception arg) { - this.saveStream.Flush(); - this.saveStream.Close(); - this.saveStream = null; + Log.Error("Exception in FinalizeLoading(): " + arg); + this.ForceStop(); + throw; + IL_00bc:; } - Scribe.mode = LoadSaveMode.Inactive; - this.savingForDebug = false; - this.loadIDsErrorsChecker.CheckForErrorsAndClear(); - } - catch (Exception arg) - { - Log.Error("Exception in FinalizeLoading(): " + arg); - this.ForceStop(); - throw; } } @@ -86,9 +84,11 @@ public void WriteElement(string elementName, string value) if (this.writer == null) { Log.Error("Called WriteElemenet(), but writer is null."); - return; } - this.writer.WriteElementString(elementName, value); + else + { + this.writer.WriteElementString(elementName, value); + } } public void WriteAttribute(string attributeName, string value) @@ -96,19 +96,20 @@ public void WriteAttribute(string attributeName, string value) if (this.writer == null) { Log.Error("Called WriteAttribute(), but writer is null."); - return; } - this.writer.WriteAttributeString(attributeName, value); + else + { + this.writer.WriteAttributeString(attributeName, value); + } } public string DebugOutputFor(IExposable saveable) { - if (Scribe.mode != LoadSaveMode.Inactive) + if (Scribe.mode != 0) { Log.Error("DebugOutput needs current mode to be Inactive"); return string.Empty; } - string result; try { using (StringWriter stringWriter = new StringWriter()) @@ -123,8 +124,11 @@ public string DebugOutputFor(IExposable saveable) { Scribe.mode = LoadSaveMode.Saving; this.savingForDebug = true; - Scribe_Deep.Look(ref saveable, "saveable", new object[0]); - result = stringWriter.ToString(); + Scribe_Deep.Look(ref saveable, "saveable"); + return stringWriter.ToString(); + IL_007e: + string result; + return result; } } finally @@ -137,9 +141,11 @@ public string DebugOutputFor(IExposable saveable) { Log.Error("Exception while getting debug output: " + arg); this.ForceStop(); - result = string.Empty; + return string.Empty; + IL_00d6: + string result; + return result; } - return result; } public bool EnterNode(string nodeName) @@ -154,11 +160,10 @@ public bool EnterNode(string nodeName) public void ExitNode() { - if (this.writer == null) + if (this.writer != null) { - return; + this.writer.WriteEndElement(); } - this.writer.WriteEndElement(); } public void ForceStop() diff --git a/Assembly-CSharp/Verse/Scribe_Collections.cs b/Assembly-CSharp/Verse/Scribe_Collections.cs index b2f31e7ba..9a8515ef2 100644 --- a/Assembly-CSharp/Verse/Scribe_Collections.cs +++ b/Assembly-CSharp/Verse/Scribe_Collections.cs @@ -16,36 +16,40 @@ public static void Look(ref List list, bool saveDestroyedThings, string la { if (lookMode == LookMode.Undefined) { - if (ParseHelper.HandlesType(typeof(T))) + if (!ParseHelper.HandlesType(typeof(T))) { - lookMode = LookMode.Value; - } - else if (typeof(T) == typeof(LocalTargetInfo)) - { - lookMode = LookMode.LocalTargetInfo; - } - else if (typeof(T) == typeof(TargetInfo)) - { - lookMode = LookMode.TargetInfo; - } - else if (typeof(T) == typeof(GlobalTargetInfo)) - { - lookMode = LookMode.GlobalTargetInfo; - } - else if (typeof(Def).IsAssignableFrom(typeof(T))) - { - lookMode = LookMode.Def; - } - else - { - if (!typeof(IExposable).IsAssignableFrom(typeof(T)) || typeof(ILoadReferenceable).IsAssignableFrom(typeof(T))) + if (typeof(T) == typeof(LocalTargetInfo)) + { + lookMode = LookMode.LocalTargetInfo; + goto IL_010e; + } + if (typeof(T) == typeof(TargetInfo)) + { + lookMode = LookMode.TargetInfo; + goto IL_010e; + } + if (typeof(T) == typeof(GlobalTargetInfo)) + { + lookMode = LookMode.GlobalTargetInfo; + goto IL_010e; + } + if (typeof(Def).IsAssignableFrom(typeof(T))) + { + lookMode = LookMode.Def; + goto IL_010e; + } + if (typeof(IExposable).IsAssignableFrom(typeof(T)) && !typeof(ILoadReferenceable).IsAssignableFrom(typeof(T))) { - Log.Error("LookList call with a list of " + typeof(T) + " must have lookMode set explicitly."); - return; + lookMode = LookMode.Deep; + goto IL_010e; } - lookMode = LookMode.Deep; + Log.Error("LookList call with a list of " + typeof(T) + " must have lookMode set explicitly."); + return; } + lookMode = LookMode.Value; } + goto IL_010e; + IL_010e: if (Scribe.EnterNode(label)) { try @@ -58,44 +62,63 @@ public static void Look(ref List list, bool saveDestroyedThings, string la } else { - foreach (T current in list) + List.Enumerator enumerator = list.GetEnumerator(); + try { - if (lookMode == LookMode.Value) - { - T t = current; - Scribe_Values.Look(ref t, "li", default(T), true); - } - else if (lookMode == LookMode.LocalTargetInfo) - { - LocalTargetInfo localTargetInfo = (LocalTargetInfo)((object)current); - Scribe_TargetInfo.Look(ref localTargetInfo, saveDestroyedThings, "li"); - } - else if (lookMode == LookMode.TargetInfo) - { - TargetInfo targetInfo = (TargetInfo)((object)current); - Scribe_TargetInfo.Look(ref targetInfo, saveDestroyedThings, "li"); - } - else if (lookMode == LookMode.GlobalTargetInfo) - { - GlobalTargetInfo globalTargetInfo = (GlobalTargetInfo)((object)current); - Scribe_TargetInfo.Look(ref globalTargetInfo, saveDestroyedThings, "li"); - } - else if (lookMode == LookMode.Def) + while (enumerator.MoveNext()) { - Def def = (Def)((object)current); - Scribe_Defs.Look(ref def, "li"); - } - else if (lookMode == LookMode.Deep) - { - T t2 = current; - Scribe_Deep.Look(ref t2, saveDestroyedThings, "li", ctorArgs); - } - else if (lookMode == LookMode.Reference) - { - ILoadReferenceable loadReferenceable = (ILoadReferenceable)((object)current); - Scribe_References.Look(ref loadReferenceable, "li", saveDestroyedThings); + T current = enumerator.Current; + switch (lookMode) + { + case LookMode.Value: + { + T val = current; + Scribe_Values.Look(ref val, "li", default(T), true); + break; + } + case LookMode.LocalTargetInfo: + { + LocalTargetInfo localTargetInfo = (LocalTargetInfo)(object)current; + Scribe_TargetInfo.Look(ref localTargetInfo, saveDestroyedThings, "li"); + break; + } + case LookMode.TargetInfo: + { + TargetInfo targetInfo = (TargetInfo)(object)current; + Scribe_TargetInfo.Look(ref targetInfo, saveDestroyedThings, "li"); + break; + } + case LookMode.GlobalTargetInfo: + { + GlobalTargetInfo globalTargetInfo = (GlobalTargetInfo)(object)current; + Scribe_TargetInfo.Look(ref globalTargetInfo, saveDestroyedThings, "li"); + break; + } + case LookMode.Def: + { + Def def = (Def)(object)current; + Scribe_Defs.Look(ref def, "li"); + break; + } + case LookMode.Deep: + { + T val2 = current; + Scribe_Deep.Look(ref val2, saveDestroyedThings, "li", ctorArgs); + break; + } + case LookMode.Reference: + { + ILoadReferenceable loadReferenceable = (ILoadReferenceable)(object)current; + Scribe_References.Look(ref loadReferenceable, "li", saveDestroyedThings); + break; + } + } } } + finally + { + ((IDisposable)(object)enumerator).Dispose(); + } } } else if (Scribe.mode == LoadSaveMode.LoadingVars) @@ -106,111 +129,134 @@ public static void Look(ref List list, bool saveDestroyedThings, string la { list = null; } - else if (lookMode == LookMode.Value) + else { - list = new List(curXmlParent.ChildNodes.Count); - foreach (XmlNode subNode in curXmlParent.ChildNodes) + switch (lookMode) + { + case LookMode.Value: { - T item = ScribeExtractor.ValueFromNode(subNode, default(T)); - list.Add(item); + list = new List(curXmlParent.ChildNodes.Count); + foreach (XmlNode childNode in curXmlParent.ChildNodes) + { + T item = ScribeExtractor.ValueFromNode(childNode, default(T)); + list.Add(item); + } + break; } - } - else if (lookMode == LookMode.Deep) - { - list = new List(curXmlParent.ChildNodes.Count); - foreach (XmlNode subNode2 in curXmlParent.ChildNodes) + case LookMode.Deep: { - T item2 = ScribeExtractor.SaveableFromNode(subNode2, ctorArgs); - list.Add(item2); + list = new List(curXmlParent.ChildNodes.Count); + foreach (XmlNode childNode2 in curXmlParent.ChildNodes) + { + T item2 = ScribeExtractor.SaveableFromNode(childNode2, ctorArgs); + list.Add(item2); + } + break; } - } - else if (lookMode == LookMode.Def) - { - list = new List(curXmlParent.ChildNodes.Count); - foreach (XmlNode subNode3 in curXmlParent.ChildNodes) + case LookMode.Def: { - T item3 = ScribeExtractor.DefFromNodeUnsafe(subNode3); - list.Add(item3); + list = new List(curXmlParent.ChildNodes.Count); + foreach (XmlNode childNode3 in curXmlParent.ChildNodes) + { + T item3 = ScribeExtractor.DefFromNodeUnsafe(childNode3); + list.Add(item3); + } + break; } - } - else if (lookMode == LookMode.LocalTargetInfo) - { - list = new List(curXmlParent.ChildNodes.Count); - int num = 0; - foreach (XmlNode node in curXmlParent.ChildNodes) + case LookMode.LocalTargetInfo: { - LocalTargetInfo localTargetInfo2 = ScribeExtractor.LocalTargetInfoFromNode(node, num.ToString(), LocalTargetInfo.Invalid); - T item4 = (T)((object)localTargetInfo2); - list.Add(item4); - num++; + list = new List(curXmlParent.ChildNodes.Count); + int num = 0; + foreach (XmlNode childNode4 in curXmlParent.ChildNodes) + { + LocalTargetInfo localTargetInfo2 = ScribeExtractor.LocalTargetInfoFromNode(childNode4, num.ToString(), LocalTargetInfo.Invalid); + T item4 = (T)(object)localTargetInfo2; + list.Add(item4); + num++; + } + break; } - } - else if (lookMode == LookMode.TargetInfo) - { - list = new List(curXmlParent.ChildNodes.Count); - int num2 = 0; - foreach (XmlNode node2 in curXmlParent.ChildNodes) + case LookMode.TargetInfo: { - TargetInfo targetInfo2 = ScribeExtractor.TargetInfoFromNode(node2, num2.ToString(), TargetInfo.Invalid); - T item5 = (T)((object)targetInfo2); - list.Add(item5); - num2++; + list = new List(curXmlParent.ChildNodes.Count); + int num2 = 0; + foreach (XmlNode childNode5 in curXmlParent.ChildNodes) + { + TargetInfo targetInfo2 = ScribeExtractor.TargetInfoFromNode(childNode5, num2.ToString(), TargetInfo.Invalid); + T item5 = (T)(object)targetInfo2; + list.Add(item5); + num2++; + } + break; } - } - else if (lookMode == LookMode.GlobalTargetInfo) - { - list = new List(curXmlParent.ChildNodes.Count); - int num3 = 0; - foreach (XmlNode node3 in curXmlParent.ChildNodes) + case LookMode.GlobalTargetInfo: { - GlobalTargetInfo globalTargetInfo2 = ScribeExtractor.GlobalTargetInfoFromNode(node3, num3.ToString(), GlobalTargetInfo.Invalid); - T item6 = (T)((object)globalTargetInfo2); - list.Add(item6); - num3++; + list = new List(curXmlParent.ChildNodes.Count); + int num3 = 0; + foreach (XmlNode childNode6 in curXmlParent.ChildNodes) + { + GlobalTargetInfo globalTargetInfo2 = ScribeExtractor.GlobalTargetInfoFromNode(childNode6, num3.ToString(), GlobalTargetInfo.Invalid); + T item6 = (T)(object)globalTargetInfo2; + list.Add(item6); + num3++; + } + break; } - } - else if (lookMode == LookMode.Reference) - { - List list2 = new List(curXmlParent.ChildNodes.Count); - foreach (XmlNode xmlNode in curXmlParent.ChildNodes) + case LookMode.Reference: { - list2.Add(xmlNode.InnerText); + List list2 = new List(curXmlParent.ChildNodes.Count); + foreach (XmlNode childNode7 in curXmlParent.ChildNodes) + { + list2.Add(childNode7.InnerText); + } + Scribe.loader.crossRefs.loadIDs.RegisterLoadIDListReadFromXml(list2, string.Empty); + break; + } } - Scribe.loader.crossRefs.loadIDs.RegisterLoadIDListReadFromXml(list2, string.Empty); } } else if (Scribe.mode == LoadSaveMode.ResolvingCrossRefs) { - if (lookMode == LookMode.Reference) + switch (lookMode) + { + case LookMode.Reference: { list = Scribe.loader.crossRefs.TakeResolvedRefList(string.Empty); + break; } - else if (lookMode == LookMode.LocalTargetInfo) + case LookMode.LocalTargetInfo: { if (list != null) { for (int i = 0; i < list.Count; i++) { - list[i] = (T)((object)ScribeExtractor.ResolveLocalTargetInfo((LocalTargetInfo)((object)list[i]), i.ToString())); + list[i] = (T)(object)ScribeExtractor.ResolveLocalTargetInfo((LocalTargetInfo)(object)list[i], i.ToString()); } } + break; } - else if (lookMode == LookMode.TargetInfo) + case LookMode.TargetInfo: { if (list != null) { for (int j = 0; j < list.Count; j++) { - list[j] = (T)((object)ScribeExtractor.ResolveTargetInfo((TargetInfo)((object)list[j]), j.ToString())); + list[j] = (T)(object)ScribeExtractor.ResolveTargetInfo((TargetInfo)(object)list[j], j.ToString()); } } + break; } - else if (lookMode == LookMode.GlobalTargetInfo && list != null) + case LookMode.GlobalTargetInfo: { - for (int k = 0; k < list.Count; k++) + if (list != null) { - list[k] = (T)((object)ScribeExtractor.ResolveGlobalTargetInfo((GlobalTargetInfo)((object)list[k]), k.ToString())); + for (int k = 0; k < list.Count; k++) + { + list[k] = (T)(object)ScribeExtractor.ResolveGlobalTargetInfo((GlobalTargetInfo)(object)list[k], k.ToString()); + } } + break; + } } } } @@ -259,10 +305,19 @@ public static void Look(ref List list, bool saveDestroyedThings, string la } if (Scribe.mode == LoadSaveMode.Saving) { - foreach (KeyValuePair current in dict) + Dictionary.Enumerator enumerator = dict.GetEnumerator(); + try { - keysWorkingList.Add(current.Key); - valuesWorkingList.Add(current.Value); + while (enumerator.MoveNext()) + { + KeyValuePair current = enumerator.Current; + keysWorkingList.Add(current.Key); + valuesWorkingList.Add(current.Value); + } + } + finally + { + ((IDisposable)(object)enumerator).Dispose(); } } Scribe_Collections.Look(ref keysWorkingList, "keys", keyLookMode, new object[0]); @@ -281,63 +336,51 @@ public static void Look(ref List list, bool saveDestroyedThings, string la } } bool flag = keyLookMode == LookMode.Reference || valueLookMode == LookMode.Reference; - if ((flag && Scribe.mode == LoadSaveMode.ResolvingCrossRefs) || (!flag && Scribe.mode == LoadSaveMode.LoadingVars)) + if (flag && Scribe.mode == LoadSaveMode.ResolvingCrossRefs) { - dict.Clear(); - if (keysWorkingList == null) - { - Log.Error("Cannot fill dictionary because there are no keys."); - } - else if (valuesWorkingList == null) + goto IL_0116; + } + if (!flag && Scribe.mode == LoadSaveMode.LoadingVars) + goto IL_0116; + goto IL_0277; + IL_0116: + dict.Clear(); + if (keysWorkingList == null) + { + Log.Error("Cannot fill dictionary because there are no keys."); + } + else if (valuesWorkingList == null) + { + Log.Error("Cannot fill dictionary because there are no values."); + } + else + { + if (keysWorkingList.Count != valuesWorkingList.Count) { - Log.Error("Cannot fill dictionary because there are no values."); + Log.Error("Keys count does not match the values count while loading a dictionary (maybe keys and values were resolved during different passes?). Some elements will be skipped. keys=" + keysWorkingList.Count + ", values=" + valuesWorkingList.Count); } - else + int num = Math.Min(keysWorkingList.Count, valuesWorkingList.Count); + for (int num2 = 0; num2 < num; num2++) { - if (keysWorkingList.Count != valuesWorkingList.Count) + if (keysWorkingList[num2] == null) { - Log.Error(string.Concat(new object[] - { - "Keys count does not match the values count while loading a dictionary (maybe keys and values were resolved during different passes?). Some elements will be skipped. keys=", - keysWorkingList.Count, - ", values=", - valuesWorkingList.Count - })); + Log.Error("Null key while loading dictionary of " + typeof(K) + " and " + typeof(V) + "."); } - int num = Math.Min(keysWorkingList.Count, valuesWorkingList.Count); - for (int i = 0; i < num; i++) + else { - if (keysWorkingList[i] == null) + try { - Log.Error(string.Concat(new object[] - { - "Null key while loading dictionary of ", - typeof(K), - " and ", - typeof(V), - "." - })); + dict.Add(keysWorkingList[num2], valuesWorkingList[num2]); } - else + catch (Exception ex) { - try - { - dict.Add(keysWorkingList[i], valuesWorkingList[i]); - } - catch (Exception ex) - { - Log.Error(string.Concat(new object[] - { - "Exception in LookDictionary(node=", - label, - "): ", - ex - })); - } + Log.Error("Exception in LookDictionary(node=" + label + "): " + ex); } } } } + goto IL_0277; + IL_0277: if (Scribe.mode == LoadSaveMode.PostLoadInit) { if (keysWorkingList != null) @@ -374,32 +417,45 @@ public static void Look(ref List list, bool saveDestroyedThings, string la if (Scribe.mode == LoadSaveMode.Saving && valueHashSet != null) { list = new List(); - foreach (T current in valueHashSet) + HashSet.Enumerator enumerator = valueHashSet.GetEnumerator(); + try { - list.Add(current); + while (enumerator.MoveNext()) + { + T current = enumerator.Current; + list.Add(current); + } + } + finally + { + ((IDisposable)(object)enumerator).Dispose(); } } Scribe_Collections.Look(ref list, saveDestroyedThings, label, lookMode, new object[0]); - if ((lookMode == LookMode.Reference && Scribe.mode == LoadSaveMode.ResolvingCrossRefs) || (lookMode != LookMode.Reference && Scribe.mode == LoadSaveMode.LoadingVars)) + if (lookMode != LookMode.Reference || Scribe.mode != LoadSaveMode.ResolvingCrossRefs) + { + if (lookMode == LookMode.Reference) + return; + if (Scribe.mode != LoadSaveMode.LoadingVars) + return; + } + if (list == null) + { + valueHashSet = null; + } + else { - if (list == null) + if (valueHashSet == null) { - valueHashSet = null; + valueHashSet = new HashSet(); } else { - if (valueHashSet == null) - { - valueHashSet = new HashSet(); - } - else - { - valueHashSet.Clear(); - } - for (int i = 0; i < list.Count; i++) - { - valueHashSet.Add(list[i]); - } + valueHashSet.Clear(); + } + for (int i = 0; i < list.Count; i++) + { + valueHashSet.Add(list[i]); } } } @@ -410,32 +466,45 @@ public static void Look(ref List list, bool saveDestroyedThings, string la if (Scribe.mode == LoadSaveMode.Saving && valueStack != null) { list = new List(); - foreach (T current in valueStack) + Stack.Enumerator enumerator = valueStack.GetEnumerator(); + try { - list.Add(current); + while (enumerator.MoveNext()) + { + T current = enumerator.Current; + list.Add(current); + } + } + finally + { + ((IDisposable)(object)enumerator).Dispose(); } } Scribe_Collections.Look(ref list, label, lookMode, new object[0]); - if ((lookMode == LookMode.Reference && Scribe.mode == LoadSaveMode.ResolvingCrossRefs) || (lookMode != LookMode.Reference && Scribe.mode == LoadSaveMode.LoadingVars)) + if (lookMode != LookMode.Reference || Scribe.mode != LoadSaveMode.ResolvingCrossRefs) + { + if (lookMode == LookMode.Reference) + return; + if (Scribe.mode != LoadSaveMode.LoadingVars) + return; + } + if (list == null) + { + valueStack = null; + } + else { - if (list == null) + if (valueStack == null) { - valueStack = null; + valueStack = new Stack(); } else { - if (valueStack == null) - { - valueStack = new Stack(); - } - else - { - valueStack.Clear(); - } - for (int i = 0; i < list.Count; i++) - { - valueStack.Push(list[i]); - } + valueStack.Clear(); + } + for (int i = 0; i < list.Count; i++) + { + valueStack.Push(list[i]); } } } diff --git a/Assembly-CSharp/Verse/Scribe_Deep.cs b/Assembly-CSharp/Verse/Scribe_Deep.cs index 684c2cf32..71dacf511 100644 --- a/Assembly-CSharp/Verse/Scribe_Deep.cs +++ b/Assembly-CSharp/Verse/Scribe_Deep.cs @@ -1,4 +1,4 @@ -using System; +using System.Xml; namespace Verse { @@ -13,76 +13,60 @@ public static void Look(ref T target, bool saveDestroyedThings, string label, { if (Scribe.mode == LoadSaveMode.Saving) { - Thing thing = target as Thing; + Thing thing = ((object)target) as Thing; if (thing != null && thing.Destroyed) { if (!saveDestroyedThings) { - Log.Warning(string.Concat(new object[] - { - "Deep-saving destroyed thing ", - thing, - " with saveDestroyedThings==false. label=", - label - })); + Log.Warning("Deep-saving destroyed thing " + thing + " with saveDestroyedThings==false. label=" + label); } else if (thing.Discarded) { - Log.Warning(string.Concat(new object[] - { - "Deep-saving discarded thing ", - thing, - ". This mode means that the thing is no longer managed by anything in the code and should not be deep-saved anywhere. (even with saveDestroyedThings==true) , label=", - label - })); + Log.Warning("Deep-saving discarded thing " + thing + ". This mode means that the thing is no longer managed by anything in the code and should not be deep-saved anywhere. (even with saveDestroyedThings==true) , label=" + label); } } - IExposable exposable = target as IExposable; + IExposable exposable = ((object)target) as IExposable; if (target != null && exposable == null) { - Log.Error(string.Concat(new object[] - { - "Cannot use LookDeep to save non-IExposable non-null ", - label, - " of type ", - typeof(T) - })); - return; + Log.Error("Cannot use LookDeep to save non-IExposable non-null " + label + " of type " + typeof(T)); } - if (target == null) + else { - if (Scribe.EnterNode(label)) + if (target == null) + { + if (Scribe.EnterNode(label)) + { + try + { + Scribe.saver.WriteAttribute("IsNull", "True"); + } + finally + { + Scribe.ExitNode(); + } + } + } + else if (Scribe.EnterNode(label)) { try { - Scribe.saver.WriteAttribute("IsNull", "True"); + if (target.GetType() != typeof(T) || typeof(T).IsGenericTypeDefinition) + { + Scribe.saver.WriteAttribute("Class", GenTypes.GetTypeNameWithoutIgnoredNamespaces(target.GetType())); + } + exposable.ExposeData(); } finally { Scribe.ExitNode(); } } + Scribe.saver.loadIDsErrorsChecker.RegisterDeepSaved(target, label); } - else if (Scribe.EnterNode(label)) - { - try - { - if (target.GetType() != typeof(T) || typeof(T).IsGenericTypeDefinition) - { - Scribe.saver.WriteAttribute("Class", GenTypes.GetTypeNameWithoutIgnoredNamespaces(target.GetType())); - } - exposable.ExposeData(); - } - finally - { - Scribe.ExitNode(); - } - } - Scribe.saver.loadIDsErrorsChecker.RegisterDeepSaved(target, label); } else if (Scribe.mode == LoadSaveMode.LoadingVars) { - target = ScribeExtractor.SaveableFromNode(Scribe.loader.curXmlParent[label], ctorArgs); + target = ScribeExtractor.SaveableFromNode((XmlNode)Scribe.loader.curXmlParent[label], ctorArgs); } } } diff --git a/Assembly-CSharp/Verse/Scribe_Defs.cs b/Assembly-CSharp/Verse/Scribe_Defs.cs index afb3c1508..d9ade6e73 100644 --- a/Assembly-CSharp/Verse/Scribe_Defs.cs +++ b/Assembly-CSharp/Verse/Scribe_Defs.cs @@ -1,4 +1,4 @@ -using System; +using System.Xml; namespace Verse { @@ -8,20 +8,12 @@ public static class Scribe_Defs { if (Scribe.mode == LoadSaveMode.Saving) { - string text; - if (value == null) - { - text = "null"; - } - else - { - text = value.defName; - } + string text = (value != null) ? ((Def)(object)value).defName : "null"; Scribe_Values.Look(ref text, label, "null", false); } else if (Scribe.mode == LoadSaveMode.LoadingVars) { - value = ScribeExtractor.DefFromNode(Scribe.loader.curXmlParent[label]); + value = ScribeExtractor.DefFromNode((XmlNode)Scribe.loader.curXmlParent[label]); } } } diff --git a/Assembly-CSharp/Verse/Scribe_References.cs b/Assembly-CSharp/Verse/Scribe_References.cs index 4f2c2eefc..fe38e1887 100644 --- a/Assembly-CSharp/Verse/Scribe_References.cs +++ b/Assembly-CSharp/Verse/Scribe_References.cs @@ -1,4 +1,3 @@ -using System; using System.Xml; namespace Verse @@ -12,56 +11,40 @@ public static void Look(ref T refee, string label, bool saveDestroyedThings = if (refee == null) { Scribe.saver.WriteElement(label, "null"); - return; } - Thing thing = refee as Thing; - if (thing != null && Scribe_References.CheckSaveReferenceToDestroyedThing(thing, label, saveDestroyedThings)) - { - return; - } - if (UnityData.isDebugBuild && thing != null) + else { - if (!thing.def.HasThingIDNumber) - { - Log.Error("Trying to cross-reference save Thing which lacks ID number: " + refee); - Scribe.saver.WriteElement(label, "null"); + Thing thing = ((object)refee) as Thing; + if (thing != null && Scribe_References.CheckSaveReferenceToDestroyedThing(thing, label, saveDestroyedThings)) return; - } - if (thing.IsSaveCompressible()) + if (UnityData.isDebugBuild && thing != null) { - Log.Error("Trying to save a reference to a thing that will be compressed away: " + refee); - Scribe.saver.WriteElement(label, "null"); - return; + if (!thing.def.HasThingIDNumber) + { + Log.Error("Trying to cross-reference save Thing which lacks ID number: " + refee); + Scribe.saver.WriteElement(label, "null"); + return; + } + if (thing.IsSaveCompressible()) + { + Log.Error("Trying to save a reference to a thing that will be compressed away: " + refee); + Scribe.saver.WriteElement(label, "null"); + return; + } } + string uniqueLoadID = refee.GetUniqueLoadID(); + Scribe.saver.WriteElement(label, uniqueLoadID); + Scribe.saver.loadIDsErrorsChecker.RegisterReferenced((ILoadReferenceable)(object)refee, label); } - string uniqueLoadID = refee.GetUniqueLoadID(); - Scribe.saver.WriteElement(label, uniqueLoadID); - Scribe.saver.loadIDsErrorsChecker.RegisterReferenced(refee, label); } else if (Scribe.mode == LoadSaveMode.LoadingVars) { if (Scribe.loader.curParent != null && Scribe.loader.curParent.GetType().IsValueType) { - Log.Warning(string.Concat(new object[] - { - "Trying to load reference of an object of type ", - typeof(T), - " with label ", - label, - ", but our current node is a value type. The reference won't be loaded properly. curParent=", - Scribe.loader.curParent - })); + Log.Warning("Trying to load reference of an object of type " + typeof(T) + " with label " + label + ", but our current node is a value type. The reference won't be loaded properly. curParent=" + Scribe.loader.curParent); } XmlNode xmlNode = Scribe.loader.curXmlParent[label]; - string targetLoadID; - if (xmlNode != null) - { - targetLoadID = xmlNode.InnerText; - } - else - { - targetLoadID = null; - } + string targetLoadID = (xmlNode == null) ? null : xmlNode.InnerText; Scribe.loader.crossRefs.loadIDs.RegisterLoadIDReadFromXml(targetLoadID, typeof(T), label); } else if (Scribe.mode == LoadSaveMode.ResolvingCrossRefs) @@ -83,13 +66,7 @@ public static bool CheckSaveReferenceToDestroyedThing(Thing th, string label, bo } if (th.Discarded) { - Log.Warning(string.Concat(new object[] - { - "Trying to save reference to a discarded thing ", - th, - " with saveDestroyedThings=true. This means that it's not deep-saved anywhere and is no longer managed by anything in the code, so saving its reference will always fail. , label=", - label - })); + Log.Warning("Trying to save reference to a discarded thing " + th + " with saveDestroyedThings=true. This means that it's not deep-saved anywhere and is no longer managed by anything in the code, so saving its reference will always fail. , label=" + label); Scribe.saver.WriteElement(label, "null"); return true; } diff --git a/Assembly-CSharp/Verse/Scribe_TargetInfo.cs b/Assembly-CSharp/Verse/Scribe_TargetInfo.cs index add9b92ff..c396b0a0e 100644 --- a/Assembly-CSharp/Verse/Scribe_TargetInfo.cs +++ b/Assembly-CSharp/Verse/Scribe_TargetInfo.cs @@ -1,5 +1,4 @@ using RimWorld.Planet; -using System; namespace Verse { @@ -27,9 +26,7 @@ public static void Look(ref LocalTargetInfo value, bool saveDestroyedThings, str if (!value.Equals(defaultValue)) { if (value.Thing != null && Scribe_References.CheckSaveReferenceToDestroyedThing(value.Thing, label, saveDestroyedThings)) - { return; - } Scribe.saver.WriteElement(label, value.ToString()); } } @@ -65,15 +62,15 @@ public static void Look(ref TargetInfo value, bool saveDestroyedThings, string l if (!value.Equals(defaultValue)) { if (value.Thing != null && Scribe_References.CheckSaveReferenceToDestroyedThing(value.Thing, label, saveDestroyedThings)) - { return; - } if (!value.HasThing && value.Cell.IsValid && (value.Map == null || !Find.Maps.Contains(value.Map))) { Scribe.saver.WriteElement(label, "null"); - return; } - Scribe.saver.WriteElement(label, value.ToString()); + else + { + Scribe.saver.WriteElement(label, value.ToString()); + } } } else if (Scribe.mode == LoadSaveMode.LoadingVars) @@ -108,20 +105,19 @@ public static void Look(ref GlobalTargetInfo value, bool saveDestroyedThings, st if (!value.Equals(defaultValue)) { if (value.Thing != null && Scribe_References.CheckSaveReferenceToDestroyedThing(value.Thing, label, saveDestroyedThings)) - { return; - } if (value.WorldObject != null && !value.WorldObject.Spawned) { Scribe.saver.WriteElement(label, "null"); - return; } - if (!value.HasThing && !value.HasWorldObject && value.Cell.IsValid && (value.Map == null || !Find.Maps.Contains(value.Map))) + else if (!value.HasThing && !value.HasWorldObject && value.Cell.IsValid && (value.Map == null || !Find.Maps.Contains(value.Map))) { Scribe.saver.WriteElement(label, "null"); - return; } - Scribe.saver.WriteElement(label, value.ToString()); + else + { + Scribe.saver.WriteElement(label, value.ToString()); + } } } else if (Scribe.mode == LoadSaveMode.LoadingVars) diff --git a/Assembly-CSharp/Verse/Scribe_Values.cs b/Assembly-CSharp/Verse/Scribe_Values.cs index f57f093a9..658e3de10 100644 --- a/Assembly-CSharp/Verse/Scribe_Values.cs +++ b/Assembly-CSharp/Verse/Scribe_Values.cs @@ -1,36 +1,40 @@ -using System; +using System.Xml; namespace Verse { public static class Scribe_Values { - public static void Look(ref T value, string label, T defaultValue = null, bool forceSave = false) + public static void Look(ref T value, string label, T defaultValue = default(T), bool forceSave = false) { if (Scribe.mode == LoadSaveMode.Saving) { if (typeof(T) == typeof(TargetInfo)) { Log.Error("Saving a TargetInfo " + label + " with Scribe_Values. TargetInfos must be saved with Scribe_TargetInfo."); - return; } - if (typeof(Thing).IsAssignableFrom(typeof(T))) + else if (typeof(Thing).IsAssignableFrom(typeof(T))) { Log.Error("Using Scribe_Values with a Thing reference " + label + ". Use Scribe_References or Scribe_Deep instead."); - return; } - if (typeof(IExposable).IsAssignableFrom(typeof(T))) + else if (typeof(IExposable).IsAssignableFrom(typeof(T))) { Log.Error("Using Scribe_Values with a IExposable reference " + label + ". Use Scribe_References or Scribe_Deep instead."); - return; } - if (forceSave || (value == null && defaultValue != null) || (value != null && !value.Equals(defaultValue))) + else { + if (!forceSave && (value != null || defaultValue == null)) + { + if (value == null) + return; + if (value.Equals(defaultValue)) + return; + } Scribe.saver.WriteElement(label, value.ToString()); } } else if (Scribe.mode == LoadSaveMode.LoadingVars) { - value = ScribeExtractor.ValueFromNode(Scribe.loader.curXmlParent[label], defaultValue); + value = ScribeExtractor.ValueFromNode((XmlNode)Scribe.loader.curXmlParent[label], defaultValue); } } } diff --git a/Assembly-CSharp/Verse/Section.cs b/Assembly-CSharp/Verse/Section.cs index 11b92e83b..514481194 100644 --- a/Assembly-CSharp/Verse/Section.cs +++ b/Assembly-CSharp/Verse/Section.cs @@ -39,26 +39,20 @@ public Section(IntVec3 sectCoords, Map map) { this.botLeft = sectCoords * 17; this.map = map; - foreach (Type current in typeof(SectionLayer).AllSubclassesNonAbstract()) + foreach (Type item in typeof(SectionLayer).AllSubclassesNonAbstract()) { - this.layers.Add((SectionLayer)Activator.CreateInstance(current, new object[] - { - this - })); + this.layers.Add((SectionLayer)Activator.CreateInstance(item, this)); } } public void DrawSection(SectionLayerPhaseDef phase, bool drawSunShadowsOnly) { int count = this.layers.Count; - for (int i = 0; i < count; i++) + for (int num = 0; num < count; num++) { - if (this.layers[i].Phase == phase) + if (this.layers[num].Phase == phase && (!drawSunShadowsOnly || this.layers[num] is SectionLayer_SunShadows)) { - if (!drawSunShadowsOnly || this.layers[i] is SectionLayer_SunShadows) - { - this.layers[i].DrawLayer(); - } + this.layers[num].DrawLayer(); } } if (!drawSunShadowsOnly && DebugViewSettings.drawSectionEdges) @@ -84,7 +78,7 @@ public void RegenerateLayers(MapMeshFlag changeType) for (int i = 0; i < this.layers.Count; i++) { SectionLayer sectionLayer = this.layers[i]; - if ((sectionLayer.relevantChangeTypes & changeType) != MapMeshFlag.None) + if ((sectionLayer.relevantChangeTypes & changeType) != 0) { sectionLayer.Regenerate(); } @@ -95,7 +89,7 @@ public SectionLayer GetLayer(Type type) { return (from sect in this.layers where sect.GetType() == type - select sect).FirstOrDefault(); + select sect).FirstOrDefault(); } } } diff --git a/Assembly-CSharp/Verse/SectionLayer.cs b/Assembly-CSharp/Verse/SectionLayer.cs index 765a6b1f7..d5e2550a7 100644 --- a/Assembly-CSharp/Verse/SectionLayer.cs +++ b/Assembly-CSharp/Verse/SectionLayer.cs @@ -44,13 +44,13 @@ public SectionLayer(Section section) public LayerSubMesh GetSubMesh(Material material) { - if (material == null) + if ((UnityEngine.Object)material == (UnityEngine.Object)null) { return null; } for (int i = 0; i < this.subMeshes.Count; i++) { - if (this.subMeshes[i].material == material) + if ((UnityEngine.Object)this.subMeshes[i].material == (UnityEngine.Object)material) { return this.subMeshes[i]; } @@ -58,13 +58,7 @@ public LayerSubMesh GetSubMesh(Material material) Mesh mesh = new Mesh(); if (UnityData.isEditor) { - mesh.name = string.Concat(new object[] - { - "SectionLayerSubMesh_", - base.GetType().Name, - "_", - this.Map.Tile - }); + mesh.name = "SectionLayerSubMesh_" + base.GetType().Name + "_" + this.Map.Tile; } LayerSubMesh layerSubMesh = new LayerSubMesh(mesh, material); this.subMeshes.Add(layerSubMesh); @@ -84,17 +78,16 @@ protected void FinalizeMesh(MeshParts tags) public virtual void DrawLayer() { - if (!this.Visible) - { - return; - } - int count = this.subMeshes.Count; - for (int i = 0; i < count; i++) + if (this.Visible) { - LayerSubMesh layerSubMesh = this.subMeshes[i]; - if (layerSubMesh.finalized && !layerSubMesh.disabled) + int count = this.subMeshes.Count; + for (int num = 0; num < count; num++) { - Graphics.DrawMesh(layerSubMesh.mesh, Vector3.zero, Quaternion.identity, layerSubMesh.material, 0); + LayerSubMesh layerSubMesh = this.subMeshes[num]; + if (layerSubMesh.finalized && !layerSubMesh.disabled) + { + Graphics.DrawMesh(layerSubMesh.mesh, Vector3.zero, Quaternion.identity, layerSubMesh.material, 0); + } } } } @@ -103,9 +96,18 @@ public virtual void DrawLayer() protected void ClearSubMeshes(MeshParts parts) { - foreach (LayerSubMesh current in this.subMeshes) + List.Enumerator enumerator = this.subMeshes.GetEnumerator(); + try + { + while (enumerator.MoveNext()) + { + LayerSubMesh current = enumerator.Current; + current.Clear(parts); + } + } + finally { - current.Clear(parts); + ((IDisposable)(object)enumerator).Dispose(); } } } diff --git a/Assembly-CSharp/Verse/SectionLayerGeometryMaker_Solid.cs b/Assembly-CSharp/Verse/SectionLayerGeometryMaker_Solid.cs index 27ce5da79..408608dcb 100644 --- a/Assembly-CSharp/Verse/SectionLayerGeometryMaker_Solid.cs +++ b/Assembly-CSharp/Verse/SectionLayerGeometryMaker_Solid.cs @@ -1,4 +1,3 @@ -using System; using UnityEngine; namespace Verse @@ -16,14 +15,14 @@ public static void MakeBaseGeometry(Section section, LayerSubMesh sm, AltitudeLa for (int j = cellRect.minZ; j <= cellRect.maxZ; j++) { sm.verts.Add(new Vector3((float)i, y, (float)j)); - sm.verts.Add(new Vector3((float)i, y, (float)j + 0.5f)); + sm.verts.Add(new Vector3((float)i, y, (float)((float)j + 0.5))); sm.verts.Add(new Vector3((float)i, y, (float)(j + 1))); - sm.verts.Add(new Vector3((float)i + 0.5f, y, (float)(j + 1))); + sm.verts.Add(new Vector3((float)((float)i + 0.5), y, (float)(j + 1))); sm.verts.Add(new Vector3((float)(i + 1), y, (float)(j + 1))); - sm.verts.Add(new Vector3((float)(i + 1), y, (float)j + 0.5f)); + sm.verts.Add(new Vector3((float)(i + 1), y, (float)((float)j + 0.5))); sm.verts.Add(new Vector3((float)(i + 1), y, (float)j)); - sm.verts.Add(new Vector3((float)i + 0.5f, y, (float)j)); - sm.verts.Add(new Vector3((float)i + 0.5f, y, (float)j + 0.5f)); + sm.verts.Add(new Vector3((float)((float)i + 0.5), y, (float)j)); + sm.verts.Add(new Vector3((float)((float)i + 0.5), y, (float)((float)j + 0.5))); } } int num = cellRect.Area * 8 * 3; diff --git a/Assembly-CSharp/Verse/SectionLayerPhaseDef.cs b/Assembly-CSharp/Verse/SectionLayerPhaseDef.cs index 31419d8d6..29252cb6d 100644 --- a/Assembly-CSharp/Verse/SectionLayerPhaseDef.cs +++ b/Assembly-CSharp/Verse/SectionLayerPhaseDef.cs @@ -1,5 +1,3 @@ -using System; - namespace Verse { public class SectionLayerPhaseDef : Def diff --git a/Assembly-CSharp/Verse/SectionLayer_BuildingsDamage.cs b/Assembly-CSharp/Verse/SectionLayer_BuildingsDamage.cs index 4cbff4824..c632e1173 100644 --- a/Assembly-CSharp/Verse/SectionLayer_BuildingsDamage.cs +++ b/Assembly-CSharp/Verse/SectionLayer_BuildingsDamage.cs @@ -1,4 +1,3 @@ -using System; using System.Collections.Generic; using UnityEngine; @@ -10,24 +9,30 @@ public class SectionLayer_BuildingsDamage : SectionLayer public SectionLayer_BuildingsDamage(Section section) : base(section) { - this.relevantChangeTypes = (MapMeshFlag.Buildings | MapMeshFlag.BuildingsDamage); + base.relevantChangeTypes = (MapMeshFlag.Buildings | MapMeshFlag.BuildingsDamage); } public override void Regenerate() { base.ClearSubMeshes(MeshParts.All); - foreach (IntVec3 current in this.section.CellRect) + foreach (IntVec3 item in base.section.CellRect) { + IntVec3 current = item; List list = base.Map.thingGrid.ThingsListAt(current); int count = list.Count; - for (int i = 0; i < count; i++) + for (int num = 0; num < count; num++) { - Building building = list[i] as Building; + Building building = list[num] as Building; if (building != null && building.def.useHitPoints && building.HitPoints < building.MaxHitPoints && building.def.drawDamagedOverlay) { - if (building.Position.x == current.x && building.Position.z == current.z) + IntVec3 position = building.Position; + if (position.x == current.x) { - this.PrintDamageVisualsFrom(building); + IntVec3 position2 = building.Position; + if (position2.z == current.z) + { + this.PrintDamageVisualsFrom(building); + } } } } @@ -38,9 +43,7 @@ public override void Regenerate() private void PrintDamageVisualsFrom(Building b) { if (b.def.graphicData != null && b.def.graphicData.damageData != null && !b.def.graphicData.damageData.enabled) - { return; - } this.PrintScratches(b); this.PrintCornersAndEdges(b); } @@ -56,44 +59,44 @@ private void PrintScratches(Building b) num++; } } - if (num == 0) - { - return; - } - Rect rect = BuildingsDamageSectionLayerUtility.GetDamageRect(b); - float num2 = Mathf.Min(0.5f * Mathf.Min(rect.width, rect.height), 1f); - rect = rect.ContractedBy(num2 / 2f); - if (rect.width <= 0f || rect.height <= 0f) - { - return; - } - float num3 = Mathf.Max(rect.width, rect.height) * 0.7f; - SectionLayer_BuildingsDamage.scratches.Clear(); - Rand.PushState(); - Rand.Seed = b.thingIDNumber * 3697; - for (int j = 0; j < num; j++) - { - this.AddScratch(b, rect.width, rect.height, ref num3); - } - Rand.PopState(); - float damageTexturesAltitude = this.GetDamageTexturesAltitude(b); - IList scratchMats = BuildingsDamageSectionLayerUtility.GetScratchMats(b); - Rand.PushState(); - Rand.Seed = b.thingIDNumber * 7; - for (int k = 0; k < SectionLayer_BuildingsDamage.scratches.Count; k++) + if (num != 0) { - float x = SectionLayer_BuildingsDamage.scratches[k].x; - float y = SectionLayer_BuildingsDamage.scratches[k].y; - float rot = Rand.Range(0f, 360f); - float num4 = num2; - if (rect.width > 0.95f && rect.height > 0.95f) + Rect rect = BuildingsDamageSectionLayerUtility.GetDamageRect(b); + float num2 = Mathf.Min((float)(0.5 * Mathf.Min(rect.width, rect.height)), 1f); + rect = rect.ContractedBy((float)(num2 / 2.0)); + if (!(rect.width <= 0.0) && !(rect.height <= 0.0)) { - num4 *= Rand.Range(0.85f, 1f); + float num3 = (float)(Mathf.Max(rect.width, rect.height) * 0.699999988079071); + SectionLayer_BuildingsDamage.scratches.Clear(); + Rand.PushState(); + Rand.Seed = b.thingIDNumber * 3697; + for (int num4 = 0; num4 < num; num4++) + { + this.AddScratch(b, rect.width, rect.height, ref num3); + } + Rand.PopState(); + float damageTexturesAltitude = this.GetDamageTexturesAltitude(b); + IList scratchMats = BuildingsDamageSectionLayerUtility.GetScratchMats(b); + Rand.PushState(); + Rand.Seed = b.thingIDNumber * 7; + for (int j = 0; j < SectionLayer_BuildingsDamage.scratches.Count; j++) + { + Vector2 vector = SectionLayer_BuildingsDamage.scratches[j]; + float x = vector.x; + Vector2 vector2 = SectionLayer_BuildingsDamage.scratches[j]; + float y = vector2.y; + float rot = Rand.Range(0f, 360f); + float num5 = num2; + if (rect.width > 0.949999988079071 && rect.height > 0.949999988079071) + { + num5 *= Rand.Range(0.85f, 1f); + } + Vector3 center = new Vector3(rect.xMin + x, damageTexturesAltitude, rect.yMin + y); + Printer_Plane.PrintPlane(this, center, new Vector2(num5, num5), scratchMats.RandomElement(), rot, false, null, null, 0f); + } + Rand.PopState(); } - Vector3 center = new Vector3(rect.xMin + x, damageTexturesAltitude, rect.yMin + y); - Printer_Plane.PrintPlane(this, center, new Vector2(num4, num4), scratchMats.RandomElement(), rot, false, null, null, 0f); } - Rand.PopState(); } private void AddScratch(Building b, float rectWidth, float rectHeight, ref float minDist) @@ -110,10 +113,21 @@ private void AddScratch(Building b, float rectWidth, float rectHeight, ref float float num3 = 3.40282347E+38f; for (int j = 0; j < SectionLayer_BuildingsDamage.scratches.Count; j++) { - float num4 = (num - SectionLayer_BuildingsDamage.scratches[j].x) * (num - SectionLayer_BuildingsDamage.scratches[j].x) + (num2 - SectionLayer_BuildingsDamage.scratches[j].y) * (num2 - SectionLayer_BuildingsDamage.scratches[j].y); - if (num4 < num3) + float num4 = num; + Vector2 vector = SectionLayer_BuildingsDamage.scratches[j]; + float num5 = num4 - vector.x; + float num6 = num; + Vector2 vector2 = SectionLayer_BuildingsDamage.scratches[j]; + float num7 = num5 * (num6 - vector2.x); + float num8 = num2; + Vector2 vector3 = SectionLayer_BuildingsDamage.scratches[j]; + float num9 = num8 - vector3.y; + float num10 = num2; + Vector2 vector4 = SectionLayer_BuildingsDamage.scratches[j]; + float num11 = num7 + num9 * (num10 - vector4.y); + if (num11 < num3) { - num3 = num4; + num3 = num11; } } if (num3 >= minDist * minDist) @@ -125,10 +139,8 @@ private void AddScratch(Building b, float rectWidth, float rectHeight, ref float if (!flag) { minDist *= 0.85f; - if (minDist < 0.001f) - { + if (minDist < 0.0010000000474974513) break; - } } } if (flag) @@ -154,113 +166,142 @@ private void PrintCornersAndEdges(Building b) private void DrawLinkableCornersAndEdges(Building b) { - if (b.def.graphicData == null) - { - return; - } - DamageGraphicData damageData = b.def.graphicData.damageData; - if (damageData == null) - { - return; - } - float damageTexturesAltitude = this.GetDamageTexturesAltitude(b); - List overlays = BuildingsDamageSectionLayerUtility.GetOverlays(b); - IntVec3 position = b.Position; - Vector3 vector = new Vector3((float)position.x + 0.5f, damageTexturesAltitude, (float)position.z + 0.5f); - float x = Rand.Range(0.4f, 0.6f); - float z = Rand.Range(0.4f, 0.6f); - float x2 = Rand.Range(0.4f, 0.6f); - float z2 = Rand.Range(0.4f, 0.6f); - for (int i = 0; i < overlays.Count; i++) + if (b.def.graphicData != null) { - switch (overlays[i]) + DamageGraphicData damageData = b.def.graphicData.damageData; + if (damageData != null) { - case DamageOverlay.TopLeftCorner: - Printer_Plane.PrintPlane(this, vector, Vector2.one, damageData.cornerTLMat, 0f, false, null, null, 0f); - break; - case DamageOverlay.TopRightCorner: - Printer_Plane.PrintPlane(this, vector, Vector2.one, damageData.cornerTRMat, 90f, false, null, null, 0f); - break; - case DamageOverlay.BotLeftCorner: - Printer_Plane.PrintPlane(this, vector, Vector2.one, damageData.cornerBLMat, 270f, false, null, null, 0f); - break; - case DamageOverlay.BotRightCorner: - Printer_Plane.PrintPlane(this, vector, Vector2.one, damageData.cornerBRMat, 180f, false, null, null, 0f); - break; - case DamageOverlay.LeftEdge: - Printer_Plane.PrintPlane(this, vector + new Vector3(0f, 0f, z2), Vector2.one, damageData.edgeLeftMat, 270f, false, null, null, 0f); - break; - case DamageOverlay.RightEdge: - Printer_Plane.PrintPlane(this, vector + new Vector3(0f, 0f, z), Vector2.one, damageData.edgeRightMat, 90f, false, null, null, 0f); - break; - case DamageOverlay.TopEdge: - Printer_Plane.PrintPlane(this, vector + new Vector3(x, 0f, 0f), Vector2.one, damageData.edgeTopMat, 0f, false, null, null, 0f); - break; - case DamageOverlay.BotEdge: - Printer_Plane.PrintPlane(this, vector + new Vector3(x2, 0f, 0f), Vector2.one, damageData.edgeBotMat, 180f, false, null, null, 0f); - break; + float damageTexturesAltitude = this.GetDamageTexturesAltitude(b); + List overlays = BuildingsDamageSectionLayerUtility.GetOverlays(b); + IntVec3 position = b.Position; + Vector3 vector = new Vector3((float)((float)position.x + 0.5), damageTexturesAltitude, (float)((float)position.z + 0.5)); + float x = Rand.Range(0.4f, 0.6f); + float z = Rand.Range(0.4f, 0.6f); + float x2 = Rand.Range(0.4f, 0.6f); + float z2 = Rand.Range(0.4f, 0.6f); + for (int i = 0; i < overlays.Count; i++) + { + switch (overlays[i]) + { + case DamageOverlay.TopEdge: + { + Printer_Plane.PrintPlane(this, vector + new Vector3(x, 0f, 0f), Vector2.one, damageData.edgeTopMat, 0f, false, null, null, 0f); + break; + } + case DamageOverlay.RightEdge: + { + Printer_Plane.PrintPlane(this, vector + new Vector3(0f, 0f, z), Vector2.one, damageData.edgeRightMat, 90f, false, null, null, 0f); + break; + } + case DamageOverlay.BotEdge: + { + Printer_Plane.PrintPlane(this, vector + new Vector3(x2, 0f, 0f), Vector2.one, damageData.edgeBotMat, 180f, false, null, null, 0f); + break; + } + case DamageOverlay.LeftEdge: + { + Printer_Plane.PrintPlane(this, vector + new Vector3(0f, 0f, z2), Vector2.one, damageData.edgeLeftMat, 270f, false, null, null, 0f); + break; + } + case DamageOverlay.TopLeftCorner: + { + Printer_Plane.PrintPlane(this, vector, Vector2.one, damageData.cornerTLMat, 0f, false, null, null, 0f); + break; + } + case DamageOverlay.TopRightCorner: + { + Printer_Plane.PrintPlane(this, vector, Vector2.one, damageData.cornerTRMat, 90f, false, null, null, 0f); + break; + } + case DamageOverlay.BotRightCorner: + { + Printer_Plane.PrintPlane(this, vector, Vector2.one, damageData.cornerBRMat, 180f, false, null, null, 0f); + break; + } + case DamageOverlay.BotLeftCorner: + { + Printer_Plane.PrintPlane(this, vector, Vector2.one, damageData.cornerBLMat, 270f, false, null, null, 0f); + break; + } + } + } } } } private void DrawFullThingCorners(Building b) { - if (b.def.graphicData == null) - { - return; - } - if (b.def.graphicData.damageData == null) - { - return; - } - Rect damageRect = BuildingsDamageSectionLayerUtility.GetDamageRect(b); - float damageTexturesAltitude = this.GetDamageTexturesAltitude(b); - float num = Mathf.Min(Mathf.Min(damageRect.width, damageRect.height), 1.5f); - Material mat; - Material mat2; - Material mat3; - Material mat4; - BuildingsDamageSectionLayerUtility.GetCornerMats(out mat, out mat2, out mat3, out mat4, b); - float num2 = num * Rand.Range(0.9f, 1f); - float num3 = num * Rand.Range(0.9f, 1f); - float num4 = num * Rand.Range(0.9f, 1f); - float num5 = num * Rand.Range(0.9f, 1f); - List overlays = BuildingsDamageSectionLayerUtility.GetOverlays(b); - for (int i = 0; i < overlays.Count; i++) + if (b.def.graphicData != null) { - switch (overlays[i]) - { - case DamageOverlay.TopLeftCorner: + DamageGraphicData damageData = b.def.graphicData.damageData; + if (damageData != null) { - Rect rect = new Rect(damageRect.xMin, damageRect.yMax - num2, num2, num2); - Printer_Plane.PrintPlane(this, new Vector3(rect.center.x, damageTexturesAltitude, rect.center.y), rect.size, mat, 0f, false, null, null, 0f); - break; - } - case DamageOverlay.TopRightCorner: - { - Rect rect2 = new Rect(damageRect.xMax - num3, damageRect.yMax - num3, num3, num3); - Printer_Plane.PrintPlane(this, new Vector3(rect2.center.x, damageTexturesAltitude, rect2.center.y), rect2.size, mat2, 90f, false, null, null, 0f); - break; - } - case DamageOverlay.BotLeftCorner: - { - Rect rect3 = new Rect(damageRect.xMin, damageRect.yMin, num5, num5); - Printer_Plane.PrintPlane(this, new Vector3(rect3.center.x, damageTexturesAltitude, rect3.center.y), rect3.size, mat4, 270f, false, null, null, 0f); - break; - } - case DamageOverlay.BotRightCorner: - { - Rect rect4 = new Rect(damageRect.xMax - num4, damageRect.yMin, num4, num4); - Printer_Plane.PrintPlane(this, new Vector3(rect4.center.x, damageTexturesAltitude, rect4.center.y), rect4.size, mat3, 180f, false, null, null, 0f); - break; - } + Rect damageRect = BuildingsDamageSectionLayerUtility.GetDamageRect(b); + float damageTexturesAltitude = this.GetDamageTexturesAltitude(b); + float num = Mathf.Min(Mathf.Min(damageRect.width, damageRect.height), 1.5f); + Material mat = default(Material); + Material mat2 = default(Material); + Material mat3 = default(Material); + Material mat4 = default(Material); + BuildingsDamageSectionLayerUtility.GetCornerMats(out mat, out mat2, out mat3, out mat4, b); + float num2 = num * Rand.Range(0.9f, 1f); + float num3 = num * Rand.Range(0.9f, 1f); + float num4 = num * Rand.Range(0.9f, 1f); + float num5 = num * Rand.Range(0.9f, 1f); + List overlays = BuildingsDamageSectionLayerUtility.GetOverlays(b); + for (int i = 0; i < overlays.Count; i++) + { + switch (overlays[i]) + { + case DamageOverlay.TopLeftCorner: + { + Rect rect = new Rect(damageRect.xMin, damageRect.yMax - num2, num2, num2); + Vector2 center = rect.center; + float x = center.x; + float y = damageTexturesAltitude; + Vector2 center2 = rect.center; + Printer_Plane.PrintPlane(this, new Vector3(x, y, center2.y), rect.size, mat, 0f, false, null, null, 0f); + break; + } + case DamageOverlay.TopRightCorner: + { + Rect rect2 = new Rect(damageRect.xMax - num3, damageRect.yMax - num3, num3, num3); + Vector2 center3 = rect2.center; + float x2 = center3.x; + float y2 = damageTexturesAltitude; + Vector2 center4 = rect2.center; + Printer_Plane.PrintPlane(this, new Vector3(x2, y2, center4.y), rect2.size, mat2, 90f, false, null, null, 0f); + break; + } + case DamageOverlay.BotRightCorner: + { + Rect rect3 = new Rect(damageRect.xMax - num4, damageRect.yMin, num4, num4); + Vector2 center5 = rect3.center; + float x3 = center5.x; + float y3 = damageTexturesAltitude; + Vector2 center6 = rect3.center; + Printer_Plane.PrintPlane(this, new Vector3(x3, y3, center6.y), rect3.size, mat3, 180f, false, null, null, 0f); + break; + } + case DamageOverlay.BotLeftCorner: + { + Rect rect4 = new Rect(damageRect.xMin, damageRect.yMin, num5, num5); + Vector2 center7 = rect4.center; + float x4 = center7.x; + float y4 = damageTexturesAltitude; + Vector2 center8 = rect4.center; + Printer_Plane.PrintPlane(this, new Vector3(x4, y4, center8.y), rect4.size, mat4, 270f, false, null, null, 0f); + break; + } + } + } } } } private float GetDamageTexturesAltitude(Building b) { - return b.def.Altitude + 0.046875f; + return (float)(b.def.Altitude + 0.046875); } } } diff --git a/Assembly-CSharp/Verse/SectionLayer_EdgeShadows.cs b/Assembly-CSharp/Verse/SectionLayer_EdgeShadows.cs index e40013630..8df9f6cf6 100644 --- a/Assembly-CSharp/Verse/SectionLayer_EdgeShadows.cs +++ b/Assembly-CSharp/Verse/SectionLayer_EdgeShadows.cs @@ -9,9 +9,9 @@ internal class SectionLayer_EdgeShadows : SectionLayer private const byte ShadowBrightness = 195; - private static readonly Color32 Shadowed = new Color32(195, 195, 195, 255); + private static readonly Color32 Shadowed = new Color32((byte)195, (byte)195, (byte)195, (byte)255); - private static readonly Color32 Lit = new Color32(255, 255, 255, 255); + private static readonly Color32 Lit = new Color32((byte)255, (byte)255, (byte)255, (byte)255); public override bool Visible { @@ -23,14 +23,14 @@ public override bool Visible public SectionLayer_EdgeShadows(Section section) : base(section) { - this.relevantChangeTypes = MapMeshFlag.Buildings; + base.relevantChangeTypes = MapMeshFlag.Buildings; } public override void Regenerate() { Building[] innerArray = base.Map.edificeGrid.InnerArray; float y = Altitudes.AltitudeFor(AltitudeLayer.Shadows); - CellRect cellRect = new CellRect(this.section.botLeft.x, this.section.botLeft.z, 17, 17); + CellRect cellRect = new CellRect(base.section.botLeft.x, base.section.botLeft.z, 17, 17); cellRect.ClipInsideMap(base.Map); LayerSubMesh sm = base.GetSubMesh(MatBases.EdgeShadow); sm.Clear(MeshParts.All); @@ -40,6 +40,8 @@ public override void Regenerate() bool[] array = new bool[4]; bool[] array2 = new bool[4]; bool[] array3 = new bool[4]; + float num = 0f; + float num2 = 0f; CellIndices cellIndices = base.Map.cellIndices; for (int i = cellRect.minX; i <= cellRect.maxX; i++) { @@ -111,7 +113,7 @@ public override void Regenerate() } } } - Action action = delegate(int idx) + Action action = (Action)delegate(int idx) { sm.tris.Add(sm.verts.Count - 2); sm.tris.Add(idx); @@ -120,7 +122,7 @@ public override void Regenerate() sm.tris.Add(idx); sm.tris.Add(idx + 1); }; - Action action2 = delegate + Action action2 = (Action)delegate { sm.colors.Add(SectionLayer_EdgeShadows.Shadowed); sm.colors.Add(SectionLayer_EdgeShadows.Lit); @@ -134,19 +136,18 @@ public override void Regenerate() { if (array2[0] || array2[1]) { - float num2; - float num = num2 = 0f; + num = (num2 = 0f); if (array2[0]) { - num = 0.45f; + num2 = 0.45f; } if (array2[1]) { - num2 = 0.45f; + num = 0.45f; } sm.verts.Add(new Vector3((float)i, y, (float)j)); sm.colors.Add(SectionLayer_EdgeShadows.Shadowed); - sm.verts.Add(new Vector3((float)i + num2, y, (float)j + num)); + sm.verts.Add(new Vector3((float)i + num, y, (float)j + num2)); sm.colors.Add(SectionLayer_EdgeShadows.Lit); if (array[1] && !array3[1]) { @@ -156,8 +157,8 @@ public override void Regenerate() else { sm.verts.Add(new Vector3((float)i, y, (float)j)); - sm.verts.Add(new Vector3((float)i, y, (float)j + 0.45f)); - sm.verts.Add(new Vector3((float)i + 0.45f, y, (float)j)); + sm.verts.Add(new Vector3((float)i, y, (float)((float)j + 0.44999998807907104))); + sm.verts.Add(new Vector3((float)((float)i + 0.44999998807907104), y, (float)j)); action2(); } } @@ -165,19 +166,18 @@ public override void Regenerate() { if (array2[1] || array2[2]) { - float num2; - float num = num2 = 0f; + num = (num2 = 0f); if (array2[1]) { - num2 = 0.45f; + num = 0.45f; } if (array2[2]) { - num = -0.45f; + num2 = -0.45f; } sm.verts.Add(new Vector3((float)i, y, (float)(j + 1))); sm.colors.Add(SectionLayer_EdgeShadows.Shadowed); - sm.verts.Add(new Vector3((float)i + num2, y, (float)(j + 1) + num)); + sm.verts.Add(new Vector3((float)i + num, y, (float)(j + 1) + num2)); sm.colors.Add(SectionLayer_EdgeShadows.Lit); if (array[2] && !array3[2]) { @@ -187,8 +187,8 @@ public override void Regenerate() else { sm.verts.Add(new Vector3((float)i, y, (float)(j + 1))); - sm.verts.Add(new Vector3((float)i + 0.45f, y, (float)(j + 1))); - sm.verts.Add(new Vector3((float)i, y, (float)(j + 1) - 0.45f)); + sm.verts.Add(new Vector3((float)((float)i + 0.44999998807907104), y, (float)(j + 1))); + sm.verts.Add(new Vector3((float)i, y, (float)((float)(j + 1) - 0.44999998807907104))); action2(); } } @@ -196,19 +196,18 @@ public override void Regenerate() { if (array2[2] || array2[3]) { - float num2; - float num = num2 = 0f; + num = (num2 = 0f); if (array2[2]) { - num = -0.45f; + num2 = -0.45f; } if (array2[3]) { - num2 = -0.45f; + num = -0.45f; } sm.verts.Add(new Vector3((float)(i + 1), y, (float)(j + 1))); sm.colors.Add(SectionLayer_EdgeShadows.Shadowed); - sm.verts.Add(new Vector3((float)(i + 1) + num2, y, (float)(j + 1) + num)); + sm.verts.Add(new Vector3((float)(i + 1) + num, y, (float)(j + 1) + num2)); sm.colors.Add(SectionLayer_EdgeShadows.Lit); if (array[3] && !array3[3]) { @@ -218,8 +217,8 @@ public override void Regenerate() else { sm.verts.Add(new Vector3((float)(i + 1), y, (float)(j + 1))); - sm.verts.Add(new Vector3((float)(i + 1), y, (float)(j + 1) - 0.45f)); - sm.verts.Add(new Vector3((float)(i + 1) - 0.45f, y, (float)(j + 1))); + sm.verts.Add(new Vector3((float)(i + 1), y, (float)((float)(j + 1) - 0.44999998807907104))); + sm.verts.Add(new Vector3((float)((float)(i + 1) - 0.44999998807907104), y, (float)(j + 1))); action2(); } } @@ -227,19 +226,18 @@ public override void Regenerate() { if (array2[3] || array2[0]) { - float num2; - float num = num2 = 0f; + num = (num2 = 0f); if (array2[3]) { - num2 = -0.45f; + num = -0.45f; } if (array2[0]) { - num = 0.45f; + num2 = 0.45f; } sm.verts.Add(new Vector3((float)(i + 1), y, (float)j)); sm.colors.Add(SectionLayer_EdgeShadows.Shadowed); - sm.verts.Add(new Vector3((float)(i + 1) + num2, y, (float)j + num)); + sm.verts.Add(new Vector3((float)(i + 1) + num, y, (float)j + num2)); sm.colors.Add(SectionLayer_EdgeShadows.Lit); if (array[0] && !array3[0]) { @@ -249,8 +247,8 @@ public override void Regenerate() else { sm.verts.Add(new Vector3((float)(i + 1), y, (float)j)); - sm.verts.Add(new Vector3((float)(i + 1) - 0.45f, y, (float)j)); - sm.verts.Add(new Vector3((float)(i + 1), y, (float)j + 0.45f)); + sm.verts.Add(new Vector3((float)((float)(i + 1) - 0.44999998807907104), y, (float)j)); + sm.verts.Add(new Vector3((float)(i + 1), y, (float)((float)j + 0.44999998807907104))); action2(); } } diff --git a/Assembly-CSharp/Verse/SectionLayer_FogOfWar.cs b/Assembly-CSharp/Verse/SectionLayer_FogOfWar.cs index e4ecfe86c..9658d83e5 100644 --- a/Assembly-CSharp/Verse/SectionLayer_FogOfWar.cs +++ b/Assembly-CSharp/Verse/SectionLayer_FogOfWar.cs @@ -1,4 +1,3 @@ -using System; using System.Collections.Generic; using UnityEngine; @@ -20,7 +19,7 @@ public override bool Visible public SectionLayer_FogOfWar(Section section) : base(section) { - this.relevantChangeTypes = MapMeshFlag.FogOfWar; + base.relevantChangeTypes = MapMeshFlag.FogOfWar; } public override void Regenerate() @@ -28,12 +27,14 @@ public override void Regenerate() LayerSubMesh subMesh = base.GetSubMesh(MatBases.FogOfWar); if (subMesh.mesh.vertexCount == 0) { - SectionLayerGeometryMaker_Solid.MakeBaseGeometry(this.section, subMesh, AltitudeLayer.FogOfWar); + SectionLayerGeometryMaker_Solid.MakeBaseGeometry(base.section, subMesh, AltitudeLayer.FogOfWar); } bool[] fogGrid = base.Map.fogGrid.fogGrid; - CellRect cellRect = this.section.CellRect; - int num = base.Map.Size.z - 1; - int num2 = base.Map.Size.x - 1; + CellRect cellRect = base.section.CellRect; + IntVec3 size = base.Map.Size; + int num = size.z - 1; + IntVec3 size2 = base.Map.Size; + int num2 = size2.x - 1; subMesh.colors = new List(subMesh.mesh.vertexCount); bool flag = false; CellIndices cellIndices = base.Map.cellIndices; @@ -100,14 +101,14 @@ public override void Regenerate() byte a; if (this.vertsCovered[m]) { - a = 255; + a = (byte)255; flag = true; } else { - a = 0; + a = (byte)0; } - subMesh.colors.Add(new Color32(255, 255, 255, a)); + subMesh.colors.Add(new Color32((byte)255, (byte)255, (byte)255, a)); } } } diff --git a/Assembly-CSharp/Verse/SectionLayer_IndoorMask.cs b/Assembly-CSharp/Verse/SectionLayer_IndoorMask.cs index aedd83d3e..3eb310f6e 100644 --- a/Assembly-CSharp/Verse/SectionLayer_IndoorMask.cs +++ b/Assembly-CSharp/Verse/SectionLayer_IndoorMask.cs @@ -1,4 +1,3 @@ -using System; using UnityEngine; namespace Verse @@ -15,7 +14,7 @@ public override bool Visible public SectionLayer_IndoorMask(Section section) : base(section) { - this.relevantChangeTypes = (MapMeshFlag.FogOfWar | MapMeshFlag.Roofs); + base.relevantChangeTypes = (MapMeshFlag.FogOfWar | MapMeshFlag.Roofs); } private bool HideRainPrimary(IntVec3 c) @@ -35,91 +34,76 @@ private bool HideRainPrimary(IntVec3 c) { return true; } - if (edifice.def.size.x > 1 || edifice.def.size.z > 1) + if (edifice.def.size.x <= 1 && edifice.def.size.z <= 1) { - return true; + goto IL_007f; } + return true; } + goto IL_007f; + IL_007f: return false; } public override void Regenerate() { - if (!MatBases.SunShadow.shader.isSupported) - { - return; - } - LayerSubMesh subMesh = base.GetSubMesh(MatBases.IndoorMask); - subMesh.Clear(MeshParts.All); - Building[] innerArray = base.Map.edificeGrid.InnerArray; - CellRect cellRect = new CellRect(this.section.botLeft.x, this.section.botLeft.z, 17, 17); - cellRect.ClipInsideMap(base.Map); - subMesh.verts.Capacity = cellRect.Area * 2; - subMesh.tris.Capacity = cellRect.Area * 4; - float y = Altitudes.AltitudeFor(AltitudeLayer.MetaOverlays); - CellIndices cellIndices = base.Map.cellIndices; - for (int i = cellRect.minX; i <= cellRect.maxX; i++) + if (MatBases.SunShadow.shader.isSupported) { - int j = cellRect.minZ; - while (j <= cellRect.maxZ) + LayerSubMesh subMesh = base.GetSubMesh(MatBases.IndoorMask); + subMesh.Clear(MeshParts.All); + Building[] innerArray = base.Map.edificeGrid.InnerArray; + CellRect cellRect = new CellRect(base.section.botLeft.x, base.section.botLeft.z, 17, 17); + cellRect.ClipInsideMap(base.Map); + subMesh.verts.Capacity = cellRect.Area * 2; + subMesh.tris.Capacity = cellRect.Area * 4; + float y = Altitudes.AltitudeFor(AltitudeLayer.MetaOverlays); + CellIndices cellIndices = base.Map.cellIndices; + for (int i = cellRect.minX; i <= cellRect.maxX; i++) { - IntVec3 intVec = new IntVec3(i, 0, j); - if (this.HideRainPrimary(intVec)) - { - goto IL_16E; - } - bool flag = intVec.Roofed(base.Map); - bool flag2 = false; - if (flag) + for (int j = cellRect.minZ; j <= cellRect.maxZ; j++) { - for (int k = 0; k < 8; k++) + IntVec3 intVec = new IntVec3(i, 0, j); + if (!this.HideRainPrimary(intVec)) { - IntVec3 c = intVec + GenAdj.AdjacentCells[k]; - if (c.InBounds(base.Map)) + bool flag = intVec.Roofed(base.Map); + bool flag2 = false; + if (flag) { - if (this.HideRainPrimary(c)) + for (int k = 0; k < 8; k++) { - flag2 = true; - break; + IntVec3 c = intVec + GenAdj.AdjacentCells[k]; + if (c.InBounds(base.Map) && this.HideRainPrimary(c)) + { + flag2 = true; + break; + } } } + if (flag && flag2) + goto IL_016e; + continue; } + goto IL_016e; + IL_016e: + Thing thing = innerArray[cellIndices.CellToIndex(i, j)]; + float num = (float)((thing == null || (thing.def.passability != Traversability.Impassable && !thing.def.IsDoor)) ? 0.15999999642372131 : 0.0); + subMesh.verts.Add(new Vector3((float)i - num, y, (float)j - num)); + subMesh.verts.Add(new Vector3((float)i - num, y, (float)(j + 1) + num)); + subMesh.verts.Add(new Vector3((float)(i + 1) + num, y, (float)(j + 1) + num)); + subMesh.verts.Add(new Vector3((float)(i + 1) + num, y, (float)j - num)); + int count = subMesh.verts.Count; + subMesh.tris.Add(count - 4); + subMesh.tris.Add(count - 3); + subMesh.tris.Add(count - 2); + subMesh.tris.Add(count - 4); + subMesh.tris.Add(count - 2); + subMesh.tris.Add(count - 1); } - if (flag && flag2) - { - goto IL_16E; - } - IL_29D: - j++; - continue; - IL_16E: - Thing thing = innerArray[cellIndices.CellToIndex(i, j)]; - float num; - if (thing != null && (thing.def.passability == Traversability.Impassable || thing.def.IsDoor)) - { - num = 0f; - } - else - { - num = 0.16f; - } - subMesh.verts.Add(new Vector3((float)i - num, y, (float)j - num)); - subMesh.verts.Add(new Vector3((float)i - num, y, (float)(j + 1) + num)); - subMesh.verts.Add(new Vector3((float)(i + 1) + num, y, (float)(j + 1) + num)); - subMesh.verts.Add(new Vector3((float)(i + 1) + num, y, (float)j - num)); - int count = subMesh.verts.Count; - subMesh.tris.Add(count - 4); - subMesh.tris.Add(count - 3); - subMesh.tris.Add(count - 2); - subMesh.tris.Add(count - 4); - subMesh.tris.Add(count - 2); - subMesh.tris.Add(count - 1); - goto IL_29D; } - } - if (subMesh.verts.Count > 0) - { - subMesh.FinalizeMesh(MeshParts.Verts | MeshParts.Tris, false); + if (subMesh.verts.Count > 0) + { + subMesh.FinalizeMesh(MeshParts.Verts | MeshParts.Tris, false); + } } } } diff --git a/Assembly-CSharp/Verse/SectionLayer_LightingOverlay.cs b/Assembly-CSharp/Verse/SectionLayer_LightingOverlay.cs index 943f242c0..3bb70731a 100644 --- a/Assembly-CSharp/Verse/SectionLayer_LightingOverlay.cs +++ b/Assembly-CSharp/Verse/SectionLayer_LightingOverlay.cs @@ -1,4 +1,3 @@ -using System; using System.Text; using UnityEngine; @@ -14,7 +13,7 @@ public class SectionLayer_LightingOverlay : SectionLayer private CellRect sectRect; - private static readonly IntVec3[] CheckSquareOffsets = new IntVec3[] + private static readonly IntVec3[] CheckSquareOffsets = new IntVec3[4] { new IntVec3(0, 0, -1), new IntVec3(-1, 0, -1), @@ -32,17 +31,17 @@ public override bool Visible public SectionLayer_LightingOverlay(Section section) : base(section) { - this.relevantChangeTypes = MapMeshFlag.GroundGlow; + base.relevantChangeTypes = MapMeshFlag.GroundGlow; } public string GlowReportAt(IntVec3 c) { Color32[] colors = base.GetSubMesh(MatBases.LightOverlay).mesh.colors32; - int num; - int num2; - int num3; - int num4; - int num5; + int num = default(int); + int num2 = default(int); + int num3 = default(int); + int num4 = default(int); + int num5 = default(int); this.CalculateVertexIndices(c.x, c.z, out num, out num2, out num3, out num4, out num5); StringBuilder stringBuilder = new StringBuilder(); stringBuilder.Append("BL=" + colors[num]); @@ -71,11 +70,11 @@ public override void Regenerate() { for (int j = this.sectRect.minZ; j <= maxZ + 1; j++) { - int num; - int num2; - int num3; - int num4; - int num5; + int num = default(int); + int num2 = default(int); + int num3 = default(int); + int num4 = default(int); + int num5 = default(int); this.CalculateVertexIndices(i, j, out num, out num2, out num3, out num4, out num5); IntVec3 a = new IntVec3(i, 0, j); bool flag = false; @@ -133,33 +132,33 @@ public override void Regenerate() } else { - array[num] = new Color32(0, 0, 0, 0); + array[num] = new Color32((byte)0, (byte)0, (byte)0, (byte)0); } if (flag && array[num].a < 100) { - array[num].a = 100; + array[num].a = (byte)100; } } } - for (int l = this.sectRect.minX; l <= maxX; l++) + for (int num7 = this.sectRect.minX; num7 <= maxX; num7++) { - for (int m = this.sectRect.minZ; m <= maxZ; m++) + for (int num8 = this.sectRect.minZ; num8 <= maxZ; num8++) { - int num7; - int num8; - int num9; - int num10; - int num11; - this.CalculateVertexIndices(l, m, out num7, out num8, out num9, out num10, out num11); - ColorInt colorInt2 = default(ColorInt) + array[num7]; - colorInt2 += array[num8]; - colorInt2 += array[num9]; - colorInt2 += array[num10]; - array[num11] = (colorInt2 / 4f).ToColor32; - Thing thing = innerArray[cellIndices.CellToIndex(l, m)]; - if (roofGrid.Roofed(l, m) && (thing == null || !thing.def.holdsRoof) && array[num11].a < 100) + int num9 = default(int); + int num10 = default(int); + int num11 = default(int); + int num12 = default(int); + int num13 = default(int); + this.CalculateVertexIndices(num7, num8, out num9, out num10, out num11, out num12, out num13); + ColorInt colA = default(ColorInt) + array[num9]; + colA += array[num10]; + colA += array[num11]; + colA += array[num12]; + array[num13] = (colA / 4f).ToColor32; + Thing thing = innerArray[cellIndices.CellToIndex(num7, num8)]; + if (roofGrid.Roofed(num7, num8) && (thing == null || !thing.def.holdsRoof) && array[num13].a < 100) { - array[num11].a = 100; + array[num13].a = (byte)100; } } } @@ -169,7 +168,7 @@ public override void Regenerate() private void MakeBaseGeometry(LayerSubMesh sm) { this.glowGrid = base.Map.glowGrid.glowGrid; - this.sectRect = new CellRect(this.section.botLeft.x, this.section.botLeft.z, 17, 17); + this.sectRect = new CellRect(base.section.botLeft.x, base.section.botLeft.z, 17, 17); this.sectRect.ClipInsideMap(base.Map); int capacity = (this.sectRect.Width + 1) * (this.sectRect.Height + 1) + this.sectRect.Area; float y = Altitudes.AltitudeFor(AltitudeLayer.LightingOverlay); @@ -186,7 +185,7 @@ private void MakeBaseGeometry(LayerSubMesh sm) { for (int l = this.sectRect.minX; l <= this.sectRect.maxX; l++) { - sm.verts.Add(new Vector3((float)l + 0.5f, y, (float)k + 0.5f)); + sm.verts.Add(new Vector3((float)((float)l + 0.5), y, (float)((float)k + 0.5))); } } sm.tris.Capacity = this.sectRect.Area * 4 * 3; @@ -194,11 +193,11 @@ private void MakeBaseGeometry(LayerSubMesh sm) { for (int n = this.sectRect.minX; n <= this.sectRect.maxX; n++) { - int item; - int item2; - int item3; - int item4; - int item5; + int item = default(int); + int item2 = default(int); + int item3 = default(int); + int item4 = default(int); + int item5 = default(int); this.CalculateVertexIndices(n, m, out item, out item2, out item3, out item4, out item5); sm.tris.Add(item); sm.tris.Add(item5); diff --git a/Assembly-CSharp/Verse/SectionLayer_Snow.cs b/Assembly-CSharp/Verse/SectionLayer_Snow.cs index ee9151644..fa244bb65 100644 --- a/Assembly-CSharp/Verse/SectionLayer_Snow.cs +++ b/Assembly-CSharp/Verse/SectionLayer_Snow.cs @@ -1,4 +1,3 @@ -using System; using System.Collections.Generic; using UnityEngine; @@ -8,9 +7,9 @@ internal class SectionLayer_Snow : SectionLayer { private float[] vertDepth = new float[9]; - private static readonly Color32 ColorClear = new Color32(255, 255, 255, 0); + private static readonly Color32 ColorClear = new Color32((byte)255, (byte)255, (byte)255, (byte)0); - private static readonly Color32 ColorWhite = new Color32(255, 255, 255, 255); + private static readonly Color32 ColorWhite = new Color32((byte)255, (byte)255, (byte)255, (byte)255); public override bool Visible { @@ -22,7 +21,7 @@ public override bool Visible public SectionLayer_Snow(Section section) : base(section) { - this.relevantChangeTypes = MapMeshFlag.Snow; + base.relevantChangeTypes = MapMeshFlag.Snow; } private bool Filled(int index) @@ -36,12 +35,14 @@ public override void Regenerate() LayerSubMesh subMesh = base.GetSubMesh(MatBases.Snow); if (subMesh.mesh.vertexCount == 0) { - SectionLayerGeometryMaker_Solid.MakeBaseGeometry(this.section, subMesh, AltitudeLayer.Terrain); + SectionLayerGeometryMaker_Solid.MakeBaseGeometry(base.section, subMesh, AltitudeLayer.Terrain); } float[] depthGridDirect_Unsafe = base.Map.snowGrid.DepthGridDirect_Unsafe; - CellRect cellRect = this.section.CellRect; - int num = base.Map.Size.z - 1; - int num2 = base.Map.Size.x - 1; + CellRect cellRect = base.section.CellRect; + IntVec3 size = base.Map.Size; + int num = size.z - 1; + IntVec3 size2 = base.Map.Size; + int num2 = size2.x - 1; subMesh.colors = new List(subMesh.mesh.vertexCount); bool flag = false; CellIndices cellIndices = base.Map.cellIndices; @@ -66,18 +67,18 @@ public override void Regenerate() float num11 = (i >= num2) ? num3 : depthGridDirect_Unsafe[num4]; num4 = cellIndices.CellToIndex(i + 1, j - 1); float num12 = (j <= 0 || i >= num2) ? num3 : depthGridDirect_Unsafe[num4]; - this.vertDepth[0] = (num5 + num6 + num7 + num3) / 4f; - this.vertDepth[1] = (num7 + num3) / 2f; - this.vertDepth[2] = (num7 + num8 + num9 + num3) / 4f; - this.vertDepth[3] = (num9 + num3) / 2f; - this.vertDepth[4] = (num9 + num10 + num11 + num3) / 4f; - this.vertDepth[5] = (num11 + num3) / 2f; - this.vertDepth[6] = (num11 + num12 + num5 + num3) / 4f; - this.vertDepth[7] = (num5 + num3) / 2f; + this.vertDepth[0] = (float)((num5 + num6 + num7 + num3) / 4.0); + this.vertDepth[1] = (float)((num7 + num3) / 2.0); + this.vertDepth[2] = (float)((num7 + num8 + num9 + num3) / 4.0); + this.vertDepth[3] = (float)((num9 + num3) / 2.0); + this.vertDepth[4] = (float)((num9 + num10 + num11 + num3) / 4.0); + this.vertDepth[5] = (float)((num11 + num3) / 2.0); + this.vertDepth[6] = (float)((num11 + num12 + num5 + num3) / 4.0); + this.vertDepth[7] = (float)((num5 + num3) / 2.0); this.vertDepth[8] = num3; for (int k = 0; k < 9; k++) { - if (this.vertDepth[k] > 0.01f) + if (this.vertDepth[k] > 0.0099999997764825821) { flag = true; } diff --git a/Assembly-CSharp/Verse/SectionLayer_SunShadows.cs b/Assembly-CSharp/Verse/SectionLayer_SunShadows.cs index d4a382e1b..7233d647f 100644 --- a/Assembly-CSharp/Verse/SectionLayer_SunShadows.cs +++ b/Assembly-CSharp/Verse/SectionLayer_SunShadows.cs @@ -1,4 +1,3 @@ -using System; using UnityEngine; namespace Verse @@ -7,7 +6,7 @@ internal class SectionLayer_SunShadows : SectionLayer { private static Building[] edificeGrid; - private static readonly Color32 LowVertexColor = new Color32(0, 0, 0, 0); + private static readonly Color32 LowVertexColor = new Color32((byte)0, (byte)0, (byte)0, (byte)0); public override bool Visible { @@ -19,115 +18,116 @@ public override bool Visible public SectionLayer_SunShadows(Section section) : base(section) { - this.relevantChangeTypes = MapMeshFlag.Buildings; + base.relevantChangeTypes = MapMeshFlag.Buildings; } public override void Regenerate() { - if (!MatBases.SunShadow.shader.isSupported) + if (MatBases.SunShadow.shader.isSupported) { - return; - } - SectionLayer_SunShadows.edificeGrid = base.Map.edificeGrid.InnerArray; - float y = Altitudes.AltitudeFor(AltitudeLayer.Shadows); - CellRect cellRect = new CellRect(this.section.botLeft.x, this.section.botLeft.z, 17, 17); - cellRect.ClipInsideMap(base.Map); - LayerSubMesh subMesh = base.GetSubMesh(MatBases.SunShadow); - subMesh.Clear(MeshParts.All); - subMesh.verts.Capacity = cellRect.Area * 2; - subMesh.tris.Capacity = cellRect.Area * 4; - subMesh.colors.Capacity = cellRect.Area * 2; - CellIndices cellIndices = base.Map.cellIndices; - for (int i = cellRect.minX; i <= cellRect.maxX; i++) - { - for (int j = cellRect.minZ; j <= cellRect.maxZ; j++) + SectionLayer_SunShadows.edificeGrid = base.Map.edificeGrid.InnerArray; + float y = Altitudes.AltitudeFor(AltitudeLayer.Shadows); + CellRect cellRect = new CellRect(base.section.botLeft.x, base.section.botLeft.z, 17, 17); + cellRect.ClipInsideMap(base.Map); + LayerSubMesh subMesh = base.GetSubMesh(MatBases.SunShadow); + subMesh.Clear(MeshParts.All); + subMesh.verts.Capacity = cellRect.Area * 2; + subMesh.tris.Capacity = cellRect.Area * 4; + subMesh.colors.Capacity = cellRect.Area * 2; + CellIndices cellIndices = base.Map.cellIndices; + for (int i = cellRect.minX; i <= cellRect.maxX; i++) { - Thing thing = SectionLayer_SunShadows.edificeGrid[cellIndices.CellToIndex(i, j)]; - if (thing != null && thing.def.staticSunShadowHeight > 0f) + for (int j = cellRect.minZ; j <= cellRect.maxZ; j++) { - float staticSunShadowHeight = thing.def.staticSunShadowHeight; - Color32 item = new Color32(0, 0, 0, (byte)(255f * staticSunShadowHeight)); - int count = subMesh.verts.Count; - subMesh.verts.Add(new Vector3((float)i, y, (float)j)); - subMesh.verts.Add(new Vector3((float)i, y, (float)(j + 1))); - subMesh.verts.Add(new Vector3((float)(i + 1), y, (float)(j + 1))); - subMesh.verts.Add(new Vector3((float)(i + 1), y, (float)j)); - subMesh.colors.Add(SectionLayer_SunShadows.LowVertexColor); - subMesh.colors.Add(SectionLayer_SunShadows.LowVertexColor); - subMesh.colors.Add(SectionLayer_SunShadows.LowVertexColor); - subMesh.colors.Add(SectionLayer_SunShadows.LowVertexColor); - int count2 = subMesh.verts.Count; - subMesh.tris.Add(count2 - 4); - subMesh.tris.Add(count2 - 3); - subMesh.tris.Add(count2 - 2); - subMesh.tris.Add(count2 - 4); - subMesh.tris.Add(count2 - 2); - subMesh.tris.Add(count2 - 1); - if (i > 0) + Thing thing = SectionLayer_SunShadows.edificeGrid[cellIndices.CellToIndex(i, j)]; + if (thing != null && thing.def.staticSunShadowHeight > 0.0) { - thing = SectionLayer_SunShadows.edificeGrid[cellIndices.CellToIndex(i - 1, j)]; - if (thing == null || thing.def.staticSunShadowHeight < staticSunShadowHeight) + float staticSunShadowHeight = thing.def.staticSunShadowHeight; + Color32 item = new Color32((byte)0, (byte)0, (byte)0, (byte)(255.0 * staticSunShadowHeight)); + int count = subMesh.verts.Count; + subMesh.verts.Add(new Vector3((float)i, y, (float)j)); + subMesh.verts.Add(new Vector3((float)i, y, (float)(j + 1))); + subMesh.verts.Add(new Vector3((float)(i + 1), y, (float)(j + 1))); + subMesh.verts.Add(new Vector3((float)(i + 1), y, (float)j)); + subMesh.colors.Add(SectionLayer_SunShadows.LowVertexColor); + subMesh.colors.Add(SectionLayer_SunShadows.LowVertexColor); + subMesh.colors.Add(SectionLayer_SunShadows.LowVertexColor); + subMesh.colors.Add(SectionLayer_SunShadows.LowVertexColor); + int count2 = subMesh.verts.Count; + subMesh.tris.Add(count2 - 4); + subMesh.tris.Add(count2 - 3); + subMesh.tris.Add(count2 - 2); + subMesh.tris.Add(count2 - 4); + subMesh.tris.Add(count2 - 2); + subMesh.tris.Add(count2 - 1); + if (i > 0) { - int count3 = subMesh.verts.Count; - subMesh.verts.Add(new Vector3((float)i, y, (float)j)); - subMesh.verts.Add(new Vector3((float)i, y, (float)(j + 1))); - subMesh.colors.Add(item); - subMesh.colors.Add(item); - subMesh.tris.Add(count + 1); - subMesh.tris.Add(count); - subMesh.tris.Add(count3); - subMesh.tris.Add(count3); - subMesh.tris.Add(count3 + 1); - subMesh.tris.Add(count + 1); + thing = SectionLayer_SunShadows.edificeGrid[cellIndices.CellToIndex(i - 1, j)]; + if (thing == null || thing.def.staticSunShadowHeight < staticSunShadowHeight) + { + int count3 = subMesh.verts.Count; + subMesh.verts.Add(new Vector3((float)i, y, (float)j)); + subMesh.verts.Add(new Vector3((float)i, y, (float)(j + 1))); + subMesh.colors.Add(item); + subMesh.colors.Add(item); + subMesh.tris.Add(count + 1); + subMesh.tris.Add(count); + subMesh.tris.Add(count3); + subMesh.tris.Add(count3); + subMesh.tris.Add(count3 + 1); + subMesh.tris.Add(count + 1); + } } - } - if (i < base.Map.Size.x - 1) - { - thing = SectionLayer_SunShadows.edificeGrid[cellIndices.CellToIndex(i + 1, j)]; - if (thing == null || thing.def.staticSunShadowHeight < staticSunShadowHeight) + int num = i; + IntVec3 size = base.Map.Size; + if (num < size.x - 1) { - int count4 = subMesh.verts.Count; - subMesh.verts.Add(new Vector3((float)(i + 1), y, (float)(j + 1))); - subMesh.verts.Add(new Vector3((float)(i + 1), y, (float)j)); - subMesh.colors.Add(item); - subMesh.colors.Add(item); - subMesh.tris.Add(count + 2); - subMesh.tris.Add(count4); - subMesh.tris.Add(count4 + 1); - subMesh.tris.Add(count4 + 1); - subMesh.tris.Add(count + 3); - subMesh.tris.Add(count + 2); + thing = SectionLayer_SunShadows.edificeGrid[cellIndices.CellToIndex(i + 1, j)]; + if (thing == null || thing.def.staticSunShadowHeight < staticSunShadowHeight) + { + int count4 = subMesh.verts.Count; + subMesh.verts.Add(new Vector3((float)(i + 1), y, (float)(j + 1))); + subMesh.verts.Add(new Vector3((float)(i + 1), y, (float)j)); + subMesh.colors.Add(item); + subMesh.colors.Add(item); + subMesh.tris.Add(count + 2); + subMesh.tris.Add(count4); + subMesh.tris.Add(count4 + 1); + subMesh.tris.Add(count4 + 1); + subMesh.tris.Add(count + 3); + subMesh.tris.Add(count + 2); + } } - } - if (j > 0) - { - thing = SectionLayer_SunShadows.edificeGrid[cellIndices.CellToIndex(i, j - 1)]; - if (thing == null || thing.def.staticSunShadowHeight < staticSunShadowHeight) + if (j > 0) { - int count5 = subMesh.verts.Count; - subMesh.verts.Add(new Vector3((float)i, y, (float)j)); - subMesh.verts.Add(new Vector3((float)(i + 1), y, (float)j)); - subMesh.colors.Add(item); - subMesh.colors.Add(item); - subMesh.tris.Add(count); - subMesh.tris.Add(count + 3); - subMesh.tris.Add(count5); - subMesh.tris.Add(count + 3); - subMesh.tris.Add(count5 + 1); - subMesh.tris.Add(count5); + thing = SectionLayer_SunShadows.edificeGrid[cellIndices.CellToIndex(i, j - 1)]; + if (thing == null || thing.def.staticSunShadowHeight < staticSunShadowHeight) + { + int count5 = subMesh.verts.Count; + subMesh.verts.Add(new Vector3((float)i, y, (float)j)); + subMesh.verts.Add(new Vector3((float)(i + 1), y, (float)j)); + subMesh.colors.Add(item); + subMesh.colors.Add(item); + subMesh.tris.Add(count); + subMesh.tris.Add(count + 3); + subMesh.tris.Add(count5); + subMesh.tris.Add(count + 3); + subMesh.tris.Add(count5 + 1); + subMesh.tris.Add(count5); + } } } } } - } - if (subMesh.verts.Count > 0) - { - subMesh.FinalizeMesh(MeshParts.Verts | MeshParts.Tris | MeshParts.Colors, false); - float num = Mathf.Max(15f, 15f); - Vector3 size = subMesh.mesh.bounds.size; - size.x += 2f * num + 2f; - size.z += 2f * num + 2f; - subMesh.mesh.bounds = new Bounds(subMesh.mesh.bounds.center, size); + if (subMesh.verts.Count > 0) + { + subMesh.FinalizeMesh(MeshParts.Verts | MeshParts.Tris | MeshParts.Colors, false); + float num2 = Mathf.Max(15f, 15f); + Vector3 size2 = subMesh.mesh.bounds.size; + size2.x += (float)(2.0 * num2 + 2.0); + size2.z += (float)(2.0 * num2 + 2.0); + subMesh.mesh.bounds = new Bounds(subMesh.mesh.bounds.center, size2); + } } } } diff --git a/Assembly-CSharp/Verse/SectionLayer_Terrain.cs b/Assembly-CSharp/Verse/SectionLayer_Terrain.cs index d32f22590..89e25b896 100644 --- a/Assembly-CSharp/Verse/SectionLayer_Terrain.cs +++ b/Assembly-CSharp/Verse/SectionLayer_Terrain.cs @@ -7,9 +7,9 @@ namespace Verse { internal class SectionLayer_Terrain : SectionLayer { - private static readonly Color32 ColorWhite = new Color32(255, 255, 255, 255); + private static readonly Color32 ColorWhite = new Color32((byte)255, (byte)255, (byte)255, (byte)255); - private static readonly Color32 ColorClear = new Color32(255, 255, 255, 0); + private static readonly Color32 ColorClear = new Color32((byte)255, (byte)255, (byte)255, (byte)0); public override bool Visible { @@ -21,7 +21,7 @@ public override bool Visible public SectionLayer_Terrain(Section section) : base(section) { - this.relevantChangeTypes = MapMeshFlag.Terrain; + base.relevantChangeTypes = MapMeshFlag.Terrain; } public virtual Material GetMaterialFor(TerrainDef terrain) @@ -33,12 +33,13 @@ public override void Regenerate() { base.ClearSubMeshes(MeshParts.All); TerrainGrid terrainGrid = base.Map.terrainGrid; - CellRect cellRect = this.section.CellRect; + CellRect cellRect = base.section.CellRect; TerrainDef[] array = new TerrainDef[8]; HashSet hashSet = new HashSet(); bool[] array2 = new bool[8]; - foreach (IntVec3 current in cellRect) + foreach (IntVec3 item in cellRect) { + IntVec3 current = item; hashSet.Clear(); TerrainDef terrainDef = terrainGrid.TerrainAt(current); LayerSubMesh subMesh = base.GetSubMesh(this.GetMaterialFor(terrainDef)); @@ -76,70 +77,76 @@ public override void Regenerate() terrainDef2 = TerrainDefOf.Underwall; } array[i] = terrainDef2; - if (terrainDef2 != terrainDef && terrainDef2.edgeType != TerrainDef.TerrainEdgeType.Hard && terrainDef2.renderPrecedence >= terrainDef.renderPrecedence) + if (terrainDef2 != terrainDef && terrainDef2.edgeType != 0 && terrainDef2.renderPrecedence >= terrainDef.renderPrecedence && !hashSet.Contains(terrainDef2)) { - if (!hashSet.Contains(terrainDef2)) - { - hashSet.Add(terrainDef2); - } + hashSet.Add(terrainDef2); } } } - foreach (TerrainDef current2 in hashSet) + HashSet.Enumerator enumerator2 = hashSet.GetEnumerator(); + try { - LayerSubMesh subMesh2 = base.GetSubMesh(this.GetMaterialFor(current2)); - if (subMesh2 != null) + while (enumerator2.MoveNext()) { - int count = subMesh2.verts.Count; - subMesh2.verts.Add(new Vector3((float)current.x + 0.5f, 0f, (float)current.z)); - subMesh2.verts.Add(new Vector3((float)current.x, 0f, (float)current.z)); - subMesh2.verts.Add(new Vector3((float)current.x, 0f, (float)current.z + 0.5f)); - subMesh2.verts.Add(new Vector3((float)current.x, 0f, (float)(current.z + 1))); - subMesh2.verts.Add(new Vector3((float)current.x + 0.5f, 0f, (float)(current.z + 1))); - subMesh2.verts.Add(new Vector3((float)(current.x + 1), 0f, (float)(current.z + 1))); - subMesh2.verts.Add(new Vector3((float)(current.x + 1), 0f, (float)current.z + 0.5f)); - subMesh2.verts.Add(new Vector3((float)(current.x + 1), 0f, (float)current.z)); - subMesh2.verts.Add(new Vector3((float)current.x + 0.5f, 0f, (float)current.z + 0.5f)); - for (int j = 0; j < 8; j++) + TerrainDef current2 = enumerator2.Current; + LayerSubMesh subMesh2 = base.GetSubMesh(this.GetMaterialFor(current2)); + if (subMesh2 != null) { - array2[j] = false; - } - for (int k = 0; k < 8; k++) - { - if (k % 2 == 0) + int count = subMesh2.verts.Count; + subMesh2.verts.Add(new Vector3((float)((float)current.x + 0.5), 0f, (float)current.z)); + subMesh2.verts.Add(new Vector3((float)current.x, 0f, (float)current.z)); + subMesh2.verts.Add(new Vector3((float)current.x, 0f, (float)((float)current.z + 0.5))); + subMesh2.verts.Add(new Vector3((float)current.x, 0f, (float)(current.z + 1))); + subMesh2.verts.Add(new Vector3((float)((float)current.x + 0.5), 0f, (float)(current.z + 1))); + subMesh2.verts.Add(new Vector3((float)(current.x + 1), 0f, (float)(current.z + 1))); + subMesh2.verts.Add(new Vector3((float)(current.x + 1), 0f, (float)((float)current.z + 0.5))); + subMesh2.verts.Add(new Vector3((float)(current.x + 1), 0f, (float)current.z)); + subMesh2.verts.Add(new Vector3((float)((float)current.x + 0.5), 0f, (float)((float)current.z + 0.5))); + for (int j = 0; j < 8; j++) + { + array2[j] = false; + } + for (int k = 0; k < 8; k++) { - if (array[k] == current2) + if (k % 2 == 0) + { + if (array[k] == current2) + { + array2[(k - 1 + 8) % 8] = true; + array2[k] = true; + array2[(k + 1) % 8] = true; + } + } + else if (array[k] == current2) { - array2[(k - 1 + 8) % 8] = true; array2[k] = true; - array2[(k + 1) % 8] = true; } } - else if (array[k] == current2) - { - array2[k] = true; - } - } - for (int l = 0; l < 8; l++) - { - if (array2[l]) + for (int l = 0; l < 8; l++) { - subMesh2.colors.Add(SectionLayer_Terrain.ColorWhite); + if (array2[l]) + { + subMesh2.colors.Add(SectionLayer_Terrain.ColorWhite); + } + else + { + subMesh2.colors.Add(SectionLayer_Terrain.ColorClear); + } } - else + subMesh2.colors.Add(SectionLayer_Terrain.ColorClear); + for (int m = 0; m < 8; m++) { - subMesh2.colors.Add(SectionLayer_Terrain.ColorClear); + subMesh2.tris.Add(count + m); + subMesh2.tris.Add(count + (m + 1) % 8); + subMesh2.tris.Add(count + 8); } } - subMesh2.colors.Add(SectionLayer_Terrain.ColorClear); - for (int m = 0; m < 8; m++) - { - subMesh2.tris.Add(count + m); - subMesh2.tris.Add(count + (m + 1) % 8); - subMesh2.tris.Add(count + 8); - } } } + finally + { + ((IDisposable)(object)enumerator2).Dispose(); + } } base.FinalizeMesh(MeshParts.All); } diff --git a/Assembly-CSharp/Verse/SectionLayer_TerrainScatter.cs b/Assembly-CSharp/Verse/SectionLayer_TerrainScatter.cs index 6261c3914..c9054d665 100644 --- a/Assembly-CSharp/Verse/SectionLayer_TerrainScatter.cs +++ b/Assembly-CSharp/Verse/SectionLayer_TerrainScatter.cs @@ -44,7 +44,7 @@ public void PrintOnto(SectionLayer layer) } } - private List scats = new List(); + private List scats = new List(); public override bool Visible { @@ -56,16 +56,16 @@ public override bool Visible public SectionLayer_TerrainScatter(Section section) : base(section) { - this.relevantChangeTypes = MapMeshFlag.Terrain; + base.relevantChangeTypes = MapMeshFlag.Terrain; } public override void Regenerate() { base.ClearSubMeshes(MeshParts.All); - this.scats.RemoveAll((SectionLayer_TerrainScatter.Scatterable scat) => !scat.IsOnValidTerrain); + this.scats.RemoveAll((Predicate)((Scatterable scat) => !scat.IsOnValidTerrain)); int num = 0; TerrainDef[] topGrid = base.Map.terrainGrid.topGrid; - CellRect cellRect = this.section.CellRect; + CellRect cellRect = base.section.CellRect; CellIndices cellIndices = base.Map.cellIndices; for (int i = cellRect.minZ; i <= cellRect.maxZ; i++) { @@ -82,20 +82,17 @@ public override void Regenerate() while (this.scats.Count < num && num2 < 200) { num2++; - IntVec3 randomCell = this.section.CellRect.RandomCell; + IntVec3 randomCell = base.section.CellRect.RandomCell; string terrScatType = base.Map.terrainGrid.TerrainAt(randomCell).scatterType; - if (terrScatType != null && !randomCell.Filled(base.Map)) + ScatterableDef def2 = default(ScatterableDef); + if (terrScatType != null && !randomCell.Filled(base.Map) && (from def in DefDatabase.AllDefs + where def.scatterType == terrScatType + select def).TryRandomElement(out def2)) { - ScatterableDef def2; - if ((from def in DefDatabase.AllDefs - where def.scatterType == terrScatType - select def).TryRandomElement(out def2)) - { - Vector3 loc = new Vector3((float)randomCell.x + Rand.Value, (float)randomCell.y, (float)randomCell.z + Rand.Value); - SectionLayer_TerrainScatter.Scatterable scatterable = new SectionLayer_TerrainScatter.Scatterable(def2, loc, base.Map); - this.scats.Add(scatterable); - scatterable.PrintOnto(this); - } + Vector3 loc = new Vector3((float)randomCell.x + Rand.Value, (float)randomCell.y, (float)randomCell.z + Rand.Value); + Scatterable scatterable = new Scatterable(def2, loc, base.Map); + this.scats.Add(scatterable); + scatterable.PrintOnto(this); } } for (int k = 0; k < this.scats.Count; k++) diff --git a/Assembly-CSharp/Verse/SectionLayer_Things.cs b/Assembly-CSharp/Verse/SectionLayer_Things.cs index 7c5f2a1eb..aae405617 100644 --- a/Assembly-CSharp/Verse/SectionLayer_Things.cs +++ b/Assembly-CSharp/Verse/SectionLayer_Things.cs @@ -1,4 +1,3 @@ -using System; using System.Collections.Generic; namespace Verse @@ -13,33 +12,32 @@ public SectionLayer_Things(Section section) : base(section) public override void DrawLayer() { - if (!DebugViewSettings.drawThingsPrinted) + if (DebugViewSettings.drawThingsPrinted) { - return; + base.DrawLayer(); } - base.DrawLayer(); } public override void Regenerate() { base.ClearSubMeshes(MeshParts.All); - foreach (IntVec3 current in this.section.CellRect) + foreach (IntVec3 item in base.section.CellRect) { + IntVec3 current = item; List list = base.Map.thingGrid.ThingsListAt(current); int count = list.Count; - for (int i = 0; i < count; i++) + for (int num = 0; num < count; num++) { - Thing thing = list[i]; - if (thing.def.drawerType != DrawerType.None) + Thing thing = list[num]; + if (thing.def.drawerType != 0 && (thing.def.drawerType != DrawerType.RealtimeOnly || !this.requireAddToMapMesh) && (!(thing.def.hideAtSnowDepth < 1.0) || !(base.Map.snowGrid.GetDepth(thing.Position) > thing.def.hideAtSnowDepth))) { - if (thing.def.drawerType != DrawerType.RealtimeOnly || !this.requireAddToMapMesh) + IntVec3 position = thing.Position; + if (position.x == current.x) { - if (thing.def.hideAtSnowDepth >= 1f || base.Map.snowGrid.GetDepth(thing.Position) <= thing.def.hideAtSnowDepth) + IntVec3 position2 = thing.Position; + if (position2.z == current.z) { - if (thing.Position.x == current.x && thing.Position.z == current.z) - { - this.TakePrintFrom(thing); - } + this.TakePrintFrom(thing); } } } diff --git a/Assembly-CSharp/Verse/SectionLayer_ThingsGeneral.cs b/Assembly-CSharp/Verse/SectionLayer_ThingsGeneral.cs index 42acdceba..d9a42f9bc 100644 --- a/Assembly-CSharp/Verse/SectionLayer_ThingsGeneral.cs +++ b/Assembly-CSharp/Verse/SectionLayer_ThingsGeneral.cs @@ -6,8 +6,8 @@ public class SectionLayer_ThingsGeneral : SectionLayer_Things { public SectionLayer_ThingsGeneral(Section section) : base(section) { - this.relevantChangeTypes = MapMeshFlag.Things; - this.requireAddToMapMesh = true; + base.relevantChangeTypes = MapMeshFlag.Things; + base.requireAddToMapMesh = true; } protected override void TakePrintFrom(Thing t) @@ -18,15 +18,7 @@ protected override void TakePrintFrom(Thing t) } catch (Exception ex) { - Log.Error(string.Concat(new object[] - { - "Exception printing ", - t, - " at ", - t.Position, - ": ", - ex.ToString() - })); + Log.Error("Exception printing " + t + " at " + t.Position + ": " + ex.ToString()); } } } diff --git a/Assembly-CSharp/Verse/SectionLayer_Watergen.cs b/Assembly-CSharp/Verse/SectionLayer_Watergen.cs index bb452b145..81208abeb 100644 --- a/Assembly-CSharp/Verse/SectionLayer_Watergen.cs +++ b/Assembly-CSharp/Verse/SectionLayer_Watergen.cs @@ -20,7 +20,7 @@ public override SectionLayerPhaseDef Phase public SectionLayer_Watergen(Section section) : base(section) { - this.relevantChangeTypes = MapMeshFlag.Terrain; + base.relevantChangeTypes = MapMeshFlag.Terrain; } public override Material GetMaterialFor(TerrainDef terrain) @@ -31,26 +31,25 @@ public override Material GetMaterialFor(TerrainDef terrain) public override void Regenerate() { base.Regenerate(); - this.renderOrder = (from sm in this.subMeshes + this.renderOrder = (from sm in base.subMeshes orderby sm.material.renderQueue - select sm).ToList(); + select sm).ToList(); } public override void DrawLayer() { - if (!this.Visible) + if (this.Visible) { - return; - } - Matrix4x4 matrix = Find.Camera.cameraToWorldMatrix * Find.Camera.projectionMatrix * Find.Camera.worldToCameraMatrix; - int count = this.renderOrder.Count; - for (int i = 0; i < count; i++) - { - LayerSubMesh layerSubMesh = this.renderOrder[i]; - if (layerSubMesh.finalized && !layerSubMesh.disabled) + Matrix4x4 matrix = Find.Camera.cameraToWorldMatrix * Find.Camera.projectionMatrix * Find.Camera.worldToCameraMatrix; + int count = this.renderOrder.Count; + for (int num = 0; num < count; num++) { - layerSubMesh.material.SetPass(0); - Graphics.DrawMeshNow(layerSubMesh.mesh, matrix); + LayerSubMesh layerSubMesh = this.renderOrder[num]; + if (layerSubMesh.finalized && !layerSubMesh.disabled) + { + layerSubMesh.material.SetPass(0); + Graphics.DrawMeshNow(layerSubMesh.mesh, matrix); + } } } } diff --git a/Assembly-CSharp/Verse/SectionLayer_Zones.cs b/Assembly-CSharp/Verse/SectionLayer_Zones.cs index 73325707c..f80df2cb1 100644 --- a/Assembly-CSharp/Verse/SectionLayer_Zones.cs +++ b/Assembly-CSharp/Verse/SectionLayer_Zones.cs @@ -1,5 +1,4 @@ using RimWorld; -using System; using UnityEngine; namespace Verse @@ -16,7 +15,7 @@ public override bool Visible public SectionLayer_Zones(Section section) : base(section) { - this.relevantChangeTypes = MapMeshFlag.Zone; + base.relevantChangeTypes = MapMeshFlag.Zone; } public override void DrawLayer() @@ -31,7 +30,7 @@ public override void Regenerate() { float y = Altitudes.AltitudeFor(AltitudeLayer.Zone); ZoneManager zoneManager = base.Map.zoneManager; - CellRect cellRect = new CellRect(this.section.botLeft.x, this.section.botLeft.z, 17, 17); + CellRect cellRect = new CellRect(base.section.botLeft.x, base.section.botLeft.z, 17, 17); cellRect.ClipInsideMap(base.Map); base.ClearSubMeshes(MeshParts.All); for (int i = cellRect.minX; i <= cellRect.maxX; i++) diff --git a/Assembly-CSharp/Verse/ShaderDatabase.cs b/Assembly-CSharp/Verse/ShaderDatabase.cs index f9d09a88d..85e28100a 100644 --- a/Assembly-CSharp/Verse/ShaderDatabase.cs +++ b/Assembly-CSharp/Verse/ShaderDatabase.cs @@ -1,4 +1,3 @@ -using System; using System.Collections.Generic; using UnityEngine; @@ -68,31 +67,55 @@ public static Shader ShaderFromType(ShaderType sType) switch (sType) { case ShaderType.Cutout: + { return ShaderDatabase.Cutout; - case ShaderType.CutoutFlying: - return ShaderDatabase.CutoutFlying; + } case ShaderType.CutoutPlant: + { return ShaderDatabase.CutoutPlant; + } case ShaderType.CutoutComplex: + { return ShaderDatabase.CutoutComplex; + } case ShaderType.CutoutSkin: + { return ShaderDatabase.CutoutSkin; + } + case ShaderType.CutoutFlying: + { + return ShaderDatabase.CutoutFlying; + } case ShaderType.Transparent: + { return ShaderDatabase.Transparent; - case ShaderType.TransparentPostLight: - return ShaderDatabase.TransparentPostLight; + } case ShaderType.MetaOverlay: + { return ShaderDatabase.MetaOverlay; + } case ShaderType.Mote: + { return ShaderDatabase.Mote; + } case ShaderType.MoteGlow: + { return ShaderDatabase.MoteGlow; + } + case ShaderType.TransparentPostLight: + { + return ShaderDatabase.TransparentPostLight; + } case ShaderType.MoteWater: + { return ShaderDatabase.MoteWater; + } default: + { Log.ErrorOnce("Unknown ShaderType " + sType, 2766893); return ShaderDatabase.DefaultShader; } + } } public static Shader LoadShader(string shaderPath) @@ -106,7 +129,7 @@ public static Shader LoadShader(string shaderPath) ShaderDatabase.lookup[shaderPath] = (Shader)Resources.Load("Materials/" + shaderPath, typeof(Shader)); } Shader shader = ShaderDatabase.lookup[shaderPath]; - if (shader == null) + if ((Object)shader == (Object)null) { Log.Warning("Could not load shader " + shaderPath); return ShaderDatabase.DefaultShader; diff --git a/Assembly-CSharp/Verse/ShaderParameter.cs b/Assembly-CSharp/Verse/ShaderParameter.cs index 32cdaffd4..2eb19fe79 100644 --- a/Assembly-CSharp/Verse/ShaderParameter.cs +++ b/Assembly-CSharp/Verse/ShaderParameter.cs @@ -1,4 +1,3 @@ -using System; using System.Xml; namespace Verse @@ -14,10 +13,12 @@ public void LoadDataFromXmlCustom(XmlNode xmlRoot) if (xmlRoot.ChildNodes.Count != 1) { Log.Error("Misconfigured ThingCount: " + xmlRoot.OuterXml); - return; } - this.name = xmlRoot.Name; - this.value = (float)ParseHelper.FromString(xmlRoot.FirstChild.Value, typeof(float)); + else + { + this.name = xmlRoot.Name; + this.value = (float)ParseHelper.FromString(xmlRoot.FirstChild.Value, typeof(float)); + } } } } diff --git a/Assembly-CSharp/Verse/ShaderPropertyIDs.cs b/Assembly-CSharp/Verse/ShaderPropertyIDs.cs index 2433a20ce..e985a756e 100644 --- a/Assembly-CSharp/Verse/ShaderPropertyIDs.cs +++ b/Assembly-CSharp/Verse/ShaderPropertyIDs.cs @@ -1,4 +1,3 @@ -using System; using UnityEngine; namespace Verse diff --git a/Assembly-CSharp/Verse/ShaderType.cs b/Assembly-CSharp/Verse/ShaderType.cs index d9f9f0129..579a86bf7 100644 --- a/Assembly-CSharp/Verse/ShaderType.cs +++ b/Assembly-CSharp/Verse/ShaderType.cs @@ -1,20 +1,18 @@ -using System; - namespace Verse { public enum ShaderType : byte { - None, - Cutout, - CutoutFlying, - CutoutPlant, - CutoutComplex, - CutoutSkin, - Transparent, - TransparentPostLight, - MetaOverlay, - Mote, - MoteGlow, - MoteWater + None = 0, + Cutout = 1, + CutoutFlying = 2, + CutoutPlant = 3, + CutoutComplex = 4, + CutoutSkin = 5, + Transparent = 6, + TransparentPostLight = 7, + MetaOverlay = 8, + Mote = 9, + MoteGlow = 10, + MoteWater = 11 } } diff --git a/Assembly-CSharp/Verse/ShaderUtility.cs b/Assembly-CSharp/Verse/ShaderUtility.cs index 05d782682..0bcc60ff8 100644 --- a/Assembly-CSharp/Verse/ShaderUtility.cs +++ b/Assembly-CSharp/Verse/ShaderUtility.cs @@ -1,4 +1,3 @@ -using System; using UnityEngine; namespace Verse @@ -7,7 +6,7 @@ public static class ShaderUtility { public static bool SupportsMaskTex(this Shader shader) { - return shader == ShaderDatabase.CutoutComplex; + return (Object)shader == (Object)ShaderDatabase.CutoutComplex; } } } diff --git a/Assembly-CSharp/Verse/ShadowData.cs b/Assembly-CSharp/Verse/ShadowData.cs index 7c584ef8f..434a835e1 100644 --- a/Assembly-CSharp/Verse/ShadowData.cs +++ b/Assembly-CSharp/Verse/ShadowData.cs @@ -1,4 +1,3 @@ -using System; using UnityEngine; namespace Verse diff --git a/Assembly-CSharp/Verse/ShadowMeshPool.cs b/Assembly-CSharp/Verse/ShadowMeshPool.cs index 724aa5e04..91d297d32 100644 --- a/Assembly-CSharp/Verse/ShadowMeshPool.cs +++ b/Assembly-CSharp/Verse/ShadowMeshPool.cs @@ -1,4 +1,3 @@ -using System; using System.Collections.Generic; using UnityEngine; @@ -21,7 +20,7 @@ public static Mesh GetShadowMesh(float baseEdgeLength, float tallness) public static Mesh GetShadowMesh(float baseWidth, float baseHeight, float tallness) { int key = ShadowMeshPool.HashOf(baseWidth, baseHeight, tallness); - Mesh mesh; + Mesh mesh = default(Mesh); if (!ShadowMeshPool.shadowMeshDict.TryGetValue(key, out mesh)) { mesh = MeshMakerShadows.NewShadowMesh(baseWidth, baseHeight, tallness); @@ -32,9 +31,9 @@ public static Mesh GetShadowMesh(float baseWidth, float baseHeight, float tallne private static int HashOf(float baseWidth, float baseheight, float tallness) { - int num = (int)(baseWidth * 1000f); - int num2 = (int)(baseheight * 1000f); - int num3 = (int)(tallness * 1000f); + int num = (int)(baseWidth * 1000.0); + int num2 = (int)(baseheight * 1000.0); + int num3 = (int)(tallness * 1000.0); int num4 = num * 391 ^ 261231; num4 ^= num2 * 612331; return num4 ^ num3 * 456123; diff --git a/Assembly-CSharp/Verse/ShootLeanUtility.cs b/Assembly-CSharp/Verse/ShootLeanUtility.cs index 526607f6e..dd072ef54 100644 --- a/Assembly-CSharp/Verse/ShootLeanUtility.cs +++ b/Assembly-CSharp/Verse/ShootLeanUtility.cs @@ -1,4 +1,3 @@ -using System; using System.Collections.Generic; namespace Verse @@ -29,54 +28,80 @@ public static void LeanShootingSourcesFromTo(IntVec3 shooterLoc, IntVec3 targetP { listToFill.Clear(); float angleFlat = (targetPos - shooterLoc).AngleFlat; - bool flag = angleFlat > 270f || angleFlat < 90f; - bool flag2 = angleFlat > 90f && angleFlat < 270f; - bool flag3 = angleFlat > 180f; - bool flag4 = angleFlat < 180f; + bool flag = angleFlat > 270.0 || angleFlat < 90.0; + bool flag2 = angleFlat > 90.0 && angleFlat < 270.0; + bool flag3 = angleFlat > 180.0; + bool flag4 = angleFlat < 180.0; bool[] workingBlockedArray = ShootLeanUtility.GetWorkingBlockedArray(); for (int i = 0; i < 8; i++) { workingBlockedArray[i] = !(shooterLoc + GenAdj.AdjacentCells[i]).CanBeSeenOver(map); } - if (!workingBlockedArray[1] && ((workingBlockedArray[0] && !workingBlockedArray[5] && flag) || (workingBlockedArray[2] && !workingBlockedArray[4] && flag2))) + if (!workingBlockedArray[1]) { - listToFill.Add(shooterLoc + new IntVec3(1, 0, 0)); - } - if (!workingBlockedArray[3] && ((workingBlockedArray[0] && !workingBlockedArray[6] && flag) || (workingBlockedArray[2] && !workingBlockedArray[7] && flag2))) - { - listToFill.Add(shooterLoc + new IntVec3(-1, 0, 0)); + if (workingBlockedArray[0] && !workingBlockedArray[5] && flag) + { + goto IL_00d3; + } + if (workingBlockedArray[2] && !workingBlockedArray[4] && flag2) + goto IL_00d3; } - if (!workingBlockedArray[2] && ((workingBlockedArray[3] && !workingBlockedArray[7] && flag3) || (workingBlockedArray[1] && !workingBlockedArray[4] && flag4))) + goto IL_00e7; + IL_0134: + if (!workingBlockedArray[2]) { - listToFill.Add(shooterLoc + new IntVec3(0, 0, -1)); + if (workingBlockedArray[3] && !workingBlockedArray[7] && flag3) + { + goto IL_016e; + } + if (workingBlockedArray[1] && !workingBlockedArray[4] && flag4) + goto IL_016e; } - if (!workingBlockedArray[0] && ((workingBlockedArray[3] && !workingBlockedArray[6] && flag3) || (workingBlockedArray[1] && !workingBlockedArray[5] && flag4))) + goto IL_0182; + IL_016e: + listToFill.Add(shooterLoc + new IntVec3(0, 0, -1)); + goto IL_0182; + IL_0120: + listToFill.Add(shooterLoc + new IntVec3(-1, 0, 0)); + goto IL_0134; + IL_01bc: + listToFill.Add(shooterLoc + new IntVec3(0, 0, 1)); + goto IL_01d0; + IL_0182: + if (!workingBlockedArray[0]) { - listToFill.Add(shooterLoc + new IntVec3(0, 0, 1)); + if (workingBlockedArray[3] && !workingBlockedArray[6] && flag3) + { + goto IL_01bc; + } + if (workingBlockedArray[1] && !workingBlockedArray[5] && flag4) + goto IL_01bc; } + goto IL_01d0; + IL_01d0: for (int j = 0; j < 4; j++) { - if (!workingBlockedArray[j]) + if (!workingBlockedArray[j] && (j != 0 || flag) && (j != 1 || flag4) && (j != 2 || flag2) && (j != 3 || flag3) && (shooterLoc + GenAdj.AdjacentCells[j]).GetCover(map) != null) { - if (j != 0 || flag) - { - if (j != 1 || flag4) - { - if (j != 2 || flag2) - { - if (j != 3 || flag3) - { - if ((shooterLoc + GenAdj.AdjacentCells[j]).GetCover(map) != null) - { - listToFill.Add(shooterLoc + GenAdj.AdjacentCells[j]); - } - } - } - } - } + listToFill.Add(shooterLoc + GenAdj.AdjacentCells[j]); } } ShootLeanUtility.ReturnWorkingBlockedArray(workingBlockedArray); + return; + IL_00d3: + listToFill.Add(shooterLoc + new IntVec3(1, 0, 0)); + goto IL_00e7; + IL_00e7: + if (!workingBlockedArray[3]) + { + if (workingBlockedArray[0] && !workingBlockedArray[6] && flag) + { + goto IL_0120; + } + if (workingBlockedArray[2] && !workingBlockedArray[7] && flag2) + goto IL_0120; + } + goto IL_0134; } public static void CalcShootableCellsOf(List outCells, Thing t) @@ -97,17 +122,16 @@ public static void CalcShootableCellsOf(List outCells, Thing t) else { outCells.Add(t.Position); - if (t.def.size.x != 1 || t.def.size.z != 1) + if (t.def.size.x == 1 && t.def.size.z == 1) + return; + CellRect.CellRectIterator iterator = t.OccupiedRect().GetIterator(); + while (!iterator.Done()) { - CellRect.CellRectIterator iterator = t.OccupiedRect().GetIterator(); - while (!iterator.Done()) + if (iterator.Current != t.Position) { - if (iterator.Current != t.Position) - { - outCells.Add(iterator.Current); - } - iterator.MoveNext(); + outCells.Add(iterator.Current); } + iterator.MoveNext(); } } } diff --git a/Assembly-CSharp/Verse/ShootLine.cs b/Assembly-CSharp/Verse/ShootLine.cs index 66bba3117..600e636a1 100644 --- a/Assembly-CSharp/Verse/ShootLine.cs +++ b/Assembly-CSharp/Verse/ShootLine.cs @@ -1,4 +1,3 @@ -using System; using System.Collections.Generic; namespace Verse @@ -48,14 +47,7 @@ public IEnumerable Points() public override string ToString() { - return string.Concat(new object[] - { - "(", - this.source, - "->", - this.dest, - ")" - }); + return "(" + this.source + "->" + this.dest + ")"; } } } diff --git a/Assembly-CSharp/Verse/ShortHashGiver.cs b/Assembly-CSharp/Verse/ShortHashGiver.cs index 0174a2ce0..5fc431f1b 100644 --- a/Assembly-CSharp/Verse/ShortHashGiver.cs +++ b/Assembly-CSharp/Verse/ShortHashGiver.cs @@ -13,24 +13,21 @@ public static void GiveAllShortHashes() { ShortHashGiver.takenHashesPerDeftype.Clear(); List list = new List(); - foreach (Type current in GenDefDatabase.AllDefTypesWithDatabases()) + foreach (Type item2 in GenDefDatabase.AllDefTypesWithDatabases()) { - Type type = typeof(DefDatabase<>).MakeGenericType(new Type[] - { - current - }); + Type type = typeof(DefDatabase<>).MakeGenericType(item2); PropertyInfo property = type.GetProperty("AllDefs"); MethodInfo getMethod = property.GetGetMethod(); IEnumerable enumerable = (IEnumerable)getMethod.Invoke(null, null); list.Clear(); - foreach (Def item in enumerable) + foreach (Def item3 in enumerable) { - list.Add(item); + list.Add(item3); } - list.SortBy((Def d) => d.defName); + list.SortBy((Func)((Def d) => d.defName)); for (int i = 0; i < list.Count; i++) { - ShortHashGiver.GiveShortHash(list[i], current); + ShortHashGiver.GiveShortHash(list[i], item2); } } } @@ -40,27 +37,31 @@ private static void GiveShortHash(Def def, Type defType) if (def.shortHash != 0) { Log.Error(def + " already has short hash."); - return; - } - HashSet hashSet; - if (!ShortHashGiver.takenHashesPerDeftype.TryGetValue(defType, out hashSet)) - { - hashSet = new HashSet(); - ShortHashGiver.takenHashesPerDeftype.Add(defType, hashSet); } - ushort num = (ushort)(GenText.StableStringHash(def.defName) % 65535); - int num2 = 0; - while (num == 0 || hashSet.Contains(num)) + else { - num += 1; - num2++; - if (num2 > 5000) + HashSet hashSet = default(HashSet); + if (!ShortHashGiver.takenHashesPerDeftype.TryGetValue(defType, out hashSet)) + { + hashSet = new HashSet(); + ShortHashGiver.takenHashesPerDeftype.Add(defType, hashSet); + } + ushort num = (ushort)(GenText.StableStringHash(def.defName) % 65535); + int num2 = 0; + while (true) { - Log.Message("Short hashes are saturated. There are probably too many Defs."); + if (num != 0 && !hashSet.Contains(num)) + break; + num = (ushort)(num + 1); + num2++; + if (num2 > 5000) + { + Log.Message("Short hashes are saturated. There are probably too many Defs."); + } } + def.shortHash = num; + hashSet.Add(num); } - def.shortHash = num; - hashSet.Add(num); } } } diff --git a/Assembly-CSharp/Verse/ShotReport.cs b/Assembly-CSharp/Verse/ShotReport.cs index 1e4c89341..ff9f47897 100644 --- a/Assembly-CSharp/Verse/ShotReport.cs +++ b/Assembly-CSharp/Verse/ShotReport.cs @@ -45,7 +45,7 @@ private float FactorFromPosture if (this.target.HasThing) { Pawn pawn = this.target.Thing as Pawn; - if (pawn != null && this.distance >= 4.5f && pawn.GetPosture() != PawnPosture.Standing) + if (((pawn != null) ? ((this.distance >= 4.5) ? pawn.GetPosture() : PawnPosture.Standing) : PawnPosture.Standing) != 0) { return 0.2f; } @@ -61,7 +61,7 @@ private float FactorFromExecution if (this.target.HasThing) { Pawn pawn = this.target.Thing as Pawn; - if (pawn != null && this.distance <= 3.9f && pawn.GetPosture() != PawnPosture.Standing) + if (((pawn != null) ? ((this.distance <= 3.9000000953674316) ? pawn.GetPosture() : PawnPosture.Standing) : PawnPosture.Standing) != 0) { return 7.5f; } @@ -76,7 +76,7 @@ private float FactorFromCoveringGas { if (this.coveringGas != null) { - return 1f - this.coveringGas.gas.accuracyPenalty; + return (float)(1.0 - this.coveringGas.gas.accuracyPenalty); } return 1f; } @@ -86,7 +86,7 @@ public float ChanceToNotHitCover { get { - return 1f - this.coversOverallBlockChance; + return (float)(1.0 - this.coversOverallBlockChance); } } @@ -111,20 +111,12 @@ public static ShotReport HitReportFor(Thing caster, Verb verb, LocalTargetInfo t { Pawn pawn = caster as Pawn; IntVec3 cell = target.Cell; - ShotReport result; + ShotReport result = default(ShotReport); result.distance = (cell - caster.Position).LengthHorizontal; result.target = target.ToTargetInfo(caster.Map); - float f; - if (pawn != null) - { - f = pawn.GetStatValue(StatDefOf.ShootingAccuracy, true); - } - else - { - f = 0.96f; - } + float f = (float)((pawn == null) ? 0.95999997854232788 : pawn.GetStatValue(StatDefOf.ShootingAccuracy, true)); result.factorFromShooterAndDist = Mathf.Pow(f, result.distance); - if (result.factorFromShooterAndDist < 0.0201f) + if (result.factorFromShooterAndDist < 0.020099999383091927) { result.factorFromShooterAndDist = 0.0201f; } @@ -132,12 +124,12 @@ public static ShotReport HitReportFor(Thing caster, Verb verb, LocalTargetInfo t result.covers = CoverUtility.CalculateCoverGiverSet(cell, caster.Position, caster.Map); result.coversOverallBlockChance = CoverUtility.CalculateOverallBlockChance(cell, caster.Position, caster.Map); result.coveringGas = null; - ShootLine shootLine; + ShootLine shootLine = default(ShootLine); if (verb.TryFindShootLineFromTo(verb.caster.Position, target, out shootLine)) { - foreach (IntVec3 current in shootLine.Points()) + foreach (IntVec3 item in shootLine.Points()) { - Thing gas = current.GetGas(caster.Map); + Thing gas = item.GetGas(caster.Map); if (gas != null && (result.coveringGas == null || result.coveringGas.gas.accuracyPenalty < gas.def.gas.accuracyPenalty)) { result.coveringGas = gas.def; @@ -162,7 +154,7 @@ public static ShotReport HitReportFor(Thing caster, Verb verb, LocalTargetInfo t } else { - result.factorFromTargetSize = target.Thing.def.fillPercent * 1.7f; + result.factorFromTargetSize = (float)(target.Thing.def.fillPercent * 1.7000000476837158); } result.factorFromTargetSize = Mathf.Clamp(result.factorFromTargetSize, 0.5f, 2f); } @@ -173,7 +165,7 @@ public static ShotReport HitReportFor(Thing caster, Verb verb, LocalTargetInfo t public string GetTextReadout() { StringBuilder stringBuilder = new StringBuilder(); - if (this.forcedMissRadius > 0.5f) + if (this.forcedMissRadius > 0.5) { stringBuilder.AppendLine(); stringBuilder.AppendLine("WeaponMissRadius".Translate() + " " + this.forcedMissRadius.ToString("F1")); @@ -182,41 +174,37 @@ public string GetTextReadout() { stringBuilder.AppendLine(" " + this.TotalEstimatedHitChance.ToStringPercent()); stringBuilder.AppendLine(" " + "ShootReportShooterAbility".Translate() + " " + this.factorFromShooterAndDist.ToStringPercent()); - if (this.factorFromEquipment < 0.99f) + if (this.factorFromEquipment < 0.99000000953674316) { stringBuilder.AppendLine(" " + "ShootReportWeapon".Translate() + " " + this.factorFromEquipment.ToStringPercent()); } - if (this.target.HasThing && this.factorFromTargetSize != 1f) + if (this.target.HasThing && this.factorFromTargetSize != 1.0) { stringBuilder.AppendLine(" " + "TargetSize".Translate() + " " + this.factorFromTargetSize.ToStringPercent()); } - if (this.factorFromWeather < 0.99f) + if (this.factorFromWeather < 0.99000000953674316) { stringBuilder.AppendLine(" " + "Weather".Translate() + " " + this.factorFromWeather.ToStringPercent()); } - if (this.FactorFromCoveringGas < 0.99f) + if (this.FactorFromCoveringGas < 0.99000000953674316) { stringBuilder.AppendLine(" " + this.coveringGas.label.CapitalizeFirst() + " " + this.FactorFromCoveringGas.ToStringPercent()); } - if (this.FactorFromPosture < 0.9999f) + if (this.FactorFromPosture < 0.99989998340606689) { stringBuilder.AppendLine(" " + "TargetProne".Translate() + " " + this.FactorFromPosture.ToStringPercent()); } - if (this.FactorFromExecution != 1f) + if (this.FactorFromExecution != 1.0) { stringBuilder.AppendLine(" " + "Execution".Translate() + " " + this.FactorFromExecution.ToStringPercent()); } - if (this.ChanceToNotHitCover < 1f) + if (this.ChanceToNotHitCover < 1.0) { stringBuilder.AppendLine(" " + "ShootingCover".Translate() + " " + this.ChanceToNotHitCover.ToStringPercent()); for (int i = 0; i < this.covers.Count; i++) { CoverInfo coverInfo = this.covers[i]; - stringBuilder.AppendLine(" " + "CoverThingBlocksPercentOfShots".Translate(new object[] - { - coverInfo.Thing.LabelCap, - coverInfo.BlockChance.ToStringPercent() - })); + stringBuilder.AppendLine(" " + "CoverThingBlocksPercentOfShots".Translate(coverInfo.Thing.LabelCap, coverInfo.BlockChance.ToStringPercent())); } } else @@ -229,7 +217,7 @@ public string GetTextReadout() public Thing GetRandomCoverToMissInto() { - return this.covers.RandomElementByWeight((CoverInfo c) => c.BlockChance).Thing; + return this.covers.RandomElementByWeight((Func)((CoverInfo c) => c.BlockChance)).Thing; } } } diff --git a/Assembly-CSharp/Verse/SimpleColor.cs b/Assembly-CSharp/Verse/SimpleColor.cs index 89cd8bd86..6ddae0e00 100644 --- a/Assembly-CSharp/Verse/SimpleColor.cs +++ b/Assembly-CSharp/Verse/SimpleColor.cs @@ -1,15 +1,13 @@ -using System; - namespace Verse { public enum SimpleColor { - White, - Red, - Green, - Blue, - Magenta, - Yellow, - Cyan + White = 0, + Red = 1, + Green = 2, + Blue = 3, + Magenta = 4, + Yellow = 5, + Cyan = 6 } } diff --git a/Assembly-CSharp/Verse/SimpleColorExtension.cs b/Assembly-CSharp/Verse/SimpleColorExtension.cs index eee87cd97..32e95acec 100644 --- a/Assembly-CSharp/Verse/SimpleColorExtension.cs +++ b/Assembly-CSharp/Verse/SimpleColorExtension.cs @@ -10,22 +10,38 @@ public static Color ToUnityColor(this SimpleColor color) switch (color) { case SimpleColor.White: + { return Color.white; + } case SimpleColor.Red: + { return Color.red; + } case SimpleColor.Green: + { return Color.green; + } case SimpleColor.Blue: + { return Color.blue; + } case SimpleColor.Magenta: + { return Color.magenta; + } case SimpleColor.Yellow: + { return Color.yellow; + } case SimpleColor.Cyan: + { return Color.cyan; + } default: + { throw new ArgumentException(); } + } } } } diff --git a/Assembly-CSharp/Verse/SimpleCurve.cs b/Assembly-CSharp/Verse/SimpleCurve.cs index ded705463..b30a9ad48 100644 --- a/Assembly-CSharp/Verse/SimpleCurve.cs +++ b/Assembly-CSharp/Verse/SimpleCurve.cs @@ -1,7 +1,6 @@ using System; using System.Collections; using System.Collections.Generic; -using System.Diagnostics; using UnityEngine; namespace Verse @@ -13,7 +12,7 @@ public class SimpleCurve : IEnumerable, IEnumerable [Unsaved] private SimpleCurveView view; - private static Comparison CurvePointsComparer = delegate(CurvePoint a, CurvePoint b) + private static Comparison CurvePointsComparer = (Comparison)delegate(CurvePoint a, CurvePoint b) { if (a.x < b.x) { @@ -80,20 +79,29 @@ IEnumerator IEnumerable.GetEnumerator() return this.GetEnumerator(); } - [DebuggerHidden] public IEnumerator GetEnumerator() { - SimpleCurve.c__Iterator23C c__Iterator23C = new SimpleCurve.c__Iterator23C(); - c__Iterator23C.<>f__this = this; - return c__Iterator23C; + List.Enumerator enumerator = this.points.GetEnumerator(); + try + { + while (enumerator.MoveNext()) + { + CurvePoint point = enumerator.Current; + yield return point; + } + } + finally + { + ((IDisposable)(object)enumerator).Dispose(); + } } public void SetPoints(IEnumerable newPoints) { this.points.Clear(); - foreach (CurvePoint current in newPoints) + foreach (CurvePoint item in newPoints) { - this.points.Add(current); + this.points.Add(item); } this.SortPoints(); } @@ -120,14 +128,21 @@ public void SortPoints() public void RemovePointNear(CurvePoint point) { - for (int i = 0; i < this.points.Count; i++) + int num = 0; + while (true) { - if ((this.points[i].Loc - point.Loc).sqrMagnitude < 0.001f) + if (num < this.points.Count) { - this.points.RemoveAt(i); - return; + if (!((this.points[num].Loc - point.Loc).sqrMagnitude < 0.0010000000474974513)) + { + num++; + continue; + } + break; } + return; } + this.points.RemoveAt(num); } public float Evaluate(float x) @@ -147,17 +162,20 @@ public float Evaluate(float x) } CurvePoint curvePoint = this.points[0]; CurvePoint curvePoint2 = this.points[this.points.Count - 1]; - for (int i = 0; i < this.points.Count; i++) + int num = 0; + while (num < this.points.Count) { - if (x <= this.points[i].x) + if (!(x <= this.points[num].x)) { - curvePoint2 = this.points[i]; - if (i > 0) - { - curvePoint = this.points[i - 1]; - } - break; + num++; + continue; + } + curvePoint2 = this.points[num]; + if (num > 0) + { + curvePoint = this.points[num - 1]; } + break; } float t = (x - curvePoint.x) / (curvePoint2.x - curvePoint.x); return Mathf.Lerp(curvePoint.y, curvePoint2.y, t); @@ -169,33 +187,40 @@ public float PeriodProbabilityFromCumulative(float startX, float span) { return 0f; } - if (this.points[0].y != 0f) + if (this.points[0].y != 0.0) { Log.Warning("PeriodProbabilityFromCumulative should only run on curves whose first point is 0."); } float num = this.Evaluate(startX + span) - this.Evaluate(startX); - if (num < 0f) + if (num < 0.0) { Log.Error("PeriodicProbability got negative probability from " + this + ": slope should never be negative."); num = 0f; } - if (num > 1f) + if (num > 1.0) { num = 1f; } return num; } - [DebuggerHidden] public IEnumerable ConfigErrors(string prefix) { - SimpleCurve.c__Iterator23D c__Iterator23D = new SimpleCurve.c__Iterator23D(); - c__Iterator23D.prefix = prefix; - c__Iterator23D.<$>prefix = prefix; - c__Iterator23D.<>f__this = this; - SimpleCurve.c__Iterator23D expr_1C = c__Iterator23D; - expr_1C.$PC = -2; - return expr_1C; + int i = 0; + while (true) + { + if (i < this.points.Count - 1) + { + if (!(this.points[i + 1].x < this.points[i].x)) + { + i++; + continue; + } + break; + } + yield break; + } + yield return prefix + ": points are out of order"; } } } diff --git a/Assembly-CSharp/Verse/SimpleCurveDrawInfo.cs b/Assembly-CSharp/Verse/SimpleCurveDrawInfo.cs index b0f7a8e73..745debe6e 100644 --- a/Assembly-CSharp/Verse/SimpleCurveDrawInfo.cs +++ b/Assembly-CSharp/Verse/SimpleCurveDrawInfo.cs @@ -1,4 +1,3 @@ -using System; using UnityEngine; namespace Verse diff --git a/Assembly-CSharp/Verse/SimpleCurveDrawer.cs b/Assembly-CSharp/Verse/SimpleCurveDrawer.cs index 782723056..213f01af6 100644 --- a/Assembly-CSharp/Verse/SimpleCurveDrawer.cs +++ b/Assembly-CSharp/Verse/SimpleCurveDrawer.cs @@ -30,152 +30,155 @@ public static class SimpleCurveDrawer public static void DrawCurve(Rect rect, SimpleCurve curve, SimpleCurveDrawerStyle style = null, List marks = null, Rect legendScreenRect = default(Rect)) { - SimpleCurveDrawer.DrawCurve(rect, new SimpleCurveDrawInfo - { - curve = curve - }, style, marks, legendScreenRect); + SimpleCurveDrawInfo simpleCurveDrawInfo = new SimpleCurveDrawInfo(); + simpleCurveDrawInfo.curve = curve; + SimpleCurveDrawer.DrawCurve(rect, simpleCurveDrawInfo, style, marks, legendScreenRect); } public static void DrawCurve(Rect rect, SimpleCurveDrawInfo curve, SimpleCurveDrawerStyle style = null, List marks = null, Rect legendScreenRect = default(Rect)) { - if (curve.curve == null) + if (curve.curve != null) { - return; + List list = new List(); + list.Add(curve); + SimpleCurveDrawer.DrawCurves(rect, list, style, marks, legendScreenRect); } - SimpleCurveDrawer.DrawCurves(rect, new List - { - curve - }, style, marks, legendScreenRect); } public static void DrawCurves(Rect rect, List curves, SimpleCurveDrawerStyle style = null, List marks = null, Rect legendRect = default(Rect)) { - if (Event.current.type != EventType.Repaint) - { - return; - } - if (style == null) - { - style = new SimpleCurveDrawerStyle(); - } - if (curves.Count == 0) - { - return; - } - bool flag = true; - Rect viewRect = default(Rect); - for (int i = 0; i < curves.Count; i++) + if (Event.current.type == EventType.Repaint) { - SimpleCurveDrawInfo simpleCurveDrawInfo = curves[i]; - if (simpleCurveDrawInfo.curve != null) + if (style == null) { - if (flag) + style = new SimpleCurveDrawerStyle(); + } + if (curves.Count != 0) + { + bool flag = true; + Rect viewRect = default(Rect); + for (int i = 0; i < curves.Count; i++) { - flag = false; - viewRect = simpleCurveDrawInfo.curve.View.rect; + SimpleCurveDrawInfo simpleCurveDrawInfo = curves[i]; + if (simpleCurveDrawInfo.curve != null) + { + if (flag) + { + flag = false; + viewRect = simpleCurveDrawInfo.curve.View.rect; + } + else + { + viewRect.xMin = Mathf.Min(viewRect.xMin, simpleCurveDrawInfo.curve.View.rect.xMin); + viewRect.xMax = Mathf.Max(viewRect.xMax, simpleCurveDrawInfo.curve.View.rect.xMax); + viewRect.yMin = Mathf.Min(viewRect.yMin, simpleCurveDrawInfo.curve.View.rect.yMin); + viewRect.yMax = Mathf.Max(viewRect.yMax, simpleCurveDrawInfo.curve.View.rect.yMax); + } + } } - else + if (style.UseFixedScale) { - viewRect.xMin = Mathf.Min(viewRect.xMin, simpleCurveDrawInfo.curve.View.rect.xMin); - viewRect.xMax = Mathf.Max(viewRect.xMax, simpleCurveDrawInfo.curve.View.rect.xMax); - viewRect.yMin = Mathf.Min(viewRect.yMin, simpleCurveDrawInfo.curve.View.rect.yMin); - viewRect.yMax = Mathf.Max(viewRect.yMax, simpleCurveDrawInfo.curve.View.rect.yMax); + Vector2 fixedScale = style.FixedScale; + viewRect.yMin = fixedScale.x; + Vector2 fixedScale2 = style.FixedScale; + viewRect.yMax = fixedScale2.y; + } + if (style.OnlyPositiveValues) + { + if (viewRect.xMin < 0.0) + { + viewRect.xMin = 0f; + } + if (viewRect.yMin < 0.0) + { + viewRect.yMin = 0f; + } + } + if (style.UseFixedSection) + { + Vector2 fixedSection = style.FixedSection; + viewRect.xMin = fixedSection.x; + Vector2 fixedSection2 = style.FixedSection; + viewRect.xMax = fixedSection2.y; + } + if (!Mathf.Approximately(viewRect.width, 0f) && !Mathf.Approximately(viewRect.height, 0f)) + { + Rect rect2 = rect; + if (style.DrawMeasures) + { + rect2.xMin += 60f; + rect2.yMax -= 30f; + } + if (marks != null) + { + Rect rect3 = rect2; + rect3.height = 15f; + SimpleCurveDrawer.DrawCurveMarks(rect3, viewRect, marks); + rect2.yMin = rect3.yMax; + } + if (style.DrawBackground) + { + GUI.color = new Color(0.302f, 0.318f, 0.365f); + GUI.DrawTexture(rect2, BaseContent.WhiteTex); + } + if (style.DrawBackgroundLines) + { + SimpleCurveDrawer.DrawGraphBackgroundLines(rect2, viewRect); + } + if (style.DrawMeasures) + { + SimpleCurveDrawer.DrawCurveMeasures(rect, viewRect, rect2, style.MeasureLabelsXCount, style.MeasureLabelsYCount); + } + List.Enumerator enumerator = curves.GetEnumerator(); + try + { + while (enumerator.MoveNext()) + { + SimpleCurveDrawInfo current = enumerator.Current; + SimpleCurveDrawer.DrawCurveLines(rect2, current, style.DrawPoints, viewRect, style.UseAntiAliasedLines, style.PointsRemoveOptimization); + } + } + finally + { + ((IDisposable)(object)enumerator).Dispose(); + } + if (style.DrawLegend) + { + SimpleCurveDrawer.DrawCurvesLegend(legendRect, curves); + } + if (style.DrawCurveMousePoint) + { + SimpleCurveDrawer.DrawCurveMousePoint(curves, rect2, viewRect, style.LabelX, style.LabelY); + } } } } - if (style.UseFixedScale) - { - viewRect.yMin = style.FixedScale.x; - viewRect.yMax = style.FixedScale.y; - } - if (style.OnlyPositiveValues) - { - if (viewRect.xMin < 0f) - { - viewRect.xMin = 0f; - } - if (viewRect.yMin < 0f) - { - viewRect.yMin = 0f; - } - } - if (style.UseFixedSection) - { - viewRect.xMin = style.FixedSection.x; - viewRect.xMax = style.FixedSection.y; - } - if (Mathf.Approximately(viewRect.width, 0f) || Mathf.Approximately(viewRect.height, 0f)) - { - return; - } - Rect rect2 = rect; - if (style.DrawMeasures) - { - rect2.xMin += 60f; - rect2.yMax -= 30f; - } - if (marks != null) - { - Rect rect3 = rect2; - rect3.height = 15f; - SimpleCurveDrawer.DrawCurveMarks(rect3, viewRect, marks); - rect2.yMin = rect3.yMax; - } - if (style.DrawBackground) - { - GUI.color = new Color(0.302f, 0.318f, 0.365f); - GUI.DrawTexture(rect2, BaseContent.WhiteTex); - } - if (style.DrawBackgroundLines) - { - SimpleCurveDrawer.DrawGraphBackgroundLines(rect2, viewRect); - } - if (style.DrawMeasures) - { - SimpleCurveDrawer.DrawCurveMeasures(rect, viewRect, rect2, style.MeasureLabelsXCount, style.MeasureLabelsYCount); - } - foreach (SimpleCurveDrawInfo current in curves) - { - SimpleCurveDrawer.DrawCurveLines(rect2, current, style.DrawPoints, viewRect, style.UseAntiAliasedLines, style.PointsRemoveOptimization); - } - if (style.DrawLegend) - { - SimpleCurveDrawer.DrawCurvesLegend(legendRect, curves); - } - if (style.DrawCurveMousePoint) - { - SimpleCurveDrawer.DrawCurveMousePoint(curves, rect2, viewRect, style.LabelX, style.LabelY); - } } public static void DrawCurveLines(Rect rect, SimpleCurveDrawInfo curve, bool drawPoints, Rect viewRect, bool useAALines, bool pointsRemoveOptimization) { - if (curve.curve == null) + if (((curve.curve != null) ? curve.curve.PointsCount : 0) != 0) { - return; - } - if (curve.curve.PointsCount == 0) - { - return; - } - Rect position = rect; - position.yMin -= 1f; - position.yMax += 1f; - GUI.BeginGroup(position); - if (Event.current.type == EventType.Repaint) - { - if (useAALines) + Rect position = rect; + position.yMin -= 1f; + position.yMax += 1f; + GUI.BeginGroup(position); + if (Event.current.type == EventType.Repaint) { - bool flag = true; - Vector2 start = default(Vector2); - Vector2 curvePoint = default(Vector2); - int num = curve.curve.AllPoints.Count((CurvePoint x) => x.x >= viewRect.xMin && x.x <= viewRect.xMax); - int num2 = SimpleCurveDrawer.RemovePointsOptimizationFreq(num); - for (int i = 0; i < curve.curve.PointsCount; i++) + if (useAALines) { - CurvePoint curvePoint2 = curve.curve[i]; - if (!pointsRemoveOptimization || i % num2 != 0 || i == num - 1) + bool flag = true; + Vector2 start = default(Vector2); + Vector2 curvePoint = default(Vector2); + int num = curve.curve.AllPoints.Count((Func)((CurvePoint x) => x.x >= viewRect.xMin && x.x <= viewRect.xMax)); + int num2 = SimpleCurveDrawer.RemovePointsOptimizationFreq(num); + for (int i = 0; i < curve.curve.PointsCount; i++) { + CurvePoint curvePoint2 = curve.curve[i]; + if (pointsRemoveOptimization && i % num2 == 0 && i != num - 1) + { + continue; + } curvePoint.x = curvePoint2.x; curvePoint.y = curvePoint2.y; Vector2 vector = SimpleCurveDrawer.CurveToScreenCoordsInsideScreenRect(rect, viewRect, curvePoint); @@ -183,54 +186,65 @@ public static void DrawCurveLines(Rect rect, SimpleCurveDrawInfo curve, bool dra { flag = false; } - else if ((start.x >= 0f && start.x <= rect.width) || (vector.x >= 0f && vector.x <= rect.width)) + else { - Widgets.DrawLine(start, vector, curve.color, 1f); + if (start.x >= 0.0 && start.x <= rect.width) + { + goto IL_0164; + } + if (vector.x >= 0.0 && vector.x <= rect.width) + goto IL_0164; } + goto IL_0177; + IL_0164: + Widgets.DrawLine(start, vector, curve.color, 1f); + goto IL_0177; + IL_0177: start = vector; } + Vector2 start2 = SimpleCurveDrawer.CurveToScreenCoordsInsideScreenRect(rect, viewRect, curve.curve.AllPoints.First()); + Vector2 start3 = SimpleCurveDrawer.CurveToScreenCoordsInsideScreenRect(rect, viewRect, curve.curve.AllPoints.Last()); + Widgets.DrawLine(start2, new Vector2(0f, start2.y), curve.color, 1f); + Widgets.DrawLine(start3, new Vector2(rect.width, start3.y), curve.color, 1f); } - Vector2 start2 = SimpleCurveDrawer.CurveToScreenCoordsInsideScreenRect(rect, viewRect, curve.curve.AllPoints.First()); - Vector2 start3 = SimpleCurveDrawer.CurveToScreenCoordsInsideScreenRect(rect, viewRect, curve.curve.AllPoints.Last()); - Widgets.DrawLine(start2, new Vector2(0f, start2.y), curve.color, 1f); - Widgets.DrawLine(start3, new Vector2(rect.width, start3.y), curve.color, 1f); + else + { + GUI.color = curve.color; + float num3 = viewRect.x; + float num4 = (float)(rect.width / 1.0); + float num5 = viewRect.width / num4; + while (num3 < viewRect.xMax) + { + num3 += num5; + Vector2 vector2 = SimpleCurveDrawer.CurveToScreenCoordsInsideScreenRect(rect, viewRect, new Vector2(num3, curve.curve.Evaluate(num3))); + GUI.DrawTexture(new Rect(vector2.x, vector2.y, 1f, 1f), BaseContent.WhiteTex); + } + } + GUI.color = Color.white; } - else + if (drawPoints) { - GUI.color = curve.color; - float num3 = viewRect.x; - float num4 = rect.width / 1f; - float num5 = viewRect.width / num4; - while (num3 < viewRect.xMax) + for (int j = 0; j < curve.curve.PointsCount; j++) { - num3 += num5; - Vector2 vector2 = SimpleCurveDrawer.CurveToScreenCoordsInsideScreenRect(rect, viewRect, new Vector2(num3, curve.curve.Evaluate(num3))); - GUI.DrawTexture(new Rect(vector2.x, vector2.y, 1f, 1f), BaseContent.WhiteTex); + CurvePoint curvePoint3 = curve.curve[j]; + Vector2 screenPoint = SimpleCurveDrawer.CurveToScreenCoordsInsideScreenRect(rect, viewRect, curvePoint3.Loc); + SimpleCurveDrawer.DrawPoint(screenPoint); } } - GUI.color = Color.white; - } - if (drawPoints) - { - for (int j = 0; j < curve.curve.PointsCount; j++) + foreach (float debugInputValue in curve.curve.View.DebugInputValues) { - CurvePoint curvePoint3 = curve.curve[j]; - Vector2 screenPoint = SimpleCurveDrawer.CurveToScreenCoordsInsideScreenRect(rect, viewRect, curvePoint3.Loc); - SimpleCurveDrawer.DrawPoint(screenPoint); + float num6 = debugInputValue; + GUI.color = new Color(0f, 1f, 0f, 0.25f); + SimpleCurveDrawer.DrawInfiniteVerticalLine(rect, viewRect, num6); + float y = curve.curve.Evaluate(num6); + Vector2 curvePoint4 = new Vector2(num6, y); + Vector2 screenPoint2 = SimpleCurveDrawer.CurveToScreenCoordsInsideScreenRect(rect, viewRect, curvePoint4); + GUI.color = Color.green; + SimpleCurveDrawer.DrawPoint(screenPoint2); + GUI.color = Color.white; } + GUI.EndGroup(); } - foreach (float num6 in curve.curve.View.DebugInputValues) - { - GUI.color = new Color(0f, 1f, 0f, 0.25f); - SimpleCurveDrawer.DrawInfiniteVerticalLine(rect, viewRect, num6); - float y = curve.curve.Evaluate(num6); - Vector2 curvePoint4 = new Vector2(num6, y); - Vector2 screenPoint2 = SimpleCurveDrawer.CurveToScreenCoordsInsideScreenRect(rect, viewRect, curvePoint4); - GUI.color = Color.green; - SimpleCurveDrawer.DrawPoint(screenPoint2); - GUI.color = Color.white; - } - GUI.EndGroup(); } public static void DrawCurveMeasures(Rect rect, Rect viewRect, Rect graphRect, int xLabelsCount, int yLabelsCount) @@ -244,18 +258,18 @@ public static void DrawCurveMeasures(Rect rect, Rect viewRect, Rect graphRect, i GUI.BeginGroup(rect); Text.Anchor = TextAnchor.UpperCenter; string b = string.Empty; - for (int i = 0; i < xLabelsCount; i++) + for (int num = 0; num < xLabelsCount; num++) { - string text = ((vector3.x - vector2.x) / (float)xLabelsCount * (float)i + vector2.x).ToString("F0"); + string text = ((vector3.x - vector2.x) / (float)xLabelsCount * (float)num + vector2.x).ToString("F0"); if (!(text == b)) { b = text; - float num = graphRect.width / (float)xLabelsCount * (float)i + 60f; - float num2 = rect.height - 30f; + float num2 = (float)(graphRect.width / (float)xLabelsCount * (float)num + 60.0); + float num3 = (float)(rect.height - 30.0); GUI.color = color; - Widgets.DrawLineVertical(num, num2, 5f); + Widgets.DrawLineVertical(num2, num3, 5f); GUI.color = color2; - Rect rect2 = new Rect(num - 31f, num2 + 2f, 60f, 30f); + Rect rect2 = new Rect((float)(num2 - 31.0), (float)(num3 + 2.0), 60f, 30f); Text.Font = GameFont.Tiny; Widgets.Label(rect2, text); Text.Font = GameFont.Small; @@ -263,20 +277,20 @@ public static void DrawCurveMeasures(Rect rect, Rect viewRect, Rect graphRect, i } b = string.Empty; Text.Anchor = TextAnchor.UpperRight; - for (int j = 0; j < yLabelsCount; j++) + for (int num4 = 0; num4 < yLabelsCount; num4++) { - string text2 = ((vector.y - vector2.y) / (float)yLabelsCount * (float)j + vector2.y).ToString("F0"); + string text2 = ((vector.y - vector2.y) / (float)yLabelsCount * (float)num4 + vector2.y).ToString("F0"); if (!(text2 == b)) { b = text2; - float num3 = 60f; - float num4 = graphRect.height / (float)yLabelsCount * (float)(yLabelsCount - j); + float num5 = 60f; + float num6 = graphRect.height / (float)yLabelsCount * (float)(yLabelsCount - num4); GUI.color = color; - Widgets.DrawLineHorizontal(num3 - 5f, num4, 5f + graphRect.width); + Widgets.DrawLineHorizontal((float)(num5 - 5.0), num6, (float)(5.0 + graphRect.width)); GUI.color = color2; - Rect rect3 = new Rect(num3 - 60f, num4 - 10f, 55f, 20f); + Rect rect3 = new Rect((float)(num5 - 60.0), (float)(num6 - 10.0), 55f, 20f); Text.Font = GameFont.Tiny; - num4 += 2f; + num6 = (float)(num6 + 2.0); Widgets.Label(rect3, text2); Text.Font = GameFont.Small; } @@ -293,133 +307,140 @@ public static void DrawCurvesLegend(Rect rect, List curves) GUI.BeginGroup(rect); float num = 0f; float num2 = 0f; - int num3 = (int)(rect.width / 140f); + int num3 = (int)(rect.width / 140.0); int num4 = 0; - foreach (SimpleCurveDrawInfo current in curves) + List.Enumerator enumerator = curves.GetEnumerator(); + try { - GUI.color = current.color; - GUI.DrawTexture(new Rect(num, num2 + 2f, 15f, 15f), BaseContent.WhiteTex); - GUI.color = Color.white; - num += 20f; - if (current.label != null) - { - Widgets.Label(new Rect(num, num2, 140f, 20f), current.label); - } - num4++; - if (num4 == num3) - { - num4 = 0; - num = 0f; - num2 += 20f; - } - else + while (enumerator.MoveNext()) { - num += 140f; + SimpleCurveDrawInfo current = enumerator.Current; + GUI.color = current.color; + GUI.DrawTexture(new Rect(num, (float)(num2 + 2.0), 15f, 15f), BaseContent.WhiteTex); + GUI.color = Color.white; + num = (float)(num + 20.0); + if (current.label != null) + { + Widgets.Label(new Rect(num, num2, 140f, 20f), current.label); + } + num4++; + if (num4 == num3) + { + num4 = 0; + num = 0f; + num2 = (float)(num2 + 20.0); + } + else + { + num = (float)(num + 140.0); + } } } + finally + { + ((IDisposable)(object)enumerator).Dispose(); + } GUI.EndGroup(); GUI.color = Color.white; } public static void DrawCurveMousePoint(List curves, Rect screenRect, Rect viewRect, string labelX, string labelY) { - if (curves.Count == 0) - { - return; - } - if (!Mouse.IsOver(screenRect)) - { - return; - } - GUI.BeginGroup(screenRect); - Vector2 mousePosition = Event.current.mousePosition; - Vector2 vector = default(Vector2); - Vector2 vector2 = default(Vector2); - bool flag = false; - foreach (SimpleCurveDrawInfo current in curves) - { - if (current.curve.AllPoints.Any()) + if (curves.Count != 0 && Mouse.IsOver(screenRect)) + { + GUI.BeginGroup(screenRect); + Vector2 mousePosition = Event.current.mousePosition; + Vector2 vector = default(Vector2); + Vector2 vector2 = default(Vector2); + bool flag = false; + List.Enumerator enumerator = curves.GetEnumerator(); + try { - Vector2 vector3 = SimpleCurveDrawer.ScreenToCurveCoords(screenRect, viewRect, mousePosition); - vector3.y = current.curve.Evaluate(vector3.x); - Vector2 vector4 = SimpleCurveDrawer.CurveToScreenCoordsInsideScreenRect(screenRect, viewRect, vector3); - if (!flag || Vector2.Distance(vector4, mousePosition) < Vector2.Distance(vector2, mousePosition)) + while (enumerator.MoveNext()) { - flag = true; - vector = vector3; - vector2 = vector4; + SimpleCurveDrawInfo current = enumerator.Current; + if (current.curve.AllPoints.Any()) + { + Vector2 vector3 = SimpleCurveDrawer.ScreenToCurveCoords(screenRect, viewRect, mousePosition); + vector3.y = current.curve.Evaluate(vector3.x); + Vector2 vector4 = SimpleCurveDrawer.CurveToScreenCoordsInsideScreenRect(screenRect, viewRect, vector3); + if (!flag || Vector2.Distance(vector4, mousePosition) < Vector2.Distance(vector2, mousePosition)) + { + flag = true; + vector = vector3; + vector2 = vector4; + } + } } } - } - SimpleCurveDrawer.DrawPoint(vector2); - Rect rect = new Rect(vector2.x, vector2.y, 100f, 60f); - Text.Anchor = TextAnchor.UpperLeft; - if (rect.x + rect.width > screenRect.width) - { - rect.x -= rect.width; - Text.Anchor = TextAnchor.UpperRight; - } - if (rect.y + rect.height > screenRect.height) - { - rect.y -= rect.height; - if (Text.Anchor == TextAnchor.UpperLeft) + finally { - Text.Anchor = TextAnchor.LowerLeft; + ((IDisposable)(object)enumerator).Dispose(); } - else + SimpleCurveDrawer.DrawPoint(vector2); + Rect rect = new Rect(vector2.x, vector2.y, 100f, 60f); + Text.Anchor = TextAnchor.UpperLeft; + if (rect.x + rect.width > screenRect.width) { - Text.Anchor = TextAnchor.LowerRight; + rect.x -= rect.width; + Text.Anchor = TextAnchor.UpperRight; } + if (rect.y + rect.height > screenRect.height) + { + rect.y -= rect.height; + if (Text.Anchor == TextAnchor.UpperLeft) + { + Text.Anchor = TextAnchor.LowerLeft; + } + else + { + Text.Anchor = TextAnchor.LowerRight; + } + } + Widgets.Label(rect, labelX + ": " + vector.x.ToString("0.##") + "\n" + labelY + ": " + vector.y.ToString("0.##")); + Text.Anchor = TextAnchor.UpperLeft; + GUI.EndGroup(); } - Widgets.Label(rect, string.Concat(new string[] - { - labelX, - ": ", - vector.x.ToString("0.##"), - "\n", - labelY, - ": ", - vector.y.ToString("0.##") - })); - Text.Anchor = TextAnchor.UpperLeft; - GUI.EndGroup(); } public static void DrawCurveMarks(Rect rect, Rect viewRect, List marks) { float x = viewRect.x; float num = viewRect.x + viewRect.width; - float num2 = rect.y + 5f; - float num3 = rect.yMax - 5f; - for (int i = 0; i < marks.Count; i++) + float num2 = (float)(rect.y + 5.0); + float num3 = (float)(rect.yMax - 5.0); + int num4; + for (num4 = 0; num4 < marks.Count; num4++) { - CurveMark curveMark = marks[i]; + CurveMark curveMark = marks[num4]; if (curveMark.X >= x && curveMark.X <= num) { GUI.color = curveMark.Color; - Vector2 screenPoint = new Vector2(rect.x + (curveMark.X - x) / (num - x) * rect.width, (i % 2 != 0) ? num3 : num2); + Vector2 screenPoint = new Vector2(rect.x + (curveMark.X - x) / (num - x) * rect.width, (num4 % 2 != 0) ? num3 : num2); SimpleCurveDrawer.DrawPoint(screenPoint); - TooltipHandler.TipRegion(new Rect(screenPoint.x - 5f, screenPoint.y - 5f, 10f, 10f), new TipSignal(curveMark.Message)); + TooltipHandler.TipRegion(new Rect((float)(screenPoint.x - 5.0), (float)(screenPoint.y - 5.0), 10f, 10f), new TipSignal(curveMark.Message)); } - i++; + num4++; } GUI.color = Color.white; } private static void DrawPoint(Vector2 screenPoint) { - Rect position = new Rect(screenPoint.x - 5f, screenPoint.y - 5f, 10f, 10f); + Rect position = new Rect((float)(screenPoint.x - 5.0), (float)(screenPoint.y - 5.0), 10f, 10f); GUI.DrawTexture(position, SimpleCurveDrawer.CurvePoint); } private static void DrawInfiniteVerticalLine(Rect rect, Rect viewRect, float curveX) { - Widgets.DrawLineVertical(SimpleCurveDrawer.CurveToScreenCoordsInsideScreenRect(rect, viewRect, new Vector2(curveX, 0f)).x, -999f, 9999f); + Vector2 vector = SimpleCurveDrawer.CurveToScreenCoordsInsideScreenRect(rect, viewRect, new Vector2(curveX, 0f)); + Widgets.DrawLineVertical(vector.x, -999f, 9999f); } private static void DrawInfiniteHorizontalLine(Rect rect, Rect viewRect, float curveY) { - Widgets.DrawLineHorizontal(-999f, SimpleCurveDrawer.CurveToScreenCoordsInsideScreenRect(rect, viewRect, new Vector2(0f, curveY)).y, 9999f); + Vector2 vector = SimpleCurveDrawer.CurveToScreenCoordsInsideScreenRect(rect, viewRect, new Vector2(0f, curveY)); + Widgets.DrawLineHorizontal(-999f, vector.y, 9999f); } public static Vector2 CurveToScreenCoordsInsideScreenRect(Rect rect, Rect viewRect, Vector2 curvePoint) @@ -448,13 +469,13 @@ public static void DrawGraphBackgroundLines(Rect rect, Rect viewRect) { GUI.BeginGroup(rect); float num = 0.01f; - while (viewRect.width / (num * 10f) > 4f) + while (viewRect.width / (num * 10.0) > 4.0) { - num *= 10f; + num = (float)(num * 10.0); } for (float num2 = (float)Mathf.FloorToInt(viewRect.x / num) * num; num2 < viewRect.xMax; num2 += num) { - if (Mathf.Abs(num2 % (10f * num)) < 0.001f) + if (Mathf.Abs((float)(num2 % (10.0 * num))) < 0.0010000000474974513) { GUI.color = SimpleCurveDrawer.MajorLineColor; } @@ -465,13 +486,13 @@ public static void DrawGraphBackgroundLines(Rect rect, Rect viewRect) SimpleCurveDrawer.DrawInfiniteVerticalLine(rect, viewRect, num2); } float num3 = 0.01f; - while (viewRect.height / (num3 * 10f) > 4f) + while (viewRect.height / (num3 * 10.0) > 4.0) { - num3 *= 10f; + num3 = (float)(num3 * 10.0); } for (float num4 = (float)Mathf.FloorToInt(viewRect.y / num3) * num3; num4 < viewRect.yMax; num4 += num3) { - if (Mathf.Abs(num4 % (10f * num3)) < 0.001f) + if (Mathf.Abs((float)(num4 % (10.0 * num3))) < 0.0010000000474974513) { GUI.color = SimpleCurveDrawer.MajorLineColor; } diff --git a/Assembly-CSharp/Verse/SimpleCurveDrawerStyle.cs b/Assembly-CSharp/Verse/SimpleCurveDrawerStyle.cs index d3e582662..bd9e4377f 100644 --- a/Assembly-CSharp/Verse/SimpleCurveDrawerStyle.cs +++ b/Assembly-CSharp/Verse/SimpleCurveDrawerStyle.cs @@ -1,4 +1,3 @@ -using System; using UnityEngine; namespace Verse diff --git a/Assembly-CSharp/Verse/SimpleCurveView.cs b/Assembly-CSharp/Verse/SimpleCurveView.cs index c84ccf071..233d27299 100644 --- a/Assembly-CSharp/Verse/SimpleCurveView.cs +++ b/Assembly-CSharp/Verse/SimpleCurveView.cs @@ -19,11 +19,22 @@ public IEnumerable DebugInputValues { get { - SimpleCurveView.<>c__Iterator23B <>c__Iterator23B = new SimpleCurveView.<>c__Iterator23B(); - <>c__Iterator23B.<>f__this = this; - SimpleCurveView.<>c__Iterator23B expr_0E = <>c__Iterator23B; - expr_0E.$PC = -2; - return expr_0E; + if (this.debugInputValues != null) + { + Dictionary.ValueCollection.Enumerator enumerator = this.debugInputValues.Values.GetEnumerator(); + try + { + while (enumerator.MoveNext()) + { + float val = enumerator.Current; + yield return val; + } + } + finally + { + ((IDisposable)(object)enumerator).Dispose(); + } + } } } @@ -42,41 +53,55 @@ public void ClearDebugInputFrom(object key) public void SetViewRectAround(SimpleCurve curve) { - if (!curve.AllPoints.Any()) + if (!curve.AllPoints.Any()) { this.rect = SimpleCurveView.identityRect; - return; } - this.rect.xMin = (from pt in curve.AllPoints - select pt.Loc.x).Min(); - this.rect.xMax = (from pt in curve.AllPoints - select pt.Loc.x).Max(); - this.rect.yMin = (from pt in curve.AllPoints - select pt.Loc.y).Min(); - this.rect.yMax = (from pt in curve.AllPoints - select pt.Loc.y).Max(); - if (Mathf.Approximately(this.rect.width, 0f)) + else { - this.rect.width = this.rect.xMin * 2f; + this.rect.xMin = curve.AllPoints.Select((Func)delegate(CurvePoint pt) + { + Vector2 loc4 = pt.Loc; + return loc4.x; + }).Min(); + this.rect.xMax = curve.AllPoints.Select((Func)delegate(CurvePoint pt) + { + Vector2 loc3 = pt.Loc; + return loc3.x; + }).Max(); + this.rect.yMin = curve.AllPoints.Select((Func)delegate(CurvePoint pt) + { + Vector2 loc2 = pt.Loc; + return loc2.y; + }).Min(); + this.rect.yMax = curve.AllPoints.Select((Func)delegate(CurvePoint pt) + { + Vector2 loc = pt.Loc; + return loc.y; + }).Max(); + if (Mathf.Approximately(this.rect.width, 0f)) + { + this.rect.width = (float)(this.rect.xMin * 2.0); + } + if (Mathf.Approximately(this.rect.height, 0f)) + { + this.rect.height = (float)(this.rect.yMin * 2.0); + } + if (Mathf.Approximately(this.rect.width, 0f)) + { + this.rect.width = 1f; + } + if (Mathf.Approximately(this.rect.height, 0f)) + { + this.rect.height = 1f; + } + float width = this.rect.width; + float height = this.rect.height; + this.rect.xMin -= (float)(width * 0.10000000149011612); + this.rect.xMax += (float)(width * 0.10000000149011612); + this.rect.yMin -= (float)(height * 0.10000000149011612); + this.rect.yMax += (float)(height * 0.10000000149011612); } - if (Mathf.Approximately(this.rect.height, 0f)) - { - this.rect.height = this.rect.yMin * 2f; - } - if (Mathf.Approximately(this.rect.width, 0f)) - { - this.rect.width = 1f; - } - if (Mathf.Approximately(this.rect.height, 0f)) - { - this.rect.height = 1f; - } - float width = this.rect.width; - float height = this.rect.height; - this.rect.xMin = this.rect.xMin - width * 0.1f; - this.rect.xMax = this.rect.xMax + width * 0.1f; - this.rect.yMin = this.rect.yMin - height * 0.1f; - this.rect.yMax = this.rect.yMax + height * 0.1f; } } } diff --git a/Assembly-CSharp/Verse/SimplePool.cs b/Assembly-CSharp/Verse/SimplePool.cs index d0d1a30d0..cff9d6eb7 100644 --- a/Assembly-CSharp/Verse/SimplePool.cs +++ b/Assembly-CSharp/Verse/SimplePool.cs @@ -1,4 +1,3 @@ -using System; using System.Collections.Generic; namespace Verse @@ -11,7 +10,7 @@ public static T Get() { if (SimplePool.freeItems.Count == 0) { - return (default(T) == null) ? Activator.CreateInstance() : default(T); + return new T(); } T result = SimplePool.freeItems[SimplePool.freeItems.Count - 1]; SimplePool.freeItems.RemoveAt(SimplePool.freeItems.Count - 1); diff --git a/Assembly-CSharp/Verse/SkillGain.cs b/Assembly-CSharp/Verse/SkillGain.cs index 90f981978..576507666 100644 --- a/Assembly-CSharp/Verse/SkillGain.cs +++ b/Assembly-CSharp/Verse/SkillGain.cs @@ -1,5 +1,4 @@ using RimWorld; -using System; using System.Xml; namespace Verse @@ -25,10 +24,12 @@ public void LoadDataFromXmlCustom(XmlNode xmlRoot) if (xmlRoot.ChildNodes.Count != 1) { Log.Error("Misconfigured SkillGain: " + xmlRoot.OuterXml); - return; } - DirectXmlCrossRefLoader.RegisterObjectWantsCrossRef(this, "skill", xmlRoot.Name); - this.xp = (int)ParseHelper.FromString(xmlRoot.FirstChild.Value, typeof(int)); + else + { + DirectXmlCrossRefLoader.RegisterObjectWantsCrossRef(this, "skill", xmlRoot.Name); + this.xp = (int)ParseHelper.FromString(xmlRoot.FirstChild.Value, typeof(int)); + } } } } diff --git a/Assembly-CSharp/Verse/SkillRequirement.cs b/Assembly-CSharp/Verse/SkillRequirement.cs index ef78536f9..357d44bf0 100644 --- a/Assembly-CSharp/Verse/SkillRequirement.cs +++ b/Assembly-CSharp/Verse/SkillRequirement.cs @@ -1,5 +1,4 @@ using RimWorld; -using System; namespace Verse { @@ -11,7 +10,11 @@ public class SkillRequirement public bool PawnSatisfies(Pawn pawn) { - return pawn.skills != null && pawn.skills.GetSkill(this.skill).Level >= this.minLevel; + if (pawn.skills == null) + { + return false; + } + return pawn.skills.GetSkill(this.skill).Level >= this.minLevel; } } } diff --git a/Assembly-CSharp/Verse/SkyColorSet.cs b/Assembly-CSharp/Verse/SkyColorSet.cs index ef5125544..ebe20232c 100644 --- a/Assembly-CSharp/Verse/SkyColorSet.cs +++ b/Assembly-CSharp/Verse/SkyColorSet.cs @@ -1,4 +1,3 @@ -using System; using UnityEngine; namespace Verse @@ -34,18 +33,7 @@ public static SkyColorSet Lerp(SkyColorSet A, SkyColorSet B, float t) public override string ToString() { - return string.Concat(new object[] - { - "(sky=", - this.sky, - ", shadow=", - this.shadow, - ", overlay=", - this.overlay, - ", sat=", - this.saturation, - ")" - }); + return "(sky=" + this.sky + ", shadow=" + this.shadow + ", overlay=" + this.overlay + ", sat=" + this.saturation + ")"; } } } diff --git a/Assembly-CSharp/Verse/SkyManager.cs b/Assembly-CSharp/Verse/SkyManager.cs index 925905421..fec895582 100644 --- a/Assembly-CSharp/Verse/SkyManager.cs +++ b/Assembly-CSharp/Verse/SkyManager.cs @@ -1,5 +1,4 @@ using RimWorld; -using System; using System.Collections.Generic; using System.Text; using UnityEngine; @@ -18,7 +17,7 @@ public class SkyManager private List> tempOverlays = new List>(); - private static readonly Color FogOfWarBaseColor = new Color32(77, 69, 66, 255); + private static readonly Color FogOfWarBaseColor = new Color32((byte)77, (byte)69, (byte)66, (byte)255); public float CurSkyGlow { @@ -56,7 +55,7 @@ public void SkyManagerUpdate() this.SetSunShadowVector(GenCelestial.CurShadowVector(this.map)); color2 = Color.Lerp(Color.white, color2, GenCelestial.CurShadowStrength(this.map)); } - Shader.SetGlobalFloat("_LightsourceShineSizeReduction", 20f * (1f / curSky.lightsourceShineSize)); + Shader.SetGlobalFloat("_LightsourceShineSizeReduction", (float)(20.0 * (1.0 / curSky.lightsourceShineSize))); Shader.SetGlobalFloat("_LightsourceShineIntensity", curSky.lightsourceShineIntensity); MatBases.SunShadow.color = color2; this.UpdateOverlays(curSky); @@ -79,7 +78,7 @@ private void UpdateOverlays(SkyTarget curSky) List overlays2 = this.map.weatherManager.lastWeather.Worker.overlays; for (int j = 0; j < overlays2.Count; j++) { - this.AddTempOverlay(new Pair(overlays2[j], 1f - this.map.weatherManager.TransitionLerpFactor)); + this.AddTempOverlay(new Pair(overlays2[j], (float)(1.0 - this.map.weatherManager.TransitionLerpFactor))); } for (int k = 0; k < this.map.gameConditionManager.ActiveConditions.Count; k++) { @@ -125,7 +124,7 @@ private SkyTarget CurrentSkyTarget() SkyTarget a = this.map.weatherManager.lastWeather.Worker.CurSkyTarget(this.map); SkyTarget skyTarget = SkyTarget.Lerp(a, b, this.map.weatherManager.TransitionLerpFactor); float num = this.map.gameConditionManager.AggregateSkyTargetLerpFactor(); - if (num > 0.0001f) + if (num > 9.9999997473787516E-05) { SkyTarget value = this.map.gameConditionManager.AggregateSkyTarget().Value; skyTarget = SkyTarget.LerpDarken(skyTarget, value, num); diff --git a/Assembly-CSharp/Verse/SkyOverlay.cs b/Assembly-CSharp/Verse/SkyOverlay.cs index e27813dac..321f200f8 100644 --- a/Assembly-CSharp/Verse/SkyOverlay.cs +++ b/Assembly-CSharp/Verse/SkyOverlay.cs @@ -21,11 +21,11 @@ public Color OverlayColor { set { - if (this.worldOverlayMat != null) + if ((UnityEngine.Object)this.worldOverlayMat != (UnityEngine.Object)null) { this.worldOverlayMat.color = value; } - if (this.screenOverlayMat != null) + if ((UnityEngine.Object)this.screenOverlayMat != (UnityEngine.Object)null) { this.screenOverlayMat.color = value; } @@ -34,7 +34,7 @@ public Color OverlayColor public SkyOverlay() { - LongEventHandler.ExecuteWhenFinished(delegate + LongEventHandler.ExecuteWhenFinished((Action)delegate { this.OverlayColor = Color.clear; }); @@ -42,29 +42,35 @@ public SkyOverlay() public virtual void TickOverlay(Map map) { - if (this.worldOverlayMat != null) + if ((UnityEngine.Object)this.worldOverlayMat != (UnityEngine.Object)null) { - this.worldOverlayMat.SetTextureOffset("_MainTex", (float)Find.TickManager.TicksGame * this.worldPanDir1 * -1f * this.worldOverlayPanSpeed1 * this.worldOverlayMat.GetTextureScale("_MainTex").x); + Material obj = this.worldOverlayMat; + Vector2 a = (float)Find.TickManager.TicksGame * this.worldPanDir1 * -1f * this.worldOverlayPanSpeed1; + Vector2 textureScale = this.worldOverlayMat.GetTextureScale("_MainTex"); + obj.SetTextureOffset("_MainTex", a * textureScale.x); if (this.worldOverlayMat.HasProperty("_MainTex2")) { - this.worldOverlayMat.SetTextureOffset("_MainTex2", (float)Find.TickManager.TicksGame * this.worldPanDir2 * -1f * this.worldOverlayPanSpeed2 * this.worldOverlayMat.GetTextureScale("_MainTex2").x); + Material obj2 = this.worldOverlayMat; + Vector2 a2 = (float)Find.TickManager.TicksGame * this.worldPanDir2 * -1f * this.worldOverlayPanSpeed2; + Vector2 textureScale2 = this.worldOverlayMat.GetTextureScale("_MainTex2"); + obj2.SetTextureOffset("_MainTex2", a2 * textureScale2.x); } } } public void DrawOverlay(Map map) { - if (this.worldOverlayMat != null) + if ((UnityEngine.Object)this.worldOverlayMat != (UnityEngine.Object)null) { Vector3 position = map.Center.ToVector3ShiftedWithAltitude(AltitudeLayer.Weather); Graphics.DrawMesh(MeshPool.wholeMapPlane, position, Quaternion.identity, this.worldOverlayMat, 0); } - if (this.screenOverlayMat != null) + if ((UnityEngine.Object)this.screenOverlayMat != (UnityEngine.Object)null) { - float num = Find.Camera.orthographicSize * 2f; + float num = (float)(Find.Camera.orthographicSize * 2.0); Vector3 s = new Vector3(num * Find.Camera.aspect, 1f, num); Vector3 position2 = Find.Camera.transform.position; - position2.y = Altitudes.AltitudeFor(AltitudeLayer.Weather) + 0.046875f; + position2.y = (float)(Altitudes.AltitudeFor(AltitudeLayer.Weather) + 0.046875); Matrix4x4 matrix = default(Matrix4x4); matrix.SetTRS(position2, Quaternion.identity, s); Graphics.DrawMesh(MeshPool.plane10, matrix, this.screenOverlayMat, 0); @@ -73,11 +79,11 @@ public void DrawOverlay(Map map) public override string ToString() { - if (this.worldOverlayMat != null) + if ((UnityEngine.Object)this.worldOverlayMat != (UnityEngine.Object)null) { return this.worldOverlayMat.name; } - if (this.screenOverlayMat != null) + if ((UnityEngine.Object)this.screenOverlayMat != (UnityEngine.Object)null) { return this.screenOverlayMat.name; } diff --git a/Assembly-CSharp/Verse/SkyTarget.cs b/Assembly-CSharp/Verse/SkyTarget.cs index 3d9a03ba6..527a3875b 100644 --- a/Assembly-CSharp/Verse/SkyTarget.cs +++ b/Assembly-CSharp/Verse/SkyTarget.cs @@ -1,4 +1,3 @@ -using System; using UnityEngine; namespace Verse @@ -45,18 +44,7 @@ public static SkyTarget LerpDarken(SkyTarget A, SkyTarget B, float t) public override string ToString() { - return string.Concat(new string[] - { - "(glow=", - this.glow.ToString("F2"), - ", colors=", - this.colors.ToString(), - ", lightsourceShineSize=", - this.lightsourceShineSize.ToString(), - ", lightsourceShineIntensity=", - this.lightsourceShineIntensity.ToString(), - ")" - }); + return "(glow=" + this.glow.ToString("F2") + ", colors=" + this.colors.ToString() + ", lightsourceShineSize=" + this.lightsourceShineSize.ToString() + ", lightsourceShineIntensity=" + this.lightsourceShineIntensity.ToString() + ")"; } } } diff --git a/Assembly-CSharp/Verse/SnowCategory.cs b/Assembly-CSharp/Verse/SnowCategory.cs index 3d030f6a0..201d9e9cf 100644 --- a/Assembly-CSharp/Verse/SnowCategory.cs +++ b/Assembly-CSharp/Verse/SnowCategory.cs @@ -1,13 +1,11 @@ -using System; - namespace Verse { public enum SnowCategory : byte { - None, - Dusting, - Thin, - Medium, - Thick + None = 0, + Dusting = 1, + Thin = 2, + Medium = 3, + Thick = 4 } } diff --git a/Assembly-CSharp/Verse/SnowGrid.cs b/Assembly-CSharp/Verse/SnowGrid.cs index ee668830c..2faaabac8 100644 --- a/Assembly-CSharp/Verse/SnowGrid.cs +++ b/Assembly-CSharp/Verse/SnowGrid.cs @@ -37,20 +37,21 @@ public SnowGrid(Map map) public void ExposeData() { - string compressedString = null; + string compressedString = (string)null; if (Scribe.mode == LoadSaveMode.Saving) { - compressedString = GridSaveUtility.CompressedStringForShortGrid((IntVec3 c) => SnowGrid.SnowFloatToShort(this.GetDepth(c)), this.map); + compressedString = GridSaveUtility.CompressedStringForShortGrid((Func)((IntVec3 c) => SnowGrid.SnowFloatToShort(this.GetDepth(c))), this.map); } - Scribe_Values.Look(ref compressedString, "depthGrid", null, false); + Scribe_Values.Look(ref compressedString, "depthGrid", (string)null, false); if (Scribe.mode == LoadSaveMode.LoadingVars) { this.totalDepth = 0.0; - foreach (GridSaveUtility.LoadedGridShort current in GridSaveUtility.LoadedUShortGrid(compressedString, this.map)) + foreach (GridSaveUtility.LoadedGridShort item in GridSaveUtility.LoadedUShortGrid(compressedString, this.map)) { + GridSaveUtility.LoadedGridShort current = item; ushort val = current.val; this.depthGrid[this.map.cellIndices.CellToIndex(current.cell)] = SnowGrid.SnowShortToFloat(val); - this.totalDepth += (double)val; + this.totalDepth += (double)(int)val; } } } @@ -58,13 +59,13 @@ public void ExposeData() private static ushort SnowFloatToShort(float depth) { depth = Mathf.Clamp(depth, 0f, 1f); - depth *= 65535f; + depth = (float)(depth * 65535.0); return (ushort)Mathf.RoundToInt(depth); } private static float SnowShortToFloat(ushort depth) { - return (float)depth / 65535f; + return (float)((float)(int)depth / 65535.0); } private bool CanHaveSnow(int ind) @@ -75,39 +76,45 @@ private bool CanHaveSnow(int ind) return false; } TerrainDef terrainDef = this.map.terrainGrid.TerrainAt(ind); - return terrainDef == null || terrainDef.holdSnow; + if (terrainDef != null && !terrainDef.holdSnow) + { + return false; + } + return true; } public static bool CanCoexistWithSnow(ThingDef def) { - return def.category != ThingCategory.Building || def.Fillage != FillCategory.Full; + if (def.category == ThingCategory.Building && def.Fillage == FillCategory.Full) + { + return false; + } + return true; } public void AddDepth(IntVec3 c, float depthToAdd) { int num = this.map.cellIndices.CellToIndex(c); float num2 = this.depthGrid[num]; - if (num2 <= 0f && depthToAdd < 0f) - { + if (num2 <= 0.0 && depthToAdd < 0.0) return; - } - if (num2 >= 0.999f && depthToAdd > 1f) - { + if (num2 >= 0.99900001287460327 && depthToAdd > 1.0) return; - } if (!this.CanHaveSnow(num)) { this.depthGrid[num] = 0f; - return; } - float num3 = num2 + depthToAdd; - num3 = Mathf.Clamp(num3, 0f, 1f); - float num4 = num3 - num2; - this.totalDepth += (double)num4; - if (Mathf.Abs(num4) > 0.0001f) + else { - this.depthGrid[num] = num3; - this.CheckVisualOrPathCostChange(c, num2, num3); + float value = num2 + depthToAdd; + value = Mathf.Clamp(value, 0f, 1f); + float num3 = value - num2; + this.totalDepth += (double)num3; + if (Mathf.Abs(num3) > 9.9999997473787516E-05) + { + this.depthGrid[num] = value; + this.CheckVisualOrPathCostChange(c, num2, value); + } } } @@ -117,26 +124,28 @@ public void SetDepth(IntVec3 c, float newDepth) if (!this.CanHaveSnow(num)) { this.depthGrid[num] = 0f; - return; } - newDepth = Mathf.Clamp(newDepth, 0f, 1f); - float num2 = this.depthGrid[num]; - this.depthGrid[num] = newDepth; - float num3 = newDepth - num2; - this.totalDepth += (double)num3; - this.CheckVisualOrPathCostChange(c, num2, newDepth); + else + { + newDepth = Mathf.Clamp(newDepth, 0f, 1f); + float num2 = this.depthGrid[num]; + this.depthGrid[num] = newDepth; + float num3 = newDepth - num2; + this.totalDepth += (double)num3; + this.CheckVisualOrPathCostChange(c, num2, newDepth); + } } private void CheckVisualOrPathCostChange(IntVec3 c, float oldDepth, float newDepth) { if (!Mathf.Approximately(oldDepth, newDepth)) { - if (Mathf.Abs(oldDepth - newDepth) > 0.15f || Rand.Value < 0.0125f) + if (Mathf.Abs(oldDepth - newDepth) > 0.15000000596046448 || Rand.Value < 0.012500000186264515) { this.map.mapDrawer.MapMeshDirty(c, MapMeshFlag.Snow, true, false); this.map.mapDrawer.MapMeshDirty(c, MapMeshFlag.Things, true, false); } - else if (newDepth == 0f) + else if (newDepth == 0.0) { this.map.mapDrawer.MapMeshDirty(c, MapMeshFlag.Snow, true, false); } diff --git a/Assembly-CSharp/Verse/SnowUtility.cs b/Assembly-CSharp/Verse/SnowUtility.cs index 65814ab47..2451c1119 100644 --- a/Assembly-CSharp/Verse/SnowUtility.cs +++ b/Assembly-CSharp/Verse/SnowUtility.cs @@ -1,24 +1,22 @@ -using System; - namespace Verse { public static class SnowUtility { public static SnowCategory GetSnowCategory(float snowDepth) { - if (snowDepth < 0.03f) + if (snowDepth < 0.029999999329447746) { return SnowCategory.None; } - if (snowDepth < 0.25f) + if (snowDepth < 0.25) { return SnowCategory.Dusting; } - if (snowDepth < 0.5f) + if (snowDepth < 0.5) { return SnowCategory.Thin; } - if (snowDepth < 0.75f) + if (snowDepth < 0.75) { return SnowCategory.Medium; } @@ -30,18 +28,30 @@ public static string GetDescription(SnowCategory category) switch (category) { case SnowCategory.None: + { return "SnowNone".Translate(); + } case SnowCategory.Dusting: + { return "SnowDusting".Translate(); + } case SnowCategory.Thin: + { return "SnowThin".Translate(); + } case SnowCategory.Medium: + { return "SnowMedium".Translate(); + } case SnowCategory.Thick: + { return "SnowThick".Translate(); + } default: + { return "Unknown snow"; } + } } public static int MovementTicksAddOn(SnowCategory category) @@ -49,31 +59,43 @@ public static int MovementTicksAddOn(SnowCategory category) switch (category) { case SnowCategory.None: + { return 0; + } case SnowCategory.Dusting: + { return 0; + } case SnowCategory.Thin: + { return 4; + } case SnowCategory.Medium: + { return 8; + } case SnowCategory.Thick: + { return 12; + } default: + { return 0; } + } } public static void AddSnowRadial(IntVec3 center, Map map, float radius, float depth) { int num = GenRadial.NumCellsInRadius(radius); - for (int i = 0; i < num; i++) + for (int num2 = 0; num2 < num; num2++) { - IntVec3 intVec = center + GenRadial.RadialPattern[i]; + IntVec3 intVec = center + GenRadial.RadialPattern[num2]; if (intVec.InBounds(map)) { float lengthHorizontal = (center - intVec).LengthHorizontal; - float num2 = 1f - lengthHorizontal / radius; - map.snowGrid.AddDepth(intVec, num2 * depth); + float num3 = (float)(1.0 - lengthHorizontal / radius); + map.snowGrid.AddDepth(intVec, num3 * depth); } } } diff --git a/Assembly-CSharp/Verse/SolidColorMaterials.cs b/Assembly-CSharp/Verse/SolidColorMaterials.cs index 84f9ed3b3..c57d09010 100644 --- a/Assembly-CSharp/Verse/SolidColorMaterials.cs +++ b/Assembly-CSharp/Verse/SolidColorMaterials.cs @@ -1,4 +1,3 @@ -using System; using System.Collections.Generic; using UnityEngine; @@ -20,7 +19,7 @@ public static int SimpleColorMatCount public static Material SimpleSolidColorMaterial(Color col, bool careAboutVertexColors = false) { - Material material; + Material material = default(Material); if (careAboutVertexColors) { if (!SolidColorMaterials.simpleColorAndVertexColorMats.TryGetValue(col, out material)) @@ -44,17 +43,10 @@ public static Material NewSolidColorMaterial(Color col, Shader shader) Log.Error("Tried to create a material from a different thread."); return null; } - return new Material(shader) - { - color = col, - name = string.Concat(new object[] - { - "SolidColorMat-", - shader.name, - "-", - col - }) - }; + Material material = new Material(shader); + material.color = col; + material.name = "SolidColorMat-" + shader.name + "-" + col; + return material; } public static Texture2D NewSolidColorTexture(float r, float g, float b, float a) diff --git a/Assembly-CSharp/Verse/SongDef.cs b/Assembly-CSharp/Verse/SongDef.cs index 35704be26..c5f3ccf75 100644 --- a/Assembly-CSharp/Verse/SongDef.cs +++ b/Assembly-CSharp/Verse/SongDef.cs @@ -28,21 +28,17 @@ public class SongDef : Def public override void PostLoad() { base.PostLoad(); - if (this.defName == "UnnamedDef") + if (base.defName == "UnnamedDef") { - string[] array = this.clipPath.Split(new char[] - { - '/', - '\\' - }); - this.defName = array[array.Length - 1]; + string[] array = this.clipPath.Split('/', '\\'); + base.defName = array[array.Length - 1]; } } public override void ResolveReferences() { base.ResolveReferences(); - LongEventHandler.ExecuteWhenFinished(delegate + LongEventHandler.ExecuteWhenFinished((Action)delegate { this.clip = ContentFinder.Get(this.clipPath, true); }); diff --git a/Assembly-CSharp/Verse/SoundDef.cs b/Assembly-CSharp/Verse/SoundDef.cs index e5ecfd8a6..ae3c037d9 100644 --- a/Assembly-CSharp/Verse/SoundDef.cs +++ b/Assembly-CSharp/Verse/SoundDef.cs @@ -1,41 +1,50 @@ using RimWorld; -using System; using System.Collections.Generic; -using System.Diagnostics; using Verse.Sound; namespace Verse { public class SoundDef : Def { - [DefaultValue(false), Description("If checked, this sound is a sustainer.\n\nSustainers are used for sounds with a defined beginning and end (as opposed to OneShots, which just fire at a given instant).\n\nThis value must match what the game expects from the SubSoundDef with this name.")] + [Description("If checked, this sound is a sustainer.\n\nSustainers are used for sounds with a defined beginning and end (as opposed to OneShots, which just fire at a given instant).\n\nThis value must match what the game expects from the SubSoundDef with this name.")] + [DefaultValue(false)] public bool sustain; - [DefaultValue(SoundContext.Any), Description("When the sound is allowed to play: only when the map view is active, only when the world view is active, or always (map + world + main menu).")] + [Description("When the sound is allowed to play: only when the map view is active, only when the world view is active, or always (map + world + main menu).")] + [DefaultValue(SoundContext.Any)] public SoundContext context; [Description("Event names for this sound. \n\nThe code will look up sounds to play them according to their name. If the code finds the event name it wants in this list, it will trigger this sound.\n\nThe Def name is also used as an event name.")] public List eventNames = new List(); - [DefaultValue(4), Description("For one-shots, this is the number of individual sounds from this Def than can be playing at a time.\n\n For sustainers, this is the number of sustainers that can be running with this sound (each of which can have sub-sounds). Sustainers can fade in and out as you move the camera or objects move, to keep the nearest ones audible.\n\nThis setting may not work for on-camera sounds.")] + [Description("For one-shots, this is the number of individual sounds from this Def than can be playing at a time.\n\n For sustainers, this is the number of sustainers that can be running with this sound (each of which can have sub-sounds). Sustainers can fade in and out as you move the camera or objects move, to keep the nearest ones audible.\n\nThis setting may not work for on-camera sounds.")] + [DefaultValue(4)] public int maxVoices = 4; - [DefaultValue(3), Description("The number of instances of this sound that can play at almost exactly the same moment. Handles cases like six gunners all firing their identical guns at the same time because a target came into view of all of them at the same time. Ordinarily this would make a painfully loud sound, but you can reduce it with this.")] + [Description("The number of instances of this sound that can play at almost exactly the same moment. Handles cases like six gunners all firing their identical guns at the same time because a target came into view of all of them at the same time. Ordinarily this would make a painfully loud sound, but you can reduce it with this.")] + [DefaultValue(3)] public int maxSimultaneous = 3; - [DefaultValue(VoicePriorityMode.PrioritizeNewest), Description("If the system has to not play some instances of this sound because of maxVoices, this determines which ones are ignored.\n\nYou should use PrioritizeNewest for things like gunshots, so older still-playing samples are overridden by newer, more important ones.\n\nSustained sounds should usually prioritize nearest, so if a new fire starts burning nearby it can override a more distant one.")] + [Description("If the system has to not play some instances of this sound because of maxVoices, this determines which ones are ignored.\n\nYou should use PrioritizeNewest for things like gunshots, so older still-playing samples are overridden by newer, more important ones.\n\nSustained sounds should usually prioritize nearest, so if a new fire starts burning nearby it can override a more distant one.")] + [DefaultValue(VoicePriorityMode.PrioritizeNewest)] public VoicePriorityMode priorityMode; - [DefaultValue(""), Description("The special sound slot this sound takes. If a sound with this slot is playing, new sounds in this slot will not play.\n\nOnly works for on-camera sounds.")] + [DefaultValue("")] + [Description("The special sound slot this sound takes. If a sound with this slot is playing, new sounds in this slot will not play.\n\nOnly works for on-camera sounds.")] public string slot = string.Empty; - [DefaultValue(""), Description("The name of the SoundDef that will be played when this sustainer starts."), LoadAlias("sustainerStartSound")] + [LoadAlias("sustainerStartSound")] + [Description("The name of the SoundDef that will be played when this sustainer starts.")] + [DefaultValue("")] public string sustainStartSound = string.Empty; - [DefaultValue(""), Description("The name of the SoundDef that will be played when this sustainer ends."), LoadAlias("sustainerStopSound")] + [LoadAlias("sustainerStopSound")] + [Description("The name of the SoundDef that will be played when this sustainer ends.")] + [DefaultValue("")] public string sustainStopSound = string.Empty; - [DefaultValue(0f), Description("After a sustainer is ended, the sound will fade out over this many real-time seconds.")] + [DefaultValue(0f)] + [Description("After a sustainer is ended, the sound will fade out over this many real-time seconds.")] public float sustainFadeoutTime; [Description("All the sounds that will play when this set is triggered.")] @@ -96,21 +105,59 @@ public override void ResolveReferences() } } - [DebuggerHidden] public override IEnumerable ConfigErrors() { - SoundDef.c__Iterator1DE c__Iterator1DE = new SoundDef.c__Iterator1DE(); - c__Iterator1DE.<>f__this = this; - SoundDef.c__Iterator1DE expr_0E = c__Iterator1DE; - expr_0E.$PC = -2; - return expr_0E; + if (this.slot != string.Empty && !this.HasSubSoundsOnCamera) + { + yield return "Sound slots only work for on-camera sounds."; + } + if (this.HasSubSoundsInWorld && this.context != SoundContext.MapOnly) + { + yield return "Sounds with non-on-camera subsounds should use MapOnly context."; + } + if (this.priorityMode == VoicePriorityMode.PrioritizeNewest && this.sustain) + { + yield return "PrioritizeNewest is not supported with sustainers."; + } + if (this.maxVoices < 1) + { + yield return "Max voices is less than 1."; + } + if (!this.sustain && (this.sustainStartSound != string.Empty || this.sustainStopSound != string.Empty)) + { + yield return "Sustainer start and end sounds only work with sounds defined as sustainers."; + } + if (!this.sustain) + { + for (int k = 0; k < this.subSounds.Count; k++) + { + if (this.subSounds[k].startDelayRange.TrueMax > 0.0010000000474974513) + { + yield return "startDelayRange is only supported on sustainers."; + } + } + } + List defs = DefDatabase.AllDefsListForReading; + for (int j = 0; j < defs.Count; j++) + { + if (!defs[j].eventNames.NullOrEmpty()) + { + for (int i = 0; i < defs[j].eventNames.Count; i++) + { + if (defs[j].eventNames[i] == base.defName) + { + yield return base.defName + " is also defined in the eventNames list for " + defs[j]; + } + } + } + } } public void DoEditWidgets(WidgetRow widgetRow) { if (this.testSustainer == null) { - if (widgetRow.ButtonIcon(TexButton.Play, null)) + if (widgetRow.ButtonIcon(TexButton.Play, (string)null)) { this.ResolveReferences(); SoundInfo info; @@ -141,7 +188,7 @@ public void DoEditWidgets(WidgetRow widgetRow) else { this.testSustainer.Maintain(); - if (widgetRow.ButtonIcon(TexButton.Stop, null)) + if (widgetRow.ButtonIcon(TexButton.Stop, (string)null)) { this.testSustainer.End(); this.testSustainer = null; @@ -183,7 +230,7 @@ public static SoundDef Named(string defName) private static SoundDef UndefinedDefNamed(string defName) { - SoundDef soundDef; + SoundDef soundDef = default(SoundDef); if (!SoundDef.undefinedSoundDefs.TryGetValue(defName, out soundDef)) { soundDef = new SoundDef(); diff --git a/Assembly-CSharp/Verse/SoundDefHelper.cs b/Assembly-CSharp/Verse/SoundDefHelper.cs index 4b002bcce..56fc44b46 100644 --- a/Assembly-CSharp/Verse/SoundDefHelper.cs +++ b/Assembly-CSharp/Verse/SoundDefHelper.cs @@ -20,14 +20,22 @@ public static bool CorrectContextNow(SoundDef def, Map sourceMap) switch (def.context) { case SoundContext.Any: + { return true; + } case SoundContext.MapOnly: + { return Current.ProgramState == ProgramState.Playing && !WorldRendererUtility.WorldRenderedNow; + } case SoundContext.WorldOnly: + { return WorldRendererUtility.WorldRenderedNow; + } default: + { throw new NotImplementedException(); } + } } } } diff --git a/Assembly-CSharp/Verse/SpanDirection.cs b/Assembly-CSharp/Verse/SpanDirection.cs index 375d5ba82..5bc7a9b72 100644 --- a/Assembly-CSharp/Verse/SpanDirection.cs +++ b/Assembly-CSharp/Verse/SpanDirection.cs @@ -1,10 +1,8 @@ -using System; - namespace Verse { public enum SpanDirection : byte { - North, - East + North = 0, + East = 1 } } diff --git a/Assembly-CSharp/Verse/SpecialProductType.cs b/Assembly-CSharp/Verse/SpecialProductType.cs index e6de89d24..d272c903f 100644 --- a/Assembly-CSharp/Verse/SpecialProductType.cs +++ b/Assembly-CSharp/Verse/SpecialProductType.cs @@ -1,10 +1,8 @@ -using System; - namespace Verse { public enum SpecialProductType : byte { - Butchery, - Smelted + Butchery = 0, + Smelted = 1 } } diff --git a/Assembly-CSharp/Verse/SpecialThingFilterDef.cs b/Assembly-CSharp/Verse/SpecialThingFilterDef.cs index 41be59ee1..8771ed402 100644 --- a/Assembly-CSharp/Verse/SpecialThingFilterDef.cs +++ b/Assembly-CSharp/Verse/SpecialThingFilterDef.cs @@ -1,6 +1,5 @@ using System; using System.Collections.Generic; -using System.Diagnostics; namespace Verse { @@ -31,14 +30,16 @@ public SpecialThingFilterWorker Worker } } - [DebuggerHidden] public override IEnumerable ConfigErrors() { - SpecialThingFilterDef.c__Iterator257 c__Iterator = new SpecialThingFilterDef.c__Iterator257(); - c__Iterator.<>f__this = this; - SpecialThingFilterDef.c__Iterator257 expr_0E = c__Iterator; - expr_0E.$PC = -2; - return expr_0E; + foreach (string item in base.ConfigErrors()) + { + yield return item; + } + if (this.workerClass == null) + { + yield return "SpecialThingFilterDef " + base.defName + " has no worker class."; + } } public static SpecialThingFilterDef Named(string defName) diff --git a/Assembly-CSharp/Verse/SpecialThingFilterWorker.cs b/Assembly-CSharp/Verse/SpecialThingFilterWorker.cs index 13d4177af..eac83fc3b 100644 --- a/Assembly-CSharp/Verse/SpecialThingFilterWorker.cs +++ b/Assembly-CSharp/Verse/SpecialThingFilterWorker.cs @@ -1,5 +1,3 @@ -using System; - namespace Verse { public abstract class SpecialThingFilterWorker diff --git a/Assembly-CSharp/Verse/Stance.cs b/Assembly-CSharp/Verse/Stance.cs index 161290cc6..1b5e10342 100644 --- a/Assembly-CSharp/Verse/Stance.cs +++ b/Assembly-CSharp/Verse/Stance.cs @@ -1,5 +1,3 @@ -using System; - namespace Verse { public abstract class Stance : IExposable diff --git a/Assembly-CSharp/Verse/Stance_Busy.cs b/Assembly-CSharp/Verse/Stance_Busy.cs index 9e32c220a..439181d8a 100644 --- a/Assembly-CSharp/Verse/Stance_Busy.cs +++ b/Assembly-CSharp/Verse/Stance_Busy.cs @@ -1,5 +1,3 @@ -using System; - namespace Verse { public abstract class Stance_Busy : Stance @@ -34,7 +32,7 @@ public Stance_Busy(int ticks, LocalTargetInfo focusTarg, Verb verb) this.verb = verb; } - public Stance_Busy(int ticks) : this(ticks, null, null) + public Stance_Busy(int ticks) : this(ticks, (Thing)null, null) { } @@ -78,9 +76,9 @@ public override void StanceTick() protected virtual void Expire() { - if (this.stanceTracker.curStance == this) + if (base.stanceTracker.curStance == this) { - this.stanceTracker.SetStance(new Stance_Mobile()); + base.stanceTracker.SetStance(new Stance_Mobile()); } } } diff --git a/Assembly-CSharp/Verse/Stance_Cooldown.cs b/Assembly-CSharp/Verse/Stance_Cooldown.cs index a2e79b522..64c0ac7eb 100644 --- a/Assembly-CSharp/Verse/Stance_Cooldown.cs +++ b/Assembly-CSharp/Verse/Stance_Cooldown.cs @@ -1,4 +1,3 @@ -using System; using UnityEngine; namespace Verse @@ -19,10 +18,10 @@ public Stance_Cooldown(int ticks, LocalTargetInfo focusTarg, Verb verb) : base(t public override void StanceDraw() { - if (Find.Selector.IsSelected(this.stanceTracker.pawn)) + if (Find.Selector.IsSelected(base.stanceTracker.pawn)) { - float radius = Mathf.Min(0.5f, (float)this.ticksLeft * 0.002f); - GenDraw.DrawCooldownCircle(this.stanceTracker.pawn.Drawer.DrawPos + new Vector3(0f, 0.2f, 0f), radius); + float radius = Mathf.Min(0.5f, (float)((float)base.ticksLeft * 0.0020000000949949026)); + GenDraw.DrawCooldownCircle(base.stanceTracker.pawn.Drawer.DrawPos + new Vector3(0f, 0.2f, 0f), radius); } } } diff --git a/Assembly-CSharp/Verse/Stance_Mobile.cs b/Assembly-CSharp/Verse/Stance_Mobile.cs index 065b67084..07fb2d3e1 100644 --- a/Assembly-CSharp/Verse/Stance_Mobile.cs +++ b/Assembly-CSharp/Verse/Stance_Mobile.cs @@ -1,5 +1,3 @@ -using System; - namespace Verse { public class Stance_Mobile : Stance diff --git a/Assembly-CSharp/Verse/Stance_Warmup.cs b/Assembly-CSharp/Verse/Stance_Warmup.cs index 3bdb2839d..0d3c7b71c 100644 --- a/Assembly-CSharp/Verse/Stance_Warmup.cs +++ b/Assembly-CSharp/Verse/Stance_Warmup.cs @@ -1,5 +1,4 @@ using RimWorld; -using System; namespace Verse { @@ -40,34 +39,35 @@ public override void ExposeData() public override void StanceDraw() { - if (Find.Selector.IsSelected(this.stanceTracker.pawn)) + if (Find.Selector.IsSelected(base.stanceTracker.pawn)) { - GenDraw.DrawAimPie(this.stanceTracker.pawn, this.focusTarg, (int)((float)this.ticksLeft * this.pieSizeFactor), 0.2f); + GenDraw.DrawAimPie(base.stanceTracker.pawn, base.focusTarg, (int)((float)base.ticksLeft * base.pieSizeFactor), 0.2f); } } public override void StanceTick() { - if (!this.targetStartedDowned && this.focusTarg.HasThing && this.focusTarg.Thing is Pawn && ((Pawn)this.focusTarg.Thing).Downed) + if (!this.targetStartedDowned && base.focusTarg.HasThing && base.focusTarg.Thing is Pawn && ((Pawn)base.focusTarg.Thing).Downed) { - this.stanceTracker.SetStance(new Stance_Mobile()); - return; + base.stanceTracker.SetStance(new Stance_Mobile()); } - if (this.focusTarg.HasThing && (!this.focusTarg.Thing.Spawned || !this.verb.CanHitTargetFrom(base.Pawn.Position, this.focusTarg))) + else if (base.focusTarg.HasThing && (!base.focusTarg.Thing.Spawned || !base.verb.CanHitTargetFrom(base.Pawn.Position, base.focusTarg))) { - this.stanceTracker.SetStance(new Stance_Mobile()); - return; + base.stanceTracker.SetStance(new Stance_Mobile()); } - if (this.focusTarg == base.Pawn.mindState.enemyTarget) + else { - base.Pawn.mindState.Notify_EngagedTarget(); + if (base.focusTarg == base.Pawn.mindState.enemyTarget) + { + base.Pawn.mindState.Notify_EngagedTarget(); + } + base.StanceTick(); } - base.StanceTick(); } protected override void Expire() { - this.verb.WarmupComplete(); + base.verb.WarmupComplete(); base.Expire(); } } diff --git a/Assembly-CSharp/Verse/StandardLetter.cs b/Assembly-CSharp/Verse/StandardLetter.cs index c9ad77932..afd11cd70 100644 --- a/Assembly-CSharp/Verse/StandardLetter.cs +++ b/Assembly-CSharp/Verse/StandardLetter.cs @@ -1,4 +1,3 @@ -using System; using System.Collections.Generic; namespace Verse @@ -9,11 +8,11 @@ protected override IEnumerable Choices { get { - StandardLetter.<>c__Iterator234 <>c__Iterator = new StandardLetter.<>c__Iterator234(); - <>c__Iterator.<>f__this = this; - StandardLetter.<>c__Iterator234 expr_0E = <>c__Iterator; - expr_0E.$PC = -2; - return expr_0E; + yield return base.OK; + if (base.lookTarget.IsValid) + { + yield return base.JumpToLocation; + } } } } diff --git a/Assembly-CSharp/Verse/StartingPawnUtility.cs b/Assembly-CSharp/Verse/StartingPawnUtility.cs index 9d38d2abc..9119acf1a 100644 --- a/Assembly-CSharp/Verse/StartingPawnUtility.cs +++ b/Assembly-CSharp/Verse/StartingPawnUtility.cs @@ -17,15 +17,15 @@ private static List StartingPawns public static void ClearAllStartingPawns() { - for (int i = StartingPawnUtility.StartingPawns.Count - 1; i >= 0; i--) + for (int num = StartingPawnUtility.StartingPawns.Count - 1; num >= 0; num--) { - StartingPawnUtility.StartingPawns[i].relations.ClearAllRelations(); + StartingPawnUtility.StartingPawns[num].relations.ClearAllRelations(); if (Find.World != null) { - PawnUtility.DestroyStartingColonistFamily(StartingPawnUtility.StartingPawns[i]); - Find.WorldPawns.PassToWorld(StartingPawnUtility.StartingPawns[i], PawnDiscardDecideMode.Discard); + PawnUtility.DestroyStartingColonistFamily(StartingPawnUtility.StartingPawns[num]); + Find.WorldPawns.PassToWorld(StartingPawnUtility.StartingPawns[num], PawnDiscardDecideMode.Discard); } - StartingPawnUtility.StartingPawns.RemoveAt(i); + StartingPawnUtility.StartingPawns.RemoveAt(num); } } @@ -61,7 +61,7 @@ private static Pawn RegenerateStartingPawnInPlace(int index) public static Pawn NewGeneratedStartingPawn() { - PawnGenerationRequest request = new PawnGenerationRequest(Faction.OfPlayer.def.basicMemberKind, Faction.OfPlayer, PawnGenerationContext.PlayerStarter, -1, true, false, false, false, true, false, 26f, false, true, true, false, false, null, null, null, null, null, null); + PawnGenerationRequest request = new PawnGenerationRequest(Faction.OfPlayer.def.basicMemberKind, Faction.OfPlayer, PawnGenerationContext.PlayerStarter, -1, true, false, false, false, true, false, 26f, false, true, true, false, false, null, default(float?), default(float?), default(Gender?), default(float?), (string)null); Pawn pawn = null; try { @@ -90,13 +90,16 @@ public static bool WorkTypeRequirementsSatisfied() if (workTypeDef.requireCapableColonist) { bool flag = false; - for (int j = 0; j < StartingPawnUtility.StartingPawns.Count; j++) + int num = 0; + while (num < StartingPawnUtility.StartingPawns.Count) { - if (!StartingPawnUtility.StartingPawns[j].story.WorkTypeIsDisabled(workTypeDef)) + if (StartingPawnUtility.StartingPawns[num].story.WorkTypeIsDisabled(workTypeDef)) { - flag = true; - break; + num++; + continue; } + flag = true; + break; } if (!flag) { @@ -104,12 +107,9 @@ public static bool WorkTypeRequirementsSatisfied() } } } - if (TutorSystem.TutorialMode) + if (TutorSystem.TutorialMode && StartingPawnUtility.StartingPawns.Any((Predicate)((Pawn p) => p.story.WorkTagIsDisabled(WorkTags.Violent)))) { - if (StartingPawnUtility.StartingPawns.Any((Pawn p) => p.story.WorkTagIsDisabled(WorkTags.Violent))) - { - return false; - } + return false; } return true; } diff --git a/Assembly-CSharp/Verse/StaticConstructorOnStartupUtility.cs b/Assembly-CSharp/Verse/StaticConstructorOnStartupUtility.cs index d5c8ebfc1..ca37d4a24 100644 --- a/Assembly-CSharp/Verse/StaticConstructorOnStartupUtility.cs +++ b/Assembly-CSharp/Verse/StaticConstructorOnStartupUtility.cs @@ -14,9 +14,9 @@ public static class StaticConstructorOnStartupUtility public static void CallAll() { IEnumerable enumerable = GenTypes.AllTypesWithAttribute(); - foreach (Type current in enumerable) + foreach (Type item in enumerable) { - RuntimeHelpers.RunClassConstructor(current.TypeHandle); + RuntimeHelpers.RunClassConstructor(item.TypeHandle); } StaticConstructorOnStartupUtility.coreStaticAssetsLoaded = true; } @@ -24,11 +24,11 @@ public static void CallAll() public static void ReportProbablyMissingAttributes() { BindingFlags bindingAttr = BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic; - foreach (Type current in GenTypes.AllTypes) + foreach (Type allType in GenTypes.AllTypes) { - if (!current.HasAttribute()) + if (!allType.HasAttribute()) { - FieldInfo fieldInfo = current.GetFields(bindingAttr).FirstOrDefault(delegate(FieldInfo x) + FieldInfo fieldInfo = allType.GetFields(bindingAttr).FirstOrDefault((Func)delegate(FieldInfo x) { Type type = x.FieldType; if (type.IsArray) @@ -39,16 +39,7 @@ public static void ReportProbablyMissingAttributes() }); if (fieldInfo != null) { - Log.Warning(string.Concat(new string[] - { - "Type ", - current.Name, - " probably needs a StaticConstructorOnStartup attribute, because it has a field ", - fieldInfo.Name, - " of type ", - fieldInfo.FieldType.Name, - ". All assets must be loaded in the main thread." - })); + Log.Warning("Type " + allType.Name + " probably needs a StaticConstructorOnStartup attribute, because it has a field " + fieldInfo.Name + " of type " + fieldInfo.FieldType.Name + ". All assets must be loaded in the main thread."); } } } diff --git a/Assembly-CSharp/Verse/SteamUtility.cs b/Assembly-CSharp/Verse/SteamUtility.cs index cbf3813b2..7be2aa874 100644 --- a/Assembly-CSharp/Verse/SteamUtility.cs +++ b/Assembly-CSharp/Verse/SteamUtility.cs @@ -1,5 +1,4 @@ using Steamworks; -using System; using UnityEngine; using Verse.Steam; diff --git a/Assembly-CSharp/Verse/StrippableUtility.cs b/Assembly-CSharp/Verse/StrippableUtility.cs index b7ca3c1ff..65275aec4 100644 --- a/Assembly-CSharp/Verse/StrippableUtility.cs +++ b/Assembly-CSharp/Verse/StrippableUtility.cs @@ -1,5 +1,3 @@ -using System; - namespace Verse { public static class StrippableUtility @@ -16,7 +14,19 @@ public static bool CanBeStrippedByColony(Thing th) return false; } Pawn pawn = th as Pawn; - return pawn == null || pawn.Downed || (pawn.IsPrisonerOfColony && pawn.guest.PrisonerIsSecure); + if (pawn == null) + { + return true; + } + if (pawn.Downed) + { + return true; + } + if (pawn.IsPrisonerOfColony && pawn.guest.PrisonerIsSecure) + { + return true; + } + return false; } } } diff --git a/Assembly-CSharp/Verse/StuffAppearanceDef.cs b/Assembly-CSharp/Verse/StuffAppearanceDef.cs index 06b4f9c66..c703d9563 100644 --- a/Assembly-CSharp/Verse/StuffAppearanceDef.cs +++ b/Assembly-CSharp/Verse/StuffAppearanceDef.cs @@ -1,5 +1,3 @@ -using System; - namespace Verse { public class StuffAppearanceDef : Def diff --git a/Assembly-CSharp/Verse/StuffProperties.cs b/Assembly-CSharp/Verse/StuffProperties.cs index b868f35bf..27ccadf23 100644 --- a/Assembly-CSharp/Verse/StuffProperties.cs +++ b/Assembly-CSharp/Verse/StuffProperties.cs @@ -1,5 +1,4 @@ using RimWorld; -using System; using System.Collections.Generic; using UnityEngine; diff --git a/Assembly-CSharp/Verse/SubEffecter.cs b/Assembly-CSharp/Verse/SubEffecter.cs index b2c9d1b24..80dbd3f81 100644 --- a/Assembly-CSharp/Verse/SubEffecter.cs +++ b/Assembly-CSharp/Verse/SubEffecter.cs @@ -1,5 +1,3 @@ -using System; - namespace Verse { public class SubEffecter diff --git a/Assembly-CSharp/Verse/SubEffecterDef.cs b/Assembly-CSharp/Verse/SubEffecterDef.cs index e87a1c26d..c957f79ba 100644 --- a/Assembly-CSharp/Verse/SubEffecterDef.cs +++ b/Assembly-CSharp/Verse/SubEffecterDef.cs @@ -42,10 +42,7 @@ public class SubEffecterDef public SubEffecter Spawn() { - return (SubEffecter)Activator.CreateInstance(this.subEffecterClass, new object[] - { - this - }); + return (SubEffecter)Activator.CreateInstance(this.subEffecterClass, this); } } } diff --git a/Assembly-CSharp/Verse/SubEffecter_DrifterEmote.cs b/Assembly-CSharp/Verse/SubEffecter_DrifterEmote.cs index b6c3f5691..20e57c282 100644 --- a/Assembly-CSharp/Verse/SubEffecter_DrifterEmote.cs +++ b/Assembly-CSharp/Verse/SubEffecter_DrifterEmote.cs @@ -1,4 +1,3 @@ -using System; using UnityEngine; namespace Verse @@ -14,19 +13,19 @@ protected void MakeMote(TargetInfo A) Vector3 vector = (!A.HasThing) ? A.Cell.ToVector3Shifted() : A.Thing.DrawPos; if (vector.ShouldSpawnMotesAt(A.Map)) { - int randomInRange = this.def.burstCount.RandomInRange; - for (int i = 0; i < randomInRange; i++) + int randomInRange = base.def.burstCount.RandomInRange; + for (int num = 0; num < randomInRange; num++) { - Mote mote = (Mote)ThingMaker.MakeThing(this.def.moteDef, null); - mote.Scale = this.def.scale.RandomInRange; - mote.exactPosition = vector + Gen.RandomHorizontalVector(this.def.positionRadius); - mote.rotationRate = this.def.rotationRate.RandomInRange; - mote.exactRotation = this.def.rotation.RandomInRange; + Mote mote = (Mote)ThingMaker.MakeThing(base.def.moteDef, null); + mote.Scale = base.def.scale.RandomInRange; + mote.exactPosition = vector + Gen.RandomHorizontalVector(base.def.positionRadius); + mote.rotationRate = base.def.rotationRate.RandomInRange; + mote.exactRotation = base.def.rotation.RandomInRange; MoteThrown moteThrown = mote as MoteThrown; if (moteThrown != null) { - moteThrown.airTimeLeft = this.def.airTime.RandomInRange; - moteThrown.SetVelocity(this.def.angle.RandomInRange, this.def.speed.RandomInRange); + moteThrown.airTimeLeft = base.def.airTime.RandomInRange; + moteThrown.SetVelocity(base.def.angle.RandomInRange, base.def.speed.RandomInRange); } if (A.HasThing) { diff --git a/Assembly-CSharp/Verse/SubEffecter_DrifterEmoteChance.cs b/Assembly-CSharp/Verse/SubEffecter_DrifterEmoteChance.cs index 6aff0e02c..0c9f16a5a 100644 --- a/Assembly-CSharp/Verse/SubEffecter_DrifterEmoteChance.cs +++ b/Assembly-CSharp/Verse/SubEffecter_DrifterEmoteChance.cs @@ -1,5 +1,3 @@ -using System; - namespace Verse { public class SubEffecter_DrifterEmoteChance : SubEffecter_DrifterEmote @@ -10,7 +8,7 @@ public SubEffecter_DrifterEmoteChance(SubEffecterDef def) : base(def) public override void SubEffectTick(TargetInfo A, TargetInfo B) { - float chancePerTick = this.def.chancePerTick; + float chancePerTick = base.def.chancePerTick; if (Rand.Value < chancePerTick) { base.MakeMote(A); diff --git a/Assembly-CSharp/Verse/SubEffecter_DrifterEmoteContinuous.cs b/Assembly-CSharp/Verse/SubEffecter_DrifterEmoteContinuous.cs index 66958a66b..a86a2ea54 100644 --- a/Assembly-CSharp/Verse/SubEffecter_DrifterEmoteContinuous.cs +++ b/Assembly-CSharp/Verse/SubEffecter_DrifterEmoteContinuous.cs @@ -1,5 +1,3 @@ -using System; - namespace Verse { public class SubEffecter_DrifterEmoteContinuous : SubEffecter_DrifterEmote @@ -16,7 +14,7 @@ public override void SubEffectTick(TargetInfo A, TargetInfo B) if (this.ticksUntilMote <= 0) { base.MakeMote(A); - this.ticksUntilMote = this.def.ticksBetweenMotes; + this.ticksUntilMote = base.def.ticksBetweenMotes; } } } diff --git a/Assembly-CSharp/Verse/SubEffecter_DrifterEmoteTriggered.cs b/Assembly-CSharp/Verse/SubEffecter_DrifterEmoteTriggered.cs index b2222802e..fa8d2a2a3 100644 --- a/Assembly-CSharp/Verse/SubEffecter_DrifterEmoteTriggered.cs +++ b/Assembly-CSharp/Verse/SubEffecter_DrifterEmoteTriggered.cs @@ -1,5 +1,3 @@ -using System; - namespace Verse { public class SubEffecter_DrifterEmoteTriggered : SubEffecter_DrifterEmote diff --git a/Assembly-CSharp/Verse/SubEffecter_InteractSymbol.cs b/Assembly-CSharp/Verse/SubEffecter_InteractSymbol.cs index 8ae7d7a1a..7beba3b25 100644 --- a/Assembly-CSharp/Verse/SubEffecter_InteractSymbol.cs +++ b/Assembly-CSharp/Verse/SubEffecter_InteractSymbol.cs @@ -1,5 +1,4 @@ using RimWorld; -using System; namespace Verse { @@ -15,7 +14,7 @@ public override void SubEffectTick(TargetInfo A, TargetInfo B) { if (this.interactMote == null) { - this.interactMote = MoteMaker.MakeInteractionOverlay(this.def.moteDef, A, B); + this.interactMote = MoteMaker.MakeInteractionOverlay(base.def.moteDef, A, B); } } diff --git a/Assembly-CSharp/Verse/SubEffecter_ProgressBar.cs b/Assembly-CSharp/Verse/SubEffecter_ProgressBar.cs index 901a2efbb..d2a7f1fe9 100644 --- a/Assembly-CSharp/Verse/SubEffecter_ProgressBar.cs +++ b/Assembly-CSharp/Verse/SubEffecter_ProgressBar.cs @@ -1,5 +1,4 @@ using RimWorld; -using System; namespace Verse { @@ -19,7 +18,7 @@ public override void SubEffectTick(TargetInfo A, TargetInfo B) { if (this.mote == null) { - this.mote = (MoteProgressBar)MoteMaker.MakeInteractionOverlay(this.def.moteDef, A, B); + this.mote = (MoteProgressBar)MoteMaker.MakeInteractionOverlay(base.def.moteDef, A, B); this.mote.exactScale.x = 0.68f; this.mote.exactScale.z = 0.12f; } diff --git a/Assembly-CSharp/Verse/SubEffecter_SoundTriggered.cs b/Assembly-CSharp/Verse/SubEffecter_SoundTriggered.cs index 2d8854aab..3fa31816e 100644 --- a/Assembly-CSharp/Verse/SubEffecter_SoundTriggered.cs +++ b/Assembly-CSharp/Verse/SubEffecter_SoundTriggered.cs @@ -1,4 +1,3 @@ -using System; using Verse.Sound; namespace Verse @@ -11,7 +10,7 @@ public SubEffecter_SoundTriggered(SubEffecterDef def) : base(def) public override void SubTrigger(TargetInfo A, TargetInfo B) { - this.def.soundDef.PlayOneShot(new TargetInfo(A.Cell, A.Map, false)); + base.def.soundDef.PlayOneShot(new TargetInfo(A.Cell, A.Map, false)); } } } diff --git a/Assembly-CSharp/Verse/SubEffecter_Sprayer.cs b/Assembly-CSharp/Verse/SubEffecter_Sprayer.cs index 641f4bfc4..82b21729a 100644 --- a/Assembly-CSharp/Verse/SubEffecter_Sprayer.cs +++ b/Assembly-CSharp/Verse/SubEffecter_Sprayer.cs @@ -1,4 +1,3 @@ -using System; using UnityEngine; namespace Verse @@ -12,65 +11,49 @@ public SubEffecter_Sprayer(SubEffecterDef def) : base(def) protected void MakeMote(TargetInfo A, TargetInfo B) { Vector3 vector = Vector3.zero; - switch (this.def.spawnLocType) + switch (base.def.spawnLocType) { case MoteSpawnLocType.OnSource: + { vector = A.Cell.ToVector3Shifted(); break; + } case MoteSpawnLocType.BetweenPositions: { Vector3 vector2 = (!A.HasThing) ? A.Cell.ToVector3Shifted() : A.Thing.DrawPos; Vector3 vector3 = (!B.HasThing) ? B.Cell.ToVector3Shifted() : B.Thing.DrawPos; - if (A.HasThing && !A.Thing.Spawned) - { - vector = vector3; - } - else if (B.HasThing && !B.Thing.Spawned) - { - vector = vector2; - } - else - { - vector = vector2 * this.def.positionLerpFactor + vector3 * (1f - this.def.positionLerpFactor); - } + vector = ((!A.HasThing || A.Thing.Spawned) ? ((!B.HasThing || B.Thing.Spawned) ? (vector2 * base.def.positionLerpFactor + vector3 * (float)(1.0 - base.def.positionLerpFactor)) : vector2) : vector3); break; } - case MoteSpawnLocType.BetweenTouchingCells: - vector = A.Cell.ToVector3Shifted() + (B.Cell - A.Cell).ToVector3().normalized * 0.5f; - break; case MoteSpawnLocType.RandomCellOnTarget: { - CellRect cellRect; - if (B.HasThing) - { - cellRect = B.Thing.OccupiedRect(); - } - else - { - cellRect = CellRect.CenteredOn(B.Cell, 0); - } - vector = cellRect.RandomCell.ToVector3Shifted(); + vector = ((!B.HasThing) ? CellRect.CenteredOn(B.Cell, 0) : B.Thing.OccupiedRect()).RandomCell.ToVector3Shifted(); + break; + } + case MoteSpawnLocType.BetweenTouchingCells: + { + vector = A.Cell.ToVector3Shifted() + (B.Cell - A.Cell).ToVector3().normalized * 0.5f; break; } } Map map = A.Map ?? B.Map; if (map != null && vector.ShouldSpawnMotesAt(map)) { - int randomInRange = this.def.burstCount.RandomInRange; - for (int i = 0; i < randomInRange; i++) + int randomInRange = base.def.burstCount.RandomInRange; + for (int num = 0; num < randomInRange; num++) { - Mote mote = (Mote)ThingMaker.MakeThing(this.def.moteDef, null); + Mote mote = (Mote)ThingMaker.MakeThing(base.def.moteDef, null); GenSpawn.Spawn(mote, vector.ToIntVec3(), map); - mote.Scale = this.def.scale.RandomInRange; - mote.exactPosition = vector + Gen.RandomHorizontalVector(this.def.positionRadius); - mote.rotationRate = this.def.rotationRate.RandomInRange; - float num = (!this.def.absoluteAngle) ? (B.Cell - A.Cell).AngleFlat : 0f; - mote.exactRotation = this.def.rotation.RandomInRange + num; + mote.Scale = base.def.scale.RandomInRange; + mote.exactPosition = vector + Gen.RandomHorizontalVector(base.def.positionRadius); + mote.rotationRate = base.def.rotationRate.RandomInRange; + float num2 = (float)((!base.def.absoluteAngle) ? (B.Cell - A.Cell).AngleFlat : 0.0); + mote.exactRotation = base.def.rotation.RandomInRange + num2; MoteThrown moteThrown = mote as MoteThrown; if (moteThrown != null) { - moteThrown.airTimeLeft = this.def.airTime.RandomInRange; - moteThrown.SetVelocity(this.def.angle.RandomInRange + num, this.def.speed.RandomInRange); + moteThrown.airTimeLeft = base.def.airTime.RandomInRange; + moteThrown.SetVelocity(base.def.angle.RandomInRange + num2, base.def.speed.RandomInRange); } } } diff --git a/Assembly-CSharp/Verse/SubEffecter_SprayerChance.cs b/Assembly-CSharp/Verse/SubEffecter_SprayerChance.cs index 0cbd05df3..d18b172df 100644 --- a/Assembly-CSharp/Verse/SubEffecter_SprayerChance.cs +++ b/Assembly-CSharp/Verse/SubEffecter_SprayerChance.cs @@ -1,5 +1,3 @@ -using System; - namespace Verse { public class SubEffecter_SprayerChance : SubEffecter_Sprayer @@ -10,8 +8,8 @@ public SubEffecter_SprayerChance(SubEffecterDef def) : base(def) public override void SubEffectTick(TargetInfo A, TargetInfo B) { - float num = this.def.chancePerTick; - if (this.def.spawnLocType == MoteSpawnLocType.RandomCellOnTarget && B.HasThing) + float num = base.def.chancePerTick; + if (base.def.spawnLocType == MoteSpawnLocType.RandomCellOnTarget && B.HasThing) { num *= (float)(B.Thing.def.size.x * B.Thing.def.size.z); } diff --git a/Assembly-CSharp/Verse/SubEffecter_SprayerContinuous.cs b/Assembly-CSharp/Verse/SubEffecter_SprayerContinuous.cs index d27dbd5ae..97ec5888e 100644 --- a/Assembly-CSharp/Verse/SubEffecter_SprayerContinuous.cs +++ b/Assembly-CSharp/Verse/SubEffecter_SprayerContinuous.cs @@ -1,5 +1,3 @@ -using System; - namespace Verse { public class SubEffecter_SprayerContinuous : SubEffecter_Sprayer @@ -16,7 +14,7 @@ public override void SubEffectTick(TargetInfo A, TargetInfo B) if (this.ticksUntilMote <= 0) { base.MakeMote(A, B); - this.ticksUntilMote = this.def.ticksBetweenMotes; + this.ticksUntilMote = base.def.ticksBetweenMotes; } } } diff --git a/Assembly-CSharp/Verse/SubEffecter_SprayerTriggered.cs b/Assembly-CSharp/Verse/SubEffecter_SprayerTriggered.cs index 63bce540f..343e27201 100644 --- a/Assembly-CSharp/Verse/SubEffecter_SprayerTriggered.cs +++ b/Assembly-CSharp/Verse/SubEffecter_SprayerTriggered.cs @@ -1,5 +1,3 @@ -using System; - namespace Verse { public class SubEffecter_SprayerTriggered : SubEffecter_Sprayer diff --git a/Assembly-CSharp/Verse/SubEffecter_Sustainer.cs b/Assembly-CSharp/Verse/SubEffecter_Sustainer.cs index 611247353..3d7e86687 100644 --- a/Assembly-CSharp/Verse/SubEffecter_Sustainer.cs +++ b/Assembly-CSharp/Verse/SubEffecter_Sustainer.cs @@ -1,4 +1,3 @@ -using System; using Verse.Sound; namespace Verse @@ -16,12 +15,12 @@ public SubEffecter_Sustainer(SubEffecterDef def) : base(def) public override void SubEffectTick(TargetInfo A, TargetInfo B) { this.age++; - if (this.age > this.def.ticksBeforeSustainerStart) + if (this.age > base.def.ticksBeforeSustainerStart) { if (this.sustainer == null) { SoundInfo info = SoundInfo.InMap(A, MaintenanceType.PerTick); - this.sustainer = this.def.soundDef.TrySpawnSustainer(info); + this.sustainer = base.def.soundDef.TrySpawnSustainer(info); } else { diff --git a/Assembly-CSharp/Verse/SummaryHealthHandler.cs b/Assembly-CSharp/Verse/SummaryHealthHandler.cs index 844b28bb1..216a1bcb3 100644 --- a/Assembly-CSharp/Verse/SummaryHealthHandler.cs +++ b/Assembly-CSharp/Verse/SummaryHealthHandler.cs @@ -1,4 +1,3 @@ -using System; using System.Collections.Generic; using UnityEngine; @@ -30,14 +29,14 @@ public float SummaryHealthPercent if (!(hediffs[i] is Hediff_MissingPart)) { float num2 = Mathf.Min(hediffs[i].SummaryHealthPercentImpact, 0.95f); - num *= 1f - num2; + num = (float)(num * (1.0 - num2)); } } List missingPartsCommonAncestors = this.pawn.health.hediffSet.GetMissingPartsCommonAncestors(); for (int j = 0; j < missingPartsCommonAncestors.Count; j++) { float num3 = Mathf.Min(missingPartsCommonAncestors[j].SummaryHealthPercentImpact, 0.95f); - num *= 1f - num3; + num = (float)(num * (1.0 - num3)); } this.cachedSummaryHealthPercent = Mathf.Clamp(num, 0.05f, 1f); ProfilerThreadCheck.EndSample(); diff --git a/Assembly-CSharp/Verse/SurfaceType.cs b/Assembly-CSharp/Verse/SurfaceType.cs index 5502aed01..6f58b0dea 100644 --- a/Assembly-CSharp/Verse/SurfaceType.cs +++ b/Assembly-CSharp/Verse/SurfaceType.cs @@ -1,11 +1,9 @@ -using System; - namespace Verse { public enum SurfaceType : byte { - None, - Item, - Eat + None = 0, + Item = 1, + Eat = 2 } } diff --git a/Assembly-CSharp/Verse/SurpriseAttackProps.cs b/Assembly-CSharp/Verse/SurpriseAttackProps.cs index 7749e5a59..5c86bd89d 100644 --- a/Assembly-CSharp/Verse/SurpriseAttackProps.cs +++ b/Assembly-CSharp/Verse/SurpriseAttackProps.cs @@ -1,4 +1,3 @@ -using System; using System.Collections.Generic; namespace Verse diff --git a/Assembly-CSharp/Verse/SwoopCallbackMethod.cs b/Assembly-CSharp/Verse/SwoopCallbackMethod.cs index ce541f041..32aaf8939 100644 --- a/Assembly-CSharp/Verse/SwoopCallbackMethod.cs +++ b/Assembly-CSharp/Verse/SwoopCallbackMethod.cs @@ -1,5 +1,3 @@ -using System; - namespace Verse { public delegate void SwoopCallbackMethod(); diff --git a/Assembly-CSharp/Verse/TabDrawer.cs b/Assembly-CSharp/Verse/TabDrawer.cs index ad81ff6de..c212ea6a8 100644 --- a/Assembly-CSharp/Verse/TabDrawer.cs +++ b/Assembly-CSharp/Verse/TabDrawer.cs @@ -20,22 +20,22 @@ public static class TabDrawer public static TabRecord DrawTabs(Rect baseRect, IEnumerable tabsEnum) { TabDrawer.tabList.Clear(); - foreach (TabRecord current in tabsEnum) + foreach (TabRecord item in tabsEnum) { - TabDrawer.tabList.Add(current); + TabDrawer.tabList.Add(item); } TabRecord tabRecord = null; TabRecord tabRecord2 = (from t in TabDrawer.tabList where t.selected - select t).FirstOrDefault(); + select t).FirstOrDefault(); if (tabRecord2 == null) { Log.ErrorOnce("Drew tabs without any being selected.", 5509712); return TabDrawer.tabList[0]; } - float num = baseRect.width + (float)(TabDrawer.tabList.Count - 1) * 10f; + float num = (float)(baseRect.width + (float)(TabDrawer.tabList.Count - 1) * 10.0); float tabWidth = num / (float)TabDrawer.tabList.Count; - if (tabWidth > 200f) + if (tabWidth > 200.0) { tabWidth = 200f; } @@ -45,17 +45,17 @@ where t.selected GUI.BeginGroup(position); Text.Anchor = TextAnchor.MiddleCenter; Text.Font = GameFont.Small; - Func func = delegate(TabRecord tab) + Func func = (Func)delegate(TabRecord tab) { int num2 = TabDrawer.tabList.IndexOf(tab); - float x = (float)num2 * (tabWidth - 10f); + float x = (float)((float)num2 * (tabWidth - 10.0)); return new Rect(x, 1f, tabWidth, 32f); }; - List list = TabDrawer.tabList.ListFullCopy(); + List list = TabDrawer.tabList.ListFullCopy(); list.Remove(tabRecord2); list.Add(tabRecord2); TabRecord tabRecord3 = null; - List list2 = list.ListFullCopy(); + List list2 = list.ListFullCopy(); list2.Reverse(); for (int i = 0; i < list2.Count; i++) { @@ -71,17 +71,26 @@ where t.selected tabRecord = tabRecord4; } } - foreach (TabRecord current2 in list) + List.Enumerator enumerator2 = list.GetEnumerator(); + try { - Rect rect2 = func(current2); - current2.Draw(rect2); + while (enumerator2.MoveNext()) + { + TabRecord current2 = enumerator2.Current; + Rect rect2 = func(current2); + current2.Draw(rect2); + } + } + finally + { + ((IDisposable)(object)enumerator2).Dispose(); } Text.Anchor = TextAnchor.UpperLeft; GUI.EndGroup(); if (tabRecord != null && tabRecord != tabRecord2) { SoundDefOf.RowTabSelect.PlayOneShotOnCamera(null); - if (tabRecord.clickedAction != null) + if ((object)tabRecord.clickedAction != null) { tabRecord.clickedAction(); } diff --git a/Assembly-CSharp/Verse/TabRecord.cs b/Assembly-CSharp/Verse/TabRecord.cs index 83462dc63..2e196fd7f 100644 --- a/Assembly-CSharp/Verse/TabRecord.cs +++ b/Assembly-CSharp/Verse/TabRecord.cs @@ -27,11 +27,15 @@ public TabRecord(string label, Action clickedAction, bool selected) public void Draw(Rect rect) { - Rect drawRect = new Rect(rect); - drawRect.width = 30f; - Rect drawRect2 = new Rect(rect); - drawRect2.width = 30f; - drawRect2.x = rect.x + rect.width - 30f; + Rect drawRect = new Rect(rect) + { + width = 30f + }; + Rect drawRect2 = new Rect(rect) + { + width = 30f, + x = (float)(rect.x + rect.width - 30.0) + }; Rect uvRect = new Rect(0.53125f, 0f, 0.46875f, 1f); Rect drawRect3 = new Rect(rect); drawRect3.x += drawRect.width; diff --git a/Assembly-CSharp/Verse/TargetInfo.cs b/Assembly-CSharp/Verse/TargetInfo.cs index b424ae905..8a93e85ec 100644 --- a/Assembly-CSharp/Verse/TargetInfo.cs +++ b/Assembly-CSharp/Verse/TargetInfo.cs @@ -123,7 +123,11 @@ public TargetInfo(IntVec3 cell, Map map, bool allowNullMap = false) public override bool Equals(object obj) { - return obj is TargetInfo && this.Equals((TargetInfo)obj); + if (!(obj is TargetInfo)) + { + return false; + } + return this.Equals((TargetInfo)obj); } public bool Equals(TargetInfo other) @@ -137,7 +141,7 @@ public override int GetHashCode() { return this.thingInt.GetHashCode(); } - return Gen.HashCombine(this.cellInt.GetHashCode(), this.mapInt); + return Gen.HashCombine(this.cellInt.GetHashCode(), this.mapInt); } public override string ToString() @@ -187,11 +191,15 @@ public static explicit operator Thing(TargetInfo targ) public static bool operator ==(TargetInfo a, TargetInfo b) { - if (a.Thing != null || b.Thing != null) + if (a.Thing == null && b.Thing == null) { - return a.Thing == b.Thing; + if (!a.cellInt.IsValid && !b.cellInt.IsValid) + { + return true; + } + return a.cellInt == b.cellInt && a.mapInt == b.mapInt; } - return (!a.cellInt.IsValid && !b.cellInt.IsValid) || (a.cellInt == b.cellInt && a.mapInt == b.mapInt); + return a.Thing == b.Thing; } public static bool operator !=(TargetInfo a, TargetInfo b) diff --git a/Assembly-CSharp/Verse/TargetType.cs b/Assembly-CSharp/Verse/TargetType.cs index f2f4b5349..c348e3206 100644 --- a/Assembly-CSharp/Verse/TargetType.cs +++ b/Assembly-CSharp/Verse/TargetType.cs @@ -1,10 +1,8 @@ -using System; - namespace Verse { public enum TargetType : byte { - Thing, - Cell + Thing = 0, + Cell = 1 } } diff --git a/Assembly-CSharp/Verse/TemperatureCache.cs b/Assembly-CSharp/Verse/TemperatureCache.cs index 3e56590a3..9d24f6bdc 100644 --- a/Assembly-CSharp/Verse/TemperatureCache.cs +++ b/Assembly-CSharp/Verse/TemperatureCache.cs @@ -25,9 +25,9 @@ public TemperatureCache(Map map) public void ResetTemperatureCache() { int numGridCells = this.map.cellIndices.NumGridCells; - for (int i = 0; i < numGridCells; i++) + for (int num = 0; num < numGridCells; num++) { - this.tempCache[i].Reset(); + this.tempCache[num].Reset(); } } @@ -59,9 +59,9 @@ public void TryCacheRegionTempInfo(IntVec3 c, Region reg) public bool TryGetAverageCachedRoomGroupTemp(RoomGroup r, out float result) { CellIndices cellIndices = this.map.cellIndices; - foreach (IntVec3 current in r.Cells) + foreach (IntVec3 cell in r.Cells) { - CachedTempInfo item = this.map.temperatureCache.tempCache[cellIndices.CellToIndex(current)]; + CachedTempInfo item = this.map.temperatureCache.tempCache[cellIndices.CellToIndex(cell)]; if (item.numCells > 0 && !this.processedRoomGroupIDs.Contains(item.roomGroupID)) { this.relevantTempInfoList.Add(item); @@ -70,13 +70,22 @@ public bool TryGetAverageCachedRoomGroupTemp(RoomGroup r, out float result) } int num = 0; float num2 = 0f; - foreach (CachedTempInfo current2 in this.relevantTempInfoList) + List.Enumerator enumerator2 = this.relevantTempInfoList.GetEnumerator(); + try { - num += current2.numCells; - num2 += current2.temperature * (float)current2.numCells; + while (enumerator2.MoveNext()) + { + CachedTempInfo current2 = enumerator2.Current; + num += current2.numCells; + num2 += current2.temperature * (float)current2.numCells; + } + } + finally + { + ((IDisposable)(object)enumerator2).Dispose(); } result = num2 / (float)num; - bool result2 = !this.relevantTempInfoList.NullOrEmpty(); + bool result2 = !this.relevantTempInfoList.NullOrEmpty(); this.processedRoomGroupIDs.Clear(); this.relevantTempInfoList.Clear(); return result2; diff --git a/Assembly-CSharp/Verse/TemperatureDisplayMode.cs b/Assembly-CSharp/Verse/TemperatureDisplayMode.cs index fc64d497f..0b6f471bb 100644 --- a/Assembly-CSharp/Verse/TemperatureDisplayMode.cs +++ b/Assembly-CSharp/Verse/TemperatureDisplayMode.cs @@ -1,11 +1,9 @@ -using System; - namespace Verse { public enum TemperatureDisplayMode : byte { - Celsius, - Fahrenheit, - Kelvin + Celsius = 0, + Fahrenheit = 1, + Kelvin = 2 } } diff --git a/Assembly-CSharp/Verse/TemperatureDisplayModeExtension.cs b/Assembly-CSharp/Verse/TemperatureDisplayModeExtension.cs index 71bf4f65d..cc1bf1ec1 100644 --- a/Assembly-CSharp/Verse/TemperatureDisplayModeExtension.cs +++ b/Assembly-CSharp/Verse/TemperatureDisplayModeExtension.cs @@ -9,14 +9,22 @@ public static string ToStringHuman(this TemperatureDisplayMode mode) switch (mode) { case TemperatureDisplayMode.Celsius: + { return "Celsius".Translate(); + } case TemperatureDisplayMode.Fahrenheit: + { return "Fahrenheit".Translate(); + } case TemperatureDisplayMode.Kelvin: + { return "Kelvin".Translate(); + } default: + { throw new NotImplementedException(); } + } } } } diff --git a/Assembly-CSharp/Verse/TemperatureInjuryStage.cs b/Assembly-CSharp/Verse/TemperatureInjuryStage.cs index 7497e4e36..d075d05c4 100644 --- a/Assembly-CSharp/Verse/TemperatureInjuryStage.cs +++ b/Assembly-CSharp/Verse/TemperatureInjuryStage.cs @@ -1,14 +1,12 @@ -using System; - namespace Verse { public enum TemperatureInjuryStage : byte { - Hidden, - Initial, - Minor, - Serious, - Extreme, - Deadly + Hidden = 0, + Initial = 1, + Minor = 2, + Serious = 3, + Extreme = 4, + Deadly = 5 } } diff --git a/Assembly-CSharp/Verse/TemperatureSaveLoad.cs b/Assembly-CSharp/Verse/TemperatureSaveLoad.cs index 157ee88f2..40bccc044 100644 --- a/Assembly-CSharp/Verse/TemperatureSaveLoad.cs +++ b/Assembly-CSharp/Verse/TemperatureSaveLoad.cs @@ -27,25 +27,26 @@ public void DoExposeWork() { tempGrid[i] = num2; } - foreach (Region current in this.map.regionGrid.AllRegions_NoRebuild_InvalidAllowed) + foreach (Region item in this.map.regionGrid.AllRegions_NoRebuild_InvalidAllowed) { - if (current.Room != null) + if (item.Room != null) { - ushort num3 = this.TempFloatToShort(current.Room.Temperature); - foreach (IntVec3 current2 in current.Cells) + ushort num3 = this.TempFloatToShort(item.Room.Temperature); + foreach (IntVec3 cell in item.Cells) { - tempGrid[this.map.cellIndices.CellToIndex(current2)] = num3; + tempGrid[this.map.cellIndices.CellToIndex(cell)] = num3; } } } - compressedString = GridSaveUtility.CompressedStringForShortGrid((IntVec3 c) => tempGrid[this.map.cellIndices.CellToIndex(c)], this.map); + compressedString = GridSaveUtility.CompressedStringForShortGrid((Func)((IntVec3 c) => tempGrid[this.map.cellIndices.CellToIndex(c)]), this.map); } - Scribe_Values.Look(ref compressedString, "temperatures", null, false); + Scribe_Values.Look(ref compressedString, "temperatures", (string)null, false); if (Scribe.mode == LoadSaveMode.LoadingVars) { this.tempGrid = new ushort[this.map.cellIndices.NumGridCells]; - foreach (GridSaveUtility.LoadedGridShort current3 in GridSaveUtility.LoadedUShortGrid(compressedString, this.map)) + foreach (GridSaveUtility.LoadedGridShort item2 in GridSaveUtility.LoadedUShortGrid(compressedString, this.map)) { + GridSaveUtility.LoadedGridShort current3 = item2; this.tempGrid[this.map.cellIndices.CellToIndex(current3.cell)] = current3.val; } } @@ -56,11 +57,11 @@ public void ApplyLoadedDataToRegions() if (this.tempGrid != null) { CellIndices cellIndices = this.map.cellIndices; - foreach (Region current in this.map.regionGrid.AllRegions_NoRebuild_InvalidAllowed) + foreach (Region item in this.map.regionGrid.AllRegions_NoRebuild_InvalidAllowed) { - if (current.Room != null) + if (item.Room != null) { - current.Room.Group.Temperature = this.TempShortToFloat(this.tempGrid[cellIndices.CellToIndex(current.Cells.First())]); + item.Room.Group.Temperature = this.TempShortToFloat(this.tempGrid[cellIndices.CellToIndex(item.Cells.First())]); } } this.tempGrid = null; @@ -70,13 +71,13 @@ public void ApplyLoadedDataToRegions() private ushort TempFloatToShort(float temp) { temp = Mathf.Clamp(temp, -270f, 2000f); - temp *= 16f; + temp = (float)(temp * 16.0); return (ushort)((int)temp + 32768); } private float TempShortToFloat(ushort temp) { - return ((float)temp - 32768f) / 16f; + return (float)(((float)(int)temp - 32768.0) / 16.0); } } } diff --git a/Assembly-CSharp/Verse/TemperatureTuning.cs b/Assembly-CSharp/Verse/TemperatureTuning.cs index 4f9ee4abe..fc4eb8b1a 100644 --- a/Assembly-CSharp/Verse/TemperatureTuning.cs +++ b/Assembly-CSharp/Verse/TemperatureTuning.cs @@ -1,5 +1,3 @@ -using System; - namespace Verse { public static class TemperatureTuning diff --git a/Assembly-CSharp/Verse/TerrainAffordance.cs b/Assembly-CSharp/Verse/TerrainAffordance.cs index ddd111122..cd469fdc0 100644 --- a/Assembly-CSharp/Verse/TerrainAffordance.cs +++ b/Assembly-CSharp/Verse/TerrainAffordance.cs @@ -1,15 +1,13 @@ -using System; - namespace Verse { public enum TerrainAffordance : byte { - Undefined, - Light, - Heavy, - GrowSoil, - Diggable, - SmoothHard, - SmoothableStone + Undefined = 0, + Light = 1, + Heavy = 2, + GrowSoil = 3, + Diggable = 4, + SmoothHard = 5, + SmoothableStone = 6 } } diff --git a/Assembly-CSharp/Verse/TerrainDef.cs b/Assembly-CSharp/Verse/TerrainDef.cs index 607283568..848c7f227 100644 --- a/Assembly-CSharp/Verse/TerrainDef.cs +++ b/Assembly-CSharp/Verse/TerrainDef.cs @@ -1,7 +1,6 @@ using RimWorld; using System; using System.Collections.Generic; -using System.Diagnostics; using UnityEngine; namespace Verse @@ -10,16 +9,16 @@ public class TerrainDef : BuildableDef { public enum TerrainEdgeType : byte { - Hard, - Fade, - FadeRough, - Water + Hard = 0, + Fade = 1, + FadeRough = 2, + Water = 3 } [NoTranslate] public string texturePath; - public TerrainDef.TerrainEdgeType edgeType; + public TerrainEdgeType edgeType; [NoTranslate] public string waterDepthShader; @@ -85,35 +84,43 @@ public bool IsCarpet { get { - return this.researchPrerequisites != null && this.researchPrerequisites.Contains(ResearchProjectDefOf.CarpetMaking); + return base.researchPrerequisites != null && base.researchPrerequisites.Contains(ResearchProjectDefOf.CarpetMaking); } } public override void PostLoad() { - this.placingDraggableDimensions = 2; - LongEventHandler.ExecuteWhenFinished(delegate + base.placingDraggableDimensions = 2; + LongEventHandler.ExecuteWhenFinished((Action)delegate { Shader shader = null; switch (this.edgeType) { - case TerrainDef.TerrainEdgeType.Hard: + case TerrainEdgeType.Hard: + { shader = ShaderDatabase.TerrainHard; break; - case TerrainDef.TerrainEdgeType.Fade: + } + case TerrainEdgeType.Fade: + { shader = ShaderDatabase.TerrainFade; break; - case TerrainDef.TerrainEdgeType.FadeRough: + } + case TerrainEdgeType.FadeRough: + { shader = ShaderDatabase.TerrainFadeRough; break; - case TerrainDef.TerrainEdgeType.Water: + } + case TerrainEdgeType.Water: + { shader = ShaderDatabase.TerrainWater; break; } - this.graphic = GraphicDatabase.Get(this.texturePath, shader, Vector2.one, this.color, 2000 + this.renderPrecedence); - if (shader == ShaderDatabase.TerrainFadeRough || shader == ShaderDatabase.TerrainWater) + } + base.graphic = GraphicDatabase.Get(this.texturePath, shader, Vector2.one, this.color, 2000 + this.renderPrecedence); + if ((UnityEngine.Object)shader == (UnityEngine.Object)ShaderDatabase.TerrainFadeRough || (UnityEngine.Object)shader == (UnityEngine.Object)ShaderDatabase.TerrainWater) { - this.graphic.MatSingle.SetTexture("_AlphaAddTex", TexGame.AlphaAddTex); + base.graphic.MatSingle.SetTexture("_AlphaAddTex", TexGame.AlphaAddTex); } if (!this.waterDepthShader.NullOrEmpty()) { @@ -132,14 +139,36 @@ public override void PostLoad() base.PostLoad(); } - [DebuggerHidden] public override IEnumerable ConfigErrors() { - TerrainDef.c__Iterator1E0 c__Iterator1E = new TerrainDef.c__Iterator1E0(); - c__Iterator1E.<>f__this = this; - TerrainDef.c__Iterator1E0 expr_0E = c__Iterator1E; - expr_0E.$PC = -2; - return expr_0E; + foreach (string item in base.ConfigErrors()) + { + yield return item; + } + if (this.texturePath.NullOrEmpty()) + { + yield return "missing texturePath"; + } + if (base.fertility < 0.0) + { + yield return "Terrain Def " + this + " has no fertility value set."; + } + if (this.renderPrecedence > 400) + { + yield return "Render order " + this.renderPrecedence + " is out of range (must be < 400)"; + } + if (this.terrainFilthDef != null && this.acceptTerrainSourceFilth) + { + yield return base.defName + " makes terrain filth and also accepts it."; + } + if (this.Flammable() && this.burnedDef == null) + { + yield return "flammable but burnedDef is null"; + } + if (this.burnedDef != null && this.burnedDef.Flammable()) + { + yield return "burnedDef is flammable"; + } } public static TerrainDef Named(string defName) diff --git a/Assembly-CSharp/Verse/TerrainGrid.cs b/Assembly-CSharp/Verse/TerrainGrid.cs index 513eb4861..674c249db 100644 --- a/Assembly-CSharp/Verse/TerrainGrid.cs +++ b/Assembly-CSharp/Verse/TerrainGrid.cs @@ -39,37 +39,39 @@ public void SetTerrain(IntVec3 c, TerrainDef newTerr) if (newTerr == null) { Log.Error("Tried to set terrain at " + c + " to null."); - return; } - if (Current.ProgramState == ProgramState.Playing) - { - Designation designation = this.map.designationManager.DesignationAt(c, DesignationDefOf.SmoothFloor); - if (designation != null) - { - designation.Delete(); - } - } - int num = this.map.cellIndices.CellToIndex(c); - if (newTerr.layerable) + else { - if (this.underGrid[num] == null) + if (Current.ProgramState == ProgramState.Playing) { - if (this.topGrid[num].passability != Traversability.Impassable) + Designation designation = this.map.designationManager.DesignationAt(c, DesignationDefOf.SmoothFloor); + if (designation != null) { - this.underGrid[num] = this.topGrid[num]; + designation.Delete(); } - else + } + int num = this.map.cellIndices.CellToIndex(c); + if (newTerr.layerable) + { + if (this.underGrid[num] == null) { - this.underGrid[num] = TerrainDefOf.Sand; + if (this.topGrid[num].passability != Traversability.Impassable) + { + this.underGrid[num] = this.topGrid[num]; + } + else + { + this.underGrid[num] = TerrainDefOf.Sand; + } } } + else + { + this.underGrid[num] = null; + } + this.topGrid[num] = newTerr; + this.DoTerrainChangedEffects(c); } - else - { - this.underGrid[num] = null; - } - this.topGrid[num] = newTerr; - this.DoTerrainChangedEffects(c); } public void RemoveTopLayer(IntVec3 c, bool doLeavings = true) @@ -97,11 +99,11 @@ private void DoTerrainChangedEffects(IntVec3 c) { this.map.mapDrawer.MapMeshDirty(c, MapMeshFlag.Terrain, true, false); List thingList = c.GetThingList(this.map); - for (int i = thingList.Count - 1; i >= 0; i--) + for (int num = thingList.Count - 1; num >= 0; num--) { - if (thingList[i].def.category == ThingCategory.Plant && this.map.fertilityGrid.FertilityAt(c) < thingList[i].def.plant.fertilityMin) + if (thingList[num].def.category == ThingCategory.Plant && this.map.fertilityGrid.FertilityAt(c) < thingList[num].def.plant.fertilityMin) { - thingList[i].Destroy(DestroyMode.Vanish); + thingList[num].Destroy(DestroyMode.Vanish); } } this.map.pathGrid.RecalculatePerceivedPathCostAt(c); @@ -123,44 +125,31 @@ private void ExposeTerrainGrid(TerrainDef[] grid, string label) string compressedString = string.Empty; if (Scribe.mode == LoadSaveMode.Saving) { - compressedString = GridSaveUtility.CompressedStringForShortGrid(delegate(IntVec3 c) + compressedString = GridSaveUtility.CompressedStringForShortGrid((Func)delegate(IntVec3 c) { TerrainDef terrainDef2 = grid[this.map.cellIndices.CellToIndex(c)]; - return (terrainDef2 == null) ? 0 : terrainDef2.shortHash; + return (ushort)((terrainDef2 != null) ? terrainDef2.shortHash : 0); }, this.map); } - Scribe_Values.Look(ref compressedString, label, null, false); + Scribe_Values.Look(ref compressedString, label, (string)null, false); if (Scribe.mode == LoadSaveMode.LoadingVars) { Dictionary dictionary = new Dictionary(); - foreach (TerrainDef current in DefDatabase.AllDefs) + foreach (TerrainDef allDef in DefDatabase.AllDefs) { - dictionary.Add(current.shortHash, current); + dictionary.Add(allDef.shortHash, allDef); } - foreach (GridSaveUtility.LoadedGridShort current2 in GridSaveUtility.LoadedUShortGrid(compressedString, this.map)) + foreach (GridSaveUtility.LoadedGridShort item in GridSaveUtility.LoadedUShortGrid(compressedString, this.map)) { + GridSaveUtility.LoadedGridShort current2 = item; TerrainDef terrainDef = null; try { - if (current2.val == 0) - { - terrainDef = null; - } - else - { - terrainDef = dictionary[current2.val]; - } + terrainDef = ((current2.val != 0) ? dictionary[current2.val] : null); } catch (KeyNotFoundException) { - Log.Error(string.Concat(new object[] - { - "Did not find terrain def with short hash ", - current2.val, - " for cell ", - current2.cell, - "." - })); + Log.Error("Did not find terrain def with short hash " + current2.val + " for cell " + current2.cell + "."); terrainDef = TerrainDefOf.Sand; dictionary.Add(current2.val, terrainDef); } diff --git a/Assembly-CSharp/Verse/TexButton.cs b/Assembly-CSharp/Verse/TexButton.cs index 45ea93f98..8cba97c01 100644 --- a/Assembly-CSharp/Verse/TexButton.cs +++ b/Assembly-CSharp/Verse/TexButton.cs @@ -1,4 +1,3 @@ -using System; using UnityEngine; namespace Verse @@ -128,7 +127,7 @@ internal class TexButton public static readonly Texture2D ExpandingIcons = ContentFinder.Get("UI/Buttons/ExpandingIcons", true); - public static readonly Texture2D[] SpeedButtonTextures = new Texture2D[] + public static readonly Texture2D[] SpeedButtonTextures = new Texture2D[5] { ContentFinder.Get("UI/TimeControls/TimeSpeedButton_Pause", true), ContentFinder.Get("UI/TimeControls/TimeSpeedButton_Normal", true), diff --git a/Assembly-CSharp/Verse/TexGame.cs b/Assembly-CSharp/Verse/TexGame.cs index 75224023f..0dab53535 100644 --- a/Assembly-CSharp/Verse/TexGame.cs +++ b/Assembly-CSharp/Verse/TexGame.cs @@ -1,4 +1,3 @@ -using System; using UnityEngine; namespace Verse diff --git a/Assembly-CSharp/Verse/TexUI.cs b/Assembly-CSharp/Verse/TexUI.cs index 1b0647f19..85c77d4f9 100644 --- a/Assembly-CSharp/Verse/TexUI.cs +++ b/Assembly-CSharp/Verse/TexUI.cs @@ -1,4 +1,3 @@ -using System; using UnityEngine; namespace Verse @@ -24,74 +23,42 @@ public static class TexUI public static readonly Texture2D RotRightTex = ContentFinder.Get("UI/Widgets/RotRight", true); - public static readonly Texture2D GrayBg; + public static readonly Texture2D GrayBg = SolidColorMaterials.NewSolidColorTexture(new ColorInt(51, 63, 51, 200).ToColor); - public static readonly Color AvailResearchColor; + public static readonly Color AvailResearchColor = new ColorInt(32, 32, 32, 255).ToColor; - public static readonly Color ActiveResearchColor; + public static readonly Color ActiveResearchColor = new ColorInt(0, 64, 64, 255).ToColor; - public static readonly Color FinishedResearchColor; + public static readonly Color FinishedResearchColor = new ColorInt(0, 64, 16, 255).ToColor; - public static readonly Color LockedResearchColor; + public static readonly Color LockedResearchColor = new ColorInt(42, 42, 42, 255).ToColor; - public static readonly Color RelatedResearchColor; + public static readonly Color RelatedResearchColor = new ColorInt(0, 0, 0, 255).ToColor; - public static readonly Color HighlightBgResearchColor; + public static readonly Color HighlightBgResearchColor = new ColorInt(30, 30, 30, 255).ToColor; - public static readonly Color HighlightBorderResearchColor; + public static readonly Color HighlightBorderResearchColor = new ColorInt(160, 160, 160, 255).ToColor; - public static readonly Color DefaultBorderResearchColor; + public static readonly Color DefaultBorderResearchColor = new ColorInt(80, 80, 80, 255).ToColor; - public static readonly Color DefaultLineResearchColor; + public static readonly Color DefaultLineResearchColor = new ColorInt(60, 60, 60, 255).ToColor; - public static readonly Color HighlightLineResearchColor; + public static readonly Color HighlightLineResearchColor = new ColorInt(51, 205, 217, 255).ToColor; - public static readonly Texture2D FastFillTex; + public static readonly Texture2D FastFillTex = Texture2D.whiteTexture; - public static readonly GUIStyle FastFillStyle; - - public static readonly Texture2D TextBGBlack; + public static readonly GUIStyle FastFillStyle = new GUIStyle + { + normal = new GUIStyleState + { + background = TexUI.FastFillTex + } + }; - public static readonly Texture2D GrayTextBG; + public static readonly Texture2D TextBGBlack = ContentFinder.Get("UI/Widgets/TextBGBlack", true); - public static readonly Texture2D FloatMenuOptionBG; + public static readonly Texture2D GrayTextBG = ContentFinder.Get("UI/Overlays/GrayTextBG", true); - static TexUI() - { - // Note: this type is marked as 'beforefieldinit'. - ColorInt colorInt = new ColorInt(51, 63, 51, 200); - TexUI.GrayBg = SolidColorMaterials.NewSolidColorTexture(colorInt.ToColor); - ColorInt colorInt2 = new ColorInt(32, 32, 32, 255); - TexUI.AvailResearchColor = colorInt2.ToColor; - ColorInt colorInt3 = new ColorInt(0, 64, 64, 255); - TexUI.ActiveResearchColor = colorInt3.ToColor; - ColorInt colorInt4 = new ColorInt(0, 64, 16, 255); - TexUI.FinishedResearchColor = colorInt4.ToColor; - ColorInt colorInt5 = new ColorInt(42, 42, 42, 255); - TexUI.LockedResearchColor = colorInt5.ToColor; - ColorInt colorInt6 = new ColorInt(0, 0, 0, 255); - TexUI.RelatedResearchColor = colorInt6.ToColor; - ColorInt colorInt7 = new ColorInt(30, 30, 30, 255); - TexUI.HighlightBgResearchColor = colorInt7.ToColor; - ColorInt colorInt8 = new ColorInt(160, 160, 160, 255); - TexUI.HighlightBorderResearchColor = colorInt8.ToColor; - ColorInt colorInt9 = new ColorInt(80, 80, 80, 255); - TexUI.DefaultBorderResearchColor = colorInt9.ToColor; - ColorInt colorInt10 = new ColorInt(60, 60, 60, 255); - TexUI.DefaultLineResearchColor = colorInt10.ToColor; - ColorInt colorInt11 = new ColorInt(51, 205, 217, 255); - TexUI.HighlightLineResearchColor = colorInt11.ToColor; - TexUI.FastFillTex = Texture2D.whiteTexture; - TexUI.FastFillStyle = new GUIStyle - { - normal = new GUIStyleState - { - background = TexUI.FastFillTex - } - }; - TexUI.TextBGBlack = ContentFinder.Get("UI/Widgets/TextBGBlack", true); - TexUI.GrayTextBG = ContentFinder.Get("UI/Overlays/GrayTextBG", true); - TexUI.FloatMenuOptionBG = ContentFinder.Get("UI/Widgets/FloatMenuOptionBG", true); - } + public static readonly Texture2D FloatMenuOptionBG = ContentFinder.Get("UI/Widgets/FloatMenuOptionBG", true); } } diff --git a/Assembly-CSharp/Verse/Text.cs b/Assembly-CSharp/Verse/Text.cs index fe1ec1001..48ed1e97e 100644 --- a/Assembly-CSharp/Verse/Text.cs +++ b/Assembly-CSharp/Verse/Text.cs @@ -1,5 +1,4 @@ using System; -using System.Collections; using UnityEngine; namespace Verse @@ -73,7 +72,7 @@ public static float LineHeight { get { - return Text.lineHeights[(int)Text.Font]; + return Text.lineHeights[(uint)Text.Font]; } } @@ -81,21 +80,29 @@ internal static GUIStyle CurFontStyle { get { - GUIStyle gUIStyle; + GUIStyle gUIStyle = null; switch (Text.fontInt) { case GameFont.Tiny: + { gUIStyle = Text.fontStyles[0]; break; + } case GameFont.Small: + { gUIStyle = Text.fontStyles[1]; break; + } case GameFont.Medium: + { gUIStyle = Text.fontStyles[2]; break; + } default: + { throw new NotImplementedException(); } + } gUIStyle.alignment = Text.anchorInt; gUIStyle.wordWrap = Text.wordWrapInt; return gUIStyle; @@ -109,14 +116,22 @@ public static GUIStyle CurTextFieldStyle switch (Text.fontInt) { case GameFont.Tiny: + { return Text.textFieldStyles[0]; + } case GameFont.Small: + { return Text.textFieldStyles[1]; + } case GameFont.Medium: + { return Text.textFieldStyles[2]; + } default: + { throw new NotImplementedException(); } + } } } @@ -127,14 +142,22 @@ public static GUIStyle CurTextAreaStyle switch (Text.fontInt) { case GameFont.Tiny: + { return Text.textAreaStyles[0]; + } case GameFont.Small: + { return Text.textAreaStyles[1]; + } case GameFont.Medium: + { return Text.textAreaStyles[2]; + } default: + { throw new NotImplementedException(); } + } } } @@ -145,14 +168,22 @@ public static GUIStyle CurTextAreaReadOnlyStyle switch (Text.fontInt) { case GameFont.Tiny: + { return Text.textAreaReadOnlyStyles[0]; + } case GameFont.Small: + { return Text.textAreaReadOnlyStyles[1]; + } case GameFont.Medium: + { return Text.textAreaReadOnlyStyles[2]; + } default: + { throw new NotImplementedException(); } + } } } @@ -204,16 +235,11 @@ static Text() } GUI.skin.settings.doubleClickSelectsWord = true; int num = 0; - using (IEnumerator enumerator = Enum.GetValues(typeof(GameFont)).GetEnumerator()) + foreach (byte value in Enum.GetValues(typeof(GameFont))) { - while (enumerator.MoveNext()) - { - GameFont font4 = (GameFont)((byte)enumerator.Current); - Text.Font = font4; - float num2 = Text.CalcHeight("W", 999f); - Text.lineHeights[num] = num2; - num++; - } + Text.Font = (GameFont)value; + float num2 = Text.lineHeights[num] = Text.CalcHeight("W", 999f); + num++; } Text.Font = GameFont.Small; } @@ -237,7 +263,7 @@ internal static void StartOfOnGUI() Log.ErrorOnce("Word wrap was false at end of frame.", 764362); Text.WordWrap = true; } - if (Text.Anchor != TextAnchor.UpperLeft) + if (Text.Anchor != 0) { Log.ErrorOnce("Alignment was " + Text.Anchor + " at end of frame.", 15558); Text.Anchor = TextAnchor.UpperLeft; diff --git a/Assembly-CSharp/Verse/TextureAndColor.cs b/Assembly-CSharp/Verse/TextureAndColor.cs index 2112f76e2..9baae6be4 100644 --- a/Assembly-CSharp/Verse/TextureAndColor.cs +++ b/Assembly-CSharp/Verse/TextureAndColor.cs @@ -1,4 +1,3 @@ -using System; using UnityEngine; namespace Verse @@ -13,7 +12,7 @@ public bool HasValue { get { - return this.texture != null; + return (Object)this.texture != (Object)null; } } diff --git a/Assembly-CSharp/Verse/Thing.cs b/Assembly-CSharp/Verse/Thing.cs index e35ebe46f..0a74b49bd 100644 --- a/Assembly-CSharp/Verse/Thing.cs +++ b/Assembly-CSharp/Verse/Thing.cs @@ -1,7 +1,6 @@ using RimWorld; using System; using System.Collections.Generic; -using System.Diagnostics; using System.Linq; using System.Text.RegularExpressions; using UnityEngine; @@ -21,7 +20,7 @@ public class Thing : Entity, IExposable, ILoadReferenceable, ISelectable public int thingIDNumber = -1; - private sbyte mapIndexOrState = -1; + private sbyte mapIndexOrState = (sbyte)(-1); private IntVec3 positionInt = IntVec3.Invalid; @@ -73,7 +72,7 @@ public bool FlammableNow { get { - if (this.GetStatValue(StatDefOf.Flammability, true) < 0.01f) + if (this.GetStatValue(StatDefOf.Flammability, true) < 0.0099999997764825821) { return false; } @@ -107,7 +106,7 @@ public bool Destroyed { get { - return (int)this.mapIndexOrState == -2 || (int)this.mapIndexOrState == -3; + return this.mapIndexOrState == -2 || this.mapIndexOrState == -3; } } @@ -115,7 +114,7 @@ public bool Discarded { get { - return (int)this.mapIndexOrState == -3; + return this.mapIndexOrState == -3; } } @@ -123,7 +122,7 @@ public bool Spawned { get { - return (int)this.mapIndexOrState >= 0; + return this.mapIndexOrState >= 0; } } @@ -131,7 +130,15 @@ public bool SpawnedOrAnyParentSpawned { get { - return this.Spawned || (this.ParentHolder != null && ThingOwnerUtility.SpawnedOrAnyParentSpawned(this.ParentHolder)); + if (this.Spawned) + { + return true; + } + if (this.ParentHolder != null) + { + return ThingOwnerUtility.SpawnedOrAnyParentSpawned(this.ParentHolder); + } + return false; } } @@ -139,9 +146,9 @@ public Map Map { get { - if ((int)this.mapIndexOrState >= 0) + if (this.mapIndexOrState >= 0) { - return Find.Maps[(int)this.mapIndexOrState]; + return Find.Maps[this.mapIndexOrState]; } return null; } @@ -171,29 +178,28 @@ public IntVec3 Position } set { - if (value == this.positionInt) - { - return; - } - if (this.Spawned) + if (!(value == this.positionInt)) { - if (this.def.AffectsRegions) + if (this.Spawned) { - Log.Warning("Changed position of a spawned thing which affects regions. This is not supported."); + if (this.def.AffectsRegions) + { + Log.Warning("Changed position of a spawned thing which affects regions. This is not supported."); + } + this.DirtyMapMesh(this.Map); + RegionListersUpdater.DeregisterInRegions(this, this.Map); + this.Map.thingGrid.Deregister(this, false); } - this.DirtyMapMesh(this.Map); - RegionListersUpdater.DeregisterInRegions(this, this.Map); - this.Map.thingGrid.Deregister(this, false); - } - this.positionInt = value; - if (this.Spawned) - { - this.Map.thingGrid.Register(this); - RegionListersUpdater.RegisterInRegions(this, this.Map); - this.DirtyMapMesh(this.Map); - if (this.def.AffectsReachability) + this.positionInt = value; + if (this.Spawned) { - this.Map.reachability.ClearCache(); + this.Map.thingGrid.Register(this); + RegionListersUpdater.RegisterInRegions(this, this.Map); + this.DirtyMapMesh(this.Map); + if (this.def.AffectsReachability) + { + this.Map.reachability.ClearCache(); + } } } } @@ -224,27 +230,28 @@ public Rot4 Rotation } set { - if (value == this.rotationInt) - { - return; - } - if (this.Spawned && (this.def.size.x != 1 || this.def.size.z != 1)) + if (!(value == this.rotationInt)) { - if (this.def.AffectsRegions) + if (this.Spawned && (this.def.size.x != 1 || this.def.size.z != 1)) { - Log.Warning("Changed rotation of a spawned non-single-cell thing which affects regions. This is not supported."); + if (this.def.AffectsRegions) + { + Log.Warning("Changed rotation of a spawned non-single-cell thing which affects regions. This is not supported."); + } + RegionListersUpdater.DeregisterInRegions(this, this.Map); + this.Map.thingGrid.Deregister(this, false); } - RegionListersUpdater.DeregisterInRegions(this, this.Map); - this.Map.thingGrid.Deregister(this, false); - } - this.rotationInt = value; - if (this.Spawned && (this.def.size.x != 1 || this.def.size.z != 1)) - { - this.Map.thingGrid.Register(this); - RegionListersUpdater.RegisterInRegions(this, this.Map); - if (this.def.AffectsReachability) + this.rotationInt = value; + if (this.Spawned) { - this.Map.reachability.ClearCache(); + if (this.def.size.x == 1 && this.def.size.z == 1) + return; + this.Map.thingGrid.Register(this); + RegionListersUpdater.RegisterInRegions(this, this.Map); + if (this.def.AffectsReachability) + { + this.Map.reachability.ClearCache(); + } } } } @@ -262,17 +269,17 @@ public IThingHolder ParentHolder { get { - IThingHolder arg_1E_0; + object result; if (this.holdingOwner != null) { IThingHolder owner = this.holdingOwner.Owner; - arg_1E_0 = owner; + result = owner; } else { - arg_1E_0 = null; + result = null; } - return arg_1E_0; + return (IThingHolder)result; } } @@ -360,7 +367,11 @@ public virtual bool IngestibleNow { get { - return !this.IsBurning() && this.def.IsIngestible; + if (this.IsBurning()) + { + return false; + } + return this.def.IsIngestible; } } @@ -376,10 +387,7 @@ public virtual IEnumerable SpecialDisplayStats { get { - Thing.<>c__Iterator139 <>c__Iterator = new Thing.<>c__Iterator139(); - Thing.<>c__Iterator139 expr_07 = <>c__Iterator; - expr_07.$PC = -2; - return expr_07; + yield break; } } @@ -432,7 +440,7 @@ public float AmbientTemperature { return GenTemperature.GetTemperatureForCell(this.Position, this.Map); } - float result; + float result = default(float); if (this.ParentHolder != null && ThingOwnerUtility.TryGetFixedTemperature(this.ParentHolder, out result)) { return result; @@ -489,14 +497,7 @@ public virtual Color DrawColor } set { - Log.Error(string.Concat(new object[] - { - "Cannot set instance color on non-ThingWithComps ", - this.LabelCap, - " at ", - this.Position, - "." - })); + Log.Error("Cannot set instance color on non-ThingWithComps " + this.LabelCap + " at " + this.Position + "."); } } @@ -519,20 +520,13 @@ public static int IDNumberFromThingID(string thingID) try { result = Convert.ToInt32(value); + return result; } catch (Exception ex) { - Log.Error(string.Concat(new string[] - { - "Could not convert id number from thingID=", - thingID, - ", numString=", - value, - " Exception=", - ex.ToString() - })); + Log.Error("Could not convert id number from thingID=" + thingID + ", numString=" + value + " Exception=" + ex.ToString()); + return result; } - return result; } public virtual void PostMake() @@ -553,15 +547,8 @@ public override void SpawnSetup(Map map, bool respawningAfterLoad) { if (this.Destroyed) { - Log.Error(string.Concat(new object[] - { - "Spawning destroyed thing ", - this, - " at ", - this.Position, - ". Correcting." - })); - this.mapIndexOrState = -1; + Log.Error("Spawning destroyed thing " + this + " at " + this.Position + ". Correcting."); + this.mapIndexOrState = (sbyte)(-1); if (this.HitPoints <= 0 && this.def.useHitPoints) { this.HitPoints = 1; @@ -569,97 +556,86 @@ public override void SpawnSetup(Map map, bool respawningAfterLoad) } if (this.Spawned) { - Log.Error(string.Concat(new object[] - { - "Tried to spawn already-spawned thing ", - this, - " at ", - this.Position - })); - return; + Log.Error("Tried to spawn already-spawned thing " + this + " at " + this.Position); } - int num = Find.Maps.IndexOf(map); - if (num < 0) + else { - Log.Error("Tried to spawn thing " + this + ", but the map provided does not exist."); - return; - } - if (this.stackCount > this.def.stackLimit) - { - Log.Error(string.Concat(new object[] + int num = Find.Maps.IndexOf(map); + if (num < 0) { - "Spawned ", - this, - " with stackCount ", - this.stackCount, - " but stackLimit is ", - this.def.stackLimit, - ". Truncating." - })); - this.stackCount = this.def.stackLimit; - } - this.mapIndexOrState = (sbyte)num; - RegionListersUpdater.RegisterInRegions(this, map); - if (!map.spawnedThings.TryAdd(this, false)) - { - Log.Error("Couldn't add thing " + this + " to spawned things."); - } - map.listerThings.Add(this); - map.thingGrid.Register(this); - if (Find.TickManager != null) - { - Find.TickManager.RegisterAllTickabilityFor(this); - } - this.DirtyMapMesh(map); - if (this.def.drawerType != DrawerType.MapMeshOnly) - { - map.dynamicDrawManager.RegisterDrawable(this); - } - map.tooltipGiverList.Notify_ThingSpawned(this); - if (this.def.graphicData != null && this.def.graphicData.Linked) - { - map.linkGrid.Notify_LinkerCreatedOrDestroyed(this); - map.mapDrawer.MapMeshDirty(this.Position, MapMeshFlag.Things, true, false); - } - if (!this.def.CanOverlapZones) - { - map.zoneManager.Notify_NoZoneOverlapThingSpawned(this); - } - if (this.def.AffectsRegions) - { - map.regionDirtyer.Notify_ThingAffectingRegionsSpawned(this); - } - if (this.def.pathCost != 0 || this.def.passability == Traversability.Impassable) - { - map.pathGrid.RecalculatePerceivedPathCostUnderThing(this); - } - if (this.def.AffectsReachability) - { - map.reachability.ClearCache(); - } - map.coverGrid.Register(this); - if (this.def.category == ThingCategory.Item) - { - map.listerHaulables.Notify_Spawned(this); - } - map.attackTargetsCache.Notify_ThingSpawned(this); - Region validRegionAt_NoRebuild = map.regionGrid.GetValidRegionAt_NoRebuild(this.Position); - Room room = (validRegionAt_NoRebuild != null) ? validRegionAt_NoRebuild.Room : null; - if (room != null) - { - room.Notify_ContainedThingSpawnedOrDespawned(this); - } - StealAIDebugDrawer.Notify_ThingChanged(this); - if (this is IThingHolder && Find.ColonistBar != null) - { - Find.ColonistBar.MarkColonistsDirty(); - } - if (this.def.category == ThingCategory.Item) - { - SlotGroup slotGroup = this.Position.GetSlotGroup(map); - if (slotGroup != null && slotGroup.parent != null) + Log.Error("Tried to spawn thing " + this + ", but the map provided does not exist."); + } + else { - slotGroup.parent.Notify_ReceivedThing(this); + if (this.stackCount > this.def.stackLimit) + { + Log.Error("Spawned " + this + " with stackCount " + this.stackCount + " but stackLimit is " + this.def.stackLimit + ". Truncating."); + this.stackCount = this.def.stackLimit; + } + this.mapIndexOrState = (sbyte)num; + RegionListersUpdater.RegisterInRegions(this, map); + if (!map.spawnedThings.TryAdd(this, false)) + { + Log.Error("Couldn't add thing " + this + " to spawned things."); + } + map.listerThings.Add(this); + map.thingGrid.Register(this); + if (Find.TickManager != null) + { + Find.TickManager.RegisterAllTickabilityFor(this); + } + this.DirtyMapMesh(map); + if (this.def.drawerType != DrawerType.MapMeshOnly) + { + map.dynamicDrawManager.RegisterDrawable(this); + } + map.tooltipGiverList.Notify_ThingSpawned(this); + if (this.def.graphicData != null && this.def.graphicData.Linked) + { + map.linkGrid.Notify_LinkerCreatedOrDestroyed(this); + map.mapDrawer.MapMeshDirty(this.Position, MapMeshFlag.Things, true, false); + } + if (!this.def.CanOverlapZones) + { + map.zoneManager.Notify_NoZoneOverlapThingSpawned(this); + } + if (this.def.AffectsRegions) + { + map.regionDirtyer.Notify_ThingAffectingRegionsSpawned(this); + } + if (this.def.pathCost != 0 || this.def.passability == Traversability.Impassable) + { + map.pathGrid.RecalculatePerceivedPathCostUnderThing(this); + } + if (this.def.AffectsReachability) + { + map.reachability.ClearCache(); + } + map.coverGrid.Register(this); + if (this.def.category == ThingCategory.Item) + { + map.listerHaulables.Notify_Spawned(this); + } + map.attackTargetsCache.Notify_ThingSpawned(this); + Region validRegionAt_NoRebuild = map.regionGrid.GetValidRegionAt_NoRebuild(this.Position); + Room room = (validRegionAt_NoRebuild != null) ? validRegionAt_NoRebuild.Room : null; + if (room != null) + { + room.Notify_ContainedThingSpawnedOrDespawned(this); + } + StealAIDebugDrawer.Notify_ThingChanged(this); + if (this is IThingHolder && Find.ColonistBar != null) + { + Find.ColonistBar.MarkColonistsDirty(); + } + if (this.def.category == ThingCategory.Item) + { + SlotGroup slotGroup = this.Position.GetSlotGroup(map); + if (slotGroup != null && slotGroup.parent != null) + { + slotGroup.parent.Notify_ReceivedThing(this); + } + } } } } @@ -669,72 +645,73 @@ public override void DeSpawn() if (this.Destroyed) { Log.Error("Tried to despawn " + this + " which is already destroyed."); - return; } - if (!this.Spawned) + else if (!this.Spawned) { Log.Error("Tried to despawn " + this + " which is not spawned."); - return; - } - Map map = this.Map; - RegionListersUpdater.DeregisterInRegions(this, map); - map.spawnedThings.Remove(this); - map.listerThings.Remove(this); - map.thingGrid.Deregister(this, false); - map.coverGrid.DeRegister(this); - map.tooltipGiverList.Notify_ThingDespawned(this); - if (this.def.graphicData != null && this.def.graphicData.Linked) - { - map.linkGrid.Notify_LinkerCreatedOrDestroyed(this); - map.mapDrawer.MapMeshDirty(this.Position, MapMeshFlag.Things, true, false); - } - Find.Selector.Deselect(this); - this.DirtyMapMesh(map); - if (this.def.drawerType != DrawerType.MapMeshOnly) - { - map.dynamicDrawManager.DeRegisterDrawable(this); - } - Region validRegionAt_NoRebuild = map.regionGrid.GetValidRegionAt_NoRebuild(this.Position); - Room room = (validRegionAt_NoRebuild != null) ? validRegionAt_NoRebuild.Room : null; - if (room != null) - { - room.Notify_ContainedThingSpawnedOrDespawned(this); - } - if (this.def.AffectsRegions) - { - map.regionDirtyer.Notify_ThingAffectingRegionsDespawned(this); } - if (this.def.pathCost != 0 || this.def.passability == Traversability.Impassable) + else { - map.pathGrid.RecalculatePerceivedPathCostUnderThing(this); - } - if (this.def.AffectsReachability) - { - map.reachability.ClearCache(); - } - Find.TickManager.DeRegisterAllTickabilityFor(this); - this.mapIndexOrState = -1; - if (this.def.category == ThingCategory.Item) - { - map.listerHaulables.Notify_DeSpawned(this); - } - map.attackTargetsCache.Notify_ThingDespawned(this); - StealAIDebugDrawer.Notify_ThingChanged(this); - if (this is IThingHolder && Find.ColonistBar != null) - { - Find.ColonistBar.MarkColonistsDirty(); - } - if (this.def.category == ThingCategory.Item) - { - SlotGroup slotGroup = this.Position.GetSlotGroup(map); - if (slotGroup != null && slotGroup.parent != null) + Map map = this.Map; + RegionListersUpdater.DeregisterInRegions(this, map); + map.spawnedThings.Remove(this); + map.listerThings.Remove(this); + map.thingGrid.Deregister(this, false); + map.coverGrid.DeRegister(this); + map.tooltipGiverList.Notify_ThingDespawned(this); + if (this.def.graphicData != null && this.def.graphicData.Linked) + { + map.linkGrid.Notify_LinkerCreatedOrDestroyed(this); + map.mapDrawer.MapMeshDirty(this.Position, MapMeshFlag.Things, true, false); + } + Find.Selector.Deselect(this); + this.DirtyMapMesh(map); + if (this.def.drawerType != DrawerType.MapMeshOnly) + { + map.dynamicDrawManager.DeRegisterDrawable(this); + } + Region validRegionAt_NoRebuild = map.regionGrid.GetValidRegionAt_NoRebuild(this.Position); + Room room = (validRegionAt_NoRebuild != null) ? validRegionAt_NoRebuild.Room : null; + if (room != null) + { + room.Notify_ContainedThingSpawnedOrDespawned(this); + } + if (this.def.AffectsRegions) { - slotGroup.parent.Notify_LostThing(this); + map.regionDirtyer.Notify_ThingAffectingRegionsDespawned(this); + } + if (this.def.pathCost != 0 || this.def.passability == Traversability.Impassable) + { + map.pathGrid.RecalculatePerceivedPathCostUnderThing(this); + } + if (this.def.AffectsReachability) + { + map.reachability.ClearCache(); + } + Find.TickManager.DeRegisterAllTickabilityFor(this); + this.mapIndexOrState = (sbyte)(-1); + if (this.def.category == ThingCategory.Item) + { + map.listerHaulables.Notify_DeSpawned(this); + } + map.attackTargetsCache.Notify_ThingDespawned(this); + StealAIDebugDrawer.Notify_ThingChanged(this); + if (this is IThingHolder && Find.ColonistBar != null) + { + Find.ColonistBar.MarkColonistsDirty(); + } + if (this.def.category == ThingCategory.Item) + { + SlotGroup slotGroup = this.Position.GetSlotGroup(map); + if (slotGroup != null && slotGroup.parent != null) + { + slotGroup.parent.Notify_LostThing(this); + } } } } - public virtual void Kill(DamageInfo? dinfo = null) + public virtual void Kill(DamageInfo? dinfo = default(DamageInfo?)) { this.Destroy(DestroyMode.KillFinalize); } @@ -744,38 +721,39 @@ public virtual void Destroy(DestroyMode mode = DestroyMode.Vanish) if (!Thing.allowDestroyNonDestroyable && !this.def.destroyable) { Log.Error("Tried to destroy non-destroyable thing " + this); - return; } - if (this.Destroyed) + else if (this.Destroyed) { Log.Error("Tried to destroy already-destroyed thing " + this); - return; } - bool spawned = this.Spawned; - Map map = this.Map; - if (this.Spawned) + else { - this.DeSpawn(); - } - this.mapIndexOrState = -2; - if (this.def.DiscardOnDestroyed) - { - this.Discard(); - } - CompExplosive compExplosive = this.TryGetComp(); - bool flag = compExplosive != null && compExplosive.detonated; - if (spawned && !flag) - { - GenLeaving.DoLeavingsFor(this, map, mode); - } - if (this.holdingOwner != null) - { - this.holdingOwner.Notify_ContainedItemDestroyed(this); - } - this.RemoveAllReservationsAndDesignationsOnThis(); - if (!(this is Pawn)) - { - this.stackCount = 0; + bool spawned = this.Spawned; + Map map = this.Map; + if (this.Spawned) + { + this.DeSpawn(); + } + this.mapIndexOrState = (sbyte)(-2); + if (this.def.DiscardOnDestroyed) + { + this.Discard(); + } + CompExplosive compExplosive = this.TryGetComp(); + bool flag = compExplosive != null && compExplosive.detonated; + if (spawned && !flag) + { + GenLeaving.DoLeavingsFor(this, map, mode); + } + if (this.holdingOwner != null) + { + this.holdingOwner.Notify_ContainedItemDestroyed(this); + } + this.RemoveAllReservationsAndDesignationsOnThis(); + if (!(this is Pawn)) + { + this.stackCount = 0; + } } } @@ -795,44 +773,39 @@ public virtual void Notify_MyMapRemoved() { if (!ThingOwnerUtility.AnyParentIs(this)) { - this.mapIndexOrState = -3; + this.mapIndexOrState = (sbyte)(-3); } this.RemoveAllReservationsAndDesignationsOnThis(); } public void DecrementMapIndex() { - if ((int)this.mapIndexOrState <= 0) + if (this.mapIndexOrState <= 0) { - Log.Warning(string.Concat(new object[] - { - "Tried to decrement map index for ", - this, - ", but mapIndexOrState=", - this.mapIndexOrState - })); - return; + Log.Warning("Tried to decrement map index for " + this + ", but mapIndexOrState=" + this.mapIndexOrState); + } + else + { + this.mapIndexOrState = (sbyte)(this.mapIndexOrState - 1); } - this.mapIndexOrState -= 1; } private void RemoveAllReservationsAndDesignationsOnThis() { - if (this.def.category == ThingCategory.Mote) + if (this.def.category != ThingCategory.Mote) { - return; - } - List maps = Find.Maps; - for (int i = 0; i < maps.Count; i++) - { - maps[i].reservationManager.ReleaseAllForTarget(this); - maps[i].physicalInteractionReservationManager.ReleaseAllForTarget(this); - IAttackTarget attackTarget = this as IAttackTarget; - if (attackTarget != null) + List maps = Find.Maps; + for (int i = 0; i < maps.Count; i++) { - maps[i].attackTargetReservationManager.ReleaseAllForTarget(attackTarget); + maps[i].reservationManager.ReleaseAllForTarget(this); + maps[i].physicalInteractionReservationManager.ReleaseAllForTarget(this); + IAttackTarget attackTarget = this as IAttackTarget; + if (attackTarget != null) + { + maps[i].attackTargetReservationManager.ReleaseAllForTarget(attackTarget); + } + maps[i].designationManager.RemoveAllDesignationsOn(this, false); } - maps[i].designationManager.RemoveAllDesignationsOn(this, false); } } @@ -842,13 +815,13 @@ public virtual void ExposeData() if (this.def.HasThingIDNumber) { string thingID = this.ThingID; - Scribe_Values.Look(ref thingID, "id", null, false); + Scribe_Values.Look(ref thingID, "id", (string)null, false); this.ThingID = thingID; } - Scribe_Values.Look(ref this.mapIndexOrState, "map", -1, false); - if (Scribe.mode == LoadSaveMode.LoadingVars && (int)this.mapIndexOrState >= 0) + Scribe_Values.Look(ref this.mapIndexOrState, "map", (sbyte)(-1), false); + if (Scribe.mode == LoadSaveMode.LoadingVars && this.mapIndexOrState >= 0) { - this.mapIndexOrState = -1; + this.mapIndexOrState = (sbyte)(-1); } Scribe_Values.Look(ref this.positionInt, "pos", IntVec3.Invalid, false); Scribe_Values.Look(ref this.rotationInt, "rot", Rot4.North, false); @@ -856,24 +829,23 @@ public virtual void ExposeData() { Scribe_Values.Look(ref this.hitPointsInt, "health", -1, false); } - bool flag = this.def.tradeability != Tradeability.Never && this.def.category == ThingCategory.Item; + bool flag = this.def.tradeability != 0 && this.def.category == ThingCategory.Item; if (this.def.stackLimit > 1 || flag) { Scribe_Values.Look(ref this.stackCount, "stackCount", 0, true); } Scribe_Defs.Look(ref this.stuffInt, "stuff"); string facID = (this.factionInt == null) ? "null" : this.factionInt.GetUniqueLoadID(); - Scribe_Values.Look(ref facID, "faction", "null", false); - if (Scribe.mode == LoadSaveMode.LoadingVars || Scribe.mode == LoadSaveMode.ResolvingCrossRefs || Scribe.mode == LoadSaveMode.PostLoadInit) + Scribe_Values.Look(ref facID, "faction", "null", false); + if (Scribe.mode != LoadSaveMode.LoadingVars && Scribe.mode != LoadSaveMode.ResolvingCrossRefs && Scribe.mode != LoadSaveMode.PostLoadInit) + return; + if (facID == "null") { - if (facID == "null") - { - this.factionInt = null; - } - else if (Find.World != null && Find.FactionManager != null) - { - this.factionInt = Find.FactionManager.AllFactions.FirstOrDefault((Faction fa) => fa.GetUniqueLoadID() == facID); - } + this.factionInt = null; + } + else if (Find.World != null && Find.FactionManager != null) + { + this.factionInt = Find.FactionManager.AllFactions.FirstOrDefault((Func)((Faction fa) => fa.GetUniqueLoadID() == facID)); } } @@ -913,7 +885,7 @@ public virtual void DrawGUIOverlay() { if (Find.CameraDriver.CurrentZoom == CameraZoomRange.Closest) { - QualityCategory cat; + QualityCategory cat = default(QualityCategory); if (this.def.stackLimit > 1) { GenMapUI.DrawThingLabel(this, this.stackCount.ToStringCached()); @@ -927,7 +899,7 @@ public virtual void DrawGUIOverlay() public virtual void DrawExtraSelectionOverlays() { - if (this.def.specialDisplayRadius > 0.1f) + if (this.def.specialDisplayRadius > 0.10000000149011612) { GenDraw.DrawRadiusRing(this.Position, this.def.specialDisplayRadius); } @@ -951,29 +923,21 @@ public virtual string GetInspectString() public virtual string GetInspectStringLowPriority() { - if (SteadyAtmosphereEffects.InDeterioratingPosition(this) && SteadyAtmosphereEffects.FinalDeteriorationRate(this) > 0.001f) + if (SteadyAtmosphereEffects.InDeterioratingPosition(this) && SteadyAtmosphereEffects.FinalDeteriorationRate(this) > 0.0010000000474974513) { return "DeterioratingDueToBeingUnroofed".Translate(); } - return null; + return (string)null; } - [DebuggerHidden] public virtual IEnumerable GetGizmos() { - Thing.c__Iterator13A c__Iterator13A = new Thing.c__Iterator13A(); - Thing.c__Iterator13A expr_07 = c__Iterator13A; - expr_07.$PC = -2; - return expr_07; + yield break; } - [DebuggerHidden] public virtual IEnumerable GetFloatMenuOptions(Pawn selPawn) { - Thing.c__Iterator13B c__Iterator13B = new Thing.c__Iterator13B(); - Thing.c__Iterator13B expr_07 = c__Iterator13B; - expr_07.$PC = -2; - return expr_07; + yield break; } public virtual IEnumerable GetInspectTabs() @@ -983,51 +947,45 @@ public virtual IEnumerable GetInspectTabs() public void TakeDamage(DamageInfo dinfo) { - if (this.Destroyed) - { - return; - } - if (dinfo.Amount == 0) - { - return; - } - if (this.def.damageMultipliers != null) + if (((!this.Destroyed) ? dinfo.Amount : 0) != 0) { - for (int i = 0; i < this.def.damageMultipliers.Count; i++) + if (this.def.damageMultipliers != null) { - if (this.def.damageMultipliers[i].damageDef == dinfo.Def) + for (int i = 0; i < this.def.damageMultipliers.Count; i++) { - int amount = Mathf.RoundToInt((float)dinfo.Amount * this.def.damageMultipliers[i].multiplier); - dinfo.SetAmount(amount); + if (this.def.damageMultipliers[i].damageDef == dinfo.Def) + { + int amount = Mathf.RoundToInt((float)dinfo.Amount * this.def.damageMultipliers[i].multiplier); + dinfo.SetAmount(amount); + } } } - } - bool flag; - this.PreApplyDamage(dinfo, out flag); - if (flag) - { - return; - } - bool spawnedOrAnyParentSpawned = this.SpawnedOrAnyParentSpawned; - Map mapHeld = this.MapHeld; - float num = dinfo.Def.Worker.Apply(dinfo, this); - if (dinfo.Def.harmsHealth && spawnedOrAnyParentSpawned) - { - mapHeld.damageWatcher.Notify_DamageTaken(this, num); - } - if (dinfo.Def.externalViolence) - { - GenLeaving.DropFilthDueToDamage(this, num); - if (dinfo.Instigator != null) + bool flag = default(bool); + this.PreApplyDamage(dinfo, out flag); + if (!flag) { - Pawn pawn = dinfo.Instigator as Pawn; - if (pawn != null) + bool spawnedOrAnyParentSpawned = this.SpawnedOrAnyParentSpawned; + Map mapHeld = this.MapHeld; + float num = dinfo.Def.Worker.Apply(dinfo, this); + if (dinfo.Def.harmsHealth && spawnedOrAnyParentSpawned) + { + mapHeld.damageWatcher.Notify_DamageTaken(this, num); + } + if (dinfo.Def.externalViolence) { - pawn.records.AddTo(RecordDefOf.DamageDealt, num); + GenLeaving.DropFilthDueToDamage(this, num); + if (dinfo.Instigator != null) + { + Pawn pawn = dinfo.Instigator as Pawn; + if (pawn != null) + { + pawn.records.AddTo(RecordDefOf.DamageDealt, num); + } + } } + this.PostApplyDamage(dinfo, num); } } - this.PostApplyDamage(dinfo, num); } public virtual void PreApplyDamage(DamageInfo dinfo, out bool absorbed) @@ -1041,7 +999,11 @@ public virtual void PostApplyDamage(DamageInfo dinfo, float totalDamageDealt) public virtual bool CanStackWith(Thing other) { - return !this.Destroyed && !other.Destroyed && this.def == other.def && this.Stuff == other.Stuff; + if (!this.Destroyed && !other.Destroyed) + { + return this.def == other.def && this.Stuff == other.Stuff; + } + return false; } public virtual bool TryAbsorbStack(Thing other, bool respectStackLimit) @@ -1076,15 +1038,7 @@ public virtual Thing SplitOff(int count) { if (count > this.stackCount) { - Log.Error(string.Concat(new object[] - { - "Tried to split off ", - count, - " of ", - this, - " but there are only ", - this.stackCount - })); + Log.Error("Tried to split off " + count + " of " + this + " but there are only " + this.stackCount); } if (this.Spawned) { @@ -1117,14 +1071,7 @@ public virtual TipSignal GetTooltip() if (this.def.useHitPoints) { string text2 = text; - text = string.Concat(new object[] - { - text2, - "\n", - this.HitPoints, - " / ", - this.MaxHitPoints - }); + text = text2 + "\n" + this.HitPoints + " / " + this.MaxHitPoints; } return new TipSignal(text, this.thingIDNumber * 251235); } @@ -1139,9 +1086,11 @@ public void SetFactionDirect(Faction newFaction) if (!this.def.CanHaveFaction) { Log.Error("Tried to SetFactionDirect on " + this + " which cannot have a faction."); - return; } - this.factionInt = newFaction; + else + { + this.factionInt = newFaction; + } } public virtual void SetFaction(Faction newFaction, Pawn recruiter = null) @@ -1149,15 +1098,17 @@ public virtual void SetFaction(Faction newFaction, Pawn recruiter = null) if (!this.def.CanHaveFaction) { Log.Error("Tried to SetFaction on " + this + " which cannot have a faction."); - return; } - this.factionInt = newFaction; - if (this.Spawned) + else { - IAttackTarget attackTarget = this as IAttackTarget; - if (attackTarget != null) + this.factionInt = newFaction; + if (this.Spawned) { - this.Map.attackTargetsCache.UpdateTarget(attackTarget); + IAttackTarget attackTarget = this as IAttackTarget; + if (attackTarget != null) + { + this.Map.attackTargetsCache.UpdateTarget(attackTarget); + } } } } @@ -1193,41 +1144,61 @@ public override int GetHashCode() public virtual void Discard() { - if ((int)this.mapIndexOrState != -2) + if (this.mapIndexOrState != -2) { - Log.Warning(string.Concat(new object[] - { - "Tried to discard ", - this, - " whose state is ", - this.mapIndexOrState, - "." - })); - return; + Log.Warning("Tried to discard " + this + " whose state is " + this.mapIndexOrState + "."); + } + else + { + this.mapIndexOrState = (sbyte)(-3); } - this.mapIndexOrState = -3; } - [DebuggerHidden] public virtual IEnumerable ButcherProducts(Pawn butcher, float efficiency) { - Thing.c__Iterator13C c__Iterator13C = new Thing.c__Iterator13C(); - c__Iterator13C.efficiency = efficiency; - c__Iterator13C.<$>efficiency = efficiency; - c__Iterator13C.<>f__this = this; - Thing.c__Iterator13C expr_1C = c__Iterator13C; - expr_1C.$PC = -2; - return expr_1C; + if (this.def.butcherProducts != null) + { + for (int i = 0; i < this.def.butcherProducts.Count; i++) + { + ThingCountClass ta = this.def.butcherProducts[i]; + int count = GenMath.RoundRandom((float)ta.count * efficiency); + if (count > 0) + { + Thing t = ThingMaker.MakeThing(ta.thingDef, null); + t.stackCount = count; + yield return t; + } + } + } } - [DebuggerHidden] public virtual IEnumerable SmeltProducts(float efficiency) { - Thing.c__Iterator13D c__Iterator13D = new Thing.c__Iterator13D(); - c__Iterator13D.<>f__this = this; - Thing.c__Iterator13D expr_0E = c__Iterator13D; - expr_0E.$PC = -2; - return expr_0E; + List costListAdj = this.def.CostListAdjusted(this.Stuff, true); + for (int j = 0; j < costListAdj.Count; j++) + { + if (!costListAdj[j].thingDef.intricate) + { + float countF = (float)((float)costListAdj[j].count * 0.25); + int count = GenMath.RoundRandom(countF); + if (count > 0) + { + Thing t = ThingMaker.MakeThing(costListAdj[j].thingDef, null); + t.stackCount = count; + yield return t; + } + } + } + if (this.def.smeltProducts != null) + { + for (int i = 0; i < this.def.smeltProducts.Count; i++) + { + ThingCountClass ta = this.def.smeltProducts[i]; + Thing t2 = ThingMaker.MakeThing(ta.thingDef, null); + t2.stackCount = ta.count; + yield return t2; + } + } } public float Ingested(Pawn ingester, float nutritionWanted) @@ -1260,15 +1231,12 @@ public float Ingested(Pawn ingester, float nutritionWanted) } if (ingester.IsColonist && FoodUtility.IsHumanlikeMeatOrHumanlikeCorpse(this)) { - TaleRecorder.RecordTale(TaleDefOf.AteRawHumanlikeMeat, new object[] - { - ingester - }); + TaleRecorder.RecordTale(TaleDefOf.AteRawHumanlikeMeat, ingester); } - int num; - float result; + int num = default(int); + float result = default(float); this.IngestedCalculateAmounts(ingester, nutritionWanted, out num, out result); - if (!ingester.Dead && ingester.needs.joy != null && Mathf.Abs(this.def.ingestible.joy) > 0.0001f && num > 0) + if (!ingester.Dead && ingester.needs.joy != null && Mathf.Abs(this.def.ingestible.joy) > 9.9999997473787516E-05 && num > 0) { JoyKindDef joyKind = (this.def.ingestible.joyKind == null) ? JoyKindDefOf.Gluttonous : this.def.ingestible.joyKind; ingester.needs.joy.GainJoy((float)num * this.def.ingestible.joy, joyKind); @@ -1295,12 +1263,7 @@ protected virtual void PostIngested(Pawn ingester) protected virtual void IngestedCalculateAmounts(Pawn ingester, float nutritionWanted, out int numTaken, out float nutritionIngested) { numTaken = Mathf.CeilToInt(nutritionWanted / this.def.ingestible.nutrition); - numTaken = Mathf.Min(new int[] - { - numTaken, - this.def.ingestible.maxNumToIngestAtOnce, - this.stackCount - }); + numTaken = Mathf.Min(numTaken, this.def.ingestible.maxNumToIngestAtOnce, this.stackCount); numTaken = Mathf.Max(numTaken, 1); nutritionIngested = (float)numTaken * this.def.ingestible.nutrition; } @@ -1312,33 +1275,38 @@ public static IntVec3 InteractionCellWhenAt(ThingDef def, IntVec3 center, Rot4 r IntVec3 b = def.interactionCellOffset.RotatedBy(rot); return center + b; } - if (def.Size.x == 1 && def.Size.z == 1) + IntVec2 size = def.Size; + if (size.x == 1) { - for (int i = 0; i < 8; i++) + IntVec2 size2 = def.Size; + if (size2.z == 1) { - IntVec3 intVec = center + GenAdj.AdjacentCells[i]; - if (intVec.Standable(map) && intVec.GetDoor(map) == null) + for (int i = 0; i < 8; i++) { - return intVec; + IntVec3 intVec = center + GenAdj.AdjacentCells[i]; + if (intVec.Standable(map) && intVec.GetDoor(map) == null) + { + return intVec; + } } - } - for (int j = 0; j < 8; j++) - { - IntVec3 intVec2 = center + GenAdj.AdjacentCells[j]; - if (intVec2.Standable(map)) + for (int j = 0; j < 8; j++) { - return intVec2; + IntVec3 intVec2 = center + GenAdj.AdjacentCells[j]; + if (intVec2.Standable(map)) + { + return intVec2; + } } - } - for (int k = 0; k < 8; k++) - { - IntVec3 intVec3 = center + GenAdj.AdjacentCells[k]; - if (intVec3.Walkable(map)) + for (int k = 0; k < 8; k++) { - return intVec3; + IntVec3 intVec3 = center + GenAdj.AdjacentCells[k]; + if (intVec3.Walkable(map)) + { + return intVec3; + } } + return center; } - return center; } List list = GenAdjFast.AdjacentCells8Way(center); for (int l = 0; l < list.Count; l++) @@ -1367,7 +1335,7 @@ public static IntVec3 InteractionCellWhenAt(ThingDef def, IntVec3 center, Rot4 r public virtual bool PreventPlayerSellingThingsNearby(out string reason) { - reason = null; + reason = (string)null; return false; } } diff --git a/Assembly-CSharp/Verse/ThingCategory.cs b/Assembly-CSharp/Verse/ThingCategory.cs index d6b9b0e2a..bb036505b 100644 --- a/Assembly-CSharp/Verse/ThingCategory.cs +++ b/Assembly-CSharp/Verse/ThingCategory.cs @@ -1,20 +1,18 @@ -using System; - namespace Verse { public enum ThingCategory : byte { - None, - Pawn, - Item, - Plant, - Building, - Filth, - Projectile, - Mote, - Ethereal, - Attachment, - Skyfaller, - Gas + None = 0, + Pawn = 1, + Item = 2, + Plant = 3, + Building = 4, + Filth = 5, + Projectile = 6, + Mote = 7, + Ethereal = 8, + Attachment = 9, + Skyfaller = 10, + Gas = 11 } } diff --git a/Assembly-CSharp/Verse/ThingCategoryDef.cs b/Assembly-CSharp/Verse/ThingCategoryDef.cs index 89af09d63..d6e84c8f4 100644 --- a/Assembly-CSharp/Verse/ThingCategoryDef.cs +++ b/Assembly-CSharp/Verse/ThingCategoryDef.cs @@ -32,11 +32,14 @@ public IEnumerable Parents { get { - ThingCategoryDef.<>c__Iterator1E1 <>c__Iterator1E = new ThingCategoryDef.<>c__Iterator1E1(); - <>c__Iterator1E.<>f__this = this; - ThingCategoryDef.<>c__Iterator1E1 expr_0E = <>c__Iterator1E; - expr_0E.$PC = -2; - return expr_0E; + if (this.parent != null) + { + yield return this.parent; + foreach (ThingCategoryDef parent2 in this.parent.Parents) + { + yield return parent2; + } + } } } @@ -44,11 +47,23 @@ public IEnumerable ThisAndChildCategoryDefs { get { - ThingCategoryDef.<>c__Iterator1E2 <>c__Iterator1E = new ThingCategoryDef.<>c__Iterator1E2(); - <>c__Iterator1E.<>f__this = this; - ThingCategoryDef.<>c__Iterator1E2 expr_0E = <>c__Iterator1E; - expr_0E.$PC = -2; - return expr_0E; + yield return this; + List.Enumerator enumerator = this.childCategories.GetEnumerator(); + try + { + while (enumerator.MoveNext()) + { + ThingCategoryDef child = enumerator.Current; + foreach (ThingCategoryDef thisAndChildCategoryDef in child.ThisAndChildCategoryDefs) + { + yield return thisAndChildCategoryDef; + } + } + } + finally + { + ((IDisposable)(object)enumerator).Dispose(); + } } } @@ -56,11 +71,22 @@ public IEnumerable DescendantThingDefs { get { - ThingCategoryDef.<>c__Iterator1E3 <>c__Iterator1E = new ThingCategoryDef.<>c__Iterator1E3(); - <>c__Iterator1E.<>f__this = this; - ThingCategoryDef.<>c__Iterator1E3 expr_0E = <>c__Iterator1E; - expr_0E.$PC = -2; - return expr_0E; + foreach (ThingCategoryDef thisAndChildCategoryDef in this.ThisAndChildCategoryDefs) + { + List.Enumerator enumerator2 = thisAndChildCategoryDef.childThingDefs.GetEnumerator(); + try + { + while (enumerator2.MoveNext()) + { + ThingDef def = enumerator2.Current; + yield return def; + } + } + finally + { + ((IDisposable)(object)enumerator2).Dispose(); + } + } } } @@ -68,11 +94,22 @@ public IEnumerable DescendantSpecialThingFilterDefs { get { - ThingCategoryDef.<>c__Iterator1E4 <>c__Iterator1E = new ThingCategoryDef.<>c__Iterator1E4(); - <>c__Iterator1E.<>f__this = this; - ThingCategoryDef.<>c__Iterator1E4 expr_0E = <>c__Iterator1E; - expr_0E.$PC = -2; - return expr_0E; + foreach (ThingCategoryDef thisAndChildCategoryDef in this.ThisAndChildCategoryDefs) + { + List.Enumerator enumerator2 = thisAndChildCategoryDef.childSpecialFilters.GetEnumerator(); + try + { + while (enumerator2.MoveNext()) + { + SpecialThingFilterDef sf = enumerator2.Current; + yield return sf; + } + } + finally + { + ((IDisposable)(object)enumerator2).Dispose(); + } + } } } @@ -80,11 +117,22 @@ public IEnumerable ParentsSpecialThingFilterDefs { get { - ThingCategoryDef.<>c__Iterator1E5 <>c__Iterator1E = new ThingCategoryDef.<>c__Iterator1E5(); - <>c__Iterator1E.<>f__this = this; - ThingCategoryDef.<>c__Iterator1E5 expr_0E = <>c__Iterator1E; - expr_0E.$PC = -2; - return expr_0E; + foreach (ThingCategoryDef parent2 in this.Parents) + { + List.Enumerator enumerator2 = parent2.childSpecialFilters.GetEnumerator(); + try + { + while (enumerator2.MoveNext()) + { + SpecialThingFilterDef filter = enumerator2.Current; + yield return filter; + } + } + finally + { + ((IDisposable)(object)enumerator2).Dispose(); + } + } } } @@ -93,7 +141,7 @@ public override void PostLoad() this.treeNode = new TreeNode_ThingCategory(this); if (!this.iconPath.NullOrEmpty()) { - LongEventHandler.ExecuteWhenFinished(delegate + LongEventHandler.ExecuteWhenFinished((Action)delegate { this.icon = ContentFinder.Get(this.iconPath, true); }); @@ -107,7 +155,7 @@ public static ThingCategoryDef Named(string defName) public override int GetHashCode() { - return this.defName.GetHashCode(); + return base.defName.GetHashCode(); } } } diff --git a/Assembly-CSharp/Verse/ThingCategoryNodeDatabase.cs b/Assembly-CSharp/Verse/ThingCategoryNodeDatabase.cs index 1a0a5ba18..31e91d678 100644 --- a/Assembly-CSharp/Verse/ThingCategoryNodeDatabase.cs +++ b/Assembly-CSharp/Verse/ThingCategoryNodeDatabase.cs @@ -35,27 +35,36 @@ public static void Clear() public static void FinalizeInit() { ThingCategoryNodeDatabase.rootNode = ThingCategoryDefOf.Root.treeNode; - foreach (ThingCategoryDef current in DefDatabase.AllDefs) + foreach (ThingCategoryDef allDef in DefDatabase.AllDefs) { - if (current.parent != null) + if (allDef.parent != null) { - current.parent.childCategories.Add(current); + allDef.parent.childCategories.Add(allDef); } } ThingCategoryNodeDatabase.SetNestLevelRecursive(ThingCategoryNodeDatabase.rootNode, 0); - foreach (ThingDef current2 in DefDatabase.AllDefs) + foreach (ThingDef allDef2 in DefDatabase.AllDefs) { - if (current2.thingCategories != null) + if (allDef2.thingCategories != null) { - foreach (ThingCategoryDef current3 in current2.thingCategories) + List.Enumerator enumerator3 = allDef2.thingCategories.GetEnumerator(); + try { - current3.childThingDefs.Add(current2); + while (enumerator3.MoveNext()) + { + ThingCategoryDef current3 = enumerator3.Current; + current3.childThingDefs.Add(allDef2); + } + } + finally + { + ((IDisposable)(object)enumerator3).Dispose(); } } } - foreach (SpecialThingFilterDef current4 in DefDatabase.AllDefs) + foreach (SpecialThingFilterDef allDef3 in DefDatabase.AllDefs) { - current4.parentCategory.childSpecialFilters.Add(current4); + allDef3.parentCategory.childSpecialFilters.Add(allDef3); } ThingCategoryNodeDatabase.rootNode.catDef.childCategories[0].treeNode.SetOpen(-1, true); ThingCategoryNodeDatabase.initialized = true; @@ -63,10 +72,19 @@ public static void FinalizeInit() private static void SetNestLevelRecursive(TreeNode_ThingCategory node, int nestDepth) { - foreach (ThingCategoryDef current in node.catDef.childCategories) + List.Enumerator enumerator = node.catDef.childCategories.GetEnumerator(); + try + { + while (enumerator.MoveNext()) + { + ThingCategoryDef current = enumerator.Current; + current.treeNode.nestDepth = nestDepth; + ThingCategoryNodeDatabase.SetNestLevelRecursive(current.treeNode, nestDepth + 1); + } + } + finally { - current.treeNode.nestDepth = nestDepth; - ThingCategoryNodeDatabase.SetNestLevelRecursive(current.treeNode, nestDepth + 1); + ((IDisposable)(object)enumerator).Dispose(); } } } diff --git a/Assembly-CSharp/Verse/ThingComp.cs b/Assembly-CSharp/Verse/ThingComp.cs index 3efc5f8d8..19051992b 100644 --- a/Assembly-CSharp/Verse/ThingComp.cs +++ b/Assembly-CSharp/Verse/ThingComp.cs @@ -1,7 +1,5 @@ using RimWorld; -using System; using System.Collections.Generic; -using System.Diagnostics; namespace Verse { @@ -90,13 +88,9 @@ public virtual string TransformLabel(string label) return label; } - [DebuggerHidden] public virtual IEnumerable CompGetGizmosExtra() { - ThingComp.c__IteratorB0 c__IteratorB = new ThingComp.c__IteratorB0(); - ThingComp.c__IteratorB0 expr_07 = c__IteratorB; - expr_07.$PC = -2; - return expr_07; + yield break; } public virtual bool AllowStackWith(Thing other) @@ -106,21 +100,17 @@ public virtual bool AllowStackWith(Thing other) public virtual string CompInspectStringExtra() { - return null; + return (string)null; } public virtual string GetDescriptionPart() { - return null; + return (string)null; } - [DebuggerHidden] public virtual IEnumerable CompFloatMenuOptions(Pawn selPawn) { - ThingComp.c__IteratorB1 c__IteratorB = new ThingComp.c__IteratorB1(); - ThingComp.c__IteratorB1 expr_07 = c__IteratorB; - expr_07.$PC = -2; - return expr_07; + yield break; } public virtual void PrePreTraded(TradeAction action, Pawn playerNegotiator, ITrader trader) @@ -137,15 +127,7 @@ public virtual void PostPostGeneratedForTrader(TraderKindDef trader, int forTile public override string ToString() { - return string.Concat(new object[] - { - base.GetType().Name, - "(parent=", - this.parent, - " at=", - (this.parent == null) ? IntVec3.Invalid : this.parent.Position, - ")" - }); + return base.GetType().Name + "(parent=" + this.parent + " at=" + ((this.parent == null) ? IntVec3.Invalid : this.parent.Position) + ")"; } } } diff --git a/Assembly-CSharp/Verse/ThingCompUtility.cs b/Assembly-CSharp/Verse/ThingCompUtility.cs index 02e1835ca..82088616c 100644 --- a/Assembly-CSharp/Verse/ThingCompUtility.cs +++ b/Assembly-CSharp/Verse/ThingCompUtility.cs @@ -1,5 +1,3 @@ -using System; - namespace Verse { public static class ThingCompUtility @@ -9,7 +7,7 @@ public static T TryGetComp(this Thing thing) where T : ThingComp ThingWithComps thingWithComps = thing as ThingWithComps; if (thingWithComps == null) { - return (T)((object)null); + return (T)null; } return thingWithComps.GetComp(); } diff --git a/Assembly-CSharp/Verse/ThingCount.cs b/Assembly-CSharp/Verse/ThingCount.cs index 191f3b8bc..bdd29ed1b 100644 --- a/Assembly-CSharp/Verse/ThingCount.cs +++ b/Assembly-CSharp/Verse/ThingCount.cs @@ -28,13 +28,7 @@ public ThingCount(ThingDef thingDef, int count) { if (count < 0) { - Log.Warning(string.Concat(new object[] - { - "Tried to set ThingCount count to ", - count, - ". thingDef=", - thingDef - })); + Log.Warning("Tried to set ThingCount count to " + count + ". thingDef=" + thingDef); count = 0; } this.thingDef = thingDef; @@ -48,7 +42,11 @@ public ThingCount WithCount(int newCount) public override bool Equals(object obj) { - return obj is ThingCount && this.Equals((ThingCount)obj); + if (!(obj is ThingCount)) + { + return false; + } + return this.Equals((ThingCount)obj); } public bool Equals(ThingCount other) @@ -58,7 +56,7 @@ public bool Equals(ThingCount other) public override int GetHashCode() { - return Gen.HashCombine(this.count, this.thingDef); + return Gen.HashCombine(this.count, this.thingDef); } public static bool operator ==(ThingCount a, ThingCount b) diff --git a/Assembly-CSharp/Verse/ThingCountClass.cs b/Assembly-CSharp/Verse/ThingCountClass.cs index 8324096d6..c121204e3 100644 --- a/Assembly-CSharp/Verse/ThingCountClass.cs +++ b/Assembly-CSharp/Verse/ThingCountClass.cs @@ -1,4 +1,3 @@ -using System; using System.Xml; namespace Verse @@ -24,27 +23,22 @@ public void LoadDataFromXmlCustom(XmlNode xmlRoot) if (xmlRoot.ChildNodes.Count != 1) { Log.Error("Misconfigured ThingCount: " + xmlRoot.OuterXml); - return; } - DirectXmlCrossRefLoader.RegisterObjectWantsCrossRef(this, "thingDef", xmlRoot.Name); - this.count = (int)ParseHelper.FromString(xmlRoot.FirstChild.Value, typeof(int)); + else + { + DirectXmlCrossRefLoader.RegisterObjectWantsCrossRef(this, "thingDef", xmlRoot.Name); + this.count = (int)ParseHelper.FromString(xmlRoot.FirstChild.Value, typeof(int)); + } } public override string ToString() { - return string.Concat(new object[] - { - "(", - this.count, - "x ", - (this.thingDef == null) ? "null" : this.thingDef.defName, - ")" - }); + return "(" + this.count + "x " + ((this.thingDef == null) ? "null" : this.thingDef.defName) + ")"; } public override int GetHashCode() { - return (int)this.thingDef.shortHash + this.count << 16; + return this.thingDef.shortHash + this.count << 16; } } } diff --git a/Assembly-CSharp/Verse/ThingDef.cs b/Assembly-CSharp/Verse/ThingDef.cs index d8f3f4e0e..b35b08b2c 100644 --- a/Assembly-CSharp/Verse/ThingDef.cs +++ b/Assembly-CSharp/Verse/ThingDef.cs @@ -1,7 +1,6 @@ using RimWorld; using System; using System.Collections.Generic; -using System.Diagnostics; using System.Linq; using UnityEngine; using Verse.AI; @@ -247,7 +246,7 @@ public bool EverStoreable { get { - return !this.thingCategories.NullOrEmpty(); + return !this.thingCategories.NullOrEmpty(); } } @@ -255,7 +254,7 @@ public float VolumePerUnit { get { - return this.smallVolume ? 0.1f : 1f; + return (float)(this.smallVolume ? 0.10000000149011612 : 1.0); } } @@ -421,11 +420,11 @@ public FillCategory Fillage { get { - if (this.fillPercent < 0.01f) + if (this.fillPercent < 0.0099999997764825821) { return FillCategory.None; } - if (this.fillPercent > 0.99f) + if (this.fillPercent > 0.99000000953674316) { return FillCategory.Full; } @@ -449,11 +448,11 @@ public bool CanOverlapZones { return false; } - if (this.passability == Traversability.Impassable && this.category != ThingCategory.Plant) + if (base.passability == Traversability.Impassable && this.category != ThingCategory.Plant) { return false; } - if (this.surfaceType >= SurfaceType.Item) + if ((int)this.surfaceType >= 1) { return false; } @@ -489,7 +488,27 @@ public bool BlockPlanting { get { - return (this.building == null || !this.building.SupportsPlants) && (this.blockPlants || this.category == ThingCategory.Plant || this.Fillage > FillCategory.None || this.IsEdifice()); + if (this.building != null && this.building.SupportsPlants) + { + return false; + } + if (this.blockPlants) + { + return true; + } + if (this.category == ThingCategory.Plant) + { + return true; + } + if ((int)this.Fillage > 0) + { + return true; + } + if (this.IsEdifice()) + { + return true; + } + return false; } } @@ -509,18 +528,25 @@ public bool CanHaveFaction { get { - if (this.IsBlueprint || this.IsFrame) - { - return true; - } - switch (this.category) + if (!this.IsBlueprint && !this.IsFrame) { - case ThingCategory.Pawn: - return true; - case ThingCategory.Building: - return true; + switch (this.category) + { + case ThingCategory.Pawn: + { + return true; + } + case ThingCategory.Building: + { + return true; + } + default: + { + return false; + } + } } - return false; + return true; } } @@ -536,7 +562,7 @@ public ThingCategoryDef FirstThingCategory { get { - if (this.thingCategories.NullOrEmpty()) + if (this.thingCategories.NullOrEmpty()) { return null; } @@ -548,7 +574,7 @@ public float MedicineTendXpGainFactor { get { - return Mathf.Clamp(this.GetStatValueAbstract(StatDefOf.MedicalPotency, null) * 0.7f, 0.5f, 1f); + return Mathf.Clamp((float)(this.GetStatValueAbstract(StatDefOf.MedicalPotency, null) * 0.699999988079071), 0.5f, 1f); } } @@ -556,7 +582,11 @@ public bool CanEverDeteriorate { get { - return this.useHitPoints && (this.category == ThingCategory.Item || this == ThingDefOf.BurnedTree); + if (!this.useHitPoints) + { + return false; + } + return this.category == ThingCategory.Item || this == ThingDefOf.BurnedTree; } } @@ -564,7 +594,7 @@ public bool AffectsRegions { get { - return this.passability == Traversability.Impassable || this.IsDoor; + return base.passability == Traversability.Impassable || this.IsDoor; } } @@ -572,7 +602,19 @@ public bool AffectsReachability { get { - return this.AffectsRegions || (this.passability == Traversability.Impassable || this.IsDoor) || TouchPathEndModeUtility.MakesOccupiedCellsAlwaysReachableDiagonally(this); + if (this.AffectsRegions) + { + return true; + } + if (base.passability != Traversability.Impassable && !this.IsDoor) + { + if (TouchPathEndModeUtility.MakesOccupiedCellsAlwaysReachableDiagonally(this)) + { + return true; + } + return false; + } + return true; } } @@ -628,7 +670,7 @@ public bool IsMedicine { get { - return this.statBases.StatListContains(StatDefOf.MedicalPotency); + return base.statBases.StatListContains(StatDefOf.MedicalPotency); } } @@ -660,7 +702,7 @@ public bool IsNutritionGivingIngestible { get { - return this.IsIngestible && this.ingestible.nutrition > 0f; + return this.IsIngestible && this.ingestible.nutrition > 0.0; } } @@ -668,7 +710,7 @@ public bool IsWeapon { get { - return this.category == ThingCategory.Item && !this.verbs.NullOrEmpty(); + return this.category == ThingCategory.Item && !this.verbs.NullOrEmpty(); } } @@ -708,7 +750,7 @@ public bool IsPleasureDrug { get { - return this.IsDrug && this.ingestible.joy > 0f; + return this.IsDrug && this.ingestible.joy > 0.0; } } @@ -725,7 +767,7 @@ public bool IsAddictiveDrug get { CompProperties_Drug compProperties = this.GetCompProperties(); - return compProperties != null && compProperties.addictiveness > 0f; + return compProperties != null && compProperties.addictiveness > 0.0; } } @@ -775,18 +817,18 @@ public string LabelAsStuff { return this.stuffProps.stuffAdjective; } - return this.label; + return base.label; } } public CompProperties CompDefFor() where T : ThingComp { - return this.comps.FirstOrDefault((CompProperties c) => c.compClass == typeof(T)); + return ((IEnumerable)this.comps).FirstOrDefault((Func)((CompProperties c) => c.compClass == typeof(T))); } public CompProperties CompDefForAssignableFrom() where T : ThingComp { - return this.comps.FirstOrDefault((CompProperties c) => typeof(T).IsAssignableFrom(c.compClass)); + return ((IEnumerable)this.comps).FirstOrDefault((Func)((CompProperties c) => typeof(T).IsAssignableFrom(c.compClass))); } public bool HasComp(Type compType) @@ -805,31 +847,31 @@ public T GetCompProperties() where T : CompProperties { for (int i = 0; i < this.comps.Count; i++) { - T t = this.comps[i] as T; - if (t != null) + T val = (T)(this.comps[i] as T); + if (val != null) { - return t; + return val; } } - return (T)((object)null); + return (T)null; } public override void PostLoad() { if (this.graphicData != null) { - LongEventHandler.ExecuteWhenFinished(delegate + LongEventHandler.ExecuteWhenFinished((Action)delegate { if (this.graphicData.shaderType == ShaderType.None) { this.graphicData.shaderType = ShaderType.Cutout; } - this.graphic = this.graphicData.Graphic; + base.graphic = this.graphicData.Graphic; }); } if (this.verbs != null && this.verbs.Count == 1) { - this.verbs[0].label = this.label; + this.verbs[0].label = base.label; } base.PostLoad(); if (this.category == ThingCategory.Building && this.building == null) @@ -850,13 +892,7 @@ public override void PostLoad() } catch (Exception ex) { - Log.Error(string.Concat(new object[] - { - "Could not instantiate inspector tab of type ", - this.inspectorTabs[i], - ": ", - ex - })); + Log.Error("Could not instantiate inspector tab of type " + this.inspectorTabs[i] + ": " + ex); } } } @@ -910,14 +946,245 @@ public override void ResolveReferences() } } - [DebuggerHidden] public override IEnumerable ConfigErrors() { - ThingDef.c__Iterator1E6 c__Iterator1E = new ThingDef.c__Iterator1E6(); - c__Iterator1E.<>f__this = this; - ThingDef.c__Iterator1E6 expr_0E = c__Iterator1E; - expr_0E.$PC = -2; - return expr_0E; + foreach (string item in base.ConfigErrors()) + { + yield return item; + } + if (base.label.NullOrEmpty()) + { + yield return "no label"; + } + if (this.graphicData != null) + { + foreach (string item2 in this.graphicData.ConfigErrors(this)) + { + yield return item2; + } + } + if (this.projectile != null) + { + foreach (string item3 in this.projectile.ConfigErrors(this)) + { + yield return item3; + } + } + if (base.statBases != null) + { + List.Enumerator enumerator4 = base.statBases.GetEnumerator(); + try + { + while (enumerator4.MoveNext()) + { + StatModifier statBase = enumerator4.Current; + if ((from st in base.statBases + where st.stat == ((_003CConfigErrors_003Ec__Iterator1E6)/*Error near IL_02ec: stateMachine*/)._003CstatBase_003E__7.stat + select st).Count() > 1) + { + yield return base.defName + " defines the stat base " + statBase.stat + " more than once."; + } + } + } + finally + { + ((IDisposable)(object)enumerator4).Dispose(); + } + } + if (char.IsNumber(base.defName[base.defName.Length - 1])) + { + yield return base.defName + " ends with a numerical digit, which is not allowed on ThingDefs."; + } + if (this.thingClass == null) + { + yield return base.defName + " has null thingClass."; + } + if (this.comps.Count > 0 && !typeof(ThingWithComps).IsAssignableFrom(this.thingClass)) + { + yield return base.defName + " has components but it's thingClass is not a ThingWithComps"; + } + if (this.ConnectToPower && this.drawerType == DrawerType.RealtimeOnly && this.IsFrame) + { + yield return base.defName + " connects to power but does not add to map mesh. Will not create wire meshes."; + } + if (base.costList != null) + { + List.Enumerator enumerator5 = base.costList.GetEnumerator(); + try + { + while (enumerator5.MoveNext()) + { + ThingCountClass cost = enumerator5.Current; + if (cost.count == 0) + { + yield return base.defName + " cost in " + cost.thingDef + " is zero."; + } + } + } + finally + { + ((IDisposable)(object)enumerator5).Dispose(); + } + } + if (this.thingCategories != null) + { + ThingCategoryDef doubleCat = this.thingCategories.FirstOrDefault((Func)delegate(ThingCategoryDef cat) + { + _003CConfigErrors_003Ec__Iterator1E6 _003CConfigErrors_003Ec__Iterator1E = (_003CConfigErrors_003Ec__Iterator1E6)/*Error near IL_05aa: stateMachine*/; + return ((_003CConfigErrors_003Ec__Iterator1E6)/*Error near IL_05aa: stateMachine*/)._003C_003Ef__this.thingCategories.Count((Func)((ThingCategoryDef c) => c == cat)) > 1; + }); + if (doubleCat != null) + { + yield return base.defName + " has duplicate thingCategory " + doubleCat + "."; + } + } + if (this.Fillage == FillCategory.Full && this.category != ThingCategory.Building) + { + yield return base.defName + " gives full cover but is not a building."; + } + if (this.comps.Any((Predicate)((CompProperties c) => c.compClass == typeof(CompPowerTrader))) && this.drawerType == DrawerType.MapMeshOnly) + { + yield return base.defName + " has PowerTrader comp but does not draw real time. It won't draw a needs-power overlay."; + } + if (this.equipmentType != 0) + { + if (this.techLevel == TechLevel.Undefined) + { + yield return base.defName + " has no tech level."; + } + if (!this.comps.Any((Predicate)((CompProperties c) => c.compClass == typeof(CompEquippable)))) + { + yield return "is equipment but has no CompEquippable"; + } + } + if (this.thingClass == typeof(Bullet) && this.projectile.damageDef == null) + { + yield return base.defName + " is a bullet but has no damageDef."; + } + if (this.destroyOnDrop && !base.menuHidden) + { + yield return base.defName + " has destroyOnDrop but not menuHidden."; + } + if (this.stackLimit > 1 && !this.drawGUIOverlay) + { + yield return base.defName + " has stackLimit > 1 but also has drawGUIOverlay = false."; + } + if (this.damageMultipliers != null) + { + List.Enumerator enumerator6 = this.damageMultipliers.GetEnumerator(); + try + { + while (enumerator6.MoveNext()) + { + DamageMultiplier mult = enumerator6.Current; + if ((from m in this.damageMultipliers + where m.damageDef == ((_003CConfigErrors_003Ec__Iterator1E6)/*Error near IL_0896: stateMachine*/)._003Cmult_003E__12.damageDef + select m).Count() > 1) + { + yield return base.defName + " has multiple damage multipliers for damageDef " + mult.damageDef; + break; + } + } + } + finally + { + ((IDisposable)(object)enumerator6).Dispose(); + } + } + if (this.Fillage == FillCategory.Full && !this.IsEdifice()) + { + yield return "fillPercent is 1.00 but is not edifice"; + } + if (base.MadeFromStuff && base.constructEffect != null) + { + yield return base.defName + " is madeFromStuff but has a defined constructEffect (which will always be overridden by stuff's construct animation)."; + } + if (base.MadeFromStuff && base.stuffCategories.NullOrEmpty()) + { + yield return "madeFromStuff but has no stuffCategories."; + } + if (base.costList.NullOrEmpty() && base.costStuffCount <= 0 && this.recipeMaker != null) + { + yield return "has a recipeMaker but no costList or costStuffCount."; + } + if (this.GetStatValueAbstract(StatDefOf.DeteriorationRate, null) > 9.9999997473787516E-06 && !this.CanEverDeteriorate) + { + yield return "has >0 DeteriorationRate but can't deteriorate."; + } + if (this.drawerType == DrawerType.MapMeshOnly && this.comps.Any((Predicate)((CompProperties c) => c.compClass == typeof(CompForbiddable)))) + { + yield return "drawerType=MapMeshOnly but has a CompForbiddable, which must draw in real time."; + } + if (this.smeltProducts != null && this.smeltable) + { + yield return "has smeltProducts but has smeltable=false"; + } + if (this.graphicData != null && this.graphicData.shadowData != null) + { + if (this.castEdgeShadows) + { + yield return "graphicData defines a shadowInfo but castEdgeShadows is also true"; + } + if (this.staticSunShadowHeight > 0.0) + { + yield return "graphicData defines a shadowInfo but staticSunShadowHeight > 0"; + } + } + if (this.race != null && this.verbs != null) + { + for (int j = 0; j < this.verbs.Count; j++) + { + if (this.verbs[j].linkedBodyPartsGroup != null && !this.race.body.AllParts.Any((Predicate)((BodyPartRecord part) => part.groups.Contains(((_003CConfigErrors_003Ec__Iterator1E6)/*Error near IL_0bd3: stateMachine*/)._003C_003Ef__this.verbs[((_003CConfigErrors_003Ec__Iterator1E6)/*Error near IL_0bd3: stateMachine*/)._003Ci_003E__13].linkedBodyPartsGroup)))) + { + yield return "has verb with linkedBodyPartsGroup " + this.verbs[j].linkedBodyPartsGroup + " but body " + this.race.body + " has no parts with that group."; + } + } + } + if (this.building != null) + { + foreach (string item4 in this.building.ConfigErrors(this)) + { + yield return item4; + } + } + if (this.apparel != null) + { + foreach (string item5 in this.apparel.ConfigErrors(this)) + { + yield return item5; + } + } + if (this.comps != null) + { + for (int i = 0; i < this.comps.Count; i++) + { + foreach (string item6 in this.comps[i].ConfigErrors(this)) + { + yield return item6; + } + } + } + if (this.race != null) + { + foreach (string item7 in this.race.ConfigErrors()) + { + yield return item7; + } + } + if (this.ingestible != null) + { + foreach (string item8 in this.ingestible.ConfigErrors(this)) + { + yield return item8; + } + } + if (this.plant != null) + { + foreach (string item9 in this.plant.ConfigErrors()) + { + yield return item9; + } + } } public static ThingDef Named(string defName) @@ -931,24 +1198,149 @@ public bool IsWithinCategory(ThingCategoryDef category) { return false; } - for (int i = 0; i < this.thingCategories.Count; i++) + int num = 0; + while (num < this.thingCategories.Count) { - if (this.thingCategories[i] == category || this.thingCategories[i].Parents.Contains(category)) + if (this.thingCategories[num] != category && !this.thingCategories[num].Parents.Contains(category)) { - return true; + num++; + continue; } + return true; } return false; } - [DebuggerHidden] public override IEnumerable SpecialDisplayStats() { - ThingDef.c__Iterator1E7 c__Iterator1E = new ThingDef.c__Iterator1E7(); - c__Iterator1E.<>f__this = this; - ThingDef.c__Iterator1E7 expr_0E = c__Iterator1E; - expr_0E.$PC = -2; - return expr_0E; + if (this.apparel != null) + { + string coveredParts = this.apparel.GetCoveredOuterPartsString(BodyDefOf.Human); + yield return new StatDrawEntry(StatCategoryDefOf.Apparel, "Covers".Translate(), coveredParts, 100); + } + if (this.IsMedicine && this.MedicineTendXpGainFactor != 1.0) + { + yield return new StatDrawEntry(StatCategoryDefOf.Basics, "MedicineXpGainFactor".Translate(), this.MedicineTendXpGainFactor.ToStringPercent(), 0); + } + if (this.fillPercent > 0.0 && this.fillPercent < 1.0 && (this.category == ThingCategory.Item || this.category == ThingCategory.Building || this.category == ThingCategory.Plant)) + { + yield return new StatDrawEntry(StatCategoryDefOf.Basics, "CoverEffectiveness".Translate(), this.BaseBlockChance().ToStringPercent(), 0) + { + overrideReportText = "CoverEffectivenessExplanation".Translate() + }; + } + if (!this.verbs.NullOrEmpty()) + { + VerbProperties verb2 = (from x in this.verbs + where x.isPrimary + select x).First(); + object obj; + StatCategoryDef verbStatCategory3; + if (this.category == ThingCategory.Pawn) + { + StatCategoryDef pawnCombat; + verbStatCategory3 = (pawnCombat = StatCategoryDefOf.PawnCombat); + obj = pawnCombat; + } + else + { + StatCategoryDef pawnCombat; + verbStatCategory3 = (pawnCombat = StatCategoryDefOf.Weapon); + obj = pawnCombat; + } + verbStatCategory3 = (StatCategoryDef)obj; + float warmup = verb2.warmupTime; + if (warmup > 0.0) + { + string warmupLabel = (this.category != ThingCategory.Pawn) ? "WarmupTime".Translate() : "MeleeWarmupTime".Translate(); + yield return new StatDrawEntry(verbStatCategory3, warmupLabel, warmup.ToString("0.##") + " s", 40); + } + if (verb2.projectileDef != null) + { + float dam = (float)verb2.projectileDef.projectile.damageAmountBase; + yield return new StatDrawEntry(verbStatCategory3, "Damage".Translate(), dam.ToString(), 50); + } + if (verb2.projectileDef != null) + { + int burstShotCount = verb2.burstShotCount; + float burstShotFireRate = (float)(60.0 / verb2.ticksBetweenBurstShots.TicksToSeconds()); + float range = verb2.range; + if (burstShotCount > 1) + { + yield return new StatDrawEntry(verbStatCategory3, "BurstShotCount".Translate(), burstShotCount.ToString(), 20); + yield return new StatDrawEntry(verbStatCategory3, "BurstShotFireRate".Translate(), burstShotFireRate.ToString("0.##") + " rpm", 19); + } + yield return new StatDrawEntry(verbStatCategory3, "Range".Translate(), range.ToString("0.##"), 10); + } + } + if (this.plant != null) + { + foreach (StatDrawEntry item in this.plant.SpecialDisplayStats()) + { + yield return item; + } + } + if (this.ingestible != null) + { + foreach (StatDrawEntry item2 in this.ingestible.SpecialDisplayStats(this)) + { + yield return item2; + } + } + if (this.race != null) + { + foreach (StatDrawEntry item3 in this.race.SpecialDisplayStats(this)) + { + yield return item3; + } + } + if (this.isBodyPartOrImplant) + { + foreach (RecipeDef item4 in from x in DefDatabase.AllDefs + where x.IsIngredient(((_003CSpecialDisplayStats_003Ec__Iterator1E7)/*Error near IL_063c: stateMachine*/)._003C_003Ef__this) + select x) + { + HediffDef diff = item4.addsHediff; + if (diff != null) + { + if (diff.addedPartProps != null) + { + yield return new StatDrawEntry(StatCategoryDefOf.Basics, "BodyPartEfficiency".Translate(), diff.addedPartProps.partEfficiency.ToStringByStyle(ToStringStyle.PercentZero, ToStringNumberSense.Absolute), 0); + } + foreach (StatDrawEntry item5 in diff.SpecialDisplayStats()) + { + yield return item5; + } + HediffCompProperties_VerbGiver vg = diff.CompProps(); + if (vg != null) + { + VerbProperties verb = vg.verbs.FirstOrDefault(); + if (!verb.MeleeRange) + { + int projDamage = verb.projectileDef.projectile.damageAmountBase; + yield return new StatDrawEntry(StatCategoryDefOf.Basics, "Damage".Translate(), projDamage.ToString(), 0); + } + else + { + int meleeDamage = verb.meleeDamageBaseAmount; + yield return new StatDrawEntry(StatCategoryDefOf.Weapon, "Damage".Translate(), meleeDamage.ToString(), 0); + } + } + ThoughtDef thought = DefDatabase.AllDefs.FirstOrDefault((Func)((ThoughtDef x) => x.hediff == ((_003CSpecialDisplayStats_003Ec__Iterator1E7)/*Error near IL_0862: stateMachine*/)._003Cdiff_003E__18)); + if (thought != null && thought.stages != null && thought.stages.Any()) + { + yield return new StatDrawEntry(StatCategoryDefOf.Basics, "MoodChange".Translate(), thought.stages.First().baseMoodEffect.ToStringByStyle(ToStringStyle.Integer, ToStringNumberSense.Offset), 0); + } + } + } + } + for (int i = 0; i < this.comps.Count; i++) + { + foreach (StatDrawEntry item6 in this.comps[i].SpecialDisplayStats()) + { + yield return item6; + } + } } } } diff --git a/Assembly-CSharp/Verse/ThingDefComparer.cs b/Assembly-CSharp/Verse/ThingDefComparer.cs index e239b9137..9da9e0191 100644 --- a/Assembly-CSharp/Verse/ThingDefComparer.cs +++ b/Assembly-CSharp/Verse/ThingDefComparer.cs @@ -1,4 +1,3 @@ -using System; using System.Collections.Generic; namespace Verse @@ -9,7 +8,15 @@ public class ThingDefComparer : IEqualityComparer public bool Equals(ThingDef x, ThingDef y) { - return (x == null && y == null) || (x != null && y != null && x.shortHash == y.shortHash); + if (x == null && y == null) + { + return true; + } + if (x != null && y != null) + { + return x.shortHash == y.shortHash; + } + return false; } public int GetHashCode(ThingDef obj) diff --git a/Assembly-CSharp/Verse/ThingFilter.cs b/Assembly-CSharp/Verse/ThingFilter.cs index cec34d096..75ea0bfa4 100644 --- a/Assembly-CSharp/Verse/ThingFilter.cs +++ b/Assembly-CSharp/Verse/ThingFilter.cs @@ -54,17 +54,17 @@ public string Summary { return this.customSummary; } - if (this.thingDefs != null && this.thingDefs.Count == 1 && this.categories.NullOrEmpty() && this.exceptedThingDefs.NullOrEmpty() && this.exceptedCategories.NullOrEmpty() && this.specialFiltersToAllow.NullOrEmpty() && this.specialFiltersToDisallow.NullOrEmpty() && this.stuffCategoriesToAllow.NullOrEmpty() && this.allowAllWhoCanMake.NullOrEmpty()) + if (this.thingDefs != null && this.thingDefs.Count == 1 && this.categories.NullOrEmpty() && this.exceptedThingDefs.NullOrEmpty() && this.exceptedCategories.NullOrEmpty() && this.specialFiltersToAllow.NullOrEmpty() && this.specialFiltersToDisallow.NullOrEmpty() && this.stuffCategoriesToAllow.NullOrEmpty() && this.allowAllWhoCanMake.NullOrEmpty()) { return this.thingDefs[0].label; } - if (this.thingDefs.NullOrEmpty() && this.categories != null && this.categories.Count == 1 && this.exceptedThingDefs.NullOrEmpty() && this.exceptedCategories.NullOrEmpty() && this.specialFiltersToAllow.NullOrEmpty() && this.specialFiltersToDisallow.NullOrEmpty() && this.stuffCategoriesToAllow.NullOrEmpty() && this.allowAllWhoCanMake.NullOrEmpty()) + if (this.thingDefs.NullOrEmpty() && this.categories != null && this.categories.Count == 1 && this.exceptedThingDefs.NullOrEmpty() && this.exceptedCategories.NullOrEmpty() && this.specialFiltersToAllow.NullOrEmpty() && this.specialFiltersToDisallow.NullOrEmpty() && this.stuffCategoriesToAllow.NullOrEmpty() && this.allowAllWhoCanMake.NullOrEmpty()) { return DefDatabase.GetNamed(this.categories[0], true).label; } if (this.allowedDefs.Count == 1) { - return this.allowedDefs.First().label; + return this.allowedDefs.First().label; } return "UsableIngredients".Translate(); } @@ -76,7 +76,7 @@ public ThingRequest BestThingRequest { if (this.allowedDefs.Count == 1) { - return ThingRequest.ForDef(this.allowedDefs.First()); + return ThingRequest.ForDef(this.allowedDefs.First()); } return ThingRequest.ForGroup(ThingRequestGroup.HaulableEver); } @@ -148,12 +148,11 @@ public TreeNode_ThingCategory DisplayRootCategory } set { - if (value == this.displayRootCategoryInt) + if (value != this.displayRootCategoryInt) { - return; + this.displayRootCategoryInt = value; + this.RecalculateSpecialFilterConfigurability(); } - this.displayRootCategoryInt = value; - this.RecalculateSpecialFilterConfigurability(); } } @@ -268,24 +267,33 @@ public void ResolveReferences() public void RecalculateDisplayRootCategory() { this.DisplayRootCategory = ThingCategoryNodeDatabase.RootNode; - foreach (TreeNode_ThingCategory current in ThingCategoryNodeDatabase.AllThingCategoryNodes) + foreach (TreeNode_ThingCategory allThingCategoryNode in ThingCategoryNodeDatabase.AllThingCategoryNodes) { bool flag = false; bool flag2 = false; - foreach (ThingDef current2 in this.allowedDefs) + HashSet.Enumerator enumerator2 = this.allowedDefs.GetEnumerator(); + try { - if (current.catDef.DescendantThingDefs.Contains(current2)) + while (enumerator2.MoveNext()) { - flag2 = true; - } - else - { - flag = true; + ThingDef current2 = enumerator2.Current; + if (allThingCategoryNode.catDef.DescendantThingDefs.Contains(current2)) + { + flag2 = true; + } + else + { + flag = true; + } } } + finally + { + ((IDisposable)(object)enumerator2).Dispose(); + } if (!flag && flag2) { - this.DisplayRootCategory = current; + this.DisplayRootCategory = allThingCategoryNode; } } } @@ -296,23 +304,23 @@ private void RecalculateSpecialFilterConfigurability() { this.allowedHitPointsConfigurable = true; this.allowedQualitiesConfigurable = true; - return; } - this.allowedHitPointsConfigurable = false; - this.allowedQualitiesConfigurable = false; - foreach (ThingDef current in this.DisplayRootCategory.catDef.DescendantThingDefs) + else { - if (current.useHitPoints) + this.allowedHitPointsConfigurable = false; + this.allowedQualitiesConfigurable = false; + foreach (ThingDef descendantThingDef in this.DisplayRootCategory.catDef.DescendantThingDefs) { - this.allowedHitPointsConfigurable = true; - } - if (current.HasComp(typeof(CompQuality))) - { - this.allowedQualitiesConfigurable = true; - } - if (this.allowedHitPointsConfigurable && this.allowedQualitiesConfigurable) - { - break; + if (descendantThingDef.useHitPoints) + { + this.allowedHitPointsConfigurable = true; + } + if (descendantThingDef.HasComp(typeof(CompQuality))) + { + this.allowedQualitiesConfigurable = true; + } + if (this.allowedHitPointsConfigurable && this.allowedQualitiesConfigurable) + break; } } } @@ -332,24 +340,24 @@ public bool IsAlwaysDisallowedDueToSpecialFilters(ThingDef def) public virtual void CopyAllowancesFrom(ThingFilter other) { this.allowedDefs.Clear(); - foreach (ThingDef current in ThingFilter.AllStorableThingDefs) + foreach (ThingDef allStorableThingDef in ThingFilter.AllStorableThingDefs) { - this.SetAllow(current, other.Allows(current)); + this.SetAllow(allStorableThingDef, other.Allows(allStorableThingDef)); } - this.disallowedSpecialFilters = other.disallowedSpecialFilters.ListFullCopyOrNull(); + this.disallowedSpecialFilters = other.disallowedSpecialFilters.ListFullCopyOrNull(); this.allowedHitPointsPercents = other.allowedHitPointsPercents; this.allowedHitPointsConfigurable = other.allowedHitPointsConfigurable; this.allowedQualities = other.allowedQualities; this.allowedQualitiesConfigurable = other.allowedQualitiesConfigurable; - this.thingDefs = other.thingDefs.ListFullCopyOrNull(); - this.categories = other.categories.ListFullCopyOrNull(); - this.exceptedThingDefs = other.exceptedThingDefs.ListFullCopyOrNull(); - this.exceptedCategories = other.exceptedCategories.ListFullCopyOrNull(); - this.specialFiltersToAllow = other.specialFiltersToAllow.ListFullCopyOrNull(); - this.specialFiltersToDisallow = other.specialFiltersToDisallow.ListFullCopyOrNull(); - this.stuffCategoriesToAllow = other.stuffCategoriesToAllow.ListFullCopyOrNull(); - this.allowAllWhoCanMake = other.allowAllWhoCanMake.ListFullCopyOrNull(); - if (this.settingsChangedCallback != null) + this.thingDefs = other.thingDefs.ListFullCopyOrNull(); + this.categories = other.categories.ListFullCopyOrNull(); + this.exceptedThingDefs = other.exceptedThingDefs.ListFullCopyOrNull(); + this.exceptedCategories = other.exceptedCategories.ListFullCopyOrNull(); + this.specialFiltersToAllow = other.specialFiltersToAllow.ListFullCopyOrNull(); + this.specialFiltersToDisallow = other.specialFiltersToDisallow.ListFullCopyOrNull(); + this.stuffCategoriesToAllow = other.stuffCategoriesToAllow.ListFullCopyOrNull(); + this.allowAllWhoCanMake = other.allowAllWhoCanMake.ListFullCopyOrNull(); + if ((object)this.settingsChangedCallback != null) { this.settingsChangedCallback(); } @@ -357,48 +365,42 @@ public virtual void CopyAllowancesFrom(ThingFilter other) public void SetAllow(ThingDef thingDef, bool allow) { - if (allow == this.Allows(thingDef)) - { - return; - } - if (allow) - { - this.allowedDefs.Add(thingDef); - } - else - { - this.allowedDefs.Remove(thingDef); - } - if (this.settingsChangedCallback != null) + if (allow != this.Allows(thingDef)) { - this.settingsChangedCallback(); + if (allow) + { + this.allowedDefs.Add(thingDef); + } + else + { + this.allowedDefs.Remove(thingDef); + } + if ((object)this.settingsChangedCallback != null) + { + this.settingsChangedCallback(); + } } } public void SetAllow(SpecialThingFilterDef sfDef, bool allow) { - if (!sfDef.configurable) - { - return; - } - if (allow == this.Allows(sfDef)) + if (sfDef.configurable && allow != this.Allows(sfDef)) { - return; - } - if (allow) - { - if (this.disallowedSpecialFilters.Contains(sfDef)) + if (allow) { - this.disallowedSpecialFilters.Remove(sfDef); + if (this.disallowedSpecialFilters.Contains(sfDef)) + { + this.disallowedSpecialFilters.Remove(sfDef); + } + } + else if (!this.disallowedSpecialFilters.Contains(sfDef)) + { + this.disallowedSpecialFilters.Add(sfDef); + } + if ((object)this.settingsChangedCallback != null) + { + this.settingsChangedCallback(); } - } - else if (!this.disallowedSpecialFilters.Contains(sfDef)) - { - this.disallowedSpecialFilters.Add(sfDef); - } - if (this.settingsChangedCallback != null) - { - this.settingsChangedCallback(); } } @@ -408,21 +410,21 @@ public void SetAllow(ThingCategoryDef categoryDef, bool allow, IEnumerable exceptedDefs = null, IEnumerable exceptedFilters = null) { - this.allowedDefs.RemoveWhere((ThingDef d) => exceptedDefs == null || !exceptedDefs.Contains(d)); - this.disallowedSpecialFilters.RemoveAll((SpecialThingFilterDef sf) => sf.configurable && (exceptedFilters == null || !exceptedFilters.Contains(sf))); - foreach (SpecialThingFilterDef current in DefDatabase.AllDefs) + this.allowedDefs.RemoveWhere((Predicate)((ThingDef d) => exceptedDefs == null || !exceptedDefs.Contains(d))); + this.disallowedSpecialFilters.RemoveAll((Predicate)((SpecialThingFilterDef sf) => sf.configurable && (exceptedFilters == null || !exceptedFilters.Contains(sf)))); + foreach (SpecialThingFilterDef allDef in DefDatabase.AllDefs) { - if (current.configurable && (exceptedFilters == null || !exceptedFilters.Contains(current))) + if (allDef.configurable && (exceptedFilters == null || !exceptedFilters.Contains(allDef))) { - this.disallowedSpecialFilters.Add(current); + this.disallowedSpecialFilters.Add(allDef); } } - if (this.settingsChangedCallback != null) + if ((object)this.settingsChangedCallback != null) { this.settingsChangedCallback(); } @@ -506,23 +508,32 @@ public void SetAllowAll(ThingFilter parentFilter) this.allowedDefs.Clear(); if (parentFilter != null) { - foreach (ThingDef current in parentFilter.allowedDefs) + HashSet.Enumerator enumerator = parentFilter.allowedDefs.GetEnumerator(); + try + { + while (enumerator.MoveNext()) + { + ThingDef current = enumerator.Current; + this.allowedDefs.Add(current); + } + } + finally { - this.allowedDefs.Add(current); + ((IDisposable)(object)enumerator).Dispose(); } } else { - foreach (ThingDef current2 in DefDatabase.AllDefs) + foreach (ThingDef allDef in DefDatabase.AllDefs) { - if (!current2.thingCategories.NullOrEmpty()) + if (!allDef.thingCategories.NullOrEmpty()) { - this.allowedDefs.Add(current2); + this.allowedDefs.Add(allDef); } } } - this.disallowedSpecialFilters.RemoveAll((SpecialThingFilterDef sf) => sf.configurable); - if (this.settingsChangedCallback != null) + this.disallowedSpecialFilters.RemoveAll((Predicate)((SpecialThingFilterDef sf) => sf.configurable)); + if ((object)this.settingsChangedCallback != null) { this.settingsChangedCallback(); } @@ -536,16 +547,16 @@ public virtual bool Allows(Thing t) } if (t.def.useHitPoints) { - float num = (float)t.HitPoints / (float)t.MaxHitPoints; - num = GenMath.RoundedHundredth(num); - if (!this.allowedHitPointsPercents.IncludesEpsilon(Mathf.Clamp01(num))) + float f = (float)t.HitPoints / (float)t.MaxHitPoints; + f = GenMath.RoundedHundredth(f); + if (!this.allowedHitPointsPercents.IncludesEpsilon(Mathf.Clamp01(f))) { return false; } } if (this.allowedQualities != QualityRange.All && t.def.FollowQualityThingFilter()) { - QualityCategory p; + QualityCategory p = default(QualityCategory); if (!t.TryGetQuality(out p)) { p = QualityCategory.Normal; @@ -577,7 +588,7 @@ public bool Allows(SpecialThingFilterDef sf) public ThingRequest GetThingRequest() { - if (this.AllowedThingDefs.Any((ThingDef def) => !def.alwaysHaulable)) + if (this.AllowedThingDefs.Any((Func)((ThingDef def) => !def.alwaysHaulable))) { return ThingRequest.ForGroup(ThingRequestGroup.HaulableEver); } diff --git a/Assembly-CSharp/Verse/ThingFilterUI.cs b/Assembly-CSharp/Verse/ThingFilterUI.cs index 485fa33ac..6542e8241 100644 --- a/Assembly-CSharp/Verse/ThingFilterUI.cs +++ b/Assembly-CSharp/Verse/ThingFilterUI.cs @@ -1,5 +1,4 @@ using RimWorld; -using System; using System.Collections.Generic; using UnityEngine; @@ -23,20 +22,20 @@ public static void DoThingFilterConfigWindow(Rect rect, ref Vector2 scrollPositi { Widgets.DrawMenuSection(rect, true); Text.Font = GameFont.Tiny; - float num = rect.width - 2f; - Rect rect2 = new Rect(rect.x + 1f, rect.y + 1f, num / 2f, 24f); + float num = (float)(rect.width - 2.0); + Rect rect2 = new Rect((float)(rect.x + 1.0), (float)(rect.y + 1.0), (float)(num / 2.0), 24f); if (Widgets.ButtonText(rect2, "ClearAll".Translate(), true, false, true)) { filter.SetDisallowAll(forceHiddenDefs, forceHiddenFilters); } - Rect rect3 = new Rect(rect2.xMax + 1f, rect2.y, rect.xMax - 1f - (rect2.xMax + 1f), 24f); + Rect rect3 = new Rect((float)(rect2.xMax + 1.0), rect2.y, (float)(rect.xMax - 1.0 - (rect2.xMax + 1.0)), 24f); if (Widgets.ButtonText(rect3, "AllowAll".Translate(), true, false, true)) { filter.SetAllowAll(parentFilter); } Text.Font = GameFont.Small; rect.yMin = rect2.yMax; - Rect viewRect = new Rect(0f, 0f, rect.width - 16f, ThingFilterUI.viewHeight); + Rect viewRect = new Rect(0f, 0f, (float)(rect.width - 16.0), ThingFilterUI.viewHeight); Widgets.BeginScrollView(rect, ref scrollPosition, viewRect, true); float num2 = 2f; ThingFilterUI.DrawHitPointsFilterConfig(ref num2, viewRect.width, filter); @@ -54,39 +53,37 @@ public static void DoThingFilterConfigWindow(Rect rect, ref Vector2 scrollPositi listing_TreeThingFilter.End(); if (Event.current.type == EventType.Layout) { - ThingFilterUI.viewHeight = num3 + listing_TreeThingFilter.CurHeight + 90f; + ThingFilterUI.viewHeight = (float)(num3 + listing_TreeThingFilter.CurHeight + 90.0); } Widgets.EndScrollView(); } private static void DrawHitPointsFilterConfig(ref float y, float width, ThingFilter filter) { - if (!filter.allowedHitPointsConfigurable) + if (filter.allowedHitPointsConfigurable) { - return; + Rect rect = new Rect(20f, y, (float)(width - 20.0), 26f); + FloatRange allowedHitPointsPercents = filter.AllowedHitPointsPercents; + Widgets.FloatRange(rect, 1, ref allowedHitPointsPercents, 0f, 1f, "HitPoints", ToStringStyle.PercentZero); + filter.AllowedHitPointsPercents = allowedHitPointsPercents; + y += 26f; + y += 5f; + Text.Font = GameFont.Small; } - Rect rect = new Rect(20f, y, width - 20f, 26f); - FloatRange allowedHitPointsPercents = filter.AllowedHitPointsPercents; - Widgets.FloatRange(rect, 1, ref allowedHitPointsPercents, 0f, 1f, "HitPoints", ToStringStyle.PercentZero); - filter.AllowedHitPointsPercents = allowedHitPointsPercents; - y += 26f; - y += 5f; - Text.Font = GameFont.Small; } private static void DrawQualityFilterConfig(ref float y, float width, ThingFilter filter) { - if (!filter.allowedQualitiesConfigurable) + if (filter.allowedQualitiesConfigurable) { - return; + Rect rect = new Rect(20f, y, (float)(width - 20.0), 26f); + QualityRange allowedQualityLevels = filter.AllowedQualityLevels; + Widgets.QualityRange(rect, 2, ref allowedQualityLevels); + filter.AllowedQualityLevels = allowedQualityLevels; + y += 26f; + y += 5f; + Text.Font = GameFont.Small; } - Rect rect = new Rect(20f, y, width - 20f, 26f); - QualityRange allowedQualityLevels = filter.AllowedQualityLevels; - Widgets.QualityRange(rect, 2, ref allowedQualityLevels); - filter.AllowedQualityLevels = allowedQualityLevels; - y += 26f; - y += 5f; - Text.Font = GameFont.Small; } } } diff --git a/Assembly-CSharp/Verse/ThingGrid.cs b/Assembly-CSharp/Verse/ThingGrid.cs index efc9a7b82..faf319ef4 100644 --- a/Assembly-CSharp/Verse/ThingGrid.cs +++ b/Assembly-CSharp/Verse/ThingGrid.cs @@ -1,6 +1,4 @@ -using System; using System.Collections.Generic; -using System.Diagnostics; namespace Verse { @@ -46,25 +44,19 @@ private void RegisterInCell(Thing t, IntVec3 c) { if (!c.InBounds(this.map)) { - Log.Warning(string.Concat(new object[] - { - t, - " tried to register out of bounds at ", - c, - ". Destroying." - })); + Log.Warning(t + " tried to register out of bounds at " + c + ". Destroying."); t.Destroy(DestroyMode.Vanish); - return; } - this.thingGrid[this.map.cellIndices.CellToIndex(c)].Add(t); + else + { + this.thingGrid[this.map.cellIndices.CellToIndex(c)].Add(t); + } } public void Deregister(Thing t, bool doEvenIfDespawned = false) { if (!t.Spawned && !doEvenIfDespawned) - { return; - } if (t.def.size.x == 1 && t.def.size.z == 1) { this.DeregisterInCell(t, t.Position); @@ -87,25 +79,27 @@ private void DeregisterInCell(Thing t, IntVec3 c) if (!c.InBounds(this.map)) { Log.Error(t + " tried to de-register out of bounds at " + c); - return; } - int num = this.map.cellIndices.CellToIndex(c); - if (this.thingGrid[num].Contains(t)) + else { - this.thingGrid[num].Remove(t); + int num = this.map.cellIndices.CellToIndex(c); + if (this.thingGrid[num].Contains(t)) + { + this.thingGrid[num].Remove(t); + } } } - [DebuggerHidden] public IEnumerable ThingsAt(IntVec3 c) { - ThingGrid.c__Iterator1F7 c__Iterator1F = new ThingGrid.c__Iterator1F7(); - c__Iterator1F.c = c; - c__Iterator1F.<$>c = c; - c__Iterator1F.<>f__this = this; - ThingGrid.c__Iterator1F7 expr_1C = c__Iterator1F; - expr_1C.$PC = -2; - return expr_1C; + if (c.InBounds(this.map)) + { + List list = this.thingGrid[this.map.cellIndices.CellToIndex(c)]; + for (int i = 0; i < list.Count; i++) + { + yield return list[i]; + } + } } public List ThingsListAt(IntVec3 c) @@ -176,18 +170,18 @@ public T ThingAt(IntVec3 c) where T : Thing { if (!c.InBounds(this.map)) { - return (T)((object)null); + return (T)null; } List list = this.thingGrid[this.map.cellIndices.CellToIndex(c)]; for (int i = 0; i < list.Count; i++) { - T t = list[i] as T; - if (t != null) + T val = (T)(list[i] as T); + if (val != null) { - return t; + return val; } } - return (T)((object)null); + return (T)null; } } } diff --git a/Assembly-CSharp/Verse/ThingIDMaker.cs b/Assembly-CSharp/Verse/ThingIDMaker.cs index 9a19736c1..45f9c3716 100644 --- a/Assembly-CSharp/Verse/ThingIDMaker.cs +++ b/Assembly-CSharp/Verse/ThingIDMaker.cs @@ -1,26 +1,17 @@ -using System; - namespace Verse { public static class ThingIDMaker { public static void GiveIDTo(Thing t) { - if (!t.def.HasThingIDNumber) + if (t.def.HasThingIDNumber) { - return; - } - if (t.thingIDNumber != -1) - { - Log.Error(string.Concat(new object[] + if (t.thingIDNumber != -1) { - "Giving ID to ", - t, - " which already has id ", - t.thingIDNumber - })); + Log.Error("Giving ID to " + t + " which already has id " + t.thingIDNumber); + } + t.thingIDNumber = Find.World.uniqueIDsManager.GetNextThingID(); } - t.thingIDNumber = Find.World.uniqueIDsManager.GetNextThingID(); } } } diff --git a/Assembly-CSharp/Verse/ThingListGroupHelper.cs b/Assembly-CSharp/Verse/ThingListGroupHelper.cs index 9277f78d3..6ab7dc614 100644 --- a/Assembly-CSharp/Verse/ThingListGroupHelper.cs +++ b/Assembly-CSharp/Verse/ThingListGroupHelper.cs @@ -13,9 +13,9 @@ static ThingListGroupHelper() int length = Enum.GetValues(typeof(ThingRequestGroup)).Length; ThingListGroupHelper.AllGroups = new ThingRequestGroup[length]; int num = 0; - foreach (object current in Enum.GetValues(typeof(ThingRequestGroup))) + foreach (object value in Enum.GetValues(typeof(ThingRequestGroup))) { - ThingListGroupHelper.AllGroups[num] = (ThingRequestGroup)((byte)current); + ThingListGroupHelper.AllGroups[num] = (ThingRequestGroup)(byte)value; num++; } } @@ -25,70 +25,134 @@ public static bool Includes(this ThingRequestGroup group, ThingDef def) switch (group) { case ThingRequestGroup.Undefined: + { return false; + } case ThingRequestGroup.Nothing: + { return false; + } case ThingRequestGroup.Everything: + { return true; + } case ThingRequestGroup.HaulableEver: + { return def.EverHaulable; + } case ThingRequestGroup.HaulableAlways: + { return def.alwaysHaulable; + } case ThingRequestGroup.Plant: + { return def.category == ThingCategory.Plant; + } case ThingRequestGroup.FoodSource: + { return def.IsNutritionGivingIngestible || def.thingClass == typeof(Building_NutrientPasteDispenser); + } case ThingRequestGroup.FoodSourceNotPlantOrTree: - return (def.IsNutritionGivingIngestible && (def.ingestible.foodType & ~FoodTypeFlags.Plant & ~FoodTypeFlags.Tree) != FoodTypeFlags.None) || def.thingClass == typeof(Building_NutrientPasteDispenser); + { + return (def.IsNutritionGivingIngestible ? ((int)def.ingestible.foodType & -65 & -129) : 0) != 0 || def.thingClass == typeof(Building_NutrientPasteDispenser); + } + case ThingRequestGroup.HasGUIOverlay: + { + return def.drawGUIOverlay; + } case ThingRequestGroup.Corpse: + { return def.thingClass == typeof(Corpse); + } case ThingRequestGroup.Blueprint: + { return def.IsBlueprint; + } + case ThingRequestGroup.Construction: + { + return def.IsBlueprint || def.IsFrame; + } case ThingRequestGroup.BuildingArtificial: + { return (def.category == ThingCategory.Building || def.IsFrame) && (def.building == null || (!def.building.isNaturalRock && !def.building.isResourceRock)); + } case ThingRequestGroup.BuildingFrame: + { return def.IsFrame; + } case ThingRequestGroup.Pawn: + { return def.category == ThingCategory.Pawn; + } case ThingRequestGroup.PotentialBillGiver: - return !def.AllRecipes.NullOrEmpty(); + { + return !def.AllRecipes.NullOrEmpty(); + } case ThingRequestGroup.Medicine: + { return def.IsMedicine; + } + case ThingRequestGroup.Apparel: + { + return def.IsApparel; + } + case ThingRequestGroup.MinifiedThing: + { + return typeof(MinifiedThing).IsAssignableFrom(def.thingClass); + } case ThingRequestGroup.Filth: + { return def.filth != null; + } case ThingRequestGroup.AttackTarget: + { return typeof(IAttackTarget).IsAssignableFrom(def.thingClass); + } case ThingRequestGroup.Weapon: + { return def.IsWeapon; + } case ThingRequestGroup.Refuelable: + { return def.HasComp(typeof(CompRefuelable)); + } case ThingRequestGroup.HaulableEverOrMinifiable: + { return def.EverHaulable || def.Minifiable; + } case ThingRequestGroup.Drug: + { return def.IsDrug; - case ThingRequestGroup.Construction: - return def.IsBlueprint || def.IsFrame; - case ThingRequestGroup.HasGUIOverlay: - return def.drawGUIOverlay; - case ThingRequestGroup.Apparel: - return def.IsApparel; - case ThingRequestGroup.MinifiedThing: - return typeof(MinifiedThing).IsAssignableFrom(def.thingClass); + } case ThingRequestGroup.Grave: + { return typeof(Building_Grave).IsAssignableFrom(def.thingClass); + } case ThingRequestGroup.Art: + { return def.HasComp(typeof(CompArt)); + } case ThingRequestGroup.ThisOrAnyCompIsThingHolder: + { return def.ThisOrAnyCompIsThingHolder(); + } case ThingRequestGroup.ActiveDropPod: + { return typeof(IActiveDropPod).IsAssignableFrom(def.thingClass); + } case ThingRequestGroup.Transporter: + { return def.HasComp(typeof(CompTransporter)); + } case ThingRequestGroup.LongRangeMineralScanner: + { return def.HasComp(typeof(CompLongRangeMineralScanner)); + } default: + { throw new ArgumentException("group"); } + } } } } diff --git a/Assembly-CSharp/Verse/ThingMaker.cs b/Assembly-CSharp/Verse/ThingMaker.cs index 792d59153..41444ac90 100644 --- a/Assembly-CSharp/Verse/ThingMaker.cs +++ b/Assembly-CSharp/Verse/ThingMaker.cs @@ -9,14 +9,7 @@ public static Thing MakeThing(ThingDef def, ThingDef stuff = null) { if (stuff != null && !stuff.IsStuff) { - Log.Error(string.Concat(new object[] - { - "MakeThing error: Tried to make ", - def, - " from ", - stuff, - " which is not a stuff. Assigning default." - })); + Log.Error("MakeThing error: Tried to make " + def + " from " + stuff + " which is not a stuff. Assigning default."); stuff = GenStuff.DefaultStuffFor(def); } if (def.MadeFromStuff && stuff == null) @@ -26,14 +19,7 @@ public static Thing MakeThing(ThingDef def, ThingDef stuff = null) } if (!def.MadeFromStuff && stuff != null) { - Log.Error(string.Concat(new object[] - { - "MakeThing error: ", - def, - " is not madeFromStuff but stuff=", - stuff, - ". Setting to null." - })); + Log.Error("MakeThing error: " + def + " is not madeFromStuff but stuff=" + stuff + ". Setting to null."); stuff = null; } Thing thing = (Thing)Activator.CreateInstance(def.thingClass); diff --git a/Assembly-CSharp/Verse/ThingOverlays.cs b/Assembly-CSharp/Verse/ThingOverlays.cs index 560cf6487..cc43e031e 100644 --- a/Assembly-CSharp/Verse/ThingOverlays.cs +++ b/Assembly-CSharp/Verse/ThingOverlays.cs @@ -8,18 +8,14 @@ public class ThingOverlays { public void ThingOverlaysOnGUI() { - if (Event.current.type != EventType.Repaint) + if (Event.current.type == EventType.Repaint) { - return; - } - CellRect currentViewRect = Find.CameraDriver.CurrentViewRect; - List list = Find.VisibleMap.listerThings.ThingsInGroup(ThingRequestGroup.HasGUIOverlay); - for (int i = 0; i < list.Count; i++) - { - Thing thing = list[i]; - if (currentViewRect.Contains(thing.Position)) + CellRect currentViewRect = Find.CameraDriver.CurrentViewRect; + List list = Find.VisibleMap.listerThings.ThingsInGroup(ThingRequestGroup.HasGUIOverlay); + for (int i = 0; i < list.Count; i++) { - if (!Find.VisibleMap.fogGrid.IsFogged(thing.Position)) + Thing thing = list[i]; + if (currentViewRect.Contains(thing.Position) && !Find.VisibleMap.fogGrid.IsFogged(thing.Position)) { try { @@ -27,13 +23,7 @@ public void ThingOverlaysOnGUI() } catch (Exception ex) { - Log.Error(string.Concat(new object[] - { - "Exception drawing ThingOverlay for ", - thing, - ": ", - ex - })); + Log.Error("Exception drawing ThingOverlay for " + thing + ": " + ex); } } } diff --git a/Assembly-CSharp/Verse/ThingOwner.cs b/Assembly-CSharp/Verse/ThingOwner.cs index 2eca552db..d155ba695 100644 --- a/Assembly-CSharp/Verse/ThingOwner.cs +++ b/Assembly-CSharp/Verse/ThingOwner.cs @@ -3,7 +3,6 @@ using System; using System.Collections; using System.Collections.Generic; -using System.Diagnostics; using System.Text; using UnityEngine; @@ -81,7 +80,7 @@ void IList.Insert(int index, T item) void ICollection.Add(T item) { - this.TryAdd(item, true); + this.TryAdd((Thing)(object)item, true); } void ICollection.CopyTo(T[] array, int arrayIndex) @@ -96,35 +95,34 @@ bool ICollection.Contains(T item) bool ICollection.Remove(T item) { - return this.Remove(item); + return this.Remove((Thing)(object)item); } IEnumerator IEnumerable.GetEnumerator() { - return this.innerList.GetEnumerator(); + return (IEnumerator)(object)this.innerList.GetEnumerator(); } IEnumerator IEnumerable.GetEnumerator() { - return this.innerList.GetEnumerator(); + return (IEnumerator)(object)this.innerList.GetEnumerator(); } public override void ExposeData() { base.ExposeData(); - Scribe_Collections.Look(ref this.innerList, true, "innerList", this.contentsLookMode, new object[0]); + Scribe_Collections.Look(ref this.innerList, true, "innerList", base.contentsLookMode, new object[0]); if (Scribe.mode == LoadSaveMode.PostLoadInit) { - this.innerList.RemoveAll((T x) => x == null); + this.innerList.RemoveAll((Predicate)((T x) => x == null)); } - if (Scribe.mode == LoadSaveMode.LoadingVars || Scribe.mode == LoadSaveMode.PostLoadInit) + if (Scribe.mode != LoadSaveMode.LoadingVars && Scribe.mode != LoadSaveMode.PostLoadInit) + return; + for (int i = 0; i < this.innerList.Count; i++) { - for (int i = 0; i < this.innerList.Count; i++) + if (this.innerList[i] != null) { - if (this.innerList[i] != null) - { - this.innerList[i].holdingOwner = this; - } + ((Thing)(object)this.innerList[i]).holdingOwner = this; } } } @@ -166,18 +164,18 @@ public override int TryAdd(Thing item, int count, bool canMergeWithExistingStack { this.Remove(thing); } - if (this.TryAdd((T)((object)thing), canMergeWithExistingStacks)) + if (!this.TryAdd((Thing)(object)(T)thing, canMergeWithExistingStacks)) { - return num; - } - if (thing != item) - { - int result = stackCount - item.stackCount - thing.stackCount; - item.TryAbsorbStack(thing, false); - return result; + if (thing != item) + { + int result = stackCount - item.stackCount - thing.stackCount; + item.TryAbsorbStack(thing, false); + return result; + } + this.TryAdd(thing, false); + return stackCount - item.stackCount; } - this.TryAdd(thing, false); - return stackCount - item.stackCount; + return num; } public override bool TryAdd(Thing item, bool canMergeWithExistingStacks = true) @@ -187,8 +185,8 @@ public override bool TryAdd(Thing item, bool canMergeWithExistingStacks = true) Log.Warning("Tried to add null item to ThingOwner."); return false; } - T t = item as T; - if (t == null) + T val = (T)(item as T); + if (val == null) { return false; } @@ -199,15 +197,7 @@ public override bool TryAdd(Thing item, bool canMergeWithExistingStacks = true) } if (item.holdingOwner != null) { - Log.Warning(string.Concat(new string[] - { - "Tried to add ", - item.ToStringSafe(), - " to ThingOwner but this thing is already in another container. owner=", - this.owner.ToStringSafe(), - ", other container owner=", - item.holdingOwner.Owner.ToStringSafe() - })); + Log.Warning("Tried to add " + item.ToStringSafe() + " to ThingOwner but this thing is already in another container. owner=" + base.owner.ToStringSafe() + ", other container owner=" + item.holdingOwner.Owner.ToStringSafe()); return false; } if (!this.CanAcceptAnyOf(item, canMergeWithExistingStacks)) @@ -218,63 +208,63 @@ public override bool TryAdd(Thing item, bool canMergeWithExistingStacks = true) { for (int i = 0; i < this.innerList.Count; i++) { - T t2 = this.innerList[i]; - if (t2.CanStackWith(item)) + T val2 = this.innerList[i]; + if (val2.CanStackWith(item)) { - int num = Mathf.Min(item.stackCount, t2.def.stackLimit - t2.stackCount); + int num = Mathf.Min(item.stackCount, ((Thing)(object)val2).def.stackLimit - ((Thing)(object)val2).stackCount); if (num > 0) { Thing other = item.SplitOff(num); - int stackCount = t2.stackCount; - t2.TryAbsorbStack(other, true); - if (t2.stackCount > stackCount) + int stackCount = ((Thing)(object)val2).stackCount; + val2.TryAbsorbStack(other, true); + if (((Thing)(object)val2).stackCount > stackCount) { - base.NotifyAddedAndMergedWith(t2, t2.stackCount - stackCount); + base.NotifyAddedAndMergedWith((Thing)(object)val2, ((Thing)(object)val2).stackCount - stackCount); } - if (item.Destroyed || item.stackCount == 0) + if (((!item.Destroyed) ? item.stackCount : 0) != 0) { - return true; + continue; } + return true; } } } } - if (this.Count >= this.maxStacks) + if (this.Count >= base.maxStacks) { return false; } item.holdingOwner = this; - this.innerList.Add(t); - base.NotifyAdded(t); + this.innerList.Add(val); + base.NotifyAdded((Thing)(object)val); return true; } - public new void TryAddRange(IEnumerable things, bool canMergeWithExistingStacks = true) + public void TryAddRange(IEnumerable things, bool canMergeWithExistingStacks = true) { - if (things == this) - { - return; - } - ThingOwner thingOwner = things as ThingOwner; - if (thingOwner != null) - { - thingOwner.TryTransferAllToContainer(this, canMergeWithExistingStacks); - } - else + if (things != this) { - IList list = things as IList; - if (list != null) + ThingOwner thingOwner = things as ThingOwner; + if (thingOwner != null) { - for (int i = 0; i < list.Count; i++) - { - this.TryAdd(list[i], canMergeWithExistingStacks); - } + thingOwner.TryTransferAllToContainer(this, canMergeWithExistingStacks); } else { - foreach (T current in things) + IList list = things as IList; + if (list != null) { - this.TryAdd(current, canMergeWithExistingStacks); + for (int i = 0; i < ((ICollection)list).Count; i++) + { + this.TryAdd((Thing)(object)list[i], canMergeWithExistingStacks); + } + } + else + { + foreach (T item in things) + { + this.TryAdd((Thing)(object)item, canMergeWithExistingStacks); + } } } } @@ -282,12 +272,12 @@ public override bool TryAdd(Thing item, bool canMergeWithExistingStacks = true) public override int IndexOf(Thing item) { - T t = item as T; - if (t == null) + T val = (T)(item as T); + if (val == null) { return -1; } - return this.innerList.IndexOf(t); + return this.innerList.IndexOf(val); } public override bool Remove(Thing item) @@ -300,20 +290,20 @@ public override bool Remove(Thing item) { item.holdingOwner = null; } - int index = this.innerList.LastIndexOf((T)((object)item)); + int index = this.innerList.LastIndexOf((T)item); this.innerList.RemoveAt(index); base.NotifyRemoved(item); return true; } - public new int RemoveAll(Predicate predicate) + public int RemoveAll(Predicate predicate) { int num = 0; - for (int i = this.innerList.Count - 1; i >= 0; i--) + for (int num2 = this.innerList.Count - 1; num2 >= 0; num2--) { - if (predicate(this.innerList[i])) + if (predicate(this.innerList[num2])) { - this.Remove(this.innerList[i]); + this.Remove((Thing)(object)this.innerList[num2]); num++; } } @@ -322,67 +312,67 @@ public override bool Remove(Thing item) protected override Thing GetAt(int index) { - return this.innerList[index]; + return (Thing)(object)this.innerList[index]; } public bool TryTransferToContainer(Thing item, ThingOwner otherContainer, int stackCount, out T resultingTransferredItem, bool canMergeWithExistingStacks = true) { - Thing thing; + Thing thing = default(Thing); bool result = base.TryTransferToContainer(item, otherContainer, stackCount, out thing, canMergeWithExistingStacks); - resultingTransferredItem = (T)((object)thing); + resultingTransferredItem = (T)thing; return result; } public new T Take(Thing thing, int count) { - return (T)((object)base.Take(thing, count)); + return (T)base.Take(thing, count); } public bool TryDrop(Thing thing, IntVec3 dropLoc, Map map, ThingPlaceMode mode, int count, out T resultingThing, Action placedAction = null) { Action placedAction2 = null; - if (placedAction != null) + if ((object)placedAction != null) { - placedAction2 = delegate(Thing t, int c) + placedAction2 = (Action)delegate(Thing t, int c) { - placedAction((T)((object)t), c); + placedAction((T)t, c); }; } - Thing thing2; + Thing thing2 = default(Thing); bool result = base.TryDrop(thing, dropLoc, map, mode, count, out thing2, placedAction2); - resultingThing = (T)((object)thing2); + resultingThing = (T)thing2; return result; } public bool TryDrop(Thing thing, ThingPlaceMode mode, out T lastResultingThing, Action placedAction = null) { Action placedAction2 = null; - if (placedAction != null) + if ((object)placedAction != null) { - placedAction2 = delegate(Thing t, int c) + placedAction2 = (Action)delegate(Thing t, int c) { - placedAction((T)((object)t), c); + placedAction((T)t, c); }; } - Thing thing2; + Thing thing2 = default(Thing); bool result = base.TryDrop(thing, mode, out thing2, placedAction2); - lastResultingThing = (T)((object)thing2); + lastResultingThing = (T)thing2; return result; } public bool TryDrop(Thing thing, IntVec3 dropLoc, Map map, ThingPlaceMode mode, out T lastResultingThing, Action placedAction = null) { Action placedAction2 = null; - if (placedAction != null) + if ((object)placedAction != null) { - placedAction2 = delegate(Thing t, int c) + placedAction2 = (Action)delegate(Thing t, int c) { - placedAction((T)((object)t), c); + placedAction((T)t, c); }; } - Thing thing2; + Thing thing2 = default(Thing); bool result = base.TryDrop(thing, dropLoc, map, mode, out thing2, placedAction2); - lastResultingThing = (T)((object)thing2); + lastResultingThing = (T)thing2; return result; } } @@ -449,9 +439,9 @@ public int TotalStackCount { int num = 0; int count = this.Count; - for (int i = 0; i < count; i++) + for (int num2 = 0; num2 < count; num2++) { - num += this.GetAt(i).stackCount; + num += this.GetAt(num2).stackCount; } return num; } @@ -467,13 +457,13 @@ public string ContentsString return "NothingLower".Translate(); } StringBuilder stringBuilder = new StringBuilder(); - for (int i = 0; i < count; i++) + for (int num = 0; num < count; num++) { - if (i != 0) + if (num != 0) { stringBuilder.Append(", "); } - stringBuilder.Append(this.GetAt(i).Label); + stringBuilder.Append(this.GetAt(num).Label); } return stringBuilder.ToString(); } @@ -490,7 +480,7 @@ public ThingOwner(IThingHolder owner) public ThingOwner(IThingHolder owner, bool oneStackOnly, LookMode contentsLookMode = LookMode.Deep) : this(owner) { - this.maxStacks = ((!oneStackOnly) ? 999999 : 1); + this.maxStacks = (oneStackOnly ? 1 : 999999); this.contentsLookMode = contentsLookMode; } @@ -512,20 +502,20 @@ void ICollection.CopyTo(Thing[] array, int arrayIndex) } } - [DebuggerHidden] IEnumerator IEnumerable.GetEnumerator() { - ThingOwner.GetEnumerator>c__Iterator22E getEnumerator>c__Iterator22E = new ThingOwner.GetEnumerator>c__Iterator22E(); - getEnumerator>c__Iterator22E.<>f__this = this; - return getEnumerator>c__Iterator22E; + for (int i = 0; i < this.Count; i++) + { + yield return this.GetAt(i); + } } - [DebuggerHidden] IEnumerator IEnumerable.GetEnumerator() { - ThingOwner.GetEnumerator>c__Iterator22F getEnumerator>c__Iterator22F = new ThingOwner.GetEnumerator>c__Iterator22F(); - getEnumerator>c__Iterator22F.<>f__this = this; - return getEnumerator>c__Iterator22F; + for (int i = 0; i < this.Count; i++) + { + yield return (object)this.GetAt(i); + } } public virtual void ExposeData() @@ -536,9 +526,9 @@ public virtual void ExposeData() public void ThingOwnerTick(bool removeIfDestroyed = true) { - for (int i = this.Count - 1; i >= 0; i--) + for (int num = this.Count - 1; num >= 0; num--) { - Thing at = this.GetAt(i); + Thing at = this.GetAt(num); if (at.def.tickerType == TickerType.Normal) { at.Tick(); @@ -552,9 +542,9 @@ public void ThingOwnerTick(bool removeIfDestroyed = true) public void ThingOwnerTickRare(bool removeIfDestroyed = true) { - for (int i = this.Count - 1; i >= 0; i--) + for (int num = this.Count - 1; num >= 0; num--) { - Thing at = this.GetAt(i); + Thing at = this.GetAt(num); if (at.def.tickerType == TickerType.Rare) { at.TickRare(); @@ -568,9 +558,9 @@ public void ThingOwnerTickRare(bool removeIfDestroyed = true) public void ThingOwnerTickLong(bool removeIfDestroyed = true) { - for (int i = this.Count - 1; i >= 0; i--) + for (int num = this.Count - 1; num >= 0; num--) { - Thing at = this.GetAt(i); + Thing at = this.GetAt(num); if (at.def.tickerType == TickerType.Long) { at.TickRare(); @@ -584,9 +574,9 @@ public void ThingOwnerTickLong(bool removeIfDestroyed = true) public void Clear() { - for (int i = this.Count - 1; i >= 0; i--) + for (int num = this.Count - 1; num >= 0; num--) { - this.Remove(this.GetAt(i)); + this.Remove(this.GetAt(num)); } } @@ -594,9 +584,9 @@ public void ClearAndDestroyContents(DestroyMode mode = DestroyMode.Vanish) { while (this.Any) { - for (int i = this.Count - 1; i >= 0; i--) + for (int num = this.Count - 1; num >= 0; num--) { - Thing at = this.GetAt(i); + Thing at = this.GetAt(num); at.Destroy(mode); this.Remove(at); } @@ -607,9 +597,9 @@ public void ClearAndDestroyContentsOrPassToWorld(DestroyMode mode = DestroyMode. { while (this.Any) { - for (int i = this.Count - 1; i >= 0; i--) + for (int num = this.Count - 1; num >= 0; num--) { - Thing at = this.GetAt(i); + Thing at = this.GetAt(num); at.DestroyOrPassToWorld(mode); this.Remove(at); } @@ -618,27 +608,27 @@ public void ClearAndDestroyContentsOrPassToWorld(DestroyMode mode = DestroyMode. public virtual bool CanAcceptAnyOf(Thing item, bool canMergeWithExistingStacks = true) { - if (item == null || item.stackCount <= 0) - { - return false; - } - int count = this.Count; - if (count >= this.maxStacks) + if (item != null && item.stackCount > 0) { - if (canMergeWithExistingStacks) + int count = this.Count; + if (count >= this.maxStacks) { - for (int i = 0; i < count; i++) + if (canMergeWithExistingStacks) { - Thing at = this.GetAt(i); - if (at.stackCount < at.def.stackLimit && at.CanStackWith(item)) + for (int num = 0; num < count; num++) { - return true; + Thing at = this.GetAt(num); + if (at.stackCount < at.def.stackLimit && at.CanStackWith(item)) + { + return true; + } } } + return false; } - return false; + return true; } - return true; + return false; } public abstract int TryAdd(Thing item, int count, bool canMergeWithExistingStacks = true); @@ -653,44 +643,48 @@ public virtual bool CanAcceptAnyOf(Thing item, bool canMergeWithExistingStacks = public bool Contains(Thing item) { - return item != null && item.holdingOwner == this; + if (item == null) + { + return false; + } + return item.holdingOwner == this; } public void RemoveAt(int index) { - if (index < 0 || index >= this.Count) + if (index >= 0 && index < this.Count) { - throw new ArgumentOutOfRangeException("index"); + this.Remove(this.GetAt(index)); + return; } - this.Remove(this.GetAt(index)); + throw new ArgumentOutOfRangeException("index"); } public void TryAddRange(IEnumerable things, bool canMergeWithExistingStacks = true) { - if (things == this) - { - return; - } - ThingOwner thingOwner = things as ThingOwner; - if (thingOwner != null) + if (things != this) { - thingOwner.TryTransferAllToContainer(this, canMergeWithExistingStacks); - } - else - { - IList list = things as IList; - if (list != null) + ThingOwner thingOwner = things as ThingOwner; + if (thingOwner != null) { - for (int i = 0; i < list.Count; i++) - { - this.TryAdd(list[i], canMergeWithExistingStacks); - } + thingOwner.TryTransferAllToContainer(this, canMergeWithExistingStacks); } else { - foreach (Thing current in things) + IList list = things as IList; + if (list != null) { - this.TryAdd(current, canMergeWithExistingStacks); + for (int i = 0; i < list.Count; i++) + { + this.TryAdd(list[i], canMergeWithExistingStacks); + } + } + else + { + foreach (Thing item in things) + { + this.TryAdd(item, canMergeWithExistingStacks); + } } } } @@ -699,11 +693,11 @@ public void TryAddRange(IEnumerable things, bool canMergeWithExistingStac public int RemoveAll(Predicate predicate) { int num = 0; - for (int i = this.Count - 1; i >= 0; i--) + for (int num2 = this.Count - 1; num2 >= 0; num2--) { - if (predicate(this.GetAt(i))) + if (predicate(this.GetAt(num2))) { - this.Remove(this.GetAt(i)); + this.Remove(this.GetAt(num2)); num++; } } @@ -717,7 +711,7 @@ public bool TryTransferToContainer(Thing item, ThingOwner otherContainer, bool c public bool TryTransferToContainer(Thing item, ThingOwner otherContainer, int count, bool canMergeWithExistingStacks = true) { - Thing thing; + Thing thing = default(Thing); return this.TryTransferToContainer(item, otherContainer, count, out thing, canMergeWithExistingStacks); } @@ -774,9 +768,9 @@ public bool TryTransferToContainer(Thing item, ThingOwner otherContainer, int co public void TryTransferAllToContainer(ThingOwner other, bool canMergeWithExistingStacks = true) { - for (int i = this.Count - 1; i >= 0; i--) + for (int num = this.Count - 1; num >= 0; num--) { - this.TryTransferToContainer(this.GetAt(i), other, canMergeWithExistingStacks); + this.TryTransferToContainer(this.GetAt(num), other, canMergeWithExistingStacks); } } @@ -784,20 +778,12 @@ public Thing Take(Thing thing, int count) { if (!this.Contains(thing)) { - Log.Error("Tried to take " + thing.ToStringSafe() + " but it's not here."); + Log.Error("Tried to take " + thing.ToStringSafe() + " but it's not here."); return null; } if (count > thing.stackCount) { - Log.Error(string.Concat(new object[] - { - "Tried to get ", - count, - " of ", - thing.ToStringSafe(), - " while only having ", - thing.stackCount - })); + Log.Error("Tried to get " + count + " of " + thing.ToStringSafe() + " while only having " + thing.stackCount); count = thing.stackCount; } if (count == thing.stackCount) @@ -819,34 +805,26 @@ public bool TryDrop(Thing thing, ThingPlaceMode mode, int count, out Thing lastR { Map rootMap = ThingOwnerUtility.GetRootMap(this.owner); IntVec3 rootPosition = ThingOwnerUtility.GetRootPosition(this.owner); - if (rootMap == null || !rootPosition.IsValid) + if (rootMap != null && rootPosition.IsValid) { - Log.Error("Cannot drop " + thing + " without a dropLoc and with an owner whose map is null."); - lastResultingThing = null; - return false; + return this.TryDrop(thing, rootPosition, rootMap, mode, count, out lastResultingThing, placedAction); } - return this.TryDrop(thing, rootPosition, rootMap, mode, count, out lastResultingThing, placedAction); + Log.Error("Cannot drop " + thing + " without a dropLoc and with an owner whose map is null."); + lastResultingThing = null; + return false; } public bool TryDrop(Thing thing, IntVec3 dropLoc, Map map, ThingPlaceMode mode, int count, out Thing resultingThing, Action placedAction = null) { if (!this.Contains(thing)) { - Log.Error("Tried to drop " + thing.ToStringSafe() + " but it's not here."); + Log.Error("Tried to drop " + thing.ToStringSafe() + " but it's not here."); resultingThing = null; return false; } if (thing.stackCount < count) { - Log.Error(string.Concat(new object[] - { - "Tried to drop ", - count, - " of ", - thing, - " while only having ", - thing.stackCount - })); + Log.Error("Tried to drop " + count + " of " + thing + " while only having " + thing.stackCount); count = thing.stackCount; } if (count == thing.stackCount) @@ -858,36 +836,33 @@ public bool TryDrop(Thing thing, IntVec3 dropLoc, Map map, ThingPlaceMode mode, } return false; } - else + Thing thing2 = thing.SplitOff(count); + if (GenDrop.TryDropSpawn(thing2, dropLoc, map, mode, out resultingThing, placedAction)) { - Thing thing2 = thing.SplitOff(count); - if (GenDrop.TryDropSpawn(thing2, dropLoc, map, mode, out resultingThing, placedAction)) - { - return true; - } - thing.TryAbsorbStack(thing2, false); - return false; + return true; } + thing.TryAbsorbStack(thing2, false); + return false; } public bool TryDrop(Thing thing, ThingPlaceMode mode, out Thing lastResultingThing, Action placedAction = null) { Map rootMap = ThingOwnerUtility.GetRootMap(this.owner); IntVec3 rootPosition = ThingOwnerUtility.GetRootPosition(this.owner); - if (rootMap == null || !rootPosition.IsValid) + if (rootMap != null && rootPosition.IsValid) { - Log.Error("Cannot drop " + thing + " without a dropLoc and with an owner whose map is null."); - lastResultingThing = null; - return false; + return this.TryDrop(thing, rootPosition, rootMap, mode, out lastResultingThing, placedAction); } - return this.TryDrop(thing, rootPosition, rootMap, mode, out lastResultingThing, placedAction); + Log.Error("Cannot drop " + thing + " without a dropLoc and with an owner whose map is null."); + lastResultingThing = null; + return false; } public bool TryDrop(Thing thing, IntVec3 dropLoc, Map map, ThingPlaceMode mode, out Thing lastResultingThing, Action placedAction = null) { if (!this.Contains(thing)) { - Log.Error(this.owner.ToStringSafe() + " container tried to drop " + thing.ToStringSafe() + " which it didn't contain."); + Log.Error(this.owner.ToStringSafe() + " container tried to drop " + thing.ToStringSafe() + " which it didn't contain."); lastResultingThing = null; return false; } @@ -902,10 +877,10 @@ public bool TryDrop(Thing thing, IntVec3 dropLoc, Map map, ThingPlaceMode mode, public bool TryDropAll(IntVec3 dropLoc, Map map, ThingPlaceMode mode) { bool result = true; - for (int i = this.Count - 1; i >= 0; i--) + for (int num = this.Count - 1; num >= 0; num--) { - Thing thing; - if (!this.TryDrop(this.GetAt(i), dropLoc, map, mode, out thing, null)) + Thing thing = default(Thing); + if (!this.TryDrop(this.GetAt(num), dropLoc, map, mode, out thing, (Action)null)) { result = false; } @@ -926,11 +901,11 @@ public bool Contains(ThingDef def, int minCount) } int num = 0; int count = this.Count; - for (int i = 0; i < count; i++) + for (int num2 = 0; num2 < count; num2++) { - if (this.GetAt(i).def == def) + if (this.GetAt(num2).def == def) { - num += this.GetAt(i).stackCount; + num += this.GetAt(num2).stackCount; } if (num >= minCount) { @@ -944,11 +919,11 @@ public int TotalStackCountOfDef(ThingDef def) { int num = 0; int count = this.Count; - for (int i = 0; i < count; i++) + for (int num2 = 0; num2 < count; num2++) { - if (this.GetAt(i).def == def) + if (this.GetAt(num2).def == def) { - num += this.GetAt(i).stackCount; + num += this.GetAt(num2).stackCount; } } return num; diff --git a/Assembly-CSharp/Verse/ThingOwnerUtility.cs b/Assembly-CSharp/Verse/ThingOwnerUtility.cs index 5337bf04c..0dbb9885d 100644 --- a/Assembly-CSharp/Verse/ThingOwnerUtility.cs +++ b/Assembly-CSharp/Verse/ThingOwnerUtility.cs @@ -1,6 +1,5 @@ using RimWorld; using RimWorld.Planet; -using System; using System.Collections.Generic; namespace Verse @@ -59,7 +58,7 @@ public static ThingOwner TryGetInnerInteractableThingOwner(this Thing thing) if (thingHolder != null) { thingHolder.GetChildHolders(ThingOwnerUtility.tmpHolders); - if (ThingOwnerUtility.tmpHolders.Any()) + if (ThingOwnerUtility.tmpHolders.Any()) { ThingOwner directlyHeldThings3 = ThingOwnerUtility.tmpHolders[0].GetDirectlyHeldThings(); if (directlyHeldThings3 != null) @@ -77,7 +76,7 @@ public static ThingOwner TryGetInnerInteractableThingOwner(this Thing thing) if (thingHolder3 != null) { thingHolder3.GetChildHolders(ThingOwnerUtility.tmpHolders); - if (ThingOwnerUtility.tmpHolders.Any()) + if (ThingOwnerUtility.tmpHolders.Any()) { ThingOwner directlyHeldThings4 = ThingOwnerUtility.tmpHolders[0].GetDirectlyHeldThings(); if (directlyHeldThings4 != null) @@ -184,33 +183,32 @@ public static bool ShouldRemoveDesignationsOnAddedThings(IThingHolder holder) public static void AppendThingHoldersFromThings(List outThingsHolders, ThingOwner container) { - if (container == null) + if (container != null) { - return; - } - int i = 0; - int count = container.Count; - while (i < count) - { - IThingHolder thingHolder = container[i] as IThingHolder; - if (thingHolder != null) - { - outThingsHolders.Add(thingHolder); - } - ThingWithComps thingWithComps = container[i] as ThingWithComps; - if (thingWithComps != null) + int num = 0; + int count = container.Count; + while (num < count) { - List allComps = thingWithComps.AllComps; - for (int j = 0; j < allComps.Count; j++) + IThingHolder thingHolder = container[num] as IThingHolder; + if (thingHolder != null) { - IThingHolder thingHolder2 = allComps[j] as IThingHolder; - if (thingHolder2 != null) + outThingsHolders.Add(thingHolder); + } + ThingWithComps thingWithComps = container[num] as ThingWithComps; + if (thingWithComps != null) + { + List allComps = thingWithComps.AllComps; + for (int i = 0; i < allComps.Count; i++) { - outThingsHolders.Add(thingHolder2); + IThingHolder thingHolder2 = allComps[i] as IThingHolder; + if (thingHolder2 != null) + { + outThingsHolders.Add(thingHolder2); + } } } + num++; } - i++; } } @@ -281,18 +279,18 @@ public static bool TryGetFixedTemperature(IThingHolder holder, out float tempera temperature = 14f; return true; } - if (holder is CompLaunchable || holder is ActiveDropPodInfo || holder is TravelingTransportPods) - { - temperature = 14f; - return true; - } - if (holder is Settlement_TraderTracker || holder is TradeShip) + if (!(holder is CompLaunchable) && !(holder is ActiveDropPodInfo) && !(holder is TravelingTransportPods)) { + if (!(holder is Settlement_TraderTracker) && !(holder is TradeShip)) + { + temperature = 21f; + return false; + } temperature = 14f; return true; } - temperature = 21f; - return false; + temperature = 14f; + return true; } } } diff --git a/Assembly-CSharp/Verse/ThingPlaceMode.cs b/Assembly-CSharp/Verse/ThingPlaceMode.cs index f56afb104..d10d5d028 100644 --- a/Assembly-CSharp/Verse/ThingPlaceMode.cs +++ b/Assembly-CSharp/Verse/ThingPlaceMode.cs @@ -1,10 +1,8 @@ -using System; - namespace Verse { public enum ThingPlaceMode : byte { - Direct, - Near + Direct = 0, + Near = 1 } } diff --git a/Assembly-CSharp/Verse/ThingRequest.cs b/Assembly-CSharp/Verse/ThingRequest.cs index bc669ae64..872348896 100644 --- a/Assembly-CSharp/Verse/ThingRequest.cs +++ b/Assembly-CSharp/Verse/ThingRequest.cs @@ -49,20 +49,16 @@ public bool Accepts(Thing t) { return t.def == this.singleDef; } - return this.group == ThingRequestGroup.Everything || this.group.Includes(t.def); + if (this.group != ThingRequestGroup.Everything) + { + return this.group.Includes(t.def); + } + return true; } public override string ToString() { - string str; - if (this.singleDef != null) - { - str = "singleDef " + this.singleDef.defName; - } - else - { - str = "group " + this.group.ToString(); - } + string str = (this.singleDef == null) ? ("group " + ((Enum)(object)this.group).ToString()) : ("singleDef " + this.singleDef.defName); return "ThingRequest(" + str + ")"; } } diff --git a/Assembly-CSharp/Verse/ThingRequestGroup.cs b/Assembly-CSharp/Verse/ThingRequestGroup.cs index 620b3ae8b..b97397964 100644 --- a/Assembly-CSharp/Verse/ThingRequestGroup.cs +++ b/Assembly-CSharp/Verse/ThingRequestGroup.cs @@ -1,39 +1,37 @@ -using System; - namespace Verse { public enum ThingRequestGroup : byte { - Undefined, - Nothing, - Everything, - HaulableEver, - HaulableAlways, - Plant, - FoodSource, - FoodSourceNotPlantOrTree, - Corpse, - Blueprint, - BuildingArtificial, - BuildingFrame, - Pawn, - PotentialBillGiver, - Medicine, - Filth, - AttackTarget, - Weapon, - Refuelable, - HaulableEverOrMinifiable, - Drug, - Construction, - HasGUIOverlay, - Apparel, - MinifiedThing, - Grave, - Art, - ThisOrAnyCompIsThingHolder, - ActiveDropPod, - Transporter, - LongRangeMineralScanner + Undefined = 0, + Nothing = 1, + Everything = 2, + HaulableEver = 3, + HaulableAlways = 4, + Plant = 5, + FoodSource = 6, + FoodSourceNotPlantOrTree = 7, + Corpse = 8, + Blueprint = 9, + BuildingArtificial = 10, + BuildingFrame = 11, + Pawn = 12, + PotentialBillGiver = 13, + Medicine = 14, + Filth = 15, + AttackTarget = 16, + Weapon = 17, + Refuelable = 18, + HaulableEverOrMinifiable = 19, + Drug = 20, + Construction = 21, + HasGUIOverlay = 22, + Apparel = 23, + MinifiedThing = 24, + Grave = 25, + Art = 26, + ThisOrAnyCompIsThingHolder = 27, + ActiveDropPod = 28, + Transporter = 29, + LongRangeMineralScanner = 30 } } diff --git a/Assembly-CSharp/Verse/ThingRequestGroupUtility.cs b/Assembly-CSharp/Verse/ThingRequestGroupUtility.cs index 6c518c504..2299a49fa 100644 --- a/Assembly-CSharp/Verse/ThingRequestGroupUtility.cs +++ b/Assembly-CSharp/Verse/ThingRequestGroupUtility.cs @@ -9,70 +9,134 @@ public static bool StoreInRegion(this ThingRequestGroup group) switch (group) { case ThingRequestGroup.Undefined: + { return false; + } case ThingRequestGroup.Nothing: + { return false; + } case ThingRequestGroup.Everything: + { return true; + } case ThingRequestGroup.HaulableEver: + { return true; + } case ThingRequestGroup.HaulableAlways: + { return true; - case ThingRequestGroup.Plant: - return false; + } case ThingRequestGroup.FoodSource: + { return true; + } case ThingRequestGroup.FoodSourceNotPlantOrTree: + { return true; + } case ThingRequestGroup.Corpse: + { return true; + } case ThingRequestGroup.Blueprint: + { return true; + } case ThingRequestGroup.BuildingArtificial: + { return true; + } case ThingRequestGroup.BuildingFrame: + { return true; + } case ThingRequestGroup.Pawn: + { return true; + } case ThingRequestGroup.PotentialBillGiver: + { return true; + } case ThingRequestGroup.Medicine: + { return true; + } case ThingRequestGroup.Filth: + { return true; + } case ThingRequestGroup.AttackTarget: + { return true; + } case ThingRequestGroup.Weapon: + { return true; + } case ThingRequestGroup.Refuelable: + { return true; + } case ThingRequestGroup.HaulableEverOrMinifiable: + { return true; + } case ThingRequestGroup.Drug: + { return true; + } + case ThingRequestGroup.Plant: + { + return false; + } case ThingRequestGroup.Construction: + { return false; + } case ThingRequestGroup.HasGUIOverlay: + { return false; + } case ThingRequestGroup.Apparel: + { return false; + } case ThingRequestGroup.MinifiedThing: + { return false; + } case ThingRequestGroup.Grave: + { return false; + } case ThingRequestGroup.Art: + { return false; + } case ThingRequestGroup.ThisOrAnyCompIsThingHolder: + { return false; + } case ThingRequestGroup.ActiveDropPod: + { return false; + } case ThingRequestGroup.Transporter: + { return false; + } case ThingRequestGroup.LongRangeMineralScanner: + { return false; + } default: + { throw new ArgumentException("group"); } + } } } } diff --git a/Assembly-CSharp/Verse/ThingStackPart.cs b/Assembly-CSharp/Verse/ThingStackPart.cs index 8a87418b5..8bd694ff7 100644 --- a/Assembly-CSharp/Verse/ThingStackPart.cs +++ b/Assembly-CSharp/Verse/ThingStackPart.cs @@ -28,26 +28,12 @@ public ThingStackPart(Thing thing, int count) { if (count < 0) { - Log.Warning(string.Concat(new object[] - { - "Tried to set ThingStackPart stack count to ", - count, - ". thing=", - thing - })); + Log.Warning("Tried to set ThingStackPart stack count to " + count + ". thing=" + thing); count = 0; } if (count > thing.stackCount) { - Log.Warning(string.Concat(new object[] - { - "Tried to set ThingStackPart stack count to ", - count, - ", but thing's stack count is only ", - thing.stackCount, - ". thing=", - thing - })); + Log.Warning("Tried to set ThingStackPart stack count to " + count + ", but thing's stack count is only " + thing.stackCount + ". thing=" + thing); count = thing.stackCount; } this.thing = thing; @@ -61,7 +47,11 @@ public ThingStackPart WithCount(int newCount) public override bool Equals(object obj) { - return obj is ThingStackPart && this.Equals((ThingStackPart)obj); + if (!(obj is ThingStackPart)) + { + return false; + } + return this.Equals((ThingStackPart)obj); } public bool Equals(ThingStackPart other) @@ -71,7 +61,7 @@ public bool Equals(ThingStackPart other) public override int GetHashCode() { - return Gen.HashCombine(this.count, this.thing); + return Gen.HashCombine(this.count, this.thing); } public static bool operator ==(ThingStackPart a, ThingStackPart b) diff --git a/Assembly-CSharp/Verse/ThingStackPartClass.cs b/Assembly-CSharp/Verse/ThingStackPartClass.cs index cc3af3026..5971661dc 100644 --- a/Assembly-CSharp/Verse/ThingStackPartClass.cs +++ b/Assembly-CSharp/Verse/ThingStackPartClass.cs @@ -1,5 +1,3 @@ -using System; - namespace Verse { public sealed class ThingStackPartClass : IExposable @@ -18,31 +16,18 @@ public int Count { if (value < 0) { - Log.Warning(string.Concat(new object[] - { - "Tried to set ThingStackPartClass stack count to ", - value, - ". thing=", - this.thing - })); + Log.Warning("Tried to set ThingStackPartClass stack count to " + value + ". thing=" + this.thing); this.countInt = 0; - return; } - if (value > this.thing.stackCount) + else if (value > this.thing.stackCount) { - Log.Warning(string.Concat(new object[] - { - "Tried to set ThingStackPartClass stack count to ", - value, - ", but thing's stack count is only ", - this.thing.stackCount, - ". thing=", - this.thing - })); + Log.Warning("Tried to set ThingStackPartClass stack count to " + value + ", but thing's stack count is only " + this.thing.stackCount + ". thing=" + this.thing); this.countInt = this.thing.stackCount; - return; } - this.countInt = value; + else + { + this.countInt = value; + } } } diff --git a/Assembly-CSharp/Verse/ThingUtility.cs b/Assembly-CSharp/Verse/ThingUtility.cs index b0934dd05..a5873da9b 100644 --- a/Assembly-CSharp/Verse/ThingUtility.cs +++ b/Assembly-CSharp/Verse/ThingUtility.cs @@ -1,5 +1,4 @@ using RimWorld.Planet; -using System; using UnityEngine; namespace Verse @@ -29,16 +28,7 @@ public static void DestroyOrPassToWorld(this Thing t, DestroyMode mode = Destroy public static int TryAbsorbStackNumToTake(Thing thing, Thing other, bool respectStackLimit) { - int result; - if (respectStackLimit) - { - result = Mathf.Min(other.stackCount, thing.def.stackLimit - thing.stackCount); - } - else - { - result = other.stackCount; - } - return result; + return (!respectStackLimit) ? other.stackCount : Mathf.Min(other.stackCount, thing.def.stackLimit - thing.stackCount); } } } diff --git a/Assembly-CSharp/Verse/ThingWithComps.cs b/Assembly-CSharp/Verse/ThingWithComps.cs index 110190e19..5558774d7 100644 --- a/Assembly-CSharp/Verse/ThingWithComps.cs +++ b/Assembly-CSharp/Verse/ThingWithComps.cs @@ -1,7 +1,6 @@ using RimWorld; using System; using System.Collections.Generic; -using System.Diagnostics; using System.Text; using UnityEngine; @@ -59,23 +58,25 @@ public T GetComp() where T : ThingComp { for (int i = 0; i < this.comps.Count; i++) { - T t = this.comps[i] as T; - if (t != null) + T val = (T)(this.comps[i] as T); + if (val != null) { - return t; + return val; } } - return (T)((object)null); + return (T)null; } - [DebuggerHidden] public IEnumerable GetComps() where T : ThingComp { - ThingWithComps.c__Iterator13E c__Iterator13E = new ThingWithComps.c__Iterator13E(); - c__Iterator13E.<>f__this = this; - ThingWithComps.c__Iterator13E expr_0E = c__Iterator13E; - expr_0E.$PC = -2; - return expr_0E; + for (int i = 0; i < this.comps.Count; i++) + { + T cT = (T)(this.comps[i] as T); + if (cT != null) + { + yield return cT; + } + } } public ThingComp GetCompByDef(CompProperties def) @@ -92,12 +93,12 @@ public ThingComp GetCompByDef(CompProperties def) public void InitializeComps() { - for (int i = 0; i < this.def.comps.Count; i++) + for (int i = 0; i < base.def.comps.Count; i++) { - ThingComp thingComp = (ThingComp)Activator.CreateInstance(this.def.comps[i].compClass); + ThingComp thingComp = (ThingComp)Activator.CreateInstance(base.def.comps[i].compClass); thingComp.parent = this; this.comps.Add(thingComp); - thingComp.Initialize(this.def.comps[i]); + thingComp.Initialize(base.def.comps[i]); } } @@ -175,16 +176,18 @@ public override void TickRare() public override void PreApplyDamage(DamageInfo dinfo, out bool absorbed) { base.PreApplyDamage(dinfo, out absorbed); - if (absorbed) + if (!absorbed) { - return; - } - for (int i = 0; i < this.comps.Count; i++) - { - this.comps[i].PostPreApplyDamage(dinfo, out absorbed); - if (absorbed) + int num = 0; + while (num < this.comps.Count) { - return; + this.comps[num].PostPreApplyDamage(dinfo, out absorbed); + if (!absorbed) + { + num++; + continue; + } + break; } } } @@ -238,14 +241,15 @@ public virtual void PrintForPowerGrid(SectionLayer layer) } } - [DebuggerHidden] public override IEnumerable GetGizmos() { - ThingWithComps.c__Iterator13F c__Iterator13F = new ThingWithComps.c__Iterator13F(); - c__Iterator13F.<>f__this = this; - ThingWithComps.c__Iterator13F expr_0E = c__Iterator13F; - expr_0E.$PC = -2; - return expr_0E; + for (int i = 0; i < this.comps.Count; i++) + { + foreach (Gizmo item in this.comps[i].CompGetGizmosExtra()) + { + yield return item; + } + } } public override bool TryAbsorbStack(Thing other, bool respectStackLimit) @@ -350,16 +354,19 @@ public override string GetDescription() return stringBuilder.ToString(); } - [DebuggerHidden] public override IEnumerable GetFloatMenuOptions(Pawn selPawn) { - ThingWithComps.c__Iterator140 c__Iterator = new ThingWithComps.c__Iterator140(); - c__Iterator.selPawn = selPawn; - c__Iterator.<$>selPawn = selPawn; - c__Iterator.<>f__this = this; - ThingWithComps.c__Iterator140 expr_1C = c__Iterator; - expr_1C.$PC = -2; - return expr_1C; + foreach (FloatMenuOption floatMenuOption in base.GetFloatMenuOptions(selPawn)) + { + yield return floatMenuOption; + } + for (int i = 0; i < this.comps.Count; i++) + { + foreach (FloatMenuOption item in this.comps[i].CompFloatMenuOptions(selPawn)) + { + yield return item; + } + } } public override void PreTraded(TradeAction action, Pawn playerNegotiator, ITrader trader) diff --git a/Assembly-CSharp/Verse/ThinkTreeDef.cs b/Assembly-CSharp/Verse/ThinkTreeDef.cs index 45b9a7600..5f4e4c7a1 100644 --- a/Assembly-CSharp/Verse/ThinkTreeDef.cs +++ b/Assembly-CSharp/Verse/ThinkTreeDef.cs @@ -1,6 +1,4 @@ -using System; using System.Collections.Generic; -using System.Diagnostics; using Verse.AI; namespace Verse @@ -17,22 +15,43 @@ public class ThinkTreeDef : Def public override void ResolveReferences() { this.thinkRoot.ResolveSubnodesAndRecur(); - foreach (ThinkNode current in this.thinkRoot.ThisAndChildrenRecursive) + foreach (ThinkNode item in this.thinkRoot.ThisAndChildrenRecursive) { - current.ResolveReferences(); + item.ResolveReferences(); } - ThinkTreeKeyAssigner.AssignKeys(this.thinkRoot, GenText.StableStringHash(this.defName)); + ThinkTreeKeyAssigner.AssignKeys(this.thinkRoot, GenText.StableStringHash(base.defName)); this.ResolveParentNodes(this.thinkRoot); } - [DebuggerHidden] public override IEnumerable ConfigErrors() { - ThinkTreeDef.c__Iterator1E8 c__Iterator1E = new ThinkTreeDef.c__Iterator1E8(); - c__Iterator1E.<>f__this = this; - ThinkTreeDef.c__Iterator1E8 expr_0E = c__Iterator1E; - expr_0E.$PC = -2; - return expr_0E; + foreach (string item in base.ConfigErrors()) + { + yield return item; + } + HashSet usedKeys = new HashSet(); + HashSet instances = new HashSet(); + foreach (ThinkNode item2 in this.thinkRoot.ThisAndChildrenRecursive) + { + int key = item2.UniqueSaveKey; + if (key == -1) + { + yield return "Thinknode " + item2.GetType() + " has invalid save key " + key; + } + else if (instances.Contains(item2)) + { + yield return "There are two same ThinkNode instances in one think tree (their type is " + item2.GetType() + ")"; + } + else if (usedKeys.Contains(key)) + { + yield return "Two ThinkNodes have the same unique save key " + key + " (one of the nodes is " + item2.GetType() + ")"; + } + if (key != -1) + { + usedKeys.Add(key); + } + instances.Add(item2); + } } public bool TryGetThinkNodeWithSaveKey(int key, out ThinkNode outNode) @@ -47,11 +66,11 @@ public bool TryGetThinkNodeWithSaveKey(int key, out ThinkNode outNode) outNode = this.thinkRoot; return true; } - foreach (ThinkNode current in this.thinkRoot.ChildrenRecursive) + foreach (ThinkNode item in this.thinkRoot.ChildrenRecursive) { - if (current.UniqueSaveKey == key) + if (item.UniqueSaveKey == key) { - outNode = current; + outNode = item; return true; } } @@ -64,16 +83,7 @@ private void ResolveParentNodes(ThinkNode node) { if (node.subNodes[i].parent != null) { - Log.Warning(string.Concat(new object[] - { - "Think node ", - node.subNodes[i], - " from think tree ", - this.defName, - " already has a parent node (", - node.subNodes[i].parent, - "). This means that it's referenced by more than one think tree (should have been copied instead)." - })); + Log.Warning("Think node " + node.subNodes[i] + " from think tree " + base.defName + " already has a parent node (" + node.subNodes[i].parent + "). This means that it's referenced by more than one think tree (should have been copied instead)."); } else { diff --git a/Assembly-CSharp/Verse/ThinkTreeKeyAssigner.cs b/Assembly-CSharp/Verse/ThinkTreeKeyAssigner.cs index 83321344b..2a0bcd168 100644 --- a/Assembly-CSharp/Verse/ThinkTreeKeyAssigner.cs +++ b/Assembly-CSharp/Verse/ThinkTreeKeyAssigner.cs @@ -1,4 +1,3 @@ -using System; using System.Collections.Generic; using Verse.AI; @@ -17,9 +16,9 @@ public static void AssignKeys(ThinkNode rootNode, int startHash) { Rand.PushState(); Rand.Seed = startHash; - foreach (ThinkNode current in rootNode.ThisAndChildrenRecursive) + foreach (ThinkNode item in rootNode.ThisAndChildrenRecursive) { - current.SetUniqueSaveKey(ThinkTreeKeyAssigner.NextUnusedKey()); + item.SetUniqueSaveKey(ThinkTreeKeyAssigner.NextUnusedKey()); } Rand.PopState(); } @@ -35,11 +34,12 @@ public static void AssignSingleKey(ThinkNode node, int startHash) private static int NextUnusedKey() { int num; - do + while (true) { num = Rand.Range(1, 2147483647); + if (!ThinkTreeKeyAssigner.assignedKeys.Contains(num)) + break; } - while (ThinkTreeKeyAssigner.assignedKeys.Contains(num)); ThinkTreeKeyAssigner.assignedKeys.Add(num); return num; } diff --git a/Assembly-CSharp/Verse/ThreadLocalDeepProfiler.cs b/Assembly-CSharp/Verse/ThreadLocalDeepProfiler.cs index bde1d802e..14cfdd864 100644 --- a/Assembly-CSharp/Verse/ThreadLocalDeepProfiler.cs +++ b/Assembly-CSharp/Verse/ThreadLocalDeepProfiler.cs @@ -1,4 +1,3 @@ -using System; using System.Collections.Generic; using System.Diagnostics; using System.Text; @@ -14,7 +13,7 @@ private class Watcher private Stopwatch watch; - private List children; + private List children; public string Label { @@ -32,7 +31,7 @@ public Stopwatch Watch } } - public List Children + public List Children { get { @@ -47,11 +46,11 @@ public Watcher(string label) this.children = null; } - public void AddChildResult(ThreadLocalDeepProfiler.Watcher w) + public void AddChildResult(Watcher w) { if (this.children == null) { - this.children = new List(); + this.children = new List(); } this.children.Add(w); } @@ -59,7 +58,7 @@ public void AddChildResult(ThreadLocalDeepProfiler.Watcher w) private const int MaxDepth = 50; - private Stack watchers = new Stack(); + private Stack watchers = new Stack(); private static readonly string[] Prefixes; @@ -69,48 +68,47 @@ static ThreadLocalDeepProfiler() for (int i = 0; i < 50; i++) { ThreadLocalDeepProfiler.Prefixes[i] = string.Empty; - for (int j = 0; j < i; j++) + for (int num = 0; num < i; num++) { - string[] expr_31_cp_0 = ThreadLocalDeepProfiler.Prefixes; - int expr_31_cp_1 = i; - expr_31_cp_0[expr_31_cp_1] += " -"; + ref string val = ref ThreadLocalDeepProfiler.Prefixes[i]; + val += " -"; } } } public void Start(string label = null) { - if (!Prefs.LogVerbose) + if (Prefs.LogVerbose) { - return; + this.watchers.Push(new Watcher(label)); } - this.watchers.Push(new ThreadLocalDeepProfiler.Watcher(label)); } public void End() { - if (!Prefs.LogVerbose) + if (Prefs.LogVerbose) { - return; - } - if (this.watchers.Count == 0) - { - Log.Error("Ended deep profiling while not profiling."); - return; - } - ThreadLocalDeepProfiler.Watcher watcher = this.watchers.Pop(); - watcher.Watch.Stop(); - if (this.watchers.Count > 0) - { - this.watchers.Peek().AddChildResult(watcher); - } - else - { - this.Output(watcher); + if (this.watchers.Count == 0) + { + Log.Error("Ended deep profiling while not profiling."); + } + else + { + Watcher watcher = this.watchers.Pop(); + watcher.Watch.Stop(); + if (this.watchers.Count > 0) + { + this.watchers.Peek().AddChildResult(watcher); + } + else + { + this.Output(watcher); + } + } } } - private void Output(ThreadLocalDeepProfiler.Watcher root) + private void Output(Watcher root) { StringBuilder stringBuilder = new StringBuilder(); if (UnityData.IsInMainThread) @@ -125,16 +123,9 @@ private void Output(ThreadLocalDeepProfiler.Watcher root) Log.Message(stringBuilder.ToString()); } - private void AppendStringRecursive(StringBuilder sb, ThreadLocalDeepProfiler.Watcher w, int depth) + private void AppendStringRecursive(StringBuilder sb, Watcher w, int depth) { - sb.AppendLine(string.Concat(new object[] - { - ThreadLocalDeepProfiler.Prefixes[depth], - " ", - w.Watch.ElapsedMilliseconds, - "ms ", - w.Label - })); + sb.AppendLine(ThreadLocalDeepProfiler.Prefixes[depth] + " " + w.Watch.ElapsedMilliseconds + "ms " + w.Label); if (w.Children != null) { for (int i = 0; i < w.Children.Count; i++) diff --git a/Assembly-CSharp/Verse/TickList.cs b/Assembly-CSharp/Verse/TickList.cs index bb17d072c..08a34bce3 100644 --- a/Assembly-CSharp/Verse/TickList.cs +++ b/Assembly-CSharp/Verse/TickList.cs @@ -20,14 +20,22 @@ private int TickInterval switch (this.tickType) { case TickerType.Normal: + { return 1; + } case TickerType.Rare: + { return 250; + } case TickerType.Long: + { return 2000; + } default: + { return -1; } + } } } @@ -107,15 +115,21 @@ public void Tick() switch (this.tickType) { case TickerType.Normal: + { list2[m].Tick(); break; + } case TickerType.Rare: + { list2[m].TickRare(); break; + } case TickerType.Long: + { list2[m].TickLong(); break; } + } } catch (Exception ex) { diff --git a/Assembly-CSharp/Verse/TickManager.cs b/Assembly-CSharp/Verse/TickManager.cs index 13b72c066..db8439ad2 100644 --- a/Assembly-CSharp/Verse/TickManager.cs +++ b/Assembly-CSharp/Verse/TickManager.cs @@ -72,35 +72,44 @@ public float TickRateMultiplier } return 1f; } - else + switch (this.curTimeSpeed) { - switch (this.curTimeSpeed) + case TimeSpeed.Paused: + { + return 0f; + } + case TimeSpeed.Normal: + { + return 1f; + } + case TimeSpeed.Fast: + { + return 3f; + } + case TimeSpeed.Superfast: + { + if (Find.VisibleMap == null) { - case TimeSpeed.Paused: - return 0f; - case TimeSpeed.Normal: - return 1f; - case TimeSpeed.Fast: - return 3f; - case TimeSpeed.Superfast: - if (Find.VisibleMap == null) - { - return 150f; - } - if (this.NothingHappeningInGame()) - { - return 12f; - } - return 6f; - case TimeSpeed.Ultrafast: - if (Find.VisibleMap == null) - { - return 250f; - } - return 15f; - default: - return -1f; + return 150f; + } + if (this.NothingHappeningInGame()) + { + return 12f; + } + return 6f; + } + case TimeSpeed.Ultrafast: + { + if (Find.VisibleMap == null) + { + return 250f; } + return 15f; + } + default: + { + return -1f; + } } } } @@ -109,11 +118,11 @@ private float CurTimePerTick { get { - if (this.TickRateMultiplier == 0f) + if (this.TickRateMultiplier == 0.0) { return 0f; } - return 1f / (60f * this.TickRateMultiplier); + return (float)(1.0 / (60.0 * this.TickRateMultiplier)); } } @@ -129,7 +138,11 @@ public bool NotPlaying { get { - return Find.MainTabsRoot.OpenTab == MainButtonDefOf.Menu; + if (Find.MainTabsRoot.OpenTab == MainButtonDefOf.Menu) + { + return true; + } + return false; } } @@ -147,7 +160,7 @@ public TimeSpeed CurTimeSpeed public void TogglePaused() { - if (this.curTimeSpeed != TimeSpeed.Paused) + if (this.curTimeSpeed != 0) { this.prePauseTimeSpeed = this.curTimeSpeed; this.curTimeSpeed = TimeSpeed.Paused; @@ -168,32 +181,38 @@ private bool NothingHappeningInGame() { this.nothingHappeningCached = true; List maps = Find.Maps; - for (int i = 0; i < maps.Count; i++) + int num = 0; + while (num < maps.Count) { - List list = maps[i].mapPawns.SpawnedPawnsInFaction(Faction.OfPlayer); - for (int j = 0; j < list.Count; j++) + List list = maps[num].mapPawns.SpawnedPawnsInFaction(Faction.OfPlayer); + for (int i = 0; i < list.Count; i++) { - Pawn pawn = list[j]; + Pawn pawn = list[i]; if (pawn.HostFaction == null && pawn.RaceProps.Humanlike && pawn.Awake()) { this.nothingHappeningCached = false; break; } } - if (!this.nothingHappeningCached) + if (this.nothingHappeningCached) { - break; + num++; + continue; } + break; } if (this.nothingHappeningCached) { - for (int k = 0; k < maps.Count; k++) + int num2 = 0; + while (num2 < maps.Count) { - if (maps[k].IsPlayerHome && maps[k].dangerWatcher.DangerRating >= StoryDanger.Low) + if (!maps[num2].IsPlayerHome || (int)maps[num2].dangerWatcher.DangerRating < 1) { - this.nothingHappeningCached = false; - break; + num2++; + continue; } + this.nothingHappeningCached = false; + break; } } this.lastNothingHappeningCheckTick = this.TicksGame; @@ -231,16 +250,26 @@ private TickList TickListFor(Thing t) switch (t.def.tickerType) { case TickerType.Never: + { return null; + } case TickerType.Normal: + { return this.tickListNormal; + } case TickerType.Rare: + { return this.tickListRare; + } case TickerType.Long: + { return this.tickListLong; + } default: + { throw new InvalidOperationException(); } + } } public void TickManagerUpdate() @@ -249,13 +278,13 @@ public void TickManagerUpdate() { this.realTimeToTickThrough += Time.deltaTime; int num = 0; - while (this.realTimeToTickThrough > 0f && (float)num < this.TickRateMultiplier * 2f) + while (this.realTimeToTickThrough > 0.0 && (float)num < this.TickRateMultiplier * 2.0) { this.DoSingleTick(); this.realTimeToTickThrough -= this.CurTimePerTick; num++; } - if (this.realTimeToTickThrough > 0f) + if (this.realTimeToTickThrough > 0.0) { this.realTimeToTickThrough = 0f; } @@ -379,9 +408,9 @@ public void DoSingleTick() public void RemoveAllFromMap(Map map) { - this.tickListNormal.RemoveWhere((Thing x) => x.Map == map); - this.tickListRare.RemoveWhere((Thing x) => x.Map == map); - this.tickListLong.RemoveWhere((Thing x) => x.Map == map); + this.tickListNormal.RemoveWhere((Predicate)((Thing x) => x.Map == map)); + this.tickListRare.RemoveWhere((Predicate)((Thing x) => x.Map == map)); + this.tickListLong.RemoveWhere((Predicate)((Thing x) => x.Map == map)); } public void DebugSetTicksGame(int newTicksGame) diff --git a/Assembly-CSharp/Verse/TickerType.cs b/Assembly-CSharp/Verse/TickerType.cs index c821ae8c3..d9a261aa3 100644 --- a/Assembly-CSharp/Verse/TickerType.cs +++ b/Assembly-CSharp/Verse/TickerType.cs @@ -1,12 +1,10 @@ -using System; - namespace Verse { public enum TickerType : byte { - Never, - Normal, - Rare, - Long + Never = 0, + Normal = 1, + Rare = 2, + Long = 3 } } diff --git a/Assembly-CSharp/Verse/TimeOfDay.cs b/Assembly-CSharp/Verse/TimeOfDay.cs index 4ff2815c2..e8c042a2f 100644 --- a/Assembly-CSharp/Verse/TimeOfDay.cs +++ b/Assembly-CSharp/Verse/TimeOfDay.cs @@ -1,11 +1,9 @@ -using System; - namespace Verse { public enum TimeOfDay : byte { - Night, - Day, - Any + Night = 0, + Day = 1, + Any = 2 } } diff --git a/Assembly-CSharp/Verse/TimeSlower.cs b/Assembly-CSharp/Verse/TimeSlower.cs index c4e101a4d..434c4d2da 100644 --- a/Assembly-CSharp/Verse/TimeSlower.cs +++ b/Assembly-CSharp/Verse/TimeSlower.cs @@ -1,5 +1,3 @@ -using System; - namespace Verse { public class TimeSlower diff --git a/Assembly-CSharp/Verse/TimeSpeed.cs b/Assembly-CSharp/Verse/TimeSpeed.cs index ddd20689a..f3dc99b72 100644 --- a/Assembly-CSharp/Verse/TimeSpeed.cs +++ b/Assembly-CSharp/Verse/TimeSpeed.cs @@ -1,13 +1,11 @@ -using System; - namespace Verse { public enum TimeSpeed : byte { - Paused, - Normal, - Fast, - Superfast, - Ultrafast + Paused = 0, + Normal = 1, + Fast = 2, + Superfast = 3, + Ultrafast = 4 } } diff --git a/Assembly-CSharp/Verse/TipSignal.cs b/Assembly-CSharp/Verse/TipSignal.cs index 7456ff817..5a2824af9 100644 --- a/Assembly-CSharp/Verse/TipSignal.cs +++ b/Assembly-CSharp/Verse/TipSignal.cs @@ -59,14 +59,7 @@ public TipSignal(TipSignal cloneSource) public override string ToString() { - return string.Concat(new object[] - { - "Tip(", - this.text, - ", ", - this.uniqueId, - ")" - }); + return "Tip(" + this.text + ", " + this.uniqueId + ")"; } public static implicit operator TipSignal(string str) diff --git a/Assembly-CSharp/Verse/TitleCaseHelper.cs b/Assembly-CSharp/Verse/TitleCaseHelper.cs index e31309c87..2ba6eca8c 100644 --- a/Assembly-CSharp/Verse/TitleCaseHelper.cs +++ b/Assembly-CSharp/Verse/TitleCaseHelper.cs @@ -1,4 +1,3 @@ -using System; using System.Collections.Generic; namespace Verse @@ -104,7 +103,11 @@ public static class TitleCaseHelper public static bool IsUppercaseTitleWord(string word) { - return word.Length > 1 && !TitleCaseHelper.NonUppercaseWords.Contains(word); + if (word.Length <= 1) + { + return false; + } + return !TitleCaseHelper.NonUppercaseWords.Contains(word); } } } diff --git a/Assembly-CSharp/Verse/ToStringNumberSense.cs b/Assembly-CSharp/Verse/ToStringNumberSense.cs index fbd87e68b..cf6b99b55 100644 --- a/Assembly-CSharp/Verse/ToStringNumberSense.cs +++ b/Assembly-CSharp/Verse/ToStringNumberSense.cs @@ -1,12 +1,10 @@ -using System; - namespace Verse { public enum ToStringNumberSense : byte { - Undefined, - Absolute, - Factor, - Offset + Undefined = 0, + Absolute = 1, + Factor = 2, + Offset = 3 } } diff --git a/Assembly-CSharp/Verse/ToStringStyle.cs b/Assembly-CSharp/Verse/ToStringStyle.cs index ce3243ccf..2d3692fce 100644 --- a/Assembly-CSharp/Verse/ToStringStyle.cs +++ b/Assembly-CSharp/Verse/ToStringStyle.cs @@ -1,17 +1,15 @@ -using System; - namespace Verse { public enum ToStringStyle : byte { - Integer, - FloatOne, - FloatTwo, - PercentZero, - PercentOne, - PercentTwo, - Temperature, - TemperatureOffset, - WorkAmount + Integer = 0, + FloatOne = 1, + FloatTwo = 2, + PercentZero = 3, + PercentOne = 4, + PercentTwo = 5, + Temperature = 6, + TemperatureOffset = 7, + WorkAmount = 8 } } diff --git a/Assembly-CSharp/Verse/TooltipGiverList.cs b/Assembly-CSharp/Verse/TooltipGiverList.cs index 7dd259949..b1374f416 100644 --- a/Assembly-CSharp/Verse/TooltipGiverList.cs +++ b/Assembly-CSharp/Verse/TooltipGiverList.cs @@ -1,5 +1,4 @@ using RimWorld; -using System; using System.Collections.Generic; using UnityEngine; using Verse.AI; @@ -12,57 +11,50 @@ public sealed class TooltipGiverList public void Notify_ThingSpawned(Thing t) { - if (t.def.hasTooltip || this.ShouldShowShotReport(t)) - { - this.givers.Add(t); - } + if (!t.def.hasTooltip && !this.ShouldShowShotReport(t)) + return; + this.givers.Add(t); } public void Notify_ThingDespawned(Thing t) { - if (t.def.hasTooltip || this.ShouldShowShotReport(t)) - { - this.givers.Remove(t); - } + if (!t.def.hasTooltip && !this.ShouldShowShotReport(t)) + return; + this.givers.Remove(t); } public void DispenseAllThingTooltips() { - if (Event.current.type != EventType.Repaint) - { - return; - } - if (Find.WindowStack.FloatMenu != null) - { - return; - } - CellRect currentViewRect = Find.CameraDriver.CurrentViewRect; - float cellSizePixels = Find.CameraDriver.CellSizePixels; - Vector2 vector = new Vector2(cellSizePixels, cellSizePixels); - Rect rect = new Rect(0f, 0f, vector.x, vector.y); - int num = 0; - for (int i = 0; i < this.givers.Count; i++) + if (Event.current.type == EventType.Repaint && Find.WindowStack.FloatMenu == null) { - Thing thing = this.givers[i]; - if (currentViewRect.Contains(thing.Position) && !thing.Position.Fogged(thing.Map)) + CellRect currentViewRect = Find.CameraDriver.CurrentViewRect; + float cellSizePixels = Find.CameraDriver.CellSizePixels; + Vector2 vector = new Vector2(cellSizePixels, cellSizePixels); + Rect rect = new Rect(0f, 0f, vector.x, vector.y); + int num = 0; + for (int i = 0; i < this.givers.Count; i++) { - Vector2 vector2 = thing.DrawPos.MapToUIPosition(); - rect.x = vector2.x - vector.x / 2f; - rect.y = vector2.y - vector.y / 2f; - if (rect.Contains(Event.current.mousePosition)) + Thing thing = this.givers[i]; + if (currentViewRect.Contains(thing.Position) && !thing.Position.Fogged(thing.Map)) { - string text = (!this.ShouldShowShotReport(thing)) ? null : TooltipUtility.ShotCalculationTipString(thing); - if (thing.def.hasTooltip || !text.NullOrEmpty()) + Vector2 vector2 = thing.DrawPos.MapToUIPosition(); + rect.x = (float)(vector2.x - vector.x / 2.0); + rect.y = (float)(vector2.y - vector.y / 2.0); + if (rect.Contains(Event.current.mousePosition)) { - TipSignal tooltip = thing.GetTooltip(); - if (!text.NullOrEmpty()) + string text = (!this.ShouldShowShotReport(thing)) ? null : TooltipUtility.ShotCalculationTipString(thing); + if (thing.def.hasTooltip || !text.NullOrEmpty()) { - tooltip.text = tooltip.text + "\n\n" + text; + TipSignal tooltip = thing.GetTooltip(); + if (!text.NullOrEmpty()) + { + tooltip.text = tooltip.text + "\n\n" + text; + } + TooltipHandler.TipRegion(rect, tooltip); } - TooltipHandler.TipRegion(rect, tooltip); } + num++; } - num++; } } } diff --git a/Assembly-CSharp/Verse/TooltipHandler.cs b/Assembly-CSharp/Verse/TooltipHandler.cs index c4c183014..d4e490065 100644 --- a/Assembly-CSharp/Verse/TooltipHandler.cs +++ b/Assembly-CSharp/Verse/TooltipHandler.cs @@ -18,20 +18,25 @@ public static class TooltipHandler public static void ClearTooltipsFrom(Rect rect) { - if (Event.current.type != EventType.Repaint) - { - return; - } - if (Mouse.IsOver(rect)) + if (Event.current.type == EventType.Repaint && Mouse.IsOver(rect)) { TooltipHandler.dyingTips.Clear(); - foreach (KeyValuePair current in TooltipHandler.activeTips) + Dictionary.Enumerator enumerator = TooltipHandler.activeTips.GetEnumerator(); + try { - if (current.Value.lastTriggerFrame == TooltipHandler.frame) + while (enumerator.MoveNext()) { - TooltipHandler.dyingTips.Add(current.Key); + KeyValuePair current = enumerator.Current; + if (current.Value.lastTriggerFrame == TooltipHandler.frame) + { + TooltipHandler.dyingTips.Add(current.Key); + } } } + finally + { + ((IDisposable)(object)enumerator).Dispose(); + } for (int i = 0; i < TooltipHandler.dyingTips.Count; i++) { TooltipHandler.activeTips.Remove(TooltipHandler.dyingTips[i]); @@ -46,27 +51,22 @@ public static void TipRegion(Rect rect, Func textGetter, int uniqueId) public static void TipRegion(Rect rect, TipSignal tip) { - if (Event.current.type != EventType.Repaint) - { - return; - } - if (!Mouse.IsOver(rect)) - { - return; - } - if (DebugViewSettings.drawTooltipEdges) + if (Event.current.type == EventType.Repaint && Mouse.IsOver(rect)) { - Widgets.DrawBox(rect, 1); - } - if (!TooltipHandler.activeTips.ContainsKey(tip.uniqueId)) - { - ActiveTip value = new ActiveTip(tip); - TooltipHandler.activeTips.Add(tip.uniqueId, value); - TooltipHandler.activeTips[tip.uniqueId].firstTriggerTime = (double)Time.realtimeSinceStartup; + if (DebugViewSettings.drawTooltipEdges) + { + Widgets.DrawBox(rect, 1); + } + if (!TooltipHandler.activeTips.ContainsKey(tip.uniqueId)) + { + ActiveTip value = new ActiveTip(tip); + TooltipHandler.activeTips.Add(tip.uniqueId, value); + TooltipHandler.activeTips[tip.uniqueId].firstTriggerTime = (double)Time.realtimeSinceStartup; + } + TooltipHandler.activeTips[tip.uniqueId].lastTriggerFrame = TooltipHandler.frame; + TooltipHandler.activeTips[tip.uniqueId].signal.text = tip.text; + TooltipHandler.activeTips[tip.uniqueId].signal.textGetter = tip.textGetter; } - TooltipHandler.activeTips[tip.uniqueId].lastTriggerFrame = TooltipHandler.frame; - TooltipHandler.activeTips[tip.uniqueId].signal.text = tip.text; - TooltipHandler.activeTips[tip.uniqueId].signal.textGetter = tip.textGetter; } public static void DoTooltipGUI() @@ -82,13 +82,22 @@ public static void DoTooltipGUI() private static void DrawActiveTips() { List list = new List(); - foreach (KeyValuePair current in TooltipHandler.activeTips) + Dictionary.Enumerator enumerator = TooltipHandler.activeTips.GetEnumerator(); + try { - if ((double)Time.realtimeSinceStartup > current.Value.firstTriggerTime + (double)TooltipHandler.TooltipDelay) + while (enumerator.MoveNext()) { - list.Add(current.Value); + KeyValuePair current = enumerator.Current; + if ((double)Time.realtimeSinceStartup > current.Value.firstTriggerTime + (double)TooltipHandler.TooltipDelay) + { + list.Add(current.Value); + } } } + finally + { + ((IDisposable)(object)enumerator).Dispose(); + } list.Sort(new Comparison(TooltipHandler.CompareTooltipsByPriority)); Vector2 pos = TooltipHandler.CalculateInitialTipPosition(list); for (int i = 0; i < list.Count; i++) @@ -101,13 +110,22 @@ private static void DrawActiveTips() private static void CleanActiveTooltips() { TooltipHandler.dyingTips.Clear(); - foreach (KeyValuePair current in TooltipHandler.activeTips) + Dictionary.Enumerator enumerator = TooltipHandler.activeTips.GetEnumerator(); + try { - if (current.Value.lastTriggerFrame != TooltipHandler.frame) + while (enumerator.MoveNext()) { - TooltipHandler.dyingTips.Add(current.Key); + KeyValuePair current = enumerator.Current; + if (current.Value.lastTriggerFrame != TooltipHandler.frame) + { + TooltipHandler.dyingTips.Add(current.Key); + } } } + finally + { + ((IDisposable)(object)enumerator).Dispose(); + } for (int i = 0; i < TooltipHandler.dyingTips.Count; i++) { TooltipHandler.activeTips.Remove(TooltipHandler.dyingTips[i]); @@ -125,33 +143,15 @@ private static Vector2 CalculateInitialTipPosition(List drawingTips) num2 = Mathf.Max(num2, tipRect.width); if (i != drawingTips.Count - 1) { - num += 2f; + num = (float)(num + 2.0); } } Vector3 vector = Event.current.mousePosition; - float y; - if (vector.y + 14f + num < (float)UI.screenHeight) - { - y = vector.y + 14f; - } - else if (vector.y - 5f - num >= 0f) - { - y = vector.y - 5f - num; - } - else - { - y = 0f; - } - float x; - if (vector.x + 16f + num2 < (float)UI.screenWidth) - { - x = vector.x + 16f; - } - else - { - x = vector.x - 4f - num2; - } - return new Vector2(x, y); + float num3 = 0f; + num3 = (float)((!(vector.y + 14.0 + num < (float)UI.screenHeight)) ? ((!(vector.y - 5.0 - num >= 0.0)) ? 0.0 : (vector.y - 5.0 - num)) : (vector.y + 14.0)); + float num4 = 0f; + num4 = (float)((!(vector.x + 16.0 + num2 < (float)UI.screenWidth)) ? (vector.x - 4.0 - num2) : (vector.x + 16.0)); + return new Vector2(num4, num3); } private static int CompareTooltipsByPriority(ActiveTip A, ActiveTip B) diff --git a/Assembly-CSharp/Verse/TooltipPriority.cs b/Assembly-CSharp/Verse/TooltipPriority.cs index 077e83259..2c9a05fdc 100644 --- a/Assembly-CSharp/Verse/TooltipPriority.cs +++ b/Assembly-CSharp/Verse/TooltipPriority.cs @@ -1,10 +1,8 @@ -using System; - namespace Verse { public enum TooltipPriority : byte { - Default, - Pawn + Default = 0, + Pawn = 1 } } diff --git a/Assembly-CSharp/Verse/TooltipUtility.cs b/Assembly-CSharp/Verse/TooltipUtility.cs index 4f4982344..f5968fded 100644 --- a/Assembly-CSharp/Verse/TooltipUtility.cs +++ b/Assembly-CSharp/Verse/TooltipUtility.cs @@ -1,5 +1,4 @@ using RimWorld; -using System; using System.Text; namespace Verse @@ -24,10 +23,7 @@ public static string ShotCalculationTipString(Thing target) } if (verb != null) { - stringBuilder.Append("ShotBy".Translate(new object[] - { - Find.Selector.SingleSelectedThing.LabelShort - }) + ": "); + stringBuilder.Append("ShotBy".Translate(Find.Selector.SingleSelectedThing.LabelShort) + ": "); if (verb.CanHitTarget(target)) { stringBuilder.Append(ShotReport.HitReportFor(verb.caster, verb, target).GetTextReadout()); diff --git a/Assembly-CSharp/Verse/Tradeability.cs b/Assembly-CSharp/Verse/Tradeability.cs index 294c5ca31..2d27a1716 100644 --- a/Assembly-CSharp/Verse/Tradeability.cs +++ b/Assembly-CSharp/Verse/Tradeability.cs @@ -1,11 +1,9 @@ -using System; - namespace Verse { public enum Tradeability : byte { - Never, - Sellable, - Stockable + Never = 0, + Sellable = 1, + Stockable = 2 } } diff --git a/Assembly-CSharp/Verse/TrainableIntelligenceDef.cs b/Assembly-CSharp/Verse/TrainableIntelligenceDef.cs index 6075350ad..fa39b8b8a 100644 --- a/Assembly-CSharp/Verse/TrainableIntelligenceDef.cs +++ b/Assembly-CSharp/Verse/TrainableIntelligenceDef.cs @@ -1,5 +1,3 @@ -using System; - namespace Verse { public class TrainableIntelligenceDef : Def diff --git a/Assembly-CSharp/Verse/TrainableIntelligenceExtension.cs b/Assembly-CSharp/Verse/TrainableIntelligenceExtension.cs index eee4fd10d..7860e88df 100644 --- a/Assembly-CSharp/Verse/TrainableIntelligenceExtension.cs +++ b/Assembly-CSharp/Verse/TrainableIntelligenceExtension.cs @@ -1,5 +1,3 @@ -using System; - namespace Verse { public static class TrainableIntelligenceExtension diff --git a/Assembly-CSharp/Verse/Translator.cs b/Assembly-CSharp/Verse/Translator.cs index 99725e91a..17be46615 100644 --- a/Assembly-CSharp/Verse/Translator.cs +++ b/Assembly-CSharp/Verse/Translator.cs @@ -43,7 +43,7 @@ public static string Translate(this string key) Log.Error("No active language! Cannot translate from key " + key + "."); return key; } - string text; + string text = default(string); if (LanguageDatabase.activeLanguage.TryGetTextFromKey(key, out text)) { return text; @@ -58,34 +58,35 @@ public static string Translate(this string key) public static string Translate(this string key, params object[] args) { - if (key == null || key == string.Empty) + if (key != null && !(key == string.Empty)) { - return key; - } - if (LanguageDatabase.activeLanguage == null) - { - Log.Error("No active language! Cannot translate from key " + key + "."); - return key; - } - string text; - if (!LanguageDatabase.activeLanguage.TryGetTextFromKey(key, out text)) - { - LanguageDatabase.defaultLanguage.TryGetTextFromKey(key, out text); - if (Prefs.DevMode) + if (LanguageDatabase.activeLanguage == null) { - text = Translator.PseudoTranslated(text); + Log.Error("No active language! Cannot translate from key " + key + "."); + return key; + } + string text = default(string); + if (!LanguageDatabase.activeLanguage.TryGetTextFromKey(key, out text)) + { + LanguageDatabase.defaultLanguage.TryGetTextFromKey(key, out text); + if (Prefs.DevMode) + { + text = Translator.PseudoTranslated(text); + } + } + string result = text; + try + { + result = string.Format(text, args); + return result; + } + catch (Exception ex) + { + Log.Error("Exception translating '" + text + "': " + ex.ToString()); + return result; } } - string result = text; - try - { - result = string.Format(text, args); - } - catch (Exception ex) - { - Log.Error("Exception translating '" + text + "': " + ex.ToString()); - } - return result; + return key; } public static bool TryGetTranslatedStringsForFile(string fileName, out List stringList) @@ -108,92 +109,146 @@ private static string PseudoTranslated(string original) for (int i = 0; i < original.Length; i++) { char c = original[i]; - string value; + string text = (string)null; switch (c) { case 'a': - value = "à"; + { + text = "à"; break; + } case 'b': - value = "þ"; + { + text = "þ"; break; + } case 'c': - value = "ç"; + { + text = "ç"; break; + } case 'd': - value = "ð"; + { + text = "ð"; break; + } case 'e': - value = "è"; + { + text = "è"; break; + } case 'f': - value = "Ƒ"; + { + text = "Ƒ"; break; + } case 'g': - value = "ğ"; + { + text = "ğ"; break; + } case 'h': - value = "ĥ"; + { + text = "ĥ"; break; + } case 'i': - value = "ì"; + { + text = "ì"; break; + } case 'j': - value = "ĵ"; + { + text = "ĵ"; break; + } case 'k': - value = "к"; + { + text = "к"; break; + } case 'l': - value = "ſ"; + { + text = "ſ"; break; + } case 'm': - value = "ṁ"; + { + text = "ṁ"; break; + } case 'n': - value = "ƞ"; + { + text = "ƞ"; break; + } case 'o': - value = "ò"; + { + text = "ò"; break; + } case 'p': - value = "ṗ"; + { + text = "ṗ"; break; + } case 'q': - value = "q"; + { + text = "q"; break; + } case 'r': - value = "ṟ"; + { + text = "ṟ"; break; + } case 's': - value = "ș"; + { + text = "ș"; break; + } case 't': - value = "ṭ"; + { + text = "ṭ"; break; + } case 'u': - value = "ù"; + { + text = "ù"; break; + } case 'v': - value = "ṽ"; + { + text = "ṽ"; break; + } case 'w': - value = "ẅ"; + { + text = "ẅ"; break; + } case 'x': - value = "ẋ"; + { + text = "ẋ"; break; + } case 'y': - value = "ý"; + { + text = "ý"; break; + } case 'z': - value = "ž"; + { + text = "ž"; break; + } default: - value = string.Empty + c; + { + text = string.Empty + c; break; } - stringBuilder.Append(value); + } + stringBuilder.Append(text); } return stringBuilder.ToString(); } diff --git a/Assembly-CSharp/Verse/Traversability.cs b/Assembly-CSharp/Verse/Traversability.cs index b7e01b3a5..cf8d4877b 100644 --- a/Assembly-CSharp/Verse/Traversability.cs +++ b/Assembly-CSharp/Verse/Traversability.cs @@ -1,11 +1,9 @@ -using System; - namespace Verse { public enum Traversability : byte { - Standable, - PassThroughOnly, - Impassable + Standable = 0, + PassThroughOnly = 1, + Impassable = 2 } } diff --git a/Assembly-CSharp/Verse/TraverseMode.cs b/Assembly-CSharp/Verse/TraverseMode.cs index 0c15c0b43..2218222fd 100644 --- a/Assembly-CSharp/Verse/TraverseMode.cs +++ b/Assembly-CSharp/Verse/TraverseMode.cs @@ -1,12 +1,10 @@ -using System; - namespace Verse { public enum TraverseMode : byte { - ByPawn, - PassDoors, - NoPassClosedDoors, - PassAllDestroyableThings + ByPawn = 0, + PassDoors = 1, + NoPassClosedDoors = 2, + PassAllDestroyableThings = 3 } } diff --git a/Assembly-CSharp/Verse/TraverseParms.cs b/Assembly-CSharp/Verse/TraverseParms.cs index e9e33fa84..ea7e0294a 100644 --- a/Assembly-CSharp/Verse/TraverseParms.cs +++ b/Assembly-CSharp/Verse/TraverseParms.cs @@ -49,7 +49,11 @@ public void Validate() public override bool Equals(object obj) { - return obj is TraverseParms && this.Equals((TraverseParms)obj); + if (!(obj is TraverseParms)) + { + return false; + } + return this.Equals((TraverseParms)obj); } public bool Equals(TraverseParms other) @@ -59,16 +63,9 @@ public bool Equals(TraverseParms other) public override int GetHashCode() { - int seed = (!this.canBash) ? 0 : 1; - if (this.pawn != null) - { - seed = Gen.HashCombine(seed, this.pawn); - } - else - { - seed = Gen.HashCombineStruct(seed, this.mode); - } - return Gen.HashCombineStruct(seed, this.maxDanger); + int seed = this.canBash ? 1 : 0; + seed = ((this.pawn == null) ? Gen.HashCombineStruct(seed, this.mode) : Gen.HashCombine(seed, this.pawn)); + return Gen.HashCombineStruct(seed, this.maxDanger); } public override string ToString() @@ -76,27 +73,9 @@ public override string ToString() string text = (!this.canBash) ? string.Empty : " canBash"; if (this.mode == TraverseMode.ByPawn) { - return string.Concat(new object[] - { - "(", - this.mode, - " ", - this.maxDanger, - " ", - this.pawn, - text, - ")" - }); + return "(" + this.mode + " " + this.maxDanger + " " + this.pawn + text + ")"; } - return string.Concat(new object[] - { - "(", - this.mode, - " ", - this.maxDanger, - text, - ")" - }); + return "(" + this.mode + " " + this.maxDanger + text + ")"; } public static implicit operator TraverseParms(TraverseMode m) diff --git a/Assembly-CSharp/Verse/TreeNode.cs b/Assembly-CSharp/Verse/TreeNode.cs index 12474dcad..4b20e2f79 100644 --- a/Assembly-CSharp/Verse/TreeNode.cs +++ b/Assembly-CSharp/Verse/TreeNode.cs @@ -1,4 +1,3 @@ -using System; using System.Collections.Generic; namespace Verse diff --git a/Assembly-CSharp/Verse/TreeNode_Editor.cs b/Assembly-CSharp/Verse/TreeNode_Editor.cs index 9c8ed0413..3fcc7275b 100644 --- a/Assembly-CSharp/Verse/TreeNode_Editor.cs +++ b/Assembly-CSharp/Verse/TreeNode_Editor.cs @@ -24,7 +24,7 @@ public object ParentObj { get { - return ((TreeNode_Editor)this.parentNode).obj; + return ((TreeNode_Editor)base.parentNode).obj; } } @@ -58,7 +58,7 @@ public object Value } if (this.IsListItem) { - return this.ListRootObject.GetType().GetProperty("Item").GetValue(this.ListRootObject, new object[] + return this.ListRootObject.GetType().GetProperty("Item").GetValue(this.ListRootObject, new object[1] { this.owningIndex }); @@ -73,7 +73,7 @@ public object Value } if (this.IsListItem) { - this.ListRootObject.GetType().GetProperty("Item").SetValue(this.ListRootObject, value, new object[] + this.ListRootObject.GetType().GetProperty("Item").SetValue(this.ListRootObject, value, new object[1] { this.owningIndex }); @@ -101,7 +101,19 @@ public override bool Openable { get { - return this.obj != null && this.nodeType != EditTreeNodeType.TerminalValue && (this.nodeType != EditTreeNodeType.ListRoot || (int)this.obj.GetType().GetProperty("Count").GetValue(this.obj, null) != 0); + if (this.obj == null) + { + return false; + } + if (this.nodeType == EditTreeNodeType.TerminalValue) + { + return false; + } + if (this.nodeType == EditTreeNodeType.ListRoot && (int)this.obj.GetType().GetProperty("Count").GetValue(this.obj, null) == 0) + { + return false; + } + return true; } } @@ -117,7 +129,15 @@ public bool HasNewButton { get { - return (this.nodeType == EditTreeNodeType.ComplexObject && this.obj == null) || (this.owningField != null && this.owningField.FieldType.HasAttribute()); + if (this.nodeType == EditTreeNodeType.ComplexObject && this.obj == null) + { + return true; + } + if (this.owningField != null && this.owningField.FieldType.HasAttribute()) + { + return true; + } + return false; } } @@ -125,7 +145,15 @@ public bool HasDeleteButton { get { - return this.IsListItem || (this.owningField != null && this.owningField.FieldType.HasAttribute()); + if (this.IsListItem) + { + return true; + } + if (this.owningField != null && this.owningField.FieldType.HasAttribute()) + { + return true; + } + return false; } } @@ -144,14 +172,7 @@ public string ExtraInfoText if (this.obj.GetType().IsGenericType && this.obj.GetType().GetGenericTypeDefinition() == typeof(List<>)) { int num = (int)this.obj.GetType().GetProperty("Count").GetValue(this.obj, null); - return string.Concat(new string[] - { - "(", - num.ToString(), - " ", - (num != 1) ? "elements" : "element", - ")" - }); + return "(" + num.ToString() + " " + ((num != 1) ? "elements" : "element") + ")"; } return string.Empty; } @@ -218,11 +239,10 @@ private static TreeNode_Editor NewChildNodeFromListItem(TreeNode_Editor parent, Type type2 = type.GetGenericArguments()[0]; if (!type2.IsValueEditable()) { - object value = type.GetProperty("Item").GetValue(obj, new object[] + object obj2 = treeNode_Editor.obj = type.GetProperty("Item").GetValue(obj, new object[1] { listIndex }); - treeNode_Editor.obj = value; treeNode_Editor.RebuildChildNodes(); } treeNode_Editor.InitiallyCacheData(); @@ -251,31 +271,30 @@ private void InitiallyCacheData() public void RebuildChildNodes() { - if (this.obj == null) - { - return; - } - this.children = new List(); - Type objType = this.obj.GetType(); - if (objType.IsGenericType && objType.GetGenericTypeDefinition() == typeof(List<>)) + if (this.obj != null) { - int num = (int)objType.GetProperty("Count").GetValue(this.obj, null); - for (int i = 0; i < num; i++) + base.children = new List(); + Type objType = this.obj.GetType(); + if (objType.IsGenericType && objType.GetGenericTypeDefinition() == typeof(List<>)) { - TreeNode_Editor item = TreeNode_Editor.NewChildNodeFromListItem(this, i); - this.children.Add(item); + int num = (int)objType.GetProperty("Count").GetValue(this.obj, null); + for (int num2 = 0; num2 < num; num2++) + { + TreeNode_Editor item = TreeNode_Editor.NewChildNodeFromListItem(this, num2); + base.children.Add(item); + } } - } - else - { - foreach (FieldInfo current in from f in this.obj.GetType().GetFields(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic) - orderby this.InheritanceDistanceBetween(objType, f.DeclaringType) descending - select f) + else { - if (current.GetCustomAttributes(typeof(UnsavedAttribute), true).Length <= 0 && current.GetCustomAttributes(typeof(EditorHiddenAttribute), true).Length <= 0) + foreach (FieldInfo item3 in from f in this.obj.GetType().GetFields(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic) + orderby this.InheritanceDistanceBetween(objType, f.DeclaringType) descending + select f) { - TreeNode_Editor item2 = TreeNode_Editor.NewChildNodeFromField(this, current); - this.children.Add(item2); + if (item3.GetCustomAttributes(typeof(UnsavedAttribute), true).Length <= 0 && item3.GetCustomAttributes(typeof(EditorHiddenAttribute), true).Length <= 0) + { + TreeNode_Editor item2 = TreeNode_Editor.NewChildNodeFromField(this, item3); + base.children.Add(item2); + } } } } @@ -285,24 +304,26 @@ private int InheritanceDistanceBetween(Type childType, Type parentType) { Type type = childType; int num = 0; - while (type != parentType) + while (true) { + if (type == parentType) + { + return num; + } type = type.BaseType; num++; if (type == null) - { - Log.Error(childType + " is not a subclass of " + parentType); - return -1; - } + break; } - return num; + Log.Error(childType + " is not a subclass of " + parentType); + return -1; } public void CheckLatentDelete() { if (this.indexToDelete >= 0) { - this.obj.GetType().GetMethod("RemoveAt").Invoke(this.obj, new object[] + this.obj.GetType().GetMethod("RemoveAt").Invoke(this.obj, new object[1] { this.indexToDelete }); @@ -316,40 +337,38 @@ public void Delete() if (this.owningField != null) { this.owningField.SetValue(this.obj, null); + return; } - else + if (this.IsListItem) { - if (!this.IsListItem) - { - throw new InvalidOperationException(); - } - ((TreeNode_Editor)this.parentNode).indexToDelete = this.owningIndex; + ((TreeNode_Editor)base.parentNode).indexToDelete = this.owningIndex; + return; } + throw new InvalidOperationException(); } public void DoSpecialPreElements(Listing_TreeDefs listing) { - if (this.obj == null) - { - return; - } - if (this.editWidgetsMethod != null) + if (this.obj != null) { - WidgetRow widgetRow = listing.StartWidgetsRow(this.nestDepth); - this.editWidgetsMethod.Invoke(this.obj, new object[] + if (this.editWidgetsMethod != null) { - widgetRow - }); - } - Editable editable = this.obj as Editable; - if (editable != null) - { - GUI.color = new Color(1f, 0.5f, 0.5f, 1f); - foreach (string current in editable.ConfigErrors()) + WidgetRow widgetRow = listing.StartWidgetsRow(base.nestDepth); + this.editWidgetsMethod.Invoke(this.obj, new object[1] + { + widgetRow + }); + } + Editable editable = this.obj as Editable; + if (editable != null) { - listing.InfoText(current, this.nestDepth); + GUI.color = new Color(1f, 0.5f, 0.5f, 1f); + foreach (string item in editable.ConfigErrors()) + { + listing.InfoText(item, base.nestDepth); + } + GUI.color = Color.white; } - GUI.color = Color.white; } } diff --git a/Assembly-CSharp/Verse/TreeNode_ThingCategory.cs b/Assembly-CSharp/Verse/TreeNode_ThingCategory.cs index dd5f5bf84..bdf69a675 100644 --- a/Assembly-CSharp/Verse/TreeNode_ThingCategory.cs +++ b/Assembly-CSharp/Verse/TreeNode_ThingCategory.cs @@ -27,11 +27,10 @@ public IEnumerable ChildCategoryNodesAndThis { get { - TreeNode_ThingCategory.<>c__Iterator235 <>c__Iterator = new TreeNode_ThingCategory.<>c__Iterator235(); - <>c__Iterator.<>f__this = this; - TreeNode_ThingCategory.<>c__Iterator235 expr_0E = <>c__Iterator; - expr_0E.$PC = -2; - return expr_0E; + foreach (ThingCategoryDef thisAndChildCategoryDef in this.catDef.ThisAndChildCategoryDefs) + { + yield return thisAndChildCategoryDef.treeNode; + } } } @@ -39,11 +38,19 @@ public IEnumerable ChildCategoryNodes { get { - TreeNode_ThingCategory.<>c__Iterator236 <>c__Iterator = new TreeNode_ThingCategory.<>c__Iterator236(); - <>c__Iterator.<>f__this = this; - TreeNode_ThingCategory.<>c__Iterator236 expr_0E = <>c__Iterator; - expr_0E.$PC = -2; - return expr_0E; + List.Enumerator enumerator = this.catDef.childCategories.GetEnumerator(); + try + { + while (enumerator.MoveNext()) + { + ThingCategoryDef other = enumerator.Current; + yield return other.treeNode; + } + } + finally + { + ((IDisposable)(object)enumerator).Dispose(); + } } } diff --git a/Assembly-CSharp/Verse/TreeOpenMasks.cs b/Assembly-CSharp/Verse/TreeOpenMasks.cs index fdbb9076a..038253b9a 100644 --- a/Assembly-CSharp/Verse/TreeOpenMasks.cs +++ b/Assembly-CSharp/Verse/TreeOpenMasks.cs @@ -1,5 +1,3 @@ -using System; - namespace Verse { public static class TreeOpenMasks diff --git a/Assembly-CSharp/Verse/Triangulator.cs b/Assembly-CSharp/Verse/Triangulator.cs index d903c4d26..f117a8c5f 100644 --- a/Assembly-CSharp/Verse/Triangulator.cs +++ b/Assembly-CSharp/Verse/Triangulator.cs @@ -1,4 +1,3 @@ -using System; using System.Collections.Generic; using UnityEngine; @@ -22,62 +21,62 @@ public int[] Triangulate() return list.ToArray(); } int[] array = new int[count]; - if (this.Area() > 0f) + if (this.Area() > 0.0) { - for (int i = 0; i < count; i++) + for (int num = 0; num < count; num++) { - array[i] = i; + array[num] = num; } } else { - for (int j = 0; j < count; j++) + for (int num2 = 0; num2 < count; num2++) { - array[j] = count - 1 - j; + array[num2] = count - 1 - num2; } } - int k = count; - int num = 2 * k; - int num2 = 0; - int num3 = k - 1; - while (k > 2) + int num3 = count; + int num4 = 2 * num3; + int num5 = 0; + int num6 = num3 - 1; + while (num3 > 2) { - if (num-- <= 0) + if (num4-- <= 0) { return list.ToArray(); } - int num4 = num3; - if (k <= num4) + int num8 = num6; + if (num3 <= num8) { - num4 = 0; + num8 = 0; } - num3 = num4 + 1; - if (k <= num3) + num6 = num8 + 1; + if (num3 <= num6) { - num3 = 0; + num6 = 0; } - int num5 = num3 + 1; - if (k <= num5) + int num9 = num6 + 1; + if (num3 <= num9) { - num5 = 0; + num9 = 0; } - if (this.Snip(num4, num3, num5, k, array)) + if (this.Snip(num8, num6, num9, num3, array)) { - int item = array[num4]; - int item2 = array[num3]; - int item3 = array[num5]; + int item = array[num8]; + int item2 = array[num6]; + int item3 = array[num9]; list.Add(item); list.Add(item2); list.Add(item3); - num2++; - int num6 = num3; - for (int l = num3 + 1; l < k; l++) + num5++; + int num10 = num6; + for (int num11 = num6 + 1; num11 < num3; num11++) { - array[num6] = array[l]; - num6++; + array[num10] = array[num11]; + num10++; } - k--; - num = 2 * k; + num3--; + num4 = 2 * num3; } } list.Reverse(); @@ -89,15 +88,15 @@ private float Area() int count = this.m_points.Count; float num = 0f; int index = count - 1; - int i = 0; - while (i < count) + int num2 = 0; + while (num2 < count) { Vector2 vector = this.m_points[index]; - Vector2 vector2 = this.m_points[i]; + Vector2 vector2 = this.m_points[num2]; num += vector.x * vector2.y - vector2.x * vector.y; - index = i++; + index = num2++; } - return num * 0.5f; + return (float)(num * 0.5); } private bool Snip(int u, int v, int w, int n, int[] V) @@ -109,11 +108,11 @@ private bool Snip(int u, int v, int w, int n, int[] V) { return false; } - for (int i = 0; i < n; i++) + for (int num = 0; num < n; num++) { - if (i != u && i != v && i != w) + if (num != u && num != v && num != w) { - Vector2 p = this.m_points[V[i]]; + Vector2 p = this.m_points[V[num]]; if (this.InsideTriangle(a, b, c, p)) { return false; @@ -140,7 +139,7 @@ private bool InsideTriangle(Vector2 A, Vector2 B, Vector2 C, Vector2 P) float num13 = num * num10 - num2 * num9; float num14 = num5 * num8 - num6 * num7; float num15 = num3 * num12 - num4 * num11; - return num13 >= 0f && num15 >= 0f && num14 >= 0f; + return num13 >= 0.0 && num15 >= 0.0 && num14 >= 0.0; } } } diff --git a/Assembly-CSharp/Verse/UI.cs b/Assembly-CSharp/Verse/UI.cs index bf327c74f..ee288b414 100644 --- a/Assembly-CSharp/Verse/UI.cs +++ b/Assembly-CSharp/Verse/UI.cs @@ -1,4 +1,3 @@ -using System; using UnityEngine; namespace Verse @@ -29,7 +28,7 @@ public static Vector2 MousePositionOnUIInverted public static void ApplyUIScale() { - if (Prefs.UIScale == 1f || LongEventHandler.AnyEventNowOrWaiting) + if (Prefs.UIScale == 1.0 || LongEventHandler.AnyEventNowOrWaiting) { UI.screenWidth = Screen.width; UI.screenHeight = Screen.height; @@ -52,7 +51,7 @@ public static void FocusControl(string controlName, Window window) public static void UnfocusCurrentControl() { - GUI.FocusControl(null); + GUI.FocusControl((string)null); } public static Vector2 GUIToScreenPoint(Vector2 guiPoint) @@ -79,7 +78,10 @@ public static Vector3 UIToMapPosition(float x, float y) public static Vector3 UIToMapPosition(Vector2 screenLoc) { Ray ray = Find.Camera.ScreenPointToRay(screenLoc * Prefs.UIScale); - return new Vector3(ray.origin.x, 0f, ray.origin.z); + Vector3 origin = ray.origin; + float x = origin.x; + Vector3 origin2 = ray.origin; + return new Vector3(x, 0f, origin2.z); } public static Vector3 MouseMapPosition() diff --git a/Assembly-CSharp/Verse/UIDirection.cs b/Assembly-CSharp/Verse/UIDirection.cs index 4a4e2de0f..2e4e38632 100644 --- a/Assembly-CSharp/Verse/UIDirection.cs +++ b/Assembly-CSharp/Verse/UIDirection.cs @@ -1,12 +1,10 @@ -using System; - namespace Verse { public enum UIDirection : byte { - LeftThenUp, - LeftThenDown, - RightThenUp, - RightThenDown + LeftThenUp = 0, + LeftThenDown = 1, + RightThenUp = 2, + RightThenDown = 3 } } diff --git a/Assembly-CSharp/Verse/UIHighlighter.cs b/Assembly-CSharp/Verse/UIHighlighter.cs index 8d4ff7e64..dc9ca7ecc 100644 --- a/Assembly-CSharp/Verse/UIHighlighter.cs +++ b/Assembly-CSharp/Verse/UIHighlighter.cs @@ -17,46 +17,38 @@ public static class UIHighlighter public static void HighlightTag(string tag) { - if (Event.current.type != EventType.Repaint) + if (Event.current.type == EventType.Repaint && !tag.NullOrEmpty()) { - return; - } - if (tag.NullOrEmpty()) - { - return; - } - for (int i = 0; i < UIHighlighter.liveTags.Count; i++) - { - if (UIHighlighter.liveTags[i].First == tag && UIHighlighter.liveTags[i].Second == Time.frameCount) + for (int i = 0; i < UIHighlighter.liveTags.Count; i++) { - return; + if (UIHighlighter.liveTags[i].First == tag && UIHighlighter.liveTags[i].Second == Time.frameCount) + return; } + UIHighlighter.liveTags.Add(new Pair(tag, Time.frameCount)); } - UIHighlighter.liveTags.Add(new Pair(tag, Time.frameCount)); } public static void HighlightOpportunity(Rect rect, string tag) { - if (Event.current.type != EventType.Repaint) - { - return; - } - for (int i = 0; i < UIHighlighter.liveTags.Count; i++) + if (Event.current.type == EventType.Repaint) { - Pair pair = UIHighlighter.liveTags[i]; - if (tag == pair.First && Time.frameCount == pair.Second + 1) + for (int i = 0; i < UIHighlighter.liveTags.Count; i++) { - Rect rect2 = rect.ContractedBy(-10f); - GUI.color = new Color(1f, 1f, 1f, Pulser.PulseBrightness(1.2f, 0.7f)); - Widgets.DrawAtlas(rect2, UIHighlighter.TutorHighlightAtlas); - GUI.color = Color.white; + Pair pair = UIHighlighter.liveTags[i]; + if (tag == pair.First && Time.frameCount == pair.Second + 1) + { + Rect rect2 = rect.ContractedBy(-10f); + GUI.color = new Color(1f, 1f, 1f, Pulser.PulseBrightness(1.2f, 0.7f)); + Widgets.DrawAtlas(rect2, UIHighlighter.TutorHighlightAtlas); + GUI.color = Color.white; + } } } } public static void UIHighlighterUpdate() { - UIHighlighter.liveTags.RemoveAll((Pair pair) => Time.frameCount > pair.Second + 1); + UIHighlighter.liveTags.RemoveAll((Predicate>)((Pair pair) => Time.frameCount > pair.Second + 1)); } } } diff --git a/Assembly-CSharp/Verse/UIMenuBackground.cs b/Assembly-CSharp/Verse/UIMenuBackground.cs index 87d4ce009..8fd5e1aff 100644 --- a/Assembly-CSharp/Verse/UIMenuBackground.cs +++ b/Assembly-CSharp/Verse/UIMenuBackground.cs @@ -1,5 +1,3 @@ -using System; - namespace Verse { public abstract class UIMenuBackground diff --git a/Assembly-CSharp/Verse/UIMenuBackgroundManager.cs b/Assembly-CSharp/Verse/UIMenuBackgroundManager.cs index 6683492e5..99191574b 100644 --- a/Assembly-CSharp/Verse/UIMenuBackgroundManager.cs +++ b/Assembly-CSharp/Verse/UIMenuBackgroundManager.cs @@ -1,5 +1,3 @@ -using System; - namespace Verse { public static class UIMenuBackgroundManager diff --git a/Assembly-CSharp/Verse/UIRoot.cs b/Assembly-CSharp/Verse/UIRoot.cs index b6893b78d..e2b500c1b 100644 --- a/Assembly-CSharp/Verse/UIRoot.cs +++ b/Assembly-CSharp/Verse/UIRoot.cs @@ -1,5 +1,4 @@ using RimWorld; -using System; using UnityEngine; using Verse.Noise; using Verse.Sound; diff --git a/Assembly-CSharp/Verse/UIRoot_Entry.cs b/Assembly-CSharp/Verse/UIRoot_Entry.cs index 8153eb085..194a712c9 100644 --- a/Assembly-CSharp/Verse/UIRoot_Entry.cs +++ b/Assembly-CSharp/Verse/UIRoot_Entry.cs @@ -14,7 +14,7 @@ private bool ShouldDoMainMenu { for (int i = 0; i < Find.WindowStack.Count; i++) { - if (this.windows[i].layer == WindowLayer.Dialog && !Find.WindowStack[i].IsDebug) + if (base.windows[i].layer == WindowLayer.Dialog && !Find.WindowStack[i].IsDebug) { return false; } @@ -33,10 +33,10 @@ public override void Init() if (!SteamManager.Initialized) { string text = "SteamClientMissing".Translate(); - Dialog_MessageBox window = new Dialog_MessageBox(text, "Quit".Translate(), delegate + Dialog_MessageBox window = new Dialog_MessageBox(text, "Quit".Translate(), (Action)delegate { Application.Quit(); - }, "Ignore".Translate(), null, null, false); + }, "Ignore".Translate(), null, (string)null, false); Find.WindowStack.Add(window); } } @@ -53,7 +53,7 @@ public override void UIRootOnGUI() { Find.Tutor.TutorOnGUI(); } - this.windows.WindowStackOnGUI(); + base.windows.WindowStackOnGUI(); ReorderableWidget.ReorderableWidgetOnGUI(); if (Find.World != null) { diff --git a/Assembly-CSharp/Verse/UnfinishedThing.cs b/Assembly-CSharp/Verse/UnfinishedThing.cs index 9f401114e..2590e3b14 100644 --- a/Assembly-CSharp/Verse/UnfinishedThing.cs +++ b/Assembly-CSharp/Verse/UnfinishedThing.cs @@ -1,8 +1,8 @@ using RimWorld; using System; using System.Collections.Generic; -using System.Diagnostics; using System.Linq; +using UnityEngine; namespace Verse { @@ -33,10 +33,12 @@ public Pawn Creator if (value == null) { Log.Error("Cannot set creator to null."); - return; } - this.creatorInt = value; - this.creatorName = value.NameStringShort; + else + { + this.creatorInt = value; + this.creatorName = value.NameStringShort; + } } } @@ -60,22 +62,21 @@ public Bill_ProductionWithUft BoundBill } set { - if (value == this.boundBillInt) - { - return; - } - Bill_ProductionWithUft bill_ProductionWithUft = this.boundBillInt; - this.boundBillInt = value; - if (bill_ProductionWithUft != null && bill_ProductionWithUft.BoundUft == this) - { - bill_ProductionWithUft.SetBoundUft(null, false); - } - if (value != null) + if (value != this.boundBillInt) { - this.recipeInt = value.recipe; - if (value.BoundUft != this) + Bill_ProductionWithUft bill_ProductionWithUft = this.boundBillInt; + this.boundBillInt = value; + if (bill_ProductionWithUft != null && bill_ProductionWithUft.BoundUft == this) + { + bill_ProductionWithUft.SetBoundUft(null, false); + } + if (value != null) { - value.SetBoundUft(this, false); + this.recipeInt = value.recipe; + if (value.BoundUft != this) + { + value.SetBoundUft(this, false); + } } } } @@ -109,16 +110,9 @@ public override string LabelNoCount } if (base.Stuff == null) { - return "UnfinishedItem".Translate(new object[] - { - this.Recipe.products[0].thingDef.label - }); + return "UnfinishedItem".Translate(this.Recipe.products[0].thingDef.label); } - return "UnfinishedItemWithStuff".Translate(new object[] - { - base.Stuff.LabelAsStuff, - this.Recipe.products[0].thingDef.label - }); + return "UnfinishedItemWithStuff".Translate(base.Stuff.LabelAsStuff, this.Recipe.products[0].thingDef.label); } } @@ -126,7 +120,7 @@ public bool Initialized { get { - return this.workLeft > -5000f; + return this.workLeft > -5000.0; } } @@ -138,7 +132,7 @@ public override void ExposeData() this.boundBillInt = null; } Scribe_References.Look(ref this.creatorInt, "creator", false); - Scribe_Values.Look(ref this.creatorName, "creatorName", null, false); + Scribe_Values.Look(ref this.creatorName, "creatorName", (string)null, false); Scribe_References.Look(ref this.boundBillInt, "bill", false); Scribe_Defs.Look(ref this.recipeInt, "recipe"); Scribe_Values.Look(ref this.workLeft, "workLeft", 0f, false); @@ -151,7 +145,7 @@ public override void Destroy(DestroyMode mode = DestroyMode.Vanish) { for (int i = 0; i < this.ingredients.Count; i++) { - int num = GenMath.RoundRandom((float)this.ingredients[i].stackCount * 0.75f); + int num = GenMath.RoundRandom((float)((float)this.ingredients[i].stackCount * 0.75)); if (num > 0) { this.ingredients[i].stackCount = num; @@ -164,14 +158,23 @@ public override void Destroy(DestroyMode mode = DestroyMode.Vanish) this.BoundBill = null; } - [DebuggerHidden] public override IEnumerable GetGizmos() { - UnfinishedThing.c__Iterator230 c__Iterator = new UnfinishedThing.c__Iterator230(); - c__Iterator.<>f__this = this; - UnfinishedThing.c__Iterator230 expr_0E = c__Iterator; - expr_0E.$PC = -2; - return expr_0E; + foreach (Gizmo gizmo in base.GetGizmos()) + { + yield return gizmo; + } + yield return (Gizmo)new Command_Action + { + defaultLabel = "CommandCancelConstructionLabel".Translate(), + defaultDesc = "CommandCancelConstructionDesc".Translate(), + icon = ContentFinder.Get("UI/Designators/Cancel", true), + hotKey = KeyBindingDefOf.DesignatorCancel, + action = (Action)delegate + { + ((_003CGetGizmos_003Ec__Iterator230)/*Error near IL_010b: stateMachine*/)._003C_003Ef__this.Destroy(DestroyMode.Cancel); + } + }; } public Bill_ProductionWithUft BillOnTableForMe(Thing workTable) @@ -182,15 +185,9 @@ public Bill_ProductionWithUft BillOnTableForMe(Thing workTable) for (int i = 0; i < billGiver.BillStack.Count; i++) { Bill_ProductionWithUft bill_ProductionWithUft = billGiver.BillStack[i] as Bill_ProductionWithUft; - if (bill_ProductionWithUft != null) + if (bill_ProductionWithUft != null && bill_ProductionWithUft.ShouldDoNow() && bill_ProductionWithUft != null && bill_ProductionWithUft.recipe == this.Recipe) { - if (bill_ProductionWithUft.ShouldDoNow()) - { - if (bill_ProductionWithUft != null && bill_ProductionWithUft.recipe == this.Recipe) - { - return bill_ProductionWithUft; - } - } + return bill_ProductionWithUft; } } } @@ -213,16 +210,9 @@ public override string GetInspectString() { text += "\n"; } - text = text + "Author".Translate() + ": " + this.creatorName; - string text2 = text; - return string.Concat(new string[] - { - text2, - "\n", - "WorkLeft".Translate(), - ": ", - this.workLeft.ToStringWorkAmount() - }); + string text2; + text = (text2 = text + "Author".Translate() + ": " + this.creatorName); + return text2 + "\n" + "WorkLeft".Translate() + ": " + this.workLeft.ToStringWorkAmount(); } } } diff --git a/Assembly-CSharp/Verse/UnityData.cs b/Assembly-CSharp/Verse/UnityData.cs index bbe210df9..cb581b425 100644 --- a/Assembly-CSharp/Verse/UnityData.cs +++ b/Assembly-CSharp/Verse/UnityData.cs @@ -1,4 +1,3 @@ -using System; using System.Threading; using UnityEngine; diff --git a/Assembly-CSharp/Verse/Vector2Utility.cs b/Assembly-CSharp/Verse/Vector2Utility.cs index 6930e7c84..ac91f57c8 100644 --- a/Assembly-CSharp/Verse/Vector2Utility.cs +++ b/Assembly-CSharp/Verse/Vector2Utility.cs @@ -1,4 +1,3 @@ -using System; using UnityEngine; namespace Verse diff --git a/Assembly-CSharp/Verse/Vector3Utility.cs b/Assembly-CSharp/Verse/Vector3Utility.cs index 99d434c6f..6298b9163 100644 --- a/Assembly-CSharp/Verse/Vector3Utility.cs +++ b/Assembly-CSharp/Verse/Vector3Utility.cs @@ -1,4 +1,3 @@ -using System; using UnityEngine; namespace Verse @@ -12,11 +11,12 @@ public static Vector3 HorizontalVectorFromAngle(float angle) public static float AngleFlat(this Vector3 v) { - if (v.x == 0f && v.z == 0f) + if (v.x == 0.0 && v.z == 0.0) { return 0f; } - return Quaternion.LookRotation(v).eulerAngles.y; + Vector3 eulerAngles = Quaternion.LookRotation(v).eulerAngles; + return eulerAngles.y; } public static Vector3 RandomHorizontalOffset(float maxDist) @@ -36,16 +36,26 @@ public static Vector3 RotatedBy(this Vector3 orig, Rot4 rot) switch (rot.AsInt) { case 0: + { return orig; + } case 1: - return new Vector3(orig.z, orig.y, -orig.x); + { + return new Vector3(orig.z, orig.y, (float)(0.0 - orig.x)); + } case 2: - return new Vector3(-orig.x, orig.y, -orig.z); + { + return new Vector3((float)(0.0 - orig.x), orig.y, (float)(0.0 - orig.z)); + } case 3: - return new Vector3(-orig.z, orig.y, orig.x); + { + return new Vector3((float)(0.0 - orig.z), orig.y, orig.x); + } default: + { return orig; } + } } } } diff --git a/Assembly-CSharp/Verse/Verb.cs b/Assembly-CSharp/Verse/Verb.cs index 8d50712f4..67d3f5d0e 100644 --- a/Assembly-CSharp/Verse/Verb.cs +++ b/Assembly-CSharp/Verse/Verb.cs @@ -21,7 +21,7 @@ public abstract class Verb : IExposable, ILoadReferenceable public VerbState state; - protected LocalTargetInfo currentTarget = null; + protected LocalTargetInfo currentTarget = (Thing)null; protected int burstShotsLeft; @@ -107,20 +107,27 @@ public bool IsStillUsableBy(Pawn pawn) { bool flag = false; List hediffs = pawn.health.hediffSet.hediffs; - for (int i = 0; i < hediffs.Count; i++) + int num = 0; + while (num < hediffs.Count) { - if (hediffs[i] == this.ownerHediffComp.parent) + if (hediffs[num] != this.ownerHediffComp.parent) { - flag = true; - break; + num++; + continue; } + flag = true; + break; } if (!flag) { return false; } } - return this.GetDamageFactorFor(pawn) != 0f; + if (this.GetDamageFactorFor(pawn) == 0.0) + { + return false; + } + return true; } public virtual void ExposeData() @@ -148,33 +155,33 @@ public bool TryStartCastOn(LocalTargetInfo castTarg, bool surpriseAttack = false { return false; } - if (this.state == VerbState.Bursting || !this.CanHitTarget(castTarg)) - { - return false; - } - if (this.verbProps.CausesTimeSlowdown && castTarg.HasThing && (castTarg.Thing.def.category == ThingCategory.Pawn || (castTarg.Thing.def.building != null && castTarg.Thing.def.building.IsTurret)) && castTarg.Thing.Faction == Faction.OfPlayer && this.caster.HostileTo(Faction.OfPlayer)) + if (this.state != VerbState.Bursting && this.CanHitTarget(castTarg)) { - Find.TickManager.slower.SignalForceNormalSpeed(); - } - this.surpriseAttack = surpriseAttack; - this.canFreeInterceptNow = canFreeIntercept; - this.currentTarget = castTarg; - if (this.CasterIsPawn && this.verbProps.warmupTime > 0f) - { - ShootLine newShootLine; - if (!this.TryFindShootLineFromTo(this.caster.Position, castTarg, out newShootLine)) + if (this.verbProps.CausesTimeSlowdown && castTarg.HasThing && (castTarg.Thing.def.category == ThingCategory.Pawn || (castTarg.Thing.def.building != null && castTarg.Thing.def.building.IsTurret)) && castTarg.Thing.Faction == Faction.OfPlayer && this.caster.HostileTo(Faction.OfPlayer)) + { + Find.TickManager.slower.SignalForceNormalSpeed(); + } + this.surpriseAttack = surpriseAttack; + this.canFreeInterceptNow = canFreeIntercept; + this.currentTarget = castTarg; + if (this.CasterIsPawn && this.verbProps.warmupTime > 0.0) { + ShootLine newShootLine = default(ShootLine); + if (this.TryFindShootLineFromTo(this.caster.Position, castTarg, out newShootLine)) + { + this.CasterPawn.Drawer.Notify_WarmingCastAlongLine(newShootLine, this.caster.Position); + float statValue = this.CasterPawn.GetStatValue(StatDefOf.AimingDelayFactor, true); + int ticks = (this.verbProps.warmupTime * statValue).SecondsToTicks(); + this.CasterPawn.stances.SetStance(new Stance_Warmup(ticks, castTarg, this)); + goto IL_01aa; + } return false; } - this.CasterPawn.Drawer.Notify_WarmingCastAlongLine(newShootLine, this.caster.Position); - float statValue = this.CasterPawn.GetStatValue(StatDefOf.AimingDelayFactor, true); - int ticks = (this.verbProps.warmupTime * statValue).SecondsToTicks(); - this.CasterPawn.stances.SetStance(new Stance_Warmup(ticks, castTarg, this)); - } - else - { this.WarmupComplete(); + goto IL_01aa; } + return false; + IL_01aa: return true; } @@ -209,7 +216,7 @@ protected void TryCastNextBurstShot() LocalTargetInfo target = this.currentTarget; if (this.TryCastShot()) { - if (this.verbProps.muzzleFlashScale > 0.01f) + if (this.verbProps.muzzleFlashScale > 0.0099999997764825821) { MoteMaker.MakeStaticMote(this.caster.Position, this.caster.Map, ThingDefOf.Mote_ShotFlash, this.verbProps.muzzleFlashScale); } @@ -232,9 +239,7 @@ protected void TryCastNextBurstShot() this.CasterPawn.mindState.Notify_AttackedTarget(target); } if (!this.CasterPawn.Spawned) - { return; - } } this.burstShotsLeft--; } @@ -257,7 +262,7 @@ protected void TryCastNextBurstShot() { this.CasterPawn.stances.SetStance(new Stance_Cooldown(this.verbProps.AdjustedCooldownTicks(this.ownerEquipment), this.currentTarget, this)); } - if (this.castCompleteCallback != null) + if ((object)this.castCompleteCallback != null) { this.castCompleteCallback(); } @@ -274,7 +279,7 @@ public void Notify_PickedUp() public virtual void Reset() { this.state = VerbState.Idle; - this.currentTarget = null; + this.currentTarget = (Thing)null; this.burstShotsLeft = 0; this.ticksToNextBurstShot = 0; this.castCompleteCallback = null; @@ -324,7 +329,7 @@ public virtual bool CanHitTargetFrom(IntVec3 root, LocalTargetInfo targ) } } } - ShootLine shootLine; + ShootLine shootLine = default(ShootLine); return this.TryFindShootLineFromTo(root, targ, out shootLine); } @@ -342,49 +347,48 @@ public bool TryFindShootLineFromTo(IntVec3 root, LocalTargetInfo targ, out Shoot } CellRect cellRect = (!targ.HasThing) ? CellRect.SingleCell(targ.Cell) : targ.Thing.OccupiedRect(); float num = cellRect.ClosestDistSquaredTo(root); - if (num > this.verbProps.range * this.verbProps.range || num < this.verbProps.minRange * this.verbProps.minRange) + if (!(num > this.verbProps.range * this.verbProps.range) && !(num < this.verbProps.minRange * this.verbProps.minRange)) { - resultingLine = new ShootLine(root, targ.Cell); - return false; - } - if (!this.verbProps.NeedsLineOfSight) - { - resultingLine = new ShootLine(root, targ.Cell); - return true; - } - if (this.CasterIsPawn) - { - IntVec3 dest; - if (this.CanHitFromCellIgnoringRange(root, targ, out dest)) + if (!this.verbProps.NeedsLineOfSight) { - resultingLine = new ShootLine(root, dest); + resultingLine = new ShootLine(root, targ.Cell); return true; } - ShootLeanUtility.LeanShootingSourcesFromTo(root, cellRect.ClosestCellTo(root), this.caster.Map, Verb.tempLeanShootSources); - for (int i = 0; i < Verb.tempLeanShootSources.Count; i++) + IntVec3 dest = default(IntVec3); + if (this.CasterIsPawn) { - IntVec3 intVec = Verb.tempLeanShootSources[i]; - if (this.CanHitFromCellIgnoringRange(intVec, targ, out dest)) + if (this.CanHitFromCellIgnoringRange(root, targ, out dest)) { - resultingLine = new ShootLine(intVec, dest); + resultingLine = new ShootLine(root, dest); return true; } + ShootLeanUtility.LeanShootingSourcesFromTo(root, cellRect.ClosestCellTo(root), this.caster.Map, Verb.tempLeanShootSources); + for (int i = 0; i < Verb.tempLeanShootSources.Count; i++) + { + IntVec3 intVec = Verb.tempLeanShootSources[i]; + if (this.CanHitFromCellIgnoringRange(intVec, targ, out dest)) + { + resultingLine = new ShootLine(intVec, dest); + return true; + } + } } - } - else - { - CellRect.CellRectIterator iterator = this.caster.OccupiedRect().GetIterator(); - while (!iterator.Done()) + else { - IntVec3 current = iterator.Current; - IntVec3 dest; - if (this.CanHitFromCellIgnoringRange(current, targ, out dest)) + CellRect.CellRectIterator iterator = this.caster.OccupiedRect().GetIterator(); + while (!iterator.Done()) { - resultingLine = new ShootLine(current, dest); - return true; + IntVec3 current = iterator.Current; + if (this.CanHitFromCellIgnoringRange(current, targ, out dest)) + { + resultingLine = new ShootLine(current, dest); + return true; + } + iterator.MoveNext(); } - iterator.MoveNext(); } + resultingLine = new ShootLine(root, targ.Cell); + return false; } resultingLine = new ShootLine(root, targ.Cell); return false; @@ -443,27 +447,7 @@ private bool CanHitCellFromCellIgnoringRange(IntVec3 sourceSq, IntVec3 targetLoc public override string ToString() { - string str; - if (!this.verbProps.label.NullOrEmpty()) - { - str = this.verbProps.label; - } - else if (this.ownerHediffComp != null) - { - str = this.ownerHediffComp.Def.label; - } - else if (this.ownerEquipment != null) - { - str = this.ownerEquipment.def.label; - } - else if (this.verbProps.linkedBodyPartsGroup != null) - { - str = this.verbProps.linkedBodyPartsGroup.defName; - } - else - { - str = "unknown"; - } + string str = this.verbProps.label.NullOrEmpty() ? ((this.ownerHediffComp == null) ? ((this.ownerEquipment == null) ? ((this.verbProps.linkedBodyPartsGroup == null) ? "unknown" : this.verbProps.linkedBodyPartsGroup.defName) : this.ownerEquipment.def.label) : this.ownerHediffComp.Def.label) : this.verbProps.label; return base.GetType().ToString() + "(" + str + ")"; } } diff --git a/Assembly-CSharp/Verse/VerbCategory.cs b/Assembly-CSharp/Verse/VerbCategory.cs index fb2aeb4a6..1b25922d1 100644 --- a/Assembly-CSharp/Verse/VerbCategory.cs +++ b/Assembly-CSharp/Verse/VerbCategory.cs @@ -1,12 +1,10 @@ -using System; - namespace Verse { public enum VerbCategory : byte { - Undefined, - BeatFire, - Ignite, - Nonnative + Undefined = 0, + BeatFire = 1, + Ignite = 2, + Nonnative = 3 } } diff --git a/Assembly-CSharp/Verse/VerbProperties.cs b/Assembly-CSharp/Verse/VerbProperties.cs index 5048ca5f8..4c7240935 100644 --- a/Assembly-CSharp/Verse/VerbProperties.cs +++ b/Assembly-CSharp/Verse/VerbProperties.cs @@ -8,10 +8,10 @@ public class VerbProperties { private enum RangeCategory : byte { - Touch, - Short, - Medium, - Long + Touch = 0, + Short = 1, + Medium = 2, + Long = 3 } private const float DistTouch = 4f; @@ -100,7 +100,7 @@ public bool MeleeRange { get { - return this.range < 1.1f; + return this.range < 1.1000000238418579; } } @@ -124,16 +124,7 @@ public string AccuracySummaryString { get { - return string.Concat(new string[] - { - this.accuracyTouch.ToStringPercent(), - " - ", - this.accuracyShort.ToStringPercent(), - " - ", - this.accuracyMedium.ToStringPercent(), - " - ", - this.accuracyLong.ToStringPercent() - }); + return this.accuracyTouch.ToStringPercent() + " - " + this.accuracyShort.ToStringPercent() + " - " + this.accuracyMedium.ToStringPercent() + " - " + this.accuracyLong.ToStringPercent(); } } @@ -147,15 +138,7 @@ public float BaseSelectionWeight public int AdjustedMeleeDamageAmount(Verb ownerVerb, Pawn attacker, Thing equipment) { - float num; - if (ownerVerb != null && ownerVerb.ownerEquipment != null) - { - num = ownerVerb.ownerEquipment.GetStatValue(StatDefOf.MeleeWeapon_DamageAmount, true); - } - else - { - num = (float)this.meleeDamageBaseAmount; - } + float num = (ownerVerb == null || ownerVerb.ownerEquipment == null) ? ((float)this.meleeDamageBaseAmount) : ownerVerb.ownerEquipment.GetStatValue(StatDefOf.MeleeWeapon_DamageAmount, true); if (attacker != null) { num *= ownerVerb.GetDamageFactorFor(attacker); @@ -170,82 +153,80 @@ public float AdjustedSelectionWeight(Verb ownerVerb, Pawn attacker, Thing equipm public int AdjustedCooldownTicks(Thing equipment) { - if (equipment == null) - { - return this.defaultCooldownTime.SecondsToTicks(); - } - if (this.MeleeRange) + if (equipment != null) { - return equipment.GetStatValue(StatDefOf.MeleeWeapon_Cooldown, true).SecondsToTicks(); + if (this.MeleeRange) + { + return equipment.GetStatValue(StatDefOf.MeleeWeapon_Cooldown, true).SecondsToTicks(); + } + return equipment.GetStatValue(StatDefOf.RangedWeapon_Cooldown, true).SecondsToTicks(); } - return equipment.GetStatValue(StatDefOf.RangedWeapon_Cooldown, true).SecondsToTicks(); + return this.defaultCooldownTime.SecondsToTicks(); } - private float AdjustedAccuracy(VerbProperties.RangeCategory cat, Thing equipment) + private float AdjustedAccuracy(RangeCategory cat, Thing equipment) { - if (equipment != null) + if (equipment == null) { - StatDef stat = null; switch (cat) { - case VerbProperties.RangeCategory.Touch: - stat = StatDefOf.AccuracyTouch; - break; - case VerbProperties.RangeCategory.Short: - stat = StatDefOf.AccuracyShort; - break; - case VerbProperties.RangeCategory.Medium: - stat = StatDefOf.AccuracyMedium; - break; - case VerbProperties.RangeCategory.Long: - stat = StatDefOf.AccuracyLong; - break; + case RangeCategory.Touch: + { + return this.accuracyTouch; + } + case RangeCategory.Short: + { + return this.accuracyShort; + } + case RangeCategory.Medium: + { + return this.accuracyMedium; + } + case RangeCategory.Long: + { + return this.accuracyLong; + } + default: + { + throw new InvalidOperationException(); + } } - return equipment.GetStatValue(stat, true); } + StatDef stat = null; switch (cat) { - case VerbProperties.RangeCategory.Touch: - return this.accuracyTouch; - case VerbProperties.RangeCategory.Short: - return this.accuracyShort; - case VerbProperties.RangeCategory.Medium: - return this.accuracyMedium; - case VerbProperties.RangeCategory.Long: - return this.accuracyLong; - default: - throw new InvalidOperationException(); - } - } - - public float GetHitChanceFactor(Thing equipment, float dist) - { - float num; - if (dist <= 4f) + case RangeCategory.Touch: { - num = this.AdjustedAccuracy(VerbProperties.RangeCategory.Touch, equipment); + stat = StatDefOf.AccuracyTouch; + break; } - else if (dist <= 15f) + case RangeCategory.Short: { - num = Mathf.Lerp(this.AdjustedAccuracy(VerbProperties.RangeCategory.Touch, equipment), this.AdjustedAccuracy(VerbProperties.RangeCategory.Short, equipment), (dist - 4f) / 11f); + stat = StatDefOf.AccuracyShort; + break; } - else if (dist <= 30f) + case RangeCategory.Medium: { - num = Mathf.Lerp(this.AdjustedAccuracy(VerbProperties.RangeCategory.Short, equipment), this.AdjustedAccuracy(VerbProperties.RangeCategory.Medium, equipment), (dist - 15f) / 15f); + stat = StatDefOf.AccuracyMedium; + break; } - else if (dist <= 50f) + case RangeCategory.Long: { - num = Mathf.Lerp(this.AdjustedAccuracy(VerbProperties.RangeCategory.Medium, equipment), this.AdjustedAccuracy(VerbProperties.RangeCategory.Long, equipment), (dist - 30f) / 20f); + stat = StatDefOf.AccuracyLong; + break; } - else - { - num = this.AdjustedAccuracy(VerbProperties.RangeCategory.Long, equipment); } - if (num < 0.01f) + return equipment.GetStatValue(stat, true); + } + + public float GetHitChanceFactor(Thing equipment, float dist) + { + float num = (!(dist <= 4.0)) ? ((!(dist <= 15.0)) ? ((!(dist <= 30.0)) ? ((!(dist <= 50.0)) ? this.AdjustedAccuracy(RangeCategory.Long, equipment) : Mathf.Lerp(this.AdjustedAccuracy(RangeCategory.Medium, equipment), this.AdjustedAccuracy(RangeCategory.Long, equipment), (float)((dist - 30.0) / 20.0))) : Mathf.Lerp(this.AdjustedAccuracy(RangeCategory.Short, equipment), this.AdjustedAccuracy(RangeCategory.Medium, equipment), (float)((dist - 15.0) / 15.0))) : Mathf.Lerp(this.AdjustedAccuracy(RangeCategory.Touch, equipment), this.AdjustedAccuracy(RangeCategory.Short, equipment), (float)((dist - 4.0) / 11.0))) : this.AdjustedAccuracy(RangeCategory.Touch, equipment); + if (num < 0.0099999997764825821) { num = 0.01f; } - if (num > 1f) + if (num > 1.0) { num = 1f; } @@ -254,21 +235,7 @@ public float GetHitChanceFactor(Thing equipment, float dist) public override string ToString() { - string str; - if (!this.label.NullOrEmpty()) - { - str = this.label; - } - else - { - str = string.Concat(new object[] - { - "range=", - this.range, - ", projectile=", - (this.projectileDef == null) ? "null" : this.projectileDef.defName - }); - } + string str = this.label.NullOrEmpty() ? ("range=" + this.range + ", projectile=" + ((this.projectileDef == null) ? "null" : this.projectileDef.defName)) : this.label; return "VerbProperties(" + str + ")"; } } diff --git a/Assembly-CSharp/Verse/VerbState.cs b/Assembly-CSharp/Verse/VerbState.cs index 124695303..798a444e2 100644 --- a/Assembly-CSharp/Verse/VerbState.cs +++ b/Assembly-CSharp/Verse/VerbState.cs @@ -1,10 +1,8 @@ -using System; - namespace Verse { public enum VerbState : byte { - Idle, - Bursting + Idle = 0, + Bursting = 1 } } diff --git a/Assembly-CSharp/Verse/VerbTracker.cs b/Assembly-CSharp/Verse/VerbTracker.cs index 7d79732d3..f55868f83 100644 --- a/Assembly-CSharp/Verse/VerbTracker.cs +++ b/Assembly-CSharp/Verse/VerbTracker.cs @@ -1,6 +1,6 @@ +using RimWorld; using System; using System.Collections.Generic; -using System.Diagnostics; using UnityEngine; namespace Verse @@ -49,24 +49,53 @@ public VerbTracker(IVerbOwner directOwner) public void VerbsTick() { - if (this.verbs == null) - { - return; - } - for (int i = 0; i < this.verbs.Count; i++) + if (this.verbs != null) { - this.verbs[i].VerbTick(); + for (int i = 0; i < this.verbs.Count; i++) + { + this.verbs[i].VerbTick(); + } } } - [DebuggerHidden] public IEnumerable GetVerbsCommands(KeyCode hotKey = KeyCode.None) { - VerbTracker.c__Iterator258 c__Iterator = new VerbTracker.c__Iterator258(); - c__Iterator.<>f__this = this; - VerbTracker.c__Iterator258 expr_0E = c__Iterator; - expr_0E.$PC = -2; - return expr_0E; + CompEquippable ce = this.directOwner as CompEquippable; + if (ce != null) + { + Thing ownerThing = ce.parent; + List verbs = this.AllVerbs; + for (int i = 0; i < verbs.Count; i++) + { + Verb verb = verbs[i]; + if (verb.verbProps.hasStandardCommand) + { + Command_VerbTarget newOpt = new Command_VerbTarget + { + defaultDesc = ownerThing.LabelCap + ": " + ownerThing.def.description, + icon = ownerThing.def.uiIcon, + tutorTag = "VerbTarget", + verb = verb + }; + if (verb.caster.Faction != Faction.OfPlayer) + { + newOpt.Disable("CannotOrderNonControlled".Translate()); + } + if (verb.CasterIsPawn) + { + if (verb.CasterPawn.story.WorkTagIsDisabled(WorkTags.Violent)) + { + newOpt.Disable("IsIncapableOfViolence".Translate(verb.CasterPawn.NameStringShort)); + } + else if (!verb.CasterPawn.drafter.Drafted) + { + newOpt.Disable("IsNotDrafted".Translate(verb.CasterPawn.NameStringShort)); + } + } + yield return (Command)newOpt; + } + } + } } public void ExposeData() @@ -95,13 +124,7 @@ private void InitVerbs() } catch (Exception ex) { - Log.Error(string.Concat(new object[] - { - "Could not instantiate Verb (directOwner=", - this.directOwner.ToStringSafe(), - "): ", - ex - })); + Log.Error("Could not instantiate Verb (directOwner=" + this.directOwner.ToStringSafe() + "): " + ex); } } this.UpdateVerbsLinksAndProps(); @@ -110,38 +133,37 @@ private void InitVerbs() private void UpdateVerbsLinksAndProps() { - if (this.verbs == null) + if (this.verbs != null) { - return; - } - List verbProperties = this.directOwner.VerbProperties; - if (this.verbs.Count != verbProperties.Count) - { - Log.Error("Verbs count is not equal to verb props count."); - while (this.verbs.Count > verbProperties.Count) - { - this.verbs.RemoveLast(); - } - } - for (int i = 0; i < this.verbs.Count; i++) - { - Verb verb = this.verbs[i]; - verb.verbProps = verbProperties[i]; - CompEquippable compEquippable = this.directOwner as CompEquippable; - Pawn pawn = this.directOwner as Pawn; - HediffComp_VerbGiver hediffComp_VerbGiver = this.directOwner as HediffComp_VerbGiver; - if (compEquippable != null) - { - verb.ownerEquipment = compEquippable.parent; - } - else if (pawn != null) + List verbProperties = this.directOwner.VerbProperties; + if (this.verbs.Count != verbProperties.Count) { - verb.caster = pawn; + Log.Error("Verbs count is not equal to verb props count."); + while (this.verbs.Count > verbProperties.Count) + { + this.verbs.RemoveLast(); + } } - else if (hediffComp_VerbGiver != null) + for (int i = 0; i < this.verbs.Count; i++) { - verb.ownerHediffComp = hediffComp_VerbGiver; - verb.caster = hediffComp_VerbGiver.Pawn; + Verb verb = this.verbs[i]; + verb.verbProps = verbProperties[i]; + CompEquippable compEquippable = this.directOwner as CompEquippable; + Pawn pawn = this.directOwner as Pawn; + HediffComp_VerbGiver hediffComp_VerbGiver = this.directOwner as HediffComp_VerbGiver; + if (compEquippable != null) + { + verb.ownerEquipment = compEquippable.parent; + } + else if (pawn != null) + { + verb.caster = pawn; + } + else if (hediffComp_VerbGiver != null) + { + verb.ownerHediffComp = hediffComp_VerbGiver; + verb.caster = hediffComp_VerbGiver.Pawn; + } } } } diff --git a/Assembly-CSharp/Verse/Verb_LaunchProjectile.cs b/Assembly-CSharp/Verse/Verb_LaunchProjectile.cs index 5eef43b54..f54e5ebdf 100644 --- a/Assembly-CSharp/Verse/Verb_LaunchProjectile.cs +++ b/Assembly-CSharp/Verse/Verb_LaunchProjectile.cs @@ -1,5 +1,4 @@ using RimWorld; -using System; using UnityEngine; namespace Verse @@ -8,121 +7,105 @@ public class Verb_LaunchProjectile : Verb { protected override bool TryCastShot() { - if (this.currentTarget.HasThing && this.currentTarget.Thing.Map != this.caster.Map) + if (base.currentTarget.HasThing && base.currentTarget.Thing.Map != base.caster.Map) { return false; } - ShootLine shootLine; - bool flag = base.TryFindShootLineFromTo(this.caster.Position, this.currentTarget, out shootLine); - if (this.verbProps.stopBurstWithoutLos && !flag) + ShootLine shootLine = default(ShootLine); + bool flag = base.TryFindShootLineFromTo(base.caster.Position, base.currentTarget, out shootLine); + if (base.verbProps.stopBurstWithoutLos && !flag) { return false; } - Vector3 drawPos = this.caster.DrawPos; - Projectile projectile = (Projectile)GenSpawn.Spawn(this.verbProps.projectileDef, shootLine.Source, this.caster.Map); - projectile.FreeIntercept = (this.canFreeInterceptNow && !projectile.def.projectile.flyOverhead); - if (this.verbProps.forcedMissRadius > 0.5f) + Vector3 drawPos = base.caster.DrawPos; + Projectile projectile = (Projectile)GenSpawn.Spawn(base.verbProps.projectileDef, shootLine.Source, base.caster.Map); + projectile.FreeIntercept = (base.canFreeInterceptNow && !projectile.def.projectile.flyOverhead); + if (base.verbProps.forcedMissRadius > 0.5) { - float num = (float)(this.currentTarget.Cell - this.caster.Position).LengthHorizontalSquared; - float num2; - if (num < 9f) + float num = (float)(base.currentTarget.Cell - base.caster.Position).LengthHorizontalSquared; + float num2 = (float)((!(num < 9.0)) ? ((!(num < 25.0)) ? ((!(num < 49.0)) ? (base.verbProps.forcedMissRadius * 1.0) : (base.verbProps.forcedMissRadius * 0.800000011920929)) : (base.verbProps.forcedMissRadius * 0.5)) : 0.0); + if (num2 > 0.5) { - num2 = 0f; - } - else if (num < 25f) - { - num2 = this.verbProps.forcedMissRadius * 0.5f; - } - else if (num < 49f) - { - num2 = this.verbProps.forcedMissRadius * 0.8f; - } - else - { - num2 = this.verbProps.forcedMissRadius * 1f; - } - if (num2 > 0.5f) - { - int max = GenRadial.NumCellsInRadius(this.verbProps.forcedMissRadius); + int max = GenRadial.NumCellsInRadius(base.verbProps.forcedMissRadius); int num3 = Rand.Range(0, max); if (num3 > 0) { if (DebugViewSettings.drawShooting) { - MoteMaker.ThrowText(this.caster.DrawPos, this.caster.Map, "ToForRad", -1f); + MoteMaker.ThrowText(base.caster.DrawPos, base.caster.Map, "ToForRad", -1f); } - IntVec3 c = this.currentTarget.Cell + GenRadial.RadialPattern[num3]; - if (this.currentTarget.HasThing) + IntVec3 c = base.currentTarget.Cell + GenRadial.RadialPattern[num3]; + if (base.currentTarget.HasThing) { - projectile.ThingToNeverIntercept = this.currentTarget.Thing; + projectile.ThingToNeverIntercept = base.currentTarget.Thing; } if (!projectile.def.projectile.flyOverhead) { projectile.InterceptWalls = true; } - projectile.Launch(this.caster, drawPos, c, this.ownerEquipment); + projectile.Launch(base.caster, drawPos, c, base.ownerEquipment); return true; } } } - ShotReport shotReport = ShotReport.HitReportFor(this.caster, this, this.currentTarget); + ShotReport shotReport = ShotReport.HitReportFor(base.caster, this, base.currentTarget); if (Rand.Value > shotReport.ChanceToNotGoWild_IgnoringPosture) { if (DebugViewSettings.drawShooting) { - MoteMaker.ThrowText(this.caster.DrawPos, this.caster.Map, "ToWild", -1f); + MoteMaker.ThrowText(base.caster.DrawPos, base.caster.Map, "ToWild", -1f); } shootLine.ChangeDestToMissWild(); - if (this.currentTarget.HasThing) + if (base.currentTarget.HasThing) { - projectile.ThingToNeverIntercept = this.currentTarget.Thing; + projectile.ThingToNeverIntercept = base.currentTarget.Thing; } if (!projectile.def.projectile.flyOverhead) { projectile.InterceptWalls = true; } - projectile.Launch(this.caster, drawPos, shootLine.Dest, this.ownerEquipment); + projectile.Launch(base.caster, drawPos, shootLine.Dest, base.ownerEquipment); return true; } if (Rand.Value > shotReport.ChanceToNotHitCover) { if (DebugViewSettings.drawShooting) { - MoteMaker.ThrowText(this.caster.DrawPos, this.caster.Map, "ToCover", -1f); + MoteMaker.ThrowText(base.caster.DrawPos, base.caster.Map, "ToCover", -1f); } - if (this.currentTarget.Thing != null && this.currentTarget.Thing.def.category == ThingCategory.Pawn) + if (base.currentTarget.Thing != null && base.currentTarget.Thing.def.category == ThingCategory.Pawn) { Thing randomCoverToMissInto = shotReport.GetRandomCoverToMissInto(); if (!projectile.def.projectile.flyOverhead) { projectile.InterceptWalls = true; } - projectile.Launch(this.caster, drawPos, randomCoverToMissInto, this.ownerEquipment); + projectile.Launch(base.caster, drawPos, randomCoverToMissInto, base.ownerEquipment); return true; } } if (DebugViewSettings.drawShooting) { - MoteMaker.ThrowText(this.caster.DrawPos, this.caster.Map, "ToHit", -1f); + MoteMaker.ThrowText(base.caster.DrawPos, base.caster.Map, "ToHit", -1f); } if (!projectile.def.projectile.flyOverhead) { - projectile.InterceptWalls = (!this.currentTarget.HasThing || this.currentTarget.Thing.def.Fillage == FillCategory.Full); + projectile.InterceptWalls = (!base.currentTarget.HasThing || base.currentTarget.Thing.def.Fillage == FillCategory.Full); } - if (this.currentTarget.Thing != null) + if (base.currentTarget.Thing != null) { - projectile.Launch(this.caster, drawPos, this.currentTarget, this.ownerEquipment); + projectile.Launch(base.caster, drawPos, base.currentTarget, base.ownerEquipment); } else { - projectile.Launch(this.caster, drawPos, shootLine.Dest, this.ownerEquipment); + projectile.Launch(base.caster, drawPos, shootLine.Dest, base.ownerEquipment); } return true; } public override float HighlightFieldRadiusAroundTarget() { - return this.verbProps.projectileDef.projectile.explosionRadius; + return base.verbProps.projectileDef.projectile.explosionRadius; } } } diff --git a/Assembly-CSharp/Verse/Verb_Shoot.cs b/Assembly-CSharp/Verse/Verb_Shoot.cs index 2d2bc8d23..4dece3d81 100644 --- a/Assembly-CSharp/Verse/Verb_Shoot.cs +++ b/Assembly-CSharp/Verse/Verb_Shoot.cs @@ -1,5 +1,4 @@ using RimWorld; -using System; namespace Verse { @@ -9,7 +8,7 @@ protected override int ShotsPerBurst { get { - return this.verbProps.burstShotCount; + return base.verbProps.burstShotCount; } } @@ -19,8 +18,8 @@ public override void WarmupComplete() if (base.CasterIsPawn && base.CasterPawn.skills != null) { float xp = 6f; - Pawn pawn = this.currentTarget.Thing as Pawn; - if (pawn != null && pawn.HostileTo(this.caster) && !pawn.Downed) + Pawn pawn = base.currentTarget.Thing as Pawn; + if (pawn != null && pawn.HostileTo(base.caster) && !pawn.Downed) { xp = 240f; } diff --git a/Assembly-CSharp/Verse/WeatherDef.cs b/Assembly-CSharp/Verse/WeatherDef.cs index c7020b9a2..a346049fd 100644 --- a/Assembly-CSharp/Verse/WeatherDef.cs +++ b/Assembly-CSharp/Verse/WeatherDef.cs @@ -1,6 +1,5 @@ using System; using System.Collections.Generic; -using System.Diagnostics; namespace Verse { @@ -61,14 +60,11 @@ public override void PostLoad() this.workerInt = new WeatherWorker(this); } - [DebuggerHidden] public override IEnumerable ConfigErrors() { - WeatherDef.c__Iterator1E9 c__Iterator1E = new WeatherDef.c__Iterator1E9(); - c__Iterator1E.<>f__this = this; - WeatherDef.c__Iterator1E9 expr_0E = c__Iterator1E; - expr_0E.$PC = -2; - return expr_0E; + if (this.skyColorsDay.saturation != 0.0 && this.skyColorsDusk.saturation != 0.0 && this.skyColorsNightMid.saturation != 0.0 && this.skyColorsNightEdge.saturation != 0.0) + yield break; + yield return "a sky color has saturation of 0"; } public static WeatherDef Named(string defName) diff --git a/Assembly-CSharp/Verse/WeatherEvent.cs b/Assembly-CSharp/Verse/WeatherEvent.cs index 84037ab4c..7eb852e80 100644 --- a/Assembly-CSharp/Verse/WeatherEvent.cs +++ b/Assembly-CSharp/Verse/WeatherEvent.cs @@ -16,7 +16,7 @@ public bool CurrentlyOverridesSky { get { - return this.SkyTargetLerpFactor >= 0f; + return this.SkyTargetLerpFactor >= 0.0; } } @@ -40,7 +40,7 @@ public virtual Vector2? OverrideShadowVector { get { - return null; + return default(Vector2?); } } diff --git a/Assembly-CSharp/Verse/WeatherEventHandler.cs b/Assembly-CSharp/Verse/WeatherEventHandler.cs index 9f07bd24b..b9add3797 100644 --- a/Assembly-CSharp/Verse/WeatherEventHandler.cs +++ b/Assembly-CSharp/Verse/WeatherEventHandler.cs @@ -1,4 +1,3 @@ -using System; using System.Collections.Generic; namespace Verse @@ -30,12 +29,12 @@ public void AddEvent(WeatherEvent newEvent) public void WeatherEventHandlerTick() { - for (int i = this.liveEvents.Count - 1; i >= 0; i--) + for (int num = this.liveEvents.Count - 1; num >= 0; num--) { - this.liveEvents[i].WeatherEventTick(); - if (this.liveEvents[i].Expired) + this.liveEvents[num].WeatherEventTick(); + if (this.liveEvents[num].Expired) { - this.liveEvents.RemoveAt(i); + this.liveEvents.RemoveAt(num); } } } diff --git a/Assembly-CSharp/Verse/WeatherEventMaker.cs b/Assembly-CSharp/Verse/WeatherEventMaker.cs index f74588876..e2e371ceb 100644 --- a/Assembly-CSharp/Verse/WeatherEventMaker.cs +++ b/Assembly-CSharp/Verse/WeatherEventMaker.cs @@ -10,12 +10,9 @@ public class WeatherEventMaker public void WeatherEventMakerTick(Map map, float strength) { - if (Rand.Value < 1f / this.averageInterval * strength) + if (Rand.Value < 1.0 / this.averageInterval * strength) { - WeatherEvent newEvent = (WeatherEvent)Activator.CreateInstance(this.eventClass, new object[] - { - map - }); + WeatherEvent newEvent = (WeatherEvent)Activator.CreateInstance(this.eventClass, map); map.weatherManager.eventHandler.AddEvent(newEvent); } } diff --git a/Assembly-CSharp/Verse/WeatherWorker.cs b/Assembly-CSharp/Verse/WeatherWorker.cs index a34eb9f92..3a29ac367 100644 --- a/Assembly-CSharp/Verse/WeatherWorker.cs +++ b/Assembly-CSharp/Verse/WeatherWorker.cs @@ -23,20 +23,29 @@ public SkyThreshold(SkyColorSet colors, float celGlowThreshold) public List overlays = new List(); - private WeatherWorker.SkyThreshold[] skyTargets = new WeatherWorker.SkyThreshold[4]; + private SkyThreshold[] skyTargets = new SkyThreshold[4]; public WeatherWorker(WeatherDef def) { this.def = def; - foreach (Type current in def.overlayClasses) + List.Enumerator enumerator = def.overlayClasses.GetEnumerator(); + try { - SkyOverlay item = (SkyOverlay)GenGeneric.InvokeStaticGenericMethod(typeof(WeatherPartPool), current, "GetInstanceOf"); - this.overlays.Add(item); + while (enumerator.MoveNext()) + { + Type current = enumerator.Current; + SkyOverlay item = (SkyOverlay)GenGeneric.InvokeStaticGenericMethod(typeof(WeatherPartPool), current, "GetInstanceOf"); + this.overlays.Add(item); + } + } + finally + { + ((IDisposable)(object)enumerator).Dispose(); } - this.skyTargets[0] = new WeatherWorker.SkyThreshold(def.skyColorsNightMid, 0f); - this.skyTargets[1] = new WeatherWorker.SkyThreshold(def.skyColorsNightEdge, 0.1f); - this.skyTargets[2] = new WeatherWorker.SkyThreshold(def.skyColorsDusk, 0.6f); - this.skyTargets[3] = new WeatherWorker.SkyThreshold(def.skyColorsDay, 1f); + this.skyTargets[0] = new SkyThreshold(def.skyColorsNightMid, 0f); + this.skyTargets[1] = new SkyThreshold(def.skyColorsNightEdge, 0.1f); + this.skyTargets[2] = new SkyThreshold(def.skyColorsDusk, 0.6f); + this.skyTargets[3] = new SkyThreshold(def.skyColorsDay, 1f); } public void DrawWeather(Map map) @@ -64,30 +73,27 @@ public SkyTarget CurSkyTarget(Map map) float num = GenCelestial.CurCelestialSunGlow(map); int num2 = 0; int num3 = 0; - for (int i = 0; i < this.skyTargets.Length; i++) + int num4 = 0; + while (num4 < this.skyTargets.Length) { - num3 = i; - if (num + 0.001f < this.skyTargets[i].celGlowThreshold) + num3 = num4; + if (!(num + 0.0010000000474974513 < this.skyTargets[num4].celGlowThreshold)) { - break; + num2 = num4; + num4++; + continue; } - num2 = i; + break; } - WeatherWorker.SkyThreshold skyThreshold = this.skyTargets[num2]; - WeatherWorker.SkyThreshold skyThreshold2 = this.skyTargets[num3]; - float num4 = skyThreshold2.celGlowThreshold - skyThreshold.celGlowThreshold; - float t; - if (num4 == 0f) + SkyThreshold skyThreshold = this.skyTargets[num2]; + SkyThreshold skyThreshold2 = this.skyTargets[num3]; + float num5 = skyThreshold2.celGlowThreshold - skyThreshold.celGlowThreshold; + float t = (float)((num5 != 0.0) ? ((num - skyThreshold.celGlowThreshold) / num5) : 1.0); + SkyTarget result = new SkyTarget { - t = 1f; - } - else - { - t = (num - skyThreshold.celGlowThreshold) / num4; - } - SkyTarget result = default(SkyTarget); - result.glow = num; - result.colors = SkyColorSet.Lerp(skyThreshold.colors, skyThreshold2.colors, t); + glow = num, + colors = SkyColorSet.Lerp(skyThreshold.colors, skyThreshold2.colors, t) + }; if (GenCelestial.IsDaytime(num)) { result.lightsourceShineIntensity = 1f; diff --git a/Assembly-CSharp/Verse/WidgetRow.cs b/Assembly-CSharp/Verse/WidgetRow.cs index f1b78bc22..a942fb626 100644 --- a/Assembly-CSharp/Verse/WidgetRow.cs +++ b/Assembly-CSharp/Verse/WidgetRow.cs @@ -1,5 +1,4 @@ using RimWorld; -using System; using UnityEngine; using Verse.Sound; @@ -62,11 +61,11 @@ public void Init(float x, float y, UIDirection growDirection = UIDirection.Right private float LeftX(float elementWidth) { - if (this.growDirection == UIDirection.RightThenUp || this.growDirection == UIDirection.RightThenDown) + if (this.growDirection != UIDirection.RightThenUp && this.growDirection != UIDirection.RightThenDown) { - return this.curX; + return this.curX - elementWidth; } - return this.curX - elementWidth; + return this.curX; } private void IncrementPosition(float amount) @@ -89,11 +88,11 @@ private void IncrementY() { if (this.growDirection == UIDirection.RightThenUp || this.growDirection == UIDirection.LeftThenUp) { - this.curY -= 24f + this.gap; + this.curY -= (float)(24.0 + this.gap); } else { - this.curY += 24f + this.gap; + this.curY += (float)(24.0 + this.gap); } this.curX = this.startX; } @@ -119,7 +118,7 @@ public bool ButtonIcon(Texture2D tex, string tooltip = null) this.IncrementYIfWillExceedMaxWidth(24f); Rect rect = new Rect(this.LeftX(24f), this.curY, 24f, 24f); bool result = Widgets.ButtonImage(rect, tex); - this.IncrementPosition(24f + this.gap); + this.IncrementPosition((float)(24.0 + this.gap)); if (!tooltip.NullOrEmpty()) { TooltipHandler.TipRegion(rect, tooltip); @@ -131,7 +130,7 @@ public void GapButtonIcon() { if (this.curY != this.startX) { - this.IncrementPosition(24f + this.gap); + this.IncrementPosition((float)(24.0 + this.gap)); } } @@ -140,12 +139,12 @@ public void ToggleableIcon(ref bool toggleable, Texture2D tex, string tooltip, S this.IncrementYIfWillExceedMaxWidth(24f); Rect rect = new Rect(this.LeftX(24f), this.curY, 24f, 24f); bool flag = Widgets.ButtonImage(rect, tex); - this.IncrementPosition(24f + this.gap); + this.IncrementPosition((float)(24.0 + this.gap)); if (!tooltip.NullOrEmpty()) { TooltipHandler.TipRegion(rect, tooltip); } - Rect position = new Rect(rect.x + rect.width / 2f, rect.y, rect.height / 2f, rect.height / 2f); + Rect position = new Rect((float)(rect.x + rect.width / 2.0), rect.y, (float)(rect.height / 2.0), (float)(rect.height / 2.0)); Texture2D image = (!toggleable) ? Widgets.CheckboxOffTex : Widgets.CheckboxOnTex; GUI.DrawTexture(position, image); if (mouseoverSound != null) @@ -179,7 +178,7 @@ public Rect Icon(Texture2D tex, string tooltip = null) { TooltipHandler.TipRegion(rect, tooltip); } - this.IncrementPosition(24f + this.gap); + this.IncrementPosition((float)(24.0 + this.gap)); return rect; } @@ -199,11 +198,12 @@ public bool ButtonText(string label, string tooltip = null, bool drawBackground return result; } - public Rect Label(string text, float width = -1f) + public Rect Label(string text, float width = -1) { - if (width < 0f) + if (width < 0.0) { - width = Text.CalcSize(text).x; + Vector2 vector = Text.CalcSize(text); + width = vector.x; } this.IncrementYIfWillExceedMaxWidth(width); Rect rect = new Rect(this.LeftX(width), this.curY, width, 24f); diff --git a/Assembly-CSharp/Verse/Widgets.cs b/Assembly-CSharp/Verse/Widgets.cs index 9db5bfa1b..8ac159996 100644 --- a/Assembly-CSharp/Verse/Widgets.cs +++ b/Assembly-CSharp/Verse/Widgets.cs @@ -15,9 +15,9 @@ public static class Widgets { private enum RangeEnd : byte { - None, - Min, - Max + None = 0, + Min = 1, + Max = 2 } public const float CheckboxSize = 24f; @@ -102,7 +102,7 @@ private enum RangeEnd : byte private static int draggingId; - private static Widgets.RangeEnd curDragEnd; + private static RangeEnd curDragEnd; private static float lastDragSliderSoundTime; @@ -150,26 +150,19 @@ static Widgets() Widgets.SeparatorLabelColor = new Color(0.8f, 0.8f, 0.8f, 1f); Widgets.SeparatorLineColor = new Color(0.3f, 0.3f, 0.3f, 1f); Widgets.ButtonSubtleAtlas = ContentFinder.Get("UI/Widgets/ButtonSubtleAtlas", true); - ColorInt colorInt = new ColorInt(78, 109, 129, 130); - Widgets.ButtonBarTex = SolidColorMaterials.NewSolidColorTexture(colorInt.ToColor); + Widgets.ButtonBarTex = SolidColorMaterials.NewSolidColorTexture(new ColorInt(78, 109, 129, 130).ToColor); Widgets.RangeControlTextColor = new Color(0.6f, 0.6f, 0.6f); Widgets.draggingId = 0; - Widgets.curDragEnd = Widgets.RangeEnd.None; + Widgets.curDragEnd = RangeEnd.None; Widgets.lastDragSliderSoundTime = -1f; Widgets.FillableBarChangeRateDisplayRatio = 1E+08f; Widgets.MaxFillableBarChangeRate = 3; - ColorInt colorInt2 = new ColorInt(97, 108, 122); - Widgets.WindowBGBorderColor = colorInt2.ToColor; - ColorInt colorInt3 = new ColorInt(21, 25, 29); - Widgets.WindowBGFillColor = colorInt3.ToColor; - ColorInt colorInt4 = new ColorInt(42, 43, 44); - Widgets.MenuSectionBGFillColor = colorInt4.ToColor; - ColorInt colorInt5 = new ColorInt(135, 135, 135); - Widgets.MenuSectionBGBorderColor = colorInt5.ToColor; - ColorInt colorInt6 = new ColorInt(133, 85, 44); - Widgets.TutorWindowBGFillColor = colorInt6.ToColor; - ColorInt colorInt7 = new ColorInt(176, 139, 61); - Widgets.TutorWindowBGBorderColor = colorInt7.ToColor; + Widgets.WindowBGBorderColor = new ColorInt(97, 108, 122).ToColor; + Widgets.WindowBGFillColor = new ColorInt(21, 25, 29).ToColor; + Widgets.MenuSectionBGFillColor = new ColorInt(42, 43, 44).ToColor; + Widgets.MenuSectionBGBorderColor = new ColorInt(135, 135, 135).ToColor; + Widgets.TutorWindowBGFillColor = new ColorInt(133, 85, 44).ToColor; + Widgets.TutorWindowBGBorderColor = new ColorInt(176, 139, 61).ToColor; Color color = new Color(1f, 1f, 1f, 0f); Widgets.LineTexAA = new Texture2D(1, 3, TextureFormat.ARGB32, false); Widgets.LineTexAA.name = "LineTexAA"; @@ -217,7 +210,7 @@ public static void ThingIcon(Rect rect, Thing thing, float alpha = 1f) { resolvedIcon = thing.Graphic.ExtractInnerGraphicFor(thing).MatSingle.mainTexture; } - if (alpha != 1f) + if (alpha != 1.0) { Color color = GUI.color; color.a *= alpha; @@ -237,7 +230,7 @@ public static void ThingIcon(Rect rect, ThingDef thingDef) private static void ThingIconWorker(Rect rect, ThingDef thingDef, Texture resolvedIcon) { float num = GenUI.IconDrawScale(thingDef); - if (num != 1f) + if (num != 1.0) { Vector2 center = rect.center; rect.width *= num; @@ -272,24 +265,23 @@ public static void DrawLine(Vector2 start, Vector2 end, Color color, float width float num = end.x - start.x; float num2 = end.y - start.y; float num3 = Mathf.Sqrt(num * num + num2 * num2); - if (num3 < 0.01f) - { - return; - } - width *= 3f; - float num4 = width * num2 / num3; - float num5 = width * num / num3; - Matrix4x4 identity = Matrix4x4.identity; - identity.m00 = num; - identity.m01 = -num4; - identity.m03 = start.x + 0.5f * num4; - identity.m10 = num2; - identity.m11 = num5; - identity.m13 = start.y - 0.5f * num5; - GL.PushMatrix(); - GL.MultMatrix(identity); - Graphics.DrawTexture(Widgets.LineRect, Widgets.LineTexAA, Widgets.LineRect, 0, 0, 0, 0, color, Widgets.LineMat); - GL.PopMatrix(); + if (!(num3 < 0.0099999997764825821)) + { + width = (float)(width * 3.0); + float num4 = width * num2 / num3; + float num5 = width * num / num3; + Matrix4x4 identity = Matrix4x4.identity; + identity.m00 = num; + identity.m01 = (float)(0.0 - num4); + identity.m03 = (float)(start.x + 0.5 * num4); + identity.m10 = num2; + identity.m11 = num5; + identity.m13 = (float)(start.y - 0.5 * num5); + GL.PushMatrix(); + GL.MultMatrix(identity); + Graphics.DrawTexture(Widgets.LineRect, Widgets.LineTexAA, Widgets.LineRect, 0, 0, 0, 0, color, Widgets.LineMat); + GL.PopMatrix(); + } } public static void DrawLineHorizontal(float x, float y, float length) @@ -338,20 +330,13 @@ public static void DrawBox(Rect rect, int thickness = 1) public static void LabelCacheHeight(ref Rect rect, string label, bool renderLabel = true, bool forceInvalidation = false) { bool flag = Widgets.LabelCache.ContainsKey(label); + float num = 0f; if (forceInvalidation) { flag = false; } - float height; - if (flag) - { - height = Widgets.LabelCache[label]; - } - else - { - height = Text.CalcHeight(label, rect.width); - } - rect.height = height; + num = ((!flag) ? Text.CalcHeight(label, rect.width) : Widgets.LabelCache[label]); + rect.height = num; if (renderLabel) { Widgets.Label(rect, label); @@ -370,7 +355,7 @@ public static void Label(Rect rect, string label) public static void LabelScrollable(Rect rect, string label, ref Vector2 scrollbarPosition) { - Rect rect2 = new Rect(0f, 0f, rect.width - 16f, Mathf.Max(Text.CalcHeight(label, rect.width) + 10f, rect.height)); + Rect rect2 = new Rect(0f, 0f, (float)(rect.width - 16.0), Mathf.Max((float)(Text.CalcHeight(label, rect.width) + 10.0), rect.height)); Widgets.BeginScrollView(rect, ref scrollbarPosition, rect2, true); Widgets.Label(rect2, label); Widgets.EndScrollView(); @@ -425,7 +410,7 @@ public static void CheckboxLabeled(Rect rect, string label, ref bool checkOn, bo SoundDefOf.CheckboxTurnedOff.PlayOneShotOnCamera(null); } } - Widgets.CheckboxDraw(rect.x + rect.width - 24f, rect.y, checkOn, disabled, 24f); + Widgets.CheckboxDraw((float)(rect.x + rect.width - 24.0), rect.y, checkOn, disabled, 24f); Text.Anchor = anchor; } @@ -446,9 +431,9 @@ public static bool CheckboxLabeledSelectable(Rect rect, string label, ref bool s } Color color = GUI.color; GUI.color = Color.white; - Widgets.CheckboxDraw(rect.xMax - 24f, rect.y, checkOn, false, 24f); + Widgets.CheckboxDraw((float)(rect.xMax - 24.0), rect.y, checkOn, false, 24f); GUI.color = color; - Rect butRect2 = new Rect(rect.xMax - 24f, rect.y, 24f, 24f); + Rect butRect2 = new Rect((float)(rect.xMax - 24.0), rect.y, 24f, 24f); if (Widgets.ButtonInvisible(butRect2, false)) { checkOn = !checkOn; @@ -471,15 +456,7 @@ private static void CheckboxDraw(float x, float y, bool active, bool disabled, f { GUI.color = Widgets.InactiveColor; } - Texture2D image; - if (active) - { - image = Widgets.CheckboxOnTex; - } - else - { - image = Widgets.CheckboxOffTex; - } + Texture2D image = (!active) ? Widgets.CheckboxOffTex : Widgets.CheckboxOnTex; Rect position = new Rect(x, y, size, size); GUI.DrawTexture(position, image); if (disabled) @@ -491,17 +468,23 @@ private static void CheckboxDraw(float x, float y, bool active, bool disabled, f public static bool CheckboxMulti(Vector2 topLeft, MultiCheckboxState state, float size) { Texture2D tex; - if (state == MultiCheckboxState.On) + switch (state) + { + case MultiCheckboxState.On: { tex = Widgets.CheckboxOnTex; + break; } - else if (state == MultiCheckboxState.Off) + case MultiCheckboxState.Off: { tex = Widgets.CheckboxOffTex; + break; } - else + default: { tex = Widgets.CheckboxPartialTex; + break; + } } Rect rect = new Rect(topLeft.x, topLeft.y, size, size); MouseoverSounds.DoRegion(rect); @@ -549,21 +532,13 @@ public static bool RadioButtonLabeled(Rect rect, string labelText, bool chosen) { SoundDefOf.RadioButtonClicked.PlayOneShotOnCamera(null); } - Widgets.RadioButtonDraw(rect.x + rect.width - 24f, rect.y + rect.height / 2f - 12f, chosen); + Widgets.RadioButtonDraw((float)(rect.x + rect.width - 24.0), (float)(rect.y + rect.height / 2.0 - 12.0), chosen); return flag; } private static void RadioButtonDraw(float x, float y, bool chosen) { - Texture2D image; - if (chosen) - { - image = Widgets.RadioButOnTex; - } - else - { - image = Widgets.RadioButOffTex; - } + Texture2D image = (!chosen) ? Widgets.RadioButOffTex : Widgets.RadioButOnTex; Rect position = new Rect(x, y, 24f, 24f); GUI.DrawTexture(position, image); } @@ -613,7 +588,11 @@ public static bool ButtonText(Rect rect, string label, bool drawBackground, bool Widgets.Label(rect, label); Text.Anchor = anchor; GUI.color = color; - return active && Widgets.ButtonInvisible(rect, false); + if (active) + { + return Widgets.ButtonInvisible(rect, false); + } + return false; } public static void DrawRectFast(Rect position, Color color, GUIContent content = null) @@ -652,10 +631,14 @@ public static bool CustomButtonText(ref Rect rect, string label, Color bgColor, Widgets.Label(rect, label); Text.Anchor = anchor; GUI.color = color; - return active && Widgets.ButtonInvisible(rect, false); + if (active) + { + return Widgets.ButtonInvisible(rect, false); + } + return false; } - public static bool ButtonTextSubtle(Rect rect, string label, float barPercent = 0f, float textLeftMargin = -1f, SoundDef mouseoverSound = null) + public static bool ButtonTextSubtle(Rect rect, string label, float barPercent = 0, float textLeftMargin = -1, SoundDef mouseoverSound = null) { bool flag = false; if (Mouse.IsOver(rect)) @@ -669,15 +652,15 @@ public static bool ButtonTextSubtle(Rect rect, string label, float barPercent = } Widgets.DrawAtlas(rect, Widgets.ButtonSubtleAtlas); GUI.color = Color.white; - if (barPercent > 0.001f) + if (barPercent > 0.0010000000474974513) { Rect rect2 = rect.ContractedBy(1f); Widgets.FillableBar(rect2, barPercent, Widgets.ButtonBarTex, null, false); } Rect rect3 = new Rect(rect); - if (textLeftMargin < 0f) + if (textLeftMargin < 0.0) { - textLeftMargin = rect.width * 0.15f; + textLeftMargin = (float)(rect.width * 0.15000000596046448); } rect3.x += textLeftMargin; if (flag) @@ -721,7 +704,7 @@ public static bool ButtonImage(Rect butRect, Texture2D tex, Color baseColor, Col public static bool CloseButtonFor(Rect rectToClose) { - Rect butRect = new Rect(rectToClose.x + rectToClose.width - 18f - 4f, rectToClose.y + 4f, 18f, 18f); + Rect butRect = new Rect((float)(rectToClose.x + rectToClose.width - 18.0 - 4.0), (float)(rectToClose.y + 4.0), 18f, 18f); return Widgets.ButtonImage(butRect, TexButton.CloseXSmall); } @@ -764,7 +747,7 @@ public static string TextArea(Rect rect, string text, bool readOnly = false) public static string TextAreaScrollable(Rect rect, string text, ref Vector2 scrollbarPosition, bool readOnly = false) { - Rect rect2 = new Rect(0f, 0f, rect.width - 16f, Mathf.Max(Text.CalcHeight(text, rect.width) + 10f, rect.height)); + Rect rect2 = new Rect(0f, 0f, (float)(rect.width - 16.0), Mathf.Max((float)(Text.CalcHeight(text, rect.width) + 10.0), rect.height)); Widgets.BeginScrollView(rect, ref scrollbarPosition, rect2, true); string result = Widgets.TextArea(rect2, text, readOnly); Widgets.EndScrollView(); @@ -779,14 +762,14 @@ public static string TextEntryLabeled(Rect rect, string label, string text) Text.Anchor = TextAnchor.MiddleRight; Widgets.Label(rect2, label); Text.Anchor = anchor; - if (rect.height <= 30f) + if (rect.height <= 30.0) { return Widgets.TextField(rect3, text); } return Widgets.TextArea(rect3, text, false); } - public static void TextFieldNumeric(Rect rect, ref T val, ref string buffer, float min = 0f, float max = 1E+09f) where T : struct + public static void TextFieldNumeric(Rect rect, ref T val, ref string buffer, float min = 0, float max = 1000000000) where T : struct { if (buffer == null) { @@ -813,33 +796,30 @@ private static void ResolveParseNow(string edited, ref T val, ref string buff { if (typeof(T) == typeof(int)) { + int num = default(int); if (edited.NullOrEmpty()) { Widgets.ResetValue(edited, ref val, ref buffer, min, max); - return; } - int num; - if (int.TryParse(edited, out num)) + else if (int.TryParse(edited, out num)) { - val = (T)((object)Mathf.RoundToInt(Mathf.Clamp((float)num, min, max))); + val = (T)(object)Mathf.RoundToInt(Mathf.Clamp((float)num, min, max)); buffer = Widgets.ToStringTypedIn(val); - return; } - if (force) + else if (force) { Widgets.ResetValue(edited, ref val, ref buffer, min, max); } } else if (typeof(T) == typeof(float)) { - float value; + float value = default(float); if (float.TryParse(edited, out value)) { - val = (T)((object)Mathf.Clamp(value, min, max)); + val = (T)(object)Mathf.Clamp(value, min, max); buffer = Widgets.ToStringTypedIn(val); - return; } - if (force) + else if (force) { Widgets.ResetValue(edited, ref val, ref buffer, min, max); } @@ -853,13 +833,13 @@ private static void ResolveParseNow(string edited, ref T val, ref string buff private static void ResetValue(string edited, ref T val, ref string buffer, float min, float max) { val = default(T); - if (min > 0f) + if (min > 0.0) { - val = (T)((object)Mathf.RoundToInt(min)); + val = (T)(object)Mathf.RoundToInt(min); } - if (max < 0f) + if (max < 0.0) { - val = (T)((object)Mathf.RoundToInt(max)); + val = (T)(object)Mathf.RoundToInt(max); } buffer = Widgets.ToStringTypedIn(val); } @@ -868,7 +848,7 @@ private static string ToStringTypedIn(T val) { if (typeof(T) == typeof(float)) { - return ((float)((object)val)).ToString("0.##########"); + return ((float)(object)val).ToString("0.##########"); } return val.ToString(); } @@ -879,7 +859,7 @@ private static bool IsPartiallyOrFullyTypedNumber(ref T val, string s, float { return true; } - if (s[0] == '-' && min >= 0f) + if (s[0] == '-' && min >= 0.0) { return false; } @@ -903,7 +883,11 @@ private static bool IsPartiallyOrFullyTypedNumber(ref T val, string s, float return true; } } - return s.IsFullyTypedNumber(); + if (s.IsFullyTypedNumber()) + { + return true; + } + return false; } private static bool IsFullyTypedNumber(this string s) @@ -914,24 +898,28 @@ private static bool IsFullyTypedNumber(this string s) } if (typeof(T) == typeof(float)) { - string[] array = s.Split(new char[] - { - '.' - }); - if (array.Length > 2 || array.Length < 1) + string[] array = s.Split('.'); + if (array.Length <= 2 && array.Length >= 1) { - return false; - } - if (!array[0].ContainsOnlyCharacters("-0123456789")) - { - return false; - } - if (array.Length == 2 && !array[1].ContainsOnlyCharacters("0123456789")) - { - return false; + if (!array[0].ContainsOnlyCharacters("-0123456789")) + { + return false; + } + if (array.Length == 2 && !array[1].ContainsOnlyCharacters("0123456789")) + { + return false; + } + goto IL_0082; } + return false; } - return typeof(T) != typeof(int) || s.ContainsOnlyCharacters("-0123456789"); + goto IL_0082; + IL_0082: + if (typeof(T) == typeof(int) && !s.ContainsOnlyCharacters("-0123456789")) + { + return false; + } + return true; } private static bool ContainsOnlyCharacters(this string s, string allowedChars) @@ -959,7 +947,7 @@ private static int CharacterCount(this string s, char c) return num; } - public static void TextFieldNumericLabeled(Rect rect, string label, ref T val, ref string buffer, float min = 0f, float max = 1E+09f) where T : struct + public static void TextFieldNumericLabeled(Rect rect, string label, ref T val, ref string buffer, float min = 0, float max = 1000000000) where T : struct { Rect rect2 = rect.LeftHalf().Rounded(); Rect rect3 = rect.RightHalf().Rounded(); @@ -972,12 +960,12 @@ public static void TextFieldNumericLabeled(Rect rect, string label, ref T val public static void TextFieldPercent(Rect rect, ref float val, ref string buffer, float min = 0f, float max = 1f) { - Rect rect2 = new Rect(rect.x, rect.y, rect.width - 25f, rect.height); + Rect rect2 = new Rect(rect.x, rect.y, (float)(rect.width - 25.0), rect.height); Rect rect3 = new Rect(rect2.xMax, rect.y, 25f, rect2.height); Widgets.Label(rect3, "%"); - float num = val * 100f; - Widgets.TextFieldNumeric(rect2, ref num, ref buffer, min * 100f, max * 100f); - val = num / 100f; + float num = (float)(val * 100.0); + Widgets.TextFieldNumeric(rect2, ref num, ref buffer, (float)(min * 100.0), (float)(max * 100.0)); + val = (float)(num / 100.0); if (val > max) { val = max; @@ -987,14 +975,14 @@ public static void TextFieldPercent(Rect rect, ref float val, ref string buffer, public static T ChangeType(this object obj) { - return (T)((object)Convert.ChangeType(obj, typeof(T))); + return (T)Convert.ChangeType(obj, typeof(T)); } public static float HorizontalSlider(Rect rect, float value, float leftValue, float rightValue, bool middleAlignment = false, string label = null, string leftAlignedLabel = null, string rightAlignedLabel = null, float roundTo = -1f) { if (middleAlignment || !label.NullOrEmpty()) { - rect.y += Mathf.Round((rect.height - 16f) / 2f); + rect.y += Mathf.Round((float)((rect.height - 16.0) / 2.0)); } if (!label.NullOrEmpty()) { @@ -1006,8 +994,18 @@ public static float HorizontalSlider(Rect rect, float value, float leftValue, fl TextAnchor anchor = Text.Anchor; GameFont font = Text.Font; Text.Font = GameFont.Tiny; - float num2 = (!label.NullOrEmpty()) ? Text.CalcSize(label).y : 18f; - rect.y = rect.y - num2 + 3f; + double num2; + if (label.NullOrEmpty()) + { + num2 = 18.0; + } + else + { + Vector2 vector = Text.CalcSize(label); + num2 = vector.y; + } + float num3 = (float)num2; + rect.y = (float)(rect.y - num3 + 3.0); if (!leftAlignedLabel.NullOrEmpty()) { Text.Anchor = TextAnchor.UpperLeft; @@ -1026,7 +1024,7 @@ public static float HorizontalSlider(Rect rect, float value, float leftValue, fl Text.Anchor = anchor; Text.Font = font; } - if (roundTo > 0f) + if (roundTo > 0.0) { num = (float)Mathf.RoundToInt(num / roundTo) * roundTo; } @@ -1036,39 +1034,21 @@ public static float HorizontalSlider(Rect rect, float value, float leftValue, fl public static float FrequencyHorizontalSlider(Rect rect, float freq, float minFreq, float maxFreq, bool roundToInt = false) { float num; - if (freq < 1f) + if (freq < 1.0) { - float x = 1f / freq; - num = GenMath.LerpDouble(1f, 1f / minFreq, 0.5f, 1f, x); + float x = (float)(1.0 / freq); + num = GenMath.LerpDouble(1f, (float)(1.0 / minFreq), 0.5f, 1f, x); } else { num = GenMath.LerpDouble(maxFreq, 1f, 0f, 0.5f, freq); } - string label; - if (freq == 1f) - { - label = "EveryDay".Translate(); - } - else if (freq < 1f) - { - label = "TimesPerDay".Translate(new object[] - { - (1f / freq).ToString("0.##") - }); - } - else - { - label = "EveryDays".Translate(new object[] - { - freq.ToString("0.##") - }); - } - float num2 = Widgets.HorizontalSlider(rect, num, 0f, 1f, true, label, null, null, -1f); + string label = (freq != 1.0) ? ((!(freq < 1.0)) ? "EveryDays".Translate(freq.ToString("0.##")) : "TimesPerDay".Translate(((float)(1.0 / freq)).ToString("0.##"))) : "EveryDay".Translate(); + float num2 = Widgets.HorizontalSlider(rect, num, 0f, 1f, true, label, (string)null, (string)null, -1f); if (num != num2) { float num3; - if (num2 < 0.5f) + if (num2 < 0.5) { num3 = GenMath.LerpDouble(0.5f, 0f, 1f, maxFreq, num2); if (roundToInt) @@ -1078,19 +1058,19 @@ public static float FrequencyHorizontalSlider(Rect rect, float freq, float minFr } else { - float num4 = GenMath.LerpDouble(1f, 0.5f, 1f / minFreq, 1f, num2); + float num4 = GenMath.LerpDouble(1f, 0.5f, (float)(1.0 / minFreq), 1f, num2); if (roundToInt) { num4 = Mathf.Round(num4); } - num3 = 1f / num4; + num3 = (float)(1.0 / num4); } freq = num3; } return freq; } - public static void FloatRange(Rect rect, int id, ref FloatRange range, float min = 0f, float max = 1f, string labelKey = null, ToStringStyle valueStyle = ToStringStyle.FloatTwo) + public static void FloatRange(Rect rect, int id, ref FloatRange range, float min = 0, float max = 1, string labelKey = null, ToStringStyle valueStyle = ToStringStyle.FloatTwo) { Rect rect2 = rect; rect2.xMin += 8f; @@ -1099,29 +1079,30 @@ public static void FloatRange(Rect rect, int id, ref FloatRange range, float min string text = range.min.ToStringByStyle(valueStyle, ToStringNumberSense.Absolute) + " - " + range.max.ToStringByStyle(valueStyle, ToStringNumberSense.Absolute); if (labelKey != null) { - text = labelKey.Translate(new object[] - { - text - }); + text = labelKey.Translate(text); } GameFont font = Text.Font; Text.Font = GameFont.Tiny; Text.Anchor = TextAnchor.UpperCenter; Widgets.Label(rect2, text); Text.Anchor = TextAnchor.UpperLeft; - Rect position = new Rect(rect2.x, rect2.yMax - 8f - 1f, rect2.width, 2f); + Rect position = new Rect(rect2.x, (float)(rect2.yMax - 8.0 - 1.0), rect2.width, 2f); GUI.DrawTexture(position, BaseContent.WhiteTex); GUI.color = Color.white; float num = rect2.x + (rect2.width * range.min - min / (max - min)); float num2 = rect2.x + (rect2.width * range.max - min / (max - min)); - Rect position2 = new Rect(num - 16f, position.center.y - 8f, 16f, 16f); + double x = num - 16.0; + Vector2 center = position.center; + Rect position2 = new Rect((float)x, (float)(center.y - 8.0), 16f, 16f); GUI.DrawTexture(position2, Widgets.FloatRangeSliderTex); - Rect position3 = new Rect(num2 + 16f, position.center.y - 8f, -16f, 16f); + double x2 = num2 + 16.0; + Vector2 center2 = position.center; + Rect position3 = new Rect((float)x2, (float)(center2.y - 8.0), -16f, 16f); GUI.DrawTexture(position3, Widgets.FloatRangeSliderTex); - if (Widgets.curDragEnd != Widgets.RangeEnd.None && (Event.current.type == EventType.MouseUp || Event.current.rawType == EventType.MouseDown)) + if (Widgets.curDragEnd != 0 && (Event.current.type == EventType.MouseUp || Event.current.rawType == EventType.MouseDown)) { Widgets.draggingId = 0; - Widgets.curDragEnd = Widgets.RangeEnd.None; + Widgets.curDragEnd = RangeEnd.None; SoundDefOf.DragSlider.PlayOneShotOnCamera(null); } bool flag = false; @@ -1130,34 +1111,36 @@ public static void FloatRange(Rect rect, int id, ref FloatRange range, float min if (Event.current.type == EventType.MouseDown && Event.current.button == 0 && id != Widgets.draggingId) { Widgets.draggingId = id; - float x = Event.current.mousePosition.x; - if (x < position2.xMax) + Vector2 mousePosition = Event.current.mousePosition; + float x3 = mousePosition.x; + if (x3 < position2.xMax) { - Widgets.curDragEnd = Widgets.RangeEnd.Min; + Widgets.curDragEnd = RangeEnd.Min; } - else if (x > position3.xMin) + else if (x3 > position3.xMin) { - Widgets.curDragEnd = Widgets.RangeEnd.Max; + Widgets.curDragEnd = RangeEnd.Max; } else { - float num3 = Mathf.Abs(x - position2.xMax); - float num4 = Mathf.Abs(x - (position3.x - 16f)); - Widgets.curDragEnd = ((num3 >= num4) ? Widgets.RangeEnd.Max : Widgets.RangeEnd.Min); + float num3 = Mathf.Abs(x3 - position2.xMax); + float num4 = Mathf.Abs((float)(x3 - (position3.x - 16.0))); + Widgets.curDragEnd = (RangeEnd)((num3 < num4) ? 1 : 2); } flag = true; Event.current.Use(); SoundDefOf.DragSlider.PlayOneShotOnCamera(null); } - if (flag || (Widgets.curDragEnd != Widgets.RangeEnd.None && Event.current.type == EventType.MouseDrag)) + if (flag || (Widgets.curDragEnd != 0 && Event.current.type == EventType.MouseDrag)) { - float num5 = (Event.current.mousePosition.x - rect2.x) / rect2.width * (max - min) + min; - num5 = Mathf.Clamp(num5, min, max); - if (Widgets.curDragEnd == Widgets.RangeEnd.Min) + Vector2 mousePosition2 = Event.current.mousePosition; + float value = (mousePosition2.x - rect2.x) / rect2.width * (max - min) + min; + value = Mathf.Clamp(value, min, max); + if (Widgets.curDragEnd == RangeEnd.Min) { - if (num5 != range.min) + if (value != range.min) { - range.min = num5; + range.min = value; if (range.max < range.min) { range.max = range.min; @@ -1165,9 +1148,9 @@ public static void FloatRange(Rect rect, int id, ref FloatRange range, float min Widgets.CheckPlayDragSliderSound(); } } - else if (Widgets.curDragEnd == Widgets.RangeEnd.Max && num5 != range.max) + else if (Widgets.curDragEnd == RangeEnd.Max && value != range.max) { - range.max = num5; + range.max = value; if (range.min > range.max) { range.min = range.max; @@ -1189,29 +1172,30 @@ public static void IntRange(Rect rect, int id, ref IntRange range, int min = 0, string text = range.min.ToStringCached() + " - " + range.max.ToStringCached(); if (labelKey != null) { - text = labelKey.Translate(new object[] - { - text - }); + text = labelKey.Translate(text); } GameFont font = Text.Font; Text.Font = GameFont.Tiny; Text.Anchor = TextAnchor.UpperCenter; Widgets.Label(rect2, text); Text.Anchor = TextAnchor.UpperLeft; - Rect position = new Rect(rect2.x, rect2.yMax - 8f - 1f, rect2.width, 2f); + Rect position = new Rect(rect2.x, (float)(rect2.yMax - 8.0 - 1.0), rect2.width, 2f); GUI.DrawTexture(position, BaseContent.WhiteTex); GUI.color = Color.white; float num = rect2.x + rect2.width * (float)(range.min - min) / (float)(max - min); float num2 = rect2.x + rect2.width * (float)(range.max - min) / (float)(max - min); - Rect position2 = new Rect(num - 16f, position.center.y - 8f, 16f, 16f); + double x = num - 16.0; + Vector2 center = position.center; + Rect position2 = new Rect((float)x, (float)(center.y - 8.0), 16f, 16f); GUI.DrawTexture(position2, Widgets.FloatRangeSliderTex); - Rect position3 = new Rect(num2 + 16f, position.center.y - 8f, -16f, 16f); + double x2 = num2 + 16.0; + Vector2 center2 = position.center; + Rect position3 = new Rect((float)x2, (float)(center2.y - 8.0), -16f, 16f); GUI.DrawTexture(position3, Widgets.FloatRangeSliderTex); - if (Widgets.curDragEnd != Widgets.RangeEnd.None && (Event.current.type == EventType.MouseUp || Event.current.rawType == EventType.MouseDown)) + if (Widgets.curDragEnd != 0 && (Event.current.type == EventType.MouseUp || Event.current.rawType == EventType.MouseDown)) { Widgets.draggingId = 0; - Widgets.curDragEnd = Widgets.RangeEnd.None; + Widgets.curDragEnd = RangeEnd.None; SoundDefOf.DragSlider.PlayOneShotOnCamera(null); } bool flag = false; @@ -1220,58 +1204,60 @@ public static void IntRange(Rect rect, int id, ref IntRange range, int min = 0, if (Event.current.type == EventType.MouseDown && Event.current.button == 0 && id != Widgets.draggingId) { Widgets.draggingId = id; - float x = Event.current.mousePosition.x; - if (x < position2.xMax) + Vector2 mousePosition = Event.current.mousePosition; + float x3 = mousePosition.x; + if (x3 < position2.xMax) { - Widgets.curDragEnd = Widgets.RangeEnd.Min; + Widgets.curDragEnd = RangeEnd.Min; } - else if (x > position3.xMin) + else if (x3 > position3.xMin) { - Widgets.curDragEnd = Widgets.RangeEnd.Max; + Widgets.curDragEnd = RangeEnd.Max; } else { - float num3 = Mathf.Abs(x - position2.xMax); - float num4 = Mathf.Abs(x - (position3.x - 16f)); - Widgets.curDragEnd = ((num3 >= num4) ? Widgets.RangeEnd.Max : Widgets.RangeEnd.Min); + float num3 = Mathf.Abs(x3 - position2.xMax); + float num4 = Mathf.Abs((float)(x3 - (position3.x - 16.0))); + Widgets.curDragEnd = (RangeEnd)((num3 < num4) ? 1 : 2); } flag = true; Event.current.Use(); SoundDefOf.DragSlider.PlayOneShotOnCamera(null); } - if (flag || (Widgets.curDragEnd != Widgets.RangeEnd.None && Event.current.type == EventType.MouseDrag)) + if (flag || (Widgets.curDragEnd != 0 && Event.current.type == EventType.MouseDrag)) { - float num5 = (Event.current.mousePosition.x - rect2.x) / rect2.width * (float)(max - min) + (float)min; - num5 = Mathf.Clamp(num5, (float)min, (float)max); - int num6 = Mathf.RoundToInt(num5); - if (Widgets.curDragEnd == Widgets.RangeEnd.Min) + Vector2 mousePosition2 = Event.current.mousePosition; + float value = (mousePosition2.x - rect2.x) / rect2.width * (float)(max - min) + (float)min; + value = Mathf.Clamp(value, (float)min, (float)max); + int num5 = Mathf.RoundToInt(value); + if (Widgets.curDragEnd == RangeEnd.Min) { - if (num6 != range.min) + if (num5 != range.min) { - range.min = num6; + range.min = num5; if (range.min > max - minWidth) { range.min = max - minWidth; } - int num7 = Mathf.Max(min, range.min + minWidth); - if (range.max < num7) + int num6 = Mathf.Max(min, range.min + minWidth); + if (range.max < num6) { - range.max = num7; + range.max = num6; } Widgets.CheckPlayDragSliderSound(); } } - else if (Widgets.curDragEnd == Widgets.RangeEnd.Max && num6 != range.max) + else if (Widgets.curDragEnd == RangeEnd.Max && num5 != range.max) { - range.max = num6; + range.max = num5; if (range.max < min + minWidth) { range.max = min + minWidth; } - int num8 = Mathf.Min(max, range.max - minWidth); - if (range.min > num8) + int num7 = Mathf.Min(max, range.max - minWidth); + if (range.min > num7) { - range.min = num8; + range.min = num7; } Widgets.CheckPlayDragSliderSound(); } @@ -1283,7 +1269,7 @@ public static void IntRange(Rect rect, int id, ref IntRange range, int min = 0, private static void CheckPlayDragSliderSound() { - if (Time.realtimeSinceStartup > Widgets.lastDragSliderSoundTime + 0.075f) + if (Time.realtimeSinceStartup > Widgets.lastDragSliderSoundTime + 0.075000002980232239) { SoundDefOf.DragSlider.PlayOneShotOnCamera(null); Widgets.lastDragSliderSoundTime = Time.realtimeSinceStartup; @@ -1296,41 +1282,30 @@ public static void QualityRange(Rect rect, int id, ref QualityRange range) rect2.xMin += 8f; rect2.xMax -= 8f; GUI.color = Widgets.RangeControlTextColor; - string label; - if (range == RimWorld.QualityRange.All) - { - label = "AnyQuality".Translate(); - } - else if (range.max == range.min) - { - label = "OnlyQuality".Translate(new object[] - { - range.min.GetLabel() - }); - } - else - { - label = range.min.GetLabel() + " - " + range.max.GetLabel(); - } + string label = (!(range == RimWorld.QualityRange.All)) ? ((range.max != range.min) ? (range.min.GetLabel() + " - " + range.max.GetLabel()) : "OnlyQuality".Translate(range.min.GetLabel())) : "AnyQuality".Translate(); GameFont font = Text.Font; Text.Font = GameFont.Tiny; Text.Anchor = TextAnchor.UpperCenter; Widgets.Label(rect2, label); Text.Anchor = TextAnchor.UpperLeft; - Rect position = new Rect(rect2.x, rect2.yMax - 8f - 1f, rect2.width, 2f); + Rect position = new Rect(rect2.x, (float)(rect2.yMax - 8.0 - 1.0), rect2.width, 2f); GUI.DrawTexture(position, BaseContent.WhiteTex); GUI.color = Color.white; int length = Enum.GetValues(typeof(QualityCategory)).Length; - float num = rect2.x + rect2.width / (float)(length - 1) * (float)range.min; - float num2 = rect2.x + rect2.width / (float)(length - 1) * (float)range.max; - Rect position2 = new Rect(num - 16f, position.center.y - 8f, 16f, 16f); + float num = rect2.x + rect2.width / (float)(length - 1) * (float)(int)range.min; + float num2 = rect2.x + rect2.width / (float)(length - 1) * (float)(int)range.max; + double x = num - 16.0; + Vector2 center = position.center; + Rect position2 = new Rect((float)x, (float)(center.y - 8.0), 16f, 16f); GUI.DrawTexture(position2, Widgets.FloatRangeSliderTex); - Rect position3 = new Rect(num2 + 16f, position.center.y - 8f, -16f, 16f); + double x2 = num2 + 16.0; + Vector2 center2 = position.center; + Rect position3 = new Rect((float)x2, (float)(center2.y - 8.0), -16f, 16f); GUI.DrawTexture(position3, Widgets.FloatRangeSliderTex); - if (Widgets.curDragEnd != Widgets.RangeEnd.None && (Event.current.type == EventType.MouseUp || Event.current.type == EventType.MouseDown)) + if (Widgets.curDragEnd != 0 && (Event.current.type == EventType.MouseUp || Event.current.type == EventType.MouseDown)) { Widgets.draggingId = 0; - Widgets.curDragEnd = Widgets.RangeEnd.None; + Widgets.curDragEnd = RangeEnd.None; SoundDefOf.DragSlider.PlayOneShotOnCamera(null); } bool flag = false; @@ -1339,46 +1314,48 @@ public static void QualityRange(Rect rect, int id, ref QualityRange range) if (Event.current.type == EventType.MouseDown && Event.current.button == 0 && id != Widgets.draggingId) { Widgets.draggingId = id; - float x = Event.current.mousePosition.x; - if (x < position2.xMax) + Vector2 mousePosition = Event.current.mousePosition; + float x3 = mousePosition.x; + if (x3 < position2.xMax) { - Widgets.curDragEnd = Widgets.RangeEnd.Min; + Widgets.curDragEnd = RangeEnd.Min; } - else if (x > position3.xMin) + else if (x3 > position3.xMin) { - Widgets.curDragEnd = Widgets.RangeEnd.Max; + Widgets.curDragEnd = RangeEnd.Max; } else { - float num3 = Mathf.Abs(x - position2.xMax); - float num4 = Mathf.Abs(x - (position3.x - 16f)); - Widgets.curDragEnd = ((num3 >= num4) ? Widgets.RangeEnd.Max : Widgets.RangeEnd.Min); + float num3 = Mathf.Abs(x3 - position2.xMax); + float num4 = Mathf.Abs((float)(x3 - (position3.x - 16.0))); + Widgets.curDragEnd = (RangeEnd)((num3 < num4) ? 1 : 2); } flag = true; Event.current.Use(); SoundDefOf.DragSlider.PlayOneShotOnCamera(null); } - if (flag || (Widgets.curDragEnd != Widgets.RangeEnd.None && Event.current.type == EventType.MouseDrag)) + if (flag || (Widgets.curDragEnd != 0 && Event.current.type == EventType.MouseDrag)) { - float num5 = (Event.current.mousePosition.x - rect2.x) / rect2.width; - int num6 = Mathf.RoundToInt(num5 * (float)(length - 1)); - num6 = Mathf.Clamp(num6, 0, length - 1); - if (Widgets.curDragEnd == Widgets.RangeEnd.Min) + Vector2 mousePosition2 = Event.current.mousePosition; + float num5 = (mousePosition2.x - rect2.x) / rect2.width; + int value = Mathf.RoundToInt(num5 * (float)(length - 1)); + value = Mathf.Clamp(value, 0, length - 1); + if (Widgets.curDragEnd == RangeEnd.Min) { - if (range.min != (QualityCategory)num6) + if (range.min != (QualityCategory)(byte)value) { - range.min = (QualityCategory)num6; - if (range.max < range.min) + range.min = (QualityCategory)(byte)value; + if ((int)range.max < (int)range.min) { range.max = range.min; } SoundDefOf.DragSlider.PlayOneShotOnCamera(null); } } - else if (Widgets.curDragEnd == Widgets.RangeEnd.Max && range.max != (QualityCategory)num6) + else if (Widgets.curDragEnd == RangeEnd.Max && range.max != (QualityCategory)(byte)value) { - range.max = (QualityCategory)num6; - if (range.min > range.max) + range.max = (QualityCategory)(byte)value; + if ((int)range.min > (int)range.max) { range.min = range.max; } @@ -1390,22 +1367,30 @@ public static void QualityRange(Rect rect, int id, ref QualityRange range) Text.Font = font; } - public static void FloatRangeWithTypeIn(Rect rect, int id, ref FloatRange fRange, float sliderMin = 0f, float sliderMax = 1f, ToStringStyle valueStyle = ToStringStyle.FloatTwo, string labelKey = null) + public static void FloatRangeWithTypeIn(Rect rect, int id, ref FloatRange fRange, float sliderMin = 0, float sliderMax = 1, ToStringStyle valueStyle = ToStringStyle.FloatTwo, string labelKey = null) { - Rect rect2 = new Rect(rect); - rect2.width = rect.width / 4f; - Rect rect3 = new Rect(rect); - rect3.width = rect.width / 2f; - rect3.x = rect.x + rect.width / 4f; - rect3.height = rect.height / 2f; + Rect rect2 = new Rect(rect) + { + width = (float)(rect.width / 4.0) + }; + Rect rect3 = new Rect(rect) + { + width = (float)(rect.width / 2.0), + x = (float)(rect.x + rect.width / 4.0), + height = (float)(rect.height / 2.0) + }; rect3.width -= rect.height; - Rect butRect = new Rect(rect3); - butRect.x = rect3.xMax; - butRect.height = rect.height; - butRect.width = rect.height; - Rect rect4 = new Rect(rect); - rect4.x = rect.x + rect.width * 0.75f; - rect4.width = rect.width / 4f; + Rect butRect = new Rect(rect3) + { + x = rect3.xMax, + height = rect.height, + width = rect.height + }; + Rect rect4 = new Rect(rect) + { + x = (float)(rect.x + rect.width * 0.75), + width = (float)(rect.width / 4.0) + }; Widgets.FloatRange(rect3, id, ref fRange, sliderMin, sliderMax, labelKey, valueStyle); if (Widgets.ButtonImage(butRect, TexButton.RangeMatch)) { @@ -1422,7 +1407,7 @@ public static void FillableBar(Rect rect, float fillPercent) public static void FillableBar(Rect rect, float fillPercent, Texture2D fillTex) { - bool doBorder = rect.height > 15f && rect.width > 20f; + bool doBorder = rect.height > 15.0 && rect.width > 20.0; Widgets.FillableBar(rect, fillPercent, fillTex, Widgets.DefaultBarBgTex, doBorder); } @@ -1433,7 +1418,7 @@ public static void FillableBar(Rect rect, float fillPercent, Texture2D fillTex, GUI.DrawTexture(rect, BaseContent.BlackTex); rect = rect.ContractedBy(3f); } - if (bgTex != null) + if ((UnityEngine.Object)bgTex != (UnityEngine.Object)null) { GUI.DrawTexture(rect, bgTex); } @@ -1443,11 +1428,11 @@ public static void FillableBar(Rect rect, float fillPercent, Texture2D fillTex, public static void FillableBarLabeled(Rect rect, float fillPercent, int labelWidth, string label) { - if (fillPercent < 0f) + if (fillPercent < 0.0) { fillPercent = 0f; } - if (fillPercent > 1f) + if (fillPercent > 1.0) { fillPercent = 1f; } @@ -1468,45 +1453,44 @@ public static void FillableBarChangeArrows(Rect barRect, float changeRate) public static void FillableBarChangeArrows(Rect barRect, int changeRate) { - if (changeRate == 0) + if (changeRate != 0) { - return; - } - if (changeRate > Widgets.MaxFillableBarChangeRate) - { - changeRate = Widgets.MaxFillableBarChangeRate; - } - if (changeRate < -Widgets.MaxFillableBarChangeRate) - { - changeRate = -Widgets.MaxFillableBarChangeRate; - } - float num = barRect.height; - if (num > 16f) - { - num = 16f; - } - int num2 = Mathf.Abs(changeRate); - float y = barRect.y + barRect.height / 2f - num / 2f; - float num3; - float num4; - Texture2D image; - if (changeRate > 0) - { - num3 = barRect.x + barRect.width + 2f; - num4 = 8f; - image = Widgets.FillArrowTexRight; - } - else - { - num3 = barRect.x - 8f - 2f; - num4 = -8f; - image = Widgets.FillArrowTexLeft; - } - for (int i = 0; i < num2; i++) - { - Rect position = new Rect(num3, y, 8f, num); - GUI.DrawTexture(position, image); - num3 += num4; + if (changeRate > Widgets.MaxFillableBarChangeRate) + { + changeRate = Widgets.MaxFillableBarChangeRate; + } + if (changeRate < -Widgets.MaxFillableBarChangeRate) + { + changeRate = -Widgets.MaxFillableBarChangeRate; + } + float num = barRect.height; + if (num > 16.0) + { + num = 16f; + } + int num2 = Mathf.Abs(changeRate); + float y = (float)(barRect.y + barRect.height / 2.0 - num / 2.0); + float num3; + float num4; + Texture2D image; + if (changeRate > 0) + { + num3 = (float)(barRect.x + barRect.width + 2.0); + num4 = 8f; + image = Widgets.FillArrowTexRight; + } + else + { + num3 = (float)(barRect.x - 8.0 - 2.0); + num4 = -8f; + image = Widgets.FillArrowTexLeft; + } + for (int num5 = 0; num5 < num2; num5++) + { + Rect position = new Rect(num3, y, 8f, num); + GUI.DrawTexture(position, image); + num3 += num4; + } } } @@ -1556,56 +1540,56 @@ public static void DrawAtlas(Rect rect, Texture2D atlas, bool drawTop) rect.y = Mathf.Round(rect.y); rect.width = Mathf.Round(rect.width); rect.height = Mathf.Round(rect.height); - float num = (float)atlas.width * 0.25f; - num = Mathf.Floor(GenMath.Min(num, rect.height / 2f, rect.width / 2f)); + float a = (float)((float)atlas.width * 0.25); + a = Mathf.Floor(GenMath.Min(a, (float)(rect.height / 2.0), (float)(rect.width / 2.0))); GUI.BeginGroup(rect); Rect drawRect; Rect uvRect; if (drawTop) { - drawRect = new Rect(0f, 0f, num, num); + drawRect = new Rect(0f, 0f, a, a); uvRect = new Rect(0f, 0f, 0.25f, 0.25f); Widgets.DrawTexturePart(drawRect, uvRect, atlas); - drawRect = new Rect(rect.width - num, 0f, num, num); + drawRect = new Rect(rect.width - a, 0f, a, a); uvRect = new Rect(0.75f, 0f, 0.25f, 0.25f); Widgets.DrawTexturePart(drawRect, uvRect, atlas); } - drawRect = new Rect(0f, rect.height - num, num, num); + drawRect = new Rect(0f, rect.height - a, a, a); uvRect = new Rect(0f, 0.75f, 0.25f, 0.25f); Widgets.DrawTexturePart(drawRect, uvRect, atlas); - drawRect = new Rect(rect.width - num, rect.height - num, num, num); + drawRect = new Rect(rect.width - a, rect.height - a, a, a); uvRect = new Rect(0.75f, 0.75f, 0.25f, 0.25f); Widgets.DrawTexturePart(drawRect, uvRect, atlas); - drawRect = new Rect(num, num, rect.width - num * 2f, rect.height - num * 2f); + drawRect = new Rect(a, a, (float)(rect.width - a * 2.0), (float)(rect.height - a * 2.0)); if (!drawTop) { - drawRect.height += num; - drawRect.y -= num; + drawRect.height += a; + drawRect.y -= a; } uvRect = new Rect(0.25f, 0.25f, 0.5f, 0.5f); Widgets.DrawTexturePart(drawRect, uvRect, atlas); if (drawTop) { - drawRect = new Rect(num, 0f, rect.width - num * 2f, num); + drawRect = new Rect(a, 0f, (float)(rect.width - a * 2.0), a); uvRect = new Rect(0.25f, 0f, 0.5f, 0.25f); Widgets.DrawTexturePart(drawRect, uvRect, atlas); } - drawRect = new Rect(num, rect.height - num, rect.width - num * 2f, num); + drawRect = new Rect(a, rect.height - a, (float)(rect.width - a * 2.0), a); uvRect = new Rect(0.25f, 0.75f, 0.5f, 0.25f); Widgets.DrawTexturePart(drawRect, uvRect, atlas); - drawRect = new Rect(0f, num, num, rect.height - num * 2f); + drawRect = new Rect(0f, a, a, (float)(rect.height - a * 2.0)); if (!drawTop) { - drawRect.height += num; - drawRect.y -= num; + drawRect.height += a; + drawRect.y -= a; } uvRect = new Rect(0f, 0.25f, 0.25f, 0.5f); Widgets.DrawTexturePart(drawRect, uvRect, atlas); - drawRect = new Rect(rect.width - num, num, num, rect.height - num * 2f); + drawRect = new Rect(rect.width - a, a, a, (float)(rect.height - a * 2.0)); if (!drawTop) { - drawRect.height += num; - drawRect.y -= num; + drawRect.height += a; + drawRect.y -= a; } uvRect = new Rect(0.75f, 0.25f, 0.25f, 0.5f); Widgets.DrawTexturePart(drawRect, uvRect, atlas); @@ -1619,17 +1603,19 @@ public static Rect ToUVRect(this Rect r, Vector2 texSize) public static void DrawTexturePart(Rect drawRect, Rect uvRect, Texture2D tex) { - uvRect.y = 1f - uvRect.y - uvRect.height; + uvRect.y = (float)(1.0 - uvRect.y - uvRect.height); GUI.DrawTextureWithTexCoords(drawRect, tex, uvRect); } - public static void ScrollHorizontal(Rect outRect, ref Vector2 scrollPosition, Rect viewRect, float ScrollWheelSpeed = 20f) + public static void ScrollHorizontal(Rect outRect, ref Vector2 scrollPosition, Rect viewRect, float ScrollWheelSpeed = 20) { if (Event.current.type == EventType.ScrollWheel && Mouse.IsOver(outRect)) { - scrollPosition.x += Event.current.delta.y * ScrollWheelSpeed; + float x = scrollPosition.x; + Vector2 delta = Event.current.delta; + scrollPosition.x = x + delta.y * ScrollWheelSpeed; float num = 0f; - float num2 = viewRect.width - outRect.width + 16f; + float num2 = (float)(viewRect.width - outRect.width + 16.0); if (scrollPosition.x < num) { scrollPosition.x = num; @@ -1645,24 +1631,8 @@ public static void ScrollHorizontal(Rect outRect, ref Vector2 scrollPosition, Re public static void BeginScrollView(Rect outRect, ref Vector2 scrollPosition, Rect viewRect, bool showScrollbars = true) { Vector2 vector = scrollPosition; - Vector2 vector2; - if (showScrollbars) - { - vector2 = GUI.BeginScrollView(outRect, scrollPosition, viewRect); - } - else - { - vector2 = GUI.BeginScrollView(outRect, scrollPosition, viewRect, GUIStyle.none, GUIStyle.none); - } - Vector2 vector3; - if (Event.current.type == EventType.MouseDown) - { - vector3 = vector; - } - else - { - vector3 = vector2; - } + Vector2 vector2 = (!showScrollbars) ? GUI.BeginScrollView(outRect, scrollPosition, viewRect, GUIStyle.none, GUIStyle.none) : GUI.BeginScrollView(outRect, scrollPosition, viewRect); + Vector2 vector3 = (Event.current.type != 0) ? vector2 : vector; if (Event.current.type == EventType.ScrollWheel && Mouse.IsOver(outRect)) { vector3 += Event.current.delta * 40f; @@ -1711,15 +1681,12 @@ public static bool InfoCardButton(float x, float y, Thing thing) } return Widgets.InfoCardButton(x, y, thing.def.entityDefToBuild); } - else + if (Widgets.InfoCardButtonWorker(x, y)) { - if (Widgets.InfoCardButtonWorker(x, y)) - { - Find.WindowStack.Add(new Dialog_InfoCard(thing)); - return true; - } - return false; + Find.WindowStack.Add(new Dialog_InfoCard(thing)); + return true; } + return false; } public static bool InfoCardButton(float x, float y, Def def) @@ -1768,46 +1735,36 @@ public static void DrawTextureFitted(Rect outerRect, Texture2D tex, float scale) public static void DrawTextureFitted(Rect outerRect, Texture2D tex, float scale, Vector2 texProportions, Rect texCoords) { - if (Event.current.type != EventType.Repaint) - { - return; - } - Rect position = new Rect(0f, 0f, texProportions.x, texProportions.y); - float num; - if (position.width / position.height < outerRect.width / outerRect.height) - { - num = outerRect.height / position.height; - } - else + if (Event.current.type == EventType.Repaint) { - num = outerRect.width / position.width; + Rect position = new Rect(0f, 0f, texProportions.x, texProportions.y); + float num = (!(position.width / position.height < outerRect.width / outerRect.height)) ? (outerRect.width / position.width) : (outerRect.height / position.height); + num *= scale; + position.width *= num; + position.height *= num; + position.x = (float)(outerRect.x + outerRect.width / 2.0 - position.width / 2.0); + position.y = (float)(outerRect.y + outerRect.height / 2.0 - position.height / 2.0); + GUI.DrawTextureWithTexCoords(position, tex, texCoords); } - num *= scale; - position.width *= num; - position.height *= num; - position.x = outerRect.x + outerRect.width / 2f - position.width / 2f; - position.y = outerRect.y + outerRect.height / 2f - position.height / 2f; - GUI.DrawTextureWithTexCoords(position, tex, texCoords); } public static void DrawTextureRotated(Vector2 center, Texture2D tex, float angle, float scale = 1f) { float num = (float)tex.width * scale; float num2 = (float)tex.height * scale; - Rect rect = new Rect(center.x - num / 2f, center.y - num2 / 2f, num, num2); + Rect rect = new Rect((float)(center.x - num / 2.0), (float)(center.y - num2 / 2.0), num, num2); Widgets.DrawTextureRotated(rect, tex, angle); } public static void DrawTextureRotated(Rect rect, Texture2D tex, float angle) { - if (Event.current.type != EventType.Repaint) + if (Event.current.type == EventType.Repaint) { - return; + Matrix4x4 matrix = GUI.matrix; + UI.RotateAroundPivot(angle, rect.center); + GUI.DrawTexture(rect, tex); + GUI.matrix = matrix; } - Matrix4x4 matrix = GUI.matrix; - UI.RotateAroundPivot(angle, rect.center); - GUI.DrawTexture(rect, tex); - GUI.matrix = matrix; } } } diff --git a/Assembly-CSharp/Verse/WindManager.cs b/Assembly-CSharp/Verse/WindManager.cs index 43c6a74a4..bbdb32924 100644 --- a/Assembly-CSharp/Verse/WindManager.cs +++ b/Assembly-CSharp/Verse/WindManager.cs @@ -1,4 +1,3 @@ -using System; using System.Collections.Generic; using System.Text; using UnityEngine; @@ -70,13 +69,7 @@ private float BaseWindSpeedAt(int ticksAbs) public string DebugString() { - return string.Concat(new object[] - { - "WindSpeed: ", - this.WindSpeed, - "\nplantSwayHead: ", - this.plantSwayHead - }); + return "WindSpeed: " + this.WindSpeed + "\nplantSwayHead: " + this.plantSwayHead; } public void LogWindSpeeds() @@ -85,13 +78,7 @@ public void LogWindSpeeds() stringBuilder.AppendLine("Upcoming wind speeds:"); for (int i = 0; i < 72; i++) { - stringBuilder.AppendLine(string.Concat(new object[] - { - "Hour ", - i, - " - ", - this.BaseWindSpeedAt(Find.TickManager.TicksAbs + 2500 * i).ToString("F2") - })); + stringBuilder.AppendLine("Hour " + i + " - " + this.BaseWindSpeedAt(Find.TickManager.TicksAbs + 2500 * i).ToString("F2")); } Log.Message(stringBuilder.ToString()); } diff --git a/Assembly-CSharp/Verse/Window.cs b/Assembly-CSharp/Verse/Window.cs index 1c342aa53..985f8f714 100644 --- a/Assembly-CSharp/Verse/Window.cs +++ b/Assembly-CSharp/Verse/Window.cs @@ -163,7 +163,7 @@ public virtual void WindowOnGUI() } this.windowRect = this.windowRect.Rounded(); Rect winRect = this.windowRect.AtZero(); - this.windowRect = GUI.Window(this.ID, this.windowRect, delegate(int x) + this.windowRect = GUI.Window(this.ID, this.windowRect, (GUI.WindowFunction)delegate(int x) { Find.WindowStack.currentlyDrawnWindow = this; if (this.doWindowBackground) @@ -202,7 +202,7 @@ public virtual void WindowOnGUI() Rect rect = winRect.ContractedBy(this.Margin); if (!this.optionalTitle.NullOrEmpty()) { - rect.yMin += this.Margin + 25f; + rect.yMin += (float)(this.Margin + 25.0); } GUI.BeginGroup(rect); try @@ -211,13 +211,7 @@ public virtual void WindowOnGUI() } catch (Exception ex) { - Log.Error(string.Concat(new object[] - { - "Exception filling window for ", - this.GetType().ToString(), - ": ", - ex - })); + Log.Error("Exception filling window for " + base.GetType().ToString() + ": " + ex); } GUI.EndGroup(); if (this.resizeable && Event.current.type == EventType.Repaint) @@ -227,7 +221,14 @@ public virtual void WindowOnGUI() if (this.doCloseButton) { Text.Font = GameFont.Small; - Rect rect2 = new Rect(winRect.width / 2f - this.CloseButSize.x / 2f, winRect.height - 55f, this.CloseButSize.x, this.CloseButSize.y); + double num = winRect.width / 2.0; + Vector2 closeButSize = this.CloseButSize; + double x2 = num - closeButSize.x / 2.0; + double y = winRect.height - 55.0; + Vector2 closeButSize2 = this.CloseButSize; + float x3 = closeButSize2.x; + Vector2 closeButSize3 = this.CloseButSize; + Rect rect2 = new Rect((float)x2, (float)y, x3, closeButSize3.y); if (Widgets.ButtonText(rect2, "CloseButton".Translate(), true, false, true)) { this.Close(true); @@ -263,7 +264,16 @@ public virtual bool CausesMessageBackground() protected virtual void SetInitialSizeAndPosition() { - this.windowRect = new Rect(((float)UI.screenWidth - this.InitialSize.x) / 2f, ((float)UI.screenHeight - this.InitialSize.y) / 2f, this.InitialSize.x, this.InitialSize.y); + float num = (float)UI.screenWidth; + Vector2 initialSize = this.InitialSize; + double x = (num - initialSize.x) / 2.0; + float num2 = (float)UI.screenHeight; + Vector2 initialSize2 = this.InitialSize; + double y = (num2 - initialSize2.y) / 2.0; + Vector2 initialSize3 = this.InitialSize; + float x2 = initialSize3.x; + Vector2 initialSize4 = this.InitialSize; + this.windowRect = new Rect((float)x, (float)y, x2, initialSize4.y); this.windowRect = this.windowRect.Rounded(); } diff --git a/Assembly-CSharp/Verse/WindowLayer.cs b/Assembly-CSharp/Verse/WindowLayer.cs index b807ad4f3..67203b87b 100644 --- a/Assembly-CSharp/Verse/WindowLayer.cs +++ b/Assembly-CSharp/Verse/WindowLayer.cs @@ -1,12 +1,10 @@ -using System; - namespace Verse { public enum WindowLayer { - GameUI, - Dialog, - SubSuper, - Super + GameUI = 0, + Dialog = 1, + SubSuper = 2, + Super = 3 } } diff --git a/Assembly-CSharp/Verse/WindowResizer.cs b/Assembly-CSharp/Verse/WindowResizer.cs index 7a9e9953b..de8da6bf8 100644 --- a/Assembly-CSharp/Verse/WindowResizer.cs +++ b/Assembly-CSharp/Verse/WindowResizer.cs @@ -1,4 +1,3 @@ -using System; using UnityEngine; namespace Verse @@ -16,7 +15,7 @@ public class WindowResizer public Rect DoResizeControl(Rect winRect) { Vector2 mousePosition = Event.current.mousePosition; - Rect rect = new Rect(winRect.width - 24f, winRect.height - 24f, 24f, 24f); + Rect rect = new Rect((float)(winRect.width - 24.0), (float)(winRect.height - 24.0), 24f, 24f); if (Event.current.type == EventType.MouseDown && Mouse.IsOver(rect)) { this.isResizing = true; @@ -42,7 +41,7 @@ public Rect DoResizeControl(Rect winRect) } } Widgets.ButtonImage(rect, TexUI.WinExpandWidget); - return new Rect(winRect.x, winRect.y, (float)((int)winRect.width), (float)((int)winRect.height)); + return new Rect(winRect.x, winRect.y, (float)(int)winRect.width, (float)(int)winRect.height); } } } diff --git a/Assembly-CSharp/Verse/WindowStack.cs b/Assembly-CSharp/Verse/WindowStack.cs index 7976ba371..be611b20c 100644 --- a/Assembly-CSharp/Verse/WindowStack.cs +++ b/Assembly-CSharp/Verse/WindowStack.cs @@ -118,7 +118,7 @@ public float SecondsSinceClosedGameStartDialog { return 0f; } - if (this.timeGameStartDialogClosed < 0f) + if (this.timeGameStartDialogClosed < 0.0) { return 9999999f; } @@ -130,15 +130,7 @@ public bool MouseObscuredNow { get { - Vector3 v; - if (Event.current != null) - { - v = UI.GUIToScreenPoint(Event.current.mousePosition); - } - else - { - v = UI.MousePositionOnUIInverted; - } + Vector3 v = (Event.current == null) ? UI.MousePositionOnUIInverted : UI.GUIToScreenPoint(Event.current.mousePosition); return this.GetWindowAt(v) != this.currentlyDrawnWindow; } } @@ -177,19 +169,17 @@ public void WindowsUpdate() public void HandleEventsHighPriority() { - if (Event.current.type == EventType.MouseDown && this.GetWindowAt(UI.GUIToScreenPoint(Event.current.mousePosition)) == null) + if (Event.current.type == EventType.MouseDown && this.GetWindowAt(UI.GUIToScreenPoint(Event.current.mousePosition)) == null && this.CloseWindowsBecauseClicked(null)) { - bool flag = this.CloseWindowsBecauseClicked(null); - if (flag) - { - Event.current.Use(); - } + Event.current.Use(); } if (Event.current.type == EventType.KeyDown && Event.current.keyCode == KeyCode.Escape) { this.Notify_PressedEscape(); } - if ((Event.current.type == EventType.MouseDown || Event.current.type == EventType.KeyDown) && !this.GetsInput(null)) + if (Event.current.type != 0 && Event.current.type != EventType.KeyDown) + return; + if (!this.GetsInput(null)) { Event.current.Use(); } @@ -199,22 +189,22 @@ public void WindowStackOnGUI() { this.windowStackOnGUITmpList.Clear(); this.windowStackOnGUITmpList.AddRange(this.windows); - for (int i = this.windowStackOnGUITmpList.Count - 1; i >= 0; i--) + for (int num = this.windowStackOnGUITmpList.Count - 1; num >= 0; num--) { - this.windowStackOnGUITmpList[i].ExtraOnGUI(); + this.windowStackOnGUITmpList[num].ExtraOnGUI(); } this.UpdateImmediateWindowsList(); this.windowStackOnGUITmpList.Clear(); this.windowStackOnGUITmpList.AddRange(this.windows); - for (int j = 0; j < this.windowStackOnGUITmpList.Count; j++) + for (int i = 0; i < this.windowStackOnGUITmpList.Count; i++) { - if (this.windowStackOnGUITmpList[j].drawShadow) + if (this.windowStackOnGUITmpList[i].drawShadow) { - GUI.color = new Color(1f, 1f, 1f, this.windowStackOnGUITmpList[j].shadowAlpha); - Widgets.DrawShadowAround(this.windowStackOnGUITmpList[j].windowRect); + GUI.color = new Color(1f, 1f, 1f, this.windowStackOnGUITmpList[i].shadowAlpha); + Widgets.DrawShadowAround(this.windowStackOnGUITmpList[i].windowRect); GUI.color = Color.white; } - this.windowStackOnGUITmpList[j].WindowOnGUI(); + this.windowStackOnGUITmpList[i].WindowOnGUI(); } if (this.updateInternalWindowsOrderLater) { @@ -247,15 +237,20 @@ public void Notify_ManuallySetFocus(Window window) public void Notify_PressedEscape() { - for (int i = this.windows.Count - 1; i >= 0; i--) + int num = this.windows.Count - 1; + while (true) { - if (this.windows[i].closeOnEscapeKey && this.GetsInput(this.windows[i])) + if (num >= 0) { - Event.current.Use(); - this.TryRemove(this.windows[i], true); - break; + if (this.windows[num].closeOnEscapeKey && this.GetsInput(this.windows[num])) + break; + num--; + continue; } + return; } + Event.current.Use(); + this.TryRemove(this.windows[num], true); } public void Notify_GameStartDialogOpened() @@ -299,21 +294,21 @@ public WindowType WindowOfType() where WindowType : Window { if (this.windows[i] is WindowType) { - return (WindowType)((object)this.windows[i]); + return (WindowType)this.windows[i]; } } - return (WindowType)((object)null); + return (WindowType)null; } public bool GetsInput(Window window) { - for (int i = this.windows.Count - 1; i >= 0; i--) + for (int num = this.windows.Count - 1; num >= 0; num--) { - if (this.windows[i] == window) + if (this.windows[num] == window) { return true; } - if (this.windows[i].absorbInputAroundWindow) + if (this.windows[num].absorbInputAroundWindow) { return false; } @@ -334,37 +329,41 @@ public void Add(Window window) public void ImmediateWindow(int ID, Rect rect, WindowLayer layer, Action doWindowFunc, bool doBackground = true, bool absorbInputAroundWindow = false, float shadowAlpha = 1f) { - if (Event.current.type != EventType.Repaint) - { - return; - } - if (ID == 0) - { - Log.Warning("Used 0 as immediate window ID."); - return; - } - ID = -Math.Abs(ID); - bool flag = false; - for (int i = 0; i < this.windows.Count; i++) + if (Event.current.type == EventType.Repaint) { - if (this.windows[i].ID == ID) + if (ID == 0) { - ImmediateWindow immediateWindow = (ImmediateWindow)this.windows[i]; - immediateWindow.windowRect = rect; - immediateWindow.doWindowFunc = doWindowFunc; - immediateWindow.layer = layer; - immediateWindow.doWindowBackground = doBackground; - immediateWindow.absorbInputAroundWindow = absorbInputAroundWindow; - immediateWindow.shadowAlpha = shadowAlpha; - flag = true; - break; + Log.Warning("Used 0 as immediate window ID."); + } + else + { + ID = -Math.Abs(ID); + bool flag = false; + int num = 0; + while (num < this.windows.Count) + { + if (this.windows[num].ID != ID) + { + num++; + continue; + } + ImmediateWindow immediateWindow = (ImmediateWindow)this.windows[num]; + immediateWindow.windowRect = rect; + immediateWindow.doWindowFunc = doWindowFunc; + immediateWindow.layer = layer; + immediateWindow.doWindowBackground = doBackground; + immediateWindow.absorbInputAroundWindow = absorbInputAroundWindow; + immediateWindow.shadowAlpha = shadowAlpha; + flag = true; + break; + } + if (!flag) + { + this.AddNewImmediateWindow(ID, rect, layer, doWindowFunc, doBackground, absorbInputAroundWindow, shadowAlpha); + } + this.immediateWindowsRequests.Add(ID); } } - if (!flag) - { - this.AddNewImmediateWindow(ID, rect, layer, doWindowFunc, doBackground, absorbInputAroundWindow, shadowAlpha); - } - this.immediateWindowsRequests.Add(ID); } public bool TryRemove(Type windowType, bool doCloseSound = true) @@ -394,13 +393,16 @@ public bool TryRemoveAssignableFromType(Type windowType, bool doCloseSound = tru public bool TryRemove(Window window, bool doCloseSound = true) { bool flag = false; - for (int i = 0; i < this.windows.Count; i++) + int num = 0; + while (num < this.windows.Count) { - if (this.windows[i] == window) + if (this.windows[num] != window) { - flag = true; - break; + num++; + continue; } + flag = true; + break; } if (!flag) { @@ -430,11 +432,11 @@ public bool TryRemove(Window window, bool doCloseSound = true) public Window GetWindowAt(Vector2 pos) { - for (int i = this.windows.Count - 1; i >= 0; i--) + for (int num = this.windows.Count - 1; num >= 0; num--) { - if (this.windows[i].windowRect.Contains(pos)) + if (this.windows[num].windowRect.Contains(pos)) { - return this.windows[i]; + return this.windows[num]; } } return null; @@ -445,51 +447,55 @@ private void AddNewImmediateWindow(int ID, Rect rect, WindowLayer layer, Action if (ID >= 0) { Log.Error("Invalid immediate window ID."); - return; } - ImmediateWindow immediateWindow = new ImmediateWindow(); - immediateWindow.ID = ID; - immediateWindow.layer = layer; - immediateWindow.doWindowFunc = doWindowFunc; - immediateWindow.doWindowBackground = doBackground; - immediateWindow.absorbInputAroundWindow = absorbInputAroundWindow; - immediateWindow.shadowAlpha = shadowAlpha; - immediateWindow.PreOpen(); - immediateWindow.windowRect = rect; - this.InsertAtCorrectPositionInList(immediateWindow); - this.FocusAfterInsertIfShould(immediateWindow); - this.updateInternalWindowsOrderLater = true; - immediateWindow.PostOpen(); + else + { + ImmediateWindow immediateWindow = new ImmediateWindow(); + immediateWindow.ID = ID; + immediateWindow.layer = layer; + immediateWindow.doWindowFunc = doWindowFunc; + immediateWindow.doWindowBackground = doBackground; + immediateWindow.absorbInputAroundWindow = absorbInputAroundWindow; + immediateWindow.shadowAlpha = shadowAlpha; + immediateWindow.PreOpen(); + immediateWindow.windowRect = rect; + this.InsertAtCorrectPositionInList(immediateWindow); + this.FocusAfterInsertIfShould(immediateWindow); + this.updateInternalWindowsOrderLater = true; + immediateWindow.PostOpen(); + } } private void UpdateImmediateWindowsList() { - if (Event.current.type != EventType.Repaint) - { - return; - } - this.updateImmediateWindowsListTmpList.Clear(); - this.updateImmediateWindowsListTmpList.AddRange(this.windows); - for (int i = 0; i < this.updateImmediateWindowsListTmpList.Count; i++) + if (Event.current.type == EventType.Repaint) { - if (this.IsImmediateWindow(this.updateImmediateWindowsListTmpList[i])) + this.updateImmediateWindowsListTmpList.Clear(); + this.updateImmediateWindowsListTmpList.AddRange(this.windows); + for (int i = 0; i < this.updateImmediateWindowsListTmpList.Count; i++) { - bool flag = false; - for (int j = 0; j < this.immediateWindowsRequests.Count; j++) + if (this.IsImmediateWindow(this.updateImmediateWindowsListTmpList[i])) { - if (this.immediateWindowsRequests[j] == this.updateImmediateWindowsListTmpList[i].ID) + bool flag = false; + int num = 0; + while (num < this.immediateWindowsRequests.Count) { + if (this.immediateWindowsRequests[num] != this.updateImmediateWindowsListTmpList[i].ID) + { + num++; + continue; + } flag = true; break; } - } - if (!flag) - { - this.TryRemove(this.updateImmediateWindowsListTmpList[i], true); + if (!flag) + { + this.TryRemove(this.updateImmediateWindowsListTmpList[i], true); + } } } + this.immediateWindowsRequests.Clear(); } - this.immediateWindowsRequests.Clear(); } private void InsertAtCorrectPositionInList(Window window) @@ -508,22 +514,27 @@ private void InsertAtCorrectPositionInList(Window window) private void FocusAfterInsertIfShould(Window window) { - if (!window.focusWhenOpened) + if (window.focusWhenOpened) { - return; - } - for (int i = this.windows.Count - 1; i >= 0; i--) - { - if (this.windows[i] == window) - { - this.focusedWindow = this.windows[i]; - this.updateInternalWindowsOrderLater = true; - break; - } - if (this.windows[i] == this.focusedWindow) + int num = this.windows.Count - 1; + while (true) { - break; + if (num >= 0) + { + if (this.windows[num] == window) + { + break; + } + if (this.windows[num] != this.focusedWindow) + { + num--; + continue; + } + } + return; } + this.focusedWindow = this.windows[num]; + this.updateInternalWindowsOrderLater = true; } } @@ -562,17 +573,15 @@ private bool CloseWindowsBecauseClicked(Window clickedWindow) this.closeWindowsTmpList.Clear(); this.closeWindowsTmpList.AddRange(this.windows); bool result = false; - for (int i = this.closeWindowsTmpList.Count - 1; i >= 0; i--) + int num = this.closeWindowsTmpList.Count - 1; + while (num >= 0 && this.closeWindowsTmpList[num] != clickedWindow) { - if (this.closeWindowsTmpList[i] == clickedWindow) - { - break; - } - if (this.closeWindowsTmpList[i].closeOnClickedOutside) + if (this.closeWindowsTmpList[num].closeOnClickedOutside) { result = true; - this.TryRemove(this.closeWindowsTmpList[i], true); + this.TryRemove(this.closeWindowsTmpList[num], true); } + num--; } return result; } diff --git a/Assembly-CSharp/Verse/WorkTypeDef.cs b/Assembly-CSharp/Verse/WorkTypeDef.cs index e8712821a..d1a4c0928 100644 --- a/Assembly-CSharp/Verse/WorkTypeDef.cs +++ b/Assembly-CSharp/Verse/WorkTypeDef.cs @@ -1,7 +1,6 @@ using RimWorld; using System; using System.Collections.Generic; -using System.Diagnostics; using System.Linq; namespace Verse @@ -35,30 +34,31 @@ public class WorkTypeDef : Def [Unsaved] public List workGiversByPriority = new List(); - [DebuggerHidden] public override IEnumerable ConfigErrors() { - WorkTypeDef.c__Iterator1EB c__Iterator1EB = new WorkTypeDef.c__Iterator1EB(); - c__Iterator1EB.<>f__this = this; - WorkTypeDef.c__Iterator1EB expr_0E = c__Iterator1EB; - expr_0E.$PC = -2; - return expr_0E; + foreach (string item in base.ConfigErrors()) + { + yield return item; + } + if (this.naturalPriority >= 0 && this.naturalPriority <= 10000) + yield break; + yield return "naturalPriority is " + this.naturalPriority + ", but it must be between 0 and 10000"; } public override void ResolveReferences() { - foreach (WorkGiverDef current in from d in DefDatabase.AllDefs + foreach (WorkGiverDef item in from d in DefDatabase.AllDefs where d.workType == this orderby d.priorityInType descending select d) { - this.workGiversByPriority.Add(current); + this.workGiversByPriority.Add(item); } } public override int GetHashCode() { - return Gen.HashCombine(this.defName.GetHashCode(), this.gerundLabel); + return Gen.HashCombine(base.defName.GetHashCode(), this.gerundLabel); } } } diff --git a/Assembly-CSharp/Verse/WorkTypeDefsUtility.cs b/Assembly-CSharp/Verse/WorkTypeDefsUtility.cs index 4fc70d49e..f02a9f20d 100644 --- a/Assembly-CSharp/Verse/WorkTypeDefsUtility.cs +++ b/Assembly-CSharp/Verse/WorkTypeDefsUtility.cs @@ -21,70 +21,75 @@ public static string LabelTranslated(this WorkTags tags) switch (tags) { case WorkTags.None: + { return "WorkTagNone".Translate(); - case (WorkTags)1: - case (WorkTags)3: - IL_1C: - if (tags == WorkTags.Violent) - { - return "WorkTagViolent".Translate(); - } - if (tags == WorkTags.Caring) - { - return "WorkTagCaring".Translate(); - } - if (tags == WorkTags.Social) - { - return "WorkTagSocial".Translate(); - } - if (tags == WorkTags.Intellectual) - { - return "WorkTagIntellectual".Translate(); - } - if (tags == WorkTags.Animals) - { - return "WorkTagAnimals".Translate(); - } - if (tags == WorkTags.Artistic) - { - return "WorkTagArtistic".Translate(); - } - if (tags == WorkTags.Crafting) - { - return "WorkTagCrafting".Translate(); - } - if (tags == WorkTags.Cooking) - { - return "WorkTagCooking".Translate(); - } - if (tags == WorkTags.Firefighting) - { - return "WorkTagFirefighting".Translate(); - } - if (tags == WorkTags.Cleaning) - { - return "WorkTagCleaning".Translate(); - } - if (tags == WorkTags.Hauling) - { - return "WorkTagHauling".Translate(); - } - if (tags == WorkTags.PlantWork) - { - return "WorkTagPlantWork".Translate(); - } - if (tags != WorkTags.Mining) - { - Log.Error("Unknown or mixed worktags for naming: " + (int)tags); - return "Worktag"; - } - return "WorkTagMining".Translate(); + } + case WorkTags.Intellectual: + { + return "WorkTagIntellectual".Translate(); + } case WorkTags.ManualDumb: + { return "WorkTagManualDumb".Translate(); + } case WorkTags.ManualSkilled: + { return "WorkTagManualSkilled".Translate(); } - goto IL_1C; + case WorkTags.Violent: + { + return "WorkTagViolent".Translate(); + } + case WorkTags.Caring: + { + return "WorkTagCaring".Translate(); + } + case WorkTags.Social: + { + return "WorkTagSocial".Translate(); + } + case WorkTags.Animals: + { + return "WorkTagAnimals".Translate(); + } + case WorkTags.Artistic: + { + return "WorkTagArtistic".Translate(); + } + case WorkTags.Crafting: + { + return "WorkTagCrafting".Translate(); + } + case WorkTags.Cooking: + { + return "WorkTagCooking".Translate(); + } + case WorkTags.Firefighting: + { + return "WorkTagFirefighting".Translate(); + } + case WorkTags.Cleaning: + { + return "WorkTagCleaning".Translate(); + } + case WorkTags.Hauling: + { + return "WorkTagHauling".Translate(); + } + case WorkTags.PlantWork: + { + return "WorkTagPlantWork".Translate(); + } + case WorkTags.Mining: + { + return "WorkTagMining".Translate(); + } + default: + { + Log.Error("Unknown or mixed worktags for naming: " + (int)tags); + return "Worktag"; + } + } } public static bool OverlapsWithOnAnyWorkType(this WorkTags a, WorkTags b) @@ -93,7 +98,7 @@ public static bool OverlapsWithOnAnyWorkType(this WorkTags a, WorkTags b) for (int i = 0; i < allDefsListForReading.Count; i++) { WorkTypeDef workTypeDef = allDefsListForReading[i]; - if ((workTypeDef.workTags & a) != WorkTags.None && (workTypeDef.workTags & b) != WorkTags.None) + if ((((workTypeDef.workTags & a) != 0) ? (workTypeDef.workTags & b) : WorkTags.None) != 0) { return true; } diff --git a/Assembly-CSharp/Verse/WorldFloodFiller.cs b/Assembly-CSharp/Verse/WorldFloodFiller.cs index 017d08e7d..93b6cb965 100644 --- a/Assembly-CSharp/Verse/WorldFloodFiller.cs +++ b/Assembly-CSharp/Verse/WorldFloodFiller.cs @@ -14,7 +14,7 @@ public class WorldFloodFiller public void FloodFill(int rootTile, Predicate passCheck, Action processor, int maxTilesToProcess = 2147483647) { - this.FloodFill(rootTile, passCheck, delegate(int tile, int traversalDistance) + this.FloodFill(rootTile, passCheck, (Func)delegate(int tile, int traversalDistance) { processor(tile); return false; @@ -23,7 +23,7 @@ public void FloodFill(int rootTile, Predicate passCheck, Action proces public void FloodFill(int rootTile, Predicate passCheck, Action processor, int maxTilesToProcess = 2147483647) { - this.FloodFill(rootTile, passCheck, delegate(int tile, int traversalDistance) + this.FloodFill(rootTile, passCheck, (Func)delegate(int tile, int traversalDistance) { processor(tile, traversalDistance); return false; @@ -32,7 +32,7 @@ public void FloodFill(int rootTile, Predicate passCheck, Action p public void FloodFill(int rootTile, Predicate passCheck, Predicate processor, int maxTilesToProcess = 2147483647) { - this.FloodFill(rootTile, passCheck, (int tile, int traversalDistance) => processor(tile), maxTilesToProcess); + this.FloodFill(rootTile, passCheck, (Func)((int tile, int traversalDistance) => processor(tile)), maxTilesToProcess); } public void FloodFill(int rootTile, Predicate passCheck, Func processor, int maxTilesToProcess = 2147483647) @@ -40,75 +40,79 @@ public void FloodFill(int rootTile, Predicate passCheck, Func tileIDToNeighbors_offsets = worldGrid.tileIDToNeighbors_offsets; - List tileIDToNeighbors_values = worldGrid.tileIDToNeighbors_values; - int num2 = 0; - this.visited.Add(rootTile); - this.traversalDistance[rootTile] = 0; - this.openSet.Clear(); - this.openSet.Enqueue(rootTile); - while (this.openSet.Count > 0) - { - int num3 = this.openSet.Dequeue(); - int num4 = this.traversalDistance[num3]; - if (processor(num3, num4)) + ProfilerThreadCheck.BeginSample("WorldFloodFill"); + this.ClearVisited(); + if (!passCheck(rootTile)) { - break; - } - num2++; - if (num2 == maxTilesToProcess) - { - break; + ProfilerThreadCheck.EndSample(); } - int num5 = (num3 + 1 >= tileIDToNeighbors_offsets.Count) ? tileIDToNeighbors_values.Count : tileIDToNeighbors_offsets[num3 + 1]; - for (int j = tileIDToNeighbors_offsets[num3]; j < num5; j++) + else { - int num6 = tileIDToNeighbors_values[j]; - if (this.traversalDistance[num6] == -1 && passCheck(num6)) + int tilesCount; + int num = tilesCount = Find.WorldGrid.TilesCount; + if (this.traversalDistance.Count != num) { - this.visited.Add(num6); - this.openSet.Enqueue(num6); - this.traversalDistance[num6] = num4 + 1; + this.traversalDistance.Clear(); + for (int num2 = 0; num2 < num; num2++) + { + this.traversalDistance.Add(-1); + } + } + WorldGrid worldGrid = Find.WorldGrid; + List tileIDToNeighbors_offsets = worldGrid.tileIDToNeighbors_offsets; + List tileIDToNeighbors_values = worldGrid.tileIDToNeighbors_values; + int num3 = 0; + this.visited.Add(rootTile); + this.traversalDistance[rootTile] = 0; + this.openSet.Clear(); + this.openSet.Enqueue(rootTile); + while (this.openSet.Count > 0) + { + int num4 = this.openSet.Dequeue(); + int num5 = this.traversalDistance[num4]; + if (!processor(num4, num5)) + { + num3++; + if (num3 != maxTilesToProcess) + { + int num6 = (num4 + 1 >= tileIDToNeighbors_offsets.Count) ? tileIDToNeighbors_values.Count : tileIDToNeighbors_offsets[num4 + 1]; + for (int num7 = tileIDToNeighbors_offsets[num4]; num7 < num6; num7++) + { + int num8 = tileIDToNeighbors_values[num7]; + if (this.traversalDistance[num8] == -1 && passCheck(num8)) + { + this.visited.Add(num8); + this.openSet.Enqueue(num8); + this.traversalDistance[num8] = num5 + 1; + } + } + if (this.openSet.Count > tilesCount) + { + Log.Error("Overflow on world flood fill (>" + tilesCount + " cells). Make sure we're not flooding over the same area after we check it."); + ProfilerThreadCheck.EndSample(); + return; + } + continue; + } + } + break; } - } - if (this.openSet.Count > num) - { - Log.Error("Overflow on world flood fill (>" + num + " cells). Make sure we're not flooding over the same area after we check it."); ProfilerThreadCheck.EndSample(); - return; } } - ProfilerThreadCheck.EndSample(); } private void ClearVisited() { - int i = 0; + int num = 0; int count = this.visited.Count; - while (i < count) + while (num < count) { - this.traversalDistance[this.visited[i]] = -1; - i++; + this.traversalDistance[this.visited[num]] = -1; + num++; } this.visited.Clear(); this.openSet.Clear(); diff --git a/Assembly-CSharp/Verse/WorldGenStep.cs b/Assembly-CSharp/Verse/WorldGenStep.cs index d9a1ccc67..3be2e9c01 100644 --- a/Assembly-CSharp/Verse/WorldGenStep.cs +++ b/Assembly-CSharp/Verse/WorldGenStep.cs @@ -1,5 +1,3 @@ -using System; - namespace Verse { public abstract class WorldGenStep diff --git a/Assembly-CSharp/Verse/WorldGenStepDef.cs b/Assembly-CSharp/Verse/WorldGenStepDef.cs index f6825792b..b9c42a95f 100644 --- a/Assembly-CSharp/Verse/WorldGenStepDef.cs +++ b/Assembly-CSharp/Verse/WorldGenStepDef.cs @@ -1,5 +1,3 @@ -using System; - namespace Verse { public class WorldGenStepDef : Def diff --git a/Assembly-CSharp/Verse/XmlContainer.cs b/Assembly-CSharp/Verse/XmlContainer.cs index cc1334882..2f0969457 100644 --- a/Assembly-CSharp/Verse/XmlContainer.cs +++ b/Assembly-CSharp/Verse/XmlContainer.cs @@ -1,4 +1,3 @@ -using System; using System.Xml; namespace Verse diff --git a/Assembly-CSharp/Verse/XmlInheritance.cs b/Assembly-CSharp/Verse/XmlInheritance.cs index a159d5a1b..873e3af7b 100644 --- a/Assembly-CSharp/Verse/XmlInheritance.cs +++ b/Assembly-CSharp/Verse/XmlInheritance.cs @@ -15,16 +15,16 @@ private class XmlInheritanceNode public ModContentPack mod; - public XmlInheritance.XmlInheritanceNode parent; + public XmlInheritanceNode parent; - public List children = new List(); + public List children = new List(); } - private static Dictionary resolvedNodes = new Dictionary(); + private static Dictionary resolvedNodes = new Dictionary(); - private static List unresolvedNodes = new List(); + private static List unresolvedNodes = new List(); - private static Dictionary> nodesByName = new Dictionary>(); + private static Dictionary> nodesByName = new Dictionary>(); private static readonly string NameAttributeName = "Name"; @@ -34,16 +34,15 @@ private class XmlInheritanceNode public static void TryRegisterAllFrom(LoadableXmlAsset xmlAsset, ModContentPack mod) { - if (xmlAsset.xmlDoc == null) + if (xmlAsset.xmlDoc != null) { - return; - } - XmlNodeList childNodes = xmlAsset.xmlDoc.DocumentElement.ChildNodes; - for (int i = 0; i < childNodes.Count; i++) - { - if (childNodes[i].NodeType == XmlNodeType.Element) + XmlNodeList childNodes = xmlAsset.xmlDoc.DocumentElement.ChildNodes; + for (int i = 0; i < childNodes.Count; i++) { - XmlInheritance.TryRegister(childNodes[i], mod); + if (childNodes[i].NodeType == XmlNodeType.Element) + { + XmlInheritance.TryRegister(childNodes[i], mod); + } } } } @@ -53,36 +52,17 @@ public static void TryRegister(XmlNode node, ModContentPack mod) XmlAttribute xmlAttribute = node.Attributes[XmlInheritance.NameAttributeName]; XmlAttribute xmlAttribute2 = node.Attributes[XmlInheritance.ParentNameAttributeName]; if (xmlAttribute == null && xmlAttribute2 == null) - { return; - } - List list = null; + List list = null; if (xmlAttribute != null && XmlInheritance.nodesByName.TryGetValue(xmlAttribute.Value, out list)) { for (int i = 0; i < list.Count; i++) { if (list[i].mod == mod) - { - if (mod == null) - { - Log.Error("XML error: Could not register node named \"" + xmlAttribute.Value + "\" because this name is already used."); - } - else - { - Log.Error(string.Concat(new string[] - { - "XML error: Could not register node named \"", - xmlAttribute.Value, - "\" in mod ", - mod.ToString(), - " because this name is already used in this mod." - })); - } - return; - } + goto IL_0067; } } - XmlInheritance.XmlInheritanceNode xmlInheritanceNode = new XmlInheritance.XmlInheritanceNode(); + XmlInheritanceNode xmlInheritanceNode = new XmlInheritanceNode(); xmlInheritanceNode.xmlNode = node; xmlInheritanceNode.mod = mod; XmlInheritance.unresolvedNodes.Add(xmlInheritanceNode); @@ -94,11 +74,21 @@ public static void TryRegister(XmlNode node, ModContentPack mod) } else { - list = new List(); + list = new List(); list.Add(xmlInheritanceNode); XmlInheritance.nodesByName.Add(xmlAttribute.Value, list); } } + return; + IL_0067: + if (mod == null) + { + Log.Error("XML error: Could not register node named \"" + xmlAttribute.Value + "\" because this name is already used."); + } + else + { + Log.Error("XML error: Could not register node named \"" + xmlAttribute.Value + "\" in mod " + mod.ToString() + " because this name is already used in this mod."); + } } public static void Resolve() @@ -111,12 +101,12 @@ public static XmlNode GetResolvedNodeFor(XmlNode originalNode) { if (originalNode.Attributes[XmlInheritance.ParentNameAttributeName] != null) { - XmlInheritance.XmlInheritanceNode xmlInheritanceNode; + XmlInheritanceNode xmlInheritanceNode = default(XmlInheritanceNode); if (XmlInheritance.resolvedNodes.TryGetValue(originalNode, out xmlInheritanceNode)) { return xmlInheritanceNode.resolvedXmlNode; } - if (XmlInheritance.unresolvedNodes.Any((XmlInheritance.XmlInheritanceNode x) => x.xmlNode == originalNode)) + if (XmlInheritance.unresolvedNodes.Any((Predicate)((XmlInheritanceNode x) => x.xmlNode == originalNode))) { Log.Error("XML error: XML node \"" + originalNode.Name + "\" has not been resolved yet. There's probably a Resolve() call missing somewhere."); } @@ -153,9 +143,9 @@ private static void ResolveParentsAndChildNodesLinks() private static void ResolveXmlNodes() { - List list = (from x in XmlInheritance.unresolvedNodes + List list = (from x in XmlInheritance.unresolvedNodes where x.parent == null || x.parent.resolvedXmlNode != null - select x).ToList(); + select x).ToList(); for (int i = 0; i < list.Count; i++) { XmlInheritance.ResolveXmlNodesRecursively(list[i]); @@ -174,127 +164,122 @@ private static void ResolveXmlNodes() XmlInheritance.unresolvedNodes.Clear(); } - private static void ResolveXmlNodesRecursively(XmlInheritance.XmlInheritanceNode node) + private static void ResolveXmlNodesRecursively(XmlInheritanceNode node) { if (node.resolvedXmlNode != null) { Log.Error("XML error: Cyclic inheritance hierarchy detected for node \"" + node.xmlNode.Name + "\". Full node: " + node.xmlNode.OuterXml); - return; } - XmlInheritance.ResolveXmlNodeFor(node); - for (int i = 0; i < node.children.Count; i++) + else { - XmlInheritance.ResolveXmlNodesRecursively(node.children[i]); + XmlInheritance.ResolveXmlNodeFor(node); + for (int i = 0; i < node.children.Count; i++) + { + XmlInheritance.ResolveXmlNodesRecursively(node.children[i]); + } } } - private static XmlInheritance.XmlInheritanceNode GetBestParentFor(XmlInheritance.XmlInheritanceNode node, string parentName) + private static XmlInheritanceNode GetBestParentFor(XmlInheritanceNode node, string parentName) { - XmlInheritance.XmlInheritanceNode xmlInheritanceNode = null; - List list; + XmlInheritanceNode xmlInheritanceNode = null; + List list = default(List); if (XmlInheritance.nodesByName.TryGetValue(parentName, out list)) { if (node.mod == null) { - for (int i = 0; i < list.Count; i++) + int num = 0; + while (num < list.Count) { - if (list[i].mod == null) + if (list[num].mod != null) { - xmlInheritanceNode = list[i]; - break; + num++; + continue; } + xmlInheritanceNode = list[num]; + break; } if (xmlInheritanceNode == null) { - for (int j = 0; j < list.Count; j++) + for (int i = 0; i < list.Count; i++) { - if (xmlInheritanceNode == null || list[j].mod.loadOrder < xmlInheritanceNode.mod.loadOrder) + if (xmlInheritanceNode == null || list[i].mod.loadOrder < xmlInheritanceNode.mod.loadOrder) { - xmlInheritanceNode = list[j]; + xmlInheritanceNode = list[i]; } } } } else { - for (int k = 0; k < list.Count; k++) + for (int j = 0; j < list.Count; j++) { - if (list[k].mod != null) + if (list[j].mod != null && list[j].mod.loadOrder <= node.mod.loadOrder && (xmlInheritanceNode == null || list[j].mod.loadOrder > xmlInheritanceNode.mod.loadOrder)) { - if (list[k].mod.loadOrder <= node.mod.loadOrder && (xmlInheritanceNode == null || list[k].mod.loadOrder > xmlInheritanceNode.mod.loadOrder)) - { - xmlInheritanceNode = list[k]; - } + xmlInheritanceNode = list[j]; } } if (xmlInheritanceNode == null) { - for (int l = 0; l < list.Count; l++) + int num2 = 0; + while (num2 < list.Count) { - if (list[l].mod == null) + if (list[num2].mod != null) { - xmlInheritanceNode = list[l]; - break; + num2++; + continue; } + xmlInheritanceNode = list[num2]; + break; } } } } if (xmlInheritanceNode == null) { - Log.Error(string.Concat(new string[] - { - "XML error: Could not find parent node named \"", - parentName, - "\" for node \"", - node.xmlNode.Name, - "\". Full node: ", - node.xmlNode.OuterXml - })); + Log.Error("XML error: Could not find parent node named \"" + parentName + "\" for node \"" + node.xmlNode.Name + "\". Full node: " + node.xmlNode.OuterXml); return null; } return xmlInheritanceNode; } - private static void ResolveXmlNodeFor(XmlInheritance.XmlInheritanceNode node) + private static void ResolveXmlNodeFor(XmlInheritanceNode node) { if (node.parent == null) { node.resolvedXmlNode = node.xmlNode; - return; } - if (node.parent.resolvedXmlNode == null) + else if (node.parent.resolvedXmlNode == null) { Log.Error("XML error: Internal error. Tried to resolve node whose parent has not been resolved yet. This means that this method was called in incorrect order."); node.resolvedXmlNode = node.xmlNode; - return; } - XmlInheritance.CheckForDuplicateNodes(node.xmlNode); - XmlNode xmlNode = node.parent.resolvedXmlNode.CloneNode(true); - xmlNode.Attributes.RemoveAll(); - XmlAttributeCollection attributes = node.xmlNode.Attributes; - for (int i = 0; i < attributes.Count; i++) + else { - if (!(attributes[i].Name == XmlInheritance.NameAttributeName) && !(attributes[i].Name == XmlInheritance.ParentNameAttributeName)) + XmlInheritance.CheckForDuplicateNodes(node.xmlNode); + XmlNode xmlNode = node.parent.resolvedXmlNode.CloneNode(true); + xmlNode.Attributes.RemoveAll(); + XmlAttributeCollection attributes = node.xmlNode.Attributes; + for (int i = 0; i < attributes.Count; i++) { - XmlAttribute node2 = (XmlAttribute)xmlNode.OwnerDocument.ImportNode(attributes[i], true); - xmlNode.Attributes.Append(node2); + if (!(attributes[i].Name == XmlInheritance.NameAttributeName) && !(attributes[i].Name == XmlInheritance.ParentNameAttributeName)) + { + XmlAttribute node2 = (XmlAttribute)xmlNode.OwnerDocument.ImportNode(attributes[i], true); + xmlNode.Attributes.Append(node2); + } } - } - XmlAttributeCollection attributes2 = node.parent.resolvedXmlNode.Attributes; - for (int j = 0; j < attributes2.Count; j++) - { - if (!(attributes2[j].Name == XmlInheritance.NameAttributeName) && !(attributes2[j].Name == XmlInheritance.ParentNameAttributeName)) + XmlAttributeCollection attributes2 = node.parent.resolvedXmlNode.Attributes; + for (int j = 0; j < attributes2.Count; j++) { - if (xmlNode.Attributes[attributes2[j].Name] == null) + if (!(attributes2[j].Name == XmlInheritance.NameAttributeName) && !(attributes2[j].Name == XmlInheritance.ParentNameAttributeName) && xmlNode.Attributes[attributes2[j].Name] == null) { XmlAttribute node3 = (XmlAttribute)xmlNode.OwnerDocument.ImportNode(attributes2[j], true); xmlNode.Attributes.Append(node3); } } + XmlInheritance.RecursiveNodeCopyOverwriteElements(node.xmlNode, xmlNode); + node.resolvedXmlNode = xmlNode; } - XmlInheritance.RecursiveNodeCopyOverwriteElements(node.xmlNode, xmlNode); - node.resolvedXmlNode = xmlNode; } private static void RecursiveNodeCopyOverwriteElements(XmlNode source, XmlNode target) @@ -317,23 +302,23 @@ private static void RecursiveNodeCopyOverwriteElements(XmlNode source, XmlNode t } else { - foreach (XmlNode xmlNode in source) + foreach (XmlNode item in source) { - if (xmlNode.Name == "li") + if (item.Name == "li") { - XmlNode newChild2 = target.OwnerDocument.ImportNode(xmlNode, true); + XmlNode newChild2 = target.OwnerDocument.ImportNode(item, true); target.AppendChild(newChild2); } else { - XmlElement xmlElement = target[xmlNode.Name]; + XmlElement xmlElement = target[item.Name]; if (xmlElement != null) { - XmlInheritance.RecursiveNodeCopyOverwriteElements(xmlNode, xmlElement); + XmlInheritance.RecursiveNodeCopyOverwriteElements(item, xmlElement); } else { - XmlNode newChild3 = target.OwnerDocument.ImportNode(xmlNode, true); + XmlNode newChild3 = target.OwnerDocument.ImportNode(item, true); target.AppendChild(newChild3); } } @@ -344,17 +329,17 @@ private static void RecursiveNodeCopyOverwriteElements(XmlNode source, XmlNode t private static void CheckForDuplicateNodes(XmlNode originalNode) { XmlInheritance.tempUsedNodeNames.Clear(); - foreach (XmlNode xmlNode in originalNode.ChildNodes) + foreach (XmlNode childNode in originalNode.ChildNodes) { - if (!(xmlNode.Name == "li")) + if (!(childNode.Name == "li")) { - if (XmlInheritance.tempUsedNodeNames.Contains(xmlNode.Name)) + if (XmlInheritance.tempUsedNodeNames.Contains(childNode.Name)) { - Log.Error("XML error: Duplicate XML node name " + xmlNode.Name + " in this XML block: " + originalNode.OuterXml); + Log.Error("XML error: Duplicate XML node name " + childNode.Name + " in this XML block: " + originalNode.OuterXml); } else { - XmlInheritance.tempUsedNodeNames.Add(xmlNode.Name); + XmlInheritance.tempUsedNodeNames.Add(childNode.Name); } } } diff --git a/Assembly-CSharp/Verse/Zone.cs b/Assembly-CSharp/Verse/Zone.cs index 299b2c898..4e6ff4c77 100644 --- a/Assembly-CSharp/Verse/Zone.cs +++ b/Assembly-CSharp/Verse/Zone.cs @@ -1,7 +1,6 @@ using RimWorld; using System; using System.Collections.Generic; -using System.Diagnostics; using UnityEngine; using Verse.Sound; @@ -45,7 +44,7 @@ public Material Material { get { - if (this.materialInt == null) + if ((UnityEngine.Object)this.materialInt == (UnityEngine.Object)null) { this.materialInt = SolidColorMaterials.SimpleSolidColorMaterial(this.color, false); this.materialInt.renderQueue = 3600; @@ -60,7 +59,7 @@ public List Cells { if (!this.cellsShuffled) { - this.cells.Shuffle(); + this.cells.Shuffle(); this.cellsShuffled = true; } return this.cells; @@ -71,11 +70,15 @@ public IEnumerable AllContainedThings { get { - Zone.<>c__IteratorB8 <>c__IteratorB = new Zone.<>c__IteratorB8(); - <>c__IteratorB.<>f__this = this; - Zone.<>c__IteratorB8 expr_0E = <>c__IteratorB; - expr_0E.$PC = -2; - return expr_0E; + ThingGrid grids = this.Map.thingGrid; + for (int j = 0; j < this.cells.Count; j++) + { + List thingList = grids.ThingsListAt(this.cells[j]); + for (int i = 0; i < thingList.Count; i++) + { + yield return thingList[i]; + } + } } } @@ -86,13 +89,16 @@ public bool ContainsStaticFire if (Find.TickManager.TicksGame > this.lastStaticFireCheckTick + 1000) { this.lastStaticFireCheckResult = false; - for (int i = 0; i < this.cells.Count; i++) + int num = 0; + while (num < this.cells.Count) { - if (this.cells[i].ContainsStaticFire(this.Map)) + if (!this.cells[num].ContainsStaticFire(this.Map)) { - this.lastStaticFireCheckResult = true; - break; + num++; + continue; } + this.lastStaticFireCheckResult = true; + break; } } return this.lastStaticFireCheckResult; @@ -124,17 +130,17 @@ public Zone(string baseName, ZoneManager zoneManager) zoneManager.RegisterZone(this); } - [DebuggerHidden] public IEnumerator GetEnumerator() { - Zone.c__IteratorB7 c__IteratorB = new Zone.c__IteratorB7(); - c__IteratorB.<>f__this = this; - return c__IteratorB; + for (int i = 0; i < this.cells.Count; i++) + { + yield return this.cells[i]; + } } public virtual void ExposeData() { - Scribe_Values.Look(ref this.label, "label", null, false); + Scribe_Values.Look(ref this.label, "label", (string)null, false); Scribe_Values.Look(ref this.color, "color", default(Color), false); Scribe_Values.Look(ref this.hidden, "hidden", false, false); Scribe_Collections.Look(ref this.cells, "cells", LookMode.Undefined, new object[0]); @@ -144,52 +150,44 @@ public virtual void AddCell(IntVec3 c) { if (this.cells.Contains(c)) { - Log.Error(string.Concat(new object[] - { - "Adding cell to zone which already has it. c=", - c, - ", zone=", - this - })); - return; + Log.Error("Adding cell to zone which already has it. c=" + c + ", zone=" + this); } - List list = this.Map.thingGrid.ThingsListAt(c); - for (int i = 0; i < list.Count; i++) + else { - Thing thing = list[i]; - if (!thing.def.CanOverlapZones) + List list = this.Map.thingGrid.ThingsListAt(c); + for (int i = 0; i < list.Count; i++) { - Log.Error("Added zone over zone-incompatible thing " + thing); - return; + Thing thing = list[i]; + if (!thing.def.CanOverlapZones) + { + Log.Error("Added zone over zone-incompatible thing " + thing); + return; + } } + this.cells.Add(c); + this.zoneManager.AddZoneGridCell(this, c); + this.Map.mapDrawer.MapMeshDirty(c, MapMeshFlag.Zone); + AutoHomeAreaMaker.Notify_ZoneCellAdded(c, this); + this.cellsShuffled = false; } - this.cells.Add(c); - this.zoneManager.AddZoneGridCell(this, c); - this.Map.mapDrawer.MapMeshDirty(c, MapMeshFlag.Zone); - AutoHomeAreaMaker.Notify_ZoneCellAdded(c, this); - this.cellsShuffled = false; } public virtual void RemoveCell(IntVec3 c) { if (!this.cells.Contains(c)) { - Log.Error(string.Concat(new object[] - { - "Cannot remove cell from zone which doesn't have it. c=", - c, - ", zone=", - this - })); - return; + Log.Error("Cannot remove cell from zone which doesn't have it. c=" + c + ", zone=" + this); } - this.cells.Remove(c); - this.zoneManager.ClearZoneGridCell(c); - this.Map.mapDrawer.MapMeshDirty(c, MapMeshFlag.Zone); - this.cellsShuffled = false; - if (this.cells.Count == 0) + else { - this.Deregister(); + this.cells.Remove(c); + this.zoneManager.ClearZoneGridCell(c); + this.Map.mapDrawer.MapMeshDirty(c, MapMeshFlag.Zone); + this.cellsShuffled = false; + if (this.cells.Count == 0) + { + this.Deregister(); + } } } @@ -232,66 +230,110 @@ public virtual string GetInspectString() return string.Empty; } - [DebuggerHidden] public virtual IEnumerable GetInspectTabs() { - Zone.c__IteratorB9 c__IteratorB = new Zone.c__IteratorB9(); - Zone.c__IteratorB9 expr_07 = c__IteratorB; - expr_07.$PC = -2; - return expr_07; + yield break; } - [DebuggerHidden] public virtual IEnumerable GetGizmos() { - Zone.c__IteratorBA c__IteratorBA = new Zone.c__IteratorBA(); - c__IteratorBA.<>f__this = this; - Zone.c__IteratorBA expr_0E = c__IteratorBA; - expr_0E.$PC = -2; - return expr_0E; - } - - public void CheckContiguous() - { - if (this.cells.Count == 0) + yield return (Gizmo)new Command_Action { - return; - } - if (Zone.extantGrid == null) - { - Zone.extantGrid = new BoolGrid(this.Map); - } - else - { - Zone.extantGrid.ClearAndResizeTo(this.Map); - } - if (Zone.foundGrid == null) - { - Zone.foundGrid = new BoolGrid(this.Map); - } - else - { - Zone.foundGrid.ClearAndResizeTo(this.Map); - } - for (int i = 0; i < this.cells.Count; i++) + icon = ContentFinder.Get("UI/Commands/RenameZone", true), + defaultLabel = "CommandRenameZoneLabel".Translate(), + defaultDesc = "CommandRenameZoneDesc".Translate(), + action = (Action)delegate + { + Find.WindowStack.Add(new Dialog_RenameZone(((_003CGetGizmos_003Ec__IteratorBA)/*Error near IL_007a: stateMachine*/)._003C_003Ef__this)); + }, + hotKey = KeyBindingDefOf.Misc1 + }; + yield return (Gizmo)new Command_Toggle { - Zone.extantGrid.Set(this.cells[i], true); - } - Predicate passCheck = (IntVec3 c) => Zone.extantGrid[c] && !Zone.foundGrid[c]; - int numFound = 0; - Action processor = delegate(IntVec3 c) + icon = ContentFinder.Get("UI/Commands/HideZone", true), + defaultLabel = ((!this.hidden) ? "CommandHideZoneLabel".Translate() : "CommandUnhideZoneLabel".Translate()), + defaultDesc = "CommandHideZoneDesc".Translate(), + isActive = (Func)(() => ((_003CGetGizmos_003Ec__IteratorBA)/*Error near IL_0123: stateMachine*/)._003C_003Ef__this.hidden), + toggleAction = (Action)delegate + { + ((_003CGetGizmos_003Ec__IteratorBA)/*Error near IL_013a: stateMachine*/)._003C_003Ef__this.hidden = !((_003CGetGizmos_003Ec__IteratorBA)/*Error near IL_013a: stateMachine*/)._003C_003Ef__this.hidden; + List.Enumerator enumerator = ((_003CGetGizmos_003Ec__IteratorBA)/*Error near IL_013a: stateMachine*/)._003C_003Ef__this.Cells.GetEnumerator(); + try + { + while (enumerator.MoveNext()) + { + IntVec3 current = enumerator.Current; + ((_003CGetGizmos_003Ec__IteratorBA)/*Error near IL_013a: stateMachine*/)._003C_003Ef__this.Map.mapDrawer.MapMeshDirty(current, MapMeshFlag.Zone); + } + } + finally + { + ((IDisposable)(object)enumerator).Dispose(); + } + }, + hotKey = KeyBindingDefOf.Misc2 + }; + yield return (Gizmo)new Command_Action { - Zone.foundGrid.Set(c, true); - numFound++; + icon = ContentFinder.Get("UI/Buttons/Delete", true), + defaultLabel = "CommandDeleteZoneLabel".Translate(), + defaultDesc = "CommandDeleteZoneDesc".Translate(), + action = new Action(this.Delete), + hotKey = KeyBindingDefOf.Misc3 }; - this.Map.floodFiller.FloodFill(this.cells[0], passCheck, processor, false); - if (numFound < this.cells.Count) + } + + public void CheckContiguous() + { + if (this.cells.Count != 0) { - foreach (IntVec3 current in this.Map.AllCells) + if (Zone.extantGrid == null) + { + Zone.extantGrid = new BoolGrid(this.Map); + } + else { - if (Zone.extantGrid[current] && !Zone.foundGrid[current]) + Zone.extantGrid.ClearAndResizeTo(this.Map); + } + if (Zone.foundGrid == null) + { + Zone.foundGrid = new BoolGrid(this.Map); + } + else + { + Zone.foundGrid.ClearAndResizeTo(this.Map); + } + for (int i = 0; i < this.cells.Count; i++) + { + Zone.extantGrid.Set(this.cells[i], true); + } + Predicate passCheck = (Predicate)delegate(IntVec3 c) + { + if (!Zone.extantGrid[c]) { - this.RemoveCell(current); + return false; + } + if (Zone.foundGrid[c]) + { + return false; + } + return true; + }; + int numFound = 0; + Action processor = (Action)delegate(IntVec3 c) + { + Zone.foundGrid.Set(c, true); + numFound++; + }; + this.Map.floodFiller.FloodFill(this.cells[0], passCheck, processor, false); + if (numFound < this.cells.Count) + { + foreach (IntVec3 allCell in this.Map.AllCells) + { + if (Zone.extantGrid[allCell] && !Zone.foundGrid[allCell]) + { + this.RemoveCell(allCell); + } } } } diff --git a/Assembly-CSharp/Verse/ZoneColorUtility.cs b/Assembly-CSharp/Verse/ZoneColorUtility.cs index 061790ebc..85ebf9eff 100644 --- a/Assembly-CSharp/Verse/ZoneColorUtility.cs +++ b/Assembly-CSharp/Verse/ZoneColorUtility.cs @@ -1,6 +1,4 @@ -using System; using System.Collections.Generic; -using System.Diagnostics; using UnityEngine; namespace Verse @@ -23,13 +21,15 @@ static ZoneColorUtility() ZoneColorUtility.storageZoneColors = new List(); ZoneColorUtility.nextGrowingZoneColorIndex = 0; ZoneColorUtility.nextStorageZoneColorIndex = 0; - foreach (Color current in ZoneColorUtility.GrowingZoneColors()) + foreach (Color item3 in ZoneColorUtility.GrowingZoneColors()) { + Color current = item3; Color item = new Color(current.r, current.g, current.b, 0.09f); ZoneColorUtility.growingZoneColors.Add(item); } - foreach (Color current2 in ZoneColorUtility.StorageZoneColors()) + foreach (Color item4 in ZoneColorUtility.StorageZoneColors()) { + Color current2 = item4; Color item2 = new Color(current2.r, current2.g, current2.b, 0.09f); ZoneColorUtility.storageZoneColors.Add(item2); } @@ -57,22 +57,23 @@ public static Color NextStorageZoneColor() return result; } - [DebuggerHidden] private static IEnumerable GrowingZoneColors() { - ZoneColorUtility.c__Iterator20C c__Iterator20C = new ZoneColorUtility.c__Iterator20C(); - ZoneColorUtility.c__Iterator20C expr_07 = c__Iterator20C; - expr_07.$PC = -2; - return expr_07; + yield return Color.Lerp(new Color(0f, 1f, 0f), Color.gray, 0.5f); + yield return Color.Lerp(new Color(1f, 1f, 0f), Color.gray, 0.5f); + yield return Color.Lerp(new Color(0.5f, 1f, 0f), Color.gray, 0.5f); + yield return Color.Lerp(new Color(1f, 1f, 0.5f), Color.gray, 0.5f); + yield return Color.Lerp(new Color(0.5f, 1f, 0.5f), Color.gray, 0.5f); } - [DebuggerHidden] private static IEnumerable StorageZoneColors() { - ZoneColorUtility.c__Iterator20D c__Iterator20D = new ZoneColorUtility.c__Iterator20D(); - ZoneColorUtility.c__Iterator20D expr_07 = c__Iterator20D; - expr_07.$PC = -2; - return expr_07; + yield return Color.Lerp(new Color(1f, 0f, 0f), Color.gray, 0.5f); + yield return Color.Lerp(new Color(1f, 0f, 1f), Color.gray, 0.5f); + yield return Color.Lerp(new Color(0f, 0f, 1f), Color.gray, 0.5f); + yield return Color.Lerp(new Color(1f, 0f, 0.5f), Color.gray, 0.5f); + yield return Color.Lerp(new Color(0f, 0.5f, 1f), Color.gray, 0.5f); + yield return Color.Lerp(new Color(0.5f, 0f, 1f), Color.gray, 0.5f); } } } diff --git a/Assembly-CSharp/Verse/ZoneMaker.cs b/Assembly-CSharp/Verse/ZoneMaker.cs index c0734fba0..ed83f6a83 100644 --- a/Assembly-CSharp/Verse/ZoneMaker.cs +++ b/Assembly-CSharp/Verse/ZoneMaker.cs @@ -1,4 +1,3 @@ -using System; using System.Collections.Generic; namespace Verse @@ -9,9 +8,12 @@ public static Zone MakeZoneWithCells(Zone z, IEnumerable cells) { if (cells != null) { - foreach (IntVec3 current in cells) { - z.AddCell(current); + foreach (IntVec3 item in cells) + { + z.AddCell(item); + } + return z; } } return z; diff --git a/Assembly-CSharp/Verse/ZoneManager.cs b/Assembly-CSharp/Verse/ZoneManager.cs index 41ed84e3f..dc942aa9f 100644 --- a/Assembly-CSharp/Verse/ZoneManager.cs +++ b/Assembly-CSharp/Verse/ZoneManager.cs @@ -47,13 +47,22 @@ private void RebuildZoneGrid() { CellIndices cellIndices = this.map.cellIndices; this.zoneGrid = new Zone[cellIndices.NumGridCells]; - foreach (Zone current in this.allZones) + List.Enumerator enumerator = this.allZones.GetEnumerator(); + try { - foreach (IntVec3 current2 in current) + while (enumerator.MoveNext()) { - this.zoneGrid[cellIndices.CellToIndex(current2)] = current; + Zone current = enumerator.Current; + foreach (IntVec3 item in current) + { + this.zoneGrid[cellIndices.CellToIndex(item)] = current; + } } } + finally + { + ((IDisposable)(object)enumerator).Dispose(); + } } public void RegisterZone(Zone newZone) @@ -86,7 +95,7 @@ public string NewZoneName(string nameBase) for (int i = 1; i <= 1000; i++) { string cand = nameBase + " " + i; - if (!this.allZones.Any((Zone z) => z.label == cand)) + if (!this.allZones.Any((Predicate)((Zone z) => z.label == cand))) { return cand; }