-
Notifications
You must be signed in to change notification settings - Fork 41
/
Copy pathcityturn.cpp
4331 lines (3824 loc) · 148 KB
/
cityturn.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
/*__ ___ ***************************************
/ \ / \ Copyright (c) 1996-2023 Freeciv21 and Freeciv
\_ \ / __/ contributors. This file is part of Freeciv21.
_\ \ / /__ Freeciv21 is free software: you can redistribute it
\___ \____/ __/ and/or modify it under the terms of the GNU General
\_ _/ Public License as published by the Free Software
| @ @ \_ Foundation, either version 3 of the License,
| or (at your option) any later version.
_/ /\ You should have received a copy of the GNU
/o) (o/\ \_ General Public License along with Freeciv21.
\_____/ / If not, see https://www.gnu.org/licenses/.
\____/ ********************************************************/
#include <cmath> // exp, sqrt
#include <cstring>
// utility
#include "fcintl.h"
#include "log.h"
#include "rand.h"
#include "shared.h"
#include "support.h"
/* common/aicore */
#include "cm.h"
// common
#include "achievements.h"
#include "actiontools.h"
#include "borders.h"
#include "calendar.h"
#include "citizens.h"
#include "city.h"
#include "culture.h"
#include "disaster.h"
#include "events.h"
#include "game.h"
#include "government.h"
#include "map.h"
#include "player.h"
#include "research.h"
#include "server_settings.h"
#include "specialist.h"
#include "style.h"
#include "tech.h"
#include "traderoutes.h"
#include "unit.h"
#include "unitlist.h"
/* common/scriptcore */
#include "luascript_types.h"
// server
#include "citizenshand.h"
#include "citytools.h"
#include "cityturn.h"
#include "maphand.h"
#include "notify.h"
#include "plrhand.h"
#include "sanitycheck.h"
#include "spacerace.h"
#include "srv_log.h"
#include "techtools.h"
#include "unittools.h"
/* server/advisors */
#include "advbuilding.h"
#include "advdata.h"
/* server/scripting */
#include "script_server.h"
// Queue for pending city_refresh()
static struct city_list *city_refresh_queue = nullptr;
/* The game is currently considering to remove the listed units because of
* missing gold upkeep. A unit ends up here if it has gold upkeep that
* can't be payed. A random unit in the list will be removed until the
* problem is solved. */
static struct unit_list *uk_rem_gold = nullptr;
static void check_pollution(struct city *pcity);
static void city_populate(struct city *pcity, struct player *nationality);
static bool worklist_change_build_target(struct player *pplayer,
struct city *pcity);
static bool city_distribute_surplus_shields(struct player *pplayer,
struct city *pcity);
static void wonder_set_build_turn(struct player *pplayer,
const struct impr_type *pimprove);
static bool city_build_building(struct player *pplayer, struct city *pcity);
static bool city_build_unit(struct player *pplayer, struct city *pcity);
static bool city_build_stuff(struct player *pplayer, struct city *pcity);
static const struct impr_type *
building_upgrades_to(struct city *pcity, const struct impr_type *pimprove);
static void upgrade_building_prod(struct city *pcity);
static const struct unit_type *unit_upgrades_to(struct city *pcity,
const struct unit_type *id);
static void upgrade_unit_prod(struct city *pcity);
// Helper struct for associating a building to a city.
struct cityimpr {
struct city *pcity;
struct impr_type *pimprove;
};
#define SPECLIST_TAG cityimpr
#define SPECLIST_TYPE struct cityimpr
#include "speclist.h"
#define cityimpr_list_iterate(cityimprlist, pcityimpr) \
TYPED_LIST_ITERATE(struct cityimpr, cityimprlist, pcityimpr)
#define cityimpr_list_iterate_end LIST_ITERATE_END
static bool sell_random_building(struct player *pplayer,
struct cityimpr_list *imprs);
static struct unit *sell_random_unit(struct player *pplayer,
struct unit_list *punitlist);
static citizens city_reduce_specialists(struct city *pcity, citizens change);
static citizens city_reduce_workers(struct city *pcity, citizens change);
static bool city_balance_treasury_buildings(struct city *pcity);
static bool city_balance_treasury_units(struct city *pcity);
static bool
player_balance_treasury_units_and_buildings(struct player *pplayer);
static bool player_balance_treasury_units(struct player *pplayer);
static bool disband_city(struct city *pcity);
static void define_orig_production_values(struct city *pcity);
static void update_city_activity(struct city *pcity);
static void nullify_caravan_and_disband_plus(struct city *pcity);
static bool city_illness_check(const struct city *pcity);
static float city_migration_score(struct city *pcity);
static bool do_city_migration(struct city *pcity_from,
struct city *pcity_to);
static bool check_city_migrations_player(const struct player *pplayer);
static bool city_handle_disorder(struct city *pcity);
static bool city_handle_plague_risk(struct city *pcity);
/**
Updates unit upkeeps and city internal cached data. Returns whether
city radius has changed.
*/
bool city_refresh(struct city *pcity)
{
bool retval;
pcity->server.needs_refresh = false;
retval = city_map_update_radius_sq(pcity);
city_units_upkeep(pcity); // update unit upkeep
city_refresh_from_main_map(pcity, nullptr,
player_gov_centers(city_owner(pcity)));
city_style_refresh(pcity);
if (retval) {
// Force a sync of the city after the change.
send_city_info(city_owner(pcity), pcity);
}
return retval;
}
/**
Called on government change or wonder completion or stuff like that
-- Syela
*/
void city_refresh_for_player(struct player *pplayer)
{
conn_list_do_buffer(pplayer->connections);
city_list_iterate(pplayer->cities, pcity)
{
if (city_refresh(pcity)) {
auto_arrange_workers(pcity);
}
send_city_info(pplayer, pcity);
}
city_list_iterate_end;
conn_list_do_unbuffer(pplayer->connections);
}
/**
Queue pending city_refresh() for later.
*/
void city_refresh_queue_add(struct city *pcity)
{
if (nullptr == city_refresh_queue) {
city_refresh_queue = city_list_new();
} else if (city_list_find_number(city_refresh_queue, pcity->id)) {
return;
}
city_list_prepend(city_refresh_queue, pcity);
pcity->server.needs_refresh = true;
}
/**
Refresh the listed cities.
Called after significant changes to borders, and arranging workers.
*/
void city_refresh_queue_processing()
{
if (nullptr == city_refresh_queue) {
return;
}
city_list_iterate(city_refresh_queue, pcity)
{
if (pcity->server.needs_refresh) {
if (city_refresh(pcity)) {
auto_arrange_workers(pcity);
}
send_city_info(city_owner(pcity), pcity);
}
}
city_list_iterate_end;
city_list_destroy(city_refresh_queue);
city_refresh_queue = nullptr;
}
/**
Automatically sells obsolete buildings from city.
*/
void remove_obsolete_buildings_city(struct city *pcity, bool refresh)
{
struct player *pplayer = city_owner(pcity);
bool sold = false;
city_built_iterate(pcity, pimprove)
{
if (improvement_obsolete(pplayer, pimprove, pcity)
&& can_city_sell_building(pcity, pimprove)) {
int sgold;
do_sell_building(pplayer, pcity, pimprove, "obsolete");
sgold = impr_sell_gold(pimprove);
notify_player(pplayer, city_tile(pcity), E_IMP_SOLD, ftc_server,
PL_("%s is selling %s (obsolete) for %d.",
"%s is selling %s (obsolete) for %d.", sgold),
city_link(pcity), improvement_name_translation(pimprove),
sgold);
sold = true;
}
}
city_built_iterate_end;
if (sold && refresh) {
if (city_refresh(pcity)) {
auto_arrange_workers(pcity);
}
send_city_info(pplayer, pcity);
send_player_info_c(pplayer, nullptr); // Send updated gold to all
}
}
/**
Sell obsolete buildings from all cities of the player
*/
void remove_obsolete_buildings(struct player *pplayer)
{
city_list_iterate(pplayer->cities, pcity)
{
remove_obsolete_buildings_city(pcity, false);
}
city_list_iterate_end;
}
/**
Rearrange workers according to a cm_result struct. The caller must make
sure that the result is valid.
*/
void apply_cmresult_to_city(struct city *pcity,
const std::unique_ptr<cm_result> &cmr)
{
struct tile *pcenter = city_tile(pcity);
// Now apply results
city_tile_iterate_skip_center(city_map_radius_sq_get(pcity), pcenter,
ptile, idx, x, y)
{
struct city *pwork = tile_worked(ptile);
if (cmr->worker_positions[idx]) {
if (nullptr == pwork) {
city_map_update_worker(pcity, ptile);
} else {
fc_assert(pwork == pcity);
}
} else {
if (pwork == pcity) {
city_map_update_empty(pcity, ptile);
}
}
}
city_tile_iterate_skip_center_end;
specialist_type_iterate(sp)
{
pcity->specialists[sp] = cmr->specialists[sp];
}
specialist_type_iterate_end;
}
/**
Set default city manager parameter for the city.
*/
static void set_default_city_manager(struct cm_parameter *cmp,
struct city *pcity)
{
cmp->require_happy = false;
cmp->allow_disorder = false;
cmp->allow_specialists = true;
/* We used to look at pplayer->ai.xxx_priority to determine the values
* to be used here. However that doesn't work at all because those values
* are on a different scale. Later the ai may wish to adjust its
* priorities - this should be done via a separate set of variables. */
if (city_size_get(pcity) > 1) {
if (city_size_get(pcity) <= game.info.notradesize) {
cmp->factor[O_FOOD] = 15;
} else {
if (city_granary_size(city_size_get(pcity)) == pcity->food_stock) {
// We don't need more food if the granary is full.
cmp->factor[O_FOOD] = 0;
} else {
cmp->factor[O_FOOD] = 10;
}
}
} else {
// Growing to size 2 is the highest priority.
cmp->factor[O_FOOD] = 20;
}
cmp->factor[O_SHIELD] = 5;
cmp->factor[O_TRADE] = 0; /* Trade only provides gold/science. */
cmp->factor[O_GOLD] = 2;
cmp->factor[O_LUXURY] = 0; // Luxury only influences happiness.
cmp->factor[O_SCIENCE] = 2;
cmp->happy_factor = 0;
if (city_granary_size(city_size_get(pcity)) == pcity->food_stock) {
cmp->minimal_surplus[O_FOOD] = 0;
} else {
cmp->minimal_surplus[O_FOOD] = 1;
}
cmp->minimal_surplus[O_SHIELD] = 1;
cmp->minimal_surplus[O_TRADE] = 0;
cmp->minimal_surplus[O_GOLD] = -FC_INFINITY;
cmp->minimal_surplus[O_LUXURY] = 0;
cmp->minimal_surplus[O_SCIENCE] = 0;
}
/**
Call sync_cities() to send the affected cities to the clients.
*/
void auto_arrange_workers(struct city *pcity)
{
struct cm_parameter cmp;
/* See comment in freeze_workers(): we can't rearrange while
* workers are frozen (i.e. multiple updates need to be done). */
if (pcity->server.workers_frozen > 0) {
pcity->server.needs_arrange = true;
return;
}
TIMING_LOG(AIT_CITIZEN_ARRANGE, TIMER_START);
/* Freeze the workers and make sure all the tiles around the city
* are up to date. Then thaw, but hackishly make sure that thaw
* doesn't call us recursively, which would waste time. */
city_freeze_workers(pcity);
pcity->server.needs_arrange = false;
city_map_update_all(pcity);
pcity->server.needs_arrange = false;
city_thaw_workers(pcity);
// Now start actually rearranging.
city_refresh(pcity);
sanity_check_city(pcity);
cm_init_parameter(&cmp);
if (pcity->cm_parameter) {
cm_copy_parameter(&cmp, pcity->cm_parameter);
} else {
set_default_city_manager(&cmp, pcity);
}
/* This must be after city_refresh() so that the result gets created for
* the right city radius */
auto cmr = cm_result_new(pcity);
cm_query_result(pcity, &cmp, cmr, false);
if (!cmr->found_a_valid) {
if (pcity->cm_parameter) {
// If player-defined parameters fail, cancel and notify player.
delete pcity->cm_parameter;
pcity->cm_parameter = nullptr;
notify_player(city_owner(pcity), city_tile(pcity), E_CITY_CMA_RELEASE,
ftc_server,
_("The citizen governor can't fulfill the requirements "
"for %s. Passing back control."),
city_link(pcity));
}
// Drop surpluses and try again.
cmp.minimal_surplus[O_FOOD] = 0;
cmp.minimal_surplus[O_SHIELD] = 0;
cmp.minimal_surplus[O_GOLD] = -FC_INFINITY;
cm_query_result(pcity, &cmp, cmr, false);
}
if (!cmr->found_a_valid) {
/* Emergency management. Get _some_ result. This doesn't use
* cm_init_emergency_parameter so we can keep the factors from
* above. */
output_type_iterate(o)
{
cmp.minimal_surplus[o] =
MIN(cmp.minimal_surplus[o], MIN(pcity->surplus[o], 0));
}
output_type_iterate_end;
cmp.require_happy = false;
cmp.allow_disorder = !is_ai(city_owner(pcity));
cm_query_result(pcity, &cmp, cmr, false);
}
if (!cmr->found_a_valid) {
CITY_LOG(LOG_DEBUG, pcity, "emergency management");
cm_init_emergency_parameter(&cmp);
cm_query_result(pcity, &cmp, cmr, true);
}
fc_assert_ret(cmr->found_a_valid);
apply_cmresult_to_city(pcity, cmr);
if (pcity->server.debug) {
// Print debug output if requested.
cm_print_city(pcity);
cm_print_result(cmr);
}
if (city_refresh(pcity)) {
qCritical("%s radius changed when already arranged workers.",
city_name_get(pcity));
/* Can't do anything - don't want to enter infinite recursive loop
* by trying to arrange workers more. */
}
sanity_check_city(pcity);
TIMING_LOG(AIT_CITIZEN_ARRANGE, TIMER_STOP);
}
/**
Notices about cities that should be sent to all players.
*/
static void city_global_turn_notify(struct conn_list *dest)
{
cities_iterate(pcity)
{
const struct impr_type *pimprove = pcity->production.value.building;
if (VUT_IMPROVEMENT == pcity->production.kind
&& is_great_wonder(pimprove)
&& (1 >= city_production_turns_to_build(pcity, true)
&& can_city_build_improvement_now(pcity, pimprove))) {
notify_conn(dest, city_tile(pcity), E_WONDER_WILL_BE_BUILT, ftc_server,
_("Notice: Wonder %s in %s will be finished next turn."),
improvement_name_translation(pimprove), city_link(pcity));
}
}
cities_iterate_end;
}
/**
Send turn notifications for specified city to specified connections.
If 'pplayer' is not nullptr, the message will be cached for this player.
*/
static void city_turn_notify(const struct city *pcity,
struct conn_list *dest,
const struct player *cache_for_player)
{
const struct impr_type *pimprove = pcity->production.value.building;
struct packet_chat_msg packet;
int turns_growth, turns_granary;
if (0 < pcity->surplus[O_FOOD]) {
turns_growth =
(city_granary_size(city_size_get(pcity)) - pcity->food_stock - 1)
/ pcity->surplus[O_FOOD];
if (0 == get_city_bonus(pcity, EFT_GROWTH_FOOD)
&& 0 < get_current_construction_bonus(pcity, EFT_GROWTH_FOOD,
RPT_CERTAIN)
&& 0 < pcity->surplus[O_SHIELD]) {
// From the check above, the surplus must always be positive.
turns_granary =
(impr_build_shield_cost(pcity, pimprove) - pcity->shield_stock)
/ pcity->surplus[O_SHIELD];
/* If growth and granary completion occur simultaneously, granary
* preserves food. -AJS. */
if (5 > turns_growth && 5 > turns_granary
&& turns_growth < turns_granary) {
package_event(
&packet, city_tile(pcity), E_CITY_GRAN_THROTTLE, ftc_server,
_("Suggest throttling growth in %s to use %s "
"(being built) more effectively."),
city_link(pcity), improvement_name_translation(pimprove));
lsend_packet_chat_msg(dest, &packet);
if (nullptr != cache_for_player) {
event_cache_add_for_player(&packet, cache_for_player);
}
}
}
if (0 >= turns_growth && !city_celebrating(pcity)
&& city_can_grow_to(pcity, city_size_get(pcity) + 1)) {
package_event(&packet, city_tile(pcity), E_CITY_MAY_SOON_GROW,
ftc_server, _("%s may soon grow to size %i."),
city_link(pcity), city_size_get(pcity) + 1);
lsend_packet_chat_msg(dest, &packet);
if (nullptr != cache_for_player) {
event_cache_add_for_player(&packet, cache_for_player);
}
}
} else {
if (0 >= pcity->food_stock + pcity->surplus[O_FOOD]
&& 0 > pcity->surplus[O_FOOD]) {
package_event(&packet, city_tile(pcity), E_CITY_FAMINE_FEARED,
ftc_server, _("Warning: Famine feared in %s."),
city_link(pcity));
lsend_packet_chat_msg(dest, &packet);
if (nullptr != cache_for_player) {
event_cache_add_for_player(&packet, cache_for_player);
}
}
}
}
/**
Send global and player specific city turn notifications. If 'pconn' is
nullptr, it will send to all connections and cache the events.
*/
void send_city_turn_notifications(struct connection *pconn)
{
if (nullptr != pconn) {
struct player *pplayer = conn_get_player(pconn);
if (nullptr != pplayer) {
city_list_iterate(pplayer->cities, pcity)
{
city_turn_notify(pcity, pconn->self, nullptr);
}
city_list_iterate_end;
}
city_global_turn_notify(pconn->self);
} else {
players_iterate(pplayer)
{
city_list_iterate(pplayer->cities, pcity)
{
city_turn_notify(pcity, pplayer->connections, pplayer);
}
city_list_iterate_end;
}
players_iterate_end;
/* NB: notifications to 'game.est_connections' are automatically
* cached. */
city_global_turn_notify(game.est_connections);
}
}
/**
Save city surplus values for use during city processing.
*/
void city_save_surpluses(struct city *pcity)
{
output_type_iterate(o) { pcity->saved_surplus[o] = pcity->surplus[o]; }
output_type_iterate_end;
}
/**
Update all cities of one nation (costs for buildings, unit upkeep, ...).
*/
void update_city_activities(struct player *pplayer)
{
char buf[4 * MAX_LEN_NAME];
int n, gold;
fc_assert(nullptr != pplayer);
fc_assert(nullptr != pplayer->cities);
n = city_list_size(pplayer->cities);
gold = pplayer->economic.gold;
pplayer->server.bulbs_last_turn = 0;
if (n > 0) {
struct city *cities[n];
int i = 0, r;
int nation_unit_upkeep = 0;
int nation_impr_upkeep = 0;
city_list_iterate(pplayer->cities, pcity)
{
citizens_convert(pcity);
// Cancel traderoutes that cannot exist any more
trade_routes_iterate_safe(pcity, proute)
{
struct city *tcity = game_city_by_number(proute->partner);
if (tcity != nullptr) {
bool cancel = false;
if (proute->dir != RDIR_FROM
&& goods_has_flag(proute->goods, GF_DEPLETES)
&& !goods_can_be_provided(tcity, proute->goods, nullptr)) {
cancel = true;
}
if (!cancel && !can_cities_trade(pcity, tcity)) {
enum trade_route_type type =
cities_trade_route_type(pcity, tcity);
struct trade_route_settings *settings =
trade_route_settings_by_type(type);
if (settings->cancelling == TRI_CANCEL) {
cancel = true;
}
}
if (cancel) {
struct trade_route *back;
back = remove_trade_route(pcity, proute, true, false);
delete proute;
delete back;
proute = nullptr;
back = nullptr;
}
}
}
trade_routes_iterate_safe_end;
/* used based on 'gold_upkeep_style', see below */
nation_unit_upkeep += city_total_unit_gold_upkeep(pcity);
nation_impr_upkeep += city_total_impr_gold_upkeep(pcity);
/* New city turn: store surplus values so changes during city
* processing don't take effect yet. nation_????_upkeep above
* also have similar effect.
* Note that changes in effects between players, like international
* trade routes and Great Wonders may still take place. */
city_save_surpluses(pcity);
// Add cities to array for later random order handling
cities[i++] = pcity;
}
city_list_iterate_end;
// Iterate over cities in a random order.
while (i > 0) {
r = fc_rand(i);
// update unit upkeep
city_units_upkeep(cities[r]);
update_city_activity(cities[r]);
cities[r] = cities[--i];
}
/* How gold upkeep is handled depends on the setting
* 'game.info.gold_upkeep_style':
* GOLD_UPKEEP_CITY: Each city tries to balance its upkeep individually
* (this is done in update_city_activity()).
* GOLD_UPKEEP_MIXED: Each city tries to balance its upkeep for
* buildings individually; the upkeep for units is
* paid by the nation.
* GOLD_UPKEEP_NATION: The nation as a whole balances the treasury. If
* the treasury is not balance units and buildings
* are sold. */
if (pplayer->economic.infra_points < 0) {
pplayer->economic.infra_points = 0;
}
switch (game.info.gold_upkeep_style) {
case GOLD_UPKEEP_CITY:
/* Cities already handled all upkeep costs. */
break;
case GOLD_UPKEEP_MIXED:
// Nation pays for units.
pplayer->economic.gold -= nation_unit_upkeep;
if (pplayer->economic.gold < 0) {
player_balance_treasury_units(pplayer);
}
break;
case GOLD_UPKEEP_NATION:
// Nation pays for units and buildings.
pplayer->economic.gold -= nation_unit_upkeep;
pplayer->economic.gold -= nation_impr_upkeep;
if (pplayer->economic.gold < 0) {
player_balance_treasury_units_and_buildings(pplayer);
}
break;
}
// Should not happen.
fc_assert(pplayer->economic.gold >= 0);
}
/* This test includes the cost of the units because
* units are paid for in update_city_activity() or
* player_balance_treasury_units(). */
if (gold - (gold - pplayer->economic.gold) * 3 < 0) {
notify_player(pplayer, nullptr, E_LOW_ON_FUNDS, ftc_server,
_("WARNING, we're LOW on FUNDS %s."),
ruler_title_for_player(pplayer, buf, sizeof(buf)));
}
city_refresh_queue_processing();
}
/**
Try to get rid of a unit because of missing upkeep.
Won't try to get rid of a unit without any action auto performers for
AAPC_UNIT_UPKEEP. Those are seen as protected from being destroyed
because of missing upkeep.
Can optionally wipe the unit in the end if it survived the actions in
the selected action auto performer.
Returns TRUE if the unit went away.
*/
static bool upkeep_kill_unit(struct unit *punit, Output_type_id outp,
enum unit_loss_reason wipe_reason,
bool wipe_in_the_end)
{
int punit_id;
if (!action_auto_perf_unit_sel(AAPC_UNIT_UPKEEP, punit, nullptr,
get_output_type(outp))) {
/* Can't get rid of this unit. It is undisbandable for the current
* situation. */
return false;
}
punit_id = punit->id;
// Try to perform this unit's can't upkeep actions.
action_auto_perf_unit_do(AAPC_UNIT_UPKEEP, punit, nullptr,
get_output_type(outp), nullptr, nullptr, nullptr,
nullptr);
if (wipe_in_the_end && unit_is_alive(punit_id)) {
// No forced action was able to kill the unit. Finish the job.
wipe_unit(punit, wipe_reason, nullptr);
}
return !unit_is_alive(punit_id);
}
/**
Reduce the city specialists by some (positive) value.
Return the amount of reduction.
*/
static citizens city_reduce_specialists(struct city *pcity, citizens change)
{
citizens want = change;
fc_assert_ret_val(0 < change, 0);
specialist_type_iterate(sp)
{
citizens fix = MIN(want, pcity->specialists[sp]);
pcity->specialists[sp] -= fix;
want -= fix;
}
specialist_type_iterate_end;
return change - want;
}
/**
Reduce the city workers by some (positive) value.
Return the amount of reduction.
*/
static citizens city_reduce_workers(struct city *pcity, citizens change)
{
struct tile *pcenter = city_tile(pcity);
int want = change;
fc_assert_ret_val(0 < change, 0);
city_tile_iterate_skip_center(city_map_radius_sq_get(pcity), pcenter,
ptile, _index, _x, _y)
{
if (0 < want && tile_worked(ptile) == pcity) {
city_map_update_empty(pcity, ptile);
want--;
}
}
city_tile_iterate_skip_center_end;
return change - want;
}
/**
Reduce the city size. Return TRUE if the city survives the population
loss.
*/
bool city_reduce_size(struct city *pcity, citizens pop_loss,
struct player *destroyer, const char *reason)
{
citizens loss_remain;
int old_radius_sq;
if (pop_loss == 0) {
return true;
}
if (city_size_get(pcity) <= pop_loss) {
script_server_signal_emit("city_destroyed", pcity, pcity->owner,
destroyer);
remove_city(pcity);
return false;
}
old_radius_sq = tile_border_source_radius_sq(pcity->tile);
city_size_add(pcity, -pop_loss);
map_update_border(pcity->tile, pcity->owner, old_radius_sq,
tile_border_source_radius_sq(pcity->tile));
// Cap the food stock at the new granary size.
pcity->food_stock =
std::min(pcity->food_stock, city_granary_size(city_size_get(pcity)));
// First try to kill off the specialists
loss_remain = pop_loss - city_reduce_specialists(pcity, pop_loss);
if (loss_remain > 0) {
// Take it out on workers
loss_remain -= city_reduce_workers(pcity, loss_remain);
}
// Update citizens.
citizens_update(pcity, nullptr);
/* Update number of people in each feelings category.
* This also updates the city radius if needed. */
city_refresh(pcity);
auto_arrange_workers(pcity);
// Send city data.
sync_cities();
fc_assert_ret_val_msg(0 == loss_remain, true,
"city_reduce_size() has remaining"
"%d of %d for \"%s\"[%d]",
loss_remain, pop_loss, city_name_get(pcity),
city_size_get(pcity));
// Update cities that have trade routes with us
trade_partners_iterate(pcity, pcity2)
{
if (city_refresh(pcity2)) {
/* This should never happen, but if it does, make sure not to
* leave workers outside city radius. */
auto_arrange_workers(pcity2);
}
}
trade_partners_iterate_end;
sanity_check_city(pcity);
if (reason != nullptr) {
int id = pcity->id;
script_server_signal_emit("city_size_change", pcity, -pop_loss, reason);
return city_exist(id);
}
return true;
}
/**
Repair the city population without affecting city size.
Used by savegame.c and sanitycheck.c
*/
void city_repair_size(struct city *pcity, int change)
{
if (change > 0) {
pcity->specialists[DEFAULT_SPECIALIST] += change;
} else if (change < 0) {
int need = change + city_reduce_specialists(pcity, -change);
if (0 > need) {
need += city_reduce_workers(pcity, -need);
}
fc_assert_msg(0 == need,
"city_repair_size() has remaining %d of %d for \"%s\"[%d]",
need, change, city_name_get(pcity), city_size_get(pcity));
}
}
/**
Return the percentage of food that is lost in this city.
Normally this value is 0% but this can be increased by EFT_GROWTH_FOOD
effects.
*/
static int granary_savings(const struct city *pcity)
{
// Do not empty food stock if city is growing by celebrating
if (city_rapture_grow(pcity)) {
return 100;
}
int savings = get_city_bonus(pcity, EFT_GROWTH_FOOD);
return CLIP(0, savings, 100);
}
/**
* Return the percentage of the food surplus that is saved in this city.
*
* Normally this value is 0% but this can be increased by
* EFT_GROWTH_SURPLUS_PCT effects.
*/
static int surplus_savings(const struct city *pcity)
{
int savings = get_city_bonus(pcity, EFT_GROWTH_SURPLUS_PCT);
return CLIP(0, savings, 100);
}
/**
Reset the foodbox, usually when a city grows or shrinks.
By default it is reset to zero, but this can be increased by Growth_Food
effects.
Usually this should be called before the city changes size.
*/
static void city_reset_foodbox(struct city *pcity, int new_size)
{
fc_assert_ret(pcity != nullptr);
const int surplus_food = std::max(
pcity->food_stock - city_granary_size(city_size_get(pcity)), 0);
const int saved_surplus = (surplus_food * surplus_savings(pcity)) / 100;
const int new_granary_size = city_granary_size(new_size);
const int saved_by_granary =
(new_granary_size * granary_savings(pcity)) / 100;
pcity->food_stock =
std::min(saved_by_granary + saved_surplus, new_granary_size);
}
/**
Increase city size by one. We do not refresh borders or send info about
the city to the clients as part of this function. There might be several
calls to this function at once, and those actions are needed only once.
*/
static bool city_increase_size(struct city *pcity,
struct player *nationality)
{
int new_food;
int savings_pct = granary_savings(pcity);
bool have_square = false;
struct tile *pcenter = city_tile(pcity);
struct player *powner = city_owner(pcity);
const struct impr_type *pimprove = pcity->production.value.building;
int saved_id = pcity->id;
if (!city_can_grow_to(pcity, city_size_get(pcity) + 1)) {
// need improvement
if (get_current_construction_bonus(pcity, EFT_SIZE_ADJ, RPT_CERTAIN) > 0
|| get_current_construction_bonus(pcity, EFT_SIZE_UNLIMIT,
RPT_CERTAIN)
> 0) {
notify_player(powner, city_tile(pcity), E_CITY_IMPROVEMENT_BLDG,
ftc_server,
_("%s needs %s (being built) to grow beyond size %d."),
city_link(pcity), improvement_name_translation(pimprove),
city_size_get(pcity));
} else {
notify_player(powner, city_tile(pcity), E_CITY_IMPROVEMENT, ftc_server,
_("%s needs an improvement to grow beyond size %d."),
city_link(pcity), city_size_get(pcity));
}
// Granary can only hold so much
new_food =
(city_granary_size(city_size_get(pcity))
* (100 * 100 - game.server.aqueductloss * (100 - savings_pct))
/ (100 * 100));
pcity->food_stock = std::min(pcity->food_stock, new_food);
return false;
}