-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathanalysis.pike
2473 lines (2385 loc) · 136 KB
/
analysis.pike
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
//Various functions to do different forms of savefile analysis.
//The primary entrypoint is analyze() which receives a savefile (as a mapping),
//a country (and optionally player name) to analyze, and the user prefs; it will
//return the useful and interesting data as a mapping.
//Note that analyzing may mutate the savefile mapping, but only to cache information
//that would not change without the savefile itself changing.
void analyze_cot(mapping data, string name, string tag, mapping write) {
mapping country = data->countries[tag];
mapping(string:int) area_has_level3 = country->area_has_level3 = ([]);
array maxlvl = ({ }), upgradeable = ({ }), developable = ({ });
foreach (country->owned_provinces, string id) {
mapping prov = data->provinces["-" + id];
if (!prov->center_of_trade) continue;
int dev = (int)prov->base_tax + (int)prov->base_production + (int)prov->base_manpower;
int need = prov->center_of_trade == "1" ? 10 : 25;
array desc = ({
sprintf("%s %04d %s", prov->owner, 9999-dev, prov->name), //Sort key
prov->center_of_trade, id, dev, prov->name, L10N(prov->trade),
});
if (prov->center_of_trade == "3") {maxlvl += ({desc}); area_has_level3[G->CFG->prov_area[id]] = (int)id;}
else if (dev >= need) upgradeable += ({desc});
else developable += ({desc});
}
sort(maxlvl); sort(upgradeable); sort(developable);
int maxlevel3 = sizeof(Array.arrayify(country->merchants->?envoy)); //You can have as many lvl 3 CoTs as you have merchants.
int level3 = sizeof(maxlvl); //You might already have some.
int maxprio = 0;
string|mapping colorize(string color, array info, int prio) {
//Colorize if it's interesting. It can't be upgraded if not in a state; also, not all level 2s
//can become level 3s, for various reasons.
[string key, string cotlevel, string id, int dev, string provname, string tradenode] = info;
array have_states = data->map_area_data[G->CFG->prov_area[id]]->?state->?country_state->?country;
string noupgrade;
if (!have_states || !has_value(have_states, tag)) noupgrade = "is territory";
else if (cotlevel == "2") {
if (area_has_level3[G->CFG->prov_area[id]]) noupgrade = "other l3 in area";
else if (++level3 > maxlevel3) noupgrade = "need merchants";
}
if (!noupgrade) maxprio = max(prio, maxprio);
return ([
"id": id, "dev": dev, "name": provname, "tradenode": tradenode,
"noupgrade": noupgrade || "",
"level": (int)cotlevel, "interesting": !noupgrade && prio,
]);
}
write->cot = ([
"level3": level3, "max": maxlevel3,
"upgradeable": colorize("", upgradeable[*], 2),
"developable": colorize("", developable[*], 1),
]);
write->cot->maxinteresting = maxprio;
}
object calendar(string date) {
sscanf(date, "%d.%d.%d", int year, int mon, int day);
return Calendar.Gregorian.Day(year, mon, day);
}
//Substitute string args into strings. Currently does not support the full "and parse another
//entire block of code" substitution form.
mixed substitute_args(mixed trigger, mapping args) {
if (stringp(trigger)) return replace(trigger, args);
if (arrayp(trigger)) return substitute_args(trigger[*], args);
if (mappingp(trigger)) return mkmapping(
substitute_args(indices(trigger)[*], args),
substitute_args(values(trigger)[*], args));
return trigger; //Anything unknown presumably can't have replacements done (eg integers).
}
//Resolve a relative reference to the actual value. See https://eu4.paradoxwikis.com/Scopes for concepts and explanation.
string resolve_scope(mapping data, array(mapping) scopes, string value, string|void attr) {
if (!attr) attr = "tag";
switch (value) {
case "ROOT": return scopes[0][attr];
case "FROM": return scopes[-2][attr]; //Not sure if this is right
case "PREV": return scopes[-2][attr];
case "PREV_PREV": return scopes[-3][attr];
case "THIS": return scopes[-1][attr];
default: return value;
}
}
//Pass the full data block, and for scopes, a sequence of country and/or province mappings.
//Triggers are tested on scopes[-1], and PREV= will switch to scopes[-2].
//What happens if you do "PREV = { PREV = { ... } }" ? Should we shorten the scopes array
//or duplicate scopes[-2] to the end of it?
int(1bit) DEBUG_TRIGGER_MATCHES = 0;
int(1bit) trigger_matches(mapping data, array(mapping) scopes, string type, mixed value) {
mapping scope = scopes[-1];
switch (type) {
case "AND": {
//Inside an AND block (and possibly an OR??), you can have an "if/else" pair.
//An "if" block has a "limit", and if the limit is true, the rest of the "if"
//applies. Otherwise, the immediately-following "else" does.
//I'm assuming here that if/else pairs are correctly matched; if there are,
//say, three "if" blocks, I assume that if[1] corresponds to else[1].
//This would be WAY easier if the "else" were inside the "if".
//Note that I may have represented the logic here incorrectly. No idea how
//this is supposed to behave if you do OR = { if = { limit = {...} a = 1 b = 2 } else = { c = 3 d = 4 } }
//with multiple entries. Is that even possible?
if (value["if"]) {
array ifs = Array.arrayify(value["if"]), elses = Array.arrayify(value["else"]);
if (sizeof(ifs) != sizeof(elses)) return 0; //Borked.
foreach (ifs; int i; mapping blk) {
mapping useme = trigger_matches(data, scopes, "AND", blk->limit || ([])) ? blk : elses[i];
if (!trigger_matches(data, scopes, "AND", useme)) return 0;
}
}
foreach (value; string t; mixed vv)
foreach (Array.arrayify(vv), mixed v) //Would it be more efficient to arrayp check rather than arrayifying?
if (!trigger_matches(data, scopes, t, v)) return 0;
return 1;
}
case "OR":
foreach (value; string t; mixed vv)
foreach (Array.arrayify(vv), mixed v) //Would it be more efficient to arrayp check rather than arrayifying?
if (trigger_matches(data, scopes, t, v)) return 1;
return 0;
case "NOT": return !trigger_matches(data, scopes, "OR", value);
case "root": return trigger_matches(data, scopes + ({scope}), "AND", value);
case "custom_trigger_tooltip": return trigger_matches(data, scopes, "AND", value);
case "tooltip": return 1; //Inside custom_trigger_tooltip is a tooltip that visually replaces the other effects.
//Okay, now for the actual triggers. Country scope.
case "has_reform": return has_value(scope->government->reform_stack->reforms, value);
case "any_owned_province":
foreach (scope->owned_provinces, string id) {
mapping prov = data->provinces["-" + id];
if (trigger_matches(data, scopes + ({prov}), "AND", value)) return 1;
}
return 0;
case "tag": return scope->tag == value;
case "capital": //Check if your capital is a particular province
return (int)scope->capital == (int)value;
case "capital_scope": //Check other details about the capital, by switching scope
return trigger_matches(data, scopes + ({data->provinces["-" + scope->capital]}), "AND", value);
case "is_subject": return !!scope->overlord == value;
case "overlord":
if (!scope->overlord) return 0;
return trigger_matches(data, scopes + ({data->countries[scope->overlord]}), "AND", value);
case "trade_income_percentage":
//Estimate trade income percentage based on last month's figures. I don't know
//whether the actual effect changes within the month, but this is likely to be
//close enough anyway. The income table runs ({tax, prod, trade, gold, ...}).
if (!scope->ledger->lastmonthincometable) return 0; //No idea why, but sometimes this is null. I guess we don't have data??
return threeplace(scope->ledger->lastmonthincometable[2]) * 1000 / threeplace(scope->ledger->lastmonthincome)
>= threeplace(value);
case "land_maintenance": return threeplace(scope->land_maintenance) >= threeplace(value);
case "has_disaster": return 0; //TODO: Where are current disasters listed?
case "num_of_continents": return `+(@(array(int))scope->continent) >= (int)value;
case "religion": return scope->religion == value;
case "religion_group":
//Calculated slightly backwards; instead of asking what religion group the
//country is in, and then seeing if that's equal to value, we look up the
//list of religions in the group specified, and ask if the country's is in
//that list.
return !undefinedp(G->CFG->religion_definitions[value][scope->religion]);
case "dominant_religion": return scope->dominant_religion == resolve_scope(data, scopes, value, "dominant_religion");
case "religious_unity": return threeplace(scope->religious_unity) >= threeplace(value);
case "is_defender_of_faith": {
mapping rel = data->religion_instance_data[scope->religion] || ([]);
return (rel->defender == scope->tag) == value;
}
case "has_church_aspect": return has_value(Array.arrayify(scope->church->?aspect), value);
case "technology_group": return scope->technology_group == value;
case "primary_culture": return scope->primary_culture == value;
case "culture_group":
//Checked the same slightly-backwards way that religion group is.
return !undefinedp(G->CFG->culture_definitions[value][?scope->primary_culture]);
case "stability": return (int)scope->stability >= (int)value;
case "corruption": return threeplace(scope->corruption) >= threeplace(value);
case "num_of_loans": return sizeof(Array.arrayify(scope->loan)) >= (int)value;
case "has_country_modifier": case "has_ruler_modifier":
//Hack: I'm counting ruler modifiers the same way as country modifiers.
return has_value(Array.arrayify(scope->modifier)->modifier, value);
case "has_country_flag":
return !!scope->flags[?value]; //Flags are mapped to the date when they happened. We just care about presence.
case "had_country_flag": { //Oh, but what if we don't just care about presence?
string date = scope->flags[?value->flag];
if (!date) return 0; //Don't have the flag, so we haven't had it for X days
object today = calendar(data->date);
int days; catch {days = calendar(date)->distance(today) / today;};
return days >= (int)value->days;
}
case "was_tag": return has_value(Array.arrayify(scope->previous_country_tags), value);
case "check_variable": return (int)scope->variables[?value->which] >= (int)value->value;
case "has_parliament":
return all_country_modifiers(data, scope)->has_parliament;
case "has_government_attribute": //Government attributes are thrown in with country modifiers for simplicity.
return all_country_modifiers(data, scope)[value];
case "has_estate":
return has_value(Array.arrayify(scope->estate)->type, value);
case "has_estate_privilege":
foreach (Array.arrayify(scope->estate), mapping est) {
if (has_value(Array.arrayify(est->granted_privileges)[*][0], value)) return 1;
}
return 0;
case "estate_influence":
foreach (Array.arrayify(scope->estate), mapping est) {
if (est->type != value->estate) continue;
return est->estimated_milliinfluence >= threeplace(value->influence);
}
return 0; //If you don't have that estate, its influence isn't above X for any X.
case "estate_loyalty":
foreach (Array.arrayify(scope->estate), mapping est) {
if (est->type != value->estate) continue;
return threeplace(est->loyalty) >= threeplace(value->loyalty);
}
return 0; //Ditto - non-estates aren't loyal to you
case "has_idea": return has_value(enumerate_ideas(scope->active_idea_groups)->id, value);
case "has_idea_group": return !undefinedp(scope->active_idea_groups[value]);
case "full_idea_group": return scope->active_idea_groups[?value] == "7";
case "adm_tech": case "dip_tech": case "mil_tech":
return (int)scope->technology[type] >= (int)value;
case "uses_piety":
return all_country_modifiers(data, scope)->uses_piety;
case "num_of_janissaries": return (int)scope->num_subunits->?janissaries >= (int)value;
case "janissary_percentage": {
if (undefinedp(scope->janissary_percentage)) {
//This gets checked a LOT by the Janissaries Estate, so cache the value
int janis = threeplace(scope->num_subunits_type_and_cat->?infantry->?janissaries);
if (janis) { //Avoid crashing if there's weird things like armies that have no regiments
int total_army = scope->army && sizeof(scope->army) && `+(@sizeof(scope->army->regiment[*])) || 1;
scope->janissary_percentage = janis / total_army;
} else scope->janissary_percentage = 0;
}
return scope->janissary_percentage >= threeplace(value);
}
//What's the proper way to recognize colonial nations?
//One of these is almost certainly wrong. Do they both need a condition (has/hasn't an overlord)?
//Should they be identified by governmental forms?
case "is_colonial_nation":
return (scope->tag[0] == 'C' && !sizeof((multiset)(array)scope->tag[1..] - (multiset)(array)"012345789")) == value;
case "is_former_colonial_nation":
return (scope->tag[0] == 'C' && !sizeof((multiset)(array)scope->tag[1..] - (multiset)(array)"012345789")) == value;
case "is_revolutionary": return all_country_modifiers(data, scope)->revolutionary;
case "is_emperor": return (data->empire->emperor == scope->tag) == value;
case "is_elector": return has_value(data->empire->electors || ({ }), scope->tag);
case "is_part_of_hre": //For countries, equivalent to asking "is the capital_scope part of the HRE?"
return (scope->capital_scope || scope)->hre;
case "hre_religion_locked": return (int)data->hre_religion_status == (int)value; //TODO: Check if this is correct (post-league-war)
case "hre_religion": return 0; //FIXME: Where is this stored, post-league-war?
case "hre_reform_passed": return has_value(Array.arrayify(data->empire->passed_reform), value); //TODO: Check savefile with 0 or 1 reforms passed - do we need the arrayify?
case "num_of_cities": return (int)scope->num_of_cities >= (int)value;
case "num_of_ports": return (int)scope->num_of_ports >= (int)value;
case "owns": return has_value(scope->owned_provinces, value);
case "has_mission": {
foreach (Array.arrayify(scope->country_missions->?mission_slot), array slot) {
foreach (Array.arrayify(slot), string kwd) {
if (G->CFG->country_missions[kwd][?value]) return 1;
}
}
return 0;
}
case "prestige": return threeplace(scope->prestige) >= threeplace(value);
case "meritocracy": return threeplace(scope->meritocracy) >= threeplace(value); //TODO: Only if you use meritocracy?? Only relevant if you test for "meritocracy = 0".
case "adm": case "dip": case "mil": { //Test monarch skills. We cache this in country modifiers.
mapping mod = scope->_all_country_modifiers;
if (mod) return mod[type] >= (int)value;
//Not there yet? Well, we can't call all_country_modifiers or we'll have a loop.
//(Though it might be okay given that this won't be needed until estate calculations??)
//Duplicate the code, for now.
if (!scope->monarch) return 0;
mapping monarch = ([]);
foreach (sort(indices(scope->history)), string key)
monarch = ((int)key && mappingp(scope->history[key]) && (scope->history[key]->monarch || scope->history[key]->monarch_heir)) || monarch;
if (arrayp(monarch)) monarch = monarch[0];
return (int)monarch[upper_case(type)] >= (int)value;
}
//Province scope.
case "province_id": return (int)scope->id == (int)value;
case "development": {
int dev = (int)scope->base_tax + (int)scope->base_production + (int)scope->base_manpower;
return dev >= (int)value;
}
case "province_has_center_of_trade_of_level": return (int)scope->center_of_trade >= (int)value;
case "area": return G->CFG->prov_area[(string)scope->id] == value;
case "region": return G->CFG->area_region[G->CFG->prov_area[(string)scope->id]] == value;
case "superregion": return G->CFG->region_superregion[G->CFG->area_region[G->CFG->prov_area[(string)scope->id]]] == value;
case "colonial_region": return G->CFG->prov_colonial_region[(string)scope->id] == value;
case "continent": return G->CFG->prov_continent[(string)scope->id] == value;
case "has_province_modifier": return all_province_modifiers(data, (int)scope->id)[value];
case "is_strongest_trade_power": {
//Assumes the province is a trade node
foreach (data->trade->node, mapping node) {
if (G->CFG->tradenode_definitions[node->definitions]->location != (string)scope->id) continue;
array top = Array.arrayify(node->top_power);
if (!sizeof(top)) return 0; //There's nobody trading in this node (yet), so nobody is the top trade power.
return resolve_scope(data, scopes, value) == top[0];
}
return 1; //Trade node not found, probably should throw an error actually
}
case "owned_by": return resolve_scope(data, scopes, value) == scope->owner;
case "country_or_non_sovereign_subject_holds": {
string tag = resolve_scope(data, scopes, value);
if (tag == scope->owner) return 1;
mapping owner = data->countries[tag];
//It's owned by someone else. Are they subject to you?
foreach (Array.arrayify(data->diplomacy->dependency), mapping dep)
if (dep->first == tag && dep->second == scope->owner)
//Hack: Assume the subject type ID is enough of a check
return dep->subject_type != "tributary_state";
return 0; //Guess not.
}
//Possibly universal scope
case "has_discovered": {
//Can be used at province scope (has_discovered = FRA) or country scope (has_discovered = 123)
if (scope->discovered_by)
//At province scope. Handle "discovered_by = ROOT" and other notations.
return has_value(scope->discovered_by, resolve_scope(data, scopes, value));
//At country scope. Assume it's a province ID.
mapping prov = data->provinces["-" + value];
if (!prov) return 0; //TODO: What if it's not an ID?
return has_value(prov->discovered_by, scope->tag);
}
case "has_dlc": return has_value(data->dlc_enabled, value);
case "has_global_flag": return !undefinedp(data->flags[value]);
case "had_global_flag": {
string date = data->flags[value->flag];
if (!date) return 0; //Don't have the flag, so we haven't had it for X days
object today = calendar(data->date);
int days; catch {days = calendar(date)->distance(today) / today;};
return days >= (int)value->days;
}
case "current_age": return data->current_age == value;
case "always": return value; //"always = no" blocks everything
//Minor point of confusion here. As well as "exists = SPA" to test whether Spain exists,
//the wiki also mentions "exists = yes" to test whether the current scope exists. But in
//other contexts where a new scope is selected (eg "overlord = { ... }"), they seem to
//implicitly check that one exists. So I'm not sure when it's possible to switch to a
//scope that doesn't exist, and what OTHER checks should do in that situation.
case "exists": {
//Note that a country might be present in the save file but without any provinces.
//This counts as not existing. If it were to be given a province, it would exist.
mapping target = data->countries[value];
return target && (int)target->num_of_cities;
}
case "normal_or_historical_nations": return 1 == (int)value; //TODO: Is this in data->gameplaysettings??
default:
//Switching to a specific province is done by giving its (numeric) ID.
if ((int)type) return trigger_matches(data, scopes + ({data->provinces["-" + type]}), "AND", value);
//Switching to a specific country, similarly, with tag.
if (data->countries[type]) return trigger_matches(data, scopes + ({data->countries[type]}), "AND", value);
if (mapping st = G->CFG->scripted_triggers[type]) {
//Scripted triggers can be called in two ways: "st = yes/no" and
//"st = { ...args... }". I don't think there's a way to internally
//negate the version with arguments (use "NOT = { st = { ... } }").
mapping args = mappingp(value) ? value : ([]); //Booleans have no args
args = mkmapping(sprintf("$%s$", indices(args)[*]), values(args)); //It's easier to include the dollar signs in the mapping
int match = trigger_matches(data, scopes, "AND", substitute_args(st, args));
if (value == 0) return !match; //"st = no" negates the result!
return match;
}
if (DEBUG_TRIGGER_MATCHES) werror("Unknown trigger %O = %O\n", type, value);
return 1; //Unknown trigger. Let it match, I guess - easier to spot? Maybe?
}
}
//List all ideas (including national) that are active
array(mapping) enumerate_ideas(mapping idea_groups) {
array ret = ({ });
foreach (idea_groups; string grp; string numtaken) {
mapping group = G->CFG->idea_definitions[grp]; if (!group) continue;
ret += ({group->start}) + group->ideas[..(int)numtaken - 1];
if (numtaken == "7") ret += ({group->bonus});
}
return ret - ({0});
}
//Gather ALL a country's modifiers. Or, try to. Note that conditional modifiers aren't included.
void _incorporate(mapping data, mapping scope, mapping modifiers, string source, mapping effect, int|void mul, int|void div) {
if (!div) mul = div = 1; //Note that mul might be zero (with a nonzero div), in which case there's no effect; or negative.
if (effect && mul) foreach (effect; string id; mixed val) {
if ((id == "modifier" || id == "modifiers") && mappingp(val)) _incorporate(data, scope, modifiers, source, val, mul, div);
if (id == "conditional") {
//Conditional attributes. There may be multiple independent blocks; each
//one has its "allow" block and then some attributes. At least, I *think*
//they're independent; the way some of them are coded, it might be that
//only one can ever match. Not sure.
foreach (Array.arrayify(val), mixed cond) if (mappingp(cond)) {
if (trigger_matches(data, ({scope}), "AND", cond->allow || ([])))
_incorporate(data, scope, modifiers, source, cond, mul, div);
}
}
if (id == "custom_attributes") _incorporate(data, scope, modifiers, source, val, mul, div); //Government reforms have some special modifiers. It's easiest to count them as country modifiers.
int effect = 0;
if (stringp(val) && sscanf(val, "%[-]%d%*[.]%[0-9]%s", string sign, int whole, string frac, string blank) && blank == "")
modifiers[id] += effect = (sign == "-" ? -1 : 1) * (whole * 1000 + (int)sprintf("%.03s", frac + "000")) * (mul||1) / (div||1);
if (intp(val) && val == 1) modifiers[id] = effect = 1; //Boolean
if (effect) modifiers->_sources[id] += ({source + ": " + effect});
}
}
void _incorporate_all(mapping data, mapping scope, mapping modifiers, string source, mapping definitions, array keys, int|void mul, int|void div) {
foreach (Array.arrayify(keys), string key)
_incorporate(data, scope, modifiers, sprintf("%s \"%s\"", source, L10N((string)key)), definitions[key], mul, div);
}
mapping(string:int) all_country_modifiers(mapping data, mapping country) {
if (mapping cached = country->all_country_modifiers) return cached;
mapping modifiers = (["_sources": ([])]);
_incorporate(data, country, modifiers, "Base", G->CFG->static_modifiers->base_values);
mapping tech = country->technology || ([]);
sscanf(data->date, "%d.%d.%d", int year, int mon, int day);
foreach ("adm dip mil" / " ", string cat) {
int level = (int)tech[cat + "_tech"];
string desc = String.capitalize(cat) + " tech";
_incorporate_all(data, country, modifiers, desc, G->CFG->tech_definitions[cat]->technology, enumerate(level + 1));
if ((int)G->CFG->tech_definitions[cat]->technology[level]->year > year)
_incorporate(data, country, modifiers, "Ahead of time in " + desc, G->CFG->tech_definitions[cat]->ahead_of_time);
//TODO: > or >= ?
}
//HACK: Army morale is actually handled in two parts: base and modifier. They are called land_morale and land_morale.
//Yeah. The one that comes from tech is the base, the other is percentage modifiers, but they have the same name.
//So in our analysis, we rename the tech ones to base_land_morale. This needs to happen prior to anything that could
//provide a percentage modifier, such as ideas, advisors, and temporary modifiers.
modifiers->base_land_morale = m_delete(modifiers, "land_morale");
modifiers->_sources->base_land_morale = m_delete(modifiers->_sources, "land_morale");
//TODO: Is naval_morale done the same way?
//Ideas are recorded by their groups and how many you've taken from that group.
array ideas = enumerate_ideas(country->active_idea_groups);
_incorporate(data, country, modifiers, ideas->desc[*], ideas[*]);
//NOTE: Custom nation ideas are not in an idea group as standard ideas are; instead
//you get a set of ten, identified by index, in country->custom_national_ideas, and
//it doesn't say which ones you have. I think the last three are the traditions and
//ambition and the first seven are the ideas themselves, but we'll have to count up
//the regular ideas and see how many to apply. It's possible that that would be out
//of sync, but it's unlikely. (If you remove an idea group, you lose national ideas
//corresponding to the number of removed ideas.)
if (array ideaids = country->custom_national_ideas) {
//First, figure out how many ideas you have. We assume that, if you have
//custom ideas, you don't also have a country idea set; which means that the
//ideas listed are exclusively ones from idea sets. You get one national idea
//for every three currently-held unlockable ideas; sum them and calculate.
int idea_count = `+(0, @(array(int))filter(values(country->active_idea_groups), stringp));
if (idea_count < 21)
//You don't have all the ideas. What you have is the first N ideas,
//plus the eighth and ninth, which are your national traditions.
ideaids = ideaids[..idea_count / 3 - 1] + ideaids[7..8];
//But if you have at least 21 other ideas, then you have all ten: the seven
//ideas, the two traditions, and the ambition.
//So! Let's figure out what those ideas actually are. They're identified by
//index, which is the same as array indices in custom_ideas[], and level,
//which is a simple multiplier on the effect. Conveniently, we already have
//a way to multiply the effects of things!
foreach (ideaids, mapping idea) {
mapping defn = G->CFG->custom_ideas[(int)idea->index];
_incorporate(data, country, modifiers, "Custom idea - " + L10N(defn->id), defn, (int)idea->level, 1);
}
}
_incorporate_all(data, country, modifiers, "Reform", G->CFG->reform_definitions, country->government->reform_stack->reforms);
//TODO: Reforms can have conditional modifiers. Notably, if you have Statists vs
//Monarchists (or Orangists), the one in power affects your country. This is
//tracked in country->statists_vs_monarchists; note that if the gauge is at
//precisely zero, this puts the statists in power, which effectively includes
//zero with the negative numbers.
//Conditional modifiers have an "allow" block and then everything else gets
//incorporated as normal. The attribute "states_general_mechanic" seems to have
//the effects of the two sides, although I'm not 100% sure of the details.
if (data->celestial_empire->emperor == country->tag) {
int mandate = threeplace(data->celestial_empire->imperial_influence);
if (mandate > 50000) _incorporate(data, country, modifiers, L10N("positive_mandate"), G->CFG->static_modifiers->positive_mandate, mandate - 50000, 50000);
if (mandate < 50000) _incorporate(data, country, modifiers, L10N("negative_mandate"), G->CFG->static_modifiers->negative_mandate, 50000 - mandate, 50000);
//TODO: Reforms should affect tributaries too. This only catches the Emperor.
foreach (Array.arrayify(data->celestial_empire->passed_reform), string reform)
_incorporate(data, country, modifiers, L10N(reform + "_emperor"), G->CFG->imperial_reforms[reform]->?emperor);
}
int stab = (int)country->stability;
if (stab > 0) _incorporate(data, country, modifiers, L10N("positive_stability"), G->CFG->static_modifiers->positive_stability, stab, 1);
if (stab < 0) _incorporate(data, country, modifiers, L10N("negative_stability"), G->CFG->static_modifiers->negative_stability, stab, 1);
_incorporate_all(data, country, modifiers, "Policy", G->CFG->policy_definitions, Array.arrayify(country->active_policy)->policy);
array tradebonus = G->CFG->trade_goods[Array.arrayify(country->traded_bonus)[*]];
_incorporate(data, country, modifiers, ("Trading in " + tradebonus->id[*])[*], tradebonus[*]); //TODO: TEST ME
_incorporate_all(data, country, modifiers, "Modifier", G->CFG->country_modifiers, Array.arrayify(country->modifier)->modifier);
mapping age = G->CFG->age_definitions[data->current_age]->abilities;
_incorporate(data, country, modifiers, "Age ability", age[Array.arrayify(country->active_age_ability)[*]][*]); //TODO: Add description
_incorporate(data, country, modifiers, L10N("war_exhaustion"), G->CFG->static_modifiers->war_exhaustion, threeplace(country->war_exhaustion), 1000);
_incorporate(data, country, modifiers, L10N("over_extension"), G->CFG->static_modifiers->over_extension, threeplace(country->overextension_percentage), 1000);
_incorporate_all(data, country, modifiers, "Aspect", G->CFG->church_aspects, Array.arrayify(country->church->?aspect));
int relig_unity = min(max(threeplace(country->religious_unity), 0), 1000);
_incorporate(data, country, modifiers, L10N("religious_unity"), G->CFG->static_modifiers->religious_unity, relig_unity, 1000);
_incorporate(data, country, modifiers, L10N("religious_unity"), G->CFG->static_modifiers->inverse_religious_unity, 1000 - relig_unity, 1000);
if (array have = country->institutions) foreach (G->CFG->institutions; string id; mapping inst) {
if (have[inst->_index] == "1") _incorporate(data, country, modifiers, "Institution", inst->bonus);
}
if (country->monarch) {
//Is there any way to directly look up the monarch details by ID?
mapping monarch = ([]);
foreach (sort(indices(country->history)), string key)
monarch = ((int)key && mappingp(country->history[key]) && (country->history[key]->monarch || country->history[key]->monarch_heir)) || monarch;
if (arrayp(monarch)) monarch = monarch[0]; //What does it mean when there are multiple? Check by ID?
if (mappingp(monarch->personalities))
_incorporate_all(data, country, modifiers, "Ruler -", G->CFG->ruler_personalities, indices(monarch->personalities));
modifiers->adm = (int)monarch->ADM;
modifiers->dip = (int)monarch->DIP;
modifiers->mil = (int)monarch->MIL;
}
//Legitimacy and its alternates
string legitimacy_type = "";
if (modifiers->republic) legitimacy_type = "republican_tradition";
else if (modifiers->enables_horde_idea_group) legitimacy_type = "horde_unity";
else if (modifiers->has_meritocracy) legitimacy_type = "meritocracy";
else if (modifiers->monarchy) legitimacy_type = "legitimacy";
else if (modifiers->has_devotion) legitimacy_type = "devotion";
//else if (modifiers->native_mechanic) ; //Native tribes have no legitimacy-like mechanic
//else werror("UNKNOWN LEGITIMACY TYPE: %O\n", country); //Shouldn't happen.
int legitimacy_value = threeplace(country[legitimacy_type]);
if (mapping inverse = G->CFG->static_modifiers["inverse_" + legitimacy_type]) {
//Republican Tradition has two contradictory effects, one scaling from 0%-100% as tradition goes 0-100,
//the other scaling as tradition goes 100-0.
_incorporate(data, country, modifiers, L10N(legitimacy_type), G->CFG->static_modifiers[legitimacy_type], legitimacy_value, 100000);
_incorporate(data, country, modifiers, L10N("inverse_" + legitimacy_type), inverse, 100000 - legitimacy_value, 100000);
} else {
//Everything else has a single main effect that scales both directions from 50.
//They may also have a low_ modifier which applies only if below 50.
_incorporate(data, country, modifiers, L10N(legitimacy_type), G->CFG->static_modifiers[legitimacy_type], legitimacy_value - 50000, 100000);
if (legitimacy_value < 50000)
_incorporate(data, country, modifiers, L10N(legitimacy_type), G->CFG->static_modifiers["low_" + legitimacy_type], 50000 - legitimacy_value, 100000);
}
int pp = `+(0, @threeplace(Array.arrayify(country->power_projection)->current[*]));
_incorporate(data, country, modifiers, L10N("power_projection"), G->CFG->static_modifiers->power_projection, pp, 100000);
_incorporate(data, country, modifiers, L10N("prestige"), G->CFG->static_modifiers->prestige, threeplace(country->prestige), 100000);
_incorporate(data, country, modifiers, L10N("army_tradition"), G->CFG->static_modifiers->army_tradition, threeplace(country->army_tradition), 100000);
//More modifier types to incorporate:
//- Religious modifiers (icons, cults, etc)
//- Government type modifiers (eg march, vassal, colony)
//- Naval tradition (which affects trade steering and thus the trade recommendations)
//- Being a trade league leader (scaled by the number of members)
//- Province Triggered Modifiers (handle them alongside monuments?)
foreach (country->owned_provinces, string id) {
mapping prov = data->provinces["-" + id];
if (prov->great_projects) foreach (prov->great_projects, string project) {
mapping proj = data->great_projects[project];
if (!(int)proj->?development_tier) continue; //Not upgraded, presumably has no effect (is that always true?)
mapping defn = G->CFG->great_projects[project];
if (!defn) continue; //In analyze_leviathans, there's a note about this possibility
mapping req = defn->can_use_modifiers_trigger;
if (sizeof(req) && !describe_requirements(req, prov, country)[1]) continue;
mapping active = defn["tier_" + proj->development_tier]; if (!active) continue;
_incorporate(data, country, modifiers, L10N(project), active->country_modifiers);
}
}
if (country->luck) _incorporate(data, country, modifiers, "Luck", G->CFG->static_modifiers->luck); //Lucky nations (AI-only) get bonuses.
if (int innov = threeplace(country->innovativeness)) _incorporate(data, country, modifiers, "Innovativeness", G->CFG->static_modifiers->innovativeness, innov, 100000);
if (int corr = threeplace(country->corruption)) _incorporate(data, country, modifiers, "Corruption", G->CFG->static_modifiers->corruption, corr, 100000);
//Having gone through all of the above, we should now have estate influence modifiers.
//Now we can calculate the total influence, and then add in the effects of each estate.
if (country->estate) {
//Some estates might not work like this. Not sure.
//First, incorporate country-wide modifiers from privileges. (It's possible for privs to
//affect other estates' influences.)
country->estate = Array.arrayify(country->estate); //In case there's only one estate
foreach (country->estate, mapping estate) {
foreach (Array.arrayify(estate->granted_privileges), [string priv, string date]) {
mapping privilege = G->CFG->estate_privilege_definitions[priv]; if (!privilege) continue;
string desc = sprintf("%s: %s", L10N(estate->type), L10N(priv));
_incorporate(data, country, modifiers, desc, privilege->penalties);
_incorporate(data, country, modifiers, desc, privilege->benefits);
}
}
//Now calculate the influence and loyalty of each estate, and the resulting effects.
foreach (country->estate, mapping estate) {
mapping estate_defn = G->CFG->estate_definitions[estate->type];
if (!estate_defn) continue;
mapping influence = (["Base": (int)estate_defn->base_influence * 1000]);
//There are some conditional modifiers. Sigh. This is seriously complicated. Why can't estate influence just be in the savefile?
foreach (Array.arrayify(estate->granted_privileges), [string priv, string date])
influence["Privilege " + L10N(priv)] =
threeplace(G->CFG->estate_privilege_definitions[priv]->?influence) * 100;
foreach (Array.arrayify(estate->influence_modifier), mapping mod)
//It's possible to have the same modifier more than once (eg "Diet Summoned").
//Rather than show them all separately, collapse them into "Diet Summoned: 15%".
influence[L10N(mod->desc) || "(unknown modifier)"] += threeplace(mod->value);
foreach (Array.arrayify(modifiers->_sources[replace(estate->type, "estate_", "") + "_influence_modifier"])
+ Array.arrayify(modifiers->_sources->all_estate_influence_modifier), string mod) {
sscanf(reverse(mod), "%[-0-9] :%s", string value, string desc);
influence[reverse(desc)] += (int)reverse(value) * 100; //Just in case they show up more than once
}
influence["Land share"] = threeplace(estate->territory) * threeplace(estate_defn->influence_from_dev_modifier) / 2000; //Not sure why the "/2" part; the modifier is 1.0 if it scales this way, otherwise larger or smaller numbers.
//Attempt to parse the estate influence modifier blocks. This is imperfect and limited.
foreach (Array.arrayify(estate_defn->influence_modifier), mapping mod) {
if (!trigger_matches(data, ({country}), "AND", mod->trigger)) continue;
influence[L10N(mod->desc)] = threeplace(mod->influence);
}
int total_influence = estate->estimated_milliinfluence = `+(@values(influence));
estate->influence_sources = influence; //Not quite the same format as _sources elsewhere though
string opinion = "neutral";
if ((float)estate->loyalty >= 60.0) opinion = "happy";
else if ((float)estate->loyalty < 30.0) opinion = "angry";
int mul = 4;
if (total_influence < 60000) mul = 3;
if (total_influence < 40000) mul = 2;
if (total_influence < 20000) mul = 1;
_incorporate(data, country, modifiers, String.capitalize(opinion) + " " + L10N(estate->type), estate_defn["country_modifier_" + opinion], mul, 4);
}
}
//To figure out what advisors you have hired, we first need to find all advisors.
//They're not listed in country details; they're listed in the provinces that they
//came from. So we first have to find all available advisors.
mapping advisors = ([]);
foreach (country->owned_provinces, string id) {
mapping prov = data->provinces["-" + id];
foreach (prov->history;; mixed infoset) foreach (Array.arrayify(infoset), mixed info) {
if (!mappingp(info)) continue; //Some info in history is just strings or booleans
if (info->advisor) advisors[info->advisor->id->id] = info->advisor;
}
if (prov->history->advisor) advisors[prov->history->advisor->id->id] = prov->history->advisor;
}
foreach (Array.arrayify(country->advisor), mapping adv) {
adv = advisors[adv->id]; if (!adv) continue;
mapping type = G->CFG->advisor_definitions[adv->type];
_incorporate(data, country, modifiers, L10N(adv->type) + " (" + adv->name + ")", type);
}
//Your religion affects your country (whodathunk). Note that we also incorporate some other
//attributes here for convenience, even though they're not really country modifiers.
foreach (G->CFG->religion_definitions; string grpname; mapping group) {
mapping relig = group[country->religion];
if (!relig) continue; //Not this group. Moving on!
_incorporate(data, country, modifiers, L10N(country->religion), relig->country);
_incorporate(data, country, modifiers, L10N(country->religion), relig & (<
"uses_anglican_power", "uses_hussite_power", "uses_church_power", "has_patriarchs",
"fervor", "uses_piety", "uses_karma", "uses_harmony", "uses_isolationism", "uses_judaism_power",
"personal_deity", "fetishist_cult", "ancestors", "authority", "religious_reforms",
"doom", "declare_war_in_regency", "can_have_secondary_religion", "fetishist_cult",
>));
_incorporate(data, country, modifiers, L10N(grpname), group & (<"can_form_personal_unions">));
//What is relig->country_as_secondary used for? Syncretic?
//TODO: Also check Muslim schools for their attributes
}
//Additional religion-specific information.
mapping rel = data->religion_instance_data[country->religion] || ([]);
if (string gb = rel->papacy->?golden_bull) _incorporate(data, country, modifiers, L10N(gb), G->CFG->golden_bulls[gb]);
//TODO: Defender of the Faith? Crusade? Curia controller? Do these get listed as their
//own modifiers or do we need to pick them up from here?
if (modifiers->uses_harmony) {
int harmony = threeplace(country->harmony);
if (harmony > 50000) _incorporate(data, country, modifiers, L10N("high_harmony"), G->CFG->static_modifiers->high_harmony, harmony - 50000, 50000);
if (harmony < 50000) _incorporate(data, country, modifiers, L10N("low_harmony"), G->CFG->static_modifiers->low_harmony, 50000 - harmony, 50000);
}
//Triggered modifiers. Some of these might be affected by other country modifiers,
//so we stash the ones we have so far. This might mean we get inaccurate results
//(if one triggered modifier affects another), but at least we don't get infinite
//recursion.
country->all_country_modifiers = modifiers;
#if 0
DEBUG_TRIGGER_MATCHES = 1;
foreach (G->CFG->triggered_modifiers; string id; mapping mod) {
if (mod->potential && !trigger_matches(data, ({country}), "AND", mod->potential)) continue;
if (!trigger_matches(data, ({country}), "AND", mod->trigger)) continue;
//Disabled for now; need to get a lot more trigger_matches clauses.
//At the moment, I'd rather have no triggered modifiers at all than
//have a ton of false positives.
//_incorporate(data, country, modifiers, L10N(id), mod);
werror("Triggered Modifier: %s %O\n", id, L10N(id));
}
DEBUG_TRIGGER_MATCHES = 0;
#endif
return modifiers;
}
mapping(string:int) all_province_modifiers(mapping data, int id) {
mapping prov = data->provinces["-" + id];
if (mapping cached = prov->all_province_modifiers) return cached;
mapping country = data->countries[prov->owner];
mapping modifiers = (["_sources": ([])]);
if (prov->center_of_trade) {
string type = G->CFG->province_info[(string)id]->?has_port ? "coastal" : "inland";
mapping cot = G->CFG->cot_definitions[type + prov->center_of_trade];
_incorporate(data, prov, modifiers, "Level " + prov->center_of_trade + " COT", cot->?province_modifiers);
}
if (int l3cot = country->?area_has_level3[?G->CFG->prov_area[(string)id]]) {
string type = G->CFG->province_info[(string)l3cot]->?has_port ? "coastal3" : "inland3";
mapping cot = G->CFG->cot_definitions[type];
_incorporate(data, prov, modifiers, "L3 COT in area", cot->?state_modifiers);
}
foreach (prov->buildings || ([]); string b;) {
_incorporate(data, prov, modifiers, "Building", G->CFG->building_types[b]);
if (has_value(G->CFG->building_types[b]->bonus_manufactory || ({ }), prov->trade_goods))
_incorporate(data, prov, modifiers, "Mfg has " + prov->trade_goods, G->CFG->building_types[b]->bonus_modifier);
}
mapping area = data->map_area_data[G->CFG->prov_area[(string)id]]->?state;
foreach (Array.arrayify(area->?country_state), mapping state) if (state->country == prov->owner) {
if (state->prosperity == "100.000") _incorporate(data, prov, modifiers, "Prosperity", G->CFG->static_modifiers->prosperity);
_incorporate(data, prov, modifiers, "State edict - " + L10N(state->active_edict->?which), G->CFG->state_edicts[state->active_edict->?which]);
_incorporate(data, prov, modifiers, "Holy order - " + L10N(state->holy_order), G->CFG->holy_orders[state->holy_order]);
}
_incorporate(data, prov, modifiers, "Terrain", G->CFG->terrain_definitions->categories[G->CFG->province_info[(string)id]->terrain]);
_incorporate(data, prov, modifiers, "Climate", G->CFG->static_modifiers[G->CFG->province_info[(string)id]->climate]);
if (prov->hre) {
foreach (Array.arrayify(data->empire->passed_reform), string reform)
_incorporate(data, prov, modifiers, "HRE province (" + L10N(reform + "_province") + ")", G->CFG->imperial_reforms[reform]->?province);
}
_incorporate(data, prov, modifiers, "Trade good: " + prov->trade_goods, G->CFG->trade_goods[prov->trade_goods]->?province);
//How do we know if it's a city or not? This should be applied only if it's a fully-developed province, not a colony.
_incorporate(data, prov, modifiers, "City", G->CFG->static_modifiers->city);
if (prov->has_port) _incorporate(data, prov, modifiers, "Port", G->CFG->static_modifiers->port);
int dev = (int)prov->base_tax + (int)prov->base_production + (int)prov->base_manpower;
modifiers->development = dev;
_incorporate(data, prov, modifiers, "Development", G->CFG->static_modifiers->development, dev);
//TODO: development_scaled (to calculate the actual development cost)
//TODO: expanded_infrastructure, centralize_state
//TODO: in_state, in_capital_state, coastal, seat_in_parliament
//TODO: Syncretic/Secondary religion for Tengri
//TODO: Confucian harmonization bonuses
//TODO: Sow Discontent (diplomatic action)
if (prov->owner) {
mapping counmod = all_country_modifiers(data, country);
//First off, what kind of religious tolerance is this?
//TODO: Use "own" if harmonized with religion or group
string type = "heathen";
if (prov->religion == country->religion) type = "own";
else foreach (G->CFG->religion_definitions; string grp; mapping defn) {
if (defn[prov->religion] && defn[country->religion]) type = "heretic";
}
int tolerance = counmod["tolerance_" + type];
//Tolerance of True Faith has no limit, but the other two are capped.
if (type != "own") tolerance = min(tolerance, counmod["tolerance_of_" + type + "s_capacity"]);
if (tolerance > 0) _incorporate(data, prov, modifiers, L10N("tolerance"), G->CFG->static_modifiers->tolerance, tolerance, 1000);
if (tolerance < 0) _incorporate(data, prov, modifiers, L10N("intolerance"), G->CFG->static_modifiers->intolerance, tolerance, 1000);
}
//TODO: Fold this in with the equivalent block in all_country_modifiers()
if (prov->great_projects) foreach (prov->great_projects, string project) {
mapping proj = data->great_projects[project];
if (!(int)proj->?development_tier) continue; //Not upgraded, presumably has no effect (is that always true?)
mapping defn = G->CFG->great_projects[project];
if (!defn) continue; //In analyze_leviathans, there's a note about this possibility
mapping req = defn->can_use_modifiers_trigger;
if (sizeof(req) && !describe_requirements(req, prov, country)[1]) continue;
mapping active = defn["tier_" + proj->development_tier]; if (!active) continue;
_incorporate(data, prov, modifiers, L10N(project), active->province_modifiers);
}
string cul = prov->culture, cul_modifier = "non_accepted_culture";
if (cul == country->?primary_culture || has_value(Array.arrayify(country->?accepted_culture), cul))
cul_modifier = "same_culture"; //This doesn't actually exist - there seem to be no "accepted culture" modifiers
else {
//What if it's in your culture group?
foreach (G->CFG->culture_definitions; string group; mapping info)
if (info[country->?primary_culture] && info[cul])
//Same group. If you're empire rank, that counts as accepted.
cul_modifier = country->government_rank == "3" ? "same_culture" : "same_culture_group";
}
_incorporate(data, prov, modifiers, L10N(cul_modifier), G->CFG->static_modifiers[cul_modifier]);
//TODO: accepted_culture_demoted (time-delay, possibly decaying, after unaccepting a culture)
//TODO: non_accepted_culture_republic (additional modifier if you're a republic)
return prov->all_province_modifiers = modifiers;
}
//Note that, unlike province and country modifiers, this is not actually cached anywhere.
//(It does make good use of province modifier caching though.)
mapping(string:int) all_area_modifiers(mapping data, string area) {
mapping modifiers = (["_sources": ([])]);
foreach (G->CFG->map_areas[area], string id) {
mapping prov = all_province_modifiers(data, (int)id);
string label = data->provinces["-" + id]->name + ": ";
foreach ("statewide_governing_cost" / " ", string attr) if (prov[attr]) {
modifiers[attr] += prov[attr];
modifiers->_sources[attr] += label + prov->_sources[attr][*];
}
}
return modifiers;
}
//Estimate a months' production of ducats/manpower/sailors (yes, I'm fixing the scaling there)
array(float) estimate_per_month(mapping data, mapping country) {
float gold = (float)country->ledger->lastmonthincome - (float)country->ledger->lastmonthexpense;
float manpower = (float)country->max_manpower * 1000 / 120.0;
float sailors = (float)country->max_sailors / 120.0;
//Attempt to calculate modifiers. This is not at all accurate but should give a reasonable estimate.
float mp_mod = 1.0, sail_mod = 1.0;
mp_mod += (float)country->army_tradition * 0.001;
sail_mod += (float)country->navy_tradition * 0.002;
mp_mod -= (float)country->war_exhaustion / 100.0;
sail_mod -= (float)country->war_exhaustion / 100.0;
mapping modifiers = all_country_modifiers(data, country);
mp_mod += modifiers->manpower_recovery_speed / 1000.0;
sail_mod += modifiers->sailors_recovery_speed / 1000.0;
//Add back on the base manpower recovery (10K base manpower across ten years),
//which isn't modified by recovery bonuses/penalties. Doesn't apply to sailors
//as there's no "base sailors".
//CJA 20211224: Despite what the wiki says, it seems this isn't the case, and
//manpower recovery modifiers are applied to the base 10K as well.
manpower = manpower * mp_mod; sailors *= sail_mod;
return ({gold, max(manpower, 100.0), max(sailors, sailors > 0.0 ? 5.0 : 0.0)}); //There's minimum manpower/sailor recovery
}
array(string|int) describe_requirements(mapping req, mapping prov, mapping country, int|void any) {
if (!country) return ({"n/a", 3}); //Not sure how useful this will be.
array ret = ({ });
string religion = prov->religion;
if (religion != country->religion) religion = "n/a";
array accepted_cultures = ({country->primary_culture}) + Array.arrayify(country->accepted_culture);
if (country->government_rank == "3") //Empire rank, all in culture group are accepted
foreach (G->CFG->culture_definitions; string group; mapping info)
if (info[country->primary_culture]) accepted_cultures += indices(info);
//Some two-part checks can also be described in one part. Fold them together.
if (m_delete(req, "has_owner_religion")) {
if (string rel = m_delete(req, "religion"))
req->province_is_or_accepts_religion = (["religion": Array.arrayify(rel)[*]]);
if (string grp = m_delete(req, "religion_group"))
req->province_is_or_accepts_religion_group = (["religion_group": Array.arrayify(grp)[*]]);
}
foreach (sort(indices(req)), string type) {
array|mapping need = Array.arrayify(req[type]);
switch (type) {
case "province_is_or_accepts_religion_group": {
//If multiple, it's gonna be "OR" mode, otherwise it could never be true
mapping accepted = `+(@G->CFG->religion_definitions[need->religion_group[*]]);
//If it says "Christian or Muslim" and you're Catholic, it will just say "Catholic"
if (accepted[religion]) ret += ({({L10N(religion), 1})});
//If it says "Christian" and you're Catholic but the province is Protestant, it will say "Christian" but type 2
else if (accepted[country->religion]) ret += ({({L10N(need->religion_group[*]) * " / ", 2})});
//Otherwise, it's unviable.
else ret += ({({L10N(need->religion_group[*]) * " / ", 3})});
break;
}
case "province_is_buddhist_or_accepts_buddhism":
need = (["religion": ({"buddhism", "vajrayana", "mahayana"})]);
//Fall through
case "province_is_or_accepts_religion": {
if (has_value(need->religion, religion)) ret += ({({L10N(religion), 1})});
else if (has_value(need->religion, country->religion)) ret += ({({L10N(need->religion[*]) * " / ", 2})});
else ret += ({({L10N(need->religion[*]) * " / ", 3})});
break;
}
case "province_is_buddhist_or_accepts_buddhism_or_is_dharmic":
ret += ({describe_requirements(([
"has_owner_religion": 1,
"religion": ({"buddhism", "vajrayana", "mahayana"}),
"religion_group": "dharmic",
]), prov, country, 1)});
break;
case "culture_group":
if (has_value(`+(@indices(G->CFG->culture_definitions[need[*]][*])), prov->culture)
&& has_value(accepted_cultures, prov->culture))
ret += ({({L10N(prov->culture), 1})});
else ret += ({({L10N(need[*]) * " / ", 2})});
break;
case "culture":
if (has_value(need[*], prov->culture)
&& has_value(accepted_cultures, prov->culture))
ret += ({({L10N(prov->culture), 1})});
else ret += ({({L10N(need[*]) * " / ", 2})});
break;
case "province_is_or_accepts_culture": break; //Always goes with culture/culture_group and is assumed to be a requirement
case "custom_trigger_tooltip": switch (need[0]->tooltip) {
//Hack: For the known ones, render them in a simplified way
case "hagia_sophia_tt":
ret += ({describe_requirements(([
"has_owner_religion": 1,
"religion": ({"orthodox", "coptic", "catholic"}),
"religion_group": "muslim",
]), prov, country, 1)});
break;
case "mount_fuji_tt":
ret += ({describe_requirements(([
"has_owner_religion": 1,
"religion": ({"shinto", "mahayana"}),
]), prov, country, 1)});
break;
//Otherwise, render the tooltip itself.
default: ret += ({({L10N(need[0]->tooltip), 3})});
}
break;
case "OR": ret += describe_requirements(need[*], prov, country, 1); break;
case "AND": ret += describe_requirements(need[*], prov, country); break;
case "if":
//There may be other conditions happening. As of v1.34, the only use of 'if'
//is a simple check that allows a country to ignore the requirements under
//some conditions, so we'll just ignore the limit and carry on.
ret += describe_requirements((need[*] - (<"limit">))[*], prov, country, any);
break;
case "owner": if (need[0]->has_reform) {ret += ({({L10N(need[0]->has_reform), 3})}); break;} //else unknown
default: ret += ({({"Unknown", 3})});
}
}
if (any) return ({ret[*][0] * " / ", min(@ret[*][1])});
return ({ret[*][0] * " + ", max(@ret[*][1])});
}
void analyze_leviathans(mapping data, string name, string tag, mapping write) {
if (!has_value(data->dlc_enabled, "Leviathan")) return;
mapping country = data->countries[tag];
array projects = ({ });
foreach (country->owned_provinces, string id) {
mapping prov = data->provinces["-" + id];
if (!prov->great_projects) continue;
mapping con = prov->great_project_construction || ([]);
foreach (prov->great_projects, string project) {
mapping proj = data->great_projects[project] || (["development_tier": "0"]); //Weirdly, I have once seen a project that's just missing from the file.
mapping defn = G->CFG->great_projects[project];
if (!defn) { //FIXME: When are we seeing unknown projects??
werror("UNKNOWN PROJECT %O\n", project);
defn = (["can_use_modifiers_trigger": ({ })]);
}
//TODO: Parse out defn->can_use_modifiers_trigger and determine:
//1) Religion-locked (list religions and/or groups that are acceptable)
// "province_is_or_accepts_religion_group", "province_is_buddhist_or_accepts_buddhism", "province_is_buddhist_or_accepts_buddhism_or_is_dharmic"
//2) Culture-locked (ditto) "culture[_group]" + "province_is_or_accepts_culture = yes"
//3) Religion-or-Culture locked (an OR= of the above two)
//4) No requirements
//5) custom_trigger_tooltip - use the tooltip as-is
//6) Other. Show the definition for debugging. (Celestial Empire possibly?)
string requirements = "None"; int req_achieved = 1;
mapping req = defn->can_use_modifiers_trigger;
if (sizeof(req))
[requirements, req_achieved] = describe_requirements(req, prov, country);
projects += ({({
//Sort key
(int)id - (int)proj->development_tier * 10000,
//Legacy: preformatted table data
({"", id, "Lvl " + proj->development_tier, prov->name, G->CFG->L10n[project] || "#" + project,
con->great_projects != project ? "" : //If you're upgrading a different great project in this province, leave this one blank (you can't upgrade two at once)
sprintf("%s%d%%, due %s",
con->type == "2" ? "Moving: " : "", //Upgrades are con->type "1", moving to capital is type "2"
threeplace(con->progress) / 10, con->date),
}), ([
//Data for the front end JS to render
"province": id, "tier": proj->development_tier,
"name": L10N(project),
"upgrading": con->great_projects != project ? 0 : con->type == "2" ? "moving" : "upgrading",
"progress": threeplace(con->progress), "completion": con->date, //Meaningful only if upgrading is nonzero
"requirements": requirements, "req_achieved": req_achieved,
]),
})});
//werror("Project: %O\n", proj);
}
}
sort(projects);
object today = calendar(data->date);
array cooldowns = ({ });
mapping cd = country->cooldowns || ([]);
array(float) permonth = estimate_per_month(data, country);
foreach ("gold men sailors" / " "; int i; string tradefor) {
string date = cd["trade_favors_for_" + tradefor];
string cur = sprintf("%.3f", permonth[i] * 6);
//Sometimes the cooldown is still recorded, but is in the past. No idea why. We hide that completely.
int days; catch {if (date) days = today->distance(calendar(date)) / today;};
if (!days) {cooldowns += ({({"", "---", "--------", String.capitalize(tradefor), cur})}); continue;}
cooldowns += ({({"", days, date, String.capitalize(tradefor), cur})}); //TODO: Remove the unnecessary empty string at the start
}
write->monuments = projects[*][2];
//Favors are all rendered on the front end.
mapping owed = ([]);
foreach (data->countries; string other; mapping c) {
int favors = threeplace(c->active_relations[tag]->?favors);
if (favors > 0) owed[other] = ({favors / 1000.0}) + estimate_per_month(data, c)[*] * 6;
}
write->favors = (["cooldowns": cooldowns, "owed": owed]);
}
int count_building_slots(mapping data, string id) {
mapping prov = data->provinces["-" + id];
return (all_province_modifiers(data, (int)id)->allowed_num_of_buildings
+ all_country_modifiers(data, data->countries[prov->owner])->global_allowed_num_of_buildings
) / 1000; //round down - partial building slots from dev don't count
}
void analyze_furnace(mapping data, string name, string tag, mapping write) {
mapping country = data->countries[tag];
array coalprov = ({ });
foreach (country->owned_provinces, string id) {
mapping prov = data->provinces["-" + id];
if (!G->CFG->province_info[id]->has_coal) continue;
int dev = (int)prov->base_tax + (int)prov->base_production + (int)prov->base_manpower;
mapping bldg = prov->buildings || ([]);
mapping mfg = bldg & G->CFG->manufactories;
string status = "";
if (prov->trade_goods != "coal") {
//Not yet producing coal. There are a few reasons this could be the case.
if (country->institutions[6] != "1") status = "Not embraced";
else if (prov->institutions[6] != "100.000") status = "Not Enlightened";
else if (dev < 20 && (int)country->innovativeness < 20) status = "Need 20 dev/innov";
else status = "Producing " + prov->trade_goods; //Assuming the above checks are bug-free, the province should flip to coal at the start of the next month.
}
else if (bldg->furnace) status = "Has Furnace";
else if (G->CFG->building_id[(int)prov->building_construction->?building] == "furnace")
status = prov->building_construction->date;
else if (sizeof(mfg)) status = values(mfg)[0];
else if (prov->settlement_growth_construction) status = "SETTLER ACTIVE"; //Can't build while there's a settler promoting growth);
int slots = count_building_slots(data, id);
int buildings = sizeof(bldg);
if (prov->building_construction) {
//There's something being built. That consumes a slot, but if it's an
//upgrade, then that slot doesn't really count. If you have four slots,