using System; using System.Collections.Generic; using System.Linq; using System.Reflection; using BlaxZones; using HarmonyLib; using RimWorld; using Verse; namespace BlaxZonesTests { /// /// Package Rewards. Design: 1.1 "Quest rewards land in the zone" > Tests. /// Tests: [BlaxTest("rewards: what", phase: N)], phase 1 fresh colony, 2 after save and reload, 3 after the component class was stripped. /// Nothing is saved by this feature, so every test is phase 1 (the rewards checkbox persists in TabTests and StoreTests). /// /// Parts are fired directly with Notify_QuestSignalReceived on a raw quest that is never in the quest /// manager. TradeDropSpot is fixed far from the test's zones by a test-only prefix, so a pod at the /// vanilla spot can't be mistaken for a routed one. Each test turns the rewards checkbox off on delivery /// zones other tests left on the map. Pods and letters are removed after the test; nothing ticks. /// public static class RewardTests { private const string HarmonyId = "blax.zones.tests.rewards"; private const string ForcedFailure = "BlaxZonesTests: forced failure inside the quest reward context"; private static Harmony harmony; private static Harmony H => harmony ??= new Harmony(HarmonyId); private static DeliveryContext contextAtFailure; /// DeliveryContext.Current at each DropThingGroupsNear call while RecordContext is patched in. private static readonly List contextsSeen = new List(); // ---- into the zone --------------------------------------------------------------------- [BlaxTest("rewards: gold and medicine from a trade-spot QuestPart_DropPods land in their zones, and the letter points into the zone")] public static void ItemsLandInZones() { Fixtures.OnlyThisTestsZones(DeliverySource.Rewards); CellRect area = Fixtures.TestArea(7, 2); Zone_Delivery goldZone = Fixtures.DeliveryZone(new CellRect(area.minX, area.minZ, 2, 2), Fixtures.FilterOf(ThingDefOf.Gold)); Zone_Delivery medZone = Fixtures.DeliveryZone(new CellRect(area.maxX - 1, area.minZ, 2, 2), Fixtures.FilterOf(ThingDefOf.MedicineIndustrial)); IntVec3 vanilla = Fixtures.FixTradeDropSpotAwayFrom(area); HashSet letters = Fixtures.DropLettersAfterTest(); Thing gold = Fixtures.Stack(ThingDefOf.Gold, 50); Thing medicine = Fixtures.Stack(ThingDefOf.MedicineIndustrial, 5); QuestPart_DropPods part = Fixtures.QuestDropPods(new[] { gold, medicine }, useTradeDropSpot: true); part.Notify_QuestSignalReceived(new Signal(Fixtures.QuestSignal)); Skyfaller goldPod = Fixtures.PodOf(gold); Skyfaller medPod = Fixtures.PodOf(medicine); T.Check(goldPod != medPod, "gold and medicine share one pod"); T.Check(goldZone.ContainsCell(goldPod.Position), "the gold pod falls on " + goldPod.Position + ", not in the gold zone (vanilla spot " + vanilla + ")"); T.Check(medZone.ContainsCell(medPod.Position), "the medicine pod falls on " + medPod.Position + ", not in the medicine zone"); T.Check(!gold.IsForbidden(Faction.OfPlayer) && !medicine.IsForbidden(Faction.OfPlayer), "the quest dropped with forbid off, but a routed reward is forbidden"); Letter letter = Find.LetterStack.LettersListForReading.LastOrDefault(l => !letters.Contains(l)); T.NotNull(letter, "the quest letter"); IntVec3 target = letter.lookTargets?.PrimaryTarget.Cell ?? IntVec3.Invalid; T.Check(Fixtures.InDeliveryZone(target), "the letter points at " + target + ", not into a delivery zone"); } [BlaxTest("rewards: QuestPart_GiveNearPawn drops its items into the zone and the letter points there")] public static void GiveNearPawnLandsInZone() { Fixtures.OnlyThisTestsZones(DeliverySource.Rewards); CellRect area = Fixtures.TestArea(3, 3); Zone_Delivery zone = Fixtures.DeliveryZone(area); Fixtures.FixTradeDropSpotAwayFrom(area); HashSet letters = Fixtures.DropLettersAfterTest(); Thing steel = Fixtures.Stack(ThingDefOf.Steel, 50); Quest quest = Fixtures.TestQuest(); var part = new QuestPart_GiveNearPawn { inSignal = Fixtures.QuestSignal, nearPawn = Fixtures.Negotiator() }; part.Things = new[] { steel }; quest.AddPart(part); part.Notify_QuestSignalReceived(new Signal(Fixtures.QuestSignal)); Skyfaller pod = Fixtures.PodOf(steel); T.Check(zone.ContainsCell(pod.Position), "the steel pod falls on " + pod.Position + ", not in the zone"); Letter letter = Find.LetterStack.LettersListForReading.LastOrDefault(l => !letters.Contains(l)); T.NotNull(letter, "the quest letter"); IntVec3 target = letter.lookTargets?.PrimaryTarget.Cell ?? IntVec3.Invalid; T.Check(zone.ContainsCell(target), "the letter points at " + target + ", not into the zone"); } [BlaxTest("rewards: a 1-cell zone with 3 reward stacks gets 1 pod, the other 2 land within 16 cells on separate cells; with overflow off more stacks go to the vanilla spot")] public static void OneCellZoneOverflows() { Fixtures.OnlyThisTestsZones(DeliverySource.Rewards); Fixtures.Settings.overflowNearZone = true; Fixtures.Settings.overflowRadius = BlaxZonesSettings.DefaultOverflowRadius; CellRect area = Fixtures.TestArea(1, 1); Zone_Delivery zone = Fixtures.DeliveryZone(area); IntVec3 vanilla = Fixtures.FixTradeDropSpotAwayFrom(area); Fixtures.DropLettersAfterTest(); var things = new[] { Fixtures.Stack(ThingDefOf.Steel, 50), Fixtures.Stack(ThingDefOf.WoodLog, 50), Fixtures.Stack(ThingDefOf.ComponentIndustrial, 5) }; QuestPart_DropPods part = Fixtures.QuestDropPods(things, useTradeDropSpot: true); part.Notify_QuestSignalReceived(new Signal(Fixtures.QuestSignal)); List pods = things.Select(Fixtures.PodOf).ToList(); T.Equal(3, pods.Distinct().Count(), "pods for 3 stacks"); T.Equal(3, pods.Select(p => p.Position).Distinct().Count(), "distinct pod cells"); T.Equal(1, pods.Count(p => zone.ContainsCell(p.Position)), "pods on the zone cell"); foreach (Skyfaller p in pods.Where(p => !zone.ContainsCell(p.Position))) { T.Check(Fixtures.Chebyshev(p.Position, vanilla) > BlaxZonesSettings.DefaultOverflowRadius, "an overflow pod went to the vanilla spot " + vanilla); int d = Fixtures.DistanceToZone(zone, p.Position); T.Check(d <= BlaxZonesSettings.DefaultOverflowRadius, "an overflow pod falls " + d + " cells from the zone, at " + p.Position); } // Overflow off: the zone's one cell holds a falling pod, so every further stack goes to the vanilla spot. Fixtures.Settings.overflowNearZone = false; var more = new[] { Fixtures.Stack(ThingDefOf.Cloth, 20), Fixtures.Stack(ThingDefOf.Plasteel, 20) }; Fixtures.QuestDropPods(more, useTradeDropSpot: true).Notify_QuestSignalReceived(new Signal(Fixtures.QuestSignal)); foreach (Thing t in more) { IntVec3 c = Fixtures.PodOf(t).Position; T.Check(!Fixtures.InDeliveryZone(c) && Fixtures.Chebyshev(c, vanilla) < Fixtures.FarSpotDistance / 2, "with overflow off the " + t.def.defName + " pod falls at " + c + ", not near the vanilla spot " + vanilla); } } // ---- never routed ------------------------------------------------------------------------ [BlaxTest("rewards: a refugee's pod stays out of the zone while the items' pods land in it")] public static void RefugeeNotRouted() { Fixtures.OnlyThisTestsZones(DeliverySource.Rewards); CellRect area = Fixtures.TestArea(3, 3); Zone_Delivery zone = Fixtures.DeliveryZone(area); IntVec3 vanilla = Fixtures.FixTradeDropSpotAwayFrom(area); Fixtures.DropLettersAfterTest(); Thing steel = Fixtures.Stack(ThingDefOf.Steel, 50); Pawn refugee = Refugee(); QuestPart_DropPods part = Fixtures.QuestDropPods(new Thing[] { steel, refugee }, useTradeDropSpot: true); part.Notify_QuestSignalReceived(new Signal(Fixtures.QuestSignal)); Skyfaller steelPod = Fixtures.PodOf(steel); Skyfaller refugeePod = Fixtures.PodOf(refugee); T.Check(zone.ContainsCell(steelPod.Position), "the steel pod falls on " + steelPod.Position + ", not in the zone"); T.Check(!Fixtures.InDeliveryZone(refugeePod.Position), "the refugee's pod falls into a delivery zone at " + refugeePod.Position); T.Check(Fixtures.Chebyshev(refugeePod.Position, vanilla) < Fixtures.FarSpotDistance / 2, "the refugee's pod falls at " + refugeePod.Position + ", far from the vanilla spot " + vanilla); } [BlaxTest("rewards: a mechanoid's pod stays out of the zone while the items' pods land in it")] public static void MechNotRouted() { PawnKindDef kind = DefDatabase.GetNamedSilentFail("Mech_Scyther"); T.NotNull(kind, "PawnKindDef Mech_Scyther (Core)"); Fixtures.OnlyThisTestsZones(DeliverySource.Rewards); CellRect area = Fixtures.TestArea(3, 3); Zone_Delivery zone = Fixtures.DeliveryZone(area); Fixtures.FixTradeDropSpotAwayFrom(area); Fixtures.DropLettersAfterTest(); Thing steel = Fixtures.Stack(ThingDefOf.Steel, 50); Pawn mech = Fixtures.Generate(kind, Faction.OfPlayer); QuestPart_DropPods part = Fixtures.QuestDropPods(new Thing[] { mech, steel }, useTradeDropSpot: true); part.Notify_QuestSignalReceived(new Signal(Fixtures.QuestSignal)); T.Check(zone.ContainsCell(Fixtures.PodOf(steel).Position), "the steel pod is not in the zone"); T.Check(!Fixtures.InDeliveryZone(Fixtures.PodOf(mech).Position), "the mechanoid's pod falls into a delivery zone"); } [BlaxTest("rewards: a Wastepack is never routed")] public static void WastepackNotRouted() { T.NeedsDlc("Biotech", ModsConfig.BiotechActive); ThingDef wastepack = ThingDefOf.Wastepack; T.NotNull(wastepack, "ThingDefOf.Wastepack with Biotech"); Fixtures.OnlyThisTestsZones(DeliverySource.Rewards); CellRect area = Fixtures.TestArea(3, 3); Zone_Delivery zone = Fixtures.DeliveryZone(area); zone.filter.SetAllow(wastepack, true); // even a filter that allows it can't pull it in Fixtures.FixTradeDropSpotAwayFrom(area); Fixtures.DropLettersAfterTest(); Thing waste = Fixtures.Stack(wastepack, 5); Thing steel = Fixtures.Stack(ThingDefOf.Steel, 50); QuestPart_DropPods part = Fixtures.QuestDropPods(new[] { waste, steel }, useTradeDropSpot: true); part.Notify_QuestSignalReceived(new Signal(Fixtures.QuestSignal)); T.Check(!Fixtures.InDeliveryZone(Fixtures.PodOf(waste).Position), "the Wastepack pod falls into a delivery zone"); T.Check(zone.ContainsCell(Fixtures.PodOf(steel).Position), "the steel pod is not in the zone"); } [BlaxTest("rewards: dropAllInSamePod with a refugee and items routes nothing")] public static void SamePodRoutesNothing() { Fixtures.OnlyThisTestsZones(DeliverySource.Rewards); CellRect area = Fixtures.TestArea(3, 3); Fixtures.DeliveryZone(area); Fixtures.FixTradeDropSpotAwayFrom(area); Fixtures.DropLettersAfterTest(); Thing steel = Fixtures.Stack(ThingDefOf.Steel, 50); Thing medicine = Fixtures.Stack(ThingDefOf.MedicineIndustrial, 5); Pawn refugee = Refugee(); QuestPart_DropPods part = Fixtures.QuestDropPods(new Thing[] { steel, medicine, refugee }, useTradeDropSpot: true); part.dropAllInSamePod = true; part.Notify_QuestSignalReceived(new Signal(Fixtures.QuestSignal)); Skyfaller pod = Fixtures.PodOf(refugee); T.Check(Fixtures.PodOf(steel) == pod && Fixtures.PodOf(medicine) == pod, "the things are not in one pod"); T.Check(!Fixtures.InDeliveryZone(pod.Position), "the shared pod falls into a delivery zone at " + pod.Position); } [BlaxTest("rewards: DropThingsNear without the context, as a raid calls it, is untouched")] public static void NoContextUntouched() { Fixtures.OnlyThisTestsZones(DeliverySource.Rewards); CellRect area = Fixtures.TestArea(3, 3); Fixtures.DeliveryZone(area); IntVec3 far = Fixtures.FarCell(area); Thing steel = Fixtures.Stack(ThingDefOf.Steel, 50); T.Equal(null, DeliveryContext.Current, "DeliveryContext.Current before the call"); DropPodUtility.DropThingsNear(far, Fixtures.Map, new[] { steel }, canRoofPunch: false, forbid: false); Skyfaller pod = Fixtures.PodOf(steel); T.Check(!Fixtures.InDeliveryZone(pod.Position), "the pod falls into a delivery zone at " + pod.Position); T.Check(Fixtures.Chebyshev(pod.Position, far) < Fixtures.FarSpotDistance / 2, "the pod falls at " + pod.Position + ", not near " + far); } [BlaxTest("rewards: with Route quest rewards off or the zone's checkbox off, rewards land at the vanilla spot")] public static void SwitchesOffVanilla() { Fixtures.OnlyThisTestsZones(DeliverySource.Rewards); CellRect area = Fixtures.TestArea(3, 3); Zone_Delivery zone = Fixtures.DeliveryZone(area); IntVec3 vanilla = Fixtures.FixTradeDropSpotAwayFrom(area); Fixtures.DropLettersAfterTest(); Fixtures.Settings.routeRewards = false; Thing steel = Fixtures.Stack(ThingDefOf.Steel, 50); Fixtures.QuestDropPods(new[] { steel }, useTradeDropSpot: true).Notify_QuestSignalReceived(new Signal(Fixtures.QuestSignal)); IntVec3 a = Fixtures.PodOf(steel).Position; T.Check(!zone.ContainsCell(a) && Fixtures.Chebyshev(a, vanilla) < Fixtures.FarSpotDistance / 2, "with Route quest rewards off the pod falls at " + a); Fixtures.Settings.routeRewards = true; zone.acceptRewards = false; Thing wood = Fixtures.Stack(ThingDefOf.WoodLog, 50); Fixtures.QuestDropPods(new[] { wood }, useTradeDropSpot: true).Notify_QuestSignalReceived(new Signal(Fixtures.QuestSignal)); IntVec3 b = Fixtures.PodOf(wood).Position; T.Check(!zone.ContainsCell(b) && Fixtures.Chebyshev(b, vanilla) < Fixtures.FarSpotDistance / 2, "with the zone's checkbox off the pod falls at " + b); } // ---- the caller's list, instaDrop, pod skins ---------------------------------------------- [BlaxTest("rewards: the list passed to DropThingGroupsNear still holds every group afterwards")] public static void CallerListUnchanged() { Fixtures.OnlyThisTestsZones(DeliverySource.Rewards); CellRect area = Fixtures.TestArea(3, 3); Zone_Delivery zone = Fixtures.DeliveryZone(area, Fixtures.FilterOf(ThingDefOf.Steel)); IntVec3 far = Fixtures.FarCell(area); Thing steel = Fixtures.Stack(ThingDefOf.Steel, 50); Thing wood = Fixtures.Stack(ThingDefOf.WoodLog, 50); var steelGroup = new List { steel }; var woodGroup = new List { wood }; var groups = new List> { steelGroup, woodGroup }; InRewardContext(() => DropPodUtility.DropThingGroupsNear(far, Fixtures.Map, groups, canRoofPunch: false, forbid: false)); T.Equal(2, groups.Count, "groups in the caller's list"); T.Check(groups[0] == steelGroup && groups[1] == woodGroup, "the caller's list holds other group lists"); T.Check(steelGroup.Count == 1 && steelGroup[0] == steel && woodGroup.Count == 1 && woodGroup[0] == wood, "a group list changed"); T.Check(zone.ContainsCell(Fixtures.PodOf(steel).Position), "the steel pod is not in the steel zone"); T.Check(!Fixtures.InDeliveryZone(Fixtures.PodOf(wood).Position), "the wood pod falls into a delivery zone"); T.Equal(null, DeliveryContext.Current, "DeliveryContext.Current after the call"); } [BlaxTest("rewards: with instaDrop the items appear in the zone with no pod")] public static void InstaDropPlaces() { Fixtures.OnlyThisTestsZones(DeliverySource.Rewards); CellRect area = Fixtures.TestArea(3, 3); Zone_Delivery zone = Fixtures.DeliveryZone(area); IntVec3 far = Fixtures.FarCell(area); Thing steel = Fixtures.Stack(ThingDefOf.Steel, 50); var groups = new List> { new List { steel } }; InRewardContext(() => DropPodUtility.DropThingGroupsNear(far, Fixtures.Map, groups, instaDrop: true, canRoofPunch: false, forbid: true)); T.Check(steel.Spawned, "the steel is not on the map; it is in " + steel.ParentHolder); T.Check(zone.ContainsCell(steel.Position), "the steel lies at " + steel.Position + ", not in the zone"); T.Check(steel.IsForbidden(Faction.OfPlayer), "forbid: true left the steel allowed"); } [BlaxTest("rewards: a mechanoid-faction drop keeps the mechanoid pod skin in the zone")] public static void FactionPodSkinKept() { Faction mechs = Faction.OfMechanoids; if (mechs == null) T.Skip("no mechanoid faction in this world"); ThingDef skin = mechs.def.dropPodIncoming; T.NotNull(skin, "the mechanoid faction's dropPodIncoming (Core Factions_Hidden.xml)"); Fixtures.OnlyThisTestsZones(DeliverySource.Rewards); CellRect area = Fixtures.TestArea(3, 3); Zone_Delivery zone = Fixtures.DeliveryZone(area); Fixtures.FixTradeDropSpotAwayFrom(area); Fixtures.DropLettersAfterTest(); Thing steel = Fixtures.Stack(ThingDefOf.Steel, 50); QuestPart_DropPods part = Fixtures.QuestDropPods(new[] { steel }, useTradeDropSpot: true); part.faction = mechs; part.Notify_QuestSignalReceived(new Signal(Fixtures.QuestSignal)); Skyfaller pod = Fixtures.PodOf(steel); T.Equal(skin, pod.def, "pod def"); T.Check(zone.ContainsCell(pod.Position), "the pod falls on " + pod.Position + ", not in the zone"); } // ---- context scope ----------------------------------------------------------------------- [BlaxTest("rewards: a chained part with useTradeDropSpot off, fired through outSignalResult, is not routed")] public static void ChainedPartNotRouted() { Fixtures.OnlyThisTestsZones(DeliverySource.Rewards); CellRect area = Fixtures.TestArea(3, 3); Zone_Delivery zone = Fixtures.DeliveryZone(area); // The second part's own drop spot: far from the zone, so only a leaked context could pull it in. IntVec3 secondSpot = Fixtures.FixTradeDropSpotAwayFrom(area); Fixtures.DropLettersAfterTest(); Thing steel = Fixtures.Stack(ThingDefOf.Steel, 50); Thing wood = Fixtures.Stack(ThingDefOf.WoodLog, 50); QuestPart_DropPods first = Fixtures.QuestDropPods(new[] { steel }, true, new[] { wood }, secondSpot, out QuestPart_DropPods second); first.Notify_QuestSignalReceived(new Signal(Fixtures.QuestSignal)); T.Check(zone.ContainsCell(Fixtures.PodOf(steel).Position), "the first part's steel is not in the zone"); Skyfaller woodPod = Fixtures.PodOf(wood); // fails when the chained part never fired T.Check(!Fixtures.InDeliveryZone(woodPod.Position), "the chained part's wood falls into a delivery zone at " + woodPod.Position); T.Check(Fixtures.Chebyshev(woodPod.Position, secondSpot) < Fixtures.FarSpotDistance / 2, "the chained part's pod falls at " + woodPod.Position + ", not near its drop spot " + secondSpot); T.Equal(null, DeliveryContext.Current, "DeliveryContext.Current after the chain"); } [BlaxTest("rewards: a chained quest part with no Zones prefix of its own sees no context, and its DropThingsNear is not routed")] public static void ChainedReceiverWithoutPrefixNotRouted() { // Only the SendSignal patch clears the context here: the probe part has no Zones prefix that // could do it, unlike a chained QuestPart_DropPods. Fixtures.OnlyThisTestsZones(DeliverySource.Rewards); CellRect area = Fixtures.TestArea(3, 3); Zone_Delivery zone = Fixtures.DeliveryZone(area); IntVec3 far = Fixtures.FixTradeDropSpotAwayFrom(area); Fixtures.DropLettersAfterTest(); Thing steel = Fixtures.Stack(ThingDefOf.Steel, 50); Thing wood = Fixtures.Stack(ThingDefOf.WoodLog, 50); Quest quest = Fixtures.TestQuest(); QuestPart_DropPods first = Fixtures.QuestDropPods(new[] { steel }, useTradeDropSpot: true, quest); first.outSignalResult = "Quest" + quest.id + ".blax.probe"; var probe = new ContextProbePart(first.outSignalResult, far, wood); quest.AddPart(probe); first.Notify_QuestSignalReceived(new Signal(Fixtures.QuestSignal)); T.Check(probe.Fired, "the chained probe part never got its signal"); T.Equal(null, probe.ContextSeen, "DeliveryContext.Current inside the chained part"); T.Check(zone.ContainsCell(Fixtures.PodOf(steel).Position), "the first part's steel is not in the zone"); Skyfaller woodPod = Fixtures.PodOf(wood); T.Check(!Fixtures.InDeliveryZone(woodPod.Position), "the probe's wood falls into a delivery zone at " + woodPod.Position); T.Check(Fixtures.Chebyshev(woodPod.Position, far) < Fixtures.FarSpotDistance / 2, "the probe's pod falls at " + woodPod.Position + ", not near " + far); T.Equal(null, DeliveryContext.Current, "DeliveryContext.Current after the chain"); } [BlaxTest("rewards: a trade-spot part with its own dropSpot, and a part with a random spot, run with no context")] public static void ContextOnlyForTradeSpotWithoutDropSpot() { Fixtures.OnlyThisTestsZones(DeliverySource.Rewards); CellRect area = Fixtures.TestArea(3, 3); Fixtures.DeliveryZone(area); IntVec3 far = Fixtures.FixTradeDropSpotAwayFrom(area); Fixtures.DropLettersAfterTest(); MethodInfo target = AccessTools.Method(typeof(DropPodUtility), nameof(DropPodUtility.DropThingGroupsNear)); MethodInfo recorder = AccessTools.Method(typeof(RewardTests), nameof(RecordContext)); H.Patch(target, prefix: new HarmonyMethod(recorder) { priority = Priority.First }); Fixtures.OnCleanup(() => H.Unpatch(target, recorder)); contextsSeen.Clear(); // useTradeDropSpot with a fixed dropSpot: vanilla drops at that spot (QuestPart_DropPods.cs:165). Thing steel = Fixtures.Stack(ThingDefOf.Steel, 50); QuestPart_DropPods fixedSpot = Fixtures.QuestDropPods(new[] { steel }, useTradeDropSpot: true); fixedSpot.dropSpot = far; fixedSpot.Notify_QuestSignalReceived(new Signal(Fixtures.QuestSignal)); T.Equal(1, contextsSeen.Count, "DropThingGroupsNear calls for the part with its own dropSpot"); T.Equal(null, contextsSeen[0], "DeliveryContext.Current inside a trade-spot part with its own dropSpot"); IntVec3 a = Fixtures.PodOf(steel).Position; T.Check(!Fixtures.InDeliveryZone(a) && Fixtures.Chebyshev(a, far) < Fixtures.FarSpotDistance / 2, "the pod of the part with its own dropSpot falls at " + a + ", not near " + far); // No trade spot and no dropSpot: a random spot (QuestPart_DropPods.cs:298-303), which may lie in a zone, so only the context counts. Thing wood = Fixtures.Stack(ThingDefOf.WoodLog, 50); Fixtures.QuestDropPods(new[] { wood }, useTradeDropSpot: false).Notify_QuestSignalReceived(new Signal(Fixtures.QuestSignal)); T.Equal(2, contextsSeen.Count, "DropThingGroupsNear calls after the part with a random spot"); T.Equal(null, contextsSeen[1], "DeliveryContext.Current inside a part with a random drop spot"); Fixtures.PodOf(wood); } [BlaxTest("rewards: an exception inside the context leaves DeliveryContext.Current null")] public static void ExceptionLeavesContextNull() { Fixtures.OnlyThisTestsZones(DeliverySource.Rewards); CellRect area = Fixtures.TestArea(3, 3); Fixtures.DeliveryZone(area); Fixtures.FixTradeDropSpotAwayFrom(area); Fixtures.DropLettersAfterTest(); MethodInfo target = AccessTools.Method(typeof(DropPodUtility), nameof(DropPodUtility.DropThingGroupsNear)); MethodInfo thrower = AccessTools.Method(typeof(RewardTests), nameof(ThrowInsideContext)); H.Patch(target, prefix: new HarmonyMethod(thrower) { priority = Priority.First }); Fixtures.OnCleanup(() => H.Unpatch(target, thrower)); Thing steel = Fixtures.Stack(ThingDefOf.Steel, 50); QuestPart_DropPods part = Fixtures.QuestDropPods(new[] { steel }, useTradeDropSpot: true); contextAtFailure = null; DeliveryContext.Current = null; bool threw = false; string failureTrace = null; try { part.Notify_QuestSignalReceived(new Signal(Fixtures.QuestSignal)); } catch (Exception e) when (Mentions(e, ForcedFailure)) { threw = true; for (Exception x = e; x != null; x = x.InnerException) { if (x.Message != null && x.Message.Contains(ForcedFailure)) failureTrace = x.StackTrace; } } T.Check(threw, "the forced failure never reached the caller"); T.Check(contextAtFailure == DeliveryContext.QuestRewards, "the quest reward context was not set inside the part"); T.Equal(null, DeliveryContext.Current, "DeliveryContext.Current after the exception"); // The finalizers return void, so Harmony rethrows: the trace still starts where the exception was thrown. T.Check(failureTrace != null && failureTrace.Contains(nameof(ThrowInsideContext)), "the exception's stack trace lost the frame that threw: " + failureTrace); } [BlaxTest("rewards: when planning throws, vanilla drops every group at its spot and Zones logs one error")] public static void PlanningFailureFallsBack() { Map map = Fixtures.Map; Fixtures.OnlyThisTestsZones(DeliverySource.Rewards); CellRect area = Fixtures.TestArea(3, 3); Zone_Delivery zone = Fixtures.DeliveryZone(area); IntVec3 vanilla = Fixtures.FixTradeDropSpotAwayFrom(area); Fixtures.DropLettersAfterTest(); Thing gold = Fixtures.Stack(ThingDefOf.Gold, 50); Thing medicine = Fixtures.Stack(ThingDefOf.MedicineIndustrial, 5); QuestPart_DropPods part = Fixtures.QuestDropPods(new[] { gold, medicine }, useTradeDropSpot: true); int podsBefore = map.listerThings.ThingsOfDef(ThingDefOf.DropPodIncoming).Count; ZonesLog.ResetOnce(); Fixtures.OnCleanup(ZonesLog.ResetOnce); ZonesTestHooks.RouterThrows = true; T.ExpectErrors("[Blax Zones] Quest reward delivery failed", 1); part.Notify_QuestSignalReceived(new Signal(Fixtures.QuestSignal)); Skyfaller goldPod = Fixtures.PodOf(gold); Skyfaller medPod = Fixtures.PodOf(medicine); T.Equal(2, map.listerThings.ThingsOfDef(ThingDefOf.DropPodIncoming).Count - podsBefore, "new drop pods"); foreach (Skyfaller pod in new[] { goldPod, medPod }) { T.Check(!zone.ContainsCell(pod.Position) && Fixtures.Chebyshev(pod.Position, vanilla) < Fixtures.FarSpotDistance / 2, "a pod falls at " + pod.Position + ", not near the vanilla spot " + vanilla); } T.Equal(50, gold.stackCount, "gold count"); T.Equal(5, medicine.stackCount, "medicine count"); T.Equal(null, DeliveryContext.Current, "DeliveryContext.Current after the failed plan"); } [BlaxTest("rewards: a failure on the second group drops nothing twice and Zones logs one error")] public static void FailureOnSecondGroup() { Map map = Fixtures.Map; Fixtures.OnlyThisTestsZones(DeliverySource.Rewards); CellRect area = Fixtures.TestArea(3, 3); Zone_Delivery zone = Fixtures.DeliveryZone(area); IntVec3 vanilla = Fixtures.FixTradeDropSpotAwayFrom(area); Fixtures.DropLettersAfterTest(); Thing gold = Fixtures.Stack(ThingDefOf.Gold, 50); Thing medicine = Fixtures.Stack(ThingDefOf.MedicineIndustrial, 5); QuestPart_DropPods part = Fixtures.QuestDropPods(new[] { gold, medicine }, useTradeDropSpot: true); int podsBefore = map.listerThings.ThingsOfDef(ThingDefOf.DropPodIncoming).Count; ZonesLog.ResetOnce(); Fixtures.OnCleanup(ZonesLog.ResetOnce); ZonesTestHooks.RoutedGroupThrowsAt = 1; T.ExpectErrors("[Blax Zones] Quest reward delivery failed", 1); part.Notify_QuestSignalReceived(new Signal(Fixtures.QuestSignal)); Skyfaller goldPod = Fixtures.PodOf(gold); Skyfaller medPod = Fixtures.PodOf(medicine); T.Check(goldPod != medPod, "gold and medicine share one pod"); T.Equal(2, map.listerThings.ThingsOfDef(ThingDefOf.DropPodIncoming).Count - podsBefore, "new drop pods"); T.Check(zone.ContainsCell(goldPod.Position), "the first group's pod is not in the zone"); T.Check(!zone.ContainsCell(medPod.Position) && Fixtures.Chebyshev(medPod.Position, vanilla) < Fixtures.FarSpotDistance / 2, "the failed group's pod falls at " + medPod.Position + ", not near the vanilla spot " + vanilla); T.Equal(50, gold.stackCount, "gold count"); T.Equal(5, medicine.stackCount, "medicine count"); } // ---- Trade Ships Drop Spot --------------------------------------------------------------- [BlaxTest("rewards: with Trade Ships Drop Spot simulated the unsubscribe hint shows once on a map tick, only with a delivery zone and both routing toggles on")] public static void TradeShipsDropSpotHintOnce() { Map map = Fixtures.Map; MapComponent_BlaxZones comp = Fixtures.Comp; T.NotNull(comp, "MapComponent_BlaxZones of the current map"); string text = TradeShipsDropSpotHint.Text; T.Check(text.Contains("Trade Ships Drop Spot"), "the hint '" + text + "' doesn't name Trade Ships Drop Spot"); DropHintsAfterTest(text); // Messages drops a repeat of a live message, so each tick starts with none live and every call counts. void Tick() { Messages.Clear(); comp.MapComponentTick(); } TradeShipsDropSpotHint.Reset(); Fixtures.Settings.routeOrbital = true; Fixtures.Settings.routeRewards = true; Fixtures.DeliveryZone(Fixtures.TestArea(1, 1)); T.Check(!Compat.TradeShipsDropSpotActive, "Trade Ships Drop Spot counts as active with nothing simulated"); Tick(); T.Equal(0, Hints(text), "hints without Trade Ships Drop Spot"); Compat.SimulatedActive.Add(Compat.TradeShipsDropSpotDef); WithoutDeliveryZones(map, Tick); T.Equal(0, Hints(text), "hints on a map with no delivery zone"); T.Check(!Fixtures.Settings.tradeShipsHintShown, "the hint counts as shown on a map with no delivery zone"); Tick(); Tick(); Tick(); T.Equal(1, Hints(text), "hints after three map ticks with a delivery zone and both routing toggles on"); T.Check(Fixtures.Settings.tradeShipsHintShown, "the shown hint is not remembered in the mod settings"); TradeShipsDropSpotHint.Reset(); Fixtures.Settings.routeRewards = false; Tick(); T.Equal(1, Hints(text), "hints after a map tick with Route quest rewards off"); Fixtures.Settings.routeRewards = true; Fixtures.Settings.routeOrbital = false; Tick(); T.Equal(1, Hints(text), "hints after a map tick with Route orbital trade off"); } // ---- helpers --------------------------------------------------------------------------------- /// A friendly pawn for a quest drop, as a refugee quest hands it over (removed after the test). private static Pawn Refugee() { Faction friendly = Fixtures.FriendlyFaction(); if (friendly == null) T.Skip("no friendly faction in this world"); return Fixtures.Generate(PawnKindDefOf.Colonist, friendly); } /// Runs the action with the quest reward context set, as the patched callers do, and restores it. private static void InRewardContext(Action action) { DeliveryContext previous = DeliveryContext.Current; DeliveryContext.Current = DeliveryContext.QuestRewards; try { action(); } finally { DeliveryContext.Current = previous; } } private static void ThrowInsideContext() { contextAtFailure = DeliveryContext.Current; throw new InvalidOperationException(ForcedFailure); } private static bool Mentions(Exception e, string text) { for (Exception x = e; x != null; x = x.InnerException) { if (x.Message != null && x.Message.Contains(text)) return true; } return false; } private static void RecordContext() => contextsSeen.Add(DeliveryContext.Current); /// Messages with the text the player got (the message history; Messages.Message archives them). private static int Hints(string text) => Find.Archive.ArchivablesListForReading.Count(a => a is Message m && m.text == text.CapitalizeFirst()); /// Removes the hint messages from the message history after the test. private static void DropHintsAfterTest(string text) { Fixtures.OnCleanup(() => { foreach (IArchivable a in Find.Archive.ArchivablesListForReading.Where(a => a is Message m && m.text == text.CapitalizeFirst()).ToList()) Find.Archive.Remove(a); }); } /// /// Runs the action while ZoneManager's list holds no delivery zone, then puts the list back exactly as /// it was. Nothing deregisters: zone grid, caches and the zones themselves stay untouched. /// private static void WithoutDeliveryZones(Map map, Action action) { List all = map.zoneManager.AllZones; List before = all.ToList(); Fixtures.OnCleanup(() => { if (!all.SequenceEqual(before)) { all.Clear(); all.AddRange(before); } }); all.RemoveAll(z => z is Zone_Delivery); try { action(); } finally { all.Clear(); all.AddRange(before); } } } /// /// A test-only quest part with no Zones patch of its own: on its signal it records DeliveryContext.Current /// and drops its things near a fixed cell with DropPodUtility.DropThingsNear, as a mod's quest part might. /// Lives on a raw test quest that is never in the quest manager, so it is never saved. /// public class ContextProbePart : QuestPart { private readonly string inSignal; private readonly IntVec3 spot; private readonly List things; public bool Fired; public DeliveryContext ContextSeen; public ContextProbePart(string inSignal, IntVec3 spot, params Thing[] things) { this.inSignal = inSignal; this.spot = spot; this.things = things.ToList(); signalListenMode = SignalListenMode.Always; } public override void Notify_QuestSignalReceived(Signal signal) { base.Notify_QuestSignalReceived(signal); if (signal.tag != inSignal) return; Fired = true; ContextSeen = DeliveryContext.Current; DropPodUtility.DropThingsNear(spot, Fixtures.Map, things, canRoofPunch: false, forbid: false); } } }