diff --git a/.github/ISSUE_TEMPLATE/bug_report_0high.md b/.github/ISSUE_TEMPLATE/bug_report_0high.md index dbadd4b3..aa1c9ee0 100644 --- a/.github/ISSUE_TEMPLATE/bug_report_0high.md +++ b/.github/ISSUE_TEMPLATE/bug_report_0high.md @@ -7,33 +7,59 @@ labels: Bug, Reproducible, Vanilla RT assignees: '' --- + + + +### Developer To Do Notes: +- [ ] +- [ ] +- [ ] + + +# **Vanilla Bug Report** + ### **Describe the bug** -!!! bug description here !!! +❗❗❗ bug description here ❗❗❗ ### **Steps to reproduce the behavior (VERY IMPORTANT)** -1. Go to '...' -2. Click on '....' -3. Scroll down to '....' -4. See error - -### **Error Logs** -#### **Player.log** -!!! Link to contents of Player.log or Error.log (MUST BE LINK) !!! +1. ❗❗❗ step 1 here ❗❗❗ +2. ❗❗❗ step 2 here ❗❗❗ +3. ❗❗❗ step 3 here ❗❗❗ +4. ❗❗❗ step 4 here ❗❗❗ + +### **Error Logs** [?](https://github.com/cseelhoff/RimThreaded/wiki/Q&A#what-logs-should-my-bug-report-include) +```cs +!!! You can copy paste an error here !!! +``` + #### **HugsLib log** -!!! Link to HugsLib log. (MUST BE LINK) !!! +❗❗❗ Link to HugsLib log. (MUST BE LINK) ❗❗❗ + +#### **Player.log (Optional)** +❗❗❗ Link to contents of Player.log or Error.log (MUST BE LINK) ❗❗❗ -### **Save file** -!!! Please add a save file where the issue occurs to speed up testing and fixing of the issue !!! +### **Save file** [?](https://github.com/cseelhoff/RimThreaded/wiki/Q&A#how-do-i-attach-the-save-file-to-the-report) +❗❗❗ Please add a save file where the issue occurs to speed up testing and fixing of the issue ❗❗❗ -### **Screenshots** -!!! Add screenshots to help explain your problem here !!! +### **Screenshots (Optional)** [?](https://github.com/cseelhoff/RimThreaded/wiki/Q%26A#how-do-i-attach-a-screenshot-to-the-report) +❗❗❗ Add screenshots to help explain your problem here ❗❗❗ -### **Mod list (For vanilla report, it has to be same as below list.)** +### **Mod list (For vanilla report, it has to be same as below list.)** [?](https://github.com/cseelhoff/RimThreaded/wiki/Q%26A#what-mod-organizer-should-i-use) +``` +[Mod list length: 6] +Harmony [https://steamcommunity.com/sharedfiles/filedetails/?id=2009463077] +Core [https:// no link (local mod)] +Royalty [Official DLC] [https:// no link (local mod)] +Ideology [Official DLC] [https:// no link (local mod)] +HugsLib [https://steamcommunity.com/sharedfiles/filedetails/?id=818773962] +RimThreaded [https://steamcommunity.com/sharedfiles/filedetails/?id=2222907981] +``` * Harmony * Core * Royalty (Optional) diff --git a/.github/ISSUE_TEMPLATE/bug_report_1med.md b/.github/ISSUE_TEMPLATE/bug_report_1med.md index 1be6e27a..1a1f3ef4 100644 --- a/.github/ISSUE_TEMPLATE/bug_report_1med.md +++ b/.github/ISSUE_TEMPLATE/bug_report_1med.md @@ -7,33 +7,53 @@ labels: Bug, Reproducible assignees: '' --- + + + +### Developer To Do Notes: +- [ ] +- [ ] +- [ ] + + +# **Non-Vanilla Bug Report** + ### **Describe the bug** -!!! bug description here !!! +❗❗❗ bug description here ❗❗❗ ### **Steps to reproduce the behavior (VERY IMPORTANT)** -1. Go to '...' -2. Click on '....' -3. Scroll down to '....' -4. See error +1. ❗❗❗ step 1 here ❗❗❗ +2. ❗❗❗ step 2 here ❗❗❗ +3. ❗❗❗ step 3 here ❗❗❗ +4. ❗❗❗ step 4 here ❗❗❗ + +### **Error Logs** [?](https://github.com/cseelhoff/RimThreaded/wiki/Q&A#what-logs-should-my-bug-report-include) +```cs +!!! You can copy paste an error here !!! +``` + +#### **HugsLib log** +❗❗❗ Link to HugsLib log. (MUST BE LINK) ❗❗❗ -### **Error Logs** -#### **Player.log** -!!! Link to contents of Player.log or Error.log (MUST BE LINK) !!! -#### **HugsLib log** -!!! Link to HugsLib log. (MUST BE LINK) !!! +#### **Player.log (Optional)** +❗❗❗ Link to contents of Player.log or Error.log (MUST BE LINK) ❗❗❗ -### **Save file** -!!! Please add a save file where the issue occurs to speed up testing and fixing of the issue !!! +### **Save file** [?](https://github.com/cseelhoff/RimThreaded/wiki/Q&A#how-do-i-attach-the-save-file-to-the-report) +❗❗❗ Please add a save file where the issue occurs to speed up testing and fixing of the issue ❗❗❗ -### **Screenshots** -!!! Add screenshots to help explain your problem here !!! +### **Screenshots (Optional)** [?](https://github.com/cseelhoff/RimThreaded/wiki/Q%26A#how-do-i-attach-a-screenshot-to-the-report) +❗❗❗ Add screenshots to help explain your problem here ❗❗❗ -### **Mod list (Preferably a RimPy compatible list.)** +### **Mod list (Preferably a RimPy compatible list.)** [?](https://github.com/cseelhoff/RimThreaded/wiki/Q%26A#what-mod-organizer-should-i-use) +``` +❗❗❗ Add RimPy mod list here ❗❗❗ +``` * Harmony * Core * Royalty (Optional) diff --git a/.github/ISSUE_TEMPLATE/bug_report_2low.md b/.github/ISSUE_TEMPLATE/bug_report_2low.md index dff32588..e93021c3 100644 --- a/.github/ISSUE_TEMPLATE/bug_report_2low.md +++ b/.github/ISSUE_TEMPLATE/bug_report_2low.md @@ -7,33 +7,59 @@ labels: Bug, Vanilla RT assignees: '' --- + + + +### Developer To Do Notes: +- [ ] +- [ ] +- [ ] + + +# **Vanilla Bug Report** + ### **Describe the bug** -!!! bug description here !!! +❗❗❗ bug description here ❗❗❗ ### **Steps to reproduce the behavior (VERY IMPORTANT)** -1. Go to '...' -2. Click on '....' -3. Scroll down to '....' -4. See error - -### **Error Logs** -#### **Player.log** -!!! Link to contents of Player.log or Error.log (MUST BE LINK) !!! +1. ❗❗❗ step 1 here ❗❗❗ +2. ❗❗❗ step 2 here ❗❗❗ +3. ❗❗❗ step 3 here ❗❗❗ +4. ❗❗❗ step 4 here ❗❗❗ + +### **Error Logs** [?](https://github.com/cseelhoff/RimThreaded/wiki/Q&A#what-logs-should-my-bug-report-include) +```cs +!!! You can copy paste an error here !!! +``` + #### **HugsLib log** -!!! Link to HugsLib log. (MUST BE LINK) !!! +❗❗❗ Link to HugsLib log. (MUST BE LINK) ❗❗❗ + +#### **Player.log (Optional)** +❗❗❗ Link to contents of Player.log or Error.log (MUST BE LINK) ❗❗❗ -### **Save file** -!!! Please add a save file where the issue occurs to speed up testing and fixing of the issue !!! +### **Save file** [?](https://github.com/cseelhoff/RimThreaded/wiki/Q&A#how-do-i-attach-the-save-file-to-the-report) +❗❗❗ Please add a save file where the issue occurs to speed up testing and fixing of the issue ❗❗❗ -### **Screenshots** -!!! Add screenshots to help explain your problem here !!! +### **Screenshots (Optional)** [?](https://github.com/cseelhoff/RimThreaded/wiki/Q%26A#how-do-i-attach-a-screenshot-to-the-report) +❗❗❗ Add screenshots to help explain your problem here ❗❗❗ -### **Mod list (For vanilla report, it has to be same as below list.)** +### **Mod list (For vanilla report, it has to be same as below list.)** [?](https://github.com/cseelhoff/RimThreaded/wiki/Q%26A#what-mod-organizer-should-i-use) +``` +[Mod list length: 6] +Harmony [https://steamcommunity.com/sharedfiles/filedetails/?id=2009463077] +Core [https:// no link (local mod)] +Royalty [Official DLC] [https:// no link (local mod)] +Ideology [Official DLC] [https:// no link (local mod)] +HugsLib [https://steamcommunity.com/sharedfiles/filedetails/?id=818773962] +RimThreaded [https://steamcommunity.com/sharedfiles/filedetails/?id=2222907981] +``` * Harmony * Core * Royalty (Optional) diff --git a/.github/ISSUE_TEMPLATE/bug_report_3lowest.md b/.github/ISSUE_TEMPLATE/bug_report_3lowest.md index a06c312b..c454cf5f 100644 --- a/.github/ISSUE_TEMPLATE/bug_report_3lowest.md +++ b/.github/ISSUE_TEMPLATE/bug_report_3lowest.md @@ -7,33 +7,53 @@ labels: Bug assignees: '' --- + + + +### Developer To Do Notes: +- [ ] +- [ ] +- [ ] + + +# **Non-Vanilla Bug Report** + ### **Describe the bug** -!!! bug description here !!! +❗❗❗ bug description here ❗❗❗ ### **Steps to reproduce the behavior (VERY IMPORTANT)** -1. Go to '...' -2. Click on '....' -3. Scroll down to '....' -4. See error +1. ❗❗❗ step 1 here ❗❗❗ +2. ❗❗❗ step 2 here ❗❗❗ +3. ❗❗❗ step 3 here ❗❗❗ +4. ❗❗❗ step 4 here ❗❗❗ + +### **Error Logs** [?](https://github.com/cseelhoff/RimThreaded/wiki/Q&A#what-logs-should-my-bug-report-include) +```cs +!!! You can copy paste an error here !!! +``` + +#### **HugsLib log** +❗❗❗ Link to HugsLib log. (MUST BE LINK) ❗❗❗ -### **Error Logs** -#### **Player.log** -!!! Link to contents of Player.log or Error.log (MUST BE LINK) !!! -#### **HugsLib log** -!!! Link to HugsLib log. (MUST BE LINK) !!! +#### **Player.log (Optional)** +❗❗❗ Link to contents of Player.log or Error.log (MUST BE LINK) ❗❗❗ -### **Save file** -!!! Please add a save file where the issue occurs to speed up testing and fixing of the issue !!! +### **Save file** [?](https://github.com/cseelhoff/RimThreaded/wiki/Q&A#how-do-i-attach-the-save-file-to-the-report) +❗❗❗ Please add a save file where the issue occurs to speed up testing and fixing of the issue ❗❗❗ -### **Screenshots** -!!! Add screenshots to help explain your problem here !!! +### **Screenshots (Optional)** [?](https://github.com/cseelhoff/RimThreaded/wiki/Q%26A#how-do-i-attach-a-screenshot-to-the-report) +❗❗❗ Add screenshots to help explain your problem here ❗❗❗ -### **Mod list (Preferably a RimPy compatible list.)** +### **Mod list (Preferably a RimPy compatible list.)** [?](https://github.com/cseelhoff/RimThreaded/wiki/Q%26A#what-mod-organizer-should-i-use) +``` +❗❗❗ Add RimPy mod list here ❗❗❗ +``` * Harmony * Core * Royalty (Optional) diff --git a/.gitignore b/.gitignore index 1b09cd17..76b1df5f 100644 --- a/.gitignore +++ b/.gitignore @@ -364,5 +364,4 @@ FodyWeavers.xsd Dependencies/*/*.dll Dependencies/*/*.hash RimWorldSource/ -RimThreaded/1.2/ -RimThreaded/1.3/ +RimThreaded/1.4/ diff --git a/README.md b/README.md index 643e5249..e9929b8e 100644 --- a/README.md +++ b/README.md @@ -38,6 +38,37 @@ DONATE: Some subscribers insisted that I set up a donation page. For those looking, here it is: https://ko-fi.com/rimthreaded CHANGE LOG: + +Version 2.7.2 +-Added RimWorld 1.4.8333.294475 support +-Fixed some bugs with Remove Hediffs including pregnancy bug +-Fixed alerts not appearing bug + +Version 2.7.1 +-Added RimWorld 1.4.8320.21511 (12-OCT) support +-Fixed some bugs with HediffSet + +Version 2.7.0 +-Added RimWorld 1.4 support +-Optimized Memory Usage + +Version 2.6.4 +-Fixed a bug with GiddyUp +-Optimized Memory Usage + +Version 2.6.3 +-Fixed another reservation bug +-Fixed a bug with Social Opinions +-Added caching for common thing request groups + +Version 2.6.2 +-Fixed Reservation Bug + +Version 2.6.0 - For Leo.S +-Recompiled for RimWorld 1.3.3200 +-Removed support for RimWorld version 1.2 +-Added SpeakUp Compatibility + Version 2.5.15 - Sith Memory Rub -Fixed bug in RecordWorker_TimeGettingJoy -Fixed bug in HediffSet.AddDirect diff --git a/RimThreaded/1.3/Assemblies/RimThreaded.dll b/RimThreaded/1.3/Assemblies/RimThreaded.dll new file mode 100644 index 00000000..17c8353e Binary files /dev/null and b/RimThreaded/1.3/Assemblies/RimThreaded.dll differ diff --git a/RimThreaded/1.3/Assemblies/RimThreaded.pdb b/RimThreaded/1.3/Assemblies/RimThreaded.pdb new file mode 100644 index 00000000..18ddb367 Binary files /dev/null and b/RimThreaded/1.3/Assemblies/RimThreaded.pdb differ diff --git a/RimThreaded/1.3/Assemblies/ThreadSafeLinkedList.dll b/RimThreaded/1.3/Assemblies/ThreadSafeLinkedList.dll new file mode 100644 index 00000000..842ce8af Binary files /dev/null and b/RimThreaded/1.3/Assemblies/ThreadSafeLinkedList.dll differ diff --git a/RimThreaded/1.3/Assemblies/ThreadSafeLinkedListRW.dll b/RimThreaded/1.3/Assemblies/ThreadSafeLinkedListRW.dll new file mode 100644 index 00000000..48f46cd2 Binary files /dev/null and b/RimThreaded/1.3/Assemblies/ThreadSafeLinkedListRW.dll differ diff --git a/RimThreaded/1.3/Assemblies/Unity.Newtonsoft.Json.dll b/RimThreaded/1.3/Assemblies/Unity.Newtonsoft.Json.dll new file mode 100644 index 00000000..251e0d2d Binary files /dev/null and b/RimThreaded/1.3/Assemblies/Unity.Newtonsoft.Json.dll differ diff --git a/Source/replacements_1.3.json b/RimThreaded/1.3/Assemblies/replacements_1.3.json similarity index 93% rename from Source/replacements_1.3.json rename to RimThreaded/1.3/Assemblies/replacements_1.3.json index 96c608ee..490662d4 100644 --- a/Source/replacements_1.3.json +++ b/RimThreaded/1.3/Assemblies/replacements_1.3.json @@ -1,5 +1,13 @@ { "ClassReplacements": [ + { + "ClassName": "Verse.AI.Pawn_JobTracker", + "ThreadStatics": [ + { + "FieldName": "tmpJobsToDequeue" + } + ] + }, { "ClassName": "Verse.AI.AttackTargetFinder", "ThreadStatics": [ @@ -23,6 +31,36 @@ } ] }, + { + "ClassName": "RimWorld.PortraitsCache", + "ThreadStatics": [ + { + "FieldName": "toRemove" + }, + { + "FieldName": "toSetDirty" + } + ] + }, + { + "ClassName": "RimWorld.PawnBioAndNameGenerator", + "ThreadStatics": [ + { + "FieldName": "tmpNames" + }, + { + "FieldName": "usedNamesTmp" + } + ] + }, + { + "ClassName": "RimWorld.JobDriver_RopeToDestination", + "ThreadStatics": [ + { + "FieldName": "tmpRopees" + } + ] + }, { "ClassName": "Verse.AI.AttackTargetsCache", "ThreadStatics": [ @@ -34,6 +72,29 @@ } ] }, + { + "ClassName": "Verse.AutoSlaughterManager", + "ThreadStatics": [ + { + "FieldName": "tmpAnimals" + }, + { + "FieldName": "tmpAnimalsMale" + }, + { + "FieldName": "tmpAnimalsMaleYoung" + }, + { + "FieldName": "tmpAnimalsFemale" + }, + { + "FieldName": "tmpAnimalsFemaleYoung" + }, + { + "FieldName": "tmpAnimalsPregnant" + } + ] + }, { "ClassName": "RimWorld.BeautyUtility", "ThreadStatics": [ @@ -907,6 +968,9 @@ }, { "FieldName": "logSbRules" + }, + { + "FieldName": "tmpSortedRuleList" } ] }, @@ -986,9 +1050,6 @@ { "FieldName": "tmpLoveRelations" }, - { - "FieldName": "tmpLoveClusterPawns" - }, { "FieldName": "tmpStack" }, @@ -1048,6 +1109,15 @@ "FieldName": "tmpPlayerTiles" } ] + }, + { + "ClassName": "SpeakUp.GrammarResolver_RandomPossiblyResolvableEntry", + "IgnoreMissing": true, + "ThreadStatics": [ + { + "FieldName": "CurrentRules" + } + ] } ] -} \ No newline at end of file +} diff --git a/RimThreaded/About/About.xml b/RimThreaded/About/About.xml index 1bbf22e8..d0ff247d 100644 --- a/RimThreaded/About/About.xml +++ b/RimThreaded/About/About.xml @@ -5,43 +5,48 @@ Major Hoff majorhoff.rimthreaded -
  • 1.2
  • -
  • 1.3
  • +
  • 1.4
  • RimThreaded enables RimWorld to utilize multiple threads and thus greatly increases the speed of the game. - Version 2.5.15 - Sith Memory Rub - -Fixed bug in RecordWorker_TimeGettingJoy - -Fixed bug in HediffSet.AddDirect - -Fixed bug in MemoryThoughtHandler.TryGainMemory - -Fixed bug in Pawn_HealthTracker.CheckForStateChange - -Fixed bug in Pawn_HealthTracker.PostApplyDamage - -Fixed bug in SituationalThoughtHandler.RemoveExpiredThoughtsFromCache - -Lowered Transpile Harmony priority for RT methods - -Removed disablelimits in RT settings - -Transpiled Thing.TakeDamage + Version 2.7.2 + -Added RimWorld 1.4.8333.294475 support + -Fixed some bugs with Remove Hediffs including pregnancy bug + -Fixed alerts not appearing bug - JOIN OUR COMMUNITY ON DISCORD / SUBMIT BUGS: + JOIN OUR COMMUNITY ON DISCORD: https://discord.gg/3JJuWK8 - MOD COMPATIBILITY/LOAD ORDER: - Use RimPy to check mod compatibility and load order + WIKI: + https://github.com/cseelhoff/RimThreaded/wiki + + MOD COMPATIBILITY: + https://github.com/cseelhoff/RimThreaded/wiki/Mod-Compatibility + + SETTINGS: + The number of threads to utilize should be set in the mod settings, according to your specific computer's core count. + If you are expiriencing "Thread Timeout" errors, try increasing your Thread Abort Timeout threshold. + + LOAD ORDER: + Put RimThreaded last in load order. + + SUBMIT BUGS: + https://github.com/cseelhoff/RimThreaded/issues/new/choose CREDITS: - Big thanks to Sernior for his continued help bug fixing and performance tweaks! + Special thank you for helping me test Austin (Stanui)! + And thank you to others in Rimworld community who have posted their bug findings! Big thanks to JoJo for his continued help bug fixing and adding mod compatibility! Big thanks to Brrainz (Pardeike) for Harmony and all of the coding help! Big thanks to Kiame Vivacity for his help with fixing sound! - Special thank you for helping me test Austin (Stanui)! - Thank you bookdude13 for your many bug fixes! + Thank you bookdude13 for your many bugfixes! Thank you to Ataman for helping me fix the LVM deep storage bug! Thank you Ken for fixing RegionCostCalculator.PathableNeighborIndices! Thank you Raccoononi for the RT 2.0 logo! https://discordhub.com/profile/245738467995156481 Thank you ArchieV1 for the RT 1.0 logo! https://github.com/ArchieV1 Logo help from: Marnador https://ludeon.com/forums/index.php?action=profile;u=36313 and JKimsey https://pixabay.com/users/jkimsey-253161/ Thank you BaRKy for reviewing my mod! I am honored! https://www.youtube.com/watch?v=EWudgTJksMU - And thank you to others in Rimworld community who have posted their bug findings! DONATE: Some subscribers insisted that I set up a donation page. For those looking, here it is: https://ko-fi.com/rimthreaded @@ -60,15 +65,13 @@
  • tachyonite.pawnmorpherpublic
  • vexedtrees980.rimuhiversi
  • ryder.turnitonoff
  • -
  • mlie.turnonoffrepowered
  • -
  • uuugggg.tdpack
  • dame.timecontrol
  • biomesteam.biomesislands
  • pyrce.terrain.movement.modkit
  • mlie.prisonerarena
  • rwmt.Multiplayer
  • zetrith.prepatcher
  • -
  • jpt.speakup
  • jecrell.doorsexpanded
  • +
  • Owlchemist.Windows
  • diff --git a/Source/1.2/replacements.json b/Source/1.2/replacements.json deleted file mode 100644 index 8c77c7ca..00000000 --- a/Source/1.2/replacements.json +++ /dev/null @@ -1,1014 +0,0 @@ -{ - "ClassReplacements": [ - { - "ClassName": "Verse.AI.AttackTargetFinder", - "ThreadStatics": [ - { - "FieldName": "tmpTargets" - }, - { - "FieldName": "availableShootingTargets" - }, - { - "FieldName": "tmpTargetScores" - }, - { - "FieldName": "tmpCanShootAtTarget" - }, - { - "FieldName": "tempDestList" - }, - { - "FieldName": "tempSourceList" - } - ] - }, - { - "ClassName": "Verse.AI.AttackTargetsCache", - "ThreadStatics": [ - { - "FieldName": "tmpTargets" - }, - { - "FieldName": "tmpToUpdate" - } - ] - }, - { - "ClassName": "RimWorld.BeautyUtility", - "ThreadStatics": [ - { - "FieldName": "tempCountedThings" - }, - { - "FieldName": "beautyRelevantCells" - }, - { - "FieldName": "visibleRooms" - } - ] - }, - { - "ClassName": "RimWorld.Planet.CaravanInventoryUtility", - "ThreadStatics": [ - { - "FieldName": "inventoryItems" - }, - { - "FieldName": "inventoryToMove" - }, - { - "FieldName": "tmpApparel" - }, - { - "FieldName": "tmpEquipment" - } - ] - }, - { - "ClassName": "RimWorld.Planet.Caravan_BedsTracker", - "ThreadStatics": [ - { - "FieldName": "tmpUsableBeds" - }, - { - "FieldName": "tmpPawnLabels" - } - ] - }, - { - "ClassName": "Verse.CellFinder", - "ThreadStatics": [ - { - "FieldName": "workingCells" - }, - { - "FieldName": "workingRegions" - }, - { - "FieldName": "workingListX" - }, - { - "FieldName": "workingListZ" - }, - { - "FieldName": "mapEdgeCells" - }, - { - "FieldName": "mapEdgeCellsSize" - }, - { - "FieldName": "mapSingleEdgeCells", - "PatchedClassName": "RimThreaded.CellFinder_Patch", - "SelfInitialized": true - }, - { - "FieldName": "mapSingleEdgeCellsSize" - }, - { - "FieldName": "tmpDistances" - }, - { - "FieldName": "tmpParents" - }, - { - "FieldName": "tmpCells" - }, - { - "FieldName": "tmpUniqueWipedThings" - } - ] - }, - { - "ClassName": "Verse.DamageWorker", - "ThreadStatics": [ - { - "FieldName": "thingsToAffect" - }, - { - "FieldName": "openCells" - }, - { - "FieldName": "adjWallCells" - } - ] - }, - { - "ClassName": "RimWorld.Fire", - "ThreadStatics": [ - { - "FieldName": "flammableList" - } - ] - }, - { - "ClassName": "RimWorld.FloatMenuMakerMap", - "ThreadStatics": [ - { - "FieldName": "tmpPawns" - } - ] - }, - { - "ClassName": "RimWorld.FoodUtility", - "ThreadStatics": [ - { - "FieldName": "bestFoodSourceOnMap_minNutrition_NewTemp" - }, - { - "FieldName": "filtered" - }, - { - "FieldName": "tmpPredatorCandidates" - }, - { - "FieldName": "ingestThoughts" - } - ] - }, - { - "ClassName": "Verse.GenAdjFast", - "ThreadStatics": [ - { - "FieldName": "resultList" - }, - { - "FieldName": "working" - } - ] - }, - { - "ClassName": "Verse.GenAdj", - "ThreadStatics": [ - { - "FieldName": "validCells" - } - ] - }, - { - "ClassName": "RimWorld.GenLeaving", - "ThreadStatics": [ - { - "FieldName": "tmpCellsCandidates" - } - ] - }, - { - "ClassName": "Verse.GenRadial", - "ThreadStatics": [ - { - "FieldName": "tmpCells" - }, - { - "FieldName": "working" - } - ] - }, - { - "ClassName": "Verse.GenTemperature", - "ThreadStatics": [ - { - "FieldName": "neighRoomGroups" - }, - { - "FieldName": "beqRoomGroups", - "PatchedClassName": "RimThreaded.GenTemperature_Patch", - "SelfInitialized": true - } - ] - }, - { - "ClassName": "Verse.GenText", - "ThreadStatics": [ - { - "FieldName": "tmpSbForCapitalizedSentences" - } - ] - }, - { - "ClassName": "Verse.GrammarResolverSimpleStringExtensions", - "ThreadStatics": [ - { - "FieldName": "argsLabels" - }, - { - "FieldName": "argsObjects" - } - ] - }, - { - "ClassName": "Verse.GrammarResolverSimple", - "ThreadStatics": [ - { - "FieldName": "tmpResultBuffer" - }, - { - "FieldName": "tmpSymbolBuffer" - }, - { - "FieldName": "tmpSymbolBuffer_objectLabel" - }, - { - "FieldName": "tmpSymbolBuffer_subSymbol" - }, - { - "FieldName": "tmpSymbolBuffer_args" - }, - { - "FieldName": "tmpArgsLabels" - }, - { - "FieldName": "tmpArgsObjects" - }, - { - "FieldName": "tmpArg" - } - ] - }, - { - "ClassName": "Verse.AI.HaulAIUtility", - "ThreadStatics": [ - { - "FieldName": "candidates" - } - ] - }, - { - "ClassName": "Verse.ImmunityHandler", - "ThreadStatics": [ - { - "FieldName": "tmpNeededImmunitiesNow" - } - ] - }, - { - "ClassName": "RimWorld.InfestationCellFinder", - "ThreadStatics": [ - { - "FieldName": "regionsDistanceToUnroofed" - }, - { - "FieldName": "tmpColonyBuildingsLocs" - }, - { - "FieldName": "tmpDistanceResult" - }, - { - "FieldName": "distToColonyBuilding" - }, - { - "FieldName": "closedAreaSize" - }, - { - "FieldName": "tmpCachedInfestationChanceCellColors" - }, - { - "FieldName": "tempUnroofedRegions" - }, - { - "FieldName": "locationCandidates" - } - ] - }, - { - "ClassName": "RimWorld.JobGiver_AnimalFlee", - "ThreadStatics": [ - { - "FieldName": "tmpThings" - } - ] - }, - { - "ClassName": "RimWorld.JobGiver_ConfigurableHostilityResponse", - "ThreadStatics": [ - { - "FieldName": "tmpThreats" - } - ] - }, - { - "ClassName": "RimWorld.JobGiver_OptimizeApparel", - "ThreadStatics": [ - { - "FieldName": "neededWarmth" - }, - { - "FieldName": "debugSb" - }, - { - "FieldName": "wornApparelScores" - } - ] - }, - { - "ClassName": "Verse.LanguageWordInfo", - "ThreadStatics": [ - { - "FieldName": "tmpLowercase" - } - ] - }, - { - "ClassName": "Verse.MapPawns", - "ThreadStatics": [ - { - "FieldName": "allPawnsResult" - }, - { - "FieldName": "allPawnsUnspawnedResult" - }, - { - "FieldName": "prisonersOfColonyResult" - }, - { - "FieldName": "freeColonistsAndPrisonersResult" - }, - { - "FieldName": "tmpThings" - }, - { - "FieldName": "freeColonistsAndPrisonersSpawnedResult" - }, - { - "FieldName": "spawnedPawnsWithAnyHediffResult" - }, - { - "FieldName": "spawnedHungryPawnsResult" - }, - { - "FieldName": "spawnedDownedPawnsResult" - }, - { - "FieldName": "spawnedPawnsWhoShouldHaveSurgeryDoneNowResult" - }, - { - "FieldName": "spawnedPawnsWhoShouldHaveInventoryUnloadedResult" - } - ] - }, - { - "ClassName": "Verse.MapTemperature", - "ThreadStatics": [ - { - "FieldName": "fastProcessedRoomGroups" - } - ] - }, - { - "ClassName": "RimWorld.Medicine", - "ThreadStatics": [ - { - "FieldName": "tendableHediffsInTendPriorityOrder" - }, - { - "FieldName": "tmpHediffs" - } - ] - }, - { - "ClassName": "Verse.AI.PathFinder", - "ThreadStatics": [ - { - "FieldName": "openList", - "PatchedClassName": "RimThreaded.PathFinder_Patch", - "SelfInitialized": true - }, - { - "FieldName": "statusOpenValue", - "PatchedClassName": "RimThreaded.PathFinder_Patch", - "SelfInitialized": true - }, - { - "FieldName": "statusClosedValue", - "PatchedClassName": "RimThreaded.PathFinder_Patch", - "SelfInitialized": true - }, - { - "FieldName": "disallowedCornerIndices", - "PatchedClassName": "RimThreaded.PathFinder_Patch", - "SelfInitialized": true - }, - { - "FieldName": "calcGrid", - "PatchedClassName": "RimThreaded.PathFinder_Patch", - "SelfInitialized": true - } - ] - }, - { - "ClassName": "RimWorld.PawnDiedOrDownedThoughtsUtility", - "ThreadStatics": [ - { - "FieldName": "tmpIndividualThoughtsToAdd" - }, - { - "FieldName": "tmpAllColonistsThoughts" - } - ] - }, - { - "ClassName": "RimWorld.PawnsFinder", - "ThreadStatics": [ - { - "FieldName": "allMapsWorldAndTemporary_AliveOrDead_Result" - }, - { - "FieldName": "allMapsWorldAndTemporary_Alive_Result" - }, - { - "FieldName": "allMapsAndWorld_Alive_Result" - }, - { - "FieldName": "allMaps_Result" - }, - { - "FieldName": "allMaps_Spawned_Result" - }, - { - "FieldName": "all_AliveOrDead_Result" - }, - { - "FieldName": "temporary_Result" - }, - { - "FieldName": "temporary_Alive_Result" - }, - { - "FieldName": "temporary_Dead_Result" - }, - { - "FieldName": "allMapsCaravansAndTravelingTransportPods_Alive_Result" - }, - { - "FieldName": "allCaravansAndTravelingTransportPods_Alive_Result" - }, - { - "FieldName": "allCaravansAndTravelingTransportPods_AliveOrDead_Result" - }, - { - "FieldName": "allMapsCaravansAndTravelingTransportPods_Alive_Colonists_Result" - }, - { - "FieldName": "allMapsCaravansAndTravelingTransportPods_Alive_FreeColonists_Result" - }, - { - "FieldName": "allMapsCaravansAndTravelingTransportPods_Alive_FreeColonists_NoLodgers_Result" - }, - { - "FieldName": "allMapsCaravansAndTravelingTransportPods_Alive_FreeColonists_NoCryptosleep_Result" - }, - { - "FieldName": "allMapsCaravansAndTravelingTransportPods_Alive_OfPlayerFaction_Result" - }, - { - "FieldName": "allMapsCaravansAndTravelingTransportPods_Alive_OfPlayerFaction_NoCryptosleep_Result" - }, - { - "FieldName": "allMapsCaravansAndTravelingTransportPods_Alive_PrisonersOfColony_Result" - }, - { - "FieldName": "allMapsCaravansAndTravelingTransportPods_Alive_FreeColonistsAndPrisoners_Result" - }, - { - "FieldName": "allMapsCaravansAndTravelingTransportPods_Alive_FreeColonistsAndPrisoners_NoCryptosleep_Result" - }, - { - "FieldName": "allMaps_PrisonersOfColonySpawned_Result" - }, - { - "FieldName": "allMaps_PrisonersOfColony_Result" - }, - { - "FieldName": "allMaps_FreeColonists_Result" - }, - { - "FieldName": "allMaps_FreeColonistsSpawned_Result" - }, - { - "FieldName": "allMaps_FreeColonistsAndPrisonersSpawned_Result" - }, - { - "FieldName": "allMaps_FreeColonistsAndPrisoners_Result" - }, - { - "FieldName": "allMaps_SpawnedPawnsInFaction_Result" - }, - { - "FieldName": "homeMaps_FreeColonistsSpawned_Result" - } - ] - }, - { - "ClassName": "RimWorld.Pawn_InteractionsTracker", - "ThreadStatics": [ - { - "FieldName": "workingList" - } - ] - }, - { - "ClassName": "RimWorld.Pawn_MeleeVerbs", - "ThreadStatics": [ - { - "FieldName": "meleeVerbs" - }, - { - "FieldName": "verbsToAdd" - } - ] - }, - { - "ClassName": "RimWorld.Pawn_WorkSettings", - "ThreadStatics": [ - { - "FieldName": "wtsByPrio" - } - ] - }, - { - "ClassName": "Verse.Projectile", - "ThreadStatics": [ - { - "FieldName": "cellThingsFiltered" - }, - { - "FieldName": "checkedCells" - } - ] - }, - { - "ClassName": "RimWorld.QuestUtility", - "ThreadStatics": [ - { - "FieldName": "tmpExtraFactions" - } - ] - }, - { - "ClassName": "Verse.Rand", - "ThreadStatics": [ - { - "FieldName": "tmpRange" - } - ] - }, - { - "ClassName": "RimWorld.RCellFinder", - "ThreadStatics": [ - { - "FieldName": "regions" - }, - { - "FieldName": "tmpBuildings" - }, - { - "FieldName": "tmpSpotThings" - }, - { - "FieldName": "tmpSpotsToAvoid" - }, - { - "FieldName": "tmpEdgeCells" - } - ] - }, - { - "ClassName": "Verse.RegionAndRoomUpdater", - "ThreadStatics": [ - { - "FieldName": "tmpVisitedRooms" - }, - { - "FieldName": "tmpRoomStack" - } - ] - }, - { - "ClassName": "Verse.AI.RegionCostCalculator", - "ThreadStatics": [ - { - "FieldName": "tmpPathableNeighborIndices" - }, - { - "FieldName": "tmpDistances" - }, - { - "FieldName": "tmpCellIndices" - } - ] - }, - { - "ClassName": "Verse.RegionListersUpdater", - "ThreadStatics": [ - { - "FieldName": "tmpRegions" - } - ] - }, - { - "ClassName": "Verse.RegionMaker", - "ThreadStatics": [ - { - "FieldName": "tmpProcessedThings" - } - ] - }, - { - "ClassName": "Verse.RegionTraverser", - "ThreadStatics": [ - { - "FieldName": "NumWorkers", - "PatchedClassName": "RimThreaded.RegionTraverser_Patch", - "SelfInitialized": true - }, - { - "FieldName": "freeWorkers", - "PatchedClassName": "RimThreaded.RegionTraverser_Patch", - "SelfInitialized": true - } - ] - }, - { - "ClassName": "Verse.Room", - "ThreadStatics": [ - { - "FieldName": "uniqueContainedThingsSet" - }, - { - "FieldName": "uniqueContainedThings" - }, - { - "FieldName": "uniqueNeighborsSet" - }, - { - "FieldName": "uniqueNeighbors" - }, - { - "FieldName": "uniqueContainedThingsOfDef" - }, - { - "FieldName": "fields" - } - ] - }, - { - "ClassName": "Verse.Sound.SustainerManager", - "ThreadStatics": [ - { - "FieldName": "playingPerDef", - "PatchedClassName": "RimThreaded.SustainerManager_Patch", - "SelfInitialized": true - } - ] - }, - { - "ClassName": "RimWorld.TendUtility", - "ThreadStatics": [ - { - "FieldName": "tmpHediffsToTend" - }, - { - "FieldName": "tmpHediffs" - }, - { - "FieldName": "tmpHediffsWithTendPriority" - } - ] - }, - { - "ClassName": "Verse.AI.ThinkNode_PrioritySorter", - "ThreadStatics": [ - { - "FieldName": "workingNodes" - } - ] - }, - { - "ClassName": "RimWorld.ThoughtHandler", - "ThreadStatics": [ - { - "FieldName": "tmpThoughts" - }, - { - "FieldName": "tmpTotalMoodOffsetThoughts" - }, - { - "FieldName": "tmpSocialThoughts" - }, - { - "FieldName": "tmpTotalOpinionOffsetThoughts" - } - ] - }, - { - "ClassName": "RimWorld.Toils_Ingest", - "ThreadStatics": [ - { - "FieldName": "spotSearchList" - }, - { - "FieldName": "cardinals", - "PatchedClassName": "RimThreaded.Toils_Ingest_Patch", - "SelfInitialized": true - }, - { - "FieldName": "diagonals", - "PatchedClassName": "RimThreaded.Toils_Ingest_Patch", - "SelfInitialized": true - } - ] - }, - { - "ClassName": "Verse.Verb", - "ThreadStatics": [ - { - "FieldName": "tempLeanShootSources" - }, - { - "FieldName": "tempDestList" - } - ] - }, - { - "ClassName": "Verse.AI.WanderUtility", - "ThreadStatics": [ - { - "FieldName": "gatherSpots" - }, - { - "FieldName": "candidateCells" - }, - { - "FieldName": "candidateBuildingsInRandomOrder" - } - ] - }, - { - "ClassName": "RimWorld.WealthWatcher", - "ThreadStatics": [ - { - "FieldName": "tmpThings" - } - ] - }, - { - "ClassName": "RimWorld.WildPlantSpawner", - "ThreadStatics": [ - { - "FieldName": "nearbyClusters" - }, - { - "FieldName": "nearbyClustersList" - }, - { - "FieldName": "distanceSqToNearbyClusters" - }, - { - "FieldName": "tmpPossiblePlantsWithWeight" - }, - { - "FieldName": "tmpPossiblePlants" - }, - { - "FieldName": "allCavePlants" - }, - { - "FieldName": "tmpPlantDefsLowerOrder" - } - ] - }, - { - "ClassName": "RimWorld.WorkGiver_Grower", - "ThreadStatics": [ - { - "FieldName": "wantedPlantDef", - "PatchedClassName": "RimThreaded.WorkGiver_Grower_Patch" - } - ] - }, - { - "ClassName": "RimWorld.WorkGiver_InteractAnimal", - "TargetedMethods": [ - { - "MethodName": "TakeFoodForAnimalInteractJob" - } - ] - }, - { - "ClassName": "Verse.WorldFloodFiller", - "ThreadStatics": [ - { - "FieldName": "openSet" - }, - { - "FieldName": "traversalDistance" - }, - { - "FieldName": "visited" - }, - { - "FieldName": "working" - } - ] - }, - { - "ClassName": "RimWorld.Planet.WorldGrid", - "ThreadStatics": [ - { - "FieldName": "tmpNeighbors" - } - ] - }, - { - "ClassName": "RimWorld.Planet.World", - "ThreadStatics": [ - { - "FieldName": "tmpNaturalRockDefs", - "PatchedClassName": "RimThreaded.World_Patch", - "SelfInitialized": true - }, - { - "FieldName": "tmpOceanDirs", - "PatchedClassName": "RimThreaded.World_Patch", - "SelfInitialized": true - }, - { - "FieldName": "tmpNeighbors", - "PatchedClassName": "RimThreaded.World_Patch", - "SelfInitialized": true - } - ] - }, - { - "ClassName": "RimWorld.ShipLandingBeaconUtility", - "ThreadStatics": [ - { - "FieldName": "tmpShipLandingAreas" - } - ] - }, - { - "ClassName": "RimWorld.DropCellFinder", - "ThreadStatics": [ - { - "FieldName": "tmpColonyBuildings" - }, - { - "FieldName": "tmpShipLandingAreas" - } - ] - }, - { - "ClassName": "Verse.Grammar.GrammarResolver", - "ThreadStatics": [ - { - "FieldName": "rules" - }, - { - "FieldName": "rulePool" - }, - { - "FieldName": "loopCount" - }, - { - "FieldName": "logSbTrace" - }, - { - "FieldName": "logSbMid" - }, - { - "FieldName": "logSbRules" - } - ] - }, - { - "ClassName": "RimWorld.ShipUtility", - "ThreadStatics": [ - { - "FieldName": "closedSet" - }, - { - "FieldName": "openSet" - } - ] - }, - { - "ClassName": "RimWorld.ThingSetMaker", - "ThreadStatics": [ - { - "FieldName": "thingsBeingGeneratedNow" - } - ] - }, - { - "ClassName": "Verse.ColoredText", - "ThreadStatics": [ - { - "FieldName": "resultBuffer" - }, - { - "FieldName": "tagBuffer" - }, - { - "FieldName": "argBuffer" - }, - { - "FieldName": "cache" - }, - { - "FieldName": "capStage" - }, - { - "FieldName": "ColonistCountRegex", - "PatchedClassName": "RimThreaded.ColoredText_Patch", - "SelfInitialized": true - } - ] - }, - { - "ClassName": "RimWorld.Pawn_ApparelTracker", - "ThreadStatics": [ - { - "FieldName": "tmpApparel", - "PatchedClassName": "RimThreaded.Pawn_ApparelTracker_Patch" - }, - { - "FieldName": "tmpApparelList" - } - ] - }, - { - "ClassName": "RimWorld.RoomStatWorker_Beauty", - "ThreadStatics": [ - { - "FieldName": "countedThings" - }, - { - "FieldName": "countedAdjCells" - } - ] - }, - { - "ClassName": "Verse.BuildingsDamageSectionLayerUtility", - "ThreadStatics": [ - { - "FieldName": "availableOverlays" - }, - { - "FieldName": "overlaysWorkingList" - }, - { - "FieldName": "overlays" - } - ] - }, - { - "ClassName": "RimWorld.Need_RoomSize", - "ThreadStatics": [ - { - "FieldName": "tempScanRooms" - } - ] - } - ] -} \ No newline at end of file diff --git a/Source/AssemblyCache.cs b/Source/AssemblyCache.cs index c792221a..94e9e695 100644 --- a/Source/AssemblyCache.cs +++ b/Source/AssemblyCache.cs @@ -37,7 +37,7 @@ public static bool TryGetFromCache(string ModuleVersionId, out List { if (Prefs.LogVerbose) { - Verse.Log.Message("TryGetFromCache: " + ModuleVersionId); + Log.Message("TryGetFromCache: " + ModuleVersionId); } string CacheFolder = Path.Combine(RimThreadedMod.replacementsFolder, "Caches"); Directory.CreateDirectory(CacheFolder); @@ -50,7 +50,7 @@ public static bool TryGetFromCache(string ModuleVersionId, out List } if (Prefs.LogVerbose) { - Verse.Log.Message("RimThreaded is loading Cached Field Replacements from: " + CurrentMethodPath); + Log.Message("RimThreaded is loading Cached Field Replacements from: " + CurrentMethodPath); } string jsonstr = File.ReadAllText(CurrentMethodPath); CacheListS = JsonConvert.DeserializeObject>(jsonstr); diff --git a/Source/AttackTargetReservationManager_Patch.cs b/Source/AttackTargetReservationManager_Patch.cs deleted file mode 100644 index e1720b05..00000000 --- a/Source/AttackTargetReservationManager_Patch.cs +++ /dev/null @@ -1,226 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Reflection; -using RimWorld; -using Verse; -using Verse.AI; -using static Verse.AI.AttackTargetReservationManager; -//using static HarmonyLib.AccessTools; -//using HarmonyLib; - -namespace RimThreaded -{ - - public class AttackTargetReservationManager_Patch // rebuild to not create new tmp lists and to recycle reservations. - { - internal static void RunDestructivePatches() - { - Type original = typeof(AttackTargetReservationManager); - Type patched = typeof(AttackTargetReservationManager_Patch); - RimThreadedHarmony.Prefix(original, patched, nameof(FirstReservationFor)); - RimThreadedHarmony.Prefix(original, patched, nameof(ReleaseClaimedBy)); - RimThreadedHarmony.Prefix(original, patched, nameof(ReleaseAllForTarget)); - RimThreadedHarmony.Prefix(original, patched, nameof(ReleaseAllClaimedBy)); - RimThreadedHarmony.Prefix(original, patched, nameof(GetReservationsCount)); - RimThreadedHarmony.Prefix(original, patched, nameof(Reserve)); - RimThreadedHarmony.Prefix(original, patched, nameof(IsReservedBy)); - RimThreadedHarmony.Prefix(original, patched, nameof(Release)); - } -/* internal static void RunNonDestructivePatches() - { - Type original = typeof(AttackTargetReservationManager); - Type patched = typeof(AttackTargetReservationManager_Patch); - ConstructorInfo oCtor = Constructor(original, new Type[] { typeof(Map)}); - MethodInfo pMethod = Method(patched, nameof(ATRMConstructor)); - RimThreadedHarmony.harmony.Patch(oCtor, postfix: new HarmonyMethod(pMethod)); - }*/ - - [ThreadStatic] static public List newAttackTargetReservations; - - internal static void InitializeThreadStatics() - { - newAttackTargetReservations = new List(); - } - /*public static void ATRMConstructor(AttackTargetReservationManager __instance, Map map) - { - newAttackTargetReservations[__instance] = new List();//only 1 thread will have this added big mistake maybe this can be done in another way. - }*/ - public static bool Release(AttackTargetReservationManager __instance, Pawn claimant, Job job, IAttackTarget target) - { - lock (__instance) - { - if (target == null) - { - Log.Warning(string.Concat(claimant, " tried to release reservation on null attack target.")); - return false; - } - List snapshotReservations = __instance.reservations; - - newAttackTargetReservations.Clear(); - for (int i = 0; i < snapshotReservations.Count; i++) - { - AttackTargetReservation attackTargetReservation = snapshotReservations[i]; - if (attackTargetReservation.target != target || attackTargetReservation.claimant != claimant || attackTargetReservation.job != job) - { - newAttackTargetReservations.Add(attackTargetReservation); - } - else - { - SimplePool_Patch.Return(attackTargetReservation); - } - } - __instance.reservations.Clear(); - __instance.reservations.AddRange(newAttackTargetReservations); - } - return false; - } - public static bool ReleaseAllForTarget(AttackTargetReservationManager __instance, IAttackTarget target) - { - lock (__instance) - { - List snapshotReservations = __instance.reservations; - - newAttackTargetReservations.Clear(); - - for (int i = 0; i < snapshotReservations.Count - 1; i++) - { - AttackTargetReservation attackTargetReservation = snapshotReservations[i]; - if (attackTargetReservation.target != target) - { - newAttackTargetReservations.Add(attackTargetReservation); - } - else - { - SimplePool_Patch.Return(attackTargetReservation); - } - } - __instance.reservations.Clear(); - __instance.reservations.AddRange(newAttackTargetReservations); - } - - return false; - } - - public static bool ReleaseAllClaimedBy(AttackTargetReservationManager __instance, Pawn claimant) - { - lock (__instance) - { - List snapshotReservations = __instance.reservations; - - newAttackTargetReservations.Clear(); - for (int i = 0; i < snapshotReservations.Count - 1; i++) - { - AttackTargetReservation attackTargetReservation = snapshotReservations[i]; - if (attackTargetReservation.claimant != claimant) - { - newAttackTargetReservations.Add(attackTargetReservation); - } - else - { - SimplePool_Patch.Return(attackTargetReservation); - } - } - __instance.reservations.Clear(); - __instance.reservations.AddRange(newAttackTargetReservations); - } - return false; - } - - - public static bool Reserve(AttackTargetReservationManager __instance, Pawn claimant, Job job, IAttackTarget target) - { - if (target == null) - { - Log.Warning(string.Concat(claimant, " tried to reserve null attack target.")); - } - else if (!__instance.IsReservedBy(claimant, target)) - { - - AttackTargetReservation attackTargetReservation = SimplePool_Patch.Get(); - attackTargetReservation.target = target; - attackTargetReservation.claimant = claimant; - attackTargetReservation.job = job; - - lock (__instance) - { - - newAttackTargetReservations.Clear(); - newAttackTargetReservations.AddRange(__instance.reservations); - newAttackTargetReservations.Add(attackTargetReservation); - - __instance.reservations.Clear(); - __instance.reservations.AddRange(newAttackTargetReservations); - } - } - return false; - } - - public static bool FirstReservationFor(AttackTargetReservationManager __instance, ref IAttackTarget __result, Pawn claimant) - { - List snapshotReservations = __instance.reservations; - for (int i = snapshotReservations.Count - 1; i >= 0; i--) - { - AttackTargetReservation reservation = snapshotReservations[i]; - if (reservation.claimant != claimant) continue; - __result = reservation.target; - return false; - } - __result = null; - return false; - } - public static bool ReleaseClaimedBy(AttackTargetReservationManager __instance, Pawn claimant, Job job) - { - lock (__instance) - { - List snapshotReservations = __instance.reservations; - - newAttackTargetReservations.Clear(); - for (int i = 0; i < snapshotReservations.Count - 1; i++) - { - AttackTargetReservation attackTargetReservation = snapshotReservations[i]; - if (attackTargetReservation.claimant != claimant || attackTargetReservation.job != job) - { - newAttackTargetReservations.Add(attackTargetReservation); - } - else - { - SimplePool_Patch.Return(attackTargetReservation); - } - } - __instance.reservations.Clear(); - __instance.reservations.AddRange(newAttackTargetReservations); - } - return false; - } - public static bool IsReservedBy(AttackTargetReservationManager __instance, ref bool __result, Pawn claimant, IAttackTarget target) - { - List snapshotReservations = __instance.reservations; - for (int i = 0; i < snapshotReservations.Count; i++) - { - AttackTargetReservation attackTargetReservation = snapshotReservations[i]; - if (attackTargetReservation.target != target || attackTargetReservation.claimant != claimant) continue; - __result = true; - return false; - } - - __result = false; - return false; - } - - public static bool GetReservationsCount(AttackTargetReservationManager __instance, ref int __result, IAttackTarget target, Faction faction) - { - int num = 0; - List snapshotReservations = __instance.reservations; - for (int i = 0; i < snapshotReservations.Count; i++) - { - AttackTargetReservation attackTargetReservation = snapshotReservations[i]; - if (attackTargetReservation.target == target && attackTargetReservation.claimant.Faction == faction) - { - num++; - } - } - __result = num; - return false; - } - } -} diff --git a/Source/BattleLog_Transpile.cs b/Source/BattleLog_Transpile.cs deleted file mode 100644 index fe0a80be..00000000 --- a/Source/BattleLog_Transpile.cs +++ /dev/null @@ -1,51 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Reflection.Emit; -using HarmonyLib; -using Verse; -using static HarmonyLib.AccessTools; - -namespace RimThreaded -{ - public class BattleLog_Transpile - { - internal static void RunNonDestructivePatches() - { - Type original = typeof(BattleLog); - Type patched = typeof(BattleLog_Transpile); - RimThreadedHarmony.Transpile(original, patched, "Add"); - } - - public static object addLogEntryLock = new object(); - public static IEnumerable Add(IEnumerable instructions, ILGenerator iLGenerator) - { - List instructionsList = instructions.ToList(); - int i = 0; - Type lockObjectType = typeof(object); - List loadLockObjectInstructions = new List - { - new CodeInstruction(OpCodes.Ldsfld, Field(typeof(BattleLog_Transpile), "addLogEntryLock")), - }; - LocalBuilder lockObject = iLGenerator.DeclareLocal(lockObjectType); - LocalBuilder lockTaken = iLGenerator.DeclareLocal(typeof(bool)); - foreach (CodeInstruction ci in RimThreadedHarmony.EnterLock( - lockObject, lockTaken, loadLockObjectInstructions, instructionsList[i])) - yield return ci; - - while (i < instructionsList.Count - 1) - { - yield return instructionsList[i++]; - } - foreach (CodeInstruction ci in RimThreadedHarmony.ExitLock( - iLGenerator, lockObject, lockTaken, instructionsList[i])) - yield return ci; - - while (i < instructionsList.Count) - { - yield return instructionsList[i++]; - } - } - - } -} diff --git a/Source/BeautyUtility_Patch.cs b/Source/BeautyUtility_Patch.cs deleted file mode 100644 index f7380f02..00000000 --- a/Source/BeautyUtility_Patch.cs +++ /dev/null @@ -1,65 +0,0 @@ -using RimWorld; -using System; -using System.Collections.Generic; -using Verse; - -namespace RimThreaded -{ - class BeautyUtility_Patch - { - internal static void RunDestructivePatches() - { - Type original = typeof(BeautyUtility); - Type patched = typeof(BeautyUtility_Patch); - RimThreadedHarmony.Prefix(original, patched, nameof(CellBeauty)); - } - public static bool CellBeauty(ref float __result, IntVec3 c, Map map, List countedThings = null) - { - float num1 = 0.0f; - float num2 = 0.0f; - bool flag = false; - if(map == null) //added - { - __result = 0f; - return false; - } - ThingGrid thingGrid = map.thingGrid; - if (thingGrid == null) //added - { - __result = 0f; - return false; - } - List thingList = thingGrid.ThingsListAt(c); //changed - for (int index = 0; index < thingList.Count; ++index) - { - Thing thing = thingList[index]; - if (BeautyUtility.BeautyRelevant(thing.def.category)) - { - if (countedThings != null) - { - if (!countedThings.Contains(thing)) - countedThings.Add(thing); - else - continue; - } - SlotGroup slotGroup = thing.GetSlotGroup(); - if (slotGroup == null || slotGroup.parent == thing || !slotGroup.parent.IgnoreStoredThingsBeauty) - { - float statValue = thing.GetStatValue(StatDefOf.Beauty); - if (thing is Filth && !map.roofGrid.Roofed(c)) - statValue *= 0.3f; - if (thing.def.Fillage == FillCategory.Full) - { - flag = true; - num2 += statValue; - } - else - num1 += statValue; - } - } - } - __result = flag ? num2 : num1 + map.terrainGrid.TerrainAt(c).GetStatValueAbstract(StatDefOf.Beauty); - return false; - } - } -} diff --git a/Source/Building_Bed_Patch.cs b/Source/Building_Bed_Patch.cs deleted file mode 100644 index 35e5dc34..00000000 --- a/Source/Building_Bed_Patch.cs +++ /dev/null @@ -1,290 +0,0 @@ -using System; -using System.Collections.Generic; -using RimWorld; -using Verse; -using Verse.Sound; - -namespace RimThreaded -{ - class Building_Bed_Patch - { - internal static void RunDestructivePatches() - { - Type original = typeof(Building_Bed); - Type patched = typeof(Building_Bed_Patch); -#if RW13 - RimThreadedHarmony.Prefix(original, patched, nameof(SpawnSetup)); -#endif - } - internal static Faction ThingFaction(Thing __instance) - { - return __instance.factionInt; - } - internal static Map ThingMap(Thing __instance) - { - if (__instance.mapIndexOrState >= 0) - { - return Find.Maps[__instance.mapIndexOrState]; - } - return null; - } - internal static IntVec3 ThingPos(Thing __instance) - { - return __instance.positionInt; - } - internal static void SpawnSetupThing(Thing __instance, Map map, bool respawningAfterLoad) - { - if (__instance.Destroyed) - { - Log.Error(string.Concat("Spawning destroyed thing ", __instance, " at ", __instance.Position, ". Correcting.")); - __instance.mapIndexOrState = -1; - if (__instance.HitPoints <= 0 && __instance.def.useHitPoints) - { - __instance.HitPoints = 1; - } - } - if (__instance.Spawned) - { - Log.Error(string.Concat("Tried to spawn already-spawned thing ", __instance, " at ", __instance.Position)); - return; - } - int num = Find.Maps.IndexOf(map); - if (num < 0) - { - Log.Error(string.Concat("Tried to spawn thing ", __instance, ", but the map provided does not exist.")); - return; - } - if (__instance.stackCount > __instance.def.stackLimit) - { - Log.Error(string.Concat("Spawned ", __instance, " with stackCount ", __instance.stackCount, " but stackLimit is ", __instance.def.stackLimit, ". Truncating.")); - __instance.stackCount = __instance.def.stackLimit; - } - __instance.mapIndexOrState = (sbyte)num; - RegionListersUpdater.RegisterInRegions(__instance, map); - if (!map.spawnedThings.TryAdd(__instance, canMergeWithExistingStacks: false)) - { - Log.Error(string.Concat("Couldn't add thing ", __instance, " to spawned things.")); - } - map.listerThings.Add(__instance); - map.thingGrid.Register(__instance); - if (map.IsPlayerHome) - { - __instance.EverSeenByPlayer = true; - } - if (Find.TickManager != null) - { - Find.TickManager.RegisterAllTickabilityFor(__instance); - } - __instance.DirtyMapMesh(map); - if (__instance.def.drawerType != DrawerType.MapMeshOnly) - { - map.dynamicDrawManager.RegisterDrawable(__instance); - } - map.tooltipGiverList.Notify_ThingSpawned(__instance); - if (__instance.def.CanAffectLinker) - { - map.linkGrid.Notify_LinkerCreatedOrDestroyed(__instance); - map.mapDrawer.MapMeshDirty(__instance.Position, MapMeshFlag.Things, regenAdjacentCells: true, regenAdjacentSections: false); - } - if (!__instance.def.CanOverlapZones) - { - map.zoneManager.Notify_NoZoneOverlapThingSpawned(__instance); - } - if (__instance.def.AffectsRegions) - { - map.regionDirtyer.Notify_ThingAffectingRegionsSpawned(__instance); - } - if (__instance.def.pathCost != 0 || __instance.def.passability == Traversability.Impassable) - { - map.pathing.RecalculatePerceivedPathCostUnderThing(__instance); - } - if (__instance.def.AffectsReachability) - { - map.reachability.ClearCache(); - } - map.coverGrid.Register(__instance); - if (__instance.def.category == ThingCategory.Item) - { - map.listerHaulables.Notify_Spawned(__instance); - map.listerMergeables.Notify_Spawned(__instance); - } - map.attackTargetsCache.Notify_ThingSpawned(__instance); - (map.regionGrid.GetValidRegionAt_NoRebuild(__instance.Position)?.Room)?.Notify_ContainedThingSpawnedOrDespawned(__instance); - StealAIDebugDrawer.Notify_ThingChanged(__instance); - IHaulDestination haulDestination = __instance as IHaulDestination; - if (haulDestination != null) - { - map.haulDestinationManager.AddHaulDestination(haulDestination); - } - if (__instance is IThingHolder && Find.ColonistBar != null) - { - Find.ColonistBar.MarkColonistsDirty(); - } - if (__instance.def.category == ThingCategory.Item) - { - SlotGroup slotGroup = __instance.Position.GetSlotGroup(map); - if (slotGroup != null && slotGroup.parent != null) - { - slotGroup.parent.Notify_ReceivedThing(__instance); - } - } - if (__instance.def.receivesSignals) - { - Find.SignalManager.RegisterReceiver(__instance); - } - if (!respawningAfterLoad) - { - QuestUtility.SendQuestTargetSignals(__instance.questTags, "Spawned", __instance.Named("SUBJECT")); - } - } - internal static void SpawnSetupThingWC(ThingWithComps __instance, Map map, bool respawningAfterLoad) - { - SpawnSetupThing((Thing)__instance, map, respawningAfterLoad); - if (__instance.comps != null) - { - for (int i = 0; i < __instance.comps.Count; i++) - { - __instance.comps[i].PostSpawnSetup(respawningAfterLoad); - } - } - } - internal static void SpawnSetupBuilding(Building __instance, Map map, bool respawningAfterLoad) - { - if (__instance.def.IsEdifice()) - { - map.edificeGrid.Register(__instance); - if (__instance.def.Fillage == FillCategory.Full) - { - map.terrainGrid.Drawer.SetDirty(); - } - if (__instance.def.AffectsFertility) - { - map.fertilityGrid.Drawer.SetDirty(); - } - } - SpawnSetupThingWC((ThingWithComps)__instance ,map, respawningAfterLoad); - Map Basemap = ThingMap((Thing)__instance); - Basemap.listerBuildings.Add(__instance); - if (__instance.def.coversFloor) - { - Basemap.mapDrawer.MapMeshDirty(ThingPos((Thing)__instance), MapMeshFlag.Terrain, regenAdjacentCells: true, regenAdjacentSections: false); - } - CellRect cellRect = __instance.OccupiedRect(); - for (int i = cellRect.minZ; i <= cellRect.maxZ; i++) - { - for (int j = cellRect.minX; j <= cellRect.maxX; j++) - { - IntVec3 intVec = new IntVec3(j, 0, i); - Basemap.mapDrawer.MapMeshDirty(intVec, MapMeshFlag.Buildings); - Basemap.glowGrid.MarkGlowGridDirty(intVec); - if (!SnowGrid.CanCoexistWithSnow(__instance.def)) - { - Basemap.snowGrid.SetDepth(intVec, 0f); - } - } - } - if (ThingFaction((Thing)__instance) == Faction.OfPlayer && __instance.def.building != null && __instance.def.building.spawnedConceptLearnOpportunity != null) - { - LessonAutoActivator.TeachOpportunity(__instance.def.building.spawnedConceptLearnOpportunity, OpportunityType.GoodToKnow); - } - AutoHomeAreaMaker.Notify_BuildingSpawned(__instance); - if (__instance.def.building != null && !__instance.def.building.soundAmbient.NullOrUndefined()) - { - LongEventHandler.ExecuteWhenFinished(delegate - { - SoundInfo info = SoundInfo.InMap(__instance); - __instance.sustainerAmbient = __instance.def.building.soundAmbient.TrySpawnSustainer(info); - }); - } - Basemap.listerBuildingsRepairable.Notify_BuildingSpawned(__instance); - Basemap.listerArtificialBuildingsForMeditation.Notify_BuildingSpawned(__instance); - Basemap.listerBuldingOfDefInProximity.Notify_BuildingSpawned(__instance); - Basemap.listerBuildingWithTagInProximity.Notify_BuildingSpawned(__instance); - if (!__instance.CanBeSeenOver()) - { - Basemap.exitMapGrid.Notify_LOSBlockerSpawned(); - } - SmoothSurfaceDesignatorUtility.Notify_BuildingSpawned(__instance); - map.avoidGrid.Notify_BuildingSpawned(__instance); - map.lordManager.Notify_BuildingSpawned(__instance); - map.animalPenManager.Notify_BuildingSpawned(__instance); - } - internal static void Notify_RoomShapeChanged2(Room r)//Maybe it must be locked to prevent adding/removing districts for r.Map - { - Map tmpMap = r.Map;//changed - if (tmpMap is null)// it is likely better to not even start the Notify procedure if map is null - { - return; - } - r.cachedCellCount = -1; - r.cachedOpenRoofCount = -1; - if (r.Dereferenced) - { - r.isPrisonCell = false; - r.statsAndRoleDirty = true; - return; - } - r.tempTracker.RoomChanged(); - if (Current.ProgramState == ProgramState.Playing && !r.Fogged) - { - tmpMap.autoBuildRoofAreaSetter.TryGenerateAreaFor(r); - } - r.isPrisonCell = false; - if (Building_Bed.RoomCanBePrisonCell(r)) - { - List containedAndAdjacentThings = r.ContainedAndAdjacentThings; - for (int i = 0; i < containedAndAdjacentThings.Count; i++) - { - Building_Bed building_Bed = containedAndAdjacentThings[i] as Building_Bed; - if (building_Bed != null && building_Bed.ForPrisoners) - { - r.isPrisonCell = true; - break; - } - } - } - List list = tmpMap.listerThings.ThingsOfDef(ThingDefOf.NutrientPasteDispenser); - for (int j = 0; j < list.Count; j++) - { - list[j].Notify_ColorChanged(); - } - if (Current.ProgramState == ProgramState.Playing && r.isPrisonCell) - { - foreach (Building_Bed containedBed in r.ContainedBeds) - { - containedBed.ForPrisoners = true; - } - } - r.statsAndRoleDirty = true; - } - public static bool SpawnSetup(Building_Bed __instance, Map map, bool respawningAfterLoad) - { - SpawnSetupBuilding((Building)__instance, map, respawningAfterLoad); - - Region validRegionAt_NoRebuild = map.regionGrid.GetValidRegionAt_NoRebuild(ThingPos((Thing)__instance)); - - if (validRegionAt_NoRebuild != null && validRegionAt_NoRebuild.Room.IsPrisonCell) - { - __instance.ForPrisoners = true; - } - if (!__instance.alreadySetDefaultMed) - { - __instance.alreadySetDefaultMed = true; - if (__instance.def.building.bed_defaultMedical) - { - __instance.Medical = true; - } - } - if (!respawningAfterLoad) - { - District district = __instance.GetDistrict(); - if (district != null) - { - district.Notify_RoomShapeOrContainedBedsChanged(); - Notify_RoomShapeChanged2(district.Room); - } - } - return false; - } - } -} diff --git a/Source/Building_Door_Patch.cs b/Source/Building_Door_Patch.cs deleted file mode 100644 index 7b04559c..00000000 --- a/Source/Building_Door_Patch.cs +++ /dev/null @@ -1,34 +0,0 @@ -using System; -using System.Collections.Generic; -using RimWorld; -using Verse; - -namespace RimThreaded -{ - - public class Building_Door_Patch - { - internal static void RunDestructivePatches() - { - Type original = typeof(Building_Door); - Type patched = typeof(Building_Door_Patch); - RimThreadedHarmony.Prefix(original, patched, "get_DoorPowerOn"); - } - - public static bool get_DoorPowerOn(Building_Door __instance, ref bool __result) - { - CompPowerTrader pc = __instance.powerComp; - bool poweron = false; - if (pc != null) - { - try - { - poweron = pc.PowerOn; - } - catch (NullReferenceException) { } - } - __result = poweron; - return false; - } - } -} diff --git a/Source/DesignationManager_Patch.cs b/Source/DesignationManager_Patch.cs deleted file mode 100644 index fc2315e9..00000000 --- a/Source/DesignationManager_Patch.cs +++ /dev/null @@ -1,146 +0,0 @@ -using System; -using System.Collections.Generic; -using RimWorld; -using Verse; - -namespace RimThreaded -{ - class DesignationManager_Patch - { - internal static void RunDestructivePatches() - { - Type original = typeof(DesignationManager); - Type patched = typeof(DesignationManager_Patch); - RimThreadedHarmony.Prefix(original, patched, nameof(RemoveDesignation)); - RimThreadedHarmony.Prefix(original, patched, nameof(RemoveAllDesignationsOn)); - RimThreadedHarmony.Prefix(original, patched, nameof(RemoveAllDesignationsOfDef)); - RimThreadedHarmony.Prefix(original, patched, nameof(AddDesignation)); - RimThreadedHarmony.Prefix(original, patched, nameof(SpawnedDesignationsOfDef)); - RimThreadedHarmony.Prefix(original, patched, nameof(DesignationOn), - new Type[] { typeof(Thing), typeof(DesignationDef) }, false); //weird CanBeBuried CanExtractSkull Ideology requirement is null - } - - public static bool DesignationOn(DesignationManager __instance, ref Designation __result, Thing t, DesignationDef def) - { - if(def == null) //weird CanBeBuried CanExtractSkull Ideology requirement is null - { - for (int index = 0; index < __instance.allDesignations.Count; ++index) - { - Designation allDesignation = __instance.allDesignations[index]; - if (allDesignation.target.Thing == t && allDesignation.def == def) - { - __result = allDesignation; - return false; - } - } - __result = null; - return false; - } - return true; - } - - public static bool RemoveDesignation(DesignationManager __instance, Designation des) - { - des.Notify_Removing(); - if (!__instance.allDesignations.Contains(des)) return false; - - lock (__instance) - { - List newAllDesignations = new List(__instance.allDesignations); - newAllDesignations.Remove(des); - __instance.allDesignations = newAllDesignations; - } - return false; - } - public static bool RemoveAllDesignationsOn(DesignationManager __instance, Thing t, bool standardCanceling = false) - { - bool matchFound = false; - for (int index = 0; index < __instance.allDesignations.Count; ++index) - { - Designation designation = __instance.allDesignations[index]; - if ((!standardCanceling || designation.def.designateCancelable) && designation.target.Thing == t) - { - designation.Notify_Removing(); - matchFound = true; - } - } - if (!matchFound) return false; - lock (__instance) - { - List newAllDesignations = new List(__instance.allDesignations); - newAllDesignations.RemoveAll(d => (!standardCanceling || d.def.designateCancelable) && d.target.Thing == t); - __instance.allDesignations = newAllDesignations; - } - - return false; - } - public static bool RemoveAllDesignationsOfDef(DesignationManager __instance, DesignationDef def) - { - lock (__instance) - { - List newAllDesignations = new List(__instance.allDesignations); - for (int index = newAllDesignations.Count - 1; index >= 0; --index) - { - if (newAllDesignations[index].def != def) continue; - - newAllDesignations[index].Notify_Removing(); - newAllDesignations.RemoveAt(index); - } - __instance.allDesignations = newAllDesignations; - } - - return false; - } - - public static bool AddDesignation(DesignationManager __instance, Designation newDes) - { - if (newDes.def.targetType == TargetType.Cell && __instance.DesignationAt(newDes.target.Cell, newDes.def) != null) - Log.Error("Tried to double-add designation at location " + newDes.target); - else if (newDes.def.targetType == TargetType.Thing && __instance.DesignationOn(newDes.target.Thing, newDes.def) != null) - { - Log.Error("Tried to double-add designation on Thing " + newDes.target); - } - else - { - if (newDes.def.targetType == TargetType.Thing) - newDes.target.Thing.SetForbidden(false, false); - lock (__instance) - { - __instance.allDesignations.Add(newDes); - } - - newDes.designationManager = __instance; - newDes.Notify_Added(); - Map map = newDes.target.HasThing ? newDes.target.Thing.Map : __instance.map; - if (map == null) - return false; -#if RW12 - MoteMaker.ThrowMetaPuffs(newDes.target.ToTargetInfo(map)); -#endif -#if RW13 - FleckMaker.ThrowMetaPuffs(newDes.target.ToTargetInfo(map)); -#endif - } - return false; - } - public static bool SpawnedDesignationsOfDef(DesignationManager __instance, ref IEnumerable __result, - DesignationDef def) - { - __result = SpawnedDesignationsOfDefEnumerable(__instance, def); - return false; - } - - public static IEnumerable SpawnedDesignationsOfDefEnumerable(DesignationManager __instance, - DesignationDef def) - { - List allDesignationsSnapshot = __instance.allDesignations; - int count = allDesignationsSnapshot.Count; - for (int i = 0; i < count; ++i) - { - Designation allDesignation = allDesignationsSnapshot[i]; - if (allDesignation.def == def && (!allDesignation.target.HasThing || allDesignation.target.Thing.Map == __instance.map)) - yield return allDesignation; - } - } - } -} diff --git a/Source/GenTemperature_Patch.cs b/Source/GenTemperature_Patch.cs deleted file mode 100644 index 99a6f5b9..00000000 --- a/Source/GenTemperature_Patch.cs +++ /dev/null @@ -1,107 +0,0 @@ -using System; -using System.Collections.Generic; -using RimWorld.Planet; -using Verse; - -namespace RimThreaded -{ - - public class GenTemperature_Patch - { -#if RW12 - [ThreadStatic] public static RoomGroup[] beqRoomGroups; -#endif -#if RW13 - [ThreadStatic] public static Room[] beqRooms; -#endif - - public static Dictionary SeasonalShiftAmplitudeCache = new Dictionary(); - public static Dictionary tileTemperature = new Dictionary(); - public static Dictionary> tileAbsTickTemperature = new Dictionary>(); - - static readonly Type original = typeof(GenTemperature); - static readonly Type patched = typeof(GenTemperature_Patch); - private static WorldGrid worldGrid; - public static void InitializeThreadStatics() - { -#if RW12 - beqRoomGroups = new RoomGroup[4]; -#endif -#if RW13 - beqRooms = new Room[4]; -#endif - - } - - public static void RunDestructivePatches() - { - RimThreadedHarmony.Prefix(original, patched, "GetTemperatureFromSeasonAtTile"); - RimThreadedHarmony.Prefix(original, patched, "SeasonalShiftAmplitudeAt"); - } - - public static bool SeasonalShiftAmplitudeAt(ref float __result, int tile) - { - WorldGrid newWorldGrid = Find.WorldGrid; - if (worldGrid != newWorldGrid) - { - worldGrid = newWorldGrid; - SeasonalShiftAmplitudeCache.Clear(); - tileAbsTickTemperature.Clear(); - tileTemperature.Clear(); - if (Prefs.LogVerbose) - { - Log.Message("RimThreaded is rebuilding WorldGrid Temperature Cache"); - } - } - - if (SeasonalShiftAmplitudeCache.TryGetValue(tile, out __result)) return false; - __result = Find.WorldGrid.LongLatOf(tile).y >= 0.0 ? - TemperatureTuning.SeasonalTempVariationCurve.Evaluate(newWorldGrid.DistanceFromEquatorNormalized(tile)) : - -TemperatureTuning.SeasonalTempVariationCurve.Evaluate(newWorldGrid.DistanceFromEquatorNormalized(tile)); - SeasonalShiftAmplitudeCache[tile] = __result; - return false; - } - public static bool GetTemperatureFromSeasonAtTile(ref float __result, int absTick, int tile) - { - WorldGrid newWorldGrid = Find.WorldGrid; - if (worldGrid != newWorldGrid) - { - worldGrid = newWorldGrid; - SeasonalShiftAmplitudeCache.Clear(); - tileAbsTickTemperature.Clear(); - tileTemperature.Clear(); - if (Prefs.LogVerbose) - { - Log.Message("RimThreaded is rebuilding WorldGrid Temperature Cache"); - } - } - if (absTick == 0) - { - absTick = 1; - } - - if (!tileAbsTickTemperature.TryGetValue(tile, out Dictionary absTickTemperature)) - { - absTickTemperature = new Dictionary(); - tileAbsTickTemperature[tile] = absTickTemperature; - } - - if (!absTickTemperature.TryGetValue(absTick, out float temperature)) - { - if (!tileTemperature.TryGetValue(tile, out float temperatureFromTile)) - { - temperatureFromTile = Find.WorldGrid[tile].temperature; - tileTemperature[tile] = temperatureFromTile; - } - temperature = temperatureFromTile + GenTemperature.OffsetFromSeasonCycle(absTick, tile); - lock (absTickTemperature) - { - absTickTemperature.SetOrAdd(absTick, temperature); - } - } - __result = temperature; - return false; - } - - } -} diff --git a/Source/GrammarResolver_Patch.cs b/Source/GrammarResolver_Patch.cs deleted file mode 100644 index deeaaceb..00000000 --- a/Source/GrammarResolver_Patch.cs +++ /dev/null @@ -1,126 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Reflection.Emit; -using HarmonyLib; -using Verse; -using Verse.Grammar; -using static HarmonyLib.AccessTools; -using static Verse.Grammar.GrammarResolver; - -namespace RimThreaded -{ - - public class GrammarResolver_Patch - { - private static readonly object ResolveUnsafeLock = new object(); - private static readonly object ResolveLock = new object(); - - //[ThreadStatic] public static Dictionary> rules = new Dictionary>(); - - public static Type original = typeof(GrammarResolver); - public static Type patched = typeof(GrammarResolver_Patch); - - //internal static void InitializeThreadStatics() - // { - // rules = new Dictionary>(); - //} - - internal static void RunNonDestructivePatches() - { - //RimThreadedHarmony.Transpile(original, patched, nameof(ResolveUnsafe), new Type[] { - // typeof(string), typeof(GrammarRequest), typeof(bool).MakeByRefType(), typeof(string), typeof(bool), typeof(bool), typeof(List), typeof(List), typeof(bool) - //}); - //RimThreadedHarmony.Transpile(original, patched, nameof(Resolve), new Type[] { - // typeof(string), typeof(GrammarRequest), typeof(string), typeof(bool), typeof(string), typeof(List), typeof(List), typeof(bool) - //}); - } - public static bool Resolve(ref string __result, string rootKeyword, GrammarRequest request, string debugLabel = null, bool forceLog = false, string untranslatedRootKeyword = null, List extraTags = null, List outTags = null, bool capitalizeFirstSentence = true) - { - lock (ResolveLock) - { - if (LanguageDatabase.activeLanguage == LanguageDatabase.defaultLanguage) - { - __result = GrammarResolver.ResolveUnsafe(rootKeyword, request, debugLabel, forceLog, useUntranslatedRules: false, extraTags, outTags, capitalizeFirstSentence); - return false; - } - string text; - bool success; - Exception ex; - try - { - text = GrammarResolver.ResolveUnsafe(rootKeyword, request, out success, debugLabel, forceLog, useUntranslatedRules: false, extraTags, outTags, capitalizeFirstSentence); - ex = null; - } - catch (Exception ex2) - { - success = false; - text = ""; - ex = ex2; - } - if (success) - { - __result = text; - return false; - } - string text2 = "Failed to resolve text. Trying again with English."; - if (ex != null) - { - text2 = text2 + " Exception: " + ex; - } - Log.ErrorOnce(text2, text.GetHashCode()); - outTags?.Clear(); - __result = GrammarResolver.ResolveUnsafe(untranslatedRootKeyword ?? rootKeyword, request, out success, debugLabel, forceLog, useUntranslatedRules: true, extraTags, outTags, capitalizeFirstSentence); - return false; - } - } - - public static IEnumerable ResolveUnsafe(IEnumerable instructions, ILGenerator iLGenerator) - { - List instructionsList = instructions.ToList(); - int i = 0; - List loadLockObjectInstructions = new List - { - new CodeInstruction(OpCodes.Ldsfld, Field(patched, nameof(ResolveUnsafeLock))) - }; - LocalBuilder lockObject = iLGenerator.DeclareLocal(typeof(object)); - LocalBuilder lockTaken = iLGenerator.DeclareLocal(typeof(bool)); - foreach (CodeInstruction ci in RimThreadedHarmony.EnterLock(lockObject, lockTaken, loadLockObjectInstructions, instructionsList[i])) - yield return ci; - while (i < instructionsList.Count - 2) - { - yield return instructionsList[i++]; - } - foreach (CodeInstruction ci in RimThreadedHarmony.ExitLock(iLGenerator, lockObject, lockTaken, instructionsList[i])) - yield return ci; - yield return instructionsList[i++]; - yield return instructionsList[i++]; - } - - public static IEnumerable Resolve(IEnumerable instructions, ILGenerator iLGenerator) - { - List instructionsList = instructions.ToList(); - int i = 0; - List loadLockObjectInstructions = new List - { - new CodeInstruction(OpCodes.Ldsfld, Field(patched, nameof(ResolveLock))) - }; - LocalBuilder lockObject = iLGenerator.DeclareLocal(typeof(object)); - LocalBuilder lockTaken = iLGenerator.DeclareLocal(typeof(bool)); - foreach (CodeInstruction ci in RimThreadedHarmony.EnterLock(lockObject, lockTaken, loadLockObjectInstructions, instructionsList[i])) - yield return ci; - while (i < instructionsList.Count - 1) - { - yield return instructionsList[i++]; - } - LocalBuilder stringResult = iLGenerator.DeclareLocal(typeof(string)); - yield return new CodeInstruction(OpCodes.Stloc, stringResult); - foreach (CodeInstruction ci in RimThreadedHarmony.ExitLock(iLGenerator, lockObject, lockTaken, instructionsList[i])) - yield return ci; - yield return new CodeInstruction(OpCodes.Ldloc, stringResult); - yield return instructionsList[i++]; - //yield return instructionsList[i++]; - } - - } -} \ No newline at end of file diff --git a/Source/GraphicDatabase_Patch.cs b/Source/GraphicDatabase_Patch.cs deleted file mode 100644 index 6f732ad7..00000000 --- a/Source/GraphicDatabase_Patch.cs +++ /dev/null @@ -1,181 +0,0 @@ -using System; -using System.Collections.Generic; -using UnityEngine; -using Verse; -using static RimThreaded.RimThreadedHarmony; -using static HarmonyLib.AccessTools; - -namespace RimThreaded -{ - class GraphicDatabase_Patch - { - public static void RunNonDestructivePatches() - { - replaceFields.Add(Method(typeof(GraphicDatabase), "Get", new Type[] { typeof(string) }, - new Type[] { typeof(Graphic_Single) }), - Method(typeof(GraphicDatabase_Patch), "Get", new Type[] { typeof(string) }, - new Type[] { typeof(Graphic_Single) })); - - replaceFields.Add(Method(typeof(GraphicDatabase), "Get", new Type[] { typeof(string), typeof(Shader) }, - new Type[] { typeof(Graphic_Single) }), - Method(typeof(GraphicDatabase_Patch), "Get", new Type[] { typeof(string), typeof(Shader) }, - new Type[] { typeof(Graphic_Single) })); - replaceFields.Add(Method(typeof(GraphicDatabase), "Get", new Type[] { typeof(string), typeof(Shader) }, - new Type[] { typeof(Graphic_Multi) }), - Method(typeof(GraphicDatabase_Patch), "Get", new Type[] { typeof(string), typeof(Shader) }, - new Type[] { typeof(Graphic_Multi) })); - - replaceFields.Add(Method(typeof(GraphicDatabase), "Get", new Type[] { typeof(string), typeof(Shader), typeof(Vector2), typeof(Color) }, - new Type[] { typeof(Graphic_Single) }), - Method(typeof(GraphicDatabase_Patch), "Get", new Type[] { typeof(string), typeof(Shader), typeof(Vector2), typeof(Color) }, - new Type[] { typeof(Graphic_Single) })); - replaceFields.Add(Method(typeof(GraphicDatabase), "Get", new Type[] { typeof(string), typeof(Shader), typeof(Vector2), typeof(Color) }, - new Type[] { typeof(Graphic_Multi) }), - Method(typeof(GraphicDatabase_Patch), "Get", new Type[] { typeof(string), typeof(Shader), typeof(Vector2), typeof(Color) }, - new Type[] { typeof(Graphic_Multi) })); - replaceFields.Add(Method(typeof(GraphicDatabase), "Get", new Type[] { typeof(string), typeof(Shader), typeof(Vector2), typeof(Color) }, - new Type[] { typeof(Graphic_Flicker) }), - Method(typeof(GraphicDatabase_Patch), "Get", new Type[] { typeof(string), typeof(Shader), typeof(Vector2), typeof(Color) }, - new Type[] { typeof(Graphic_Flicker) })); - - replaceFields.Add(Method(typeof(GraphicDatabase), "Get", new Type[] { typeof(string), typeof(Shader), typeof(Vector2), typeof(Color), typeof(int) }, - new Type[] { typeof(Graphic_Terrain) }), - Method(typeof(GraphicDatabase_Patch), "Get", new Type[] { typeof(string), typeof(Shader), typeof(Vector2), typeof(Color), typeof(int) }, - new Type[] { typeof(Graphic_Terrain) })); - - replaceFields.Add(Method(typeof(GraphicDatabase), "Get", new Type[] { typeof(string), typeof(Shader), typeof(Vector2), typeof(Color), typeof(Color), typeof(GraphicData), typeof(string) }, - new Type[] { typeof(Graphic_Single) }), - Method(typeof(GraphicDatabase_Patch), "Get", new Type[] { typeof(string), typeof(Shader), typeof(Vector2), typeof(Color), typeof(Color), typeof(GraphicData), typeof(string) }, - new Type[] { typeof(Graphic_Single) })); - replaceFields.Add(Method(typeof(GraphicDatabase), "Get", new Type[] { typeof(string), typeof(Shader), typeof(Vector2), typeof(Color), typeof(Color), typeof(GraphicData), typeof(string) }, - new Type[] { typeof(Graphic_Appearances) }), - Method(typeof(GraphicDatabase_Patch), "Get", new Type[] { typeof(string), typeof(Shader), typeof(Vector2), typeof(Color), typeof(Color), typeof(GraphicData), typeof(string) }, - new Type[] { typeof(Graphic_Appearances) })); - replaceFields.Add(Method(typeof(GraphicDatabase), "Get", new Type[] { typeof(string), typeof(Shader), typeof(Vector2), typeof(Color), typeof(Color), typeof(GraphicData), typeof(string) }, - new Type[] { typeof(Graphic_Multi) }), - Method(typeof(GraphicDatabase_Patch), "Get", new Type[] { typeof(string), typeof(Shader), typeof(Vector2), typeof(Color), typeof(Color), typeof(GraphicData), typeof(string) }, - new Type[] { typeof(Graphic_Multi) })); - replaceFields.Add(Method(typeof(GraphicDatabase), "Get", new Type[] { typeof(string), typeof(Shader), typeof(Vector2), typeof(Color), typeof(Color), typeof(GraphicData), typeof(string) }, - new Type[] { typeof(Graphic_StackCount) }), - Method(typeof(GraphicDatabase_Patch), "Get", new Type[] { typeof(string), typeof(Shader), typeof(Vector2), typeof(Color), typeof(Color), typeof(GraphicData), typeof(string) }, - new Type[] { typeof(Graphic_StackCount) })); - replaceFields.Add(Method(typeof(GraphicDatabase), "Get", new Type[] { typeof(string), typeof(Shader), typeof(Vector2), typeof(Color), typeof(Color), typeof(GraphicData), typeof(string) }, - new Type[] { typeof(Graphic_Random) }), - Method(typeof(GraphicDatabase_Patch), "Get", new Type[] { typeof(string), typeof(Shader), typeof(Vector2), typeof(Color), typeof(Color), typeof(GraphicData), typeof(string) }, - new Type[] { typeof(Graphic_Random) })); - - replaceFields.Add(Method(typeof(GraphicDatabase), "Get", new Type[] { typeof(Type), typeof(string), typeof(Shader), typeof(Vector2), typeof(Color), typeof(Color), typeof(string) }), - Method(typeof(GraphicDatabase_Patch), "Get", new Type[] { typeof(Type), typeof(string), typeof(Shader), typeof(Vector2), typeof(Color), typeof(Color), typeof(string) })); - - replaceFields.Add(Method(typeof(GraphicDatabase), "Get", new Type[] { typeof(Type), typeof(string), typeof(Shader), typeof(Vector2), typeof(Color), typeof(Color), typeof(GraphicData), typeof(List), typeof(string) }), - Method(typeof(GraphicDatabase_Patch), "Get", new Type[] { typeof(Type), typeof(string), typeof(Shader), typeof(Vector2), typeof(Color), typeof(Color), typeof(GraphicData), typeof(List), typeof(string) })); - - } - - public static Graphic Get(string path) where T : Graphic, new() - { - return GetInner(new GraphicRequest(typeof(T), path, ShaderDatabase.Cutout, Vector2.one, Color.white, Color.white, null, 0, null, null)); - } - - public static Graphic Get(string path, Shader shader) where T : Graphic, new() - { - return GetInner(new GraphicRequest(typeof(T), path, shader, Vector2.one, Color.white, Color.white, null, 0, null, null)); - } - - public static Graphic Get(string path, Shader shader, Vector2 drawSize, Color color) where T : Graphic, new() - { - return GetInner(new GraphicRequest(typeof(T), path, shader, drawSize, color, Color.white, null, 0, null, null)); - } - - public static Graphic Get(string path, Shader shader, Vector2 drawSize, Color color, int renderQueue) where T : Graphic, new() - { - return GetInner(new GraphicRequest(typeof(T), path, shader, drawSize, color, Color.white, null, renderQueue, null, null)); - } - - public static Graphic Get(string path, Shader shader, Vector2 drawSize, Color color, Color colorTwo) where T : Graphic, new() - { - return GetInner(new GraphicRequest(typeof(T), path, shader, drawSize, color, colorTwo, null, 0, null, null)); - } - - public static Graphic Get(string path, Shader shader, Vector2 drawSize, Color color, Color colorTwo, GraphicData data, string maskPath = null) where T : Graphic, new() - { - return GetInner(new GraphicRequest(typeof(T), path, shader, drawSize, color, colorTwo, data, 0, null, maskPath)); - } - - public static Graphic Get(Type graphicClass, string path, Shader shader, Vector2 drawSize, Color color, Color colorTwo, string maskPath = null) - { - return Get(graphicClass, path, shader, drawSize, color, colorTwo, null, null, maskPath); - } - - public static Graphic Get(Type graphicClass, string path, Shader shader, Vector2 drawSize, Color color, Color colorTwo, GraphicData data, List shaderParameters, string maskPath = null) - { - GraphicRequest graphicRequest = new GraphicRequest(graphicClass, path, shader, drawSize, color, colorTwo, data, 0, shaderParameters, maskPath); - if (graphicRequest.graphicClass == typeof(Graphic_Single)) - { - return GetInner(graphicRequest); - } - if (graphicRequest.graphicClass == typeof(Graphic_Terrain)) - { - return GetInner(graphicRequest); - } - if (graphicRequest.graphicClass == typeof(Graphic_Multi)) - { - return GetInner(graphicRequest); - } - if (graphicRequest.graphicClass == typeof(Graphic_Mote)) - { - return GetInner(graphicRequest); - } - if (graphicRequest.graphicClass == typeof(Graphic_Random)) - { - return GetInner(graphicRequest); - } - if (graphicRequest.graphicClass == typeof(Graphic_Flicker)) - { - return GetInner(graphicRequest); - } - if (graphicRequest.graphicClass == typeof(Graphic_Appearances)) - { - return GetInner(graphicRequest); - } - if (graphicRequest.graphicClass == typeof(Graphic_StackCount)) - { - return GetInner(graphicRequest); - } - try - { - return (Graphic)GenGeneric.InvokeStaticGenericMethod(typeof(GraphicDatabase), graphicRequest.graphicClass, "GetInner", graphicRequest); - } - catch (Exception ex) - { - Log.Error(string.Concat("Exception getting ", graphicClass, " at ", path, ": ", ex.ToString())); - } - return BaseContent.BadGraphic; - } - - - public static T GetInner(GraphicRequest req) where T : Graphic, new() - { - req.color = (Color32)req.color; - req.colorTwo = (Color32)req.colorTwo; - req.renderQueue = ((req.renderQueue == 0 && req.graphicData != null) ? req.graphicData.renderQueue : req.renderQueue); - if (!GraphicDatabase.allGraphics.TryGetValue(req, out var value)) - { - lock (GraphicDatabase.allGraphics) - { - if (!GraphicDatabase.allGraphics.TryGetValue(req, out var value2)) - { - value = new T(); - value.Init(req); - GraphicDatabase.allGraphics.Add(req, value); - } - else - { - value = value2; - } - } - } - return (T)value; - } - } -} diff --git a/Source/HaulingCache.cs b/Source/HaulingCache.cs index 703d0212..c17daff0 100644 --- a/Source/HaulingCache.cs +++ b/Source/HaulingCache.cs @@ -4,16 +4,17 @@ using UnityEngine; using Verse; using Verse.AI; -using static RimThreaded.Area_Patch; +using static RimThreaded.RW_Patches.Area_Patch; using static Verse.AI.ReservationManager; using static HarmonyLib.AccessTools; using System.Reflection; +using RimThreaded.RW_Patches; namespace RimThreaded { - class HaulingCache + class HaulingCache { - static readonly Dictionary[]> waitingForZoneBetterThanMapDict = new Dictionary[]>(); //each Map has sets of Things for each storage priority (typically 6) + public static readonly Dictionary[]> waitingForZoneBetterThanMapDict = new Dictionary[]>(); //each Map has sets of Things for each storage priority (typically 6) public static List zoomLevels = new List(); public static Dictionary[]>> awaitingHaulingMapDict = new Dictionary[]>>(); public const float ZOOM_MULTIPLIER = 1.5f; //must be greater than 1. lower numbers will make searches slower, but ensure pawns find the closer things first. @@ -529,10 +530,12 @@ public static Thing ClosestThingReachable(Pawn pawn, WorkGiver_Scanner scanner, { if (scanner.HasJobOnThing(pawn, tryThing)) { + /* if (Prefs.LogVerbose) { Log.Message(pawn + " is going to haul thing: " + tryThing + " at pos " + tryThing.Position); } + */ thing = tryThing; break; } diff --git a/Source/Hauling_Transpile.cs b/Source/Hauling_Transpile.cs deleted file mode 100644 index 4c1a1c46..00000000 --- a/Source/Hauling_Transpile.cs +++ /dev/null @@ -1,61 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Reflection; -using System.Reflection.Emit; -using HarmonyLib; -using Verse; -using static RimThreaded.RimThreadedHarmony; - -namespace RimThreaded -{ - class Hauling_Transpile - { - public static IEnumerable CanHaul(IEnumerable instructions, ILGenerator iLGenerator) - { - int[] matchesFound = new int[1]; //EDIT - Type dictionary_Thing_IntVec3 = typeof(Dictionary); //EDIT - List instructionsList = instructions.ToList(); - int i = 0; - while (i < instructionsList.Count) - { - int matchIndex = 0; - if ( - i + 5 < instructionsList.Count && //EDIT - instructionsList[i].opcode == OpCodes.Ldsfld && //EDIT - (FieldInfo)instructionsList[i].operand == cachedStoreCell && //EDIT - instructionsList[i + 5].opcode == OpCodes.Call //EDIT - ) - { - List loadLockObjectInstructions = new List - { - new CodeInstruction(OpCodes.Ldsfld, cachedStoreCell) //EDIT - }; - LocalBuilder lockObject = iLGenerator.DeclareLocal(dictionary_Thing_IntVec3); //EDIT - LocalBuilder lockTaken = iLGenerator.DeclareLocal(typeof(bool)); - foreach (CodeInstruction ci in EnterLock(lockObject, lockTaken, loadLockObjectInstructions, instructionsList[i])) - yield return ci; - - while (i < instructionsList.Count) - { - if ( - instructionsList[i - 1].opcode == OpCodes.Call //EDIT - ) - break; - yield return instructionsList[i++]; - } - foreach (CodeInstruction ci in ExitLock(iLGenerator, lockObject, lockTaken, instructionsList[i])) - yield return ci; - matchesFound[matchIndex]++; - continue; - } - yield return instructionsList[i++]; - } - for (int mIndex = 0; mIndex < matchesFound.Length; mIndex++) - { - if (matchesFound[mIndex] < 1) - Log.Error("IL code instruction set " + mIndex + " not found"); - } - } - } -} diff --git a/Source/HediffGiver_Heat_Patch.cs b/Source/HediffGiver_Heat_Patch.cs deleted file mode 100644 index b1730dac..00000000 --- a/Source/HediffGiver_Heat_Patch.cs +++ /dev/null @@ -1,61 +0,0 @@ -using System; -using RimWorld; -using UnityEngine; -using Verse; -using Verse.AI.Group; - -namespace RimThreaded -{ - class HediffGiver_Heat_Patch - { - internal static void RunDestructivePatches() - { - Type original = typeof(HediffGiver_Heat); - Type patched = typeof(HediffGiver_Heat_Patch); - RimThreadedHarmony.Prefix(original, patched, "OnIntervalPassed"); - } - - public static bool OnIntervalPassed(HediffGiver_Heat __instance, Pawn pawn, Hediff cause) - { - float ambientTemperature = pawn.AmbientTemperature; - float comfortableTemperatureMax = pawn.GetStatValue(StatDefOf.ComfyTemperatureMax); - float maxTemp = comfortableTemperatureMax + 10f; - Hediff firstHediffOfDef = pawn.health.hediffSet.GetFirstHediffOfDef(__instance.hediff); - if (ambientTemperature > maxTemp) - { - float x = ambientTemperature - maxTemp; - float sevOffset = Mathf.Max(HediffGiver_Heat.TemperatureOverageAdjustmentCurve.Evaluate(x) * 6.45E-05f, 0.000375f); - HealthUtility.AdjustSeverity(pawn, __instance.hediff, sevOffset); - } - else if (firstHediffOfDef != null && ambientTemperature < comfortableTemperatureMax) - { - float num = Mathf.Clamp(firstHediffOfDef.Severity * 0.027f, 0.0015f, 0.015f); - firstHediffOfDef.Severity -= num; - } - if (pawn.Dead || !pawn.IsNestedHashIntervalTick(60, 420)) - return false; - - float num4 = comfortableTemperatureMax + 150f; - if (ambientTemperature <= num4) - return false; - - float x1 = ambientTemperature - num4; - int num2 = Mathf.Max(GenMath.RoundRandom(HediffGiver_Heat.TemperatureOverageAdjustmentCurve.Evaluate(x1) * 0.06f), 3); - DamageInfo dinfo = new DamageInfo(DamageDefOf.Burn, num2); - dinfo.SetBodyRegion(BodyPartHeight.Undefined, BodyPartDepth.Outside); - pawn.TakeDamage(dinfo); - if (pawn.Faction == Faction.OfPlayer) - { - Find.TickManager.slower.SignalForceNormalSpeed(); - if (MessagesRepeatAvoider.MessageShowAllowed("PawnBeingBurned", 60f)) - { - Messages.Message("MessagePawnBeingBurned".Translate(pawn.LabelShort, pawn), pawn, MessageTypeDefOf.ThreatSmall, true); - } - } - pawn.GetLord()?.ReceiveMemo(HediffGiver_Heat.MemoPawnBurnedByAir); - - return false; - } - - } -} diff --git a/Source/HediffGiver_Hypothermia_Patch.cs b/Source/HediffGiver_Hypothermia_Patch.cs deleted file mode 100644 index 3aa1952c..00000000 --- a/Source/HediffGiver_Hypothermia_Patch.cs +++ /dev/null @@ -1,52 +0,0 @@ -using System.Linq; -using RimWorld; -using UnityEngine; -using Verse; - -namespace RimThreaded -{ - class HediffGiver_Hypothermia_Patch - { - public static bool OnIntervalPassed(HediffGiver_Hypothermia __instance, Pawn pawn, Hediff cause) - { - float ambientTemperature = pawn.AmbientTemperature; - //FloatRange floatRange = pawn.ComfortableTemperatureRange(); //REMOVED - //FloatRange floatRange2 = pawn.SafeTemperatureRange(); //REMOVED - float comfortableTemperatureMin = pawn.GetStatValue(StatDefOf.ComfyTemperatureMin); //ADDED - float minTemp = comfortableTemperatureMin - 10f; //ADDED - HediffSet hediffSet = pawn.health.hediffSet; - HediffDef hediffDef = pawn.RaceProps.FleshType == FleshTypeDefOf.Insectoid ? __instance.hediffInsectoid : __instance.hediff; - Hediff firstHediffOfDef = hediffSet.GetFirstHediffOfDef(hediffDef); - //if (ambientTemperature < floatRange2.min) //REMOVED - if (ambientTemperature < minTemp) //ADDED - { - //float a = Mathf.Abs(ambientTemperature - floatRange2.min) * 6.45E-05f; //REMOVED - float a = Mathf.Abs(ambientTemperature - minTemp) * 6.45E-05f; //ADDED - a = Mathf.Max(a, 0.00075f); - HealthUtility.AdjustSeverity(pawn, hediffDef, a); - if (pawn.Dead) - return false; - } - if (firstHediffOfDef == null) - return false; - //if (ambientTemperature > floatRange.min) //REMOVED - if (ambientTemperature > comfortableTemperatureMin) //ADDED - { - float value = firstHediffOfDef.Severity * 0.027f; - value = Mathf.Clamp(value, 0.0015f, 0.015f); - firstHediffOfDef.Severity -= value; - } - else if (pawn.RaceProps.FleshType != FleshTypeDefOf.Insectoid && ambientTemperature < 0f && firstHediffOfDef.Severity > 0.37f) - { - float num = 0.025f * firstHediffOfDef.Severity; - if (Rand.Value < num && pawn.RaceProps.body.AllPartsVulnerableToFrostbite.Where(x => !hediffSet.PartIsMissing(x)).TryRandomElementByWeight(x => x.def.frostbiteVulnerability, out BodyPartRecord result)) - { - int num2 = Mathf.CeilToInt(result.def.hitPoints * 0.5f); - DamageInfo dinfo = new DamageInfo(DamageDefOf.Frostbite, num2, 0f, -1f, null, result); - pawn.TakeDamage(dinfo); - } - } - return false; - } - } -} diff --git a/Source/HediffGiver_Hypothermia_Transpile.cs b/Source/HediffGiver_Hypothermia_Transpile.cs deleted file mode 100644 index 5eca49d9..00000000 --- a/Source/HediffGiver_Hypothermia_Transpile.cs +++ /dev/null @@ -1,67 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Reflection; -using System.Reflection.Emit; -using HarmonyLib; -using RimWorld; -using Verse; - -namespace RimThreaded -{ - public class HediffGiver_Hypothermia_Transpile - { - internal static void RunNonDestructivePatches() - { - Type original = typeof(HediffGiver_Hypothermia); - Type patched = typeof(HediffGiver_Hypothermia_Transpile); - RimThreadedHarmony.Transpile(original, patched, "OnIntervalPassed"); - } - public static IEnumerable OnIntervalPassed(IEnumerable instructions, ILGenerator iLGenerator) - { - LocalBuilder comfortableTemperatureMin = iLGenerator.DeclareLocal(typeof(float)); - LocalBuilder minTemp = iLGenerator.DeclareLocal(typeof(float)); - - List instructionsList = instructions.ToList(); - int i = 0; - - - while (i < instructionsList.Count) - { - if (i + 1 < instructionsList.Count && - instructionsList[i].opcode == OpCodes.Ldarg_1 && - instructionsList[i + 1].opcode == OpCodes.Call && - (MethodInfo)instructionsList[i + 1].operand == AccessTools.Method(typeof(GenTemperature), "ComfortableTemperatureRange", new Type[] { typeof(Pawn) }) - ) { - yield return new CodeInstruction(OpCodes.Ldarg_1); - yield return new CodeInstruction(OpCodes.Ldsfld, AccessTools.Field(typeof(StatDefOf), "ComfyTemperatureMin")); - yield return new CodeInstruction(OpCodes.Ldc_I4_1); - yield return new CodeInstruction(OpCodes.Call, AccessTools.Method(typeof(StatExtension), "GetStatValue")); - yield return new CodeInstruction(OpCodes.Stloc, comfortableTemperatureMin.LocalIndex); - yield return new CodeInstruction(OpCodes.Ldloc, comfortableTemperatureMin.LocalIndex); - yield return new CodeInstruction(OpCodes.Ldc_R4, 10f); - yield return new CodeInstruction(OpCodes.Sub); - yield return new CodeInstruction(OpCodes.Stloc, minTemp.LocalIndex); - i += 6; - } - else if (instructionsList[i].opcode == OpCodes.Ldloc_3) - { - yield return new CodeInstruction(OpCodes.Ldloc, minTemp.LocalIndex); - i += 2; - } - else if (instructionsList[i].opcode == OpCodes.Ldloc_2) - { - yield return new CodeInstruction(OpCodes.Ldloc, comfortableTemperatureMin.LocalIndex); - i += 2; - } - else - { - yield return instructionsList[i]; - i++; - } - } - - } - - } -} diff --git a/Source/JobGiver_Work_Patch.cs b/Source/JobGiver_Work_Patch.cs deleted file mode 100644 index 45435765..00000000 --- a/Source/JobGiver_Work_Patch.cs +++ /dev/null @@ -1,384 +0,0 @@ -using System; -using System.Collections.Generic; -using RimWorld; -using Verse; -using Verse.AI; - -namespace RimThreaded -{ - - public class JobGiver_Work_Patch - { - internal static void RunDestructivePatches() - { - Type original = typeof(JobGiver_Work); - Type patched = typeof(JobGiver_Work_Patch); - RimThreadedHarmony.Prefix(original, patched, "TryIssueJobPackage"); - } - public static bool TryIssueJobPackage(JobGiver_Work __instance, ref ThinkResult __result, Pawn pawn, JobIssueParams jobParams) - { -#if DEBUG - DateTime startTime = DateTime.Now; -#endif - if (__instance.emergency && pawn.mindState.priorityWork.IsPrioritized) - { - List workGiversByPriority = pawn.mindState.priorityWork.WorkGiver.workType.workGiversByPriority; - for (int i = 0; i < workGiversByPriority.Count; i++) - { - WorkGiver worker = workGiversByPriority[i].Worker; - if (__instance.WorkGiversRelated(pawn.mindState.priorityWork.WorkGiver, worker.def)) - { - Job job = GiverTryGiveJobPrioritized(__instance, pawn, worker, pawn.mindState.priorityWork.Cell); - if (job != null) - { - job.playerForced = true; - __result = new ThinkResult(job, __instance, workGiversByPriority[i].tagToGive); - return false; - } - } - } - pawn.mindState.priorityWork.Clear(); - } - List list = (!__instance.emergency) ? pawn.workSettings.WorkGiversInOrderNormal : pawn.workSettings.WorkGiversInOrderEmergency; - int num = -999; - TargetInfo bestTargetOfLastPriority = TargetInfo.Invalid; - WorkGiver_Scanner scannerWhoProvidedTarget = null; - WorkGiver_Scanner scanner; - IntVec3 pawnPosition; - float closestDistSquared; - float bestPriority; - bool prioritized; - bool allowUnreachable; - Danger maxPathDanger; - for (int j = 0; j < list.Count; j++) - { - WorkGiver workGiver = list[j]; - if (workGiver.def.priorityInType != num && bestTargetOfLastPriority.IsValid) - { - break; - } - if (!__instance.PawnCanUseWorkGiver(pawn, workGiver)) - { - continue; - } - try - { - Job job2 = workGiver.NonScanJob(pawn); - if (job2 != null) - { - __result = new ThinkResult(job2, __instance, workGiver.def.tagToGive); - return false; - } - scanner = (workGiver as WorkGiver_Scanner); - - if (scanner != null) - { - if (scanner.def.scanThings) - { -//----------------------THERE HAVE BEEN NO CHANGES ABOVE THIS--------------------------------- - - Predicate validator; - if (scanner is WorkGiver_DoBill workGiver_DoBill) - { - validator = (Thing t) => !t.IsForbidden(pawn) && WorkGiver_Scanner_Patch.HasJobOnThing(workGiver_DoBill, pawn, t); - } - else - { - validator = (Thing t) => !t.IsForbidden(pawn) && scanner.HasJobOnThing(pawn, t); - } - IEnumerable enumerable = scanner.PotentialWorkThingsGlobal(pawn); - Thing thing; - if (scanner.Prioritized) - { - IEnumerable enumerable2 = enumerable; - if (enumerable2 == null) - { - enumerable2 = pawn.Map.listerThings.ThingsMatching(scanner.PotentialWorkThingRequest); - } - thing = ((!scanner.AllowUnreachable) ? - GenClosest.ClosestThing_Global_Reachable(pawn.Position, pawn.Map, enumerable2, scanner.PathEndMode, TraverseParms.For(pawn, scanner.MaxPathDanger(pawn)), 9999f, validator, (Thing x) => scanner.GetPriority(pawn, x)) : - GenClosest.ClosestThing_Global(pawn.Position, enumerable2, 99999f, validator, (Thing x) => scanner.GetPriority(pawn, x))); - } - else if (scanner.AllowUnreachable) - { - IEnumerable enumerable3 = enumerable; - if (enumerable3 == null) - { - enumerable3 = pawn.Map.listerThings.ThingsMatching(scanner.PotentialWorkThingRequest); - } - thing = GenClosest.ClosestThing_Global(pawn.Position, enumerable3, 99999f, validator); - } - else - { - //TODO: use better ThingRequest groups - if ( - workGiver.def.defName.Equals("DoctorFeedAnimals") || - workGiver.def.defName.Equals("DoctorFeedHumanlikes") || - workGiver.def.defName.Equals("DoctorTendToAnimals") || - workGiver.def.defName.Equals("DoctorTendToHumanlikes") || - workGiver.def.defName.Equals("DoBillsUseCraftingSpot") || - workGiver.def.defName.Equals("DoctorTendEmergency") || - workGiver.def.defName.Equals("HaulCorpses") || - workGiver.def.defName.Equals("FillFermentingBarrel") || - workGiver.def.defName.Equals("HandlingFeedPatientAnimals") || - workGiver.def.defName.Equals("Train") || - workGiver.def.defName.Equals("VisitSickPawn") || - workGiver.def.defName.Equals("DoBillsButcherFlesh") || - workGiver.def.defName.Equals("DoBillsCook") || - workGiver.def.defName.Equals("DoBillsMakeApparel") - ) - { - //long - thing = GenClosest_Patch.ClosestThingReachable2(pawn.Position, pawn.Map, scanner.PotentialWorkThingRequest, scanner.PathEndMode, TraverseParms.For(pawn, scanner.MaxPathDanger(pawn)), 9999f, validator, enumerable, 0, scanner.MaxRegionsToScanBeforeGlobalSearch, enumerable != null); - } - else if ( - workGiver.def.defName.Equals("HaulGeneral") - ) - { - //long - thing = HaulingCache.ClosestThingReachable(pawn, scanner, pawn.Map, scanner.PotentialWorkThingRequest, scanner.PathEndMode, TraverseParms.For(pawn, scanner.MaxPathDanger(pawn)), 9999f, validator, enumerable, 0, scanner.MaxRegionsToScanBeforeGlobalSearch, enumerable != null); - } - /* - else if( - workGiver.def.defName.Equals("DoBillsButcherFlesh") || - workGiver.def.defName.Equals("DoBillsCook") || - workGiver.def.defName.Equals("DoBillsMakeApparel")) - { - - thing = null; - //ThingGrid_Patch - int mapSizeX = pawn.Map.Size.x; - int mapSizeZ = pawn.Map.Size.z; - int index = pawn.Map.cellIndices.CellToIndex(pawn.Position); - //Dictionary billPointsDict = ThingGrid_Patch.thingBillPoints[t.def]; - Dictionary[]>>> ingredientDict = ThingGrid_Patch.mapIngredientDict[pawn.Map]; - ThingRequest thingReq = scanner.PotentialWorkThingRequest; - if(!ingredientDict.TryGetValue(scanner, out Dictionary[]>> scoreToJumboCellsList)) { - scoreToJumboCellsList = new Dictionary[]>>(); - List thingsMatchingRequest = pawn.Map.listerThings.ThingsMatching(thingReq); - } - - } - */ - else - { - //long - thing = GenClosest.ClosestThingReachable(pawn.Position, pawn.Map, scanner.PotentialWorkThingRequest, scanner.PathEndMode, TraverseParms.For(pawn, scanner.MaxPathDanger(pawn)), 9999f, validator, enumerable, 0, scanner.MaxRegionsToScanBeforeGlobalSearch, enumerable != null); - } - } - if (thing != null) - { - bestTargetOfLastPriority = thing; - scannerWhoProvidedTarget = scanner; - } - } - if (scanner.def.scanCells) - { - pawnPosition = pawn.Position; - closestDistSquared = 99999f; - bestPriority = float.MinValue; - prioritized = scanner.Prioritized; - allowUnreachable = scanner.AllowUnreachable; - maxPathDanger = scanner.MaxPathDanger(pawn); - IEnumerable enumerable4; - if (scanner is WorkGiver_GrowerSow workGiver_Grower) - { - //RimThreaded.WorkGiver_GrowerSow_Patch_JobOnCell = 0; - - //thing = HaulingCache.ClosestThingReachable(pawn, scanner, pawn.Map, scanner.PotentialWorkThingRequest, scanner.PathEndMode, TraverseParms.For(pawn, scanner.MaxPathDanger(pawn)), 9999f, validator, enumerable, 0, scanner.MaxRegionsToScanBeforeGlobalSearch, enumerable != null); - IntVec3 bestCell = WorkGiver_Grower_Patch.ClosestLocationReachable(workGiver_Grower, pawn); - //Log.Message(bestCell.ToString()); - if (bestCell.IsValid) - { - bestTargetOfLastPriority = new TargetInfo(bestCell, pawn.Map); - scannerWhoProvidedTarget = scanner; - } - //Log.Message(RimThreaded.WorkGiver_GrowerSow_Patch_JobOnCell.ToString()); - } - else if(scanner is WorkGiver_GrowerHarvest workGiver_GrowerHarvest) - { - IntVec3 bestCell = WorkGiver_GrowerHarvest_Patch.ClosestLocationReachable(workGiver_GrowerHarvest, pawn); - if (bestCell.IsValid) - { - bestTargetOfLastPriority = new TargetInfo(bestCell, pawn.Map); - scannerWhoProvidedTarget = scanner; - } - /* - enumerable4 = workGiver_GrowerHarvest.PotentialWorkCellsGlobal(pawn); - IList list2; - if ((list2 = (enumerable4 as IList)) != null) - { - for (int k = 0; k < list2.Count; k++) - { - ProcessCell(list2[k]); - } - } - else - { - foreach (IntVec3 item in enumerable4) - { - ProcessCell(item); - } - } - */ - } - else - { - enumerable4 = scanner.PotentialWorkCellsGlobal(pawn); - IList list2; - if ((list2 = (enumerable4 as IList)) != null) - { - for (int k = 0; k < list2.Count; k++) - { - ProcessCell(list2[k]); - } - } - else - { - foreach (IntVec3 item in enumerable4) - { - ProcessCell(item); - } - } - } - - } - } - void ProcessCell(IntVec3 c) - { - float newDistanceSquared = (c - pawnPosition).LengthHorizontalSquared; - float newPriority = 0f; - - if (prioritized) - { - newPriority = scanner.GetPriority(pawn, c); - if (newPriority < bestPriority) - { - return; - } - } - - if (newDistanceSquared < closestDistSquared && !c.IsForbidden(pawn) && scanner.HasJobOnCell(pawn, c)) - { - if (!allowUnreachable && !pawn.CanReach(c, scanner.PathEndMode, maxPathDanger)) - { - return; - } - - bestTargetOfLastPriority = new TargetInfo(c, pawn.Map); - scannerWhoProvidedTarget = scanner; - closestDistSquared = newDistanceSquared; - bestPriority = newPriority; - } - } - } - catch (Exception ex) - { - Log.Error(string.Concat(pawn, " threw exception in WorkGiver ", workGiver.def.defName, ": ", ex.ToString())); - } - finally - { - } - if (bestTargetOfLastPriority.IsValid) - { - Job job3 = (!bestTargetOfLastPriority.HasThing) ? scannerWhoProvidedTarget.JobOnCell(pawn, bestTargetOfLastPriority.Cell) : scannerWhoProvidedTarget.JobOnThing(pawn, bestTargetOfLastPriority.Thing); - if (job3 != null) - { - job3.workGiverDef = scannerWhoProvidedTarget.def; - __result = new ThinkResult(job3, __instance, workGiver.def.tagToGive); - return false; - } - - //If this was a cached plant job, deregister it and check if it is still valid to be registered - if (scannerWhoProvidedTarget is WorkGiver_GrowerSow) - { - Map map = pawn.Map; - IntVec3 cell = bestTargetOfLastPriority.Cell; - JumboCell.ReregisterObject(map, cell, RimThreaded.plantSowing_Cache); - } - //HACK - I know. I'm awful. - //Log.ErrorOnce(string.Concat(scannerWhoProvidedTarget, " provided target ", bestTargetOfLastPriority, " but yielded no actual job for pawn ", pawn, ". The CanGiveJob and JobOnX methods may not be synchronized."), 6112651); - if (Prefs.LogVerbose) { - Log.Warning(string.Concat(scannerWhoProvidedTarget, " provided target ", bestTargetOfLastPriority, " but yielded no actual job for pawn ", pawn, ". The CanGiveJob and JobOnX methods may not be synchronized.")); - } - } - num = workGiver.def.priorityInType; - -#if DEBUG - int milli99 = (int)DateTime.Now.Subtract(startTime).TotalMilliseconds; - if (milli99 > 300) - { - Log.Warning("99 JobGiver_Work.TryIssueJobPackage Took over " + milli99.ToString() + "ms for workGiver: " + workGiver.def.defName); - //Log.Warning(scanner.PotentialWorkThingRequest.ToString()); - //Log.Warning(validator.ToString()); - } -#endif - - - } - __result = ThinkResult.NoJob; - return false; - } - - private static Job GiverTryGiveJobPrioritized(JobGiver_Work __instance, Pawn pawn, WorkGiver giver, IntVec3 cell) - { - if (!__instance.PawnCanUseWorkGiver(pawn, giver)) - { - return null; - } - try - { - Job job = giver.NonScanJob(pawn); - if (job != null) - { - return job; - } - WorkGiver_Scanner scanner = giver as WorkGiver_Scanner; - if (scanner != null) - { - if (giver.def.scanThings) - { - Predicate predicate; - if (scanner is WorkGiver_DoBill workGiver_DoBill) - { - predicate = (Thing t) => !t.IsForbidden(pawn) && WorkGiver_Scanner_Patch.HasJobOnThing(workGiver_DoBill, pawn, t); - } - else - { - predicate = (Thing t) => !t.IsForbidden(pawn) && scanner.HasJobOnThing(pawn, t); - } - - List thingList = cell.GetThingList(pawn.Map); - for (int i = 0; i < thingList.Count; i++) - { - Thing thing = thingList[i]; - if (scanner.PotentialWorkThingRequest.Accepts(thing) && predicate(thing)) - { - Job job2 = scanner.JobOnThing(pawn, thing); - if (job2 != null) - { - job2.workGiverDef = giver.def; - } - return job2; - } - } - } - if (giver.def.scanCells && !cell.IsForbidden(pawn) && scanner.HasJobOnCell(pawn, cell)) - { - Job job3 = scanner.JobOnCell(pawn, cell); - if (job3 != null) - { - job3.workGiverDef = giver.def; - } - return job3; - } - } - } - catch (Exception ex) - { - Log.Error(string.Concat(pawn, " threw exception in GiverTryGiveJobTargeted on WorkGiver ", giver.def.defName, ": ", ex.ToString())); - } - return null; - } - } -} diff --git a/Source/JumboCell.cs b/Source/JumboCell.cs index 80b8b4b8..e9c6a71b 100644 --- a/Source/JumboCell.cs +++ b/Source/JumboCell.cs @@ -4,7 +4,7 @@ using System.Linq; using UnityEngine; using Verse; -using static RimThreaded.Area_Patch; +using static RimThreaded.RW_Patches.Area_Patch; namespace RimThreaded { @@ -14,13 +14,15 @@ static class JumboCell static readonly IntVec3[] noOffset = new IntVec3[] { IntVec3.Zero }; private static readonly List zoomLevels = new List(); private const float ZOOM_MULTIPLIER = 1.5f; - const int sixteen = 16; + internal static void InitializeThreadStatics() { retrunedThings = new HashSet(); } public static void ReregisterObject(Map map, IntVec3 location, JumboCell_Cache jumboCell_Cache) { + if (!location.IsValid) + return; Dictionary[]>> positionsAwaitingAction = jumboCell_Cache.positionsAwaitingAction; //try to remove an item that has a null map. only way is to check all maps... if (map == null) @@ -33,7 +35,7 @@ public static void ReregisterObject(Map map, IntVec3 location, JumboCell_Cache j } return; } - List[]> awaitingActionZoomLevels = GetAwaitingActionsZoomLevels(jumboCell_Cache.positionsAwaitingAction, map); + List[]> awaitingActionZoomLevels = GetAwaitingActionsZoomLevels(jumboCell_Cache.positionsAwaitingAction, map, jumboCell_Cache); RemoveObjectFromAwaitingActionHashSets(map, location, awaitingActionZoomLevels); if (jumboCell_Cache.IsActionableObject(map, location)) AddObjectToActionableObjects(map, location, awaitingActionZoomLevels); @@ -232,7 +234,7 @@ public static IEnumerable GetClosestActionableLocations(Pawn pawn, Map int mapSizeX = map.Size.x; retrunedThings.Clear(); IntVec3[] objectsAtCellCopy; - List[]> awaitingActionZoomLevels = GetAwaitingActionsZoomLevels(jumboCell_Cache.positionsAwaitingAction, map); + List[]> awaitingActionZoomLevels = GetAwaitingActionsZoomLevels(jumboCell_Cache.positionsAwaitingAction, map, jumboCell_Cache); IntVec3 position = pawn.Position; Area effectiveAreaRestrictionInPawnCurrentMap = pawn.playerSettings.EffectiveAreaRestrictionInPawnCurrentMap; Range2D areaRange = GetCorners(effectiveAreaRestrictionInPawnCurrentMap); @@ -295,21 +297,21 @@ public static void RemoveObjectFromAwaitingActionHashSets(Map map, IntVec3 locat zoomLevel = 0; do { - jumboCellWidth = getJumboCellWidth(zoomLevel); - int cellIndex = CellToIndexCustom(location, mapSizeX, jumboCellWidth); + jumboCellWidth = getJumboCellWidth(zoomLevel); + int cellIndex = CellToIndexCustom(location, mapSizeX, jumboCellWidth); HashSet hashset = awaitingActionZoomLevels[zoomLevel][cellIndex]; - if (hashset != null) - { - lock (hashset) - { - hashset.Remove(location); - } - } - zoomLevel++; + if (hashset != null) + { + lock (hashset) + { + hashset.Remove(location); + } + } + zoomLevel++; } while (jumboCellWidth < mapSizeX || jumboCellWidth < mapSizeZ); } - public static List[]> GetAwaitingActionsZoomLevels(Dictionary[]>> awaitingActionMapDict, Map map) + public static List[]> GetAwaitingActionsZoomLevels(Dictionary[]>> awaitingActionMapDict, Map map, JumboCell_Cache jumboCell_Cache) { if (!awaitingActionMapDict.TryGetValue(map, out List[]> awaitingActionsZoomLevels)) { @@ -337,7 +339,10 @@ public static List[]> GetAwaitingActionsZoomLevels(Dictionary value)) - { - value = new List(); - __instance.listsByDef.Add(t.def, value); - } - value.Add(t); - } - - ThingRequestGroup[] allGroups = ThingListGroupHelper.AllGroups; - foreach (ThingRequestGroup thingRequestGroup in allGroups) - { - if ((__instance.use != ListerThingsUse.Region || thingRequestGroup.StoreInRegion()) && thingRequestGroup.Includes(thingDef)) - { - lock (__instance) - { - List list = __instance.listsByGroup[(uint)thingRequestGroup]; - if (list == null) - { - list = new List(); - __instance.listsByGroup[(uint)thingRequestGroup] = list; - } - list.Add(t); - } - } - } - return false; - } - - public static bool Remove(ListerThings __instance, Thing t) - { - ThingDef thingDef = t.def; - if (!ListerThings.EverListable(thingDef, __instance.use)) - { - return false; - } - lock(__instance) - { - List newListsByDef = new List(__instance.listsByDef[thingDef]); - newListsByDef.Remove(t); - __instance.listsByDef[thingDef] = newListsByDef; - } - - ThingRequestGroup[] allGroups = ThingListGroupHelper.AllGroups; - for (int i = 0; i < allGroups.Length; i++) - { - ThingRequestGroup group = allGroups[i]; - if ((__instance.use != ListerThingsUse.Region || group.StoreInRegion()) && group.Includes(thingDef)) - { - lock (__instance) - { - List newListsByGroup = new List(__instance.listsByGroup[i]); - newListsByGroup.Remove(t); - __instance.listsByGroup[i] = newListsByGroup; - } - } - } - return false; - } - - } - -} diff --git a/Source/ListerThings_Transpile.cs b/Source/ListerThings_Transpile.cs deleted file mode 100644 index dd64f751..00000000 --- a/Source/ListerThings_Transpile.cs +++ /dev/null @@ -1,271 +0,0 @@ -using HarmonyLib; -using System.Collections.Generic; -using Verse; -using System.Reflection; -using System.Reflection.Emit; -using System.Linq; -using System; -using static RimThreaded.RimThreadedHarmony; -using static HarmonyLib.AccessTools; - -namespace RimThreaded -{ - public class ListerThings_Transpile - { - public static IEnumerable Add(IEnumerable instructions, ILGenerator iLGenerator) - { - //---START EDIT--- - int[] matchesFound = new int[4]; - Type dictionary_ThingDef_List_Thing = typeof(Dictionary>); - Type list_Thing = typeof(List); - Type list_ThingArray = typeof(List[]); - Type listerThings = typeof(ListerThings); - //---END EDIT--- - List instructionsList = instructions.ToList(); - int i = 0; - while (i < instructionsList.Count) - { - int matchIndex = 0; - if ( - //---START EDIT--- - i + 3 < instructionsList.Count && - instructionsList[i + 3].opcode == OpCodes.Callvirt && - (MethodInfo)instructionsList[i + 3].operand == Method(dictionary_ThingDef_List_Thing, "TryGetValue") - //---END EDIT--- - ) - { - List loadLockObjectInstructions = new List - { - //---START EDIT--- - new CodeInstruction(OpCodes.Ldarg_0), - new CodeInstruction(OpCodes.Ldfld, Field(typeof(ListerThings), "listsByDef")) - //---END EDIT--- - }; - - //---START EDIT--- - LocalBuilder lockObject = iLGenerator.DeclareLocal(dictionary_ThingDef_List_Thing); - //---END EDIT--- - - LocalBuilder lockTaken = iLGenerator.DeclareLocal(typeof(bool)); - foreach (CodeInstruction ci in EnterLock(lockObject, lockTaken, loadLockObjectInstructions, instructionsList[i])) - yield return ci; - - while (i < instructionsList.Count) - { - if ( - //---START EDIT--- - instructionsList[i - 1].opcode == OpCodes.Callvirt && - (MethodInfo)instructionsList[i - 1].operand == Method(dictionary_ThingDef_List_Thing, "Add") - //---END EDIT--- - ) - break; - yield return instructionsList[i++]; - } - foreach (CodeInstruction ci in ExitLock(iLGenerator, lockObject, lockTaken, instructionsList[i])) - yield return ci; - matchesFound[matchIndex]++; - continue; - } - matchIndex++; - if ( - //---START EDIT--- - i + 2 < instructionsList.Count && - instructionsList[i].opcode == OpCodes.Ldloc_0 && - instructionsList[i + 2].opcode == OpCodes.Callvirt && - (MethodInfo)instructionsList[i + 2].operand == Method(list_Thing, "Add") - //---END EDIT--- - ) - { - List loadLockObjectInstructions = new List - { - //---START EDIT--- - new CodeInstruction(OpCodes.Ldloc_0) - //---END EDIT--- - }; - - //---START EDIT--- - LocalBuilder lockObject = iLGenerator.DeclareLocal(list_Thing); - //---END EDIT--- - - LocalBuilder lockTaken = iLGenerator.DeclareLocal(typeof(bool)); - foreach (CodeInstruction ci in EnterLock(lockObject, lockTaken, loadLockObjectInstructions, instructionsList[i])) - yield return ci; - - while (i < instructionsList.Count) - { - if ( - //---START EDIT--- - instructionsList[i - 1].opcode == OpCodes.Callvirt && - (MethodInfo)instructionsList[i - 1].operand == Method(list_Thing, "Add") - //---END EDIT--- - ) - break; - yield return instructionsList[i++]; - } - foreach (CodeInstruction ci in ExitLock(iLGenerator, lockObject, lockTaken, instructionsList[i])) - yield return ci; - matchesFound[matchIndex]++; - continue; - } - matchIndex++; - if ( - //---START EDIT--- - i + 3 < instructionsList.Count && - instructionsList[i + 1].opcode == OpCodes.Ldfld && - (FieldInfo)instructionsList[i + 1].operand == Field(listerThings, "listsByGroup") && - instructionsList[i + 3].opcode == OpCodes.Ldelem_Ref - //---END EDIT--- - ) - { - List loadLockObjectInstructions = new List - { - //---START EDIT--- - new CodeInstruction(OpCodes.Ldarg_0), - new CodeInstruction(OpCodes.Ldfld, Field(listerThings, "listsByGroup")) - //---END EDIT--- - }; - - //---START EDIT--- - LocalBuilder lockObject = iLGenerator.DeclareLocal(list_ThingArray); - //---END EDIT--- - - LocalBuilder lockTaken = iLGenerator.DeclareLocal(typeof(bool)); - foreach (CodeInstruction ci in EnterLock(lockObject, lockTaken, loadLockObjectInstructions, instructionsList[i])) - yield return ci; - - while (i < instructionsList.Count) - { - if ( - //---START EDIT--- - instructionsList[i - 1].opcode == OpCodes.Stelem_Ref - //---END EDIT--- - ) - break; - yield return instructionsList[i++]; - } - foreach (CodeInstruction ci in ExitLock(iLGenerator, lockObject, lockTaken, instructionsList[i])) - yield return ci; - matchesFound[matchIndex]++; - continue; - } - matchIndex++; - if ( - //---START EDIT--- - i + 2 < instructionsList.Count && - instructionsList[i].opcode == OpCodes.Ldloc_S && - ((LocalBuilder)instructionsList[i].operand).LocalIndex == 4 && - instructionsList[i + 2].opcode == OpCodes.Callvirt && - (MethodInfo)instructionsList[i + 2].operand == Method(list_Thing, "Add") - //---END EDIT--- - ) - { - List loadLockObjectInstructions = new List - { - //---START EDIT--- - new CodeInstruction(OpCodes.Ldloc_S, 4) - //---END EDIT--- - }; - - //---START EDIT--- - LocalBuilder lockObject = iLGenerator.DeclareLocal(list_Thing); - //---END EDIT--- - - LocalBuilder lockTaken = iLGenerator.DeclareLocal(typeof(bool)); - foreach (CodeInstruction ci in EnterLock(lockObject, lockTaken, loadLockObjectInstructions, instructionsList[i])) - yield return ci; - - while (i < instructionsList.Count) - { - if ( - //---START EDIT--- - instructionsList[i - 1].opcode == OpCodes.Callvirt && - (MethodInfo)instructionsList[i - 1].operand == Method(list_Thing, "Add") - //---END EDIT--- - ) - break; - yield return instructionsList[i++]; - } - foreach (CodeInstruction ci in ExitLock(iLGenerator, lockObject, lockTaken, instructionsList[i])) - yield return ci; - matchesFound[matchIndex]++; - continue; - } - yield return instructionsList[i++]; - } - for (int mIndex = 0; mIndex < matchesFound.Length; mIndex++) - { - if (matchesFound[mIndex] < 1) - Log.Error("IL code instruction set " + mIndex + " not found"); - } - } - - public static IEnumerable Remove(IEnumerable instructions, ILGenerator iLGenerator) - { - List instructionsList = instructions.ToList(); - - Type loadLockObjectType = typeof(List); - List loadLockObjectInstructions = new List - { - new CodeInstruction(OpCodes.Ldarg_0), - new CodeInstruction(OpCodes.Ldfld, Field(typeof(ListerThings), "listsByDef")), - new CodeInstruction(OpCodes.Ldarg_1), - new CodeInstruction(OpCodes.Ldfld, Field(typeof(Thing), "def")), - new CodeInstruction(OpCodes.Callvirt, Method(typeof(Dictionary>), "get_Item")) - }; - List searchInstructions = loadLockObjectInstructions.ListFullCopy(); - searchInstructions.Add(new CodeInstruction(OpCodes.Ldarg_1)); - searchInstructions.Add(new CodeInstruction(OpCodes.Callvirt, Method(typeof(Thing), "Remove"))); - searchInstructions.Add(new CodeInstruction(OpCodes.Pop)); - - Type loadLockObjectType2 = typeof(List); - List loadLockObjectInstructions2 = new List - { - new CodeInstruction(OpCodes.Ldarg_0), - new CodeInstruction(OpCodes.Ldfld, Field(typeof(ListerThings), "listsByGroup")), - new CodeInstruction(OpCodes.Ldloc_1), - new CodeInstruction(OpCodes.Ldelem_Ref) - }; - List searchInstructions2 = loadLockObjectInstructions2.ListFullCopy(); - searchInstructions2.Add(new CodeInstruction(OpCodes.Ldarg_1)); - searchInstructions2.Add(new CodeInstruction(OpCodes.Callvirt, Method(loadLockObjectType2, "Remove"))); - searchInstructions2.Add(new CodeInstruction(OpCodes.Pop)); - - int i = 0; - int matchesFound = 0; - - while (i < instructionsList.Count) - { - if (IsCodeInstructionsMatching(searchInstructions, instructionsList, i)) - { - matchesFound++; - foreach (CodeInstruction codeInstruction in GetLockCodeInstructions( - iLGenerator, instructionsList, i, searchInstructions.Count, loadLockObjectInstructions, loadLockObjectType)) - { - yield return codeInstruction; - } - i += searchInstructions.Count; - } - else if (IsCodeInstructionsMatching(searchInstructions2, instructionsList, i)) - { - matchesFound++; - foreach (CodeInstruction codeInstruction in GetLockCodeInstructions( - iLGenerator, instructionsList, i, searchInstructions2.Count, loadLockObjectInstructions2, loadLockObjectType2)) - { - yield return codeInstruction; - } - i += searchInstructions2.Count; - } - else - { - yield return instructionsList[i]; - i++; - } - } - if (matchesFound < 1) - { - Log.Error("IL code instructions not found"); - } - } - - } -} diff --git a/Source/LongEventHandler_Patch.cs b/Source/LongEventHandler_Patch.cs deleted file mode 100644 index 7641c3ba..00000000 --- a/Source/LongEventHandler_Patch.cs +++ /dev/null @@ -1,74 +0,0 @@ -using System; -using Verse; -using System.Collections.Concurrent; - -namespace RimThreaded -{ - - public class LongEventHandler_Patch - { - - public static ConcurrentQueue toExecuteWhenFinished2 = new ConcurrentQueue(); - - internal static void RunDestructivePatches() - { - Type original = typeof(LongEventHandler); - Type patched = typeof(LongEventHandler_Patch); - RimThreadedHarmony.Prefix(original, patched, "ExecuteToExecuteWhenFinished"); - RimThreadedHarmony.Prefix(original, patched, "ExecuteWhenFinished"); - } - public static void RunNonDestructivePatches() - { - Type original = typeof(LongEventHandler); - Type patched = typeof(LongEventHandler_Patch); - RimThreadedHarmony.Prefix(original, patched, "RunEventFromAnotherThread", null, false); - } - - public static bool ExecuteToExecuteWhenFinished() - { - if (toExecuteWhenFinished2.Count > 0) - { - DeepProfiler.Start("ExecuteToExecuteWhenFinished()"); - } - while (toExecuteWhenFinished2.TryDequeue(out Action action)) - { - DeepProfiler.Start(action.Method.DeclaringType + " -> " + action.Method); - try - { - action(); - } - catch (Exception arg) - { - Log.Error("Could not execute post-long-event action. Exception: " + arg); - } - finally - { - DeepProfiler.End(); - } - } - - if (toExecuteWhenFinished2.Count > 0) - { - DeepProfiler.End(); - } - - LongEventHandler.toExecuteWhenFinished.Clear(); - return false; - } - public static bool ExecuteWhenFinished(Action action) - { - toExecuteWhenFinished2.Enqueue(action); - return true; - } - - public static bool RunEventFromAnotherThread(Action action) - { - RimThreaded.InitializeAllThreadStatics(); - return true; - } - - } - - - -} diff --git a/Source/MapPawns_Transpile.cs b/Source/MapPawns_Transpile.cs deleted file mode 100644 index 2f9f06ef..00000000 --- a/Source/MapPawns_Transpile.cs +++ /dev/null @@ -1,311 +0,0 @@ -using HarmonyLib; -using System.Collections.Generic; -using Verse; -using System.Reflection; -using RimWorld; -using RimWorld.Planet; -using UnityEngine; -using System.Reflection.Emit; -using System.Linq; -using System; -using System.Threading; -using Verse.AI; - -namespace RimThreaded -{ - public class MapPawns_Transpile - { - public static IEnumerable RegisterPawn(IEnumerable instructions, ILGenerator iLGenerator) - { - List instructionsList = instructions.ToList(); - Type loadLockObjectType = typeof(List); - List loadLockObjectInstructions = new List - { - new CodeInstruction(OpCodes.Ldarg_0), - new CodeInstruction(OpCodes.Ldfld, AccessTools.Field(typeof(MapPawns), "pawnsSpawned")) - }; - List searchInstructions = loadLockObjectInstructions.ListFullCopy(); - searchInstructions.Add(new CodeInstruction(OpCodes.Ldarg_1)); - searchInstructions.Add(new CodeInstruction(OpCodes.Callvirt, AccessTools.Method(typeof(List), "Contains"))); - searchInstructions.Add(new CodeInstruction(OpCodes.Brtrue_S)); - searchInstructions.Add(new CodeInstruction(OpCodes.Ldarg_0)); - searchInstructions.Add(new CodeInstruction(OpCodes.Ldfld, AccessTools.Field(typeof(MapPawns), "pawnsSpawned"))); - searchInstructions.Add(new CodeInstruction(OpCodes.Ldarg_1)); - searchInstructions.Add(new CodeInstruction(OpCodes.Callvirt, AccessTools.Method(typeof(List), "Add"))); - - Type loadLockObjectType2 = typeof(Dictionary>); - List loadLockObjectInstructions2 = new List - { - new CodeInstruction(OpCodes.Ldarg_0), - new CodeInstruction(OpCodes.Ldfld, AccessTools.Field(typeof(MapPawns), "pawnsInFactionSpawned")) - - }; - List searchInstructions2 = new List(); //loadLockObjectInstructions2.ListFullCopy(); - searchInstructions2.Add(new CodeInstruction(OpCodes.Ldarg_1)); - searchInstructions2.Add(new CodeInstruction(OpCodes.Callvirt, AccessTools.Method(typeof(Thing), "get_Faction"))); - searchInstructions2.Add(new CodeInstruction(OpCodes.Brfalse_S)); - /* - searchInstructions2.Add(new CodeInstruction(OpCodes.Ldarg_1)); - searchInstructions2.Add(new CodeInstruction(OpCodes.Callvirt, AccessTools.Method(typeof(Thing), "get_Faction"))); - searchInstructions2.Add(new CodeInstruction(OpCodes.Callvirt, AccessTools.Method(typeof(Dictionary>), "get_Item"))); - searchInstructions2.Add(new CodeInstruction(OpCodes.Ldarg_1)); - searchInstructions2.Add(new CodeInstruction(OpCodes.Callvirt, AccessTools.Method(typeof(List), "Contains"))); - */ - /* - searchInstructions2.Add(new CodeInstruction(OpCodes.Brtrue_S)); - searchInstructions2.Add(new CodeInstruction(OpCodes.Ldarg_0)); - searchInstructions2.Add(new CodeInstruction(OpCodes.Ldfld, AccessTools.Field(typeof(MapPawns), "pawnsInFactionSpawned"))); - searchInstructions2.Add(new CodeInstruction(OpCodes.Ldarg_1)); - searchInstructions2.Add(new CodeInstruction(OpCodes.Callvirt, AccessTools.Method(typeof(Thing), "get_Faction"))); - searchInstructions2.Add(new CodeInstruction(OpCodes.Callvirt, AccessTools.Method(typeof(List), "get_Item"))); - searchInstructions2.Add(new CodeInstruction(OpCodes.Ldarg_1)); - searchInstructions2.Add(new CodeInstruction(OpCodes.Callvirt, AccessTools.Method(typeof(List), "Add"))); - searchInstructions2.Add(new CodeInstruction(OpCodes.Ldarg_1)); - searchInstructions2.Add(new CodeInstruction(OpCodes.Callvirt, AccessTools.Method(typeof(Thing), "get_Faction"))); - searchInstructions2.Add(new CodeInstruction(OpCodes.Call, AccessTools.Method(typeof(Faction), "get_OfPlayer"))); - searchInstructions2.Add(new CodeInstruction(OpCodes.Bne_Un_S)); - searchInstructions2.Add(new CodeInstruction(OpCodes.Ldarg_0)); - searchInstructions2.Add(new CodeInstruction(OpCodes.Ldfld, AccessTools.Field(typeof(MapPawns), "pawnsInFactionSpawned"))); - searchInstructions2.Add(new CodeInstruction(OpCodes.Call, AccessTools.Method(typeof(Faction), "get_OfPlayer"))); - searchInstructions2.Add(new CodeInstruction(OpCodes.Callvirt, AccessTools.Method(typeof(List), "get_Item"))); - searchInstructions2.Add(new CodeInstruction(OpCodes.Ldsfld, AccessTools.Field(AccessTools.TypeByName("Verse.MapPawns+<>c"), "<>9__82_0"))); - searchInstructions2.Add(new CodeInstruction(OpCodes.Dup)); - searchInstructions2.Add(new CodeInstruction(OpCodes.Brtrue_S)); - searchInstructions2.Add(new CodeInstruction(OpCodes.Pop)); - searchInstructions2.Add(new CodeInstruction(OpCodes.Ldsfld, AccessTools.Field(AccessTools.TypeByName("Verse.MapPawns+<>c"), "<>9"))); - searchInstructions2.Add(new CodeInstruction(OpCodes.Ldftn, AccessTools.Method(AccessTools.TypeByName("Verse.MapPawns+<>c"), "b__82_0"))); - searchInstructions2.Add(new CodeInstruction(OpCodes.Newobj, AccessTools.Constructor(typeof(Comparison), new Type[] { typeof(object), typeof(int) } ))); - searchInstructions2.Add(new CodeInstruction(OpCodes.Dup)); - searchInstructions2.Add(new CodeInstruction(OpCodes.Stsfld, AccessTools.Field(AccessTools.TypeByName("Verse.MapPawns+<>c"), "<>9__82_0"))); - searchInstructions2.Add(new CodeInstruction(OpCodes.Call, AccessTools.Method(typeof(GenList), "InsertionSort"))); - */ - Type loadLockObjectType3 = typeof(List); - List loadLockObjectInstructions3 = new List - { - new CodeInstruction(OpCodes.Ldarg_0), - new CodeInstruction(OpCodes.Ldfld, AccessTools.Field(typeof(MapPawns), "prisonersOfColonySpawned")) - - }; - List searchInstructions3 = new List(); - searchInstructions3.Add(new CodeInstruction(OpCodes.Ldarg_1)); - searchInstructions3.Add(new CodeInstruction(OpCodes.Callvirt, AccessTools.Method(typeof(Pawn), "get_IsPrisonerOfColony"))); - searchInstructions3.Add(new CodeInstruction(OpCodes.Brfalse_S)); - searchInstructions3.Add(new CodeInstruction(OpCodes.Ldarg_0)); - searchInstructions3.Add(new CodeInstruction(OpCodes.Ldfld, AccessTools.Field(typeof(MapPawns), "prisonersOfColonySpawned"))); - searchInstructions3.Add(new CodeInstruction(OpCodes.Ldarg_1)); - searchInstructions3.Add(new CodeInstruction(OpCodes.Callvirt, AccessTools.Method(typeof(List), "Contains"))); - searchInstructions3.Add(new CodeInstruction(OpCodes.Brtrue_S)); - searchInstructions3.Add(new CodeInstruction(OpCodes.Ldarg_0)); - searchInstructions3.Add(new CodeInstruction(OpCodes.Ldfld, AccessTools.Field(typeof(MapPawns), "prisonersOfColonySpawned"))); - searchInstructions3.Add(new CodeInstruction(OpCodes.Ldarg_1)); - searchInstructions3.Add(new CodeInstruction(OpCodes.Callvirt, AccessTools.Method(typeof(List), "Add"))); - - int i = 0; - int[] matchesFound = { 0, 0, 0 }; - - while (i < instructionsList.Count) - { - if (RimThreadedHarmony.IsCodeInstructionsMatching(searchInstructions, instructionsList, i)) - { - matchesFound[0]++; - - foreach (CodeInstruction codeInstruction in RimThreadedHarmony.GetLockCodeInstructions( - iLGenerator, instructionsList, i, searchInstructions.Count, loadLockObjectInstructions, loadLockObjectType)) - { - yield return codeInstruction; - } - i += searchInstructions.Count; - - //yield return new CodeInstruction(OpCodes.Ldarg_0); - //yield return new CodeInstruction(OpCodes.Ldarg_1); - //yield return new CodeInstruction(OpCodes.Call, AccessTools.Method(typeof(MapPawns_Patch), "RegisterPawn3")); - //i += searchInstructions.Count; - } - else if (RimThreadedHarmony.IsCodeInstructionsMatching(searchInstructions2, instructionsList, i)) - { - matchesFound[1]++; - /* - LocalBuilder lockObject = iLGenerator.DeclareLocal(loadLockObjectType2); - LocalBuilder lockTaken = iLGenerator.DeclareLocal(typeof(bool)); - loadLockObjectInstructions2[0].labels = instructionsList[i].labels; - for (int j = 0; j < loadLockObjectInstructions2.Count; j++) - { - yield return (loadLockObjectInstructions2[j]); - } - instructionsList[i].labels = new List