-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathBotStorage.cs
More file actions
315 lines (270 loc) · 9.86 KB
/
BotStorage.cs
File metadata and controls
315 lines (270 loc) · 9.86 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
using Bindito.Core;
using HarmonyLib;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using Timberborn.AssetSystem;
using Timberborn.Automation;
using Timberborn.AutomationBuildings;
using Timberborn.BaseComponentSystem;
using Timberborn.BlockSystem;
using Timberborn.BlueprintSystem;
using Timberborn.Buildings;
using Timberborn.CharacterModelSystem;
using Timberborn.DeteriorationSystem;
using Timberborn.EnterableSystem;
using Timberborn.EntitySystem;
using Timberborn.Goods;
using Timberborn.ModManagerScene;
using Timberborn.NeedSystem;
using Timberborn.PrioritySystem;
using Timberborn.SlotSystem;
using Timberborn.StatusSystem;
using Timberborn.TemplateInstantiation;
using Timberborn.WorkSystem;
using UnityEngine;
namespace Calloatti.BotStorage
{
public class BotStorageModStarter : IModStarter
{
public void StartMod(IModEnvironment modEnvironment)
{
new Harmony("calloatti.botstorage").PatchAll();
}
}
public record BotStorageBuildingSpec : ComponentSpec;
// Removed IStatusHider to prevent the ECS crash
public class BotStorageBuilding : BaseComponent, IAwakableComponent, IUpdatableComponent, IDeletableEntity
{
private Enterable _enterable;
private SlotManager _slotManager;
private float _easterEggTimer;
private float _nextEasterEggTime;
private static readonly string[] EasterEggAnimations = { "ForcedIdle", "Sleeping", "Sitting", "CharacterControl", "Stranded" };
public void Awake()
{
_enterable = GetComponent<Enterable>();
_slotManager = GetComponent<SlotManager>();
// Safely subscribe using named methods
_enterable.EntererAdded += OnEntererAdded;
_enterable.EntererRemoved += OnEntererRemoved;
GetComponent<WorkplacePriority>()?.SetPriority(Timberborn.PrioritySystem.Priority.VeryLow);
ResetEasterEggTimer();
}
// Implement IDeletableEntity to prevent memory leaks when the building is destroyed
public void DeleteEntity()
{
if (_enterable != null)
{
_enterable.EntererAdded -= OnEntererAdded;
_enterable.EntererRemoved -= OnEntererRemoved;
}
}
private void OnEntererAdded(object sender, EntererAddedEventArgs e)
{
NeedManager nm = e.Enterer.GetComponent<NeedManager>();
if (nm != null) foreach (var n in nm.NeedSpecs) nm.DisableUpdate(n.Id);
}
private void OnEntererRemoved(object sender, EntererRemovedEventArgs e)
{
NeedManager nm = e.Enterer.GetComponent<NeedManager>();
if (nm != null) foreach (var n in nm.NeedSpecs) nm.EnableUpdate(n.Id);
CharacterAnimator animator = e.Enterer.GetComponent<CharacterAnimator>();
if (animator != null)
{
foreach (string anim in EasterEggAnimations)
{
if (animator.HasParameter(anim))
{
animator.SetBool(anim, false);
}
}
}
}
public void Update()
{
if (_enterable.NumberOfEnterersInside == 0) return;
_easterEggTimer += Time.deltaTime;
if (_easterEggTimer >= _nextEasterEggTime)
{
TriggerEasterEgg();
ResetEasterEggTimer();
}
}
private void ResetEasterEggTimer()
{
_easterEggTimer = 0f;
_nextEasterEggTime = UnityEngine.Random.Range(30f, 120f);
}
private void TriggerEasterEgg()
{
var bots = _enterable.EnterersInside.ToList();
if (bots.Count == 0) return;
var randomBot = bots[UnityEngine.Random.Range(0, bots.Count)];
GetComponent<MonoBehaviour>().StartCoroutine(EasterEggRoutine(randomBot));
}
private IEnumerator EasterEggRoutine(Enterer bot)
{
CharacterAnimator animator = bot.GetComponent<CharacterAnimator>();
if (animator == null) yield break;
string defaultAnim = "ForcedAPose";
var slots = Traverse.Create(_slotManager).Field("_slots").GetValue<List<ISlot>>();
var botSlot = slots?.OfType<TransformSlot>().FirstOrDefault(s => s.AssignedEnterer == bot);
if (botSlot != null)
{
var spec = Traverse.Create(botSlot).Field("_transformSlotSpec").GetValue<TransformSlotSpec>();
if (spec != null)
{
defaultAnim = spec.Animation;
}
}
string randomAnim = EasterEggAnimations[UnityEngine.Random.Range(0, EasterEggAnimations.Length)];
if (animator.HasParameter(defaultAnim))
{
animator.SetBool(defaultAnim, false);
}
if (animator.HasParameter(randomAnim))
{
animator.SetBool(randomAnim, true);
}
yield return new WaitForSeconds(UnityEngine.Random.Range(3f, 6f));
// Re-verify that both the bot and its animator still exist after the wait
if (bot != null && animator != null && _enterable.EnterersInside.Contains(bot))
{
if (animator.HasParameter(randomAnim))
{
animator.SetBool(randomAnim, false);
}
if (animator.HasParameter(defaultAnim))
{
animator.SetBool(defaultAnim, true);
}
}
}
}
// Banner Setter
public class BotStorageBannerSetter : BaseComponent, IAwakableComponent, IFinishedStateListener, IDeletableEntity
{
private static readonly Color BannerIconColor = new Color(0.33f, 0.33f, 0.33f);
private readonly IAssetLoader _assetLoader;
private BlockObject _blockObject;
private MeshRenderer _meshRenderer;
private Material _cachedMaterial;
// Cache the texture statically so we only query the asset loader once per game session
private static Texture2D _botHeadTexture;
private static bool _textureLoaded = false;
private static readonly int IconColorProperty = Shader.PropertyToID("_DetailAlbedoUV2Color");
private static readonly int TextureProperty = Shader.PropertyToID("_DetailAlbedoMap2");
public BotStorageBannerSetter(IAssetLoader assetLoader)
{
_assetLoader = assetLoader;
}
public void Awake()
{
_blockObject = GetComponent<BlockObject>();
BuildingModel component = GetComponent<BuildingModel>();
if (!_textureLoaded)
{
_botHeadTexture = _assetLoader.LoadSafe<Texture2D>("Sprites/Goods/BotHeadIcon");
_textureLoaded = true;
}
// First, try to find a separated BannerMesh if they made one
Transform bannerTransform = component.FinishedModel.transform.Find("BannerMesh");
if (bannerTransform != null)
{
_meshRenderer = bannerTransform.GetComponent<MeshRenderer>();
}
else
{
// Fallback: If they kept it as one mesh but added UV2, grab the main building mesh
_meshRenderer = component.FinishedModel.GetComponentInChildren<MeshRenderer>();
}
}
public void OnEnterFinishedState()
{
if (_meshRenderer != null && _botHeadTexture != null)
{
// Accessing .material creates a clone of the material in memory just for this building
if (_cachedMaterial == null)
{
_cachedMaterial = _meshRenderer.material;
}
// Apply the texture and color directly to the shader properties used by Timberborn's Decal/UV2 system
_cachedMaterial.SetTexture(TextureProperty, _botHeadTexture);
_cachedMaterial.SetColor(IconColorProperty, BannerIconColor);
}
}
public void OnExitFinishedState() { }
// Flush the cloned material from memory when the building gets demolished
public void DeleteEntity()
{
if (_cachedMaterial != null)
{
UnityEngine.Object.Destroy(_cachedMaterial);
_cachedMaterial = null;
}
}
}
[Context("Game")]
public class BotStorageConfigurator : Configurator
{
protected override void Configure()
{
Bind<BotStorageBuilding>().AsTransient();
Bind<BotStorageBannerSetter>().AsTransient();
MultiBind<TemplateModule>().ToProvider(ProvideTemplateModule).AsSingleton();
}
private static TemplateModule ProvideTemplateModule()
{
var builder = new TemplateModule.Builder();
builder.AddDecorator<BotStorageBuildingSpec, BotStorageBuilding>();
builder.AddDecorator<BotStorageBuildingSpec, WaitInsideIdlyWorkplaceBehavior>();
builder.AddDecorator<BotStorageBuildingSpec, BotStorageBannerSetter>();
builder.AddDecorator<BotStorageBuildingSpec, PausableBuilding>();
return builder.Build();
}
}
// Stops the "Unstaffed/No Workers" warning from ever registering onto the Bot Storage building
[HarmonyPatch(typeof(StatusSubject), nameof(StatusSubject.RegisterStatus))]
public static class PreventUnstaffedStatusPatch
{
public static bool Prefix(StatusSubject __instance, StatusToggle statusToggle)
{
// If this status is trying to attach to our BotStorageBuilding
if (__instance.GetComponent<BotStorageBuilding>() != null)
{
// Target the internal SpriteName, which is hardcoded and language-independent!
string spriteName = statusToggle.StatusSpecification.SpriteName ?? "";
// Timberborn uses "NoUnemployed" for the lack of workers icon
if (spriteName.Contains("NoUnemployed"))
{
// Return false to completely skip running the original method, effectively blocking the warning
return false;
}
}
return true;
}
}
[HarmonyPatch(typeof(Deteriorable), nameof(Deteriorable.Tick))]
public static class DeteriorableTickPatch
{
public static bool Prefix(Deteriorable __instance)
{
Worker worker = __instance.GetComponent<Worker>();
if (worker != null && worker.Employed)
{
var workplace = worker.Workplace;
if (workplace != null && workplace.GetComponent<BotStorageBuilding>() != null)
{
var enterable = workplace.GetComponent<Enterable>();
var enterer = worker.GetComponent<Enterer>();
if (enterable != null && enterer != null && enterable.EnterersInside.Contains(enterer))
{
return false;
}
}
}
return true;
}
}
}