73 lines
2.4 KiB
C#
73 lines
2.4 KiB
C#
using RimWorld;
|
|
using rjw;
|
|
using rjwquirks.Modules.Shared.Events;
|
|
using System.Collections.Generic;
|
|
using System.Linq;
|
|
using Verse;
|
|
|
|
namespace rjwquirks.Modules.Quirks.EventHandlers
|
|
{
|
|
/// <summary>
|
|
/// Handler that passes RJW events a particular comps of an unassigned QuirkDef
|
|
/// </summary>
|
|
public class RecordChangedRjwEventHandler : RjwEventHandler
|
|
{
|
|
/// <summary>
|
|
/// Records that have associated quirk adder def comps.
|
|
/// Used to quickly filter out updates of irrelevant records.
|
|
/// </summary>
|
|
private static Dictionary<RecordDef, List<Comps.Adder_OnRecordExceeding>> _recordsWithAdder;
|
|
|
|
public override void HandleEvent(RjwEvent ev)
|
|
{
|
|
if (ev.def != RjwEventDefOf.RecordChanged)
|
|
{
|
|
ModLog.Warning($"RecordChangedRjwEventHandler recieved {ev.def}, but it only handles RecordChanged event");
|
|
return;
|
|
}
|
|
|
|
if (_recordsWithAdder == null)
|
|
{
|
|
BuildAdderCache();
|
|
}
|
|
|
|
if (!ev.args.TryGetArg(RjwEventArgNames.Record, out RecordDef recordDef))
|
|
{
|
|
ModLog.Error($"RecordChangedRjwEventHandler recieved {ev.def}, but event has no '{RjwEventArgNames.Record}' argument");
|
|
return;
|
|
}
|
|
|
|
if (!_recordsWithAdder.TryGetValue(recordDef, out var comps))
|
|
{
|
|
return;
|
|
}
|
|
|
|
foreach (var comp in comps)
|
|
{
|
|
// Send message to the def comps directly because the quirk is not assigned to a pawn yet
|
|
comp.NotifyEvent(ev);
|
|
}
|
|
}
|
|
|
|
/// <summary>
|
|
/// Builds _recordsWithAdder dictionary
|
|
/// </summary>
|
|
private static void BuildAdderCache()
|
|
{
|
|
_recordsWithAdder = new Dictionary<RecordDef, List<Comps.Adder_OnRecordExceeding>>();
|
|
|
|
foreach (var comp in DefDatabase<QuirkDef>.AllDefs.SelectMany(def => def.GetComps<Comps.Adder_OnRecordExceeding>()))
|
|
{
|
|
if (_recordsWithAdder.TryGetValue(comp.record, out var comps))
|
|
{
|
|
comps.Add(comp);
|
|
}
|
|
else
|
|
{
|
|
_recordsWithAdder[comp.record] = new List<Comps.Adder_OnRecordExceeding>() { comp };
|
|
}
|
|
}
|
|
}
|
|
}
|
|
}
|