forked from fluffy-mods/ColonyManager
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathManagerJob_Forestry.cs
548 lines (450 loc) · 20.7 KB
/
ManagerJob_Forestry.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
// ManagerJob_Forestry.cs
// Copyright Karel Kroeze, 2020-2020
using System.Collections.Generic;
using System.Linq;
using RimWorld;
using UnityEngine;
using Verse;
using static FluffyManager.Constants;
namespace FluffyManager
{
public class ManagerJob_Forestry : ManagerJob
{
public enum ForestryJobType
{
ClearArea,
ClearWind,
Logging
}
private static readonly WorkTypeDef PlantCutting =
DefDatabase<WorkTypeDef>.GetNamed( "PlantCutting" );
private readonly Utilities.CachedValue<int>
_designatedWoodCachedValue = new Utilities.CachedValue<int>();
public Dictionary<ThingDef, bool> AllowedTrees = new Dictionary<ThingDef, bool>();
public bool AllowSaplings;
public Dictionary<Area, bool> ClearAreas = new Dictionary<Area, bool>();
public bool ClearWindCells;
public History History;
public Area LoggingArea;
public new Trigger_Threshold Trigger;
private List<bool> _clearAreas_allowed;
private List<Area> _clearAreas_areas;
private List<Designation> _designations = new List<Designation>();
// backwards compatibility for new clear jobs
// TODO: REMOVE ON NEXT BREAKING VERSION!
private bool _newClearJobs;
private ForestryJobType _type = ForestryJobType.Logging;
public ManagerJob_Forestry( Manager manager ) : base( manager )
{
// populate the trigger field, set the root category to wood.
Trigger = new Trigger_Threshold( this );
Trigger.ThresholdFilter.SetDisallowAll();
Trigger.ThresholdFilter.SetAllow( ThingDefOf.WoodLog, true );
// initialize clearAreas list with current areas
UpdateClearAreas();
History = new History( new[] {I18n.HistoryStock, I18n.HistoryDesignated}, new[] {Color.white, Color.grey} );
// init stuff if we're not loading
// todo: please, please refactor this into something less clumsy!
if ( Scribe.mode == LoadSaveMode.Inactive )
RefreshAllowedTrees();
}
public override bool Completed
{
get
{
switch ( Type )
{
case ForestryJobType.Logging:
return !Trigger.State;
default:
return false;
}
}
}
public List<Designation> Designations => new List<Designation>( _designations );
public override bool IsValid => base.IsValid && Trigger != null && History != null;
public override string Label => "FMF.Forestry".Translate();
public override ManagerTab Tab
{
get { return manager.Tabs.Find( tab => tab is ManagerTab_Forestry ); }
}
public override string[] Targets
{
get
{
switch ( Type )
{
case ForestryJobType.Logging:
return AllowedTrees.Keys.Where( key => AllowedTrees[key] )
.Select( tree => tree.LabelCap.Resolve() )
.ToArray();
default:
var targets = ClearAreas
.Where( ca => ca.Value )
.Select( ca => ca.Key.Label );
if ( ClearWindCells )
targets = targets.Concat( "FMF.TurbineArea".Translate().Resolve() );
if ( !targets.Any() )
return new[] {"FM.None".Translate().RawText};
return targets.ToArray();
}
}
}
public ForestryJobType Type
{
get => _type;
set
{
_type = value;
RefreshAllowedTrees();
}
}
public override WorkTypeDef WorkTypeDef => PlantCutting;
public void AddRelevantGameDesignations()
{
// get list of game designations not managed by this job that could have been assigned by this job.
foreach ( var des in manager.map.designationManager.SpawnedDesignationsOfDef( DesignationDefOf.CutPlant )
.Except( _designations )
.Where( des => IsValidForestryTarget( des.target ) ) )
AddDesignation( des );
}
/// <summary>
/// Remove obsolete designations from the list.
/// </summary>
public void CleanDesignations()
{
// get the intersection of bills in the game and bills in our list.
var gameDesignations = manager.map.designationManager
.SpawnedDesignationsOfDef( DesignationDefOf.HarvestPlant ).ToList();
_designations = _designations.Intersect( gameDesignations ).ToList();
}
public override void CleanUp()
{
// clear the list of obsolete designations
CleanDesignations();
// cancel outstanding designation
foreach ( var des in _designations ) des.Delete();
// clear the list completely
_designations.Clear();
}
public string DesignationLabel( Designation designation )
{
// label, dist, yield.
var plant = designation.target.Thing as Plant;
return "Fluffy.Manager.DesignationLabel".Translate(
plant.LabelCap,
Distance( plant, manager.map.GetBaseCenter() ).ToString( "F0" ),
plant.YieldNow(),
plant.def.plant.harvestedThingDef.LabelCap );
}
public void DoClearAreaDesignations( IEnumerable<IntVec3> cells, ref bool workDone )
{
var map = manager.map;
var designationManager = map.designationManager;
foreach ( var cell in cells )
{
// confirm there is a plant here that it is a tree and that it has no current designation
var plant = cell.GetPlant( map );
// if there is no plant, or there is already a designation here, bail out
if ( plant == null || designationManager.AllDesignationsOn( plant ).Any() )
continue;
// if the plant is not in the allowed filter
if ( !AllowedTrees.ContainsKey( plant.def ) || !AllowedTrees[plant.def] )
continue;
// we don't cut stuff in growing zones
if ( map.zoneManager.ZoneAt( cell ) is IPlantToGrowSettable )
continue;
// nor in plant pots (or hydroponics)
if ( map.thingGrid.ThingsListAt( cell ).Any( t => t is Building_PlantGrower ) )
continue;
// there's no reason not to cut it down, so cut it down.
designationManager.AddDesignation( new Designation( plant, DesignationDefOf.CutPlant ) );
workDone = true;
}
}
public override void DrawListEntry( Rect rect, bool overview = true, bool active = true )
{
// (detailButton) | name | (bar | last update)/(stamp) -> handled in Utilities.DrawStatusForListEntry
var shownTargets = overview ? 4 : 3; // there's more space on the overview
// set up rects
Rect labelRect = new Rect( Margin, Margin, rect.width -
( active ? StatusRectWidth + 4 * Margin : 2 * Margin ),
rect.height - 2 * Margin ),
statusRect = new Rect( labelRect.xMax + Margin, Margin, StatusRectWidth, rect.height - 2 * Margin );
// create label string
var subtext = SubLabel( labelRect );
var text = Label + "\n" + subtext;
// do the drawing
GUI.BeginGroup( rect );
// draw label
Widgets_Labels.Label( labelRect, text, subtext, TextAnchor.MiddleLeft, margin: Margin );
// if the bill has a manager job, give some more info.
if ( active )
this.DrawStatusForListEntry( statusRect, Trigger );
GUI.EndGroup();
}
public override void DrawOverviewDetails( Rect rect )
{
History.DrawPlot( rect, Trigger.TargetCount );
}
public override void ExposeData()
{
// scribe base things
base.ExposeData();
// settings, references first!
Scribe_References.Look( ref LoggingArea, "LoggingArea" );
Scribe_Deep.Look( ref Trigger, "trigger", manager );
Scribe_Collections.Look( ref AllowedTrees, "AllowedTrees", LookMode.Def, LookMode.Value );
Scribe_Values.Look( ref _type, "type", ForestryJobType.Logging );
Scribe_Values.Look( ref AllowSaplings, "AllowSaplings" );
Scribe_Values.Look( ref ClearWindCells, "ClearWindCells" );
// backwards compatibility for clearing jobs
// TODO: REMOVE ON NEXT BREAKING VERSION!
Scribe_Values.Look( ref _newClearJobs, "NEW_CLEAR_JOBS" );
// clearing areas list
if ( Scribe.mode == LoadSaveMode.Saving )
{
// make sure areas list doesn't contain deleted areas
UpdateClearAreas();
// create scribe helper vars
_clearAreas_areas = new List<Area>( ClearAreas.Keys );
_clearAreas_allowed = new List<bool>( ClearAreas.Values );
}
// scribe that stuff
Scribe_Collections.Look( ref _clearAreas_areas, "ClearAreas_areas", LookMode.Reference );
Scribe_Collections.Look( ref _clearAreas_allowed, "ClearAreas_allowed", LookMode.Value );
// initialize areas dict from scribe helpers
if ( Scribe.mode == LoadSaveMode.PostLoadInit )
{
ClearAreas = new Dictionary<Area, bool>();
for ( var i = 0; i < _clearAreas_areas.Count; i++ )
if ( _clearAreas_areas[i] != null )
ClearAreas.Add( _clearAreas_areas[i], _clearAreas_allowed[i] );
}
if ( Manager.LoadSaveMode == Manager.Modes.Normal )
// scribe history
Scribe_Deep.Look( ref History, "History" );
}
public int GetWoodInDesignations()
{
var count = 0;
// try get cache
if ( _designatedWoodCachedValue.TryGetValue( out count ) ) return count;
foreach ( var des in _designations )
if ( des.target.HasThing &&
des.target.Thing is Plant )
{
var plant = des.target.Thing as Plant;
count += plant.YieldNow();
}
// update cache
_designatedWoodCachedValue.Update( count );
return count;
}
public void RefreshAllowedTrees()
{
Logger.Debug( "Refreshing allowed trees" );
// all plants
var options = manager.map.Biome.AllWildPlants
// cave plants (shrooms)
.Concat( DefDatabase<ThingDef>.AllDefsListForReading
.Where( td => td.plant?.cavePlant ?? false ) )
// ambrosia
.Concat( ThingDefOf.Plant_Ambrosia )
// and anything on the map that is not in a plant zone/planter
.Concat( manager.map.listerThings.AllThings.OfType<Plant>()
.Where( p => p.Spawned &&
!( manager.map.zoneManager.ZoneAt( p.Position ) is
IPlantToGrowSettable ) &&
manager.map.thingGrid.ThingsAt( p.Position )
.FirstOrDefault(
t => t is Building_PlantGrower ) == null )
.Select( p => p.def ) )
// add stuff in the current list
.Concat( AllowedTrees.Keys.ToList() )
// if type == logging, remove things that do not yield wood
.Where( td => Type == ForestryJobType.ClearArea ||
( td.plant.harvestTag == "Wood" ||
td.plant.harvestedThingDef == ThingDefOf.WoodLog ) &&
td.plant.harvestYield > 0 )
.Distinct();
// remove stuff not in new list
foreach ( var tree in AllowedTrees.Keys.ToList() )
if ( !options.Contains( tree ) )
AllowedTrees.Remove( tree );
// add stuff not in current list
foreach ( var tree in options )
if ( !AllowedTrees.ContainsKey( tree ) )
AllowedTrees.Add( tree, false );
// sort
AllowedTrees = AllowedTrees.OrderBy( at => at.Key.LabelCap.RawText )
.ToDictionary( at => at.Key, at => at.Value );
}
public string SubLabel( Rect rect )
{
string sublabel;
switch ( Type )
{
case ForestryJobType.Logging:
sublabel = string.Join( ", ", Targets );
if ( sublabel.Fits( rect ) )
return sublabel.Italic();
else
return "multiple".Translate().Italic();
default:
sublabel = "FMF.Clear".Translate( string.Join( ", ", Targets ) );
if ( sublabel.Fits( rect ) )
return sublabel.Italic();
else
return "FMF.Clear".Translate( "multiple".Translate() ).Italic();
}
}
public override void Tick()
{
History.Update( Trigger.CurrentCount, GetWoodInDesignations() );
}
public override bool TryDoJob()
{
// keep track if any actual work was done.
var workDone = false;
// clean dead designations
CleanDesignations();
switch ( Type )
{
case ForestryJobType.Logging:
DoLoggingJob( ref workDone );
break;
case ForestryJobType.ClearArea:
if ( ClearWindCells )
DoClearAreaDesignations( GetWindCells(), ref workDone );
if ( ClearAreas.Any() )
DoClearAreas( ref workDone );
break;
}
return workDone;
}
internal void UpdateClearAreas()
{
// init list of areas
if ( ClearAreas == null || ClearAreas.Count == 0 )
{
ClearAreas =
manager.map.areaManager.AllAreas.Where( area => area.AssignableAsAllowed() )
.ToDictionary( a => a, v => false );
}
else
{
// iterate over areas, add new areas.
foreach ( var area in manager.map.areaManager.AllAreas.Where( a => a.AssignableAsAllowed() ) )
if ( !ClearAreas.ContainsKey( area ) )
ClearAreas.Add( area, false );
// iterate over existing areas, clear deleted areas.
var Areas = new List<Area>( ClearAreas.Keys );
foreach ( var area in Areas )
if ( !manager.map.areaManager.AllAreas.Contains( area ) )
ClearAreas.Remove( area );
}
}
private void AddDesignation( Designation des )
{
// add to game
manager.map.designationManager.AddDesignation( des );
// add to internal list
_designations.Add( des );
}
private void AddDesignation( Plant p, DesignationDef def = null )
{
// create designation
var des = new Designation( p, def );
// pass to adder
AddDesignation( des );
}
private void CleanAreaDesignations()
{
foreach ( var des in _designations )
if ( !des.target.HasThing )
des.Delete();
else if ( !LoggingArea.ActiveCells.Contains( des.target.Thing.Position ) )
des.Delete();
}
private void DoClearAreas( ref bool workDone )
{
foreach ( var area in ClearAreas )
if ( area.Value )
DoClearAreaDesignations( area.Key.ActiveCells, ref workDone );
}
private void DoLoggingJob( ref bool workDone )
{
// remove designations not in zone.
if ( LoggingArea != null )
CleanAreaDesignations();
// add external designations
AddRelevantGameDesignations();
// get current lumber count
var count = Trigger.CurrentCount + GetWoodInDesignations();
// get sorted list of loggable trees
var trees = GetLoggableTreesSorted();
// designate untill we're either out of trees or we have enough designated.
for ( var i = 0; i < trees.Count && count < Trigger.TargetCount; i++ )
{
workDone = true;
AddDesignation( trees[i], DesignationDefOf.HarvestPlant );
count += trees[i].YieldNow();
}
}
private List<Plant> GetLoggableTreesSorted()
{
var position = manager.map.GetBaseCenter();
#if DEBUG_PERFORMANCE
DeepProfiler.Start( "GetLoggableTreesSorted" );
#endif
var list = manager.map.listerThings.AllThings.Where( IsValidForestryTarget )
.Select( p => p as Plant )
.OrderByDescending( p => p.YieldNow() / Distance( p, position ) )
.ToList();
#if DEBUG_PERFORMANCE
DeepProfiler.End();
#endif
return list;
}
private List<IntVec3> GetWindCells()
{
return manager.map.listerBuildings
.allBuildingsColonist
.Where( b => b.GetComp<CompPowerPlantWind>() != null )
.SelectMany( turbine => WindTurbineUtility.CalculateWindCells( turbine.Position,
turbine.Rotation,
turbine.RotatedSize ) )
.ToList();
}
private bool IsInWindTurbineArea( IntVec3 position )
{
return GetWindCells().Contains( position );
}
private bool IsValidForestryTarget( LocalTargetInfo t )
{
return t.HasThing
&& IsValidForestryTarget( t.Thing );
}
private bool IsValidForestryTarget( Thing t )
{
return t is Plant
&& IsValidForestryTarget( (Plant) t );
}
private bool IsValidForestryTarget( Plant target )
{
return target.def.plant != null
// non-biome trees won't be on the list
&& AllowedTrees.ContainsKey( target.def )
// also filters out non-tree plants
&& AllowedTrees[target.def]
&& target.Spawned
&& manager.map.designationManager.DesignationOn( target ) == null
// cut only mature trees, or saplings that yield something right now.
&& ( AllowSaplings || target.LifeStage == PlantLifeStage.Mature ) && target.YieldNow() > 1
&& ( LoggingArea == null || LoggingArea.ActiveCells.Contains( target.Position ) )
// reachable
&& IsReachable( target );
}
}
}