Skip to content

Commit

Permalink
Merge pull request #8 from Mehni/Stable_1.0
Browse files Browse the repository at this point in the history
Stable 1.0
  • Loading branch information
Mehni authored Aug 29, 2018
2 parents 9c62845 + cf5e8d5 commit 8a67148
Show file tree
Hide file tree
Showing 14 changed files with 103 additions and 122 deletions.
5 changes: 3 additions & 2 deletions About/About.xml
Original file line number Diff line number Diff line change
Expand Up @@ -2,11 +2,11 @@
<ModMetaData>
<name>Pick Up And Haul</name>
<author>Mehni</author>
<targetVersion>0.18.0</targetVersion>
<targetVersion>0.19.0</targetVersion>
<url>https://ludeon.com/forums/index.php?topic=35832</url>
<description>"Greatest hauling mod ever" - Chicken Plucker

v0.18.2.0
v.1.0.3

Colonists will gather stuff in their inventory, then haul it all to a stockpile.

Expand All @@ -19,6 +19,7 @@ Safe to add to existing games.
&lt;size=20&gt;Credits and thanks:&lt;/size&gt;
- erdelf, Zorba, Why_is_that and Dingo for code and advice (yet again!)
- Chicken Plucker, for the preview image
- AlexTD, for his direct contributions
- Brrainz, for the amazing Harmony library

Ludeon: https://ludeon.com/forums/index.php?topic=35832
Expand Down
7 changes: 0 additions & 7 deletions About/ModSync.xml

This file was deleted.

Binary file modified Assemblies/0Harmony.dll
Binary file not shown.
Binary file modified Assemblies/PickUpAndHaul.dll
Binary file not shown.
2 changes: 1 addition & 1 deletion Patches/PickUpAndHaul.xml
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
<Patch>

<Operation Class="PatchOperationAdd">
<xpath>Defs/ThingDef [@Name ="BasePawn"]/comps</xpath>
<xpath>Defs/ThingDef[thingClass="Pawn"]/comps</xpath>
<value>
<li><compClass>PickUpAndHaul.CompHauledToInventory</compClass></li>
</value>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ public class CompHauledToInventory : ThingComp

public HashSet<Thing> GetHashSet()
{
TakenToInventory.Remove(null);
TakenToInventory.RemoveWhere(x => x == null);
return TakenToInventory;
}

Expand Down
24 changes: 10 additions & 14 deletions Source/PickUpAndHaul/PickUpAndHaul/HarmonyPatches.cs
Original file line number Diff line number Diff line change
Expand Up @@ -12,11 +12,9 @@

