forked from DFHack/dfhack
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathworkflow.cpp
1910 lines (1549 loc) · 52.9 KB
/
workflow.cpp
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
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#include "Core.h"
#include "Console.h"
#include "Export.h"
#include "PluginManager.h"
#include "MiscUtils.h"
#include "LuaTools.h"
#include "DataFuncs.h"
#include "modules/Materials.h"
#include "modules/Items.h"
#include "modules/Gui.h"
#include "modules/Job.h"
#include "modules/World.h"
#include "DataDefs.h"
#include "df/world.h"
#include "df/ui.h"
#include "df/building_workshopst.h"
#include "df/building_furnacest.h"
#include "df/job.h"
#include "df/job_item.h"
#include "df/job_list_link.h"
#include "df/dfhack_material_category.h"
#include "df/item.h"
#include "df/item_quality.h"
#include "df/items_other_id.h"
#include "df/tool_uses.h"
#include "df/general_ref.h"
#include "df/general_ref_unit_workerst.h"
#include "df/general_ref_unit_holderst.h"
#include "df/general_ref_building_holderst.h"
#include "df/general_ref_contains_itemst.h"
#include "df/general_ref_contained_in_itemst.h"
#include "df/general_ref_contains_unitst.h"
#include "df/itemdef_foodst.h"
#include "df/reaction.h"
#include "df/reaction_reagent_itemst.h"
#include "df/reaction_product_itemst.h"
#include "df/plant_raw.h"
#include "df/inorganic_raw.h"
#include "df/builtin_mats.h"
#include "df/vehicle.h"
using std::vector;
using std::string;
using std::endl;
using namespace DFHack;
using namespace df::enums;
using df::global::world;
using df::global::ui;
using df::global::ui_workshop_job_cursor;
using df::global::job_next_id;
/* Plugin registration */
static command_result workflow_cmd(color_ostream &out, vector <string> & parameters);
static void init_state(color_ostream &out);
static void cleanup_state(color_ostream &out);
DFHACK_PLUGIN("workflow");
DFhackCExport command_result plugin_init (color_ostream &out, std::vector <PluginCommand> &commands)
{
if (!world || !ui)
return CR_FAILURE;
if (ui_workshop_job_cursor && job_next_id) {
commands.push_back(
PluginCommand(
"workflow", "Manage control of repeat jobs.",
workflow_cmd, false,
" workflow enable [option...]\n"
" workflow disable [option...]\n"
" If no options are specified, enables or disables the plugin.\n"
" Otherwise, enables or disables any of the following options:\n"
" - drybuckets: Automatically empty abandoned water buckets.\n"
" - auto-melt: Resume melt jobs when there are objects to melt.\n"
" workflow jobs\n"
" List workflow-controlled jobs (if in a workshop, filtered by it).\n"
" workflow list\n"
" List active constraints, and their job counts.\n"
" workflow list-commands\n"
" List workflow commands that re-create existing constraints.\n"
" workflow count <constraint-spec> <cnt-limit> [cnt-gap]\n"
" workflow amount <constraint-spec> <cnt-limit> [cnt-gap]\n"
" Set a constraint. The first form counts each stack as only 1 item.\n"
" workflow unlimit <constraint-spec>\n"
" Delete a constraint.\n"
" workflow unlimit-all\n"
" Delete all constraints.\n"
"Function:\n"
" - When the plugin is enabled, it protects all repeat jobs from removal.\n"
" If they do disappear due to any cause, they are immediately re-added\n"
" to their workshop and suspended.\n"
" - In addition, when any constraints on item amounts are set, repeat jobs\n"
" that produce that kind of item are automatically suspended and resumed\n"
" as the item amount goes above or below the limit. The gap specifies how\n"
" much below the limit the amount has to drop before jobs are resumed;\n"
" this is intended to reduce the frequency of jobs being toggled.\n"
"Constraint format:\n"
" The contstraint spec consists of 4 parts, separated with '/' characters:\n"
" ITEM[:SUBTYPE]/[GENERIC_MAT,...]/[SPECIFIC_MAT:...]/[LOCAL,<quality>]\n"
" The first part is mandatory and specifies the item type and subtype,\n"
" using the raw tokens for items, in the same syntax you would e.g. use\n"
" for a custom reaction input. The subsequent parts are optional:\n"
" - A generic material spec constrains the item material to one of\n"
" the hard-coded generic classes, like WOOD, METAL, YARN or MILK.\n"
" - A specific material spec chooses the material exactly, using the\n"
" raw syntax for reaction input materials, e.g. INORGANIC:IRON,\n"
" although for convenience it also allows just IRON, or ACACIA:WOOD.\n"
" - A comma-separated list of miscellaneous flags, which currently can\n"
" be used to ignore imported items or items below a certain quality.\n"
"Constraint examples:\n"
" workflow amount AMMO:ITEM_AMMO_BOLTS/METAL 1000 100\n"
" workflow amount AMMO:ITEM_AMMO_BOLTS/WOOD,BONE 200 50\n"
" Keep metal bolts within 900-1000, and wood/bone within 150-200.\n"
" workflow count FOOD 120 30\n"
" workflow count DRINK 120 30\n"
" Keep the number of prepared food & drink stacks between 90 and 120\n"
" workflow count BIN 30\n"
" workflow count BARREL 30\n"
" workflow count BOX/CLOTH,SILK,YARN 30\n"
" Make sure there are always 25-30 empty bins/barrels/bags.\n"
" workflow count BAR//COAL 20\n"
" workflow count BAR//COPPER 30\n"
" Make sure there are always 15-20 coal and 25-30 copper bars.\n"
" workflow count CRAFTS//GOLD 20\n"
" Produce 15-20 gold crafts.\n"
" workflow count POWDER_MISC/SAND 20\n"
" workflow count BOULDER/CLAY 20\n"
" Collect 15-20 sand bags and clay boulders.\n"
" workflow amount POWDER_MISC//MUSHROOM_CUP_DIMPLE:MILL 100 20\n"
" Make sure there are always 80-100 units of dimple dye.\n"
" In order for this to work, you have to set the material of\n"
" the PLANT input on the Mill Plants job to MUSHROOM_CUP_DIMPLE\n"
" using the 'job item-material' command.\n"
" workflow count CRAFTS///LOCAL,EXCEPTIONAL 100 90\n"
" Maintain 10-100 locally-made crafts of exceptional quality.\n"
)
);
}
init_state(out);
return CR_OK;
}
DFhackCExport command_result plugin_shutdown (color_ostream &out)
{
cleanup_state(out);
return CR_OK;
}
DFhackCExport command_result plugin_onstatechange(color_ostream &out, state_change_event event)
{
switch (event) {
case SC_MAP_LOADED:
cleanup_state(out);
init_state(out);
break;
case SC_MAP_UNLOADED:
cleanup_state(out);
break;
default:
break;
}
return CR_OK;
}
/******************************
* JOB STATE TRACKING STRUCTS *
******************************/
const int DAY_TICKS = 1200;
const int MONTH_DAYS = 28;
const int YEAR_MONTHS = 12;
struct ItemConstraint;
struct ProtectedJob {
int id;
int building_id;
int tick_idx;
static int cur_tick_idx;
df::building *holder;
df::job *job_copy;
int reaction_id;
df::job *actual_job;
bool want_resumed;
int resume_time, resume_delay;
std::vector<ItemConstraint*> constraints;
public:
ProtectedJob(df::job *job) : id(job->id)
{
tick_idx = cur_tick_idx;
holder = Job::getHolder(job);
building_id = holder ? holder->id : -1;
job_copy = Job::cloneJobStruct(job);
actual_job = job;
reaction_id = -1;
want_resumed = false;
resume_time = 0; resume_delay = DAY_TICKS;
}
~ProtectedJob()
{
Job::deleteJobStruct(job_copy);
}
bool isActuallyResumed() {
return actual_job && !actual_job->flags.bits.suspend;
}
bool isResumed() {
return want_resumed || isActuallyResumed();
}
bool isLive() { return actual_job != NULL; }
void update(df::job *job)
{
actual_job = job;
if (*job == *job_copy)
return;
reaction_id = -1;
Job::deleteJobStruct(job_copy);
job_copy = Job::cloneJobStruct(job);
}
void tick_job(df::job *job, int ticks)
{
tick_idx = cur_tick_idx;
actual_job = job;
if (isActuallyResumed())
{
resume_time = 0;
resume_delay = std::max(DAY_TICKS, resume_delay - ticks);
}
else if (want_resumed)
{
if (!resume_time)
want_resumed = false;
else if (world->frame_counter >= resume_time)
actual_job->flags.bits.suspend = false;
}
}
void recover(df::job *job)
{
actual_job = job;
job->flags.bits.repeat = true;
job->flags.bits.suspend = true;
resume_delay = std::min(DAY_TICKS*MONTH_DAYS, 5*resume_delay/3);
resume_time = world->frame_counter + resume_delay;
}
void set_resumed(bool resume)
{
if (resume)
{
if (world->frame_counter >= resume_time)
actual_job->flags.bits.suspend = false;
}
else
{
resume_time = 0;
if (isActuallyResumed())
resume_delay = DAY_TICKS;
actual_job->flags.bits.suspend = true;
}
want_resumed = resume;
}
};
int ProtectedJob::cur_tick_idx = 0;
typedef std::map<std::pair<int,int>, bool> TMaterialCache;
static const size_t MAX_HISTORY_SIZE = 28;
enum HistoryItem {
HIST_COUNT = 0,
HIST_AMOUNT,
HIST_INUSE_COUNT,
HIST_INUSE_AMOUNT
};
struct ItemConstraint {
PersistentDataItem config;
PersistentDataItem history;
// Fixed key parsed into fields
bool is_craft;
ItemTypeInfo item;
MaterialInfo material;
df::dfhack_material_category mat_mask;
item_quality::item_quality min_quality;
bool is_local;
// Tracking data
int weight;
std::vector<ProtectedJob*> jobs;
int item_amount, item_count, item_inuse_amount, item_inuse_count;
bool request_suspend, request_resume;
bool is_active, cant_resume_reported;
int low_stock_reported;
TMaterialCache material_cache;
public:
ItemConstraint()
: is_craft(false), min_quality(item_quality::Ordinary), is_local(false),
weight(0), item_amount(0), item_count(0), item_inuse_amount(0), item_inuse_count(0),
is_active(false), cant_resume_reported(false), low_stock_reported(-1)
{}
int goalCount() { return config.ival(0); }
void setGoalCount(int v) { config.ival(0) = v; }
int goalGap() {
int cval = (config.ival(1) <= 0) ? std::min(5,goalCount()/2) : config.ival(1);
return std::max(1, std::min(goalCount()-1, cval));
}
void setGoalGap(int v) { config.ival(1) = v; }
bool goalByCount() { return config.ival(2) & 1; }
void setGoalByCount(bool v) {
if (v)
config.ival(2) |= 1;
else
config.ival(2) &= ~1;
}
int curItemStock() { return goalByCount() ? item_count : item_amount; }
void init(const std::string &str)
{
config.val() = str;
config.ival(0) = 10;
config.ival(2) = 0;
}
void computeRequest()
{
int size = curItemStock();
request_resume = (size <= goalCount()-goalGap());
request_suspend = (size >= goalCount());
}
static const size_t int28_size = PersistentDataItem::int28_size;
static const size_t hist_entry_size = PersistentDataItem::int28_size * 4;
size_t history_size() {
return history.data_size() / hist_entry_size;
}
int history_value(int idx, HistoryItem item) {
size_t hsize = history_size();
size_t base = ((history.ival(0)+1+idx) % hsize) * hist_entry_size;
return history.get_int28(base + item*int28_size);
}
int history_count(int idx) { return history_value(idx, HIST_COUNT); }
int history_amount(int idx) { return history_value(idx, HIST_AMOUNT); }
int history_inuse_count(int idx) { return history_value(idx, HIST_INUSE_COUNT); }
int history_inuse_amount(int idx) { return history_value(idx, HIST_INUSE_AMOUNT); }
void updateHistory()
{
size_t buffer_size = history_size();
if (buffer_size < MAX_HISTORY_SIZE && size_t(history.ival(0)+1) == buffer_size)
history.ensure_data(hist_entry_size*++buffer_size);
history.ival(0) = (history.ival(0)+1) % buffer_size;
size_t base = history.ival(0) * hist_entry_size;
history.set_int28(base + HIST_COUNT*int28_size, item_count);
history.set_int28(base + HIST_AMOUNT*int28_size, item_amount);
history.set_int28(base + HIST_INUSE_COUNT*int28_size, item_inuse_count);
history.set_int28(base + HIST_INUSE_AMOUNT*int28_size, item_inuse_amount);
}
};
/******************************
* GLOBAL VARIABLES *
******************************/
static bool enabled = false;
static PersistentDataItem config;
static int last_tick_frame_count = 0;
static int last_frame_count = 0;
enum ConfigFlags {
CF_ENABLED = 1,
CF_DRYBUCKETS = 2,
CF_AUTOMELT = 4
};
typedef std::map<int, ProtectedJob*> TKnownJobs;
static TKnownJobs known_jobs;
static std::vector<ProtectedJob*> pending_recover;
static std::vector<ItemConstraint*> constraints;
static int meltable_count = 0;
static bool melt_active = false;
/******************************
* MISC FUNCTIONS *
******************************/
static ProtectedJob *get_known(int id)
{
TKnownJobs::iterator it = known_jobs.find(id);
return (it != known_jobs.end()) ? it->second : NULL;
}
static bool isSupportedJob(df::job *job)
{
return job->specific_refs.empty() &&
Job::getHolder(job) &&
(!job->job_items.empty() ||
job->job_type == job_type::CollectClay ||
job->job_type == job_type::CollectSand ||
job->job_type == job_type::MilkCreature ||
job->job_type == job_type::ShearCreature);
}
static bool isOptionEnabled(unsigned flag)
{
return config.isValid() && (config.ival(0) & flag) != 0;
}
static void setOptionEnabled(ConfigFlags flag, bool on)
{
if (!config.isValid())
return;
if (on)
config.ival(0) |= flag;
else
config.ival(0) &= ~flag;
}
/******************************
* STATE INITIALIZATION *
******************************/
static void stop_protect(color_ostream &out)
{
pending_recover.clear();
if (!known_jobs.empty())
out.print("Unprotecting %d jobs.\n", known_jobs.size());
for (TKnownJobs::iterator it = known_jobs.begin(); it != known_jobs.end(); ++it)
delete it->second;
known_jobs.clear();
}
static void cleanup_state(color_ostream &out)
{
config = PersistentDataItem();
stop_protect(out);
for (size_t i = 0; i < constraints.size(); i++)
delete constraints[i];
constraints.clear();
}
static void check_lost_jobs(color_ostream &out, int ticks);
static ItemConstraint *get_constraint(color_ostream &out, const std::string &str, PersistentDataItem *cfg = NULL, bool create = true);
static void start_protect(color_ostream &out)
{
check_lost_jobs(out, 0);
if (!known_jobs.empty())
out.print("Protecting %d jobs.\n", known_jobs.size());
}
static void init_state(color_ostream &out)
{
config = World::GetPersistentData("workflow/config");
if (config.isValid() && config.ival(0) == -1)
config.ival(0) = 0;
enabled = isOptionEnabled(CF_ENABLED);
// Parse constraints
std::vector<PersistentDataItem> items;
World::GetPersistentData(&items, "workflow/constraints");
for (int i = items.size()-1; i >= 0; i--) {
if (get_constraint(out, items[i].val(), &items[i]))
continue;
out.printerr("Lost constraint %s\n", items[i].val().c_str());
World::DeletePersistentData(items[i]);
}
last_tick_frame_count = world->frame_counter;
last_frame_count = world->frame_counter;
if (!enabled)
return;
start_protect(out);
}
static void enable_plugin(color_ostream &out)
{
if (!config.isValid())
{
config = World::AddPersistentData("workflow/config");
config.ival(0) = 0;
}
setOptionEnabled(CF_ENABLED, true);
enabled = true;
out << "Enabling the plugin." << endl;
start_protect(out);
}
/******************************
* JOB AUTO-RECOVERY *
******************************/
static void forget_job(color_ostream &out, ProtectedJob *pj)
{
known_jobs.erase(pj->id);
delete pj;
}
static bool recover_job(color_ostream &out, ProtectedJob *pj)
{
if (pj->isLive())
return true;
// Check that the building exists
pj->holder = df::building::find(pj->building_id);
if (!pj->holder)
{
out.printerr("Forgetting job %d (%s): holder building lost.\n",
pj->id, ENUM_KEY_STR(job_type, pj->job_copy->job_type).c_str());
forget_job(out, pj);
return true;
}
// Check its state and postpone or cancel if invalid
if (pj->holder->jobs.size() >= 10)
{
out.printerr("Forgetting job %d (%s): holder building has too many jobs.\n",
pj->id, ENUM_KEY_STR(job_type, pj->job_copy->job_type).c_str());
forget_job(out, pj);
return true;
}
if (!pj->holder->jobs.empty())
{
df::job_type ftype = pj->holder->jobs[0]->job_type;
if (ftype == job_type::DestroyBuilding)
return false;
if (ENUM_ATTR(job_type,type,ftype) == job_type_class::StrangeMood)
return false;
}
// Create and link in the actual job structure
df::job *recovered = Job::cloneJobStruct(pj->job_copy);
if (!Job::linkIntoWorld(recovered, false)) // reuse same id
{
Job::deleteJobStruct(recovered);
out.printerr("Inconsistency: job %d (%s) already in list.\n",
pj->id, ENUM_KEY_STR(job_type, pj->job_copy->job_type).c_str());
return true;
}
pj->holder->jobs.push_back(recovered);
// Done
pj->recover(recovered);
return true;
}
static void check_lost_jobs(color_ostream &out, int ticks)
{
ProtectedJob::cur_tick_idx++;
if (ticks < 0) ticks = 0;
df::job_list_link *p = world->job_list.next;
for (; p; p = p->next)
{
df::job *job = p->item;
ProtectedJob *pj = get_known(job->id);
if (pj)
{
if (!job->flags.bits.repeat)
forget_job(out, pj);
else
pj->tick_job(job, ticks);
}
else if (job->flags.bits.repeat && isSupportedJob(job))
{
pj = new ProtectedJob(job);
assert(pj->holder);
known_jobs[pj->id] = pj;
}
}
for (TKnownJobs::const_iterator it = known_jobs.begin(); it != known_jobs.end(); ++it)
{
if (it->second->tick_idx == ProtectedJob::cur_tick_idx ||
!it->second->isLive())
continue;
it->second->actual_job = NULL;
pending_recover.push_back(it->second);
}
}
static void update_job_data(color_ostream &out)
{
df::job_list_link *p = world->job_list.next;
for (; p; p = p->next)
{
ProtectedJob *pj = get_known(p->item->id);
if (!pj)
continue;
pj->update(p->item);
}
}
static void recover_jobs(color_ostream &out)
{
for (int i = pending_recover.size()-1; i >= 0; i--)
if (recover_job(out, pending_recover[i]))
vector_erase_at(pending_recover, i);
}
static void process_constraints(color_ostream &out);
DFhackCExport command_result plugin_onupdate(color_ostream &out)
{
if (!enabled)
return CR_OK;
// Every 5 frames check the jobs for disappearance
static unsigned cnt = 0;
if ((++cnt % 5) != 0)
return CR_OK;
check_lost_jobs(out, world->frame_counter - last_tick_frame_count);
last_tick_frame_count = world->frame_counter;
// Proceed every in-game half-day, or when jobs to recover changed
static unsigned last_rlen = 0;
bool check_time = (world->frame_counter - last_frame_count) >= DAY_TICKS/2;
if (pending_recover.size() != last_rlen || check_time)
{
recover_jobs(out);
last_rlen = pending_recover.size();
// If the half-day passed, proceed to update
if (check_time)
{
last_frame_count = world->frame_counter;
update_job_data(out);
process_constraints(out);
for (size_t i = 0; i < constraints.size(); i++)
constraints[i]->updateHistory();
}
}
return CR_OK;
}
/******************************
* ITEM COUNT CONSTRAINT *
******************************/
static std::string history_key(PersistentDataItem &config) {
return stl_sprintf("workflow/history/%d", config.entry_id());
}
static ItemConstraint *get_constraint(color_ostream &out, const std::string &str, PersistentDataItem *cfg, bool create)
{
std::vector<std::string> tokens;
split_string(&tokens, str, "/");
if (tokens.size() > 4)
return NULL;
int weight = 0;
bool is_craft = false;
ItemTypeInfo item;
if (tokens[0] == "ANY_CRAFT" || tokens[0] == "CRAFTS") {
is_craft = true;
} else if (!item.find(tokens[0]) || !item.isValid()) {
out.printerr("Cannot find item type: %s\n", tokens[0].c_str());
return NULL;
}
if (item.subtype >= 0)
weight += 10000;
df::dfhack_material_category mat_mask(0);
std::string maskstr = vector_get(tokens,1);
if (!maskstr.empty() && !parseJobMaterialCategory(&mat_mask, maskstr)) {
out.printerr("Cannot decode material mask: %s\n", maskstr.c_str());
return NULL;
}
if (mat_mask.whole != 0)
weight += 100;
MaterialInfo material;
std::string matstr = vector_get(tokens,2);
if (!matstr.empty() && (!material.find(matstr) || !material.isValid())) {
out.printerr("Cannot find material: %s\n", matstr.c_str());
return NULL;
}
if (material.type >= 0)
weight += (material.index >= 0 ? 5000 : 1000);
if (mat_mask.whole && material.isValid() && !material.matches(mat_mask)) {
out.printerr("Material %s doesn't match mask %s\n", matstr.c_str(), maskstr.c_str());
return NULL;
}
item_quality::item_quality minqual = item_quality::Ordinary;
bool is_local = false;
std::string qualstr = vector_get(tokens, 3);
if(!qualstr.empty())
{
std::vector<std::string> qtokens;
split_string(&qtokens, qualstr, ",");
for (size_t i = 0; i < qtokens.size(); i++)
{
auto token = toLower(qtokens[i]);
if (token == "local")
is_local = true;
else
{
bool found = false;
FOR_ENUM_ITEMS(item_quality, qv)
{
if (toLower(ENUM_KEY_STR(item_quality, qv)) != token)
continue;
minqual = qv;
found = true;
}
if (!found)
{
out.printerr("Cannot parse token: %s\n", token.c_str());
return NULL;
}
}
}
}
if (is_local || minqual > item_quality::Ordinary)
weight += 10;
for (size_t i = 0; i < constraints.size(); i++)
{
ItemConstraint *ct = constraints[i];
if (ct->is_craft == is_craft &&
ct->item == item && ct->material == material &&
ct->mat_mask.whole == mat_mask.whole &&
ct->min_quality == minqual &&
ct->is_local == is_local)
return ct;
}
if (!create)
return NULL;
ItemConstraint *nct = new ItemConstraint;
nct->is_craft = is_craft;
nct->item = item;
nct->material = material;
nct->mat_mask = mat_mask;
nct->min_quality = minqual;
nct->is_local = is_local;
nct->weight = weight;
if (cfg)
nct->config = *cfg;
else
{
nct->config = World::AddPersistentData("workflow/constraints");
nct->init(str);
}
nct->history = World::GetPersistentData(history_key(nct->config), NULL);
constraints.push_back(nct);
return nct;
}
static void delete_constraint(ItemConstraint *cv)
{
int idx = linear_index(constraints, cv);
if (idx >= 0)
vector_erase_at(constraints, idx);
World::DeletePersistentData(cv->config);
World::DeletePersistentData(cv->history);
delete cv;
}
static bool deleteConstraint(std::string name)
{
for (size_t i = 0; i < constraints.size(); i++)
{
if (constraints[i]->config.val() != name)
continue;
delete_constraint(constraints[i]);
return true;
}
return false;
}
/******************************
* JOB-CONSTRAINT MAPPING *
******************************/
static bool isCraftItem(df::item_type type)
{
using namespace df::enums::job_type;
auto lst = ENUM_ATTR(job_type, possible_item, MakeCrafts);
for (size_t i = 0; i < lst.size; i++)
if (lst.items[i] == type)
return true;
return false;
}
static void link_job_constraint(ProtectedJob *pj, df::item_type itype, int16_t isubtype,
df::dfhack_material_category mat_mask,
int16_t mat_type, int32_t mat_index,
bool is_craft = false)
{
MaterialInfo mat(mat_type, mat_index);
for (size_t i = 0; i < constraints.size(); i++)
{
ItemConstraint *ct = constraints[i];
if (is_craft)
{
if (!ct->is_craft && !isCraftItem(ct->item.type))
continue;
}
else
{
if (ct->item.type != itype ||
(ct->item.subtype != -1 && ct->item.subtype != isubtype))
continue;
}
if (!mat.matches(ct->material))
continue;
if (ct->mat_mask.whole)
{
if (mat.isValid())
{
if (!mat.matches(ct->mat_mask))
continue;
}
else
{
if (!(mat_mask.whole & ct->mat_mask.whole))
continue;
}
}
if (linear_index(pj->constraints, ct) >= 0)
continue;
ct->jobs.push_back(pj);
pj->constraints.push_back(ct);
if (!ct->is_active && pj->isResumed())
ct->is_active = true;
}
}
static void guess_job_material(df::job *job, MaterialInfo &mat, df::dfhack_material_category &mat_mask)
{
using namespace df::enums::job_type;
if (job->job_type == PrepareMeal)
mat.decode(-1);
else
mat.decode(job);
mat_mask.whole = job->material_category.whole;
// Material from the job enum
const char *job_material = ENUM_ATTR(job_type, material, job->job_type);
if (job_material)
{
MaterialInfo info;
if (info.findBuiltin(job_material))
mat = info;
else
parseJobMaterialCategory(&mat_mask, job_material);
}
// Material from the job reagent
if (!mat.isValid() && !job->job_items.empty() &&
(job->job_items.size() == 1 ||
job->job_items[0]->item_type == item_type::PLANT))
{
mat.decode(job->job_items[0]);
switch (job->job_items[0]->item_type)
{
case item_type::WOOD:
mat_mask.bits.wood = mat_mask.bits.wood2 = true;
break;
default:
break;
}
}
}
static int cbEnumJobOutputs(lua_State *L)
{
auto pj = (ProtectedJob*)lua_touserdata(L, lua_upvalueindex(1));
lua_settop(L, 6);
df::dfhack_material_category mat_mask(0);
if (!lua_isnil(L, 3))
Lua::CheckDFAssign(L, &mat_mask, 3);
link_job_constraint(
pj,
(df::item_type)luaL_optint(L, 1, -1), luaL_optint(L, 2, -1),
mat_mask, luaL_optint(L, 4, -1), luaL_optint(L, 5, -1),
lua_toboolean(L, 6)
);
return 0;
}
static void map_job_constraints(color_ostream &out)
{
melt_active = false;
for (size_t i = 0; i < constraints.size(); i++)
{
constraints[i]->jobs.clear();
constraints[i]->is_active = false;
}
auto L = Lua::Core::State;
Lua::StackUnwinder frame(L);