forked from cuproPanda/Quarry
-
Notifications
You must be signed in to change notification settings - Fork 4
/
Building_Quarry.cs
641 lines (569 loc) · 21.1 KB
/
Building_Quarry.cs
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
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
using System.Collections.Generic;
using System.Linq;
using UnityEngine;
using RimWorld;
using Verse;
using System.Text;
namespace Quarry
{
public enum ResourceRequest
{
None,
Resources,
Blocks
}
public enum MoteType
{
None,
LargeVein,
Failure
}
[StaticConstructorOnStartup]
public class Building_Quarry : Building
{
#region Fields
public bool autoHaul = true;
public bool mineModeToggle = true;
private float quarryPercent = 1f;
private int jobsCompleted = 0;
private bool firstSpawn = false;
private CompAffectedByFacilities facilityComp;
private List<string> rockTypesUnder = new List<string>();
private List<ThingDef> blocksUnder = new List<ThingDef>();
private List<ThingDef> chunksUnder = new List<ThingDef>();
private List<Pawn> owners => compAssignable.AssignedPawnsForReading;
#endregion Fields
#region Public Properties
public virtual int WallThickness => 2;
public bool Unowned => owners.Count <= 0;
public bool Depleted => QuarryPercent <= 0;
public IEnumerable<Pawn> AssigningCandidates
{
get
{
if (!Spawned)
{
return Enumerable.Empty<Pawn>();
}
return Map.mapPawns.FreeColonists.Where(x=> !x.WorkTagIsDisabled(WorkTags.Mining) && !x.WorkTypeIsDisabled(WorkTypeDefOf.Mining));
}
}
public CompAssignableToPawn compAssignable
{
get
{
return this.TryGetComp<CompAssignableToPawn>();
}
}
public CompForbiddable forbiddable
{
get
{
return this.TryGetComp<CompForbiddable>();
}
}
public IEnumerable<Pawn> AssignedPawns
{
get
{
return owners;
}
}
public int MaxAssignedPawnsCount
{
get
{
if (!Spawned)
{
return 0;
}
return this.OccupiedRect().ContractedBy(WallThickness).Cells.Count();
}
}
public bool AssignedAnything(Pawn pawn)
{
return false;
}
public float QuarryPercent
{
get
{
if (QuarrySettings.QuarryMaxHealth == int.MaxValue)
{
return 100f;
}
return quarryPercent * 100f;
}
}
public bool HasConnectedPlatform
{
get { return !facilityComp.LinkedFacilitiesListForReading.NullOrEmpty(); }
}
public List<ThingDef> ChunksUnder
{
get
{
if (chunksUnder.Count <= 0)
{
MakeThingDefListsFrom(RockTypesUnder);
}
return chunksUnder;
}
}
public List<ThingDef> BlocksUnder
{
get
{
if (blocksUnder.Count <= 0)
{
MakeThingDefListsFrom(RockTypesUnder);
}
return blocksUnder;
}
}
#endregion Public Properties
#region Protected Properties
protected virtual int QuarryDamageMultiplier => 1;
protected virtual int SinkholeFrequency => 100;
protected virtual List<IntVec3> LadderOffsets
{
get
{
return new List<IntVec3>() {
Static.LadderOffset_Big1,
Static.LadderOffset_Big2,
Static.LadderOffset_Big3,
Static.LadderOffset_Big4
};
}
}
#endregion Protected Properties
#region Private Properties
private int OwnerInspectCount => (owners.Count > 3) ? 3 : owners.Count;
private bool PlayerCanSeeOwners
{
get
{
if (Faction == Faction.OfPlayer)
{
return true;
}
for (int i = 0; i < owners.Count; i++)
{
if (owners[i].Faction == Faction.OfPlayer || owners[i].HostFaction == Faction.OfPlayer)
{
return true;
}
}
return false;
}
}
private List<string> RockTypesUnder
{
get
{
if (rockTypesUnder.Count <= 0)
{
rockTypesUnder = RockTypesFromMap();
}
return rockTypesUnder;
}
}
private string HaulDescription
{
get { return (autoHaul ? Static.LabelHaul : Static.LabelNotHaul); }
}
#endregion Private Properties
#region MethodGroup_Root
#region MethodGroup_SaveLoad
public override void ExposeData()
{
base.ExposeData();
if (Scribe.mode == LoadSaveMode.Saving)
{
owners.RemoveAll((Pawn x) => x.Destroyed);
}
Scribe_Values.Look(ref autoHaul, "QRY_boolAutoHaul", true);
Scribe_Values.Look(ref mineModeToggle, "QRY_mineMode", true);
Scribe_Values.Look(ref quarryPercent, "QRY_quarryPercent", 1f);
Scribe_Values.Look(ref jobsCompleted, "QRY_jobsCompleted", 0);
Scribe_Collections.Look(ref rockTypesUnder, "QRY_rockTypesUnder", LookMode.Value);
if (Scribe.mode == LoadSaveMode.PostLoadInit)
{
SortOwners();
}
}
public override void PostMake()
{
base.PostMake();
firstSpawn = true;
}
public override void SpawnSetup(Map map, bool respawningAfterLoad)
{
base.SpawnSetup(map, respawningAfterLoad);
facilityComp = GetComp<CompAffectedByFacilities>();
if (firstSpawn)
{
// Set the initial quarry health
quarryPercent = 1f;
CellRect rect = this.OccupiedRect();
// Remove this area from the quarry grid. Quarries can never be built here again
map.GetComponent<QuarryGrid>().RemoveFromGrid(rect);
foreach (IntVec3 c in rect)
{
// What type of terrain are we over?
string rockType = c.GetTerrain(Map).defName.Split('_').First();
// If this is a valid rock type, add it to the list
if (QuarryUtility.IsValidQuarryRock(rockType))
{
rockTypesUnder.Add(rockType);
}
// Change the terrain here to be quarried stone
if (rect.ContractedBy(WallThickness).Contains(c))
{
Map.terrainGrid.SetTerrain(c, QuarryDefOf.QRY_QuarriedGround);
}
else
{
Map.terrainGrid.SetTerrain(c, QuarryDefOf.QRY_QuarriedGroundWall);
}
}
// Now that all the cells have been processed, create ThingDef lists
MakeThingDefListsFrom(RockTypesUnder);
// Spawn filth for the quarry
foreach (IntVec3 c in rect)
{
SpawnFilth(c);
}
// Change the ground back to normal quarried stone where the ladders are
// This is to negate the speed decrease and encourages pawns to use the ladders
foreach (IntVec3 offset in LadderOffsets)
{
Map.terrainGrid.SetTerrain(Position + offset.RotatedBy(Rotation), QuarryDefOf.QRY_QuarriedGround);
}
}
}
public override void Destroy(DestroyMode mode = DestroyMode.Vanish)
{
RemoveAllOwners();
foreach (IntVec3 c in GenAdj.CellsOccupiedBy(this))
{
// Change the terrain here back to quarried stone, removing the walls
Map.terrainGrid.SetTerrain(c, QuarryDefOf.QRY_QuarriedGround);
}
if (!QuarrySettings.letterSent && !TutorSystem.AdaptiveTrainingEnabled)
{
Find.LetterStack.ReceiveLetter(Static.LetterLabel, Static.LetterText, QuarryDefOf.CuproLetter, new RimWorld.Planet.GlobalTargetInfo(Position, Map));
QuarrySettings.letterSent = true;
}
if (TutorSystem.AdaptiveTrainingEnabled)
{
LessonAutoActivator.TeachOpportunity(QuarryDefOf.QRY_ReclaimingSoil, OpportunityType.GoodToKnow);
}
base.Destroy(mode);
}
#endregion MethodGroup_SaveLoad
#region MethodGroup_Assigning
public void TryAssignPawn(Pawn pawn)
{
if (!owners.Contains(pawn))
{
owners.Add(pawn);
}
}
public void TryUnassignPawn(Pawn pawn)
{
if (owners.Contains(pawn))
{
owners.Remove(pawn);
}
}
public void SortOwners()
{
owners.SortBy((Pawn x) => x.thingIDNumber);
}
private void RemoveAllOwners()
{
owners.Clear();
}
#endregion MethodGroup_Assigning
#region MethodGroup_Quarry
private List<string> RockTypesFromMap()
{
// Try to add all the rock types found in the map
List<string> list = new List<string>();
List<TaggedString> tempRockTypesUnder = Find.World.NaturalRockTypesIn(Map.Tile).Select(r => r.LabelCap).ToList();
foreach (string str in tempRockTypesUnder)
{
if (QuarryUtility.IsValidQuarryRock(str))
{
list.Add(str);
}
}
// This will cause an error if there still isn't a list, so make a new one using known rocks
if (list.Count <= 0)
{
Log.Warning("Quarry:: No valid rock types were found in the map. Building list using vanilla rocks.");
list = new List<string>() { "Sandstone", "Limestone", "Granite", "Marble", "Slate" };
}
return list;
}
private void MakeThingDefListsFrom(List<string> stringList)
{
chunksUnder = new List<ThingDef>();
blocksUnder = new List<ThingDef>();
foreach (string str in stringList)
{
if (QuarryUtility.IsValidQuarryChunk(str, out ThingDef chunk))
{
chunksUnder.Add(chunk);
}
if (QuarryUtility.IsValidQuarryBlocks(str, out ThingDef blocks))
{
blocksUnder.Add(blocks);
}
}
}
private void SpawnFilth(IntVec3 c)
{
List<Thing> thingsInCell = new List<Thing>();
// Skip this cell if it is occupied by a placed object
// This is to avoid save compression errors
thingsInCell = Map.thingGrid.ThingsListAtFast(c);
for (int t = 0; t < thingsInCell.Count; t++)
{
if (thingsInCell[t].def.saveCompressible)
{
return;
}
}
int filthAmount = Rand.RangeInclusive(1, 100);
// If this cell isn't filthy enough, skip it
if (filthAmount <= 20)
{
return;
}
// Check for dirt filth
if (filthAmount <= 40)
{
GenSpawn.Spawn(ThingMaker.MakeThing(ThingDefOf.Filth_Dirt), c, Map);
}
else
{
GenSpawn.Spawn(ThingMaker.MakeThing(ThingDefOf.Filth_RubbleRock), c, Map);
// Check for chunks
if (filthAmount > 80)
{
GenSpawn.Spawn(ThingMaker.MakeThing(ChunksUnder.RandomElement()), c, Map);
}
}
}
public ThingDef GiveResources(ResourceRequest req, out MoteType mote, out bool singleSpawn, out bool eventTriggered)
{
// Increment the jobs completed
jobsCompleted++;
eventTriggered = false;
mote = MoteType.None;
singleSpawn = true;
// Decrease the amount this quarry can be mined, eventually depleting it
if (QuarrySettings.QuarryMaxHealth != int.MaxValue)
{
QuarryMined();
}
// Determine if the mining job resulted in a sinkhole event, based on game difficulty
if (jobsCompleted % SinkholeFrequency == 0 && Rand.Chance(Find.Storyteller.difficulty.difficulty / 50f))
{
eventTriggered = true;
// The sinkhole damages the quarry a little
QuarryMined(Rand.RangeInclusive(1, 3));
}
// Cache values since this process is convoluted and the values need to remain the same
bool junkMined = Rand.Chance(QuarrySettings.junkChance / 100f);
// Check for blocks first to prevent spawning chunks (these would just be cut into blocks)
if (req == ResourceRequest.Blocks)
{
if (!junkMined)
{
singleSpawn = false;
return BlocksUnder.RandomElement();
}
// The rock didn't break into a usable size, spawn rubble
mote = MoteType.Failure;
return ThingDefOf.Filth_RubbleRock;
}
// Try to give junk before resources. This simulates only mining chunks or useless rubble
if (junkMined)
{
if (Rand.Chance(QuarrySettings.chunkChance / 100f))
{
return ChunksUnder.RandomElement();
}
else
{
mote = MoteType.Failure;
return ThingDefOf.Filth_RubbleRock;
}
}
// Try to give resources
if (req == ResourceRequest.Resources)
{
singleSpawn = false;
return OreDictionary.TakeOne();
}
// The quarry was most likely toggled off while a pawn was still working. Give junk
else
{
return ThingDefOf.Filth_RubbleRock;
}
}
private void QuarryMined(int damage = 1)
{
quarryPercent = ((QuarrySettings.quarryMaxHealth * quarryPercent) - (damage * QuarryDamageMultiplier)) / QuarrySettings.quarryMaxHealth;
}
public bool TryFindBestPlatformCell(Thing t, Pawn carrier, Map map, Faction faction, out IntVec3 foundCell)
{
List<Thing> facilities = facilityComp.LinkedFacilitiesListForReading;
for (int f = 0; f < facilities.Count; f++)
{
if (facilities[f].GetSlotGroup() == null || !facilities[f].GetSlotGroup().Settings.AllowedToAccept(t))
{
continue;
}
foreach (IntVec3 c in GenAdj.CellsOccupiedBy(facilities[f]))
{
if (StoreUtility.IsGoodStoreCell(c, map, t, carrier, faction))
{
foundCell = c;
return true;
}
}
}
foundCell = IntVec3.Invalid;
return false;
}
#endregion MethodGroup_Quarry
#region MethodGroup_Inspecting
public override IEnumerable<Gizmo> GetGizmos()
{
Command_Action mineMode = new Command_Action()
{
icon = (mineModeToggle ? Static.DesignationQuarryResources : Static.DesignationQuarryBlocks),
defaultLabel = (mineModeToggle ? Static.LabelMineResources : Static.LabelMineBlocks),
defaultDesc = (mineModeToggle ? Static.DescriptionMineResources : Static.DescriptionMineBlocks),
hotKey = KeyBindingDefOf.Misc10,
activateSound = SoundDefOf.Click,
action = () => { mineModeToggle = !mineModeToggle; },
};
// Only allow this option if stonecutting has been researched
// The default behavior is to allow resources, but not blocks
if (!QuarryDefOf.Stonecutting.IsFinished)
{
mineMode.Disable(Static.ReportGizmoLackingResearch);
}
yield return mineMode;
yield return new Command_Toggle()
{
icon = Static.DesignationHaul,
defaultLabel = Static.LabelHaulMode,
defaultDesc = HaulDescription,
hotKey = KeyBindingDefOf.Misc11,
activateSound = SoundDefOf.Click,
isActive = () => autoHaul,
toggleAction = () => { autoHaul = !autoHaul; },
};
yield return new Command_Action
{
defaultLabel = Static.CommandBedSetOwnerLabel,
icon = ContentFinder<Texture2D>.Get("UI/Commands/AssignOwner", true),
defaultDesc = Static.CommandSetOwnerDesc,
action = delegate
{
Find.WindowStack.Add(new Dialog_AssignBuildingOwner(this.TryGetComp<CompAssignableToPawn>()));
},
hotKey = KeyBindingDefOf.Misc3
};
/*
if (base.GetGizmos() != null)
{
Log.Message("do base.GetGizmos()");
foreach (Command c in base.GetGizmos())
{
Log.Message(string.Format("base.GetGizmos() {0}",c));
yield return c;
}
}
*/
IEnumerator<Gizmo> enumerator = null;
if (((this.def.BuildableByPlayer && this.def.passability != Traversability.Impassable && !this.def.IsDoor) || this.def.building.forceShowRoomStats) && Gizmo_RoomStats.GetRoomToShowStatsFor(this) != null && Find.Selector.SingleSelectedObject == this)
{
yield return new Gizmo_RoomStats(this);
}
if (this.def.Minifiable && base.Faction == Faction.OfPlayer)
{
yield return InstallationDesignatorDatabase.DesignatorFor(this.def);
}
Command command = BuildCopyCommandUtility.BuildCopyCommand(this.def, base.Stuff);
if (command != null)
{
yield return command;
}
if (base.Faction == Faction.OfPlayer)
{
foreach (Command command2 in BuildFacilityCommandUtility.BuildFacilityCommands(this.def))
{
yield return command2;
}
IEnumerator<Command> enumerator2 = null;
}
if (forbiddable!=null)
{
foreach (Gizmo item in forbiddable.CompGetGizmosExtra())
{
yield return item;
}
;
}
yield break;
Log.Message("post base.GetGizmos()");
}
public override string GetInspectString()
{
StringBuilder stringBuilder = new StringBuilder();
stringBuilder.AppendLine(Static.InspectQuarryPercent + ": " + QuarryPercent.ToStringDecimalIfSmall() + "%");
if (PlayerCanSeeOwners)
{
stringBuilder.AppendLine("ForColonistUse".Translate());
if (owners.Count == 0)
{
stringBuilder.AppendLine("Owner".Translate() + ": " + "Nobody".Translate().ToLower());
}
else if (owners.Count == 1)
{
stringBuilder.AppendLine("Owner".Translate() + ": " + owners[0].Label);
}
else
{
stringBuilder.Append("Owners".Translate() + ": ");
bool conjugate = false;
for (int i = 0; i < OwnerInspectCount; i++)
{
if (conjugate)
{
stringBuilder.Append(", ");
}
conjugate = true;
stringBuilder.Append(owners[i].LabelShort);
}
if (owners.Count > 3)
{
stringBuilder.Append($" (+ {owners.Count - 3})");
}
stringBuilder.AppendLine();
}
}
return stringBuilder.ToString().TrimEndNewlines();
}
#endregion MethodGroup_Inspecting
#endregion MethodGroup_Root
}
}