namespace PickUpAndHaul
{

[StaticConstructorOnStartup]
static class HarmonyPatches
{

static HarmonyPatches()
{
HarmonyInstance harmony = HarmonyInstance.Create("mehni.rimworld.pickupthatcan.main");
Expand All @@ -38,14 +36,14 @@ static HarmonyPatches()

harmony.Patch(AccessTools.Method(typeof(JobGiver_Idle), "TryGiveJob"), null,
new HarmonyMethod(typeof(HarmonyPatches), nameof(IdleJoy_Postfix)), null);

try
{
((Action)(() =>
{
if (ModCompatibilityCheck.AllowToolIsActive)
{
harmony.Patch(AccessTools.Method(typeof(AllowTool.WorkGiver_HaulUrgently), "JobOnThing"),
harmony.Patch(AccessTools.Method(typeof(AllowTool.WorkGiver_HaulUrgently), nameof(AllowTool.WorkGiver_HaulUrgently.JobOnThing)),
new HarmonyMethod(typeof(HarmonyPatches), nameof(AllowToolHaulUrgentlyJobOnThing_PreFix)), null, null);
}
}))();
Expand All @@ -66,10 +64,9 @@ static HarmonyPatches()
}
catch (TypeLoadException) { }

Log.Message("PickUpAndHaul v0.18.2.0 welcomes you to RimWorld with pointless logspam.");
Log.Message("PickUpAndHaul v0.1.0.3 welcomes you to RimWorld with pointless logspam.");
}


private static bool AllowToolHaulUrgentlyJobOnThing_PreFix(ref Job __result, Pawn pawn, Thing t, bool forced = false)
{
if (ModCompatibilityCheck.AllowToolIsActive)
Expand All @@ -84,14 +81,14 @@ private static bool AllowToolHaulUrgentlyJobOnThing_PreFix(ref Job __result, Paw
&& !(t.def.defName.Contains("Chunk")) //most of the time we don't have space for it
)
{
StoragePriority currentPriority = HaulAIUtility.StoragePriorityAtFor(t.Position, t);
StoragePriority currentPriority = StoreUtility.CurrentStoragePriorityOf(t);
if (!StoreUtility.TryFindBestBetterStoreCellFor(t, pawn, pawn.Map, currentPriority, pawn.Faction, out IntVec3 storeCell, true))
{
JobFailReason.Is("NoEmptyPlaceLower".Translate());
return false;
}

Job haul = new Job(PickUpAndHaulJobDefOf.HaulToInventory, t)
Job haul = new Job(PickUpAndHaulJobDefOf.HaulToInventory, t, storeCell)
{
count = t.stackCount
};
Expand All @@ -102,7 +99,7 @@ private static bool AllowToolHaulUrgentlyJobOnThing_PreFix(ref Job __result, Paw
return true;
}

private static bool Drop_Prefix(ref Pawn pawn, ref Thing thing)
private static bool Drop_Prefix(Pawn pawn, Thing thing)
{
CompHauledToInventory takenToInventory = pawn.TryGetComp<CompHauledToInventory>();
if (takenToInventory == null) return true;
Expand All @@ -116,7 +113,7 @@ private static bool Drop_Prefix(ref Pawn pawn, ref Thing thing)
return true;
}

private static void Pawn_InventoryTracker_PostFix(Pawn_InventoryTracker __instance, ref Thing item)
private static void Pawn_InventoryTracker_PostFix(Pawn_InventoryTracker __instance, Thing item)
{
CompHauledToInventory takenToInventory = __instance.pawn.TryGetComp<CompHauledToInventory>();
if (takenToInventory == null) return;
Expand Down Expand Up @@ -154,12 +151,12 @@ private static void JobDriver_HaulToCell_PostFix(JobDriver_HaulToCell __instance
//}
}

public static void IdleJoy_Postfix(ref Pawn pawn)
public static void IdleJoy_Postfix(Pawn pawn)
{
PawnUnloadChecker.CheckIfPawnShouldUnloadInventory(pawn, true);
}

public static void DropUnusedInventory_PostFix(ref Pawn pawn)
public static void DropUnusedInventory_PostFix(Pawn pawn)
{
PawnUnloadChecker.CheckIfPawnShouldUnloadInventory(pawn);
}
Expand Down Expand Up @@ -202,8 +199,7 @@ public static void WhileYoureUpMaybeHaulOtherStuffFirst_PostFix(Pawn pawn, Local
{
if (__result == null || __result.def != JobDefOf.HaulToCell) return;

WorkGiver_HaulToInventory worker = pawn.workSettings.WorkGiversInOrderNormal.FirstOrDefault(wg => wg is WorkGiver_HaulToInventory) as WorkGiver_HaulToInventory;
if (worker == null) return;
if (!(pawn.workSettings.WorkGiversInOrderNormal.FirstOrDefault(wg => wg is WorkGiver_HaulToInventory) is WorkGiver_HaulToInventory worker)) return;

Job myJob = worker.JobOnThing(pawn, __result.targetA.Thing, false);
if (myJob == null) return;
Expand Down
104 changes: 50 additions & 54 deletions Source/PickUpAndHaul/PickUpAndHaul/JobDriver_HaulToInventory.cs
Original file line number Diff line number Diff line change
@@ -1,34 +1,31 @@
using System;
using System.Collections.Generic;
using RimWorld;
using UnityEngine;
using Verse;
using Verse.AI;
using UnityEngine;

namespace PickUpAndHaul
{
public class JobDriver_HaulToInventory : JobDriver
{


public override bool TryMakePreToilReservations()
public override bool TryMakePreToilReservations(bool errorOnFailed)
{
return this.pawn.Reserve(this.job.targetA, this.job, 1, -1, null);
return this.pawn.Reserve(this.job.targetA, this.job) && pawn.Reserve(job.targetB, this.job);
}

//reserve, goto, take, check for more. Branches off to "all over the place"
protected override IEnumerable<Toil> MakeNewToils()
{
CompHauledToInventory takenToInventory = pawn.TryGetComp<CompHauledToInventory>();
HashSet<Thing> carriedThings = takenToInventory.GetHashSet();
DesignationDef HaulUrgentlyDesignation = DefDatabase<DesignationDef>.GetNamed("HaulUrgentlyDesignation", false);

//Thanks to AlexTD for the more dynamic search range
float searchForOthersRangeFraction = 0.5f;
float distanceToOthers = 0f;

Toil wait = Toils_General.Wait(2);
Toil reserveTargetA = Toils_Reserve.Reserve(TargetIndex.A, 1, -1, null);
Toil reserveTargetA = Toils_Reserve.Reserve(TargetIndex.A);

Toil calculateExtraDistanceToGo = new Toil
{
Expand All @@ -40,8 +37,8 @@ protected override IEnumerable<Toil> MakeNewToils()
};
yield return calculateExtraDistanceToGo;

Toil checkForOtherItemsToHaulToInventory = CheckForOtherItemsToHaulToInventory(reserveTargetA, TargetIndex.A, distanceToOthers, null);
Toil checkForOtherItemsToUrgentlyHaulToInventory = CheckForOtherItemsToHaulToInventory(reserveTargetA, TargetIndex.A, distanceToOthers, (Thing x) => pawn.Map.designationManager.DesignationOn(x)?.def == HaulUrgentlyDesignation);
Toil checkForOtherItemsToHaulToInventory = CheckForOtherItemsToHaulToInventory(reserveTargetA, TargetIndex.A, distanceToOthers);
Toil checkForOtherItemsToUrgentlyHaulToInventory = CheckForOtherItemsToHaulToInventory(reserveTargetA, TargetIndex.A, distanceToOthers, x => pawn.Map.designationManager.DesignationOn(x)?.def == HaulUrgentlyDesignation);

yield return reserveTargetA;

Expand All @@ -51,7 +48,7 @@ protected override IEnumerable<Toil> MakeNewToils()
{
this.pawn.pather.StartPath(this.TargetThingA, PathEndMode.ClosestTouch);
},
defaultCompleteMode = ToilCompleteMode.PatherArrival,
defaultCompleteMode = ToilCompleteMode.PatherArrival
};
gotoThing.FailOnDespawnedNullOrForbidden(TargetIndex.A);
yield return gotoThing;
Expand All @@ -65,7 +62,7 @@ protected override IEnumerable<Toil> MakeNewToils()
Toils_Haul.ErrorCheckForCarry(actor, thing);

//get max we can pick up
int num = Mathf.Min(thing.stackCount, MassUtility.CountToPickUpUntilOverEncumbered(actor, thing));
int num = Mathf.Min(thing.stackCount, MassUtility.CountToPickUpUntilOverEncumbered(actor, thing), job.count);

// yo dawg, I heard you like delegates so I put delegates in your delegate, so you can delegate your delegates.
// because compilers don't respect IF statements in delegates and toils are fully iterated over as soon as the job starts.
Expand All @@ -76,7 +73,7 @@ protected override IEnumerable<Toil> MakeNewToils()
if (ModCompatibilityCheck.CombatExtendedIsActive)
{
CombatExtended.CompInventory ceCompInventory = actor.GetComp<CombatExtended.CompInventory>();
ceCompInventory.CanFitInInventory(thing, out num, false, false);
ceCompInventory.CanFitInInventory(thing, out num);
}
}))();
}
Expand All @@ -86,9 +83,9 @@ protected override IEnumerable<Toil> MakeNewToils()
if (num <= 0)
{
Job haul = HaulAIUtility.HaulToStorageJob(actor, thing);
if (haul?.TryMakePreToilReservations(actor) ?? false)
if (haul?.TryMakePreToilReservations(actor, false) ?? false)
{
actor.jobs.jobQueue.EnqueueFirst(haul, new JobTag?(JobTag.Misc));
actor.jobs.jobQueue.EnqueueFirst(haul, JobTag.Misc);
}
actor.jobs.curDriver.JumpToToil(wait);
}
Expand All @@ -104,7 +101,7 @@ protected override IEnumerable<Toil> MakeNewToils()
}
}

actor.inventory.GetDirectlyHeldThings().TryAdd(thing.SplitOff(num), true);
actor.inventory.GetDirectlyHeldThings().TryAdd(thing.SplitOff(num));
takenToInventory.RegisterHauledItem(thing);

try
Expand Down Expand Up @@ -145,60 +142,59 @@ public Toil CheckForOtherItemsToHaulToInventory(Toil getHaulTargetToil, TargetIn
Job curJob = actor.jobs.curJob;
IntVec3 storeCell = IntVec3.Invalid;

Predicate<Thing> validator = (Thing t) => t.Spawned
&& HaulAIUtility.PawnCanAutomaticallyHaulFast(actor, t, false)
&& (!t.IsInValidBestStorage())
&& !t.IsForbidden(actor)
&& !(t is Corpse)
&& (StoreUtility.TryFindBestBetterStoreCellFor(t, pawn, pawn.Map, (HaulAIUtility.StoragePriorityAtFor(t.Position, t)), actor.Faction, out storeCell, true))
&& (extraValidator == null || extraValidator (t))
&& actor.CanReserve(t, 1, -1, null, false);
bool Validator(Thing t) => t.Spawned && HaulAIUtility.PawnCanAutomaticallyHaulFast(actor, t, false)
&& !t.IsInValidBestStorage()
&& !t.IsForbidden(actor)
&& !(t is Corpse)
&& StoreUtility.TryFindBestBetterStoreCellFor(t, this.pawn, this.pawn.Map, StoreUtility.CurrentStoragePriorityOf(t), actor.Faction, out storeCell)
&& (extraValidator == null || extraValidator(t))
&& actor.CanReserve(t);

Thing thing = GenClosest.ClosestThingReachable(actor.Position, actor.Map, ThingRequest.ForGroup(ThingRequestGroup.HaulableAlways), PathEndMode.ClosestTouch,
TraverseParms.For(actor, Danger.Deadly, TraverseMode.ByPawn, false), Math.Max(distanceToOthers, 12f), validator, null, 0, -1, false, RegionType.Set_Passable, false);

float usedBulkByPct = 1f;
float usedWeightByPct = 1f;

try
{
((Action)(() =>
{
if (ModCompatibilityCheck.CombatExtendedIsActive)
{
CombatExtended.CompInventory ceCompInventory = actor.GetComp<CombatExtended.CompInventory>();
usedWeightByPct = ceCompInventory.currentWeight / ceCompInventory.capacityWeight;
usedBulkByPct = ceCompInventory.currentBulk / ceCompInventory.capacityBulk;
}
}))();
}
catch (TypeLoadException) { }


if (thing != null && (MassUtility.EncumbrancePercent(actor) <= 0.9f || usedBulkByPct >= 0.7f || usedWeightByPct >= 0.8f))
TraverseParms.For(actor), Math.Max(distanceToOthers, 12f), Validator);

//float usedBulkByPct = 1f;
//float usedWeightByPct = 1f;

//try
//{
// ((Action)(() =>
// {
// if (ModCompatibilityCheck.CombatExtendedIsActive)
// {
// CompInventory ceCompInventory = actor.GetComp<CompInventory>();
// usedWeightByPct = ceCompInventory.currentWeight / ceCompInventory.capacityWeight;
// usedBulkByPct = ceCompInventory.currentBulk / ceCompInventory.capacityBulk;
// }
// }))();
//}
//catch (TypeLoadException) { }


if (thing != null && (MassUtility.EncumbrancePercent(actor) <= 0.9f /*|| usedBulkByPct >= 0.7f || usedWeightByPct >= 0.8f*/))
{
curJob.SetTarget(haulableInd, thing);
actor.Reserve(storeCell, this.job, 1, -1, null);
actor.Reserve(storeCell, this.job);
this.job.count = 99999; //done for "num", to solve scenarios like hauling 150 meat to single free spot near stove
actor.jobs.curDriver.JumpToToil(getHaulTargetToil);
return;
}
if (thing != null)
{
Job haul = HaulAIUtility.HaulToStorageJob(actor, thing);
if (haul?.TryMakePreToilReservations(actor) ?? false)
if (haul?.TryMakePreToilReservations(actor, false) ?? false)
{
actor.jobs.jobQueue.EnqueueFirst(haul, new JobTag?(JobTag.Misc));
//note that HaulToStorageJob etc doesn't do opportunistic duplicate hauling for items in valid storage. REEEE
actor.jobs.jobQueue.EnqueueFirst(haul, JobTag.Misc);
this.EndJobWith(JobCondition.Succeeded);
return;
}
}
if (thing == null)
Job unload = new Job(PickUpAndHaulJobDefOf.UnloadYourHauledInventory, storeCell);
if (unload.TryMakePreToilReservations(actor, false))
{
Job job = new Job(PickUpAndHaulJobDefOf.UnloadYourHauledInventory);
if (job.TryMakePreToilReservations(actor))
{
actor.jobs.jobQueue.EnqueueFirst(job, new JobTag?(JobTag.Misc));
this.EndJobWith(JobCondition.Succeeded);
}
actor.jobs.jobQueue.EnqueueFirst(unload, JobTag.Misc);
this.EndJobWith(JobCondition.Succeeded);
}
};
return toil;
Expand Down
Loading

0 comments on commit 8a67148

Please sign in to comment.